diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0c7e86caf206a..f66de61167af8 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -123,6 +123,13 @@ jobs: if: ${{ !cancelled() && steps.setup.outcome == 'success' && inputs.python }} run: just check --only os-marker-fakes + # The desktop redesign keeps its design values in apps/desktop/src/app/redesign/tokens/: + # redesign CSS that restates one may only shrink per file, an undefined --portal-* token or + # stale DESIGN.md token tables fail. Frontend-only change, so not gated on inputs.python. + - name: Desktop redesign design tokens + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} + run: just check --only desktop-design-tokens + # Files at old module paths that shipped updaters still reach after a move are generated from # hermes_agent/compat/{moves,required_names}.py and must match the generator byte for byte. - name: Keep the move shims in sync with their generator diff --git a/.gitignore b/.gitignore index aa9b27899a52c..aa981ddc4e1a2 100644 --- a/.gitignore +++ b/.gitignore @@ -117,6 +117,8 @@ apps/desktop/electron/**/*.d.ts # e.g. hermes-bots): plugin.js IS the source, not tsc output. No .tsx # sibling exists, so the stale-shadow hazard above cannot apply. !apps/desktop/src/plugins/*/plugin.js +# ...and plain-ESM plugin fixtures (the contract probe), source for the same reason. +!apps/desktop/src/contrib/__fixtures__/*/plugin.js !apps/desktop/src/global.d.ts !apps/desktop/src/vite-env.d.ts diff --git a/agent/onboarding_record.py b/agent/onboarding_record.py index ae3608904d0de..e5718fc4fe2f5 100644 --- a/agent/onboarding_record.py +++ b/agent/onboarding_record.py @@ -83,7 +83,8 @@ def update(current: Any) -> Any: # Told before the flag write, which can fail: the record already says the run ended. if step is not None and holder["was_active"] and not is_active(step.record): _announce(step.record.get("run_id"), session_id, step.record["ended_by"]) - if step is not None and not is_active(step.record) and active_session_id(db, persistence=persistence) is None: + if (step is not None and not step.record.get("sessionless") + and not is_active(step.record) and active_session_id(db, persistence=persistence) is None): _close_install_flag() return step @@ -103,9 +104,8 @@ def _close_install_flag() -> None: def start(db, session_id: str, facts: Facts, *, persistence=None) -> dict: - """Write a fresh run record (the row must exist) and mark the install as mid-onboarding, so a - crash or a quit before the end runs onboarding again on the next launch (which starts over: - ``onboarding.start`` with ``fresh_launch``).""" + """Write a classic conversational run record (the row must exist) and mark the install + mid-onboarding. The redesigned guide never creates these records.""" from hermes_cli.onboarding_run import set_run from agent.agent_init_session import writer_interface @@ -119,30 +119,28 @@ def start(db, session_id: str, facts: Facts, *, persistence=None) -> dict: def advance(db, session_id: str, event: Event, *, persistence=None) -> Step: - """Apply one event to the stored run; LookupError when this session has no run.""" + """Apply one event to the stored run; LookupError when this session has no run. A sessionless + ``End`` leaves the install flag to sessionless setup.""" step = _transition(db, session_id, event, persistence=persistence) if db is not None and session_id else None if step is None: raise LookupError(f"session {session_id} has no onboarding run") return step -def open_session_ids(db, *, persistence=None) -> list[str]: - """The chats whose run is still in progress, newest first. Rotation leaves the active copy on the +def run_tips(db, *, persistence=None) -> list[str]: + """Every chat that carries a run record, newest first. Rotation leaves the live copy on the compression parent, so each id is read at its compression tip.""" store = _reader(db, persistence) - tips: set[str] = set() - open_ids: list[str] = [] if store is not None: ids, resolve = store.sessions.session_ids_with_model_config_key(KEY), store.lineage.resolve_resume_target else: ids, resolve = db.session_ids_with_model_config_key(KEY), db.resolve_resume_session_id - for sid in ids: - tip = resolve(sid) or sid - if tip not in tips: - tips.add(tip) - if is_active(load(db, tip, persistence=persistence)): - open_ids.append(tip) - return open_ids + return list(dict.fromkeys(resolve(sid) or sid for sid in ids)) + + +def open_session_ids(db, *, persistence=None) -> list[str]: + """The chats whose run is still in progress, newest first.""" + return [tip for tip in run_tips(db, persistence=persistence) if is_active(load(db, tip, persistence=persistence))] def active_session_id(db, *, persistence=None) -> str | None: diff --git a/apps/desktop/DESIGN.md b/apps/desktop/DESIGN.md index 2f01ac0dc6633..3d39fa79d3c7b 100644 --- a/apps/desktop/DESIGN.md +++ b/apps/desktop/DESIGN.md @@ -15,13 +15,43 @@ This doc contains two kinds of content, maintained differently: - **Principles** (flatness, intent, feedback, motion, cancellation) are durable. They hold as components come and go. - **Named contracts** (tokens, `Button` variants, primitive names) are the - design system's current API. They are maintained *with* the code: if you + design system's current API. They are maintained _with_ the code: if you change a primitive, token, or variant, update its entry here **in the same change** — a stale name in this file is a bug, exactly like a stale type. When a rule and the code disagree, fix whichever is wrong rather than forking a one-off at the call site. +## Source of truth + +The web app and desktop design system is the code, in four places that must agree: + +- the tokens, `src/app/redesign/tokens/`; +- the primitives, `src/components/ui/` (and the redesign's page frame: `PageHeader`, + `PageSidebarPanel`, the settings cards); +- this document; +- the **design system page** in the app (`#/design-system`, ⌘K "Design system"), which renders the + tokens and the primitives from that code, so it cannot drift from it. + +Figma (`EuTlgG8nMQo02z5RlImIu9`, see "Portal design language" below) gives direction: information +architecture, layout, interaction and the overall visual language. It is not pixel-authoritative. When +Figma and the implementation disagree, the implementation is what ships and what other surfaces +should match, until someone deliberately changes a token or a primitive here. Known disagreements +are listed, with the value that should win, in "Still to unify"; the design system page shows +that table rather than pretending to be complete. + +To change the design system, change the code: edit the token (see "How to change a token") or the +primitive and its variants, update its entry in this document in the same change, and look at it on +the design system page in dark, light and every accent. The token tables below and the page are +generated from the same CSS, so neither needs a hand edit. `scripts/check` fails while the tables +are stale or a redesign stylesheet restates a value a token owns, and the page's coverage tests fail +when a file in `src/components/ui/` is neither shown nor listed as not shown with a reason. + +The Nous portal design system (https://portal.nousresearch.com/ds) is the brand's reference for the +portal; this app's language shares its spirit (the navy family, one brand blue, a display face for +names over a plain sans) but is the web app's own reference, with its own names and values. No +token-for-token parity with the portal is claimed or checked. + ## Principles 1. **Flat, not boxed.** No card-in-card, no divider borders inside a panel. @@ -57,6 +87,10 @@ one-off at the call site. - **Panes are working context.** Preview, files, review, and terminal remain attached to the current task. Their state survives temporary hiding and chat switches where the underlying tool is meant to persist. + Activating a tool tab also restores its open state; hiding a stacked terminal + must not leave a visible tab pointing at an inert shell. + Review follows the focused chat's worktree and sends agent-ship actions back + to that same conversation, including when focus moves into tool chrome. - **One action, one home.** A command may have keyboard, palette, and visible affordances, but they invoke the same action and state. Do not fork behavior per entry point. @@ -77,6 +111,1344 @@ Navigation must preserve context. A background session finishing, a tool result arriving, or a project refresh may update badges and cached data; it must not replace the foreground transcript or steal focus. +The boxed conversation sidebar follows Figma Desktop 10 (`147:7470`, machine +box `143:6270`), not the alternate crowded-agent card mockup. Each expanded +machine has a 6px container, 5% neutral body fill, and a brighter 7% selected +heading; the heading's lower corners join the body and round when collapsed. +Agent rows are transparent, 45px tall, with 10px horizontal padding, 7px between +groups, and 20px colored robot tiles using the exported Figma artwork. Do not +replace them with blue selection cards or large antenna-outline avatars. +Selected/hovered names brighten without painting an agent-row background. +Names, descriptions, colors, and connection status use actual owner metadata; +never invent team names, sharing counts, or connection state. + +The agent name/avatar opens that owner's canonical chat without a redundant +child row. Its menu offers **New chat with this agent**, **Open agent**, and +**Hide from chat list**. Collapse remains a separate keyboard/touch control: +reserve a 16px leading gutter so its 24px target stays inside the machine card +without overlapping the avatar. Nested 31px session rows have a 1px, 20% neutral +indentation guide centered beneath the avatar, 36px from the machine's edge. +Titles align with agent names at 54px. Empty and collapsed agents have no +dangling guide. Session hover and selection brighten only the name, like agent +rows; the click target still includes the guide gutter. Reveal actions for +hover, visible keyboard focus, or an open menu, not lingering mouse focus; +touch controls remain visible. Only truncated titles need a tooltip. +Screen is a tool rather than a conversation: use **Open Screen** in the command +palette for the focused owner; classic/Bot Mode entry points remain available. + +**Hidden agents** stays outside the agent list's scroll viewport so its count +and attention dot remain reachable in crowded installations. Its expanded rows +have their own bounded scroll area. **Show** restores an agent; a row needing +attention opens the source conversation when its owner-qualified route is known. +Hiding affects presentation only: chats remain searchable, work and notifications +continue, and the current conversation is not closed or replaced. Hidden agents' +pinned rows disappear from the ordinary list but remain available in search. +Visibility and expansion persist by `(connectionId, targetProfile)`; local/null +owners normalize identically. Renaming migrates preferences and deletion clears +them. Scroll position and the Hidden agents disclosure survive navigation/reload. + +Attention priority is approval, input, failure, running, then unread. Use existing +owned runtime/session signals and owner-tagged schedule snapshots, not guessed +state or extra polling. Same-name agents and colliding session IDs on different +machines must not borrow each other's signals. Display elapsed time only when +the source supplies a real timestamp. An unobserved remote failure cannot be +inferred from a reachable roster entry. + +Finished settings and management frames use bundled, OFL-licensed Oswald for +display headings and Mona Sans for body text. The Figma trial navigation font +is not redistributed. Redesigned geometry is root-scoped because route +overlays render outside the shell: rails, the panel width and the page columns are the layout +tokens in `tokens/space.css`. Chat uses the wide layout described below. Native titlebar sizing, +user-controlled panes, themes, and the classic layout remain functional. + +Appearance starts with working Light/Dark/System previews, text size, +language, and tips controls. Advanced retains the full settings and theme +gallery, including deep links. Agent management uses owner-scoped Overview, +History, and Settings tabs. Settings has its own grouped, agent-only navigation: +184px navigation, 32px gap, and a 584px body at full width. Model selection, +fallbacks, and collapsed Advanced controls share one page; provider setup stays +available inside the model picker. Reuse the existing editors and save paths. +Auxiliary-model deep links reveal enclosing Advanced disclosures before +focusing the target or consuming the link. Activating a settings owner preserves +the requested page rather than redirecting to a new chat. +Navigation and editor bodies scroll independently; changing section/subpage resets +only the editor scroll. Instructions use a 322px card including the Save footer. +Classic dispatch preserves the same semantic destination and owner. Retained +instruction revisions and config draft/baseline/save queues live above the +presentation branch, not in duplicate hidden editors; a pending save cannot erase +a newer draft after switching presentation. +The overview header uses a 40px light Mona Sans title and the outline avatar. +**Open chat** sits beside the action menu: duplicate, set default, hide/show in +the chat list, copy the actual profile path, and a hint directing deletion to +Settings → General. Menu rows have 44px targets. Disconnection warnings reflect +the backend's actual failed/retrying/stopped states for configured, enabled channels. +Overview cards use 436:300 columns with a 24px gap, 16px section-title spacing, +44px rows, 64px activity rows, and 4px corners; narrow layouts collapse to one column. +Global desktop settings remain available outside the agent editor. New agent +opens creation directly on the captured machine rather than another management page. + +### Terminology: classic vs redesign + +The redesign renames five product nouns; classic keeps `main`'s wording verbatim, so turning +the **Redesigned interface** preference off restores exactly what `main` ships. + +| Classic (base catalog, `main`'s wording) | Redesign | +|---|---| +| Sessions | Chats | +| Artifacts | Library | +| Profiles / bots (Hermes agents) | Agents | +| Cron / cron jobs / scheduled jobs | Routines | +| Gateways (and "host" meaning a Hermes machine) | Machines | + +The swap is a wording layer, not a fork: `resolveTranslations(locale)` +(`src/i18n/registry.ts`) reads the shell from the presentation leaf +(`src/store/shell-presentation.ts`, i.e. `$portalShell`) and, in the redesigned shell, +merges `src/i18n/redesign/.ts` over the base catalog — before backend/plugin +language packs, which still win. Each overlay holds ONLY the keys whose wording differs, +typed against `Translations`; a locale inherits the English overlay where its base still +shows English. Call sites keep reading `t.x.y` / `translateNow(...)`; never branch a string on +the shell. The popped-out Browser always renders classic, so it reads classic +wording; the HUD follows the shell. **New shell wording goes in the overlay, never in the base catalog.** Redesign-only +surfaces with their own copy modules (`src/i18n/simplified-agents.ts`, `src/app/**/*-copy.ts`) +use the redesign terms directly. `src/i18n/redesign/terminology-guard.test.ts` fails on a +classic noun left in the redesign and on a redesign-only word reaching classic. + +Rulings: a routine *has* a schedule ("schedule" stays the word for its timing; "cron +expression" stays the input syntax's name). Service operations say **Restart Hermes**, not +“restart the machine,” which would imply rebooting the computer. "host" stays only for a +literal hostname or SSH host; skill/plugin "library" is "catalog", so Library means only the +artifacts destination. Team Gateway and Tool Gateway remain product names; Group chats and +Channels keep their names. Actual Telegram/Discord bots, subagents, browser profiles, the +memory "user profile", sign-in sessions and session tokens, and user-authored names retain +their meanings. Protocol fields, `/profiles` and `/cron` routes, CLI commands, cron +expressions, plugin IDs, and the exact stored `Bot Chat` title are technical contracts, not +copy to rename. + +Drift coverage exercises navigation into Agent and Routine editors, cancellation, +and return to the current view with the redesign enabled and disabled. Component +tests use canonical translated controls while checking ownership, routing, and +mutations; avoid source scans or snapshots that freeze incidental sentences. + +Owner actions preserve the roster's backend `targetProfile`, including aliases +before Bot Mode has mounted. History uses bounded 25-row requests with offsets, +deduplicates pinned backfills, and keeps earlier pages reachable past 500 sessions. +Source/archive filters are server-side; explicit text search and cleanup walk +remaining bounded pages. Read-only previews expose Open chat, Archive, and Delete. +Cleanup previews its candidates before confirmation and rechecks owner, running +state, and eligibility before each fenced deletion. Protected/running sessions +are skipped; failed writes are never counted as deleted. Selection and confirmation +belong to one gateway/profile and are discarded when that owner changes. +History dialogs use a dimmed, unblurred backdrop, 24px content padding, display +headings, and semantic destructive colors for confirmed deletion. +Bulk pin/archive operations retain failed selections and report partial success. +Search, independent filter chips, and pagination reuse the same owner-scoped queries. +The read-only History preview is a right-edge drawer below the real titlebar, +not a centered dialog. It explicitly resets both shared-dialog translation axes; +at narrow widths it fills the available viewport without hiding its actions. +Session lists capture their serving connection before awaiting the response; +cached rows never inherit a newly selected foreground gateway. Selection follows +the focused conversation's owner. Explicit owners survive tab and window opens. +Primary-local project rows retain their legacy profile-door shape; deletion +normalizes both lookup claims and project-only targets using the tree's captured +source. Never infer that source from the newly foregrounded machine. +Conversation settings links resolve profile-only chats through the primary source, +not the ambient connection; unresolved owners cannot open another agent's settings. +The current per-window runtime caches cannot host identical stored IDs from two +owners simultaneously: conflicting opens fail visibly without reassigning the +existing chat; use separate windows for those conversations. +Tile identity comparisons live in `src/store/session-tile-identity.ts`; strip +ordering and close-to-next selection live in `src/store/session-tile-order.ts`. + +Agent-profile settings use `agentProfile` in the URL; the plugin settings +contract keeps `agent` for the plugin key. Settings pin the complete gateway and +profile on entry, including links that omit an explicit connection. +Config, credentials, messaging, memory, and plugin operations retain this owner +through asynchronous work. Same-name agents on another gateway keep their own +configuration, plugin cache, conversations, and open tiles. + +Keep section resolution, visibility, and model-default derivation separate from +editor composition. Refactoring these boundaries must preserve owner checks and +must not mount inactive capability editors or pending inventory content. +The agent header uses the Figma robot and display type. The directory count and +default badge come from the owning machine's actual metadata, never sample data +or a same-named agent on another machine. Each settings page supplies its own +localized description. Instructions keeps the SOUL.md heading, proportional +editor text, character count, and Save footer without changing draft ownership. +Voice groups Conversation, Listening, and Speaking; the mode selector exposes +only backend-supported values, while detailed provider/pricing help stays under +Advanced. Schema/config availability still determines which provider fields exist. + +Page toolbars occupy the native titlebar band on the window canvas so open +chat/tool tabs cannot bleed through; Back is a 30px chrome button and controls +remain outside the drag region. + +The redesigned shell is a window canvas with panels laid on it +(`app/redesign/portal-shell.css`; every colour, radius and size comes from the tokens in +"Portal design language" below). The titlebar band and the 60px rails show the canvas; zones +touching the window top become panels starting below the band, together one workspace frame: +a card on the canvas between the rails (`--portal-workspace-inset-start` past the global rail and +before the developer rail, `-end` and `-bottom` to the window edge: x 65–1265, y 60–865 of Figma's +1280×880) with 15px outer corners (`--portal-radius-frame`), a soft shadow +(`--portal-shadow-workspace`) and a top highlight (`--portal-shadow-workspace-highlight`). Its +panels, the developer tool panes among them, meet square inside it with no hairlines (Content +`16292:14463`; a phone keeps the full window). Behind it all lies the launch's artwork (see "Artwork" below), which the canvas +shows at full strength and every panel veils. Window Glass (macOS default) never switches the redesign off: its +rules are unlayered and beat the `@layer base` Glass rules, and only the canvas (rails, band) takes +the native material, tinted with the portal canvas at the user's Glass intensity. Titlebar, rail and +pane header buttons are chrome buttons (`--portal-surface-chrome*`); the open destination or shown +pane wears the brand selection with a brand ring. The titlebar band is a shell property: 60px in the +redesign (Figma's header; content starts at y 60), 34px classic (44px browser +touch). Electron reads the shell choice from the shared UI preferences before +creating a window and re-seats the macOS traffic lights (centred, in the rail +column) and the Windows/Linux caption overlay when it flips +(`electron/window-chrome.ts`); the popped-out Browser keeps the classic band. +The band carries the leading cluster past the rail (Back and Forward through the window's own router +history on every screen, `app/shell/history-position.ts`; a page with nothing behind it closes to the +chat), the open session's title pill with "+" at the stage's leading edge, and the panel toggles at +the end. Pages cover the chat, they do not replace it (`contrib/route-cover.tsx`): a route overlay or +workspace page paints over a chat that stays mounted, skipped by style, layout and paint +(`content-visibility: hidden`), inert and aria-hidden, so returning to Chats is a flip with its +scroll, draft and focus intact. Toasts of every kind stack at the stage's end corner, resting on a +docked composer, clear of page headers. Page content columns sit centred in their stage (the frame past a +page's sidebar panel), never closer to its edges than `--portal-frame-inset`, and Routines lists every +agent's routines in the shared page sidebar panel like Agents (see Routines below). +Workspace pages (Capabilities, Library, …) and the overlay pages lie in the same +workspace frame as the chat. Without an explicit skin pick, the redesign paints the +Hermes Portal skin and classic paints Nous (`defaultSkinName`); flipping the +shell never writes a pick. + +Redesigned surfaces use neutral foreground-derived fills and strokes, not +accent-tinted greys (the colour roles below). Global settings cards and agent settings cards wear +the one card role. Settings-navigation selection is the neutral selection role; +sub-pages reveal under the active row, without per-row carets. Settings pages compose +`SettingsOverview` / `SettingsCard` / `SettingsDisclosure` (`settings-card.tsx`), which fall back to +the classic wrapper. The global rail marks its open destination with a brighter navy tile. Agent-management navigation +tiles stay translucent; agent rows and the overview header use the Figma robot with the real +owner's color. +The global rail tracks the owning agent even inside its settings editor. +Shared rail/sidebar geometry lives at the document root while the redesign is +enabled. Sibling route overlays reserve the rail with logical inline offsets +in both LTR and RTL layouts. +Checked switches use the brand-blue track and light thumb across settings +and the capability catalog; unchecked tracks are neutral 14% fills. + +The global rail (rail 16292:15233) carries no brand badge: Figma hides that layer and draws the +window's traffic lights at the top of the column, so the destinations start 90px down on every host +(clear of macOS lights), 30px navy tiles with 16px glyphs at .4 ink on a 50px pitch, the open one a +brighter tile with its glyph in full ink; the foot (usage, Settings) carries 20px glyphs 40px off the +floor, and Routines draws a clock. The rail never moves between states and has no edge of its own. The redesigned chat sidebar +(340px, "Prod - Desktop" Panel 16292:15497) opens with its header (Top 16292:15498): the "Hermes" +wordmark in Oswald Light 30 over a mono "// NOUS RESEARCH" caption (brand marks, never translated), +and at its end a 30px search button. Search lives behind that button: it brings out a rimmed field +under New chat with the session-search shortcut's keycaps (hidden on touch), and the shortcut or the +command palette bring it out too; Escape on an empty field or the button again puts it away and ends +the search. New chat (16292:15511) is a 40px radius-3 slab with rimless mono keycaps and keeps its +agent picker at the end. The open destination's rail button folds its panel and brings it back: Chats folds the chat sidebar +("Hide chats" / "Show chats", `aria-expanded`), Agents, Schedules and Settings their page panel +("Hide panel" / "Show panel"); it stays the open destination either way, and ⌘B does the same. Picking +a destination with a panel from elsewhere shows it whole; a destination without one leaves a folded +panel alone. Page panels carry no fold button of their own. While a panel is folded on a wide window, +Simple mode brings it back from one floating 44×40 button at the stage's top-leading corner, under the +band (1061:7816, `app/shell/panel-reveal.tsx`), and Advanced from the band's sidebar button; below wide +the band's button is the sheet's menu in both. Dragging the sidebar's sash 72px under its 280px minimum +(`--sessions-pane-collapse-width`) folds it live as the pointer crosses and on release, writing no +width, so it returns at the width it had; a drag that stops short rests at the minimum. Classic defines +no fold width, so its sash never folds. + +Below New chat the sidebar follows the same panel (Centre 16292:15509): sections under sentence-case +mono captions with the disclosure chevron right after the label (Agents keeps its brand count badge at +the end), separated by whitespace only, on a 32px text inset with row fills bleeding 12px past it. +Pinned and group-chat rows are 20px of SemiBold title on a 36px pitch after a 5px leading dot (row ink +at rest, full ink for the open chat, brand for unread news, the status tones while a turn runs or +waits), their tags, ages and statuses in the mono font, 10px uppercase. A machine is one radius-12 +card at 2% ink (set 16292:15581) under a 52px header, its dot in the machine's status tone and the status +label at the end. Closing it folds the card down to that header at the same width and height; open, the +header sticks to the top of the list while its agents scroll under it. Agents are cards inside it (16292:15592): radius 9, the agent's 32px colour tile (in its +snapped Figma primary, `lib/portal-profile-color.ts`; Figma's character avatars are not adopted) over +the name and a mono second line (roster description, else the chat count), the caret at the end and the +CRT texture dodged into the fill. The open agent is the brand slab (white .10 / black .40 / blue), the +others a navy card; light draws both as a pale brand card under a 1px brand rule, solid for the open +one. An agent's chats are 40px rows across the machine card with the dot 30px in; no fill marks the +open chat, its title and dot take full ink while the agent's other chats sit at the ladder's floor. +An agent's card lists its three most recent chats (plus the open one and any running or unread) +over a "Show all (N)" / "Show less" row remembered per agent; search lists every match. A row under +the pointer or keyboard focus takes a 4% fill. Figma's "Recent" list is not built: it would repeat the +chats the agent cards already list. A chat row resolves the click and its title is the one focusable button, as in classic, so +plugin row decorations (`sessionRow.leading` before the title, `.trailing` before the age) and an +agent card's `sidebar.profileGroup.header` contributions sit beside that button, never in it. Row and +agent actions (ellipsis, caret, kebab) are bare glyphs that appear on hover, keyboard +focus or an open menu; touch keeps them visible. Arrow keys, Home and End walk the +visible rows; right-click opens the row menu. Captions and meta keep the AA ladder +where Figma's inks fail 4.5:1. The band's leading cluster (Back/Forward on the native app) starts at +`--portal-band-start` (x 150 past macOS traffic lights, navigation 16292:15284; else 80) and the +session pill is anchored 25px past the stage's leading edge (tab 16292:15297) with CSS anchor +positioning, so it tracks a sash drag in the same frame. Band buttons and the pill are navy tiles +(white .05 / black .60 / blue .20) with glyphs at .4. The main chat's Agent settings is the band's +trailing sliders button (settings-2 16292:15304), present wherever a conversation holds the stage; +an extra tile keeps its own in its header. The stage keeps its "machine // agent" line at its top end +in the mono caption style, though Figma draws none. +The global Agents icon uses the Figma robot silhouette tinted by `currentColor`, +sharing its peers' inactive, hover, and selected tones in both light and dark themes; +rail destinations rest at .4 ink on navy tiles and the open one takes the brighter tile with its glyph in +full ink. +The Hermes Portal skin supplies only the seeds the roles read (`--ui-base`, `--ui-bg-chrome`, the +floating `--ui-bg-elevated`, the canvas `--portal-skin-window`: navy `#0a0a1a` / `#07071a` / +`#0d0d1e` on dark); the shell's panels derive from them. Custom theme choices and classic styling +stay available. +The **Redesigned interface** preference gates the setup guide, catalog/agent +controls, composer layout, machine menu, and hidden-agent presentation as well as +the shell. One seam owns it (`src/store/shell-variant.ts`): `usePortalShell()` / +`$portalShell` say whether this window renders the redesign; `installShellAttribute()` +(main.tsx, before first render) mirrors it to `` and follows +every toggle (absent in classic). Every redesign selector is gated +`:root[data-shell='portal'] …`, or `:where(:root[data-shell='portal']) …` where a rule on a class +only the redesign emits must keep that class's own specificity; never gate on a mounted component +(`:has(.portal-sidebar)`) or on a shell ancestor. The popped-out Browser +window stays classic in both modes. The chromeless HUD renders the redesign with it: the same +composer and transcript, so their look carries over, and `redesign/portal-hud.css` restates only +what its floating layout needs (a navy transcript sheet, its own turn rhythm, the model kept on the +one bar, Send as its glyph). `$portalPreferred`, the +window-independent preference, is only for behaviour every window must agree on +(setup flow, metrics, session scope, the plugin SDK). Brand marks, floating +surfaces (`app/redesign/portal-floating.css`) and the control scale (`portal-controls.css`, 36px +inside pages and dialogs) belong to the redesign, not to the Hermes Portal theme, which carries +palette and typography only. +Turning it off restores classic onboarding and all classic agent rows without +migrating conversations or destroying the redesign's saved visibility. +Chat chrome leaves the keyboard tab order when covered by a route overlay, without +remounting the draft-owning host. The session-search shortcut reopens and focuses +the redesigned sidebar. Global settings keep seven primary destinations; extra +configuration remains under Advanced, with active deep links revealed. +An unqualified Settings entry opens Account & Plan (billing) in the redesign rather +than a legacy Model page tucked under Advanced; explicit destinations and the classic +default remain unchanged. The redesigned rail follows Figma 823:15804 ("does this +change anything for another agent?" → global, else Agent settings): Account & Plan, +Appearance, Notifications, Keyboard Shortcuts, Gateways & Machines, Sessions & History, +About & Updates, Advanced (device-level and remaining global pages), and an Agent +settings card. Provider accounts and keys live under Agent › Providers & Keys. +A page's list panel (Agents, Routines; `PageSidebarPanel`) wears the chat sidebar's and the +Settings column's header: its title 30px in and 30px down on a 36px line, its start row (New agent, +New routine) 122px under the panel's top where New chat starts, as New chat's borderless light/5 slab +with rimless mono keycaps, and its open row a light/5 fill with no stroke. +Every rail page keeps one page frame, laid by one rule: the page stage contract in +`redesign/portal-pages.css`. A page marks the element its content hangs off `page-stage` (plus +`data-scrolls` when that element scrolls) and sizes nothing itself; the contract centres the one +page column, `--portal-column-page` (980), in the stage, as the chat column is centred. Beside a +sidebar panel the stage is what lies past the panel's divider. Figma left-anchors the column and +draws forms at 840; the owner centres it and keeps one width, so no heading moves between Agents, +Capabilities, Library, Routines, Messaging, Webhooks and the Spawn tree, or between a page's tabs. +A stage narrower than the column keeps `--page-content-inset` (24px, 16 on a phone) on both sides. +`scripts/check_desktop_design_tokens.py` fails any stylesheet outside `tokens/` and the contract +that reads the column token (`page-column`), so a new page cannot lay its own. +Every H1 (or agent hero) tops out at the same y; header actions end +at the column's right edge. Global Settings is the exception ("Prod - Desktop" 06 · Settings/Account, +16292:16447): a 640px column centred in the stage, its H1 (Oswald Light 40/48, -1px) 104px under the +stage's top with a mono description; the column's content box is its text column, 32px inside +the 640 (the header and the scroller pad to it), so the header, section heads (14 SemiBold at .8), +forms and every page's own content start at one x, and only the card primitives (SettingsCard, +SettingsDisclosure, the empty block) bleed out to the column's edges with their rows padded back in; cards are radius 15, borderless, white .02 / black .50 / blue .10, 16px over +and under their rows, rows 12px with 16px Regular labels and mono descriptions. Its panel (16292:16359) +titles "Settings" on a 30px inset with the settings search at its end (the band's pill is gone; typing +and ⌘K still open the palette), 40px rows 4px apart in SemiBold with no stroke on the selected one, and +the Agent settings card 20px under them: radius 9, borderless, the lattice art masked in from its +leading edge. Figma's "// META INFO" caption (placeholder copy) and its Help & Feedback entry (no +destination yet) are not built; Advanced and the Documentation link stay, though Figma omits them. +An agent's page has one vertical menu (Figma 1036:7189). On Overview and History the +page sidebar panel lists the agents; on the Settings tab the same panel swaps to +"← Back to agents" (a history step back to the Overview), the agent's own row, and the +settings sections (10px group labels, 32px rows, counts at the row end), while the stage +holds the agent header, the tabs and the selected page at full width. When the panel is +folded away (the Agents rail button, ⌘B) or the window is too narrow for panels, the sections menu leads the +page in the stage instead, so every section stays reachable. + +Transcript styling is isolated in `components/assistant-ui/thread/redesign.css`, +following the Figma conversation (`491:40346`; width from "Prod - Desktop" chat 16292:16175): one +centred 640px column shared with the docked composer (`--portal-column-conversation`, read as +`--portal-conversation-*` in `app/chat/stage.css`), prose flush with the composer's edges +(`--portal-column-conversation-inset`), 30px turn gaps and 20px output gaps. User bubbles hug their text at +the right edge up to 380px, with 6px corners, 6/10px insets and a 5% (light 2%) +fill and no border; their time and restore actions sit beside the bubble. Base text +is 13px at 1.6 leading before user scaling. A pinned prompt keeps 12px of clearance +below its bubble so clipped reply lines never touch it, and reply lines dissolve over the two +lines beneath it: a still strip at the prompt's edge repaints the stage and fades out downwards +(`aui_sticky-prompt-edge`). Never soften that edge with a mask on the turns that scroll: it changes +every frame and redraws each covered reply whole. Retain the current branded +body font, timestamp preference, and working message actions; enabled timestamps +use caption ink and sit above the bubble. Collapsed tool runs, including +single-tool runs, use the dashed [2,4] summary frame with a status dot. The stage is a +veil over the launch's artwork, lighter behind a new chat than behind a conversation. The composer has no ring: its static 2px spectrum edge +is full strength while it holds focus and dims when focus leaves; its native base +text is 14px before the +user's scale, retaining the browser minimum. Floating dialogs inherit redesigned padding, display typography, and +brand-blue primary actions and the shell's corner radius through root-scoped +rules; their classic defaults remain unchanged. Route overlays and body-portalled dialogs are siblings of the +chat shell, so their redesign styles must not require the shell as an ancestor. + +Redesigned setup is a sessionless preferences/model guide. It resumes from +root `onboarding.run` / `onboarding.step`, retains a working provider, and offers +the free model only when the backend reports eligibility. Finishing settles setup +without replacing the existing draft, attachments, owner, or route; no setup +transcript is created. Explicit sessionless migration retires legacy setup +metadata/cards without deleting conversation history and +broadcasts the end once so connected classic clients leave setup immediately. +Resuming an existing guide is read-only; the first-start latch preserves newer +peer progress and cannot reopen completed setup. A completed/skipped guide with a +persisted step stays settled after a fresh renderer launch; this does not +acknowledge unrelated account-level model notices. Older runtimes show an explicit +upgrade/retry offer rather than silently dropping setup or creating a setup chat. +Local-model configuration releases the modal and leaves a **Resume setup** action. + +Global Capabilities is the inventory/catalog entry; agent settings owns +enablement. Agent Tools groups On/Off switches with per-tool configuration +disclosures; the page-level Advanced disclosure retains Keys and Config. +Installations and tool enablement retain their actual agent and machine scopes. +Hosted connector accounts belong to the Nous identity: agents +sharing that identity share those accounts, and removing one affects them all. +Read-only command search must not replace an agent editor's writable inventory. + +Usage collection belongs to a consenting connection/profile, not merely the +foreground UI. Changing scope revokes the old metrics binding immediately; +events during rebinding are discarded, never replayed under later consent. + +The redesigned composer is 640 × 148 on an empty landing (msg 16292:15670). In a populated native +conversation it keeps the 148px base height, spans the shared 640px column and +docks 30px above the stage floor. Its card is navy, white .05 / blue .10 / black .80 flattened onto +the stage (white on light), with no shadow, and its resting prompt is the card's heading line in +full ink (16292:15681); Figma's dim second line ("Prompt suggestions or processing...") is template +copy and is not built, with model/effort as quiet right-aligned text above the input and attachment, microphone, and labeled Send +controls below. Browser touch targets keep their larger accessibility sizing. +Gateway menus distinguish connection from inference +readiness. Simple mode keeps reconnect and lazy recent activity; Advanced adds +system/restart/logs, with 28px icon controls and destructive restart styling at rest. +A routed page waits for its code inside its own frame (`overlays/page-frame-fallback.tsx`: the +page's panel and a header at the PageHeader geometry), never an empty window; rail buttons warm their +page on hover and focus. A redesign confirm has one anatomy: no corner X, a bordered Cancel beside the +solid action, and a destructive confirm opens on Cancel. The developer tool panel (Files, Terminal, +Review, Browser) has one user-resizable width shared by every tool, never under a tool's own minimum. +It belongs to the chat on screen (`app/redesign/chat-tool-panel.ts`): a page's right side is its own +detail, so off a chat the panel and its rail are out of sight (route-collapsed: a running terminal or +a loaded Browser page stays alive), and each chat comes back with the tools it had open. A chat never +opened, or a new one, starts closed; a new chat's panel goes with it into the conversation on its +first send. Browser tabs follow their own session already; the other tools are remembered per stored +session (`hermes.desktop.chatToolPanels.v1`, the 256 most recently changed). Classic keeps one panel +for the window. Menus draw no stroke: the floating fill and its shadow raise them; popovers, dialogs +and toasts keep their hairline. A dialog's text reads at the 14px body size, its field labels too. +The rail's Settings menu lists the Settings page's destinations, in its order and under its names +(`settings/redesign-navigation.ts`), with Interface mode and Documentation below a separator. + +The redesign's status bar (Figma "status bar", rev 11/16) stands in the canvas under the workspace +frame, ending at the frame's end: the readouts that describe the chat being worked in (workspace, turn +timer, context, cache hit rate, tokens per second, focus timer, approvals) and what plugins add, as +20px mono chips, then a toggle. A readout with nothing to report stays off it. Open, the frame's floor +gap grows from 15px to 40px; collapsed, the toggle floats in the frame's end corner and the bar's +items join the rest of the classic bar's as rows in the rail's System popover. It is open by default +with developer chrome only: Simple rests it collapsed, and its toggle there opens it for the session. +Open, it rests at half ink and comes to full when the pointer reaches the floor around it, the +keyboard is in it or one of its menus is open (a touch screen keeps it full). +A phone has neither bar nor toggle. It lives in `app/redesign/portal-status-bar.*` and +`store/portal-status-bar.ts`. + +## Portal design language (the redesign) + +The redesign (``) is one small design language. Its +source is the Figma file `EuTlgG8nMQo02z5RlImIu9`, newest frame wins: 1036:7189 +(Settings · General) and 1038:7284 (History preview), then agents 895/877, +settings 856, capabilities 919, the chat sidebar's Variation 1 (147:7470) and +the session shell 906:19396; Brand rev 491 supplies conversation content and +Light. Every value lives in one folder, `src/app/redesign/tokens/`, imported once +by `main.tsx` right after `styles.css` (the order matters: the root-gated tokens +tie `styles.css`'s own `:root.dark` rules on specificity and must come later). + +1. **Navy, flat, layered.** One navy family: canvas → translucent panels → stage + → cards. Depth comes from 2–5% ink layers and hairlines, not shadows; only + floating things (menus, popovers, dialogs, toasts, the composer) cast one. +2. **One brand gesture.** `#0000F2` fills primary actions, toggles, checked + states and the active tab underline; everything else is neutral ink. Thin + blue (rings, links, counts) uses the lighter brand ink on dark. +3. **Display for names, sans for everything else.** Oswald Light only for H1, + panel/dialog titles and the wordmark; Mona Sans for UI; mono for paths, ids + and code (OFL stand-ins for Figma's Rules Compressed / Aeonik Fono Pro). +4. **A small, fixed type scale and an AA ink ladder.** Nine sizes, four text inks + that all pass 4.5:1 on every surface. +5. **Radius by role.** 2 chip, 3 control, 4 card, 6 chat surface, 8 floating, + 9 panel corner. +6. **Rows, not boxes.** Grouped rows in one card with hairline dividers; no card + in a card; sections separated by space, not rules. +7. **Instant navigation, quiet motion.** Navigation and selection never animate; + hover paints at once and eases back (120ms); disclosures and popovers 180ms; + drawers 240ms; nothing moves under reduced motion. +8. **States are derived, not drawn.** Figma draws rest and selected. Hover and + pressed are the next ink steps, focus is one 2px brand-ink ring, disabled is + 40% opacity — the same rule for every component. + +### Responsive (compact, medium, wide) + +One renderer serves the desktop window and phones (the browser host), so the language has three +width classes and two breakpoints, defined once in `src/app/redesign/breakpoints.ts` (`$widthClass`, +`widthClassFor`). A custom property cannot feed a media query, so there is no breakpoint token: every +redesign query repeats the literal (`max-width: 639.98px` compact, `max-width: 1023.98px` below wide) +with a comment naming the class. Classic's sidebar dock point is the medium breakpoint; classic is otherwise untouched. + +- **Wide (≥ 1024)**: the desktop layout above, pixel for pixel. +- **Medium (640–1023)**: the rail stays; the chat sidebar and page panels leave the layout and open + as **sheets** from the band's sidebar button over a full-width stage; page columns start at the + panel inset. +- **Compact (< 640)**: no rail column (`--portal-rail-reserve: 0`). The band is the menu, the title + and "+" (no Back/Forward: the browser has them), 48px in the browser (44px on touch; native windows + keep 60, where Electron seats its controls). The menu opens the desktop's left side as one sheet: + the rail beside the chat sidebar or the page's panel, or the rail alone on a page without one. + Page insets collapse to 16px; the developer rail has no compact form. +- **Sheets** (`app/shell/shell-sheet.ts`): full height past the rail, `--portal-sheet-width` + (`min(20rem, 100vw − 3.5rem)`), opaque, over `--portal-surface-scrim`. A tap on the scrim, Esc, or + any pick (navigation) closes one; focus moves into it and returns to the menu. Sheets sit under + menus and popovers (`--portal-layer-sheet*`), so a row's menu opens over its sheet. +- **Short (max-height 30rem, `SHORT_QUERY`)**: a landscape phone or a raised keyboard puts the + composer on one row (attach, editor, send), hides the model row until there is room, and takes the browser's compact band (48, touch 44). +- **Touch** (`(hover: none), (pointer: coarse)` on the browser host, any width): chrome buttons, + rows, menu items, tabs and page buttons take `--portal-touch-target` (44px); switches and + checkboxes keep their visual and extend their hit area; text fields never go under + `--portal-type-field-touch-min` (16px, iOS zoom); hover-only affordances are shown. +- **Floating surfaces** stay inside the window (Radix's available size less a 16px gutter); on + compact a dialog is the whole window with its footer on the floor, and toasts span the window above + the composer. +- **Browser chrome** (`app/redesign/browser-chrome.ts`): `theme-color` follows the canvas; + `viewport-fit=cover` lays the page under the notch, and on a device that reports a safe area the + app root is inset by it as a whole (body-portalled dialogs read `--portal-safe-*`). + +### Artwork + +The redesign paints one artwork per app launch behind the whole window (Figma "Prod - Desktop" › +Brand, frame `16292:10764`: one row per artwork; the onboarding's picker, 18695:18059, adds five). +Dark rotates, in the picker's order, Ascend, Cathedral, Forest, Angel, Sword, Throne and Lattice, then +Wing (the RGB wing), Karborn and Vanilla (the engraved wing as a trace); light rotates its own Ascend +and Vanilla, the only two the Brand page draws in light. `app/redesign/artwork.ts` picks the next one +in that order on every launch (per device, in +localStorage), so two launches in a row never repeat; every window of one launch shares the pick +through the main process's launch id (`hermesDesktop.launchId`), and in a browser each page load +is a launch. A theme switch keeps the same artwork when the other theme draws it, else the next +one it does. The pick is mirrored onto `` before the first paint; +classic and the popped-out Browser get none, and the transparent HUD has no canvas to show its on. + +`app/redesign/portal-artwork.css` holds the art: Figma's geometry in frame pixels (the 1270×870 +Background), scaled to cover the window and centred, plus its ground (`--portal-artwork-ground-*`, +which becomes `--portal-surface-canvas`). Panels are veils over it, Figma's own fills: the stage of +a new chat and a page body `--portal-surface-stage-veil`, a conversation the stronger +`--portal-surface-stage-veil-conversation`, the sidebar kind `--portal-sidebar-panel-background`. +Every painter repeats the art on its own box (`--artwork-paint`, `background-attachment: fixed`) +so nested surfaces never compound a veil; covers that cannot (`--portal-surface-stage`, +`--portal-page-background`) take the veil flattened onto the ground. With a sidebar or page nav +docked (wide), the figure artworks move right by Figma's own amount to stay on the stage; every +image carries bleed past every placement (Ascend repeats across), so no window size ever reaches an +image edge. The panels carry Figma's NOISE effects as small tiling PNGs +(`assets/portal-noise-*.png`, `--artwork-panel-noise`/`--artwork-stage-noise`): the sidebar kind in +both themes, the stage in light. Each is its `feTurbulence` SVG beside it rendered once at 2x: used +directly, the filter is recomputed for every tile the compositor rasters, which made scrolling flash. +Page-wide state a style needs goes on the root as an attribute (`useRootAttribute`), never as +`:root:has(…)`: that selector makes Chromium re-match every `:has()` rule across the document on +each DOM change. Figma's +"01 · Artwork" screens are the canvas layer on its own, not an app state. The one place to choose +the art is the first-time splash's "Make it yours" (Onboarding 18695:18059): it offers the artworks +the current mode draws, and a choice (`$artworkChoice`, a machine-level appearance preference like +the accent) is painted on every later launch instead of the rotation; someone who never chooses keeps +rotating. There is no setting to turn the art off. + +### Tokens + +`raw.css` holds the only colour literals (primitives: brand, status, danger, the +ink ladder of `--ui-base` alphas). The other files hold roles — what a value is +*for* — and read the primitives. Base blocks are dark; `:not(.dark)` blocks hold +light (a `.dark` block, where a file has one, overrides a base value for dark only); Glass changes +only the canvas (one rule in `color.css`). `bridge.css` +maps the roles onto the names shared components already read (`--ui-text-*`, +`--ui-stroke-*`, `--ui-bg-card`, …), so classic primitives rendered inside the +redesign follow the language without forking. Names that predate the role names +remain as aliases (`--portal-brand-fill` → `--portal-surface-brand`, …) until +their readers move. Component CSS may keep local custom properties only as +aliases of tokens (`--portal-sidebar-hover: var(--portal-raw-ink-4)`). + +The tables below are generated from the CSS; do not edit them by hand. Values are the root-level +blocks'; an override under a media query (a width class, a coarse pointer) is noted with its condition. + + + +#### Primitives (`raw.css`): the only colour literals + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--portal-raw-blue` | `#0000f2` | ″ | Figma primary/blue: fills of primary actions, toggles, checked states, the active tab underline. | +| `--portal-raw-blue-ink-dark` | `#8585ff` | ″ | The blue lightened to AA for thin marks (rings, links, counts) on navy. | +| `--portal-raw-violet` | `#6d28d9` | ″ | "Make it yours" (Onboarding 18695:18059): the seven other colours the brand gesture can wear, in the swatches' order. Each is a fill, the ink on it, the brand ink on light and the brand ink on navy. Deep fills (violet, pink, red, orange) take white ink and are their own light ink; bright ones (yellow, green, cyan: Figma's secondary colours as drawn) take the navy ink and a darkened light ink. Every set keeps the blue's contrast duties: 4.5:1 for the on-brand ink, the brand ink on every light and dark panel, and the text on a brand selection (portal-accent-contrast.test.ts). | +| `--portal-raw-violet-ink-dark` | `#b79cff` | ″ | | +| `--portal-raw-pink` | `#b0124f` | ″ | | +| `--portal-raw-pink-ink-dark` | `#ff80b0` | ″ | | +| `--portal-raw-red` | `#c40d0d` | ″ | | +| `--portal-raw-red-ink-light` | `#b00c0c` | ″ | | +| `--portal-raw-red-ink-dark` | `#ff8080` | ″ | | +| `--portal-raw-orange-deep` | `#a33f00` | ″ | | +| `--portal-raw-orange-ink-dark` | `#ff9a52` | ″ | | +| `--portal-raw-yellow` | `#f2f200` | ″ | | +| `--portal-raw-yellow-ink-light` | `#666000` | ″ | | +| `--portal-raw-green-deep` | `#086b36` | ″ | | +| `--portal-raw-green-ink-dark` | `#3fd68a` | ″ | | +| `--portal-raw-cyan` | `#00f2f2` | ″ | | +| `--portal-raw-cyan-ink-light` | `#00696b` | ″ | | +| `--portal-raw-navy` | `#0b0b24` | ″ | The ink on a bright fill: the dark canvas navy (--portal-raw-navy-channels). | +| `--portal-raw-accent` | `var(--portal-raw-blue)` | ″ | The accent the brand gesture wears: the blue, or the person's pick (data-portal-accent, below). The navy family (veils, panels, the composer card) stays on the blue whatever the accent. | +| `--portal-raw-accent-on` | `var(--portal-raw-white)` | ″ | | +| `--portal-raw-accent-ink-light` | `var(--portal-raw-blue)` | ″ | | +| `--portal-raw-accent-ink-dark` | `var(--portal-raw-blue-ink-dark)` | ″ | | +| `--portal-raw-white` | `#f2f2f2` | ″ | Figma primary/white: ink on the brand fill. | +| `--portal-raw-pure-white` | `#fff` | ″ | | +| `--portal-raw-black` | `#000` | ″ | | +| `--portal-raw-green` | `#00f279` | ″ | Figma secondary/green (live dots and gradients); at .6 it is the connected / online ink on dark (1089:8305). | +| `--portal-raw-green-60` | `color-mix(in srgb, var(--portal-raw-green) 60%, transparent)` | ″ | | +| `--portal-raw-mint-deep` | `#1f8a65` | ″ | Connected / online ink on light: the green darkened to AA. | +| `--portal-raw-orange` | `#f27900` | ″ | Figma secondary/orange: pending and warning. | +| `--portal-raw-red-signal` | `#f20000` | ″ | Figma secondary/red: a status badge's fill under black ink (UNVERIFIED, 18732:33155). | +| `--portal-raw-danger` | `#a22a20` | ″ | Danger fill and stroke (877:4212, 878:7066, 1038:7836) and its soft status text (877:4312). | +| `--portal-raw-danger-soft` | `#cc8a84` | ″ | | +| `--portal-raw-danger-bright` | `#ff7373` | ″ | The danger label on dark (1038:7836): bright enough for 4.5:1 on the danger tint. | +| `--portal-raw-spectrum-red` | `#aa1515` | ″ | The composer's spectrum edge (906:19872). | +| `--portal-raw-spectrum-yellow` | `#ddd61c` | ″ | | +| `--portal-raw-gray` | `#797979` | ″ | The neutral of a hovered sidebar row's gradient (1089:8351): the selected row's brand ramp in grayscale. | +| `--portal-raw-navy-channels` | `11 11 36` | ″ | The HUD's transcript sheet: the dark canvas navy as channels, laid at the HUD's own alphas (styles.css). Always dark, in both modes: its ink is white over someone else's window. | +| `--portal-raw-shadow-4` | `rgb(0 0 0 / 0.04)` | ″ | Shadow inks. | +| `--portal-raw-shadow-8` | `rgb(0 0 0 / 0.08)` | ″ | | +| `--portal-raw-shadow-20` | `rgb(0 0 0 / 0.2)` | ″ | | +| `--portal-raw-shadow-50` | `rgb(0 0 0 / 0.5)` | ″ | | +| `--portal-raw-highlight-5` | `rgb(255 255 255 / 0.05)` | ″ | The workspace frame's top highlight (16292:14463): white at .05. | +| `--portal-raw-shadow-navy-10` | `rgb(18 20 38 / 0.1)` | ″ | Light's workspace frame shadow ink (16292:23801): a navy at .1. | +| `--portal-raw-ink-2` | `color-mix(in srgb, var(--ui-base) 2%, transparent)` | ″ | The ink ladder (LANGUAGE §1.1): Figma's light/2, 5, 10, 40 plus the page steps 3, 4, 8, 14, 22, 28. No other neutral alpha belongs to the language; the off-ladder steps still in use are listed in color.css and the "Still to unify" table. | +| `--portal-raw-ink-3` | `color-mix(in srgb, var(--ui-base) 3%, transparent)` | ″ | | +| `--portal-raw-ink-4` | `color-mix(in srgb, var(--ui-base) 4%, transparent)` | ″ | | +| `--portal-raw-ink-5` | `color-mix(in srgb, var(--ui-base) 5%, transparent)` | ″ | | +| `--portal-raw-ink-8` | `color-mix(in srgb, var(--ui-base) 8%, transparent)` | ″ | | +| `--portal-raw-ink-10` | `color-mix(in srgb, var(--ui-base) 10%, transparent)` | ″ | | +| `--portal-raw-ink-14` | `color-mix(in srgb, var(--ui-base) 14%, transparent)` | ″ | | +| `--portal-raw-ink-20` | `color-mix(in srgb, var(--ui-base) 20%, transparent)` | ″ | | +| `--portal-raw-ink-22` | `color-mix(in srgb, var(--ui-base) 22%, transparent)` | ″ | | +| `--portal-raw-ink-28` | `color-mix(in srgb, var(--ui-base) 28%, transparent)` | ″ | | +| `--portal-raw-ink-40` | `color-mix(in srgb, var(--ui-base) 40%, transparent)` | ″ | | +| `--portal-raw-brand-8` | `color-mix(in srgb, var(--portal-raw-accent) 8%, transparent)` | ″ | Brand tints, in the accent: row selection 8, info banner 10, light brand selection 12, dark brand selection 25, info banner stroke 60. | +| `--portal-raw-brand-10` | `color-mix(in srgb, var(--portal-raw-accent) 10%, transparent)` | ″ | | +| `--portal-raw-brand-12` | `color-mix(in srgb, var(--portal-raw-accent) 12%, transparent)` | ″ | | +| `--portal-raw-brand-25` | `color-mix(in srgb, var(--portal-raw-accent) 25%, transparent)` | ″ | | +| `--portal-raw-brand-30` | `color-mix(in srgb, var(--portal-raw-accent) 30%, transparent)` | ″ | The blue under a sidebar agent card (16292:15630). | +| `--portal-raw-brand-60` | `color-mix(in srgb, var(--portal-raw-accent) 60%, transparent)` | ″ | | +| `--portal-raw-danger-8` | `color-mix(in srgb, var(--portal-raw-danger) 8%, transparent)` | ″ | Danger tints (1038:7836): the tint 8, its hover and pressed steps 14 and 20, the stroke 50. | +| `--portal-raw-danger-14` | `color-mix(in srgb, var(--portal-raw-danger) 14%, transparent)` | ″ | | +| `--portal-raw-danger-20` | `color-mix(in srgb, var(--portal-raw-danger) 20%, transparent)` | ″ | | +| `--portal-raw-danger-50` | `color-mix(in srgb, var(--portal-raw-danger) 50%, transparent)` | ″ | | + +#### Colour roles (`color.css`) + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--portal-surface-brand` | `var(--portal-raw-accent)` | ″ | Brand, in the accent (blue unless the person picked another). The fill is the same in every theme and mode, and so is the ink on it (white, or the navy on a bright accent); thin rings, underlines and small brand text use the brand ink, which lightens on dark canvases and darkens on light ones for contrast. | +| `--portal-text-on-brand` | `var(--portal-raw-accent-on)` | ″ | | +| `--portal-surface-brand-hover` | `color-mix(in srgb, var(--portal-surface-brand) 86%, var(--ui-base))` | ″ | A brand-filled card under the pointer (the sidebar's Create an Account): a step toward the ink. | +| `--portal-text-brand` | `var(--portal-raw-accent-ink-dark)` | `var(--portal-raw-accent-ink-light)` | | +| `--portal-composer-fill` | `color-mix( in srgb, var(--portal-raw-pure-white) 8%, color-mix( in srgb, var(--portal-raw-blue) 10%, color-mix(in srgb, var(--portal-raw-black) 80%, var(--ui-chat-surface-background)) ) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 98%, var(--ui-chat-surface-background))` | The composer card (msg 16292:15670): white .05 / blue .10 / black .80 at .94, flattened onto the stage so the transcript never shows through. Figma's card lets 6% of the art through, which lifts it to #171635 on Wing; the opaque card takes white .08 to land there. Light draws it white (16292:27185). Its resting prompt is the card's heading line at full ink (16292:15681). | +| `--portal-composer-prompt-ink` | `var(--portal-text-primary)` | ″ | | +| `--portal-surface-brand-selected` | `var(--portal-raw-brand-25)` | `var(--portal-raw-brand-12)` | Brand selection: selected destinations, segments, scope chips, choice tiles and the DEFAULT / RUNNING chips (856:3444, 1036:7318). | +| `--portal-spectrum-red` | `var(--portal-raw-spectrum-red)` | ″ | | +| `--portal-spectrum-yellow` | `var(--portal-raw-spectrum-yellow)` | ″ | | +| `--portal-text-primary` | `var(--ui-base)` | ″ | Text ladder. Figma steps ink 1 / .8 / .6 / .5 / .4 / .3, but .4 and .3 fail AA for the 12-13px meta and labels that use them, so the ladder's floor is the least ink that keeps 4.5:1 on every real surface (sidebar, stage, page canvas, cards, popovers, selected rows), and the rungs above are spaced by contrast, not alpha: light ≈ 16 / 8.9 / 6.7 / 5.1:1, dark ≈ 17 / 8.7 / 6.6 / 4.9:1. Dark ink on light canvases loses contrast faster, so light needs more alpha per rung. | +| `--portal-text-secondary` | `color-mix(in srgb, var(--ui-base) 70%, transparent)` | `color-mix(in srgb, var(--ui-base) 80%, transparent)` | | +| `--portal-text-tertiary` | `color-mix(in srgb, var(--ui-base) 60%, transparent)` | `color-mix(in srgb, var(--ui-base) 72%, transparent)` | | +| `--portal-text-quaternary` | `color-mix(in srgb, var(--ui-base) 50%, transparent)` | `color-mix(in srgb, var(--ui-base) 64%, transparent)` | | +| `--portal-text-quiet-opacity` | `0.5` | `0.64` | The floor as a layer opacity, for a live line that dims as a whole: full-ink regular text quieted by opacity, not a pale ink stacked under a fade (the working row, design review 2026-11-17). | +| `--portal-backdrop-opacity` | `0.2` | ″ | What the rest of the first-time splash fades to while one of its rows speaks (Onboarding 18695:17294): a backdrop, not text to read, so it may go under the floor. | +| `--portal-surface-canvas` | `var(--portal-skin-window, var(--ui-bg-chrome))` | `var(--portal-skin-window, color-mix(in srgb, var(--ui-base) 5%, var(--ui-bg-chrome)))` | Window canvas (rails, titlebar band): the skin's own canvas, else its chrome. Under the launch's artwork (portal-artwork.css) it is that artwork's ground instead. | +| `--portal-artwork-ground-vanilla` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix(in srgb, var(--portal-raw-black) 94%, var(--portal-raw-blue)) )` | ″ | The artworks' grounds (Prod - Desktop › Brand 16291:10506, each row's Background fill): brand blue under black .94 and white .05 (Vanilla 16292:10768), black .90 (Wing 16292:13812), black .96 (Angel 16292:17116, Ascend 16292:20301); Karborn lays black .98 on the blue and lightens it with a blue .10 filter (16292:35757). Light paints #f2f2f2 under both of its artworks (16292:26683). | +| `--portal-artwork-ground-wing` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix(in srgb, var(--portal-raw-black) 90%, var(--portal-raw-blue)) )` | ″ | | +| `--portal-artwork-ground-photo` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix(in srgb, var(--portal-raw-black) 96%, var(--portal-raw-blue)) )` | ″ | | +| `--portal-artwork-ground-karborn` | `color-mix( in srgb, var(--portal-raw-blue) 10%, color-mix(in srgb, var(--portal-raw-black) 98%, var(--portal-raw-blue)) )` | ″ | | +| `--portal-artwork-ground-light` | `var(--portal-raw-white)` | ″ | | +| `--portal-surface-stage-veil` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix(in srgb, var(--portal-raw-black) 80%, color-mix(in srgb, var(--portal-raw-blue) 40%, transparent)) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 80%, transparent)` | Panels over the artwork are veils, Figma's three-layer fills (top layer first), so the art reads through each at its own strength: navy, the brand blue under black, where the previous design put chat on a neutral (white 5% on black). The stage of a new chat and a page body (Panel/flexible 16292:18060, 16292:19906): white .05 / black .80 / blue .40, about 89% opaque, #0E0E23 where it is solid. | +| `--portal-surface-stage-veil-conversation` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix(in srgb, var(--portal-raw-black) 85%, color-mix(in srgb, var(--portal-raw-blue) 60%, transparent)) )` | `color-mix( in srgb, var(--portal-raw-black) 2%, color-mix(in srgb, var(--portal-raw-pure-white) 96%, transparent) )` | A conversation strengthens it to focus the transcript (05 · Workspace/Chat 16292:18949): white .05 / black .85 / blue .60, about 94% opaque. | +| `--portal-surface-stage` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix( in srgb, var(--portal-raw-black) 85%, color-mix(in srgb, var(--portal-raw-blue) 60%, var(--portal-surface-canvas)) ) )` | `color-mix( in srgb, var(--portal-raw-black) 2%, color-mix(in srgb, var(--portal-raw-pure-white) 96%, var(--portal-surface-canvas)) )` | The stage flattened onto the canvas: what covers inside a conversation paint (the docked composer's floor, overlays on the transcript) where the art itself is not repainted. | +| `--portal-sidebar-background` | `color-mix( in srgb, var(--portal-raw-pure-white) 2%, color-mix( in srgb, var(--portal-raw-black) 85%, color-mix(in srgb, var(--portal-raw-blue) 70%, var(--portal-surface-canvas)) ) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 98%, var(--portal-surface-canvas))` | The chat sidebar's opaque fill (the shared sidebar surface, sheets): its veil flattened onto the canvas. | +| `--portal-page-background` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix( in srgb, var(--portal-raw-black) 80%, color-mix(in srgb, var(--portal-raw-blue) 40%, var(--portal-surface-canvas)) ) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 80%, var(--portal-surface-canvas))` | Routed pages lay their nav and body on the window canvas like chat (06 · Settings/Account 16292:19723): the band shows the art, the body is the new chat's stage, flattened here for what covers it. | +| `--portal-page-sidebar-background` | `var(--portal-sidebar-background)` | ″ | | +| `--portal-surface-collection` | `color-mix( in srgb, var(--portal-raw-pure-white) 2%, color-mix(in srgb, var(--portal-raw-black) 50%, color-mix(in srgb, var(--portal-raw-blue) 10%, transparent)) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 70%, transparent)` | A collection's cards and table on a page body (Library 1163:18113, 1163:18155): white .02 / black .50 / blue .10 over the stage. | +| `--portal-surface-elevated` | `var(--ui-bg-elevated)` | ″ | Menus, popovers, dialogs, drawers, toasts: the solid floating fill (878:6044 #0D0D1E on dark). | +| `--portal-surface-card` | `var(--portal-raw-ink-2)` | ″ | Cards of grouped rows (1036:7576, 1038:7803). | +| `--portal-settings-card` | `color-mix( in srgb, var(--portal-raw-pure-white) 2%, color-mix(in srgb, var(--portal-raw-black) 50%, var(--portal-raw-brand-10)) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 70%, transparent)` | Global Settings' cards lift off the page with no stroke (Card 16292:16456): white .02 / black .50 / blue .10 (#1A1A30 where solid); their dividers light/5. Section heads at .8 ink. | +| `--portal-settings-divider` | `var(--portal-raw-ink-5)` | ″ | | +| `--portal-welcome-card` | `color-mix( in srgb, var(--portal-raw-pure-white) 2%, color-mix(in srgb, var(--portal-raw-black) 60%, color-mix(in srgb, var(--portal-raw-blue) 20%, transparent)) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 70%, transparent)` | The first-time splash's cards (Onboarding 18695:17163 "Information", the artwork cards): white .02 / black .60 / blue .20 over the stage. | +| `--portal-surface-brand-card` | `var(--portal-raw-brand-10)` | ″ | Hermes' answer to a message held until sign up (18695:18641): the accent at 10%. | +| `--portal-badge-alert-fill` | `var(--portal-raw-red-signal)` | ″ | A step's status badge on the sign-in screens (18732:33155, 18695:19224): Figma's red, green and white .4 fills under black ink. The waiting fill takes the ladder's .5 so black keeps 4.5:1. | +| `--portal-badge-ok-fill` | `var(--portal-status-online)` | ″ | | +| `--portal-badge-waiting-fill` | `var(--portal-text-quaternary)` | ″ | | +| `--portal-badge-ink` | `var(--portal-raw-black)` | ″ | | +| `--portal-badge-waiting-ink` | `var(--portal-raw-black)` | `var(--portal-raw-pure-white)` | Light's waiting fill is the dark ink at .64: white reads on it, black does not. | +| `--portal-choice-rim` | `color-mix(in srgb, var(--portal-raw-black) 80%, transparent)` | `color-mix(in srgb, var(--portal-raw-pure-white) 80%, transparent)` | The dark rim inside a colour swatch and a chosen artwork card (18695:18079): black .80. | +| `--portal-settings-section-ink` | `color-mix(in srgb, var(--ui-base) 80%, transparent)` | ″ | | +| `--portal-settings-link` | `var(--portal-raw-ink-5)` | ″ | The column's Agent settings card (16292:16428): light/5. | +| `--portal-surface-selected` | `var(--portal-raw-ink-5)` | ″ | Neutral selection: list rows, nav rows (1036:7409), with --portal-stroke-selected. | +| `--portal-surface-row-hover` | `var(--portal-raw-ink-3)` | ″ | A row under the pointer on a panel, the stage or a card: one ink step over its rest. | +| `--portal-surface-skeleton` | `var(--portal-raw-ink-8)` | ″ | Content still loading (skeleton bars, tiles and rows): one quiet ink block on any surface. | +| `--portal-surface-chrome` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix(in srgb, var(--portal-raw-black) 60%, color-mix(in srgb, var(--portal-raw-blue) 20%, transparent)) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 20%, transparent)` | 30px chrome buttons and the session pill: the band's navy tile, white .05 / black .60 / blue .20 (16292:15285, 16292:15297), the glyph at .4; hover and pressed brighten a step each. | +| `--portal-surface-chrome-hover` | `color-mix( in srgb, var(--portal-raw-pure-white) 8%, color-mix(in srgb, var(--portal-raw-black) 60%, color-mix(in srgb, var(--portal-raw-blue) 30%, transparent)) )` | `var(--portal-raw-ink-5)` | | +| `--portal-surface-chrome-pressed` | `color-mix( in srgb, var(--portal-raw-pure-white) 10%, color-mix(in srgb, var(--portal-raw-black) 60%, color-mix(in srgb, var(--portal-raw-blue) 40%, transparent)) )` | `var(--portal-raw-ink-10)` | | +| `--portal-text-chrome` | `var(--portal-raw-ink-40)` | `color-mix(in srgb, var(--ui-base) 48%, transparent)` | | +| `--portal-status-chip-fill` | `var(--portal-surface-chrome)` | `color-mix(in srgb, var(--portal-raw-pure-white) 60%, transparent)` | The status bar's chips (tab 1262:39845): the band's chrome tile in dark, white .6 in light. | +| `--portal-hud-ink-user` | `color-mix(in srgb, var(--portal-raw-blue-ink-dark) 55%, var(--portal-raw-pure-white))` | ″ | Your own lines in the HUD's transcript: the brand ink lightened to body-text contrast on its navy sheet. One value in both modes; the sheet is always dark. | +| `--portal-rail-fill` | `color-mix( in srgb, var(--portal-raw-pure-white) 5%, color-mix(in srgb, var(--portal-raw-black) 60%, color-mix(in srgb, var(--portal-raw-blue) 20%, transparent)) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 20%, transparent)` | The global rail's buttons (ico 16292:15253): a navy tile, white .05 / black .60 / blue .20, the glyph at .4; the open destination white .10 / black .60 / blue .40 (16292:15245) with its glyph in full ink. Hover takes the step between them. | +| `--portal-rail-fill-hover` | `color-mix( in srgb, var(--portal-raw-pure-white) 8%, color-mix(in srgb, var(--portal-raw-black) 60%, color-mix(in srgb, var(--portal-raw-blue) 30%, transparent)) )` | `var(--portal-raw-ink-5)` | | +| `--portal-rail-fill-selected` | `color-mix( in srgb, var(--portal-raw-pure-white) 10%, color-mix(in srgb, var(--portal-raw-black) 60%, color-mix(in srgb, var(--portal-raw-blue) 40%, transparent)) )` | `var(--portal-raw-ink-10)` | | +| `--portal-rail-ink` | `var(--portal-raw-ink-40)` | `color-mix(in srgb, var(--ui-base) 48%, transparent)` | | +| `--portal-rail-ink-selected` | `var(--portal-text-primary)` | ″ | | +| `--portal-panel-action` | `var(--portal-raw-ink-5)` | `var(--portal-raw-ink-2)` | A list panel's start row (New agent, New routine) wears New chat's slab (16292:15511): light/5, no rim; dark/2 on light. | +| `--portal-panel-action-hover` | `var(--portal-raw-ink-8)` | `var(--portal-raw-ink-5)` | | +| `--portal-surface-control` | `var(--portal-raw-ink-5)` | `var(--portal-raw-ink-3)` | Secondary and icon buttons (877:4189) at rest, hover and pressed: one ink step each. | +| `--portal-surface-control-hover` | `var(--portal-raw-ink-8)` | `var(--portal-raw-ink-5)` | | +| `--portal-surface-control-pressed` | `var(--portal-raw-ink-10)` | `var(--portal-raw-ink-8)` | | +| `--portal-surface-field` | `var(--portal-raw-ink-4)` | `var(--portal-raw-ink-2)` | Inputs, search, segmented tracks (895:9670). | +| `--portal-surface-select` | `var(--portal-raw-ink-8)` | `var(--portal-raw-ink-4)` | Select triggers (856:3456). | +| `--portal-surface-floating-hover` | `color-mix(in srgb, var(--ui-base) 6%, transparent)` | `var(--portal-raw-ink-5)` | A menu item under the pointer, on the elevated surface. | +| `--portal-surface-scrim` | `var(--portal-raw-shadow-50)` | `var(--portal-raw-shadow-20)` | The modal scrim: a plain dim, never a blur. | +| `--portal-surface-danger-solid` | `var(--portal-raw-danger)` | ″ | Danger, one family (1038:7836). The confirm of a destructive dialog (878:7066) is the solid slab with white ink (7.3:1); every other destructive mark (outline buttons, menu items, banners) is the 8% tint with a 50% stroke and the danger ink, which keeps 4.5:1 on that tint: #FF7373 on dark (≈7:1), the slab's own red on light (≈6:1). | +| `--portal-text-on-danger` | `var(--portal-raw-pure-white)` | ″ | | +| `--portal-surface-danger` | `var(--portal-raw-danger-8)` | ″ | | +| `--portal-surface-danger-hover` | `var(--portal-raw-danger-14)` | ″ | | +| `--portal-surface-danger-pressed` | `var(--portal-raw-danger-20)` | ″ | | +| `--portal-stroke-danger` | `var(--portal-raw-danger-50)` | ″ | | +| `--portal-text-danger` | `var(--portal-raw-danger-bright)` | `var(--portal-raw-danger)` | | +| `--portal-stroke-hairline` | `var(--portal-raw-ink-5)` | ″ | Strokes. Card edges, the panel-to-stage edge, page footer rules (1038:7803). | +| `--portal-stroke-divider` | `var(--portal-raw-ink-3)` | `var(--portal-raw-ink-5)` | Between rows inside a card and under the page tabs (877:4229, 1038:7499); light takes one step more to stay visible on #f2f2f2. | +| `--portal-stroke-edge` | `var(--portal-raw-ink-10)` | ″ | The chat sidebar's edge and header rule (Var1 147:7470: light/10). | +| `--portal-stroke-control` | `var(--portal-raw-ink-10)` | `var(--portal-raw-ink-14)` | | +| `--portal-stroke-field` | `var(--portal-raw-ink-14)` | `color-mix(in srgb, var(--ui-base) 18%, transparent)` | | +| `--portal-stroke-strong` | `var(--portal-raw-ink-28)` | ″ | Selects, checkbox and radio at rest. | +| `--portal-stroke-selected` | `var(--portal-raw-ink-5)` | ″ | | +| `--portal-stroke-floating` | `var(--portal-raw-ink-10)` | ″ | | +| `--portal-status-online` | `var(--portal-raw-green-60)` | `var(--portal-raw-mint-deep)` | Status inks, one set for the whole redesign (sidebar machines, dots, chips, page status text): online is secondary/green at .6 (1089:8305, the newest sidebar), pending Figma's orange, failed its soft red; each passes 4.5:1 on its mode's panels. | +| `--portal-status-pending` | `var(--portal-raw-orange)` | `color-mix(in srgb, var(--portal-raw-orange) 70%, var(--portal-raw-black))` | | +| `--portal-status-error-ink` | `var(--portal-raw-danger-soft)` | `var(--portal-raw-danger)` | | +| `--portal-focus-ring-color` | `var(--portal-text-brand)` | ″ | The one focus ring's colour (geometry in shape.css). | +| `--portal-brand-fill` | `var(--portal-surface-brand)` | ″ | Names in use before the role names; Phase B moves their readers to the role and deletes them. | +| `--portal-on-brand` | `var(--portal-text-on-brand)` | ″ | | +| `--portal-brand-ink` | `var(--portal-text-brand)` | ″ | | +| `--portal-selection-background` | `var(--portal-surface-brand-selected)` | ″ | | +| `--portal-neutral-selection-background` | `var(--portal-surface-selected)` | ″ | | +| `--portal-neutral-selection-stroke` | `var(--portal-stroke-selected)` | ″ | | +| `--portal-window-background` | `var(--portal-surface-canvas)` | ″ | | +| `--portal-sidebar-panel-background` | `color-mix( in srgb, var(--portal-raw-pure-white) 2%, color-mix(in srgb, var(--portal-raw-black) 85%, color-mix(in srgb, var(--portal-raw-blue) 70%, transparent)) )` | `color-mix(in srgb, var(--portal-raw-pure-white) 98%, transparent)` | The chat sidebar, side tool panels and page navs (Panel 16292:18203): white .02 / black .85 / blue .70, about 96% opaque, so the art still reads through. | +| `--portal-panel-divider` | `var(--portal-stroke-hairline)` | ″ | | +| `--portal-control-fill` | `var(--portal-surface-control)` | ″ | | +| `--portal-control-fill-hover` | `var(--portal-surface-control-hover)` | ″ | | +| `--portal-control-fill-pressed` | `var(--portal-surface-control-pressed)` | ″ | | +| `--portal-control-stroke` | `var(--portal-stroke-control)` | ″ | | +| `--portal-field-fill` | `var(--portal-surface-field)` | ″ | | +| `--portal-field-stroke` | `var(--portal-stroke-field)` | ″ | | +| `--portal-select-fill` | `var(--portal-surface-select)` | ″ | | +| `--portal-select-stroke` | `var(--portal-stroke-strong)` | ″ | | +| `--portal-control-danger-fill` | `var(--portal-surface-danger-solid)` | ″ | | +| `--portal-control-on-danger` | `var(--portal-text-on-danger)` | ″ | | +| `--portal-floating-surface` | `var(--portal-surface-elevated)` | ″ | | +| `--portal-floating-stroke` | `var(--portal-stroke-floating)` | ″ | | +| `--portal-floating-item-hover` | `var(--portal-surface-floating-hover)` | ″ | | + +#### Type (`type.css`) + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--portal-font-display` | `var(--dt-font-chosen, 'Oswald'), var(--dt-font-sans)` | ″ | H1, panel, dialog and drawer titles, the wordmark. | +| `--portal-font-body` | `var(--dt-font-chosen, 'Mona Sans'), var(--dt-font-sans)` | ″ | Every other line of UI. | +| `--portal-font-mono` | `var(--dt-font-mono)` | ″ | Paths, ids, code and an agent's own words (the SOUL preview, 877:4245): the theme's mono, the bundled JetBrains Mono standing in for Aeonik Fono. | +| `--portal-type-display-xl-size` | `2.5rem` | ″ | Page H1, agent name (1036:7378). | +| `--portal-type-display-lg-size` | `1.875rem` | ″ | Panel title, sub-page H2, dialog and drawer title (1036:7476, 1038:7797). | +| `--portal-type-section-size` | `0.9375rem` | ″ | Section heading, stat value (1036:7481). | +| `--portal-type-body-size` | `0.875rem` | ″ | Row label, button, tab, input value (label 500, body 400); a dialog's body, its field labels and its lists (design review 2026-11-17: 14px body in the redesign). | +| `--portal-type-ui-size` | `0.875rem` | ″ | Nav row, sidebar row, menu item, description. Figma draws 13px (1036:7410); the designer asked for 14 after seeing it in the app (2026-11-13). | +| `--portal-type-meta-size` | `0.75rem` | ″ | Timestamps, row meta, the composer's model row (906:19738). | +| `--portal-type-micro-size` | `0.6875rem` | ″ | Nav counts, tags, keycaps, the "You" label (1036:7434). | +| `--portal-type-caption-size` | `0.625rem` | ″ | UPPERCASE group labels, table headers, stat labels, menu labels (1036:7408). | +| `--portal-type-chip-size` | `0.5625rem` | ″ | UPPERCASE DEFAULT / RUNNING / EMPTY chips (1036:7318). | +| `--portal-type-field-touch-min` | `16px` | ″ | The smallest text a field may use on a coarse pointer in the browser: iOS Safari zooms into any focused field under 16px (px, not rem: the zoom rule reads CSS pixels). | +| `--portal-settings-h1-line` | `3rem` | ″ | Global Settings (16292:16447): the H1 at Figma's 48px line and -1px tracking; row labels in the 16px body (Nous/Body 22.4 line); descriptions in the mono signal font. | +| `--portal-settings-h1-tracking` | `-1px` | ″ | | +| `--portal-settings-row-label-size` | `1rem` | ″ | | +| `--portal-settings-row-label-line` | `1.4` | ″ | | +| `--portal-settings-section-line` | `1.25rem` | ″ | Section heads: Nous/Compact SemiBold on a 20px line, at the UI step (Figma's 13 drawn at 14). | +| `--portal-settings-meta-font` | `var(--portal-font-mono)` | ″ | | +| `--portal-tracking-display` | `-0.01em` | ″ | Tracking per role: display titles tighten, small UI opens up, captions and chips open most. | +| `--portal-tracking-ui` | `0.01em` | ″ | | +| `--portal-tracking-chip` | `0.04em` | ″ | | +| `--portal-tracking-caption` | `0.06em` | ″ | | + +#### Space and layout (`space.css`) + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--portal-rail-width` | `3.75rem` | ″ | The global rail and the developer rail (1036:7202). | +| `--portal-rail-reserve` | `var(--portal-rail-width)` | ″ | What the rail takes from the layout: its width, none on compact, where it rides the sheet. `(max-width: 639.98px)`: `0px`. | +| `--portal-rail-top` | `5.625rem` | ″ | The global rail ("Prod - Desktop" rail 16292:15233): no brand badge (its layer is hidden in every row), the destinations from 90px down on every host, clear of macOS traffic lights in the column; 30px buttons (the chrome row, the touch target on a coarse pointer), 20px apart, the foot's 40px off the window floor. Every glyph is 20px: Figma draws the destinations at 16 and the foot at 20, and the designer's review of the build (rev 11/16, 1260:39312) asks for 20 throughout. | +| `--portal-rail-button` | `var(--portal-row-chrome)` | ″ | | +| `--portal-rail-glyph` | `1.25rem` | ″ | | +| `--portal-rail-gap` | `1.25rem` | ″ | | +| `--portal-rail-bottom` | `2.5rem` | ″ | | +| `--portal-rail-popover-offset` | `calc( (var(--portal-rail-width) - var(--portal-rail-button)) / 2 + var(--portal-space-tight) )` | ″ | A rail menu or popover opens one tight gap past the rail's edge, whatever the rail button's size (30px, 44px on touch): the distance from the button's end to the rail's, plus that gap. | +| `--portal-panel-reveal-width` | `2.75rem` | ″ | The way back to a folded sidebar or page panel in Simple mode (1061:7816): a 44×40 floating button at the stage's top-leading corner, clear of the band. Advanced keeps it in the band. | +| `--portal-panel-reveal-height` | `2.5rem` | ″ | | +| `--portal-panel-reveal-inset` | `1rem` | ″ | | +| `--portal-panel-reveal-glyph` | `1.125rem` | ″ | | +| `--portal-sheet-width` | `min(var(--sessions-pane-width), 100vw - 3.5rem)` | ″ | Below wide the chat sidebar and page panels are sheets over the stage: the sidebar's width, leaving a 56px strip of scrim to tap. | +| `--portal-sheet-panel-width` | `calc(var(--portal-sheet-width) - var(--portal-rail-width) + var(--portal-rail-reserve))` | ″ | The sheet's panel past the rail: the whole sheet on medium (the rail stays in the layout), the sheet less the rail on compact (the rail rides the sheet). | +| `--portal-sheet-panel-max-width` | `calc(100vw - 3.5rem - var(--portal-rail-width))` | ″ | The widest a sheet's panel may be: from the rail's edge to the scrim strip. A plugin pane's sheet keeps the width the pane declares, up to this. | +| `--portal-touch-target` | `2.75rem` | ″ | The smallest hit area on a coarse pointer (WCAG 2.5.5); a control's visual may stay smaller. | +| `--portal-space-compact` | `0.75rem` | ″ | A phone's tighter rhythm (compact and short windows): the composer's padding and gaps, its dock's floor, and on touch its control rows, whose 44px targets overlap the padding. | +| `--portal-space-tight` | `0.5rem` | ″ | | +| `--portal-composer-row-touch` | `1.75rem` | ″ | | +| `--portal-safe-top` | `env(safe-area-inset-top, 0px)` | ″ | The browser's safe area (notch, home indicator) once the page is laid out under it (viewport-fit=cover, app/redesign/browser-chrome.ts); zero on every other host. The app root is inset by it as a whole (portal-shell.css), so only body-portalled surfaces (dialogs) read these. | +| `--portal-safe-bottom` | `env(safe-area-inset-bottom, 0px)` | ″ | | +| `--portal-safe-start` | `env(safe-area-inset-left, 0px)` | ″ | | +| `--portal-safe-end` | `env(safe-area-inset-right, 0px)` | ″ | | +| `--portal-panel-width` | `var(--portal-sidebar-width, var(--sessions-pane-width))` | ″ | ONE sidebar column for every rail destination: page panels (Agents, Routines, Settings) take the chat sidebar's width — the user's sash width once they size it (published by the pane tree as --portal-sidebar-width), else its default — so switching destinations never moves the panel edge, its divider or the stage's content edge. | +| `--portal-frame-inset` | `1.25rem` | ″ | The page-frame contract: a page's content column sits centred in its stage (the frame past the page's sidebar panel, where it has one), as the chat column does, and never closer to the stage's edges than this inset. Figma left-anchors the column; the owner centres it. `(max-width: 639.98px)`: `1rem`. | +| `--portal-workspace-inset-start` | `0.3125rem` | ″ | The workspace frame's gaps, where the artwork shows, measured in Figma's 1280×880 window (Content 16292:14463 at x 65–1265, y 60–865): 5px past a 60px rail (and before the developer rail), 15px to the window's end (the "inset" column 18521:22266 and the frame's 5px edge) and to its floor (the "Spacer" 18521:17513). 0 for all three puts the panels back on the edges. | +| `--portal-workspace-inset-end` | `0.9375rem` | ″ | | +| `--portal-workspace-inset-bottom` | `0.9375rem` | ″ | | +| `--portal-status-bar-rest-opacity` | `0.5` | ″ | The status bar ("status bar", rev 11/16: Frame 403 1262:39850) stands in the floor under the frame: 20px chips 9px apart, 12px off the window's floor and 8px under the frame, whose floor gap grows to 40px while the bar is open. Collapsed (1264:40699), its toggle floats 7px inside the frame's end corner. Open, it rests at half ink so the floor stays quiet, and comes to full under the pointer or the keyboard. | +| `--portal-status-bar-height` | `1.25rem` | ″ | | +| `--portal-status-bar-gap` | `0.5625rem` | ″ | | +| `--portal-status-bar-floor` | `0.75rem` | ″ | | +| `--portal-status-bar-open-inset` | `2.5rem` | ″ | | +| `--portal-status-bar-corner` | `0.4375rem` | ″ | | +| `--portal-status-bar-glyph` | `0.8125rem` | ″ | | +| `--portal-welcome-glyph` | `1rem` | ″ | The first-time splash's glyphs (Onboarding 18695:17165, 18695:18477): 16 on a place's row and in its seen tile, 20 on a starter idea. | +| `--portal-idea-glyph` | `1.25rem` | ″ | | +| `--portal-notice-strip-height` | `1.5rem` | ″ | The notice strip (app/shell/butterbar.tsx: the terms) is one 24px row at the window's floor, under the frame; while it shows, the status bar stands on it rather than over it. | +| `--portal-column-page` | `61.25rem` | ″ | The one column every rail page shares (Capabilities 919:9281: 980): Agents, Capabilities, Library, Routines, Messaging, Webhooks and the Spawn tree all centre it in their stage through the page stage contract (portal-pages.css), which is its only reader outside this folder (scripts/check_desktop_design_tokens.py). Figma draws forms and details at 840 (1036:7189); the owner keeps one width so no heading moves between pages. Then the conversation shared by the transcript and the docked composer: both 640 wide, the transcript flush with the composer's edges. Figma draws 440 (chat 16292:16175); the owner keeps the wider column. | +| `--portal-column-conversation` | `40rem` | ″ | | +| `--portal-column-conversation-inset` | `0px` | ″ | | +| `--portal-column-landing` | `40rem` | ″ | The landing's composer before the first message, as wide as a conversation's (16292:14822). | +| `--portal-tool-panel-width` | `26.25rem` | ″ | The developer tool panel's default width (Files, Terminal, Review and Browser share one width, redesign/developer-tool-panel.ts): room for an 80-column terminal beside the conversation. | +| `--page-content-inset` | `1.5rem` | ″ | The least a page's column keeps clear of its stage's sides, when the stage is narrower than the column. `(max-width: 639.98px)`: `1rem`. | +| `--portal-scroll-edge-fade` | `1.5rem` | ″ | How far a sideways scroller's trailing edge fades while more follows (portal-pages.css). | +| `--page-content-max-width` | `calc(var(--portal-column-page) + 2 * var(--page-content-inset))` | ″ | | +| `--portal-scrollbar-size` | `0.5rem` | ″ | The app's scrollbar (styles.css draws every native scroller's at this width): what a scrolling page stage reserves on both sides and gives back from its gutters. | +| `--portal-page-end-space` | `2rem` | ″ | The space a page scroller keeps below its last row, under its bottom fade. | +| `--portal-page-top` | `1.125rem` | ″ | The page header (PageHeader, app/redesign/page-header.tsx), one geometry for every routed page so its H1, description and tab bar sit at the same y on all of them: the column's top (856:2827 y 18), a title block that always reserves the agent header's 68 (877:4166: 56 tile, or H1 44 + 6 + one 13px line), 24 to the tabs and from the tabs to the content (877:4166 gap 24), 32h tabs (877:4200) and the page rhythm of 32 between sections and after a heading with no tabs (1036:7405). `(max-width: 639.98px)`: `1rem`. | +| `--portal-page-title-block` | `4.25rem` | ″ | | +| `--portal-page-header-gap` | `1.5rem` | ″ | | +| `--portal-page-rhythm` | `2rem` | ″ | | +| `--portal-page-tab-height` | `2rem` | ″ | `(hover: none), (pointer: coarse)` on `html[data-hermes-desktop-host='browser'][data-shell='portal']`: `var(--portal-touch-target)`. | +| `--portal-page-tab-inset` | `0.75rem` | ″ | | +| `--portal-panel-title-top` | `1.875rem` | ″ | A page's list panel (Agents, Routines) shares the chat sidebar's and the Settings column's header (Top 16292:15498, 16292:16360): its title 30px in and 30px down on a 36px line, its first control 122px under the panel's top, where New chat and the Settings rows start. | +| `--portal-panel-title-inset` | `1.875rem` | ″ | | +| `--portal-panel-title-line` | `2.25rem` | ″ | | +| `--portal-panel-first-row` | `7.625rem` | ″ | | +| `--portal-settings-column` | `40rem` | ″ | Global Settings ("Prod - Desktop" 06 · Settings/Account, Panel/flexible 16292:16447): a 640px column centred in the stage, its header 104px under the stage's top; the header, section heads and card rows share a 32px text inset; cards pad 16px over and under their rows, rows 12px. | +| `--portal-settings-top` | `6.5rem` | ″ | `(max-width: 1023.98px)`: `var(--portal-page-top)`. | +| `--portal-page-eyebrow-top` | `max(var(--portal-page-top), calc(var(--portal-settings-top) - 1.25rem))` | ″ | A page whose header opens with an eyebrow line (the agent page, 18563:12658) starts that line one eyebrow (a 16px line and its 4px gap) above the Settings top, so its H1 lands where a Settings page's does; below wide it is the page top, as Settings' is. | +| `--portal-settings-inset` | `2rem` | ″ | `(max-width: 639.98px)`: `1rem`. | +| `--portal-settings-card-pad` | `1rem` | ″ | | +| `--portal-settings-row-pad` | `0.75rem` | ″ | | +| `--portal-settings-nav-inset` | `1.875rem` | ″ | The column's panel (Panel 16292:16359): the title on a 30px inset, 30px down, 20px over 40px rows 4px apart; the Agent settings card 20px under them (16292:16428). | +| `--portal-settings-nav-gap` | `0.25rem` | ″ | | +| `--portal-settings-related-gap` | `1.25rem` | ″ | | +| `--portal-settings-link-width` | `17.125rem` | ″ | | +| `--portal-settings-nav-title-line` | `2.25rem` | ″ | Its title is Nous/Identity: 30px on a 36px line (16292:16363). The rows start 122px down: Figma's "// META INFO" caption under the title is placeholder copy and not built, its room is kept. | +| `--portal-settings-nav-head-gap` | `3.5rem` | ″ | | +| `--portal-dialog-action-height` | `2.75rem` | ″ | The actions of a dialog or drawer footer (1038:7792): taller than the page's 36px buttons. | +| `--portal-session-tab-inset` | `1.5625rem` | ″ | The band's title pill starts 25px past the stage's leading edge (tab 16292:15297 at x 425, the stage at 400), after the Back/Forward group. | +| `--portal-band-trail-inset` | `0.8125rem` | ″ | The band's trailing Agent settings ends 15px inside the workspace frame (settings-2 16292:15303): the trailing cluster stands 12px off the window, the frame 10px, so the button steps 13px in. | +| `--portal-row-chrome` | `1.875rem` | ″ | Row heights: 30 chrome buttons (906:19469), 40 panel list rows (1038:7408). `(hover: none), (pointer: coarse)` on `html[data-hermes-desktop-host='browser'][data-shell='portal']`: `var(--portal-touch-target)`. | +| `--portal-row-panel` | `2.5rem` | ″ | `(hover: none), (pointer: coarse)` on `html[data-hermes-desktop-host='browser'][data-shell='portal']`: `var(--portal-touch-target)`. | +| `--page-nav-width` | `var(--portal-panel-width)` | ″ | Names in use before the role names; Phase B moves their readers to the role and deletes them. | +| `--page-panel-inset` | `var(--portal-frame-inset)` | ″ | | +| `--portal-chrome-button-size` | `var(--portal-row-chrome)` | ″ | | + +#### Shape: radii, strokes, shadows (`shape.css`) + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--portal-radius-chip` | `2px` | ″ | Chips, counts, segments, tags (877:4186). | +| `--portal-radius-control` | `3px` | ″ | Buttons, inputs, selects, checkboxes, keycaps, chrome buttons, page-panel rows (1036:7409). | +| `--portal-radius-card` | `4px` | ″ | Cards, tables, banners, menus (1036:7576, 878:6044). | +| `--portal-radius-tile` | `12px` | ″ | Media cards and the collections they sit beside (Library 1163:18113: 12px; its table draws 15, held to the card's step). | +| `--portal-radius-surface` | `6px` | ″ | Chat content (bubble, tool row, code card) and chat-sidebar rows (491:40655, 147:7470). | +| `--portal-radius-floating` | `8px` | ″ | Popovers, dialogs, choice tiles (616:1685). | +| `--portal-radius-panel` | `9px` | ″ | The outer top corner of panels, the stage and the composer (906:19804). | +| `--portal-radius-frame` | `15px` | ″ | The workspace frame: the one card the chat sidebar and the stage (or a page's nav and body) sit in, inset from the window (Content 16292:14463). Global Settings' cards round the same (Card 16292:16456). | +| `--portal-radius-settings-card` | `var(--portal-radius-frame)` | ″ | | +| `--portal-radius-settings-link` | `9px` | ″ | The Settings column's Agent settings card (16292:16428). | +| `--portal-radius-settings-nav-row` | `9px` | ″ | The Settings column's rows and its search tile (18563:12472, 18563:12431). | +| `--portal-radius-settings-search` | `var(--portal-radius-surface)` | ″ | | +| `--portal-shadow-settings-link` | `0 1px 4px var(--portal-raw-shadow-20)` | ″ | | +| `--portal-radius-round` | `999px` | ″ | Switch tracks, swatches, dots. | +| `--portal-focus-ring-width` | `2px` | ″ | The one focus ring: 2px of brand ink as an outline, so it never replaces a control's own stroke shadow. Outset by default; a context whose scroller or overflow would clip an outset ring (sidebar, page nav) sets --portal-focus-ring-offset to the inset value on its container and every control inside follows. | +| `--portal-focus-ring-outset` | `1px` | ″ | | +| `--portal-focus-ring-inset` | `calc(-1 * var(--portal-focus-ring-width))` | ″ | | +| `--portal-focus-ring-offset` | `var(--portal-focus-ring-outset)` | ″ | | +| `--portal-shadow-floating` | `0 8px 24px var(--portal-raw-shadow-50)` | `0 1px 2px var(--portal-raw-shadow-4), 0 8px 24px var(--portal-raw-shadow-8)` | Menus, popovers, dialogs (878:6044): one soft drop shadow. | +| `--portal-shadow-composer` | `none` | ″ | The composer card casts none (msg 16292:15670). | +| `--portal-shadow-workspace` | `0 -4px 30px var(--portal-raw-shadow-20)` | `0 8px 12px var(--portal-raw-shadow-navy-10)` | The workspace frame lifted off the artwork (16292:14463): a soft shadow up and around it. | +| `--portal-shadow-workspace-highlight` | `inset 0 1px 2px var(--portal-raw-highlight-5)` | `none` | ...and its inner highlight along the top (inner shadow, 16292:14463): white .05, 1px down, 2px soft. | +| `--portal-control-radius` | `var(--portal-radius-control)` | ″ | Names in use before the role names; Phase B moves their readers to the role and deletes them. | +| `--portal-menu-radius` | `var(--portal-radius-card)` | ″ | | +| `--portal-panel-radius` | `var(--portal-radius-frame)` | ″ | The panel row's outer corners are the workspace frame's. | +| `--portal-floating-shadow` | `var(--portal-shadow-floating)` | ″ | | + +#### Motion (`motion.css`) + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--portal-motion-fast` | `120ms` | ″ | | +| `--portal-motion-base` | `180ms` | ″ | | +| `--portal-motion-slow` | `240ms` | ″ | | +| `--portal-ease` | `cubic-bezier(0.2, 0.8, 0.2, 1)` | ″ | | + +#### Layers (`layers.css`) + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--portal-layer-dock` | `5` | ″ | The docked composer's own top layer (its spectrum edge over the card). | +| `--portal-layer-stage-overlay` | `20` | ″ | What floats over the transcript inside the stage (the conversation header row). | +| `--portal-layer-sheet-scrim` | `44` | ″ | Sheets below wide (the chat sidebar, a page panel) and their scrim: over the stage and the band, under menus and popovers (z-50), so a row's menu opens over its sheet. The rail joins a compact sheet from outside the page layer (route pages are z-50), so it alone sits just over it. | +| `--portal-layer-sheet` | `45` | ″ | | +| `--portal-layer-sheet-rail` | `51` | ″ | | +| `--portal-layer-status-bar` | `50` | ″ | The status bar stands in the canvas on route pages too (z-50, mounted before it), and under the menus and popovers opened after it. | +| `--portal-layer-spotlight` | `52` | ″ | A splash row's spotlight on the nav (app/discovery/nav-spotlight.tsx): over the rail, the chat sidebar and their sheets, which it points into; it is never hit. | + +#### Bridge (`bridge.css`): portal roles under the names shared components read + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--theme-fill-primary-accent-mix` | `0%` | ″ | Brand marks belong to the shell, not the skin: neutral fills and rows take no accent tint. | +| `--theme-fill-secondary-accent-mix` | `0%` | ″ | | +| `--theme-fill-tertiary-accent-mix` | `0%` | ″ | | +| `--theme-fill-quaternary-accent-mix` | `0%` | ″ | | +| `--theme-fill-quinary-accent-mix` | `0%` | ″ | | +| `--theme-row-hover-accent-mix` | `0%` | ″ | | +| `--theme-row-active-accent-mix` | `0%` | ″ | | +| `--theme-control-hover-accent-mix` | `0%` | ″ | | +| `--theme-control-active-accent-mix` | `0%` | ″ | | +| `--ui-text-primary` | `var(--portal-text-primary)` | ″ | | +| `--ui-text-secondary` | `var(--portal-text-secondary)` | ″ | | +| `--ui-text-tertiary` | `var(--portal-text-tertiary)` | ″ | | +| `--ui-text-quaternary` | `var(--portal-text-quaternary)` | ″ | | +| `--ui-bg-card` | `var(--portal-surface-card)` | ″ | | +| `--ui-stroke-primary` | `var(--portal-stroke-strong)` | ″ | | +| `--ui-stroke-secondary` | `var(--portal-raw-ink-14)` | ″ | Ink 14 in both modes; the field role is 14 / 18 (Phase B). | +| `--ui-stroke-tertiary` | `var(--portal-stroke-hairline)` | ″ | | +| `--ui-stroke-quaternary` | `var(--portal-stroke-hairline)` | ″ | | +| `--sidebar-edge-border` | `var(--portal-stroke-edge)` | ″ | | +| `--ui-sidebar-surface-background` | `var(--portal-sidebar-background)` | ″ | | +| `--ui-chat-surface-background` | `var(--portal-surface-stage)` | ″ | | +| `--ui-editor-surface-background` | `var(--portal-surface-stage)` | ″ | | +| `--radius-scalar` | `0.6` | ″ | Tailwind rounded-* in shared components: the redesign's squarer scale. | +| `--terminal-panel-min-width` | `min(22rem, 40vw)` | ″ | | +| `--global-nav-width` | `var(--portal-rail-reserve)` | ″ | | +| `--page-nav-row-height` | `var(--portal-row-panel)` | ″ | | +| `--composer-width` | `var(--portal-column-conversation)` | ″ | | +| `--dialog-body-padding` | `1.5rem` | ″ | | +| `--dialog-body-gap` | `1.5rem` | ″ | | +| `--titlebar-control-size` | `var(--portal-row-chrome)` | ″ | Figma's 30×30 chrome buttons (r3, 16px glyphs): titlebar, rails, pane headers; breadcrumb spacing 906:19467. | +| `--titlebar-control-height` | `var(--portal-row-chrome)` | ″ | | +| `--titlebar-icon-size` | `1rem` | ″ | | +| `--titlebar-control-gap` | `0.625rem` | ″ | | +| `--ui-green` | `var(--portal-status-online)` | ″ | One status family: shared components' success inks read the redesign's online green. | + +#### Chat sidebar (`sidebar.css`): the Variation 1 variant's own roles + +| Token | Dark | Light | Note | +|---|---|---|---| +| `--sessions-pane-width` | `21.25rem` | ″ | | +| `--sessions-pane-min-width` | `17.5rem` | ″ | Below this the New-chat split and the agent cards start to truncate (sash drags); the sash reaches 40px past the default. | +| `--sessions-pane-max-width` | `23.75rem` | ″ | | +| `--sessions-pane-collapse-width` | `calc(var(--sessions-pane-min-width) - 4.5rem)` | ″ | Dragging the sash this far under the minimum folds the sidebar away (1054:22350), as ⌘B does; a drag that stops short of it rests at the minimum. Classic has no such width, so it never folds. | +| `--portal-sidebar-head-top` | `1.875rem` | ″ | The header (Top 16292:15498): the wordmark and its caption on a 30px inset, 30px under the panel's top edge, the search button 28px from its end edge; 30px over New chat (its own 20 plus the list's 10px top pad). | +| `--portal-sidebar-head-bottom` | `1.875rem` | ″ | | +| `--portal-sidebar-head-start` | `1.875rem` | ″ | | +| `--portal-sidebar-head-end` | `1.75rem` | ″ | | +| `--portal-sidebar-wordmark-size` | `1.875rem` | ″ | | +| `--portal-sidebar-wordmark-line` | `2.25rem` | ″ | | +| `--portal-sidebar-wordmark-tracking` | `-1px` | ″ | | +| `--portal-sidebar-wordmark-gap` | `0.625rem` | ″ | | +| `--portal-sidebar-inset` | `2rem` | ″ | The list (Centre 16292:15509): section captions and row text on a 32px inset; New chat and row fills bleed 12px past it (the 300px New chat in a 340px panel); 16px between the actions and the first section. | +| `--portal-sidebar-bleed` | `0.75rem` | ″ | | +| `--portal-sidebar-gutter` | `calc(var(--portal-sidebar-inset) - var(--portal-sidebar-bleed))` | ″ | | +| `--portal-sidebar-actions-gap` | `1rem` | ″ | | +| `--portal-sidebar-row` | `2rem` | ″ | A caption sits 10px under what precedes it and 16px over its first row's text; rows are 20px of text 16px apart (36 pitch, 04 · Workspace/Agent); an agent's chats are 40px (16292:15602). | +| `--portal-sidebar-pin-row` | `2.25rem` | ″ | | +| `--portal-sidebar-chat-row` | `2.5rem` | ″ | | +| `--portal-sidebar-row-gap` | `0px` | ″ | | +| `--portal-sidebar-section-gap` | `0.5rem` | ″ | | +| `--portal-sidebar-label-top` | `0.625rem` | ″ | | +| `--portal-sidebar-label-bottom` | `0.5rem` | ″ | | +| `--portal-sidebar-dot` | `0.3125rem` | ″ | The 5px leading dot, 12px before the title (16px past its box in Figma's item). | +| `--portal-sidebar-dot-gap` | `0.75rem` | ″ | | +| `--portal-sidebar-caption` | `0.625rem` | ″ | Tags, ages and statuses: Figma's Nous/Uppercase, the mono signal font at 10px, 0.6px tracking. | +| `--portal-sidebar-caption-tracking` | `0.06em` | ″ | | +| `--portal-sidebar-meta-font` | `var(--portal-font-mono)` | ″ | | +| `--portal-sidebar-label-font` | `var(--portal-font-mono)` | ″ | Section captions: Nous/Metadata, the mono signal font in sentence case (16292:15526); 14px where Figma draws 13, as every 13px UI step (type.css › --portal-type-ui-size). | +| `--portal-sidebar-label-size` | `var(--portal-type-ui-size)` | ″ | | +| `--portal-sidebar-label-line` | `1rem` | ″ | | +| `--portal-sidebar-label-glyph` | `1rem` | ″ | | +| `--portal-sidebar-row-weight` | `600` | ″ | Row titles: Nous/Compact SemiBold at 20px line (16292:15538). | +| `--portal-sidebar-row-line` | `1.25rem` | ″ | | +| `--portal-sidebar-hover` | `var(--portal-raw-ink-4)` | ″ | | +| `--portal-sidebar-press` | `color-mix(in srgb, var(--ui-base) 7%, transparent)` | ″ | | +| `--portal-sidebar-row-radius` | `var(--portal-radius-control)` | ″ | Chat rows (1252:38769): the open chat takes light/5, a row under the pointer a 1.5px light/20 rule; ink is full for those, unread chats and the flat rows, the floor for an agent's other chats (Figma's .4 fails AA). | +| `--portal-sidebar-row-ink` | `var(--ui-text-primary)` | ″ | | +| `--portal-sidebar-chat-ink` | `var(--ui-text-quaternary)` | ″ | | +| `--portal-sidebar-row-selected-ink` | `var(--ui-text-primary)` | ″ | | +| `--portal-sidebar-chat-radius` | `var(--portal-radius-surface)` | ″ | | +| `--portal-sidebar-row-selected` | `var(--portal-raw-ink-5)` | ″ | | +| `--portal-sidebar-row-hover-rule` | `var(--portal-raw-ink-20)` | ″ | | +| `--portal-sidebar-row-hover-rule-width` | `1.5px` | ″ | | +| `--portal-sidebar-card` | `var(--portal-raw-ink-5)` | ″ | | +| `--portal-sidebar-action` | `var(--portal-raw-ink-5)` | `var(--portal-raw-ink-2)` | New chat (16292:15511): 40px, radius 3, light/5 (dark/2 on light), 12px sides, 10px gap, a 16px glyph; rimless light/5 keycaps (16292:15520) in the mono font at 11px, 60% ink. The search button (16292:15507) is a 30px square on the same fill. | +| `--portal-sidebar-action-key` | `var(--portal-raw-ink-5)` | ″ | | +| `--portal-sidebar-action-rim` | `var(--portal-raw-ink-10)` | ″ | | +| `--portal-sidebar-action-pad` | `0.75rem` | ″ | | +| `--portal-sidebar-action-gap` | `0.625rem` | ″ | | +| `--portal-sidebar-action-weight` | `500` | ″ | | +| `--portal-sidebar-key-font` | `var(--portal-font-mono)` | ″ | | +| `--portal-sidebar-key-ink` | `var(--ui-text-tertiary)` | ″ | | +| `--portal-sidebar-search-button` | `var(--portal-row-chrome)` | ″ | | +| `--portal-sidebar-machine-fill` | `var(--portal-raw-ink-2)` | ″ | An open machine is one card (set 16292:15581): radius 12, light/2, 5px in from the rows on each side, its header 16px over and under its name; its agents 6px inside it. | +| `--portal-sidebar-machine-radius` | `12px` | ″ | | +| `--portal-sidebar-machine-pad` | `0.3125rem` | ″ | | +| `--portal-sidebar-machine-head` | `3.25rem` | ″ | | +| `--portal-sidebar-agent-inset` | `0.375rem` | ″ | Agent cards (16292:15592): radius 9, 6px leading pad (12 to the name past the 32px tile), 16px trailing, 12px over and under, a soft drop shadow. The open agent is the brand slab, white .10 / black .40 / blue (#2E2EA8); the others white .10 / black .60 / blue .30 (16292:15630). Both carry the CRT texture at 5% colour-dodge. Light draws both as blue .10 on white .80 under a 1px brand rule, the open one solid brand, the others brand .10 (16292:25188, 16292:25226), the texture at 90%. | +| `--portal-sidebar-agent-radius` | `9px` | ″ | | +| `--portal-sidebar-agent-pad-block` | `0.75rem` | ″ | | +| `--portal-sidebar-agent-pad-start` | `0.375rem` | ″ | | +| `--portal-sidebar-agent-pad-end` | `1rem` | ″ | | +| `--portal-sidebar-agent-gap` | `0.75rem` | ″ | | +| `--portal-sidebar-agent-action-gap` | `0.25rem` | ″ | | +| `--portal-sidebar-agent-avatar` | `2rem` | ″ | | +| `--portal-sidebar-agent-avatar-radius` | `var(--portal-radius-surface)` | ″ | | +| `--portal-sidebar-agent-shadow` | `0 1px 4px var(--portal-raw-shadow-20)` | `0 0 transparent` | | +| `--portal-sidebar-agent-fill` | `color-mix( in srgb, var(--portal-raw-pure-white) 10%, color-mix(in srgb, var(--portal-raw-black) 60%, var(--portal-raw-brand-30)) )` | `color-mix( in srgb, var(--portal-raw-blue) 10%, color-mix(in srgb, var(--portal-raw-pure-white) 80%, transparent) )` | | +| `--portal-sidebar-agent-fill-open` | `color-mix( in srgb, var(--portal-raw-pure-white) 10%, color-mix(in srgb, var(--portal-raw-black) 40%, var(--portal-raw-blue)) )` | `var(--portal-sidebar-agent-fill)` | | +| `--portal-sidebar-agent-rule` | `transparent` | `var(--portal-raw-brand-10)` | | +| `--portal-sidebar-agent-rule-open` | `transparent` | `var(--portal-raw-blue)` | | +| `--portal-sidebar-agent-hover` | `var(--portal-raw-ink-4)` | ″ | | +| `--portal-sidebar-agent-texture-opacity` | `0.05` | `0.9` | | +| `--portal-sidebar-agent-subtitle` | `var(--ui-text-quaternary)` | ″ | | +| `--portal-sidebar-agent-subtitle-open` | `var(--ui-text-secondary)` | `var(--ui-text-quaternary)` | On the open agent's brand slab the floor needs .7 to hold 4.5:1. | +| `--portal-sidebar-chats-pad` | `0.375rem` | ″ | An agent's chats (list 1250:37633): 6px over and under, rows as wide as the agent's card, the dot 24px into the row, the title 22px after it, the age 14px from the row's end. | +| `--portal-sidebar-chat-start` | `1.5rem` | ″ | | +| `--portal-sidebar-chat-end` | `0.875rem` | ″ | | +| `--portal-sidebar-chat-dot-gap` | `1.375rem` | ″ | | +| `--portal-sidebar-chat-title` | `calc( var(--portal-sidebar-chat-start) + var(--portal-sidebar-dot) + var(--portal-sidebar-chat-dot-gap) )` | ″ | | +| `--portal-sidebar-dot-ink` | `var(--ui-text-quaternary)` | ″ | A settled row's dot: the row's ink, quieter than its title; the open chat's in full ink. | +| `--portal-sidebar-label` | `var(--ui-text-quaternary)` | ″ | Captions, tags, subtitles and ages take the ladder's floor where Figma's .3-.4 fail AA. | +| `--portal-sidebar-meta` | `var(--ui-text-quaternary)` | ″ | | +| `--portal-sidebar-green` | `var(--portal-status-online)` | ″ | | +| `--portal-sidebar-orange` | `var(--portal-status-pending)` | ″ | | +| `--portal-sidebar-count-fill` | `var(--portal-raw-brand-25)` | `var(--portal-raw-brand-10)` | The Agents count: a brand-tinted pill (147:6260), lighter on light. | +| `--portal-sidebar-count-radius` | `10px` | ″ | | +| `--portal-sidebar-offer-fill` | `var(--portal-sidebar-card)` | ″ | The usage-stats offer (1370:34567): the agent card's light/5, radius and drop on the sidebar's opaque fill, so rows never show through; 16px pads, the text on the list's 32px inset past the lattice art, which lightens in at Figma's .8 (light multiplies it in, inverted, so the streak reads dark on white). | +| `--portal-sidebar-offer-ground` | `var(--portal-sidebar-background)` | ″ | | +| `--portal-sidebar-offer-radius` | `var(--portal-sidebar-agent-radius)` | ″ | | +| `--portal-sidebar-offer-shadow` | `var(--portal-sidebar-agent-shadow)` | ″ | | +| `--portal-sidebar-offer-pad` | `1rem` | ″ | | +| `--portal-sidebar-offer-gap` | `0.75rem` | ″ | | +| `--portal-sidebar-offer-text-gap` | `0.375rem` | ″ | | +| `--portal-sidebar-offer-title-ink` | `var(--ui-text-primary)` | ″ | | +| `--portal-sidebar-offer-body-ink` | `var(--portal-sidebar-meta)` | ″ | | +| `--portal-sidebar-offer-share-ink` | `var(--ui-text-primary)` | ″ | | +| `--portal-sidebar-offer-decline-ink` | `var(--portal-sidebar-meta)` | ″ | | +| `--portal-sidebar-offer-art-blend` | `lighten` | `multiply` | | +| `--portal-sidebar-offer-art-filter` | `none` | `invert(1) hue-rotate(180deg)` | | +| `--portal-sidebar-offer-art-opacity` | `0.8` | ″ | | + + + +### Page header (`app/redesign/page-header.tsx`) + +Every routed page with a title or tabs renders `PageHeader` (Agents and an agent's Overview / +History / Settings, Capabilities, Library, Messaging, Routines, Spawn tree, Webhooks, every global +Settings page), so the H1, its description, the actions and the tab bar sit at one place on all of +them. The geometry is `--portal-page-*` in `tokens/space.css`: the column top 18 (16 on compact), an +H1 row (H1, actions at its end), the description 6 under it spanning the column, an optional leading +tile (the agent avatar) beside both; with tabs the title block always reserves 68 (877:4166), so the +tab bar is at one y whether a page has a description or not, then 24 to the tabs, 32h tabs and 24 to +the content; without tabs the content follows after the page rhythm, 32. `PageTabs` is a WAI-ARIA +tab list (arrows, Home, End; roving focus) whose tabs all take the widest tab's width, and a count +reserves three digits while it loads, so switching tabs or a count arriving never moves a neighbour. +On compact the actions take their own row and the tabs keep their own widths in one row that scrolls sideways when it must (44px on touch). +Two optional slots extend the title block: `eyebrow` (a caption line over the H1, the agent's home +path) and `badge` (a chip beside the H1 that stays out of the heading's accessible name, the agent's +machine). `PageTabs variant="segmented"` (the agent page, 18563:12870) draws the same tab list as one +filled track (control fill, r6, 3px inset, 36 tall) whose selected tab is filled in the brand colour; +roles, roving focus and keys are the underline bar's. +A page that loads in fills its first paint with placeholders shaped like the loaded content +(`SettingsCardSkeleton`: the card's 64px rows and 48px add row), never arbitrary spacers. + +The page's edges are one rule, read from these tokens and the page stage contract: the column's first +row (a breadcrumb, else the H1) starts `--portal-page-top` under the stage's top, never inside that +inset; its sides keep `--page-content-inset` at least (16 on compact); the header ends in its own gap +(24 under tabs, the page rhythm without), which the content under it never adds to; and a page +scroller ends `--portal-page-end-space` above the floor. Global Settings keeps its own frame +(`--portal-settings-*`), and a conversation keeps the chat column. + +### Page hero (`app/redesign/page-hero.tsx`) + +A band of artwork behind the top of a page's stage that fades into the page. Three pages carry one: +the agent page (`tide`, 18563:12658), Account & Plan (`stream`, 18563:12067) and Machines (`veil`, +18563:12326); no other Settings page does. `` takes the art as a variant +(`PageHeroArt`) and renders one decorative, `aria-hidden`, pointer-transparent box. Mount it as a +child of the stage, after any page sidebar panel and before the header; the stage must be its +containing block (`position: relative`: the agent page's `.agent-management`, Settings' +`[data-slot='overlay-main']`, which takes `relative` only while it shows a band). The box sits at the +stage's top from `--page-stage-nav` (0 where the page has none) at Figma's own geometry per art +(`--page-hero-min-width`, the panel width Figma draws it on, and `--page-hero-height`). The band keeps +that height on every stage (scaled in proportion it covered the whole page on a wide window) and a +narrower stage crops it at the far side. On a wider one `stream`, a band across the top, stretches +sideways; `tide` and `veil`, whose light is in the far top corner, stay Figma's size in that corner, +clear of the page's column (`tide` fades its top line in over 6rem where its box starts). Its following siblings become `position: relative` so they paint over it. The page frame +placeholder carries it too (`PageFrame.hero`), so it does not pop in when the page's code lands. + +Each art is two baked images in `src/assets/` (`page-hero--dark.avif`, `-light.avif`) with +Figma's fade already in them, painted with one blend mode and nothing else: dark `screen`s a +navy-on-black image (black is a no-op), light `multiply`s a tinted-on-white one (white is a no-op), so +the band fades into whatever veil the stage paints. No mask, filter, gradient or fixed attachment at +paint time; it sits still while the page scrolls, and scrolling over it measured no cost against the +same page without it. `tide` is baked from the source image and Figma's mask (light: the art +excluded from the panel, then lightened with the brand blue, divided back out of the light ground); +`stream` and `veil` from Figma's own 2x renders of the panel's mask group with the panel's ground +taken back out (inverse screen for dark, a divide for light, the light grain floor lifted), cropped +where the art ends with a 48px fade. Keep each under ~150KB (tide 101/35KB, stream 50/16KB, veil +42/52KB, dark/light). A new art is a new `PageHeroArt` value plus its geometry and two +`--page-hero-art` rules in `page-hero.css`. A control drawn over the band needs a solid fill of its +own: a translucent ink fill vanishes over the art's brightest part (the agent header's overflow +button takes `--portal-surface-elevated`). + +A page whose header opens with an eyebrow line (the agent page) starts its stage at +`--portal-page-eyebrow-top`, one eyebrow above `--portal-settings-top`, so its H1 lands where a +Settings page title does; below wide both are the page top. + +### Routines (`app/routines/`) + +The rail's Routines destination follows Figma "Routines final rev" (1081:29252) and is **the only place a +routine is created or changed**. It lists every agent's routines on this window's machine (the shared +`$cronJobs` snapshot, which the redesign's sidebar sync keeps at every profile). The panel (the shared +page-panel frame: panel at the rail's edge, `--page-nav-width`) holds New routine and the routines +themselves, as Chats lists chats, under NEEDS ATTENTION / SCHEDULED / PAUSED (/ FINISHED, only when a run +limit completed one) with a status dot and the agent's name as a tag; a search appears once the list +outgrows a glance. There is no overview row or table. With nothing selected the stage shows the first +routine in the panel's order (below wide, where the panel is a sheet, it shows the list itself until one +is opened); with no routines it is the empty state with New routine. + +One routine on the stage: the breadcrumb (Routines › agent) at the page top like every page's first row, +the H1 with its status chip, and three actions, each with a tooltip on hover and keyboard focus: Run now +(Run routine while paused; Stop while a run is live), a Pause / Resume icon button and an Edit pencil. +Under it, while the last run went wrong, a danger-tint banner names which run ("Yesterday's run +failed"), its chip, the reason as one plain sentence (the backend's text behind Details) and Retry. One +card holds the instruction (mono, folding past eight lines) beside Frequency, Last ran, Next run and Send +results to, read in the app's own moment words; one column on compact. Run history is When · Duration · +Outcome; outcome chips only where the backend recorded one (never a guessed success); each row's View +(View error for a failed run; a run with no chat says its reason in place) shows on hover, on focus and +always on touch. The history loads a batch of 20 as its end scrolls into view, up to the endpoint's 100. + +**The sheet** (`routine-sheet.tsx`, `components/ui/sheet` from the stage's end, 640 wide, the whole +window on compact; the page's control language via `data-page-surface`) creates and edits. Create: +Agent (only when there is more than one), Start from Blank or Template, and nothing else until one is +picked. Template is the catalog for that agent by category with a search; picking one fills every field +from the job its defaults make (`prefill` on `/api/cron/blueprints`, skills kept). Then Name (optional), +Instruction, Frequency (a frequency "at" a time, read back in words under it once set; none picked at +first), Send results to, and Advanced collapsed (model, missed runs, run limit, remember last run, each +description in its info tooltip). The footer sits on the sheet's opaque fill: Cancel, Create in chat (a +new chat with the agent, its composer seeded), Create routine, and above them "First run: …" once a +frequency is set (`lib/routine-first-run.ts`). A created routine is selected and toasts. Edit is the same +sheet titled Edit "", without Start from, the agent read only with its tooltip, and Delete routine / +Cancel / Save & update routine; Delete swaps the footer for "Delete this routine?" with Keep it (focused) +and Delete. Esc, the scrim and × close it and focus returns to its opener. + +**Delete with Undo** (`routine-held-delete.ts`): a delete is held, not done, while its banner (" +deleted." with Undo and ×, the stage's first row above the breadcrumb) is up. The routine is paused on its +owner and hidden, and the list lands on the next routine. Undo resumes it only if it was on; ×, deleting +another routine, leaving Routines or closing the window make the delete final. The hold is written down +first, so a window that closes or crashes mid-hold is finished on the next launch; Undo drops that note +before resuming, and a delete that fails shows the routine again, paused, never hidden. + +An agent's Settings › Routines and its Overview's Routines are read only: each routine opens on the Routines +page, and New routine starts one there for that agent. A chat's items pane lists the routines of the chat's +agent first (a Routines section and tab; rev 11/16, 1264:40927), each with its schedule in words and an +error dot while it needs attention, and opens one on the Routines page. The chat list carries no routines; +runs never join Chats. The sidebar's scheduled-jobs section and the statusbar's Cron item are classic +only, and classic keeps `CronView`. + +### Discovery: splashes and the notifications tray (`app/discovery/`) + +Onboarding and discovery (Figma "Hermes web app onboarding and discovery", Phase 1) live in the +redesign only. A **splash** fills the chat area, never the window: it is the workspace pane's cover +(`KeptChatRoutes`' `cover`), so whatever it covers is inert and gets its focus back, while the rail +and the chat sidebar stay live and any click in them closes it (the click still goes where it was +going); it takes focus when opened from the tray and closes on Escape (`useSplashFrame`). Every +splash is the stage itself in the welcome's language: the launch's artwork under the stage veil, +edge to edge, and the 640 column with an eyebrow, the display title, one card of rows and the way +out. The rename splash ("Hermes got a new look", Figma E5 18677:29814, `SplashSurface`) is the +first: one row per rename in the alias table ("Sessions → Chats"), its line and the person's own +count; a row a pointer, focus or tap reaches rings its real place in the nav with a dashed elbow +(`NavSpotlight`, `--portal-layer-spotlight`), following that place every frame and drawing nothing +when it is not on screen; nothing is lit at rest. Escape, its button or a nav click marks it seen +through the one guidance seam (`store/guidance-ledger.ts`). + +The **notifications tray** ("Notifications & updates", Figma E6 18677:29931) is the rail's bell +(above the account and status controls) opening a rail popover; Figma draws a sheet, the redesign +keeps the popover. Its items are a typed table (`TRAY_ITEMS` in `tray-items.tsx`): each publishes a +state atom (`null` = not listed; `news` = a token for what it announces) and a row, usually the +shared `TrayCard` (glyph, title, line, the action with its chevron), all in one welcome card. Under +the card: Open introduction (while the rename splash can be reopened), Mark all read (while a row +says New) and the footnote. The bell carries a brand-ink dot while any listed item has news not yet +seen; opening the tray sees it, and the rows that were new say so until it closes or Mark all read. +Community posts from the frames are not built. + +The **usage-stats offer** (Figma 1335:32952, 1365:34379) is the redesign's place for classic's +composer strip: a card at the foot of the chat sidebar (`usage-stats-card.tsx`, its own slot under +the list on the sidebar's opaque fill, so no row hides under it or shows through), shown wherever the +sidebar is and nowhere else, waiting while the free-tier notice is up. Share with Nous and No thanks +save the answer through the same path as the strip; Details opens "Help improve Hermes", a short +dialog (`usage-stats-dialog.tsx`, painted by the classic consent host, so every rule about when to +ask holds) whose Share stats answers and whose Not now, × and Escape only close it; the re-ask reason +shows there. The card's × answers nothing: it moves the question into the tray (`deferred` in the +guidance ledger, so it survives reloads) until it is answered or the tray item's × clears it +(`store/usage-stats-offer.ts`). The copy promises a random ID, never anonymity. + +A Webapp tab that was open when a newer build was deployed (E4 18677:29704) says so in the chat, +over the composer in the developer-view offer's place (`update-ready-notice.tsx`: the info line, +Refresh now and Later), and in the tray, and never reloads under the person: the new build loads at +the next new chat while nothing is running, on the next visit, or from "Refresh now" +(`store/new-version.ts`, `lib/deployed-build.ts`). Later puts the chat's notice away for the page; +the tray keeps it. + +The desktop updater's dialog (`updates-overlay.tsx`, shared with classic) takes the welcome's +language in the redesign only while it pitches or installs an update (E2 18677:29477, E3 +18677:29591, `updates-portal-views.tsx`): the column's width, the title and line, the update's real +notes (or changelog) as numbered rows, Update now and Maybe later, the release notes link; while +installing, each updater stage reached as a row, done or under way, over the real progress. Every +other view of the dialog is classic's. + +The **first-time splash** ("Welcome to Hermes", Figma "Prod - Desktop" › Onboarding 18695:17147) is +the second splash, for a new install (the verdict the rename splash records as `not_applicable`). It +is not a card on the stage but the stage itself (its veil over the art, edge to edge). The navigation +stays as it is while the splash is up, as under the rename splash: a sidebar that came and went with +a row's hover moved the whole page. Step 1 is a 640 column: eyebrow, display +title, one line, then Chats, Agents, Routines and Library as rows in one card (`--portal-welcome-card`). +The row a pointer, focus or tap last reached is the place. While the pointer or focus is on the rows, +that row says its example in place of its line, its place is ringed where it sits in the navigation +with a dashed line from the row (`nav-spotlight.tsx`, the rename splash's; the open destination's +selection stands down in the rail while a splash is up) and everything else fades to +`--portal-backdrop-opacity`. The ring and line are placed in the spotlight layer's own pixels, so +they hold at any UI scale. Every row reached carries +the seen check (the band's chrome tile) for the rest of the showing. "Make it yours" leads to step 2: the accent's eight swatches and Light / Dark in +one card, "Make it beautiful" (the artworks the mode draws, as cards that run the stage's width and fade +off both sides), and the way in: Sign up and Look around where sign up is required, one button +elsewhere. A quiet Back on the eyebrow's line returns to step 1. Every control is a native button or +radio group; there is no ×: a nav click, Escape or the step's buttons close it. + +The colours are the redesign's **accent** (`store/portal-accent.ts`, ``): the +brand gesture's fill, the ink on it, its ink and its tints (`--portal-raw-accent*`, `--portal-raw-brand-*`) +take the pick; the bright ones (yellow, green, cyan) carry the canvas navy as their on-brand ink and a +darkened light-mode ink, so no component special-cases them. The navy family (canvas, veils, panels, +the composer card, the sidebar's agent slabs) and the skin's own primary (`--dt-primary`, which a +shared component's default button outside pages and dialogs still paints) stay as they are. Every +accent keeps the blue's AA duties in both modes (`tokens/portal-accent-contrast.test.ts`). + +A newcomer's empty chat is headed like the splash ("Welcome to Hermes", Figma 18695:18388) and lays four +fixed starter ideas, each with its glyph, in two rows under the composer, then Hide +(`app/discovery/starter-ideas.tsx`); after two chats in which a task finished, or Hide, they give way to +Show ideas, and the composer asks for a task instead of rotating starters. Where the visitor must sign +up before anything runs (`store/visitor-access.ts`; no page served today asks it), the composer's model +row is "Sign up to start", the chat sidebar's foot is "Create an Account" (before the usage-stats card, +which waits for it), and what they send is held, not sent: the chat shows their message and Hermes' +local answer with the way to sign up (`held-exchange.tsx`, 18695:18570), never as a transcript, and the +held message runs first once they are signed in. + +As a newcomer settles in (Figma Onboarding 03, `$landingMoment` in `store/starter-ideas.ts`), the +heading follows: "Welcome back." after a first finished task (C4), its line asking what to work on +once the ideas are put away (C5: two finished chats, or Hide ideas, which stays until Show ideas), +and "Good to see you again." when their newest chat has been still for 30 days (C8: Continue a recent +chat and Show ideas in place of the chips; the next finished task settles it). At two finished chats +"How's Hermes going so far?" (`check-in.tsx`, C7) takes the heading's place until it is answered or +dismissed; Dismiss puts it in the tray. Someone in Simple whose chat produced a code artifact is +offered the developer view (`developer-view-offer.tsx`, C6: Advanced, previewed while its row is +hovered, focused or tapped through the interface mode's in-memory override, stored only by Turn on) +once. Section 03 has its own 36px buttons (`.discovery-landing-action`). + +A sign up that comes back without signing the visitor in (`?hermes_sign_in=failed`, read once) opens +**"Let's try signing in again"** (`sign-in-recovery.tsx`, 18732:33066 / 18695:19224) over the chat, the +first splash in line: the welcome splash's stage, column and card, with one row per step and a status +badge (`--portal-badge-*`: Your account UNVERIFIED, Your request SAVED only while a message is held, +Opening Hermes WAITING). Try again, Use another email and "Request a new one." all start sign up again +(the hand-off takes no hint for either); a nav click or Escape puts it away, back to the ordinary +signed-out app. It is the one place a failed sign in is told: the held answer and the tray's card stay +as they were. There is no "verified" screen: nothing tells the app that a visitor just came back signed +in while it is still opening. + +### The chat sidebar is a variant + +The chat sidebar (`app/chat/sidebar/portal/**`) is matched to "Prod - Desktop" (Panel 16292:15497). +Where it draws a state differently from the page language (row hover ink 4, the open chat marked by ink +alone, mono sentence-case captions, the r10 brand count pill, rimless mono keycaps, agent cards, its +inset focus rings), the sidebar keeps those values as its own named roles in `tokens/sidebar.css` +(`--portal-sidebar-*`) instead of the page roles. That is deliberate, not drift: change the sidebar there, and never point +page components at `--portal-sidebar-*`. + +### Still to unify + +Phase B unified cards (U1: 2% fill, 5% hairline, r4), page rhythm (U2: 32), page tabs (U3), in-card +dividers (U4: ink 3, light ink 5), row hover outside the sidebar (U5), danger (U10), display-lg (U11), +the text ladder outside the sidebar (U12), dialogs and drawers (U13: 24 padding and gap, 44px footer +actions), page focus rings (U16), brand selection (U17: 25% / light 12%) and control and floating +states (U18). What remains, one reviewable change per row: + +| # | Role | Today: value · where | Winner | +|---|---|---|---| +| U6 | Neutral selection | the pane tab-strip's active tab (ink 5, no stroke) | ink 5 + 0.5px ink 5 stroke (1036:7409) | +| U7 | Caption | new-session picker label 0.08em/500/brand ink; gateway menu `tracking-[0.08em]` | 10/1.4, `--portal-tracking-caption` 0.06em, 400, tertiary (1036:7408) | +| U8 | Chip and Count | new-session tag 0.06em/500/r3; RUNNING/EMPTY chip line boxes | Chip h14 9/0.04em r2, Count h14 10/500 r2 (1036:7318, 856:3474) | +| U9 | Keycap | New agent row keycaps (0.5px ink 5 rim, ink 5 fill, `portal-pages.css`) vs `[data-slot=kbd]` field ink 4 + 1px control stroke | ink 4 fill, 1px ink 14, r3, 11px (1038:7401) | +| U14 | Small text in mixed TSX | 14 sizes between 0.6 and 0.82rem and 0.07–0.2em tracking in the classic/portal branches | caption / micro / meta / ui sizes | +| U15 | Radius by role | `0.5rem` / `0.375rem` (agent overview menu and items), Tailwind `rounded-*` in redesign TSX (G2 warnings) | the seven `--portal-radius-*` roles | +| U19 | Units | px font sizes, line heights and radii in `agent-settings.css`, `history.css`, capabilities `page.css` (the guard's baseline lists them) | rem through the type tokens | +| U20 | Spacing drift | 3/5/7/9/11/13/15/17/22/23px insets (catalog, history, settings editor) | the 4px scale; Figma optical offsets keep `/* token-exempt */` | +| U21 | Status and brand badges | `Badge` success / warn paint Tailwind emerald / amber; default / solid paint the skin's `--dt-primary` (`components/ui/badge.tsx`) | `--portal-status-online` / `--portal-status-pending` and the brand roles in `color.css` | +| U22 | Alert | the classic card (`rounded-lg`, `bg-card`, `shadow-xs`); warning and success look the same (`components/ui/alert.tsx`) | the redesign card (ink 2 fill, ink 5 hairline, r4) with one status ink per variant | +| U23 | Field sizes and invalid | Input xs / sm / default render at one height in the redesign; `aria-invalid` has no visible treatment (`components/ui/control.ts`) | one height per size; a danger stroke on an invalid field | + +### Rules of thumb + +- A new colour must be a role in `color.css`. A new alpha is not allowed: pick + the nearest ink step. +- A new size must be a type role. If none fits, the design or the language is + wrong: change the language (here and in `tokens/`) first. +- Cards never nest. A card inside a disclosure body loses its fill and stroke. +- Blue means action or selection, never decoration. +- Status colour lives in dots, chips and one status label — never in row fills + (except the chat sidebar's attention rows). +- A Figma one-off (a 23px optical offset) is encoded in the component with a + `/* token-exempt: why */` comment, not as a token. +- Redesign-only TSX uses token-backed classes (the `ds-` utilities: `text-ds-caption`, + `rounded-ds-card`, `bg-ds-card`, `text-ds-text-3`, from `tokens/tailwind.css`), not arbitrary + visual values such as a literal rem size, a px radius or an inline colour mix: the + `hermes-desktop/no-portal-arbitrary` lint warns on them. + +### How to change a token + +1. Edit the one line in `src/app/redesign/tokens/.css` (dark in the base + block, light in the `:not(.dark)` block). +2. Regenerate the tables: `python scripts/check_desktop_design_tokens.py --write-docs` + (`scripts/check` fails while they are stale). +3. Look at it in dark, light and Glass, on the states the role appears in. +4. If the change unifies a "Still to unify" row, delete the legacy token and its row, and + lower the guard's baseline (`--write-baseline`) in the same change. + +`scripts/check` runs `check_desktop_design_tokens.py`: outside `tokens/`, redesign +CSS that restates a colour, an ink mix, a radius, a font size, tracking, a px +line height, a duration or a z-index fails once a file's count rises above its +ratchet (`scripts/desktop_design_tokens_baseline.json`, which may only go down), +and a `var(--portal-…)` naming an undefined token always fails. + ## Surfaces & elevation Floating panels (base `Dialog`, route overlays, boot/install/update surfaces, @@ -147,16 +1519,16 @@ renderer and Electron's first window paint. ## Stroke & color tokens -| Token | Use | -| --- | --- | -| `--ui-stroke-primary…quaternary` | hairlines, in descending strength | -| `--ui-stroke-tertiary` | the default in-panel divider / list hairline — and every bordered surface in the transcript | -| `--stroke-nous` | the overlay hairline (pairs with `shadow-nous`) | -| `--ui-text-primary / -secondary / -tertiary` | text hierarchy | -| `--ui-bg-quaternary` | soft control fill (secondary button) | -| `--ui-widget-surface-background` | fill for inline chat widgets (`WIDGET_SHELL_CLASS`) | -| `--chrome-action-hover` | hover fill for quiet controls | -| `--theme-primary`, `--ui-accent` | brand/accent | +| Token | Use | +| -------------------------------------------- | ------------------------------------------------------------------------------------------- | +| `--ui-stroke-primary…quaternary` | hairlines, in descending strength | +| `--ui-stroke-tertiary` | the default in-panel divider / list hairline — and every bordered surface in the transcript | +| `--stroke-nous` | the overlay hairline (pairs with `shadow-nous`) | +| `--ui-text-primary / -secondary / -tertiary` | text hierarchy | +| `--ui-bg-quaternary` | soft control fill (secondary button) | +| `--ui-widget-surface-background` | fill for inline chat widgets (`WIDGET_SHELL_CLASS`) | +| `--chrome-action-hover` | hover fill for quiet controls | +| `--theme-primary`, `--ui-accent` | brand/accent | Never hardcode `border-gray-*`, `bg-white`, `text-black`, etc. The two tiles in `BrandMark` (white in light mode, `#0d1117` in dark) are the sanctioned literals @@ -225,6 +1597,7 @@ context-dependent (e.g. "Show" / "Hide"). Never hardcode combos; always use `useKeybindHint` or `TipKeybindLabel`. Notes: + - Text buttons are square (no radius) and sized by padding + line-height (no fixed heights). Only icon buttons carry the shared 4px radius. - SVGs inherit `size-3.5` (`size-3` at `xs`). Don't re-set icon size. @@ -376,6 +1749,10 @@ inline-edit composers. It does not resize the sidebar, settings, toolbars, media, or pane geometry. Conversation size and line-height tokens are derived inside the transcript/editor from their root base tokens; do not multiply the global tokens or nest CSS zoom. +In the redesign the working row under a running turn ("Working on …", "waiting for the first stream +chunk") is regular-weight text in full ink, quieted as a whole by `--portal-text-quiet-opacity` (the +ladder's floor, 50% dark / 64% light), never a pale ink under a second fade; its timer takes the brand +ink beside the brand pixel. ## Chat, tools & boot surfaces @@ -392,7 +1769,7 @@ from their root base tokens; do not multiply the global tokens or nest CSS zoom. - **Inline widgets** — a tool result that renders as a panel the user reads or acts on (clarify, artifact card) wears `WIDGET_SHELL_CLASS` (`src/components/chat/widget-shell.ts`): shared radius, the - `--ui-widget-surface-background` fill, no border. Its actions sit *outside* + `--ui-widget-surface-background` fill, no border. Its actions sit _outside_ the panel, below it. Don't give one widget its own radius or fill. - Bordered surfaces in the transcript (tables, fences, callouts, attachments) use `--ui-stroke-tertiary`. Not `border-border` — that's the app-wide @@ -483,7 +1860,7 @@ from their root base tokens; do not multiply the global tokens or nest CSS zoom. (toasts, tooltips, command surfaces) and `--z-over-modal-content`, `--z-switcher-backdrop` / `--z-switcher`, then the boot chain `--z-connecting` → `--z-onboarding` → `--z-setup` → `--z-crash`. Plain - `z-10`/`z-20` are still right for stacking *within* one component. + `z-10`/`z-20` are still right for stacking _within_ one component. ## Iconography & brand @@ -496,14 +1873,24 @@ from their root base tokens; do not multiply the global tokens or nest CSS zoom. - Pick the vocabulary by semantic context and reuse the existing icon for an action. Do not introduce a third icon set or mix styles within one control group. +- **The redesign (portal shell) draws every one of those glyphs from + Pixelarticons**, the brand set the Figma frames use. The swap is central: + `src/lib/pixel-icons.ts` maps each Tabler alias and codicon name to its pixel + twin (the Figma frame's icon where one draws the control), `src/lib/icons.ts` + aliases and `Codicon` pick the set from the shell, and classic is untouched. + A new alias or codicon needs a mapping entry (`KEEP_CLASSIC` for a brand or + language mark); the type and `pixel-icons.test.tsx` fail without one. A role + that the redesign draws differently from a shared glyph gets its own alias + (`Gateway`: the classic globe, the redesign's `server`). Directional glyphs + mirror in RTL from `RTL_MIRRORED`, not per component. - **`BrandMark`** (`src/components/brand-mark.tsx`) is the brand glyph — the `nous-girl` mark on a fixed tile, theme-aware: black girl on white in light mode, white girl on the `#0d1117` dark tile in dark mode (keyed off `renderedMode` so bright surfaces in dark skins stay on the light mark). The marks are generated by `scripts/generate_icons.py` from the girl SVGs - + squircle backgrounds (`assets/nous-girl-*.svg` × `assets/backgrounds/`). - It replaced scattered Sparkles glyphs in updates / onboarding / about. Use it - for hero/brand moments; don't reintroduce decorative star/sparkle icons. + - squircle backgrounds (`assets/nous-girl-*.svg` × `assets/backgrounds/`). + It replaced scattered Sparkles glyphs in updates / onboarding / about. Use it + for hero/brand moments; don't reintroduce decorative star/sparkle icons. ## Motion @@ -515,11 +1902,11 @@ from their root base tokens; do not multiply the global tokens or nest CSS zoom. `prefers-reduced-motion` for anything beyond a fade. - Hover paints instantly; only the return eases. Put the transition on the resting state and drop it while hovered (`transition-colors duration-100 - hover:transition-none`, or the CSS equivalent on `:hover`). A group that +hover:transition-none`, or the CSS equivalent on `:hover`). A group that dims siblings goes instant too. Exceptions are named, e.g. the catalog card's arc border fades in and out. - Choreographed exits (e.g. onboarding's "matrix" fade-down) stagger per-element - then settle the surface — the outer container's fade is *delayed* so it + then settle the surface — the outer container's fade is _delayed_ so it doesn't swallow the inner animation. Don't let a global fade race the detail. - Motion follows state; it never delays state. Selection, drag targets, cancel, and pressed feedback paint in the current frame. @@ -591,6 +1978,10 @@ long transcript or a busy terminal. - **Sparse locales** (`ar`, `ru`) override the English base through `defineLocale()`. Large catalogs are split by topic: the Arabic source lives in `src/i18n/ar_.ts`, recomposed by `src/i18n/ar.ts`. +- **Shell wording** — the base catalog is classic's wording. Wording that differs only + in the redesigned shell goes in `src/i18n/redesign/.ts` for every locale + (see Terminology above), never in the base catalog and never as a `portal ? a : b` + string at the call site. ## State (TypeScript) @@ -654,3 +2045,6 @@ The detailed state contract lives in the scoped - [ ] `cursor-pointer`, focus ring, and `Esc`-to-close behave? - [ ] Touched a primitive, token, or variant? Its named-contract entry in this file is updated in the same change. +- [ ] A new file in `src/components/ui/`? It has an entry in the design system + page's registry (`src/app/redesign/design-system/registry/`), or a line in + its `NOT_SHOWN` table saying why not. diff --git a/apps/desktop/ENGINEERING.md b/apps/desktop/ENGINEERING.md index 3b40e74de679d..83fa3a689537c 100644 --- a/apps/desktop/ENGINEERING.md +++ b/apps/desktop/ENGINEERING.md @@ -25,6 +25,17 @@ rename via `migrateTilesForProfile(old, new)` (`store/session-states.ts`), the rename sibling of `dropTilesForProfile`. Add any new profile-keyed localStorage family to BOTH, or a rename leaves it pointing at a backend that no longer exists ("Couldn't open this session" on every restore). +Explicitly scoped local renames follow that same migration path; supplying a +scope object does not make a local agent remote. +The settings rename continuation follows the visible owner route, not a +history-entry key: state-only replacements must not strand the old name. +Leaving that destination or unmounting still cancels the continuation. + +Deletion is scoped by machine and profile as well as stored ID. A copied ID +on another owner must not clear the active conversation's runtime, queues, +tiles, or cached history, including when navigation changes during the request. +Failed deletions restore rows to their canonical sidebar slice without +overwriting newer rows or restoring messaging/schedule chats into recents. Tile rotation stays coordinated by `store/session-states.ts`; its owner-profile projection, owner comparisons and placement-preserving merge live in `store/session-tile-identity.ts`. Matching diff --git a/apps/desktop/docs/images/classic-capabilities.png b/apps/desktop/docs/images/classic-capabilities.png new file mode 100644 index 0000000000000..3bd104fd620ae Binary files /dev/null and b/apps/desktop/docs/images/classic-capabilities.png differ diff --git a/apps/desktop/docs/images/classic-conversation.png b/apps/desktop/docs/images/classic-conversation.png new file mode 100644 index 0000000000000..ce17cd9408397 Binary files /dev/null and b/apps/desktop/docs/images/classic-conversation.png differ diff --git a/apps/desktop/docs/images/classic-landing.png b/apps/desktop/docs/images/classic-landing.png new file mode 100644 index 0000000000000..add66ef2e262b Binary files /dev/null and b/apps/desktop/docs/images/classic-landing.png differ diff --git a/apps/desktop/docs/images/classic-settings.png b/apps/desktop/docs/images/classic-settings.png new file mode 100644 index 0000000000000..3b4339fecaa1e Binary files /dev/null and b/apps/desktop/docs/images/classic-settings.png differ diff --git a/apps/desktop/docs/images/design-system-components.png b/apps/desktop/docs/images/design-system-components.png new file mode 100644 index 0000000000000..8a2252c02a6c8 Binary files /dev/null and b/apps/desktop/docs/images/design-system-components.png differ diff --git a/apps/desktop/docs/images/design-system-light.png b/apps/desktop/docs/images/design-system-light.png new file mode 100644 index 0000000000000..63e8b16eabfa8 Binary files /dev/null and b/apps/desktop/docs/images/design-system-light.png differ diff --git a/apps/desktop/docs/images/design-system-phone.png b/apps/desktop/docs/images/design-system-phone.png new file mode 100644 index 0000000000000..0d0b8181488d5 Binary files /dev/null and b/apps/desktop/docs/images/design-system-phone.png differ diff --git a/apps/desktop/docs/images/design-system-tokens.png b/apps/desktop/docs/images/design-system-tokens.png new file mode 100644 index 0000000000000..b1d4dba4de157 Binary files /dev/null and b/apps/desktop/docs/images/design-system-tokens.png differ diff --git a/apps/desktop/docs/images/design-system-top.png b/apps/desktop/docs/images/design-system-top.png new file mode 100644 index 0000000000000..38c15bc7ab17c Binary files /dev/null and b/apps/desktop/docs/images/design-system-top.png differ diff --git a/apps/desktop/docs/images/design-system-violet.png b/apps/desktop/docs/images/design-system-violet.png new file mode 100644 index 0000000000000..14f033d998d28 Binary files /dev/null and b/apps/desktop/docs/images/design-system-violet.png differ diff --git a/apps/desktop/docs/images/onboarding-accent-green.png b/apps/desktop/docs/images/onboarding-accent-green.png new file mode 100644 index 0000000000000..baad322a0c577 Binary files /dev/null and b/apps/desktop/docs/images/onboarding-accent-green.png differ diff --git a/apps/desktop/docs/images/onboarding-first-time-splash.png b/apps/desktop/docs/images/onboarding-first-time-splash.png new file mode 100644 index 0000000000000..75f6d683aa460 Binary files /dev/null and b/apps/desktop/docs/images/onboarding-first-time-splash.png differ diff --git a/apps/desktop/docs/images/onboarding-held-message.png b/apps/desktop/docs/images/onboarding-held-message.png new file mode 100644 index 0000000000000..58b7996b56b95 Binary files /dev/null and b/apps/desktop/docs/images/onboarding-held-message.png differ diff --git a/apps/desktop/docs/images/onboarding-new-version.png b/apps/desktop/docs/images/onboarding-new-version.png new file mode 100644 index 0000000000000..0c9dddc91da54 Binary files /dev/null and b/apps/desktop/docs/images/onboarding-new-version.png differ diff --git a/apps/desktop/docs/images/onboarding-phone.png b/apps/desktop/docs/images/onboarding-phone.png new file mode 100644 index 0000000000000..66ca5b1846f30 Binary files /dev/null and b/apps/desktop/docs/images/onboarding-phone.png differ diff --git a/apps/desktop/docs/images/onboarding-rename-splash.png b/apps/desktop/docs/images/onboarding-rename-splash.png new file mode 100644 index 0000000000000..714bab094c827 Binary files /dev/null and b/apps/desktop/docs/images/onboarding-rename-splash.png differ diff --git a/apps/desktop/docs/images/onboarding-starter-ideas.png b/apps/desktop/docs/images/onboarding-starter-ideas.png new file mode 100644 index 0000000000000..9187676cb7b8b Binary files /dev/null and b/apps/desktop/docs/images/onboarding-starter-ideas.png differ diff --git a/apps/desktop/docs/images/onboarding-tray.png b/apps/desktop/docs/images/onboarding-tray.png new file mode 100644 index 0000000000000..b382eba041535 Binary files /dev/null and b/apps/desktop/docs/images/onboarding-tray.png differ diff --git a/apps/desktop/docs/images/redesign-agent-settings.png b/apps/desktop/docs/images/redesign-agent-settings.png new file mode 100644 index 0000000000000..0fec96d32811a Binary files /dev/null and b/apps/desktop/docs/images/redesign-agent-settings.png differ diff --git a/apps/desktop/docs/images/redesign-agents.png b/apps/desktop/docs/images/redesign-agents.png new file mode 100644 index 0000000000000..ad38106f5dfeb Binary files /dev/null and b/apps/desktop/docs/images/redesign-agents.png differ diff --git a/apps/desktop/docs/images/redesign-capabilities.png b/apps/desktop/docs/images/redesign-capabilities.png new file mode 100644 index 0000000000000..475ec4be5001c Binary files /dev/null and b/apps/desktop/docs/images/redesign-capabilities.png differ diff --git a/apps/desktop/docs/images/redesign-conversation.png b/apps/desktop/docs/images/redesign-conversation.png new file mode 100644 index 0000000000000..b7638ec50a590 Binary files /dev/null and b/apps/desktop/docs/images/redesign-conversation.png differ diff --git a/apps/desktop/docs/images/redesign-landing.png b/apps/desktop/docs/images/redesign-landing.png new file mode 100644 index 0000000000000..30914d3fb58a6 Binary files /dev/null and b/apps/desktop/docs/images/redesign-landing.png differ diff --git a/apps/desktop/docs/images/redesign-light.png b/apps/desktop/docs/images/redesign-light.png new file mode 100644 index 0000000000000..8435ce5f4847a Binary files /dev/null and b/apps/desktop/docs/images/redesign-light.png differ diff --git a/apps/desktop/docs/images/redesign-phone.png b/apps/desktop/docs/images/redesign-phone.png new file mode 100644 index 0000000000000..4b53c91c91bf3 Binary files /dev/null and b/apps/desktop/docs/images/redesign-phone.png differ diff --git a/apps/desktop/docs/images/redesign-routine.png b/apps/desktop/docs/images/redesign-routine.png new file mode 100644 index 0000000000000..7eefda61eb96c Binary files /dev/null and b/apps/desktop/docs/images/redesign-routine.png differ diff --git a/apps/desktop/docs/images/redesign-routines.png b/apps/desktop/docs/images/redesign-routines.png new file mode 100644 index 0000000000000..9184bc31edc1c Binary files /dev/null and b/apps/desktop/docs/images/redesign-routines.png differ diff --git a/apps/desktop/docs/images/redesign-settings.png b/apps/desktop/docs/images/redesign-settings.png new file mode 100644 index 0000000000000..bada7fc328769 Binary files /dev/null and b/apps/desktop/docs/images/redesign-settings.png differ diff --git a/apps/desktop/e2e/core/harness.ts b/apps/desktop/e2e/core/harness.ts index 026b225cab2d8..fc2b3a58eaa4f 100644 --- a/apps/desktop/e2e/core/harness.ts +++ b/apps/desktop/e2e/core/harness.ts @@ -248,9 +248,16 @@ export async function launchCoreApp(env: Record): Promise<{ app: throw new Error("Desktop dist not built: run 'pnpm run build' in apps/desktop first") } + // Select Ozone before launch; an entrypoint relaunch breaks Playwright's process attachment. + const args = [DESKTOP_ROOT, '--disable-gpu', '--no-sandbox'] + + if (process.platform === 'linux' && (env.WAYLAND_DISPLAY || env.XDG_SESSION_TYPE === 'wayland')) { + args.push(`--ozone-platform=${env.ELECTRON_OZONE_PLATFORM_HINT === 'x11' ? 'x11' : 'wayland'}`) + } + const app = await _electron.launch({ executablePath: resolveElectronBinary([DESKTOP_ROOT, REPO_ROOT]), - args: [DESKTOP_ROOT, '--disable-gpu', '--no-sandbox'], + args, env, cwd: DESKTOP_ROOT }) diff --git a/apps/desktop/e2e/core/onboarding-first-chat.spec.ts b/apps/desktop/e2e/core/onboarding-first-chat.spec.ts index 4791c7eb8cf59..85db54ff28272 100644 --- a/apps/desktop/e2e/core/onboarding-first-chat.spec.ts +++ b/apps/desktop/e2e/core/onboarding-first-chat.spec.ts @@ -1,10 +1,11 @@ /** * C2 core: onboarding completion, then the first chat. * - * Fresh sandbox, NO provider configured: the real first-run onboarding shows. - * The user picks the local / custom endpoint path and enters the fake - * provider's URL; the real backend probes it (/v1/models), persists the - * assignment, and the overlay closes. Then the first chat must obey the same + * Fresh sandbox, NO provider configured: the real first-run onboarding shows, + * once in the classic shell (provider overlay) and once in the redesign + * (sessionless setup guide). The user picks the local / custom endpoint path + * and enters the fake provider's URL; the real backend probes it (/v1/models), + * persists the assignment, and the onboarding surface closes. Then the first chat must obey the same * transcript oracle as everything else. A smoke test for onboarding followed * by a first chat; the #120005 double-paint needs a non-default profile and is * guarded by transcript-integrity.spec.ts. @@ -19,7 +20,9 @@ import * as fs from 'node:fs' import * as path from 'node:path' -import { expect, test } from '@playwright/test' +import { type ElectronApplication, expect, type Page, test } from '@playwright/test' + +import { CLASSIC_SHELL, seedUiPreferences } from '../ui-preferences-seed' import { coreAppEnv, @@ -28,10 +31,11 @@ import { launchCoreApp, recordWebSockets, send, - waitForInteractive + waitForInteractive, + type WsRecorder } from './harness' import { assertTranscriptOracle, installDuplicateSampler } from './oracle' -import { startScriptedProvider } from './provider' +import { type ScriptedProvider, startScriptedProvider } from './provider' const nonce = Math.random() .toString(36) @@ -42,49 +46,33 @@ const nonce = Math.random() const U = (n: number) => `U${n}-${nonce}` const A = (n: number) => `A${n}-${nonce}` -test('onboarding (custom endpoint) then first chat renders exactly once', async () => { +interface OnboardingRun { + app: ElectronApplication + page: Page + ws: WsRecorder + provider: ScriptedProvider +} + +async function onboardThenFirstChat( + label: string, + config: string, + uiPreferences: null | Record, + onboard: (run: OnboardingRun) => Promise +) { const provider = await startScriptedProvider() - const sandbox = createCoreSandbox('onboard') - // A fresh desktop install starts the first-run onboarding chat on the free trial, and once a - // provider is configured it starts it on that provider at the next launch (#137522, #137807). This - // spec covers the provider setup a user without the trial gets, then plain chats: no guest trial, - // onboarding recorded as done. - fs.writeFileSync(path.join(sandbox.hermesHome, 'config.yaml'), 'nous:\n guest: false\nonboarding:\n run: false\n') + const sandbox = createCoreSandbox(label) + fs.writeFileSync(path.join(sandbox.hermesHome, 'config.yaml'), config) + + if (uiPreferences) { + seedUiPreferences(sandbox.hermesHome, uiPreferences) + } + const { app, page } = await launchCoreApp(coreAppEnv(sandbox)) const ws = recordWebSockets(page) try { await installDuplicateSampler(page) - - await test.step('first-run onboarding: custom endpoint', async () => { - // The onboarding surface masks the whole app until it finishes. - const openKeyForm = page - .locator('[data-glass-opaque]') - .filter({ visible: true }) - .getByRole('button', { name: /api key/i }) - - await expect(openKeyForm).toHaveCount(1, { timeout: 180_000 }) - await openKeyForm.click() - await page - .locator('[data-glass-opaque]') - .filter({ visible: true }) - .getByRole('button', { name: /custom endpoint/i }) - .click() - - // The endpoint URL is the form's only plain-text input (API keys are password inputs). - const form = page - .locator('[data-glass-opaque]') - .filter({ visible: true }) - .filter({ has: page.locator('input[type="text"]') }) - - await expect(form).toHaveCount(1) - await form.locator('input[type="text"]').fill(provider.url) - await form.getByRole('button', { name: /connect/i }).click() - // The overlay unmounts only after the backend probed the endpoint, saved - // the assignment and confirmed the runtime is ready; waitForInteractive - // fails while any full-viewport fixed layer still covers the composer. - await waitForInteractive(app, page) - }) + await onboard({ app, page, ws, provider }) await test.step('the persisted assignment is what the user entered', async () => { const config = fs.readFileSync(path.join(sandbox.hermesHome, 'config.yaml'), 'utf8') @@ -145,4 +133,78 @@ test('onboarding (custom endpoint) then first chat renders exactly once', async await provider.close() sandbox.cleanup() } +} + +test('classic onboarding (custom endpoint) then first chat renders exactly once', async () => { + // In the classic shell (the redesign switched off) a fresh desktop install starts the first-run + // onboarding chat on the free trial, and once a provider is configured it starts it on that provider + // at the next launch (#137522, #137807). This covers the provider setup a user without the trial + // gets, then plain chats: no guest trial, onboarding recorded as done. + await onboardThenFirstChat( + 'onboard-classic', + 'nous:\n guest: false\nonboarding:\n run: false\n', + CLASSIC_SHELL, + async ({ app, page, provider }) => { + await test.step('first-run onboarding: custom endpoint', async () => { + // The onboarding surface masks the whole app until it finishes. + const openKeyForm = page + .locator('[data-glass-opaque]') + .filter({ visible: true }) + .getByRole('button', { name: /api key/i }) + + await expect(openKeyForm).toHaveCount(1, { timeout: 180_000 }) + await openKeyForm.click() + await page + .locator('[data-glass-opaque]') + .filter({ visible: true }) + .getByRole('button', { name: /custom endpoint/i }) + .click() + + // The endpoint URL is the form's only plain-text input (API keys are password inputs). + const form = page + .locator('[data-glass-opaque]') + .filter({ visible: true }) + .filter({ has: page.locator('input[type="text"]') }) + + await expect(form).toHaveCount(1) + await form.locator('input[type="text"]').fill(provider.url) + await form.getByRole('button', { name: /connect/i }).click() + // The overlay unmounts only after the backend probed the endpoint, saved + // the assignment and confirmed the runtime is ready; waitForInteractive + // fails while any full-viewport fixed layer still covers the composer. + await waitForInteractive(app, page) + }) + } + ) +}) + +test('onboarding (custom endpoint) then first chat renders exactly once', async () => { + // The deterministic guide renders without any provider or free-model allocation. + await onboardThenFirstChat( + 'onboard', + 'nous:\n guest: false\nonboarding:\n run: true\n', + null, + async ({ app, page, provider, ws }) => { + await test.step('sessionless setup resumes and connects a custom endpoint', async () => { + const guide = page.getByRole('dialog', { name: 'Set up Hermes' }) + await expect(guide).toBeVisible({ timeout: 180_000 }) + await guide.getByRole('button', { name: 'Continue', exact: true }).click() + await expect(guide.getByRole('heading', { name: 'Choose a model' })).toBeVisible() + await page.reload() + await expect(guide.getByRole('heading', { name: 'Choose a model' })).toBeVisible({ timeout: 180_000 }) + expect(provider.completions).toHaveLength(0) + expect(ws.sent.filter(frame => ['session.create', 'prompt.submit'].includes(frame.method))).toHaveLength(0) + await guide.getByRole('button', { name: 'Connect a provider', exact: true }).click() + await page.getByRole('button', { name: /api key/i }).click() + await page.getByRole('button', { name: /custom endpoint/i }).click() + await page.getByPlaceholder('http://127.0.0.1:8000/v1').fill(provider.url) + await page.getByRole('button', { name: /^connect$/i }).click() + await page.getByRole('button', { name: 'Begin', exact: true }).click() + await expect(guide.getByRole('button', { name: 'Finish setup' })).toBeEnabled() + await guide.getByRole('button', { name: 'Finish setup' }).click() + await waitForInteractive(app, page) + expect(provider.completions).toHaveLength(0) + }) + } + ) }) diff --git a/apps/desktop/e2e/core/redesign-responsive.spec.ts b/apps/desktop/e2e/core/redesign-responsive.spec.ts new file mode 100644 index 0000000000000..f47fd12e4a56f --- /dev/null +++ b/apps/desktop/e2e/core/redesign-responsive.spec.ts @@ -0,0 +1,391 @@ +import { appendFileSync } from 'node:fs' + +import { chromium, expect, type Locator, type Page, test } from '@playwright/test' + +import { composer, createCoreSandbox, freePort, send, webappLaunchLink, writeProviderHome } from './harness' +import { startScriptedProvider } from './provider' + +test('redesigned web app stays usable on touch screens and restores the classic interface', async () => { + test.setTimeout(180_000) + const provider = await startScriptedProvider() + provider.script('U1-preview', [{ text: ['The history preview is ready.'] }]) + const sandbox = createCoreSandbox('redesign-responsive') + writeProviderHome(sandbox.hermesHome, provider.url) + appendFileSync(sandbox.hermesHome + '/config.yaml', `\nwebapp:\n enabled: true\n port: ${await freePort()}\n`) + const browser = await chromium.launch({ executablePath: process.env.HERMES_E2E_CHROMIUM }) + + try { + const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }) + // An unrelated release notification must not cover the touch-sized rail. + await context.addInitScript(() => { + localStorage.setItem('hermes:update-toast-snooze-until', String(Date.now() + 86_400_000)) + }) + const page = await context.newPage() + page.setDefaultTimeout(12_000) + await page.goto(webappLaunchLink(sandbox)) + await expect(composer(page)).toBeVisible({ timeout: 120_000 }) + + const go = async (route: string) => + page.evaluate(route => { + location.hash = route + }, route) + + for (const viewport of [ + { width: 320, height: 740 }, + { width: 390, height: 844 }, + { width: 768, height: 1024 }, + { width: 844, height: 390 } + ]) { + await page.setViewportSize(viewport) + await go('/') + await expect(composer(page)).toBeVisible() + await expect(page.locator('html')).toHaveAttribute('data-shell', 'portal') + const nav = page.getByRole('navigation', { name: 'Hermes', exact: true }) + await nav.getByRole('button', { name: 'Capabilities', exact: true }).tap() + await expect(page).toHaveURL(/capabilities/) + await expect(page.getByRole('heading', { name: 'Capabilities', exact: true }).first()).toBeVisible() + await nav.getByRole('button', { name: 'Chats', exact: true }).tap() + await expect(composer(page)).toBeVisible() + const sidebar = page.locator('.portal-sidebar') + + if (!(await sidebar.isVisible())) { + await page.getByRole('button', { name: 'Show sidebar', exact: true }).tap() + } + + await expect(sidebar).toBeVisible() + const bounds = await sidebar.boundingBox() + expect(bounds!.x).toBeGreaterThanOrEqual(0) + expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(viewport.width) + await page + .getByLabel('Window controls', { exact: true }) + .getByRole('button', { name: 'Hide sidebar', exact: true }) + .tap() + await expect(sidebar).not.toBeVisible() + await expect.poll(() => page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true) + await go('/settings?tab=config:appearance&page=window-layout') + const toggle = page.getByRole('switch', { name: 'Redesigned interface', exact: true }) + await expect(toggle).toBeVisible() + await expect(toggle).toBeChecked() + await toggle.tap() + await expect(toggle).not.toBeChecked() + await expect(page.locator('html')).not.toHaveAttribute('data-shell', /.*/) + await toggle.tap() + await expect(toggle).toBeChecked() + await expect(page.locator('html')).toHaveAttribute('data-shell', 'portal') + await go('/') + await expect(composer(page)).toBeVisible() + const consent = page.locator('[data-slot="composer-status-stack"]') + const consentBounds = await consent.boundingBox() + + for (const name of ['Share with Nous', 'No thanks', 'Details']) { + const choice = consent.getByRole('button', { name, exact: true }) + await expect(choice).toBeVisible() + const bounds = await choice.boundingBox() + expect(bounds!.x).toBeGreaterThanOrEqual(consentBounds!.x) + expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(consentBounds!.x + consentBounds!.width) + } + + await page.screenshot({ path: test.info().outputPath(`redesign-${viewport.width}.png`) }) + } + + await page.setViewportSize({ width: 1280, height: 860 }) + await exerciseHistoryPreview(page) + await exerciseManagementEntries(page, true) + + if (!(await page.locator('.portal-sidebar').isVisible())) { + await page.getByRole('button', { name: 'Show sidebar', exact: true }).tap() + } + + const sidebarWidth = (await page.locator('.portal-sidebar').boundingBox())!.width + + // Both modes let the wing show through the translucent sidebar as a trace. + for (const colorScheme of ['dark', 'light'] as const) { + await page.emulateMedia({ colorScheme }) + await expect(page.locator('html')).toHaveClass(colorScheme === 'dark' ? /\bdark\b/ : /^(?!.*\bdark\b)/) + await expectFaintWing(page, page.locator('.portal-sidebar')) + } + + await go('/settings?tab=config:appearance&page=window-layout') + await page.getByRole('button', { name: 'Simple', exact: true }).tap() + await go('/') + await expect(page.getByRole('button', { name: 'Terminal', exact: true })).not.toBeVisible() + await go('/settings?tab=config:appearance&page=window-layout') + await page + .locator('[id="setting-field-appearance.interface-mode"]') + .getByRole('button', { name: 'Advanced', exact: true }) + .tap() + await go('/settings?tab=config:safety&page=approvals') + await expect(page.getByRole('radio', { name: /^Smart/ })).toBeVisible() + const settings = page.locator('[data-page-surface]') + const rail = page.locator('[data-slot="global-nav"]') + const settingsNav = settings.locator('[data-tour="overlay-nav"]') + // Settings is a sibling of the shell: it must still clear the rail and + // share the redesigned sidebar's width rather than inherit classic sizes. + await expect + .poll( + async () => { + const railBounds = (await rail.boundingBox())! + + return (await settings.boundingBox())!.x - (railBounds.x + railBounds.width) + }, + { timeout: 5000 } + ) + .toBeCloseTo(0) + await expect.poll(async () => (await settingsNav.boundingBox())!.width, { timeout: 5000 }).toBe(sidebarWidth) + await page.locator('[data-slot="portal-safety-settings"] summary').tap() + await expect(page.locator('[data-slot="portal-safety-settings"] details')).toHaveAttribute('open', '') + await page.screenshot({ path: test.info().outputPath('redesign-safety.png') }) + await page.emulateMedia({ colorScheme: 'dark' }) + await expect(page.locator('html')).toHaveClass(/dark/) + await expectFaintWing(page, settings) + await page.screenshot({ path: test.info().outputPath('redesign-safety-dark.png') }) + await page.emulateMedia({ colorScheme: 'light' }) + await expect(page.locator('html')).not.toHaveClass(/dark/) + await expectFaintWing(page, settings) + await go('/settings?tab=config:appearance') + await page.getByRole('button', { name: 'Switch language', exact: true }).tap() + await page.getByRole('combobox').fill('العربية') + await page.getByRole('combobox').press('Enter') + await expect(page.locator('html')).toHaveAttribute('dir', 'rtl') + await expect + .poll(async () => { + const railBounds = (await rail.boundingBox())! + const settingsBounds = (await settings.boundingBox())! + + return railBounds.x - (settingsBounds.x + settingsBounds.width) + }) + .toBeCloseTo(0) + await rail.getByRole('button', { name: 'المحادثات', exact: true }).tap() + await expect(composer(page)).toBeVisible() + await go('/settings?tab=config:appearance') + await page.getByRole('button', { name: 'تغيير اللغة', exact: true }).tap() + await page.getByRole('combobox').fill('English') + await page.getByRole('combobox').press('Enter') + await expect(page.locator('html')).toHaveAttribute('dir', 'ltr') + await go('/') + + if (!(await page.locator('.portal-sidebar').isVisible())) { + await page.getByRole('button', { name: 'Show sidebar', exact: true }).tap() + } + + await page.getByRole('button', { name: 'New group chat', exact: true }).tap() + await expect(page.getByRole('dialog')).toBeVisible() + // Body-portalled dialogs sit outside the shell and must still wear its rounder geometry. + await expect + .poll(() => + page.getByRole('dialog').evaluate(dialog => getComputedStyle(dialog).getPropertyValue('--radius-scalar').trim()) + ) + .toBe('0.6') + await page.getByRole('dialog').getByRole('button', { name: 'Cancel', exact: true }).tap() + await expect(page.getByRole('dialog')).not.toBeVisible() + await page.getByRole('button', { name: 'Terminal', exact: true }).tap() + const terminal = page.locator('[data-persistent-terminal][aria-hidden="false"] .xterm-helper-textarea').first() + await expect(terminal).toBeVisible() + const tools = page.getByRole('navigation', { name: 'Right sidebar panels' }) + const terminalPanel = page.locator('[data-persistent-terminal]') + await expect.poll(async () => (await terminalPanel.boundingBox())?.height ?? 0).toBeGreaterThan(600) + await page.screenshot({ path: test.info().outputPath('redesign-terminal.png') }) + + for (const name of ['Files', 'Review', 'Preview']) { + await tools.getByRole('button', { name, exact: true }).tap() + await expect(tools.getByRole('button', { name, exact: true })).toHaveAttribute('aria-pressed', 'true', { + timeout: 10_000 + }) + await expect(tools.getByRole('button', { name: 'Terminal', exact: true })).toHaveAttribute( + 'aria-pressed', + 'false', + { timeout: 10_000 } + ) + await expect(terminalPanel).toHaveAttribute('aria-hidden', 'true') + await tools.getByRole('button', { name: 'Terminal', exact: true }).tap() + await expect(terminal).toBeVisible() + await expect(tools.getByRole('button', { name, exact: true })).toHaveAttribute('aria-pressed', 'false', { + timeout: 10_000 + }) + await expect.poll(async () => (await terminalPanel.boundingBox())?.height ?? 0).toBeGreaterThan(600) + await expect.poll(async () => (await terminalPanel.boundingBox())?.width ?? 0).toBeGreaterThan(300) + } + + await page.getByRole('button', { name: 'Hide terminal', exact: true }).tap() + await expect(page.locator('[data-persistent-terminal]')).toHaveAttribute('aria-hidden', 'true', { timeout: 5000 }) + await expect(page.locator('[data-persistent-terminal]')).toHaveAttribute('inert', '') + await expect(page.locator('[data-persistent-terminal]')).toHaveCSS('opacity', '0') + await expect(terminal).not.toBeVisible() + await expect(page.locator('[data-persistent-terminal] .xterm-helper-textarea')).toHaveCount(1) + await page.getByRole('button', { name: 'Terminal', exact: true }).tap() + await expect(terminal).toBeVisible() + await page.getByRole('button', { name: 'Hide terminal', exact: true }).tap() + await page.screenshot({ path: test.info().outputPath('redesign-desktop.png') }) + await go('/settings?tab=config:appearance&page=window-layout') + await page.getByRole('switch', { name: 'Redesigned interface', exact: true }).tap() + await go('/') + await expect(composer(page)).toBeVisible() + await exerciseManagementEntries(page, false) + await page.screenshot({ path: test.info().outputPath('classic-desktop.png') }) + } finally { + await browser.close() + sandbox.cleanup() + await provider.close() + } +}) + +// The largest per-channel change (0-255) the wing may make to any pixel: a trace, never the +// full-strength art the bare canvas would show. +const WING_FAINT_PEAK = 32 + +/** The wing art's (portal-artwork.css) own contribution to `region`: the same pixels rendered with + * it and with its strength set to zero, compared channel by channel. Content cancels out, so the + * number is the art alone. */ +async function wingPeak(page: Page, region: Locator): Promise { + const clip = (await region.boundingBox())! + const shoot = async () => (await page.screenshot({ animations: 'disabled', clip })).toString('base64') + + const setStrength = (strength: null | string) => + page.evaluate(strength => { + for (const name of ['--portal-wing-opacity', '--portal-page-wing-opacity']) { + if (strength === null) { + document.documentElement.style.removeProperty(name) + } else { + document.documentElement.style.setProperty(name, strength) + } + } + }, strength) + + const withArt = await shoot() + await setStrength('0') + const withoutArt = await shoot() + await setStrength(null) + + return page.evaluate( + async pngs => { + const pixels = await Promise.all( + pngs.map(async png => { + const image = new Image() + image.src = `data:image/png;base64,${png}` + await image.decode() + const canvas = document.createElement('canvas') + canvas.width = image.width + canvas.height = image.height + const context = canvas.getContext('2d')! + context.drawImage(image, 0, 0) + + return context.getImageData(0, 0, image.width, image.height).data + }) + ) + + const [withArt, withoutArt] = pixels as [Uint8ClampedArray, Uint8ClampedArray] + let peak = 0 + + for (let i = 0; i < withArt.length; i++) { + if (i % 4 !== 3) { + peak = Math.max(peak, Math.abs(withArt[i]! - withoutArt[i]!)) + } + } + + return peak + }, + [withArt, withoutArt] + ) +} + +async function expectFaintWing(page: Page, region: Locator) { + const peak = await wingPeak(page, region) + + expect(peak, 'the wing shows through').toBeGreaterThan(0) + expect(peak, 'the wing stays a faint trace').toBeLessThanOrEqual(WING_FAINT_PEAK) +} + +async function exerciseHistoryPreview(page: Page) { + await page.getByRole('button', { name: 'No thanks', exact: true }).tap() + await send(page, 'U1-preview Keep this conversation for the history preview.') + await expect(page.getByText('The history preview is ready.', { exact: true })).toBeVisible() + await page.getByRole('button', { name: 'Agent settings', exact: true }).tap() + await page.getByRole('button', { name: 'History', exact: true }).tap() + + for (const viewport of [ + { width: 1280, height: 860 }, + { width: 320, height: 740 } + ]) { + await page.setViewportSize(viewport) + await page + .getByRole('button', { name: /^Chat actions/ }) + .first() + .tap() + await page.getByRole('menuitem', { name: 'Preview', exact: true }).tap() + const preview = page.getByRole('dialog') + await expect(preview.getByText('The history preview is ready.', { exact: true })).toBeVisible() + await expect + .poll(async () => { + const bounds = await preview.boundingBox() + + return ( + bounds !== null && + bounds.x >= 0 && + bounds.y >= 0 && + bounds.x + bounds.width <= viewport.width && + bounds.y + bounds.height <= viewport.height + ) + }) + .toBe(true) + await expect(preview.getByRole('button', { name: 'Open chat', exact: true })).toBeInViewport({ ratio: 1 }) + await preview.getByRole('button', { name: 'Close', exact: true }).tap() + await expect(preview).not.toBeVisible() + } + + await page.setViewportSize({ width: 1280, height: 860 }) +} + +// Exercise the same Agent/Routine concepts from navigation through both editors. +async function exerciseManagementEntries(page: Page, redesigned: boolean) { + const rail = page.locator('[data-slot="global-nav"]') + + if (redesigned) { + await rail.getByRole('button', { name: 'Routines', exact: true }).click() + } else { + await page.evaluate(() => { + location.hash = '/cron' + }) + } + + await expect(page).toHaveURL(/#\/cron/) + await page.getByRole('heading', { name: 'Routines', exact: true }).first().waitFor({ state: 'visible' }) + // The empty-state button is replaced when the async blueprint catalog arrives. + // Use the schedule-list action so this assertion tracks the same opener. + const newSchedule = page.locator('button[aria-label="New routine"]') + await newSchedule.click() + const schedule = page.getByRole('dialog', { name: 'New routine', exact: true }) + await schedule.getByRole('textbox', { name: /^Name\b/ }).fill('Weekly briefing') + await schedule.getByRole('textbox', { name: 'Prompt', exact: true }).fill('Summarize the week.') + await schedule.getByRole('button', { name: 'Cancel', exact: true }).click() + await expect(schedule).not.toBeVisible() + + if (redesigned) { + await expect(newSchedule).toBeFocused() + } + + if (redesigned) { + await rail.getByRole('button', { name: 'Agents', exact: true }).click() + } else { + await page.evaluate(() => { + location.hash = '/profiles?manage=true' + }) + } + + await page.getByRole('heading', { name: 'Agents', exact: true }).first().waitFor({ state: 'visible' }) + + const newAgent = page.getByRole('button', { name: 'New agent', exact: true }).first() + await newAgent.click() + const agent = page.getByRole('dialog', { name: 'New agent', exact: true }) + await agent.getByRole('textbox', { name: /^Name\b/ }).fill('terminology-smoke') + await agent.getByRole('button', { name: 'Cancel', exact: true }).click() + await expect(agent).not.toBeVisible() + + if (redesigned) { + await expect(newAgent).toBeFocused() + } + + await page.evaluate(() => { + location.hash = '/' + }) + await expect(composer(page)).toBeVisible() +} diff --git a/apps/desktop/e2e/correction-session-switch.spec.ts b/apps/desktop/e2e/correction-session-switch.spec.ts index 2910c3afcfd1b..ae342240ed863 100644 --- a/apps/desktop/e2e/correction-session-switch.spec.ts +++ b/apps/desktop/e2e/correction-session-switch.spec.ts @@ -117,7 +117,7 @@ async function transcriptMessageOrder(page: Page): Promise { * for the old text to disappear from the page (it never will). */ async function openFreshDraft(page: Page, priorSessionText: string): Promise { - await page.locator('[data-slot="sidebar"] button[aria-label="New session"]').first().click() + await page.locator('[data-slot="sidebar"] button[aria-label="New chat"]').first().click() await page.waitForFunction( ([priorText, surfaceSelector]: [string, string]) => { const surfaces = document.querySelectorAll(surfaceSelector) diff --git a/apps/desktop/e2e/desktop-plugin-contract-probe.spec.ts b/apps/desktop/e2e/desktop-plugin-contract-probe.spec.ts new file mode 100644 index 0000000000000..95c2fe30152f3 --- /dev/null +++ b/apps/desktop/e2e/desktop-plugin-contract-probe.spec.ts @@ -0,0 +1,114 @@ +/** + * The plugin contract in the real app: the contract probe (src/contrib/__fixtures__/contract-probe, + * one contribution in every SDK area) is dropped into the sandbox's `desktop-plugins/` folder the + * way a user or agent installs a disk plugin, and each shell × interface mode is checked for where + * its contributions land. Real Electron and real `hermes serve`; the probe needs no backend. + * + * Status-bar contributions are asserted as they CURRENTLY behave (the redesign has no strip; its + * items sit in the rail's System popover) — their home in the redesign is an open decision. + */ +import fs from 'node:fs' +import path from 'node:path' + +import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures' +import { expect, test } from './test' + +const PROBE_SOURCE = path.join(__dirname, '..', 'src', 'contrib', '__fixtures__', 'contract-probe', 'plugin.js') +const SHELL_KEY = 'hermes.desktop.agentShell.v1' +const MODE_KEY = 'hermes.desktop.interfaceMode.v1' + +let fixture: MockBackendFixture | null = null + +test.beforeAll(async () => { + fixture = await setupMockBackend() + const folder = path.join(fixture.sandbox.hermesHome, 'desktop-plugins', 'contract-probe') + fs.mkdirSync(folder, { recursive: true }) + fs.copyFileSync(PROBE_SOURCE, path.join(folder, 'plugin.js')) +}) + +test.afterAll(async () => { + await fixture?.cleanup() + fixture = null +}) + +const marker = (area: string) => fixture!.page.getByTestId(`probe-${area}`) + +for (const shell of ['classic', 'redesign'] as const) { + for (const mode of ['simple', 'advanced'] as const) { + test(`the probe's contributions reach the ${shell} shell in ${mode} mode`, async () => { + test.setTimeout(240_000) + const { page } = fixture! + await waitForAppReady(fixture!, 120_000) + // Both keys are machine-shared: the reload hydrates them from ui-preferences.json, so they go + // through the store (the write the app's own toggles make), not into localStorage alone. The + // local copy is set to match too: a window not yet joined to the store's generation keeps a + // local key the store deleted. + await page.evaluate( + async ([shellKey, modeKey, classic, simple]) => { + const values = { [shellKey]: classic ? 'false' : null, [modeKey]: simple ? 'simple' : null } + + const { uiPreferences } = ( + window as unknown as { + hermesDesktop: { uiPreferences: { write: (payload: { values: typeof values }) => Promise } } + } + ).hermesDesktop + + await uiPreferences.write({ values }) + + for (const [key, value] of Object.entries(values)) { + if (value === null) { + localStorage.removeItem(key) + } else { + localStorage.setItem(key, value) + } + } + + location.hash = '#/' + }, + [SHELL_KEY, MODE_KEY, shell === 'classic', mode === 'simple'] as const + ) + await page.reload() + await waitForAppReady(fixture!, 120_000) + + // The chat: titlebar slots, composer render areas, the floating pane. + for (const area of ['titleBar.left', 'titleBar.right', 'composer.top', 'composer.bottom', 'pane-floating']) { + await expect(marker(area).first(), area).toBeVisible({ timeout: 60_000 }) + } + + await expect(page.getByLabel('Probe tool').first()).toBeVisible() + + // The page, reached from its nav row (the rail in the redesign, the sidebar in classic). + await page.getByRole('button', { name: 'Probe page' }).first().click() + await expect(marker('route')).toBeVisible() + await expect(marker('workspace.pageHeader')).toBeVisible() + await expect(marker('i18n')).toHaveText(shell === 'redesign' ? 'Contract probe (redesign)' : 'Contract probe') + await expect(marker('viewport')).toContainText('"narrow":false') + + // Settings ▸ Plugins and Appearance. + await page.evaluate(() => (location.hash = '#/settings?tab=plugins&plugin=contract-probe')) + await expect(marker('settings.plugins')).toBeVisible() + await page.evaluate(() => (location.hash = '#/settings?tab=appearance')) + await expect(marker('appearance.extra')).toBeVisible() + + // Titlebar slots survive the overlay destinations in the redesign (parked), as permanent mounts. + await expect(marker('titleBar.right')).toHaveCount(shell === 'redesign' ? 1 : 0) + + // host.openWorkspace through the palette command. + await page.evaluate(() => (location.hash = '#/')) + await page.keyboard.press('ControlOrMeta+k') + await page.keyboard.type('Probe: open workspace') + await page.keyboard.press('Enter') + await expect(marker('openWorkspace')).toBeVisible() + + // CURRENT behaviour, pending the redesign's status-bar decision: classic shows the strip's + // items in Advanced; the redesign lists them only in the rail's System popover. + if (shell === 'classic' && mode === 'advanced') { + await expect(marker('statusBar.right')).toBeVisible() + } + + if (shell === 'redesign') { + await expect(marker('statusBar.right')).toHaveCount(0) + } + }) + } +} diff --git a/apps/desktop/e2e/fixtures.ts b/apps/desktop/e2e/fixtures.ts index a9747efd65d60..a04623729ce87 100644 --- a/apps/desktop/e2e/fixtures.ts +++ b/apps/desktop/e2e/fixtures.ts @@ -33,6 +33,7 @@ import { type MockServerOptions, startMockServer } from '../../../tests-js/scrip import { resolveElectronBinary } from './electron-binary' import { stopSandboxGatewayDaemons } from './run-tmp-reaper' import { installErrorBannerGuard } from './test' +import { seedUiPreferences } from './ui-preferences-seed' const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..') const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..') @@ -173,7 +174,11 @@ export function createSandbox(prefix: string): Sandbox { */ function writeEmptyConfig(hermesHome: string): void { const configPath = path.join(hermesHome, 'config.yaml') - fs.writeFileSync(configPath, '# Auto-generated by E2E test fixtures — no providers configured\n', 'utf8') + fs.writeFileSync( + configPath, + '# Auto-generated by E2E test fixtures — no providers configured\nonboarding:\n run: true\n', + 'utf8' + ) } // ─── Env building ────────────────────────────────────────────────────── @@ -390,10 +395,14 @@ export interface NoProviderFixture { * Launch the app with no provider configured. The onboarding overlay should * appear because there's no inference provider in config.yaml. */ -export async function setupNoProvider(): Promise { +export async function setupNoProvider(uiPreferences?: Record): Promise { const sandbox = createSandbox('noprovider') writeEmptyConfig(sandbox.hermesHome) + if (uiPreferences) { + seedUiPreferences(sandbox.hermesHome, uiPreferences) + } + const env = buildAppEnv(sandbox) const { app, page } = await launchDesktop(env) diff --git a/apps/desktop/e2e/fleet-profile-rail.spec.ts b/apps/desktop/e2e/fleet-profile-rail.spec.ts index e99b2efc5661c..11b8fba6f9b9a 100644 --- a/apps/desktop/e2e/fleet-profile-rail.spec.ts +++ b/apps/desktop/e2e/fleet-profile-rail.spec.ts @@ -26,7 +26,7 @@ import { launchDesktop, type MockBackendFixture, type Sandbox, - waitForAppReady, + waitForAppReady } from './fixtures' import { type ElectronApplication, expect, type Page, test } from './test' @@ -104,10 +104,10 @@ async function startRemoteGateway(root: string, mockUrl: string, profiles: strin env: { ...process.env, HERMES_HOME: home, - HERMES_DASHBOARD_SESSION_TOKEN: REMOTE_TOKEN, + HERMES_DASHBOARD_SESSION_TOKEN: REMOTE_TOKEN }, - stdio: ['ignore', 'pipe', 'pipe'], - }, + stdio: ['ignore', 'pipe', 'pipe'] + } ) let log = '' @@ -127,7 +127,7 @@ async function startRemoteGateway(root: string, mockUrl: string, profiles: strin try { const response = await fetch(`${url}/api/status`, { - headers: { 'X-Hermes-Session-Token': REMOTE_TOKEN }, + headers: { 'X-Hermes-Session-Token': REMOTE_TOKEN } }) if (response.ok) { @@ -157,7 +157,7 @@ async function startRemoteGateway(root: string, mockUrl: string, profiles: strin } await new Promise(resolve => setTimeout(resolve, 500)) - }, + } } } @@ -178,14 +178,14 @@ function writeConnectionsRegistry(sandbox: Sandbox, remoteUrl: string): void { label: REMOTE_LABEL, url: remoteUrl, authMode: 'token', - token: { encoding: 'plain', value: REMOTE_TOKEN }, - }, - ], + token: { encoding: 'plain', value: REMOTE_TOKEN } + } + ] }, null, - 2, + 2 ), - { encoding: 'utf8', mode: 0o600 }, + { encoding: 'utf8', mode: 0o600 } ) } @@ -203,13 +203,24 @@ async function capture(page: Page, name: string): Promise { } const rail = (page: Page) => page.locator('[data-slot="profile-rail"]') -const gatewayGroup = (page: Page, id: string) => rail(page).locator(`[data-slot="profile-rail-gateway"][data-connection-id="${id}"]`) -const activeGatewayLabel = (page: Page) => page.getByRole('button', { name: /^Registered gateways: / }) + +const gatewayGroup = (page: Page, id: string) => + rail(page).locator(`[data-slot="profile-rail-gateway"][data-connection-id="${id}"]`) + +const activeGatewayLabel = (page: Page) => page.getByRole('button', { name: /^Machines: / }) async function groupOrder(page: Page): Promise> { - return rail(page).locator('[data-slot="profile-rail-gateway"]').evaluateAll(nodes => - nodes.map(node => [node.getAttribute('data-connection-id') ?? '', node.getAttribute('data-active') === 'true'] as [string, boolean]), - ) + return rail(page) + .locator('[data-slot="profile-rail-gateway"]') + .evaluateAll(nodes => + nodes.map( + node => + [node.getAttribute('data-connection-id') ?? '', node.getAttribute('data-active') === 'true'] as [ + string, + boolean + ] + ) + ) } test.describe('fleet profile rail — two registered gateways', () => { @@ -240,7 +251,9 @@ test.describe('fleet profile rail — two registered gateways', () => { // Let boot settle fully (the gateway health item reports "ready" once the // primary socket is open) so the boot-time launch-mode restore has run // before any click — the rail must then hold whatever the user picks. - await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ timeout: 120_000 }) + await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ + timeout: 120_000 + }) await page.waitForTimeout(2_000) }) @@ -253,7 +266,7 @@ test.describe('fleet profile rail — two registered gateways', () => { test('lays both gateways on one strip, active gateway in its registry slot', async () => { // The statusbar readout names the gateway the workspace is on. - await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Registered gateways: This device', { timeout: 60_000 }) + await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Machines: This device', { timeout: 60_000 }) // The remote gateway's group appears once the roster has enumerated it. const homelab = gatewayGroup(page, REMOTE_ID) @@ -265,7 +278,9 @@ test.describe('fleet profile rail — two registered gateways', () => { // Its marker carries the remote (network) glyph. await expect( - rail(page).locator(`[data-slot="profile-rail-divider"][data-connection-id="${REMOTE_ID}"] [data-connection-kind="remote"]`), + rail(page).locator( + `[data-slot="profile-rail-divider"][data-connection-id="${REMOTE_ID}"] [data-connection-kind="remote"]` + ) ).toBeVisible() // This device is the active group: its squares are unqualified, as before. @@ -276,24 +291,32 @@ test.describe('fleet profile rail — two registered gateways', () => { // Registry order: This device first, Homelab second. expect(await groupOrder(page)).toEqual([ ['local', true], - [REMOTE_ID, false], + [REMOTE_ID, false] ]) - await gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }).hover() + await gatewayGroup(page, REMOTE_ID) + .getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }) + .hover() await capture(page, '1-on-this-device-hover-inbox-homelab') }) test('clicking an at-rest square re-homes onto that exact gateway and profile', async () => { test.setTimeout(180_000) - await gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }).click() + await gatewayGroup(page, REMOTE_ID) + .getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }) + .click() // The workspace follows the agent: statusbar readout flips to Homelab… - await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', `Registered gateways: ${REMOTE_LABEL}`, { timeout: 120_000 }) + await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', `Machines: ${REMOTE_LABEL}`, { + timeout: 120_000 + }) // …Homelab's group is now the active one, on the clicked profile… const homelab = gatewayGroup(page, REMOTE_ID) await expect(homelab).toHaveAttribute('data-active', 'true', { timeout: 30_000 }) - await expect(homelab.getByRole('button', { name: 'inbox', exact: true })).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 }) + await expect(homelab.getByRole('button', { name: 'inbox', exact: true })).toHaveAttribute('aria-pressed', 'true', { + timeout: 30_000 + }) // …This device is at rest with qualified squares… const local = gatewayGroup(page, 'local') @@ -303,7 +326,7 @@ test.describe('fleet profile rail — two registered gateways', () => { // …and nothing moved: the order is still This device, then Homelab. expect(await groupOrder(page)).toEqual([ ['local', false], - [REMOTE_ID, true], + [REMOTE_ID, true] ]) await capture(page, '2-re-homed-on-homelab-inbox') @@ -325,15 +348,17 @@ test.describe('fleet profile rail — two registered gateways', () => { test.setTimeout(180_000) await gatewayGroup(page, 'local').getByRole('button', { name: 'research · This device' }).click() - await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Registered gateways: This device', { timeout: 120_000 }) + await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Machines: This device', { timeout: 120_000 }) const local = gatewayGroup(page, 'local') await expect(local).toHaveAttribute('data-active', 'true', { timeout: 30_000 }) - await expect(local.getByRole('button', { name: 'research', exact: true })).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 }) + await expect(local.getByRole('button', { name: 'research', exact: true })).toHaveAttribute('aria-pressed', 'true', { + timeout: 30_000 + }) await expect(gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` })).toBeVisible() expect(await groupOrder(page)).toEqual([ ['local', true], - [REMOTE_ID, false], + [REMOTE_ID, false] ]) }) }) diff --git a/apps/desktop/e2e/image-attachment-resume.spec.ts b/apps/desktop/e2e/image-attachment-resume.spec.ts index 6a4db925d745d..2b36ac194e85a 100644 --- a/apps/desktop/e2e/image-attachment-resume.spec.ts +++ b/apps/desktop/e2e/image-attachment-resume.spec.ts @@ -125,7 +125,7 @@ async function openSeededSession(page: Page): Promise { * surface is empty rather than waiting for the old caption to leave the page. */ async function openNewSession(page: Page): Promise { - await page.locator('[data-slot="sidebar"] button[aria-label="New session"]').first().click() + await page.locator('[data-slot="sidebar"] button[aria-label="New chat"]').first().click() await page.waitForFunction( ([expected, surfaceSelector]: [string, string]) => { const surfaces = document.querySelectorAll(surfaceSelector) diff --git a/apps/desktop/e2e/large-session-resume.spec.ts b/apps/desktop/e2e/large-session-resume.spec.ts index b13aa66b555f7..5a04264efe658 100644 --- a/apps/desktop/e2e/large-session-resume.spec.ts +++ b/apps/desktop/e2e/large-session-resume.spec.ts @@ -89,7 +89,7 @@ async function openSeededSession(page: Page): Promise { } async function openNewSession(page: Page): Promise { - const button = page.locator('[data-slot="sidebar"] button').filter({ hasText: 'New session' }).first() + const button = page.locator('[data-slot="sidebar"] button').filter({ hasText: 'New chat' }).first() await button.waitFor({ state: 'visible', timeout: 10_000 }) await button.click() await page.waitForFunction( diff --git a/apps/desktop/e2e/legacy-desktop-history.spec.ts b/apps/desktop/e2e/legacy-desktop-history.spec.ts index 6d531b631b3a9..ee3bcd83c5910 100644 --- a/apps/desktop/e2e/legacy-desktop-history.spec.ts +++ b/apps/desktop/e2e/legacy-desktop-history.spec.ts @@ -168,7 +168,7 @@ seed(home / 'profiles' / 'developer', [{'id': sys.argv[2], 'source': 'desktop', await entry.click() const answer = page.locator('[data-slot="aui_thread-viewport"]').getByText('Historical answer ' + row.id) - const failure = page.getByText("Couldn't open this session") + const failure = page.getByText("Couldn't open this chat") await expect(answer.or(failure).first()).toBeVisible({ timeout: 45_000 }).catch(() => undefined) results[row.id].opened = await answer.isVisible() diff --git a/apps/desktop/e2e/onboarding.spec.ts b/apps/desktop/e2e/onboarding.spec.ts index 48c13f91207aa..d6c29886be3b7 100644 --- a/apps/desktop/e2e/onboarding.spec.ts +++ b/apps/desktop/e2e/onboarding.spec.ts @@ -1,21 +1,14 @@ /** - * E2E onboarding tests — verify the provider picker appears when no - * inference provider is configured. - * - * Launches the app with an empty config.yaml (no providers). The renderer - * should detect the unconfigured state and show the DesktopOnboardingOverlay - * with provider options / API key form. + * E2E onboarding tests. The redesign's deterministic guide renders without an inference provider, + * provider setup remaining an explicit choice from the model step. The classic shell (the redesign + * switched off) still shows the provider picker when no inference provider is configured. * * Prerequisite: `pnpm run build` must have been run so dist/ exists. */ -import { test } from './test' - -import { - type NoProviderFixture, - setupNoProvider, - waitForOnboarding, -} from './fixtures' +import { type NoProviderFixture, setupNoProvider, waitForOnboarding } from './fixtures' +import { expect, test } from './test' +import { CLASSIC_SHELL } from './ui-preferences-seed' import { expectVisualSnapshot } from './visual-snapshot' let fixture: NoProviderFixture | null = null @@ -29,10 +22,12 @@ test.describe('onboarding with no provider configured', () => { test('onboarding overlay appears on first boot', async () => { fixture = await setupNoProvider() - // The app should boot (hermes serve starts fine even without a provider), - // but the renderer should show the onboarding overlay because no - // provider is configured. - await waitForOnboarding(fixture.page, 90_000) + const guide = fixture.page.getByRole('dialog') + await expect(guide.getByRole('heading', { name: 'Set up Hermes' })).toBeVisible({ timeout: 90_000 }) + await guide.getByRole('button', { name: 'Continue', exact: true }).click() + await expect(guide.getByRole('heading', { name: 'Choose a model', exact: true })).toBeVisible() + await expect(guide.getByRole('button', { name: 'Finish setup', exact: true })).toBeDisabled() + await expect(guide.getByRole('button', { name: 'Connect a provider', exact: true })).toBeEnabled() }) test('screenshot of onboarding overlay', async () => { @@ -45,3 +40,22 @@ test.describe('onboarding with no provider configured', () => { await expectVisualSnapshot(fixture.page, { name: 'onboarding-overlay', app: fixture.app }) }) }) + +test.describe('classic shell onboarding with no provider configured', () => { + let classic: NoProviderFixture | null = null + + test.afterAll(async () => { + await classic?.cleanup() + classic = null + }) + + test('onboarding overlay appears on first boot', async () => { + classic = await setupNoProvider(CLASSIC_SHELL) + + // The app should boot (hermes serve starts fine even without a provider), + // but the renderer should show the onboarding overlay because no + // provider is configured. + await waitForOnboarding(classic.page, 90_000) + await expect(classic.page.locator('html')).not.toHaveAttribute('data-shell', /.*/) + }) +}) diff --git a/apps/desktop/e2e/peer-device-reset.spec.ts b/apps/desktop/e2e/peer-device-reset.spec.ts index 65d40b5b14dbe..ccd8ce68ce515 100644 --- a/apps/desktop/e2e/peer-device-reset.spec.ts +++ b/apps/desktop/e2e/peer-device-reset.spec.ts @@ -123,11 +123,11 @@ async function stopRemote(child: ChildProcess | undefined): Promise { } } -const gateway = (page: Page) => page.getByRole('button', { name: /^Registered gateways: / }) +const gateway = (page: Page) => page.getByRole('button', { name: /^Machines: / }) const composer = (page: Page) => page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first() async function expectReady(page: Page, label: string): Promise { - await expect(gateway(page)).toHaveAttribute('aria-label', `Registered gateways: ${label}`, { timeout: 90_000 }) + await expect(gateway(page)).toHaveAttribute('aria-label', `Machines: ${label}`, { timeout: 90_000 }) await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ timeout: 90_000 }) await expect(composer(page)).toBeEditable() } diff --git a/apps/desktop/e2e/provider-setup-owner.spec.ts b/apps/desktop/e2e/provider-setup-owner.spec.ts index 4141b840a6876..8cbe7006f9df0 100644 --- a/apps/desktop/e2e/provider-setup-owner.spec.ts +++ b/apps/desktop/e2e/provider-setup-owner.spec.ts @@ -243,9 +243,9 @@ async function selectGateway(page: Page, id: string, label: string, profile: str const group = gatewayGroup(page, id) await expect(group).toBeVisible({ timeout: 60_000 }) await group.getByRole('button', { name: `${profile} · ${label}`, exact: true }).click() - await expect(page.getByRole('button', { name: /^Registered gateways: / })).toHaveAttribute( + await expect(page.getByRole('button', { name: `Machines: ${label}`, exact: true })).toHaveAttribute( 'aria-label', - `Registered gateways: ${label}`, + `Machines: ${label}`, { timeout: 90_000 } ) await expect(group).toHaveAttribute('data-active', 'true') diff --git a/apps/desktop/e2e/remote-oauth-recovery.spec.ts b/apps/desktop/e2e/remote-oauth-recovery.spec.ts index 3ae505dc8c10d..8685cbd7570da 100644 --- a/apps/desktop/e2e/remote-oauth-recovery.spec.ts +++ b/apps/desktop/e2e/remote-oauth-recovery.spec.ts @@ -68,13 +68,13 @@ for (const status of [401, 403]) { })) app = launched.app const page = launched.page - await expect(page.getByRole('button', { name: /gateway settings/i })).toBeVisible({ timeout: 60_000 }) + await expect(page.getByRole('button', { name: 'Machine settings' })).toBeVisible({ timeout: 60_000 }) const snapshot = await page.evaluate(() => (window as unknown as DesktopWindow).hermesDesktop.getBootProgress()) expect(snapshot).toMatchObject({ running: false, retryable: false, statusCode: status }) expect(snapshot.error).toMatch(/not signed in/) expect(mints).toBeGreaterThan(0) const settledMints = mints - await page.getByRole('button', { name: /gateway settings/i }).click() + await page.getByRole('button', { name: 'Machine settings' }).click() const back = page.getByRole('button', { name: /^back$/i }) await expect(back).toBeVisible() const gatewayUrl = page.getByPlaceholder('https://gateway.example.com/hermes') diff --git a/apps/desktop/e2e/sidebar-background-finish-offscreen.spec.ts b/apps/desktop/e2e/sidebar-background-finish-offscreen.spec.ts index d0063a5ec71e3..1e0259a1feba3 100644 --- a/apps/desktop/e2e/sidebar-background-finish-offscreen.spec.ts +++ b/apps/desktop/e2e/sidebar-background-finish-offscreen.spec.ts @@ -22,7 +22,7 @@ import { import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures' const BG_DOT_LABEL = 'Background task running' -const SESSION_RUNNING_DOT_LABEL = 'Session running' +const SESSION_RUNNING_DOT_LABEL = 'Chat running' // Script indices must line up with real chat turns (see sidebar-states.spec.ts). const DISABLE_AUTO_TITLE = 'auxiliary:\n title_generation:\n enabled: false' diff --git a/apps/desktop/e2e/sidebar-search-profile-scope.spec.ts b/apps/desktop/e2e/sidebar-search-profile-scope.spec.ts index 3e750efebc0ef..48df17a10f713 100644 --- a/apps/desktop/e2e/sidebar-search-profile-scope.spec.ts +++ b/apps/desktop/e2e/sidebar-search-profile-scope.spec.ts @@ -79,7 +79,7 @@ async function selectProfile(page: Page, name: string): Promise { async function expectSearchScopedTo(page: Page, profile: keyof typeof MARKER): Promise { const other = profile === 'default' ? PROFILE_B : 'default' - const search = page.getByRole('textbox', { name: 'Search sessions' }) + const search = page.getByRole('textbox', { name: 'Search chats' }) await search.fill('') await search.fill('zebra') diff --git a/apps/desktop/e2e/sidebar-states.spec.ts b/apps/desktop/e2e/sidebar-states.spec.ts index 73c67dda6c8e5..2ecb507bb8806 100644 --- a/apps/desktop/e2e/sidebar-states.spec.ts +++ b/apps/desktop/e2e/sidebar-states.spec.ts @@ -26,7 +26,7 @@ import { /** Background-running dot aria-label (from i18n en.ts). */ const BG_DOT_LABEL = 'Background task running' /** Foreground turn-running dot aria-label. */ -const SESSION_RUNNING_DOT_LABEL = 'Session running' +const SESSION_RUNNING_DOT_LABEL = 'Chat running' /** Finished-unread dot aria-label. */ const UNREAD_DOT_LABEL = 'Finished — unread' diff --git a/apps/desktop/e2e/ui-preferences-seed.ts b/apps/desktop/e2e/ui-preferences-seed.ts new file mode 100644 index 0000000000000..8090d250792be --- /dev/null +++ b/apps/desktop/e2e/ui-preferences-seed.ts @@ -0,0 +1,17 @@ +import * as fs from 'node:fs' +import * as path from 'node:path' + +/** The classic (pre-redesign) shell: the machine-shared rollback choice `store/shell-variant.ts` reads. */ +export const CLASSIC_SHELL = { 'hermes.desktop.agentShell.v1': 'false' } as const + +/** + * Write the machine's `ui-preferences.json` (the on-disk contract in `electron/ui-preferences.ts`) + * before launch. Machine-shared keys hydrate from this file on the first paint, so a value set only in + * localStorage would be overwritten by whatever the store holds. + */ +export function seedUiPreferences(hermesHome: string, values: Record): void { + fs.writeFileSync( + path.join(hermesHome, 'ui-preferences.json'), + JSON.stringify({ version: 1, generation: 'e2e-seed', revision: 1, values }) + ) +} diff --git a/apps/desktop/e2e/unread-dot-restart.spec.ts b/apps/desktop/e2e/unread-dot-restart.spec.ts index 85d4ec2ed3142..7b807f0620922 100644 --- a/apps/desktop/e2e/unread-dot-restart.spec.ts +++ b/apps/desktop/e2e/unread-dot-restart.spec.ts @@ -105,7 +105,7 @@ test.describe('unread dot survives app restart', () => { await fixture.mock.waitForHeldStream() // ── 2. Session B: complete a turn while SELECTED (stays read) ────── - await page.locator('button:has-text("New session")').first().click() + await page.locator('button:has-text("New chat")').first().click() await sendMessage(page, SECOND_PROMPT) // B's reply lands in the open transcript — this session is "read". diff --git a/apps/desktop/e2e/warm-resume-jitter.spec.ts b/apps/desktop/e2e/warm-resume-jitter.spec.ts index 91ee15331935f..03350ae3513c4 100644 --- a/apps/desktop/e2e/warm-resume-jitter.spec.ts +++ b/apps/desktop/e2e/warm-resume-jitter.spec.ts @@ -300,7 +300,7 @@ async function waitForActiveTranscriptWithoutText( /** Stack an empty tab while leaving the current transcript mounted and warm. */ async function openNewSessionTab(page: import('@playwright/test').Page, priorText: string): Promise { - await page.locator('[data-slot="sidebar"] button[aria-label="New session"]').first().click() + await page.locator('[data-slot="sidebar"] button[aria-label="New chat"]').first().click() await waitForActiveTranscriptWithoutText(page, priorText) } diff --git a/apps/desktop/electron/backend-health.ts b/apps/desktop/electron/backend-health.ts index 178100e5dcaff..2eb5ffe71d664 100644 --- a/apps/desktop/electron/backend-health.ts +++ b/apps/desktop/electron/backend-health.ts @@ -1,6 +1,8 @@ // Relative, not `@hermes/shared`: esbuild bundles electron/ without tsconfig paths. import { isHermesCloudUrl } from '../../shared/src/hermes-cloud' +import { shellMessages } from './shell-wording' + // A cold backend boot (plugin discovery + route mounting at web_server import // time) can take 45-60s on slower hardware. A 45s deadline makes first-boot // readiness a coin flip: every lost race tears down a healthy-but-slow backend @@ -57,13 +59,6 @@ export function isConnectionRefusedError(error: unknown): boolean { return (error as { code?: unknown } | null)?.code === 'ECONNREFUSED' } -export const REMOTE_SESSION_EXPIRED_MESSAGE = - 'Your remote gateway session has expired. Open Settings → Gateway and click "Sign in" again.' - -export const REMOTE_UNSIGNED_OAUTH_MESSAGE = - 'Remote Hermes gateway uses OAuth, but you are not signed in. ' + - 'Open Settings → Gateway and click "Sign in", or switch back to Local.' - /** * True for HTTP 502/503/504 from the backend — a server-side fault, not a * connectivity or auth issue. These keep polling in the readiness loop but, @@ -152,7 +147,7 @@ export function makeNousCloudBackendDownError(baseUrl: string, error: unknown): `Nous Cloud agent ${hostname} is down ` + `(HTTP ${serverError.statusCode}: server-side fault). ` + 'Check https://portal.nousresearch.com for backend status, ' + - 'or switch to Local mode in Settings → Gateway. ' + + shellMessages.switchToLocalMode() + 'You can also reach out on Discord at discord.gg/NousResearch ' + 'for immediate assistance. ' + `Original detail: ${detail}` @@ -209,7 +204,7 @@ export function isGatedMissingHealthError(error: unknown): boolean { /** Tag a terminal reauth failure the main process latches and the overlay keys on. */ export function makeReauthRequiredError(detail?: string): Error { - const error = new Error(REMOTE_SESSION_EXPIRED_MESSAGE) as any + const error = new Error(shellMessages.remoteSessionExpired()) as any error.needsOauthLogin = true error.isReauthRequired = true @@ -228,7 +223,7 @@ export function makeReauthRequiredError(detail?: string): Error { * (see gatewayTicketFailure, #95701). */ export function makeUnsignedOauthError(): Error { - const error = new Error(REMOTE_UNSIGNED_OAUTH_MESSAGE) as any + const error = new Error(shellMessages.remoteUnsignedOauth()) as any error.needsOauthLogin = true error.isReauthRequired = true diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.ts index 8713eae8f088e..6003b86d4c922 100644 --- a/apps/desktop/electron/connection-config.ts +++ b/apps/desktop/electron/connection-config.ts @@ -39,6 +39,7 @@ import { PROFILE_ID_ARG_RE } from '../../shared/src/profile-id' import { readStatusCode } from './api-transport' import { sharesHostBackend } from './host-backend-singleton' import { profileCollectionRoute, profileRouteSuffix } from './profile-routes' +import { shellMessages } from './shell-wording' const AT_COOKIE_VARIANTS = ['__Host-hermes_session_at', '__Secure-hermes_session_at', 'hermes_session_at'] const RT_COOKIE_VARIANTS = ['__Host-hermes_session_rt', '__Secure-hermes_session_rt', 'hermes_session_rt'] @@ -289,8 +290,7 @@ async function resolveTestWsUrl(baseUrl, authMode, token, deps: any = {}) { // bearer is named inside gatewayTicketFailure. throw gatewayTicketFailure( error, - 'Reached the gateway over HTTP, but the OAuth session was rejected while minting a WebSocket ticket. ' + - 'Open Settings → Gateway and sign in again.', + shellMessages.ticketSessionRejected(), 'Reached the gateway over HTTP, but could not mint a WebSocket ticket. Check the remote gateway connection and try again.' ) } diff --git a/apps/desktop/electron/feature-flags.test.ts b/apps/desktop/electron/feature-flags.test.ts index 4a4a67f4318f0..9ceb5f8c32b7d 100644 --- a/apps/desktop/electron/feature-flags.test.ts +++ b/apps/desktop/electron/feature-flags.test.ts @@ -6,7 +6,7 @@ import assert from 'node:assert/strict' import { test } from 'vitest' -import { isCanaryTag, releaseTagVersion, resolveFeatureFlags } from './feature-flags' +import { isCanaryTag, releaseTagVersion, resolveFeatureFlags, resolveLaunchFacts } from './feature-flags' const shipsLocalModels: boolean = process.platform === 'win32' || @@ -41,3 +41,23 @@ test('isCanaryTag recognizes canary stamps and rejects stable/dev tags', () => { assert.equal(isCanaryTag(null), false) assert.equal(isCanaryTag(undefined), false) }) + +test('every window of one launch reads the same launch id', () => { + const first = resolveLaunchFacts({ argv: [], canary: false, packaged: true }) + const second = resolveLaunchFacts({ argv: ['--local'], canary: true, packaged: true }) + + assert.equal(typeof first.launchId, 'string') + assert.ok(first.launchId.length > 0) + assert.equal(second.launchId, first.launchId) +}) + +test('--fresh-install is honoured only by an unpackaged app', () => { + assert.equal( + resolveLaunchFacts({ argv: ['--fresh-install'], canary: false, packaged: false }).assumeFreshInstall, + true + ) + assert.equal( + resolveLaunchFacts({ argv: ['--fresh-install'], canary: false, packaged: true }).assumeFreshInstall, + false + ) +}) diff --git a/apps/desktop/electron/feature-flags.ts b/apps/desktop/electron/feature-flags.ts index 29313c4c86770..b1544e9f30a62 100644 --- a/apps/desktop/electron/feature-flags.ts +++ b/apps/desktop/electron/feature-flags.ts @@ -1,3 +1,5 @@ +import { randomUUID } from 'node:crypto' + const featureFlags = { /** Local-models GUI surfaces (settings pane, pickers, statusbar, tips). */ localModels: ({ argv }) => @@ -37,3 +39,22 @@ export interface FeatureFlagInput { export function resolveFeatureFlags(input: FeatureFlagInput): FeatureFlags { return Object.fromEntries(Object.entries(featureFlags).map(([k, v]) => [k, v(input)])) as FeatureFlags } + +/** This main process's identity: every window of one launch reads the same id, a relaunch mints a + * new one. The renderer keys per-launch choices on it (the redesign's rotating artwork). */ +const LAUNCH_ID = randomUUID() + +export interface LaunchFacts extends FeatureFlags { + assumeFreshInstall: boolean + launchId: string +} + +/** What `hermes:feature-flags` answers each window's preload before its first paint. */ +export function resolveLaunchFacts(input: FeatureFlagInput & { packaged: boolean }): LaunchFacts { + return { + ...resolveFeatureFlags(input), + // Dev-only: `--fresh-install` makes onboarding treat this launch as a fresh install. + assumeFreshInstall: !input.packaged && input.argv.includes('--fresh-install'), + launchId: LAUNCH_ID + } +} diff --git a/apps/desktop/electron/hardening.ts b/apps/desktop/electron/hardening.ts index 53aa73fa21680..2cd95ca5f45db 100644 --- a/apps/desktop/electron/hardening.ts +++ b/apps/desktop/electron/hardening.ts @@ -13,6 +13,8 @@ import { DATA_URL_READ_MIN_MAX_MB } from '../../shared/src/data-url-read-max' +import { shellMessages } from './shell-wording' + const DEFAULT_FETCH_TIMEOUT_MS = 30_000 // Remote file.attach sends one base64 JSON-RPC frame. Cap the dedicated attach // reader so the payload still fits uvicorn's raised ws_max_size (384 MiB) @@ -211,7 +213,7 @@ function encryptDesktopSecret(value, safeStorageApi, options: { allowPlainText?: throw new Error( 'Secure token storage is unavailable (no OS keyring service was found), so Hermes Desktop cannot save remote gateway tokens. ' + 'Either enable an OS keyring (e.g. GNOME Keyring or KWallet providing org.freedesktop.secrets) and try again, ' + - 'confirm the plain-text storage option when prompted in Settings → Gateway, ' + + shellMessages.plainTextStoragePrompt() + 'or set HERMES_DESKTOP_REMOTE_URL and HERMES_DESKTOP_REMOTE_TOKEN in your environment.' ) } diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index 33bdfc0f2045c..ed772053079af 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -260,7 +260,7 @@ import { tuiResumeArgs } from './external-terminal' import { f12ShortcutDecision, toF12KeyboardEventPayload } from './f12-shortcut' -import { resolveFeatureFlags } from './feature-flags' +import { resolveLaunchFacts } from './feature-flags' import { installFindShortcut, installFoundInPageForwarder, @@ -578,6 +578,7 @@ import { SESSION_WINDOW_MIN_WIDTH } from './session-windows' import { ensureLoginShellPath } from './shell-path' +import { adoptShellPreference, shellMessages } from './shell-wording' import { removeStaleSingletonLock } from './singleton-lock' import { createSourcePythonBackend, resolveSourceInstallationBackend, type SourceBackend } from './source-backend' import { resolveSourcePython } from './source-python' @@ -610,7 +611,7 @@ import { windowOpacityFor, windowOpacityOptions } from './translucency' -import { uiPreferencesRoot } from './ui-preferences' +import { tryReadUiPreferences, uiPreferencesPath, uiPreferencesRoot } from './ui-preferences' import { registerMachineUiPreferences } from './ui-preferences-ipc' import { UPDATE_HANDOFF_DWELL_MS, @@ -680,6 +681,8 @@ import { createWakeIndicatorWindowController } from './wake-indicator-window' import { guardedWatch } from './watch-storm-breaker' import { windowAcceleratorAction } from './window-accelerator' import { enumerateWindowsFrontToBack, enumerationFailed, readWindowBelow } from './window-below' +import { type WindowChromeKind } from './window-chrome' +import { createWindowChromeBands } from './window-chrome-bands' import { bindWindowChromeEvents } from './window-chrome-events' import { appliedPrimaryWindowRoute, WindowConnectionRouteRegistry } from './window-connection-route' import { registerWindowControlIpc, windowControlState } from './window-controls' @@ -1402,13 +1405,17 @@ const BOOT_FAKE_STEP_MS = (() => { const APP_NAME: string = IDENTITY_APP_NAME || process.env.HERMES_DESKTOP_APP_NAME || 'Hermes' const HUD_WINDOW_TITLE = `${APP_NAME} HUD` -const TITLEBAR_HEIGHT = 34 -const MACOS_TRAFFIC_LIGHTS_HEIGHT = 14 -const WINDOW_BUTTON_POSITION = { - x: 12, - y: TITLEBAR_HEIGHT / 2 - MACOS_TRAFFIC_LIGHTS_HEIGHT / 2 -} +// Native chrome follows the band the renderer draws, from the shell choice in the shared UI +// preferences read before the first window exists, so it is created at the right height. +const windowChrome = createWindowChromeBands({ + isMac: IS_MAC, + portal: adoptShellPreference(tryReadUiPreferences(uiPreferencesPath(uiPreferencesRoot(HERMES_HOME)))?.values), + relayout: win => { + applyTitleBarOverlay(win, getTitleBarOverlayOptions(win)) + sendWindowStateChanged(undefined, win) + } +}) // Right-edge window-control reservation lives in titlebar-overlay-width.ts // (pure + unit-testable); computeNativeOverlayWidth() applies it per platform. @@ -1638,11 +1645,11 @@ const TITLEBAR_OVERLAY_COLOR = 'rgba(1, 0, 0, 0)' // Electron's own overlay drifts its hit-region under RAIL, so the renderer // paints its own min/max/close (wslg-window-controls.tsx) over the // hermes:window-control IPC channel. See titleBarOverlayOptions. -function getTitleBarOverlayOptions(win?) { +function getTitleBarOverlayOptions(win?, kind: WindowChromeKind = windowChrome.kindOf(win)) { return titleBarOverlayOptions({ platform: IS_MAC ? 'mac' : IS_WINDOWS ? 'windows' : IS_WSL ? 'wslg' : 'linux', darwinMajor: DARWIN_MAJOR, - titlebarHeight: TITLEBAR_HEIGHT, + titlebarHeight: windowChrome.titlebarHeightFor(kind), color: TITLEBAR_OVERLAY_COLOR, foreground: rendererTitleBarTheme && isHexColor(rendererTitleBarTheme.foreground) ? rendererTitleBarTheme.foreground : null, @@ -6037,7 +6044,7 @@ function getWindowButtonPosition(win = mainWindow) { return null } - return win?.getWindowButtonPosition?.() || WINDOW_BUTTON_POSITION + return win?.getWindowButtonPosition?.() || windowChrome.buttonPositionFor(windowChrome.kindOf(win)) } function getNativeOverlayWidth() { @@ -7565,9 +7572,7 @@ async function discoverCloudAgents(org?: string) { const portalBaseUrl = resolvePortalBaseUrl() if (!(await hasLivePortalSession())) { - const err = new Error( - 'You are not signed in to Hermes Cloud. Open Settings → Gateway, choose Hermes Cloud, and sign in.' - ) as any + const err = new Error(shellMessages.cloudNotSignedIn()) as any err.needsCloudLogin = true throw err @@ -7616,9 +7621,7 @@ async function discoverCloudAgents(org?: string) { // A 401 means the portal session lapsed (and silent renewal could not // recover it) — surface it as a re-login, not a generic failure. if (error && error.statusCode === 401) { - const err = new Error( - 'Your Hermes Cloud session has expired. Open Settings → Gateway and sign in again.' - ) as any + const err = new Error(shellMessages.cloudSessionExpired()) as any err.needsCloudLogin = true err.cause = error @@ -8756,10 +8759,7 @@ async function buildRemoteConnection( } if (!token) { - throw new Error( - 'Remote Hermes gateway is selected, but no session token is saved. ' + - 'Open Settings → Gateway and save a token, or switch back to Local.' - ) + throw new Error(shellMessages.remoteTokenMissing()) } const wsUrl = buildGatewayWsUrl(baseUrl, token) @@ -11798,7 +11798,7 @@ function spawnSecondaryWindow({ title: 'Hermes', titleBarStyle: 'hidden', titleBarOverlay: getTitleBarOverlayOptions(), - trafficLightPosition: IS_MAC ? WINDOW_BUTTON_POSITION : undefined, + trafficLightPosition: IS_MAC ? windowChrome.buttonPositionFor('chat') : undefined, ...chatWindowSurfaceOptions(), icon, // Don't show until the renderer's first themed paint is ready. macOS @@ -11817,9 +11817,7 @@ function spawnSecondaryWindow({ minimizeToTray.registerWindow(win) translucencyBackedWindows.add(win) - if (IS_MAC) { - win.setWindowButtonPosition?.(WINDOW_BUTTON_POSITION) - } + windowChrome.track(win, 'chat') wireWindowReveal(win) @@ -11902,20 +11900,17 @@ function spawnBrowserWindow(tabId) { minHeight: BROWSER_WINDOW_MIN_HEIGHT, title: 'Hermes', titleBarStyle: 'hidden', - titleBarOverlay: getTitleBarOverlayOptions(), - trafficLightPosition: IS_MAC ? WINDOW_BUTTON_POSITION : undefined, + titleBarOverlay: getTitleBarOverlayOptions(undefined, 'browser'), + trafficLightPosition: IS_MAC ? windowChrome.buttonPositionFor('browser') : undefined, ...chatWindowSurfaceOptions(), icon, show: false, webPreferences: chatWindowWebPreferences(PRELOAD_PATH) }) + windowChrome.track(win, 'browser') translucencyBackedWindows.add(win) - if (IS_MAC) { - win.setWindowButtonPosition?.(WINDOW_BUTTON_POSITION) - } - wireWindowReveal(win) bindWindowChromeEvents(win, sendWindowStateChanged) @@ -12015,7 +12010,7 @@ function createInstanceWindow( title: 'Hermes', titleBarStyle: 'hidden', titleBarOverlay: getTitleBarOverlayOptions(), - trafficLightPosition: IS_MAC ? WINDOW_BUTTON_POSITION : undefined, + trafficLightPosition: IS_MAC ? windowChrome.buttonPositionFor('chat') : undefined, ...chatWindowSurfaceOptions(), icon, show: false, @@ -12030,9 +12025,7 @@ function createInstanceWindow( // Chat-surface registration: see applyWindowTranslucency. translucencyBackedWindows.add(win) - if (IS_MAC) { - win.setWindowButtonPosition?.(WINDOW_BUTTON_POSITION) - } + windowChrome.track(win, 'chat') wireWindowReveal(win) @@ -13106,7 +13099,7 @@ function createWindow() { // macOS it just reserves a content inset alongside the traffic lights. titleBarStyle: 'hidden', titleBarOverlay: getTitleBarOverlayOptions(), - trafficLightPosition: IS_MAC ? WINDOW_BUTTON_POSITION : undefined, + trafficLightPosition: IS_MAC ? windowChrome.buttonPositionFor('chat') : undefined, ...chatWindowSurfaceOptions(), icon, // Hidden until the first themed paint so macOS `vibrancy` (which ignores @@ -13136,9 +13129,9 @@ function createWindow() { // Chat-surface registration: see applyWindowTranslucency. translucencyBackedWindows.add(mainWindow) - if (IS_MAC) { - mainWindow.setWindowButtonPosition?.(WINDOW_BUTTON_POSITION) + windowChrome.track(mainWindow, 'chat') + if (IS_MAC) { // Packaged builds keep the bundle icon so macOS can style it (#73195). if (icon && shouldOverrideDockIcon({ platform: process.platform, isPackaged: app.isPackaged })) { // The window icon is full-bleed for Linux; the Dock wants the mac grid. @@ -16213,15 +16206,11 @@ ipcMain.on('hermes:translucency:support', event => { // flags survive self-relaunches because collectRelaunchArgs only strips // internal flags. ipcMain.on('hermes:feature-flags', (event: IpcMainEvent): void => { - event.returnValue = { - ...resolveFeatureFlags({ - argv: process.argv, - canary: resolveUpdaterChannelFromStamp() === 'canary' - }), - // Dev-only: `--fresh-install` makes onboarding treat this launch as a fresh - // install. Packaged builds never honour it. - assumeFreshInstall: !app.isPackaged && process.argv.includes('--fresh-install') - } + event.returnValue = resolveLaunchFacts({ + argv: process.argv, + canary: resolveUpdaterChannelFromStamp() === 'canary', + packaged: app.isPackaged + }) }) ipcMain.on('hermes:translucency', (_event, payload) => { @@ -16586,7 +16575,10 @@ ipcMain.on('hermes:logs:renderer-error', (_event, report) => { // Pre-paint payloads the preload reads synchronously: the local skin, and this // machine's shared UI preferences (#145213) — see local-skin.ts, ui-preferences.ts. registerLocalSkinIpc(ipcMain, HERMES_HOME, id => windowConnectionRoutes.get(id)?.profile, primaryProfileKey) -registerMachineUiPreferences(HERMES_HOME) +registerMachineUiPreferences(HERMES_HOME, snapshot => { + adoptShellPreference(snapshot.values) + windowChrome.applyPreferences(snapshot.values) +}) // Another writer (the Webapp) changed the shared list: same teardown as a local save/remove. gatewayConnectionsStore.watch({ onRegistry: (changes, { after, before }) => { diff --git a/apps/desktop/electron/native-auth-decisions.ts b/apps/desktop/electron/native-auth-decisions.ts index 0fd5aa1a2828b..bb059722550be 100644 --- a/apps/desktop/electron/native-auth-decisions.ts +++ b/apps/desktop/electron/native-auth-decisions.ts @@ -47,6 +47,7 @@ * pin that contract at the one seam that got it wrong. */ import { readStatusCode } from './api-transport' +import { shellMessages } from './shell-wording' export function resolveJsonBody(body: T): T { return body @@ -143,13 +144,6 @@ export interface AdvertisedAuthProvider { /** Dashboard `basic` auth is username/password; `/api/status` often lists it as a bare string. */ const PASSWORD_PROVIDER_NAMES = new Set(['basic']) -const OAUTH_NOT_SIGNED_IN_MESSAGE = - 'Remote Hermes gateway uses OAuth, but you are not signed in. ' + - 'Open Settings → Gateway and click "Sign in", or switch back to Local.' - -const OAUTH_SESSION_EXPIRED_MESSAGE = - 'Your remote gateway session has expired. Open Settings → Gateway and click "Sign in" again.' - /** * Normalize `/api/auth/providers` objects *or* `/api/status` `auth_providers` * string names into the shape `oauthGuardMayHardFail` understands. @@ -205,7 +199,7 @@ export function normalizeAdvertisedAuthProviders(providers: unknown): Advertised * ticket mint 401s — that must send the user to Sign in, not "expired". */ export function oauthTicketFailureAuthMessage(hasDecryptableNativeSession: boolean): string { - return hasDecryptableNativeSession ? OAUTH_SESSION_EXPIRED_MESSAGE : OAUTH_NOT_SIGNED_IN_MESSAGE + return hasDecryptableNativeSession ? shellMessages.remoteSessionExpired() : shellMessages.remoteUnsignedOauth() } /** diff --git a/apps/desktop/electron/native-oauth-login.ts b/apps/desktop/electron/native-oauth-login.ts index 6179e30fab3a0..cba608dd982e0 100644 --- a/apps/desktop/electron/native-oauth-login.ts +++ b/apps/desktop/electron/native-oauth-login.ts @@ -37,6 +37,7 @@ import { parseLoopbackCallback, parseTokenResponse } from './native-oauth' +import { shellMessages } from './shell-wording' // Loopback login must complete inside this window (user opens browser, // authenticates, gets redirected back). Matches the server-side pending TTL. @@ -189,12 +190,7 @@ export async function runNativeLogin( }) timer = setTimeout(() => { - fail( - new Error( - 'Native sign-in timed out. The browser window may not have completed ' + - 'sign-in; open Settings → Gateway and try again.' - ) - ) + fail(new Error(shellMessages.nativeSignInTimedOut())) }, timeoutMs) log(`[native-oauth] loopback listening on 127.0.0.1:${addr.port}; opening system browser`) diff --git a/apps/desktop/electron/oauth-login-window.test.ts b/apps/desktop/electron/oauth-login-window.test.ts index 6c174c407b0a3..eed2d645247e4 100644 --- a/apps/desktop/electron/oauth-login-window.test.ts +++ b/apps/desktop/electron/oauth-login-window.test.ts @@ -2,6 +2,8 @@ import { afterEach, beforeEach, expect, test, vi } from 'vitest' import { OauthLoginFlights } from './oauth-login-flights' import { type OauthLoginWindowLike, startOauthLoginWindow } from './oauth-login-window' +import { adoptShellPreference } from './shell-wording' +import { SHELL_CHOICE_KEY } from './window-chrome' const GATEWAY = 'https://fedora.example.ts.net' @@ -78,6 +80,7 @@ beforeEach(() => { afterEach(() => { vi.useRealTimers() + adoptShellPreference(null) }) test('an unattended sign-in never shows its window and gives up after the deadline', async () => { @@ -159,6 +162,7 @@ test('a foreground silent sign-in reveals itself when auto-SSO does not finish', }) test('an interactive sign-in opens visible on the provider chooser', () => { + adoptShellPreference({ [SHELL_CHOICE_KEY]: 'false' }) const h = harness() h.start({ silent: false, background: false }) @@ -166,6 +170,14 @@ test('an interactive sign-in opens visible on the provider chooser', () => { expect(h.windows[0].state.loaded).toBe(`${GATEWAY}/login`) }) +test('the redesign titles the sign-in window without the gateway term', () => { + adoptShellPreference({ [SHELL_CHOICE_KEY]: 'true' }) + const h = harness() + + h.start({ silent: false, background: false }) + expect(h.created).toEqual([{ show: true, title: 'Sign in to Hermes' }]) +}) + test('reveal promotes a hidden attempt and lifts its unattended deadline', async () => { const h = harness() const attempt = h.start({ silent: true, background: true }) diff --git a/apps/desktop/electron/oauth-login-window.ts b/apps/desktop/electron/oauth-login-window.ts index 8b0d05920f79e..83dc3153ad897 100644 --- a/apps/desktop/electron/oauth-login-window.ts +++ b/apps/desktop/electron/oauth-login-window.ts @@ -19,6 +19,7 @@ */ import type { LoginAttempt } from './oauth-login-flights' +import { shellMessages } from './shell-wording' export interface OauthLoginWindowLike { destroy: () => void @@ -115,7 +116,7 @@ export function startOauthLoginWindow( try { win = deps.createWindow({ session, - title: silent ? 'Connecting to Hermes Cloud agent…' : 'Sign in to Hermes gateway', + title: silent ? 'Connecting to Hermes Cloud agent…' : shellMessages.oauthWindowTitle(), // Silent windows start hidden: the auto-SSO chain normally finishes // in well under a second and never needs to be seen. show: !silent && !hiddenRecovery diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts index 76f705decab6a..0eb892447c56b 100644 --- a/apps/desktop/electron/preload.ts +++ b/apps/desktop/electron/preload.ts @@ -15,7 +15,7 @@ const translucencySupport = ipcRenderer.sendSync('hermes:translucency:support') const hudWindowing = ipcRenderer.sendSync('hermes:hud:windowing') const hudNativeDrag = hudWindowing?.nativeDrag === true -const launchFlags: { localModels?: boolean; assumeFreshInstall?: boolean } | undefined = +const launchFlags: { localModels?: boolean; assumeFreshInstall?: boolean; launchId?: string } | undefined = ipcRenderer.sendSync('hermes:feature-flags') // Local, sanitized skin payload for the first renderer theme paint. This does @@ -38,6 +38,8 @@ contextBridge.exposeInMainWorld('hermesDesktop', { // Dev-only launch fact: an unpackaged app started with --fresh-install, so // onboarding treats this launch as a fresh install. Always false when packaged. assumeFreshInstall: launchFlags?.assumeFreshInstall === true, + // This app launch's id: the same in every window until the app quits. + launchId: typeof launchFlags?.launchId === 'string' ? launchFlags.launchId : undefined, localSkin: localSkin && typeof localSkin === 'object' ? localSkin : null, uiPreferences: { snapshot: uiPreferencesSnapshot && typeof uiPreferencesSnapshot === 'object' ? uiPreferencesSnapshot : null, diff --git a/apps/desktop/electron/shell-wording.test.ts b/apps/desktop/electron/shell-wording.test.ts new file mode 100644 index 0000000000000..80272a669abf8 --- /dev/null +++ b/apps/desktop/electron/shell-wording.test.ts @@ -0,0 +1,171 @@ +import { afterEach, describe, expect, test } from 'vitest' + +import { makeNousCloudBackendDownError, makeReauthRequiredError, makeUnsignedOauthError } from './backend-health' +import { migrateV1ToRegistry } from './connection-registry' +import { encryptDesktopSecret } from './hardening' +import { oauthTicketFailureAuthMessage } from './native-auth-decisions' +import { adoptShellPreference, shellMessages } from './shell-wording' +import { SHELL_CHOICE_KEY } from './window-chrome' + +const CLASSIC = { [SHELL_CHOICE_KEY]: 'false' } +const REDESIGN = { [SHELL_CHOICE_KEY]: 'true' } + +const noKeyring = { isEncryptionAvailable: () => false } + +// DESIGN.md › Terminology: the classic nouns the redesign renames (Sessions → Chats, Artifacts → +// Library, Profiles → Agents, Cron / scheduled jobs → Routines, Gateways → Machines). +const CLASSIC_NOUNS = /\b(artifacts?|cron|gateways?|profiles?|scheduled jobs?)\b/i +const SESSION = /\bsessions?\b/i + +/** Messages whose "session" is a sign-in session (or its token), not a conversation. */ +const SIGN_IN_SESSION = new Set([ + 'remoteSessionExpired', + 'ticketSessionRejected', + 'cloudSessionExpired', + 'remoteTokenMissing' +]) + +/** Messages that keep a classic noun on purpose, with why. */ +const KEEPS: Record = { + // The renderer recognises a reauth failure by this phrase (boot-failure-reauth.ts) and the health + // contract asserts it (backend-health.test.ts); it changes with both. + remoteSessionExpired: '"remote gateway session has expired" is matched as a reauth signal' +} + +function cloudDownMessage(): string { + const error = Object.assign(new Error('upstream unavailable'), { statusCode: 503 }) + + return makeNousCloudBackendDownError('https://ares-3009.agents.nousresearch.com', error)!.message +} + +function plainTextRefusal(): string { + try { + encryptDesktopSecret('token', noKeyring) + } catch (error) { + return (error as Error).message + } + + throw new Error('expected the keyring-less save to be refused') +} + +afterEach(() => { + adoptShellPreference(null) +}) + +test('the redesign wording is on until the user rolls the shell back, and follows a later change', () => { + expect(adoptShellPreference(null)).toBe(true) + expect(shellMessages.oauthWindowTitle()).toBe('Sign in to Hermes') + + expect(adoptShellPreference(CLASSIC)).toBe(false) + expect(shellMessages.oauthWindowTitle()).toBe('Sign in to Hermes gateway') + + expect(adoptShellPreference(REDESIGN)).toBe(true) + expect(shellMessages.oauthWindowTitle()).toBe('Sign in to Hermes') +}) + +describe('classic keeps the main-branch wording', () => { + test('in the auth errors main builds', () => { + adoptShellPreference(CLASSIC) + + const expired = 'Your remote gateway session has expired. Open Settings → Gateway and click "Sign in" again.' + + const unsigned = + 'Remote Hermes gateway uses OAuth, but you are not signed in. ' + + 'Open Settings → Gateway and click "Sign in", or switch back to Local.' + + expect(makeReauthRequiredError().message).toBe(expired) + expect(makeUnsignedOauthError().message).toBe(unsigned) + expect(oauthTicketFailureAuthMessage(true)).toBe(expired) + expect(oauthTicketFailureAuthMessage(false)).toBe(unsigned) + expect(cloudDownMessage()).toContain('or switch to Local mode in Settings → Gateway. ') + expect(plainTextRefusal()).toContain('confirm the plain-text storage option when prompted in Settings → Gateway, ') + }) + + test('in every other main-process message', () => { + adoptShellPreference(CLASSIC) + + expect(Object.fromEntries(Object.entries(shellMessages).map(([key, message]) => [key, message()]))).toEqual({ + cloudNotSignedIn: + 'You are not signed in to Hermes Cloud. Open Settings → Gateway, choose Hermes Cloud, and sign in.', + cloudSessionExpired: 'Your Hermes Cloud session has expired. Open Settings → Gateway and sign in again.', + nativeSignInTimedOut: + 'Native sign-in timed out. The browser window may not have completed sign-in; open Settings → Gateway and try again.', + oauthWindowTitle: 'Sign in to Hermes gateway', + plainTextStoragePrompt: 'confirm the plain-text storage option when prompted in Settings → Gateway, ', + remoteSessionExpired: + 'Your remote gateway session has expired. Open Settings → Gateway and click "Sign in" again.', + remoteTokenMissing: + 'Remote Hermes gateway is selected, but no session token is saved. ' + + 'Open Settings → Gateway and save a token, or switch back to Local.', + remoteUnsignedOauth: + 'Remote Hermes gateway uses OAuth, but you are not signed in. ' + + 'Open Settings → Gateway and click "Sign in", or switch back to Local.', + switchToLocalMode: 'or switch to Local mode in Settings → Gateway. ', + ticketSessionRejected: + 'Reached the gateway over HTTP, but the OAuth session was rejected while minting a WebSocket ticket. ' + + 'Open Settings → Gateway and sign in again.' + }) + }) +}) + +describe('the redesign points at Settings → Machines', () => { + test('in the auth errors main builds', () => { + adoptShellPreference(REDESIGN) + + expect(makeReauthRequiredError().message).toBe( + 'Your remote gateway session has expired. Open Settings → Machines and click "Sign in" again.' + ) + expect(oauthTicketFailureAuthMessage(false)).toBe( + 'The remote Hermes machine uses OAuth, but you are not signed in. ' + + 'Open Settings → Machines and click "Sign in", or switch back to Local.' + ) + expect(cloudDownMessage()).toContain('or switch to Local mode in Settings → Machines. ') + expect(plainTextRefusal()).toContain('confirm the plain-text storage option when prompted in Settings → Machines, ') + }) + + test('in every other main-process message', () => { + adoptShellPreference(REDESIGN) + + expect(shellMessages.remoteTokenMissing()).toBe( + 'A remote Hermes machine is selected, but no session token is saved. ' + + 'Open Settings → Machines and save a token, or switch back to Local.' + ) + expect(shellMessages.oauthWindowTitle()).toBe('Sign in to Hermes') + expect(shellMessages.cloudNotSignedIn()).toContain('Open Settings → Machines, choose Hermes Cloud') + }) + + test('with no classic noun in any message, beyond a sign-in session', () => { + adoptShellPreference(REDESIGN) + + const offenders = Object.entries(shellMessages) + .map(([key, message]) => [key, message()] as const) + .filter(([key]) => !(key in KEEPS)) + .filter(([key, text]) => CLASSIC_NOUNS.test(text) || (!SIGN_IN_SESSION.has(key) && SESSION.test(text))) + + expect(offenders).toEqual([]) + }) + + test('whose keeps are real messages that still carry what they keep', () => { + adoptShellPreference(REDESIGN) + + const messages: Record string> = shellMessages + + for (const key of SIGN_IN_SESSION) { + expect(messages[key]?.()).toMatch(SESSION) + } + + for (const key of Object.keys(KEEPS)) { + expect(messages[key]?.()).toMatch(CLASSIC_NOUNS) + } + }) +}) + +test("persisted data never takes shell wording: a host-less remote stores main's default label", () => { + for (const shell of [CLASSIC, REDESIGN]) { + adoptShellPreference(shell) + + const registry = migrateV1ToRegistry({ mode: 'remote', remote: { url: 'not a url', authMode: 'token' } }) + + expect(registry.connections.find(connection => connection.kind === 'remote')?.label).toBe('Remote gateway') + } +}) diff --git a/apps/desktop/electron/shell-wording.ts b/apps/desktop/electron/shell-wording.ts new file mode 100644 index 0000000000000..7cb01977a08ed --- /dev/null +++ b/apps/desktop/electron/shell-wording.ts @@ -0,0 +1,68 @@ +// Main-process copy the redesigned shell rewords (Gateway → Machines). Classic keeps +// `main`'s text verbatim; the redesign gets its own. The renderer's catalog does this for its +// strings (src/i18n/redesign); these messages are built in main, so they follow the same +// shell choice from the machine's shared UI preferences (window-chrome.ts), adopted where +// main reads and re-applies it. Messages resolve at use time, so a toggle needs no restart. + +import { portalShellPreferred } from './window-chrome' + +let portalShell = portalShellPreferred(null) + +/** Adopt the shell choice from the shared UI preferences; returns whether it is the redesign. */ +export function adoptShellPreference(values: Readonly> | null | undefined): boolean { + portalShell = portalShellPreferred(values) + + return portalShell +} + +const pick = (classic: string, redesign: string) => (portalShell ? redesign : classic) + +export const shellMessages = { + remoteSessionExpired: () => + pick( + 'Your remote gateway session has expired. Open Settings → Gateway and click "Sign in" again.', + 'Your remote gateway session has expired. Open Settings → Machines and click "Sign in" again.' + ), + remoteUnsignedOauth: () => + pick( + 'Remote Hermes gateway uses OAuth, but you are not signed in. ' + + 'Open Settings → Gateway and click "Sign in", or switch back to Local.', + 'The remote Hermes machine uses OAuth, but you are not signed in. ' + + 'Open Settings → Machines and click "Sign in", or switch back to Local.' + ), + switchToLocalMode: () => + pick('or switch to Local mode in Settings → Gateway. ', 'or switch to Local mode in Settings → Machines. '), + ticketSessionRejected: () => + pick( + 'Reached the gateway over HTTP, but the OAuth session was rejected while minting a WebSocket ticket. ' + + 'Open Settings → Gateway and sign in again.', + 'Reached the machine over HTTP, but the OAuth session was rejected while minting a WebSocket ticket. ' + + 'Open Settings → Machines and sign in again.' + ), + plainTextStoragePrompt: () => + pick( + 'confirm the plain-text storage option when prompted in Settings → Gateway, ', + 'confirm the plain-text storage option when prompted in Settings → Machines, ' + ), + cloudNotSignedIn: () => + pick( + 'You are not signed in to Hermes Cloud. Open Settings → Gateway, choose Hermes Cloud, and sign in.', + 'You are not signed in to Hermes Cloud. Open Settings → Machines, choose Hermes Cloud, and sign in.' + ), + cloudSessionExpired: () => + pick( + 'Your Hermes Cloud session has expired. Open Settings → Gateway and sign in again.', + 'Your Hermes Cloud session has expired. Open Settings → Machines and sign in again.' + ), + remoteTokenMissing: () => + pick( + 'Remote Hermes gateway is selected, but no session token is saved. ' + + 'Open Settings → Gateway and save a token, or switch back to Local.', + 'A remote Hermes machine is selected, but no session token is saved. ' + + 'Open Settings → Machines and save a token, or switch back to Local.' + ), + nativeSignInTimedOut: () => + 'Native sign-in timed out. The browser window may not have completed ' + + pick('sign-in; open Settings → Gateway and try again.', 'sign-in; open Settings → Machines and try again.'), + oauthWindowTitle: () => pick('Sign in to Hermes gateway', 'Sign in to Hermes') +} diff --git a/apps/desktop/electron/ui-preferences-ipc.ts b/apps/desktop/electron/ui-preferences-ipc.ts index 253cabc42f91b..00e2b75610003 100644 --- a/apps/desktop/electron/ui-preferences-ipc.ts +++ b/apps/desktop/electron/ui-preferences-ipc.ts @@ -2,15 +2,21 @@ // every app window hears about a change, whoever made it. import { BrowserWindow, ipcMain } from 'electron' -import { registerUiPreferencesIpc } from './ui-preferences' +import { registerUiPreferencesIpc, type UiPreferencesSnapshot } from './ui-preferences' /** `hermesHome` is main's resolved ROOT home (never a profile's), the one the - * Webapp's Python server resolves too. */ -export function registerMachineUiPreferences(hermesHome: string): () => void { + * Webapp's Python server resolves too. `onChange` lets main follow the + * preferences it acts on itself (the shell's titlebar band). */ +export function registerMachineUiPreferences( + hermesHome: string, + onChange: (snapshot: UiPreferencesSnapshot) => void +): () => void { return registerUiPreferencesIpc({ ipcMain, hermesHome, broadcast: snapshot => { + onChange(snapshot) + for (const window of BrowserWindow.getAllWindows()) { window.webContents.send('hermes:ui-preferences:changed', snapshot) } diff --git a/apps/desktop/electron/ui-preferences.ts b/apps/desktop/electron/ui-preferences.ts index d95c16b0d800a..ef783b9ed0871 100644 --- a/apps/desktop/electron/ui-preferences.ts +++ b/apps/desktop/electron/ui-preferences.ts @@ -113,9 +113,10 @@ export function readUiPreferences(file: string): UiPreferencesSnapshot { return readStore(file).snapshot } -/** For the paths that must never throw (the preload's first paint, the - * watcher): an unreadable store is simply not known yet. */ -function tryReadUiPreferences(file: string): null | UiPreferencesSnapshot { +/** The store, or null when it cannot be read right now. For the paths that must + * never throw (the preload's first paint, the watcher, main's first window): + * an unreadable store is simply not known yet. */ +export function tryReadUiPreferences(file: string): null | UiPreferencesSnapshot { try { return readUiPreferences(file) } catch { diff --git a/apps/desktop/electron/window-chrome-bands.test.ts b/apps/desktop/electron/window-chrome-bands.test.ts new file mode 100644 index 0000000000000..923b9a2100565 --- /dev/null +++ b/apps/desktop/electron/window-chrome-bands.test.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict' + +import { test } from 'vitest' + +import { CLASSIC_TITLEBAR_HEIGHT, PORTAL_TITLEBAR_HEIGHT, SHELL_CHOICE_KEY, windowButtonPosition } from './window-chrome' +import { createWindowChromeBands } from './window-chrome-bands' + +function fakeWindow() { + const closed: (() => void)[] = [] + + return { + positions: [] as { x: number; y: number }[], + close: () => closed.forEach(listener => listener()), + isDestroyed: () => false, + once: (_event: 'closed', listener: () => void) => closed.push(listener), + setWindowButtonPosition(position: { x: number; y: number }) { + this.positions.push(position) + } + } +} + +test('a shell flip moves every open shell window to its new band; the Browser stays classic', () => { + const relaid: unknown[] = [] + const bands = createWindowChromeBands({ isMac: true, portal: true, relayout: win => relaid.push(win) }) + const chat = fakeWindow() + const browser = fakeWindow() + + bands.track(chat, 'chat') + bands.track(browser, 'browser') + assert.deepEqual(chat.positions, [windowButtonPosition(PORTAL_TITLEBAR_HEIGHT)]) + assert.deepEqual(browser.positions, [windowButtonPosition(CLASSIC_TITLEBAR_HEIGHT)]) + assert.equal(bands.titlebarHeightFor(bands.kindOf(chat)), PORTAL_TITLEBAR_HEIGHT) + + bands.applyPreferences({ [SHELL_CHOICE_KEY]: 'false' }) + assert.equal(bands.titlebarHeightFor(bands.kindOf(chat)), CLASSIC_TITLEBAR_HEIGHT) + assert.deepEqual(chat.positions.at(-1), windowButtonPosition(CLASSIC_TITLEBAR_HEIGHT)) + assert.deepEqual(relaid, [chat, browser]) + + // An unrelated preference write is not a flip. + bands.applyPreferences({ [SHELL_CHOICE_KEY]: 'false', other: '1' }) + assert.equal(relaid.length, 2) + + chat.close() + bands.applyPreferences({}) + assert.deepEqual(relaid, [chat, browser, browser]) +}) + +test('only macOS seats traffic lights', () => { + const bands = createWindowChromeBands({ isMac: false, portal: true, relayout: () => undefined }) + const win = fakeWindow() + + bands.track(win, 'chat') + assert.deepEqual(win.positions, []) +}) diff --git a/apps/desktop/electron/window-chrome-bands.ts b/apps/desktop/electron/window-chrome-bands.ts new file mode 100644 index 0000000000000..8f818739c822f --- /dev/null +++ b/apps/desktop/electron/window-chrome-bands.ts @@ -0,0 +1,80 @@ +// The live side of window-chrome.ts: which band each open window is drawn +// with, and moving every one of them when the shell choice changes (no +// restart). Main supplies the platform overlay/notify step as `relayout`. +// +// The first window is created from the shared store read at startup. The +// shell choice has been a shared key since it existed, so a renderer cache +// that says classic while the store has nothing needs a failed host write; +// even then the renderer's sync lands the value and `applyPreferences` moves +// the window to its band live, so nothing is copied ahead of window creation. + +import { + portalShellPreferred, + windowButtonPosition, + type WindowChromeKind, + windowTitlebarHeight +} from './window-chrome' + +type ButtonPosition = ReturnType + +/** The slice of BrowserWindow this needs. */ +export interface BandWindow { + isDestroyed(): boolean + once(event: 'closed', listener: () => void): unknown + setWindowButtonPosition?(position: ButtonPosition): void +} + +interface WindowChromeBandsOptions { + isMac: boolean + /** The shell choice read from the shared UI preferences before the first window exists. */ + portal: boolean + /** Re-apply the platform overlay and tell the renderer where its controls now sit. */ + relayout: (win: W) => void +} + +export function createWindowChromeBands({ isMac, portal, relayout }: WindowChromeBandsOptions) { + let portalShell = portal + const bandWindows = new Set() + const classicChromeWindows = new WeakSet() + + const titlebarHeightFor = (kind: WindowChromeKind) => windowTitlebarHeight({ kind, portal: portalShell }) + const kindOf = (win?: null | object): WindowChromeKind => (win && classicChromeWindows.has(win) ? 'browser' : 'chat') + const buttonPositionFor = (kind: WindowChromeKind) => windowButtonPosition(titlebarHeightFor(kind)) + + function placeButtons(win: W) { + if (isMac && !win.isDestroyed()) { + win.setWindowButtonPosition?.(buttonPositionFor(kindOf(win))) + } + } + + return { + buttonPositionFor, + kindOf, + titlebarHeightFor, + /** Register a window drawn with a titlebar band and seat its traffic lights. */ + track(win: W, kind: WindowChromeKind) { + if (kind === 'browser') { + classicChromeWindows.add(win) + } + + bandWindows.add(win) + win.once('closed', () => bandWindows.delete(win)) + placeButtons(win) + }, + /** The shared UI preferences changed: move every open window to its new band. */ + applyPreferences(values: Readonly> | null | undefined) { + const next = portalShellPreferred(values) + + if (next === portalShell) { + return + } + + portalShell = next + + for (const win of bandWindows) { + placeButtons(win) + relayout(win) + } + } + } +} diff --git a/apps/desktop/electron/window-chrome.test.ts b/apps/desktop/electron/window-chrome.test.ts new file mode 100644 index 0000000000000..4862a7024bd97 --- /dev/null +++ b/apps/desktop/electron/window-chrome.test.ts @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict' + +import { test } from 'vitest' + +import { + CLASSIC_TITLEBAR_HEIGHT, + PORTAL_TITLEBAR_HEIGHT, + portalShellPreferred, + SHELL_CHOICE_KEY, + windowButtonPosition, + windowTitlebarHeight +} from './window-chrome' + +test('the redesign is on until the user rolls it back', () => { + assert.equal(portalShellPreferred(null), true) + assert.equal(portalShellPreferred({}), true) + assert.equal(portalShellPreferred({ [SHELL_CHOICE_KEY]: 'true' }), true) + assert.equal(portalShellPreferred({ [SHELL_CHOICE_KEY]: 'false' }), false) +}) + +test('shell windows follow the shell; the popped-out Browser stays classic', () => { + assert.equal(windowTitlebarHeight({ kind: 'chat', portal: true }), PORTAL_TITLEBAR_HEIGHT) + assert.equal(windowTitlebarHeight({ kind: 'chat', portal: false }), CLASSIC_TITLEBAR_HEIGHT) + assert.equal(windowTitlebarHeight({ kind: 'browser', portal: true }), CLASSIC_TITLEBAR_HEIGHT) +}) + +test('traffic lights sit centred in whichever band the window draws', () => { + for (const height of [CLASSIC_TITLEBAR_HEIGHT, PORTAL_TITLEBAR_HEIGHT]) { + const { y } = windowButtonPosition(height) + + assert.ok(Math.abs(y + 7 - height / 2) <= 0.5) + } + + assert.deepEqual(windowButtonPosition(CLASSIC_TITLEBAR_HEIGHT), { x: 12, y: 10 }) + assert.deepEqual(windowButtonPosition(PORTAL_TITLEBAR_HEIGHT), { x: 23, y: 23 }) +}) diff --git a/apps/desktop/electron/window-chrome.ts b/apps/desktop/electron/window-chrome.ts new file mode 100644 index 0000000000000..d5de632850871 --- /dev/null +++ b/apps/desktop/electron/window-chrome.ts @@ -0,0 +1,40 @@ +// The titlebar band each app window's native chrome is laid out for. The +// renderer draws the band (src/app/shell/titlebar.ts, same numbers); main +// places the macOS traffic lights and sizes the Windows/Linux caption overlay +// to match it, from the shell choice in the machine's shared UI preferences +// (ui-preferences.ts) — read at window creation so the first paint is right, +// and re-applied when the choice changes. + +/** Shared-preferences key of the redesign opt-out (src/store/shell-variant.ts). */ +export const SHELL_CHOICE_KEY = 'hermes.desktop.agentShell.v1' + +/** Classic: Electron's compact band. */ +export const CLASSIC_TITLEBAR_HEIGHT = 34 +/** Redesign: Figma's 60px header (906:19463). */ +export const PORTAL_TITLEBAR_HEIGHT = 60 +/** Native traffic-light cluster height on macOS. */ +export const MACOS_TRAFFIC_LIGHTS_HEIGHT = 14 + +/** Windows that render the app shell follow the shell choice; the popped-out + * Browser keeps the classic layout in every mode (as the renderer does). */ +export type WindowChromeKind = 'browser' | 'chat' + +/** The redesign is on unless the user rolled it back (`'false'`), exactly as + * the renderer's `$portalPreferred` decodes the same key. */ +export function portalShellPreferred(values: Readonly> | null | undefined): boolean { + return values?.[SHELL_CHOICE_KEY] !== 'false' +} + +export function windowTitlebarHeight({ kind, portal }: { kind: WindowChromeKind; portal: boolean }): number { + return portal && kind === 'chat' ? PORTAL_TITLEBAR_HEIGHT : CLASSIC_TITLEBAR_HEIGHT +} + +/** Traffic lights vertically centred in the band. The redesign seats them in + * its 60px rail column at Figma's inset (906:19415: first light's left edge + * ≈ x 23, centre y ≈ 30). */ +export function windowButtonPosition(titlebarHeight: number): { x: number; y: number } { + return { + x: titlebarHeight === PORTAL_TITLEBAR_HEIGHT ? 23 : 12, + y: Math.round(titlebarHeight / 2 - MACOS_TRAFFIC_LIGHTS_HEIGHT / 2) + } +} diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjs index 1a9728a8e12d7..5f313028ddb0c 100644 --- a/apps/desktop/eslint.config.mjs +++ b/apps/desktop/eslint.config.mjs @@ -1,6 +1,81 @@ import shared from '../../eslint.config.shared.mjs' import globals from 'globals' +// Drift guard G2 (DESIGN.md "Portal design language"): redesign-only TSX takes its look from the +// tokens in src/app/redesign/tokens/, not from arbitrary Tailwind values. Flags, inside className / +// cn() strings: an arbitrary text, leading, tracking, radius, colour, ring, shadow, fill or stroke value +// unless it is a bare token read (a var() of a token), Tailwind's own text sizes and scaled radii (the +// redesign's --radius-scalar makes those land between Figma's steps), and hex colours. Arbitrary layout +// values (grid templates, min() widths) are fine. +const VISUAL_ARBITRARY = + /^-?(text|leading|tracking|rounded(-[a-z]{1,2})?|bg|border(-[a-z]{1,2})?|ring|shadow|fill|stroke|outline|decoration)-\[(.+)\]$/ +const TOKEN_READ = /^(?:[a-z-]+:)?var\(--[\w-]+(?:,[^\]]*)?\)$/ +const SCALED = /^(rounded(-[a-z]{1,2})?-(xs|sm|md|lg|xl|2xl|3xl)|text-(xs|sm|base|lg))$/ +const CLASS_CALLS = new Set(['cn', 'clsx', 'cva', 'twMerge']) + +const utilityOf = token => { + let depth = 0 + let cut = 0 + + for (let i = 0; i < token.length; i++) { + const ch = token[i] + depth += ch === '[' ? 1 : ch === ']' ? -1 : 0 + + if (ch === ':' && depth === 0) { + cut = i + 1 + } + } + + return token.slice(cut).replace(/^!/, '') +} + +const offendingClass = token => { + const utility = utilityOf(token) + const arbitrary = VISUAL_ARBITRARY.exec(utility) + + if (arbitrary) { + return !TOKEN_READ.test(arbitrary[4]) + } + + return SCALED.test(utility) || /#[0-9a-f]{3,8}\b/i.test(utility) +} + +const inClassContext = ancestors => + ancestors.some( + node => + (node.type === 'JSXAttribute' && ['className', 'class'].includes(node.name.name)) || + (node.type === 'CallExpression' && CLASS_CALLS.has(node.callee.name)) + ) + +const noPortalArbitrary = { + meta: { + type: 'suggestion', + messages: { + arbitrary: + '`{{cls}}` restates a design value in redesign-only markup. Use a token-backed class or a CSS rule that reads src/app/redesign/tokens/ (DESIGN.md "Portal design language").' + }, + schema: [] + }, + create(context) { + const check = (node, text) => { + if (!inClassContext(context.sourceCode.getAncestors(node))) { + return + } + + for (const cls of text.split(/\s+/).filter(Boolean)) { + if (offendingClass(cls)) { + context.report({ node, messageId: 'arbitrary', data: { cls } }) + } + } + } + + return { + Literal: node => typeof node.value === 'string' && check(node, node.value), + TemplateElement: node => check(node, node.value.cooked ?? '') + } + } +} + export default [ ...shared, { @@ -34,6 +109,21 @@ export default [ ] } }, + { + // Redesign-only markup (mixed files with a classic branch are not judged yet). Warn while the + // existing sites burn down (DESIGN.md "To unify in Phase B"); then it becomes an error. + files: [ + 'src/app/redesign/**/*.tsx', + 'src/app/chat/sidebar/portal/**/*.tsx', + 'src/app/agent-settings/**/*.tsx', + 'src/components/portal/**/*.tsx', + 'src/app/settings/settings-card.tsx', + 'src/app/settings/appearance-overview.tsx' + ], + ignores: ['src/**/*.test.tsx', 'src/app/agent-settings/classic-settings.tsx'], + plugins: { 'hermes-desktop': { rules: { 'no-portal-arbitrary': noPortalArbitrary } } }, + rules: { 'hermes-desktop/no-portal-arbitrary': 'warn' } + }, { files: ['**/*.test.tsx'], rules: { diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e704c79b61710..5dbab9378bfb2 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -141,6 +141,7 @@ "nanostores": "1.4.2", "node-pty": "1.1.0", "pele": "1.13.0", + "pixelarticons": "2.4.2", "proxy-from-env": "2.1.0", "qrcode": "1.5.4", "radix-ui": "1.7.0", diff --git a/apps/desktop/src/api/canonical-deadline.test.ts b/apps/desktop/src/api/canonical-deadline.test.ts index 3395d4e612765..0f662cf1845b8 100644 --- a/apps/desktop/src/api/canonical-deadline.test.ts +++ b/apps/desktop/src/api/canonical-deadline.test.ts @@ -3,7 +3,9 @@ import { afterEach, expect, test, vi } from 'vitest' import { HermesGateway } from './client' -afterEach(() => { vi.restoreAllMocks() }) +afterEach(() => { + vi.restoreAllMocks() +}) test.each([60, 120])('compress follow-up spends only the remaining caller budget after %i ms', async elapsed => { let now = 1_000 @@ -27,7 +29,13 @@ test.each([60, 120])('compress follow-up spends only the remaining caller budget await client.request('session.resume', { session_id: 's', profile: 'sibling' }) calls.length = 0 const controller = new AbortController() - const compression = client.request('session.compress', { session_id: 's', profile: 'sibling' }, 100, controller.signal) + + const compression = client.request( + 'session.compress', + { session_id: 's', profile: 'sibling' }, + 100, + controller.signal + ) if (elapsed < 100) { await expect(compression).resolves.toHaveProperty('messages') @@ -64,12 +72,19 @@ test('the prerequisite attachment shares the caller deadline and cancellation', const controller = new AbortController() try { - await client.request('prompt.submit', { session_id: 's', submission_id: 'one', text: 'hello' }, 100, controller.signal) + await client.request( + 'prompt.submit', + { session_id: 's', submission_id: 'one', text: 'hello' }, + 100, + controller.signal + ) expect(calls).toEqual([ { method: 'session.resume', timeout: 100, signal: controller.signal }, { method: 'prompt.submit', timeout: 40, signal: controller.signal } ]) - } finally { client.close() } + } finally { + client.close() + } }) test('a prerequisite attachment resolves the launch profile alias before preparing a mutation', async () => { @@ -79,23 +94,39 @@ test('a prerequisite attachment resolves the launch profile alias before prepari calls.push({ method, params }) if (method === 'session.resume') { - return { session_id: 's', revision: 3, execution_generation: 2, replay_epoch: 'named-owner', - messages: [], info: { profile_name: 'work', profile_id: '/profiles/work' } } as never + return { + session_id: 's', + revision: 3, + execution_generation: 2, + replay_epoch: 'named-owner', + messages: [], + info: { profile_name: 'work', profile_id: '/profiles/work' } + } as never } - return { session_id: 's', revision: 4, operation: 'branch', branched_session_id: 'child', copied_messages: 0 } as never + return { + session_id: 's', + revision: 4, + operation: 'branch', + branched_session_id: 'child', + copied_messages: 0 + } as never }) const client = new HermesGateway() await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=fixture') try { - await expect(client.request('session.branch_stored', { parent_session_id: 's' })).resolves.toMatchObject({ session_id: 'child' }) + await expect(client.request('session.branch_stored', { parent_session_id: 's' })).resolves.toMatchObject({ + session_id: 'child' + }) expect(calls[1]).toMatchObject({ method: 'session.mutate', params: { profile: 'work', expected_revision: 3 } }) - } finally { client.close() } + } finally { + client.close() + } }) test('a zero timeout is no deadline on the canonical socket: the request is sent and waits (F3)', async () => { - // onboarding.state / onboarding.start pass 0 (NO_DEADLINE): the shared channel arms no timer for 0. + // onboarding.state passes 0 (NO_DEADLINE): the shared channel arms no timer for 0. // The canonical wrapper used to read 0 as an already-spent deadline and throw before sending, so the // first-run decision settled at once and the setup card covered a configured home until readiness answered. vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue() @@ -105,7 +136,9 @@ test('a zero timeout is no deadline on the canonical socket: the request is sent vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async (method, _params, timeout) => { calls.push({ method, timeout }) - return new Promise(resolve => { answer = resolve }) as never + return new Promise(resolve => { + answer = resolve + }) as never }) const client = new HermesGateway() await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=fixture') @@ -115,5 +148,7 @@ test('a zero timeout is no deadline on the canonical socket: the request is sent await vi.waitFor(() => expect(calls).toEqual([{ method: 'onboarding.state', timeout: 0 }])) answer({ run: false, eligible: false }) await expect(state).resolves.toEqual({ run: false, eligible: false }) - } finally { client.close() } + } finally { + client.close() + } }) diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts index ac0831a636b02..1721c2d426956 100644 --- a/apps/desktop/src/api/client.ts +++ b/apps/desktop/src/api/client.ts @@ -12,7 +12,15 @@ import { map, type MapStore } from 'nanostores' import type { HermesApiRequest } from '@/global' import { desktopClientIdentity } from '@/lib/client-identity' -import { CanonicalDesktopProtocol, canonicalProfile, canonicalPromptParams, canonicalSessionKey, openGatewaySocket, recordCanonicalOwner, splitRewindSubmit } from './canonical-protocol' +import { + CanonicalDesktopProtocol, + canonicalProfile, + canonicalPromptParams, + canonicalSessionKey, + openGatewaySocket, + recordCanonicalOwner, + splitRewindSubmit +} from './canonical-protocol' import { DialReadiness, GATEWAY_NOT_CONNECTED_MESSAGE, remainingRequestBudget } from './dial-readiness' // Desktop startup fires a burst of read-only data calls (config, profiles, @@ -45,7 +53,10 @@ export { GATEWAY_NOT_CONNECTED_MESSAGE } // answered through `approval.respond` / `clarify.respond`. The renderer only // knows server→client REQUESTS (#110521), so each prompt event is delivered to // the same `onRequest` registry as a request whose `respond` issues the RPC. -const CANONICAL_PROMPT_EVENTS: Record = { 'approval.request': 'approval', 'clarify.request': 'clarify' } +const CANONICAL_PROMPT_EVENTS: Record = { + 'approval.request': 'approval', + 'clarify.request': 'clarify' +} const ATTACH_REQUIRED = new Set([ 'prompt.submit', @@ -79,13 +90,15 @@ const LEGACY_STRIP: Record = { function legacyParams(method: string, params: Record): Record { const strip = LEGACY_STRIP[method] - if (!strip || !strip.some(key => key in params)) { return params } + if (!strip || !strip.some(key => key in params)) { + return params + } return Object.fromEntries(Object.entries(params).filter(([key]) => !strip.includes(key))) } // A caller timeout of 0 (or less) means no deadline, as in the shared channel, which arms no timer -// for it. Callers that wait on a way-out offer instead (onboarding.state / onboarding.start) pass 0. +// The onboarding due check can pass 0 while its boot-overlay way out remains available. function requestDeadline(timeoutMs: number | undefined): number { const budget = timeoutMs ?? DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS @@ -122,17 +135,26 @@ export class HermesGateway extends JsonRpcGatewayClient { } } - private deliverCanonicalPrompt(event: { type: string; session_id?: string; profile?: string; payload?: unknown }, replayed: boolean) { + private deliverCanonicalPrompt( + event: { type: string; session_id?: string; profile?: string; payload?: unknown }, + replayed: boolean + ) { const kind = CANONICAL_PROMPT_EVENTS[event.type] const p = event.payload as Record | undefined const sid = event.session_id - if (!kind || !p || !sid || typeof p.prompt_id !== 'string') { return } + if (!kind || !p || !sid || typeof p.prompt_id !== 'string') { + return + } + const id = p.prompt_id const profile = canonicalProfile(event.profile) const generation = this.connectionGeneration - if (this.deliveredPrompts.has(id)) { return } + if (this.deliveredPrompts.has(id)) { + return + } + this.deliveredPrompts.set(id, { sessionId: sid, profile }) const params = canonicalPromptParams(kind, sid, p) @@ -144,42 +166,64 @@ export class HermesGateway extends JsonRpcGatewayClient { params, replayed, respond: result => { - if (settled || generation !== this.connectionGeneration) { return } + if (settled || generation !== this.connectionGeneration) { + return + } + settled = true // A clarify reply without an answer (skip, Stop, cancel) is the empty answer the // authority records as skipped; `clarify.respond` refuses a missing field. - const answer = kind === 'clarify' - ? { answer: typeof result.answer === 'string' ? result.answer : '' } - : { choice: result.choice } - - void this.request(`${kind}.respond`, { session_id: sid, profile, request_id: id, ...answer }) - .catch(() => this.recoverCanonicalPrompt(id, sid, profile, generation)) + const answer = + kind === 'clarify' + ? { answer: typeof result.answer === 'string' ? result.answer : '' } + : { choice: result.choice } + + void this.request(`${kind}.respond`, { session_id: sid, profile, request_id: id, ...answer }).catch(() => + this.recoverCanonicalPrompt(id, sid, profile, generation) + ) }, // A card this window declined (a stopped session) is not delivered: the next authoritative // snapshot that still lists the prompt shows it again. Only answered prompts stay deduplicated. fail: () => { - if (settled) { return } + if (settled) { + return + } + settled = true - if (generation === this.connectionGeneration) { this.deliveredPrompts.delete(id) } + if (generation === this.connectionGeneration) { + this.deliveredPrompts.delete(id) + } } } recordCanonicalOwner(request, this.displayProfiles.get(canonicalSessionKey(sid, profile)) ?? profile) for (const handler of this.promptHandlers) { - if (handler(request) !== false) { return } + if (handler(request) !== false) { + return + } } } - private async recoverCanonicalPrompt(id: string, sessionId: string, profile: string, generation: number): Promise { - if (generation !== this.connectionGeneration || !this.deliveredPrompts.has(id)) { return } + private async recoverCanonicalPrompt( + id: string, + sessionId: string, + profile: string, + generation: number + ): Promise { + if (generation !== this.connectionGeneration || !this.deliveredPrompts.has(id)) { + return + } + this.deliveredPrompts.delete(id) // A lost reply may have committed. Reopen a card only if the authority's // snapshot still lists it; never resend an approval from a cached event. - try { await this.request('session.resume', { session_id: sessionId, profile }) } catch { + try { + await this.request('session.resume', { session_id: sessionId, profile }) + } catch { // A disconnected socket will reconcile its pending prompts on reattach. } } @@ -204,7 +248,9 @@ export class HermesGateway extends JsonRpcGatewayClient { const cursors = this.getSeqWatermarks() for (const [epoch, owner] of this.replayProfiles) { - if (!(owner.sessionId in cursors)) { this.replayProfiles.delete(epoch) } + if (!(owner.sessionId in cursors)) { + this.replayProfiles.delete(epoch) + } } } @@ -224,7 +270,9 @@ export class HermesGateway extends JsonRpcGatewayClient { const parked = this.canonical && event.session_id ? this.parkedFrames.get(key) : undefined const deliver = () => { - if (!this.canonical || this.normalizeCanonicalEvent(event)) { handler(event) } + if (!this.canonical || this.normalizeCanonicalEvent(event)) { + handler(event) + } } if (parked) { @@ -237,7 +285,6 @@ export class HermesGateway extends JsonRpcGatewayClient { } } - private rememberSessionProfile(sessionId: string, profile: unknown): void { const profiles = this.sessionProfiles.get(sessionId) ?? new Set() profiles.add(this.resolveSessionProfile(sessionId, profile)) @@ -251,13 +298,16 @@ export class HermesGateway extends JsonRpcGatewayClient { private snapshotRoute(params: Record, snapshot: any): Record { const sid = snapshot?.session_id - if (typeof sid !== 'string') { return params } + if (typeof sid !== 'string') { + return params + } + const previous = canonicalProfile(params.profile) const replayOwner = this.replayProfiles.get(snapshot.replay_epoch) const named = snapshot.info?.profile_name - const profile = typeof named === 'string' && named ? named : - replayOwner?.sessionId === sid ? replayOwner.profile : previous + const profile = + typeof named === 'string' && named ? named : replayOwner?.sessionId === sid ? replayOwner.profile : previous this.profileAliases.set(canonicalSessionKey(sid, previous), profile) @@ -275,12 +325,18 @@ export class HermesGateway extends JsonRpcGatewayClient { } private normalizeCanonicalEvent(event: GatewayEvent): boolean { - if (!event.session_id) { return true } + if (!event.session_id) { + return true + } + const owner = event.replay_epoch ? this.replayProfiles.get(event.replay_epoch) : undefined const profiles = this.sessionProfiles.get(event.session_id) - let profile = owner?.sessionId === event.session_id ? owner.profile : this.eventRoutes.get(event) ?? - (profiles?.size === 1 ? profiles.values().next().value : profiles?.size ? undefined : 'default') + let profile = + owner?.sessionId === event.session_id + ? owner.profile + : (this.eventRoutes.get(event) ?? + (profiles?.size === 1 ? profiles.values().next().value : profiles?.size ? undefined : 'default')) if (profile === undefined) { this.reconcileAmbiguousEvent(event.session_id, event.replay_epoch) @@ -301,18 +357,25 @@ export class HermesGateway extends JsonRpcGatewayClient { private reconcileAmbiguousEvent(sessionId: string, epoch?: string): void { const key = JSON.stringify([sessionId, epoch]) - if (this.reconciledEpochs.has(key)) { return } + if (this.reconciledEpochs.has(key)) { + return + } + this.reconciledEpochs.add(key) this.parkedFrames.set(key, []) const generation = this.connectionGeneration // A new/unknown replay epoch cannot choose between equal stored IDs. One // authoritative snapshot per known owner recovers cards and establishes routes. - const probes = [...this.sessionProfiles.get(sessionId) ?? []].map(profile => - this.request('session.resume', { session_id: sessionId, profile })) + const probes = [...(this.sessionProfiles.get(sessionId) ?? [])].map(profile => + this.request('session.resume', { session_id: sessionId, profile }) + ) void Promise.allSettled(probes).then(results => { - if (generation !== this.connectionGeneration) { return } + if (generation !== this.connectionGeneration) { + return + } + const parked = this.parkedFrames.get(key) ?? [] this.parkedFrames.delete(key) @@ -323,7 +386,9 @@ export class HermesGateway extends JsonRpcGatewayClient { return } - for (const deliver of parked) { deliver() } + for (const deliver of parked) { + deliver() + } }) } @@ -358,7 +423,10 @@ export class HermesGateway extends JsonRpcGatewayClient { } override async connect(wsUrl: string): Promise { - if (this.connectionState === 'open' || this.connectionState === 'connecting') { return this.readiness.promise } + if (this.connectionState === 'open' || this.connectionState === 'connecting') { + return this.readiness.promise + } + const generation = ++this.connectionGeneration this.nativeDial = new URL(wsUrl).searchParams.has('native_dial') this.canonical = this.nativeDial @@ -381,7 +449,10 @@ export class HermesGateway extends JsonRpcGatewayClient { } catch (error) { this.readiness.failDial(ready, error instanceof Error ? error : new Error(GATEWAY_NOT_CONNECTED_MESSAGE)) - if (generation === this.connectionGeneration) { this.invalidate('Hermes gateway protocol negotiation failed') } + if (generation === this.connectionGeneration) { + this.invalidate('Hermes gateway protocol negotiation failed') + } + throw error } } @@ -397,7 +468,10 @@ export class HermesGateway extends JsonRpcGatewayClient { // The shared client's reconnect cursor predates the new socket's // attachments. Never route an unknown old cursor to the launch profile. - if (!owner || owner.sessionId !== params.session_id) { throw new Error('Replay owner unavailable; reopen the session') } + if (!owner || owner.sessionId !== params.session_id) { + throw new Error('Replay owner unavailable; reopen the session') + } + params = { ...params, profile: owner.profile } } @@ -412,10 +486,15 @@ export class HermesGateway extends JsonRpcGatewayClient { const profiles = this.sessionProfiles.get(String(sid ?? '')) if (params.profile === undefined && profiles?.size) { - if (profiles.size !== 1) { throw new Error('Session ID belongs to several profiles; select its owner profile before continuing') } + if (profiles.size !== 1) { + throw new Error('Session ID belongs to several profiles; select its owner profile before continuing') + } + const profile = profiles.values().next().value! - if (profile !== 'default') { params = { ...params, profile } } + if (profile !== 'default') { + params = { ...params, profile } + } } if (typeof sid === 'string' && ['session.resume', 'session.activate'].includes(method)) { @@ -427,7 +506,12 @@ export class HermesGateway extends JsonRpcGatewayClient { return params } - override async request(method: string, params: Record = {}, timeoutMs?: number, signal?: AbortSignal): Promise { + override async request( + method: string, + params: Record = {}, + timeoutMs?: number, + signal?: AbortSignal + ): Promise { const generation = this.connectionGeneration const deadline = requestDeadline(timeoutMs) @@ -439,10 +523,16 @@ export class HermesGateway extends JsonRpcGatewayClient { this.requireConnectionGeneration(generation) } - if (!this.canonical) { return super.request(method, legacyParams(method, params), remainingRequestBudget(deadline, signal), signal) } + if (!this.canonical) { + return super.request(method, legacyParams(method, params), remainingRequestBudget(deadline, signal), signal) + } + const redirected = this.canonicalRedirect(method, params, timeoutMs, deadline, signal) - if (redirected) { return redirected } + if (redirected) { + return redirected + } + params = this.routeCanonicalParams(method, params) await this.attachForRequest(method, params, deadline, signal) @@ -455,12 +545,16 @@ export class HermesGateway extends JsonRpcGatewayClient { // retained rewind is keyed under its name, which a redial forgets until the attach. const local = this.protocol.localAnswer(method, params) - if (local) { return local as T } + if (local) { + return local as T + } // The clarify card answers a whole question set as one form: declared, the owner asks the // turn's multi-question clarify as ONE request; undeclared, one card per question. An older // owner refuses the unknown key, so it rides only where `client.capabilities` advertised it. - if (method === 'prompt.submit' && this.backendClarifyBatch) { params = { ...params, clarify_batch: true } } + if (method === 'prompt.submit' && this.backendClarifyBatch) { + params = { ...params, clarify_batch: true } + } let prepared = this.protocol.prepare(method, params) const wireMethod = this.protocol.wire(method, prepared) @@ -471,7 +565,10 @@ export class HermesGateway extends JsonRpcGatewayClient { try { result = await super.request(wireMethod, prepared, remainingRequestBudget(deadline, signal), signal) } catch (error) { - if (!this.protocol.retryableFence(prepared, error)) { throw error } + if (!this.protocol.retryableFence(prepared, error)) { + throw error + } + // The refusal carried the owner's current fences: one retry at them, never a loop. this.protocol.failure(prepared, error) this.requireConnectionGeneration(generation) @@ -492,11 +589,20 @@ export class HermesGateway extends JsonRpcGatewayClient { return this.request(m, p, remainingRequestBudget(deadline, signal), signal) } - const settled = await this.protocol.settle(method, prepared, this.protocol.result(method, prepared, result), followUp) as T + const settled = (await this.protocol.settle( + method, + prepared, + this.protocol.result(method, prepared, result), + followUp + )) as T + this.requireConnectionGeneration(generation) if (method === 'session.resume' || method === 'session.create' || method === 'session.activate') { - this.adoptAttachedSnapshot(settled as { session_id?: string; prompts?: Array> }, prepared.profile) + this.adoptAttachedSnapshot( + settled as { session_id?: string; prompts?: Array> }, + prepared.profile + ) } return settled @@ -508,12 +614,20 @@ export class HermesGateway extends JsonRpcGatewayClient { // Requests the canonical wire answers as other requests: a truncating submit (edit / regenerate / // restore) is the owner's rewind, then the submit; a clarify lock is the prompt owner's respond. - private canonicalRedirect(method: string, params: Record, timeoutMs: number | undefined, deadline: number, signal?: AbortSignal): Promise | null { + private canonicalRedirect( + method: string, + params: Record, + timeoutMs: number | undefined, + deadline: number, + signal?: AbortSignal + ): Promise | null { const rewind = method === 'prompt.submit' ? splitRewindSubmit(params) : null if (rewind) { return (async () => { - if (rewind.rewind) { await this.request('session.rewind', rewind.rewind, remainingRequestBudget(deadline, signal), signal) } + if (rewind.rewind) { + await this.request('session.rewind', rewind.rewind, remainingRequestBudget(deadline, signal), signal) + } return this.request('prompt.submit', rewind.submit, remainingRequestBudget(deadline, signal), signal) })() @@ -521,40 +635,74 @@ export class HermesGateway extends JsonRpcGatewayClient { // A question's owner is immutable even when a second profile attaches an // equal stored session ID while the first card remains open. - const promptOwner = method === 'clarify.lock' ? this.deliveredPrompts.get(String(params.request_id ?? '')) : undefined + const promptOwner = + method === 'clarify.lock' ? this.deliveredPrompts.get(String(params.request_id ?? '')) : undefined + + if (!promptOwner) { + return null + } - if (!promptOwner) { return null } const answer = typeof params.answer === 'string' ? params.answer : '' - return this.request('clarify.respond', { session_id: promptOwner.sessionId, profile: promptOwner.profile, request_id: params.request_id, answer }, timeoutMs, signal) + return this.request( + 'clarify.respond', + { session_id: promptOwner.sessionId, profile: promptOwner.profile, request_id: params.request_id, answer }, + timeoutMs, + signal + ) } private requireConnectionGeneration(generation: number): void { - if (generation !== this.connectionGeneration) { throw new Error('Hermes gateway connection changed; reopen the session') } + if (generation !== this.connectionGeneration) { + throw new Error('Hermes gateway connection changed; reopen the session') + } } // Resume the session (and, for branch-like methods, its parent) on THIS socket before a // method that needs an authority subscription here. - private async attachForRequest(method: string, params: Record, deadline: number, signal?: AbortSignal): Promise { + private async attachForRequest( + method: string, + params: Record, + deadline: number, + signal?: AbortSignal + ): Promise { const sid = typeof params.session_id === 'string' ? params.session_id : null - const resume = (sessionId: string) => this.request('session.resume', { - session_id: sessionId, defer_history: true, omit_messages: true, - ...(params.profile ? { profile: params.profile } : {}) - }, remainingRequestBudget(deadline, signal), signal) + const resume = (sessionId: string) => + this.request( + 'session.resume', + { + session_id: sessionId, + defer_history: true, + omit_messages: true, + ...(params.profile ? { profile: params.profile } : {}) + }, + remainingRequestBudget(deadline, signal), + signal + ) if (sid && ATTACH_REQUIRED.has(method) && !this.attached.has(canonicalSessionKey(sid, params.profile))) { await resume(sid) } - const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id ?? params.session_key : null + const parent = PARENT_ATTACH_REQUIRED.has(method) + ? (params.parent_session_id ?? params.session_id ?? params.session_key) + : null if (typeof parent === 'string' && parent && !this.attached.has(canonicalSessionKey(parent, params.profile))) { await resume(parent) } } - private adoptAttachedSnapshot(settled: { session_id?: string; replay_epoch?: string; info?: { profile_name?: string }; prompts?: Array> }, profile?: unknown): void { + private adoptAttachedSnapshot( + settled: { + session_id?: string + replay_epoch?: string + info?: { profile_name?: string } + prompts?: Array> + }, + profile?: unknown + ): void { // Prompts still open on the authority re-deliver like `open_requests` after a reconnect. const sid = settled.session_id @@ -571,8 +719,11 @@ export class HermesGateway extends JsonRpcGatewayClient { } } - for (const prompt of (settled.prompts ?? [])) { - this.deliverCanonicalPrompt({ type: `${prompt.kind}.request`, session_id: sid, profile: canonicalProfile(profile), payload: prompt }, true) + for (const prompt of settled.prompts ?? []) { + this.deliverCanonicalPrompt( + { type: `${prompt.kind}.request`, session_id: sid, profile: canonicalProfile(profile), payload: prompt }, + true + ) } } @@ -595,19 +746,25 @@ export class HermesGateway extends JsonRpcGatewayClient { }) // The wire follows the peer's explicit advertisement, read before any subscriber runs; a // native dial is canonical by provenance. - super.on('gateway.ready', event => this.readiness.adoptReady(this.connectionGeneration, () => { - this.canonical = event.payload?.session_authority === true - })) + super.on('gateway.ready', event => + this.readiness.adoptReady(this.connectionGeneration, () => { + this.canonical = event.payload?.session_authority === true + }) + ) super.onState(state => this.readiness.trackTransport(state)) this.onEvent(event => { - if (!this.canonical) { return } + if (!this.canonical) { + return + } if (event.type in CANONICAL_PROMPT_EVENTS) { this.deliverCanonicalPrompt({ ...event, profile: this.eventRoutes.get(event) }, false) } else if (event.type.endsWith('.settled')) { const id = (event.payload as { prompt_id?: unknown } | undefined)?.prompt_id - if (typeof id === 'string') { this.deliveredPrompts.delete(id) } + if (typeof id === 'string') { + this.deliveredPrompts.delete(id) + } } }) } @@ -905,5 +1062,7 @@ export function sessionFileOwnerScope(id: string): { connectionId?: string; prof const connectionId = String(owner.connectionId ?? '').trim() - return connectionId && connectionId !== (ambientOwnerConnectionId() ?? 'local') ? { connectionId, profile } : { profile } + return connectionId && connectionId !== (ambientOwnerConnectionId() ?? 'local') + ? { connectionId, profile } + : { profile } } diff --git a/apps/desktop/src/api/config-route-binding.test.ts b/apps/desktop/src/api/config-route-binding.test.ts index 211ec8447f491..26a52d532d3f1 100644 --- a/apps/desktop/src/api/config-route-binding.test.ts +++ b/apps/desktop/src/api/config-route-binding.test.ts @@ -3,10 +3,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getHermesConfigRecord, peekConfigReadOrigin, + retainConfigReadOrigin, saveHermesConfig, setApiRequestConnection, setApiRequestProfile } from '@/hermes' +import type { HermesConfigRecord } from '@/types/hermes' describe('config read/write route binding', () => { let api: ReturnType @@ -57,4 +59,44 @@ describe('config read/write route binding', () => { ) expect(puts.filter(call => call[0].connectionId === 'connection-b')).toHaveLength(0) }) + + it('keeps delayed reads and derived writes isolated for the same profile on two gateways', async () => { + const readA = Promise.withResolvers() + const readB = Promise.withResolvers() + api.mockReturnValueOnce(readA.promise) + api.mockReturnValueOnce(readB.promise) + + const ownerA = Object.freeze({ connectionId: 'connection-a', profile: 'worker' }) + const ownerB = Object.freeze({ connectionId: 'connection-b', profile: 'worker' }) + const pendingA = getHermesConfigRecord(ownerA) + const pendingB = getHermesConfigRecord(ownerB) + setApiRequestConnection('unrelated-gateway') + setApiRequestProfile('unrelated-profile') + + readB.resolve({ model: 'model-b' }) + const recordB = await pendingB + await saveHermesConfig(retainConfigReadOrigin({ ...recordB, model: 'updated-b' }, recordB)) + readA.resolve({ model: 'model-a' }) + const recordA = await pendingA + await saveHermesConfig(retainConfigReadOrigin({ ...recordA, model: 'updated-a' }, recordA)) + + expect(api.mock.calls.map(([request]) => request)).toEqual([ + { ...ownerA, priority: 'foreground', path: '/api/config' }, + { ...ownerB, priority: 'foreground', path: '/api/config' }, + { + ...ownerB, + priority: 'foreground', + path: '/api/config', + method: 'PUT', + body: { config: { model: 'updated-b' } } + }, + { + ...ownerA, + priority: 'foreground', + path: '/api/config', + method: 'PUT', + body: { config: { model: 'updated-a' } } + } + ]) + }) }) diff --git a/apps/desktop/src/api/config.ts b/apps/desktop/src/api/config.ts index 976f79976e40c..9808f74e732cd 100644 --- a/apps/desktop/src/api/config.ts +++ b/apps/desktop/src/api/config.ts @@ -85,20 +85,23 @@ export function resolveConfigWriteScope( return capabilityScoped(requestScope) } -export function getStatus(): Promise { +export function getStatus(profile?: string): Promise { return hermesApi({ - ...profileScoped(), + ...profileScoped(profile), path: '/api/status' }) } -export function getLogs(params: { - component?: string - file?: string - level?: string - lines?: number - search?: string -}): Promise { +export function getLogs( + params: { + component?: string + file?: string + level?: string + lines?: number + search?: string + }, + profile?: ProfileScope +): Promise { const query = new URLSearchParams() if (params.file) { @@ -124,14 +127,14 @@ export function getLogs(params: { const suffix = query.toString() return hermesApi({ - ...profileScoped(), + ...capabilityScoped(profile), path: suffix ? `/api/logs?${suffix}` : '/api/logs' }) } -export function getHermesConfig(profile?: string): Promise { +export function getHermesConfig(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/config', timeoutMs: STARTUP_REQUEST_TIMEOUT_MS }) @@ -170,9 +173,9 @@ export function getHermesConfigDefaults(): Promise { }) } -export function getHermesConfigSchema(profile?: null | string): Promise { +export function getHermesConfigSchema(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/config/schema' }) } @@ -202,9 +205,9 @@ export function saveHermesConfigRecord(config: HermesConfigRecord, profile?: Pro }) } -export function getEnvVars(profile?: null | string): Promise> { +export function getEnvVars(profile?: ProfileScope): Promise> { return hermesApi>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/env' }) } @@ -263,19 +266,19 @@ export function validateProviderCredential( }) } -export function getCustomEndpoints(profile?: null | string): Promise { +export function getCustomEndpoints(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/providers/custom-endpoints' }) } export function saveCustomEndpoint( endpoint: CustomEndpointUpdate, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/providers/custom-endpoints', method: 'POST', body: endpoint @@ -284,10 +287,10 @@ export function saveCustomEndpoint( export function validateCustomEndpoint( endpoint: CustomEndpointUpdate, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/providers/custom-endpoints/validate', method: 'POST', body: endpoint @@ -296,18 +299,18 @@ export function validateCustomEndpoint( export function activateCustomEndpoint( id: string, - profile?: null | string + profile?: ProfileScope ): Promise<{ ok: boolean; provider: string; model: string }> { return hermesApi<{ ok: boolean; provider: string; model: string }>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/providers/custom-endpoints/${encodeURIComponent(id)}/activate`, method: 'POST' }) } -export function deleteCustomEndpoint(id: string, profile?: null | string): Promise { +export function deleteCustomEndpoint(id: string, profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/providers/custom-endpoints/${encodeURIComponent(id)}`, method: 'DELETE' }) @@ -322,10 +325,10 @@ export function listOAuthProviders(profile?: ProfileScope): Promise { return hermesApi<{ ok: boolean; provider: string }>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/providers/oauth/${encodeURIComponent(providerId)}`, method: 'DELETE' }) diff --git a/apps/desktop/src/api/cron.ts b/apps/desktop/src/api/cron.ts index a841b6a9c30a9..1e9cbc49ad02e 100644 --- a/apps/desktop/src/api/cron.ts +++ b/apps/desktop/src/api/cron.ts @@ -5,11 +5,12 @@ import type { CronDeliveryTarget, CronJob, CronJobCreatePayload, - CronJobUpdates, - SessionInfo -} from '@/types/hermes' + CronJobUpdates +} from '@/types/cron' +import type { SessionInfo } from '@/types/hermes' import { + capabilityScoped, connectionScoped, getApiRequestConnection, hermesApi, @@ -17,6 +18,25 @@ import { STARTUP_REQUEST_TIMEOUT_MS } from './client' +/** A routine's owner: its agent (profile) and, when pinned, the machine (connection) serving it. The + * per-job calls below take one so a surface listing several agents' routines acts on each in its own + * profile; without it they keep the ambient scope, exactly as before. */ +export interface CronOwnerScope { + connectionId?: null | string + profile?: null | string +} + +function cronScoped(owner?: CronOwnerScope) { + return owner ? capabilityScoped(owner) : { ...profileScoped(), ...connectionScoped() } +} + +/** `?profile=` names the owning profile for the backend (a hint it verifies for per-job calls). */ +function ownerQuery(owner: CronOwnerScope | undefined, joiner: '?' | '&' = '?'): string { + const profile = owner?.profile?.trim() + + return profile ? `${joiner}profile=${encodeURIComponent(profile)}` : '' +} + // The cron trigger endpoint intentionally waits for the whole job so its // response reflects the persisted execution result. Agent jobs can run far // longer than the Electron fetch default; keep this override local to the one @@ -47,11 +67,15 @@ export function getCronJob(jobId: string): Promise { }) } -export async function getCronJobRuns(jobId: string, limit = 20): Promise { +export async function getCronJobRuns(jobId: string, limit = 20, scope?: CronOwnerScope): Promise { + // Captured before awaiting: runs belong to the source the request is pinned + // to, `local` included. An unpinned request rides the profile door, which can + // resolve to a legacy per-profile remote override, so its runs stay untagged. + const owner = scope?.connectionId?.trim() || getApiRequestConnection() + const { runs } = await hermesApi<{ runs: SessionInfo[] }>({ - ...profileScoped(), - ...connectionScoped(), - path: `/api/cron/jobs/${encodeURIComponent(jobId)}/runs?limit=${limit}` + ...cronScoped(scope), + path: `/api/cron/jobs/${encodeURIComponent(jobId)}/runs?limit=${limit}${ownerQuery(scope, '&')}` }) // Run rows are backend-returned sessions like any other page, so they carry @@ -63,7 +87,7 @@ export async function getCronJobRuns(jobId: string, limit = 20): Promise { return targets ?? [] } -export function createCronJob(body: CronJobCreatePayload): Promise { +/** The same targets for one routine owner: its own profile's gateways, on its machine. */ +export async function getOwnerCronDeliveryTargets(scope: CronOwnerScope): Promise { + const { targets } = await hermesApi<{ targets: CronDeliveryTarget[] }>({ + ...cronScoped(scope), + path: `/api/cron/delivery-targets${ownerQuery(scope)}` + }) + + return targets ?? [] +} + +export function createCronJob(body: CronJobCreatePayload, scope?: CronOwnerScope): Promise { return hermesApi({ - ...profileScoped(), - ...connectionScoped(), - path: '/api/cron/jobs', + ...cronScoped(scope), + path: `/api/cron/jobs${ownerQuery(scope)}`, method: 'POST', body }) } -export function updateCronJob(jobId: string, updates: CronJobUpdates): Promise { +export function updateCronJob(jobId: string, updates: CronJobUpdates, scope?: CronOwnerScope): Promise { return hermesApi({ - ...profileScoped(), - ...connectionScoped(), - path: `/api/cron/jobs/${encodeURIComponent(jobId)}`, + ...cronScoped(scope), + path: `/api/cron/jobs/${encodeURIComponent(jobId)}${ownerQuery(scope)}`, method: 'PUT', body: { updates } }) } -export function pauseCronJob(jobId: string): Promise { +export function pauseCronJob(jobId: string, scope?: CronOwnerScope): Promise { return hermesApi({ - ...profileScoped(), - ...connectionScoped(), - path: `/api/cron/jobs/${encodeURIComponent(jobId)}/pause`, + ...cronScoped(scope), + path: `/api/cron/jobs/${encodeURIComponent(jobId)}/pause${ownerQuery(scope)}`, method: 'POST' }) } -export function resumeCronJob(jobId: string): Promise { +export function resumeCronJob(jobId: string, scope?: CronOwnerScope): Promise { return hermesApi({ - ...profileScoped(), - ...connectionScoped(), - path: `/api/cron/jobs/${encodeURIComponent(jobId)}/resume`, + ...cronScoped(scope), + path: `/api/cron/jobs/${encodeURIComponent(jobId)}/resume${ownerQuery(scope)}`, method: 'POST' }) } -export function triggerCronJob(jobId: string): Promise { +export function triggerCronJob(jobId: string, scope?: CronOwnerScope): Promise { return hermesApi({ - ...profileScoped(), - ...connectionScoped(), - path: `/api/cron/jobs/${encodeURIComponent(jobId)}/trigger`, + ...cronScoped(scope), + path: `/api/cron/jobs/${encodeURIComponent(jobId)}/trigger${ownerQuery(scope)}`, method: 'POST', timeoutMs: CRON_TRIGGER_REQUEST_TIMEOUT_MS }) @@ -129,20 +158,18 @@ export function triggerCronJob(jobId: string): Promise { // Asks the job's live run to stop; the run books a 'cancelled' attempt at its next cancel // check (a second or two), so callers poll the job list for the ledger to settle. -export function cancelCronJobRun(jobId: string): Promise { +export function cancelCronJobRun(jobId: string, scope?: CronOwnerScope): Promise { return hermesApi({ - ...profileScoped(), - ...connectionScoped(), - path: `/api/cron/jobs/${encodeURIComponent(jobId)}/cancel`, + ...cronScoped(scope), + path: `/api/cron/jobs/${encodeURIComponent(jobId)}/cancel${ownerQuery(scope)}`, method: 'POST' }) } -export function deleteCronJob(jobId: string): Promise<{ ok: boolean }> { +export function deleteCronJob(jobId: string, scope?: CronOwnerScope): Promise<{ ok: boolean }> { return hermesApi<{ ok: boolean }>({ - ...profileScoped(), - ...connectionScoped(), - path: `/api/cron/jobs/${encodeURIComponent(jobId)}`, + ...cronScoped(scope), + path: `/api/cron/jobs/${encodeURIComponent(jobId)}${ownerQuery(scope)}`, method: 'DELETE' }) } @@ -157,10 +184,12 @@ export function deleteCronJob(jobId: string): Promise<{ ok: boolean }> { // (built-ins plus that profile's plugin-registered blueprints, deliver options // from its gateways), and instantiate creates the job in that profile. Fetch the // catalog for the same profile you instantiate into. Mirrors the dashboard's api.ts. -export function getAutomationBlueprints(profile: string): Promise<{ blueprints: AutomationBlueprint[] }> { +export function getAutomationBlueprints( + profile: string, + connectionId?: null | string +): Promise<{ blueprints: AutomationBlueprint[] }> { return hermesApi<{ blueprints: AutomationBlueprint[] }>({ - ...profileScoped(), - ...connectionScoped(), + ...(connectionId ? capabilityScoped({ connectionId, profile }) : { ...profileScoped(), ...connectionScoped() }), path: `/api/cron/blueprints?profile=${encodeURIComponent(profile)}`, timeoutMs: STARTUP_REQUEST_TIMEOUT_MS }) @@ -168,11 +197,11 @@ export function getAutomationBlueprints(profile: string): Promise<{ blueprints: export function instantiateAutomationBlueprint( body: { blueprint: string; values: Record }, - profile: string + profile: string, + connectionId?: null | string ): Promise { return hermesApi({ - ...profileScoped(), - ...connectionScoped(), + ...(connectionId ? capabilityScoped({ connectionId, profile }) : { ...profileScoped(), ...connectionScoped() }), path: `/api/cron/blueprints/instantiate?profile=${encodeURIComponent(profile)}`, method: 'POST', body diff --git a/apps/desktop/src/api/messaging.ts b/apps/desktop/src/api/messaging.ts index a470f8b180940..e7fbf7778edbe 100644 --- a/apps/desktop/src/api/messaging.ts +++ b/apps/desktop/src/api/messaging.ts @@ -18,11 +18,11 @@ import type { WebhooksResponse } from '@/types/webhooks' -import { hermesApi, profileScoped } from './client' +import { capabilityScoped, hermesApi, type ProfileScope } from './client' -export function getMessagingPlatforms(profile?: null | string): Promise { +export function getMessagingPlatforms(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/messaging/platforms' }) } @@ -38,10 +38,10 @@ export interface MessagingPlatformUpdateResponse { export function updateMessagingPlatform( platformId: string, body: MessagingPlatformUpdate, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/messaging/platforms/${encodeURIComponent(platformId)}`, method: 'PUT', body @@ -50,10 +50,10 @@ export function updateMessagingPlatform( export function testMessagingPlatform( platformId: string, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/messaging/platforms/${encodeURIComponent(platformId)}/test`, method: 'POST' }) @@ -64,21 +64,21 @@ export function testMessagingPlatform( // the one-time `/link ` that binds a chat account to this agent. The profile tag picks the // backend (a profile may point at another host); the relay itself serves that gateway's own profile. -export function getRelayLinks(profile?: null | string): Promise { - return hermesApi({ ...profileScoped(profile), path: '/api/messaging/relay' }) +export function getRelayLinks(profile?: ProfileScope): Promise { + return hermesApi({ ...capabilityScoped(profile), path: '/api/messaging/relay' }) } -export function requestRelayLink(platform: string, profile?: null | string): Promise { +export function requestRelayLink(platform: string, profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/messaging/relay/${encodeURIComponent(platform)}/link`, method: 'POST' }) } -export function getRelayLinkState(code: string, profile?: null | string): Promise { +export function getRelayLinkState(code: string, profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/messaging/relay/link/${encodeURIComponent(code)}` }) } @@ -86,10 +86,10 @@ export function getRelayLinkState(code: string, profile?: null | string): Promis export function unlinkRelayAccount( platform: string, platformUserId: string, - profile?: null | string + profile?: ProfileScope ): Promise<{ unlinked: boolean }> { return hermesApi<{ unlinked: boolean }>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/messaging/relay/${encodeURIComponent(platform)}/accounts/${encodeURIComponent(platformUserId)}`, method: 'DELETE' }) @@ -102,10 +102,10 @@ export function unlinkRelayAccount( export function startTelegramOnboarding( botName?: string, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/messaging/telegram/onboarding/start', method: 'POST', body: botName ? { bot_name: botName } : {} @@ -114,10 +114,10 @@ export function startTelegramOnboarding( export function getTelegramOnboardingStatus( pairingId: string, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/messaging/telegram/onboarding/${encodeURIComponent(pairingId)}` }) } @@ -125,9 +125,9 @@ export function getTelegramOnboardingStatus( export function applyTelegramOnboarding( pairingId: string, allowedUserIds: string[], - profile?: null | string + profile?: ProfileScope ): Promise { - const scope = profileScoped(profile) + const scope = capabilityScoped(profile) return hermesApi({ ...scope, @@ -137,9 +137,9 @@ export function applyTelegramOnboarding( }) } -export function cancelTelegramOnboarding(pairingId: string, profile?: null | string): Promise<{ ok: boolean }> { +export function cancelTelegramOnboarding(pairingId: string, profile?: ProfileScope): Promise<{ ok: boolean }> { return hermesApi<{ ok: boolean }>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/messaging/telegram/onboarding/${encodeURIComponent(pairingId)}`, method: 'DELETE' }) @@ -152,9 +152,9 @@ export function cancelTelegramOnboarding(pairingId: string, profile?: null | str // returned by the API, while an authenticated admin is only ever identifying // a row they can already see. -export function getPairing(profile?: null | string): Promise { +export function getPairing(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/pairing' }) } @@ -162,9 +162,9 @@ export function getPairing(profile?: null | string): Promise { export function approvePairing( platform: string, requestId: string, - profile?: null | string + profile?: ProfileScope ): Promise<{ ok: boolean; user: PairingUser }> { - const scope = profileScoped(profile) + const scope = capabilityScoped(profile) return hermesApi<{ ok: boolean; user: PairingUser }>({ ...scope, @@ -176,8 +176,8 @@ export function approvePairing( }) } -export function revokePairing(platform: string, userId: string, profile?: null | string): Promise<{ ok: boolean }> { - const scope = profileScoped(profile) +export function revokePairing(platform: string, userId: string, profile?: ProfileScope): Promise<{ ok: boolean }> { + const scope = capabilityScoped(profile) return hermesApi<{ ok: boolean }>({ ...scope, @@ -195,33 +195,33 @@ export function revokePairing(platform: string, userId: string, profile?: null | /** `profile` = the backend owner this view captured at mount; omitted → the * ambient request scope. Keyed explicitly so a view that survives an active * profile switch keeps talking to the profile it belongs to (#71352). */ -export function getWebhooks(profile?: null | string): Promise { +export function getWebhooks(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/webhooks' }) } -export function enableWebhooks(profile?: null | string): Promise { +export function enableWebhooks(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/webhooks/enable', method: 'POST' }) } -export function createWebhook(body: WebhookCreatePayload, profile?: null | string): Promise { +export function createWebhook(body: WebhookCreatePayload, profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/webhooks', method: 'POST', body }) } -export function deleteWebhook(name: string, profile?: null | string): Promise<{ ok: boolean }> { +export function deleteWebhook(name: string, profile?: ProfileScope): Promise<{ ok: boolean }> { return hermesApi<{ ok: boolean }>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/webhooks/${encodeURIComponent(name)}`, method: 'DELETE' }) @@ -230,10 +230,10 @@ export function deleteWebhook(name: string, profile?: null | string): Promise<{ export function setWebhookEnabled( name: string, enabled: boolean, - profile?: null | string + profile?: ProfileScope ): Promise<{ enabled: boolean; name: string; ok: boolean }> { return hermesApi<{ enabled: boolean; name: string; ok: boolean }>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/webhooks/${encodeURIComponent(name)}/enabled`, method: 'PUT', body: { enabled } diff --git a/apps/desktop/src/api/models.ts b/apps/desktop/src/api/models.ts index 4357a80cc2445..fc399bf988cd2 100644 --- a/apps/desktop/src/api/models.ts +++ b/apps/desktop/src/api/models.ts @@ -17,9 +17,9 @@ import { capabilityScoped, hermesApi, type ProfileScope, profileScoped, STARTUP_ // side of that budget). const MODEL_INFO_REQUEST_TIMEOUT_MS = 5_000 -export function getGlobalModelInfo(profile?: null | string): Promise { +export function getGlobalModelInfo(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/model/info', timeoutMs: MODEL_INFO_REQUEST_TIMEOUT_MS }) @@ -94,26 +94,26 @@ export function setGlobalModel( }) } -export function getAuxiliaryModels(profile?: null | string): Promise { +export function getAuxiliaryModels(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/model/auxiliary' }) } -export function getMoaModels(profile?: null | string): Promise { +export function getMoaModels(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/model/moa' }) } export function saveMoaModels( body: MoaConfigResponse, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/model/moa', method: 'PUT', body diff --git a/apps/desktop/src/api/profiles.ts b/apps/desktop/src/api/profiles.ts index dc6cf9cb27d3e..26c48d89b9c29 100644 --- a/apps/desktop/src/api/profiles.ts +++ b/apps/desktop/src/api/profiles.ts @@ -28,8 +28,12 @@ export function getConnectionServedProfiles(connectionId: string): Promise<{ gat }) } -export function createProfile(body: ProfileCreatePayload): Promise<{ name: string; ok: boolean; path: string; soul_set?: boolean }> { +export function createProfile( + body: ProfileCreatePayload, + scope?: ProfileScope +): Promise<{ name: string; ok: boolean; path: string; soul_set?: boolean }> { return hermesApi<{ name: string; ok: boolean; path: string; soul_set?: boolean }>({ + ...(scope === undefined ? {} : capabilityScoped(scope)), path: '/api/profiles', method: 'POST', body diff --git a/apps/desktop/src/api/session-list-owner.test.ts b/apps/desktop/src/api/session-list-owner.test.ts new file mode 100644 index 0000000000000..9fe1e0d752a02 --- /dev/null +++ b/apps/desktop/src/api/session-list-owner.test.ts @@ -0,0 +1,102 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { resolveResumeOwner } from '@/app/session/hooks/use-session-actions/resume-owner' +import type { HermesApiRequest } from '@/global' +import { sessionOwnerRouteFromRow } from '@/store/session-request-router' +import { deferred } from '@/test/deferred' +import { installRestBridge } from '@/test/rest-bridge' +import { makeSessionInfo } from '@/test/session-info' + +import { setApiRequestConnection, setApiRequestLocalMode } from './client' +import { listAllProfileSessions, listSessions, listSidebarSessions } from './sessions' + +// A local primary whose `work` profile Electron resolves to a legacy +// per-profile remote override: the untagged list request is answered by that +// remote, so its rows must keep the profile-door route that reaches it again. +const overrideRow = makeSessionInfo({ id: 'served-by-override', profile: 'work' }) + +const sidebar = { + recentsProfile: 'all', + recentsLimit: 50, + recentsExclude: [], + cronLimit: 50, + messagingLimit: 100, + messagingExclude: [] +} + +const sidebarPage = { + recents: { sessions: [overrideRow] }, + cron: { sessions: [{ ...overrideRow, source: 'cron' }] }, + messaging: { sessions: [{ ...overrideRow, source: 'telegram' }] } +} + +function resumeRoute(row: ReturnType) { + // The ambient resume connection of a legacy local primary is the profile door (''). + return resolveResumeOwner(sessionOwnerRouteFromRow(row), row, '') +} + +beforeEach(() => { + setApiRequestLocalMode(true) + setApiRequestConnection(null) +}) + +afterEach(() => { + setApiRequestLocalMode(false) + setApiRequestConnection(null) +}) + +describe('session lists on a local primary with a legacy per-profile remote override', () => { + it.each([ + ['listSessions', () => listSessions()], + ['listAllProfileSessions', () => listAllProfileSessions()] + ])('%s keeps served rows on the profile door', async (_name, list) => { + const api = installRestBridge(() => ({ sessions: [overrideRow] })) + + const [row] = (await list()).sessions + + expect((api.mock.calls[0][0] as HermesApiRequest).connectionId).toBeUndefined() + expect(resumeRoute(row)).toEqual({ resolvedConnectionId: '', sessionOwner: 'work' }) + }) + + it('keeps every sidebar slice on the profile door', async () => { + installRestBridge(() => sidebarPage) + + const result = await listSidebarSessions(sidebar) + + for (const row of [...result.recents.sessions, ...result.cron.sessions, ...result.messaging.sessions]) { + expect(resumeRoute(row)).toEqual({ resolvedConnectionId: '', sessionOwner: 'work' }) + } + }) + + it('does not hand a delayed page to the gateway selected while it was in flight', async () => { + const pending = deferred() + installRestBridge(() => pending.promise) + + const request = listSessions() + setApiRequestConnection('remote-b') + pending.resolve({ sessions: [overrideRow] }) + + expect((await request).sessions[0].connection_id).toBeUndefined() + }) + + it('keeps a delayed page fetched through an explicit local pin on this machine', async () => { + setApiRequestConnection('local') + const pending = deferred() + installRestBridge(() => pending.promise) + + const request = listSessions() + setApiRequestConnection('remote-b') + pending.resolve({ sessions: [overrideRow] }) + + expect(sessionOwnerRouteFromRow((await request).sessions[0])).toEqual({ connectionId: 'local', profile: 'work' }) + }) + + it('still stamps rows served by an active registry source', async () => { + setApiRequestConnection('remote-b') + installRestBridge(() => ({ sessions: [overrideRow] })) + + const [row] = (await listSessions()).sessions + + expect(sessionOwnerRouteFromRow(row)).toEqual({ connectionId: 'remote-b', profile: 'work' }) + }) +}) diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.ts index 7bdaff9c7d3aa..f737b39c60e3f 100644 --- a/apps/desktop/src/api/sessions.test.ts +++ b/apps/desktop/src/api/sessions.test.ts @@ -1,5 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { SessionInfo } from '@/hermes' +import { deferred } from '@/test/deferred' +import { makeSessionInfo } from '@/test/session-info' + import type { SidebarSessionsResponse } from './sessions' vi.mock('@/lib/gateway-rpc', () => ({ isMissingRestEndpoint: () => false })) @@ -26,13 +30,16 @@ const { setSessionArchived, setSessionPinnedRemote, setSessionUnreadRemote, - listSidebarSessions + listSidebarSessions, + listAllProfileSessions, + listSessions } = await import('./sessions') const hermesApi = vi.mocked(client.hermesApi) beforeEach(() => { vi.clearAllMocks() + vi.mocked(client.ambientOwnerConnectionId).mockReturnValue('prometheus') vi.mocked(client.getApiRequestConnection).mockReturnValue('prometheus') vi.mocked(client.getApiRequestProfile).mockReturnValue(null) // Session writes scope through the same helper as reads: a named owner is @@ -42,6 +49,53 @@ beforeEach(() => { ) }) +describe('immutable list source ownership', () => { + it.each([listSessions, listAllProfileSessions])('stamps a delayed list with the source it was sent to', async list => { + const pending = deferred<{ sessions: SessionInfo[] }>() + vi.mocked(client.getApiRequestConnection).mockReturnValue('remote-a') + hermesApi.mockReturnValueOnce(pending.promise as never) + const request = list() + vi.mocked(client.getApiRequestConnection).mockReturnValue('remote-b') + pending.resolve({ sessions: [makeSessionInfo({ id: 'same', profile: 'default' })] }) + + expect((await request).sessions[0].connection_id).toBe('remote-a') + }) + + it('stamps every sidebar slice before foreground changes and preserves explicit owners', async () => { + const pending = deferred() + vi.mocked(client.getApiRequestConnection).mockReturnValue('remote-a') + hermesApi.mockReturnValueOnce(pending.promise as never) + + const request = listSidebarSessions({ + recentsProfile: 'all', + recentsLimit: 50, + recentsExclude: [], + cronLimit: 50, + messagingLimit: 100, + messagingExclude: [] + }) + + vi.mocked(client.getApiRequestConnection).mockReturnValue('remote-b') + const served = makeSessionInfo({ id: 'same' }) + const spliced = makeSessionInfo({ id: 'same', connection_id: 'remote-c' }) + pending.resolve({ + recents: { sessions: [served, spliced] }, + cron: { sessions: [{ ...served, source: 'cron' }] }, + messaging: { sessions: [{ ...served, source: 'telegram' }] } + }) + const result = await request + expect(result.recents.sessions.map(row => row.connection_id)).toEqual(['remote-a', 'remote-c']) + expect(result.cron.sessions[0].connection_id).toBe('remote-a') + expect(result.messaging.sessions[0].connection_id).toBe('remote-a') + }) + + it('keeps connectionless primary lists on their profile-only route', async () => { + vi.mocked(client.getApiRequestConnection).mockReturnValue(null) + hermesApi.mockResolvedValueOnce({ sessions: [makeSessionInfo({ id: 'legacy' })] }) + expect((await listSessions()).sessions[0].connection_id).toBeUndefined() + }) +}) + describe('deleteSession profile scoping', () => { it('scopes the DELETE to the owning profile in the URL (object owner)', async () => { // Regression: the sidebar "All Profiles" delete sent the profile only via diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.ts index 22bc5d9807af5..aea3f2254555e 100644 --- a/apps/desktop/src/api/sessions.ts +++ b/apps/desktop/src/api/sessions.ts @@ -10,7 +10,11 @@ import type { SessionSearchResponse } from '@/types/hermes' -import { createSessionMutationClient, type SessionMutationIdentity, type SessionMutationSnapshot } from '../../../shared/src/session-http-mutations' +import { + createSessionMutationClient, + type SessionMutationIdentity, + type SessionMutationSnapshot +} from '../../../shared/src/session-http-mutations' import { ambientOwnerConnectionId, @@ -75,21 +79,21 @@ function sessionScopeQuery(scope?: ProfileScope): string { } /** - * The active registered gateway owns every row it returns, but its HTTP APIs - * correctly know nothing about this Desktop-local registry id. Preserve an - * explicit owner from a multi-source response; otherwise stamp the active - * non-local source so a later resume cannot fall back to a same-named local - * profile. Delegates to the canonical row-stamp helper so this stays the ONE - * write shape for connection_id on backend-returned rows. + * The registry source a list request is pinned to, captured before it is + * awaited: a response must never inherit the gateway selected while it was in + * flight. An explicit `local` pin names this machine and is stamped like any + * other source; an unpinned list rides the legacy profile door, which Electron + * may resolve to a per-profile remote override, so its rows stay untagged — + * the ambient `local` would misname the machine that served them. */ -function stampActiveConnectionOwner(sessions: SessionInfo[]): SessionInfo[] { +function captureListOwner(): null | string { // Durable half of the same ownership contract (#94724): enumeration under // registry topology triggers the one-shot server-side owner backfill for // the serving store when its owner is a single match. Fire-and-forget; // idempotent server-side; never blocks or fails the list that triggered it. maybeBackfillLegacySessionOwners() - return stampRowsWithOwningConnection(sessions, getApiRequestConnection()) + return getApiRequestConnection() } /** @@ -118,6 +122,8 @@ export async function listSessions( archived: 'exclude' | 'include' | 'only' = 'exclude', order: 'created' | 'recent' = 'recent' ): Promise { + const owner = captureListOwner() + const result = await hermesApi({ ...profileScoped(), path: @@ -128,7 +134,7 @@ export async function listSessions( return { ...result, - sessions: pageWindow(stampActiveConnectionOwner(result.sessions), limit), + sessions: pageWindow(stampRowsWithOwningConnection(result.sessions, owner, true), limit), offset: 0 } } @@ -155,6 +161,7 @@ export async function listAllProfileSessions( filter: SessionSourceFilter = {}, offset = 0 ): Promise { + const owner = captureListOwner() const sourceParam = filter.source ? `&source=${encodeURIComponent(filter.source)}` : '' const excludeParam = filter.excludeSources?.length @@ -171,7 +178,7 @@ export async function listAllProfileSessions( return { ...result, - sessions: pageWindow(stampActiveConnectionOwner(result.sessions), limit), + sessions: pageWindow(stampRowsWithOwningConnection(result.sessions, owner, true), limit), offset: Math.max(0, offset) } } @@ -188,7 +195,7 @@ export interface SidebarSessionSlice { profiles_truncated?: Record /** Per-profile tokens and spend over every session, not just this window. * Absent from the legacy per-slice endpoint, which has no aggregate. */ - profiles_usage?: Record + profiles_usage?: Record /** This slice is a failed load, not a successful empty session list. */ failed?: boolean /** Ask the sidebar to offer Retry instead of rendering "No sessions yet". */ @@ -328,6 +335,8 @@ export async function listSidebarSessions(req: SidebarSessionsRequest): Promise< return listSidebarSessionsLegacy(req) } + const owner = captureListOwner() + const params = new URLSearchParams({ recents_profile: req.recentsProfile, recents_limit: String(Math.max(1, req.recentsLimit)), @@ -367,17 +376,17 @@ export async function listSidebarSessions(req: SidebarSessionsRequest): Promise< return { recents: { ...result.recents, - sessions: stampActiveConnectionOwner(result.recents?.sessions ?? []), + sessions: stampRowsWithOwningConnection(result.recents?.sessions ?? [], owner, true), ...(result.errors?.length ? { errors: result.errors } : {}) }, cron: { ...result.cron, - sessions: stampActiveConnectionOwner(result.cron?.sessions ?? []), + sessions: stampRowsWithOwningConnection(result.cron?.sessions ?? [], owner, true), ...(result.errors?.length ? { errors: result.errors } : {}) }, messaging: { ...result.messaging, - sessions: stampActiveConnectionOwner(result.messaging?.sessions ?? []), + sessions: stampRowsWithOwningConnection(result.messaging?.sessions ?? [], owner, true), ...(result.errors?.length ? { errors: result.errors } : {}) }, errors: result.errors, @@ -395,21 +404,41 @@ class MissingMutationSnapshotRoute extends Error {} * verdict on the read, before any write was attempted, selects it; a session/profile 404, * refusal, conflict, timeout or failed write keeps the canonical CAS path and its retained * identity. */ -export function mutateSessionFenced(key: string, read: () => Promise, - send: (identity: Partial) => Promise): Promise { - return runSessionMutation(key, () => read().catch(error => { - // The prepared read is shared by equal concurrent edits; its verdict must - // travel with that rejection, rather than one caller's local closure. - if (isUnroutedRestPath(error)) { throw new MissingMutationSnapshotRoute(String(error), { cause: error }) } - throw error - }), send).catch(error => { - if (!(error instanceof MissingMutationSnapshotRoute)) { throw error } +export function mutateSessionFenced( + key: string, + read: () => Promise, + send: (identity: Partial) => Promise +): Promise { + return runSessionMutation( + key, + () => + read().catch(error => { + // The prepared read is shared by equal concurrent edits; its verdict must + // travel with that rejection, rather than one caller's local closure. + if (isUnroutedRestPath(error)) { + throw new MissingMutationSnapshotRoute(String(error), { cause: error }) + } + + throw error + }), + send + ).catch(error => { + if (!(error instanceof MissingMutationSnapshotRoute)) { + throw error + } return send({}) }) } -function mutateSessionHttp(id: string, method: 'PATCH' | 'DELETE', payload: Record, profile?: ProfileScope): Promise { +export function mutateSessionHttp( + id: string, + method: 'PATCH' | 'DELETE', + payload: Record, + profile?: ProfileScope, + beforeSend?: (identity: Partial) => void, + revalidate?: () => Promise +): Promise { // Null is the window's v1 route (its primary, local or remote); defaulting it to // the registry's 'local' source would pin a remote primary's edits to this machine. const scope = { connectionId: getApiRequestConnection(), ...sessionScoped(profile) } @@ -418,24 +447,47 @@ function mutateSessionHttp(id: string, method: 'PATCH' | 'DELETE', payload: R const suffix = query.size ? `?${query}` : '' const key = JSON.stringify([scope, id, method, payload]) - const send = (identity: Partial) => { + const send = async (identity: Partial) => { + // Revalidation may read the row after the fenced snapshot. Any newer edit + // then conflicts instead of becoming part of a stale destructive decision. + if (revalidate) { + await revalidate() + } + + beforeSend?.(identity) + if (method === 'DELETE') { const params = new URLSearchParams(query) - for (const [name, value] of Object.entries(identity)) { params.set(name, String(value)) } + for (const [name, value] of Object.entries(identity)) { + params.set(name, String(value)) + } return hermesApi({ ...scope, path: params.size ? `${path}?${params}` : path, method }) } - return hermesApi({ ...scope, path, method, - body: { ...payload, ...identity, ...(scope.profile ? { profile: scope.profile } : {}) } }) + return hermesApi({ + ...scope, + path, + method, + body: { ...payload, ...identity, ...(scope.profile ? { profile: scope.profile } : {}) } + }) } - return mutateSessionFenced(key, () => hermesApi({ ...scope, path: `${path}/mutation-snapshot${suffix}` }), send) + return mutateSessionFenced( + key, + () => hermesApi({ ...scope, path: `${path}/mutation-snapshot${suffix}` }), + send + ) } -export function setSessionArchived(id: string, archived: boolean, profile?: string | null): Promise<{ ok: boolean }> { - return mutateSessionHttp(id, 'PATCH', { archived, ...(archived ? { pinned: false } : {}) }, sessionWriteProfile(profile)) +export function setSessionArchived(id: string, archived: boolean, profile?: ProfileScope): Promise<{ ok: boolean }> { + return mutateSessionHttp( + id, + 'PATCH', + { archived, ...(archived ? { pinned: false } : {}) }, + profile && typeof profile === 'object' ? profile : sessionWriteProfile(profile) + ) } export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: string | null): Promise<{ ok: boolean }> { @@ -730,6 +782,10 @@ export function deleteSession(id: string, profile?: ProfileScope): Promise<{ ok: return mutateSessionHttp(id, 'DELETE', {}, profile) } -export function renameSession(id: string, title: string, profile?: string | null): Promise<{ ok: boolean; title: string }> { +export function renameSession( + id: string, + title: string, + profile?: string | null +): Promise<{ ok: boolean; title: string }> { return mutateSessionHttp(id, 'PATCH', { title }, sessionWriteProfile(profile)) } diff --git a/apps/desktop/src/api/settings-owner-scope.test.ts b/apps/desktop/src/api/settings-owner-scope.test.ts new file mode 100644 index 0000000000000..58a9c2c711e72 --- /dev/null +++ b/apps/desktop/src/api/settings-owner-scope.test.ts @@ -0,0 +1,168 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { HermesApiRequest } from '@/global' +import type { MoaConfigResponse } from '@/types/hermes' + +import { type ProfileScope, setApiRequestConnection, setApiRequestProfile } from './client' +import { + activateCustomEndpoint, + deleteCustomEndpoint, + disconnectOAuthProvider, + getCustomEndpoints, + getEnvVars, + getHermesConfig, + getHermesConfigSchema, + saveCustomEndpoint, + validateCustomEndpoint +} from './config' +import { getAuxiliaryModels, getGlobalModelInfo, getMoaModels, saveMoaModels } from './models' +import { + getElevenLabsVoices, + getMemoryProviderConfig, + getMemoryProviderOAuthStatus, + getMemoryStatus, + saveMemoryProviderConfig, + startMemoryProviderOAuth +} from './system' + +const endpoint = { base_url: 'https://models.example/v1', model: 'model-a', name: 'Model server' } + +const moa: MoaConfigResponse = { + default_preset: 'custom', + active_preset: 'custom', + presets: {}, + aggregator: { provider: 'nous', model: 'model-a' }, + aggregator_temperature: 0.5, + degraded_reference_policy: 'loud', + enabled: false, + reference_models: [], + reference_temperature: 0.5, + reference_timeout: null +} + +// Only the preload transport is replaced; the wrappers and ambient/explicit +// scope resolution run unchanged, including hermesApi's ambient connection tag. +const operations: Array<{ + name: string + request: HermesApiRequest + run: (scope?: ProfileScope) => Promise +}> = [ + { name: 'config', request: { path: '/api/config' }, run: getHermesConfig }, + { name: 'schema', request: { path: '/api/config/schema' }, run: getHermesConfigSchema }, + { name: 'credentials', request: { path: '/api/env' }, run: getEnvVars }, + { name: 'endpoints', request: { path: '/api/providers/custom-endpoints' }, run: getCustomEndpoints }, + { + name: 'save endpoint', + request: { path: '/api/providers/custom-endpoints', method: 'POST', body: endpoint }, + run: scope => saveCustomEndpoint(endpoint, scope) + }, + { + name: 'validate endpoint', + request: { path: '/api/providers/custom-endpoints/validate', method: 'POST', body: endpoint }, + run: scope => validateCustomEndpoint(endpoint, scope) + }, + { + name: 'activate endpoint', + request: { path: '/api/providers/custom-endpoints/endpoint%2Fa/activate', method: 'POST' }, + run: scope => activateCustomEndpoint('endpoint/a', scope) + }, + { + name: 'delete endpoint', + request: { path: '/api/providers/custom-endpoints/endpoint%2Fa', method: 'DELETE' }, + run: scope => deleteCustomEndpoint('endpoint/a', scope) + }, + { + name: 'disconnect provider', + request: { path: '/api/providers/oauth/nous', method: 'DELETE' }, + run: scope => disconnectOAuthProvider('nous', scope) + }, + { name: 'model info', request: { path: '/api/model/info' }, run: getGlobalModelInfo }, + { name: 'auxiliary models', request: { path: '/api/model/auxiliary' }, run: getAuxiliaryModels }, + { name: 'MoA models', request: { path: '/api/model/moa' }, run: getMoaModels }, + { + name: 'save MoA', + request: { path: '/api/model/moa', method: 'PUT', body: moa }, + run: scope => saveMoaModels(moa, scope) + }, + { + name: 'memory provider config', + request: { path: '/api/memory/providers/honcho/config?surface=declared' }, + run: scope => getMemoryProviderConfig('honcho', scope) + }, + { + name: 'save memory provider config', + request: { + path: '/api/memory/providers/honcho/config?surface=declared', + method: 'PUT', + body: { values: { workspace: 'research' } } + }, + run: scope => saveMemoryProviderConfig('honcho', { workspace: 'research' }, scope) + }, + { + name: 'start memory OAuth', + request: { path: '/api/memory/providers/honcho/oauth/start', method: 'POST' }, + run: scope => startMemoryProviderOAuth('honcho', scope) + }, + { + name: 'poll memory OAuth', + request: { path: '/api/memory/providers/honcho/oauth/status' }, + run: scope => getMemoryProviderOAuthStatus('honcho', scope) + }, + { name: 'memory status', request: { path: '/api/memory' }, run: getMemoryStatus }, + { name: 'voice catalog', request: { path: '/api/audio/elevenlabs/voices' }, run: getElevenLabsVoices } +] + +describe('settings API owner scope', () => { + const api = vi.fn(async (_request: HermesApiRequest) => ({})) + + beforeEach(() => { + api.mockClear() + Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } }) + setApiRequestConnection('ambient-gateway') + setApiRequestProfile('ambient-profile') + }) + + afterEach(() => { + setApiRequestConnection(null) + setApiRequestProfile(null) + Reflect.deleteProperty(window, 'hermesDesktop') + }) + + it.each(operations)('$name isolates same-named profiles on distinct gateways', async ({ run, request }) => { + for (const connectionId of ['gateway-a', 'gateway-b', 'local']) { + const owner = Object.freeze({ connectionId, profile: 'worker' }) + await run(owner) + expect(api.mock.calls.at(-1)?.[0]).toMatchObject({ + ...request, + connectionId, + profile: 'worker', + priority: 'foreground' + }) + setApiRequestConnection('another-ambient-gateway') + setApiRequestProfile('another-ambient-profile') + } + }) + + it.each(operations)('$name preserves classic omitted, null, and string scopes', async ({ run, request }) => { + await run() + expect(api.mock.calls.at(-1)?.[0]).toMatchObject({ + ...request, + connectionId: 'ambient-gateway', + profile: 'ambient-profile' + }) + expect(api.mock.calls.at(-1)?.[0]).not.toHaveProperty('priority') + + await run(null) + expect(api.mock.calls.at(-1)?.[0]).toMatchObject({ ...request, connectionId: 'ambient-gateway' }) + expect(api.mock.calls.at(-1)?.[0]).not.toHaveProperty('profile') + expect(api.mock.calls.at(-1)?.[0]).not.toHaveProperty('priority') + + await run(' worker ') + expect(api.mock.calls.at(-1)?.[0]).toMatchObject({ + ...request, + connectionId: 'ambient-gateway', + profile: ' worker ', + priority: 'foreground' + }) + }) +}) diff --git a/apps/desktop/src/api/system.ts b/apps/desktop/src/api/system.ts index 01740ec3d1a94..52481b554346a 100644 --- a/apps/desktop/src/api/system.ts +++ b/apps/desktop/src/api/system.ts @@ -57,9 +57,9 @@ export function audioTranscribeRequestTimeoutMs(dataUrl: string): number { } // surface=declared serves the curated desktop schema; the dashboard consumes the raw plugin schema. -export function getMemoryProviderConfig(provider: string, profile?: null | string): Promise { +export function getMemoryProviderConfig(provider: string, profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/memory/providers/${encodeURIComponent(provider)}/config?surface=declared` }) } @@ -67,10 +67,10 @@ export function getMemoryProviderConfig(provider: string, profile?: null | strin export function saveMemoryProviderConfig( provider: string, values: Record, - profile?: null | string + profile?: ProfileScope ): Promise<{ ok: boolean }> { return hermesApi<{ ok: boolean }>({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/memory/providers/${encodeURIComponent(provider)}/config?surface=declared`, method: 'PUT', body: { values } @@ -79,12 +79,9 @@ export function saveMemoryProviderConfig( // Memory-provider OAuth connect (provider-keyed; 404s for providers without an // OAuth flow). Profile-scoped: the grant lands in the active profile's config. -export function startMemoryProviderOAuth( - provider: string, - profile?: null | string -): Promise { +export function startMemoryProviderOAuth(provider: string, profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/memory/providers/${encodeURIComponent(provider)}/oauth/start`, method: 'POST' }) @@ -92,10 +89,10 @@ export function startMemoryProviderOAuth( export function getMemoryProviderOAuthStatus( provider: string, - profile?: null | string + profile?: ProfileScope ): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: `/api/memory/providers/${encodeURIComponent(provider)}/oauth/status` }) } @@ -104,9 +101,9 @@ export function getMemoryProviderOAuthStatus( // Memory data + curator (parity with `hermes memory` / `hermes curator`). // --------------------------------------------------------------------------- -export function getMemoryStatus(profile?: null | string): Promise { +export function getMemoryStatus(profile?: ProfileScope): Promise { return hermesApi({ - ...profileScoped(profile), + ...capabilityScoped(profile), path: '/api/memory' }) } @@ -261,10 +258,10 @@ export function setSttLease(lease: string, active: boolean, owner: ResolvedOwner }) } -export function getElevenLabsVoices(profile?: null | string): Promise { +export function getElevenLabsVoices(profile?: ProfileScope): Promise { return hermesApi({ path: '/api/audio/elevenlabs/voices', - ...profileScoped(profile) + ...capabilityScoped(profile) }) } diff --git a/apps/desktop/src/api/toolsets.test.ts b/apps/desktop/src/api/toolsets.test.ts new file mode 100644 index 0000000000000..064d51d0ea9ba --- /dev/null +++ b/apps/desktop/src/api/toolsets.test.ts @@ -0,0 +1,36 @@ +import { afterEach, expect, it, vi } from 'vitest' + +import { setApiRequestConnection, setApiRequestProfile } from './client' +import { getComputerUseStatus, grantComputerUsePermissions } from './toolsets' + +afterEach(() => { + setApiRequestConnection(null) + setApiRequestProfile(null) + vi.unstubAllGlobals() +}) + +it.each(['local', 'homelab'])( + 'routes computer readiness and permission actions to the explicit %s owner', + async connectionId => { + const api = vi.fn().mockResolvedValue({ ok: true }) + vi.stubGlobal('hermesDesktop', { api }) + setApiRequestConnection('other-gateway') + setApiRequestProfile('other-agent') + const owner = { connectionId, profile: 'research' } + + await getComputerUseStatus(owner) + await grantComputerUsePermissions(owner) + + expect(api).toHaveBeenNthCalledWith(1, { + ...owner, + priority: 'foreground', + path: '/api/tools/computer-use/status' + }) + expect(api).toHaveBeenNthCalledWith(2, { + ...owner, + priority: 'foreground', + path: '/api/tools/computer-use/permissions/grant', + method: 'POST' + }) + } +) diff --git a/apps/desktop/src/api/toolsets.ts b/apps/desktop/src/api/toolsets.ts index 4b5424574f7b3..ed71c1c87caf0 100644 --- a/apps/desktop/src/api/toolsets.ts +++ b/apps/desktop/src/api/toolsets.ts @@ -7,7 +7,7 @@ import type { ToolsetModelsResponse } from '@/types/hermes' -import { capabilityScoped, hermesApi, type ProfileScope, profileScoped } from './client' +import { capabilityScoped, type ProfileScope } from './client' // The optional trailing `profile` on every capability fetcher below is the // Capabilities view's profile-scope override: it lets the Skills/Tools/MCP @@ -128,16 +128,16 @@ export function selectTerminalBackend( }) } -export function getComputerUseStatus(): Promise { - return hermesApi({ - ...profileScoped(), +export function getComputerUseStatus(profile?: ProfileScope): Promise { + return window.hermesDesktop.api({ + ...capabilityScoped(profile), path: '/api/tools/computer-use/status' }) } -export function grantComputerUsePermissions(): Promise { - return hermesApi({ - ...profileScoped(), +export function grantComputerUsePermissions(profile?: ProfileScope): Promise { + return window.hermesDesktop.api({ + ...capabilityScoped(profile), path: '/api/tools/computer-use/permissions/grant', method: 'POST' }) diff --git a/apps/desktop/src/app/agent-settings/activation.test.tsx b/apps/desktop/src/app/agent-settings/activation.test.tsx new file mode 100644 index 0000000000000..67d4ff3fba43b --- /dev/null +++ b/apps/desktop/src/app/agent-settings/activation.test.tsx @@ -0,0 +1,231 @@ +import type * as ReactQuery from '@tanstack/react-query' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { MemoryRouter, useLocation, useNavigate } from 'react-router' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +import { $apiRequestScope } from '@/api/client' +import { renameProfile } from '@/hermes' +import type * as HermesApi from '@/hermes' +import { $connectionsRegistry } from '@/store/connection-registry-state' +import { selectConnection } from '@/store/connections' +import type * as ConnectionsStore from '@/store/connections' +import type * as FleetRosterStore from '@/store/fleet-roster' +import type * as GatewayStore from '@/store/gateway' +import type * as ProfileStore from '@/store/profile' +import { $activeGatewayProfile, requestFreshSession } from '@/store/profile' +import { + getRememberedSessionId, + getSessionOwnerHints, + setRememberedSessionId, + setSessionOwnerHint +} from '@/store/session' +import { deferred } from '@/test/deferred' + +import { useFreshSessionRequest } from '../contrib/wiring-effects' + +import { AgentSettingsView } from './index' + +vi.mock('@tanstack/react-query', async importOriginal => ({ + ...(await importOriginal()), + useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => + queryKey.includes('profiles') + ? { + data: { + profiles: ['research', 'renamed'].map(name => ({ name, path: `/tmp/${name}`, is_default: false })) + } + } + : {} +})) +vi.mock('../hooks/use-config-record', () => ({ useHermesConfigRecord: () => ({}) })) +vi.mock('../capabilities/skills/skills-data', () => ({ useSkillsQuery: () => ({}) })) +vi.mock('../capabilities/toolsets/toolsets-data', () => ({ useToolsetsQuery: () => ({}) })) +vi.mock('@/store/connections', async importOriginal => ({ + ...(await importOriginal()), + selectConnection: vi.fn() +})) +vi.mock('@/store/fleet-roster', async importOriginal => ({ + ...(await importOriginal()), + refreshFleetRoster: vi.fn(async () => undefined) +})) +vi.mock('@/store/gateway', async importOriginal => ({ + ...(await importOriginal()), + activeGatewayConnectionId: () => 'local', + retireLocalProfileGateways: vi.fn(() => $activeGatewayProfile.set('default')) +})) +// The harness has no backend: the list re-read after a rename resolves at once instead of retrying. +vi.mock('@/store/profile', async importOriginal => ({ + ...(await importOriginal()), + refreshProfiles: vi.fn(async () => undefined) +})) +vi.mock('@/hermes', async importOriginal => ({ + ...(await importOriginal()), + renameProfile: vi.fn() +})) + +const destination = '/settings?agentProfile=research&connection=local&panel=settings&tab=agent%3Ageneral' +// Another machine's agent still waits for "Open agent"; this window's machine renders in place. +const remoteDestination = destination.replace('connection=local', 'connection=remote') + +function Harness() { + const location = useLocation() + const navigate = useNavigate() + useFreshSessionRequest(options => { + if (!options?.preserveRoute) { + navigate('/') + } + }) + const params = new URLSearchParams(location.search) + const profile = params.get('agentProfile') ?? 'default' + const connectionId = params.get('connection') ?? 'local' + + return ( + <> + {location.pathname + location.search} + + + {location.pathname === '/settings' && ( + navigate('/')} owner={{ connectionId, profile }} /> + )} + + ) +} + +function mount(entry = destination) { + render( + + + + ) +} + +// The dialog finishes a beat after its last await (the telemetry move, then the list re-read): +// let it settle inside the test, not after the file's environment is gone. +const renameSettled = () => act(async () => void (await new Promise(resolve => setTimeout(resolve, 0)))) + +beforeEach(() => { + localStorage.clear() + $apiRequestScope.set({ connectionId: 'local', profile: 'default' }) + $activeGatewayProfile.set('default') + $connectionsRegistry.set({ + connections: [ + { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false }, + { id: 'remote', kind: 'remote', label: 'Remote', tokenPreview: null, tokenSet: false } + ], + primary: 'local', + secureTokenStorage: true, + version: 2 + }) + vi.mocked(selectConnection).mockImplementation(async (connection, options) => { + requestFreshSession({ preserveRoute: options?.preserveRoute }) + $apiRequestScope.setKey('connectionId', connection) + $activeGatewayProfile.set(options?.profile ?? 'default') + }) +}) + +afterEach(() => { + cleanup() + vi.clearAllMocks() + $connectionsRegistry.set(null) + $apiRequestScope.set({ connectionId: null, profile: null }) + $activeGatewayProfile.set('default') +}) + +it.each([false, true])('keeps the requested panel without overriding later navigation (leave=%s)', async leave => { + const activation = deferred() + vi.mocked(selectConnection).mockImplementation(async (connection, options) => { + await activation.promise + requestFreshSession({ preserveRoute: options?.preserveRoute }) + $apiRequestScope.setKey('connectionId', connection) + $activeGatewayProfile.set(options?.profile ?? 'default') + }) + mount(remoteDestination) + fireEvent.click(screen.getByRole('button', { name: 'Open agent' })) + + if (leave) { + fireEvent.click(screen.getByRole('button', { name: 'Leave settings' })) + } + + await act(async () => { + activation.resolve() + await activation.promise + }) + expect(screen.getByTestId('route').textContent).toBe(leave ? '/elsewhere' : remoteDestination) + + if (!leave) { + expect(screen.queryByRole('button', { name: 'Open agent' })).toBeNull() + expect(screen.getByRole('button', { name: /^Rename: / })).toBeTruthy() + } + + // A later ordinary new-chat request must not inherit settings preservation. + act(() => requestFreshSession()) + expect(screen.getByTestId('route').textContent).toBe('/') +}) + +it.each(['stay', 'leave', 'refresh'] as const)( + 'finishes a local rename after gateway retirement without stealing navigation (%s)', + async navigation => { + $activeGatewayProfile.set('research') + setRememberedSessionId('rename-session', 'research') + setSessionOwnerHint('rename-session', { connectionId: 'local', profile: 'research' }) + setSessionOwnerHint('remote-session', { connectionId: 'remote', profile: 'research' }) + const renamed = deferred<{ name: string; ok: boolean; path: string }>() + vi.mocked(renameProfile).mockReturnValueOnce(renamed.promise) + mount() + fireEvent.click(screen.getByRole('button', { name: /^Rename: / })) + fireEvent.change(screen.getByLabelText(/new name/i), { target: { value: 'renamed' } }) + fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Rename' })) + await waitFor(() => expect(renameProfile).toHaveBeenCalled()) + // Retirement moved the window to the default agent; the page keeps showing its owner. + expect($activeGatewayProfile.get()).toBe('default') + expect(screen.queryByRole('button', { name: 'Open agent' })).toBeNull() + + // The rename dialog is still open over the page, so the harness controls sit behind it. + if (navigation === 'leave') { + fireEvent.click(screen.getByRole('button', { hidden: true, name: 'Leave settings' })) + } else if (navigation === 'refresh') { + fireEvent.click(screen.getByRole('button', { hidden: true, name: 'Refresh route state' })) + } + + await act(async () => { + renamed.resolve({ name: 'renamed', ok: true, path: '/tmp/renamed' }) + await renamed.promise + }) + expect(getRememberedSessionId('research')).toBeNull() + expect(getRememberedSessionId('renamed')).toBe('rename-session') + expect(getSessionOwnerHints('rename-session')).toEqual([{ connectionId: 'local', profile: 'renamed' }]) + expect(getSessionOwnerHints('remote-session')).toEqual([{ connectionId: 'remote', profile: 'research' }]) + expect(screen.getByTestId('route').textContent).toBe( + navigation === 'leave' ? '/elsewhere' : destination.replace('agentProfile=research', 'agentProfile=renamed') + ) + + if (navigation === 'leave') { + expect(selectConnection).not.toHaveBeenCalled() + } else { + expect($activeGatewayProfile.get()).toBe('renamed') + expect(screen.getByRole('button', { name: /^Rename: / })).toBeTruthy() + } + + await renameSettled() + } +) + +it('follows a renamed agent the window was only viewing without activating it', async () => { + vi.mocked(renameProfile).mockResolvedValueOnce({ name: 'renamed', ok: true, path: '/tmp/renamed' }) + mount() + fireEvent.click(screen.getByRole('button', { name: /^Rename: / })) + fireEvent.change(screen.getByLabelText(/new name/i), { target: { value: 'renamed' } }) + fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Rename' })) + await waitFor(() => + expect(screen.getByTestId('route').textContent).toBe(destination.replace('agentProfile=research', 'agentProfile=renamed')) + ) + expect(selectConnection).not.toHaveBeenCalled() + expect($activeGatewayProfile.get()).toBe('default') + await renameSettled() +}) diff --git a/apps/desktop/src/app/agent-settings/agent-dialogs.tsx b/apps/desktop/src/app/agent-settings/agent-dialogs.tsx new file mode 100644 index 0000000000000..f978f64aaf888 --- /dev/null +++ b/apps/desktop/src/app/agent-settings/agent-dialogs.tsx @@ -0,0 +1,140 @@ +import { useQuery } from '@tanstack/react-query' +import { useLayoutEffect, useRef, useState } from 'react' +import { useLocation, useNavigate } from 'react-router' + +import { $apiRequestScope } from '@/api/client' +import { getProfiles } from '@/hermes' +import { useI18n } from '@/i18n' +import { queryClient } from '@/lib/query-client' +import { $activeConnectionId } from '@/store/connections' +import { refreshFleetRoster } from '@/store/fleet-roster' +import { notifyError } from '@/store/notifications' +import { profileLabel, refreshProfiles } from '@/store/profile' +import type { ProfileInfo } from '@/types/hermes' + +import { CreateProfileDialog } from '../profiles/create-profile-dialog' +import { DeleteProfileDialog } from '../profiles/delete-profile-dialog' +import { RenameProfileDialog } from '../profiles/rename-profile-dialog' +import { PROFILES_ROUTE } from '../routes' + +import { type AgentRouteOwner, agentSettingsKey } from './data' +import { agentMachine, forgetViewedAgent } from './landing' +import { useOverviewActionsCopy } from './overview-actions-copy' + +/** A create names only the machine (and, duplicating, the agent copied); a rename or delete names + * the agent it acts on. */ +export type AgentDialogTarget = + | { kind: 'create' | 'duplicate'; owner: AgentRouteOwner } + | { kind: 'delete' | 'rename'; owner: AgentRouteOwner; profile: ProfileInfo } + +/** The owner's profile list, as its page's General settings reads it (one cache row). */ +export const agentProfilesQuery = (owner: AgentRouteOwner) => ({ + queryKey: [...agentSettingsKey(owner), 'profiles'], + queryFn: () => getProfiles(owner) +}) + +/** After an agent is created, renamed or deleted, everything that lists agents re-reads: the window's + * own list (`$profiles`, which the agent list and an agent page's header read) when the agent lives + * on this window's machine, the roster for every machine, and the owner's page reads. */ +async function refreshAgentLists(owner: AgentRouteOwner, failedLoad: string): Promise { + const foreground = + agentMachine($apiRequestScope.get().connectionId ?? $activeConnectionId.get()) === owner.connectionId + + await Promise.all([ + foreground ? refreshProfiles().catch(error => notifyError(error, failedLoad)) : null, + refreshFleetRoster({ force: true }), + queryClient.invalidateQueries({ + predicate: ({ queryKey }) => + queryKey[0] === 'agent-settings' && queryKey[1] === owner.connectionId && queryKey[3] === 'profiles' + }) + ]) +} + +interface AgentDialogsOptions { + /** The page follows its renamed agent to the new name (a display-name change keeps the name). */ + onRenamed?: (name: string) => Promise +} + +/** New agent, Duplicate, Rename and Delete for every agent surface: one set of dialogs, one refresh + * after each, and a delete leaves the deleted agent's page. */ +export function useAgentDialogs({ onRenamed }: AgentDialogsOptions = {}) { + const [target, setTarget] = useState(null) + + return { + // The owner is captured as opened: a later window or page change must not retarget the dialog. + open: (next: AgentDialogTarget) => setTarget({ ...next, owner: { ...next.owner } }), + dialogs: target && setTarget(null)} onRenamed={onRenamed} target={target} /> + } +} + +interface AgentDialogProps extends AgentDialogsOptions { + target: AgentDialogTarget + onClose: () => void +} + +export function AgentDialog({ target, onClose, onRenamed }: AgentDialogProps) { + const { t } = useI18n() + const c = useOverviewActionsCopy() + const navigate = useNavigate() + const { owner } = target + const profiles = useQuery({ ...agentProfilesQuery(owner), enabled: !('profile' in target) }) + const refresh = () => refreshAgentLists(owner, t.profiles.failedLoad) + + // A delete that finishes after the user moved on must not pull them back. + const { key } = useLocation() + const here = useRef(key) + useLayoutEffect(() => { + here.current = key + + return () => { + here.current = null + } + }, [key]) + + async function leaveDeleted() { + forgetViewedAgent(owner) + + if (here.current === key) { + navigate(PROFILES_ROUTE, { replace: true }) + } + + await refresh() + } + + if (!('profile' in target)) { + return ( + + ) + } + + const { profile } = target + + return target.kind === 'rename' ? ( + { + // Following the agent first: the page under the old name is already gone. + if (!profile.is_default) { + await onRenamed?.(name) + } + + await refresh() + }} + open + owner={owner} + /> + ) : ( + + ) +} diff --git a/apps/desktop/src/app/agent-settings/agent-settings.css b/apps/desktop/src/app/agent-settings/agent-settings.css new file mode 100644 index 0000000000000..e12e8db241ce1 --- /dev/null +++ b/apps/desktop/src/app/agent-settings/agent-settings.css @@ -0,0 +1,347 @@ +/* The column is the page stage contract's (portal-pages.css). No bottom padding: the scrollers run + to the stage's edge and keep their own end space. */ +[data-page-surface] .management-panel.agent-management { + /* The page hero's containing block (page-hero.css). */ + position: relative; + padding-block: var(--portal-page-eyebrow-top) 0; + font-family: var(--portal-font-body); +} + +.agent-management-avatar { + width: 56px; + height: 56px; + flex-shrink: 0; + border-radius: var(--portal-radius-card); +} + +.agent-management-avatar > img { + width: 32px; + height: 32px; + margin: auto; +} + +/* The machine chip beside the name (18563:12863): 10px caps on the status green, black ink, as the + sign-in steps' "ok" badge; the quiet waiting fill while this window's gateway is not connected. */ +.agent-management-machine { + padding: 0.1875rem 0.25rem; + border-radius: var(--portal-radius-control); + background-color: var(--portal-badge-waiting-fill); + color: var(--portal-badge-waiting-ink); + font-size: var(--portal-type-caption-size); + font-weight: 500; + letter-spacing: var(--portal-tracking-caption); + line-height: 1; + text-transform: uppercase; + white-space: nowrap; +} + +/* A long machine name gives way before the agent's own name does: it keeps at most 14rem and ends + in an ellipsis (the shared header holds everything beside an H1 at its full width). */ +.portal-page-header-name > .agent-management-machine { + min-width: 0; + max-width: 14rem; + flex-shrink: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.agent-management-machine[data-connected='true'] { + background-color: var(--portal-badge-ok-fill); + color: var(--portal-badge-ink); +} + +/* The overflow sits on the hero's brightest corner: it takes the solid floating fill (page-hero.css). */ +:root[data-shell='portal'] .agent-management .portal-page-header .portal-page-header-actions button[data-variant='secondary'] { + background-color: var(--portal-surface-elevated); +} + +/* The description row is held for every agent (one 14px line at 1.4 and its 6px gap), so the tab + bar lands at one y whether the agent is the default (which fills it) or not. */ +:root[data-shell='portal'] .agent-management .portal-page-header-title { + grid-template-rows: auto auto minmax(1.6rem, auto); +} + +/* "DEFAULT AGENT" under the name (18563:12868): the 10px caps caption at the quiet ink. */ +.agent-management-role { + color: var(--ui-text-tertiary); + font-size: var(--portal-type-caption-size); + letter-spacing: var(--portal-tracking-caption); + line-height: 1.6; + text-transform: uppercase; +} + +/* Warning banner (877:4212, 878:7066): the danger tint and stroke, r4, orange warn glyph. */ +.agent-channel-warning { + display: flex; + align-items: center; + gap: 0.75rem; + margin-bottom: 2rem; + padding: 0.75rem 0.75rem 0.75rem 1rem; + border: 1px solid var(--portal-stroke-danger); + border-radius: var(--portal-radius-card); + background: var(--portal-surface-danger); + font-size: var(--portal-type-body-size); + font-weight: 500; + line-height: 1.4; +} + +.agent-channel-warning > svg { + flex-shrink: 0; + width: 1rem; + height: 1rem; + color: var(--portal-status-pending); +} + +.agent-channel-warning p + p { + margin-top: 0.125rem; + color: var(--ui-text-secondary); + font-size: var(--portal-type-ui-size); + font-weight: 400; +} + +/* Status cell (877:4307): 6px dot + label; green when connected, red when it dropped. */ +.agent-channel-status { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.agent-channel-status::before { + width: 6px; + height: 6px; + flex-shrink: 0; + border-radius: 50%; + background: currentColor; + content: ''; +} + +.agent-channel-status[data-tone='connected'] { + color: var(--portal-status-online, var(--ui-green)); +} + +/* 877:4307: a #a22a20 dot beside softer #cc8a84 text (the dot alone carries the alarm colour). */ +.agent-channel-status[data-tone='disconnected'] { + color: var(--portal-status-error-ink); +} + +.agent-channel-status[data-tone='disconnected']::before { + background: var(--portal-control-danger-fill); +} + +.agent-overview-menu { + border-radius: 0.5rem; +} + +.agent-overview-menu [data-slot='dropdown-menu-item'] { + min-height: 2.75rem; + gap: 0.75rem; + border-radius: 0.375rem; + padding: 0.5rem 0.75rem; + font-size: var(--portal-type-body-size); +} + +.agent-management-scroll, +.agent-management-editor { + min-height: 0; + flex: 1; + overflow: auto; +} + +/* Every agent page scroller ends like a Settings page: the last row clears the stage edge by the + page's end space and the content fades out under it while more is below. */ +.agent-management-scroll, +.agent-history { + padding-bottom: var(--portal-page-end-space); +} + +.agent-management-scroll { + container: agent-overview / inline-size; +} + +.agent-overview-grid { + display: grid; + grid-template-columns: minmax(0, 436fr) minmax(0, 300fr); + align-items: start; + gap: 24px; +} + +.agent-overview-column { + display: grid; + min-width: 0; + align-content: start; + gap: 32px; +} + +.agent-overview-section { + display: grid; + min-width: 0; + gap: 12px; +} + +.agent-overview-section h2 { + color: var(--ui-text-primary); + font-size: 15px; + font-weight: 500; + line-height: 1.1; +} + +.agent-overview-section-link { + display: inline-flex; + align-items: center; + gap: 6px; + text-align: start; +} + +.agent-overview-section-link .codicon { + color: var(--ui-text-quaternary); +} + +.agent-overview-section-link:hover .codicon { + color: var(--ui-text-secondary); +} + +.agent-overview-section-link:focus-visible { + outline: var(--portal-focus-ring-width) solid var(--portal-focus-ring-color); + outline-offset: var(--portal-focus-ring-offset); + border-radius: var(--portal-radius-chip); +} + +.agent-overview-row:has(.agent-overview-row-subtitle) { + min-height: 64px; +} + +.agent-overview-card { + overflow: hidden; + border: 1px solid var(--ui-stroke-tertiary); + border-radius: var(--portal-radius-card); + background: var(--ui-bg-card); +} + +/* List row (877:4230): 44px, label 14 Medium, value 13 at .6, chevron at .4. */ +.agent-overview-row { + display: flex; + width: 100%; + min-height: 44px; + align-items: center; + gap: 12px; + padding: 10px 12px 10px 16px; + text-align: start; + font-size: 14px; + font-weight: 500; + line-height: 1.4; +} + +.agent-overview-row + .agent-overview-row, +.agent-overview-footer { + border-top: 1px solid var(--portal-stroke-divider); +} + +.agent-overview-row:hover { + background: var(--portal-surface-row-hover); +} + +.agent-overview-row:focus-visible { + outline: var(--portal-focus-ring-width) solid var(--portal-focus-ring-color); + outline-offset: var(--portal-focus-ring-inset); +} + +.agent-overview-row > span:nth-child(2) { + font-size: var(--portal-type-ui-size); + font-weight: 400; +} + +.agent-overview-row > .codicon { + color: var(--ui-text-quaternary); +} + +.agent-overview-empty, +.agent-overview-footer { + padding: 12px 16px; + color: var(--ui-text-tertiary); + font-size: 13px; +} + +.agent-instructions-preview { + padding: 16px; + color: var(--ui-text-secondary); + font-family: var(--portal-font-mono); + font-size: 13px; + line-height: 18px; +} + +.agent-instructions-preview p { + display: -webkit-box; + overflow: hidden; + white-space: pre-wrap; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; +} + +.agent-instructions-preview p.agent-instructions-skeleton { + display: grid; +} + +/* Three 18px lines, the clamped preview's height. */ +.agent-instructions-skeleton > span { + height: 8px; + margin-block: 5px; + translate: none; +} + +/* "SOUL.md · ~/.hermes" (877:4228): one line, the path elided in its middle. */ +.agent-instructions-source { + display: flex; + min-width: 0; + gap: 0.375em; + margin-top: 10px; + white-space: nowrap; + color: var(--ui-text-tertiary); + font-size: 11px; +} + +.agent-management-error { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 24px; + font-size: 13px; +} + +.agent-management-editor { + container: agent-editor / inline-size; + overflow: hidden; +} + +@container agent-overview (max-width: 640px) { + .agent-overview-grid { + grid-template-columns: minmax(0, 1fr); + } +} + +/* Below wide (breakpoints.ts: max-width 1023.98px). */ +@media (max-width: 1023.98px) { + .agent-overview-grid { + grid-template-columns: minmax(0, 1fr); + gap: 32px; + } +} + +/* DEFAULT chip (877:4186): brand tint with a 0.5px brand ring, 9px uppercase. */ +.agent-management-default { + align-self: center; + flex-shrink: 0; + padding: 0 4px; + border-radius: var(--portal-radius-chip); + background: var(--portal-surface-brand-selected); + box-shadow: inset 0 0 0 0.5px var(--portal-brand-ink); + color: var(--ui-text-primary); + font-size: var(--portal-type-chip-size); + letter-spacing: var(--portal-tracking-chip); + line-height: 0.875rem; + text-transform: uppercase; +} + +:root:not(.dark) .agent-management-default { + color: var(--portal-brand-ink); +} diff --git a/apps/desktop/src/app/agent-settings/channel-warning.tsx b/apps/desktop/src/app/agent-settings/channel-warning.tsx new file mode 100644 index 0000000000000..57e6f7044bc69 --- /dev/null +++ b/apps/desktop/src/app/agent-settings/channel-warning.tsx @@ -0,0 +1,24 @@ +import type { MessagingPlatformsResponse } from '@/hermes' +import { AlertTriangle } from '@/lib/icons' +import { platformStatusTone } from '@/lib/platform-status' + +import { useOverviewActionsCopy } from './overview-actions-copy' + +export function AgentChannelWarnings({ messaging }: { messaging?: MessagingPlatformsResponse }) { + const c = useOverviewActionsCopy() + + const disconnected = + messaging?.platforms.filter( + platform => platform.configured && platform.enabled && ['bad', 'warn'].includes(platformStatusTone(platform)) + ) ?? [] + + return disconnected.map(platform => ( +
+ +
+

{c.disconnectedTitle.replace('{name}', platform.name)}

+

{c.disconnectedHelp}

+
+
+ )) +} diff --git a/apps/desktop/src/app/agent-settings/copy.ts b/apps/desktop/src/app/agent-settings/copy.ts new file mode 100644 index 0000000000000..a7d3c2878098e --- /dev/null +++ b/apps/desktop/src/app/agent-settings/copy.ts @@ -0,0 +1,308 @@ +import { isBundledLocale, useI18n } from '@/i18n' +import type { BundledLocale } from '@/i18n/types' + +const copy = { + en: { + back: 'Back to chat', + overview: 'Overview', + history: 'History', + openChat: 'Open chat', + behavior: 'Behavior', + instructions: 'Instructions', + channels: 'Channels', + viewHistory: 'See all in History', + capabilities: 'Capabilities', + tools: 'Tools', + skills: 'Skills', + connectors: 'Connectors & MCP', + memory: 'Memory', + provider: 'Provider', + connections: 'Connections', + voice: 'Voice', + model: 'Model', + primary: 'Primary', + fallbacks: 'Fallbacks', + approvals: 'Access', + approvalMode: 'Approval mode', + recent: 'Recent activity', + noSessions: 'No recent chats', + openAgent: 'Open agent', + openAgentDescription: 'Open this agent to see its overview and change its settings.', + backToAgents: 'Back to agents', + unavailable: 'Unavailable', + retry: 'Retry', + configured: 'Configured', + connected: 'Connected', + disconnected: 'Disconnected' + }, + fr: { + back: 'Retour à la discussion', + overview: 'Vue d’ensemble', + history: 'Historique', + openChat: 'Ouvrir la discussion', + behavior: 'Comportement', + instructions: 'Instructions', + channels: 'Canaux', + viewHistory: 'Tout voir dans l’historique', + capabilities: 'Capacités', + tools: 'Outils', + skills: 'Compétences', + connectors: 'Connecteurs et MCP', + memory: 'Mémoire', + provider: 'Fournisseur', + connections: 'Connexions', + voice: 'Voix', + model: 'Modèle', + primary: 'Principal', + fallbacks: 'Solutions de secours', + approvals: 'Accès', + approvalMode: 'Mode d’approbation', + recent: 'Activité récente', + noSessions: 'Aucune discussion récente', + openAgent: 'Ouvrir l’agent', + openAgentDescription: 'Ouvrez cet agent pour voir sa vue d’ensemble et modifier ses paramètres.', + backToAgents: 'Retour aux agents', + unavailable: 'Indisponible', + retry: 'Réessayer', + configured: 'Configuré', + connected: 'Connecté', + disconnected: 'Déconnecté' + }, + de: { + back: 'Zurück zum Chat', + overview: 'Übersicht', + history: 'Verlauf', + openChat: 'Chat öffnen', + behavior: 'Verhalten', + instructions: 'Anweisungen', + channels: 'Kanäle', + viewHistory: 'Alle im Verlauf anzeigen', + capabilities: 'Fähigkeiten', + tools: 'Werkzeuge', + skills: 'Skills', + connectors: 'Konnektoren & MCP', + memory: 'Gedächtnis', + provider: 'Anbieter', + connections: 'Verbindungen', + voice: 'Sprache', + model: 'Modell', + primary: 'Primär', + fallbacks: 'Alternativen', + approvals: 'Zugriff', + approvalMode: 'Freigabemodus', + recent: 'Letzte Aktivitäten', + noSessions: 'Keine letzten Chats', + openAgent: 'Agent öffnen', + openAgentDescription: 'Öffne diesen Agenten, um seine Übersicht zu sehen und seine Einstellungen zu ändern.', + backToAgents: 'Zurück zu den Agenten', + unavailable: 'Nicht verfügbar', + retry: 'Erneut versuchen', + configured: 'Konfiguriert', + connected: 'Verbunden', + disconnected: 'Getrennt' + }, + es: { + back: 'Volver al chat', + overview: 'Resumen', + history: 'Historial', + openChat: 'Abrir chat', + behavior: 'Comportamiento', + instructions: 'Instrucciones', + channels: 'Canales', + viewHistory: 'Ver todo el historial', + capabilities: 'Capacidades', + tools: 'Herramientas', + skills: 'Habilidades', + connectors: 'Conectores y MCP', + memory: 'Memoria', + provider: 'Proveedor', + connections: 'Conexiones', + voice: 'Voz', + model: 'Modelo', + primary: 'Principal', + fallbacks: 'Alternativas', + approvals: 'Acceso', + approvalMode: 'Modo de aprobación', + recent: 'Actividad reciente', + noSessions: 'No hay chats recientes', + openAgent: 'Abrir agente', + openAgentDescription: 'Abre este agente para ver su resumen y cambiar su configuración.', + backToAgents: 'Volver a los agentes', + unavailable: 'No disponible', + retry: 'Reintentar', + configured: 'Configurado', + connected: 'Conectado', + disconnected: 'Desconectado' + }, + ja: { + back: 'チャットに戻る', + overview: '概要', + history: '履歴', + openChat: 'チャットを開く', + behavior: '動作', + instructions: '指示', + channels: 'チャンネル', + viewHistory: '履歴をすべて表示', + capabilities: '機能', + tools: 'ツール', + skills: 'スキル', + connectors: 'コネクターとMCP', + memory: 'メモリ', + provider: 'プロバイダー', + connections: '接続', + voice: '音声', + model: 'モデル', + primary: 'プライマリ', + fallbacks: 'フォールバック', + approvals: 'アクセス', + approvalMode: '承認モード', + recent: '最近のアクティビティ', + noSessions: '最近のチャットはありません', + openAgent: 'エージェントを開く', + openAgentDescription: 'このエージェントを開くと、概要の確認と設定の変更ができます。', + backToAgents: 'エージェント一覧に戻る', + unavailable: '利用不可', + retry: '再試行', + configured: '設定済み', + connected: '接続済み', + disconnected: '未接続' + }, + zh: { + back: '返回对话', + overview: '概览', + history: '历史', + openChat: '打开对话', + behavior: '行为', + instructions: '指令', + channels: '频道', + viewHistory: '查看全部历史', + capabilities: '能力', + tools: '工具', + skills: '技能', + connectors: '连接器与 MCP', + memory: '记忆', + provider: '提供商', + connections: '连接', + voice: '语音', + model: '模型', + primary: '主要模型', + fallbacks: '备用项', + approvals: '访问权限', + approvalMode: '审批模式', + recent: '最近活动', + noSessions: '暂无最近对话', + openAgent: '打开智能体', + openAgentDescription: '打开此智能体以查看概览并更改其设置。', + backToAgents: '返回智能体', + unavailable: '不可用', + retry: '重试', + configured: '已配置', + connected: '已连接', + disconnected: '未连接' + }, + 'zh-hant': { + back: '返回對話', + overview: '概覽', + history: '歷史', + openChat: '開啟對話', + behavior: '行為', + instructions: '指令', + channels: '頻道', + viewHistory: '查看全部歷史', + capabilities: '能力', + tools: '工具', + skills: '技能', + connectors: '連接器與 MCP', + memory: '記憶', + provider: '提供者', + connections: '連線', + voice: '語音', + model: '模型', + primary: '主要模型', + fallbacks: '備用項目', + approvals: '存取權限', + approvalMode: '核准模式', + recent: '最近活動', + noSessions: '尚無最近對話', + openAgent: '開啟智慧體', + openAgentDescription: '開啟此智慧體以查看概覽並變更其設定。', + backToAgents: '返回智慧體', + unavailable: '無法使用', + retry: '重試', + configured: '已設定', + connected: '已連線', + disconnected: '未連線' + }, + ru: { + back: 'Назад к чату', + overview: 'Обзор', + history: 'История', + openChat: 'Открыть чат', + behavior: 'Поведение', + instructions: 'Инструкции', + channels: 'Каналы', + viewHistory: 'Показать всю историю', + capabilities: 'Возможности', + tools: 'Инструменты', + skills: 'Навыки', + connectors: 'Коннекторы и MCP', + memory: 'Память', + provider: 'Провайдер', + connections: 'Подключения', + voice: 'Голос', + model: 'Модель', + primary: 'Основная', + fallbacks: 'Резервные варианты', + approvals: 'Доступ', + approvalMode: 'Режим подтверждения', + recent: 'Недавняя активность', + noSessions: 'Нет недавних чатов', + openAgent: 'Открыть агента', + openAgentDescription: 'Откройте этого агента, чтобы увидеть обзор и изменить настройки.', + backToAgents: 'Назад к агентам', + unavailable: 'Недоступно', + retry: 'Повторить', + configured: 'Настроено', + connected: 'Подключено', + disconnected: 'Отключено' + }, + ar: { + back: 'العودة إلى المحادثة', + overview: 'نظرة عامة', + history: 'السجل', + openChat: 'فتح المحادثة', + behavior: 'السلوك', + instructions: 'التعليمات', + channels: 'القنوات', + viewHistory: 'عرض السجل بالكامل', + capabilities: 'الإمكانات', + tools: 'الأدوات', + skills: 'المهارات', + connectors: 'الموصلات وMCP', + memory: 'الذاكرة', + provider: 'المزوّد', + connections: 'الاتصالات', + voice: 'الصوت', + model: 'النموذج', + primary: 'الأساسي', + fallbacks: 'البدائل', + approvals: 'الوصول', + approvalMode: 'وضع الموافقة', + recent: 'النشاط الأخير', + noSessions: 'لا توجد محادثات حديثة', + openAgent: 'فتح الوكيل', + openAgentDescription: 'افتح هذا الوكيل لعرض نظرته العامة وتغيير إعداداته.', + backToAgents: 'العودة إلى الوكلاء', + unavailable: 'غير متاح', + retry: 'إعادة المحاولة', + configured: 'تم الإعداد', + connected: 'متصل', + disconnected: 'غير متصل' + } +} satisfies Record> + +export function useAgentSettingsCopy() { + const { locale } = useI18n() + + return isBundledLocale(locale) ? copy[locale] : copy.en +} diff --git a/apps/desktop/src/app/agent-settings/data.test.ts b/apps/desktop/src/app/agent-settings/data.test.ts new file mode 100644 index 0000000000000..b45ba2ba0758c --- /dev/null +++ b/apps/desktop/src/app/agent-settings/data.test.ts @@ -0,0 +1,44 @@ +import { afterEach, expect, it, vi } from 'vitest' + +import * as client from '@/api/client' + +import { getAgentMessaging, getAgentRecentSessions, getAgentRoutines, saveAgentRoutine } from './data' + +afterEach(() => vi.restoreAllMocks()) + +it('pins every read and routine write to the named gateway and profile', async () => { + const request = vi.spyOn(client, 'hermesApi').mockResolvedValue({}) + + for (const connectionId of ['alpha', 'beta']) { + const owner = { connectionId, profile: 'research' } + await getAgentRoutines(owner) + await getAgentMessaging(owner) + await getAgentRecentSessions(owner) + await saveAgentRoutine(owner, { prompt: 'Review notes', schedule: '0 9 * * *', deliver: 'local' }) + await saveAgentRoutine(owner, { name: 'Updated' }, 'same-job') + } + + expect(request).toHaveBeenCalledTimes(10) + + for (const [index, [call]] of request.mock.calls.entries()) { + expect(call.connectionId).toBe(index < 5 ? 'alpha' : 'beta') + expect(call.profile).toBe('research') + expect(call.path).toContain('profile=research') + } + + expect(request.mock.calls[4][0]).toEqual( + expect.objectContaining({ method: 'PUT', body: { updates: { name: 'Updated' } } }) + ) +}) + +it('loads more history without changing its owner or including archived sessions', async () => { + const request = vi.spyOn(client, 'hermesApi').mockResolvedValue({}) + await getAgentRecentSessions({ connectionId: 'beta', profile: 'research' }, 50) + expect(request).toHaveBeenCalledWith( + expect.objectContaining({ + connectionId: 'beta', + profile: 'research', + path: '/api/profiles/sessions?profile=research&limit=50&offset=0&archived=exclude&order=recent' + }) + ) +}) diff --git a/apps/desktop/src/app/agent-settings/data.ts b/apps/desktop/src/app/agent-settings/data.ts new file mode 100644 index 0000000000000..27805554d53c4 --- /dev/null +++ b/apps/desktop/src/app/agent-settings/data.ts @@ -0,0 +1,52 @@ +import { capabilityScoped, hermesApi } from '@/api/client' +import type { + CronJob, + CronJobCreatePayload, + CronJobUpdates, + MessagingPlatformsResponse, + PaginatedSessions +} from '@/hermes' + +export interface AgentSettingsOwner { + connectionId?: string + profile: string +} + +/** An agent page's owner, its machine resolved ('local' for this one). */ +export type AgentRouteOwner = Required + +export const agentSettingsKey = (owner: AgentSettingsOwner) => + ['agent-settings', owner.connectionId ?? '', owner.profile] as const + +export function getAgentRoutines(owner: AgentSettingsOwner): Promise { + return hermesApi({ ...capabilityScoped(owner), path: `/api/cron/jobs?profile=${encodeURIComponent(owner.profile)}` }) +} + +export function getAgentMessaging(owner: AgentSettingsOwner): Promise { + return hermesApi({ + ...capabilityScoped(owner), + path: `/api/messaging/platforms?profile=${encodeURIComponent(owner.profile)}` + }) +} + +export function getAgentRecentSessions(owner: AgentSettingsOwner, limit = 5, offset = 0): Promise { + return hermesApi({ + ...capabilityScoped(owner), + path: `/api/profiles/sessions?profile=${encodeURIComponent(owner.profile)}&limit=${limit}&offset=${offset}&archived=exclude&order=recent` + }) +} + +export function saveAgentRoutine( + owner: AgentSettingsOwner, + values: CronJobCreatePayload | CronJobUpdates, + id?: string +): Promise { + const path = id ? `/api/cron/jobs/${encodeURIComponent(id)}` : '/api/cron/jobs' + + return hermesApi({ + ...capabilityScoped(owner), + path: `${path}?profile=${encodeURIComponent(owner.profile)}`, + method: id ? 'PUT' : 'POST', + body: id ? { updates: values } : values + }) +} diff --git a/apps/desktop/src/app/agent-settings/default-agent.ts b/apps/desktop/src/app/agent-settings/default-agent.ts new file mode 100644 index 0000000000000..9cddcb0fa9ea8 --- /dev/null +++ b/apps/desktop/src/app/agent-settings/default-agent.ts @@ -0,0 +1,50 @@ +import { LOCAL_CONNECTION_ID } from '@hermes/shared' +import { useStore } from '@nanostores/react' +import { useState } from 'react' + +import { useI18n } from '@/i18n' +import { hostHas } from '@/lib/host-capabilities' +import { $defaultProfileRoute, setDefaultProfile } from '@/store/default-profile' +import { notify, notifyError } from '@/store/notifications' +import type { ProfileInfo } from '@/types/hermes' + +import { settingsScopeLabel } from '../settings/profile-scope' + +import type { AgentSettingsOwner } from './data' + +/** The owner's default-agent state and the one write that changes it. There is no "unset": another + * agent becoming the default is the only way off, so callers render a set-only control. */ +export function useDefaultAgent(owner: AgentSettingsOwner, profile?: ProfileInfo) { + const { t } = useI18n() + const defaultRoute = useStore($defaultProfileRoute) + const [saving, setSaving] = useState(false) + const route = { connectionId: owner.connectionId ?? null, profile: owner.profile } + // No stored route means the app opens the backend's own default profile, so that agent is the + // default until the user picks another (keeps this in step with the DEFAULT chip). + const isDefault = defaultRoute + ? defaultRoute.connectionId === route.connectionId && defaultRoute.profile === route.profile + : Boolean(profile?.is_default) && (!route.connectionId || route.connectionId === LOCAL_CONNECTION_ID) + + const canSetDefault = + Boolean(window.hermesDesktop?.profile?.setDefault) && + (!hostHas('servingOriginConnection') || !route.connectionId || route.connectionId === LOCAL_CONNECTION_ID) + + async function makeDefault() { + setSaving(true) + + try { + await setDefaultProfile(route) + notify({ + kind: 'success', + title: t.profiles.defaultSet(profile ? settingsScopeLabel(profile) : owner.profile), + message: t.profiles.defaultDescription + }) + } catch (error) { + notifyError(error, t.profiles.failedSetDefault) + } finally { + setSaving(false) + } + } + + return { canSetDefault, isDefault, makeDefault, saving } +} diff --git a/apps/desktop/src/app/agent-settings/directory.test.tsx b/apps/desktop/src/app/agent-settings/directory.test.tsx new file mode 100644 index 0000000000000..e6c97aa451030 --- /dev/null +++ b/apps/desktop/src/app/agent-settings/directory.test.tsx @@ -0,0 +1,157 @@ +import { QueryClientProvider } from '@tanstack/react-query' +import { cleanup, fireEvent, render, type RenderOptions, screen, waitFor, within } from '@testing-library/react' +import type { ReactNode } from 'react' +import { MemoryRouter, useLocation } from 'react-router' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +import { en } from '@/i18n/en' +import { queryClient } from '@/lib/query-client' +import type * as FleetRosterStore from '@/store/fleet-roster' +import { refreshFleetRoster } from '@/store/fleet-roster' +import type * as ProfileStore from '@/store/profile' +import { $profiles, refreshProfiles } from '@/store/profile' + +import type { SimplifiedAgent } from '../chat/sidebar/use-simplified-agents' + +import { AgentDirectory, AgentNavigation } from './directory' + +let narrow = false + +vi.mock('@/hooks/use-media-query', () => ({ useMediaQuery: () => narrow })) +vi.mock('../chat/sidebar/use-fleet-roster', () => ({ useFleetRoster: () => {} })) +const roster: { agents: SimplifiedAgent[] } = { agents: [] } + +const twoAgents: SimplifiedAgent[] = [ + { id: 'a', label: 'Research', profile: 'research', connectionId: 'alpha', gateway: 'Laptop' }, + { id: 'b', label: 'Research', profile: 'research', connectionId: 'beta', gateway: 'Studio' } +] + +vi.mock('../chat/sidebar/use-simplified-agents', () => ({ + useSimplifiedAgents: () => ({ owner: 'alpha', agents: roster.agents }) +})) +vi.mock('@/store/profile', async importOriginal => ({ + ...(await importOriginal()), + refreshProfiles: vi.fn(async () => []) +})) +vi.mock('@/store/fleet-roster', async importOriginal => ({ + ...(await importOriginal()), + refreshFleetRoster: vi.fn(async () => undefined) +})) +beforeEach(() => { + roster.agents = twoAgents +}) +afterEach(() => { + cleanup() + queryClient.clear() + vi.clearAllMocks() + $profiles.set([]) +}) + +const withQueries: RenderOptions['wrapper'] = ({ children }: { children: ReactNode }) => ( + {children} +) + +function Route() { + const location = useLocation() + + return ( + + {location.pathname} + {location.search} + + ) +} + +it('lands a normal window on an agent page instead of a directory', () => { + narrow = false + render( + + + + , + { wrapper: withQueries } + ) + expect(screen.getByLabelText('route').textContent).toBe('/settings?agentProfile=research&connection=alpha') +}) + +it('lists agents in a narrow window and opens the chosen gateway/profile identity', () => { + narrow = true + render( + + + + , + { wrapper: withQueries } + ) + // A two-agent roster is scanned, not searched. + expect(screen.queryByRole('textbox')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Research · Studio' })) + expect(screen.getByLabelText('route').textContent).toBe('/settings?agentProfile=research&connection=beta') +}) + +it('opens agent creation from the narrow list without navigating', () => { + narrow = true + render( + + + + , + { wrapper: withQueries } + ) + fireEvent.click(screen.getByRole('button', { name: en.profiles.newProfile })) + expect(screen.getByRole('dialog', { name: en.profiles.newProfile })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: en.common.cancel })) + expect(screen.queryByRole('dialog')).toBeNull() + expect(screen.getByLabelText('route').textContent).toBe('/') +}) + +it.each([true, false])('keeps default identity attached to its machine (is_default=%s)', isDefault => { + $profiles.set([ + { + name: 'research', + path: '/alpha/research', + has_env: false, + is_default: isDefault, + model: null, + provider: null, + skill_count: 0 + } + ]) + render( + + + , + { wrapper: withQueries } + ) + const local = screen.getByRole('button', { name: 'Research · Laptop' }) + const remote = screen.getByRole('button', { name: 'Research · Studio' }) + + expect(Boolean(within(local).queryByText(en.profiles.defaultBadge))).toBe(isDefault) + expect(within(remote).queryByText(en.profiles.defaultBadge)).toBeNull() +}) + +it.each(['directory', 'navigation'])( + 'ends an empty roster that failed to load in a Retry, not a loader (%s)', + async at => { + narrow = false + roster.agents = [] + vi.mocked(refreshProfiles).mockRejectedValueOnce(new Error('gateway unreachable')) + render( + + {at === 'directory' ? ( + + ) : ( + + )} + , + { wrapper: withQueries } + ) + + expect(await screen.findByText('gateway unreachable')).toBeTruthy() + expect(refreshFleetRoster).toHaveBeenCalledWith({ force: true }) + roster.agents = twoAgents + fireEvent.click(screen.getByRole('button', { name: en.common.retry })) + await waitFor(() => expect(screen.queryByText('gateway unreachable')).toBeNull()) + expect(refreshProfiles).toHaveBeenCalledTimes(2) + } +) diff --git a/apps/desktop/src/app/agent-settings/directory.tsx b/apps/desktop/src/app/agent-settings/directory.tsx new file mode 100644 index 0000000000000..239e5eeb0341a --- /dev/null +++ b/apps/desktop/src/app/agent-settings/directory.tsx @@ -0,0 +1,204 @@ +import './agent-settings.css' + +import { useStore } from '@nanostores/react' +import { useQuery } from '@tanstack/react-query' +import { useEffect, useState } from 'react' +import { useNavigate } from 'react-router' + +import { Button } from '@/components/ui/button' +import { ErrorState } from '@/components/ui/error-state' +import { FigmaAgentIcon } from '@/components/ui/figma-agent-icon' +import { SearchField } from '@/components/ui/search-field' +import { useMediaQuery } from '@/hooks/use-media-query' +import { useI18n } from '@/i18n' +import { resolveProfileColor } from '@/lib/profile-color' +import { refreshFleetRoster } from '@/store/fleet-roster' +import { $profileColors, $profiles, refreshProfiles } from '@/store/profile' + +import { useFleetRoster } from '../chat/sidebar/use-fleet-roster' +import { type SimplifiedAgent, useSimplifiedAgents } from '../chat/sidebar/use-simplified-agents' +import { usePageFrameCopy } from '../overlays/page-frame-copy' +import { AgentsFrameFallback } from '../overlays/page-frame-fallback' +import { + PAGE_SIDEBAR_NARROW, + PageSidebarCaption, + PageSidebarList, + PageSidebarPanel, + PageSidebarRow +} from '../overlays/page-sidebar' +import { Panel, PanelEmpty, PanelHeader } from '../overlays/panel' + +import { $lastViewedAgent, agentMachine, agentPageHref, pickLandingAgent } from './landing' +import { NewAgentButton } from './new-agent-button' + +/** A short roster is scanned, not searched; the field appears once the list outgrows a glance. */ +const SEARCH_FROM = 9 + +/** Every gateway lists at least its default agent, so an empty roster is loading until this window's + * agent list and the roster have both been read again; still empty after that, the reads failed. */ +function useEmptyRosterLoad(empty: boolean) { + const load = useQuery({ + queryKey: ['agent-roster', 'empty-load'], + queryFn: async () => { + await Promise.all([refreshProfiles(), refreshFleetRoster({ force: true })]) + + return true + }, + enabled: empty, + retry: false, + staleTime: 0 + }) + + return { + failed: empty && !load.isFetching && (load.isError || load.isSuccess) ? { error: load.error } : null, + retry: () => void load.refetch() + } +} + +/** The roster every Agents surface lists, with which row is the gateway's default agent. */ +function useAgentRoster() { + const profiles = useStore($profiles) + useFleetRoster(true) + const { agents, owner } = useSimplifiedAgents([]) + const defaultProfile = profiles.find(item => item.is_default)?.name + const load = useEmptyRosterLoad(agents.length === 0) + + const isDefault = (agent: SimplifiedAgent) => + agent.profile === defaultProfile && agentMachine(agent.connectionId) === agentMachine(owner) + + return { agents, isDefault, ...load } +} + +/** The roster could not be read: say so, with the one way forward. */ +function RosterFailure({ error, onRetry }: { error: unknown; onRetry: () => void }) { + const { t } = useI18n() + + return ( + + + + ) +} + +interface AgentRowsProps { + agents: readonly SimplifiedAgent[] + isDefault: (agent: SimplifiedAgent) => boolean + selected?: (agent: SimplifiedAgent) => boolean +} + +/** "N AGENTS" and one row per agent: tinted tile, name, DEFAULT chip (895:9473). */ +function AgentRows({ agents, isDefault, selected }: AgentRowsProps) { + const { t } = useI18n() + const navigate = useNavigate() + const colors = useStore($profileColors) + + return ( + + {t.agents.agentsCount(agents.length)} + {agents.map(agent => ( + navigate(agentPageHref(agent))} + > + + {agent.label} + {isDefault(agent) && {t.profiles.defaultBadge}} + + ))} + + ) +} + +interface AgentNavigationProps { + profile: string + connectionId: string +} + +/** Keep the selected agent's neighbours reachable while inspecting its settings. */ +export function AgentNavigation({ profile, connectionId }: AgentNavigationProps) { + const { t } = useI18n() + const { agents, isDefault, failed, retry } = useAgentRoster() + + return ( + } + title={t.simplifiedAgents.agents} + > + {failed && } + {agents.length > 0 && ( + agent.profile === profile && (agent.connectionId ?? 'local') === connectionId} + /> + )} + + ) +} + +/** The Agents destination. A normal window opens an agent's page (its column lists the others); + * a narrow one, where that column folds away, lands on the list itself and a row opens the page. */ +export function AgentDirectory({ onClose }: { onClose: () => void }) { + const { t } = useI18n() + const frame = usePageFrameCopy() + const narrow = useMediaQuery(PAGE_SIDEBAR_NARROW) + const lastViewed = useStore($lastViewedAgent) + const [query, setQuery] = useState('') + const { agents, isDefault, failed, retry } = useAgentRoster() + const landing = pickLandingAgent(agents, lastViewed, isDefault) + const navigate = useNavigate() + const target = landing && !narrow ? agentPageHref(landing) : null + + useEffect(() => { + if (target) { + navigate(target, { replace: true }) + } + }, [navigate, target]) + + if (failed) { + return ( + + } subtitle={frame.agentsDescription} title={t.profiles.title} /> + + + ) + } + + if (!landing || target) { + return + } + + const needle = query.trim().toLocaleLowerCase() + const visible = agents.filter(agent => `${agent.label} ${agent.gateway}`.toLocaleLowerCase().includes(needle)) + + return ( + + } subtitle={frame.agentsDescription} title={t.profiles.title} /> + {agents.length >= SEARCH_FROM && ( + + )} +
+ {visible.length === 0 ? ( + + ) : ( + + )} +
+
+ ) +} diff --git a/apps/desktop/src/app/agent-settings/entry.test.tsx b/apps/desktop/src/app/agent-settings/entry.test.tsx new file mode 100644 index 0000000000000..dc8c65d3f85f0 --- /dev/null +++ b/apps/desktop/src/app/agent-settings/entry.test.tsx @@ -0,0 +1,519 @@ +import { QueryClientProvider } from '@tanstack/react-query' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { MemoryRouter, useLocation } from 'react-router' +import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest' + +import { $apiRequestScope } from '@/api/client' +import { pluginSettingsRouteHref } from '@/contrib/settings-pages' +import { en } from '@/i18n/en' +import { queryClient } from '@/lib/query-client' +import { $agentPlugins, $agentPluginsStatus } from '@/store/agent-plugins' +import type * as GatewayStore from '@/store/gateway' +import { requestGatewayForAgent } from '@/store/gateway' +import { $activeGatewayProfile, $profiles } from '@/store/profile' +import { $settingsScopeOverride } from '@/store/settings-scope' +import { $shellChoice } from '@/store/shell-variant' + +import { routinesCopy } from '../routines/routines-copy' +import { $routineSelection, $routineSheet, closeRoutineSheet, selectRoutine } from '../routines/routines-store' + +import { SettingsView } from './entry' +import { $lastViewedAgent } from './landing' + +const routines = routinesCopy('en') + +const plugin = { + description: '', + key: 'image_gen/fal', + name: 'Fal', + source: 'user', + status: 'enabled', + version: '1', + settings_schema: [{ description: '', key: 'region', label: 'Region', required: false, type: 'string', value: 'us' }] +} + +const requestGateway = vi.fn(async (method: string, params?: Record) => { + if (method === 'plugins.manage') { + return params?.action === 'list' ? { plugins: [plugin] } : { ok: true, plugin } + } + + // The agent page counts connectors from the same list the Connectors page reads. + if (method === 'connectors.list') { + return { connectors: [] } + } + + return {} +}) + +vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({ + useGatewayRequest: () => ({ requestGateway }) +})) + +vi.mock('@/store/gateway', async importOriginal => ({ + ...(await importOriginal()), + requestGatewayForAgent: vi.fn( + async (_connectionId: string, _profile: string, method: string, params?: Record) => + requestGateway(method, params) + ) +})) + +vi.mock('@/components/chat/code-editor', () => ({ + CodeEditor: ({ + disabled, + initialValue, + onChange + }: { + disabled?: boolean + initialValue: string + onChange: (value: string) => void + }) => ( +