A local-first multi-agent app development platform, built on PenguinHarness
feat: theme switching lands in the Web App, and the gallery frames the real app (#892)
Yaowei Zheng1249e00d93fe
diff --git a/.agents/skills/penguin-harness-frontend/SKILL.md b/.agents/skills/penguin-harness-frontend/SKILL.mdindex 84e3bd67..ce1cf471 100644--- a/.agents/skills/penguin-harness-frontend/SKILL.md+++ b/.agents/skills/penguin-harness-frontend/SKILL.md@@ -38,9 +38,9 @@ Rules:- **Never make colour the only carrier.** Every status mark also names its state in an accessiblename or in adjacent text.- **Contrast is measured, not assumed.** The ratios in `tone.ts` are WCAG 2.x against the four- surfaces marks actually sit on — white and gray-50 in light, and the values this app *overrides*- in `styles.css` for dark (gray-950 is `#000000`, gray-900 is `#0d0d0d`, not Tailwind's stock- values). Recompute if you change a tone; a graphical mark needs 3:1, and `muted` is the one tone+ surfaces marks actually sit on — white and gray-50 in light, and the values the default theme+ *overrides* for dark (`packages/ui/src/themes/github.css`: gray-950 is `#000000`, gray-900 is+ `#0d0d0d`, not Tailwind's stock values). Recompute if you change a tone; a graphical mark needs 3:1, and `muted` is the one toneallowed below it because its meaning is always already in text.- **What is out of scope**, and must not be folded in: categorical palettes where colour is anidentity rather than a judgement (`category-colors.ts`, `token-colors.ts`, the timeline phase@@ -137,8 +137,9 @@ One record: `sizeTextClass` in `components/ui/input.tsx`. Two rungs — `sm` is`text-base` — and `sizeClass` pairs each with its padding. `Select`'s menu rows, `OptionMenu`'s rowtitles, `Textarea` and `FormPicker` all read it, so a rung moves the whole family at once.-The rungs are **relative, not the pixel values their names suggest**. `theme.tsx`'s `FONT_PX` sets-the root font size per tier (16/18/20px, default 18) and `styles.css` overrides no `--text-*`, so+The rungs are **relative, not the pixel values their names suggest**. `FONT_SCALE_PX` (in+`@prismshadow/penguin-ui/boot`, applied before first paint and by `theme.tsx`) sets the root font+size per tier (16/18/20px, default 18) and no stylesheet overrides a `--text-*`, so`text-xs` is 13.5px at the default tier rather than 12px, and every rung tracks the user's setting.**A call site passes `size`; it never spells a `text-*` class.** The caller's class and thediff --git a/.agents/skills/penguin-harness-manual-test/SKILL.md b/.agents/skills/penguin-harness-manual-test/SKILL.mdindex 3b22f0a5..e75f6468 100644--- a/.agents/skills/penguin-harness-manual-test/SKILL.md+++ b/.agents/skills/penguin-harness-manual-test/SKILL.md@@ -1,6 +1,6 @@---name: penguin-harness-manual-test-description: Use when standing PenguinHarness up to try a change by hand — launching the Web App, the desktop shell, the landing page or the docs site to click through it, screenshot it, or reproduce a report. Covers the four dev entry points and their ports, which data root each writes to, and the four ways a healthy setup looks broken.+description: Use when standing PenguinHarness up to try a change by hand — launching the Web App, the desktop shell, the landing page, the docs site or the component gallery to click through it, screenshot it, or reproduce a report. Covers the dev entry points and their ports, which data root each writes to, and the four ways a healthy setup looks broken.---# Standing PenguinHarness up to test by hand@@ -17,11 +17,14 @@ workspace deps); `pnpm desktop` runs a full `pnpm -r build`, so it is slow to st| installed app, launched with `--dev` | its own window | `~/.penguin/dev-data` || `pnpm dev:landing` | http://localhost:7366 | none (static) || `pnpm dev:docs` | http://localhost:7367 | none (static) |+| `pnpm dev:gallery` | http://localhost:7372 | none (static) |Other fixed ports (`packages/core/src/internal/ports.ts`): 7364 installed server, 7368 dev backend,7369 `pnpm penguin web` (data root `~/.penguin/dev-data-cli` — its own, so it can serve while anAgent it hosts runs `pnpm dev`; the lock is per root). On a shared box, `ss -tln` before assuming-one is free; `PORT=` inline moves it.+one is free; `PORT=` inline moves it. The gallery's port is strict — a busy 7372 fails instead of+drifting, because quoted gallery links and `pnpm --filter @prismshadow/penguin-ui-gallery shots`+name it.The user's installed app, server and CLI all use `~/.penguin/data` — their real Agents, Sessionsand keys. Never point a dev run there. Both surfaces print the root they took (`Data root: …`,diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9f090437..a37e50a3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -146,12 +146,14 @@ jobs:tests: pnpm --filter @prismshadow/penguin-server test- shard: web-clibuild: "@prismshadow/penguin-core...,@prismshadow/penguin-web..."- tests: pnpm --filter @prismshadow/penguin-web --filter @prismshadow/penguin-cli test+ tests: >-+ pnpm --filter @prismshadow/penguin-web --filter @prismshadow/penguin-ui+ --filter @prismshadow/penguin-cli test- shard: restbuild: "@prismshadow/penguin-desktop..."tests: >-pnpm --filter @prismshadow/penguin-desktop --filter @prismshadow/penguin-landing- --filter @prismshadow/penguin-docs test+ --filter @prismshadow/penguin-docs --filter @prismshadow/penguin-ui-gallery teststeps:- uses: actions/checkout@v5- uses: ./.github/actions/setupdiff --git a/.gitignore b/.gitignoreindex 12de4503..028a558f 100644--- a/.gitignore+++ b/.gitignore@@ -31,6 +31,8 @@ cache/# playwright e2e artifactspackages/web/test-results/+# component gallery screenshots (scripts/shots.mjs); never committed+packages/ui-gallery/shots/packages/web/playwright-report/# blog images staged locally by the landing capture/render scripts, then uploaded todiff --git a/.prettierignore b/.prettierignoreindex 2f5cbb64..928b82bc 100644--- a/.prettierignore+++ b/.prettierignore@@ -11,6 +11,10 @@ packages/desktop/stage/packages/desktop/out/packages/desktop/skills/+# Frost's MiSans slices and their @font-face sheet, written by scripts/build-misans.py (a+# formatter pass would read as drift against the script's own output)+packages/ui/src/fonts/misans/+# docs-only area (mostly Chinese; not machine-formatted)specs/*.mddiff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 1c9df78a..c97e1d5b 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -4,10 +4,14 @@ PenguinHarness itself is licensed under Apache-2.0 (see [LICENSE](LICENSE)). Somrelease artifacts** additionally bundle third-party programs and files, which keep their ownlicenses. This file records those, and how to obtain their source.-The programs below are downloaded by the release workflow (`.github/workflows/release.yml`) and-placed alongside the application inside the release archives; the fonts are copied out of an npm-dependency into the built web assets. Installing from npm (`@prismshadow/penguin-cli`) bundles none-of those programs or fonts.+The MiSans font files committed to this repository under `packages/ui/src/fonts/misans/` are not+covered by its Apache-2.0 license; like every other work listed here, they keep their own. The+programs below are downloaded by the release workflow (`.github/workflows/release.yml`) and placed+alongside the application inside the release archives. The fonts are part of the built web assets:+the build takes the MiSans files from this repository and copies every other font out of an npm+dependency. The web assets ship wherever the Web App does, and that includes npm:+`@prismshadow/penguin-cli` depends on `@prismshadow/penguin-server`, whose package carries them as+`web-dist/`. Installing from npm therefore bundles the fonts, but none of those programs.What earns an entry is a third-party work redistributed **as its own file**, or third-party code**adapted into this repository's own source**, whose license asks for its notice to go with every@@ -56,8 +60,8 @@ above, open an issue on this repository and we will provide it.## KaTeX fonts — `KaTeX_*.woff2` in the web assets-Present wherever the Web App ships: every release archive, the desktop application, and the assets-the server serves.+Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`.Math rendering uses [KaTeX](https://katex.org), whose typefaces are separate font files rather thancode. The web build copies them unmodified out of the `katex` npm package into the application's@@ -72,6 +76,249 @@ truetype fallbacks KaTeX also ships are dropped at build time (`dropNonWoff2FontSource: <https://github.com/KaTeX/KaTeX> — the tag matching the `katex` version resolved in`pnpm-lock.yaml`. The font sources and the script that builds them live in that repository.+## Mona Sans fonts — `mona-sans-*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`.++Mona Sans Variable, latin and latin-ext. The web build copies the files unmodified out of the+`@fontsource-variable/mona-sans` npm package.++**License: SIL Open Font License 1.1.** The full text ships in every build as+`fonts-licenses/mona-sans.txt`, mirrored from the package's `LICENSE` into+`packages/ui/src/fonts/LICENSES/mona-sans.txt`.++Source: <https://fontsource.org/fonts/mona-sans> — the `@fontsource-variable/mona-sans` version+resolved in `pnpm-lock.yaml`.++## JetBrains Mono fonts — `jetbrains-mono-*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`.++JetBrains Mono Variable, latin and latin-ext. The web build copies the files unmodified out of the+`@fontsource-variable/jetbrains-mono` npm package.++**License: SIL Open Font License 1.1.** The full text ships in every build as+`fonts-licenses/jetbrains-mono.txt`, mirrored from the package's `LICENSE` into+`packages/ui/src/fonts/LICENSES/jetbrains-mono.txt`.++Source: <https://fontsource.org/fonts/jetbrains-mono> — the `@fontsource-variable/jetbrains-mono`+version resolved in `pnpm-lock.yaml`.++## IBM Plex Sans fonts — `ibm-plex-sans-latin*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`.++IBM Plex Sans Variable, latin and latin-ext. The web build copies the files unmodified out of the+`@fontsource-variable/ibm-plex-sans` npm package.++**License: SIL Open Font License 1.1.** The full text ships in every build as+`fonts-licenses/ibm-plex-sans.txt`, mirrored from the package's `LICENSE` into+`packages/ui/src/fonts/LICENSES/ibm-plex-sans.txt`.++Source: <https://fontsource.org/fonts/ibm-plex-sans> — the `@fontsource-variable/ibm-plex-sans`+version resolved in `pnpm-lock.yaml`.++## IBM Plex Sans Condensed fonts — `ibm-plex-sans-condensed-*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`.++IBM Plex Sans Condensed at weight 600, latin and latin-ext. The web build copies the files+unmodified out of the `@fontsource/ibm-plex-sans-condensed` npm package.++**License: SIL Open Font License 1.1.** The full text ships in every build as+`fonts-licenses/ibm-plex-sans-condensed.txt`, mirrored from the package's `LICENSE` into+`packages/ui/src/fonts/LICENSES/ibm-plex-sans-condensed.txt`.++Source: <https://fontsource.org/fonts/ibm-plex-sans-condensed> — the+`@fontsource/ibm-plex-sans-condensed` version resolved in `pnpm-lock.yaml`.++## Commit Mono fonts — `commit-mono-*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`.++Commit Mono at weights 400 and 700, one latin file each. The web build copies the files unmodified+out of the `@fontsource/commit-mono` npm package.++**License: SIL Open Font License 1.1.** The full text ships in every build as+`fonts-licenses/commit-mono.txt`, mirrored from the package's `LICENSE` into+`packages/ui/src/fonts/LICENSES/commit-mono.txt`.++Source: <https://fontsource.org/fonts/commit-mono> — the `@fontsource/commit-mono` version resolved+in `pnpm-lock.yaml`.++## Noto Sans SC fonts — `noto-sans-sc-*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`.++Noto Sans SC Variable, as the 101 `unicode-range` slices of the package's own stylesheet. The web+build copies the files unmodified out of the `@fontsource-variable/noto-sans-sc` npm package.++**License: SIL Open Font License 1.1.** The full text ships in every build as+`fonts-licenses/noto-sans-sc.txt`, mirrored from the package's `LICENSE` into+`packages/ui/src/fonts/LICENSES/noto-sans-sc.txt`.++Source: <https://fontsource.org/fonts/noto-sans-sc> — the `@fontsource-variable/noto-sans-sc`+version resolved in `pnpm-lock.yaml`.++## MiSans fonts — `misans-*.woff2` in the web assets++Present wherever the Web App ships: every release archive, the desktop application, the assets the+server serves, and the npm server package's `web-dist/`. The files are also committed to this+repository, under `packages/ui/src/fonts/misans/`.++[MiSans](https://hyperos.mi.com/font/) is a typeface licensed by Xiaomi Inc. (小米科技有限责任公司).+The Frost theme sets its Latin and Chinese text in MiSans Regular (400) and Medium (500), and only a+browser showing that theme loads them. `packages/ui/scripts/build-misans.py` subsets the two faces+from Xiaomi's official package into `unicode-range` WOFF2 slices: glyph outlines, metrics, OpenType+features and name records are kept, the tables that index glyphs are rebuilt for each slice's+smaller glyph set, and the DSIG table is dropped. The slices are distributed only as part of the+application, in its source tree, its builds and its npm package, and are never offered on their+own. The application states that it uses MiSans on the Credits page of the Web App's settings+(Settings → Credits / 设置 → 版权信息), which names every bundled font with its licence+(condition 1 of the Agreement).++Every slice keeps the copyright notice of the font files:++Copyright © 2020-2025 Beijing Xiaomi Mobile Software Co.,Ltd. All Rights Reserved.++**License: MiSans Font Intellectual Property License Agreement (MiSans 字体知识产权许可协议).** The+full text, in Chinese and English, ships beside the fonts in every build as+`fonts-licenses/misans.txt`, so every copy keeps both the copyright notice and the Agreement+(condition 4). The canonical copy of the text is `packages/ui/src/fonts/LICENSES/misans.txt`,+transcribed from the licensor's PDF; the text below repeats it, and the two must be updated+together.++<details>+<summary>Full text</summary>++MiSans字体知识产权许可协议++MiSans Font Intellectual Property License Agreement++用户须知:++User Notes:++本《MiSans字体知识产权许可协议》(以下简称“协议”)是您与小米科技有限责任公司(以下简称“小米”或“许可方”)之间有关安装、使用MiSans字体(以下简称“MiSans”或“MiSans字体”)的法律协议。您在使用MiSans的所有或任何部分前,应接受本协议中规定的所有条款和条件。安装、使用MiSans的行为表示您同意接受本协议所有条款的约束。否则,请不要安装和/或使用MiSans,并应立即销毁和删除所有 MiSans 字体包。++The MiSans Font Intellectual Property License Agreement (hereinafter referred to as the “Agreement”) is a legal agreement between You and Xiaomi Inc. (hereinafter referred to as “Xiaomi” or “Licensor”) regarding the installation and use of MiSans fonts (hereinafter referred to “MiSans” or “MiSans Fonts”). You shall accept all of the terms and conditions in the Agreement before using all or any part of MiSans. By installing and using MiSans, You agree to be bound by all of the terms of this Agreement. Otherwise, You shall not install and/or use MiSans, and shall immediately destroy and delete all MiSans font packages.++1.定义++1\. Definition++1.1 “MiSans字体”代表许可方在本协议项下提供并明确标记为“MiSans”的字体软件,包括但不限于以各种形式、格式及媒介存在的源代码、数据库、文档等。++1.1 “MiSans Fonts” refers to the font software clearly marked as “MiSans” that is provided by Licensor under this Agreement, including but not limited to source code, database, and documentation in various forms, formats, and media.++1.2 “用户”或“您”代表行使本协议授予许可的自然人、法人或非法人组织。用户应依照本协议安装、使用MiSans。++1.2 The term “User” or “You” represents the natural person, legal person, or unincorporated organization exercising the license granted in this Agreement. The User shall install and use MiSans according to this Agreement.++1.3 “使用”是指安装、下载、复制、展览或以其他方式通过利用MiSans而获益的行为。++1.3 “Use” refers to the act of installing, downloading, copying, exhibiting, or otherwise benefiting from the use of MiSans.++2.授权许可++2\. Authorization and Permission++根据本协议的条款和条件,许可方在此授予您一份不可转让的、非独占的、免版税的、可撤销的、全球性的版权许可,使您依照本协议约定使用MiSans字体,前提是符合下列条件:++According to the terms and conditions of this Agreement, Licensor hereby grants You a non-transferable, non-exclusive, royalty-free, revocable, and global copyright license to use the MiSans fonts in accordance with this Agreement, provided that the following conditions are met:++1) 您应在软件中特别注明使用了 MiSans 字体。++1\) You shall specifically indicate in the Software that You are using MiSans fonts.++2)您不得对 MiSans 字体或其任何单独组件进行改编或二次开发。++2\) You shall not adapt or redevelop MiSans fonts or any of their individual components.++3)您不得单独将MiSans 字体或其组件对外租赁、再许可、给予、出借或进一步分发字体软件或其任何副本以及重新分发或售卖。此限制不适用于您使用 MiSans 字体创作的任何其他作品。如您使用 MiSans 字体创作宣传素材、logo、应用App等,您有权分发或出售该作品。++3\) You shall not individually rent, sublicense, give, loan, or further distribute the MiSans fonts or their components, or any copies thereof, nor shall you redistribute or sell them. This restriction does not apply to any other work that You create using MiSans fonts. For example, if You use MiSans fonts to create promotional materials, logos, applications (Apps), etc., You shall have the right to distribute or sell that work.++4)您应在 MiSans 字体的任何副本中保留版权声明和本协议。++4\) You shall retain the copyright notice and this Agreement in any copies of MiSans fonts.++5)不可将 MiSans 字体用于任何违法用途。++(5) You shall not use MiSans fonts for any illegal purposes.++3.知识产权++3\. Intellectual Property Rights++MiSans字体软件及其所包含的字体以及小米授权您制作的任何副本均为小米的知识产品,本字库软件的结构、组织和代码以及与本字库软件相关的所有信息均为小米的商业秘密。本字库软件及其所包含的字体受《中华人民共和国著作权法》、《计算机软件保护条例》和其他知识产权法律法规及国际公约、条约的保护。除本协议中明确的许可,小米不授予您对MiSans相关的其他知识产权权利。++MiSans Font Software and the fonts contained therein and any copies that Xiaomi authorizes You to make are the intellectual products of Xiaomi, and the structure, organization, and code of this font software and all information related to this font software are the trade secrets of Xiaomi. This font software and the fonts contained therein are protected by the Copyright Law of the People’s Republic of China, the Regulations on the Protection of Computer Software, and other intellectual property laws and regulations as well as international conventions and treaties. Xiaomi does not grant You any other intellectual property rights related to MiSans except those expressly granted in this Agreement.++4.免责声明++4\. Disclaimer++4.1 MiSans是按“原样”提供的。许可方不对本协议作出任何明示、暗示或依照法令的担保,包括但不限于对适销性、所有权、就某一用途的适用性或不侵犯版权、专利、商标或其他权利的保证。++4.1 MiSans is provided “as is”. The Licensor makes no express, implied, or statutory warranties with respect to this Agreement, including, but not limited to, warranties of merchantability, ownership, fitness for a particular purpose, or non-infringement of copyrights, patents, trademarks, or other rights.++4.2 在任何情况下,许可方及其关联公司均不对任何直接、间接、特殊、附带或间接的损害(包括但不限于购买替代商品或服务)负责。无论根据合同理论、侵权行为(包括过失)理论、严格责任理论或其他法律理论,因使用或无法使用 MiSans 字体,即使许可方及其关联公司已被告知存在这种损害的可能性,而导致的任何方式的业务中断,使用数据或利润的损失,许可方及其关联公司不承担任何责任。++4.2 In no event shall Licensor and its affiliates be liable for any direct, indirect, special, incidental, or consequential damages (including, but not limited to, the purchase of substitute goods or services). Whether under the contract theory, the tort (including negligence) theory, the strict liability theory, or other legal theories, Licensor and its affiliates shall not be liable for any form of business interruption, or loss of service data or profits resulting from the use of or inability to use MiSans fonts, even if Licensor and its affiliates have been advised of the possibility of such damages.++4.3 您需明确承担使用 MiSans 字体的所有责任和风险。如果无法证明 MiSans 有任何缺陷,您将承担所有必要的服务,修复或纠正的全部费用。++4.3 You shall expressly assume all responsibility and risk for using MiSans fonts. If it cannot be proven that MiSans is subject to any defect, You shall be responsible for all necessary services, repairs, or rectifications at full cost.++5.许可终止。++5\. License Termination++一旦您违反本协议的条款,小米随时可能终止本协议、收回授权,并要求您承担相应法律责任。++If You violate the terms of this Agreement, Xiaomi may terminate the Agreement, withdraw the license, and hold You liable for the corresponding legal responsibility at any time.++6.适用法律与管辖。++6\. Applicable Laws and Jurisdiction++本协议适用中华人民共和国的法律。如您与小米就本协议的相关问题发生争议,您与小米均有权向北京市海淀区人民法院提起诉讼。++The Agreement shall be governed by the laws of the People’s Republic of China. In case of any dispute between You and Xiaomi regarding this Agreement, both You and Xiaomi shall have the right to file a lawsuit at Beijing Haidian District People’s Court.++7.一般规定。++7\. General Provisions++7.1 本协议是小米与您之间有关MiSans软件及其所包含的字体的最新许可协议,它将取代先前所有与本字库软件相关的陈述、承诺、宣传或许可协议。++7.1 This is the most recent license agreement between Xiaomi and You regarding the MiSans Software and the fonts contained therein, and it shall supersede all prior representations, undertakings, publicity, or license agreements relating to this font software.++7.2 如果您对本协议有任何疑问或者希望获得有关字体授权许可的任何信息,请通过如下方式与小米联系:++7.2 If You have any questions regarding the Agreement or wish to learn any information regarding the licensing of the Font, please contact Xiaomi as follows:++小米科技有限责任公司++Xiaomi Inc.++地址: 北京市海淀区西二旗中路33号院小米科技园++Address: Xiaomi Campus, No. 33 Xi erqi Middle Road, Haidian District, Beijing,100085,China+++Email: [email protected]++</details>+## GenericAgent — the built-in browser's page scriptsAdapted into this repository's source, so present wherever the server ships: every release archive,diff --git a/changelog/unreleased/2026-09-16-penguin-ui-token-contract.md b/changelog/unreleased/2026-09-16-penguin-ui-token-contract.mdnew file mode 100644index 00000000..e439b4f8--- /dev/null+++ b/changelog/unreleased/2026-09-16-penguin-ui-token-contract.md@@ -0,0 +1,57 @@+# The shared UI package, its token contract, and the default theme wired into the Web App++- **Date:** 2026-09-16+- **Type:** refactor+- **Scope:** `ui`, `web`, `ci`+- **PR:** [#765](https://github.com/Prism-Shadow/penguin-harness/pull/765)++[中文版](2026-09-16-penguin-ui-token-contract.zh.md)++The first step of the theme system. A private, source-only package, `@prismshadow/penguin-ui`+(`packages/ui`), took over the Web App's colours, radii, shadows, fonts and focus and scrollbar+rules as one named set of design tokens, and the current look became its default theme, `github`,+value for value: the twelve pages the pixel diff covers render identically in both modes and both+languages, and the one rule whose font stack moved, `.font-sans`, is described below. The one+intended visible change is on first load: the stored light/dark mode, accent and font size are+applied before the first frame, so a dark page no longer flashes white while the bundle loads and+the first frame no longer renders at 16px and reflows to the 18px default.++## Details++- `tokens.ts` holds the contract: 186 `--ui-*` names in 15 groups (surfaces, text, lines, accent,+ six semantic tones × five parts including the new `done` and `info`, charts, code and diff,+ shape, elevation and glass, type families, the type and heading scale, density, motion, icons,+ focus/selection/scrollbar), plus the theme ids `github` / `modern` / `geek`.+- `theme.css` declares the `dark` variant, two cascade layers after Tailwind's own (`ui-theme`,+ then `ui-accent`, so an accent preset always beats a theme's dark block), a bridge that exposes+ the tokens as utilities (`bg-surface`, `text-fg-muted`, `border-line`, `bg-accent`,+ `text-tone-danger-fg`, …) and re-points Tailwind's font, radius and shadow scales at them, the+ base rules that read tokens, and the five accent presets.+- `.font-sans` reads the app's own sans stack (`--ui-font-sans`) instead of Tailwind's stock+ `ui-sans-serif, system-ui, sans-serif, …`. One element uses the class, the full-prompt preview+ folded into the Create-with-AI dialogs: its Latin text keeps its face (`system-ui` is second in+ both stacks), and its CJK text now resolves through the named PingFang SC / Microsoft YaHei+ instead of the OS fallback, the same face on most systems but not guaranteed on Windows.+- `themes/github.css` defines every token with the app's existing values, and a gray bridge that+ re-points Tailwind's `--color-gray-*` and `--color-white`, so the existing gray classes follow+ the theme with no component edits. Its base rule holds every token; its dark rule holds only the+ values dark changes, so a mode-independent group (shape, type, density, motion, icons) is+ written once. `themes/modern.css` and `themes/geek.css` were added as empty placeholders.+- `boot.ts` generates the pre-paint script now inlined in `packages/web/index.html`, and the+ `applyThemeAttributes()` the theme provider reconciles with. The dark `theme-color` became+ `#000000`, the page's real dark background.+- The theme provider gained a stored theme id (`penguin.themeId`, default `github`), applied as+ `html[data-theme]`; no setting exposes it yet. The key is classified as a browser preference for+ the data-root sweep.+- The Web App depends on the package as `workspace:*`, which pnpm links to `packages/ui`, so Vite,+ vitest and tsc read its live source through the package's `exports`, and Tailwind scans the+ package's source. `styles.css` dropped the rules the package now owns.+- Call sites that spelled `var(--accent-bg)` / `var(--accent-fg)` moved to `bg-accent`,+ `border-accent`, `ring-accent` and `text-accent-fg`, and the three `bg-black/45` dialog backdrops+ moved to the `--ui-overlay-backdrop` token. `--accent-bg` / `--accent-fg` remain as aliases for+ one wave.+- `packages/web/scripts/theme-shots.mjs` captures twelve pages × light/dark × en/zh from any+ number of web builds against one server, one data set and a frozen clock, and diffs the shot+ trees pixel for pixel.+- The CI `web-cli` shard runs the new package's tests, and the port table in+ `packages/core/src/internal/ports.ts` reserves 7372 for the component gallery's dev server.diff --git a/changelog/unreleased/2026-09-16-penguin-ui-token-contract.zh.md b/changelog/unreleased/2026-09-16-penguin-ui-token-contract.zh.mdnew file mode 100644index 00000000..1f243707--- /dev/null+++ b/changelog/unreleased/2026-09-16-penguin-ui-token-contract.zh.md@@ -0,0 +1,45 @@+# 共享 UI 包、令牌契约,以及接入 Web App 的默认主题++- **Date:** 2026-09-16+- **Type:** refactor+- **Scope:** `ui`, `web`, `ci`+- **PR:** [#765](https://github.com/Prism-Shadow/penguin-harness/pull/765)++[English](2026-09-16-penguin-ui-token-contract.md)++主题系统的第一步。新增私有、源码直引的包 `@prismshadow/penguin-ui`(`packages/ui`),把 Web App 的+颜色、圆角、阴影、字体以及焦点环与滚动条规则收拢为一组具名设计令牌;现有外观原值原样成为它的默认主题+`github`:像素比对覆盖的 12 个页面在明暗两种模式、中英两种语言下渲染完全一致,字体栈有变的唯一一条规则+`.font-sans` 见下文。唯一有意的可见变化在首次加载:已存的明暗模式、强调色与字号在首帧之前就已套用,+深色页面在脚本加载期间不再闪白,首帧也不再先以 16px 渲染、再重排到默认的 18px。++## 细节++- `tokens.ts` 承载契约:15 组共 186 个 `--ui-*` 名称(表面、文字、线条、强调色、六个语义色调 × 五部分+ ——含新增的 `done` 与 `info`、图表、代码与差异、形状、层次与磨砂、字体族、字号与标题层级、密度、动效、+ 图标、焦点/选区/滚动条),以及主题 id `github` / `modern` / `geek`。+- `theme.css` 声明 `dark` 变体、排在 Tailwind 自身之后的两个级联层(先 `ui-theme` 后 `ui-accent`,+ 强调色预设因此总能压过主题的深色块)、把令牌暴露为工具类(`bg-surface`、`text-fg-muted`、+ `border-line`、`bg-accent`、`text-tone-danger-fg` 等)并把 Tailwind 的字体、圆角与阴影刻度改指令牌的+ 桥接、读取令牌的基础规则,以及五个强调色预设。+- `.font-sans` 改读应用自身的无衬线字体栈(`--ui-font-sans`),不再是 Tailwind 缺省的+ `ui-sans-serif, system-ui, sans-serif, …`。用到该类的只有一处,即「用 AI 创建」对话框里折叠的+ 完整提示词预览:拉丁文字体不变(两个字体栈的第二项都是 `system-ui`),中文改经具名的 PingFang SC /+ Microsoft YaHei 解析、不再落到系统回退字体,多数系统上是同一字体,Windows 上则不能保证。+- `themes/github.css` 以应用现有取值定义每个令牌,并用一段灰阶桥接改指 Tailwind 的+ `--color-gray-*` 与 `--color-white`,现有灰阶类无需改动组件即随主题变化。它的基础规则定义全部令牌,+ 深色规则只写深色下取值不同的令牌,与明暗无关的组(形状、字号、密度、动效、图标)只写一次。+ `themes/modern.css` 与 `themes/geek.css` 以空占位文件加入。+- `boot.ts` 生成现已内联进 `packages/web/index.html` 的首帧前脚本,以及主题 Provider 用来同步的+ `applyThemeAttributes()`。深色 `theme-color` 改为页面真实的深色背景 `#000000`。+- 主题 Provider 新增一个存储的主题 id(`penguin.themeId`,缺省 `github`),以 `html[data-theme]`+ 套用;尚无设置项暴露它。该键在数据根清扫中归为浏览器偏好。+- Web App 以 `workspace:*` 依赖该包,pnpm 将其链接到 `packages/ui`,Vite、vitest 与 tsc 因而按包的+ `exports` 直接读取包的源码,Tailwind 也扫描包的源码。`styles.css` 删去了改由包负责的规则。+- 原先写 `var(--accent-bg)` / `var(--accent-fg)` 的调用处改为 `bg-accent`、`border-accent`、+ `ring-accent` 与 `text-accent-fg`,三处 `bg-black/45` 对话框遮罩改读 `--ui-overlay-backdrop` 令牌。+ `--accent-bg` / `--accent-fg` 作为别名再保留一个波次。+- `packages/web/scripts/theme-shots.mjs` 针对同一服务端、同一份数据与冻结的时钟,从任意多个 Web 构建+ 截取 12 个页面 × 浅色/深色 × 中/英,并逐像素比对截图目录。+- CI 的 `web-cli` 分片运行新包的测试;`packages/core/src/internal/ports.ts` 的端口表为组件画廊的开发+ 服务器预留 7372。diff --git a/changelog/unreleased/2026-09-16-theme-fixtures-screens.md b/changelog/unreleased/2026-09-16-theme-fixtures-screens.mdnew file mode 100644index 00000000..b4511f20--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-fixtures-screens.md@@ -0,0 +1,77 @@+# The shared UI package gains a mock dataset and four full-screen mock-ups for the gallery++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `ui`+- **PR:** [#763](https://github.com/Prism-Shadow/penguin-harness/pull/763)++[中文版](2026-09-16-theme-fixtures-screens.zh.md)++`@prismshadow/penguin-ui` gained `fixtures/`, one typed mock dataset in English and Chinese, and+`screens/`, four static full-screen compositions the theme gallery renders at `/screens/:name`. The+Web App imports neither, so it looks exactly as before.++## Fixtures++- The "Build Claude Code docs expert" session the landing page's screenshots are captured from, as+ a two-turn run: user and assistant turns, settled and streaming thinking and text, and tool calls+ to `exec_command` with output, `read_file`, `edit_file` and `write_file` with diffs, a+ `run_subagent` call with the child's own transcript, and a command waiting for approval.+- A Trace of the same run (file list, overall figures, per-turn timeline lanes and event rows), ten+ models copied from the built-in catalog, the Workspace file tree and a file preview, the sidebar's+ session groups, and a company with employees, tickets in every column and a week of calendar+ events.+- Chrome copy taken from the Web App's two dictionaries, and specimen text for the fonts page and+ the Typography foundation that mixes Chinese, Latin, code and numbers.+- The sets the gallery's modules compose: a notice per tone and a toast pair, a provider form with+ one invalid and one policy-held field, a message context menu with a shortcut and one destructive+ item, six Vault rows, four installed plugins, the command palette's two groups, and a week of+ token usage in three buckets. Their colours, versions, icons, shortcuts and series are+ locale-independent and live in `fixtures/shared.ts`; only words are per locale.+- `en` and `zh` are built from one structure (`fixtures/dataset.ts`) and differ only in prose;+ `fixturesFor(lang)` returns either.++## Screens++- `chat`: a Task mid-run, with the sidebar, an opened diff, a running subagent, a pending approval,+ the composer with chips, and the Subagents dock streaming the child's reply.+- `traces`: the Trajectories dock with the Overall summary, a turn's execution timeline, legend and+ event rows.+- `settings`: the paged settings dialog on Appearance over the chat, with an info popover open.+- `login`: the sign-in card over the decorative canvas.+- The screens use token utilities and the declared style hooks only, so each theme restyles them+ through its token values; package components replace their stand-in pieces wave by wave.+- The package exports them as `@prismshadow/penguin-ui/screens` (`SCREENS`, `screenById`).++## De-slop++The screens are held to the theme work's component rules, so what the gallery shows is what the+rules ask for rather than the drafts they were written from.++- The deleted style hooks are gone from the markup: no ambient wash or column grid behind a+ transcript, a settings page or a Trace panel, no dot matrix behind the login (the circuit traces+ stay — the login's one decoration, in every theme), no corner ticks on the approval block, no+ hover-pill radius on buttons and cards, no mono uppercase button labels. Controls read their+ shape from `--ui-radius-control` instead.+- Each remaining hook sits on the component that hosts it: the glass of the settings dialog is a+ `Modal`, the glass of its popover a `FloatingPanel`, the glass of the composer a `ComposerCard`,+ the rail's group titles the `PagedDialog`'s eyebrows, the sidebar's and the call graph's a+ `GroupHeader`, the diff a `DiffViewer` and the fenced block a `CodeBlock`. The dialog's page+ title is an ordinary `h2` — the display face is for a page's one display title — and it lost the+ sun glyph the rail already shows.+- Status is a word again: a run state prints in sentence case at the caption rung in its tone's+ ink (`Running`, `Needs approval`, `Failed`), with the five words in both dictionaries, instead of+ 10–11 px uppercase with wide tracking. Nothing on the screens is set below `.75rem` any more.+- The pending-approval block keeps its amber fill but takes the neutral rule above it, and its+ alias is mono text rather than a chip; the subagent shortcut is a row under its call instead of a+ bordered card inside the work group; the Trace's Overall is a ruled section and its timeline sits+ in the turn's body, both without a box of their own; the composer's stop is a solid control, not+ a danger glyph on a danger tint.+- `Pill`, `IconSquare` and the hand-rolled ring spinner were replaced by stand-ins in the shapes+ W1's components take, so the swap is a rename: `Badge` (`tone`, `variant`, `soft` taking the+ neutral line), `IconButton` (flat at rest, filled only when `pressed`, label required) and+ `Spinner` (`xs` / `sm` / `md` at 10 / 12 / 14, `tone`, `label`). The spinner is the real+ component: it lives at `src/components/icons/spinner/spinner.tsx`, the one file allowed to spin,+ and draws an arc a theme re-times through `.ui-live[data-live="spinner"]`.+- The accent swatches' hex values moved into the fixtures, where identity data belongs, and each+ swatch now carries its name in both dictionaries.diff --git a/changelog/unreleased/2026-09-16-theme-fixtures-screens.zh.md b/changelog/unreleased/2026-09-16-theme-fixtures-screens.zh.mdnew file mode 100644index 00000000..e4c89acf--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-fixtures-screens.zh.md@@ -0,0 +1,58 @@+# 共享 UI 包新增模拟数据集与四个整页示意,供组件画廊使用++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `ui`+- **PR:** [#763](https://github.com/Prism-Shadow/penguin-harness/pull/763)++[English](2026-09-16-theme-fixtures-screens.md)++`@prismshadow/penguin-ui` 新增 `fixtures/` 与 `screens/`:前者是一套中英双语的类型化模拟数据,后者是四个静态+整页组合,由主题画廊在 `/screens/:name` 渲染。Web App 不引用其中任何一个,应用外观与此前完全一致。++## 模拟数据++- 取自落地页截图所用的「构建 Claude Code 文档专家」会话,扩展为两轮运行:用户与助手轮次,已完成和流式输出中的+ 思考与正文,以及工具调用——带输出的 `exec_command`、`read_file`、带 diff 的 `edit_file` 与 `write_file`、+ 附带子会话记录的 `run_subagent`,还有一条等待审批的命令。+- 同一次运行的 Trace(文件列表、全局统计、每轮执行时间线与事件行)、取自内置模型目录的十个模型、Workspace+ 文件树与文件预览、侧栏会话分组,以及一家公司:员工、覆盖全部列的工单和一周的日历事件。+- 界面文案取自 Web App 的两本词典;为字体页与排版基础页准备了混排中文、拉丁字母、代码与数字的字样文本。+- 画廊各模块所需的数据集:每种色调一条通知与两条浮条、一份含一个非法字段和一个被服务器策略锁定字段的提供方+ 表单、一份带快捷键与一个危险项的消息右键菜单、六行密钥库记录、四个已安装插件、命令面板的两个分组,以及+ 一周分三档的 Token 用量。其中的颜色、版本号、图标、快捷键与数值序列与语言无关,放在 `fixtures/shared.ts`;+ 按语言区分的只有文字。+- `en` 与 `zh` 由同一份结构(`fixtures/dataset.ts`)生成,只有文字不同;`fixturesFor(lang)` 返回对应语言。++## 整页示意++- `chat`:运行中的 Task,含侧栏、展开的 diff、运行中的子智能体、待审批命令、带附件标签的输入框,以及正在流式输出+ 子会话回复的子智能体停靠面板。+- `traces`:轨迹观测停靠面板,含全局统计、单轮执行时间线、图例与事件行。+- `settings`:对话之上的分页设置对话框,停在「外观」页,并展开一个说明浮层。+- `login`:装饰画布上的登录卡片。+- 示意只使用令牌工具类与已声明的样式钩子,各主题通过自身令牌取值改变其外观;组件逐波迁入共享包后,替换其中的占位部件。+- 包以 `@prismshadow/penguin-ui/screens` 导出(`SCREENS`、`screenById`)。++## 去 AI 味++整页示意改为遵守主题工作的组件规则,画廊所展示的因此是规则要求的样子,而不是当初草稿的样子。++- 被删除的样式钩子从标记中移除:对话、设置页与 Trace 面板背后不再有氛围渐变与栅格,登录页背后不再有点阵+ (电路走线保留——它是登录页在三个主题中唯一的装饰),审批块不再有角标,按钮与卡片不再在悬停时改变圆角,+ 按钮标签也不再是等宽大写。控件改为从 `--ui-radius-control` 取形状。+- 保留的每个钩子都落在承载它的组件上:设置对话框的玻璃属于 `Modal`,其说明浮层的玻璃属于 `FloatingPanel`,+ 输入框的玻璃属于 `ComposerCard`,导航栏分组标题是 `PagedDialog` 的 eyebrow,侧栏与调用关系的分组标题是+ `GroupHeader`,diff 是 `DiffViewer`,代码块是 `CodeBlock`。对话框的页面标题改为普通 `h2`——display+ 字面留给一个页面唯一的展示标题——并去掉了导航栏已经显示过的太阳图标。+- 状态重新成为一个词:运行状态以说明文字字号、句首大写、按色调着墨呈现(`运行中`、`待审批`、`失败`),五个+ 词在两本词典中都有,而不再是 10–11 px 的大写加宽字距。整页示意中不再有小于 `.75rem` 的文字。+- 待审批块保留琥珀色底,但其上方改用中性分隔线,工具短名改为等宽文本而非标签;子会话快捷入口从工作组内部+ 的带框卡片改为其调用下方的一行;Trace 的全局统计改为带横线的分节,执行时间线直接放在该轮正文里,两者都+ 不再自带盒子;输入框的停止按钮是一个实心控件,而不是浅色危险底上的危险色图标。+- `Pill`、`IconSquare` 与手写的环形转圈替换为 W1 组件形状的占位件,将来替换只是改名:`Badge`(`tone`、+ `variant`,`soft` 取中性边线)、`IconButton`(静止时无底色,仅 `pressed` 时填充,label 必填)与+ `Spinner`(`xs` / `sm` / `md` 对应 10 / 12 / 14,含 `tone` 与 `label`)。其中转圈是真组件:它位于+ `src/components/icons/spinner/spinner.tsx`——唯一允许旋转的文件——绘制一段圆弧,主题通过+ `.ui-live[data-live="spinner"]` 重新设定其节奏。+- 主题色色块的十六进制取值移入模拟数据(身份数据本就该放在那里),每个色块在两本词典中都有了名字。diff --git a/changelog/unreleased/2026-09-16-theme-fonts-frost-console.md b/changelog/unreleased/2026-09-16-theme-fonts-frost-console.mdnew file mode 100644index 00000000..4c6b5c36--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-fonts-frost-console.md@@ -0,0 +1,72 @@+# The shared UI package bundles its fonts and defines the Frost and Console themes++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `ui`, `web`+- **PR:** [#761](https://github.com/Prism-Shadow/penguin-harness/pull/761)++[中文版](2026-09-16-theme-fonts-frost-console.zh.md)++`@prismshadow/penguin-ui` gained the fonts of all three themes, the token values of its two new+themes, Frost (`modern`, after sierra.ai) and Console (`geek`, after e2b.dev), and the closed list of+style hooks the themes give recipes to. Nothing in the Web App names a new theme yet, so the app+looks as before, apart from a font credit at the foot of the account menu.++## Fonts++- Six fontsource packages, all SIL Open Font License 1.1: Mona Sans and JetBrains Mono (declared+ for the later Primer polish; Frost already sets code in JetBrains Mono), IBM Plex Sans, IBM Plex+ Sans Condensed (600 only) and Commit Mono for Console, and Noto Sans SC for Console's Chinese (and+ Primer's from W1a).+- Frost sets Latin and Chinese alike in MiSans by Xiaomi, at weights 400 and 500. MiSans has no+ official npm package, so `scripts/build-misans.py` cuts MiSans Regular and Medium from Xiaomi's+ official package into 99 `unicode-range` WOFF2 slices per weight under `fonts/misans/`, following+ Noto Sans SC's slice partition, and reads every slice back to confirm that its glyphs, features and+ name records are the original's. The rare ideographs outside that partition are not shipped.+ Frost turns weight synthesis off, so a bold request renders in Medium.+- A page downloads only the font files its theme names and the slices its text touches: on a+ specimen page, Frost fetched 93 KB of fonts for English and 627 KB for Chinese, and Primer, which+ names no bundled family yet, fetches none. The `@font-face` declarations are different: every+ theme's rules sit in the app's main stylesheet, so every user downloads them, about 94 KB of its+ 122 KB gzipped, an accepted cost rather than loading each theme's font sheet on demand. The build+ never inlines a font into that stylesheet. A build carries 9.1 MB of fonts: 4.26 MB of MiSans,+ 4.52 MB of Noto Sans SC and 0.32 MB of Latin faces.+- `scripts/sync-font-licenses.mjs` mirrors each fontsource licence into `fonts/LICENSES/`. The MiSans+ Font Intellectual Property License Agreement is transcribed there from Xiaomi's PDF and listed in+ `fonts/vendored-fonts.json`. The `penguinUi()` Vite plugin emits every licence text into each build+ as `fonts-licenses/<name>.txt`, and `fonts/README.md` records the families, their licences, the+ bytes and how to update them.+- The Web App's account menu ends with a line crediting MiSans, as its licence requires, in both+ languages.++## Tokens and hooks++- The token contract holds 188 names: `--ui-radius-control` (the pressable control's shape, bridged+ as `rounded-control`; Primer 0.375rem, Frost a pill, Console 0), `--ui-stack-0` and `--ui-stack-4`+ were added, and `--ui-glass-highlight` was removed. `themes/github.css` declares the three new names+ at the app's current values.+- `hooks.ts` lists the six style hooks, `ui-glass`, `ui-eyebrow`, `ui-display`, `ui-live`, `ui-frame`+ and `ui-underline-nav`, with the markup each recipe relies on.+- `theme.css` gives buttons, links and tabs a default transition-property list (colour,+ background and border colour, opacity and box-shadow), which any `transition-*` utility+ replaces; nothing animates until a component sets a duration.++## Themes++- `themes/modern.css` and `themes/geek.css` define every token, plus the gray and white re-pointing+ that carries the app's existing palette classes onto each theme's neutrals. As in+ `themes/github.css`, the base rule holds every token with its light value and the dark rule only+ what dark changes.+- Frost: a warm off-white canvas with white cards, pill-shaped controls with boxes on a 4–20 px+ radius scale, one green accent, regular-weight headings, untinted tight shadows, and frosted glass+ (a 16 px blur) only on menus, popovers, the modal card, the floating composer and a sticky header.+ Its dark mode is a warm near-black palette of our own, since sierra.ai has none.+- Console: a black (or white) canvas, 1 px rules, radius 0 everywhere, one orange accent, a condensed+ uppercase h1 above Plex Sans headings in sentence case, uppercase group labels, stepped live+ signals, mono only for code and data, and depth drawn with lines; the modal card carries a+ line-emphasis border instead of a shadow.+- Both themes share one type scale, with heading steps of 1.25 and nothing below .75rem, and state+ transitions of 120–200 ms. The padding-block of their controls (0.25, 0.375 and 0.625rem), rows+ (0.375rem) and menu rows (0.5rem) is Primer's, so a theme switch shifts no such height. Both carry+ the `done` and `info` tones, and every tone reads at 4.5:1 as text on its own tint and at 3:1 as a+ mark on every surface.diff --git a/changelog/unreleased/2026-09-16-theme-fonts-frost-console.zh.md b/changelog/unreleased/2026-09-16-theme-fonts-frost-console.zh.mdnew file mode 100644index 00000000..39b7c4a6--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-fonts-frost-console.zh.md@@ -0,0 +1,60 @@+# 共享 UI 包打包字体,并定义 Frost 与 Console 两套主题++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `ui`, `web`+- **PR:** [#761](https://github.com/Prism-Shadow/penguin-harness/pull/761)++[English](2026-09-16-theme-fonts-frost-console.md)++`@prismshadow/penguin-ui` 加入了三套主题的字体、两套新主题的令牌取值:Frost(`modern`,参照 sierra.ai)+与 Console(`geek`,参照 e2b.dev),以及各主题为之编写样式的封闭样式钩子清单。Web App 中尚无任何地方引用+新主题,除账户菜单底部多出一行字体致谢外,应用外观与此前一致。++## 字体++- 六个 fontsource 包,全部为 SIL Open Font License 1.1:Mona Sans 与 JetBrains Mono(为后续的 Primer 打磨+ 预先声明;Frost 已用 JetBrains Mono 排代码)、Console 的 IBM Plex Sans、IBM Plex Sans Condensed(仅 600)+ 与 Commit Mono,以及 Console 的中文字体 Noto Sans SC(Primer 自 W1a 起也用它)。+- Frost 的拉丁文与中文统一使用小米的 MiSans,字重 400 与 500。MiSans 没有官方 npm 包,因此由+ `scripts/build-misans.py` 从小米官方字体包中截取 MiSans Regular 与 Medium,按 Noto Sans SC 的分片划分,+ 各切成 99 个 `unicode-range` WOFF2 分片放入 `fonts/misans/`,并逐个回读分片,确认其中的字形、OpenType+ 特性与名称记录均与原字体一致。该划分之外的生僻汉字不随包分发。Frost 关闭了字重合成,粗体请求以 Medium+ 呈现。+- 页面只下载当前主题引用的字体文件,以及文字实际用到的分片:在样例页面上,Frost 的英文页加载 93 KB 字体,+ 中文页加载 627 KB;Primer 目前不引用任何随包字族,不下载字体文件。`@font-face` 声明则不同:三套主题的声明都+ 在应用的主样式表里,每个用户都要下载,约占其压缩后 122 KB 中的 94 KB;这一开销已被接受,没有改为按主题按需+ 加载字体样式表。构建时不把字体内联进该样式表。构建产物共含 9.1 MB 字体:MiSans 4.26 MB、Noto Sans SC+ 4.52 MB、拉丁字形 0.32 MB。+- `scripts/sync-font-licenses.mjs` 把各 fontsource 包的许可文本镜像到 `fonts/LICENSES/`。《MiSans 字体知识产权+ 许可协议》依小米发布的 PDF 转录到同一目录,并登记在 `fonts/vendored-fonts.json` 中。`penguinUi()` Vite 插件+ 把所有许可文本以 `fonts-licenses/<名称>.txt` 输出到每个构建产物中;`fonts/README.md` 记录各字族、许可、+ 字节数与更新方法。+- Web App 的账户菜单末尾按 MiSans 许可协议的要求加入一行致谢,中英文各一。++## 令牌与钩子++- 令牌契约共 188 个名称:新增 `--ui-radius-control`(可按压控件的形状,桥接为 `rounded-control`;Primer+ 0.375rem、Frost 胶囊形、Console 为 0)、`--ui-stack-0` 与 `--ui-stack-4`,删除 `--ui-glass-highlight`。+ `themes/github.css` 以应用当前的取值声明了这三个新名称。+- `hooks.ts` 列出六个样式钩子:`ui-glass`、`ui-eyebrow`、`ui-display`、`ui-live`、`ui-frame` 与+ `ui-underline-nav`,并写明每个样式依赖的标记结构。+- `theme.css` 为按钮、链接与标签页设定默认的过渡属性列表(文字颜色、背景与边框颜色、不透明度和阴影),+ 任何 `transition-*` 工具类都会将其替换;组件不设时长就没有过渡。++## 主题++- `themes/modern.css` 与 `themes/geek.css` 定义全部令牌,并重新指向灰阶与白色,让应用现有的调色板类落到+ 各主题自己的中性色上。与 `themes/github.css` 相同,基础规则以浅色取值定义全部令牌,深色规则只写深色下+ 变化的取值。+- Frost:暖米白画布配白色卡片,控件为胶囊形,容器圆角取 4–20 px 刻度,单一绿色强调色,标题用常规字重,阴影+ 不带色调且收得很紧;磨砂玻璃(16 px 模糊)只用于菜单、弹出层、模态卡片、悬浮输入框与吸顶页头。sierra.ai+ 没有暗色模式,Frost 的暗色是自拟的暖调近黑配色。+- Console:黑色(或白色)画布、1 px 线条、处处零圆角、单一橙色强调色;只有 h1 用窄体大写,其下的 Plex Sans+ 标题用常规大小写;分组标签大写,进行中信号为步进动画,等宽字体只用于代码与数据,层次靠线条表达:模态卡片+ 以较深的 `line-emphasis` 线条描边,不投阴影。+- 两套主题共用一套字号阶梯:标题逐级放大 1.25 倍,最小不低于 .75rem;状态过渡时长为 120–200 ms;控件+ (0.25、0.375 与 0.625rem)、列表行(0.375rem)与菜单行(0.5rem)的纵向内边距与 Primer 相同,切换主题+ 不改变这些高度。两套主题+ 都包含 `done` 与 `info` 色调,每个色调在自身底色上作为文字对比度达 4.5:1,在所有表面上作为标记对比度达+ 3:1。diff --git a/changelog/unreleased/2026-09-16-theme-gallery.md b/changelog/unreleased/2026-09-16-theme-gallery.mdnew file mode 100644index 00000000..aca00e73--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-gallery.md@@ -0,0 +1,60 @@+# A local component gallery renders the shared UI package in every theme++- **Date:** 2026-09-16+- **Type:** process+- **Scope:** `ui-gallery`, `ui`, `tooling`, `ci`+- **PR:** [#764](https://github.com/Prism-Shadow/penguin-harness/pull/764)++[中文版](2026-09-16-theme-gallery.zh.md)++A new private package, `@prismshadow/penguin-ui-gallery`, is a Vite + React app that shows the shared UI+package in each of the three themes (Primer, Frost, Console), light and dark, at the 16 / 18 / 20 px root+sizes and in English and Chinese. It is a local dev tool started with `pnpm dev:gallery` on port 7372 and+never ships with the product. Nothing in the Web App changed.++## The gallery++- One long page of fifteen modules — Foundations, Conversation, Composer, Sidebar & navigation, Buttons &+ actions, Status & feedback, Forms, Overlays, Tables & lists, Stats & charts, Markdown & code, Files &+ trees, Pages & sections, Company board, Screens. Each module is one realistic composition built from the+ shared fixtures (a docs-expert Session, English and Chinese) with three to five variants; its header+ carries the title and a sentence, and its card carries the variant pills and a quotable breadcrumb such+ as `Frost › Conversation › Approval · dark · zh`.+- A sticky rail switches theme, mode, root size and language, toggles compare and reduced motion, and+ lists the modules. Compare shows the three themes at once: side by side for a narrow module, stacked at+ full width for a wide one. `compare=<module>` compares a single module while the rest of the page stays+ single.+- Every view is addressable. The URL carries the theme, mode, size, language and each module's variant+ pick; `/embed?module=<id>&variant=<key>` renders one composition alone, and `/embed?demo=<part-id>`+ still renders one part.+- Each module has three drawers: its parts (the component demos that exist, and one line per planned+ component with its wave and the web code it replaces), the tokens the composition actually reads+ (resolved in the active theme and mode, with their WCAG ratios), and the module's own source.+- Foundations is a module as well: the palette, the type scale in English and Chinese, shape and depth,+ the rhythm steps, the icon registry at the theme's stroke, motion, focus and selection, and the six+ style hooks on the markup their recipes select on.+- `/screens/<name>` shows the full-page composites from `packages/ui/src/screens`, and `/fonts` lists each+ theme's families, every declared face grouped per family and weight with its slice count and load+ status, and the licence texts.+- Chrome copy is in English and Chinese, local to the gallery.++## Package additions++- `packages/ui/src/module.ts` defines the module contract (`defineModule`, `MODULE_IDS`), and+ `packages/ui/src/modules/*.module.tsx` holds the thirteen compositions the package owns — the gallery+ owns Foundations and Screens, which are made of its own machinery. `packages/ui/src/catalog.ts` files+ every component section under its module, and `packages/ui/src/demo.ts` defines the demo contract+ (`defineDemo`).+- The compositions carry no data of their own: every word and number comes from+ `packages/ui/src/fixtures/`, which gains what they need beyond the sets the screens already use —+ the citation test failing, the Task's to-do list, the slash menu, a docs answer, the plugin+ library's totals, the group chat, the dock's panel menu, the dialog form's search and choice+ groups, and the chrome copy of the pages they imitate.++## Tooling++- `pnpm --filter @prismshadow/penguin-ui-gallery shots` photographs modules × variants × themes × modes ×+ languages through `/embed`, with `--parts` for the atomic demos. It fails the run when a family the+ theme names has no loaded face, and `shots.mjs diff <before> <after>` compares two runs pixel by pixel.+- The root `pnpm dev:gallery` script starts the gallery; the manual-test skill lists it; CI runs the+ gallery's unit tests in the `rest` shard, and `pnpm -r build` builds it.diff --git a/changelog/unreleased/2026-09-16-theme-gallery.zh.md b/changelog/unreleased/2026-09-16-theme-gallery.zh.mdnew file mode 100644index 00000000..bd7bcfb3--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-gallery.zh.md@@ -0,0 +1,47 @@+# 本地组件画廊:在每套主题下渲染共享 UI 包++- **Date:** 2026-09-16+- **Type:** process+- **Scope:** `ui-gallery`, `ui`, `tooling`, `ci`+- **PR:** [#764](https://github.com/Prism-Shadow/penguin-harness/pull/764)++[English](2026-09-16-theme-gallery.md)++新增私有包 `@prismshadow/penguin-ui-gallery`:一个 Vite + React 应用,把共享 UI 包分别在三套主题(Primer、Frost、+Console)、浅色与深色、16 / 18 / 20 px 三档根字号、中英文下展示出来。它是本地开发工具,用 `pnpm dev:gallery` 在+7372 端口启动,不随产品发布。Web App 没有任何改动。++## 画廊++- 单页长滚动,共十五个模块:基础、对话、输入区、侧栏与导航、按钮与操作、状态与反馈、表单、浮层、表格与列表、+ 统计与图表、Markdown 与代码、文件与目录树、页面与分区、公司看板、整页。每个模块是一幅由共享 fixture(一次+ docs-expert 会话,中英文各一份)搭出的真实合成,带三到五个变体;标题行写模块名与一句说明,卡片内含变体胶囊与+ 可直接引用的路径,例如 `Frost › Conversation › Approval · dark · zh`。+- 左侧吸顶栏切换主题、明暗、根字号与语言,开关对比与减弱动效,并列出全部模块。对比会同时呈现三套主题:窄模块+ 三栏并排,宽模块整宽堆叠;`compare=<module>` 只对比单个模块,其余模块保持单主题。+- 每个视图都有地址。URL 记录主题、明暗、字号、语言与每个模块选中的变体;`/embed?module=<id>&variant=<key>` 单独+ 渲染一幅合成,`/embed?demo=<part-id>` 仍可单独渲染一个部件。+- 每个模块有三个抽屉:部件(已有的组件演示,以及每个计划中组件的一行说明,标注波次与它将替代的 Web 代码)、+ 该合成实际读取的令牌(按当前主题与明暗解析,并给出 WCAG 对比度)、模块自身的源码。+- 基础本身也是一个模块:调色板、中英文排版尺度、形状与层次、节奏步长、按主题描边绘制的图标册、动效、焦点与+ 选区,以及挂在配方所选结构上的六个样式钩子。+- `/screens/<name>` 展示 `packages/ui/src/screens` 中的整页合成;`/fonts` 列出各主题的字体族、按字体族与字重归并+ 的已声明字体(含切片数量与加载状态)以及许可文本。+- 画廊界面文案有中英文两份,只属于画廊本身。++## 包内新增++- `packages/ui/src/module.ts` 定义模块契约(`defineModule`、`MODULE_IDS`),`packages/ui/src/modules/*.module.tsx`+ 放置由包自己拥有的十三幅合成——基础与整页两个模块由画廊拥有,它们本就由画廊自身的机制搭成。+ `packages/ui/src/catalog.ts` 把每个组件分区归入所属模块,`packages/ui/src/demo.ts` 定义演示契约(`defineDemo`)。+- 这些合成本身不含数据:所有文字与数字都来自 `packages/ui/src/fixtures/`。在整页已用的数据集之外,fixtures 补上了它们+ 所需的部分——失败的引用测试、Task 的待办清单、斜杠菜单、一篇文档回答、插件库统计、群聊、停靠面板的添加菜单、对话框+ 表单的搜索框与选项组,以及所模仿页面的界面文案。++## 工具++- `pnpm --filter @prismshadow/penguin-ui-gallery shots` 经 `/embed` 为模块 × 变体 × 主题 × 明暗 × 语言拍摄截图,+ `--parts` 另外拍摄原子演示。若主题声明的某个字体族没有成功加载,该次运行判为失败;`shots.mjs diff <before>+ <after>` 可逐像素比较两次运行。+- 根目录的 `pnpm dev:gallery` 启动画廊;manual-test 技能收录该入口;CI 在 `rest` 分片运行画廊的单元测试,+ `pnpm -r build` 会构建画廊。diff --git a/changelog/unreleased/2026-09-16-theme-w0-guards.md b/changelog/unreleased/2026-09-16-theme-w0-guards.mdnew file mode 100644index 00000000..03ef2ff6--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-w0-guards.md@@ -0,0 +1,88 @@+# The shared UI package gains its test harness and de-slop guards, and the web style guards scan both source roots++- **Date:** 2026-09-16+- **Type:** process+- **Scope:** `ui`, `web`+- **PR:** [#762](https://github.com/Prism-Shadow/penguin-harness/pull/762)++[中文版](2026-09-16-theme-w0-guards.zh.md)++The theme system's shared UI package (`@prismshadow/penguin-ui`) gained a Node-only test suite+that judges the theme files by their computed values and holds the package and the Web App to the+theme work's de-slop rules, and the Web App's style-guard tests were made to scan `packages/ui/src`+beside `packages/web/src`, failing by name when either root yields no files instead of passing over+nothing as components move between the two.++## Package tests++- `token-contract`: every theme × mode (light, dark) defines every name in `tokens.ts` — the base+ rule, plus the dark rule in dark — inside `@layer ui-theme` on the canonical selectors, once each,+ with nothing outside the contract, and a dark rule never repeats a base value; a non-default+ theme also re-points all eleven gray steps. The contract holds 188 names, with+ `--ui-radius-control` (bridged as `rounded-control`), `--ui-stack-0` and `--ui-stack-4` and without+ `--ui-glass-highlight` or `--ui-fg-on-emphasis`, and every `--ui-*` name spelled in the package,+ the Web App or the gallery (stylesheets and string literals) must be a contract name. The Web+ App's and the gallery's entry stylesheets import `themes/github.css` before the other two themes,+ whose dark rules rely on that order.+- `contrast`: WCAG 2 ratios resolved from the theme CSS — text on every surface (4.5:1), tone inks+ on the page surfaces (3:1, `neutral` exempt), tone text on its tint and solid-badge labels+ (4.5:1), and the accent label on the theme accent and on every user preset (4.5:1). Shortfalls+ are recorded in an exception list that fails once an entry starts passing.+- `no-app-strings` and `no-theme-reads`: the package imports nothing from the web app's+ dictionaries, and nothing outside the theme machinery reads the theme id.+- `demo-coverage`: every component directory carries a `*.demo.tsx`, with an empty exemption list.+- `font-licenses`: every font dependency has its licence mirrored under `src/fonts/LICENSES/`,+ matching the installed package's text, and every font the stylesheets load comes from one. A font+ with no package, listed in `src/fonts/vendored-fonts.json`, may ship only as woff2 slices in its+ own directory, with a licence text in `LICENSES/` that names its title; TTF and OTF files are+ refused everywhere.+- `boot-script`: `BOOT_SCRIPT` paints what `applyThemeAttributes` would for every combination of+ stored preferences, and `packages/web/index.html` carries it verbatim.+- A theme file that is still a stub, a package with no fonts or components yet, and an index.html+ with no inline script are reported as named skipped cases rather than passes.++## De-slop guards++- `src/testing/deslop.ts` reads Tailwind classes out of the TypeScript AST (string literals and+ template text, never comments) and out of `@apply` lists, with each JSX element's classes, direct+ children and enclosing component, and checks 22 rules: transitions name colour, opacity or shadow+ properties (transforms only in the chevron and the sheet, launcher and drawer files); no hover or+ press transforms; `duration-150` / `duration-200` or the duration tokens; nested radii; borders on+ clipping rounded boxes; halos and pulses on status marks; icons on a tint of their own ink; coloured+ left-border callouts; a tone's tint beside the same tone's line; mood words in badges; one spinner+ file and no `border-t-transparent`; gaps, stacks and padding on the rhythm steps; no literal text+ sizes; `uppercase` and wide tracking only through the eyebrow and display hooks, and no eyebrow+ directly above a heading; tabular figures in stat chips, counts and key-value values; no mono in+ button, nav, heading or menu labels; no bordered surface inside another; no gradient or backdrop+ blur without a job; shadows from the shadow tokens; colours from tokens; no emoji in dictionaries+ or fixtures; no eyebrow on a page header.+- `packages/ui/test/deslop.test.ts` runs every check over `packages/ui/src` with an empty allowlist,+ and checks the theme files' heading tokens: no h2–h5 is uppercased and no heading is set in mono.+- `packages/web/test/deslop.test.ts` runs the same checks over `packages/web/src` against an+ allowlist of the 374 hits the app held in 96 files, counted exactly per file and rule, each entry+ naming the wave that removes it; palette classes are not checked in the Web App.+- `packages/ui/test/hooks.test.ts` holds the package, the Web App and the gallery to the six style+ hooks of `src/hooks.ts`, allows each hook only inside the components that host it, and checks the+ markup the recipes select on: `data-live` on `.ui-live`, `.ui-display` on an h1, and `head`,+ `body`, `foot` or `pane` slots in `.ui-frame`.++## Test helpers++- `src/testing/` gained a source-root scanner with per-root file counts, a CSS rule reader, a+ theme-file analyzer that resolves `var()` through the theme cascade, colour parsing (hex, `rgb()`,+ `hsl()`, `oklch()`, `color-mix(in srgb, …)`) with WCAG contrast, static-render helpers and the+ de-slop rule engine.+- `packages/ui` gained a `vitest.config.ts`; its `test` script no longer passes on an empty suite.++## Web guards++- `packages/web/test/helpers/roots.ts` names the two source roots and provides+ `expectEveryRootScanned`, `sourceFile` and `expectSingleHome`.+- The 21 style guards — `control-size`, `icon-scale`, `tone`, `disclosure-anchor`,+ `disclosure-body`, `company-click-targets`, `required-mark`, `info-popover`, `help-fold`,+ `title-reveal`, `session-activity`, `session-row-menu`, `company-beta`, `todo-notice`,+ `modal-focus`, `esc-layers`, `portal-panel-dismiss`, `context-menu`, `inner-html-stability`,+ `group-list`, `autofill` — scan both roots, assert each yielded files, and assert every module+ they read lives in exactly one place; files are named by repo-relative path.+- `GlyphIcon` draws its stroke from `--ui-icon-stroke` with a 1.7 fallback, and `icon-scale`+ asserts that and checks each theme's token against the line-family weights 1.7 / 1.6 / 1.4.diff --git a/changelog/unreleased/2026-09-16-theme-w0-guards.zh.md b/changelog/unreleased/2026-09-16-theme-w0-guards.zh.mdnew file mode 100644index 00000000..46c2f7a8--- /dev/null+++ b/changelog/unreleased/2026-09-16-theme-w0-guards.zh.md@@ -0,0 +1,74 @@+# 共享 UI 包有了测试框架与去 AI 味守卫,Web 样式守卫同时扫描两个源码根++- **Date:** 2026-09-16+- **Type:** process+- **Scope:** `ui`, `web`+- **PR:** [#762](https://github.com/Prism-Shadow/penguin-harness/pull/762)++[English](2026-09-16-theme-w0-guards.md)++主题系统的共享 UI 包(`@prismshadow/penguin-ui`)新增了一套只在 Node 中运行的测试,按主题文件的计算值来+检验主题,并让包与 Web App 都遵守主题工作的去 AI 味规则;Web App 的样式守卫测试改为在 `packages/web/src`+之外同时扫描 `packages/ui/src`,任一源码根扫不到文件时按名字报错,而不是在组件于两处之间迁移时对着空集静默+通过。++## 包内测试++- `token-contract`:每个主题 × 明暗模式都在 `@layer ui-theme` 的规范选择器上,把 `tokens.ts` 中的每个名字+ 各声明一次(基础规则,深色模式再加上深色规则),且不含契约之外的名字,深色规则也不得重复基础规则的取值;+ 非默认主题还须重新指定全部十一级灰阶。契约共 188 个名字:含+ `--ui-radius-control`(桥接为 `rounded-control`)、`--ui-stack-0` 与 `--ui-stack-4`,不含+ `--ui-glass-highlight` 与 `--ui-fg-on-emphasis`;包、Web App 与画廊中写出的每个 `--ui-*` 名字(样式表与+ 字符串字面量中)都必须是契约中的名字。Web App 与画廊的入口样式表须先导入 `themes/github.css`,再导入另两套+ 主题,后两者的深色规则依赖这一顺序。+- `contrast`:从主题 CSS 解析出 WCAG 2 对比度——各表面上的正文(4.5:1)、页面表面上的色调墨色(3:1,+ `neutral` 除外)、色调底色上的色调文字与实心徽标文字(4.5:1)、主题强调色与每个用户预设上的强调色文字+ (4.5:1)。未达标项记入例外清单,某项一旦达标,测试即失败直到将其移除。+- `no-app-strings` 与 `no-theme-reads`:包内不从 Web App 的词典导入任何内容,主题机制之外也不读取主题 id。+- `demo-coverage`:每个组件目录都带有 `*.demo.tsx`,豁免清单初始为空。+- `font-licenses`:每个字体依赖的许可文本都镜像在 `src/fonts/LICENSES/` 下且与已安装包中的文本一致,+ 样式表加载的每个字体文件都来自这样的依赖。没有 npm 包、列于 `src/fonts/vendored-fonts.json` 的字体,+ 只能以 woff2 切片的形式放在自己的目录中,其许可文本放在 `LICENSES/` 下并写明许可名称;TTF 与 OTF 文件+ 在任何位置都不允许。+- `boot-script`:对存储偏好的每种组合,`BOOT_SCRIPT` 绘制出的结果都与 `applyThemeAttributes` 一致,+ 且 `packages/web/index.html` 原样内联了它。+- 仍是桩文件的主题、尚无字体或组件的包、尚无内联脚本的 index.html,都以具名的跳过用例报告,而不算通过。++## 去 AI 味守卫++- `src/testing/deslop.ts` 从 TypeScript AST(字符串字面量与模板文本,从不读注释)和 `@apply` 列表中读出+ Tailwind 类名,连同每个 JSX 元素的类名、直接子元素与所在组件,检查 22 条规则:过渡只列出颜色、不透明度+ 或阴影属性(变换只允许出现在 chevron 以及 sheet、launcher、drawer 文件中);不做悬停或按下时的变换;+ 时长用 `duration-150` / `duration-200` 或时长令牌;嵌套圆角;裁剪圆角盒子上的边框;状态标记上的光晕与+ 脉动;在自身墨色的浅底上放图标;彩色左边框提示框;同一色调的底色与边线并用;徽标里的情绪词;只有一个+ 转圈文件,且不用 `border-t-transparent`;间距、堆叠与内边距落在节奏阶梯上;不写字面字号;`uppercase`+ 与加宽字距只通过 eyebrow 与 display 钩子出现,且 eyebrow 不紧贴在标题之上;统计标签、计数与键值中的+ 数字使用等宽数字;按钮、导航、标题与菜单的标签不用等宽字体;带边框的表面不嵌套;不用没有用途的渐变或+ 背景模糊;阴影取自阴影令牌;颜色取自令牌;词典与测试数据中没有 emoji;页面标题不带 eyebrow。+- `packages/ui/test/deslop.test.ts` 在 `packages/ui/src` 上运行全部检查,允许清单为空;并检查各主题文件的+ 标题令牌:h2–h5 均不大写,也没有哪级标题使用等宽字体。+- `packages/web/test/deslop.test.ts` 在 `packages/web/src` 上运行同样的检查,对照一份允许清单:列出应用+ 现有的 374 处命中,分布在 96 个文件中,按文件与规则精确计数,每条都写明由哪一波次移除;Web App 中不检查+ 调色板类名。+- `packages/ui/test/hooks.test.ts` 要求包、Web App 与画廊只使用 `src/hooks.ts` 中的六个样式钩子,每个钩子+ 只能出现在承载它的组件中,并检查钩子样式所依赖的标记:`.ui-live` 带 `data-live`,`.ui-display` 位于+ h1 上,`.ui-frame` 的插槽为 `head`、`body`、`foot` 或 `pane`。++## 测试辅助++- `src/testing/` 新增:带每个根文件计数的源码根扫描器、CSS 规则读取器、沿主题层叠解析 `var()` 的主题文件+ 分析器、颜色解析(十六进制、`rgb()`、`hsl()`、`oklch()`、`color-mix(in srgb, …)`)与 WCAG 对比度计算、+ 静态渲染辅助函数,以及去 AI 味规则引擎。+- `packages/ui` 新增 `vitest.config.ts`;其 `test` 脚本不再在空测试集上通过。++## Web 守卫++- `packages/web/test/helpers/roots.ts` 列出两个源码根,并提供 `expectEveryRootScanned`、`sourceFile`+ 与 `expectSingleHome`。+- 21 个样式守卫——`control-size`、`icon-scale`、`tone`、`disclosure-anchor`、`disclosure-body`、+ `company-click-targets`、`required-mark`、`info-popover`、`help-fold`、`title-reveal`、+ `session-activity`、`session-row-menu`、`company-beta`、`todo-notice`、`modal-focus`、`esc-layers`、+ `portal-panel-dismiss`、`context-menu`、`inner-html-stability`、`group-list`、`autofill`——都扫描两个根,+ 断言每个根都扫到了文件,并断言所读的每个模块只存在于一处;文件以仓库相对路径命名。+- `GlyphIcon` 的描边改为读取 `--ui-icon-stroke`(回退值 1.7),`icon-scale` 断言这一点,并检查每个主题的+ 该令牌取值属于线条族粗细 1.7 / 1.6 / 1.4。diff --git a/changelog/unreleased/2026-09-17-notice-misans.md b/changelog/unreleased/2026-09-17-notice-misans.mdnew file mode 100644index 00000000..330464fc--- /dev/null+++ b/changelog/unreleased/2026-09-17-notice-misans.md@@ -0,0 +1,10 @@+# The third-party notices cover the bundled fonts++- **Date:** 2026-09-17+- **Type:** process+- **Scope:** `tooling`+- **PR:** [#770](https://github.com/Prism-Shadow/penguin-harness/pull/770)++[中文版](2026-09-17-notice-misans.zh.md)++`THIRD-PARTY-NOTICES.md` gained an entry for MiSans by Xiaomi, whose Regular and Medium weights the Frost theme ships as `unicode-range` WOFF2 slices. The entry says what subsetting the fonts into slices changes and what it keeps, quotes the copyright notice the font files carry, names `fonts-licenses/misans.txt` as the license text every build ships beside them, and reproduces the full MiSans Font Intellectual Property License Agreement in Chinese and English. The file also gained an entry for each of the six SIL Open Font License 1.1 faces in the web assets (Mona Sans, JetBrains Mono, IBM Plex Sans, IBM Plex Sans Condensed, Commit Mono and Noto Sans SC), and its introduction now says that the fonts also ship through npm, in the `@prismshadow/penguin-server` package's `web-dist/`.diff --git a/changelog/unreleased/2026-09-17-notice-misans.zh.md b/changelog/unreleased/2026-09-17-notice-misans.zh.mdnew file mode 100644index 00000000..a112a6c0--- /dev/null+++ b/changelog/unreleased/2026-09-17-notice-misans.zh.md@@ -0,0 +1,10 @@+# 第三方声明涵盖随应用分发的字体++- **Date:** 2026-09-17+- **Type:** process+- **Scope:** `tooling`+- **PR:** [#770](https://github.com/Prism-Shadow/penguin-harness/pull/770)++[English](2026-09-17-notice-misans.md)++`THIRD-PARTY-NOTICES.md` 新增小米 MiSans 字体一节:Frost 主题使用它的 Regular 与 Medium 两个字重,以 `unicode-range` WOFF2 切片的形式随应用分发。该节写明子集化切片改动了什么、保留了什么,逐字引用字体文件自带的版权声明,指明每个构建产物都在字体旁附带许可文本 `fonts-licenses/misans.txt`,并收录《MiSans 字体知识产权许可协议》中英文全文。该文件还为 Web 资源中的六款 SIL Open Font License 1.1 字体(Mona Sans、JetBrains Mono、IBM Plex Sans、IBM Plex Sans Condensed、Commit Mono 与 Noto Sans SC)各新增一节,其引言也改为说明这些字体同样经由 npm 分发,位于 `@prismshadow/penguin-server` 包的 `web-dist/` 中。diff --git a/changelog/unreleased/2026-09-19-theme-identities-live-gallery.md b/changelog/unreleased/2026-09-19-theme-identities-live-gallery.mdnew file mode 100644index 00000000..0d2edcad--- /dev/null+++ b/changelog/unreleased/2026-09-19-theme-identities-live-gallery.md@@ -0,0 +1,108 @@+# The three themes look like three themes, and the gallery plays interactions on demand++- **Date:** 2026-09-19+- **Type:** process+- **Scope:** `ui`, `ui-gallery`+- **PR:** [#795](https://github.com/Prism-Shadow/penguin-harness/pull/795)++[中文版](2026-09-19-theme-identities-live-gallery.zh.md)++Frost and Console were redesigned so that the three themes no longer share one silhouette, and the+component gallery gained live variants that play an interaction frame by frame in every theme. Primer is+unchanged pixel for pixel, and so is the Web App, which renders only Primer until the theme switcher+opens.++## Themes++- Sizes are no longer shared across themes. A new space-unit token is bridged to Tailwind's `--spacing`,+ so every spacing and size utility scales with the theme: Primer keeps the stock 0.25rem, Frost is+ roomier (0.28rem, a 15px body) and Console denser (0.225rem, a 13px body). `text-sm` and `text-xs`+ follow each theme's body and small rungs.+- Frost takes Sierra's colour field back: a warm field behind the app window, the navigation column+ on the field and the main column as a floating rounded sheet, generous box radii, pill controls and+ regular-weight large titles.+- Console becomes a monospaced interface in the manner of opencode.ai: navigation, buttons, labels,+ headings, badges and tables are set in Commit Mono, while reading surfaces (message text, answer+ Markdown, the composer's input) stay in IBM Plex Sans. Paper-white and warm near-black modes, the+ orange accent, square corners, a ruled full-bleed window with a `>` before the selected navigation+ row, and boxes whose head title sits in the top rule.+- A seventh style hook, `ui-shell`, carries the app window (`data-slot="nav"` / `"main"`); its only+ host is `AppShell`. A new `--ui-font-ui` token is the face of the chrome (`body` reads it), beside+ `--ui-font-sans` for reading.+- The token contract grew from 188 to 210 names: the shell group, `--ui-font-ui`, the space unit, and+ eleven motion tokens for entering, leaving, revealing and resizing.++## Motion++- Components declare motion with four data attributes — `data-presence` with `data-side`,+ `data-backdrop`, `data-reveal` and `data-layout-motion` — and `theme.css` animates them from the+ theme's tokens: Primer fades with a 4px slide, Frost springs in from 0.96 with a blur that clears and+ streams text in word by word, Console steps with no fade. Reduced motion shows every end state at+ once.++## Gallery++- Six modules gained a live variant: Streaming reply (conversation), Type and send (composer),+ Collapse and expand (navigation), Open and close (overlays: menu, dialog, toast), Run to finish+ (status) and Expand a folder (files). Each is a list of frames the card plays on a clock and loops.+- A card autoplays while it is on screen. Its foot carries a transport: play and pause, restart,+ previous and next frame, frame chips that jump, and 0.5× / 1× / 2×. In compare mode the three+ themes share the card's clock, so they show the same frame at the same moment.+- `/embed?module=&variant=&frame=&play=` addresses a frame. By default a live variant is paused on its+ last frame. Screenshots of a live variant are named `<module>--<variant>@<frame>.png`, one per frame+ with `--variants all`. A paused card's breadcrumb names its frame.+- The Foundations Motion board replays each motion specimen, and the Density and Shape boards show the+ space unit and the shell.++## Themes, round 2++- Three structure hooks make the themes differ in how a surface is organised, not only in colour:+ `ui-icon-decor` (an icon its label already says — Primer keeps it monochrome, Frost colours it by+ role, Console drops it, so Console shows far fewer icons), `ui-tree` (rows that nest — Primer's+ bordered box, a soft guide inside Frost's card, and in Console no box at all, just `└`/`├`+ connectors drawn in CSS) and `ui-field` (a labelled control row — Primer as today, Frost with the+ label above a full-width control, Console as a tabular row with a fixed label column). Ten hooks now.+- Each theme lists its own accent presets: Primer keeps `blue / green / violet / rose / amber` with+ today's values, Frost adds five warm muted hues and Console five terminal ones. A stored preset the+ active theme does not list paints nothing — the theme's own accent stands in — and comes back when+ the reader returns to a theme that lists it, so no stored preference is lost.+- The contract is 215 names: a structure group carries the tree ladder, its guide colour and the+ field's label column and gap.+- The themes have Chinese names: 通用 (Primer), 白领 (Frost), 极客 (Console). The ids are unchanged.++## The gallery, redesigned++- **Nothing plays until you ask.** A scene now belongs to the variant it ends in, and a card rests on+ its settled frame. Play runs it once and stops; the `live-*` variants are gone, folded into the+ static ones. Every module's default variant carries a scene.+- The page opens with a **hero** — the product line, a pitch, two buttons and a full app window in the+ current theme, which answers clicks (sessions, dock tabs, the composer) and plays its own scene. It+ lives in the UI package, so the landing page can import it.+- Four new modules: Hero, Dialogs & confirmation, Create with AI, and Empty states & onboarding —+ nineteen in all. The dialog sections moved out of Overlays.+- The rail carries the controls the app has: theme (by its Chinese name in Chinese), mode, **accent**+ (the active theme's own presets, painted in their colours), **root size** (16 / 18 / 20 px, the real+ root font size), language, viewport, compare and reduced motion. `accent=` and `view=` join the URL.+- **Phone width works twice over**: `view=phone` renders any module in a 390px frame, and the gallery+ itself folds its rail into a top-bar drawer, goes single column and never scrolls sideways.++## The gallery, at the app's size++- **App regions render at the app's width.** A module that imitates part of the app window declares+ the width it is designed at (`viewport` in `module.ts`): 1280px for a whole window (Sidebar & navigation,+ Hero), 956px for what fills its main column (Conversation, Composer, Pages, Company board, Dialogs,+ Empty states, Create with AI, Overlays, Files). The card lays the composition out at that width and+ scales the picture down to fit, so it wraps and truncates as the app does. `/embed` and the+ screenshots show it at that width unscaled; the phone view keeps its 390px frame.+- **The stand-ins follow the app.** The sidebar leads with the collapse button and the Project+ switcher, and carries the app's nav labels (新建对话, 插件市场), no counts, the Sessions header with+ its three controls, Workspace groups, the running hourglass, and the user row with the role. The+ chat header, the composer's control row (`+`, approval mode, Skills with its count, the slash hint,+ the context gauge, thinking level, model, send), the stats line and the dock's labels match the app,+ and the chat without a right dock shows the 快捷方式 launcher ball. The Pages module is the real+ Plugins page and the Agents page with its create pair; page titles, the Files panel and company copy+ use the app's words.+- A guard test pins every label the gallery shares with the app to the app's own dictionaries+ (`packages/web/src/lib/strings.ts` and `strings-en.ts`), in both languages.+- `/screens/<name>` puts its toolbar in a strip above the composite instead of floating it over the+ composer.diff --git a/changelog/unreleased/2026-09-19-theme-identities-live-gallery.zh.md b/changelog/unreleased/2026-09-19-theme-identities-live-gallery.zh.mdnew file mode 100644index 00000000..4ed393e4--- /dev/null+++ b/changelog/unreleased/2026-09-19-theme-identities-live-gallery.zh.md@@ -0,0 +1,77 @@+# 三套主题拉开差异,画廊按需演示交互++- **Date:** 2026-09-19+- **Type:** process+- **Scope:** `ui`, `ui-gallery`+- **PR:** [#795](https://github.com/Prism-Shadow/penguin-harness/pull/795)++[English](2026-09-19-theme-identities-live-gallery.md)++重新设计了 Frost 与 Console,三套主题不再共用同一副轮廓;组件画廊新增动态变体,在每套主题下逐帧演示交互。Primer+逐像素不变;Web App 在主题切换开放前只渲染 Primer,因此同样不变。++## 主题++- 尺寸不再跨主题共享。新增的间距单位令牌桥接为 Tailwind 的 `--spacing`,所有间距与尺寸工具类随主题缩放:Primer+ 保持原生的 0.25rem,Frost 更宽松(0.28rem,正文 15px),Console 更紧凑(0.225rem,正文 13px)。`text-sm` 与+ `text-xs` 跟随各主题的正文与小字字阶。+- Frost 恢复 Sierra 式的色场:应用窗口后铺暖色底场,导航列落在底场上,主列是悬浮的圆角薄片;盒子圆角更大,控件为+ 胶囊形,标题用常规字重的大字号。+- Console 改为 opencode.ai 式的等宽界面:导航、按钮、标签、标题、徽章与表格用 Commit Mono,阅读面(消息正文、回答+ 的 Markdown、输入框)仍用 IBM Plex Sans。浅色为纸白、深色为暖近黑,保留橙色强调色与直角;窗口通栏并以细线分隔,+ 选中的导航行前有 `>`,带头部的框把标题嵌在顶线里。+- 新增第七个样式钩子 `ui-shell`,挂在应用窗口上(`data-slot="nav"` / `"main"`),唯一宿主是 `AppShell`。新增令牌+ `--ui-font-ui` 作为界面字体(`body` 读它),与阅读用的 `--ui-font-sans` 分列。+- 令牌契约由 188 个增至 210 个:外壳一组、`--ui-font-ui`、间距单位,以及用于进出、显现与尺寸变化的 11 个动效令牌。++## 动效++- 组件用四个数据属性声明动效——`data-presence` 配 `data-side`、`data-backdrop`、`data-reveal` 与+ `data-layout-motion`——由 `theme.css` 按主题的令牌演绎:Primer 淡入加 4px 位移,Frost 从 0.96 弹入、模糊渐清并+ 逐词显现流式文本,Console 逐格跳变、不淡入。减少动效下一律直接呈现终态。++## 画廊++- 六个模块各新增一个动态变体:流式回复(对话)、输入并发送(输入区)、收起与展开(侧栏与导航)、打开与关闭(浮层:+ 菜单、对话框、通知)、运行到结束(状态)与展开目录(文件)。每个变体是一组帧,卡片按时钟逐帧播放并循环。+- 卡片在视口内时自动播放。卡片底部有走带控件:播放与暂停、重播、上一帧与下一帧、点击跳转的帧标签,以及 0.5× /+ 1× / 2× 变速。比较模式下三套主题共用该卡片的时钟,同一时刻停在同一帧。+- `/embed?module=&variant=&frame=&play=` 可定位到某一帧,动态变体缺省暂停在最后一帧。动态变体的截图命名为+ `<模块>--<变体>@<帧>.png`,加 `--variants all` 时逐帧出图。卡片暂停时,路径标注当前帧。+- 「基础」的动效板可逐项重放,间距与形状板展示间距单位与外壳。++## 主题,第二轮++- 三个结构钩子让三套主题在**组织方式**上分开,而不只是颜色:`ui-icon-decor`(标签已经说明了的图标——通用保持单色,白领+ 按角色着色,极客直接不画,因此极客的图标明显更少)、`ui-tree`(会嵌套的行——通用是描边盒,白领在卡片内画柔和参考线,+ 极客不要盒子,用 CSS 画 `└`/`├` 连线)、`ui-field`(带标签的控件行——通用维持现状,白领标签在上、控件撑满,极客是固定+ 标签列的表格行)。钩子增至十个。+- 每套主题各列一组强调色预设:通用保留 `blue / green / violet / rose / amber` 与现有取值,白领另给五个暖而含蓄的色相,+ 极客给五个终端色相。当前主题未列出的存储值不着色(由主题自带的强调色顶上),切回列出它的主题即恢复,偏好本身不丢。+- 令牌增至 215 个:新增「结构」一组,承载树的缩进阶梯、连线色与字段的标签列宽和间距。+- 三套主题有了中文名:通用(Primer)、白领(Frost)、极客(Console);id 不变。++## 画廊重做++- **不点就不动。** 场景现在挂在它所结束的那个变体上,卡片停在完成态;点播放才走一遍并停住。`live-*` 变体取消,并回静态+ 变体,每个模块的缺省变体都带场景。+- 页首是**首屏**——产品名、一句话、两个按钮,以及一整扇当前主题下的应用窗口:可点会话、可切停靠面板、可在输入区打字,也+ 可播放自己的场景。它放在共享 UI 包里,落地页可以直接引用。+- 新增四个模块:首屏、弹窗与确认、用 AI 创建、空状态与引导,共十九个;弹窗相关的部件从「浮层」移了过来。+- 侧栏给齐了应用里有的控件:主题(中文界面用中文名)、明暗、**强调色**(当前主题自带的预设,按各自颜色作色标)、**根字号**+ (16 / 18 / 20 px,改的就是真实根字号)、语言、视口、比较与减少动效。URL 新增 `accent=` 与 `view=`。+- **窄屏两头都顾**:`view=phone` 把任意模块放进 390px 的框里看,画廊自身也把侧栏收进顶栏抽屉、卡片单列、横向不滚动。++## 画廊按应用尺寸呈现++- **应用区域按应用的宽度排版。** 模仿应用窗口某一部分的模块在 `module.ts` 里声明其设计宽度(`viewport`):整扇窗口+ (侧栏与导航、首屏)为 1280px,主列里的内容(对话、输入区、页面、公司看板、弹窗、空状态、用 AI 创建、浮层、文件)为+ 956px。卡片按这个宽度排版,再把画面等比缩到卡片宽,换行与截断都与应用一致。`/embed` 与截图按该宽度原尺寸输出;窄屏+ 视图仍用 390px 的框。+- **替身向应用看齐。** 侧栏首行是收起按钮与 Project 切换器,导航文案与应用一致(新建对话、插件市场)且不带计数;Session+ 标题带三个控件,会话按工作区分组,运行中显示沙漏,底部用户行带角色。对话头部、输入区控件行(`+`、审批模式、带数量的+ 技能、斜杠提示、上下文占用、思考等级、模型、发送)、统计行与停靠面板的文案均与应用一致;未开右侧面板的对话显示「快捷+ 方式」悬浮球。「页面」模块改为真实的插件页与带创建按钮组的智能体页;页面标题、文件面板与公司模式的文案改用应用的原词。+- 新增一个守护测试:画廊与应用共有的每条文案,都在中英两种语言下与应用自己的词典(`packages/web/src/lib/strings.ts`+ 与 `strings-en.ts`)逐字比对。+- `/screens/<name>` 的工具栏改为合成图上方的一条横栏,不再浮在输入区上面。diff --git a/changelog/unreleased/2026-09-27-gallery-docs-site.md b/changelog/unreleased/2026-09-27-gallery-docs-site.mdnew file mode 100644index 00000000..7d44b016--- /dev/null+++ b/changelog/unreleased/2026-09-27-gallery-docs-site.md@@ -0,0 +1,38 @@+# The gallery becomes a docs-style site you can click through++- **Date:** 2026-09-27+- **Type:** process+- **Scope:** `ui-gallery`, `ui`+- **PR:** [#859](https://github.com/Prism-Shadow/penguin-harness/pull/859)++[中文版](2026-09-27-gallery-docs-site.zh.md)++The component gallery was one long page of heavy cards, variant pills and drawers. It is now a home+page and one page per module, laid out like the product's documentation site, and the demos that are+about interaction can actually be used.++## The site++- The home page opens on a clickable app shell: a real-proportion window whose sidebar switches between+ Chat, Agents, Plugins, Models, Cost, Evaluation and Settings, built from the modules' own compositions.+ Sessions open, the sidebar folds to its rail, the composer takes a prompt and streams the scripted reply,+ and the dock's tabs switch. Below it, the modules are indexed by group.+- Each module has its own page at `/c/<module>`: a grouped navigation with search on the left, the module's+ title and one-line description, a section per variant, and Parts, Tokens and Source at the end, with an+ "On this page" list on the right. Compare across the three themes is per section.+- The top bar carries the theme (通用 / 白领 / 极客), accent, root size, language, viewport, compare and+ reduced-motion controls. At phone width the navigation moves into a drawer.++## Three kinds of demo++- **Animation** — a running process worth watching (a streaming reply, a run finishing, numbers counting+ up). It rests on its finished state and plays once when asked, as before.+- **Interactive** — the reader drives it: menus and dialogs open and close, the sidebar folds, the+ composer takes typing and sends, folders expand, the models table sorts and filters, forms validate.+ These no longer pretend with a timed scene; a Reset puts them back.+- **Still** — a single frame.++## Primer's group labels++The app's group labels (the Sessions label, time groups) are small uppercase tracked text; Primer's+eyebrow now reproduces them, so the gallery's sidebars read like the app's.diff --git a/changelog/unreleased/2026-09-27-gallery-docs-site.zh.md b/changelog/unreleased/2026-09-27-gallery-docs-site.zh.mdnew file mode 100644index 00000000..baabded8--- /dev/null+++ b/changelog/unreleased/2026-09-27-gallery-docs-site.zh.md@@ -0,0 +1,26 @@+# 画廊改成可以点着逛的文档式站点++- **Date:** 2026-09-27+- **Type:** process+- **Scope:** `ui-gallery`, `ui`+- **PR:** [#859](https://github.com/Prism-Shadow/penguin-harness/pull/859)++[English](2026-09-27-gallery-docs-site.md)++组件画廊原本是一整页厚重的卡片、变体胶囊和抽屉。现在它是一个首页加每个模块一页,版式照产品的文档站来做,讲交互的演示也真的能上手操作。++## 站点++- 首页开头是一扇可以点的应用外壳:按真实比例的窗口,侧栏能在对话、智能体、插件、模型、成本、评估和设置之间切换,内容取自各模块现成的合成。会话能打开,侧栏能收成图标栏,输入框能写提示词并流式得到脚本化回答,停靠面板的标签能切换。下面按组列出全部模块。+- 每个模块在 `/c/<模块>` 有自己的一页:左侧是带搜索的分组导航,中间是模块标题和一句说明、每个变体一节,末尾是部件、令牌与源码,右侧是本页目录。三主题对比按节进行。+- 顶栏放主题(通用 / 白领 / 极客)、强调色、根字号、语言、视口、对比与减少动效控件;窄屏下导航收进抽屉。++## 三类演示++- **动画**:值得观看的运行过程(流式回复、运行到结束、数字累加)。平时停在完成态,点了才播一遍,与之前相同。+- **交互**:由读者亲手操作——菜单与弹窗能开能关,侧栏能收起,输入框能打字发送,目录能展开,模型表能排序筛选,表单会校验。这些不再用计时动画假装,「重置」可以恢复原样。+- **静态**:只有一帧。++## 通用主题的分组标签++真实应用的分组标签(会话标签、时间分组)是小号大写并加字距的文字;通用主题的眉题现在照样复刻,画廊里的侧栏读起来和应用一致。diff --git a/changelog/unreleased/2026-09-29-backward-compatibility.md b/changelog/unreleased/2026-09-29-backward-compatibility.mdindex 6127eeed..cf822e62 100644--- a/changelog/unreleased/2026-09-29-backward-compatibility.md+++ b/changelog/unreleased/2026-09-29-backward-compatibility.md@@ -1,27 +1,31 @@-# Backward compatibility: `user_prompt` commands of hook packages from before 2026.09.29.1+# Backward compatibility- **Date:** 2026-09-29- **Type:** process-- **Scope:** `core`, `plugins`-- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891)+- **Scope:** `core`, `plugins`, `web`, `ui`+- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891), [#892](https://github.com/Prism-Shadow/penguin-harness/pull/892)[中文版](2026-09-29-backward-compatibility.zh.md)+Two changes of this date left something on disk or in the browser that needs a compatibility rule: the `user_prompt` commands of hook packages installed before 2026.09.29.1, and the font size a browser stored before the text sizes changed.++## `user_prompt` commands of hook packages from before 2026.09.29.1+[Hook packages follow the model context, and `user_prompt` hooks run on every prompt](2026-09-29-hooks-per-context-and-every-prompt.md) changed what a `user_prompt` command that names no `trigger` means: it had run only when a host started it by name, and it runs on every prompt the user submits after the change. The `goal` package already installed on agents names no trigger on its `start.mjs`, and that script starts a goal with no budget whenever it runs without one, so read the new way it would have turned every ordinary message into an unbudgeted goal.-## What is tolerated+### What is tolerated`userPromptTrigger(manifestVersion, command)` in `packages/core/src/plugins/index.ts` reads a manifest whose `version` is a plugin version older than `USER_PROMPT_EVERY_PROMPT_SINCE` (`2026.09.29.1`), in either spelling (`YYYY.MM.DD.N` or the older `YYYY-MM-DD.N`), the old way: its `user_prompt` commands that name no `trigger` are read as `trigger: "host"`. Those commands stay out of the every-prompt consult, and the goal start still finds its command through `Session.runUserPromptHook`. A `trigger` that a command names always wins, and a manifest with no version, or with one that is not a plugin version, is read the new way. Core writes one stderr line per process per package directory when it reads a package this way (`remindToUpdate` in `packages/core/src/agent.ts`).-## Scope+### ScopeEvery installed hook package whose manifest carries such a version and has a `user_prompt` command without a `trigger`. In practice that is the `goal` package installed from the plugin library at `2026.09.01.1` or earlier, which `default_agent` gets preinstalled. `continual-learning` has no `user_prompt` command and is unaffected. A package written by hand is affected only when it copied a version number from before `2026.09.29.1`.-## What users need to do+### What users need to doUpdate the `goal` plugin from the plugin library; the library's update notice offers it, because the plugin moved to `2026.09.29.1`. Nothing breaks until then: the old package keeps starting goals as before and never runs on an ordinary prompt. Whoever edits an older package by hand, a person or an agent, gives each `user_prompt` command an explicit `trigger`, or raises the `version` when the commands should run on every prompt.-## When it can be removed+### When it can be removedAt the 0.3.0 release preparation, by whoever prepares that release. Precondition: the 0.3.0 release notes require updating the `goal` plugin, so an install still on the old package is told to update before the reading goes away. The removal takes out:@@ -29,3 +33,17 @@ At the 0.3.0 release preparation, by whoever prepares that release. Precondition- `remindToUpdate` in `packages/core/src/agent.ts`;- the legacy case in `packages/core/test/hook-packages.test.ts`;- the note on the legacy reading in the Skills & Plugins docs page (`skills.en.md` and `skills.zh.md`), the matching sentence in the agent-initialization skill's `reference/hooks.md`, and the compatibility paragraph in the design spec's Hook section.++## Text-size setting++The [theme switching change](2026-09-29-theme-switching.md) replaced the three-step font size, stored per browser under `penguin.fontScale`, with five text sizes stored under `penguin.textSize`.++### Existing settings++- A stored choice carries over by pixels: `sm` (16px) became M, `md` (18px) became L and `lg` (20px) became XL, so everyone who picked a size sees the same size as before.+- A browser that never picked a size gets the new default, M (16px); it used to get 18px.+- The old value is read once, before the first paint, written under the new key and removed. Nobody needs to do anything by hand.++### Removal schedule++The read of `penguin.fontScale` — in the pre-paint boot script and in `readTextSize` (`@prismshadow/penguin-ui/boot`) — can be removed in the next minor version, by the release that prepares it. A browser that has not opened the app by then starts at the default size.diff --git a/changelog/unreleased/2026-09-29-backward-compatibility.zh.md b/changelog/unreleased/2026-09-29-backward-compatibility.zh.mdindex b8f4c6ec..4c0851c4 100644--- a/changelog/unreleased/2026-09-29-backward-compatibility.zh.md+++ b/changelog/unreleased/2026-09-29-backward-compatibility.zh.md@@ -1,27 +1,31 @@-# 向后兼容:2026.09.29.1 之前的钩子包中的 `user_prompt` 命令+# 向后兼容- **Date:** 2026-09-29- **Type:** process-- **Scope:** `core`, `plugins`-- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891)+- **Scope:** `core`, `plugins`, `web`, `ui`+- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891), [#892](https://github.com/Prism-Shadow/penguin-harness/pull/892)[English](2026-09-29-backward-compatibility.md)+这一天有两处改动在磁盘或浏览器里留下了需要兼容处理的旧形态:2026.09.29.1 之前安装的钩子包中的 `user_prompt` 命令,以及字号改版之前浏览器保存的字号。++## 2026.09.29.1 之前的钩子包中的 `user_prompt` 命令+[钩子包随模型上下文读取,`user_prompt` 钩子在每条 Prompt 上运行](2026-09-29-hooks-per-context-and-every-prompt.zh.md)改变了未写 `trigger` 的 `user_prompt` 命令的含义:此前它只在宿主按名启动时运行,改动之后则在用户每次提交 Prompt 时运行。各 Agent 上已安装的 `goal` 包,其 `start.mjs` 没有写 trigger,而这个脚本在缺少预算时会启动一个不设预算的目标;若按新的读法,每条普通消息都会变成一次不设预算的目标。-## 兼容的旧形态+### 兼容的旧形态`packages/core/src/plugins/index.ts` 中的 `userPromptTrigger(manifestVersion, command)` 对 `version` 为早于 `USER_PROMPT_EVERY_PROMPT_SINCE`(`2026.09.29.1`)的插件版本(`YYYY.MM.DD.N` 或旧写法 `YYYY-MM-DD.N` 均可)的清单沿用旧读法:其中没有写 `trigger` 的 `user_prompt` 命令一律按 `trigger: "host"` 读取。这些命令不参与每条 Prompt 的咨询,goal 的启动仍能经 `Session.runUserPromptHook` 找到它的命令。命令显式写出的 `trigger` 始终优先;没有版本、或版本不是插件版本格式的清单按新读法读取。core 以这种方式读取某个包时,每个进程对每个包目录向 stderr 写一行提示(`packages/core/src/agent.ts` 中的 `remindToUpdate`)。-## 生效范围+### 生效范围清单带有这类版本、且含未写 `trigger` 的 `user_prompt` 命令的每个已安装钩子包。实际上就是从插件库安装的 `2026.09.01.1` 及更早版本的 `goal` 包,`default_agent` 预装的正是它。`continual-learning` 没有 `user_prompt` 命令,不受影响。手写的钩子包只有照抄了 `2026.09.29.1` 之前的版本号时才受影响。-## 用户需要做什么+### 用户需要做什么从插件库更新 `goal` 插件;插件已升至 `2026.09.29.1`,插件库的更新提示会给出这项更新。在此之前不会出现任何问题:旧包照常启动目标,也不会在普通 Prompt 上运行。无论是人还是 Agent,手工修改旧包时,给每条 `user_prompt` 命令写上明确的 `trigger`;要让这些命令在每条 Prompt 上运行,则提高 `version`。-## 何时可以移除+### 何时可以移除在 0.3.0 发布准备时,由负责该次发布的人移除。前提:0.3.0 的发布说明要求更新 `goal` 插件,让仍在使用旧包的安装在这一读法移除之前得到更新提示。移除的内容:@@ -29,3 +33,17 @@- `packages/core/src/agent.ts` 中的 `remindToUpdate`;- `packages/core/test/hook-packages.test.ts` 中针对旧清单的用例;- 技能与插件文档页(`skills.en.md` 与 `skills.zh.md`)中关于旧读法的提示、agent-initialization Skill 的 `reference/hooks.md` 中对应的一句,以及设计文档 Hook 一节中的兼容段落。++## 字号设置++[主题切换改动](2026-09-29-theme-switching.zh.md)把按浏览器保存在 `penguin.fontScale` 下的三档字号,换成保存在 `penguin.textSize` 下的五档字号。++### 既有设置++- 已保存的选择按像素延续:`sm`(16px)对应「中」,`md`(18px)对应「大」,`lg`(20px)对应「特大」,选过字号的人看到的字号与之前相同。+- 从未选过字号的浏览器使用新的默认「中」(16px),此前是 18px。+- 旧值在首帧绘制前读取一次,写入新键后删除。无需任何手动操作。++### 移除计划++对 `penguin.fontScale` 的读取——位于首帧前的启动脚本与 `readTextSize`(`@prismshadow/penguin-ui/boot`)中——可在下一个次版本中移除,由准备该版本的发布负责。届时仍未打开过应用的浏览器会从默认字号开始。diff --git a/changelog/unreleased/2026-09-29-gallery-real-app.md b/changelog/unreleased/2026-09-29-gallery-real-app.mdnew file mode 100644index 00000000..a7d20b02--- /dev/null+++ b/changelog/unreleased/2026-09-29-gallery-real-app.md@@ -0,0 +1,29 @@+# The gallery frames the real Web App++- **Date:** 2026-09-29+- **Type:** process+- **Scope:** `ui-gallery`, `ui`, `web`, `landing`+- **PR:** [#892](https://github.com/Prism-Shadow/penguin-harness/pull/892)++[中文版](2026-09-29-gallery-real-app.zh.md)++The gallery used to rebuild the app's screens from stand-in compositions, which drifted from the real interface. It now mounts the Web App itself in a frame, against an in-browser demo API, and is still a static site with no server.++## What the gallery shows++- The home page is the real app, fully clickable. Each surface — conversations (idle, running, thinking, waiting for approval), a new conversation, agents and their settings, schedules, the plugin marketplace, models, machines, cost, evaluation, settings (including Appearance) and sign-in — has its own page.+- The demo data covers a signed-in admin, a Project with agents and Sessions, running tool calls and thinking, models from the built-in catalog, plugins, usage, benchmarks and schedules, in English and Chinese. Sending a message streams a scripted reply; actions that need a real server answer with a read-only notice. The terminal is not available.+- The top bar keeps to one row: theme, language and mode sit in it, and accent, text size, the labelled Latin and CJK font pickers and the viewport sit in a popover. They drive the framed app through the same preferences the app reads, and the popover names the Latin, CJK and monospaced faces actually rendering and the text size in pixels.+- Its pickers and hints follow the app's own select and tooltip, and its dark mode shares one neutral palette with the landing site.++## Sections++- The site has four sections — Home, Surfaces, Foundations and Fonts — each with its own navigation. Surfaces opens straight onto the conversation page.+- Foundations is a component library: one page per topic (buttons, inputs, pickers, toasts, notices, dialogs, tooltips, tabs, badges, empty states, loading, charts, avatars, files, and the colour, type, shape, density, focus, motion, icon and hook boards), each rendering the Web App's own components in a themed frame.+- Fonts lists each theme's default Latin, CJK and monospaced faces, the current pairing and the licences.++## Details++- A Foundations frame grows to hold whatever is open in it — a select panel, a menu, a tooltip, a toast or a dialog — and shrinks back when it closes, so nothing is clipped.+- The stand-in modules, screens, hero and fixtures in `packages/ui` are removed, along with the gallery's `/embed` and `/screens` routes; the Foundations boards and the fonts page stay.+- The Web App gained two small seams for this: `App` takes an optional initial route, and the Settings dialog can be opened on a given page by request.diff --git a/changelog/unreleased/2026-09-29-gallery-real-app.zh.md b/changelog/unreleased/2026-09-29-gallery-real-app.zh.mdnew file mode 100644index 00000000..2e978ddd--- /dev/null+++ b/changelog/unreleased/2026-09-29-gallery-real-app.zh.md@@ -0,0 +1,29 @@+# 画廊改为框住真实的 Web App++- **Date:** 2026-09-29+- **Type:** process+- **Scope:** `ui-gallery`, `ui`, `web`, `landing`+- **PR:** [#892](https://github.com/Prism-Shadow/penguin-harness/pull/892)++[English](2026-09-29-gallery-real-app.md)++画廊过去用替身合成重搭应用界面,与真实界面越走越远。现在它直接在框中挂载 Web App 本身,接一个浏览器内的演示 API,仍是无需服务端的静态站点。++## 画廊展示什么++- 首页就是可完整点击的真实应用。每个界面——对话(空闲、运行中、思考中、等待审批)、新对话、智能体及其设置、定时任务、插件市场、模型库、机器、成本中心、评估中心、设置(含外观)与登录——各有一页。+- 演示数据包括已登录的管理员、带智能体与 Session 的 Project、运行中的工具调用与思考、取自内置目录的模型、插件、用量、评估与定时任务,中英文各一套。发送消息会流式返回预设回复;需要真实服务端的操作会给出只读提示。终端不可用。+- 顶栏收为一行:主题、语言与明暗留在栏上,强调色、字号、带标签的英文与中文字体选择以及视口收进弹出面板。它们通过应用自身读取的同一组偏好驱动框内应用;面板同时标明实际渲染的英文、中文与等宽字体,以及以像素计的字号。+- 画廊的下拉选择与悬停提示沿用应用自己的样式,深色模式与落地页共用同一套中性配色。++## 栏目++- 站点分为首页、界面、基础、字体四个栏目,各有自己的导航;「界面」直接打开对话页。+- 「基础」是组件库:每个主题一页(按钮、输入与表单、选择器、提示弹窗、提示条、对话框、悬停提示、标签页、徽标与状态、空状态、加载、图表、头像、文件,以及颜色、字体排印、形状、密度、焦点、动效、图标与样式钩子),每页在带主题的框内渲染 Web App 自己的组件。+- 「字体」列出每个主题默认的英文、中文与等宽字体、当前的字体组合与许可。++## 细节++- 「基础」页的框会随打开的内容变高——下拉面板、菜单、悬停提示、提示弹窗或对话框——关闭后恢复,不再有内容被遮住。+- `packages/ui` 中的替身模块、界面、首屏与模拟数据已删除,画廊的 `/embed` 与 `/screens` 路由一并移除;基础令牌展板与字体页保留。+- Web App 为此加了两个小接口:`App` 可接收初始路由,设置对话框可按请求直接打开到指定页。diff --git a/changelog/unreleased/2026-09-29-theme-switching.md b/changelog/unreleased/2026-09-29-theme-switching.mdnew file mode 100644index 00000000..aeb5589c--- /dev/null+++ b/changelog/unreleased/2026-09-29-theme-switching.md@@ -0,0 +1,51 @@+# Settings → Appearance switches between the three themes++- **Date:** 2026-09-29+- **Type:** feature+- **Scope:** `web`, `ui`+- **PR:** [#892](https://github.com/Prism-Shadow/penguin-harness/pull/892)++[中文版](2026-09-29-theme-switching.zh.md)++The Web App's Appearance settings gained a theme picker — Primer (通用), Frost (白领) and Console (极客) — together with five text sizes, a font pairing and the active theme's own accent palette. Every choice applies on the spot and is remembered per browser. The default text size became 16px, the step that used to be the smallest.++## Appearance settings++- **Theme** picks Primer, Frost or Console; **Mode** keeps light, dark and follow-system.+- **Accent** lists the active theme's own presets after "Theme's own". A preset another theme lists is kept: it shows as the theme's own accent until a theme that lists it is active again. "Theme's own" is painted in the colour it resolves to; Console's own accent is black and white (near-black in light, near-white in dark), with its former orange-red kept as a preset.+- **Font size** has five steps — XS 14px, S 15px, M 16px (the new default), L 18px (the old default) and XL 20px. A size chosen in an earlier release carries over by pixels; see [backward compatibility](2026-09-29-backward-compatibility.md).+- **Fonts** picks the Latin face and the CJK face separately, each defaulting to the theme's own; the monospaced face always stays the theme's.+- A new **Credits** page, last in the Personal group and open to every account (the desktop window included), lists each bundled font — its family, the themes that use it, its license, and the full license text on request. The MiSans credit moved there from the account menu, as MiSans's entry in the list.++## The themes reach the real app++- The app window, the sidebar's navigation rows and group headers, the settings rail, menu rows, the work group and its thinking and tool rows, the composer card, menus, popovers, tooltips and dialogs, settings rows, page titles and tab bars carry the theme hooks, so Frost and Console restyle them as they do in the gallery — Frost's shimmer on running work and Console's transcript-style steps included. Notices (toasts and notice strips) and the usage, context and score charts carry hooks too, so each theme draws them its own way. Primer looks as before apart from the new default size.+- The switch knob and filled accent buttons take their colours from the theme, so a knob stays visible on a light accent track and a label stays readable on every accent fill.++## Tooltips, pickers and counts++- Every hover hint in the Web App shows in the app's own tooltip — the one the sidebar's rail used — instead of the browser's: it opens after a short pause, on keyboard focus as well as on hover, and follows the theme. A hint shows only where its words are not already on screen: on an icon-only control or a chart mark, or when the element's text is cut off, and then it shows the text whole. Elements whose hint was their only name keep that name for screen readers.+- A copy button turns its icon into a check for a moment after copying; its label and its tooltip never change to "Copied".+- Pickers and menus share one look: the panel, row spacing, hover and selected states and the check mark of the settings selects, in the composer's model, thinking, permission and skill pickers, the agent, machine, protocol and organization pickers, and every menu.+- The pending-approval count beside a Session title is a plain number in the attention colour, with no rounded badge behind it.++## Charts follow the theme++- Every chart draws through one shared set of chart parts — bars, lines, the fill under a line, points, grid and axis labels, and the Trace timeline's bars: the cost center's requests, Token and cost charts, the context donut, the Evaluation Center's score chart and sparkline, the agents' activity sparkline and the Trace timeline. The theme decides how each part looks: its palette, bar width, corners, outline and fill, line width and curve, point shape and the fill under a line. The context donut's track stays a solid ring in every theme, even where a theme dashes the grid.+- Frost draws soft, low-glare pastels — pale, borderless, rounded bars, smooth curves and a faint grid; Console draws thin, solid bars with a 1px outline, stepped 1px lines, square points and a dashed grid. Primer keeps its look with two small changes: in light mode the amber, sky, emerald, teal and orange series are one step deeper so every series reads at 3:1 on white, and the Trace timeline uses the same palette as the other charts — in dark mode its bars are one step deeper, and the approval-wait bar is a slightly deeper rose in both modes. In Primer light the settings switch's knob gains a gray hairline while off, so it stays visible on its pale track.++## Frost and Console, refined++- Frost follows a calm, cool off-white: the sidebar and the main area are told apart by fill alone (no inset card, radius or shadow), groups are soft fills instead of lines — the Settings rows sit in one soft band — dialogs are opaque with 20px corners, status pills have no border, and icons are muted monochrome.+- Console is pared down to a terminal's plainness: cards, rows and menus are the page plus a hairline, tints and shadows are gone, and notices and toasts read as status lines (`[ OK ]`, `[WARN]`, `[FAIL]`, `[INFO]`, `[NOTE]`).+- The settings switch's knob now scales with the theme's spacing, so it no longer runs past Console's track; the two font pickers in Appearance stay on one line.++## Calmer dark mode++- Dark mode keeps near-white for headings and emphasis and sets body text a step below it, at least 11:1 against every page surface; secondary text stays at least 6:1 and meta text (timestamps, placeholders) at least 4.5:1. Primer's dark canvas is lifted off pure black, and the gray scale behind `dark:` classes moves with it.+- In Console, messages, the composer's input and Session titles read in the sans reading face; navigation, labels, step rows and code stay monospaced. Console's work group loses its box, and Frost's work group lines its steps up with the header.+- Frost's dialogs are opaque (only menus, popovers and tooltips stay frosted), and the page behind a dialog, sheet, drawer, the command palette or a zoomed image is blurred as well as dimmed. At phone width the app fills the screen with no inset around it.++## Details++- The de-slop guard's new hits from recent work were fixed in place (literal text sizes moved onto rungs, off-rhythm gaps and paddings, an unnamed transform transition, pulsing marks now carrying the `ui-live` hook, one oversized shadow); the spinners, the notice-strip map, one uppercase heading and one inset accent bar were allowlisted for their planned waves.diff --git a/changelog/unreleased/2026-09-29-theme-switching.zh.md b/changelog/unreleased/2026-09-29-theme-switching.zh.mdnew file mode 100644index 00000000..1543c828--- /dev/null+++ b/changelog/unreleased/2026-09-29-theme-switching.zh.md@@ -0,0 +1,51 @@+# 设置 → 外观可以在三个主题之间切换++- **Date:** 2026-09-29+- **Type:** feature+- **Scope:** `web`, `ui`+- **PR:** [#892](https://github.com/Prism-Shadow/penguin-harness/pull/892)++[English](2026-09-29-theme-switching.md)++Web App 的外观设置新增主题选择——通用(Primer)、白领(Frost)、极客(Console),同时提供五档字号、字体组合,以及当前主题自己的一组强调色。每项选择即时生效,按浏览器记住。默认字号改为 16px,即原来最小的一档。++## 外观设置++- **主题**:在通用、白领、极客之间选择;**明暗**保留浅色、深色与跟随系统。+- **强调色**:「随主题」之后列出当前主题自己的可选色。其他主题的可选色会被保留:在当前主题下按主题自身的强调色显示,切回列出它的主题后恢复。「随主题」色块按它实际对应的颜色绘制;极客自身的强调色改为黑白(浅色下近黑、深色下近白),原先的橙红保留为一个可选色。+- **字号**:五档——特小 14px、小 15px、中 16px(新的默认)、大 18px(原来的默认)、特大 20px。旧版本里选过的字号按像素延续,见[向后兼容](2026-09-29-backward-compatibility.zh.md)。+- **字体**:英文与中文字体分别选择,默认都随主题;等宽字体始终由主题决定。+- 新增 **版权信息** 页面,位于「个人」分组末尾,所有账号(包括桌面应用窗口)都能打开:逐一列出内置字体的名称、使用它的主题、许可名称,并可展开查看许可全文。MiSans 的字体声明从账号菜单移到了这里,成为列表中 MiSans 的一项。++## 主题落到真实应用++- 应用窗口、侧边栏的导航行与分组标题、设置对话框的导航栏、菜单行、工作分组及其中的思考与工具调用行、输入卡片、菜单、弹出层、提示与对话框、设置行、页面标题和标签栏都挂上了主题钩子,白领与极客会像在画廊里一样重新组织它们——包括白领运行中文字上的流光和极客的转录式步骤。通知(浮动提示与提示条)以及用量、上下文和评分图表也挂上了钩子,各主题按自己的方式绘制。除新的默认字号外,通用主题的外观不变。+- 开关的圆点与实心强调色按钮的文字改由主题提供颜色:浅色强调色的轨道上圆点依然可见,任何强调色填充上的文字都清晰可读。++## 提示、下拉选择与计数++- Web App 里所有悬停提示都改用应用自己的提示框(即侧边栏图标栏原来用的那种),不再用浏览器自带的提示:短暂停留即出现,键盘聚焦时同样显示,并随主题变化。提示只在文字本身看不到时出现:图标按钮、图表标记,或文字被截断时(此时完整显示原文)。原本只靠提示命名的元素,屏幕阅读器仍能读出名称。+- 复制按钮复制后只把图标短暂换成对勾,按钮文字和提示都不会变成「已复制」。+- 下拉选择与菜单统一为一种样式:设置里下拉框的面板、行距、悬停与选中状态和勾选标记,同样用于输入框的模型、思考等级、权限与技能选择,智能体、机器、协议与组织选择,以及所有菜单。+- Session 标题旁的待审批计数改为注意色的纯数字,不再带圆角底色。++## 图表随主题变化++- 所有图表都改由一套共用的图表部件绘制——柱子、折线、折线下的填充、数据点、网格与坐标标签,以及轨迹时间线的色条:成本中心的请求、Token 与成本图,上下文环形图,评估中心的评分图与小折线,智能体的活跃度小折线,以及轨迹时间线。各部件的样式由主题决定:配色、柱宽、圆角、描边与填充、线宽与曲线形态、数据点形状以及折线下的填充。上下文环形图的底环在所有主题下都是实线,即使主题把网格画成虚线。+- 白领用柔和不刺眼的淡色,柱子为不加边框的浅色圆角柱,曲线平滑,网格很淡;极客用细而实心的柱子加 1px 边框、阶梯状的 1px 线条、方形数据点和虚线网格。通用主题基本保持原样,只有两处小变化:浅色下琥珀、天蓝、翠绿、青与橙五种系列色各深一档,让每种颜色在白底上都达到 3:1;轨迹时间线改用与其他图表相同的配色,深色模式下各色条深一档,审批等待色条在两种模式下都略深一些。通用浅色下设置开关关闭时,圆点多一圈灰色细边,在浅色轨道上依然清晰。++## 白领与极客的细化++- 白领改用平静、偏冷的米白:侧栏与主区只靠底色区分(没有内缩卡片、圆角或阴影),分组靠柔和底色而非线条——设置项收在一整块柔和的底色里——对话框不透明、圆角 20px,状态小标签不带边框,图标为柔和的单色。+- 极客精简到终端般朴素:卡片、行与菜单就是页面本身加一条细线,去掉了底色与阴影;提示条与提示弹窗改为状态行(`[ OK ]`、`[WARN]`、`[FAIL]`、`[INFO]`、`[NOTE]`)。+- 设置里开关的圆点随主题的间距缩放,不再超出极客的轨道;外观页的两个字体选择始终保持在一行。++## 更平静的深色模式++- 深色模式把近白留给标题与强调,正文低一级,在各页面表面上的对比度不低于 11:1;次要文字不低于 6:1,时间戳、占位符等辅助文字不低于 4.5:1。通用主题的深色画布抬离纯黑,`dark:` 类名背后的灰阶随之调整。+- 极客主题中,消息、输入框里的文字与 Session 标题改用无衬线阅读字体;导航、标签、步骤行与代码仍为等宽。极客的工作分组不再加框,白领的工作分组步骤与标题对齐。+- 白领的对话框改为不透明(只有菜单、弹出层与提示保留磨砂),打开对话框、底部面板、抽屉、命令面板或放大图片时,背后的页面既变暗也模糊。手机宽度下应用铺满屏幕、四周不留空白。++## 细节++- 去俗套检查在近期代码中新发现的问题已就地修正(字面字号改用字号阶梯、不在节奏步长上的间距与内边距、未指名的 transform 过渡、改挂 `ui-live` 钩子的脉动标记、一处过大的阴影);各处加载转圈、提示条配色表、一处大写标题和一处内嵌强调色竖条按计划中的批次列入允许清单。diff --git a/package.json b/package.jsonindex ef4dd075..f10bd6fb 100644--- a/package.json+++ b/package.json@@ -24,6 +24,7 @@"dev:web": "node scripts/dev-prebuild.mjs && pnpm --filter @prismshadow/penguin-web dev","dev:docs": "node scripts/dev-prebuild.mjs --install-only && pnpm --filter @prismshadow/penguin-docs dev","dev:landing": "node scripts/dev-prebuild.mjs --install-only && pnpm --filter @prismshadow/penguin-landing dev",+ "dev:gallery": "node scripts/dev-prebuild.mjs --install-only && pnpm --filter @prismshadow/penguin-ui-gallery dev","build:site": "node scripts/build-site.mjs","desktop": "pnpm -r build && node scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data -- pnpm --dir packages/desktop start"},diff --git a/packages/core/src/internal/ports.ts b/packages/core/src/internal/ports.tsindex ae099b13..1602be3b 100644--- a/packages/core/src/internal/ports.ts+++ b/packages/core/src/internal/ports.ts@@ -20,6 +20,7 @@* | 7368 | `pnpm dev:server` (dev backend) | `~/.penguin/dev-data` | `packages/server/package.json` `dev` |* | 7369 | `pnpm penguin web` (dev CLI) | `~/.penguin/dev-data-cli` | the root and cli `penguin` scripts |* | 7371 | a machine's dev-profile server | `~/.penguin-dev/data` there | `DEFAULT_DEV_SERVER_PORT` below |+ * | 7372 | `pnpm dev:gallery` (Vite) | none (static) | `packages/ui-gallery/vite.config.ts` |** The desktop app binds no fixed port in either form (PORT=0 with a per-instance sticky* preference); its release profile shares `~/.penguin/data` with the CLI by design and itsdiff --git a/packages/landing/index.html b/packages/landing/index.htmlindex 98114e32..c93ff079 100644--- a/packages/landing/index.html+++ b/packages/landing/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /><meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />- <meta name="theme-color" content="#030712" media="(prefers-color-scheme: dark)" />+ <meta name="theme-color" content="#141414" media="(prefers-color-scheme: dark)" /><metaname="description"content="A zero-code CLI and Web UI for building AI agents, connected to 1,000+ models. Open source, local-first, and recursively self-improving."diff --git a/packages/landing/public/og-cover.png b/packages/landing/public/og-cover.pngindex 41c3701b..373c1bf9 100644Binary files a/packages/landing/public/og-cover.png and b/packages/landing/public/og-cover.png differdiff --git a/packages/landing/scripts/og-cover.html b/packages/landing/scripts/og-cover.htmlindex 6552d1ef..7bd2551f 100644--- a/packages/landing/scripts/og-cover.html+++ b/packages/landing/scripts/og-cover.html@@ -5,8 +5,8 @@edit this file, re-run the script, commit the PNG.Sized 1200x630 — the ratio X, Facebook, LinkedIn, Discord and WeChat all crop- from. Colors are the landing page's dark theme: gray-950 behind the brand-500 and- sky-500 glows the NeonBackground drifts across the real site.+ from. Colors are the landing page's dark theme — its neutral gray-950 behind the+ brand-500 and sky-500 glows the NeonBackground drifts across the real site.--><html lang="en"><head>@@ -32,8 +32,8 @@width: 1200px;height: 630px;overflow: hidden;- background: #030712;- color: #f9fafb;+ background: #141414;+ color: #f7f7f7;}/* Same two glows as .neon-blob-a / .neon-blob-b, without the drift animation. */.glow {@@ -87,15 +87,15 @@display: flex;align-items: center;justify-content: space-between;- border-top: 1px solid rgba(148, 163, 184, 0.22);+ border-top: 1px solid rgba(171, 171, 171, 0.22);padding-top: 28px;font-size: 25px;- color: #cbd5e1;+ color: #d4d4d4;}.facts span + span::before {content: "·";margin: 0 14px;- color: #64748b;+ color: #8f8f8f;}.domain {font-weight: 600;diff --git a/packages/landing/src/styles.css b/packages/landing/src/styles.cssindex 15a64504..82a887a3 100644--- a/packages/landing/src/styles.css+++ b/packages/landing/src/styles.css@@ -30,11 +30,22 @@}.dark {color-scheme: dark;- /* Pure-black dark base, matching the Web App (true-neutral gray overrides). */- --color-gray-950: #000000;- --color-gray-900: #0d0d0d;- --color-gray-800: #1f1f1f;- --color-gray-700: #303030;+ /* A calm neutral dark, shared with the Web App's Primer dark and the theme gallery: the+ canvas lifted off black, surfaces a step lighter, and the whole gray ramp re-pointed to+ true neutrals — Tailwind's own grays lean blue, which is what made the dark landing look+ like a different site. Body text (100) sits at 16:1 on the canvas, muted (400) at 7:1+ and subtle (500) above 4.5:1 on the surfaces. */+ --color-gray-950: #141414;+ --color-gray-900: #1c1c1c;+ --color-gray-800: #2a2a2a;+ --color-gray-700: #383838;+ --color-gray-600: #575757;+ --color-gray-500: #8f8f8f;+ --color-gray-400: #ababab;+ --color-gray-300: #d4d4d4;+ --color-gray-200: #e3e3e3;+ --color-gray-100: #f0f0f0;+ --color-gray-50: #f7f7f7;}html {scroll-behavior: smooth;diff --git a/packages/landing/test/blog-post-anchors.test.ts b/packages/landing/test/blog-post-anchors.test.tsindex 117d4db4..93ecd065 100644--- a/packages/landing/test/blog-post-anchors.test.ts+++ b/packages/landing/test/blog-post-anchors.test.ts@@ -76,5 +76,7 @@ describe("blog post in-page anchors", () => {const dangling = inPageHrefs(html).filter((href) => !ids.has(targetOf(href)));expect(dangling, `dangling in-page anchors in ${file}`).toEqual([]);}- });+ // Renders every post through the full markdown pipeline: on hosted runners that alone sits at+ // the 5 s default, so the budget grows with the blog rather than flaking at its edge.+ }, 30_000);});diff --git a/packages/ui-gallery/app.html b/packages/ui-gallery/app.htmlnew file mode 100644index 00000000..1c3ce213--- /dev/null+++ b/packages/ui-gallery/app.html@@ -0,0 +1,16 @@+<!doctype html>+<html lang="zh-CN">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <link rel="icon" type="image/svg+xml" href="./penguin-logo.svg" />+ <title>PenguinHarness</title>+ <!-- The gallery's Vite config prepends two inline scripts here: the storage seed that gives+ this document its own preferences from the URL, then the app's own pre-paint boot+ script, so the framed app never flashes another theme or size. -->+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/app/main.tsx"></script>+ </body>+</html>diff --git a/packages/ui-gallery/index.html b/packages/ui-gallery/index.htmlnew file mode 100644index 00000000..533d8024--- /dev/null+++ b/packages/ui-gallery/index.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <link rel="icon" type="image/svg+xml" href="./penguin-logo.svg" />+ <title>Penguin UI gallery</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/packages/ui-gallery/lib.html b/packages/ui-gallery/lib.htmlnew file mode 100644index 00000000..344efff0--- /dev/null+++ b/packages/ui-gallery/lib.html@@ -0,0 +1,16 @@+<!doctype html>+<html lang="zh-CN">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <link rel="icon" type="image/svg+xml" href="./penguin-logo.svg" />+ <title>Penguin UI components</title>+ <!-- The gallery's Vite config prepends the same two inline scripts as app.html: the storage+ seed that gives this document its own preferences from the URL, then the app's own+ pre-paint boot script, so the components never flash another theme or size. -->+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/library/main.tsx"></script>+ </body>+</html>diff --git a/packages/ui-gallery/package.json b/packages/ui-gallery/package.jsonnew file mode 100644index 00000000..6f63d602--- /dev/null+++ b/packages/ui-gallery/package.json@@ -0,0 +1,34 @@+{+ "name": "@prismshadow/penguin-ui-gallery",+ "version": "0.2.13",+ "private": true,+ "type": "module",+ "description": "PenguinHarness UI gallery (local dev tool, Vite + React): the real Web App framed against an in-browser demo API, one page per surface in every theme, mode, text size, font pairing and language, plus the Foundations boards and the bundled fonts.",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "preview": "vite preview",+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "vitest run --passWithNoTests",+ "shots": "node scripts/shots.mjs"+ },+ "dependencies": {+ "@prismshadow/penguin-ui": "workspace:*",+ "react": "^19.1.0",+ "react-dom": "^19.1.0"+ },+ "devDependencies": {+ "@playwright/test": "^1.61.1",+ "@prismshadow/penguin-core": "workspace:*",+ "@prismshadow/penguin-web": "workspace:*",+ "@tailwindcss/vite": "^4.1.0",+ "@types/node": "^24.0.0",+ "@types/react": "^19.1.0",+ "@types/react-dom": "^19.1.0",+ "@vitejs/plugin-react": "^4.5.0",+ "tailwindcss": "^4.1.0",+ "typescript": "^5.6.0",+ "vite": "^7.0.0",+ "vitest": "^3.2.6"+ }+}diff --git a/packages/ui-gallery/public/penguin-logo.svg b/packages/ui-gallery/public/penguin-logo.svgnew file mode 100644index 00000000..0d48619e--- /dev/null+++ b/packages/ui-gallery/public/penguin-logo.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="139 129 954 954"><defs><clipPath id="rounded"><rect x="139" y="129" width="954" height="954" rx="230"/></clipPath><linearGradient id="a" x1="432" x2="978" y1="304" y2="884" gradientUnits="userSpaceOnUse"><stop stop-color="#111b2a"/><stop offset="1" stop-color="#091423"/></linearGradient><linearGradient id="b"><stop stop-color="#0e1928"/><stop offset=".4" stop-color="#0b2963"/><stop offset=".7" stop-color="#054ac8"/><stop offset=".82" stop-color="#0258f4"/><stop offset="1" stop-color="#015dfc"/></linearGradient><linearGradient xlink:href="#b" id="c" x1="964" x2="1065" y1="451" y2="423" gradientUnits="userSpaceOnUse"/><linearGradient xlink:href="#b" id="d" x1="365" x2="260" y1="800" y2="860" gradientUnits="userSpaceOnUse"/><linearGradient xlink:href="#b" id="e" x1="442" x2="350" y1="836" y2="905" gradientUnits="userSpaceOnUse"/></defs><g clip-path="url(#rounded)"><path fill="#fefefe" d="M0 0h1254v1254H0Z"/><path fill="#015dfc" d="M475 558v3c-1 0-3 1-4 1-16 4-31 9-47 14-1 0-2 1-4 1-76 26-179 67-217 143-7 15-9 29-4 45 2 5 4 10 8 14s4 4 4 6c1 1 3 1 4 2s2 1 3 2c9 6 18 10 29 14 4 1 4 1 8 3v2c-23 4-48-1-67-14-12-9-19-19-22-34-2-28 8-50 27-71 1-2 3-4 5-6s4-4 5-6l3-3h2c1-1 1-3 2-4 20-19 44-35 69-48 1-1 3-2 4-2 14-8 29-15 44-21l9-3c36-15 74-26 112-34 1 0 2 0 3-1 17-3 17-3 24-3m571 110c-7 13-22 25-33 35l-3 3c-7 6-15 12-23 18-1 1-2 2-3 2-71 54-153 93-236 122-1 0-2 1-3 1-31 11-63 20-95 27-1 0-1 0-4 1-65 14-132 17-198 8 0-1-1-1-1-2 4-1 7-2 11-2 141-16 278-54 423-118 1 0 2-1 3-1 26-12 51-24 75-38 1 0 1 0 5-3 14-8 27-16 40-24 1-1 2-1 4-2 11-8 21-16 32-24 4-3 4-3 6-3"/><path fill="url(#a)" d="M532 329c35 18 68 41 97 68l9 6 12 12c3 3 6 6 10 9 3 3 6 5 8 8 36 34 36 34 56 42l-3-3-17-17c1-5 2-8 5-13 0-1 0-1 2-4 1-2 1-4 2-5 1-2 2-3 2-5 13-26 25-51 45-72 0-1 0-1 2-3 24-26 60-37 94-39 20-1 39 1 58 6 19 6 39 8 58 2-1 6-3 10-7 14-3 2-6 4-9 5 1 1 2 1 3 2 16 11 26 24 30 44 3 18 3 18 0 24h3c50-4 50-4 71 10 2 2 2 2 3 7-5 5-10 6-16 8-31 9-53 23-72 49-1 1-2 2-3 4-24 33-41 70-57 108-17 42-39 80-68 114-1 1-1 2-2 2-10 12-22 24-34 34-2 1-4 3-6 5-12 10-24 18-37 26-1 1-3 2-4 3-73 47-165 69-251 56-21-3-38 2-58 8-1 0-1 0-4 1-2 1-3 1-4 2-2 0-3 0-4 1-6 2-8 7-11 13-4 7-8 14-13 20l-3 3c-9 11-19 23-34 26-6 0-7 0-11-4-2-3-1-6-1-10v-3c-1 1-3 2-4 3-7 4-12 6-20 5-4-2-5-3-6-7 0-8 3-13 8-18h-3c-4-1-4-1-6-3-2-4-2-5-1-9 17-29 46-44 77-53-17-3-37-6-53 2-2 2-4 5-6 7-4 6-9 11-14 16l-3 3c-12 12-27 25-45 29-5 0-6 0-10-4-2-2-2-2-2-6 1-5 2-7 4-11-10 3-10 3-13 4-5 1-8 1-13 0-4-4-4-4-5-8 1-7 6-11 11-16-2-1-3-1-5-2l-2-2c1-11 11-18 19-25 18-16 40-27 63-35 5-2 9-4 13-8l4-4c-2 0-3-1-5-1-18-4-34-10-50-21v-3h3c33-3 64-17 86-42 3-3 6-7 8-11 3-3 6-7 10-10 2-3 4-5 6-8 6-7 13-14 19-21 2-1 3-2 4-3 7-7 14-14 22-20 2-2 4-4 6-5 32-27 68-49 104-69l3 3c9 7 20 10 32 12-2-1-3-2-5-3-24-15-41-37-55-62 0-1 0-1-3-5-5-8-9-16-14-25-15-27-32-52-51-76-1-1-2-3-3-4-6-8-13-15-19-23-4-4-8-9-12-14-1-1-2-2-3-4-12-15-12-15-12-23 1-4 1-4 3-6 25-15 74 11 97 22m288 38-3 3c-16 14-26 35-27 56 0 15 1 27 8 40 1 1 1 2 2 3 10 18 25 29 44 38 2 0 3 1 5 1v2l-3 1c-43 10-81 41-108 76-2 2-4 5-6 7-4 5-8 11-12 16-5 7-11 14-17 21-2 3-5 7-8 10-47 58-107 90-180 104-30 6-56 19-81 38-2 2-4 3-6 4-2 2-3 3-5 4 3 3 9 4 13 6 7 2 14 4 21 7 27 10 54 17 83 20h4c80 7 163-20 228-65 1-1 2-2 4-3 25-17 50-37 69-61 2-2 3-5 5-7 28-32 46-71 62-109 17-40 36-78 63-112-3-2-6-3-10-4-15-4-26-12-37-23 1-2 2-3 3-5 7-10 9-21 7-33-4-19-12-32-29-43-29-16-64-13-89 8"/><path fill="url(#c)" d="M985 405h3c0 2 1 4 1 6h4c49-5 49-5 67 7 4 4 4 4 6 7-1 2-1 3-2 5-1 0-2 1-4 1-3 1-6 2-10 3l-9 3c-19 6-35 15-49 30l-3 3-5 5-6 6c-3-1-5-3-8-4 1-5 2-7 6-11l-12-3c0-1-1-3-1-4 1-1 1-2 2-3 3-5 5-9 6-14 1-2 1-3 2-5 2-6 2-6 2-8l3-3c1-3 1-5 2-8 1-5 2-8 5-13"/><path fill="url(#d)" d="M308 782c1 0 1 1 2 1v4c1 1 3 1 4 2v2c2 0 3-1 5-1l2 2c8 8 15 11 26 11 3 1 7 3 10 4h5l3 1c-2 8-8 14-14 20-2 3-3 5-5 7-13 14-31 31-51 32-5 0-5 0-9-3-2-6 0-11 3-17q-4.5 0-9 3c-5 2-10 2-15 1-3-1-3-1-6-4-1-5 0-8 3-12 2-3 4-5 7-8l-6-3c0-2-1-4-1-6 10-12 21-23 35-31h3v-2c3-1 5-2 8-3"/><path fill="url(#e)" d="M393 824c1 1 2 1 3 2h4c6 1 7 3 11 6 3 1 7 2 10 3 1 1 2 1 4 2 3 1 3 1 8 2 6 1 7 2 10 7l-1 3h-2c-1 2-1 3-2 5-9 19-25 45-45 53-6 2-10 4-16 2-4-4-4-5-4-10 0-2 1-4 1-6-1 0-2 1-3 1-1 1-2 2-3 2-1 1-3 2-4 2-5 3-9 3-15 3-3-2-5-3-6-7 0-7 3-13 8-18-1 0-3-1-4-1-4-1-4-1-6-3-1-5 0-7 2-11 1-2 2-3 3-4s1-2 2-3l8-8c0-1 0-1 3-3 23-22 23-22 34-19"/><path fill="#0e1827" d="M880 387c10 6 19 13 23 25 1 7 1 12-2 18-4 5-8 8-15 8-8 0-11-2-16-7-4-9-3-17 0-25 2-4 2-4 6-8h2c-4-6-10-8-17-10h-15c2-4 2-4 5-6 10-3 20 1 29 5m-3 16c-2 2-2 2-2 6s0 4 4 8c5-3 5-3 6-6 0-3 0-3-3-8Z"/></g></svg>diff --git a/packages/ui-gallery/scripts/fonts.conf b/packages/ui-gallery/scripts/fonts.confnew file mode 100644index 00000000..2a6d6f6a--- /dev/null+++ b/packages/ui-gallery/scripts/fonts.conf@@ -0,0 +1,24 @@+<?xml version="1.0"?>+<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">+<!--+ Font configuration for screenshot runs only: scripts/shots.mjs launches Chromium with+ FONTCONFIG_FILE pointing here. It is the system configuration plus the user font directory+ (~/.local/share/fonts, where MiSans-Light.ttf is installed by hand and never committed), with one+ rule: a sans-serif request lighter than regular resolves to MiSans, so a light fallback renders+ in a real light face instead of DejaVu or a synthetic thin CJK face.+-->+<fontconfig>+ <include ignore_missing="yes">/etc/fonts/fonts.conf</include>+ <dir prefix="xdg">fonts</dir>+ <match target="pattern">+ <test qual="any" name="family">+ <string>sans-serif</string>+ </test>+ <test name="weight" compare="less">+ <const>regular</const>+ </test>+ <edit name="family" mode="prepend" binding="strong">+ <string>MiSans</string>+ </edit>+ </match>+</fontconfig>diff --git a/packages/ui-gallery/scripts/shots.mjs b/packages/ui-gallery/scripts/shots.mjsnew file mode 100644index 00000000..28ea9605--- /dev/null+++ b/packages/ui-gallery/scripts/shots.mjs@@ -0,0 +1,118 @@+#!/usr/bin/env node+/**+ * Screenshots of the app's surfaces through the gallery's frame document: one PNG per surface ×+ * theme × mode × language, written to `<out>/<theme>/<mode>/<lang>/<surface>.png` — the app at its+ * window width (1280 × 800), or at phone width with `--view phone`.+ *+ * Needs the gallery running (`pnpm dev:gallery`, port 7372) and Playwright's Chromium. Shots are+ * never committed.+ *+ * node scripts/shots.mjs --surfaces chat,models --themes modern --modes light,dark --langs en+ * node scripts/shots.mjs --surfaces all --out /tmp/gallery-shots+ *+ * Options (comma lists):+ * --base gallery origin (default http://localhost:7372)+ * --out output directory (default packages/ui-gallery/shots)+ * --surfaces surface ids, or `all` (default all)+ * --themes github,modern,geek (default: all three)+ * --modes light,dark (default: both)+ * --langs en,zh (default: both)+ * --size xs | s | m | l | xl (default m: the 16 px root)+ * --latin a Latin pairing id (default theme)+ * --cjk a CJK pairing id (default theme)+ * --accent an accent preset id (default: the theme's own accent)+ * --view desktop | phone (default desktop)+ * --settle ms to wait after the app reports ready (default 1200: the demo API answers with+ * a beat, and a running Session's stream needs a+ * moment to show its first frame)+ *+ * Fonts must be the real ones: Chromium runs with FONTCONFIG_FILE=scripts/fonts.conf, which+ * sends a sans-serif request lighter than regular to MiSans (installed by hand under+ * ~/.local/share/fonts) rather than to a synthetic thin face.+ */+import { mkdirSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { chromium } from "@playwright/test";+// Read by Node's type stripping: the module carries no value import, by design (see its doc).+import { SURFACE_IDS, surfaceById } from "../src/app/surfaces.ts";++/** The frames the gallery uses (src/app/frame.ts, which Node cannot import: it reaches the package's boot module). */+const APP_FRAME = { width: 1280, height: 800 };+const PHONE_FRAME = { width: 390, height: 844 };++const HERE = path.dirname(fileURLToPath(import.meta.url));+const FONTCONFIG_FILE = path.join(HERE, "fonts.conf");++const args = Object.fromEntries(+ process.argv+ .slice(2)+ .map((arg, i, all) => (arg.startsWith("--") ? [arg.slice(2), all[i + 1] ?? ""] : null))+ .filter(Boolean),+);+const list = (value, fallback) =>+ value === undefined || value === "" ? fallback : value.split(",");++const base = args.base ?? "http://localhost:7372";+const out = args.out ?? path.join(HERE, "..", "shots");+const surfaces =+ args.surfaces === undefined || args.surfaces === "all"+ ? [...SURFACE_IDS]+ : list(args.surfaces, []);+const themes = list(args.themes, ["github", "modern", "geek"]);+const modes = list(args.modes, ["light", "dark"]);+const langs = list(args.langs, ["en", "zh"]);+const size = args.size ?? "m";+const latin = args.latin ?? "theme";+const cjk = args.cjk ?? "theme";+const accent = args.accent ?? "neutral";+const view = args.view === "phone" ? "phone" : "desktop";+const settle = Number(args.settle ?? 1200);+const frame = view === "phone" ? PHONE_FRAME : APP_FRAME;++const browser = await chromium.launch({ env: { ...process.env, FONTCONFIG_FILE } });+const context = await browser.newContext({+ viewport: { width: frame.width, height: frame.height },+ deviceScaleFactor: 2,+});+const page = await context.newPage();+let shots = 0;+for (const theme of themes) {+ for (const mode of modes) {+ for (const lang of langs) {+ const dir = path.join(out, theme, mode, lang);+ mkdirSync(dir, { recursive: true });+ for (const id of surfaces) {+ const surface = surfaceById(id);+ if (!surface) {+ console.error(`unknown surface: ${id}`);+ process.exitCode = 1;+ continue;+ }+ const params = new URLSearchParams({+ route: surface.route,+ theme,+ mode,+ accent,+ size,+ latin,+ cjk,+ lang,+ });+ if (surface.signedOut) params.set("auth", "out");+ if (surface.open) params.set("open", surface.open);+ await page.goto(`${base}/app.html?${params}`, { waitUntil: "load" });+ await page.waitForSelector("html[data-gallery-ready]", { timeout: 30_000 });+ // A surface that opens a dialog is not ready until the dialog is on screen.+ if (surface.open) await page.waitForSelector('[role="dialog"]', { timeout: 30_000 });+ await page.waitForTimeout(settle);+ const file = path.join(dir, `${id}.png`);+ await page.screenshot({ path: file });+ shots += 1;+ console.log(path.relative(process.cwd(), file));+ }+ }+ }+}+await browser.close();+console.log(`${shots} shots`);diff --git a/packages/ui-gallery/src/app.tsx b/packages/ui-gallery/src/app.tsxnew file mode 100644index 00000000..1095e6af--- /dev/null+++ b/packages/ui-gallery/src/app.tsx@@ -0,0 +1,32 @@+/**+ * The route switch. The routes themselves are in lib/routes.ts; every one is a full page load+ * (each is also a screenshot target), so there are no client-side transitions to manage. The+ * framed documents, `app.html` and `lib.html`, are not routes here.+ */+import { FontsPage } from "./pages/fonts";+import { HomePage } from "./pages/home";+import { LibraryPage } from "./pages/library";+import { MissingPage } from "./pages/missing";+import { SurfacePage } from "./pages/surface";+import { routePath } from "./lib/location";+import { parseRoute } from "./lib/routes";+import { GalleryProvider } from "./state";++export function App() {+ const route = parseRoute(routePath());+ return (+ <GalleryProvider canonicalizeUrl>+ {route.kind === "surface" ? (+ <SurfacePage id={route.id} />+ ) : route.kind === "topic" ? (+ <LibraryPage id={route.id} />+ ) : route.kind === "fonts" ? (+ <FontsPage page={route.page} />+ ) : route.kind === "missing" ? (+ <MissingPage id={route.id} />+ ) : (+ <HomePage />+ )}+ </GalleryProvider>+ );+}diff --git a/packages/ui-gallery/src/app/app.css b/packages/ui-gallery/src/app/app.cssnew file mode 100644index 00000000..fcaaff52--- /dev/null+++ b/packages/ui-gallery/src/app/app.css@@ -0,0 +1,7 @@+/*+ * The framed app's stylesheet: the Web App's own entry, exactly as the app loads it. The app's+ * sources sit outside this Vite root, so Tailwind is pointed at them explicitly — otherwise+ * the utilities the app's markup carries would never enter the sheet.+ */+@import "../../../web/src/styles.css";+@source "../../../web/src";diff --git a/packages/ui-gallery/src/app/fonts.ts b/packages/ui-gallery/src/app/fonts.tsnew file mode 100644index 00000000..38854eb7--- /dev/null+++ b/packages/ui-gallery/src/app/fonts.ts@@ -0,0 +1,174 @@+/**+ * What fonts a document is actually set in: for each role's stack, the first family that can+ * render — not the first family named, which is what a stack opening with "PingFang SC" on a+ * Linux box would report while Noto or the platform's sans does the work — and the root size in+ * px, read from computed styles: the framed app's when the page has one, else the page's own+ * root, which carries the same theme attributes and the same theme sheets.+ *+ * A family can render when the document bundles a face for it (a `@font-face` in+ * `document.fonts` that has not failed; a face the page has not needed yet is still the one that+ * would render), or, for a family the document does not declare, when the platform has it+ * installed. `document.fonts.check` answers neither question: it says true for any family it+ * holds no face for, installed or not, and false for a bundled face whose slices the page has not+ * needed yet. So the set's own faces and their statuses answer the first, and the platform is+ * asked the old way for the second, by measuring a sample in the family against the generic+ * fallback alone — a family that is not there measures exactly as the fallback. A stack that+ * reaches a generic keyword, or runs out, has fallen through to the platform, which the readout+ * says in words ("system").+ *+ * The resolution is pure over a probe (unit-tested); the document probe is the one place the+ * browser is asked.+ */++/** The three roles the readout names, and the token each is read from. */+export const FONT_ROLES = {+ latin: "--ui-font-sans",+ cjk: "--ui-font-cjk",+ mono: "--ui-font-mono",+} as const;+export type FontRole = keyof typeof FONT_ROLES;++export interface FontReadout {+ /** The family rendering the role, or null when the stack fell through to the platform's face. */+ latin: string | null;+ cjk: string | null;+ mono: string | null;+ /** The root font size, in CSS px. */+ px: number;+}++/** The generic families and the system aliases: a stack that reaches one of them defers to the platform. */+const GENERIC = new Set([+ "system-ui",+ "ui-sans-serif",+ "ui-serif",+ "ui-monospace",+ "ui-rounded",+ "-apple-system",+ "blinkmacsystemfont",+ "sans-serif",+ "serif",+ "monospace",+ "cursive",+ "fantasy",+ "math",+ "emoji",+]);++/** The families of a `font-family` stack, unquoted, in order; empty for an empty stack. */+export function familiesOf(stack: string): string[] {+ return stack+ .split(",")+ .map((family) =>+ family+ .trim()+ .replace(/^["']|["']$/g, "")+ .trim(),+ )+ .filter((family) => family !== "");+}++/** Whether a family name is a generic keyword or a system alias rather than a face. */+export function isGenericFamily(family: string): boolean {+ return GENERIC.has(family.toLowerCase());+}++/**+ * What a document knows about a family: a bundled face that can render ("bundled"), one whose+ * every face failed to load ("failed"), or no face declared at all ("absent").+ */+export type Declared = "bundled" | "failed" | "absent";++export interface FaceProbe {+ declared(family: string): Declared;+ /** Whether the platform has a face installed under this name. Asked only for undeclared families. */+ installed(family: string): boolean;+}++/**+ * The family a stack renders in: the first that is bundled or installed, skipping a family that+ * is neither; null once the stack reaches a generic keyword or runs out.+ */+export function faceInUse(stack: string, probe: FaceProbe): string | null {+ for (const family of familiesOf(stack)) {+ if (isGenericFamily(family)) return null;+ const declared = probe.declared(family);+ if (declared === "bundled") return family;+ if (declared === "failed") continue;+ if (probe.installed(family)) return family;+ }+ return null;+}++/**+ * The sample each role is measured with. Latin letters of unequal width tell a proportional face+ * from the monospace fallback; the CJK sample keeps Latin letters too, because CJK glyphs are an+ * em wide in every face and would measure the same in any of them.+ */+const SAMPLES: Readonly<Record<FontRole, string>> = {+ latin: "mmmmmmmmmmlliI1O0",+ cjk: "中文字体样张 mmmmlliI1O0",+ mono: "mmmmmmmmmmlliI1O0",+};++/** The document's answer, for one role's sample text. */+export function documentProbe(doc: Document, sample: string): FaceProbe {+ const faces = new Map<string, FontFace[]>();+ doc.fonts.forEach((face) => {+ const family = face.family.replace(/^["']|["']$/g, "");+ const list = faces.get(family) ?? [];+ list.push(face);+ faces.set(family, list);+ });+ let context: CanvasRenderingContext2D | null | undefined;+ const width = (font: string): number => {+ if (context === undefined) context = doc.createElement("canvas").getContext("2d");+ if (!context) return 0;+ context.font = font;+ return context.measureText(sample).width;+ };+ return {+ declared(family) {+ const list = faces.get(family);+ if (!list) return "absent";+ return list.every((face) => face.status === "error") ? "failed" : "bundled";+ },+ installed(family) {+ // Measured against two fallbacks, so a face that happens to match one's metrics still+ // shows against the other.+ return ["monospace", "serif"].some(+ (fallback) => width(`72px "${family}", ${fallback}`) !== width(`72px ${fallback}`),+ );+ },+ };+}++/** Reads the three roles and the root size off a document's computed styles. */+export function readFontReadout(doc: Document): FontReadout {+ const view = doc.defaultView;+ if (!view) return { latin: null, cjk: null, mono: null, px: 16 };+ const styles = view.getComputedStyle(doc.documentElement);+ const px = Number.parseFloat(styles.fontSize);+ const role = (name: FontRole) =>+ faceInUse(styles.getPropertyValue(FONT_ROLES[name]), documentProbe(doc, SAMPLES[name]));+ return {+ latin: role("latin"),+ cjk: role("cjk"),+ mono: role("mono"),+ px: Number.isFinite(px) ? Math.round(px * 10) / 10 : 16,+ };+}++/** `Latin Mona Sans · CJK MiSans · Mono JetBrains Mono · 16px`, with the words the caller supplies. */+export function formatFontReadout(+ readout: FontReadout,+ labels: { latin: string; cjk: string; mono: string; system: string },+): string {+ const face = (family: string | null) => family ?? labels.system;+ return [+ `${labels.latin} ${face(readout.latin)}`,+ `${labels.cjk} ${face(readout.cjk)}`,+ `${labels.mono} ${face(readout.mono)}`,+ `${readout.px}px`,+ ].join(" · ");+}diff --git a/packages/ui-gallery/src/app/frame.ts b/packages/ui-gallery/src/app/frame.tsnew file mode 100644index 00000000..5d83223a--- /dev/null+++ b/packages/ui-gallery/src/app/frame.ts@@ -0,0 +1,115 @@+/**+ * The framed app's contract with the gallery — pure, so it is unit-tested.+ *+ * A framed app is its own document (`app.html`): its own root for the theme attributes, its own+ * storage, its own router. The gallery drives it through the URL alone:+ *+ * app.html?route=/chat/s-1&theme=modern&mode=dark&accent=neutral&size=m&latin=theme&cjk=theme&lang=zh+ *+ * Inside the document, an inline script that runs before anything else replaces+ * `localStorage` (and `sessionStorage`) with an in-memory store seeded from those params under+ * the app's own storage keys — the same keys the app's pre-paint boot script and its theme,+ * locale and sidebar state read. So the app boots exactly as it does for a user who chose those+ * preferences, three frames of one page can each show a different theme without fighting over+ * the shared origin storage, and what the app writes (a preference changed in its Settings, a+ * collapsed sidebar) stays in that frame.+ */+import { THEME_STORAGE_KEYS } from "../../../ui/src/boot";++/** The frame's document, relative to the gallery's base. */+export const APP_FRAME_PATH = "/app.html";++/**+ * The window the app is framed at: a common laptop viewport, and the narrowest one where the+ * app shows its full sidebar beside a roomy chat column. The page scales it to the column.+ */+export const APP_FRAME = { width: 1280, height: 800 } as const;+/** The phone frame: an iPhone-class viewport, a plain frame with no device art. */+export const PHONE_FRAME = { width: 390, height: 844 } as const;++/**+ * The app's language preference key (`state/locale.tsx`). The theme keys are the package's;+ * this one is the app's own and has no export, so it is spelled here and pinned by a test.+ */+export const APP_LANG_KEY = "penguin.lang";++/** Frame URL param → the app storage key the seeding script writes it to. */+export const SEEDED_KEYS: Readonly<Record<string, string>> = {+ theme: THEME_STORAGE_KEYS.themeId,+ mode: THEME_STORAGE_KEYS.mode,+ accent: THEME_STORAGE_KEYS.accent,+ size: THEME_STORAGE_KEYS.textSize,+ latin: THEME_STORAGE_KEYS.fontLatin,+ cjk: THEME_STORAGE_KEYS.fontCjk,+ lang: APP_LANG_KEY,+};++/** What the gallery tells a frame, besides the app route. */+export interface FramePrefs {+ theme: string;+ mode: string;+ accent: string;+ size: string;+ latin: string;+ cjk: string;+ lang: "en" | "zh";+}++export interface FrameTarget {+ /** The app route to open on. */+ route: string;+ /** Start signed out (the login surface). */+ signedOut?: boolean;+ /** A dialog to open once the app is up. */+ open?: string;+}++/** The frame's URL: the document, then the target and the preferences as query params. */+export function appFrameSrc(base: string, prefs: FramePrefs, target: FrameTarget): string {+ const params = new URLSearchParams();+ params.set("route", target.route);+ for (const key of Object.keys(SEEDED_KEYS)) params.set(key, prefs[key as keyof FramePrefs]);+ if (target.signedOut) params.set("auth", "out");+ if (target.open) params.set("open", target.open);+ return `${base}${APP_FRAME_PATH}?${params.toString()}`;+}++export interface FrameParams extends FrameTarget {+ lang: "en" | "zh";+}++/** What a frame document reads back from its own URL. An absent route opens the chat. */+export function parseFrameParams(search: string): FrameParams {+ const params = new URLSearchParams(search);+ const route = params.get("route");+ const open = params.get("open");+ return {+ route: route && route.startsWith("/") ? route : "/chat",+ lang: params.get("lang") === "zh" ? "zh" : "en",+ ...(params.get("auth") === "out" ? { signedOut: true } : {}),+ ...(open ? { open } : {}),+ };+}++/**+ * The inline script that gives the frame document its own storage, seeded from the URL. A+ * classic, dependency-free IIFE, generated from `SEEDED_KEYS` so the keys can never drift from+ * the app's. It must run before the app's boot script, which reads the same storage.+ */+export function storageSeedScript(): string {+ return (+ "(function(){" ++ "function store(seed){var m=seed;return{" ++ "getItem:function(k){return Object.prototype.hasOwnProperty.call(m,k)?m[k]:null}," ++ "setItem:function(k,v){m[k]=String(v)}," ++ "removeItem:function(k){delete m[k]}," ++ "clear:function(){m={}}," ++ "key:function(i){var ks=Object.keys(m);return i<ks.length?ks[i]:null}," ++ "get length(){return Object.keys(m).length}}}" ++ `var S=${JSON.stringify(SEEDED_KEYS)},q=new URLSearchParams(location.search),seed={};` ++ "for(var p in S){var v=q.get(p);if(v)seed[S[p]]=v}" ++ 'Object.defineProperty(window,"localStorage",{value:store(seed),configurable:true});' ++ 'Object.defineProperty(window,"sessionStorage",{value:store({}),configurable:true});' ++ "})()"+ );+}diff --git a/packages/ui-gallery/src/app/main.tsx b/packages/ui-gallery/src/app/main.tsxnew file mode 100644index 00000000..b7ec057b--- /dev/null+++ b/packages/ui-gallery/src/app/main.tsx@@ -0,0 +1,78 @@+/**+ * The framed app's entry (`app.html`): the real Web App, mounted on an in-memory router at the+ * route the URL names, against the demo store in the language the URL names. The document's+ * storage was already replaced and seeded by the inline script in the page head, and the app's+ * own boot script has applied the theme, so by the time this runs the app boots exactly as it+ * does for a user with those preferences.+ *+ * The app's own entry reconciles browser storage against the server's data root before+ * mounting; a frame's storage is fresh every load, so there is nothing to reconcile and the+ * app mounts at once. KaTeX's stylesheet and the app's come in the same order as in the app's+ * entry, so the app's `.katex` rules still win the cascade.+ *+ * `open=settings` (or `settings.<page>`) asks the app for its Settings dialog through the+ * app's own request seam, which the account menu answers as soon as it mounts.+ */+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { App } from "../../../web/src/app";+import { requestSettings } from "../../../web/src/features/settings/settings-request";+import type { SettingsSectionKey } from "../../../web/src/lib/settings-sections";+// The app's dependency, reached through its own node_modules: the gallery does not depend on+// KaTeX, and the app's math rules expect this sheet ahead of the app's own.+import "../../../web/node_modules/katex/dist/katex.min.css";+import "./app.css";+import { parseFrameParams } from "./frame";+import { installFetchShim } from "./mock/fetch-shim";+import { getStore } from "./mock/store";++/** The dialog's pages, as `open=settings.<page>` may name them. */+const SETTINGS_PAGES = [+ "profile",+ "general",+ "appearance",+ "account",+ "proxy",+ "uploads",+ "company",+ "plugins",+ "users",+] as const satisfies readonly SettingsSectionKey[];++const isSettingsPage = (value: string): value is SettingsSectionKey =>+ (SETTINGS_PAGES as readonly string[]).includes(value);++const params = parseFrameParams(window.location.search);+getStore({ lang: params.lang, signedIn: !params.signedOut });+installFetchShim();++// Framed, a focus must not scroll the page around the frame: the chat composer focuses itself+// on mount, and the browser scrolls every ancestor document to centre a newly focused element,+// which dragged the gallery page down until the frame's top sat under the sticky bar. The frame+// is scaled to fit, so nothing in it is ever out of view; the app's own scroll-on-focus is not+// missed. Standalone (opened in its own tab) keeps the browser's behaviour.+if (window.parent !== window) {+ const focus = HTMLElement.prototype.focus;+ HTMLElement.prototype.focus = function (this: HTMLElement, options?: FocusOptions) {+ focus.call(this, { ...options, preventScroll: true });+ };+}++const container = document.getElementById("root");+if (!container) throw new Error("#root mount point not found");++createRoot(container).render(+ <StrictMode>+ <App initialPath={params.route} />+ </StrictMode>,+);++if (params.open === "settings" || params.open?.startsWith("settings.")) {+ const page = params.open.slice("settings.".length);+ requestSettings(isSettingsPage(page) ? { section: page } : {});+}++// What the screenshot script waits for: the app mounted and its fonts loaded.+void document.fonts.ready.then(() => {+ document.documentElement.dataset.galleryReady = "1";+});diff --git a/packages/ui-gallery/src/app/mock/client.ts b/packages/ui-gallery/src/app/mock/client.tsnew file mode 100644index 00000000..a58602ce--- /dev/null+++ b/packages/ui-gallery/src/app/mock/client.ts@@ -0,0 +1,76 @@+/**+ * The Web App's `api/client.ts`, swapped in by the gallery's Vite config: the same exports+ * with the same shapes, answered by the demo store's router instead of `fetch`. The app's+ * endpoint wrappers, its providers and its features import this file without knowing.+ *+ * A request takes a beat (a few ms) before it answers, so the app's loading states render+ * the way they do against a server, and so nothing that relies on "the answer comes later"+ * runs in the wrong order.+ */+import { ApiError } from "./errors";+import { router } from "./routes";+import { getStore } from "./store";+import type { Method } from "./router";++export { ApiError };++/** Session-invalidation callback (registered by AuthProvider; not triggered by auth endpoints). */+let onUnauthorized: (() => void) | null = null;++export function setUnauthorizedHandler(handler: (() => void) | null): void {+ onUnauthorized = handler;+}++function isAuthEndpoint(path: string): boolean {+ return path.startsWith("/api/auth/");+}++export interface ApiFetchOptions {+ method?: Method;+ body?: unknown;+ query?: Record<string, string | number | undefined>;+ server?: string | null;+}++export interface ApiFetchMeta {+ serverNowMs: number | null;+}++/** A beat in the browser; none under Node, where the tests walk every endpoint. */+const LATENCY_MS = typeof window === "undefined" ? 0 : 24;++const beat = () => new Promise<void>((resolve) => setTimeout(resolve, LATENCY_MS));++export async function apiFetch<T>(path: string, options: ApiFetchOptions = {}): Promise<T> {+ return (await apiFetchWithMeta<T>(path, options)).data;+}++export async function apiFetchWithMeta<T>(+ path: string,+ options: ApiFetchOptions = {},+): Promise<{ data: T } & ApiFetchMeta> {+ let url = path;+ if (options.query) {+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(options.query)) {+ if (value !== undefined) params.set(key, String(value));+ }+ const qs = params.toString();+ if (qs) url += (url.includes("?") ? "&" : "?") + qs;+ }+ await beat();+ let answer;+ try {+ answer = await router.dispatch(getStore(), options.method ?? "GET", url, options.body);+ } catch (error) {+ if (error instanceof ApiError) {+ if (error.status === 401 && !isAuthEndpoint(path)) onUnauthorized?.();+ throw error;+ }+ throw new ApiError(500, "internal", error instanceof Error ? error.message : String(error));+ }+ const serverNowMs = Date.now();+ if (answer.kind === "empty") return { data: undefined as T, serverNowMs };+ if (answer.kind === "raw") return { data: answer.body as T, serverNowMs };+ return { data: answer.body as T, serverNowMs };+}diff --git a/packages/ui-gallery/src/app/mock/errors.ts b/packages/ui-gallery/src/app/mock/errors.tsnew file mode 100644index 00000000..f6b38c2c--- /dev/null+++ b/packages/ui-gallery/src/app/mock/errors.ts@@ -0,0 +1,24 @@+/**+ * The API error the app's client throws, reproduced with the same shape so everything that+ * catches an `ApiError` in the app (toasts, the 401 sign-out, the per-code messages) works+ * unchanged against the mock. Its own module because both the router and the client need it.+ */+export class ApiError extends Error {+ readonly status: number;+ readonly code: string;+ readonly retryAfterSeconds?: number;++ constructor(status: number, code: string, message: string, retryAfterSeconds?: number) {+ super(message);+ this.name = "ApiError";+ this.status = status;+ this.code = code;+ if (retryAfterSeconds !== undefined) this.retryAfterSeconds = retryAfterSeconds;+ }+}++/** The code an unrouted request answers with — what the coverage test looks for. */+export const UNMOCKED = "gallery_unmocked";++/** The code a write the demo refuses answers with: the app shows it as an ordinary failure toast. */+export const READ_ONLY = "demo_read_only";diff --git a/packages/ui-gallery/src/app/mock/fetch-shim.ts b/packages/ui-gallery/src/app/mock/fetch-shim.tsnew file mode 100644index 00000000..e8ea97f4--- /dev/null+++ b/packages/ui-gallery/src/app/mock/fetch-shim.ts@@ -0,0 +1,73 @@+/**+ * A few of the app's features bypass its client and call `fetch` themselves — the Workspace+ * file preview (which reads the `ETag` off the response), the benchmark case browser, the+ * archive downloads, the terminal list. The frame answers those from the same router by+ * wrapping `fetch` for `/api/…` URLs; everything else (the frame's own assets) goes to the+ * network as before.+ */+import { ApiError } from "./errors";+import { isApiUrl, splitUrl } from "./router";+import type { Method } from "./router";+import { router } from "./routes";+import { getStore } from "./store";++function urlOf(input: RequestInfo | URL): string {+ if (typeof input === "string") return input;+ if (input instanceof URL) return input.href;+ return input.url;+}++function bodyOf(init: RequestInit | undefined): unknown {+ const body = init?.body;+ if (typeof body !== "string") return undefined;+ try {+ return JSON.parse(body) as unknown;+ } catch {+ return body;+ }+}++/** The response an answer becomes, in the shape the direct callers read. */+export async function answerAsResponse(+ method: Method,+ url: string,+ body: unknown,+): Promise<Response> {+ try {+ const answer = await router.dispatch(getStore(), method, url, body);+ if (answer.kind === "empty") return new Response(null, { status: answer.status });+ if (answer.kind === "raw") {+ return new Response(answer.body, { status: answer.status, headers: answer.headers });+ }+ return new Response(JSON.stringify(answer.body), {+ status: answer.status,+ headers: { "content-type": "application/json" },+ });+ } catch (error) {+ const status = error instanceof ApiError ? error.status : 500;+ const code = error instanceof ApiError ? error.code : "internal";+ const message = error instanceof Error ? error.message : String(error);+ return new Response(JSON.stringify({ error: { code, message } }), {+ status,+ headers: { "content-type": "application/json" },+ });+ }+}++export function installFetchShim(): void {+ const real = window.fetch.bind(window);+ window.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {+ const url = urlOf(input);+ if (!isApiUrl(url)) return real(input, init);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : "GET")+ ).toUpperCase() as Method;+ return answerAsResponse(method, splitUrl(url).path + urlQuery(url), bodyOf(init));+ };+}++function urlQuery(url: string): string {+ const { query } = splitUrl(url);+ const qs = query.toString();+ return qs ? `?${qs}` : "";+}diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.tsnew file mode 100644index 00000000..c43b19b5--- /dev/null+++ b/packages/ui-gallery/src/app/mock/fixtures.ts@@ -0,0 +1,1408 @@+/**+ * The demo world the mocked API answers from, built for one language at a time: a signed-in+ * admin, one Project with two Agents, their conversations, the model table, the plugin+ * library and what is installed, thirty days of usage, two Benchmarks, schedules, the+ * machines, the memory and vault of the docs Agent, a small Workspace and the server's+ * settings. Every row is typed by the server's own DTOs, so the compiler is what keeps this+ * data in step with the app that reads it.+ */+import type {+ AgentConfigResponse,+ AgentSummary,+ BenchmarkCaseSummary,+ BenchmarkSummary,+ CaseMaterial,+ ChatDefaultsDto,+ CommandPolicyDto,+ DirListResponse,+ HookItem,+ InstalledPluginsResponse,+ MachinesResponse,+ MeResponse,+ MemberInfo,+ MemoryFileResponse,+ MemoryOverviewResponse,+ ModelInfo,+ ModelsResponse,+ PluginConfigEntry,+ PluginIndexResponse,+ PluginLibraryResponse,+ ProjectScheduleItem,+ ProjectSummary,+ ProxyProbeTargetsResponse,+ ServerSettings,+ SessionContextResponse,+ SessionInfo,+ SkillMetadataItem,+ UiPrefs,+ UpdateCheckResponse,+ UsageErrorItem,+ UserInfo,+ VaultResponse,+ VersionResponse,+ WorkspaceFileEntry,+} from "@prismshadow/penguin-server/api";+// The built-in catalog, as the app reads it (the same built module the app imports): the model+// table is every preset it seeds a Project with, so the app's "sync presets" badge stays quiet.+import {+ catalogEntryFor,+ PENGUIN_GO_PROVIDER_ID,+ presetModelEntries,+ presetPromotions,+} from "../../../../core/dist/state/model-catalog.js";+import { IDS } from "./ids";+import type { Lang } from "./types";+import type { ModelRef } from "./transcripts";++// ---------------------------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------------------------++const DAY = 86_400_000;+const iso = (ms: number) => new Date(ms).toISOString();+/** `yyyy-mm-dd` in UTC, which is also what the usage series buckets on. */+export const dayKey = (ms: number) => new Date(ms).toISOString().slice(0, 10);++/** A small deterministic generator, so the numbers are stable between reloads and tests. */+export function seeded(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state * 1_664_525 + 1_013_904_223) >>> 0;+ return state / 0x1_0000_0000;+ };+}++/** The model every demo Session runs on: the catalog's default. */+export const DEFAULT_MODEL: ModelRef = {+ provider: "deepseek",+ modelId: "deepseek-flash",+ contextWindow: 1_000_000,+};++// ---------------------------------------------------------------------------------------------+// Rows+// ---------------------------------------------------------------------------------------------++export interface DemoFixtures {+ lang: Lang;+ now: number;+ user: UserInfo;+ users: UserInfo[];+ me: Omit<MeResponse, "user">;+ prefs: UiPrefs;+ serverSettings: ServerSettings;+ project: ProjectSummary;+ members: MemberInfo[];+ agents: AgentSummary[];+ agentConfigs: Record<string, AgentConfigResponse>;+ models: ModelsResponse;+ sessions: SessionInfo[];+ schedules: ProjectScheduleItem[];+ library: PluginLibraryResponse;+ pluginFiles: Record<string, Record<string, string>>;+ installed: Record<string, { skills: SkillMetadataItem[]; hooks: HookItem[] }>;+ installedPlugins: InstalledPluginsResponse;+ pluginIndex: PluginIndexResponse;+ readmes: Record<string, string>;+ benchmarks: BenchmarkSummary[];+ benchmarkCases: Record<string, BenchmarkCaseSummary[]>;+ caseFiles: Record<string, Record<CaseMaterial, Record<string, string>>>;+ machines: MachinesResponse;+ version: VersionResponse;+ update: UpdateCheckResponse;+ memory: Record<string, { overview: MemoryOverviewResponse; files: MemoryFileResponse[] }>;+ vault: Record<string, VaultResponse>;+ workspace: { entries: Record<string, WorkspaceFileEntry[]>; content: Record<string, string> };+ chatDefaults: ChatDefaultsDto;+ commandPolicy: CommandPolicyDto;+ pluginConfig: PluginConfigEntry[];+ probeTargets: ProxyProbeTargetsResponse;+ dirs: Record<string, DirListResponse>;+ context: SessionContextResponse;+ usage: UsageDay[];+ usageErrors: UsageErrorItem[];+}++/** One day of one Agent on one model, the grain the usage routes aggregate from. */+export interface UsageDay {+ date: string;+ agentId: string;+ sessionId: string;+ provider: string;+ modelId: string;+ cacheRead: number;+ cacheWrite: number;+ output: number;+ requests: number;+ completed: number;+ aborted: number;+}++export function buildFixtures(lang: Lang, now: number): DemoFixtures {+ const L = <T>(zh: T, en: T): T => (lang === "zh" ? zh : en);+ const ago = (days: number, minutes = 0) => now - days * DAY - minutes * 60_000;++ const user: UserInfo = {+ userId: IDS.users.admin,+ isAdmin: true,+ passwordIsInitial: false,+ displayName: L("演示管理员", "Demo Admin"),+ createdAt: iso(ago(120)),+ };+ const member: UserInfo = {+ userId: IDS.users.member,+ isAdmin: false,+ passwordIsInitial: true,+ createdAt: iso(ago(30)),+ };++ const project: ProjectSummary = {+ projectId: IDS.project,+ name: L("PenguinHarness 演示", "PenguinHarness demo"),+ role: "owner",+ ownerUserId: user.userId,+ createdAt: iso(ago(120)),+ };++ const activity = (seed: number, peak: number): number[] => {+ const rnd = seeded(seed);+ return Array.from({ length: 30 }, (_, i) => Math.round(rnd() * peak * (0.4 + i / 30)));+ };++ const agents: AgentSummary[] = [+ {+ agentId: IDS.agents.docs,+ name: L("文档专家", "Docs Expert"),+ description: L(+ "回答关于 Claude Code 文档的问题,每条结论都引用语料库里的真实文件。",+ "Answers questions about the Claude Code docs, citing a real corpus file for every claim.",+ ),+ createdAt: iso(ago(90)),+ updatedAt: iso(ago(1, 30)),+ activeSessionCount: 3,+ sessionCount: 11,+ sessionActivity: activity(7, 6),+ toolCount: 6,+ version: 14,+ kernelOutdated: false,+ vaultKeyCount: 2,+ scheduleCount: 2,+ skillCount: 3,+ hookCount: 1,+ pluginUpdates: [{ name: IDS.plugins.registry, version: "2026.09.20.1" }],+ memoryCount: 4,+ },+ {+ agentId: IDS.agents.notes,+ name: L("发布说明助手", "Release Notes"),+ description: L(+ "从变更日志起草发布说明,中英各一份。",+ "Drafts release notes from the changelog, in both languages.",+ ),+ createdAt: iso(ago(40)),+ updatedAt: iso(ago(6)),+ activeSessionCount: 0,+ sessionCount: 2,+ sessionActivity: activity(11, 2),+ toolCount: 4,+ version: 3,+ kernelOutdated: true,+ vaultKeyCount: 0,+ scheduleCount: 1,+ skillCount: 1,+ hookCount: 0,+ pluginUpdates: [],+ memoryCount: 0,+ },+ ];++ const systemPrompt = L(+ "你是文档专家。回答问题时引用语料库中真实存在的文件。\n\n{{MEMORY}}\n\n{{SKILLS}}\n\n{{VAULT}}\n\n{{SCHEDULES}}",+ "You are Docs Expert. Cite a real corpus file for every claim.\n\n{{MEMORY}}\n\n{{SKILLS}}\n\n{{VAULT}}\n\n{{SCHEDULES}}",+ );+ const agentConfig = (agent: AgentSummary, full: boolean): AgentConfigResponse => ({+ agentsMd: L(+ `# ${agent.name}\n\n回答前先检索语料库;引用格式为 \`[n] path\`。`,+ `# ${agent.name}\n\nSearch the corpus before answering; cite as \`[n] path\`.`,+ ),+ systemConfigYaml: `version: ${agent.version}\nkernel_version: "2026-09-11"\nname: ${agent.name}\nmodel:\n thinking_level: medium\n max_tokens: 32000\ncompaction:\n max_context_length: 800000\n mode: summarize\n`,+ config: {+ name: agent.name,+ description: agent.description,+ version: agent.version,+ kernelVersion: agent.kernelOutdated ? "2026-08-20" : "2026-09-11",+ kernelLatest: "2026-09-11",+ kernelOutdated: agent.kernelOutdated,+ systemPrompt,+ maxTurns: 40,+ model: { maxTokens: 32_000, thinkingLevel: "medium", timeoutMs: 120_000 },+ compaction: { maxContextLength: 800_000, maxSessionTurns: 60, mode: "summarize" },+ memory: {+ enabled: true,+ prompt: "# Memory\n\n{{USER_MEMORY_INDEX}}",+ workspacePrompt:+ "## Workspace memory ({{WORKSPACE_MEMORY_DIR}})\n\n{{WORKSPACE_MEMORY_INDEX}}",+ },+ vault: {+ enabled: true,+ prompt: "# Vault\n\nThese environment variables are set: {{VAULT_KEYS}}",+ templateHasPlaceholder: true,+ legacySectionPresent: false,+ },+ skills: {+ enabled: true,+ prompt: "# Skills\n\n{{SKILL_METADATA}}",+ templateHasPlaceholder: true,+ legacySectionPresent: false,+ },+ schedules: {+ enabled: full,+ prompt: "# Scheduled tasks\n\n{{SCHEDULE_LIST}}",+ templateHasPlaceholder: full,+ },+ hooks: { enabled: true },+ toolsBuiltin: [+ {+ name: "read_file",+ description: "Read a file from the Workspace.",+ parameters: { type: "object", properties: { path: { type: "string" } } },+ permission: "r",+ },+ {+ name: "write_file",+ description: "Write a whole file.",+ parameters: {+ type: "object",+ properties: { path: { type: "string" }, content: { type: "string" } },+ },+ permission: "rw",+ },+ {+ name: "edit_file",+ description: "Replace one exact string in a file.",+ parameters: {+ type: "object",+ properties: {+ path: { type: "string" },+ old_string: { type: "string" },+ new_string: { type: "string" },+ },+ },+ permission: "rw",+ },+ {+ name: "exec_command",+ description: "Run a shell command in the Workspace.",+ parameters: {+ type: "object",+ properties: { description: { type: "string" }, cmd: { type: "string" } },+ },+ permission: "rw",+ timeoutMs: 600_000,+ maxOutputLength: 20_000,+ },+ ...(full+ ? [+ {+ name: "run_subagent",+ description: "Delegate a task to a child Agent.",+ parameters: {+ type: "object",+ properties: { description: { type: "string" }, task: { type: "string" } },+ },+ permission: "rw",+ } as AgentConfigResponse["config"]["toolsBuiltin"][number],+ ]+ : []),+ ],+ mcpServers: full+ ? [+ {+ name: "filesystem",+ config: {+ transport: "stdio",+ command: "npx",+ args: ["-y", "@modelcontextprotocol/server-filesystem", IDS.workspace],+ },+ },+ ]+ : [],+ },+ stateDir: `/home/demo/.penguin/data/projects/${IDS.project}/agents/${agent.agentId}/agent_state`,+ activeSessionCount: agent.activeSessionCount,+ });++ // Every preset the catalog seeds a Project with, in catalog order, each row exactly as the+ // server serves a freshly synced table — name, context window, protocol, vision, list price,+ // base URL and the running promotion — so the app's catalog check finds nothing to add or+ // update. Three groups carry a credential; the rest wait for a key, as in a fresh install.+ const promotions = new Map(+ presetPromotions().map((p) => [`${p.provider}\0${p.modelId}`, p.discount]),+ );+ const credentials: Record<string, Partial<ModelInfo>> = {+ deepseek: {+ envKey: "DEEPSEEK_API_KEY",+ credential: { apiKeyMasked: "sk-3f…9a2c", createdAt: iso(ago(60)) },+ },+ anthropic: { envKey: "ANTHROPIC_API_KEY", envKeyMasked: "sk-ant…Qm4x" },+ openai: {+ envKey: "OPENAI_API_KEY",+ credential: { apiKeyMasked: "sk-pr…7Hd1", createdAt: iso(ago(12)) },+ },+ };+ const models: ModelInfo[] = presetModelEntries().map((entry) => {+ const catalog = catalogEntryFor(entry.provider, entry.model_id);+ const discount = promotions.get(`${entry.provider}\0${entry.model_id}`);+ const row: ModelInfo = {+ provider: entry.provider,+ modelId: entry.model_id,+ ...(catalog?.displayName ? { displayName: catalog.displayName } : {}),+ ...(entry.context_window !== undefined ? { contextWindow: entry.context_window } : {}),+ ...(entry.client_type !== undefined ? { clientType: entry.client_type } : {}),+ ...(entry.vision === false ? { vision: false } : {}),+ ...(entry.pricing+ ? {+ pricing: {+ cacheRead: entry.pricing.cache_read,+ cacheWrite: entry.pricing.cache_write,+ output: entry.pricing.output,+ },+ }+ : {}),+ ...(discount !== undefined && entry.provider !== PENGUIN_GO_PROVIDER_ID ? { discount } : {}),+ ...(credentials[entry.provider] ?? {}),+ isDefault:+ entry.provider === DEFAULT_MODEL.provider && entry.model_id === DEFAULT_MODEL.modelId,+ };+ if (entry.base_url !== undefined) {+ row.credential = { ...(row.credential ?? {}), baseUrl: entry.base_url };+ }+ return row;+ });+ models.push({+ provider: "custom",+ modelId: "qwen3.8-27b-local",+ displayName: L("本机 Qwen 3.8", "Local Qwen 3.8"),+ contextWindow: 131_072,+ clientType: "openai-chat",+ vision: false,+ maxTokens: 8_192,+ credential: { baseUrl: "http://127.0.0.1:8000/v1", createdAt: iso(ago(3)) },+ isDefault: false,+ });+ const modelsResponse: ModelsResponse = {+ defaultModel: { provider: DEFAULT_MODEL.provider, modelId: DEFAULT_MODEL.modelId },+ visionModel: { provider: "anthropic", modelId: "claude-sonnet-5" },+ updatedAt: iso(ago(3)),+ models,+ };++ const sandbox: SessionInfo["sandbox"] = {+ mode: "workspace-write",+ network: "open",+ localNetworkSupported: false,+ };+ const session = (+ sessionId: string,+ agentId: string,+ title: string,+ createdAt: number,+ extra: Partial<SessionInfo> = {},+ ): SessionInfo => ({+ sessionId,+ projectId: IDS.project,+ agentId,+ provider: DEFAULT_MODEL.provider,+ modelId: DEFAULT_MODEL.modelId,+ workspace: IDS.workspace,+ approvalMode: "allow-all",+ sandbox,+ title,+ createdAt: iso(createdAt),+ lastActiveAt: iso(createdAt + 40_000),+ status: "idle",+ pendingApprovalCount: 0,+ pendingFollowUpCount: 0,+ hasTrace: true,+ archived: false,+ client: "web",+ ...extra,+ });+ const tempWorkspace = `/home/demo/.penguin/data/projects/${IDS.project}/agents/${IDS.agents.docs}/workspaces/tmp-7c1e9b2a`;+ const sessions: SessionInfo[] = [+ session(+ IDS.sessions.approval,+ IDS.agents.docs,+ L("发布文档包", "Publish the docs package"),+ ago(0, 1),+ {+ status: "running",+ pendingApprovalCount: 1,+ approvalMode: "always-ask",+ lastActiveAt: iso(ago(0, 0)),+ },+ ),+ session(+ IDS.sessions.thinking,+ IDS.agents.docs,+ L("规划 0.3 发布说明", "Plan the 0.3 release notes"),+ ago(0, 2),+ {+ status: "running",+ lastActiveAt: iso(ago(0, 0)),+ },+ ),+ session(+ IDS.sessions.runningTool,+ IDS.agents.docs,+ L("检查文档里的全部链接", "Check every link in the docs"),+ ago(0, 3),+ {+ status: "running",+ lastActiveAt: iso(ago(0, 1)),+ backgroundTasks: { processes: 1, subagents: 0 },+ },+ ),+ session(+ IDS.sessions.done,+ IDS.agents.docs,+ L("为 hooks 文档建立索引", "Index the hooks docs"),+ ago(0, 45),+ ),+ session(IDS.sessions.older[0], IDS.agents.docs, L("同步语料库", "Sync the corpus"), ago(1, 20)),+ session(IDS.sessions.older[1], IDS.agents.docs, L("上手说明", "Onboarding note"), ago(2, 60), {+ workspace: tempWorkspace,+ }),+ session(+ IDS.sessions.older[2],+ IDS.agents.docs,+ L("常失败的评估用例", "Cases that fail most"),+ ago(4, 10),+ ),+ session(+ IDS.sessions.older[3],+ IDS.agents.docs,+ L("接入 MCP 服务器", "Connect the MCP server"),+ ago(6, 5),+ {+ approvalMode: "read-only",+ },+ ),+ session(+ IDS.sessions.archived,+ IDS.agents.docs,+ L("迁移旧索引", "Migrate the old index"),+ ago(20),+ {+ archived: true,+ },+ ),+ session(IDS.sessions.schedule, IDS.agents.docs, L("每晚同步", "Nightly sync"), ago(0, 420), {+ source: "schedule",+ }),+ session(+ IDS.sessions.subagent,+ IDS.agents.docs,+ L("检查 hooks.md 的链接", "Check links in hooks.md"),+ ago(0, 44),+ {+ source: "subagent",+ },+ ),+ session(+ IDS.sessions.benchmark,+ IDS.agents.docs,+ L("评估 CASE-001", "Evaluate CASE-001"),+ ago(3),+ {+ source: "benchmark",+ workspace: `/home/demo/.penguin/data/projects/${IDS.project}/agents/${IDS.agents.docs}/workspaces/case-001`,+ },+ ),+ session(+ IDS.sessions.notes[0],+ IDS.agents.notes,+ L("0.2.13 发布说明", "0.2.13 release notes"),+ ago(5, 30),+ ),+ session(+ IDS.sessions.notes[1],+ IDS.agents.notes,+ L("破坏性变更清单", "Breaking changes list"),+ ago(9),+ ),+ ];++ const schedules: ProjectScheduleItem[] = [+ {+ agentId: IDS.agents.docs,+ name: "nightly-docs-sync",+ prompt: L(+ "从文档仓库同步语料库,汇报变化。",+ "Sync the corpus from the docs repository and report what changed.",+ ),+ enabled: true,+ startAt: iso(ago(30)),+ period: "24h",+ status: "active",+ nextFireAt: iso(now + 6 * 3_600_000),+ lastFiredAt: iso(ago(0, 420)),+ queued: false,+ creatorUserId: user.userId,+ },+ {+ agentId: IDS.agents.docs,+ name: "weekly-link-check",+ prompt: L("检查语料库里的所有链接。", "Check every link in the corpus."),+ enabled: true,+ startAt: iso(ago(14)),+ period: "7d",+ sessionId: IDS.sessions.runningTool,+ status: "active",+ nextFireAt: iso(now + 5 * DAY),+ lastFiredAt: iso(ago(2)),+ queued: false,+ creatorUserId: user.userId,+ },+ {+ agentId: IDS.agents.notes,+ name: "release-digest",+ prompt: L("汇总本周合并的 PR。", "Summarize the PRs merged this week."),+ enabled: false,+ startAt: iso(ago(20)),+ period: "7d",+ endAt: iso(now + 60 * DAY),+ provider: "anthropic",+ modelId: "claude-sonnet-5",+ status: "disabled",+ queued: false,+ creatorUserId: user.userId,+ },+ ];++ const skill = (+ name: string,+ zh: string,+ en: string,+ version = "2026.09.11.1",+ ): SkillMetadataItem => ({+ name,+ description: en,+ shortDescription: en,+ shortDescriptionZh: zh,+ version,+ });+ const library: PluginLibraryResponse = {+ groups: [+ {+ id: "developer",+ title: "Developer",+ titleZh: "开发",+ plugins: [+ {+ name: IDS.plugins.registry,+ description:+ "Answer questions about Claude Code from its documentation, with citations.",+ descriptionZh: "基于 Claude Code 文档回答问题,并给出引用。",+ shortDescription: "Claude Code docs, with citations",+ shortDescriptionZh: "带引用的 Claude Code 文档问答",+ version: "2026.09.20.1",+ skills: [+ skill(+ "claude-code-expert",+ "检索并引用 Claude Code 文档",+ "Search and cite the Claude Code docs",+ "2026.09.20.1",+ ),+ skill("docs-sync", "从上游同步文档语料库", "Sync the docs corpus from upstream"),+ ],+ hooks: [],+ },+ {+ name: "penguin-sdk",+ description:+ "Build with the PenguinHarness SDK: the Session, Agent State and OmniMessage APIs.",+ descriptionZh:+ "使用 PenguinHarness SDK 开发:Session、Agent State 与 OmniMessage 接口。",+ version: "2026.09.11.1",+ skills: [+ skill("penguin-sdk", "PenguinHarness SDK 用法", "How to use the PenguinHarness SDK"),+ ],+ hooks: [],+ },+ {+ name: "web-design",+ description: "Design and build web pages that do not read as templated defaults.",+ descriptionZh: "设计并实现不像模板默认值的网页。",+ version: "2026.09.11.1",+ skills: [skill("web-design", "网页视觉设计", "Web visual design")],+ hooks: [],+ },+ ],+ },+ {+ id: "office",+ title: "Office Productivity",+ titleZh: "办公效率",+ plugins: [+ {+ name: "goal",+ description:+ "Run a Session round after round until an objective is met, within a token budget.",+ descriptionZh: "在 Token 预算内一轮轮推进,直到达成目标。",+ version: "2026.09.02.1",+ skills: [],+ hooks: ["stop"],+ },+ {+ name: "continual-learning",+ description: "Write what a Session learned into the Agent's memory when it ends.",+ descriptionZh: "会话结束时把学到的东西写进智能体记忆。",+ version: "2026.09.02.1",+ skills: [+ skill(+ "continual-learning",+ "会话结束时沉淀记忆",+ "Consolidate memory when a Session ends",+ ),+ ],+ hooks: ["stop"],+ },+ {+ name: "report-writer",+ description:+ "Turn findings into a structured report with a summary, sections and an appendix.",+ descriptionZh: "把调查结果整理成带摘要、分节和附录的报告。",+ version: "2026.09.02.1",+ skills: [skill("report-writer", "撰写结构化报告", "Write structured reports")],+ hooks: [],+ },+ ],+ },+ ],+ };+ const pluginFiles: Record<string, Record<string, string>> = {+ [IDS.plugins.registry]: {+ "skills/claude-code-expert/SKILL.md":+ "---\nname: claude-code-expert\nversion: 2026.09.20.1\ndescription: Search and cite the Claude Code docs\n---\n\n# Claude Code expert\n\nSearch the corpus first, then answer with `[n] path` citations.\n",+ "skills/claude-code-expert/scripts/search.mjs":+ "#!/usr/bin/env node\n// BM25 over corpus/*.md\n",+ "skills/docs-sync/SKILL.md":+ "---\nname: docs-sync\nversion: 2026.09.11.1\ndescription: Sync the docs corpus from upstream\n---\n\n# Docs sync\n",+ },+ goal: {+ "hooks/hooks.json":+ '{ "name": "goal", "version": "2026.09.02.1", "events": ["stop"], "scripts": { "stop": "stop.mjs" } }\n',+ "hooks/stop.mjs":+ "export default async function stop(ctx) { return ctx.goal.done ? 'stop' : 'continue'; }\n",+ },+ };+ const docsSkills = library.groups[0]!.plugins[0]!.skills.map((s) => ({+ ...s,+ version: s.name === "claude-code-expert" ? "2026.09.11.1" : s.version,+ }));+ const installed: DemoFixtures["installed"] = {+ [IDS.agents.docs]: {+ skills: [+ ...docsSkills,+ skill("report-writer", "撰写结构化报告", "Write structured reports", "2026.09.02.1"),+ ],+ hooks: [+ {+ name: "goal",+ description: "Run a Session round after round until an objective is met.",+ descriptionZh: "一轮轮推进,直到达成目标。",+ version: "2026.09.02.1",+ events: ["stop"],+ },+ ],+ },+ [IDS.agents.notes]: {+ skills: [+ skill("report-writer", "撰写结构化报告", "Write structured reports", "2026.09.02.1"),+ ],+ hooks: [],+ },+ };++ const installedPlugins: InstalledPluginsResponse = {+ plugins: [+ {+ specifier: "@penguinharness/sandbox-bwrap",+ active: true,+ builtin: true,+ modules: ["sandbox.bwrap"],+ replaces: ["sandbox"],+ everywhere: true,+ machines: [],+ here: true,+ },+ {+ specifier: "@penguinharness/messaging-feishu",+ active: false,+ builtin: false,+ modules: ["messaging.feishu"],+ replaces: [],+ everywhere: false,+ machines: ["gpu-box-a8f3c2"],+ here: false,+ },+ ],+ shipped: ["@penguinharness/sandbox-bwrap", "@penguinharness/sandbox-seatbelt"],+ file: ".project_config.toml",+ machineId: "demo-machine-0001",+ restartPending: false,+ };+ const pluginIndex: PluginIndexResponse = {+ plugins: [+ {+ name: "@penguinharness/sandbox-bwrap",+ version: "0.2.13",+ description: "Confines agent commands with bubblewrap on Linux.",+ authors: ["PenguinHarness"],+ license: "MIT",+ repository: "https://github.com/prismshadow/penguin-harness",+ keywords: ["linux", "sandbox"],+ categories: ["sandbox"],+ updatedAt: Math.floor(ago(19) / 1000),+ },+ {+ name: "@penguinharness/sandbox-seatbelt",+ version: "0.2.13",+ description: "Confines agent commands with Seatbelt on macOS.",+ authors: ["PenguinHarness"],+ license: "MIT",+ repository: "https://github.com/prismshadow/penguin-harness",+ keywords: ["macos", "sandbox"],+ categories: ["sandbox"],+ updatedAt: Math.floor(ago(19) / 1000),+ },+ {+ name: "@penguinharness/messaging-feishu",+ version: "0.2.12",+ description: "Relays a Session to a Feishu bot.",+ authors: ["PenguinHarness"],+ license: "MIT",+ keywords: ["messaging", "feishu"],+ categories: ["messaging"],+ updatedAt: Math.floor(ago(40) / 1000),+ },+ ],+ };+ const readmes: Record<string, string> = {+ "@penguinharness/sandbox-bwrap":+ '# sandbox-bwrap\n\nRuns every agent command inside a bubblewrap namespace: the Workspace is writable, the rest of the filesystem read-only, and the network follows the Session\'s sandbox level.\n\n```toml\n[plugins]\nsandbox-bwrap = "@penguinharness/sandbox-bwrap"\n```\n',+ "@penguinharness/sandbox-seatbelt":+ "# sandbox-seatbelt\n\nThe macOS counterpart of sandbox-bwrap, on Seatbelt profiles.\n",+ "@penguinharness/messaging-feishu":+ "# messaging-feishu\n\nBinds a Session to a Feishu bot so replies reach a chat.\n",+ };++ const evaluation = (+ days: number,+ score: number,+ version: number,+ agentId: string,+ modelId: string,+ provider = "deepseek",+ ): BenchmarkSummary["evaluations"][number] => {+ const rnd = seeded(Math.round(score * 100));+ const cases = ["CASE-001-hooks", "CASE-002-mcp", "CASE-003-memory", "CASE-004-citations"].map(+ (id, i) => {+ const caseScore = Math.max(0, Math.min(100, Math.round(score + (rnd() - 0.5) * 24)));+ return {+ case: id,+ score: caseScore,+ cost: Math.round((0.012 + rnd() * 0.02) * 10_000) / 10_000,+ durationMs: 40_000 + Math.round(rnd() * 50_000),+ runs: [+ {+ score: caseScore,+ cost: 0.014,+ durationMs: 52_000 + i * 3_000,+ sessionId: IDS.sessions.benchmark,+ },+ ],+ };+ },+ );+ return {+ time: iso(ago(days)),+ agentId,+ summaryTitle: L(+ score > 78 ? "引用命中率明显提升" : "hooks 用例仍是短板",+ score > 78 ? "Citation accuracy up markedly" : "The hooks case is still the weak spot",+ ),+ summary: L(+ "四个用例平均分见上;本轮把语料库扫描改为按文件存在性过滤后,引用类失分消失。",+ "Average over four cases above; filtering the corpus walk on file existence removed the citation losses this round.",+ ),+ modelId,+ provider,+ thinkingLevel: "medium",+ version,+ score,+ cost:+ Math.round((cases.reduce((sum, c) => sum + (c.cost ?? 0), 0) / cases.length) * 10_000) /+ 10_000,+ durationMs: Math.round(cases.reduce((sum, c) => sum + c.durationMs, 0) / cases.length),+ cases,+ };+ };+ const benchmarks: BenchmarkSummary[] = [+ {+ id: IDS.benchmarks.docs,+ title: L("文档问答 v1", "Docs QA v1"),+ description: L(+ "四个关于 Claude Code 文档的问题,按引用是否真实、答案是否完整计分。",+ "Four questions about the Claude Code docs, scored on real citations and completeness.",+ ),+ runs: 1,+ status: "published",+ caseCount: 4,+ evaluations: [+ evaluation(12, 62, 11, IDS.agents.docs, "deepseek-flash"),+ evaluation(7, 74, 13, IDS.agents.docs, "deepseek-flash"),+ evaluation(2, 81, 14, IDS.agents.docs, "deepseek-flash"),+ evaluation(1, 77, 14, IDS.agents.docs, "claude-sonnet-5", "anthropic"),+ ],+ agentIds: [IDS.agents.docs],+ },+ {+ id: IDS.benchmarks.draft,+ title: L("发布说明草稿", "Release notes draft"),+ status: "draft",+ caseCount: 2,+ evaluations: [],+ agentIds: [],+ },+ ];+ const benchmarkCases: Record<string, BenchmarkCaseSummary[]> = {+ [IDS.benchmarks.docs]: [+ { id: "CASE-001-hooks", title: L("hooks 是怎么配置的?", "How are hooks configured?") },+ { id: "CASE-002-mcp", title: L("接入一个 MCP 服务器", "Connect an MCP server") },+ { id: "CASE-003-memory", title: L("记忆何时写入", "When memory is written") },+ {+ id: "CASE-004-citations",+ title: L("引用必须指向真实文件", "Citations must open a real file"),+ },+ ],+ [IDS.benchmarks.draft]: [+ { id: "CASE-001-lead", title: L("写一段导语", "Write a lead paragraph") },+ { id: "CASE-002-breaking", title: L("列出破坏性变更", "List the breaking changes") },+ ],+ };+ const caseFiles: DemoFixtures["caseFiles"] = {};+ for (const [benchmarkId, cases] of Object.entries(benchmarkCases)) {+ for (const item of cases) {+ caseFiles[`${benchmarkId}/${item.id}`] = {+ statement: {+ "README.md": `# ${item.title}\n\n${L("回答这个问题,并引用语料库里的文件。", "Answer the question, citing corpus files.")}\n`,+ "input/question.txt": `${item.title}\n`,+ },+ rubric: {+ "README.md": `# Rubric\n\n- ${L("引用真实文件", "Cites a real file")} — 50\n- ${L("答案完整", "Complete answer")} — 30\n- ${L("简洁", "Concise")} — 20\n`,+ },+ };+ }+ }++ const machines: MachinesResponse = {+ machines: [+ {+ id: IDS.machine,+ alias: "local",+ installed: { version: "0.2.13", at: iso(ago(19)) },+ machineId: "demo-machine-0001",+ local: true,+ connection: null,+ api: null,+ status: { state: "running", checkedAt: iso(ago(0, 1)), port: 7364 },+ root: "/home/demo/.penguin/data",+ },+ {+ id: "ssh:gpu-box",+ alias: "gpu-box",+ installed: { version: "0.2.13", at: iso(ago(5)) },+ machineId: "gpu-box-a8f3c2",+ local: false,+ connection: { pid: 41_226 },+ api: { answeredAt: iso(ago(0, 3)) },+ status: { state: "running", checkedAt: iso(ago(0, 3)), port: 7364 },+ root: "/home/ubuntu/.penguin/data",+ },+ {+ id: "ssh:office-mac",+ alias: "office-mac",+ installed: null,+ machineId: null,+ local: false,+ connection: null,+ api: null,+ status: null,+ root: "~/.penguin/data",+ },+ ],+ imageVersion: "0.2.13",+ job: null,+ jobs: [],+ };++ const version: VersionResponse = {+ version: "0.2.13",+ describe: "v0.2.13",+ channel: "release",+ buildDate: "2026-09-10",+ commit: "34f17ad35a2d4c1f9e8b7d6c5a4b3c2d1e0f9a8b",+ branch: null,+ dirty: null,+ runtime: { node: "24.8.0", platform: "linux", arch: "x64" },+ harness: null,+ };+ const update: UpdateCheckResponse = {+ currentVersion: "0.2.13",+ buildDate: "2026-09-10",+ latestVersion: "0.2.13",+ updateAvailable: false,+ releaseUrl: "https://github.com/prismshadow/penguin-harness/releases/tag/v0.2.13",+ publishedAt: iso(ago(19)),+ checkedAt: iso(ago(0, 12)),+ };++ const memoryFile = (+ scopeKey: string,+ name: string,+ title: string,+ description: string,+ content: string,+ days: number,+ ): MemoryFileResponse => ({+ scopeKey,+ file: {+ name,+ title,+ description,+ updatedAt: dayKey(ago(days)),+ size: content.length,+ modifiedAt: iso(ago(days)),+ },+ content,+ });+ const workspaceScope = "docs-expert-4f2a9c";+ const memory: DemoFixtures["memory"] = {+ [IDS.agents.docs]: {+ overview: {+ enabled: true,+ templateHasMemory: true,+ memoryDir: `/home/demo/.penguin/data/projects/${IDS.project}/agents/${IDS.agents.docs}/agent_state/memory`,+ scopes: [+ { scopeKey: "user", kind: "user", fileCount: 3, hasIndex: true, updatedAt: iso(ago(1)) },+ {+ scopeKey: workspaceScope,+ kind: "workspace",+ workspacePath: IDS.workspace,+ fileCount: 1,+ hasIndex: true,+ updatedAt: iso(ago(2)),+ },+ ],+ },+ files: [+ memoryFile(+ "user",+ "prefers-pnpm.md",+ L("偏好 pnpm", "Prefers pnpm"),+ L("包管理器一律用 pnpm。", "Always use pnpm as the package manager."),+ `---\nname: ${L("偏好 pnpm", "Prefers pnpm")}\nupdated_at: ${dayKey(ago(1))}\n---\n\n${L("用户在每个仓库里都用 pnpm;不要建议 npm 或 yarn。", "The user runs pnpm in every repository; never suggest npm or yarn.")}\n`,+ 1,+ ),+ memoryFile(+ "user",+ "citation-style.md",+ L("引用格式", "Citation style"),+ L("引用写成 [n] path。", "Cite as [n] path."),+ `---\nname: ${L("引用格式", "Citation style")}\nupdated_at: ${dayKey(ago(4))}\n---\n\n${L("引用编号放在句末,文件路径列在答案末尾。", "Number citations at the end of the sentence and list paths at the end of the answer.")}\n`,+ 4,+ ),+ memoryFile(+ "user",+ "timezone.md",+ L("时区", "Timezone"),+ L("用户在 UTC+8。", "The user is in UTC+8."),+ `---\nname: ${L("时区", "Timezone")}\nupdated_at: ${dayKey(ago(9))}\n---\n\n${L("时间一律按 UTC+8 显示。", "Show times in UTC+8.")}\n`,+ 9,+ ),+ memoryFile(+ workspaceScope,+ "corpus-layout.md",+ L("语料库结构", "Corpus layout"),+ L("corpus/ 下按上游仓库分目录。", "corpus/ is split by upstream repository."),+ `---\nname: ${L("语料库结构", "Corpus layout")}\nupdated_at: ${dayKey(ago(2))}\n---\n\ncorpus/claude-code-docs/ · corpus/penguin-docs/\n`,+ 2,+ ),+ ],+ },+ [IDS.agents.notes]: {+ overview: {+ enabled: true,+ templateHasMemory: false,+ memoryDir: `/home/demo/.penguin/data/projects/${IDS.project}/agents/${IDS.agents.notes}/agent_state/memory`,+ scopes: [{ scopeKey: "user", kind: "user", fileCount: 0, hasIndex: false }],+ },+ files: [],+ },+ };++ const vault: DemoFixtures["vault"] = {+ [IDS.agents.docs]: {+ entries: [+ { key: "GITHUB_TOKEN", valueMasked: "ghp_…9x2Q" },+ { key: "DOCS_UPSTREAM", valueMasked: "http…docs" },+ ],+ },+ [IDS.agents.notes]: { entries: [] },+ };++ const file = (name: string, sizeBytes: number, days: number): WorkspaceFileEntry => ({+ name,+ kind: "file",+ sizeBytes,+ mtime: iso(ago(days)),+ });+ const dir = (name: string, days: number): WorkspaceFileEntry => ({+ name,+ kind: "dir",+ sizeBytes: 0,+ mtime: iso(ago(days)),+ });+ const ragSource = `import fs from "node:fs";\nimport { bm25 } from "./bm25";\n\nexport function buildIndex(root: string) {\n const files = walk(root)\n .filter((f) => f.endsWith(".md"))\n .filter((f) => fs.existsSync(f)); // a citation must open a real file\n return bm25(files.map((f) => ({ source: f, text: fs.readFileSync(f, "utf8") })));\n}\n`;+ const workspace: DemoFixtures["workspace"] = {+ entries: {+ "": [+ dir("corpus", 1),+ dir("scripts", 3),+ dir("src", 0),+ dir("test", 0),+ file("CHANGELOG.md", 48_213, 1),+ file("README.md", 2_140, 12),+ file("package.json", 612, 12),+ ],+ corpus: [dir("claude-code-docs", 1), dir("penguin-docs", 1)],+ "corpus/claude-code-docs": [+ file("hooks.md", 9_812, 1),+ file("mcp.md", 7_420, 1),+ file("memory.md", 5_118, 1),+ ],+ "corpus/penguin-docs": [file("server-api.md", 31_004, 1), file("omni-message.md", 22_870, 1)],+ scripts: [file("check-links.mjs", 1_984, 3)],+ src: [file("bm25.ts", 3_102, 5), file("rag.ts", 1_410, 0)],+ test: [file("rag.test.ts", 2_206, 0)],+ },+ content: {+ "README.md": `# Docs Expert\n\n${L("一个引用来源的文档问答智能体。", "A docs question-answering Agent that cites its sources.")}\n\n- \`pnpm install\`\n- \`pnpm test\`\n`,+ "package.json":+ '{\n "name": "docs-expert",\n "private": true,\n "scripts": { "test": "vitest run" }\n}\n',+ "CHANGELOG.md":+ "# Changelog\n\n## Unreleased\n\n- Filter the corpus walk on file existence.\n",+ "src/rag.ts": ragSource,+ "src/bm25.ts":+ "export function bm25(docs: { source: string; text: string }[]) {\n // Okapi BM25, k1 = 1.2, b = 0.75\n return { query: (q: string) => rank(docs, q) };\n}\n",+ "test/rag.test.ts":+ 'import { expect, it } from "vitest";\nimport { buildIndex, rank } from "../src/rag";\n\nit("never cites a file that does not exist", () => {\n const index = buildIndex("corpus");\n for (const hit of rank("hooks", index)) expect(hit.source).toMatch(/\\.md$/);\n});\n',+ "scripts/check-links.mjs":+ "#!/usr/bin/env node\n// Walks every .md under corpus/, extracts links, HEADs each URL with a 10s timeout.\n",+ "corpus/claude-code-docs/hooks.md": `# Hooks\n\n${L("hooks 在 Agent State 的 hooks.json 里配置,每个钩子点一条。", "Hooks are configured in hooks.json under the Agent State, one entry per hook point.")}\n`,+ "corpus/claude-code-docs/mcp.md":+ "# MCP servers\n\nAn MCP server is declared under `tools.mcpServers` in system_config.yaml.\n",+ "corpus/claude-code-docs/memory.md":+ "# Memory\n\nMemory files are Markdown with a frontmatter name and description.\n",+ "corpus/penguin-docs/server-api.md": "# Server API\n\nEvery route is listed here.\n",+ "corpus/penguin-docs/omni-message.md": "# OmniMessage\n\nThe message protocol.\n",+ },+ };++ const chatDefaults: ChatDefaultsDto = {+ agentId: IDS.agents.docs,+ workspace: IDS.workspace,+ approvalMode: "allow-all",+ thinkingLevel: "medium",+ sandbox,+ };+ const rules: CommandPolicyDto["rules"] = [+ {+ name: "no-rm-root",+ pattern: "^rm\\s+-rf\\s+/(\\s|$)",+ description: L("删除根目录", "Deleting the root directory"),+ enabled: true,+ },+ {+ name: "no-force-push",+ pattern: "git\\s+push\\s+.*--force",+ description: L("强制推送", "Force pushing"),+ enabled: true,+ },+ {+ name: "no-curl-pipe-sh",+ pattern: "curl\\s.*\\|\\s*(ba)?sh",+ description: L("管道执行远程脚本", "Piping a download into a shell"),+ enabled: false,+ },+ ];+ const commandPolicy: CommandPolicyDto = {+ enabled: true,+ rules,+ defaultRules: rules.map((r) => ({ ...r, enabled: true })),+ };++ const pluginConfig: PluginConfigEntry[] = [+ {+ name: "sandbox",+ configuration: {+ title: "Sandbox",+ titleZh: "沙箱",+ description: "How agent commands are confined on this machine.",+ descriptionZh: "这台机器上智能体命令的隔离方式。",+ properties: {+ backend: {+ type: "enum",+ title: "Backend",+ titleZh: "后端",+ default: "bwrap",+ options: [+ { value: "bwrap", title: "bubblewrap" },+ { value: "seatbelt", title: "Seatbelt" },+ { value: "none", title: "None", titleZh: "不隔离" },+ ],+ },+ network: {+ type: "enum",+ title: "Network",+ titleZh: "网络",+ default: "open",+ options: [+ { value: "open", title: "Open", titleZh: "开放" },+ { value: "local", title: "Local only", titleZh: "仅本机" },+ { value: "none", title: "None", titleZh: "无" },+ ],+ },+ allowPaths: {+ type: "list",+ title: "Writable paths",+ titleZh: "可写路径",+ description: "Paths outside the Workspace the sandbox may write.",+ descriptionZh: "工作区之外允许写入的路径。",+ maxItems: 20,+ },+ },+ },+ values: { backend: "bwrap", network: "open", allowPaths: ["/tmp"] },+ unavailable: [+ { field: "backend", value: "seatbelt", reason: "macOS only", reasonZh: "仅 macOS" },+ ],+ actions: [+ {+ id: "verify",+ title: "Verify",+ titleZh: "验证",+ description: "Run a command through the sandbox and report what it could reach.",+ descriptionZh: "在沙箱里跑一条命令,报告它能触及什么。",+ },+ ],+ },+ ];+ const probeTargets: ProxyProbeTargetsResponse = {+ targets: [+ { provider: "openai", url: "https://api.openai.com/v1/models" },+ { provider: "anthropic", url: "https://api.anthropic.com/v1/models" },+ { provider: "gemini", url: "https://generativelanguage.googleapis.com/v1beta/models" },+ { provider: "deepseek", url: "https://api.deepseek.com/models" },+ { provider: "zai", url: "https://api.z.ai/api/paas/v4/models" },+ { provider: "bigmodel", url: "https://open.bigmodel.cn/api/paas/v4/models" },+ ],+ };++ const dirs: Record<string, DirListResponse> = {+ "/home/demo": {+ path: "/home/demo",+ parent: "/home",+ entries: [+ { name: ".penguin", path: "/home/demo/.penguin" },+ { name: "projects", path: "/home/demo/projects" },+ ],+ },+ "/home/demo/projects": {+ path: "/home/demo/projects",+ parent: "/home/demo",+ entries: [+ { name: "docs-expert", path: IDS.workspace },+ { name: "release-notes", path: "/home/demo/projects/release-notes" },+ ],+ },+ [IDS.workspace]: {+ path: IDS.workspace,+ parent: "/home/demo/projects",+ entries: [+ { name: "corpus", path: `${IDS.workspace}/corpus` },+ { name: "src", path: `${IDS.workspace}/src` },+ ],+ },+ "/home": { path: "/home", parent: "/", entries: [{ name: "demo", path: "/home/demo" }] },+ "/": { path: "/", parent: null, entries: [{ name: "home", path: "/home" }] },+ };++ const context: SessionContextResponse = {+ systemPrompt: 2_140,+ toolDefs: 1_860,+ userMessages: 320,+ assistantMessages: 4_210,+ toolRequests: 610,+ toolResults: 3_260,+ total: 12_400,+ topTools: [+ { name: "read_file", tokens: 2_100 },+ { name: "exec_command", tokens: 1_180 },+ { name: "edit_file", tokens: 590 },+ ],+ topFiles: [+ { path: "src/rag.ts", tokens: 1_640, ops: { read: 1, edit: 1, write: 0 } },+ { path: "test/rag.test.ts", tokens: 460, ops: { read: 1, edit: 0, write: 0 } },+ ],+ contextClosed: false,+ compactionThreshold: 800_000,+ };++ // Thirty days of usage: the docs Agent most days on the default model, the notes Agent on+ // a few, and a couple of days on the Anthropic model — enough to draw every chart.+ const rnd = seeded(2026);+ const usage: UsageDay[] = [];+ for (let day = 29; day >= 0; day -= 1) {+ const date = dayKey(ago(day));+ const busy = day % 7 !== 0 && day % 7 !== 6;+ const scale = busy ? 1 : 0.25;+ const docsRequests = Math.round((6 + rnd() * 14) * scale);+ usage.push({+ date,+ agentId: IDS.agents.docs,+ sessionId: day === 0 ? IDS.sessions.done : IDS.sessions.older[day % 4]!,+ provider: DEFAULT_MODEL.provider,+ modelId: DEFAULT_MODEL.modelId,+ cacheRead: Math.round(docsRequests * (18_000 + rnd() * 9_000)),+ cacheWrite: Math.round(docsRequests * (2_000 + rnd() * 1_500)),+ output: Math.round(docsRequests * (900 + rnd() * 700)),+ requests: docsRequests,+ completed: docsRequests - (rnd() < 0.15 ? 1 : 0),+ aborted: rnd() < 0.1 ? 1 : 0,+ });+ if (day % 3 === 0) {+ const notesRequests = Math.round((2 + rnd() * 5) * scale);+ usage.push({+ date,+ agentId: IDS.agents.notes,+ sessionId: IDS.sessions.notes[day % 2]!,+ provider: "anthropic",+ modelId: "claude-sonnet-5",+ cacheRead: Math.round(notesRequests * (12_000 + rnd() * 6_000)),+ cacheWrite: Math.round(notesRequests * (1_500 + rnd() * 900)),+ output: Math.round(notesRequests * (1_400 + rnd() * 900)),+ requests: notesRequests,+ completed: notesRequests,+ aborted: 0,+ });+ }+ }+ const usageErrors: UsageErrorItem[] = [+ {+ ts: iso(ago(0, 95)),+ source: "llm",+ code: "rate_limited",+ kind: "expected",+ message: "429 Too Many Requests from api.deepseek.com; retried after 8s.",+ },+ {+ ts: iso(ago(2, 40)),+ source: "http",+ code: "file_too_large",+ kind: "expected",+ message: "attachment exceeds the 100 MB limit (142 MB).",+ },+ {+ ts: iso(ago(5, 12)),+ source: "runtime",+ code: "internal",+ kind: "unexpected",+ message:+ "TypeError: cannot read properties of undefined (reading 'source') at rank (src/rag.ts:14).",+ },+ ];++ return {+ lang,+ now,+ user,+ users: [user, member],+ me: {+ previewIsolated: true,+ desktopMode: false,+ sessionVia: "password",+ uploadLimits: {+ attachmentMaxMb: 100,+ attachmentTotalMb: 120,+ attachmentMaxCount: 20,+ imageMaxMb: 20,+ attachmentLimitMinMb: 1,+ attachmentLimitMaxMb: 200,+ },+ companyMode: false,+ },+ prefs: {+ lastProjectId: IDS.project,+ credentialGuideSeen: true,+ initialPasswordBannerDismissed: true,+ workMode: "dev",+ },+ serverSettings: {+ proxyForApp: true,+ proxyForAgent: true,+ proxyUrl: null,+ attachmentMaxMb: 100,+ attachmentTotalMb: 120,+ companyMode: false,+ },+ project,+ members: [+ { userId: user.userId, role: "owner", createdAt: project.createdAt },+ { userId: member.userId, role: "member", createdAt: iso(ago(30)) },+ ],+ agents,+ agentConfigs: {+ [IDS.agents.docs]: agentConfig(agents[0]!, true),+ [IDS.agents.notes]: agentConfig(agents[1]!, false),+ },+ models: modelsResponse,+ sessions,+ schedules,+ library,+ pluginFiles,+ installed,+ installedPlugins,+ pluginIndex,+ readmes,+ benchmarks,+ benchmarkCases,+ caseFiles,+ machines,+ version,+ update,+ memory,+ vault,+ workspace,+ chatDefaults,+ commandPolicy,+ pluginConfig,+ probeTargets,+ dirs,+ context,+ usage,+ usageErrors,+ };+}diff --git a/packages/ui-gallery/src/app/mock/ids.ts b/packages/ui-gallery/src/app/mock/ids.tsnew file mode 100644index 00000000..dcd5ec30--- /dev/null+++ b/packages/ui-gallery/src/app/mock/ids.ts@@ -0,0 +1,50 @@+/**+ * The demo store's identifiers, in one place: the surfaces' routes name them, the fixtures+ * build the rows they name, and a test holds the two together. Ids follow the server's own+ * rules (a Project or Agent id is `^[a-z][a-z0-9_-]+$`; a session id is opaque).+ */+export const IDS = {+ project: "demo",+ users: { admin: "admin", member: "alice" },+ agents: { docs: "docs-expert", notes: "release-notes" },+ sessions: {+ /** A finished Task: thinking, three tools, a diff, a Markdown answer. */+ done: "s-hooks-index",+ /** A Task mid-run: a command executing, its output still to come. */+ runningTool: "s-link-check",+ /** A Task mid-run: the model thinking, the text still streaming in. */+ thinking: "s-release-plan",+ /** A Task waiting on a human: a command that needs approval. */+ approval: "s-publish",+ /** Older conversations that fill the list. */+ older: ["s-sync-corpus", "s-onboarding", "s-benchmarks", "s-mcp-setup"],+ /** One row per folder: archived, a scheduled run, a subagent, an evaluation. */+ archived: "s-archived-migration",+ schedule: "s-nightly-sync",+ subagent: "s-sub-linkcheck",+ benchmark: "s-eval-run",+ /** The release-notes Agent's own. */+ notes: ["s-notes-0213", "s-notes-0212"],+ },+ benchmarks: { docs: "docs-qa-v1", draft: "release-notes-draft" },+ plugins: {+ /** A library plugin the detail page opens on. */+ registry: "claude-code-expert",+ },+ machine: "local",+ workspace: "/home/demo/projects/docs-expert",+} as const;++/** Every session id the store seeds, for the tests that walk them. */+export const ALL_SESSION_IDS: readonly string[] = [+ IDS.sessions.done,+ IDS.sessions.runningTool,+ IDS.sessions.thinking,+ IDS.sessions.approval,+ ...IDS.sessions.older,+ IDS.sessions.archived,+ IDS.sessions.schedule,+ IDS.sessions.subagent,+ IDS.sessions.benchmark,+ ...IDS.sessions.notes,+];diff --git a/packages/ui-gallery/src/app/mock/router.ts b/packages/ui-gallery/src/app/mock/router.tsnew file mode 100644index 00000000..bee0b6e5--- /dev/null+++ b/packages/ui-gallery/src/app/mock/router.ts@@ -0,0 +1,187 @@+/**+ * Routing for the mocked API: a method and a path pattern per handler, `:name` segments bound+ * as params, the query parsed, the body passed through. A request no route matches answers+ * 404 with the `gallery_unmocked` code — that, and nothing else, is what the coverage test+ * treats as a gap. A signed-out request to anything but the public routes answers 401, as the+ * server does, so the app's sign-out path is exercised too.+ *+ * Machine-routed paths (`/server/<id>/api/…`) are answered as if by this server: the demo has+ * one machine's worth of everything.+ */+import { ApiError, UNMOCKED } from "./errors";+import type { DemoStore } from "./store";++export type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";++/** A handler's answer: JSON (the default), a raw body with headers, or nothing (204). */+export type Answer =+ | { kind: "json"; status: number; body: unknown }+ | { kind: "raw"; status: number; body: string; headers: Record<string, string> }+ | { kind: "empty"; status: number };++export interface RequestContext {+ store: DemoStore;+ method: Method;+ path: string;+ params: Record<string, string>;+ query: URLSearchParams;+ body: unknown;+}++export type Handler = (ctx: RequestContext) => unknown | Answer | Promise<unknown | Answer>;++interface Route {+ method: Method;+ pattern: string;+ segments: string[];+ handler: Handler;+}++/** Marks an answer as raw text with headers (a file's content, a download). */+export function raw(body: string, headers: Record<string, string> = {}, status = 200): Answer {+ return { kind: "raw", status, body, headers };+}++/** Marks an answer as bodiless (a 204, or a 202 that says nothing). */+export function empty(status = 204): Answer {+ return { kind: "empty", status };+}++/** JSON with a status other than 200 (a 201 on creation). */+export function json(body: unknown, status: number): Answer {+ return { kind: "json", status, body };+}++/** Throws the failure the app expects for a refused request. */+export function fail(status: number, code: string, message: string): never {+ throw new ApiError(status, code, message);+}++function isAnswer(value: unknown): value is Answer {+ return (+ typeof value === "object" &&+ value !== null &&+ "kind" in value &&+ ((value as Answer).kind === "json" ||+ (value as Answer).kind === "raw" ||+ (value as Answer).kind === "empty")+ );+}++export class Router {+ private readonly routes: Route[] = [];+ private readonly publicPaths = new Set<string>();++ add(method: Method, pattern: string, handler: Handler): this {+ this.routes.push({ method, pattern, segments: pattern.split("/"), handler });+ return this;+ }++ get(pattern: string, handler: Handler): this {+ return this.add("GET", pattern, handler);+ }+ post(pattern: string, handler: Handler): this {+ return this.add("POST", pattern, handler);+ }+ put(pattern: string, handler: Handler): this {+ return this.add("PUT", pattern, handler);+ }+ patch(pattern: string, handler: Handler): this {+ return this.add("PATCH", pattern, handler);+ }+ delete(pattern: string, handler: Handler): this {+ return this.add("DELETE", pattern, handler);+ }++ /** Routes a signed-out request may take. */+ public(...patterns: string[]): this {+ for (const pattern of patterns) this.publicPaths.add(pattern);+ return this;+ }++ /** The route a method and path name, with the params bound; null when none matches. */+ match(method: Method, path: string): { route: Route; params: Record<string, string> } | null {+ const parts = path.split("/");+ for (const route of this.routes) {+ if (route.method !== method) continue;+ const params = matchSegments(route.segments, parts);+ if (params !== null) return { route, params };+ }+ return null;+ }++ /** Every pattern, for the tests. */+ patterns(): readonly { method: Method; pattern: string }[] {+ return this.routes.map(({ method, pattern }) => ({ method, pattern }));+ }++ async dispatch(store: DemoStore, method: Method, url: string, body: unknown): Promise<Answer> {+ const { path, query } = splitUrl(url);+ const found = this.match(method, path);+ if (found === null) {+ throw new ApiError(+ 404,+ UNMOCKED,+ `The gallery's demo API has no answer for ${method} ${path}.`,+ );+ }+ if (!store.signedIn && !this.publicPaths.has(found.route.pattern)) {+ throw new ApiError(401, "unauthorized", "Not signed in.");+ }+ const result = await found.route.handler({+ store,+ method,+ path,+ params: found.params,+ query,+ body,+ });+ if (isAnswer(result)) return result;+ if (result === undefined) return { kind: "empty", status: 204 };+ return { kind: "json", status: 200, body: result };+ }+}++/** `:name` segments bind; `*` at the end swallows the rest; anything else matches literally. */+function matchSegments(pattern: string[], parts: string[]): Record<string, string> | null {+ const params: Record<string, string> = {};+ for (let i = 0; i < pattern.length; i += 1) {+ const expected = pattern[i]!;+ if (expected === "*") {+ params["*"] = parts.slice(i).map(decode).join("/");+ return params;+ }+ const actual = parts[i];+ if (actual === undefined) return null;+ if (expected.startsWith(":")) params[expected.slice(1)] = decode(actual);+ else if (expected !== actual) return null;+ }+ return parts.length === pattern.length ? params : null;+}++function decode(segment: string): string {+ try {+ return decodeURIComponent(segment);+ } catch {+ return segment;+ }+}++/** The path (machine prefix removed) and query of a request URL, relative or absolute. */+export function splitUrl(url: string): { path: string; query: URLSearchParams } {+ const withoutOrigin = url.replace(/^[a-z]+:\/\/[^/]+/i, "");+ const hash = withoutOrigin.indexOf("#");+ const clean = hash === -1 ? withoutOrigin : withoutOrigin.slice(0, hash);+ const q = clean.indexOf("?");+ let path = q === -1 ? clean : clean.slice(0, q);+ const query = new URLSearchParams(q === -1 ? "" : clean.slice(q + 1));+ const machine = /^\/server\/[^/]+(\/api\/.*)$/.exec(path);+ if (machine) path = machine[1]!;+ return { path, query };+}++/** Whether a URL is one the mock answers: this server's API, or a machine's through it. */+export function isApiUrl(url: string): boolean {+ const { path } = splitUrl(url);+ return path.startsWith("/api/");+}diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsnew file mode 100644index 00000000..dda44ee8--- /dev/null+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -0,0 +1,2029 @@+/**+ * Every endpoint the Web App calls (`packages/web/src/api/endpoints.ts`), answered from the+ * demo store. Reads answer the fixtures; writes mutate them where the app shows the result+ * (a renamed Session, a saved model table, a new schedule) and answer `demo_read_only` where+ * the operation would need a machine, a registry or a provider behind it. Each handler's+ * return is annotated with the contract type it stands for, so a DTO change fails here+ * before it fails in the app.+ *+ * Grouped as endpoints.ts groups them, in its order.+ */+import type {+ AdminUserCreateResponse,+ AdminUsersResponse,+ AgentConfigResponse,+ AgentCreateResponse,+ AgentHooksResponse,+ AgentKernelUpdateResponse,+ AgentPluginsInstallResponse,+ AgentSchedulesConfigDto,+ AgentSkillsConfigDto,+ AgentSkillsResponse,+ AgentsResponse,+ AgentVaultConfigDto,+ AuthResponse,+ BenchmarkCasesResponse,+ BuiltinBrowserHistoryResponse,+ BuiltinBrowserImportSourcesResponse,+ BuiltinBrowserSettings,+ BuiltinBrowserStatus,+ BenchmarkCreateResponse,+ BenchmarksResponse,+ CaseMaterial,+ ChatDefaultsDto,+ CommandPolicyDto,+ DefaultModelResponse,+ DesktopTrayStatusResponse,+ DesktopUpdateStatusResponse,+ DirectorySkillsResponse,+ DirListResponse,+ EndpointModelListResponse,+ FilesStatResponse,+ GoalResponse,+ InstallResponse,+ InstalledPluginsResponse,+ MachinesResponse,+ MachinesUseResponse,+ McpServerTestResponse,+ MemberAddResponse,+ MembersResponse,+ MemoryFileResponse,+ MemoryFilesResponse,+ MemoryImportResponse,+ MemoryOverviewResponse,+ MemoryScopeExport,+ MeResponse,+ MessagesResponse,+ MessagingBindingsResponse,+ ModelProtocolDetectResponse,+ ModelsResponse,+ ModelTestResponse,+ ModelVisionDetectResponse,+ OrganizationsResponse,+ PluginConfigActionResponse,+ PluginConfigResponse,+ PluginFilesResponse,+ PluginIndexResponse,+ PluginLibraryResponse,+ PluginReadmeResponse,+ PrefsResponse,+ ProjectSchedulesResponse,+ ProjectsResponse,+ ProjectUpdateResponse,+ ProxyProbeResponse,+ ProxyProbeTargetsResponse,+ RestartResponse,+ RetryNowResponse,+ ScheduleItem,+ SchedulesResponse,+ SemanticIdSuggestResponse,+ ServerSettingsResponse,+ SessionCategory,+ SessionCategoryCounts,+ SessionContextResponse,+ SessionCreateResponse,+ SessionForkResponse,+ SessionInfo,+ SessionProcessesResponse,+ SessionResponse,+ SessionTracesResponse,+ SshHostResponse,+ SubagentMessageResponse,+ TaskCreateResponse,+ TraceAnalysisResponse,+ TraceEventsResponse,+ TraceImportResponse,+ UpdateCheckResponse,+ UpdateJobStatus,+ UpdateProfileResponse,+ UsageErrorsClearResponse,+ UsageErrorsPage,+ UsageGranularity,+ UsageGroupBy,+ UsageModelTotals,+ UsageResponse,+ UserInfo,+ VaultResponse,+ VersionHistoryResponse,+ VersionResponse,+ WorkflowInfo,+ WorkspaceFilesResponse,+ WorkspaceSearchResponse,+} from "@prismshadow/penguin-server/api";+import { READ_ONLY } from "./errors";+import { dayKey } from "./fixtures";+import type { UsageDay } from "./fixtures";+import { IDS } from "./ids";+import { empty, fail, json, raw, Router } from "./router";+import type { RequestContext } from "./router";+import type { DemoStore } from "./store";+import { payloadOf } from "./types";+import type { OmniMessage } from "./types";++type Ctx = RequestContext;++const record = (body: unknown): Record<string, unknown> =>+ typeof body === "object" && body !== null ? (body as Record<string, unknown>) : {};++const str = (value: unknown, fallback = ""): string =>+ typeof value === "string" ? value : fallback;++/** Function declarations rather than arrows: only those narrow control flow as `never` calls. */+function readOnly(what: string): never {+ return fail(409, READ_ONLY, `The gallery's demo cannot ${what}; it has no server behind it.`);+}++function notFound(what: string): never {+ return fail(404, "not_found", `${what} not found.`);+}++/** The cost of a Token bucket at the demo's default rates (USD per million). */+function costOf(day: Pick<UsageDay, "cacheRead" | "cacheWrite" | "output" | "provider">): number {+ const rate =+ day.provider === "anthropic"+ ? { cacheRead: 0.2, cacheWrite: 2.5, output: 10 }+ : { cacheRead: 0.0057, cacheWrite: 0.2857, output: 1.1429 };+ return (+ (day.cacheRead * rate.cacheRead + day.cacheWrite * rate.cacheWrite + day.output * rate.output) /+ 1_000_000+ );+}++export const router = new Router();++// ---------------------------------------------------------------------------------------------+// Auth & user+// ---------------------------------------------------------------------------------------------++router+ .public("/api/auth/login", "/api/auth/logout", "/api/install", "/api/version")+ .post("/api/auth/login", ({ store, body }): AuthResponse => {+ const { userId, password } = record(body);+ if (str(password).length === 0) fail(401, "invalid_credentials", "Wrong user id or password.");+ if (userId !== undefined && userId !== store.f.user.userId) {+ fail(401, "invalid_credentials", "Wrong user id or password.");+ }+ store.signedIn = true;+ return { user: store.f.user };+ })+ .post("/api/auth/logout", ({ store }) => {+ store.signedIn = false;+ return empty();+ })+ .get("/api/install", (): InstallResponse => ({ installId: "gallery-demo" }))+ .get("/api/me", ({ store }): MeResponse => ({ user: store.f.user, ...store.f.me }))+ .put("/api/me/password", () => empty())+ .put("/api/me/profile", ({ store, body }): UpdateProfileResponse => {+ const patch = record(body);+ const user: UserInfo = { ...store.f.user };+ if (patch.displayName === null) delete user.displayName;+ else if (typeof patch.displayName === "string") user.displayName = patch.displayName;+ if (patch.avatar === null) delete user.avatar;+ else if (typeof patch.avatar === "string") user.avatar = patch.avatar;+ store.f.user = user;+ return { user };+ })+ .get("/api/me/prefs", ({ store }): PrefsResponse => ({ prefs: store.f.prefs }))+ .put("/api/me/prefs", ({ store, body }): PrefsResponse => {+ store.f.prefs = { ...store.f.prefs, ...record(body) };+ return { prefs: store.f.prefs };+ });++// ---------------------------------------------------------------------------------------------+// Admin+// ---------------------------------------------------------------------------------------------++router+ .get("/api/admin/users", ({ store }): AdminUsersResponse => ({ users: store.f.users }))+ .post("/api/admin/users", ({ store, body }): unknown => {+ const userId = str(record(body).userId, "new-user");+ const user: UserInfo = {+ userId,+ isAdmin: false,+ passwordIsInitial: true,+ createdAt: new Date().toISOString(),+ };+ store.f.users.push(user);+ return json({ user } satisfies AdminUserCreateResponse, 201);+ })+ .post("/api/admin/users/:userId/password", () => empty())+ .delete("/api/admin/users/:userId", ({ store, params }) => {+ store.f.users = store.f.users.filter((u) => u.userId !== params.userId);+ return empty();+ })+ .get("/api/admin/settings", ({ store }): ServerSettingsResponse => ({+ settings: store.f.serverSettings,+ }))+ .put("/api/admin/settings", ({ store, body }): ServerSettingsResponse => {+ store.f.serverSettings = { ...store.f.serverSettings, ...record(body) };+ return { settings: store.f.serverSettings };+ })+ .get("/api/admin/plugin-config", ({ store }): PluginConfigResponse => ({+ plugins: store.f.pluginConfig,+ }))+ .put("/api/admin/plugin-config", ({ store, body }): PluginConfigResponse => {+ const { name, values } = record(body);+ const entry = store.f.pluginConfig.find((p) => p.name === name);+ if (entry) entry.values = { ...entry.values, ...record(values) };+ return { plugins: store.f.pluginConfig };+ })+ .post("/api/admin/plugin-config/action", ({ store }): PluginConfigActionResponse => ({+ ok: true,+ message: "The sandbox confined the command as configured.",+ messageZh: "沙箱按配置隔离了命令。",+ plugins: store.f.pluginConfig,+ }))+ .get(+ "/api/admin/settings/proxy-probe",+ ({ store }): ProxyProbeTargetsResponse => store.f.probeTargets,+ )+ .post("/api/admin/settings/proxy-probe/:provider", ({ store, params }): ProxyProbeResponse => {+ const target = store.f.probeTargets.targets.find((t) => t.provider === params.provider);+ if (!target) notFound("Probe target");+ return { probe: { ...target, outcome: "reachable", ms: 180 + target.url.length, status: 401 } };+ });++// ---------------------------------------------------------------------------------------------+// Projects & members+// ---------------------------------------------------------------------------------------------++router+ .get("/api/projects", ({ store }): ProjectsResponse => ({ projects: [store.f.project] }))+ .post("/api/projects", (): unknown => readOnly("create a Project"))+ .patch("/api/projects/:projectId", ({ store, body }): ProjectUpdateResponse => {+ store.f.project.name = str(record(body).name, store.f.project.name);+ return { project: store.f.project };+ })+ .delete("/api/projects/:projectId", () => readOnly("delete the Project"))+ .get("/api/projects/:projectId/members", ({ store }): MembersResponse => ({+ members: store.f.members,+ }))+ .post("/api/projects/:projectId/members", ({ store, body }): unknown => {+ const member = {+ userId: str(record(body).userId, "guest"),+ role: "member" as const,+ createdAt: new Date().toISOString(),+ };+ store.f.members.push(member);+ return json({ member } satisfies MemberAddResponse, 201);+ })+ .delete("/api/projects/:projectId/members/:userId", ({ store, params }) => {+ store.f.members = store.f.members.filter((m) => m.userId !== params.userId);+ return empty();+ })+ .get(+ "/api/projects/:projectId/chat-defaults",+ ({ store }): ChatDefaultsDto => store.f.chatDefaults,+ )+ .put("/api/projects/:projectId/chat-defaults", ({ store, body }): ChatDefaultsDto => {+ const { sandbox } = store.f.chatDefaults;+ store.f.chatDefaults = {+ ...(record(body) as ChatDefaultsDto),+ ...(sandbox ? { sandbox } : {}),+ };+ return store.f.chatDefaults;+ })+ .get(+ "/api/projects/:projectId/command-policy",+ ({ store }): CommandPolicyDto => store.f.commandPolicy,+ )+ .put("/api/projects/:projectId/command-policy", ({ store, body }): CommandPolicyDto => {+ const { enabled, rules } = record(body);+ store.f.commandPolicy = {+ ...store.f.commandPolicy,+ enabled: typeof enabled === "boolean" ? enabled : store.f.commandPolicy.enabled,+ rules: Array.isArray(rules)+ ? (rules as CommandPolicyDto["rules"]).map((r) => ({ ...r, enabled: r.enabled !== false }))+ : store.f.commandPolicy.rules,+ };+ return store.f.commandPolicy;+ });++// ---------------------------------------------------------------------------------------------+// Models and provider keys+// ---------------------------------------------------------------------------------------------++router+ .get("/api/projects/:projectId/models", ({ store }): ModelsResponse => store.f.models)+ .put("/api/projects/:projectId/models", ({ store, body }): ModelsResponse => {+ const { defaultModel, visionModel, models } = record(body) as Partial<{+ defaultModel: ModelsResponse["defaultModel"];+ visionModel: ModelsResponse["visionModel"];+ models: Array<Record<string, unknown>>;+ }>;+ if (Array.isArray(models)) {+ store.f.models.models = models.map((entry) => {+ const existing = store.f.models.models.find(+ (m) => m.provider === entry.provider && m.modelId === entry.modelId,+ );+ const { apiKey, clearApiKey, baseUrl, renamedFrom, discount, ...rest } = entry;+ const credential = { ...(existing?.credential ?? {}) };+ if (typeof apiKey === "string" && apiKey !== "") {+ credential.apiKeyMasked = `${apiKey.slice(0, 4)}…${apiKey.slice(-4)}`;+ credential.createdAt = new Date().toISOString();+ }+ if (clearApiKey === true) delete credential.apiKeyMasked;+ if (typeof baseUrl === "string") credential.baseUrl = baseUrl;+ if (baseUrl === null) delete credential.baseUrl;+ void renamedFrom;+ const next = {+ ...(existing ?? {}),+ ...(rest as Partial<ModelsResponse["models"][number]>),+ provider: str(entry.provider),+ modelId: str(entry.modelId),+ isDefault:+ defaultModel?.provider === entry.provider && defaultModel?.modelId === entry.modelId,+ } as ModelsResponse["models"][number];+ if (Object.keys(credential).length > 0) next.credential = credential;+ else delete next.credential;+ if (typeof discount === "number") next.discount = discount;+ else if (discount === null) delete next.discount;+ return next;+ });+ }+ if (defaultModel) store.f.models.defaultModel = defaultModel;+ if (visionModel) store.f.models.visionModel = visionModel;+ store.f.models.updatedAt = new Date().toISOString();+ return store.f.models;+ })+ .put("/api/projects/:projectId/models/default", ({ store, body }): DefaultModelResponse => {+ const { provider, modelId } = record(body);+ const ref = { provider: str(provider), modelId: str(modelId) };+ store.f.models.defaultModel = ref;+ for (const m of store.f.models.models) {+ m.isDefault = m.provider === ref.provider && m.modelId === ref.modelId;+ }+ return { defaultModel: ref };+ })+ .post("/api/projects/:projectId/models/test", (): ModelTestResponse => ({+ ok: true,+ latencyMs: 640,+ ttftMs: 410,+ tps: 62.5,+ }))+ .post("/api/projects/:projectId/models/detect", ({ body }): ModelProtocolDetectResponse => {+ const baseUrl = str(record(body).baseUrl, "https://example.invalid");+ return {+ detected: "openai-chat",+ baseUrl: baseUrl.replace(/\/+$/, ""),+ probes: [+ {+ clientType: "openai-responses",+ url: `${baseUrl}/responses`,+ outcome: "route_missing",+ status: 404,+ },+ {+ clientType: "ant-messages",+ url: `${baseUrl}/messages`,+ outcome: "route_missing",+ status: 404,+ },+ {+ clientType: "openai-chat",+ url: `${baseUrl}/chat/completions`,+ outcome: "served",+ status: 401,+ },+ ],+ };+ })+ .post("/api/projects/:projectId/models/list", (): EndpointModelListResponse => ({+ ok: true,+ models: ["qwen3.8-27b-local", "qwen3.6-35b-a3b"],+ }))+ .post("/api/projects/:projectId/models/detect-vision", (): ModelVisionDetectResponse => ({+ outcome: "unsupported",+ }))+ .post("/api/projects/:projectId/model-oauth/start", () =>+ readOnly("open a provider authorization flow"),+ )+ .get("/api/projects/:projectId/model-oauth/:flowId", () => notFound("Authorization flow"))+ .post("/api/projects/:projectId/model-oauth/:flowId/code", () => notFound("Authorization flow"));++for (const route of ["platform-auth", "modelscope-auth"]) {+ router+ .post(`/api/projects/:projectId/${route}/start`, () => readOnly("start a key authorization"))+ .get(`/api/projects/:projectId/${route}/:flowId/status`, () =>+ fail(404, `${route.replace("-", "_")}_flow_not_found`, "No such flow."),+ )+ .post(`/api/projects/:projectId/${route}/:flowId/retry`, () =>+ fail(404, `${route.replace("-", "_")}_flow_not_found`, "No such flow."),+ )+ .post(`/api/projects/:projectId/${route}/:flowId/cancel`, () => ({ ok: true }));+}+router.post("/api/projects/:projectId/platform-auth/sync", ({ store }): unknown => ({+ ...store.f.models,+ added: 0,+ updated: 0,+}));++// ---------------------------------------------------------------------------------------------+// Vault, template placeholders, memory+// ---------------------------------------------------------------------------------------------++const agentOf = ({ store, params }: Ctx) => {+ const agent = store.f.agents.find((a) => a.agentId === params.agentId);+ if (!agent) notFound("Agent");+ return agent;+};+const configOf = (ctx: Ctx): AgentConfigResponse => {+ const config = ctx.store.f.agentConfigs[agentOf(ctx).agentId];+ if (!config) notFound("Agent config");+ return config;+};++router+ .get(+ "/api/projects/:projectId/agents/:agentId/vault",+ (ctx): VaultResponse => ctx.store.f.vault[agentOf(ctx).agentId] ?? { entries: [] },+ )+ .put("/api/projects/:projectId/agents/:agentId/vault", (ctx): VaultResponse => {+ const agentId = agentOf(ctx).agentId;+ const entries = record(ctx.body).entries;+ const previous = ctx.store.f.vault[agentId]?.entries ?? [];+ const next: VaultResponse = {+ entries: Array.isArray(entries)+ ? (entries as Array<{ key: string; value?: string }>).map((e) => ({+ key: e.key,+ valueMasked:+ typeof e.value === "string"+ ? `${e.value.slice(0, 3)}…${e.value.slice(-3)}`+ : (previous.find((p) => p.key === e.key)?.valueMasked ?? "***"),+ }))+ : previous,+ };+ ctx.store.f.vault[agentId] = next;+ return next;+ })+ .post(+ "/api/projects/:projectId/agents/:agentId/vault/template-placeholder",+ (ctx): AgentVaultConfigDto => {+ const config = configOf(ctx);+ config.config.vault = {+ ...config.config.vault,+ templateHasPlaceholder: true,+ legacySectionPresent: false,+ };+ return config.config.vault;+ },+ )+ .post(+ "/api/projects/:projectId/agents/:agentId/skills/template-placeholder",+ (ctx): AgentSkillsConfigDto => {+ const config = configOf(ctx);+ config.config.skills = {+ ...config.config.skills,+ templateHasPlaceholder: true,+ legacySectionPresent: false,+ };+ return config.config.skills;+ },+ )+ .post(+ "/api/projects/:projectId/agents/:agentId/schedules/template-placeholder",+ (ctx): AgentSchedulesConfigDto => {+ const config = configOf(ctx);+ config.config.schedules = { ...config.config.schedules, templateHasPlaceholder: true };+ return config.config.schedules;+ },+ );++const memoryOf = (ctx: Ctx) => {+ const memory = ctx.store.f.memory[agentOf(ctx).agentId];+ if (!memory) notFound("Memory");+ return memory;+};++router+ .get(+ "/api/projects/:projectId/agents/:agentId/memory",+ (ctx): MemoryOverviewResponse => memoryOf(ctx).overview,+ )+ .post(+ "/api/projects/:projectId/agents/:agentId/memory/template-placeholder",+ (ctx): MemoryOverviewResponse => {+ const memory = memoryOf(ctx);+ memory.overview.templateHasMemory = true;+ return memory.overview;+ },+ )+ .get(+ "/api/projects/:projectId/agents/:agentId/memory/scopes/:scopeKey/files",+ (ctx): MemoryFilesResponse => ({+ scopeKey: ctx.params.scopeKey!,+ files: memoryOf(ctx)+ .files.filter((f) => f.scopeKey === ctx.params.scopeKey)+ .map((f) => f.file),+ }),+ )+ .get(+ "/api/projects/:projectId/agents/:agentId/memory/scopes/:scopeKey/files/:name",+ (ctx): MemoryFileResponse => {+ const found = memoryOf(ctx).files.find(+ (f) => f.scopeKey === ctx.params.scopeKey && f.file.name === ctx.params.name,+ );+ if (!found) notFound("Memory file");+ return found;+ },+ )+ .delete("/api/projects/:projectId/agents/:agentId/memory/scopes/:scopeKey/files/:name", (ctx) => {+ const memory = memoryOf(ctx);+ memory.files = memory.files.filter(+ (f) => !(f.scopeKey === ctx.params.scopeKey && f.file.name === ctx.params.name),+ );+ const scope = memory.overview.scopes.find((s) => s.scopeKey === ctx.params.scopeKey);+ if (scope) scope.fileCount = memory.files.filter((f) => f.scopeKey === scope.scopeKey).length;+ return empty();+ })+ .get(+ "/api/projects/:projectId/agents/:agentId/memory/scopes/:scopeKey/export",+ (ctx): MemoryScopeExport => {+ const memory = memoryOf(ctx);+ const scope = memory.overview.scopes.find((s) => s.scopeKey === ctx.params.scopeKey);+ if (!scope) notFound("Memory scope");+ return {+ format: "penguin-memory-scope",+ version: 1,+ scopeKey: scope.scopeKey,+ kind: scope.kind,+ ...(scope.workspacePath ? { workspacePath: scope.workspacePath } : {}),+ exportedAt: new Date().toISOString(),+ index: scope.hasIndex ? "# Memory\n" : null,+ files: memory.files+ .filter((f) => f.scopeKey === scope.scopeKey)+ .map((f) => ({ name: f.file.name, content: f.content })),+ };+ },+ )+ .post(+ "/api/projects/:projectId/agents/:agentId/memory/scopes/:scopeKey/import",+ (ctx): MemoryImportResponse => ({+ scopeKey: ctx.params.scopeKey!,+ mode: "skip",+ added: [],+ overwritten: [],+ skipped: memoryOf(ctx)+ .files.filter((f) => f.scopeKey === ctx.params.scopeKey)+ .map((f) => f.file.name),+ removed: [],+ indexWritten: false,+ }),+ );++// ---------------------------------------------------------------------------------------------+// Agents and their config+// ---------------------------------------------------------------------------------------------++router+ .get("/api/projects/:projectId/agents", ({ store }): AgentsResponse => ({+ agents: store.f.agents,+ }))+ .post("/api/projects/:projectId/agents", ({ store, body }): unknown => {+ const { agentId, name, description } = record(body);+ const id = str(agentId, `agent-${store.f.agents.length + 1}`);+ if (store.f.agents.some((a) => a.agentId === id))+ fail(409, "agent_exists", "An Agent with that id exists.");+ const agent: AgentsResponse["agents"][number] = {+ agentId: id,+ name: str(name, id),+ ...(typeof description === "string" ? { description } : {}),+ createdAt: new Date().toISOString(),+ activeSessionCount: 0,+ sessionCount: 0,+ sessionActivity: Array.from({ length: 30 }, () => 0),+ toolCount: 4,+ version: 1,+ kernelOutdated: false,+ vaultKeyCount: 0,+ scheduleCount: 0,+ skillCount: 0,+ hookCount: 0,+ pluginUpdates: [],+ memoryCount: 0,+ };+ store.f.agents.push(agent);+ const template = store.f.agentConfigs[IDS.agents.notes]!;+ store.f.agentConfigs[id] = {+ ...template,+ config: { ...template.config, name: agent.name, description: agent.description, version: 1 },+ stateDir: template.stateDir.replace(IDS.agents.notes, id),+ activeSessionCount: 0,+ };+ store.f.installed[id] = { skills: [], hooks: [] };+ store.f.vault[id] = { entries: [] };+ store.f.memory[id] = {+ overview: { ...store.f.memory[IDS.agents.notes]!.overview, scopes: [] },+ files: [],+ };+ return json({ agent } satisfies AgentCreateResponse, 201);+ })+ .get("/api/projects/:projectId/agents/:agentId/config", (ctx): AgentConfigResponse =>+ configOf(ctx),+ )+ .put("/api/projects/:projectId/agents/:agentId/config", (ctx): AgentConfigResponse => {+ const current = configOf(ctx);+ const { agentsMd, config } = record(ctx.body) as {+ agentsMd?: string;+ config?: Record<string, unknown>;+ };+ if (typeof agentsMd === "string") current.agentsMd = agentsMd;+ if (config) {+ const next = { ...current.config } as Record<string, unknown>;+ for (const [key, value] of Object.entries(config)) {+ const previous = next[key];+ next[key] =+ typeof value === "object" &&+ value !== null &&+ !Array.isArray(value) &&+ typeof previous === "object" &&+ previous !== null+ ? { ...(previous as Record<string, unknown>), ...(value as Record<string, unknown>) }+ : value;+ }+ current.config = next as unknown as AgentConfigResponse["config"];+ const agent = agentOf(ctx);+ if (typeof config.name === "string") agent.name = config.name;+ if (typeof config.description === "string") agent.description = config.description;+ agent.updatedAt = new Date().toISOString();+ }+ return current;+ })+ .post(+ "/api/projects/:projectId/agents/:agentId/config/mcp-test",+ ({ body }): McpServerTestResponse => ({+ ok: true,+ tools: [+ `mcp__${str(record(body).name, "server")}__read_file`,+ `mcp__${str(record(body).name, "server")}__list_directory`,+ ],+ latencyMs: 820,+ }),+ )+ .post("/api/projects/:projectId/agents/:agentId/config/reset", (ctx): AgentConfigResponse =>+ configOf(ctx),+ )+ .post(+ "/api/projects/:projectId/agents/:agentId/config/kernel-update",+ (ctx): AgentKernelUpdateResponse => {+ const config = configOf(ctx);+ config.config.kernelOutdated = false;+ config.config.kernelVersion = config.config.kernelLatest;+ agentOf(ctx).kernelOutdated = false;+ return {+ advanced: ["runtime", "tools"],+ kept: ["prompt"],+ kernelVersion: config.config.kernelLatest,+ };+ },+ )+ .delete("/api/projects/:projectId/agents/:agentId", (ctx) => {+ const agent = agentOf(ctx);+ if (agent.agentId === IDS.agents.docs)+ fail(409, "agent_builtin", "The docs Agent is the demo's; it stays.");+ ctx.store.f.agents = ctx.store.f.agents.filter((a) => a.agentId !== agent.agentId);+ return empty();+ });++// ---------------------------------------------------------------------------------------------+// Sessions: the list, directories, creation, the row+// ---------------------------------------------------------------------------------------------++const TEMP_WORKSPACE = /[/\\]workspaces[/\\][^/\\]+$/;+const isTemp = (workspace: string) => workspace === "" || TEMP_WORKSPACE.test(workspace);++function categoryOf(row: SessionInfo): SessionCategory {+ if (row.archived) return "archived";+ return row.source ?? "active";+}++function countsOf(rows: readonly SessionInfo[]): SessionCategoryCounts {+ const counts: SessionCategoryCounts = {+ active: 0,+ schedule: 0,+ subagent: 0,+ benchmark: 0,+ archived: 0,+ };+ for (const row of rows) counts[categoryOf(row)] += 1;+ return counts;+}++router+ .get("/api/projects/:projectId/agents/:agentId/sessions", (ctx): unknown => {+ const { store, params, query } = ctx;+ const all = store.f.sessions+ .filter((s) => s.agentId === params.agentId)+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0));+ const category = query.get("category") as SessionCategory | null;+ const group = query.get("workspaceGroup");+ let rows = category ? all.filter((s) => categoryOf(s) === category) : all;+ if (group !== null) {+ rows = rows.filter((s) => (group === "temp" ? isTemp(s.workspace) : s.workspace === group));+ }+ const limit = Number(query.get("limit"));+ const offset = Number(query.get("offset")) || 0;+ const page = Number.isFinite(limit) && limit > 0 ? rows.slice(offset, offset + limit) : rows;+ const response: { sessions: SessionInfo[] } & Partial<+ Pick<+ import("@prismshadow/penguin-server/api").SessionsResponse,+ "counts" | "workspaceCounts" | "workspaceLatest"+ >+ > = { sessions: page };+ if (query.get("counts") === "1") {+ response.counts = countsOf(all);+ const byWorkspace: Record<string, SessionInfo[]> = {};+ for (const row of all) (byWorkspace[row.workspace] ??= []).push(row);+ response.workspaceCounts = Object.fromEntries(+ Object.entries(byWorkspace).map(([path, list]) => [path, countsOf(list)]),+ );+ response.workspaceLatest = Object.fromEntries(+ Object.entries(byWorkspace).map(([path, list]) => [path, list[0]!.createdAt]),+ );+ }+ return response;+ })+ .get("/api/projects/:projectId/dirs", ({ store, query }): DirListResponse => {+ const path = query.get("path") || "/home/demo";+ return store.f.dirs[path] ?? { path, parent: "/home/demo", entries: [] };+ })+ .get("/api/projects/:projectId/machines/:machineId/dirs", ({ store, query }): DirListResponse => {+ const path = query.get("path") || "/home/demo";+ return store.f.dirs[path] ?? { path, parent: "/home/demo", entries: [] };+ })+ // Only the desktop app's own window may ask macOS for a folder, and the gallery is not one.+ .post("/api/projects/:projectId/dirs/access", () =>+ fail(+ 403,+ "desktop_shell_only",+ "Asking macOS for a folder is available from the desktop app's own window.",+ ),+ )+ .get("/api/projects/:projectId/dir-skills", ({ query }): DirectorySkillsResponse => ({+ path: query.get("path") ?? "",+ skills: [],+ }))+ .post("/api/projects/:projectId/agents/:agentId/sessions", (ctx): unknown => {+ const agent = agentOf(ctx);+ const body = record(ctx.body) as Partial<SessionInfo>;+ const session = ctx.store.createSession(agent.agentId, body);+ return json({ session } satisfies SessionCreateResponse, 201);+ })+ .post("/api/sessions/:sessionId/fork", ({ store, params }): unknown => {+ const source = store.session(params.sessionId!);+ if (!source) notFound("Session");+ const session = store.createSession(source.agentId, {+ ...(source.title ? { title: `${source.title} (fork)` } : {}),+ workspace: source.workspace,+ });+ return json({ session } satisfies SessionForkResponse, 201);+ })+ .get("/api/sessions/:sessionId", ({ store, params }): SessionResponse => {+ const session = store.session(params.sessionId!);+ if (!session) notFound("Session");+ return {+ session: {+ ...session,+ tracePath: `/home/demo/.penguin/data/traces/${session.sessionId}/001.jsonl`,+ },+ };+ })+ .patch("/api/sessions/:sessionId", ({ store, params, body }): SessionResponse => {+ const session = store.patchSession(params.sessionId!, record(body) as Partial<SessionInfo>);+ if (!session) notFound("Session");+ return { session };+ })+ .delete("/api/sessions/:sessionId", ({ store, params }) => {+ if (!store.deleteSession(params.sessionId!)) notFound("Session");+ return empty();+ });++// ---------------------------------------------------------------------------------------------+// Messaging bindings: nothing bound in the demo; every write needs a platform behind it+// ---------------------------------------------------------------------------------------------++router.get("/api/sessions/:sessionId/messaging", (): MessagingBindingsResponse => ({+ bindings: [],+}));+for (const channel of ["feishu", "telegram", "qq", "wechat"]) {+ router+ .put(`/api/sessions/:sessionId/messaging/${channel}`, () =>+ readOnly("save a messaging binding"),+ )+ .post(`/api/sessions/:sessionId/messaging/${channel}/test`, () =>+ readOnly("test a messaging binding"),+ );+}+router+ .post("/api/sessions/:sessionId/messaging/:channel/state", () =>+ readOnly("connect a messaging channel"),+ )+ .post("/api/sessions/:sessionId/messaging/:channel/test-message", () =>+ readOnly("send a test message"),+ )+ .post("/api/sessions/:sessionId/messaging/qq/scan", () => readOnly("start a QQ scan"))+ .post("/api/sessions/:sessionId/messaging/qq/scan/poll", () => readOnly("poll a QQ scan"))+ .post("/api/sessions/:sessionId/messaging/qq/scan/cancel", () => empty())+ .post("/api/sessions/:sessionId/messaging/wechat/scan", () => readOnly("start a WeChat scan"))+ .post("/api/sessions/:sessionId/messaging/wechat/scan/poll", () => readOnly("poll a WeChat scan"))+ .post("/api/sessions/:sessionId/messaging/wechat/scan/verify", () => empty())+ .post("/api/sessions/:sessionId/messaging/wechat/scan/cancel", () => empty());++// ---------------------------------------------------------------------------------------------+// Messages, tasks, approvals, the run+// ---------------------------------------------------------------------------------------------++const transcriptOf = ({ store, params }: Ctx) => {+ const transcript = store.transcript(params.sessionId!);+ if (!transcript) notFound("Session");+ return transcript;+};++router+ .get("/api/sessions/:sessionId/messages", (ctx): MessagesResponse => {+ const transcript = transcriptOf(ctx);+ const live = ctx.store.liveTail(ctx.params.sessionId!);+ const windowed = ctx.query.has("tailLimit") || ctx.query.has("before");+ const before = ctx.query.get("before");+ const messages = before === null ? transcript.history : [];+ return {+ messages,+ ...(live && before === null ? { live } : {}),+ ...(windowed+ ? {+ page: {+ earlierTurns: 0,+ prior: {+ subagentTokens: 0,+ elapsedMs: 0,+ apiMs: 0,+ toolMs: 0,+ sessionTokens: 0,+ contextTokens: 0,+ },+ },+ }+ : {}),+ };+ })+ .post("/api/sessions/:sessionId/tasks", ({ store, params, body }): unknown => {+ const sessionId = params.sessionId!;+ const row = store.session(sessionId);+ if (!row) notFound("Session");+ const input = record(body).input;+ const text = Array.isArray(input)+ ? input+ .map((part) =>+ typeof part === "object" && part !== null && "text" in part+ ? str((part as { text: unknown }).text)+ : "",+ )+ .filter((t) => t !== "")+ .join("\n")+ : "";+ if (row.status !== "idle") {+ if (record(body).queueIfBusy === true) {+ row.pendingFollowUpCount += 1;+ return json({ sessionId, queued: true } satisfies TaskCreateResponse, 202);+ }+ fail(409, "session_busy", "A Task is already running.");+ }+ store.startTask(sessionId, text || "…");+ return json({ sessionId } satisfies TaskCreateResponse, 202);+ })+ .get("/api/sessions/:sessionId/goal", (): GoalResponse => ({ goal: null }))+ .post("/api/sessions/:sessionId/approvals/:toolCallId", ({ store, params, body }) => {+ const decision = record(body).decision === "deny" ? "deny" : "allow";+ if (!store.decide(params.sessionId!, params.toolCallId!, decision)) {+ fail(404, "approval_not_found", "No approval is pending for that call.");+ }+ return empty();+ })+ .post("/api/sessions/:sessionId/tool-calls/:toolCallId/background", ({ store, params }) => {+ if (!store.detachToolCall(params.sessionId!, params.toolCallId!)) {+ fail(404, "tool_call_not_found", "That call is not executing.");+ }+ return empty();+ })+ .post("/api/sessions/:sessionId/abort", ({ store, params }) => {+ store.abort(params.sessionId!);+ return empty();+ })+ .post("/api/sessions/:sessionId/retry-now", (): RetryNowResponse => ({ skipped: false }))+ .get("/api/sessions/:sessionId/processes", ({ store, params }): SessionProcessesResponse => {+ const row = store.session(params.sessionId!);+ return {+ processes: row?.backgroundTasks?.processes+ ? [+ {+ processId: "proc-links",+ pid: 48_112,+ cmd: "node scripts/check-links.mjs --all",+ cwd: IDS.workspace,+ startedAt: row.lastActiveAt,+ running: true,+ },+ ]+ : [],+ };+ })+ .post("/api/sessions/:sessionId/processes/:processId/kill", ({ store, params }) => {+ const row = store.session(params.sessionId!);+ if (row) delete row.backgroundTasks;+ return empty();+ })+ .delete("/api/sessions/:sessionId/processes/:processId", () => empty())+ .post("/api/sessions/:sessionId/steer", ({ store, params }) => {+ const row = store.session(params.sessionId!);+ if (!row || row.status === "idle") fail(409, "not_running", "No Task is running.");+ return empty(202);+ })+ .post(+ "/api/sessions/:sessionId/subagents/:childSessionId/message",+ (): SubagentMessageResponse => ({+ outcome: "steered",+ }),+ )+ .post("/api/sessions/:sessionId/subagents/:childSessionId/abort", () => empty())+ .delete("/api/sessions/:sessionId/steer/:steerId", () =>+ fail(409, "not_pending", "Already delivered."),+ )+ .delete("/api/sessions/:sessionId/follow-ups/:followUpId", () =>+ fail(409, "follow_up_started", "Already started."),+ )+ .post("/api/sessions/:sessionId/compact", ({ store, params }): unknown => {+ const sessionId = params.sessionId!;+ if (!store.session(sessionId)) notFound("Session");+ return json({ sessionId } satisfies TaskCreateResponse, 202);+ })+ .get("/api/sessions/:sessionId/context", ({ store }): SessionContextResponse => store.f.context);++// ---------------------------------------------------------------------------------------------+// Traces+// ---------------------------------------------------------------------------------------------++/** What the server derives from a Trace file, derived here from the transcript the same way. */+function analyze(history: readonly OmniMessage[]): TraceAnalysisResponse {+ const ms = (m: OmniMessage) => Date.parse(m.timestamp);+ const requests: TraceAnalysisResponse["requests"] = [];+ const tasks: TraceAnalysisResponse["tasks"] = [];+ const toolCalls: TraceAnalysisResponse["toolCalls"] = [];+ const modelSegments: TraceAnalysisResponse["modelSegments"] = [];+ const toolSpans: TraceAnalysisResponse["toolSpans"] = [];+ const usageTrend: TraceAnalysisResponse["usageTrend"] = [];+ let taskIndex = -1;+ let openRequest: (typeof requests)[number] | null = null;+ let previous: OmniMessage | null = null;+ const calls = new Map<string, { index: number; span: (typeof toolSpans)[number] }>();+ history.forEach((message, i) => {+ const p = payloadOf(message);+ if (p === null) {+ // The session_meta record opens the file: it belongs to no turn and times nothing.+ previous = message;+ return;+ }+ if (p.type === "text" && p.role === "user") {+ taskIndex += 1;+ tasks.push({+ taskIndex,+ messageFrom: i,+ messageTo: i,+ startTs: "",+ endTs: message.timestamp,+ tokens: { cacheRead: 0, cacheWrite: 0, output: 0 },+ llmMs: 0,+ toolMs: 0,+ });+ }+ const task = tasks[tasks.length - 1];+ if (task) {+ task.messageTo = i;+ task.endTs = message.timestamp;+ }+ if (p.type === "request_begin") {+ openRequest = { beginTs: message.timestamp, taskIndex: Math.max(taskIndex, 0) };+ requests.push(openRequest);+ if (task && task.startTs === "") task.startTs = message.timestamp;+ } else if (p.type === "request_end" && openRequest) {+ const duration = ms(message) - Date.parse(openRequest.beginTs);+ openRequest.endTs = message.timestamp;+ openRequest.durationMs = duration;+ openRequest.activeMs = duration;+ openRequest.status = p.status;+ if (task) task.llmMs += duration;+ openRequest = null;+ } else if (+ p.type === "thinking" ||+ (p.type === "text" && p.role === "assistant") ||+ p.type === "tool_call"+ ) {+ const kind = p.type === "thinking" ? "thinking" : p.type === "text" ? "text" : "tool_call";+ modelSegments.push({+ kind,+ startTs: previous ? previous.timestamp : message.timestamp,+ endTs: message.timestamp,+ taskIndex: Math.max(taskIndex, 0),+ ...(p.type === "tool_call" ? { toolCallId: p.tool_call_id, name: p.name } : {}),+ });+ if (p.type === "tool_call") {+ const span = {+ toolCallId: p.tool_call_id,+ name: p.name,+ callTs: message.timestamp,+ taskIndex: Math.max(taskIndex, 0),+ };+ toolSpans.push(span);+ calls.set(p.tool_call_id, { index: toolCalls.length, span });+ toolCalls.push({ toolCallId: p.tool_call_id, name: p.name, startTs: message.timestamp });+ }+ } else if (p.type === "tool_call_output") {+ const call = calls.get(p.tool_call_id);+ if (call) {+ const started = Date.parse(call.span.callTs);+ call.span.outputTs = message.timestamp;+ call.span.stopReason = p.stop_reason ?? "completed";+ const entry = toolCalls[call.index]!;+ entry.endTs = message.timestamp;+ entry.durationMs = ms(message) - started;+ entry.stopReason = p.stop_reason ?? "completed";+ if (task) task.toolMs += ms(message) - started;+ }+ } else if (p.type === "approval_decision") {+ const call = calls.get(p.tool_call_id);+ if (call) {+ call.span.approvalTs = message.timestamp;+ call.span.decision = p.decision;+ }+ } else if (p.type === "token_usage") {+ usageTrend.push({+ ts: message.timestamp,+ requestTotal: p.request.total,+ sessionTotal: p.session.total,+ });+ if (task) {+ task.tokens = {+ cacheRead: p.request.cache_read,+ cacheWrite: p.request.cache_write,+ output: p.request.output,+ };+ task.context = { ...task.tokens };+ task.cost = costOf({ ...task.tokens, provider: "deepseek" });+ }+ }+ previous = message;+ });+ const elapsedMs = tasks.reduce(+ (sum, t) => sum + (t.startTs ? Math.max(0, Date.parse(t.endTs) - Date.parse(t.startTs)) : 0),+ 0,+ );+ return {+ elapsedMs,+ apiMs: tasks.reduce((sum, t) => sum + t.llmMs, 0),+ toolMs: tasks.reduce((sum, t) => sum + t.toolMs, 0),+ cost: tasks.reduce((sum, t) => sum + (t.cost ?? 0), 0),+ requests,+ tasks,+ toolCalls,+ modelSegments,+ toolSpans,+ otherSpans: [],+ reconnectCount: 0,+ compactionCount: 0,+ usageTrend,+ };+}++const traceFile = (ctx: Ctx, sessionId: string) => {+ const transcript = ctx.store.transcript(sessionId);+ const row = ctx.store.session(sessionId);+ if (!transcript || !row) notFound("Trace");+ return { transcript, row };+};++const traceEvents = (ctx: Ctx, sessionId: string): TraceEventsResponse => {+ const { transcript } = traceFile(ctx, sessionId);+ const offset = Number(ctx.query.get("offset")) || 0;+ const limit = Number(ctx.query.get("limit")) || 200;+ return {+ events: transcript.history.slice(offset, offset + limit),+ offset,+ limit,+ total: transcript.history.length,+ };+};++const traceJsonl = (ctx: Ctx, sessionId: string) =>+ raw(+ traceFile(ctx, sessionId)+ .transcript.history.map((m) => JSON.stringify(m))+ .join("\n"),+ {+ "content-type": "application/x-ndjson",+ "content-disposition": `attachment; filename="${sessionId}-001.jsonl"`,+ },+ );++router+ .get("/api/sessions/:sessionId/traces", (ctx): SessionTracesResponse => {+ const { transcript, row } = traceFile(ctx, ctx.params.sessionId!);+ return {+ files: [+ {+ index: 1,+ date: dayKey(Date.parse(row.createdAt)),+ sizeBytes: JSON.stringify(transcript.history).length,+ mtime: row.lastActiveAt,+ },+ ],+ };+ })+ .get("/api/sessions/:sessionId/traces/:index", (ctx) => traceEvents(ctx, ctx.params.sessionId!))+ .get("/api/sessions/:sessionId/traces/:index/analysis", (ctx): TraceAnalysisResponse =>+ analyze(traceFile(ctx, ctx.params.sessionId!).transcript.history),+ )+ .get("/api/projects/:projectId/agents/:agentId/traces/:sessionId/:index", (ctx) =>+ traceEvents(ctx, ctx.params.sessionId!),+ )+ .get(+ "/api/projects/:projectId/agents/:agentId/traces/:sessionId/:index/analysis",+ (ctx): TraceAnalysisResponse =>+ analyze(traceFile(ctx, ctx.params.sessionId!).transcript.history),+ )+ .get("/api/projects/:projectId/agents/:agentId/traces/:sessionId/:index/download", (ctx) =>+ traceJsonl(ctx, ctx.params.sessionId!),+ )+ .post("/api/projects/:projectId/agents/:agentId/traces/import", (): unknown =>+ json(+ { sessionId: "s-imported", index: 1, date: dayKey(Date.now()) } satisfies TraceImportResponse,+ 201,+ ),+ );++// ---------------------------------------------------------------------------------------------+// Usage+// ---------------------------------------------------------------------------------------------++function filterUsage(store: DemoStore, query: URLSearchParams, withModel: boolean): UsageDay[] {+ const from = query.get("from");+ const to = query.get("to");+ const agentId = query.get("agentId");+ const provider = query.get("provider");+ const modelId = query.get("modelId");+ return store.f.usage.filter(+ (day) =>+ (!from || day.date >= from) &&+ (!to || day.date <= to) &&+ (!agentId || day.agentId === agentId) &&+ (!withModel || !provider || (day.provider === provider && day.modelId === modelId)),+ );+}++const bucket = (day: UsageDay[]): UsageResponse["summary"]["today"] => ({+ total: day.reduce((s, d) => s + d.cacheRead + d.cacheWrite + d.output, 0),+ requests: day.reduce((s, d) => s + d.requests, 0),+ cost: day.reduce((s, d) => s + costOf(d), 0),+ hasUncosted: false,+});++/** The series bucket a day falls in at a granularity: the day, its ISO week's Monday, or its month. */+function bucketKey(date: string, granularity: UsageGranularity): string {+ if (granularity === "month") return date.slice(0, 7);+ if (granularity === "week") {+ const d = new Date(`${date}T00:00:00Z`);+ const weekday = (d.getUTCDay() + 6) % 7;+ d.setUTCDate(d.getUTCDate() - weekday);+ return d.toISOString().slice(0, 10);+ }+ return date;+}++router+ .get("/api/projects/:projectId/usage/errors", ({ store, query }): UsageErrorsPage => {+ const kind = query.get("kind");+ const items = store.f.usageErrors.filter((e) => !kind || e.kind === kind);+ const offset = Number(query.get("offset")) || 0;+ const limit = Number(query.get("limit")) || items.length;+ return { items: items.slice(offset, offset + limit), total: items.length };+ })+ .delete("/api/projects/:projectId/usage/errors", ({ store }): UsageErrorsClearResponse => {+ const deleted = store.f.usageErrors.length;+ store.f.usageErrors = [];+ return { deleted };+ })+ .get("/api/projects/:projectId/usage/model-totals", ({ store }): UsageModelTotals => {+ const totals = new Map<string, UsageModelTotals["totals"][number]>();+ for (const day of store.f.usage) {+ const key = `${day.provider}/${day.modelId}`;+ const entry = totals.get(key) ?? {+ provider: day.provider,+ modelId: day.modelId,+ tokens: 0,+ requests: 0,+ };+ entry.tokens += day.cacheRead + day.cacheWrite + day.output;+ entry.requests += day.requests;+ totals.set(key, entry);+ }+ return { totals: [...totals.values()] };+ })+ .get("/api/projects/:projectId/usage", ({ store, query }): UsageResponse => {+ const groupBy = (query.get("groupBy") ?? "date") as UsageGroupBy;+ const granularity = (query.get("granularity") ?? "day") as UsageGranularity;+ const days = filterUsage(store, query, true);+ const today = dayKey(store.f.now);+ const weekAgo = dayKey(store.f.now - 7 * 86_400_000);+ const keyOf = (d: UsageDay) =>+ groupBy === "date"+ ? d.date+ : groupBy === "agent"+ ? d.agentId+ : groupBy === "model"+ ? d.modelId+ : d.sessionId;+ const groups = new Map<string, UsageResponse["groups"][number]>();+ for (const d of days) {+ const key = keyOf(d);+ const row = groups.get(key) ?? {+ key,+ ...(groupBy === "model" ? { provider: d.provider } : {}),+ cacheRead: 0,+ cacheWrite: 0,+ output: 0,+ total: 0,+ requests: 0,+ cost: 0,+ hasUncosted: false,+ };+ row.cacheRead += d.cacheRead;+ row.cacheWrite += d.cacheWrite;+ row.output += d.output;+ row.total += d.cacheRead + d.cacheWrite + d.output;+ row.requests += d.requests;+ row.cost = (row.cost ?? 0) + costOf(d);+ groups.set(key, row);+ }+ const buckets = new Map<string, UsageResponse["series"][number]>();+ const dates = [...new Set(days.map((d) => d.date))].sort();+ for (const date of dates) {+ const key = bucketKey(date, granularity);+ if (!buckets.has(key)) {+ buckets.set(key, {+ bucket: key,+ cacheRead: 0,+ cacheWrite: 0,+ output: 0,+ total: 0,+ cost: 0,+ requests: 0,+ completed: 0,+ denominator: 0,+ });+ }+ }+ const perAgent = new Map<string, UsageResponse["byAgentSeries"][number]>();+ const perModel = new Map<string, UsageResponse["byModelSeries"][number]>();+ const keys = [...buckets.keys()];+ const zeros = () => keys.map(() => 0);+ for (const d of days) {+ const key = bucketKey(d.date, granularity);+ const point = buckets.get(key)!;+ point.cacheRead += d.cacheRead;+ point.cacheWrite += d.cacheWrite;+ point.output += d.output;+ point.total += d.cacheRead + d.cacheWrite + d.output;+ point.cost = (point.cost ?? 0) + costOf(d);+ point.requests += d.requests;+ point.completed += d.completed;+ point.denominator += d.requests - d.aborted;+ const index = keys.indexOf(key);+ const agent = perAgent.get(d.agentId) ?? {+ agentId: d.agentId,+ requests: zeros(),+ completed: zeros(),+ denominator: zeros(),+ };+ agent.requests[index]! += d.requests;+ agent.completed[index]! += d.completed;+ agent.denominator[index]! += d.requests - d.aborted;+ perAgent.set(d.agentId, agent);+ const modelKey = `${d.provider}/${d.modelId}`;+ const model = perModel.get(modelKey) ?? {+ provider: d.provider,+ modelId: d.modelId,+ requests: zeros(),+ completed: zeros(),+ denominator: zeros(),+ };+ model.requests[index]! += d.requests;+ model.completed[index]! += d.completed;+ model.denominator[index]! += d.requests - d.aborted;+ perModel.set(modelKey, model);+ }+ const unexpected = store.f.usageErrors.filter((e) => e.kind === "unexpected").length;+ return {+ summary: {+ today: bucket(store.f.usage.filter((d) => d.date === today)),+ last7d: bucket(store.f.usage.filter((d) => d.date >= weekAgo)),+ total: bucket(store.f.usage),+ },+ groupBy,+ groups: [...groups.values()],+ granularity,+ series: keys.map((key) => buckets.get(key)!),+ byAgentSeries: [...perAgent.values()],+ byModelSeries: [...perModel.values()],+ errors: {+ total: store.f.usageErrors.length,+ unexpected,+ topCode: store.f.usageErrors[0]+ ? {+ source: store.f.usageErrors[0].source,+ code: store.f.usageErrors[0].code,+ kind: store.f.usageErrors[0].kind,+ count: 1,+ }+ : null,+ recent: store.f.usageErrors,+ },+ agentIds: [...new Set(store.f.usage.map((d) => d.agentId))],+ models: [...perModel.values()].map(({ provider, modelId }) => ({ provider, modelId })),+ };+ });++// ---------------------------------------------------------------------------------------------+// Workspace files+// ---------------------------------------------------------------------------------------------++const normalizePath = (path: string) => path.replace(/^\.?\/+/, "").replace(/\/+$/, "");++router+ .get("/api/sessions/:sessionId/files", ({ store, query }): WorkspaceFilesResponse => {+ const path = normalizePath(query.get("path") ?? "");+ const entries = store.f.workspace.entries[path];+ if (!entries) notFound("Directory");+ return { path, entries };+ })+ .get("/api/sessions/:sessionId/files/content", ({ store, query }) => {+ const path = normalizePath(query.get("path") ?? "");+ const content = store.f.workspace.content[path];+ if (content === undefined) notFound("File");+ const name = path.slice(path.lastIndexOf("/") + 1);+ return raw(content, {+ "content-type": path.endsWith(".json") ? "application/json" : "text/plain; charset=utf-8",+ etag: `"${content.length}-${path.length}"`,+ ...(query.get("download") === "1"+ ? { "content-disposition": `attachment; filename="${name}"` }+ : {}),+ });+ })+ .put("/api/sessions/:sessionId/files/content", ({ store, query, body }) => {+ const path = normalizePath(query.get("path") ?? "");+ const data = str(record(body).dataBase64);+ try {+ store.f.workspace.content[path] = decodeURIComponent(escape(atob(data)));+ } catch {+ store.f.workspace.content[path] = "";+ }+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";+ const name = path.slice(path.lastIndexOf("/") + 1);+ const entries = (store.f.workspace.entries[dir] ??= []);+ const size = store.f.workspace.content[path]!.length;+ const existing = entries.find((e) => e.name === name);+ if (existing) {+ existing.sizeBytes = size;+ existing.mtime = new Date().toISOString();+ } else entries.push({ name, kind: "file", sizeBytes: size, mtime: new Date().toISOString() });+ return empty();+ })+ .delete("/api/sessions/:sessionId/files/content", ({ store, query }) => {+ const path = normalizePath(query.get("path") ?? "");+ delete store.f.workspace.content[path];+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";+ const name = path.slice(path.lastIndexOf("/") + 1);+ store.f.workspace.entries[dir] = (store.f.workspace.entries[dir] ?? []).filter(+ (e) => e.name !== name,+ );+ return empty();+ })+ .post("/api/sessions/:sessionId/files/reveal", () =>+ fail(404, "not_desktop", "Only the desktop shell can reveal a file."),+ )+ // The separate preview origin has no counterpart here: the file is served as the page itself.+ .get("/api/sessions/:sessionId/files/preview-redirect", ({ store, query }) => {+ const path = normalizePath(query.get("path") ?? "");+ const content = store.f.workspace.content[path];+ if (content === undefined) notFound("File");+ return raw(content, {+ "content-type": path.endsWith(".html")+ ? "text/html; charset=utf-8"+ : "text/plain; charset=utf-8",+ });+ })+ .post("/api/sessions/:sessionId/files/move", ({ store, body }) => {+ const { from, to } = record(body);+ const source = normalizePath(str(from));+ const target = normalizePath(str(to));+ const content = store.f.workspace.content[source];+ if (content === undefined) notFound("File");+ if (store.f.workspace.content[target] !== undefined)+ fail(409, "target_exists", "The destination exists.");+ delete store.f.workspace.content[source];+ store.f.workspace.content[target] = content;+ const move = (path: string, remove: boolean) => {+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";+ const name = path.slice(path.lastIndexOf("/") + 1);+ const entries = (store.f.workspace.entries[dir] ??= []);+ if (remove) store.f.workspace.entries[dir] = entries.filter((e) => e.name !== name);+ else+ entries.push({+ name,+ kind: "file",+ sizeBytes: content.length,+ mtime: new Date().toISOString(),+ });+ };+ move(source, true);+ move(target, false);+ return empty();+ })+ .get("/api/sessions/:sessionId/files/search", ({ store, query }): WorkspaceSearchResponse => {+ const q = (query.get("q") ?? "").toLowerCase();+ if (q === "") fail(400, "empty_query", "Nothing to search for.");+ const hits: WorkspaceSearchResponse["hits"] = [];+ for (const [dir, entries] of Object.entries(store.f.workspace.entries)) {+ for (const entry of entries) {+ if (entry.name.toLowerCase().includes(q)) {+ hits.push({+ path: dir ? `${dir}/${entry.name}` : entry.name,+ kind: entry.kind,+ sizeBytes: entry.sizeBytes,+ mtime: entry.mtime,+ });+ }+ }+ }+ return { hits, truncated: false };+ })+ .post("/api/sessions/:sessionId/files/stat", ({ store, body }): FilesStatResponse => {+ const paths = record(body).paths;+ return {+ existing: Array.isArray(paths)+ ? paths.filter(+ (p): p is string =>+ typeof p === "string" && store.f.workspace.content[normalizePath(p)] !== undefined,+ )+ : [],+ };+ });++// ---------------------------------------------------------------------------------------------+// Schedules+// ---------------------------------------------------------------------------------------------++const withoutAgent = (item: ProjectSchedulesResponse["schedules"][number]): ScheduleItem => {+ const { agentId, ...rest } = item;+ void agentId;+ return rest;+};++router+ .get("/api/projects/:projectId/agents/:agentId/schedules", (ctx): SchedulesResponse => ({+ schedules: ctx.store.f.schedules+ .filter((s) => s.agentId === agentOf(ctx).agentId)+ .map(withoutAgent),+ invalidFiles: [],+ }))+ .get("/api/projects/:projectId/schedules", ({ store }): ProjectSchedulesResponse => ({+ schedules: store.f.schedules,+ invalidFiles: [],+ }))+ .post("/api/projects/:projectId/agents/:agentId/schedules", (ctx): unknown => {+ const agent = agentOf(ctx);+ const body = record(ctx.body);+ const name = str(body.name, `task-${ctx.store.f.schedules.length + 1}`);+ if (ctx.store.f.schedules.some((s) => s.agentId === agent.agentId && s.name === name)) {+ fail(409, "schedule_exists", "A task with that name exists.");+ }+ const item: ProjectSchedulesResponse["schedules"][number] = {+ agentId: agent.agentId,+ name,+ prompt: str(body.prompt),+ enabled: body.enabled !== false,+ startAt: str(body.startAt, new Date().toISOString()),+ ...(typeof body.period === "string" ? { period: body.period } : {}),+ ...(typeof body.endAt === "string" ? { endAt: body.endAt } : {}),+ ...(typeof body.sessionId === "string" ? { sessionId: body.sessionId } : {}),+ ...(typeof body.workspace === "string" ? { workspace: body.workspace } : {}),+ ...(typeof body.modelId === "string" && typeof body.provider === "string"+ ? { modelId: body.modelId, provider: body.provider }+ : {}),+ status: body.enabled === false ? "disabled" : "active",+ nextFireAt: str(body.startAt, new Date(Date.now() + 3_600_000).toISOString()),+ queued: false,+ creatorUserId: ctx.store.f.user.userId,+ };+ ctx.store.f.schedules.push(item);+ agent.scheduleCount += 1;+ return json(withoutAgent(item), 201);+ })+ .put("/api/projects/:projectId/agents/:agentId/schedules/:name", (ctx): ScheduleItem => {+ const agent = agentOf(ctx);+ const item = ctx.store.f.schedules.find(+ (s) => s.agentId === agent.agentId && s.name === ctx.params.name,+ );+ if (!item) notFound("Scheduled task");+ const body = record(ctx.body);+ Object.assign(item, body);+ item.status = item.enabled ? "active" : "disabled";+ if (item.enabled)+ item.nextFireAt = item.nextFireAt ?? new Date(Date.now() + 3_600_000).toISOString();+ else delete item.nextFireAt;+ return withoutAgent(item);+ })+ .delete("/api/projects/:projectId/agents/:agentId/schedules/:name", (ctx) => {+ const agent = agentOf(ctx);+ const before = ctx.store.f.schedules.length;+ ctx.store.f.schedules = ctx.store.f.schedules.filter(+ (s) => !(s.agentId === agent.agentId && s.name === ctx.params.name),+ );+ if (ctx.store.f.schedules.length === before) notFound("Scheduled task");+ agent.scheduleCount = Math.max(0, agent.scheduleCount - 1);+ return empty();+ });++// ---------------------------------------------------------------------------------------------+// Plugins, skills and hooks+// ---------------------------------------------------------------------------------------------++const installedOf = (ctx: Ctx) => {+ const agent = agentOf(ctx);+ return (ctx.store.f.installed[agent.agentId] ??= { skills: [], hooks: [] });+};++const libraryPlugins = (store: DemoStore) => store.f.library.groups.flatMap((g) => g.plugins);++router+ .get("/api/plugins", ({ store }): PluginLibraryResponse => store.f.library)+ .get("/api/plugins/registry", ({ store }): PluginIndexResponse => store.f.pluginIndex)+ .get("/api/plugins/registry/readme", ({ store, query }): PluginReadmeResponse => {+ const name = query.get("name") ?? "";+ return { name, readme: store.f.readmes[name] ?? null };+ })+ .get("/api/plugins/:plugin/files", ({ store, params }): PluginFilesResponse => {+ const files = store.f.pluginFiles[params.plugin!];+ if (!files) {+ if (!libraryPlugins(store).some((p) => p.name === params.plugin)) notFound("Plugin");+ return { files: {} };+ }+ return { files };+ })+ .post("/api/projects/:projectId/agents/:agentId/plugins", (ctx): unknown => {+ const installed = installedOf(ctx);+ const agent = agentOf(ctx);+ const names = record(ctx.body).names;+ const wanted = Array.isArray(names)+ ? names.filter((n): n is string => typeof n === "string")+ : [];+ for (const name of wanted) {+ const plugin = libraryPlugins(ctx.store).find((p) => p.name === name);+ if (!plugin) fail(404, "unknown_plugin", `No plugin named ${name}.`);+ for (const skill of plugin.skills) {+ installed.skills = installed.skills.filter((s) => s.name !== skill.name);+ installed.skills.push({ ...skill });+ }+ if (plugin.hooks.length > 0) {+ installed.hooks = installed.hooks.filter((h) => h.name !== plugin.name);+ installed.hooks.push({+ name: plugin.name,+ description: plugin.description,+ ...(plugin.descriptionZh ? { descriptionZh: plugin.descriptionZh } : {}),+ version: plugin.version,+ events: [...plugin.hooks],+ });+ }+ agent.pluginUpdates = agent.pluginUpdates.filter((u) => u.name !== name);+ }+ agent.skillCount = installed.skills.length;+ agent.hookCount = installed.hooks.length;+ return json(+ { skills: installed.skills, hooks: installed.hooks } satisfies AgentPluginsInstallResponse,+ 201,+ );+ })+ .get("/api/projects/:projectId/agents/:agentId/skills", (ctx): AgentSkillsResponse => ({+ skills: installedOf(ctx).skills,+ }))+ .get("/api/projects/:projectId/agents/:agentId/hooks", (ctx): AgentHooksResponse => ({+ hooks: installedOf(ctx).hooks,+ }))+ .delete("/api/projects/:projectId/agents/:agentId/hooks/:name", (ctx) => {+ const installed = installedOf(ctx);+ const before = installed.hooks.length;+ installed.hooks = installed.hooks.filter((h) => h.name !== ctx.params.name);+ if (installed.hooks.length === before) notFound("Hook package");+ agentOf(ctx).hookCount = installed.hooks.length;+ return empty();+ })+ .post("/api/projects/:projectId/agents/:agentId/hooks/archive", () =>+ readOnly("install a hook archive"),+ )+ .get("/api/projects/:projectId/agents/:agentId/hooks/:name/archive", ({ params }) =>+ raw("PK\u0003\u0004 demo archive", {+ "content-type": "application/zip",+ "content-disposition": `attachment; filename="${params.name}.zip"`,+ }),+ )+ .post("/api/projects/:projectId/agents/:agentId/skills/archive", () =>+ readOnly("install a skill archive"),+ )+ .get("/api/projects/:projectId/agents/:agentId/skills/:name/archive", ({ params }) =>+ raw("PK\u0003\u0004 demo archive", {+ "content-type": "application/zip",+ "content-disposition": `attachment; filename="${params.name}.zip"`,+ }),+ )+ .delete("/api/projects/:projectId/agents/:agentId/skills/:name", (ctx) => {+ const installed = installedOf(ctx);+ const before = installed.skills.length;+ installed.skills = installed.skills.filter((s) => s.name !== ctx.params.name);+ if (installed.skills.length === before) notFound("Skill");+ agentOf(ctx).skillCount = installed.skills.length;+ return empty();+ });++// ---------------------------------------------------------------------------------------------+// Benchmarks+// ---------------------------------------------------------------------------------------------++const benchmarkOf = ({ store, params }: Ctx) => {+ const benchmark = store.f.benchmarks.find((b) => b.id === params.benchmarkId);+ if (!benchmark) notFound("Benchmark");+ return benchmark;+};++const caseFilesOf = (ctx: Ctx, material: CaseMaterial): Record<string, string> => {+ const benchmark = benchmarkOf(ctx);+ const files = ctx.store.f.caseFiles[`${benchmark.id}/${ctx.params.caseId}`];+ if (!files) notFound("Case");+ return files[material];+};++const listCaseFiles = (ctx: Ctx, material: CaseMaterial): WorkspaceFilesResponse => {+ const files = caseFilesOf(ctx, material);+ const path = normalizePath(ctx.query.get("path") ?? "");+ const seen = new Set<string>();+ const entries: WorkspaceFilesResponse["entries"] = [];+ for (const [filePath, content] of Object.entries(files)) {+ if (path !== "" && !filePath.startsWith(`${path}/`)) continue;+ const rest = path === "" ? filePath : filePath.slice(path.length + 1);+ const name = rest.split("/")[0]!;+ if (seen.has(name)) continue;+ seen.add(name);+ const isDir = rest.includes("/");+ entries.push({+ name,+ kind: isDir ? "dir" : "file",+ sizeBytes: isDir ? 0 : content.length,+ mtime: new Date(ctx.store.f.now).toISOString(),+ });+ }+ return { path, entries };+};++const caseFileContent = (ctx: Ctx, material: CaseMaterial) => {+ const files = caseFilesOf(ctx, material);+ const path = normalizePath(ctx.query.get("path") ?? "");+ const content = files[path];+ if (content === undefined) notFound("File");+ return raw(content, { "content-type": "text/plain; charset=utf-8", etag: `"${content.length}"` });+};++router+ .get("/api/projects/:projectId/benchmarks", ({ store }): BenchmarksResponse => ({+ benchmarks: store.f.benchmarks,+ }))+ .get("/api/projects/:projectId/benchmarks/:benchmarkId/cases", (ctx): BenchmarkCasesResponse => ({+ cases: ctx.store.f.benchmarkCases[benchmarkOf(ctx).id] ?? [],+ }))+ .post("/api/projects/:projectId/benchmarks", ({ store, body }): unknown => {+ const { id, title, description, runs, cases } = record(body);+ const benchmarkId = str(id, `benchmark-${store.f.benchmarks.length + 1}`);+ if (store.f.benchmarks.some((b) => b.id === benchmarkId))+ fail(409, "benchmark_exists", "That id is taken.");+ const list = Array.isArray(cases) ? (cases as Array<Record<string, unknown>>) : [];+ const benchmark: BenchmarksResponse["benchmarks"][number] = {+ id: benchmarkId,+ title: str(title, benchmarkId),+ ...(typeof description === "string" ? { description } : {}),+ runs: typeof runs === "number" ? runs : 1,+ status: "published",+ caseCount: list.length,+ evaluations: [],+ agentIds: [],+ };+ store.f.benchmarks.push(benchmark);+ store.f.benchmarkCases[benchmarkId] = list.map((c) => ({+ id: str(c.id),+ title: str(c.title, str(c.id)),+ }));+ for (const c of list) {+ store.f.caseFiles[`${benchmarkId}/${str(c.id)}`] = {+ statement: { "README.md": `# ${str(c.title)}\n\n${str(c.statement)}\n` },+ rubric: { "README.md": str(c.rubric) },+ };+ }+ return json({ benchmark } satisfies BenchmarkCreateResponse, 201);+ })+ .delete("/api/projects/:projectId/benchmarks/:benchmarkId", (ctx) => {+ const benchmark = benchmarkOf(ctx);+ ctx.store.f.benchmarks = ctx.store.f.benchmarks.filter((b) => b.id !== benchmark.id);+ return empty();+ })+ .get("/api/projects/:projectId/benchmarks/:benchmarkId/cases/:caseId/files", (ctx) =>+ listCaseFiles(ctx, "statement"),+ )+ .get("/api/projects/:projectId/benchmarks/:benchmarkId/cases/:caseId/rubric/files", (ctx) =>+ listCaseFiles(ctx, "rubric"),+ )+ .get("/api/projects/:projectId/benchmarks/:benchmarkId/cases/:caseId/files/content", (ctx) =>+ caseFileContent(ctx, "statement"),+ )+ .get(+ "/api/projects/:projectId/benchmarks/:benchmarkId/cases/:caseId/rubric/files/content",+ (ctx) => caseFileContent(ctx, "rubric"),+ );++// ---------------------------------------------------------------------------------------------+// Agent State export / import+// ---------------------------------------------------------------------------------------------++router+ .get("/api/projects/:projectId/agents/:agentId/export", ({ params }) =>+ raw("\u001f\u008b demo snapshot", {+ "content-type": "application/gzip",+ "content-disposition": `attachment; filename="${params.agentId}.tar.gz"`,+ }),+ )+ .post("/api/projects/:projectId/agents/:agentId/import", () => readOnly("import a snapshot"));++// ---------------------------------------------------------------------------------------------+// Machines (admin)+// ---------------------------------------------------------------------------------------------++const machinesResponse = (store: DemoStore): MachinesResponse => store.f.machines;++router+ .get("/api/projects/:projectId/machines", ({ store }) => machinesResponse(store))+ .post("/api/projects/:projectId/machines/probe", ({ store }) => {+ const checkedAt = new Date().toISOString();+ for (const machine of store.f.machines.machines) {+ if (machine.status) machine.status = { ...machine.status, checkedAt };+ }+ return machinesResponse(store);+ })+ .post("/api/projects/:projectId/machines/use", ({ store, body }): unknown => {+ const ids = record(body).machines;+ const refused: MachinesUseResponse["refused"] = Array.isArray(ids)+ ? ids+ .filter((id): id is string => typeof id === "string")+ .map((machineId) => ({ machineId, why: "no-image" as const }))+ : [];+ return json({ ...machinesResponse(store), refused } satisfies MachinesUseResponse, 202);+ })+ .post("/api/projects/:projectId/machines/ssh-hosts", ({ store, body }): unknown => {+ const { alias, hostName } = record(body);+ const name = str(alias, "new-host");+ if (store.f.machines.machines.some((m) => m.alias === name))+ fail(409, "ssh_host_exists", "That alias exists.");+ store.f.machines.machines.push({+ id: `ssh:${name}`,+ alias: name,+ installed: null,+ machineId: null,+ local: false,+ connection: null,+ api: null,+ status: null,+ root: `~/.penguin/data`,+ });+ void hostName;+ return json(machinesResponse(store), 201);+ })+ .get("/api/projects/:projectId/machines/ssh-hosts/:alias", ({ params }): SshHostResponse => ({+ alias: params.alias!,+ hostName: `${params.alias}.example.internal`,+ user: "ubuntu",+ port: 22,+ editable: true,+ }))+ .put("/api/projects/:projectId/machines/ssh-hosts/:alias", ({ store }) => machinesResponse(store))+ .post("/api/projects/:projectId/machines/stop-using", ({ store }) => machinesResponse(store))+ .post("/api/projects/:projectId/machines/:machineId/install", () =>+ readOnly("install on a machine"),+ )+ .post("/api/projects/:projectId/machines/:machineId/connect", () => readOnly("connect a machine"))+ .post("/api/projects/:projectId/machines/:machineId/release", ({ store }) =>+ machinesResponse(store),+ )+ .post("/api/projects/:projectId/machines/:machineId/restart", () => readOnly("restart a machine"))+ .post("/api/projects/:projectId/machines/:machineId/disconnect", ({ store }) =>+ machinesResponse(store),+ );++// ---------------------------------------------------------------------------------------------+// Version, self-update, desktop+// ---------------------------------------------------------------------------------------------++const idleJob: UpdateJobStatus = { state: "idle", targetVersion: null, output: "" };++router+ .get("/api/version", ({ store }): VersionResponse => store.f.version)+ .get("/api/version/history", (): VersionHistoryResponse => ({+ current: null,+ entries: [],+ lastRollback: null,+ }))+ .post("/api/version/history/rollback", () => readOnly("roll a version back"))+ .get("/api/version/history/ifaces/:hash", () => notFound("Interface table"))+ .get("/api/version/history/diff", () => ({ added: [], removed: [], changed: [] }))+ .get("/api/version/update-check", ({ store }): UpdateCheckResponse => store.f.update)+ .get("/api/version/update", (): UpdateJobStatus => idleJob)+ .post("/api/version/update", () => readOnly("update the server"))+ .post("/api/version/restart", (): RestartResponse => ({+ restarting: false,+ reason: "no_supervisor",+ }))+ .get("/api/desktop/update", (): DesktopUpdateStatusResponse => ({ status: null }))+ .post("/api/desktop/update/check", () => notFound("Desktop updater"))+ .post("/api/desktop/update/download", () => notFound("Desktop updater"))+ .post("/api/desktop/update/install", () => notFound("Desktop updater"))+ .get("/api/desktop/tray", (): DesktopTrayStatusResponse => ({ status: null }))+ .put("/api/desktop/tray", () => empty())+ .post("/api/desktop/privacy-settings", () => notFound("Desktop mode"));++// ---------------------------------------------------------------------------------------------+// The built-in browser: the desktop shell's, so it answers as a server with no shell does+// ---------------------------------------------------------------------------------------------++function browserUnavailable(): never {+ return fail(503, "browser_unavailable", "The built-in browser needs the desktop app.");+}++router+ .get("/api/builtin-browser/status", (): BuiltinBrowserStatus => ({+ available: false,+ reason: "not_desktop",+ tabs: [],+ activeTabId: null,+ }))+ .post("/api/builtin-browser/tabs", browserUnavailable)+ .post("/api/builtin-browser/tabs/claim", browserUnavailable)+ .post("/api/builtin-browser/tabs/on-screen", browserUnavailable)+ .post("/api/builtin-browser/tabs/:tab/activate", browserUnavailable)+ .delete("/api/builtin-browser/tabs/:tab", browserUnavailable)+ .get("/api/builtin-browser/import/sources", (): BuiltinBrowserImportSourcesResponse => ({+ sources: [],+ }))+ .post("/api/builtin-browser/import", () => readOnly("import into the built-in browser"))+ .get("/api/builtin-browser/settings", (): BuiltinBrowserSettings => ({ homepage: null }))+ .put("/api/builtin-browser/settings", () => readOnly("change the built-in browser's settings"))+ .get("/api/builtin-browser/history", (): BuiltinBrowserHistoryResponse => ({ entries: [] }))+ .delete("/api/builtin-browser/history", () => empty())+ .post("/api/builtin-browser/clear-data", browserUnavailable);++// ---------------------------------------------------------------------------------------------+// Company mode: off in the demo, so every organization route answers as the server does then+// ---------------------------------------------------------------------------------------------++function companyOff(): never {+ return fail(404, "company_mode_off", "Company mode is off.");+}++router+ .get("/api/projects/:projectId/organizations", (): OrganizationsResponse => ({+ organizations: [],+ }))+ .post("/api/projects/:projectId/organizations", companyOff)+ .post("/api/projects/:projectId/suggest-id", ({ body }): SemanticIdSuggestResponse => {+ const name = str(record(body).name, "untitled");+ const id = name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "");+ return id === ""+ ? { id: `untitled-${dayKey(Date.now())}`, source: "placeholder", reason: "no_ascii" }+ : { id, source: "fallback", reason: "no_default_model" };+ })+ .get("/api/projects/:projectId/organizations/:orgId", companyOff)+ .patch("/api/projects/:projectId/organizations/:orgId", companyOff)+ .delete("/api/projects/:projectId/organizations/:orgId", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/chart", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/employees", companyOff)+ .patch("/api/projects/:projectId/organizations/:orgId/employees/:agentId", companyOff)+ .delete("/api/projects/:projectId/organizations/:orgId/employees/:agentId", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/employees/:agentId/desk", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/employees/:agentId/desk", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/handbook", companyOff)+ .put("/api/projects/:projectId/organizations/:orgId/handbook", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/handbook/files", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/handbook/files/*", companyOff)+ .put("/api/projects/:projectId/organizations/:orgId/handbook/files/*", companyOff)+ .delete("/api/projects/:projectId/organizations/:orgId/handbook/files/*", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/calendar", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/calendar", companyOff)+ .put("/api/projects/:projectId/organizations/:orgId/calendar/:agentId/:name", companyOff)+ .delete("/api/projects/:projectId/organizations/:orgId/calendar/:agentId/:name", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/tickets", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/tickets/:ticketId", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/tickets", companyOff)+ .put("/api/projects/:projectId/organizations/:orgId/tickets/:ticketId", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/tickets/:ticketId/:action", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/channels", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/channels", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/channels/:channelId", companyOff)+ .patch("/api/projects/:projectId/organizations/:orgId/channels/:channelId", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/channels/:channelId/members", companyOff)+ .delete(+ "/api/projects/:projectId/organizations/:orgId/channels/:channelId/members/:principal",+ companyOff,+ )+ .get("/api/projects/:projectId/organizations/:orgId/channels/:channelId/messages", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/channels/:channelId/messages", companyOff)+ .post("/api/projects/:projectId/organizations/:orgId/channels/:channelId/read", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/finance", companyOff)+ .get("/api/projects/:projectId/organizations/:orgId/sessions", companyOff);++// ---------------------------------------------------------------------------------------------+// Workflows and the Project's plugin list+// ---------------------------------------------------------------------------------------------++router+ .get("/api/projects/:projectId/agents/:agentId/workflows", (): { workflows: WorkflowInfo[] } => ({+ workflows: [],+ }))+ .post("/api/projects/:projectId/agents/:agentId/workflows/:workflowId/reload", () =>+ notFound("Workflow"),+ )+ .get("/api/projects/:projectId/agents/:agentId/workflows/:workflowId/history", () => ({+ versions: [],+ }))+ .post("/api/projects/:projectId/agents/:agentId/workflows/:workflowId/rollback", () =>+ notFound("Workflow"),+ )+ .delete("/api/projects/:projectId/agents/:agentId/workflows/:workflowId", () =>+ notFound("Workflow"),+ )+ .get(+ "/api/projects/:projectId/plugins/installed",+ ({ store }): InstalledPluginsResponse => store.f.installedPlugins,+ )+ .put(+ "/api/projects/:projectId/plugins/installed",+ ({ store, body }): InstalledPluginsResponse => {+ const list = record(body).plugins;+ if (Array.isArray(list)) {+ const wanted = new Set(list.filter((p): p is string => typeof p === "string"));+ for (const plugin of store.f.installedPlugins.plugins)+ plugin.everywhere = wanted.has(plugin.specifier);+ }+ return store.f.installedPlugins;+ },+ )+ .post(+ "/api/projects/:projectId/plugins/installed",+ ({ store, body }): InstalledPluginsResponse => {+ const specifier = str(record(body).specifier);+ if (!store.f.installedPlugins.shipped.includes(specifier))+ fail(404, "plugin_not_shipped", "This build does not ship that plugin.");+ if (!store.f.installedPlugins.plugins.some((p) => p.specifier === specifier)) {+ store.f.installedPlugins.plugins.push({+ specifier,+ active: false,+ builtin: true,+ modules: [],+ replaces: [],+ everywhere: true,+ machines: [],+ here: true,+ });+ store.f.installedPlugins.restartPending = true;+ }+ return store.f.installedPlugins;+ },+ )+ .delete(+ "/api/projects/:projectId/plugins/installed",+ ({ store, query }): InstalledPluginsResponse => {+ const specifier = query.get("specifier");+ store.f.installedPlugins.plugins = store.f.installedPlugins.plugins.filter(+ (p) => p.specifier !== specifier,+ );+ return store.f.installedPlugins;+ },+ );++// ---------------------------------------------------------------------------------------------+// The terminal list (a direct fetch in the app): nothing to attach to without a machine+// ---------------------------------------------------------------------------------------------++router.get("/api/terminals", () => ({ terminals: [] }));diff --git a/packages/ui-gallery/src/app/mock/sse.ts b/packages/ui-gallery/src/app/mock/sse.tsnew file mode 100644index 00000000..e0db0ab3--- /dev/null+++ b/packages/ui-gallery/src/app/mock/sse.ts@@ -0,0 +1,59 @@+/**+ * The Web App's `api/sse.ts`, swapped in by the gallery's Vite config: the same two+ * subscriptions, fed by the demo store's channels instead of an EventSource. A Session+ * subscription is told the run-state snapshot and every pending approval first, as the server+ * does on connect, and a running Session's script then streams on it.+ */+import type { StreamHandlers as AppStreamHandlers } from "./types";+import { getStore } from "./store";++export type StreamHandlers = AppStreamHandlers;++export interface StreamConnection {+ close: () => void;+}++/** Subscribes to a Session's output stream (GET /api/sessions/:sessionId/stream). */+export function openSessionStream(sessionId: string, handlers: StreamHandlers): StreamConnection {+ const store = getStore();+ const channel = store.channel(sessionId);+ if (!channel) {+ setTimeout(() => handlers.onError?.(true), 0);+ return { close: () => undefined };+ }+ const unsubscribe = channel.subscribe(handlers);+ let open = true;+ setTimeout(() => {+ if (!open) return;+ handlers.onOpen?.();+ store.onSubscribe(sessionId, handlers);+ }, 0);+ return {+ close: () => {+ open = false;+ unsubscribe();+ },+ };+}++/** Subscribes to the user-level server event stream (GET /api/events). */+export function openUserEvents(+ handlers: StreamHandlers,+ machineId: string | null = null,+): StreamConnection {+ void machineId;+ const store = getStore();+ const unsubscribe = store.userChannel.subscribe(handlers);+ let open = true;+ setTimeout(() => {+ if (!open) return;+ handlers.onOpen?.();+ handlers.onServerEvent({ type: "hello" }, null);+ }, 0);+ return {+ close: () => {+ open = false;+ unsubscribe();+ },+ };+}diff --git a/packages/ui-gallery/src/app/mock/store.ts b/packages/ui-gallery/src/app/mock/store.tsnew file mode 100644index 00000000..736fd0b8--- /dev/null+++ b/packages/ui-gallery/src/app/mock/store.ts@@ -0,0 +1,398 @@+/**+ * The in-memory demo store one framed app runs against: the fixtures as mutable state, the+ * two event channels the app subscribes to (the user channel and one per Session), and the+ * scripts that keep a running Session running — the executing command, the thinking that+ * keeps growing, the command waiting for approval — and stream a reply when a message is sent.+ *+ * One store per document (a frame is a document), created on first use for the frame's+ * language, and re-creatable for tests. Nothing here touches the DOM.+ */+import type { ServerEvent, SessionInfo } from "@prismshadow/penguin-server/api";+import { buildFixtures, DEFAULT_MODEL } from "./fixtures";+import type { DemoFixtures } from "./fixtures";+import { IDS } from "./ids";+import {+ abortEvent,+ approvalDecision,+ approvalOutcome,+ approvalTranscript,+ assistantText,+ doneTranscript,+ partial,+ requestEnd,+ replyTitle,+ runningToolTranscript,+ scriptedReply,+ shortTranscript,+ thinkingBeats,+ thinkingTranscript,+ tokenUsage,+ toolOutput,+ TOOL_CALL_IDS,+ userText,+} from "./transcripts";+import type { Transcript } from "./transcripts";+import { payloadOf } from "./types";+import type { Lang, OmniMessage, StreamHandlers } from "./types";++// ---------------------------------------------------------------------------------------------+// Channels+// ---------------------------------------------------------------------------------------------++/** The one epoch every id of this store carries: a frame never reconnects to another server. */+const EPOCH = "g1";++/** A channel: subscribers, and the running id the server stamps on every event. */+class Channel {+ private seq = 0;+ private readonly subscribers = new Set<StreamHandlers>();++ /** The id of the last event published — the live tail's cursor. */+ get cursor(): string {+ return `${EPOCH}-${this.seq}`;+ }++ subscribe(handlers: StreamHandlers): () => void {+ this.subscribers.add(handlers);+ return () => this.subscribers.delete(handlers);+ }++ private nextId(): string {+ this.seq += 1;+ return `${EPOCH}-${this.seq}`;+ }++ message(msg: OmniMessage, only?: StreamHandlers): void {+ const id = this.nextId();+ for (const s of only ? [only] : this.subscribers) s.onOmniMessage(msg, id);+ }++ event(ev: ServerEvent, only?: StreamHandlers): void {+ const id = this.nextId();+ for (const s of only ? [only] : this.subscribers) s.onServerEvent(ev, id);+ }+}++// ---------------------------------------------------------------------------------------------+// The store+// ---------------------------------------------------------------------------------------------++/** What a Session's live state adds to its rows and history. */+interface Live {+ transcript: Transcript;+ channel: Channel;+ /** Timers of a running script, cleared on abort or dispose. */+ timers: number[];+}++export class DemoStore {+ readonly f: DemoFixtures;+ readonly lang: Lang;+ /** Signed in as the fixtures' admin, or nobody. */+ signedIn: boolean;+ readonly userChannel = new Channel();+ private readonly live = new Map<string, Live>();+ private created = 0;++ constructor(lang: Lang, now: number, signedIn: boolean) {+ this.lang = lang;+ this.signedIn = signedIn;+ this.f = buildFixtures(lang, now);+ const ref = DEFAULT_MODEL;+ const seeded: Record<string, Transcript> = {+ [IDS.sessions.done]: doneTranscript(lang, now, ref),+ [IDS.sessions.runningTool]: runningToolTranscript(lang, now, ref),+ [IDS.sessions.thinking]: thinkingTranscript(lang, now, ref),+ [IDS.sessions.approval]: approvalTranscript(lang, now, ref),+ };+ for (const row of this.f.sessions) {+ const transcript =+ seeded[row.sessionId] ??+ shortTranscript(lang, row.sessionId, Date.parse(row.createdAt), ref);+ this.live.set(row.sessionId, { transcript, channel: new Channel(), timers: [] });+ }+ }++ // ---- Sessions --------------------------------------------------------------------------++ session(sessionId: string): SessionInfo | undefined {+ return this.f.sessions.find((s) => s.sessionId === sessionId);+ }++ transcript(sessionId: string): Transcript | undefined {+ return this.live.get(sessionId)?.transcript;+ }++ channel(sessionId: string): Channel | undefined {+ return this.live.get(sessionId)?.channel;+ }++ /** The live tail of a running Session: the open fragments and the channel cursor they cover. */+ liveTail(sessionId: string): { cursor: string; fragments: OmniMessage[] } | undefined {+ const live = this.live.get(sessionId);+ if (!live || !live.transcript.running) return undefined;+ const open = live.transcript.openThinking;+ const fragments = open+ ? [+ partial(open.startedAt, {+ type: "partial_thinking",+ role: "assistant",+ event_type: "start",+ thinking: open.text,+ }),+ ]+ : [];+ return { cursor: live.channel.cursor, fragments };+ }++ /**+ * A new Session (the draft's first send, a fork, a compaction's self-heal). Prepended to the+ * list, announced on the user channel, and given an empty transcript that the first Task+ * fills.+ */+ createSession(agentId: string, body: Partial<SessionInfo> & { title?: string }): SessionInfo {+ this.created += 1;+ const now = Date.now();+ const row: SessionInfo = {+ sessionId: `s-new-${this.created}`,+ projectId: IDS.project,+ agentId,+ provider: body.provider ?? DEFAULT_MODEL.provider,+ modelId: body.modelId ?? DEFAULT_MODEL.modelId,+ workspace: body.workspace ?? IDS.workspace,+ approvalMode: body.approvalMode ?? "allow-all",+ sandbox: body.sandbox ??+ this.f.chatDefaults.sandbox ?? { mode: "workspace-write", network: "open" },+ ...(body.title !== undefined ? { title: body.title } : {}),+ ...(body.source !== undefined ? { source: body.source } : {}),+ createdAt: new Date(now).toISOString(),+ lastActiveAt: new Date(now).toISOString(),+ status: "idle",+ pendingApprovalCount: 0,+ pendingFollowUpCount: 0,+ hasTrace: false,+ archived: false,+ client: "web",+ };+ this.f.sessions.unshift(row);+ this.live.set(row.sessionId, {+ transcript: { history: [], running: false },+ channel: new Channel(),+ timers: [],+ });+ this.userChannel.event({+ type: "session_created",+ projectId: IDS.project,+ agentId,+ sessionId: row.sessionId,+ });+ return row;+ }++ deleteSession(sessionId: string): boolean {+ const index = this.f.sessions.findIndex((s) => s.sessionId === sessionId);+ if (index === -1) return false;+ this.stopScript(sessionId);+ this.f.sessions.splice(index, 1);+ this.live.delete(sessionId);+ return true;+ }++ patchSession(sessionId: string, patch: Partial<SessionInfo>): SessionInfo | undefined {+ const row = this.session(sessionId);+ if (!row) return undefined;+ Object.assign(row, patch);+ if (patch.title !== undefined) {+ this.userChannel.event({ type: "session_title", sessionId, title: patch.title });+ }+ return row;+ }++ // ---- Running state ---------------------------------------------------------------------++ /**+ * What a fresh subscription is told first: the run state snapshot, then every approval still+ * pending — exactly what the server resends on connect.+ */+ onSubscribe(sessionId: string, handlers: StreamHandlers): void {+ const live = this.live.get(sessionId);+ if (!live) return;+ const row = this.session(sessionId);+ live.channel.event({ type: "task_state", state: row?.status ?? "idle" }, handlers);+ const pending = live.transcript.pendingApproval;+ if (pending) live.channel.event({ type: "approval_request", toolCall: pending }, handlers);+ if (sessionId === IDS.sessions.thinking) this.keepThinking(live);+ }++ private setStatus(sessionId: string, state: SessionInfo["status"]): void {+ const row = this.session(sessionId);+ const live = this.live.get(sessionId);+ if (!row || !live) return;+ row.status = state;+ row.lastActiveAt = new Date().toISOString();+ row.hasTrace = true;+ live.transcript.running = state !== "idle";+ live.channel.event({ type: "task_state", state });+ this.userChannel.event({+ type: "session_state",+ sessionId,+ state,+ lastActiveAt: row.lastActiveAt,+ hasTrace: true,+ });+ }++ private schedule(live: Live, at: number, run: () => void): void {+ live.timers.push(setTimeout(run, at) as unknown as number);+ }++ private stopScript(sessionId: string): void {+ const live = this.live.get(sessionId);+ if (!live) return;+ for (const timer of live.timers) clearTimeout(timer);+ live.timers = [];+ }++ /** Publishes a message on a Session's channel and records it as history, stamped now. */+ private emit(live: Live, msg: OmniMessage): void {+ const stamped: OmniMessage = { ...msg, timestamp: new Date().toISOString() };+ live.channel.message(stamped);+ const payload = payloadOf(stamped);+ if (payload === null || !payload.type.startsWith("partial_"))+ live.transcript.history.push(stamped);+ }++ /** The thinking Session's fragment keeps growing, one beat every 1.6 s, until it is opened elsewhere or aborted. */+ private keepThinking(live: Live): void {+ const open = live.transcript.openThinking;+ if (!open || live.timers.length > 0) return;+ const beats = thinkingBeats(this.lang);+ let index = 2;+ const tick = () => {+ const beat = beats[index % beats.length]!;+ index += 1;+ open.text += beat;+ live.channel.message(+ partial(Date.now(), {+ type: "partial_thinking",+ role: "assistant",+ event_type: "delta",+ thinking: beat,+ }),+ );+ if (index < 40) this.schedule(live, 1600, tick);+ };+ this.schedule(live, 1600, tick);+ }++ /**+ * A sent message: the Session runs, the prompt is echoed as the user's text, then the+ * scripted reply streams and the Session settles. The first turn of a new Session also+ * earns it a title.+ */+ startTask(sessionId: string, text: string): boolean {+ const live = this.live.get(sessionId);+ const row = this.session(sessionId);+ if (!live || !row) return false;+ if (row.status !== "idle") return false;+ const firstTurn = live.transcript.history.length === 0;+ this.stopScript(sessionId);+ this.setStatus(sessionId, "running");+ this.emit(live, userText(Date.now(), text));+ const callId = `call_${Date.now().toString(36)}`;+ const steps = scriptedReply(this.lang, callId);+ for (const step of steps) this.schedule(live, step.at, () => this.emit(live, step.msg));+ const last = steps[steps.length - 1]?.at ?? 0;+ this.schedule(live, last + 200, () => {+ if (firstTurn) this.patchSession(sessionId, { title: replyTitle(this.lang) });+ this.setStatus(sessionId, "idle");+ live.timers = [];+ });+ return true;+ }++ abort(sessionId: string): void {+ const live = this.live.get(sessionId);+ const row = this.session(sessionId);+ if (!live || !row || row.status === "idle") return;+ this.stopScript(sessionId);+ if (live.transcript.openThinking) delete live.transcript.openThinking;+ if (live.transcript.pendingApproval) {+ delete live.transcript.pendingApproval;+ row.pendingApprovalCount = 0;+ }+ this.emit(live, abortEvent(Date.now()));+ this.setStatus(sessionId, "idle");+ }++ /** A decision on the pending command: the event, then the command's outcome and the answer. */+ decide(sessionId: string, toolCallId: string, decision: "allow" | "deny"): boolean {+ const live = this.live.get(sessionId);+ const row = this.session(sessionId);+ const pending = live?.transcript.pendingApproval;+ if (!live || !row || !pending || pending.payload.tool_call_id !== toolCallId) return false;+ delete live.transcript.pendingApproval;+ row.pendingApprovalCount = 0;+ const outcome = approvalOutcome(this.lang, decision);+ this.emit(live, approvalDecision(Date.now(), toolCallId, decision));+ this.schedule(live, decision === "allow" ? 1800 : 200, () => {+ this.emit(live, toolOutput(Date.now(), toolCallId, outcome.output));+ this.emit(live, requestEnd(Date.now()));+ });+ this.schedule(live, decision === "allow" ? 3200 : 1200, () => {+ this.emit(live, assistantText(Date.now(), outcome.text));+ this.emit(live, tokenUsage(Date.now(), 22_400, 6_100));+ this.emit(live, requestEnd(Date.now()));+ this.setStatus(sessionId, "idle");+ live.timers = [];+ });+ return true;+ }++ /** The executing command hands itself to the background: the turn closes, the command runs on. */+ detachToolCall(sessionId: string, toolCallId: string): boolean {+ const live = this.live.get(sessionId);+ const row = this.session(sessionId);+ if (!live || !row || toolCallId !== TOOL_CALL_IDS.runningCommand) return false;+ this.emit(+ live,+ toolOutput(+ Date.now(),+ toolCallId,+ this.lang === "zh"+ ? "[detached] 命令已转入后台继续运行。"+ : "[detached] The command keeps running in the background.",+ ),+ );+ this.emit(live, requestEnd(Date.now()));+ this.setStatus(sessionId, "idle");+ row.backgroundTasks = { processes: 1, subagents: 0 };+ this.userChannel.event({ type: "session_background", sessionId, processes: 1, subagents: 0 });+ return true;+ }++ dispose(): void {+ for (const id of this.live.keys()) this.stopScript(id);+ }+}++// ---------------------------------------------------------------------------------------------+// The one store of this document+// ---------------------------------------------------------------------------------------------++let current: DemoStore | null = null;++/** The store the frame's language and sign-in state ask for; created once per document. */+export function getStore(init?: { lang: Lang; signedIn: boolean }): DemoStore {+ if (current === null) {+ current = new DemoStore(init?.lang ?? "en", Date.now(), init?.signedIn ?? true);+ }+ return current;+}++/** A fresh store (tests, and a frame that re-seeds itself). */+export function resetStore(init: { lang: Lang; signedIn: boolean; now?: number }): DemoStore {+ current?.dispose();+ current = new DemoStore(init.lang, init.now ?? Date.now(), init.signedIn);+ return current;+}diff --git a/packages/ui-gallery/src/app/mock/transcripts.ts b/packages/ui-gallery/src/app/mock/transcripts.tsnew file mode 100644index 00000000..f320994a--- /dev/null+++ b/packages/ui-gallery/src/app/mock/transcripts.ts@@ -0,0 +1,663 @@+/**+ * The demo conversations as OmniMessage transcripts, in both languages, plus the scripted+ * reply a sent message streams. Every message is built by the small builders below, so the+ * envelopes (timestamps, roles, stop reasons) are always well-formed, and the running states+ * the gallery exists to show are set up the way the server produces them:+ *+ * - a tool call with no `tool_call_output` yet is a running tool (the card's timer ticks);+ * - an open `partial_thinking` fragment, carried as the live tail, is running thinking;+ * - a tool call the stream has escalated with `approval_request` is waiting on a human.+ */+import { IDS } from "./ids";+import type { Lang, OmniMessage, PayloadOf, ToolCallMessage } from "./types";++// ---------------------------------------------------------------------------------------------+// Builders+// ---------------------------------------------------------------------------------------------++const iso = (ms: number) => new Date(ms).toISOString();++const model = <T extends PayloadOf<"text" | "thinking" | "tool_call" | "tool_call_output">>(+ ms: number,+ payload: T,+): OmniMessage => ({ timestamp: iso(ms), type: "model_msg", payload });++const event = (ms: number, payload: OmniMessage["payload"]): OmniMessage => ({+ timestamp: iso(ms),+ type: "event_msg",+ payload,+});++export const meta = (+ ms: number,+ sessionId: string,+ ref: { provider: string; modelId: string; contextWindow: number },+ workspace: string,+): OmniMessage => ({+ timestamp: iso(ms),+ type: "session_meta",+ payload: {+ session_id: sessionId,+ provider: ref.provider,+ model_id: ref.modelId,+ model_context_window: ref.contextWindow,+ system_prompt: "You are Docs Expert. Cite a real file for every claim.",+ agent_state: `/home/demo/.penguin/data/projects/${IDS.project}/agents/${IDS.agents.docs}/agent_state`,+ workspace,+ },+});++export const userText = (ms: number, text: string): OmniMessage =>+ model(ms, { type: "text", role: "user", text });++export const assistantText = (ms: number, text: string): OmniMessage =>+ model(ms, { type: "text", role: "assistant", text, stop_reason: "completed" });++export const thinking = (ms: number, text: string): OmniMessage =>+ model(ms, { type: "thinking", role: "assistant", thinking: text, stop_reason: "completed" });++export const toolCall = (+ ms: number,+ id: string,+ name: string,+ args: Record<string, unknown>,+): ToolCallMessage => ({+ timestamp: iso(ms),+ type: "model_msg",+ payload: {+ type: "tool_call",+ role: "assistant",+ name,+ arguments: JSON.stringify(args),+ tool_call_id: id,+ stop_reason: "completed",+ },+});++export const toolOutput = (ms: number, id: string, output: string): OmniMessage =>+ model(ms, {+ type: "tool_call_output",+ role: "user",+ output,+ tool_call_id: id,+ stop_reason: "completed",+ });++export const requestBegin = (ms: number): OmniMessage => event(ms, { type: "request_begin" });++export const requestEnd = (ms: number): OmniMessage =>+ event(ms, { type: "request_end", status: "completed" });++export const tokenUsage = (ms: number, sessionTotal: number, requestTotal: number): OmniMessage =>+ event(ms, {+ type: "token_usage",+ session: {+ cache_read: Math.round(sessionTotal * 0.62),+ cache_write: Math.round(sessionTotal * 0.09),+ output: Math.round(sessionTotal * 0.29),+ total: sessionTotal,+ },+ request: {+ cache_read: Math.round(requestTotal * 0.7),+ cache_write: Math.round(requestTotal * 0.05),+ output: Math.round(requestTotal * 0.25),+ total: requestTotal,+ },+ });++export const approvalDecision = (ms: number, id: string, decision: "allow" | "deny"): OmniMessage =>+ event(ms, { type: "approval_decision", decision, tool_call_id: id });++export const abortEvent = (ms: number): OmniMessage =>+ event(ms, { type: "abort", error_code: "user_abort" });++/** A streaming fragment; `event_type` says whether it opens, extends or closes the fragment. */+export const partial = (+ ms: number,+ payload:+ | PayloadOf<"partial_text">+ | PayloadOf<"partial_thinking">+ | PayloadOf<"partial_tool_call">+ | PayloadOf<"partial_tool_call_output">,+): OmniMessage => ({ timestamp: iso(ms), type: "model_msg", payload });++// ---------------------------------------------------------------------------------------------+// The content, per language+// ---------------------------------------------------------------------------------------------++const RAG_EXCERPT = `export function buildIndex(root: string): Index {+ const files = walk(root).filter((f) => f.endsWith(".md"));+ const docs = files.map((f) => ({ source: f, text: fs.readFileSync(f, "utf8") }));+ return bm25(docs, { k1: 1.2, b: 0.75 });+}++export function rank(question: string, index: Index): Hit[] {+ return index.query(question).slice(0, 6);+}`;++const RAG_OLD = ` const files = walk(root).filter((f) => f.endsWith(".md"));`;+const RAG_NEW = ` const files = walk(root)+ .filter((f) => f.endsWith(".md"))+ .filter((f) => fs.existsSync(f)); // a citation must open a real file`;++const TEST_OUTPUT = ` RUN v3.2.6 /home/demo/projects/docs-expert++ ✓ test/rag.test.ts (6 tests) 412ms+ ✓ indexes every markdown file under corpus/+ ✓ ranks hooks.md first for a hooks question+ ✓ never cites a file that does not exist++ Test Files 1 passed (1)+ Tests 6 passed (6)+ Start at 14:02:11+ Duration 1.08s`;++interface Copy {+ done: { prompt: string; thinking: string; answer: string; title: string };+ runningTool: { prompt: string; thinking: string; readOutput: string; title: string };+ thinking: { prompt: string; sentences: string[]; title: string };+ approval: { prompt: string; thinking: string; title: string; allowed: string; denied: string };+ reply: { thinking: string; text: string[]; title: string };+ older: Record<string, { prompt: string; answer: string }>;+}++const COPY: Record<Lang, Copy> = {+ en: {+ done: {+ title: "Index the hooks docs",+ prompt:+ "Add corpus/claude-code-docs/hooks.md to the BM25 index and make sure every citation points at a real file.",+ thinking:+ "The index is built in src/rag.ts from a recursive walk of corpus/. hooks.md is already under that directory, so the question is why it never surfaces: the walk probably filters on the extension before the file exists on disk in the test fixture. I should read the file first, then guard the citation path rather than the ranking.",+ answer: `Done — \`hooks.md\` is indexed and citations are guarded.++| Change | File | Effect |+| --- | --- | --- |+| Filter the walk on \`fs.existsSync\` | \`src/rag.ts\` | A citation can only name a file that opens |+| Re-ran the retrieval tests | \`test/rag.test.ts\` | 6 passed, 412 ms |++The hooks question now ranks the right file first:++\`\`\`ts+rank("How do I configure hooks?", index)[0].source;+// => "corpus/claude-code-docs/hooks.md"+\`\`\`++Nothing else in the corpus changed, so the index rebuild took 12.4 ms [1].++[1] corpus/claude-code-docs/hooks.md`,+ },+ runningTool: {+ title: "Check every link in the docs",+ prompt: "Check every link in corpus/ and list the ones that 404.",+ thinking:+ "There is a link checker in scripts/check-links.mjs. Let me confirm what it covers before running it over the whole corpus, since a full run takes a while.",+ readOutput: `#!/usr/bin/env node+// Walks every .md under corpus/, extracts links, HEADs each URL with a 10s timeout.+// --all also follows relative links to files in the repository.`,+ },+ thinking: {+ title: "Plan the 0.3 release notes",+ prompt: "Read CHANGELOG.md and draft the structure of the 0.3 release notes.",+ sentences: [+ "The changelog has forty-one unreleased entries. ",+ "Grouping them by the surface they touch reads better than by type: the chat, the Agents page, the Evaluation Center, machines. ",+ "Three entries carry a Breaking marker, so the notes need a compatibility section up front. ",+ "The migration entries reference each other; I should name the one a reader has to act on and fold the rest under it. ",+ "The highlight is remote machines — every other entry is a refinement. ",+ "Let me outline: one paragraph of lead, Highlights with three items, then Notable by surface, then Requirements. ",+ ],+ },+ approval: {+ title: "Publish the docs package",+ prompt: "The tests pass. Publish the docs package to npm.",+ thinking:+ "Publishing is irreversible and touches a registry outside the workspace, so this call goes through approval even though the session allows most commands.",+ allowed:+ "Published `@penguinharness/[email protected]`. The registry lists the new version and the tarball is 48.2 KB.",+ denied:+ "Not published. The package is built and ready in `dist/`; run the publish yourself when you want it out.",+ },+ reply: {+ title: "A question about the corpus",+ thinking:+ "The answer is in the corpus. Let me open the retrieval module to quote the exact rule rather than paraphrase it.",+ text: [+ "Here is what the corpus says.\n\n",+ "The retrieval module ranks the six best matches and keeps only the ones whose source file exists, ",+ "so every citation in an answer opens a real file — that is the rule `src/rag.ts` enforces on line 4.\n\n",+ "If you want the ranking itself changed, the BM25 parameters (`k1`, `b`) are the place to start.",+ ],+ },+ older: {+ [IDS.sessions.older[0]]: {+ prompt: "Sync the corpus from the docs repository.",+ answer: "Synced 214 Markdown files; 3 changed since last time.",+ },+ [IDS.sessions.older[1]]: {+ prompt: "Write an onboarding note for the docs expert.",+ answer: "Drafted docs/onboarding.md with the three questions people ask first.",+ },+ [IDS.sessions.older[2]]: {+ prompt: "Which benchmark cases fail most often?",+ answer: "CASE-003 (hooks configuration) fails in 2 of 3 runs; the rest pass.",+ },+ [IDS.sessions.older[3]]: {+ prompt: "Connect the filesystem MCP server.",+ answer: "Connected `filesystem` (3 tools). The session now reads corpus/ through it.",+ },+ [IDS.sessions.archived]: {+ prompt: "Migrate the old index format.",+ answer: "Migrated; the legacy loader is removed.",+ },+ [IDS.sessions.schedule]: {+ prompt: "[scheduled] Nightly corpus sync.",+ answer: "Nothing changed upstream tonight.",+ },+ [IDS.sessions.subagent]: {+ prompt: "Check the links in hooks.md.",+ answer: "All 14 links answer 200.",+ },+ [IDS.sessions.benchmark]: {+ prompt: "CASE-001: how are hooks configured?",+ answer:+ "Hooks are configured in hooks.json under the Agent State, one entry per hook point [1].",+ },+ [IDS.sessions.notes[0]]: {+ prompt: "Draft the release notes for 0.2.13.",+ answer: "Drafted; see changelog/0.2.13/RELEASE.md.",+ },+ [IDS.sessions.notes[1]]: {+ prompt: "List the breaking changes since 0.2.10.",+ answer: "Three: the plugin version spelling, the trace window and the goal state file.",+ },+ },+ },+ zh: {+ done: {+ title: "为 hooks 文档建立索引",+ prompt:+ "把 corpus/claude-code-docs/hooks.md 加进 BM25 索引,并确认每条引用都指向真实存在的文件。",+ thinking:+ "索引在 src/rag.ts 里由 corpus/ 的递归扫描建立。hooks.md 本来就在这个目录下,所以问题是它为什么从不被命中:扫描大概在测试夹具落盘之前就按扩展名过滤了。先读文件,再守住引用这一步,而不是改排序。",+ answer: `完成——\`hooks.md\` 已进入索引,引用也加了校验。++| 改动 | 文件 | 效果 |+| --- | --- | --- |+| 扫描时按 \`fs.existsSync\` 过滤 | \`src/rag.ts\` | 引用只会指向能打开的文件 |+| 重跑检索测试 | \`test/rag.test.ts\` | 6 项通过,412 ms |++关于 hooks 的问题现在会把正确的文件排在第一位:++\`\`\`ts+rank("如何配置 hooks?", index)[0].source;+// => "corpus/claude-code-docs/hooks.md"+\`\`\`++语料库里其他文件没有变化,索引重建用时 12.4 ms [1]。++[1] corpus/claude-code-docs/hooks.md`,+ },+ runningTool: {+ title: "检查文档里的全部链接",+ prompt: "检查 corpus/ 里的所有链接,列出返回 404 的那些。",+ thinking:+ "scripts/check-links.mjs 里有一个链接检查器。整个语料库跑一遍要花些时间,先确认它覆盖了什么再运行。",+ readOutput: `#!/usr/bin/env node+// 遍历 corpus/ 下的每个 .md,提取链接,对每个 URL 发 HEAD 请求,超时 10s。+// --all 会同时跟进指向仓库内文件的相对链接。`,+ },+ thinking: {+ title: "规划 0.3 发布说明",+ prompt: "读一下 CHANGELOG.md,起草 0.3 发布说明的结构。",+ sentences: [+ "变更日志里有四十一条未发布的条目。",+ "按它们触及的界面分组比按类型分组更好读:对话、智能体页、评估中心、机器。",+ "有三条带 Breaking 标记,所以说明开头需要一节兼容性说明。",+ "迁移相关的条目互相引用;应该点名读者必须动手的那一条,其余折叠在它下面。",+ "亮点是远程机器——其他条目都是打磨。",+ "先列提纲:一段导语,三条 Highlights,然后按界面分的 Notable,最后是 Requirements。",+ ],+ },+ approval: {+ title: "发布文档包",+ prompt: "测试通过了。把文档包发布到 npm。",+ thinking:+ "发布不可撤销,而且会触及工作区之外的注册表,所以即使这个会话允许大多数命令,这一步也要经过审批。",+ allowed:+ "已发布 `@penguinharness/[email protected]`。注册表已列出新版本,压缩包 48.2 KB。",+ denied: "没有发布。包已经构建好放在 `dist/`,需要时自行运行发布命令即可。",+ },+ reply: {+ title: "关于语料库的一个问题",+ thinking: "答案在语料库里。打开检索模块,引用原文里的规则,而不是转述。",+ text: [+ "语料库里是这样写的。\n\n",+ "检索模块会取排名最高的六条匹配,只保留源文件真实存在的那些,",+ "所以回答里的每条引用都能打开一个真实文件——这就是 `src/rag.ts` 第 4 行守住的规则。\n\n",+ "如果你想改的是排序本身,BM25 的参数(`k1`、`b`)是起点。",+ ],+ },+ older: {+ [IDS.sessions.older[0]]: {+ prompt: "从文档仓库同步语料库。",+ answer: "已同步 214 个 Markdown 文件,其中 3 个自上次以来有变化。",+ },+ [IDS.sessions.older[1]]: {+ prompt: "给文档专家写一份上手说明。",+ answer: "已起草 docs/onboarding.md,收录了大家最先问的三个问题。",+ },+ [IDS.sessions.older[2]]: {+ prompt: "哪些评估用例最常失败?",+ answer: "CASE-003(hooks 配置)三次里失败两次,其余通过。",+ },+ [IDS.sessions.older[3]]: {+ prompt: "接入 filesystem MCP 服务器。",+ answer: "已连接 `filesystem`(3 个工具)。会话现在通过它读取 corpus/。",+ },+ [IDS.sessions.archived]: {+ prompt: "迁移旧的索引格式。",+ answer: "已迁移;旧的加载器已移除。",+ },+ [IDS.sessions.schedule]: {+ prompt: "[定时] 每晚同步语料库。",+ answer: "今晚上游没有变化。",+ },+ [IDS.sessions.subagent]: {+ prompt: "检查 hooks.md 里的链接。",+ answer: "14 条链接全部返回 200。",+ },+ [IDS.sessions.benchmark]: {+ prompt: "CASE-001:hooks 是怎么配置的?",+ answer: "hooks 在 Agent State 下的 hooks.json 里配置,每个钩子点一条 [1]。",+ },+ [IDS.sessions.notes[0]]: {+ prompt: "起草 0.2.13 的发布说明。",+ answer: "已起草;见 changelog/0.2.13/RELEASE.md。",+ },+ [IDS.sessions.notes[1]]: {+ prompt: "列出 0.2.10 以来的破坏性变更。",+ answer: "三条:插件版本号写法、轨迹窗口和目标状态文件。",+ },+ },+ },+};++export const copyFor = (lang: Lang): Copy => COPY[lang];++// ---------------------------------------------------------------------------------------------+// The transcripts+// ---------------------------------------------------------------------------------------------++export interface ModelRef {+ provider: string;+ modelId: string;+ contextWindow: number;+}++/** The tool call ids the stream events name, so the store can decide them. */+export const TOOL_CALL_IDS = {+ runningCommand: "call_running_links",+ pendingPublish: "call_publish",+} as const;++export interface Transcript {+ history: OmniMessage[];+ /** An open thinking fragment the live tail carries (running thinking). */+ openThinking?: { startedAt: number; text: string };+ /** A tool call awaiting a human decision. */+ pendingApproval?: ToolCallMessage;+ running: boolean;+}++/** The finished Task: a minute and a bit of work, ended a while ago. */+export function doneTranscript(lang: Lang, now: number, ref: ModelRef): Transcript {+ const c = COPY[lang].done;+ const t0 = now - 42 * 60_000;+ const s = (sec: number) => t0 + sec * 1000;+ return {+ running: false,+ history: [+ meta(s(0), IDS.sessions.done, ref, IDS.workspace),+ userText(s(0), c.prompt),+ requestBegin(s(0.4)),+ thinking(s(6), c.thinking),+ toolCall(s(7), "call_read_rag", "read_file", { path: "src/rag.ts" }),+ requestEnd(s(7.1)),+ toolOutput(s(7.5), "call_read_rag", RAG_EXCERPT),+ requestBegin(s(7.8)),+ toolCall(s(14), "call_edit_rag", "edit_file", {+ path: "src/rag.ts",+ old_string: RAG_OLD,+ new_string: RAG_NEW,+ }),+ requestEnd(s(14.1)),+ toolOutput(s(14.6), "call_edit_rag", "Edited src/rag.ts (+3 -1)."),+ requestBegin(s(15)),+ toolCall(s(18), "call_test", "exec_command", {+ cmd: "pnpm vitest run test/rag.test.ts",+ description: lang === "zh" ? "运行检索测试" : "Run the retrieval tests",+ }),+ requestEnd(s(18.1)),+ toolOutput(s(20.2), "call_test", TEST_OUTPUT),+ requestBegin(s(20.5)),+ assistantText(s(31), c.answer),+ tokenUsage(s(31.2), 43_800, 12_400),+ requestEnd(s(31.2)),+ ],+ };+}++/** A Task mid-run: a command executing, its output still to come. */+export function runningToolTranscript(lang: Lang, now: number, ref: ModelRef): Transcript {+ const c = COPY[lang].runningTool;+ const t0 = now - 95_000;+ const s = (sec: number) => t0 + sec * 1000;+ return {+ running: true,+ history: [+ meta(s(0), IDS.sessions.runningTool, ref, IDS.workspace),+ userText(s(0), c.prompt),+ requestBegin(s(0.3)),+ thinking(s(4), c.thinking),+ toolCall(s(5), "call_read_checker", "read_file", { path: "scripts/check-links.mjs" }),+ requestEnd(s(5.1)),+ toolOutput(s(5.4), "call_read_checker", c.readOutput),+ requestBegin(s(5.7)),+ toolCall(s(9), TOOL_CALL_IDS.runningCommand, "exec_command", {+ cmd: "node scripts/check-links.mjs --all",+ description: lang === "zh" ? "检查全部链接" : "Check every link",+ }),+ requestEnd(s(9.1)),+ ],+ };+}++/** A Task mid-run: the model thinking; the fragment is open and keeps growing. */+export function thinkingTranscript(lang: Lang, now: number, ref: ModelRef): Transcript {+ const c = COPY[lang].thinking;+ const t0 = now - 50_000;+ const s = (sec: number) => t0 + sec * 1000;+ return {+ running: true,+ openThinking: { startedAt: s(8), text: c.sentences.slice(0, 2).join("") },+ history: [+ meta(s(0), IDS.sessions.thinking, ref, IDS.workspace),+ userText(s(0), c.prompt),+ requestBegin(s(0.3)),+ toolCall(s(3), "call_read_changelog", "read_file", { path: "CHANGELOG.md" }),+ requestEnd(s(3.1)),+ toolOutput(+ s(3.5),+ "call_read_changelog",+ "# Changelog\n\n## Unreleased\n\n41 entries in changelog/unreleased/ …",+ ),+ requestBegin(s(4)),+ ],+ };+}++/** A Task waiting on a human: the publish command awaits approval. */+export function approvalTranscript(lang: Lang, now: number, ref: ModelRef): Transcript {+ const c = COPY[lang].approval;+ const t0 = now - 30_000;+ const s = (sec: number) => t0 + sec * 1000;+ const call = toolCall(s(6), TOOL_CALL_IDS.pendingPublish, "exec_command", {+ cmd: "pnpm publish --access public",+ description: lang === "zh" ? "发布到 npm" : "Publish to npm",+ });+ return {+ running: true,+ pendingApproval: call,+ history: [+ meta(s(0), IDS.sessions.approval, ref, IDS.workspace),+ userText(s(0), c.prompt),+ requestBegin(s(0.3)),+ thinking(s(5), c.thinking),+ call,+ ],+ };+}++/** A short finished exchange for the rows that only fill the list. */+export function shortTranscript(+ lang: Lang,+ sessionId: string,+ startedAt: number,+ ref: ModelRef,+): Transcript {+ const c = COPY[lang].older[sessionId] ?? { prompt: sessionId, answer: "Done." };+ const s = (sec: number) => startedAt + sec * 1000;+ return {+ running: false,+ history: [+ meta(s(0), sessionId, ref, IDS.workspace),+ userText(s(0), c.prompt),+ requestBegin(s(0.3)),+ assistantText(s(6), c.answer),+ tokenUsage(s(6.1), 8_200, 8_200),+ requestEnd(s(6.1)),+ ],+ };+}++// ---------------------------------------------------------------------------------------------+// The scripted reply+// ---------------------------------------------------------------------------------------------++/** One step of a script: what to publish, `at` ms after the script starts. */+export interface ScriptStep {+ at: number;+ msg: OmniMessage;+}++/** Splits text into word-sized chunks so a stream reads as one. */+function chunks(text: string): string[] {+ return text.match(/\S+\s*/g) ?? [text];+}++/**+ * The reply a sent message streams: thinking, one tool call with its output, then the answer,+ * each arriving as the server streams it (fragments first, the complete message closing each),+ * ending with the usage and the request's end. Timestamps are stamped when the step runs.+ */+export function scriptedReply(lang: Lang, callId: string): ScriptStep[] {+ const c = COPY[lang].reply;+ const steps: ScriptStep[] = [];+ let at = 250;+ const push = (msg: OmniMessage) => steps.push({ at, msg });+ const p = (ms: number, payload: Parameters<typeof partial>[1]) => partial(ms, payload);++ push(requestBegin(0));+ at += 300;+ push(p(0, { type: "partial_thinking", role: "assistant", event_type: "start", thinking: "" }));+ for (const chunk of chunks(c.thinking)) {+ at += 70;+ push(+ p(0, { type: "partial_thinking", role: "assistant", event_type: "delta", thinking: chunk }),+ );+ }+ at += 120;+ push(p(0, { type: "partial_thinking", role: "assistant", event_type: "stop", thinking: "" }));+ push(thinking(0, c.thinking));++ at += 400;+ const args = JSON.stringify({ path: "src/rag.ts" });+ push(+ p(0, {+ type: "partial_tool_call",+ role: "assistant",+ event_type: "start",+ name: "read_file",+ arguments: "",+ tool_call_id: callId,+ }),+ );+ at += 200;+ push(+ p(0, {+ type: "partial_tool_call",+ role: "assistant",+ event_type: "delta",+ name: "read_file",+ arguments: args,+ tool_call_id: callId,+ }),+ );+ at += 100;+ push(+ p(0, {+ type: "partial_tool_call",+ role: "assistant",+ event_type: "stop",+ name: "read_file",+ arguments: "",+ tool_call_id: callId,+ }),+ );+ push(toolCall(0, callId, "read_file", { path: "src/rag.ts" }));+ push(requestEnd(0));+ at += 1400;+ push(toolOutput(0, callId, RAG_EXCERPT));+ at += 300;+ push(requestBegin(0));++ at += 500;+ push(p(0, { type: "partial_text", role: "assistant", event_type: "start", text: "" }));+ for (const part of c.text) {+ for (const chunk of chunks(part)) {+ at += 45;+ push(p(0, { type: "partial_text", role: "assistant", event_type: "delta", text: chunk }));+ }+ }+ at += 150;+ push(p(0, { type: "partial_text", role: "assistant", event_type: "stop", text: "" }));+ push(assistantText(0, c.text.join("")));+ push(tokenUsage(0, 51_300, 7_500));+ push(requestEnd(0));+ return steps;+}++/** The title the model gives a conversation after its first turn. */+export const replyTitle = (lang: Lang): string => COPY[lang].reply.title;++/** What the approval session's command says once decided. */+export function approvalOutcome(+ lang: Lang,+ decision: "allow" | "deny",+): {+ output: string;+ text: string;+} {+ const c = COPY[lang].approval;+ return decision === "allow"+ ? {+ output:+ "npm notice publishing @penguinharness/[email protected]\nnpm notice 48.2 KB dist/index.js\n+ @penguinharness/[email protected]",+ text: c.allowed,+ }+ : { output: "Tool call denied by user.", text: c.denied };+}++/** The sentences the thinking session keeps adding, one per beat, cycling. */+export const thinkingBeats = (lang: Lang): readonly string[] => COPY[lang].thinking.sentences;diff --git a/packages/ui-gallery/src/app/mock/types.ts b/packages/ui-gallery/src/app/mock/types.tsnew file mode 100644index 00000000..67d0f0e8--- /dev/null+++ b/packages/ui-gallery/src/app/mock/types.ts@@ -0,0 +1,34 @@+/**+ * The message types the demo store speaks, derived from the server's API contract rather+ * than imported from core: the gallery does not depend on the core package, and the contract+ * already carries every shape the app reads off the wire, so deriving keeps one source.+ */+import type { MessagesLiveTail, ServerEvent } from "@prismshadow/penguin-server/api";++export type OmniMessage = MessagesLiveTail["fragments"][number];+export type OmniPayload = OmniMessage["payload"];+/** The `session_meta` record's payload, the one arm of the union that carries no `type`. */+export type SessionMetaPayload = Extract<OmniPayload, { session_id: string }>;+/** Every other payload: a model message or an event, discriminated by `type`. */+export type TypedPayload = Exclude<OmniPayload, SessionMetaPayload>;+export type PayloadOf<T extends TypedPayload["type"]> = Extract<TypedPayload, { type: T }>;+export type ToolCallMessage = Extract<ServerEvent, { type: "approval_request" }>["toolCall"];++/**+ * A message's typed payload, or null for the `session_meta` record. The envelope's `type` is+ * what says which payload a message carries (the payload union itself has no shared+ * discriminant), so this is the one place that reads it.+ */+export function payloadOf(msg: OmniMessage): TypedPayload | null {+ return msg.type === "session_meta" ? null : (msg.payload as TypedPayload);+}++/** The stream handlers the app's SSE module declares, as the mock delivers to them. */+export interface StreamHandlers {+ onOmniMessage: (msg: OmniMessage, eventId: string | null) => void;+ onServerEvent: (event: ServerEvent, eventId: string | null) => void;+ onOpen?: () => void;+ onError?: (closed: boolean) => void;+}++export type Lang = "en" | "zh";diff --git a/packages/ui-gallery/src/app/mock/vite-plugin.ts b/packages/ui-gallery/src/app/mock/vite-plugin.tsnew file mode 100644index 00000000..6aa3d812--- /dev/null+++ b/packages/ui-gallery/src/app/mock/vite-plugin.ts@@ -0,0 +1,43 @@+/**+ * The Vite plugin that swaps the Web App's network layer for the demo store's: every import+ * that resolves to `packages/web/src/api/client.ts` or `api/sse.ts` — from the endpoint+ * wrappers, the providers, the features — resolves to the mocks here instead. Matching on+ * the resolved file rather than the specifier text means `./client`, `../api/client` and+ * `../../api/client` are all caught, and nothing else is.+ *+ * Shared by the gallery's Vite config and its vitest config, so the tests that walk the+ * app's endpoint wrappers run them against the mock too. The resolution is path arithmetic+ * (the app imports these two modules by extensionless relative specifiers from TypeScript+ * files, and nothing else), so the plugin needs no plugin context and fits both configs'+ * plugin types structurally.+ */+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const here = (rel: string) => fileURLToPath(new URL(rel, import.meta.url));++/** Real module (absolute path, no extension) → the mock that stands in for it. */+export const SWAPPED_MODULES: Readonly<Record<string, string>> = {+ [here("../../../../web/src/api/client")]: here("./client.ts"),+ [here("../../../../web/src/api/sse")]: here("./sse.ts"),+};++/** The mock a relative import from `importer` should resolve to, or null for any other import. */+export function swappedModuleFor(source: string, importer: string | undefined): string | null {+ if (importer === undefined || !source.startsWith(".")) return null;+ const from = importer.split("?")[0] ?? importer;+ const target = resolve(dirname(from), source).replace(/\.tsx?$/, "");+ return SWAPPED_MODULES[target] ?? null;+}++export function mockWebNetwork(): {+ name: string;+ enforce: "pre";+ resolveId: (source: string, importer: string | undefined) => string | null;+} {+ return {+ name: "penguin:gallery-mock-web-network",+ enforce: "pre",+ resolveId: (source, importer) => swappedModuleFor(source, importer),+ };+}diff --git a/packages/ui-gallery/src/app/surfaces.ts b/packages/ui-gallery/src/app/surfaces.tsnew file mode 100644index 00000000..6c6833ee--- /dev/null+++ b/packages/ui-gallery/src/app/surfaces.ts@@ -0,0 +1,98 @@+/**+ * The app's surfaces: what the gallery frames, one page each (`/s/<id>`), grouped the way the+ * index and the left nav list them. A surface is a route of the real Web App plus how the+ * frame opens it — signed in or out, and a dialog to open once it is up. The titles and+ * descriptions are chrome copy (`S.surfaces`), keyed by these ids.+ *+ * Pure data with no value imports, so Node can import this file as it is (the screenshot+ * script does): the ids the routes name are spelled here, and a test holds them to the demo+ * store's (src/app/mock/ids.ts).+ */++export const SURFACE_GROUP_IDS = [+ "conversation",+ "workbench",+ "resources",+ "measure",+ "system",+] as const;+export type SurfaceGroupId = (typeof SURFACE_GROUP_IDS)[number];++export const SURFACE_IDS = [+ "chat",+ "chat-running",+ "chat-thinking",+ "chat-approval",+ "chat-new",+ "agents",+ "agent-settings",+ "schedules",+ "plugins",+ "plugin-detail",+ "models",+ "machines",+ "usage",+ "benchmark",+ "benchmark-detail",+ "settings",+ "settings-appearance",+ "login",+] as const;+export type SurfaceId = (typeof SURFACE_IDS)[number];++/** A dialog the frame asks the app to open once it is up: Settings, on the page named after the dot. */+export type SurfaceOpen = "settings" | `settings.${string}`;++export interface Surface {+ id: SurfaceId;+ group: SurfaceGroupId;+ /** The app route the frame opens on (path, query and all). */+ route: string;+ /** Start signed out: the frame lands on the login page and signs in from there. */+ signedOut?: true;+ open?: SurfaceOpen;+}++export const SURFACES: readonly Surface[] = [+ { id: "chat", group: "conversation", route: "/chat/s-hooks-index" },+ { id: "chat-running", group: "conversation", route: "/chat/s-link-check" },+ { id: "chat-thinking", group: "conversation", route: "/chat/s-release-plan" },+ { id: "chat-approval", group: "conversation", route: "/chat/s-publish" },+ { id: "chat-new", group: "conversation", route: "/chat" },+ { id: "agents", group: "workbench", route: "/agents" },+ { id: "agent-settings", group: "workbench", route: "/agents/docs-expert" },+ { id: "schedules", group: "workbench", route: "/agents/docs-expert?tab=schedules" },+ { id: "plugins", group: "resources", route: "/plugins" },+ { id: "plugin-detail", group: "resources", route: "/plugins/registry/claude-code-expert" },+ { id: "models", group: "resources", route: "/models" },+ { id: "machines", group: "resources", route: "/machines" },+ { id: "usage", group: "measure", route: "/usage" },+ { id: "benchmark", group: "measure", route: "/benchmark" },+ { id: "benchmark-detail", group: "measure", route: "/benchmark/docs-qa-v1" },+ { id: "settings", group: "system", route: "/chat/s-hooks-index", open: "settings" },+ {+ id: "settings-appearance",+ group: "system",+ route: "/chat/s-hooks-index",+ open: "settings.appearance",+ },+ { id: "login", group: "system", route: "/login", signedOut: true },+];++const BY_ID = new Map<string, Surface>(SURFACES.map((surface) => [surface.id, surface]));++export const isSurfaceId = (id: string): id is SurfaceId => BY_ID.has(id);++export function surfaceById(id: string): Surface | undefined {+ return BY_ID.get(id);+}++/** The groups in index order, each listing its surfaces in `SURFACES` order. */+export const SURFACE_GROUPS: readonly { id: SurfaceGroupId; surfaces: readonly Surface[] }[] =+ SURFACE_GROUP_IDS.map((id) => ({+ id,+ surfaces: SURFACES.filter((surface) => surface.group === id),+ }));++/** The surface the home page frames: the finished conversation, the app's everyday view. */+export const HOME_SURFACE: SurfaceId = "chat";diff --git a/packages/ui-gallery/src/chrome.css b/packages/ui-gallery/src/chrome.cssnew file mode 100644index 00000000..d052aace--- /dev/null+++ b/packages/ui-gallery/src/chrome.css@@ -0,0 +1,1059 @@+/*+ * The gallery chrome: the top bar, a section's navigation list, the content column with its+ * sections and toolbars, "on this page", the framed app, the framed component library and the+ * fonts pages.+ * Deliberately UNTHEMED — every colour is a `--g-*` variable and every length is px, never rem or+ * em — so switching the theme, the accent or the root size under test never moves the chrome; only+ * the previews follow `<html style="font-size">`. It follows only the mode (`.dark` on <html>).+ *+ * The layout is a docs site's: a quiet top bar; a left column with a search box and the surfaces+ * grouped, the current one marked by a thin rule and accent text; a reading-width content column+ * with an eyebrow, a large title, a one-line lead and H2 sections ruled underneath; a right column+ * listing what is on the page. One accent, hairlines, whitespace, the system sans at 14–16 px.+ * The framed app sits in a hairline frame, nothing heavier.+ *+ * Unlayered on purpose: these rules outrank Tailwind's layers and theme.css's base rules (focus+ * outline, selection, body font) wherever a `.g-*` class matches, and match nothing inside a+ * preview except the labels that carry a `.g-*` class themselves.+ */++:root {+ --g-font:+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial,+ "PingFang SC", "Microsoft YaHei", sans-serif;+ --g-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;+ --g-page: #ffffff;+ --g-surface: #ffffff;+ --g-inset: #f6f8fa;+ --g-hover: #f2f4f7;+ --g-ink: #1f2328;+ --g-ink-2: #59636e;+ --g-ink-3: #8c959f;+ --g-line: #e8ebef;+ --g-line-strong: #d0d7de;+ --g-accent: #2563eb;+ --g-accent-soft: rgb(37 99 235 / 0.08);+ --g-bad: #c62828;+ --g-raise: 0 1px 2px rgb(0 0 0 / 0.06), 0 0 0 1px rgb(0 0 0 / 0.05);+ --g-float: 0 12px 32px rgb(0 0 0 / 0.12);+ /* The page frame: the bar's height, the columns' widths, the side gutter. */+ --g-bar: 56px;+ --g-nav: 236px;+ --g-toc: 200px;+ --g-column: 720px;+ --g-gutter: 24px;+}++/* Dark: a calm neutral, the landing site's and the app's Primer dark — a near-neutral canvas+ lifted off black, surfaces a step lighter, ink at 15:1 on the canvas, the muted ink at 7:1 and+ the subtle one above 4.5:1 on every chrome surface, one brand blue. */+:root.dark {+ --g-page: #141414;+ --g-surface: #1c1c1c;+ --g-inset: #1f1f1f;+ --g-hover: #262626;+ --g-ink: #ececec;+ --g-ink-2: #ababab;+ --g-ink-3: #8f8f8f;+ --g-line: #2a2a2a;+ --g-line-strong: #383838;+ --g-accent: #669df6;+ --g-accent-soft: rgb(102 157 246 / 0.14);+ --g-bad: #f28b82;+ --g-raise: 0 0 0 1px rgb(255 255 255 / 0.08);+ --g-float: 0 12px 32px rgb(0 0 0 / 0.55);+}++/* ---- Base for chrome subtrees ------------------------------------------------------------ */++.g-chrome {+ font-family: var(--g-font);+ font-size: 14px;+ line-height: 1.5;+ letter-spacing: normal;+ text-transform: none;+ color: var(--g-ink);+ -webkit-font-smoothing: antialiased;+}+.g-chrome ::selection {+ background: color-mix(in srgb, var(--g-accent) 25%, transparent);+}+.g-chrome button,+.g-chrome a {+ font: inherit;+ color: inherit;+}+.g-chrome a {+ text-decoration: none;+}+.g-chrome button:focus-visible,+.g-chrome a:focus-visible,+.g-chrome input:focus-visible,+.g-chrome summary:focus-visible {+ outline: 2px solid var(--g-accent);+ outline-offset: 1px;+}+.g-chrome code {+ font-family: var(--g-mono);+ font-size: 12.5px;+}+.g-muted {+ color: var(--g-ink-3);+}+.g-icon {+ display: block;+ flex-shrink: 0;+}++/* ---- The site: bar over body -------------------------------------------------------------- */++.g-site {+ min-height: 100vh;+ overflow-x: clip;+ background: var(--g-page);+}++/* The top bar, one row: brand and page links left, the controls right; never wraps — what does+ not fit the row lives in the popover, and at phone width in the drawer. */+.g-topbar {+ position: sticky;+ top: 0;+ z-index: 30;+ display: flex;+ align-items: center;+ gap: 20px;+ height: var(--g-bar);+ padding: 0 var(--g-gutter);+ border-bottom: 1px solid var(--g-line);+ background: var(--g-page);+}+.g-brand {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-shrink: 0;+}+.g-brand img {+ width: 24px;+ height: 24px;+ border-radius: 6px;+}+.g-brand strong {+ font-size: 15px;+ font-weight: 600;+ letter-spacing: -0.15px;+ white-space: nowrap;+}+.g-links {+ display: flex;+ align-items: center;+ gap: 2px;+}+.g-link {+ display: inline-flex;+ align-items: center;+ height: 28px;+ padding: 0 9px;+ border-radius: 6px;+ color: var(--g-ink-2);+ white-space: nowrap;+}+.g-link:hover {+ color: var(--g-ink);+ background: var(--g-hover);+}+.g-link[aria-current="page"] {+ color: var(--g-page);+ background: var(--g-ink);+}+.g-bar-controls {+ display: flex;+ align-items: center;+ flex-shrink: 0;+ gap: 10px;+ margin-left: auto;+}+/* The menu button is the phone bar's; it outranks the icon button's display below. */+.g-topbar .g-menu {+ display: none;+}++/* The body: the module list, the content column and "on this page", centred. */+.g-body {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ justify-content: center;+ column-gap: 48px;+ max-width: 1040px;+ margin: 0 auto;+ padding: 0 var(--g-gutter) 120px;+}+.g-site[data-nav] .g-body {+ grid-template-columns: var(--g-nav) minmax(0, var(--g-column));+ max-width: 1280px;+}+.g-site[data-nav][data-toc] .g-body {+ grid-template-columns: var(--g-nav) minmax(0, var(--g-column)) var(--g-toc);+}+/* A framed board needs the room: the content column grows past the reading width. */+.g-site[data-nav] .g-body[data-wide] {+ grid-template-columns: var(--g-nav) minmax(0, 960px);+}+.g-main {+ min-width: 0;+}++/* ---- Controls ----------------------------------------------------------------------------- */++/* The labelled rows of the popover and the drawer: the label left, the control right. */+.g-controls {+ display: grid;+ gap: 12px;+}+.g-control {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ min-width: 0;+}+.g-controls-foot {+ padding-top: 12px;+ border-top: 1px solid var(--g-line);+}+.g-control-label {+ color: var(--g-ink-2);+ font-size: 13px;+ flex-shrink: 0;+}+.g-seg {+ display: inline-flex;+ padding: 2px;+ gap: 1px;+ border-radius: 7px;+ background: var(--g-inset);+}+.g-seg button {+ display: inline-flex;+ align-items: center;+ height: 24px;+ padding: 0 8px;+ border: 0;+ border-radius: 5px;+ background: transparent;+ color: var(--g-ink-2);+ font-size: 12.5px;+ font-weight: 500;+ font-variant-numeric: tabular-nums;+ cursor: pointer;+ white-space: nowrap;+}+.g-seg button:hover {+ color: var(--g-ink);+}+.g-seg button[aria-pressed="true"] {+ background: var(--g-page);+ color: var(--g-ink);+ box-shadow: var(--g-raise);+}+.g-seg-icon {+ display: inline-flex;+ align-items: center;+ gap: 4px;+}+.g-mode {+ display: inline-flex;+ padding: 2px;+ gap: 1px;+ border-radius: 7px;+ background: var(--g-inset);+}+.g-mode button {+ display: grid;+ place-items: center;+ width: 26px;+ height: 24px;+ border: 0;+ border-radius: 5px;+ background: transparent;+ color: var(--g-ink-3);+ cursor: pointer;+}+.g-mode button:hover {+ color: var(--g-ink);+}+.g-mode button[aria-pressed="true"] {+ background: var(--g-page);+ color: var(--g-ink);+ box-shadow: var(--g-raise);+}+/* The accent row: each swatch painted in the colour it applies; the pressed one ringed. */+.g-swatches {+ display: inline-flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 5px;+}+.g-swatch {+ width: 16px;+ height: 16px;+ padding: 0;+ border: 0;+ border-radius: 999px;+ background: var(--g-swatch);+ box-shadow: inset 0 0 0 1px rgb(127 127 127 / 0.35);+ cursor: pointer;+}+.g-swatch[data-empty] {+ background: var(--g-inset);+}+.g-swatch[aria-pressed="true"] {+ box-shadow:+ 0 0 0 2px var(--g-page),+ 0 0 0 3.5px var(--g-ink);+}++/* The drawn select (chrome/select.tsx): a trigger showing the chosen option, a listbox panel+ portaled to the body, the chosen row checked, the active row filled. */+.g-select {+ display: inline-flex;+ align-items: center;+ justify-content: space-between;+ gap: 6px;+ width: 168px;+ height: 28px;+ padding: 0 6px 0 10px;+ border: 1px solid var(--g-line-strong);+ border-radius: 7px;+ background: var(--g-page);+ color: var(--g-ink);+ font-size: 13px;+ text-align: left;+ cursor: pointer;+}+.g-select:hover {+ background: var(--g-hover);+}+.g-select[aria-expanded="true"] {+ border-color: var(--g-accent);+}+.g-select-value {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.g-select > .g-icon {+ color: var(--g-ink-3);+}+.g-listbox {+ position: fixed;+ z-index: 60;+ max-height: 280px;+ overflow-y: auto;+ padding: 4px;+ border: 1px solid var(--g-line);+ border-radius: 8px;+ background: var(--g-page);+ box-shadow: var(--g-float);+}+.g-option {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ width: 100%;+ height: 30px;+ padding: 0 8px;+ border: 0;+ border-radius: 5px;+ background: transparent;+ color: var(--g-ink-2);+ font-size: 13px;+ text-align: left;+ white-space: nowrap;+ cursor: pointer;+}+.g-option[data-active],+.g-option:hover {+ color: var(--g-ink);+ background: var(--g-hover);+}+.g-option[aria-selected="true"] {+ color: var(--g-ink);+ font-weight: 500;+}+/* The active row's fill is its focus mark; a ring on top of it would double it. */+.g-chrome .g-option:focus-visible {+ outline: none;+}+.g-option > .g-icon {+ color: var(--g-ink-3);+}++/* The popover under the bar's settings button: the secondary controls, then the fonts in use. */+.g-popover {+ position: relative;+}+.g-popover-panel {+ position: absolute;+ top: calc(100% + 8px);+ right: 0;+ z-index: 31;+ display: grid;+ gap: 12px;+ width: 336px;+ padding: 14px 16px;+ border: 1px solid var(--g-line);+ border-radius: 10px;+ background: var(--g-page);+ box-shadow: var(--g-float);+}++/* The tooltip (chrome/tooltip.tsx): a small panel under whatever carries `data-tooltip`. */+.g-tip {+ position: fixed;+ z-index: 70;+ width: max-content;+ padding: 4px 8px;+ border: 1px solid var(--g-line);+ border-radius: 6px;+ background: var(--g-page);+ color: var(--g-ink);+ font-size: 12px;+ line-height: 1.4;+ white-space: pre-line;+ box-shadow: var(--g-float);+ pointer-events: none;+}++/* The fonts in use: the label muted, the families in ink, wrapping as they need. */+.g-readout {+ display: grid;+ gap: 2px;+ font-size: 12.5px;+ color: var(--g-ink-3);+}+.g-readout-value {+ color: var(--g-ink-2);+ font-variant-numeric: tabular-nums;+}+.g-readout-line {+ font-variant-numeric: tabular-nums;+}++.g-icon-button {+ display: inline-grid;+ place-items: center;+ width: 28px;+ height: 28px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--g-ink-3);+ cursor: pointer;+}+.g-icon-button:hover {+ color: var(--g-ink);+ background: var(--g-hover);+}++/* ---- The surface list: a search box, the groups, the current page ruled ----------------- */++.g-sidenav {+ position: sticky;+ top: var(--g-bar);+ align-self: start;+ max-height: calc(100vh - var(--g-bar));+ overflow-y: auto;+ padding: 28px 24px 40px 0;+ border-right: 1px solid var(--g-line);+ scrollbar-width: thin;+ scrollbar-color: var(--g-line-strong) transparent;+}+.g-search {+ display: flex;+ align-items: center;+ gap: 8px;+ height: 36px;+ padding: 0 10px;+ border: 1px solid var(--g-line-strong);+ border-radius: 8px;+ background: var(--g-page);+ color: var(--g-ink-3);+}+.g-search:focus-within {+ border-color: var(--g-accent);+}+.g-search input {+ flex: 1;+ min-width: 0;+ border: 0;+ background: transparent;+ font: inherit;+ color: var(--g-ink);+ outline: none;+}+.g-search input::-webkit-search-cancel-button {+ display: none;+}+.g-search kbd {+ padding: 1px 5px;+ border: 1px solid var(--g-line);+ border-radius: 4px;+ font-family: var(--g-mono);+ font-size: 11px;+ color: var(--g-ink-3);+ white-space: nowrap;+}+.g-nav-empty {+ margin: 16px 0 0;+ font-size: 13px;+}+.g-nav-group {+ margin-top: 22px;+}+.g-nav-eyebrow {+ display: block;+ margin-bottom: 6px;+ font-size: 12px;+ color: var(--g-ink-3);+}+.g-nav-group ul {+ list-style: none;+ margin: 0;+ padding: 0;+ border-left: 1px solid var(--g-line);+}+.g-nav-link {+ display: block;+ margin-left: -1px;+ padding: 5px 12px;+ border-left: 1px solid transparent;+ color: var(--g-ink-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.g-nav-link:hover {+ color: var(--g-ink);+}+.g-nav-link[aria-current="page"] {+ padding-left: 11px;+ border-left: 2px solid var(--g-accent);+ color: var(--g-accent);+ font-weight: 500;+}++/* ---- The content column ------------------------------------------------------------------- */++.g-doc,+.g-home {+ min-width: 0;+ padding-top: 36px;+}+.g-doc-wide {+ max-width: 960px;+}+.g-doc-head {+ display: grid;+ gap: 0;+}+.g-eyebrow {+ margin: 0 0 6px;+ font-size: 13px;+ font-weight: 500;+ color: var(--g-accent);+}+.g-h1 {+ margin: 0;+ font-size: 32px;+ line-height: 1.2;+ font-weight: 600;+ letter-spacing: -0.4px;+ text-wrap: balance;+}+.g-lead {+ margin: 12px 0 0;+ font-size: 16px;+ line-height: 1.6;+ color: var(--g-ink-2);+}+.g-h2 {+ margin: 48px 0 0;+ padding-bottom: 8px;+ border-bottom: 1px solid var(--g-line);+ font-size: 22px;+ line-height: 1.3;+ font-weight: 600;+ letter-spacing: -0.2px;+}+.g-section,+.g-variant {+ scroll-margin-top: calc(var(--g-bar) + 16px);+}+.g-section-lead,+.g-variant-desc {+ margin: 12px 0 0;+ font-size: 15px;+ line-height: 1.6;+ color: var(--g-ink-2);+}+.g-section-meta {+ margin: 10px 0 0;+ font-size: 13px;+ color: var(--g-ink-3);+}+/* The toolbar over a preview: the primary control, open standalone, the link, the crumb. */+.g-toolbar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 2px 4px;+ margin: 14px 0 8px;+ font-size: 13px;+ color: var(--g-ink-2);+}+.g-tool {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ height: 26px;+ padding: 0 8px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--g-ink-2);+ font-size: 13px;+ white-space: nowrap;+ cursor: pointer;+}+.g-tool:hover {+ color: var(--g-ink);+ background: var(--g-hover);+}+.g-tool-primary {+ color: var(--g-accent);+ font-weight: 500;+}+.g-tool-primary:hover {+ color: var(--g-accent);+ background: var(--g-accent-soft);+}+.g-tool-icon {+ width: 26px;+ padding: 0;+ justify-content: center;+}+.g-toolbar > .g-crumb {+ margin-left: auto;+}++/* The preview in a hairline frame, on the theme's canvas. */+.g-frame {+ border: 1px solid var(--g-line);+ border-radius: 8px;+ overflow: hidden;+ background: var(--ui-canvas, var(--g-surface));+}+/* The composition on the theme's canvas, vertically centred with room around it. */+.g-preview {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ align-content: center;+ min-height: 240px;+ padding: 28px 24px;+ background: var(--ui-canvas, var(--g-surface));+ color: var(--ui-fg, var(--g-ink));+ /* The chrome face, as the app's body sets it: a reading surface inside opts into font-sans. */+ font-family: var(--ui-font-ui, var(--g-font));+ font-size: var(--ui-text-body-size, 16px);+ line-height: var(--ui-text-body-lh, 1.5);+}++/* The quotable breadcrumb. */+.g-crumb {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ max-width: 100%;+ height: 26px;+ padding: 0 6px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--g-ink-3);+ font-family: var(--g-mono);+ font-size: 11.5px;+ cursor: pointer;+ text-align: left;+}+.g-crumb > span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.g-crumb:hover {+ color: var(--g-ink);+}++/* ---- "On this page" ----------------------------------------------------------------------- */++.g-toc {+ position: sticky;+ top: var(--g-bar);+ align-self: start;+ max-height: calc(100vh - var(--g-bar));+ overflow-y: auto;+ padding: 36px 0 40px;+ font-size: 13px;+ scrollbar-width: thin;+ scrollbar-color: var(--g-line-strong) transparent;+}+.g-toc-eyebrow {+ display: block;+ margin-bottom: 8px;+ color: var(--g-ink-3);+}+.g-toc-list ul {+ list-style: none;+ margin: 0;+ padding: 0;+ border-left: 1px solid var(--g-line);+}+.g-toc-list a {+ display: block;+ margin-left: -1px;+ padding: 4px 12px;+ border-left: 1px solid transparent;+ color: var(--g-ink-2);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.g-toc-list a:hover {+ color: var(--g-ink);+}+.g-toc-list a[data-active] {+ padding-left: 11px;+ border-left: 2px solid var(--g-accent);+ color: var(--g-accent);+}++/* ---- The framed app ------------------------------------------------------------------------ */++/* The app's document: its own root, sized to the app's window and scaled by the fit below. */+.g-app {+ min-width: 0;+}+.g-app-frame {+ display: block;+ max-width: 100%;+ border: 0;+ background: transparent;+}+/* Phone: a 390 px frame, centred, in a rounded hairline on the chrome's inset. */+.g-app[data-phone] {+ display: flex;+ justify-content: center;+ padding: 28px 20px;+ background: var(--g-inset);+}+.g-app[data-phone] .g-app-frame {+ border: 1px solid var(--g-line-strong);+ border-radius: 12px;+}++/* ---- The framed component library: at the column's width, as tall as its board ------------- */++.g-lib {+ min-width: 0;+}+.g-lib-frame {+ display: block;+ width: 100%;+ border: 0;+ background: transparent;+}+/* Until the board has reported its height the frame is the pending size: shown then, never+ clipped, and never animated between sizes — a growing frame would scroll the page under it. */+.g-lib:not([data-loaded]) .g-lib-frame {+ visibility: hidden;+}++/* ---- Fitted frames: the app laid out at its window width, scaled to the column -------------- */++/* The box the page sees takes the scaled height (set inline); the frame inside keeps its natural+ width, so its unscaled layout box overflows and is clipped here. Centred when the column is+ wider than the frame, which is never scaled up. */+.g-fit {+ min-width: 0;+ overflow: hidden;+}+.g-fit-inner {+ margin-inline: auto;+ transform-origin: 0 0;+}++/* ---- Code and tables ----------------------------------------------------------------------- */++.g-code {+ margin: 12px 0 0;+ max-height: 560px;+ padding: 12px 14px;+ overflow: auto;+ border: 1px solid var(--g-line);+ border-radius: 8px;+ background: var(--g-inset);+ font-family: var(--g-mono);+ font-size: 12.5px;+ line-height: 1.55;+ white-space: pre;+ color: var(--g-ink);+}++/* ---- Home: the index and the feedback note ------------------------------------------------ */++.g-index-eyebrow {+ margin: 28px 0 0;+ font-size: 12px;+ font-weight: 500;+ color: var(--g-ink-3);+}+.g-index {+ list-style: none;+ margin: 10px 0 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+ gap: 12px;+}+.g-index a {+ display: grid;+ gap: 4px;+ height: 100%;+ padding: 14px 16px;+ border: 1px solid var(--g-line);+ border-radius: 8px;+ color: var(--g-ink);+}+.g-index a:hover {+ border-color: var(--g-line-strong);+ background: var(--g-hover);+}+.g-index strong {+ font-size: 15px;+ font-weight: 600;+}+.g-index span {+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+ overflow: hidden;+ font-size: 13px;+ line-height: 1.5;+ color: var(--g-ink-2);+}+.g-note {+ margin-top: 48px;+ padding: 14px 16px;+ border: 1px solid var(--g-line);+ border-radius: 8px;+ font-size: 13px;+ color: var(--g-ink-2);+}+.g-note p {+ margin: 2px 0 6px;+}+.g-note code {+ display: inline-block;+ padding: 2px 6px;+ border-radius: 5px;+ background: var(--g-inset);+ color: var(--g-ink);+ overflow-wrap: anywhere;+}++/* ---- /fonts ------------------------------------------------------------------------------ */++.g-font-theme h3 {+ margin: 24px 0 8px;+ font-size: 15px;+ font-weight: 600;+}+.g-font-role {+ display: grid;+ grid-template-columns: 220px minmax(0, 1fr);+ gap: 16px;+ padding: 12px 0;+ border-top: 1px solid var(--g-line);+}+.g-font-role-meta {+ display: grid;+ gap: 2px;+ align-content: start;+ font-size: 12.5px;+ word-break: break-word;+}+.g-font-role-meta [data-unset] {+ color: var(--g-bad);+}+.g-font-samples {+ display: grid;+ gap: 10px;+}+.g-font-sample p {+ margin: 0;+ line-height: 1.6;+}+.g-font-size {+ display: block;+ font-family: var(--g-mono);+ font-size: 11px;+ color: var(--g-ink-3);+}+.g-table {+ width: 100%;+ margin-top: 12px;+ border-collapse: collapse;+ font-size: 13px;+}+.g-table th {+ padding: 6px 8px;+ text-align: left;+ font-weight: 500;+ color: var(--g-ink-3);+}+.g-table td {+ padding: 6px 8px;+ border-top: 1px solid var(--g-line);+ vertical-align: top;+}+.g-fonts-table th[scope="row"] {+ font-weight: 500;+ text-align: left;+}+.g-fonts-table tr[aria-current] td,+.g-fonts-table tr[aria-current] th {+ color: var(--g-accent);+}+.g-fonts-current {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, max-content));+ gap: 12px 40px;+ margin: 16px 0;+}+.g-fonts-current dt {+ font-size: 13px;+ color: var(--g-ink-3);+}+.g-fonts-current dd {+ margin: 2px 0 0;+ font-size: 15px;+}+.g-num-cell {+ font-variant-numeric: tabular-nums;+}+.g-licence {+ border-top: 1px solid var(--g-line);+ padding: 6px 0;+}+.g-licence summary {+ cursor: pointer;+ font-family: var(--g-mono);+ font-size: 12.5px;+}+.g-licence .g-code {+ margin-top: 8px;+ white-space: pre-wrap;+}++/* ---- Phone width: one column, the columns in a drawer, nothing sideways ------------------- */++/* The drawer only exists while open; at desktop widths it is never shown. */+.g-drawer {+ display: none;+}++@media (max-width: 900px) {+ :root {+ --g-gutter: 16px;+ }+ .g-topbar {+ gap: 12px;+ }+ .g-links,+ .g-bar-controls {+ display: none;+ }+ .g-topbar .g-menu {+ display: inline-grid;+ margin-left: auto;+ }+ .g-drawer {+ display: grid;+ align-content: start;+ gap: 24px;+ position: fixed;+ z-index: 29;+ inset: var(--g-bar) 0 0 0;+ overflow-y: auto;+ padding: 16px var(--g-gutter) 40px;+ background: var(--g-page);+ }+ .g-drawer-links {+ display: grid;+ gap: 2px;+ }+ .g-drawer-links .g-link {+ height: 32px;+ }+ .g-drawer-controls {+ display: grid;+ gap: 12px;+ }+ .g-drawer-controls .g-select {+ width: min(168px, 55vw);+ }+ .g-drawer .g-nav-group {+ margin-top: 16px;+ }+ .g-body,+ .g-site[data-nav] .g-body,+ .g-site[data-nav][data-toc] .g-body,+ .g-site[data-nav] .g-body[data-wide] {+ grid-template-columns: minmax(0, 1fr);+ max-width: none;+ padding-bottom: 80px;+ }+ .g-sidenav,+ .g-toc {+ display: none;+ }+ .g-doc,+ .g-home {+ padding-top: 24px;+ }+ .g-h1 {+ font-size: 26px;+ }+ .g-h2 {+ margin-top: 36px;+ font-size: 19px;+ }+ .g-preview {+ min-height: 160px;+ padding: 16px 12px;+ }+ .g-toolbar > .g-crumb {+ margin-left: 0;+ flex-basis: 100%;+ }+ .g-app[data-phone] {+ padding: 16px 12px;+ }+ .g-font-role {+ grid-template-columns: minmax(0, 1fr);+ }+}diff --git a/packages/ui-gallery/src/chrome/app-frame.tsx b/packages/ui-gallery/src/chrome/app-frame.tsxnew file mode 100644index 00000000..ec13cee5--- /dev/null+++ b/packages/ui-gallery/src/chrome/app-frame.tsx@@ -0,0 +1,101 @@+/**+ * The real Web App in a frame: one `app.html` document per frame — its own root for the theme+ * attributes, its own storage, its own router — opened on a surface's route with the page's+ * preferences in the URL (src/app/frame.ts). Laid out at the app's window width and scaled to+ * the column (chrome/fit.tsx), or at phone width, unscaled, in a phone-shaped frame on the+ * chrome's inset.+ *+ * A change of theme, mode, size or fonts changes the frame's URL, and the frame reloads with+ * the new preferences — the URL is the state, as everywhere in the gallery. The frame reports+ * the fonts it is actually set in, for the readout in the top bar's popover and, when the page+ * asks, its own font line.+ */+import type { ThemeId } from "@prismshadow/penguin-ui";+import { useEffect, useRef, useState } from "react";+import { APP_FRAME, appFrameSrc, PHONE_FRAME } from "../app/frame";+import type { FontReadout } from "../app/fonts";+import type { Surface } from "../app/surfaces";+import { BASE } from "../lib/location";+import { useGallery } from "../state";+import { Fit } from "./fit";+import { readFrameFonts, reportFrameFonts } from "./font-readout";++/** The frame's URL for a surface under the page's preferences, in one theme. */+export function useFrameSrc(surface: Surface, theme: ThemeId): string {+ const { state } = useGallery();+ return appFrameSrc(+ BASE,+ {+ theme,+ mode: state.mode,+ accent: state.accent,+ size: state.size,+ latin: state.latin,+ cjk: state.cjk,+ lang: state.lang,+ },+ {+ route: surface.route,+ ...(surface.signedOut ? { signedOut: true } : {}),+ ...(surface.open ? { open: surface.open } : {}),+ },+ );+}++export function AppFrame({+ surface,+ onFonts,+ reloadKey = 0,+}: {+ surface: Surface;+ /** Also hand the readout to the page, for its own font line. */+ onFonts?: (readout: FontReadout | null) => void;+ /** A new value reloads the frame (the Reload control). */+ reloadKey?: number;+}) {+ const { S, state } = useGallery();+ const src = useFrameSrc(surface, state.theme);+ const phone = state.view === "phone";+ const size = phone ? PHONE_FRAME : APP_FRAME;+ const frame = useRef<HTMLIFrameElement>(null);+ const [loaded, setLoaded] = useState(false);++ useEffect(() => {+ setLoaded(false);+ }, [src, reloadKey]);++ useEffect(() => {+ if (!loaded || !frame.current) return;+ let live = true;+ void readFrameFonts(frame.current).then((readout) => {+ if (!live) return;+ reportFrameFonts(readout);+ onFonts?.(readout);+ });+ return () => {+ live = false;+ };+ }, [loaded, src, onFonts]);++ // Leaving the page takes the frame's report with it; the popover falls back to the page's own root.+ useEffect(() => () => reportFrameFonts(null), []);++ const iframe = (+ <iframe+ key={`${src}#${reloadKey}`}+ ref={frame}+ className="g-app-frame"+ title={S.frame.frameOf(S.rail.themeNames[state.theme])}+ src={src}+ width={size.width}+ height={size.height}+ loading="eager"+ onLoad={() => setLoaded(true)}+ />+ );+ return (+ <div className="g-app" data-phone={phone || undefined} data-loaded={loaded || undefined}>+ {phone ? iframe : <Fit natural={size.width}>{iframe}</Fit>}+ </div>+ );+}diff --git a/packages/ui-gallery/src/chrome/controls.tsx b/packages/ui-gallery/src/chrome/controls.tsxnew file mode 100644index 00000000..5f26e0b2--- /dev/null+++ b/packages/ui-gallery/src/chrome/controls.tsx@@ -0,0 +1,80 @@+/**+ * Chrome controls, styled by chrome.css only: a segmented control and a swatch row for the accent+ * — each swatch painted in the colour it would apply, so the row previews the theme's palette+ * before anything is chosen. The select for the longer option lists is chrome/select.tsx.+ */+import type { CSSProperties, ReactNode } from "react";++export interface SegmentOption<T extends string> {+ value: T;+ label: ReactNode;+ /** A hint shown on hover and focus, for a segment whose label is short or an icon. */+ hint?: string;+}++export function Segmented<T extends string>({+ label,+ value,+ options,+ onChange,+}: {+ label: string;+ value: T;+ options: readonly SegmentOption<T>[];+ onChange: (value: T) => void;+}) {+ return (+ <div className="g-seg" role="group" aria-label={label}>+ {options.map((option) => (+ <button+ key={option.value}+ type="button"+ aria-pressed={option.value === value}+ aria-label={option.hint}+ data-tooltip={option.hint}+ onClick={() => onChange(option.value)}+ >+ {option.label}+ </button>+ ))}+ </div>+ );+}++export interface SwatchOption {+ value: string;+ /** The name shown on hover and read to assistive technology. */+ label: string;+ /** The colour the swatch is painted in; empty until the probe has resolved it. */+ color: string;+}++export function Swatches({+ label,+ value,+ options,+ onChange,+}: {+ label: string;+ value: string;+ options: readonly SwatchOption[];+ onChange: (value: string) => void;+}) {+ return (+ <div className="g-swatches" role="group" aria-label={label}>+ {options.map((option) => (+ <button+ key={option.value}+ type="button"+ className="g-swatch"+ aria-pressed={option.value === value}+ aria-label={option.label}+ data-tooltip={option.label}+ data-empty={option.color === "" || undefined}+ style={{ "--g-swatch": option.color || "transparent" } as CSSProperties}+ onClick={() => onChange(option.value)}+ />+ ))}+ </div>+ );+}diff --git a/packages/ui-gallery/src/chrome/copy.ts b/packages/ui-gallery/src/chrome/copy.tsnew file mode 100644index 00000000..835fbe8f--- /dev/null+++ b/packages/ui-gallery/src/chrome/copy.ts@@ -0,0 +1,34 @@+/** Clipboard writes with a transient "copied" flag for the button that asked. */+import { useCallback, useEffect, useRef, useState } from "react";++export async function copyText(text: string): Promise<void> {+ try {+ await navigator.clipboard.writeText(text);+ return;+ } catch {+ // Fall through: an insecure origin or a denied permission still has execCommand.+ }+ const area = document.createElement("textarea");+ area.value = text;+ area.setAttribute("readonly", "");+ area.style.cssText = "position:fixed;top:0;left:0;opacity:0";+ document.body.appendChild(area);+ area.select();+ document.execCommand("copy");+ area.remove();+}++/** `[copiedKey, copy]`: `copiedKey` names the last thing copied for 1.2 s, so one hook serves many buttons. */+export function useCopy(): [string | null, (key: string, text: string) => void] {+ const [copied, setCopied] = useState<string | null>(null);+ const timer = useRef(0);+ useEffect(() => () => window.clearTimeout(timer.current), []);+ const copy = useCallback((key: string, text: string) => {+ void copyText(text).then(() => {+ setCopied(key);+ window.clearTimeout(timer.current);+ timer.current = window.setTimeout(() => setCopied(null), 1200);+ });+ }, []);+ return [copied, copy];+}diff --git a/packages/ui-gallery/src/chrome/crumb.tsx b/packages/ui-gallery/src/chrome/crumb.tsxnew file mode 100644index 00000000..c5120450--- /dev/null+++ b/packages/ui-gallery/src/chrome/crumb.tsx@@ -0,0 +1,25 @@+/**+ * The quotable breadcrumb: the address of what a preview shows (lib/breadcrumb.ts), copied to the+ * clipboard with a click, so feedback can name a view exactly. Copied, only the icon changes to a+ * check for a moment; the address stays readable.+ */+import { useGallery } from "../state";+import { useCopy } from "./copy";+import { ChromeIcon } from "./icons";++export function Breadcrumb({ text, className = "" }: { text: string; className?: string }) {+ const { S } = useGallery();+ const [copied, copy] = useCopy();+ return (+ <button+ type="button"+ className={`g-crumb ${className}`}+ aria-label={S.section.copyBreadcrumb}+ data-tooltip={S.section.copyBreadcrumb}+ onClick={() => copy("crumb", text)}+ >+ <ChromeIcon name={copied ? "check" : "copy"} size={13} />+ <span>{text}</span>+ </button>+ );+}diff --git a/packages/ui-gallery/src/chrome/fit.tsx b/packages/ui-gallery/src/chrome/fit.tsxnew file mode 100644index 00000000..013be2f3--- /dev/null+++ b/packages/ui-gallery/src/chrome/fit.tsx@@ -0,0 +1,62 @@+/**+ * A box that lays its children out at a fixed natural width and scales the result to the room it+ * has: the card's composition for a module designed at the app's width, and the framed embed of+ * one when comparing themes.+ *+ * Why a transform rather than CSS `zoom`: a transform leaves layout alone, so the composition is+ * laid out at exactly its natural width — the same line breaks, truncations and container-query+ * answers it has in the app — and only the picture shrinks. `zoom` re-lays the text out at the+ * scaled font size, where glyph advances round differently and a title can wrap or truncate at a+ * different word than it does at full size. The price is that a transform does not shrink the box+ * the page sees, so this measures the composition's height and gives the box the scaled height+ * itself. Pointer events map through the transform, so everything inside stays clickable, and the+ * composition stays in the page's own document, so its scene clock, its controls and the tokens+ * drawer's measuring all work as they do unscaled.+ */+import type { ReactNode } from "react";+import { useLayoutEffect, useRef, useState } from "react";+import { fitScale, fittedHeight } from "../lib/fit";++export function Fit({ natural, children }: { natural: number; children: ReactNode }) {+ const outer = useRef<HTMLDivElement>(null);+ const inner = useRef<HTMLDivElement>(null);+ const [box, setBox] = useState({ available: 0, height: 0 });++ useLayoutEffect(() => {+ const out = outer.current;+ const content = inner.current;+ if (!out || !content) return;+ const measure = () =>+ setBox((current) => {+ const next = { available: out.clientWidth, height: content.offsetHeight };+ return next.available === current.available && next.height === current.height+ ? current+ : next;+ });+ measure();+ // The card's width moves with the window and the drawers; the composition's height moves as a+ // scene plays. Either changes the scaled box.+ const observer = new ResizeObserver(measure);+ observer.observe(out);+ observer.observe(content);+ return () => observer.disconnect();+ }, []);++ const scale = fitScale(natural, box.available);+ return (+ <div+ ref={outer}+ className="g-fit"+ data-scaled={scale < 1 || undefined}+ style={{ height: box.height > 0 ? fittedHeight(box.height, scale) : undefined }}+ >+ <div+ ref={inner}+ className="g-fit-inner"+ style={{ width: natural, transform: scale < 1 ? `scale(${scale})` : undefined }}+ >+ {children}+ </div>+ </div>+ );+}diff --git a/packages/ui-gallery/src/chrome/font-readout.tsx b/packages/ui-gallery/src/chrome/font-readout.tsxnew file mode 100644index 00000000..2bfb1071--- /dev/null+++ b/packages/ui-gallery/src/chrome/font-readout.tsx@@ -0,0 +1,71 @@+/**+ * The fonts in use, as the top bar's popover and each surface page state them: the Latin, CJK+ * and mono faces actually rendering and the root size, read from a framed app once it has loaded+ * — the frame on the page reports its readout here — or, on a page without a frame, from the+ * page's own root, which carries the same theme attributes and theme sheets.+ */+import { useEffect, useState, useSyncExternalStore } from "react";+import { formatFontReadout, readFontReadout } from "../app/fonts";+import type { FontReadout } from "../app/fonts";+import { useGallery } from "../state";++let frameReadout: FontReadout | null = null;+const listeners = new Set<() => void>();++/** A framed app reports what it is set in; the readout follows the latest report. */+export function reportFrameFonts(readout: FontReadout | null): void {+ frameReadout = readout;+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++/** Reads a frame's fonts once it has loaded and its fonts are ready; null when it has no document. */+export function readFrameFonts(frame: HTMLIFrameElement): Promise<FontReadout | null> {+ const doc = frame.contentDocument;+ if (!doc || !doc.defaultView) return Promise.resolve(null);+ return doc.fonts.ready.then(+ () => readFontReadout(doc),+ () => readFontReadout(doc),+ );+}++/** The readout the page shows: the frame's when one has reported, else the page root's. */+export function useFontReadout(): FontReadout | null {+ const { state } = useGallery();+ const reported = useSyncExternalStore(subscribe, () => frameReadout);+ const [own, setOwn] = useState<FontReadout | null>(null);+ // The page root re-applies its attributes in a layout effect on every change of these; this+ // effect runs after that, so it reads what the root now carries.+ useEffect(() => {+ let live = true;+ const read = () => {+ if (live) setOwn(readFontReadout(document));+ };+ read();+ void document.fonts.ready.then(read);+ document.fonts.addEventListener("loadingdone", read);+ return () => {+ live = false;+ document.fonts.removeEventListener("loadingdone", read);+ };+ }, [state.theme, state.mode, state.size, state.latin, state.cjk]);+ return reported ?? own;+}++/** The label, then `Latin Mona Sans · CJK MiSans · Mono JetBrains Mono · 16px` or the pending word. */+export function FontReadoutLine() {+ const { S } = useGallery();+ const readout = useFontReadout();+ return (+ <div className="g-readout">+ <span className="g-readout-label">{S.readout.label}</span>+ <span className="g-readout-value">+ {readout ? formatFontReadout(readout, S.readout) : S.readout.pending}+ </span>+ </div>+ );+}diff --git a/packages/ui-gallery/src/chrome/icons.tsx b/packages/ui-gallery/src/chrome/icons.tsxnew file mode 100644index 00000000..9f1d1929--- /dev/null+++ b/packages/ui-gallery/src/chrome/icons.tsx@@ -0,0 +1,55 @@+/**+ * The chrome's own glyphs: a 16px line icon at a fixed 1.5 stroke. They deliberately ignore+ * `--ui-icon-stroke` — the chrome must look the same whatever theme is under test.+ */+const PATHS = {+ link: "M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1",+ code: "m8 7-5 5 5 5M16 7l5 5-5 5",+ tokens:+ "M12 3a9 9 0 1 0 0 18c1.1 0 2-.9 2-2 0-.5-.2-1-.5-1.3-.3-.4-.5-.8-.5-1.3 0-1.1.9-2 2-2h2.4A4.6 4.6 0 0 0 22 9.8C22 5.9 17.5 3 12 3zM7.5 11.5h.01M10.5 7.5h.01M15.5 7.5h.01",+ check: "M5 13l4 4L19 7",+ copy: "M9 9h9v9a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V9zM7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1",+ sun: "M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 1v2M12 21v2M4.2 4.2l1.4 1.4M18.4 18.4l1.4 1.4M1 12h2M21 12h2M4.2 19.8l1.4-1.4M18.4 5.6l1.4-1.4",+ moon: "M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z",+ monitor: "M3 4h18v12H3zM8 20h8M12 16v4",+ phone:+ "M8 2.5h8a1.5 1.5 0 0 1 1.5 1.5v16a1.5 1.5 0 0 1-1.5 1.5H8A1.5 1.5 0 0 1 6.5 20V4A1.5 1.5 0 0 1 8 2.5zM10.5 18h3",+ external: "M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5",+ back: "M15 18 9 12l6-6",+ type: "M4 7V4h16v3M9 20h6M12 4v16",+ parts: "m12 3 9 5-9 5-9-5 9-5zM3 13l9 5 9-5M3 17.5l9 5 9-5",+ play: "M7 4.5v15l12-7.5z",+ pause: "M8 5v14M16 5v14",+ restart: "M3 12a9 9 0 1 0 2.64-6.36L3 8M3 3v5h5",+ previous: "M19 20 9 12l10-8zM5 19V5",+ next: "m5 4 10 8-10 8zM19 5v14",+ menu: "M4 7h16M4 12h16M4 17h16",+ close: "M6 6l12 12M18 6 6 18",+ search: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM21 21l-4.35-4.35",+ chevron: "m6 9 6 6 6-6",+ sliders: "M21 4h-7M10 4H3M21 12h-9M8 12H3M21 20h-5M12 20H3M14 2v4M8 10v4M16 18v4",+ pointer: "M5 3l7 17 2.5-7 7-2.5z",+ still: "M4 5h16v14H4zM8 15l3-3 2 2 3-4 4 5M9 9.5h.01",+ motion: "M3 12h4l3-8 4 16 3-8h4",+} as const;++export type ChromeIconName = keyof typeof PATHS;++export function ChromeIcon({ name, size = 16 }: { name: ChromeIconName; size?: number }) {+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ className="g-icon"+ >+ <path d={PATHS[name]} />+ </svg>+ );+}diff --git a/packages/ui-gallery/src/chrome/library-frame.tsx b/packages/ui-gallery/src/chrome/library-frame.tsxnew file mode 100644index 00000000..b3395bbe--- /dev/null+++ b/packages/ui-gallery/src/chrome/library-frame.tsx@@ -0,0 +1,76 @@+/**+ * A component library board in a frame: one `lib.html` document (src/library/main.tsx) — its+ * own root for the theme attributes, its own storage, the app's own stylesheet — opened on a+ * topic with the page's preferences in the URL (src/library/frame.ts). Laid out at the column's+ * width, unscaled, and as tall as what it paints, an open menu or dialog included: the frame+ * reports that height through a window message (src/library/frame-height.ts) and the page+ * sizes it to match, so the page scrolls, never the frame, and nothing opened inside is cut+ * off at the frame's edge.+ *+ * As with the app frames, a change of theme, mode, size or fonts changes the frame's URL and+ * the frame reloads with the new preferences.+ */+import { useEffect, useRef, useState } from "react";+import { LIBRARY_HEIGHT_MESSAGE, libraryFrameSrc } from "../library/frame";+import type { TopicId } from "../library/topics";+import { BASE } from "../lib/location";+import { useGallery } from "../state";+import { useText } from "../text";++/** The height a frame shows at until its board has reported one. */+const PENDING_HEIGHT = 240;++/** The frame's URL for a topic under the page's preferences. */+export function useLibraryFrameSrc(topic: TopicId): string {+ const { state } = useGallery();+ return libraryFrameSrc(+ BASE,+ {+ theme: state.theme,+ mode: state.mode,+ accent: state.accent,+ size: state.size,+ latin: state.latin,+ cjk: state.cjk,+ lang: state.lang,+ },+ topic,+ );+}++export function LibraryFrame({ topic, reloadKey = 0 }: { topic: TopicId; reloadKey?: number }) {+ const text = useText();+ const src = useLibraryFrameSrc(topic);+ const frame = useRef<HTMLIFrameElement>(null);+ const [height, setHeight] = useState<number | null>(null);++ useEffect(() => {+ setHeight(null);+ }, [src, reloadKey]);++ useEffect(() => {+ const onMessage = (event: MessageEvent) => {+ if (event.source !== frame.current?.contentWindow) return;+ const data: unknown = event.data;+ if (typeof data !== "object" || data === null) return;+ const { type, height: reported } = data as { type?: unknown; height?: unknown };+ if (type !== LIBRARY_HEIGHT_MESSAGE || typeof reported !== "number") return;+ setHeight(Math.ceil(reported));+ };+ window.addEventListener("message", onMessage);+ return () => window.removeEventListener("message", onMessage);+ }, []);++ return (+ <div className="g-lib" data-loaded={height !== null || undefined}>+ <iframe+ key={`${src}#${reloadKey}`}+ ref={frame}+ className="g-lib-frame"+ title={text.topic(topic).title}+ src={src}+ style={{ height: height ?? PENDING_HEIGHT }}+ />+ </div>+ );+}diff --git a/packages/ui-gallery/src/chrome/popover.tsx b/packages/ui-gallery/src/chrome/popover.tsxnew file mode 100644index 00000000..c4651e48--- /dev/null+++ b/packages/ui-gallery/src/chrome/popover.tsx@@ -0,0 +1,71 @@+/**+ * A disclosure in the top bar: an icon button that opens a panel under itself, right-aligned,+ * holding the controls that do not fit the bar. Not portaled — the bar is sticky, so the panel+ * scrolls with it and nothing clips it. It closes on a click outside, on Escape (focus returns to+ * the button) and when its button is pressed again. A click inside a select's list, which is+ * portaled to the body and so outside the panel's subtree, is not a click outside.+ */+import { useEffect, useId, useRef, useState } from "react";+import type { ReactNode } from "react";+import { ChromeIcon } from "./icons";+import type { ChromeIconName } from "./icons";++export function Popover({+ label,+ icon,+ children,+}: {+ label: string;+ icon: ChromeIconName;+ children: ReactNode;+}) {+ const [open, setOpen] = useState(false);+ const root = useRef<HTMLDivElement>(null);+ const button = useRef<HTMLButtonElement>(null);+ const panelId = useId();++ useEffect(() => {+ if (!open) return;+ const onPointerDown = (event: MouseEvent) => {+ const target = event.target;+ if (!(target instanceof Node)) return;+ if (root.current?.contains(target)) return;+ if (target instanceof Element && target.closest(".g-listbox")) return;+ setOpen(false);+ };+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ setOpen(false);+ button.current?.focus();+ };+ window.addEventListener("mousedown", onPointerDown);+ window.addEventListener("keydown", onKey);+ return () => {+ window.removeEventListener("mousedown", onPointerDown);+ window.removeEventListener("keydown", onKey);+ };+ }, [open]);++ return (+ <div ref={root} className="g-popover">+ <button+ ref={button}+ type="button"+ className="g-icon-button"+ aria-haspopup="dialog"+ aria-expanded={open}+ aria-controls={open ? panelId : undefined}+ aria-label={label}+ data-tooltip={open ? undefined : label}+ onClick={() => setOpen((current) => !current)}+ >+ <ChromeIcon name={icon} size={16} />+ </button>+ {open && (+ <div id={panelId} role="dialog" aria-label={label} className="g-popover-panel">+ {children}+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui-gallery/src/chrome/select.tsx b/packages/ui-gallery/src/chrome/select.tsxnew file mode 100644index 00000000..29d2e498--- /dev/null+++ b/packages/ui-gallery/src/chrome/select.tsx@@ -0,0 +1,211 @@+/**+ * The chrome's select, in the app's own idiom rather than the browser's: a drawn trigger that+ * shows the chosen option and a chevron, a panel listing the options with a check on the chosen+ * one, portaled to the body at fixed viewport coordinates so no drawer or panel clips it. What it+ * replaces is the native `<select>`, whose popup takes the platform's look, never the chrome's,+ * and cannot be told apart from the app's own drawn selects in a screenshot.+ *+ * Keyboard: on the trigger, Enter, Space or an arrow opens the list on the chosen option; in the+ * list, the arrows step, Home and End jump, a typed character jumps to the next option starting+ * with it, Enter or Space picks, Escape closes and Tab closes and moves on — every close puts the+ * focus back on the trigger first, so Tab continues from there rather than from the end of the+ * body, where the panel lives. Focus follows the active row (one option is in the tab order at a+ * time), so the row is what assistive technology reads. The panel also closes on a click outside+ * it, on a scroll that would move its trigger, and on a resize.+ */+import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";+import type { KeyboardEvent as ReactKeyboardEvent } from "react";+import { createPortal } from "react-dom";+import { nextOptionIndex, placePanel, typeaheadIndex } from "../lib/listbox";+import type { PanelPlacement } from "../lib/listbox";+import { ChromeIcon } from "./icons";++export interface SelectOption<T extends string> {+ value: T;+ label: string;+}++/** The rows' height and the panel's padding, as chrome.css draws them: only the flip decision reads them. */+const ROW_HEIGHT = 30;+const PANEL_PADDING = 8;++export function Select<T extends string>({+ label,+ value,+ options,+ onChange,+}: {+ /** The control's accessible name; the visible words beside it are the caller's. */+ label: string;+ value: T;+ options: readonly SelectOption<T>[];+ onChange: (value: T) => void;+}) {+ const [open, setOpen] = useState(false);+ const [active, setActive] = useState(0);+ const [placement, setPlacement] = useState<PanelPlacement | null>(null);+ const trigger = useRef<HTMLButtonElement>(null);+ const panel = useRef<HTMLDivElement>(null);+ const listId = useId();+ const selectedIndex = Math.max(+ 0,+ options.findIndex((option) => option.value === value),+ );+ const selected = options[selectedIndex];++ const show = () => {+ setActive(selectedIndex);+ setOpen(true);+ };+ const close = (refocus: boolean) => {+ setOpen(false);+ setPlacement(null);+ if (refocus) trigger.current?.focus();+ };+ const pick = (index: number) => {+ const option = options[index];+ if (option && option.value !== value) onChange(option.value);+ close(true);+ };++ useLayoutEffect(() => {+ if (!open || !trigger.current) return;+ setPlacement(+ placePanel(+ trigger.current.getBoundingClientRect(),+ { width: window.innerWidth, height: window.innerHeight },+ options.length * ROW_HEIGHT + PANEL_PADDING,+ ),+ );+ }, [open, options.length]);++ // The active row takes the focus once the panel is placed, and again whenever it moves.+ useEffect(() => {+ if (!open || !placement) return;+ const rows = panel.current?.querySelectorAll<HTMLElement>('[role="option"]');+ rows?.[active]?.focus({ preventScroll: true });+ }, [open, placement, active]);++ useEffect(() => {+ if (!open) return;+ const onPointerDown = (event: MouseEvent) => {+ const target = event.target as Node;+ if (trigger.current?.contains(target) || panel.current?.contains(target)) return;+ setOpen(false);+ setPlacement(null);+ };+ // The panel's own scrolling (a long list) keeps it open; any other scroll has moved the+ // trigger the panel was placed against, and so has a resize.+ const onScroll = (event: Event) => {+ if (panel.current?.contains(event.target as Node)) return;+ setOpen(false);+ setPlacement(null);+ };+ const onResize = () => {+ setOpen(false);+ setPlacement(null);+ };+ window.addEventListener("mousedown", onPointerDown);+ window.addEventListener("scroll", onScroll, true);+ window.addEventListener("resize", onResize);+ return () => {+ window.removeEventListener("mousedown", onPointerDown);+ window.removeEventListener("scroll", onScroll, true);+ window.removeEventListener("resize", onResize);+ };+ }, [open]);++ const onTriggerKey = (event: ReactKeyboardEvent<HTMLButtonElement>) => {+ if (["ArrowDown", "ArrowUp", "Enter", " "].includes(event.key)) {+ event.preventDefault();+ show();+ }+ };++ const onListKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ const next = nextOptionIndex(event.key, active, options.length);+ if (next !== null) {+ event.preventDefault();+ setActive(next);+ return;+ }+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ pick(active);+ return;+ }+ if (event.key === "Escape") {+ // Stopped here so the popover or drawer holding this select stays open.+ event.preventDefault();+ event.stopPropagation();+ close(true);+ return;+ }+ if (event.key === "Tab") {+ // Not prevented: the browser's own Tab then continues from the refocused trigger.+ close(true);+ return;+ }+ const hit = typeaheadIndex(+ event.key,+ options.map((option) => option.label),+ active,+ );+ if (hit !== null) setActive(hit);+ };++ return (+ <>+ <button+ ref={trigger}+ type="button"+ className="g-select"+ aria-haspopup="listbox"+ aria-expanded={open}+ aria-controls={open ? listId : undefined}+ aria-label={label}+ onClick={() => (open ? close(false) : show())}+ onKeyDown={onTriggerKey}+ >+ <span className="g-select-value">{selected?.label ?? ""}</span>+ <ChromeIcon name="chevron" size={13} />+ </button>+ {open &&+ placement &&+ createPortal(+ <div+ ref={panel}+ id={listId}+ role="listbox"+ aria-label={label}+ className="g-chrome g-listbox"+ style={{+ top: placement.top,+ bottom: placement.bottom,+ left: placement.left,+ minWidth: placement.minWidth,+ }}+ onKeyDown={onListKey}+ >+ {options.map((option, index) => (+ <button+ key={option.value}+ type="button"+ role="option"+ aria-selected={option.value === value}+ tabIndex={index === active ? 0 : -1}+ data-active={index === active || undefined}+ className="g-option"+ onMouseEnter={() => setActive(index)}+ onClick={() => pick(index)}+ >+ <span>{option.label}</span>+ {option.value === value && <ChromeIcon name="check" size={14} />}+ </button>+ ))}+ </div>,+ document.body,+ )}+ </>+ );+}diff --git a/packages/ui-gallery/src/chrome/sidenav.tsx b/packages/ui-gallery/src/chrome/sidenav.tsxnew file mode 100644index 00000000..7d8bea66--- /dev/null+++ b/packages/ui-gallery/src/chrome/sidenav.tsx@@ -0,0 +1,198 @@+/**+ * A section's left column: the links of the section the page is in, grouped, the current page+ * marked. Three sections have one — 界面 lists the app's surfaces under a search box (Ctrl/⌘ K+ * focuses it; it matches a title in either language and the id), 基础 lists the component+ * library's topics by group, 字体 lists the fonts pages. At phone width the drawer holds the same+ * list.+ */+import { useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";+import { SURFACE_GROUPS } from "../app/surfaces";+import { TOPIC_GROUPS } from "../library/topics";+import { BASE } from "../lib/location";+import { FONTS_PAGE_IDS, fontsHref, surfaceHref, topicHref } from "../lib/routes";+import type { FontsPageId } from "../lib/routes";+import { useGallery } from "../state";+import { zh } from "../strings";+import { en } from "../strings-en";+import { useText } from "../text";+import { ChromeIcon } from "./icons";++export interface NavLink {+ id: string;+ title: string;+ href: string;+}++/** One group of a list; a group without a title is the list's only one. */+export interface NavGroup {+ id: string;+ title?: string;+ links: NavLink[];+}++/** A section's navigation list, as every section renders it. */+export function SectionNav({+ label,+ groups,+ activeId,+ onNavigate,+ children,+}: {+ label: string;+ groups: readonly NavGroup[];+ /** The page this is, for the current mark. */+ activeId: string | null;+ /** A link was followed: the drawer closes. */+ onNavigate?: () => void;+ /** What sits above the groups: the surface list's search box, or what a search left empty. */+ children?: ReactNode;+}) {+ return (+ <nav className="g-nav" aria-label={label}>+ {children}+ {groups.map((group) => (+ <div key={group.id} className="g-nav-group">+ {group.title !== undefined && <span className="g-nav-eyebrow">{group.title}</span>}+ <ul>+ {group.links.map((link) => (+ <li key={link.id}>+ <a+ className="g-nav-link"+ href={link.href}+ aria-current={link.id === activeId ? "page" : undefined}+ onClick={onNavigate}+ >+ {link.title}+ </a>+ </li>+ ))}+ </ul>+ </div>+ ))}+ </nav>+ );+}++export function SurfaceNav({+ activeId,+ onNavigate,+}: {+ activeId: string | null;+ onNavigate?: () => void;+}) {+ const { S, state } = useGallery();+ const text = useText();+ const [query, setQuery] = useState("");+ const input = useRef<HTMLInputElement>(null);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {+ event.preventDefault();+ input.current?.focus();+ input.current?.select();+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ const needle = query.trim().toLowerCase();+ const matches = (...names: string[]) =>+ needle === "" || names.some((name) => name.toLowerCase().includes(needle));+ const groups: NavGroup[] = SURFACE_GROUPS.map((group) => ({+ id: group.id,+ title: text.surfaceGroup(group.id),+ links: group.surfaces.flatMap((surface) => {+ const title = text.surface(surface.id).title;+ return matches(+ title,+ zh.surfaces[surface.id].title,+ en.surfaces[surface.id].title,+ surface.id,+ )+ ? [{ id: surface.id, title, href: surfaceHref(BASE, state, surface.id) }]+ : [];+ }),+ })).filter((group) => group.links.length > 0);++ return (+ <SectionNav+ label={S.site.nav}+ groups={groups}+ activeId={activeId}+ {...(onNavigate ? { onNavigate } : {})}+ >+ <label className="g-search">+ <ChromeIcon name="search" size={14} />+ <input+ ref={input}+ type="search"+ placeholder={S.site.search}+ aria-label={S.site.search}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ <kbd>{S.site.searchShortcut}</kbd>+ </label>+ {groups.length === 0 && <p className="g-muted g-nav-empty">{S.site.noMatches}</p>}+ </SectionNav>+ );+}++export function TopicNav({+ activeId,+ onNavigate,+}: {+ activeId: string | null;+ onNavigate?: () => void;+}) {+ const { S, state } = useGallery();+ const text = useText();+ const groups: NavGroup[] = TOPIC_GROUPS.map((group) => ({+ id: group.id,+ title: text.topicGroup(group.id),+ links: group.topics.map((topic) => ({+ id: topic.id,+ title: text.topic(topic.id).title,+ href: topicHref(BASE, state, topic.id),+ })),+ }));+ return (+ <SectionNav+ label={S.library.title}+ groups={groups}+ activeId={activeId}+ {...(onNavigate ? { onNavigate } : {})}+ />+ );+}++export function FontsNav({+ activeId,+ onNavigate,+}: {+ activeId: FontsPageId;+ onNavigate?: () => void;+}) {+ const { S, state } = useGallery();+ const groups: NavGroup[] = [+ {+ id: "fonts",+ links: FONTS_PAGE_IDS.map((page) => ({+ id: page,+ title: S.fonts.pages[page],+ href: fontsHref(BASE, state, page),+ })),+ },+ ];+ return (+ <SectionNav+ label={S.site.fonts}+ groups={groups}+ activeId={activeId}+ {...(onNavigate ? { onNavigate } : {})}+ />+ );+}diff --git a/packages/ui-gallery/src/chrome/site.tsx b/packages/ui-gallery/src/chrome/site.tsxnew file mode 100644index 00000000..958e3566--- /dev/null+++ b/packages/ui-gallery/src/chrome/site.tsx@@ -0,0 +1,74 @@+/**+ * The site frame every page renders inside: the top bar, then the body — an optional left column+ * with the section's navigation list, the content column, and an optional right column ("on this+ * page") — and the tooltip layer the chrome's `data-tooltip` hints render through.+ *+ * At phone width the columns collapse: the left and right columns disappear, the content column+ * fills, and the menu button in the bar opens a drawer under it holding the page links, every+ * view control with its label and the section's list, closed again by a link, the button or+ * Escape.+ */+import { useEffect, useState } from "react";+import type { ReactNode } from "react";+import { useGallery } from "../state";+import { ChromeTooltips } from "./tooltip";+import { PageLinks, TopBar, ViewControls } from "./topbar";+import type { SitePage } from "./topbar";++export function Site({+ page,+ nav,+ toc,+ wide = false,+ children,+}: {+ page: SitePage;+ /** The section's navigation list, rendered in the left column and again in the drawer, which passes its close. */+ nav?: (onNavigate?: () => void) => ReactNode;+ /** The right column's content. */+ toc?: ReactNode;+ /** Let the content column grow past the reading width: a framed board needs the room. */+ wide?: boolean;+ children: ReactNode;+}) {+ const { S } = useGallery();+ const [open, setOpen] = useState(false);+ const close = () => setOpen(false);++ useEffect(() => {+ if (!open) return;+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") close();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [open]);++ return (+ <div+ className="g-site g-chrome"+ data-nav={nav ? true : undefined}+ data-toc={toc ? true : undefined}+ >+ <TopBar page={page} open={open} onToggle={() => setOpen((current) => !current)} />+ {open && (+ <div className="g-drawer">+ <nav className="g-drawer-links" aria-label={S.site.pages}>+ <PageLinks current={page} onNavigate={close} />+ </nav>+ <div className="g-drawer-controls">+ <span className="g-nav-eyebrow">{S.site.settings}</span>+ <ViewControls all />+ </div>+ {nav?.(close)}+ </div>+ )}+ <div className="g-body" data-wide={wide || undefined}>+ {nav && <aside className="g-sidenav">{nav()}</aside>}+ <main className="g-main">{children}</main>+ {toc && <aside className="g-toc">{toc}</aside>}+ </div>+ <ChromeTooltips />+ </div>+ );+}diff --git a/packages/ui-gallery/src/chrome/toc.tsx b/packages/ui-gallery/src/chrome/toc.tsxnew file mode 100644index 00000000..3a5e5cec--- /dev/null+++ b/packages/ui-gallery/src/chrome/toc.tsx@@ -0,0 +1,37 @@+/**+ * "On this page": the right column of a module page — its variants, then Parts, Tokens and+ * Source — the one in view marked by the scroll-spy (lib/use-scroll-spy.ts).+ */+import { useGallery } from "../state";++export interface TocItem {+ id: string;+ title: string;+}++export function OnThisPage({+ items,+ activeId,+}: {+ items: readonly TocItem[];+ activeId: string | null;+}) {+ const { S } = useGallery();+ return (+ <nav className="g-toc-list" aria-label={S.site.onThisPage}>+ <span className="g-toc-eyebrow">{S.site.onThisPage}</span>+ <ul>+ {items.map((item) => (+ <li key={item.id}>+ <a+ href={`#${encodeURIComponent(item.id)}`}+ data-active={item.id === activeId || undefined}+ >+ {item.title}+ </a>+ </li>+ ))}+ </ul>+ </nav>+ );+}diff --git a/packages/ui-gallery/src/chrome/tooltip.tsx b/packages/ui-gallery/src/chrome/tooltip.tsxnew file mode 100644index 00000000..b739fe52--- /dev/null+++ b/packages/ui-gallery/src/chrome/tooltip.tsx@@ -0,0 +1,110 @@+/**+ * The chrome's tooltips, one layer for the whole page: any element carrying `data-tooltip` gets a+ * drawn panel under it on hover and on keyboard focus, after a short delay — but only when the+ * hint adds something: the element shows no text of its own, or the text it shows is cut off+ * (lib/tip.ts, decided at the moment it would open, since truncation depends on the room the+ * element has right then). What it replaces is the native `title`, which waits about a second,+ * takes the platform's look and never shows on focus. Like `title`, the attribute names nothing+ * to assistive technology, so an element whose only name was its title carries an `aria-label`+ * with the same words.+ *+ * The panel is portaled to the body at fixed viewport coordinates and takes no pointer events, so+ * it never covers a click meant for what it describes, and it closes on leave, blur, Escape, a+ * press (the element is being used now, not asked about), any scroll and a resize — the last+ * three because it is placed once and would be stale the moment its trigger moved.+ */+import { useEffect, useState } from "react";+import { createPortal } from "react-dom";+import { placeTip, shouldHint } from "../lib/tip";+import type { TipPlacement } from "../lib/tip";++export const TOOLTIP_ATTR = "data-tooltip";++/**+ * Long enough that a pointer crossing the bar on its way elsewhere leaves no trail of panels,+ * short enough to answer a pointer that stopped to ask.+ */+const OPEN_DELAY_MS = 350;++/** The width a hint wraps at, before the room left on screen caps it further. */+const MAX_WIDTH = 280;++export function ChromeTooltips() {+ const [open, setOpen] = useState<{ label: string; at: TipPlacement } | null>(null);++ useEffect(() => {+ let current: Element | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const close = () => {+ if (timer !== null) clearTimeout(timer);+ timer = null;+ current = null;+ setOpen(null);+ };+ const holder = (node: EventTarget | null): Element | null =>+ node instanceof Element ? node.closest(`[${TOOLTIP_ATTR}]`) : null;+ const start = (node: Element | null) => {+ if (node === current) return;+ close();+ const label = node?.getAttribute(TOOLTIP_ATTR)?.trim() ?? "";+ if (node === null || label === "") return;+ const el: Element = node;+ current = el;+ timer = setTimeout(() => {+ timer = null;+ if (!el.isConnected) return;+ if (!shouldHint(el.textContent ?? "", [el, ...el.querySelectorAll("*")])) return;+ const viewport = { width: window.innerWidth, height: window.innerHeight };+ setOpen({ label, at: placeTip(el.getBoundingClientRect(), viewport) });+ }, OPEN_DELAY_MS);+ };+ const onOver = (event: PointerEvent) => start(holder(event.target));+ const onOut = (event: PointerEvent) => {+ if (current === null) return;+ const next = event.relatedTarget;+ if (next instanceof Node && current.contains(next)) return;+ close();+ };+ const onFocusIn = (event: FocusEvent) => start(holder(event.target));+ const onKey = (event: KeyboardEvent) => {+ // Heard, never stopped: the same press still reaches the popover or drawer behind it.+ if (event.key === "Escape") close();+ };+ document.addEventListener("pointerover", onOver);+ document.addEventListener("pointerout", onOut);+ document.addEventListener("pointerdown", close, true);+ document.addEventListener("focusin", onFocusIn);+ document.addEventListener("focusout", close);+ window.addEventListener("keydown", onKey, true);+ window.addEventListener("scroll", close, true);+ window.addEventListener("resize", close);+ return () => {+ close();+ document.removeEventListener("pointerover", onOver);+ document.removeEventListener("pointerout", onOut);+ document.removeEventListener("pointerdown", close, true);+ document.removeEventListener("focusin", onFocusIn);+ document.removeEventListener("focusout", close);+ window.removeEventListener("keydown", onKey, true);+ window.removeEventListener("scroll", close, true);+ window.removeEventListener("resize", close);+ };+ }, []);++ if (open === null) return null;+ return createPortal(+ <div+ className="g-chrome g-tip"+ aria-hidden+ style={{+ top: open.at.top,+ left: open.at.left,+ right: open.at.right,+ maxWidth: Math.min(MAX_WIDTH, open.at.room),+ }}+ >+ {open.label}+ </div>,+ document.body,+ );+}diff --git a/packages/ui-gallery/src/chrome/topbar.tsx b/packages/ui-gallery/src/chrome/topbar.tsxnew file mode 100644index 00000000..489a7d77--- /dev/null+++ b/packages/ui-gallery/src/chrome/topbar.tsx@@ -0,0 +1,280 @@+/**+ * The top bar every page shares (unthemed), one row: the brand and the page links — Home,+ * Surfaces, Foundations, Fonts, the current one marked — on the left; on the right the controls+ * a reviewer reaches for most, theme (by its display name), language and the mode switch, then a+ * button opening the rest in a popover: accent (the active theme's own presets, each painted in+ * its colour, after 随主题), text size (the five steps by name), the Latin and CJK font pairings,+ * the viewport, and under them the fonts the framed app is actually set in. Every control writes+ * the URL, and the frames reload with it.+ *+ * At phone width the links and controls leave the bar for the drawer (chrome/site.tsx), where+ * every control has its label, and a menu button opens it.+ */+import { THEME_IDS } from "@prismshadow/penguin-ui";+import type { ReactNode } from "react";+import { accentPresetsOf, accentSwatch, THEME_ACCENT } from "../lib/accents";+import { BASE } from "../lib/location";+import { FIRST_TOPIC } from "../library/topics";+import { HOME_SURFACE } from "../app/surfaces";+import { fontsHref, homeHref, surfaceHref, topicHref } from "../lib/routes";+import { CJK_FONTS, fontLabel, LATIN_FONTS, TEXT_SIZE_PX_NUMBER, TEXT_SIZES } from "../lib/themes";+import { LANGS, MODE_PREFS, VIEWS } from "../lib/url-state";+import type { ModePref } from "../lib/url-state";+import { useGallery } from "../state";+import { useText } from "../text";+import { Segmented, Swatches } from "./controls";+import { FontReadoutLine } from "./font-readout";+import { ChromeIcon } from "./icons";+import { Popover } from "./popover";+import { Select } from "./select";++const MODE_ICONS = { light: "sun", dark: "moon", system: "monitor" } as const;+const VIEW_ICONS = { desktop: "monitor", phone: "phone" } as const;++/** The page a link row marks as current. */+export type SitePage = "home" | "surfaces" | "foundations" | "fonts";++export function ModeSwitch() {+ const { S, state, update } = useGallery();+ return (+ <div className="g-mode" role="group" aria-label={S.rail.mode}>+ {MODE_PREFS.map((mode: ModePref) => (+ <button+ key={mode}+ type="button"+ aria-label={S.rail.modes[mode]}+ data-tooltip={S.rail.modes[mode]}+ aria-pressed={state.mode === mode}+ onClick={() => update({ mode })}+ >+ <ChromeIcon name={MODE_ICONS[mode]} size={15} />+ </button>+ ))}+ </div>+ );+}++function ThemeControl() {+ const { S, state, update } = useGallery();+ const text = useText();+ return (+ <Segmented+ label={S.rail.theme}+ value={state.theme}+ options={THEME_IDS.map((id) => ({ value: id, label: text.theme(id) }))}+ onChange={(theme) => update({ theme })}+ />+ );+}++function LanguageControl() {+ const { S, state, update } = useGallery();+ return (+ <Segmented+ label={S.rail.language}+ value={state.lang}+ options={LANGS.map((lang) => ({ value: lang, label: S.rail.langNames[lang] }))}+ onChange={(lang) => update({ lang })}+ />+ );+}++/**+ * The accent row: 随主题 first, painted in the theme's own accent, then the theme's presets, each+ * in the colour it applies in the current mode (the package's light swatch until the probe has+ * resolved the page's CSS).+ */+function AccentControl() {+ const { S, state, mode, accents, update } = useGallery();+ const resolved = accents?.[state.theme][mode] ?? {};+ const options = [THEME_ACCENT, ...accentPresetsOf(state.theme)].map((id) => ({+ value: id,+ label: id === THEME_ACCENT ? S.rail.accentTheme : id,+ color: resolved[id] || accentSwatch(state.theme, id),+ }));+ // A remembered preset the active theme does not list shows as 随主题, which is what applies.+ const shown = options.some((option) => option.value === state.accent)+ ? state.accent+ : THEME_ACCENT;+ return (+ <Swatches+ label={S.rail.accent}+ value={shown}+ options={options}+ onChange={(accent) => update({ accent })}+ />+ );+}++function SizeControl() {+ const { S, state, update } = useGallery();+ return (+ <Segmented+ label={S.rail.size}+ value={state.size}+ options={TEXT_SIZES.map((size) => ({+ value: size,+ label: S.rail.sizeNames[size],+ hint: S.rail.sizeTitle(S.rail.sizeNames[size], TEXT_SIZE_PX_NUMBER[size]),+ }))}+ onChange={(size) => update({ size })}+ />+ );+}++function ViewportControl() {+ const { S, state, update } = useGallery();+ return (+ <Segmented+ label={S.rail.viewport}+ value={state.view}+ options={VIEWS.map((view) => ({+ value: view,+ label: (+ <span className="g-seg-icon">+ <ChromeIcon name={VIEW_ICONS[view]} size={13} />+ {S.rail.viewports[view]}+ </span>+ ),+ }))}+ onChange={(view) => update({ view })}+ />+ );+}++/** One labelled row of the popover or the drawer. */+function Control({ label, children }: { label: string; children: ReactNode }) {+ return (+ <div className="g-control">+ <span className="g-control-label">{label}</span>+ {children}+ </div>+ );+}++/**+ * The labelled rows: the secondary controls — accent, size, the two font pairings, viewport —+ * or, in the drawer, every control. The fonts in use close the list.+ */+export function ViewControls({ all = false }: { all?: boolean }) {+ const { S, state, update } = useGallery();+ const fontWords = { theme: S.rail.fontTheme, system: S.rail.fontSystem };+ return (+ <>+ <div className="g-controls">+ {all && (+ <>+ <Control label={S.rail.theme}>+ <ThemeControl />+ </Control>+ <Control label={S.rail.mode}>+ <ModeSwitch />+ </Control>+ <Control label={S.rail.language}>+ <LanguageControl />+ </Control>+ </>+ )}+ <Control label={S.rail.accent}>+ <AccentControl />+ </Control>+ <Control label={S.rail.size}>+ <SizeControl />+ </Control>+ <Control label={S.rail.fontLatin}>+ <Select+ label={S.rail.fontLatin}+ value={state.latin}+ options={LATIN_FONTS.map((id) => ({ value: id, label: fontLabel(id, fontWords) }))}+ onChange={(latin) => update({ latin })}+ />+ </Control>+ <Control label={S.rail.fontCjk}>+ <Select+ label={S.rail.fontCjk}+ value={state.cjk}+ options={CJK_FONTS.map((id) => ({ value: id, label: fontLabel(id, fontWords) }))}+ onChange={(cjk) => update({ cjk })}+ />+ </Control>+ <Control label={S.rail.viewport}>+ <ViewportControl />+ </Control>+ </div>+ <div className="g-controls-foot">+ <FontReadoutLine />+ </div>+ </>+ );+}++/**+ * The section links, each carrying the view state, the current section marked: 界面 opens the+ * chat surface's page, 基础 the library's first topic, 字体 the fonts defaults.+ */+export function PageLinks({ current, onNavigate }: { current: SitePage; onNavigate?: () => void }) {+ const { S, state } = useGallery();+ const links: { page: SitePage; label: string; href: string }[] = [+ { page: "home", label: S.site.home, href: homeHref(BASE, state) },+ { page: "surfaces", label: S.site.surfaces, href: surfaceHref(BASE, state, HOME_SURFACE) },+ { page: "foundations", label: S.site.foundations, href: topicHref(BASE, state, FIRST_TOPIC) },+ { page: "fonts", label: S.site.fonts, href: fontsHref(BASE, state, "defaults") },+ ];+ return (+ <>+ {links.map((link) => (+ <a+ key={link.page}+ className="g-link"+ href={link.href}+ aria-current={link.page === current ? "page" : undefined}+ onClick={onNavigate}+ >+ {link.label}+ </a>+ ))}+ </>+ );+}++export function TopBar({+ page,+ open,+ onToggle,+}: {+ page: SitePage;+ /** The phone drawer is open. */+ open: boolean;+ onToggle: () => void;+}) {+ const { S, state } = useGallery();+ return (+ <header className="g-topbar">+ <a className="g-brand" href={homeHref(BASE, state)}>+ <img src={`${BASE}/penguin-logo.svg`} alt="" width={24} height={24} />+ <strong>{S.brand.title}</strong>+ </a>+ <nav className="g-links" aria-label={S.site.pages}>+ <PageLinks current={page} />+ </nav>+ <div className="g-bar-controls">+ <ThemeControl />+ <LanguageControl />+ <ModeSwitch />+ <Popover label={S.site.settings} icon="sliders">+ <ViewControls />+ </Popover>+ </div>+ <button+ type="button"+ className="g-icon-button g-menu"+ aria-label={open ? S.site.closeMenu : S.site.menu}+ data-tooltip={open ? S.site.closeMenu : S.site.menu}+ aria-expanded={open}+ onClick={onToggle}+ >+ <ChromeIcon name={open ? "close" : "menu"} />+ </button>+ </header>+ );+}diff --git a/packages/ui-gallery/src/foundations/color.tsx b/packages/ui-gallery/src/foundations/color.tsxnew file mode 100644index 00000000..7a46fa54--- /dev/null+++ b/packages/ui-gallery/src/foundations/color.tsx@@ -0,0 +1,270 @@+/**+ * Foundations › Colour: the palette as it is used, not as a list. The four surfaces stacked with+ * the three inks and the three lines drawn on each; the accent — the theme's own and the five+ * presets the active theme lists, in the mode under review — as a filled button and a selected+ * row, and the link; the six tones as a dot, a word and the soft / outline / solid badge; the+ * chart series as bars; the code and diff colours on a hunk. Every value, with its contrast+ * ratios, is in the tokens drawer.+ */+import { ACCENT_PRESETS, TONES } from "@prismshadow/penguin-ui";+import type { ThemeId, ThemeModeName, ToneName } from "@prismshadow/penguin-ui";+import type { CSSProperties } from "react";+import geekCss from "../../../ui/src/themes/geek.css?raw";+import githubCss from "../../../ui/src/themes/github.css?raw";+import modernCss from "../../../ui/src/themes/modern.css?raw";+import { useGallery } from "../state";+import { BoardGroup } from "./shared";++const SURFACES = ["--ui-canvas", "--ui-surface", "--ui-surface-muted", "--ui-inset"] as const;+const INKS = ["--ui-fg", "--ui-fg-muted", "--ui-fg-subtle"] as const;+const LINES = ["--ui-line", "--ui-line-muted", "--ui-line-emphasis"] as const;++/** Each theme file's source: its presets are read from it, the way the contract test reads them. */+const THEME_CSS: Readonly<Record<ThemeId, string>> = {+ github: githubCss,+ modern: modernCss,+ geek: geekCss,+};++/**+ * The six accent tokens a preset sets under a theme in a mode, as inline custom properties: the+ * `[data-accent="<id>"] { … }` rule of the theme's file, overlaid in dark with the+ * `[data-accent="<id>"].dark { … }` rule when the theme lifts the preset. A specimen carrying them+ * paints the preset without touching the root, which stays on the reader's own choice.+ */+function presetStyle(theme: ThemeId, preset: string, mode: ThemeModeName): CSSProperties {+ const css = THEME_CSS[theme];+ const style: Record<string, string> = {};+ const overlay = (dark: boolean) => {+ const tail = dark ? String.raw`\.dark` : "";+ const block =+ new RegExp(String.raw`\[data-accent="${preset}"\]${tail}\s*\{([^}]*)\}`).exec(css)?.[1] ?? "";+ for (const match of block.matchAll(/(--ui-accent[\w-]*):\s*([^;]+);/g)) {+ style[match[1]!] = match[2]!.trim();+ }+ };+ overlay(false);+ if (mode === "dark") overlay(true);+ return style as CSSProperties;+}++const tone = (name: ToneName, part: string) => `var(--ui-tone-${name}-${part})`;++/** Bar heights for the six chart series: a plausible week, not a gradient. */+const BARS = [72, 48, 88, 36, 60, 24];++function Surfaces() {+ const { S } = useGallery();+ return (+ <div>+ <div className="gf-surfaces-head gf-caption">+ <span />+ <span>{S.foundations.inks}</span>+ <span>{S.foundations.lines}</span>+ </div>+ <div className="gf-surfaces">+ {SURFACES.map((surface) => (+ <div key={surface} className="gf-surface" style={{ background: `var(${surface})` }}>+ <code className="gf-caption gf-mono">{surface.slice(5)}</code>+ <span className="gf-inks">+ {INKS.map((ink, i) => (+ <span key={ink} style={{ color: `var(${ink})` }}>+ {S.foundations.inkWords[i]}+ </span>+ ))}+ </span>+ <span className="gf-lines">+ {LINES.map((line) => (+ <span key={line} className="gf-line" style={{ borderColor: `var(${line})` }}>+ <span className="gf-caption gf-mono">+ {line === "--ui-line" ? "line" : line.slice("--ui-line-".length)}+ </span>+ </span>+ ))}+ </span>+ </div>+ ))}+ </div>+ </div>+ );+}++function Accents() {+ const { S, state, mode } = useGallery();+ const columns = [+ { key: "theme", label: S.foundations.themeAccent, style: {} },+ ...ACCENT_PRESETS[state.theme].map((preset) => ({+ key: preset.id,+ label: preset.id,+ style: presetStyle(state.theme, preset.id, mode),+ })),+ ];+ return (+ <>+ <div className="gf-accents">+ {columns.map((column) => (+ <div key={column.key} className="gf-accent" style={column.style}>+ <span className="gf-caption gf-mono">{column.label}</span>+ <span className="gf-accent-button">{S.foundations.sampleSend}</span>+ <span className="gf-accent-row">{S.foundations.selectedRow}</span>+ </div>+ ))}+ </div>+ <p className="gf-links">+ <a href="#colour" onClick={(event) => event.preventDefault()} className="gf-link">+ {S.foundations.sampleLink}+ </a>+ <span className="gf-link" data-hover>+ {S.foundations.sampleLink}+ </span>+ <span className="gf-caption">{S.foundations.linkHover}</span>+ </p>+ </>+ );+}++function Tones() {+ const { S } = useGallery();+ return (+ <div className="gf-tones">+ {TONES.map((name) => {+ const word = S.foundations.toneWords[name];+ return (+ <div key={name} className="gf-tone">+ <code className="gf-caption gf-mono">{name}</code>+ <span className="gf-tone-mark" style={{ color: tone(name, "fg") }}>+ <span className="gf-dot" />+ {word}+ </span>+ <span+ className="gf-badge"+ style={{ color: tone(name, "fg"), background: tone(name, "bg") }}+ >+ {word}+ </span>+ <span+ className="gf-badge"+ style={{+ color: tone(name, "fg"),+ borderColor: tone(name, "line"),+ background: "transparent",+ }}+ >+ {word}+ </span>+ <span+ className="gf-badge"+ style={{+ color: tone(name, "emphasis-fg"),+ background: tone(name, "emphasis"),+ borderColor: tone(name, "emphasis"),+ }}+ >+ {word}+ </span>+ </div>+ );+ })}+ </div>+ );+}++function Charts() {+ const { S } = useGallery();+ return (+ <div className="gf-charts">+ <div>+ <div className="gf-bars" role="img" aria-label={S.foundations.charts}>+ {BARS.map((height, i) => (+ <span+ key={i}+ className="gf-bar"+ style={{ height: `${height}%`, background: `var(--ui-chart-${i + 1})` }}+ />+ ))}+ </div>+ <div className="gf-bar-captions gf-caption gf-mono">+ {BARS.map((_, i) => (+ <span key={i}>{i + 1}</span>+ ))}+ </div>+ </div>+ <div className="gf-stacked">+ <span className="gf-caption">{S.foundations.tokenSeries}</span>+ <span className="gf-stacked-bar">+ <span style={{ flexGrow: 62, background: "var(--ui-chart-cache-read)" }} />+ <span style={{ flexGrow: 14, background: "var(--ui-chart-cache-write)" }} />+ <span style={{ flexGrow: 24, background: "var(--ui-chart-output)" }} />+ </span>+ <span className="gf-legend gf-caption">+ {(["cache-read", "cache-write", "output"] as const).map((series) => (+ <span key={series}>+ <span className="gf-swatch" style={{ background: `var(--ui-chart-${series})` }} />+ {series}+ </span>+ ))}+ </span>+ </div>+ </div>+ );+}++function Code() {+ const { S } = useGallery();+ const hunk = S.foundations.codeLines;+ return (+ <div className="gf-code">+ <div className="gf-code-line" style={{ background: "var(--ui-diff-hunk-bg)" }}>+ <span className="gf-gutter" />+ <span className="gf-subtle">@@ -38,3 +38,5 @@</span>+ </div>+ <div className="gf-code-line" style={{ background: "var(--ui-diff-del-bg)" }}>+ <span className="gf-gutter">38</span>+ <span>+ {hunk.before}+ <mark style={{ background: "var(--ui-diff-del-word)" }}>{hunk.removed}</mark>+ {hunk.after}+ </span>+ </div>+ <div className="gf-code-line" style={{ background: "var(--ui-diff-add-bg)" }}>+ <span className="gf-gutter">38</span>+ <span>+ {hunk.before}+ <mark style={{ background: "var(--ui-diff-add-word)" }}>{hunk.added}</mark>+ {hunk.after}+ </span>+ </div>+ <div className="gf-code-line">+ <span className="gf-gutter">39</span>+ <span>+ <mark style={{ background: "var(--ui-code-selection)" }}>{hunk.selected}</mark>+ </span>+ </div>+ </div>+ );+}++export function ColourBoard() {+ const { S } = useGallery();+ return (+ <div className="gf-board">+ <BoardGroup title={S.foundations.surfaces}>+ <Surfaces />+ </BoardGroup>+ <BoardGroup title={S.foundations.accent} aside={S.foundations.presetsHint}>+ <Accents />+ </BoardGroup>+ <BoardGroup title={S.foundations.tones}>+ <Tones />+ </BoardGroup>+ <div className="gf-pair">+ <BoardGroup title={S.foundations.charts}>+ <Charts />+ </BoardGroup>+ <BoardGroup title={S.foundations.code}>+ <Code />+ </BoardGroup>+ </div>+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/density.tsx b/packages/ui-gallery/src/foundations/density.tsxnew file mode 100644index 00000000..936df749--- /dev/null+++ b/packages/ui-gallery/src/foundations/density.tsx@@ -0,0 +1,138 @@+/**+ * Foundations › Spacing: the five rhythm steps as a ruler over a real settings page — a glyph welded+ * to its label (stack-0), related rows (stack-1), a row group under its section title (stack-2), one+ * section after another (stack-3) and the page header above the content (stack-4) — so it shows that+ * siblings of different kinds never share a gap. Below it, the theme's space unit at one, two, four+ * and eight (every `h-8` and `px-2` is a multiple of it, so this is where a theme's density starts)+ * and the control rungs with their measured heights — each theme's own, since nothing about size+ * is shared between themes.+ */+import type { CSSProperties, ReactNode } from "react";+import { useGallery } from "../state";+import { BoardGroup, Glyph, Measured } from "./shared";++const GLYPHS = {+ sun: "M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41",+ type: "M4 7V4h16v3M9 20h6M12 4v16",+ bell: "M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.94 1.94 0 0 0 3.4 0",+ globe:+ "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20ZM2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10Z",+} as const;++/** A gap drawn as a measured band: its height is the step, its label names it. */+function Gap({ step }: { step: 0 | 1 | 2 | 3 | 4 }) {+ return (+ <div className="gf-gap" style={{ height: `var(--ui-stack-${step})` }}>+ <span className="gf-gap-label gf-caption gf-mono">stack-{step}</span>+ </div>+ );+}++function Row({+ glyph,+ label,+ value,+}: {+ glyph: keyof typeof GLYPHS;+ label: string;+ value: ReactNode;+}) {+ return (+ <div className="gf-pref">+ <span className="gf-pref-label">+ <Glyph d={GLYPHS[glyph]} size={15} />+ <span className="gf-gap-inline" style={{ width: "var(--ui-stack-0)" }} />+ {label}+ </span>+ {value}+ </div>+ );+}++function Segments({ options, value }: { options: readonly string[]; value: number }) {+ return (+ <span className="gf-segmented">+ {options.map((option, i) => (+ <span key={option} data-active={i === value || undefined}>+ {option}+ </span>+ ))}+ </span>+ );+}++const RUNGS = [+ { rung: "sm", text: "small" },+ { rung: "md", text: "body" },+ { rung: "lg", text: "body" },+] as const;++const UNITS = [1, 2, 4, 8] as const;++export function SpacingBoard() {+ const { S } = useGallery();+ const t = S.foundations.spacingPage;+ return (+ <div className="gf-board">+ <div className="gf-ruler">+ <h3 className="gf-page-title">{t.title}</h3>+ <Gap step={4} />+ <h4 className="gf-section-title">{t.appearance}</h4>+ <Gap step={2} />+ <Row glyph="sun" label={t.theme} value={<Segments options={t.themeOptions} value={2} />} />+ <Gap step={1} />+ <Row+ glyph="type"+ label={t.fontSize}+ value={<Segments options={t.sizeOptions} value={1} />}+ />+ <Gap step={3} />+ <h4 className="gf-section-title">{t.general}</h4>+ <Gap step={2} />+ <Row+ glyph="globe"+ label={t.language}+ value={<Segments options={t.languageOptions} value={0} />}+ />+ <Gap step={1} />+ <Row glyph="bell" label={t.notifications} value={<span className="gf-switch" data-on />} />+ <p className="gf-caption gf-note gf-ruler-note">{S.foundations.stack0Note}</p>+ </div>+ <BoardGroup title={S.foundations.spaceUnit} aside={S.foundations.spaceUnitNote}>+ <div className="gf-units">+ {UNITS.map((n) => (+ <span key={n} className="gf-unit">+ <span className="gf-caption gf-mono">× {n}</span>+ <Measured+ className="gf-unit-bar"+ style={{ height: `calc(var(--ui-space-unit) * ${n})` }}+ />+ </span>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={S.foundations.controlHeights}>+ <div className="gf-rungs">+ {RUNGS.map(({ rung, text }) => (+ <span key={rung} className="gf-rung">+ <span className="gf-caption gf-mono">{rung}</span>+ <Measured+ className="gf-control"+ style={+ {+ paddingBlock: `var(--ui-control-py-${rung})`,+ paddingInline: `var(--ui-control-px-${rung})`,+ fontSize: `var(--ui-text-${text}-size)`,+ lineHeight: `var(--ui-text-${text}-lh)`,+ } as CSSProperties+ }+ >+ {S.foundations.scene.primary}+ </Measured>+ </span>+ ))}+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/focus.tsx b/packages/ui-gallery/src/foundations/focus.tsxnew file mode 100644index 00000000..982dd510--- /dev/null+++ b/packages/ui-gallery/src/foundations/focus.tsx@@ -0,0 +1,51 @@+/**+ * Foundations › Focus: the focus ring drawn permanently on a primary and a secondary button and on+ * a link, the input focus treatment, a text selection, and a scroll box wearing the theme's+ * scrollbar.+ */+import { useGallery } from "../state";+import { BoardGroup } from "./shared";+import { SPECIMENS } from "./specimens";++export function FocusBoard() {+ const { S, state } = useGallery();+ const specimen = SPECIMENS[state.lang];+ // Select a run of whole words (Chinese has no spaces, so it falls back to a fixed slice).+ const text = specimen.paragraph;+ const from = text.indexOf(" ", 20) > 0 ? text.indexOf(" ", 20) + 1 : 20;+ const to = text.indexOf(" ", from + 30) > 0 ? text.indexOf(" ", from + 30) : from + 30;+ return (+ <div className="gf-board">+ <div className="gf-pair">+ <BoardGroup title={S.foundations.focusRing}>+ <div className="gf-controls">+ <span className="gf-button gf-focused" data-variant="primary">+ {S.foundations.scene.primary}+ </span>+ <span className="gf-button gf-focused">{S.foundations.scene.secondary}</span>+ <span className="gf-link gf-focused">{S.foundations.sampleLink}</span>+ </div>+ </BoardGroup>+ <BoardGroup title={S.foundations.inputFocus}>+ <span className="gf-input gf-input-focused">{S.foundations.scene.input}</span>+ </BoardGroup>+ </div>+ <div className="gf-pair">+ <BoardGroup title={S.foundations.selection}>+ <p className="gf-selection">+ {text.slice(0, from)}+ <mark>{text.slice(from, to)}</mark>+ {text.slice(to)}+ </p>+ </BoardGroup>+ <BoardGroup title={S.foundations.scrollbar}>+ <div className="gf-scroll" tabIndex={0}>+ {Array.from({ length: 12 }, (_, i) => (+ <p key={i}>{specimen.ui}</p>+ ))}+ </div>+ </BoardGroup>+ </div>+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/foundations.css b/packages/ui-gallery/src/foundations/foundations.cssnew file mode 100644index 00000000..efe1d489--- /dev/null+++ b/packages/ui-gallery/src/foundations/foundations.css@@ -0,0 +1,1342 @@+/*+ * The Foundations boards. They render inside the themed preview, so they are the opposite of the+ * chrome: lengths are rem (they follow the root size under test) and colours are the theme's+ * tokens, read bare — an undefined token must look broken, not fall back to something plausible.+ */++/* ---- Board layout ---- */++.gf-board {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ gap: 2.5rem;+}+.gf-group {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ gap: 0.75rem;+ align-content: start;+ min-width: 0;+}+.gf-group-head {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0.25rem 0.75rem;+}+.gf-group-head h3 {+ margin: 0;+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ font-weight: var(--ui-weight-medium);+ color: var(--ui-fg);+}+.gf-aside {+ font-size: var(--ui-text-caption-size);+ line-height: var(--ui-text-caption-lh);+ color: var(--ui-fg-subtle);+}+.gf-group-action {+ margin-left: auto;+}+.gf-replay {+ padding: var(--ui-control-py-sm) var(--ui-control-px-sm);+ border: 1px solid var(--ui-line-emphasis);+ border-radius: var(--ui-radius-control);+ background: var(--ui-surface);+ color: var(--ui-fg);+ font: inherit;+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ font-weight: var(--ui-weight-medium);+ white-space: nowrap;+ cursor: pointer;+ transition: background-color var(--ui-dur-fast) var(--ui-ease-out);+}+.gf-replay:hover {+ background: var(--ui-surface-muted);+}+.gf-pair {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(17rem, 1fr));+ gap: 2.5rem 2rem;+}+.gf-caption {+ font-size: var(--ui-text-caption-size);+ line-height: var(--ui-text-caption-lh);+ color: var(--ui-fg-muted);+}+.gf-mono {+ font-family: var(--ui-font-mono);+}+.gf-muted {+ color: var(--ui-fg-muted);+}+.gf-subtle {+ color: var(--ui-fg-subtle);+}+.gf-note {+ margin: 0;+}+.gf-glyph {+ display: block;+ flex-shrink: 0;+}++/* ---- Colour ---- */++.gf-surfaces-head,+.gf-surface {+ display: grid;+ grid-template-columns: 6.5rem minmax(0, 1fr) minmax(0, 1fr);+ align-items: center;+ gap: 1rem;+ padding: 0 1rem;+}+.gf-surfaces-head {+ margin-bottom: -0.25rem;+}+.gf-surfaces {+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ overflow: hidden;+}+.gf-surface {+ padding-block: 0.875rem;+}+.gf-surface + .gf-surface {+ border-top: 1px solid var(--ui-line);+}+.gf-inks {+ display: flex;+ flex-wrap: wrap;+ gap: 0.25rem 1rem;+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+}+.gf-lines {+ display: flex;+ gap: 0.5rem;+}+.gf-line {+ flex: 1;+ display: grid;+ place-items: center;+ height: 2rem;+ border: 1px solid;+ border-radius: var(--ui-radius-sm);+}+.gf-line .gf-caption {+ color: var(--ui-fg-subtle);+}++/* Six columns where they fit (the theme's own accent and its five presets); at phone width the+ columns wrap to two or three rows rather than squeezing the samples. */+.gf-accents {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(5.5rem, 1fr));+ gap: 1rem 0.75rem;+}+.gf-accent {+ display: grid;+ gap: 0.5rem;+ justify-items: start;+ min-width: 0;+}+.gf-accent-button {+ padding: var(--ui-control-py-md) var(--ui-control-px-md);+ border-radius: var(--ui-radius-control);+ background: var(--ui-accent);+ color: var(--ui-accent-fg);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ font-weight: var(--ui-weight-medium);+}+.gf-accent-row {+ justify-self: stretch;+ padding: var(--ui-row-py) var(--ui-row-px);+ border-radius: var(--ui-radius-md);+ background: var(--ui-accent-muted);+ color: var(--ui-fg);+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.gf-links {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0.5rem 1rem;+ margin: 0.25rem 0 0;+ font-size: var(--ui-text-body-size);+}+.gf-link {+ color: var(--ui-fg-link);+ text-decoration: underline;+ text-decoration-color: color-mix(in srgb, currentColor 40%, transparent);+ text-underline-offset: 0.2em;+}+.gf-link[data-hover] {+ color: var(--ui-fg-link-hover);+ text-decoration-color: currentColor;+}++.gf-tones {+ display: grid;+ grid-template-columns: 5rem 7rem repeat(3, max-content);+ align-items: center;+ gap: 0.625rem 1rem;+}+.gf-tone {+ display: contents;+}+.gf-tone-mark {+ display: inline-flex;+ align-items: center;+ gap: var(--ui-stack-0);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ font-weight: var(--ui-weight-medium);+}+.gf-dot {+ width: 0.5rem;+ height: 0.5rem;+ flex-shrink: 0;+ border-radius: 999px;+ background: currentColor;+}+.gf-badge {+ display: inline-flex;+ align-items: center;+ height: 1.375rem;+ padding: 0 0.5rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-pill);+ font-size: var(--ui-text-caption-size);+ font-weight: var(--ui-weight-medium);+ line-height: 1;+ white-space: nowrap;+}++.gf-charts {+ display: grid;+ gap: 1.25rem;+}+.gf-bars {+ display: flex;+ align-items: flex-end;+ gap: 0.75rem;+ height: 6.5rem;+ padding: 0 0.5rem;+ border-top: 1px solid var(--ui-chart-grid);+ border-bottom: 1px solid var(--ui-chart-axis);+}+.gf-bar {+ flex: 1;+ min-width: 0;+ border-radius: var(--ui-radius-xs) var(--ui-radius-xs) 0 0;+}+.gf-bar-captions {+ display: flex;+ gap: 0.75rem;+ margin-top: 0.25rem;+ padding: 0 0.5rem;+}+.gf-bar-captions > span {+ flex: 1;+ text-align: center;+}+.gf-stacked {+ display: grid;+ gap: 0.375rem;+}+.gf-stacked-bar {+ display: flex;+ height: 0.75rem;+ border-radius: var(--ui-radius-xs);+ overflow: hidden;+}+.gf-legend {+ display: flex;+ flex-wrap: wrap;+ gap: 0.25rem 1rem;+}+.gf-legend > span {+ display: inline-flex;+ align-items: center;+ gap: var(--ui-stack-0);+}+.gf-swatch {+ width: 0.625rem;+ height: 0.625rem;+ border-radius: var(--ui-radius-xs);+}++.gf-code {+ display: grid;+ padding: 0.375rem 0;+ border: 1px solid var(--ui-code-line);+ border-radius: var(--ui-radius-md);+ background: var(--ui-code-bg);+ font-family: var(--ui-font-mono);+ font-size: var(--ui-text-code-size);+ line-height: var(--ui-text-code-lh);+ color: var(--ui-fg);+ overflow-x: auto;+}+.gf-code-line {+ display: flex;+ gap: 0.75rem;+ padding: 0 0.75rem;+ white-space: pre;+}+.gf-gutter {+ width: 1.25rem;+ flex-shrink: 0;+ text-align: right;+ color: var(--ui-code-gutter);+}+.gf-code mark {+ color: inherit;+}++/* ---- Type ---- */++.gf-type {+ display: grid;+ grid-template-columns: 3.5rem minmax(0, 1fr) minmax(0, 1fr);+ column-gap: 1.5rem;+ align-items: start;+}+.gf-type > .gf-caption {+ padding-bottom: 0.5rem;+}+.gf-type-row {+ display: contents;+}+.gf-type-row > * {+ min-width: 0;+ margin: 0;+ padding-block: 0.75rem;+ border-top: 1px solid var(--ui-line-muted);+ overflow-wrap: anywhere;+}+.gf-type-row > code {+ padding-top: 1rem;+}++/* ---- Shape & depth ---- */++.gf-scene {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr));+ gap: 1rem;+}+.gf-scene-page,+.gf-scene-modal {+ position: relative;+ min-height: 24rem;+ padding: 2.25rem 1rem 1rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-canvas);+ overflow: hidden;+}+.gf-tier {+ position: absolute;+ top: 0.625rem;+ left: 1rem;+ z-index: 2;+ white-space: nowrap;+}+.gf-card {+ position: relative;+ display: grid;+ gap: 0.75rem;+ padding: var(--ui-card-p);+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-surface);+ box-shadow: var(--ui-shadow-raised);+}+.gf-card-head {+ display: flex;+ align-items: baseline;+ gap: 0.5rem;+ font-size: var(--ui-text-body-size);+}+.gf-card-head > .gf-caption {+ flex: 1;+}+.gf-more {+ color: var(--ui-fg-muted);+ letter-spacing: 0.1em;+}+.gf-nested {+ padding: 0.5rem 0.75rem;+ border-radius: max(var(--ui-radius-xs), calc(var(--ui-radius-lg) - var(--ui-card-p)));+ background: var(--ui-surface-muted);+}+.gf-controls {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.5rem;+}+.gf-controls-end {+ justify-content: flex-end;+}+.gf-button {+ display: inline-flex;+ align-items: center;+ padding: var(--ui-control-py-sm) var(--ui-control-px-sm);+ border: 1px solid var(--ui-line-emphasis);+ border-radius: var(--ui-radius-control);+ background: var(--ui-surface);+ color: var(--ui-fg);+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ font-weight: var(--ui-weight-medium);+ white-space: nowrap;+}+.gf-button[data-variant="primary"] {+ border-color: var(--ui-accent);+ background: var(--ui-accent);+ color: var(--ui-accent-fg);+}+.gf-button[data-variant="danger"] {+ border-color: var(--ui-tone-danger-emphasis);+ background: var(--ui-tone-danger-emphasis);+ color: var(--ui-tone-danger-emphasis-fg);+}+.gf-input {+ display: flex;+ min-width: 9rem;+ padding: var(--ui-control-py-sm) var(--ui-control-px-sm);+ border: 1px solid var(--ui-line-emphasis);+ border-radius: var(--ui-radius-md);+ background: var(--ui-surface);+ color: var(--ui-fg-subtle);+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+}+/* Hung from the card's bottom-right corner, so no label is cut in half at any theme's row heights. */+.gf-menu {+ position: absolute;+ top: calc(100% - 1.75rem);+ right: -0.75rem;+ display: grid;+ gap: 0.125rem;+ width: 9.5rem;+ padding: 0.25rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-md);+ background: var(--ui-overlay);+ box-shadow: var(--ui-shadow-overlay);+}+.gf-layer-tier {+ padding: 0.25rem var(--ui-menu-row-px) 0.125rem;+ border-top: 1px solid var(--ui-line-muted);+}+.gf-menu-row {+ padding: var(--ui-menu-row-py) var(--ui-menu-row-px);+ border-radius: max(var(--ui-radius-xs), calc(var(--ui-radius-md) - 0.25rem));+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+}+.gf-menu-row[data-active] {+ background: var(--ui-surface-muted);+}+.gf-scene-lines {+ position: absolute;+ inset: 2.25rem 1rem auto;+ display: grid;+ gap: 0.875rem;+}+.gf-scene-lines > span {+ height: 0.5rem;+ border-radius: var(--ui-radius-xs);+ background: var(--ui-fg-subtle);+}+.gf-backdrop {+ position: absolute;+ inset: 0;+ background: var(--ui-overlay-backdrop);+}+.gf-dialog {+ position: relative;+ z-index: 1;+ display: grid;+ gap: 0.5rem;+ margin-top: 0.5rem;+ padding: 1rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-overlay);+ box-shadow: var(--ui-shadow-modal);+ font-size: var(--ui-text-body-size);+}+.gf-dialog p {+ margin: 0 0 0.5rem;+ font-size: var(--ui-text-small-size);+}+.gf-toast {+ position: absolute;+ z-index: 1;+ right: 1rem;+ bottom: 1rem;+ display: flex;+ align-items: baseline;+ gap: 0.75rem;+ padding: 0.5rem 0.75rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-md);+ background: var(--ui-overlay);+ box-shadow: var(--ui-shadow-overlay);+ font-size: var(--ui-text-small-size);+}++.gf-radii {+ display: flex;+ flex-wrap: wrap;+ gap: 0.75rem;+}+.gf-radius {+ display: grid;+ justify-items: center;+ gap: 0.25rem;+}+.gf-radius-box {+ width: 3rem;+ height: 2.25rem;+ border: 1px solid var(--ui-line-emphasis);+ background: var(--ui-surface-muted);+}+.gf-borders {+ display: grid;+ gap: 0.5rem;+ margin-top: 0.5rem;+}+.gf-border-row {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}+.gf-border {+ flex: 1;+ border-top-style: solid;+ border-top-color: var(--ui-fg);+}+.gf-shadows {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem;+ padding: 0.25rem;+}+.gf-shadow {+ display: grid;+ place-items: center;+ width: 5rem;+ height: 3.5rem;+ /* The hairline keeps the box visible in a theme that raises nothing by shadow. */+ border: var(--ui-border-w) solid var(--ui-line-muted);+ border-radius: var(--ui-radius-md);+ background: var(--ui-surface);+}++/* ---- Spacing ---- */++.gf-ruler {+ display: grid;+ max-width: 34rem;+}+.gf-page-title {+ margin: 0;+ font-family: var(--ui-h2-font);+ font-size: var(--ui-h2-size);+ line-height: var(--ui-h2-lh);+ font-weight: var(--ui-h2-weight);+ letter-spacing: var(--ui-h2-tracking);+}+.gf-section-title {+ margin: 0;+ font-family: var(--ui-h4-font);+ font-size: var(--ui-h4-size);+ line-height: var(--ui-h4-lh);+ font-weight: var(--ui-h4-weight);+}+.gf-gap {+ position: relative;+ background: color-mix(in srgb, var(--ui-tone-info-emphasis) 16%, transparent);+}+.gf-gap-label {+ position: absolute;+ top: 50%;+ left: calc(100% + 0.75rem);+ transform: translateY(-50%);+ color: var(--ui-tone-info-fg);+ white-space: nowrap;+}+.gf-ruler-note {+ padding-top: 1rem;+}+.gf-gap-inline {+ display: inline-block;+ align-self: stretch;+ background: color-mix(in srgb, var(--ui-tone-info-emphasis) 32%, transparent);+}+.gf-pref {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+}+.gf-pref-label {+ display: inline-flex;+ align-items: center;+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+}+.gf-pref-label .gf-glyph {+ color: var(--ui-fg-muted);+}+.gf-segmented {+ display: inline-flex;+ padding: 0.125rem;+ border-radius: var(--ui-radius-control);+ background: var(--ui-surface-muted);+}+.gf-segmented > span {+ padding: 0.125rem 0.625rem;+ border-radius: var(--ui-radius-control);+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ color: var(--ui-fg-muted);+}+.gf-segmented > span[data-active] {+ background: var(--ui-surface);+ color: var(--ui-fg);+ box-shadow: var(--ui-shadow-raised);+}+.gf-switch {+ position: relative;+ width: 2.25rem;+ height: 1.25rem;+ border-radius: 999px;+ background: var(--ui-line-emphasis);+}+.gf-switch::after {+ content: "";+ position: absolute;+ top: 0.125rem;+ left: 0.125rem;+ width: 1rem;+ height: 1rem;+ border-radius: 999px;+ /* Light in both modes, with a hairline so it reads on a near-white accent (Primer dark). */+ border: 1px solid var(--ui-line);+ background: var(--ui-tone-neutral-emphasis-fg);+}+.gf-switch[data-on] {+ background: var(--ui-accent);+}+.gf-switch[data-on]::after {+ left: calc(100% - 1.125rem);+}+.gf-units {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: 1rem 2rem;+}+.gf-unit {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+}+.gf-unit-bar {+ display: inline-block;+ width: 4rem;+ background: color-mix(in srgb, var(--ui-tone-info-emphasis) 32%, transparent);+}+.gf-rungs {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 1rem 2rem;+}+.gf-rung,+.gf-measured {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+}+.gf-control {+ display: inline-flex;+ align-items: center;+ border-radius: var(--ui-radius-control);+ background: var(--ui-accent);+ color: var(--ui-accent-fg);+ font-weight: var(--ui-weight-medium);+}++/* ---- Icons ---- */++.gf-icon-sizes {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: 1rem 1.5rem;+}+.gf-icon-size {+ display: grid;+ justify-items: center;+ gap: 0.375rem;+ color: var(--ui-fg);+}+.gf-icon-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(6.5rem, 1fr));+ gap: 0.25rem 0.5rem;+}+.gf-icon {+ position: relative;+ display: grid;+ justify-items: center;+ align-content: start;+ gap: 0.375rem;+ min-width: 0;+ padding: 0.625rem 0.25rem;+ color: var(--ui-fg);+}+.gf-icon-name {+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.gf-icon-dupes {+ position: absolute;+ top: 0.25rem;+ right: 0.25rem;+ color: var(--ui-tone-attention-fg);+}++/* ---- Shell (the ui-shell specimen; the theme's recipe re-paints it) ---- */++.gf-shell {+ display: flex;+ height: 12rem;+ overflow: hidden;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-canvas);+}+.gf-shell-nav {+ display: grid;+ align-content: start;+ gap: 2px;+ width: calc(var(--ui-space-unit) * 44);+ flex-shrink: 0;+ padding: calc(var(--ui-space-unit) * 2);+ border-right: 1px solid var(--ui-line);+ background: var(--ui-surface-muted);+}+.gf-shell-row {+ padding: var(--ui-row-py) calc(var(--ui-space-unit) * 2.5);+ border-radius: var(--ui-radius-md);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ color: var(--ui-fg-muted);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.gf-shell-row[aria-current] {+ background: var(--ui-accent-muted);+ color: var(--ui-fg);+ font-weight: var(--ui-weight-medium);+}+.gf-shell-main {+ flex: 1;+ min-width: 0;+ display: grid;+ align-content: start;+ gap: 0.5rem;+ padding: var(--ui-panel-p);+}+.gf-shell-title {+ font-family: var(--ui-h4-font);+ font-size: var(--ui-h4-size);+ line-height: var(--ui-h4-lh);+ font-weight: var(--ui-h4-weight);+ letter-spacing: var(--ui-h4-tracking);+}+.gf-shell-text {+ margin: 0;+ font-family: var(--ui-font-sans);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ color: var(--ui-fg-muted);+}++/* ---- Motion ---- */++/* The presence specimens: a stage with the layer that enters and leaves; the layer's box carries+ the attribute and the panel inside it carries the look, the way the modules' Presence wraps a+ glass panel. */+.gf-presence {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));+ gap: 1rem;+}+.gf-specimen {+ display: grid;+ gap: 0.5rem;+ min-width: 0;+}+.gf-specimen-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+}+.gf-stage {+ position: relative;+ height: 12rem;+ overflow: hidden;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-canvas);+}+.gf-stage-trigger {+ position: absolute;+ top: 0.75rem;+ left: 0.75rem;+ padding: var(--ui-control-py-sm) var(--ui-control-px-sm);+ border: 1px solid var(--ui-line-emphasis);+ border-radius: var(--ui-radius-control);+ background: var(--ui-surface);+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+}+.gf-layer {+ position: absolute;+}+.gf-layer[data-side="top"] {+ top: 3.25rem;+ left: 0.75rem;+}+.gf-layer[data-side="center"] {+ inset: 0;+ display: grid;+ place-items: center;+ padding: 1rem;+}+.gf-layer[data-side="bottom"] {+ right: 0.75rem;+ bottom: 0.75rem;+}+.gf-motion-menu {+ display: grid;+ gap: 0.125rem;+ width: 10rem;+ padding: 0.25rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-md);+ background: var(--ui-overlay);+ box-shadow: var(--ui-shadow-overlay);+}+.gf-motion-dialog {+ position: relative;+ display: grid;+ gap: 0.5rem;+ width: min(100%, 17rem);+ padding: 1rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-overlay);+ box-shadow: var(--ui-shadow-modal);+ font-size: var(--ui-text-body-size);+}+.gf-motion-dialog p {+ margin: 0 0 0.25rem;+ font-size: var(--ui-text-small-size);+}+.gf-motion-toast {+ padding: 0.5rem 0.75rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-md);+ background: var(--ui-overlay);+ box-shadow: var(--ui-shadow-overlay);+ font-size: var(--ui-text-small-size);+ white-space: nowrap;+}++/* The reveal specimen reads as a reply: the reading face at the prose rung. */+.gf-reveal {+ min-height: 5rem;+ margin: 0;+ font-family: var(--ui-font-sans);+ font-size: var(--ui-text-prose-size);+ line-height: var(--ui-text-prose-lh);+}++/* The layout specimen: a sidebar beside a page, folding to a rail by width alone. */+.gf-layout-stage {+ display: flex;+ height: 9rem;+ overflow: hidden;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-canvas);+}+.gf-layout-nav {+ display: grid;+ align-content: start;+ gap: 2px;+ width: calc(var(--ui-space-unit) * 44);+ flex-shrink: 0;+ overflow: hidden;+ padding: calc(var(--ui-space-unit) * 2);+ border-right: 1px solid var(--ui-line);+ background: var(--ui-surface-muted);+}+.gf-layout-nav[data-rail] {+ width: calc(var(--ui-space-unit) * 13);+}+.gf-layout-row {+ display: flex;+ align-items: center;+ gap: var(--ui-stack-1);+ padding: var(--ui-row-py) calc(var(--ui-space-unit) * 2.5);+ border-radius: var(--ui-radius-md);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ color: var(--ui-fg-muted);+ white-space: nowrap;+}+.gf-layout-row[aria-current] {+ background: var(--ui-accent-muted);+ color: var(--ui-fg);+}+.gf-layout-main {+ flex: 1;+ display: grid;+ align-content: start;+ gap: 0.75rem;+ padding: 1rem;+}+.gf-layout-main > span {+ height: 0.5rem;+ border-radius: var(--ui-radius-xs);+ background: var(--ui-line);+}++.gf-motion {+ display: grid;+ grid-template-columns: 6.5rem repeat(3, minmax(0, 1fr));+ align-items: center;+ gap: 0.5rem 1rem;+}+.gf-motion-row {+ display: contents;+}+.gf-track {+ position: relative;+ height: 1.25rem;+ border-radius: 999px;+ background: var(--ui-surface-muted);+}+.gf-track-dot {+ position: absolute;+ top: 50%;+ left: 0.25rem;+ width: 0.75rem;+ height: 0.75rem;+ margin-top: -0.375rem;+ border-radius: 999px;+ background: var(--ui-accent);+ animation: gf-slide calc(var(--gf-dur) * 4) var(--gf-ease) infinite;+}+@keyframes gf-slide {+ 0% {+ left: 0.25rem;+ }+ 25%,+ 50% {+ left: calc(100% - 1rem);+ }+ 75%,+ 100% {+ left: 0.25rem;+ }+}+.gf-live {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 1rem 2rem;+ font-size: var(--ui-text-body-size);+}+.gf-live-item {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+}++/* ---- Focus ---- */++.gf-focused {+ outline: var(--ui-focus-ring);+ outline-offset: var(--ui-focus-ring-offset);+}+.gf-input-focused {+ border-color: var(--ui-accent);+ box-shadow: var(--ui-focus-ring-input);+ color: var(--ui-fg);+}+.gf-selection {+ margin: 0;+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+}+.gf-selection mark {+ background: var(--ui-selection-bg);+ color: inherit;+}+.gf-scroll {+ height: 7rem;+ overflow-y: scroll;+ padding: 0.5rem 0.75rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-md);+ background: var(--ui-surface);+ font-size: var(--ui-text-small-size);+}+.gf-scroll p {+ margin: 0 0 0.25rem;+}++/* ---- Hooks ----+ * Base looks only, in `components`: each hook's recipe lives in `@layer ui-theme` and must win. */++@layer components {+ .gf-hooks {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr));+ gap: 2.5rem 2rem;+ }+ .gf-hook {+ display: grid;+ gap: 0.75rem;+ align-content: start;+ min-width: 0;+ }+ .gf-hook-body {+ display: grid;+ gap: 0.75rem;+ min-width: 0;+ }+ .gh-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 1rem;+ font-size: var(--ui-text-body-size);+ }+ .gh-live {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ }+ .gh-stage {+ position: relative;+ height: 10rem;+ overflow: hidden;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background-color: var(--ui-canvas);+ }+ .gh-stage-text {+ margin: 0;+ padding: 0.75rem;+ font-size: var(--ui-text-prose-size);+ line-height: var(--ui-text-prose-lh);+ color: var(--ui-fg-muted);+ }+ .gh-panel {+ position: absolute;+ top: 2rem;+ left: 50%;+ transform: translateX(-50%);+ display: grid;+ gap: 0.125rem;+ width: min(12rem, 80%);+ padding: 0.25rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-md);+ background-color: var(--ui-overlay);+ box-shadow: var(--ui-shadow-overlay);+ }+ .gh-menu-row {+ padding: var(--ui-menu-row-py) var(--ui-menu-row-px);+ border-radius: max(var(--ui-radius-xs), calc(var(--ui-radius-md) - 0.25rem));+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ }+ .gh-menu-row[data-active] {+ background: var(--ui-surface-muted);+ }+ .gh-list {+ display: grid;+ gap: 0.125rem;+ }+ .gh-eyebrow {+ margin: 0 0 0.25rem;+ padding: 0 var(--ui-row-px);+ font-size: var(--ui-h6-size);+ line-height: var(--ui-h6-lh);+ font-weight: var(--ui-h6-weight);+ color: var(--ui-fg-muted);+ }+ .gh-list-row {+ padding: var(--ui-row-py) var(--ui-row-px);+ border-radius: var(--ui-radius-md);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ }+ .gh-list-row:first-of-type {+ background: var(--ui-accent-muted);+ }+ .gh-display {+ margin: 0;+ font-family: var(--ui-h1-font);+ font-size: var(--ui-h1-size);+ line-height: var(--ui-h1-lh);+ font-weight: var(--ui-h1-weight);+ letter-spacing: var(--ui-h1-tracking);+ }+ .gh-caret,+ .gf-caret {+ margin-left: 0.125rem;+ animation: gf-blink 1s steps(2, jump-none) infinite;+ }+ .gh-dot,+ .gf-live-dot {+ width: 0.5rem;+ height: 0.5rem;+ border-radius: 999px;+ background-color: var(--ui-tone-success-fg);+ animation: gf-pulse 1.4s ease-in-out infinite;+ }+ .gh-spinner,+ .gf-spinner {+ width: 0.875rem;+ height: 0.875rem;+ border-radius: 999px;+ border: 1.5px solid var(--ui-line);+ border-top-color: var(--ui-fg);+ animation: gf-spin 0.8s linear infinite;+ }+ .gh-frame {+ overflow: hidden;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background-color: var(--ui-code-bg);+ }+ .gh-frame-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ padding: 0.25rem 0.75rem;+ border-bottom: 1px solid var(--ui-line);+ background-color: var(--ui-surface-muted);+ font-size: var(--ui-text-caption-size);+ color: var(--ui-fg-muted);+ }+ .gh-frame-body {+ margin: 0;+ padding: 0.75rem;+ overflow-x: auto;+ font-family: var(--ui-font-mono);+ font-size: var(--ui-text-code-size);+ line-height: var(--ui-text-code-lh);+ white-space: pre-wrap;+ }+ .gh-frame-foot {+ padding: 0.25rem 0.75rem;+ border-top: 1px solid var(--ui-line);+ font-size: var(--ui-text-caption-size);+ color: var(--ui-fg-muted);+ }+ .gh-frame-panes {+ display: grid;+ grid-template-columns: 1fr 1fr;+ background-color: var(--ui-surface);+ }+ .gh-frame-panes > [data-slot="pane"] {+ padding: 0.75rem;+ font-size: var(--ui-text-small-size);+ }+ .gh-tabs {+ display: flex;+ gap: 1rem;+ border-bottom: 1px solid var(--ui-line);+ }+ .gh-tab {+ padding: 0.375rem 0.125rem;+ font-size: var(--ui-text-body-size);+ color: var(--ui-fg-muted);+ }+ .gh-tab[aria-selected="true"] {+ color: var(--ui-fg);+ font-weight: var(--ui-weight-medium);+ }++ /* ui-icon-decor: a sidebar's rows, group header and a menu row, each glyph beside its label. */+ .gh-nav {+ display: grid;+ gap: 0.125rem;+ max-width: 16rem;+ padding: 0.375rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background-color: var(--ui-surface-muted);+ }+ .gh-nav-row {+ display: flex;+ align-items: center;+ gap: var(--ui-stack-1);+ padding: var(--ui-row-py) calc(var(--ui-space-unit) * 2.5);+ border-radius: var(--ui-radius-md);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ color: var(--ui-fg-muted);+ }+ .gh-nav-row[aria-current] {+ background-color: var(--ui-accent-muted);+ color: var(--ui-fg);+ font-weight: var(--ui-weight-medium);+ }+ .gh-nav-glyph {+ display: inline-flex;+ flex-shrink: 0;+ color: var(--ui-fg-subtle);+ }+ .gh-nav-row[aria-current] .gh-nav-glyph {+ color: var(--ui-fg);+ }+ .gh-nav-group {+ display: flex;+ align-items: center;+ gap: var(--ui-stack-0);+ padding: 0.75rem calc(var(--ui-space-unit) * 2) 0.25rem;+ }+ .gh-nav-group-label {+ font-size: var(--ui-h6-size);+ line-height: var(--ui-h6-lh);+ font-weight: var(--ui-h6-weight);+ color: var(--ui-fg-muted);+ }+ .gh-nav-menu {+ color: var(--ui-fg);+ }++ /* ui-tree: Primer's bordered box with the host's own indent; a theme's recipe adds its rules+ or takes the box away. Rows are one line high, so an elbow lands on their middle. */+ .gh-tree {+ max-width: 18rem;+ padding: 0.25rem;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-md);+ background-color: var(--ui-surface);+ }+ .gh-tree-row {+ display: flex;+ align-items: center;+ gap: 0.375rem;+ height: 1.75rem;+ padding-inline-end: 0.5rem;+ border-radius: var(--ui-radius-sm);+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ color: var(--ui-fg);+ white-space: nowrap;+ }+ .gh-tree-row .gf-glyph {+ color: var(--ui-fg-muted);+ }+ .gh-tree-gap {+ width: 0.75rem;+ flex-shrink: 0;+ }+ .gh-tree-name {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ /* ui-field: a form field stacks (label, control, hint) and a settings row puts its label beside+ the control — Primer's two layouts, which Frost and Console each re-lay their own way. */+ .gh-fields {+ display: grid;+ gap: 1rem;+ max-width: 24rem;+ }+ .gh-field {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ gap: 0.375rem;+ }+ .gh-field-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1.5rem;+ padding-block: 0.5rem;+ border-top: 1px solid var(--ui-line-muted);+ }+ .gh-field-label {+ display: grid;+ gap: 0.125rem;+ min-width: 0;+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ font-weight: var(--ui-weight-medium);+ color: var(--ui-fg);+ }+ .gh-field-sub {+ font-weight: var(--ui-weight-body);+ }+ /* A filled text control, drawn like .gf-input but in this layer, so a field recipe may stretch it. */+ .gh-field-input {+ display: flex;+ width: 100%;+ padding: var(--ui-control-py-sm) var(--ui-control-px-sm);+ border: 1px solid var(--ui-line-emphasis);+ border-radius: var(--ui-radius-md);+ background-color: var(--ui-surface);+ color: var(--ui-fg);+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ }+}+@keyframes gf-blink {+ 50% {+ opacity: 0.15;+ }+}+@keyframes gf-pulse {+ 50% {+ opacity: 0.4;+ }+}+@keyframes gf-spin {+ to {+ transform: rotate(360deg);+ }+}diff --git a/packages/ui-gallery/src/foundations/hooks.tsx b/packages/ui-gallery/src/foundations/hooks.tsxnew file mode 100644index 00000000..70e022e5--- /dev/null+++ b/packages/ui-gallery/src/foundations/hooks.tsx@@ -0,0 +1,244 @@+/**+ * Foundations › Hooks: the ten style hooks (`packages/ui/src/hooks.ts`), each on the minimal+ * markup its recipes select on — `.ui-frame` children carry `data-slot`, `.ui-live` carries+ * `data-live`, `.ui-underline-nav` holds `[role=tab]` items, `.ui-display` sits on an `h1`,+ * `.ui-shell` holds a `nav` and a `main` slot, `.ui-icon-decor` sits on the icon with its+ * `data-role`, `.ui-tree` rows carry `data-depth` and `data-last` with a `data-branch` under a+ * parent, `.ui-field` children carry the `label` / `control` / `hint` slots — so a theme's hooks+ * can be reviewed before any component carries them. The specimens live here, in the gallery,+ * rather than in a package module: a package file applies a hook only inside the component that+ * hosts it.+ *+ * The base look of each sample lives in `@layer components` (foundations.css): a hook's recipe sits+ * in `@layer ui-theme` and must win over it, exactly as it wins over a component's utilities. The+ * tree sample indents its rows the way a host does — by the inset and the indent tokens — so the+ * three themes' guides land on the same columns as in the modules.+ */+import { HOOKS } from "@prismshadow/penguin-ui";+import type { CSSProperties, ReactNode } from "react";+import { useGallery } from "../state";+import { Glyph, NAV_GLYPHS, SAMPLE_GLYPHS, ShellSpecimen } from "./shared";+import { SPECIMENS } from "./specimens";++function Hook({ name, children }: { name: (typeof HOOKS)[number]; children: ReactNode }) {+ const { S } = useGallery();+ return (+ <section className="gf-hook">+ <div className="gf-group-head">+ <h3 className="gf-mono">.{name}</h3>+ <span className="gf-aside">{S.foundations.hookJobs[name]}</span>+ </div>+ <div className="gf-hook-body">{children}</div>+ </section>+ );+}++/** A host's own indent for a tree row: what every module's rows spell, from the two tree tokens. */+const indent = (depth: number): CSSProperties => ({+ paddingInlineStart: `calc(var(--ui-tree-inset) + var(--ui-tree-indent) * ${depth})`,+});++function TreeRow({+ depth,+ last = false,+ dir = false,+ open = false,+ children,+}: {+ depth: number;+ last?: boolean;+ dir?: boolean;+ open?: boolean;+ children: string;+}) {+ return (+ <div+ className="gh-tree-row"+ data-depth={depth}+ data-last={last || undefined}+ style={indent(depth)}+ >+ {dir ? (+ <Glyph d={open ? SAMPLE_GLYPHS.chevronDown : SAMPLE_GLYPHS.chevronRight} size={12} />+ ) : (+ <span className="gh-tree-gap" />+ )}+ <Glyph d={dir ? SAMPLE_GLYPHS.folder : SAMPLE_GLYPHS.file} size={14} />+ <span className="gh-tree-name">{children}</span>+ </div>+ );+}++export function HooksBoard() {+ const { state, S } = useGallery();+ const specimen = SPECIMENS[state.lang];+ const t = S.foundations.hookSamples;+ return (+ <div className="gf-hooks">+ <Hook name="ui-glass">+ <div className="gh-stage">+ <p className="gh-stage-text" aria-hidden>+ {specimen.paragraph}+ </p>+ <div className="ui-glass gh-panel" role="menu">+ {t.menu.map((item, i) => (+ <span key={item} className="gh-menu-row" data-active={i === 1 || undefined}>+ {item}+ </span>+ ))}+ </div>+ </div>+ </Hook>++ <Hook name="ui-eyebrow">+ <div className="gh-list">+ <p className="ui-eyebrow gh-eyebrow">{t.group}</p>+ {t.rows.map((row) => (+ <span key={row} className="gh-list-row">+ {row}+ </span>+ ))}+ </div>+ </Hook>++ <Hook name="ui-display">+ <h1 className="ui-display gh-display" lang="en">+ {SPECIMENS.en.display}+ </h1>+ <h1 className="ui-display gh-display" lang="zh-CN">+ {SPECIMENS.zh.display}+ </h1>+ </Hook>++ <Hook name="ui-live">+ <div className="gh-row">+ <span>+ {t.streaming}+ <span className="ui-live gh-caret" data-live="caret">+ ▌+ </span>+ </span>+ <span className="gh-live">+ <span className="ui-live gh-dot" data-live="dot" />+ {S.foundations.toneWords.success}+ </span>+ <span className="gh-live">+ <span className="ui-live gh-spinner" data-live="spinner" />+ {S.foundations.loading}+ </span>+ </div>+ </Hook>++ <Hook name="ui-frame">+ <div className="ui-frame gh-frame">+ <div data-slot="head" className="gh-frame-head">+ <span className="gf-mono">claude-code-expert/src/rag.ts</span>+ <span>{t.copy}</span>+ </div>+ <pre data-slot="body" className="gh-frame-body">+ {specimen.code.split("\n").slice(0, 2).join("\n")}+ </pre>+ <div data-slot="foot" className="gh-frame-foot">+ <span className="gf-mono">412ms · exit 0</span>+ </div>+ </div>+ <div className="ui-frame gh-frame gh-frame-panes">+ <div data-slot="pane">{SPECIMENS.en.ui}</div>+ <div data-slot="pane">{SPECIMENS.zh.ui}</div>+ </div>+ </Hook>++ <Hook name="ui-underline-nav">+ <div className="ui-underline-nav gh-tabs" role="tablist">+ {t.tabs.map((tab, i) => (+ <span key={tab} role="tab" aria-selected={i === 0} className="gh-tab">+ {tab}+ </span>+ ))}+ </div>+ </Hook>++ <Hook name="ui-shell">+ <ShellSpecimen />+ </Hook>++ {/* Three navigation rows (the first selected), a group header and a menu row, each with a+ glyph its label already says: Frost tints them by role, Console drops them. */}+ <Hook name="ui-icon-decor">+ <div className="gh-nav">+ {S.foundations.motionSpecimens.sidebarRows.map((row, i) => (+ <span key={row} className="gh-nav-row" aria-current={i === 0 ? "page" : undefined}>+ <span className="ui-icon-decor gh-nav-glyph" data-role="nav">+ <Glyph d={NAV_GLYPHS[i % NAV_GLYPHS.length] ?? NAV_GLYPHS[0]} size={16} />+ </span>+ {row}+ </span>+ ))}+ <span className="gh-nav-group">+ <span className="ui-icon-decor gh-nav-glyph" data-role="group">+ <Glyph d={SAMPLE_GLYPHS.folder} size={14} />+ </span>+ <span className="ui-eyebrow gh-nav-group-label">{t.group}</span>+ </span>+ <span className="gh-nav-row gh-nav-menu">+ <span className="ui-icon-decor gh-nav-glyph" data-role="menu">+ <Glyph d={SAMPLE_GLYPHS.pin} size={14} />+ </span>+ {t.menu[0]}+ </span>+ </div>+ </Hook>++ {/* A file tree: a root, a folder with two files in a branch, and a last file. */}+ <Hook name="ui-tree">+ <div className="ui-tree gh-tree">+ <TreeRow depth={0} dir open>+ {t.tree.root}+ </TreeRow>+ <div data-branch data-depth={1}>+ <TreeRow depth={1} dir open>+ {t.tree.dir}+ </TreeRow>+ <div data-branch data-depth={2}>+ {t.tree.files.map((file, i) => (+ <TreeRow key={file} depth={2} last={i === t.tree.files.length - 1}>+ {file}+ </TreeRow>+ ))}+ </div>+ <TreeRow depth={1} last>+ {t.tree.last}+ </TreeRow>+ </div>+ </div>+ </Hook>++ {/* A form field (label, control, hint) and a settings row (label with its hint, a switch):+ Primer keeps each host's own layout, Frost stacks both, Console tabulates both. */}+ <Hook name="ui-field">+ <div className="gh-fields">+ <div className="ui-field gh-field">+ <span data-slot="label" className="gh-field-label">+ {t.field.name}+ </span>+ <div data-slot="control">+ <span className="gh-field-input">{t.field.value}</span>+ </div>+ <span data-slot="hint" className="gf-caption">+ {t.field.hint}+ </span>+ </div>+ <div className="ui-field gh-field-row">+ <div data-slot="label" className="gh-field-label">+ {t.field.notify}+ <span className="gf-caption gh-field-sub">{t.field.notifyHint}</span>+ </div>+ <div data-slot="control">+ <span className="gf-switch" data-on />+ </div>+ </div>+ </div>+ </Hook>+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/icons.tsx b/packages/ui-gallery/src/foundations/icons.tsxnew file mode 100644index 00000000..5851b835--- /dev/null+++ b/packages/ui-gallery/src/foundations/icons.tsx@@ -0,0 +1,68 @@+/**+ * Foundations › Icons: every line icon the Web App declares (read from its source, see+ * lib/icon-registry.ts; W1 moves the registry into the package) drawn at the theme's stroke, cap and+ * join, grouped by the file that declares it, after the size rungs of `ICON_SIZE`. A path declared+ * under several names shows once, marked with its count — W1's deduplication list.+ */+import { WEB_ICON_SIZES, WEB_ICONS } from "../sources";+import { useGallery } from "../state";+import { BoardGroup, Glyph } from "./shared";++export function IconsBoard() {+ const { S } = useGallery();+ const sources = [...new Set(WEB_ICONS.map((icon) => icon.sources[0] ?? ""))];+ const sample =+ WEB_ICONS.find((icon) => icon.names.includes("GEAR_ICON"))?.d ?? WEB_ICONS[0]?.d ?? "";+ return (+ <div className="gf-board">+ <BoardGroup+ title={S.foundations.iconSizes}+ aside={S.foundations.iconRegistry(WEB_ICONS.length, sources.length)}+ >+ <div className="gf-icon-sizes">+ {WEB_ICON_SIZES.map(({ name, px }) => (+ <span key={name} className="gf-icon-size" data-tooltip={`ICON_SIZE.${name}`}>+ <Glyph d={sample} size={px} />+ <span className="gf-caption gf-mono">+ {name} {px}+ </span>+ </span>+ ))}+ </div>+ </BoardGroup>+ {sources.map((source) => {+ const icons = WEB_ICONS.filter((icon) => icon.sources[0] === source);+ return (+ <BoardGroup+ key={source}+ title={<span className="gf-mono">{source}</span>}+ aside={icons.length}+ >+ <div className="gf-icon-grid">+ {icons.map((icon) => (+ <span+ key={icon.d}+ className="gf-icon"+ data-tooltip={`${icon.names.join("\n")}\n— ${icon.sources.join(", ")}`}+ >+ <Glyph d={icon.d} size={16} />+ <span className="gf-caption gf-mono gf-icon-name">+ {icon.names[0]?.replace(/_ICONS?$/, "").replace(/^[A-Z_]+ICONS\./, "")}+ </span>+ {icon.names.length > 1 && (+ <span+ className="gf-caption gf-icon-dupes"+ data-tooltip={S.foundations.duplicateNames}+ >+ ×{icon.names.length}+ </span>+ )}+ </span>+ ))}+ </div>+ </BoardGroup>+ );+ })}+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/motion.tsx b/packages/ui-gallery/src/foundations/motion.tsxnew file mode 100644index 00000000..3f678ebe--- /dev/null+++ b/packages/ui-gallery/src/foundations/motion.tsx@@ -0,0 +1,337 @@+/**+ * Foundations › Motion, replayable: the three presence specimens (a menu from the top, a dialog+ * with its backdrop from the centre, a toast from the bottom) entering and leaving on the theme's+ * `data-presence` rules; a streamed line arriving chunk by chunk under `data-reveal`; a sidebar's+ * width folding to a rail and back under `data-layout-motion`; then every duration × easing pair+ * as a dot crossing a track, and the live signals — a caret, a running dot and a spinner — on the+ * timing each theme gives `.ui-live`. The specimens set the same attributes the modules set and+ * nothing else, so what moves here is exactly what the theme's motion tokens say.+ *+ * With `motion=reduced` (chrome.css, and the package's own reduced rules) every change shows its+ * end state at once — which is also what keeps screenshots deterministic.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import type { AnimationEvent, CSSProperties, ReactNode } from "react";+import { useGallery } from "../state";+import { BoardGroup, NAV_GLYPHS, ReplayButton } from "./shared";+import { SPECIMENS } from "./specimens";++const DURATIONS = ["fast", "base", "slow"] as const;+const EASINGS = ["out", "in-out", "spring", "overlay-in", "overlay-out"] as const;++/** How long a presence specimen stays open between its entrance and its exit. */+const HOLD_MS = 1400;+/** A streamed chunk every so often; Frost's reveal overlaps the next chunk's, by design. */+const CHUNK_MS = 90;++type Phase = "hidden" | "enter" | "exit";++/**+ * The presence owner, as the modules implement it: mounted with `enter`, flipped to `exit` after+ * the hold, unmounted when the exit's `animationend` arrives — or at once when the computed+ * `animation-name` is `none` (reduced motion, or a theme that jumps), since no event ever comes.+ */+function usePresence(run: number) {+ const [phase, setPhase] = useState<Phase>("hidden");+ const [key, setKey] = useState(0);+ const ref = useRef<HTMLDivElement>(null);+ const hold = useRef<number | null>(null);++ const play = useCallback(() => {+ if (hold.current !== null) window.clearTimeout(hold.current);+ setKey((k) => k + 1);+ setPhase("enter");+ hold.current = window.setTimeout(() => setPhase("exit"), HOLD_MS);+ }, []);++ useEffect(() => {+ if (run > 0) play();+ }, [run, play]);++ useEffect(() => {+ if (phase !== "exit") return;+ const el = ref.current;+ if (el !== null && getComputedStyle(el).animationName === "none") setPhase("hidden");+ }, [phase]);++ useEffect(+ () => () => {+ if (hold.current !== null) window.clearTimeout(hold.current);+ },+ [],+ );++ const onAnimationEnd = (event: AnimationEvent<HTMLDivElement>) => {+ if (event.target === event.currentTarget && phase === "exit") setPhase("hidden");+ };++ return { phase, key, ref, play, onAnimationEnd };+}++function PresenceSpecimen({+ title,+ side,+ run,+ backdrop = false,+ children,+}: {+ title: string;+ side: "top" | "bottom" | "center";+ run: number;+ backdrop?: boolean;+ children: ReactNode;+}) {+ const { S } = useGallery();+ const presence = usePresence(run);+ const shown = presence.phase !== "hidden";+ const trigger = S.foundations.motionSpecimens.trigger;+ return (+ <div className="gf-specimen">+ <div className="gf-stage" data-side={side}>+ {side === "top" && <span className="gf-stage-trigger">{trigger}</span>}+ {shown && backdrop && <span className="gf-backdrop" data-backdrop={presence.phase} />}+ {shown && (+ <div+ key={presence.key}+ ref={presence.ref}+ className="gf-layer"+ data-presence={presence.phase}+ data-side={side}+ onAnimationEnd={presence.onAnimationEnd}+ >+ {children}+ </div>+ )}+ </div>+ <div className="gf-specimen-foot">+ <span className="gf-caption">+ {title} <span className="gf-mono">{side}</span>+ </span>+ <ReplayButton onClick={presence.play} />+ </div>+ </div>+ );+}++/** Streaming splits into words for Latin text and one or two Han characters for Chinese. */+function chunksOf(text: string, lang: "en" | "zh"): string[] {+ const parts = lang === "zh" ? text.match(/[\s\S]{1,2}/g) : text.match(/\S+\s*/g);+ return parts ?? [text];+}++function RevealSpecimen({ run }: { run: number }) {+ const { state } = useGallery();+ const chunks = chunksOf(SPECIMENS[state.lang].paragraph, state.lang);+ const total = chunks.length;+ const [shown, setShown] = useState(total);+ const timer = useRef<number | null>(null);++ const play = useCallback(() => {+ if (timer.current !== null) window.clearInterval(timer.current);+ setShown(0);+ timer.current = window.setInterval(() => {+ setShown((n) => {+ if (n + 1 >= total && timer.current !== null) {+ window.clearInterval(timer.current);+ timer.current = null;+ }+ return Math.min(n + 1, total);+ });+ }, CHUNK_MS);+ }, [total]);++ useEffect(() => {+ if (run > 0) play();+ }, [run, play]);+ useEffect(+ () => () => {+ if (timer.current !== null) window.clearInterval(timer.current);+ },+ [],+ );++ const streaming = shown < total;+ return (+ <div className="gf-specimen">+ <p className="gf-reveal" lang={state.lang === "zh" ? "zh-CN" : "en"}>+ {chunks.slice(0, shown).map((chunk, i) => (+ <span key={i} data-reveal>+ {chunk}+ </span>+ ))}+ {streaming && (+ <span className="ui-live gf-caret" data-live="caret">+ ▌+ </span>+ )}+ </p>+ <div className="gf-specimen-foot">+ <span className="gf-caption gf-mono">data-reveal</span>+ <ReplayButton onClick={play} />+ </div>+ </div>+ );+}++function LayoutSpecimen({ run }: { run: number }) {+ const { S } = useGallery();+ const [rail, setRail] = useState(false);+ const timer = useRef<number | null>(null);++ const play = useCallback(() => {+ if (timer.current !== null) window.clearTimeout(timer.current);+ setRail(true);+ timer.current = window.setTimeout(() => setRail(false), HOLD_MS);+ }, []);++ useEffect(() => {+ if (run > 0) play();+ }, [run, play]);+ useEffect(+ () => () => {+ if (timer.current !== null) window.clearTimeout(timer.current);+ },+ [],+ );++ return (+ <div className="gf-specimen">+ <div className="gf-layout-stage">+ <div className="gf-layout-nav" data-layout-motion data-rail={rail || undefined}>+ {S.foundations.motionSpecimens.sidebarRows.map((row, i) => (+ <span key={row} className="gf-layout-row" aria-current={i === 0 ? "page" : undefined}>+ <svg+ width={16}+ height={16}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ aria-hidden+ className="gf-glyph"+ style={{ strokeWidth: "var(--ui-icon-stroke)" }}+ >+ <path d={NAV_GLYPHS[i] ?? NAV_GLYPHS[0]} />+ </svg>+ <span className="gf-layout-label">{row}</span>+ </span>+ ))}+ </div>+ <div className="gf-layout-main" aria-hidden>+ <span style={{ width: "72%" }} />+ <span style={{ width: "48%" }} />+ <span style={{ width: "60%" }} />+ </div>+ </div>+ <div className="gf-specimen-foot">+ <span className="gf-caption gf-mono">data-layout-motion</span>+ <ReplayButton onClick={play} />+ </div>+ </div>+ );+}++export function MotionBoard() {+ const { S, state } = useGallery();+ const t = S.foundations;+ const [run, setRun] = useState(0);+ // The board follows the OS preference, as the framed app does: there is no gallery switch.+ const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches+ ? t.reducedNote+ : undefined;+ return (+ <div className="gf-board">+ <BoardGroup+ title={t.presence}+ aside={reduced ?? t.presenceNote}+ action={<ReplayButton label={t.replayAll} onClick={() => setRun((n) => n + 1)} />}+ >+ <div className="gf-presence">+ <PresenceSpecimen title={t.motionSpecimens.menu} side="top" run={run}>+ <div className="ui-glass gf-motion-menu" role="menu">+ {t.scene.menuItems.map((item, i) => (+ <span key={item} className="gf-menu-row" data-active={i === 1 || undefined}>+ {item}+ </span>+ ))}+ </div>+ </PresenceSpecimen>+ <PresenceSpecimen title={t.motionSpecimens.dialog} side="center" run={run} backdrop>+ <div+ className="ui-glass gf-motion-dialog"+ role="dialog"+ aria-label={t.scene.dialogTitle}+ >+ <strong>{t.scene.dialogTitle}</strong>+ <p className="gf-muted">{t.scene.dialogBody}</p>+ <div className="gf-controls gf-controls-end">+ <span className="gf-button">{t.scene.cancel}</span>+ <span className="gf-button" data-variant="danger">+ {t.scene.confirm}+ </span>+ </div>+ </div>+ </PresenceSpecimen>+ <PresenceSpecimen title={t.motionSpecimens.toast} side="bottom" run={run}>+ <div className="gf-motion-toast" role="status">+ {t.scene.toast}+ </div>+ </PresenceSpecimen>+ </div>+ </BoardGroup>+ <div className="gf-pair">+ <BoardGroup title={t.reveal} aside={t.revealNote}>+ <RevealSpecimen run={run} />+ </BoardGroup>+ <BoardGroup title={t.layout} aside={t.layoutNote}>+ <LayoutSpecimen run={run} />+ </BoardGroup>+ </div>+ <BoardGroup title={t.durations}>+ <div className="gf-motion">+ <span />+ {DURATIONS.map((duration) => (+ <span key={duration} className="gf-caption gf-mono">+ {duration}+ </span>+ ))}+ {EASINGS.map((easing) => (+ <div key={easing} className="gf-motion-row">+ <span className="gf-caption gf-mono">{easing}</span>+ {DURATIONS.map((duration) => (+ <span key={duration} className="gf-track">+ <span+ className="gf-track-dot"+ style={+ {+ "--gf-dur": `var(--ui-dur-${duration})`,+ "--gf-ease": `var(--ui-ease-${easing})`,+ } as CSSProperties+ }+ />+ </span>+ ))}+ </div>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.liveSignal}>+ <div className="gf-live">+ <span>+ {SPECIMENS[state.lang].heading}+ <span className="ui-live gf-caret" data-live="caret">+ ▌+ </span>+ </span>+ <span className="gf-live-item">+ <span className="ui-live gf-live-dot" data-live="dot" />+ {t.toneWords.success}+ </span>+ <span className="gf-live-item">+ <span className="ui-live gf-spinner" data-live="spinner" />+ {t.loading}+ </span>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/shape.tsx b/packages/ui-gallery/src/foundations/shape.tsxnew file mode 100644index 00000000..c4033b9a--- /dev/null+++ b/packages/ui-gallery/src/foundations/shape.tsx@@ -0,0 +1,131 @@+/**+ * Foundations › Shape & depth: the things radius, border and shadow are for, in one stack — a page+ * card with its controls and a box nested at the inner radius, a menu dropped from the card's head+ * (glass in Frost), a dialog over the dimmed page and a toast above everything — each layer naming+ * the stacking tier it takes. Then the app window through `.ui-shell`, where a theme decides how+ * its two columns relate (Frost's floating sheet on a field, Console's ruled columns, Primer's+ * plain window). Below it, the radius steps, the border widths and the five shadow levels on+ * plain boxes.+ */+import { useGallery } from "../state";+import { BoardGroup, ShellSpecimen } from "./shared";++const RADII = ["xs", "sm", "md", "lg", "xl", "pill", "control"] as const;+const SHADOWS = ["flat", "raised", "overlay", "modal", "drawer"] as const;+/** The page under the dialog, drawn as text lines: enough for the blur and the dim to act on. */+const LINES = [92, 78, 85, 64, 88, 70, 81, 58] as const;++function Tier({ children }: { children: string }) {+ return <span className="gf-tier gf-caption gf-mono">{children}</span>;+}++function Scene() {+ const { S } = useGallery();+ const t = S.foundations.scene;+ return (+ <div className="gf-scene">+ <div className="gf-scene-page">+ <Tier>{t.pageTier}</Tier>+ <div className="gf-card">+ <div className="gf-card-head">+ <strong>{t.cardTitle}</strong>+ <span className="gf-caption">{t.cardMeta}</span>+ <span className="gf-more" aria-hidden>+ ···+ </span>+ </div>+ <div className="gf-nested">+ <span className="gf-caption">{t.nested}</span>+ </div>+ <div className="gf-controls">+ <span className="gf-button" data-variant="primary">+ {t.primary}+ </span>+ <span className="gf-button">{t.secondary}</span>+ <span className="gf-badge">{t.badge}</span>+ </div>+ <span className="gf-input">{t.input}</span>+ <div className="gf-menu ui-glass" role="menu">+ {t.menuItems.map((item, i) => (+ <span key={item} className="gf-menu-row" data-active={i === 1 || undefined}>+ {item}+ </span>+ ))}+ <span className="gf-layer-tier gf-caption gf-mono">{t.menuTier}</span>+ </div>+ </div>+ </div>+ <div className="gf-scene-modal">+ <div className="gf-scene-lines" aria-hidden>+ {LINES.map((width, i) => (+ <span key={i} style={{ width: `${width}%` }} />+ ))}+ </div>+ <span className="gf-backdrop" />+ <Tier>{t.backdropTier}</Tier>+ <div className="gf-dialog ui-glass" role="dialog" aria-label={t.dialogTitle}>+ <strong>{t.dialogTitle}</strong>+ <p className="gf-muted">{t.dialogBody}</p>+ <div className="gf-controls gf-controls-end">+ <span className="gf-button">{t.cancel}</span>+ <span className="gf-button" data-variant="danger">+ {t.confirm}+ </span>+ </div>+ </div>+ <div className="gf-toast">+ <span>{t.toast}</span>+ <span className="gf-caption gf-mono">{t.toastTier}</span>+ </div>+ </div>+ </div>+ );+}++export function ShapeBoard() {+ const { S } = useGallery();+ return (+ <div className="gf-board">+ <Scene />+ <BoardGroup title={S.foundations.shell} aside={S.foundations.shellNote}>+ <ShellSpecimen />+ </BoardGroup>+ <div className="gf-pair">+ <BoardGroup title={S.foundations.radius}>+ <div className="gf-radii">+ {RADII.map((step) => (+ <span key={step} className="gf-radius">+ <span+ className="gf-radius-box"+ style={{ borderRadius: `var(--ui-radius-${step})` }}+ />+ <span className="gf-caption gf-mono">{step}</span>+ </span>+ ))}+ </div>+ <div className="gf-borders">+ {(["border-w", "border-w-thick"] as const).map((name) => (+ <span key={name} className="gf-border-row">+ <span className="gf-border" style={{ borderTopWidth: `var(--ui-${name})` }} />+ <span className="gf-caption gf-mono">{name}</span>+ </span>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={S.foundations.shadows}>+ <div className="gf-shadows">+ {SHADOWS.map((level) => (+ <span+ key={level}+ className="gf-shadow"+ style={{ boxShadow: `var(--ui-shadow-${level})` }}+ >+ <span className="gf-caption gf-mono">{level}</span>+ </span>+ ))}+ </div>+ </BoardGroup>+ </div>+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/shared.tsx b/packages/ui-gallery/src/foundations/shared.tsxnew file mode 100644index 00000000..5752cdec--- /dev/null+++ b/packages/ui-gallery/src/foundations/shared.tsx@@ -0,0 +1,157 @@+/**+ * Building blocks the Foundations boards share. A board renders INSIDE the themed preview, so it is+ * themed: every specimen reads the bare token (an undefined token must look broken), and the names+ * printed beside a specimen are labels in the caption rung, not token rows — the resolved values+ * live in the module's tokens drawer.+ */+import { useLayoutEffect, useRef, useState } from "react";+import type { CSSProperties, ReactNode } from "react";+import { useGallery } from "../state";+import { SPECIMENS } from "./specimens";++/** A titled group on a board: a label rung and its content, ruled from the group above. */+export function BoardGroup({+ title,+ aside,+ action,+ children,+}: {+ title: ReactNode;+ aside?: ReactNode;+ /** A control at the end of the head row: the motion board's replay. */+ action?: ReactNode;+ children: ReactNode;+}) {+ return (+ <section className="gf-group">+ <div className="gf-group-head">+ <h3>{title}</h3>+ {aside !== undefined && <span className="gf-aside">{aside}</span>}+ {action !== undefined && <span className="gf-group-action">{action}</span>}+ </div>+ {children}+ </section>+ );+}++export function Resolving() {+ const { S } = useGallery();+ return <p className="gf-muted">{S.intro.resolving}</p>;+}++/** Renders its child and prints the child's rendered height in px, re-measured on resize. */+export function Measured({+ children,+ style,+ className,+}: {+ children?: ReactNode;+ style: CSSProperties;+ className: string;+}) {+ const ref = useRef<HTMLSpanElement>(null);+ const [height, setHeight] = useState<number | null>(null);+ useLayoutEffect(() => {+ const el = ref.current;+ if (!el) return;+ const measure = () => setHeight(Math.round(el.getBoundingClientRect().height * 10) / 10);+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);+ return (+ <span className="gf-measured">+ <span ref={ref} className={className} style={style}>+ {children}+ </span>+ <span className="gf-caption gf-mono">{height === null ? "…" : `${height}px`}</span>+ </span>+ );+}++/** A 24-grid line icon at the theme's stroke, cap and join. */+export function Glyph({ d, size = 16 }: { d: string; size?: number }) {+ const style: CSSProperties = {+ strokeWidth: "var(--ui-icon-stroke)",+ strokeLinecap: "var(--ui-icon-cap)" as CSSProperties["strokeLinecap"],+ strokeLinejoin: "var(--ui-icon-join)" as CSSProperties["strokeLinejoin"],+ };+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ style={style}+ aria-hidden+ className="gf-glyph"+ >+ <path d={d} />+ </svg>+ );+}++/**+ * Line-icon paths the boards' stand-in rows draw (24-grid, the app's own shapes): the three+ * navigation entries, a folder and a file with their chevrons, and two menu verbs.+ */+export const SAMPLE_GLYPHS = {+ newChat: "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z",+ agents:+ "M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75",+ models:+ "M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",+ folder: "M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z",+ file: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6",+ chevronDown: "m6 9 6 6 6-6",+ chevronRight: "m9 18 6-6-6-6",+ pin: "M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1z",+ trash:+ "M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6",+} as const;++/** The navigation rows' glyphs, in the order the specimens list the rows. */+export const NAV_GLYPHS = [+ SAMPLE_GLYPHS.newChat,+ SAMPLE_GLYPHS.agents,+ SAMPLE_GLYPHS.models,+] as const;++/** A small themed control that replays a motion specimen. */+export function ReplayButton({ onClick, label }: { onClick: () => void; label?: string }) {+ const { S } = useGallery();+ return (+ <button type="button" className="gf-replay" onClick={onClick}>+ {label ?? S.foundations.replay}+ </button>+ );+}++/**+ * The app window through `.ui-shell`: a navigation column with three rows (the first selected) and+ * a main column with a title and a line of text, in the anatomy the recipes select on. Frost lays+ * its field behind it and floats the main column; Console rules the columns and marks the selected+ * row; Primer leaves the specimen's own classes alone.+ */+export function ShellSpecimen() {+ const { S, state } = useGallery();+ const [newChat, agents, models] = S.foundations.motionSpecimens.sidebarRows;+ const specimen = SPECIMENS[state.lang];+ return (+ <div className="ui-shell gf-shell">+ <div data-slot="nav" className="gf-shell-nav">+ <span className="gf-shell-row" aria-current="page">+ {newChat}+ </span>+ <span className="gf-shell-row">{agents}</span>+ <span className="gf-shell-row">{models}</span>+ </div>+ <div data-slot="main" className="gf-shell-main">+ <strong className="gf-shell-title">{specimen.heading}</strong>+ <p className="gf-shell-text">{specimen.ui}</p>+ </div>+ </div>+ );+}diff --git a/packages/ui-gallery/src/foundations/specimens.ts b/packages/ui-gallery/src/foundations/specimens.tsnew file mode 100644index 00000000..d15e9be8--- /dev/null+++ b/packages/ui-gallery/src/foundations/specimens.ts@@ -0,0 +1,55 @@+/**+ * Specimen text for the Foundations boards and `/fonts`: the "Build a Claude Code docs expert"+ * session the product screenshots use, one set per language. Both languages render regardless+ * of the chrome language where a board sets them side by side — CJK legibility is judged in+ * every theme.+ */+export interface Specimen {+ /** A short display line (hero / h1). */+ display: string;+ /** A section heading. */+ heading: string;+ /** A body paragraph: prose with inline product names, numbers and a path. */+ paragraph: string;+ /** A dense UI line: labels, counts, a price, a duration. */+ ui: string;+ /** A caption / hint line. */+ caption: string;+ /** A code block exercising the mono face: identifiers, strings with CJK, numbers, operators. */+ code: string;+ /** Tabular numerals and units, to judge figure widths. */+ numerals: string;+ /** A dense UI line, named for where the old pages used it. */+ short: string;+}++const en: Omit<Specimen, "short"> = {+ display: "Agents that cite their sources",+ heading: "Prompt cache hit 81% across 2 turns",+ paragraph:+ "PenguinHarness ran the claude-code-expert Session for 1m12s on DeepSeek V4.1 Flash: 43.8k tokens, $0.0231 and 7 tool calls. The BM25 index covers 214 Markdown files, so even a question asked as “如何配置 hooks?” still cites corpus/claude-code-docs/hooks.md [1].",+ ui: "Running · 6 steps · 34s — read_file …/src/rag.ts (421ms) · edit_file +3 −1 · $0.0110",+ caption: "Last synced 2026-09-14 14:02 (UTC+8) · 48.2 KB · Trace #001",+ code: `// A citation must open a real file (引用必须指向真实文件)+const hits = rank(question).slice(0, 6).filter((c) => fs.existsSync(c.source));+console.log(\`\${hits.length} hits in \${(performance.now() - t0).toFixed(1)}ms\`); // 6 hits in 12.4ms`,+ numerals: "0123456789 · 1,048,576 tokens · $0.0231 · 71.8s · 99.95% · 3 × 4 = 12 · v0.2.13",+};++const zh: Omit<Specimen, "short"> = {+ display: "会引用来源的智能体",+ heading: "两轮对话,提示缓存命中率 81%",+ paragraph:+ "PenguinHarness 用 DeepSeek V4.1 Flash 运行 claude-code-expert 会话 1 分 12 秒:共 43.8k tokens、$0.0231、7 次工具调用。BM25 索引覆盖 214 个 Markdown 文件,所以即便问 “How do I configure hooks?”,回答也会引用 corpus/claude-code-docs/hooks.md [1]。",+ ui: "运行中 · 6 步 · 34s — read_file …/src/rag.ts(421ms)· edit_file +3 −1 · $0.0110",+ caption: "最近同步 2026-09-14 14:02(UTC+8)· 48.2 KB · Trace #001",+ code: `// 引用必须指向语料库中真实存在的文件+const hits = rank("如何配置 hooks?").slice(0, 6).filter((c) => fs.existsSync(c.source));+console.log(\`命中 \${hits.length} 条,用时 \${(performance.now() - t0).toFixed(1)}ms\`); // 命中 6 条,用时 12.4ms`,+ numerals: "0123456789 · 1,048,576 tokens · ¥0.1617 · 71.8 秒 · 99.95% · 第 2 轮 · v0.2.13",+};++export const SPECIMENS: Readonly<Record<"en" | "zh", Specimen>> = {+ en: { ...en, short: en.ui },+ zh: { ...zh, short: zh.ui },+};diff --git a/packages/ui-gallery/src/foundations/typography.tsx b/packages/ui-gallery/src/foundations/typography.tsxnew file mode 100644index 00000000..0f60c084--- /dev/null+++ b/packages/ui-gallery/src/foundations/typography.tsx@@ -0,0 +1,116 @@+/**+ * Foundations › Type: the role scale from h1 to caption, prose, the chrome line and code, each set+ * in its own role tokens, English and Chinese side by side — the step between rungs, the heading+ * weights, Console's mono chrome against its sans prose, and where a Latin face hands over to its+ * CJK fallback, all at a glance. `prose` is the reading face; `ui` is the chrome face `body` sets.+ */+import type { CSSProperties } from "react";+import { useGallery } from "../state";+import { SPECIMENS } from "./specimens";+import type { Specimen } from "./specimens";++interface Role {+ id: string;+ style: CSSProperties;+ text: (s: Specimen) => string;+}++const heading = (n: number, text: (s: Specimen) => string): Role => ({+ id: `h${n}`,+ style: {+ fontFamily: `var(--ui-h${n}-font)`,+ fontSize: `var(--ui-h${n}-size)`,+ lineHeight: `var(--ui-h${n}-lh)`,+ fontWeight: `var(--ui-h${n}-weight)`,+ letterSpacing: `var(--ui-h${n}-tracking)`,+ textTransform: `var(--ui-h${n}-transform)` as CSSProperties["textTransform"],+ },+ text,+});++const ROLES: readonly Role[] = [+ heading(1, (s) => s.display),+ heading(2, (s) => s.heading),+ heading(3, (s) => s.heading),+ heading(4, (s) => s.heading),+ heading(5, (s) => s.heading),+ heading(6, (s) => s.heading),+ {+ id: "prose",+ style: {+ fontFamily: "var(--ui-font-sans)",+ fontSize: "var(--ui-text-prose-size)",+ lineHeight: "var(--ui-text-prose-lh)",+ },+ text: (s) => s.paragraph,+ },+ {+ id: "body",+ style: {+ fontFamily: "var(--ui-font-sans)",+ fontSize: "var(--ui-text-body-size)",+ lineHeight: "var(--ui-text-body-lh)",+ letterSpacing: "var(--ui-tracking-body)",+ },+ text: (s) => s.ui,+ },+ {+ id: "ui",+ style: {+ fontFamily: "var(--ui-font-ui)",+ fontSize: "var(--ui-text-body-size)",+ lineHeight: "var(--ui-text-body-lh)",+ letterSpacing: "var(--ui-tracking-body)",+ },+ text: (s) => s.ui,+ },+ {+ id: "small",+ style: { fontSize: "var(--ui-text-small-size)", lineHeight: "var(--ui-text-small-lh)" },+ text: (s) => s.ui,+ },+ {+ id: "caption",+ style: {+ fontSize: "var(--ui-text-caption-size)",+ lineHeight: "var(--ui-text-caption-lh)",+ color: "var(--ui-fg-muted)",+ },+ text: (s) => s.caption,+ },+ {+ id: "code",+ style: {+ fontFamily: "var(--ui-font-mono)",+ fontSize: "var(--ui-text-code-size)",+ lineHeight: "var(--ui-text-code-lh)",+ letterSpacing: "var(--ui-tracking-mono)",+ whiteSpace: "pre-wrap",+ },+ text: (s) => s.code.split("\n").slice(0, 2).join("\n"),+ },+];++export function TypeBoard() {+ const { S } = useGallery();+ return (+ <div className="gf-board">+ <div className="gf-type">+ <span />+ <span className="gf-caption">{S.rail.langNames.en}</span>+ <span className="gf-caption">{S.rail.langNames.zh}</span>+ {ROLES.map((role) => (+ <div key={role.id} className="gf-type-row">+ <code className="gf-caption gf-mono">{role.id}</code>+ {(["en", "zh"] as const).map((lang) => (+ <p key={lang} lang={lang === "zh" ? "zh-CN" : "en"} style={role.style}>+ {role.text(SPECIMENS[lang])}+ </p>+ ))}+ </div>+ ))}+ </div>+ <p className="gf-caption gf-note">{S.foundations.typeNote}</p>+ </div>+ );+}diff --git a/packages/ui-gallery/src/lib/accents.ts b/packages/ui-gallery/src/lib/accents.tsnew file mode 100644index 00000000..0cba9784--- /dev/null+++ b/packages/ui-gallery/src/lib/accents.ts@@ -0,0 +1,50 @@+/**+ * The accent choices the rail offers: the theme's own accent (随主题, stored as `neutral`, which+ * sets no `data-accent`) and the presets the ACTIVE theme lists. Each theme declares its own list+ * in the package (`ACCENT_PRESETS` in tokens.ts — Primer the five the Web App has always had,+ * Frost a warm set, Console terminal hues), and this file is the one place the gallery reads it,+ * so the rail, the URL and the resolution agree on what a preset is.+ *+ * A chosen preset outlives the theme that listed it: it stays in the URL and in memory and goes+ * onto the root as it is — a theme's preset rules match only their own theme, so under a theme+ * that does not list it the theme's own accent shows, and the preset comes back when the reader+ * returns to a theme that does. So switching themes to look at something never loses a choice,+ * and a link with `accent=amber` means the same thing whichever theme it opens on.+ */+import {+ ACCENT_PRESET_IDS,+ ACCENT_PRESETS,+ resolveAccent as resolveListed,+ THEME_ACCENT_PRESETS,+} from "@prismshadow/penguin-ui";+import type { ThemeId } from "@prismshadow/penguin-ui";+import type { AccentChoice } from "@prismshadow/penguin-ui/boot";++/** The stored value for "no preset": the theme's own accent, no `data-accent` on the root. */+export const THEME_ACCENT: AccentChoice = "neutral";++/** The preset ids the theme lists, in its own order. */+export function accentPresetsOf(theme: ThemeId): readonly string[] {+ return THEME_ACCENT_PRESETS[theme];+}++/** Every value `accent=` may carry: the theme's own, then every theme's presets, each once. */+export const ACCENT_IDS: readonly AccentChoice[] = [THEME_ACCENT, ...ACCENT_PRESET_IDS];++/** A validated `accent=` value as the package's contract types it. */+export function asAccentChoice(accent: string): AccentChoice {+ return (ACCENT_IDS as readonly string[]).includes(accent)+ ? (accent as AccentChoice)+ : THEME_ACCENT;+}++/** What a choice paints under a theme: the preset when the theme lists it, else the theme's own. */+export function resolveAccent(theme: ThemeId, accent: string): string {+ return resolveListed(theme, accent) ?? THEME_ACCENT;+}++/** The colour a theme's preset sets in light mode, as the package spells it; `""` for none. */+export function accentSwatch(theme: ThemeId, accent: string): string {+ const presets: readonly { id: string; swatch: string }[] = ACCENT_PRESETS[theme];+ return presets.find((preset) => preset.id === accent)?.swatch ?? "";+}diff --git a/packages/ui-gallery/src/lib/breadcrumb.ts b/packages/ui-gallery/src/lib/breadcrumb.tsnew file mode 100644index 00000000..de5a9092--- /dev/null+++ b/packages/ui-gallery/src/lib/breadcrumb.ts@@ -0,0 +1,43 @@+/**+ * The quotable address of whatever a frame or a board shows, in the chrome's own language:+ *+ * Frost › Chat · dark+ * 白领 › 对话 · 深色+ * Console › Foundations › Colour · dark · amber · 20px · phone+ *+ * theme › page, then the section when the address is one section of the page, then the resolved+ * mode, then only what differs from the defaults: the accent preset (an id, the same in both+ * languages), the root size when it is not the default, and the phone frame. The language needs+ * no qualifier — the words carry it, and the chrome and the frames always share one language —+ * so one quote still means one view. The caller passes every name already localized; this file+ * only spells the address.+ */+import { DEFAULT_TEXT_SIZE } from "@prismshadow/penguin-ui/boot";+import type { TextSize } from "@prismshadow/penguin-ui/boot";+import { TEXT_SIZE_PX_NUMBER } from "./themes";++export interface BreadcrumbParts {+ /** The theme's display name. */+ theme: string;+ /** The page's title: a surface, or a module. */+ page: string;+ /** A section of the page, when the address is one section: a board of Foundations. */+ section?: string;+ /** The resolved mode's word: `dark` / `深色`. */+ mode: string;+ /** An accent preset id, when one is applied; omitted for the theme's own accent. */+ accent?: string;+ size: TextSize;+ /** The phone frame's word, when the app sits in one. */+ view?: string;+}++export function formatBreadcrumb(parts: BreadcrumbParts): string {+ const names = [parts.theme, parts.page];+ if (parts.section !== undefined) names.push(parts.section);+ const qualifiers = [parts.mode];+ if (parts.accent !== undefined) qualifiers.push(parts.accent);+ if (parts.size !== DEFAULT_TEXT_SIZE) qualifiers.push(`${TEXT_SIZE_PX_NUMBER[parts.size]}px`);+ if (parts.view !== undefined) qualifiers.push(parts.view);+ return `${names.join(" › ")} · ${qualifiers.join(" · ")}`;+}diff --git a/packages/ui-gallery/src/lib/color.ts b/packages/ui-gallery/src/lib/color.tsnew file mode 100644index 00000000..b30df167--- /dev/null+++ b/packages/ui-gallery/src/lib/color.ts@@ -0,0 +1,97 @@+/**+ * WCAG 2 contrast arithmetic for the Colour page. Colours arrive as 8-bit sRGB (the browser+ * resolves any CSS colour — `color-mix()`, `oklch()` — by painting it; see token-probe.ts), so+ * this module only parses the plain forms and does the maths.+ */++export interface Rgba {+ /** 0–255 */+ r: number;+ g: number;+ b: number;+ /** 0–1 */+ a: number;+}++/** `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` / `rgba()` in comma or space syntax, `transparent`. */+export function parseCssColor(value: string): Rgba | null {+ const v = value.trim().toLowerCase();+ if (v === "transparent") return { r: 0, g: 0, b: 0, a: 0 };+ const hex = /^#([0-9a-f]{3,8})$/.exec(v)?.[1];+ if (hex !== undefined) {+ if (hex.length === 3 || hex.length === 4) {+ const [r, g, b, a = "f"] = [...hex].map((ch) => ch + ch);+ return {+ r: parseInt(r!, 16),+ g: parseInt(g!, 16),+ b: parseInt(b!, 16),+ a: parseInt(a.length === 2 ? a : a + a, 16) / 255,+ };+ }+ if (hex.length === 6 || hex.length === 8) {+ const n = (i: number) => parseInt(hex.slice(i, i + 2), 16);+ return { r: n(0), g: n(2), b: n(4), a: hex.length === 8 ? n(6) / 255 : 1 };+ }+ return null;+ }+ const fn = /^rgba?\(\s*([^)]*)\)$/.exec(v)?.[1];+ if (fn === undefined) return null;+ const [channels, slashAlpha] = fn.split("/").map((s) => s.trim());+ const parts = (channels ?? "").split(/[\s,]+/).filter(Boolean);+ if (parts.length < 3) return null;+ const channel = (s: string) => (s.endsWith("%") ? (parseFloat(s) / 100) * 255 : parseFloat(s));+ const alphaText = slashAlpha ?? parts[3];+ const alpha =+ alphaText === undefined+ ? 1+ : alphaText.endsWith("%")+ ? parseFloat(alphaText) / 100+ : parseFloat(alphaText);+ const [r, g, b] = parts.slice(0, 3).map(channel);+ if ([r, g, b, alpha].some((n) => n === undefined || Number.isNaN(n))) return null;+ return { r: r!, g: g!, b: b!, a: alpha };+}++/** Source-over compositing of `top` onto an opaque `bottom`. */+export function composite(top: Rgba, bottom: Rgba): Rgba {+ const a = top.a;+ return {+ r: top.r * a + bottom.r * (1 - a),+ g: top.g * a + bottom.g * (1 - a),+ b: top.b * a + bottom.b * (1 - a),+ a: 1,+ };+}++export function relativeLuminance({ r, g, b }: Rgba): number {+ const lin = (c: number) => {+ const s = c / 255;+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);+}++/** The WCAG contrast ratio of two opaque colours, 1–21. */+export function contrastRatio(a: Rgba, b: Rgba): number {+ const [hi, lo] = [relativeLuminance(a), relativeLuminance(b)].sort((x, y) => y - x) as [+ number,+ number,+ ];+ return (hi + 0.05) / (lo + 0.05);+}++/** Text thresholds: 4.5 body, 3 large text and non-text marks. */+export function wcagGrade(ratio: number): "AAA" | "AA" | "AA large" | "fail" {+ if (ratio >= 7) return "AAA";+ if (ratio >= 4.5) return "AA";+ if (ratio >= 3) return "AA large";+ return "fail";+}++export function toHex({ r, g, b, a }: Rgba): string {+ const h = (n: number) =>+ Math.round(Math.min(255, Math.max(0, n)))+ .toString(16)+ .padStart(2, "0");+ return `#${h(r)}${h(g)}${h(b)}${a < 1 ? h(a * 255) : ""}`;+}diff --git a/packages/ui-gallery/src/lib/fit.ts b/packages/ui-gallery/src/lib/fit.tsnew file mode 100644index 00000000..b7102ca8--- /dev/null+++ b/packages/ui-gallery/src/lib/fit.ts@@ -0,0 +1,21 @@+/**+ * Fitting something laid out at a fixed natural width — the framed app at its window width, a+ * phone frame — into the room a page column has: it lays out at its natural width and the result+ * is scaled down, never up. Pure, so the rule is unit-tested; chrome/fit.tsx measures and+ * applies it.+ */++/**+ * The factor that fits `natural` px into `available` px. Never above 1: a narrow column shrinks+ * the frame, a wide one centres it at its natural size rather than blowing it up. A width not+ * measured yet (0) reads as no scaling, so the first paint is the frame at rest.+ */+export function fitScale(natural: number, available: number): number {+ if (!(natural > 0) || !(available > 0)) return 1;+ return Math.min(1, available / natural);+}++/** The height the fitted box takes on the page: the frame's own height at the scale. */+export function fittedHeight(height: number, scale: number): number {+ return Math.ceil(height * scale);+}diff --git a/packages/ui-gallery/src/lib/icon-registry.ts b/packages/ui-gallery/src/lib/icon-registry.tsnew file mode 100644index 00000000..57db00e1--- /dev/null+++ b/packages/ui-gallery/src/lib/icon-registry.ts@@ -0,0 +1,182 @@+/**+ * Reads the Web App's line-icon path strings out of its source text, for the Icons foundation page.+ *+ * Until W1 moves the icons into one registry in `packages/ui`, the paths are spread over a few web+ * modules, several re-export each other, and some are template literals built from shared+ * fragments. The gallery must not import web modules (they pull in the app's strings and state),+ * so it takes their raw text (`?raw`) and extracts:+ *+ * export const TRASH_ICON = "M4 6h16…"; → TRASH_ICON+ * export const HIDDEN_ICON = `${EYE_OUTLINE}M3 3l18 18`; → HIDDEN_ICON (fragment resolved)+ * export const NAV_ICONS = { usage: "M4 20V10…", agents: AGENT_GROUP_ICON };+ * → NAV_ICONS.usage, NAV_ICONS.agents+ *+ * Constants resolve across every given file. Only strings that are SVG path data survive, and+ * entries sharing one path are merged, so the page shows each distinct glyph once with every name+ * it goes by — duplicates become visible instead of silently multiplying.+ */++export interface IconEntry {+ /** The path data. */+ d: string;+ /** Every name the path is declared under, in first-seen order. */+ names: string[];+ /** The files that declare it, in first-seen order. */+ sources: string[];+}++/** SVG path data: a moveto, then only path commands, numbers and separators. */+const PATH_DATA = /^[Mm][\d\s.,eE+\-MmZzLlHhVvCcSsQqTtAa]*$/;++type Expr = { kind: "literal"; text: string } | { kind: "ref"; name: string };++interface Declaration {+ name: string;+ expr: Expr;+ source: string;+}++const STRING = String.raw`"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|\x60([^\x60\\]*)\x60`;+const REF = String.raw`([A-Z][A-Z0-9_]*(?:\.[A-Za-z_$][\w$]*)?)`;+const VALUE = String.raw`(?:${STRING}|${REF})`;++const CONST_DECL = new RegExp(+ String.raw`\bconst\s+([A-Z][A-Z0-9_]*)\s*(?::[^=;]*)?=\s*(?:${VALUE})\s*(?:as\s+const\s*)?[;\n]`,+ "g",+);+const OBJECT_DECL = new RegExp(String.raw`\bconst\s+([A-Z][A-Z0-9_]*)\s*(?::[^=;]*)?=\s*\{`, "g");+const ENTRY = new RegExp(+ String.raw`(?:^|[\s,{])([A-Za-z_$][\w$]*)\s*:\s*(?:${VALUE})\s*(?=[,}\n]|$)`,+ "g",+);++function exprOf(match: RegExpExecArray, offset: number): Expr | null {+ const [dq, sq, tpl, ref] = [+ match[offset],+ match[offset + 1],+ match[offset + 2],+ match[offset + 3],+ ];+ if (dq !== undefined) return { kind: "literal", text: dq };+ if (sq !== undefined) return { kind: "literal", text: sq };+ if (tpl !== undefined) return { kind: "literal", text: tpl };+ if (ref !== undefined) return { kind: "ref", name: ref };+ return null;+}++/** The body between the `{` at `open` and its matching `}`, skipping braces inside strings. */+function objectBody(text: string, open: number): string {+ let depth = 0;+ let quote: string | null = null;+ for (let i = open; i < text.length; i++) {+ const ch = text[i];+ if (quote !== null) {+ if (ch === "\\") i++;+ else if (ch === quote) quote = null;+ continue;+ }+ if (ch === '"' || ch === "'" || ch === "`") quote = ch;+ else if (ch === "{") depth++;+ else if (ch === "}" && --depth === 0) return text.slice(open + 1, i);+ }+ return "";+}++/** Block and line comments out, strings kept intact (a path never contains `//`, a URL might). */+function stripComments(text: string): string {+ let out = "";+ let quote: string | null = null;+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (quote !== null) {+ out += ch;+ if (ch === "\\") out += text[++i] ?? "";+ else if (ch === quote) quote = null;+ continue;+ }+ if (ch === "/" && text[i + 1] === "*") {+ const end = text.indexOf("*/", i + 2);+ i = end === -1 ? text.length : end + 1;+ continue;+ }+ if (ch === "/" && text[i + 1] === "/") {+ const end = text.indexOf("\n", i);+ i = end === -1 ? text.length : end - 1;+ continue;+ }+ if (ch === '"' || ch === "'" || ch === "`") quote = ch;+ out += ch;+ }+ return out;+}++function declarations(source: string, raw: string): Declaration[] {+ const text = stripComments(raw);+ const found: Declaration[] = [];+ for (const m of text.matchAll(CONST_DECL)) {+ const expr = exprOf(m, 2);+ if (m[1] && expr) found.push({ name: m[1], expr, source });+ }+ for (const m of text.matchAll(OBJECT_DECL)) {+ if (!m[1]) continue;+ const body = objectBody(text, (m.index ?? 0) + m[0].length - 1);+ for (const e of body.matchAll(ENTRY)) {+ const expr = exprOf(e, 2);+ if (e[1] && expr) found.push({ name: `${m[1]}.${e[1]}`, expr, source });+ }+ }+ return found;+}++export function extractIconPaths(sources: Readonly<Record<string, string>>): IconEntry[] {+ const all = Object.entries(sources).flatMap(([source, text]) => declarations(source, text));+ const table = new Map<string, Declaration>();+ for (const decl of all) if (!table.has(decl.name)) table.set(decl.name, decl);++ const resolving = new Set<string>();+ const resolve = (expr: Expr): string | null => {+ if (expr.kind === "ref") {+ const target = table.get(expr.name);+ if (!target || resolving.has(expr.name)) return null;+ resolving.add(expr.name);+ const value = resolve(target.expr);+ resolving.delete(expr.name);+ return value;+ }+ let failed = false;+ const text = expr.text.replace(+ /\$\{\s*([A-Z][A-Z0-9_]*(?:\.[A-Za-z_$][\w$]*)?)\s*\}/g,+ (_, name: string) => {+ const value = resolve({ kind: "ref", name });+ if (value === null) failed = true;+ return value ?? "";+ },+ );+ return failed ? null : text;+ };++ const byPath = new Map<string, IconEntry>();+ for (const decl of all) {+ const d = resolve(decl.expr)?.trim();+ if (!d || !PATH_DATA.test(d)) continue;+ const entry = byPath.get(d);+ if (!entry) byPath.set(d, { d, names: [decl.name], sources: [decl.source] });+ else {+ if (!entry.names.includes(decl.name)) entry.names.push(decl.name);+ if (!entry.sources.includes(decl.source)) entry.sources.push(decl.source);+ }+ }+ return [...byPath.values()];+}++/** `ICON_SIZE = { rowMark: 12, … }` → its rungs, from `lib/icon-scale.ts`'s text. */+export function extractIconSizes(raw: string): { name: string; px: number }[] {+ const text = stripComments(raw);+ const decl = /\bconst\s+ICON_SIZE\s*(?::[^=;]*)?=\s*\{/.exec(text);+ if (!decl) return [];+ const body = objectBody(text, decl.index + decl[0].length - 1);+ return [...body.matchAll(/([A-Za-z_$][\w$]*)\s*:\s*(\d+(?:\.\d+)?)/g)].map((m) => ({+ name: m[1] ?? "",+ px: Number(m[2]),+ }));+}diff --git a/packages/ui-gallery/src/lib/listbox.ts b/packages/ui-gallery/src/lib/listbox.tsnew file mode 100644index 00000000..c0451afb--- /dev/null+++ b/packages/ui-gallery/src/lib/listbox.ts@@ -0,0 +1,96 @@+/**+ * What the chrome's select shares with any listbox, pure so it is unit-tested: which option a key+ * moves the active row to (the arrows step and stop at the ends, Home and End jump, a typed+ * character jumps to the next option that starts with it), and where the panel opens against its+ * trigger — below it, or above when below lacks the room and above has more, with its left edge+ * kept inside the viewport.+ */++/** The option `key` moves to from `current` (-1 for none) among `count`; null for a key that is not navigation. */+export function nextOptionIndex(key: string, current: number, count: number): number | null {+ if (count === 0) return null;+ const last = count - 1;+ switch (key) {+ case "ArrowDown":+ return current < 0 ? 0 : Math.min(current + 1, last);+ case "ArrowUp":+ return current < 0 ? last : Math.max(current - 1, 0);+ case "Home":+ return 0;+ case "End":+ return last;+ default:+ return null;+ }+}++/**+ * The option a typed character jumps to: the first after `current` whose label starts with it,+ * wrapping round, case-folded; null when none does (or the key is not one printable character).+ */+export function typeaheadIndex(+ key: string,+ labels: readonly string[],+ current: number,+): number | null {+ if (key.length !== 1 || key === " ") return null;+ const wanted = key.toLowerCase();+ for (let step = 1; step <= labels.length; step++) {+ const index = (current + step + labels.length) % labels.length;+ if (labels[index]?.toLowerCase().startsWith(wanted)) return index;+ }+ return null;+}++/** A trigger's viewport box: the part of a DOMRect the placement reads. */+export interface Box {+ top: number;+ bottom: number;+ left: number;+ width: number;+}++export interface Viewport {+ width: number;+ height: number;+}++/** Where a listbox panel sits, in fixed viewport coordinates: exactly one of `top` / `bottom` is given. */+export interface PanelPlacement {+ top?: number;+ bottom?: number;+ left: number;+ /** The trigger's width: the panel is never narrower than what opened it. */+ minWidth: number;+}++const PANEL_GAP = 4;+const VIEWPORT_MARGIN = 16;++/**+ * Below the trigger, or above it when the room below is short of `panelHeight` and the room+ * above is larger; the left edge clamped so a panel `panelWidth` wide (the trigger's width when+ * not given) stays inside the viewport's margin.+ */+export function placePanel(+ trigger: Box,+ viewport: Viewport,+ panelHeight: number,+ panelWidth = trigger.width,+): PanelPlacement {+ const spaceBelow = viewport.height - trigger.bottom;+ const spaceAbove = trigger.top;+ const height = Math.min(panelHeight, viewport.height * 0.7);+ const upward = spaceBelow < height && spaceAbove > spaceBelow;+ const left = Math.max(+ VIEWPORT_MARGIN,+ Math.min(trigger.left, viewport.width - panelWidth - VIEWPORT_MARGIN),+ );+ return {+ ...(upward+ ? { bottom: viewport.height - trigger.top + PANEL_GAP }+ : { top: trigger.bottom + PANEL_GAP }),+ left,+ minWidth: trigger.width,+ };+}diff --git a/packages/ui-gallery/src/lib/location.ts b/packages/ui-gallery/src/lib/location.tsnew file mode 100644index 00000000..c5ddfaf8--- /dev/null+++ b/packages/ui-gallery/src/lib/location.ts@@ -0,0 +1,55 @@+/**+ * The URL as an external store: components subscribe to `location.search`, and the gallery's+ * controls rewrite it with `history.replaceState` (a view tweak is not a history entry) and keep+ * the hash, so the section in view stays put.+ */+import { useSyncExternalStore } from "react";++const listeners = new Set<() => void>();++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ window.addEventListener("popstate", listener);+ return () => {+ listeners.delete(listener);+ window.removeEventListener("popstate", listener);+ };+}++export function useSearch(): string {+ return useSyncExternalStore(subscribe, () => window.location.search);+}++export function replaceSearch(search: string): void {+ if (search === window.location.search) return;+ const { pathname, hash } = window.location;+ window.history.replaceState(window.history.state, "", `${pathname}${search}${hash}`);+ for (const listener of listeners) listener();+}++/** `import.meta.env.BASE_URL` without its trailing slash, so `${base}/embed` works at any base. */+export const BASE = import.meta.env.BASE_URL.replace(/\/$/, "");++/** The route path with the base stripped: `/`, `/embed`, `/screens/chat`, `/fonts`. */+export function routePath(): string {+ const path = window.location.pathname;+ const rest = BASE && path.startsWith(BASE) ? path.slice(BASE.length) : path;+ return rest === "" ? "/" : rest.replace(/\/+$/, "") || "/";+}++export function absoluteUrl(path: string): string {+ return `${window.location.origin}${BASE}${path}`;+}++function subscribeDark(listener: () => void): () => void {+ const query = window.matchMedia("(prefers-color-scheme: dark)");+ query.addEventListener("change", listener);+ return () => query.removeEventListener("change", listener);+}++export function usePrefersDark(): boolean {+ return useSyncExternalStore(+ subscribeDark,+ () => window.matchMedia("(prefers-color-scheme: dark)").matches,+ );+}diff --git a/packages/ui-gallery/src/lib/routes.ts b/packages/ui-gallery/src/lib/routes.tsnew file mode 100644index 00000000..3203188e--- /dev/null+++ b/packages/ui-gallery/src/lib/routes.ts@@ -0,0 +1,105 @@+/**+ * The site's routes, by path — pure, so the address rules are unit-tested and the app's switch+ * (app.tsx) stays a lookup. Every route is a full page load (each is also a screenshot target),+ * so there is no client-side router to keep in step.+ *+ * / home: the app in a frame, the surface and library indexes+ * /s/<surface> 界面: one surface's page, the app framed at that route+ * /c/<topic> 基础: one component library page, the topic's board framed+ * /fonts 字体: each theme's default faces and the current choice+ * /fonts/specimens the specimens at the five sizes and the declared faces+ * /fonts/licences the bundled faces' licence texts+ *+ * The framed documents, `app.html` and `lib.html`, are not routes of the site: their URLs are+ * built by `appFrameSrc` (src/app/frame.ts) and `libraryFrameSrc` (src/library/frame.ts), and+ * those are also what "open standalone" opens.+ *+ * The view state (theme, mode, …) rides in the query on every route (lib/url-state.ts), so a link+ * built here carries it, and a reader who follows one keeps what they had set.+ */+import { isSurfaceId } from "../app/surfaces";+import type { SurfaceId } from "../app/surfaces";+import { isTopicId } from "../library/topics";+import type { TopicId } from "../library/topics";+import { formatGalleryQuery } from "./url-state";+import type { GalleryState } from "./url-state";++export const FONTS_PAGE_IDS = ["defaults", "specimens", "licences"] as const;+export type FontsPageId = (typeof FONTS_PAGE_IDS)[number];++export type Route =+ | { kind: "home" }+ | { kind: "surface"; id: SurfaceId }+ | { kind: "topic"; id: TopicId }+ | { kind: "fonts"; page: FontsPageId }+ /** `/s/<something>`, `/c/<something>` or `/fonts/<something>` that names nothing: the page says so. */+ | { kind: "missing"; id: string }+ | { kind: "unknown"; path: string };++const isFontsPage = (id: string): id is FontsPageId =>+ (FONTS_PAGE_IDS as readonly string[]).includes(id);++/** The route a base-stripped path names (`/`, `/s/chat`, `/c/buttons`, `/fonts/specimens`). */+export function parseRoute(path: string): Route {+ const clean = path.replace(/\/+$/, "") || "/";+ if (clean === "/") return { kind: "home" };+ if (clean === "/fonts") return { kind: "fonts", page: "defaults" };+ const fonts = /^\/fonts\/([^/]+)$/.exec(clean)?.[1];+ if (fonts !== undefined) {+ const id = decodeURIComponent(fonts);+ return isFontsPage(id) ? { kind: "fonts", page: id } : { kind: "missing", id };+ }+ const surface = /^\/s\/([^/]+)$/.exec(clean)?.[1];+ if (surface !== undefined) {+ const id = decodeURIComponent(surface);+ return isSurfaceId(id) ? { kind: "surface", id } : { kind: "missing", id };+ }+ const topic = /^\/c\/([^/]+)$/.exec(clean)?.[1];+ if (topic !== undefined) {+ const id = decodeURIComponent(topic);+ return isTopicId(id) ? { kind: "topic", id } : { kind: "missing", id };+ }+ return { kind: "unknown", path: clean };+}++/** `/s/<surface>`, without the base. */+export function surfacePath(id: string): string {+ return `/s/${encodeURIComponent(id)}`;+}++/** `/c/<topic>`, without the base. */+export function topicPath(id: string): string {+ return `/c/${encodeURIComponent(id)}`;+}++/** `/fonts`, `/fonts/specimens` or `/fonts/licences`, without the base. */+export function fontsPath(page: FontsPageId): string {+ return page === "defaults" ? "/fonts" : `/fonts/${page}`;+}++/** A link to a surface page carrying the view state. */+export function surfaceHref(base: string, state: GalleryState, id: string): string {+ return `${base}${surfacePath(id)}${formatGalleryQuery(state)}`;+}++/** A link to a library page carrying the view state: `/c/<topic>?theme=…#<group>`. */+export function topicHref(base: string, state: GalleryState, id: string, anchor?: string): string {+ const query = formatGalleryQuery(state);+ return `${base}${topicPath(id)}${query}${anchor ? `#${encodeURIComponent(anchor)}` : ""}`;+}++/** A link to a fonts page carrying the view state. */+export function fontsHref(base: string, state: GalleryState, page: FontsPageId): string {+ return `${base}${fontsPath(page)}${formatGalleryQuery(state)}`;+}++/** A link to the home page, or to a section of it (`#surfaces`), carrying the view state. */+export function homeHref(base: string, state: GalleryState, anchor?: string): string {+ return `${base}/${formatGalleryQuery(state)}${anchor ? `#${anchor}` : ""}`;+}++/** The section a page's hash names, or null for none. */+export function anchorOf(hash: string): string | null {+ const id = decodeURIComponent(hash.replace(/^#/, ""));+ return id === "" ? null : id;+}diff --git a/packages/ui-gallery/src/lib/theme-fonts.ts b/packages/ui-gallery/src/lib/theme-fonts.tsnew file mode 100644index 00000000..9315b905--- /dev/null+++ b/packages/ui-gallery/src/lib/theme-fonts.ts@@ -0,0 +1,30 @@+/**+ * Each theme's default faces, for the fonts page's table: the package states them+ * (`THEME_FONTS`, kept in step with the theme sheets by the package's own test) as display names,+ * the same names the pairing options carry; a role the theme leaves to the platform is+ * `SYSTEM_FONT`, which the page prints in its own words.+ */+import { THEME_IDS } from "@prismshadow/penguin-ui";+import type { ThemeId } from "@prismshadow/penguin-ui";+import { SYSTEM_FONT, THEME_FONTS } from "@prismshadow/penguin-ui/boot";++export interface ThemeFontRow {+ theme: ThemeId;+ /** The reading and interface sans. */+ latin: string;+ cjk: string;+ mono: string;+}++/** One row per theme, in the package's order. */+export function themeFontRows(): ThemeFontRow[] {+ return THEME_IDS.map((theme) => {+ const fonts = THEME_FONTS[theme];+ return { theme, latin: fonts.latin, cjk: fonts.cjk, mono: fonts.mono };+ });+}++/** Whether a role's default is the platform's face rather than a bundled one. */+export function isSystemFont(name: string): boolean {+ return name === SYSTEM_FONT;+}diff --git a/packages/ui-gallery/src/lib/themes.ts b/packages/ui-gallery/src/lib/themes.tsnew file mode 100644index 00000000..048d8336--- /dev/null+++ b/packages/ui-gallery/src/lib/themes.ts@@ -0,0 +1,52 @@+/**+ * The preferences' display forms: the five text sizes as the top bar prints them (the size id+ * with its pixel value — the size is real: `<html style="font-size">` takes it, and every rem in+ * the framed app follows), and the font pairings the app offers, with the proper names of the+ * bundled faces (the same in both languages) and the two words — the theme's own, the platform's+ * — that the dictionaries carry. The ids are the package's own, stored and quoted as they are.+ *+ * Theme display names are chrome copy and live in the dictionaries (`S.rail.themeNames`): 通用 /+ * 白领 / 极客 in Chinese, Primer / Frost / Console in English. Ids (`github` / `modern` / `geek`)+ * stay in URLs and file names.+ */+import {+ FONT_CJK_OPTIONS,+ FONT_LATIN_OPTIONS,+ TEXT_SIZE_PX,+ TEXT_SIZES,+} from "@prismshadow/penguin-ui/boot";+import type { FontCjk, FontLatin, TextSize } from "@prismshadow/penguin-ui/boot";++export { TEXT_SIZES };+export type { FontCjk, FontLatin, TextSize };++/** Root font size per text size, in CSS px, from the package's own table. */+export const TEXT_SIZE_PX_NUMBER: Readonly<Record<TextSize, number>> = Object.fromEntries(+ TEXT_SIZES.map((size) => [size, Number.parseFloat(TEXT_SIZE_PX[size])]),+) as Record<TextSize, number>;++/**+ * The retired three-step scale, still found in links quoted before the five sizes: mapped by+ * its pixels, the way the app migrates a stored value.+ */+export const LEGACY_SIZES: Readonly<Record<string, TextSize>> = { sm: "m", md: "l", lg: "xl" };++/** The Latin (reading and UI sans) choices, in the order the app lists them. */+export const LATIN_FONTS: readonly FontLatin[] = FONT_LATIN_OPTIONS.map((option) => option.id);++/** The CJK choices, likewise. */+export const CJK_FONTS: readonly FontCjk[] = FONT_CJK_OPTIONS.map((option) => option.id);++/**+ * A pairing's display name: the package's proper name for a bundled face; for `theme` and+ * `system`, the caller's own words (the dictionaries carry them in both languages).+ */+export function fontLabel(+ id: FontLatin | FontCjk,+ words: { theme: string; system: string },+): string {+ if (id === "theme") return words.theme;+ if (id === "system") return words.system;+ const option = [...FONT_LATIN_OPTIONS, ...FONT_CJK_OPTIONS].find((o) => o.id === id);+ return option?.label ?? id;+}diff --git a/packages/ui-gallery/src/lib/tip.ts b/packages/ui-gallery/src/lib/tip.tsnew file mode 100644index 00000000..192c261c--- /dev/null+++ b/packages/ui-gallery/src/lib/tip.ts@@ -0,0 +1,61 @@+/**+ * When a tooltip shows and where it hangs, pure so both are unit-tested.+ *+ * It shows only when the element shows no text of its own (an icon-only control) or when the+ * text it shows is cut off — some box of it, the element or a descendant, scrolls wider or taller+ * than it is. An element whose words are all on screen gets no hint, whatever it carries: the+ * hint would only repeat them.+ *+ * Placement: under the trigger, aligned to whichever+ * of its vertical edges faces the roomier half of the window, so the panel always grows inward —+ * a control at the right end of the top bar gets a panel that grows leftward and stays on+ * screen. `room` is how wide the panel may grow from its anchored edge before it would cross the+ * margin on the other side; a long hint wraps at it.+ */++export interface TipBox {+ bottom: number;+ left: number;+ right: number;+ width: number;+}++/** Exactly one of `left` / `right` is given: the edge the panel is pinned by. */+export interface TipPlacement {+ top: number;+ left?: number;+ right?: number;+ room: number;+}++const TIP_GAP = 6;+const VIEWPORT_MARGIN = 8;++export function placeTip(+ trigger: TipBox,+ viewport: { width: number; height: number },+): TipPlacement {+ const top = trigger.bottom + TIP_GAP;+ if (trigger.left + trigger.width / 2 > viewport.width / 2) {+ const right = Math.max(viewport.width - trigger.right, VIEWPORT_MARGIN);+ return { top, right, room: Math.max(viewport.width - right - VIEWPORT_MARGIN, 0) };+ }+ const left = Math.max(trigger.left, VIEWPORT_MARGIN);+ return { top, left, room: Math.max(viewport.width - left - VIEWPORT_MARGIN, 0) };+}++/** The overflow facts of one box, as the DOM reports them. */+export interface OverflowBox {+ scrollWidth: number;+ clientWidth: number;+ scrollHeight: number;+ clientHeight: number;+}++const overflows = (box: OverflowBox) =>+ box.scrollWidth > box.clientWidth || box.scrollHeight > box.clientHeight;++/** Whether an element with this visible text and these boxes (itself and its descendants) gets a hint. */+export function shouldHint(text: string, boxes: readonly OverflowBox[]): boolean {+ return text.trim() === "" || boxes.some(overflows);+}diff --git a/packages/ui-gallery/src/lib/token-probe.ts b/packages/ui-gallery/src/lib/token-probe.tsnew file mode 100644index 00000000..06514c1f--- /dev/null+++ b/packages/ui-gallery/src/lib/token-probe.ts@@ -0,0 +1,142 @@+/**+ * Resolves every contract token in every theme × mode, as the browser computes it — and, on the+ * same footing, each theme's accent presets.+ *+ * The theme files select on `:root[data-theme]`, `:root.dark` and `:root[data-accent]`, so a+ * theme only takes effect on a document root. The probe therefore copies the page's own CSS into a+ * hidden, same-origin blank frame and flips that frame's root through the theme × mode pairs (and+ * the accent presets), reading each token with `getComputedStyle` — synchronous, and nothing on+ * the visible page restyles. A custom property's computed value has its `var()` references+ * substituted, so `--ui-accent-line: var(--ui-accent)` comes back as the colour it points at; an+ * undefined token comes back as the empty string.+ */+import { THEME_IDS, THEME_MODES, TOKEN_NAMES } from "@prismshadow/penguin-ui";+import type { ThemeId, ThemeModeName } from "@prismshadow/penguin-ui";+import { applyThemeAttributes } from "@prismshadow/penguin-ui/boot";+import { accentPresetsOf, THEME_ACCENT } from "./accents";+import type { Rgba } from "./color";++/** Token name → resolved value (`""` when the theme leaves it undefined). */+export type TokenValues = Readonly<Record<string, string>>;+export type TokenMatrix = Readonly<Record<ThemeId, Readonly<Record<ThemeModeName, TokenValues>>>>;++/**+ * Per theme × mode: `neutral` → the theme's own `--ui-accent`, and each listed preset id → the+ * `--ui-accent` it sets, so a swatch can be painted in the preset's own colour.+ */+export type AccentMatrix = Readonly<+ Record<ThemeId, Readonly<Record<ThemeModeName, Readonly<Record<string, string>>>>>+>;++function documentCss(doc: Document): string {+ const chunks: string[] = [];+ for (const sheet of Array.from(doc.styleSheets)) {+ try {+ for (const rule of Array.from(sheet.cssRules)) chunks.push(rule.cssText);+ } catch {+ // A cross-origin sheet hides its rules; the gallery loads none, and none carries tokens.+ }+ }+ return chunks.join("\n");+}++/** Runs `read` against the root of a hidden frame that carries the page's CSS, then removes it. */+function withProbeRoot<T>(read: (root: HTMLElement, win: Window) => T): T {+ const frame = document.createElement("iframe");+ frame.setAttribute("aria-hidden", "true");+ frame.tabIndex = -1;+ frame.style.cssText =+ "position:fixed;width:0;height:0;border:0;visibility:hidden;pointer-events:none";+ document.body.appendChild(frame);+ try {+ const doc = frame.contentDocument;+ const win = frame.contentWindow;+ if (!doc || !win) throw new Error("token probe: the blank frame has no document");+ const style = doc.createElement("style");+ style.textContent = documentCss(document);+ doc.head.appendChild(style);+ return read(doc.documentElement, win);+ } finally {+ frame.remove();+ }+}++/** The root's `data-accent` for a choice: absent for the theme's own accent. */+function setAccent(root: HTMLElement, accent: string): void {+ if (accent === THEME_ACCENT) delete root.dataset.accent;+ else root.dataset.accent = accent;+}++export function probeTokens(): TokenMatrix {+ return withProbeRoot((root, win) => {+ const matrix = {} as Record<ThemeId, Record<ThemeModeName, TokenValues>>;+ for (const themeId of THEME_IDS) {+ matrix[themeId] = {} as Record<ThemeModeName, TokenValues>;+ for (const mode of THEME_MODES) {+ applyThemeAttributes(root, { themeId, dark: mode === "dark" });+ const computed = win.getComputedStyle(root);+ const values: Record<string, string> = {};+ for (const name of TOKEN_NAMES) values[name] = computed.getPropertyValue(name).trim();+ matrix[themeId][mode] = values;+ }+ }+ return matrix;+ });+}++export function probeAccents(): AccentMatrix {+ return withProbeRoot((root, win) => {+ const matrix = {} as Record<ThemeId, Record<ThemeModeName, Record<string, string>>>;+ for (const themeId of THEME_IDS) {+ matrix[themeId] = {} as Record<ThemeModeName, Record<string, string>>;+ for (const mode of THEME_MODES) {+ applyThemeAttributes(root, { themeId, dark: mode === "dark" });+ const values: Record<string, string> = {};+ for (const accent of [THEME_ACCENT, ...accentPresetsOf(themeId)]) {+ setAccent(root, accent);+ values[accent] = win.getComputedStyle(root).getPropertyValue("--ui-accent").trim();+ }+ setAccent(root, THEME_ACCENT);+ matrix[themeId][mode] = values;+ }+ }+ return matrix;+ });+}++let paintCtx: CanvasRenderingContext2D | null | undefined;++/**+ * Paints a CSS colour (optionally over an opaque backdrop) into one canvas pixel and reads it back+ * as 8-bit sRGB — the one way to get numbers out of `color-mix()`, `oklch()` or `color()` without+ * a colour library. Returns null for anything that is not a colour.+ */+export function paintColor(value: string, backdrop?: string): Rgba | null {+ if (value === "") return null;+ if (paintCtx === undefined) {+ const canvas = document.createElement("canvas");+ canvas.width = 1;+ canvas.height = 1;+ paintCtx = canvas.getContext("2d", { willReadFrequently: true });+ }+ const ctx = paintCtx;+ if (!ctx) return null;+ // An invalid assignment leaves fillStyle unchanged; two different sentinels tell it apart from a+ // value that happens to equal one of them.+ const accepted = (sentinel: string) => {+ ctx.fillStyle = sentinel;+ const before = ctx.fillStyle;+ ctx.fillStyle = value;+ return ctx.fillStyle !== before;+ };+ if (!accepted("#010203") && !accepted("#040506")) return null;+ ctx.clearRect(0, 0, 1, 1);+ if (backdrop) {+ ctx.fillStyle = backdrop;+ ctx.fillRect(0, 0, 1, 1);+ }+ ctx.fillStyle = value;+ ctx.fillRect(0, 0, 1, 1);+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data;+ return { r, g, b, a: a / 255 };+}diff --git a/packages/ui-gallery/src/lib/url-state.ts b/packages/ui-gallery/src/lib/url-state.tsnew file mode 100644index 00000000..906ae3ed--- /dev/null+++ b/packages/ui-gallery/src/lib/url-state.ts@@ -0,0 +1,119 @@+/**+ * The gallery's view state, which lives in the URL so any view can be quoted as a link.+ *+ * /s/chat?theme=geek&mode=dark&size=l&latin=mona-sans&cjk=theme&lang=zh&accent=neutral&view=phone+ *+ * `theme`, `mode`, `size`, `latin`, `cjk`, `lang` and `accent` are always written out — they are+ * also the preferences a fresh visit restores from the last one, so a copied link must pin them+ * or it would open on the reader's own — and a link keeps meaning the same thing if a default+ * ever changes. `view` appears only when set: `view=phone` frames every surface at phone width.+ * Pure: parsing never throws, and an unknown or missing value falls back to the caller's+ * fallback (the last-used value) and then to the default.+ *+ * The preferences are the app's own: the frame writes them under the app's storage keys, and the+ * gallery's root applies them through the package's `applyThemeAttributes`, so a size or a font+ * pairing chosen here is what a user of the app would have chosen in its Settings.+ */+import { DEFAULT_THEME_ID, THEME_IDS } from "@prismshadow/penguin-ui";+import type { ThemeId } from "@prismshadow/penguin-ui";+import { DEFAULT_TEXT_SIZE, TEXT_SIZES } from "@prismshadow/penguin-ui/boot";+import type { TextSize } from "@prismshadow/penguin-ui/boot";+import { ACCENT_IDS, THEME_ACCENT } from "./accents";+import { CJK_FONTS, LATIN_FONTS, LEGACY_SIZES } from "./themes";+import type { FontCjk, FontLatin } from "./themes";++export const MODE_PREFS = ["light", "dark", "system"] as const;+export type ModePref = (typeof MODE_PREFS)[number];++export const LANGS = ["en", "zh"] as const;+export type Lang = (typeof LANGS)[number];++/** Desktop: the app at its window width. Phone: the app in a 390 px frame. */+export const VIEWS = ["desktop", "phone"] as const;+export type View = (typeof VIEWS)[number];++export interface GalleryState {+ theme: ThemeId;+ mode: ModePref;+ size: TextSize;+ latin: FontLatin;+ cjk: FontCjk;+ lang: Lang;+ /**+ * An accent preset id, or `neutral` for the theme's own accent (随主题). Kept as chosen even+ * when the active theme does not list it: it resolves to the theme's own accent for now and+ * comes back when the reader returns to a theme that lists it.+ */+ accent: string;+ view: View;+}++export const DEFAULT_STATE: GalleryState = {+ theme: DEFAULT_THEME_ID,+ mode: "light",+ size: DEFAULT_TEXT_SIZE,+ latin: "theme",+ cjk: "theme",+ lang: "en",+ accent: THEME_ACCENT,+ view: "desktop",+};++/** The seven preferences a fresh visit restores from the last one when the URL omits them. */+export const PREF_KEYS = ["theme", "mode", "size", "latin", "cjk", "lang", "accent"] as const;+export type PrefKey = (typeof PREF_KEYS)[number];+export type RememberedPrefs = Partial<Pick<GalleryState, PrefKey>>;++function pick<T extends string>(+ allowed: readonly T[],+ ...candidates: (string | null | undefined)[]+): T | undefined {+ for (const value of candidates) {+ if (value != null && (allowed as readonly string[]).includes(value)) return value as T;+ }+ return undefined;+}++/** A `size=` value, with the retired `tier=` scale (sm / md / lg) read the way the app migrates it. */+function parseSize(params: URLSearchParams): string | null {+ const size = params.get("size");+ if (size !== null) return LEGACY_SIZES[size] ?? size;+ const tier = params.get("tier");+ return tier === null ? null : (LEGACY_SIZES[tier] ?? null);+}++export function parseGalleryState(search: string, remembered: RememberedPrefs = {}): GalleryState {+ const params = new URLSearchParams(search);+ return {+ theme: pick(THEME_IDS, params.get("theme"), remembered.theme) ?? DEFAULT_STATE.theme,+ mode: pick(MODE_PREFS, params.get("mode"), remembered.mode) ?? DEFAULT_STATE.mode,+ size: pick(TEXT_SIZES, parseSize(params), remembered.size) ?? DEFAULT_STATE.size,+ latin: pick(LATIN_FONTS, params.get("latin"), remembered.latin) ?? DEFAULT_STATE.latin,+ cjk: pick(CJK_FONTS, params.get("cjk"), remembered.cjk) ?? DEFAULT_STATE.cjk,+ lang: pick(LANGS, params.get("lang"), remembered.lang) ?? DEFAULT_STATE.lang,+ accent: pick(ACCENT_IDS, params.get("accent"), remembered.accent) ?? DEFAULT_STATE.accent,+ view: pick(VIEWS, params.get("view")) ?? DEFAULT_STATE.view,+ };+}++/** A readable query component: `encodeURIComponent` keeps `-_.!~*'()` as they are. */+const enc = encodeURIComponent;++/**+ * The canonical query string (with its leading `?`) for a state. `extra` params come right after+ * the preferences, in the order given.+ */+export function formatGalleryQuery(+ state: GalleryState,+ extra: Readonly<Record<string, string>> = {},+): string {+ const parts = PREF_KEYS.map((key) => `${key}=${enc(state[key])}`);+ for (const [key, value] of Object.entries(extra)) parts.push(`${enc(key)}=${enc(value)}`);+ if (state.view !== DEFAULT_STATE.view) parts.push(`view=${enc(state.view)}`);+ return `?${parts.join("&")}`;+}++/** `system` resolved against the OS preference; every other mode is itself. */+export function resolveMode(mode: ModePref, prefersDark: boolean): "light" | "dark" {+ return mode === "system" ? (prefersDark ? "dark" : "light") : mode;+}diff --git a/packages/ui-gallery/src/lib/use-scroll-spy.ts b/packages/ui-gallery/src/lib/use-scroll-spy.tsnew file mode 100644index 00000000..af014568--- /dev/null+++ b/packages/ui-gallery/src/lib/use-scroll-spy.ts@@ -0,0 +1,41 @@+/**+ * Scroll-spy for "on this page": the id of the last section whose top has crossed the activation+ * line — just under the sticky top bar — measured with viewport rects on a rAF-throttled+ * capture-phase scroll listener.+ */+import { useEffect, useState } from "react";++const ACTIVATION_LINE_PX = 120;++export function useScrollSpy(ids: readonly string[]): string | null {+ const [active, setActive] = useState<string | null>(null);+ const key = ids.join("|");+ useEffect(() => {+ let raf = 0;+ const measure = () => {+ raf = 0;+ let current: string | null = ids[0] ?? null;+ for (const id of ids) {+ const el = document.getElementById(id);+ if (!el) continue;+ if (el.getBoundingClientRect().top <= ACTIVATION_LINE_PX) current = id;+ else break;+ }+ setActive(current);+ };+ const schedule = () => {+ if (raf === 0) raf = requestAnimationFrame(measure);+ };+ measure();+ document.addEventListener("scroll", schedule, { capture: true, passive: true });+ window.addEventListener("resize", schedule);+ return () => {+ document.removeEventListener("scroll", schedule, { capture: true });+ window.removeEventListener("resize", schedule);+ if (raf) cancelAnimationFrame(raf);+ };+ // The id list is captured through its joined key.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key]);+ return active;+}diff --git a/packages/ui-gallery/src/library/boards.tsx b/packages/ui-gallery/src/library/boards.tsxnew file mode 100644index 00000000..ee52e5fe--- /dev/null+++ b/packages/ui-gallery/src/library/boards.tsx@@ -0,0 +1,54 @@+/**+ * The board each topic renders inside its frame: the component boards (src/library/boards/*)+ * and the Foundations boards (src/foundations/*). One entry per topic id; a test checks the+ * registry covers every topic.+ */+import type { ComponentType } from "react";+import { ColourBoard } from "../foundations/color";+import { SpacingBoard } from "../foundations/density";+import { FocusBoard } from "../foundations/focus";+import { HooksBoard } from "../foundations/hooks";+import { IconsBoard } from "../foundations/icons";+import { MotionBoard } from "../foundations/motion";+import { ShapeBoard } from "../foundations/shape";+import { TypeBoard } from "../foundations/typography";+import { AvatarsBoard } from "./boards/avatars";+import { BadgesBoard } from "./boards/badges";+import { ButtonsBoard } from "./boards/buttons";+import { ChartsBoard } from "./boards/charts";+import { DialogsBoard } from "./boards/dialogs";+import { EmptyBoard } from "./boards/empty";+import { FilesBoard } from "./boards/files";+import { InputsBoard } from "./boards/inputs";+import { LoadingBoard } from "./boards/loading";+import { NoticesBoard } from "./boards/notices";+import { PickersBoard } from "./boards/pickers";+import { TabsBoard } from "./boards/tabs";+import { ToastsBoard } from "./boards/toasts";+import { TooltipsBoard } from "./boards/tooltips";+import type { TopicId } from "./topics";++export const BOARDS: Readonly<Record<TopicId, ComponentType>> = {+ buttons: ButtonsBoard,+ inputs: InputsBoard,+ pickers: PickersBoard,+ toasts: ToastsBoard,+ notices: NoticesBoard,+ dialogs: DialogsBoard,+ tooltips: TooltipsBoard,+ tabs: TabsBoard,+ badges: BadgesBoard,+ empty: EmptyBoard,+ loading: LoadingBoard,+ charts: ChartsBoard,+ avatars: AvatarsBoard,+ files: FilesBoard,+ colour: ColourBoard,+ type: TypeBoard,+ shape: ShapeBoard,+ density: SpacingBoard,+ focus: FocusBoard,+ motion: MotionBoard,+ icons: IconsBoard,+ hooks: HooksBoard,+};diff --git a/packages/ui-gallery/src/library/boards/avatars.tsx b/packages/ui-gallery/src/library/boards/avatars.tsxnew file mode 100644index 00000000..eb4d8bd9--- /dev/null+++ b/packages/ui-gallery/src/library/boards/avatars.tsx@@ -0,0 +1,51 @@+/** 头像: the user avatar at its two rungs, with and without a nickname, and the agent avatar at three sizes. */+import { AgentAvatar } from "../../../../web/src/components/ui/agent-avatar";+import { USER_AVATAR_SIZE, UserAvatar } from "../../../../web/src/components/ui/user-avatar";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function AvatarsBoard() {+ const { S } = useGallery();+ const t = S.library.avatars;+ const [userId, displayName] = t.userNames;+ return (+ <div className="gf-board">+ <BoardGroup title={t.user}>+ <div className="lib-row">+ <span className="lib-cell">+ <UserAvatar userId={userId ?? "admin"} />+ <span className="lib-caption">{userId}</span>+ </span>+ <span className="lib-cell">+ <UserAvatar userId={userId ?? "admin"} displayName={displayName} />+ <span className="lib-caption">{displayName}</span>+ </span>+ <span className="lib-cell">+ <UserAvatar+ userId={userId ?? "admin"}+ displayName={displayName}+ size={USER_AVATAR_SIZE.preview}+ />+ <span className="lib-caption">{USER_AVATAR_SIZE.preview}px</span>+ </span>+ </div>+ </BoardGroup>+ <BoardGroup title={t.agent}>+ <div className="lib-row">+ {t.agents.map((agent) => (+ <span key={agent.id} className="lib-cell">+ <AgentAvatar id={agent.id} name={agent.name} />+ <span className="lib-caption">{agent.name}</span>+ </span>+ ))}+ {[24, 32].map((size) => (+ <span key={size} className="lib-cell">+ <AgentAvatar id={t.agents[0]?.id ?? "agent"} name={t.agents[0]?.name} size={size} />+ <span className="lib-caption">{size}px</span>+ </span>+ ))}+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/badges.tsx b/packages/ui-gallery/src/library/boards/badges.tsxnew file mode 100644index 00000000..48d1df1f--- /dev/null+++ b/packages/ui-gallery/src/library/boards/badges.tsx@@ -0,0 +1,79 @@+/** 徽标与状态: Badge in every tone, StatusIcon in every run state, the session activity marks, and the update dot and pill. */+import { Badge } from "../../../../web/src/components/ui/badge";+import type { BadgeTone } from "../../../../web/src/components/ui/badge";+import {+ BackgroundTasksMark,+ ScheduleMark,+ SessionActivityIcon,+} from "../../../../web/src/components/ui/session-activity-icon";+import { StatusIcon } from "../../../../web/src/components/ui/status-icon";+import type { RunState } from "../../../../web/src/components/ui/status-icon";+import { UpdateDot, UpdatePill } from "../../../../web/src/components/ui/update-dot";+import { ICON_SIZE } from "../../../../web/src/lib/icon-scale";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++const BADGE_TONES: readonly BadgeTone[] = ["gray", "brand", "green", "amber", "red"];+const RUN_STATES: readonly RunState[] = ["running", "waiting", "done", "failed", "stopped"];+const ACTIVITIES = ["running", "compacting", "completedUnread"] as const;++export function BadgesBoard() {+ const { S } = useGallery();+ const t = S.library.badges;+ return (+ <div className="gf-board">+ <BoardGroup title={t.badges}>+ <div className="lib-row">+ {BADGE_TONES.map((tone) => (+ <Badge key={tone} tone={tone}>+ {t.tones[tone]}+ </Badge>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.status}>+ <div className="lib-row">+ {RUN_STATES.map((state) => (+ <span key={state} className="lib-cell">+ <StatusIcon state={state} size={16} label={t.states[state]} />+ <span className="lib-caption">{t.states[state]}</span>+ </span>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.activity}>+ <div className="lib-row">+ {ACTIVITIES.map((activity) => (+ <span key={activity} className="lib-cell">+ <SessionActivityIcon activity={activity} />+ <span className="lib-caption">{t.activities[activity]}</span>+ </span>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.marks}>+ <div className="lib-row">+ <span className="lib-cell">+ <BackgroundTasksMark label={t.background} size={ICON_SIZE.rowMark} />+ <span className="lib-caption">{t.background}</span>+ </span>+ <span className="lib-cell">+ <ScheduleMark size={ICON_SIZE.rowMark} />+ <span className="lib-caption">{t.schedule}</span>+ </span>+ <span className="lib-cell">+ <span className="relative inline-flex rounded-md border px-2 py-1 text-sm">+ {t.dotAnchor}+ <UpdateDot />+ </span>+ <span className="lib-caption">{t.dot}</span>+ </span>+ <span className="lib-cell">+ <UpdatePill onClick={() => undefined}>{t.pillText}</UpdatePill>+ <span className="lib-caption">{t.pill}</span>+ </span>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/buttons.tsx b/packages/ui-gallery/src/library/boards/buttons.tsxnew file mode 100644index 00000000..868a4f27--- /dev/null+++ b/packages/ui-gallery/src/library/boards/buttons.tsx@@ -0,0 +1,50 @@+/** 按钮: the app's Button in its four variants, two sizes and the icon form, disabled and busy. */+import { Button } from "../../../../web/src/components/ui/button";+import { PlusIcon } from "../../../../web/src/components/ui/icons";+import { StatusIcon } from "../../../../web/src/components/ui/status-icon";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function ButtonsBoard() {+ const { S } = useGallery();+ const t = S.library.buttons;+ return (+ <div className="gf-board">+ <BoardGroup title={t.variants}>+ <div className="lib-row">+ <Button variant="primary">{t.primary}</Button>+ <Button variant="secondary">{t.secondary}</Button>+ <Button variant="danger">{t.danger}</Button>+ <Button variant="ghost">{t.ghost}</Button>+ </div>+ </BoardGroup>+ <BoardGroup title={t.sizes}>+ <div className="lib-row">+ <Button variant="primary" size="md">+ {t.md}+ </Button>+ <Button variant="primary" size="sm">+ {t.sm}+ </Button>+ <Button variant="secondary" size="icon" aria-label={t.icon} data-tooltip={t.icon}>+ <PlusIcon />+ </Button>+ </div>+ </BoardGroup>+ <BoardGroup title={t.states}>+ <div className="lib-row">+ <Button variant="primary" disabled>+ {t.disabled}+ </Button>+ <Button variant="secondary" disabled>+ {t.disabled}+ </Button>+ <Button variant="primary" disabled aria-busy>+ <StatusIcon state="running" />+ <span>{t.busy}</span>+ </Button>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/chart-primitives.tsx b/packages/ui-gallery/src/library/boards/chart-primitives.tsxnew file mode 100644index 00000000..f9388451--- /dev/null+++ b/packages/ui-gallery/src/library/boards/chart-primitives.tsx@@ -0,0 +1,231 @@+/**+ * The chart primitives on their own (packages/web/src/components/ui/chart), each on a small+ * stage with demo data: the bar, the line, the area, the point, the arc, the grid and axis+ * labels, and the Trace timeline's HTML bar. They read the theme's chart tokens themselves; the+ * stages only say where a mark sits and which slot it paints with.+ *+ * The line's curve is the theme's (`--ui-chart-curve`), so ChartLine draws in one curve at a+ * time; beside it the three values the token may take are drawn with the same path helper the+ * primitive uses, as a key to what the token chooses.+ */+import type { ReactNode } from "react";+import { useChartStyle } from "../../../../web/src/lib/chart-style";+import type { ChartCurve } from "../../../../web/src/lib/chart-style";+import {+ ChartArc,+ ChartArea,+ ChartAxis,+ ChartBar,+ ChartGrid,+ ChartLine,+ ChartPoint,+ TimelineBar,+ curvePath,+} from "../../../../web/src/components/ui/chart";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++const W = 240;+const H = 100;+const BASE = 84;++/** Five points across the stage, the shape every line-like stage shares. */+const POINTS: ReadonlyArray<readonly [number, number]> = [+ [20, 70],+ [70, 34],+ [120, 52],+ [170, 22],+ [220, 44],+];++const CURVES: readonly ChartCurve[] = ["linear", "smooth", "step"];++/** The Trace timeline's five bar kinds on their slots (1, 3, 2, 4, 5) and where each sits in the lane. */+const LANES = [+ { kind: "thinking", series: 0, left: 0, width: 22 },+ { kind: "tool_call", series: 2, left: 22, width: 8 },+ { kind: "approval", series: 3, left: 32, width: 12 },+ { kind: "tool", series: 4, left: 44, width: 26 },+ { kind: "text", series: 1, left: 72, width: 28 },+] as const;++function Stage({ children, label }: { children: ReactNode; label: string }) {+ return (+ <svg+ className="lib-stage"+ viewBox={`0 0 ${W} ${H}`}+ role="img"+ aria-label={label}+ xmlns="http://www.w3.org/2000/svg"+ >+ {children}+ </svg>+ );+}++export function ChartPrimitives() {+ const { S } = useGallery();+ const t = S.library.charts.primitives;+ const chart = useChartStyle();+ return (+ <>+ <BoardGroup title={t.bar} aside={t.barHint}>+ <Stage label={t.bar}>+ {[62, 38, 50, 24, 44].map((height, i) => (+ <ChartBar+ key={i}+ cx={24 + i * 40}+ band={40}+ y={BASE - height}+ height={height}+ paint={{ series: i }}+ />+ ))}+ <ChartBar+ cx={224}+ band={40}+ y={BASE - 30}+ height={30}+ paint={{ series: 5 }}+ top={false}+ />+ <ChartBar cx={224} band={40} y={BASE - 56} height={26} paint={{ series: 6 }} />+ </Stage>+ </BoardGroup>+ <BoardGroup title={t.line} aside={t.lineHint}>+ <div className="lib-row">+ <Stage label={`${t.line} · ${chart.curve}`}>+ <ChartLine points={POINTS} paint={{ series: 0 }} />+ <ChartLine+ points={POINTS.map(([x, y]) => [x, y + 18] as const)}+ paint={{ role: "ref" }}+ dash="4 3"+ />+ </Stage>+ <span className="lib-caption">--ui-chart-curve: {chart.curve}</span>+ </div>+ <div className="lib-row">+ {CURVES.map((curve) => (+ <span key={curve} className="lib-cell">+ <svg className="lib-stage lib-stage-small" viewBox={`0 0 ${W} ${H}`} aria-hidden>+ <path+ d={curvePath(POINTS, curve)}+ fill="none"+ stroke="currentColor"+ strokeWidth={chart.lineWidth}+ className="text-[var(--ui-fg-muted)]"+ />+ </svg>+ <span className="lib-caption">{t.curves[curve]}</span>+ </span>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.area} aside={t.areaHint}>+ <Stage label={t.area}>+ <ChartArea points={POINTS} baseY={BASE} paint={{ series: 2 }} />+ <ChartLine points={POINTS} paint={{ series: 2 }} />+ </Stage>+ </BoardGroup>+ <BoardGroup title={t.point} aside={t.pointHint}>+ <Stage label={t.point}>+ {POINTS.map(([x, y], i) => (+ <ChartPoint key={i} cx={x} cy={y} paint={{ series: i }} grow={i === 3} />+ ))}+ </Stage>+ </BoardGroup>+ <BoardGroup title={t.arc} aside={t.arcHint}>+ <Stage label={t.arc}>+ <ChartArc+ cx={50}+ cy={50}+ r={36}+ width={10}+ paint={{ ink: "text-[var(--ui-fg-subtle)]" }}+ track+ trackOpacity={0.3}+ />+ <ChartArc cx={50} cy={50} r={36} width={10} paint={{ role: "cacheRead" }} length={110} />+ <ChartArc+ cx={50}+ cy={50}+ r={36}+ width={10}+ paint={{ role: "cacheWrite" }}+ length={40}+ offset={-110}+ />+ <ChartArc+ cx={50}+ cy={50}+ r={36}+ width={10}+ paint={{ role: "output" }}+ length={30}+ offset={-150}+ />+ <ChartArc+ cx={150}+ cy={50}+ r={36}+ width={10}+ paint={{ ink: "text-[var(--ui-fg-subtle)]" }}+ track+ trackOpacity={0.3}+ />+ {[0, 1, 2, 3].map((slot) => (+ <ChartArc+ key={slot}+ cx={150}+ cy={50}+ r={36}+ width={10}+ paint={{ series: slot }}+ length={40}+ offset={-slot * 48}+ />+ ))}+ </Stage>+ </BoardGroup>+ <BoardGroup title={t.grid} aside={t.gridHint}>+ <Stage label={t.grid}>+ {[20, 50, 80].map((y, i) => (+ <g key={y}>+ <ChartGrid x1={36} x2={W - 8} y={y} />+ <ChartAxis x={30} y={y + 3} anchor="end">+ {[100, 50, 0][i]}+ </ChartAxis>+ </g>+ ))}+ {["09-15", "09-22", "09-28"].map((label, i) => (+ <ChartAxis+ key={label}+ x={36 + i * 98}+ y={H - 4}+ anchor={i === 0 ? "start" : i === 2 ? "end" : "middle"}+ >+ {label}+ </ChartAxis>+ ))}+ <ChartLine points={POINTS} paint={{ series: 0 }} />+ </Stage>+ </BoardGroup>+ <BoardGroup title={t.timeline} aside={t.timelineHint}>+ <div className="lib-stack">+ {LANES.map((lane) => (+ <div key={lane.kind} className="lib-lane">+ <span className="lib-caption lib-lane-label">{t.kinds[lane.kind]}</span>+ <div className="lib-lane-track">+ <TimelineBar+ paint={{ series: lane.series }}+ place={{ left: `${lane.left}%`, width: `${lane.width}%` }}+ aria-hidden+ />+ </div>+ </div>+ ))}+ </div>+ </BoardGroup>+ </>+ );+}diff --git a/packages/ui-gallery/src/library/boards/chart-tokens.tsx b/packages/ui-gallery/src/library/boards/chart-tokens.tsxnew file mode 100644index 00000000..5545fd3f--- /dev/null+++ b/packages/ui-gallery/src/library/boards/chart-tokens.tsx@@ -0,0 +1,83 @@+/**+ * The current theme's chart tokens, live: the palette as swatches and the geometry as values,+ * read from this frame root's computed style — the theme under test, since the frame carries the+ * page's theme attributes — and read again when the root's theme attributes change.+ */+import { useEffect, useState } from "react";+import { useGallery } from "../../state";+import { readChartTokens } from "../chart-tokens";+import type { ChartToken, ChartTokenRow } from "../chart-tokens";++type Tokens = ReturnType<typeof readChartTokens>;++function read(): Tokens {+ const computed = getComputedStyle(document.documentElement);+ return readChartTokens((name) => computed.getPropertyValue(name));+}++function useChartTokens(): Tokens | null {+ const [tokens, setTokens] = useState<Tokens | null>(null);+ useEffect(() => {+ const update = () => setTokens(read());+ update();+ const observer = new MutationObserver(update);+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class", "data-theme", "data-accent", "style"],+ });+ return () => observer.disconnect();+ }, []);+ return tokens;+}++function TokenRows<T extends ChartToken>({+ rows,+ swatch,+}: {+ rows: readonly ChartTokenRow<T>[];+ /** Paint the value as a colour beside its name. */+ swatch: boolean;+}) {+ const { S } = useGallery();+ return (+ <table className="lib-tokens">+ <tbody>+ {rows.map((row) => (+ <tr key={row.name} data-unset={row.value === "" || undefined}>+ {swatch && (+ <td className="lib-tokens-swatch">+ <span style={{ background: row.value || "transparent" }} aria-hidden />+ </td>+ )}+ <th scope="row">+ <code>{row.name}</code>+ </th>+ <td className="lib-tokens-meaning">{S.library.charts.tokenMeaning[row.name]}</td>+ <td className="lib-tokens-value">+ <code>{row.value || S.section.unset}</code>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ );+}++export function ChartTokenTable() {+ const { S } = useGallery();+ const t = S.library.charts;+ const tokens = useChartTokens();+ if (!tokens) return <p className="gf-muted">{S.intro.resolving}</p>;+ return (+ <div className="lib-stack lib-stack-wide">+ <div>+ <p className="lib-caption">{t.palette}</p>+ <TokenRows rows={tokens.palette} swatch />+ </div>+ <div>+ <p className="lib-caption">{t.geometry}</p>+ <TokenRows rows={tokens.geometry} swatch={false} />+ </div>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/charts.tsx b/packages/ui-gallery/src/library/boards/charts.tsxnew file mode 100644index 00000000..a0fa406b--- /dev/null+++ b/packages/ui-gallery/src/library/boards/charts.tsx@@ -0,0 +1,223 @@+/**+ * 图表: the chart foundation's page — first the primitives every chart draws through, then the+ * current theme's chart tokens, live, then every chart kind the app draws, on fixed demo data+ * so the themes' chart styles compare: the token donut, the cost trend line, the stacked token+ * bars with their cache-hit curve and legend, the requests-and-success-rate stack, the activity+ * and score sparklines, and the Trace timeline's lanes.+ *+ * Every input a chart receives is built once, at module level or memoized: a chart keeps+ * effects keyed on its data (the timeline re-measures its scroller whenever its groups change),+ * and a fresh array on every render would run them on every render.+ */+import { useMemo, useState } from "react";+import type { ReactNode } from "react";+import type {+ TraceModelSegment,+ TraceOtherSpan,+ TraceToolSpan,+ UsageSeriesPoint,+} from "@prismshadow/penguin-server/api";+import { TokenDonut } from "../../../../web/src/components/ui/token-donut";+import { ActivitySparkline } from "../../../../web/src/features/agents/activity-sparkline";+import { ScoreSparkline } from "../../../../web/src/features/benchmark/score-sparkline";+import { TimelineChart } from "../../../../web/src/features/traces/timeline-chart";+import type { TraceHighlight } from "../../../../web/src/features/traces/timeline-chart";+import { TrendChart } from "../../../../web/src/features/usage/trend-chart";+import {+ RequestsChart,+ TokenBarChart,+ TokenLegend,+} from "../../../../web/src/features/usage/usage-charts";+import type { TokenLegendKey } from "../../../../web/src/features/usage/usage-charts";+import type { EntityCounts } from "../../../../web/src/features/usage/usage-controls";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";+import { ChartPrimitives } from "./chart-primitives";+import { ChartTokenTable } from "./chart-tokens";++/** Fourteen days ending on a fixed date, so the charts are the same on every visit. */+const DAY_COSTS = [+ 0.41, 0.63, 0.22, 0.98, 1.24, 0.77, 0.15, 0.09, 0.88, 1.43, 1.02, 0.56, 0.71, 0.93,+];++function daySeries(): UsageSeriesPoint[] {+ const end = Date.UTC(2026, 8, 28);+ return DAY_COSTS.map((cost, index) => {+ const date = new Date(end - (DAY_COSTS.length - 1 - index) * 86_400_000);+ const requests = Math.round(cost * 40) + 3;+ const output = Math.round(cost * 30_000);+ const cacheRead = output * 6;+ const cacheWrite = Math.round(output * 0.8);+ return {+ bucket: date.toISOString().slice(0, 10),+ cacheRead,+ cacheWrite,+ output,+ total: cacheRead + cacheWrite + output,+ cost,+ requests,+ completed: requests - (index % 5 === 0 ? 1 : 0),+ denominator: requests,+ };+ });+}++const SERIES: UsageSeriesPoint[] = daySeries();++/** The day series split between two agents, the first taking the larger share. */+function agentCounts(+ series: readonly UsageSeriesPoint[],+ labels: readonly string[],+): EntityCounts[] {+ const shares = [0.6, 0.4];+ return shares.map((share, entity) => {+ const requests = series.map((point) => Math.round(point.requests * share));+ return {+ label: labels[entity] ?? `agent-${entity + 1}`,+ requests,+ completed: requests.map((count, index) => count - (entity === 0 && index % 5 === 0 ? 1 : 0)),+ denominator: requests,+ };+ });+}++const SCORES = [0.62, 0.66, 0.71, 0.69, 0.74, 0.78, 0.77, 0.83];+const ACTIVITY = [2, 3, 1, 5, 6, 4, 1, 0, 4, 7, 5, 3, 4, 5];+const FLAT = [0, 0, 0, 0, 0, 0, 0];++/** A Task's timeline: seconds after a fixed start, as the trace records them. */+const T0 = Date.UTC(2026, 8, 28, 9, 0, 0);+const at = (seconds: number) => new Date(T0 + seconds * 1000).toISOString();++const SEGMENTS: TraceModelSegment[] = [+ { kind: "thinking", startTs: at(0), endTs: at(1.8), taskIndex: 0 },+ {+ kind: "tool_call",+ startTs: at(1.8),+ endTs: at(2.4),+ toolCallId: "c1",+ name: "read_file",+ taskIndex: 0,+ },+ { kind: "thinking", startTs: at(4.0), endTs: at(5.2), taskIndex: 0 },+ {+ kind: "tool_call",+ startTs: at(5.2),+ endTs: at(5.6),+ toolCallId: "c2",+ name: "run_command",+ taskIndex: 0,+ },+ {+ kind: "tool_call",+ startTs: at(5.6),+ endTs: at(5.9),+ toolCallId: "c3",+ name: "read_file",+ taskIndex: 0,+ },+ { kind: "text", startTs: at(9.2), endTs: at(12.6), taskIndex: 0 },+ { kind: "thinking", startTs: at(20.0), endTs: at(21.1), taskIndex: 1 },+ { kind: "text", startTs: at(21.1), endTs: at(24.0), taskIndex: 1 },+];++const TOOL_SPANS: TraceToolSpan[] = [+ { toolCallId: "c1", name: "read_file", callTs: at(2.4), outputTs: at(3.9), taskIndex: 0 },+ {+ toolCallId: "c2",+ name: "run_command",+ callTs: at(5.9),+ approvalTs: at(6.9),+ decision: "allow",+ outputTs: at(9.0),+ taskIndex: 0,+ },+ { toolCallId: "c3", name: "read_file", callTs: at(5.9), outputTs: at(6.4), taskIndex: 0 },+];++/** Always the same empty list: the timeline's default parameter would be a new array every render. */+const OTHER_SPANS: TraceOtherSpan[] = [];++function Part({ title, hint, children }: { title: string; hint: string; children: ReactNode }) {+ return (+ <section className="lib-part">+ <div className="lib-part-head">+ <h2>{title}</h2>+ <p>{hint}</p>+ </div>+ {children}+ </section>+ );+}++export function ChartsBoard() {+ const { S } = useGallery();+ const t = S.library.charts;+ const [legend, setLegend] = useState<TokenLegendKey | null>(null);+ const [highlight, setHighlight] = useState<TraceHighlight | null>(null);+ const entities = useMemo(() => agentCounts(SERIES, t.agents), [t.agents]);+ return (+ <div className="gf-board">+ <Part title={t.parts.primitives} hint={t.parts.primitivesHint}>+ <ChartPrimitives />+ </Part>+ <Part title={t.parts.tokens} hint={t.parts.tokensHint}>+ <ChartTokenTable />+ </Part>+ <Part title={t.parts.charts} hint={t.parts.chartsHint}>+ <BoardGroup title={t.donut} aside={t.donutHint}>+ <div className="lib-row">+ <TokenDonut cacheRead={42_000} cacheWrite={6_000} output={9_000} max={200_000} />+ <TokenDonut cacheRead={120_000} cacheWrite={14_000} output={31_000} max={200_000} />+ <TokenDonut cacheRead={150_000} cacheWrite={20_000} output={26_000} max={200_000} />+ <TokenDonut+ cacheRead={42_000}+ cacheWrite={6_000}+ output={9_000}+ max={200_000}+ size={64}+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.trend} aside={t.trendHint}>+ <div className="lib-box p-3">+ <TrendChart series={SERIES} granularity="day" />+ </div>+ </BoardGroup>+ <BoardGroup title={t.tokens} aside={t.tokensHint}>+ <div className="lib-box p-3">+ <TokenBarChart series={SERIES} granularity="day" legend={legend} />+ <TokenLegend active={legend} onHover={setLegend} />+ </div>+ </BoardGroup>+ <BoardGroup title={t.requests} aside={t.requestsHint}>+ <div className="lib-box p-3">+ <RequestsChart series={SERIES} entities={entities} granularity="day" />+ </div>+ </BoardGroup>+ <BoardGroup title={t.activity} aside={t.activityHint}>+ <div className="lib-row">+ <ActivitySparkline data={ACTIVITY} label={t.activity} className="h-8 w-40" />+ <ActivitySparkline data={FLAT} label={t.activity} className="h-8 w-40" />+ </div>+ </BoardGroup>+ <BoardGroup title={t.sparkline} aside={t.sparklineHint}>+ <div className="lib-row">+ <ScoreSparkline values={SCORES} label={t.sparkline} />+ </div>+ </BoardGroup>+ <BoardGroup title={t.timeline} aside={t.timelineHint}>+ <div className="lib-box p-3">+ <TimelineChart+ segments={SEGMENTS}+ toolSpans={TOOL_SPANS}+ otherSpans={OTHER_SPANS}+ highlight={highlight}+ onHighlight={setHighlight}+ />+ </div>+ </BoardGroup>+ </Part>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/dialogs.tsx b/packages/ui-gallery/src/library/boards/dialogs.tsxnew file mode 100644index 00000000..f4d77854--- /dev/null+++ b/packages/ui-gallery/src/library/boards/dialogs.tsx@@ -0,0 +1,89 @@+/** 对话框: Modal, ConfirmModal, Drawer and Sheet, each opened from a button and closed as the app closes it. */+import { useState } from "react";+import { Button } from "../../../../web/src/components/ui/button";+import { ConfirmModal } from "../../../../web/src/components/ui/confirm-modal";+import { Drawer } from "../../../../web/src/components/ui/drawer";+import { Input } from "../../../../web/src/components/ui/input";+import { Modal } from "../../../../web/src/components/ui/modal";+import { Sheet } from "../../../../web/src/components/ui/sheet";+import type { SheetSnap } from "../../../../web/src/components/ui/sheet";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function DialogsBoard() {+ const { S } = useGallery();+ const t = S.library.dialogs;+ const [modal, setModal] = useState(false);+ const [confirm, setConfirm] = useState(false);+ const [drawer, setDrawer] = useState(false);+ const [sheet, setSheet] = useState(false);+ const [snap, setSnap] = useState<SheetSnap>("half");+ const [name, setName] = useState(t.modalTitle);+ return (+ <div className="gf-board">+ <BoardGroup title={t.modal}>+ <div className="lib-row">+ <Button variant="primary" onClick={() => setModal(true)}>+ {t.openModal}+ </Button>+ </div>+ <Modal+ open={modal}+ title={t.modalTitle}+ onClose={() => setModal(false)}+ footer={+ <>+ <Button size="sm" onClick={() => setModal(false)}>+ {t.cancel}+ </Button>+ <Button size="sm" variant="primary" onClick={() => setModal(false)}>+ {t.save}+ </Button>+ </>+ }+ >+ <p className="mb-3 text-sm">{t.modalBody}</p>+ <Input value={name} onChange={(event) => setName(event.target.value)} />+ </Modal>+ </BoardGroup>+ <BoardGroup title={t.confirm}>+ <div className="lib-row">+ <Button variant="danger" onClick={() => setConfirm(true)}>+ {t.openConfirm}+ </Button>+ </div>+ <ConfirmModal+ open={confirm}+ title={t.confirmTitle}+ confirmLabel={t.confirmLabel}+ onClose={() => setConfirm(false)}+ onConfirm={() => setConfirm(false)}+ >+ {t.confirmBody}+ </ConfirmModal>+ </BoardGroup>+ <BoardGroup title={t.drawer}>+ <div className="lib-row">+ <Button onClick={() => setDrawer(true)}>{t.openDrawer}</Button>+ </div>+ <Drawer open={drawer} title={t.drawerTitle} onClose={() => setDrawer(false)}>+ <p className="p-4 text-sm">{t.drawerBody}</p>+ </Drawer>+ </BoardGroup>+ <BoardGroup title={t.sheet}>+ <div className="lib-row">+ <Button onClick={() => setSheet(true)}>{t.openSheet}</Button>+ </div>+ <Sheet+ open={sheet}+ snap={snap}+ onSnapChange={setSnap}+ title={t.sheetTitle}+ onClose={() => setSheet(false)}+ >+ <p className="p-4 text-sm">{t.sheetBody}</p>+ </Sheet>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/empty.tsx b/packages/ui-gallery/src/library/boards/empty.tsxnew file mode 100644index 00000000..8db6709f--- /dev/null+++ b/packages/ui-gallery/src/library/boards/empty.tsx@@ -0,0 +1,31 @@+/** 空状态: the page placeholder with and without an action, and the settings one. */+import { Button } from "../../../../web/src/components/ui/button";+import { EmptyState, SettingsEmpty } from "../../../../web/src/components/ui/empty-state";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function EmptyBoard() {+ const { S } = useGallery();+ const t = S.library.empty;+ return (+ <div className="gf-board">+ <BoardGroup title={t.page}>+ <div className="lib-box">+ <EmptyState+ title={t.title}+ description={t.description}+ action={<Button variant="primary">{t.action}</Button>}+ />+ </div>+ <div className="lib-box">+ <EmptyState title={t.title} />+ </div>+ </BoardGroup>+ <BoardGroup title={t.settings}>+ <div className="lib-box">+ <SettingsEmpty>{t.settingsText}</SettingsEmpty>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/files.tsx b/packages/ui-gallery/src/library/boards/files.tsxnew file mode 100644index 00000000..a0d94038--- /dev/null+++ b/packages/ui-gallery/src/library/boards/files.tsx@@ -0,0 +1,88 @@+/** 文件: the app's FileTree over a demo workspace, and the read-only FileBrowser previewing its README. */+import { useState } from "react";+import { FileBrowser } from "../../../../web/src/components/ui/file-browser";+import type { FileBrowserPreview } from "../../../../web/src/components/ui/file-browser";+import { FileTree } from "../../../../web/src/components/ui/file-tree";+import type { TreeToggle } from "../../../../web/src/components/ui/file-tree";+import type { FileTreeRow } from "../../../../web/src/lib/file-tree";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";+import { DEMO_OPEN_DIRS, DEMO_TREE, demoSize, flattenTree } from "../demo-tree";++function formatSize(bytes: number): string {+ return bytes >= 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${bytes} B`;+}++/** The open directories and the last toggle, as the app keeps them for a tree. */+function useDemoTree() {+ const [open, setOpen] = useState<ReadonlySet<string>>(() => new Set(DEMO_OPEN_DIRS));+ const [toggled, setToggled] = useState<TreeToggle | null>(null);+ const [selected, setSelected] = useState<string | null>(null);+ const toggle = (dir: string) => {+ const next = new Set(open);+ const opening = !next.has(dir);+ if (opening) next.add(dir);+ else next.delete(dir);+ setOpen(next);+ setToggled({ dir, open: opening, serial: (toggled?.serial ?? 0) + 1 });+ };+ return { rows: flattenTree(DEMO_TREE, open), toggled, selected, setSelected, toggle };+}++const trailing = (row: FileTreeRow) => {+ const size = demoSize(row.path);+ return size === null ? null : <span className="lib-caption">{formatSize(size)}</span>;+};++export function FilesBoard() {+ const { S } = useGallery();+ const t = S.library.files;+ const tree = useDemoTree();+ const browser = useDemoTree();+ const preview: FileBrowserPreview | null =+ browser.selected === null+ ? null+ : {+ path: browser.selected,+ name: browser.selected.split("/").pop() ?? browser.selected,+ kind: browser.selected.endsWith(".md") ? "md" : "text",+ content: browser.selected === "README.md" ? t.readme : `// ${browser.selected}\n`,+ };+ return (+ <div className="gf-board">+ <BoardGroup title={t.tree}>+ <div className="lib-box" data-narrow>+ <FileTree+ rows={tree.rows}+ label={t.treeLabel}+ selectedPath={tree.selected}+ toggled={tree.toggled}+ rowTrailing={trailing}+ emptyLabel={t.emptyDir}+ className="py-1"+ onToggleDir={tree.toggle}+ onOpenFile={tree.setSelected}+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.browser}>+ <div className="lib-box">+ <FileBrowser+ rows={browser.rows}+ treeLabel={t.treeLabel}+ selectedPath={browser.selected}+ toggled={browser.toggled}+ rowTrailing={trailing}+ headerFallback={t.header}+ preview={preview}+ emptyPreview={t.emptyPreview}+ treeMaxHeight={40}+ previewHeight={40}+ onToggleDir={browser.toggle}+ onOpenFile={browser.setSelected}+ />+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/inputs.tsx b/packages/ui-gallery/src/library/boards/inputs.tsxnew file mode 100644index 00000000..b1627dd8--- /dev/null+++ b/packages/ui-gallery/src/library/boards/inputs.tsx@@ -0,0 +1,80 @@+/** 输入与表单: Input, Textarea and PasswordInput on the shared field scaffolding, with hint, info and error. */+import { useState } from "react";+import { Input, Textarea } from "../../../../web/src/components/ui/input";+import { PasswordInput } from "../../../../web/src/components/ui/password-input";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function InputsBoard() {+ const { S } = useGallery();+ const t = S.library.inputs;+ const [name, setName] = useState("");+ const [email, setEmail] = useState(t.emailValue);+ const [prompt, setPrompt] = useState("");+ const [params, setParams] = useState(t.monoValue);+ const [password, setPassword] = useState("");+ return (+ <div className="gf-board">+ <BoardGroup title={t.basics}>+ <div className="lib-stack">+ <Input+ label={t.name}+ hint={t.nameHint}+ placeholder={t.namePlaceholder}+ value={name}+ onChange={(event) => setName(event.target.value)}+ />+ <Input+ label={t.email}+ type="email"+ error={t.emailError}+ value={email}+ onChange={(event) => setEmail(event.target.value)}+ />+ <Input label={t.required} required placeholder={t.required} />+ <Input+ label={t.info}+ info={t.infoText}+ infoLabel={t.info}+ id="lib-input-info"+ placeholder={t.info}+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.sizes}>+ <div className="lib-stack">+ <Input label={t.base} size="base" placeholder={t.base} />+ <Input label={t.small} size="sm" placeholder={t.small} />+ </div>+ </BoardGroup>+ <BoardGroup title={t.textarea}>+ <div className="lib-stack">+ <Textarea+ label={t.textarea}+ placeholder={t.textareaPlaceholder}+ rows={3}+ value={prompt}+ onChange={(event) => setPrompt(event.target.value)}+ />+ <Textarea+ label={t.mono}+ mono+ rows={3}+ value={params}+ onChange={(event) => setParams(event.target.value)}+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.password}>+ <div className="lib-stack">+ <PasswordInput+ label={t.password}+ hint={t.passwordHint}+ value={password}+ onChange={(event) => setPassword(event.target.value)}+ />+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/loading.tsx b/packages/ui-gallery/src/library/boards/loading.tsxnew file mode 100644index 00000000..3cf594ef--- /dev/null+++ b/packages/ui-gallery/src/library/boards/loading.tsx@@ -0,0 +1,40 @@+/** 加载: the spinner (the running-state ring) at three sizes, and the skeleton line, list and card. */+import { Skeleton, SkeletonCard, SkeletonList } from "../../../../web/src/components/ui/skeleton";+import { StatusIcon } from "../../../../web/src/components/ui/status-icon";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function LoadingBoard() {+ const { S } = useGallery();+ const t = S.library.loading;+ return (+ <div className="gf-board">+ <BoardGroup title={t.spinner} aside={t.sizes}>+ <div className="lib-row">+ {[13, 16, 24].map((size) => (+ <span key={size} className="lib-cell">+ <StatusIcon state="running" size={size} />+ <span className="lib-caption">{size}px</span>+ </span>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.skeleton}>+ <div className="lib-stack">+ <Skeleton className="h-4 w-2/3" />+ <Skeleton className="h-4 w-1/2" />+ </div>+ </BoardGroup>+ <BoardGroup title={t.list}>+ <div className="lib-box">+ <SkeletonList rows={3} />+ </div>+ </BoardGroup>+ <BoardGroup title={t.card}>+ <div className="lib-stack">+ <SkeletonCard />+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/notices.tsx b/packages/ui-gallery/src/library/boards/notices.tsxnew file mode 100644index 00000000..92a527bc--- /dev/null+++ b/packages/ui-gallery/src/library/boards/notices.tsx@@ -0,0 +1,61 @@+/**+ * 提示条: the app's NoticeStrip in every tone — plain, with the leading mark a call site draws+ * (`data-slot="icon"`, which a theme that draws its own tone mark hides), and with actions.+ */+import { Button } from "../../../../web/src/components/ui/button";+import { NoticeStrip } from "../../../../web/src/components/ui/notice-strip";+import { toneDot } from "../../../../web/src/lib/tone";+import type { Tone } from "../../../../web/src/lib/tone";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++const TONES: readonly Tone[] = ["link", "success", "busy", "attention", "danger", "muted"];++const STRIP_CLASS = "flex flex-wrap items-center gap-2 rounded-md border px-3 py-2 text-sm";++export function NoticesBoard() {+ const { S } = useGallery();+ const t = S.library.notices;+ return (+ <div className="gf-board">+ <BoardGroup title={t.plain}>+ <div className="lib-stack">+ {TONES.map((tone) => (+ <NoticeStrip key={tone} tone={tone} as="p" className={STRIP_CLASS}>+ {t.texts[tone]}+ </NoticeStrip>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.dotted}>+ <div className="lib-stack">+ {TONES.map((tone) => (+ <NoticeStrip key={tone} tone={tone} className={STRIP_CLASS}>+ <span+ data-slot="icon"+ aria-hidden+ className={`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${toneDot[tone]}`}+ />+ <span>{t.texts[tone]}</span>+ </NoticeStrip>+ ))}+ </div>+ </BoardGroup>+ <BoardGroup title={t.withActions}>+ <div className="lib-stack">+ {(["link", "attention", "danger"] as const).map((tone) => (+ <NoticeStrip key={tone} tone={tone} className={STRIP_CLASS}>+ <span className="min-w-0 flex-1">{t.texts[tone]}</span>+ <span data-slot="actions" className="flex shrink-0 gap-2">+ <Button size="sm" variant="ghost">+ {t.dismiss}+ </Button>+ <Button size="sm">{t.action}</Button>+ </span>+ </NoticeStrip>+ ))}+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/pickers.tsx b/packages/ui-gallery/src/library/boards/pickers.tsxnew file mode 100644index 00000000..0ad81cad--- /dev/null+++ b/packages/ui-gallery/src/library/boards/pickers.tsx@@ -0,0 +1,113 @@+/** 选择器: the app's Select, Segmented, Switch, OptionMenu and Dropdown, each holding its own choice. */+import { useState } from "react";+import { Button } from "../../../../web/src/components/ui/button";+import { Dropdown, menuItemClass } from "../../../../web/src/components/ui/dropdown";+import { ChevronDown } from "../../../../web/src/components/ui/icons";+import { OptionMenu } from "../../../../web/src/components/ui/option-menu";+import { Segmented } from "../../../../web/src/components/ui/segmented";+import { Select } from "../../../../web/src/components/ui/select";+import { Switch } from "../../../../web/src/components/ui/switch";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function PickersBoard() {+ const { S } = useGallery();+ const t = S.library.pickers;+ const [model, setModel] = useState(t.options[0] ?? "");+ const [segment, setSegment] = useState(t.segments[0] ?? "");+ const [notify, setNotify] = useState(true);+ const [shortNames, setShortNames] = useState(false);+ const [permission, setPermission] = useState<string | null>(t.choices[1]?.value ?? null);+ const [menuOpen, setMenuOpen] = useState(false);+ return (+ <div className="gf-board">+ <BoardGroup title={t.select}>+ <div className="lib-stack">+ <Select+ label={t.selectLabel}+ value={model}+ onChange={(event) => setModel(event.target.value)}+ >+ {t.options.map((option) => (+ <option key={option} value={option}>+ {option}+ </option>+ ))}+ </Select>+ </div>+ </BoardGroup>+ <BoardGroup title={t.segmented}>+ <div className="lib-stack">+ <Segmented+ options={t.segments.map((label) => ({ value: label, label }))}+ value={segment}+ onChange={setSegment}+ cols={3}+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.switches}>+ <div className="lib-stack">+ <label className="ui-field flex items-center justify-between gap-4">+ <span>+ <span className="block">{t.switchLabel}</span>+ <span className="lib-caption">{t.switchHint}</span>+ </span>+ <Switch checked={notify} onChange={setNotify} />+ </label>+ <label className="ui-field flex items-center justify-between gap-4">+ <span>{t.switchOff}</span>+ <Switch checked={shortNames} onChange={setShortNames} />+ </label>+ </div>+ </BoardGroup>+ <BoardGroup title={t.optionMenu}>+ <div className="lib-stack">+ <OptionMenu+ label={t.optionLabel}+ mono+ options={t.choices.map((choice) => ({+ value: choice.value,+ triggerLabel: choice.trigger,+ label: choice.label,+ description: choice.description,+ }))}+ value={permission}+ onChange={setPermission}+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.dropdown}>+ <div className="lib-row">+ <Dropdown+ open={menuOpen}+ setOpen={setMenuOpen}+ button={+ <Button+ size="sm"+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ onClick={() => setMenuOpen(!menuOpen)}+ >+ <span>{t.menu}</span>+ <ChevronDown />+ </Button>+ }+ >+ {t.menuItems.map((item) => (+ <button+ key={item}+ type="button"+ role="menuitem"+ className={menuItemClass}+ onClick={() => setMenuOpen(false)}+ >+ {item}+ </button>+ ))}+ </Dropdown>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/tabs.tsx b/packages/ui-gallery/src/library/boards/tabs.tsxnew file mode 100644index 00000000..e6dbea99--- /dev/null+++ b/packages/ui-gallery/src/library/boards/tabs.tsx@@ -0,0 +1,32 @@+/** 标签页: the app's Tabs, plain and with an update badge on one tab. */+import { useState } from "react";+import { Tabs } from "../../../../web/src/components/ui/tabs";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function TabsBoard() {+ const { S } = useGallery();+ const t = S.library.tabs;+ const items = t.items.map((label) => ({ key: label, label }));+ const [active, setActive] = useState(items[0]?.key ?? "");+ const [badgedActive, setBadgedActive] = useState(items[0]?.key ?? "");+ const badged = items.map((item, index) =>+ index === items.length - 1 ? { ...item, badge: t.badgeText } : item,+ );+ return (+ <div className="gf-board">+ <BoardGroup title={t.basic}>+ <div className="lib-box">+ <Tabs items={items} active={active} onChange={setActive} />+ <p className="p-4 text-sm">{t.body(active)}</p>+ </div>+ </BoardGroup>+ <BoardGroup title={t.badged}>+ <div className="lib-box">+ <Tabs items={badged} active={badgedActive} onChange={setBadgedActive} />+ <p className="p-4 text-sm">{t.body(badgedActive)}</p>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/toasts.tsx b/packages/ui-gallery/src/library/boards/toasts.tsxnew file mode 100644index 00000000..131c2fd5--- /dev/null+++ b/packages/ui-gallery/src/library/boards/toasts.tsx@@ -0,0 +1,31 @@+/** 提示弹窗: the toast after an action completes, in its four kinds, fired from buttons (the Toaster is mounted by the frame). */+import { Button } from "../../../../web/src/components/ui/button";+import {+ toastAttention,+ toastError,+ toastInfo,+ toastSuccess,+} from "../../../../web/src/components/ui/toast";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++export function ToastsBoard() {+ const { S } = useGallery();+ const t = S.library.toasts;+ return (+ <div className="gf-board">+ <BoardGroup title={t.fire} aside={t.hint}>+ <div className="lib-row">+ <Button variant="primary" onClick={() => toastSuccess(t.successText)}>+ {t.success}+ </Button>+ <Button onClick={() => toastInfo(t.infoText)}>{t.info}</Button>+ <Button onClick={() => toastAttention(t.attentionText)}>{t.attention}</Button>+ <Button variant="danger" onClick={() => toastError(t.errorText)}>+ {t.error}+ </Button>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/boards/tooltips.tsx b/packages/ui-gallery/src/library/boards/tooltips.tsxnew file mode 100644index 00000000..2980e77f--- /dev/null+++ b/packages/ui-gallery/src/library/boards/tooltips.tsx@@ -0,0 +1,73 @@+/** 悬停提示: the app's one tooltip, by attribute (read by the frame's TooltipLayer) and by component, and on a truncated line. */+import { Button } from "../../../../web/src/components/ui/button";+import { Tooltip } from "../../../../web/src/components/ui/tooltip";+import { BoardGroup } from "../../foundations/shared";+import { useGallery } from "../../state";++const EDIT = "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z";+const COPY =+ "M9 9h9v9a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V9zM7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1";+const GEAR =+ "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z";++function Glyph({ d }: { d: string }) {+ return (+ <svg+ width={15}+ height={15}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ >+ <path d={d} />+ </svg>+ );+}++export function TooltipsBoard() {+ const { S } = useGallery();+ const t = S.library.tooltips;+ return (+ <div className="gf-board">+ <BoardGroup title={t.attribute} aside={t.attributeHint}>+ <div className="lib-row">+ <Button size="icon" aria-label={t.edit} data-tooltip={t.edit}>+ <Glyph d={EDIT} />+ </Button>+ <Button size="icon" aria-label={t.copy} data-tooltip={t.copy}>+ <Glyph d={COPY} />+ </Button>+ <Button size="icon" aria-label={t.settings} data-tooltip={t.settings}>+ <Glyph d={GEAR} />+ </Button>+ </div>+ </BoardGroup>+ <BoardGroup title={t.component} aside={t.componentHint}>+ <div className="lib-row">+ <Tooltip label={t.beside} placement="right">+ <Button size="sm">{t.beside}</Button>+ </Tooltip>+ <Tooltip label={t.below} placement="bottom">+ <Button size="sm">{t.below}</Button>+ </Tooltip>+ </div>+ </BoardGroup>+ <BoardGroup title={t.truncated} aside={t.truncatedHint}>+ <div className="lib-box" data-narrow>+ <span+ className="lib-truncated px-3 py-2"+ data-tooltip={t.command}+ data-tooltip-content="code"+ tabIndex={0}+ >+ {t.command}+ </span>+ </div>+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/chart-tokens.ts b/packages/ui-gallery/src/library/chart-tokens.tsnew file mode 100644index 00000000..c3a19000--- /dev/null+++ b/packages/ui-gallery/src/library/chart-tokens.ts@@ -0,0 +1,57 @@+/**+ * The chart tokens the 图表 page tables for the current theme: the palette (the eight series+ * slots, the reference line, the three token kinds, the grid and axis inks) and the geometry+ * (bar fill, radius, outline and opacity, line width, point radius, curve, area opacity). Pure+ * over a reader of custom properties, so the list and the reading are unit-tested; the board+ * reads them off the frame root's computed style, which is the theme under test.+ */++export const CHART_PALETTE_TOKENS = [+ "--ui-chart-1",+ "--ui-chart-2",+ "--ui-chart-3",+ "--ui-chart-4",+ "--ui-chart-5",+ "--ui-chart-6",+ "--ui-chart-7",+ "--ui-chart-8",+ "--ui-chart-ref",+ "--ui-chart-cache-read",+ "--ui-chart-cache-write",+ "--ui-chart-output",+ "--ui-chart-grid",+ "--ui-chart-axis",+] as const;+export type ChartPaletteToken = (typeof CHART_PALETTE_TOKENS)[number];++export const CHART_GEOMETRY_TOKENS = [+ "--ui-chart-bar-fill",+ "--ui-chart-bar-radius",+ "--ui-chart-bar-stroke",+ "--ui-chart-bar-stroke-color",+ "--ui-chart-bar-opacity",+ "--ui-chart-line-width",+ "--ui-chart-point-radius",+ "--ui-chart-curve",+ "--ui-chart-area-opacity",+] as const;+export type ChartGeometryToken = (typeof CHART_GEOMETRY_TOKENS)[number];++export type ChartToken = ChartPaletteToken | ChartGeometryToken;++export interface ChartTokenRow<T extends ChartToken = ChartToken> {+ name: T;+ /** The computed value, trimmed; empty when the theme leaves the token undefined. */+ value: string;+}++/** Every token's computed value, in the tables' order, from a reader such as `getPropertyValue`. */+export function readChartTokens(read: (name: string) => string): {+ palette: ChartTokenRow<ChartPaletteToken>[];+ geometry: ChartTokenRow<ChartGeometryToken>[];+} {+ return {+ palette: CHART_PALETTE_TOKENS.map((name) => ({ name, value: read(name).trim() })),+ geometry: CHART_GEOMETRY_TOKENS.map((name) => ({ name, value: read(name).trim() })),+ };+}diff --git a/packages/ui-gallery/src/library/demo-tree.ts b/packages/ui-gallery/src/library/demo-tree.tsnew file mode 100644index 00000000..0b5d3d4a--- /dev/null+++ b/packages/ui-gallery/src/library/demo-tree.ts@@ -0,0 +1,73 @@+/**+ * The demo workspace the file boards draw, and the flat row list the app's tree components take+ * from it: every visible entry in order, with its depth, its position in its directory and, for+ * a directory, whether it is open — pure, so the flattening is unit-tested.+ */+import type { FileTreeRow } from "../../../web/src/lib/file-tree";++export interface DemoEntry {+ name: string;+ /** A directory's entries; absent for a file. */+ children?: readonly DemoEntry[];+ /** A file's size in bytes, for the row's trailing text. */+ size?: number;+}++export const DEMO_TREE: readonly DemoEntry[] = [+ {+ name: "corpus",+ children: [+ { name: "claude-code-docs", children: [{ name: "hooks.md", size: 8210 }] },+ { name: "index.json", size: 41230 },+ ],+ },+ {+ name: "src",+ children: [+ { name: "rag.ts", size: 3944 },+ { name: "embed.ts", size: 1210 },+ { name: "empty", children: [] },+ ],+ },+ { name: "test", children: [{ name: "rag.test.ts", size: 2711 }] },+ { name: "README.md", size: 612 },+ { name: "package.json", size: 388 },+];++/** The directories open when a board first renders. */+export const DEMO_OPEN_DIRS: readonly string[] = ["src"];++/** The flat rows for the tree, given which directories are open. */+export function flattenTree(+ entries: readonly DemoEntry[],+ openDirs: ReadonlySet<string>,+ parent = "",+ depth = 0,+): FileTreeRow[] {+ return entries.flatMap((entry, index) => {+ const path = parent === "" ? entry.name : `${parent}/${entry.name}`;+ const isDir = entry.children !== undefined;+ const expanded = isDir && openDirs.has(path);+ const row: FileTreeRow = {+ path,+ name: entry.name,+ kind: isDir ? "dir" : "file",+ depth,+ posInSet: index + 1,+ setSize: entries.length,+ expanded,+ loaded: isDir,+ empty: isDir && entry.children!.length === 0,+ };+ return expanded ? [row, ...flattenTree(entry.children!, openDirs, path, depth + 1)] : [row];+ });+}++/** The size a demo file reports, or null for a directory. */+export function demoSize(path: string, entries: readonly DemoEntry[] = DEMO_TREE): number | null {+ const [head, ...rest] = path.split("/");+ const entry = entries.find((candidate) => candidate.name === head);+ if (!entry) return null;+ if (rest.length === 0) return entry.size ?? null;+ return entry.children ? demoSize(rest.join("/"), entry.children) : null;+}diff --git a/packages/ui-gallery/src/library/frame-height.ts b/packages/ui-gallery/src/library/frame-height.tsnew file mode 100644index 00000000..7786efb1--- /dev/null+++ b/packages/ui-gallery/src/library/frame-height.ts@@ -0,0 +1,124 @@+/**+ * How tall a library frame must be: tall enough for what is actually painted, not only for+ * the board. The app renders its overlays — menus, listboxes, tooltips, toasts, dialogs — in+ * portals on the body with fixed positioning, and a dropdown inside the board is absolutely+ * positioned below its trigger; none of them add to the board's own box, so a frame sized to+ * the board alone cut them off.+ *+ * The rule, pure so it is unit-tested (`frameHeight`):+ * - the board's box, or its overflowing content (a menu opened inside it) plus a margin;+ * - every floating overlay's bottom plus a margin, so a menu or a tooltip below its trigger+ * is whole and a stack of toasts fits;+ * - an overlay that covers the viewport (a dialog's backdrop, a drawer, a sheet) is sized from+ * the panel inside it — the tallest part of it that does not itself span the viewport — with+ * a margin above and below, and never under `dialogMin`, so a dialog is never squeezed. A+ * part spanning the viewport is left out because it follows the frame's height and would+ * otherwise grow it without end.+ * The height shrinks back as soon as an overlay closes; it is a function of what is there.+ *+ * `measureFrameHeight` reads those rects off a document; only the direct children of the body+ * other than the app's root count as overlays.+ */++export interface MeasuredMain {+ /** The board's own box bottom. */+ bottom: number;+ /** The lowest visible edge of anything inside the board, positioned or not. */+ contentBottom: number;+}++export interface MeasuredOverlay {+ /** The overlay's own bottom edge. */+ bottom: number;+ /** Whether it spans the viewport top to bottom: a dialog's backdrop, a drawer, a sheet. */+ covers: boolean;+ /** For a covering overlay: the tallest part inside it that does not span the viewport. */+ panelHeight: number;+}++export interface FrameHeightOptions {+ /** Room kept under a floating overlay, and above and below a dialog's panel, px. */+ margin: number;+ /** The least a frame shows while a covering overlay is open, px. */+ dialogMin: number;+}++export const FRAME_HEIGHT_OPTIONS: FrameHeightOptions = { margin: 16, dialogMin: 560 };++export function frameHeight(+ main: MeasuredMain,+ overlays: readonly MeasuredOverlay[],+ { margin, dialogMin }: FrameHeightOptions = FRAME_HEIGHT_OPTIONS,+): number {+ let height = main.bottom;+ if (main.contentBottom > main.bottom) height = Math.max(height, main.contentBottom + margin);+ for (const overlay of overlays) {+ height = overlay.covers+ ? Math.max(height, dialogMin, overlay.panelHeight + 2 * margin)+ : Math.max(height, overlay.bottom + margin);+ }+ return Math.ceil(Math.max(0, height));+}++/** A box spanning the viewport top to bottom, give or take a pixel of border. */+export function coversViewport(+ rect: { top: number; bottom: number },+ viewportHeight: number,+): boolean {+ return rect.top <= 1 && rect.bottom >= viewportHeight - 1;+}++/** A painted box: anything with no size is not on screen and says nothing about the height. */+const painted = (rect: DOMRect) => rect.width > 0 && rect.height > 0;++/** The lowest visible edge of an element and everything inside it. */+function lowestEdge(el: Element): number {+ let bottom = -Infinity;+ const rect = el.getBoundingClientRect();+ if (painted(rect)) bottom = rect.bottom;+ for (const child of el.querySelectorAll("*")) {+ const r = child.getBoundingClientRect();+ if (painted(r)) bottom = Math.max(bottom, r.bottom);+ }+ return bottom;+}++/** The tallest part inside a covering overlay that does not itself span the viewport. */+function panelHeightIn(el: Element, viewportHeight: number): number {+ let tallest = 0;+ for (const child of el.querySelectorAll("*")) {+ const r = child.getBoundingClientRect();+ if (painted(r) && r.height < viewportHeight - 1) tallest = Math.max(tallest, r.height);+ }+ return tallest;+}++/** Reads the board and the overlays off a document and applies the rule. */+export function measureFrameHeight(+ doc: Document,+ main: HTMLElement,+ root: HTMLElement,+ options: FrameHeightOptions = FRAME_HEIGHT_OPTIONS,+): number {+ const viewportHeight = doc.defaultView?.innerHeight ?? 0;+ const measuredMain: MeasuredMain = {+ bottom: main.getBoundingClientRect().bottom,+ contentBottom: lowestEdge(main),+ };+ const overlays: MeasuredOverlay[] = [];+ for (const el of Array.from(doc.body.children)) {+ if (el === root || el.tagName === "SCRIPT" || el.tagName === "STYLE") continue;+ const rect = el.getBoundingClientRect();+ if (coversViewport(rect, viewportHeight)) {+ overlays.push({+ bottom: rect.bottom,+ covers: true,+ panelHeight: panelHeightIn(el, viewportHeight),+ });+ } else {+ const bottom = lowestEdge(el);+ if (bottom > -Infinity) overlays.push({ bottom, covers: false, panelHeight: 0 });+ }+ }+ return frameHeight(measuredMain, overlays, options);+}diff --git a/packages/ui-gallery/src/library/frame-resize.ts b/packages/ui-gallery/src/library/frame-resize.tsnew file mode 100644index 00000000..8c141a36--- /dev/null+++ b/packages/ui-gallery/src/library/frame-resize.ts@@ -0,0 +1,50 @@+/**+ * A frame's own height changes must not read as window resizes to the app inside it.+ *+ * The app closes its floating panels on a window resize (a menu, a listbox, a tooltip): the+ * panel was placed once against its trigger, and a resize may have moved the trigger. When the+ * page around a library frame grows the frame so an open menu fits, the frame's window gets a+ * `resize` too — and the menu would close the instant it was given room. Nothing moved: the+ * frame only grew at the bottom, and every trigger stays where it was. So a resize the frame+ * asked for itself is stopped here before the app's listeners hear it.+ *+ * The listener is registered before the app mounts, so it runs first; at the window (the+ * event's target) listeners run in registration order, and `stopImmediatePropagation` keeps+ * the rest from running. A resize the frame did not ask for — the reader resizing the browser+ * with a standalone board open — passes through as before. The page's own measurer still+ * needs to hear the frame's growth (a dialog's body opens up to the taller viewport and may+ * need more), so it subscribes through `onSelfResize` rather than the window event.+ */++/** How long a requested resize stays expected; a request the page never applied then lapses. */+const EXPECT_MS = 1000;++let expectedUntil = 0;+const listeners = new Set<() => void>();++/** Installs the guard on `win`. Call once, before the app mounts. */+export function installSelfResizeGuard(win: Window): void {+ win.addEventListener(+ "resize",+ (event) => {+ if (Date.now() > expectedUntil) return;+ expectedUntil = 0;+ event.stopImmediatePropagation();+ for (const listener of listeners) listener();+ },+ true,+ );+}++/** Hears the resizes the guard swallowed; returns the unsubscribe. */+export function onSelfResize(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/** The frame is about to be resized at its own request: the next resize is its own. */+export function expectSelfResize(): void {+ expectedUntil = Date.now() + EXPECT_MS;+}diff --git a/packages/ui-gallery/src/library/frame.ts b/packages/ui-gallery/src/library/frame.tsnew file mode 100644index 00000000..3db89a8a--- /dev/null+++ b/packages/ui-gallery/src/library/frame.ts@@ -0,0 +1,41 @@+/**+ * The framed component library's contract with the gallery — pure, so it is unit-tested.+ *+ * A library page is its own document (`lib.html`), seeded and booted exactly as a framed app is+ * (src/app/frame.ts): the same preference params under the same storage keys, the same+ * pre-paint boot script, so the components render under the page's theme, mode, size and fonts+ * with no flash. `topic` names the board. The frame reports its content height to the page+ * through a window message, so the page gives the frame exactly the room the board takes.+ */+import { SEEDED_KEYS } from "../app/frame";+import type { FramePrefs } from "../app/frame";+import { FIRST_TOPIC, isTopicId } from "./topics";+import type { TopicId } from "./topics";++/** The frame's document, relative to the gallery's base. */+export const LIBRARY_FRAME_PATH = "/lib.html";++/** The `type` of the message a library frame posts with its content height. */+export const LIBRARY_HEIGHT_MESSAGE = "penguin-gallery:library-height";++export function libraryFrameSrc(base: string, prefs: FramePrefs, topic: TopicId): string {+ const params = new URLSearchParams();+ params.set("topic", topic);+ for (const key of Object.keys(SEEDED_KEYS)) params.set(key, prefs[key as keyof FramePrefs]);+ return `${base}${LIBRARY_FRAME_PATH}?${params.toString()}`;+}++export interface LibraryParams {+ topic: TopicId;+ lang: "en" | "zh";+}++/** What a library frame reads back from its own URL; an unknown topic opens the first. */+export function parseLibraryParams(search: string): LibraryParams {+ const params = new URLSearchParams(search);+ const topic = params.get("topic") ?? "";+ return {+ topic: isTopicId(topic) ? topic : FIRST_TOPIC,+ lang: params.get("lang") === "zh" ? "zh" : "en",+ };+}diff --git a/packages/ui-gallery/src/library/library.css b/packages/ui-gallery/src/library/library.cssnew file mode 100644index 00000000..9de63b77--- /dev/null+++ b/packages/ui-gallery/src/library/library.css@@ -0,0 +1,166 @@+/*+ * The framed component library's stylesheet: the Web App's own entry, exactly as the app loads+ * it (Tailwind pointed at the app's sources, since they sit outside this Vite root), then the+ * Foundations boards' sheet, then the little the board pages add — a page padding on the theme's+ * canvas and a few row layouts. The boards read the theme's tokens, so lengths here are rem and+ * every colour is a token, as in foundations.css.+ */+@import "../../../web/src/styles.css";+@source "../../../web/src";+@import "../foundations/foundations.css";++/* Framed, the document is exactly as tall as its board — the page around it takes the height+ from the board and sizes the frame — so it never scrolls itself: a scrollbar would only flash+ between the board's first paint and the frame's resize. Standalone, the page scrolls as usual. */+html[data-framed],+html[data-framed] body {+ overflow: hidden;+}+.lib-page {+ padding: 1.5rem;+ background: var(--ui-canvas);+ color: var(--ui-fg);+}++/* A row of controls, wrapping; the wide variant stacks full-width fields. */+.lib-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;+}+.lib-stack {+ display: grid;+ gap: 0.75rem;+ max-width: 28rem;+}+.lib-stack-wide {+ max-width: none;+ gap: 1.25rem;+}+/* A part of a board that groups several specimens under a heading of its own: the chart+ foundation's primitives, tokens and charts. */+.lib-part {+ display: grid;+ gap: 1.5rem;+ padding-top: 1.5rem;+ border-top: 1px solid var(--ui-line);+}+.lib-part:first-child {+ padding-top: 0;+ border-top: 0;+}+.lib-part-head h2 {+ margin: 0;+ font-size: var(--ui-text-body-size);+ line-height: var(--ui-text-body-lh);+ font-weight: var(--ui-weight-medium);+ color: var(--ui-fg);+}+.lib-part-head p {+ margin: 0.25rem 0 0;+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+ color: var(--ui-fg-muted);+}+/* The token table: a swatch, the name, what it is for, the computed value. */+.lib-tokens {+ width: 100%;+ border-collapse: collapse;+ font-size: var(--ui-text-small-size);+ line-height: var(--ui-text-small-lh);+}+.lib-tokens td,+.lib-tokens th {+ padding: 0.375rem 0.75rem 0.375rem 0;+ border-top: 1px solid var(--ui-line);+ text-align: left;+ vertical-align: middle;+ font-weight: var(--ui-weight-body);+}+.lib-tokens tr:first-child td,+.lib-tokens tr:first-child th {+ border-top: 0;+}+.lib-tokens code {+ font-family: var(--ui-font-mono);+ font-size: var(--ui-text-caption-size);+}+.lib-tokens-swatch {+ width: 1.5rem;+}+.lib-tokens-swatch span {+ display: block;+ width: 1rem;+ height: 1rem;+ border-radius: var(--ui-radius-control);+ box-shadow: inset 0 0 0 1px var(--ui-line-emphasis);+}+.lib-tokens-meaning {+ color: var(--ui-fg-muted);+}+.lib-tokens-value {+ text-align: right;+ white-space: nowrap;+}+.lib-tokens tr[data-unset] .lib-tokens-value {+ color: var(--ui-fg-subtle);+}+/* A primitive shown on its own: a small SVG stage on the surface. */+.lib-stage {+ display: block;+ width: 100%;+ max-width: 24rem;+ height: auto;+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-surface);+}+.lib-stage-small {+ width: 8rem;+}+/* One lane of the timeline stage: a label and a track the bar sits in. */+.lib-lane {+ display: grid;+ grid-template-columns: 6rem minmax(0, 1fr);+ align-items: center;+ gap: 0.75rem;+}+.lib-lane-track {+ position: relative;+ height: 1rem;+ border-radius: var(--ui-radius-control);+ background: var(--ui-surface-muted);+}+.lib-cell {+ display: inline-flex;+ flex-direction: column;+ align-items: center;+ gap: 0.375rem;+}+/* A caption under a specimen: the caption rung in the subtle ink. */+.lib-caption {+ font-size: var(--ui-text-caption-size);+ line-height: var(--ui-text-caption-lh);+ color: var(--ui-fg-subtle);+}+/* A framed area for a component that owns its layout: the file tree, a truncated row. */+.lib-box {+ border: 1px solid var(--ui-line);+ border-radius: var(--ui-radius-lg);+ background: var(--ui-surface);+ overflow: hidden;+}+.lib-box[data-narrow] {+ max-width: 18rem;+}+/* A line a row truncates, for the tooltip board. */+.lib-truncated {+ display: block;+ max-width: 20rem;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-family: var(--ui-font-mono);+ font-size: var(--ui-text-small-size);+}diff --git a/packages/ui-gallery/src/library/main.tsx b/packages/ui-gallery/src/library/main.tsxnew file mode 100644index 00000000..7507abad--- /dev/null+++ b/packages/ui-gallery/src/library/main.tsx@@ -0,0 +1,62 @@+/**+ * The framed component library's entry (`lib.html`): one topic's board, made of the Web App's+ * real components, mounted under the app's own providers — locale, theme, the toast overlay and+ * the tooltip layer — with the gallery's context for the boards that read tokens and the+ * gallery's dictionary. The document's storage was already replaced and seeded by the inline+ * script in the page head, and the app's own boot script has applied the theme, so the board+ * renders exactly as the app would.+ *+ * The mock network is installed as in the app frame: a component that fetches (the file+ * browser's preview, a chart) gets the demo store's answer.+ */+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { Toaster } from "../../../web/src/components/ui/toast";+import { TooltipLayer } from "../../../web/src/components/ui/tooltip";+import { LocaleProvider, LocaleScope } from "../../../web/src/state/locale";+import { ThemeProvider } from "../../../web/src/state/theme";+// The app's dependency, reached through its own node_modules, ahead of the app's own sheet.+import "../../../web/node_modules/katex/dist/katex.min.css";+import "./library.css";+import { installFetchShim } from "../app/mock/fetch-shim";+import { getStore } from "../app/mock/store";+import { GalleryProvider } from "../state";+import { parseLibraryParams } from "./frame";+import { installSelfResizeGuard } from "./frame-resize";+import { LibraryBoardPage } from "./page";++const params = parseLibraryParams(window.location.search);+getStore({ lang: params.lang, signedIn: true });+installFetchShim();++// Framed, the document is sized by the page around it and must never show a scrollbar of its own+// (library.css keys on the attribute; set before the first paint), and a focus must not scroll+// the page around the frame (see src/app/main.tsx).+if (window.parent !== window) {+ document.documentElement.dataset.framed = "1";+ // Before the app mounts, so the guard's listener runs ahead of the app's own.+ installSelfResizeGuard(window);+ const focus = HTMLElement.prototype.focus;+ HTMLElement.prototype.focus = function (this: HTMLElement, options?: FocusOptions) {+ focus.call(this, { ...options, preventScroll: true });+ };+}++const container = document.getElementById("root");+if (!container) throw new Error("#root mount point not found");++createRoot(container).render(+ <StrictMode>+ <LocaleProvider>+ <ThemeProvider>+ <LocaleScope>+ <GalleryProvider>+ <LibraryBoardPage topic={params.topic} />+ </GalleryProvider>+ <Toaster />+ <TooltipLayer />+ </LocaleScope>+ </ThemeProvider>+ </LocaleProvider>+ </StrictMode>,+);diff --git a/packages/ui-gallery/src/library/page.tsx b/packages/ui-gallery/src/library/page.tsxnew file mode 100644index 00000000..cfae2246--- /dev/null+++ b/packages/ui-gallery/src/library/page.tsx@@ -0,0 +1,76 @@+/**+ * The board page inside a library frame: the topic's board on the theme's canvas, and the+ * height report the page around the frame sizes it by. The height is what is painted+ * (frame-height.ts): the board, and any overlay open over it — a menu, a tooltip, a toast, a+ * dialog — measured again whenever the board lays out differently or anything is added to,+ * removed from or moved in the body (the app's overlays are portals on the body). The reports+ * are coalesced to one per animation frame, and one is sent only when the height changed.+ *+ * A report that will resize the frame is announced to the resize guard first (frame-resize.ts),+ * so the app's panels do not take the frame's own growth for a window resize and close; the+ * growth itself is heard back through the guard and measured once more, since a dialog's body+ * opens up to the taller viewport and the panel may then need a little more.+ */+import { useEffect, useRef } from "react";+import { BOARDS } from "./boards";+import { LIBRARY_HEIGHT_MESSAGE } from "./frame";+import { measureFrameHeight } from "./frame-height";+import { expectSelfResize, onSelfResize } from "./frame-resize";+import type { TopicId } from "./topics";++export function LibraryBoardPage({ topic }: { topic: TopicId }) {+ const Board = BOARDS[topic];+ const page = useRef<HTMLElement>(null);++ useEffect(() => {+ const main = page.current;+ const root = document.getElementById("root");+ if (!main || !root || window.parent === window) return;+ let frame = 0;+ let reported = -1;+ const report = () => {+ frame = 0;+ const height = measureFrameHeight(document, main, root);+ if (height === reported) return;+ reported = height;+ if (height !== window.innerHeight) expectSelfResize();+ window.parent.postMessage({ type: LIBRARY_HEIGHT_MESSAGE, height }, "*");+ };+ const schedule = () => {+ if (frame === 0) frame = requestAnimationFrame(report);+ };+ schedule();+ const sizes = new ResizeObserver(schedule);+ sizes.observe(main);+ // Portals come and go as direct children of the body; a panel that moves or grows changes+ // its style or its contents.+ const mutations = new MutationObserver(schedule);+ mutations.observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ["style", "class"],+ });+ void document.fonts.ready.then(schedule);+ const unsubscribe = onSelfResize(schedule);+ return () => {+ sizes.disconnect();+ mutations.disconnect();+ unsubscribe();+ if (frame !== 0) cancelAnimationFrame(frame);+ };+ }, []);++ // What the screenshot script waits for: the board mounted and its fonts loaded.+ useEffect(() => {+ void document.fonts.ready.then(() => {+ document.documentElement.dataset.galleryReady = "1";+ });+ }, []);++ return (+ <main ref={page} className="lib-page" data-topic={topic}>+ <Board />+ </main>+ );+}diff --git a/packages/ui-gallery/src/library/topics.ts b/packages/ui-gallery/src/library/topics.tsnew file mode 100644index 00000000..9e976c30--- /dev/null+++ b/packages/ui-gallery/src/library/topics.ts@@ -0,0 +1,85 @@+/**+ * The component library's pages, one per topic: the Web App's real components by kind, then the+ * boards of the token vocabulary. Value-import-free, so the screenshot script and the tests can+ * read it under Node; the titles live in the dictionaries, keyed by these ids.+ *+ * Each topic renders in its own framed document (`lib.html`, src/library/main.tsx) under the+ * page's theme, mode, size and fonts, in a frame sized to what the board paints, overlays+ * included (src/library/frame-height.ts).+ */++export const TOPIC_GROUP_IDS = ["components", "foundations"] as const;+export type TopicGroupId = (typeof TOPIC_GROUP_IDS)[number];++export const TOPIC_IDS = [+ "buttons",+ "inputs",+ "pickers",+ "toasts",+ "notices",+ "dialogs",+ "tooltips",+ "tabs",+ "badges",+ "empty",+ "loading",+ "charts",+ "avatars",+ "files",+ "colour",+ "type",+ "shape",+ "density",+ "focus",+ "motion",+ "icons",+ "hooks",+] as const;+export type TopicId = (typeof TOPIC_IDS)[number];++export interface Topic {+ id: TopicId;+ group: TopicGroupId;+}++const component = (id: TopicId): Topic => ({ id, group: "components" });+const foundation = (id: TopicId): Topic => ({ id, group: "foundations" });++export const TOPICS: readonly Topic[] = [+ component("buttons"),+ component("inputs"),+ component("pickers"),+ component("toasts"),+ component("notices"),+ component("dialogs"),+ component("tooltips"),+ component("tabs"),+ component("badges"),+ component("empty"),+ component("loading"),+ component("charts"),+ component("avatars"),+ component("files"),+ foundation("colour"),+ foundation("type"),+ foundation("shape"),+ foundation("density"),+ foundation("focus"),+ foundation("motion"),+ foundation("icons"),+ foundation("hooks"),+];++/** The page the 基础 link opens. */+export const FIRST_TOPIC: TopicId = "buttons";++export const TOPIC_GROUPS: readonly { id: TopicGroupId; topics: readonly Topic[] }[] =+ TOPIC_GROUP_IDS.map((id) => ({ id, topics: TOPICS.filter((topic) => topic.group === id) }));++export function isTopicId(value: string): value is TopicId {+ return (TOPIC_IDS as readonly string[]).includes(value);+}++export function topicById(id: TopicId): Topic {+ return TOPICS.find((topic) => topic.id === id)!;+}diff --git a/packages/ui-gallery/src/main.tsx b/packages/ui-gallery/src/main.tsxnew file mode 100644index 00000000..1c54044a--- /dev/null+++ b/packages/ui-gallery/src/main.tsx@@ -0,0 +1,14 @@+/** Gallery entry point. */+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { App } from "./app";+import "./styles.css";++const container = document.getElementById("root");+if (!container) throw new Error("#root mount point not found");++createRoot(container).render(+ <StrictMode>+ <App />+ </StrictMode>,+);diff --git a/packages/ui-gallery/src/pages/fonts.tsx b/packages/ui-gallery/src/pages/fonts.tsxnew file mode 100644index 00000000..24a425f8--- /dev/null+++ b/packages/ui-gallery/src/pages/fonts.tsx@@ -0,0 +1,310 @@+/**+ * `/fonts`, `/fonts/specimens`, `/fonts/licences` — the 字体 section, three pages under one nav:+ *+ * - Defaults: each theme's default Latin, CJK and mono face as the package states them+ * (lib/theme-fonts.ts), the active theme's row marked; then the pairing chosen in the top bar+ * and the faces actually rendering (the readout).+ * - Specimens: each theme's families, resolved from its tokens, set in an en and a zh paragraph+ * at the five text sizes; then the `@font-face` rules the page's styles declare, one row per+ * family, weight and style, with the number of `unicode-range` slices and their load status.+ * - Licences: the licence texts under the package's `fonts/LICENSES/`.+ */+import { THEME_IDS } from "@prismshadow/penguin-ui";+import { useEffect, useState } from "react";+import type { ReactNode } from "react";+import { FontReadoutLine } from "../chrome/font-readout";+import { FontsNav } from "../chrome/sidenav";+import { Site } from "../chrome/site";+import { SPECIMENS } from "../foundations/specimens";+import type { FontsPageId } from "../lib/routes";+import { isSystemFont, themeFontRows } from "../lib/theme-fonts";+import { fontLabel, TEXT_SIZE_PX_NUMBER, TEXT_SIZES } from "../lib/themes";+import { FONT_LICENSES, licencePath } from "../sources";+import { useGallery } from "../state";+import { useText } from "../text";++const ROLES = ["--ui-font-sans", "--ui-font-mono", "--ui-font-display", "--ui-font-cjk"] as const;++interface FaceRow {+ family: string;+ /** `400`, or a variable face's range `100 900`. */+ weight: string;+ style: string;+ /** How many `@font-face` rules (unicode-range slices) share this family, weight and style. */+ slices: number;+ status: Record<FontFaceLoadStatus, number>;+}++function useFaces(): FaceRow[] {+ const [faces, setFaces] = useState<FaceRow[]>([]);+ useEffect(() => {+ const read = () => {+ const rows = new Map<string, FaceRow>();+ document.fonts.forEach((face) => {+ const family = face.family.replace(/^["']|["']$/g, "");+ const key = `${family}|${face.weight}|${face.style}`;+ const row = rows.get(key) ?? {+ family,+ weight: face.weight,+ style: face.style,+ slices: 0,+ status: { unloaded: 0, loading: 0, loaded: 0, error: 0 },+ };+ row.slices++;+ row.status[face.status]++;+ rows.set(key, row);+ });+ setFaces(+ [...rows.values()].sort(+ (a, b) =>+ a.family.localeCompare(b.family) ||+ a.weight.localeCompare(b.weight, "en", { numeric: true }) ||+ a.style.localeCompare(b.style),+ ),+ );+ };+ read();+ document.fonts.addEventListener("loadingdone", read);+ void document.fonts.ready.then(read);+ return () => document.fonts.removeEventListener("loadingdone", read);+ }, []);+ return faces;+}++function Licence({ path }: { path: string }) {+ const [text, setText] = useState<string | null>(null);+ return (+ <details+ className="g-licence"+ onToggle={(event) => {+ const load = FONT_LICENSES[path];+ if ((event.target as HTMLDetailsElement).open && text === null && load)+ void load().then(setText);+ }}+ >+ <summary>{licencePath(path)}</summary>+ <pre className="g-code">{text ?? "…"}</pre>+ </details>+ );+}++/** The section frame the three pages share. */+function FontsSite({+ page,+ title,+ children,+}: {+ page: FontsPageId;+ title: string;+ children: ReactNode;+}) {+ const { S } = useGallery();+ return (+ <Site+ page="fonts"+ nav={(onNavigate) => <FontsNav activeId={page} {...(onNavigate ? { onNavigate } : {})} />}+ wide+ >+ <article className="g-doc g-doc-wide">+ <header className="g-doc-head">+ <p className="g-eyebrow">{S.site.fonts}</p>+ <h1 className="g-h1">{title}</h1>+ </header>+ {children}+ </article>+ </Site>+ );+}++function DefaultsPage() {+ const { S, state } = useGallery();+ const text = useText();+ const face = (name: string) => (isSystemFont(name) ? S.fonts.system : name);+ const words = { theme: S.rail.fontTheme, system: S.rail.fontSystem };+ const active = text.theme(state.theme);+ const choice = (id: string, label: string) =>+ id === "theme" ? S.fonts.followsTheme(active) : label;++ useEffect(() => {+ void document.fonts.ready.then(() => {+ document.documentElement.dataset.galleryReady = "1";+ });+ }, []);++ return (+ <FontsSite page="defaults" title={S.fonts.defaultsTitle}>+ <section id="defaults" className="g-section">+ <p className="g-section-lead">{S.fonts.defaultsHint}</p>+ <table className="g-table g-fonts-table">+ <thead>+ <tr>+ <th>{S.rail.theme}</th>+ <th>{S.readout.latin}</th>+ <th>{S.readout.cjk}</th>+ <th>{S.readout.mono}</th>+ </tr>+ </thead>+ <tbody>+ {themeFontRows().map((row) => (+ <tr key={row.theme} aria-current={row.theme === state.theme ? "true" : undefined}>+ <th scope="row">{text.theme(row.theme)}</th>+ <td>{face(row.latin)}</td>+ <td>{face(row.cjk)}</td>+ <td>{face(row.mono)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </section>++ <section id="current" className="g-section">+ <h2 className="g-h2">{S.fonts.current}</h2>+ <p className="g-section-lead">{S.fonts.currentHint}</p>+ <dl className="g-fonts-current">+ <div>+ <dt>{S.rail.fontLatin}</dt>+ <dd>{choice(state.latin, fontLabel(state.latin, words))}</dd>+ </div>+ <div>+ <dt>{S.rail.fontCjk}</dt>+ <dd>{choice(state.cjk, fontLabel(state.cjk, words))}</dd>+ </div>+ </dl>+ <FontReadoutLine />+ </section>+ </FontsSite>+ );+}++function SpecimensPage() {+ const { S, mode, tokens } = useGallery();+ const text = useText();+ const faces = useFaces();++ useEffect(() => {+ if (!tokens) return;+ void document.fonts.ready.then(() => {+ document.documentElement.dataset.galleryReady = "1";+ });+ }, [tokens]);++ return (+ <FontsSite page="specimens" title={S.fonts.specimensTitle}>+ <section id="specimens" className="g-section">+ <p className="g-section-lead">{S.fonts.specimensHint}</p>+ {!tokens && <p className="g-muted">{S.intro.resolving}</p>}+ {tokens &&+ THEME_IDS.map((themeId) => {+ const values = tokens[themeId][mode];+ return (+ <div key={themeId} className="g-font-theme">+ <h3>{text.theme(themeId)}</h3>+ {ROLES.map((role) => {+ const family = values[role];+ return (+ <div key={role} className="g-font-role">+ <div className="g-font-role-meta">+ <code>{role}</code>+ <span className="g-muted" data-unset={!family || undefined}>+ {family || S.section.unset}+ </span>+ </div>+ <div className="g-font-samples">+ {TEXT_SIZES.map((size) => (+ <div+ key={size}+ className="g-font-sample"+ style={{+ fontFamily: family || undefined,+ fontSize: TEXT_SIZE_PX_NUMBER[size],+ }}+ >+ <span className="g-font-size">{TEXT_SIZE_PX_NUMBER[size]}px</span>+ {(["en", "zh"] as const).map((lang) => (+ <p key={lang} lang={lang === "zh" ? "zh-CN" : "en"}>+ {role === "--ui-font-mono"+ ? SPECIMENS[lang].code+ : SPECIMENS[lang].paragraph}+ </p>+ ))}+ </div>+ ))}+ </div>+ </div>+ );+ })}+ </div>+ );+ })}+ </section>++ <section id="declared" className="g-section">+ <h2 className="g-h2">{S.fonts.declared}</h2>+ <p className="g-section-lead">{S.fonts.declaredHint}</p>+ {faces.length === 0 ? (+ <p className="g-muted">{S.fonts.noFaces}</p>+ ) : (+ <table className="g-table">+ <thead>+ <tr>+ <th>{S.fonts.family}</th>+ <th>{S.fonts.weight}</th>+ <th>{S.fonts.slicesColumn}</th>+ <th>{S.fonts.loadStatus}</th>+ </tr>+ </thead>+ <tbody>+ {faces.map((face) => (+ <tr key={`${face.family}|${face.weight}|${face.style}`}>+ <td+ style={{+ fontFamily: `"${face.family}"`,+ fontWeight: face.weight.split(" ")[0],+ }}+ >+ {face.family}+ </td>+ <td>+ <code>+ {face.weight}+ {face.style !== "normal" ? ` ${face.style}` : ""}+ </code>+ </td>+ <td className="g-num-cell">{face.slices}</td>+ <td className="g-muted">+ {(Object.keys(face.status) as FontFaceLoadStatus[])+ .filter((status) => face.status[status] > 0)+ .map((status) => `${S.fonts.status[status]} ${face.status[status]}`)+ .join(" · ")}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </section>+ </FontsSite>+ );+}++function LicencesPage() {+ const { S } = useGallery();+ const licences = Object.keys(FONT_LICENSES).sort();+ return (+ <FontsSite page="licences" title={S.fonts.licencesTitle}>+ <section id="licences" className="g-section">+ {licences.length === 0 ? (+ <p className="g-muted">{S.fonts.noLicences}</p>+ ) : (+ licences.map((path) => <Licence key={path} path={path} />)+ )}+ </section>+ </FontsSite>+ );+}++export function FontsPage({ page }: { page: FontsPageId }) {+ if (page === "specimens") return <SpecimensPage />;+ if (page === "licences") return <LicencesPage />;+ return <DefaultsPage />;+}diff --git a/packages/ui-gallery/src/pages/home.tsx b/packages/ui-gallery/src/pages/home.tsxnew file mode 100644index 00000000..e268e54b--- /dev/null+++ b/packages/ui-gallery/src/pages/home.tsx@@ -0,0 +1,124 @@+/**+ * `/` — the home page: a short intro, the real app in a frame (the finished conversation, in the+ * active theme, laid out for the app's window and scaled to the column; Reload reloads it), then+ * the three sections' indexes — every surface in its group, every library topic in its group,+ * and the fonts pages — each entry a card linking to its page.+ */+import { useState } from "react";+import { HOME_SURFACE, SURFACE_GROUPS, surfaceById } from "../app/surfaces";+import { AppFrame, useFrameSrc } from "../chrome/app-frame";+import { ChromeIcon } from "../chrome/icons";+import { Site } from "../chrome/site";+import { TOPIC_GROUPS } from "../library/topics";+import { BASE } from "../lib/location";+import { FONTS_PAGE_IDS, fontsHref, surfaceHref, topicHref } from "../lib/routes";+import { useGallery } from "../state";+import { useText } from "../text";++export function HomePage() {+ const { S, state } = useGallery();+ const text = useText();+ const [epoch, setEpoch] = useState(0);+ const surface = surfaceById(HOME_SURFACE)!;+ const standalone = useFrameSrc(surface, state.theme);++ return (+ <Site page="home">+ <div className="g-home">+ <header className="g-doc-head">+ <p className="g-eyebrow">{S.home.eyebrow}</p>+ <h1 className="g-h1">{S.home.title}</h1>+ <p className="g-lead">{S.home.lead}</p>+ </header>++ <section id="app" className="g-section">+ <h2 className="g-h2">{S.home.app}</h2>+ <p className="g-section-lead">{S.home.appLead}</p>+ <div className="g-toolbar">+ <button+ type="button"+ className="g-tool g-tool-primary"+ onClick={() => setEpoch((current) => current + 1)}+ >+ <ChromeIcon name="restart" size={13} />+ <span>{S.frame.reload}</span>+ </button>+ <a className="g-tool" href={standalone} target="_blank" rel="noreferrer">+ <ChromeIcon name="external" size={14} />+ <span>{S.frame.open}</span>+ </a>+ </div>+ <div className="g-frame">+ <AppFrame surface={surface} reloadKey={epoch} />+ </div>+ </section>++ <section id="surfaces" className="g-section">+ <h2 className="g-h2">{S.home.index}</h2>+ <p className="g-section-lead">{S.home.indexLead}</p>+ {SURFACE_GROUPS.map((group) => (+ <div key={group.id} className="g-index-group">+ <h3 className="g-index-eyebrow">{text.surfaceGroup(group.id)}</h3>+ <ul className="g-index">+ {group.surfaces.map((entry) => {+ const { title, description } = text.surface(entry.id);+ return (+ <li key={entry.id}>+ <a href={surfaceHref(BASE, state, entry.id)}>+ <strong>{title}</strong>+ <span>{description}</span>+ </a>+ </li>+ );+ })}+ </ul>+ </div>+ ))}+ </section>++ <section id="library" className="g-section">+ <h2 className="g-h2">{S.home.library}</h2>+ <p className="g-section-lead">{S.home.libraryLead}</p>+ {TOPIC_GROUPS.map((group) => (+ <div key={group.id} className="g-index-group">+ <h3 className="g-index-eyebrow">{text.topicGroup(group.id)}</h3>+ <ul className="g-index">+ {group.topics.map((topic) => {+ const { title, description } = text.topic(topic.id);+ return (+ <li key={topic.id}>+ <a href={topicHref(BASE, state, topic.id)}>+ <strong>{title}</strong>+ <span>{description}</span>+ </a>+ </li>+ );+ })}+ </ul>+ </div>+ ))}+ </section>++ <section id="fonts" className="g-section">+ <h2 className="g-h2">{S.home.fonts}</h2>+ <p className="g-section-lead">{S.home.fontsLead}</p>+ <ul className="g-index">+ {FONTS_PAGE_IDS.map((page) => (+ <li key={page}>+ <a href={fontsHref(BASE, state, page)}>+ <strong>{S.fonts.pages[page]}</strong>+ </a>+ </li>+ ))}+ </ul>+ </section>++ <aside className="g-note">+ <strong>{S.site.feedbackTitle}</strong>+ <p>{S.site.feedbackBody}</p>+ <code>{S.site.feedbackExample}</code>+ </aside>+ </div>+ </Site>+ );+}diff --git a/packages/ui-gallery/src/pages/library.tsx b/packages/ui-gallery/src/pages/library.tsxnew file mode 100644index 00000000..448ab795--- /dev/null+++ b/packages/ui-gallery/src/pages/library.tsx@@ -0,0 +1,82 @@+/**+ * `/c/<topic>` — one component library page: the topic list on the left, the content column —+ * the group's eyebrow, the title, the description, a toolbar (reload, open standalone, copy+ * link, the breadcrumb) and the topic's board framed (chrome/library-frame.tsx).+ */+import { useState } from "react";+import { LibraryFrame, useLibraryFrameSrc } from "../chrome/library-frame";+import { useCopy } from "../chrome/copy";+import { Breadcrumb } from "../chrome/crumb";+import { ChromeIcon } from "../chrome/icons";+import { TopicNav } from "../chrome/sidenav";+import { Site } from "../chrome/site";+import { topicById } from "../library/topics";+import type { TopicId } from "../library/topics";+import { formatBreadcrumb } from "../lib/breadcrumb";+import { absoluteUrl } from "../lib/location";+import { topicPath } from "../lib/routes";+import { formatGalleryQuery } from "../lib/url-state";+import { useGallery } from "../state";+import { useText } from "../text";++export function LibraryPage({ id }: { id: TopicId }) {+ const { S, state } = useGallery();+ const text = useText();+ const [copied, copy] = useCopy();+ const [epoch, setEpoch] = useState(0);+ const { title, description } = text.topic(id);+ const standalone = useLibraryFrameSrc(id);+ const crumb = formatBreadcrumb({+ theme: text.theme(state.theme),+ page: title,+ size: state.size,+ ...text.qualifiers(),+ });+ const link = () => absoluteUrl(`${topicPath(id)}${formatGalleryQuery(state)}`);++ return (+ <Site+ page="foundations"+ nav={(onNavigate) => <TopicNav activeId={id} {...(onNavigate ? { onNavigate } : {})} />}+ wide+ >+ <article className="g-doc g-doc-wide">+ <header className="g-doc-head">+ <p className="g-eyebrow">{text.topicGroup(topicById(id).group)}</p>+ <h1 className="g-h1">{title}</h1>+ <p className="g-lead">{description}</p>+ </header>++ <section id="board" className="g-section">+ <div className="g-toolbar">+ <button+ type="button"+ className="g-tool g-tool-primary"+ onClick={() => setEpoch((current) => current + 1)}+ >+ <ChromeIcon name="restart" size={13} />+ <span>{S.frame.reload}</span>+ </button>+ <a className="g-tool" href={standalone} target="_blank" rel="noreferrer">+ <ChromeIcon name="external" size={14} />+ <span>{S.frame.open}</span>+ </a>+ <button+ type="button"+ className="g-tool g-tool-icon"+ aria-label={S.section.copyLink}+ data-tooltip={S.section.copyLink}+ onClick={() => copy("link", link())}+ >+ <ChromeIcon name={copied === "link" ? "check" : "link"} size={14} />+ </button>+ <Breadcrumb text={crumb} />+ </div>+ <div className="g-frame">+ <LibraryFrame topic={id} reloadKey={epoch} />+ </div>+ </section>+ </article>+ </Site>+ );+}diff --git a/packages/ui-gallery/src/pages/missing.tsx b/packages/ui-gallery/src/pages/missing.tsxnew file mode 100644index 00000000..5c9ad85a--- /dev/null+++ b/packages/ui-gallery/src/pages/missing.tsx@@ -0,0 +1,70 @@+/**+ * `/s/<nothing>`, `/c/<nothing>` or `/fonts/<nothing>`: says so and lists every page there is —+ * the surfaces, the library topics and the fonts pages.+ */+import { SURFACES } from "../app/surfaces";+import { Site } from "../chrome/site";+import { TOPICS } from "../library/topics";+import { BASE } from "../lib/location";+import { FONTS_PAGE_IDS, fontsHref, surfaceHref, topicHref } from "../lib/routes";+import { useGallery } from "../state";+import { useText } from "../text";++export function MissingPage({ id }: { id: string }) {+ const { S, state } = useGallery();+ const text = useText();+ return (+ <Site page="surfaces">+ <article className="g-doc">+ <header className="g-doc-head">+ <p className="g-eyebrow">{S.site.surfaces}</p>+ <h1 className="g-h1">{S.site.notFound(id)}</h1>+ </header>+ <section className="g-section">+ <h2 className="g-h2">{S.site.allSurfaces}</h2>+ <ul className="g-index">+ {SURFACES.map((surface) => {+ const named = text.surface(surface.id);+ return (+ <li key={surface.id}>+ <a href={surfaceHref(BASE, state, surface.id)}>+ <strong>{named.title}</strong>+ <span>{named.description}</span>+ </a>+ </li>+ );+ })}+ </ul>+ </section>+ <section className="g-section">+ <h2 className="g-h2">{S.library.title}</h2>+ <ul className="g-index">+ {TOPICS.map((topic) => {+ const named = text.topic(topic.id);+ return (+ <li key={topic.id}>+ <a href={topicHref(BASE, state, topic.id)}>+ <strong>{named.title}</strong>+ <span>{named.description}</span>+ </a>+ </li>+ );+ })}+ </ul>+ </section>+ <section className="g-section">+ <h2 className="g-h2">{S.site.fonts}</h2>+ <ul className="g-index">+ {FONTS_PAGE_IDS.map((page) => (+ <li key={page}>+ <a href={fontsHref(BASE, state, page)}>+ <strong>{S.fonts.pages[page]}</strong>+ </a>+ </li>+ ))}+ </ul>+ </section>+ </article>+ </Site>+ );+}diff --git a/packages/ui-gallery/src/pages/surface.tsx b/packages/ui-gallery/src/pages/surface.tsxnew file mode 100644index 00000000..64d60f50--- /dev/null+++ b/packages/ui-gallery/src/pages/surface.tsx@@ -0,0 +1,112 @@+/**+ * `/s/<surface>` — one surface's page: the surface list on the left, the content column — the+ * group's eyebrow, the title, the description, the app framed on the surface's route, then+ * where the surface is in the app and the fonts the frame is set in — and "on this page" on the+ * right.+ */+import { useCallback, useState } from "react";+import type { FontReadout } from "../app/fonts";+import { formatFontReadout } from "../app/fonts";+import { surfaceById } from "../app/surfaces";+import type { SurfaceId } from "../app/surfaces";+import { AppFrame, useFrameSrc } from "../chrome/app-frame";+import { useCopy } from "../chrome/copy";+import { Breadcrumb } from "../chrome/crumb";+import { ChromeIcon } from "../chrome/icons";+import { SurfaceNav } from "../chrome/sidenav";+import { Site } from "../chrome/site";+import { OnThisPage } from "../chrome/toc";+import { formatBreadcrumb } from "../lib/breadcrumb";+import { absoluteUrl } from "../lib/location";+import { surfacePath } from "../lib/routes";+import { formatGalleryQuery } from "../lib/url-state";+import { useScrollSpy } from "../lib/use-scroll-spy";+import { useGallery } from "../state";+import { useText } from "../text";++export function SurfacePage({ id }: { id: SurfaceId }) {+ const { S, state } = useGallery();+ const text = useText();+ const [copied, copy] = useCopy();+ const [epoch, setEpoch] = useState(0);+ const [fonts, setFonts] = useState<FontReadout | null>(null);+ const onFonts = useCallback((readout: FontReadout | null) => setFonts(readout), []);+ const surface = surfaceById(id)!;+ const { title, description, how } = text.surface(id);+ const standalone = useFrameSrc(surface, state.theme);+ const active = useScrollSpy(["app", "where", "fonts"]);+ const crumb = formatBreadcrumb({+ theme: text.theme(state.theme),+ page: title,+ size: state.size,+ ...text.qualifiers(),+ });+ const link = () => absoluteUrl(`${surfacePath(id)}${formatGalleryQuery(state)}`);+ const toc = [+ { id: "app", title: S.home.app },+ { id: "where", title: S.frame.how },+ { id: "fonts", title: S.readout.label },+ ];++ return (+ <Site+ page="surfaces"+ nav={(onNavigate) => <SurfaceNav activeId={id} {...(onNavigate ? { onNavigate } : {})} />}+ toc={<OnThisPage items={toc} activeId={active} />}+ >+ <article className="g-doc">+ <header className="g-doc-head">+ <p className="g-eyebrow">{text.surfaceGroup(surface.group)}</p>+ <h1 className="g-h1">{title}</h1>+ <p className="g-lead">{description}</p>+ </header>++ <section id="app" className="g-section">+ <div className="g-toolbar">+ <button+ type="button"+ className="g-tool g-tool-primary"+ onClick={() => setEpoch((current) => current + 1)}+ >+ <ChromeIcon name="restart" size={13} />+ <span>{S.frame.reload}</span>+ </button>+ <a className="g-tool" href={standalone} target="_blank" rel="noreferrer">+ <ChromeIcon name="external" size={14} />+ <span>{S.frame.open}</span>+ </a>+ <button+ type="button"+ className="g-tool g-tool-icon"+ aria-label={S.section.copyLink}+ data-tooltip={S.section.copyLink}+ onClick={() => copy("link", link())}+ >+ <ChromeIcon name={copied === "link" ? "check" : "link"} size={14} />+ </button>+ <Breadcrumb text={crumb} />+ </div>+ <div className="g-frame" data-framed>+ <AppFrame surface={surface} reloadKey={epoch} onFonts={onFonts} />+ </div>+ </section>++ <section id="where" className="g-section">+ <h2 className="g-h2">{S.frame.how}</h2>+ <p className="g-section-lead">{how}</p>+ <p className="g-section-meta">+ {S.frame.route} <code>{surface.route}</code>+ {surface.signedOut && <> · {S.frame.signedOut}</>}+ </p>+ </section>++ <section id="fonts" className="g-section">+ <h2 className="g-h2">{S.readout.label}</h2>+ <p className="g-section-lead g-readout-line">+ {fonts ? formatFontReadout(fonts, S.readout) : S.readout.pending}+ </p>+ </section>+ </article>+ </Site>+ );+}diff --git a/packages/ui-gallery/src/sources.ts b/packages/ui-gallery/src/sources.tsnew file mode 100644index 00000000..85888a44--- /dev/null+++ b/packages/ui-gallery/src/sources.ts@@ -0,0 +1,40 @@+/**+ * Files the gallery reads as text, via Vite globs:+ *+ * - icon sources: the Web App modules that declare line-icon paths (see lib/icon-registry.ts), for+ * the library's Icons board;+ * - font licences: `packages/ui/src/fonts/LICENSES/*.txt`, lazy, for `/fonts/licences`.+ */+import { extractIconPaths, extractIconSizes } from "./lib/icon-registry";++/** Glob path → repo-relative path, for display. */+const repoPath = (globPath: string) => globPath.replace(/^(\.\.\/)+/, "packages/");++const iconSources = import.meta.glob<string>(+ [+ "../../web/src/components/ui/icons.tsx",+ "../../web/src/components/ui/group-list.tsx",+ "../../web/src/components/ui/session-row-menu.tsx",+ "../../web/src/lib/stat-icons.ts",+ ],+ { query: "?raw", import: "default", eager: true },+);++export const WEB_ICONS = extractIconPaths(+ Object.fromEntries(Object.entries(iconSources).map(([path, text]) => [repoPath(path), text])),+);++const iconScale = import.meta.glob<string>("../../web/src/lib/icon-scale.ts", {+ query: "?raw",+ import: "default",+ eager: true,+});++export const WEB_ICON_SIZES = extractIconSizes(Object.values(iconScale)[0] ?? "");++export const FONT_LICENSES = import.meta.glob<string>("../../ui/src/fonts/LICENSES/*.txt", {+ query: "?raw",+ import: "default",+});++export { repoPath as licencePath };diff --git a/packages/ui-gallery/src/state.tsx b/packages/ui-gallery/src/state.tsxnew file mode 100644index 00000000..3980b880--- /dev/null+++ b/packages/ui-gallery/src/state.tsx@@ -0,0 +1,167 @@+/**+ * The gallery context every route renders inside: the URL-backed view state, the resolved mode,+ * the chrome dictionary, and the token and accent matrices.+ *+ * The provider owns the document root: it applies the theme under test to <html> through the+ * package's own `applyThemeAttributes` (the same contract the app's boot script and theme provider+ * follow) — theme, mode, the accent choice, the text size and the font pairing, which is what makes+ * the size real: every rem in a Foundations board follows `<html style="font-size">`, while the+ * chrome, sized in px, does not — sets `lang` so CJK text shapes as Chinese, and marks the phone+ * view. The framed app gets the same preferences through its own URL (src/app/frame.ts), so the+ * page's root and every frame carry one theme. The gallery chrome never reads those attributes'+ * theme — only `.dark`, to pick its own light or dark palette.+ */+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useLayoutEffect,+ useMemo,+ useState,+} from "react";+import type { ReactNode } from "react";+import { applyThemeAttributes } from "@prismshadow/penguin-ui/boot";+import { asAccentChoice, resolveAccent } from "./lib/accents";+import { replaceSearch, usePrefersDark, useSearch } from "./lib/location";+import { probeAccents, probeTokens } from "./lib/token-probe";+import type { AccentMatrix, TokenMatrix } from "./lib/token-probe";+import { formatGalleryQuery, parseGalleryState, PREF_KEYS, resolveMode } from "./lib/url-state";+import type { GalleryState, RememberedPrefs } from "./lib/url-state";+import { zh } from "./strings";+import type { GalleryStrings } from "./strings";+import { en } from "./strings-en";++const storageKey = (key: string) => `penguin-gallery.${key}`;++function readRemembered(): RememberedPrefs {+ const prefs: Record<string, string> = {};+ try {+ for (const key of PREF_KEYS) {+ const value = window.localStorage.getItem(storageKey(key));+ if (value) prefs[key] = value;+ }+ } catch {+ // Storage can be unavailable (a sandboxed frame); the URL alone still works.+ }+ return prefs as RememberedPrefs;+}++function remember(state: GalleryState): void {+ try {+ for (const key of PREF_KEYS) window.localStorage.setItem(storageKey(key), state[key]);+ } catch {+ // Convenience only.+ }+}++export interface GalleryContextValue {+ state: GalleryState;+ /** `state.mode` with `system` resolved. */+ mode: "light" | "dark";+ /** `state.accent` as the active theme applies it: the preset, or `neutral` when it lists none such. */+ accent: string;+ S: GalleryStrings;+ /** Every token in every theme × mode; null until the first probe has run. */+ tokens: TokenMatrix | null;+ /** Every theme's own accent and listed presets, resolved; null until the first probe has run. */+ accents: AccentMatrix | null;+ /** Rewrites the URL (and the remembered preferences) with a patched state. */+ update: (patch: Partial<GalleryState> | ((state: GalleryState) => GalleryState)) => void;+}++const GalleryContext = createContext<GalleryContextValue | null>(null);++export function useGallery(): GalleryContextValue {+ const value = useContext(GalleryContext);+ if (!value) throw new Error("useGallery() outside <GalleryProvider>");+ return value;+}++interface Probed {+ tokens: TokenMatrix;+ accents: AccentMatrix;+}++/** Re-probe after the page's CSS changes (Vite HMR swaps <style> tags); debounced. */+function useProbe(): Probed | null {+ const [probed, setProbed] = useState<Probed | null>(null);+ useEffect(() => {+ let timer = 0;+ const run = () => {+ timer = 0;+ setProbed({ tokens: probeTokens(), accents: probeAccents() });+ };+ run();+ const observer = new MutationObserver(() => {+ if (timer) window.clearTimeout(timer);+ timer = window.setTimeout(run, 150);+ });+ observer.observe(document.head, { childList: true, subtree: true, characterData: true });+ return () => {+ observer.disconnect();+ if (timer) window.clearTimeout(timer);+ };+ }, []);+ return probed;+}++export function GalleryProvider({+ children,+ canonicalizeUrl = false,+}: {+ children: ReactNode;+ /** Write the full canonical query into the URL on load, so a copied address pins the view. */+ canonicalizeUrl?: boolean;+}) {+ const search = useSearch();+ const [remembered] = useState(readRemembered);+ const state = useMemo(() => parseGalleryState(search, remembered), [search, remembered]);+ const prefersDark = usePrefersDark();+ const mode = resolveMode(state.mode, prefersDark);+ const accent = resolveAccent(state.theme, state.accent);+ const probed = useProbe();++ const update = useCallback<GalleryContextValue["update"]>((patch) => {+ const current = parseGalleryState(window.location.search, readRemembered());+ const next = typeof patch === "function" ? patch(current) : { ...current, ...patch };+ remember(next);+ replaceSearch(formatGalleryQuery(next));+ }, []);++ useEffect(() => {+ if (canonicalizeUrl) replaceSearch(formatGalleryQuery(state));+ // Only the first render's state is canonicalized; later changes go through update().+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [canonicalizeUrl]);++ useLayoutEffect(() => {+ const root = document.documentElement;+ // The chosen preset goes onto the root as it is, listed by the active theme or not — the+ // app's boot script does the same, and a theme's preset rules match only their own theme.+ applyThemeAttributes(root, {+ themeId: state.theme,+ dark: mode === "dark",+ accent: asAccentChoice(state.accent),+ textSize: state.size,+ fontLatin: state.latin,+ fontCjk: state.cjk,+ });+ root.lang = state.lang === "zh" ? "zh-CN" : "en";+ root.dataset.view = state.view;+ }, [state.theme, mode, state.size, state.latin, state.cjk, state.accent, state.lang, state.view]);++ const value = useMemo<GalleryContextValue>(+ () => ({+ state,+ mode,+ accent,+ S: state.lang === "zh" ? zh : en,+ tokens: probed?.tokens ?? null,+ accents: probed?.accents ?? null,+ update,+ }),+ [state, mode, accent, probed, update],+ );+ return <GalleryContext.Provider value={value}>{children}</GalleryContext.Provider>;+}diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.tsnew file mode 100644index 00000000..5775394b--- /dev/null+++ b/packages/ui-gallery/src/strings-en.ts@@ -0,0 +1,737 @@+/**+ * English gallery chrome copy, constrained by `GalleryStrings` to the shape of the Chinese+ * dictionary in strings.ts: the surfaces and the library topics are named here, as there.+ */+import type { GalleryStrings } from "./strings";++export const en: GalleryStrings = {+ brand: {+ title: "Penguin UI",+ },+ site: {+ home: "Home",+ surfaces: "Surfaces",+ foundations: "Foundations",+ fonts: "Fonts",+ pages: "Pages",+ search: "Search surfaces",+ searchShortcut: "Ctrl K",+ noMatches: "No surface matches.",+ nav: "Surfaces",+ onThisPage: "On this page",+ settings: "View settings",+ menu: "Open the menu",+ closeMenu: "Close the menu",+ notFound: (id) => `There is no page named “${id}”.`,+ allSurfaces: "All surfaces",+ feedbackTitle: "Feedback",+ feedbackBody:+ "Quote the breadcrumb at the end of a frame's toolbar, or copy the page's address with the link button.",+ feedbackExample: "Frost › Chat · dark",+ },+ surfaceGroups: {+ conversation: "Conversation",+ workbench: "Workbench",+ resources: "Resources",+ measure: "Measure",+ system: "System",+ },+ surfaces: {+ chat: {+ title: "Chat",+ description:+ "A finished Task: thinking, three tool calls, a diff, and a Markdown answer with a table and code.",+ how: "Sidebar › any row of the session list.",+ },+ "chat-running": {+ title: "Chat · tool running",+ description:+ "A Task mid-run: a command is executing, and the tool row shows the running state and its timer.",+ how: "Sidebar › a session row with the running mark.",+ },+ "chat-thinking": {+ title: "Chat · thinking",+ description:+ "A Task mid-run: the model is thinking; the thinking row shows the running state and the text keeps growing.",+ how: "Sidebar › a session row with the running mark.",+ },+ "chat-approval": {+ title: "Chat · awaiting approval",+ description:+ "A Task waiting on a human: a command needs approval; allow or deny it and the Task carries on and ends.",+ how: "Sidebar › a session row with the approval mark.",+ },+ "chat-new": {+ title: "New chat",+ description:+ "The draft page: pick the Agent, Workspace, approval mode and model, then type and send the first message.",+ how: "Sidebar › New chat.",+ },+ agents: {+ title: "Agents",+ description:+ "The Agent list: each Agent's activity curve and its session, tool, Skill and schedule counts.",+ how: "Sidebar › Agents.",+ },+ "agent-settings": {+ title: "Agent settings",+ description:+ "One Agent's settings page: overview, prompt, memory, runtime, tools, Skills, hooks, Vault and schedule tabs.",+ how: "Agents › any Agent.",+ },+ schedules: {+ title: "Schedules",+ description:+ "The Agent settings' schedule tab: periods, next fire time, the bound Session and model.",+ how: "Agents › Agent settings › the Schedules tab.",+ },+ plugins: {+ title: "Plugins",+ description:+ "The plugin library by category, with search and filters; installed Skills and hooks per Agent.",+ how: "Sidebar › Plugins.",+ },+ "plugin-detail": {+ title: "Plugin detail",+ description:+ "One plugin's page: its description, the Skills it brings, its file browser and the install action.",+ how: "Plugins › any plugin.",+ },+ models: {+ title: "Models",+ description:+ "The model table by provider: the default model, credentials, prices, context windows and usage.",+ how: "Sidebar › Models.",+ },+ machines: {+ title: "Machines",+ description:+ "This machine and remote ones: install state, connections, probe results, and adding an ssh host.",+ how: "Sidebar › Machines (admins only).",+ },+ usage: {+ title: "Cost center",+ description:+ "Thirty days of usage: Tokens, cost, requests and success rate, grouped by date, Agent, model or Session, with the error panel.",+ how: "Sidebar › Cost center.",+ },+ benchmark: {+ title: "Evaluation center",+ description:+ "The Benchmark list: published and draft status, case counts, and the score trend across evaluations.",+ how: "Sidebar › Evaluation center.",+ },+ "benchmark-detail": {+ title: "Benchmark detail",+ description:+ "One Benchmark: the score curve, each evaluation's case scores, and the cases' statement and rubric files.",+ how: "Evaluation center › any Benchmark.",+ },+ settings: {+ title: "Settings",+ description:+ "The settings dialog: profile, general, appearance (theme, mode, accent, text size, fonts), account, and the server settings.",+ how: "The account menu at the bottom of the sidebar › Settings.",+ },+ "settings-appearance": {+ title: "Appearance settings",+ description:+ "The settings dialog on its Appearance page: theme, mode, accent, the five text sizes and the font pairing — where theme switching lives.",+ how: "The account menu at the bottom of the sidebar › Settings › Appearance.",+ },+ login: {+ title: "Login",+ description:+ "The sign-in page: the login card over the decorative canvas. Any password signs the demo account in.",+ how: "Any address while signed out.",+ },+ },+ home: {+ eyebrow: "Surface gallery",+ title: "Penguin UI",+ lead: "The real Web App, running in three themes, two modes, five text sizes, the font pairings and two languages — on an in-browser demo API, fully clickable.",+ app: "The app",+ appLead:+ "This is the app itself: the sidebar, every center, the chat and the settings all open. The theme and size controls drive the app in the frame; sending a message streams a scripted reply.",+ index: "Surface index",+ indexLead:+ "One page per surface: the app opened on it, under whatever theme, size and fonts you set.",+ library: "Component library",+ libraryLead:+ "The real Web components, one page per kind, rendered under the theme, mode, size and fonts you set — and interactive.",+ fonts: "Fonts",+ fontsLead: "Each theme's default faces, the current choice, specimens and licences.",+ },+ rail: {+ theme: "Theme",+ themeNames: { github: "Primer", modern: "Frost", geek: "Console" },+ mode: "Mode",+ accent: "Accent",+ accentTheme: "Theme's own",+ size: "Size",+ sizeNames: { xs: "XS", s: "S", m: "M", l: "L", xl: "XL" },+ sizeTitle: (name, px) => `${name} · ${px}px root`,+ fontLatin: "Latin font",+ fontCjk: "CJK font",+ fontTheme: "Theme default",+ fontSystem: "System",+ language: "Language",+ viewport: "Viewport",+ viewports: { desktop: "Desktop", phone: "Phone" },+ langNames: { en: "EN", zh: "中文" },+ modes: { light: "Light", dark: "Dark", system: "System" },+ },+ readout: {+ label: "Fonts in use",+ latin: "Latin",+ cjk: "CJK",+ mono: "Mono",+ system: "System",+ pending: "Reading…",+ },+ crumb: {+ modes: { light: "light", dark: "dark" },+ phone: "phone",+ },+ intro: {+ resolving: "Resolving tokens…",+ },+ frame: {+ open: "Open standalone",+ reload: "Reload",+ frameOf: (theme) => `The app in ${theme}`,+ how: "Where it is in the app",+ route: "Route",+ signedOut: "signed out",+ },+ section: {+ copyLink: "Copy link",+ copyBreadcrumb: "Copy breadcrumb",+ unset: "unset",+ },+ foundations: {+ surfaces: "Surfaces",+ inks: "Inks",+ lines: "Lines",+ inkWords: ["Text", "Muted", "Subtle"],+ accent: "Accent",+ presetsHint:+ "The theme's own accent and the five presets this theme lists; another theme's presets paint nothing here",+ themeAccent: "theme",+ sampleSend: "Send",+ selectedRow: "Selected",+ sampleLink: "Open the docs",+ linkHover: "hover",+ tones: "Tones",+ toneWords: {+ success: "Running",+ attention: "Waiting",+ danger: "Failed",+ done: "Done",+ neutral: "Idle",+ info: "Syncing",+ },+ charts: "Chart series",+ tokenSeries: "Token mix",+ code: "Code and diff",+ codeLines: {+ before: "const hits = rank(q).slice(0, ",+ removed: "3",+ added: "6",+ after: ");",+ selected: "return cite(hits);",+ },+ typeNote:+ "Each row is set in its own role's tokens; the Chinese column shows how the theme's faces set Chinese with Latin runs in it.",+ scene: {+ pageTier: "page",+ cardTitle: "Docs Expert",+ cardMeta: "3 sessions · $0.0231",+ nested: "Inner radius = outer radius − padding",+ primary: "Save",+ secondary: "Cancel",+ input: "Search sessions",+ badge: "Running",+ menuTier: "z-[60] menu",+ menuItems: ["Pin", "Rename", "Move to…"],+ backdropTier: "z-50 dialog",+ dialogTitle: "Delete this session?",+ dialogBody: "Its transcript and Trace files are deleted with it.",+ cancel: "Cancel",+ confirm: "Delete",+ toastTier: "z-[100] toast",+ toast: "Exported Trace #001",+ },+ radius: "Radius",+ shadows: "Shadow levels",+ spacingPage: {+ title: "Settings",+ appearance: "Appearance",+ theme: "Theme",+ themeOptions: ["Light", "Dark", "System"],+ fontSize: "Text size",+ sizeOptions: ["XS", "S", "M", "L", "XL"],+ general: "General",+ language: "Language",+ languageOptions: ["中文", "English"],+ notifications: "Notify when done",+ },+ stack0Note: "stack-0: the narrow bars between a glyph and its label",+ controlHeights: "Control heights, measured",+ iconSizes: "Icon sizes",+ iconRegistry: (icons, files) => `${icons} icons from ${files} files`,+ duplicateNames: "One path, several names",+ durations: "Durations × easings",+ reducedNote: "Reduced motion: every change shows its end state at once.",+ liveSignal: "Live signals",+ loading: "Loading",+ focusRing: "Focus ring",+ inputFocus: "Input focus",+ selection: "Selection",+ scrollbar: "Scrollbar",+ spaceUnit: "Space unit",+ spaceUnitNote: "Every spacing and size utility is a multiple of it: h-8 is eight units.",+ shell: "Shell",+ shellNote:+ "The app window through .ui-shell: the field, the navigation column and the main column, related as each theme decides.",+ presence: "Presence",+ presenceNote:+ "A menu from the top, a dialog from the centre, a toast from the bottom — each on the active theme's enter and exit tokens.",+ reveal: "Reveal",+ revealNote:+ "Streamed text arrives chunk by chunk; each chunk moves once, on the reveal tokens, as it appears.",+ layout: "Layout",+ layoutNote: "The sidebar's width between expanded and rail, on the layout tokens.",+ replay: "Replay",+ replayAll: "Replay all",+ motionSpecimens: {+ menu: "Menu",+ dialog: "Dialog",+ toast: "Toast",+ trigger: "More",+ sidebarRows: ["New chat", "Agents", "Models"],+ },+ hookJobs: {+ "ui-glass": "a transient layer over content",+ "ui-eyebrow": "a group label naming the items below it",+ "ui-display": "the one display title of a page or hero",+ "ui-live": "motion for something running right now",+ "ui-frame": "a ruled box with a head, a body, a foot and panes",+ "ui-underline-nav": "the selected-tab marker of a tab bar",+ "ui-shell": "the app window: a navigation column beside a main column",+ "ui-icon-decor": "an icon its label already says: a theme may tint it or drop it",+ "ui-tree":+ "a list whose rows nest: a file tree, a work group's tool rows, the subagent graph",+ "ui-field": "a labelled control row: a form field or a settings row",+ "ui-activity": "a thinking or tool row at work: running, done or in error",+ "ui-notice":+ "a notice strip or toast, coloured by its tone: info, success, warning, danger or neutral",+ "ui-chart": "a chart: its grid, axes, lines, areas, bars and points",+ "ui-scrim": "the dimmed layer behind a dialog, drawer or sheet",+ },+ hookSamples: {+ menu: ["Pin", "Rename", "Delete"],+ group: "Workspaces",+ rows: ["claude-code-expert", "docs-sync", "release-notes"],+ copy: "Copy",+ tabs: ["Overview", "Traces", "Files"],+ streaming: "Writing the answer",+ tree: {+ root: "claude-code-expert",+ dir: "src",+ files: ["rag.ts", "embed.ts"],+ last: "README.md",+ },+ field: {+ name: "Name",+ value: "Docs Expert",+ hint: "Shown in the sidebar and in messages.",+ notify: "Notify when done",+ notifyHint: "A system notification when a Task ends.",+ },+ },+ },+ fonts: {+ title: "Fonts",+ pages: { defaults: "Defaults", specimens: "Specimens", licences: "Licences" },+ defaultsTitle: "Default faces",+ defaultsHint:+ "Each theme's default face per role: Latin (reading and interface), CJK and mono. “System” leaves the role to the platform.",+ system: "System",+ current: "Current choice",+ currentHint:+ "The pairing picked in the top bar; “theme default” is the active theme's row above. What actually renders is on the next line.",+ followsTheme: (theme) => `Theme default (${theme})`,+ specimensTitle: "Specimens",+ licencesTitle: "Licences",+ specimens: "Specimens",+ specimensHint:+ "Each theme's families, one en and one zh paragraph at the five text sizes (14 / 15 / 16 / 18 / 20 px).",+ declared: "Declared faces",+ declaredHint:+ "The @font-face rules in the page's stylesheets, merged by family, weight and style; a browser downloads a slice only when text uses it.",+ noFaces: "No faces declared.",+ family: "Family",+ weight: "Weight",+ slicesColumn: "Slices",+ loadStatus: "Loaded",+ licences: "Licence texts",+ noLicences: "No licence texts yet.",+ status: { loaded: "loaded", unloaded: "unused", loading: "loading", error: "failed" },+ },+ library: {+ title: "Component library",+ groups: { components: "Components", foundations: "Foundations" },+ topics: {+ buttons: {+ title: "Buttons",+ description: "Four variants, two sizes and the icon button; disabled and busy.",+ },+ inputs: {+ title: "Inputs and forms",+ description:+ "Input, textarea, password and the field scaffolding: label, hint, info and error.",+ },+ pickers: {+ title: "Pickers",+ description: "Select, segmented control, switch, option menu and dropdown.",+ },+ toasts: {+ title: "Toasts",+ description:+ "The notice after an action completes: success, info, attention and error, fired from buttons.",+ },+ notices: {+ title: "Notice strips",+ description: "A notice that owns a row: every tone, with and without actions.",+ },+ dialogs: {+ title: "Dialogs",+ description: "Modal, confirmation, drawer and bottom sheet.",+ },+ tooltips: {+ title: "Tooltips",+ description:+ "Hints on hover and focus: the data-tooltip attribute and the Tooltip component.",+ },+ tabs: { title: "Tabs", description: "The underline tab switcher, with an update badge." },+ badges: {+ title: "Badges and status",+ description: "Badges, run-state icons, session activity marks and the update dot.",+ },+ empty: {+ title: "Empty states",+ description: "The placeholder for a list or detail with nothing in it, with an action.",+ },+ loading: { title: "Loading", description: "The spinner and the skeletons." },+ charts: {+ title: "Charts",+ description:+ "The chart foundation: the primitives every chart draws through, the current theme's chart tokens, and every chart built on them — the donut, cost trend and token bars, requests and success rate, the activity and score sparklines, the Trace timeline.",+ },+ avatars: { title: "Avatars", description: "The user and agent avatars at their sizes." },+ files: { title: "Files", description: "The file tree and the read-only file browser." },+ colour: {+ title: "Colour",+ description: "Surfaces, inks, lines, the accent, the tones, chart series and code colours.",+ },+ type: { title: "Typography", description: "Size, line height and weight per role." },+ shape: { title: "Shape", description: "Radii, the shadow tiers and nesting." },+ density: { title: "Density", description: "The space unit and the control heights." },+ focus: { title: "Focus", description: "Focus ring, input focus, selection and scrollbars." },+ motion: { title: "Motion", description: "Presence, reveal, layout, durations and easing." },+ icons: { title: "Icons", description: "Icon sizes and the Web App's icon registry." },+ hooks: {+ title: "Hooks",+ description: "The structural hooks a theme may redraw, one by one.",+ },+ },+ buttons: {+ variants: "Variants",+ primary: "Save",+ secondary: "Cancel",+ danger: "Delete",+ ghost: "More",+ sizes: "Sizes",+ md: "Default size",+ sm: "Small",+ icon: "Icon button",+ states: "States",+ disabled: "Disabled",+ busy: "Saving…",+ },+ inputs: {+ basics: "Inputs",+ name: "Name",+ namePlaceholder: "Docs Expert",+ nameHint: "Shown in the sidebar and in messages.",+ email: "Email",+ emailValue: "zheng@example",+ emailError: "The address is incomplete.",+ required: "Required",+ info: "With info",+ infoText: "Takes effect when the next Task starts.",+ sizes: "Sizes",+ base: "Base size",+ small: "Form size",+ textarea: "Textarea",+ textareaPlaceholder: "Write a system prompt…",+ mono: "Monospace",+ monoValue: "temperature: 0.2\nmax_tokens: 4096",+ password: "Password",+ passwordHint: "At least 12 characters.",+ },+ pickers: {+ select: "Select",+ selectLabel: "Model",+ options: ["DeepSeek V4.1 Flash", "Claude Sonnet 4.5", "GLM-5.3"],+ segmented: "Segmented",+ segments: ["Light", "Dark", "System"],+ switches: "Switch",+ switchLabel: "Notify when done",+ switchHint: "A system notification when a Task ends.",+ switchOff: "Short tool names",+ optionMenu: "Option menu",+ optionLabel: "Permission",+ choices: [+ {+ value: "r",+ trigger: "r",+ label: "Read only",+ description: "Can only read the workspace.",+ },+ {+ value: "rw",+ trigger: "rw",+ label: "Read and write",+ description: "May change files in the workspace.",+ },+ {+ value: "ask",+ trigger: "ask",+ label: "Ask each time",+ description: "Asks before every write.",+ },+ ],+ dropdown: "Dropdown",+ menu: "More actions",+ menuItems: ["Pin", "Rename", "Move to…", "Delete"],+ },+ toasts: {+ fire: "Fire a toast",+ hint: "A toast appears at the top of the page and leaves after a few seconds; an error or an advisory stays longer.",+ success: "Success",+ info: "Info",+ attention: "Attention",+ error: "Error",+ successText: "Saved.",+ infoText: "The index is rebuilding in the background.",+ attentionText: "Saved, but 2 fields were truncated.",+ errorText: "Connection failed: api.example is unreachable.",+ },+ notices: {+ plain: "Every tone",+ dotted: "With a leading mark",+ withActions: "With actions",+ texts: {+ link: "Version 0.3.0 is available.",+ success: "Index rebuilt: 214 files.",+ busy: "Syncing the corpus…",+ attention: "1 unexpected error.",+ danger: "The model returned 401: invalid key.",+ muted: "This session is archived.",+ },+ action: "View",+ dismiss: "Dismiss",+ },+ dialogs: {+ modal: "Modal",+ openModal: "Open a dialog",+ modalTitle: "Rename session",+ modalBody: "The new name shows in the sidebar and in messages.",+ save: "Save",+ cancel: "Cancel",+ confirm: "Confirmation",+ openConfirm: "Delete session…",+ confirmTitle: "Delete this session?",+ confirmBody: "The transcript and the Trace files go with it; this cannot be undone.",+ confirmLabel: "Delete",+ drawer: "Drawer",+ openDrawer: "Open a drawer",+ drawerTitle: "Navigation",+ drawerBody: "The sidebar at phone width slides in from the edge.",+ sheet: "Bottom sheet",+ openSheet: "Open a sheet",+ sheetTitle: "Files",+ sheetBody: "Drag up for the full screen, down to close.",+ },+ tooltips: {+ attribute: "The data-tooltip attribute",+ attributeHint:+ "Any element takes the attribute; an icon-only button carries an aria-label too.",+ component: "The Tooltip component",+ componentHint: "For a trigger that needs the wrapper: beside it, or below it.",+ truncated: "Truncated text",+ truncatedHint: "A command or title the row cannot fit goes whole into the hint.",+ edit: "Edit",+ copy: "Copy",+ settings: "Settings",+ beside: "Beside",+ below: "Below",+ command:+ "pnpm --filter @prismshadow/penguin-web exec vitest run test/session-activity.test.ts --reporter verbose",+ },+ tabs: {+ basic: "Tab switcher",+ badged: "With an update badge",+ items: ["Overview", "Trace", "Files", "Settings"],+ badgeText: "3 skills can be updated",+ body: (tab) => `The “${tab}” tab's content.`,+ },+ badges: {+ badges: "Badges",+ tones: {+ gray: "default",+ brand: "origin",+ green: "running",+ amber: "aborted",+ red: "failed",+ },+ status: "Run state",+ states: {+ running: "Running",+ waiting: "Waiting for approval",+ done: "Done",+ failed: "Failed",+ stopped: "Stopped",+ },+ activity: "Session activity",+ activities: { running: "Running", compacting: "Compacting", completedUnread: "Unread reply" },+ marks: "Other marks",+ background: "Background tasks",+ schedule: "Scheduled",+ dot: "Update dot",+ dotAnchor: "Plugins",+ pill: "Update pill",+ pillText: "3 updates",+ },+ empty: {+ page: "Page empty state",+ title: "No sessions yet",+ description: "Sessions appear here once you send a first message.",+ action: "New chat",+ settings: "Settings empty state",+ settingsText: "No MCP servers added yet.",+ },+ loading: {+ spinner: "Spinner",+ sizes: "Three sizes",+ skeleton: "Skeletons",+ list: "List",+ card: "Card",+ },+ charts: {+ parts: {+ primitives: "Primitives",+ primitivesHint:+ "Every chart draws its marks through these alone: they read the theme's chart tokens and write data-part, the one place a token becomes SVG or HTML.",+ tokens: "The current theme's chart tokens",+ tokensHint:+ "Read from this frame root's computed style; read again after a theme, mode or accent change.",+ charts: "Charts built on them",+ chartsHint: "Every chart kind in the app, on demo data.",+ },+ primitives: {+ bar: "ChartBar",+ barHint: "Its width from bar-fill; top radius, outline and fill opacity each from a token.",+ line: "ChartLine",+ lineHint: "One set of points drawn once per curve; the stroke width from a token.",+ curves: { linear: "linear", smooth: "smooth", step: "step" },+ area: "ChartArea",+ areaHint: "The fill under a line, its opacity from a token.",+ point: "ChartPoint",+ pointHint: "Radius from a token; the theme decides round or square.",+ arc: "ChartArc",+ arcHint:+ "One arc of a ring: the track is a grid part, each segment a Token kind or a slot.",+ grid: "ChartGrid and ChartAxis",+ gridHint: "Grid and axis inks from tokens; the theme decides solid or dashed.",+ timeline: "TimelineBar",+ timelineHint: "The Trace timeline's HTML bar, each of the five kinds on its slot.",+ kinds: {+ thinking: "thinking",+ text: "reply",+ tool_call: "tool call",+ approval: "approval wait",+ tool: "tool run",+ },+ },+ palette: "Palette",+ geometry: "Geometry",+ tokenMeaning: {+ "--ui-chart-1": "slot 1 · violet",+ "--ui-chart-2": "slot 2 · amber",+ "--ui-chart-3": "slot 3 · sky",+ "--ui-chart-4": "slot 4 · rose",+ "--ui-chart-5": "slot 5 · emerald",+ "--ui-chart-6": "slot 6 · fuchsia",+ "--ui-chart-7": "slot 7 · spare",+ "--ui-chart-8": "slot 8 · spare",+ "--ui-chart-ref": "reference line",+ "--ui-chart-cache-read": "cache read",+ "--ui-chart-cache-write": "cache write",+ "--ui-chart-output": "output",+ "--ui-chart-grid": "grid",+ "--ui-chart-axis": "axis",+ "--ui-chart-bar-fill": "share of its band a bar fills (0–1)",+ "--ui-chart-bar-radius": "bar top radius",+ "--ui-chart-bar-stroke": "bar outline width",+ "--ui-chart-bar-stroke-color": "bar outline colour (series = the series colour)",+ "--ui-chart-bar-opacity": "bar fill opacity (0–1)",+ "--ui-chart-line-width": "line width",+ "--ui-chart-point-radius": "data point radius",+ "--ui-chart-curve": "curve (linear / smooth / step)",+ "--ui-chart-area-opacity": "area fill opacity (0–1)",+ },+ donut: "Token donut",+ donutHint:+ "Cache reads, cache writes and output; the ring's remainder warns as usage nears the limit.",+ trend: "Cost trend",+ trendHint: "Fourteen days of cost as a line; hover a day.",+ tokens: "Token usage",+ tokensHint:+ "Daily tokens stacked by kind, with the cache-hit-rate curve over them; hover a legend entry to highlight one.",+ requests: "Requests and success rate",+ requestsHint: "Daily requests stacked by agent, each with its success-rate line.",+ agents: ["docs-expert", "release-notes"],+ activity: "Activity sparkline",+ activityHint:+ "The agent card's fourteen-day session count curve; relative ups and downs only.",+ sparkline: "Score sparkline",+ sparklineHint: "One benchmark's scores over its runs, the newest marked.",+ timeline: "Trace timeline",+ timelineHint:+ "One Task's model segments and tool calls: thinking, reply, tool-call generation, approval wait and execution, each in its lane.",+ },+ avatars: {+ user: "User avatar",+ agent: "Agent avatar",+ userNames: ["admin", "Demo admin"],+ agents: [+ { id: "docs-expert", name: "Docs Expert" },+ { id: "release-notes", name: "Release Notes" },+ { id: "qa", name: "QA" },+ ],+ },+ files: {+ tree: "File tree",+ treeLabel: "Workspace",+ browser: "File browser",+ header: "docs-expert",+ emptyPreview: "Pick a file on the left to preview it.",+ emptyDir: "Empty directory",+ readme:+ "# Docs Expert\n\nBuilds a BM25 index over `corpus/` and answers questions about the Claude Code docs.\n\n- `src/rag.ts` — retrieval\n- `test/` — cases",+ },+ },+};diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.tsnew file mode 100644index 00000000..12dfce7d--- /dev/null+++ b/packages/ui-gallery/src/strings.ts@@ -0,0 +1,701 @@+/**+ * Gallery chrome copy (bilingual): this file holds the Chinese dictionary `zh` and the+ * `GalleryStrings` shape; the English dictionary lives in strings-en.ts. These strings are the+ * gallery's own and never reach the product. Theme display names are per language (通用 / 白领 /+ * 极客 here, Primer / Frost / Console in English) and so are breadcrumbs; theme ids, token names,+ * accent preset ids and font names stay English in both.+ *+ * `surfaces` names the app's surfaces the gallery frames (src/app/surfaces.ts) and `library`+ * the component library's topics (src/library/topics.ts), in both dictionaries; a test checks+ * each covers every id.+ */+import type { HookName, ThemeId, ToneName } from "@prismshadow/penguin-ui";+import type { TextSize } from "@prismshadow/penguin-ui/boot";+import type { SurfaceGroupId, SurfaceId } from "./app/surfaces";+import type { ChartToken } from "./library/chart-tokens";+import type { TopicGroupId, TopicId } from "./library/topics";++/** What a surface page says: its title, one line on what the frame shows, and how the app reaches it. */+export interface SurfaceCopy {+ title: string;+ description: string;+ /** Where the surface sits in the app, for a reader who wants to find it themselves. */+ how: string;+}++export const zh = {+ brand: {+ title: "Penguin UI",+ },+ /** The top bar's page links, the left nav, the "on this page" list and the phone drawer. */+ site: {+ home: "首页",+ surfaces: "界面",+ foundations: "基础",+ fonts: "字体",+ pages: "页面",+ search: "搜索界面",+ searchShortcut: "Ctrl K",+ noMatches: "没有匹配的界面。",+ nav: "界面列表",+ onThisPage: "本页目录",+ settings: "显示设置",+ menu: "打开菜单",+ closeMenu: "关闭菜单",+ notFound: (id: string) => `没有名为「${id}」的页面。`,+ allSurfaces: "全部界面",+ feedbackTitle: "反馈",+ feedbackBody: "引用预览工具条末尾的路径,或用链接按钮复制这一页的地址。",+ feedbackExample: "白领 › 对话 · 深色",+ },+ /** The surface groups (src/app/surfaces.ts): the index's headings, the nav's eyebrows, a page's eyebrow. */+ surfaceGroups: {+ conversation: "对话",+ workbench: "工作台",+ resources: "资源",+ measure: "度量",+ system: "系统",+ } as Record<SurfaceGroupId, string>,+ surfaces: {+ chat: {+ title: "对话",+ description:+ "一次完成的任务:思考、三次工具调用、一处差异、一段带表格与代码的 Markdown 回答。",+ how: "侧栏 › 会话列表中的任意一行。",+ },+ "chat-running": {+ title: "对话 · 工具运行中",+ description: "任务进行中:一条命令正在执行,工具行显示运行状态与计时。",+ how: "侧栏 › 带运行标记的会话行。",+ },+ "chat-thinking": {+ title: "对话 · 思考中",+ description: "任务进行中:模型正在思考,思考行显示运行状态,文字仍在增长。",+ how: "侧栏 › 带运行标记的会话行。",+ },+ "chat-approval": {+ title: "对话 · 待审批",+ description: "任务等待人工:一条命令需要批准,允许或拒绝之后任务继续并结束。",+ how: "侧栏 › 带审批标记的会话行。",+ },+ "chat-new": {+ title: "新对话",+ description: "草稿页:选择智能体、工作区、审批模式与模型,输入并发送第一条消息。",+ how: "侧栏 › 新对话。",+ },+ agents: {+ title: "智能体",+ description: "智能体列表:每个智能体的活动曲线、会话数、工具、Skill 与定时任务计数。",+ how: "侧栏 › 智能体。",+ },+ "agent-settings": {+ title: "智能体设置",+ description:+ "一个智能体的设置页:概览、提示词、记忆、运行时、工具、Skill、钩子、Vault 与定时任务标签页。",+ how: "智能体 › 任意一个智能体。",+ },+ schedules: {+ title: "定时任务",+ description: "智能体设置的定时任务标签页:周期、下次触发、绑定的会话与模型。",+ how: "智能体 › 智能体设置 › 定时任务标签页。",+ },+ plugins: {+ title: "插件市场",+ description: "插件库按分类列出,带搜索与筛选;已安装的 Skill 与钩子按智能体显示。",+ how: "侧栏 › 插件市场。",+ },+ "plugin-detail": {+ title: "插件详情",+ description: "一个插件的详情页:说明、它带来的 Skill、文件浏览器与安装入口。",+ how: "插件市场 › 任意一个插件。",+ },+ models: {+ title: "模型库",+ description: "按供应商分组的模型表:默认模型、凭据、价格、上下文窗口与用量。",+ how: "侧栏 › 模型库。",+ },+ machines: {+ title: "机器",+ description: "本机与远程机器:安装状态、连接、探测结果,以及添加 ssh 主机。",+ how: "侧栏 › 机器(仅管理员)。",+ },+ usage: {+ title: "成本中心",+ description:+ "三十天的用量:Token、花费、请求数与成功率,按日期、智能体、模型或会话分组,附错误面板。",+ how: "侧栏 › 成本中心。",+ },+ benchmark: {+ title: "评估中心",+ description: "评估任务列表:已发布与草稿状态、用例数、历次评估的分数走势。",+ how: "侧栏 › 评估中心。",+ },+ "benchmark-detail": {+ title: "评估详情",+ description: "一个评估任务:分数曲线、每轮评估的用例得分、用例的题面与评分标准文件。",+ how: "评估中心 › 任意一个评估任务。",+ },+ settings: {+ title: "设置",+ description:+ "设置对话框:个人资料、通用、外观(主题、明暗、强调色、字号、字体)、账户,以及服务器设置。",+ how: "侧栏底部的账户菜单 › 设置。",+ },+ "settings-appearance": {+ title: "外观设置",+ description:+ "设置对话框停在「外观」页:主题、明暗、强调色、五档字号与字体组合——主题切换就在这里。",+ how: "侧栏底部的账户菜单 › 设置 › 外观。",+ },+ login: {+ title: "登录",+ description: "登录页:装饰画布上的登录卡片。任意密码即可登录演示账户。",+ how: "未登录时的任意地址。",+ },+ } as Record<SurfaceId, SurfaceCopy>,+ home: {+ eyebrow: "界面画廊",+ title: "Penguin UI",+ lead: "真实的 Web App,在三套主题、两种明暗、五档字号、可选字体组合与两种语言下运行——数据来自浏览器内的演示接口,可以随意点击。",+ app: "应用",+ appLead:+ "这就是应用本身:侧栏、各个中心、对话与设置都能点开。主题与字号等控件作用于框内的应用;发送消息会得到一段脚本回复。",+ index: "界面索引",+ indexLead: "每个界面一页:应用停在该界面上,切换主题、字号与字体即可查看。",+ library: "组件库",+ libraryLead: "真实的 Web 组件,按类别各一页,在当前主题、明暗、字号与字体下渲染,可以操作。",+ fonts: "字体",+ fontsLead: "每个主题的默认字体、当前选择、字样与许可。",+ },+ /**+ * The view controls' copy, in the top bar; the key keeps the name of the rail that held them,+ * which the Foundations boards read (`S.rail.langNames`).+ */+ rail: {+ theme: "主题",+ themeNames: { github: "通用", modern: "白领", geek: "极客" } as Record<ThemeId, string>,+ mode: "明暗",+ accent: "强调色",+ accentTheme: "随主题",+ size: "字号",+ sizeNames: { xs: "特小", s: "小", m: "中", l: "大", xl: "特大" } as Record<TextSize, string>,+ sizeTitle: (name: string, px: number) => `${name} · 根字号 ${px}px`,+ fontLatin: "英文字体",+ fontCjk: "中文字体",+ fontTheme: "随主题",+ fontSystem: "系统",+ language: "语言",+ viewport: "视口",+ viewports: { desktop: "桌面", phone: "手机" },+ langNames: { en: "EN", zh: "中文" },+ modes: { light: "浅色", dark: "深色", system: "跟随系统" },+ },+ /** The current fonts, read from the framed app: the role labels before each family. */+ readout: {+ label: "当前字体",+ latin: "英文",+ cjk: "中文",+ mono: "等宽",+ system: "系统",+ pending: "读取中…",+ },+ /** The breadcrumb's own words; everything else in it is a name from elsewhere. */+ crumb: {+ modes: { light: "浅色", dark: "深色" },+ phone: "手机",+ },+ intro: {+ resolving: "正在解析令牌…",+ },+ /** A framed app's toolbar and captions. */+ frame: {+ open: "单独打开",+ reload: "重新载入",+ frameOf: (theme: string) => `${theme} 下的应用`,+ how: "在应用里的位置",+ route: "路由",+ signedOut: "未登录",+ },+ section: {+ copyLink: "复制链接",+ copyBreadcrumb: "复制路径",+ unset: "未定义",+ },+ foundations: {+ surfaces: "表面",+ inks: "文字",+ lines: "线条",+ inkWords: ["正文", "次要", "弱化"] as readonly string[],+ accent: "强调色",+ presetsHint: "主题自带的强调色,与当前主题列出的五个预设;别的主题的预设在这里不生效",+ themeAccent: "主题",+ sampleSend: "发送",+ selectedRow: "选中",+ sampleLink: "打开文档",+ linkHover: "悬停",+ tones: "语义色调",+ toneWords: {+ success: "运行中",+ attention: "等待中",+ danger: "失败",+ done: "已完成",+ neutral: "空闲",+ info: "同步中",+ } as Record<ToneName, string>,+ charts: "图表序列",+ tokenSeries: "Token 构成",+ code: "代码与差异",+ codeLines: {+ before: "const hits = rank(q).slice(0, ",+ removed: "3",+ added: "6",+ after: ");",+ selected: "return cite(hits);",+ },+ typeNote: "每一行都用各自角色的令牌排版;中文列显示主题字体如何排中文与夹在其中的拉丁文字。",+ scene: {+ pageTier: "页面",+ cardTitle: "Docs Expert",+ cardMeta: "3 个会话 · $0.0231",+ nested: "内层方框的圆角 = 外层圆角 − 内边距",+ primary: "保存",+ secondary: "取消",+ input: "搜索会话",+ badge: "运行中",+ menuTier: "z-[60] 菜单",+ menuItems: ["置顶", "重命名", "移动到…"] as readonly string[],+ backdropTier: "z-50 对话框",+ dialogTitle: "删除这个会话?",+ dialogBody: "对话记录与 Trace 文件会一并删除。",+ cancel: "取消",+ confirm: "删除",+ toastTier: "z-[100] 通知",+ toast: "已导出 Trace #001",+ },+ radius: "圆角",+ shadows: "阴影层级",+ spacingPage: {+ title: "设置",+ appearance: "外观",+ theme: "主题",+ themeOptions: ["浅色", "深色", "跟随系统"] as readonly string[],+ fontSize: "字号",+ sizeOptions: ["特小", "小", "中", "大", "特大"] as readonly string[],+ general: "通用",+ language: "语言",+ languageOptions: ["中文", "English"] as readonly string[],+ notifications: "完成时通知",+ },+ stack0Note: "stack-0:图标与文字之间的窄条",+ controlHeights: "控件高度(实测)",+ iconSizes: "图标尺寸",+ iconRegistry: (icons: number, files: number) => `${icons} 个图标,来自 ${files} 个文件`,+ duplicateNames: "同一路径的多个名字",+ durations: "时长 × 缓动",+ reducedNote: "已减弱动效:每个变化直接呈现终态。",+ liveSignal: "实时信号",+ loading: "加载中",+ focusRing: "焦点环",+ inputFocus: "输入框焦点",+ selection: "选区",+ scrollbar: "滚动条",+ spaceUnit: "间距单位",+ spaceUnitNote: "所有间距与尺寸工具类都是它的倍数:h-8 即八个单位。",+ shell: "外壳",+ shellNote: "经 .ui-shell 的应用窗口:底场、导航列与主列,各主题自行决定它们的关系。",+ presence: "进出",+ presenceNote: "菜单自上方、对话框自中心、通知自下方进出,各按当前主题的进出令牌。",+ reveal: "显现",+ revealNote: "流式文本逐块显现,每一块只在出现时按显现令牌动一次。",+ layout: "布局",+ layoutNote: "侧栏在展开与图标栏之间的宽度变化,按布局令牌。",+ replay: "重放",+ replayAll: "全部重放",+ motionSpecimens: {+ menu: "菜单",+ dialog: "对话框",+ toast: "通知",+ trigger: "更多",+ sidebarRows: ["新对话", "智能体", "模型库"] as readonly string[],+ },+ hookJobs: {+ "ui-glass": "盖在内容之上的临时层",+ "ui-eyebrow": "为下方一组条目命名的分组标签",+ "ui-display": "页面或主视觉唯一的展示标题",+ "ui-live": "正在进行之物的动效",+ "ui-frame": "带头部、主体、底部与窗格的细线框",+ "ui-underline-nav": "标签栏中选中项的标记",+ "ui-shell": "应用窗口:导航列与主列",+ "ui-icon-decor": "标签已经说明了的图标:主题可以着色或不画",+ "ui-tree": "行会嵌套的列表:文件树、工作组的工具行、子 Agent 调用图",+ "ui-field": "带标签的控件行:表单字段或设置行",+ "ui-activity": "正在工作的思考行或工具行:运行中、已完成或出错",+ "ui-notice": "提示条与弹出通知:按语气(信息、成功、警告、错误、中性)着色",+ "ui-chart": "统计图:网格、坐标轴、折线、面积、柱与数据点",+ "ui-scrim": "对话框、抽屉与面板背后的遮罩层",+ } as Record<HookName, string>,+ hookSamples: {+ menu: ["置顶", "重命名", "删除"] as readonly string[],+ group: "工作区",+ rows: ["claude-code-expert", "docs-sync", "release-notes"] as readonly string[],+ copy: "复制",+ tabs: ["概览", "轨迹", "文件"] as readonly string[],+ streaming: "正在写回答",+ tree: {+ root: "claude-code-expert",+ dir: "src",+ files: ["rag.ts", "embed.ts"] as readonly string[],+ last: "README.md",+ },+ field: {+ name: "名称",+ value: "Docs Expert",+ hint: "在侧栏与消息中显示的名字。",+ notify: "完成时通知",+ notifyHint: "Task 结束时弹出系统通知。",+ },+ },+ },+ fonts: {+ title: "字体",+ pages: { defaults: "默认字体", specimens: "字样", licences: "许可" },+ defaultsTitle: "默认字体",+ defaultsHint:+ "每个主题各角色的默认字体:英文(正文与界面)、中文与等宽。「系统字体」指交给平台决定。",+ system: "系统字体",+ current: "当前选择",+ currentHint: "顶栏里选定的字体组合;「随主题」即上表中当前主题的一行。实际渲染的字体见下一行。",+ followsTheme: (theme: string) => `随主题(${theme})`,+ specimensTitle: "字样",+ licencesTitle: "许可",+ specimens: "字样",+ specimensHint: "每个主题的字体族,在五档字号(14 / 15 / 16 / 18 / 20 px)下各排一段中英文。",+ declared: "已声明的字体",+ declaredHint:+ "页面样式表中的 @font-face,按字体族、字重与样式合并;只有文本用到某个分片时浏览器才会下载它。",+ noFaces: "尚未声明任何字体。",+ family: "字体族",+ weight: "字重",+ slicesColumn: "分片",+ loadStatus: "加载情况",+ licences: "许可文本",+ noLicences: "还没有许可文本。",+ status: { loaded: "已加载", unloaded: "未使用", loading: "加载中", error: "失败" },+ },+ /** The component library: its topics, and the words each board prints. */+ library: {+ title: "组件库",+ groups: { components: "组件", foundations: "视觉基础" } as Record<TopicGroupId, string>,+ topics: {+ buttons: { title: "按钮", description: "四种变体、两档尺寸与图标按钮,以及禁用与进行中。" },+ inputs: {+ title: "输入与表单",+ description: "文本框、多行文本、密码框与字段脚手架:标签、提示、说明与错误。",+ },+ pickers: { title: "选择器", description: "下拉选择、分段控件、开关、选项菜单与下拉菜单。" },+ toasts: {+ title: "提示弹窗",+ description: "完成操作后的弹出提示:成功、信息、注意与错误,按按钮触发。",+ },+ notices: { title: "提示条", description: "占据一行的提示:每种语气,带与不带操作。" },+ dialogs: { title: "对话框", description: "模态对话框、确认框、抽屉与底部面板。" },+ tooltips: {+ title: "悬停提示",+ description: "悬停与聚焦时出现的提示:data-tooltip 属性与 Tooltip 组件。",+ },+ tabs: { title: "标签页", description: "下划线式标签切换,可带更新标记。" },+ badges: {+ title: "徽标与状态",+ description: "徽标、运行状态图标、会话活动标记与更新点。",+ },+ empty: { title: "空状态", description: "列表或详情为空时的占位文字,可带操作。" },+ loading: { title: "加载", description: "转圈与骨架屏。" },+ charts: {+ title: "图表",+ description:+ "统计图的基础:所有图表共用的绘图原语、当前主题的图表令牌,以及建立在它们之上的每一种图表——环形图、趋势与用量柱、请求与成功率、活动与评分折线、轨迹时间线。",+ },+ avatars: { title: "头像", description: "用户头像与智能体头像的各个尺寸。" },+ files: { title: "文件", description: "文件树与只读文件浏览器。" },+ colour: {+ title: "颜色",+ description: "表面、文字、线条、强调色、语义色调、图表序列与代码色。",+ },+ type: { title: "字体排印", description: "各角色的字号、行高与字重。" },+ shape: { title: "形状", description: "圆角、阴影层级与嵌套。" },+ density: { title: "密度", description: "间距单位与控件高度。" },+ focus: { title: "焦点", description: "焦点环、输入框焦点、选区与滚动条。" },+ motion: { title: "动效", description: "进出、显现、布局与时长缓动。" },+ icons: { title: "图标", description: "图标尺寸与 Web App 的图标表。" },+ hooks: { title: "样式钩子", description: "主题可以重绘的结构钩子,逐个示范。" },+ } as Record<TopicId, { title: string; description: string }>,+ buttons: {+ variants: "变体",+ primary: "保存",+ secondary: "取消",+ danger: "删除",+ ghost: "更多",+ sizes: "尺寸",+ md: "默认尺寸",+ sm: "小尺寸",+ icon: "图标按钮",+ states: "状态",+ disabled: "已禁用",+ busy: "保存中…",+ },+ inputs: {+ basics: "文本框",+ name: "名称",+ namePlaceholder: "Docs Expert",+ nameHint: "在侧栏与消息中显示的名字。",+ email: "邮箱",+ emailValue: "zheng@example",+ emailError: "邮箱地址不完整。",+ required: "必填",+ info: "带说明",+ infoText: "改动在下一次 Task 开始时生效。",+ sizes: "尺寸",+ base: "基础尺寸",+ small: "表单尺寸",+ textarea: "多行文本",+ textareaPlaceholder: "写一段系统提示…",+ mono: "等宽",+ monoValue: "temperature: 0.2\nmax_tokens: 4096",+ password: "密码",+ passwordHint: "至少 12 个字符。",+ },+ pickers: {+ select: "下拉选择",+ selectLabel: "模型",+ options: ["DeepSeek V4.1 Flash", "Claude Sonnet 4.5", "GLM-5.3"] as readonly string[],+ segmented: "分段控件",+ segments: ["浅色", "深色", "跟随系统"] as readonly string[],+ switches: "开关",+ switchLabel: "完成时通知",+ switchHint: "Task 结束时弹出系统通知。",+ switchOff: "工具短名",+ optionMenu: "选项菜单",+ optionLabel: "权限",+ choices: [+ { value: "r", trigger: "r", label: "只读", description: "只能读取工作区。" },+ { value: "rw", trigger: "rw", label: "读写", description: "可以修改工作区里的文件。" },+ { value: "ask", trigger: "ask", label: "逐项审批", description: "每次写入前先询问。" },+ ] as readonly { value: string; trigger: string; label: string; description: string }[],+ dropdown: "下拉菜单",+ menu: "更多操作",+ menuItems: ["置顶", "重命名", "移动到…", "删除"] as readonly string[],+ },+ toasts: {+ fire: "触发一条提示",+ hint: "提示出现在页面顶部,几秒后自动消失;错误与注意会停留更久。",+ success: "成功",+ info: "信息",+ attention: "注意",+ error: "错误",+ successText: "已保存。",+ infoText: "索引正在后台重建。",+ attentionText: "已保存,但有 2 个字段被截断。",+ errorText: "连接失败:无法访问 api.example。",+ },+ notices: {+ plain: "每种语气",+ dotted: "带前导标记",+ withActions: "带操作",+ texts: {+ link: "新版本 0.3.0 可用。",+ success: "索引已重建,共 214 个文件。",+ busy: "正在同步语料库…",+ attention: "有 1 条未预期错误。",+ danger: "模型返回 401:密钥无效。",+ muted: "这个会话已归档。",+ },+ action: "查看",+ dismiss: "忽略",+ },+ dialogs: {+ modal: "模态对话框",+ openModal: "打开对话框",+ modalTitle: "重命名会话",+ modalBody: "新的名字会显示在侧栏与消息里。",+ save: "保存",+ cancel: "取消",+ confirm: "确认框",+ openConfirm: "删除会话…",+ confirmTitle: "删除这个会话?",+ confirmBody: "对话记录与 Trace 文件会一并删除,无法恢复。",+ confirmLabel: "删除",+ drawer: "抽屉",+ openDrawer: "打开抽屉",+ drawerTitle: "导航",+ drawerBody: "手机宽度下的侧栏从边缘滑入。",+ sheet: "底部面板",+ openSheet: "打开底部面板",+ sheetTitle: "文件",+ sheetBody: "向上拖动展开到整屏,向下拖动关闭。",+ },+ tooltips: {+ attribute: "data-tooltip 属性",+ attributeHint: "任何元素加上属性即可;只有图标的按钮同时带 aria-label。",+ component: "Tooltip 组件",+ componentHint: "需要包裹时使用:右侧或下方摆放。",+ truncated: "被截断的文本",+ truncatedHint: "行里放不下的命令或标题,完整内容放进提示里。",+ edit: "编辑",+ copy: "复制",+ settings: "设置",+ beside: "右侧",+ below: "下方",+ command:+ "pnpm --filter @prismshadow/penguin-web exec vitest run test/session-activity.test.ts --reporter verbose",+ },+ tabs: {+ basic: "标签切换",+ badged: "带更新标记",+ items: ["概览", "轨迹", "文件", "设置"] as readonly string[],+ badgeText: "有 3 个技能可更新",+ body: (tab: string) => `「${tab}」的内容。`,+ },+ badges: {+ badges: "徽标",+ tones: {+ gray: "默认",+ brand: "来源",+ green: "运行中",+ amber: "已中止",+ red: "失败",+ },+ status: "运行状态",+ states: {+ running: "运行中",+ waiting: "等待审批",+ done: "已完成",+ failed: "失败",+ stopped: "已停止",+ },+ activity: "会话活动",+ activities: { running: "运行中", compacting: "压缩中", completedUnread: "有未读回复" },+ marks: "其他标记",+ background: "后台任务",+ schedule: "定时任务",+ dot: "更新点",+ dotAnchor: "插件市场",+ pill: "更新提示",+ pillText: "3 个可更新",+ },+ empty: {+ page: "页面空状态",+ title: "还没有会话",+ description: "发送第一条消息后,会话会出现在这里。",+ action: "新对话",+ settings: "设置区空状态",+ settingsText: "还没有添加任何 MCP 服务器。",+ },+ loading: {+ spinner: "转圈",+ sizes: "三档尺寸",+ skeleton: "骨架屏",+ list: "列表",+ card: "卡片",+ },+ charts: {+ parts: {+ primitives: "绘图原语",+ primitivesHint:+ "每个图表都只通过这几个原语落笔:它们读取主题的图表令牌,写出 data-part,是令牌变成 SVG 或 HTML 的唯一地方。",+ tokens: "当前主题的图表令牌",+ tokensHint: "从这个框的根元素的计算样式读取;换主题、明暗或强调色后重新读取。",+ charts: "建立在原语上的图表",+ chartsHint: "应用里的每一种图表,使用演示数据。",+ },+ primitives: {+ bar: "ChartBar · 柱",+ barHint: "宽度由 bar-fill 决定,顶角圆角、边框与填充不透明度各按令牌。",+ line: "ChartLine · 折线",+ lineHint: "同一组点,按三种连线方式各画一次;线宽按令牌。",+ curves: { linear: "linear · 直连", smooth: "smooth · 平滑", step: "step · 阶梯" },+ area: "ChartArea · 面积",+ areaHint: "折线下方的填充,不透明度按令牌。",+ point: "ChartPoint · 数据点",+ pointHint: "半径按令牌;主题决定圆点还是方点。",+ arc: "ChartArc · 弧",+ arcHint: "环形图的一段:底环是 grid,各段按 Token 种类色或色槽。",+ grid: "ChartGrid 与 ChartAxis · 网格与坐标轴",+ gridHint: "网格线与坐标轴的墨色按令牌,主题决定实线或虚线。",+ timeline: "TimelineBar · 轨迹条",+ timelineHint: "轨迹时间线的 HTML 条,五种分段各取一个色槽。",+ kinds: {+ thinking: "思考",+ text: "回复",+ tool_call: "工具调用",+ approval: "等待审批",+ tool: "工具执行",+ },+ },+ palette: "调色板",+ geometry: "几何",+ tokenMeaning: {+ "--ui-chart-1": "色槽 1 · 紫",+ "--ui-chart-2": "色槽 2 · 琥珀",+ "--ui-chart-3": "色槽 3 · 天蓝",+ "--ui-chart-4": "色槽 4 · 玫红",+ "--ui-chart-5": "色槽 5 · 翠绿",+ "--ui-chart-6": "色槽 6 · 品红",+ "--ui-chart-7": "色槽 7 · 备用",+ "--ui-chart-8": "色槽 8 · 备用",+ "--ui-chart-ref": "参考线",+ "--ui-chart-cache-read": "缓存读取",+ "--ui-chart-cache-write": "缓存写入",+ "--ui-chart-output": "输出",+ "--ui-chart-grid": "网格线",+ "--ui-chart-axis": "坐标轴",+ "--ui-chart-bar-fill": "柱宽占带宽的比例(0–1)",+ "--ui-chart-bar-radius": "柱顶圆角",+ "--ui-chart-bar-stroke": "柱边框宽",+ "--ui-chart-bar-stroke-color": "柱边框色(series 即序列色)",+ "--ui-chart-bar-opacity": "柱填充不透明度(0–1)",+ "--ui-chart-line-width": "线宽",+ "--ui-chart-point-radius": "数据点半径",+ "--ui-chart-curve": "连线方式(linear / smooth / step)",+ "--ui-chart-area-opacity": "面积填充不透明度(0–1)",+ } as Record<ChartToken, string>,+ donut: "Token 环形图",+ donutHint: "缓存读取、缓存写入与输出的构成,环的余量随接近上限变色。",+ trend: "成本趋势",+ trendHint: "十四天的成本折线,悬停查看某一天。",+ tokens: "Token 用量",+ tokensHint: "按种类堆叠的每日 Token 柱,叠加缓存命中率曲线;悬停图例高亮一种。",+ requests: "请求与成功率",+ requestsHint: "按智能体堆叠的每日请求数,与各自的成功率线。",+ agents: ["docs-expert", "release-notes"] as readonly string[],+ activity: "活动折线",+ activityHint: "智能体卡片上的十四天会话数曲线,只看相对起伏。",+ sparkline: "评分折线",+ sparklineHint: "一个评估任务的历次得分,最新一次标出。",+ timeline: "轨迹时间线",+ timelineHint:+ "一次 Task 的模型分段与工具调用:思考、回复、工具调用、等待审批与执行,各占一道。",+ },+ avatars: {+ user: "用户头像",+ agent: "智能体头像",+ userNames: ["admin", "演示管理员"] as readonly string[],+ agents: [+ { id: "docs-expert", name: "Docs Expert" },+ { id: "release-notes", name: "Release Notes" },+ { id: "qa", name: "QA" },+ ] as readonly { id: string; name: string }[],+ },+ files: {+ tree: "文件树",+ treeLabel: "工作区",+ browser: "文件浏览器",+ header: "docs-expert",+ emptyPreview: "选择左侧的文件预览。",+ emptyDir: "空目录",+ readme:+ "# Docs Expert\n\n从 `corpus/` 建立 BM25 索引,回答关于 Claude Code 文档的问题。\n\n- `src/rag.ts` — 检索\n- `test/` — 用例",+ },+ },+};++export type GalleryStrings = typeof zh;diff --git a/packages/ui-gallery/src/styles.css b/packages/ui-gallery/src/styles.cssnew file mode 100644index 00000000..74283906--- /dev/null+++ b/packages/ui-gallery/src/styles.css@@ -0,0 +1,17 @@+/**+ * Gallery page styles. The package's theme foundation comes first, exactly as the Web App imports+ * it, so the page's own root carries the theme under test (the fonts page's specimens read it);+ * then chrome.css, the unthemed site chrome. The boards and the app render in their own framed+ * documents (src/app/app.css, src/library/library.css), which carry the app's stylesheet.+ */+@import "tailwindcss";+@import "@prismshadow/penguin-ui/theme.css";+@import "@prismshadow/penguin-ui/themes/github.css";+@import "@prismshadow/penguin-ui/themes/modern.css";+@import "@prismshadow/penguin-ui/themes/geek.css";+@import "@prismshadow/penguin-ui/fonts.css";+@import "./chrome.css";++@source "../../ui/src";+/* The test helpers spell class patterns the guards look for; they are not markup. */+@source not "../../ui/src/testing";diff --git a/packages/ui-gallery/src/text.ts b/packages/ui-gallery/src/text.tsnew file mode 100644index 00000000..15758305--- /dev/null+++ b/packages/ui-gallery/src/text.ts@@ -0,0 +1,36 @@+/**+ * The localized names every page prints: the surfaces and their groups, the library topics and+ * their groups, the theme display names, and the breadcrumb's qualifiers — all from the+ * dictionaries.+ */+import type { ThemeId } from "@prismshadow/penguin-ui";+import type { SurfaceGroupId, SurfaceId } from "./app/surfaces";+import { THEME_ACCENT } from "./lib/accents";+import type { TopicGroupId, TopicId } from "./library/topics";+import { useGallery } from "./state";+import type { SurfaceCopy } from "./strings";++export function useText(): {+ surface: (id: SurfaceId) => SurfaceCopy;+ surfaceGroup: (id: SurfaceGroupId) => string;+ topic: (id: TopicId) => { title: string; description: string };+ topicGroup: (id: TopicGroupId) => string;+ /** 通用 / 白领 / 极客, or Primer / Frost / Console. */+ theme: (id: ThemeId) => string;+ /** The breadcrumb's qualifiers: the mode word, the accent id when applied, the phone frame's word. */+ qualifiers: () => { mode: string; accent: string | undefined; view: string | undefined };+} {+ const { S, state, mode, accent } = useGallery();+ return {+ surface: (id) => S.surfaces[id],+ surfaceGroup: (id) => S.surfaceGroups[id],+ topic: (id) => S.library.topics[id],+ topicGroup: (id) => S.library.groups[id],+ theme: (id) => S.rail.themeNames[id],+ qualifiers: () => ({+ mode: S.crumb.modes[mode],+ accent: accent === THEME_ACCENT ? undefined : accent,+ view: state.view === "phone" ? S.crumb.phone : undefined,+ }),+ };+}diff --git a/packages/ui-gallery/test/accents.test.ts b/packages/ui-gallery/test/accents.test.tsnew file mode 100644index 00000000..493734f3--- /dev/null+++ b/packages/ui-gallery/test/accents.test.ts@@ -0,0 +1,56 @@+/**+ * The accent choice: the rail offers the active theme's own list after 随主题, a choice survives a+ * theme that does not list it, and the URL accepts every theme's ids and nothing else.+ */+import { THEME_ACCENT_PRESETS, THEME_IDS } from "@prismshadow/penguin-ui";+import { describe, expect, it } from "vitest";+import {+ ACCENT_IDS,+ accentPresetsOf,+ accentSwatch,+ asAccentChoice,+ resolveAccent,+ THEME_ACCENT,+} from "../src/lib/accents";+import { parseGalleryState } from "../src/lib/url-state";++describe("accent presets", () => {+ it("are each theme's own list, in its order, after the theme's own accent", () => {+ for (const theme of THEME_IDS) {+ expect(accentPresetsOf(theme)).toEqual(THEME_ACCENT_PRESETS[theme]);+ expect(accentPresetsOf(theme).length, theme).toBeGreaterThan(0);+ for (const id of accentPresetsOf(theme)) {+ expect(id, theme).toMatch(/^[a-z]+$/);+ expect(accentSwatch(theme, id), `${theme} ${id}`).toMatch(/^#[0-9a-f]{6}$/i);+ }+ }+ // Primer keeps the five the Web App has always had, so nothing there moves.+ expect(accentPresetsOf("github")).toEqual(["blue", "green", "violet", "rose", "amber"]);+ expect(ACCENT_IDS[0]).toBe(THEME_ACCENT);+ expect(new Set(ACCENT_IDS).size).toBe(ACCENT_IDS.length);+ });++ it("resolve to the preset when the active theme lists it, else to the theme's own accent", () => {+ for (const theme of THEME_IDS) {+ for (const id of accentPresetsOf(theme)) expect(resolveAccent(theme, id)).toBe(id);+ expect(resolveAccent(theme, THEME_ACCENT)).toBe(THEME_ACCENT);+ expect(resolveAccent(theme, "plaid")).toBe(THEME_ACCENT);+ }+ // A choice made under one theme comes back when the reader returns to it.+ const [first] = accentPresetsOf("github");+ const other = THEME_IDS.find((theme) => !accentPresetsOf(theme).includes(first ?? ""));+ if (other !== undefined) expect(resolveAccent(other, first ?? "")).toBe(THEME_ACCENT);+ expect(resolveAccent("github", first ?? "")).toBe(first);+ });++ it("are the values the URL accepts, whichever theme the link opens on", () => {+ for (const id of ACCENT_IDS) {+ expect(asAccentChoice(id)).toBe(id);+ for (const theme of THEME_IDS) {+ expect(parseGalleryState(`?theme=${theme}&accent=${id}`).accent).toBe(id);+ }+ }+ expect(asAccentChoice("plaid")).toBe(THEME_ACCENT);+ expect(parseGalleryState("?accent=plaid").accent).toBe(THEME_ACCENT);+ });+});diff --git a/packages/ui-gallery/test/breadcrumb.test.ts b/packages/ui-gallery/test/breadcrumb.test.tsnew file mode 100644index 00000000..b226f2f8--- /dev/null+++ b/packages/ui-gallery/test/breadcrumb.test.ts@@ -0,0 +1,65 @@+/**+ * The breadcrumb spells an address in the chrome's language: the names come in localized, and the+ * language itself needs no qualifier, since the words carry it.+ */+import { describe, expect, it } from "vitest";+import { formatBreadcrumb } from "../src/lib/breadcrumb";+import { zh } from "../src/strings";+import { en } from "../src/strings-en";++describe("formatBreadcrumb", () => {+ it("spells a surface's address: theme › surface, then the mode", () => {+ expect(+ formatBreadcrumb({+ theme: en.rail.themeNames.modern,+ page: en.surfaces.chat.title,+ mode: en.crumb.modes.dark,+ size: "m",+ }),+ ).toBe("Frost › Chat · dark");+ });++ it("reads in Chinese when the chrome does, with the theme's Chinese name", () => {+ expect(+ formatBreadcrumb({+ theme: zh.rail.themeNames.modern,+ page: zh.surfaces.chat.title,+ mode: zh.crumb.modes.dark,+ size: "m",+ }),+ ).toBe("白领 › 对话 · 深色");+ expect(zh.rail.themeNames).toEqual({ github: "通用", modern: "白领", geek: "极客" });+ expect(en.rail.themeNames).toEqual({ github: "Primer", modern: "Frost", geek: "Console" });+ });++ it("names a section of a page, the section joining the path", () => {+ expect(+ formatBreadcrumb({+ theme: "Console",+ page: "Foundations",+ section: "Colour",+ mode: "dark",+ size: "m",+ }),+ ).toBe("Console › Foundations › Colour · dark");+ });++ it("appends the accent, the root size and the phone frame only when they differ from the defaults", () => {+ expect(+ formatBreadcrumb({+ theme: "Primer",+ page: "Models",+ mode: "dark",+ accent: "amber",+ size: "xl",+ view: "phone",+ }),+ ).toBe("Primer › Models · dark · amber · 20px · phone");+ expect(+ formatBreadcrumb({ theme: "通用", page: "模型库", mode: "深色", size: "xs", view: "手机" }),+ ).toBe("通用 › 模型库 · 深色 · 14px · 手机");+ expect(formatBreadcrumb({ theme: "Primer", page: "Models", mode: "light", size: "m" })).toBe(+ "Primer › Models · light",+ );+ });+});diff --git a/packages/ui-gallery/test/chrome-controls.test.ts b/packages/ui-gallery/test/chrome-controls.test.tsnew file mode 100644index 00000000..8d362ef5--- /dev/null+++ b/packages/ui-gallery/test/chrome-controls.test.ts@@ -0,0 +1,184 @@+/**+ * The chrome's drawn controls. The gallery's vitest is node-only, so the select's keyboard and+ * placement rules are tested as the pure functions they are, and the components are held to+ * their idiom by source contract: the select is the app's — a trigger that owns a listbox, rows+ * that are options, the chosen one checked — with no native `<select>` left; hints are the+ * chrome's tooltip, with no native `title` left on anything but the frame itself.+ */+import { readdirSync, readFileSync, statSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { nextOptionIndex, placePanel, typeaheadIndex } from "../src/lib/listbox";+import { placeTip, shouldHint } from "../src/lib/tip";++const SRC = fileURLToPath(new URL("../src", import.meta.url));+const read = (rel: string) => readFileSync(path.join(SRC, rel), "utf8");+/** A source with its comments blanked, so a comment naming what was replaced is not a hit. */+const code = (file: string) =>+ readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm, "");++function walk(dir: string): string[] {+ return readdirSync(dir).flatMap((name) => {+ const full = path.join(dir, name);+ return statSync(full).isDirectory() ? walk(full) : /\.tsx$/.test(name) ? [full] : [];+ });+}++describe("the listbox keys", () => {+ it("step with the arrows and stop at the ends", () => {+ expect(nextOptionIndex("ArrowDown", 0, 3)).toBe(1);+ expect(nextOptionIndex("ArrowDown", 2, 3)).toBe(2);+ expect(nextOptionIndex("ArrowUp", 2, 3)).toBe(1);+ expect(nextOptionIndex("ArrowUp", 0, 3)).toBe(0);+ });++ it("enter the list at its first or last row when nothing is active", () => {+ expect(nextOptionIndex("ArrowDown", -1, 3)).toBe(0);+ expect(nextOptionIndex("ArrowUp", -1, 3)).toBe(2);+ });++ it("jump with Home and End, and leave every other key alone", () => {+ expect(nextOptionIndex("Home", 2, 3)).toBe(0);+ expect(nextOptionIndex("End", 0, 3)).toBe(2);+ expect(nextOptionIndex("Enter", 1, 3)).toBeNull();+ expect(nextOptionIndex("ArrowDown", 0, 0)).toBeNull();+ });++ it("jump to the next option starting with a typed character, wrapping round", () => {+ const labels = ["Theme default", "System", "Mona Sans", "MiSans", "Noto Sans SC"];+ expect(typeaheadIndex("m", labels, 0)).toBe(2);+ expect(typeaheadIndex("M", labels, 2)).toBe(3);+ expect(typeaheadIndex("m", labels, 3)).toBe(2);+ expect(typeaheadIndex("z", labels, 0)).toBeNull();+ expect(typeaheadIndex(" ", labels, 0)).toBeNull();+ expect(typeaheadIndex("Enter", labels, 0)).toBeNull();+ });+});++describe("the panel placement", () => {+ const viewport = { width: 1280, height: 800 };+ const trigger = { top: 100, bottom: 128, left: 900, width: 168 };++ it("opens under the trigger, as wide as it at least", () => {+ expect(placePanel(trigger, viewport, 160)).toEqual({ top: 132, left: 900, minWidth: 168 });+ });++ it("opens above when below lacks the room and above has more", () => {+ const low = { top: 700, bottom: 728, left: 900, width: 168 };+ expect(placePanel(low, viewport, 160)).toEqual({ bottom: 104, left: 900, minWidth: 168 });+ // Below is short but above is shorter still: it stays below.+ const high = { top: 40, bottom: 68, left: 900, width: 168 };+ expect(placePanel(high, { width: 1280, height: 200 }, 160).top).toBe(72);+ });++ it("keeps the left edge inside the viewport", () => {+ expect(placePanel({ ...trigger, left: 1200 }, viewport, 160).left).toBe(1280 - 168 - 16);+ expect(placePanel({ ...trigger, left: 4 }, viewport, 160).left).toBe(16);+ });+});++describe("the tooltip rule", () => {+ const fits = { scrollWidth: 80, clientWidth: 80, scrollHeight: 20, clientHeight: 20 };+ const cutOff = { scrollWidth: 140, clientWidth: 80, scrollHeight: 20, clientHeight: 20 };+ const wrapped = { scrollWidth: 80, clientWidth: 80, scrollHeight: 40, clientHeight: 20 };++ it("hints an icon-only element, whatever its boxes", () => {+ expect(shouldHint("", [fits])).toBe(true);+ expect(shouldHint(" \n ", [fits, fits])).toBe(true);+ expect(shouldHint("", [])).toBe(true);+ });++ it("hints text only when some box of it is cut off, sideways or downward", () => {+ expect(shouldHint("Copy breadcrumb", [fits, fits])).toBe(false);+ expect(shouldHint("Primer › Chat · dark", [fits, cutOff])).toBe(true);+ expect(shouldHint("Two lines", [wrapped])).toBe(true);+ });++ it("is what the layer asks before it opens", () => {+ const layer = read("chrome/tooltip.tsx");+ expect(layer).toMatch(+ /if \(!shouldHint\(el\.textContent \?\? "", \[el, \.\.\.el\.querySelectorAll\("\*"\)\]\)\) return;/,+ );+ });+});++describe("the tooltip placement", () => {+ const viewport = { width: 1000, height: 800 };++ it("hangs under a trigger on the left half, growing rightward", () => {+ expect(placeTip({ bottom: 40, left: 100, right: 130, width: 30 }, viewport)).toEqual({+ top: 46,+ left: 100,+ room: 1000 - 100 - 8,+ });+ });++ it("hangs under a trigger on the right half by its right edge, growing leftward", () => {+ expect(placeTip({ bottom: 40, left: 960, right: 990, width: 30 }, viewport)).toEqual({+ top: 46,+ right: 10,+ room: 1000 - 10 - 8,+ });+ });++ it("never sits closer to an edge than the margin", () => {+ expect(placeTip({ bottom: 40, left: 2, right: 20, width: 18 }, viewport).left).toBe(8);+ expect(placeTip({ bottom: 40, left: 990, right: 1000, width: 10 }, viewport).right).toBe(8);+ });+});++describe("the chrome's idiom", () => {+ const files = walk(SRC);++ it("draws its selects the app's way: a listbox trigger, option rows, the chosen one checked", () => {+ const select = read("chrome/select.tsx");+ expect(select).toMatch(/aria-haspopup="listbox"/);+ expect(select).toMatch(/role="listbox"/);+ expect(select).toMatch(/role="option"/);+ expect(select).toMatch(/aria-selected=\{option\.value === value\}/);+ expect(select).toMatch(/option\.value === value && <ChromeIcon name="check"/);+ expect(select).toMatch(/createPortal\(/);+ // The font pairings go through it, each under its visible label.+ const topbar = read("chrome/topbar.tsx");+ expect(topbar).toMatch(/<Control label=\{S\.rail\.fontLatin\}>\s*<Select/);+ expect(topbar).toMatch(/<Control label=\{S\.rail\.fontCjk\}>\s*<Select/);+ });++ it("renders no native select", () => {+ const offenders = files.filter((file) => /<select[\s>]/.test(code(file)));+ expect(offenders.map((file) => path.relative(SRC, file))).toEqual([]);+ });++ it("hints with the chrome's tooltip, never a native title, except on the frame", () => {+ const offenders = files.flatMap((file) => {+ // A `title=` on an intrinsic element; `title={title}` on a component is a prop.+ return [...code(file).matchAll(/<([a-z][\w-]*)\b[^>]*?\stitle=/gs)]+ .filter((m) => m[1] !== "iframe")+ .map((m) => `${path.relative(SRC, file)}: <${m[1]}>`);+ });+ expect(offenders).toEqual([]);+ expect(read("chrome/site.tsx")).toMatch(/<ChromeTooltips \/>/);+ expect(read("chrome/tooltip.tsx")).toMatch(/TOOLTIP_ATTR = "data-tooltip"/);+ });++ it("marks a copy as done on the icon alone, never by swapping the text", () => {+ for (const file of ["chrome/crumb.tsx", "pages/surface.tsx", "pages/library.tsx"]) {+ const source = read(file);+ expect(source).toMatch(/copied[^\n]*\? "check" :/);+ expect(source).not.toMatch(/copied\b[^\n]*\? S\./);+ }+ expect(read("strings.ts")).not.toMatch(/\bcopied:/);+ });++ it("keeps the bar to one row, with the menu button for phone width only", () => {+ const css = read("chrome.css");+ expect(css).toMatch(/\.g-topbar \{[^}]*height: var\(--g-bar\)/s);+ expect(css).not.toMatch(/\.g-topbar \{[^}]*flex-wrap/s);+ // The hiding rule carries the bar's selector, so the generic icon-button rule cannot outrank it.+ expect(css).toMatch(/\.g-topbar \.g-menu \{\s*display: none;\s*\}/);+ expect(css).toMatch(+ /@media \(max-width: 900px\) \{[\s\S]*\.g-topbar \.g-menu \{\s*display: inline-grid/,+ );+ });+});diff --git a/packages/ui-gallery/test/chrome-untouched.test.ts b/packages/ui-gallery/test/chrome-untouched.test.tsnew file mode 100644index 00000000..b78fa394--- /dev/null+++ b/packages/ui-gallery/test/chrome-untouched.test.ts@@ -0,0 +1,38 @@+/**+ * The gallery is judged by what changes when the theme under test changes, so nothing it renders+ * itself may follow Tailwind's palette or the `dark:` variant: the chrome reads its own `--g-*`+ * variables and the Foundations pages read `--ui-*` tokens. A `gray-*` class or a `dark:` variant+ * here would move with the theme bridge and muddy every comparison.+ */+import { readdirSync, readFileSync, statSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const SRC = fileURLToPath(new URL("../src", import.meta.url));++function walk(dir: string): string[] {+ return readdirSync(dir).flatMap((name) => {+ const full = path.join(dir, name);+ return statSync(full).isDirectory() ? walk(full) : /\.(tsx?|css)$/.test(name) ? [full] : [];+ });+}++describe("gallery sources stay off the palette the themes re-point", () => {+ const files = walk(SRC);++ it("scans a non-empty tree", () => {+ expect(files.length).toBeGreaterThan(20);+ });++ it("uses no gray-* class and no dark: variant", () => {+ // A variant is `dark:` glued to a utility; `{ dark: true }` and `dark: "深色"` are not.+ const offenders = files.flatMap((file) => {+ const text = readFileSync(file, "utf8");+ return [...text.matchAll(/\b(?:[a-z-]+-)?gray-\d{2,3}\b|\bdark:[a-z[!-]/g)].map(+ (m) => `${path.relative(SRC, file)}: ${m[0]}`,+ );+ });+ expect(offenders).toEqual([]);+ });+});diff --git a/packages/ui-gallery/test/color.test.ts b/packages/ui-gallery/test/color.test.tsnew file mode 100644index 00000000..9faf6046--- /dev/null+++ b/packages/ui-gallery/test/color.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { composite, contrastRatio, parseCssColor, toHex, wcagGrade } from "../src/lib/color";++describe("colour maths", () => {+ it("parses hex and rgb() in both syntaxes", () => {+ expect(parseCssColor("#fff")).toEqual({ r: 255, g: 255, b: 255, a: 1 });+ expect(parseCssColor("#0d0d0d")).toEqual({ r: 13, g: 13, b: 13, a: 1 });+ expect(parseCssColor("#00000080")?.a).toBeCloseTo(128 / 255);+ expect(parseCssColor("rgb(0 0 0 / 0.45)")).toEqual({ r: 0, g: 0, b: 0, a: 0.45 });+ expect(parseCssColor("rgba(37, 99, 235, 0.12)")).toEqual({ r: 37, g: 99, b: 235, a: 0.12 });+ expect(parseCssColor("transparent")?.a).toBe(0);+ expect(parseCssColor("oklch(50% 0.1 20)")).toBeNull();+ });++ it("computes WCAG ratios", () => {+ const white = parseCssColor("#ffffff")!;+ const black = parseCssColor("#000000")!;+ expect(contrastRatio(white, black)).toBeCloseTo(21, 5);+ expect(contrastRatio(black, white)).toBeCloseTo(21, 5);+ // Tailwind gray-500 on white: the app's muted text.+ expect(contrastRatio(parseCssColor("#6a7282")!, white)).toBeCloseTo(4.83, 1);+ expect(wcagGrade(7.1)).toBe("AAA");+ expect(wcagGrade(4.5)).toBe("AA");+ expect(wcagGrade(3.2)).toBe("AA large");+ expect(wcagGrade(2.9)).toBe("fail");+ });++ it("composites a translucent ink over its backdrop", () => {+ const mixed = composite({ r: 0, g: 0, b: 0, a: 0.5 }, { r: 255, g: 255, b: 255, a: 1 });+ expect(toHex(mixed)).toBe("#808080");+ expect(toHex({ r: 17, g: 24, b: 39, a: 0.5 })).toBe("#11182780");+ });+});diff --git a/packages/ui-gallery/test/demo-store.test.ts b/packages/ui-gallery/test/demo-store.test.tsnew file mode 100644index 00000000..59800510--- /dev/null+++ b/packages/ui-gallery/test/demo-store.test.ts@@ -0,0 +1,215 @@+/**+ * The demo store: the same world in both languages, models the built-in catalog knows, the+ * running states the gallery exists to show, and the scripts that move them — a sent message+ * streams a reply and settles, an approval decides the pending command, an abort stops a run.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import type { ServerEvent } from "@prismshadow/penguin-server/api";+import { catalogEntryFor } from "../../core/dist/state/model-catalog.js";+import { catalogDelta } from "../../web/src/features/models/catalog-sync";+import { buildFixtures } from "../src/app/mock/fixtures";+import { ALL_SESSION_IDS, IDS } from "../src/app/mock/ids";+import { resetStore } from "../src/app/mock/store";+import { TOOL_CALL_IDS } from "../src/app/mock/transcripts";+import { payloadOf } from "../src/app/mock/types";+import type { OmniMessage, StreamHandlers } from "../src/app/mock/types";++const NOW = Date.parse("2026-09-29T08:00:00Z");++/** The dataset's shape with every string and number reduced to its type (a file's size follows its text), so the two languages compare. */+function shape(value: unknown): unknown {+ if (typeof value === "string") return "string";+ if (typeof value === "number") return "number";+ if (Array.isArray(value)) return value.map(shape);+ if (value !== null && typeof value === "object") {+ return Object.fromEntries(+ Object.entries(value)+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))+ .map(([k, v]) => [k, shape(v)]),+ );+ }+ return value;+}++/** A message's payload type, the session_meta record reading as its own kind. */+const typeOf = (m: OmniMessage): string => payloadOf(m)?.type ?? "session_meta";++/** A subscriber that keeps what it is sent. */+function collector(): StreamHandlers & { messages: OmniMessage[]; events: ServerEvent[] } {+ const messages: OmniMessage[] = [];+ const events: ServerEvent[] = [];+ return {+ messages,+ events,+ onOmniMessage: (msg) => messages.push(msg),+ onServerEvent: (ev) => events.push(ev),+ };+}++describe("the fixtures", () => {+ it("hold the same structure and the same ids in both languages", () => {+ const en = buildFixtures("en", NOW);+ const zh = buildFixtures("zh", NOW);+ expect(shape({ ...en, lang: "x" })).toEqual(shape({ ...zh, lang: "x" }));+ expect(en.sessions.map((s) => s.sessionId)).toEqual(zh.sessions.map((s) => s.sessionId));+ expect(en.agents.map((a) => a.agentId)).toEqual(zh.agents.map((a) => a.agentId));+ expect(en.benchmarks.map((b) => b.id)).toEqual(zh.benchmarks.map((b) => b.id));+ // Prose in the language it claims.+ const han = /[一-鿿]/;+ expect(han.test(zh.agents[0]!.name!)).toBe(true);+ expect(han.test(en.agents[0]!.name!)).toBe(false);+ });++ it("seed every Session id the ids module lists, and no other", () => {+ const f = buildFixtures("en", NOW);+ expect(f.sessions.map((s) => s.sessionId).sort()).toEqual([...ALL_SESSION_IDS].sort());+ expect(+ f.sessions+ .filter((s) => s.status === "running")+ .map((s) => s.sessionId)+ .sort(),+ ).toEqual([IDS.sessions.approval, IDS.sessions.runningTool, IDS.sessions.thinking].sort());+ });++ it("carry the whole built-in catalog, settled: the app's sync check finds nothing to add or update", () => {+ const f = buildFixtures("en", NOW);+ for (const m of f.models.models) {+ if (m.provider === "custom") continue;+ expect(catalogEntryFor(m.provider, m.modelId), `${m.provider}/${m.modelId}`).toBeDefined();+ }+ expect(f.models.models.length).toBeGreaterThan(100);+ expect(catalogDelta(f.models.models)).toEqual({ added: 0, updated: 0, refs: [] });+ expect(f.models.defaultModel).toEqual({ provider: "deepseek", modelId: "deepseek-flash" });+ expect(f.models.models.filter((m) => m.isDefault).map((m) => m.modelId)).toEqual([+ "deepseek-flash",+ ]);+ for (const s of f.sessions)+ expect(f.models.models.some((m) => m.modelId === s.modelId)).toBe(true);+ });++ it("carry thirty days of usage in both Agents' names", () => {+ const f = buildFixtures("en", NOW);+ expect(new Set(f.usage.map((d) => d.date)).size).toBe(30);+ expect(new Set(f.usage.map((d) => d.agentId))).toEqual(+ new Set([IDS.agents.docs, IDS.agents.notes]),+ );+ });+});++describe("the running states", () => {+ it("a tool call executing: its call is in the history, its output is not, and the Session runs", () => {+ const store = resetStore({ lang: "en", signedIn: true, now: NOW });+ const transcript = store.transcript(IDS.sessions.runningTool)!;+ const calls = transcript.history.filter((m) => typeOf(m) === "tool_call");+ const outputs = transcript.history.filter((m) => typeOf(m) === "tool_call_output");+ expect(calls.length).toBe(outputs.length + 1);+ expect(transcript.running).toBe(true);+ expect(store.liveTail(IDS.sessions.runningTool)).toEqual({ cursor: "g1-0", fragments: [] });+ });++ it("thinking mid-stream: the live tail carries the open fragment, and the stream keeps adding to it", () => {+ vi.useFakeTimers();+ const store = resetStore({ lang: "zh", signedIn: true, now: NOW });+ const tail = store.liveTail(IDS.sessions.thinking)!;+ expect(tail.fragments).toHaveLength(1);+ expect(tail.fragments[0]!.payload).toMatchObject({+ type: "partial_thinking",+ event_type: "start",+ });+ const sub = collector();+ store.channel(IDS.sessions.thinking)!.subscribe(sub);+ store.onSubscribe(IDS.sessions.thinking, sub);+ expect(sub.events[0]).toEqual({ type: "task_state", state: "running" });+ vi.advanceTimersByTime(5000);+ expect(+ sub.messages.filter((m) => typeOf(m) === "partial_thinking").length,+ ).toBeGreaterThanOrEqual(3);+ const grown = store.liveTail(IDS.sessions.thinking)!;+ const before = (tail.fragments[0]!.payload as { thinking: string }).thinking;+ const after = (grown.fragments[0]!.payload as { thinking: string }).thinking;+ expect(after.length).toBeGreaterThan(before.length);+ expect(grown.cursor).not.toBe(tail.cursor);+ });++ it("an approval pending: the subscription is told, and a decision runs the command and settles", () => {+ vi.useFakeTimers();+ const store = resetStore({ lang: "en", signedIn: true, now: NOW });+ const sub = collector();+ store.channel(IDS.sessions.approval)!.subscribe(sub);+ store.onSubscribe(IDS.sessions.approval, sub);+ expect(sub.events.map((e) => e.type)).toEqual(["task_state", "approval_request"]);+ expect(store.decide(IDS.sessions.approval, "nope", "allow")).toBe(false);+ expect(store.decide(IDS.sessions.approval, TOOL_CALL_IDS.pendingPublish, "allow")).toBe(true);+ expect(sub.messages.at(-1)?.payload).toMatchObject({+ type: "approval_decision",+ decision: "allow",+ });+ vi.advanceTimersByTime(4000);+ const types = sub.messages.map(typeOf);+ expect(types).toContain("tool_call_output");+ expect(types).toContain("text");+ expect(sub.events.at(-1)).toEqual({ type: "task_state", state: "idle" });+ expect(store.session(IDS.sessions.approval)?.status).toBe("idle");+ expect(store.session(IDS.sessions.approval)?.pendingApprovalCount).toBe(0);+ });+});++describe("a sent message", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("streams thinking, a tool call with its output and the answer, then settles with a title", () => {+ vi.useFakeTimers();+ const store = resetStore({ lang: "en", signedIn: true, now: NOW });+ const user = collector();+ store.userChannel.subscribe(user);+ const row = store.createSession(IDS.agents.docs, {});+ expect(user.events.at(-1)).toMatchObject({ type: "session_created", sessionId: row.sessionId });+ const sub = collector();+ store.channel(row.sessionId)!.subscribe(sub);+ expect(store.startTask(row.sessionId, "What does the corpus say?")).toBe(true);+ expect(store.startTask(row.sessionId, "again")).toBe(false);+ expect(sub.events[0]).toEqual({ type: "task_state", state: "running" });+ expect(sub.messages[0]?.payload).toMatchObject({ type: "text", role: "user" });+ vi.advanceTimersByTime(30_000);+ const types = sub.messages.map(typeOf);+ for (const expected of [+ "partial_thinking",+ "thinking",+ "partial_tool_call",+ "tool_call",+ "tool_call_output",+ "partial_text",+ "text",+ "token_usage",+ "request_end",+ ]) {+ expect(types, expected).toContain(expected);+ }+ // The complete messages are history; the fragments never are.+ const history = store.transcript(row.sessionId)!.history.map(typeOf);+ expect(history.some((t) => t.startsWith("partial_"))).toBe(false);+ expect(history).toContain("text");+ expect(sub.events.at(-1)).toEqual({ type: "task_state", state: "idle" });+ expect(store.session(row.sessionId)?.title).toBeDefined();+ expect(user.events.some((e) => e.type === "session_title")).toBe(true);+ });++ it("stops on abort, leaving the Session idle with an abort event in its history", () => {+ vi.useFakeTimers();+ const store = resetStore({ lang: "en", signedIn: true, now: NOW });+ const row = store.createSession(IDS.agents.docs, {});+ const sub = collector();+ store.channel(row.sessionId)!.subscribe(sub);+ store.startTask(row.sessionId, "hi");+ vi.advanceTimersByTime(1000);+ store.abort(row.sessionId);+ const count = sub.messages.length;+ vi.advanceTimersByTime(30_000);+ expect(sub.messages.length).toBe(count);+ expect(store.session(row.sessionId)?.status).toBe("idle");+ const last = store.transcript(row.sessionId)!.history.at(-1);+ expect(last && typeOf(last)).toBe("abort");+ });+});diff --git a/packages/ui-gallery/test/fit.test.ts b/packages/ui-gallery/test/fit.test.tsnew file mode 100644index 00000000..7b8e19f8--- /dev/null+++ b/packages/ui-gallery/test/fit.test.ts@@ -0,0 +1,34 @@+/**+ * The fitting rule for the framed app: laid out at the app's window width, scaled down to the+ * column, never up.+ */+import { describe, expect, it } from "vitest";+import { APP_FRAME, PHONE_FRAME } from "../src/app/frame";+import { fitScale, fittedHeight } from "../src/lib/fit";++describe("the frames", () => {+ it("are the app's laptop window and an iPhone-class phone", () => {+ expect(APP_FRAME).toEqual({ width: 1280, height: 800 });+ expect(PHONE_FRAME.width).toBe(390);+ });+});++describe("fitScale", () => {+ it("shrinks the frame to a narrower column", () => {+ expect(fitScale(1280, 704)).toBeCloseTo(0.55, 5);+ expect(fitScale(956, 704)).toBeCloseTo(704 / 956, 10);+ });++ it("never scales up, and holds at 1 until the column has been measured", () => {+ expect(fitScale(956, 1200)).toBe(1);+ expect(fitScale(956, 956)).toBe(1);+ expect(fitScale(956, 0)).toBe(1);+ expect(fitScale(0, 704)).toBe(1);+ });++ it("gives the box the frame's height at that scale, rounded up so nothing is cut", () => {+ expect(fittedHeight(702, 0.55)).toBe(387);+ expect(fittedHeight(800, 0.5)).toBe(400);+ expect(fittedHeight(640, 1)).toBe(640);+ });+});diff --git a/packages/ui-gallery/test/fonts.test.ts b/packages/ui-gallery/test/fonts.test.tsnew file mode 100644index 00000000..e06eb4c0--- /dev/null+++ b/packages/ui-gallery/test/fonts.test.ts@@ -0,0 +1,109 @@+/**+ * The font readout: the family a stack actually renders in, resolved over a probe of what the+ * document bundles and what the platform has, and the line the chrome prints.+ */+import { describe, expect, it } from "vitest";+import {+ faceInUse,+ familiesOf,+ FONT_ROLES,+ formatFontReadout,+ isGenericFamily,+} from "../src/app/fonts";+import type { Declared, FaceProbe } from "../src/app/fonts";+import { zh } from "../src/strings";+import { en } from "../src/strings-en";++/** A document that bundles `bundled`, has given up on `failed`, on a platform that has `installed`. */+function probe(+ bundled: readonly string[],+ installed: readonly string[],+ failed: readonly string[] = [],+): FaceProbe {+ const declared = (family: string): Declared =>+ bundled.includes(family) ? "bundled" : failed.includes(family) ? "failed" : "absent";+ return { declared, installed: (family) => installed.includes(family) };+}++describe("the font readout", () => {+ it("reads the sans, CJK and mono tokens", () => {+ expect(FONT_ROLES).toEqual({+ latin: "--ui-font-sans",+ cjk: "--ui-font-cjk",+ mono: "--ui-font-mono",+ });+ });++ it("splits a stack into unquoted families, in order", () => {+ expect(familiesOf(`"Mona Sans Variable", "MiSans", system-ui, sans-serif`)).toEqual([+ "Mona Sans Variable",+ "MiSans",+ "system-ui",+ "sans-serif",+ ]);+ expect(familiesOf(" 'JetBrains Mono Variable' , monospace ")).toEqual([+ "JetBrains Mono Variable",+ "monospace",+ ]);+ expect(familiesOf("")).toEqual([]);+ });++ it("knows the generic keywords and the system aliases", () => {+ for (const family of ["system-ui", "-apple-system", "BlinkMacSystemFont", "sans-serif"])+ expect(isGenericFamily(family)).toBe(true);+ expect(isGenericFamily("PingFang SC")).toBe(false);+ });++ it("names a bundled face, wherever it sits in the stack", () => {+ const linux = probe(["MiSans", "Mona Sans Variable"], ["Noto Sans CJK SC"]);+ expect(faceInUse(`"Mona Sans Variable", system-ui`, linux)).toBe("Mona Sans Variable");+ // The first family is not installed here: the readout does not claim it.+ expect(faceInUse(`"PingFang SC", "MiSans", sans-serif`, linux)).toBe("MiSans");+ });++ it("names an installed platform face when nothing before it can render", () => {+ const linux = probe([], ["Noto Sans CJK SC"]);+ expect(+ faceInUse(`"PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`, linux),+ ).toBe("Noto Sans CJK SC");+ });++ it("says the platform only when the stack falls through to it", () => {+ const linux = probe([], []);+ expect(faceInUse("system-ui, -apple-system, sans-serif", linux)).toBeNull();+ expect(faceInUse(`"PingFang SC", "Microsoft YaHei", sans-serif`, linux)).toBeNull();+ expect(faceInUse(`"PingFang SC"`, linux)).toBeNull();+ expect(faceInUse("", linux)).toBeNull();+ // A generic keyword ahead of a bundled face means the platform renders, not the bundle.+ expect(faceInUse(`system-ui, "MiSans"`, probe(["MiSans"], []))).toBeNull();+ });++ it("skips a bundled face whose every slice failed to load", () => {+ const broken = probe(["MiSans"], ["Noto Sans CJK SC"], ["Mona Sans Variable"]);+ expect(faceInUse(`"Mona Sans Variable", "Noto Sans CJK SC", sans-serif`, broken)).toBe(+ "Noto Sans CJK SC",+ );+ });++ it("prints the three roles and the size in the chrome's language, the platform in words", () => {+ const readout = {+ latin: "Mona Sans Variable",+ cjk: "MiSans",+ mono: "JetBrains Mono Variable",+ px: 16,+ };+ expect(formatFontReadout(readout, en.readout)).toBe(+ "Latin Mona Sans Variable · CJK MiSans · Mono JetBrains Mono Variable · 16px",+ );+ expect(formatFontReadout(readout, zh.readout)).toBe(+ "英文 Mona Sans Variable · 中文 MiSans · 等宽 JetBrains Mono Variable · 16px",+ );+ const platform = { latin: null, cjk: null, mono: null, px: 15 };+ expect(formatFontReadout(platform, en.readout)).toBe(+ "Latin System · CJK System · Mono System · 15px",+ );+ expect(formatFontReadout(platform, zh.readout)).toBe(+ "英文 系统 · 中文 系统 · 等宽 系统 · 15px",+ );+ });+});diff --git a/packages/ui-gallery/test/frame-height.test.ts b/packages/ui-gallery/test/frame-height.test.tsnew file mode 100644index 00000000..28aa2dc5--- /dev/null+++ b/packages/ui-gallery/test/frame-height.test.ts@@ -0,0 +1,62 @@+/**+ * The library frame's height rule: the board, what overflows it, every floating overlay, and+ * the panel of a covering one — and back down when they close.+ */+import { describe, expect, it } from "vitest";+import { coversViewport, FRAME_HEIGHT_OPTIONS, frameHeight } from "../src/library/frame-height";++const main = { bottom: 400, contentBottom: 380 };+const opts = { margin: 10, dialogMin: 560 };++describe("frameHeight", () => {+ it("is the board's box when nothing floats over it", () => {+ expect(frameHeight(main, [], opts)).toBe(400);+ expect(frameHeight({ bottom: 400.2, contentBottom: 0 }, [], opts)).toBe(401);+ });++ it("follows content that overflows the board, with the margin", () => {+ // A dropdown opened inside the board, absolutely positioned below its trigger.+ expect(frameHeight({ bottom: 400, contentBottom: 520 }, [], opts)).toBe(530);+ });++ it("follows a floating overlay's bottom, with the margin", () => {+ const menu = { bottom: 610, covers: false, panelHeight: 0 };+ expect(frameHeight(main, [menu], opts)).toBe(620);+ // One that fits inside the board changes nothing.+ expect(frameHeight(main, [{ bottom: 200, covers: false, panelHeight: 0 }], opts)).toBe(400);+ // Several: the lowest wins.+ const toasts = [+ { bottom: 60, covers: false, panelHeight: 0 },+ { bottom: 120, covers: false, panelHeight: 0 },+ ];+ expect(frameHeight({ bottom: 90, contentBottom: 80 }, toasts, opts)).toBe(130);+ });++ it("gives a covering overlay its panel plus margins, and never less than the dialog floor", () => {+ const backdrop = { bottom: 400, covers: true, panelHeight: 300 };+ expect(frameHeight(main, [backdrop], opts)).toBe(560);+ const tall = { bottom: 400, covers: true, panelHeight: 700 };+ expect(frameHeight(main, [tall], opts)).toBe(720);+ // A drawer whose panel spans the viewport counts only what is inside the panel.+ expect(frameHeight(main, [{ bottom: 400, covers: true, panelHeight: 0 }], opts)).toBe(560);+ });++ it("shrinks back to the board once the overlays are gone", () => {+ const withMenu = frameHeight(main, [{ bottom: 900, covers: false, panelHeight: 0 }], opts);+ expect(withMenu).toBe(910);+ expect(frameHeight(main, [], opts)).toBe(400);+ });++ it("ships with a small margin and a dialog floor of 560", () => {+ expect(FRAME_HEIGHT_OPTIONS).toEqual({ margin: 16, dialogMin: 560 });+ });+});++describe("coversViewport", () => {+ it("is a box from the top of the viewport to its bottom, give or take a pixel", () => {+ expect(coversViewport({ top: 0, bottom: 480 }, 480)).toBe(true);+ expect(coversViewport({ top: 1, bottom: 479 }, 480)).toBe(true);+ expect(coversViewport({ top: 40, bottom: 480 }, 480)).toBe(false);+ expect(coversViewport({ top: 0, bottom: 300 }, 480)).toBe(false);+ });+});diff --git a/packages/ui-gallery/test/frame.test.ts b/packages/ui-gallery/test/frame.test.tsnew file mode 100644index 00000000..349f927e--- /dev/null+++ b/packages/ui-gallery/test/frame.test.ts@@ -0,0 +1,109 @@+/**+ * The frame's contract: the URL the gallery builds is the URL the frame reads back, the seeding+ * script writes the app's own storage keys, and the one key the package does not export is the+ * app's.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import vm from "node:vm";+import { describe, expect, it } from "vitest";+import { THEME_STORAGE_KEYS } from "@prismshadow/penguin-ui/boot";+import {+ APP_FRAME_PATH,+ APP_LANG_KEY,+ appFrameSrc,+ parseFrameParams,+ SEEDED_KEYS,+ storageSeedScript,+} from "../src/app/frame";+import type { FramePrefs } from "../src/app/frame";++const PREFS: FramePrefs = {+ theme: "modern",+ mode: "dark",+ accent: "amber",+ size: "l",+ latin: "mona-sans",+ cjk: "noto-sans-sc",+ lang: "zh",+};++describe("the frame URL", () => {+ it("names the document, the route and every preference, and reads back what it wrote", () => {+ const src = appFrameSrc("/gallery", PREFS, {+ route: "/chat/s-1?tab=x",+ signedOut: true,+ open: "settings",+ });+ expect(src.startsWith(`/gallery${APP_FRAME_PATH}?`)).toBe(true);+ const params = parseFrameParams(src.slice(src.indexOf("?")));+ expect(params).toEqual({+ route: "/chat/s-1?tab=x",+ lang: "zh",+ signedOut: true,+ open: "settings",+ });+ for (const [param, key] of Object.entries(SEEDED_KEYS)) {+ expect(src, key).toContain(`${param}=`);+ }+ });++ it("opens the chat when the route is missing or not a path, signed in by default", () => {+ expect(parseFrameParams("")).toEqual({ route: "/chat", lang: "en" });+ expect(parseFrameParams("?route=http://evil&lang=fr")).toEqual({ route: "/chat", lang: "en" });+ });++ it("seeds the app's own storage keys, every one of them the package's or the app's", () => {+ expect(SEEDED_KEYS).toEqual({+ theme: THEME_STORAGE_KEYS.themeId,+ mode: THEME_STORAGE_KEYS.mode,+ accent: THEME_STORAGE_KEYS.accent,+ size: THEME_STORAGE_KEYS.textSize,+ latin: THEME_STORAGE_KEYS.fontLatin,+ cjk: THEME_STORAGE_KEYS.fontCjk,+ lang: APP_LANG_KEY,+ });+ // The language key is the app's own (state/locale.tsx), spelled here because it has no export.+ const locale = readFileSync(+ fileURLToPath(new URL("../../web/src/state/locale.tsx", import.meta.url)),+ "utf8",+ );+ expect(locale).toContain(`const STORAGE_KEY = "${APP_LANG_KEY}";`);+ });++ it("is a classic script that gives the document a seeded in-memory storage", () => {+ const src = appFrameSrc("", PREFS, { route: "/models" });+ const search = src.slice(src.indexOf("?"));+ const window: Record<string, unknown> = {};+ const context = vm.createContext({+ window,+ location: { search },+ URLSearchParams,+ Object,+ });+ vm.runInContext(storageSeedScript(), context);+ const storage = window.localStorage as Storage;+ expect(storage.getItem(THEME_STORAGE_KEYS.themeId)).toBe("modern");+ expect(storage.getItem(THEME_STORAGE_KEYS.mode)).toBe("dark");+ expect(storage.getItem(THEME_STORAGE_KEYS.textSize)).toBe("l");+ expect(storage.getItem(THEME_STORAGE_KEYS.fontLatin)).toBe("mona-sans");+ expect(storage.getItem(THEME_STORAGE_KEYS.fontCjk)).toBe("noto-sans-sc");+ expect(storage.getItem(APP_LANG_KEY)).toBe("zh");+ expect(storage.getItem("penguin.nothing")).toBeNull();+ // It is a working Storage: writes stay in this document and enumerate.+ storage.setItem("penguin.sidebarCollapsed", "1");+ expect(storage.length).toBe(8);+ expect(storage.key(7)).toBe("penguin.sidebarCollapsed");+ storage.removeItem("penguin.sidebarCollapsed");+ expect(storage.getItem("penguin.sidebarCollapsed")).toBeNull();+ const session = window.sessionStorage as Storage;+ expect(session.length).toBe(0);+ // Dependency-free and strict-safe: no globals leak.+ expect(Object.keys(context).sort()).toEqual([+ "Object",+ "URLSearchParams",+ "location",+ "window",+ ]);+ });+});diff --git a/packages/ui-gallery/test/icon-registry.test.ts b/packages/ui-gallery/test/icon-registry.test.tsnew file mode 100644index 00000000..fc528fe2--- /dev/null+++ b/packages/ui-gallery/test/icon-registry.test.ts@@ -0,0 +1,69 @@+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { extractIconPaths, extractIconSizes } from "../src/lib/icon-registry";++describe("extractIconPaths", () => {+ it("reads constants, object entries, template fragments and cross-file references", () => {+ const icons = extractIconPaths({+ "a.tsx": `+ /** A doc comment mentioning label: "M0 0" that must not count. */+ const EYE = "M2 12s3-7 10-7 10 7 10 7";+ export const HIDDEN_ICON = \`\${EYE}M3 3l18 18\`;+ export const TRASH_ICON =+ "M4 6h16M9 6V4";+ export const LABEL = "Delete"; // not path data+ export const URL = "https://example.invalid/M1"; // not path data either+ `,+ "b.ts": `+ import { TRASH_ICON } from "./a";+ export const NAV_ICONS = {+ /** the bin */+ bin: TRASH_ICON,+ usage: "M4 20V10m6 10V4",+ nested: HIDDEN_ICON+ } as const;+ export const ICON_SIZE = { row: 12 };+ `,+ });+ const byName = (name: string) => icons.find((icon) => icon.names.includes(name));+ expect(byName("HIDDEN_ICON")?.d).toBe("M2 12s3-7 10-7 10 7 10 7M3 3l18 18");+ expect(byName("TRASH_ICON")?.names).toEqual(["TRASH_ICON", "NAV_ICONS.bin"]);+ expect(byName("TRASH_ICON")?.sources).toEqual(["a.tsx", "b.ts"]);+ expect(byName("NAV_ICONS.usage")?.d).toBe("M4 20V10m6 10V4");+ expect(byName("NAV_ICONS.nested")).toBe(byName("HIDDEN_ICON"));+ expect(icons.flatMap((icon) => icon.names)).not.toContain("LABEL");+ expect(icons.flatMap((icon) => icon.names)).not.toContain("URL");+ });++ it("skips an unresolved or circular reference instead of throwing", () => {+ const icons = extractIconPaths({+ "c.ts": `const A = B;\nconst B = A;\nconst C = \`\${MISSING}M1 1\`;\nconst D = "M0 0h1";`,+ });+ expect(icons.map((icon) => icon.names)).toEqual([["D"]]);+ });++ it("finds the Web App's icons in the modules the gallery reads", () => {+ const read = (path: string) =>+ readFileSync(fileURLToPath(new URL(`../../web/src/${path}`, import.meta.url)), "utf8");+ const icons = extractIconPaths({+ icons: read("components/ui/icons.tsx"),+ groupList: read("components/ui/group-list.tsx"),+ rowMenu: read("components/ui/session-row-menu.tsx"),+ stat: read("lib/stat-icons.ts"),+ });+ const names = icons.flatMap((icon) => icon.names);+ expect(icons.length).toBeGreaterThan(30);+ for (const name of [+ "TRASH_ICON",+ "GEAR_ICON",+ "FOLDER_ICON",+ "STAT_ICONS.copy",+ "NAV_ICONS.models",+ ]) {+ expect(names).toContain(name);+ }+ const sizes = extractIconSizes(read("lib/icon-scale.ts"));+ expect(sizes.find((rung) => rung.name === "inlineGlyph")?.px).toBe(13);+ });+});diff --git a/packages/ui-gallery/test/library.test.ts b/packages/ui-gallery/test/library.test.tsnew file mode 100644index 00000000..a479572d--- /dev/null+++ b/packages/ui-gallery/test/library.test.ts@@ -0,0 +1,303 @@+/**+ * The component library: every topic is registered once, sits in one of the two groups, has a+ * board and a title in both dictionaries, and reaches its frame through the same preference+ * params as the app frames; the sections' top-bar links open where the owner asked.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { TOKEN_NAMES } from "@prismshadow/penguin-ui";+import { HOME_SURFACE } from "../src/app/surfaces";+import { SEEDED_KEYS } from "../src/app/frame";+import {+ CHART_GEOMETRY_TOKENS,+ CHART_PALETTE_TOKENS,+ readChartTokens,+} from "../src/library/chart-tokens";+import { DEMO_TREE, flattenTree } from "../src/library/demo-tree";+import { LIBRARY_FRAME_PATH, libraryFrameSrc, parseLibraryParams } from "../src/library/frame";+import {+ FIRST_TOPIC,+ isTopicId,+ TOPIC_GROUP_IDS,+ TOPIC_GROUPS,+ TOPIC_IDS,+ TOPICS,+ topicById,+} from "../src/library/topics";+import { DEFAULT_STATE } from "../src/lib/url-state";+import { zh } from "../src/strings";+import { en } from "../src/strings-en";++const read = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8");++describe("the library's topics", () => {+ it("are each registered once, in a group, and the groups list them all", () => {+ expect(new Set(TOPIC_IDS).size).toBe(TOPIC_IDS.length);+ expect(TOPICS.map((topic) => topic.id)).toEqual([...TOPIC_IDS]);+ for (const topic of TOPICS) expect(TOPIC_GROUP_IDS).toContain(topic.group);+ expect(TOPIC_GROUPS.flatMap((group) => group.topics.map((topic) => topic.id))).toEqual(+ [...TOPIC_IDS].sort(+ (a, b) =>+ TOPIC_GROUP_IDS.indexOf(topicById(a).group) - TOPIC_GROUP_IDS.indexOf(topicById(b).group),+ ),+ );+ expect(isTopicId(FIRST_TOPIC)).toBe(true);+ expect(isTopicId("foundations")).toBe(false);+ });++ it("cover the owner's list: the component kinds, then the token boards", () => {+ const components = TOPIC_GROUPS.find((group) => group.id === "components")!.topics;+ expect(components.map((topic) => topic.id)).toEqual([+ "buttons",+ "inputs",+ "pickers",+ "toasts",+ "notices",+ "dialogs",+ "tooltips",+ "tabs",+ "badges",+ "empty",+ "loading",+ "charts",+ "avatars",+ "files",+ ]);+ const foundations = TOPIC_GROUPS.find((group) => group.id === "foundations")!.topics;+ expect(foundations.map((topic) => topic.id)).toEqual([+ "colour",+ "type",+ "shape",+ "density",+ "focus",+ "motion",+ "icons",+ "hooks",+ ]);+ });++ it("each have a board in the frame's registry", () => {+ const registry = read("../src/library/boards.tsx");+ for (const id of TOPIC_IDS) expect(registry).toMatch(new RegExp(`^ ${id}: \\w+Board,$`, "m"));+ });++ it("each have a title and a description in both dictionaries", () => {+ for (const id of TOPIC_IDS) {+ for (const S of [zh, en]) {+ expect(S.library.topics[id].title.trim()).not.toBe("");+ expect(S.library.topics[id].description.trim()).not.toBe("");+ }+ }+ for (const group of TOPIC_GROUP_IDS) {+ expect(zh.library.groups[group].trim()).not.toBe("");+ expect(en.library.groups[group].trim()).not.toBe("");+ }+ });+});++describe("the library frame", () => {+ const prefs = { ...DEFAULT_STATE, theme: "geek" as const, lang: "zh" as const };++ it("opens lib.html on a topic with the same preference params as an app frame", () => {+ const src = libraryFrameSrc("/base", prefs, "pickers");+ expect(src.startsWith(`/base${LIBRARY_FRAME_PATH}?topic=pickers&`)).toBe(true);+ const params = new URLSearchParams(src.slice(src.indexOf("?")));+ for (const key of Object.keys(SEEDED_KEYS))+ expect(params.get(key)).toBe(prefs[key as keyof typeof prefs]);+ expect(parseLibraryParams(src.slice(src.indexOf("?")))).toEqual({+ topic: "pickers",+ lang: "zh",+ });+ });++ it("falls back to the first topic and English for anything unknown", () => {+ expect(parseLibraryParams("?topic=nope&lang=fr")).toEqual({ topic: FIRST_TOPIC, lang: "en" });+ expect(parseLibraryParams("")).toEqual({ topic: FIRST_TOPIC, lang: "en" });+ });++ it("is booted like the app frame: both documents get the seed and boot scripts", () => {+ const config = read("../vite.config.ts");+ expect(config).toMatch(/FRAME_DOCUMENTS = \["app\.html", "lib\.html"\]/);+ expect(config).toMatch(/library: at\("\.\/lib\.html"\)/);+ });+});++describe("the sections", () => {+ it("open where the owner asked: 界面 on the chat surface, 基础 on the first topic, 字体 on the defaults", () => {+ const topbar = read("../src/chrome/topbar.tsx");+ expect(topbar).toMatch(+ /page: "surfaces", label: S\.site\.surfaces, href: surfaceHref\(BASE, state, HOME_SURFACE\)/,+ );+ expect(topbar).toMatch(+ /page: "foundations", label: S\.site\.foundations, href: topicHref\(BASE, state, FIRST_TOPIC\)/,+ );+ expect(topbar).toMatch(+ /page: "fonts", label: S\.site\.fonts, href: fontsHref\(BASE, state, "defaults"\)/,+ );+ expect(HOME_SURFACE).toBe("chat");+ expect(FIRST_TOPIC).toBe("buttons");+ });++ it("each carry their own list: surfaces alone, topics alone, fonts pages alone", () => {+ const nav = read("../src/chrome/sidenav.tsx");+ expect(nav).toMatch(/export function SurfaceNav/);+ expect(nav).toMatch(/export function TopicNav/);+ expect(nav).toMatch(/export function FontsNav/);+ // The surface list no longer appends Foundations and Fonts.+ expect(nav).not.toMatch(/MODULES|routeHref\(/);+ expect(read("../src/pages/surface.tsx")).toMatch(/<SurfaceNav activeId=\{id\}/);+ expect(read("../src/pages/library.tsx")).toMatch(/<TopicNav activeId=\{id\}/);+ expect(read("../src/pages/fonts.tsx")).toMatch(/<FontsNav activeId=\{page\}/);+ });+});++describe("the charts board", () => {+ it("documents the foundation in three parts: the primitives, the tokens, then the charts", () => {+ const board = read("../src/library/boards/charts.tsx");+ const order = ["t.parts.primitives", "t.parts.tokens", "t.parts.charts"].map((part) =>+ board.indexOf(`<Part title={${part}}`),+ );+ expect(order.every((index) => index >= 0)).toBe(true);+ expect(order).toEqual([...order].sort((a, b) => a - b));+ expect(board).toMatch(/<ChartPrimitives \/>/);+ expect(board).toMatch(/<ChartTokenTable \/>/);+ });++ it("shows each primitive on its own, from the app's chart module", () => {+ const stage = read("../src/library/boards/chart-primitives.tsx");+ expect(stage).toMatch(/from "\.\.\/\.\.\/\.\.\/\.\.\/web\/src\/components\/ui\/chart"/);+ for (const primitive of [+ "ChartBar",+ "ChartLine",+ "ChartArea",+ "ChartPoint",+ "ChartArc",+ "ChartGrid",+ "ChartAxis",+ "TimelineBar",+ ]) {+ expect(stage).toMatch(new RegExp(`<${primitive}[\\s/>]`));+ }+ // The line is drawn once per curve the token may take.+ expect(stage).toMatch(/CURVES: readonly ChartCurve\[\] = \["linear", "smooth", "step"\]/);+ });++ it("tables the current theme's chart tokens, read from the frame root's computed style", () => {+ const table = read("../src/library/boards/chart-tokens.tsx");+ expect(table).toMatch(/getComputedStyle\(document\.documentElement\)/);+ expect(table).toMatch(/readChartTokens\(\(name\) => computed\.getPropertyValue\(name\)\)/);+ expect(table).toMatch(/new MutationObserver\(update\)/);+ const tokens = readChartTokens((name) => (name === "--ui-chart-2" ? " #f59e0b " : ""));+ expect(tokens.palette[1]).toEqual({ name: "--ui-chart-2", value: "#f59e0b" });+ expect(tokens.palette.map((row) => row.name)).toEqual([...CHART_PALETTE_TOKENS]);+ expect(tokens.geometry.map((row) => row.name)).toEqual([...CHART_GEOMETRY_TOKENS]);+ expect(tokens.geometry.every((row) => row.value === "")).toBe(true);+ // Both dictionaries say what every token is for.+ for (const name of [...CHART_PALETTE_TOKENS, ...CHART_GEOMETRY_TOKENS]) {+ expect(zh.library.charts.tokenMeaning[name].trim()).not.toBe("");+ expect(en.library.charts.tokenMeaning[name].trim()).not.toBe("");+ }+ });++ it("tables exactly the package's chart tokens", () => {+ const packaged = TOKEN_NAMES.filter((name) => name.startsWith("--ui-chart-")).sort();+ expect([...CHART_PALETTE_TOKENS, ...CHART_GEOMETRY_TOKENS].sort()).toEqual(packaged);+ });++ it("hands every chart data that never changes identity between renders", () => {+ const board = read("../src/library/boards/charts.tsx");+ expect(board).toMatch(/^const SERIES: UsageSeriesPoint\[\] = daySeries\(\);$/m);+ expect(board).toMatch(/^const OTHER_SPANS: TraceOtherSpan\[\] = \[\];$/m);+ expect(board).toMatch(/otherSpans=\{OTHER_SPANS\}/);+ expect(board).toMatch(/useMemo\(\(\) => agentCounts\(SERIES, t\.agents\), \[t\.agents\]\)/);+ // No input is rebuilt inside the component.+ const component = board.slice(board.indexOf("export function ChartsBoard"));+ expect(component).not.toMatch(/daySeries\(\)|\bat\(/);+ });++ it("mounts every chart kind the app draws, the Trace timeline included", () => {+ const board = read("../src/library/boards/charts.tsx");+ for (const chart of [+ "TokenDonut",+ "TrendChart",+ "TokenBarChart",+ "TokenLegend",+ "RequestsChart",+ "ActivitySparkline",+ "ScoreSparkline",+ "TimelineChart",+ ]) {+ expect(board).toMatch(new RegExp(`<${chart}[\\s/>]`));+ }+ expect(board).toMatch(+ /from "\.\.\/\.\.\/\.\.\/\.\.\/web\/src\/features\/traces\/timeline-chart"/,+ );+ });+});++describe("the library frame's sizing", () => {+ it("measures what is painted, overlays included, and swallows the resizes it asks for", () => {+ const page = read("../src/library/page.tsx");+ expect(page).toMatch(/measureFrameHeight\(document, main, root\)/);+ expect(page).toMatch(+ /mutations\.observe\(document\.body, \{\s*childList: true,\s*subtree: true,/,+ );+ expect(page).toMatch(/if \(height !== window\.innerHeight\) expectSelfResize\(\);/);+ const entry = read("../src/library/main.tsx");+ // The guard is installed ahead of the app's own resize listeners.+ expect(entry.indexOf("installSelfResizeGuard(window)")).toBeLessThan(+ entry.indexOf("createRoot("),+ );+ // No per-topic reserve remains: the measurement is the only sizing.+ expect(read("../src/library/topics.ts")).not.toMatch(/room/);+ expect(read("../src/chrome/library-frame.tsx")).not.toMatch(/room/);+ });++ it("never shows a scrollbar: the framed document cannot scroll, the frame is hidden until sized and never animates", () => {+ expect(read("../src/library/main.tsx")).toMatch(+ /document\.documentElement\.dataset\.framed = "1";/,+ );+ expect(read("../src/library/library.css")).toMatch(+ /html\[data-framed\],\s*html\[data-framed\] body \{\s*overflow: hidden;/,+ );+ const css = read("../src/chrome.css");+ expect(css).toMatch(/\.g-lib:not\(\[data-loaded\]\) \.g-lib-frame \{\s*visibility: hidden;/);+ expect(css).not.toMatch(/\.g-lib-frame \{[^}]*transition/s);+ expect(read("../src/chrome/library-frame.tsx")).toMatch(+ /data-loaded=\{height !== null \|\| undefined\}/,+ );+ });+});++describe("the demo file tree", () => {+ it("flattens open directories in order, with each row's place in its set", () => {+ const rows = flattenTree(DEMO_TREE, new Set(["src"]));+ expect(rows.map((row) => row.path)).toEqual([+ "corpus",+ "src",+ "src/rag.ts",+ "src/embed.ts",+ "src/empty",+ "test",+ "README.md",+ "package.json",+ ]);+ expect(rows[1]).toMatchObject({+ kind: "dir",+ depth: 0,+ posInSet: 2,+ setSize: 5,+ expanded: true,+ });+ expect(rows[2]).toMatchObject({ kind: "file", depth: 1, posInSet: 1, setSize: 3 });+ expect(rows[4]).toMatchObject({ kind: "dir", expanded: false, loaded: true, empty: true });+ expect(flattenTree(DEMO_TREE, new Set()).map((row) => row.path)).toEqual([+ "corpus",+ "src",+ "test",+ "README.md",+ "package.json",+ ]);+ });+});diff --git a/packages/ui-gallery/test/mock-api.test.ts b/packages/ui-gallery/test/mock-api.test.tsnew file mode 100644index 00000000..4d81e7c0--- /dev/null+++ b/packages/ui-gallery/test/mock-api.test.ts@@ -0,0 +1,216 @@+/**+ * The mocked API covers every endpoint the Web App calls: the app's own endpoint wrappers+ * (`packages/web/src/api/endpoints.ts`) are imported with the network layer swapped, as the+ * gallery swaps it, and every one is called against the mock. An endpoint the mock does not+ * route answers with the `gallery_unmocked` code and nothing else does, so that code — and a+ * handler that throws anything but the app's `ApiError` — is what fails here. The URL helpers+ * (file content, downloads) are checked the same way through the fetch path.+ */+import { describe, expect, it } from "vitest";+import * as api from "../../web/src/api/endpoints";+import { ApiError, UNMOCKED } from "../src/app/mock/errors";+import { answerAsResponse } from "../src/app/mock/fetch-shim";+import { router } from "../src/app/mock/routes";+import { resetStore } from "../src/app/mock/store";++type AnyFn = (...args: unknown[]) => unknown;++/** Every function the wrappers module exports, the key-auth descriptors' included. */+function wrappers(): [name: string, fn: AnyFn][] {+ const found: [string, AnyFn][] = [];+ for (const [name, value] of Object.entries(api)) {+ if (typeof value === "function") found.push([name, value as AnyFn]);+ else if (typeof value === "object" && value !== null) {+ for (const [inner, fn] of Object.entries(value)) {+ if (typeof fn === "function") found.push([`${name}.${inner}`, fn as AnyFn]);+ }+ }+ }+ return found;+}++/** Dummy arguments: ids everywhere; a wrapper reading a field off one gets `undefined`, which its path tolerates. */+const ARGS = ["a", "b", "c", "d", "e", "f"];++describe("the mocked API", () => {+ it("routes every endpoint the app's wrappers name", async () => {+ const gaps: string[] = [];+ const crashes: string[] = [];+ for (const [name, fn] of wrappers()) {+ resetStore({ lang: "en", signedIn: true });+ let result: unknown;+ try {+ result = await fn(...ARGS);+ } catch (error) {+ if (error instanceof ApiError) {+ if (error.code === UNMOCKED) gaps.push(name);+ continue;+ }+ crashes.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);+ continue;+ }+ // A URL helper: the fetch path must answer it too.+ if (typeof result === "string" && result.startsWith("/api/")) {+ const response = await answerAsResponse("GET", result, undefined);+ const body =+ response.status >= 400 ? ((await response.json()) as { error: { code: string } }) : null;+ if (body?.error.code === UNMOCKED) gaps.push(name);+ }+ }+ expect(gaps, "wrappers with no mock route").toEqual([]);+ expect(crashes, "handlers that threw something other than an ApiError").toEqual([]);+ expect(wrappers().length).toBeGreaterThan(150);+ });++ it("answers the real ids with the fixtures, and unknown ids with 404", async () => {+ const store = resetStore({ lang: "zh", signedIn: true });+ const me = await api.getMe();+ expect(me.user.isAdmin).toBe(true);+ expect(me.companyMode).toBe(false);+ const projects = await api.listProjects();+ expect(projects.projects.map((p) => p.projectId)).toEqual([store.f.project.projectId]);+ const agents = await api.listAgents(store.f.project.projectId);+ expect(agents.agents.length).toBe(2);+ await expect(api.getSession("nope")).rejects.toMatchObject({ status: 404, code: "not_found" });+ });++ it("pages a Session list per category with totals, own rows only", async () => {+ const store = resetStore({ lang: "en", signedIn: true });+ const project = store.f.project.projectId;+ const agent = store.f.agents[0]!.agentId;+ const first = await api.listSessions(project, agent, {+ offset: 0,+ limit: 3,+ category: "active",+ withCounts: true,+ excludeOrg: true,+ });+ expect(first.sessions.length).toBe(3);+ expect(first.counts?.active).toBeGreaterThan(3);+ expect(first.counts?.archived).toBe(1);+ expect(first.counts?.schedule).toBe(1);+ expect(first.counts?.subagent).toBe(1);+ expect(first.counts?.benchmark).toBe(1);+ expect(first.workspaceCounts).toBeDefined();+ const rest = await api.listSessions(project, agent, {+ offset: 3,+ limit: 100,+ category: "active",+ });+ expect(rest.sessions.length).toBe(first.counts!.active - 3);+ // Newest first, and no row twice across the pages.+ const ids = [...first.sessions, ...rest.sessions].map((s) => s.sessionId);+ expect(new Set(ids).size).toBe(ids.length);+ const archived = await api.listSessions(project, agent, {+ offset: 0,+ limit: 10,+ category: "archived",+ });+ expect(archived.sessions.every((s) => s.archived)).toBe(true);+ });++ it("serves a running Session's history with its live tail, and a finished one without", async () => {+ const store = resetStore({ lang: "en", signedIn: true });+ const running = store.f.sessions.find((s) => s.status === "running")!;+ const tail = await api.getMessages(running.sessionId, { kind: "tail", limit: 50 });+ expect(tail.page).toEqual({+ earlierTurns: 0,+ prior: expect.objectContaining({ elapsedMs: 0 }),+ });+ expect(tail.live).toBeDefined();+ expect(tail.live!.cursor).toMatch(/^g1-\d+$/);+ const done = store.f.sessions.find((s) => s.status === "idle")!;+ const full = await api.getMessages(done.sessionId);+ expect(full.live).toBeUndefined();+ expect(full.page).toBeUndefined();+ expect(full.messages[0]?.type).toBe("session_meta");+ const older = await api.getMessages(done.sessionId, {+ kind: "before",+ cursor: "1:0",+ limit: 50,+ });+ expect(older.messages).toEqual([]);+ });++ it("signs out on logout and back in on login, refusing the rest in between", async () => {+ resetStore({ lang: "en", signedIn: true });+ await api.logout();+ await expect(api.getMe()).rejects.toMatchObject({ status: 401 });+ await expect(api.getInstall()).resolves.toEqual({ installId: "gallery-demo" });+ await expect(api.login({ userId: "admin", password: "" })).rejects.toMatchObject({+ status: 401,+ });+ const signedIn = await api.login({ userId: "admin", password: "penguin" });+ expect(signedIn.user.userId).toBe("admin");+ await expect(api.getMe()).resolves.toMatchObject({ user: { userId: "admin" } });+ });++ it("mutates the store on writes the app shows", async () => {+ const store = resetStore({ lang: "en", signedIn: true });+ const project = store.f.project.projectId;+ const done = store.f.sessions.find((s) => s.status === "idle")!;+ const renamed = await api.patchSession(done.sessionId, { title: "Renamed" });+ expect(renamed.session.title).toBe("Renamed");+ await api.deleteSession(done.sessionId);+ expect(store.session(done.sessionId)).toBeUndefined();+ const created = await api.createSchedule(project, store.f.agents[0]!.agentId, {+ name: "hourly",+ prompt: "Check the corpus.",+ enabled: true,+ startAt: new Date().toISOString(),+ period: "1h",+ });+ expect(created.status).toBe("active");+ expect(+ (await api.listSchedules(project, store.f.agents[0]!.agentId)).schedules.some(+ (s) => s.name === "hourly",+ ),+ ).toBe(true);+ const models = await api.putDefaultModel(project, {+ provider: "anthropic",+ modelId: "claude-sonnet-5",+ });+ expect(models.defaultModel).toEqual({ provider: "anthropic", modelId: "claude-sonnet-5" });+ expect(store.f.models.models.find((m) => m.isDefault)?.modelId).toBe("claude-sonnet-5");+ });++ it("serves a Workspace file with its version marker through the fetch path", async () => {+ const store = resetStore({ lang: "en", signedIn: true });+ const session = store.f.sessions[0]!.sessionId;+ const response = await answerAsResponse(+ "GET",+ api.workspaceFileUrl(session, "src/rag.ts"),+ undefined,+ );+ expect(response.status).toBe(200);+ expect(response.headers.get("etag")).toMatch(/^".+"$/);+ expect(await response.text()).toContain("buildIndex");+ const missing = await answerAsResponse(+ "GET",+ api.workspaceFileUrl(session, "nope.txt"),+ undefined,+ );+ expect(missing.status).toBe(404);+ });++ it("refuses what needs a server behind it with one code the app turns into a toast", async () => {+ resetStore({ lang: "en", signedIn: true });+ await expect(api.createProject({ projectId: "x" })).rejects.toMatchObject({+ code: "demo_read_only",+ });+ await expect(api.startUpdateJob()).rejects.toMatchObject({ code: "demo_read_only" });+ });++ it("names an unrouted request by the one code the coverage test looks for", async () => {+ const store = resetStore({ lang: "en", signedIn: true });+ await expect(+ router.dispatch(store, "GET", "/api/nothing/here", undefined),+ ).rejects.toMatchObject({+ status: 404,+ code: UNMOCKED,+ });+ // A machine's route is this server's route.+ const answer = await router.dispatch(store, "GET", "/server/gpu-box/api/me", undefined);+ expect(answer.kind).toBe("json");+ });+});diff --git a/packages/ui-gallery/test/routes.test.ts b/packages/ui-gallery/test/routes.test.tsnew file mode 100644index 00000000..ec470eee--- /dev/null+++ b/packages/ui-gallery/test/routes.test.ts@@ -0,0 +1,89 @@+/**+ * The site's addresses: a path names a route, a surface page is `/s/<surface>`, a library page+ * is `/c/<topic>`, the fonts pages are `/fonts`, `/fonts/specimens` and `/fonts/licences`, and+ * every link built for another page carries the view state.+ */+import { describe, expect, it } from "vitest";+import { SURFACE_IDS } from "../src/app/surfaces";+import { TOPIC_IDS } from "../src/library/topics";+import {+ anchorOf,+ FONTS_PAGE_IDS,+ fontsHref,+ fontsPath,+ homeHref,+ parseRoute,+ surfaceHref,+ surfacePath,+ topicHref,+ topicPath,+} from "../src/lib/routes";+import { DEFAULT_STATE } from "../src/lib/url-state";++const PREFS = "theme=modern&mode=light&size=m&latin=theme&cjk=theme&lang=en&accent=neutral";++describe("parseRoute", () => {+ it("names the home route", () => {+ expect(parseRoute("/")).toEqual({ kind: "home" });+ expect(parseRoute("")).toEqual({ kind: "home" });+ });++ it("gives every surface a page at /s/<id>, and names what /s/<other> misses", () => {+ for (const id of SURFACE_IDS) {+ expect(parseRoute(surfacePath(id))).toEqual({ kind: "surface", id });+ }+ expect(parseRoute("/s/nope")).toEqual({ kind: "missing", id: "nope" });+ expect(parseRoute("/s/chat/extra")).toEqual({ kind: "unknown", path: "/s/chat/extra" });+ });++ it("gives every library topic a page at /c/<id>, and names what /c/<other> misses", () => {+ for (const id of TOPIC_IDS) {+ expect(parseRoute(topicPath(id))).toEqual({ kind: "topic", id });+ }+ expect(parseRoute("/c/nope")).toEqual({ kind: "missing", id: "nope" });+ // The one-page Foundations module is gone: its old address names nothing.+ expect(parseRoute("/c/foundations")).toEqual({ kind: "missing", id: "foundations" });+ expect(parseRoute("/c/buttons/extra")).toEqual({ kind: "unknown", path: "/c/buttons/extra" });+ });++ it("gives the fonts section three pages, the defaults at /fonts itself", () => {+ expect(FONTS_PAGE_IDS).toEqual(["defaults", "specimens", "licences"]);+ expect(fontsPath("defaults")).toBe("/fonts");+ expect(fontsPath("specimens")).toBe("/fonts/specimens");+ for (const page of FONTS_PAGE_IDS) {+ expect(parseRoute(fontsPath(page))).toEqual({ kind: "fonts", page });+ }+ expect(parseRoute("/fonts/")).toEqual({ kind: "fonts", page: "defaults" });+ expect(parseRoute("/fonts/nope")).toEqual({ kind: "missing", id: "nope" });+ // The retired routes name nothing now.+ expect(parseRoute("/embed").kind).toBe("unknown");+ expect(parseRoute("/screens/chat").kind).toBe("unknown");+ });+});++describe("links between pages", () => {+ const state = { ...DEFAULT_STATE, theme: "modern" as const };++ it("build a surface page's address with the view state", () => {+ expect(surfaceHref("", state, "models")).toBe(`/s/models?${PREFS}`);+ expect(surfaceHref("/gallery", state, "chat-new")).toBe(`/gallery/s/chat-new?${PREFS}`);+ });++ it("build a library page's address, with a group in the hash", () => {+ expect(topicHref("", state, "buttons")).toBe(`/c/buttons?${PREFS}`);+ expect(topicHref("", state, "colour", "surfaces")).toBe(`/c/colour?${PREFS}#surfaces`);+ });++ it("build the home and the fonts pages the same way", () => {+ expect(homeHref("", state, "surfaces")).toBe(`/?${PREFS}#surfaces`);+ expect(fontsHref("/base", state, "defaults")).toBe(`/base/fonts?${PREFS}`);+ expect(fontsHref("/base", state, "licences")).toBe(`/base/fonts/licences?${PREFS}`);+ });++ it("read the anchor a hash names", () => {+ expect(anchorOf("#colour")).toBe("colour");+ expect(anchorOf("#%E5%AF%B9%E8%AF%9D")).toBe("对话");+ expect(anchorOf("#")).toBeNull();+ expect(anchorOf("")).toBeNull();+ });+});diff --git a/packages/ui-gallery/test/surfaces.test.ts b/packages/ui-gallery/test/surfaces.test.tsnew file mode 100644index 00000000..78a11e7b--- /dev/null+++ b/packages/ui-gallery/test/surfaces.test.ts@@ -0,0 +1,106 @@+/**+ * The app's surfaces: every one in exactly one group, named in both dictionaries, opening on a+ * route the demo store can answer, and the ones the contract names all present.+ */+import { describe, expect, it } from "vitest";+import { IDS } from "../src/app/mock/ids";+import { resetStore } from "../src/app/mock/store";+import {+ HOME_SURFACE,+ isSurfaceId,+ SURFACE_GROUP_IDS,+ SURFACE_GROUPS,+ SURFACE_IDS,+ SURFACES,+ surfaceById,+} from "../src/app/surfaces";+import { zh } from "../src/strings";+import { en } from "../src/strings-en";++describe("the surfaces", () => {+ it("are each in exactly one group, the groups in their fixed order", () => {+ const placed = SURFACE_GROUPS.flatMap((group) => group.surfaces.map((s) => s.id));+ expect([...placed].sort()).toEqual([...SURFACE_IDS].sort());+ expect(new Set(placed).size).toBe(placed.length);+ expect(SURFACE_GROUPS.map((group) => group.id)).toEqual([...SURFACE_GROUP_IDS]);+ for (const group of SURFACE_GROUPS) expect(group.surfaces.length, group.id).toBeGreaterThan(0);+ });++ it("cover the surfaces the owner named, and the home page frames one of them", () => {+ for (const id of [+ "chat",+ "agents",+ "plugins",+ "models",+ "usage",+ "benchmark",+ "schedules",+ "settings",+ "login",+ ]) {+ expect(isSurfaceId(id), id).toBe(true);+ }+ expect(surfaceById(HOME_SURFACE)).toBeDefined();+ expect(surfaceById("nope")).toBeUndefined();+ });++ it("have a title, a description and a how-to in both languages, and a group name", () => {+ for (const surface of SURFACES) {+ for (const dict of [zh, en]) {+ const copy = dict.surfaces[surface.id];+ expect(copy.title.trim(), surface.id).not.toBe("");+ expect(copy.description.trim(), surface.id).not.toBe("");+ expect(copy.how.trim(), surface.id).not.toBe("");+ }+ }+ for (const id of SURFACE_GROUP_IDS) {+ expect(zh.surfaceGroups[id].trim(), id).not.toBe("");+ expect(en.surfaceGroups[id].trim(), id).not.toBe("");+ }+ });++ it("open on routes the demo store answers: the Sessions, Agents, plugins and Benchmarks they name exist", () => {+ const store = resetStore({ lang: "en", signedIn: true });+ for (const surface of SURFACES) {+ expect(surface.route.startsWith("/"), surface.id).toBe(true);+ const session = /^\/chat\/([^/?]+)/.exec(surface.route)?.[1];+ if (session) expect(store.session(session), surface.id).toBeDefined();+ const agent = /^\/agents\/([^/?]+)/.exec(surface.route)?.[1];+ if (agent)+ expect(+ store.f.agents.some((a) => a.agentId === agent),+ surface.id,+ ).toBe(true);+ const benchmark = /^\/benchmark\/([^/?]+)/.exec(surface.route)?.[1];+ if (benchmark)+ expect(+ store.f.benchmarks.some((b) => b.id === benchmark),+ surface.id,+ ).toBe(true);+ const plugin = /^\/plugins\/registry\/(.+)$/.exec(surface.route)?.[1];+ if (plugin) {+ expect(+ store.f.library.groups.some((g) => g.plugins.some((p) => p.name === plugin)),+ surface.id,+ ).toBe(true);+ }+ }+ // The login surface is the one that starts signed out; the settings one opens its dialog.+ expect(surfaceById("login")?.signedOut).toBe(true);+ expect(surfaceById("settings")?.open).toBe("settings");+ expect(surfaceById("settings-appearance")?.open).toBe("settings.appearance");+ expect(SURFACES.filter((s) => s.signedOut).map((s) => s.id)).toEqual(["login"]);+ });++ it("spell the store's ids in their routes exactly (the file carries no import, so Node can read it)", () => {+ expect(surfaceById("chat")?.route).toBe(`/chat/${IDS.sessions.done}`);+ expect(surfaceById("chat-running")?.route).toBe(`/chat/${IDS.sessions.runningTool}`);+ expect(surfaceById("chat-thinking")?.route).toBe(`/chat/${IDS.sessions.thinking}`);+ expect(surfaceById("chat-approval")?.route).toBe(`/chat/${IDS.sessions.approval}`);+ expect(surfaceById("settings")?.route).toBe(`/chat/${IDS.sessions.done}`);+ expect(surfaceById("agent-settings")?.route).toBe(`/agents/${IDS.agents.docs}`);+ expect(surfaceById("schedules")?.route).toBe(`/agents/${IDS.agents.docs}?tab=schedules`);+ expect(surfaceById("plugin-detail")?.route).toBe(`/plugins/registry/${IDS.plugins.registry}`);+ expect(surfaceById("benchmark-detail")?.route).toBe(`/benchmark/${IDS.benchmarks.docs}`);+ });+});diff --git a/packages/ui-gallery/test/text-size.test.ts b/packages/ui-gallery/test/text-size.test.tsnew file mode 100644index 00000000..f586669d--- /dev/null+++ b/packages/ui-gallery/test/text-size.test.ts@@ -0,0 +1,111 @@+/**+ * The text size is real, and only the framed app and the boards follow it. The gallery's vitest+ * is node-only, so the proof is the source contract, each link of it: the size control writes+ * `<html style="font-size">` through the package's own `applyThemeAttributes` (which the app's+ * boot script and theme provider also use), the five sizes are 14 / 15 / 16 / 18 / 20 px and+ * the top bar names them, every frame takes the same `size=` (and the font pairing) in its own+ * URL, and the chrome's stylesheet has no rem or em in it — a px-sized chrome cannot move when+ * the root does.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import {+ applyThemeAttributes,+ DEFAULT_TEXT_SIZE,+ FONT_CJK_OPTIONS,+ FONT_LATIN_OPTIONS,+ TEXT_SIZE_PX,+} from "@prismshadow/penguin-ui/boot";+import { appFrameSrc } from "../src/app/frame";+import {+ CJK_FONTS,+ LATIN_FONTS,+ TEXT_SIZE_PX_NUMBER,+ TEXT_SIZES,+ fontLabel,+} from "../src/lib/themes";+import { DEFAULT_STATE } from "../src/lib/url-state";+import { zh } from "../src/strings";+import { en } from "../src/strings-en";++const read = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8");++/** A root as `applyThemeAttributes` sees it: a class list, a dataset and an inline style. */+function fakeRoot() {+ const classes = new Set<string>();+ return {+ classList: {+ toggle: (name: string, force?: boolean) => {+ if (force ?? !classes.has(name)) classes.add(name);+ else classes.delete(name);+ return classes.has(name);+ },+ },+ dataset: {} as Record<string, string | undefined>,+ style: {} as Record<string, string>,+ } as unknown as HTMLElement;+}++describe("the text size", () => {+ it("has five real steps, 14 / 15 / 16 / 18 / 20 px, opening on 16", () => {+ expect(TEXT_SIZES).toEqual(["xs", "s", "m", "l", "xl"]);+ expect(TEXT_SIZES.map((size) => TEXT_SIZE_PX_NUMBER[size])).toEqual([14, 15, 16, 18, 20]);+ for (const size of TEXT_SIZES)+ expect(TEXT_SIZE_PX[size]).toBe(`${TEXT_SIZE_PX_NUMBER[size]}px`);+ expect(DEFAULT_STATE.size).toBe(DEFAULT_TEXT_SIZE);+ // Both dictionaries name every step.+ for (const size of TEXT_SIZES) {+ expect(zh.rail.sizeNames[size].trim()).not.toBe("");+ expect(en.rail.sizeNames[size].trim()).not.toBe("");+ }+ });++ it("is written onto <html> by the package's own contract, per step", () => {+ const root = fakeRoot();+ for (const size of TEXT_SIZES) {+ applyThemeAttributes(root, { textSize: size });+ expect(root.style.fontSize).toBe(TEXT_SIZE_PX[size]);+ }+ // The provider applies the state's size and pairing through that same function.+ const state = read("../src/state.tsx");+ expect(state).toMatch(/applyThemeAttributes\(root, \{[^}]*textSize: state\.size/s);+ expect(state).toMatch(/fontLatin: state\.latin/);+ expect(state).toMatch(/fontCjk: state\.cjk/);+ });++ it("reaches every framed app through `size=`, `latin=` and `cjk=` in its own URL", () => {+ for (const size of TEXT_SIZES) {+ const src = appFrameSrc(+ "",+ { ...DEFAULT_STATE, size, latin: "misans", cjk: "noto-sans-sc" },+ { route: "/chat" },+ );+ expect(src).toContain(`size=${size}`);+ expect(src).toContain("latin=misans");+ expect(src).toContain("cjk=noto-sans-sc");+ }+ // The frames' src is built by that one function, never by hand.+ expect(read("../src/chrome/app-frame.tsx")).toMatch(/appFrameSrc\(/);+ });++ it("offers the app's own font pairings, named as the app names them", () => {+ expect(LATIN_FONTS).toEqual(FONT_LATIN_OPTIONS.map((option) => option.id));+ expect(CJK_FONTS).toEqual(FONT_CJK_OPTIONS.map((option) => option.id));+ expect(LATIN_FONTS[0]).toBe("theme");+ const words = { theme: zh.rail.fontTheme, system: zh.rail.fontSystem };+ expect(fontLabel("theme", words)).toBe("随主题");+ expect(fontLabel("system", words)).toBe("系统");+ expect(fontLabel("mona-sans", words)).toBe("Mona Sans");+ expect(fontLabel("noto-sans-sc", words)).toBe("Noto Sans SC");+ });++ it("never moves the chrome: chrome.css sets no rem or em length", () => {+ const css = read("../src/chrome.css").replace(/\/\*[\s\S]*?\*\//g, "");+ const relative = [...css.matchAll(/-?\d*\.?\d+r?em\b/g)].map((m) => m[0]);+ expect(relative).toEqual([]);+ // The boards are the one place on a gallery page the root size may show, and they read the+ // theme's own rem-based body size rather than a chrome value.+ expect(css).toMatch(/\.g-preview \{[^}]*font-size: var\(--ui-text-body-size/s);+ });+});diff --git a/packages/ui-gallery/test/theme-fonts.test.ts b/packages/ui-gallery/test/theme-fonts.test.tsnew file mode 100644index 00000000..344a2184--- /dev/null+++ b/packages/ui-gallery/test/theme-fonts.test.ts@@ -0,0 +1,30 @@+/**+ * The fonts page's defaults table prints what the package states for every theme, and names the+ * platform's face only where the package does.+ */+import { THEME_IDS } from "@prismshadow/penguin-ui";+import { SYSTEM_FONT, THEME_FONTS } from "@prismshadow/penguin-ui/boot";+import { describe, expect, it } from "vitest";+import { isSystemFont, themeFontRows } from "../src/lib/theme-fonts";+import { zh } from "../src/strings";+import { en } from "../src/strings-en";++describe("the theme fonts table", () => {+ it("has one row per theme, in the package's order, with the package's names", () => {+ const rows = themeFontRows();+ expect(rows.map((row) => row.theme)).toEqual([...THEME_IDS]);+ for (const row of rows) {+ expect(row.latin).toBe(THEME_FONTS[row.theme].latin);+ expect(row.cjk).toBe(THEME_FONTS[row.theme].cjk);+ expect(row.mono).toBe(THEME_FONTS[row.theme].mono);+ for (const name of [row.latin, row.cjk, row.mono]) expect(name.trim()).not.toBe("");+ }+ });++ it("tells the platform's face from a bundled one, and both dictionaries word it", () => {+ expect(isSystemFont(SYSTEM_FONT)).toBe(true);+ expect(isSystemFont("MiSans")).toBe(false);+ expect(zh.fonts.system.trim()).not.toBe("");+ expect(en.fonts.system.trim()).not.toBe("");+ });+});diff --git a/packages/ui-gallery/test/url-state.test.ts b/packages/ui-gallery/test/url-state.test.tsnew file mode 100644index 00000000..c089a033--- /dev/null+++ b/packages/ui-gallery/test/url-state.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_STATE,+ formatGalleryQuery,+ parseGalleryState,+ PREF_KEYS,+ resolveMode,+} from "../src/lib/url-state";++const PREFS = "theme=github&mode=light&size=m&latin=theme&cjk=theme&lang=en&accent=neutral";++describe("gallery URL state", () => {+ it("reads every field and round-trips through the canonical query", () => {+ const search =+ "?theme=geek&mode=dark&size=xl&latin=mona-sans&cjk=noto-sans-sc&lang=zh&accent=blue&view=phone";+ const state = parseGalleryState(search);+ expect(state).toEqual({+ theme: "geek",+ mode: "dark",+ size: "xl",+ latin: "mona-sans",+ cjk: "noto-sans-sc",+ lang: "zh",+ accent: "blue",+ view: "phone",+ });+ expect(parseGalleryState(formatGalleryQuery(state))).toEqual(state);+ });++ it("opens on the 16px size, the theme's own faces and the theme's own accent", () => {+ expect(DEFAULT_STATE.size).toBe("m");+ expect(DEFAULT_STATE.latin).toBe("theme");+ expect(DEFAULT_STATE.cjk).toBe("theme");+ expect(PREF_KEYS).toEqual(["theme", "mode", "size", "latin", "cjk", "lang", "accent"]);+ });++ it("always writes the seven preferences and the view only when set", () => {+ expect(formatGalleryQuery(DEFAULT_STATE)).toBe(`?${PREFS}`);+ expect(formatGalleryQuery({ ...DEFAULT_STATE, view: "phone" })).toBe(`?${PREFS}&view=phone`);+ });++ it("ignores the retired compare param: a link quoted with it opens on one frame", () => {+ expect(parseGalleryState("?compare=1")).toEqual(DEFAULT_STATE);+ expect(parseGalleryState("?compare=chat")).toEqual(DEFAULT_STATE);+ expect(formatGalleryQuery(parseGalleryState("?compare=1"))).not.toContain("compare");+ });++ it("keeps route params right after the preferences, in the order given", () => {+ expect(formatGalleryQuery({ ...DEFAULT_STATE, theme: "modern" }, { a: "1", b: "2" })).toBe(+ "?theme=modern&mode=light&size=m&latin=theme&cjk=theme&lang=en&accent=neutral&a=1&b=2",+ );+ });++ it("still opens a link quoted with the retired three-step size, by its pixels", () => {+ expect(parseGalleryState("?size=sm").size).toBe("m");+ expect(parseGalleryState("?size=md").size).toBe("l");+ expect(parseGalleryState("?size=lg").size).toBe("xl");+ expect(parseGalleryState("?tier=lg").size).toBe("xl");+ expect(parseGalleryState("?tier=md&size=xs").size).toBe("xs");+ expect(formatGalleryQuery(parseGalleryState("?size=md"))).toContain("size=l");+ });++ it("falls back to the remembered value, then the default, for anything unknown", () => {+ expect(+ parseGalleryState(+ "?theme=nope&mode=sepia&size=xxl&latin=comic&cjk=nope&lang=fr&accent=plaid&view=tv",+ ),+ ).toEqual(DEFAULT_STATE);+ expect(+ parseGalleryState("?theme=nope", { theme: "modern", lang: "zh", latin: "misans", size: "l" }),+ ).toMatchObject({ theme: "modern", lang: "zh", latin: "misans", size: "l" });+ // The URL beats the remembered value.+ expect(parseGalleryState("?theme=geek", { theme: "modern" }).theme).toBe("geek");+ });++ it("keeps an accent preset whichever theme is active, so switching themes never loses it", () => {+ expect(parseGalleryState("?theme=geek&accent=blue")).toMatchObject({+ theme: "geek",+ accent: "blue",+ });+ });++ it("resolves system mode against the OS preference", () => {+ expect(resolveMode("system", true)).toBe("dark");+ expect(resolveMode("system", false)).toBe("light");+ expect(resolveMode("light", true)).toBe("light");+ });+});diff --git a/packages/ui-gallery/tsconfig.json b/packages/ui-gallery/tsconfig.jsonnew file mode 100644index 00000000..aab28a20--- /dev/null+++ b/packages/ui-gallery/tsconfig.json@@ -0,0 +1,13 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "types": ["node", "vite/client"],+ "jsx": "react-jsx",+ "useDefineForClassFields": true,+ "paths": {+ "@prismshadow/penguin-server/api": ["../server/src/api/types.ts"]+ }+ },+ "include": ["src", "test", "vite.config.ts", "vitest.config.ts"]+}diff --git a/packages/ui-gallery/vite.config.ts b/packages/ui-gallery/vite.config.tsnew file mode 100644index 00000000..31110087--- /dev/null+++ b/packages/ui-gallery/vite.config.ts@@ -0,0 +1,118 @@+/**+ * Vite config: the component gallery (React SPA + Tailwind CSS 4), a local dev tool, plus the+ * framed Web App as a second page.+ *+ * Three documents come out of one build: `index.html`, the gallery site; `app.html`, the real+ * Web App mounted against an in-browser mock of its API (src/app); and `lib.html`, one component+ * library board made of the app's real components (src/library). The app's own source is+ * imported from `packages/web/src`; its network layer is swapped for the mock by+ * `mockWebNetwork()` (src/app/mock/vite-plugin.ts), and the two inline boot scripts — the+ * storage seed that gives a frame its own preferences, then the app's own pre-paint script,+ * generated from the package so neither can drift — are prepended to both framed documents at+ * serve and build time. The app's highlighting worker needs ES-format workers, as in the app's config,+ * and React is deduplicated so the app and the gallery never load two copies.+ *+ * `@prismshadow/penguin-ui` resolves to the live `packages/ui/src` through the workspace link;+ * `penguinUi()` emits the bundled fonts' licence texts beside a build. Port 7372 is fixed and+ * strict: screenshot runs and quoted feedback links name it. BASE_PATH lets a static build be+ * served under a subpath. The vitest config stays separate (vitest's embedded vite types+ * conflict with vite 7's).+ *+ * The package source and the app's live outside this Vite root, which the dev server's file+ * watcher does not cover by default; the plugin below watches both.+ */+import react from "@vitejs/plugin-react";+import tailwindcss from "@tailwindcss/vite";+import { fileURLToPath } from "node:url";+import { defineConfig } from "vite";+import type { Plugin } from "vite";+import { BOOT_SCRIPT } from "../ui/src/boot";+import { penguinUi } from "../ui/src/vite-plugin";+import { dropNonWoff2FontSources } from "../web/vite.config";+import { storageSeedScript } from "./src/app/frame";+import { mockWebNetwork } from "./src/app/mock/vite-plugin";++const at = (rel: string) => fileURLToPath(new URL(rel, import.meta.url));++function watchPackageSources(): Plugin {+ const roots = [at("../ui/src/"), at("../web/src/")];+ const stylesheets = [+ at("./src/styles.css"),+ at("./src/app/app.css"),+ at("./src/library/library.css"),+ ];+ return {+ name: "penguin:gallery-watch-sources",+ configureServer(server) {+ for (const root of roots) server.watcher.add(root);+ // Tailwind rescans a stylesheet's sources only when that stylesheet is transformed again,+ // and a file added outside the Vite root does not trigger that — a new component would+ // render without its utility classes until a restart. Invalidate the sheets and reload.+ server.watcher.on("add", (file) => {+ if (!roots.some((root) => file.startsWith(root)) || !/\.(tsx?|css)$/.test(file)) return;+ for (const sheet of stylesheets) {+ for (const mod of server.moduleGraph.getModulesByFile(sheet) ?? []) {+ server.moduleGraph.invalidateModule(mod);+ }+ }+ server.ws.send({ type: "full-reload" });+ });+ },+ };+}++/** The framed documents, which open with two inline scripts, in the order a frame needs them. */+const FRAME_DOCUMENTS = ["app.html", "lib.html"];++function frameDocument(): Plugin {+ const scripts = `${storageSeedScript()};${BOOT_SCRIPT}`;+ return {+ name: "penguin:gallery-frame-document",+ transformIndexHtml: {+ order: "pre",+ handler(_html, ctx) {+ if (!FRAME_DOCUMENTS.some((name) => ctx.filename.endsWith(name))) return;+ return [{ tag: "script", children: scripts, injectTo: "head-prepend" }];+ },+ },+ };+}++/** KaTeX's woff and truetype fallbacks stay out of the bundle, as in the app's own build. */+function katexWoff2Only(): Plugin {+ return {+ name: "penguin:katex-woff2-only",+ enforce: "pre",+ transform(code, id) {+ if (!id.includes("/katex/dist/") || !id.includes(".css")) return null;+ const next = dropNonWoff2FontSources(code);+ return next === code ? null : { code: next, map: null };+ },+ };+}++export default defineConfig({+ base: process.env.BASE_PATH ?? "/",+ plugins: [+ mockWebNetwork(),+ react(),+ tailwindcss(),+ penguinUi(),+ katexWoff2Only(),+ frameDocument(),+ watchPackageSources(),+ ],+ resolve: { dedupe: ["react", "react-dom"] },+ build: {+ // Never inline a font, as in the web app: a small slice would otherwise sit in the+ // stylesheet as a data: URI, whatever theme is shown.+ assetsInlineLimit: (file) => (file.endsWith(".woff2") ? false : undefined),+ rollupOptions: {+ input: { gallery: at("./index.html"), app: at("./app.html"), library: at("./lib.html") },+ },+ },+ worker: { format: "es" },+ // Fixed PenguinHarness dev port; the allocation table lives in core's internal/ports.ts.+ server: { port: 7372, strictPort: true },+ preview: { port: 7372, strictPort: true },+});diff --git a/packages/ui-gallery/vitest.config.ts b/packages/ui-gallery/vitest.config.tsnew file mode 100644index 00000000..30c71389--- /dev/null+++ b/packages/ui-gallery/vitest.config.ts@@ -0,0 +1,14 @@+/**+ * Vitest config kept separate from vite.config.ts (vitest's embedded vite types conflict with+ * this package's vite 7 plugin types). A node environment suffices: the tests cover the+ * gallery's pure modules and the demo store, which never touches the DOM. The network swap+ * plugin is applied here too, so a test can import the Web App's endpoint wrappers and drive+ * them against the mock — that is how the coverage test walks every endpoint.+ */+import { defineConfig } from "vitest/config";+import { mockWebNetwork } from "./src/app/mock/vite-plugin";++export default defineConfig({+ plugins: [mockWebNetwork()],+ test: { environment: "node" },+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonnew file mode 100644index 00000000..f75cf74e--- /dev/null+++ b/packages/ui/package.json@@ -0,0 +1,52 @@+{+ "name": "@prismshadow/penguin-ui",+ "version": "0.2.13",+ "private": true,+ "type": "module",+ "description": "PenguinHarness shared UI: design tokens, the three themes, bundled fonts and the component set the Web App and the gallery render.",+ "sideEffects": [+ "**/*.css"+ ],+ "exports": {+ ".": "./src/index.ts",+ "./theme.css": {+ "style": "./src/theme.css",+ "default": "./src/theme.css"+ },+ "./themes/*": "./src/themes/*",+ "./fonts.css": {+ "style": "./src/fonts/index.css",+ "default": "./src/fonts/index.css"+ },+ "./boot": "./src/boot.ts",+ "./fonts-credits": "./src/fonts/credits.ts",+ "./testing": "./src/testing/index.ts"+ },+ "scripts": {+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "vitest run",+ "sync:font-licenses": "node scripts/sync-font-licenses.mjs",+ "fonts:misans": "uv run scripts/build-misans.py"+ },+ "peerDependencies": {+ "react": "^19.1.0",+ "react-dom": "^19.1.0"+ },+ "dependencies": {+ "@fontsource-variable/ibm-plex-sans": "^5.3.0",+ "@fontsource-variable/jetbrains-mono": "^5.3.0",+ "@fontsource-variable/mona-sans": "^5.3.0",+ "@fontsource-variable/noto-sans-sc": "^5.3.0",+ "@fontsource/commit-mono": "^5.3.0",+ "@fontsource/ibm-plex-sans-condensed": "^5.3.0"+ },+ "devDependencies": {+ "@types/node": "^24.0.0",+ "@types/react": "^19.1.0",+ "@types/react-dom": "^19.1.0",+ "react": "^19.1.0",+ "react-dom": "^19.1.0",+ "typescript": "^5.6.0",+ "vitest": "^3.2.6"+ }+}diff --git a/packages/ui/scripts/build-misans.py b/packages/ui/scripts/build-misans.pynew file mode 100644index 00000000..64a4c796--- /dev/null+++ b/packages/ui/scripts/build-misans.py@@ -0,0 +1,373 @@+#!/usr/bin/env python3+# /// script+# requires-python = ">=3.10"+# dependencies = ["fonttools==4.65.0", "brotli==1.2.0"]+# ///+"""+Frost's MiSans web font slices, cut from Xiaomi's official MiSans package.++MiSans (https://hyperos.mi.com/font/) has no official npm package, so unlike every other face the+package bundles it cannot arrive as a dependency. This script turns the official download into+what `src/fonts/misans/` ships:++- `misans-<weight>-<slice>.woff2`: MiSans Regular as CSS weight 400 and MiSans Medium as 500, each+ cut into `unicode-range` slices. The slices follow the partition fontsource ships for Noto Sans SC+ (Google Fonts' frequency-ordered slicing, read from @fontsource-variable/noto-sans-sc's+ `unicode.json`), so a zh page downloads about as many MiSans slices under Frost as Noto slices+ under the other themes. One `extra` slice holds MiSans's other non-ideograph characters (Greek,+ more Cyrillic, number forms, box drawing, ...). Ideographs outside the partition, about 15,500+ rare ones worth 2.5 MB per weight, are left out and fall back to the system CJK face.+- `misans.css`: one `@font-face` per slice, its `unicode-range` computed from the characters the+ slice actually holds, so a browser never fetches a slice for a character it lacks.++What subsetting changes (the MiSans licence forbids adapting the font, so this is kept to+delivery): a slice holds the glyphs its characters reach, and each of those glyphs is copied+unchanged, including outline, hinting instructions, horizontal and vertical metrics and glyph+name. Every OpenType feature is kept along with the glyphs it reaches, and every name record is+kept, so each file still carries Xiaomi's copyright notice and the MiSans family name. Only the+tables that index glyphs (cmap, loca, hmtx/vmtx, GSUB/GPOS/GDEF, post) are rebuilt for the smaller+glyph set, and the DSIG table goes, because no digital signature survives any repackaging. WOFF2+is a lossless container. The full TTF or OTF is never written into the repository.++Usage, from the repository root:++ uv run packages/ui/scripts/build-misans.py <MiSans.zip> rebuild src/fonts/misans/+ uv run packages/ui/scripts/build-misans.py <MiSans.zip> --check exit 1 if the committed files differ++<MiSans.zip> is the official package, https://hyperos.mi.com/font-download/MiSans.zip, downloaded+through the site, which asks you to accept the MiSans licence first. The script refuses a package+whose Regular or Medium TTF differs from the files pinned in FACES: adopting a new MiSans release+is a deliberate change to the pins, reviewed with the slices it produces. Run `pnpm install` first+so the partition is present in node_modules.+"""++from __future__ import annotations++import argparse+import concurrent.futures+import filecmp+import hashlib+import io+import json+import os+import shutil+import sys+import tempfile+import zipfile+from pathlib import Path++from fontTools import subset+from fontTools.ttLib import TTFont++PACKAGE_DIR = Path(__file__).resolve().parent.parent+OUT_DIR = PACKAGE_DIR / "src" / "fonts" / "misans"+PARTITION_DIR = PACKAGE_DIR / "node_modules" / "@fontsource-variable" / "noto-sans-sc"++FAMILY = "MiSans"+PACKAGE_URL = "https://hyperos.mi.com/font-download/MiSans.zip"++# CSS weight -> (member of the official zip, its sha256). MiSans names its own weights on a+# 150-700 axis where Regular is 330 and Medium 380; they are the faces a 400 and a 500 request want.+FACES: dict[int, tuple[str, str]] = {+ 400: (+ "MiSans/ttf/MiSans-Regular.ttf",+ "9c120f0a849bc0aa5048daae2a3c0f6eecd828b5b33fce682a9622833f5feea6",+ ),+ 500: (+ "MiSans/ttf/MiSans-Medium.ttf",+ "b03e98374e971594b0b7a9706d0704241f76e1b88556cdda79c5039ef8a638d1",+ ),+}++# Left out of the `extra` slice: the ideographs the partition does not carry.+EXCLUDED_FROM_EXTRA = (+ (0x3400, 0x4DBF), # CJK Unified Ideographs Extension A+ (0x4E00, 0x9FFF), # CJK Unified Ideographs+ (0xF900, 0xFAFF), # CJK Compatibility Ideographs+ (0x20000, 0x3FFFF), # Supplementary and Tertiary Ideographic Planes+)++EXTRA_SLICE = "extra"+++def subset_options() -> subset.Options:+ options = subset.Options()+ options.flavor = "woff2"+ options.layout_features = ["*"] # every feature, e.g. tnum for tabular figures+ options.name_IDs = ["*"] # every name record: copyright, family, version, manufacturer+ options.name_languages = ["*"]+ options.name_legacy = True+ options.legacy_cmap = True+ options.symbol_cmap = True+ options.glyph_names = True+ options.notdef_outline = True+ options.hinting = True+ options.prune_unicode_ranges = False # OS/2 keeps the original font's declared ranges+ options.prune_codepage_ranges = False+ options.recalc_bounds = False+ options.recalc_timestamp = False+ options.harfbuzz_repacker = False # the same table packing whether or not uharfbuzz is installed+ return options+++def parse_range(text: str) -> set[int]:+ """A CSS `unicode-range` value ("U+0020-007e,U+00a0") as a set of code points."""+ points: set[int] = set()+ for part in text.split(","):+ part = part.strip().upper().removeprefix("U+")+ if not part:+ continue+ if "-" in part:+ start, end = part.split("-")+ points.update(range(int(start, 16), int(end, 16) + 1))+ else:+ points.add(int(part, 16))+ return points+++def format_range(points: list[int]) -> str:+ """Sorted code points as a compact `unicode-range` value."""+ spans: list[str] = []+ start = previous = points[0]+ for point in points[1:] + [-1]:+ if point == previous + 1:+ previous = point+ continue+ spans.append(f"U+{start:04X}" if start == previous else f"U+{start:04X}-{previous:04X}")+ start = previous = point+ return ", ".join(spans)+++def load_partition() -> tuple[list[tuple[str, set[int]]], str]:+ unicode_json = PARTITION_DIR / "unicode.json"+ if not unicode_json.exists():+ sys.exit(f"build-misans: {unicode_json} is missing; run `pnpm install` first")+ raw: dict[str, str] = json.loads(unicode_json.read_text(encoding="utf-8"))+ version = json.loads((PARTITION_DIR / "package.json").read_text(encoding="utf-8"))["version"]+ # Google's ranges overlap: a numbered CJK slice also lists the ASCII and punctuation that+ # co-occur with its characters, and the script slices (latin, latin-ext, ...) come last. A+ # browser tries overlapping faces last-declared first, so under the Noto CSS a code point is+ # fetched from the last slice that lists it. Assigning each code point to that slice alone+ # gives slices that load the same way and share almost nothing. The exception: the subsetter+ # adds a requested character's Bidi mirror to the cut, so the pairs ≤ ≥, 〈 〉 and < > are+ # held, and declared, by two slices each. That is harmless: a browser takes the last-declared+ # face, as it does under Noto.+ taken: set[int] = set()+ slices: list[tuple[str, set[int]]] = []+ for key, value in reversed(list(raw.items())):+ points = parse_range(value) - taken+ taken |= points+ slices.append((key.strip("[]"), points))+ slices.reverse()+ return slices, version+++def read_faces(package: Path) -> dict[int, bytes]:+ faces: dict[int, bytes] = {}+ with zipfile.ZipFile(package) as archive:+ for weight, (member, expected) in FACES.items():+ try:+ data = archive.read(member)+ except KeyError:+ sys.exit(f"build-misans: {package} has no {member}; is it the official MiSans.zip?")+ actual = hashlib.sha256(data).hexdigest()+ if actual != expected:+ sys.exit(+ f"build-misans: {member} is sha256 {actual}, not the pinned {expected}.\n"+ "A different MiSans release: update FACES deliberately and review the output."+ )+ faces[weight] = data+ return faces+++_FACE_DATA: dict[int, bytes] = {}+++def _init_worker(faces: dict[int, bytes]) -> None:+ """Hands each worker the TTFs `build()` already read and verified."""+ _FACE_DATA.update(faces)+++def _cut(job: tuple[int, str, list[int]]) -> tuple[int, str, bytes, list[int]]:+ weight, name, points = job+ options = subset_options()+ font = subset.load_font(io.BytesIO(_FACE_DATA[weight]), options, dontLoadGlyphNames=False)+ subsetter = subset.Subsetter(options)+ subsetter.populate(unicodes=points)+ subsetter.subset(font)+ # The subsetter keeps name IDs below 256 but drops the higher ones nothing references any more+ # (the labels of stylistic sets a CJK slice has no glyphs for). Every record goes back, so each+ # slice carries the source's name table whole.+ font["name"].names = TTFont(io.BytesIO(_FACE_DATA[weight]), lazy=True)["name"].names+ out = io.BytesIO()+ subset.save_font(font, out, options)+ font.close()+ data = out.getvalue()+ problems, held = compare_with_source(_FACE_DATA[weight], data)+ if problems:+ raise RuntimeError(f"{FAMILY} {weight} {name} is not a faithful cut:\n " + "\n ".join(problems[:20]))+ return weight, name, data, held+++def compare_with_source(source_data: bytes, cut_data: bytes) -> tuple[list[str], list[int]]:+ """+ Reads the finished WOFF2 back and holds it against the official TTF: every character it maps,+ and every glyph it carries (outline points, on-curve flags, contours, components, hinting+ instructions, advance and side bearings, both directions), must be the source's own, and so+ must every name record. Returns the differences and the characters the cut holds.+ """+ source = TTFont(io.BytesIO(source_data), lazy=True)+ cut = TTFont(io.BytesIO(cut_data))+ problems: list[str] = []+ source_cmap, cut_cmap = source.getBestCmap(), cut.getBestCmap()+ for point, glyph in cut_cmap.items():+ if source_cmap.get(point) != glyph:+ problems.append(f"U+{point:04X} maps to {glyph}, the source maps it to {source_cmap.get(point)}")++ def outline(font: TTFont, glyph_name: str) -> tuple:+ glyf = font["glyf"]+ glyph = glyf[glyph_name]+ glyph.expand(glyf)+ program = glyph.program.getBytecode() if hasattr(glyph, "program") else b""+ if glyph.isComposite():+ parts = tuple(+ (c.glyphName, c.x, c.y, getattr(c, "transform", None), c.flags & 0x0204)+ for c in glyph.components+ )+ return ("composite", parts, program)+ if glyph.numberOfContours == 0:+ return ("empty",)+ coordinates, ends, flags = glyph.getCoordinates(glyf)+ return ("simple", tuple(coordinates), tuple(ends), tuple(f & 0x01 for f in flags), program)++ for glyph_name in cut.getGlyphOrder():+ if outline(source, glyph_name) != outline(cut, glyph_name):+ problems.append(f"glyph {glyph_name}: outline or instructions differ")+ for table in ("hmtx", "vmtx"):+ if table in source and source[table][glyph_name] != cut[table][glyph_name]:+ problems.append(f"glyph {glyph_name}: {table} metrics differ")++ def names(font: TTFont) -> set[tuple]:+ return {+ (r.platformID, r.platEncID, r.langID, r.nameID, r.toUnicode()) for r in font["name"].names+ }++ if names(source) != names(cut):+ problems.append("the name table differs from the source's")+ if source["OS/2"].fsType != cut["OS/2"].fsType:+ problems.append("OS/2 fsType differs from the source's")+ return problems, sorted(cut_cmap)+++def font_version(data: bytes) -> str:+ font = subset.load_font(io.BytesIO(data), subset_options())+ version = font["name"].getDebugName(5)+ font.close()+ return version.removeprefix("Version ")+++def build(package: Path, target: Path, jobs: int) -> None:+ faces = read_faces(package)+ partition, partition_version = load_partition()+ coverage = {w: set(TTFont(io.BytesIO(d), lazy=True).getBestCmap()) for w, d in faces.items()}+ if len({frozenset(points) for points in coverage.values()}) != 1:+ sys.exit("build-misans: the weights cover different characters; slices would not line up")+ covered = next(iter(coverage.values()))+ in_partition = set().union(*(points for _, points in partition))+ extra = sorted(+ point+ for point in covered - in_partition+ if not any(start <= point <= end for start, end in EXCLUDED_FROM_EXTRA)+ )++ slices = [(name, sorted(points & covered)) for name, points in partition]+ slices = [(name, points) for name, points in slices if points]+ if extra:+ slices.append((EXTRA_SLICE, extra))++ work = [(weight, name, points) for weight in FACES for name, points in slices]+ results: dict[tuple[int, str], tuple[bytes, list[int]]] = {}+ with concurrent.futures.ProcessPoolExecutor(+ max_workers=jobs, initializer=_init_worker, initargs=(faces,)+ ) as pool:+ for weight, name, data, held in pool.map(_cut, work, chunksize=1):+ results[(weight, name)] = (data, held)+ print(f" {FAMILY} {weight} {name}: {len(held)} characters, {len(data)} bytes")++ target.mkdir(parents=True, exist_ok=True)+ faces_css: list[str] = []+ for weight in FACES:+ for name, _ in slices:+ data, held = results[(weight, name)]+ file = f"misans-{weight}-{name}.woff2"+ (target / file).write_bytes(data)+ faces_css.append(+ "@font-face {\n"+ f' font-family: "{FAMILY}";\n'+ " font-style: normal;\n"+ " font-display: swap;\n"+ f" font-weight: {weight};\n"+ f' src: url("./{file}") format("woff2");\n'+ f" unicode-range: {format_range(held)};\n"+ "}\n"+ )++ version = font_version(faces[400])+ header = f"""/**+ * GENERATED by packages/ui/scripts/build-misans.py; do not edit, rerun the script.+ *+ * {FAMILY} {version} by Xiaomi Inc., from the official package {PACKAGE_URL}:+ * MiSans Regular as weight 400 and MiSans Medium as weight 500, {len(slices)} slices each: one per+ * slice of the unicode-range partition of @fontsource-variable/noto-sans-sc {partition_version} that+ * MiSans has characters for, plus `{EXTRA_SLICE}` for its other non-ideograph characters. Ideographs+ * outside the partition are not shipped and fall back to the system CJK face.+ *+ * Licence: the MiSans Font Intellectual Property License Agreement (fonts/LICENSES/misans.txt).+ * The software must state that it uses MiSans, and the font is never offered on its own.+ */+"""+ (target / "misans.css").write_text(header + "\n" + "\n".join(faces_css), encoding="utf-8")+++def owned_files(directory: Path) -> set[str]:+ if not directory.exists():+ return set()+ return {+ path.name+ for path in directory.iterdir()+ if path.name == "misans.css" or (path.name.startswith("misans-") and path.suffix == ".woff2")+ }+++def main() -> None:+ parser = argparse.ArgumentParser(description="Cut Frost's MiSans slices from MiSans.zip.")+ parser.add_argument("package", type=Path, help="the official MiSans.zip")+ parser.add_argument("--check", action="store_true", help="compare with the committed files")+ parser.add_argument("--jobs", type=int, default=min(4, os.cpu_count() or 1))+ args = parser.parse_args()++ with tempfile.TemporaryDirectory(prefix="misans-") as scratch:+ fresh = Path(scratch)+ build(args.package, fresh, args.jobs)+ built, committed = owned_files(fresh), owned_files(OUT_DIR)+ if args.check:+ drift = sorted(built ^ committed) + sorted(+ name+ for name in built & committed+ if not filecmp.cmp(fresh / name, OUT_DIR / name, shallow=False)+ )+ if drift:+ sys.exit("build-misans: src/fonts/misans/ differs from the package:\n " + "\n ".join(drift))+ print(f"build-misans: src/fonts/misans/ is current ({len(built)} files).")+ return+ OUT_DIR.mkdir(parents=True, exist_ok=True)+ for name in committed - built:+ (OUT_DIR / name).unlink()+ for name in sorted(built):+ shutil.copyfile(fresh / name, OUT_DIR / name)+ total = sum((OUT_DIR / name).stat().st_size for name in built if name.endswith(".woff2"))+ print(f"build-misans: wrote {len(built)} files to src/fonts/misans/ ({total} bytes of woff2).")+++if __name__ == "__main__":+ main()diff --git a/packages/ui/scripts/sync-font-licenses.mjs b/packages/ui/scripts/sync-font-licenses.mjsnew file mode 100644index 00000000..c96a17c1--- /dev/null+++ b/packages/ui/scripts/sync-font-licenses.mjs@@ -0,0 +1,135 @@+/**+ * Mirrors the licence text of every font package @prismshadow/penguin-ui depends on into+ * `src/fonts/LICENSES/<package>.txt` — verbatim except for whitespace: line endings become LF,+ * trailing spaces go and the file ends in one newline, because the repository stores text as LF+ * (.gitattributes) and a CRLF original (Commit Mono's) would otherwise read as drift after every+ * checkout.+ *+ * The texts are checked in so the licence a build ships is reviewable in the diff that changes a+ * font, and so the `penguinUi()` Vite plugin can emit them beside the fonts+ * (`fonts-licenses/<package>.txt` in every consumer's dist) without reaching into node_modules at+ * build time.+ *+ * pnpm --filter @prismshadow/penguin-ui sync:font-licenses rewrite the mirror+ * pnpm --filter @prismshadow/penguin-ui sync:font-licenses --check exit 1 on any drift, write nothing+ *+ * A font package is any `@fontsource/*` or `@fontsource-variable/*` dependency. Its file is named+ * after the package without its scope, so `@fontsource-variable/mona-sans` → `mona-sans.txt`.+ *+ * A font with no package (`src/fonts/vendored-fonts.json`: MiSans, whose slices+ * `scripts/build-misans.py` cuts from Xiaomi's download) keeps a licence text transcribed from the+ * licensor's own publication. The sync never writes or removes it; `--check` asserts that it is+ * there, names its licence, and is whitespace-normalized like the rest.+ */+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { join } from "node:path";+import { fileURLToPath } from "node:url";++const packageRoot = fileURLToPath(new URL("..", import.meta.url));+const mirrorDir = join(packageRoot, "src", "fonts", "LICENSES");+const check = process.argv.includes("--check");++/** `LICENSES/<file>` → the vendored font it belongs to (see src/fonts/vendored-fonts.json). */+const vendored = new Map(+ Object.values(+ JSON.parse(readFileSync(join(packageRoot, "src", "fonts", "vendored-fonts.json"), "utf8")),+ ).map((font) => [font.license.slice(font.license.lastIndexOf("/") + 1), font]),+);++const manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));+const fontPackages = Object.keys(manifest.dependencies ?? {})+ .filter((name) => /^@fontsource(-variable)?\//.test(name))+ .sort();++function normalizeWhitespace(text) {+ const lines = text+ .replace(/\r\n?/g, "\n")+ .split("\n")+ .map((line) => line.trimEnd());+ return `${lines.join("\n").trimEnd()}\n`;+}++// Resolve from this package, through each package's `exports` (fontsource exports `./LICENSE`).+const require = createRequire(join(packageRoot, "package.json"));+const expected = new Map();+for (const name of fontPackages) {+ const file = `${name.slice(name.indexOf("/") + 1)}.txt`;+ if (expected.has(file)) {+ console.error(`sync-font-licenses: ${name} and another dependency both mirror to ${file}`);+ process.exit(1);+ }+ const text = readFileSync(require.resolve(`${name}/LICENSE`), "utf8");+ expected.set(file, { name, text: normalizeWhitespace(text) });+}++const present = existsSync(mirrorDir)+ ? readdirSync(mirrorDir).filter((file) => file.endsWith(".txt"))+ : [];+const problems = [];+for (const [file, { name, text }] of expected) {+ const path = join(mirrorDir, file);+ if (!existsSync(path)) problems.push(`missing ${file} (${name})`);+ else if (readFileSync(path, "utf8") !== text) problems.push(`stale ${file} (${name})`);+}+for (const file of present) {+ if (!expected.has(file) && !vendored.has(file)) {+ problems.push(`orphaned ${file} (no font dependency mirrors to it)`);+ }+}+// A vendored licence is the licensor's text, kept by hand: problems with one are reported, never+// "fixed" by a rewrite.+const vendoredProblems = [];+for (const [file, font] of vendored) {+ if (expected.has(file)) {+ vendoredProblems.push(+ `${file} is claimed by both a dependency and the vendored ${font.family}`,+ );+ continue;+ }+ const path = join(mirrorDir, file);+ if (!existsSync(path)) {+ vendoredProblems.push(`missing ${file} (${font.family}: transcribe ${font.licenseSource})`);+ continue;+ }+ const text = readFileSync(path, "utf8");+ if (!text.includes(font.licenseTitle)) {+ vendoredProblems.push(`${file} does not name its licence, ${font.licenseTitle}`);+ }+ if (normalizeWhitespace(text) !== text) {+ vendoredProblems.push(+ `${file} is not whitespace-normalized (LF, no trailing spaces, one final newline)`,+ );+ }+}++if (check) {+ if (problems.length > 0) {+ console.error(+ `Font licence mirror is out of date:\n ${problems.join("\n ")}\n` ++ "Run `pnpm --filter @prismshadow/penguin-ui sync:font-licenses`.",+ );+ }+ if (vendoredProblems.length > 0) {+ console.error(`Vendored font licences need a hand fix:\n ${vendoredProblems.join("\n ")}`);+ }+ if (problems.length > 0 || vendoredProblems.length > 0) process.exit(1);+ console.log(+ `Font licence mirror is current (${expected.size} packages, ${vendored.size} vendored).`,+ );+} else {+ mkdirSync(mirrorDir, { recursive: true });+ for (const file of present) {+ if (!expected.has(file) && !vendored.has(file)) rmSync(join(mirrorDir, file));+ }+ for (const [file, { text }] of expected) writeFileSync(join(mirrorDir, file), text);+ console.log(+ problems.length > 0+ ? `Updated the font licence mirror:\n ${problems.join("\n ")}`+ : `Font licence mirror already current (${expected.size} packages).`,+ );+ if (vendoredProblems.length > 0) {+ console.error(`Vendored font licences need a hand fix:\n ${vendoredProblems.join("\n ")}`);+ process.exit(1);+ }+}diff --git a/packages/ui/src/boot.ts b/packages/ui/src/boot.tsnew file mode 100644index 00000000..6673d1d4--- /dev/null+++ b/packages/ui/src/boot.ts@@ -0,0 +1,251 @@+/**+ * Theme attributes on <html>, applied twice: once before the first paint by {@link BOOT_SCRIPT}+ * (inlined into the app's index.html), and from then on by the app's theme provider through+ * {@link applyThemeAttributes}.+ *+ * The pre-paint pass is what keeps a dark or non-default-theme page from flashing the light+ * default while the bundle loads, keeps the first frame from rendering at the browser's 16px+ * root and reflowing once React applies the stored text size, and keeps a chosen font pairing+ * from swapping in after the first paint.+ *+ * The inline copy in index.html must equal {@link BOOT_SCRIPT} byte for byte; a test asserts it.+ * Change the constants here, then paste the regenerated string there.+ */+import { ACCENT_PRESET_IDS, DEFAULT_THEME_ID, THEME_IDS } from "./tokens";+import type { AccentPreset, ThemeId } from "./tokens";++/**+ * localStorage keys. `penguin.theme` predates themes and stores the MODE (light / dark / system).+ * `penguin.fontScale` is the key of the retired three-step size: {@link readTextSize} reads it+ * once, maps it and removes it; nothing writes it. Drop it with the next minor version.+ */+export const THEME_STORAGE_KEYS = {+ mode: "penguin.theme",+ themeId: "penguin.themeId",+ accent: "penguin.accent",+ textSize: "penguin.textSize",+ fontLatin: "penguin.fontLatin",+ fontCjk: "penguin.fontCjk",+ fontScale: "penguin.fontScale",+} as const;++/** What the readers need of `localStorage`; a test passes a Map-backed stand-in. */+export type PreferenceStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;++// ---------------------------------------------------------------------------+// Text size+// ---------------------------------------------------------------------------++/** The five text sizes, smallest first: 特小 · 小 · 中 · 大 · 特大. */+export const TEXT_SIZES = ["xs", "s", "m", "l", "xl"] as const;+export type TextSize = (typeof TEXT_SIZES)[number];++/** Text size → root font-size. Every type and density token is rem, so this scales them all. */+export const TEXT_SIZE_PX: Readonly<Record<TextSize, string>> = {+ xs: "14px",+ s: "15px",+ m: "16px",+ l: "18px",+ xl: "20px",+};++/** 16px — what the retired scale called its small step (user decision, 2026-09-29). */+export const DEFAULT_TEXT_SIZE: TextSize = "m";++/** The retired three-step scale and, by index, the size with the same pixels: 16 / 18 / 20px. */+const LEGACY_FONT_SCALES = ["sm", "md", "lg"] as const;+const LEGACY_FONT_SCALE_SIZES: readonly TextSize[] = ["m", "l", "xl"];++export function isTextSize(value: unknown): value is TextSize {+ return (TEXT_SIZES as readonly unknown[]).includes(value);+}++/**+ * The stored text size, or the default. A store that still holds the retired three-step scale+ * and no text size is migrated on this read: the step is mapped by its pixels, written under the+ * new key and the old key removed (an unrecognised old value is removed without a write), so the+ * next read is a plain lookup. The pre-paint script does the same before the first frame.+ */+export function readTextSize(storage: PreferenceStorage): TextSize {+ const stored = storage.getItem(THEME_STORAGE_KEYS.textSize);+ if (isTextSize(stored)) return stored;+ const legacy = storage.getItem(THEME_STORAGE_KEYS.fontScale);+ if (legacy === null) return DEFAULT_TEXT_SIZE;+ const size = LEGACY_FONT_SCALE_SIZES[(LEGACY_FONT_SCALES as readonly string[]).indexOf(legacy)];+ if (size !== undefined) storage.setItem(THEME_STORAGE_KEYS.textSize, size);+ storage.removeItem(THEME_STORAGE_KEYS.fontScale);+ return size ?? DEFAULT_TEXT_SIZE;+}++// ---------------------------------------------------------------------------+// Font pairing+// ---------------------------------------------------------------------------++/**+ * One face a user may pair: its id (the `data-font-latin` / `data-font-cjk` value, and what is+ * stored) and its display label — a proper name, the same in both languages. `theme` (the+ * theme's own face, no attribute) and `system` (the platform's face) are not names: a consumer+ * words those two from its own dictionary and shows the label of every other entry as it is.+ */+export interface FontOption {+ readonly id: string;+ readonly label: string;+}++/**+ * The Latin faces, only those the app already bundles (`fonts/*.css`). They replace the reading+ * and chrome sans (`--ui-font-sans`, which `--ui-font-ui` follows in Primer and Frost); a+ * theme's mono face is never replaced — Console's chrome stays mono, its identity, and a+ * pairing only changes what Console reads in.+ */+export const FONT_LATIN_OPTIONS = [+ { id: "theme", label: "Theme default" },+ { id: "system", label: "System" },+ { id: "mona-sans", label: "Mona Sans" },+ { id: "ibm-plex-sans", label: "IBM Plex Sans" },+ { id: "misans", label: "MiSans" },+] as const satisfies readonly FontOption[];+export type FontLatin = (typeof FONT_LATIN_OPTIONS)[number]["id"];++/** The CJK faces, likewise; they replace `--ui-font-cjk`, which every theme's stacks read. */+export const FONT_CJK_OPTIONS = [+ { id: "theme", label: "Theme default" },+ { id: "system", label: "System" },+ { id: "noto-sans-sc", label: "Noto Sans SC" },+ { id: "misans", label: "MiSans" },+] as const satisfies readonly FontOption[];+export type FontCjk = (typeof FONT_CJK_OPTIONS)[number]["id"];++const optionIds = (options: readonly FontOption[]) => options.map((option) => option.id);++export function isFontLatin(value: unknown): value is FontLatin {+ return (optionIds(FONT_LATIN_OPTIONS) as readonly unknown[]).includes(value);+}++export function isFontCjk(value: unknown): value is FontCjk {+ return (optionIds(FONT_CJK_OPTIONS) as readonly unknown[]).includes(value);+}++// ---------------------------------------------------------------------------+// The themes' own faces+// ---------------------------------------------------------------------------++/**+ * The display name of every bundled family → the family its `@font-face` declares+ * (`fonts/*.css`). The pairing options and the themes' own faces are named by the display+ * names, which is also what the credits and the Fonts page print.+ */+export const BUNDLED_FONT_FAMILIES = {+ "Mona Sans": "Mona Sans Variable",+ "IBM Plex Sans": "IBM Plex Sans Variable",+ MiSans: "MiSans",+ "Noto Sans SC": "Noto Sans SC Variable",+ "JetBrains Mono": "JetBrains Mono Variable",+ "Commit Mono": "Commit Mono",+} as const;+export type BundledFontName = keyof typeof BUNDLED_FONT_FAMILIES;++/** A theme that names no bundled face names the platform's own; a consumer words this. */+export const SYSTEM_FONT = "System";+export type ThemeFontName = BundledFontName | typeof SYSTEM_FONT;++export interface ThemeFonts {+ /** The reading / UI sans (`--ui-font-sans`); Console's chrome is its mono face on top of it. */+ readonly latin: ThemeFontName;+ /** `--ui-font-cjk`. */+ readonly cjk: ThemeFontName;+ /** `--ui-font-mono`. */+ readonly mono: ThemeFontName;+}++/**+ * Each theme's own faces, as display names — what the Fonts page states as a theme's defaults+ * beside the user's choice. A test holds every entry to the family its theme file's stack names+ * first (`System` = a stack that names no bundled family).+ */+export const THEME_FONTS: Readonly<Record<ThemeId, ThemeFonts>> = {+ github: { latin: SYSTEM_FONT, cjk: SYSTEM_FONT, mono: SYSTEM_FONT },+ modern: { latin: "MiSans", cjk: "MiSans", mono: "JetBrains Mono" },+ geek: { latin: "IBM Plex Sans", cjk: "Noto Sans SC", mono: "Commit Mono" },+};++// ---------------------------------------------------------------------------+// Applying the attributes+// ---------------------------------------------------------------------------++/**+ * `neutral` is the stored value for "no preset": the theme's own accent, no `data-accent`. Any+ * other known id is written to the root as it is, whichever theme is active: a theme's preset+ * rules match only their own theme, so an id the active theme does not list paints nothing (the+ * theme's own accent shows) and takes effect again when the user returns to a theme that lists+ * it. The resolution lives in the CSS, and `resolveAccent` (tokens.ts) only mirrors it for a+ * picker.+ */+export type AccentChoice = "neutral" | AccentPreset;++export interface ThemeAttributes {+ /** The resolved mode (a `system` preference already resolved against the media query). */+ dark: boolean;+ themeId: ThemeId;+ accent: AccentChoice;+ textSize: TextSize;+ /** `theme` is the theme's own face and writes no attribute, like `neutral` for the accent. */+ fontLatin: FontLatin;+ fontCjk: FontCjk;+}++/**+ * The three `data-*` attributes share one rule: the value that means "the theme's own" (the+ * default theme, no preset, the theme's face) is the ABSENCE of the attribute, so a theme file's+ * plain selectors match it and nothing has to name a default.+ */+function setOrDrop(root: HTMLElement, key: string, value: string, own: string): void {+ if (value === own) delete root.dataset[key];+ else root.dataset[key] = value;+}++/**+ * Writes the given attributes onto `root`. Each field is optional so a provider can reconcile one+ * preference per effect; an absent field is left as it is.+ */+export function applyThemeAttributes(root: HTMLElement, attrs: Partial<ThemeAttributes>): void {+ if (attrs.dark !== undefined) root.classList.toggle("dark", attrs.dark);+ if (attrs.themeId !== undefined) setOrDrop(root, "theme", attrs.themeId, DEFAULT_THEME_ID);+ if (attrs.accent !== undefined) setOrDrop(root, "accent", attrs.accent, "neutral");+ if (attrs.fontLatin !== undefined) setOrDrop(root, "fontLatin", attrs.fontLatin, "theme");+ if (attrs.fontCjk !== undefined) setOrDrop(root, "fontCjk", attrs.fontCjk, "theme");+ if (attrs.textSize !== undefined) root.style.fontSize = TEXT_SIZE_PX[attrs.textSize];+}++// ---------------------------------------------------------------------------+// The pre-paint script+// ---------------------------------------------------------------------------++const NON_DEFAULT_THEMES = THEME_IDS.filter((id) => id !== DEFAULT_THEME_ID);+/** The ids that write an attribute: every option but `theme`, which is the attribute's absence. */+const chosenFaces = (options: readonly FontOption[]) =>+ optionIds(options).filter((id) => id !== "theme");+const j = JSON.stringify;+const K = THEME_STORAGE_KEYS;++/**+ * The pre-paint script: a classic, dependency-free IIFE (no globals leak) that mirrors+ * {@link applyThemeAttributes} and {@link readTextSize} for the stored preferences. It validates+ * every stored value the way the provider's initializers do, so an unknown value renders exactly+ * as the provider will, and it swallows everything — storage can throw (disabled cookies,+ * sandboxed frames) and the page must still render. The text-size migration writes storage last+ * and in its own try, so a store that reads but refuses writes still paints the migrated size.+ */+export const BOOT_SCRIPT =+ "(function(){try{" ++ `var d=document.documentElement,s=localStorage,m=s.getItem(${j(K.mode)});` ++ 'if(m==="dark"||(m!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches))d.classList.add("dark");' ++ `var t=s.getItem(${j(K.themeId)});if(${j(NON_DEFAULT_THEMES)}.indexOf(t)>=0)d.dataset.theme=t;` ++ `var a=s.getItem(${j(K.accent)});if(${j(ACCENT_PRESET_IDS)}.indexOf(a)>=0)d.dataset.accent=a;` ++ `var l=s.getItem(${j(K.fontLatin)});if(${j(chosenFaces(FONT_LATIN_OPTIONS))}.indexOf(l)>=0)d.dataset.fontLatin=l;` ++ `var c=s.getItem(${j(K.fontCjk)});if(${j(chosenFaces(FONT_CJK_OPTIONS))}.indexOf(c)>=0)d.dataset.fontCjk=c;` ++ `var z=s.getItem(${j(K.textSize)}),g=null,o=-1;` ++ `if(${j(TEXT_SIZES)}.indexOf(z)<0){g=s.getItem(${j(K.fontScale)});o=${j(LEGACY_FONT_SCALES)}.indexOf(g);z=o<0?${j(DEFAULT_TEXT_SIZE)}:${j(LEGACY_FONT_SCALE_SIZES)}[o]}` ++ `d.style.fontSize=${j(TEXT_SIZE_PX)}[z];` ++ `if(g!==null){try{if(o>=0)s.setItem(${j(K.textSize)},z);s.removeItem(${j(K.fontScale)})}catch(e){}}` ++ "}catch(e){}})()";diff --git a/packages/ui/src/components/icons/spinner/spinner.tsx b/packages/ui/src/components/icons/spinner/spinner.tsxnew file mode 100644index 00000000..5af5cc7f--- /dev/null+++ b/packages/ui/src/components/icons/spinner/spinner.tsx@@ -0,0 +1,74 @@+/**+ * The one spinner (K-redesign §3 rule 11, §5.1).+ *+ * Every busy indicator is this component: an arc on a track, centred in its own viewBox so the+ * rotation cannot wobble, at three sizes. It lives here because the guard lets `animate-spin`+ * appear in this file and nowhere else — thirteen hand-rolled rings at 2.5 / 3 / 3.5 px with+ * 1 / 1.5 / 2 px borders are what that rule exists to prevent coming back.+ *+ * The rotation is drawn once and re-timed by the theme: `.ui-live[data-live="spinner"]` keeps it+ * linear in Primer and Frost and steps it eight times a turn in Console, without either theme+ * redrawing the arc.+ *+ * The one component the package exports so far (`index.ts`): the Web App renders it where it+ * used to hand-draw a ring, and the gallery reviews it as the Web App's screens render it — the+ * package ships no demos of its own.+ */+import type { ToneName } from "../../../tokens";++/** Pixel sizes, the icon-scale convention: a spinner never scales with the root font tier. */+const SIZES = { xs: 10, sm: 12, md: 14 } as const;++const TONE_INK: Record<ToneName, string> = {+ success: "text-tone-success-fg",+ attention: "text-tone-attention-fg",+ danger: "text-tone-danger-fg",+ done: "text-tone-done-fg",+ neutral: "text-tone-neutral-fg",+ info: "text-tone-info-fg",+};++/** The arc's share of the circle: a quarter reads as motion without becoming a ring. */+const ARC = 0.28;+const RADIUS = 7;+const CIRCUMFERENCE = 2 * Math.PI * RADIUS;++export function Spinner({+ size = "md",+ tone = "inherit",+ label,+ className = "",+}: {+ size?: keyof typeof SIZES;+ /** `inherit` takes the ink around it, which is how a tone-coloured row stays one colour. */+ tone?: ToneName | "inherit";+ /** What is running. Announced, never drawn — the word beside a spinner is the caller's. */+ label: string;+ className?: string;+}) {+ const px = SIZES[size];+ return (+ <svg+ role="status"+ aria-label={label}+ data-live="spinner"+ width={px}+ height={px}+ viewBox="0 0 20 20"+ fill="none"+ className={`ui-live block shrink-0 animate-spin ${tone === "inherit" ? "" : TONE_INK[tone]} ${className}`}+ style={{ transformOrigin: "center" }}+ >+ <circle cx="10" cy="10" r={RADIUS} stroke="currentColor" strokeWidth="1.5" opacity="0.25" />+ <circle+ cx="10"+ cy="10"+ r={RADIUS}+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeDasharray={`${CIRCUMFERENCE * ARC} ${CIRCUMFERENCE}`}+ />+ </svg>+ );+}diff --git a/packages/ui/src/fonts/LICENSES/commit-mono.txt b/packages/ui/src/fonts/LICENSES/commit-mono.txtnew file mode 100644index 00000000..5cb48f81--- /dev/null+++ b/packages/ui/src/fonts/LICENSES/commit-mono.txt@@ -0,0 +1,90 @@+This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/ui/src/fonts/LICENSES/ibm-plex-sans-condensed.txt b/packages/ui/src/fonts/LICENSES/ibm-plex-sans-condensed.txtnew file mode 100644index 00000000..14fddb0f--- /dev/null+++ b/packages/ui/src/fonts/LICENSES/ibm-plex-sans-condensed.txt@@ -0,0 +1,93 @@+Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-ThinItalic.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-ExtraLight.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-ExtraLightItalic.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-Light.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-LightItalic.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-Regular.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-Italic.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-Medium.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-MediumItalic.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-SemiBold.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-SemiBoldItalic.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-Bold.ttf: Copyright 2019 IBM Corp. All rights reserved. IBMPlexSansCondensed-BoldItalic.ttf: Copyright 2019 IBM Corp. All rights reserved.++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/ui/src/fonts/LICENSES/ibm-plex-sans.txt b/packages/ui/src/fonts/LICENSES/ibm-plex-sans.txtnew file mode 100644index 00000000..2ae8ef3c--- /dev/null+++ b/packages/ui/src/fonts/LICENSES/ibm-plex-sans.txt@@ -0,0 +1,93 @@+Copyright 2019 IBM Corp. All rights reserved. IBMPlexSans-Italic[wdth,wght].ttf: Copyright 2019 IBM Corp. All rights reserved.++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/ui/src/fonts/LICENSES/jetbrains-mono.txt b/packages/ui/src/fonts/LICENSES/jetbrains-mono.txtnew file mode 100644index 00000000..8f7ed671--- /dev/null+++ b/packages/ui/src/fonts/LICENSES/jetbrains-mono.txt@@ -0,0 +1,93 @@+Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) JetBrainsMono-Italic[wght].ttf: Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/ui/src/fonts/LICENSES/misans.txt b/packages/ui/src/fonts/LICENSES/misans.txtnew file mode 100644index 00000000..b5500c9c--- /dev/null+++ b/packages/ui/src/fonts/LICENSES/misans.txt@@ -0,0 +1,119 @@+MiSans字体知识产权许可协议++MiSans Font Intellectual Property License Agreement++用户须知:++User Notes:++本《MiSans字体知识产权许可协议》(以下简称“协议”)是您与小米科技有限责任公司(以下简称“小米”或“许可方”)之间有关安装、使用MiSans字体(以下简称“MiSans”或“MiSans字体”)的法律协议。您在使用MiSans的所有或任何部分前,应接受本协议中规定的所有条款和条件。安装、使用MiSans的行为表示您同意接受本协议所有条款的约束。否则,请不要安装和/或使用MiSans,并应立即销毁和删除所有 MiSans 字体包。++The MiSans Font Intellectual Property License Agreement (hereinafter referred to as the “Agreement”) is a legal agreement between You and Xiaomi Inc. (hereinafter referred to as “Xiaomi” or “Licensor”) regarding the installation and use of MiSans fonts (hereinafter referred to “MiSans” or “MiSans Fonts”). You shall accept all of the terms and conditions in the Agreement before using all or any part of MiSans. By installing and using MiSans, You agree to be bound by all of the terms of this Agreement. Otherwise, You shall not install and/or use MiSans, and shall immediately destroy and delete all MiSans font packages.++1.定义++1. Definition++1.1 “MiSans字体”代表许可方在本协议项下提供并明确标记为“MiSans”的字体软件,包括但不限于以各种形式、格式及媒介存在的源代码、数据库、文档等。++1.1 “MiSans Fonts” refers to the font software clearly marked as “MiSans” that is provided by Licensor under this Agreement, including but not limited to source code, database, and documentation in various forms, formats, and media.++1.2 “用户”或“您”代表行使本协议授予许可的自然人、法人或非法人组织。用户应依照本协议安装、使用MiSans。++1.2 The term “User” or “You” represents the natural person, legal person, or unincorporated organization exercising the license granted in this Agreement. The User shall install and use MiSans according to this Agreement.++1.3 “使用”是指安装、下载、复制、展览或以其他方式通过利用MiSans而获益的行为。++1.3 “Use” refers to the act of installing, downloading, copying, exhibiting, or otherwise benefiting from the use of MiSans.++2.授权许可++2. Authorization and Permission++根据本协议的条款和条件,许可方在此授予您一份不可转让的、非独占的、免版税的、可撤销的、全球性的版权许可,使您依照本协议约定使用MiSans字体,前提是符合下列条件:++According to the terms and conditions of this Agreement, Licensor hereby grants You a non-transferable, non-exclusive, royalty-free, revocable, and global copyright license to use the MiSans fonts in accordance with this Agreement, provided that the following conditions are met:++1) 您应在软件中特别注明使用了 MiSans 字体。++1) You shall specifically indicate in the Software that You are using MiSans fonts.++2)您不得对 MiSans 字体或其任何单独组件进行改编或二次开发。++2) You shall not adapt or redevelop MiSans fonts or any of their individual components.++3)您不得单独将MiSans 字体或其组件对外租赁、再许可、给予、出借或进一步分发字体软件或其任何副本以及重新分发或售卖。此限制不适用于您使用 MiSans 字体创作的任何其他作品。如您使用 MiSans 字体创作宣传素材、logo、应用App等,您有权分发或出售该作品。++3) You shall not individually rent, sublicense, give, loan, or further distribute the MiSans fonts or their components, or any copies thereof, nor shall you redistribute or sell them. This restriction does not apply to any other work that You create using MiSans fonts. For example, if You use MiSans fonts to create promotional materials, logos, applications (Apps), etc., You shall have the right to distribute or sell that work.++4)您应在 MiSans 字体的任何副本中保留版权声明和本协议。++4) You shall retain the copyright notice and this Agreement in any copies of MiSans fonts.++5)不可将 MiSans 字体用于任何违法用途。++(5) You shall not use MiSans fonts for any illegal purposes.++3.知识产权++3. Intellectual Property Rights++MiSans字体软件及其所包含的字体以及小米授权您制作的任何副本均为小米的知识产品,本字库软件的结构、组织和代码以及与本字库软件相关的所有信息均为小米的商业秘密。本字库软件及其所包含的字体受《中华人民共和国著作权法》、《计算机软件保护条例》和其他知识产权法律法规及国际公约、条约的保护。除本协议中明确的许可,小米不授予您对MiSans相关的其他知识产权权利。++MiSans Font Software and the fonts contained therein and any copies that Xiaomi authorizes You to make are the intellectual products of Xiaomi, and the structure, organization, and code of this font software and all information related to this font software are the trade secrets of Xiaomi. This font software and the fonts contained therein are protected by the Copyright Law of the People’s Republic of China, the Regulations on the Protection of Computer Software, and other intellectual property laws and regulations as well as international conventions and treaties. Xiaomi does not grant You any other intellectual property rights related to MiSans except those expressly granted in this Agreement.++4.免责声明++4. Disclaimer++4.1 MiSans是按“原样”提供的。许可方不对本协议作出任何明示、暗示或依照法令的担保,包括但不限于对适销性、所有权、就某一用途的适用性或不侵犯版权、专利、商标或其他权利的保证。++4.1 MiSans is provided “as is”. The Licensor makes no express, implied, or statutory warranties with respect to this Agreement, including, but not limited to, warranties of merchantability, ownership, fitness for a particular purpose, or non-infringement of copyrights, patents, trademarks, or other rights.++4.2 在任何情况下,许可方及其关联公司均不对任何直接、间接、特殊、附带或间接的损害(包括但不限于购买替代商品或服务)负责。无论根据合同理论、侵权行为(包括过失)理论、严格责任理论或其他法律理论,因使用或无法使用 MiSans 字体,即使许可方及其关联公司已被告知存在这种损害的可能性,而导致的任何方式的业务中断,使用数据或利润的损失,许可方及其关联公司不承担任何责任。++4.2 In no event shall Licensor and its affiliates be liable for any direct, indirect, special, incidental, or consequential damages (including, but not limited to, the purchase of substitute goods or services). Whether under the contract theory, the tort (including negligence) theory, the strict liability theory, or other legal theories, Licensor and its affiliates shall not be liable for any form of business interruption, or loss of service data or profits resulting from the use of or inability to use MiSans fonts, even if Licensor and its affiliates have been advised of the possibility of such damages.++4.3 您需明确承担使用 MiSans 字体的所有责任和风险。如果无法证明 MiSans 有任何缺陷,您将承担所有必要的服务,修复或纠正的全部费用。++4.3 You shall expressly assume all responsibility and risk for using MiSans fonts. If it cannot be proven that MiSans is subject to any defect, You shall be responsible for all necessary services, repairs, or rectifications at full cost.++5.许可终止。++5. License Termination++一旦您违反本协议的条款,小米随时可能终止本协议、收回授权,并要求您承担相应法律责任。++If You violate the terms of this Agreement, Xiaomi may terminate the Agreement, withdraw the license, and hold You liable for the corresponding legal responsibility at any time.++6.适用法律与管辖。++6. Applicable Laws and Jurisdiction++本协议适用中华人民共和国的法律。如您与小米就本协议的相关问题发生争议,您与小米均有权向北京市海淀区人民法院提起诉讼。++The Agreement shall be governed by the laws of the People’s Republic of China. In case of any dispute between You and Xiaomi regarding this Agreement, both You and Xiaomi shall have the right to file a lawsuit at Beijing Haidian District People’s Court.++7.一般规定。++7. General Provisions++7.1 本协议是小米与您之间有关MiSans软件及其所包含的字体的最新许可协议,它将取代先前所有与本字库软件相关的陈述、承诺、宣传或许可协议。++7.1 This is the most recent license agreement between Xiaomi and You regarding the MiSans Software and the fonts contained therein, and it shall supersede all prior representations, undertakings, publicity, or license agreements relating to this font software.++7.2 如果您对本协议有任何疑问或者希望获得有关字体授权许可的任何信息,请通过如下方式与小米联系:++7.2 If You have any questions regarding the Agreement or wish to learn any information regarding the licensing of the Font, please contact Xiaomi as follows:++小米科技有限责任公司++Xiaomi Inc.++地址: 北京市海淀区西二旗中路33号院小米科技园++Address: Xiaomi Campus, No. 33 Xi erqi Middle Road, Haidian District, Beijing,100085,China+++Email: [email protected]diff --git a/packages/ui/src/fonts/LICENSES/mona-sans.txt b/packages/ui/src/fonts/LICENSES/mona-sans.txtnew file mode 100644index 00000000..fd6728bb--- /dev/null+++ b/packages/ui/src/fonts/LICENSES/mona-sans.txt@@ -0,0 +1,93 @@+Copyright 2022 The Mona Sans Project Authors (https://github.com/github/mona-sans), with Reserved Font Name "Mona" MonaSans-Italic[wdth,wght].ttf: Copyright 2022 The Mona Sans Project Authors (https://github.com/github/mona-sans), with Reserved Font Name "Mona"++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/ui/src/fonts/LICENSES/noto-sans-sc.txt b/packages/ui/src/fonts/LICENSES/noto-sans-sc.txtnew file mode 100644index 00000000..046fc664--- /dev/null+++ b/packages/ui/src/fonts/LICENSES/noto-sans-sc.txt@@ -0,0 +1,93 @@+Google Inc.++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/ui/src/fonts/README.md b/packages/ui/src/fonts/README.mdnew file mode 100644index 00000000..15a4dde4--- /dev/null+++ b/packages/ui/src/fonts/README.md@@ -0,0 +1,125 @@+# Fonts++The faces `@prismshadow/penguin-ui` bundles, which theme names each one, what they cost, the licence+each one carries and what that licence asks of the app, and how to update them. Bundled rather than+fetched from a CDN, so the desktop build renders offline.++## Families++| theme | sans (reading) | ui (chrome) | mono | CJK |+| --- | --- | --- | --- | --- |+| Primer `github` | Mona Sans Variable (from W1a; system stack until then) | = sans | JetBrains Mono Variable behind the system mono stack (W1a) | Noto Sans SC Variable (W1a) |+| Frost `modern` | **MiSans** 400 / 500 | = sans | JetBrains Mono Variable | MiSans (the same family) |+| Console `geek` | IBM Plex Sans Variable | Commit Mono 400 / 700 | Commit Mono 400 / 700 | Noto Sans SC Variable |++Two faces per theme since the theme identities (2026-09-19): `--ui-font-ui` is the chrome's face+(`body` sets it; navigation, controls, labels, headings, badges, tables) and `--ui-font-sans` the+reading face (message text, prose, the composer's input opt in with `font-sans`). Primer and Frost+point both at one family; Console sets its chrome in Commit Mono and reads in Plex Sans. The display+face is the chrome face everywhere: Console's h1 is the mono bold, and IBM Plex Sans Condensed 600+(the old uppercase h1) stays declared in `geek.css` but unnamed until its dependency is dropped.++| family | files | source | licence |+| --- | --- | --- | --- |+| Mona Sans Variable | `github.css`: latin + latin-ext | `@fontsource-variable/mona-sans` | OFL-1.1 |+| JetBrains Mono Variable | `github.css`: latin + latin-ext (Frost names the same faces) | `@fontsource-variable/jetbrains-mono` | OFL-1.1 |+| MiSans | `modern.css` → `misans/misans.css`: Regular as 400 and Medium as 500, 99 `unicode-range` slices each | vendored: `scripts/build-misans.py` cuts them from Xiaomi's official package | MiSans Font Intellectual Property License Agreement |+| IBM Plex Sans Variable | `geek.css`: latin + latin-ext | `@fontsource-variable/ibm-plex-sans` | OFL-1.1 |+| IBM Plex Sans Condensed | `geek.css`: 600, latin + latin-ext | `@fontsource/ibm-plex-sans-condensed` | OFL-1.1 |+| Commit Mono | `geek.css`: 400 and 700, one latin file each | `@fontsource/commit-mono` | OFL-1.1 |+| Noto Sans SC Variable | `cjk.css`: fontsource's own sheet, 101 `unicode-range` slices | `@fontsource-variable/noto-sans-sc` | OFL-1.1 |++Why these faces: Mona Sans is GitHub's product face. MiSans gives Frost one family for Latin and+Chinese, so a zh line sits in the same face as the English around it; no other face on the shortlist+has Chinese. Commit Mono, the face opencode.ai and e2b.dev ship, is Console's chrome — navigation,+controls, labels, headings — and its code face; IBM Plex Sans keeps Console's reading text+proportional, which a monospaced paragraph is not.++Frost ships two MiSans weights and no more, so `themes/modern.css` turns off weight synthesis: a 600+or 700 request renders in Medium instead of a synthesized bold, which smears Han strokes. Frost's+own tokens stop at 500.++## Loading++Font files and font declarations cost differently:++- **Files.** A browser fetches a font file only when an element's `font-family` names its family+ and its text falls inside the face's `unicode-range`. Each theme file names only its own+ families, so a session downloads its theme's faces and nothing else, and only the slices its text+ touches; Primer names no bundled family in W0 and downloads none. The consumers' Vite configs+ never inline a font (`build.assetsInlineLimit`), so every slice stays a file of its own.+- **Declarations.** `index.css` declares every theme's faces unconditionally, so all of them are+ rules in the app's main stylesheet and every session downloads them, Primer's included: about+ 94 KB of the stylesheet's 122 KB gzipped, most of it the `unicode-range` lists of MiSans's 198+ faces and Noto's 101. That cost was accepted on 2026-09-18 over loading each theme's font sheet+ on demand.++Font files fetched on a specimen page (the same paragraphs, headings, controls and a code frame in+each language; Playwright network log, identical in light and dark):++| theme | English page | Chinese page |+| --- | --- | --- |+| Primer (W0: system fonts) | 0 files | 0 files |+| Frost | 5 files, 92.6 KB (MiSans 3 + 1 slices, JetBrains Mono) | 27 files, 627 KB (MiSans 16 + 10 slices, JetBrains Mono) |+| Console | 4 files, 121.7 KB (Plex Sans, Condensed 600, Commit Mono 400, 1 Noto slice for a symbol) | 17 files, 893 KB (14 Noto slices, the three Latin faces) |++## Bytes in `dist/`++Every declared face is emitted into a consumer's build (the served app, the desktop bundle, the+gallery), because the offline desktop app needs them all:++| family | files | bytes |+| --- | ---: | ---: |+| MiSans 400 | 99 | 2,121,092 |+| MiSans 500 | 99 | 2,135,204 |+| Noto Sans SC Variable | 101 | 4,516,508 |+| Mona Sans Variable | 2 | 55,312 |+| JetBrains Mono Variable | 2 | 55,600 |+| IBM Plex Sans Variable | 2 | 76,676 |+| IBM Plex Sans Condensed 600 | 2 | 35,860 |+| Commit Mono 400 / 700 | 2 | 95,432 |+| **total** | **309** | **9,091,684** |++MiSans covers the characters of Noto's slice partition plus its own other non-ideograph characters.+The roughly 15,500 rare ideographs outside that partition are not shipped (they would add 2.46 MB per+weight) and fall back to the system CJK face, as they do under the other themes.++## Licences++The `penguinUi()` Vite plugin emits every text in `LICENSES/` beside the build as+`fonts-licenses/<name>.txt`.++**OFL-1.1 faces.** `scripts/sync-font-licenses.mjs` mirrors each fontsource package's `LICENSE` into+`LICENSES/<package>.txt` (`pnpm --filter @prismshadow/penguin-ui sync:font-licenses`, `--check` to+verify without writing).++**MiSans.** Xiaomi Inc. publishes MiSans under the MiSans Font Intellectual Property License+Agreement: https://hyperos.mi.com/font-download/MiSans%E5%AD%97%E4%BD%93%E7%9F%A5%E8%AF%86%E4%BA%A7%E6%9D%83%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE.pdf+(sha256 `4a93a27cd2bd81b3b5ecfd0a853144a876fa26938a93a68443c67d74172fcb86`, retrieved 2026-09-17).+`LICENSES/misans.txt` is that PDF's bilingual text, transcribed: paragraphs rejoined across the PDF's+line breaks, and the Kangxi-radical code points the PDF's text layer uses (`⽤` for `用`) written as+the ideographs they stand for. The sync script never rewrites it; its `--check` confirms that it is+present and names its licence (`vendored-fonts.json` lists it).++What the licence asks, and where the app does it:++| condition | how it is met |+| --- | --- |+| 1. The software states that it uses MiSans. | The Web App's account menu ends with a credit line in both dictionaries (`S.settings.fontCredit`). |+| 2. No adaptation or redevelopment of the font or its components. | The slices are subsets delivered as WOFF2: every glyph they carry keeps its outline, hinting, metrics and name, every feature and every name record is kept, and `build-misans.py` reads each finished file back and fails unless it matches the official TTF. The maintainer decided on 2026-09-17 that cutting the official TTFs into these slices is delivery, not adaptation. |+| 3. No renting, sublicensing or redistributing the font on its own. | The slices are part of the application: committed in its source tree, and shipped inside its builds and its npm package. Nothing links to them or offers them for download on their own, and the full TTF is never committed. |+| 4. Copies keep the copyright notice and the agreement. | Every slice keeps the font's name table (its copyright record included), and `fonts-licenses/misans.txt` ships beside the files in every build. |+| 5. No illegal use. | — |++## Updating++- **A fontsource face:** change the dependency, run `pnpm install`, then `sync:font-licenses`, and+ check the paths in the theme's font sheet against the package's `files/`.+- **MiSans:** download the official package from https://hyperos.mi.com/font/ (the site asks you to+ accept the licence first), then from the repository root run+ `uv run packages/ui/scripts/build-misans.py <MiSans.zip>` (or `pnpm --filter+ @prismshadow/penguin-ui fonts:misans /absolute/path/to/MiSans.zip`: pnpm runs the script in+ `packages/ui`, so a relative path would not resolve); `--check` rebuilds in a temporary directory+ and compares byte for byte. The script pins the sha256 of the Regular and Medium TTFs it accepts,+ so a new MiSans release is a deliberate change: update the pins, rebuild, review the slices, and+ re-read the licence PDF for changes.diff --git a/packages/ui/src/fonts/cjk.css b/packages/ui/src/fonts/cjk.cssnew file mode 100644index 00000000..65773293--- /dev/null+++ b/packages/ui/src/fonts/cjk.css@@ -0,0 +1,11 @@+/**+ * Console's CJK face, and Primer's from W1a (Frost's is MiSans, and Primer stays on the system CJK+ * stack until W1a): Noto Sans SC, variable `wght` 100–900, OFL-1.1 — fontsource's own stylesheet+ * imported as-is. It declares the family "Noto Sans SC Variable" as 101 `unicode-range` slices (97+ * Han / punctuation / symbol slices plus latin, latin-ext, cyrillic and vietnamese), about 4.5 MB+ * in all; a page whose theme names the family downloads only the slices its text touches.+ *+ * A stack that names Noto names a Latin face first, so ASCII never reaches Noto's latin slice;+ * that slice and the cyrillic / vietnamese ones only answer text the Latin face cannot.+ */+@import "@fontsource-variable/noto-sans-sc/index.css";diff --git a/packages/ui/src/fonts/credits.ts b/packages/ui/src/fonts/credits.tsnew file mode 100644index 00000000..c868aea3--- /dev/null+++ b/packages/ui/src/fonts/credits.ts@@ -0,0 +1,106 @@+/**+ * The bundled fonts' credits, for the app's Credits page: each face the package ships, which+ * themes name it by default, where it comes from, and its licence — title and full text. The+ * licences are the texts in `LICENSES/` (the mirror `scripts/sync-font-licenses.mjs` keeps and+ * `font-licenses.test.ts` holds to the packages), imported whole, so the page shows the very+ * text that ships beside the font files. A test holds this list to that directory: every text+ * credited once, every credit naming its licence, the vendored font's title and source equal to+ * `vendored-fonts.json`.+ *+ * MiSans's licence asks the software to credit the font; the sentence that does so is UI copy+ * and lives in the app's dictionaries, on the same page.+ */+import { THEME_IDS } from "../tokens";+import type { ThemeId } from "../tokens";+import { THEME_FONTS } from "../boot";+import type { BundledFontName } from "../boot";+import commitMono from "./LICENSES/commit-mono.txt?raw";+import ibmPlexSans from "./LICENSES/ibm-plex-sans.txt?raw";+import ibmPlexSansCondensed from "./LICENSES/ibm-plex-sans-condensed.txt?raw";+import jetbrainsMono from "./LICENSES/jetbrains-mono.txt?raw";+import misans from "./LICENSES/misans.txt?raw";+import monaSans from "./LICENSES/mona-sans.txt?raw";+import notoSansSc from "./LICENSES/noto-sans-sc.txt?raw";++export interface FontCredit {+ /** The licence file's name in `LICENSES/`, without the extension. */+ readonly id: string;+ /** The family's display name. */+ readonly family: string;+ /** The themes that name the family by default; empty for a face only the pairing offers. */+ readonly themes: readonly ThemeId[];+ /** The npm package the face arrives through, or the vendor's download for a vendored face. */+ readonly source: string;+ readonly licenseTitle: string;+ readonly licenseText: string;+}++const OFL = "SIL Open Font License 1.1";++/** The vendored face's manifest entry (`vendored-fonts.json`), spelled here so the list is plain data. */+export const MISANS_LICENSE_TITLE = "MiSans Font Intellectual Property License Agreement";+export const MISANS_SOURCE = "https://hyperos.mi.com/font-download/MiSans.zip";++const namedBy = (family: BundledFontName): readonly ThemeId[] =>+ THEME_IDS.filter((id) => Object.values(THEME_FONTS[id]).includes(family));++export const FONT_CREDITS: readonly FontCredit[] = [+ {+ id: "mona-sans",+ family: "Mona Sans",+ themes: namedBy("Mona Sans"),+ source: "@fontsource-variable/mona-sans",+ licenseTitle: OFL,+ licenseText: monaSans,+ },+ {+ id: "jetbrains-mono",+ family: "JetBrains Mono",+ themes: namedBy("JetBrains Mono"),+ source: "@fontsource-variable/jetbrains-mono",+ licenseTitle: OFL,+ licenseText: jetbrainsMono,+ },+ {+ id: "misans",+ family: "MiSans",+ themes: namedBy("MiSans"),+ source: MISANS_SOURCE,+ licenseTitle: MISANS_LICENSE_TITLE,+ licenseText: misans,+ },+ {+ id: "ibm-plex-sans",+ family: "IBM Plex Sans",+ themes: namedBy("IBM Plex Sans"),+ source: "@fontsource-variable/ibm-plex-sans",+ licenseTitle: OFL,+ licenseText: ibmPlexSans,+ },+ {+ // Declared in `fonts/geek.css` and named by no theme since Console's h1 moved to the mono+ // bold; its files still ship until the dependency is dropped, so it is still credited.+ id: "ibm-plex-sans-condensed",+ family: "IBM Plex Sans Condensed",+ themes: [],+ source: "@fontsource/ibm-plex-sans-condensed",+ licenseTitle: OFL,+ licenseText: ibmPlexSansCondensed,+ },+ {+ id: "commit-mono",+ family: "Commit Mono",+ themes: namedBy("Commit Mono"),+ source: "@fontsource/commit-mono",+ licenseTitle: OFL,+ licenseText: commitMono,+ },+ {+ id: "noto-sans-sc",+ family: "Noto Sans SC",+ themes: namedBy("Noto Sans SC"),+ source: "@fontsource-variable/noto-sans-sc",+ licenseTitle: OFL,+ licenseText: notoSansSc,+ },+];diff --git a/packages/ui/src/fonts/geek.css b/packages/ui/src/fonts/geek.cssnew file mode 100644index 00000000..a0ba293e--- /dev/null+++ b/packages/ui/src/fonts/geek.css@@ -0,0 +1,84 @@+/**+ * Console (`geek`) Latin faces, all OFL-1.1:+ * - IBM Plex Sans (the reading face), variable `wght`, latin + latin-ext —+ * @fontsource-variable/ibm-plex-sans+ * - Commit Mono (the chrome face and the code face), static 400 and 700 — @fontsource/commit-mono.+ * Fontsource builds it as a single `latin` file with no `unicode-range`, so none is declared here+ * either: the browser loads the file for any chrome or mono text and falls back per missing+ * glyph.+ * - IBM Plex Sans Condensed, static 600, latin + latin-ext — @fontsource/ibm-plex-sans-condensed.+ * Declared but no longer named by the theme: the uppercase condensed h1 gave way to the mono+ * chrome's bold h1. A declared face nobody names is never downloaded; drop the dependency and+ * these two rules with the next install.+ *+ * Only `themes/geek.css` names these families, so no other theme ever downloads them. The+ * `url()`s are relative to this file on purpose — see `index.css`.+ */++@font-face {+ font-family: "IBM Plex Sans Variable";+ font-style: normal;+ font-display: swap;+ font-weight: 100 700;+ src: url("../../node_modules/@fontsource-variable/ibm-plex-sans/files/ibm-plex-sans-latin-ext-wght-normal.woff2")+ format("woff2-variations");+ unicode-range:+ U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329,+ U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,+ U+A720-A7FF;+}++@font-face {+ font-family: "IBM Plex Sans Variable";+ font-style: normal;+ font-display: swap;+ font-weight: 100 700;+ src: url("../../node_modules/@fontsource-variable/ibm-plex-sans/files/ibm-plex-sans-latin-wght-normal.woff2")+ format("woff2-variations");+ unicode-range:+ U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329,+ U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}++@font-face {+ font-family: "IBM Plex Sans Condensed";+ font-style: normal;+ font-display: swap;+ font-weight: 600;+ src: url("../../node_modules/@fontsource/ibm-plex-sans-condensed/files/ibm-plex-sans-condensed-latin-ext-600-normal.woff2")+ format("woff2");+ unicode-range:+ U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329,+ U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,+ U+A720-A7FF;+}++@font-face {+ font-family: "IBM Plex Sans Condensed";+ font-style: normal;+ font-display: swap;+ font-weight: 600;+ src: url("../../node_modules/@fontsource/ibm-plex-sans-condensed/files/ibm-plex-sans-condensed-latin-600-normal.woff2")+ format("woff2");+ unicode-range:+ U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329,+ U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}++@font-face {+ font-family: "Commit Mono";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("../../node_modules/@fontsource/commit-mono/files/commit-mono-latin-400-normal.woff2")+ format("woff2");+}++@font-face {+ font-family: "Commit Mono";+ font-style: normal;+ font-display: swap;+ font-weight: 700;+ src: url("../../node_modules/@fontsource/commit-mono/files/commit-mono-latin-700-normal.woff2")+ format("woff2");+}diff --git a/packages/ui/src/fonts/github.css b/packages/ui/src/fonts/github.cssnew file mode 100644index 00000000..e84e151a--- /dev/null+++ b/packages/ui/src/fonts/github.css@@ -0,0 +1,60 @@+/**+ * Primer (`github`) Latin faces: Mona Sans (sans) and JetBrains Mono, variable `wght`, latin ++ * latin-ext slices only, from @fontsource-variable/mona-sans and+ * @fontsource-variable/jetbrains-mono (OFL-1.1).+ *+ * Declared ahead of use: Primer stays on the system font stack until the W1a polish names these+ * families in `themes/github.css`. A declared face that no `font-family` names is never+ * downloaded, so until then they cost bundle bytes only. The `url()`s are relative to this file on+ * purpose — see `index.css`.+ */++@font-face {+ font-family: "Mona Sans Variable";+ font-style: normal;+ font-display: swap;+ font-weight: 200 900;+ src: url("../../node_modules/@fontsource-variable/mona-sans/files/mona-sans-latin-ext-wght-normal.woff2")+ format("woff2-variations");+ unicode-range:+ U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329,+ U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,+ U+A720-A7FF;+}++@font-face {+ font-family: "Mona Sans Variable";+ font-style: normal;+ font-display: swap;+ font-weight: 200 900;+ src: url("../../node_modules/@fontsource-variable/mona-sans/files/mona-sans-latin-wght-normal.woff2")+ format("woff2-variations");+ unicode-range:+ U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329,+ U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}++@font-face {+ font-family: "JetBrains Mono Variable";+ font-style: normal;+ font-display: swap;+ font-weight: 100 800;+ src: url("../../node_modules/@fontsource-variable/jetbrains-mono/files/jetbrains-mono-latin-ext-wght-normal.woff2")+ format("woff2-variations");+ unicode-range:+ U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329,+ U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,+ U+A720-A7FF;+}++@font-face {+ font-family: "JetBrains Mono Variable";+ font-style: normal;+ font-display: swap;+ font-weight: 100 800;+ src: url("../../node_modules/@fontsource-variable/jetbrains-mono/files/jetbrains-mono-latin-wght-normal.woff2")+ format("woff2-variations");+ unicode-range:+ U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329,+ U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}diff --git a/packages/ui/src/fonts/index.css b/packages/ui/src/fonts/index.cssnew file mode 100644index 00000000..59db057f--- /dev/null+++ b/packages/ui/src/fonts/index.css@@ -0,0 +1,44 @@+/**+ * Font faces for every theme, bundled with the app so the desktop build renders offline.+ *+ * A browser fetches a font FILE only when some element's `font-family` names its family and the+ * text falls inside the face's `unicode-range`. Each theme file under `themes/` names only its own+ * families, so a session downloads the active theme's faces and nothing else: Frost's MiSans+ * slices and JetBrains Mono, or Console's Latin faces and the Noto Sans SC slices its CJK text+ * touches; Primer names no bundled family in W0 and downloads none. The DECLARATIONS are another+ * matter: every theme's faces are declared unconditionally here, so these rules sit in the app's+ * main stylesheet and every session downloads them (about 94 KB gzipped, most of it MiSans's and+ * Noto's `unicode-range` lists). That cost was accepted on 2026-09-18 over loading each theme's+ * font sheet on demand. A consumer's build must not inline the font files (`assetsInlineLimit`),+ * or small slices would ride in that stylesheet as data URIs. The unconditional declarations are+ * also what lets the user's font pairing (boot.ts, theme.css's `ui-font` layer) name any of these+ * families under any theme: a chosen face is downloaded the moment a stack names it.+ *+ * | theme | sans (reading) | ui (chrome) | mono | CJK |+ * | --------------- | ---------------------------------- | ---------------------- | ----------------------------- | ---------------------------- |+ * | Primer `github` | Mona Sans Variable (W1a) | = sans | JetBrains Mono Variable (W1a) | Noto Sans SC Variable (W1a) |+ * | Frost `modern` | MiSans 400 / 500 | = sans | JetBrains Mono Variable | MiSans (the same family) |+ * | Console `geek` | IBM Plex Sans Variable | Commit Mono 400 / 700 | Commit Mono 400 / 700 | Noto Sans SC Variable |+ *+ * The display face is the chrome face in every theme (Console's h1 is the mono bold); IBM Plex+ * Sans Condensed stays declared in `geek.css` until its dependency is dropped.+ *+ * Every face but MiSans is SIL Open Font License 1.1 and arrives through a fontsource package,+ * whose licence text `scripts/sync-font-licenses.mjs` mirrors into `LICENSES/`. MiSans has no+ * official package: `scripts/build-misans.py` cuts its slices from Xiaomi's download into+ * `misans/`, and its licence is transcribed into `LICENSES/misans.txt` (`vendored-fonts.json`+ * lists it). The `penguinUi()` Vite plugin emits every text in `LICENSES/` beside the build as+ * `fonts-licenses/<name>.txt`. `README.md` has the families, licences, sources and bytes.+ *+ * The Latin faces are hand-declared (latin + latin-ext only, normal style, woff2) instead of+ * importing fontsource's stylesheets, which would also bundle the cyrillic, greek and vietnamese+ * slices and the woff fallbacks. Their `url()`s are paths relative to the file that holds them,+ * into this package's own node_modules: a bare `@fontsource…` specifier would be resolved from the+ * CONSUMER's stylesheet (Tailwind inlines every `@import` and leaves bare `url()`s untouched), and+ * the consumer does not depend on fontsource. A relative path is rebased by Tailwind and resolves+ * from here.+ */+@import "./github.css";+@import "./modern.css";+@import "./geek.css";+@import "./cjk.css";diff --git a/packages/ui/src/fonts/misans/README.md b/packages/ui/src/fonts/misans/README.mdnew file mode 100644index 00000000..0c14b726--- /dev/null+++ b/packages/ui/src/fonts/misans/README.md@@ -0,0 +1,13 @@+# MiSans slices++The `misans-*.woff2` files and `misans.css` in this directory are **not** covered by this+repository's Apache-2.0 licence. They are cut from MiSans, a typeface by Xiaomi Inc. (copyright+Beijing Xiaomi Mobile Software Co., Ltd.), for the PenguinHarness application, which uses MiSans as+the Frost theme's typeface. They are governed by the MiSans Font Intellectual Property License+Agreement, reproduced in [`../LICENSES/misans.txt`](../LICENSES/misans.txt).++They are part of the application and are not offered for use or redistribution on their own. To use+MiSans, get it from Xiaomi: https://hyperos.mi.com/font/.++`packages/ui/scripts/build-misans.py` writes these files from Xiaomi's official package; do not edit+them by hand. `../README.md` describes the fonts, their licences and how to update them.diff --git a/packages/ui/src/fonts/misans/misans-400-100.woff2 b/packages/ui/src/fonts/misans/misans-400-100.woff2new file mode 100644index 00000000..3066e559Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-100.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-101.woff2 b/packages/ui/src/fonts/misans/misans-400-101.woff2new file mode 100644index 00000000..91e2dee2Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-101.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-102.woff2 b/packages/ui/src/fonts/misans/misans-400-102.woff2new file mode 100644index 00000000..d44dc580Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-102.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-103.woff2 b/packages/ui/src/fonts/misans/misans-400-103.woff2new file mode 100644index 00000000..5567c6aeBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-103.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-104.woff2 b/packages/ui/src/fonts/misans/misans-400-104.woff2new file mode 100644index 00000000..0c31f543Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-104.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-105.woff2 b/packages/ui/src/fonts/misans/misans-400-105.woff2new file mode 100644index 00000000..2ac04382Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-105.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-106.woff2 b/packages/ui/src/fonts/misans/misans-400-106.woff2new file mode 100644index 00000000..533d5e7cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-106.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-107.woff2 b/packages/ui/src/fonts/misans/misans-400-107.woff2new file mode 100644index 00000000..6fa46af8Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-107.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-108.woff2 b/packages/ui/src/fonts/misans/misans-400-108.woff2new file mode 100644index 00000000..1ef029d9Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-108.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-109.woff2 b/packages/ui/src/fonts/misans/misans-400-109.woff2new file mode 100644index 00000000..f60a1a8bBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-109.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-110.woff2 b/packages/ui/src/fonts/misans/misans-400-110.woff2new file mode 100644index 00000000..0821d86aBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-110.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-111.woff2 b/packages/ui/src/fonts/misans/misans-400-111.woff2new file mode 100644index 00000000..c0e3ab7eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-111.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-112.woff2 b/packages/ui/src/fonts/misans/misans-400-112.woff2new file mode 100644index 00000000..1a3aee52Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-112.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-113.woff2 b/packages/ui/src/fonts/misans/misans-400-113.woff2new file mode 100644index 00000000..11475714Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-113.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-114.woff2 b/packages/ui/src/fonts/misans/misans-400-114.woff2new file mode 100644index 00000000..3a2ef834Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-114.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-115.woff2 b/packages/ui/src/fonts/misans/misans-400-115.woff2new file mode 100644index 00000000..8df26c8aBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-115.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-116.woff2 b/packages/ui/src/fonts/misans/misans-400-116.woff2new file mode 100644index 00000000..bd1e07a0Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-116.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-117.woff2 b/packages/ui/src/fonts/misans/misans-400-117.woff2new file mode 100644index 00000000..9b8f9908Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-117.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-118.woff2 b/packages/ui/src/fonts/misans/misans-400-118.woff2new file mode 100644index 00000000..97df6862Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-118.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-119.woff2 b/packages/ui/src/fonts/misans/misans-400-119.woff2new file mode 100644index 00000000..a839921fBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-119.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-21.woff2 b/packages/ui/src/fonts/misans/misans-400-21.woff2new file mode 100644index 00000000..94a4f58dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-21.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-22.woff2 b/packages/ui/src/fonts/misans/misans-400-22.woff2new file mode 100644index 00000000..c9f83dafBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-22.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-23.woff2 b/packages/ui/src/fonts/misans/misans-400-23.woff2new file mode 100644index 00000000..ac21cf25Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-23.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-24.woff2 b/packages/ui/src/fonts/misans/misans-400-24.woff2new file mode 100644index 00000000..4e598357Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-24.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-25.woff2 b/packages/ui/src/fonts/misans/misans-400-25.woff2new file mode 100644index 00000000..9e5e4e66Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-25.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-26.woff2 b/packages/ui/src/fonts/misans/misans-400-26.woff2new file mode 100644index 00000000..5925afdaBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-26.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-27.woff2 b/packages/ui/src/fonts/misans/misans-400-27.woff2new file mode 100644index 00000000..69a16f0cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-27.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-28.woff2 b/packages/ui/src/fonts/misans/misans-400-28.woff2new file mode 100644index 00000000..c230b4e2Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-28.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-29.woff2 b/packages/ui/src/fonts/misans/misans-400-29.woff2new file mode 100644index 00000000..e2e153a1Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-29.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-30.woff2 b/packages/ui/src/fonts/misans/misans-400-30.woff2new file mode 100644index 00000000..772720e0Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-30.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-31.woff2 b/packages/ui/src/fonts/misans/misans-400-31.woff2new file mode 100644index 00000000..331e466eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-31.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-32.woff2 b/packages/ui/src/fonts/misans/misans-400-32.woff2new file mode 100644index 00000000..08d9c153Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-32.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-33.woff2 b/packages/ui/src/fonts/misans/misans-400-33.woff2new file mode 100644index 00000000..60f27dd4Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-33.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-34.woff2 b/packages/ui/src/fonts/misans/misans-400-34.woff2new file mode 100644index 00000000..74033682Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-34.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-35.woff2 b/packages/ui/src/fonts/misans/misans-400-35.woff2new file mode 100644index 00000000..14a8d8f7Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-35.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-36.woff2 b/packages/ui/src/fonts/misans/misans-400-36.woff2new file mode 100644index 00000000..61dcaa2cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-36.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-37.woff2 b/packages/ui/src/fonts/misans/misans-400-37.woff2new file mode 100644index 00000000..44bcee00Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-37.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-38.woff2 b/packages/ui/src/fonts/misans/misans-400-38.woff2new file mode 100644index 00000000..14c9014cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-38.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-39.woff2 b/packages/ui/src/fonts/misans/misans-400-39.woff2new file mode 100644index 00000000..b7f0328dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-39.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-40.woff2 b/packages/ui/src/fonts/misans/misans-400-40.woff2new file mode 100644index 00000000..a45441d0Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-40.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-41.woff2 b/packages/ui/src/fonts/misans/misans-400-41.woff2new file mode 100644index 00000000..9a620929Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-41.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-42.woff2 b/packages/ui/src/fonts/misans/misans-400-42.woff2new file mode 100644index 00000000..45649af4Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-42.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-43.woff2 b/packages/ui/src/fonts/misans/misans-400-43.woff2new file mode 100644index 00000000..11db61dfBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-43.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-44.woff2 b/packages/ui/src/fonts/misans/misans-400-44.woff2new file mode 100644index 00000000..cf7df9bdBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-44.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-45.woff2 b/packages/ui/src/fonts/misans/misans-400-45.woff2new file mode 100644index 00000000..67c7deadBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-45.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-46.woff2 b/packages/ui/src/fonts/misans/misans-400-46.woff2new file mode 100644index 00000000..f4d6a2c0Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-46.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-47.woff2 b/packages/ui/src/fonts/misans/misans-400-47.woff2new file mode 100644index 00000000..b7ea25a5Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-47.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-48.woff2 b/packages/ui/src/fonts/misans/misans-400-48.woff2new file mode 100644index 00000000..03100177Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-48.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-49.woff2 b/packages/ui/src/fonts/misans/misans-400-49.woff2new file mode 100644index 00000000..b923aa32Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-49.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-5.woff2 b/packages/ui/src/fonts/misans/misans-400-5.woff2new file mode 100644index 00000000..9eccc164Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-5.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-50.woff2 b/packages/ui/src/fonts/misans/misans-400-50.woff2new file mode 100644index 00000000..f0062876Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-50.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-51.woff2 b/packages/ui/src/fonts/misans/misans-400-51.woff2new file mode 100644index 00000000..9eb4e3a4Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-51.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-52.woff2 b/packages/ui/src/fonts/misans/misans-400-52.woff2new file mode 100644index 00000000..09bf60c1Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-52.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-53.woff2 b/packages/ui/src/fonts/misans/misans-400-53.woff2new file mode 100644index 00000000..dc03b7c6Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-53.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-54.woff2 b/packages/ui/src/fonts/misans/misans-400-54.woff2new file mode 100644index 00000000..65eced55Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-54.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-55.woff2 b/packages/ui/src/fonts/misans/misans-400-55.woff2new file mode 100644index 00000000..ac2fe2d9Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-55.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-56.woff2 b/packages/ui/src/fonts/misans/misans-400-56.woff2new file mode 100644index 00000000..293e93afBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-56.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-57.woff2 b/packages/ui/src/fonts/misans/misans-400-57.woff2new file mode 100644index 00000000..6d336de9Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-57.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-58.woff2 b/packages/ui/src/fonts/misans/misans-400-58.woff2new file mode 100644index 00000000..e7d13275Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-58.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-59.woff2 b/packages/ui/src/fonts/misans/misans-400-59.woff2new file mode 100644index 00000000..89ecb151Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-59.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-6.woff2 b/packages/ui/src/fonts/misans/misans-400-6.woff2new file mode 100644index 00000000..125a47abBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-6.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-60.woff2 b/packages/ui/src/fonts/misans/misans-400-60.woff2new file mode 100644index 00000000..d9173966Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-60.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-61.woff2 b/packages/ui/src/fonts/misans/misans-400-61.woff2new file mode 100644index 00000000..35e93dedBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-61.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-62.woff2 b/packages/ui/src/fonts/misans/misans-400-62.woff2new file mode 100644index 00000000..dce4d781Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-62.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-63.woff2 b/packages/ui/src/fonts/misans/misans-400-63.woff2new file mode 100644index 00000000..a7a7e256Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-63.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-64.woff2 b/packages/ui/src/fonts/misans/misans-400-64.woff2new file mode 100644index 00000000..333d9801Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-64.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-65.woff2 b/packages/ui/src/fonts/misans/misans-400-65.woff2new file mode 100644index 00000000..cf0aa679Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-65.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-66.woff2 b/packages/ui/src/fonts/misans/misans-400-66.woff2new file mode 100644index 00000000..3507f8ffBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-66.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-67.woff2 b/packages/ui/src/fonts/misans/misans-400-67.woff2new file mode 100644index 00000000..e95b110eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-67.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-68.woff2 b/packages/ui/src/fonts/misans/misans-400-68.woff2new file mode 100644index 00000000..a48352cfBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-68.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-69.woff2 b/packages/ui/src/fonts/misans/misans-400-69.woff2new file mode 100644index 00000000..728bd8e3Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-69.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-70.woff2 b/packages/ui/src/fonts/misans/misans-400-70.woff2new file mode 100644index 00000000..1d83b167Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-70.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-71.woff2 b/packages/ui/src/fonts/misans/misans-400-71.woff2new file mode 100644index 00000000..d6fa8a0dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-71.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-72.woff2 b/packages/ui/src/fonts/misans/misans-400-72.woff2new file mode 100644index 00000000..b20367daBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-72.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-73.woff2 b/packages/ui/src/fonts/misans/misans-400-73.woff2new file mode 100644index 00000000..646313acBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-73.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-74.woff2 b/packages/ui/src/fonts/misans/misans-400-74.woff2new file mode 100644index 00000000..5bc065fcBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-74.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-75.woff2 b/packages/ui/src/fonts/misans/misans-400-75.woff2new file mode 100644index 00000000..7c5bdbb7Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-75.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-76.woff2 b/packages/ui/src/fonts/misans/misans-400-76.woff2new file mode 100644index 00000000..9565e21bBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-76.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-77.woff2 b/packages/ui/src/fonts/misans/misans-400-77.woff2new file mode 100644index 00000000..22471324Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-77.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-78.woff2 b/packages/ui/src/fonts/misans/misans-400-78.woff2new file mode 100644index 00000000..ec32ac1fBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-78.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-79.woff2 b/packages/ui/src/fonts/misans/misans-400-79.woff2new file mode 100644index 00000000..a3d58c68Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-79.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-80.woff2 b/packages/ui/src/fonts/misans/misans-400-80.woff2new file mode 100644index 00000000..b331e001Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-80.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-81.woff2 b/packages/ui/src/fonts/misans/misans-400-81.woff2new file mode 100644index 00000000..a1b40e8eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-81.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-82.woff2 b/packages/ui/src/fonts/misans/misans-400-82.woff2new file mode 100644index 00000000..d3adb2dbBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-82.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-83.woff2 b/packages/ui/src/fonts/misans/misans-400-83.woff2new file mode 100644index 00000000..05e67680Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-83.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-84.woff2 b/packages/ui/src/fonts/misans/misans-400-84.woff2new file mode 100644index 00000000..c8e968e3Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-84.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-85.woff2 b/packages/ui/src/fonts/misans/misans-400-85.woff2new file mode 100644index 00000000..afaf867aBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-85.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-86.woff2 b/packages/ui/src/fonts/misans/misans-400-86.woff2new file mode 100644index 00000000..309e9640Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-86.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-87.woff2 b/packages/ui/src/fonts/misans/misans-400-87.woff2new file mode 100644index 00000000..a72b9d38Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-87.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-88.woff2 b/packages/ui/src/fonts/misans/misans-400-88.woff2new file mode 100644index 00000000..b87a99e5Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-88.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-89.woff2 b/packages/ui/src/fonts/misans/misans-400-89.woff2new file mode 100644index 00000000..7139d78aBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-89.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-90.woff2 b/packages/ui/src/fonts/misans/misans-400-90.woff2new file mode 100644index 00000000..b938f709Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-90.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-91.woff2 b/packages/ui/src/fonts/misans/misans-400-91.woff2new file mode 100644index 00000000..4426929eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-91.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-97.woff2 b/packages/ui/src/fonts/misans/misans-400-97.woff2new file mode 100644index 00000000..51863b08Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-97.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-cyrillic.woff2 b/packages/ui/src/fonts/misans/misans-400-cyrillic.woff2new file mode 100644index 00000000..4f74702dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-cyrillic.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-extra.woff2 b/packages/ui/src/fonts/misans/misans-400-extra.woff2new file mode 100644index 00000000..89161c4fBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-extra.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-latin-ext.woff2 b/packages/ui/src/fonts/misans/misans-400-latin-ext.woff2new file mode 100644index 00000000..2cfb6f80Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-latin-ext.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-latin.woff2 b/packages/ui/src/fonts/misans/misans-400-latin.woff2new file mode 100644index 00000000..d5eee547Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-latin.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-400-vietnamese.woff2 b/packages/ui/src/fonts/misans/misans-400-vietnamese.woff2new file mode 100644index 00000000..5951d96eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-400-vietnamese.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-100.woff2 b/packages/ui/src/fonts/misans/misans-500-100.woff2new file mode 100644index 00000000..4d4bbf31Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-100.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-101.woff2 b/packages/ui/src/fonts/misans/misans-500-101.woff2new file mode 100644index 00000000..5de2884cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-101.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-102.woff2 b/packages/ui/src/fonts/misans/misans-500-102.woff2new file mode 100644index 00000000..d62bd342Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-102.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-103.woff2 b/packages/ui/src/fonts/misans/misans-500-103.woff2new file mode 100644index 00000000..805e7f1aBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-103.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-104.woff2 b/packages/ui/src/fonts/misans/misans-500-104.woff2new file mode 100644index 00000000..474a09ceBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-104.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-105.woff2 b/packages/ui/src/fonts/misans/misans-500-105.woff2new file mode 100644index 00000000..2601361dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-105.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-106.woff2 b/packages/ui/src/fonts/misans/misans-500-106.woff2new file mode 100644index 00000000..ba45a786Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-106.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-107.woff2 b/packages/ui/src/fonts/misans/misans-500-107.woff2new file mode 100644index 00000000..c7df4a76Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-107.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-108.woff2 b/packages/ui/src/fonts/misans/misans-500-108.woff2new file mode 100644index 00000000..e19de4a2Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-108.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-109.woff2 b/packages/ui/src/fonts/misans/misans-500-109.woff2new file mode 100644index 00000000..081b5eeeBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-109.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-110.woff2 b/packages/ui/src/fonts/misans/misans-500-110.woff2new file mode 100644index 00000000..7c555f7bBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-110.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-111.woff2 b/packages/ui/src/fonts/misans/misans-500-111.woff2new file mode 100644index 00000000..e088fb4dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-111.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-112.woff2 b/packages/ui/src/fonts/misans/misans-500-112.woff2new file mode 100644index 00000000..44a3e8b7Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-112.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-113.woff2 b/packages/ui/src/fonts/misans/misans-500-113.woff2new file mode 100644index 00000000..8930a9f0Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-113.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-114.woff2 b/packages/ui/src/fonts/misans/misans-500-114.woff2new file mode 100644index 00000000..823841d6Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-114.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-115.woff2 b/packages/ui/src/fonts/misans/misans-500-115.woff2new file mode 100644index 00000000..937bdbb3Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-115.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-116.woff2 b/packages/ui/src/fonts/misans/misans-500-116.woff2new file mode 100644index 00000000..af1d61eaBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-116.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-117.woff2 b/packages/ui/src/fonts/misans/misans-500-117.woff2new file mode 100644index 00000000..91091513Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-117.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-118.woff2 b/packages/ui/src/fonts/misans/misans-500-118.woff2new file mode 100644index 00000000..9fedae97Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-118.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-119.woff2 b/packages/ui/src/fonts/misans/misans-500-119.woff2new file mode 100644index 00000000..c9d6e81cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-119.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-21.woff2 b/packages/ui/src/fonts/misans/misans-500-21.woff2new file mode 100644index 00000000..abcf995eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-21.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-22.woff2 b/packages/ui/src/fonts/misans/misans-500-22.woff2new file mode 100644index 00000000..864a9b28Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-22.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-23.woff2 b/packages/ui/src/fonts/misans/misans-500-23.woff2new file mode 100644index 00000000..46e4f9bdBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-23.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-24.woff2 b/packages/ui/src/fonts/misans/misans-500-24.woff2new file mode 100644index 00000000..829b9399Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-24.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-25.woff2 b/packages/ui/src/fonts/misans/misans-500-25.woff2new file mode 100644index 00000000..cd8492b5Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-25.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-26.woff2 b/packages/ui/src/fonts/misans/misans-500-26.woff2new file mode 100644index 00000000..57b6696dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-26.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-27.woff2 b/packages/ui/src/fonts/misans/misans-500-27.woff2new file mode 100644index 00000000..18b2e23aBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-27.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-28.woff2 b/packages/ui/src/fonts/misans/misans-500-28.woff2new file mode 100644index 00000000..05f1e087Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-28.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-29.woff2 b/packages/ui/src/fonts/misans/misans-500-29.woff2new file mode 100644index 00000000..86f6e80eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-29.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-30.woff2 b/packages/ui/src/fonts/misans/misans-500-30.woff2new file mode 100644index 00000000..6b5ca6e8Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-30.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-31.woff2 b/packages/ui/src/fonts/misans/misans-500-31.woff2new file mode 100644index 00000000..2edb13f3Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-31.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-32.woff2 b/packages/ui/src/fonts/misans/misans-500-32.woff2new file mode 100644index 00000000..bb88d8d1Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-32.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-33.woff2 b/packages/ui/src/fonts/misans/misans-500-33.woff2new file mode 100644index 00000000..2e3d7670Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-33.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-34.woff2 b/packages/ui/src/fonts/misans/misans-500-34.woff2new file mode 100644index 00000000..d758c2edBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-34.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-35.woff2 b/packages/ui/src/fonts/misans/misans-500-35.woff2new file mode 100644index 00000000..81adc94eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-35.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-36.woff2 b/packages/ui/src/fonts/misans/misans-500-36.woff2new file mode 100644index 00000000..f92b8756Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-36.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-37.woff2 b/packages/ui/src/fonts/misans/misans-500-37.woff2new file mode 100644index 00000000..1e3ffd14Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-37.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-38.woff2 b/packages/ui/src/fonts/misans/misans-500-38.woff2new file mode 100644index 00000000..3a8dba14Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-38.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-39.woff2 b/packages/ui/src/fonts/misans/misans-500-39.woff2new file mode 100644index 00000000..2622b73fBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-39.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-40.woff2 b/packages/ui/src/fonts/misans/misans-500-40.woff2new file mode 100644index 00000000..69d611a4Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-40.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-41.woff2 b/packages/ui/src/fonts/misans/misans-500-41.woff2new file mode 100644index 00000000..2770a43dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-41.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-42.woff2 b/packages/ui/src/fonts/misans/misans-500-42.woff2new file mode 100644index 00000000..8389c217Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-42.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-43.woff2 b/packages/ui/src/fonts/misans/misans-500-43.woff2new file mode 100644index 00000000..3bc70f4dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-43.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-44.woff2 b/packages/ui/src/fonts/misans/misans-500-44.woff2new file mode 100644index 00000000..85ba7331Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-44.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-45.woff2 b/packages/ui/src/fonts/misans/misans-500-45.woff2new file mode 100644index 00000000..3f3b60b8Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-45.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-46.woff2 b/packages/ui/src/fonts/misans/misans-500-46.woff2new file mode 100644index 00000000..c984ed60Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-46.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-47.woff2 b/packages/ui/src/fonts/misans/misans-500-47.woff2new file mode 100644index 00000000..38824d5cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-47.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-48.woff2 b/packages/ui/src/fonts/misans/misans-500-48.woff2new file mode 100644index 00000000..8fc4fb41Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-48.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-49.woff2 b/packages/ui/src/fonts/misans/misans-500-49.woff2new file mode 100644index 00000000..bd267336Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-49.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-5.woff2 b/packages/ui/src/fonts/misans/misans-500-5.woff2new file mode 100644index 00000000..b243987bBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-5.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-50.woff2 b/packages/ui/src/fonts/misans/misans-500-50.woff2new file mode 100644index 00000000..ea1ca8bfBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-50.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-51.woff2 b/packages/ui/src/fonts/misans/misans-500-51.woff2new file mode 100644index 00000000..fa155c75Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-51.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-52.woff2 b/packages/ui/src/fonts/misans/misans-500-52.woff2new file mode 100644index 00000000..7cd077f6Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-52.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-53.woff2 b/packages/ui/src/fonts/misans/misans-500-53.woff2new file mode 100644index 00000000..cbad9b6aBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-53.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-54.woff2 b/packages/ui/src/fonts/misans/misans-500-54.woff2new file mode 100644index 00000000..b3093aa1Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-54.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-55.woff2 b/packages/ui/src/fonts/misans/misans-500-55.woff2new file mode 100644index 00000000..0f7ea8beBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-55.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-56.woff2 b/packages/ui/src/fonts/misans/misans-500-56.woff2new file mode 100644index 00000000..bb21a13cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-56.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-57.woff2 b/packages/ui/src/fonts/misans/misans-500-57.woff2new file mode 100644index 00000000..d45d7b60Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-57.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-58.woff2 b/packages/ui/src/fonts/misans/misans-500-58.woff2new file mode 100644index 00000000..a31d7fd6Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-58.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-59.woff2 b/packages/ui/src/fonts/misans/misans-500-59.woff2new file mode 100644index 00000000..e81f4044Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-59.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-6.woff2 b/packages/ui/src/fonts/misans/misans-500-6.woff2new file mode 100644index 00000000..66b0923dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-6.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-60.woff2 b/packages/ui/src/fonts/misans/misans-500-60.woff2new file mode 100644index 00000000..618e0d0dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-60.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-61.woff2 b/packages/ui/src/fonts/misans/misans-500-61.woff2new file mode 100644index 00000000..bb9f713eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-61.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-62.woff2 b/packages/ui/src/fonts/misans/misans-500-62.woff2new file mode 100644index 00000000..780fdd9eBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-62.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-63.woff2 b/packages/ui/src/fonts/misans/misans-500-63.woff2new file mode 100644index 00000000..1be00279Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-63.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-64.woff2 b/packages/ui/src/fonts/misans/misans-500-64.woff2new file mode 100644index 00000000..1761097bBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-64.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-65.woff2 b/packages/ui/src/fonts/misans/misans-500-65.woff2new file mode 100644index 00000000..f4b73247Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-65.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-66.woff2 b/packages/ui/src/fonts/misans/misans-500-66.woff2new file mode 100644index 00000000..1da62cb1Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-66.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-67.woff2 b/packages/ui/src/fonts/misans/misans-500-67.woff2new file mode 100644index 00000000..106415a9Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-67.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-68.woff2 b/packages/ui/src/fonts/misans/misans-500-68.woff2new file mode 100644index 00000000..df3b1df4Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-68.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-69.woff2 b/packages/ui/src/fonts/misans/misans-500-69.woff2new file mode 100644index 00000000..a7678c18Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-69.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-70.woff2 b/packages/ui/src/fonts/misans/misans-500-70.woff2new file mode 100644index 00000000..f896da52Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-70.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-71.woff2 b/packages/ui/src/fonts/misans/misans-500-71.woff2new file mode 100644index 00000000..19c4fdcaBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-71.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-72.woff2 b/packages/ui/src/fonts/misans/misans-500-72.woff2new file mode 100644index 00000000..8e53e29cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-72.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-73.woff2 b/packages/ui/src/fonts/misans/misans-500-73.woff2new file mode 100644index 00000000..b671bf14Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-73.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-74.woff2 b/packages/ui/src/fonts/misans/misans-500-74.woff2new file mode 100644index 00000000..e799de7bBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-74.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-75.woff2 b/packages/ui/src/fonts/misans/misans-500-75.woff2new file mode 100644index 00000000..727a1fd3Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-75.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-76.woff2 b/packages/ui/src/fonts/misans/misans-500-76.woff2new file mode 100644index 00000000..ced8a729Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-76.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-77.woff2 b/packages/ui/src/fonts/misans/misans-500-77.woff2new file mode 100644index 00000000..afa940f2Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-77.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-78.woff2 b/packages/ui/src/fonts/misans/misans-500-78.woff2new file mode 100644index 00000000..149c76a8Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-78.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-79.woff2 b/packages/ui/src/fonts/misans/misans-500-79.woff2new file mode 100644index 00000000..8d47b6c7Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-79.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-80.woff2 b/packages/ui/src/fonts/misans/misans-500-80.woff2new file mode 100644index 00000000..adf7d716Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-80.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-81.woff2 b/packages/ui/src/fonts/misans/misans-500-81.woff2new file mode 100644index 00000000..7069053cBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-81.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-82.woff2 b/packages/ui/src/fonts/misans/misans-500-82.woff2new file mode 100644index 00000000..71fca1baBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-82.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-83.woff2 b/packages/ui/src/fonts/misans/misans-500-83.woff2new file mode 100644index 00000000..e43857afBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-83.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-84.woff2 b/packages/ui/src/fonts/misans/misans-500-84.woff2new file mode 100644index 00000000..1b4fbda3Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-84.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-85.woff2 b/packages/ui/src/fonts/misans/misans-500-85.woff2new file mode 100644index 00000000..cbb77efdBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-85.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-86.woff2 b/packages/ui/src/fonts/misans/misans-500-86.woff2new file mode 100644index 00000000..9dcbde72Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-86.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-87.woff2 b/packages/ui/src/fonts/misans/misans-500-87.woff2new file mode 100644index 00000000..97efe028Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-87.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-88.woff2 b/packages/ui/src/fonts/misans/misans-500-88.woff2new file mode 100644index 00000000..425758fcBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-88.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-89.woff2 b/packages/ui/src/fonts/misans/misans-500-89.woff2new file mode 100644index 00000000..7814836dBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-89.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-90.woff2 b/packages/ui/src/fonts/misans/misans-500-90.woff2new file mode 100644index 00000000..fb351175Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-90.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-91.woff2 b/packages/ui/src/fonts/misans/misans-500-91.woff2new file mode 100644index 00000000..37a1bc41Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-91.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-97.woff2 b/packages/ui/src/fonts/misans/misans-500-97.woff2new file mode 100644index 00000000..a948ac2bBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-97.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-cyrillic.woff2 b/packages/ui/src/fonts/misans/misans-500-cyrillic.woff2new file mode 100644index 00000000..5db8d486Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-cyrillic.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-extra.woff2 b/packages/ui/src/fonts/misans/misans-500-extra.woff2new file mode 100644index 00000000..de2bc7beBinary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-extra.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-latin-ext.woff2 b/packages/ui/src/fonts/misans/misans-500-latin-ext.woff2new file mode 100644index 00000000..c7b649a5Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-latin-ext.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-latin.woff2 b/packages/ui/src/fonts/misans/misans-500-latin.woff2new file mode 100644index 00000000..0c39fbf5Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-latin.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans-500-vietnamese.woff2 b/packages/ui/src/fonts/misans/misans-500-vietnamese.woff2new file mode 100644index 00000000..4fc9cd19Binary files /dev/null and b/packages/ui/src/fonts/misans/misans-500-vietnamese.woff2 differdiff --git a/packages/ui/src/fonts/misans/misans.css b/packages/ui/src/fonts/misans/misans.cssnew file mode 100644index 00000000..53a0272d--- /dev/null+++ b/packages/ui/src/fonts/misans/misans.css@@ -0,0 +1,1794 @@+/**+ * GENERATED by packages/ui/scripts/build-misans.py; do not edit, rerun the script.+ *+ * MiSans 4.009 by Xiaomi Inc., from the official package https://hyperos.mi.com/font-download/MiSans.zip:+ * MiSans Regular as weight 400 and MiSans Medium as weight 500, 99 slices each: one per+ * slice of the unicode-range partition of @fontsource-variable/noto-sans-sc 5.3.0 that+ * MiSans has characters for, plus `extra` for its other non-ideograph characters. Ideographs+ * outside the partition are not shipped and fall back to the system CJK face.+ *+ * Licence: the MiSans Font Intellectual Property License Agreement (fonts/LICENSES/misans.txt).+ * The software must state that it uses MiSans, and the font is never offered on its own.+ */++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-5.woff2") format("woff2");+ unicode-range: U+FF03-FF04, U+FF07, U+FF0A, U+FF17-FF19, U+FF1C-FF1E, U+FF20-FF3A, U+FF3C, U+FF3E-FF5B, U+FF5D, U+FFE0-FFE4;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-6.woff2") format("woff2");+ unicode-range: U+F92C, U+F979, U+FA11, U+FE30-FE31, U+FE33-FE44, U+FE49-FE52, U+FE54-FE57, U+FE59-FE66, U+FE68-FE6B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-21.woff2") format("woff2");+ unicode-range: U+9F83, U+9F85-9F8D, U+9F90-9F91, U+9F94-9F96, U+9F98, U+9F9B-9F9C, U+9F9E, U+9FA0, U+9FA2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-22.woff2") format("woff2");+ unicode-range: U+9E30-9E33, U+9E35-9E3B, U+9E3E, U+9E40-9E44, U+9E46-9E4E, U+9E51, U+9E53, U+9E55-9E58, U+9E5A-9E5C, U+9E5E-9E63, U+9E66-9E6E, U+9E71, U+9E73, U+9E75, U+9E78-9E79, U+9E7C-9E7E, U+9E82, U+9E86-9E88, U+9E8B-9E8C, U+9E90-9E91, U+9E93, U+9E95, U+9E97, U+9E9D, U+9EA4-9EA5, U+9EA9-9EAA, U+9EB4-9EB5, U+9EB8-9EBA, U+9EBC-9EBF, U+9EC3, U+9EC9, U+9ECD, U+9ED0, U+9ED2-9ED3, U+9ED5-9ED6, U+9ED9, U+9EDC-9EDD, U+9EDF-9EE0, U+9EE2, U+9EE5, U+9EE7-9EEA, U+9EEF, U+9EF1, U+9EF3-9EF4, U+9EF6, U+9EF9, U+9EFB-9EFC, U+9EFE, U+9F0B, U+9F0D, U+9F10, U+9F14, U+9F17, U+9F19, U+9F22, U+9F29, U+9F2C, U+9F2F, U+9F31, U+9F37, U+9F39, U+9F3D-9F3E, U+9F41, U+9F4A-9F4B, U+9F51-9F52, U+9F61-9F63, U+9F66-9F67, U+9F80-9F81;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-23.woff2") format("woff2");+ unicode-range: U+9C82-9C83, U+9C85-9C8C, U+9C8E-9C92, U+9C94-9C9B, U+9C9E-9CA3, U+9CA5-9CA7, U+9CA9, U+9CAB, U+9CAD-9CAE, U+9CB1-9CB7, U+9CB9-9CBD, U+9CBF-9CC0, U+9CC3, U+9CC5-9CC7, U+9CC9-9CD1, U+9CD3-9CDA, U+9CDC-9CDD, U+9CDF, U+9CE1-9CE3, U+9CE5, U+9CE9, U+9CEE-9CEF, U+9CF3-9CF4, U+9CF6, U+9CFC-9CFD, U+9D02, U+9D08-9D09, U+9D12, U+9D1B, U+9D1E, U+9D26, U+9D28, U+9D37, U+9D3B, U+9D3F, U+9D51, U+9D59, U+9D5C-9D5D, U+9D5F-9D61, U+9D6C, U+9D70, U+9D72, U+9D7A, U+9D7E, U+9D84, U+9D89, U+9D8F, U+9D92, U+9DAF, U+9DB4, U+9DB8, U+9DBC, U+9DC4, U+9DC7, U+9DC9, U+9DD7, U+9DDF, U+9DF2, U+9DF9-9DFA, U+9E0A, U+9E11, U+9E1A, U+9E1E, U+9E20, U+9E22, U+9E28-9E2C, U+9E2E-9E2F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-24.woff2") format("woff2");+ unicode-range: U+9A80, U+9A83, U+9A85, U+9A88-9A8A, U+9A8D-9A8E, U+9A90, U+9A92-9A93, U+9A95-9A96, U+9A98-9A99, U+9A9B-9AA2, U+9AA5, U+9AA7, U+9AAF-9AB1, U+9AB5-9AB6, U+9AB9-9ABA, U+9AC0-9AC4, U+9AC8, U+9ACB-9ACC, U+9ACE-9ACF, U+9AD1-9AD2, U+9AD9, U+9ADF, U+9AE1, U+9AE3, U+9AEA-9AEB, U+9AED-9AEF, U+9AF4, U+9AF9, U+9AFB, U+9B03-9B04, U+9B06, U+9B08, U+9B0D, U+9B0F-9B10, U+9B13, U+9B18, U+9B1A, U+9B1F, U+9B22-9B23, U+9B25, U+9B27-9B28, U+9B2A, U+9B2F, U+9B31-9B32, U+9B3B, U+9B43, U+9B46-9B49, U+9B4D-9B4E, U+9B51, U+9B56, U+9B58, U+9B5A, U+9B5C, U+9B5F, U+9B61-9B62, U+9B6F, U+9B77, U+9B80, U+9B88, U+9B8B, U+9B8E, U+9B91, U+9B9F-9BA0, U+9BA8, U+9BAA-9BAB, U+9BAD-9BAE, U+9BB0-9BB1, U+9BB8, U+9BC9-9BCA, U+9BD3, U+9BD6, U+9BDB, U+9BE8, U+9BF0-9BF1, U+9C02, U+9C10, U+9C15, U+9C24, U+9C2D, U+9C32, U+9C39, U+9C3B, U+9C40, U+9C47-9C49, U+9C53, U+9C57, U+9C64, U+9C72, U+9C77-9C78, U+9C7B, U+9C7F-9C80;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-25.woff2") format("woff2");+ unicode-range: U+98DD, U+98E1-98E2, U+98E7-98EA, U+98EC, U+98EE-98EF, U+98F2, U+98F4, U+98FC-98FE, U+9903, U+9905, U+9908, U+990A, U+990C-990D, U+9913-9914, U+9918, U+991A-991B, U+991E, U+9921, U+9928, U+992C, U+992E, U+9935, U+9938-9939, U+993D-993E, U+9945, U+994B-994C, U+9951-9952, U+9954-9955, U+9957, U+995E, U+9963, U+9966-9969, U+996B-996C, U+996F, U+9974-9975, U+9977-9979, U+997D-997E, U+9980-9981, U+9983-9984, U+9987, U+998A-998B, U+998D-9991, U+9993-9995, U+9997-9998, U+99A5, U+99AB, U+99AD-99AE, U+99B1, U+99B3-99B4, U+99BC, U+99BF, U+99C1, U+99C3-99C6, U+99CC, U+99D0, U+99D2, U+99D5, U+99DB, U+99DD, U+99E1, U+99ED, U+99F1, U+99FF, U+9A01, U+9A03-9A04, U+9A0E-9A0F, U+9A11-9A13, U+9A19, U+9A1B, U+9A28, U+9A2B, U+9A30, U+9A32, U+9A37, U+9A40, U+9A45, U+9A4A, U+9A4D-9A4E, U+9A52, U+9A55, U+9A57, U+9A5A-9A5B, U+9A5F, U+9A62, U+9A65, U+9A69, U+9A6B, U+9A6E, U+9A75, U+9A77-9A7A, U+9A7D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-26.woff2") format("woff2");+ unicode-range: U+975B-975C, U+9763, U+9765-9766, U+976C-976D, U+9773, U+9776, U+977A, U+977C, U+9784-9785, U+978E-978F, U+9791-9792, U+9794-9795, U+9798, U+979A, U+979E, U+97A3, U+97A5-97A6, U+97A8, U+97AB-97AC, U+97AE-97AF, U+97B2, U+97B4, U+97C6, U+97CB-97CC, U+97D3, U+97D8, U+97DC, U+97E1, U+97EA-97EB, U+97EE, U+97FB, U+97FE-97FF, U+9801-9803, U+9805-9806, U+9808, U+980C, U+9810-9814, U+9817-9818, U+981E, U+9820-9821, U+9824, U+9828, U+982B-982D, U+9830, U+9834, U+9838-9839, U+983C, U+9846, U+984D-984F, U+9851-9852, U+9854-9855, U+9857-9858, U+985A-985B, U+9862-9863, U+9865, U+9867, U+986B, U+986F-9871, U+9877-9878, U+987C, U+9880, U+9883, U+9885, U+9889, U+988B-988F, U+9893-9895, U+9899-989B, U+989E-989F, U+98A1-98A2, U+98A5-98A7, U+98A9, U+98AF, U+98B1, U+98B6, U+98BA, U+98BE, U+98C3-98C4, U+98C6-98C8, U+98CF-98D6, U+98DA-98DB;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-27.woff2") format("woff2");+ unicode-range: U+95C4-95CA, U+95CC-95CD, U+95D4-95D6, U+95D8, U+95E1-95E2, U+95E9, U+95F0-95F1, U+95F3, U+95F6, U+95FC, U+95FE-95FF, U+9602-9604, U+9606-960D, U+960F, U+9611-9613, U+9615-9617, U+9619-961B, U+961D, U+9621, U+9628, U+962F, U+963C-963E, U+9641-9642, U+9649, U+9654, U+965B-965F, U+9661, U+9663, U+9665, U+9667-9668, U+966C, U+9670, U+9672-9674, U+9678, U+967A, U+967D, U+9682, U+9685, U+9688, U+968A, U+968D-968E, U+9695, U+9697-9698, U+969E, U+96A0, U+96A3-96A4, U+96A8, U+96AA, U+96B0-96B1, U+96B3-96B4, U+96B7-96B9, U+96BB-96BD, U+96C9, U+96CB, U+96CE, U+96D1-96D2, U+96D6, U+96D9, U+96DB-96DC, U+96DE, U+96E0, U+96E3, U+96E9, U+96EB, U+96F0-96F2, U+96F9, U+96FF, U+9701-9702, U+9705, U+9708, U+970A, U+970E-970F, U+9711, U+9719, U+9727, U+972A, U+972D, U+9730, U+973D, U+9742, U+9744, U+9748-9749, U+9750-9751, U+975A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-28.woff2") format("woff2");+ unicode-range: U+94F5, U+94F7, U+94F9, U+94FB-94FD, U+94FF, U+9503-9504, U+9506-9507, U+9509-950A, U+950D-950F, U+9511-9518, U+951A-9520, U+9522, U+9528-952D, U+9530-953A, U+953C-953F, U+9543-9546, U+9548-9550, U+9552-9555, U+9557-955B, U+955D-9568, U+956A-956D, U+9570-9574, U+9583, U+9586, U+9589, U+958E-958F, U+9591-9592, U+9594, U+9598-9599, U+959E-95A0, U+95A2-95A6, U+95A8-95B2, U+95B4, U+95B8-95C3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-29.woff2") format("woff2");+ unicode-range: U+941C-942B, U+942D-942E, U+9432-9433, U+9435, U+9438, U+943A, U+943E, U+9444, U+944A, U+9451-9452, U+945A, U+9462-9463, U+9465, U+9470-9487, U+948A-9492, U+9494-9498, U+949A, U+949C-949D, U+94A1, U+94A3-94A4, U+94A8, U+94AA-94AD, U+94AF, U+94B2, U+94B4-94BA, U+94BC-94C0, U+94C4, U+94C6-94DB, U+94DE-94EC, U+94EE-94F1, U+94F3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-30.woff2") format("woff2");+ unicode-range: U+92EC-92ED, U+92F0, U+92F3, U+92F8, U+92FC, U+9304, U+9306, U+9310, U+9312, U+9315, U+9318, U+931A, U+931E, U+9320-9322, U+9324, U+9326-9329, U+932B-932C, U+932F, U+9331-9332, U+9335-9336, U+933E, U+9340-9341, U+934A-9360, U+9362-9363, U+9365-936B, U+936E, U+9375, U+937E, U+9382, U+938A, U+938C, U+938F, U+9393-9394, U+9396-9397, U+939A, U+93A2, U+93A7, U+93AC-93CD, U+93D0-93D1, U+93D6-93D8, U+93DE-93DF, U+93E1-93E2, U+93E4, U+93F8, U+93FB, U+93FD, U+940E-941A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-31.woff2") format("woff2");+ unicode-range: U+9163-9164, U+9169, U+9170, U+9172, U+9174, U+9179-917A, U+917D-917E, U+9182-9183, U+9185, U+918C-918D, U+9190-9191, U+919A, U+919C, U+91A1-91A4, U+91A8, U+91AA-91AF, U+91B4-91B5, U+91B8, U+91BA, U+91BE, U+91C0-91C1, U+91C6, U+91C8, U+91CB, U+91D0, U+91D2, U+91D7-91D8, U+91DD, U+91E3, U+91E6-91E7, U+91ED, U+91F0, U+91F5, U+91F9, U+9200, U+9205, U+9207-920A, U+920D-920E, U+9210, U+9214-9215, U+921C, U+921E, U+9221, U+9223-9227, U+9229-922A, U+922D, U+9234-9235, U+9237, U+9239-923A, U+923C-9240, U+9244-9246, U+9249, U+924E-924F, U+9251, U+9253, U+9257, U+925B, U+925E, U+9262, U+9264-9266, U+9268, U+926C, U+926F, U+9271, U+927B, U+927E, U+9280, U+9283, U+9285-928A, U+928E, U+9291, U+9293, U+9296, U+9298, U+929C-929D, U+92A8, U+92AB-92AE, U+92B3, U+92B6-92B7, U+92B9, U+92C1, U+92C5-92C6, U+92C8, U+92CC, U+92D0, U+92D2, U+92E4, U+92EA;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-32.woff2") format("woff2");+ unicode-range: U+9004, U+900B, U+9011, U+9015-9016, U+901E, U+9021, U+9026, U+902D, U+902F, U+9031, U+9035-9036, U+9039-903A, U+9041, U+9044-9046, U+904A, U+904F-9052, U+9054-9055, U+9058-9059, U+905B-905E, U+9060-9062, U+9068-9069, U+906F, U+9072, U+9074, U+9076-907A, U+907C-907D, U+9081, U+9083, U+9085, U+9087-908B, U+908F, U+9095, U+9097, U+9099-909B, U+909D, U+90A0-90A1, U+90A8-90A9, U+90AC, U+90B0, U+90B2-90B4, U+90B6, U+90B8, U+90BA, U+90BD-90BE, U+90C3-90C5, U+90C7-90C8, U+90CF-90D0, U+90D3, U+90D5, U+90D7, U+90DA-90DC, U+90DE, U+90E2, U+90E4, U+90E6-90E7, U+90EA-90EB, U+90EF, U+90F4-90F5, U+90F7, U+90FE-9100, U+9104, U+9109, U+910C, U+9112, U+9114-9115, U+9118, U+911C, U+911E, U+9120, U+9122-9123, U+9127, U+912D, U+912F-9132, U+9139-913A, U+9143, U+9146, U+9149-914A, U+914C, U+914E-9150, U+9154, U+9157, U+915A, U+915D-915E, U+9161-9162;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-33.woff2") format("woff2");+ unicode-range: U+8E41-8E42, U+8E47, U+8E49-8E4B, U+8E50-8E53, U+8E59-8E5A, U+8E5F-8E60, U+8E64, U+8E69, U+8E6C, U+8E70, U+8E74, U+8E76, U+8E7A-8E7C, U+8E7F, U+8E84-8E85, U+8E87, U+8E89, U+8E8B, U+8E8D, U+8E8F-8E90, U+8E94, U+8E99, U+8E9C, U+8E9E, U+8EAA, U+8EAC, U+8EB0, U+8EB6, U+8EC0, U+8EC6, U+8ECA-8ECE, U+8ED2, U+8EDA, U+8EDF, U+8EE2, U+8EEB, U+8EF8, U+8EFB-8EFE, U+8F03, U+8F09, U+8F0B, U+8F12-8F15, U+8F1B, U+8F1D, U+8F1F, U+8F29-8F2A, U+8F2F, U+8F36, U+8F38, U+8F3B, U+8F3E-8F3F, U+8F44-8F45, U+8F49, U+8F4D-8F4E, U+8F5F, U+8F6B, U+8F6D, U+8F71-8F73, U+8F75-8F76, U+8F78-8F7A, U+8F7C, U+8F7E, U+8F81-8F82, U+8F84, U+8F87, U+8F8A-8F8B, U+8F8D-8F8F, U+8F94-8F95, U+8F97-8F9A, U+8FA6, U+8FAD-8FAF, U+8FB2, U+8FB5-8FB7, U+8FBA-8FBC, U+8FBF, U+8FC2, U+8FCB, U+8FCD, U+8FD3, U+8FD5, U+8FD7, U+8FDA, U+8FE2-8FE5, U+8FE8-8FE9, U+8FEE, U+8FF3-8FF4, U+8FF8, U+8FFA;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-34.woff2") format("woff2");+ unicode-range: U+8CBD, U+8CBF-8CC4, U+8CC7-8CC8, U+8CCA, U+8CCD, U+8CD1, U+8CD3, U+8CDB-8CDC, U+8CDE, U+8CE0, U+8CE2-8CE4, U+8CE6-8CE8, U+8CEA, U+8CED, U+8CF4, U+8CF8, U+8CFA, U+8CFC-8CFD, U+8D04-8D05, U+8D07-8D08, U+8D0A, U+8D0D, U+8D0F, U+8D13-8D14, U+8D16, U+8D1B, U+8D20, U+8D30, U+8D32-8D33, U+8D36, U+8D3B, U+8D3D, U+8D40, U+8D42-8D43, U+8D45-8D46, U+8D48-8D4A, U+8D4D, U+8D51, U+8D53, U+8D55, U+8D59, U+8D5C-8D5D, U+8D5F, U+8D61, U+8D66-8D67, U+8D6A, U+8D6D, U+8D71, U+8D73, U+8D84, U+8D90-8D91, U+8D94-8D95, U+8D99, U+8DA8, U+8DAF, U+8DB1, U+8DB5, U+8DB8, U+8DBA, U+8DBC, U+8DBF, U+8DC2, U+8DC4, U+8DC6, U+8DCB, U+8DCE-8DCF, U+8DD6-8DD7, U+8DDA-8DDB, U+8DDE, U+8DE1, U+8DE3-8DE4, U+8DE9, U+8DEB-8DEC, U+8DF0-8DF1, U+8DF6-8DFD, U+8E05, U+8E07, U+8E09-8E0A, U+8E0C, U+8E0E, U+8E10, U+8E14, U+8E1D-8E1F, U+8E23, U+8E26, U+8E2B-8E31, U+8E34-8E35, U+8E39-8E3A, U+8E3D, U+8E40;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-35.woff2") format("woff2");+ unicode-range: U+8B80, U+8B83, U+8B8A, U+8B8C, U+8B90, U+8B93, U+8B99-8B9A, U+8BA0, U+8BA3, U+8BA5-8BA7, U+8BAA-8BAC, U+8BB4-8BB5, U+8BB7, U+8BB9, U+8BC2-8BC3, U+8BC5, U+8BCB-8BCC, U+8BCE-8BD0, U+8BD2-8BD4, U+8BD6, U+8BD8-8BD9, U+8BDC, U+8BDF, U+8BE3-8BE4, U+8BE7-8BE9, U+8BEB-8BEC, U+8BEE, U+8BF0, U+8BF2-8BF3, U+8BF6, U+8BF9, U+8BFC-8BFD, U+8BFF-8C00, U+8C02, U+8C04, U+8C06-8C07, U+8C0C, U+8C0F, U+8C11-8C12, U+8C14-8C1B, U+8C1D-8C21, U+8C24-8C25, U+8C27, U+8C2A-8C2C, U+8C2E-8C30, U+8C32-8C36, U+8C3F, U+8C47-8C4C, U+8C4E-8C50, U+8C54-8C56, U+8C62, U+8C68, U+8C6C, U+8C73, U+8C78, U+8C7A, U+8C82, U+8C85, U+8C89-8C8A, U+8C8D-8C8E, U+8C90, U+8C93-8C94, U+8C98, U+8C9D-8C9E, U+8CA0-8CA2, U+8CA7-8CAC, U+8CAF-8CB0, U+8CB3-8CB4, U+8CB6-8CB9, U+8CBB-8CBC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-36.woff2") format("woff2");+ unicode-range: U+8A15-8A18, U+8A1A-8A1B, U+8A1D, U+8A1F, U+8A22-8A23, U+8A25, U+8A2B, U+8A2D, U+8A31, U+8A33-8A34, U+8A36-8A38, U+8A3A, U+8A3C, U+8A3E, U+8A40-8A41, U+8A46, U+8A48, U+8A50, U+8A52, U+8A54-8A55, U+8A58, U+8A5B, U+8A5D-8A63, U+8A66, U+8A69-8A6B, U+8A6D-8A6E, U+8A70, U+8A72-8A73, U+8A7A, U+8A85, U+8A87, U+8A8A, U+8A8C-8A8D, U+8A90-8A92, U+8A95, U+8A98, U+8AA0-8AA1, U+8AA3-8AA6, U+8AA8-8AA9, U+8AAC-8AAE, U+8AB0, U+8AB2, U+8AB8-8AB9, U+8ABC, U+8ABE-8ABF, U+8AC7, U+8ACF, U+8AD2, U+8AD6-8AD7, U+8ADB-8ADC, U+8ADF, U+8AE1, U+8AE6-8AE8, U+8AEB, U+8AED-8AEE, U+8AF1, U+8AF3-8AF4, U+8AF7-8AF8, U+8AFA, U+8AFE, U+8B00-8B02, U+8B07, U+8B0A, U+8B0C, U+8B0E, U+8B10, U+8B17, U+8B19, U+8B1B, U+8B1D, U+8B20-8B21, U+8B26, U+8B28, U+8B2C, U+8B33, U+8B39, U+8B3E-8B3F, U+8B41, U+8B45, U+8B49, U+8B4C, U+8B4F, U+8B57-8B58, U+8B5A, U+8B5C, U+8B5E, U+8B60, U+8B6C, U+8B6F-8B70, U+8B72, U+8B74, U+8B77, U+8B7D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-37.woff2") format("woff2");+ unicode-range: U+8882, U+8884-8886, U+8888, U+888F, U+8892-8893, U+889B, U+88A2, U+88A4, U+88A6, U+88A8, U+88AA, U+88AE, U+88B1, U+88B4, U+88B7, U+88BC, U+88C0, U+88C6-88C9, U+88CE-88CF, U+88D1-88D3, U+88D8, U+88DB-88DD, U+88DF, U+88E1-88E3, U+88E5, U+88E8, U+88EC, U+88F0-88F1, U+88F3-88F4, U+88FC-88FE, U+8900, U+8902, U+8906-8907, U+8909-890C, U+8912-8915, U+8918-891B, U+8921, U+8925, U+892B, U+8930, U+8932, U+8934, U+8936, U+893B, U+893D, U+8941, U+894C, U+8955-8956, U+8959, U+895C, U+895E-8960, U+8966, U+896A, U+896C, U+896F-8970, U+8972, U+897B, U+897E, U+8980, U+8983, U+8985, U+8987-8988, U+898C, U+898F, U+8993, U+8997, U+899A, U+89A1, U+89A7, U+89A9-89AA, U+89B2-89B3, U+89B7, U+89C0, U+89C7, U+89CA-89CC, U+89CE-89D1, U+89D6, U+89DA, U+89DC, U+89DE, U+89E5, U+89E7, U+89EB, U+89EF, U+89F1, U+89F3-89F4, U+89F8, U+89FF, U+8A01-8A03, U+8A07-8A0A, U+8A0E-8A0F, U+8A13;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-38.woff2") format("woff2");+ unicode-range: U+86F4, U+86F8-86F9, U+86FB, U+86FE, U+8703, U+8706-870A, U+870D, U+8711-8713, U+871A, U+871E, U+8722-8723, U+8725, U+8729, U+872E, U+8731, U+8734, U+8737, U+873A-873B, U+873E-8740, U+8742, U+8747-8748, U+8753, U+8755, U+8757-8758, U+875D, U+875F, U+8762-8766, U+8768, U+876E, U+8770, U+8772, U+8775, U+8778, U+877B-877E, U+8782, U+8785, U+8788, U+878B, U+8793, U+8797, U+879A, U+879E-87A0, U+87A2-87A3, U+87A8, U+87AB-87AD, U+87AF, U+87B3, U+87B5, U+87BD, U+87C0, U+87C4, U+87C6, U+87CA-87CB, U+87D1-87D2, U+87DB-87DC, U+87DE, U+87E0, U+87E5, U+87EA, U+87EC, U+87EE, U+87F2-87F3, U+87FB, U+87FD-87FE, U+8802-8803, U+8805, U+880A-880B, U+880D, U+8813-8816, U+8819, U+881B, U+881F, U+8821, U+8823, U+8831-8832, U+8835-8836, U+8839, U+883B-883C, U+8844, U+8846, U+884A, U+884E, U+8852-8853, U+8855, U+8859, U+885B, U+885D-885E, U+8862, U+8864, U+8869-886A, U+886E-886F, U+8872, U+8879, U+887D-887F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-39.woff2") format("woff2");+ unicode-range: U+8548, U+854E, U+8553, U+8556-8557, U+8559, U+855E, U+8561, U+8564-8565, U+8568-856A, U+856D, U+856F-8570, U+8572, U+8576, U+8579-857B, U+8580, U+8585-8586, U+8588, U+858A, U+858F, U+8591, U+8594, U+8599, U+859C, U+85A2, U+85A4, U+85A6, U+85A8-85A9, U+85AB-85AC, U+85AE, U+85B7-85B9, U+85BE, U+85C1, U+85C7, U+85CD, U+85D0, U+85D3, U+85D5, U+85DC-85DD, U+85DF-85E0, U+85E5-85E6, U+85E8-85EA, U+85F4, U+85F9, U+85FE-85FF, U+8602, U+8605-8607, U+860A-860B, U+8616, U+8618, U+861A, U+8627, U+8629, U+862D, U+8638, U+863C, U+863F, U+864D, U+864F, U+8652-8655, U+865B-865C, U+865F, U+8662, U+8667, U+866C, U+866E, U+8671, U+8675, U+867A-867C, U+867F, U+868B, U+868D, U+8693, U+869C-869D, U+86A1, U+86A3-86A4, U+86A7-86A9, U+86AC, U+86AF-86B1, U+86B4-86B6, U+86BA, U+86C0, U+86C4, U+86C6, U+86C9-86CA, U+86CD-86D1, U+86D4, U+86D8, U+86DE-86DF, U+86E4, U+86E6, U+86E9, U+86ED, U+86EF-86F3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-40.woff2") format("woff2");+ unicode-range: U+83C5, U+83C8-83C9, U+83CB, U+83D1, U+83D3-83D6, U+83D8, U+83DB, U+83DD, U+83DF, U+83E1, U+83E5, U+83EA-83EB, U+83F0, U+83F4, U+83F8-83F9, U+83FB, U+83FD, U+83FF, U+8401, U+8406, U+840A-840B, U+840F, U+8411, U+8418, U+841C, U+8420, U+8422-8424, U+8426, U+8429, U+842C, U+8438-8439, U+843B-843C, U+843F, U+8446-8447, U+8449, U+844E, U+8451-8452, U+8456, U+8459-845A, U+845C, U+8462, U+8466, U+846D, U+846F-8470, U+8473, U+8476-8478, U+847A, U+847D, U+8484-8485, U+8487, U+8489, U+848C, U+848E, U+8490, U+8493-8494, U+8497, U+849B, U+849E-849F, U+84A1, U+84A5, U+84A8, U+84AF, U+84B4, U+84B9-84BF, U+84C1-84C2, U+84C5-84C7, U+84CA-84CB, U+84CD, U+84D0-84D1, U+84D3, U+84D6, U+84DF-84E0, U+84E2-84E3, U+84E5-84E7, U+84EE, U+84F3, U+84F6, U+84FA, U+84FC, U+84FF-8500, U+850C, U+8511, U+8514-8515, U+8517-8518, U+851F, U+8523, U+8525-8526, U+8529, U+852B, U+852D, U+8532, U+8534-8535, U+8538-853A, U+853C, U+8543, U+8545;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-41.woff2") format("woff2");+ unicode-range: U+82BC, U+82BE, U+82C0-82C2, U+82C4-82C8, U+82CA-82CC, U+82CE, U+82D0, U+82D2-82D3, U+82D5-82D6, U+82D8-82D9, U+82DC-82DE, U+82E0-82E4, U+82E7, U+82E9-82EB, U+82ED-82EE, U+82F3-82F4, U+82F7-82F8, U+82FA-8301, U+8306-8308, U+830C-830D, U+830F, U+8311, U+8313-8315, U+8318, U+831A-831B, U+831D, U+8324, U+8327, U+832A, U+832C-832D, U+832F, U+8331-8334, U+833A-833C, U+8340, U+8343-8345, U+8347-8348, U+834A, U+834C, U+834F, U+8351, U+8356, U+8358-835C, U+835E, U+8360, U+8364-8366, U+8368-836A, U+836C-836E, U+8373, U+8378, U+837B-837D, U+837F-8380, U+8382, U+8388, U+838A-838B, U+8392, U+8394, U+8396, U+8398-8399, U+839B-839C, U+83A0, U+83A2-83A3, U+83A8-83AA, U+83AE-83B0, U+83B3-83B4, U+83B6, U+83B8, U+83BA, U+83BC-83BD, U+83BF-83C0, U+83C2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-42.woff2") format("woff2");+ unicode-range: U+8166-8169, U+816B, U+816D, U+8171, U+8173-8174, U+8178, U+817C-817D, U+8182, U+8188, U+8191, U+8198-819B, U+81A0, U+81A3, U+81A5-81A6, U+81A9, U+81B6, U+81BA-81BB, U+81BD, U+81BF, U+81C1, U+81C3, U+81C6, U+81C9-81CA, U+81CC-81CD, U+81D1, U+81D3-81D4, U+81D8, U+81DB-81DC, U+81DE-81DF, U+81E5, U+81E7-81E9, U+81EB-81EC, U+81EE-81EF, U+81F5, U+81F8, U+81FA, U+81FC, U+81FE, U+8200-8202, U+8204, U+8208-820A, U+820E-8210, U+8216-8218, U+821B-821C, U+8221-8224, U+8226-8228, U+822B, U+822D, U+822F, U+8232-8234, U+8237-8238, U+823A-823B, U+823E, U+8244, U+8249, U+824B, U+824F, U+8259-825A, U+825F, U+8266, U+8268, U+826E, U+8271, U+8276-8279, U+827D, U+827F, U+8283-8284, U+8288-828A, U+828D-8291, U+8293-8294, U+8296-8298, U+829F-82A1, U+82A3-82A4, U+82A7-82AB, U+82AE, U+82B0, U+82B2, U+82B4-82B6;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-43.woff2") format("woff2");+ unicode-range: U+8016, U+8018-8019, U+801C, U+801E, U+8026-802A, U+8031, U+8034-8035, U+8037, U+8043, U+804B, U+804D, U+8052, U+8056, U+8059, U+805E, U+8061, U+8068-8069, U+806E-8074, U+8076-8078, U+807C-8080, U+8082, U+8084-8085, U+8088, U+808F, U+8093, U+809C, U+809F, U+80AB, U+80AD-80AE, U+80B1, U+80B6-80B8, U+80BC-80BD, U+80C2, U+80C4, U+80CA, U+80CD, U+80D1, U+80D4, U+80D7, U+80D9-80DB, U+80DD, U+80E0, U+80E4-80E5, U+80E7-80ED, U+80EF-80F1, U+80F3-80F4, U+80FC, U+8101, U+8104-8105, U+8107-8108, U+810C-810E, U+8112-8115, U+8117-8119, U+811B-811F, U+8121-8130, U+8132-8134, U+8137, U+8139, U+813F-8140, U+8142, U+8146, U+8148, U+814D-814E, U+8151, U+8153, U+8158-815A, U+815E, U+8160;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-44.woff2") format("woff2");+ unicode-range: U+7EF0-7EF2, U+7EF6, U+7EFA-7EFB, U+7EFE, U+7F01-7F04, U+7F08, U+7F0A-7F12, U+7F17, U+7F19, U+7F1B-7F1C, U+7F1F, U+7F21-7F23, U+7F25-7F28, U+7F2A-7F33, U+7F35-7F37, U+7F3D, U+7F42, U+7F44-7F45, U+7F4C-7F4D, U+7F52, U+7F54, U+7F58-7F59, U+7F5D, U+7F5F-7F61, U+7F63, U+7F65, U+7F68, U+7F70-7F71, U+7F73-7F75, U+7F77, U+7F79, U+7F7D-7F7E, U+7F85-7F86, U+7F88-7F89, U+7F8B-7F8C, U+7F90-7F91, U+7F94-7F96, U+7F98-7F9B, U+7F9D, U+7F9F, U+7FA3, U+7FA7-7FA9, U+7FAC-7FB2, U+7FB4, U+7FB6, U+7FB8, U+7FBC, U+7FBF-7FC0, U+7FC3, U+7FCA, U+7FCC, U+7FCE, U+7FD2, U+7FD5, U+7FD9-7FDB, U+7FDF, U+7FE3, U+7FE5-7FE7, U+7FE9, U+7FEB-7FEC, U+7FEE-7FEF, U+7FF1, U+7FF3-7FF4, U+7FF9-7FFA, U+7FFE, U+8004, U+8006, U+800B, U+800E, U+8011-8012, U+8014;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-45.woff2") format("woff2");+ unicode-range: U+7DD2, U+7DD4, U+7DD6-7DD8, U+7DDA-7DE0, U+7DE2-7DE6, U+7DE8-7DED, U+7DEF, U+7DF1-7DF5, U+7DF7, U+7DF9, U+7DFB-7DFC, U+7DFE-7E02, U+7E04, U+7E08-7E0B, U+7E12, U+7E1B, U+7E1E, U+7E20, U+7E22-7E23, U+7E26, U+7E29, U+7E2B, U+7E2E-7E2F, U+7E31, U+7E37, U+7E39-7E3E, U+7E40, U+7E43-7E44, U+7E46-7E47, U+7E4A-7E4B, U+7E4D-7E4E, U+7E51, U+7E54-7E56, U+7E58-7E5B, U+7E5D-7E5E, U+7E61, U+7E66-7E67, U+7E69-7E6B, U+7E6D, U+7E70, U+7E73, U+7E77, U+7E79, U+7E7B-7E7D, U+7E81-7E82, U+7E8C-7E8D, U+7E8F, U+7E92-7E94, U+7E96, U+7E98, U+7E9A-7E9C, U+7E9E-7E9F, U+7EA1, U+7EA3, U+7EA5, U+7EA8-7EA9, U+7EAB, U+7EAD-7EAE, U+7EB0, U+7EBB, U+7EBE, U+7EC0-7EC2, U+7EC9, U+7ECB-7ECC, U+7ED0, U+7ED4, U+7ED7, U+7EDB, U+7EE0-7EE2, U+7EE5-7EE6, U+7EE8, U+7EEB;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-46.woff2") format("woff2");+ unicode-range: U+7CE8, U+7CEC, U+7CF0, U+7CF5-7CF9, U+7CFC, U+7CFE, U+7D00, U+7D04-7D0B, U+7D0D, U+7D10-7D14, U+7D17-7D19, U+7D1B-7D1F, U+7D21, U+7D24-7D26, U+7D28-7D2A, U+7D2C-7D2E, U+7D30-7D31, U+7D33, U+7D35-7D36, U+7D38-7D3A, U+7D40, U+7D42-7D44, U+7D46, U+7D4B-7D4C, U+7D4F, U+7D51, U+7D54-7D56, U+7D58, U+7D5B-7D5C, U+7D5E, U+7D61-7D63, U+7D66, U+7D68, U+7D6A-7D6C, U+7D6F, U+7D71-7D73, U+7D75-7D77, U+7D79-7D7A, U+7D7E, U+7D81, U+7D84-7D8B, U+7D8D, U+7D8F, U+7D91, U+7D94, U+7D96, U+7D98-7D9A, U+7D9C-7DA0, U+7DA2, U+7DA6, U+7DAA-7DB1, U+7DB4-7DB8, U+7DBA-7DBF, U+7DC1, U+7DC4, U+7DC7-7DC8, U+7DCA-7DCD, U+7DCF, U+7DD1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-47.woff2") format("woff2");+ unicode-range: U+7BD3-7BD4, U+7BD9-7BDA, U+7BDD, U+7BE0-7BE1, U+7BE4-7BE6, U+7BE9-7BEA, U+7BEF, U+7BF4, U+7BF6, U+7BFC, U+7BFE, U+7C01, U+7C03, U+7C07-7C08, U+7C0A-7C0D, U+7C0F, U+7C11, U+7C15-7C16, U+7C19, U+7C1E-7C21, U+7C23-7C24, U+7C26, U+7C28-7C33, U+7C35, U+7C37-7C3B, U+7C3D-7C3E, U+7C40-7C41, U+7C43, U+7C47-7C48, U+7C4C, U+7C50, U+7C53-7C54, U+7C59, U+7C5F-7C60, U+7C63-7C65, U+7C6C, U+7C6E, U+7C72, U+7C74, U+7C79-7C7A, U+7C7C, U+7C81-7C82, U+7C84-7C85, U+7C88, U+7C8A-7C91, U+7C93-7C96, U+7C99, U+7C9B-7C9E, U+7CA0-7CA2, U+7CA6-7CA9, U+7CAC, U+7CAF-7CB3, U+7CB5-7CB7, U+7CBA-7CBD, U+7CBF-7CC2, U+7CC5, U+7CC7-7CC9, U+7CCC-7CCD, U+7CD7, U+7CDC, U+7CDE, U+7CE0, U+7CE4-7CE5, U+7CE7;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-48.woff2") format("woff2");+ unicode-range: U+7AE6, U+7AF4-7AF7, U+7AFA-7AFB, U+7AFD-7B0A, U+7B0C, U+7B0E-7B0F, U+7B13, U+7B15-7B16, U+7B18-7B19, U+7B1E-7B20, U+7B22-7B25, U+7B29-7B2B, U+7B2D-7B2E, U+7B30-7B3B, U+7B3E-7B3F, U+7B41-7B42, U+7B44-7B47, U+7B4A, U+7B4C-7B50, U+7B58, U+7B5A, U+7B5C, U+7B60, U+7B66-7B67, U+7B69, U+7B6C-7B6F, U+7B72-7B76, U+7B7B-7B7D, U+7B7F, U+7B82, U+7B85, U+7B87, U+7B8B-7B96, U+7B98-7B99, U+7B9B-7B9F, U+7BA2-7BA4, U+7BA6-7BAC, U+7BAE-7BB0, U+7BB4, U+7BB7-7BB9, U+7BBB, U+7BC0-7BC1, U+7BC3-7BC4, U+7BC6, U+7BC8-7BCC, U+7BD1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-49.woff2") format("woff2");+ unicode-range: U+798B-798E, U+7992, U+7994-7995, U+7997-7998, U+799A-799C, U+799F, U+79A3-79A6, U+79A8-79AC, U+79AE-79B1, U+79B3-79B5, U+79B8, U+79BA, U+79BF, U+79C2, U+79C6, U+79C8, U+79CF, U+79D5-79D6, U+79DD-79DE, U+79E3, U+79E7-79E8, U+79EB, U+79ED, U+79F4, U+79F7-79F8, U+79FA, U+79FE, U+7A02-7A03, U+7A05, U+7A0A, U+7A14, U+7A17, U+7A19, U+7A1C, U+7A1E-7A1F, U+7A23, U+7A25-7A26, U+7A2C, U+7A2E, U+7A30-7A32, U+7A36-7A37, U+7A39, U+7A3C, U+7A40, U+7A42, U+7A47, U+7A49, U+7A4C-7A4F, U+7A51, U+7A55, U+7A5B, U+7A5D-7A5E, U+7A62-7A63, U+7A66, U+7A68-7A69, U+7A6B, U+7A70, U+7A78, U+7A80, U+7A85-7A88, U+7A8A, U+7A90, U+7A93-7A96, U+7A98, U+7A9B-7A9C, U+7A9E, U+7AA0-7AA1, U+7AA3, U+7AA8-7AAA, U+7AAC-7AB0, U+7AB3, U+7AB8, U+7ABA, U+7ABD-7ABF, U+7AC4-7AC5, U+7AC7-7AC8, U+7ACA, U+7AD1-7AD2, U+7ADA-7ADD, U+7AE1, U+7AE4;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-50.woff2") format("woff2");+ unicode-range: U+784C, U+784E-7854, U+7856-7857, U+7859-785A, U+7865, U+7869-786A, U+786D, U+786F, U+7876-7877, U+787C, U+787E-787F, U+7881, U+7887-7889, U+7893-7894, U+7898-789E, U+78A1, U+78A3, U+78A5, U+78A9, U+78AD, U+78B2, U+78B4, U+78B6, U+78B9-78BA, U+78BC, U+78BF, U+78C3, U+78C9, U+78CB, U+78D0-78D2, U+78D4, U+78D9-78DA, U+78DC, U+78DE, U+78E1, U+78E5-78E6, U+78EA, U+78EC, U+78EF, U+78F1-78F2, U+78F4, U+78FA-78FB, U+78FE, U+7901-7902, U+7905, U+7907, U+7909, U+790B-790C, U+790E, U+7910, U+7913, U+7919-791B, U+791E-791F, U+7921, U+7924, U+7926, U+792A-792B, U+7934, U+7936, U+7939, U+793B, U+793D, U+7940, U+7942-7943, U+7945-7947, U+7949-794A, U+794C, U+794E-7951, U+7953-7955, U+7957-795A, U+795C, U+795F-7960, U+7962, U+7964, U+7966-7967, U+7969, U+796B, U+796F, U+7972, U+7974, U+7979, U+797B-797C, U+797E-7980, U+7982, U+7986-7987, U+7989-798A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-51.woff2") format("woff2");+ unicode-range: U+7722, U+7726, U+7728, U+772B-7730, U+7732-7736, U+7739-773A, U+773D-773F, U+7743, U+7746-7747, U+774C-774F, U+7751-7752, U+7758-775A, U+775C-775E, U+7762, U+7765-7766, U+7768-776A, U+776C-776D, U+7771-7772, U+777A, U+777C-777E, U+7780, U+7785, U+7787, U+778B-778D, U+778F-7791, U+7793, U+779E-77A0, U+77A2, U+77A5, U+77AD, U+77AF, U+77B4-77B7, U+77BD-77C0, U+77C2, U+77C5, U+77C7, U+77CD, U+77D6-77D7, U+77D9-77DA, U+77DD-77DE, U+77E7, U+77EA, U+77EC, U+77EF, U+77F8, U+77FB, U+77FD-77FE, U+7800, U+7803, U+7806, U+7809, U+780F-7812, U+7815, U+7817-7818, U+781A-781F, U+7821-7823, U+7825-7827, U+7829, U+782B-7830, U+7832-7833, U+7835, U+7837, U+7839-783C, U+783E, U+7841-7844, U+7847-7849, U+784B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-52.woff2") format("woff2");+ unicode-range: U+7613-7619, U+761B-761D, U+761F-7622, U+7625, U+7627-762A, U+762E-7630, U+7632-7635, U+7638-763A, U+763C-763D, U+763F-7640, U+7642-7643, U+7647-7648, U+764D-764E, U+7652, U+7654, U+7658, U+765A, U+765C, U+765E-765F, U+7661-7663, U+7665, U+7669, U+766C, U+766E-766F, U+7671-7673, U+7675-7676, U+7678-767A, U+767F, U+7681, U+7683, U+7688, U+768A-768C, U+768E, U+7690-7692, U+7695, U+7698, U+769A-769B, U+769D-76A0, U+76A2, U+76A4-76A7, U+76AB-76AC, U+76AF-76B0, U+76B2, U+76B4-76B5, U+76BA-76BB, U+76BF, U+76C2-76C3, U+76C5, U+76C9, U+76CC-76CE, U+76DC-76DE, U+76E1-76EA, U+76F1, U+76F9-76FB, U+76FD, U+76FF-7700, U+7703-7704, U+7707-7708, U+770C-770F, U+7712, U+7714, U+7716, U+7719-771B, U+771E, U+7721;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-53.woff2") format("woff2");+ unicode-range: U+750D, U+750F, U+7511, U+7513, U+7515, U+7517, U+7519, U+7521-7527, U+752A, U+752C-752D, U+752F, U+7534, U+7536, U+753A, U+753E, U+7540, U+7544, U+7547-754B, U+754D-754E, U+7550-7553, U+7556-7557, U+755A-755B, U+755D-755E, U+7560, U+7562, U+7564, U+7566-7568, U+756B-756C, U+756F-7573, U+7575, U+7579-757C, U+757E-757F, U+7581-7584, U+7587, U+7589-758E, U+7590, U+7592, U+7594, U+7596, U+7599-759A, U+759D, U+759F-75A0, U+75A3, U+75A5, U+75A8, U+75AC-75AD, U+75B0-75B1, U+75B3-75B5, U+75B8, U+75BD, U+75C1-75C4, U+75C8-75CA, U+75CC-75CD, U+75D4, U+75D6, U+75D9, U+75DE, U+75E0, U+75E2-75E4, U+75E6-75EA, U+75F1-75F3, U+75F7, U+75F9-75FA, U+75FC, U+75FE-7601, U+7603, U+7605-7606, U+7608-760E, U+7610-7612;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-54.woff2") format("woff2");+ unicode-range: U+73F0, U+73F2, U+73F4-73F5, U+73F7, U+73F9-73FA, U+73FC-73FD, U+73FF-7402, U+7404, U+7407-7408, U+740A-740F, U+7418, U+741A-741C, U+741E, U+7424-7425, U+7428-7429, U+742C-7430, U+7432, U+7435-7436, U+7438-743B, U+743E-7441, U+7443-7446, U+7448, U+744A-744B, U+7452, U+7457, U+745B, U+745D, U+7460, U+7462-7465, U+7467-746A, U+746D, U+746F, U+7471, U+7473-7474, U+7477, U+747A, U+747E, U+7481-7482, U+7484, U+7486, U+7488-748B, U+748E-748F, U+7493, U+7498, U+749A, U+749C-74A0, U+74A3, U+74A6, U+74A9-74AA, U+74AE, U+74B0-74B2, U+74B6, U+74B8-74BA, U+74BD, U+74BF, U+74C1, U+74C3, U+74C5, U+74C8, U+74CA, U+74CC, U+74CF, U+74D1-74D2, U+74D4-74D5, U+74D8-74DB, U+74DE-74E0, U+74E2, U+74E4-74E5, U+74E7-74E9, U+74EE-74EF, U+74F4, U+74FF, U+7501, U+7503, U+7505, U+7508;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-55.woff2") format("woff2");+ unicode-range: U+72E6, U+72E8, U+72EF-72F0, U+72F2-72F4, U+72F6-72F7, U+72F9-72FB, U+72FD, U+7300-7304, U+7307, U+730A-730C, U+7313-7317, U+731D-7322, U+7327, U+7329, U+732C-732D, U+7330-7331, U+7333, U+7335-7337, U+7339, U+733D-733E, U+7340, U+7342, U+7344-7345, U+734A, U+734D-7350, U+7352, U+7355, U+7357, U+7359, U+735F-7360, U+7362-7363, U+7365, U+7368, U+736C-736D, U+736F-7370, U+7372, U+7374-7376, U+7378, U+737A-737B, U+737D-737E, U+7382-7383, U+7386, U+7388, U+738A, U+738C-7393, U+7395, U+7397-739A, U+739C, U+739E, U+73A0-73A3, U+73A5-73A8, U+73AA, U+73AD, U+73B1, U+73B3, U+73B6-73B7, U+73B9, U+73C2, U+73C5-73C9, U+73CC, U+73CE-73D0, U+73D2, U+73D6, U+73D9, U+73DB-73DE, U+73E3, U+73E5-73EA, U+73EE-73EF;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-56.woff2") format("woff2");+ unicode-range: U+71A8, U+71AF, U+71B1-71BC, U+71BE, U+71C1-71C2, U+71C4, U+71C8-71CB, U+71CE-71D0, U+71D2, U+71D4, U+71D9-71DA, U+71DC, U+71DF-71E0, U+71E6-71E8, U+71EA, U+71ED-71EE, U+71F4, U+71F6, U+71F9, U+71FB-71FC, U+71FF-7200, U+7207, U+720C-720D, U+7210, U+7216, U+721A-721E, U+7223, U+7228, U+722B, U+722D-722E, U+7230, U+7232, U+723A-723C, U+723E-7242, U+7246, U+724B, U+724D-724E, U+7252, U+7256, U+7258, U+725A, U+725C-725D, U+7260, U+7264-7266, U+726A, U+726C, U+726E-726F, U+7271, U+7273-7274, U+7278, U+727B, U+727D-727E, U+7281-7282, U+7284, U+7287, U+728A, U+728D, U+728F, U+7292, U+729B, U+729F-72A0, U+72A7, U+72AD-72AE, U+72B0-72B5, U+72B7-72B8, U+72BA-72BE, U+72C0-72C1, U+72C3, U+72C5-72C6, U+72C8, U+72CC-72CE, U+72D2, U+72D6, U+72DB, U+72DD-72DF, U+72E1, U+72E5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-57.woff2") format("woff2");+ unicode-range: U+700B, U+700D, U+7015, U+7018, U+701B, U+701D-701F, U+7023, U+7026-7028, U+702C, U+702E-7030, U+7035, U+7037, U+7039-703A, U+703C-703E, U+7044, U+7049-704B, U+704F, U+7051, U+7058, U+705A, U+705C-705E, U+7061, U+7064, U+7066, U+706C, U+707D, U+7080-7081, U+7085-7086, U+708A, U+708F, U+7091, U+7094-7095, U+7098-7099, U+709C-709D, U+709F, U+70A4, U+70A9-70AA, U+70AF-70B2, U+70B4-70B7, U+70BB, U+70C0, U+70C3, U+70C7, U+70CB, U+70CE-70CF, U+70D4, U+70D9-70DA, U+70DC-70DD, U+70E0, U+70E9, U+70EC, U+70F7, U+70FA, U+70FD, U+70FF, U+7104, U+7108-7109, U+710C, U+7110, U+7113-7114, U+7116-7118, U+711C, U+711E, U+7120, U+712E-712F, U+7131, U+713C, U+7142, U+7144-7147, U+7149-714B, U+7150, U+7152, U+7155-7156, U+7159-715A, U+715C, U+7161, U+7165-7166, U+7168-7169, U+716D, U+7173-7174, U+7176, U+7178, U+717A, U+717D, U+717F-7180, U+7184, U+7186-7188, U+7192, U+7198, U+719C, U+71A0, U+71A4-71A5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-58.woff2") format("woff2");+ unicode-range: U+6ED9, U+6EDB, U+6EDD, U+6EDF-6EE0, U+6EE2, U+6EE6, U+6EEA, U+6EEC, U+6EEE-6EEF, U+6EF2-6EF3, U+6EF7-6EFA, U+6EFE, U+6F01, U+6F03, U+6F08-6F09, U+6F15-6F16, U+6F19, U+6F22-6F25, U+6F28-6F2A, U+6F2C-6F2D, U+6F2F, U+6F32, U+6F36-6F38, U+6F3F, U+6F43-6F46, U+6F48, U+6F4B, U+6F4E-6F4F, U+6F51, U+6F54-6F57, U+6F59-6F5B, U+6F5E-6F5F, U+6F61, U+6F64-6F67, U+6F69-6F6C, U+6F6F-6F72, U+6F74-6F76, U+6F78-6F7E, U+6F80-6F83, U+6F86, U+6F89, U+6F8B-6F8D, U+6F90, U+6F92, U+6F94, U+6F97-6F98, U+6F9B, U+6FA3-6FA5, U+6FA7, U+6FAA, U+6FAF, U+6FB1, U+6FB4, U+6FB6, U+6FB9, U+6FC1-6FCB, U+6FD1-6FD3, U+6FD5, U+6FDB, U+6FDE-6FE1, U+6FE4, U+6FE9, U+6FEB-6FEC, U+6FEE-6FF1, U+6FFA, U+6FFE, U+7005-7006, U+7009;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-59.woff2") format("woff2");+ unicode-range: U+6DC3, U+6DC5-6DC6, U+6DC9, U+6DCC, U+6DCF, U+6DD2-6DD3, U+6DD6, U+6DD9-6DDE, U+6DE0, U+6DE4, U+6DE6, U+6DE8-6DEA, U+6DEC, U+6DEF-6DF0, U+6DF5-6DF6, U+6DF8, U+6DFA, U+6DFC, U+6E03-6E04, U+6E07-6E09, U+6E0B-6E0C, U+6E0E, U+6E11, U+6E13, U+6E15-6E16, U+6E19-6E1B, U+6E1E-6E1F, U+6E22, U+6E25-6E27, U+6E2B-6E2C, U+6E36-6E37, U+6E39-6E3A, U+6E3C-6E41, U+6E44-6E45, U+6E47, U+6E49-6E4B, U+6E4D-6E4E, U+6E51, U+6E53-6E55, U+6E5C-6E5F, U+6E61-6E63, U+6E65-6E67, U+6E6A-6E6B, U+6E6D-6E70, U+6E72-6E74, U+6E76-6E78, U+6E7C, U+6E80-6E82, U+6E86-6E87, U+6E89, U+6E8D, U+6E8F, U+6E96, U+6E98, U+6E9D-6E9F, U+6EA1, U+6EA5-6EA7, U+6EAB, U+6EB1-6EB2, U+6EB4, U+6EB7, U+6EBB-6EBD, U+6EBF-6EC6, U+6EC8-6EC9, U+6ECC, U+6ECF-6ED0, U+6ED3-6ED4, U+6ED7-6ED8;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-60.woff2") format("woff2");+ unicode-range: U+6CB1-6CB2, U+6CB4-6CB5, U+6CB7, U+6CBA, U+6CBC-6CBD, U+6CC1-6CC3, U+6CC5-6CC7, U+6CD0-6CD4, U+6CD6-6CD7, U+6CD9-6CDA, U+6CDE-6CE0, U+6CE4, U+6CE6, U+6CE9, U+6CEB-6CEF, U+6CF1-6CF2, U+6CF6-6CF7, U+6CFA, U+6CFE, U+6D03-6D05, U+6D07-6D08, U+6D0A, U+6D0C, U+6D0E-6D11, U+6D13-6D14, U+6D16, U+6D18-6D1A, U+6D1C, U+6D1F, U+6D22-6D23, U+6D26-6D29, U+6D2B, U+6D2E-6D30, U+6D33, U+6D35-6D36, U+6D38-6D3A, U+6D3C, U+6D3F, U+6D42-6D44, U+6D48-6D49, U+6D4D, U+6D50, U+6D52, U+6D54, U+6D56-6D58, U+6D5A-6D5C, U+6D5E, U+6D60-6D61, U+6D63-6D65, U+6D67, U+6D6C-6D6D, U+6D6F, U+6D75, U+6D7B-6D7D, U+6D87, U+6D8A, U+6D8E, U+6D90-6D9A, U+6D9C-6DA0, U+6DA2-6DA3, U+6DA7, U+6DAA-6DAC, U+6DAE, U+6DB3-6DB4, U+6DB6, U+6DB8, U+6DBC, U+6DBF, U+6DC2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-61.woff2") format("woff2");+ unicode-range: U+6B83-6B86, U+6B89, U+6B8D, U+6B91-6B93, U+6B95, U+6B97-6B98, U+6B9A-6B9B, U+6B9E, U+6BA1-6BA4, U+6BA9-6BAA, U+6BAD, U+6BAF-6BB0, U+6BB2-6BB3, U+6BBA-6BBD, U+6BC0, U+6BC2, U+6BC6, U+6BCA-6BCC, U+6BCE, U+6BD0-6BD1, U+6BD3, U+6BD6-6BD8, U+6BDA, U+6BE1, U+6BE6, U+6BEC, U+6BF1, U+6BF3-6BF5, U+6BF9, U+6BFD, U+6C05-6C08, U+6C0D, U+6C10, U+6C15-6C1A, U+6C21, U+6C23-6C26, U+6C29-6C2D, U+6C30-6C33, U+6C35-6C37, U+6C39-6C3A, U+6C3C-6C3F, U+6C46, U+6C4A-6C4C, U+6C4E-6C50, U+6C54, U+6C56, U+6C59-6C5C, U+6C5E, U+6C63, U+6C67-6C69, U+6C6B, U+6C6D, U+6C6F, U+6C72-6C74, U+6C78-6C7A, U+6C7C, U+6C84-6C87, U+6C8B-6C8C, U+6C8F, U+6C91, U+6C93-6C96, U+6C98, U+6C9A, U+6C9D, U+6CA2-6CA4, U+6CA8-6CA9, U+6CAC-6CAE;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-62.woff2") format("woff2");+ unicode-range: U+69FE-6A01, U+6A06, U+6A09, U+6A0B, U+6A11, U+6A13, U+6A17-6A19, U+6A1B, U+6A1E, U+6A23, U+6A28-6A29, U+6A2B, U+6A2F-6A30, U+6A35, U+6A38-6A40, U+6A46-6A48, U+6A4A-6A4B, U+6A4E, U+6A50, U+6A52, U+6A5B, U+6A5E, U+6A62, U+6A65-6A67, U+6A6B, U+6A79, U+6A7C, U+6A7E-6A7F, U+6A84, U+6A86, U+6A8E, U+6A90-6A91, U+6A94, U+6A97, U+6A9C, U+6A9E, U+6AA0, U+6AA2, U+6AA4, U+6AA9, U+6AAB, U+6AAE-6AB0, U+6AB2-6AB3, U+6AB5, U+6AB7-6AB8, U+6ABA-6ABB, U+6ABD, U+6ABF, U+6AC2-6AC4, U+6AC6, U+6AC8, U+6ACC, U+6ACE, U+6AD2-6AD3, U+6AD8-6ADC, U+6ADF-6AE0, U+6AE4-6AE5, U+6AE7-6AE8, U+6AFB, U+6B04-6B05, U+6B0D-6B13, U+6B16-6B17, U+6B19, U+6B24-6B25, U+6B2C, U+6B37-6B39, U+6B3B, U+6B3D, U+6B43, U+6B46, U+6B4E, U+6B50, U+6B53-6B54, U+6B58-6B59, U+6B5B, U+6B60, U+6B69, U+6B6D, U+6B6F-6B70, U+6B73-6B74, U+6B77-6B7A, U+6B80-6B82;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-63.woff2") format("woff2");+ unicode-range: U+68D3, U+68D7, U+68DD, U+68DF, U+68E1, U+68E3-68E4, U+68E6-68ED, U+68EF-68F0, U+68F2, U+68F4, U+68F6-68F7, U+68F9, U+68FB-68FD, U+68FF-6902, U+6906-6908, U+690B, U+6910, U+691A-691C, U+691F-6920, U+6924-6925, U+692A, U+692D, U+6934, U+6939, U+693C-6945, U+694A-694B, U+6952-6954, U+6957, U+6959, U+695B, U+695D, U+695F, U+6962-6964, U+6966, U+6968-696C, U+696E-696F, U+6971, U+6973-6974, U+6978-6979, U+697D, U+697F-6980, U+6985, U+6987-698A, U+698D-698E, U+6994-6999, U+699B, U+69A3-69A4, U+69A6-69A7, U+69AB, U+69AD-69AE, U+69B1, U+69B7, U+69BB-69BC, U+69C1, U+69C3-69C5, U+69C7, U+69CA-69CE, U+69D0-69D1, U+69D3-69D4, U+69D7-69DA, U+69E0, U+69E4, U+69E6, U+69EC-69ED, U+69F1-69F3, U+69F8, U+69FA-69FC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-64.woff2") format("woff2");+ unicode-range: U+678B-678D, U+678F, U+6792-6793, U+6796, U+6798, U+679E-67A1, U+67A5, U+67A7-67A9, U+67AC-67AD, U+67B0-67B1, U+67B3, U+67B5, U+67B7, U+67B9, U+67BB-67BC, U+67C0-67C1, U+67C3, U+67C5-67CA, U+67D1-67D2, U+67D7-67D9, U+67DD-67DF, U+67E2-67E4, U+67E6-67E9, U+67F0, U+67F5, U+67F7-67F8, U+67FA-67FB, U+67FD-67FE, U+6800-6801, U+6803-6804, U+6806, U+6809-680A, U+680C, U+680E, U+6812, U+681D-681F, U+6822, U+6824-6829, U+682B-682D, U+6831-6835, U+683B, U+683E, U+6840-6841, U+6844-6845, U+6849, U+684E, U+6853, U+6855-6856, U+685C-685D, U+685F-6862, U+6864, U+6866-6868, U+686B, U+686F, U+6872, U+6874, U+6877, U+687F, U+6883, U+6886, U+688F, U+689B, U+689F-68A0, U+68A2-68A3, U+68B1, U+68B6, U+68B9-68BA, U+68BC-68BF, U+68C1-68C4, U+68C6, U+68C8, U+68CA, U+68CC, U+68D0-68D1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-65.woff2") format("woff2");+ unicode-range: U+6631, U+6633-6634, U+6636, U+663A-663B, U+663D, U+6641, U+6644-6645, U+6649, U+664C, U+664F, U+6654, U+6659, U+665B, U+665D-665E, U+6660-6667, U+6669, U+666B-666C, U+6671, U+6673, U+6677-6679, U+667C, U+6680-6681, U+6684-6685, U+6688-6689, U+668B-668E, U+6690, U+6692, U+6695, U+6698, U+669A, U+669D, U+669F-66A0, U+66A2-66A3, U+66A6, U+66AA-66AB, U+66B1-66B2, U+66B5, U+66B8-66B9, U+66BB, U+66BE, U+66C1, U+66C6-66C9, U+66CC, U+66D5-66D8, U+66DA-66DC, U+66DE-66E2, U+66E8-66EA, U+66EC, U+66F1, U+66F3, U+66F7, U+66FA, U+66FD, U+6702, U+6705, U+670A, U+670F-6710, U+6713, U+6715, U+6719, U+6722-6723, U+6725-6727, U+6729, U+672D-672E, U+6732-6733, U+6736, U+6739, U+673B, U+673F, U+6744, U+6748, U+674C-674D, U+6753, U+6755, U+6762, U+6767, U+6769-676C, U+676E, U+6772-6773, U+6775, U+6777, U+677A-677D, U+6782-6783, U+6787, U+678A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-66.woff2") format("woff2");+ unicode-range: U+64F1-64F2, U+64F4, U+64F7-64F8, U+64FA, U+64FC, U+64FE-64FF, U+6503, U+6509, U+650F, U+6514, U+6518, U+651C-651E, U+6522-6525, U+652A-652C, U+652E, U+6530-6532, U+6534-6535, U+6537-6538, U+653A, U+653C-653D, U+6542, U+6549-654B, U+654D-654E, U+6553-6555, U+6557-6558, U+655D, U+6564, U+6569, U+656B, U+656D-656F, U+6571, U+6573, U+6575-6576, U+6578-657E, U+6581-6583, U+6585-6586, U+6589, U+658E-658F, U+6592-6593, U+6595-6596, U+659B, U+659D, U+659F-65A1, U+65A3, U+65AB-65AC, U+65B2, U+65B6-65B7, U+65BA-65BB, U+65BE-65C0, U+65C2-65C4, U+65C6-65C8, U+65CC, U+65CE, U+65D0, U+65D2-65D3, U+65D6, U+65DB, U+65DD, U+65E1, U+65E3, U+65EE-65F0, U+65F3-65F5, U+65F8, U+65FB-65FC, U+65FE-6600, U+6603, U+6607, U+6609, U+660B, U+6610-6611, U+6619-661A, U+661C-661E, U+6621, U+6624, U+6626, U+662A-662C, U+662E, U+6630;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-67.woff2") format("woff2");+ unicode-range: U+63B8-63BC, U+63BE, U+63C0, U+63C3-63C4, U+63C6, U+63C8, U+63CD-63CE, U+63D1, U+63D6, U+63DA-63DB, U+63DE, U+63E0, U+63E3, U+63E9-63EA, U+63EE, U+63F2, U+63F5-63FA, U+63FC, U+63FE-6400, U+6406, U+640B-640D, U+6410, U+6414, U+6416-6417, U+641B, U+6420-6423, U+6425-6428, U+642A, U+6431-6432, U+6434-6437, U+643D-6442, U+6445, U+6448, U+6450-6452, U+645B-645F, U+6462, U+6465, U+6468, U+646D, U+646F-6471, U+6473, U+6477, U+6479-647D, U+6482-6485, U+6487-6488, U+648C, U+6490, U+6493, U+6496-649A, U+649D, U+64A0, U+64A5, U+64AB-64AC, U+64B1-64B7, U+64B9-64BB, U+64BE-64C1, U+64C4, U+64C7, U+64C9-64CB, U+64D0, U+64D4, U+64D7-64D8, U+64DA, U+64DE, U+64E0-64E2, U+64E4, U+64E9, U+64EC, U+64F0;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-68.woff2") format("woff2");+ unicode-range: U+622C, U+622E-6230, U+6232, U+6238, U+623B, U+623D-623E, U+6243, U+6246, U+6248-6249, U+624C, U+6255, U+6259, U+625E, U+6260-6261, U+6265-6266, U+626A, U+6271, U+627A, U+627C-627D, U+6283, U+6286, U+6289, U+628E, U+6294, U+629C, U+629E-629F, U+62A1, U+62A8, U+62BA-62BB, U+62BF, U+62C2, U+62C4, U+62C8, U+62CA-62CB, U+62CF, U+62D1, U+62D7, U+62D9-62DA, U+62DD, U+62E0-62E1, U+62E3-62E4, U+62E7, U+62EB, U+62EE, U+62F0, U+62F4-62F6, U+6308, U+630A-630E, U+6310, U+6312-6313, U+6317, U+6319, U+631B, U+631D-631F, U+6322, U+6326, U+6329, U+6331-6332, U+6334-6337, U+6339, U+633B-633C, U+633E-6340, U+6343, U+6347, U+634B-634E, U+6354, U+635C-635D, U+6368-6369, U+636D, U+636F-6372, U+6376, U+637A-637B, U+637D, U+6382-6383, U+6387, U+638A-638B, U+638D-638E, U+6391, U+6393-6397, U+6399, U+639B, U+639E-639F, U+63A1, U+63A3-63A4, U+63AC-63AE, U+63B1-63B5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-69.woff2") format("woff2");+ unicode-range: U+60ED-60EE, U+60F0-60F1, U+60F4, U+60F6, U+60FA, U+6100, U+6106, U+610D-610E, U+6112, U+6114-6115, U+6119, U+611C, U+6120, U+6122-6123, U+6126, U+6128-6130, U+6136-6137, U+613A, U+613D-613E, U+6144, U+6146-6147, U+614A-614B, U+6151, U+6153, U+6158, U+615A, U+615C-615D, U+615F, U+6161, U+6163-6165, U+616B-616C, U+616E, U+6171, U+6173-6177, U+617E, U+6182, U+6187, U+618A, U+618D-618E, U+6190-6191, U+6194, U+6199-619A, U+619C, U+619F, U+61A1, U+61A3-61A4, U+61A7-61A9, U+61AB-61AD, U+61B2-61B3, U+61B5-61B7, U+61BA-61BB, U+61BF, U+61C3-61C4, U+61C6-61C7, U+61C9-61CB, U+61D0-61D1, U+61D3-61D4, U+61D7, U+61DA, U+61DF-61E1, U+61E6, U+61EE, U+61F0, U+61F2, U+61F6-61F8, U+61FA, U+61FC-61FE, U+6200, U+6206-6207, U+6209, U+620B, U+620D-620E, U+6213-6215, U+6217, U+6219, U+621B-6223, U+6225-6226;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-70.woff2") format("woff2");+ unicode-range: U+5FC4, U+5FC9, U+5FCB, U+5FCE-5FD6, U+5FDA-5FDE, U+5FE1-5FE2, U+5FE4-5FE5, U+5FEA, U+5FED-5FEE, U+5FF1-5FF3, U+5FF6, U+5FF8, U+5FFB, U+5FFE-5FFF, U+6002-6006, U+600A, U+600D, U+600F, U+6014, U+6019, U+601B, U+6020, U+6023, U+6026, U+6029, U+602B, U+602E-602F, U+6031, U+6033, U+6035, U+6039, U+603F, U+6041-6043, U+6046, U+604F, U+6053-6054, U+6058-605B, U+605D-605E, U+6060, U+6063, U+6065, U+6067, U+606A-606C, U+6075, U+6078-6079, U+607B, U+607D, U+607F, U+6083, U+6085-6087, U+608A, U+608C, U+608E-608F, U+6092-6093, U+6095-6097, U+609B-609D, U+60A2, U+60A7, U+60A9-60AB, U+60AD, U+60AF-60B1, U+60B3-60B6, U+60B8, U+60BB, U+60BD-60BE, U+60C0-60C3, U+60C6-60C9, U+60CB, U+60CE, U+60D3-60D4, U+60D7-60DB, U+60DD, U+60E1-60E4, U+60E6, U+60EA, U+60EC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-71.woff2") format("woff2");+ unicode-range: U+5E98, U+5E9B, U+5E9D, U+5EA0-5EA5, U+5EA8, U+5EAB, U+5EAF, U+5EB3, U+5EB5-5EB6, U+5EB9, U+5EBE, U+5EC1-5EC3, U+5EC6, U+5EC8, U+5ECB-5ECC, U+5ED1-5ED2, U+5ED4, U+5ED9-5EDB, U+5EDD, U+5EDF-5EE0, U+5EE2-5EE3, U+5EE8, U+5EEA, U+5EEC, U+5EEF-5EF0, U+5EF3-5EF4, U+5EF8, U+5EFB-5EFC, U+5EFE-5EFF, U+5F01, U+5F07, U+5F0B-5F0E, U+5F10-5F12, U+5F14, U+5F1A, U+5F22, U+5F28-5F29, U+5F2C-5F2D, U+5F35-5F36, U+5F38, U+5F3B-5F43, U+5F45-5F4A, U+5F4C-5F4E, U+5F50, U+5F54, U+5F56-5F59, U+5F5B-5F5F, U+5F61, U+5F63, U+5F65, U+5F67-5F68, U+5F6B, U+5F6E-5F6F, U+5F72-5F78, U+5F7A, U+5F7E-5F7F, U+5F82-5F83, U+5F87, U+5F89-5F8A, U+5F8D, U+5F91, U+5F93, U+5F95, U+5F98-5F99, U+5F9C, U+5F9E, U+5FA0, U+5FA6-5FA9, U+5FAC-5FAD, U+5FAF, U+5FB3-5FB5, U+5FB9, U+5FBC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-72.woff2") format("woff2");+ unicode-range: U+5D26-5D27, U+5D2E-5D34, U+5D3C-5D3E, U+5D41-5D44, U+5D46-5D48, U+5D4A-5D4B, U+5D4E, U+5D50, U+5D52, U+5D55-5D58, U+5D5A-5D5D, U+5D68-5D69, U+5D6B-5D6C, U+5D6F, U+5D74, U+5D7F, U+5D82-5D89, U+5D8B-5D8C, U+5D8F, U+5D92-5D93, U+5D99, U+5D9D, U+5DB2, U+5DB6-5DB7, U+5DBA, U+5DBC-5DBD, U+5DC2-5DC3, U+5DC6-5DC7, U+5DC9, U+5DCC, U+5DD2, U+5DD4, U+5DD6-5DD8, U+5DDB-5DDC, U+5DE3, U+5DED, U+5DEF, U+5DF3, U+5DF6, U+5DFA-5DFD, U+5DFF-5E00, U+5E07, U+5E0F, U+5E11, U+5E13-5E14, U+5E19-5E1B, U+5E22, U+5E25, U+5E28, U+5E2A, U+5E2F-5E31, U+5E33-5E34, U+5E36, U+5E39-5E3C, U+5E3E, U+5E40, U+5E44, U+5E46-5E48, U+5E4C, U+5E4F, U+5E53-5E54, U+5E57, U+5E59, U+5E5B, U+5E5E-5E5F, U+5E61, U+5E63, U+5E6A-5E6B, U+5E75, U+5E77, U+5E79-5E7A, U+5E7E, U+5E80-5E81, U+5E83, U+5E85, U+5E87, U+5E8B, U+5E91-5E92, U+5E96;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-73.woff2") format("woff2");+ unicode-range: U+5BEC, U+5BEE-5BF0, U+5BF2-5BF3, U+5BF5-5BF6, U+5BFE, U+5C02-5C03, U+5C05, U+5C07-5C09, U+5C0B-5C0C, U+5C0E, U+5C10, U+5C12-5C13, U+5C15, U+5C17, U+5C19, U+5C1B-5C1C, U+5C1E-5C1F, U+5C22, U+5C25, U+5C28, U+5C2A-5C2B, U+5C2F-5C30, U+5C37, U+5C3B, U+5C43-5C44, U+5C46-5C47, U+5C4D, U+5C50, U+5C59, U+5C5B-5C5C, U+5C62-5C64, U+5C66, U+5C6C, U+5C6E, U+5C74, U+5C78-5C7E, U+5C80, U+5C83-5C84, U+5C88, U+5C8B-5C8D, U+5C91, U+5C94-5C96, U+5C98-5C99, U+5C9C, U+5C9E, U+5CA1-5CA3, U+5CAB-5CAC, U+5CB1, U+5CB5, U+5CB7, U+5CBA, U+5CBD-5CBF, U+5CC1, U+5CC3-5CC4, U+5CC7, U+5CCB, U+5CD2, U+5CD8-5CD9, U+5CDF-5CE0, U+5CE3-5CE6, U+5CE8-5CEA, U+5CED, U+5CEF, U+5CF3-5CF4, U+5CF6, U+5CF8, U+5CFD, U+5D00-5D04, U+5D06, U+5D08, U+5D0B-5D0D, U+5D0F-5D13, U+5D15, U+5D17-5D1A, U+5D1D-5D22, U+5D24-5D25;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-74.woff2") format("woff2");+ unicode-range: U+5AA0, U+5AA3-5AA4, U+5AAA, U+5AAE-5AAF, U+5AB1-5AB2, U+5AB4-5AB5, U+5AB7-5ABA, U+5ABD-5ABF, U+5AC3-5AC4, U+5AC6-5AC8, U+5ACA-5ACB, U+5ACD, U+5ACF-5AD2, U+5AD4, U+5AD8-5ADA, U+5ADC, U+5ADF-5AE2, U+5AE4, U+5AE6, U+5AE8, U+5AEA-5AED, U+5AF0-5AF3, U+5AF5, U+5AF9-5AFB, U+5AFD, U+5B01, U+5B05, U+5B08, U+5B0B-5B0C, U+5B11, U+5B16-5B17, U+5B1B, U+5B21-5B22, U+5B24, U+5B27-5B2E, U+5B30, U+5B32, U+5B34, U+5B36-5B38, U+5B3E-5B40, U+5B43, U+5B45, U+5B4A-5B4B, U+5B51-5B53, U+5B56, U+5B5A-5B5B, U+5B62, U+5B65, U+5B67, U+5B6A-5B6E, U+5B70-5B71, U+5B73, U+5B7A-5B7B, U+5B7F-5B80, U+5B84, U+5B8D, U+5B91, U+5B93-5B95, U+5B9F, U+5BA5-5BA6, U+5BAC, U+5BAE, U+5BB8, U+5BC0, U+5BC3, U+5BCB, U+5BD0-5BD1, U+5BD4-5BD8, U+5BDA-5BDC, U+5BE2, U+5BE4-5BE5, U+5BE7, U+5BE9, U+5BEB;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-75.woff2") format("woff2");+ unicode-range: U+596A, U+596C-596E, U+5977, U+597B-597C, U+5981, U+598F, U+5997-5998, U+599A, U+599C-599D, U+59A0-59A1, U+59A3-59A4, U+59A7, U+59AA-59AD, U+59AF, U+59B2-59B3, U+59B5-59B6, U+59B8, U+59BA, U+59BD-59BE, U+59C0-59C1, U+59C3-59C4, U+59C7-59CA, U+59CC-59CD, U+59CF, U+59D2, U+59D5-59D6, U+59D8-59D9, U+59DB, U+59DD-59E0, U+59E2-59E7, U+59E9-59EB, U+59EE, U+59F1, U+59F3, U+59F5, U+59F7-59F9, U+59FD, U+5A06, U+5A08-5A0A, U+5A0C-5A0D, U+5A11-5A13, U+5A15-5A16, U+5A1A-5A1B, U+5A21-5A23, U+5A2D-5A2F, U+5A32, U+5A38, U+5A3C, U+5A3E-5A45, U+5A47, U+5A4A, U+5A4C-5A4D, U+5A4F-5A51, U+5A53, U+5A55-5A57, U+5A5E, U+5A60, U+5A62, U+5A65-5A67, U+5A6A, U+5A6C-5A6D, U+5A72-5A73, U+5A75-5A76, U+5A79-5A7C, U+5A81-5A84, U+5A8C, U+5A8E, U+5A93, U+5A96-5A97, U+5A9C, U+5A9E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-76.woff2") format("woff2");+ unicode-range: U+5820, U+5822-5823, U+5825-5826, U+582C, U+582F, U+5831, U+583A, U+583D, U+583F-5842, U+5844-5846, U+5848, U+584A, U+584D, U+5852, U+5857, U+5859-585A, U+585C-585D, U+5862, U+5868-5869, U+586C-586D, U+586F-5873, U+5875, U+5879, U+587D-587E, U+5880-5881, U+5888-588A, U+588D, U+5892, U+5896-5898, U+589A, U+589C-589D, U+58A0-58A1, U+58A3, U+58A6, U+58A9, U+58AB-58AE, U+58B0, U+58B3, U+58BB-58BF, U+58C2-58C3, U+58C5-58C8, U+58CA, U+58CC, U+58CE, U+58D1-58D3, U+58D5, U+58D8-58D9, U+58DE-58DF, U+58E2, U+58E9, U+58EC, U+58EF, U+58F1-58F2, U+58F5, U+58F7-58F8, U+58FA, U+58FD, U+5900, U+5902, U+5906, U+5908-590C, U+590E, U+5910, U+5914, U+5919, U+591B, U+591D-591E, U+5920, U+5922-5925, U+5928, U+592C-592D, U+592F, U+5932, U+5936, U+593C, U+593E, U+5940-5942, U+5944, U+594C-594D, U+5950, U+5953, U+5958, U+595A, U+5961, U+5966-5968;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-77.woff2") format("woff2");+ unicode-range: U+56F9, U+56FC, U+56FF-5700, U+5703-5704, U+5709-570A, U+570C-570D, U+570F, U+5712-5713, U+5718-5719, U+571C, U+571E, U+5725, U+5727, U+5729-572A, U+572C, U+572E-572F, U+5734-5735, U+5739, U+573B, U+5741, U+5743, U+5745, U+5749, U+574C-574D, U+575C, U+5763, U+5768-5769, U+576B, U+576D-576E, U+5770, U+5773, U+5775, U+5777, U+577B-577C, U+5785-5786, U+5788, U+578C, U+578E-578F, U+5793-5795, U+5799-57A1, U+57A3-57A4, U+57A6-57AA, U+57AC-57AD, U+57AF-57B2, U+57B4-57B6, U+57B8-57B9, U+57BD-57BF, U+57C2, U+57C4-57C8, U+57CC-57CD, U+57CF, U+57D2, U+57D5-57DE, U+57E1-57E2, U+57E4-57E5, U+57E7, U+57EB, U+57ED, U+57EF, U+57F4-57F8, U+57FC-57FD, U+5800-5801, U+5803, U+5805, U+5807, U+5809, U+580B-580E, U+5811, U+5814, U+5819, U+581B-581F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-78.woff2") format("woff2");+ unicode-range: U+55F5-55F7, U+55FB, U+55FE, U+5600-5601, U+5605-5606, U+5608, U+560C-560D, U+560F, U+5614, U+5616-5617, U+561A, U+561C, U+561E, U+5621-5625, U+5627, U+5629, U+562B-5630, U+5636, U+5638-563A, U+563C, U+5640-5642, U+5649, U+564C-5650, U+5653-5655, U+5657-565B, U+5660, U+5663-5664, U+5666, U+566B, U+566F-5671, U+5673-567C, U+567E, U+5684-5687, U+568C, U+568E-5693, U+5695, U+5697, U+569B-569C, U+569E-569F, U+56A1-56A2, U+56A4-56A9, U+56AC-56AF, U+56B1, U+56B4, U+56B6-56B8, U+56BF, U+56C1-56C3, U+56C9, U+56CD, U+56D1, U+56D4, U+56D6-56D9, U+56DD, U+56DF, U+56E1, U+56E3-56E6, U+56E8-56EC, U+56EE-56EF, U+56F1-56F3, U+56F5, U+56F7-56F8;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-79.woff2") format("woff2");+ unicode-range: U+550F, U+5511-5514, U+5516-5517, U+5519, U+551B, U+551D-551E, U+5520, U+5522-5523, U+5526-5527, U+552A-552C, U+5530, U+5532-5535, U+5537-5538, U+553B-5541, U+5543-5544, U+5547-5549, U+554B, U+554D, U+5550, U+5553, U+5555-5558, U+555B-555F, U+5567-5569, U+556B-5572, U+5574-5577, U+557B-557C, U+557E-557F, U+5581, U+5583, U+5585-5586, U+5588, U+558B-558C, U+558E-5591, U+5593, U+5599-559A, U+559F, U+55A5-55A6, U+55A8-55AC, U+55AE, U+55B0-55B3, U+55B6, U+55B9-55BA, U+55BC-55BE, U+55C4, U+55C6-55C7, U+55C9, U+55CC-55D2, U+55D4-55DB, U+55DD-55DF, U+55E1, U+55E3-55E6, U+55EA-55EE, U+55F0-55F3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-80.woff2") format("woff2");+ unicode-range: U+53E7-53E9, U+53F1, U+53F4-53F5, U+53FA-5400, U+5402, U+5405-5407, U+540B, U+540F, U+5412, U+5414, U+5416, U+5418-541A, U+541D, U+5420-5423, U+5425, U+5429-542A, U+542D-542E, U+5431-5433, U+5436, U+543D, U+543F, U+5442-5443, U+5449, U+544B-544C, U+544E, U+5451-5454, U+5456, U+5459, U+545B-545C, U+5461, U+5463-5464, U+546A-5472, U+5474, U+5476-5478, U+547A, U+547E-5484, U+5486, U+548A, U+548D-548E, U+5490-5491, U+5494, U+5497-5499, U+549B, U+549D, U+54A1-54A7, U+54A9, U+54AB, U+54AD, U+54B4-54B5, U+54B9, U+54BB, U+54BE-54BF, U+54C2-54C3, U+54C9-54CC, U+54CF-54D0, U+54D3, U+54D5-54D6, U+54D9-54DA, U+54DC-54DE, U+54E2, U+54E7, U+54F3-54F4, U+54F8-54F9, U+54FD-54FF, U+5501, U+5504-5506, U+550C-550E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-81.woff2") format("woff2");+ unicode-range: U+5289, U+528B, U+528D, U+528F, U+5291-5293, U+529A, U+52A2, U+52A6-52A7, U+52AC-52AD, U+52AF, U+52B4-52B5, U+52B9, U+52BB-52BC, U+52BE, U+52C1, U+52C5, U+52CA, U+52CD, U+52D0, U+52D6-52D7, U+52D9, U+52DB, U+52DD-52DE, U+52E0, U+52E2-52E3, U+52E5, U+52E7-52F0, U+52F2-52F3, U+52F5-52F9, U+52FB-52FC, U+5302, U+5304, U+530B, U+530D, U+530F-5310, U+5315, U+531A, U+531C-531D, U+5321, U+5323, U+5326, U+532E-5331, U+5338, U+533C-533E, U+5344-5345, U+534B-534D, U+5350, U+5354, U+5358, U+535D-535F, U+5363, U+5368-5369, U+536C, U+536E-536F, U+5372, U+5379-537B, U+537D, U+538D-538E, U+5390, U+5393-5394, U+5396, U+539B-539D, U+53A0-53A1, U+53A3-53A5, U+53A9, U+53AD-53AE, U+53B0, U+53B2-53B3, U+53B5-53B8, U+53BC, U+53BE, U+53C1, U+53C3-53C7, U+53CE-53CF, U+53D2-53D3, U+53D5, U+53DA, U+53DE-53DF, U+53E1-53E2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-82.woff2") format("woff2");+ unicode-range: U+5104, U+5106-5107, U+5109-510B, U+510D, U+510F-5110, U+5113, U+5115, U+5117-5118, U+511A-511C, U+511E-511F, U+5121, U+5128, U+512B-512D, U+5131-5135, U+5137-5139, U+513C, U+5140, U+5142, U+5147, U+514C, U+514E-5150, U+5155-5158, U+5162, U+5169, U+5172, U+517F, U+5181-5184, U+5186-5187, U+518B, U+518F, U+5191, U+5195-5197, U+519A, U+51A2-51A3, U+51A6-51AB, U+51AD-51AE, U+51B1, U+51B4, U+51BC-51BD, U+51BF, U+51C3, U+51C7-51C8, U+51CA-51CB, U+51CD-51CE, U+51D4, U+51D6, U+51DB-51DC, U+51E6, U+51E8-51EB, U+51F1, U+51F5, U+51FC, U+51FF, U+5202, U+5205, U+5208, U+520B, U+520D-520E, U+5215-5216, U+5228, U+522A, U+522C-522D, U+5233, U+523C-523D, U+523F-5240, U+5245, U+5247, U+5249, U+524B-524C, U+524E, U+5250, U+525B-525F, U+5261, U+5263-5264, U+5270, U+5273, U+5275, U+5277, U+527D, U+527F, U+5281-5285, U+5287;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-83.woff2") format("woff2");+ unicode-range: U+4FD1, U+4FD3, U+4FDA-4FDC, U+4FDF-4FE0, U+4FE2-4FE4, U+4FE6, U+4FE8, U+4FEB-4FED, U+4FF3, U+4FF5-4FF6, U+4FF8, U+4FFE, U+5001, U+5005-5006, U+5009, U+500C, U+500F, U+5013-5018, U+501B-501E, U+5022-5025, U+5027-5028, U+502B-502E, U+5030, U+5033-5034, U+5036-5039, U+503B, U+5041-5043, U+5045-5046, U+5048-504A, U+504C-504E, U+5051, U+5053, U+5055-5057, U+505B, U+505E, U+5060, U+5062-5063, U+5067, U+506A, U+506C, U+5070-5072, U+5074-5075, U+5078, U+507B, U+507D-507E, U+5080, U+5088-5089, U+5091-5092, U+5095, U+5097-509E, U+50A2-50A3, U+50A5-50A7, U+50A9, U+50AD, U+50B3, U+50B5, U+50B7, U+50BA, U+50BE, U+50C4-50C5, U+50C7, U+50CA, U+50CD, U+50D1, U+50D5-50D6, U+50DA, U+50DE, U+50E5-50E6, U+50EC-50EE, U+50F0-50F1, U+50F3, U+50F9-50FB, U+50FE-5102;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-84.woff2") format("woff2");+ unicode-range: U+4EA3, U+4EA5, U+4EB0-4EB1, U+4EB3-4EB6, U+4EB8-4EB9, U+4EBB-4EBE, U+4EC2-4EC4, U+4EC8-4EC9, U+4ECC, U+4ECF-4ED0, U+4ED2, U+4EDA-4EDB, U+4EDD-4EE1, U+4EE6-4EE9, U+4EEB, U+4EEE-4EEF, U+4EF3-4EF5, U+4EF8-4EFA, U+4EFC, U+4F00, U+4F03-4F05, U+4F08-4F09, U+4F0B, U+4F0E, U+4F12-4F13, U+4F15, U+4F1B, U+4F1D, U+4F21-4F22, U+4F25, U+4F27-4F29, U+4F2B-4F2E, U+4F31-4F33, U+4F36-4F37, U+4F39, U+4F3E, U+4F40-4F41, U+4F43, U+4F47-4F49, U+4F54, U+4F57-4F58, U+4F5D-4F5E, U+4F61-4F62, U+4F64-4F65, U+4F67, U+4F6A, U+4F6E-4F6F, U+4F72, U+4F74-4F7E, U+4F80-4F82, U+4F84, U+4F89-4F8A, U+4F8E-4F98, U+4F9E, U+4FA1, U+4FA5, U+4FA9-4FAA, U+4FAC, U+4FB3, U+4FB6-4FB8, U+4FBD, U+4FC2, U+4FC5-4FC6, U+4FCD-4FCE, U+4FD0;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-85.woff2") format("woff2");+ unicode-range: U+3129, U+3220-3229, U+3231, U+32A3, U+338E-338F, U+339C-339E, U+33C4, U+33D1-33D2, U+33D5, U+3434, U+34DC, U+34EE, U+353E, U+355D, U+3566, U+3575, U+3592, U+35A0-35A1, U+35AD, U+35CE, U+36A2, U+36AB, U+38A8, U+3DAB, U+3DE7, U+3DEB, U+3E1A, U+3F1B, U+3F6D, U+4495, U+4723, U+48FA, U+4CA3, U+4E02, U+4E04-4E06, U+4E0C, U+4E0F, U+4E15, U+4E17, U+4E1F-4E21, U+4E26, U+4E29, U+4E2C, U+4E2F, U+4E31, U+4E35, U+4E37, U+4E3C, U+4E3F-4E42, U+4E44, U+4E46-4E47, U+4E57, U+4E5A-4E5C, U+4E64-4E65, U+4E67, U+4E69, U+4E6D, U+4E78, U+4E7F-4E82, U+4E85, U+4E87, U+4E8A, U+4E8D, U+4E93, U+4E96, U+4E98-4E99, U+4E9C, U+4E9E-4EA0, U+4EA2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-86.woff2") format("woff2");+ unicode-range: U+2EBB, U+3003, U+3005-3007, U+3012-3013, U+301D-301E, U+3021, U+3023-3024, U+3041, U+3043, U+3045, U+3047, U+3049, U+3056, U+3058, U+305C, U+305E, U+3062, U+306C, U+3074, U+3077, U+307A, U+307C-307D, U+3080, U+308E, U+3090-3091, U+3099-309B, U+309D-309E, U+30A5, U+30BC, U+30BE, U+30C2, U+30C5, U+30CC, U+30D8, U+30E2, U+30E8, U+30EE, U+30F0-30F2, U+30F4-30F6, U+30FD-30FE, U+3105-3126, U+3128;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-87.woff2") format("woff2");+ unicode-range: U+2713, U+2715, U+275B, U+275D-275E, U+2780-2782, U+278A-278C, U+278E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-88.woff2") format("woff2");+ unicode-range: U+2550-2551, U+2554, U+2557, U+255A-255B, U+255D, U+255F-2560, U+2562-2563, U+2565-2567, U+2569-256A, U+256C-2572, U+2581-258F, U+2593-2595, U+25A1, U+25B3, U+25BD, U+25CA-25CB, U+25E2-25E5, U+2609, U+2640, U+2642;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-89.woff2") format("woff2");+ unicode-range: U+2465-2469, U+2474-249B, U+2500-2509, U+250B-2526, U+2528-2534, U+2536-2537, U+253B-2548, U+254A-254B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-90.woff2") format("woff2");+ unicode-range: U+207F-2083, U+208D-208E, U+2105, U+2109, U+2117, U+2120-2121, U+2126, U+2196-2199, U+21C4, U+2202, U+2206, U+2208, U+220F, U+2211, U+221D-2220, U+2223, U+2225, U+2227-222B, U+222E, U+2234-2237, U+223C-223D, U+2248, U+224C, U+2252, U+2260-2261, U+2266-2267, U+226E-226F, U+2295, U+2299, U+22A5, U+22BF, U+2312;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-91.woff2") format("woff2");+ unicode-range: U+1DC4-1DC5, U+2070, U+2074-2078, U+207A-207B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-97.woff2") format("woff2");+ unicode-range: U+02D8-02D9, U+0302, U+0305-0307, U+030A-030C, U+0324-0325, U+0327-0328, U+032C, U+0332, U+0334, U+0339, U+033C-033D, U+0348, U+035C, U+0361;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-100.woff2") format("woff2");+ unicode-range: U+221A, U+2264-2265, U+2464, U+25A0, U+3008-3009, U+4E10, U+512A, U+5152, U+5201, U+5241, U+5340, U+5352, U+549A, U+54B2, U+54C6, U+54D7, U+54E1, U+5509, U+55C5, U+5618, U+5716, U+576F, U+5784, U+57A2, U+589F, U+5A20, U+5A25, U+5A29, U+5A34, U+5A7F, U+5AD6, U+5B09, U+5B5C, U+5BC7, U+5BE6, U+5C27, U+5D2D, U+5DCD, U+5F1B, U+5F37, U+604D, U+6055, U+6073, U+60EB, U+61FF, U+62CE, U+62ED, U+6345, U+6390, U+63B0, U+63B7, U+64AE, U+64C2, U+64D2, U+6556, U+663C, U+667E, U+66D9, U+66F8, U+6756, U+6789, U+689D, U+68F1, U+695E, U+6975, U+6A1F, U+6B0A, U+6B61, U+6B87, U+6C5D, U+6C7E, U+6C92, U+6D31, U+6DF9, U+6E0D, U+6E2D, U+6F31, U+6F3E, U+70B3, U+70BD, U+70CA, U+70E8, U+725F, U+733F, U+7396, U+739F, U+7459, U+74A7, U+75A1, U+75F0, U+76CF, U+76D4, U+7729, U+77AA, U+77B0, U+77E3, U+780C, U+78D5, U+7941, U+7977, U+797A, U+79C3, U+7A20, U+7A92, U+7B71, U+7BF1, U+7C9F, U+7EB6, U+7ECA, U+7EF7, U+7F07, U+7F09, U+7F15, U+7F81, U+7FB9, U+8038, U+8098, U+80B4, U+8110, U+814B-814C, U+816E, U+818A, U+8205, U+8235, U+828B, U+82A5, U+82B7, U+82D4, U+82DB, U+82DF, U+8317, U+8338, U+8385-8386, U+83C1, U+83CF, U+8537, U+853B, U+854A, U+8715, U+8783, U+892A, U+8A71, U+8BB3, U+8D2E, U+8D58, U+8DBE, U+8F67, U+8FAB, U+8FC4, U+8FE6, U+9023, U+9084, U+9091, U+916A, U+91C9, U+91DC, U+94B3, U+9502, U+9523, U+9551, U+956F, U+960E, U+962A, U+962E, U+9647, U+96F3, U+9739, U+97A0, U+97ED, U+983B, U+985E, U+988A, U+99AC, U+9A6F, U+9A87, U+9A8B, U+9AB7, U+9ABC, U+9AC5, U+9E25, U+FF06, U+FF14-FF16;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-101.woff2") format("woff2");+ unicode-range: U+25C7, U+25CE, U+3008-3009, U+3016-3017, U+4E4D, U+4E53, U+4F5A, U+4F70, U+4FAE, U+4FD8, U+4FFA, U+5011, U+501A, U+51C4, U+5225, U+547B, U+5495, U+54E8, U+54EE, U+5594, U+55D3, U+55DC, U+55FD, U+560E, U+565C, U+5662, U+5669, U+566C, U+56BC, U+5742, U+5824, U+5834, U+598A, U+5992, U+59A9, U+5A04, U+5AC9, U+5B75, U+5B7D, U+5BC5, U+5C49, U+5C90, U+5E1C, U+5E27, U+5E2B, U+5E37, U+5E90, U+618B, U+61F5, U+620A, U+620C, U+6273, U+62C7, U+62F7, U+6320, U+6342, U+6401-6402, U+6413, U+6512, U+655B, U+65A7, U+65F1, U+65F7, U+665F, U+6687, U+66A7, U+673D, U+67B8, U+6854, U+68D8, U+68FA, U+696D, U+6A02, U+6A0A, U+6A80, U+6B7C, U+6BD9, U+6C2E, U+6C76, U+6CF8, U+6D4A, U+6D85, U+6E24, U+6E32, U+6EC7, U+6F88, U+700F, U+701A, U+7078, U+707C, U+70AC, U+70C1, U+72E9, U+7409, U+7422, U+745A, U+7480, U+74A8, U+752B, U+7574, U+7656, U+7699, U+7737, U+785D, U+78BE, U+79B9, U+7A3D, U+7A91, U+7A9F, U+7AE3, U+7B77, U+7C3F, U+7D1A, U+7D50, U+7D93, U+8042, U+808B, U+8236, U+82B8-82B9, U+82EF, U+8309, U+836B, U+83EF, U+8431, U+85C9, U+865E, U+868C, U+8759, U+8760, U+8845, U+89BA, U+8A2A, U+8AAA, U+8C41, U+8D2C, U+8D4E, U+8E66, U+8E6D, U+8EAF, U+902E, U+914B, U+916E, U+919B, U+949B, U+94A0, U+94B0, U+9541-9542, U+9556, U+95EB, U+95F5, U+964B, U+968B, U+96CC-96CD, U+96CF, U+9713, U+9890, U+98A8, U+9985, U+9992, U+9A6D, U+9A81, U+9A86, U+9AB8, U+9CA4, U+FF02, U+FF1C, U+FF1E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-102.woff2") format("woff2");+ unicode-range: U+2264-2265, U+2463, U+2573, U+25B2, U+3448-3449, U+4E1E, U+4E5E, U+4F3A, U+4F5F, U+4FEA, U+5026, U+508D, U+516E, U+5189, U+5254, U+5288, U+52D8, U+52FA, U+5306, U+5308, U+5364, U+5384, U+53ED, U+543C, U+5450, U+5455, U+5466, U+54C4, U+5578, U+55A7, U+561F, U+5631, U+572D, U+575F, U+57AE, U+57E0, U+5830, U+594E, U+5984, U+5993, U+5BDD, U+5C0D, U+5C7F, U+5C82, U+5E62, U+5ED3, U+5F08, U+607A, U+60BC, U+625B, U+6292, U+62E2, U+6363, U+6467, U+6714, U+675E, U+6771, U+67A2, U+67FF, U+6805, U+68A7, U+68E0, U+6930, U+6986, U+69A8, U+69DF, U+6A44, U+6A5F, U+6C13, U+6C1F, U+6C22, U+6C2F, U+6C40, U+6C81, U+6C9B, U+6CA5, U+6DA4, U+6DF3, U+6E85, U+6EBA, U+6ED5, U+6F13, U+6F33, U+6F62, U+715E, U+72C4, U+73D1, U+7405, U+7487, U+7578, U+75A4, U+75EB, U+7693, U+7738, U+7741, U+776B, U+7792, U+77A7, U+77A9, U+77B3, U+788C, U+7984, U+79A7, U+79E4, U+7A1A, U+7A57, U+7AA6, U+7B0B, U+7B5D, U+7C27, U+7C7D, U+7CAA, U+7CD9, U+7CEF, U+7EDA, U+7EDE, U+7F24, U+803F, U+8046, U+80FA, U+81FB, U+8207, U+8258, U+8335, U+8339, U+8354, U+840E, U+85B0, U+85FB, U+8695, U+86AA, U+8717, U+8749, U+874C, U+8996, U+89BD, U+89C5, U+8BDB, U+8BF5, U+8C5A, U+8CEC, U+8D3F, U+8D9F, U+8E44, U+8FED, U+9005, U+9019, U+9082, U+90AF, U+90DD, U+90E1, U+90F8, U+916F, U+9176, U+949E, U+94A7, U+94C2, U+9525, U+9580, U+95DC, U+96E2, U+96FB, U+9704, U+9A7C, U+9A7F, U+9B41, U+9CA8, U+9CC4, U+9CDE, U+9E92, U+9EDE, U+9F9A, U+FF10, U+FF13, U+FF3B, U+FF3D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-103.woff2") format("woff2");+ unicode-range: U+2606, U+3014-3015, U+309C, U+33A1, U+4E52, U+4EC6, U+4F86, U+4F8D, U+4FDE, U+4FEF, U+500B, U+502A, U+515C, U+518A, U+51A5, U+51F3, U+5243, U+52C9, U+52D5, U+53A2, U+53EE, U+54CE, U+54FA, U+54FC, U+5580, U+5587, U+563F, U+56DA, U+5792, U+5815, U+5960, U+59D7, U+5B78, U+5B9B, U+5BE1, U+5C4E, U+5C51, U+5C6F, U+5C9A, U+5CFB, U+5D16, U+5ED6, U+5F27, U+5F6A, U+609A, U+60DF, U+6168, U+61C8, U+6236, U+62F1, U+62FD, U+631A, U+6328, U+632B, U+6346, U+638F, U+63A0, U+63C9, U+655E, U+6590, U+6615, U+6627, U+66AE, U+66E6, U+66F0, U+67DA, U+67EC, U+6813, U+6816, U+6869, U+6893, U+68AD, U+68F5, U+6977, U+6984, U+69DB, U+6B72, U+6BB7, U+6CE3, U+6CFB, U+6D47, U+6DA1, U+6DC4, U+6E43, U+6EAF, U+6EFF, U+6F8E, U+7011, U+7063, U+7076, U+7096, U+70BA, U+70DB, U+70EF, U+7119-711A, U+7172, U+718F, U+7194, U+727A, U+72D9, U+72ED, U+7325, U+73AE, U+73BA, U+73C0, U+73FE, U+7410, U+7426, U+7455, U+7554, U+7576, U+75AE, U+75B9, U+762B, U+766B, U+7682, U+7750, U+7779, U+7784, U+77EB, U+77EE, U+78F7, U+79E9, U+7A79, U+7B1B, U+7B28, U+7BF7, U+7DB2, U+7EC5, U+7EEE, U+7F14, U+7F1A, U+7FE1, U+8087, U+809B, U+81B3, U+8231, U+830E, U+835F, U+83E9, U+849C, U+851A, U+868A, U+8718, U+874E, U+8822, U+8910, U+8944, U+8A3B, U+8BB6, U+8BBC, U+8E72, U+8F9C, U+900D, U+904B, U+904E, U+9063, U+90A2, U+90B9, U+9119, U+94F2, U+952F, U+9576-9577, U+9593, U+95F8, U+961C, U+969B, U+96A7, U+96C1, U+9716, U+9761, U+97AD, U+97E7, U+98A4, U+997A, U+9A73, U+9B44, U+9E3D, U+9ECF, U+9ED4, U+FF11-FF12;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-104.woff2") format("woff2");+ unicode-range: U+2462, U+4E19, U+4E2B, U+4E36, U+4EA8, U+4ED1, U+4ED7, U+4F51, U+4F63, U+4F83, U+50E7, U+5112, U+5167, U+51A4, U+51B6, U+5239, U+5265, U+532A, U+5351, U+537F, U+5401, U+548F, U+5492, U+54AF, U+54B3, U+54BD, U+54D1, U+54DF, U+554F, U+5564, U+5598, U+5632, U+56A3, U+56E7, U+574E, U+575D-575E, U+57D4, U+584C, U+58E4, U+5937, U+5955, U+5A05, U+5A1F, U+5A49, U+5AC2, U+5C39, U+5C61, U+5D0E, U+5DE9, U+5E9A, U+5EB8, U+5F0A, U+5F13, U+5F6C, U+5F8C, U+603C, U+608D, U+611B, U+6127, U+62A0, U+62D0, U+634F, U+635E, U+63FD, U+6577, U+658B, U+65BC, U+660A, U+6643, U+6656, U+6703, U+6760, U+67AF, U+67C4, U+67E0, U+6817, U+68CD, U+690E, U+6960, U+69B4, U+6A71, U+6AAC, U+6B67, U+6BB4, U+6C55, U+6C70, U+6C82, U+6CA6, U+6CB8, U+6CBE, U+6EDE, U+6EE5, U+6F4D, U+6F84, U+6F9C, U+7115, U+7121, U+722A, U+7261, U+7272, U+7280, U+72F8, U+7504, U+754F, U+75D8, U+767C, U+76EF, U+778E, U+77BB, U+77F6, U+786B, U+78B1, U+7948, U+7985, U+79BE, U+7A83, U+7A8D, U+7EAC, U+7EEF, U+7EF8, U+7EFD, U+7F00, U+803D, U+8086, U+810A, U+8165, U+819D, U+81A8, U+8214, U+829C, U+831C, U+832B, U+8367, U+83E0, U+83F1, U+8403, U+846B, U+8475, U+84B2, U+8513, U+8574, U+85AF, U+86D9, U+86DB, U+8ACB, U+8BBD, U+8BE0-8BE1, U+8C0E, U+8D29, U+8D50, U+8D63, U+8F7F, U+9032, U+9042, U+90B1, U+90B5, U+9165, U+9175, U+94A6, U+94C5, U+950C, U+9610, U+9631, U+9699, U+973E, U+978D, U+97EC, U+97F6, U+984C, U+987D, U+9882, U+9965, U+996A, U+9972, U+9A8F, U+9AD3, U+9AE6, U+9CB8, U+9EDB, U+FF05, U+FF0B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-105.woff2") format("woff2");+ unicode-range: U+2190, U+250A, U+25BC, U+25CF, U+4E56, U+4EA9, U+4F3D, U+4F6C, U+4F88, U+4FA8, U+4FCF, U+5029, U+5188, U+51F9, U+5203, U+524A, U+5256, U+529D, U+5375, U+53DB, U+541F, U+5435, U+5457, U+548B, U+54C7, U+54D4, U+54E9, U+556A, U+5589, U+55BB, U+55E8, U+55EF, U+563B, U+566A, U+576A, U+58F9, U+598D, U+599E, U+59A8, U+5A9B, U+5AE3, U+5BB0, U+5BDE, U+5C4C, U+5C60, U+5D1B, U+5DEB, U+5DF7, U+5E18, U+5F26, U+5F64, U+601C, U+6084, U+60E9, U+614C, U+6208, U+621A, U+6233, U+6254, U+62D8, U+62E6, U+62EF, U+6323, U+632A, U+633D, U+6361, U+6405, U+640F, U+6614, U+6642, U+6657, U+67A3, U+6808, U+683D, U+6850, U+6897, U+68B3, U+68B5, U+68D5, U+6A58, U+6B47, U+6B6A, U+6C28, U+6C90, U+6CA7, U+6CF5, U+6D51, U+6DA9, U+6DC7, U+6DD1, U+6E0A, U+6E5B, U+6E9C, U+6F47, U+6F6D, U+70AD, U+70F9, U+710A, U+7130, U+71AC, U+745F, U+7476, U+7490, U+7529, U+7538, U+75D2, U+7696, U+76B1, U+76FC, U+777F, U+77DC, U+789F, U+795B, U+79BD, U+79C9, U+7A3B, U+7A46, U+7AA5, U+7AD6, U+7CA5, U+7CB9, U+7CDF, U+7D6E, U+7F06, U+7F38, U+7FA1, U+7FC1, U+8015, U+803B, U+80A2, U+80AA, U+8116, U+813E, U+82BD, U+8305, U+8328, U+8346, U+846C, U+8549, U+859B, U+8611, U+8680, U+87F9, U+884D, U+8877, U+888D, U+88D4, U+898B, U+8A79, U+8A93, U+8C05, U+8C0D, U+8C26, U+8D1E, U+8D31, U+8D81, U+8E22, U+8E81, U+8F90, U+8F96, U+90CA, U+916C, U+917F, U+9187, U+918B, U+9499, U+94A9, U+9524, U+9540, U+958B, U+9600, U+9640, U+96B6, U+96C7, U+96EF, U+98D9, U+9976, U+997F, U+9A74, U+9A84, U+9C8D, U+9E26, U+9E9F, U+FF0F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-106.woff2") format("woff2");+ unicode-range: U+2460-2461, U+25C6, U+300E-300F, U+4E1B, U+4E7E, U+4ED5, U+4EF2, U+4F10, U+4F1E, U+4F50, U+4FA6, U+4FAF, U+5021, U+50F5, U+5179, U+5180, U+51D1, U+522E, U+52A3, U+52C3, U+52CB, U+5300, U+5319, U+5320, U+5349, U+5395, U+53D9, U+541E, U+5428, U+543E, U+54B1, U+54C0, U+54D2, U+570B, U+5858, U+58F6, U+5974, U+59A5, U+59E8, U+59EC, U+5A36, U+5A9A, U+5AB3, U+5B99, U+5BAA, U+5CE1, U+5D14, U+5D4C, U+5DC5, U+5DE2, U+5E99, U+5E9E, U+5F18, U+5F66, U+5F70, U+6070, U+60D5, U+60E7, U+6101, U+611A, U+61BE, U+6241, U+6252, U+626F, U+6296, U+62BC, U+62CC, U+6380, U+63A9, U+644A, U+6454, U+64A9, U+64B8, U+6500, U+6572, U+65A5, U+65A9, U+65EC, U+660F, U+6749, U+6795, U+67AB, U+68DA, U+6912, U+6BBF, U+6BEF, U+6CAB, U+6CCA, U+6CCC, U+6CFC, U+6D3D, U+6D78, U+6DEE, U+6E17, U+6E34, U+6E83, U+6EA2, U+6EB6, U+6F20, U+6FA1, U+707F, U+70D8, U+70EB, U+714C, U+714E, U+7235, U+7239, U+73CA, U+743C, U+745C, U+7624, U+763E, U+76F2, U+77DB, U+77E9, U+780D, U+7838, U+7845, U+78CA, U+796D, U+7A84, U+7AED, U+7B3C, U+7EB2, U+7F05, U+7F20, U+7F34, U+7F62, U+7FC5, U+7FD8, U+7FF0, U+800D, U+8036, U+80BA, U+80BE, U+80C0-80C1, U+8155, U+817A, U+8180, U+81E3, U+8206, U+8247, U+8270, U+8299, U+82AD, U+8304, U+8393, U+83B9, U+840D, U+8427, U+8469, U+8471, U+84C4, U+84EC, U+853D, U+8681-8682, U+8721, U+8854, U+88D5, U+88F9, U+8BC0, U+8C0A, U+8C29, U+8C2D, U+8D41, U+8DEA, U+8EB2, U+8F9F, U+903B, U+903E, U+9102, U+9493, U+94A5, U+94F8, U+95F7, U+9706, U+9709, U+9774, U+98A0, U+9E64, U+9F9F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-107.woff2") format("woff2");+ unicode-range: U+2103, U+4E18, U+4E27-4E28, U+4E38, U+4E59, U+4E8F, U+4EAD, U+4EC7, U+4FE9, U+503A, U+5085, U+5146, U+51AF, U+51F8, U+52AB, U+5339, U+535C, U+5378, U+538C, U+5398, U+53F9, U+5415, U+5475, U+54AA, U+54AC, U+54B8, U+5582, U+5760, U+5764, U+57CB, U+5835, U+5885, U+5951, U+5983, U+59DA, U+5A77, U+5B5D, U+5B5F, U+5BB5, U+5BC2, U+5BE8, U+5BFA, U+5C2C, U+5C34, U+5C41, U+5C48, U+5C65, U+5CAD, U+5E06, U+5E42, U+5EF7, U+5F17, U+5F25, U+5F6D, U+5F79, U+6028, U+6064, U+6068, U+606D, U+607C, U+6094, U+6109, U+6124, U+6247, U+626D, U+6291, U+629A, U+62AC, U+62B9, U+62FE, U+6324, U+6349, U+6367, U+6398, U+6495, U+64A4, U+64B0, U+64BC, U+64CE, U+658C, U+65ED, U+6602, U+6674, U+6691, U+66A8, U+674F, U+679A, U+67EF, U+67F4, U+680B, U+6876, U+68A8, U+6A59, U+6A61, U+6B20, U+6BC5, U+6D12, U+6D46, U+6D8C, U+6DC0, U+6E14, U+6E23, U+6F06, U+7164, U+716E, U+7199, U+71E5, U+72AC, U+742A, U+755C, U+75AB, U+75B2, U+75F4, U+7897, U+78B3, U+78C5, U+7978, U+79FD, U+7A74, U+7B4B, U+7B5B, U+7ECE, U+7ED2, U+7EE3, U+7EF3, U+7F50, U+7F55, U+7F9E, U+7FE0, U+809D, U+8106, U+814A, U+8154, U+817B, U+818F, U+81C2, U+81ED, U+821F, U+82A6, U+82D1, U+8302, U+83C7, U+83CA, U+845B, U+848B, U+84C9, U+85E4, U+86EE, U+8700, U+8774, U+8881, U+8C1C, U+8C79, U+8D2A, U+8D3C, U+8EBA, U+8F70, U+8FA9, U+8FB1, U+900A, U+9017, U+901D, U+9022, U+906E, U+946B, U+94DD, U+94ED, U+953B, U+95EF, U+95FA, U+95FD, U+96C0, U+971E, U+9753, U+9756, U+97E6, U+9881, U+9887, U+9B4F, U+9E2D, U+9F0E, U+FF5C;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-108.woff2") format("woff2");+ unicode-range: U+4E08, U+4E43, U+4E4F, U+4EF0, U+4F2A, U+507F, U+50AC, U+50BB, U+5151, U+51BB, U+51F6, U+51FD, U+5272, U+52FE, U+5362, U+53C9, U+53D4, U+53E0, U+543B, U+54F2, U+5507, U+5524, U+558A, U+55B5, U+561B, U+56CA, U+5782, U+57C3, U+5893, U+5915, U+5949, U+5962, U+59AE, U+59DC, U+59FB, U+5BD3, U+5C38, U+5CB3, U+5D07, U+5D29, U+5DE1, U+5DFE, U+5E15, U+5ECA, U+5F2F, U+5F7C, U+5FCC, U+6021, U+609F, U+60F9, U+6108, U+6148, U+6155, U+6170, U+61D2, U+6251, U+629B, U+62AB, U+62E8, U+62F3, U+6321, U+6350, U+6566, U+659C, U+65E8, U+6635, U+6655, U+6670, U+66F9, U+6734, U+679D, U+6851, U+6905, U+6B49, U+6B96, U+6C1B, U+6C41, U+6C6A, U+6C83, U+6CF3, U+6D9B, U+6DCB, U+6E1D, U+6E20-6E21, U+6EAA, U+6EE4, U+6EE9, U+6F58, U+70E4, U+722C, U+7262, U+7267, U+72B9, U+72E0, U+72EE, U+72F1, U+7334, U+73AB, U+7433, U+7470, U+758F, U+75D5, U+764C, U+7686, U+76C6, U+76FE, U+7720, U+77E2, U+7802, U+7816, U+788D, U+7891, U+7A00, U+7A9D, U+7B52, U+7BAD, U+7C98, U+7CCA, U+7EBA, U+7EEA, U+7EF5, U+7F1D, U+7F69, U+806A, U+809A, U+80BF, U+80C3, U+81C0, U+820C, U+82AC, U+82AF, U+82CD, U+82D7, U+838E, U+839E, U+8404, U+84B8, U+852C, U+8587, U+8650, U+8679, U+86C7, U+8702, U+87BA, U+886B-886C, U+8870, U+8C10, U+8C23, U+8C6B, U+8D3E, U+8D4B-8D4C, U+8D64, U+8D6B, U+8D74, U+8E29, U+8F69, U+8F74, U+8FB0, U+8FDF, U+901B, U+9038, U+9093, U+9171, U+9489, U+94AE, U+94C3, U+9508, U+9510, U+9601, U+9614, U+964C, U+9675, U+971C, U+97F5, U+9888, U+98D8, U+9971, U+9AA4, U+9E3F, U+9E45, U+9E4F, U+9E70, U+9F7F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-109.woff2") format("woff2");+ unicode-range: U+2192, U+2605, U+4E11, U+4E22, U+4E32, U+4F0D, U+4F0F, U+4F69, U+4FF1, U+50B2, U+5154, U+51DD, U+51F0, U+5211, U+5269, U+533F, U+5366-5367, U+5389, U+5413, U+5440, U+5446, U+5561, U+574A, U+5751, U+57AB, U+5806, U+5821, U+582A, U+58F3, U+5938, U+5948, U+5978, U+59D1, U+5A03, U+5A07, U+5AC1, U+5ACC, U+5AE9, U+5BB4, U+5BC4, U+5C3F, U+5E3D, U+5E7D, U+5F92, U+5FAA, U+5FE0, U+5FFD, U+6016, U+60A0, U+60DC, U+60E8, U+614E, U+6212, U+6284, U+62C6, U+62D3-62D4, U+63F4, U+642C, U+6478, U+6491-6492, U+64E6, U+6591, U+65A4, U+664B, U+6735, U+6746, U+67F1, U+67F3, U+6842, U+68AF, U+68C9, U+68CB, U+6A31, U+6B3A, U+6BC1, U+6C0F, U+6C27, U+6C57, U+6CC4, U+6CE5, U+6D2A, U+6D66, U+6D69, U+6DAF, U+6E58, U+6ECB, U+6EF4, U+707E, U+7092, U+70AB, U+71D5, U+7275, U+7384, U+73B2, U+7434, U+74E6, U+74F7, U+75BC, U+76C8, U+76D0, U+7709, U+77AC, U+7855, U+78A7, U+78C1, U+7A77, U+7B79, U+7C92, U+7CAE, U+7CD5, U+7EA4, U+7EB5, U+7EBD, U+7F5A, U+7FD4, U+7FFC, U+8083, U+8096, U+80A0, U+80D6, U+80DE, U+8102, U+8109, U+810F, U+8179, U+8292, U+82B3, U+8352, U+8361, U+83CC, U+841D, U+8461, U+8482, U+8521, U+857E, U+85AA, U+866B, U+8776, U+8896, U+889C, U+88F8, U+8A9E, U+8BC8, U+8BF8, U+8C0B, U+8C28, U+8D2B, U+8D2F, U+8D37, U+8D3A, U+8D54, U+8DC3, U+8DCC, U+8DF5, U+8E0F, U+8E48, U+8F86, U+8F88, U+8F9E, U+8FC1, U+8FC8, U+8FEB, U+9065, U+90A6, U+90AA, U+90BB, U+90C1, U+94DC, U+9521, U+9676, U+96D5, U+970D, U+9897, U+997C, U+9A70, U+9A76, U+9A9A, U+9AD4, U+9E23, U+9E7F, U+9F3B, U+FFE5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-110.woff2") format("woff2");+ unicode-range: U+300C-300D, U+4E54, U+4E58, U+4E95, U+4EC1, U+4F2F, U+4F38, U+4FA3, U+4FCA, U+503E, U+5141, U+5144, U+517C, U+51CC, U+51ED, U+5242, U+52B2, U+52D2, U+52E4, U+540A, U+5439, U+5448, U+5496, U+54ED, U+5565, U+5761, U+5766, U+58EE, U+593A, U+594B, U+594F, U+5954, U+5996, U+59C6, U+59FF, U+5B64, U+5BFF, U+5C18, U+5C1D, U+5C97, U+5CA9, U+5CB8, U+5E9F, U+5EC9, U+5F04, U+5F7B, U+5FA1, U+5FCD, U+6012, U+60A6, U+60AC, U+60B2, U+60EF, U+626E, U+6270, U+6276, U+62D6, U+62DC, U+6316, U+632F, U+633A, U+6355, U+63AA, U+6447, U+649E, U+64C5, U+654C, U+65C1, U+65CB, U+65E6, U+6606, U+6731, U+675C, U+67CF, U+67DC, U+6846, U+6B8B, U+6BEB, U+6C61, U+6C88, U+6CBF, U+6CDB, U+6CEA, U+6D45, U+6D53, U+6D74, U+6D82, U+6DA8, U+6DB5, U+6DEB, U+6EDA, U+6EE8, U+6F0F, U+706D, U+708E, U+70AE, U+70BC, U+70C2, U+70E6, U+7237-7238, U+72FC, U+730E, U+731B, U+739B, U+73BB, U+7483, U+74DC, U+74F6, U+7586, U+7626, U+775B, U+77FF, U+788E, U+78B0, U+7956, U+7965, U+79E6, U+7AF9, U+7BEE, U+7C97, U+7EB1, U+7EB7, U+7ED1, U+7ED5, U+7F6A, U+7F72, U+7FBD, U+8017, U+808C, U+80A9, U+80C6, U+80CE, U+8150, U+8170, U+819C, U+820D, U+8230, U+8239, U+827E, U+8377, U+8389, U+83B2, U+8428, U+8463, U+867E, U+88C2, U+88D9, U+8986, U+8BCA, U+8BDE, U+8C13, U+8C8C, U+8D21, U+8D24, U+8D56, U+8D60, U+8D8B, U+8DB4, U+8E2A, U+8F68, U+8F89, U+8F9B, U+8FA8, U+8FBD, U+9003, U+90CE, U+90ED, U+9189, U+94BB, U+9505, U+95F9, U+963B, U+9655, U+966A, U+9677, U+96FE, U+9896, U+99A8, U+9A71, U+9A82, U+9A91, U+9B45, U+9ECE, U+9F20, U+FF0D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-111.woff2") format("woff2");+ unicode-range: U+4E4C, U+4E88, U+4EA1, U+4EA6, U+4ED3-4ED4, U+4EFF, U+4F30, U+4FA7, U+4FC4, U+4FD7, U+500D, U+504F, U+5076-5077, U+517D, U+5192, U+51C9, U+51EF, U+5238, U+5251, U+526A, U+52C7, U+52DF, U+52FF, U+53A6, U+53A8, U+53EC, U+5410, U+559D, U+55B7, U+5634, U+573E, U+5783, U+585E, U+586B, U+58A8, U+5999, U+59D3, U+5A1C, U+5A46, U+5B54-5B55, U+5B85, U+5B8B, U+5B8F, U+5BBF, U+5BD2, U+5C16, U+5C24, U+5E05, U+5E45, U+5E7C, U+5E84, U+5F03, U+5F1F, U+5F31, U+5F84, U+5F90, U+5FBD, U+5FC6, U+5FD9, U+5FE7, U+6052, U+6062, U+6089, U+60A3, U+60D1, U+6167, U+622A, U+6234, U+624E, U+6269, U+626C, U+62B5, U+62D2, U+6325, U+63E1, U+643A, U+6446, U+6562, U+656C, U+65E2, U+65FA, U+660C, U+6628, U+6652, U+6668, U+6676, U+66FC, U+66FF, U+6717, U+676D, U+67AA, U+67D4, U+6843, U+6881, U+68D2, U+695A, U+69FD, U+6A2A, U+6B8A, U+6C60, U+6C64, U+6C9F, U+6CAA, U+6CC9, U+6CE1, U+6CFD, U+6D1B, U+6D1E, U+6D6E, U+6DE1, U+6E10, U+6E7F, U+6F5C, U+704C, U+7070, U+7089, U+70B8, U+718A, U+71C3, U+723D, U+732A, U+73CD, U+7518, U+756A, U+75AF, U+75BE, U+75C7, U+76D2, U+76D7, U+7763, U+78E8, U+795D, U+79DF, U+7C4D, U+7D2F, U+7EE9, U+7F13, U+7F8A, U+8000, U+8010, U+80AF, U+80F6, U+80F8, U+8212, U+8273, U+82F9, U+83AB, U+83B1, U+83F2, U+8584, U+871C, U+8861, U+888B, U+88C1, U+88E4, U+8BD1, U+8BF1, U+8C31, U+8D5A, U+8D75-8D76, U+8DE8, U+8F85, U+8FA3, U+8FC5, U+9006, U+903C, U+904D, U+9075, U+9178, U+9274, U+950B, U+9526, U+95EA, U+9636, U+9686, U+978B, U+987F, U+9A7E, U+9B42, U+9E1F, U+9EA6, U+9F13, U+9F84, U+FF5E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-112.woff2") format("woff2");+ unicode-range: U+4E01, U+4E39, U+4E73, U+4ECD, U+4ED9, U+4EEA, U+4F0A, U+4F1F, U+4F5B, U+4FA0, U+4FC3, U+501F, U+50A8, U+515A, U+5175, U+51A0, U+51C0, U+51E1, U+51E4, U+5200, U+520A, U+5224, U+523A, U+52AA, U+52B1, U+52B3, U+5348, U+5353, U+5360, U+5371, U+5377, U+539A, U+541B, U+5434, U+547C, U+54E6, U+5510, U+5531, U+5609, U+56F0, U+56FA, U+5733, U+574F, U+5851, U+5854, U+5899, U+58C1, U+592E, U+5939, U+5976, U+5986, U+59BB, U+5A18, U+5A74, U+5B59, U+5B87, U+5B97, U+5BA0, U+5BAB, U+5BBD-5BBE, U+5BF8, U+5C0A, U+5C3A, U+5C4A, U+5E16, U+5E1D, U+5E2D, U+5E8A, U+6015, U+602A, U+6050, U+6069, U+6162, U+61C2, U+6293, U+6297, U+62B1, U+62BD, U+62DF, U+62FC, U+6302, U+635F, U+638C, U+63ED, U+6458, U+6469, U+6563, U+6620, U+6653, U+6696-6697, U+66DD, U+675F, U+676F-6770, U+67D0, U+67D3, U+684C, U+6865, U+6885, U+68B0, U+68EE, U+690D, U+6B23, U+6B32, U+6BD5, U+6C89, U+6D01, U+6D25, U+6D89, U+6DA6, U+6DB2, U+6DF7, U+6ED1, U+6F02, U+70C8, U+70DF, U+70E7, U+7126, U+7236, U+7259, U+731C, U+745E, U+74E3, U+751A, U+751C, U+7532, U+7545, U+75DB, U+7761, U+7A0D, U+7B51, U+7CA4, U+7CD6, U+7D2B, U+7EA0, U+7EB9, U+7ED8, U+7F18, U+7F29, U+8033, U+804A, U+80A4-80A5, U+80E1, U+817F, U+829D, U+82E6, U+8336, U+840C, U+8499, U+864E, U+8651, U+865A, U+88AD, U+89E6, U+8BD7, U+8BFA, U+8C37, U+8D25, U+8D38, U+8DDD, U+8FEA, U+9010, U+9012, U+906D, U+907F-9080, U+90D1, U+9177, U+91CA, U+94FA, U+9501, U+9634-9635, U+9694, U+9707, U+9738, U+9769, U+9A7B, U+9A97, U+9AA8, U+9B3C, U+9C81, U+9ED8;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-113.woff2") format("woff2");+ unicode-range: U+4E4E, U+4E61, U+4E71, U+4EBF, U+4F26, U+5012, U+51AC, U+51B0, U+51B2, U+51B7, U+5218, U+521A, U+5220, U+5237, U+523B, U+526F, U+5385, U+53BF, U+53E5, U+53EB, U+53F3, U+53F6, U+5409, U+5438, U+54C8, U+54E5, U+552F, U+5584, U+5706, U+5723, U+5750, U+575A, U+5987-5988, U+59B9, U+59D0, U+59D4, U+5B88, U+5B9C, U+5BDF, U+5BFB, U+5C01, U+5C04, U+5C3E, U+5C4B, U+5C4F, U+5C9B, U+5CF0, U+5DDD, U+5DE6, U+5DE8, U+5E01, U+5E78, U+5E7B, U+5E9C, U+5EAD, U+5EF6, U+5F39, U+5FD8, U+6000, U+6025, U+604B, U+6076, U+613F, U+6258, U+6263, U+6267, U+6298, U+62A2, U+62E5, U+62EC, U+6311, U+6377, U+6388-6389, U+63A2, U+63D2, U+641E, U+642D, U+654F, U+6551, U+6597, U+65CF, U+65D7, U+65E7, U+6682, U+66F2, U+671D, U+672B, U+6740, U+6751, U+6768, U+6811, U+6863, U+6982, U+6BD2, U+6CF0, U+6D0B, U+6D17, U+6D59, U+6DD8, U+6DFB, U+6E7E, U+6F6E, U+6FB3, U+706F, U+719F, U+72AF, U+72D0, U+72D7, U+732B, U+732E, U+7389, U+73E0, U+7530, U+7687, U+76D6, U+76DB, U+7840, U+786C, U+79CB, U+79D2, U+7A0E, U+7A33, U+7A3F, U+7A97, U+7ADE-7ADF, U+7B26, U+7E41, U+7EC3, U+7F3A, U+8089, U+80DC, U+811A, U+8131, U+8138, U+821E, U+8349, U+83DC, U+8457, U+867D, U+86CB, U+8A89, U+8BA8, U+8BAD, U+8BEF, U+8BFE, U+8C6A, U+8D1D, U+8D4F, U+8D62, U+8DD1, U+8DF3, U+8F6E, U+8FF9, U+900F, U+9014, U+9057, U+9192, U+91CE, U+9488, U+94A2, U+9547, U+955C, U+95F2, U+9644, U+964D, U+96C4-96C5, U+96E8, U+96F6-96F7, U+9732, U+9759, U+9760, U+987A, U+989C, U+9910, U+996D-996E, U+9B54, U+9E21, U+9EBB, U+9F50;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-114.woff2") format("woff2");+ unicode-range: U+4E03, U+4E25, U+4E30, U+4E34, U+4E45, U+4E5D, U+4E89, U+4EAE, U+4ED8, U+4F11, U+4F19, U+4F24, U+4F34, U+4F59, U+4F73, U+4F9D, U+4FB5, U+5047, U+505C, U+5170, U+519C, U+51CF, U+5267, U+5356, U+5374, U+5382, U+538B, U+53E6, U+5426, U+542B, U+542F, U+5462, U+5473, U+554A, U+5566, U+5708, U+571F, U+5757, U+57DF, U+57F9, U+5802, U+590F, U+591C, U+591F, U+592B, U+5965, U+5979, U+5A01, U+5A5A, U+5B63, U+5B69, U+5B81, U+5BA1, U+5BA3, U+5C3C, U+5C42, U+5C81, U+5DE7, U+5DEE, U+5E0C, U+5E10, U+5E55, U+5E86, U+5E8F, U+5EA7, U+5F02, U+5F52, U+5F81, U+5FF5, U+60CA, U+60E0, U+6279, U+62C5, U+62FF, U+63CF, U+6444, U+64CD, U+653B, U+65BD, U+65E9, U+665A, U+66B4, U+66FE, U+6728, U+6742, U+677E, U+67B6, U+680F, U+68A6, U+68C0, U+699C, U+6B4C, U+6B66, U+6B7B, U+6BCD, U+6BDB, U+6C38, U+6C47, U+6C49, U+6CB3, U+6CB9, U+6CE2, U+6D32, U+6D3E, U+6D4F, U+6E56, U+6FC0, U+7075, U+7206, U+725B, U+72C2, U+73ED, U+7565, U+7591, U+7597, U+75C5, U+76AE, U+76D1, U+76DF, U+7834, U+7968, U+7981, U+79C0, U+7A7F, U+7A81, U+7AE5, U+7B14, U+7C89, U+7D27, U+7EAF, U+7EB3, U+7EB8, U+7EC7, U+7EE7, U+7EFF, U+7F57, U+7FFB, U+805A, U+80A1, U+822C, U+82CF, U+82E5, U+8363, U+836F, U+84DD, U+878D, U+8840, U+8857, U+8863, U+8865, U+8B66, U+8BB2, U+8BDA, U+8C01, U+8C08, U+8C46, U+8D1F, U+8D35, U+8D5B, U+8D5E, U+8DA3, U+8DDF, U+8F93, U+8FDD, U+8FF0, U+8FF7, U+8FFD, U+9000, U+9047, U+9152, U+949F, U+94C1, U+94F6, U+9646, U+9648, U+9669, U+969C, U+96EA, U+97E9, U+987B, U+987E, U+989D, U+9970, U+9986, U+9C7C, U+9C9C;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-115.woff2") format("woff2");+ unicode-range: U+4E14, U+4E1D, U+4E3D, U+4E49, U+4E60, U+4E9A, U+4EB2, U+4EC5, U+4EFD, U+4F3C, U+4F4F, U+4F8B, U+4FBF, U+5019, U+5145, U+514B, U+516B, U+516D, U+5174, U+5178, U+517B, U+5199, U+519B, U+51B3, U+51B5, U+5207, U+5212, U+5219, U+521D, U+52BF, U+533B, U+5343, U+5347, U+534A, U+536B, U+5370, U+53E4, U+53F2, U+5403, U+542C, U+547D, U+54A8, U+54CD, U+54EA, U+552E, U+56F4, U+5747, U+575B, U+5883, U+589E, U+5931, U+5947, U+5956-5957, U+5A92, U+5B83, U+5BA4, U+5BB3, U+5BCC, U+5C14, U+5C1A, U+5C3D, U+5C40, U+5C45, U+5C5E, U+5DF4, U+5E72, U+5E95, U+5F80, U+5F85, U+5FB7, U+5FD7, U+601D, U+626B, U+627F, U+62C9, U+62CD, U+6309, U+63A7, U+6545, U+65AD, U+65AF, U+65C5, U+666E, U+667A, U+670B, U+671B, U+674E, U+677F, U+6781, U+6790, U+6797, U+6821, U+6838-6839, U+697C, U+6B27, U+6B62, U+6BB5, U+6C7D, U+6C99, U+6D4B, U+6D4E, U+6D6A, U+6E29, U+6E2F, U+6EE1, U+6F14, U+6F2B, U+72B6, U+72EC, U+7387, U+7533, U+753B, U+76CA, U+76D8, U+7701, U+773C, U+77ED, U+77F3, U+7814, U+793C, U+79BB, U+79C1, U+79D8, U+79EF, U+79FB, U+7A76, U+7B11, U+7B54, U+7B56, U+7B97, U+7BC7, U+7C73, U+7D20, U+7EAA, U+7EC8, U+7EDD, U+7EED, U+7EFC, U+7FA4, U+804C, U+8058, U+80CC, U+8111, U+817E, U+826F, U+8303, U+843D, U+89C9, U+89D2, U+8BA2, U+8BBF, U+8BC9, U+8BCD, U+8BE6, U+8C22, U+8C61, U+8D22, U+8D26-8D27, U+8D8A, U+8F6F, U+8F7B, U+8F83, U+8F91, U+8FB9, U+8FD4, U+8FDC, U+9002, U+94B1, U+9519, U+95ED, U+961F, U+9632-9633, U+963F, U+968F-9690, U+96BE, U+9876, U+9884, U+98DE, U+9988, U+9999, U+9EC4, U+FF1B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-116.woff2") format("woff2");+ unicode-range: U+3000, U+300A-300B, U+4E16, U+4E66, U+4E70, U+4E91-4E92, U+4E94, U+4E9B, U+4EC0, U+4ECA, U+4F01, U+4F17-4F18, U+4F46, U+4F4E, U+4F9B, U+4FEE, U+503C, U+5065, U+50CF, U+513F, U+5148, U+518D, U+51C6, U+51E0, U+5217, U+529E-529F, U+5341, U+534F, U+5361, U+5386, U+53C2, U+53C8, U+53CC, U+53D7-53D8, U+53EA, U+5404, U+5411, U+5417, U+5427, U+5468, U+559C, U+5668, U+56E0, U+56E2, U+56ED, U+5740, U+57FA, U+58EB, U+5904, U+592A, U+59CB, U+5A31, U+5B58, U+5B9D, U+5BC6, U+5C71, U+5DDE, U+5DF1, U+5E08, U+5E26, U+5E2E, U+5E93, U+5E97, U+5EB7, U+5F15, U+5F20, U+5F3A, U+5F62, U+5F69, U+5F88, U+5F8B, U+5FC5, U+600E, U+620F, U+6218, U+623F, U+627E, U+628A, U+62A4, U+62DB, U+62E9, U+6307, U+6362, U+636E, U+64AD, U+6539, U+653F, U+6548, U+6574, U+6613, U+6625, U+663E, U+666F, U+672A, U+6750, U+6784, U+6A21, U+6B3E, U+6B65, U+6BCF, U+6C11, U+6C5F, U+6DF1, U+706B, U+7167, U+724C, U+738B, U+73A9, U+73AF, U+7403, U+7537, U+754C, U+7559, U+767D, U+7740, U+786E, U+795E, U+798F, U+79F0, U+7AEF, U+7B7E, U+7BB1, U+7EA2, U+7EA6, U+7EC4, U+7EC6, U+7ECD, U+7EDC, U+7EF4, U+8003, U+80B2, U+81F3-81F4, U+822A, U+827A, U+82F1, U+83B7, U+8425, U+89C2, U+89C8, U+8BA9, U+8BB8, U+8BC6, U+8BD5, U+8BE2, U+8BE5, U+8BED, U+8C03, U+8D23, U+8D2D, U+8D34, U+8D70, U+8DB3, U+8FBE, U+8FCE, U+8FD1, U+8FDE, U+9001, U+901F-9020, U+90A3, U+914D, U+91C7, U+94FE, U+9500, U+952E, U+9605, U+9645, U+9662, U+9664, U+9700, U+9752, U+975E, U+97F3, U+9879, U+9886, U+98DF, U+9A6C, U+9A8C, U+9ED1, U+9F99;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-117.woff2") format("woff2");+ unicode-range: U+3010-3011, U+4E07, U+4E1C, U+4E24, U+4E3E, U+4E48, U+4E50, U+4E5F, U+4E8B-4E8C, U+4EA4, U+4EAB-4EAC, U+4ECB, U+4ECE, U+4ED6, U+4EE3, U+4EF6-4EF7, U+4EFB, U+4F20, U+4F55, U+4F7F, U+4FDD, U+505A, U+5143, U+5149, U+514D, U+5171, U+5177, U+518C, U+51FB, U+521B, U+5229, U+522B, U+52A9, U+5305, U+5317, U+534E, U+5355, U+5357, U+535A, U+5373, U+539F, U+53BB, U+53CA, U+53CD, U+53D6, U+53E3, U+53F0, U+5458, U+5546, U+56DB, U+573A, U+578B, U+57CE, U+58F0, U+590D, U+5934, U+5973, U+5B57, U+5B8C, U+5B98, U+5BB9, U+5BFC, U+5C06, U+5C11, U+5C31, U+5C55, U+5DF2, U+5E03, U+5E38, U+5E76, U+5E94, U+5EFA, U+5F71, U+5F97, U+5FEB, U+6001, U+603B, U+60F3, U+611F, U+6216, U+624D, U+6253, U+6295, U+6301, U+6392, U+641C, U+652F, U+653E, U+6559, U+6599, U+661F, U+671F, U+672F, U+6761, U+67E5, U+6807, U+6837, U+683C, U+6848, U+6B22, U+6B64, U+6BD4, U+6C14, U+6C34, U+6C42, U+6CA1, U+6D41, U+6D77, U+6D88, U+6E05, U+6E38, U+6E90, U+7136, U+7231, U+7531, U+767E, U+76EE, U+76F4, U+771F, U+7801, U+793A, U+79CD, U+7A0B, U+7A7A, U+7ACB, U+7AE0, U+7B2C, U+7B80, U+7BA1, U+7CBE, U+7D22, U+7EA7, U+7ED3, U+7ED9, U+7EDF, U+7F16, U+7F6E, U+8001, U+800C, U+8272, U+8282, U+82B1, U+8350, U+88AB, U+88C5, U+897F, U+89C1, U+89C4, U+89E3, U+8A00, U+8BA1, U+8BA4, U+8BAE-8BB0, U+8BBE, U+8BC1, U+8BC4, U+8BFB, U+8D28, U+8D39, U+8D77, U+8D85, U+8DEF, U+8EAB, U+8F66, U+8F6C, U+8F7D, U+8FD0, U+9009, U+90AE, U+90FD, U+91CC-91CD, U+91CF, U+95FB, U+9650, U+96C6, U+9891, U+98CE, U+FF1F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-118.woff2") format("woff2");+ unicode-range: U+4E09-4E0B, U+4E0D-4E0E, U+4E13, U+4E1A, U+4E2A, U+4E3A-4E3B, U+4E4B, U+4E86, U+4E8E, U+4EA7, U+4EBA, U+4EE4-4EE5, U+4EEC, U+4F1A, U+4F4D, U+4F53, U+4F5C, U+4F60, U+4FE1, U+5165, U+5168, U+516C, U+5173, U+5176, U+5185, U+51FA, U+5206, U+5230, U+5236, U+524D, U+529B, U+52A0-52A1, U+52A8, U+5316, U+533A, U+53CB, U+53D1, U+53EF, U+53F7-53F8, U+5408, U+540C-540E, U+544A, U+548C, U+54C1, U+56DE, U+56FD-56FE, U+5728, U+5730, U+5907, U+5916, U+591A, U+5927, U+5929, U+597D, U+5982, U+5B50, U+5B66, U+5B89, U+5B9A, U+5B9E, U+5BA2, U+5BB6, U+5BF9, U+5C0F, U+5DE5, U+5E02, U+5E73-5E74, U+5E7F, U+5EA6, U+5F00, U+5F0F, U+5F53, U+5F55, U+5FAE, U+5FC3, U+6027, U+606F, U+60A8, U+60C5, U+610F, U+6210-6211, U+6237, U+6240, U+624B, U+6280, U+62A5, U+63A5, U+63A8, U+63D0, U+6536, U+6570, U+6587, U+65B9, U+65E0, U+65F6, U+660E, U+662D, U+662F, U+66F4, U+6700, U+670D, U+672C, U+673A, U+6743, U+6765, U+679C, U+682A, U+6B21, U+6B63, U+6CBB, U+6CD5, U+6CE8, U+6D3B, U+70ED, U+7247-7248, U+7269, U+7279, U+73B0, U+7406, U+751F, U+7528, U+7535, U+767B, U+76F8, U+770B, U+77E5, U+793E, U+79D1, U+7AD9, U+7B49, U+7C7B, U+7CFB, U+7EBF, U+7ECF, U+7F8E, U+8005, U+8054, U+80FD, U+81EA, U+85CF, U+884C, U+8868, U+8981, U+89C6, U+8BBA, U+8BDD, U+8BF4, U+8BF7, U+8D44, U+8FC7, U+8FD8-8FD9, U+8FDB, U+901A, U+9053, U+90E8, U+91D1, U+957F, U+95E8, U+95EE, U+95F4, U+9762, U+9875, U+9898, U+9996, U+9AD8, U+FF01, U+FF08-FF09;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-119.woff2") format("woff2");+ unicode-range: U+3001-3002, U+3042, U+3044, U+3046, U+3048, U+304A-3055, U+3057, U+3059-305B, U+305D, U+305F-3061, U+3063-306B, U+306D-3073, U+3075-3076, U+3078-3079, U+307B, U+307E-307F, U+3081-308D, U+308F, U+3092-3093, U+30A1-30A4, U+30A6-30BB, U+30BD, U+30BF-30C1, U+30C3-30C4, U+30C6-30CB, U+30CD-30D7, U+30D9-30E1, U+30E3-30E7, U+30E9-30ED, U+30EF, U+30F3, U+30FC, U+3127, U+4E00, U+4E2D, U+65B0, U+65E5, U+6708-6709, U+70B9, U+7684, U+7F51, U+FF0C, U+FF0E, U+FF1A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-cyrillic.woff2") format("woff2");+ unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-vietnamese.woff2") format("woff2");+ unicode-range: U+0300-0301, U+0303, U+0309, U+0323, U+1EA0-1EF1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-latin-ext.woff2") format("woff2");+ unicode-range: U+0100-0130, U+0132-0151, U+0154-017F, U+0181, U+0188, U+018A, U+018F, U+0192, U+0198-0199, U+01A0-01A1, U+01A5, U+01AD, U+01AF-01B0, U+01B3-01B4, U+01B7, U+01C0-01C3, U+01CD-01DC, U+01E4-01E9, U+01EE-01F0, U+01F9-01FF, U+0218-021B, U+021E-021F, U+0237, U+0250-0268, U+026A-0276, U+0278-027B, U+027D-027E, U+0280-0284, U+0288-0292, U+0294-0295, U+0298-0299, U+029B-02AD, U+02B0, U+02B2-02B3, U+02B7-02B8, U+02C1, U+02C7-02CC, U+02D0-02D1, U+02DD-02DE, U+02E0-02E3, U+02E5-02E9, U+02EC-02ED, U+02F3, U+1D43, U+1D47-1D49, U+1D4D, U+1D4F-1D50, U+1D52, U+1D56-1D58, U+1D5B, U+1D6C-1D76, U+1D9C, U+1DA0, U+1DBB, U+1E00-1E01, U+1E3E-1E3F, U+1E80-1E85, U+1E9E, U+1EF2-1EF9, U+20A3-20A4, U+20A8-20A9, U+20AB, U+20AE, U+20B1, U+20B8-20BA, U+20BD, U+20BF, U+2113;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-latin.woff2") format("woff2");+ unicode-range: U+0001, U+000A, U+000D, U+0020-007F, U+00A0-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2004-2006, U+2009-200A, U+2010, U+2013-2016, U+2018-201A, U+201C-201E, U+2020-2022, U+2025-2026, U+2028-2029, U+2030-2037, U+2039-203C, U+203E-203F, U+2042-2044, U+2047-2049, U+204E, U+2051, U+2055, U+2060-2064, U+2066-2069, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 400;+ src: url("./misans-400-extra.woff2") format("woff2");+ unicode-range: U+02DB, U+030F, U+0312, U+0318-031A, U+031C-0320, U+0326, U+032A, U+0330, U+033A-033B, U+0346-0347, U+0349-034E, U+0362, U+0374-0375, U+037E, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03CE, U+03D1-03D4, U+03D6, U+0462-0463, U+046A-046B, U+0472-0475, U+0492-0493, U+0497, U+049A-049D, U+04A2-04A3, U+04AE-04AF, U+04B2-04B3, U+04B6-04BB, U+04CA, U+04D8-04D9, U+04E2-04E3, U+04E8-04E9, U+04EE-04EF, U+0E3F, U+1DC6-1DC9, U+1F45, U+2071, U+2079, U+2084-2089, U+2114, U+211E, U+212E, U+2153-2154, U+215B-215E, U+2160-2179, U+2180-2182, U+2527, U+2535, U+2538-253A, U+2549, U+2552-2553, U+2555-2556, U+2558-2559, U+255C, U+255E, U+2561, U+2564, U+2568, U+256B, U+275C, U+2783-2789, U+278D, U+278F-2793, U+2E81, U+2E84, U+2E88, U+2E8B-2E8C, U+2E97, U+2EA7, U+2EAA, U+2EAE, U+2EB3, U+2EB6-2EB7, U+2ECA, U+2FF0-2FFB, U+3022, U+3025-3029, U+303E, U+3094, U+30F7-30FA, U+33CE, U+A71B-A71C, U+AB53, U+FE10-FE19;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-5.woff2") format("woff2");+ unicode-range: U+FF03-FF04, U+FF07, U+FF0A, U+FF17-FF19, U+FF1C-FF1E, U+FF20-FF3A, U+FF3C, U+FF3E-FF5B, U+FF5D, U+FFE0-FFE4;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-6.woff2") format("woff2");+ unicode-range: U+F92C, U+F979, U+FA11, U+FE30-FE31, U+FE33-FE44, U+FE49-FE52, U+FE54-FE57, U+FE59-FE66, U+FE68-FE6B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-21.woff2") format("woff2");+ unicode-range: U+9F83, U+9F85-9F8D, U+9F90-9F91, U+9F94-9F96, U+9F98, U+9F9B-9F9C, U+9F9E, U+9FA0, U+9FA2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-22.woff2") format("woff2");+ unicode-range: U+9E30-9E33, U+9E35-9E3B, U+9E3E, U+9E40-9E44, U+9E46-9E4E, U+9E51, U+9E53, U+9E55-9E58, U+9E5A-9E5C, U+9E5E-9E63, U+9E66-9E6E, U+9E71, U+9E73, U+9E75, U+9E78-9E79, U+9E7C-9E7E, U+9E82, U+9E86-9E88, U+9E8B-9E8C, U+9E90-9E91, U+9E93, U+9E95, U+9E97, U+9E9D, U+9EA4-9EA5, U+9EA9-9EAA, U+9EB4-9EB5, U+9EB8-9EBA, U+9EBC-9EBF, U+9EC3, U+9EC9, U+9ECD, U+9ED0, U+9ED2-9ED3, U+9ED5-9ED6, U+9ED9, U+9EDC-9EDD, U+9EDF-9EE0, U+9EE2, U+9EE5, U+9EE7-9EEA, U+9EEF, U+9EF1, U+9EF3-9EF4, U+9EF6, U+9EF9, U+9EFB-9EFC, U+9EFE, U+9F0B, U+9F0D, U+9F10, U+9F14, U+9F17, U+9F19, U+9F22, U+9F29, U+9F2C, U+9F2F, U+9F31, U+9F37, U+9F39, U+9F3D-9F3E, U+9F41, U+9F4A-9F4B, U+9F51-9F52, U+9F61-9F63, U+9F66-9F67, U+9F80-9F81;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-23.woff2") format("woff2");+ unicode-range: U+9C82-9C83, U+9C85-9C8C, U+9C8E-9C92, U+9C94-9C9B, U+9C9E-9CA3, U+9CA5-9CA7, U+9CA9, U+9CAB, U+9CAD-9CAE, U+9CB1-9CB7, U+9CB9-9CBD, U+9CBF-9CC0, U+9CC3, U+9CC5-9CC7, U+9CC9-9CD1, U+9CD3-9CDA, U+9CDC-9CDD, U+9CDF, U+9CE1-9CE3, U+9CE5, U+9CE9, U+9CEE-9CEF, U+9CF3-9CF4, U+9CF6, U+9CFC-9CFD, U+9D02, U+9D08-9D09, U+9D12, U+9D1B, U+9D1E, U+9D26, U+9D28, U+9D37, U+9D3B, U+9D3F, U+9D51, U+9D59, U+9D5C-9D5D, U+9D5F-9D61, U+9D6C, U+9D70, U+9D72, U+9D7A, U+9D7E, U+9D84, U+9D89, U+9D8F, U+9D92, U+9DAF, U+9DB4, U+9DB8, U+9DBC, U+9DC4, U+9DC7, U+9DC9, U+9DD7, U+9DDF, U+9DF2, U+9DF9-9DFA, U+9E0A, U+9E11, U+9E1A, U+9E1E, U+9E20, U+9E22, U+9E28-9E2C, U+9E2E-9E2F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-24.woff2") format("woff2");+ unicode-range: U+9A80, U+9A83, U+9A85, U+9A88-9A8A, U+9A8D-9A8E, U+9A90, U+9A92-9A93, U+9A95-9A96, U+9A98-9A99, U+9A9B-9AA2, U+9AA5, U+9AA7, U+9AAF-9AB1, U+9AB5-9AB6, U+9AB9-9ABA, U+9AC0-9AC4, U+9AC8, U+9ACB-9ACC, U+9ACE-9ACF, U+9AD1-9AD2, U+9AD9, U+9ADF, U+9AE1, U+9AE3, U+9AEA-9AEB, U+9AED-9AEF, U+9AF4, U+9AF9, U+9AFB, U+9B03-9B04, U+9B06, U+9B08, U+9B0D, U+9B0F-9B10, U+9B13, U+9B18, U+9B1A, U+9B1F, U+9B22-9B23, U+9B25, U+9B27-9B28, U+9B2A, U+9B2F, U+9B31-9B32, U+9B3B, U+9B43, U+9B46-9B49, U+9B4D-9B4E, U+9B51, U+9B56, U+9B58, U+9B5A, U+9B5C, U+9B5F, U+9B61-9B62, U+9B6F, U+9B77, U+9B80, U+9B88, U+9B8B, U+9B8E, U+9B91, U+9B9F-9BA0, U+9BA8, U+9BAA-9BAB, U+9BAD-9BAE, U+9BB0-9BB1, U+9BB8, U+9BC9-9BCA, U+9BD3, U+9BD6, U+9BDB, U+9BE8, U+9BF0-9BF1, U+9C02, U+9C10, U+9C15, U+9C24, U+9C2D, U+9C32, U+9C39, U+9C3B, U+9C40, U+9C47-9C49, U+9C53, U+9C57, U+9C64, U+9C72, U+9C77-9C78, U+9C7B, U+9C7F-9C80;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-25.woff2") format("woff2");+ unicode-range: U+98DD, U+98E1-98E2, U+98E7-98EA, U+98EC, U+98EE-98EF, U+98F2, U+98F4, U+98FC-98FE, U+9903, U+9905, U+9908, U+990A, U+990C-990D, U+9913-9914, U+9918, U+991A-991B, U+991E, U+9921, U+9928, U+992C, U+992E, U+9935, U+9938-9939, U+993D-993E, U+9945, U+994B-994C, U+9951-9952, U+9954-9955, U+9957, U+995E, U+9963, U+9966-9969, U+996B-996C, U+996F, U+9974-9975, U+9977-9979, U+997D-997E, U+9980-9981, U+9983-9984, U+9987, U+998A-998B, U+998D-9991, U+9993-9995, U+9997-9998, U+99A5, U+99AB, U+99AD-99AE, U+99B1, U+99B3-99B4, U+99BC, U+99BF, U+99C1, U+99C3-99C6, U+99CC, U+99D0, U+99D2, U+99D5, U+99DB, U+99DD, U+99E1, U+99ED, U+99F1, U+99FF, U+9A01, U+9A03-9A04, U+9A0E-9A0F, U+9A11-9A13, U+9A19, U+9A1B, U+9A28, U+9A2B, U+9A30, U+9A32, U+9A37, U+9A40, U+9A45, U+9A4A, U+9A4D-9A4E, U+9A52, U+9A55, U+9A57, U+9A5A-9A5B, U+9A5F, U+9A62, U+9A65, U+9A69, U+9A6B, U+9A6E, U+9A75, U+9A77-9A7A, U+9A7D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-26.woff2") format("woff2");+ unicode-range: U+975B-975C, U+9763, U+9765-9766, U+976C-976D, U+9773, U+9776, U+977A, U+977C, U+9784-9785, U+978E-978F, U+9791-9792, U+9794-9795, U+9798, U+979A, U+979E, U+97A3, U+97A5-97A6, U+97A8, U+97AB-97AC, U+97AE-97AF, U+97B2, U+97B4, U+97C6, U+97CB-97CC, U+97D3, U+97D8, U+97DC, U+97E1, U+97EA-97EB, U+97EE, U+97FB, U+97FE-97FF, U+9801-9803, U+9805-9806, U+9808, U+980C, U+9810-9814, U+9817-9818, U+981E, U+9820-9821, U+9824, U+9828, U+982B-982D, U+9830, U+9834, U+9838-9839, U+983C, U+9846, U+984D-984F, U+9851-9852, U+9854-9855, U+9857-9858, U+985A-985B, U+9862-9863, U+9865, U+9867, U+986B, U+986F-9871, U+9877-9878, U+987C, U+9880, U+9883, U+9885, U+9889, U+988B-988F, U+9893-9895, U+9899-989B, U+989E-989F, U+98A1-98A2, U+98A5-98A7, U+98A9, U+98AF, U+98B1, U+98B6, U+98BA, U+98BE, U+98C3-98C4, U+98C6-98C8, U+98CF-98D6, U+98DA-98DB;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-27.woff2") format("woff2");+ unicode-range: U+95C4-95CA, U+95CC-95CD, U+95D4-95D6, U+95D8, U+95E1-95E2, U+95E9, U+95F0-95F1, U+95F3, U+95F6, U+95FC, U+95FE-95FF, U+9602-9604, U+9606-960D, U+960F, U+9611-9613, U+9615-9617, U+9619-961B, U+961D, U+9621, U+9628, U+962F, U+963C-963E, U+9641-9642, U+9649, U+9654, U+965B-965F, U+9661, U+9663, U+9665, U+9667-9668, U+966C, U+9670, U+9672-9674, U+9678, U+967A, U+967D, U+9682, U+9685, U+9688, U+968A, U+968D-968E, U+9695, U+9697-9698, U+969E, U+96A0, U+96A3-96A4, U+96A8, U+96AA, U+96B0-96B1, U+96B3-96B4, U+96B7-96B9, U+96BB-96BD, U+96C9, U+96CB, U+96CE, U+96D1-96D2, U+96D6, U+96D9, U+96DB-96DC, U+96DE, U+96E0, U+96E3, U+96E9, U+96EB, U+96F0-96F2, U+96F9, U+96FF, U+9701-9702, U+9705, U+9708, U+970A, U+970E-970F, U+9711, U+9719, U+9727, U+972A, U+972D, U+9730, U+973D, U+9742, U+9744, U+9748-9749, U+9750-9751, U+975A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-28.woff2") format("woff2");+ unicode-range: U+94F5, U+94F7, U+94F9, U+94FB-94FD, U+94FF, U+9503-9504, U+9506-9507, U+9509-950A, U+950D-950F, U+9511-9518, U+951A-9520, U+9522, U+9528-952D, U+9530-953A, U+953C-953F, U+9543-9546, U+9548-9550, U+9552-9555, U+9557-955B, U+955D-9568, U+956A-956D, U+9570-9574, U+9583, U+9586, U+9589, U+958E-958F, U+9591-9592, U+9594, U+9598-9599, U+959E-95A0, U+95A2-95A6, U+95A8-95B2, U+95B4, U+95B8-95C3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-29.woff2") format("woff2");+ unicode-range: U+941C-942B, U+942D-942E, U+9432-9433, U+9435, U+9438, U+943A, U+943E, U+9444, U+944A, U+9451-9452, U+945A, U+9462-9463, U+9465, U+9470-9487, U+948A-9492, U+9494-9498, U+949A, U+949C-949D, U+94A1, U+94A3-94A4, U+94A8, U+94AA-94AD, U+94AF, U+94B2, U+94B4-94BA, U+94BC-94C0, U+94C4, U+94C6-94DB, U+94DE-94EC, U+94EE-94F1, U+94F3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-30.woff2") format("woff2");+ unicode-range: U+92EC-92ED, U+92F0, U+92F3, U+92F8, U+92FC, U+9304, U+9306, U+9310, U+9312, U+9315, U+9318, U+931A, U+931E, U+9320-9322, U+9324, U+9326-9329, U+932B-932C, U+932F, U+9331-9332, U+9335-9336, U+933E, U+9340-9341, U+934A-9360, U+9362-9363, U+9365-936B, U+936E, U+9375, U+937E, U+9382, U+938A, U+938C, U+938F, U+9393-9394, U+9396-9397, U+939A, U+93A2, U+93A7, U+93AC-93CD, U+93D0-93D1, U+93D6-93D8, U+93DE-93DF, U+93E1-93E2, U+93E4, U+93F8, U+93FB, U+93FD, U+940E-941A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-31.woff2") format("woff2");+ unicode-range: U+9163-9164, U+9169, U+9170, U+9172, U+9174, U+9179-917A, U+917D-917E, U+9182-9183, U+9185, U+918C-918D, U+9190-9191, U+919A, U+919C, U+91A1-91A4, U+91A8, U+91AA-91AF, U+91B4-91B5, U+91B8, U+91BA, U+91BE, U+91C0-91C1, U+91C6, U+91C8, U+91CB, U+91D0, U+91D2, U+91D7-91D8, U+91DD, U+91E3, U+91E6-91E7, U+91ED, U+91F0, U+91F5, U+91F9, U+9200, U+9205, U+9207-920A, U+920D-920E, U+9210, U+9214-9215, U+921C, U+921E, U+9221, U+9223-9227, U+9229-922A, U+922D, U+9234-9235, U+9237, U+9239-923A, U+923C-9240, U+9244-9246, U+9249, U+924E-924F, U+9251, U+9253, U+9257, U+925B, U+925E, U+9262, U+9264-9266, U+9268, U+926C, U+926F, U+9271, U+927B, U+927E, U+9280, U+9283, U+9285-928A, U+928E, U+9291, U+9293, U+9296, U+9298, U+929C-929D, U+92A8, U+92AB-92AE, U+92B3, U+92B6-92B7, U+92B9, U+92C1, U+92C5-92C6, U+92C8, U+92CC, U+92D0, U+92D2, U+92E4, U+92EA;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-32.woff2") format("woff2");+ unicode-range: U+9004, U+900B, U+9011, U+9015-9016, U+901E, U+9021, U+9026, U+902D, U+902F, U+9031, U+9035-9036, U+9039-903A, U+9041, U+9044-9046, U+904A, U+904F-9052, U+9054-9055, U+9058-9059, U+905B-905E, U+9060-9062, U+9068-9069, U+906F, U+9072, U+9074, U+9076-907A, U+907C-907D, U+9081, U+9083, U+9085, U+9087-908B, U+908F, U+9095, U+9097, U+9099-909B, U+909D, U+90A0-90A1, U+90A8-90A9, U+90AC, U+90B0, U+90B2-90B4, U+90B6, U+90B8, U+90BA, U+90BD-90BE, U+90C3-90C5, U+90C7-90C8, U+90CF-90D0, U+90D3, U+90D5, U+90D7, U+90DA-90DC, U+90DE, U+90E2, U+90E4, U+90E6-90E7, U+90EA-90EB, U+90EF, U+90F4-90F5, U+90F7, U+90FE-9100, U+9104, U+9109, U+910C, U+9112, U+9114-9115, U+9118, U+911C, U+911E, U+9120, U+9122-9123, U+9127, U+912D, U+912F-9132, U+9139-913A, U+9143, U+9146, U+9149-914A, U+914C, U+914E-9150, U+9154, U+9157, U+915A, U+915D-915E, U+9161-9162;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-33.woff2") format("woff2");+ unicode-range: U+8E41-8E42, U+8E47, U+8E49-8E4B, U+8E50-8E53, U+8E59-8E5A, U+8E5F-8E60, U+8E64, U+8E69, U+8E6C, U+8E70, U+8E74, U+8E76, U+8E7A-8E7C, U+8E7F, U+8E84-8E85, U+8E87, U+8E89, U+8E8B, U+8E8D, U+8E8F-8E90, U+8E94, U+8E99, U+8E9C, U+8E9E, U+8EAA, U+8EAC, U+8EB0, U+8EB6, U+8EC0, U+8EC6, U+8ECA-8ECE, U+8ED2, U+8EDA, U+8EDF, U+8EE2, U+8EEB, U+8EF8, U+8EFB-8EFE, U+8F03, U+8F09, U+8F0B, U+8F12-8F15, U+8F1B, U+8F1D, U+8F1F, U+8F29-8F2A, U+8F2F, U+8F36, U+8F38, U+8F3B, U+8F3E-8F3F, U+8F44-8F45, U+8F49, U+8F4D-8F4E, U+8F5F, U+8F6B, U+8F6D, U+8F71-8F73, U+8F75-8F76, U+8F78-8F7A, U+8F7C, U+8F7E, U+8F81-8F82, U+8F84, U+8F87, U+8F8A-8F8B, U+8F8D-8F8F, U+8F94-8F95, U+8F97-8F9A, U+8FA6, U+8FAD-8FAF, U+8FB2, U+8FB5-8FB7, U+8FBA-8FBC, U+8FBF, U+8FC2, U+8FCB, U+8FCD, U+8FD3, U+8FD5, U+8FD7, U+8FDA, U+8FE2-8FE5, U+8FE8-8FE9, U+8FEE, U+8FF3-8FF4, U+8FF8, U+8FFA;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-34.woff2") format("woff2");+ unicode-range: U+8CBD, U+8CBF-8CC4, U+8CC7-8CC8, U+8CCA, U+8CCD, U+8CD1, U+8CD3, U+8CDB-8CDC, U+8CDE, U+8CE0, U+8CE2-8CE4, U+8CE6-8CE8, U+8CEA, U+8CED, U+8CF4, U+8CF8, U+8CFA, U+8CFC-8CFD, U+8D04-8D05, U+8D07-8D08, U+8D0A, U+8D0D, U+8D0F, U+8D13-8D14, U+8D16, U+8D1B, U+8D20, U+8D30, U+8D32-8D33, U+8D36, U+8D3B, U+8D3D, U+8D40, U+8D42-8D43, U+8D45-8D46, U+8D48-8D4A, U+8D4D, U+8D51, U+8D53, U+8D55, U+8D59, U+8D5C-8D5D, U+8D5F, U+8D61, U+8D66-8D67, U+8D6A, U+8D6D, U+8D71, U+8D73, U+8D84, U+8D90-8D91, U+8D94-8D95, U+8D99, U+8DA8, U+8DAF, U+8DB1, U+8DB5, U+8DB8, U+8DBA, U+8DBC, U+8DBF, U+8DC2, U+8DC4, U+8DC6, U+8DCB, U+8DCE-8DCF, U+8DD6-8DD7, U+8DDA-8DDB, U+8DDE, U+8DE1, U+8DE3-8DE4, U+8DE9, U+8DEB-8DEC, U+8DF0-8DF1, U+8DF6-8DFD, U+8E05, U+8E07, U+8E09-8E0A, U+8E0C, U+8E0E, U+8E10, U+8E14, U+8E1D-8E1F, U+8E23, U+8E26, U+8E2B-8E31, U+8E34-8E35, U+8E39-8E3A, U+8E3D, U+8E40;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-35.woff2") format("woff2");+ unicode-range: U+8B80, U+8B83, U+8B8A, U+8B8C, U+8B90, U+8B93, U+8B99-8B9A, U+8BA0, U+8BA3, U+8BA5-8BA7, U+8BAA-8BAC, U+8BB4-8BB5, U+8BB7, U+8BB9, U+8BC2-8BC3, U+8BC5, U+8BCB-8BCC, U+8BCE-8BD0, U+8BD2-8BD4, U+8BD6, U+8BD8-8BD9, U+8BDC, U+8BDF, U+8BE3-8BE4, U+8BE7-8BE9, U+8BEB-8BEC, U+8BEE, U+8BF0, U+8BF2-8BF3, U+8BF6, U+8BF9, U+8BFC-8BFD, U+8BFF-8C00, U+8C02, U+8C04, U+8C06-8C07, U+8C0C, U+8C0F, U+8C11-8C12, U+8C14-8C1B, U+8C1D-8C21, U+8C24-8C25, U+8C27, U+8C2A-8C2C, U+8C2E-8C30, U+8C32-8C36, U+8C3F, U+8C47-8C4C, U+8C4E-8C50, U+8C54-8C56, U+8C62, U+8C68, U+8C6C, U+8C73, U+8C78, U+8C7A, U+8C82, U+8C85, U+8C89-8C8A, U+8C8D-8C8E, U+8C90, U+8C93-8C94, U+8C98, U+8C9D-8C9E, U+8CA0-8CA2, U+8CA7-8CAC, U+8CAF-8CB0, U+8CB3-8CB4, U+8CB6-8CB9, U+8CBB-8CBC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-36.woff2") format("woff2");+ unicode-range: U+8A15-8A18, U+8A1A-8A1B, U+8A1D, U+8A1F, U+8A22-8A23, U+8A25, U+8A2B, U+8A2D, U+8A31, U+8A33-8A34, U+8A36-8A38, U+8A3A, U+8A3C, U+8A3E, U+8A40-8A41, U+8A46, U+8A48, U+8A50, U+8A52, U+8A54-8A55, U+8A58, U+8A5B, U+8A5D-8A63, U+8A66, U+8A69-8A6B, U+8A6D-8A6E, U+8A70, U+8A72-8A73, U+8A7A, U+8A85, U+8A87, U+8A8A, U+8A8C-8A8D, U+8A90-8A92, U+8A95, U+8A98, U+8AA0-8AA1, U+8AA3-8AA6, U+8AA8-8AA9, U+8AAC-8AAE, U+8AB0, U+8AB2, U+8AB8-8AB9, U+8ABC, U+8ABE-8ABF, U+8AC7, U+8ACF, U+8AD2, U+8AD6-8AD7, U+8ADB-8ADC, U+8ADF, U+8AE1, U+8AE6-8AE8, U+8AEB, U+8AED-8AEE, U+8AF1, U+8AF3-8AF4, U+8AF7-8AF8, U+8AFA, U+8AFE, U+8B00-8B02, U+8B07, U+8B0A, U+8B0C, U+8B0E, U+8B10, U+8B17, U+8B19, U+8B1B, U+8B1D, U+8B20-8B21, U+8B26, U+8B28, U+8B2C, U+8B33, U+8B39, U+8B3E-8B3F, U+8B41, U+8B45, U+8B49, U+8B4C, U+8B4F, U+8B57-8B58, U+8B5A, U+8B5C, U+8B5E, U+8B60, U+8B6C, U+8B6F-8B70, U+8B72, U+8B74, U+8B77, U+8B7D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-37.woff2") format("woff2");+ unicode-range: U+8882, U+8884-8886, U+8888, U+888F, U+8892-8893, U+889B, U+88A2, U+88A4, U+88A6, U+88A8, U+88AA, U+88AE, U+88B1, U+88B4, U+88B7, U+88BC, U+88C0, U+88C6-88C9, U+88CE-88CF, U+88D1-88D3, U+88D8, U+88DB-88DD, U+88DF, U+88E1-88E3, U+88E5, U+88E8, U+88EC, U+88F0-88F1, U+88F3-88F4, U+88FC-88FE, U+8900, U+8902, U+8906-8907, U+8909-890C, U+8912-8915, U+8918-891B, U+8921, U+8925, U+892B, U+8930, U+8932, U+8934, U+8936, U+893B, U+893D, U+8941, U+894C, U+8955-8956, U+8959, U+895C, U+895E-8960, U+8966, U+896A, U+896C, U+896F-8970, U+8972, U+897B, U+897E, U+8980, U+8983, U+8985, U+8987-8988, U+898C, U+898F, U+8993, U+8997, U+899A, U+89A1, U+89A7, U+89A9-89AA, U+89B2-89B3, U+89B7, U+89C0, U+89C7, U+89CA-89CC, U+89CE-89D1, U+89D6, U+89DA, U+89DC, U+89DE, U+89E5, U+89E7, U+89EB, U+89EF, U+89F1, U+89F3-89F4, U+89F8, U+89FF, U+8A01-8A03, U+8A07-8A0A, U+8A0E-8A0F, U+8A13;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-38.woff2") format("woff2");+ unicode-range: U+86F4, U+86F8-86F9, U+86FB, U+86FE, U+8703, U+8706-870A, U+870D, U+8711-8713, U+871A, U+871E, U+8722-8723, U+8725, U+8729, U+872E, U+8731, U+8734, U+8737, U+873A-873B, U+873E-8740, U+8742, U+8747-8748, U+8753, U+8755, U+8757-8758, U+875D, U+875F, U+8762-8766, U+8768, U+876E, U+8770, U+8772, U+8775, U+8778, U+877B-877E, U+8782, U+8785, U+8788, U+878B, U+8793, U+8797, U+879A, U+879E-87A0, U+87A2-87A3, U+87A8, U+87AB-87AD, U+87AF, U+87B3, U+87B5, U+87BD, U+87C0, U+87C4, U+87C6, U+87CA-87CB, U+87D1-87D2, U+87DB-87DC, U+87DE, U+87E0, U+87E5, U+87EA, U+87EC, U+87EE, U+87F2-87F3, U+87FB, U+87FD-87FE, U+8802-8803, U+8805, U+880A-880B, U+880D, U+8813-8816, U+8819, U+881B, U+881F, U+8821, U+8823, U+8831-8832, U+8835-8836, U+8839, U+883B-883C, U+8844, U+8846, U+884A, U+884E, U+8852-8853, U+8855, U+8859, U+885B, U+885D-885E, U+8862, U+8864, U+8869-886A, U+886E-886F, U+8872, U+8879, U+887D-887F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-39.woff2") format("woff2");+ unicode-range: U+8548, U+854E, U+8553, U+8556-8557, U+8559, U+855E, U+8561, U+8564-8565, U+8568-856A, U+856D, U+856F-8570, U+8572, U+8576, U+8579-857B, U+8580, U+8585-8586, U+8588, U+858A, U+858F, U+8591, U+8594, U+8599, U+859C, U+85A2, U+85A4, U+85A6, U+85A8-85A9, U+85AB-85AC, U+85AE, U+85B7-85B9, U+85BE, U+85C1, U+85C7, U+85CD, U+85D0, U+85D3, U+85D5, U+85DC-85DD, U+85DF-85E0, U+85E5-85E6, U+85E8-85EA, U+85F4, U+85F9, U+85FE-85FF, U+8602, U+8605-8607, U+860A-860B, U+8616, U+8618, U+861A, U+8627, U+8629, U+862D, U+8638, U+863C, U+863F, U+864D, U+864F, U+8652-8655, U+865B-865C, U+865F, U+8662, U+8667, U+866C, U+866E, U+8671, U+8675, U+867A-867C, U+867F, U+868B, U+868D, U+8693, U+869C-869D, U+86A1, U+86A3-86A4, U+86A7-86A9, U+86AC, U+86AF-86B1, U+86B4-86B6, U+86BA, U+86C0, U+86C4, U+86C6, U+86C9-86CA, U+86CD-86D1, U+86D4, U+86D8, U+86DE-86DF, U+86E4, U+86E6, U+86E9, U+86ED, U+86EF-86F3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-40.woff2") format("woff2");+ unicode-range: U+83C5, U+83C8-83C9, U+83CB, U+83D1, U+83D3-83D6, U+83D8, U+83DB, U+83DD, U+83DF, U+83E1, U+83E5, U+83EA-83EB, U+83F0, U+83F4, U+83F8-83F9, U+83FB, U+83FD, U+83FF, U+8401, U+8406, U+840A-840B, U+840F, U+8411, U+8418, U+841C, U+8420, U+8422-8424, U+8426, U+8429, U+842C, U+8438-8439, U+843B-843C, U+843F, U+8446-8447, U+8449, U+844E, U+8451-8452, U+8456, U+8459-845A, U+845C, U+8462, U+8466, U+846D, U+846F-8470, U+8473, U+8476-8478, U+847A, U+847D, U+8484-8485, U+8487, U+8489, U+848C, U+848E, U+8490, U+8493-8494, U+8497, U+849B, U+849E-849F, U+84A1, U+84A5, U+84A8, U+84AF, U+84B4, U+84B9-84BF, U+84C1-84C2, U+84C5-84C7, U+84CA-84CB, U+84CD, U+84D0-84D1, U+84D3, U+84D6, U+84DF-84E0, U+84E2-84E3, U+84E5-84E7, U+84EE, U+84F3, U+84F6, U+84FA, U+84FC, U+84FF-8500, U+850C, U+8511, U+8514-8515, U+8517-8518, U+851F, U+8523, U+8525-8526, U+8529, U+852B, U+852D, U+8532, U+8534-8535, U+8538-853A, U+853C, U+8543, U+8545;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-41.woff2") format("woff2");+ unicode-range: U+82BC, U+82BE, U+82C0-82C2, U+82C4-82C8, U+82CA-82CC, U+82CE, U+82D0, U+82D2-82D3, U+82D5-82D6, U+82D8-82D9, U+82DC-82DE, U+82E0-82E4, U+82E7, U+82E9-82EB, U+82ED-82EE, U+82F3-82F4, U+82F7-82F8, U+82FA-8301, U+8306-8308, U+830C-830D, U+830F, U+8311, U+8313-8315, U+8318, U+831A-831B, U+831D, U+8324, U+8327, U+832A, U+832C-832D, U+832F, U+8331-8334, U+833A-833C, U+8340, U+8343-8345, U+8347-8348, U+834A, U+834C, U+834F, U+8351, U+8356, U+8358-835C, U+835E, U+8360, U+8364-8366, U+8368-836A, U+836C-836E, U+8373, U+8378, U+837B-837D, U+837F-8380, U+8382, U+8388, U+838A-838B, U+8392, U+8394, U+8396, U+8398-8399, U+839B-839C, U+83A0, U+83A2-83A3, U+83A8-83AA, U+83AE-83B0, U+83B3-83B4, U+83B6, U+83B8, U+83BA, U+83BC-83BD, U+83BF-83C0, U+83C2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-42.woff2") format("woff2");+ unicode-range: U+8166-8169, U+816B, U+816D, U+8171, U+8173-8174, U+8178, U+817C-817D, U+8182, U+8188, U+8191, U+8198-819B, U+81A0, U+81A3, U+81A5-81A6, U+81A9, U+81B6, U+81BA-81BB, U+81BD, U+81BF, U+81C1, U+81C3, U+81C6, U+81C9-81CA, U+81CC-81CD, U+81D1, U+81D3-81D4, U+81D8, U+81DB-81DC, U+81DE-81DF, U+81E5, U+81E7-81E9, U+81EB-81EC, U+81EE-81EF, U+81F5, U+81F8, U+81FA, U+81FC, U+81FE, U+8200-8202, U+8204, U+8208-820A, U+820E-8210, U+8216-8218, U+821B-821C, U+8221-8224, U+8226-8228, U+822B, U+822D, U+822F, U+8232-8234, U+8237-8238, U+823A-823B, U+823E, U+8244, U+8249, U+824B, U+824F, U+8259-825A, U+825F, U+8266, U+8268, U+826E, U+8271, U+8276-8279, U+827D, U+827F, U+8283-8284, U+8288-828A, U+828D-8291, U+8293-8294, U+8296-8298, U+829F-82A1, U+82A3-82A4, U+82A7-82AB, U+82AE, U+82B0, U+82B2, U+82B4-82B6;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-43.woff2") format("woff2");+ unicode-range: U+8016, U+8018-8019, U+801C, U+801E, U+8026-802A, U+8031, U+8034-8035, U+8037, U+8043, U+804B, U+804D, U+8052, U+8056, U+8059, U+805E, U+8061, U+8068-8069, U+806E-8074, U+8076-8078, U+807C-8080, U+8082, U+8084-8085, U+8088, U+808F, U+8093, U+809C, U+809F, U+80AB, U+80AD-80AE, U+80B1, U+80B6-80B8, U+80BC-80BD, U+80C2, U+80C4, U+80CA, U+80CD, U+80D1, U+80D4, U+80D7, U+80D9-80DB, U+80DD, U+80E0, U+80E4-80E5, U+80E7-80ED, U+80EF-80F1, U+80F3-80F4, U+80FC, U+8101, U+8104-8105, U+8107-8108, U+810C-810E, U+8112-8115, U+8117-8119, U+811B-811F, U+8121-8130, U+8132-8134, U+8137, U+8139, U+813F-8140, U+8142, U+8146, U+8148, U+814D-814E, U+8151, U+8153, U+8158-815A, U+815E, U+8160;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-44.woff2") format("woff2");+ unicode-range: U+7EF0-7EF2, U+7EF6, U+7EFA-7EFB, U+7EFE, U+7F01-7F04, U+7F08, U+7F0A-7F12, U+7F17, U+7F19, U+7F1B-7F1C, U+7F1F, U+7F21-7F23, U+7F25-7F28, U+7F2A-7F33, U+7F35-7F37, U+7F3D, U+7F42, U+7F44-7F45, U+7F4C-7F4D, U+7F52, U+7F54, U+7F58-7F59, U+7F5D, U+7F5F-7F61, U+7F63, U+7F65, U+7F68, U+7F70-7F71, U+7F73-7F75, U+7F77, U+7F79, U+7F7D-7F7E, U+7F85-7F86, U+7F88-7F89, U+7F8B-7F8C, U+7F90-7F91, U+7F94-7F96, U+7F98-7F9B, U+7F9D, U+7F9F, U+7FA3, U+7FA7-7FA9, U+7FAC-7FB2, U+7FB4, U+7FB6, U+7FB8, U+7FBC, U+7FBF-7FC0, U+7FC3, U+7FCA, U+7FCC, U+7FCE, U+7FD2, U+7FD5, U+7FD9-7FDB, U+7FDF, U+7FE3, U+7FE5-7FE7, U+7FE9, U+7FEB-7FEC, U+7FEE-7FEF, U+7FF1, U+7FF3-7FF4, U+7FF9-7FFA, U+7FFE, U+8004, U+8006, U+800B, U+800E, U+8011-8012, U+8014;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-45.woff2") format("woff2");+ unicode-range: U+7DD2, U+7DD4, U+7DD6-7DD8, U+7DDA-7DE0, U+7DE2-7DE6, U+7DE8-7DED, U+7DEF, U+7DF1-7DF5, U+7DF7, U+7DF9, U+7DFB-7DFC, U+7DFE-7E02, U+7E04, U+7E08-7E0B, U+7E12, U+7E1B, U+7E1E, U+7E20, U+7E22-7E23, U+7E26, U+7E29, U+7E2B, U+7E2E-7E2F, U+7E31, U+7E37, U+7E39-7E3E, U+7E40, U+7E43-7E44, U+7E46-7E47, U+7E4A-7E4B, U+7E4D-7E4E, U+7E51, U+7E54-7E56, U+7E58-7E5B, U+7E5D-7E5E, U+7E61, U+7E66-7E67, U+7E69-7E6B, U+7E6D, U+7E70, U+7E73, U+7E77, U+7E79, U+7E7B-7E7D, U+7E81-7E82, U+7E8C-7E8D, U+7E8F, U+7E92-7E94, U+7E96, U+7E98, U+7E9A-7E9C, U+7E9E-7E9F, U+7EA1, U+7EA3, U+7EA5, U+7EA8-7EA9, U+7EAB, U+7EAD-7EAE, U+7EB0, U+7EBB, U+7EBE, U+7EC0-7EC2, U+7EC9, U+7ECB-7ECC, U+7ED0, U+7ED4, U+7ED7, U+7EDB, U+7EE0-7EE2, U+7EE5-7EE6, U+7EE8, U+7EEB;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-46.woff2") format("woff2");+ unicode-range: U+7CE8, U+7CEC, U+7CF0, U+7CF5-7CF9, U+7CFC, U+7CFE, U+7D00, U+7D04-7D0B, U+7D0D, U+7D10-7D14, U+7D17-7D19, U+7D1B-7D1F, U+7D21, U+7D24-7D26, U+7D28-7D2A, U+7D2C-7D2E, U+7D30-7D31, U+7D33, U+7D35-7D36, U+7D38-7D3A, U+7D40, U+7D42-7D44, U+7D46, U+7D4B-7D4C, U+7D4F, U+7D51, U+7D54-7D56, U+7D58, U+7D5B-7D5C, U+7D5E, U+7D61-7D63, U+7D66, U+7D68, U+7D6A-7D6C, U+7D6F, U+7D71-7D73, U+7D75-7D77, U+7D79-7D7A, U+7D7E, U+7D81, U+7D84-7D8B, U+7D8D, U+7D8F, U+7D91, U+7D94, U+7D96, U+7D98-7D9A, U+7D9C-7DA0, U+7DA2, U+7DA6, U+7DAA-7DB1, U+7DB4-7DB8, U+7DBA-7DBF, U+7DC1, U+7DC4, U+7DC7-7DC8, U+7DCA-7DCD, U+7DCF, U+7DD1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-47.woff2") format("woff2");+ unicode-range: U+7BD3-7BD4, U+7BD9-7BDA, U+7BDD, U+7BE0-7BE1, U+7BE4-7BE6, U+7BE9-7BEA, U+7BEF, U+7BF4, U+7BF6, U+7BFC, U+7BFE, U+7C01, U+7C03, U+7C07-7C08, U+7C0A-7C0D, U+7C0F, U+7C11, U+7C15-7C16, U+7C19, U+7C1E-7C21, U+7C23-7C24, U+7C26, U+7C28-7C33, U+7C35, U+7C37-7C3B, U+7C3D-7C3E, U+7C40-7C41, U+7C43, U+7C47-7C48, U+7C4C, U+7C50, U+7C53-7C54, U+7C59, U+7C5F-7C60, U+7C63-7C65, U+7C6C, U+7C6E, U+7C72, U+7C74, U+7C79-7C7A, U+7C7C, U+7C81-7C82, U+7C84-7C85, U+7C88, U+7C8A-7C91, U+7C93-7C96, U+7C99, U+7C9B-7C9E, U+7CA0-7CA2, U+7CA6-7CA9, U+7CAC, U+7CAF-7CB3, U+7CB5-7CB7, U+7CBA-7CBD, U+7CBF-7CC2, U+7CC5, U+7CC7-7CC9, U+7CCC-7CCD, U+7CD7, U+7CDC, U+7CDE, U+7CE0, U+7CE4-7CE5, U+7CE7;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-48.woff2") format("woff2");+ unicode-range: U+7AE6, U+7AF4-7AF7, U+7AFA-7AFB, U+7AFD-7B0A, U+7B0C, U+7B0E-7B0F, U+7B13, U+7B15-7B16, U+7B18-7B19, U+7B1E-7B20, U+7B22-7B25, U+7B29-7B2B, U+7B2D-7B2E, U+7B30-7B3B, U+7B3E-7B3F, U+7B41-7B42, U+7B44-7B47, U+7B4A, U+7B4C-7B50, U+7B58, U+7B5A, U+7B5C, U+7B60, U+7B66-7B67, U+7B69, U+7B6C-7B6F, U+7B72-7B76, U+7B7B-7B7D, U+7B7F, U+7B82, U+7B85, U+7B87, U+7B8B-7B96, U+7B98-7B99, U+7B9B-7B9F, U+7BA2-7BA4, U+7BA6-7BAC, U+7BAE-7BB0, U+7BB4, U+7BB7-7BB9, U+7BBB, U+7BC0-7BC1, U+7BC3-7BC4, U+7BC6, U+7BC8-7BCC, U+7BD1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-49.woff2") format("woff2");+ unicode-range: U+798B-798E, U+7992, U+7994-7995, U+7997-7998, U+799A-799C, U+799F, U+79A3-79A6, U+79A8-79AC, U+79AE-79B1, U+79B3-79B5, U+79B8, U+79BA, U+79BF, U+79C2, U+79C6, U+79C8, U+79CF, U+79D5-79D6, U+79DD-79DE, U+79E3, U+79E7-79E8, U+79EB, U+79ED, U+79F4, U+79F7-79F8, U+79FA, U+79FE, U+7A02-7A03, U+7A05, U+7A0A, U+7A14, U+7A17, U+7A19, U+7A1C, U+7A1E-7A1F, U+7A23, U+7A25-7A26, U+7A2C, U+7A2E, U+7A30-7A32, U+7A36-7A37, U+7A39, U+7A3C, U+7A40, U+7A42, U+7A47, U+7A49, U+7A4C-7A4F, U+7A51, U+7A55, U+7A5B, U+7A5D-7A5E, U+7A62-7A63, U+7A66, U+7A68-7A69, U+7A6B, U+7A70, U+7A78, U+7A80, U+7A85-7A88, U+7A8A, U+7A90, U+7A93-7A96, U+7A98, U+7A9B-7A9C, U+7A9E, U+7AA0-7AA1, U+7AA3, U+7AA8-7AAA, U+7AAC-7AB0, U+7AB3, U+7AB8, U+7ABA, U+7ABD-7ABF, U+7AC4-7AC5, U+7AC7-7AC8, U+7ACA, U+7AD1-7AD2, U+7ADA-7ADD, U+7AE1, U+7AE4;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-50.woff2") format("woff2");+ unicode-range: U+784C, U+784E-7854, U+7856-7857, U+7859-785A, U+7865, U+7869-786A, U+786D, U+786F, U+7876-7877, U+787C, U+787E-787F, U+7881, U+7887-7889, U+7893-7894, U+7898-789E, U+78A1, U+78A3, U+78A5, U+78A9, U+78AD, U+78B2, U+78B4, U+78B6, U+78B9-78BA, U+78BC, U+78BF, U+78C3, U+78C9, U+78CB, U+78D0-78D2, U+78D4, U+78D9-78DA, U+78DC, U+78DE, U+78E1, U+78E5-78E6, U+78EA, U+78EC, U+78EF, U+78F1-78F2, U+78F4, U+78FA-78FB, U+78FE, U+7901-7902, U+7905, U+7907, U+7909, U+790B-790C, U+790E, U+7910, U+7913, U+7919-791B, U+791E-791F, U+7921, U+7924, U+7926, U+792A-792B, U+7934, U+7936, U+7939, U+793B, U+793D, U+7940, U+7942-7943, U+7945-7947, U+7949-794A, U+794C, U+794E-7951, U+7953-7955, U+7957-795A, U+795C, U+795F-7960, U+7962, U+7964, U+7966-7967, U+7969, U+796B, U+796F, U+7972, U+7974, U+7979, U+797B-797C, U+797E-7980, U+7982, U+7986-7987, U+7989-798A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-51.woff2") format("woff2");+ unicode-range: U+7722, U+7726, U+7728, U+772B-7730, U+7732-7736, U+7739-773A, U+773D-773F, U+7743, U+7746-7747, U+774C-774F, U+7751-7752, U+7758-775A, U+775C-775E, U+7762, U+7765-7766, U+7768-776A, U+776C-776D, U+7771-7772, U+777A, U+777C-777E, U+7780, U+7785, U+7787, U+778B-778D, U+778F-7791, U+7793, U+779E-77A0, U+77A2, U+77A5, U+77AD, U+77AF, U+77B4-77B7, U+77BD-77C0, U+77C2, U+77C5, U+77C7, U+77CD, U+77D6-77D7, U+77D9-77DA, U+77DD-77DE, U+77E7, U+77EA, U+77EC, U+77EF, U+77F8, U+77FB, U+77FD-77FE, U+7800, U+7803, U+7806, U+7809, U+780F-7812, U+7815, U+7817-7818, U+781A-781F, U+7821-7823, U+7825-7827, U+7829, U+782B-7830, U+7832-7833, U+7835, U+7837, U+7839-783C, U+783E, U+7841-7844, U+7847-7849, U+784B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-52.woff2") format("woff2");+ unicode-range: U+7613-7619, U+761B-761D, U+761F-7622, U+7625, U+7627-762A, U+762E-7630, U+7632-7635, U+7638-763A, U+763C-763D, U+763F-7640, U+7642-7643, U+7647-7648, U+764D-764E, U+7652, U+7654, U+7658, U+765A, U+765C, U+765E-765F, U+7661-7663, U+7665, U+7669, U+766C, U+766E-766F, U+7671-7673, U+7675-7676, U+7678-767A, U+767F, U+7681, U+7683, U+7688, U+768A-768C, U+768E, U+7690-7692, U+7695, U+7698, U+769A-769B, U+769D-76A0, U+76A2, U+76A4-76A7, U+76AB-76AC, U+76AF-76B0, U+76B2, U+76B4-76B5, U+76BA-76BB, U+76BF, U+76C2-76C3, U+76C5, U+76C9, U+76CC-76CE, U+76DC-76DE, U+76E1-76EA, U+76F1, U+76F9-76FB, U+76FD, U+76FF-7700, U+7703-7704, U+7707-7708, U+770C-770F, U+7712, U+7714, U+7716, U+7719-771B, U+771E, U+7721;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-53.woff2") format("woff2");+ unicode-range: U+750D, U+750F, U+7511, U+7513, U+7515, U+7517, U+7519, U+7521-7527, U+752A, U+752C-752D, U+752F, U+7534, U+7536, U+753A, U+753E, U+7540, U+7544, U+7547-754B, U+754D-754E, U+7550-7553, U+7556-7557, U+755A-755B, U+755D-755E, U+7560, U+7562, U+7564, U+7566-7568, U+756B-756C, U+756F-7573, U+7575, U+7579-757C, U+757E-757F, U+7581-7584, U+7587, U+7589-758E, U+7590, U+7592, U+7594, U+7596, U+7599-759A, U+759D, U+759F-75A0, U+75A3, U+75A5, U+75A8, U+75AC-75AD, U+75B0-75B1, U+75B3-75B5, U+75B8, U+75BD, U+75C1-75C4, U+75C8-75CA, U+75CC-75CD, U+75D4, U+75D6, U+75D9, U+75DE, U+75E0, U+75E2-75E4, U+75E6-75EA, U+75F1-75F3, U+75F7, U+75F9-75FA, U+75FC, U+75FE-7601, U+7603, U+7605-7606, U+7608-760E, U+7610-7612;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-54.woff2") format("woff2");+ unicode-range: U+73F0, U+73F2, U+73F4-73F5, U+73F7, U+73F9-73FA, U+73FC-73FD, U+73FF-7402, U+7404, U+7407-7408, U+740A-740F, U+7418, U+741A-741C, U+741E, U+7424-7425, U+7428-7429, U+742C-7430, U+7432, U+7435-7436, U+7438-743B, U+743E-7441, U+7443-7446, U+7448, U+744A-744B, U+7452, U+7457, U+745B, U+745D, U+7460, U+7462-7465, U+7467-746A, U+746D, U+746F, U+7471, U+7473-7474, U+7477, U+747A, U+747E, U+7481-7482, U+7484, U+7486, U+7488-748B, U+748E-748F, U+7493, U+7498, U+749A, U+749C-74A0, U+74A3, U+74A6, U+74A9-74AA, U+74AE, U+74B0-74B2, U+74B6, U+74B8-74BA, U+74BD, U+74BF, U+74C1, U+74C3, U+74C5, U+74C8, U+74CA, U+74CC, U+74CF, U+74D1-74D2, U+74D4-74D5, U+74D8-74DB, U+74DE-74E0, U+74E2, U+74E4-74E5, U+74E7-74E9, U+74EE-74EF, U+74F4, U+74FF, U+7501, U+7503, U+7505, U+7508;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-55.woff2") format("woff2");+ unicode-range: U+72E6, U+72E8, U+72EF-72F0, U+72F2-72F4, U+72F6-72F7, U+72F9-72FB, U+72FD, U+7300-7304, U+7307, U+730A-730C, U+7313-7317, U+731D-7322, U+7327, U+7329, U+732C-732D, U+7330-7331, U+7333, U+7335-7337, U+7339, U+733D-733E, U+7340, U+7342, U+7344-7345, U+734A, U+734D-7350, U+7352, U+7355, U+7357, U+7359, U+735F-7360, U+7362-7363, U+7365, U+7368, U+736C-736D, U+736F-7370, U+7372, U+7374-7376, U+7378, U+737A-737B, U+737D-737E, U+7382-7383, U+7386, U+7388, U+738A, U+738C-7393, U+7395, U+7397-739A, U+739C, U+739E, U+73A0-73A3, U+73A5-73A8, U+73AA, U+73AD, U+73B1, U+73B3, U+73B6-73B7, U+73B9, U+73C2, U+73C5-73C9, U+73CC, U+73CE-73D0, U+73D2, U+73D6, U+73D9, U+73DB-73DE, U+73E3, U+73E5-73EA, U+73EE-73EF;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-56.woff2") format("woff2");+ unicode-range: U+71A8, U+71AF, U+71B1-71BC, U+71BE, U+71C1-71C2, U+71C4, U+71C8-71CB, U+71CE-71D0, U+71D2, U+71D4, U+71D9-71DA, U+71DC, U+71DF-71E0, U+71E6-71E8, U+71EA, U+71ED-71EE, U+71F4, U+71F6, U+71F9, U+71FB-71FC, U+71FF-7200, U+7207, U+720C-720D, U+7210, U+7216, U+721A-721E, U+7223, U+7228, U+722B, U+722D-722E, U+7230, U+7232, U+723A-723C, U+723E-7242, U+7246, U+724B, U+724D-724E, U+7252, U+7256, U+7258, U+725A, U+725C-725D, U+7260, U+7264-7266, U+726A, U+726C, U+726E-726F, U+7271, U+7273-7274, U+7278, U+727B, U+727D-727E, U+7281-7282, U+7284, U+7287, U+728A, U+728D, U+728F, U+7292, U+729B, U+729F-72A0, U+72A7, U+72AD-72AE, U+72B0-72B5, U+72B7-72B8, U+72BA-72BE, U+72C0-72C1, U+72C3, U+72C5-72C6, U+72C8, U+72CC-72CE, U+72D2, U+72D6, U+72DB, U+72DD-72DF, U+72E1, U+72E5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-57.woff2") format("woff2");+ unicode-range: U+700B, U+700D, U+7015, U+7018, U+701B, U+701D-701F, U+7023, U+7026-7028, U+702C, U+702E-7030, U+7035, U+7037, U+7039-703A, U+703C-703E, U+7044, U+7049-704B, U+704F, U+7051, U+7058, U+705A, U+705C-705E, U+7061, U+7064, U+7066, U+706C, U+707D, U+7080-7081, U+7085-7086, U+708A, U+708F, U+7091, U+7094-7095, U+7098-7099, U+709C-709D, U+709F, U+70A4, U+70A9-70AA, U+70AF-70B2, U+70B4-70B7, U+70BB, U+70C0, U+70C3, U+70C7, U+70CB, U+70CE-70CF, U+70D4, U+70D9-70DA, U+70DC-70DD, U+70E0, U+70E9, U+70EC, U+70F7, U+70FA, U+70FD, U+70FF, U+7104, U+7108-7109, U+710C, U+7110, U+7113-7114, U+7116-7118, U+711C, U+711E, U+7120, U+712E-712F, U+7131, U+713C, U+7142, U+7144-7147, U+7149-714B, U+7150, U+7152, U+7155-7156, U+7159-715A, U+715C, U+7161, U+7165-7166, U+7168-7169, U+716D, U+7173-7174, U+7176, U+7178, U+717A, U+717D, U+717F-7180, U+7184, U+7186-7188, U+7192, U+7198, U+719C, U+71A0, U+71A4-71A5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-58.woff2") format("woff2");+ unicode-range: U+6ED9, U+6EDB, U+6EDD, U+6EDF-6EE0, U+6EE2, U+6EE6, U+6EEA, U+6EEC, U+6EEE-6EEF, U+6EF2-6EF3, U+6EF7-6EFA, U+6EFE, U+6F01, U+6F03, U+6F08-6F09, U+6F15-6F16, U+6F19, U+6F22-6F25, U+6F28-6F2A, U+6F2C-6F2D, U+6F2F, U+6F32, U+6F36-6F38, U+6F3F, U+6F43-6F46, U+6F48, U+6F4B, U+6F4E-6F4F, U+6F51, U+6F54-6F57, U+6F59-6F5B, U+6F5E-6F5F, U+6F61, U+6F64-6F67, U+6F69-6F6C, U+6F6F-6F72, U+6F74-6F76, U+6F78-6F7E, U+6F80-6F83, U+6F86, U+6F89, U+6F8B-6F8D, U+6F90, U+6F92, U+6F94, U+6F97-6F98, U+6F9B, U+6FA3-6FA5, U+6FA7, U+6FAA, U+6FAF, U+6FB1, U+6FB4, U+6FB6, U+6FB9, U+6FC1-6FCB, U+6FD1-6FD3, U+6FD5, U+6FDB, U+6FDE-6FE1, U+6FE4, U+6FE9, U+6FEB-6FEC, U+6FEE-6FF1, U+6FFA, U+6FFE, U+7005-7006, U+7009;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-59.woff2") format("woff2");+ unicode-range: U+6DC3, U+6DC5-6DC6, U+6DC9, U+6DCC, U+6DCF, U+6DD2-6DD3, U+6DD6, U+6DD9-6DDE, U+6DE0, U+6DE4, U+6DE6, U+6DE8-6DEA, U+6DEC, U+6DEF-6DF0, U+6DF5-6DF6, U+6DF8, U+6DFA, U+6DFC, U+6E03-6E04, U+6E07-6E09, U+6E0B-6E0C, U+6E0E, U+6E11, U+6E13, U+6E15-6E16, U+6E19-6E1B, U+6E1E-6E1F, U+6E22, U+6E25-6E27, U+6E2B-6E2C, U+6E36-6E37, U+6E39-6E3A, U+6E3C-6E41, U+6E44-6E45, U+6E47, U+6E49-6E4B, U+6E4D-6E4E, U+6E51, U+6E53-6E55, U+6E5C-6E5F, U+6E61-6E63, U+6E65-6E67, U+6E6A-6E6B, U+6E6D-6E70, U+6E72-6E74, U+6E76-6E78, U+6E7C, U+6E80-6E82, U+6E86-6E87, U+6E89, U+6E8D, U+6E8F, U+6E96, U+6E98, U+6E9D-6E9F, U+6EA1, U+6EA5-6EA7, U+6EAB, U+6EB1-6EB2, U+6EB4, U+6EB7, U+6EBB-6EBD, U+6EBF-6EC6, U+6EC8-6EC9, U+6ECC, U+6ECF-6ED0, U+6ED3-6ED4, U+6ED7-6ED8;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-60.woff2") format("woff2");+ unicode-range: U+6CB1-6CB2, U+6CB4-6CB5, U+6CB7, U+6CBA, U+6CBC-6CBD, U+6CC1-6CC3, U+6CC5-6CC7, U+6CD0-6CD4, U+6CD6-6CD7, U+6CD9-6CDA, U+6CDE-6CE0, U+6CE4, U+6CE6, U+6CE9, U+6CEB-6CEF, U+6CF1-6CF2, U+6CF6-6CF7, U+6CFA, U+6CFE, U+6D03-6D05, U+6D07-6D08, U+6D0A, U+6D0C, U+6D0E-6D11, U+6D13-6D14, U+6D16, U+6D18-6D1A, U+6D1C, U+6D1F, U+6D22-6D23, U+6D26-6D29, U+6D2B, U+6D2E-6D30, U+6D33, U+6D35-6D36, U+6D38-6D3A, U+6D3C, U+6D3F, U+6D42-6D44, U+6D48-6D49, U+6D4D, U+6D50, U+6D52, U+6D54, U+6D56-6D58, U+6D5A-6D5C, U+6D5E, U+6D60-6D61, U+6D63-6D65, U+6D67, U+6D6C-6D6D, U+6D6F, U+6D75, U+6D7B-6D7D, U+6D87, U+6D8A, U+6D8E, U+6D90-6D9A, U+6D9C-6DA0, U+6DA2-6DA3, U+6DA7, U+6DAA-6DAC, U+6DAE, U+6DB3-6DB4, U+6DB6, U+6DB8, U+6DBC, U+6DBF, U+6DC2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-61.woff2") format("woff2");+ unicode-range: U+6B83-6B86, U+6B89, U+6B8D, U+6B91-6B93, U+6B95, U+6B97-6B98, U+6B9A-6B9B, U+6B9E, U+6BA1-6BA4, U+6BA9-6BAA, U+6BAD, U+6BAF-6BB0, U+6BB2-6BB3, U+6BBA-6BBD, U+6BC0, U+6BC2, U+6BC6, U+6BCA-6BCC, U+6BCE, U+6BD0-6BD1, U+6BD3, U+6BD6-6BD8, U+6BDA, U+6BE1, U+6BE6, U+6BEC, U+6BF1, U+6BF3-6BF5, U+6BF9, U+6BFD, U+6C05-6C08, U+6C0D, U+6C10, U+6C15-6C1A, U+6C21, U+6C23-6C26, U+6C29-6C2D, U+6C30-6C33, U+6C35-6C37, U+6C39-6C3A, U+6C3C-6C3F, U+6C46, U+6C4A-6C4C, U+6C4E-6C50, U+6C54, U+6C56, U+6C59-6C5C, U+6C5E, U+6C63, U+6C67-6C69, U+6C6B, U+6C6D, U+6C6F, U+6C72-6C74, U+6C78-6C7A, U+6C7C, U+6C84-6C87, U+6C8B-6C8C, U+6C8F, U+6C91, U+6C93-6C96, U+6C98, U+6C9A, U+6C9D, U+6CA2-6CA4, U+6CA8-6CA9, U+6CAC-6CAE;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-62.woff2") format("woff2");+ unicode-range: U+69FE-6A01, U+6A06, U+6A09, U+6A0B, U+6A11, U+6A13, U+6A17-6A19, U+6A1B, U+6A1E, U+6A23, U+6A28-6A29, U+6A2B, U+6A2F-6A30, U+6A35, U+6A38-6A40, U+6A46-6A48, U+6A4A-6A4B, U+6A4E, U+6A50, U+6A52, U+6A5B, U+6A5E, U+6A62, U+6A65-6A67, U+6A6B, U+6A79, U+6A7C, U+6A7E-6A7F, U+6A84, U+6A86, U+6A8E, U+6A90-6A91, U+6A94, U+6A97, U+6A9C, U+6A9E, U+6AA0, U+6AA2, U+6AA4, U+6AA9, U+6AAB, U+6AAE-6AB0, U+6AB2-6AB3, U+6AB5, U+6AB7-6AB8, U+6ABA-6ABB, U+6ABD, U+6ABF, U+6AC2-6AC4, U+6AC6, U+6AC8, U+6ACC, U+6ACE, U+6AD2-6AD3, U+6AD8-6ADC, U+6ADF-6AE0, U+6AE4-6AE5, U+6AE7-6AE8, U+6AFB, U+6B04-6B05, U+6B0D-6B13, U+6B16-6B17, U+6B19, U+6B24-6B25, U+6B2C, U+6B37-6B39, U+6B3B, U+6B3D, U+6B43, U+6B46, U+6B4E, U+6B50, U+6B53-6B54, U+6B58-6B59, U+6B5B, U+6B60, U+6B69, U+6B6D, U+6B6F-6B70, U+6B73-6B74, U+6B77-6B7A, U+6B80-6B82;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-63.woff2") format("woff2");+ unicode-range: U+68D3, U+68D7, U+68DD, U+68DF, U+68E1, U+68E3-68E4, U+68E6-68ED, U+68EF-68F0, U+68F2, U+68F4, U+68F6-68F7, U+68F9, U+68FB-68FD, U+68FF-6902, U+6906-6908, U+690B, U+6910, U+691A-691C, U+691F-6920, U+6924-6925, U+692A, U+692D, U+6934, U+6939, U+693C-6945, U+694A-694B, U+6952-6954, U+6957, U+6959, U+695B, U+695D, U+695F, U+6962-6964, U+6966, U+6968-696C, U+696E-696F, U+6971, U+6973-6974, U+6978-6979, U+697D, U+697F-6980, U+6985, U+6987-698A, U+698D-698E, U+6994-6999, U+699B, U+69A3-69A4, U+69A6-69A7, U+69AB, U+69AD-69AE, U+69B1, U+69B7, U+69BB-69BC, U+69C1, U+69C3-69C5, U+69C7, U+69CA-69CE, U+69D0-69D1, U+69D3-69D4, U+69D7-69DA, U+69E0, U+69E4, U+69E6, U+69EC-69ED, U+69F1-69F3, U+69F8, U+69FA-69FC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-64.woff2") format("woff2");+ unicode-range: U+678B-678D, U+678F, U+6792-6793, U+6796, U+6798, U+679E-67A1, U+67A5, U+67A7-67A9, U+67AC-67AD, U+67B0-67B1, U+67B3, U+67B5, U+67B7, U+67B9, U+67BB-67BC, U+67C0-67C1, U+67C3, U+67C5-67CA, U+67D1-67D2, U+67D7-67D9, U+67DD-67DF, U+67E2-67E4, U+67E6-67E9, U+67F0, U+67F5, U+67F7-67F8, U+67FA-67FB, U+67FD-67FE, U+6800-6801, U+6803-6804, U+6806, U+6809-680A, U+680C, U+680E, U+6812, U+681D-681F, U+6822, U+6824-6829, U+682B-682D, U+6831-6835, U+683B, U+683E, U+6840-6841, U+6844-6845, U+6849, U+684E, U+6853, U+6855-6856, U+685C-685D, U+685F-6862, U+6864, U+6866-6868, U+686B, U+686F, U+6872, U+6874, U+6877, U+687F, U+6883, U+6886, U+688F, U+689B, U+689F-68A0, U+68A2-68A3, U+68B1, U+68B6, U+68B9-68BA, U+68BC-68BF, U+68C1-68C4, U+68C6, U+68C8, U+68CA, U+68CC, U+68D0-68D1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-65.woff2") format("woff2");+ unicode-range: U+6631, U+6633-6634, U+6636, U+663A-663B, U+663D, U+6641, U+6644-6645, U+6649, U+664C, U+664F, U+6654, U+6659, U+665B, U+665D-665E, U+6660-6667, U+6669, U+666B-666C, U+6671, U+6673, U+6677-6679, U+667C, U+6680-6681, U+6684-6685, U+6688-6689, U+668B-668E, U+6690, U+6692, U+6695, U+6698, U+669A, U+669D, U+669F-66A0, U+66A2-66A3, U+66A6, U+66AA-66AB, U+66B1-66B2, U+66B5, U+66B8-66B9, U+66BB, U+66BE, U+66C1, U+66C6-66C9, U+66CC, U+66D5-66D8, U+66DA-66DC, U+66DE-66E2, U+66E8-66EA, U+66EC, U+66F1, U+66F3, U+66F7, U+66FA, U+66FD, U+6702, U+6705, U+670A, U+670F-6710, U+6713, U+6715, U+6719, U+6722-6723, U+6725-6727, U+6729, U+672D-672E, U+6732-6733, U+6736, U+6739, U+673B, U+673F, U+6744, U+6748, U+674C-674D, U+6753, U+6755, U+6762, U+6767, U+6769-676C, U+676E, U+6772-6773, U+6775, U+6777, U+677A-677D, U+6782-6783, U+6787, U+678A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-66.woff2") format("woff2");+ unicode-range: U+64F1-64F2, U+64F4, U+64F7-64F8, U+64FA, U+64FC, U+64FE-64FF, U+6503, U+6509, U+650F, U+6514, U+6518, U+651C-651E, U+6522-6525, U+652A-652C, U+652E, U+6530-6532, U+6534-6535, U+6537-6538, U+653A, U+653C-653D, U+6542, U+6549-654B, U+654D-654E, U+6553-6555, U+6557-6558, U+655D, U+6564, U+6569, U+656B, U+656D-656F, U+6571, U+6573, U+6575-6576, U+6578-657E, U+6581-6583, U+6585-6586, U+6589, U+658E-658F, U+6592-6593, U+6595-6596, U+659B, U+659D, U+659F-65A1, U+65A3, U+65AB-65AC, U+65B2, U+65B6-65B7, U+65BA-65BB, U+65BE-65C0, U+65C2-65C4, U+65C6-65C8, U+65CC, U+65CE, U+65D0, U+65D2-65D3, U+65D6, U+65DB, U+65DD, U+65E1, U+65E3, U+65EE-65F0, U+65F3-65F5, U+65F8, U+65FB-65FC, U+65FE-6600, U+6603, U+6607, U+6609, U+660B, U+6610-6611, U+6619-661A, U+661C-661E, U+6621, U+6624, U+6626, U+662A-662C, U+662E, U+6630;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-67.woff2") format("woff2");+ unicode-range: U+63B8-63BC, U+63BE, U+63C0, U+63C3-63C4, U+63C6, U+63C8, U+63CD-63CE, U+63D1, U+63D6, U+63DA-63DB, U+63DE, U+63E0, U+63E3, U+63E9-63EA, U+63EE, U+63F2, U+63F5-63FA, U+63FC, U+63FE-6400, U+6406, U+640B-640D, U+6410, U+6414, U+6416-6417, U+641B, U+6420-6423, U+6425-6428, U+642A, U+6431-6432, U+6434-6437, U+643D-6442, U+6445, U+6448, U+6450-6452, U+645B-645F, U+6462, U+6465, U+6468, U+646D, U+646F-6471, U+6473, U+6477, U+6479-647D, U+6482-6485, U+6487-6488, U+648C, U+6490, U+6493, U+6496-649A, U+649D, U+64A0, U+64A5, U+64AB-64AC, U+64B1-64B7, U+64B9-64BB, U+64BE-64C1, U+64C4, U+64C7, U+64C9-64CB, U+64D0, U+64D4, U+64D7-64D8, U+64DA, U+64DE, U+64E0-64E2, U+64E4, U+64E9, U+64EC, U+64F0;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-68.woff2") format("woff2");+ unicode-range: U+622C, U+622E-6230, U+6232, U+6238, U+623B, U+623D-623E, U+6243, U+6246, U+6248-6249, U+624C, U+6255, U+6259, U+625E, U+6260-6261, U+6265-6266, U+626A, U+6271, U+627A, U+627C-627D, U+6283, U+6286, U+6289, U+628E, U+6294, U+629C, U+629E-629F, U+62A1, U+62A8, U+62BA-62BB, U+62BF, U+62C2, U+62C4, U+62C8, U+62CA-62CB, U+62CF, U+62D1, U+62D7, U+62D9-62DA, U+62DD, U+62E0-62E1, U+62E3-62E4, U+62E7, U+62EB, U+62EE, U+62F0, U+62F4-62F6, U+6308, U+630A-630E, U+6310, U+6312-6313, U+6317, U+6319, U+631B, U+631D-631F, U+6322, U+6326, U+6329, U+6331-6332, U+6334-6337, U+6339, U+633B-633C, U+633E-6340, U+6343, U+6347, U+634B-634E, U+6354, U+635C-635D, U+6368-6369, U+636D, U+636F-6372, U+6376, U+637A-637B, U+637D, U+6382-6383, U+6387, U+638A-638B, U+638D-638E, U+6391, U+6393-6397, U+6399, U+639B, U+639E-639F, U+63A1, U+63A3-63A4, U+63AC-63AE, U+63B1-63B5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-69.woff2") format("woff2");+ unicode-range: U+60ED-60EE, U+60F0-60F1, U+60F4, U+60F6, U+60FA, U+6100, U+6106, U+610D-610E, U+6112, U+6114-6115, U+6119, U+611C, U+6120, U+6122-6123, U+6126, U+6128-6130, U+6136-6137, U+613A, U+613D-613E, U+6144, U+6146-6147, U+614A-614B, U+6151, U+6153, U+6158, U+615A, U+615C-615D, U+615F, U+6161, U+6163-6165, U+616B-616C, U+616E, U+6171, U+6173-6177, U+617E, U+6182, U+6187, U+618A, U+618D-618E, U+6190-6191, U+6194, U+6199-619A, U+619C, U+619F, U+61A1, U+61A3-61A4, U+61A7-61A9, U+61AB-61AD, U+61B2-61B3, U+61B5-61B7, U+61BA-61BB, U+61BF, U+61C3-61C4, U+61C6-61C7, U+61C9-61CB, U+61D0-61D1, U+61D3-61D4, U+61D7, U+61DA, U+61DF-61E1, U+61E6, U+61EE, U+61F0, U+61F2, U+61F6-61F8, U+61FA, U+61FC-61FE, U+6200, U+6206-6207, U+6209, U+620B, U+620D-620E, U+6213-6215, U+6217, U+6219, U+621B-6223, U+6225-6226;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-70.woff2") format("woff2");+ unicode-range: U+5FC4, U+5FC9, U+5FCB, U+5FCE-5FD6, U+5FDA-5FDE, U+5FE1-5FE2, U+5FE4-5FE5, U+5FEA, U+5FED-5FEE, U+5FF1-5FF3, U+5FF6, U+5FF8, U+5FFB, U+5FFE-5FFF, U+6002-6006, U+600A, U+600D, U+600F, U+6014, U+6019, U+601B, U+6020, U+6023, U+6026, U+6029, U+602B, U+602E-602F, U+6031, U+6033, U+6035, U+6039, U+603F, U+6041-6043, U+6046, U+604F, U+6053-6054, U+6058-605B, U+605D-605E, U+6060, U+6063, U+6065, U+6067, U+606A-606C, U+6075, U+6078-6079, U+607B, U+607D, U+607F, U+6083, U+6085-6087, U+608A, U+608C, U+608E-608F, U+6092-6093, U+6095-6097, U+609B-609D, U+60A2, U+60A7, U+60A9-60AB, U+60AD, U+60AF-60B1, U+60B3-60B6, U+60B8, U+60BB, U+60BD-60BE, U+60C0-60C3, U+60C6-60C9, U+60CB, U+60CE, U+60D3-60D4, U+60D7-60DB, U+60DD, U+60E1-60E4, U+60E6, U+60EA, U+60EC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-71.woff2") format("woff2");+ unicode-range: U+5E98, U+5E9B, U+5E9D, U+5EA0-5EA5, U+5EA8, U+5EAB, U+5EAF, U+5EB3, U+5EB5-5EB6, U+5EB9, U+5EBE, U+5EC1-5EC3, U+5EC6, U+5EC8, U+5ECB-5ECC, U+5ED1-5ED2, U+5ED4, U+5ED9-5EDB, U+5EDD, U+5EDF-5EE0, U+5EE2-5EE3, U+5EE8, U+5EEA, U+5EEC, U+5EEF-5EF0, U+5EF3-5EF4, U+5EF8, U+5EFB-5EFC, U+5EFE-5EFF, U+5F01, U+5F07, U+5F0B-5F0E, U+5F10-5F12, U+5F14, U+5F1A, U+5F22, U+5F28-5F29, U+5F2C-5F2D, U+5F35-5F36, U+5F38, U+5F3B-5F43, U+5F45-5F4A, U+5F4C-5F4E, U+5F50, U+5F54, U+5F56-5F59, U+5F5B-5F5F, U+5F61, U+5F63, U+5F65, U+5F67-5F68, U+5F6B, U+5F6E-5F6F, U+5F72-5F78, U+5F7A, U+5F7E-5F7F, U+5F82-5F83, U+5F87, U+5F89-5F8A, U+5F8D, U+5F91, U+5F93, U+5F95, U+5F98-5F99, U+5F9C, U+5F9E, U+5FA0, U+5FA6-5FA9, U+5FAC-5FAD, U+5FAF, U+5FB3-5FB5, U+5FB9, U+5FBC;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-72.woff2") format("woff2");+ unicode-range: U+5D26-5D27, U+5D2E-5D34, U+5D3C-5D3E, U+5D41-5D44, U+5D46-5D48, U+5D4A-5D4B, U+5D4E, U+5D50, U+5D52, U+5D55-5D58, U+5D5A-5D5D, U+5D68-5D69, U+5D6B-5D6C, U+5D6F, U+5D74, U+5D7F, U+5D82-5D89, U+5D8B-5D8C, U+5D8F, U+5D92-5D93, U+5D99, U+5D9D, U+5DB2, U+5DB6-5DB7, U+5DBA, U+5DBC-5DBD, U+5DC2-5DC3, U+5DC6-5DC7, U+5DC9, U+5DCC, U+5DD2, U+5DD4, U+5DD6-5DD8, U+5DDB-5DDC, U+5DE3, U+5DED, U+5DEF, U+5DF3, U+5DF6, U+5DFA-5DFD, U+5DFF-5E00, U+5E07, U+5E0F, U+5E11, U+5E13-5E14, U+5E19-5E1B, U+5E22, U+5E25, U+5E28, U+5E2A, U+5E2F-5E31, U+5E33-5E34, U+5E36, U+5E39-5E3C, U+5E3E, U+5E40, U+5E44, U+5E46-5E48, U+5E4C, U+5E4F, U+5E53-5E54, U+5E57, U+5E59, U+5E5B, U+5E5E-5E5F, U+5E61, U+5E63, U+5E6A-5E6B, U+5E75, U+5E77, U+5E79-5E7A, U+5E7E, U+5E80-5E81, U+5E83, U+5E85, U+5E87, U+5E8B, U+5E91-5E92, U+5E96;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-73.woff2") format("woff2");+ unicode-range: U+5BEC, U+5BEE-5BF0, U+5BF2-5BF3, U+5BF5-5BF6, U+5BFE, U+5C02-5C03, U+5C05, U+5C07-5C09, U+5C0B-5C0C, U+5C0E, U+5C10, U+5C12-5C13, U+5C15, U+5C17, U+5C19, U+5C1B-5C1C, U+5C1E-5C1F, U+5C22, U+5C25, U+5C28, U+5C2A-5C2B, U+5C2F-5C30, U+5C37, U+5C3B, U+5C43-5C44, U+5C46-5C47, U+5C4D, U+5C50, U+5C59, U+5C5B-5C5C, U+5C62-5C64, U+5C66, U+5C6C, U+5C6E, U+5C74, U+5C78-5C7E, U+5C80, U+5C83-5C84, U+5C88, U+5C8B-5C8D, U+5C91, U+5C94-5C96, U+5C98-5C99, U+5C9C, U+5C9E, U+5CA1-5CA3, U+5CAB-5CAC, U+5CB1, U+5CB5, U+5CB7, U+5CBA, U+5CBD-5CBF, U+5CC1, U+5CC3-5CC4, U+5CC7, U+5CCB, U+5CD2, U+5CD8-5CD9, U+5CDF-5CE0, U+5CE3-5CE6, U+5CE8-5CEA, U+5CED, U+5CEF, U+5CF3-5CF4, U+5CF6, U+5CF8, U+5CFD, U+5D00-5D04, U+5D06, U+5D08, U+5D0B-5D0D, U+5D0F-5D13, U+5D15, U+5D17-5D1A, U+5D1D-5D22, U+5D24-5D25;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-74.woff2") format("woff2");+ unicode-range: U+5AA0, U+5AA3-5AA4, U+5AAA, U+5AAE-5AAF, U+5AB1-5AB2, U+5AB4-5AB5, U+5AB7-5ABA, U+5ABD-5ABF, U+5AC3-5AC4, U+5AC6-5AC8, U+5ACA-5ACB, U+5ACD, U+5ACF-5AD2, U+5AD4, U+5AD8-5ADA, U+5ADC, U+5ADF-5AE2, U+5AE4, U+5AE6, U+5AE8, U+5AEA-5AED, U+5AF0-5AF3, U+5AF5, U+5AF9-5AFB, U+5AFD, U+5B01, U+5B05, U+5B08, U+5B0B-5B0C, U+5B11, U+5B16-5B17, U+5B1B, U+5B21-5B22, U+5B24, U+5B27-5B2E, U+5B30, U+5B32, U+5B34, U+5B36-5B38, U+5B3E-5B40, U+5B43, U+5B45, U+5B4A-5B4B, U+5B51-5B53, U+5B56, U+5B5A-5B5B, U+5B62, U+5B65, U+5B67, U+5B6A-5B6E, U+5B70-5B71, U+5B73, U+5B7A-5B7B, U+5B7F-5B80, U+5B84, U+5B8D, U+5B91, U+5B93-5B95, U+5B9F, U+5BA5-5BA6, U+5BAC, U+5BAE, U+5BB8, U+5BC0, U+5BC3, U+5BCB, U+5BD0-5BD1, U+5BD4-5BD8, U+5BDA-5BDC, U+5BE2, U+5BE4-5BE5, U+5BE7, U+5BE9, U+5BEB;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-75.woff2") format("woff2");+ unicode-range: U+596A, U+596C-596E, U+5977, U+597B-597C, U+5981, U+598F, U+5997-5998, U+599A, U+599C-599D, U+59A0-59A1, U+59A3-59A4, U+59A7, U+59AA-59AD, U+59AF, U+59B2-59B3, U+59B5-59B6, U+59B8, U+59BA, U+59BD-59BE, U+59C0-59C1, U+59C3-59C4, U+59C7-59CA, U+59CC-59CD, U+59CF, U+59D2, U+59D5-59D6, U+59D8-59D9, U+59DB, U+59DD-59E0, U+59E2-59E7, U+59E9-59EB, U+59EE, U+59F1, U+59F3, U+59F5, U+59F7-59F9, U+59FD, U+5A06, U+5A08-5A0A, U+5A0C-5A0D, U+5A11-5A13, U+5A15-5A16, U+5A1A-5A1B, U+5A21-5A23, U+5A2D-5A2F, U+5A32, U+5A38, U+5A3C, U+5A3E-5A45, U+5A47, U+5A4A, U+5A4C-5A4D, U+5A4F-5A51, U+5A53, U+5A55-5A57, U+5A5E, U+5A60, U+5A62, U+5A65-5A67, U+5A6A, U+5A6C-5A6D, U+5A72-5A73, U+5A75-5A76, U+5A79-5A7C, U+5A81-5A84, U+5A8C, U+5A8E, U+5A93, U+5A96-5A97, U+5A9C, U+5A9E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-76.woff2") format("woff2");+ unicode-range: U+5820, U+5822-5823, U+5825-5826, U+582C, U+582F, U+5831, U+583A, U+583D, U+583F-5842, U+5844-5846, U+5848, U+584A, U+584D, U+5852, U+5857, U+5859-585A, U+585C-585D, U+5862, U+5868-5869, U+586C-586D, U+586F-5873, U+5875, U+5879, U+587D-587E, U+5880-5881, U+5888-588A, U+588D, U+5892, U+5896-5898, U+589A, U+589C-589D, U+58A0-58A1, U+58A3, U+58A6, U+58A9, U+58AB-58AE, U+58B0, U+58B3, U+58BB-58BF, U+58C2-58C3, U+58C5-58C8, U+58CA, U+58CC, U+58CE, U+58D1-58D3, U+58D5, U+58D8-58D9, U+58DE-58DF, U+58E2, U+58E9, U+58EC, U+58EF, U+58F1-58F2, U+58F5, U+58F7-58F8, U+58FA, U+58FD, U+5900, U+5902, U+5906, U+5908-590C, U+590E, U+5910, U+5914, U+5919, U+591B, U+591D-591E, U+5920, U+5922-5925, U+5928, U+592C-592D, U+592F, U+5932, U+5936, U+593C, U+593E, U+5940-5942, U+5944, U+594C-594D, U+5950, U+5953, U+5958, U+595A, U+5961, U+5966-5968;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-77.woff2") format("woff2");+ unicode-range: U+56F9, U+56FC, U+56FF-5700, U+5703-5704, U+5709-570A, U+570C-570D, U+570F, U+5712-5713, U+5718-5719, U+571C, U+571E, U+5725, U+5727, U+5729-572A, U+572C, U+572E-572F, U+5734-5735, U+5739, U+573B, U+5741, U+5743, U+5745, U+5749, U+574C-574D, U+575C, U+5763, U+5768-5769, U+576B, U+576D-576E, U+5770, U+5773, U+5775, U+5777, U+577B-577C, U+5785-5786, U+5788, U+578C, U+578E-578F, U+5793-5795, U+5799-57A1, U+57A3-57A4, U+57A6-57AA, U+57AC-57AD, U+57AF-57B2, U+57B4-57B6, U+57B8-57B9, U+57BD-57BF, U+57C2, U+57C4-57C8, U+57CC-57CD, U+57CF, U+57D2, U+57D5-57DE, U+57E1-57E2, U+57E4-57E5, U+57E7, U+57EB, U+57ED, U+57EF, U+57F4-57F8, U+57FC-57FD, U+5800-5801, U+5803, U+5805, U+5807, U+5809, U+580B-580E, U+5811, U+5814, U+5819, U+581B-581F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-78.woff2") format("woff2");+ unicode-range: U+55F5-55F7, U+55FB, U+55FE, U+5600-5601, U+5605-5606, U+5608, U+560C-560D, U+560F, U+5614, U+5616-5617, U+561A, U+561C, U+561E, U+5621-5625, U+5627, U+5629, U+562B-5630, U+5636, U+5638-563A, U+563C, U+5640-5642, U+5649, U+564C-5650, U+5653-5655, U+5657-565B, U+5660, U+5663-5664, U+5666, U+566B, U+566F-5671, U+5673-567C, U+567E, U+5684-5687, U+568C, U+568E-5693, U+5695, U+5697, U+569B-569C, U+569E-569F, U+56A1-56A2, U+56A4-56A9, U+56AC-56AF, U+56B1, U+56B4, U+56B6-56B8, U+56BF, U+56C1-56C3, U+56C9, U+56CD, U+56D1, U+56D4, U+56D6-56D9, U+56DD, U+56DF, U+56E1, U+56E3-56E6, U+56E8-56EC, U+56EE-56EF, U+56F1-56F3, U+56F5, U+56F7-56F8;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-79.woff2") format("woff2");+ unicode-range: U+550F, U+5511-5514, U+5516-5517, U+5519, U+551B, U+551D-551E, U+5520, U+5522-5523, U+5526-5527, U+552A-552C, U+5530, U+5532-5535, U+5537-5538, U+553B-5541, U+5543-5544, U+5547-5549, U+554B, U+554D, U+5550, U+5553, U+5555-5558, U+555B-555F, U+5567-5569, U+556B-5572, U+5574-5577, U+557B-557C, U+557E-557F, U+5581, U+5583, U+5585-5586, U+5588, U+558B-558C, U+558E-5591, U+5593, U+5599-559A, U+559F, U+55A5-55A6, U+55A8-55AC, U+55AE, U+55B0-55B3, U+55B6, U+55B9-55BA, U+55BC-55BE, U+55C4, U+55C6-55C7, U+55C9, U+55CC-55D2, U+55D4-55DB, U+55DD-55DF, U+55E1, U+55E3-55E6, U+55EA-55EE, U+55F0-55F3;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-80.woff2") format("woff2");+ unicode-range: U+53E7-53E9, U+53F1, U+53F4-53F5, U+53FA-5400, U+5402, U+5405-5407, U+540B, U+540F, U+5412, U+5414, U+5416, U+5418-541A, U+541D, U+5420-5423, U+5425, U+5429-542A, U+542D-542E, U+5431-5433, U+5436, U+543D, U+543F, U+5442-5443, U+5449, U+544B-544C, U+544E, U+5451-5454, U+5456, U+5459, U+545B-545C, U+5461, U+5463-5464, U+546A-5472, U+5474, U+5476-5478, U+547A, U+547E-5484, U+5486, U+548A, U+548D-548E, U+5490-5491, U+5494, U+5497-5499, U+549B, U+549D, U+54A1-54A7, U+54A9, U+54AB, U+54AD, U+54B4-54B5, U+54B9, U+54BB, U+54BE-54BF, U+54C2-54C3, U+54C9-54CC, U+54CF-54D0, U+54D3, U+54D5-54D6, U+54D9-54DA, U+54DC-54DE, U+54E2, U+54E7, U+54F3-54F4, U+54F8-54F9, U+54FD-54FF, U+5501, U+5504-5506, U+550C-550E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-81.woff2") format("woff2");+ unicode-range: U+5289, U+528B, U+528D, U+528F, U+5291-5293, U+529A, U+52A2, U+52A6-52A7, U+52AC-52AD, U+52AF, U+52B4-52B5, U+52B9, U+52BB-52BC, U+52BE, U+52C1, U+52C5, U+52CA, U+52CD, U+52D0, U+52D6-52D7, U+52D9, U+52DB, U+52DD-52DE, U+52E0, U+52E2-52E3, U+52E5, U+52E7-52F0, U+52F2-52F3, U+52F5-52F9, U+52FB-52FC, U+5302, U+5304, U+530B, U+530D, U+530F-5310, U+5315, U+531A, U+531C-531D, U+5321, U+5323, U+5326, U+532E-5331, U+5338, U+533C-533E, U+5344-5345, U+534B-534D, U+5350, U+5354, U+5358, U+535D-535F, U+5363, U+5368-5369, U+536C, U+536E-536F, U+5372, U+5379-537B, U+537D, U+538D-538E, U+5390, U+5393-5394, U+5396, U+539B-539D, U+53A0-53A1, U+53A3-53A5, U+53A9, U+53AD-53AE, U+53B0, U+53B2-53B3, U+53B5-53B8, U+53BC, U+53BE, U+53C1, U+53C3-53C7, U+53CE-53CF, U+53D2-53D3, U+53D5, U+53DA, U+53DE-53DF, U+53E1-53E2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-82.woff2") format("woff2");+ unicode-range: U+5104, U+5106-5107, U+5109-510B, U+510D, U+510F-5110, U+5113, U+5115, U+5117-5118, U+511A-511C, U+511E-511F, U+5121, U+5128, U+512B-512D, U+5131-5135, U+5137-5139, U+513C, U+5140, U+5142, U+5147, U+514C, U+514E-5150, U+5155-5158, U+5162, U+5169, U+5172, U+517F, U+5181-5184, U+5186-5187, U+518B, U+518F, U+5191, U+5195-5197, U+519A, U+51A2-51A3, U+51A6-51AB, U+51AD-51AE, U+51B1, U+51B4, U+51BC-51BD, U+51BF, U+51C3, U+51C7-51C8, U+51CA-51CB, U+51CD-51CE, U+51D4, U+51D6, U+51DB-51DC, U+51E6, U+51E8-51EB, U+51F1, U+51F5, U+51FC, U+51FF, U+5202, U+5205, U+5208, U+520B, U+520D-520E, U+5215-5216, U+5228, U+522A, U+522C-522D, U+5233, U+523C-523D, U+523F-5240, U+5245, U+5247, U+5249, U+524B-524C, U+524E, U+5250, U+525B-525F, U+5261, U+5263-5264, U+5270, U+5273, U+5275, U+5277, U+527D, U+527F, U+5281-5285, U+5287;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-83.woff2") format("woff2");+ unicode-range: U+4FD1, U+4FD3, U+4FDA-4FDC, U+4FDF-4FE0, U+4FE2-4FE4, U+4FE6, U+4FE8, U+4FEB-4FED, U+4FF3, U+4FF5-4FF6, U+4FF8, U+4FFE, U+5001, U+5005-5006, U+5009, U+500C, U+500F, U+5013-5018, U+501B-501E, U+5022-5025, U+5027-5028, U+502B-502E, U+5030, U+5033-5034, U+5036-5039, U+503B, U+5041-5043, U+5045-5046, U+5048-504A, U+504C-504E, U+5051, U+5053, U+5055-5057, U+505B, U+505E, U+5060, U+5062-5063, U+5067, U+506A, U+506C, U+5070-5072, U+5074-5075, U+5078, U+507B, U+507D-507E, U+5080, U+5088-5089, U+5091-5092, U+5095, U+5097-509E, U+50A2-50A3, U+50A5-50A7, U+50A9, U+50AD, U+50B3, U+50B5, U+50B7, U+50BA, U+50BE, U+50C4-50C5, U+50C7, U+50CA, U+50CD, U+50D1, U+50D5-50D6, U+50DA, U+50DE, U+50E5-50E6, U+50EC-50EE, U+50F0-50F1, U+50F3, U+50F9-50FB, U+50FE-5102;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-84.woff2") format("woff2");+ unicode-range: U+4EA3, U+4EA5, U+4EB0-4EB1, U+4EB3-4EB6, U+4EB8-4EB9, U+4EBB-4EBE, U+4EC2-4EC4, U+4EC8-4EC9, U+4ECC, U+4ECF-4ED0, U+4ED2, U+4EDA-4EDB, U+4EDD-4EE1, U+4EE6-4EE9, U+4EEB, U+4EEE-4EEF, U+4EF3-4EF5, U+4EF8-4EFA, U+4EFC, U+4F00, U+4F03-4F05, U+4F08-4F09, U+4F0B, U+4F0E, U+4F12-4F13, U+4F15, U+4F1B, U+4F1D, U+4F21-4F22, U+4F25, U+4F27-4F29, U+4F2B-4F2E, U+4F31-4F33, U+4F36-4F37, U+4F39, U+4F3E, U+4F40-4F41, U+4F43, U+4F47-4F49, U+4F54, U+4F57-4F58, U+4F5D-4F5E, U+4F61-4F62, U+4F64-4F65, U+4F67, U+4F6A, U+4F6E-4F6F, U+4F72, U+4F74-4F7E, U+4F80-4F82, U+4F84, U+4F89-4F8A, U+4F8E-4F98, U+4F9E, U+4FA1, U+4FA5, U+4FA9-4FAA, U+4FAC, U+4FB3, U+4FB6-4FB8, U+4FBD, U+4FC2, U+4FC5-4FC6, U+4FCD-4FCE, U+4FD0;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-85.woff2") format("woff2");+ unicode-range: U+3129, U+3220-3229, U+3231, U+32A3, U+338E-338F, U+339C-339E, U+33C4, U+33D1-33D2, U+33D5, U+3434, U+34DC, U+34EE, U+353E, U+355D, U+3566, U+3575, U+3592, U+35A0-35A1, U+35AD, U+35CE, U+36A2, U+36AB, U+38A8, U+3DAB, U+3DE7, U+3DEB, U+3E1A, U+3F1B, U+3F6D, U+4495, U+4723, U+48FA, U+4CA3, U+4E02, U+4E04-4E06, U+4E0C, U+4E0F, U+4E15, U+4E17, U+4E1F-4E21, U+4E26, U+4E29, U+4E2C, U+4E2F, U+4E31, U+4E35, U+4E37, U+4E3C, U+4E3F-4E42, U+4E44, U+4E46-4E47, U+4E57, U+4E5A-4E5C, U+4E64-4E65, U+4E67, U+4E69, U+4E6D, U+4E78, U+4E7F-4E82, U+4E85, U+4E87, U+4E8A, U+4E8D, U+4E93, U+4E96, U+4E98-4E99, U+4E9C, U+4E9E-4EA0, U+4EA2;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-86.woff2") format("woff2");+ unicode-range: U+2EBB, U+3003, U+3005-3007, U+3012-3013, U+301D-301E, U+3021, U+3023-3024, U+3041, U+3043, U+3045, U+3047, U+3049, U+3056, U+3058, U+305C, U+305E, U+3062, U+306C, U+3074, U+3077, U+307A, U+307C-307D, U+3080, U+308E, U+3090-3091, U+3099-309B, U+309D-309E, U+30A5, U+30BC, U+30BE, U+30C2, U+30C5, U+30CC, U+30D8, U+30E2, U+30E8, U+30EE, U+30F0-30F2, U+30F4-30F6, U+30FD-30FE, U+3105-3126, U+3128;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-87.woff2") format("woff2");+ unicode-range: U+2713, U+2715, U+275B, U+275D-275E, U+2780-2782, U+278A-278C, U+278E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-88.woff2") format("woff2");+ unicode-range: U+2550-2551, U+2554, U+2557, U+255A-255B, U+255D, U+255F-2560, U+2562-2563, U+2565-2567, U+2569-256A, U+256C-2572, U+2581-258F, U+2593-2595, U+25A1, U+25B3, U+25BD, U+25CA-25CB, U+25E2-25E5, U+2609, U+2640, U+2642;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-89.woff2") format("woff2");+ unicode-range: U+2465-2469, U+2474-249B, U+2500-2509, U+250B-2526, U+2528-2534, U+2536-2537, U+253B-2548, U+254A-254B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-90.woff2") format("woff2");+ unicode-range: U+207F-2083, U+208D-208E, U+2105, U+2109, U+2117, U+2120-2121, U+2126, U+2196-2199, U+21C4, U+2202, U+2206, U+2208, U+220F, U+2211, U+221D-2220, U+2223, U+2225, U+2227-222B, U+222E, U+2234-2237, U+223C-223D, U+2248, U+224C, U+2252, U+2260-2261, U+2266-2267, U+226E-226F, U+2295, U+2299, U+22A5, U+22BF, U+2312;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-91.woff2") format("woff2");+ unicode-range: U+1DC4-1DC5, U+2070, U+2074-2078, U+207A-207B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-97.woff2") format("woff2");+ unicode-range: U+02D8-02D9, U+0302, U+0305-0307, U+030A-030C, U+0324-0325, U+0327-0328, U+032C, U+0332, U+0334, U+0339, U+033C-033D, U+0348, U+035C, U+0361;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-100.woff2") format("woff2");+ unicode-range: U+221A, U+2264-2265, U+2464, U+25A0, U+3008-3009, U+4E10, U+512A, U+5152, U+5201, U+5241, U+5340, U+5352, U+549A, U+54B2, U+54C6, U+54D7, U+54E1, U+5509, U+55C5, U+5618, U+5716, U+576F, U+5784, U+57A2, U+589F, U+5A20, U+5A25, U+5A29, U+5A34, U+5A7F, U+5AD6, U+5B09, U+5B5C, U+5BC7, U+5BE6, U+5C27, U+5D2D, U+5DCD, U+5F1B, U+5F37, U+604D, U+6055, U+6073, U+60EB, U+61FF, U+62CE, U+62ED, U+6345, U+6390, U+63B0, U+63B7, U+64AE, U+64C2, U+64D2, U+6556, U+663C, U+667E, U+66D9, U+66F8, U+6756, U+6789, U+689D, U+68F1, U+695E, U+6975, U+6A1F, U+6B0A, U+6B61, U+6B87, U+6C5D, U+6C7E, U+6C92, U+6D31, U+6DF9, U+6E0D, U+6E2D, U+6F31, U+6F3E, U+70B3, U+70BD, U+70CA, U+70E8, U+725F, U+733F, U+7396, U+739F, U+7459, U+74A7, U+75A1, U+75F0, U+76CF, U+76D4, U+7729, U+77AA, U+77B0, U+77E3, U+780C, U+78D5, U+7941, U+7977, U+797A, U+79C3, U+7A20, U+7A92, U+7B71, U+7BF1, U+7C9F, U+7EB6, U+7ECA, U+7EF7, U+7F07, U+7F09, U+7F15, U+7F81, U+7FB9, U+8038, U+8098, U+80B4, U+8110, U+814B-814C, U+816E, U+818A, U+8205, U+8235, U+828B, U+82A5, U+82B7, U+82D4, U+82DB, U+82DF, U+8317, U+8338, U+8385-8386, U+83C1, U+83CF, U+8537, U+853B, U+854A, U+8715, U+8783, U+892A, U+8A71, U+8BB3, U+8D2E, U+8D58, U+8DBE, U+8F67, U+8FAB, U+8FC4, U+8FE6, U+9023, U+9084, U+9091, U+916A, U+91C9, U+91DC, U+94B3, U+9502, U+9523, U+9551, U+956F, U+960E, U+962A, U+962E, U+9647, U+96F3, U+9739, U+97A0, U+97ED, U+983B, U+985E, U+988A, U+99AC, U+9A6F, U+9A87, U+9A8B, U+9AB7, U+9ABC, U+9AC5, U+9E25, U+FF06, U+FF14-FF16;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-101.woff2") format("woff2");+ unicode-range: U+25C7, U+25CE, U+3008-3009, U+3016-3017, U+4E4D, U+4E53, U+4F5A, U+4F70, U+4FAE, U+4FD8, U+4FFA, U+5011, U+501A, U+51C4, U+5225, U+547B, U+5495, U+54E8, U+54EE, U+5594, U+55D3, U+55DC, U+55FD, U+560E, U+565C, U+5662, U+5669, U+566C, U+56BC, U+5742, U+5824, U+5834, U+598A, U+5992, U+59A9, U+5A04, U+5AC9, U+5B75, U+5B7D, U+5BC5, U+5C49, U+5C90, U+5E1C, U+5E27, U+5E2B, U+5E37, U+5E90, U+618B, U+61F5, U+620A, U+620C, U+6273, U+62C7, U+62F7, U+6320, U+6342, U+6401-6402, U+6413, U+6512, U+655B, U+65A7, U+65F1, U+65F7, U+665F, U+6687, U+66A7, U+673D, U+67B8, U+6854, U+68D8, U+68FA, U+696D, U+6A02, U+6A0A, U+6A80, U+6B7C, U+6BD9, U+6C2E, U+6C76, U+6CF8, U+6D4A, U+6D85, U+6E24, U+6E32, U+6EC7, U+6F88, U+700F, U+701A, U+7078, U+707C, U+70AC, U+70C1, U+72E9, U+7409, U+7422, U+745A, U+7480, U+74A8, U+752B, U+7574, U+7656, U+7699, U+7737, U+785D, U+78BE, U+79B9, U+7A3D, U+7A91, U+7A9F, U+7AE3, U+7B77, U+7C3F, U+7D1A, U+7D50, U+7D93, U+8042, U+808B, U+8236, U+82B8-82B9, U+82EF, U+8309, U+836B, U+83EF, U+8431, U+85C9, U+865E, U+868C, U+8759, U+8760, U+8845, U+89BA, U+8A2A, U+8AAA, U+8C41, U+8D2C, U+8D4E, U+8E66, U+8E6D, U+8EAF, U+902E, U+914B, U+916E, U+919B, U+949B, U+94A0, U+94B0, U+9541-9542, U+9556, U+95EB, U+95F5, U+964B, U+968B, U+96CC-96CD, U+96CF, U+9713, U+9890, U+98A8, U+9985, U+9992, U+9A6D, U+9A81, U+9A86, U+9AB8, U+9CA4, U+FF02, U+FF1C, U+FF1E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-102.woff2") format("woff2");+ unicode-range: U+2264-2265, U+2463, U+2573, U+25B2, U+3448-3449, U+4E1E, U+4E5E, U+4F3A, U+4F5F, U+4FEA, U+5026, U+508D, U+516E, U+5189, U+5254, U+5288, U+52D8, U+52FA, U+5306, U+5308, U+5364, U+5384, U+53ED, U+543C, U+5450, U+5455, U+5466, U+54C4, U+5578, U+55A7, U+561F, U+5631, U+572D, U+575F, U+57AE, U+57E0, U+5830, U+594E, U+5984, U+5993, U+5BDD, U+5C0D, U+5C7F, U+5C82, U+5E62, U+5ED3, U+5F08, U+607A, U+60BC, U+625B, U+6292, U+62E2, U+6363, U+6467, U+6714, U+675E, U+6771, U+67A2, U+67FF, U+6805, U+68A7, U+68E0, U+6930, U+6986, U+69A8, U+69DF, U+6A44, U+6A5F, U+6C13, U+6C1F, U+6C22, U+6C2F, U+6C40, U+6C81, U+6C9B, U+6CA5, U+6DA4, U+6DF3, U+6E85, U+6EBA, U+6ED5, U+6F13, U+6F33, U+6F62, U+715E, U+72C4, U+73D1, U+7405, U+7487, U+7578, U+75A4, U+75EB, U+7693, U+7738, U+7741, U+776B, U+7792, U+77A7, U+77A9, U+77B3, U+788C, U+7984, U+79A7, U+79E4, U+7A1A, U+7A57, U+7AA6, U+7B0B, U+7B5D, U+7C27, U+7C7D, U+7CAA, U+7CD9, U+7CEF, U+7EDA, U+7EDE, U+7F24, U+803F, U+8046, U+80FA, U+81FB, U+8207, U+8258, U+8335, U+8339, U+8354, U+840E, U+85B0, U+85FB, U+8695, U+86AA, U+8717, U+8749, U+874C, U+8996, U+89BD, U+89C5, U+8BDB, U+8BF5, U+8C5A, U+8CEC, U+8D3F, U+8D9F, U+8E44, U+8FED, U+9005, U+9019, U+9082, U+90AF, U+90DD, U+90E1, U+90F8, U+916F, U+9176, U+949E, U+94A7, U+94C2, U+9525, U+9580, U+95DC, U+96E2, U+96FB, U+9704, U+9A7C, U+9A7F, U+9B41, U+9CA8, U+9CC4, U+9CDE, U+9E92, U+9EDE, U+9F9A, U+FF10, U+FF13, U+FF3B, U+FF3D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-103.woff2") format("woff2");+ unicode-range: U+2606, U+3014-3015, U+309C, U+33A1, U+4E52, U+4EC6, U+4F86, U+4F8D, U+4FDE, U+4FEF, U+500B, U+502A, U+515C, U+518A, U+51A5, U+51F3, U+5243, U+52C9, U+52D5, U+53A2, U+53EE, U+54CE, U+54FA, U+54FC, U+5580, U+5587, U+563F, U+56DA, U+5792, U+5815, U+5960, U+59D7, U+5B78, U+5B9B, U+5BE1, U+5C4E, U+5C51, U+5C6F, U+5C9A, U+5CFB, U+5D16, U+5ED6, U+5F27, U+5F6A, U+609A, U+60DF, U+6168, U+61C8, U+6236, U+62F1, U+62FD, U+631A, U+6328, U+632B, U+6346, U+638F, U+63A0, U+63C9, U+655E, U+6590, U+6615, U+6627, U+66AE, U+66E6, U+66F0, U+67DA, U+67EC, U+6813, U+6816, U+6869, U+6893, U+68AD, U+68F5, U+6977, U+6984, U+69DB, U+6B72, U+6BB7, U+6CE3, U+6CFB, U+6D47, U+6DA1, U+6DC4, U+6E43, U+6EAF, U+6EFF, U+6F8E, U+7011, U+7063, U+7076, U+7096, U+70BA, U+70DB, U+70EF, U+7119-711A, U+7172, U+718F, U+7194, U+727A, U+72D9, U+72ED, U+7325, U+73AE, U+73BA, U+73C0, U+73FE, U+7410, U+7426, U+7455, U+7554, U+7576, U+75AE, U+75B9, U+762B, U+766B, U+7682, U+7750, U+7779, U+7784, U+77EB, U+77EE, U+78F7, U+79E9, U+7A79, U+7B1B, U+7B28, U+7BF7, U+7DB2, U+7EC5, U+7EEE, U+7F14, U+7F1A, U+7FE1, U+8087, U+809B, U+81B3, U+8231, U+830E, U+835F, U+83E9, U+849C, U+851A, U+868A, U+8718, U+874E, U+8822, U+8910, U+8944, U+8A3B, U+8BB6, U+8BBC, U+8E72, U+8F9C, U+900D, U+904B, U+904E, U+9063, U+90A2, U+90B9, U+9119, U+94F2, U+952F, U+9576-9577, U+9593, U+95F8, U+961C, U+969B, U+96A7, U+96C1, U+9716, U+9761, U+97AD, U+97E7, U+98A4, U+997A, U+9A73, U+9B44, U+9E3D, U+9ECF, U+9ED4, U+FF11-FF12;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-104.woff2") format("woff2");+ unicode-range: U+2462, U+4E19, U+4E2B, U+4E36, U+4EA8, U+4ED1, U+4ED7, U+4F51, U+4F63, U+4F83, U+50E7, U+5112, U+5167, U+51A4, U+51B6, U+5239, U+5265, U+532A, U+5351, U+537F, U+5401, U+548F, U+5492, U+54AF, U+54B3, U+54BD, U+54D1, U+54DF, U+554F, U+5564, U+5598, U+5632, U+56A3, U+56E7, U+574E, U+575D-575E, U+57D4, U+584C, U+58E4, U+5937, U+5955, U+5A05, U+5A1F, U+5A49, U+5AC2, U+5C39, U+5C61, U+5D0E, U+5DE9, U+5E9A, U+5EB8, U+5F0A, U+5F13, U+5F6C, U+5F8C, U+603C, U+608D, U+611B, U+6127, U+62A0, U+62D0, U+634F, U+635E, U+63FD, U+6577, U+658B, U+65BC, U+660A, U+6643, U+6656, U+6703, U+6760, U+67AF, U+67C4, U+67E0, U+6817, U+68CD, U+690E, U+6960, U+69B4, U+6A71, U+6AAC, U+6B67, U+6BB4, U+6C55, U+6C70, U+6C82, U+6CA6, U+6CB8, U+6CBE, U+6EDE, U+6EE5, U+6F4D, U+6F84, U+6F9C, U+7115, U+7121, U+722A, U+7261, U+7272, U+7280, U+72F8, U+7504, U+754F, U+75D8, U+767C, U+76EF, U+778E, U+77BB, U+77F6, U+786B, U+78B1, U+7948, U+7985, U+79BE, U+7A83, U+7A8D, U+7EAC, U+7EEF, U+7EF8, U+7EFD, U+7F00, U+803D, U+8086, U+810A, U+8165, U+819D, U+81A8, U+8214, U+829C, U+831C, U+832B, U+8367, U+83E0, U+83F1, U+8403, U+846B, U+8475, U+84B2, U+8513, U+8574, U+85AF, U+86D9, U+86DB, U+8ACB, U+8BBD, U+8BE0-8BE1, U+8C0E, U+8D29, U+8D50, U+8D63, U+8F7F, U+9032, U+9042, U+90B1, U+90B5, U+9165, U+9175, U+94A6, U+94C5, U+950C, U+9610, U+9631, U+9699, U+973E, U+978D, U+97EC, U+97F6, U+984C, U+987D, U+9882, U+9965, U+996A, U+9972, U+9A8F, U+9AD3, U+9AE6, U+9CB8, U+9EDB, U+FF05, U+FF0B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-105.woff2") format("woff2");+ unicode-range: U+2190, U+250A, U+25BC, U+25CF, U+4E56, U+4EA9, U+4F3D, U+4F6C, U+4F88, U+4FA8, U+4FCF, U+5029, U+5188, U+51F9, U+5203, U+524A, U+5256, U+529D, U+5375, U+53DB, U+541F, U+5435, U+5457, U+548B, U+54C7, U+54D4, U+54E9, U+556A, U+5589, U+55BB, U+55E8, U+55EF, U+563B, U+566A, U+576A, U+58F9, U+598D, U+599E, U+59A8, U+5A9B, U+5AE3, U+5BB0, U+5BDE, U+5C4C, U+5C60, U+5D1B, U+5DEB, U+5DF7, U+5E18, U+5F26, U+5F64, U+601C, U+6084, U+60E9, U+614C, U+6208, U+621A, U+6233, U+6254, U+62D8, U+62E6, U+62EF, U+6323, U+632A, U+633D, U+6361, U+6405, U+640F, U+6614, U+6642, U+6657, U+67A3, U+6808, U+683D, U+6850, U+6897, U+68B3, U+68B5, U+68D5, U+6A58, U+6B47, U+6B6A, U+6C28, U+6C90, U+6CA7, U+6CF5, U+6D51, U+6DA9, U+6DC7, U+6DD1, U+6E0A, U+6E5B, U+6E9C, U+6F47, U+6F6D, U+70AD, U+70F9, U+710A, U+7130, U+71AC, U+745F, U+7476, U+7490, U+7529, U+7538, U+75D2, U+7696, U+76B1, U+76FC, U+777F, U+77DC, U+789F, U+795B, U+79BD, U+79C9, U+7A3B, U+7A46, U+7AA5, U+7AD6, U+7CA5, U+7CB9, U+7CDF, U+7D6E, U+7F06, U+7F38, U+7FA1, U+7FC1, U+8015, U+803B, U+80A2, U+80AA, U+8116, U+813E, U+82BD, U+8305, U+8328, U+8346, U+846C, U+8549, U+859B, U+8611, U+8680, U+87F9, U+884D, U+8877, U+888D, U+88D4, U+898B, U+8A79, U+8A93, U+8C05, U+8C0D, U+8C26, U+8D1E, U+8D31, U+8D81, U+8E22, U+8E81, U+8F90, U+8F96, U+90CA, U+916C, U+917F, U+9187, U+918B, U+9499, U+94A9, U+9524, U+9540, U+958B, U+9600, U+9640, U+96B6, U+96C7, U+96EF, U+98D9, U+9976, U+997F, U+9A74, U+9A84, U+9C8D, U+9E26, U+9E9F, U+FF0F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-106.woff2") format("woff2");+ unicode-range: U+2460-2461, U+25C6, U+300E-300F, U+4E1B, U+4E7E, U+4ED5, U+4EF2, U+4F10, U+4F1E, U+4F50, U+4FA6, U+4FAF, U+5021, U+50F5, U+5179, U+5180, U+51D1, U+522E, U+52A3, U+52C3, U+52CB, U+5300, U+5319, U+5320, U+5349, U+5395, U+53D9, U+541E, U+5428, U+543E, U+54B1, U+54C0, U+54D2, U+570B, U+5858, U+58F6, U+5974, U+59A5, U+59E8, U+59EC, U+5A36, U+5A9A, U+5AB3, U+5B99, U+5BAA, U+5CE1, U+5D14, U+5D4C, U+5DC5, U+5DE2, U+5E99, U+5E9E, U+5F18, U+5F66, U+5F70, U+6070, U+60D5, U+60E7, U+6101, U+611A, U+61BE, U+6241, U+6252, U+626F, U+6296, U+62BC, U+62CC, U+6380, U+63A9, U+644A, U+6454, U+64A9, U+64B8, U+6500, U+6572, U+65A5, U+65A9, U+65EC, U+660F, U+6749, U+6795, U+67AB, U+68DA, U+6912, U+6BBF, U+6BEF, U+6CAB, U+6CCA, U+6CCC, U+6CFC, U+6D3D, U+6D78, U+6DEE, U+6E17, U+6E34, U+6E83, U+6EA2, U+6EB6, U+6F20, U+6FA1, U+707F, U+70D8, U+70EB, U+714C, U+714E, U+7235, U+7239, U+73CA, U+743C, U+745C, U+7624, U+763E, U+76F2, U+77DB, U+77E9, U+780D, U+7838, U+7845, U+78CA, U+796D, U+7A84, U+7AED, U+7B3C, U+7EB2, U+7F05, U+7F20, U+7F34, U+7F62, U+7FC5, U+7FD8, U+7FF0, U+800D, U+8036, U+80BA, U+80BE, U+80C0-80C1, U+8155, U+817A, U+8180, U+81E3, U+8206, U+8247, U+8270, U+8299, U+82AD, U+8304, U+8393, U+83B9, U+840D, U+8427, U+8469, U+8471, U+84C4, U+84EC, U+853D, U+8681-8682, U+8721, U+8854, U+88D5, U+88F9, U+8BC0, U+8C0A, U+8C29, U+8C2D, U+8D41, U+8DEA, U+8EB2, U+8F9F, U+903B, U+903E, U+9102, U+9493, U+94A5, U+94F8, U+95F7, U+9706, U+9709, U+9774, U+98A0, U+9E64, U+9F9F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-107.woff2") format("woff2");+ unicode-range: U+2103, U+4E18, U+4E27-4E28, U+4E38, U+4E59, U+4E8F, U+4EAD, U+4EC7, U+4FE9, U+503A, U+5085, U+5146, U+51AF, U+51F8, U+52AB, U+5339, U+535C, U+5378, U+538C, U+5398, U+53F9, U+5415, U+5475, U+54AA, U+54AC, U+54B8, U+5582, U+5760, U+5764, U+57CB, U+5835, U+5885, U+5951, U+5983, U+59DA, U+5A77, U+5B5D, U+5B5F, U+5BB5, U+5BC2, U+5BE8, U+5BFA, U+5C2C, U+5C34, U+5C41, U+5C48, U+5C65, U+5CAD, U+5E06, U+5E42, U+5EF7, U+5F17, U+5F25, U+5F6D, U+5F79, U+6028, U+6064, U+6068, U+606D, U+607C, U+6094, U+6109, U+6124, U+6247, U+626D, U+6291, U+629A, U+62AC, U+62B9, U+62FE, U+6324, U+6349, U+6367, U+6398, U+6495, U+64A4, U+64B0, U+64BC, U+64CE, U+658C, U+65ED, U+6602, U+6674, U+6691, U+66A8, U+674F, U+679A, U+67EF, U+67F4, U+680B, U+6876, U+68A8, U+6A59, U+6A61, U+6B20, U+6BC5, U+6D12, U+6D46, U+6D8C, U+6DC0, U+6E14, U+6E23, U+6F06, U+7164, U+716E, U+7199, U+71E5, U+72AC, U+742A, U+755C, U+75AB, U+75B2, U+75F4, U+7897, U+78B3, U+78C5, U+7978, U+79FD, U+7A74, U+7B4B, U+7B5B, U+7ECE, U+7ED2, U+7EE3, U+7EF3, U+7F50, U+7F55, U+7F9E, U+7FE0, U+809D, U+8106, U+814A, U+8154, U+817B, U+818F, U+81C2, U+81ED, U+821F, U+82A6, U+82D1, U+8302, U+83C7, U+83CA, U+845B, U+848B, U+84C9, U+85E4, U+86EE, U+8700, U+8774, U+8881, U+8C1C, U+8C79, U+8D2A, U+8D3C, U+8EBA, U+8F70, U+8FA9, U+8FB1, U+900A, U+9017, U+901D, U+9022, U+906E, U+946B, U+94DD, U+94ED, U+953B, U+95EF, U+95FA, U+95FD, U+96C0, U+971E, U+9753, U+9756, U+97E6, U+9881, U+9887, U+9B4F, U+9E2D, U+9F0E, U+FF5C;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-108.woff2") format("woff2");+ unicode-range: U+4E08, U+4E43, U+4E4F, U+4EF0, U+4F2A, U+507F, U+50AC, U+50BB, U+5151, U+51BB, U+51F6, U+51FD, U+5272, U+52FE, U+5362, U+53C9, U+53D4, U+53E0, U+543B, U+54F2, U+5507, U+5524, U+558A, U+55B5, U+561B, U+56CA, U+5782, U+57C3, U+5893, U+5915, U+5949, U+5962, U+59AE, U+59DC, U+59FB, U+5BD3, U+5C38, U+5CB3, U+5D07, U+5D29, U+5DE1, U+5DFE, U+5E15, U+5ECA, U+5F2F, U+5F7C, U+5FCC, U+6021, U+609F, U+60F9, U+6108, U+6148, U+6155, U+6170, U+61D2, U+6251, U+629B, U+62AB, U+62E8, U+62F3, U+6321, U+6350, U+6566, U+659C, U+65E8, U+6635, U+6655, U+6670, U+66F9, U+6734, U+679D, U+6851, U+6905, U+6B49, U+6B96, U+6C1B, U+6C41, U+6C6A, U+6C83, U+6CF3, U+6D9B, U+6DCB, U+6E1D, U+6E20-6E21, U+6EAA, U+6EE4, U+6EE9, U+6F58, U+70E4, U+722C, U+7262, U+7267, U+72B9, U+72E0, U+72EE, U+72F1, U+7334, U+73AB, U+7433, U+7470, U+758F, U+75D5, U+764C, U+7686, U+76C6, U+76FE, U+7720, U+77E2, U+7802, U+7816, U+788D, U+7891, U+7A00, U+7A9D, U+7B52, U+7BAD, U+7C98, U+7CCA, U+7EBA, U+7EEA, U+7EF5, U+7F1D, U+7F69, U+806A, U+809A, U+80BF, U+80C3, U+81C0, U+820C, U+82AC, U+82AF, U+82CD, U+82D7, U+838E, U+839E, U+8404, U+84B8, U+852C, U+8587, U+8650, U+8679, U+86C7, U+8702, U+87BA, U+886B-886C, U+8870, U+8C10, U+8C23, U+8C6B, U+8D3E, U+8D4B-8D4C, U+8D64, U+8D6B, U+8D74, U+8E29, U+8F69, U+8F74, U+8FB0, U+8FDF, U+901B, U+9038, U+9093, U+9171, U+9489, U+94AE, U+94C3, U+9508, U+9510, U+9601, U+9614, U+964C, U+9675, U+971C, U+97F5, U+9888, U+98D8, U+9971, U+9AA4, U+9E3F, U+9E45, U+9E4F, U+9E70, U+9F7F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-109.woff2") format("woff2");+ unicode-range: U+2192, U+2605, U+4E11, U+4E22, U+4E32, U+4F0D, U+4F0F, U+4F69, U+4FF1, U+50B2, U+5154, U+51DD, U+51F0, U+5211, U+5269, U+533F, U+5366-5367, U+5389, U+5413, U+5440, U+5446, U+5561, U+574A, U+5751, U+57AB, U+5806, U+5821, U+582A, U+58F3, U+5938, U+5948, U+5978, U+59D1, U+5A03, U+5A07, U+5AC1, U+5ACC, U+5AE9, U+5BB4, U+5BC4, U+5C3F, U+5E3D, U+5E7D, U+5F92, U+5FAA, U+5FE0, U+5FFD, U+6016, U+60A0, U+60DC, U+60E8, U+614E, U+6212, U+6284, U+62C6, U+62D3-62D4, U+63F4, U+642C, U+6478, U+6491-6492, U+64E6, U+6591, U+65A4, U+664B, U+6735, U+6746, U+67F1, U+67F3, U+6842, U+68AF, U+68C9, U+68CB, U+6A31, U+6B3A, U+6BC1, U+6C0F, U+6C27, U+6C57, U+6CC4, U+6CE5, U+6D2A, U+6D66, U+6D69, U+6DAF, U+6E58, U+6ECB, U+6EF4, U+707E, U+7092, U+70AB, U+71D5, U+7275, U+7384, U+73B2, U+7434, U+74E6, U+74F7, U+75BC, U+76C8, U+76D0, U+7709, U+77AC, U+7855, U+78A7, U+78C1, U+7A77, U+7B79, U+7C92, U+7CAE, U+7CD5, U+7EA4, U+7EB5, U+7EBD, U+7F5A, U+7FD4, U+7FFC, U+8083, U+8096, U+80A0, U+80D6, U+80DE, U+8102, U+8109, U+810F, U+8179, U+8292, U+82B3, U+8352, U+8361, U+83CC, U+841D, U+8461, U+8482, U+8521, U+857E, U+85AA, U+866B, U+8776, U+8896, U+889C, U+88F8, U+8A9E, U+8BC8, U+8BF8, U+8C0B, U+8C28, U+8D2B, U+8D2F, U+8D37, U+8D3A, U+8D54, U+8DC3, U+8DCC, U+8DF5, U+8E0F, U+8E48, U+8F86, U+8F88, U+8F9E, U+8FC1, U+8FC8, U+8FEB, U+9065, U+90A6, U+90AA, U+90BB, U+90C1, U+94DC, U+9521, U+9676, U+96D5, U+970D, U+9897, U+997C, U+9A70, U+9A76, U+9A9A, U+9AD4, U+9E23, U+9E7F, U+9F3B, U+FFE5;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-110.woff2") format("woff2");+ unicode-range: U+300C-300D, U+4E54, U+4E58, U+4E95, U+4EC1, U+4F2F, U+4F38, U+4FA3, U+4FCA, U+503E, U+5141, U+5144, U+517C, U+51CC, U+51ED, U+5242, U+52B2, U+52D2, U+52E4, U+540A, U+5439, U+5448, U+5496, U+54ED, U+5565, U+5761, U+5766, U+58EE, U+593A, U+594B, U+594F, U+5954, U+5996, U+59C6, U+59FF, U+5B64, U+5BFF, U+5C18, U+5C1D, U+5C97, U+5CA9, U+5CB8, U+5E9F, U+5EC9, U+5F04, U+5F7B, U+5FA1, U+5FCD, U+6012, U+60A6, U+60AC, U+60B2, U+60EF, U+626E, U+6270, U+6276, U+62D6, U+62DC, U+6316, U+632F, U+633A, U+6355, U+63AA, U+6447, U+649E, U+64C5, U+654C, U+65C1, U+65CB, U+65E6, U+6606, U+6731, U+675C, U+67CF, U+67DC, U+6846, U+6B8B, U+6BEB, U+6C61, U+6C88, U+6CBF, U+6CDB, U+6CEA, U+6D45, U+6D53, U+6D74, U+6D82, U+6DA8, U+6DB5, U+6DEB, U+6EDA, U+6EE8, U+6F0F, U+706D, U+708E, U+70AE, U+70BC, U+70C2, U+70E6, U+7237-7238, U+72FC, U+730E, U+731B, U+739B, U+73BB, U+7483, U+74DC, U+74F6, U+7586, U+7626, U+775B, U+77FF, U+788E, U+78B0, U+7956, U+7965, U+79E6, U+7AF9, U+7BEE, U+7C97, U+7EB1, U+7EB7, U+7ED1, U+7ED5, U+7F6A, U+7F72, U+7FBD, U+8017, U+808C, U+80A9, U+80C6, U+80CE, U+8150, U+8170, U+819C, U+820D, U+8230, U+8239, U+827E, U+8377, U+8389, U+83B2, U+8428, U+8463, U+867E, U+88C2, U+88D9, U+8986, U+8BCA, U+8BDE, U+8C13, U+8C8C, U+8D21, U+8D24, U+8D56, U+8D60, U+8D8B, U+8DB4, U+8E2A, U+8F68, U+8F89, U+8F9B, U+8FA8, U+8FBD, U+9003, U+90CE, U+90ED, U+9189, U+94BB, U+9505, U+95F9, U+963B, U+9655, U+966A, U+9677, U+96FE, U+9896, U+99A8, U+9A71, U+9A82, U+9A91, U+9B45, U+9ECE, U+9F20, U+FF0D;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-111.woff2") format("woff2");+ unicode-range: U+4E4C, U+4E88, U+4EA1, U+4EA6, U+4ED3-4ED4, U+4EFF, U+4F30, U+4FA7, U+4FC4, U+4FD7, U+500D, U+504F, U+5076-5077, U+517D, U+5192, U+51C9, U+51EF, U+5238, U+5251, U+526A, U+52C7, U+52DF, U+52FF, U+53A6, U+53A8, U+53EC, U+5410, U+559D, U+55B7, U+5634, U+573E, U+5783, U+585E, U+586B, U+58A8, U+5999, U+59D3, U+5A1C, U+5A46, U+5B54-5B55, U+5B85, U+5B8B, U+5B8F, U+5BBF, U+5BD2, U+5C16, U+5C24, U+5E05, U+5E45, U+5E7C, U+5E84, U+5F03, U+5F1F, U+5F31, U+5F84, U+5F90, U+5FBD, U+5FC6, U+5FD9, U+5FE7, U+6052, U+6062, U+6089, U+60A3, U+60D1, U+6167, U+622A, U+6234, U+624E, U+6269, U+626C, U+62B5, U+62D2, U+6325, U+63E1, U+643A, U+6446, U+6562, U+656C, U+65E2, U+65FA, U+660C, U+6628, U+6652, U+6668, U+6676, U+66FC, U+66FF, U+6717, U+676D, U+67AA, U+67D4, U+6843, U+6881, U+68D2, U+695A, U+69FD, U+6A2A, U+6B8A, U+6C60, U+6C64, U+6C9F, U+6CAA, U+6CC9, U+6CE1, U+6CFD, U+6D1B, U+6D1E, U+6D6E, U+6DE1, U+6E10, U+6E7F, U+6F5C, U+704C, U+7070, U+7089, U+70B8, U+718A, U+71C3, U+723D, U+732A, U+73CD, U+7518, U+756A, U+75AF, U+75BE, U+75C7, U+76D2, U+76D7, U+7763, U+78E8, U+795D, U+79DF, U+7C4D, U+7D2F, U+7EE9, U+7F13, U+7F8A, U+8000, U+8010, U+80AF, U+80F6, U+80F8, U+8212, U+8273, U+82F9, U+83AB, U+83B1, U+83F2, U+8584, U+871C, U+8861, U+888B, U+88C1, U+88E4, U+8BD1, U+8BF1, U+8C31, U+8D5A, U+8D75-8D76, U+8DE8, U+8F85, U+8FA3, U+8FC5, U+9006, U+903C, U+904D, U+9075, U+9178, U+9274, U+950B, U+9526, U+95EA, U+9636, U+9686, U+978B, U+987F, U+9A7E, U+9B42, U+9E1F, U+9EA6, U+9F13, U+9F84, U+FF5E;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-112.woff2") format("woff2");+ unicode-range: U+4E01, U+4E39, U+4E73, U+4ECD, U+4ED9, U+4EEA, U+4F0A, U+4F1F, U+4F5B, U+4FA0, U+4FC3, U+501F, U+50A8, U+515A, U+5175, U+51A0, U+51C0, U+51E1, U+51E4, U+5200, U+520A, U+5224, U+523A, U+52AA, U+52B1, U+52B3, U+5348, U+5353, U+5360, U+5371, U+5377, U+539A, U+541B, U+5434, U+547C, U+54E6, U+5510, U+5531, U+5609, U+56F0, U+56FA, U+5733, U+574F, U+5851, U+5854, U+5899, U+58C1, U+592E, U+5939, U+5976, U+5986, U+59BB, U+5A18, U+5A74, U+5B59, U+5B87, U+5B97, U+5BA0, U+5BAB, U+5BBD-5BBE, U+5BF8, U+5C0A, U+5C3A, U+5C4A, U+5E16, U+5E1D, U+5E2D, U+5E8A, U+6015, U+602A, U+6050, U+6069, U+6162, U+61C2, U+6293, U+6297, U+62B1, U+62BD, U+62DF, U+62FC, U+6302, U+635F, U+638C, U+63ED, U+6458, U+6469, U+6563, U+6620, U+6653, U+6696-6697, U+66DD, U+675F, U+676F-6770, U+67D0, U+67D3, U+684C, U+6865, U+6885, U+68B0, U+68EE, U+690D, U+6B23, U+6B32, U+6BD5, U+6C89, U+6D01, U+6D25, U+6D89, U+6DA6, U+6DB2, U+6DF7, U+6ED1, U+6F02, U+70C8, U+70DF, U+70E7, U+7126, U+7236, U+7259, U+731C, U+745E, U+74E3, U+751A, U+751C, U+7532, U+7545, U+75DB, U+7761, U+7A0D, U+7B51, U+7CA4, U+7CD6, U+7D2B, U+7EA0, U+7EB9, U+7ED8, U+7F18, U+7F29, U+8033, U+804A, U+80A4-80A5, U+80E1, U+817F, U+829D, U+82E6, U+8336, U+840C, U+8499, U+864E, U+8651, U+865A, U+88AD, U+89E6, U+8BD7, U+8BFA, U+8C37, U+8D25, U+8D38, U+8DDD, U+8FEA, U+9010, U+9012, U+906D, U+907F-9080, U+90D1, U+9177, U+91CA, U+94FA, U+9501, U+9634-9635, U+9694, U+9707, U+9738, U+9769, U+9A7B, U+9A97, U+9AA8, U+9B3C, U+9C81, U+9ED8;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-113.woff2") format("woff2");+ unicode-range: U+4E4E, U+4E61, U+4E71, U+4EBF, U+4F26, U+5012, U+51AC, U+51B0, U+51B2, U+51B7, U+5218, U+521A, U+5220, U+5237, U+523B, U+526F, U+5385, U+53BF, U+53E5, U+53EB, U+53F3, U+53F6, U+5409, U+5438, U+54C8, U+54E5, U+552F, U+5584, U+5706, U+5723, U+5750, U+575A, U+5987-5988, U+59B9, U+59D0, U+59D4, U+5B88, U+5B9C, U+5BDF, U+5BFB, U+5C01, U+5C04, U+5C3E, U+5C4B, U+5C4F, U+5C9B, U+5CF0, U+5DDD, U+5DE6, U+5DE8, U+5E01, U+5E78, U+5E7B, U+5E9C, U+5EAD, U+5EF6, U+5F39, U+5FD8, U+6000, U+6025, U+604B, U+6076, U+613F, U+6258, U+6263, U+6267, U+6298, U+62A2, U+62E5, U+62EC, U+6311, U+6377, U+6388-6389, U+63A2, U+63D2, U+641E, U+642D, U+654F, U+6551, U+6597, U+65CF, U+65D7, U+65E7, U+6682, U+66F2, U+671D, U+672B, U+6740, U+6751, U+6768, U+6811, U+6863, U+6982, U+6BD2, U+6CF0, U+6D0B, U+6D17, U+6D59, U+6DD8, U+6DFB, U+6E7E, U+6F6E, U+6FB3, U+706F, U+719F, U+72AF, U+72D0, U+72D7, U+732B, U+732E, U+7389, U+73E0, U+7530, U+7687, U+76D6, U+76DB, U+7840, U+786C, U+79CB, U+79D2, U+7A0E, U+7A33, U+7A3F, U+7A97, U+7ADE-7ADF, U+7B26, U+7E41, U+7EC3, U+7F3A, U+8089, U+80DC, U+811A, U+8131, U+8138, U+821E, U+8349, U+83DC, U+8457, U+867D, U+86CB, U+8A89, U+8BA8, U+8BAD, U+8BEF, U+8BFE, U+8C6A, U+8D1D, U+8D4F, U+8D62, U+8DD1, U+8DF3, U+8F6E, U+8FF9, U+900F, U+9014, U+9057, U+9192, U+91CE, U+9488, U+94A2, U+9547, U+955C, U+95F2, U+9644, U+964D, U+96C4-96C5, U+96E8, U+96F6-96F7, U+9732, U+9759, U+9760, U+987A, U+989C, U+9910, U+996D-996E, U+9B54, U+9E21, U+9EBB, U+9F50;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-114.woff2") format("woff2");+ unicode-range: U+4E03, U+4E25, U+4E30, U+4E34, U+4E45, U+4E5D, U+4E89, U+4EAE, U+4ED8, U+4F11, U+4F19, U+4F24, U+4F34, U+4F59, U+4F73, U+4F9D, U+4FB5, U+5047, U+505C, U+5170, U+519C, U+51CF, U+5267, U+5356, U+5374, U+5382, U+538B, U+53E6, U+5426, U+542B, U+542F, U+5462, U+5473, U+554A, U+5566, U+5708, U+571F, U+5757, U+57DF, U+57F9, U+5802, U+590F, U+591C, U+591F, U+592B, U+5965, U+5979, U+5A01, U+5A5A, U+5B63, U+5B69, U+5B81, U+5BA1, U+5BA3, U+5C3C, U+5C42, U+5C81, U+5DE7, U+5DEE, U+5E0C, U+5E10, U+5E55, U+5E86, U+5E8F, U+5EA7, U+5F02, U+5F52, U+5F81, U+5FF5, U+60CA, U+60E0, U+6279, U+62C5, U+62FF, U+63CF, U+6444, U+64CD, U+653B, U+65BD, U+65E9, U+665A, U+66B4, U+66FE, U+6728, U+6742, U+677E, U+67B6, U+680F, U+68A6, U+68C0, U+699C, U+6B4C, U+6B66, U+6B7B, U+6BCD, U+6BDB, U+6C38, U+6C47, U+6C49, U+6CB3, U+6CB9, U+6CE2, U+6D32, U+6D3E, U+6D4F, U+6E56, U+6FC0, U+7075, U+7206, U+725B, U+72C2, U+73ED, U+7565, U+7591, U+7597, U+75C5, U+76AE, U+76D1, U+76DF, U+7834, U+7968, U+7981, U+79C0, U+7A7F, U+7A81, U+7AE5, U+7B14, U+7C89, U+7D27, U+7EAF, U+7EB3, U+7EB8, U+7EC7, U+7EE7, U+7EFF, U+7F57, U+7FFB, U+805A, U+80A1, U+822C, U+82CF, U+82E5, U+8363, U+836F, U+84DD, U+878D, U+8840, U+8857, U+8863, U+8865, U+8B66, U+8BB2, U+8BDA, U+8C01, U+8C08, U+8C46, U+8D1F, U+8D35, U+8D5B, U+8D5E, U+8DA3, U+8DDF, U+8F93, U+8FDD, U+8FF0, U+8FF7, U+8FFD, U+9000, U+9047, U+9152, U+949F, U+94C1, U+94F6, U+9646, U+9648, U+9669, U+969C, U+96EA, U+97E9, U+987B, U+987E, U+989D, U+9970, U+9986, U+9C7C, U+9C9C;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-115.woff2") format("woff2");+ unicode-range: U+4E14, U+4E1D, U+4E3D, U+4E49, U+4E60, U+4E9A, U+4EB2, U+4EC5, U+4EFD, U+4F3C, U+4F4F, U+4F8B, U+4FBF, U+5019, U+5145, U+514B, U+516B, U+516D, U+5174, U+5178, U+517B, U+5199, U+519B, U+51B3, U+51B5, U+5207, U+5212, U+5219, U+521D, U+52BF, U+533B, U+5343, U+5347, U+534A, U+536B, U+5370, U+53E4, U+53F2, U+5403, U+542C, U+547D, U+54A8, U+54CD, U+54EA, U+552E, U+56F4, U+5747, U+575B, U+5883, U+589E, U+5931, U+5947, U+5956-5957, U+5A92, U+5B83, U+5BA4, U+5BB3, U+5BCC, U+5C14, U+5C1A, U+5C3D, U+5C40, U+5C45, U+5C5E, U+5DF4, U+5E72, U+5E95, U+5F80, U+5F85, U+5FB7, U+5FD7, U+601D, U+626B, U+627F, U+62C9, U+62CD, U+6309, U+63A7, U+6545, U+65AD, U+65AF, U+65C5, U+666E, U+667A, U+670B, U+671B, U+674E, U+677F, U+6781, U+6790, U+6797, U+6821, U+6838-6839, U+697C, U+6B27, U+6B62, U+6BB5, U+6C7D, U+6C99, U+6D4B, U+6D4E, U+6D6A, U+6E29, U+6E2F, U+6EE1, U+6F14, U+6F2B, U+72B6, U+72EC, U+7387, U+7533, U+753B, U+76CA, U+76D8, U+7701, U+773C, U+77ED, U+77F3, U+7814, U+793C, U+79BB, U+79C1, U+79D8, U+79EF, U+79FB, U+7A76, U+7B11, U+7B54, U+7B56, U+7B97, U+7BC7, U+7C73, U+7D20, U+7EAA, U+7EC8, U+7EDD, U+7EED, U+7EFC, U+7FA4, U+804C, U+8058, U+80CC, U+8111, U+817E, U+826F, U+8303, U+843D, U+89C9, U+89D2, U+8BA2, U+8BBF, U+8BC9, U+8BCD, U+8BE6, U+8C22, U+8C61, U+8D22, U+8D26-8D27, U+8D8A, U+8F6F, U+8F7B, U+8F83, U+8F91, U+8FB9, U+8FD4, U+8FDC, U+9002, U+94B1, U+9519, U+95ED, U+961F, U+9632-9633, U+963F, U+968F-9690, U+96BE, U+9876, U+9884, U+98DE, U+9988, U+9999, U+9EC4, U+FF1B;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-116.woff2") format("woff2");+ unicode-range: U+3000, U+300A-300B, U+4E16, U+4E66, U+4E70, U+4E91-4E92, U+4E94, U+4E9B, U+4EC0, U+4ECA, U+4F01, U+4F17-4F18, U+4F46, U+4F4E, U+4F9B, U+4FEE, U+503C, U+5065, U+50CF, U+513F, U+5148, U+518D, U+51C6, U+51E0, U+5217, U+529E-529F, U+5341, U+534F, U+5361, U+5386, U+53C2, U+53C8, U+53CC, U+53D7-53D8, U+53EA, U+5404, U+5411, U+5417, U+5427, U+5468, U+559C, U+5668, U+56E0, U+56E2, U+56ED, U+5740, U+57FA, U+58EB, U+5904, U+592A, U+59CB, U+5A31, U+5B58, U+5B9D, U+5BC6, U+5C71, U+5DDE, U+5DF1, U+5E08, U+5E26, U+5E2E, U+5E93, U+5E97, U+5EB7, U+5F15, U+5F20, U+5F3A, U+5F62, U+5F69, U+5F88, U+5F8B, U+5FC5, U+600E, U+620F, U+6218, U+623F, U+627E, U+628A, U+62A4, U+62DB, U+62E9, U+6307, U+6362, U+636E, U+64AD, U+6539, U+653F, U+6548, U+6574, U+6613, U+6625, U+663E, U+666F, U+672A, U+6750, U+6784, U+6A21, U+6B3E, U+6B65, U+6BCF, U+6C11, U+6C5F, U+6DF1, U+706B, U+7167, U+724C, U+738B, U+73A9, U+73AF, U+7403, U+7537, U+754C, U+7559, U+767D, U+7740, U+786E, U+795E, U+798F, U+79F0, U+7AEF, U+7B7E, U+7BB1, U+7EA2, U+7EA6, U+7EC4, U+7EC6, U+7ECD, U+7EDC, U+7EF4, U+8003, U+80B2, U+81F3-81F4, U+822A, U+827A, U+82F1, U+83B7, U+8425, U+89C2, U+89C8, U+8BA9, U+8BB8, U+8BC6, U+8BD5, U+8BE2, U+8BE5, U+8BED, U+8C03, U+8D23, U+8D2D, U+8D34, U+8D70, U+8DB3, U+8FBE, U+8FCE, U+8FD1, U+8FDE, U+9001, U+901F-9020, U+90A3, U+914D, U+91C7, U+94FE, U+9500, U+952E, U+9605, U+9645, U+9662, U+9664, U+9700, U+9752, U+975E, U+97F3, U+9879, U+9886, U+98DF, U+9A6C, U+9A8C, U+9ED1, U+9F99;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-117.woff2") format("woff2");+ unicode-range: U+3010-3011, U+4E07, U+4E1C, U+4E24, U+4E3E, U+4E48, U+4E50, U+4E5F, U+4E8B-4E8C, U+4EA4, U+4EAB-4EAC, U+4ECB, U+4ECE, U+4ED6, U+4EE3, U+4EF6-4EF7, U+4EFB, U+4F20, U+4F55, U+4F7F, U+4FDD, U+505A, U+5143, U+5149, U+514D, U+5171, U+5177, U+518C, U+51FB, U+521B, U+5229, U+522B, U+52A9, U+5305, U+5317, U+534E, U+5355, U+5357, U+535A, U+5373, U+539F, U+53BB, U+53CA, U+53CD, U+53D6, U+53E3, U+53F0, U+5458, U+5546, U+56DB, U+573A, U+578B, U+57CE, U+58F0, U+590D, U+5934, U+5973, U+5B57, U+5B8C, U+5B98, U+5BB9, U+5BFC, U+5C06, U+5C11, U+5C31, U+5C55, U+5DF2, U+5E03, U+5E38, U+5E76, U+5E94, U+5EFA, U+5F71, U+5F97, U+5FEB, U+6001, U+603B, U+60F3, U+611F, U+6216, U+624D, U+6253, U+6295, U+6301, U+6392, U+641C, U+652F, U+653E, U+6559, U+6599, U+661F, U+671F, U+672F, U+6761, U+67E5, U+6807, U+6837, U+683C, U+6848, U+6B22, U+6B64, U+6BD4, U+6C14, U+6C34, U+6C42, U+6CA1, U+6D41, U+6D77, U+6D88, U+6E05, U+6E38, U+6E90, U+7136, U+7231, U+7531, U+767E, U+76EE, U+76F4, U+771F, U+7801, U+793A, U+79CD, U+7A0B, U+7A7A, U+7ACB, U+7AE0, U+7B2C, U+7B80, U+7BA1, U+7CBE, U+7D22, U+7EA7, U+7ED3, U+7ED9, U+7EDF, U+7F16, U+7F6E, U+8001, U+800C, U+8272, U+8282, U+82B1, U+8350, U+88AB, U+88C5, U+897F, U+89C1, U+89C4, U+89E3, U+8A00, U+8BA1, U+8BA4, U+8BAE-8BB0, U+8BBE, U+8BC1, U+8BC4, U+8BFB, U+8D28, U+8D39, U+8D77, U+8D85, U+8DEF, U+8EAB, U+8F66, U+8F6C, U+8F7D, U+8FD0, U+9009, U+90AE, U+90FD, U+91CC-91CD, U+91CF, U+95FB, U+9650, U+96C6, U+9891, U+98CE, U+FF1F;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-118.woff2") format("woff2");+ unicode-range: U+4E09-4E0B, U+4E0D-4E0E, U+4E13, U+4E1A, U+4E2A, U+4E3A-4E3B, U+4E4B, U+4E86, U+4E8E, U+4EA7, U+4EBA, U+4EE4-4EE5, U+4EEC, U+4F1A, U+4F4D, U+4F53, U+4F5C, U+4F60, U+4FE1, U+5165, U+5168, U+516C, U+5173, U+5176, U+5185, U+51FA, U+5206, U+5230, U+5236, U+524D, U+529B, U+52A0-52A1, U+52A8, U+5316, U+533A, U+53CB, U+53D1, U+53EF, U+53F7-53F8, U+5408, U+540C-540E, U+544A, U+548C, U+54C1, U+56DE, U+56FD-56FE, U+5728, U+5730, U+5907, U+5916, U+591A, U+5927, U+5929, U+597D, U+5982, U+5B50, U+5B66, U+5B89, U+5B9A, U+5B9E, U+5BA2, U+5BB6, U+5BF9, U+5C0F, U+5DE5, U+5E02, U+5E73-5E74, U+5E7F, U+5EA6, U+5F00, U+5F0F, U+5F53, U+5F55, U+5FAE, U+5FC3, U+6027, U+606F, U+60A8, U+60C5, U+610F, U+6210-6211, U+6237, U+6240, U+624B, U+6280, U+62A5, U+63A5, U+63A8, U+63D0, U+6536, U+6570, U+6587, U+65B9, U+65E0, U+65F6, U+660E, U+662D, U+662F, U+66F4, U+6700, U+670D, U+672C, U+673A, U+6743, U+6765, U+679C, U+682A, U+6B21, U+6B63, U+6CBB, U+6CD5, U+6CE8, U+6D3B, U+70ED, U+7247-7248, U+7269, U+7279, U+73B0, U+7406, U+751F, U+7528, U+7535, U+767B, U+76F8, U+770B, U+77E5, U+793E, U+79D1, U+7AD9, U+7B49, U+7C7B, U+7CFB, U+7EBF, U+7ECF, U+7F8E, U+8005, U+8054, U+80FD, U+81EA, U+85CF, U+884C, U+8868, U+8981, U+89C6, U+8BBA, U+8BDD, U+8BF4, U+8BF7, U+8D44, U+8FC7, U+8FD8-8FD9, U+8FDB, U+901A, U+9053, U+90E8, U+91D1, U+957F, U+95E8, U+95EE, U+95F4, U+9762, U+9875, U+9898, U+9996, U+9AD8, U+FF01, U+FF08-FF09;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-119.woff2") format("woff2");+ unicode-range: U+3001-3002, U+3042, U+3044, U+3046, U+3048, U+304A-3055, U+3057, U+3059-305B, U+305D, U+305F-3061, U+3063-306B, U+306D-3073, U+3075-3076, U+3078-3079, U+307B, U+307E-307F, U+3081-308D, U+308F, U+3092-3093, U+30A1-30A4, U+30A6-30BB, U+30BD, U+30BF-30C1, U+30C3-30C4, U+30C6-30CB, U+30CD-30D7, U+30D9-30E1, U+30E3-30E7, U+30E9-30ED, U+30EF, U+30F3, U+30FC, U+3127, U+4E00, U+4E2D, U+65B0, U+65E5, U+6708-6709, U+70B9, U+7684, U+7F51, U+FF0C, U+FF0E, U+FF1A;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-cyrillic.woff2") format("woff2");+ unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-vietnamese.woff2") format("woff2");+ unicode-range: U+0300-0301, U+0303, U+0309, U+0323, U+1EA0-1EF1;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-latin-ext.woff2") format("woff2");+ unicode-range: U+0100-0130, U+0132-0151, U+0154-017F, U+0181, U+0188, U+018A, U+018F, U+0192, U+0198-0199, U+01A0-01A1, U+01A5, U+01AD, U+01AF-01B0, U+01B3-01B4, U+01B7, U+01C0-01C3, U+01CD-01DC, U+01E4-01E9, U+01EE-01F0, U+01F9-01FF, U+0218-021B, U+021E-021F, U+0237, U+0250-0268, U+026A-0276, U+0278-027B, U+027D-027E, U+0280-0284, U+0288-0292, U+0294-0295, U+0298-0299, U+029B-02AD, U+02B0, U+02B2-02B3, U+02B7-02B8, U+02C1, U+02C7-02CC, U+02D0-02D1, U+02DD-02DE, U+02E0-02E3, U+02E5-02E9, U+02EC-02ED, U+02F3, U+1D43, U+1D47-1D49, U+1D4D, U+1D4F-1D50, U+1D52, U+1D56-1D58, U+1D5B, U+1D6C-1D76, U+1D9C, U+1DA0, U+1DBB, U+1E00-1E01, U+1E3E-1E3F, U+1E80-1E85, U+1E9E, U+1EF2-1EF9, U+20A3-20A4, U+20A8-20A9, U+20AB, U+20AE, U+20B1, U+20B8-20BA, U+20BD, U+20BF, U+2113;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-latin.woff2") format("woff2");+ unicode-range: U+0001, U+000A, U+000D, U+0020-007F, U+00A0-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2004-2006, U+2009-200A, U+2010, U+2013-2016, U+2018-201A, U+201C-201E, U+2020-2022, U+2025-2026, U+2028-2029, U+2030-2037, U+2039-203C, U+203E-203F, U+2042-2044, U+2047-2049, U+204E, U+2051, U+2055, U+2060-2064, U+2066-2069, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215;+}++@font-face {+ font-family: "MiSans";+ font-style: normal;+ font-display: swap;+ font-weight: 500;+ src: url("./misans-500-extra.woff2") format("woff2");+ unicode-range: U+02DB, U+030F, U+0312, U+0318-031A, U+031C-0320, U+0326, U+032A, U+0330, U+033A-033B, U+0346-0347, U+0349-034E, U+0362, U+0374-0375, U+037E, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03CE, U+03D1-03D4, U+03D6, U+0462-0463, U+046A-046B, U+0472-0475, U+0492-0493, U+0497, U+049A-049D, U+04A2-04A3, U+04AE-04AF, U+04B2-04B3, U+04B6-04BB, U+04CA, U+04D8-04D9, U+04E2-04E3, U+04E8-04E9, U+04EE-04EF, U+0E3F, U+1DC6-1DC9, U+1F45, U+2071, U+2079, U+2084-2089, U+2114, U+211E, U+212E, U+2153-2154, U+215B-215E, U+2160-2179, U+2180-2182, U+2527, U+2535, U+2538-253A, U+2549, U+2552-2553, U+2555-2556, U+2558-2559, U+255C, U+255E, U+2561, U+2564, U+2568, U+256B, U+275C, U+2783-2789, U+278D, U+278F-2793, U+2E81, U+2E84, U+2E88, U+2E8B-2E8C, U+2E97, U+2EA7, U+2EAA, U+2EAE, U+2EB3, U+2EB6-2EB7, U+2ECA, U+2FF0-2FFB, U+3022, U+3025-3029, U+303E, U+3094, U+30F7-30FA, U+33CE, U+A71B-A71C, U+AB53, U+FE10-FE19;+}diff --git a/packages/ui/src/fonts/modern.css b/packages/ui/src/fonts/modern.cssnew file mode 100644index 00000000..83cedad6--- /dev/null+++ b/packages/ui/src/fonts/modern.css@@ -0,0 +1,17 @@+/**+ * Frost (`modern`) faces:+ * - MiSans (sans), Latin and Chinese in one family, so zh text sits in the same face as the Latin+ * around it. MiSans Regular is weight 400 and MiSans Medium is 500, each cut into `unicode-range`+ * slices under `misans/`, which `scripts/build-misans.py` writes from Xiaomi's official package.+ * It is the one font this package vendors: MiSans has no official npm package. Licence: the MiSans+ * Font Intellectual Property License Agreement (`LICENSES/misans.txt`). The software must credit+ * MiSans (the Web App does, in the account menu), may not adapt the font, and never offers it for+ * download on its own.+ * - JetBrains Mono (mono): the variable face Primer also names, declared once in `github.css`, so+ * Frost's mono adds no bytes.+ *+ * Only `themes/modern.css` names MiSans, so only a Frost session downloads its slices, and only the+ * slices its text touches. Frost uses weights 400 and 500 alone; its theme turns weight synthesis+ * off, so a 600 or 700 request renders in Medium rather than as a smeared fake bold.+ */+@import "./misans/misans.css";diff --git a/packages/ui/src/fonts/raw-text.d.ts b/packages/ui/src/fonts/raw-text.d.tsnew file mode 100644index 00000000..3d0eff69--- /dev/null+++ b/packages/ui/src/fonts/raw-text.d.ts@@ -0,0 +1,9 @@+/**+ * A licence text imported whole (`import text from "./LICENSES/x.txt?raw"`), typed for this+ * package's own type check. Every consumer bundles with Vite, whose `vite/client` types declare+ * the same module shape; this file is not part of a consumer's program.+ */+declare module "*.txt?raw" {+ const text: string;+ export default text;+}diff --git a/packages/ui/src/fonts/vendored-fonts.json b/packages/ui/src/fonts/vendored-fonts.jsonnew file mode 100644index 00000000..79d81ffe--- /dev/null+++ b/packages/ui/src/fonts/vendored-fonts.json@@ -0,0 +1,13 @@+{+ "misans": {+ "family": "MiSans",+ "themes": ["modern"],+ "files": "src/fonts/misans/",+ "builtBy": "scripts/build-misans.py",+ "package": "https://hyperos.mi.com/font-download/MiSans.zip",+ "license": "src/fonts/LICENSES/misans.txt",+ "licenseTitle": "MiSans Font Intellectual Property License Agreement",+ "licenseSource": "https://hyperos.mi.com/font-download/MiSans%E5%AD%97%E4%BD%93%E7%9F%A5%E8%AF%86%E4%BA%A7%E6%9D%83%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE.pdf",+ "licenseSourceSha256": "4a93a27cd2bd81b3b5ecfd0a853144a876fa26938a93a68443c67d74172fcb86"+ }+}diff --git a/packages/ui/src/hooks.ts b/packages/ui/src/hooks.tsnew file mode 100644index 00000000..8741ca25--- /dev/null+++ b/packages/ui/src/hooks.ts@@ -0,0 +1,125 @@+/**+ * The style hooks: the closed list of `ui-*` classes a component may carry so that a theme can+ * give it a treatment tokens cannot express (a backdrop blur, a ruled frame, a stepped animation,+ * a colour field behind the app window, connector rules between nested rows).+ *+ * A hook names a job, never a look. The component carries the class, and each theme file decides+ * in `@layer ui-theme` what the hook does, which may be nothing: Primer's `.ui-glass` and+ * `.ui-shell` are no-ops. The layer sits after Tailwind's `utilities`, so a recipe beats the+ * utilities its host also carries.+ *+ * Only the names below exist. A `ui-*` class outside this list is a decoration without a job, and+ * the package's de-slop guard fails it. Adding a hook is a design change: add it here, give it a+ * recipe (or a documented no-op) in every theme file, and list its allowed hosts.+ *+ * | hook | the job | anatomy the recipes rely on |+ * | ------------------ | -------------------------------------------------------- | ----------------------------------------------------- |+ * | `ui-glass` | a transient layer over content: menus, popovers, the | — |+ * | | modal card, the floating composer, a sticky page header | |+ * | `ui-eyebrow` | a group label naming the items below it (never directly | — |+ * | | above an `h1`–`h4`) | |+ * | `ui-display` | the one display title of a page or hero | only on an `h1` or `[aria-level="1"]` |+ * | `ui-live` | motion for something that is running right now | `data-live="dot" \| "caret" \| "spinner"` |+ * | `ui-frame` | a ruled box with a head, a body, a foot and panes | children carry `data-slot="head" \| "body" \| "foot" \| "pane"` |+ * | `ui-underline-nav` | the selected-tab marker of a tab bar | items `[role="tab"]`, selected by `aria-selected="true"` |+ * | `ui-shell` | the app window: a navigation column beside a main column | children carry `data-slot="nav" \| "main"` (a right column may carry `"dock"`); the selected nav row is `[aria-current="page"]` |+ * | `ui-icon-decor` | an icon that says nothing its label does not already say | on the icon itself (or the element holding only it); optional `data-role="nav" \| "group" \| "menu" \| "empty"` |+ * | `ui-tree` | a container whose rows nest | rows carry `data-depth="0"…"8"`, the last row of a level `data-last="true"`; a row's children may follow it in a `data-branch` element carrying the children's `data-depth` |+ * | `ui-field` | a labelled control row | children carry `data-slot="label" \| "control"` and optionally `"hint"` |+ * | `ui-activity` | a step of the agent's work in the transcript: a thinking | `data-kind="thinking" \| "tool"`, `data-state="running" \| "done" \| "error"`; descendants may carry `data-slot="label" \| "detail" \| "progress"` (the progress slot exists only while running, hidden by the host — a recipe that draws it sets `display` itself) |+ * | | row, a tool-call row, a work group's header | |+ * | `ui-notice` | a notice: a toast, an inline notice strip | `data-tone="info" \| "success" \| "warning" \| "danger" \| "neutral"`; children may carry `data-slot="icon" \| "title" \| "body" \| "actions"` |+ * | `ui-chart` | a chart's root (its `<svg>`) | parts carry `data-part="grid" \| "axis" \| "series" \| "area" \| "bar" \| "point" \| "label"`; a series may carry `data-series="<n>"` |+ * | `ui-scrim` | the dimmed layer behind a dialog, drawer or sheet | — |+ *+ * `ui-shell` is the one place a theme may paint a field of colour: Frost paints the navigation+ * column a soft grey beside a near-white main column, flat (its earlier warm field and floating+ * sheet were retired at the owner's review of 2026-09-29); Console rules the columns off each+ * other with hairlines, full bleed; Primer changes nothing — the window's look is its own+ * classes.+ *+ * The three structure hooks (2026-09-19) are how the themes differ in organisation, not only in+ * colour and radius:+ *+ * - `ui-icon-decor` marks the icons a theme may recolour or drop: a nav row's glyph, a group+ * header's, a menu row's, an empty state's illustration — never a status mark, a file kind, a+ * tool glyph or an avatar, which carry information and stay in every theme. Primer keeps them+ * monochrome; Frost draws them in the muted ink (a menu row's keeps the row's own ink — a+ * danger row keeps its red); Console hides them, so the eyebrow and the selected row's weight+ * carry the structure and it shows far fewer icons.+ * A call site applies it by passing `decor="<role>"` to an icon renderer (`GlyphIcon`,+ * `Glyph`), which writes the class and `data-role` for it; the hook guard reads the prop on+ * the call site and holds the enclosing row or header to the host list. A wrapper that holds+ * only the icon may carry the class itself instead, so a hidden icon leaves no empty box+ * behind in a flex row.+ * - `ui-tree` marks a list whose rows nest: a file tree, a work group's tool rows under its head,+ * a plan's sub-steps, the subagent call graph. A host indents its rows itself, by+ * `calc(var(--ui-tree-inset) + var(--ui-tree-indent) * depth)`, so every theme's connector+ * rules land on the same columns; rows directly under the container's own head (a work group's+ * tool rows) are depth 1, a tree's roots depth 0, and depths past 8 draw as 8. Console draws+ * `├─` / `└─` connector rules in CSS (no box, no glyphs in the markup) and takes the box away+ * from a frame whose body is a tree; Frost indents against a soft guide rule and keeps its+ * card; Primer keeps today's bordered box. A branch is a plain block holding one level's rows+ * right after their parent row (`<li data-depth="1">` then `<div data-branch data-depth="2">`);+ * the recipes continue the parent's rule alongside it. Rows draw with `::before` / `::after`,+ * so a tree row carries no pseudo-elements of its own.+ * - `ui-field` marks a labelled control row — a form field or a settings row — so a theme can+ * lay its parts out its own way: Primer keeps the host's layout (label above in a form, label+ * left and control right in settings); Frost keeps the host's row and sets it as a band in a+ * soft-filled group, the block's first and last rows rounded; Console sets a tabular row with+ * a fixed label column (`--ui-field-label-w`) and the control left-aligned in the next, so a+ * settings page reads+ * like a table. The hint (or error) may be its own slot or sit inside the label slot.+ *+ * `ui-activity` (2026-09-29) is how a theme renders work in progress without the component+ * knowing which theme runs. The host writes what it knows — the kind of step, its state, and+ * which descendant is the label, the detail (a path, an argument preview, a duration) and the+ * progress slot — and stays a plain row under Primer. Frost adds nothing around the row — no+ * fill, border, ring or halo, the way Codex and macOS show work in progress — and lets a soft+ * highlight in the accent's hue sweep across the label; at rest nothing is added. Console+ * renders a transcript: the label in the chrome face at the small rung, uppercase and tracked,+ * muted once done and full ink while running, the detail muted, no box around the row and no+ * fill that moves between rest, hover, open and stuck (a hover changes the ink alone), and a+ * hatched block bar in the progress slot while the step runs; a step in a work group hangs off+ * the `└` its `ui-tree` row draws. Both recipes go still under reduced motion (a plain label,+ * the bar holding one fill) and read as finished at rest. The host's own status icon stays: the+ * recipes add to it, never replace it.+ *+ * `ui-notice` and `ui-chart` (2026-09-29) let notices and charts differ per theme where their+ * components had one look. A notice names its tone; Primer keeps the host's own strip, Frost+ * floats a soft card on the overlay surface with the tone as one small dot of its ink, Console+ * prints a console status line — a bracketed tone tag (`[INFO]`, `[ OK ]`, `[WARN]`, `[FAIL]`,+ * `[NOTE]`) in the tone's ink and the chrome face, the message in the reading face, nothing+ * round it. A chart names its parts;+ * Primer keeps the host's drawing, Frost draws soft low-chroma series, translucent bars with no+ * outline, round joins, caps and points and a fading area, Console draws thin solid+ * bars outlined in the ink, a dashed grid on crisp pixels, axis labels as tracked mono capitals+ * and 1px stepped lines with square joins. Nearly all of that is tokens the chart primitives+ * read (`--ui-chart-*`); a recipe adds only what a token cannot say — dashes, joins and caps,+ * pixel alignment, a fade. A series keeps the colour its host gave it in every theme.+ *+ * `ui-scrim` (2026-09-30) is the backdrop a dialog, drawer or sheet dims the page with: the host+ * paints its dim from `--ui-overlay-backdrop` and carries the hook, whether the scrim is a+ * sibling behind the panel or the full-viewport overlay the panel sits in. Primer and Console+ * leave the dim as it is; Frost blurs the page behind it, the reference's frosted backdrop — a+ * backdrop filter never reaches the element's own descendants, so a panel inside the scrim stays+ * sharp. It moves only with the host's fade, so reduced motion needs nothing from it.+ */+export const HOOKS = [+ "ui-glass",+ "ui-eyebrow",+ "ui-display",+ "ui-live",+ "ui-frame",+ "ui-underline-nav",+ "ui-shell",+ "ui-icon-decor",+ "ui-tree",+ "ui-field",+ "ui-activity",+ "ui-notice",+ "ui-chart",+ "ui-scrim",+] as const;++export type HookName = (typeof HOOKS)[number];diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsnew file mode 100644index 00000000..41a621ef--- /dev/null+++ b/packages/ui/src/index.ts@@ -0,0 +1,10 @@+/**+ * @prismshadow/penguin-ui — the shared UI package: token contract, themes, fonts and the+ * component set. Source-only: a consumer's `workspace:*` dependency is linked to this directory,+ * so Vite, vitest and tsc read `src/` through the `exports` map in package.json, never a build.+ */+export * from "./hooks";+export * from "./tokens";+// The component set, as it lands: the Spinner first (the Web App renders it where it used to+// hand-draw a ring).+export * from "./components/icons/spinner/spinner";diff --git a/packages/ui/src/testing/color.ts b/packages/ui/src/testing/color.tsnew file mode 100644index 00000000..d68e819b--- /dev/null+++ b/packages/ui/src/testing/color.ts@@ -0,0 +1,251 @@+/**+ * Colour parsing and WCAG 2 contrast, for tests that judge theme tokens by their computed values+ * instead of by a ratio typed into a comment.+ *+ * Covers the notations the theme files use: hex (3/4/6/8 digits), `rgb()`/`rgba()` in both the+ * comma and the space-and-slash syntax, `hsl()`/`hsla()`, `oklch()`, `color-mix(in srgb, …)`,+ * `transparent`, `white` and `black`. Anything else parses to `null`, and a caller reports that as+ * a failure — an unreadable colour is never assumed to pass.+ */++/** sRGB channels 0–255 (unrounded) and alpha 0–1. */+export interface Rgba {+ readonly r: number;+ readonly g: number;+ readonly b: number;+ readonly a: number;+}++export const WHITE: Rgba = { r: 255, g: 255, b: 255, a: 1 };+export const BLACK: Rgba = { r: 0, g: 0, b: 0, a: 1 };++const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));++/** Splits on commas (or whitespace when there are none) at parenthesis depth 0. */+function splitTopLevel(text: string, separator: "," | " "): string[] {+ const parts: string[] = [];+ let depth = 0;+ let current = "";+ for (const ch of text) {+ if (ch === "(") depth++;+ else if (ch === ")") depth--;+ const splits = separator === "," ? ch === "," : /\s/.test(ch);+ if (depth === 0 && splits) {+ if (current.trim() !== "") parts.push(current.trim());+ current = "";+ } else {+ current += ch;+ }+ }+ if (current.trim() !== "") parts.push(current.trim());+ return parts;+}++/** `name(args)` → `[name, args]`, or null when the value is not a single function call. */+function functionCall(value: string): [string, string] | null {+ const match = /^([a-z-]+)\((.*)\)$/is.exec(value.trim());+ return match === null ? null : [match[1]!.toLowerCase(), match[2]!];+}++/** A number, or a percentage scaled so 100% = `percentScale`. */+function numberOrPercent(token: string, percentScale: number): number | null {+ const match = /^(-?\d*\.?\d+(?:e-?\d+)?)(%?)$/i.exec(token.trim());+ if (match === null) return null;+ const n = Number(match[1]);+ return match[2] === "%" ? (n / 100) * percentScale : n;+}++function hue(token: string): number | null {+ const match = /^(-?\d*\.?\d+)(deg|turn|rad)?$/i.exec(token.trim());+ if (match === null) return null;+ const n = Number(match[1]);+ const unit = (match[2] ?? "deg").toLowerCase();+ return unit === "turn" ? n * 360 : unit === "rad" ? (n * 180) / Math.PI : n;+}++/** Channel and alpha tokens of a colour function, in either the legacy or the modern syntax. */+function channels(args: string): { values: string[]; alpha: string | undefined } | null {+ if (args.includes(",")) {+ const values = splitTopLevel(args, ",");+ if (values.length === 3) return { values, alpha: undefined };+ if (values.length === 4) return { values: values.slice(0, 3), alpha: values[3] };+ return null;+ }+ const [main, alpha, ...rest] = args.split("/");+ if (main === undefined || rest.length > 0) return null;+ const values = splitTopLevel(main, " ");+ if (values.length !== 3) return null;+ return { values, alpha: alpha?.trim() };+}++function parseAlpha(token: string | undefined): number | null {+ if (token === undefined) return 1;+ const a = numberOrPercent(token, 1);+ return a === null ? null : clamp(a, 0, 1);+}++function parseHex(value: string): Rgba | null {+ const hex = /^#([0-9a-f]{3,8})$/i.exec(value)?.[1];+ if (hex === undefined || hex.length === 5 || hex.length === 7) return null;+ const full = hex.length <= 4 ? [...hex].map((c) => c + c).join("") : hex;+ const byte = (i: number) => parseInt(full.slice(i, i + 2), 16);+ return {+ r: byte(0),+ g: byte(2),+ b: byte(4),+ a: full.length === 8 ? byte(6) / 255 : 1,+ };+}++function hslToRgb(h: number, s: number, l: number): [number, number, number] {+ const hh = (((h % 360) + 360) % 360) / 360;+ const f = (n: number) => {+ const k = (n + hh * 12) % 12;+ const a = s * Math.min(l, 1 - l);+ return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));+ };+ return [f(0) * 255, f(8) * 255, f(4) * 255];+}++/** OKLCH → gamma-encoded sRGB 0–255, clamped to the gamut (Björn Ottosson's matrices). */+function oklchToRgb(lightness: number, chroma: number, hueDeg: number): [number, number, number] {+ const rad = (hueDeg * Math.PI) / 180;+ const A = chroma * Math.cos(rad);+ const B = chroma * Math.sin(rad);+ const l = (lightness + 0.3963377774 * A + 0.2158037573 * B) ** 3;+ const m = (lightness - 0.1055613458 * A - 0.0638541728 * B) ** 3;+ const s = (lightness - 0.0894841775 * A - 1.291485548 * B) ** 3;+ const linear = [+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,+ ];+ const encode = (c: number) => {+ const v = clamp(c, 0, 1);+ return (v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055) * 255;+ };+ return [encode(linear[0]!), encode(linear[1]!), encode(linear[2]!)];+}++/** `color-mix(in srgb, A [p%], B [q%])`, premultiplied as CSS Color 5 specifies. */+function parseColorMix(args: string): Rgba | null {+ const [space, first, second, ...rest] = splitTopLevel(args, ",");+ if (space?.replace(/\s+/g, " ").toLowerCase() !== "in srgb" || rest.length > 0) return null;+ if (first === undefined || second === undefined) return null;+ const component = (part: string): { color: Rgba; pct: number | undefined } | null => {+ const tokens = splitTopLevel(part, " ");+ const pctToken = tokens.find((t) => /^-?\d*\.?\d+%$/.test(t));+ const colorText = tokens.filter((t) => t !== pctToken).join(" ");+ const color = parseColor(colorText);+ if (color === null) return null;+ return { color, pct: pctToken === undefined ? undefined : Number(pctToken.slice(0, -1)) };+ };+ const a = component(first);+ const b = component(second);+ if (a === null || b === null) return null;+ let p1 = a.pct;+ let p2 = b.pct;+ if (p1 === undefined && p2 === undefined) [p1, p2] = [50, 50];+ else if (p1 === undefined) p1 = 100 - p2!;+ else if (p2 === undefined) p2 = 100 - p1;+ const sum = p1 + p2!;+ if (sum <= 0) return null;+ const w1 = p1 / sum;+ const w2 = p2! / sum;+ const alpha = a.color.a * w1 + b.color.a * w2;+ const mix = (x: number, y: number) =>+ alpha === 0 ? 0 : (x * a.color.a * w1 + y * b.color.a * w2) / alpha;+ return {+ r: mix(a.color.r, b.color.r),+ g: mix(a.color.g, b.color.g),+ b: mix(a.color.b, b.color.b),+ a: alpha * Math.min(1, sum / 100),+ };+}++/** Parses a CSS colour value with no `var()` left in it. `null` when the notation is not covered. */+export function parseColor(input: string): Rgba | null {+ const value = input.trim();+ const lower = value.toLowerCase();+ if (lower === "transparent") return { r: 0, g: 0, b: 0, a: 0 };+ if (lower === "white") return WHITE;+ if (lower === "black") return BLACK;+ if (value.startsWith("#")) return parseHex(value);+ const call = functionCall(value);+ if (call === null) return null;+ const [name, args] = call;+ if (name === "color-mix") return parseColorMix(args);+ const parts = channels(args);+ if (parts === null) return null;+ const alpha = parseAlpha(parts.alpha);+ if (alpha === null) return null;+ const [c1, c2, c3] = parts.values as [string, string, string];+ if (name === "rgb" || name === "rgba") {+ const rgb = [c1, c2, c3].map((t) => numberOrPercent(t, 255));+ if (rgb.some((c) => c === null)) return null;+ const [r, g, b] = rgb.map((c) => clamp(c!, 0, 255)) as [number, number, number];+ return { r, g, b, a: alpha };+ }+ if (name === "hsl" || name === "hsla") {+ const h = hue(c1);+ const s = numberOrPercent(c2, 1);+ const l = numberOrPercent(c3, 1);+ if (h === null || s === null || l === null) return null;+ const [r, g, b] = hslToRgb(h, clamp(s, 0, 1), clamp(l, 0, 1));+ return { r, g, b, a: alpha };+ }+ if (name === "oklch") {+ const l = numberOrPercent(c1, 1);+ const c = numberOrPercent(c2, 0.4);+ const h = hue(c3);+ if (l === null || c === null || h === null) return null;+ const [r, g, b] = oklchToRgb(l, c, h);+ return { r, g, b, a: alpha };+ }+ return null;+}++/** `top` painted over `bottom` (source-over). */+export function composite(top: Rgba, bottom: Rgba): Rgba {+ const a = top.a + bottom.a * (1 - top.a);+ if (a === 0) return { r: 0, g: 0, b: 0, a: 0 };+ const channel = (t: number, b: number) => (t * top.a + b * bottom.a * (1 - top.a)) / a;+ return {+ r: channel(top.r, bottom.r),+ g: channel(top.g, bottom.g),+ b: channel(top.b, bottom.b),+ a,+ };+}++/** WCAG 2 relative luminance of an opaque colour. */+export function relativeLuminance(color: Rgba): number {+ const linear = (c: number) => {+ const v = c / 255;+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * linear(color.r) + 0.7152 * linear(color.g) + 0.0722 * linear(color.b);+}++/**+ * WCAG 2 contrast ratio of `fg` drawn on `bg`, 1–21. A translucent `fg` is composited over `bg`+ * first; `bg` must already be opaque — composite it over whatever it sits on before asking.+ */+export function contrastRatio(fg: Rgba, bg: Rgba): number {+ if (bg.a < 1)+ throw new Error("contrastRatio: composite the background onto an opaque layer first");+ const top = relativeLuminance(composite(fg, bg));+ const bottom = relativeLuminance(bg);+ const [light, dark] = top > bottom ? [top, bottom] : [bottom, top];+ return (light + 0.05) / (dark + 0.05);+}++/** `#rrggbb` (or `#rrggbbaa` when translucent), for messages. */+export function formatColor(color: Rgba): string {+ const hex = (n: number) =>+ Math.round(clamp(n, 0, 255))+ .toString(16)+ .padStart(2, "0");+ const alpha = color.a < 1 ? hex(color.a * 255) : "";+ return `#${hex(color.r)}${hex(color.g)}${hex(color.b)}${alpha}`;+}diff --git a/packages/ui/src/testing/css.ts b/packages/ui/src/testing/css.tsnew file mode 100644index 00000000..78f888d9--- /dev/null+++ b/packages/ui/src/testing/css.ts@@ -0,0 +1,151 @@+/**+ * A small CSS reader for tests: enough structure to find which rules declare which custom+ * properties, under which at-rules, at which line. Not a validator — it trusts the input to be CSS+ * that Tailwind and the browser already accept, and only has to see blocks, selectors and+ * declarations the way they do.+ */++export interface CssDeclaration {+ /** Property name as written, e.g. `--ui-canvas` or `color-scheme`. */+ readonly name: string;+ /** Value with surrounding whitespace trimmed and internal whitespace collapsed. */+ readonly value: string;+ /** 1-based line of the declaration's first character. */+ readonly line: number;+}++export interface CssStyleRule {+ /** The selector list as written, whitespace collapsed. */+ readonly selector: string;+ /** Enclosing at-rule preludes, outermost first, e.g. `["@layer ui-theme"]`. */+ readonly atRules: readonly string[];+ /** Selectors of enclosing style rules when CSS nesting is used, outermost first. */+ readonly parents: readonly string[];+ readonly declarations: readonly CssDeclaration[];+ /** 1-based line of the selector. */+ readonly line: number;+}++/** Replaces comments with spaces, keeping every newline so line numbers survive. */+export function stripCssComments(css: string): string {+ return css.replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, " "));+}++const collapse = (text: string) => text.replace(/\s+/g, " ").trim();++/** Every style rule in the sheet, nested ones included, in source order. */+export function parseCssRules(input: string): CssStyleRule[] {+ const css = stripCssComments(input);+ const lineStarts = [0];+ for (let at = css.indexOf("\n"); at !== -1; at = css.indexOf("\n", at + 1)) {+ lineStarts.push(at + 1);+ }+ const lineAt = (index: number) => {+ let lo = 0;+ let hi = lineStarts.length - 1;+ while (lo < hi) {+ const mid = (lo + hi + 1) >> 1;+ if (lineStarts[mid]! <= index) lo = mid;+ else hi = mid - 1;+ }+ return lo + 1;+ };++ const rules: CssStyleRule[] = [];+ let i = 0;++ /** Consumes statements up to the matching `}` (or the end of input for the top level). */+ const block = (+ atRules: readonly string[],+ parents: readonly string[],+ selector: string | null,+ selectorLine: number,+ ): void => {+ const declarations: CssDeclaration[] = [];+ let start = i;+ let parens = 0;+ let quote: string | null = null;++ /** The text since `start`, and the index of its first non-whitespace character. */+ const pending = (end: number): { text: string; line: number } => {+ const text = css.slice(start, end);+ const lead = text.length - text.trimStart().length;+ return { text, line: lineAt(start + lead) };+ };++ const flushDeclaration = (end: number) => {+ const { text, line } = pending(end);+ // Outside a style rule this is an at-rule statement (`@layer a, b;`, `@import …;`): skipped.+ if (selector === null) return;+ const colon = text.indexOf(":");+ if (colon === -1 || collapse(text) === "") return;+ declarations.push({+ name: collapse(text.slice(0, colon)),+ value: collapse(text.slice(colon + 1)),+ line,+ });+ };++ while (i < css.length) {+ const ch = css[i]!;+ if (quote !== null) {+ if (ch === "\\") i++;+ else if (ch === quote) quote = null;+ } else if (ch === '"' || ch === "'") {+ quote = ch;+ } else if (ch === "(") {+ parens++;+ } else if (ch === ")") {+ parens--;+ } else if (parens === 0 && ch === ";") {+ flushDeclaration(i);+ start = i + 1;+ } else if (parens === 0 && ch === "{") {+ const { text, line } = pending(i);+ const prelude = collapse(text);+ i++;+ if (prelude.startsWith("@")) block([...atRules, prelude], parents, null, line);+ else block(atRules, selector === null ? parents : [...parents, selector], prelude, line);+ start = i;+ continue;+ } else if (parens === 0 && ch === "}") {+ flushDeclaration(i);+ i++;+ break;+ }+ i++;+ }+ if (selector !== null) {+ rules.push({ selector, atRules, parents, declarations, line: selectorLine });+ }+ };++ while (i < css.length) block([], [], null, 1);+ // A rule is recorded when its block closes, so a nesting parent lands after its children.+ return rules.sort((a, b) => a.line - b.line);+}++/** Splits a selector list on its top-level commas and normalizes each selector's spelling. */+export function selectorList(selector: string): string[] {+ const parts: string[] = [];+ let depth = 0;+ let current = "";+ for (const ch of selector) {+ if (ch === "(" || ch === "[") depth++;+ else if (ch === ")" || ch === "]") depth--;+ if (ch === "," && depth === 0) {+ parts.push(current);+ current = "";+ } else current += ch;+ }+ parts.push(current);+ return parts.map(normalizeSelector).filter((s) => s !== "");+}++/** Collapses whitespace and double-quotes attribute values: `[data-theme='x']` → `[data-theme="x"]`. */+export function normalizeSelector(selector: string): string {+ return collapse(selector)+ .replace(/\[\s*([\w-]+)\s*=\s*'([^']*)'\s*\]/g, '[$1="$2"]')+ .replace(/\[\s*([\w-]+)\s*=\s*([\w-]+)\s*\]/g, '[$1="$2"]')+ .replace(/\[\s*([\w-]+)\s*=\s*"([^"]*)"\s*\]/g, '[$1="$2"]');+}diff --git a/packages/ui/src/testing/deslop.ts b/packages/ui/src/testing/deslop.tsnew file mode 100644index 00000000..c17651a0--- /dev/null+++ b/packages/ui/src/testing/deslop.ts@@ -0,0 +1,1315 @@+/**+ * The de-slop rules (K-redesign §3) as source scans, shared by the package's suite+ * (`packages/ui/test/deslop.test.ts`) and the web app's (`packages/web/test/deslop.test.ts`).+ *+ * What a check reads:+ *+ * - **Class tokens**: Tailwind classes from the TypeScript AST — string literals and the literal+ * text of template strings, never comments — and from `@apply` lists in stylesheets. A string is+ * a class string when it sits in a `className`-like JSX attribute, or when every word in it is+ * shaped like a class: `"Uppercase letters"` in a dictionary is prose, `"flex uppercase"` in a+ * lookup table is classes. A word touching an interpolation (`` `h-${n}` ``) is incomplete and+ * never matched.+ * - **Class units**: the tokens that land on one element together — a JSX element's class+ * attributes, a class string outside JSX (a `Record` entry), an `@apply` list. The co-occurrence+ * rules (a tone's tint beside the same tone's line) read units.+ * - **JSX elements**: tag, literal attributes, direct children (seen through `{cond && …}`,+ * `.map(…)` and fragments), the enclosing element, and the component they are written in — the+ * nearest enclosing PascalCase function.+ * - **CSS rules** from `css.ts`: selectors, declarations, lines.+ *+ * A check reports hits: rule, file, line, and what it found. Homes a rule names (the one spinner+ * file, the files that move a sheet) come in through a {@link DeslopPolicy}; occurrences a later+ * wave removes are the suite's allowlist, counted per file and rule ({@link allowlistProblems}).+ *+ * Out of sight, and so review rather than guard: classes assembled at runtime (`TONE[tone]`), and+ * nesting across component boundaries.+ */+import ts from "typescript";+import { parseCssRules, stripCssComments } from "./css";+import type { CssStyleRule } from "./css";+import type { SourceFile } from "./source-roots";++// ---------------------------------------------------------------------------+// Rules and policy+// ---------------------------------------------------------------------------++/** §3's rules by their number in the design, so a hit points straight at its rule. */+export const DESLOP_RULES = {+ 1: "transitions name their properties, never all",+ 2: "no hover or press transforms",+ 3: "state transitions take 120–200 ms",+ 4: "a rounded child in a padded rounded box takes the inner radius",+ 5: "a rounded clipping box owns the border",+ 6: "status marks have no halo, and pulse only where something is live",+ 7: "no icon in a tint of itself",+ 8: "no coloured left-border callouts",+ 9: "a filled tone box takes the neutral line",+ 10: "badges carry state, kind or numbers, never mood",+ 11: "one spinner",+ 12: "spacing on the rhythm steps",+ 13: "text sizes are rungs",+ 14: "uppercase only through the eyebrow, display, activity and chart hooks",+ 15: "numbers that align or update use tabular figures",+ 16: "mono is for data, not labels",+ 17: "one bordered surface per region",+ 18: "no decoration without a job",+ 19: "shadows are tokens",+ 20: "colour is tokens",+ 21: "no emoji in copy",+ 22: "a page header has no eyebrow",+} as const;++export type DeslopRule = keyof typeof DESLOP_RULES;++export const DESLOP_RULE_NUMBERS = Object.keys(DESLOP_RULES).map(Number) as DeslopRule[];++export interface DeslopHit {+ readonly rule: DeslopRule;+ /** Repo-relative id of the file, forward slashes. */+ readonly file: string;+ readonly line: number;+ /** What was found: the class, the declaration, or a short description. */+ readonly found: string;+}++/**+ * Where a rule's named exceptions live. Entries are root-relative: ending in `/` matches a+ * directory, containing `/` matches that path, and a bare file name (`chevron.tsx`) matches the+ * file wherever it sits — the design names these homes by file name.+ */+export interface DeslopPolicy {+ /** Rule 1: files that may transition a transform — the chevron, the sheet, launcher and drawer motion. */+ readonly transformMotion: readonly string[];+ /**+ * Rule 1: files that may transition a size — the one `data-layout-motion` rule in the theme+ * foundation, which moves a sidebar's width or a disclosure's grid rows on the theme's layout+ * tokens. A component never transitions geometry itself; it sets the attribute.+ */+ readonly layoutMotion?: readonly string[];+ /** Rule 3: keyframe-driven entrances that may run 300 ms or longer. */+ readonly entranceMotion: readonly string[];+ /** Rule 6: files that may pulse without `.ui-live` — the dot, the skeleton, the streaming caret. */+ readonly pulseHomes: readonly string[];+ /** Rule 11: the one file that spins. */+ readonly spinnerHomes: readonly string[];+ /**+ * Rule 20: palette classes, `dark:` and hex literals are refused. True for the package, whose+ * source reads tokens only; false for the web app, which leaves the palette wave by wave.+ */+ readonly tokensOnly: boolean;+ /** Rule 20: where source may spell a hex colour — the avatar palette and the contract's swatches. */+ readonly hexHomes: readonly string[];+}++export function matchesPolicyPath(rel: string, entries: readonly string[]): boolean {+ return entries.some((entry) =>+ entry.endsWith("/")+ ? rel.startsWith(entry)+ : entry.includes("/")+ ? rel === entry+ : rel === entry || rel.endsWith(`/${entry}`),+ );+}++// ---------------------------------------------------------------------------+// Class tokens+// ---------------------------------------------------------------------------++export interface ClassToken {+ /** As written: `dark:hover:bg-gray-800`. */+ readonly raw: string;+ /** Variants before the utility, outermost first: `["dark", "hover"]`. */+ readonly variants: readonly string[];+ /** The utility, `!` stripped: `bg-gray-800`, `-translate-x-1`. */+ readonly utility: string;+ readonly line: number;+ /** Character offset in the file. */+ readonly pos: number;+}++/** Splits `md:hover:[&>svg]:size-4!` into variants and utility on its top-level colons. */+export function parseClassToken(raw: string): { variants: string[]; utility: string } {+ const parts: string[] = [];+ let depth = 0;+ let current = "";+ for (const ch of raw) {+ if (ch === "[" || ch === "(") depth++;+ else if ((ch === "]" || ch === ")") && depth > 0) depth--;+ if (ch === ":" && depth === 0) {+ parts.push(current);+ current = "";+ } else current += ch;+ }+ return { variants: parts, utility: current.replace(/^!|!$/g, "") };+}++/** Class words with no hyphen, colon or bracket. Any other bare word makes its string prose. */+const SINGLE_WORD_CLASSES = new Set(+ (+ "absolute antialiased block blur border capitalize collapse container contents dark filter " ++ "fixed flex grayscale grid group grow hidden inline invert invisible isolate italic lowercase " ++ "ordinal outline overline peer prose relative resize ring rounded sepia shadow shrink static " ++ "sticky table transform transition truncate underline uppercase visible"+ ).split(" "),+);++/**+ * Whether a word is shaped like a class. A `partial` word touches an interpolation, so an open+ * bracket or a trailing hyphen is fine.+ */+export function isClassShaped(word: string, partial = false): boolean {+ let depth = 0;+ let letters = false;+ let plain = true;+ for (const ch of word) {+ if (ch === "[" || ch === "(") {+ depth++;+ plain = false;+ } else if (ch === "]" || ch === ")") {+ if (depth-- === 0) return false;+ } else if (depth === 0) {+ if (ch >= "a" && ch <= "z") letters = true;+ else if (!/[0-9\-:/.!@*%_&>+~]/.test(ch)) return false;+ if ("-:/@".includes(ch)) plain = false;+ }+ }+ if (word === "") return false;+ if (partial) return true;+ if (!letters || depth !== 0 || /^[.:/,]|[.:,/]$/.test(word)) return false;+ return !plain || SINGLE_WORD_CLASSES.has(word.replace(/^!|!$/g, ""));+}++interface Word {+ readonly text: string;+ readonly offset: number;+ readonly partial: boolean;+}++function splitWords(text: string, openStart: boolean, openEnd: boolean): Word[] {+ return [...text.matchAll(/\S+/g)].map((match) => ({+ text: match[0],+ offset: match.index,+ partial:+ (openStart && match.index === 0) ||+ (openEnd && match.index + match[0].length === text.length),+ }));+}++function toTokens(words: readonly Word[], base: number, lineAt: (pos: number) => number) {+ return words+ .filter((word) => !word.partial && isClassShaped(word.text))+ .map((word): ClassToken => {+ const pos = base + word.offset;+ return { raw: word.text, ...parseClassToken(word.text), line: lineAt(pos), pos };+ });+}++// ---------------------------------------------------------------------------+// File analysis+// ---------------------------------------------------------------------------++export interface StringChunk {+ readonly text: string;+ readonly line: number;+ /** The chunk runs into an interpolation: its last word continues at runtime (`h-${n}`). */+ readonly openEnd: boolean;+}++/** Tokens that land on one element together. */+export interface ClassUnit {+ readonly tokens: readonly ClassToken[];+ readonly line: number;+}++export type JsxChild =+ | { readonly kind: "element"; readonly element: JsxElementInfo }+ | { readonly kind: "text"; readonly text: string }+ | { readonly kind: "expression" };++export interface JsxElementInfo {+ /** `div`, `Glyph`, `motion.div`. */+ readonly tag: string;+ readonly intrinsic: boolean;+ /** Literal attribute values: the string, `true` for a bare attribute, `null` for an expression. */+ readonly attributes: ReadonlyMap<string, string | true | null>;+ /** Complete class tokens from the element's class attributes. */+ readonly classes: readonly ClassToken[];+ readonly line: number;+ /** The nearest enclosing PascalCase function; `null` at module level. */+ readonly component: string | null;+ readonly parent: JsxElementInfo | null;+ readonly children: readonly JsxChild[];+}++export interface ComponentInfo {+ readonly name: string;+ readonly line: number;+ /** Class tokens written inside the component. */+ readonly classes: readonly ClassToken[];+ /** The first parameter's destructured names and declared type members. */+ readonly props: readonly string[];+ readonly elements: readonly JsxElementInfo[];+}++export interface FileAnalysis {+ readonly file: SourceFile;+ readonly surface: "markup" | "stylesheet";+ readonly tokens: readonly ClassToken[];+ readonly units: readonly ClassUnit[];+ readonly elements: readonly JsxElementInfo[];+ readonly components: readonly ComponentInfo[];+ /** Children lists of every element and fragment: where sibling order is read. */+ readonly siblingGroups: readonly (readonly JsxChild[])[];+ /** Every string chunk in markup, class or not: hex literals and emoji are looked for here. */+ readonly strings: readonly StringChunk[];+ readonly cssRules: readonly CssStyleRule[];+}++/** JSX attributes that carry classes: `className`, `class`, `panelClassName`, `iconClass`. */+const CLASS_ATTRIBUTE = /^(?:class|className)$|(?:ClassName|Class)$/;++const analyses = new WeakMap<SourceFile, FileAnalysis>();++export function analyzeFile(file: SourceFile): FileAnalysis {+ let analysis = analyses.get(file);+ if (analysis === undefined) {+ analysis = file.name.endsWith(".css") ? analyzeStylesheet(file) : analyzeMarkup(file);+ analyses.set(file, analysis);+ }+ return analysis;+}++function analyzeStylesheet(file: SourceFile): FileAnalysis {+ const css = stripCssComments(file.text);+ const lineAt = (pos: number) => css.slice(0, pos).split("\n").length;+ const units = [...css.matchAll(/@apply\s+([^;{}]+)/g)].map((match) => ({+ tokens: toTokens(+ splitWords(match[1]!, false, false),+ match.index + match[0].length - match[1]!.length,+ lineAt,+ ),+ line: lineAt(match.index),+ }));+ return {+ file,+ surface: "stylesheet",+ tokens: units.flatMap((unit) => unit.tokens),+ units,+ elements: [],+ components: [],+ siblingGroups: [],+ strings: [],+ cssRules: parseCssRules(file.text),+ };+}++/** The name a function goes by: its own, or the variable, property or method holding it. */+function functionName(node: ts.Node): string | null {+ if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) && node.name) {+ return node.name.text;+ }+ if (ts.isMethodDeclaration(node) && ts.isIdentifier(node.name)) return node.name.text;+ if (!ts.isArrowFunction(node) && !ts.isFunctionExpression(node)) return null;+ let holder: ts.Node = node.parent;+ // Through `memo(() => …)` and `forwardRef(function (…) {…})`.+ while (ts.isCallExpression(holder) || ts.isParenthesizedExpression(holder))+ holder = holder.parent;+ if (+ (ts.isVariableDeclaration(holder) || ts.isPropertyAssignment(holder)) &&+ ts.isIdentifier(holder.name)+ ) {+ return holder.name.text;+ }+ return null;+}++const isPascalCase = (name: string) => /^[A-Z][A-Za-z0-9]*$/.test(name);++function analyzeMarkup(file: SourceFile): FileAnalysis {+ const source = ts.createSourceFile(+ file.path,+ file.text,+ ts.ScriptTarget.Latest,+ /* setParentNodes */ true,+ file.name.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );+ const lineAt = (pos: number) => source.getLineAndCharacterOfPosition(pos).line + 1;+ const strings: StringChunk[] = [];+ const tokens: ClassToken[] = [];+ const looseUnits: ClassUnit[] = [];+ const attributeTokens = new Map<ts.Node, ClassToken[]>();++ /** One literal chunk: in a class attribute (`attribute`), or `classes` false in any other. */+ const chunk = (+ text: string,+ start: number,+ open: readonly [boolean, boolean],+ attribute: ts.JsxAttribute | null,+ classes: boolean,+ ) => {+ strings.push({ text, line: lineAt(start), openEnd: open[1] });+ if (!classes) return;+ const words = splitWords(text, open[0], open[1]);+ const classString =+ attribute !== null ||+ (words.length > 0 && words.every((word) => isClassShaped(word.text, word.partial)));+ if (!classString) return;+ const found = toTokens(words, start, lineAt);+ if (found.length === 0) return;+ tokens.push(...found);+ if (attribute === null) {+ looseUnits.push({ tokens: found, line: lineAt(start) });+ } else {+ const owner = attribute.parent.parent;+ attributeTokens.set(owner, [...(attributeTokens.get(owner) ?? []), ...found]);+ }+ };++ const visit = (node: ts.Node, attribute: ts.JsxAttribute | null, classes: boolean): void => {+ if (+ ts.isImportDeclaration(node) ||+ ts.isExportDeclaration(node) ||+ ts.isLiteralTypeNode(node) ||+ ts.isImportTypeNode(node) ||+ (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword)+ ) {+ return;+ }+ if (ts.isJsxAttribute(node)) {+ const isClass = CLASS_ATTRIBUTE.test(node.name.getText(source));+ if (node.initializer) visit(node.initializer, isClass ? node : null, isClass);+ } else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {+ chunk(node.text, node.getStart(source) + 1, [false, false], attribute, classes);+ } else if (ts.isTemplateExpression(node)) {+ chunk(node.head.text, node.head.getStart(source) + 1, [false, true], attribute, classes);+ for (const span of node.templateSpans) {+ visit(span.expression, attribute, classes);+ const open = [true, !ts.isTemplateTail(span.literal)] as const;+ chunk(span.literal.text, span.literal.getStart(source) + 1, open, attribute, classes);+ }+ } else if (ts.isPropertyAssignment(node)) {+ visit(node.initializer, attribute, classes); // the key is a name, not a value+ } else {+ ts.forEachChild(node, (child) => visit(child, attribute, classes));+ }+ };+ visit(source, null, true);++ // Elements.+ type Element = JsxElementInfo & { parent: JsxElementInfo | null; children: JsxChild[] };+ const infos = new Map<ts.Node, Element>();+ const collect = (node: ts.Node): void => {+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {+ const opening = ts.isJsxElement(node) ? node.openingElement : node;+ const tag = opening.tagName.getText(source);+ const attributes = new Map<string, string | true | null>();+ for (const attr of opening.attributes.properties) {+ if (!ts.isJsxAttribute(attr)) continue;+ const init = attr.initializer;+ const literal =+ init !== undefined && ts.isJsxExpression(init) ? init.expression : (init ?? null);+ attributes.set(+ attr.name.getText(source),+ init === undefined+ ? true+ : literal !== undefined &&+ literal !== null &&+ (ts.isStringLiteral(literal) ||+ ts.isNoSubstitutionTemplateLiteral(literal) ||+ ts.isNumericLiteral(literal))+ ? literal.text+ : null,+ );+ }+ let component: string | null = null;+ for (let at: ts.Node | undefined = node.parent; at !== undefined; at = at.parent) {+ const name = functionName(at);+ if (name !== null && isPascalCase(name)) {+ component = name;+ break;+ }+ }+ infos.set(node, {+ tag,+ intrinsic: /^[a-z][\w-]*$/.test(tag),+ attributes,+ classes: attributeTokens.get(opening) ?? [],+ line: lineAt(node.getStart(source)),+ component,+ parent: null,+ children: [],+ });+ }+ ts.forEachChild(node, collect);+ };+ collect(source);++ /** The elements an expression renders: JSX in it that is not inside other JSX in it. */+ const rendered = (expression: ts.Node): Element[] => {+ const found: Element[] = [];+ const walk = (node: ts.Node): void => {+ const info = infos.get(node);+ if (info !== undefined) found.push(info);+ else ts.forEachChild(node, walk);+ };+ walk(expression);+ return found;+ };+ const childrenOf = (children: ts.NodeArray<ts.JsxChild>): JsxChild[] =>+ children.flatMap((child): JsxChild[] => {+ if (ts.isJsxText(child)) {+ return child.text.trim() === "" ? [] : [{ kind: "text", text: child.text.trim() }];+ }+ if (ts.isJsxFragment(child)) return childrenOf(child.children);+ if (!ts.isJsxExpression(child)) return [{ kind: "element", element: infos.get(child)! }];+ const expression = child.expression;+ if (expression === undefined) return [];+ if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) {+ return [{ kind: "text", text: expression.text }];+ }+ const elements = rendered(expression);+ return elements.length === 0+ ? [{ kind: "expression" }]+ : elements.map((element) => ({ kind: "element", element }));+ });+ const siblingGroups: JsxChild[][] = [];+ const fragments = (node: ts.Node): void => {+ if (ts.isJsxFragment(node)) siblingGroups.push(childrenOf(node.children));+ ts.forEachChild(node, fragments);+ };+ fragments(source);+ for (const [node, info] of infos) {+ if (ts.isJsxElement(node)) info.children = childrenOf(node.children);+ siblingGroups.push(info.children);+ for (let at: ts.Node | undefined = node.parent; at !== undefined; at = at.parent) {+ const parent = infos.get(at);+ if (parent !== undefined) {+ info.parent = parent;+ break;+ }+ }+ }++ // Components.+ const membersOf = (type: ts.TypeNode | undefined): string[] => {+ if (type === undefined) return [];+ if (ts.isTypeLiteralNode(type))+ return type.members.flatMap((m) => m.name?.getText(source) ?? []);+ if (ts.isIntersectionTypeNode(type)) return type.types.flatMap(membersOf);+ if (!ts.isTypeReferenceNode(type)) return [];+ const name = type.typeName.getText(source);+ for (const statement of source.statements) {+ if (ts.isInterfaceDeclaration(statement) && statement.name.text === name) {+ return statement.members.flatMap((m) => m.name?.getText(source) ?? []);+ }+ if (ts.isTypeAliasDeclaration(statement) && statement.name.text === name) {+ return membersOf(statement.type);+ }+ }+ return [];+ };+ const components: ComponentInfo[] = [];+ const findComponents = (node: ts.Node): void => {+ const name =+ ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)+ ? functionName(node)+ : null;+ if (name !== null && isPascalCase(name)) {+ const fn = node as ts.FunctionLikeDeclarationBase;+ const [start, end] = [fn.getStart(source), fn.getEnd()];+ const param = fn.parameters[0];+ const props = param === undefined ? [] : membersOf(param.type);+ if (param !== undefined && ts.isObjectBindingPattern(param.name)) {+ props.push(...param.name.elements.map((e) => (e.propertyName ?? e.name).getText(source)));+ }+ components.push({+ name,+ line: lineAt(start),+ classes: tokens.filter((token) => token.pos >= start && token.pos < end),+ props,+ elements: [...infos]+ .filter(([element]) => element.getStart(source) >= start && element.getEnd() <= end)+ .map(([, info]) => info),+ });+ }+ ts.forEachChild(node, findComponents);+ };+ findComponents(source);++ const elements = [...infos.values()];+ return {+ file,+ surface: "markup",+ tokens,+ units: [+ ...elements+ .filter((element) => element.classes.length > 0)+ .map((element) => ({ tokens: element.classes, line: element.line })),+ ...looseUnits,+ ],+ elements,+ components,+ siblingGroups,+ strings,+ cssRules: [],+ };+}++// ---------------------------------------------------------------------------+// Vocabulary+// ---------------------------------------------------------------------------++const TONE_NAMES = ["success", "attention", "danger", "done", "neutral", "info"] as const;+/** Tailwind's chromatic hues: what a tone box, a callout or a halo can be painted in. */+const CHROMATIC_HUES =+ "red orange amber yellow lime green emerald teal cyan sky blue indigo violet purple fuchsia pink rose".split(+ " ",+ );+const HUE = `(?:${[...CHROMATIC_HUES, "slate", "gray", "zinc", "neutral", "stone"].join("|")})`;+const CHROMA = `(?:${CHROMATIC_HUES.join("|")})`;+const STEP = "(?:50|[1-9]00|950)";+const ALPHA = "(?:/[\\w.%[\\]()-]+)?";+const TINT = "(?:50|100|200)";++/** Rule 20: a colour utility on Tailwind's palette, or white / black. */+const PALETTE_CLASS = new RegExp(+ "^(?:bg|text|border(?:-[xytrblse])?|ring(?:-offset)?|outline|fill|stroke|from|via|to|divide|" ++ `placeholder|caret|accent|decoration|shadow|inset-shadow|inset-ring|drop-shadow)-(?:${HUE}-${STEP}|white|black)${ALPHA}$`,+);++/** Rule 1: what a transition may name. The transform family only in the motion files. */+const TRANSITION_PROPERTIES = new Set(+ "color background-color border-color opacity box-shadow outline-color text-decoration-color fill stroke".split(+ " ",+ ),+);+const TRANSFORM_PROPERTIES = new Set(["transform", "translate", "scale", "rotate"]);+/** Rule 1: the sizes the layout-motion rule may transition, and nothing else may. */+const LAYOUT_PROPERTIES = new Set(+ "width height min-width max-width flex-basis grid-template-rows grid-template-columns".split(" "),+);++/** Rule 12: the steps a gap, a stack or an all-sides padding may take. */+const RHYTHM_STEPS = new Set(["0", "px", "1", "1.5", "2", "3", "4", "6", "10"]);++/** Rule 10: words that sell rather than state. */+const MOOD_WORDS = new Set(["new", "hot", "popular", "beta", "trending", "exclusive"]);++/** Rule 21: pictographs that render as emoji by default, or are forced into emoji by VS16. */+export const EMOJI = /\p{Emoji_Presentation}|\p{Extended_Pictographic}\uFE0F/u;++/** Rule 20: a hex colour inside a string: `#fff`, `#2563eb`, `bg-[#00000080]`. */+const HEX_COLOUR = /(?:^|[\s([,:=])(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8}))(?![0-9a-z])/gi;+/** A short form with no letter is a label (`#001`), unless it is one repeated digit (`#000`). */+const isHexColour = (hex: string) =>+ hex.length > 5 || /[a-f]/i.test(hex) || new Set(hex.slice(1)).size === 1;++/** The components §3 names: tabular figures (15), mono-free labels (16), no eyebrow (22). */+export const TABULAR_COMPONENTS: readonly string[] = ["StatChip", "Count", "KeyValue"];+export const LABEL_COMPONENTS: readonly string[] = ["Button", "NavRow", "Heading", "MenuItem"];+export const PAGE_HEADER_COMPONENTS: readonly string[] = ["PageHeader"];++const BORDER_WIDTH = /^border(?:-(?:2|4|8))?$/;+const ROUNDED_STEP = /^rounded-(?:sm|md|lg|xl)$/;+const INNER_RADIUS =+ /^rounded-(?:full|control|\[var\(--radius-inner\)\]|\(--radius-inner\)|\[var\(--ui-radius-control\)\]|\(--ui-radius-control\))$/;+const DURATION_TOKEN = /^var\(\s*--ui-dur-(fast|base|slow)\s*(?:,[^)]*)?\)$/;++/** True when a token with no variants in the unit matches. */+const has = (tokens: readonly ClassToken[], pattern: RegExp) =>+ tokens.some((token) => token.variants.length === 0 && pattern.test(token.utility));++// ---------------------------------------------------------------------------+// Token predicates: what to report for one token, or null+// ---------------------------------------------------------------------------++type TokenPredicate = (token: ClassToken, file: SourceFile, policy: DeslopPolicy) => string | null;++const inPolicy = (file: SourceFile, entries: readonly string[]) =>+ matchesPolicyPath(file.rel, entries);++/** The comma-separated values of `name-[a,b]` or `name-(a,b)`, or null. */+function arbitraryValues(utility: string, name: string): string[] | null {+ if (!utility.startsWith(`${name}-[`) && !utility.startsWith(`${name}-(`)) return null;+ return utility+ .slice(name.length + 2, -1)+ .split(",")+ .map((part) => part.trim().replace(/_/g, " "));+}++function refusedTransitionProperties(+ properties: readonly string[],+ transformOk: boolean,+ layoutOk = false,+) {+ return properties.filter(+ (p) =>+ !TRANSITION_PROPERTIES.has(p) &&+ !(transformOk && TRANSFORM_PROPERTIES.has(p)) &&+ !(layoutOk && LAYOUT_PROPERTIES.has(p)),+ );+}++/** Rule 1: `transition-all`, bare `transition`, `transition-transform` off the motion files, a `transition-[…]` list off the set. */+const transitionToken: TokenPredicate = (token, file, policy) => {+ const u = token.utility;+ if (u === "transition-all" || u === "transition") return token.raw;+ const transformOk = inPolicy(file, policy.transformMotion);+ if (u === "transition-transform") return transformOk ? null : token.raw;+ const list = arbitraryValues(u, "transition");+ if (list === null || list.some((p) => p.startsWith("--") || p.startsWith("var("))) return null;+ const refused = refusedTransitionProperties(+ list,+ transformOk,+ inPolicy(file, policy.layoutMotion ?? []),+ );+ return refused.length > 0 ? token.raw : null;+};++/** Rule 2: `scale-*` / `translate-*` under a hover, active or focus variant (group- and peer- too). */+const hoverTransformToken: TokenPredicate = (token) =>+ token.variants.some((v) =>+ /^(?:group-|peer-)?(?:hover|active|focus|focus-visible|focus-within)(?:\/[\w-]+)?$/.test(v),+ ) && /^-?(?:scale|translate)-/.test(token.utility)+ ? token.raw+ : null;++function milliseconds(value: string): number | null {+ const match = /^(\d*\.?\d+)(ms|s)$/.exec(value.trim());+ return match === null ? null : Number(match[1]) * (match[2] === "s" ? 1000 : 1);+}++/**+ * Rule 3 on one duration. A duration token is fine (slow only in an entrance); a literal is fine+ * at 0, in `allowed`, or at 300 ms and up in an entrance. Other `var()`s are not ours to judge.+ */+function durationRefused(value: string, entrance: boolean, allowed: (ms: number) => boolean) {+ const token = DURATION_TOKEN.exec(value.trim());+ if (token !== null) return token[1] === "slow" && !entrance;+ const ms = milliseconds(value);+ return ms !== null && ms !== 0 && !allowed(ms) && !(ms >= 300 && entrance);+}++/** Utilities: `duration-150`, `duration-200` or the fast / base token — nothing in between. */+const UTILITY_DURATIONS = (ms: number) => ms === 150 || ms === 200;+/** Stylesheets: anything from 120 to 200 ms. */+const CSS_DURATIONS = (ms: number) => ms >= 120 && ms <= 200;++/** Rule 3: `duration-*` other than 150, 200 or the fast / base token; 300+ only in an entrance file. */+const durationToken: TokenPredicate = (token, file, policy) => {+ const entrance = inPolicy(file, policy.entranceMotion);+ const numeric = /^duration-(\d+)$/.exec(token.utility);+ const values =+ numeric !== null ? [`${numeric[1]}ms`] : arbitraryValues(token.utility, "duration");+ if (values === null || values.length !== 1) return null;+ const value = values[0]!.startsWith("--") ? `var(${values[0]})` : values[0]!;+ if (value.startsWith("var(") && !DURATION_TOKEN.test(value)) return null;+ return durationRefused(value, entrance, UTILITY_DURATIONS) ? token.raw : null;+};++/** Rule 11: `animate-spin` outside the Spinner file; `border-t-transparent` anywhere. */+const spinnerToken: TokenPredicate = (token, file, policy) => {+ const u = token.utility;+ if (u === "border-t-transparent") return token.raw;+ const spins = u === "animate-spin" || /^animate-[[(]spin[_\s]/.test(u);+ return spins && !inPolicy(file, policy.spinnerHomes) ? token.raw : null;+};++/** Rule 12: `gap-*`, `space-x|y-*`, `p-*` off the rhythm steps; a `var(--ui-*)` value is a step. */+const spacingToken: TokenPredicate = (token) => {+ const match = /^(?:gap(?:-[xy])?|space-[xy]|p)-(.+)$/.exec(token.utility);+ if (match === null || match[1] === "reverse" || RHYTHM_STEPS.has(match[1]!)) return null;+ return /^(?:\[var\(--ui-[\w-]+\)\]|\(--ui-[\w-]+\))$/.test(match[1]!) ? null : token.raw;+};++/** Rule 13: a literal font size, `text-[11px]` or `text-[0.6875rem]`. */+const textSizeToken: TokenPredicate = (token) =>+ /^text-\[(?:length:)?\d*\.?\d+(?:px|rem)\]$/.test(token.utility) ? token.raw : null;++/** Rule 14: `uppercase` and `tracking-wide|wider|widest`. */+const uppercaseToken: TokenPredicate = (token) =>+ /^(?:uppercase|tracking-(?:wide|wider|widest))$/.test(token.utility) ? token.raw : null;++/** Rule 19: a shadow other than `shadow-sm|lg|xl|none` or `shadow-[var(--ui-shadow-*)]`; any `drop-shadow`. */+const shadowToken: TokenPredicate = (token) => {+ const u = token.utility;+ if (!/^(?:shadow|inset-shadow|drop-shadow)(?:-|$)/.test(u)) return null;+ if (/^shadow-(?:sm|lg|xl|none)$/.test(u)) return null;+ if (/^shadow-(?:\[var\(--ui-shadow-[a-z]+\)\]|\(--ui-shadow-[a-z]+\))$/.test(u)) return null;+ return token.raw;+};++/** Rule 20: a palette colour class or a `dark:` variant, where the policy is tokens only. */+const paletteToken: TokenPredicate = (token, _file, policy) =>+ policy.tokensOnly && (token.variants.includes("dark") || PALETTE_CLASS.test(token.utility))+ ? token.raw+ : null;++// ---------------------------------------------------------------------------+// Unit and element checks+// ---------------------------------------------------------------------------++type Check = (analysis: FileAnalysis, policy: DeslopPolicy) => Omit<DeslopHit, "rule" | "file">[];++const tokenCheck =+ (predicate: TokenPredicate): Check =>+ (analysis, policy) =>+ analysis.tokens.flatMap((token) => {+ const found = predicate(token, analysis.file, policy);+ return found === null ? [] : [{ line: token.line, found }];+ });++/** Rule 6: `animate-ping`; `animate-pulse` off `.ui-live` outside the pulse homes; a halo on a dot. */+const statusMarkCheck: Check = (analysis, policy) =>+ analysis.units.flatMap((unit) => {+ const hits: { line: number; found: string }[] = [];+ const live = unit.tokens.some((t) => t.utility === "ui-live");+ for (const token of unit.tokens) {+ if (+ token.utility === "animate-ping" ||+ (token.utility === "animate-pulse" && !live && !inPolicy(analysis.file, policy.pulseHomes))+ ) {+ hits.push({ line: token.line, found: token.raw });+ }+ }+ const dot =+ has(unit.tokens, /^rounded-full$/) &&+ (has(unit.tokens, /^size-(?:1|1\.5|2|2\.5)$/) ||+ (has(unit.tokens, /^h-(?:1|1\.5|2|2\.5)$/) && has(unit.tokens, /^w-(?:1|1\.5|2|2\.5)$/)));+ if (dot) {+ const halo = new RegExp(`^(?:ring-(?:tone-|accent|${CHROMA}-)|shadow(?!-none$))`);+ for (const token of unit.tokens) {+ if (halo.test(token.utility))+ hits.push({ line: token.line, found: `${token.raw} on a dot` });+ }+ }+ return hits;+ });++/** Rule 7: a tone's (or a hue's) tint and ink on an element whose only content is icons. */+const tintedIconCheck: Check = (analysis) =>+ analysis.elements.flatMap((element) => {+ const iconOnly =+ element.children.length > 0 &&+ element.children.every(+ (child) =>+ child.kind === "element" &&+ (/^(?:svg|Glyph|GlyphIcon|Chevron)$|Icon$/.test(child.element.tag) ||+ (child.element.intrinsic && child.element.children.length === 0)),+ );+ if (!iconOnly) return [];+ const tone =+ TONE_NAMES.find(+ (t) =>+ has(element.classes, new RegExp(`^bg-tone-${t}-bg$`)) &&+ has(element.classes, new RegExp(`^text-tone-${t}-fg$`)),+ ) ??+ CHROMATIC_HUES.find(+ (h) =>+ has(element.classes, new RegExp(`^bg-${h}-${TINT}${ALPHA}$`)) &&+ has(element.classes, new RegExp(`^text-${h}-${STEP}${ALPHA}$`)),+ );+ return tone === undefined+ ? []+ : [+ {+ line: element.line,+ found: `<${element.tag}> holds only an icon, in ${tone} ink on ${tone} tint`,+ },+ ];+ });++/** Rule 8: a 2 or 4 px left border in a tone, the accent or a chromatic hue. */+const leftBorderCheck: Check = (analysis) => {+ const colour = new RegExp(+ `^border-(?:[ls]-)?(?:tone-[a-z]+-(?:line|fg|emphasis|bg)|accent(?:-[a-z]+)?|${CHROMA}-${STEP}${ALPHA})$`,+ );+ return analysis.units.flatMap((unit) => {+ const width = unit.tokens.find((t) => /^border-[ls]-(?:2|4)$/.test(t.utility));+ if (width === undefined || !unit.tokens.some((t) => colour.test(t.utility))) return [];+ return [{ line: width.line, found: `${width.raw} in a colour` }];+ });+};++/** Rule 9: a tone's tint beside the same tone's line, or a hue's 50–200 tint beside its border. */+const oneHueCheck: Check = (analysis) =>+ analysis.units.flatMap((unit) => [+ ...TONE_NAMES.filter(+ (t) =>+ has(unit.tokens, new RegExp(`^bg-tone-${t}-bg$`)) &&+ has(unit.tokens, new RegExp(`^border(?:-[xytrblse])?-tone-${t}-(?:line|fg|emphasis)$`)),+ ).map((t) => ({ line: unit.line, found: `${t}: tint and line on one box` })),+ ...CHROMATIC_HUES.filter(+ (h) =>+ has(unit.tokens, new RegExp(`^bg-${h}-${TINT}${ALPHA}$`)) &&+ has(unit.tokens, new RegExp(`^border(?:-[xytrblse])?-${h}-${STEP}${ALPHA}$`)),+ ).map((h) => ({ line: unit.line, found: `${h}: tint and line on one box` })),+ ]);++/** Rule 4: a stepped radius on a direct child of a padded box with a stepped radius. */+const nestedRadiusCheck: Check = (analysis) =>+ analysis.elements.flatMap((element) => {+ if (!has(element.classes, ROUNDED_STEP) || !has(element.classes, /^p-(?!0$|px$)/)) return [];+ return element.children.flatMap((child) => {+ if (child.kind !== "element") return [];+ const radius = child.element.classes.find(+ (t) => t.variants.length === 0 && ROUNDED_STEP.test(t.utility),+ );+ if (radius === undefined || has(child.element.classes, INNER_RADIUS)) return [];+ return [+ {+ line: child.element.line,+ found: `<${child.element.tag}> ${radius.raw} in a padded rounded box`,+ },+ ];+ });+ });++/** Rule 5: a full border on a direct child of a rounded box that clips. */+const clippedBorderCheck: Check = (analysis) =>+ analysis.elements.flatMap((element) => {+ if (+ !has(element.classes, /^rounded(?:-(?!none$|0$).+)?$/) ||+ !has(element.classes, /^overflow(?:-[xy])?-(?:hidden|clip)$/)+ ) {+ return [];+ }+ return element.children.flatMap((child) => {+ if (child.kind !== "element") return [];+ const border = child.element.classes.find(+ (t) => t.variants.length === 0 && BORDER_WIDTH.test(t.utility),+ );+ return border === undefined+ ? []+ : [+ {+ line: child.element.line,+ found: `<${child.element.tag}> ${border.raw} inside a clipping rounded box`,+ },+ ];+ });+ });++/** Rule 10: a `<Badge>` whose literal text is a mood word or an emoji. */+const moodBadgeCheck: Check = (analysis) =>+ analysis.elements.flatMap((element) =>+ element.tag !== "Badge"+ ? []+ : element.children.flatMap((child) => {+ if (child.kind !== "text") return [];+ const word = child.text.trim().toLowerCase();+ const mood =+ MOOD_WORDS.has(word) && !(word === "beta" && element.component === "BetaBadge");+ return mood || EMOJI.test(child.text)+ ? [{ line: element.line, found: `<Badge>${child.text.trim()}</Badge>` }]+ : [];+ }),+ );++const isEyebrow = (element: JsxElementInfo) =>+ element.classes.some((t) => t.utility === "ui-eyebrow") ||+ (element.tag === "Text" && element.attributes.get("variant") === "eyebrow");++function headingLevel(element: JsxElementInfo): number | null {+ const intrinsic = /^h([1-6])$/.exec(element.tag);+ if (intrinsic !== null) return Number(intrinsic[1]);+ const level = element.tag === "Heading" ? element.attributes.get("level") : undefined;+ return typeof level === "string" && /^[1-6]$/.test(level) ? Number(level) : null;+}++/** Rule 14: an eyebrow as the previous sibling of an h1–h4. */+const eyebrowSiblingCheck: Check = (analysis) =>+ analysis.siblingGroups.flatMap((group) =>+ group.flatMap((child, i) => {+ const next = group[i + 1];+ if (child.kind !== "element" || next?.kind !== "element") return [];+ const level = headingLevel(next.element);+ return isEyebrow(child.element) && level !== null && level <= 4+ ? [{ line: child.element.line, found: `eyebrow directly above <${next.element.tag}>` }]+ : [];+ }),+ );++/** Rule 15: a listed component with no `tabular-nums`. */+const tabularCheck: Check = (analysis) =>+ analysis.components+ .filter((c) => TABULAR_COMPONENTS.includes(c.name))+ .filter((c) => !c.classes.some((t) => t.utility === "tabular-nums"))+ .map((c) => ({ line: c.line, found: `${c.name} has no tabular-nums` }));++/** Rule 16: `font-mono` inside a listed label component. */+const monoLabelCheck: Check = (analysis) =>+ analysis.components+ .filter((c) => LABEL_COMPONENTS.includes(c.name))+ .flatMap((c) =>+ c.classes+ .filter((t) => t.utility === "font-mono")+ .map((t) => ({ line: t.line, found: `${t.raw} in ${c.name}` })),+ );++/** Block containers: what a card is written as. A bordered filled `<span>` or `<input>` is a control. */+const BLOCK_TAGS =+ /^(?:div|section|article|aside|header|footer|main|nav|ul|ol|li|details|form|fieldset)$/;++/** Rule 17: a bordered surface nested in another bordered surface in the same file. */+const nestedSurfaceCheck: Check = (analysis) => {+ const surface = (e: JsxElementInfo) =>+ BLOCK_TAGS.test(e.tag) &&+ has(e.classes, BORDER_WIDTH) &&+ has(e.classes, /^bg-surface(?:-muted|-inset)?$/);+ return analysis.elements.flatMap((element) => {+ if (!surface(element)) return [];+ for (let up = element.parent; up !== null; up = up.parent) {+ if (surface(up)) {+ return [+ {+ line: element.line,+ found: `<${element.tag}> surface inside the surface at line ${up.line}`,+ },+ ];+ }+ }+ return [];+ });+};++/** Rule 18: gradient backgrounds, and backdrop filters on a unit without `.ui-glass` / `.ui-scrim`. */+const decorationCheck: Check = (analysis) =>+ analysis.units.flatMap((unit) => {+ const glass = unit.tokens.some((t) => t.utility === "ui-glass" || t.utility === "ui-scrim");+ return unit.tokens.flatMap((token) => {+ const u = token.utility;+ const gradient =+ /^bg-(?:gradient-|linear-|radial|conic)/.test(u) ||+ /^bg-\[(?:image:)?(?:repeating-)?(?:linear|radial|conic)-gradient/.test(u) ||+ /^\[background(?:-image)?:[^\]]*gradient/.test(u);+ const blur = /^(?:backdrop-(?:blur|saturate|filter)|\[(?:-webkit-)?backdrop-filter:)/.test(u);+ return gradient || (blur && !glass) ? [{ line: token.line, found: token.raw }] : [];+ });+ });++/** Rule 20's hex half: hex colours in source strings outside the identity-data homes. */+const hexCheck: Check = (analysis, policy) => {+ if (!policy.tokensOnly || inPolicy(analysis.file, policy.hexHomes)) return [];+ return analysis.strings.flatMap((chunk) =>+ [...chunk.text.matchAll(HEX_COLOUR)]+ .filter((match) => isHexColour(match[1]!))+ .map((match) => ({+ line: chunk.line + (chunk.text.slice(0, match.index).match(/\n/g)?.length ?? 0),+ found: match[1]!,+ })),+ );+};++/** Rule 21: emoji in a `strings*.ts` dictionary. */+const emojiCheck: Check = (analysis) => {+ if (!/^strings.*\.ts$/.test(analysis.file.name)) return [];+ return analysis.strings+ .filter((chunk) => EMOJI.test(chunk.text))+ .map((chunk) => ({ line: chunk.line, found: chunk.text.match(EMOJI)![0] }));+};++/** Rule 22: a page header that takes or renders an eyebrow. */+const pageHeaderCheck: Check = (analysis) =>+ analysis.components+ .filter((c) => PAGE_HEADER_COMPONENTS.includes(c.name))+ .flatMap((c) => [+ ...(c.props.includes("eyebrow")+ ? [{ line: c.line, found: `${c.name} takes an eyebrow` }]+ : []),+ ...c.elements+ .filter(isEyebrow)+ .map((e) => ({ line: e.line, found: `${c.name} renders an eyebrow` })),+ ]);++// ---------------------------------------------------------------------------+// Stylesheet checks+// ---------------------------------------------------------------------------++const fullSelector = (rule: CssStyleRule) => [...rule.parents, rule.selector].join(" ");++/** Transition shorthand items; a missing property is `all`, as in CSS. */+function transitionItems(value: string): { property: string; duration: string | null }[] {+ const items: string[] = [];+ let depth = 0;+ let current = "";+ for (const ch of value.replace(/!important/g, "")) {+ if (ch === "(") depth++;+ else if (ch === ")") depth--;+ if (ch === "," && depth === 0) {+ items.push(current);+ current = "";+ } else current += ch;+ }+ items.push(current);+ return items+ .map((item) => item.trim())+ .filter((item) => item !== "" && item !== "none")+ .map((item) => {+ let property: string | null = null;+ let duration: string | null = null;+ for (const part of item.match(/[\w-]+\((?:[^()]|\([^()]*\))*\)|\S+/g) ?? []) {+ if (DURATION_TOKEN.test(part) || milliseconds(part) !== null) duration ??= part;+ else if (+ property === null &&+ /^[a-z-]+$/.test(part) &&+ !/^(?:ease|ease-in|ease-out|ease-in-out|linear|step-start|step-end|allow-discrete|normal)$/.test(+ part,+ )+ ) {+ property = part;+ }+ }+ return { property: property ?? "all", duration };+ });+}++const declarations = (analysis: FileAnalysis) =>+ analysis.cssRules.flatMap((rule) => rule.declarations.map((decl) => ({ rule, decl })));++/** Rule 1: `transition` / `transition-property` naming `all` (or nothing) or a property off the set. */+const cssTransitionCheck: Check = (analysis, policy) =>+ declarations(analysis).flatMap(({ decl }) => {+ const properties =+ decl.name === "transition"+ ? transitionItems(decl.value).map((item) => item.property)+ : decl.name === "transition-property"+ ? decl.value+ .split(",")+ .map((p) => p.trim())+ .filter((p) => p !== "none" && !p.startsWith("var("))+ : [];+ const refused = refusedTransitionProperties(+ properties,+ inPolicy(analysis.file, policy.transformMotion),+ inPolicy(analysis.file, policy.layoutMotion ?? []),+ );+ return refused.length > 0+ ? [{ line: decl.line, found: `${decl.name}: ${refused.join(", ")}` }]+ : [];+ });++/** Rule 2: `transform`, `translate` or `scale` declared under `:hover` or `:active`. */+const cssHoverTransformCheck: Check = (analysis) =>+ declarations(analysis).flatMap(({ rule, decl }) =>+ /:(?:hover|active)\b/.test(fullSelector(rule)) &&+ /^(?:transform|translate|scale)$/.test(decl.name) &&+ decl.value !== "none"+ ? [{ line: decl.line, found: `${rule.selector} { ${decl.name}: ${decl.value} }` }]+ : [],+ );++/** Rule 3: a transition duration outside 120–200 ms (300+ only in an entrance file). */+const cssDurationCheck: Check = (analysis, policy) => {+ const entrance = inPolicy(analysis.file, policy.entranceMotion);+ return declarations(analysis).flatMap(({ decl }) => {+ const durations =+ decl.name === "transition"+ ? transitionItems(decl.value).flatMap((item) => item.duration ?? [])+ : decl.name === "transition-duration"+ ? decl.value.split(",").map((part) => part.trim())+ : [];+ return durations+ .filter((duration) => durationRefused(duration, entrance, CSS_DURATIONS))+ .map((duration) => ({ line: decl.line, found: `${decl.name}: ${duration}` }));+ });+};++/** Animations named `names` outside the rules whose selector matches `except` (the live hook). */+const cssAnimationCheck =+ (names: RegExp, except: RegExp): Check =>+ (analysis) =>+ declarations(analysis).flatMap(({ rule, decl }) =>+ /^animation(?:-name)?$/.test(decl.name) &&+ names.test(decl.value) &&+ !except.test(fullSelector(rule))+ ? [{ line: decl.line, found: `${rule.selector} { ${decl.name}: ${decl.value} }` }]+ : [],+ );++/**+ * Rule 14: `text-transform: uppercase` outside `.ui-eyebrow` / `.ui-display` rules — and the+ * `.ui-activity` label, the transcript's mono capitals (user decision, 2026-09-29): a step's+ * label is a group-label rung in Console, and the hook is the one door to it — and, the same+ * way, a `.ui-chart` axis label, Console's tracked mono capitals on a plot.+ */+const cssUppercaseCheck: Check = (analysis) =>+ declarations(analysis).flatMap(({ rule, decl }) =>+ decl.name === "text-transform" &&+ decl.value === "uppercase" &&+ !/\.ui-(?:eyebrow|display|activity|chart)\b/.test(fullSelector(rule))+ ? [{ line: decl.line, found: `${rule.selector} { text-transform: uppercase }` }]+ : [],+ );++/** Rule 16: a hook recipe (`.ui-*`) setting a mono `font-family`. */+const cssHookMonoCheck: Check = (analysis) =>+ declarations(analysis).flatMap(({ rule, decl }) =>+ /\.ui-[a-z]/.test(fullSelector(rule)) &&+ decl.name === "font-family" &&+ /--ui-font-mono|monospace/.test(decl.value)+ ? [{ line: decl.line, found: `${rule.selector} { font-family: ${decl.value} }` }]+ : [],+ );++/**+ * Gradients painted by a hook recipe — the atmosphere tell — and backdrop filters off the two+ * hooks that may blur: `.ui-glass` (the frosted layer) and `.ui-scrim` (the dimmed backdrop+ * behind a dialog, which Frost blurs; user decision, 2026-09-30).+ * Two recipes may paint a gradient, each with a job: `.ui-shell`'s colour field behind the app+ * window, which holds the floating sheet and the glass layers against it (user decision,+ * 2026-09-19), and the RUNNING state of `.ui-activity`, whose highlight sweeping across a label+ * is the signal that a step is in progress (user decision, 2026-09-29) — never the resting+ * states, so a finished transcript carries no wash. A third, `.ui-chart`, may paint one as a+ * MASK: a line's area fading towards the baseline — a gradient that carries the data's shape,+ * not atmosphere (user decision, 2026-09-29). A gradient on any other hook, as a background or+ * as a mask, is still the tell. A gradient in app CSS that is not a hook (the context bar's+ * hatch, which carries meaning) is review.+ */+const GRADIENT_RECIPES = /\.ui-shell\b|\.ui-activity\[data-state="running"\]|\.ui-chart\b/;++const cssDecorationCheck: Check = (analysis) =>+ declarations(analysis).flatMap(({ rule, decl }) => {+ const selector = fullSelector(rule);+ if (+ /\.ui-[a-z]/.test(selector) &&+ !GRADIENT_RECIPES.test(selector) &&+ /^(?:background(?:-image)?|(?:-webkit-)?mask-image)$/.test(decl.name) &&+ /gradient\(/.test(decl.value)+ ) {+ return [{ line: decl.line, found: `${rule.selector} { ${decl.name}: …gradient() }` }];+ }+ if (+ /^(?:-webkit-)?backdrop-filter$/.test(decl.name) &&+ decl.value !== "none" &&+ !/\.ui-(?:glass|scrim)\b/.test(selector)+ ) {+ return [{ line: decl.line, found: `${rule.selector} { ${decl.name}: ${decl.value} }` }];+ }+ return [];+ });++// ---------------------------------------------------------------------------+// The check table+// ---------------------------------------------------------------------------++export interface DeslopCheck {+ readonly rule: DeslopRule;+ /** Which files the check reads: `.ts`/`.tsx`, or `.css`. */+ readonly surface: "markup" | "stylesheet";+ readonly run: Check;+}++const markup = (rule: DeslopRule, run: Check): DeslopCheck => ({ rule, surface: "markup", run });+const sheet = (rule: DeslopRule, run: Check): DeslopCheck => ({ rule, surface: "stylesheet", run });+/** A class-token check reads markup and `@apply` lists alike. */+const both = (rule: DeslopRule, run: Check) => [markup(rule, run), sheet(rule, run)];++export const DESLOP_CHECKS: readonly DeslopCheck[] = [+ ...both(1, tokenCheck(transitionToken)),+ sheet(1, cssTransitionCheck),+ ...both(2, tokenCheck(hoverTransformToken)),+ sheet(2, cssHoverTransformCheck),+ ...both(3, tokenCheck(durationToken)),+ sheet(3, cssDurationCheck),+ markup(4, nestedRadiusCheck),+ markup(5, clippedBorderCheck),+ ...both(6, statusMarkCheck),+ sheet(6, cssAnimationCheck(/\b(?:pulse|ping)\b/, /\.ui-live\b/)),+ markup(7, tintedIconCheck),+ ...both(8, leftBorderCheck),+ ...both(9, oneHueCheck),+ markup(10, moodBadgeCheck),+ ...both(11, tokenCheck(spinnerToken)),+ sheet(11, cssAnimationCheck(/\bspin\b/, /\.ui-live\b/)),+ ...both(12, tokenCheck(spacingToken)),+ ...both(13, tokenCheck(textSizeToken)),+ ...both(14, tokenCheck(uppercaseToken)),+ markup(14, eyebrowSiblingCheck),+ sheet(14, cssUppercaseCheck),+ markup(15, tabularCheck),+ markup(16, monoLabelCheck),+ sheet(16, cssHookMonoCheck),+ markup(17, nestedSurfaceCheck),+ ...both(18, decorationCheck),+ sheet(18, cssDecorationCheck),+ ...both(19, tokenCheck(shadowToken)),+ ...both(20, tokenCheck(paletteToken)),+ markup(20, hexCheck),+ markup(21, emojiCheck),+ markup(22, pageHeaderCheck),+];++/**+ * Every hit of one rule across the files, both surfaces unless one is named, sorted by file and+ * line. Each occurrence counts once: two identical classes on one line are two hits.+ */+export function deslopHits(+ files: readonly SourceFile[],+ rule: DeslopRule,+ policy: DeslopPolicy,+ surface?: "markup" | "stylesheet",+): DeslopHit[] {+ const hits: DeslopHit[] = [];+ for (const file of files) {+ const analysis = analyzeFile(file);+ for (const check of DESLOP_CHECKS) {+ if (check.rule !== rule || check.surface !== analysis.surface) continue;+ if (surface !== undefined && check.surface !== surface) continue;+ for (const { line, found } of check.run(analysis, policy)) {+ hits.push({ rule, file: file.id, line, found });+ }+ }+ }+ return hits.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1));+}++// ---------------------------------------------------------------------------+// Allowlists+// ---------------------------------------------------------------------------++/**+ * Exempted occurrences, by root-relative file path, then rule: how many hits the file still holds+ * and the wave that removes them — `"features/chat/foo.tsx": { 13: [4, "W6"] }`.+ */+export type DeslopAllowlist = Readonly<+ Record<string, Partial<Readonly<Record<DeslopRule, readonly [count: number, wave: string]>>>>+>;++/**+ * One rule's hits against an allowlist, as lines to print: empty when they agree. A file with no+ * entry must hold no hits; a file with an entry must hold exactly its count — more is new slop,+ * fewer means the entry shrinks in the same change, so the list only tightens.+ */+export function allowlistProblems(+ hits: readonly DeslopHit[],+ rule: DeslopRule,+ allowlist: DeslopAllowlist,+ relOf: (hit: DeslopHit) => string,+): string[] {+ const byFile = new Map<string, DeslopHit[]>();+ for (const found of hits) byFile.set(relOf(found), [...(byFile.get(relOf(found)) ?? []), found]);+ const problems: string[] = [];+ for (const [rel, list] of byFile) {+ const entry = allowlist[rel]?.[rule];+ const where = list.map((f) => `\n ${f.file}:${f.line} ${f.found}`).join("");+ if (entry === undefined) problems.push(`${rel}: ${list.length} new${where}`);+ else if (list.length > entry[0]) {+ problems.push(+ `${rel}: ${list.length} where ${entry[0]} are allowlisted (${entry[1]})${where}`,+ );+ } else if (list.length < entry[0]) {+ problems.push(+ `${rel}: ${list.length} left of ${entry[0]} — shrink the entry to [${list.length}, "${entry[1]}"]`,+ );+ }+ }+ for (const [rel, rules] of Object.entries(allowlist)) {+ const entry = rules[rule];+ if (entry !== undefined && !byFile.has(rel)) {+ problems.push(`${rel}: none left of ${entry[0]} (${entry[1]}) — delete the entry`);+ }+ }+ return problems.sort();+}diff --git a/packages/ui/src/testing/index.ts b/packages/ui/src/testing/index.tsnew file mode 100644index 00000000..72a245f6--- /dev/null+++ b/packages/ui/src/testing/index.ts@@ -0,0 +1,11 @@+/**+ * Test helpers shared by this package's suites and the web app's guard tests: source-root+ * scanning, a CSS reader, theme-file analysis, colour contrast, static rendering and the de-slop+ * rules. Node-only; never imported by application code.+ */+export * from "./color";+export * from "./css";+export * from "./deslop";+export * from "./render";+export * from "./source-roots";+export * from "./theme-tokens";diff --git a/packages/ui/src/testing/render.ts b/packages/ui/src/testing/render.tsnew file mode 100644index 00000000..225c7a21--- /dev/null+++ b/packages/ui/src/testing/render.ts@@ -0,0 +1,30 @@+/**+ * Static render helpers for component tests. The package's suites run in Node with no DOM, the+ * web app's convention: a component is rendered once with `react-dom/server` and the markup is+ * asserted as text. Effects, state transitions and portals are out of reach — keep that logic in+ * pure modules beside the component, where it can be called directly.+ */+import type { ReactElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";++/** The element's initial render as an HTML string. */+export function renderStatic(element: ReactElement): string {+ return renderToStaticMarkup(element);+}++/**+ * Markup with every `class` and `style` attribute removed — what a theme is not allowed to change.+ * Two renders that differ after this differ in structure, text or ARIA, not in styling.+ */+export function markupStructure(html: string): string {+ return html.replace(/\s(?:class|style)="[^"]*"/g, "");+}++/** Every class token on elements in the markup, de-duplicated and sorted. */+export function classTokens(html: string): string[] {+ const tokens = new Set<string>();+ for (const match of html.matchAll(/\sclass="([^"]*)"/g)) {+ for (const token of match[1]!.split(/\s+/)) if (token !== "") tokens.add(token);+ }+ return [...tokens].sort();+}diff --git a/packages/ui/src/testing/source-roots.ts b/packages/ui/src/testing/source-roots.tsnew file mode 100644index 00000000..ad93bbac--- /dev/null+++ b/packages/ui/src/testing/source-roots.ts@@ -0,0 +1,155 @@+/**+ * Source-root scanning for guard tests.+ *+ * A guard that walks one hard-coded directory narrows silently when the code it guards moves: the+ * walk still succeeds, it just visits fewer files, and every "found nothing wrong" assertion stays+ * green over a tree that no longer holds the thing it was written for. The theme work moves+ * components from `packages/web/src` into `packages/ui/src` one wave at a time, so a guard scans a+ * named set of roots and reports, per root, how many files it actually read — a root that yields+ * nothing (a typo, a renamed directory, a package that moved) is a failure, never an empty pass.+ *+ * Node-only (`node:fs`) and framework-free: the caller asserts with its own test runner.+ */+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { basename, join, relative, sep } from "node:path";++/** Root name → absolute directory, e.g. `{ web: ".../packages/web/src", ui: ".../packages/ui/src" }`. */+export type SourceRoots = Readonly<Record<string, string>>;++/** What a guard scans unless it asks otherwise: source and the stylesheets that sit beside it. */+export const DEFAULT_SOURCE_EXTENSIONS: readonly string[] = [".ts", ".tsx", ".css"];++/** Directories never descended into: installed or generated trees are not source. */+const SKIPPED_DIRECTORIES = new Set(["node_modules", "dist", ".vite", "coverage"]);++export interface SourceFile {+ /** The root's key in the {@link SourceRoots} record, e.g. `"web"`. */+ readonly root: string;+ /** Path relative to its root, forward slashes on every platform: `components/ui/icons.tsx`. */+ readonly rel: string;+ /**+ * Path relative to the repository root, forward slashes: `packages/web/src/components/ui/icons.tsx`.+ * The name a guard reports and expects, because it stays unambiguous across roots.+ */+ readonly id: string;+ /** Absolute path, platform separators. */+ readonly path: string;+ /** The file name alone: `icons.tsx`. */+ readonly name: string;+ /** The file's text, read on first access and cached. */+ readonly text: string;+}++export interface RootReport {+ readonly name: string;+ readonly dir: string;+ readonly exists: boolean;+ /** Files with a scanned extension found under the root. */+ readonly files: number;+}++export interface SourceScan {+ /** Every scanned file across every root, sorted by {@link SourceFile.id}. */+ readonly files: readonly SourceFile[];+ /** One report per root, in the order the roots were given. */+ readonly roots: readonly RootReport[];+}++export interface ScanOptions {+ /** The repository root that {@link SourceFile.id} is relative to. */+ readonly repoRoot: string;+ /** File extensions to include, with the dot. Defaults to {@link DEFAULT_SOURCE_EXTENSIONS}. */+ readonly extensions?: readonly string[];+}++const toPosix = (path: string): string => path.split(sep).join("/");++// Plain fields rather than constructor parameter properties, so the module stays erasable-syntax+// TypeScript that Node can also run directly.+class ScannedFile implements SourceFile {+ readonly root: string;+ readonly rel: string;+ readonly id: string;+ readonly path: string;+ #text: string | undefined;++ constructor(root: string, rel: string, id: string, path: string) {+ this.root = root;+ this.rel = rel;+ this.id = id;+ this.path = path;+ }++ get name(): string {+ return basename(this.path);+ }++ get text(): string {+ this.#text ??= readFileSync(this.path, "utf8");+ return this.#text;+ }+}++function walk(dir: string, extensions: readonly string[], out: string[]): void {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!SKIPPED_DIRECTORIES.has(entry.name)) walk(path, extensions, out);+ } else if (entry.isFile() && extensions.some((ext) => entry.name.endsWith(ext))) {+ out.push(path);+ }+ }+}++/**+ * Walks every root and returns its files plus a per-root count. A root that does not exist is+ * reported (`exists: false`, `files: 0`) rather than thrown, so the guard's own "every root was+ * scanned" assertion is what fails — with the root's name in the message.+ */+export function scanSourceRoots(roots: SourceRoots, options: ScanOptions): SourceScan {+ const extensions = options.extensions ?? DEFAULT_SOURCE_EXTENSIONS;+ const files: SourceFile[] = [];+ const reports: RootReport[] = [];+ for (const [name, dir] of Object.entries(roots)) {+ const exists = existsSync(dir) && statSync(dir).isDirectory();+ const paths: string[] = [];+ if (exists) walk(dir, extensions, paths);+ for (const path of paths) {+ files.push(+ new ScannedFile(+ name,+ toPosix(relative(dir, path)),+ toPosix(relative(options.repoRoot, path)),+ path,+ ),+ );+ }+ reports.push({ name, dir, exists, files: paths.length });+ }+ files.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+ return { files, roots: reports };+}++/**+ * One line per root that yielded no files, naming the root, its directory and why — empty when+ * every root was scanned. Guards assert this equals `[]`.+ */+export function unscannedRoots(scan: SourceScan): string[] {+ return scan.roots+ .filter((root) => root.files === 0)+ .map((root) =>+ root.exists+ ? `${root.name} (${root.dir}): no source files found`+ : `${root.name} (${root.dir}): directory does not exist`,+ );+}++/** The scanned file with this repo-relative id, or `undefined`. */+export function findSourceFile(scan: SourceScan, id: string): SourceFile | undefined {+ return scan.files.find((file) => file.id === id);+}++/** Every scanned file with this file name, across all roots — the input to a "one home" check. */+export function filesNamed(scan: SourceScan, name: string): SourceFile[] {+ return scan.files.filter((file) => file.name === name);+}diff --git a/packages/ui/src/testing/theme-tokens.ts b/packages/ui/src/testing/theme-tokens.tsnew file mode 100644index 00000000..bde9a52a--- /dev/null+++ b/packages/ui/src/testing/theme-tokens.ts@@ -0,0 +1,407 @@+/**+ * Reading a theme file (`src/themes/<id>.css`) the way the token contract describes it, for the+ * contract and contrast tests — and for anyone filling a theme who wants the list of what is+ * still missing without running the suite.+ *+ * A theme file is one `@layer ui-theme` block with a base rule and a dark rule on fixed+ * selectors (tokens.ts, `themes/github.css`):+ *+ * default theme base `:root, :root[data-theme="github"]` dark `:root.dark, :root[data-theme="github"].dark`+ * any other base `:root[data-theme="<id>"]` dark `:root[data-theme="<id>"].dark`+ *+ * The base rule declares every contract name with its light value, plus the gray bridge that+ * re-points Tailwind's own palette variables. The dark rule matches the same root and declares+ * only what dark changes, so a mode is the base rule overlaid with that mode's own rule (light has+ * none of its own). Nothing else is a token.+ *+ * After the theme block, one `@layer ui-accent` block holds the theme's own accent presets+ * (tokens.ts, `ACCENT_PRESETS`), each on the theme's root with `[data-accent="<id>"]` — the+ * default theme's on a bare root as well, spelled `:root:not([data-theme])` so it never matches+ * another theme's root — and optionally a `.dark` rule that lifts the preset for dark mode:+ *+ * default theme light `:root:not([data-theme])[data-accent="x"], :root[data-theme="github"][data-accent="x"]`+ * any other light `:root[data-theme="<id>"][data-accent="x"]` dark `…[data-accent="x"].dark`+ *+ * A preset's light rule sets `--ui-accent` and nothing outside the accent group; its dark rule+ * declares only what dark changes. In a mode a preset overlays the theme's values for that mode.+ * The accent tokens a preset leaves alone must follow it anyway: the theme derives them from+ * `--ui-accent` (a `var(--ui-accent)` in their value), or — for the label ink alone — the+ * theme's own ink for the mode, whose pairing with every preset the contrast suite measures.+ * Primer's presets set all six literally (the app's pixels are pinned), which satisfies this+ * trivially.+ */+import { DEFAULT_THEME_ID, THEME_MODES, TOKEN_GROUPS, TOKEN_NAMES } from "../tokens";+import type { ThemeId, ThemeModeName } from "../tokens";+import { parseCssRules, selectorList } from "./css";+import type { CssDeclaration } from "./css";++/** The layer every theme block lives in, so a user accent preset (`@layer ui-accent`) beats it. */+export const THEME_LAYER = "@layer ui-theme";++/** The layer a theme's accent presets live in: after `ui-theme`, so a preset beats the dark rule. */+export const ACCENT_LAYER = "@layer ui-accent";++/** The six names a preset sets: the contract's accent group, and nothing outside it. */+export const ACCENT_TOKEN_NAMES: readonly string[] =+ TOKEN_GROUPS.find((group) => group.id === "color-accent")?.names ?? [];++/** Tailwind palette variables a theme may re-point: the gray bridge, plus white and black. */+export const BRIDGE_VARIABLE = /^--color-(?:white|black|gray-(?:50|[1-9]00|950))$/;++/** The eleven gray steps. A non-default theme re-points all of them, in its base rule (see below). */+export const GRAY_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950] as const;++/** Marker a stub theme file carries in its header comment until its tokens are written. */+export const STUB_MARKER = "Stub:";++const CONTRACT = new Set<string>(TOKEN_NAMES);++/** The canonical selector list of a theme's rule for one mode. */+export function themeSelectors(themeId: ThemeId, mode: ThemeModeName): string[] {+ const attr = `:root[data-theme="${themeId}"]`;+ const suffix = mode === "dark" ? ".dark" : "";+ return themeId === DEFAULT_THEME_ID+ ? [`:root${suffix}`, `${attr}${suffix}`]+ : [`${attr}${suffix}`];+}++/** The canonical selector list of one accent preset's rule for one mode. */+export function accentSelectors(themeId: ThemeId, presetId: string, mode: ThemeModeName): string[] {+ const attr = `[data-accent="${presetId}"]`;+ const suffix = mode === "dark" ? ".dark" : "";+ const own = `:root[data-theme="${themeId}"]${attr}${suffix}`;+ return themeId === DEFAULT_THEME_ID ? [`:root:not([data-theme])${attr}${suffix}`, own] : [own];+}++/** One preset's rules: the light rule (it applies in both modes) and the dark rule alone. */+export interface AccentPresetRules {+ readonly light: ReadonlyMap<string, string>;+ readonly dark: ReadonlyMap<string, string>;+}++export interface ThemeFileAnalysis {+ readonly themeId: ThemeId;+ /**+ * Custom properties each canonical rule declares itself, name → value: `light` is the base rule+ * (it applies in both modes), `dark` the dark rule alone. {@link modeDeclarations} gives what a+ * mode resolves to.+ */+ readonly modes: Readonly<Record<ThemeModeName, ReadonlyMap<string, string>>>;+ /** The theme's accent presets, id → rules, in the order the file declares them. */+ readonly accents: ReadonlyMap<string, AccentPresetRules>;+ /** True once any rule in the file declares a `--ui-*` property. */+ readonly declaresTokens: boolean;+ /** True while the header still carries {@link STUB_MARKER} and nothing is declared. */+ readonly isStub: boolean;+ /** Shape problems: token declarations outside the canonical rules or layer, duplicates. */+ readonly structure: readonly string[];+}++const sameSet = (a: readonly string[], b: readonly string[]) =>+ a.length === b.length && a.every((s) => b.includes(s));++/** The one preset id a selector list names, or null when it names none (or several). */+function presetOf(selectors: readonly string[]): string | null {+ const ids = new Set(+ selectors.map((selector) => /\[data-accent="([\w-]+)"\]/.exec(selector)?.[1] ?? ""),+ );+ const [id, ...rest] = [...ids];+ return id !== undefined && id !== "" && rest.length === 0 ? id : null;+}++export function analyzeThemeFile(css: string, themeId: ThemeId): ThemeFileAnalysis {+ const rules = parseCssRules(css);+ const modes = { light: new Map<string, string>(), dark: new Map<string, string>() };+ const firstLine = { light: new Map<string, number>(), dark: new Map<string, number>() };+ const accents = new Map<string, { light: Map<string, string>; dark: Map<string, string> }>();+ const structure: string[] = [];+ let declaresTokens = false;++ for (const rule of rules) {+ const custom = rule.declarations.filter((d: CssDeclaration) => d.name.startsWith("--"));+ if (rule.declarations.some((d) => d.name.startsWith("--ui-"))) declaresTokens = true;+ if (custom.length === 0) continue;+ const selectors = selectorList(rule.selector);++ const preset = presetOf(selectors);+ if (preset !== null) {+ const mode = THEME_MODES.find((m) => sameSet(selectors, accentSelectors(themeId, preset, m)));+ if (mode === undefined) {+ structure.push(+ `line ${rule.line}: \`${rule.selector}\` declares ${custom[0]!.name} — a preset's rules are ` ++ `${THEME_MODES.map((m) => `\`${accentSelectors(themeId, preset, m).join(", ")}\``).join(" / ")}`,+ );+ continue;+ }+ const layered =+ rule.parents.length === 0 && rule.atRules.length === 1 && rule.atRules[0] === ACCENT_LAYER;+ if (!layered) {+ const where = [...rule.atRules, ...rule.parents].join(" › ") || "top level";+ structure.push(+ `line ${rule.line}: the ${preset} preset's ${mode} rule sits in ${where}; it must sit ` ++ `directly in \`${ACCENT_LAYER}\` so it overrides the theme's dark rule by layer order`,+ );+ }+ const entry = accents.get(preset) ?? { light: new Map(), dark: new Map() };+ for (const declaration of custom) {+ if (entry[mode].has(declaration.name)) {+ structure.push(+ `line ${declaration.line}: ${declaration.name} is declared again for the ${preset} preset (${mode}); the later one silently wins`,+ );+ }+ entry[mode].set(declaration.name, declaration.value);+ }+ accents.set(preset, entry);+ continue;+ }++ const mode = THEME_MODES.find((m) => sameSet(selectors, themeSelectors(themeId, m)));+ if (mode === undefined) {+ structure.push(+ `line ${rule.line}: \`${rule.selector}\` declares ${custom[0]!.name} — tokens belong in the ` ++ `canonical rules (${THEME_MODES.map((m) => `\`${themeSelectors(themeId, m).join(", ")}\``).join(" / ")})`,+ );+ continue;+ }+ if (rule.parents.length > 0 || rule.atRules.length !== 1 || rule.atRules[0] !== THEME_LAYER) {+ const where = [...rule.atRules, ...rule.parents].join(" › ") || "top level";+ structure.push(+ `line ${rule.line}: the ${mode} rule sits in ${where}; it must sit directly in \`${THEME_LAYER}\` ` ++ `so the user's accent presets (\`@layer ui-accent\`) override it`,+ );+ }+ for (const declaration of custom) {+ const seen = firstLine[mode].get(declaration.name);+ if (seen !== undefined) {+ structure.push(+ `line ${declaration.line}: ${declaration.name} is declared again for ${mode} (first at line ${seen}); the later one silently wins`,+ );+ } else firstLine[mode].set(declaration.name, declaration.line);+ modes[mode].set(declaration.name, declaration.value);+ }+ }++ return {+ themeId,+ modes,+ accents,+ declaresTokens,+ isStub: !declaresTokens && css.includes(STUB_MARKER),+ structure,+ };+}++/** A value that follows `--ui-accent`: it reads the token (with or without a fallback). */+const DERIVED_FROM_ACCENT = /var\(\s*--ui-accent\s*[,)]/;++/**+ * Problems with a theme's accent presets against the list tokens.ts declares for it: the ids+ * and their order, a light rule that sets `--ui-accent` and only accent names, a dark rule that+ * sets only accent names and only what dark changes, values that resolve, every accent token a+ * preset leaves alone derived from `--ui-accent` by the theme (the label ink excepted — the+ * contrast suite measures it against every preset), and the swatch tokens.ts carries for each+ * preset equal to the `--ui-accent` its light rule sets.+ */+export function accentProblems(+ analysis: ThemeFileAnalysis,+ expected: readonly { readonly id: string; readonly swatch: string }[],+): string[] {+ const problems: string[] = [];+ const declared = [...analysis.accents.keys()];+ const expectedIds = expected.map((preset) => preset.id);+ if (declared.join(",") !== expectedIds.join(",")) {+ problems.push(+ `the presets are [${declared.join(", ")}]; tokens.ts lists [${expectedIds.join(", ")}] in that order`,+ );+ }+ for (const { id, swatch } of expected) {+ const rules = analysis.accents.get(id);+ if (rules === undefined) continue;+ if (!rules.light.has("--ui-accent")) {+ problems.push(`${id}: the light rule does not set --ui-accent`);+ }+ for (const mode of THEME_MODES) {+ // A token the preset does not set in this mode takes the theme's value for the mode, which+ // must be a derivation of `--ui-accent` — otherwise the theme's own hover, wash or line+ // would show under the preset's accent.+ const themeValues = modeDeclarations(analysis, mode);+ for (const name of ACCENT_TOKEN_NAMES) {+ if (name === "--ui-accent" || name === "--ui-accent-fg") continue;+ if (rules.light.has(name) || (mode === "dark" && rules.dark.has(name))) continue;+ const value = themeValues.get(name);+ if (value === undefined || !DERIVED_FROM_ACCENT.test(value)) {+ problems.push(+ `${id}: ${name} (${mode}) is neither set by the preset nor derived from --ui-accent by the theme (${value ?? "undeclared"})`,+ );+ }+ }+ }+ for (const [mode, values] of [+ ["light", rules.light],+ ["dark", rules.dark],+ ] as const) {+ for (const [name, value] of values) {+ if (!ACCENT_TOKEN_NAMES.includes(name)) {+ problems.push(`${id}: the ${mode} rule sets ${name}, which is not an accent token`);+ }+ if (value === "") problems.push(`${id}: ${name} (${mode}) has an empty value`);+ for (const ref of value.matchAll(/var\(\s*(--[\w-]+)/g)) {+ if (!CONTRACT.has(ref[1]!)) {+ problems.push(`${id}: ${name} (${mode}) reads ${ref[1]}, not a contract token`);+ }+ }+ if (mode === "dark" && rules.light.get(name) === value) {+ problems.push(+ `${id}: the dark rule repeats ${name}: ${value} — drop it from the dark rule`,+ );+ }+ }+ }+ const accent = rules.light.get("--ui-accent");+ if (accent !== undefined && accent !== swatch) {+ problems.push(+ `${id}: tokens.ts carries the swatch ${swatch}, the light rule sets --ui-accent: ${accent}`,+ );+ }+ }+ return problems;+}++/**+ * What one mode of a theme defines within its own file: the base rule, overlaid in dark with the+ * dark rule. `:root.dark` also matches the base rule, so a name the dark rule leaves out keeps its+ * base value.+ */+export function modeDeclarations(+ analysis: ThemeFileAnalysis,+ mode: ThemeModeName,+): ReadonlyMap<string, string> {+ return mode === "light"+ ? analysis.modes.light+ : new Map([...analysis.modes.light, ...analysis.modes.dark]);+}++/**+ * Contract problems for one mode — the base rule plus that mode's own: missing names, names+ * outside the contract, bad values.+ */+export function contractProblems(analysis: ThemeFileAnalysis, mode: ThemeModeName): string[] {+ const declared = modeDeclarations(analysis, mode);+ const problems: string[] = [];+ const missing = TOKEN_NAMES.filter((name) => !declared.has(name));+ if (missing.length > 0) {+ problems.push(`missing ${missing.length} of ${TOKEN_NAMES.length}: ${missing.join(", ")}`);+ }+ for (const [name, value] of declared) {+ if (name.startsWith("--ui-") && !CONTRACT.has(name)) {+ problems.push(`${name} is not in tokens.ts — add it to the contract or remove it`);+ } else if (!name.startsWith("--ui-") && !BRIDGE_VARIABLE.test(name)) {+ problems.push(+ `${name} is neither a contract token nor a bridged Tailwind palette variable (${BRIDGE_VARIABLE})`,+ );+ }+ if (value === "") problems.push(`${name} has an empty value`);+ for (const ref of value.matchAll(/var\(\s*(--[\w-]+)/g)) {+ const target = ref[1]!;+ if (target.startsWith("--ui-") && !CONTRACT.has(target)) {+ problems.push(`${name} reads ${target}, which is not a contract token`);+ }+ }+ }+ if (analysis.themeId !== DEFAULT_THEME_ID) {+ // The default theme's rules match every <html> (`:root`, `:root.dark`), so a gray step this+ // theme leaves alone renders in the default theme's value — the palette classes the app+ // still spells would mix two themes on one screen.+ const grays = GRAY_STEPS.filter((step) => !declared.has(`--color-gray-${step}`));+ if (grays.length > 0) {+ problems.push(+ `the gray bridge is incomplete — re-point ${grays.map((s) => `--color-gray-${s}`).join(", ")}`,+ );+ }+ }+ return problems;+}++/**+ * Dark-rule declarations that repeat the base rule's value, as `name: value`. The base rule already+ * gives the name that value in dark, so a repeat is a second home for one value — the two drift the+ * first time an edit reaches one of them. The dark rule declares only what dark changes.+ */+export function darkRepeats(analysis: ThemeFileAnalysis): string[] {+ return [...analysis.modes.dark]+ .filter(([name, value]) => analysis.modes.light.get(name) === value)+ .map(([name, value]) => `${name}: ${value}`);+}++/**+ * The value a custom property resolves to for `mode` of a theme, following the cascade the+ * selectors produce: an applied accent preset's rules first (its dark rule, then its light one —+ * they sit in `ui-accent`, after every theme rule), then the mode's own rule, then (dark only)+ * the same theme's base rule, which the dark `<html>` also matches, then the default theme's+ * rules, which match every `<html>`. (Against the default theme's dark rule, another theme's base+ * rule ties on specificity and wins because the theme files are imported after `github.css`.)+ * `var()` references are substituted recursively, fallbacks honoured. `null` when unresolvable.+ */+export function resolveThemeValue(+ name: string,+ mode: ThemeModeName,+ theme: ThemeFileAnalysis,+ defaultTheme: ThemeFileAnalysis,+ preset: AccentPresetRules | null = null,+): string | null {+ const scopes: ReadonlyMap<string, string>[] = [];+ const push = (analysis: ThemeFileAnalysis) => {+ scopes.push(analysis.modes[mode]);+ if (mode === "dark") scopes.push(analysis.modes.light);+ };+ if (preset !== null) {+ if (mode === "dark") scopes.push(preset.dark);+ scopes.push(preset.light);+ }+ push(theme);+ if (defaultTheme !== theme) push(defaultTheme);++ const lookup = (key: string) => {+ for (const scope of scopes) {+ const value = scope.get(key);+ if (value !== undefined) return value;+ }+ return undefined;+ };++ /** Replaces every `var()` in `value`, left to right; `depth` counts reference hops (cycle guard). */+ const substitute = (value: string, depth: number): string | null => {+ if (depth > 32) return null;+ let out = value;+ for (;;) {+ const at = out.indexOf("var(");+ if (at === -1) return out;+ let parens = 0;+ let end = -1;+ for (let i = at + 3; i < out.length; i++) {+ if (out[i] === "(") parens++;+ else if (out[i] === ")" && --parens === 0) {+ end = i;+ break;+ }+ }+ if (end === -1) return null;+ const inner = out.slice(at + 4, end);+ const comma = inner.indexOf(",");+ const ref = (comma === -1 ? inner : inner.slice(0, comma)).trim();+ const fallback = comma === -1 ? undefined : inner.slice(comma + 1).trim();+ const found = lookup(ref);+ const replacement =+ found !== undefined+ ? substitute(found, depth + 1)+ : fallback !== undefined+ ? substitute(fallback, depth + 1)+ : null;+ if (replacement === null) return null;+ out = out.slice(0, at) + replacement + out.slice(end + 1);+ }+ };++ const raw = lookup(name);+ return raw === undefined ? null : substitute(raw, 0);+}diff --git a/packages/ui/src/theme.css b/packages/ui/src/theme.cssnew file mode 100644index 00000000..d64bb20a--- /dev/null+++ b/packages/ui/src/theme.css@@ -0,0 +1,506 @@+/**+ * The theme foundation every consumer imports right after `@import "tailwindcss"`:+ *+ * @import "tailwindcss";+ * @import "@prismshadow/penguin-ui/theme.css";+ * @import "@prismshadow/penguin-ui/themes/github.css"; (then modern.css, geek.css)+ * @import "@prismshadow/penguin-ui/fonts.css";+ *+ * What lives here is theme-independent: the `dark` variant, the cascade layer order, the bridge+ * from the `--ui-*` token contract (tokens.ts) to Tailwind utilities, the base rules that read+ * tokens, the motion rules behind the `data-presence` / `data-backdrop` / `data-reveal` /+ * `data-layout-motion` attributes, and the depth ladder the `ui-tree` recipes measure with. Token+ * VALUES live only in `themes/*.css`, and so do the user's accent presets: each theme lists its+ * own, in `@layer ui-accent`, scoped to that theme (tokens.ts, `ACCENT_PRESETS`).+ *+ * Attributes on <html>: `class="dark"` (mode), `data-theme` (absent = github), `data-accent`+ * (absent = the theme's own accent; an id the active theme does not list paints nothing, which+ * is the same), `data-font-latin` / `data-font-cjk` (absent = the theme's own faces; the `ui-font`+ * layer at the end resolves a chosen face), `data-motion="reduced"` (the gallery's switch; the+ * app answers the media query instead). The pre-paint script in boot.ts sets all but the last+ * before the first frame, and the root font-size with them; the app's theme provider keeps them+ * in sync afterwards.+ */++/* Dark mode is the `dark` class on <html>, not the media query: the user can pin either mode. */+@custom-variant dark (&:where(.dark, .dark *));++/* Appended after Tailwind's own `theme, base, components, utilities`. A theme's blocks live in+ ui-theme and its accent presets in ui-accent, so a preset beats the theme's `.dark` block by+ layer order alone — `:root[data-theme="x"].dark` would otherwise tie with+ `:root[data-theme="x"][data-accent="blue"]` on specificity and win by coming later. The token+ blocks and the presets declare custom properties only, so sitting after `utilities` never lets+ them override a utility's declaration. The one thing in ui-theme that does override utilities+ is a theme's style-hook recipes (hooks.ts), and they sit there for exactly that: `.ui-live`+ re-times its host's `animate-spin`, `.ui-glass` replaces its host's opaque fill, `.ui-shell`+ re-paints its host's columns, `.ui-field` re-lays its host's row. The user's font pairing+ lives in ui-font, last: a chosen face must beat every theme rule, the dark one included,+ whatever its specificity, and a layer after the theme's does that without a selector race. */+@layer ui-theme, ui-accent, ui-font;++/*+ * The bridge. `inline` makes each utility reference `var(--ui-*)` directly instead of the+ * Tailwind theme variable, so a `[data-theme]` or `.dark` set on a subtree resolves at the element+ * rather than being frozen at :root.+ *+ * Caveats, written down where they bite:+ * 1. Tailwind emits only the theme variables some utility uses, so bridging an unused scale step+ * costs nothing.+ * 2. `rounded` (bare) and `rounded-full` are literals (`0.25rem`, `calc(infinity * 1px)`), not+ * theme variables, so neither follows the theme. Components use `rounded-sm` (same 0.25rem) and+ * `rounded-[var(--ui-radius-pill)]` for pills, and keep `rounded-full` for state dots and the+ * switch knob — which is how a square theme keeps round dots.+ * 3. Bare `border` is a literal 1px; thinner-looking lines come from `--ui-line` alpha, not width.+ * 4. Shadows bridged here lose Tailwind's `--tw-shadow-color` hook (`shadow-lg shadow-black/20`);+ * no call site combines the two today.+ * 5. `--ui-inset` is aliased as `surface-inset`, not `inset`: a `--color-inset` would make+ * Tailwind read the existing static `ring-inset` utility as a ring COLOUR as well, and emit both.+ * 6. `--spacing` is Tailwind v4's one spacing multiplier: every spacing and size utility is+ * `calc(var(--spacing) * n)` (`h-8`, `px-2`, `gap-3`, `size-4`, `w-64`, `leading-5`, …), so+ * pointing it at `--ui-space-unit` scales all of them per theme. Primer's unit is Tailwind's+ * stock 0.25rem, so Primer moves no pixel; Frost's is larger and Console's smaller. Literal+ * lengths (`w-[24rem]`, `max-w-2xl`) do not follow it, by design.+ * 7. `text-xs` and `text-sm` read the small and body rungs (size and line-height). Primer's rungs+ * equal Tailwind's stock values, so again nothing moves there; the other themes set their own.+ * `text-base` and up keep Tailwind's scale: no rung token names them.+ */+@theme inline {+ /* Surfaces */+ --color-canvas: var(--ui-canvas);+ --color-surface: var(--ui-surface);+ --color-surface-muted: var(--ui-surface-muted);+ --color-surface-inset: var(--ui-inset);+ --color-overlay: var(--ui-overlay);++ /* Text */+ --color-fg: var(--ui-fg);+ --color-fg-emphasis: var(--ui-fg-emphasis);+ --color-fg-muted: var(--ui-fg-muted);+ --color-fg-subtle: var(--ui-fg-subtle);+ --color-link: var(--ui-fg-link);+ --color-link-hover: var(--ui-fg-link-hover);++ /* Lines */+ --color-line: var(--ui-line);+ --color-line-muted: var(--ui-line-muted);+ --color-line-emphasis: var(--ui-line-emphasis);+ --color-divider: var(--ui-divider);++ /* Accent */+ --color-accent: var(--ui-accent);+ --color-accent-hover: var(--ui-accent-hover);+ --color-accent-active: var(--ui-accent-active);+ --color-accent-fg: var(--ui-accent-fg);+ --color-accent-muted: var(--ui-accent-muted);+ --color-accent-line: var(--ui-accent-line);++ /* The switch: bg-switch-track (off), bg-switch-knob (the knob on it), bg-switch-knob-on (the+ knob on the accent), border-switch-knob-line (the knob's hairline edge). */+ --color-switch-track: var(--ui-switch-track);+ --color-switch-knob: var(--ui-switch-knob);+ --color-switch-knob-on: var(--ui-switch-knob-on);+ --color-switch-knob-line: var(--ui-switch-knob-line);++ /* Semantic tones: text-tone-danger-fg, bg-tone-success-bg, border-tone-attention-line, … */+ --color-tone-success-fg: var(--ui-tone-success-fg);+ --color-tone-success-bg: var(--ui-tone-success-bg);+ --color-tone-success-line: var(--ui-tone-success-line);+ --color-tone-success-emphasis: var(--ui-tone-success-emphasis);+ --color-tone-success-emphasis-fg: var(--ui-tone-success-emphasis-fg);+ --color-tone-attention-fg: var(--ui-tone-attention-fg);+ --color-tone-attention-bg: var(--ui-tone-attention-bg);+ --color-tone-attention-line: var(--ui-tone-attention-line);+ --color-tone-attention-emphasis: var(--ui-tone-attention-emphasis);+ --color-tone-attention-emphasis-fg: var(--ui-tone-attention-emphasis-fg);+ --color-tone-danger-fg: var(--ui-tone-danger-fg);+ --color-tone-danger-bg: var(--ui-tone-danger-bg);+ --color-tone-danger-line: var(--ui-tone-danger-line);+ --color-tone-danger-emphasis: var(--ui-tone-danger-emphasis);+ --color-tone-danger-emphasis-fg: var(--ui-tone-danger-emphasis-fg);+ --color-tone-done-fg: var(--ui-tone-done-fg);+ --color-tone-done-bg: var(--ui-tone-done-bg);+ --color-tone-done-line: var(--ui-tone-done-line);+ --color-tone-done-emphasis: var(--ui-tone-done-emphasis);+ --color-tone-done-emphasis-fg: var(--ui-tone-done-emphasis-fg);+ --color-tone-neutral-fg: var(--ui-tone-neutral-fg);+ --color-tone-neutral-bg: var(--ui-tone-neutral-bg);+ --color-tone-neutral-line: var(--ui-tone-neutral-line);+ --color-tone-neutral-emphasis: var(--ui-tone-neutral-emphasis);+ --color-tone-neutral-emphasis-fg: var(--ui-tone-neutral-emphasis-fg);+ --color-tone-info-fg: var(--ui-tone-info-fg);+ --color-tone-info-bg: var(--ui-tone-info-bg);+ --color-tone-info-line: var(--ui-tone-info-line);+ --color-tone-info-emphasis: var(--ui-tone-info-emphasis);+ --color-tone-info-emphasis-fg: var(--ui-tone-info-emphasis-fg);++ /* Charts: identity colours, not judgement */+ --color-chart-1: var(--ui-chart-1);+ --color-chart-2: var(--ui-chart-2);+ --color-chart-3: var(--ui-chart-3);+ --color-chart-4: var(--ui-chart-4);+ --color-chart-5: var(--ui-chart-5);+ --color-chart-6: var(--ui-chart-6);+ --color-chart-7: var(--ui-chart-7);+ --color-chart-8: var(--ui-chart-8);+ --color-chart-ref: var(--ui-chart-ref);+ --color-chart-cache-read: var(--ui-chart-cache-read);+ --color-chart-cache-write: var(--ui-chart-cache-write);+ --color-chart-output: var(--ui-chart-output);+ --color-chart-grid: var(--ui-chart-grid);+ --color-chart-axis: var(--ui-chart-axis);++ /* Tailwind's own namespaces follow the theme, so existing classes need no edits. `font-sans` is+ the reading face a bubble or a prose block opts into; `font-ui` the chrome's, which `body`+ already sets and a component names only to opt back out of a reading surface. */+ --font-sans: var(--ui-font-sans);+ --font-ui: var(--ui-font-ui);+ --font-mono: var(--ui-font-mono);+ --font-display: var(--ui-font-display);++ /* Density: caveat 6. */+ --spacing: var(--ui-space-unit);++ /* Type rungs: caveat 7. */+ --text-xs: var(--ui-text-small-size);+ --text-xs--line-height: var(--ui-text-small-lh);+ --text-sm: var(--ui-text-body-size);+ --text-sm--line-height: var(--ui-text-body-lh);++ --radius-xs: var(--ui-radius-xs);+ --radius-sm: var(--ui-radius-sm);+ --radius-md: var(--ui-radius-md);+ --radius-lg: var(--ui-radius-lg);+ --radius-xl: var(--ui-radius-xl);+ /* The contract stops at xl; the two larger steps the app uses (the mobile sheet's 2xl, one 3xl)+ keep Tailwind's stock ratios to xl — 1rem and 1.5rem against 0.75rem — so they follow a+ theme's radius, including all the way down to 0. */+ --radius-2xl: calc(var(--ui-radius-xl) * 4 / 3);+ --radius-3xl: calc(var(--ui-radius-xl) * 2);+ /* The pressable control's shape (Button, IconButton, Segmented, the Switch track, SendButton):+ `rounded-control`. Its own token because a theme's controls and boxes differ in kind, not in+ scale step — Frost's controls are pills while its boxes stay on the scale. */+ --radius-control: var(--ui-radius-control);++ --shadow-sm: var(--ui-shadow-raised);+ --shadow-lg: var(--ui-shadow-overlay);+ --shadow-xl: var(--ui-shadow-modal);+ --shadow-2xl: var(--ui-shadow-drawer);++ --default-transition-duration: var(--ui-dur-fast);+}++@layer base {+ :root {+ color-scheme: light;+ /* Kept for one wave so branches still spelling `var(--accent-bg)` keep rendering; new code+ writes `bg-accent` / `text-accent-fg`. Delete once no source reads them. */+ --accent-bg: var(--ui-accent);+ --accent-fg: var(--ui-accent-fg);+ }+ .dark {+ color-scheme: dark;+ }+ body {+ background-color: var(--ui-canvas);+ color: var(--ui-fg);+ font-family: var(--ui-font-ui);+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ }+ code,+ pre,+ kbd {+ font-family: var(--ui-font-mono);+ }+ /* What a pressable element may animate: colour, lines, opacity and the focus/elevation shadow,+ never geometry (no radius, size or position easing on hover). Only the property list is set+ here, so nothing animates until a component adds a duration (`duration-150`), and any+ `transition-*` utility replaces the list. `:where()` keeps the rule at zero specificity. */+ :where(button, a, [role="button"], [role="tab"]) {+ transition-property: color, background-color, border-color, opacity, box-shadow;+ }+ /* Keyboard focus for buttons and links; text controls draw their own ring and do not stack this one. */+ button:focus-visible,+ a:focus-visible,+ [role="tab"]:focus-visible,+ summary:focus-visible {+ outline: var(--ui-focus-ring);+ outline-offset: var(--ui-focus-ring-offset);+ }+ ::selection {+ background: var(--ui-selection-bg);+ }+ * {+ scrollbar-width: var(--ui-scrollbar-w);+ scrollbar-color: var(--ui-scrollbar-thumb) var(--ui-scrollbar-track);+ }++ /*+ * Motion. A component never writes a duration, an easing, a keyframe or a transform for these:+ * it sets one attribute and the active theme's motion tokens decide how the change looks —+ * Primer a quick fade with a few px of slide, Frost a soft spring with a scale-up and a blur-in,+ * Console a `steps()` jump. Every rule reads tokens only, and every one is switched off further+ * down under `data-motion="reduced"` and the reduced-motion media query.+ *+ * - `data-presence="enter" | "exit"` on a transient layer (menu, popover, tooltip, dialog card,+ * toast, dock panel), with `data-side` naming the edge it comes from: `top` (a menu under its+ * trigger), `bottom` (a toast), `left` / `right` (a dock), `center` (a dialog). The `exit`+ * state stays mounted until `animationend`; with `animation-name: none` (reduced motion, or a+ * theme that jumps) the owner unmounts at once.+ * - `data-backdrop="enter" | "exit"`: the dialog's scrim, opacity only.+ * - `data-reveal`: content that just appeared inside a settled surface — a streamed chunk of+ * text, a new tool row — fades (and de-blurs) in once; put it on the appended element only.+ * - `data-layout-motion`: an element whose size changes between states, the sidebar's width or a+ * disclosure's `grid-template-rows: 0fr ↔ 1fr`; the theme sets the duration and the curve.+ *+ * The presence keyframes move the element through the individual `translate` and `scale`+ * properties, never `transform`, so a layer that positions itself with a `transform` keeps it+ * while it animates; Tailwind v4's `translate-*` and `scale-*` utilities set the SAME individual+ * properties and would be overridden for the animation's duration, so a presence box carries+ * neither. Fill modes matter for the glass inside: an entrance fills `backwards` and a reveal+ * too, so once they finish no animated `filter` (not even `blur(0)`) stays on the box — a held+ * filter would make the box a backdrop root and the `.ui-glass` panel inside it would blur+ * nothing; only the exit fills `forwards`, holding its end state until the owner unmounts it.+ * `--_shift-x` / `--_shift-y` are private to these rules (not tokens).+ */+ [data-presence] {+ --_shift-x: 0px;+ --_shift-y: 0px;+ transform-origin: center;+ }+ [data-presence][data-side="top"] {+ --_shift-y: calc(-1 * var(--ui-enter-shift));+ transform-origin: top center;+ }+ [data-presence][data-side="bottom"] {+ --_shift-y: var(--ui-enter-shift);+ transform-origin: bottom center;+ }+ [data-presence][data-side="left"] {+ --_shift-x: calc(-1 * var(--ui-enter-shift));+ transform-origin: left center;+ }+ [data-presence][data-side="right"] {+ --_shift-x: var(--ui-enter-shift);+ transform-origin: right center;+ }+ [data-presence="enter"] {+ animation: ui-presence-enter var(--ui-dur-enter) var(--ui-ease-enter) backwards;+ }+ [data-presence="exit"] {+ animation: ui-presence-exit var(--ui-dur-exit) var(--ui-ease-exit) forwards;+ pointer-events: none;+ }+ @keyframes ui-presence-enter {+ from {+ opacity: 0;+ translate: var(--_shift-x) var(--_shift-y);+ scale: var(--ui-enter-scale);+ filter: blur(var(--ui-enter-blur));+ }+ }+ @keyframes ui-presence-exit {+ to {+ opacity: 0;+ translate: var(--_shift-x) var(--_shift-y);+ scale: var(--ui-enter-scale);+ filter: blur(var(--ui-enter-blur));+ }+ }++ [data-backdrop="enter"] {+ animation: ui-backdrop-enter var(--ui-dur-enter) var(--ui-ease-overlay-in) backwards;+ }+ [data-backdrop="exit"] {+ animation: ui-backdrop-exit var(--ui-dur-exit) var(--ui-ease-overlay-out) forwards;+ pointer-events: none;+ }+ @keyframes ui-backdrop-enter {+ from {+ opacity: 0;+ }+ }+ @keyframes ui-backdrop-exit {+ to {+ opacity: 0;+ }+ }++ [data-reveal] {+ animation: ui-reveal var(--ui-dur-reveal) var(--ui-ease-out) backwards;+ }+ @keyframes ui-reveal {+ from {+ opacity: 0;+ filter: blur(var(--ui-reveal-blur));+ }+ }++ [data-layout-motion] {+ transition-property:+ width, height, min-width, max-width, flex-basis, grid-template-rows, grid-template-columns;+ transition-duration: var(--ui-dur-layout);+ transition-timing-function: var(--ui-ease-layout);+ }+}++/* No motion: the gallery's switch on the root, then the user's system preference. Live signals+ go still as well (a static caret block, an arc that does not turn), so a reduced page has no+ movement at all. Nothing is left at a zero duration or paused on a first frame (an entrance+ paused on its first frame would be invisible): each attribute computes to `animation-name:+ none`, the element shows its end state at once, and that is what the presence owner checks+ before unmounting an exit without waiting. These rules sit in no layer on purpose: an unlayered+ declaration beats every layer, so they also silence a theme's own `.ui-live` recipes in+ `ui-theme`, which would otherwise out-rank a rule in `base` whatever its specificity. */+:root[data-motion="reduced"] :is([data-presence], [data-backdrop], [data-reveal], .ui-live) {+ animation: none;+}+:root[data-motion="reduced"] [data-layout-motion] {+ transition: none;+}+/* The `ui-activity` recipes animate the running row (Frost's halo), a slot inside it (Frost's+ label highlight) and a slot's pseudo-elements (Console's block bar), so all three are named:+ each holds its declared, unanimated state instead — a still halo, plain ink, one fill. */+:root[data-motion="reduced"] :is(.ui-activity, .ui-activity *),+:root[data-motion="reduced"] :is(.ui-activity, .ui-activity *)::before,+:root[data-motion="reduced"] :is(.ui-activity, .ui-activity *)::after {+ animation: none;+}+@media (prefers-reduced-motion: reduce) {+ :is([data-presence], [data-backdrop], [data-reveal], .ui-live) {+ animation: none;+ }+ [data-layout-motion] {+ transition: none;+ }+ :is(.ui-activity, .ui-activity *),+ :is(.ui-activity, .ui-activity *)::before,+ :is(.ui-activity, .ui-activity *)::after {+ animation: none;+ }+}++/* The `ui-tree` depth ladder, shared by the themes' recipes: a row or a branch carrying+ `data-depth` gets its depth as a number a recipe can multiply — CSS cannot read an attribute as+ a number, so the eight levels the product nests to are spelled out, and anything deeper draws as+ the eighth. This sets no length: a host indents its own rows by+ `calc(var(--ui-tree-inset) + var(--ui-tree-indent) * depth)`, and a theme's recipe draws its+ rules on the columns that formula gives. `--_depth` is private to the recipes (not a token). It+ sits in ui-theme so a theme's own `.ui-tree` rules, which come later in the layer, may read or+ override it; Primer, with no tree recipe, is untouched by it.++ Two recipes are the same in every theme and so live here once, reading tokens: the eyebrow is+ the h6 rung (a theme says what the rung is — Primer's small tracked capitals, Frost's+ sentence case, Console's tracked mono capitals — and may add its ink in its own rule), and+ the display title takes the emphasis ink, the near-white a dark theme keeps for its headings+ over a calmer body ink. A theme file's own `.ui-eyebrow` / `.ui-display` rules come later in+ the layer and add to these. */+@layer ui-theme {+ .ui-eyebrow {+ font-family: var(--ui-h6-font);+ font-size: var(--ui-h6-size);+ line-height: var(--ui-h6-lh);+ font-weight: var(--ui-h6-weight);+ letter-spacing: var(--ui-h6-tracking);+ text-transform: var(--ui-h6-transform);+ }+ .ui-display {+ color: var(--ui-fg-emphasis);+ }++ /* A notice's tone as one ink every theme's recipe reads: the tone tokens keyed by the hook's+ five tone names (`warning` is the attention tone), mapped here once so no theme restates+ it. `--_tone-fg` is private to the recipes (not a token). */+ .ui-notice[data-tone="info"] {+ --_tone-fg: var(--ui-tone-info-fg);+ }+ .ui-notice[data-tone="success"] {+ --_tone-fg: var(--ui-tone-success-fg);+ }+ .ui-notice[data-tone="warning"] {+ --_tone-fg: var(--ui-tone-attention-fg);+ }+ .ui-notice[data-tone="danger"] {+ --_tone-fg: var(--ui-tone-danger-fg);+ }+ .ui-notice[data-tone="neutral"] {+ --_tone-fg: var(--ui-tone-neutral-fg);+ }++ /* Where a tree's levels start. A tree with roots (a file tree) indents from the tree inset;+ a tree with no depth-0 rows hangs off its container's own head (a work group's steps under+ its header), so its first level is the head's level: a recipe that indents by+ `--_lead + indent × (depth − base)` sets that level flush with the head and only indents+ deeper ones. Console reads `--_depth` alone, because its elbows hang the first level off+ the head on purpose. Both are private to the recipes (not tokens). */+ .ui-tree {+ --_base: 0;+ --_lead: var(--ui-tree-inset);+ }+ .ui-tree:not(:has([data-depth="0"])) {+ --_base: 1;+ --_lead: 0px;+ }+ .ui-tree [data-depth] {+ --_depth: 8;+ }+ .ui-tree [data-depth="0"] {+ --_depth: 0;+ }+ .ui-tree [data-depth="1"] {+ --_depth: 1;+ }+ .ui-tree [data-depth="2"] {+ --_depth: 2;+ }+ .ui-tree [data-depth="3"] {+ --_depth: 3;+ }+ .ui-tree [data-depth="4"] {+ --_depth: 4;+ }+ .ui-tree [data-depth="5"] {+ --_depth: 5;+ }+ .ui-tree [data-depth="6"] {+ --_depth: 6;+ }+ .ui-tree [data-depth="7"] {+ --_depth: 7;+ }+}++/* The user's font pairing (boot.ts, `FONT_LATIN_OPTIONS` / `FONT_CJK_OPTIONS`): a chosen Latin+ face replaces the reading sans — `--ui-font-ui` follows it in Primer and Frost, and Console's+ chrome stays in its mono face, which no pairing touches — and a chosen CJK face replaces+ `--ui-font-cjk`, which every theme's sans stack reads for Han (the mono stacks that read it+ follow too: Han inside code takes the chosen face, the Latin code face stays). No attribute is+ the theme's own choice, declared in its theme file. Only faces the app bundles are listed, so+ a choice never names a family the page cannot load; the Latin stacks keep the CJK face ahead+ of the generic fallbacks, and a Latin face first, so ASCII always renders in the chosen face.+ The system CJK stack names the platform faces the themes already fall back on. */+@layer ui-font {+ :root[data-font-latin="system"] {+ --ui-font-sans:+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, var(--ui-font-cjk), sans-serif;+ }+ :root[data-font-latin="mona-sans"] {+ --ui-font-sans: "Mona Sans Variable", var(--ui-font-cjk), ui-sans-serif, system-ui, sans-serif;+ }+ :root[data-font-latin="ibm-plex-sans"] {+ --ui-font-sans:+ "IBM Plex Sans Variable", var(--ui-font-cjk), ui-sans-serif, system-ui, sans-serif;+ }+ :root[data-font-latin="misans"] {+ --ui-font-sans: "MiSans", var(--ui-font-cjk), ui-sans-serif, system-ui, sans-serif;+ }+ :root[data-font-cjk="system"] {+ --ui-font-cjk: "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC";+ }+ :root[data-font-cjk="noto-sans-sc"] {+ --ui-font-cjk: "Noto Sans SC Variable", "PingFang SC", "Microsoft YaHei";+ }+ :root[data-font-cjk="misans"] {+ --ui-font-cjk: "MiSans", "PingFang SC", "Microsoft YaHei";+ }+}diff --git a/packages/ui/src/themes/geek.css b/packages/ui/src/themes/geek.cssnew file mode 100644index 00000000..30934a9f--- /dev/null+++ b/packages/ui/src/themes/geek.css@@ -0,0 +1,895 @@+/**+ * Console (`geek`) — mono chrome, as plain as a terminal. Navigation, controls, labels,+ * headings, badges and tables are set in Commit Mono; only reading text (message bubbles,+ * assistant prose, the composer's input) stays in IBM Plex Sans. Paper-white light and warm+ * near-black dark with no fill on a card or a row (a card is the page), one accent — black and+ * white by default, the interface orange and five terminal hues as presets — square corners+ * everywhere, no shadow anywhere, hairlines only where they carry structure, a+ * ruled full-bleed window, a standalone frame a plain hairline box, the selected navigation row+ * set in the bold cut, a block caret, motion that jumps in steps, and the agent's work rendered+ * as a transcript — `└` steps, mono capitals, a hatched block bar. References: opencode.ai (the+ * mono chrome, the paper and the warm black, the ruled column, the underline tabs, the calm+ * dark), e2b.dev (the orange, the square shapes, the stepped signals), claude.dev's blog (the+ * tree, the progress line, the near-boxless dark) and a Linux console (the owner's ask of+ * 2026-09-29: as minimal as possible, no decoration).+ *+ * Status of each group:+ * - Light is opencode's paper (`#fdfcfc` page, `rgb(29 29 31)` ink, `rgb(100 98 98)` muted),+ * stepped one shade so cards read as a lighter step on the page; dark is opencode's warm+ * near-black (`#131010`) with the same steps upward, and its ink set calm but not dim+ * (2026-09-29): the body at about 12:1 on the canvas, the near-white kept for headings, the+ * muted ink about 6.2:1 and the subtle 4.7:1 on the muted surface — a first pass at+ * opencode's `rgb(184 178 178)` (8.7:1) read too dim to the owner. The theme's own accent is+ * monochrome (owner's call, 2026-09-30): the ink in light under a white label, a warm+ * near-white in dark under black ink, as every dark fill here takes; E2B's orange, the accent+ * the theme shipped with, stays as its first preset. The rest of the family derives from+ * `--ui-accent` (hover and active shaded, the wash and the line at an alpha), so a preset sets+ * the one value per mode.+ * - Semantic tones are a hairline and its ink on E2B's code hues, with no tint (a badge is a+ * ruled word, never a coloured shape), tuned so every tone reads at 4.5:1 as text on the page+ * and 3:1 as a mark on every surface; the line and the solid fill of a tone are its ink,+ * declared once; dark danger is lifted to `#ff5252` so it reads on the warm black.+ * - Fonts: Commit Mono (400 / 700, the face opencode and e2b.dev ship) for the chrome and for+ * code — one stack, the chrome face reads the data face — IBM Plex Sans for reading, Noto Sans+ * SC behind both for Han (`fonts/geek.css`). The Plex Sans Condensed face the old uppercase h1+ * used is still declared and no longer named here; drop its dependency with the next install.+ * - Radius is 0 everywhere, badges, counters, avatars and controls included (`--ui-radius-pill`+ * and `--ui-radius-control` are 0). State dots and the switch knob stay round and the switch+ * track stays a pill: those components use Tailwind's literal `rounded-full`, which no token+ * re-points.+ * - Density and type are Console's own: a 0.225rem space unit (10% under Tailwind's 0.25rem, so+ * every `h-8` and `px-2` shrinks with it) and a 0.8125rem body rung. Medium weight is 400 —+ * Commit Mono has no 500 — so emphasis in the chrome is colour, and strong is the 700 cut.+ * - Lines and fills (2026-09-29): a rule is drawn only where it carries structure, and a fill+ * nowhere but a hover. The window's columns are ruled off each other and a standalone frame+ * keeps a plain hairline box (the earlier TUI head — the title standing in the top rule — was+ * decoration and went); a frame that holds a tree or sits in one gives its box up, a tree row+ * hangs off a `└` alone (no `│` between siblings — the indent already says the level), an+ * overlay's own 1px line is its edge (no ring around it), a step of the agent's work is a bare+ * row, and the card surface is the page itself.+ *+ * Shape of the file (the same in every theme): one `@layer ui-theme` block holding the base rule,+ * which defines every name in tokens.ts in its group order with its light value, after the gray+ * bridge that re-points Tailwind's `--color-gray-*` / `--color-white` so the app's existing+ * palette classes follow the theme; the dark rule, which declares only what dark changes (the+ * rest keeps its base value, since this file comes after `github.css` and so its base rule beats+ * that file's dark rule); and then this theme's recipes for the style hooks (hooks.ts). After it,+ * one `@layer ui-accent` block with the theme's own accent presets.+ */+@layer ui-theme {+ /* Light: paper. */+ :root[data-theme="geek"] {+ /* Tailwind bridge. white = the surface. */+ --color-white: var(--ui-surface);+ --color-gray-50: #fbfafa;+ --color-gray-100: #f4f2f2;+ --color-gray-200: #e6e3e3;+ --color-gray-300: #d3cfcf;+ --color-gray-400: #8f8b8b;+ --color-gray-500: #5f5c5c;+ --color-gray-600: #4d4a4a;+ --color-gray-700: #383535;+ --color-gray-800: #282525;+ --color-gray-900: #1d1d1f;+ --color-gray-950: #131010;++ /* Colour — surfaces: the page is paper, and a card or an overlay is the page too — a+ hairline, not a fill, sets it apart; only a hover and an inset (a code block) step off it */+ --ui-canvas: #fbfafa;+ --ui-surface: var(--ui-canvas);+ --ui-surface-muted: #f4f2f2;+ --ui-inset: #f0eeee;+ --ui-overlay: var(--ui-canvas);+ --ui-overlay-backdrop: rgb(19 16 16 / 0.28);++ /* Colour — text. A link is the ink, underlined by the markup; it takes the accent on hover+ (under the black-and-white default that is the ink again — the underline is the link). */+ --ui-fg: #1d1d1f;+ --ui-fg-emphasis: var(--ui-fg);+ --ui-fg-muted: #5f5c5c;+ --ui-fg-subtle: #8f8b8b;+ --ui-fg-link: var(--ui-fg);+ --ui-fg-link-hover: var(--ui-accent);++ /* Colour — lines */+ --ui-line: #e6e3e3;+ --ui-line-muted: #efeded;+ --ui-line-emphasis: #bdb8b8;+ --ui-divider: #efeded;++ /* Colour — accent: the ink itself under a white label — the default is black and white,+ and a hue is a preset. The family derives from it: hover and active shade toward black+ (away from the white label, so they only gain contrast; on the ink the step is slight,+ and a fill that barely moves is this theme's way), the wash and the line are the accent+ at an alpha. A preset sets `--ui-accent` alone; its label ink is the theme's for the+ mode. */+ --ui-accent: #1d1d1f;+ --ui-accent-hover: color-mix(in srgb, var(--ui-accent) 86%, #000000);+ --ui-accent-active: color-mix(in srgb, var(--ui-accent) 74%, #000000);+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: color-mix(in srgb, var(--ui-accent) 10%, transparent);+ --ui-accent-line: color-mix(in srgb, var(--ui-accent) 50%, transparent);++ /* Colour — semantic tones: a hairline and its ink, no tint — a badge is a ruled word on the+ page. A tone's line and its solid fill are its ink, so each tone is two values per mode+ (ink, the fill's label); neutral's line is the plain line and its fill a mid grey. */+ --ui-tone-success-fg: #4d6000;+ --ui-tone-success-bg: transparent;+ --ui-tone-success-line: var(--ui-tone-success-fg);+ --ui-tone-success-emphasis: var(--ui-tone-success-fg);+ --ui-tone-success-emphasis-fg: #ffffff;+ --ui-tone-attention-fg: #7d6300;+ --ui-tone-attention-bg: transparent;+ --ui-tone-attention-line: var(--ui-tone-attention-fg);+ --ui-tone-attention-emphasis: var(--ui-tone-attention-fg);+ --ui-tone-attention-emphasis-fg: #ffffff;+ --ui-tone-danger-fg: #ad2000;+ --ui-tone-danger-bg: transparent;+ --ui-tone-danger-line: var(--ui-tone-danger-fg);+ --ui-tone-danger-emphasis: var(--ui-tone-danger-fg);+ --ui-tone-danger-emphasis-fg: #ffffff;+ --ui-tone-done-fg: #9a0fa4;+ --ui-tone-done-bg: transparent;+ --ui-tone-done-line: var(--ui-tone-done-fg);+ --ui-tone-done-emphasis: var(--ui-tone-done-fg);+ --ui-tone-done-emphasis-fg: #ffffff;+ --ui-tone-neutral-fg: var(--ui-fg-muted);+ --ui-tone-neutral-bg: transparent;+ --ui-tone-neutral-line: var(--ui-line);+ --ui-tone-neutral-emphasis: #5f5c5c;+ --ui-tone-neutral-emphasis-fg: #ffffff;+ --ui-tone-info-fg: #003ee9;+ --ui-tone-info-bg: transparent;+ --ui-tone-info-line: var(--ui-tone-info-fg);+ --ui-tone-info-emphasis: var(--ui-tone-info-fg);+ --ui-tone-info-emphasis-fg: #ffffff;++ /* Charts: terminal hues in the roles (indigo, ochre, cobalt, crimson, phosphor, magenta,+ cyan, orange — the presets' own hues, deep enough for paper), the reference curve in the+ muted ink, the token-kind blues, and a plotter's geometry — thin solid bars with square+ tops outlined 1px in the ink, 1px lines stepped between points, small square points, next+ to no fill under a line. */+ --ui-chart-1: #5b3fd6;+ --ui-chart-2: #a87d00;+ --ui-chart-3: #2f6bd8;+ --ui-chart-4: #c8123f;+ --ui-chart-5: #1f7a1f;+ --ui-chart-6: #b0177e;+ --ui-chart-7: #0e7490;+ --ui-chart-8: #d24b1f;+ --ui-chart-ref: var(--ui-fg-muted);+ --ui-chart-cache-read: #9ab8f6;+ --ui-chart-cache-write: #3d74ec;+ --ui-chart-output: #0030b5;+ --ui-chart-grid: #efeded;+ --ui-chart-axis: #8f8b8b;+ --ui-chart-bar-fill: 0.38;+ --ui-chart-bar-radius: 0px;+ --ui-chart-line-width: 1px;+ --ui-chart-point-radius: 2px;+ --ui-chart-curve: step;+ --ui-chart-area-opacity: 0.06;+ --ui-chart-bar-stroke: 1px;+ --ui-chart-bar-stroke-color: var(--ui-fg);+ --ui-chart-bar-opacity: 1;++ /* Colour — code (E2B light code hues live in the Shiki theme, W5) */+ --ui-code-bg: #f4f2f2;+ --ui-code-line: #e6e3e3;+ --ui-code-gutter: #8f8b8b;+ --ui-code-selection: color-mix(in srgb, var(--ui-accent) 14%, transparent);+ --ui-diff-add-bg: rgb(77 96 0 / 0.08);+ --ui-diff-add-word: rgb(77 96 0 / 0.2);+ --ui-diff-del-bg: rgb(173 32 0 / 0.07);+ --ui-diff-del-word: rgb(173 32 0 / 0.18);+ --ui-diff-hunk-bg: rgb(0 62 233 / 0.06);++ /* Shape: square. Emphasis is carried by colour, never by a thicker line. */+ --ui-radius-xs: 0;+ --ui-radius-sm: 0;+ --ui-radius-md: 0;+ --ui-radius-lg: 0;+ --ui-radius-xl: 0;+ --ui-radius-pill: 0;+ --ui-radius-control: 0;+ --ui-border-w: 1px;+ --ui-border-w-thick: 1px;++ /* Elevation: layering, not shadow. Every overlay, drawer and modal card draws its own 1px+ line, and that line is its edge — no ring around it, which would double the rule. Zero+ shadows are `0 0 #0000`, not `none`, which would break Tailwind's shadow list. */+ --ui-shadow-flat: 0 0 #0000;+ --ui-shadow-raised: 0 0 #0000;+ --ui-shadow-overlay: 0 0 #0000;+ --ui-shadow-modal: 0 0 #0000;+ --ui-shadow-drawer: 0 0 #0000;+ --ui-glass-bg: var(--ui-overlay);+ --ui-glass-blur: 0px;+ --ui-glass-saturate: 1;+ --ui-glass-line: var(--ui-line);++ /* Shell: full bleed. Both columns are the page, one hairline between them, no inset, no+ corner, no shadow. Every value is a reference or a zero, so dark needs no second copy. */+ --ui-shell-field: var(--ui-canvas);+ --ui-shell-wash-1: transparent;+ --ui-shell-wash-2: transparent;+ --ui-shell-nav-bg: var(--ui-canvas);+ --ui-shell-main-bg: var(--ui-canvas);+ --ui-shell-line: var(--ui-line);+ --ui-shell-gap: 0px;+ --ui-shell-radius: 0px;+ --ui-shell-shadow: 0 0 #0000;++ /* Structure: a tree indents two characters of the mono face per level (1rem at the 13px+ body) from the row inset, and its connector rules take the emphasis line so `└` reads on+ paper and on the warm black alike; a field is a table row with a 10rem label column and+ three quarters of a rem before the value. */+ --ui-tree-inset: 0.625rem;+ --ui-tree-indent: 1rem;+ --ui-tree-guide: var(--ui-line-emphasis);+ --ui-field-label-w: 10rem;+ --ui-field-gap: 0.75rem;++ /* Controls: the switch's off track is the line, its knob the muted ink (5:1 on the track);+ on the accent the knob takes the accent's label ink. */+ --ui-switch-track: var(--color-gray-200);+ --ui-switch-knob: var(--ui-fg-muted);+ --ui-switch-knob-on: var(--ui-accent-fg);+ --ui-switch-knob-line: rgb(0 0 0 / 0.1);++ /* Typography — families. Latin face first, so ASCII always renders in the theme's face; the+ chrome is the mono face — one stack, read by both names — with Noto behind it for Han, and+ reading text is Plex Sans. */+ --ui-font-cjk: "Noto Sans SC Variable", "PingFang SC", "Microsoft YaHei";+ --ui-font-sans:+ "IBM Plex Sans Variable", var(--ui-font-cjk), ui-sans-serif, system-ui, sans-serif;+ --ui-font-mono:+ "Commit Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono",+ var(--ui-font-cjk), monospace;+ --ui-font-ui: var(--ui-font-mono);+ --ui-font-display: var(--ui-font-ui);++ /* Typography — scale and roles: a 13px body at the 16px root (Commit Mono is wide), 12px+ small and caption, 16px reading text; headings in the chrome face at 700, sentence case,+ no tracking — mono needs none — and the h6 group label uppercase with letter-spacing, the+ one eyebrow rung. */+ --ui-text-body-size: 0.8125rem;+ --ui-text-body-lh: 1.5;+ --ui-text-small-size: 0.75rem;+ --ui-text-small-lh: 1.5;+ --ui-text-caption-size: 0.75rem;+ --ui-text-caption-lh: 1.4;+ --ui-text-code-size: 0.8125rem;+ --ui-text-code-lh: 1.6;+ --ui-text-prose-size: 1rem;+ --ui-text-prose-lh: 1.6;+ --ui-h1-size: 1.75rem;+ --ui-h1-lh: 1.15;+ --ui-h1-weight: 700;+ --ui-h1-tracking: 0;+ --ui-h1-transform: none;+ --ui-h1-font: var(--ui-font-display);+ --ui-h2-size: 1.375rem;+ --ui-h2-lh: 1.2;+ --ui-h2-weight: 700;+ --ui-h2-tracking: 0;+ --ui-h2-transform: none;+ --ui-h2-font: var(--ui-font-ui);+ --ui-h3-size: 1.125rem;+ --ui-h3-lh: 1.3;+ --ui-h3-weight: 700;+ --ui-h3-tracking: 0;+ --ui-h3-transform: none;+ --ui-h3-font: var(--ui-font-ui);+ --ui-h4-size: 1rem;+ --ui-h4-lh: 1.4;+ --ui-h4-weight: 700;+ --ui-h4-tracking: 0;+ --ui-h4-transform: none;+ --ui-h4-font: var(--ui-font-ui);+ --ui-h5-size: 0.875rem;+ --ui-h5-lh: 1.5;+ --ui-h5-weight: 700;+ --ui-h5-tracking: 0;+ --ui-h5-transform: none;+ --ui-h5-font: var(--ui-font-ui);+ --ui-h6-size: 0.75rem;+ --ui-h6-lh: 1.5;+ --ui-h6-weight: 500;+ --ui-h6-tracking: 0.08em;+ --ui-h6-transform: uppercase;+ --ui-h6-font: var(--ui-font-ui);+ --ui-md-h1-size: 1.25rem;+ --ui-md-h2-size: 1.125rem;+ --ui-md-h3-size: 1rem;+ --ui-weight-body: 400;+ --ui-weight-medium: 400;+ --ui-weight-strong: 700;+ --ui-tracking-body: 0;+ --ui-tracking-mono: 0;+ --ui-tracking-label: 0.08em;++ /* Density: a 0.225rem space unit (every Tailwind spacing and size utility shrinks with it),+ tight control, row and menu-row padding, and short stacks. */+ --ui-space-unit: 0.225rem;+ --ui-control-py-sm: 0.1875rem;+ --ui-control-py-md: 0.3125rem;+ --ui-control-py-lg: 0.5rem;+ --ui-control-px-sm: 0.5rem;+ --ui-control-px-md: 0.75rem;+ --ui-control-px-lg: 0.875rem;+ --ui-control-gap-sm: 0.375rem;+ --ui-control-gap-md: 0.5rem;+ --ui-row-py: 0.25rem;+ --ui-row-px: 0.625rem;+ --ui-menu-row-py: 0.375rem;+ --ui-menu-row-px: 0.5rem;+ --ui-card-p: 0.75rem;+ --ui-panel-p: 1rem;+ --ui-stack-0: 0.25rem;+ --ui-stack-1: 0.5rem;+ --ui-stack-2: 0.875rem;+ --ui-stack-3: 1.25rem;+ --ui-stack-4: 2rem;++ /* Motion: colour changes stay quick and smooth (E2B's 100ms held to the 120ms floor every+ theme's state changes share); everything that appears, leaves or resizes jumps. A layer+ enters in three frames over 120ms and leaves in two over 60ms, with no slide, no scale and+ no blur; a streamed chunk is simply there (a zero reveal); the sidebar's width jumps+ through four steps; the live signals tick. */+ --ui-dur-fast: 120ms;+ --ui-dur-base: 150ms;+ --ui-dur-slow: 260ms;+ --ui-ease-out: cubic-bezier(0.23, 1, 0.32, 1);+ --ui-ease-in-out: cubic-bezier(0.215, 0.61, 0.355, 1);+ --ui-ease-spring: cubic-bezier(0.23, 1, 0.32, 1);+ --ui-ease-overlay-in: steps(3, jump-none);+ --ui-ease-overlay-out: steps(2, jump-none);+ --ui-live-timing: steps(2, end);+ --ui-dur-enter: 120ms;+ --ui-dur-exit: 60ms;+ --ui-ease-enter: steps(3, jump-none);+ --ui-ease-exit: steps(2, jump-none);+ --ui-enter-shift: 0px;+ --ui-enter-scale: 1;+ --ui-enter-blur: 0px;+ --ui-dur-reveal: 0ms;+ --ui-reveal-blur: 0px;+ --ui-dur-layout: 160ms;+ --ui-ease-layout: steps(4, end);++ /* Icons */+ --ui-icon-stroke: 1.4;+ --ui-icon-cap: butt;+ --ui-icon-join: miter;++ /* Focus, selection and scrollbar: a 1px accent outline off the edge; always-visible square+ thumbs on a tinted track. */+ --ui-focus-ring: 1px solid var(--ui-accent);+ --ui-focus-ring-offset: 2px;+ --ui-focus-ring-input: inset 0 0 0 1px var(--ui-accent);+ --ui-selection-bg: color-mix(in srgb, var(--ui-accent) 18%, transparent);+ --ui-scrollbar-w: thin;+ --ui-scrollbar-thumb: #d3cfcf;+ --ui-scrollbar-thumb-hover: #bdb8b8;+ --ui-scrollbar-track: #f4f2f2;+ --ui-scrollbar-visibility: always;+ }++ /* Dark: opencode's warm near-black, with the ink set calm. */+ :root[data-theme="geek"].dark {+ /* Tailwind bridge: 950 keeps the base's canvas value, 900 raised, 800 hover / panel line,+ 700 control line, then the ink ramp — 500 subtle, 400 muted, 100 body, 50 the near-white+ for headings. white stays literal: `dark:*-white/N` hairlines read it as ink. */+ --color-white: #ffffff;+ --color-gray-50: #f3f1f0;+ --color-gray-100: #d9d4d3;+ --color-gray-200: #c5c0bf;+ --color-gray-300: #b4afae;+ --color-gray-400: #a39e9d;+ --color-gray-500: #8d8887;+ --color-gray-600: #5a5453;+ --color-gray-700: #2f2b2b;+ --color-gray-800: #242020;+ --color-gray-900: var(--ui-canvas);++ /* Colour — surfaces: the warm black is the page, the card and the overlay alike; a hover+ steps up, an inset steps down */+ --ui-canvas: #131010;+ --ui-surface-muted: #221f1f;+ --ui-inset: #0d0b0b;+ --ui-overlay-backdrop: rgb(0 0 0 / 0.6);++ /* Colour — text: body about 12:1 on the canvas, headings and links near-white, muted about+ 6.2:1 and subtle 4.7:1 on the muted surface */+ --ui-fg: var(--color-gray-100);+ --ui-fg-emphasis: var(--color-gray-50);+ --ui-fg-muted: var(--color-gray-400);+ --ui-fg-subtle: var(--color-gray-500);+ --ui-fg-link: var(--ui-fg-emphasis);++ /* Colour — lines */+ --ui-line: #2f2b2b;+ --ui-line-muted: #242020;+ --ui-line-emphasis: #5a5453;+ --ui-divider: #242020;++ /* Colour — accent: a warm near-white with black ink, as every dark fill here takes, so+ hover shades toward white and active toward black — away from the ink, as in light — and+ the wash and the line strengthen a step on the dark page. */+ --ui-accent: #f4f2f2;+ --ui-accent-hover: color-mix(in srgb, var(--ui-accent) 86%, #ffffff);+ --ui-accent-active: color-mix(in srgb, var(--ui-accent) 90%, #000000);+ --ui-accent-fg: #000000;+ --ui-accent-muted: color-mix(in srgb, var(--ui-accent) 16%, transparent);+ --ui-accent-line: color-mix(in srgb, var(--ui-accent) 60%, transparent);++ /* Colour — semantic tones: E2B's code hues; fills take black ink. The lines, the fills and+ the absent tints follow the base rule. */+ --ui-tone-success-fg: #9dc20c;+ --ui-tone-success-emphasis-fg: #000000;+ --ui-tone-attention-fg: #f2c230;+ --ui-tone-attention-emphasis-fg: #000000;+ --ui-tone-danger-fg: #ff5252;+ --ui-tone-danger-emphasis-fg: #000000;+ --ui-tone-done-fg: #b57cff;+ --ui-tone-done-emphasis-fg: #000000;+ --ui-tone-neutral-emphasis: #5a5453;+ --ui-tone-info-fg: #5696fd;+ --ui-tone-info-emphasis-fg: #000000;++ /* Charts: the same roles as bright terminal hues on the warm black */+ --ui-chart-1: #9b7bff;+ --ui-chart-2: #f2c230;+ --ui-chart-3: #5696fd;+ --ui-chart-4: #ff5c8a;+ --ui-chart-5: #3ddc84;+ --ui-chart-6: #ff6ac1;+ --ui-chart-7: #22d3ee;+ --ui-chart-8: #ff795b;+ --ui-chart-cache-read: #a8c8fe;+ --ui-chart-cache-write: #5696fd;+ --ui-chart-output: #2059d1;+ --ui-chart-grid: #242020;+ --ui-chart-axis: var(--color-gray-500);++ /* Colour — code */+ --ui-code-bg: #0d0b0b;+ --ui-code-line: #2f2b2b;+ --ui-code-gutter: var(--color-gray-500);+ --ui-code-selection: color-mix(in srgb, var(--ui-accent) 28%, transparent);+ --ui-diff-add-bg: rgb(157 194 12 / 0.1);+ --ui-diff-add-word: rgb(157 194 12 / 0.28);+ --ui-diff-del-bg: rgb(255 82 82 / 0.1);+ --ui-diff-del-word: rgb(255 82 82 / 0.3);+ --ui-diff-hunk-bg: rgb(86 150 253 / 0.1);++ /* Elevation: a glass layer's line steps up so it reads on the dark overlay. */+ --ui-glass-line: var(--ui-line-emphasis);++ /* Controls: the dark off track, and the body ink as the knob on it */+ --ui-switch-track: var(--color-gray-700);+ --ui-switch-knob: var(--ui-fg);++ /* Focus, selection and scrollbar */+ --ui-selection-bg: color-mix(in srgb, var(--ui-accent) 32%, transparent);+ --ui-scrollbar-thumb: #2f2b2b;+ --ui-scrollbar-thumb-hover: #5a5453;+ --ui-scrollbar-track: #0d0b0b;+ }++ /*+ * Style hooks (hooks.ts). A component opts into a hook with its class; this theme decides what+ * the hook does. These rules sit in `ui-theme`, after Tailwind's `utilities`, so a hook wins over+ * the utilities its component also carries — that is what lets `.ui-live` re-time an+ * `animate-spin` and `.ui-frame` redraw a card's box.+ *+ * Console gives a recipe to: eyebrow (its ink; the rung is theme.css's), display, live, frame,+ * underline-nav, shell, icon-decor, tree, field, activity, notice, chart. `.ui-glass` and+ * `.ui-scrim` are no-ops here: the overlay is opaque through the glass tokens, and the page+ * behind a dialog is dimmed, not blurred.+ */++ /* Group label on the h6 rung (theme.css): the chrome face, uppercase, tracked — and muted. */+ :root[data-theme="geek"] .ui-eyebrow {+ color: var(--ui-fg-muted);+ }++ /* The page's one display title: the chrome face at its bold cut, sentence case, no tracking —+ opencode's h1. Han glyphs need a little more leading than the Latin bold. */+ :root[data-theme="geek"] .ui-display {+ font-family: var(--ui-font-ui);+ font-weight: 700;+ text-transform: none;+ letter-spacing: 0;+ }+ :root[data-theme="geek"] .ui-display:lang(zh) {+ line-height: 1.25;+ }++ /* Stepped live signals: the busy dot blinks, the caret is a block, the spinner ticks. */+ :root[data-theme="geek"] .ui-live {+ animation-timing-function: var(--ui-live-timing);+ }+ :root[data-theme="geek"] .ui-live[data-live="dot"] {+ animation: ui-geek-signal 1.25s var(--ui-live-timing) infinite;+ }+ :root[data-theme="geek"] .ui-live[data-live="spinner"] {+ animation-timing-function: steps(8, end);+ }+ :root[data-theme="geek"] .ui-live[data-live="caret"] {+ display: inline-block;+ width: 0.6ch;+ height: 1em;+ vertical-align: text-bottom;+ overflow: hidden;+ background-color: currentColor;+ -webkit-text-fill-color: transparent;+ animation: ui-geek-signal 1s var(--ui-live-timing) infinite;+ }+ @keyframes ui-geek-signal {+ 50% {+ opacity: 0.2;+ }+ }++ /* A frame is a plain hairline box on the page: one rule round it, one under its head and over+ its foot, one between panes, no fill of its own, head text in the chrome face. (A first+ pass drew a TUI box with the title standing in the top rule; it was decoration and went.)+ The parts are selected through `:where()`, which adds no specificity, so the boxless rules+ further down — a frame that holds a tree or sits in one — can take every part of it back. */+ :root[data-theme="geek"] .ui-frame {+ border: var(--ui-border-w) solid var(--ui-line);+ border-radius: 0;+ background-color: transparent;+ }+ :root[data-theme="geek"] .ui-frame > :where([data-slot="head"]) {+ border-bottom: var(--ui-border-w) solid var(--ui-line);+ background-color: transparent;+ font-family: var(--ui-font-ui);+ }+ :root[data-theme="geek"] .ui-frame > :where([data-slot="foot"]) {+ border-top: var(--ui-border-w) solid var(--ui-line);+ }+ :root[data-theme="geek"] .ui-frame :where([data-slot="pane"] + [data-slot="pane"]) {+ border-left: var(--ui-border-w) solid var(--ui-line);+ }++ /* Tabs: a 2px ink rule under the selected tab, opencode's underline; no hover bar. */+ :root[data-theme="geek"] .ui-underline-nav [role="tab"] {+ position: relative;+ }+ :root[data-theme="geek"] .ui-underline-nav [role="tab"]::after {+ content: "";+ position: absolute;+ inset-inline: 0;+ bottom: -1px;+ height: 2px;+ background-color: transparent;+ pointer-events: none;+ }+ :root[data-theme="geek"] .ui-underline-nav [role="tab"][aria-selected="true"]::after {+ background-color: var(--ui-fg);+ }++ /* The app window: full bleed on the page, the navigation column ruled off the main column by+ one hairline (and a dock column, when there is one, ruled off on its other side), no corner+ anywhere, and a `>` in the accent before the selected navigation row — a nav entry or the+ open session — standing in the row's own inline padding (two space units, the narrowest+ row's) at the small rung, so the row's content does not move. */+ :root[data-theme="geek"] .ui-shell {+ background-color: var(--ui-shell-field);+ border-radius: 0;+ }+ :root[data-theme="geek"] .ui-shell > [data-slot="nav"] {+ background-color: var(--ui-shell-nav-bg);+ border-inline-end: var(--ui-border-w) solid var(--ui-shell-line);+ }+ :root[data-theme="geek"] .ui-shell > [data-slot="main"] {+ background-color: var(--ui-shell-main-bg);+ }+ :root[data-theme="geek"] .ui-shell > [data-slot="dock"] {+ border-inline-start: var(--ui-border-w) solid var(--ui-shell-line);+ }+ /* The selected navigation row — a nav entry or the open session — is marked quietly: the+ bold cut over the host's own selected fill, no glyph (a first pass hung an accent `>` before+ it; the owner asked for it to go). Mono bold keeps the row's advance, so nothing moves. */+ :root[data-theme="geek"] .ui-shell [data-slot="nav"] [aria-current="page"] {+ font-weight: var(--ui-weight-strong);+ }++ /* Decorative icons are not drawn: a navigation row is its label, a group header its eyebrow, a+ menu row its verb, and the selected row is marked by its weight alone. Icons that carry+ information (status marks, file kinds, tool glyphs, avatars) never take the hook and stay. */+ :root[data-theme="geek"] .ui-icon-decor {+ display: none;+ }++ /* Nested rows hang off `└` elbows, the way claude.dev prints its tree, and the box goes: the+ host's border, fill, corner and shadow turn off, and so do the rules it draws between its+ rows. Each row past the roots indents on the tree tokens and draws one elbow on its parent's+ column, half an indent before its own content — a rule from the row's top to its middle+ with a short tick at the end. No `│` runs between siblings and none continues alongside a+ branch: the indent already says the level, and every rule not drawn is a line less. Nothing+ here is a glyph in the markup. */+ :root[data-theme="geek"] .ui-tree {+ border-color: transparent;+ border-radius: 0;+ background-color: transparent;+ box-shadow: none;+ }+ :root[data-theme="geek"] .ui-tree > [data-depth],+ :root[data-theme="geek"] .ui-tree > [data-branch] {+ border-color: transparent;+ }+ :root[data-theme="geek"] .ui-tree [data-depth]:not([data-branch]) {+ position: relative;+ padding-inline-start: calc(var(--ui-tree-inset) + var(--ui-tree-indent) * var(--_depth));+ }+ :root[data-theme="geek"] .ui-tree [data-depth]:not([data-branch], [data-depth="0"])::before {+ content: "";+ position: absolute;+ top: 0;+ height: 50%;+ inset-inline-start: calc(var(--ui-tree-inset) + var(--ui-tree-indent) * (var(--_depth) - 0.5));+ width: calc(var(--ui-tree-indent) * 0.5 - 0.1875rem);+ border-inline-start: var(--ui-border-w) solid var(--ui-tree-guide);+ border-bottom: var(--ui-border-w) solid var(--ui-tree-guide);+ pointer-events: none;+ }++ /* A frame headed by a step of the agent's work (a work group, open or collapsed — collapsed+ it has no tree, so the head is what names it) or holding a tree, or sitting inside one (a+ tool card hung off an elbow), gives up the box: no rule on it or on any part (the host's+ own rules between head and body included), so the rows hang off the head, or the card off+ its elbow, by the connector rules alone. A frame standing on its own keeps its box. */+ :root[data-theme="geek"] .ui-frame:has(> .ui-tree, > .ui-activity),+ :root[data-theme="geek"] .ui-tree .ui-frame,+ :root[data-theme="geek"] .ui-frame:has(> .ui-tree, > .ui-activity) > *,+ :root[data-theme="geek"] .ui-tree .ui-frame > * {+ border: 0;+ }++ /* A labelled control row is a table row: a fixed label column, the control left-aligned in the+ next column and stretched to it (a text control fills it, a switch or a segmented control+ keeps its own width), the hint under the control. The label takes the md control's block+ padding so its line sits on the control's first line, and rows separate by the host's own+ rules, so a page of them reads like a table. */+ :root[data-theme="geek"] .ui-field {+ display: grid;+ grid-template-columns: var(--ui-field-label-w) minmax(0, 1fr);+ column-gap: var(--ui-field-gap);+ row-gap: var(--ui-stack-0);+ align-items: start;+ }+ :root[data-theme="geek"] .ui-field > [data-slot="label"] {+ grid-row: 1;+ grid-column: 1;+ min-width: 0;+ padding-block: calc(var(--ui-control-py-md) + var(--ui-border-w));+ }+ :root[data-theme="geek"] .ui-field > [data-slot="control"] {+ grid-row: 1;+ grid-column: 2;+ min-width: 0;+ max-width: 100%;+ }+ :root[data-theme="geek"] .ui-field > [data-slot="hint"] {+ grid-column: 2;+ }++ /* Work in progress, as a transcript (claude.dev's tree and progress line): the row is no box —+ no border, no corner, no shadow, and the rule a list draws above it goes with the border —+ its label is the chrome face at the small rung, uppercase and tracked like an eyebrow, muted+ once the step is done and the body ink while it runs (the danger ink when it failed), the+ detail (a path, an argument preview, a duration) is muted, and while the step runs the+ progress slot draws a hatched block bar: a dotted track of `░` under a shaded fill of `▓`+ that advances a block at a time and starts over — indeterminate, because a step has no+ percentage. The host hides the slot; the recipe shows it. A step in a work group hangs off+ the `└` its tree row draws, so no connector is added here. The slots are found anywhere+ inside the row (a card nests them in its own button). Under reduced motion the bar holds+ one fill. */+ :root[data-theme="geek"] .ui-activity {+ border-color: transparent;+ border-radius: 0;+ box-shadow: none;+ }+ /* In a boxless work group the header and the rows are painted in the page's own colour: they+ stick while their bodies scroll, so they must stay opaque, and on the page that fill is+ invisible in every state. A row inside a frame that keeps its box keeps its own fill. */+ :root[data-theme="geek"] .ui-frame:has(> .ui-tree, > .ui-activity) > [data-slot="head"],+ :root[data-theme="geek"] .ui-tree .ui-activity {+ background-color: var(--ui-canvas);+ }+ /* A hover changes the ink alone — the label steps up to the body ink — so the group looks the+ same at rest, hovered, open and stuck; no fill moves. */+ :root[data-theme="geek"]+ .ui-frame:has(> .ui-tree, > .ui-activity)+ > [data-slot="head"]:hover+ [data-slot="label"],+ :root[data-theme="geek"] .ui-tree .ui-activity:hover [data-slot="label"] {+ color: var(--ui-fg);+ }+ :root[data-theme="geek"] .ui-activity [data-slot="label"] {+ font-family: var(--ui-font-ui);+ font-size: var(--ui-text-small-size);+ font-weight: var(--ui-weight-body);+ letter-spacing: var(--ui-tracking-label);+ text-transform: uppercase;+ color: var(--ui-fg-muted);+ }+ :root[data-theme="geek"] .ui-activity[data-state="running"] [data-slot="label"] {+ color: var(--ui-fg);+ }+ :root[data-theme="geek"] .ui-activity[data-state="error"] [data-slot="label"] {+ color: var(--ui-tone-danger-fg);+ }+ :root[data-theme="geek"] .ui-activity [data-slot="detail"] {+ font-family: var(--ui-font-ui);+ font-size: var(--ui-text-small-size);+ color: var(--ui-fg-muted);+ }+ :root[data-theme="geek"] .ui-activity[data-state="running"] [data-slot="progress"] {+ position: relative;+ display: inline-block;+ vertical-align: middle;+ font-family: var(--ui-font-ui);+ font-size: var(--ui-text-small-size);+ line-height: 1;+ letter-spacing: 0;+ color: var(--ui-fg-subtle);+ }+ :root[data-theme="geek"] .ui-activity[data-state="running"] [data-slot="progress"]::before {+ content: "░░░░░░░░░░░░";+ }+ :root[data-theme="geek"] .ui-activity[data-state="running"] [data-slot="progress"]::after {+ content: "▓▓▓▓▓▓▓▓▓▓▓▓";+ position: absolute;+ inset: 0;+ color: var(--ui-fg);+ clip-path: inset(0 50% 0 0);+ animation: ui-geek-progress 2.4s steps(12, end) infinite;+ }+ @keyframes ui-geek-progress {+ from {+ clip-path: inset(0 100% 0 0);+ }+ to {+ clip-path: inset(0 0 0 0);+ }+ }++ /* A notice is a status line, the way a console prints one: a bracketed tone tag in the tone's+ ink — `[ OK ]`, `[WARN]`, `[FAIL]` — in the chrome face at the start, the message beside it+ in the reading face, nothing round it, painted in the page's own colour (quiet on the page,+ opaque where a toast floats over content). The tag stands out of the flow — absolutely at+ the row's inset, the host padded for it — because a host lays its body and actions out as a+ flex row, and a tag in the flow would be a third item pushing the body to the middle. A+ toast is the same line inside one hairline, so it has an edge where it floats. (Two earlier+ passes — a coloured left rule, then a solid tone block — were decoration and went.) */+ :root[data-theme="geek"] .ui-notice {+ position: relative;+ padding-inline-start: calc(4rem + var(--ui-row-px));+ border: 0;+ border-radius: 0;+ background-color: var(--ui-canvas);+ box-shadow: none;+ color: var(--ui-fg);+ font-family: var(--ui-font-sans);+ }+ :root[data-theme="geek"] button.ui-notice {+ border: var(--ui-border-w) solid var(--ui-line-emphasis);+ }+ /* The host's own leading mark gives way to the tag: two marks would say the same thing. */+ :root[data-theme="geek"] .ui-notice [data-slot="icon"] {+ display: none;+ }+ :root[data-theme="geek"] .ui-notice::before {+ content: "[INFO]";+ position: absolute;+ inset-inline-start: var(--ui-row-px);+ inset-block: 0;+ display: flex;+ align-items: center;+ color: var(--_tone-fg);+ font-family: var(--ui-font-ui);+ font-size: var(--ui-text-small-size);+ font-weight: var(--ui-weight-strong);+ }+ :root[data-theme="geek"] .ui-notice[data-tone="success"]::before {+ content: "[ OK ]";+ }+ :root[data-theme="geek"] .ui-notice[data-tone="warning"]::before {+ content: "[WARN]";+ }+ :root[data-theme="geek"] .ui-notice[data-tone="danger"]::before {+ content: "[FAIL]";+ }+ :root[data-theme="geek"] .ui-notice[data-tone="neutral"]::before {+ content: "[NOTE]";+ }++ /* Charts are drawn like a terminal plot: a dashed grid on crisp pixels, axis labels in the+ chrome face as tracked capitals, 1px lines with hard joins and ends, square points, and+ thin solid bars outlined in the ink (the tokens say so; an earlier stripe hatch was+ decoration and went). The chart primitives write every colour, width, radius and opacity+ the tokens hold; the recipe owns only what a token cannot: dashes, joins and caps, pixel+ alignment, the label face. A grid line is SVG in the usage charts and an HTML lane track+ in the Trace timeline, so its rule carries both spellings — a dashed stroke, and a dashed+ rule under a lane with no fill — and an engine ignores the one that does not apply. */+ :root[data-theme="geek"] .ui-chart [data-part="grid"] {+ background-color: transparent;+ border-bottom: var(--ui-border-w) dashed var(--ui-line-emphasis);+ }+ /* Dashes and pixel alignment are for the grid's straight rules — the SVG lines, and the HTML+ lane rule above — never the donut's track, a circle that is a grid part too and stays a+ solid ring (dashed it read as stitching; without anti-aliasing it is a staircase). */+ :root[data-theme="geek"] .ui-chart line[data-part="grid"] {+ stroke-dasharray: 2 3;+ }+ :root[data-theme="geek"] .ui-chart line:is([data-part="grid"], [data-part="axis"]) {+ shape-rendering: crispEdges;+ }+ /* The axis part is both the tick text and the axis-break marks: the face rules reach the text+ alone, so a line never picks up a font. */+ :root[data-theme="geek"] .ui-chart text:is([data-part="axis"], [data-part="label"]) {+ font-family: var(--ui-font-ui);+ letter-spacing: var(--ui-tracking-label);+ text-transform: uppercase;+ }+ :root[data-theme="geek"] .ui-chart :is(path, polyline)[data-part="series"] {+ stroke-linejoin: miter;+ stroke-linecap: butt;+ }+ /* A point is a rect the chart rounds to a circle by its `rx`; squared off here. */+ :root[data-theme="geek"] .ui-chart [data-part="point"] {+ rx: 0;+ shape-rendering: crispEdges;+ }+}++/*+ * The user's accent presets (tokens.ts, `ACCENT_PRESETS.geek`): E2B's orange, the accent the+ * theme shipped with before its own went black and white, then five terminal hues — phosphor+ * green, cyan, magenta, gold, cobalt — each deep in light for the theme's white label and bright+ * in dark for its black ink, the way the theme's dark fills are. A preset sets `--ui-accent` and+ * nothing else — hover, active, wash and line derive from it in the theme's rules above, and the+ * label ink is the theme's for the mode — so each preset is one value per mode; the orange holds+ * across modes (black ink on it clears 4.5:1 in dark) and has no dark rule. The selectors match+ * only Console's root, so a preset another theme lists paints nothing here.+ */+@layer ui-accent {+ :root[data-theme="geek"][data-accent="orange"] {+ --ui-accent: #e32a01;+ }+ :root[data-theme="geek"][data-accent="phosphor"] {+ --ui-accent: #1f7a1f;+ }+ :root[data-theme="geek"][data-accent="phosphor"].dark {+ --ui-accent: #3ddc84;+ }+ :root[data-theme="geek"][data-accent="cyan"] {+ --ui-accent: #0e7490;+ }+ :root[data-theme="geek"][data-accent="cyan"].dark {+ --ui-accent: #22d3ee;+ }+ :root[data-theme="geek"][data-accent="magenta"] {+ --ui-accent: #b0177e;+ }+ :root[data-theme="geek"][data-accent="magenta"].dark {+ --ui-accent: #ff6ac1;+ }+ :root[data-theme="geek"][data-accent="gold"] {+ --ui-accent: #8a6d00;+ }+ :root[data-theme="geek"][data-accent="gold"].dark {+ --ui-accent: #f2c230;+ }+ :root[data-theme="geek"][data-accent="cobalt"] {+ --ui-accent: #003ee9;+ }+ :root[data-theme="geek"][data-accent="cobalt"].dark {+ --ui-accent: #5696fd;+ }+}diff --git a/packages/ui/src/themes/github.css b/packages/ui/src/themes/github.cssnew file mode 100644index 00000000..fa77436f--- /dev/null+++ b/packages/ui/src/themes/github.css@@ -0,0 +1,557 @@+/**+ * Primer (`github`) — the default theme. Reference: github.com and primer.style.+ *+ * W0 status: every LIGHT value is the app's CURRENT computed value, so adopting the token layer+ * moves no pixel there — system font stacks, stock Tailwind gray, emerald / amber / red status+ * tones, the 6px control radius, Tailwind's stock shadow recipes and the 3px gray focus ring.+ * Values the app had no equivalent for (the `done` and `info` tones, diff surfaces, glass, the+ * type and density roles) are proposals in the same palette, consumed by nothing yet. The Primer+ * unification — Mona Sans + Noto, one border grey, Primer's tone hues — lands as W1a.+ *+ * Dark is no longer the app's white-on-pure-black inversion (user decision, 2026-09-29): the+ * canvas lifts to #121212, the body ink sits at about 12:1 with the muted ink at 6:1 and the+ * subtle at 4.7:1 (a first pass at 9:1 read too dim), and the near-white is kept for headings+ * and emphasis, the way claude.dev and opencode.ai set their dark pages. The dark rule+ * re-points the whole gray bridge to that ramp, so the app's `dark:text-gray-*` classes calm+ * with the tokens.+ *+ * Shape every theme file follows: one `@layer ui-theme` block with a base rule and a dark rule,+ * then one `@layer ui-accent` block with the theme's own accent presets. The base rule declares+ * every name in tokens.ts, in its group order, with its light value, plus the gray bridge that+ * re-points Tailwind's `--color-gray-*` / `--color-white` so the app's existing palette classes+ * follow the theme. The dark rule matches the same root and declares only what dark changes,+ * bridge steps included; everything else keeps its base value.+ *+ * This file is the default and is imported first, so it also matches <html> with no `data-theme`+ * at all. Another theme's base rule outranks this base rule, and ties with this dark rule and wins+ * by coming later, so its dark mode starts from its own base values and never from these; the+ * theme files must therefore be imported in this order (theme.css shows it).+ *+ * Tokens here may read the gray bridge declared in the same block (`var(--color-gray-500)`); the+ * bridge itself is always literal, so no reference can cycle. Stock Tailwind colours are copied+ * as their exact `oklch()` values from tailwindcss/theme.css — a rounded hex would move pixels.+ *+ * The names added for the theme identities (the space unit, the chrome face, the shell, the+ * presence / reveal / layout motion) carry the values that reproduce today's rendering: Tailwind's+ * stock 0.25rem unit, one face for chrome and reading, no field behind the window, quick fades+ * with a few px of slide. `.ui-shell` is a no-op here — the window's look is its own classes.+ */+@layer ui-theme {+ :root,+ :root[data-theme="github"] {+ /* ---- Gray bridge: stock Tailwind v4 gray ---- */+ --color-white: var(--ui-surface);+ --color-gray-50: oklch(98.5% 0.002 247.839);+ --color-gray-100: oklch(96.7% 0.003 264.542);+ --color-gray-200: oklch(92.8% 0.006 264.531);+ --color-gray-300: oklch(87.2% 0.01 258.338);+ --color-gray-400: oklch(70.7% 0.022 261.325);+ --color-gray-500: oklch(55.1% 0.027 264.364);+ --color-gray-600: oklch(44.6% 0.03 256.802);+ --color-gray-700: oklch(37.3% 0.034 259.733);+ --color-gray-800: oklch(27.8% 0.033 256.848);+ --color-gray-900: oklch(21% 0.034 264.665);+ --color-gray-950: oklch(13% 0.028 261.692);++ /* ---- Colour — surfaces ---- */+ --ui-canvas: #ffffff;+ --ui-surface: #ffffff;+ --ui-surface-muted: var(--color-gray-50);+ --ui-inset: var(--color-gray-50);+ --ui-overlay: #ffffff;+ --ui-overlay-backdrop: oklab(0% 0 0 / 0.45); /* = bg-black/45, alpha exactly .45 */++ /* ---- Colour — text ---- */+ --ui-fg: var(--color-gray-900);+ --ui-fg-emphasis: var(--ui-fg);+ --ui-fg-muted: var(--color-gray-500);+ --ui-fg-subtle: var(--color-gray-400);+ --ui-fg-link: #0b57d0; /* brand-700 */+ --ui-fg-link-hover: #1a73e8; /* brand-600 */++ /* ---- Colour — lines ---- */+ --ui-line: var(--color-gray-200);+ --ui-line-muted: var(--color-gray-100);+ --ui-line-emphasis: var(--color-gray-300);+ --ui-divider: var(--color-gray-200);++ /* ---- Colour — accent (neutral: near-black on white) ---- */+ --ui-accent: #111827;+ --ui-accent-hover: #1f2937;+ --ui-accent-active: #374151;+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: rgb(17 24 39 / 0.08);+ --ui-accent-line: rgb(17 24 39 / 0.4);++ /* ---- Colour — semantic tones ----+ Ink on a tint and a solid fill's label clear 4.5:1 (badge text is the 700 step, as the app's+ tinted pills draw it); fg on the page surfaces clears 3:1. `neutral` ink is the muted pill's+ gray-600. Nothing in the app reads these yet — its tones still come from tone.ts classes. */+ --ui-tone-success-fg: oklch(50.8% 0.118 165.612); /* emerald-700 */+ --ui-tone-success-bg: oklch(97.9% 0.021 166.113); /* emerald-50 */+ --ui-tone-success-line: oklch(84.5% 0.143 164.978); /* emerald-300 */+ --ui-tone-success-emphasis: oklch(50.8% 0.118 165.612); /* emerald-700 */+ --ui-tone-success-emphasis-fg: #ffffff;+ --ui-tone-attention-fg: oklch(55.5% 0.163 48.998); /* amber-700 */+ --ui-tone-attention-bg: oklch(98.7% 0.022 95.277); /* amber-50 */+ --ui-tone-attention-line: oklch(87.9% 0.169 91.605); /* amber-300 */+ --ui-tone-attention-emphasis: oklch(76.9% 0.188 70.08); /* amber-500, dark label */+ --ui-tone-attention-emphasis-fg: var(--color-gray-950);+ --ui-tone-danger-fg: oklch(50.5% 0.213 27.518); /* red-700 */+ --ui-tone-danger-bg: oklch(97.1% 0.013 17.38); /* red-50 */+ --ui-tone-danger-line: oklch(80.8% 0.114 19.571); /* red-300 */+ --ui-tone-danger-emphasis: oklch(50.5% 0.213 27.518); /* red-700 */+ --ui-tone-danger-emphasis-fg: #ffffff;+ --ui-tone-done-fg: oklch(49.6% 0.265 301.924); /* purple-700 */+ --ui-tone-done-bg: oklch(97.7% 0.014 308.299); /* purple-50 */+ --ui-tone-done-line: oklch(82.7% 0.119 306.383); /* purple-300 */+ --ui-tone-done-emphasis: oklch(49.6% 0.265 301.924); /* purple-700 */+ --ui-tone-done-emphasis-fg: #ffffff;+ --ui-tone-neutral-fg: var(--color-gray-600);+ --ui-tone-neutral-bg: var(--color-gray-100);+ --ui-tone-neutral-line: var(--color-gray-200);+ --ui-tone-neutral-emphasis: var(--color-gray-600);+ --ui-tone-neutral-emphasis-fg: #ffffff;+ --ui-tone-info-fg: oklch(50% 0.134 242.749); /* sky-700 */+ --ui-tone-info-bg: oklch(97.7% 0.013 236.62); /* sky-50 */+ --ui-tone-info-line: oklch(82.8% 0.111 230.318); /* sky-300 */+ --ui-tone-info-emphasis: oklch(50% 0.134 242.749); /* sky-700 */+ --ui-tone-info-emphasis-fg: #ffffff;++ /* ---- Charts: the series palette in its roles (violet, amber, sky, rose, emerald, fuchsia,+ then teal and orange from the employee palette). Amber, sky, emerald, teal and orange sit+ at their 600 steps — the steps the app's dark series already used — since their 500s read+ at 2.2–2.9:1 on white (lifted 2026-09-30, the one Primer change of the theme work; violet,+ rose and fuchsia clear 3:1 at 500). The reference curve is amber like the second series;+ the token-kind blues and today's geometry — bars at 60% of their band with square tops,+ 2px lines joined straight, 2.5px points, a 10% fill under a line. ---- */+ --ui-chart-1: oklch(60.6% 0.25 292.717); /* violet-500 */+ --ui-chart-2: oklch(66.6% 0.179 58.318); /* amber-600 */+ --ui-chart-3: oklch(58.8% 0.158 241.966); /* sky-600 */+ --ui-chart-4: oklch(64.5% 0.246 16.439); /* rose-500 */+ --ui-chart-5: oklch(59.6% 0.145 163.225); /* emerald-600 */+ --ui-chart-6: oklch(66.7% 0.295 322.15); /* fuchsia-500 */+ --ui-chart-7: oklch(60% 0.118 184.704); /* teal-600 */+ --ui-chart-8: oklch(64.6% 0.222 41.116); /* orange-600 */+ --ui-chart-ref: var(--ui-chart-2);+ --ui-chart-cache-read: #7dd3fc;+ --ui-chart-cache-write: #0ea5e9;+ --ui-chart-output: #0369a1;+ --ui-chart-grid: var(--color-gray-200);+ --ui-chart-axis: var(--color-gray-400);+ --ui-chart-bar-fill: 0.6;+ --ui-chart-bar-radius: 0px;+ --ui-chart-line-width: 2px;+ --ui-chart-point-radius: 2.5px;+ --ui-chart-curve: linear;+ --ui-chart-area-opacity: 0.1;+ --ui-chart-bar-stroke: 0px;+ --ui-chart-bar-stroke-color: series;+ --ui-chart-bar-opacity: 1;++ /* ---- Colour — code ---- */+ --ui-code-bg: var(--color-gray-50);+ --ui-code-line: var(--color-gray-200);+ --ui-code-gutter: var(--color-gray-400);+ --ui-code-selection: oklch(90.1% 0.058 230.902); /* sky-200 */+ --ui-diff-add-bg: oklch(97.9% 0.021 166.113); /* emerald-50 */+ --ui-diff-add-word: oklch(90.5% 0.093 164.15); /* emerald-200 */+ --ui-diff-del-bg: oklch(97.1% 0.013 17.38); /* red-50 */+ --ui-diff-del-word: oklch(88.5% 0.062 18.334); /* red-200 */+ --ui-diff-hunk-bg: oklch(97.7% 0.013 236.62); /* sky-50 */++ /* ---- Shape: Tailwind's stock radius scale ---- */+ --ui-radius-xs: 0.125rem;+ --ui-radius-sm: 0.25rem;+ --ui-radius-md: 0.375rem;+ --ui-radius-lg: 0.5rem;+ --ui-radius-xl: 0.75rem;+ --ui-radius-pill: 9999px;+ --ui-radius-control: 0.375rem;+ --ui-border-w: 1px;+ --ui-border-w-thick: 2px;++ /* ---- Elevation: Tailwind's stock shadow-sm / lg / xl / 2xl; no glass ---- */+ --ui-shadow-flat: 0 0 #0000;+ --ui-shadow-raised: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);+ --ui-shadow-overlay: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);+ --ui-shadow-modal: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);+ --ui-shadow-drawer: 0 25px 50px -12px rgb(0 0 0 / 0.25);+ --ui-glass-bg: var(--ui-overlay);+ --ui-glass-blur: 0px;+ --ui-glass-saturate: 100%;+ --ui-glass-line: var(--ui-line);++ /* ---- Shell: today's window — the sidebar's muted fill beside the canvas, one rule between+ them, no field, no inset, no corner, no shadow. Every value is a reference, so dark needs+ no second copy. ---- */+ --ui-shell-field: var(--ui-canvas);+ --ui-shell-wash-1: transparent;+ --ui-shell-wash-2: transparent;+ --ui-shell-nav-bg: var(--ui-surface-muted);+ --ui-shell-main-bg: var(--ui-canvas);+ --ui-shell-line: var(--ui-line);+ --ui-shell-gap: 0px;+ --ui-shell-radius: 0px;+ --ui-shell-shadow: 0 0 #0000;++ /* ---- Structure: today's file tree (a 0.5rem inset and 0.875rem per level) and form rows.+ No recipe draws the guide or reads the label column here; the values are what a Primer+ polish would start from. ---- */+ --ui-tree-inset: 0.5rem;+ --ui-tree-indent: 0.875rem;+ --ui-tree-guide: var(--ui-line-muted);+ --ui-field-label-w: auto;+ --ui-field-gap: 0.375rem;++ /* ---- Controls: the switch the app has always drawn — the gray-200 track when off, a white+ knob, and the accent's own label ink for the knob on the accent (white on the dark fills).+ The white knob on the gray-200 track is under 3:1 and kept: it is today's look, and the+ knob's own hairline draws its edge — that hairline is gray-500 here (2026-09-30, the+ least visible change that reads at 3:1 on the track; it was a 10% black), so the edge+ carries the knob where the fill cannot. ---- */+ --ui-switch-track: var(--color-gray-200);+ --ui-switch-knob: #ffffff;+ --ui-switch-knob-on: var(--ui-accent-fg);+ --ui-switch-knob-line: var(--color-gray-500);++ /* ---- Typography — families: the system stacks the app ships today; chrome and reading text+ share the one face. The sans stack reads the CJK face where the app's stack names the two+ system CJK faces, so the computed list is the same and a chosen CJK face reaches it. ---- */+ --ui-font-sans:+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, var(--ui-font-cjk), sans-serif;+ --ui-font-ui: var(--ui-font-sans);+ --ui-font-mono:+ ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New",+ monospace;+ --ui-font-display: var(--ui-font-sans);+ --ui-font-cjk: "PingFang SC", "Microsoft YaHei";++ /* ---- Typography — scale and roles: Tailwind's stock text-sm / text-xs rungs, which is what+ the app's classes render today (theme.css bridges `text-sm` and `text-xs` to these). The two+ line-heights are Tailwind's own unitless ratios, not their rem equivalents: a child that sets+ only its font size inherits a ratio but would inherit a rem as a fixed length, and every row+ holding such a child would grow by a fraction of a pixel. ---- */+ --ui-text-body-size: 0.875rem;+ --ui-text-body-lh: calc(1.25 / 0.875);+ --ui-text-small-size: 0.75rem;+ --ui-text-small-lh: calc(1 / 0.75);+ --ui-text-caption-size: 0.75rem;+ --ui-text-caption-lh: 1rem;+ --ui-text-code-size: 0.8125rem;+ --ui-text-code-lh: 1.25rem;+ --ui-text-prose-size: 0.875rem;+ --ui-text-prose-lh: 1.5rem;+ --ui-h1-size: 1.5rem;+ --ui-h1-lh: 2rem;+ --ui-h1-weight: 600;+ --ui-h1-tracking: normal;+ --ui-h1-transform: none;+ --ui-h1-font: var(--ui-font-sans);+ --ui-h2-size: 1.25rem;+ --ui-h2-lh: 1.75rem;+ --ui-h2-weight: 600;+ --ui-h2-tracking: normal;+ --ui-h2-transform: none;+ --ui-h2-font: var(--ui-font-sans);+ --ui-h3-size: 1.125rem;+ --ui-h3-lh: 1.75rem;+ --ui-h3-weight: 600;+ --ui-h3-tracking: normal;+ --ui-h3-transform: none;+ --ui-h3-font: var(--ui-font-sans);+ --ui-h4-size: 1rem;+ --ui-h4-lh: 1.5rem;+ --ui-h4-weight: 600;+ --ui-h4-tracking: normal;+ --ui-h4-transform: none;+ --ui-h4-font: var(--ui-font-sans);+ --ui-h5-size: 0.875rem;+ --ui-h5-lh: 1.25rem;+ --ui-h5-weight: 600;+ --ui-h5-tracking: normal;+ --ui-h5-transform: none;+ --ui-h5-font: var(--ui-font-sans);+ /* The h6 rung is the group label's (the eyebrow's): the app sets the Sessions label, its time+ and Agent groups and the settings dialog's rail in 11 px semibold capitals tracked wide, in+ px so they hold at every root size. */+ --ui-h6-size: 11px;+ --ui-h6-lh: 1rem;+ --ui-h6-weight: 600;+ --ui-h6-tracking: 0.025em;+ --ui-h6-transform: uppercase;+ --ui-h6-font: var(--ui-font-sans);+ --ui-md-h1-size: 1.25rem;+ --ui-md-h2-size: 1.125rem;+ --ui-md-h3-size: 1rem;+ --ui-weight-body: 400;+ --ui-weight-medium: 500;+ --ui-weight-strong: 600;+ --ui-tracking-body: normal;+ --ui-tracking-mono: normal;+ --ui-tracking-label: normal;++ /* ---- Density ----+ The space unit is Tailwind's stock 0.25rem, so every `h-8` / `px-2` / `gap-3` the app spells+ computes to what it computes today. Control rungs, content height = 2 × padding-block + the+ rung's line-height (sm: small, md and lg: body), plus a 1px border on each side:+ sm 0.25rem × 2 + 1rem = 1.5rem (Button sm, Input sm)+ md 0.375rem × 2 + 1.25rem = 2rem (Button md)+ lg 0.625rem × 2 + 1.25rem = 2.5rem (Input base; it reaches the height with py-2 + text-base)+ That is 27 / 36 / 45px at the default 18px root (29 / 38 / 47 with borders) and 24 / 32 / 40+ at 16px. They are the app's existing controls, which is why they are not Primer's+ 28 / 32 / 40px at the 18px root: moving there changes every control's height, a visible+ change for a later wave. */+ --ui-space-unit: 0.25rem;+ --ui-control-py-sm: 0.25rem;+ --ui-control-py-md: 0.375rem;+ --ui-control-py-lg: 0.625rem;+ --ui-control-px-sm: 0.625rem;+ --ui-control-px-md: 0.75rem;+ --ui-control-px-lg: 0.75rem;+ --ui-control-gap-sm: 0.25rem;+ --ui-control-gap-md: 0.5rem;+ --ui-row-py: 0.375rem;+ --ui-row-px: 0.5rem;+ --ui-menu-row-py: 0.5rem;+ --ui-menu-row-px: 0.875rem;+ --ui-card-p: 1rem;+ --ui-panel-p: 1rem;+ --ui-stack-0: 0.25rem;+ --ui-stack-1: 0.5rem;+ --ui-stack-2: 1rem;+ --ui-stack-3: 1.5rem;+ --ui-stack-4: 2.5rem;++ /* ---- Motion ---- */+ --ui-dur-fast: 150ms;+ --ui-dur-base: 200ms;+ --ui-dur-slow: 280ms;+ --ui-ease-out: cubic-bezier(0.2, 0.7, 0.3, 1);+ --ui-ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);+ --ui-ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);+ --ui-ease-overlay-in: ease-out;+ --ui-ease-overlay-out: ease-in;+ --ui-live-timing: linear;+ /* Presence, reveal and layout: the app's own feel — a layer fades in over 150ms with a 4px+ slide from its edge and leaves faster, streamed text fades in, the sidebar's width eases. */+ --ui-dur-enter: 150ms;+ --ui-dur-exit: 100ms;+ --ui-ease-enter: var(--ui-ease-overlay-in);+ --ui-ease-exit: var(--ui-ease-overlay-out);+ --ui-enter-shift: 4px;+ --ui-enter-scale: 1;+ --ui-enter-blur: 0px;+ --ui-dur-reveal: 150ms;+ --ui-reveal-blur: 0px;+ --ui-dur-layout: 200ms;+ --ui-ease-layout: var(--ui-ease-in-out);++ /* ---- Icons ---- */+ --ui-icon-stroke: 1.7;+ --ui-icon-cap: round;+ --ui-icon-join: round;++ /* ---- Focus, selection and scrollbar ---- */+ --ui-focus-ring: 3px solid rgb(107 114 128 / 0.4);+ --ui-focus-ring-offset: 2px;+ --ui-focus-ring-input: 0 0 0 2px color-mix(in oklab, var(--color-gray-400) 30%, transparent);+ --ui-selection-bg: rgb(0 0 0 / 0.1);+ --ui-scrollbar-w: thin;+ --ui-scrollbar-thumb: rgb(60 64 67 / 0.28);+ --ui-scrollbar-thumb-hover: rgb(60 64 67 / 0.45);+ --ui-scrollbar-track: transparent;+ --ui-scrollbar-visibility: auto;+ }++ /* Dark declares only what the mode changes. `:root.dark` also matches the rule above, so every+ name not repeated here — the shape, type, density, motion and icon groups whole, the solid+ fills and their labels, the backdrop — keeps its one value from there, and a `var()` in it+ resolves against this rule's values (`--ui-glass-bg: var(--ui-overlay)` is the dark overlay). */+ :root.dark,+ :root[data-theme="github"].dark {+ /* ---- Gray bridge: one neutral ramp (no indigo tint) for a calm dark. The four dark steps+ lift off pure black — the canvas is 950 at #121212 — and the ink steps come down from+ white: 50 is the near-white kept for headings, 100 the body ink at about 12:1 on the+ canvas, 300 a secondary ink at about 8:1, 400 the muted ink at about 6:1, 500 the subtle+ ink for placeholders and meta text at about 4.7:1 on the muted surface. The app's message+ prose is `dark:text-gray-100` and its meta text `dark:text-gray-400`, so re-pointing the+ whole ramp is what sets the app's dark. ---- */+ --color-gray-950: #121212;+ --color-gray-900: #1a1a1a;+ --color-gray-800: #262626;+ --color-gray-700: #333333;+ --color-gray-600: #5a5a5a;+ --color-gray-500: #8a8a8a;+ --color-gray-400: #a1a1a1;+ --color-gray-300: #b0b0b0;+ --color-gray-200: #c2c2c2;+ --color-gray-100: #d6d6d6;+ --color-gray-50: #f0f0f0;+ /* Stays literal white in dark: the app's `dark:border-white/10`, `dark:bg-white/10`,+ `dark:hover:bg-white` and `ring-white` read it as light INK, and its few unpaired `bg-white`+ have always rendered white here. A theme that re-points it at a dark surface must first+ move those call sites to tokens. */+ --color-white: #ffffff;++ /* ---- Colour — surfaces: the canvas a step off black, cards a step above it, the inset a+ step below ---- */+ --ui-canvas: var(--color-gray-950);+ --ui-surface: var(--color-gray-900);+ --ui-surface-muted: #202020;+ --ui-inset: #0e0e0e;+ --ui-overlay: var(--color-gray-900);++ /* ---- Colour — text: body about 12:1, headings near-white, muted about 6:1, subtle 4.7:1 ---- */+ --ui-fg: var(--color-gray-100);+ --ui-fg-emphasis: var(--color-gray-50);+ --ui-fg-muted: var(--color-gray-400);+ --ui-fg-subtle: var(--color-gray-500);+ --ui-fg-link: #8ab4f8; /* brand-300 */+ --ui-fg-link-hover: var(--ui-fg-link);++ /* ---- Colour — lines ---- */+ --ui-line: var(--color-gray-800);+ --ui-line-muted: var(--color-gray-800); /* the app's dark divider, `dark:border-gray-800` */+ --ui-line-emphasis: var(--color-gray-700);+ --ui-divider: var(--color-gray-800);++ /* ---- Colour — accent (neutral: light gray with dark text) ---- */+ --ui-accent: #f3f4f6;+ --ui-accent-hover: #e5e7eb;+ --ui-accent-active: #d1d5db;+ --ui-accent-fg: #111827;+ --ui-accent-muted: rgb(243 244 246 / 0.12);+ --ui-accent-line: rgb(243 244 246 / 0.4);++ /* ---- Colour — semantic tones: 400 ink on the 950/40 tints the app's dark notices use; the+ solid fills and their labels are the light ones ---- */+ --ui-tone-success-fg: oklch(76.5% 0.177 163.223); /* emerald-400 */+ --ui-tone-success-bg: oklch(26.2% 0.051 172.552 / 0.4); /* emerald-950/40 */+ --ui-tone-success-line: oklch(50.8% 0.118 165.612); /* emerald-700 */+ --ui-tone-attention-fg: oklch(82.8% 0.189 84.429); /* amber-400 */+ --ui-tone-attention-bg: oklch(27.9% 0.077 45.635 / 0.4); /* amber-950/40 */+ --ui-tone-attention-line: oklch(55.5% 0.163 48.998); /* amber-700 */+ --ui-tone-danger-fg: oklch(70.4% 0.191 22.216); /* red-400 */+ --ui-tone-danger-bg: oklch(25.8% 0.092 26.042 / 0.4); /* red-950/40 */+ --ui-tone-danger-line: oklch(50.5% 0.213 27.518); /* red-700 */+ --ui-tone-done-fg: oklch(71.4% 0.203 305.504); /* purple-400 */+ --ui-tone-done-bg: oklch(29.1% 0.149 302.717 / 0.4); /* purple-950/40 */+ --ui-tone-done-line: oklch(49.6% 0.265 301.924); /* purple-700 */+ --ui-tone-neutral-fg: var(--color-gray-300);+ --ui-tone-neutral-bg: var(--color-gray-800);+ --ui-tone-neutral-line: var(--color-gray-800);+ --ui-tone-info-fg: oklch(74.6% 0.16 232.661); /* sky-400 */+ --ui-tone-info-bg: oklch(29.3% 0.066 243.157 / 0.4); /* sky-950/40 */+ --ui-tone-info-line: oklch(50% 0.134 242.749); /* sky-700 */++ /* ---- Charts: light now shares the 600 steps the app's dark series use, so dark restates+ only what still differs — emerald at 400 as the timeline draws its work phase, fuchsia at+ 600; violet and rose hold ---- */+ --ui-chart-5: oklch(76.5% 0.177 163.223); /* emerald-400 */+ --ui-chart-6: oklch(59.1% 0.293 322.896); /* fuchsia-600 */+ --ui-chart-grid: var(--color-gray-800);+ --ui-chart-axis: var(--color-gray-500);++ /* ---- Colour — code ---- */+ --ui-code-bg: var(--color-gray-900);+ --ui-code-line: var(--color-gray-800);+ --ui-code-gutter: var(--color-gray-600);+ --ui-code-selection: color-mix(in oklab, oklch(68.5% 0.169 237.323) 40%, transparent);+ --ui-diff-add-bg: color-mix(in oklab, oklch(69.6% 0.17 162.48) 15%, transparent);+ --ui-diff-add-word: color-mix(in oklab, oklch(69.6% 0.17 162.48) 35%, transparent);+ --ui-diff-del-bg: color-mix(in oklab, oklch(63.7% 0.237 25.331) 15%, transparent);+ --ui-diff-del-word: color-mix(in oklab, oklch(63.7% 0.237 25.331) 35%, transparent);+ --ui-diff-hunk-bg: color-mix(in oklab, oklch(68.5% 0.169 237.323) 15%, transparent);++ /* ---- Controls: the app's dark off track, and the body ink as the knob on it ---- */+ --ui-switch-track: var(--color-gray-700);+ --ui-switch-knob: var(--ui-fg);+ --ui-switch-knob-line: rgb(0 0 0 / 0.1);++ /* ---- Selection and scrollbar ---- */+ --ui-selection-bg: rgb(255 255 255 / 0.18);+ --ui-scrollbar-thumb: rgb(232 234 237 / 0.2);+ --ui-scrollbar-thumb-hover: rgb(232 234 237 / 0.35);+ }++ /*+ * Style hooks (hooks.ts): every one is a no-op in Primer. The app's look is what the+ * components' own classes render — an opaque overlay, a semibold h1, a linear pulse, a bordered+ * card with a muted head, the accent bar under a tab, the sidebar's muted fill beside the+ * canvas, monochrome icons, a bordered tree box with the host's own indent, a form's label+ * above its control and a settings row's label beside it, a plain row for a step of the+ * agent's work, a plain dim behind a dialog — so no recipe is written for those, and none may+ * be until a Primer polish wave changes that look on purpose (the 2026-09-30 lift of the light+ * chart steps and the knob's hairline was such a change, made in tokens, not recipes). The+ * two rules every theme shares (the eyebrow on the h6 rung,+ * the display title in the emphasis ink) live in theme.css and are what the app's group labels+ * and page titles already draw: 11px semibold tracked capitals, and the body ink in light.+ */+}++/*+ * The user's accent presets (tokens.ts, `ACCENT_PRESETS.github`): the five ids and values the app+ * has always had, literal — a preset sets the six accent tokens itself, nothing derives — and+ * the same in both modes, with one lift: rose-700 was a 3:1 mark only on the pure-black dark,+ * and on the lifted dark surfaces it is 2.98:1, so dark takes rose-600 (its white label still+ * clears 4.5:1) with the 700 / 800 steps as hover and active. The selectors match only Primer's+ * root — a bare <html> or `data-theme="github"` — so a stored preset another theme lists paints+ * nothing here, and these paint nothing under another theme. The layer puts them after the+ * theme's dark rule, which they would otherwise only tie with.+ */+@layer ui-accent {+ :root:not([data-theme])[data-accent="blue"],+ :root[data-theme="github"][data-accent="blue"] {+ --ui-accent: #2563eb;+ --ui-accent-hover: #1d4ed8;+ --ui-accent-active: #1e40af;+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: rgb(37 99 235 / 0.12);+ --ui-accent-line: rgb(37 99 235 / 0.5);+ }+ :root:not([data-theme])[data-accent="green"],+ :root[data-theme="github"][data-accent="green"] {+ --ui-accent: #15803d; /* green-700: white text clears AA */+ --ui-accent-hover: #166534;+ --ui-accent-active: #14532d;+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: rgb(21 128 61 / 0.12);+ --ui-accent-line: rgb(21 128 61 / 0.5);+ }+ :root:not([data-theme])[data-accent="violet"],+ :root[data-theme="github"][data-accent="violet"] {+ --ui-accent: #7c3aed;+ --ui-accent-hover: #6d28d9;+ --ui-accent-active: #5b21b6;+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: rgb(124 58 237 / 0.12);+ --ui-accent-line: rgb(124 58 237 / 0.5);+ }+ :root:not([data-theme])[data-accent="rose"],+ :root[data-theme="github"][data-accent="rose"] {+ --ui-accent: #be123c; /* rose-700: white text clears AA */+ --ui-accent-hover: #9f1239;+ --ui-accent-active: #881337;+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: rgb(190 18 60 / 0.12);+ --ui-accent-line: rgb(190 18 60 / 0.5);+ }+ :root:not([data-theme])[data-accent="rose"].dark,+ :root[data-theme="github"][data-accent="rose"].dark {+ --ui-accent: #e11d48; /* rose-600: a 3:1 mark on the lifted dark surfaces */+ --ui-accent-hover: #be123c;+ --ui-accent-active: #9f1239;+ --ui-accent-muted: rgb(225 29 72 / 0.12);+ --ui-accent-line: rgb(225 29 72 / 0.5);+ }+ :root:not([data-theme])[data-accent="amber"],+ :root[data-theme="github"][data-accent="amber"] {+ --ui-accent: #b45309; /* amber-700: white text clears AA */+ --ui-accent-hover: #92400e;+ --ui-accent-active: #78350f;+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: rgb(180 83 9 / 0.12);+ --ui-accent-line: rgb(180 83 9 / 0.5);+ }+}diff --git a/packages/ui/src/themes/modern.css b/packages/ui/src/themes/modern.cssnew file mode 100644index 00000000..ddcdfc5b--- /dev/null+++ b/packages/ui/src/themes/modern.css@@ -0,0 +1,862 @@+/**+ * Frost (`modern`) — soft, roomy, quiet. A cool-neutral off-white with almost no lines: the+ * navigation column is a soft grey beside a near-white main column (flat — no field, no+ * floating sheet), grouping comes from soft grey fills rather than borders, a card's edge is a+ * hairline that barely exists, dialogs are opaque on a dimmed backdrop with large corners; pill+ * controls, regular-weight titles set large with negative tracking, a light frost on the small+ * layers that float over content, motion that springs and de-blurs, and work in progress shown+ * by nothing more than a highlight sweeping across its label. References: the owner's three+ * captures of 2026-09-29 (a grey sidebar beside a near-white transcript, an opaque About dialog+ * on a blurred page, a settings dialog whose rows sit in soft-filled groups), with Codex /+ * macOS for the lineless working state; the earlier sierra.ai warm field and floating sheet+ * were retired at that review.+ *+ * Status of each group:+ * - Light is a near-neutral grey ramp with a faint cool cast: the canvas `#fafafa` (never a+ * stark white slab), the navigation column and grouped rows `#f3f4f5`, cards white, lines a+ * step above the fill they sit on. Dark is the same ramp inverted, set calm but not dim — the+ * body ink about 11:1 on the muted surface, the near-white kept for headings, the muted ink+ * 6.5:1 and the subtle 4.9:1 there.+ * - The accent family derives from `--ui-accent`: hover and active are the accent shaded, the+ * wash and the line are the accent at an alpha, so a preset sets the one value per mode.+ * - Semantic tones use Sierra's hues, tuned until every tone reads at 4.5:1 as text on its own+ * tint and 3:1 as a mark on every surface (proposal). Chart and code colours are proposals.+ * - Fonts: MiSans (Xiaomi) in place of Sierra's commercial GT America, Latin and Chinese in one+ * family at weights 400 and 500, with JetBrains Mono for code (`fonts/modern.css`). Chrome and+ * reading text share the face.+ * - Density and type are Frost's own: a 0.28rem space unit (12% above Tailwind's 0.25rem, so+ * every `h-8` and `px-2` grows with it), a 0.9375rem body rung, roomier control padding. The+ * size of nothing is shared with the other themes any more.+ *+ * Shape of the file (the same in every theme): one `@layer ui-theme` block holding the base rule,+ * which defines every name in tokens.ts in its group order with its light value, after the gray+ * bridge that re-points Tailwind's `--color-gray-*` / `--color-white` so the app's existing+ * palette classes follow the theme; the dark rule, which declares only what dark changes (the+ * rest keeps its base value, since this file comes after `github.css` and so its base rule beats+ * that file's dark rule); and then this theme's recipes for the style hooks (hooks.ts). After it,+ * one `@layer ui-accent` block with the theme's own accent presets.+ */+@layer ui-theme {+ :root[data-theme="modern"] {+ /* Tailwind bridge: the app's gray classes land on the cool-neutral ramp. white = the card+ surface. */+ --color-white: var(--ui-surface);+ --color-gray-50: #fafafa;+ --color-gray-100: #f3f4f5;+ --color-gray-200: #e6e8ea;+ --color-gray-300: #d0d3d6;+ --color-gray-400: #979b9f;+ --color-gray-500: #686c71;+ --color-gray-600: #565a5e;+ --color-gray-700: #424549;+ --color-gray-800: #313336;+ --color-gray-900: #242628;+ --color-gray-950: #18191b;++ /* Colour — surfaces. The canvas is a near-white, not a white slab; grouped rows and the+ navigation column sit on the muted grey; cards and dialogs are white. */+ --ui-canvas: #fafafa;+ --ui-surface: #ffffff;+ --ui-surface-muted: #f3f4f5;+ --ui-inset: #f5f6f7;+ --ui-overlay: #ffffff;+ --ui-overlay-backdrop: rgb(24 25 27 / 0.4);++ /* Colour — text */+ --ui-fg: #232527;+ --ui-fg-emphasis: var(--ui-fg);+ --ui-fg-muted: #686c71;+ --ui-fg-subtle: #979b9f;+ --ui-fg-link: #2f66c4;+ --ui-fg-link-hover: #244f9a;++ /* Colour — lines: a step above the fill they sit on, so a card's edge barely exists */+ --ui-line: #e9eaec;+ --ui-line-muted: #f0f1f2;+ --ui-line-emphasis: #d0d3d6;+ --ui-divider: #f0f1f2;++ /* Colour — accent: Sierra's forest green. The rest of the family derives from it: hover and+ active are the accent shaded toward black (the label is white, so a darker fill only gains+ contrast), the wash and the line are the accent at an alpha. A preset therefore sets+ `--ui-accent` alone; its label ink is the theme's for the mode. */+ --ui-accent: #006838;+ --ui-accent-hover: color-mix(in srgb, var(--ui-accent) 86%, #000000);+ --ui-accent-active: color-mix(in srgb, var(--ui-accent) 74%, #000000);+ --ui-accent-fg: #ffffff;+ --ui-accent-muted: color-mix(in srgb, var(--ui-accent) 14%, transparent);+ --ui-accent-line: color-mix(in srgb, var(--ui-accent) 35%, transparent);++ /* Colour — semantic tones: a soft tint with its ink and no edge — a tone's line is its tint,+ so a badge or a pill is a tinted shape, never a bordered one. */+ --ui-tone-success-fg: #007a3a;+ --ui-tone-success-bg: #e4f2e8;+ --ui-tone-success-line: var(--ui-tone-success-bg);+ --ui-tone-success-emphasis: #007a3a;+ --ui-tone-success-emphasis-fg: #ffffff;+ --ui-tone-attention-fg: #806210;+ --ui-tone-attention-bg: #fbf4dc;+ --ui-tone-attention-line: var(--ui-tone-attention-bg);+ --ui-tone-attention-emphasis: #ebc247;+ --ui-tone-attention-emphasis-fg: #232527;+ --ui-tone-danger-fg: #c72d06;+ --ui-tone-danger-bg: #fcebe8;+ --ui-tone-danger-line: var(--ui-tone-danger-bg);+ --ui-tone-danger-emphasis: #c72d06;+ --ui-tone-danger-emphasis-fg: #ffffff;+ --ui-tone-done-fg: #7644a6;+ --ui-tone-done-bg: #f1edf8;+ --ui-tone-done-line: var(--ui-tone-done-bg);+ --ui-tone-done-emphasis: #7644a6;+ --ui-tone-done-emphasis-fg: #ffffff;+ --ui-tone-neutral-fg: #5f6367;+ --ui-tone-neutral-bg: #f3f4f5;+ --ui-tone-neutral-line: var(--ui-tone-neutral-bg);+ --ui-tone-neutral-emphasis: #6d7176;+ --ui-tone-neutral-emphasis-fg: #ffffff;+ --ui-tone-info-fg: #2f66c4;+ --ui-tone-info-bg: #eaf0fa;+ --ui-tone-info-line: var(--ui-tone-info-bg);+ --ui-tone-info-emphasis: #2f66c4;+ --ui-tone-info-emphasis-fg: #ffffff;++ /* Charts: soft. A low-chroma palette in the roles (heather, ochre, dusk blue, rose, sage,+ mauve, teal, clay), each just clearing 3:1 on the canvas so a line and a point read; the+ bars are the same colours let through at seven tenths (a little more in dark) with no+ outline — a first pass edged them in their own colour and the owner preferred them plain+ — so a chart never glares. The reference curve in the muted ink, the token-kind blues+ softened, and a soft geometry: bars a little over half their band with rounded tops, a+ 2px smooth curve, round points, a light wash under a line. */+ --ui-chart-1: #8b7cc4;+ --ui-chart-2: #a8863a;+ --ui-chart-3: #6590c2;+ --ui-chart-4: #c4718b;+ --ui-chart-5: #5f9c7a;+ --ui-chart-6: #b57cb3;+ --ui-chart-7: #58978f;+ --ui-chart-8: #bd7d52;+ --ui-chart-ref: var(--ui-fg-muted);+ --ui-chart-cache-read: #b9cfe8;+ --ui-chart-cache-write: #7fa3d2;+ --ui-chart-output: #4d6f9e;+ --ui-chart-grid: #eef0f1;+ --ui-chart-axis: #979b9f;+ --ui-chart-bar-fill: 0.55;+ --ui-chart-bar-radius: 3px;+ --ui-chart-line-width: 2px;+ --ui-chart-point-radius: 3px;+ --ui-chart-curve: smooth;+ --ui-chart-area-opacity: 0.12;+ --ui-chart-bar-stroke: 0px;+ --ui-chart-bar-stroke-color: series;+ --ui-chart-bar-opacity: 0.7;++ /* Colour — code */+ --ui-code-bg: #f5f6f7;+ --ui-code-line: #e9eaec;+ --ui-code-gutter: #979b9f;+ --ui-code-selection: rgb(47 102 196 / 0.16);+ --ui-diff-add-bg: #e7f3ea;+ --ui-diff-add-word: #c2e5ca;+ --ui-diff-del-bg: #fcebe8;+ --ui-diff-del-word: #f6c9bb;+ --ui-diff-hunk-bg: #eaf0fa;++ /* Shape: large on boxes — 6 / 8 / 12 / 20 / 24 px at the 16px root, so a card takes 12px+ and a dialog 20px — with the pill kept for every pressable control. */+ --ui-radius-xs: 0.375rem;+ --ui-radius-sm: 0.5rem;+ --ui-radius-md: 0.75rem;+ --ui-radius-lg: 1.25rem;+ --ui-radius-xl: 1.5rem;+ --ui-radius-pill: 9999px;+ --ui-radius-control: 9999px;+ --ui-border-w: 1px;+ --ui-border-w-thick: 2px;++ /* Elevation: untinted and soft — a faint drop, no ring (a layer's edge is its own hairline).+ `flat` is a zero shadow rather than `none`: Tailwind composes shadows into a comma list,+ where `none` would invalidate the whole declaration. The frost is light and nearly opaque:+ a small layer over content keeps a hint of what moves under it, no more. */+ --ui-shadow-flat: 0 0 #0000;+ --ui-shadow-raised: 0 1px 2px rgb(0 0 0 / 0.04);+ --ui-shadow-overlay: 0 4px 16px -4px rgb(0 0 0 / 0.1);+ --ui-shadow-modal: 0 12px 40px -12px rgb(0 0 0 / 0.18);+ --ui-shadow-drawer: var(--ui-shadow-modal);+ --ui-glass-bg: rgb(255 255 255 / 0.85);+ --ui-glass-blur: 16px;+ --ui-glass-saturate: 1.2;+ --ui-glass-line: rgb(0 0 0 / 0.06);++ /* Shell: flat. The navigation column is the muted grey, the main column the canvas, and the+ change of fill is the whole edge between them — no field, no washes, no gap, no corner,+ no shadow (the floating sheet was retired at the owner's review of 2026-09-29). */+ --ui-shell-field: var(--ui-surface-muted);+ --ui-shell-wash-1: transparent;+ --ui-shell-wash-2: transparent;+ --ui-shell-nav-bg: var(--ui-surface-muted);+ --ui-shell-main-bg: var(--ui-canvas);+ --ui-shell-line: transparent;+ --ui-shell-gap: 0px;+ --ui-shell-radius: 0px;+ --ui-shell-shadow: 0 0 #0000;++ /* Structure: a roomy tree (a 0.75rem inset, 1.125rem per level) against a soft guide in the+ line colour; a field keeps the host's label-beside-control row (the label column is+ unused), with a half-rem between label and control. */+ --ui-tree-inset: 0.75rem;+ --ui-tree-indent: 1.125rem;+ --ui-tree-guide: var(--ui-line);+ --ui-field-label-w: auto;+ --ui-field-gap: 0.5rem;++ /* Controls: the switch's off track is the line, its knob the muted ink (5:1 on the track);+ on the accent the knob takes the accent's label ink. */+ --ui-switch-track: var(--color-gray-200);+ --ui-switch-knob: var(--ui-fg-muted);+ --ui-switch-knob-on: var(--ui-accent-fg);+ --ui-switch-knob-line: rgb(0 0 0 / 0.1);++ /* Typography — families. MiSans sets Latin and Chinese alike; the system CJK faces stay ahead+ of the generic fallbacks for the rare ideograph MiSans's slices do not carry. Chrome and+ reading text share the one face. */+ --ui-font-cjk: "MiSans", "PingFang SC", "Microsoft YaHei";+ --ui-font-sans: "MiSans", var(--ui-font-cjk), ui-sans-serif, system-ui, sans-serif;+ --ui-font-ui: var(--ui-font-sans);+ --ui-font-mono:+ "JetBrains Mono Variable", ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono",+ var(--ui-font-cjk), monospace;+ --ui-font-display: var(--ui-font-sans);++ /* Typography — scale and roles: a 15px body at the 16px root, 13px small and caption, and+ titles set large in the regular weight with tightening negative tracking up the scale, the+ way Sierra sets its h1 and h2 (400, −1.3px at 65px). Frost's weights stop at 500. */+ --ui-text-body-size: 0.9375rem;+ --ui-text-body-lh: 1.5;+ --ui-text-small-size: 0.8125rem;+ --ui-text-small-lh: 1.5;+ --ui-text-caption-size: 0.8125rem;+ --ui-text-caption-lh: 1.4;+ --ui-text-code-size: 0.8125rem;+ --ui-text-code-lh: 1.6;+ --ui-text-prose-size: 1rem;+ --ui-text-prose-lh: 1.65;+ --ui-h1-size: 2.25rem;+ --ui-h1-lh: 1.1;+ --ui-h1-weight: 400;+ --ui-h1-tracking: -0.03em;+ --ui-h1-transform: none;+ --ui-h1-font: var(--ui-font-display);+ --ui-h2-size: 1.75rem;+ --ui-h2-lh: 1.15;+ --ui-h2-weight: 400;+ --ui-h2-tracking: -0.025em;+ --ui-h2-transform: none;+ --ui-h2-font: var(--ui-font-display);+ --ui-h3-size: 1.375rem;+ --ui-h3-lh: 1.25;+ --ui-h3-weight: 400;+ --ui-h3-tracking: -0.015em;+ --ui-h3-transform: none;+ --ui-h3-font: var(--ui-font-sans);+ --ui-h4-size: 1.125rem;+ --ui-h4-lh: 1.35;+ --ui-h4-weight: 500;+ --ui-h4-tracking: -0.01em;+ --ui-h4-transform: none;+ --ui-h4-font: var(--ui-font-sans);+ --ui-h5-size: 0.9375rem;+ --ui-h5-lh: 1.5;+ --ui-h5-weight: 500;+ --ui-h5-tracking: 0;+ --ui-h5-transform: none;+ --ui-h5-font: var(--ui-font-sans);+ --ui-h6-size: 0.8125rem;+ --ui-h6-lh: 1.5;+ --ui-h6-weight: 500;+ --ui-h6-tracking: 0;+ --ui-h6-transform: none;+ --ui-h6-font: var(--ui-font-sans);+ --ui-md-h1-size: 1.5rem;+ --ui-md-h2-size: 1.25rem;+ --ui-md-h3-size: 1.0625rem;+ --ui-weight-body: 400;+ --ui-weight-medium: 500;+ --ui-weight-strong: 500;+ --ui-tracking-body: 0;+ --ui-tracking-mono: 0;+ --ui-tracking-label: 0;++ /* Density: a 0.28rem space unit (every Tailwind spacing and size utility scales with it), and+ control, row and menu-row padding a step roomier than the unit alone gives. Pills take wide+ padding-inline. Stacks are the unit's multiples. */+ --ui-space-unit: 0.28rem;+ --ui-control-py-sm: 0.375rem;+ --ui-control-py-md: 0.5rem;+ --ui-control-py-lg: 0.75rem;+ --ui-control-px-sm: 0.875rem;+ --ui-control-px-md: 1.125rem;+ --ui-control-px-lg: 1.375rem;+ --ui-control-gap-sm: 0.375rem;+ --ui-control-gap-md: 0.625rem;+ --ui-row-py: 0.5rem;+ --ui-row-px: 1rem;+ --ui-menu-row-py: 0.5625rem;+ --ui-menu-row-px: 0.75rem;+ --ui-card-p: 1.25rem;+ --ui-panel-p: 1.5rem;+ --ui-stack-0: 0.3125rem;+ --ui-stack-1: 0.625rem;+ --ui-stack-2: 1.25rem;+ --ui-stack-3: 1.875rem;+ --ui-stack-4: 3rem;++ /* Motion: Sierra's cubic-bezier(.4,0,.2,1) for state changes, held to 120–200ms. Layers enter+ on a soft spring (a touch of overshoot, never a bounce) scaling up from 0.96 with a 6px+ blur-in and an 8px slide from their edge, and leave quickly on the overlay-out curve;+ streamed text de-blurs in word by word over 360ms; the sidebar's width settles on a long+ ease-out. */+ --ui-dur-fast: 120ms;+ --ui-dur-base: 200ms;+ --ui-dur-slow: 320ms;+ --ui-ease-out: cubic-bezier(0, 0, 0.2, 1);+ --ui-ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);+ --ui-ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);+ --ui-ease-overlay-in: cubic-bezier(0.16, 1, 0.3, 1);+ --ui-ease-overlay-out: cubic-bezier(0.4, 0, 1, 1);+ --ui-live-timing: linear;+ --ui-dur-enter: 280ms;+ --ui-dur-exit: 160ms;+ --ui-ease-enter: cubic-bezier(0.22, 1.15, 0.36, 1);+ --ui-ease-exit: var(--ui-ease-overlay-out);+ --ui-enter-shift: 8px;+ --ui-enter-scale: 0.96;+ --ui-enter-blur: 6px;+ --ui-dur-reveal: 360ms;+ --ui-reveal-blur: 4px;+ --ui-dur-layout: 320ms;+ --ui-ease-layout: cubic-bezier(0.22, 1, 0.36, 1);++ /* Icons */+ --ui-icon-stroke: 1.6;+ --ui-icon-cap: round;+ --ui-icon-join: round;++ /* Focus, selection and scrollbar. The outline follows the element's radius, so pills get a+ round halo; inputs draw theirs as a box-shadow. */+ --ui-focus-ring: 3px solid color-mix(in srgb, var(--ui-accent) 32%, transparent);+ --ui-focus-ring-offset: 1px;+ --ui-focus-ring-input: 0 0 0 3px color-mix(in srgb, var(--ui-accent) 22%, transparent);+ --ui-selection-bg: rgb(47 102 196 / 0.2);+ --ui-scrollbar-w: thin;+ --ui-scrollbar-thumb: rgb(0 0 0 / 0.2);+ --ui-scrollbar-thumb-hover: rgb(0 0 0 / 0.36);+ --ui-scrollbar-track: transparent;+ --ui-scrollbar-visibility: hover;+ }++ /* Dark: the same cool-neutral ramp inverted — calm greys, fills rather than lines, the body+ ink a light grey and the near-white kept for headings. */+ :root[data-theme="modern"].dark {+ /* Tailwind bridge: 950 canvas, 900 surface, 800 grouped rows / hover, 700 control line, then+ the ink ramp — 500 subtle, 400 muted, 100 body, 50 the near-white for headings. white+ stays literal: `dark:*-white/N` hairlines read it as ink. */+ --color-white: #ffffff;+ --color-gray-50: #f5f5f6;+ --color-gray-100: #e4e4e5;+ --color-gray-200: #cfd0d2;+ --color-gray-300: #bcbdbf;+ --color-gray-400: #adaeb0;+ --color-gray-500: #95979a;+ --color-gray-600: #6a6c70;+ --color-gray-700: #3a3c3f;+ --color-gray-800: #2f3033;+ --color-gray-900: #232426;+ --color-gray-950: #1b1c1e;++ /* Colour — surfaces: the navigation column a step below the canvas, cards a step above,+ grouped rows another */+ --ui-canvas: #1b1c1e;+ --ui-surface: #232426;+ --ui-surface-muted: #2a2b2e;+ --ui-inset: #161718;+ --ui-overlay: #262729;+ --ui-overlay-backdrop: rgb(0 0 0 / 0.55);++ /* Colour — text: body about 11:1 on the muted surface, muted 6.5:1 and subtle 4.9:1 there */+ --ui-fg: var(--color-gray-100);+ --ui-fg-emphasis: var(--color-gray-50);+ --ui-fg-muted: var(--color-gray-400);+ --ui-fg-subtle: var(--color-gray-500);+ --ui-fg-link: #8bbff5;+ --ui-fg-link-hover: #b8d7f9;++ /* Colour — lines */+ --ui-line: rgb(255 255 255 / 0.07);+ --ui-line-muted: rgb(255 255 255 / 0.04);+ --ui-line-emphasis: rgb(255 255 255 / 0.16);+ --ui-divider: rgb(255 255 255 / 0.04);++ /* Colour — accent. The green lifts and takes the canvas as ink (white on it is under+ 4.5:1), so hover now shades toward white and active toward black — away from the ink,+ as in light — and the wash and the line strengthen a step on the dark page. */+ --ui-accent: #4aa45c;+ --ui-accent-hover: color-mix(in srgb, var(--ui-accent) 86%, #ffffff);+ --ui-accent-active: color-mix(in srgb, var(--ui-accent) 90%, #000000);+ --ui-accent-fg: #111214;+ --ui-accent-muted: color-mix(in srgb, var(--ui-accent) 18%, transparent);+ --ui-accent-line: color-mix(in srgb, var(--ui-accent) 45%, transparent);++ /* Colour — semantic tones: the tints lifted; a tone's line stays its tint */+ --ui-tone-success-fg: #7ed185;+ --ui-tone-success-bg: rgb(126 209 133 / 0.14);+ --ui-tone-success-emphasis: #2a7a3f;+ --ui-tone-attention-fg: #ebc247;+ --ui-tone-attention-bg: rgb(235 194 71 / 0.14);+ --ui-tone-attention-emphasis-fg: #1b1c1e;+ --ui-tone-danger-fg: #f0765a;+ --ui-tone-danger-bg: rgb(233 78 42 / 0.16);+ --ui-tone-danger-emphasis: #c23a1c;+ --ui-tone-done-fg: #c9a8f0;+ --ui-tone-done-bg: rgb(166 115 222 / 0.16);+ --ui-tone-done-emphasis: #7f52b5;+ --ui-tone-neutral-fg: var(--color-gray-300);+ --ui-tone-neutral-bg: rgb(255 255 255 / 0.06);+ --ui-tone-neutral-emphasis: #5a5c60;+ --ui-tone-info-fg: #8bbff5;+ --ui-tone-info-bg: rgb(139 191 245 / 0.14);+ --ui-tone-info-emphasis: #3a6bc4;++ /* Charts: the same roles lifted for the dark page */+ --ui-chart-1: #9f90d4;+ --ui-chart-2: #c4a45f;+ --ui-chart-3: #84a8d6;+ --ui-chart-4: #d494ab;+ --ui-chart-5: #86b99b;+ --ui-chart-6: #c99ac5;+ --ui-chart-7: #82b5b0;+ --ui-chart-8: #d3a281;+ --ui-chart-cache-read: #c5d8ee;+ --ui-chart-cache-write: #8fb1dc;+ --ui-chart-output: #6a8fc0;+ --ui-chart-bar-opacity: 0.78;+ --ui-chart-grid: rgb(255 255 255 / 0.06);+ --ui-chart-axis: var(--color-gray-500);++ /* Colour — code */+ --ui-code-bg: #161718;+ --ui-code-line: rgb(255 255 255 / 0.07);+ --ui-code-gutter: var(--color-gray-500);+ --ui-code-selection: rgb(139 191 245 / 0.22);+ --ui-diff-add-bg: rgb(126 209 133 / 0.1);+ --ui-diff-add-word: rgb(126 209 133 / 0.28);+ --ui-diff-del-bg: rgb(233 78 42 / 0.12);+ --ui-diff-del-word: rgb(233 78 42 / 0.32);+ --ui-diff-hunk-bg: rgb(139 191 245 / 0.1);++ /* Elevation: a faint top edge on raised surfaces; overlays keep a soft drop, their edge a+ light hairline of their own. */+ --ui-shadow-raised: inset 0 1px 0 rgb(255 255 255 / 0.04);+ --ui-shadow-overlay: 0 4px 16px -4px rgb(0 0 0 / 0.5);+ --ui-shadow-modal: 0 12px 40px -12px rgb(0 0 0 / 0.6);+ --ui-glass-bg: rgb(35 36 38 / 0.85);+ --ui-glass-line: rgb(255 255 255 / 0.08);++ /* Shell: the navigation column a step below the canvas; the rest keeps its base values */+ --ui-shell-field: #17181a;+ --ui-shell-nav-bg: #17181a;++ /* Controls: the dark off track, and the body ink as the knob on it */+ --ui-switch-track: var(--color-gray-700);+ --ui-switch-knob: var(--ui-fg);++ /* Focus, selection and scrollbar */+ --ui-focus-ring: 3px solid color-mix(in srgb, var(--ui-accent) 40%, transparent);+ --ui-focus-ring-input: 0 0 0 3px color-mix(in srgb, var(--ui-accent) 28%, transparent);+ --ui-selection-bg: rgb(139 191 245 / 0.28);+ --ui-scrollbar-thumb: rgb(255 255 255 / 0.16);+ --ui-scrollbar-thumb-hover: rgb(255 255 255 / 0.3);+ }++ /*+ * Style hooks (hooks.ts). A component opts into a hook with its class; this theme decides what+ * the hook does. These rules sit in `ui-theme`, after Tailwind's `utilities`, so a hook wins over+ * the utilities its component also carries — that is what lets `.ui-live` re-time an+ * `animate-spin`, `.ui-glass` replace a panel's opaque fill and `.ui-shell` re-paint the+ * window's columns.+ *+ * Frost gives all fourteen a recipe: glass, eyebrow (its ink; the rung is theme.css's),+ * display, live, frame, underline-nav, shell, icon-decor, tree, field, activity, notice, chart,+ * scrim.+ */++ /* Frosted transient layer: menus, popovers, tooltips and the floating composer — the small+ layers with content moving underneath, which is what a light frost shows. Never on cards,+ the sidebar or the login card, where nothing scrolls behind. Elevation stays the host's own+ shadow token; the edge is the glass hairline, barely there. */+ :root[data-theme="modern"] .ui-glass {+ background-color: var(--ui-glass-bg);+ -webkit-backdrop-filter: blur(var(--ui-glass-blur)) saturate(var(--ui-glass-saturate));+ backdrop-filter: blur(var(--ui-glass-blur)) saturate(var(--ui-glass-saturate));+ border-color: var(--ui-glass-line);+ }+ /* A dialog is opaque, unfrosted and edgeless, with the large corner, on a dimmed backdrop —+ the reference's About and settings dialogs: a page of its own to read, nothing of the page+ behind showing through (even at 96% the Settings dialog let the transcript's lines ghost+ through its rows). Menus, popovers and tooltips keep the frost at a translucency whose ink+ clears 4.5:1 on the worst backdrop — the contrast suite measures the glass over black in+ light and over white in dark. */+ :root[data-theme="modern"] .ui-glass[role="dialog"] {+ background-color: var(--ui-overlay);+ -webkit-backdrop-filter: none;+ backdrop-filter: none;+ border-color: transparent;+ border-radius: var(--ui-radius-lg);+ }+ @supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {+ :root[data-theme="modern"] .ui-glass {+ background-color: color-mix(in srgb, var(--ui-overlay) 96%, transparent);+ }+ }+ @media (prefers-reduced-transparency: reduce) {+ :root[data-theme="modern"] .ui-glass {+ background-color: color-mix(in srgb, var(--ui-overlay) 96%, transparent);+ -webkit-backdrop-filter: none;+ backdrop-filter: none;+ }+ }++ /* The scrim — the dimmed layer behind a dialog, drawer or sheet: the page blurs behind it+ under the host's dim (--ui-overlay-backdrop), the reference's frosted backdrop, in both+ modes. The blur is the scrim's backdrop only — a backdrop filter never reaches an element's+ own descendants — so a dialog drawn inside the scrim stays sharp; and the scrim is already+ fixed to the viewport, so becoming a containing block moves nothing. Without backdrop+ filters, or under reduced transparency, the dim alone remains. */+ :root[data-theme="modern"] .ui-scrim {+ -webkit-backdrop-filter: blur(14px);+ backdrop-filter: blur(14px);+ }+ @supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {+ :root[data-theme="modern"] .ui-scrim {+ background-color: var(--ui-overlay-backdrop);+ }+ }+ @media (prefers-reduced-transparency: reduce) {+ :root[data-theme="modern"] .ui-scrim {+ -webkit-backdrop-filter: none;+ backdrop-filter: none;+ }+ }++ /* Group label, in sentence case on the h6 rung (theme.css), in the muted ink. */+ :root[data-theme="modern"] .ui-eyebrow {+ color: var(--ui-fg-muted);+ }++ /* Regular-weight display title with tight tracking. */+ :root[data-theme="modern"] .ui-display {+ font-weight: 400;+ letter-spacing: -0.03em;+ }++ :root[data-theme="modern"] .ui-live {+ animation-timing-function: var(--ui-live-timing);+ }+ :root[data-theme="modern"] .ui-live[data-live="caret"] {+ animation-duration: 1.2s;+ }++ /* Tool cards, code blocks and the work group: rounded on the box scale with an edge that+ barely exists, the header inside the box with no fill or rule of its own — it takes the+ box's fill rather than none, because a work group's header sticks while its rows scroll+ under it and must stay opaque. */+ :root[data-theme="modern"] .ui-frame {+ border-radius: var(--ui-radius-md);+ border-color: var(--ui-line-muted);+ }+ :root[data-theme="modern"] .ui-frame > [data-slot="head"] {+ background-color: inherit;+ border-bottom-color: transparent;+ }++ /* A work group — a frame headed by a step of the agent's work, open or collapsed — is lineless+ in every state, the way Codex and macOS list work: no card border, no fill, no rule under+ the header or between the rows. Header and rows sit on the page, painted in its colour so+ they stay opaque while they stick, spaced by whitespace, and a hover is a soft rounded+ highlight; a running step adds nothing but the sweep across its label. */+ :root[data-theme="modern"] .ui-frame:has(> .ui-activity) {+ border-color: transparent;+ background-color: transparent;+ box-shadow: none;+ }+ :root[data-theme="modern"] .ui-frame:has(> .ui-activity) > * {+ border-color: transparent;+ }+ :root[data-theme="modern"] .ui-frame:has(> .ui-activity) > [data-slot="head"],+ :root[data-theme="modern"] .ui-frame:has(> .ui-activity) .ui-tree .ui-activity {+ border-radius: var(--ui-radius-sm);+ background-color: var(--ui-canvas);+ }+ :root[data-theme="modern"] .ui-frame:has(> .ui-activity) > [data-slot="head"]:hover,+ :root[data-theme="modern"] .ui-frame:has(> .ui-activity) .ui-tree .ui-activity:hover {+ background-color: var(--ui-surface-muted);+ }+ :root[data-theme="modern"] .ui-frame:has(> .ui-activity) .ui-tree > [data-depth] {+ border-color: transparent;+ margin-block: var(--ui-stack-0);+ }++ /* Tabs: a rounded accent bar under the selected tab. */+ :root[data-theme="modern"] .ui-underline-nav [role="tab"] {+ position: relative;+ }+ :root[data-theme="modern"] .ui-underline-nav [role="tab"]::after {+ content: "";+ position: absolute;+ inset-inline: 0.5rem;+ bottom: -1px;+ height: 2px;+ border-radius: var(--ui-radius-pill);+ background-color: transparent;+ transition: background-color var(--ui-dur-fast) var(--ui-ease-out);+ pointer-events: none;+ }+ :root[data-theme="modern"] .ui-underline-nav [role="tab"]:hover::after {+ background-color: var(--ui-line);+ }+ :root[data-theme="modern"] .ui-underline-nav [role="tab"][aria-selected="true"]::after {+ background-color: var(--ui-accent);+ }++ /* The app window, flat: the navigation column on the muted grey, the main column and the dock+ on the canvas, and the change of fill the whole edge between them — the shell tokens set no+ gap, corner, shadow or wash, so the recipe below (which still reads them, as the tokens may+ yet say otherwise) paints nothing but the two fills. A host's rule between the columns turns+ transparent. */+ :root[data-theme="modern"] .ui-shell {+ background-color: var(--ui-shell-field);+ background-image:+ radial-gradient(70% 60% at 0% 0%, var(--ui-shell-wash-1), transparent 70%),+ radial-gradient(60% 55% at 100% 100%, var(--ui-shell-wash-2), transparent 70%);+ }+ :root[data-theme="modern"] .ui-shell > [data-slot="nav"] {+ background-color: var(--ui-shell-nav-bg);+ border-color: var(--ui-shell-line);+ }+ :root[data-theme="modern"] .ui-shell > [data-slot="main"],+ :root[data-theme="modern"] .ui-shell > [data-slot="dock"] {+ margin: var(--ui-shell-gap);+ border-radius: var(--ui-shell-radius);+ border-color: var(--ui-shell-line);+ background-color: var(--ui-shell-main-bg);+ box-shadow: var(--ui-shell-shadow);+ overflow: clip;+ }+ :root[data-theme="modern"] .ui-shell > [data-slot="nav"] + [data-slot="main"],+ :root[data-theme="modern"] .ui-shell > [data-slot="main"] + [data-slot="dock"] {+ margin-inline-start: 0;+ }+ /* Decorative icons are drawn in the muted ink, as the reference's sidebar draws its glyphs —+ quiet, one colour, beside labels in the body ink; a menu row's icon keeps the row's own ink+ (a danger row's stays as red as its label). Ink only: no tinted chip behind an icon. */+ :root[data-theme="modern"] .ui-icon-decor:not([data-role="menu"]) {+ color: var(--ui-fg-muted);+ }++ /* Nested rows sit against a soft guide inside the host's own card: each row past its tree's+ first level indents on the tree tokens and draws a hairline down its parent's column — half+ an indent before its own content — and a branch continues its parent's guide alongside the+ rows it holds, so every ancestor's guide runs the whole way down. No elbows and no box of+ its own. The first level is the tree's base (theme.css): a file tree's roots sit at the+ inset, and a work group's steps, which hang off the header, sit flush with it — their+ icons in the header's icon column, no gutter and no guide, the card alone holding them. */+ :root[data-theme="modern"] .ui-tree [data-depth]:not([data-branch]) {+ position: relative;+ padding-inline-start: calc(+ var(--_lead) + var(--ui-tree-indent) * (var(--_depth) - var(--_base))+ );+ }+ :root[data-theme="modern"] .ui-tree [data-depth]:not([data-branch], [data-depth="0"])::before {+ content: "";+ position: absolute;+ inset-block: 0;+ inset-inline-start: calc(+ var(--_lead) + var(--ui-tree-indent) * (var(--_depth) - var(--_base) - 0.5)+ );+ border-inline-start: var(--ui-border-w) solid var(--ui-tree-guide);+ pointer-events: none;+ }+ :root[data-theme="modern"] .ui-tree [data-branch] {+ position: relative;+ }+ :root[data-theme="modern"]+ .ui-tree+ [data-branch]:not([data-depth="0"], [data-depth="1"])::before {+ content: "";+ position: absolute;+ inset-block: 0;+ inset-inline-start: calc(+ var(--_lead) + var(--ui-tree-indent) * (var(--_depth) - var(--_base) - 1.5)+ );+ border-inline-start: var(--ui-border-w) solid var(--ui-tree-guide);+ pointer-events: none;+ }+ /* In a tree that starts a level in, its first level has no parent column to draw on. */+ :root[data-theme="modern"] .ui-tree:not(:has([data-depth="0"])) [data-depth="1"]::before,+ :root[data-theme="modern"]+ .ui-tree:not(:has([data-depth="0"]))+ [data-branch][data-depth="2"]::before {+ content: none;+ }++ /* A labelled control row is a band in a grouped block, the way the reference lists its+ settings: the muted fill, the row's own padding, the label beside its control (the host's+ layout), the host's faint divider between rows, and the block's corners rounded on its first+ and last rows. Grouping by fill, not by border. */+ :root[data-theme="modern"] .ui-field {+ padding: var(--ui-row-py) var(--ui-row-px);+ background-color: var(--ui-surface-muted);+ }+ :root[data-theme="modern"] .ui-field:first-child {+ border-start-start-radius: var(--ui-radius-md);+ border-start-end-radius: var(--ui-radius-md);+ }+ :root[data-theme="modern"] .ui-field:last-child {+ border-end-start-radius: var(--ui-radius-md);+ border-end-end-radius: var(--ui-radius-md);+ }++ /* Work in progress is shown the way Codex and macOS show it: nothing around the row — no+ fill, no border, no ring, no halo (a first pass drew a luminous surface; the owner asked+ for the lineless version) — and a soft highlight in the accent's hue sweeping across the+ label, beside the host's own status mark. At rest (done, error) the row is the host's plain+ row, so a finished transcript adds nothing. The highlight is a gradient clipped to the+ label's glyphs and slid across them; parked at either end it shows only the ink, which is+ what reduced motion shows: a plain label. The slots are found anywhere inside the row (a+ card nests them in its own button); a work group's header shares the recipe with its rows. */+ :root[data-theme="modern"] .ui-activity[data-state="running"] [data-slot="label"] {+ color: var(--ui-fg);+ background-image: linear-gradient(+ 90deg,+ currentColor 0 38%,+ var(--ui-accent) 50%,+ currentColor 62% 100%+ );+ background-size: 300% 100%;+ background-position: 100% 0;+ background-repeat: no-repeat;+ -webkit-background-clip: text;+ background-clip: text;+ -webkit-text-fill-color: transparent;+ animation: ui-frost-shimmer 2.8s var(--ui-ease-in-out) infinite;+ }+ @keyframes ui-frost-shimmer {+ from {+ background-position: 100% 0;+ }+ to {+ background-position: 0% 0;+ }+ }++ /* A notice is a soft card: the overlay surface under the overlay's shadow, no coloured border+ and no tinted fill — the tone is one small dot of its ink at the start (a toast is a button;+ the dot is its `::before`, which a button draws too). The dot sits out of the flow,+ absolutely at the row's inset with the host padded to make room, because a host lays its+ body and actions out as a flex row — a dot in the flow would be a third item and push the+ body to the middle. A toast that also carries `ui-glass` frosts like every other floating+ layer. */+ :root[data-theme="modern"] .ui-notice {+ position: relative;+ padding-inline-start: calc(var(--ui-row-px) + 1.125em);+ border-color: transparent;+ border-radius: var(--ui-radius-lg);+ background-color: var(--ui-overlay);+ box-shadow: var(--ui-shadow-overlay);+ color: var(--ui-fg);+ }+ /* The host's own leading mark gives way to the dot: two marks would say the same thing. */+ :root[data-theme="modern"] .ui-notice [data-slot="icon"] {+ display: none;+ }+ :root[data-theme="modern"] .ui-notice::before {+ content: "";+ position: absolute;+ inset-inline-start: var(--ui-row-px);+ top: 50%;+ width: 0.5em;+ height: 0.5em;+ margin-top: -0.25em;+ border-radius: var(--ui-radius-pill);+ background-color: var(--_tone-fg);+ }++ /* Charts: the chart primitives write everything a token can say — colours, widths, radii,+ opacities, the curve — so the recipe owns only what a token cannot: lines join and end+ round, a line's area fades to nothing towards the baseline (a mask, the one gradient a+ chart may paint), and a point wears a thin ring of the surface. */+ :root[data-theme="modern"] .ui-chart :is(path, polyline)[data-part="series"] {+ stroke-linejoin: round;+ stroke-linecap: round;+ }+ :root[data-theme="modern"] .ui-chart [data-part="area"] {+ -webkit-mask-image: linear-gradient(to bottom, #000000, transparent);+ mask-image: linear-gradient(to bottom, #000000, transparent);+ }+ :root[data-theme="modern"] .ui-chart [data-part="point"] {+ stroke: var(--ui-surface);+ stroke-width: 1.5;+ }++ /* MiSans ships Regular (400) and Medium (500) only. A heavier request renders in Medium rather+ than as a synthesized bold, which smears Han strokes; Frost's own weights stop at 500. */+ :root[data-theme="modern"] {+ font-synthesis-weight: none;+ }++ /* Scrollbar thumbs show only while the pointer is over their scroller (--ui-scrollbar-visibility). */+ :root[data-theme="modern"] :not(:hover) {+ scrollbar-color: transparent var(--ui-scrollbar-track);+ }+}++/*+ * The user's accent presets (tokens.ts, `ACCENT_PRESETS.modern`): five warm, muted hues beside+ * Frost's own forest green, each deep enough in light for the theme's white label and lifted in+ * dark for its dark ink, the way the theme's own accent flips. A preset sets `--ui-accent` and+ * nothing else — hover, active, wash and line derive from it in the theme's rules above, and+ * the label ink is the theme's for the mode — so each preset is one value per mode. The+ * selectors match only Frost's root, so a preset another theme lists paints nothing here.+ */+@layer ui-accent {+ :root[data-theme="modern"][data-accent="ocean"] {+ --ui-accent: #3b6ea8;+ }+ :root[data-theme="modern"][data-accent="ocean"].dark {+ --ui-accent: #7fa9df;+ }+ :root[data-theme="modern"][data-accent="clay"] {+ --ui-accent: #b8552f;+ }+ :root[data-theme="modern"][data-accent="clay"].dark {+ --ui-accent: #e08a66;+ }+ :root[data-theme="modern"][data-accent="plum"] {+ --ui-accent: #7a4d8f;+ }+ :root[data-theme="modern"][data-accent="plum"].dark {+ --ui-accent: #b78fd0;+ }+ :root[data-theme="modern"][data-accent="honey"] {+ --ui-accent: #96660f;+ }+ :root[data-theme="modern"][data-accent="honey"].dark {+ --ui-accent: #d9ab4a;+ }+ :root[data-theme="modern"][data-accent="slate"] {+ --ui-accent: #5c6470;+ }+ :root[data-theme="modern"][data-accent="slate"].dark {+ --ui-accent: #9ea6b3;+ }+}diff --git a/packages/ui/src/tokens.ts b/packages/ui/src/tokens.tsnew file mode 100644index 00000000..801c0d02--- /dev/null+++ b/packages/ui/src/tokens.ts@@ -0,0 +1,539 @@+/**+ * The token contract: every CSS custom property a theme must define, grouped the way the+ * gallery's Foundations pages present them.+ *+ * One name set for every theme. Each of `themes/github.css`, `themes/modern.css` and+ * `themes/geek.css` gives **every** name below a value in **both** modes (light and dark): its+ * base rule declares all of them with the light values, and its dark rule declares only the names+ * whose value dark changes — a group that does not vary by mode (shape, families, type scale,+ * density, motion, icons) lives once, in the base rule. The contract test parses the three files+ * and diffs each mode (the base rule plus that mode's own) against {@link TOKEN_NAMES}. Components+ * read these names only — through the semantic Tailwind utilities `theme.css` bridges+ * (`bg-surface`, `text-fg-muted`, `border-line`, …) or through `var(--ui-*)` directly — and never+ * branch on which theme is active.+ *+ * Adding, renaming or removing a name is a contract change: every theme file changes in the+ * same commit, and so does the bridge in `theme.css` when the name has a utility alias.+ *+ * Nothing about size is shared between themes any more. Each theme sets its own space unit+ * (`--ui-space-unit`, which `theme.css` bridges to Tailwind's `--spacing`, so every `h-8`, `px-2`,+ * `gap-3` and `w-64` scales with it), its own type rungs and line-heights, and its own control,+ * row and menu-row padding; switching themes reflows a layout, by design (user decision,+ * 2026-09-19). What every theme still shares is the NAMES, the markup they act on and the+ * anatomy the style hooks rely on — a component never asks which theme is active. All type and+ * density lengths are rem, so the 16 / 18 / 20 px root tiers keep scaling them within a theme.+ *+ * Two faces, not one: `--ui-font-ui` is the chrome's face (navigation, controls, labels, headings,+ * badges, tables — `body` reads it), `--ui-font-sans` the reading face (message text, prose, the+ * composer's input, which opt in with `font-sans`). Primer and Frost point both at one family;+ * Console sets the chrome in a monospaced face and keeps reading text in a sans. Every sans+ * stack reads `--ui-font-cjk` for Han, so the user's font pairing (boot.ts, `data-font-latin` /+ * `data-font-cjk`, resolved in `theme.css`'s `ui-font` layer) replaces the sans and the CJK face+ * under any theme and leaves the mono face alone.+ *+ * Dark mode is calmer than a white-on-black inversion, but not dim: `--ui-fg` is the body ink+ * at roughly 84% white (about 12:1 on the page surfaces, never under 11:1 — the owner found a+ * first, 9:1 pass too dim), `--ui-fg-emphasis` the near-white kept for headings and emphasis+ * (the two are one value in light), and the muted and subtle inks step down from the body ink+ * (muted never under 6:1, subtle — timestamps, placeholders, meta — never under 4.5:1).+ * Surfaces sit a step off pure black.+ *+ * Motion is three languages behind one set of names: the presence tokens (`--ui-dur-enter`,+ * `--ui-enter-shift`, `--ui-enter-scale`, `--ui-enter-blur`, …) drive the theme-independent+ * rules in `theme.css` for `data-presence`, `data-backdrop`, `data-reveal` and+ * `data-layout-motion`; a theme picks a quick fade, a soft spring or a `steps()` jump by value+ * alone. `--ui-dur-fast` / `base` / `slow` stay the state-change durations a component may name.+ */++/** Stable, lowercase theme ids. Display names (Primer / Frost / Console) are UI copy, not ids. */+export const THEME_IDS = ["github", "modern", "geek"] as const;+export type ThemeId = (typeof THEME_IDS)[number];++/** The theme an absent or unknown `data-theme` resolves to. Its file needs no attribute selector. */+export const DEFAULT_THEME_ID: ThemeId = "github";++/** The two modes every theme file defines. `system` is a preference, not a mode. */+export const THEME_MODES = ["light", "dark"] as const;+export type ThemeModeName = (typeof THEME_MODES)[number];++/**+ * One accent preset a theme lists: its id (the `data-accent` value, lowercase, the same in both+ * languages) and its swatch — the `--ui-accent` its light rule sets, spelled exactly as the theme+ * file spells it, so a picker can paint the swatch without a stylesheet probe. A theme's dark rule+ * may lift the preset (a dark theme wants a lighter fill with dark ink); the swatch is the light+ * one, and a test holds it equal to the CSS.+ */+export interface AccentPresetSpec {+ readonly id: string;+ readonly swatch: string;+}++/**+ * The user's accent presets, per theme (user decision, 2026-09-19). Each theme declares its own+ * list and values in its own file, in `@layer ui-accent`, on `:root[data-accent="<id>"]` scoped to+ * that theme. A preset sets `--ui-accent` — and `--ui-accent-fg` where its label's ink differs+ * from the theme's — and nothing outside the accent group: Frost and Console derive the hover+ * and active fills and the muted and line washes from `--ui-accent` in their base rules, so a+ * preset is one value per mode and carries no second copy of the family. Primer's five keep all+ * six values literal, byte for byte what the Web App has always rendered. `neutral` is the+ * absence of a preset — no `data-accent` attribute — and resolves to the active theme's accent.+ *+ * A stored choice outlives the theme that listed it: the root carries `data-accent` for any known+ * id, a theme's preset rules match only their own theme, so a preset the active theme does not+ * list paints nothing (the theme's own accent shows, as `neutral` would) and comes back when the+ * user returns to a theme that lists it. Primer keeps the five ids and values the Web App has+ * always had, so nothing there moves; Frost's five are warm and muted; Console's six are the+ * orange it shipped with and five terminal hues — its own accent went black and white+ * (2026-09-30), so the orange became a preset.+ */+export const ACCENT_PRESETS = {+ github: [+ { id: "blue", swatch: "#2563eb" },+ { id: "green", swatch: "#15803d" },+ { id: "violet", swatch: "#7c3aed" },+ { id: "rose", swatch: "#be123c" },+ { id: "amber", swatch: "#b45309" },+ ],+ modern: [+ { id: "ocean", swatch: "#3b6ea8" },+ { id: "clay", swatch: "#b8552f" },+ { id: "plum", swatch: "#7a4d8f" },+ { id: "honey", swatch: "#96660f" },+ { id: "slate", swatch: "#5c6470" },+ ],+ geek: [+ { id: "orange", swatch: "#e32a01" },+ { id: "phosphor", swatch: "#1f7a1f" },+ { id: "cyan", swatch: "#0e7490" },+ { id: "magenta", swatch: "#b0177e" },+ { id: "gold", swatch: "#8a6d00" },+ { id: "cobalt", swatch: "#003ee9" },+ ],+} as const satisfies Readonly<Record<ThemeId, readonly AccentPresetSpec[]>>;++/** Every preset id any theme lists. */+export type AccentPreset = (typeof ACCENT_PRESETS)[ThemeId][number]["id"];++/** The preset ids each theme lists, in the theme's own order — what a picker offers. */+export const THEME_ACCENT_PRESETS: Readonly<Record<ThemeId, readonly AccentPreset[]>> = {+ github: ACCENT_PRESETS.github.map((preset) => preset.id),+ modern: ACCENT_PRESETS.modern.map((preset) => preset.id),+ geek: ACCENT_PRESETS.geek.map((preset) => preset.id),+};++/** Every id once, across the themes — what a stored value is validated against. */+export const ACCENT_PRESET_IDS: readonly AccentPreset[] = [+ ...new Set(THEME_IDS.flatMap((id) => THEME_ACCENT_PRESETS[id])),+];++/**+ * The accent a theme paints when no preset is chosen (`neutral`): its own `--ui-accent` per+ * mode, spelled as the theme file spells it, so a picker can paint the "theme's own" swatch+ * without a stylesheet probe (a test holds each value equal to the CSS). Primer's and Console's+ * are monochrome — the ink in light, a near-white in dark — so that swatch shows black or white+ * rather than a hue; Frost's is its green.+ */+export const THEME_OWN_ACCENTS: OwnAccents = {+ github: { light: "#111827", dark: "#f3f4f6" },+ modern: { light: "#006838", dark: "#4aa45c" },+ geek: { light: "#1d1d1f", dark: "#f4f2f2" },+};+type OwnAccents = Readonly<Record<ThemeId, Readonly<Record<ThemeModeName, string>>>>;++/**+ * What a stored choice paints under a theme: the preset when the theme lists it, otherwise+ * `null` — the theme's own accent, exactly as `neutral`. The CSS resolves the same way on its+ * own; this is for a picker that must show which swatch is in effect.+ */+export function resolveAccent(+ themeId: ThemeId,+ choice: string | null | undefined,+): AccentPreset | null {+ const listed = THEME_ACCENT_PRESETS[themeId];+ return (listed as readonly string[]).includes(choice ?? "") ? (choice as AccentPreset) : null;+}++/** Semantic tones. `busy` is a JS alias of `success` (see the web app's `tone.ts`), not a token. */+export const TONES = ["success", "attention", "danger", "done", "neutral", "info"] as const;+export type ToneName = (typeof TONES)[number];++/** The five parts every tone defines. */+export const TONE_PARTS = ["fg", "bg", "line", "emphasis", "emphasis-fg"] as const;+export type TonePart = (typeof TONE_PARTS)[number];++/** Token groups, in the order the Foundations pages and the theme files list them. */+export const TOKEN_GROUPS = [+ {+ id: "color-surfaces",+ title: "Colour — surfaces",+ names: [+ "--ui-canvas",+ "--ui-surface",+ "--ui-surface-muted",+ "--ui-inset",+ "--ui-overlay",+ "--ui-overlay-backdrop",+ ],+ },+ {+ id: "color-text",+ title: "Colour — text",+ // `fg` is the body ink; `fg-emphasis` the strong ink of headings and emphasis (the same+ // value in light, near-white in dark where the body ink is calmer).+ names: [+ "--ui-fg",+ "--ui-fg-emphasis",+ "--ui-fg-muted",+ "--ui-fg-subtle",+ "--ui-fg-link",+ "--ui-fg-link-hover",+ ],+ },+ {+ id: "color-lines",+ title: "Colour — lines",+ names: ["--ui-line", "--ui-line-muted", "--ui-line-emphasis", "--ui-divider"],+ },+ {+ id: "color-accent",+ title: "Colour — accent",+ names: [+ "--ui-accent",+ "--ui-accent-hover",+ "--ui-accent-active",+ "--ui-accent-fg",+ "--ui-accent-muted",+ "--ui-accent-line",+ ],+ },+ {+ id: "color-tones",+ title: "Colour — semantic tones",+ names: [+ "--ui-tone-success-fg",+ "--ui-tone-success-bg",+ "--ui-tone-success-line",+ "--ui-tone-success-emphasis",+ "--ui-tone-success-emphasis-fg",+ "--ui-tone-attention-fg",+ "--ui-tone-attention-bg",+ "--ui-tone-attention-line",+ "--ui-tone-attention-emphasis",+ "--ui-tone-attention-emphasis-fg",+ "--ui-tone-danger-fg",+ "--ui-tone-danger-bg",+ "--ui-tone-danger-line",+ "--ui-tone-danger-emphasis",+ "--ui-tone-danger-emphasis-fg",+ "--ui-tone-done-fg",+ "--ui-tone-done-bg",+ "--ui-tone-done-line",+ "--ui-tone-done-emphasis",+ "--ui-tone-done-emphasis-fg",+ "--ui-tone-neutral-fg",+ "--ui-tone-neutral-bg",+ "--ui-tone-neutral-line",+ "--ui-tone-neutral-emphasis",+ "--ui-tone-neutral-emphasis-fg",+ "--ui-tone-info-fg",+ "--ui-tone-info-bg",+ "--ui-tone-info-line",+ "--ui-tone-info-emphasis",+ "--ui-tone-info-emphasis-fg",+ ],+ },+ {+ id: "chart",+ title: "Charts — series colours and geometry",+ // The categorical palette has fixed roles across themes — 1 violet, 2 amber, 3 sky, 4 rose,+ // 5 emerald, 6 fuchsia, 7 teal, 8 orange in Primer's hues, each theme picking its own hue+ // for the role — and the usage charts take entity series from 1–4 in order, the Trace+ // timeline its phases from 1, 3, 2, 4 and 5. `ref` is a reference line (a hit-rate or+ // success-rate curve); the three token-kind blues stay their own. The geometry is what a+ // chart draws with, read once per theme through the app's chart-style hook: the share of+ // its band a bar fills (0–1), a bar's top radius, the series stroke, the point radius, how+ // a line joins its points (`linear` | `smooth` | `step`), the fill under a line (0–1), and a+ // bar's outline — its width, its colour (a colour, or the exact keyword `series` for the+ // bar's own series colour) — and the bar's fill opacity (0–1): a theme may draw a bar pale+ // and edge it in the full series colour. Lengths are px: the charts draw in SVG user units.+ names: [+ "--ui-chart-1",+ "--ui-chart-2",+ "--ui-chart-3",+ "--ui-chart-4",+ "--ui-chart-5",+ "--ui-chart-6",+ "--ui-chart-7",+ "--ui-chart-8",+ "--ui-chart-ref",+ "--ui-chart-cache-read",+ "--ui-chart-cache-write",+ "--ui-chart-output",+ "--ui-chart-grid",+ "--ui-chart-axis",+ "--ui-chart-bar-fill",+ "--ui-chart-bar-radius",+ "--ui-chart-line-width",+ "--ui-chart-point-radius",+ "--ui-chart-curve",+ "--ui-chart-area-opacity",+ "--ui-chart-bar-stroke",+ "--ui-chart-bar-stroke-color",+ "--ui-chart-bar-opacity",+ ],+ },+ {+ id: "color-code",+ title: "Colour — code",+ names: [+ "--ui-code-bg",+ "--ui-code-line",+ "--ui-code-gutter",+ "--ui-code-selection",+ "--ui-diff-add-bg",+ "--ui-diff-add-word",+ "--ui-diff-del-bg",+ "--ui-diff-del-word",+ "--ui-diff-hunk-bg",+ ],+ },+ {+ id: "shape",+ title: "Shape",+ names: [+ "--ui-radius-xs",+ "--ui-radius-sm",+ "--ui-radius-md",+ "--ui-radius-lg",+ "--ui-radius-xl",+ "--ui-radius-pill",+ "--ui-radius-control",+ "--ui-border-w",+ "--ui-border-w-thick",+ ],+ },+ {+ id: "elevation",+ title: "Elevation",+ names: [+ "--ui-shadow-flat",+ "--ui-shadow-raised",+ "--ui-shadow-overlay",+ "--ui-shadow-modal",+ "--ui-shadow-drawer",+ "--ui-glass-bg",+ "--ui-glass-blur",+ "--ui-glass-saturate",+ "--ui-glass-line",+ ],+ },+ {+ id: "shell",+ title: "Shell",+ // The app window's own frame (the `ui-shell` hook): the field behind it, the two washes a+ // theme may paint over the field, the two columns' fills, the rule between them, and the main+ // column's inset, corner and shadow when it floats. Primer's values are today's rendering.+ names: [+ "--ui-shell-field",+ "--ui-shell-wash-1",+ "--ui-shell-wash-2",+ "--ui-shell-nav-bg",+ "--ui-shell-main-bg",+ "--ui-shell-line",+ "--ui-shell-gap",+ "--ui-shell-radius",+ "--ui-shell-shadow",+ ],+ },+ {+ id: "structure",+ title: "Structure — trees and fields",+ // What the `ui-tree` and `ui-field` hooks measure with: a tree row's base inset and its+ // indent per level (a host indents its rows by these two, so every theme's connector rules+ // land on the same columns), the colour of a connector or guide rule, and a field's label+ // column width (Console's tabular rows) and the gap between its label and its control.+ // Primer's values are today's file tree and form rows.+ names: [+ "--ui-tree-inset",+ "--ui-tree-indent",+ "--ui-tree-guide",+ "--ui-field-label-w",+ "--ui-field-gap",+ ],+ },+ {+ id: "controls",+ title: "Controls — the switch",+ // The switch's off track and the knob on it, and the knob on the on track (the accent). A+ // knob keeps 3:1 against its track in every theme, mode and preset — `knob-on` follows the+ // accent's label ink, which already flips to a dark ink on a light fill — so the knob never+ // vanishes on a near-white dark accent. `knob-line` is the knob's hairline edge: where the+ // knob itself does not reach 3:1 on the off track (Primer's white knob on gray-200, kept),+ // the edge does — a gray-500 hairline there (2026-09-30), a faint one elsewhere.+ names: [+ "--ui-switch-track",+ "--ui-switch-knob",+ "--ui-switch-knob-on",+ "--ui-switch-knob-line",+ ],+ },+ {+ id: "type-families",+ title: "Typography — families",+ names: [+ "--ui-font-sans",+ "--ui-font-ui",+ "--ui-font-mono",+ "--ui-font-display",+ "--ui-font-cjk",+ ],+ },+ {+ id: "type-scale",+ title: "Typography — scale and roles",+ names: [+ "--ui-text-body-size",+ "--ui-text-body-lh",+ "--ui-text-small-size",+ "--ui-text-small-lh",+ "--ui-text-caption-size",+ "--ui-text-caption-lh",+ "--ui-text-code-size",+ "--ui-text-code-lh",+ "--ui-text-prose-size",+ "--ui-text-prose-lh",+ "--ui-h1-size",+ "--ui-h1-lh",+ "--ui-h1-weight",+ "--ui-h1-tracking",+ "--ui-h1-transform",+ "--ui-h1-font",+ "--ui-h2-size",+ "--ui-h2-lh",+ "--ui-h2-weight",+ "--ui-h2-tracking",+ "--ui-h2-transform",+ "--ui-h2-font",+ "--ui-h3-size",+ "--ui-h3-lh",+ "--ui-h3-weight",+ "--ui-h3-tracking",+ "--ui-h3-transform",+ "--ui-h3-font",+ "--ui-h4-size",+ "--ui-h4-lh",+ "--ui-h4-weight",+ "--ui-h4-tracking",+ "--ui-h4-transform",+ "--ui-h4-font",+ "--ui-h5-size",+ "--ui-h5-lh",+ "--ui-h5-weight",+ "--ui-h5-tracking",+ "--ui-h5-transform",+ "--ui-h5-font",+ "--ui-h6-size",+ "--ui-h6-lh",+ "--ui-h6-weight",+ "--ui-h6-tracking",+ "--ui-h6-transform",+ "--ui-h6-font",+ "--ui-md-h1-size",+ "--ui-md-h2-size",+ "--ui-md-h3-size",+ "--ui-weight-body",+ "--ui-weight-medium",+ "--ui-weight-strong",+ "--ui-tracking-body",+ "--ui-tracking-mono",+ "--ui-tracking-label",+ ],+ },+ {+ id: "density",+ title: "Density",+ names: [+ "--ui-space-unit",+ "--ui-control-py-sm",+ "--ui-control-py-md",+ "--ui-control-py-lg",+ "--ui-control-px-sm",+ "--ui-control-px-md",+ "--ui-control-px-lg",+ "--ui-control-gap-sm",+ "--ui-control-gap-md",+ "--ui-row-py",+ "--ui-row-px",+ "--ui-menu-row-py",+ "--ui-menu-row-px",+ "--ui-card-p",+ "--ui-panel-p",+ "--ui-stack-0",+ "--ui-stack-1",+ "--ui-stack-2",+ "--ui-stack-3",+ "--ui-stack-4",+ ],+ },+ {+ id: "motion",+ title: "Motion",+ names: [+ "--ui-dur-fast",+ "--ui-dur-base",+ "--ui-dur-slow",+ "--ui-ease-out",+ "--ui-ease-in-out",+ "--ui-ease-spring",+ "--ui-ease-overlay-in",+ "--ui-ease-overlay-out",+ "--ui-live-timing",+ "--ui-dur-enter",+ "--ui-dur-exit",+ "--ui-ease-enter",+ "--ui-ease-exit",+ "--ui-enter-shift",+ "--ui-enter-scale",+ "--ui-enter-blur",+ "--ui-dur-reveal",+ "--ui-reveal-blur",+ "--ui-dur-layout",+ "--ui-ease-layout",+ ],+ },+ {+ id: "icons",+ title: "Icons",+ names: ["--ui-icon-stroke", "--ui-icon-cap", "--ui-icon-join"],+ },+ {+ id: "focus",+ title: "Focus, selection and scrollbar",+ names: [+ "--ui-focus-ring",+ "--ui-focus-ring-offset",+ "--ui-focus-ring-input",+ "--ui-selection-bg",+ "--ui-scrollbar-w",+ "--ui-scrollbar-thumb",+ "--ui-scrollbar-thumb-hover",+ "--ui-scrollbar-track",+ "--ui-scrollbar-visibility",+ ],+ },+] as const;++export type TokenGroup = (typeof TOKEN_GROUPS)[number];+export type TokenGroupId = TokenGroup["id"];+/** One contract name, e.g. `"--ui-surface"`. */+export type TokenName = TokenGroup["names"][number];++/** Every contract name, flattened in group order. The contract test diffs the theme files against this. */+export const TOKEN_NAMES: readonly TokenName[] = TOKEN_GROUPS.flatMap(+ (group): readonly TokenName[] => group.names,+);++/** `var(--ui-…)` for a contract name — for inline styles and SVG attributes that cannot take a class. */+export function tokenVar(name: TokenName): `var(${TokenName})` {+ return `var(${name})`;+}diff --git a/packages/ui/src/vite-plugin.ts b/packages/ui/src/vite-plugin.tsnew file mode 100644index 00000000..ddd29d2b--- /dev/null+++ b/packages/ui/src/vite-plugin.ts@@ -0,0 +1,49 @@+/**+ * `penguinUi()` — the Vite plugin that ships the bundled fonts' licences.+ *+ * On a build it emits the licence texts in `src/fonts/LICENSES/*.txt` (mirrored from the font+ * packages by `scripts/sync-font-licenses.mjs`, and MiSans's transcribed from its licensor) as+ * `fonts-licenses/<name>.txt`, so every dist that carries the fonts — the served app, the desktop+ * bundle, the gallery — carries their licences beside them. Resolving the package needs no plugin:+ * a consumer's `workspace:*` dependency is linked to this directory.+ *+ * A vite config imports it by relative path (`../ui/src/vite-plugin`), which the config bundle+ * inlines; it is not one of the package's `exports`. Structural types only, so the package needs+ * no `vite` dependency.+ */+import { readFileSync, readdirSync } from "node:fs";++/** The slice of Rollup's plugin context the licence emission uses. */+export interface PenguinUiEmitContext {+ emitFile(file: { type: "asset"; fileName: string; source: string }): string;+}++export interface PenguinUiPlugin {+ name: string;+ generateBundle: (this: PenguinUiEmitContext) => void;+}++/** Where the emitted licence texts land in a consumer's dist. */+export const FONT_LICENSES_DIR = "fonts-licenses";++/** The licence texts in `src/fonts/LICENSES/`, `{ fileName, source }` per font, sorted by file name. */+export function fontLicenseAssets(): { fileName: string; source: string }[] {+ const dir = new URL("./fonts/LICENSES/", import.meta.url);+ return readdirSync(dir)+ .filter((file) => file.endsWith(".txt"))+ .sort()+ .map((file) => ({+ fileName: `${FONT_LICENSES_DIR}/${file}`,+ source: readFileSync(new URL(file, dir), "utf8"),+ }));+}++export function penguinUi(): PenguinUiPlugin {+ return {+ name: "penguin:ui",+ // Build only: Vite never calls generateBundle from the dev server.+ generateBundle() {+ for (const asset of fontLicenseAssets()) this.emitFile({ type: "asset", ...asset });+ },+ };+}diff --git a/packages/ui/test/boot-script.test.ts b/packages/ui/test/boot-script.test.tsnew file mode 100644index 00000000..70894fde--- /dev/null+++ b/packages/ui/test/boot-script.test.ts@@ -0,0 +1,329 @@+/**+ * The pre-paint script (src/boot.ts).+ *+ * It exists twice: as `BOOT_SCRIPT`, generated from the same constants the app's theme provider+ * reads, and pasted inline into `packages/web/index.html`, where it runs before the bundle loads.+ * Two things break silently and only on a reload: the pasted copy falling behind the constants (a+ * new theme id that paints the default theme for one frame, then snaps), and the script disagreeing+ * with `applyThemeAttributes` / `readTextSize` about a stored value (the first frame and the second+ * frame differ, or the text-size migration writes something the provider would not). Both are held+ * here — the copy byte for byte, the behaviour by running the script against a fake document and a+ * fake store for every combination of stored preferences and comparing the root AND the store+ * afterwards with what the provider's path produces.+ */+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { Script, createContext, runInNewContext } from "node:vm";+import { describe, expect, it } from "vitest";+import {+ BOOT_SCRIPT,+ DEFAULT_TEXT_SIZE,+ FONT_CJK_OPTIONS,+ FONT_LATIN_OPTIONS,+ TEXT_SIZES,+ TEXT_SIZE_PX,+ THEME_STORAGE_KEYS,+ applyThemeAttributes,+ isFontCjk,+ isFontLatin,+ readTextSize,+} from "../src/boot";+import type { AccentChoice } from "../src/boot";+import {+ ACCENT_PRESET_IDS,+ DEFAULT_THEME_ID,+ THEME_ACCENT_PRESETS,+ THEME_IDS,+} from "../src/tokens";+import type { ThemeId } from "../src/tokens";+import { WEB_DIR } from "./helpers/paths";++/** The attributes the script and the provider write, captured from a stand-in `<html>`. */+interface FakeRoot {+ classList: { add(name: string): void; toggle(name: string, on: boolean): void };+ dataset: Record<string, string | undefined>;+ style: { fontSize?: string };+ classes: Set<string>;+}++function fakeRoot(): FakeRoot {+ const classes = new Set<string>();+ return {+ classes,+ classList: {+ add: (name) => void classes.add(name),+ toggle: (name, on) => void (on ? classes.add(name) : classes.delete(name)),+ },+ dataset: {},+ style: {},+ };+}++/** A `localStorage` stand-in over a Map, so what a run wrote or removed can be read back. */+function fakeStorage(stored: Record<string, string | null>, throwing = false) {+ const map = new Map(+ Object.entries(stored).filter((entry): entry is [string, string] => entry[1] !== null),+ );+ return {+ map,+ getItem(key: string) {+ if (throwing) throw new Error("storage is disabled");+ return map.get(key) ?? null;+ },+ setItem(key: string, value: string) {+ if (throwing) throw new Error("storage is disabled");+ map.set(key, value);+ },+ removeItem(key: string) {+ if (throwing) throw new Error("storage is disabled");+ map.delete(key);+ },+ };+}++const snapshot = (root: FakeRoot, storage: { map: Map<string, string> }) => ({+ dark: root.classes.has("dark"),+ theme: root.dataset.theme,+ accent: root.dataset.accent,+ fontLatin: root.dataset.fontLatin,+ fontCjk: root.dataset.fontCjk,+ fontSize: root.style.fontSize,+ stored: Object.fromEntries([...storage.map].sort()),+});++/**+ * One compiled script in one context, re-pointed at a fresh root and store per run: the sweep+ * below runs it tens of thousands of times, and a new context per run would cost seconds. (The+ * script leaks no global — a case below holds that — so runs cannot see each other.)+ */+const compiled = new Script(BOOT_SCRIPT);+const context = createContext({ document: {}, localStorage: {}, matchMedia: () => ({}) });++/** Runs the script against the given storage and system preference. */+function runBoot(stored: Record<string, string | null>, systemDark: boolean, throwing = false) {+ const root = fakeRoot();+ const localStorage = fakeStorage(stored, throwing);+ context.document = { documentElement: root };+ context.localStorage = localStorage;+ context.matchMedia = (query: string) => ({+ matches: query === "(prefers-color-scheme: dark)" && systemDark,+ });+ compiled.runInContext(context);+ return snapshot(root, localStorage);+}++/**+ * What the provider resolves the same stored values to, written from the stored-preference rules+ * rather than from the script: an unknown mode means "system", an unknown theme id the default+ * theme, an unknown accent `neutral`, an unknown face the theme's own, and the text size is what+ * `readTextSize` says (the legacy scale mapped and migrated on the way). A preset any theme lists+ * is written to the root whichever theme is active — the theme files scope their presets to+ * their own root, so an unlisted one paints nothing and comes back with its theme.+ */+function viaProvider(stored: Record<string, string | null>, systemDark: boolean) {+ const mode = stored[THEME_STORAGE_KEYS.mode];+ const themeId = stored[THEME_STORAGE_KEYS.themeId];+ const accent = stored[THEME_STORAGE_KEYS.accent];+ const latin = stored[THEME_STORAGE_KEYS.fontLatin];+ const cjk = stored[THEME_STORAGE_KEYS.fontCjk];+ const storage = fakeStorage(stored);+ const root = fakeRoot();+ applyThemeAttributes(root as unknown as HTMLElement, {+ dark: mode === "dark" || (mode !== "light" && systemDark),+ themeId: (THEME_IDS as readonly (string | null | undefined)[]).includes(themeId)+ ? (themeId as ThemeId)+ : DEFAULT_THEME_ID,+ accent: (ACCENT_PRESET_IDS as readonly (string | null | undefined)[]).includes(accent)+ ? (accent as AccentChoice)+ : "neutral",+ textSize: readTextSize(storage),+ fontLatin: isFontLatin(latin) ? latin : "theme",+ fontCjk: isFontCjk(cjk) ? cjk : "theme",+ });+ return snapshot(root, storage);+}++describe("BOOT_SCRIPT", () => {+ it("paints what the provider will, and leaves the store as the provider does, for every combination", () => {+ const modes = [null, "light", "dark", "sepia"];+ const themes = [null, ...THEME_IDS, "retro"];+ // One preset of each theme's list, so a Frost preset stored under Primer is exercised too.+ const accents = [null, "neutral", ...THEME_IDS.map((id) => THEME_ACCENT_PRESETS[id][0]!)];+ // Stored sizes and the retired scale beside them: absent, valid, junk, and the names of+ // Object.prototype members, which a map lookup would find and an array lookup does not.+ const sizes = [null, "xs", "m", "huge", "toString"];+ const legacy = [null, "sm", "md", "lg", "xl", "hasOwnProperty"];+ const latins = [null, "theme", "misans", "comic-sans"];+ const cjks = [null, "noto-sans-sc", "valueOf"];+ const mismatches: string[] = [];+ let cases = 0;+ for (const mode of modes)+ for (const themeId of themes)+ for (const accent of accents)+ for (const size of sizes)+ for (const scale of legacy)+ for (const latin of latins)+ for (const cjk of cjks)+ for (const systemDark of [false, true]) {+ const stored = {+ [THEME_STORAGE_KEYS.mode]: mode,+ [THEME_STORAGE_KEYS.themeId]: themeId,+ [THEME_STORAGE_KEYS.accent]: accent,+ [THEME_STORAGE_KEYS.textSize]: size,+ [THEME_STORAGE_KEYS.fontScale]: scale,+ [THEME_STORAGE_KEYS.fontLatin]: latin,+ [THEME_STORAGE_KEYS.fontCjk]: cjk,+ };+ cases++;+ const boot = runBoot(stored, systemDark);+ const provider = viaProvider(stored, systemDark);+ if (JSON.stringify(boot) !== JSON.stringify(provider)) {+ mismatches.push(+ `${JSON.stringify(stored)} system=${systemDark ? "dark" : "light"}: ` ++ `boot ${JSON.stringify(boot)} vs provider ${JSON.stringify(provider)}`,+ );+ }+ }+ expect(cases).toBeGreaterThan(10_000);+ expect(mismatches.slice(0, 5)).toEqual([]);+ });++ it("migrates the retired three-step scale by pixels, once, and drops its key", () => {+ // sm was 16px, md 18px, lg 20px: the size with the same pixels, written under the new key so+ // the next load is a plain read; a step the scale never had is dropped without a write.+ for (const [scale, size] of [+ ["sm", "m"],+ ["md", "l"],+ ["lg", "xl"],+ ] as const) {+ const painted = runBoot({ [THEME_STORAGE_KEYS.fontScale]: scale }, false);+ expect(painted.fontSize).toBe(TEXT_SIZE_PX[size]);+ expect(painted.stored).toEqual({ [THEME_STORAGE_KEYS.textSize]: size });+ }+ expect(runBoot({ [THEME_STORAGE_KEYS.fontScale]: "huge" }, false)).toMatchObject({+ fontSize: TEXT_SIZE_PX[DEFAULT_TEXT_SIZE],+ stored: {},+ });+ // A stored text size wins over a lingering old key, which is then left alone: nothing reads+ // it any more.+ const both = runBoot(+ { [THEME_STORAGE_KEYS.textSize]: "xs", [THEME_STORAGE_KEYS.fontScale]: "lg" },+ false,+ );+ expect(both.fontSize).toBe("14px");+ expect(both.stored).toEqual({+ [THEME_STORAGE_KEYS.textSize]: "xs",+ [THEME_STORAGE_KEYS.fontScale]: "lg",+ });+ });++ it("still paints the migrated size when the store reads but refuses writes", () => {+ const root = fakeRoot();+ const storage = fakeStorage({ [THEME_STORAGE_KEYS.fontScale]: "md" });+ storage.setItem = () => {+ throw new Error("quota");+ };+ context.document = { documentElement: root };+ context.localStorage = storage;+ context.matchMedia = () => ({ matches: false });+ compiled.runInContext(context);+ expect(root.style.fontSize).toBe("18px");+ });++ it("knows every preset every theme lists, and writes one under any theme", () => {+ // The script paints the first frame; a preset it did not know would snap in when the provider+ // mounts. And a preset stays on the root under a theme that does not list it: the theme+ // files, not the script, decide what it paints.+ for (const themeId of THEME_IDS) {+ for (const accent of THEME_ACCENT_PRESETS[themeId]) {+ for (const under of THEME_IDS) {+ const painted = runBoot(+ { [THEME_STORAGE_KEYS.themeId]: under, [THEME_STORAGE_KEYS.accent]: accent },+ false,+ );+ expect(painted.accent, `${accent} (${themeId}) under ${under}`).toBe(accent);+ }+ }+ }+ expect(ACCENT_PRESET_IDS.length).toBe(new Set(ACCENT_PRESET_IDS).size);+ });++ it("knows every face the pairing offers, and writes no attribute for the theme's own", () => {+ for (const option of FONT_LATIN_OPTIONS) {+ const painted = runBoot({ [THEME_STORAGE_KEYS.fontLatin]: option.id }, false);+ expect(painted.fontLatin).toBe(option.id === "theme" ? undefined : option.id);+ }+ for (const option of FONT_CJK_OPTIONS) {+ const painted = runBoot({ [THEME_STORAGE_KEYS.fontCjk]: option.id }, false);+ expect(painted.fontCjk).toBe(option.id === "theme" ? undefined : option.id);+ }+ // The lists open with the theme's own face and name only faces the app bundles.+ expect(FONT_LATIN_OPTIONS[0].id).toBe("theme");+ expect(FONT_CJK_OPTIONS[0].id).toBe("theme");+ for (const options of [FONT_LATIN_OPTIONS, FONT_CJK_OPTIONS]) {+ const ids = options.map((option) => option.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const option of options) expect(option.label).not.toBe("");+ }+ });++ it("renders the page untouched when storage throws, instead of throwing itself", () => {+ expect(() => runBoot({}, true, true)).not.toThrow();+ expect(runBoot({}, true, true)).toEqual({+ dark: false,+ theme: undefined,+ accent: undefined,+ fontLatin: undefined,+ fontCjk: undefined,+ fontSize: undefined,+ stored: {},+ });+ });++ it("leaves no global behind", () => {+ const context: Record<string, unknown> = {+ document: { documentElement: fakeRoot() },+ localStorage: fakeStorage({}),+ matchMedia: () => ({ matches: false }),+ };+ runInNewContext(BOOT_SCRIPT, context);+ expect(Object.keys(context).sort()).toEqual(["document", "localStorage", "matchMedia"]);+ });+});++describe("readTextSize", () => {+ it("reads a stored size, maps the retired scale once, and defaults otherwise", () => {+ for (const size of TEXT_SIZES) {+ expect(readTextSize(fakeStorage({ [THEME_STORAGE_KEYS.textSize]: size }))).toBe(size);+ }+ const migrated = fakeStorage({ [THEME_STORAGE_KEYS.fontScale]: "sm" });+ expect(readTextSize(migrated)).toBe("m");+ expect(migrated.map.get(THEME_STORAGE_KEYS.textSize)).toBe("m");+ expect(migrated.map.has(THEME_STORAGE_KEYS.fontScale)).toBe(false);+ expect(readTextSize(migrated)).toBe("m");+ expect(readTextSize(fakeStorage({}))).toBe(DEFAULT_TEXT_SIZE);+ expect(readTextSize(fakeStorage({ [THEME_STORAGE_KEYS.textSize]: "constructor" }))).toBe(+ DEFAULT_TEXT_SIZE,+ );+ });+});++describe("the inline copy in packages/web/index.html", () => {+ const indexHtml = join(WEB_DIR, "index.html");+ const html = readFileSync(indexHtml, "utf8");+ /** Inline classic scripts: no `src`, no `type="module"`. */+ const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)([^>]*)>([\s\S]*?)<\/script>/g)]+ .filter((m) => !/type\s*=\s*["']module["']/.test(m[1]!))+ .map((m) => m[2]!.trim());++ it("reads the web app's index.html", () => {+ expect(existsSync(indexHtml)).toBe(true);+ });++ it("carries BOOT_SCRIPT verbatim, once", () => {+ const copies = inline.filter((script) => script.includes(THEME_STORAGE_KEYS.mode));+ expect(copies, "Regenerate the inline script from BOOT_SCRIPT (src/boot.ts).").toEqual([+ BOOT_SCRIPT,+ ]);+ });+});diff --git a/packages/ui/test/contrast.test.ts b/packages/ui/test/contrast.test.tsnew file mode 100644index 00000000..f9baa9e4--- /dev/null+++ b/packages/ui/test/contrast.test.ts@@ -0,0 +1,433 @@+/**+ * WCAG 2 contrast of the theme tokens, computed from the theme files.+ *+ * The web app used to record its ratios in comments beside `tone.ts`, measured against the two+ * surfaces it had. Three themes × two modes each bring their own surfaces, and a comment cannot+ * follow a value that changes in a file three directories away — so the pairs a reader actually+ * sees are resolved here from the CSS, composited onto what sits behind them, and measured.+ *+ * The pairs (A-architecture §7.2, plus the text pairs every surface implies):+ * - text: `fg` on every surface and the overlay, `fg-muted` on the page surfaces, the link on the+ * page — 4.5:1;+ * - a tone's ink (`tone-*-fg`) as a glyph or status word on the four page surfaces — 3:1, except+ * `neutral`, the one tone allowed to recede where its meaning is already in text;+ * - a tone's ink on its own tint (`tone-*-bg`, a badge) and a solid badge's label on its fill — 4.5:1;+ * - the accent's label on the accent at rest and on hover (the primary button) — 4.5:1 — and the+ * accent as a mark on the page and the card (a selected row's `>`, a link-coloured glyph) —+ * 3:1; both for the theme's own accent and, in the second suite, for every preset the theme+ * lists, overlaid on the theme's values for that mode (a dark lift included);+ * - text and muted text on the shell's two columns, composited onto the field behind the window+ * (Frost's navigation column is transparent on the field) — 4.5:1. The field's two washes are+ * gradients this suite cannot read; a theme keeps them faint enough that the muted ink still+ * clears 4.5:1 where they are strongest (Frost's values were measured by hand at 4.56:1);+ * - the calm dark (2026-09-29, raised the same day after the owner found the first pass too+ * dim): in dark, body text at 11:1 or better on the three page surfaces, the muted ink at+ * 6:1 and the subtle ink at 4.5:1; light keeps 7:1 and 4.5:1; the emphasis ink at 4.5:1 in+ * both;+ * - the switch: its knob on the off track — 3:1, the knob itself or its hairline edge+ * (`knob-line` over the track) — and, for the theme's accent and every preset, the `knob-on`+ * on the accent — 3:1, so the knob never vanishes on a near-white dark accent.+ *+ * `fg-subtle` has no floor in light — placeholder and disabled ink, which WCAG exempts, and+ * Primer's is the app's — and holds 4.5:1 in dark, where timestamps and meta text read from it.+ *+ * A pair a theme cannot meet yet goes in EXCEPTIONS with the reason and the wave that fixes it; an+ * exception that has started passing fails the suite until it is removed.+ */+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import {+ DEFAULT_THEME_ID,+ THEME_ACCENT_PRESETS,+ THEME_IDS,+ THEME_MODES,+ TONES,+} from "../src/tokens";+import type { ThemeId, ThemeModeName, TokenName } from "../src/tokens";+import {+ BLACK,+ WHITE,+ analyzeThemeFile,+ composite,+ contrastRatio,+ formatColor,+ parseColor,+ resolveThemeValue,+} from "../src/testing";+import type { AccentPresetRules, Rgba, ThemeFileAnalysis } from "../src/testing";+import { SRC_DIR } from "./helpers/paths";++interface Pair {+ readonly fg: TokenName;+ readonly bg: TokenName;+ readonly min: number;+}++interface ContrastException {+ readonly theme: ThemeId;+ readonly mode: ThemeModeName;+ readonly fg: TokenName;+ readonly bg: TokenName;+ /** Why the pair is below its floor today. */+ readonly reason: string;+ /** The wave or PR that lifts it. */+ readonly until: string;+}++/**+ * Known shortfalls. Empty is the goal, and it is empty: the last entries — Primer's white knob on+ * its gray-200 track, and its light chart palette at the 500 steps — were lifted on 2026-09-30+ * (a gray-500 hairline on the knob, which the switch check measures as its edge; the 600 steps+ * for the light series). An entry names its fix and the wave that lifts it.+ */+const EXCEPTIONS: readonly ContrastException[] = [];++const PAGE_SURFACES = ["--ui-canvas", "--ui-surface", "--ui-surface-muted", "--ui-inset"] as const;++/**+ * What an accent must clear, the theme's own or a preset's: its label on it, and it as a mark,+ * and the switch knob on it (the on track).+ */+const ACCENT_PAIRS: readonly Pair[] = [+ { fg: "--ui-accent-fg", bg: "--ui-accent", min: 4.5 },+ { fg: "--ui-accent-fg", bg: "--ui-accent-hover", min: 4.5 },+ { fg: "--ui-accent", bg: "--ui-canvas", min: 3 },+ { fg: "--ui-accent", bg: "--ui-surface", min: 3 },+ { fg: "--ui-switch-knob-on", bg: "--ui-accent", min: 3 },+];++/**+ * The ink floors on the three page surfaces, per mode. Light keeps the WCAG floors and exempts+ * the subtle ink (placeholders and disabled text; Primer's is the app's). Dark is held higher+ * on purpose: a first calm dark at 7 / 4.5 read too dim to the owner (2026-09-29), so body text+ * holds 11:1, the muted ink 6:1 and the subtle ink — timestamps, placeholders, meta — 4.5:1.+ */+const INK_FLOORS: Readonly<Record<ThemeModeName, ReadonlyArray<readonly [TokenName, number]>>> = {+ light: [+ ["--ui-fg", 7],+ ["--ui-fg-muted", 4.5],+ ],+ dark: [+ ["--ui-fg", 11],+ ["--ui-fg-muted", 6],+ ["--ui-fg-subtle", 4.5],+ ],+};+const INK_SURFACES = ["--ui-canvas", "--ui-surface", "--ui-surface-muted"] as const;++const pairsFor = (mode: ThemeModeName): readonly Pair[] => [+ ...[...PAGE_SURFACES, "--ui-overlay" as const].map((bg) => ({+ fg: "--ui-fg" as const,+ bg,+ min: 4.5,+ })),+ ...INK_FLOORS[mode].flatMap(([fg, min]) => INK_SURFACES.map((bg) => ({ fg, bg, min }))),+ ...(["--ui-canvas", "--ui-surface"] as const).map((bg) => ({+ fg: "--ui-fg-emphasis" as const,+ bg,+ min: 4.5,+ })),+ // The knob on the off track is measured by `knobReads` below: the knob, or its hairline edge.+ // A frosted layer's ink on the glass over the worst backdrop it can float over (black in+ // light, white in dark): a menu stays legible whatever scrolls behind it.+ { fg: "--ui-fg", bg: "--ui-glass-bg", min: 4.5 },+ ...(["--ui-canvas", "--ui-surface"] as const).map((bg) => ({+ fg: "--ui-fg-link" as const,+ bg,+ min: 4.5 as const,+ })),+ ...TONES.filter((tone) => tone !== "neutral").flatMap((tone) =>+ PAGE_SURFACES.map((bg) => ({ fg: `--ui-tone-${tone}-fg` as TokenName, bg, min: 3 as const })),+ ),+ ...TONES.flatMap((tone) => [+ {+ fg: `--ui-tone-${tone}-fg` as TokenName,+ bg: `--ui-tone-${tone}-bg` as TokenName,+ min: 4.5 as const,+ },+ {+ fg: `--ui-tone-${tone}-emphasis-fg` as TokenName,+ bg: `--ui-tone-${tone}-emphasis` as TokenName,+ min: 4.5 as const,+ },+ ]),+ ...ACCENT_PAIRS,+ ...(["--ui-shell-nav-bg", "--ui-shell-main-bg"] as const).flatMap((bg) => [+ { fg: "--ui-fg" as const, bg, min: 4.5 as const },+ { fg: "--ui-fg-muted" as const, bg, min: 4.5 as const },+ ]),+];++/**+ * What a background token is painted over: the page over the UA canvas, surfaces over the page,+ * fills (an accent, a tint, the switch's track) over a surface, the shell's field over the UA+ * canvas and its columns over the field.+ */+function layerBelow(bg: TokenName): TokenName | "base" | "worst" {+ if (bg === "--ui-canvas" || bg === "--ui-shell-field") return "base";+ if (bg === "--ui-glass-bg") return "worst";+ if ((PAGE_SURFACES as readonly string[]).includes(bg) || bg === "--ui-overlay")+ return "--ui-canvas";+ if (bg === "--ui-shell-nav-bg" || bg === "--ui-shell-main-bg") return "--ui-shell-field";+ return "--ui-surface";+}++type Resolve = (name: TokenName) => Rgba | string;++/** The opaque colour a background token shows, composited down its layers; a string is an error. */+function opaqueBackground(bg: TokenName, mode: ThemeModeName, resolve: Resolve): Rgba | string {+ const color = resolve(bg);+ if (typeof color === "string") return color;+ const below = layerBelow(bg);+ // The page sits on the UA canvas; a frosted layer is measured over the worst content it can+ // float over — the opposite extreme.+ const under =+ below === "base"+ ? mode === "light"+ ? WHITE+ : BLACK+ : below === "worst"+ ? mode === "light"+ ? BLACK+ : WHITE+ : opaqueBackground(below, mode, resolve);+ return typeof under === "string" ? under : composite(color, under);+}++function measure(+ pair: Pair,+ mode: ThemeModeName,+ resolve: Resolve,+): { ratio: number; detail: string } | string {+ const fg = resolve(pair.fg);+ if (typeof fg === "string") return fg;+ const bg = opaqueBackground(pair.bg, mode, resolve);+ if (typeof bg === "string") return bg;+ const ratio = contrastRatio(fg, bg);+ return { ratio, detail: `${formatColor(composite(fg, bg))} on ${formatColor(bg)}` };+}++function themeAnalysis(id: ThemeId): ThemeFileAnalysis | null {+ const path = join(SRC_DIR, "themes", `${id}.css`);+ if (!existsSync(path)) return null;+ const analysis = analyzeThemeFile(readFileSync(path, "utf8"), id);+ return analysis.isStub ? null : analysis;+}++const defaultTheme = themeAnalysis(DEFAULT_THEME_ID) ?? analyzeThemeFile("", DEFAULT_THEME_ID);++/** The series colours and the reference line: the marks a chart draws on the page. */+const SERIES_TOKENS = [+ "--ui-chart-1",+ "--ui-chart-2",+ "--ui-chart-3",+ "--ui-chart-4",+ "--ui-chart-5",+ "--ui-chart-6",+ "--ui-chart-7",+ "--ui-chart-8",+ "--ui-chart-ref",+] as const;++/**+ * Whether a series reads on the canvas: a bar, a line or a point must clear WCAG's 3:1 for a+ * graphical object. A theme may draw its bars pale (`--ui-chart-bar-opacity` under 1) so long+ * as the full series colour still clears the floor — the bar's outline (`--ui-chart-bar-stroke`+ * of at least 1px, in the series colour or a colour of the theme's) and every line and point+ * carry it at full strength, so a mark's edge reads even where its fill is soft. So a series+ * passes when its colour clears 3:1, or when its outline is at least 1px wide and does. The+ * result names the ratios so a failure says which of the two fell short.+ */+function seriesReads(+ token: (typeof SERIES_TOKENS)[number],+ mode: ThemeModeName,+ theme: ThemeFileAnalysis,+): { ok: boolean; detail: string } {+ const resolve: Resolve = (name) => {+ const value = resolveThemeValue(name, mode, theme, defaultTheme);+ if (value === null) return `${name} does not resolve to a value`;+ return parseColor(value) ?? `${name} = \`${value}\` is not a colour this suite can read`;+ };+ const series = resolve(token);+ const canvas = opaqueBackground("--ui-canvas", mode, resolve);+ if (typeof series === "string") return { ok: false, detail: series };+ if (typeof canvas === "string") return { ok: false, detail: canvas };+ const direct = contrastRatio(series, canvas);+ const strokeWidth = Number.parseFloat(+ resolveThemeValue("--ui-chart-bar-stroke", mode, theme, defaultTheme) ?? "0",+ );+ const strokeSpec = resolveThemeValue("--ui-chart-bar-stroke-color", mode, theme, defaultTheme);+ const outlineColor =+ strokeSpec === null || strokeSpec.trim() === "series" ? series : parseColor(strokeSpec);+ const outline =+ strokeWidth >= 1 && outlineColor !== null ? contrastRatio(outlineColor, canvas) : null;+ const colors = `${formatColor(series)} on ${formatColor(canvas)}`;+ const edge = outline === null ? "no outline" : `outline ${outline.toFixed(2)}:1`;+ return {+ ok: direct >= 3 || (outline !== null && outline >= 3),+ detail: `${token}: ${direct.toFixed(2)}:1 on the canvas (${colors}), ${edge}`,+ };+}++describe("theme contrast", () => {+ for (const id of THEME_IDS) {+ const theme = themeAnalysis(id);+ if (theme === null) {+ it.skip(`src/themes/${id}.css — PENDING, contrast not checked: no tokens declared yet`, () => {});+ continue;+ }+ for (const mode of THEME_MODES) {+ const resolve: Resolve = (name) => {+ const value = resolveThemeValue(name, mode, theme, defaultTheme);+ if (value === null) return `${name} does not resolve to a value`;+ return parseColor(value) ?? `${name} = \`${value}\` is not a colour this suite can read`;+ };+ const excepted = (pair: Pair) =>+ EXCEPTIONS.find(+ (e) => e.theme === id && e.mode === mode && e.fg === pair.fg && e.bg === pair.bg,+ );++ it(`${id} ${mode}: every listed pair clears its floor`, () => {+ const failures: string[] = [];+ for (const pair of pairsFor(mode)) {+ const result = measure(pair, mode, resolve);+ if (typeof result === "string") failures.push(`${pair.fg} on ${pair.bg}: ${result}`);+ else if (result.ratio < pair.min && excepted(pair) === undefined) {+ failures.push(+ `${pair.fg} on ${pair.bg}: ${result.ratio.toFixed(2)}:1 < ${pair.min}:1 (${result.detail})`,+ );+ }+ }+ // Joined into the message: vitest elides long arrays in a diff, and the list is the finding.+ expect(failures, `\n${failures.join("\n")}\n`).toEqual([]);+ });++ it(`${id} ${mode}: carries no exception that has started passing`, () => {+ const stale = EXCEPTIONS.filter((e) => e.theme === id && e.mode === mode).filter((e) => {+ const pair = pairsFor(mode).find((p) => p.fg === e.fg && p.bg === e.bg);+ if (pair === undefined) {+ // A series exception is stale once the series reads, itself or by its outline.+ const series = SERIES_TOKENS.find((token) => token === e.fg);+ return series === undefined || e.bg !== "--ui-canvas"+ ? true+ : seriesReads(series, mode, theme).ok;+ }+ const result = measure(pair, mode, resolve);+ return typeof result !== "string" && result.ratio >= pair.min;+ });+ const names = stale.map((e) => `${e.fg} on ${e.bg} (${e.until})`);+ expect(names, `remove from EXCEPTIONS:\n${names.join("\n")}\n`).toEqual([]);+ });+ }+ }+});++/**+ * Whether the switch's knob reads on its off track: the knob itself at 3:1, or — where a theme+ * keeps a knob that does not (Primer's white knob on gray-200, today's look) — its hairline edge,+ * `--ui-switch-knob-line` composited over the track, at 3:1. A transparent edge is no edge.+ */+function knobReads(mode: ThemeModeName, theme: ThemeFileAnalysis): { ok: boolean; detail: string } {+ const resolve: Resolve = (name) => {+ const value = resolveThemeValue(name, mode, theme, defaultTheme);+ if (value === null) return `${name} does not resolve to a value`;+ return parseColor(value) ?? `${name} = \`${value}\` is not a colour this suite can read`;+ };+ const track = opaqueBackground("--ui-switch-track", mode, resolve);+ const knob = resolve("--ui-switch-knob");+ const line = resolve("--ui-switch-knob-line");+ if (typeof track === "string") return { ok: false, detail: track };+ if (typeof knob === "string") return { ok: false, detail: knob };+ if (typeof line === "string") return { ok: false, detail: line };+ const direct = contrastRatio(composite(knob, track), track);+ const edge = line.a === 0 ? null : contrastRatio(composite(line, track), track);+ const colors = `${formatColor(composite(knob, track))} on ${formatColor(track)}`;+ const edgeNote = edge === null ? "no edge" : `edge ${edge.toFixed(2)}:1`;+ return {+ ok: direct >= 3 || (edge !== null && edge >= 3),+ detail: `knob ${direct.toFixed(2)}:1 on the off track (${colors}), ${edgeNote}`,+ };+}++describe("the switch's knob on its off track", () => {+ for (const id of THEME_IDS) {+ const theme = themeAnalysis(id);+ if (theme === null) {+ it.skip(`src/themes/${id}.css — PENDING, switch not checked: no tokens declared yet`, () => {});+ continue;+ }+ for (const mode of THEME_MODES) {+ it(`${id} ${mode}: the knob reads at 3:1, itself or by its edge`, () => {+ const result = knobReads(mode, theme);+ expect(result.ok, result.detail).toBe(true);+ });+ }+ }+});++describe("chart series marks", () => {+ for (const id of THEME_IDS) {+ const theme = themeAnalysis(id);+ if (theme === null) {+ it.skip(`src/themes/${id}.css — PENDING, series not checked: no tokens declared yet`, () => {});+ continue;+ }+ for (const mode of THEME_MODES) {+ it(`${id} ${mode}: every series reads on the canvas, itself or by its bar's outline`, () => {+ const failures = SERIES_TOKENS.flatMap((token) => {+ const result = seriesReads(token, mode, theme);+ const excepted = EXCEPTIONS.some(+ (e) => e.theme === id && e.mode === mode && e.fg === token && e.bg === "--ui-canvas",+ );+ return result.ok || excepted ? [] : [result.detail];+ });+ expect(failures, `\n${failures.join("\n")}\n`).toEqual([]);+ });+ }+ }+});++describe("accent presets, per theme", () => {+ // A preset replaces the six accent tokens under its theme, in both modes (a dark rule lifts it+ // where the theme says so), and everything else stays the theme's: so each preset is measured+ // on its own theme's surfaces for that mode, exactly as the theme's own accent is above.+ for (const id of THEME_IDS) {+ const theme = themeAnalysis(id);+ if (theme === null) {+ it.skip(`src/themes/${id}.css — PENDING, presets not checked: no tokens declared yet`, () => {});+ continue;+ }++ it(`${id}: declares a rule for every preset tokens.ts lists for it, and no other`, () => {+ expect([...theme.accents.keys()]).toEqual([...THEME_ACCENT_PRESETS[id]]);+ });++ for (const accent of THEME_ACCENT_PRESETS[id]) {+ for (const mode of THEME_MODES) {+ it(`${id} ${mode} · ${accent}: its label clears 4.5:1 on it, and it clears 3:1 as a mark`, () => {+ const preset: AccentPresetRules | null = theme.accents.get(accent) ?? null;+ expect(preset, `${accent} has no rule`).not.toBeNull();+ const resolve: Resolve = (name) => {+ const value = resolveThemeValue(name, mode, theme, defaultTheme, preset);+ if (value === null) return `${name} does not resolve to a value`;+ return (+ parseColor(value) ?? `${name} = \`${value}\` is not a colour this suite can read`+ );+ };+ const failures: string[] = [];+ for (const pair of ACCENT_PAIRS) {+ const result = measure(pair, mode, resolve);+ if (typeof result === "string") failures.push(`${pair.fg} on ${pair.bg}: ${result}`);+ else if (result.ratio < pair.min) {+ failures.push(+ `${pair.fg} on ${pair.bg}: ${result.ratio.toFixed(2)}:1 < ${pair.min}:1 (${result.detail})`,+ );+ }+ }+ expect(failures, `\n${failures.join("\n")}\n`).toEqual([]);+ });+ }+ }+ }+});diff --git a/packages/ui/test/deslop.test.ts b/packages/ui/test/deslop.test.tsnew file mode 100644index 00000000..31ebea7b--- /dev/null+++ b/packages/ui/test/deslop.test.ts@@ -0,0 +1,616 @@+/**+ * The de-slop rules (K-redesign §3) over `packages/ui/src`.+ *+ * The W0 drafts copied the tells killaislop.com catalogues — an ambient gradient behind glass,+ * radius that eases on hover, a terminal costume, one-hue status boxes, 10–11 px uppercase+ * micro-titles, a tinted stop button — and none of them fails a type check or a contract test.+ * Each rule §3 marks as a guard is a check in `src/testing/deslop.ts`; this suite runs every one+ * over the package's markup (`.ts`, `.tsx`) and stylesheets, and the web app's suite runs the same+ * checks over `packages/web/src` with its own allowlist.+ *+ * The package holds itself to the rules outright. Where a rule names a home — the one spinner+ * file, the motion files, the pulse of a dot or a skeleton — it is in {@link POLICY}; an occurrence+ * a later wave removes would go in {@link ALLOWLIST} with that wave, and the list starts empty.+ *+ * A rule with nothing to read on this branch is a named skip, never a pass: the markup rules wait+ * for the first `.tsx` (the screens, #763; the modules, #764; the components, W1), and the+ * component rules (15, 16, 22) name the components they read and skip while none exists.+ * The rules §3 leaves to review — two badges per row, spacing steps per kind of child, nesting+ * across components, copy voice — are not here; the frontend skill carries them.+ */+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { THEME_IDS, THEME_MODES } from "../src/tokens";+import {+ DESLOP_CHECKS,+ DESLOP_RULE_NUMBERS,+ DESLOP_RULES,+ LABEL_COMPONENTS,+ PAGE_HEADER_COMPONENTS,+ TABULAR_COMPONENTS,+ allowlistProblems,+ analyzeFile,+ analyzeThemeFile,+ deslopHits,+ isClassShaped,+ matchesPolicyPath,+ modeDeclarations,+ parseClassToken,+ scanSourceRoots,+ unscannedRoots,+} from "../src/testing";+import type {+ DeslopAllowlist,+ DeslopPolicy,+ DeslopRule,+ SourceFile,+ ThemeFileAnalysis,+} from "../src/testing";+import { REPO_ROOT, SRC_DIR } from "./helpers/paths";++/** The homes §3 names. Bare file names match wherever the file lands. */+const POLICY: DeslopPolicy = {+ // Rule 1: the chevron rotates; the sheet, the launcher fan and the drawer move.+ transformMotion: ["chevron.tsx", "sheet.tsx", "launcher.tsx", "drawer.tsx"],+ // Rule 1: the `data-layout-motion` rule in the theme foundation transitions a width or a grid+ // row on the theme's layout tokens; a component only sets the attribute.+ layoutMotion: ["theme.css"],+ // Rule 3: keyframe-driven entrances longer than 200 ms. None in the package yet: the presence,+ // reveal and layout rules in theme.css read their own tokens (`--ui-dur-enter`, …), which the+ // rule does not judge — it holds STATE transitions (hover, press, selection) to 120–200 ms.+ entranceMotion: [],+ // Rule 6: the dot's live pulse, the skeleton's arrival pulse and the streaming caret.+ pulseHomes: ["dot.tsx", "skeleton.tsx", "streaming-caret.tsx"],+ // Rule 11: the one Spinner (K-redesign §5.1).+ spinnerHomes: ["components/icons/spinner/spinner.tsx"],+ // Rule 20: tokens only; hex colours in the avatar palette and in the contract, whose accent+ // presets carry the swatch a picker paints for a preset the active theme does not apply.+ tokensOnly: true,+ hexHomes: ["avatar.ts", "tokens.ts"],+};++/** Occurrences a named wave removes, by root-relative path. The package starts with none. */+const ALLOWLIST: DeslopAllowlist = {};++/** Not UI: the test machinery spells the patterns the rules look for, and hooks.ts is a list. */+const NOT_UI = ["testing/", "hooks.ts"];++const SCAN = scanSourceRoots({ ui: SRC_DIR }, { repoRoot: REPO_ROOT });+const ACTIVE = SCAN.files.filter((file) => !matchesPolicyPath(file.rel, NOT_UI));+const relOf = (id: string) => id.slice("packages/ui/src/".length);++const MARKUP = /\.tsx?$/;+const hasTsx = ACTIVE.some((file) => file.name.endsWith(".tsx"));++/** Why a rule has nothing to read here yet, or null when it does. */+function nothingToRead(rule: DeslopRule, surface: "markup" | "stylesheet"): string | null {+ const active = ACTIVE.filter((f) => (surface === "markup" ? MARKUP : /\.css$/).test(f.name));+ if (surface === "stylesheet") return active.length > 0 ? null : "no stylesheet to read";+ if (rule === 21) {+ return active.some((f) => /^strings.*\.ts$/.test(f.name)) ? null : "no strings dictionary yet";+ }+ if (!hasTsx) {+ return "no .tsx under packages/ui/src yet — the screens (#763), the modules (#764) and the W1 components are read when they land";+ }+ const named =+ rule === 15+ ? TABULAR_COMPONENTS+ : rule === 16+ ? LABEL_COMPONENTS+ : rule === 22+ ? PAGE_HEADER_COMPONENTS+ : null;+ if (named !== null) {+ const found = active.some((f) => analyzeFile(f).components.some((c) => named.includes(c.name)));+ if (!found) return `no ${named.join(" / ")} component yet`;+ }+ return null;+}++describe("de-slop rules over packages/ui/src", () => {+ it("scans the package source, and every allowlisted file is in it", () => {+ expect(unscannedRoots(SCAN)).toEqual([]);+ expect(Object.keys(ALLOWLIST).filter((rel) => !ACTIVE.some((f) => f.rel === rel))).toEqual([]);+ });++ for (const rule of DESLOP_RULE_NUMBERS) {+ for (const surface of ["markup", "stylesheet"] as const) {+ if (!DESLOP_CHECKS.some((c) => c.rule === rule && c.surface === surface)) continue;+ const title = `rule ${rule}: ${DESLOP_RULES[rule]} (${surface === "markup" ? "markup" : "stylesheets"})`;++ const extension = surface === "markup" ? MARKUP : /\.css$/;+ const reason = nothingToRead(rule, surface);+ if (reason !== null) {+ it.skip(`${title} — PENDING: ${reason}`, () => {});+ continue;+ }+ it(title, () => {+ const hits = deslopHits(+ ACTIVE.filter((f) => extension.test(f.name)),+ rule,+ POLICY,+ surface,+ );+ expect(+ allowlistProblems(hits, rule, ALLOWLIST, (hit) => relOf(hit.file)),+ `K-redesign §3 rule ${rule}: ${DESLOP_RULES[rule]}.`,+ ).toEqual([]);+ });+ }+ }+});++describe("theme values the rules reach", () => {+ // §2.4: a theme may uppercase its h1 (through .ui-display) and h6, the group-label rung+ // (through .ui-eyebrow); nothing between is uppercased. Headings are set in the theme's chrome+ // face (`--ui-font-ui`), its reading face or its display face — never in `--ui-font-mono`, the+ // DATA face, and never in a literal monospace stack. Console's chrome face is itself+ // monospaced (user decision, 2026-09-19), and that is the one door: a heading rung reaches a+ // mono face only by reading `--ui-font-ui`, so a theme that wants mono titles says so once,+ // in the face, and a component still never writes `font-mono` on a label (rule 16). The+ // reading face stays proportional in every theme: prose is not set in mono.+ const themes = THEME_IDS.map((id) => {+ const rel = `themes/${id}.css`;+ const path = join(SRC_DIR, rel);+ const analysis: ThemeFileAnalysis | null = existsSync(path)+ ? analyzeThemeFile(readFileSync(path, "utf8"), id)+ : null;+ return { id, rel, analysis };+ });+ const MONO = /--ui-font-mono|monospace/;+ for (const { id, rel, analysis } of themes) {+ const title = `${rel}: h2–h5 not uppercased, no heading in the data face, prose not mono (rules 14, 16)`;+ if (analysis === null || analysis.isStub) {+ it.skip(`${title} — PENDING: the theme file is still a stub`, () => {});+ continue;+ }+ it(title, () => {+ const problems: string[] = [];+ for (const mode of THEME_MODES) {+ const values = modeDeclarations(analysis, mode);+ for (const level of [1, 2, 3, 4, 5, 6]) {+ const transform = values.get(`--ui-h${level}-transform`);+ if (level >= 2 && level <= 5 && transform !== undefined && transform !== "none") {+ problems.push(`${id} ${mode}: --ui-h${level}-transform is ${transform}`);+ }+ const font = values.get(`--ui-h${level}-font`) ?? "";+ if (MONO.test(font)) {+ problems.push(`${id} ${mode}: --ui-h${level}-font is ${font}`);+ }+ }+ const reading = values.get("--ui-font-sans") ?? "";+ if (MONO.test(reading) || /--ui-font-ui/.test(reading)) {+ problems.push(`${id} ${mode}: --ui-font-sans (the reading face) is ${reading}`);+ }+ }+ expect(problems).toEqual([]);+ });+ }+});++describe("the rule checks, on known shapes", () => {+ const file = (rel: string, text: string): SourceFile => ({+ root: "ui",+ rel,+ id: `packages/ui/src/${rel}`,+ path: `/virtual/${rel}`,+ name: rel.slice(rel.lastIndexOf("/") + 1),+ text,+ });+ /** What each rule reports for a snippet, as `rule:found`. */+ const found = (rel: string, text: string, policy: DeslopPolicy = POLICY) =>+ DESLOP_RULE_NUMBERS.flatMap((rule) =>+ deslopHits([file(rel, text)], rule, policy).map((hit) => `${rule}:${hit.found}`),+ );+ const tsx = (jsx: string, policy: DeslopPolicy = POLICY) =>+ found("screens/probe.tsx", `export function Probe() { return ${jsx}; }`, policy);+ /** The web app's reading of rule 20: palette classes are not refused, so other rules show alone. */+ const PALETTE_OK: DeslopPolicy = { ...POLICY, tokensOnly: false };++ it("tell class strings from prose, and split variants from the utility", () => {+ expect(isClassShaped("hover:scale-105")).toBe(true);+ expect(isClassShaped("[&>svg]:size-4")).toBe(true);+ expect(isClassShaped("uppercase")).toBe(true);+ expect(isClassShaped("Uppercase")).toBe(false);+ expect(isClassShaped("letters.")).toBe(false);+ expect(isClassShaped("sm")).toBe(false);+ expect(parseClassToken("dark:hover:!bg-gray-800")).toEqual({+ variants: ["dark", "hover"],+ utility: "bg-gray-800",+ });+ expect(parseClassToken("[&_[role=tab]]:text-fg")).toEqual({+ variants: ["[&_[role=tab]]"],+ utility: "text-fg",+ });+ // A dictionary sentence is not classes; a lookup table is.+ expect(+ found("strings.ts", 'export const S = { hint: "Names are shown in uppercase" };'),+ ).toEqual([]);+ expect(found("parts.ts", 'export const LABEL = "text-xs uppercase";')).toEqual([+ "14:uppercase",+ ]);+ // Comments and interpolation-adjacent fragments are never read.+ expect(+ found("parts.ts", "// transition-all\nexport const c = (n: number) => `duration-${n}`;"),+ ).toEqual([]);+ });++ it("rule 1 — transition properties", () => {+ expect(tsx('<i className="transition-all" />')).toEqual(["1:transition-all"]);+ expect(tsx('<i className="transition" />')).toEqual(["1:transition"]);+ expect(tsx('<i className="transition-[width]" />')).toEqual(["1:transition-[width]"]);+ expect(tsx('<i className="transition-transform" />')).toEqual(["1:transition-transform"]);+ expect(+ found(+ "components/chevron.tsx",+ 'export const C = () => <i className="transition-transform" />;',+ ),+ ).toEqual([]);+ expect(+ tsx('<i className="transition-colors transition-opacity transition-[color,opacity]" />'),+ ).toEqual([]);+ expect(+ found(+ "x.css",+ ".a { transition: all 150ms; }\n.b { transition: 150ms ease; }\n.c { transition: color 150ms, opacity 150ms; }",+ ),+ ).toEqual(["1:transition: all", "1:transition: all"]);+ expect(found("x.css", ".a { transition-property: color, border-radius; }")).toEqual([+ "1:transition-property: border-radius",+ ]);+ // A size transitions only in the layout-motion home, and only the sizes that rule names.+ const layout =+ ".a { transition-property: width, grid-template-rows; }\n.b { transition: height var(--ui-dur-layout); }";+ expect(found("theme.css", layout, { ...POLICY, layoutMotion: [] })).toEqual([+ "1:transition-property: width, grid-template-rows",+ "1:transition: height",+ ]);+ expect(found("theme.css", layout)).toEqual([]);+ expect(found("theme.css", ".a { transition-property: width, border-radius; }")).toEqual([+ "1:transition-property: border-radius",+ ]);+ });++ it("rule 2 — hover and press transforms", () => {+ expect(+ tsx('<i className="hover:scale-110 active:scale-95 group-hover:-translate-y-0.5" />'),+ ).toEqual(["2:hover:scale-110", "2:active:scale-95", "2:group-hover:-translate-y-0.5"]);+ expect(tsx('<i className="scale-110 rotate-180" />')).toEqual([]);+ expect(found("x.css", ".a:hover { transform: scale(1.05); }")).toEqual([+ "2:.a:hover { transform: scale(1.05) }",+ ]);+ });++ it("rule 3 — durations", () => {+ expect(+ tsx('<i className="duration-150 duration-200 duration-[var(--ui-dur-fast)]" />'),+ ).toEqual([]);+ expect(tsx('<i className="duration-100 duration-300 duration-[250ms]" />')).toEqual([+ "3:duration-100",+ "3:duration-300",+ "3:duration-[250ms]",+ ]);+ const entrance = { ...POLICY, entranceMotion: ["screens/probe.tsx"] };+ expect(+ found(+ "screens/probe.tsx",+ 'export const P = () => <i className="duration-300" />;',+ entrance,+ ),+ ).toEqual([]);+ expect(+ found("x.css", ".a { transition: color 160ms; }\n.b { transition-duration: 90ms; }"),+ ).toEqual(["3:transition-duration: 90ms"]);+ });++ it("rule 4 — nested radius", () => {+ expect(tsx('<div className="rounded-lg p-3"><div className="rounded-md" /></div>')).toEqual([+ "4:<div> rounded-md in a padded rounded box",+ ]);+ expect(+ tsx(+ '<div className="rounded-lg p-3"><div className="rounded-[var(--radius-inner)]" /><span className="rounded-full" /></div>',+ ),+ ).toEqual([]);+ expect(tsx('<div className="rounded-lg px-3"><div className="rounded-md" /></div>')).toEqual(+ [],+ );+ });++ it("rule 5 — a clipping rounded box owns the border", () => {+ expect(+ tsx(+ '<div className="overflow-hidden rounded-md"><ul className="border border-line" /></div>',+ ),+ ).toEqual(["5:<ul> border inside a clipping rounded box"]);+ expect(+ tsx('<div className="overflow-hidden rounded-md border"><ul className="border-t" /></div>'),+ ).toEqual([]);+ });++ it("rule 6 — halos and pulses", () => {+ expect(tsx('<i className="animate-ping" />')).toEqual(["6:animate-ping"]);+ expect(tsx('<i className="animate-pulse" />')).toEqual(["6:animate-pulse"]);+ expect(tsx('<i className="ui-live animate-pulse" data-live="caret" />')).toEqual([]);+ expect(+ found(+ "components/skeleton/skeleton.tsx",+ 'export const S = () => <i className="animate-pulse" />;',+ ),+ ).toEqual([]);+ expect(+ tsx('<i className="h-2 w-2 rounded-full bg-tone-success-fg ring-2 ring-tone-success-bg" />'),+ ).toEqual(["6:ring-tone-success-bg on a dot"]);+ expect(tsx('<i className="size-2 rounded-full ring-2 ring-canvas" />')).toEqual([]);+ });++ it("rule 7 — an icon in a tint of itself", () => {+ expect(+ tsx(+ '<span className="bg-tone-danger-bg text-tone-danger-fg"><span className="h-2.5 w-2.5 bg-current" /></span>',+ ),+ ).toEqual(["7:<span> holds only an icon, in danger ink on danger tint"]);+ expect(+ tsx('<span className="bg-red-50 text-red-600"><GlyphIcon d={x} /></span>', PALETTE_OK),+ ).toEqual(["7:<span> holds only an icon, in red ink on red tint"]);+ expect(+ tsx(+ '<span className="bg-tone-danger-bg text-tone-danger-fg"><GlyphIcon d={x} />{label}</span>',+ ),+ ).toEqual([]);+ expect(+ tsx(+ '<span className="bg-tone-danger-emphasis text-tone-danger-emphasis-fg"><GlyphIcon d={x} /></span>',+ ),+ ).toEqual([]);+ });++ it("rule 8 — coloured left-border callouts", () => {+ expect(tsx('<div className="border-l-4 border-tone-attention-line" />')).toEqual([+ "8:border-l-4 in a colour",+ ]);+ expect(found("x.css", ".q { @apply border-l-2 border-amber-400; }", PALETTE_OK)).toEqual([+ "8:border-l-2 in a colour",+ ]);+ expect(tsx('<div className="border-l-2 border-line" />')).toEqual([]);+ });++ it("rule 9 — tint and line of one hue", () => {+ expect(+ tsx('<div className="border-t border-tone-attention-line bg-tone-attention-bg" />'),+ ).toEqual(["9:attention: tint and line on one box"]);+ expect(+ found(+ "toast.ts",+ 'export const K = { error: "border-red-200 bg-red-50 text-red-800" };',+ PALETTE_OK,+ ),+ ).toEqual(["9:red: tint and line on one box"]);+ expect(+ tsx('<div className="border border-line bg-tone-attention-bg text-tone-attention-fg" />'),+ ).toEqual([]);+ expect(tsx('<span className="border border-tone-danger-line text-tone-danger-fg" />')).toEqual(+ [],+ );+ });++ it("rule 10 — mood badges", () => {+ expect(tsx("<Badge>New</Badge>")).toEqual(["10:<Badge>New</Badge>"]);+ expect(tsx("<Badge>✨</Badge>")).toEqual(["10:<Badge>✨</Badge>"]);+ expect(+ found("beta.tsx", "export function BetaBadge() { return <Badge>beta</Badge>; }"),+ ).toEqual([]);+ expect(tsx("<Badge>Running</Badge>")).toEqual([]);+ });++ it("rule 11 — one spinner", () => {+ expect(+ tsx('<i className="animate-spin rounded-full border-2 border-t-transparent" />'),+ ).toEqual(["11:animate-spin", "11:border-t-transparent"]);+ expect(+ found(+ "components/icons/spinner/spinner.tsx",+ 'export const S = () => <svg className="animate-spin" />;',+ ),+ ).toEqual([]);+ });++ it("rule 12 — rhythm steps", () => {+ expect(tsx('<div className="gap-0.5 gap-x-5 space-y-2.5 p-[3px]" />')).toEqual([+ "12:gap-0.5",+ "12:gap-x-5",+ "12:space-y-2.5",+ "12:p-[3px]",+ ]);+ expect(+ tsx(+ '<div className="gap-1 gap-1.5 space-y-3 p-4 px-2.5 gap-[var(--ui-stack-1)] -space-x-2" />',+ ),+ ).toEqual([]);+ });++ it("rule 13 — text rungs", () => {+ expect(tsx('<i className="text-[11px] text-[0.6875rem]" />')).toEqual([+ "13:text-[11px]",+ "13:text-[0.6875rem]",+ ]);+ expect(tsx('<i className="text-xs text-[0.85em] text-[var(--ui-text-code-size)]" />')).toEqual(+ [],+ );+ });++ it("rule 14 — uppercase and eyebrows", () => {+ expect(tsx('<i className="uppercase tracking-wide" />')).toEqual([+ "14:uppercase",+ "14:tracking-wide",+ ]);+ expect(tsx('<div><p className="ui-eyebrow">Group</p><h2>Title</h2></div>')).toEqual([+ "14:eyebrow directly above <h2>",+ ]);+ expect(tsx('<><Text variant="eyebrow">Group</Text><Heading level={3}>T</Heading></>')).toEqual([+ "14:eyebrow directly above <Heading>",+ ]);+ expect(tsx('<div><p className="ui-eyebrow">Group</p><ul /></div>')).toEqual([]);+ expect(+ found(+ "t.css",+ ".a .ui-eyebrow { text-transform: uppercase; }\n.b { text-transform: uppercase; }\n" ++ // The transcript's mono capitals: a step's label is a group-label rung in Console;+ // a plot's axis labels are the same rung.+ '.ui-activity [data-slot="label"] { text-transform: uppercase; }\n' ++ '.ui-chart [data-part="label"] { text-transform: uppercase; }',+ ),+ ).toEqual(["14:.b { text-transform: uppercase }"]);+ });++ it("rules 15, 16, 22 — the named components", () => {+ expect(+ found("chip.tsx", 'export function StatChip() { return <span className="font-mono" />; }'),+ ).toEqual(["15:StatChip has no tabular-nums"]);+ expect(+ found("button.tsx", 'export function Button() { return <button className="font-mono" />; }'),+ ).toEqual(["16:font-mono in Button"]);+ expect(+ found("t.css", ".x .ui-frame > [data-slot=head] { font-family: var(--ui-font-mono); }"),+ ).toEqual(["16:.x .ui-frame > [data-slot=head] { font-family: var(--ui-font-mono) }"]);+ expect(+ found(+ "page-header.tsx",+ "export function PageHeader({ title, eyebrow }: { title: string; eyebrow?: string }) { return <h2>{title}</h2>; }",+ ),+ ).toEqual(["22:PageHeader takes an eyebrow"]);+ });++ it("rule 17 — one surface per region", () => {+ expect(+ tsx(+ '<div className="border bg-surface">{items.map((i) => <div className="rounded-md border bg-surface-muted" />)}</div>',+ ),+ ).toEqual(["17:<div> surface inside the surface at line 1"]);+ expect(+ tsx('<div className="border bg-surface"><span className="border bg-surface" /></div>'),+ ).toEqual([]);+ });++ it("rule 18 — decoration", () => {+ expect(+ tsx(+ '<i className="bg-gradient-to-r bg-[radial-gradient(circle,red,blue)] backdrop-blur-md" />',+ ),+ ).toEqual([+ "18:bg-gradient-to-r",+ "18:bg-[radial-gradient(circle,red,blue)]",+ "18:backdrop-blur-md",+ ]);+ expect(tsx('<i className="ui-glass backdrop-blur-md" />')).toEqual([]);+ expect(tsx('<i className="ui-scrim backdrop-blur-md" />')).toEqual([]);+ expect(+ found(+ "t.css",+ ".ui-wash { background-image: radial-gradient(red, blue); }\n.hatch { background-image: repeating-linear-gradient(red, blue); }",+ ),+ ).toEqual(["18:.ui-wash { background-image: …gradient() }"]);+ // The shell's colour field and the running activity row's highlight are the two gradients a+ // recipe may paint (each has a job); a blur on the shell is still off, and so is a gradient+ // on a resting activity row.+ expect(+ found(+ "t.css",+ ':root .ui-activity[data-state="running"] [data-slot="label"] { background-image: linear-gradient(red, blue); }\n' ++ ':root .ui-activity[data-state="done"] { background: linear-gradient(red, blue); }',+ ),+ ).toEqual(['18::root .ui-activity[data-state="done"] { background: …gradient() }']);+ // A chart may paint a gradient as a mask (an area's fade, a bar's hatch); a mask gradient on+ // any other hook is the tell like a background one.+ expect(+ found(+ "t.css",+ ':root .ui-chart [data-part="area"] { mask-image: linear-gradient(#000, transparent); }\n' ++ ':root .ui-chart [data-part="bar"] { -webkit-mask-image: repeating-linear-gradient(red, blue); }\n' ++ ":root .ui-frame { mask-image: linear-gradient(red, blue); }",+ ),+ ).toEqual(["18::root .ui-frame { mask-image: …gradient() }"]);+ expect(+ found(+ "t.css",+ ':root .ui-shell { background-image: radial-gradient(red, blue); }\n:root .ui-shell > [data-slot="nav"] { backdrop-filter: blur(4px); }\n:root .ui-frame { background: linear-gradient(red, blue); }',+ ),+ ).toEqual([+ '18::root .ui-shell > [data-slot="nav"] { backdrop-filter: blur(4px) }',+ "18::root .ui-frame { background: …gradient() }",+ ]);+ // The scrim behind a dialog may blur the page as the glass does (Frost's frosted backdrop).+ expect(+ found(+ "t.css",+ ":root .ui-scrim { backdrop-filter: blur(14px); }\n:root .ui-glass { -webkit-backdrop-filter: blur(16px); }",+ ),+ ).toEqual([]);+ });++ it("rule 19 — shadows", () => {+ expect(+ tsx(+ '<i className="shadow-md shadow-2xl shadow-black/10 drop-shadow-sm shadow" />',+ PALETTE_OK,+ ),+ ).toEqual([+ "19:shadow-md",+ "19:shadow-2xl",+ "19:shadow-black/10",+ "19:drop-shadow-sm",+ "19:shadow",+ ]);+ expect(+ tsx(+ '<i className="shadow-sm shadow-lg shadow-xl shadow-none shadow-[var(--ui-shadow-drawer)]" />',+ ),+ ).toEqual([]);+ });++ it("rule 20 — colour is tokens", () => {+ expect(+ tsx('<i className="bg-gray-100 dark:bg-surface text-white" style={{ color: "#2563eb" }} />'),+ ).toEqual(["20:bg-gray-100", "20:dark:bg-surface", "20:text-white", "20:#2563eb"]);+ expect(found("tokens.ts", 'export const C = "#2563eb";')).toEqual([]);+ expect(found("screens/p.tsx", 'export const L = "trace file #001";')).toEqual([]);+ expect(+ found("x.tsx", 'export const X = () => <i className="bg-gray-100" />;', PALETTE_OK),+ ).toEqual([]);+ });++ it("hold an allowlist to its exact counts, so it only shrinks", () => {+ const hit = (rel: string, line: number) => ({+ rule: 13 as const,+ file: `packages/web/src/${rel}`,+ line,+ found: "text-[11px]",+ });+ const hits = [hit("a.tsx", 1), hit("a.tsx", 2), hit("b.tsx", 3), hit("c.tsx", 4)];+ const problems = allowlistProblems(+ hits,+ 13,+ {+ "a.tsx": { 13: [1, "W4"] }, // two hits against one allowed: the second is new slop+ "c.tsx": { 13: [2, "W6"] }, // one left of two: the entry shrinks+ "d.tsx": { 13: [1, "W7"] }, // none left: the entry goes+ "e.tsx": { 12: [1, "W7"] }, // another rule's entry is not this rule's business+ },+ (h) => h.file.slice("packages/web/src/".length),+ );+ expect(problems).toEqual([+ "a.tsx: 2 where 1 are allowlisted (W4)\n packages/web/src/a.tsx:1 text-[11px]\n packages/web/src/a.tsx:2 text-[11px]",+ "b.tsx: 1 new\n packages/web/src/b.tsx:3 text-[11px]",+ 'c.tsx: 1 left of 2 — shrink the entry to [1, "W6"]',+ "d.tsx: none left of 1 (W7) — delete the entry",+ ]);+ });++ it("rule 21 — emoji in copy", () => {+ expect(found("strings.ts", 'export const T = { title: "✨ New" };')).toEqual(["21:✨"]);+ expect(found("strings-en.ts", 'export const S = { ok: "Done ✓", copy: "© 2026" };')).toEqual(+ [],+ );+ });+});diff --git a/packages/ui/test/font-credits.test.ts b/packages/ui/test/font-credits.test.tsnew file mode 100644index 00000000..b8180b1f--- /dev/null+++ b/packages/ui/test/font-credits.test.ts@@ -0,0 +1,62 @@+/**+ * The credits list (src/fonts/credits.ts) against the licence mirror (src/fonts/LICENSES/).+ *+ * `font-licenses.test.ts` holds the mirror to the font packages; this suite holds the list a+ * Credits page renders to the mirror: every text credited exactly once, every credit's text the+ * file's own, every credit naming the licence its text carries, the vendored face's title and+ * source what `vendored-fonts.json` declares, and the themes a face is credited to the themes+ * whose stacks name it.+ */+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { BUNDLED_FONT_FAMILIES, THEME_FONTS } from "../src/boot";+import { FONT_CREDITS, MISANS_LICENSE_TITLE, MISANS_SOURCE } from "../src/fonts/credits";+import { THEME_IDS } from "../src/tokens";+import { SRC_DIR } from "./helpers/paths";++const LICENSES_DIR = join(SRC_DIR, "fonts", "LICENSES");++describe("FONT_CREDITS", () => {+ it("credits every licence in the mirror once, with the file's own text", () => {+ const files = readdirSync(LICENSES_DIR)+ .filter((name) => name.endsWith(".txt"))+ .map((name) => name.slice(0, -".txt".length))+ .sort();+ expect([...FONT_CREDITS.map((credit) => credit.id)].sort()).toEqual(files);+ for (const credit of FONT_CREDITS) {+ const text = readFileSync(join(LICENSES_DIR, `${credit.id}.txt`), "utf8");+ expect(credit.licenseText, credit.id).toBe(text);+ }+ });++ it("names the licence each text carries, and the vendored face's manifest values", () => {+ for (const credit of FONT_CREDITS) {+ expect(credit.licenseText, credit.id).toMatch(+ credit.id === "misans" ? credit.licenseTitle : /SIL Open Font License/i,+ );+ expect(credit.family).not.toBe("");+ expect(credit.source).not.toBe("");+ }+ const manifest = JSON.parse(+ readFileSync(join(SRC_DIR, "fonts", "vendored-fonts.json"), "utf8"),+ ) as Record<string, { licenseTitle: string; package: string; family: string }>;+ expect(MISANS_LICENSE_TITLE).toBe(manifest.misans!.licenseTitle);+ expect(MISANS_SOURCE).toBe(manifest.misans!.package);+ expect(FONT_CREDITS.find((credit) => credit.id === "misans")?.family).toBe(+ manifest.misans!.family,+ );+ });++ it("credits each face to the themes whose own faces name it, and every bundled face once", () => {+ const families = FONT_CREDITS.map((credit) => credit.family);+ expect(new Set(families).size).toBe(families.length);+ for (const family of Object.keys(BUNDLED_FONT_FAMILIES)) {+ const credit = FONT_CREDITS.find((entry) => entry.family === family);+ expect(credit, family).toBeDefined();+ expect([...credit!.themes]).toEqual(+ THEME_IDS.filter((id) => Object.values(THEME_FONTS[id]).includes(family)),+ );+ }+ });+});diff --git a/packages/ui/test/font-licenses.test.ts b/packages/ui/test/font-licenses.test.tsnew file mode 100644index 00000000..224ef7c8--- /dev/null+++ b/packages/ui/test/font-licenses.test.ts@@ -0,0 +1,273 @@+/**+ * Every font the package ships carries its licence (A-architecture §5).+ *+ * The fonts are bundled into the Web App's `dist/` — and from there into the server tarball and the+ * desktop app — so the OFL's condition travels with them: the licence text has to ship beside the+ * font files. The package mirrors each font dependency's licence into `src/fonts/LICENSES/`+ * (`scripts/sync-font-licenses.mjs`), and the Vite plugin emits that directory into every consumer's+ * build. What decays is the mirror: a font added without its text, a text left behind after its+ * font was dropped, a copy that no longer matches the package it came from, or a `@font-face` that+ * names a file the package does not have. Each is checked here.+ *+ * Naming: a dependency `@fontsource[-variable]/<family>` mirrors to `LICENSES/<family>.txt`, the+ * text normalized the way the sync script writes it (LF endings, no trailing spaces, one final+ * newline).+ *+ * Fonts arrive as dependencies, with one exception the manifest `src/fonts/vendored-fonts.json`+ * declares: a font with no package (MiSans) is vendored as woff2 slices in its own directory, and its+ * licence is the licensor's own text, transcribed into `LICENSES/` by hand and naming its title. Any+ * other font binary checked into the package is refused, and a TTF or OTF is refused everywhere — the+ * package never carries a whole font file that could be offered on its own.+ *+ * Until the package ships a font, the checks have nothing to hold and say so as a skipped case.+ */+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { basename, dirname, join, relative, resolve, sep } from "node:path";+import { describe, expect, it } from "vitest";+import { scanSourceRoots, stripCssComments } from "../src/testing";+import { PACKAGE_DIR, REPO_ROOT, SRC_DIR } from "./helpers/paths";++const FONTS_DIR = join(SRC_DIR, "fonts");+const LICENSES_DIR = join(FONTS_DIR, "LICENSES");+const NODE_MODULES = join(PACKAGE_DIR, "node_modules");+const FONT_PACKAGE = /^@fontsource(?:-variable)?\/([a-z0-9-]+)$/;+const FONT_FILE = /\.(?:woff2?|ttf|otf|eot)$/i;+/** The licences a bundled font may carry. */+const KNOWN_LICENSE = /SIL OPEN FONT LICENSE|Apache License|Permission is hereby granted/i;+const LICENSE_FILES = ["LICENSE", "LICENSE.txt", "LICENSE.md", "OFL.txt"];++/** An entry of `src/fonts/vendored-fonts.json`: a font with no package, cut into the package. */+interface VendoredFont {+ readonly family: string;+ /** Package-relative directory holding its woff2 slices, ending in `/`. */+ readonly files: string;+ /** Package-relative path of its licence text, under `src/fonts/LICENSES/`. */+ readonly license: string;+ /** The licence's title; the text must contain it. */+ readonly licenseTitle: string;+}+const VENDORED_MANIFEST = join(FONTS_DIR, "vendored-fonts.json");+const vendoredManifest: readonly VendoredFont[] = existsSync(VENDORED_MANIFEST)+ ? Object.values(+ JSON.parse(readFileSync(VENDORED_MANIFEST, "utf8")) as Record<string, VendoredFont>,+ )+ : [];+const vendoredLicenseNames = new Set(vendoredManifest.map((font) => basename(font.license)));+/** The vendored font a package-relative path belongs to, if it sits in one's slice directory. */+const vendoredFontOf = (rel: string) => vendoredManifest.find((font) => rel.startsWith(font.files));++const manifest = JSON.parse(readFileSync(join(PACKAGE_DIR, "package.json"), "utf8")) as {+ dependencies?: Record<string, string>;+};+const fontDependencies = Object.keys(manifest.dependencies ?? {}).filter((name) =>+ FONT_PACKAGE.test(name),+);+const family = (dependency: string) => FONT_PACKAGE.exec(dependency)![1]!;++interface FontReference {+ /** The stylesheet's repo-relative id. */+ readonly file: string;+ /** As written in `url()` or `@import`. */+ readonly specifier: string;+ /** The npm package the reference lands in (`@fontsource-variable/geist`); null for our own files. */+ readonly dependency: string | null;+ /** Absolute path of the target inside the installed package; null for our own files. */+ readonly target: string | null;+}++/**+ * Every `url()` and `@import` in the fonts CSS, placed: a bare `@scope/name/…` specifier, or a+ * relative path that climbs into `node_modules/@scope/name/…`, lands in that package; a relative+ * path to one of our own sheets lands in none.+ */+function fontReferences(): FontReference[] {+ if (!existsSync(FONTS_DIR)) return [];+ const scan = scanSourceRoots({ fonts: FONTS_DIR }, { repoRoot: REPO_ROOT, extensions: [".css"] });+ const refs: FontReference[] = [];+ const place = (file: { id: string; path: string }, specifier: string) => {+ if (specifier.startsWith("data:")) return;+ const bare = specifier.startsWith(".") ? null : /^(@[^/]+\/[^/]+)/.exec(specifier)?.[1];+ if (bare !== null) {+ refs.push({+ file: file.id,+ specifier,+ dependency: bare ?? null,+ target: bare === undefined ? null : join(NODE_MODULES, specifier),+ });+ return;+ }+ const target = resolve(dirname(file.path), specifier.replace(/[?#].*$/, ""));+ const [scope, name] = relative(NODE_MODULES, target).split(sep);+ const dependency =+ scope !== undefined && scope.startsWith("@") && name !== undefined+ ? `${scope}/${name}`+ : null;+ refs.push({+ file: file.id,+ specifier,+ dependency,+ target: dependency === null ? null : target,+ });+ };+ for (const file of scan.files) {+ const css = stripCssComments(file.text);+ for (const m of css.matchAll(/url\(\s*(["']?)([^"')]+)\1\s*\)/g)) place(file, m[2]!.trim());+ for (const m of css.matchAll(/@import\s+(["'])([^"']+)\1/g)) place(file, m[2]!.trim());+ }+ return refs;+}++/** Font binaries checked into the package itself (node_modules excluded), package-relative with `/`. */+function fontBinaries(dir = PACKAGE_DIR, out: string[] = []): string[] {+ for (const name of readdirSync(dir)) {+ if (name === "node_modules") continue;+ const path = join(dir, name);+ if (statSync(path).isDirectory()) fontBinaries(path, out);+ else if (FONT_FILE.test(name)) out.push(relative(PACKAGE_DIR, path).split(sep).join("/"));+ }+ return out;+}++/** The licence file inside an installed dependency, or undefined. */+function installedLicense(dependency: string): string | undefined {+ const dir = join(NODE_MODULES, dependency);+ const file = LICENSE_FILES.map((name) => join(dir, name)).find((path) => existsSync(path));+ return file === undefined ? undefined : readFileSync(file, "utf8");+}++/** The sync script's normalization: LF endings, no trailing spaces, one final newline. */+const normalize = (text: string) =>+ `${text+ .replace(/\r\n?/g, "\n")+ .split("\n")+ .map((line) => line.trimEnd())+ .join("\n")+ .trimEnd()}\n`;++describe("font licences", () => {+ const references = fontReferences();+ const binaries = fontBinaries();+ const mirrored = existsSync(LICENSES_DIR)+ ? readdirSync(LICENSES_DIR).filter((name) => name.endsWith(".txt"))+ : [];+ const shipsFonts =+ fontDependencies.length > 0 ||+ references.some((ref) => ref.dependency !== null) ||+ binaries.length > 0 ||+ mirrored.length > 0;++ if (!shipsFonts) {+ it.skip("src/fonts — PENDING, the package ships no font yet: licences not checked", () => {});+ return;+ }++ it("are mirrored for every font dependency", () => {+ const missing = fontDependencies+ .filter((dependency) => !mirrored.includes(`${family(dependency)}.txt`))+ .map((dependency) => `${dependency} → src/fonts/LICENSES/${family(dependency)}.txt`);+ expect(missing, "Run `pnpm --filter @prismshadow/penguin-ui sync:font-licenses`.").toEqual([]);+ });++ it("are not kept for fonts the package no longer depends on or vendors", () => {+ const families = new Set(fontDependencies.map(family));+ expect(+ mirrored.filter(+ (name) => !families.has(name.replace(/\.txt$/, "")) && !vendoredLicenseNames.has(name),+ ),+ ).toEqual([]);+ });++ it("match the licence each dependency ships, and are a licence a bundled font may carry", () => {+ const problems: string[] = [];+ for (const dependency of fontDependencies) {+ const copy = join(LICENSES_DIR, `${family(dependency)}.txt`);+ if (!existsSync(copy)) continue; // reported above+ const text = readFileSync(copy, "utf8");+ if (!KNOWN_LICENSE.test(text)) problems.push(`${dependency}: not a recognised font licence`);+ const upstream = installedLicense(dependency);+ if (upstream === undefined) {+ problems.push(`${dependency}: no licence file in the installed package`);+ } else if (normalize(upstream) !== text) {+ problems.push(`${dependency}: the mirrored text has drifted from the package's own`);+ }+ }+ expect(problems).toEqual([]);+ });++ it("name their licence for every vendored font, beside the slices they cover", () => {+ const problems: string[] = [];+ for (const font of vendoredManifest) {+ if (!font.files.endsWith("/") || !existsSync(join(PACKAGE_DIR, font.files))) {+ problems.push(`${font.family}: files "${font.files}" is not a directory of the package`);+ } else if (+ !fontBinaries().some((rel) => rel.startsWith(font.files) && rel.endsWith(".woff2"))+ ) {+ problems.push(`${font.family}: ${font.files} holds no woff2 slice — drop the entry`);+ }+ if (dirname(join(PACKAGE_DIR, font.license)) !== LICENSES_DIR) {+ problems.push(+ `${font.family}: ${font.license} is outside src/fonts/LICENSES/, so no build ships it`,+ );+ } else if (!existsSync(join(PACKAGE_DIR, font.license))) {+ problems.push(`${font.family}: ${font.license} is missing`);+ } else {+ const text = readFileSync(join(PACKAGE_DIR, font.license), "utf8");+ if (!text.includes(font.licenseTitle)) {+ problems.push(`${font.family}: ${font.license} does not name ${font.licenseTitle}`);+ }+ if (normalize(text) !== text) {+ problems.push(`${font.family}: ${font.license} is not whitespace-normalized`);+ }+ }+ if (+ fontDependencies.some(+ (dependency) => `${family(dependency)}.txt` === basename(font.license),+ )+ ) {+ problems.push(`${font.family}: ${basename(font.license)} is also a dependency's mirror`);+ }+ }+ expect(problems).toEqual([]);+ });++ it("cover every font the stylesheets load, which must exist in its package", () => {+ const problems: string[] = [];+ for (const { file, specifier, dependency, target } of references) {+ if (dependency === null) {+ // One of our own files: a sheet, or a vendored font's slice.+ if (!FONT_FILE.test(specifier.replace(/[?#].*$/, ""))) continue;+ const sheet = join(REPO_ROOT, file);+ const rel = relative(PACKAGE_DIR, resolve(dirname(sheet), specifier.replace(/[?#].*$/, "")))+ .split(sep)+ .join("/");+ if (vendoredFontOf(rel) === undefined) {+ problems.push(`${file}: ${specifier} is a font file of no vendored font`);+ } else if (!existsSync(join(PACKAGE_DIR, rel))) {+ problems.push(`${file}: ${specifier} does not exist`);+ }+ continue;+ }+ if (!fontDependencies.includes(dependency)) {+ problems.push(`${file}: ${specifier} is from ${dependency}, not a font dependency`);+ } else if (!mirrored.includes(`${family(dependency)}.txt`)) {+ problems.push(`${file}: ${specifier} is from ${dependency}, whose licence is not mirrored`);+ } else if (target === null || !existsSync(target)) {+ problems.push(`${file}: ${specifier} does not exist in the installed package`);+ }+ }+ expect(problems).toEqual([]);+ });++ it("finds the font files the stylesheets load — the scan is exercised on the real sheets", () => {+ // A reference pattern that stopped matching would pass the check above over nothing.+ expect(references.filter((ref) => ref.dependency !== null).length).toBeGreaterThan(0);+ });++ it("arrive as dependencies or as a vendored font's woff2 slices, never as other binaries", () => {+ expect(+ binaries.filter((rel) => !(rel.endsWith(".woff2") && vendoredFontOf(rel) !== undefined)),+ "A font binary in the package must be a woff2 slice under a vendored-fonts.json entry's " ++ "files directory; a TTF or OTF is never checked in.",+ ).toEqual([]);+ });+});diff --git a/packages/ui/test/helpers/paths.ts b/packages/ui/test/helpers/paths.tsnew file mode 100644index 00000000..7a281954--- /dev/null+++ b/packages/ui/test/helpers/paths.ts@@ -0,0 +1,11 @@+/** Absolute paths the package's suites read from. */+import { fileURLToPath } from "node:url";++/** `packages/ui/`, with a trailing separator. */+export const PACKAGE_DIR = fileURLToPath(new URL("../../", import.meta.url));+/** `packages/ui/src/`. */+export const SRC_DIR = fileURLToPath(new URL("../../src/", import.meta.url));+/** The monorepo root. */+export const REPO_ROOT = fileURLToPath(new URL("../../../../", import.meta.url));+/** `packages/web/`, whose index.html carries the inline copy of the boot script. */+export const WEB_DIR = fileURLToPath(new URL("../../../web/", import.meta.url));diff --git a/packages/ui/test/hooks.test.ts b/packages/ui/test/hooks.test.tsnew file mode 100644index 00000000..74ab4597--- /dev/null+++ b/packages/ui/test/hooks.test.ts@@ -0,0 +1,472 @@+/**+ * The closed list of style hooks (K-redesign §1.2, Appendices A and B).+ *+ * A hook is a class a component opts into and each theme's CSS gives meaning to. The list is+ * closed so that no theme grows a costume one class at a time: the W0 drafts had eleven hooks, and+ * five of them (a gradient wash, a column grid, a dot matrix, corner ticks, radius that eases on+ * hover, mono button labels) were decoration with no job. `src/hooks.ts` exports the six that+ * remained, the seventh added with the theme identities — `ui-shell`, the app window, the one+ * place a theme may lay a colour field (user decision, 2026-09-19) — the three structure hooks+ * that let the themes differ in organisation rather than in colour alone: `ui-icon-decor` (an icon+ * a theme may recolour or drop), `ui-tree` (rows that nest, which Console joins with connector+ * rules) and `ui-field` (a labelled control row, which Console sets as a table row) — and the+ * eleventh, `ui-activity` (a step of the agent's work: Frost sweeps a highlight across its label,+ * Console renders a transcript; user decision, 2026-09-29), the twelfth and thirteenth,+ * `ui-notice` and `ui-chart` (notices and charts that differ per theme; the same day), and the+ * fourteenth, `ui-scrim` (the dimmed backdrop behind a dialog, which Frost blurs; 2026-09-30).+ * This suite holds the source to it:+ *+ * - no `ui-*` class in markup, and no `.ui-*` selector in a stylesheet, outside the list — in the+ * package, the web app and the gallery;+ * - each hook applied only inside the components Appendix B names as its hosts: glass only on+ * transient layers, the eyebrow only as a group label, the display face only on a page title,+ * the shell only on an app-window frame, the tree only on a nesting list. A host is the nearest+ * enclosing PascalCase function, so a stand-in in `screens/` or `modules/` carries the name of+ * the component it imitates. The decorative-icon hook is applied through the icon renderers+ * (`GlyphIcon`, `Glyph`), which write the class when a call site passes `decor`; the guard+ * therefore reads `decor` on the call site and holds its enclosing component to the list, so+ * the renderer being a host loosens nothing;+ * - the markup the recipes select on: `.ui-live` names its signal in `data-live`, `.ui-display`+ * sits on an h1, `.ui-frame`'s slots are `head`, `body`, `foot` or `pane`, `.ui-shell`'s are+ * `nav`, `main` or `dock`, `.ui-field`'s are `label`, `control` or `hint`, a tree row's+ * `data-depth` is a digit 0–8 and its `data-last` is `"true"`, a decorative icon's+ * `data-role` is one of the four the recipes tint apart, `.ui-activity` names its kind+ * (`thinking` / `tool`), its state (`running` / `done` / `error`) and its slots (`label`,+ * `detail`, `progress`), `.ui-notice` its tone (the five) and its slots (`icon`, `title`,+ * `body`, `actions`), and a chart's parts are the seven the recipes style, wherever a+ * `data-part` is written.+ */+import { existsSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { HOOKS } from "../src/hooks";+import { analyzeFile, matchesPolicyPath, scanSourceRoots, unscannedRoots } from "../src/testing";+import type { ClassToken, FileAnalysis, JsxElementInfo, SourceFile } from "../src/testing";+import { REPO_ROOT, SRC_DIR, WEB_DIR } from "./helpers/paths";++/** Appendix A. Adding a hook is a catalog change: this list, the host table and every theme. */+const APPENDIX_A = [+ "ui-glass",+ "ui-eyebrow",+ "ui-display",+ "ui-live",+ "ui-frame",+ "ui-underline-nav",+ "ui-shell",+ "ui-icon-decor",+ "ui-tree",+ "ui-field",+ "ui-activity",+ "ui-notice",+ "ui-chart",+ "ui-scrim",+];++/**+ * Appendix B: the components that may apply each hook — the web app's own components, which the+ * gallery frames as they are (the package itself renders none). A component is listed only while+ * it exists: the last test below fails on a host no scanned file declares.+ *+ * Glass is for the layers that float over the page (the composer card, dialogs, menus, popovers,+ * tooltips); the eyebrow and display rungs for the sidebar's list label and the page titles; live+ * marks for the spinner and the machines page's working marks; frames for the transcript's cards;+ * the shell for the app layout; a decorative icon for the rows and headers whose label already+ * says what the icon says (sidebar rows and group headers, the settings rail, a menu row's glyph,+ * a tab, an empty state) — a session row is not a host, its avatar and marks carry information;+ * a tree for a file tree and a work group's steps; a field for a settings row; activity for the+ * transcript's work in progress (the work group's header, a tool call, the thinking row).+ */+const HOSTS: Readonly<Record<string, readonly string[]>> = {+ "ui-glass": [+ "ChatInput",+ "Modal",+ "Dropdown",+ "Select",+ "OptionMenu",+ "InfoPopover",+ "Tooltip",+ "TooltipLayer",+ "TooltipPanel",+ ],+ "ui-eyebrow": ["Sidebar", "GroupHeader", "PagedDialog"],+ "ui-display": [+ "Heading",+ "EmptyState",+ "AgentsPage",+ "ModelsPage",+ "PluginsPage",+ "UsagePage",+ "BenchmarkPage",+ "MachinesPage",+ "DraftView",+ ],+ "ui-live": ["Spinner", "Stepper", "MachineCard"],+ "ui-frame": ["ToolCallCard", "WorkGroup", "CodeBlock"],+ "ui-underline-nav": ["Tabs"],+ "ui-shell": ["AppLayout"],+ "ui-icon-decor": [+ "GlyphIcon",+ "Sidebar",+ "PagedDialog",+ "SettingsDialog",+ "MenuItemGlyph",+ "GroupHeader",+ "Tabs",+ "EmptyState",+ ],+ "ui-tree": ["FileTree", "WorkGroup"],+ "ui-field": ["Field", "PrefRow", "SettingRow"],+ "ui-activity": ["WorkGroup", "ToolCallCard", "DisclosureRow"],+ // The Web App's notices (2026-09-29): the toast, and the one shared strip every inline notice+ // renders through. The charts: the usage charts' frame (its children — the trend, requests and+ // token-bar charts — carry parts, not the hook), the token donut and the two sparklines.+ "ui-notice": ["Toaster", "NoticeStrip"],+ // The Trace timeline draws its lanes and spans as HTML (`grid` on a lane track, `bar` on a+ // span with a 1-based `data-series`), so the chart recipes carry HTML spellings beside the+ // SVG ones.+ "ui-chart": ["ChartFrame", "TokenDonut", "ScoreSparkline", "ActivitySparkline", "TimelineChart"],+ // The dimmed backdrop (2026-09-30): a sibling behind a sheet or drawer, or the full-viewport+ // overlay a modal, the command palette, the harness overlay and the lightbox sit in.+ "ui-scrim": ["Modal", "Sheet", "Drawer", "CommandPalette", "HarnessHistoryOverlay", "Lightbox"],+};++/** CSS keywords that start with `ui-` and are not classes. */+const NOT_HOOKS = new Set(["ui-sans-serif", "ui-serif", "ui-monospace", "ui-rounded"]);++const FRAME_SLOTS = new Set(["head", "body", "foot", "pane"]);+const SHELL_SLOTS = new Set(["nav", "main", "dock"]);+const FIELD_SLOTS = new Set(["label", "control", "hint"]);+const LIVE_SIGNALS = new Set(["dot", "caret", "spinner"]);+const ICON_ROLES = new Set(["nav", "group", "menu", "empty"]);+const ACTIVITY_KINDS = new Set(["thinking", "tool"]);+const ACTIVITY_STATES = new Set(["running", "done", "error"]);+const ACTIVITY_SLOTS = new Set(["label", "detail", "progress"]);+const NOTICE_TONES = new Set(["info", "success", "warning", "danger", "neutral"]);+const NOTICE_SLOTS = new Set(["icon", "title", "body", "actions"]);+/** A chart's parts, wherever a chart's children are written (a mark component draws into the frame's svg). */+const CHART_PARTS = new Set(["grid", "axis", "series", "area", "bar", "point", "label"]);+/** The icon renderers: a `decor` prop on one of these is the decorative-icon hook applied. */+const ICON_RENDERERS = new Set(["GlyphIcon"]);+/** A tree row's depth: the eight levels the recipes spell out, and the roots. */+const TREE_DEPTH = /^[0-8]$/;++/** Not UI: the test machinery spells the patterns the checks look for, and hooks.ts is the list. */+const NOT_UI = ["testing/", "hooks.ts"];++const GALLERY_DIR = join(REPO_ROOT, "packages", "ui-gallery", "src");+const ROOTS = {+ ui: SRC_DIR,+ web: join(WEB_DIR, "src"),+ ...(existsSync(GALLERY_DIR) ? { gallery: GALLERY_DIR } : {}),+};+const SCAN = scanSourceRoots(ROOTS, { repoRoot: REPO_ROOT });+const filesOf = (root: string) =>+ SCAN.files.filter((f) => f.root === root && !(root === "ui" && matchesPolicyPath(f.rel, NOT_UI)));++/** Every `ui-*` class token in markup and every `.ui-*` class in a selector, with where it is. */+function hookNames(file: SourceFile): { name: string; line: number }[] {+ const analysis = analyzeFile(file);+ if (analysis.surface === "stylesheet") {+ return analysis.cssRules.flatMap((rule) =>+ [...[...rule.parents, rule.selector].join(" ").matchAll(/\.(ui-[a-z][\w-]*)/g)].map((m) => ({+ name: m[1]!,+ line: rule.line,+ })),+ );+ }+ return analysis.tokens+ .filter((t) => t.utility.startsWith("ui-") && !NOT_HOOKS.has(t.utility))+ .map((t) => ({ name: t.utility, line: t.line }));+}++/** The innermost component a token was written in, or null at module level. */+function componentOf(analysis: FileAnalysis, token: ClassToken): string | null {+ const owners = analysis.components.filter((c) => c.classes.includes(token));+ owners.sort((a, b) => a.classes.length - b.classes.length);+ return owners[0]?.name ?? null;+}++/** The literal `data-slot` values of an element's direct children, with the child. */+function childSlots(element: JsxElementInfo): { slot: string; child: JsxElementInfo }[] {+ return element.children.flatMap((child) => {+ if (child.kind !== "element") return [];+ const slot = child.element.attributes.get("data-slot");+ return typeof slot === "string" ? [{ slot, child: child.element }] : [];+ });+}++describe("style hooks", () => {+ const hooks = new Set<string>(HOOKS);++ it("are the fourteen of Appendix A, each with its hosts", () => {+ expect([...HOOKS].sort()).toEqual([...APPENDIX_A].sort());+ expect(Object.keys(HOSTS).sort()).toEqual([...APPENDIX_A].sort());+ });++ it("scans the package and the web app", () => {+ expect(unscannedRoots(SCAN)).toEqual([]);+ });++ for (const root of Object.keys(ROOTS)) {+ it(`are the only ui-* classes and selectors in ${root}`, () => {+ const strays = filesOf(root).flatMap((file) =>+ hookNames(file)+ .filter((found) => !hooks.has(found.name))+ .map((found) => `${file.id}:${found.line} ${found.name}`),+ );+ expect(+ strays,+ "A ui-* class outside src/hooks.ts is a hook no theme has agreed to — the deleted ones " ++ "(wash, grid, grid-dots, ticks, pill-hover, button) were decoration; use tokens instead.",+ ).toEqual([]);+ });+ }+ if (!existsSync(GALLERY_DIR)) {+ it.skip("in the gallery — PENDING: packages/ui-gallery does not exist on this branch (#764)", () => {});+ }++ // Hooks are applied in markup; a .ts module that names one (a catalog entry) is data, not a host.+ // The web app is where the hosts live now, so its markup is checked alongside the package's.+ const markup = [...filesOf("ui"), ...filesOf("web")].filter((f) => f.name.endsWith(".tsx"));++ it("find markup to check", () => {+ expect(markup.length).toBeGreaterThan(0);+ });++ it("are applied by their hosts only (Appendix B)", () => {+ const misplaced = markup.flatMap((file) => {+ const analysis = analyzeFile(file);+ const byClass = analysis.tokens+ .filter((t) => hooks.has(t.utility))+ .flatMap((t) => {+ const component = componentOf(analysis, t);+ return component !== null && HOSTS[t.utility]!.includes(component)+ ? []+ : [`${file.id}:${t.line} ${t.utility} in ${component ?? "module scope"}`];+ });+ // The icon renderers write `ui-icon-decor` for a call site that passes `decor`, so the+ // call site is where the hook is applied: its enclosing component must be a host.+ const byProp = analysis.elements+ .filter((e) => ICON_RENDERERS.has(e.tag) && e.attributes.has("decor"))+ .flatMap((e) =>+ e.component !== null && HOSTS["ui-icon-decor"]!.includes(e.component)+ ? []+ : [`${file.id}:${e.line} decor on <${e.tag}> in ${e.component ?? "module scope"}`],+ );+ return [...byClass, ...byProp];+ });+ expect(+ misplaced,+ "Each hook belongs to the components K-redesign Appendix B names (see HOSTS). A stand-in " ++ "takes the name of the component it imitates; anything else uses tokens, not the hook.",+ ).toEqual([]);+ });++ it("carry the markup their recipes select on", () => {+ const broken = markup.flatMap((file) =>+ analyzeFile(file).elements.flatMap((element) => {+ const names = new Set(element.classes.map((t) => t.utility));+ const at = `${file.id}:${element.line} <${element.tag}>`;+ const problems: string[] = [];+ const live = element.attributes.get("data-live");+ if (names.has("ui-live") && live !== null && !LIVE_SIGNALS.has(String(live))) {+ problems.push(`${at} .ui-live needs data-live="dot|caret|spinner", has ${String(live)}`);+ }+ const level = element.attributes.get("aria-level");+ if (names.has("ui-display") && element.intrinsic && element.tag !== "h1" && level !== "1") {+ problems.push(`${at} .ui-display belongs on an h1`);+ }+ if (names.has("ui-frame")) {+ for (const { slot } of childSlots(element)) {+ if (!FRAME_SLOTS.has(slot)) {+ problems.push(`${at} .ui-frame slot "${slot}" is not head, body, foot or pane`);+ }+ }+ }+ if (names.has("ui-shell")) {+ for (const { slot } of childSlots(element)) {+ if (!SHELL_SLOTS.has(slot)) {+ problems.push(`${at} .ui-shell slot "${slot}" is not nav, main or dock`);+ }+ }+ }+ if (names.has("ui-field")) {+ for (const { slot } of childSlots(element)) {+ if (!FIELD_SLOTS.has(slot)) {+ problems.push(`${at} .ui-field slot "${slot}" is not label, control or hint`);+ }+ }+ }+ const role = element.attributes.get("data-role");+ if (names.has("ui-icon-decor") && typeof role === "string" && !ICON_ROLES.has(role)) {+ problems.push(`${at} .ui-icon-decor data-role="${role}" is not nav|group|menu|empty`);+ }+ // An activity row names its kind and its state as literals the recipes select on; a+ // slot is a literal too, and only the three the recipes style (the slots are found+ // anywhere inside the row, so every literal `data-slot` under it is checked by name).+ if (names.has("ui-activity")) {+ const kind = element.attributes.get("data-kind");+ if (kind !== null && (typeof kind !== "string" || !ACTIVITY_KINDS.has(kind))) {+ problems.push(+ `${at} .ui-activity needs data-kind="thinking|tool", has ${String(kind)}`,+ );+ }+ const state = element.attributes.get("data-state");+ if (state !== null && (typeof state !== "string" || !ACTIVITY_STATES.has(state))) {+ problems.push(+ `${at} .ui-activity needs data-state="running|done|error", has ${String(state)}`,+ );+ }+ for (const { slot } of childSlots(element)) {+ if (!ACTIVITY_SLOTS.has(slot)) {+ problems.push(`${at} .ui-activity slot "${slot}" is not label, detail or progress`);+ }+ }+ }+ // A notice names its tone as a literal the recipes select on, and its slots are the four.+ if (names.has("ui-notice")) {+ const tone = element.attributes.get("data-tone");+ if (tone !== null && (typeof tone !== "string" || !NOTICE_TONES.has(tone))) {+ problems.push(+ `${at} .ui-notice needs data-tone="info|success|warning|danger|neutral", has ${String(tone)}`,+ );+ }+ for (const { slot } of childSlots(element)) {+ if (!NOTICE_SLOTS.has(slot)) {+ problems.push(`${at} .ui-notice slot "${slot}" is not icon, title, body or actions`);+ }+ }+ }+ // A chart's parts are written wherever a mark is drawn, inside the frame's svg or by a+ // component that renders into it: every literal `data-part` is one the recipes style.+ const part = element.attributes.get("data-part");+ if (typeof part === "string" && !CHART_PARTS.has(part)) {+ problems.push(`${at} data-part="${part}" is not grid|axis|series|area|bar|point|label`);+ }+ // Tree rows are written by the host, wherever it renders them: every literal depth and+ // last mark in the package must be what the recipes select on.+ const depth = element.attributes.get("data-depth");+ if (typeof depth === "string" && !TREE_DEPTH.test(depth)) {+ problems.push(`${at} data-depth="${depth}" is not a level from 0 to 8`);+ }+ const last = element.attributes.get("data-last");+ if (typeof last === "string" && last !== "true") {+ problems.push(`${at} data-last="${last}" — the last row of a level carries "true"`);+ }+ const branch = element.attributes.get("data-branch");+ if (branch !== undefined && branch !== true && branch !== null && branch !== "true") {+ problems.push(`${at} data-branch="${String(branch)}" — a branch carries the bare flag`);+ }+ if (branch !== undefined && depth === undefined) {+ problems.push(`${at} a branch carries the data-depth of the rows it holds`);+ }+ return problems;+ }),+ );+ expect(broken).toEqual([]);+ });++ it("name only hosts that exist", () => {+ const declared = new Set(+ markup.flatMap((file) => analyzeFile(file).components.map((c) => c.name)),+ );+ const missing = Object.entries(HOSTS).flatMap(([hook, hosts]) =>+ hosts.filter((host) => !declared.has(host)).map((host) => `${hook}: ${host}`),+ );+ expect(missing, "A host no scanned file declares is a stale entry: remove it.").toEqual([]);+ });+});++describe("the hook checks, on known shapes", () => {+ const file = (rel: string, text: string): SourceFile => ({+ root: "ui",+ rel,+ id: `packages/ui/src/${rel}`,+ path: `/virtual/${rel}`,+ name: rel.slice(rel.lastIndexOf("/") + 1),+ text,+ });++ it("find hook classes in markup and selectors, and nothing that only looks like one", () => {+ expect(+ hookNames(+ file(+ "a.tsx",+ [+ 'const A = () => <div className="ui-wash flex" />;',+ 'const font = "ui-monospace, SFMono-Regular";',+ "// a comment naming ui-ticks is not a class",+ ].join("\n"),+ ),+ ).map((f) => f.name),+ ).toEqual(["ui-wash"]);+ expect(+ hookNames(+ file("t.css", "@layer ui-theme {\n :root .ui-grid.ui-grid-dots { --ui-canvas: #000; }\n}"),+ ).map((f) => f.name),+ ).toEqual(["ui-grid", "ui-grid-dots"]);+ });++ it("name the innermost component a hook is written in", () => {+ const analysis = analyzeFile(+ file(+ "b.tsx",+ [+ "export function Composer() {",+ ' const Card = () => <div className="ui-glass" />;',+ ' return <span className="ui-live" data-live="caret" />;',+ "}",+ 'const LOOSE = "ui-frame";',+ ].join("\n"),+ ),+ );+ const named = (hook: string) =>+ componentOf(+ analysis,+ analysis.tokens.find((t) => t.utility === hook)!,+ );+ expect(named("ui-glass")).toBe("Card");+ expect(named("ui-live")).toBe("Composer");+ expect(named("ui-frame")).toBeNull();+ });++ it("read a tree's rows and a field's slots as the recipes do", () => {+ const analysis = analyzeFile(+ file(+ "c.tsx",+ [+ "export function TreePane() {",+ " return (",+ ' <ul className="ui-tree">',+ ' <li data-depth="0">root</li>',+ ' <div data-branch data-depth="1">',+ ' <li data-depth="1" data-last="true">leaf</li>',+ " </div>",+ " </ul>",+ " );",+ "}",+ "export function Field() {",+ " return (",+ ' <div className="ui-field">',+ ' <span data-slot="label">Name</span>',+ ' <div data-slot="control" />',+ " </div>",+ " );",+ "}",+ ].join("\n"),+ ),+ );+ const tree = analysis.elements.find((e) => e.classes.some((t) => t.utility === "ui-tree"))!;+ expect(childSlots(tree)).toEqual([]);+ const rows = analysis.elements.filter((e) => e.attributes.has("data-depth"));+ const marks = rows.map((e) => [e.attributes.get("data-depth"), e.attributes.get("data-last")]);+ expect(marks).toEqual([+ ["0", undefined],+ ["1", undefined],+ ["1", "true"],+ ]);+ expect(rows[1]!.attributes.get("data-branch")).toBe(true);+ const field = analysis.elements.find((e) => e.classes.some((t) => t.utility === "ui-field"))!;+ expect(childSlots(field).map((s) => s.slot)).toEqual(["label", "control"]);+ });+});diff --git a/packages/ui/test/no-app-strings.test.ts b/packages/ui/test/no-app-strings.test.tsnew file mode 100644index 00000000..82f5ee20--- /dev/null+++ b/packages/ui/test/no-app-strings.test.ts@@ -0,0 +1,120 @@+/**+ * The package never reaches for the web app's dictionaries (A-architecture §3.15).+ *+ * Copy is the caller's: a title, a label, an empty-state sentence arrive as props, and only the+ * handful of accessibility strings a primitive needs when a caller forgets come from the package's+ * own `UiStrings` defaults. The failure this guards is quiet — importing `S` from the web app+ * compiles, renders the right words in the app, and breaks only in the gallery and the tests, where+ * nobody has set the active dictionary — so it is parsed rather than remembered.+ *+ * Three shapes are refused anywhere under packages/ui/src: an import or re-export (static, dynamic+ * or `require`) whose specifier resolves outside packages/ui — which is how `../../web/src/lib/strings`+ * would arrive — or names the web package; a specifier ending in the web's dictionary modules+ * (`lib/strings`, `strings-en`); and a member access on an identifier `S`, the web's dictionary+ * binding, whatever it was imported from.+ */+import { dirname, resolve, sep } from "node:path";+import ts from "typescript";+import { describe, expect, it } from "vitest";+import { scanSourceRoots, unscannedRoots } from "../src/testing";+import { PACKAGE_DIR, REPO_ROOT, SRC_DIR } from "./helpers/paths";++const APP_DICTIONARY = /(?:^|\/)(?:lib\/strings|strings-en)(?:\.tsx?)?$/;+const APP_PACKAGE = /^@prismshadow\/penguin-web(?:\/|$)/;++/** Every refused shape in one source text, as "line: what". `path` places relative specifiers. */+function appStringReaches(path: string, text: string): string[] {+ const found: string[] = [];+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const at = (node: ts.Node) =>+ source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;++ const checkSpecifier = (node: ts.Node, specifier: string) => {+ if (APP_PACKAGE.test(specifier)) found.push(`${at(node)}: imports ${specifier}`);+ else if (APP_DICTIONARY.test(specifier)) found.push(`${at(node)}: imports ${specifier}`);+ else if (specifier.startsWith(".")) {+ const target = resolve(dirname(path), specifier);+ if (!`${target}${sep}`.startsWith(PACKAGE_DIR)) {+ found.push(`${at(node)}: imports ${specifier}, outside packages/ui`);+ }+ }+ };++ const visit = (node: ts.Node): void => {+ if (+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&+ node.moduleSpecifier !== undefined &&+ ts.isStringLiteral(node.moduleSpecifier)+ ) {+ checkSpecifier(node, node.moduleSpecifier.text);+ } else if (+ ts.isCallExpression(node) &&+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||+ (ts.isIdentifier(node.expression) && node.expression.text === "require")) &&+ node.arguments[0] !== undefined &&+ ts.isStringLiteralLike(node.arguments[0])+ ) {+ checkSpecifier(node, node.arguments[0].text);+ } else if (+ ts.isPropertyAccessExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === "S"+ ) {+ found.push(`${at(node)}: reads S.${node.name.text}`);+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return found;+}++describe("the package's copy", () => {+ const scan = scanSourceRoots(+ { ui: SRC_DIR },+ { repoRoot: REPO_ROOT, extensions: [".ts", ".tsx"] },+ );++ it("scans the package source", () => {+ expect(unscannedRoots(scan)).toEqual([]);+ });++ it("never comes from the web app's dictionaries", () => {+ const reaches = scan.files.flatMap((file) =>+ appStringReaches(file.path, file.text).map((hit) => `${file.id}:${hit}`),+ );+ expect(+ reaches,+ "Copy arrives as props; accessibility fallbacks come from the package's own UiStrings.",+ ).toEqual([]);+ });++ it("recognizes each refused shape — the check is exercised on known sources", () => {+ const probe = resolve(SRC_DIR, "components", "actions", "button", "button.tsx");+ const hits = (text: string) => appStringReaches(probe, text);+ // One report per import, however many of the shapes it matches.+ expect(hits('import { S } from "../../../../../web/src/lib/strings";')).toEqual([+ "1: imports ../../../../../web/src/lib/strings",+ ]);+ expect(hits('import { zh } from "../../../../../web/src/i18n";')).toEqual([+ "1: imports ../../../../../web/src/i18n, outside packages/ui",+ ]);+ expect(hits('export { en } from "@prismshadow/penguin-web/strings-en";')).toEqual([+ "1: imports @prismshadow/penguin-web/strings-en",+ ]);+ expect(hits('const m = await import("../lib/strings");')).toEqual([+ "1: imports ../lib/strings",+ ]);+ expect(hits("const label = S.common.close;")).toEqual(["1: reads S.common"]);+ // The package's own strings, sibling modules and npm packages are all fine.+ expect(+ hits(+ [+ 'import { useUiStrings } from "../../../strings";',+ 'import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";',+ 'import { renderToStaticMarkup } from "react-dom/server";',+ "const s = useUiStrings(); const label = s.close;",+ ].join("\n"),+ ),+ ).toEqual([]);+ });+});diff --git a/packages/ui/test/no-theme-reads.test.ts b/packages/ui/test/no-theme-reads.test.tsnew file mode 100644index 00000000..73d6cdc2--- /dev/null+++ b/packages/ui/test/no-theme-reads.test.ts@@ -0,0 +1,136 @@+/**+ * Components never branch on which theme is active (A-architecture §3, §4).+ *+ * Every theme renders the same component with the same props and the same markup; a theme differs+ * only in the values of the `--ui-*` tokens and in what its CSS does with the closed list of style+ * hooks. A component that asks for the theme id — to pick a class, swap an icon, skip a wrapper —+ * forks the component per theme, and the fork is invisible from the gallery page of any single+ * theme. So the source is parsed for the ways a theme id can be read in JS, and each is refused+ * outside the modules whose job the theme id is.+ *+ * Refused: the identifiers that carry the id (`useTheme`, `themeId`, `ThemeId`, `THEME_IDS`,+ * `DEFAULT_THEME_ID`), any string or template text naming `data-theme` (an attribute read, a+ * selector, or a `[data-theme=…]:` class variant), a JSX `data-theme` attribute, and+ * `dataset.theme`. Comments are not code and are not scanned.+ */+import ts from "typescript";+import { describe, expect, it } from "vitest";+import { scanSourceRoots, unscannedRoots } from "../src/testing";+import { REPO_ROOT, SRC_DIR } from "./helpers/paths";++/**+ * Modules whose job is the theme id, relative to src/. The contract names the ids, the boot script+ * applies them, and the test helpers read the theme files by id. Nothing a component imports.+ */+const THEME_MACHINERY: readonly string[] = [+ "tokens.ts",+ "boot.ts",+ "testing/",+ // The fonts' credits name the themes that use each face: data about the themes, not a+ // component that renders differently under one.+ "fonts/credits.ts",+];++const THEME_IDENTIFIERS = new Set([+ "useTheme",+ "themeId",+ "ThemeId",+ "THEME_IDS",+ "DEFAULT_THEME_ID",+]);++function themeReads(text: string): string[] {+ const found: string[] = [];+ const source = ts.createSourceFile(+ "probe.tsx",+ text,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );+ const report = (node: ts.Node, what: string) =>+ found.push(`${source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1}: ${what}`);++ const visit = (node: ts.Node): void => {+ if (ts.isIdentifier(node) && THEME_IDENTIFIERS.has(node.text)) {+ report(node, node.text);+ } else if (+ (ts.isStringLiteralLike(node) || ts.isTemplateLiteralToken(node)) &&+ node.text.includes("data-theme")+ ) {+ report(node, `"${node.text}"`);+ } else if (ts.isJsxAttribute(node) && node.name.getText(source) === "data-theme") {+ report(node, "data-theme attribute");+ } else if (+ ts.isPropertyAccessExpression(node) &&+ node.name.text === "theme" &&+ ts.isPropertyAccessExpression(node.expression) &&+ node.expression.name.text === "dataset"+ ) {+ report(node, "dataset.theme");+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return found;+}++describe("theme reads", () => {+ const scan = scanSourceRoots(+ { ui: SRC_DIR },+ { repoRoot: REPO_ROOT, extensions: [".ts", ".tsx"] },+ );++ it("scans the package source", () => {+ expect(unscannedRoots(scan)).toEqual([]);+ });++ it("are confined to the theme machinery", () => {+ const reads = scan.files+ .filter(+ (file) =>+ !THEME_MACHINERY.some((allowed) => file.rel === allowed || file.rel.startsWith(allowed)),+ )+ .flatMap((file) => themeReads(file.text).map((hit) => `${file.id}:${hit}`));+ expect(+ reads,+ "A component renders the same for every theme; express the difference as a token or a " ++ "declared style hook in the theme CSS instead.",+ ).toEqual([]);+ });++ it("keeps its allow-list pointing at modules that exist", () => {+ for (const allowed of THEME_MACHINERY) {+ expect(+ scan.files.some((file) => file.rel === allowed || file.rel.startsWith(allowed)),+ `${allowed} is allow-listed but no longer exists`,+ ).toBe(true);+ }+ });++ it("recognizes each refused shape — the check is exercised on known sources", () => {+ expect(themeReads("const { themeId } = useTheme();")).toEqual(["1: themeId", "1: useTheme"]);+ expect(themeReads('import type { ThemeId } from "../../tokens";')).toEqual(["1: ThemeId"]);+ expect(themeReads("const t = document.documentElement.dataset.theme;")).toEqual([+ "1: dataset.theme",+ ]);+ expect(themeReads('const t = root.getAttribute("data-theme");')).toEqual(['1: "data-theme"']);+ expect(themeReads("const c = `px-2 [[data-theme=geek]_&]:rounded-none ${x}`;")).toEqual([+ '1: "px-2 [[data-theme=geek]_&]:rounded-none "',+ ]);+ expect(themeReads('const e = <div data-theme="modern" />;')).toEqual([+ "1: data-theme attribute",+ ]);+ // Reading a token's value, a comment naming the attribute, and a prop named `theme` for+ // something else (a code block's language theme) are all fine.+ expect(+ themeReads(+ [+ "// the theme lives in data-theme on <html>; never read it here",+ 'const w = getComputedStyle(el).getPropertyValue("--ui-icon-stroke");',+ "const block = <CodeBlock theme={shikiTheme} />;",+ ].join("\n"),+ ),+ ).toEqual([]);+ });+});diff --git a/packages/ui/test/testing-helpers.test.ts b/packages/ui/test/testing-helpers.test.tsnew file mode 100644index 00000000..d8e3f96a--- /dev/null+++ b/packages/ui/test/testing-helpers.test.ts@@ -0,0 +1,306 @@+/**+ * The helpers in src/testing — exercised on known inputs, because every guard built on them would+ * pass just as happily on a parser that had stopped seeing anything. A contrast calculator that+ * returned 21 for every pair, or a theme reader that found no declarations, would turn the+ * contract and contrast suites into green no-ops.+ */+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { TOKEN_NAMES } from "../src/tokens";+import {+ BLACK,+ GRAY_STEPS,+ WHITE,+ analyzeThemeFile,+ classTokens,+ composite,+ contractProblems,+ contrastRatio,+ darkRepeats,+ filesNamed,+ findSourceFile,+ formatColor,+ markupStructure,+ modeDeclarations,+ parseColor,+ parseCssRules,+ renderStatic,+ resolveThemeValue,+ scanSourceRoots,+ selectorList,+ unscannedRoots,+} from "../src/testing";+import { REPO_ROOT, SRC_DIR } from "./helpers/paths";++describe("parseColor", () => {+ it("reads every hex length", () => {+ expect(parseColor("#fff")).toEqual(WHITE);+ expect(parseColor("#000000")).toEqual(BLACK);+ expect(parseColor("#0f08")).toEqual({ r: 0, g: 255, b: 0, a: 0x88 / 255 });+ expect(parseColor("#2563eb80")).toEqual({ r: 0x25, g: 0x63, b: 0xeb, a: 0x80 / 255 });+ expect(parseColor("#12345")).toBeNull();+ });++ it("reads rgb() in the legacy and the modern syntax", () => {+ expect(parseColor("rgba(255, 255, 255, .1)")).toEqual({ r: 255, g: 255, b: 255, a: 0.1 });+ expect(parseColor("rgb(37 99 235 / 0.12)")).toEqual({ r: 37, g: 99, b: 235, a: 0.12 });+ expect(parseColor("rgb(0 0 0 / 45%)")).toEqual({ r: 0, g: 0, b: 0, a: 0.45 });+ expect(parseColor("rgb(100% 0% 0%)")).toEqual({ r: 255, g: 0, b: 0, a: 1 });+ });++ it("reads hsl() and oklch()", () => {+ const red = parseColor("hsl(0 100% 50%)")!;+ expect([red.r, red.g, red.b].map(Math.round)).toEqual([255, 0, 0]);+ expect(formatColor(parseColor("oklch(1 0 0)")!)).toBe("#ffffff");+ expect(formatColor(parseColor("oklch(0% 0 0)")!)).toBe("#000000");+ // Tailwind v4's stock gray-500, which the installed theme.css spells in oklch.+ const gray = parseColor("oklch(55.1% 0.027 264.364)")!;+ expect(Math.abs(gray.r - 0x6a)).toBeLessThan(1.5);+ expect(Math.abs(gray.g - 0x72)).toBeLessThan(1.5);+ expect(Math.abs(gray.b - 0x82)).toBeLessThan(1.5);+ });++ it("mixes in srgb the way color-mix() does, premultiplied", () => {+ expect(formatColor(parseColor("color-mix(in srgb, #000 50%, #fff)")!)).toBe("#808080");+ expect(parseColor("color-mix(in srgb, #ff0000 30%, transparent)")).toEqual({+ r: 255,+ g: 0,+ b: 0,+ a: 0.3,+ });+ expect(parseColor("color-mix(in oklab, red, blue)")).toBeNull();+ });++ it("refuses what it cannot read instead of guessing", () => {+ expect(parseColor("var(--ui-fg)")).toBeNull();+ expect(parseColor("currentColor")).toBeNull();+ expect(parseColor("linear-gradient(red, blue)")).toBeNull();+ });+});++describe("contrastRatio", () => {+ it("matches the WCAG reference values", () => {+ expect(contrastRatio(BLACK, WHITE)).toBeCloseTo(21, 5);+ expect(contrastRatio(WHITE, WHITE)).toBeCloseTo(1, 5);+ // #767676 is the lightest gray that clears 4.5:1 on white; #777777 is the first that fails.+ expect(contrastRatio(parseColor("#767676")!, WHITE)).toBeGreaterThanOrEqual(4.5);+ expect(contrastRatio(parseColor("#777777")!, WHITE)).toBeLessThan(4.5);+ });++ it("composites a translucent foreground over the background first", () => {+ const halfBlack = parseColor("rgb(0 0 0 / 0.5)")!;+ expect(formatColor(composite(halfBlack, WHITE))).toBe("#808080");+ expect(contrastRatio(halfBlack, WHITE)).toBeCloseTo(3.98, 2);+ });++ it("refuses a translucent background, which has no single luminance", () => {+ expect(() => contrastRatio(BLACK, parseColor("rgb(255 255 255 / .5)")!)).toThrow(/opaque/);+ });+});++describe("parseCssRules", () => {+ const css = [+ "@layer ui-theme, ui-accent; /* a { comment } with braces */",+ "@layer ui-theme {",+ " :root,",+ " :root[data-theme='github'] {",+ " --ui-canvas: #fff;",+ ' --ui-font-sans: "A;B", sans-serif;',+ " --ui-shadow-raised: 0 1px 0 rgb(0 0 0 / 0.1)",+ " }",+ "}",+ ":root.dark { --ui-canvas: #000; }",+ ].join("\n");+ const rules = parseCssRules(css);++ it("finds each style rule with its enclosing at-rules and its line", () => {+ expect(rules.map((r) => [r.selector, r.atRules, r.line])).toEqual([+ [":root, :root[data-theme='github']", ["@layer ui-theme"], 3],+ [":root.dark", [], 10],+ ]);+ });++ it("reads declarations through strings, parentheses and a missing final semicolon", () => {+ expect(rules[0]!.declarations).toEqual([+ { name: "--ui-canvas", value: "#fff", line: 5 },+ { name: "--ui-font-sans", value: '"A;B", sans-serif', line: 6 },+ { name: "--ui-shadow-raised", value: "0 1px 0 rgb(0 0 0 / 0.1)", line: 7 },+ ]);+ });++ it("normalizes selector lists, including attribute quoting", () => {+ expect(selectorList(rules[0]!.selector)).toEqual([":root", ':root[data-theme="github"]']);+ expect(selectorList(":root[data-theme=geek].dark, :is(a, b)")).toEqual([+ ':root[data-theme="geek"].dark',+ ":is(a, b)",+ ]);+ });+});++describe("theme file analysis", () => {+ const grays = GRAY_STEPS.map((step) => `--color-gray-${step}: #808080;`).join("\n");+ const rule = (selector: string, body: string) => `${selector} {\n${body}\n}`;+ const complete = (value = "#123456") => TOKEN_NAMES.map((n) => `${n}: ${value};`).join("\n");+ /** The base rule carries the gray bridge; the dark rule only what it is given. */+ const modern = (+ light: string,+ dark: string,+ wrap = (s: string) => `@layer ui-theme {\n${s}\n}`,+ ) =>+ wrap(+ [+ rule(':root[data-theme="modern"]', `${light}\n${grays}`),+ rule(':root[data-theme="modern"].dark', dark),+ ].join("\n"),+ );++ it("accepts a complete file", () => {+ const analysis = analyzeThemeFile(modern(complete(), complete("#654321")), "modern");+ expect(analysis.declaresTokens).toBe(true);+ expect(analysis.isStub).toBe(false);+ expect(analysis.structure).toEqual([]);+ expect(contractProblems(analysis, "light")).toEqual([]);+ expect(contractProblems(analysis, "dark")).toEqual([]);+ expect(darkRepeats(analysis)).toEqual([]);+ expect(analysis.modes.light.size).toBe(TOKEN_NAMES.length + GRAY_STEPS.length);+ expect(analysis.modes.dark.size).toBe(TOKEN_NAMES.length);+ });++ it("completes dark from the base rule, and flags a dark value that repeats the base one", () => {+ const analysis = analyzeThemeFile(+ modern(complete(), "--ui-canvas: #000000;\n--ui-fg: #123456;\n--color-gray-50: #808080;"),+ "modern",+ );+ expect(contractProblems(analysis, "dark")).toEqual([]);+ expect(modeDeclarations(analysis, "dark").get("--ui-canvas")).toBe("#000000");+ expect(modeDeclarations(analysis, "dark").get("--ui-surface")).toBe("#123456");+ expect(darkRepeats(analysis)).toEqual(["--ui-fg: #123456", "--color-gray-50: #808080"]);+ });++ it("names a missing token, an extra one and an unknown variable per mode", () => {+ const light = complete().replace("--ui-canvas: #123456;", "--ui-bogus: #fff;");+ const analysis = analyzeThemeFile(modern(light, "--brand-thing: 1;"), "modern");+ expect(contractProblems(analysis, "light")).toEqual([+ `missing 1 of ${TOKEN_NAMES.length}: --ui-canvas`,+ "--ui-bogus is not in tokens.ts — add it to the contract or remove it",+ ]);+ // Dark mode inherits the base rule's gap and stray, and adds its own.+ expect(contractProblems(analysis, "dark")).toEqual([+ `missing 1 of ${TOKEN_NAMES.length}: --ui-canvas`,+ "--ui-bogus is not in tokens.ts — add it to the contract or remove it",+ expect.stringMatching(/^--brand-thing is neither a contract token nor a bridged/),+ ]);+ });++ it("flags a dangling token reference and an incomplete gray bridge", () => {+ const light = complete().replace("--ui-fg: #123456;", "--ui-fg: var(--ui-ink);");+ const css = modern(light, complete()).replace("--color-gray-500: #808080;", "");+ const analysis = analyzeThemeFile(css, "modern");+ expect(contractProblems(analysis, "light")).toEqual([+ "--ui-fg reads --ui-ink, which is not a contract token",+ "the gray bridge is incomplete — re-point --color-gray-500",+ ]);+ });++ it("flags tokens outside the canonical rules, outside the layer, and declared twice", () => {+ const wrongSelector = analyzeThemeFile(+ `@layer ui-theme { [data-theme="modern"] { --ui-canvas: #fff; } }`,+ "modern",+ );+ expect(wrongSelector.structure).toEqual([+ expect.stringContaining("declares --ui-canvas — tokens belong in the canonical rules"),+ ]);+ const unlayered = analyzeThemeFile(+ modern(complete(), complete(), (s) => s),+ "modern",+ );+ expect(unlayered.structure).toEqual([+ expect.stringContaining("the light rule sits in top level"),+ expect.stringContaining("the dark rule sits in top level"),+ ]);+ const twice = analyzeThemeFile(+ modern(`${complete()}\n--ui-canvas: #fff;`, complete()),+ "modern",+ );+ expect(twice.structure).toEqual([+ expect.stringMatching(/--ui-canvas is declared again for light \(first at line \d+\)/),+ ]);+ });++ it("gives the default theme its attribute-less selectors and no gray-bridge duty", () => {+ const github = analyzeThemeFile(+ `@layer ui-theme {\n:root, :root[data-theme="github"] {\n${complete()}\n}\n:root.dark, :root[data-theme="github"].dark {\n${complete()}\n}\n}`,+ "github",+ );+ expect(github.structure).toEqual([]);+ expect(contractProblems(github, "dark")).toEqual([]);+ });++ it("tells a stub from a file whose tokens were deleted", () => {+ expect(analyzeThemeFile("/** Stub: filled later. */", "geek").isStub).toBe(true);+ expect(analyzeThemeFile("/** Console. */\n@layer ui-theme {}", "geek").isStub).toBe(false);+ });++ it("resolves var() through the cascade the selectors produce", () => {+ const github = analyzeThemeFile(+ `@layer ui-theme {+ :root, :root[data-theme="github"] { --color-gray-900: #101828; --ui-fg: var(--color-gray-900); --ui-line: var(--ui-missing, #d1d5dc); }+ :root.dark, :root[data-theme="github"].dark { --color-gray-900: #0d0d0d; }+ }`,+ "github",+ );+ const modernTheme = analyzeThemeFile(+ `@layer ui-theme { :root[data-theme="modern"] { --ui-surface: var(--color-gray-900); } }`,+ "modern",+ );+ // A dark value this theme leaves alone falls back to its own light rule's declaration…+ expect(resolveThemeValue("--ui-fg", "dark", github, github)).toBe("#0d0d0d");+ // …with fallbacks honoured, and the default theme's rules reachable from any other theme.+ expect(resolveThemeValue("--ui-line", "light", github, github)).toBe("#d1d5dc");+ expect(resolveThemeValue("--ui-surface", "light", modernTheme, github)).toBe("#101828");+ expect(resolveThemeValue("--ui-canvas", "light", modernTheme, github)).toBeNull();+ const cycle = analyzeThemeFile(+ `@layer ui-theme { :root { --ui-fg: var(--ui-fg-muted); --ui-fg-muted: var(--ui-fg); } }`,+ "github",+ );+ expect(resolveThemeValue("--ui-fg", "light", cycle, cycle)).toBeNull();+ });+});++describe("scanSourceRoots", () => {+ const scan = scanSourceRoots(+ { ui: SRC_DIR, gone: join(SRC_DIR, "no-such-directory") },+ { repoRoot: REPO_ROOT },+ );++ it("reads a real root with repo-relative, forward-slash ids", () => {+ const tokens = findSourceFile(scan, "packages/ui/src/tokens.ts");+ expect(tokens).toBeDefined();+ expect(tokens!.root).toBe("ui");+ expect(tokens!.rel).toBe("tokens.ts");+ expect(tokens!.text).toContain("export const TOKEN_NAMES");+ expect(scan.files.every((file) => !file.id.includes("\\"))).toBe(true);+ expect(filesNamed(scan, "tokens.ts").map((file) => file.id)).toEqual([+ "packages/ui/src/tokens.ts",+ ]);+ });++ it("reports a root that yielded nothing instead of passing over it", () => {+ expect(scan.roots.find((root) => root.name === "ui")!.files).toBeGreaterThan(0);+ expect(unscannedRoots(scan)).toEqual([+ `gone (${join(SRC_DIR, "no-such-directory")}): directory does not exist`,+ ]);+ });+});++describe("static render helpers", () => {+ it("renders markup and separates structure from styling", () => {+ const html = renderStatic(+ createElement("button", { className: "px-2 rounded-md", style: { color: "red" } }, "Go"),+ );+ expect(html).toBe('<button class="px-2 rounded-md" style="color:red">Go</button>');+ expect(markupStructure(html)).toBe("<button>Go</button>");+ expect(classTokens(html)).toEqual(["px-2", "rounded-md"]);+ });+});diff --git a/packages/ui/test/token-contract.test.ts b/packages/ui/test/token-contract.test.tsnew file mode 100644index 00000000..107df650--- /dev/null+++ b/packages/ui/test/token-contract.test.ts@@ -0,0 +1,796 @@+/**+ * The token contract (src/tokens.ts): every theme × mode defines every name — the base rule plus+ * that mode's own, the dark rule declaring only what dark changes — and nothing else is a token.+ *+ * Components read tokens by name and never ask which theme is active, so a name one theme leaves+ * out does not fail loudly anywhere — the property is simply unset, the utility that reads it+ * computes to its initial value, and a surface turns transparent or a label falls back to the+ * browser's serif in that one theme and mode only. The theme files are parsed here and diffed+ * against the contract so that gap is a named test failure instead of a screenshot someone has to+ * notice.+ *+ * A theme file that does not exist yet, or is still the skeleton's stub (its header says `Stub:`+ * and it declares no `--ui-*` property), is reported as a skipped, named case — never as a pass.+ * The moment a file declares a single token, the whole contract applies to it.+ */+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import {+ BUNDLED_FONT_FAMILIES,+ FONT_CJK_OPTIONS,+ FONT_LATIN_OPTIONS,+ SYSTEM_FONT,+ THEME_FONTS,+} from "../src/boot";+import {+ ACCENT_PRESETS,+ DEFAULT_THEME_ID,+ THEME_ACCENT_PRESETS,+ THEME_IDS,+ THEME_MODES,+ THEME_OWN_ACCENTS,+ TOKEN_GROUPS,+ TOKEN_NAMES,+} from "../src/tokens";+import type { ThemeId } from "../src/tokens";+import {+ accentProblems,+ analyzeFile,+ analyzeThemeFile,+ contractProblems,+ darkRepeats,+ matchesPolicyPath,+ parseCssRules,+ scanSourceRoots,+ stripCssComments,+ unscannedRoots,+} from "../src/testing";+import type { SourceFile, ThemeFileAnalysis } from "../src/testing";+import { REPO_ROOT, SRC_DIR, WEB_DIR } from "./helpers/paths";++type ThemeState =+ | { id: ThemeId; file: string; status: "filled"; analysis: ThemeFileAnalysis }+ | { id: ThemeId; file: string; status: "pending"; reason: string };++function themeState(id: ThemeId): ThemeState {+ const file = `src/themes/${id}.css`;+ const path = join(SRC_DIR, "themes", `${id}.css`);+ if (!existsSync(path)) {+ return { id, file, status: "pending", reason: "the file does not exist yet" };+ }+ const analysis = analyzeThemeFile(readFileSync(path, "utf8"), id);+ if (analysis.isStub) {+ return {+ id,+ file,+ status: "pending",+ reason: "still the skeleton's stub (no --ui-* declared)",+ };+ }+ return { id, file, status: "filled", analysis };+}++const THEMES = THEME_IDS.map(themeState);+const read = (rel: string) => readFileSync(join(SRC_DIR, rel), "utf8");++describe("the contract itself", () => {+ it("lists each name once, every one a --ui-* custom property", () => {+ expect(TOKEN_NAMES.length).toBeGreaterThan(0);+ expect(new Set(TOKEN_NAMES).size).toBe(TOKEN_NAMES.length);+ expect(TOKEN_NAMES.filter((name) => !/^--ui-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))).toEqual([]);+ });++ it("flattens its groups in order, with no empty group", () => {+ expect(TOKEN_GROUPS.flatMap((group) => group.names)).toEqual(TOKEN_NAMES);+ expect(TOKEN_GROUPS.map((group) => group.names.length).filter((n: number) => n === 0)).toEqual(+ [],+ );+ expect(new Set(TOKEN_GROUPS.map((group) => group.id)).size).toBe(TOKEN_GROUPS.length);+ });+});++describe("theme files", () => {+ it("exist for the default theme, which every other theme's cascade falls back on", () => {+ // Skipping a stub is for themes still being written; the default file's absence would leave+ // every <html> with no tokens at all.+ expect(existsSync(join(SRC_DIR, "themes", `${DEFAULT_THEME_ID}.css`))).toBe(true);+ });++ for (const theme of THEMES) {+ if (theme.status === "pending") {+ it.skip(`${theme.file} — PENDING, contract not checked: ${theme.reason}`, () => {});+ continue;+ }+ const { analysis } = theme;++ describe(theme.file, () => {+ it("declares its tokens in the two canonical rules, inside @layer ui-theme, once each", () => {+ expect(analysis.structure).toEqual([]);+ });++ for (const mode of THEME_MODES) {+ const rules = mode === "light" ? "the base rule" : "the base rule plus the dark rule";+ it(`defines every contract name in ${mode} mode (${rules}), and nothing outside the contract`, () => {+ expect(+ contractProblems(analysis, mode),+ `${theme.file} (${mode}: ${rules}) must declare exactly the names in tokens.ts`,+ ).toEqual([]);+ });+ }++ it("declares in its dark rule only what dark changes", () => {+ // `:root.dark` also matches the base rule, so a dark declaration equal to the base one is a+ // second copy of that value: the mode-independent groups (shape, type, density, motion,+ // icons) live once, in the base rule (user decision, 2026-09-18).+ expect(+ darkRepeats(analysis),+ `${theme.file}: the dark rule repeats these base values — drop them from it`,+ ).toEqual([]);+ });++ it("declares the accent presets tokens.ts lists for it, each setting the six accent names", () => {+ // A preset is the one rule outside the canonical two that may set a token: the six accent+ // names, on the theme's own root, in `@layer ui-accent`; a dark rule lifts what dark+ // changes. The ids and their order are the picker's, so tokens.ts and the file agree.+ expect(accentProblems(analysis, ACCENT_PRESETS[theme.id])).toEqual([]);+ });+ });+ }+});++describe("the accent presets, per theme (2026-09-19)", () => {+ // Each theme lists its own presets and values (user decision): Primer the five ids and values+ // the Web App has always had, so it moves no pixel; Frost warm and muted; Console terminal+ // hues. A theme's rules match only its own root, so a stored preset another theme lists paints+ // nothing under it and comes back when that theme returns.+ const PRIMER_TODAY: Readonly<Record<string, Readonly<Record<string, string>>>> = {+ blue: {+ "--ui-accent": "#2563eb",+ "--ui-accent-hover": "#1d4ed8",+ "--ui-accent-active": "#1e40af",+ "--ui-accent-fg": "#ffffff",+ "--ui-accent-muted": "rgb(37 99 235 / 0.12)",+ "--ui-accent-line": "rgb(37 99 235 / 0.5)",+ },+ green: {+ "--ui-accent": "#15803d",+ "--ui-accent-hover": "#166534",+ "--ui-accent-active": "#14532d",+ "--ui-accent-fg": "#ffffff",+ "--ui-accent-muted": "rgb(21 128 61 / 0.12)",+ "--ui-accent-line": "rgb(21 128 61 / 0.5)",+ },+ violet: {+ "--ui-accent": "#7c3aed",+ "--ui-accent-hover": "#6d28d9",+ "--ui-accent-active": "#5b21b6",+ "--ui-accent-fg": "#ffffff",+ "--ui-accent-muted": "rgb(124 58 237 / 0.12)",+ "--ui-accent-line": "rgb(124 58 237 / 0.5)",+ },+ rose: {+ "--ui-accent": "#be123c",+ "--ui-accent-hover": "#9f1239",+ "--ui-accent-active": "#881337",+ "--ui-accent-fg": "#ffffff",+ "--ui-accent-muted": "rgb(190 18 60 / 0.12)",+ "--ui-accent-line": "rgb(190 18 60 / 0.5)",+ },+ amber: {+ "--ui-accent": "#b45309",+ "--ui-accent-hover": "#92400e",+ "--ui-accent-active": "#78350f",+ "--ui-accent-fg": "#ffffff",+ "--ui-accent-muted": "rgb(180 83 9 / 0.12)",+ "--ui-accent-line": "rgb(180 83 9 / 0.5)",+ },+ };++ /**+ * The one dark lift Primer carries (2026-09-29): rose-700 was a 3:1 mark only on the old+ * pure-black dark; on the lifted surfaces dark takes rose-600, with the 700 / 800 steps as+ * hover and active and the same white label. Light stays byte for byte.+ */+ const PRIMER_DARK_LIFTS: Readonly<Record<string, Readonly<Record<string, string>>>> = {+ rose: {+ "--ui-accent": "#e11d48",+ "--ui-accent-hover": "#be123c",+ "--ui-accent-active": "#9f1239",+ "--ui-accent-muted": "rgb(225 29 72 / 0.12)",+ "--ui-accent-line": "rgb(225 29 72 / 0.5)",+ },+ };++ it("keeps Primer's five ids and light values byte for byte, and lifts only rose in dark", () => {+ const primer = THEMES.find((theme) => theme.id === DEFAULT_THEME_ID);+ if (primer === undefined || primer.status !== "filled") throw new Error("Primer is filled");+ expect([...THEME_ACCENT_PRESETS.github]).toEqual(Object.keys(PRIMER_TODAY));+ for (const [id, values] of Object.entries(PRIMER_TODAY)) {+ const rules = primer.analysis.accents.get(id);+ expect(rules, id).toBeDefined();+ expect(Object.fromEntries(rules!.light), id).toEqual(values);+ expect(Object.fromEntries(rules!.dark), `${id} in dark`).toEqual(PRIMER_DARK_LIFTS[id] ?? {});+ }+ });++ it("gives every theme its own list (Console's has six), with no id shared between two themes", () => {+ const all = THEME_IDS.flatMap((id) => THEME_ACCENT_PRESETS[id]);+ expect(all.length).toBe(new Set(all).size);+ // Console's own accent went black and white (2026-09-30); the orange it had is now its first+ // preset, so its list is one longer.+ const listed: Readonly<Record<ThemeId, number>> = { github: 5, modern: 5, geek: 6 };+ for (const id of THEME_IDS) expect(THEME_ACCENT_PRESETS[id].length, id).toBe(listed[id]);+ expect(THEME_ACCENT_PRESETS.geek[0]).toBe("orange");+ });++ it("spells each theme's own accent (the neutral choice) in tokens.ts as the CSS does", () => {+ for (const theme of THEMES) {+ if (theme.status !== "filled") continue;+ for (const mode of THEME_MODES) {+ expect(theme.analysis.modes[mode].get("--ui-accent"), `${theme.id} ${mode}`).toBe(+ THEME_OWN_ACCENTS[theme.id][mode],+ );+ }+ }+ });++ it("no longer lives in theme.css, and theme.css still declares the ui-accent layer after ui-theme", () => {+ const sheet = read("theme.css");+ const presets = parseCssRules(sheet).filter((rule) => /data-accent=/.test(rule.selector));+ expect(presets.map((rule) => `${rule.line}: ${rule.selector}`)).toEqual([]);+ expect(stripCssComments(sheet)).toMatch(/@layer ui-theme, ui-accent, ui-font;/);+ });++ it("is one value per mode in Frost and Console: the family derives from --ui-accent", () => {+ // The owner asked for less redundancy in the switching code (2026-09-29): a preset no longer+ // restates hover, active, wash and line — the theme derives them — and keeps the theme's+ // label ink for the mode. Primer's presets stay literal (the check above pins them).+ for (const theme of THEMES) {+ if (theme.status !== "filled" || theme.id === DEFAULT_THEME_ID) continue;+ for (const [id, rules] of theme.analysis.accents) {+ expect([...rules.light.keys()], `${theme.id} ${id} light`).toEqual(["--ui-accent"]);+ // A dark rule lifts the accent and nothing else; a preset that holds across modes+ // (Console's orange takes black ink in dark) has none.+ expect(["", "--ui-accent"], `${theme.id} ${id} dark`).toContain(+ [...rules.dark.keys()].join(","),+ );+ }+ for (const mode of THEME_MODES) {+ const values = theme.analysis.modes[mode];+ for (const name of [+ "--ui-accent-hover",+ "--ui-accent-active",+ "--ui-accent-muted",+ "--ui-accent-line",+ ]) {+ expect(values.get(name), `${theme.id} ${mode} ${name}`).toMatch(/var\(--ui-accent\)/);+ }+ }+ }+ });+});++describe("the de-slop revision of the contract (K-redesign §2.5)", () => {+ it("adds the control radius and the outer rhythm steps, and drops the glass highlight", () => {+ // 186 names in W0, less the inset glow line glass drew, plus three: 188 (the count itself is+ // held by the theme-identities revision below, which added to it).+ for (const name of ["--ui-radius-control", "--ui-stack-0", "--ui-stack-4"]) {+ expect(TOKEN_NAMES).toContain(name);+ }+ expect(TOKEN_NAMES.includes("--ui-glass-highlight" as never)).toBe(false);+ });++ it("has no second name for the neutral fill's label", () => {+ // `--ui-fg-on-emphasis` said what `--ui-tone-neutral-emphasis-fg` says (user decision,+ // 2026-09-18); a component labelling the neutral emphasis fill reads the tone token.+ expect(TOKEN_NAMES.includes("--ui-fg-on-emphasis" as never)).toBe(false);+ expect(TOKEN_NAMES).toContain("--ui-tone-neutral-emphasis-fg");+ });++ it("bridges the control radius, so a pressable control reads it as rounded-control", () => {+ // `@theme inline { … }` is a block with no selector, which the CSS reader does not file, so the+ // bridge line is matched in the comment-stripped sheet.+ const sheet = stripCssComments(readFileSync(join(SRC_DIR, "theme.css"), "utf8"));+ expect(sheet).toMatch(/@theme inline\s*\{[^}]*--radius-control:\s*var\(--ui-radius-control\);/);+ });+});++describe("the theme-identities revision of the contract (2026-09-19)", () => {+ // Nothing about size is shared between themes any more: each sets its own space unit, its own+ // rungs and its own control padding, and the chrome and reading faces are two names. The+ // presence / reveal / layout motion reads tokens of its own, and the app window has a hook with+ // tokens behind it. 188 + 1 (the space unit) + 1 (the chrome face) + 9 (the shell) + 11 (motion)+ // = 210; the structure revision below adds 5 more.+ it("adds the space unit, the chrome face, the shell group and the motion names", () => {+ for (const name of [+ "--ui-space-unit",+ "--ui-font-ui",+ "--ui-shell-field",+ "--ui-shell-wash-1",+ "--ui-shell-wash-2",+ "--ui-shell-nav-bg",+ "--ui-shell-main-bg",+ "--ui-shell-line",+ "--ui-shell-gap",+ "--ui-shell-radius",+ "--ui-shell-shadow",+ "--ui-dur-enter",+ "--ui-dur-exit",+ "--ui-ease-enter",+ "--ui-ease-exit",+ "--ui-enter-shift",+ "--ui-enter-scale",+ "--ui-enter-blur",+ "--ui-dur-reveal",+ "--ui-reveal-blur",+ "--ui-dur-layout",+ "--ui-ease-layout",+ ]) {+ expect(TOKEN_NAMES).toContain(name);+ }+ expect(TOKEN_GROUPS.find((group) => group.id === "shell")?.names.length).toBe(9);+ // 215, plus the integration round's four (the emphasis ink and the switch's three), plus+ // the chart round's nine (two more series, the reference line, six geometry names), plus+ // the bar outline's three, plus the knob's hairline edge (2026-09-30).+ expect(TOKEN_NAMES.length).toBe(232);+ });++ it("adds the structure group behind the tree and field hooks (round 2)", () => {+ // A host indents a tree row by the inset and the indent per level, so a theme's connector+ // rules land on the columns the host used; a field's label column and gap are the theme's.+ // 210 + 5 = 215.+ const structure = TOKEN_GROUPS.find((group) => group.id === "structure");+ expect(structure?.names).toEqual([+ "--ui-tree-inset",+ "--ui-tree-indent",+ "--ui-tree-guide",+ "--ui-field-label-w",+ "--ui-field-gap",+ ]);+ const primer = THEMES.find((theme) => theme.id === DEFAULT_THEME_ID);+ if (primer === undefined || primer.status !== "filled") throw new Error("Primer is filled");+ // Today's file tree: a 0.5rem inset and 0.875rem per level.+ expect(primer.analysis.modes.light.get("--ui-tree-inset")).toBe("0.5rem");+ expect(primer.analysis.modes.light.get("--ui-tree-indent")).toBe("0.875rem");+ });++ it("bridges the space unit, the chrome face and the body rung to Tailwind and body", () => {+ // With `--spacing` inlined, every `h-8` / `px-2` / `gap-3` / `size-4` / `w-64` a component+ // spells computes from the theme's unit; with `--text-sm` inlined, its size and line-height are+ // the theme's body rung. The chrome face reaches everything through `body`, and a reading+ // surface opts into `font-sans`.+ const sheet = stripCssComments(readFileSync(join(SRC_DIR, "theme.css"), "utf8"));+ const bridge = /@theme inline\s*\{([^}]*)\}/.exec(sheet)?.[1] ?? "";+ expect(bridge).toMatch(/--spacing:\s*var\(--ui-space-unit\);/);+ expect(bridge).toMatch(/--font-ui:\s*var\(--ui-font-ui\);/);+ expect(bridge).toMatch(/--font-sans:\s*var\(--ui-font-sans\);/);+ expect(bridge).toMatch(/--text-sm:\s*var\(--ui-text-body-size\);/);+ expect(bridge).toMatch(/--text-sm--line-height:\s*var\(--ui-text-body-lh\);/);+ expect(bridge).toMatch(/--text-xs:\s*var\(--ui-text-small-size\);/);+ expect(sheet).toMatch(/\bbody\s*\{[^}]*font-family:\s*var\(--ui-font-ui\);/);+ });++ it("keeps Primer at today's rendering: Tailwind's stock unit and rungs, one face, no field", () => {+ const primer = THEMES.find((theme) => theme.id === DEFAULT_THEME_ID);+ if (primer === undefined || primer.status !== "filled") throw new Error("Primer is filled");+ const light = primer.analysis.modes.light;+ expect(light.get("--ui-space-unit")).toBe("0.25rem");+ expect(light.get("--ui-text-body-size")).toBe("0.875rem");+ expect(light.get("--ui-text-body-lh")).toBe("calc(1.25 / 0.875)");+ expect(light.get("--ui-text-small-size")).toBe("0.75rem");+ expect(light.get("--ui-text-small-lh")).toBe("calc(1 / 0.75)");+ expect(light.get("--ui-font-ui")).toBe("var(--ui-font-sans)");+ expect(light.get("--ui-shell-field")).toBe("var(--ui-canvas)");+ expect(light.get("--ui-shell-gap")).toBe("0px");+ expect(light.get("--ui-shell-radius")).toBe("0px");+ expect(light.get("--ui-enter-scale")).toBe("1");+ expect(light.get("--ui-enter-blur")).toBe("0px");+ });++ it("gives the presence rules a token for every motion property they animate", () => {+ // The rules in theme.css read only tokens for what moves: a theme that wants no motion sets+ // zeros, one that wants steps sets a `steps()` easing. A rule that spelled a literal duration+ // or shift would move the same way in every theme.+ const sheet = stripCssComments(readFileSync(join(SRC_DIR, "theme.css"), "utf8"));+ const presence = /\[data-presence="enter"\]\s*\{([^}]*)\}/.exec(sheet)?.[1] ?? "";+ expect(presence).toMatch(/var\(--ui-dur-enter\)\s+var\(--ui-ease-enter\)/);+ const layout = /\[data-layout-motion\]\s*\{([^}]*)\}/.exec(sheet)?.[1] ?? "";+ expect(layout).toMatch(/transition-duration:\s*var\(--ui-dur-layout\)/);+ expect(layout).toMatch(/transition-timing-function:\s*var\(--ui-ease-layout\)/);+ const reveal = /\[data-reveal\]\s*\{([^}]*)\}/.exec(sheet)?.[1] ?? "";+ expect(reveal).toMatch(/var\(--ui-dur-reveal\)/);+ const animated = [+ "--ui-enter-shift",+ "--ui-enter-scale",+ "--ui-enter-blur",+ "--ui-reveal-blur",+ ];+ for (const name of animated) {+ expect(sheet, `${name} is read by a keyframe`).toContain(`var(${name})`);+ }+ // Everything stops under the gallery's switch and the system preference.+ expect(sheet).toMatch(+ /:root\[data-motion="reduced"\]\s*:is\(\[data-presence\],\s*\[data-backdrop\],\s*\[data-reveal\],\s*\.ui-live\)\s*\{\s*animation:\s*none;/,+ );+ expect(sheet).toMatch(/@media \(prefers-reduced-motion: reduce\)/);+ });+});++describe("the integration revision of the contract (2026-09-29)", () => {+ // The calm dark needs a second ink for headings; the switch needs its track and knobs named+ // so a knob can be held to 3:1 against its track; the user's font pairing needs every sans+ // stack to read the CJK face, and a layer of its own so a chosen face beats the theme's rules.+ it("adds the emphasis ink and the switch group", () => {+ expect(TOKEN_GROUPS.find((group) => group.id === "color-text")?.names).toContain(+ "--ui-fg-emphasis",+ );+ expect(TOKEN_GROUPS.find((group) => group.id === "controls")?.names).toEqual([+ "--ui-switch-track",+ "--ui-switch-knob",+ "--ui-switch-knob-on",+ "--ui-switch-knob-line",+ ]);+ for (const theme of THEMES) {+ if (theme.status !== "filled") continue;+ const light = theme.analysis.modes.light;+ // In light the emphasis ink is the body ink; the on-knob follows the accent's label.+ expect(light.get("--ui-fg-emphasis"), theme.id).toBe("var(--ui-fg)");+ expect(light.get("--ui-switch-knob-on"), theme.id).toBe("var(--ui-accent-fg)");+ }+ });++ it("keeps Primer's light ink, faces and switch as today's, and moves only its dark", () => {+ const primer = THEMES.find((theme) => theme.id === DEFAULT_THEME_ID);+ if (primer === undefined || primer.status !== "filled") throw new Error("Primer is filled");+ const light = primer.analysis.modes.light;+ expect(light.get("--ui-fg")).toBe("var(--color-gray-900)");+ expect(light.get("--ui-switch-track")).toBe("var(--color-gray-200)");+ expect(light.get("--ui-switch-knob")).toBe("#ffffff");+ // The sans stack reads the CJK face where it named the two system faces: the same list.+ expect(light.get("--ui-font-sans")).toContain("var(--ui-font-cjk)");+ expect(light.get("--ui-font-cjk")).toBe('"PingFang SC", "Microsoft YaHei"');+ // Dark lifts off pure black and calms the body ink: the ramp, not the app's #000.+ const dark = primer.analysis.modes.dark;+ expect(dark.get("--color-gray-950")).not.toBe("#000000");+ expect(dark.get("--color-gray-100")).not.toBe(light.get("--color-gray-100"));+ });++ it("resolves the font pairing in theme.css's ui-font layer, for every face the lists offer", () => {+ // Every chosen face has a rule; a Latin choice sets the reading sans (and keeps the CJK face+ // in its stack), a CJK choice sets the CJK face; no pairing rule touches the mono or the+ // chrome face directly — Console's mono chrome is its identity, not a reading preference.+ const rules = parseCssRules(read("theme.css")).filter((rule) =>+ /data-font-(?:latin|cjk)=/.test(rule.selector),+ );+ const byAttribute = (attr: string, id: string) =>+ rules.find((rule) => rule.selector === `:root[data-font-${attr}="${id}"]`);+ for (const option of FONT_LATIN_OPTIONS) {+ if (option.id === "theme") continue;+ const rule = byAttribute("latin", option.id);+ expect(rule, `data-font-latin="${option.id}"`).toBeDefined();+ expect(rule!.declarations.map((d) => d.name)).toEqual(["--ui-font-sans"]);+ expect(rule!.declarations[0]!.value).toContain("var(--ui-font-cjk)");+ }+ for (const option of FONT_CJK_OPTIONS) {+ if (option.id === "theme") continue;+ const rule = byAttribute("cjk", option.id);+ expect(rule, `data-font-cjk="${option.id}"`).toBeDefined();+ expect(rule!.declarations.map((d) => d.name)).toEqual(["--ui-font-cjk"]);+ }+ for (const rule of rules) {+ expect(rule.atRules, rule.selector).toEqual(["@layer ui-font"]);+ expect(rule.declarations.map((d) => d.name)).not.toContain("--ui-font-mono");+ expect(rule.declarations.map((d) => d.name)).not.toContain("--ui-font-ui");+ }+ // A chosen face reaches every theme: each sans stack reads the CJK face, and the chrome+ // face is the sans (Primer, Frost) or the mono (Console), never a third stack.+ for (const theme of THEMES) {+ if (theme.status !== "filled") continue;+ for (const mode of THEME_MODES) {+ const values = new Map([...theme.analysis.modes.light, ...theme.analysis.modes[mode]]);+ expect(values.get("--ui-font-sans"), `${theme.id} ${mode}`).toContain("var(--ui-font-cjk)");+ expect(["var(--ui-font-sans)", "var(--ui-font-mono)"], `${theme.id} ${mode}`).toContain(+ values.get("--ui-font-ui"),+ );+ }+ }+ });++ it("shares the eyebrow rung and the display ink in theme.css, once for every theme", () => {+ // The three eyebrow recipes were one recipe reading the h6 rung; a theme adds only its ink.+ const rules = parseCssRules(read("theme.css"));+ const eyebrow = rules.find((rule) => rule.selector === ".ui-eyebrow");+ expect(eyebrow?.atRules).toEqual(["@layer ui-theme"]);+ expect(eyebrow?.declarations.map((d) => `${d.name}: ${d.value}`)).toEqual([+ "font-family: var(--ui-h6-font)",+ "font-size: var(--ui-h6-size)",+ "line-height: var(--ui-h6-lh)",+ "font-weight: var(--ui-h6-weight)",+ "letter-spacing: var(--ui-h6-tracking)",+ "text-transform: var(--ui-h6-transform)",+ ]);+ const display = rules.find((rule) => rule.selector === ".ui-display");+ expect(display?.declarations.map((d) => `${d.name}: ${d.value}`)).toEqual([+ "color: var(--ui-fg-emphasis)",+ ]);+ for (const id of THEME_IDS) {+ const own = parseCssRules(read(`themes/${id}.css`)).filter((rule) =>+ /\.ui-eyebrow\b/.test(rule.selector),+ );+ for (const rule of own) {+ expect(+ rule.declarations.map((d) => d.name),+ `${id}: ${rule.selector}`,+ ).toEqual(["color"]);+ }+ }+ });+});++describe("the chart style tokens (round 7)", () => {+ // A chart draws with tokens the app reads once per theme: the palette in fixed roles, a+ // reference line, and the geometry. Primer's are today's charts; a curve is one of the three+ // keywords the app knows, and the geometry is written in the units the app parses.+ const chart = TOKEN_GROUPS.find((group) => group.id === "chart");++ it("names the eight series, the reference line and the six geometry values", () => {+ expect(chart?.names).toEqual([+ "--ui-chart-1",+ "--ui-chart-2",+ "--ui-chart-3",+ "--ui-chart-4",+ "--ui-chart-5",+ "--ui-chart-6",+ "--ui-chart-7",+ "--ui-chart-8",+ "--ui-chart-ref",+ "--ui-chart-cache-read",+ "--ui-chart-cache-write",+ "--ui-chart-output",+ "--ui-chart-grid",+ "--ui-chart-axis",+ "--ui-chart-bar-fill",+ "--ui-chart-bar-radius",+ "--ui-chart-line-width",+ "--ui-chart-point-radius",+ "--ui-chart-curve",+ "--ui-chart-area-opacity",+ "--ui-chart-bar-stroke",+ "--ui-chart-bar-stroke-color",+ "--ui-chart-bar-opacity",+ ]);+ });++ it("keeps Primer at today's geometry, and its palette at the steps that read on white", () => {+ // The one Primer change of the theme work (2026-09-30): amber, sky, emerald, teal and orange+ // move from their 500 steps (2.2–2.9:1 on white) to the 600 steps the app's dark series+ // already used; violet, rose and fuchsia clear 3:1 at 500 and stay.+ const primer = THEMES.find((theme) => theme.id === DEFAULT_THEME_ID);+ if (primer === undefined || primer.status !== "filled") throw new Error("Primer is filled");+ const light = primer.analysis.modes.light;+ expect(light.get("--ui-chart-1")).toBe("oklch(60.6% 0.25 292.717)"); // violet-500+ expect(light.get("--ui-chart-2")).toBe("oklch(66.6% 0.179 58.318)"); // amber-600+ expect(light.get("--ui-chart-3")).toBe("oklch(58.8% 0.158 241.966)"); // sky-600+ expect(light.get("--ui-chart-4")).toBe("oklch(64.5% 0.246 16.439)"); // rose-500+ expect(light.get("--ui-chart-5")).toBe("oklch(59.6% 0.145 163.225)"); // emerald-600+ expect(light.get("--ui-chart-6")).toBe("oklch(66.7% 0.295 322.15)"); // fuchsia-500+ expect(light.get("--ui-chart-7")).toBe("oklch(60% 0.118 184.704)"); // teal-600+ expect(light.get("--ui-chart-8")).toBe("oklch(64.6% 0.222 41.116)"); // orange-600+ expect(light.get("--ui-chart-ref")).toBe("var(--ui-chart-2)");+ expect(light.get("--ui-chart-bar-fill")).toBe("0.6");+ expect(light.get("--ui-chart-bar-radius")).toBe("0px");+ expect(light.get("--ui-chart-line-width")).toBe("2px");+ expect(light.get("--ui-chart-point-radius")).toBe("2.5px");+ expect(light.get("--ui-chart-curve")).toBe("linear");+ expect(light.get("--ui-chart-area-opacity")).toBe("0.1");+ // No outline and a solid fill: the bar as the app has always drawn it.+ expect(light.get("--ui-chart-bar-stroke")).toBe("0px");+ expect(light.get("--ui-chart-bar-stroke-color")).toBe("series");+ expect(light.get("--ui-chart-bar-opacity")).toBe("1");+ // Dark restates only what still differs from light: the timeline's emerald-400 work phase+ // and fuchsia-600.+ const dark = primer.analysis.modes.dark;+ expect(dark.get("--ui-chart-5")).toBe("oklch(76.5% 0.177 163.223)"); // emerald-400+ expect(dark.get("--ui-chart-6")).toBe("oklch(59.1% 0.293 322.896)"); // fuchsia-600+ });++ it("writes the geometry in the units the app parses, and a curve the app knows", () => {+ for (const theme of THEMES) {+ if (theme.status !== "filled") continue;+ for (const mode of THEME_MODES) {+ const values = new Map([...theme.analysis.modes.light, ...theme.analysis.modes[mode]]);+ const at = `${theme.id} ${mode}`;+ expect(values.get("--ui-chart-curve"), at).toMatch(/^(?:linear|smooth|step)$/);+ for (const name of [+ "--ui-chart-bar-fill",+ "--ui-chart-area-opacity",+ "--ui-chart-bar-opacity",+ ]) {+ expect(Number(values.get(name)), `${at} ${name}`).toBeGreaterThanOrEqual(0);+ expect(Number(values.get(name)), `${at} ${name}`).toBeLessThanOrEqual(1);+ }+ for (const name of [+ "--ui-chart-bar-radius",+ "--ui-chart-line-width",+ "--ui-chart-point-radius",+ "--ui-chart-bar-stroke",+ ]) {+ expect(values.get(name), `${at} ${name}`).toMatch(/^\d+(?:\.\d+)?px$/);+ }+ // The outline's colour is the exact keyword for the bar's own series colour, or a+ // colour the app can use as one.+ expect(values.get("--ui-chart-bar-stroke-color"), `${at} bar-stroke-color`).toMatch(+ /^(?:series|#[0-9a-f]{3,8}|(?:rgb|hsl|oklch|color-mix|var)\()/i,+ );+ }+ }+ });++ it("differs between the themes in geometry, not only in colour", () => {+ const geometry = (id: ThemeId) => {+ const theme = THEMES.find((entry) => entry.id === id);+ if (theme === undefined || theme.status !== "filled") return null;+ const light = theme.analysis.modes.light;+ return ["bar-fill", "bar-radius", "line-width", "curve"]+ .map((part) => light.get(`--ui-chart-${part}`))+ .join(" ");+ };+ const all = THEME_IDS.map(geometry).filter((value) => value !== null);+ expect(new Set(all).size).toBe(all.length);+ });+});++describe("the themes' own faces (round 6)", () => {+ // THEME_FONTS is what the Fonts page states as a theme's defaults; it must be what the theme+ // file's stacks name first — a bundled family by its declared name, or, for `System`, a stack+ // that names no bundled family at all. The pairing options name faces by the same names.+ const bundled = new Set<string>(Object.values(BUNDLED_FONT_FAMILIES));+ const firstFamily = (stack: string | undefined) =>+ (stack ?? "")+ .split(",")[0]!+ .trim()+ .replace(/^["']|["']$/g, "");+ const STACKS = { latin: "--ui-font-sans", cjk: "--ui-font-cjk", mono: "--ui-font-mono" } as const;++ it("names, for every theme, the family each stack puts first", () => {+ for (const theme of THEMES) {+ if (theme.status !== "filled") continue;+ for (const [role, token] of Object.entries(STACKS)) {+ const name = THEME_FONTS[theme.id][role as keyof typeof STACKS];+ const first = firstFamily(theme.analysis.modes.light.get(token));+ if (name === SYSTEM_FONT) {+ expect(bundled.has(first), `${theme.id} ${role}: ${first} is a bundled face`).toBe(false);+ } else {+ expect(first, `${theme.id} ${role}`).toBe(BUNDLED_FONT_FAMILIES[name]);+ }+ }+ }+ });++ it("offers the pairing's faces under the same names", () => {+ for (const option of [...FONT_LATIN_OPTIONS, ...FONT_CJK_OPTIONS]) {+ if (option.id === "theme" || option.id === "system") continue;+ expect(Object.keys(BUNDLED_FONT_FAMILIES), option.id).toContain(option.label);+ }+ });+});++describe("theme import order", () => {+ // In dark, a theme takes every token its dark rule leaves out from its own base rule. That base+ // rule ties with github.css's dark rule (`:root.dark`) on specificity and wins only by coming+ // later in the sheet, so an entry stylesheet must import github.css before the other themes:+ // the other way round, Frost and Console in dark would take Primer's dark values for those+ // tokens.+ const GALLERY = join(REPO_ROOT, "packages", "ui-gallery");+ const entries: Record<string, string> = {+ web: join(WEB_DIR, "src", "styles.css"),+ ...(existsSync(GALLERY) ? { gallery: join(GALLERY, "src", "styles.css") } : {}),+ };+ const IMPORT = /@import\s+["']@prismshadow\/penguin-ui\/themes\/([\w-]+)\.css["']/g;++ for (const [name, file] of Object.entries(entries)) {+ it(`${name}: imports every theme once, the default (${DEFAULT_THEME_ID}.css) first`, () => {+ const themes = [...stripCssComments(readFileSync(file, "utf8")).matchAll(IMPORT)].map(+ (m) => m[1],+ );+ expect(themes[0], `${file} imports its themes as ${themes.join(", ")}`).toBe(+ DEFAULT_THEME_ID,+ );+ expect([...themes].sort()).toEqual([...THEME_IDS].sort());+ });+ }+});++describe("token reads", () => {+ // A name a component or a recipe reads but no theme declares computes to nothing: a removed token+ // still read by a recipe (Frost's glass read the inset highlight) leaves the declaration invalid+ // at computed-value time, silently, in every theme. So every `--ui-*` name the source spells —+ // in stylesheets and in string literals, never in comments — must be in the contract.+ const GALLERY = join(REPO_ROOT, "packages", "ui-gallery", "src");+ const roots = {+ ui: SRC_DIR,+ web: join(WEB_DIR, "src"),+ ...(existsSync(GALLERY) ? { gallery: GALLERY } : {}),+ };+ const scan = scanSourceRoots(roots, { repoRoot: REPO_ROOT });+ const contract = new Set<string>(TOKEN_NAMES);+ const NAME = /--ui-[a-z0-9]+(?:-[a-z0-9]+)*/g;++ /**+ * The whole names in one piece of text. A name that goes on past what the pattern reads is only a+ * prefix, built at runtime or written as a wildcard — `--ui-tone-${tone}-fg`, `--ui-h${n}-size`,+ * `--ui-chart-*` — and is not judged.+ */+ const namesIn = (text: string, openEnd: boolean) =>+ [...text.matchAll(NAME)].filter((m) => {+ const end = m.index + m[0].length;+ return text[end] !== "-" && !(openEnd && end === text.length);+ });++ const spelled = (file: SourceFile): { name: string; line: number }[] => {+ if (file.name.endsWith(".css")) {+ return stripCssComments(file.text)+ .split("\n")+ .flatMap((text, i) => namesIn(text, false).map((m) => ({ name: m[0], line: i + 1 })));+ }+ return analyzeFile(file).strings.flatMap((chunk) =>+ namesIn(chunk.text, chunk.openEnd).map((m) => ({ name: m[0], line: chunk.line })),+ );+ };++ it("scans the package, the web app and the gallery when it exists, and finds reads in each", () => {+ expect(unscannedRoots(scan)).toEqual([]);+ // A name pattern or a chunk reader that stopped matching would pass the check below over nothing.+ for (const root of Object.keys(roots)) {+ const reads = scan.files.filter((file) => file.root === root).flatMap(spelled);+ expect(reads.length, `${root} spells no --ui-* name`).toBeGreaterThan(0);+ }+ });++ /**+ * Names the file spells that are not tokens. A family prefix (`startsWith("--ui-chart")`) names+ * tokens that exist; a removed or misspelt token prefixes none.+ */+ const strays = (file: SourceFile) =>+ spelled(file).filter(+ (found) =>+ !contract.has(found.name) && !TOKEN_NAMES.some((t) => t.startsWith(`${found.name}-`)),+ );++ it("reads whole names only — the check is exercised on known shapes", () => {+ const probe = (text: string) =>+ strays({+ root: "ui",+ rel: "probe.tsx",+ id: "packages/ui/src/probe.tsx",+ path: "/virtual/probe.tsx",+ name: "probe.tsx",+ text,+ }).map((found) => found.name);+ expect(+ probe(+ [+ 'const a = "var(--ui-glass-highlight)";',+ 'const b = "var(--ui-canvas)";',+ "const c = (t: string) => `var(--ui-tone-${t}-fg)`;",+ "const d = (n: number) => `var(--ui-h${n}-size)`;",+ 'const e = "chart inks read --ui-chart-* through the bridge";',+ 'const f = (name: string) => name.startsWith("--ui-chart");',+ "// --ui-comment-only is not read",+ ].join("\n"),+ ),+ ).toEqual(["--ui-glass-highlight"]);+ });++ it("name only contract tokens", () => {+ const found = scan.files+ // The test machinery spells names in its own messages.+ .filter((file) => !(file.root === "ui" && matchesPolicyPath(file.rel, ["testing/"])))+ .flatMap((file) => strays(file).map((stray) => `${file.id}:${stray.line} ${stray.name}`));+ expect(+ found,+ "Read a name tokens.ts lists, or add the name to the contract (and to every theme file).",+ ).toEqual([]);+ });+});diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.jsonnew file mode 100644index 00000000..41b37748--- /dev/null+++ b/packages/ui/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "jsx": "react-jsx",+ "useDefineForClassFields": true+ },+ "include": ["src", "test", "vitest.config.ts"]+}diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsnew file mode 100644index 00000000..53c2a75d--- /dev/null+++ b/packages/ui/vitest.config.ts@@ -0,0 +1,16 @@+/**+ * Vitest config: Node environment, no DOM — the web app's convention. Components are exercised+ * through `react-dom/server` static markup (src/testing/render.ts) and source scans; interaction+ * logic lives in pure modules that are called directly.+ */+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ environment: "node",+ include: ["test/**/*.test.ts"],+ // The guards scan every source file of the package, the web app and the gallery; on the+ // hosted Windows and macOS runners one scan can take several seconds.+ testTimeout: 30_000,+ },+});diff --git a/packages/web/e2e/background-notify.spec.mjs b/packages/web/e2e/background-notify.spec.mjsindex b53b7a9e..86a9a935 100644--- a/packages/web/e2e/background-notify.spec.mjs+++ b/packages/web/e2e/background-notify.spec.mjs@@ -58,8 +58,8 @@ test("a run_in_background completion reaches the open chat page unprompted", asy// The launched command is a normal background process: the header stats show a background// task (same registry as the promoted-past-yield path).- const detailsBtn = page.locator('button[title="Session 信息"]');- await expect(detailsBtn.locator('span[title="1 个后台任务"]')).toBeVisible({+ const detailsBtn = page.locator('button[data-tooltip="Session 信息"]');+ await expect(detailsBtn.locator('span[data-tooltip="1 个后台任务"]')).toBeVisible({timeout: 10_000,});diff --git a/packages/web/e2e/chat-tweaks.spec.mjs b/packages/web/e2e/chat-tweaks.spec.mjsindex f23f00d5..cb1ed7bb 100644--- a/packages/web/e2e/chat-tweaks.spec.mjs+++ b/packages/web/e2e/chat-tweaks.spec.mjs@@ -89,26 +89,25 @@ test("schedule form pickers and details Session-id copy", async ({ page }) => {// --- Details card Session id + copy ---// The id is selectable mono text with the copy button beside it (not inside it); the- // copied feedback is the button's own icon flipping to the check + its tooltip flipping- // to "已复制" — NO "已复制" text is rendered (#312), and the "Session id" label is untouched.+ // copied feedback is the button's own icon flipping to the check — NO text changes: no+ // "已复制" label, the tooltip keeps naming the action (#312), and "Session id" is untouched.await page.goto(`${BASE}/chat/${sessionId}`);await page.getByPlaceholder(/输入消息/).waitFor();- await page.locator('button[title="Session 信息"]').click();+ await page.locator('button[data-tooltip="Session 信息"]').click();await expect(page.getByText(sessionId, { exact: true }).first()).toBeVisible();const copyBtn = page.getByRole("button", { name: "复制 Session ID" });await copyBtn.click();expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(sessionId);- // Feedback at the button: tooltip flips while copied; the accessible name (aria-label)- // and the icon-only content stay — no transient text label anywhere.- await expect(copyBtn).toHaveAttribute("title", "已复制");+ // Feedback at the button: the tooltip, the accessible name (aria-label) and the icon-only+ // content all stay — no transient text anywhere.+ await expect(copyBtn).toHaveAttribute("data-tooltip", "复制 Session ID");await expect(copyBtn).toHaveText("");// An icon swap is silent, so the confirmation ALSO lands in a visually hidden live// region beside the button — present in the DOM (that is what a screen reader reads)// while the button itself stays icon-only, as asserted right above.await expect(page.getByText("已复制", { exact: true })).toHaveCount(1);- // …and both halves clear once the copied flash ends (1.5s).- await expect(copyBtn).toHaveAttribute("title", "复制 Session ID", { timeout: 5_000 });- await expect(page.getByText("已复制", { exact: true })).toHaveCount(0);+ // …and the announcement clears once the copied flash ends (1.5s).+ await expect(page.getByText("已复制", { exact: true })).toHaveCount(0, { timeout: 5_000 });// The section label above the id is not the feedback target — it stays "Session id".await expect(page.getByText("Session id", { exact: true })).toBeVisible();});diff --git a/packages/web/e2e/chat.spec.mjs b/packages/web/e2e/chat.spec.mjsindex f9464320..ee35703a 100644--- a/packages/web/e2e/chat.spec.mjs+++ b/packages/web/e2e/chat.spec.mjs@@ -67,7 +67,9 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })// event. Scoped to the toolbar's details trigger (the chips now double as the "Session 信息"// button at the far right): the per-reply footer reuses the same 用时 ("elapsed") label once// the turn's stats line lands.- const headerElapsed = page.locator('button[title="Session 信息"] span[title="用时"]');+ const headerElapsed = page.locator(+ 'button[data-tooltip="Session 信息"] span[data-tooltip="用时"]',+ );const elapsedBefore = await headerElapsed.textContent();await expect(headerElapsed).not.toHaveText(elapsedBefore);@@ -77,8 +79,11 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })// Keep the status dot and the live stats, but their rendered boxes must remain disjoint.await page.setViewportSize({ width: 877, height: 438 });await page.waitForTimeout(200);- const runningStatus = page.locator('span[title="运行中"]').filter({ hasText: "运行中" }).first();- const tokenTotal = page.locator('span[title="Token 累计(Token)"]');+ const runningStatus = page+ .locator('span[data-tooltip="运行中"]')+ .filter({ hasText: "运行中" })+ .first();+ const tokenTotal = page.locator('span[data-tooltip="Token 累计(Token)"]');const [runningBox, tokenBox] = await Promise.all([runningStatus.boundingBox(),tokenTotal.boundingBox(),@@ -260,7 +265,7 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })const overflowY = await timeline.evaluate((el) => getComputedStyle(el).overflowY);expect(overflowY).toBe("hidden");// Hover a timeline tool-exec segment → the matching event row highlights (cross-link).- const seg = main.getByTitle(/exec_command · 工具调用执行/).first();+ const seg = main.locator('[data-tooltip*="exec_command · 工具调用执行"]').first();await expect(seg).toBeVisible();await seg.hover();await expect(main.locator("button.bg-amber-50").first()).toBeVisible();@@ -309,10 +314,10 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })await expect(page.getByText(/Report generated/)).toBeVisible();await expect(page.getByText("1 个文件")).toBeVisible();// Card rows carry the 点击预览 ("click to preview") affordance — that distinguishes them from- // the Files panel tree rows, which also use title=<name> on their buttons.- const cardRow = page.locator('button[title="demo.html"]').filter({ hasText: "点击预览" });+ // the Files panel tree rows, which also use data-tooltip=<name> on their buttons.+ const cardRow = page.locator('button[data-tooltip="demo.html"]').filter({ hasText: "点击预览" });await expect(cardRow).toBeVisible();- await expect(page.locator('button[title="missing-report.pdf"]')).toHaveCount(0);+ await expect(page.locator('button[data-tooltip="missing-report.pdf"]')).toHaveCount(0);// Clicking the row opens the Files panel preview via the normalized relative path.await cardRow.click();await expect(page.locator("iframe")).toBeVisible();@@ -347,10 +352,11 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })await expect.poll(() => page.evaluate(() => document.documentElement.dataset.accent)).toBe("blue");+ // 大 is the old default (18px); the new default, 中, is 16px.await page.getByRole("button", { name: "大", exact: true }).click();await expect.poll(() => page.evaluate(() => document.documentElement.style.fontSize))- .toBe("20px");+ .toBe("18px");await page.keyboard.press("Escape");// --- session rename (manual title wins over the auto-generated one) ---diff --git a/packages/web/e2e/draft.spec.mjs b/packages/web/e2e/draft.spec.mjsindex bb997260..ff5d4496 100644--- a/packages/web/e2e/draft.spec.mjs+++ b/packages/web/e2e/draft.spec.mjs@@ -172,7 +172,7 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses).json();const meta = replay.messages.find((m) => m.type === "session_meta");expect(meta?.payload?.thinking_level).toBeUndefined();- await expect(page.getByTitle("思考等级:高 (high)")).toBeVisible();+ await expect(page.locator('[data-tooltip="思考等级:高 (high)"]')).toBeVisible();// On a successful send the cache clears — except the model selection, which carries over as// the next conversation's default (switch-becomes-default, like the thinking level above).diff --git a/packages/web/e2e/files-switch.spec.mjs b/packages/web/e2e/files-switch.spec.mjsindex a6d95e9e..e81358b8 100644--- a/packages/web/e2e/files-switch.spec.mjs+++ b/packages/web/e2e/files-switch.spec.mjs@@ -64,7 +64,7 @@ test("switching conversations closes the old session's HTML preview and shows thawait ta.fill("files card test");await page.getByRole("button", { name: "发送" }).click();await expect(page.getByText(/Report generated/)).toBeVisible();- const cardRow = page.locator('button[title="demo.html"]').filter({ hasText: "点击预览" });+ const cardRow = page.locator('button[data-tooltip="demo.html"]').filter({ hasText: "点击预览" });await cardRow.click();await expect(page.frameLocator("iframe").getByText("Session A page")).toBeVisible();diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjsindex 0ad8ece0..5e62e366 100644--- a/packages/web/e2e/layout.spec.mjs+++ b/packages/web/e2e/layout.spec.mjs@@ -114,7 +114,7 @@ test("layout: en draft + context gauge + mobile models", async ({ page }) => {await page.getByPlaceholder(/Type a message/).waitFor();let d = await docWidths(page);expect(d.scrollWidth, "draft @1280 no horizontal overflow").toBeLessThanOrEqual(d.clientWidth);- await expect(page.locator('[title*="Context usage"]')).toHaveCount(0);+ await expect(page.locator('[data-tooltip*="Context usage"]')).toHaveCount(0);// Goal mode keeps its chip compact: the committed budget is a value button, while editing// happens in a fixed upward popover (never inline and never covering the objective textarea).@@ -215,7 +215,7 @@ test("layout: en draft + context gauge + mobile models", async ({ page }) => {await page.setViewportSize({ width: 1280, height: 720 });await page.goto(`${BASE}/chat/${sess.session.sessionId}`);await page.getByPlaceholder(/Type a message/).waitFor();- await expect(page.locator('[title*="Context usage"]')).toHaveCount(1);+ await expect(page.locator('[data-tooltip*="Context usage"]')).toHaveCount(1);// --- Models page @390: must not overflow, text must not overlap ---await page.setViewportSize({ width: 390, height: 844 });@@ -728,10 +728,13 @@ test("layout: mobile chat dropdowns stay inside the viewport", async ({ page })// Chips at 390: input/output/elapsed shown (no pricing configured -> no cost chip); TPS is// deliberately dropped below sm to keep the row inside the width.for (const chip of ["Input tokens", "Output tokens", "Elapsed"]) {- await expect(footer.locator(`[title="${chip}"]`), `${chip} chip present @390`).toBeVisible();+ await expect(+ footer.locator(`[data-tooltip="${chip}"]`),+ `${chip} chip present @390`,+ ).toBeVisible();}- await expect(footer.locator('[title="Output TPS"]'), "TPS chip in DOM").toHaveCount(1);- await expect(footer.locator('[title="Output TPS"]'), "TPS chip hidden @390").toBeHidden();+ await expect(footer.locator('[data-tooltip="Output TPS"]'), "TPS chip in DOM").toHaveCount(1);+ await expect(footer.locator('[data-tooltip="Output TPS"]'), "TPS chip hidden @390").toBeHidden();// With TPS dropped and compact decimals the common case FITS at 390 — no sideways scroll// needed (the scroll container remains only as a fallback for extreme values).const statsSpan = footer.locator("span").first();diff --git a/packages/web/e2e/processes.spec.mjs b/packages/web/e2e/processes.spec.mjsindex eb3a9906..98da401f 100644--- a/packages/web/e2e/processes.spec.mjs+++ b/packages/web/e2e/processes.spec.mjs@@ -55,8 +55,8 @@ test("background process appears in the details card and can be stopped", async// The turn finishes with the command promoted to background: the stats trigger (far// right; it doubles as the "Session 信息" details button) gains the background-task count.- const detailsBtn = page.locator('button[title="Session 信息"]');- await expect(detailsBtn.locator('span[title="1 个后台任务"]')).toBeVisible({+ const detailsBtn = page.locator('button[data-tooltip="Session 信息"]');+ await expect(detailsBtn.locator('span[data-tooltip="1 个后台任务"]')).toBeVisible({timeout: 30_000,});@@ -82,7 +82,7 @@ test("background process appears in the details card and can be stopped", async// The kill drops the process from the registry: the row disappears on the follow-up// refresh and the header count goes with it.await expect(page.getByText("会话进程")).toHaveCount(0, { timeout: 10_000 });- await expect(detailsBtn.locator('span[title="1 个后台任务"]')).toHaveCount(0);+ await expect(detailsBtn.locator('span[data-tooltip="1 个后台任务"]')).toHaveCount(0);// The server-side list agrees (the registry entry is gone, not merely marked exited).const procs = await (@@ -133,7 +133,7 @@ test("an exited process can be removed from the list", async ({ page }) => {// Open the details card. The exited row keeps its 已退出 label and gains a remove// button (#312); running rows are the only ones with 停止. The generous timeout rides// out one 15s poll interval in case the idle refresh still saw the process alive.- await page.locator('button[title="Session 信息"]').click();+ await page.locator('button[data-tooltip="Session 信息"]').click();await expect(page.getByText("会话进程")).toBeVisible();const row = page.locator("li", { hasText: "sleep 0.5" }).first();await expect(row.getByText("已退出")).toBeVisible({ timeout: 30_000 });@@ -188,7 +188,7 @@ test("clear exited removes every exited process and leaves the running one", asyawait page.getByRole("button", { name: "发送" }).click();await expect(page.getByText(/Command finished/).first()).toBeVisible({ timeout: 30_000 });- await page.locator('button[title="Session 信息"]').click();+ await page.locator('button[data-tooltip="Session 信息"]').click();await expect(page.getByText("会话进程")).toBeVisible();const running = page.locator("li", { hasText: "sleep 600" }).first();const exited = page.locator("li", { hasText: "sleep 0.5" }).first();diff --git a/packages/web/e2e/selection-menu.spec.mjs b/packages/web/e2e/selection-menu.spec.mjsindex 2e3a9754..730970bb 100644--- a/packages/web/e2e/selection-menu.spec.mjs+++ b/packages/web/e2e/selection-menu.spec.mjs@@ -98,7 +98,7 @@ test("selected conversation text offers Copy and Add to conversation", async ({// Staged as a chip whose tooltip is the whole excerpt. The draft stays empty, nothing was// sent, the menu has closed, and the text is still selected.- const chip = page.locator(`span[title="${SENTENCE}"]`);+ const chip = page.locator(`span[data-tooltip="${SENTENCE}"]`);await expect(chip).toBeVisible();await expect(composer).toHaveValue("");await expect(addRow).toHaveCount(0);diff --git a/packages/web/index.html b/packages/web/index.htmlindex b763229a..0d18114c 100644--- a/packages/web/index.html+++ b/packages/web/index.html@@ -11,9 +11,15 @@content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content"/><meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />- <meta name="theme-color" content="#030712" media="(prefers-color-scheme: dark)" />+ <meta name="theme-color" content="#000000" media="(prefers-color-scheme: dark)" /><link rel="icon" type="image/svg+xml" href="/penguin-logo.svg" /><title>PenguinHarness</title>+ <!-- Pre-paint theme: sets html.dark, data-theme, data-accent and the root font size from the+ stored preferences before the first frame, so a dark or non-default page never flashes+ the light default and the first frame never renders at 16px and reflows. Must equal+ BOOT_SCRIPT in @prismshadow/penguin-ui/boot byte for byte (a test compares them). -->+ <!-- prettier-ignore -->+ <script>(function(){try{var d=document.documentElement,s=localStorage,m=s.getItem("penguin.theme");if(m==="dark"||(m!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches))d.classList.add("dark");var t=s.getItem("penguin.themeId");if(["modern","geek"].indexOf(t)>=0)d.dataset.theme=t;var a=s.getItem("penguin.accent");if(["blue","green","violet","rose","amber","ocean","clay","plum","honey","slate","orange","phosphor","cyan","magenta","gold","cobalt"].indexOf(a)>=0)d.dataset.accent=a;var l=s.getItem("penguin.fontLatin");if(["system","mona-sans","ibm-plex-sans","misans"].indexOf(l)>=0)d.dataset.fontLatin=l;var c=s.getItem("penguin.fontCjk");if(["system","noto-sans-sc","misans"].indexOf(c)>=0)d.dataset.fontCjk=c;var z=s.getItem("penguin.textSize"),g=null,o=-1;if(["xs","s","m","l","xl"].indexOf(z)<0){g=s.getItem("penguin.fontScale");o=["sm","md","lg"].indexOf(g);z=o<0?"m":["m","l","xl"][o]}d.style.fontSize={"xs":"14px","s":"15px","m":"16px","l":"18px","xl":"20px"}[z];if(g!==null){try{if(o>=0)s.setItem("penguin.textSize",z);s.removeItem("penguin.fontScale")}catch(e){}}}catch(e){}})()</script></head><body><div id="root"></div>diff --git a/packages/web/package.json b/packages/web/package.jsonindex 7af5edec..c4fd101c 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -14,6 +14,7 @@},"dependencies": {"@prismshadow/penguin-core": "workspace:*",+ "@prismshadow/penguin-ui": "workspace:*","@shikijs/langs": "^4.3.1","@shikijs/themes": "^4.3.1","@xterm/addon-clipboard": "^0.1.0",diff --git a/packages/web/scripts/theme-shots.mjs b/packages/web/scripts/theme-shots.mjsnew file mode 100644index 00000000..bd8bb261--- /dev/null+++ b/packages/web/scripts/theme-shots.mjs@@ -0,0 +1,702 @@+/**+ * Pixel-diff harness for theme work: screenshots the real app built two (or more) ways against the+ * SAME server, data and clock, then compares the shots pixel for pixel.+ *+ * node scripts/theme-shots.mjs capture --out <dir> before=<web dist> after=<web dist>+ * node scripts/theme-shots.mjs diff <dir>/before <dir>/after [--diff-out <dir>]+ *+ * `capture` hosts a scripted mock LLM, starts the built server (packages/server/dist) on a+ * throwaway data root, provisions one user per UI language, drives one real conversation each+ * (a thinking block, a tool call that executes, a Markdown answer with code, a table and links),+ * and then, per language × mode (light / dark) × variant, screenshots twelve pages into+ * `<out>/<variant>/<lang>/<mode>/<page>.png`. Every variant is served by the one server: page+ * requests are fulfilled from that variant's dist through Playwright routing, while `/api` reaches+ * the server, so the only thing that differs between two shots is the bundle.+ *+ * What keeps runs comparable: `Date.now()` is frozen after seeding (relative times stay put), a+ * warm-up pass visits every page first (read marks and lazy server state settle before any+ * shot), Chromium rasterises without the GPU, animations are finished or cancelled at capture,+ * the caret is hidden, and a shot is kept only once two consecutive captures agree. Passing the+ * same dist twice (`before=<dist> again=<dist>`) measures the harness's own noise floor.+ *+ * `diff` compares two shot trees. Identical PNG bytes pass outright; otherwise both images are+ * decoded in Chromium and compared exactly (threshold 0) — any differing pixel fails, and a diff+ * image with the differing pixels in red is written for inspection. Exit code 1 on any difference.+ *+ * Prereqs: `pnpm --filter "@prismshadow/penguin-server..." build`, each variant's web dist, and+ * Playwright's Chromium. Local only; never committed output.+ */+import http from "node:http";+import { spawn } from "node:child_process";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ statSync,+ writeFileSync,+} from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { chromium } from "@playwright/test";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(HERE, "../../..");+const SRV_PORT = Number(process.env.THEME_SHOTS_PORT || 8950);+const MOCK_PORT = SRV_PORT + 1;+// `localhost`, not `127.0.0.1`: that literal address is the Workspace-preview host and the API+// answers 401 on it.+const BASE = `http://localhost:${SRV_PORT}`;+const MOCK = `http://127.0.0.1:${MOCK_PORT}`;+const ADMIN_PASSWORD = "penguin-0000";+// THEME_SHOTS_LANGS / THEME_SHOTS_MODES / THEME_SHOTS_PAGES (comma lists) narrow a run while+// investigating one difference; a verdict is only ever the full matrix.+const LANGS = process.env.THEME_SHOTS_LANGS?.split(",") ?? ["en", "zh"];+const MODES = process.env.THEME_SHOTS_MODES?.split(",") ?? ["light", "dark"];+const VIEWPORT = { width: 1280, height: 800 };++// ---------------------------------------------------------------------------+// The scripted conversation.+// ---------------------------------------------------------------------------++const DONE_MARKER = "theme-shots-done";+const CMD = "printf 'palette\\ntokens\\nthemes\\n' | sort";++const SCRIPTS = {+ en: {+ marker: "theme audit",+ prompt: "Run a quick theme audit of this workspace and summarise it.",+ title: "Theme audit",+ thinking:+ "A short audit: list the three theme files, then summarise with a table and a code sample.",+ lead: "Listing what the audit covers first:",+ answer: `The audit is done — see the [token contract](https://example.com/tokens) for names.++| Theme | Radius | Glass |+| --- | --- | --- |+| Primer | 6px | no |+| Frost | 12px | yes |+| Console | 0 | no |++\`\`\`css+:root { --ui-surface: #ffffff; }+\`\`\`++- Inline \`code\` renders on the inset surface;+- Marker: \`${DONE_MARKER}\`.`,+ },+ zh: {+ marker: "主题审计",+ prompt: "对这个工作区做一次快速的主题审计并总结。",+ title: "主题审计",+ thinking: "简短审计:先列出三个主题文件,再用表格和代码示例总结。",+ lead: "先列出审计覆盖的内容:",+ answer: `审计完成,名称见[令牌契约](https://example.com/tokens)。++| 主题 | 圆角 | 磨砂 |+| --- | --- | --- |+| Primer | 6px | 否 |+| Frost | 12px | 是 |+| Console | 0 | 否 |++\`\`\`css+:root { --ui-surface: #ffffff; }+\`\`\`++- 行内 \`code\` 画在嵌入面上;+- 标记:\`${DONE_MARKER}\`。`,+ },+};++const scriptFor = (flat) => (flat.includes(SCRIPTS.zh.marker) ? SCRIPTS.zh : SCRIPTS.en);++function openaiReply(res, body) {+ const flat = JSON.stringify(body.messages ?? []);+ const script = scriptFor(flat);+ const isTitle = flat.includes("concise title");+ const toolDone = flat.includes('"role":"tool"');+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });+ const chunk = (delta, finishReason = null, usage) => {+ const payload = {+ id: "chatcmpl-theme-shots",+ object: "chat.completion.chunk",+ created: 1_700_000_000,+ model: "deepseek-v4-pro",+ choices: [{ index: 0, delta, finish_reason: finishReason }],+ };+ if (usage) payload.usage = usage;+ res.write(`data: ${JSON.stringify(payload)}\n\n`);+ };+ const usage = {+ prompt_tokens: 5200,+ completion_tokens: 420,+ total_tokens: 5620,+ prompt_cache_hit_tokens: 4300,+ prompt_cache_miss_tokens: 900,+ };+ const pieces = (s, n) => s.match(new RegExp(`[\\s\\S]{1,${n}}`, "g")) ?? [];+ chunk({ role: "assistant" });+ if (isTitle) {+ chunk({ content: script.title });+ chunk({}, "stop", usage);+ } else if (!toolDone) {+ for (const t of pieces(script.thinking, 18)) chunk({ reasoning_content: t });+ for (const t of pieces(script.lead, 24)) chunk({ content: t });+ chunk({+ tool_calls: [+ {+ index: 0,+ id: "call_theme_shots_1",+ type: "function",+ function: { name: "exec_command", arguments: "" },+ },+ ],+ });+ for (const part of pieces(JSON.stringify({ cmd: CMD }), 32)) {+ chunk({ tool_calls: [{ index: 0, function: { arguments: part } }] });+ }+ chunk({}, "tool_calls", usage);+ } else {+ for (const t of pieces(script.answer, 24)) chunk({ content: t });+ chunk({}, "stop", usage);+ }+ res.write("data: [DONE]\n\n");+ res.end();+}++function startMock() {+ const server = http.createServer((req, res) => {+ let body = "";+ req.on("data", (c) => (body += c));+ req.on("end", () => {+ let json = {};+ try {+ json = JSON.parse(body);+ } catch {}+ if (req.method === "POST" && req.url?.includes("chat/completions"))+ return openaiReply(res, json);+ res.writeHead(404).end();+ });+ });+ return new Promise((resolve) => server.listen(MOCK_PORT, "127.0.0.1", () => resolve(server)));+}++// ---------------------------------------------------------------------------+// Server and API helpers.+// ---------------------------------------------------------------------------++async function waitFor(url, tries = 120) {+ for (let i = 0; i < tries; i++) {+ try {+ if ((await fetch(url)).ok) return;+ } catch {}+ await new Promise((r) => setTimeout(r, 500));+ }+ throw new Error(`server not ready: ${url}`);+}++async function api(cookie, method, url, body) {+ const res = await fetch(`${BASE}${url}`, {+ method,+ headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },+ ...(body ? { body: JSON.stringify(body) } : {}),+ });+ if (!res.ok) throw new Error(`${method} ${url} -> ${res.status} ${await res.text()}`);+ return { json: await res.json().catch(() => ({})), setCookie: res.headers.get("set-cookie") };+}++async function login(userId, password) {+ const { json, setCookie } = await api(null, "POST", "/api/auth/login", { userId, password });+ if (!setCookie) throw new Error("no session cookie from login");+ return { cookie: setCookie.split(";")[0], user: json.user };+}++const USERS = {+ en: {+ userId: "alex",+ agents: [+ { agentId: "data_analyst", name: "Data Analyst", description: "CSV analysis and charts" },+ { agentId: "web_scout", name: "Web Scout", description: "Web research and fact checking" },+ ],+ },+ zh: {+ userId: "demo",+ agents: [+ { agentId: "data_analyst", name: "数据分析师", description: "CSV 数据分析与图表" },+ { agentId: "web_scout", name: "网页调研员", description: "网页检索与信息核对" },+ ],+ },+};++async function provisionUser(adminCookie, lang, wsRoot) {+ const { userId, agents } = USERS[lang];+ const initial = `${userId}12345`;+ const password = `penguin-${userId}-2026`;+ await api(adminCookie, "POST", "/api/admin/users", { userId, password: initial });+ let session = await login(userId, initial);+ // Rotate once so the initial-password banner stays out of the shots.+ await api(session.cookie, "PUT", "/api/me/password", {+ oldPassword: initial,+ newPassword: password,+ });+ session = await login(userId, password);+ const projectId = (await api(session.cookie, "GET", "/api/projects")).json.projects[0].projectId;+ await api(session.cookie, "PUT", `/api/projects/${projectId}/models`, {+ defaultModel: { provider: "deepseek", modelId: "deepseek-v4-pro" },+ models: [+ {+ provider: "deepseek",+ modelId: "deepseek-v4-pro",+ clientType: "openai-chat",+ apiKey: "sk-demo",+ baseUrl: MOCK,+ contextWindow: 1000000,+ pricing: { cacheRead: 0.003571, cacheWrite: 0.428571, output: 0.857143 },+ },+ ],+ });+ for (const agent of agents) {+ await api(session.cookie, "POST", `/api/projects/${projectId}/agents`, agent);+ }+ const ws = path.join(wsRoot, lang);+ mkdirSync(ws, { recursive: true });+ const created = await api(+ session.cookie,+ "POST",+ `/api/projects/${projectId}/agents/default_agent/sessions`,+ { provider: "deepseek", modelId: "deepseek-v4-pro", approvalMode: "allow-all", workspace: ws },+ );+ return { userId, password, projectId, sessionId: created.json.session.sessionId };+}++// ---------------------------------------------------------------------------+// Browser helpers.+// ---------------------------------------------------------------------------++/** A context whose page requests are answered from `dist`; `/api` still reaches the server. */+async function newContext(browser, { dist, lang, mode, user, fixedNow, reducedMotion }) {+ const context = await browser.newContext({+ viewport: VIEWPORT,+ deviceScaleFactor: 1,+ locale: lang === "zh" ? "zh-CN" : "en-US",+ colorScheme: mode,+ reducedMotion: reducedMotion ? "reduce" : "no-preference",+ });+ await context.addInitScript(+ ([m, l]) => {+ localStorage.setItem("penguin.theme", m);+ localStorage.setItem("penguin.lang", l);+ localStorage.setItem("penguin.dock.layout", JSON.stringify({ scopes: {}, bottomRatio: 0.6 }));+ },+ [mode, lang],+ );+ await context.route(+ (url) => url.origin === BASE && !url.pathname.startsWith("/api/"),+ async (route) => {+ const rel = decodeURIComponent(new URL(route.request().url()).pathname).replace(/^\/+/, "");+ let file = path.join(dist, rel);+ if (!rel || !existsSync(file) || statSync(file).isDirectory()) {+ file = path.join(dist, "index.html"); // SPA fallback, as the server does+ }+ await route.fulfill({ path: file });+ },+ );+ if (fixedNow !== undefined) await context.clock.setFixedTime(fixedNow);+ if (user) {+ const res = await context.request.post(`${BASE}/api/auth/login`, {+ data: { userId: user.userId, password: user.password },+ });+ if (!res.ok()) throw new Error(`browser login failed: ${res.status()}`);+ }+ return context;+}++/**+ * Chromium flags that take the GPU and its timing out of rasterisation. Without them the same+ * build, shot twice, differs by a handful of anti-aliasing pixels on rounded corners and small+ * glyphs — noise that a threshold-0 comparison cannot tell from a real change.+ */+const DETERMINISTIC_ARGS = [+ "--disable-gpu",+ "--disable-gpu-rasterization",+ "--disable-partial-raster",+ "--disable-skia-runtime-opts",+ "--force-color-profile=srgb",+ "--font-render-hinting=none",+ "--disable-lcd-text",+];++/**+ * A screenshot taken only once three consecutive captures, 300ms apart, agree byte for byte, so a+ * transition or a late layout still settling never lands in a shot.+ */+async function stableScreenshot(page, label) {+ // The session's cost figure is DATA with a load-order race of its own (a stored-rate estimate+ // until the server-priced total lands, or not), so its value is masked; the chip's styling is+ // still covered by the token and duration chips beside it.+ const mask = [page.locator('[title*="(USD)"], [title*="(CNY)"]')];+ let previous = null;+ let agreeing = 0;+ for (let attempt = 1; attempt <= 20; attempt++) {+ const buf = await page.screenshot({ animations: "disabled", caret: "hide", mask });+ agreeing = previous !== null && buf.equals(previous) ? agreeing + 1 : 0;+ if (agreeing === 2) return buf;+ previous = buf;+ await page.waitForTimeout(300);+ }+ console.log(`[theme-shots] never stable: ${label}`);+ return previous;+}++/** Fonts loaded, the network quiet (bounded: a page may hold an event stream open), then a pause. */+async function settle(page, ms = 1200) {+ await page.evaluate(() => document.fonts.ready);+ await page.waitForLoadState("networkidle", { timeout: 5000 }).catch(() => {});+ await page.waitForTimeout(ms);+}++/**+ * Re-shoot rounds for one page. Variants are shot back to back per page, so data that moves with+ * the clock (a cost figure repriced a moment after load) cannot separate them by minutes. When a+ * variant still disagrees with the first, the whole page is re-shot, up to this many rounds: a+ * rendering race disappears on a re-shoot, a real stylesheet difference is deterministic and+ * survives every round. The rounds each page took are logged, so nothing is re-shot silently.+ */+const ROUNDS = 3;++/** The twelve pages. Each leaves the page in the state to capture. */+const PAGES = [+ {+ id: "login",+ auth: false,+ // The circuit-trace background loops on a 14s CSS cycle whose phase at capture time decides+ // a few anti-aliased pixels behind the form; under reduced motion it rests as static lines.+ reducedMotion: true,+ run: async (page) => {+ await page.goto(`${BASE}/login`);+ await page.locator("form button[type=submit]").waitFor({ timeout: 20000 });+ },+ },+ {+ id: "chat-new",+ run: async (page) => {+ await page.goto(`${BASE}/chat`);+ await page.getByPlaceholder(/输入消息|Type a message/).waitFor({ timeout: 20000 });+ },+ },+ {+ id: "chat",+ run: async (page, { user }) => {+ await page.goto(`${BASE}/chat/${user.sessionId}`);+ await page.getByText(DONE_MARKER).first().waitFor({ timeout: 30000 });+ },+ },+ {+ id: "trace",+ run: async (page, { user }) => {+ await page.goto(`${BASE}/chat/${user.sessionId}`);+ await page.getByText(DONE_MARKER).first().waitFor({ timeout: 30000 });+ await page.getByTestId("dock-toggle-bottom").click();+ const dock = page.locator("[data-testid='dock'][data-position='bottom']");+ await dock.getByTestId("dock-pick-trace").click();+ await dock.locator('[data-tab-id="trace"][data-active="true"]').waitFor({ timeout: 20000 });+ await dock+ .getByTitle(/exec_command/)+ .first()+ .waitFor({ timeout: 30000 });+ },+ },+ {+ id: "user-menu",+ run: async (page, { user }) => {+ await page.goto(`${BASE}/chat/${user.sessionId}`);+ await page.getByText(DONE_MARKER).first().waitFor({ timeout: 30000 });+ await page.getByRole("button", { name: user.userId }).last().click();+ await page.getByRole("button", { name: /^(System settings|系统设置)$/ }).waitFor();+ await page.mouse.move(0, 0);+ },+ },+ {+ id: "settings",+ run: async (page, { user }) => {+ await page.goto(`${BASE}/chat/${user.sessionId}`);+ await page.getByText(DONE_MARKER).first().waitFor({ timeout: 30000 });+ await page.getByRole("button", { name: user.userId }).last().click();+ await page.getByRole("button", { name: /^(System settings|系统设置)$/ }).click();+ const dialog = page.getByRole("dialog");+ await dialog+ .getByRole("button", { name: /^(Appearance|外观)$/ })+ .first()+ .click();+ await dialog.getByRole("button", { name: /^(Blue|蓝)$/ }).waitFor({ timeout: 10000 });+ await page.mouse.move(0, 0);+ },+ },+ { id: "agents", run: (page) => page.goto(`${BASE}/agents`) },+ { id: "agent-settings", run: (page) => page.goto(`${BASE}/agents/data_analyst`) },+ { id: "plugins", run: (page) => page.goto(`${BASE}/plugins`) },+ { id: "models", run: (page) => page.goto(`${BASE}/models`) },+ { id: "usage", run: (page) => page.goto(`${BASE}/usage`) },+ {+ id: "benchmark",+ run: async (page) => {+ await page.goto(`${BASE}/benchmark`);+ await page.waitForTimeout(1500);+ await page+ .getByText(/Example Benchmark|示例/)+ .first()+ .click({ timeout: 5000 });+ },+ },+];++// ---------------------------------------------------------------------------+// capture+// ---------------------------------------------------------------------------++async function capture(args) {+ const outIdx = args.indexOf("--out");+ if (outIdx < 0 || !args[outIdx + 1]) throw new Error("capture needs --out <dir>");+ const out = path.resolve(args[outIdx + 1]);+ const variants = args+ .filter((a, i) => i !== outIdx && i !== outIdx + 1 && a.includes("="))+ .map((a) => {+ const [name, dist] = a.split("=");+ const abs = path.resolve(dist);+ if (!existsSync(path.join(abs, "index.html"))) throw new Error(`no index.html in ${abs}`);+ return { name, dist: abs };+ });+ if (variants.length === 0) throw new Error("capture needs at least one <name>=<dist>");+ const only = process.env.THEME_SHOTS_PAGES?.split(",");+ const pages = only ? PAGES.filter((p) => only.includes(p.id)) : PAGES;++ const dataRoot = mkdtempSync(path.join(os.tmpdir(), "penguin-theme-shots-"));+ const mock = await startMock();+ const srv = spawn("node", [path.join(ROOT, "packages/server/dist/index.js")], {+ env: {+ ...process.env,+ PENGUIN_HOME: path.join(dataRoot, "home"),+ PENGUIN_WEB_DB: path.join(dataRoot, "web.db"),+ PENGUIN_WEB_DIST: variants[0].dist,+ PORT: String(SRV_PORT),+ HOST: "127.0.0.1",+ PENGUIN_SEED_ADMIN_PASSWORD: ADMIN_PASSWORD,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ srv.stderr.on("data", (d) => process.stderr.write(`[srv!] ${d}`));+ const cleanup = () => {+ srv.kill();+ mock.close();+ };+ process.on("exit", cleanup);++ await waitFor(`${BASE}/`);+ console.log(`[theme-shots] server on ${BASE}, data root ${dataRoot}`);+ // The listener can answer before the seeded admin exists; retry the first login briefly.+ let admin;+ for (let i = 0; !admin; i++) {+ admin = await login("admin", ADMIN_PASSWORD).catch((err) => {+ if (i >= 40) throw err;+ return new Promise((r) => setTimeout(r, 500));+ });+ }+ const browser = await chromium.launch({ args: DETERMINISTIC_ARGS });+ let shots = 0;++ for (const lang of LANGS) {+ const user = { ...(await provisionUser(admin.cookie, lang, path.join(dataRoot, "ws"))), lang };++ // Seed: drive the conversation once, through the UI, to completion.+ {+ const context = await newContext(browser, {+ dist: variants[0].dist,+ lang,+ mode: "light",+ user,+ });+ const page = await context.newPage();+ await page.goto(`${BASE}/chat/${user.sessionId}`);+ const input = page.getByPlaceholder(/输入消息|Type a message/);+ await input.waitFor({ timeout: 20000 });+ await input.fill(SCRIPTS[lang].prompt);+ await page.getByRole("button", { name: /发送|Send/ }).click();+ await page.getByText(DONE_MARKER).first().waitFor({ timeout: 90000 });+ await page.waitForTimeout(3000); // title generation and stats settle+ await context.close();+ }+ const fixedNow = Date.now();++ // Warm-up: every page once, so first-visit side effects land before any shot.+ {+ const context = await newContext(browser, {+ dist: variants[0].dist,+ lang,+ mode: "light",+ user,+ fixedNow,+ });+ const page = await context.newPage();+ for (const def of pages.filter((p) => p.auth !== false)) {+ await def.run(page, { user });+ await settle(page, 800);+ }+ await context.close();+ }++ for (const mode of MODES) {+ for (const def of pages) {+ let bufs = [];+ let round = 0;+ while (round < ROUNDS) {+ round++;+ bufs = [];+ for (const variant of variants) {+ // A fresh context per shot: no focus, scroll or storage state carries from one shot+ // (or one variant) into the next.+ const context = await newContext(browser, {+ dist: variant.dist,+ lang,+ mode,+ fixedNow,+ reducedMotion: def.reducedMotion === true,+ ...(def.auth === false ? {} : { user }),+ });+ const page = await context.newPage();+ await def.run(page, { user });+ await settle(page);+ bufs.push(await stableScreenshot(page, `${variant.name}/${lang}/${mode}/${def.id}`));+ await context.close();+ }+ if (bufs.every((b) => b.equals(bufs[0]))) break;+ }+ for (const [i, variant] of variants.entries()) {+ const file = path.join(out, variant.name, lang, mode, `${def.id}.png`);+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, bufs[i]);+ shots++;+ }+ if (round > 1) console.log(`[theme-shots] ${lang} ${mode} ${def.id}: ${round} rounds`);+ }+ console.log(`[theme-shots] ${lang} ${mode}: ${pages.length} pages × ${variants.length}`);+ }+ }++ await browser.close();+ cleanup();+ console.log(`[theme-shots] ${shots} shots -> ${out}`);+}++// ---------------------------------------------------------------------------+// diff+// ---------------------------------------------------------------------------++function listPngs(dir, prefix = "") {+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) =>+ e.isDirectory()+ ? listPngs(path.join(dir, e.name), `${prefix}${e.name}/`)+ : e.name.endsWith(".png")+ ? [`${prefix}${e.name}`]+ : [],+ );+}++async function diff(args) {+ const [a, b] = args.filter((x) => !x.startsWith("--")).map((d) => path.resolve(d));+ if (!a || !b) throw new Error("diff needs <dirA> <dirB>");+ const outIdx = args.indexOf("--diff-out");+ const diffOut = outIdx >= 0 ? path.resolve(args[outIdx + 1]) : path.join(path.dirname(b), "diff");+ const left = new Set(listPngs(a));+ const right = new Set(listPngs(b));+ const names = [...new Set([...left, ...right])].sort();+ let browser;+ let page;+ const failures = [];+ for (const name of names) {+ if (!left.has(name) || !right.has(name)) {+ failures.push(`${name}: missing on the ${left.has(name) ? "right" : "left"}`);+ continue;+ }+ const bufA = readFileSync(path.join(a, name));+ const bufB = readFileSync(path.join(b, name));+ if (bufA.equals(bufB)) continue;+ browser ??= await chromium.launch();+ page ??= await browser.newPage();+ const result = await page.evaluate(+ async ([pa, pb]) => {+ const load = async (b64) => {+ const img = new Image();+ img.src = `data:image/png;base64,${b64}`;+ await img.decode();+ const c = document.createElement("canvas");+ c.width = img.width;+ c.height = img.height;+ const ctx = c.getContext("2d", { willReadFrequently: true });+ ctx.drawImage(img, 0, 0);+ return {+ w: img.width,+ h: img.height,+ ctx,+ data: ctx.getImageData(0, 0, c.width, c.height),+ };+ };+ const x = await load(pa);+ const y = await load(pb);+ if (x.w !== y.w || x.h !== y.h) return { sizeMismatch: `${x.w}x${x.h} vs ${y.w}x${y.h}` };+ const out = x.ctx.createImageData(x.w, x.h);+ let count = 0;+ for (let i = 0; i < x.data.data.length; i += 4) {+ const same =+ x.data.data[i] === y.data.data[i] &&+ x.data.data[i + 1] === y.data.data[i + 1] &&+ x.data.data[i + 2] === y.data.data[i + 2] &&+ x.data.data[i + 3] === y.data.data[i + 3];+ if (same) {+ const g = (x.data.data[i] + x.data.data[i + 1] + x.data.data[i + 2]) / 3;+ out.data.set([g, g, g, 60], i);+ } else {+ count++;+ out.data.set([255, 0, 0, 255], i);+ }+ }+ if (count === 0) return { count };+ const c = document.createElement("canvas");+ c.width = x.w;+ c.height = x.h;+ c.getContext("2d").putImageData(out, 0, 0);+ return { count, png: c.toDataURL("image/png").split(",")[1] };+ },+ [bufA.toString("base64"), bufB.toString("base64")],+ );+ if (result.sizeMismatch) {+ failures.push(`${name}: size ${result.sizeMismatch}`);+ } else if (result.count > 0) {+ const file = path.join(diffOut, name);+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, Buffer.from(result.png, "base64"));+ failures.push(`${name}: ${result.count} px differ -> ${file}`);+ }+ }+ await browser?.close();+ console.log(`[theme-shots] compared ${names.length} shots: ${failures.length} differ`);+ for (const f of failures) console.log(` ${f}`);+ return failures.length === 0;+}++const [command, ...rest] = process.argv.slice(2);+try {+ if (command === "capture") {+ await capture(rest);+ process.exit(0);+ } else if (command === "diff") {+ process.exit((await diff(rest)) ? 0 : 1);+ } else {+ console.error("usage: theme-shots.mjs capture --out <dir> <name>=<dist>… | diff <dirA> <dirB>");+ process.exit(2);+ }+} catch (err) {+ console.error("[theme-shots] FAILED:", err);+ process.exit(1);+}diff --git a/packages/web/src/app.tsx b/packages/web/src/app.tsxindex 9dd1ad4e..a529494b 100644--- a/packages/web/src/app.tsx+++ b/packages/web/src/app.tsx@@ -14,9 +14,14 @@ import { ThemeProvider } from "./state/theme";import { AuthProvider } from "./state/auth";import { AppRouter } from "./router";import { Toaster } from "./components/ui/toast";+import { TooltipLayer } from "./components/ui/tooltip";import { guardWindowDragOver, guardWindowDrop } from "./lib/file-drop";-export function App() {+/**+ * `initialPath`: mount the app on an in-memory router opened at that path instead of the+ * browser's address bar (see AppRouter) — for a host document that frames the app.+ */+export function App({ initialPath }: { initialPath?: string } = {}) {// The guard reads `defaultPrevented` rather than assuming it runs last: the chat area's// drop zone is a window listener too, so the two fire in registration order. Both orders// converge — whichever runs second either finds the drag already claimed and bails, or@@ -34,9 +39,11 @@ export function App() {<ThemeProvider><AuthProvider><LocaleScope>- <AppRouter />+ <AppRouter {...(initialPath === undefined ? {} : { initialPath })} />{/* Top toast overlay: portaled to body, z-index above modals, shared site-wide. */}<Toaster />+ {/* The hover hints of every `data-tooltip` element: one listener set, one panel. */}+ <TooltipLayer /></LocaleScope></AuthProvider></ThemeProvider>diff --git a/packages/web/src/components/account/update-modal.tsx b/packages/web/src/components/account/update-modal.tsxindex 034112a5..cbb22666 100644--- a/packages/web/src/components/account/update-modal.tsx+++ b/packages/web/src/components/account/update-modal.tsx@@ -278,7 +278,7 @@ function ProgressBar({ percent }: { percent: number | null }) {className="h-2 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-800"><div- className={`h-full rounded-full bg-[var(--accent-bg)] ${+ className={`h-full rounded-full bg-accent ${percent === null ? "w-1/3 animate-pulse" : "transition-[width] duration-300"}`}style={percent === null ? undefined : { width: `${percent}%` }}diff --git a/packages/web/src/components/account/update-row.tsx b/packages/web/src/components/account/update-row.tsxindex fd3fef75..8e6fbb36 100644--- a/packages/web/src/components/account/update-row.tsx+++ b/packages/web/src/components/account/update-row.tsx@@ -35,9 +35,7 @@ export function UpdateRow({className="inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"/>)}- {row.dot && (- <span aria-hidden className="h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]" />- )}+ {row.dot && <span aria-hidden className="h-2 w-2 shrink-0 rounded-full bg-accent" />}<span className="min-w-0 truncate">{rowLabel(flow)}</span></span>{currentVersion !== null && (diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex 876067c5..9443551d 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -45,7 +45,7 @@ import { ShortcutRuntime } from "../../features/settings/shortcut-runtime";import { BuiltinBrowserLayer } from "../../features/builtin-browser/browser-layer";import { setDockScope } from "../../features/dock/dock-state";import { AppPalette } from "../../features/palette/app-palette";-import { toneStrip } from "../../lib/tone";+import { NoticeStrip } from "../ui/notice-strip";/*** "Last conversation" glyph, used only by the rail: lucide's history mark — a clock read@@ -465,7 +465,9 @@ export function AppLayout() {}, [collapsed, inCompany, newChat]);return (- <div className="flex h-full">+ // ui-shell: the app window. A theme may paint a field behind it, float the main column as a+ // sheet or rule the columns apart; the navigation column is `nav`, the page column `main`.+ <div className="ui-shell flex h-full">{/* Desktop: single-column sidebar (collapsible to a narrow rail).Collapsing animates the WIDTH, which is the one animation here that transform cannotcarry: the sidebar is in flow, so the main content reflows beside it rather than@@ -479,6 +481,7 @@ export function AppLayout() {rail sits at its final 48px from the first frame while the box closes around it, andthe pinned sidebar is uncovered left to right instead of reflowing on every frame. */}<aside+ data-slot="nav"className={`hidden shrink-0 overflow-hidden border-r border-gray-200 bg-gray-50 transition-[width] duration-200 ease-out md:block dark:border-gray-800 dark:bg-gray-900 ${collapsed ? "w-12" : "w-64 lg:w-72"}`}@@ -503,7 +506,7 @@ export function AppLayout() {</div></aside>- <div className="flex min-w-0 flex-1 flex-col">+ <div data-slot="main" className="flex min-w-0 flex-1 flex-col">{/* Mobile: top thin bar (hamburger + brand) */}<header className="flex h-12 shrink-0 items-center gap-2 border-b border-gray-200 bg-white px-2 md:hidden dark:border-gray-800 dark:bg-gray-950">{/* The outermost menu on a phone: it carries a dot for EITHER trail, so its wording@@ -513,7 +516,7 @@ export function AppLayout() {<buttontype="button"aria-label={badges.note !== null ? `${drawerName} · ${badges.note}` : drawerName}- {...(badges.note !== null ? { title: badges.note } : {})}+ {...(badges.note !== null ? { "data-tooltip": badges.note } : {})}onClick={() => setDrawerOpen(true)}className="relative flex h-9 w-9 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200">@@ -539,8 +542,9 @@ export function AppLayout() {Permanently dismissible via the X on the right (per-user ui_prefs); only rendered oncehydrated prefs confirm it was never dismissed, so it does not flash-then-vanish on load. */}{passwordBannerRelevant && passwordBannerDismissed === false && (- <div- className={`relative flex shrink-0 items-center justify-center gap-3 border-b px-8 py-1.5 text-xs ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="relative flex shrink-0 items-center justify-center gap-3 border-b px-8 py-1.5 text-xs"><span>{S.account.initialPasswordBanner}</span><button@@ -559,13 +563,13 @@ export function AppLayout() {<buttontype="button"aria-label={S.common.close}- title={S.common.close}+ data-tooltip={S.common.close}onClick={dismissPasswordBanner}className="absolute inset-y-0.5 right-1.5 flex items-center rounded-md px-1 text-amber-500 transition-colors duration-150 hover:text-amber-950 dark:text-amber-400/70 dark:hover:text-amber-100"><CloseIcon size={12} /></button>- </div>+ </NoticeStrip>)}<main className="min-h-0 min-w-0 flex-1 overflow-hidden">diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsxindex b1933b5e..9335b0d7 100644--- a/packages/web/src/components/layout/project-dialogs.tsx+++ b/packages/web/src/components/layout/project-dialogs.tsx@@ -714,8 +714,8 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwne</option>))}</Select>- {/* Plain tier names, not the composer dropdown's annotated variant: a native- <select> paints the picked option's own text on the collapsed control, so+ {/* Plain tier names, not the composer dropdown's annotated variant: a Select+ shows the picked option's own text on its closed trigger, soannotating the rows here would also put "(xhigh)" on what is, once closed,a trigger. Matches the approval-mode select directly above, whose optionsare plain localized names too. */}@@ -1075,7 +1075,8 @@ function SecurityPolicySection({ projectId, isOwner }: { projectId: string; isOw)}<pclassName="mt-0.5 truncate font-mono text-[11px] text-gray-400"- title={r.pattern}+ data-tooltip={r.pattern}+ data-tooltip-content="code">{r.pattern}</p>diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex b2a0ccc0..a0838de6 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -1824,7 +1824,7 @@ export function Sidebar({{onCollapse && (<buttontype="button"- title={collapseTitle}+ data-tooltip={collapseTitle}aria-label={S.nav.collapseSidebar}onClick={onCollapse}className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"@@ -1846,7 +1846,7 @@ export function Sidebar({onClick={() => setProjectOpen(!projectOpen)}className="flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-base font-semibold transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800">- <span className="min-w-0 flex-1 truncate text-left">+ <span className="min-w-0 flex-1 truncate font-sans text-left">{currentProject ? projectDisplayName(currentProject) : S.common.loading}</span><span className="text-gray-400">@@ -1867,7 +1867,7 @@ export function Sidebar({p.projectId === currentProject?.projectId ? "font-semibold" : ""}`}>- <span className="truncate">{projectDisplayName(p)}</span>+ <span className="truncate font-sans">{projectDisplayName(p)}</span><Badge tone="gray">{p.role}</Badge></button>))}@@ -1917,7 +1917,7 @@ export function Sidebar({<div className="shrink-0 px-2 pb-2 pt-2"><buttontype="button"- title={newChatTitle}+ data-tooltip={newChatTitle}onClick={() => newChat()}className={`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors duration-150 ${activeSessionId === DRAFT_SESSION_ID@@ -1925,7 +1925,7 @@ export function Sidebar({: "text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"}`}>- <span className="text-gray-500 dark:text-gray-400">+ <span className="ui-icon-decor text-gray-500 dark:text-gray-400" data-role="nav"><Icon d={NEW_CHAT_ICON} /></span>{S.chat.newSessionMenu}@@ -1942,8 +1942,12 @@ export function Sidebar({(each row's sr-only Agent name) anchor and scroll inside it — anchored to theinitial containing block instead, rows past the fold would bypass thisoverflow-y-auto and stretch the **document**, so expanding "More" / a source- folder made the whole page scroll (composer pushed up, blank space below). */}- <div className="relative min-h-0 flex-1 overflow-y-auto px-2 pb-2">+ folder made the whole page scroll (composer pushed up, blank space below).+ overflow-x-clip: the list scrolls one way only. With overflow-y set, a horizontal+ overflow of a single pixel — a group header's actions in a theme with wider type or+ roomier controls — would otherwise turn into a sideways scrollbar under the list;+ nothing here is meant to be reached by scrolling sideways. */}+ <div className="relative min-h-0 flex-1 overflow-y-auto overflow-x-clip px-2 pb-2"><nav className="space-y-0.5">{/* Expand/collapse SLIDE: grid-template-rows tweens between 0fr and 1fr with theinner overflow-hidden clipping the rows (the skills/models-page convention) —@@ -1984,7 +1988,10 @@ export function Sidebar({aria-disabled="true"className="relative flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-gray-400 dark:text-gray-600">- <span className="text-gray-300 dark:text-gray-700">+ <span+ className="ui-icon-decor text-gray-300 dark:text-gray-700"+ data-role="nav"+ ><Icon d={item.icon} /></span>{item.label}@@ -2014,7 +2021,10 @@ export function Sidebar({}`}>- <span className="text-gray-500 dark:text-gray-400">+ <span+ className="ui-icon-decor text-gray-500 dark:text-gray-400"+ data-role="nav"+ ><Icon d={item.icon} /></span>{item.label}@@ -2042,7 +2052,7 @@ export function Sidebar({onClick={toggleNavGroup}aria-expanded={!navCollapsed}aria-label={navCollapsed ? S.nav.expandGroup : S.nav.collapseGroup}- title={navCollapsed ? S.nav.expandGroup : S.nav.collapseGroup}+ data-tooltip={navCollapsed ? S.nav.expandGroup : S.nav.collapseGroup}className="flex h-4 w-full items-center justify-center rounded-md bg-gray-200/70 text-gray-400 transition-colors duration-150 hover:bg-gray-300/60 hover:text-gray-700 dark:bg-gray-800/70 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-300"><ChevronDown@@ -2090,7 +2100,7 @@ export function Sidebar({}`}><span- className={`min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${+ className={`ui-eyebrow min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${searchOpen ? "opacity-0" : "opacity-100"}`}>@@ -2123,7 +2133,7 @@ export function Sidebar({/><buttontype="button"- title={S.chat.searchClear}+ data-tooltip={S.chat.searchClear}aria-label={S.chat.searchClear}onClick={closeSearch}className="flex h-4 w-4 shrink-0 items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-300"@@ -2134,7 +2144,7 @@ export function Sidebar({) : (<buttontype="button"- title={searchTitle}+ data-tooltip={searchTitle}aria-label={S.chat.searchSessions}onClick={() => setSearchOpen(true)}className={headerControlClass(false)}@@ -2150,7 +2160,7 @@ export function Sidebar({button={<buttontype="button"- title={S.chat.listSettings}+ data-tooltip={S.chat.listSettings}aria-label={S.chat.listSettings}aria-haspopup="menu"aria-expanded={listSettingsOpen}@@ -2224,7 +2234,7 @@ export function Sidebar({{newEntity === "agent" ? (<buttontype="button"- title={newEntityLabel}+ data-tooltip={newEntityLabel}aria-label={newEntityLabel}onClick={() => {navigate("/agents", { state: { create: true } });@@ -2237,7 +2247,7 @@ export function Sidebar({) : newEntity === "chat" ? (<buttontype="button"- title={newEntityLabel}+ data-tooltip={newEntityLabel}aria-label={newEntityLabel}onClick={() => newChat()}className={headerControlClass(false)}@@ -2261,7 +2271,7 @@ export function Sidebar({trigger={(open, toggle) => (<buttontype="button"- title={newEntityLabel}+ data-tooltip={newEntityLabel}aria-label={newEntityLabel}aria-expanded={open}onClick={toggle}@@ -2284,7 +2294,10 @@ export function Sidebar({open={searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)}onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}icon={- <span className="shrink-0 text-gray-400 dark:text-gray-500">+ <span+ className="ui-icon-decor shrink-0 text-gray-400 dark:text-gray-500"+ data-role="group"+ ><Icon d={NEW_CHAT_ICON} size={ICON_SIZE.groupHeaderGlyph} /></span>}@@ -2363,7 +2376,7 @@ export function Sidebar({{/* New chat: enters draft state directly with this group's Agent (all options live on the draft input card) */}<buttontype="button"- title={S.chat.newSessionMenu}+ data-tooltip={S.chat.newSessionMenu}aria-label={S.chat.newSessionMenu}onClick={() => newChat({ agentId: agent.agentId })}className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"@@ -2372,7 +2385,8 @@ export function Sidebar({</button><buttontype="button"- title={S.agent.settings}+ data-tooltip={S.agent.settings}+ aria-label={S.agent.settings}onClick={() => go(`/agents/${agent.agentId}`)}className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200">@@ -2454,7 +2468,10 @@ export function Sidebar({onToggle={() => toggleGroup(group.key, foldedOnly !== undefined)}icon={/* Folder opens and closes with the group */- <span className="shrink-0 text-gray-400 dark:text-gray-500">+ <span+ className="ui-icon-decor shrink-0 text-gray-400 dark:text-gray-500"+ data-role="group"+ ><Icond={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON}size={ICON_SIZE.groupHeaderGlyph}@@ -2480,7 +2497,7 @@ export function Sidebar({{/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the Project's new-chat default, like any other new chat */}<buttontype="button"- title={S.chat.newSessionInWorkspace}+ data-tooltip={S.chat.newSessionInWorkspace}aria-label={S.chat.newSessionInWorkspace}onClick={() =>newChat({@@ -2546,7 +2563,10 @@ export function Sidebar({open={!collapsed}onToggle={() => toggleGroup(group.key)}icon={- <span className="shrink-0 text-gray-400 dark:text-gray-500">+ <span+ className="ui-icon-decor shrink-0 text-gray-400 dark:text-gray-500"+ data-role="group"+ ><Icon d={GROUP_MODE_ICONS.time} size={ICON_SIZE.groupHeaderGlyph} /></span>}@@ -2622,7 +2642,7 @@ export function Sidebar({? {// The dot alone is mysterious: name what is waiting on the trigger (hover// tooltip + accessible name), in the update row's own wording.- title: badges.softwareNote,+ "data-tooltip": badges.softwareNote,"aria-label": `${user?.displayName ?? user?.userId ?? ""} · ${badges.softwareNote}`,}: {})}@@ -2637,7 +2657,7 @@ export function Sidebar({it, and the trigger's tooltip/label above say what it is. */}{badges.software !== null && <UpdateDot />}</UserAvatar>- <span className="min-w-0 flex-1 truncate text-sm font-medium">+ <span className="min-w-0 flex-1 truncate font-sans text-sm font-medium">{user?.displayName ?? user?.userId}</span>{user?.isAdmin && (@@ -2834,7 +2854,7 @@ function DraftRow({<TruncatedscrollRevealtext={title}- className={`min-w-0 flex-1 text-sm ${+ className={`min-w-0 flex-1 font-sans text-sm ${active? "font-medium text-gray-900 dark:text-gray-100": "text-gray-700 dark:text-gray-300"@@ -2844,7 +2864,7 @@ function DraftRow({<div className="flex shrink-0 items-center"><buttontype="button"- title={S.chat.deleteDraft}+ data-tooltip={S.chat.deleteDraft}aria-label={S.chat.deleteDraft}onClick={onDelete}className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 hover:bg-gray-300/60 hover:text-red-600 focus-visible:opacity-100 group-hover:opacity-100 dark:hover:bg-gray-700 dark:hover:text-red-400"@@ -2883,7 +2903,7 @@ function GroupBlock({{dropEdge !== null && (<divaria-hidden- className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${+ className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-accent ${dropEdge === "above" ? "top-1" : "-bottom-1"}`}/>@@ -2908,7 +2928,7 @@ function GroupPinButton({ pinned, onToggle }: { pinned: boolean; onToggle: () =>return (<buttontype="button"- title={pinned ? S.nav.unpinGroup : S.nav.pinGroup}+ data-tooltip={pinned ? S.nav.unpinGroup : S.nav.pinGroup}aria-label={S.nav.pinGroup}aria-pressed={pinned}onClick={onToggle}@@ -3043,7 +3063,7 @@ function SessionRow({{dropEdge !== null && (<divaria-hidden- className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${+ className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-accent ${dropEdge === "above" ? "-top-px" : "-bottom-px"}`}/>@@ -3079,7 +3099,7 @@ function SessionRow({className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left">{agentHint !== undefined && (- <span title={agentHint} className="flex shrink-0 items-center">+ <span data-tooltip={agentHint} className="flex shrink-0 items-center"><AgentAvatar id={s.agentId} name={agentHint} size={14} className="rounded" />{/* The avatar is aria-hidden and title only serves pointer users: expose the Agent name to keyboard/screen-reader users as visually hidden text inside the row button. */}<span className="sr-only">{agentHint}</span>@@ -3095,7 +3115,7 @@ function SessionRow({<TruncatedscrollRevealtext={s.title ?? S.chat.defaultSessionTitle}- className={`min-w-0 flex-1 text-sm ${+ className={`min-w-0 flex-1 font-sans text-sm ${active? "font-medium text-gray-900 dark:text-gray-100": s.archived@@ -3111,7 +3131,7 @@ function SessionRow({and in sr text, which is what lets them recede this far. */}{/* Pinned indicator: a dim pin after the title (unpin lives in the row menu). */}{pinned && canPin && (- <span title={S.chat.pinnedSession} className={`shrink-0 ${toneInk.muted}`}>+ <span data-tooltip={S.chat.pinnedSession} className={`shrink-0 ${toneInk.muted}`}><Icon d={PIN_ICON} size={ICON_SIZE.rowMark} /><span className="sr-only">{S.chat.pinnedSession}</span></span>@@ -3121,7 +3141,7 @@ function SessionRow({dialog lives in the row menu). */}{s.messagingChannel !== undefined && (<span- title={S.messaging.enabledIndicator[s.messagingChannel]}+ data-tooltip={S.messaging.enabledIndicator[s.messagingChannel]}className={`shrink-0 ${toneInk.muted}`}><Icon d={MESSAGING_RELAY_ICON} size={ICON_SIZE.rowMark} />@@ -3143,9 +3163,14 @@ function SessionRow({)}{/* No per-row source tag: subagent / scheduled Sessions live in their own labelled, collapsed folders, so a badge on the title would just repeat the folder. */}<StatusGlyph activity={activity} />+ {/* The count is a numeral in the attention ink, with no pill: a filled chip beside the+ title read as a second button and fought every theme's row. */}{s.pendingApprovalCount > 0 && (- <span title={S.chat.pendingApprovals(s.pendingApprovalCount)}>- <Badge tone="amber">{s.pendingApprovalCount}</Badge>+ <span+ data-tooltip={S.chat.pendingApprovals(s.pendingApprovalCount)}+ className={`shrink-0 text-xs font-semibold tabular-nums ${toneInk.attention}`}+ >+ {s.pendingApprovalCount}</span>)}</button>@@ -3246,7 +3271,7 @@ function GroupOverflowMenu({ onRename, onDelete }: { onRename: () => void; onDelglyph the dot columns line up with the rows' trailing slot below. */<buttontype="button"- title={S.chat.workspaceMenu}+ data-tooltip={S.chat.workspaceMenu}aria-label={S.chat.workspaceMenu}aria-haspopup="menu"aria-expanded={open}diff --git a/packages/web/src/components/layout/user-menu.tsx b/packages/web/src/components/layout/user-menu.tsxindex c3fb3b3d..630895c2 100644--- a/packages/web/src/components/layout/user-menu.tsx+++ b/packages/web/src/components/layout/user-menu.tsx@@ -14,7 +14,7 @@* it once a nickname stands in for it. Both anchors are avatars, and the rail's is nothing but* an avatar, so without the header the menu never says whose account its rows act on.*/-import { useState } from "react";+import { useEffect, useState } from "react";import type { ReactNode } from "react";import { useNavigate } from "react-router";import { S } from "../../lib/strings";@@ -27,6 +27,8 @@ import type { DropdownPortal } from "../ui/dropdown";import { UpdateRow } from "../account/update-row";import { openUpdateModal } from "../../lib/use-update-flow";import { SettingsDialog } from "../../features/settings/settings-dialog";+import { onSettingsRequest } from "../../features/settings/settings-request";+import type { SettingsSectionKey } from "../../lib/settings-sections";export function UserMenu({trigger,@@ -53,8 +55,21 @@ export function UserMenu({const { user, logout, desktopMode } = useAuth();const [open, setOpen] = useState(false);const [settingsOpen, setSettingsOpen] = useState(false);+ /** The page a request asked for; the menu's own row asks for none (the viewer's first). */+ const [settingsSection, setSettingsSection] = useState<SettingsSectionKey | undefined>(undefined);const [confirmingLogout, setConfirmingLogout] = useState(false);+ // Settings can be asked for from outside this menu (see settings-request.ts): the request+ // opens the same dialog, on the page it names.+ useEffect(+ () =>+ onSettingsRequest(({ section }) => {+ setSettingsSection(section);+ setSettingsOpen(true);+ }),+ [],+ );+return (<><Dropdown@@ -98,6 +113,7 @@ export function UserMenu({className={menuItemClass}onClick={() => {setOpen(false);+ setSettingsSection(undefined);setSettingsOpen(true);}}>@@ -133,7 +149,11 @@ export function UserMenu({)}</div></Dropdown>- <SettingsDialog open={settingsOpen} onClose={() => setSettingsOpen(false)} />+ <SettingsDialog+ open={settingsOpen}+ onClose={() => setSettingsOpen(false)}+ {...(settingsSection !== undefined ? { section: settingsSection } : {})}+ />{/* Signing out is confirmed first: the row sits in a menu of harmless entries, and aslip would end the session and land on the login page. Mounted beside the settingsdialog, outside the dropdown, so it outlives the menu that opened it. */}diff --git a/packages/web/src/components/ui/button.tsx b/packages/web/src/components/ui/button.tsxindex e8b89318..dc54ed65 100644--- a/packages/web/src/components/ui/button.tsx+++ b/packages/web/src/components/ui/button.tsx@@ -9,7 +9,7 @@ type Size = "sm" | "md" | "icon";const variantClass: Record<Variant, string> = {// primary uses the theme accent variable (defaults to neutral gray/white, switching with light/dark; becomes that color once an accent is selected).primary:- "bg-[var(--accent-bg)] text-[var(--accent-fg)] border border-[var(--accent-bg)] " ++ "bg-accent text-accent-fg border border-accent " +"transition-opacity hover:opacity-90 disabled:opacity-50",secondary:"bg-white text-gray-800 border border-gray-300 hover:bg-gray-50 " +@@ -38,10 +38,23 @@ export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {size?: Size;}-export function Button({ variant = "secondary", size = "md", className, ...rest }: ButtonProps) {+export function Button({+ variant = "secondary",+ size = "md",+ className,+ title,+ ...rest+}: ButtonProps) {+ // `title` is the hover hint, shown in the shared tooltip (tooltip.tsx) rather than the+ // browser's own. The native attribute also named a wordless button; the shared tooltip names+ // nothing, so an icon button whose only label was its title keeps it as its accessible name.+ const nameless =+ size === "icon" && rest["aria-label"] === undefined && rest["aria-labelledby"] === undefined;return (<buttontype="button"+ data-tooltip={title}+ {...(nameless && title !== undefined ? { "aria-label": title } : {})}className={`${buttonBase} disabled:cursor-not-allowed disabled:opacity-60 ${variantClass[variant]} ${sizeClass[size]} ${className ?? ""}`}{...rest}/>diff --git a/packages/web/src/components/ui/chart/geom.ts b/packages/web/src/components/ui/chart/geom.tsnew file mode 100644index 00000000..f5f189a3--- /dev/null+++ b/packages/web/src/components/ui/chart/geom.ts@@ -0,0 +1,74 @@+/**+ * The geometry the chart primitives draw with — the part of a chart's layout a theme reaches+ * through its tokens: how a line runs between its points (`--ui-chart-curve`) and how wide a+ * bar is in its band (`--ui-chart-bar-fill`). Chart-specific layout (a plot's padding and+ * scales, stacked segments, hit bands, the hover bubble) stays with the charts that use it.+ */+import type { ChartCurve } from "../../../lib/chart-style";++/** Path coordinates keep 2 decimal places: the path string stays short and readable, and is easy to assert on in unit tests. */+export const roundCoord = (v: number): number => Math.round(v * 100) / 100;+const rnd = roundCoord;++/**+ * A series' path through its points, drawn the way the theme's `--ui-chart-curve` says:+ * - `linear`: `M x0,y0 L x1,y1 …`, straight segments (identical to the original cost line);+ * - `step`: a level run from each point to halfway to the next, then a vertical jump — the+ * value holds over its own cell, as a bar would;+ * - `smooth`: a cubic through every point (Catmull-Rom tangents), with each control point held+ * between its segment's two values, so the curve never swings above a peak or below a+ * trough the data does not have.+ */+export function curvePath(+ points: ReadonlyArray<readonly [number, number]>,+ curve: ChartCurve = "linear",+): string {+ if (points.length === 0) return "";+ if (curve === "step") {+ const parts = [`M${points[0]![0]},${points[0]![1]}`];+ for (let i = 1; i < points.length; i++) {+ const [x0] = points[i - 1]!;+ const [x1, y1] = points[i]!;+ const mid = rnd((x0 + x1) / 2);+ parts.push(`H${mid} V${y1} H${x1}`);+ }+ return parts.join(" ");+ }+ if (curve === "smooth" && points.length > 2) {+ const parts = [`M${points[0]![0]},${points[0]![1]}`];+ for (let i = 0; i < points.length - 1; i++) {+ const p0 = points[Math.max(0, i - 1)]!;+ const p1 = points[i]!;+ const p2 = points[i + 1]!;+ const p3 = points[Math.min(points.length - 1, i + 2)]!;+ const lo = Math.min(p1[1], p2[1]);+ const hi = Math.max(p1[1], p2[1]);+ const clampY = (y: number) => Math.min(hi, Math.max(lo, y));+ const c1x = rnd(p1[0] + (p2[0] - p0[0]) / 6);+ const c1y = rnd(clampY(p1[1] + (p2[1] - p0[1]) / 6));+ const c2x = rnd(p2[0] - (p3[0] - p1[0]) / 6);+ const c2y = rnd(clampY(p2[1] - (p3[1] - p1[1]) / 6));+ parts.push(`C${c1x},${c1y} ${c2x},${c2y} ${p2[0]},${p2[1]}`);+ }+ return parts.join(" ");+ }+ return points.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x},${y}`).join(" ");+}++/**+ * Ceiling on bar width (**real CSS pixels**, since 1 canvas unit = 1 pixel):+ * with few points the bars never balloon past this — the extra space goes to+ * bar spacing.+ */+export const BAR_W = 25;++/**+ * Bar width that always fits the container (**no horizontal scrolling**): the theme's+ * `--ui-chart-bar-fill` share of the cell width (60% by default) — leaving ≥ 40% as spacing so adjacent bars never touch —+ * capped at BAR_W (few points must not balloon into slabs) and floored at 1px:+ * a dense range at fine granularity degrades to hairlines, not to overlap+ * (only a degenerate sub-1.7px cell can make the 1px floor fill its cell).+ */+export function fitBarWidth(step: number, fill = 0.6): number {+ return Math.max(1, Math.min(BAR_W, Math.floor(step * fill)));+}diff --git a/packages/web/src/components/ui/chart/index.ts b/packages/web/src/components/ui/chart/index.tsnew file mode 100644index 00000000..364906e5--- /dev/null+++ b/packages/web/src/components/ui/chart/index.ts@@ -0,0 +1,22 @@+/**+ * The chart primitives: every chart mark in the app is drawn by one of these (see marks.tsx).+ */+export {+ ChartArc,+ ChartArea,+ ChartAxis,+ ChartAxisBreak,+ ChartBar,+ ChartBarHit,+ ChartCursor,+ ChartGrid,+ ChartHit,+ ChartLine,+ ChartPoint,+ ChartSwatch,+ resolvePaint,+ useBarWidth,+} from "./marks";+export type { ChartPaint } from "./marks";+export { TimelineBar } from "./timeline-bar";+export { BAR_W, curvePath, fitBarWidth, roundCoord } from "./geom";diff --git a/packages/web/src/components/ui/chart/marks.tsx b/packages/web/src/components/ui/chart/marks.tsxnew file mode 100644index 00000000..096c7735--- /dev/null+++ b/packages/web/src/components/ui/chart/marks.tsx@@ -0,0 +1,459 @@+/**+ * The chart primitives: the one place a theme's chart tokens (lib/chart-style.ts) become marks.+ *+ * Every chart in the app — the cost center's requests, Token and cost charts, the context donut,+ * the score and activity sparklines — draws its bars, lines, areas, points, grid and axis+ * labels through these, and the Trace timeline its lanes through TimelineBar+ * (timeline-bar.tsx). A chart decides WHAT to draw — where a mark sits, which series it+ * belongs to, whether it is dimmed — and never HOW: the width of a bar in its band, its corner+ * radius, outline and fill opacity, a line's width and curve, a point's size, the fill under a+ * line and every colour come from the active theme here. A source guard (chart-marks.test.ts)+ * holds the charts to that.+ *+ * Each primitive writes `data-part` (and `data-series` where a series index exists), so a theme+ * may still restyle a part in CSS — a dashed grid, square points (a point is a rect whose `rx`+ * is its radius, so `rx: 0` squares it), round joins.+ *+ * A mark's colour is a `ChartPaint`: a palette slot, one of the named roles (the reference line,+ * the Token kinds), or an `ink` — a Tailwind text class the mark paints with as currentColor,+ * for marks whose colour is a neutral or a state rather than an identity (the folded "rest"+ * series, the cost line, a near-limit ring).+ */+import type { CSSProperties, MouseEventHandler, ReactNode } from "react";+import { seriesStroke, useChartStyle } from "../../../lib/chart-style";+import type { ChartStyle } from "../../../lib/chart-style";+import { curvePath, fitBarWidth } from "./geom";++export type ChartPaint =+ /** Palette slot `series` (0-based; cycles past the last). */+ | { series: number }+ /** A named colour: the reference line, or one of the Token kinds. */+ | { role: "ref" | "cacheRead" | "cacheWrite" | "output" }+ /**+ * A Tailwind text class; the mark paints with currentColor. `swatch` is the same colour as a+ * background class, for its legend swatch.+ */+ | { ink: string; swatch?: string };++/** A paint resolved against the theme: a colour for `style`, or the ink class. */+export function resolvePaint(+ chart: ChartStyle,+ paint: ChartPaint,+): { color?: string; className: string } {+ if ("series" in paint) return { color: seriesStroke(chart, paint.series), className: "" };+ if ("role" in paint) return { color: chart[paint.role], className: "" };+ return { className: paint.ink };+}++/** `data-series` for a paint: the 1-based slot, like the tokens (none for a role or an ink). */+const seriesAttr = (paint: ChartPaint) =>+ "series" in paint ? { "data-series": paint.series + 1 } : {};++/** The width a bar takes in a band of `band` px: the theme's fill share, capped and floored. */+export function useBarWidth(band: number): number {+ return fitBarWidth(band, useChartStyle().barFill);+}++/** The path of a bar whose top two corners round by `r` (clamped to its size). */+export function barPath(x: number, y: number, w: number, h: number, radius: number): string | null {+ const r = Math.max(0, Math.min(radius, w / 2, h));+ if (r === 0) return null;+ const right = x + w;+ const bottom = y + h;+ return `M${x},${bottom} V${y + r} A${r},${r} 0 0 1 ${x + r},${y} H${right - r} A${r},${r} 0 0 1 ${right},${y + r} V${bottom} Z`;+}++/**+ * A bar, centred on `cx` in a band `band` px wide, from `y` down `height` px. Its width is the+ * theme's share of the band; a bar that tops its stack (`top`) rounds its top corners by the+ * theme's radius; its fill takes the theme's bar opacity, and an outline the theme's bar+ * stroke (in the bar's own colour unless the theme names one). `opacity` dims the whole mark+ * (a highlight fading the rest).+ */+export function ChartBar({+ cx,+ band,+ y,+ height,+ paint,+ top = true,+ opacity,+ className = "",+}: {+ cx: number;+ band: number;+ y: number;+ height: number;+ paint: ChartPaint;+ top?: boolean;+ opacity?: number;+ className?: string;+}) {+ const chart = useChartStyle();+ const width = fitBarWidth(band, chart.barFill);+ const x = cx - width / 2;+ const { color, className: ink } = resolvePaint(chart, paint);+ const outline =+ chart.barStroke > 0+ ? {+ stroke: chart.barStrokeColor === "series" ? "currentColor" : chart.barStrokeColor,+ strokeWidth: chart.barStroke,+ }+ : {};+ const common = {+ "data-part": "bar",+ ...seriesAttr(paint),+ className: `${ink} ${className}`.trim(),+ fill: "currentColor",+ ...(chart.barOpacity < 1 ? { fillOpacity: chart.barOpacity } : {}),+ ...outline,+ opacity,+ style: color !== undefined ? { color } : undefined,+ };+ const d = top ? barPath(x, y, width, height, chart.barRadius) : null;+ return d === null ? (+ <rect x={x} y={y} width={width} height={height} {...common} />+ ) : (+ <path d={d} {...common} />+ );+}++/**+ * A series line through `points`, in the theme's curve and line width (`scale` shrinks it for+ * a sparkline). `dash` is data, not decoration: it tells a line on the right-hand axis from the+ * bars it shares a colour with. `round` gives it round caps and joins (the sparklines).+ */+export function ChartLine({+ points,+ paint,+ scale = 1,+ dash,+ round = false,+ opacity,+ className = "",+}: {+ points: ReadonlyArray<readonly [number, number]>;+ paint: ChartPaint;+ scale?: number;+ dash?: string;+ round?: boolean;+ opacity?: number;+ className?: string;+}) {+ const chart = useChartStyle();+ const { color, className: ink } = resolvePaint(chart, paint);+ return (+ <path+ data-part="series"+ {...seriesAttr(paint)}+ d={curvePath(points, chart.curve)}+ fill="none"+ stroke="currentColor"+ strokeWidth={chart.lineWidth * scale}+ {...(dash !== undefined ? { strokeDasharray: dash } : {})}+ {...(round ? { strokeLinecap: "round" as const, strokeLinejoin: "round" as const } : {})}+ opacity={opacity}+ className={`${ink} ${className}`.trim() || undefined}+ style={color !== undefined ? { color } : undefined}+ />+ );+}++/**+ * The fill under a line: the line's path in the theme's curve, dropped to `baseY` and closed.+ * Its opacity is the theme's area opacity times `strength` (a chart dims it while a point is+ * singled out, or draws a sparkline's a little stronger).+ */+export function ChartArea({+ points,+ baseY,+ paint,+ strength = 1,+}: {+ points: ReadonlyArray<readonly [number, number]>;+ baseY: number;+ paint: ChartPaint;+ strength?: number;+}) {+ const chart = useChartStyle();+ if (points.length === 0) return null;+ const { color, className: ink } = resolvePaint(chart, paint);+ const first = points[0]!;+ const last = points[points.length - 1]!;+ return (+ <path+ data-part="area"+ {...seriesAttr(paint)}+ d={`${curvePath(points, chart.curve)} L${last[0]},${baseY} L${first[0]},${baseY} Z`}+ fill="currentColor"+ stroke="none"+ opacity={chart.areaOpacity * strength}+ className={ink || undefined}+ style={color !== undefined ? { color } : undefined}+ />+ );+}++/**+ * A data point at (cx, cy), at the theme's point radius (`scale` for a sparkline; `grow` for+ * the hovered one). Drawn as a rect whose corner radius is its radius — a circle — so a theme+ * can square it in CSS.+ */+export function ChartPoint({+ cx,+ cy,+ paint,+ scale = 1,+ grow = false,+ opacity,+}: {+ cx: number;+ cy: number;+ paint: ChartPaint;+ scale?: number;+ grow?: boolean;+ opacity?: number;+}) {+ const chart = useChartStyle();+ const { color, className: ink } = resolvePaint(chart, paint);+ const r = chart.pointRadius * scale + (grow ? 1.5 : 0);+ return (+ <rect+ data-part="point"+ {...seriesAttr(paint)}+ x={cx - r}+ y={cy - r}+ width={2 * r}+ height={2 * r}+ rx={r}+ fill="currentColor"+ opacity={opacity}+ className={ink || undefined}+ style={color !== undefined ? { color } : undefined}+ />+ );+}++/**+ * An arc of a ring (the context donut): `length` px of the circumference from `offset`, clockwise+ * from twelve o'clock, `width` thick. A series arc takes its paint; the ring's empty track is a+ * `grid` part painted with an ink at `trackOpacity`.+ */+export function ChartArc({+ cx,+ cy,+ r,+ width,+ paint,+ length,+ offset = 0,+ track = false,+ trackOpacity,+}: {+ cx: number;+ cy: number;+ r: number;+ width: number;+ paint: ChartPaint;+ /** Omitted for the whole ring. */+ length?: number;+ offset?: number;+ track?: boolean;+ trackOpacity?: number;+}) {+ const chart = useChartStyle();+ const { color, className: ink } = resolvePaint(chart, paint);+ const circumference = 2 * Math.PI * r;+ return (+ <circle+ data-part={track ? "grid" : "series"}+ {...(track ? {} : seriesAttr(paint))}+ cx={cx}+ cy={cy}+ r={r}+ fill="none"+ stroke="currentColor"+ strokeWidth={width}+ {...(trackOpacity !== undefined ? { strokeOpacity: trackOpacity } : {})}+ {...(length !== undefined+ ? {+ strokeDasharray: `${length} ${circumference}`,+ strokeDashoffset: offset,+ transform: `rotate(-90 ${cx} ${cy})`,+ }+ : {})}+ className={ink || undefined}+ style={color !== undefined ? { color } : undefined}+ />+ );+}++/** A horizontal grid line across the plot, in the chart's recessive gray. */+export function ChartGrid({ x1, x2, y }: { x1: number; x2: number; y: number }) {+ return (+ <line+ data-part="grid"+ x1={x1}+ x2={x2}+ y1={y}+ y2={y}+ className="stroke-gray-200 dark:stroke-gray-800"+ strokeWidth={1}+ />+ );+}++/** The vertical line under the pointer on a line chart: chrome, not data, so it has no part. */+export function ChartCursor({ x, y1, y2 }: { x: number; y1: number; y2: number }) {+ return (+ <line+ x1={x}+ x2={x}+ y1={y1}+ y2={y2}+ className="stroke-gray-300 dark:stroke-gray-700"+ strokeWidth={1}+ />+ );+}++/** An axis label (a tick value or a date), in the axis ink at the chart's small size. */+export function ChartAxis({+ x,+ y,+ anchor,+ children,+}: {+ x: number;+ y: number;+ anchor: "start" | "middle" | "end";+ children: ReactNode;+}) {+ return (+ <text+ data-part="axis"+ x={x}+ y={y}+ textAnchor={anchor}+ className="fill-gray-400 dark:fill-gray-500"+ fontSize={9}+ >+ {children}+ </text>+ );+}++/**+ * The "//" on the x axis between two points that are not neighbours in time: two short slashes+ * centred on `x`, just across the baseline at `y`. Never hoverable.+ */+export function ChartAxisBreak({ x, y }: { x: number; y: number }) {+ return (+ <g+ data-part="axis"+ className="pointer-events-none stroke-gray-400 dark:stroke-gray-500"+ strokeWidth={1}+ >+ {[-2, 2].map((dx) => {+ const cx = x + dx / 2;+ return <line key={dx} x1={cx - 2} y1={y + 3} x2={cx + 2} y2={y - 3} />;+ })}+ </g>+ );+}++/** A transparent hit area: pointer handling for a mark, never drawn. */+export function ChartHit({+ x,+ y,+ width,+ height,+ cursor = "crosshair",+ onMouseEnter,+ onMouseLeave,+}: {+ x: number;+ y: number;+ width: number;+ height: number;+ cursor?: "crosshair" | "pointer";+ onMouseEnter?: MouseEventHandler<SVGRectElement>;+ onMouseLeave?: MouseEventHandler<SVGRectElement>;+}) {+ return (+ <rect+ x={x}+ y={y}+ width={width}+ height={height}+ fill="transparent"+ className={cursor === "pointer" ? "cursor-pointer" : "cursor-crosshair"}+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ />+ );+}++/**+ * The hit area of one bar (or one stacked segment): as wide as the bar the theme draws in that+ * band, so the pointer finds exactly the mark it sees.+ */+export function ChartBarHit({+ cx,+ band,+ y,+ height,+ onMouseEnter,+ onMouseLeave,+}: {+ cx: number;+ band: number;+ y: number;+ height: number;+ onMouseEnter?: MouseEventHandler<SVGRectElement>;+ onMouseLeave?: MouseEventHandler<SVGRectElement>;+}) {+ const width = useBarWidth(band);+ return (+ <ChartHit+ x={cx - width / 2}+ y={y}+ width={width}+ height={height}+ cursor="pointer"+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ />+ );+}++/** A legend or bubble swatch in a paint: a square for a bar series, a dash for a line. */+export function ChartSwatch({+ paint,+ shape = "square",+ className = "",+}: {+ paint: ChartPaint;+ /** square / block: a series (sharper or softer corners); chip: a wider bar swatch; dash / tick: a line, long or short. */+ shape?: "square" | "block" | "dash" | "tick" | "chip";+ className?: string;+}) {+ const chart = useChartStyle();+ const { color } = resolvePaint(chart, paint);+ const ink = "ink" in paint ? (paint.swatch ?? "") : "";+ const size =+ shape === "dash"+ ? "h-0.5 w-3 rounded-sm"+ : shape === "tick"+ ? "h-0.5 w-2 rounded-sm"+ : shape === "block"+ ? "h-2 w-2 rounded-sm"+ : shape === "chip"+ ? "h-2 w-3 rounded-sm"+ : "h-2 w-2 rounded-[2px]";+ const style: CSSProperties | undefined =+ color !== undefined ? { backgroundColor: color } : undefined;+ return (+ <span className={`inline-block shrink-0 ${size} ${ink} ${className}`.trim()} style={style} />+ );+}diff --git a/packages/web/src/components/ui/chart/timeline-bar.tsx b/packages/web/src/components/ui/chart/timeline-bar.tsxnew file mode 100644index 00000000..78cd2c74--- /dev/null+++ b/packages/web/src/components/ui/chart/timeline-bar.tsx@@ -0,0 +1,58 @@+/**+ * A Trace timeline bar: the HTML twin of ChartBar, for the lanes the Trace view lays out with+ * absolutely positioned spans. The chart places it (`place`: left and width along the lane)+ * and says what it is (`paint`); the theme decides how it looks — its colour, corner radius,+ * outline (drawn inside the box, so it never changes the bar's size or position) and fill+ * opacity (applied to the fill alone, so a dimmed bar's own opacity class still works).+ *+ * Everything else a lane needs from a bar — the pointer handlers, the jump on click, the+ * accessible name of a data mark, a ring for a failure, a pulse while it runs — passes through.+ */+import type { CSSProperties, HTMLAttributes } from "react";+import { useChartStyle } from "../../../lib/chart-style";+import { resolvePaint } from "./marks";+import type { ChartPaint } from "./marks";++export function TimelineBar({+ paint,+ place,+ className = "",+ ...rest+}: {+ paint: ChartPaint;+ /** Where the bar sits along its lane (left / width / margin), from the chart's time scale. */+ place: CSSProperties;+ className?: string;+} & Omit<HTMLAttributes<HTMLSpanElement>, "className" | "style" | "color">) {+ const chart = useChartStyle();+ const { color, className: ink } = resolvePaint(chart, paint);+ // A paint with an ink class carries its colour as a background class (`swatch`); the mark+ // itself only ever sets the fill here.+ const fillClass = "ink" in paint ? (paint.swatch ?? "") : "";+ const fill =+ color === undefined+ ? undefined+ : chart.barOpacity < 1+ ? `color-mix(in srgb, ${color} ${Math.round(chart.barOpacity * 100)}%, transparent)`+ : color;+ const outlineColor =+ chart.barStrokeColor === "series" ? (color ?? "currentColor") : chart.barStrokeColor;+ const style: CSSProperties = {+ ...place,+ ...(fill !== undefined ? { backgroundColor: fill } : {}),+ ...(chart.barRadius > 0 ? { borderRadius: chart.barRadius } : {}),+ ...(chart.barStroke > 0+ ? { boxShadow: `inset 0 0 0 ${chart.barStroke}px ${outlineColor}` }+ : {}),+ };+ return (+ <span+ data-part="bar"+ {...("series" in paint ? { "data-series": paint.series + 1 } : {})}+ {...rest}+ // The ink class (text-*) makes currentColor the bar's colour, for an outline in it.+ className={`absolute inset-y-0 min-w-[2px] ${fillClass} ${ink} ${className}`.trim()}+ style={style}+ />+ );+}diff --git a/packages/web/src/components/ui/copy-button.tsx b/packages/web/src/components/ui/copy-button.tsxindex 45534f8e..43b5a260 100644--- a/packages/web/src/components/ui/copy-button.tsx+++ b/packages/web/src/components/ui/copy-button.tsx@@ -6,10 +6,10 @@* reached the clipboard (writeClipboard reports that), so a copy the browser refused* never reads as one that succeeded;* - the feedback is ALWAYS shown AT THE BUTTON, and it is the icon alone: copy swaps to- * the check for COPIED_MS and the tooltip flips to "已复制" (#312 — no transient- * "已复制" text is rendered, and the feedback never replaces an unrelated label/title- * elsewhere). A control that keeps a visible text label (e.g. "复制 Prompt") keeps it- * unchanged and swaps only its glyph — see CopyCheckGlyph + useCopied;+ * the check for COPIED_MS. No text changes anywhere — not a label, not the tooltip, which+ * keeps naming the action (#312). A control that keeps a visible text label (e.g.+ * "复制 Prompt") keeps it unchanged and swaps only its glyph — see CopyCheckGlyph ++ * useCopied;* - the icon swap is silent, so every copy affordance also renders a CopiedStatus live* region beside itself — that is the screen-reader half of the same feedback.*/@@ -19,7 +19,7 @@ import { S } from "../../lib/strings";import { STAT_ICONS } from "../../lib/stat-icons";import { GlyphIcon } from "./glyph-icon";-/** How long the copied state (check icon + flipped tooltip) stays after a click. */+/** How long the copied state (the check icon) stays after a click. */const COPIED_MS = 1500;/**@@ -67,8 +67,8 @@ export function CopyCheckGlyph({ copied, size }: { copied: boolean; size?: numbe/*** Screen-reader half of the copy feedback, rendered NEXT TO the control (never inside it,* so it joins neither the visible label nor the accessible name). The check glyph is- * `aria-hidden` and the tooltip flip is never announced — a `title` only contributes when- * there is no `aria-label` — so without this region the confirmation is silent. The region+ * `aria-hidden` and the tooltip names the action, not the result, so without this region the+ * confirmation is silent. The region* is always rendered and merely filled on copy: a live region announces changes to its* content, so it has to exist before the text appears.*@@ -103,7 +103,7 @@ export function CopyButton({}: {/** The string to copy, or a getter for content computed at click time (e.g. a formatted stats line). */text: string | (() => string);- /** Accessible name / idle tooltip for the copy action (the tooltip flips to "已复制" while copied). */+ /** Accessible name and tooltip of the copy action; neither changes while copied. */label: string;/** Overrides the compact default look (e.g. the reply row's fixed-size button). */className?: string;@@ -113,7 +113,7 @@ export function CopyButton({<><buttontype="button"- title={copied ? S.common.copied : label}+ data-tooltip={label}aria-label={label}onClick={() => flash(typeof text === "function" ? text() : text)}className={className}diff --git a/packages/web/src/components/ui/drawer.tsx b/packages/web/src/components/ui/drawer.tsxindex 2efafaa0..ffb1de3a 100644--- a/packages/web/src/components/ui/drawer.tsx+++ b/packages/web/src/components/ui/drawer.tsx@@ -44,7 +44,11 @@ export function Drawer({ open, side = "left", title, onClose, children, widthClaif (!open) return null;return (<div className="fixed inset-0 z-50">- <div className="anim-fade absolute inset-0 bg-black/45" onMouseDown={onClose} />+ <div+ // ui-scrim: the dimmed layer behind the drawer; a theme may blur the page through it.+ className="ui-scrim anim-fade absolute inset-0 bg-[var(--ui-overlay-backdrop)]"+ onMouseDown={onClose}+ /><divclassName={`absolute inset-y-0 flex w-[80vw] flex-col bg-white shadow-xl dark:bg-gray-900 ${widthClass ?? "max-w-xs"} ${side === "left"diff --git a/packages/web/src/components/ui/dropdown.tsx b/packages/web/src/components/ui/dropdown.tsxindex d3c6e19c..c945c03f 100644--- a/packages/web/src/components/ui/dropdown.tsx+++ b/packages/web/src/components/ui/dropdown.tsx@@ -38,14 +38,14 @@ import { createPortal } from "react-dom";import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";import { FOCUSABLE_SELECTOR, isTopEscLayer, popEscLayer, pushEscLayer } from "./modal";import { scrollMovesAnchor } from "../../lib/context-menu";+import { menuPanelClass, menuRowClass, menuRowTone } from "./field";/** Gap between the trigger and the portaled panel, and the panel's minimum distance from the viewport edge (px). */const PANEL_GAP = 4;const VIEWPORT_MARGIN = 8;/** The panel's plain row: full-width, left-aligned, hover-filled. Shared so menus opened from different anchors cannot drift apart on density. */-export const menuItemClass =- "block w-full px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800";+export const menuItemClass = `block ${menuRowClass} text-sm ${menuRowTone()}`;/** Portal docking: which way the panel opens and which of its edges lines up with the trigger. */export interface DropdownPortal {@@ -305,7 +305,7 @@ export function Dropdown({// Portaled panels sit at z-[60], above a Modal's z-50 overlay (a body portal appended// after the overlay would otherwise paint UNDER it and be unclickable); in-flow panels// keep the z-40 menu tier — they stack within their host's own context.- const panelClass = `anim-pop ${portal ? "z-[60]" : "z-40"} overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900 ${+ const panelClass = `ui-glass ${menuPanelClass} ${portal ? "z-[60]" : "z-40"} ${portal ? "" : "max-h-[70vh]"} ${menuClass ?? "left-0 top-full mt-1 w-64 max-w-[calc(100vw-2rem)] origin-top-left"}`;diff --git a/packages/web/src/components/ui/field.tsx b/packages/web/src/components/ui/field.tsxindex d7335a77..394f2e6c 100644--- a/packages/web/src/components/ui/field.tsx+++ b/packages/web/src/components/ui/field.tsx@@ -7,6 +7,7 @@*/import type { ReactNode } from "react";import { InfoPopover } from "./info-popover";+import { CheckIcon } from "./icons";/*** The control "look" shared by Input, Select and OptionMenu: rounded box, gray@@ -24,6 +25,38 @@ export const controlBase =/** Base padding/alignment/transition for a menu row (Select, OptionMenu, and the chat composer menus); callers add flex/block and the hover/selected colors. */export const menuRowClass = "w-full px-3 py-1.5 text-left transition-colors duration-150";+/**+ * The floating panel every picker and menu opens — Select's surface: a hairline box on the+ * overlay layer, one shadow step, a little padding above the first row and below the last.+ * Callers add position, width, z-layer and max height, and the `ui-glass` hook in the+ * component that opens the panel (a hook belongs to its host component, not to a string).+ */+export const menuPanelClass =+ "anim-pop overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900";++/**+ * A menu row's ink and fill: an action row, or a choice that is not the current one, fills on+ * hover; the current choice is filled and set in the medium weight (and carries ChoiceCheck).+ * The same two states in every picker, so a choice reads the same wherever it is made.+ */+export function menuRowTone(selected = false): string {+ return selected+ ? "bg-gray-100 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800";+}++/**+ * The current choice's mark, Select's check. It sits in a fixed slot at the row's end, so the+ * rows of one list align whether or not they carry it.+ */+export function ChoiceCheck({ on }: { on: boolean }) {+ return (+ <span aria-hidden className="flex w-3 shrink-0 justify-center">+ {on && <CheckIcon className="text-gray-500 dark:text-gray-400" />}+ </span>+ );+}+/*** The red "*" that marks a field as required, and the only place it is spelled. A field is* required when submitting without it is refused — never because its label sounds mandatory —diff --git a/packages/web/src/components/ui/file-tree.tsx b/packages/web/src/components/ui/file-tree.tsxindex ff9c9f61..8a07add4 100644--- a/packages/web/src/components/ui/file-tree.tsx+++ b/packages/web/src/components/ui/file-tree.tsx@@ -234,7 +234,7 @@ export function FileTree<Row extends FileTreeRow>({// A retained row carries no path: rowElement() and a caller's pointer hit test both// resolve a row by this attribute, and neither may land on one that is on its way out.{...(retained ? {} : { "data-tree-path": row.path, "data-tree-kind": row.kind })}- title={rowTitle?.(row) ?? row.path}+ data-tooltip={rowTitle?.(row) ?? row.path}aria-label={rowLabel?.(row)}{...(retained ? {} : { onClick: () => activate(row), onFocus: () => setFocused(row.path) })}style={{ paddingLeft: TREE_PAD_PX + row.depth * TREE_INDENT_PX }}diff --git a/packages/web/src/components/ui/form-picker.tsx b/packages/web/src/components/ui/form-picker.tsxindex e0bf1276..eda3f34c 100644--- a/packages/web/src/components/ui/form-picker.tsx+++ b/packages/web/src/components/ui/form-picker.tsx@@ -60,7 +60,7 @@ export function FormPickerTrigger({return (<buttontype="button"- title={title}+ data-tooltip={title}aria-label={ariaLabel}aria-haspopup={ariaHaspopup}aria-expanded={expanded}diff --git a/packages/web/src/components/ui/glyph-icon.tsx b/packages/web/src/components/ui/glyph-icon.tsxindex 1d50cb02..0bd03dc3 100644--- a/packages/web/src/components/ui/glyph-icon.tsx+++ b/packages/web/src/components/ui/glyph-icon.tsx@@ -1,6 +1,7 @@/**- * The app's one line-icon renderer: a 24x24 path stroked at 1.7 in currentColor, so the mark- * follows the caller's text colour and every glyph in the app carries the same weight. Icon+ * The app's one line-icon renderer: a 24x24 path in currentColor, stroked at the active theme's+ * `--ui-icon-stroke` (1.7 in the default theme), so the mark follows the caller's text colour and+ * every glyph in the app carries the same weight. Icon* paths live in the modules that own them — `lib/stat-icons.ts`, `components/ui/icons.tsx`,* `components/ui/group-list.tsx`, `components/ui/session-row-menu.tsx` — and the size comes from* the role-named scale in `lib/icon-scale.ts`.@@ -26,7 +27,9 @@ export function GlyphIcon({viewBox="0 0 24 24"fill={filled ? "currentColor" : "none"}stroke="currentColor"- strokeWidth="1.7"+ // A style, not the attribute: an SVG presentation attribute cannot read a custom property.+ // The fallback is the default theme's weight, for a page that has not loaded the theme CSS.+ style={{ strokeWidth: "var(--ui-icon-stroke, 1.7)" }}strokeLinecap="round"strokeLinejoin="round"className={`block shrink-0 ${className}`}diff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsxindex 8df82387..b8f58b9e 100644--- a/packages/web/src/components/ui/group-list.tsx+++ b/packages/web/src/components/ui/group-list.tsx@@ -183,7 +183,7 @@ export function GroupPager({<div className="mt-1 flex items-center justify-center gap-1.5 px-1.5 py-0.5"><buttontype="button"- title={S.chat.prevGroupPage}+ data-tooltip={S.chat.prevGroupPage}aria-label={S.chat.prevGroupPage}disabled={page <= 0}onClick={() => step(-1)}@@ -202,7 +202,7 @@ export function GroupPager({</span><buttontype="button"- title={S.chat.nextGroupPage}+ data-tooltip={S.chat.nextGroupPage}aria-label={S.chat.nextGroupPage}disabled={page >= pageCount - 1}onClick={() => step(1)}@@ -351,7 +351,9 @@ export function GroupHeader({// cursor-grab while the header is a handle — the SessionRow treatment one axis up.// Groups have no sort toggle by design, so the cursor is the only thing on screen// that says this row can be dragged at all.- className={`group/header flex items-center gap-0.5 px-1 pb-0.5${+ // min-w-0: the row never asks for more than its column; the title button is the part+ // that gives way (it truncates), the actions after it keep their size.+ className={`group/header flex min-w-0 items-center gap-0.5 px-1 pb-0.5${draggable ? " cursor-grab" : ""}`}{...(draggable@@ -363,7 +365,7 @@ export function GroupHeader({onClick={onToggle}aria-expanded={open}aria-label={open ? S.nav.collapseGroup : S.nav.expandGroup}- {...(title !== undefined ? { title } : {})}+ {...(title !== undefined ? { "data-tooltip": title } : {})}className="flex min-w-0 flex-1 items-center gap-1 self-stretch rounded px-1 py-0.5 text-left transition-colors duration-150 hover:bg-gray-200/50 dark:hover:bg-gray-800/50">{icon}diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsxindex 2bd383e3..da0c5795 100644--- a/packages/web/src/components/ui/icons.tsx+++ b/packages/web/src/components/ui/icons.tsx@@ -143,6 +143,7 @@ export function CloseIcon({ size = 14, className = "" }: { size?: number; classNexport function CloseButton({onClose,className = "",+ title,...rest}: { onClose: () => void; className?: string } & Omit<ButtonHTMLAttributes<HTMLButtonElement>,@@ -154,6 +155,7 @@ export function CloseButton({aria-label={S.common.close}onClick={onClose}className={`rounded-md p-1.5 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300 ${className}`}+ data-tooltip={title}{...rest}><CloseIcon />diff --git a/packages/web/src/components/ui/image-zoom.tsx b/packages/web/src/components/ui/image-zoom.tsxindex 83f92814..6698a2d6 100644--- a/packages/web/src/components/ui/image-zoom.tsx+++ b/packages/web/src/components/ui/image-zoom.tsx@@ -44,7 +44,8 @@ function Lightbox({ src, alt, onClose }: { src: string; alt: string; onClose: ()return createPortal(<div- className="anim-fade fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-10"+ // ui-scrim: the overlay is the dimmed layer, with the image inside it.+ className="ui-scrim anim-fade fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-10"onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}diff --git a/packages/web/src/components/ui/info-popover.tsx b/packages/web/src/components/ui/info-popover.tsxindex 9bbccf04..a311a9ff 100644--- a/packages/web/src/components/ui/info-popover.tsx+++ b/packages/web/src/components/ui/info-popover.tsx@@ -62,7 +62,7 @@ export function InfoPopover({ref={triggerRef}type="button"aria-label={name}- title={name}+ data-tooltip={name}aria-expanded={open}aria-controls={panelId}// While open the panel is also the trigger's description, so a screen reader reads the@@ -99,7 +99,7 @@ export function InfoPopover({bottom: position.bottomPx,left: position.left,}}- className="anim-pop z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-gray-200 bg-white px-3 py-2 text-xs leading-relaxed text-gray-600 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300"+ className="ui-glass anim-pop z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-gray-200 bg-white px-3 py-2 text-xs leading-relaxed text-gray-600 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300">{children}</div>,diff --git a/packages/web/src/components/ui/input.tsx b/packages/web/src/components/ui/input.tsxindex 39d7e2b6..0efd08d9 100644--- a/packages/web/src/components/ui/input.tsx+++ b/packages/web/src/components/ui/input.tsx@@ -150,6 +150,7 @@ export function Input({className,autoComplete,id,+ title,...rest}: InputProps) {const bad = Boolean(error) || Boolean(invalid);@@ -181,6 +182,8 @@ export function Input({// Secret while masked; PasswordInput's reveal toggle flips the type to text, and the// opt-out that matters was already read from the password state.{...autofillProps(autoComplete, rest.type === "password")}+ // A hover hint shows in the shared tooltip, never the browser's own `title`.+ data-tooltip={title}{...rest}/></Field>@@ -217,6 +220,7 @@ export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(functionclassName,autoComplete,id,+ title,...rest},ref,@@ -248,6 +252,7 @@ export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(functionaria-required={required || undefined}aria-describedby={error ? errorId : undefined}{...autofillProps(autoComplete, false)}+ data-tooltip={title}{...rest}/></Field>diff --git a/packages/web/src/components/ui/modal.tsx b/packages/web/src/components/ui/modal.tsxindex 52806a0a..68d36fd7 100644--- a/packages/web/src/components/ui/modal.tsx+++ b/packages/web/src/components/ui/modal.tsx@@ -211,7 +211,9 @@ export function Modal({if (!open) return null;return createPortal(<div- className="anim-fade fixed inset-0 z-50 flex items-end justify-center bg-black/45 p-0 sm:items-center sm:p-4"+ // ui-scrim: the dimmed layer between the page and the dialog; a theme may blur the page+ // through it. The overlay is the scrim itself, with the dialog inside it.+ className="ui-scrim anim-fade fixed inset-0 z-50 flex items-end justify-center bg-[var(--ui-overlay-backdrop)] p-0 sm:items-center sm:p-4"onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}@@ -225,7 +227,7 @@ export function Modal({{...(headerless ? { "aria-label": title } : { "aria-labelledby": titleId })}tabIndex={-1}onKeyDown={onPanelKeyDown}- className={`anim-pop w-full ${widthClass ?? "sm:max-w-md"} ${+ className={`ui-glass anim-pop w-full ${widthClass ?? "sm:max-w-md"} ${fullScreenOnPhone? "flex h-[100dvh] flex-col pt-[env(safe-area-inset-top)] sm:pt-0": "rounded-t-lg"diff --git a/packages/web/src/components/ui/notice-strip.tsx b/packages/web/src/components/ui/notice-strip.tsxnew file mode 100644index 00000000..5a01d05a--- /dev/null+++ b/packages/web/src/components/ui/notice-strip.tsx@@ -0,0 +1,49 @@+/**+ * A notice that owns a row: an error line, a warning above a form, a status strip. The strip's+ * colours are `toneStrip`'s, chosen by meaning (see lib/tone.ts); the caller keeps its own+ * layout, spacing and border classes, so every strip sits where it sat before.+ *+ * It carries the `ui-notice` hook, so a theme can render notices its own way — a floating card+ * with a tone dot, a log line with a tone tag — without every call site knowing. `data-tone`+ * names the tone in the hook's vocabulary; callers may mark their text `data-slot="body"` and+ * their buttons `data-slot="actions"`.+ */+import type { HTMLAttributes, ReactNode } from "react";+import { toneStrip } from "../../lib/tone";+import type { Tone } from "../../lib/tone";++export type NoticeTone = "info" | "success" | "warning" | "danger" | "neutral";++/** The app's tones in the notice hook's words: an unfinished state warns, a settled one is neutral. */+export const NOTICE_TONE: Readonly<Record<Tone, NoticeTone>> = {+ busy: "success",+ success: "success",+ attention: "warning",+ danger: "danger",+ link: "info",+ muted: "neutral",+};++export function NoticeStrip({+ tone,+ as: Tag = "div",+ className = "",+ children,+ ...rest+}: {+ tone: Tone;+ /** A strip that is one sentence of prose may be a paragraph. */+ as?: "div" | "p";+ className?: string;+ children?: ReactNode;+} & Omit<HTMLAttributes<HTMLElement>, "className" | "children">) {+ return (+ <Tag+ {...rest}+ data-tone={NOTICE_TONE[tone]}+ className={`ui-notice ${className} ${toneStrip[tone]}`}+ >+ {children}+ </Tag>+ );+}diff --git a/packages/web/src/components/ui/option-menu.tsx b/packages/web/src/components/ui/option-menu.tsxindex 7f9961c4..4c9bf135 100644--- a/packages/web/src/components/ui/option-menu.tsx+++ b/packages/web/src/components/ui/option-menu.tsx@@ -29,8 +29,15 @@ import { useId, useState } from "react";import { createPortal } from "react-dom";import { errorClass, sizeClass, sizeTextClass } from "./input";import type { ControlSize } from "./input";-import { Field, controlBase, menuRowClass } from "./field";-import { CheckIcon, ChevronDown } from "./icons";+import {+ ChoiceCheck,+ Field,+ controlBase,+ menuPanelClass,+ menuRowClass,+ menuRowTone,+} from "./field";+import { ChevronDown } from "./icons";import { usePortalPanel } from "./use-portal-panel";export interface OptionMenuChoice<T extends string> {@@ -132,7 +139,7 @@ export function OptionMenu<T extends string>({left: position.left,minWidth: position.triggerWidth,}}- className="anim-pop z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900"+ className={`ui-glass ${menuPanelClass} z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)]`}>{options.map((opt) => (<button@@ -144,25 +151,13 @@ export function OptionMenu<T extends string>({onChange(opt.value);setOpen(false);}}- className={`block ${menuRowClass} hover:bg-gray-100 dark:hover:bg-gray-800 ${- opt.value === value ? "bg-gray-100 dark:bg-gray-800" : ""- }`}+ className={`block ${menuRowClass} ${menuRowTone(opt.value === value)}`}><span className="flex items-center justify-between gap-2">{/* Row title takes the control's own tier, so the menu reads exactly likean Input of that tier. */}- <span- className={`${sizeTextClass[size]} ${- opt.value === value- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-700 dark:text-gray-300"- }`}- >- {opt.label}- </span>- {opt.value === value && (- <CheckIcon className="text-gray-500 dark:text-gray-400" />- )}+ <span className={sizeTextClass[size]}>{opt.label}</span>+ <ChoiceCheck on={opt.value === value} /></span><spanclassName={`mt-0.5 block ${rowDescClass[size]} text-gray-500 dark:text-gray-400`}diff --git a/packages/web/src/components/ui/paged-dialog.tsx b/packages/web/src/components/ui/paged-dialog.tsxindex 52ad1b62..3d8a069e 100644--- a/packages/web/src/components/ui/paged-dialog.tsx+++ b/packages/web/src/components/ui/paged-dialog.tsx@@ -93,7 +93,11 @@ export function PagedDialog<K extends string>({onClick={() => onSelect(item.key)}>{item.icon !== undefined && (- <span aria-hidden className="shrink-0 text-gray-400 dark:text-gray-500">+ <span+ aria-hidden+ className="ui-icon-decor shrink-0 text-gray-400 dark:text-gray-500"+ data-role="nav"+ >{item.icon}</span>)}diff --git a/packages/web/src/components/ui/password-input.tsx b/packages/web/src/components/ui/password-input.tsxindex 1e5e57c0..68bf5fdc 100644--- a/packages/web/src/components/ui/password-input.tsx+++ b/packages/web/src/components/ui/password-input.tsx@@ -64,7 +64,7 @@ export function PasswordInput({<buttontype="button"aria-label={toggleLabel}- title={toggleLabel}+ data-tooltip={toggleLabel}// Skip in the tab order: Tab should move between fields, not land on the reveal toggle.tabIndex={-1}onClick={() => setVisible((v) => !v)}diff --git a/packages/web/src/components/ui/segmented.tsx b/packages/web/src/components/ui/segmented.tsxindex eee946e7..ca1c3e2f 100644--- a/packages/web/src/components/ui/segmented.tsx+++ b/packages/web/src/components/ui/segmented.tsx@@ -1,5 +1,5 @@/**- * Segmented control (for 2- to 4-way choices like theme/language/messaging channel): small+ * Segmented control (for 2- to 5-way choices like theme/language/messaging channel): small* grayscale style. Shared by the sidebar user menu, the login page and the binding editor.** An option may carry a `badge`: a mini tag pinned at the top-right of its label, for a mark that@@ -23,13 +23,13 @@ export function Segmented<T extends string>({}>;value: T;onChange: (v: T) => void;- cols?: 2 | 3 | 4;+ cols?: 2 | 3 | 4 | 5;}) {return (<div// Spelled out rather than interpolated: Tailwind scans for whole class names, and a// `grid-cols-${n}` built at runtime is never emitted into the stylesheet.- className={`grid ${cols === 2 ? "grid-cols-2" : cols === 4 ? "grid-cols-4" : "grid-cols-3"} gap-0.5 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800`}+ className={`grid ${cols === 2 ? "grid-cols-2" : cols === 4 ? "grid-cols-4" : cols === 5 ? "grid-cols-5" : "grid-cols-3"} gap-0.5 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800`}>{options.map((opt) => (<buttondiff --git a/packages/web/src/components/ui/select.tsx b/packages/web/src/components/ui/select.tsxindex b2d56144..279427a5 100644--- a/packages/web/src/components/ui/select.tsx+++ b/packages/web/src/components/ui/select.tsx@@ -11,8 +11,15 @@ import type { ChangeEvent, ReactNode, SelectHTMLAttributes } from "react";import { createPortal } from "react-dom";import { errorClass, sizeClass, sizeTextClass } from "./input";import type { ControlSize } from "./input";-import { Field, controlBase, menuRowClass } from "./field";-import { CheckIcon, ChevronDown } from "./icons";+import {+ ChoiceCheck,+ Field,+ controlBase,+ menuPanelClass,+ menuRowClass,+ menuRowTone,+} from "./field";+import { ChevronDown } from "./icons";import { usePortalPanel } from "./use-portal-panel";export interface SelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, "size"> {@@ -109,7 +116,7 @@ export function Select({<divref={panelRef}role="listbox"- className="anim-pop fixed z-[60] max-h-60 overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900"+ className={`ui-glass ${menuPanelClass} fixed z-[60] max-h-60`}style={{left: position.left,width: position.triggerWidth,@@ -127,14 +134,12 @@ export function Select({onClick={() => pick(o.value)}// Menu-row text takes the control's own tier, so the dropdown reads exactly// like an Input of that tier.- className={`flex items-center ${menuRowClass} ${sizeTextClass[size]} disabled:opacity-50 ${- o.value === current- ? "bg-gray-100 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"- }`}+ className={`flex items-center gap-2 ${menuRowClass} ${sizeTextClass[size]} disabled:opacity-50 ${menuRowTone(+ o.value === current,+ )}`}><span className="min-w-0 flex-1 truncate">{o.label}</span>- {o.value === current && <CheckIcon className="text-gray-500 dark:text-gray-400" />}+ <ChoiceCheck on={o.value === current} /></button>))}</div>,diff --git a/packages/web/src/components/ui/session-activity-icon.tsx b/packages/web/src/components/ui/session-activity-icon.tsxindex bae102e1..7eb173a6 100644--- a/packages/web/src/components/ui/session-activity-icon.tsx+++ b/packages/web/src/components/ui/session-activity-icon.tsx@@ -87,7 +87,7 @@ export function BackgroundTasksMark({ label, size }: { label: string; size: numb<spanrole="img"aria-label={label}- title={label}+ data-tooltip={label}className={`flex shrink-0 items-center ${toneInk.busy}`}><GlyphIcon d={BACKGROUND_TASKS_ICON} size={size} />@@ -116,7 +116,7 @@ export function ScheduleMark({ size }: { size: number }) {<spanrole="img"aria-label={label}- title={label}+ data-tooltip={label}className={`flex shrink-0 items-center ${toneInk.muted}`}><GlyphIcon d={SCHEDULE_ICON} size={size} />@@ -137,7 +137,7 @@ export function SessionActivityIcon({ activity }: { activity: Activity }) {<spanrole="img"aria-label={label}- title={label}+ data-tooltip={label}style={{ width: size, height: size }}className="flex shrink-0 items-center justify-center">@@ -159,10 +159,9 @@ export function SessionActivityIcon({ activity }: { activity: Activity }) {// completion is already announced by the notification path, not this glyph).role="status"aria-label={label}+ data-tooltip={label}className={`block shrink-0 ${APPEARANCE[activity]}`}>- {/* The svg <title> child doubles as the hover tooltip (svg has no HTML title attribute). */}- <title>{label}</title><path d={ACTIVITY_GLYPH[activity]} /></svg>);diff --git a/packages/web/src/components/ui/session-row-menu.tsx b/packages/web/src/components/ui/session-row-menu.tsxindex 0aaf296e..38768ab6 100644--- a/packages/web/src/components/ui/session-row-menu.tsx+++ b/packages/web/src/components/ui/session-row-menu.tsx@@ -23,6 +23,7 @@ import { S } from "../../lib/strings";import { GlyphIcon } from "./glyph-icon";import { Icon } from "./group-list";import { MESSAGING_RELAY_ICON } from "./icons";+import { menuRowClass, menuRowTone } from "./field";import { STAT_ICONS } from "../../lib/stat-icons";/** Pushpin (lucide pin: head + body + stem), the group-header pin toggle / pinned indicator. */@@ -47,19 +48,29 @@ export const ELLIPSIS_ICON ="M4.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM12 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM19.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4z";/** Compact overflow-menu row (session row menu + workspace group menu): small text, leading thin-line glyph. */-export const overflowMenuRowClass =- "flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800";+export const overflowMenuRowClass = `flex items-center gap-2 ${menuRowClass} text-xs ${menuRowTone()}`;/** The overflow menus' destructive row (delete keeps the red treatment; its glyph inherits the red). */-export const overflowMenuDangerClass =- "flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-red-600 transition-colors duration-150 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40";+export const overflowMenuDangerClass = `flex items-center gap-2 ${menuRowClass} text-xs text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40`;-/** The overflow menus' muted leading glyph (a danger row inlines its own so the red inherits). */-export const overflowMenuGlyph = (d: string) => (- <span className="shrink-0 text-gray-400 dark:text-gray-500">- <Icon d={d} size={13} />- </span>-);+/**+ * A menu row's leading glyph. It names the row's subject beside a label that is never dropped,+ * so it is decorative (`ui-icon-decor`, role `menu`): a theme may recolour it or leave it out.+ * Muted, except on a danger row, where it inherits the row's red.+ */+export function MenuItemGlyph({ d, danger = false }: { d: string; danger?: boolean }) {+ return (+ <span+ className={`ui-icon-decor shrink-0 ${danger ? "" : "text-gray-400 dark:text-gray-500"}`}+ data-role="menu"+ >+ <Icon d={d} size={13} />+ </span>+ );+}++/** The overflow menus' muted leading glyph, for call sites that build their rows inline. */+export const overflowMenuGlyph = (d: string) => <MenuItemGlyph d={d} />;/** One thing a Session row can do to its Session. */export type SessionRowAction = "pin" | "rename" | "copy" | "messaging" | "archive" | "delete";@@ -162,14 +173,7 @@ export function SessionRowMenuRows({className={item.danger ? overflowMenuDangerClass : overflowMenuRowClass}onClick={() => onRun(action)}>- {item.danger ? (- /* The glyph inherits the row's red. */- <span className="shrink-0">- <Icon d={item.icon} size={13} />- </span>- ) : (- overflowMenuGlyph(item.icon)- )}+ <MenuItemGlyph d={item.icon} danger={item.danger} />{item.label}</button>);@@ -220,7 +224,7 @@ export function SessionRowHoverActions({<buttonkey={action}type="button"- title={item.label}+ data-tooltip={item.label}aria-label={item.label}onClick={() => onRun(action)}className={`${hoverButtonClass} ${@@ -235,7 +239,7 @@ export function SessionRowHoverActions({})}<buttontype="button"- title={S.chat.moreActions}+ data-tooltip={S.chat.moreActions}aria-label={S.chat.moreActions}aria-haspopup="menu"onClick={openMore}diff --git a/packages/web/src/components/ui/sheet.tsx b/packages/web/src/components/ui/sheet.tsxindex e2225860..81cb3f90 100644--- a/packages/web/src/components/ui/sheet.tsx+++ b/packages/web/src/components/ui/sheet.tsx@@ -264,7 +264,8 @@ export function Sheet({ open, snap, onSnapChange, onClose, title, children }: Sh<div className="fixed inset-0 z-50" role="dialog" aria-modal="true" aria-label={title}><divref={scrimRef}- className={`absolute inset-0 bg-black/45 ${reduced ? "anim-fade" : ""}`}+ // ui-scrim: the dimmed layer behind the sheet; a theme may blur the page through it.+ className={`ui-scrim absolute inset-0 bg-[var(--ui-overlay-backdrop)] ${reduced ? "anim-fade" : ""}`}style={{ opacity: 0 }}onPointerDown={() => onClose()}/>diff --git a/packages/web/src/components/ui/status-icon.tsx b/packages/web/src/components/ui/status-icon.tsxindex 0ae02973..b92e94c3 100644--- a/packages/web/src/components/ui/status-icon.tsx+++ b/packages/web/src/components/ui/status-icon.tsx@@ -42,7 +42,7 @@ export function StatusIcon({return (<span{...(label- ? { title: label, "aria-label": label, role: "status" }+ ? { "data-tooltip": label, "aria-label": label, role: "status" }: { "aria-hidden": true })}style={{ width: size, height: size }}className={`inline-block shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent ${TONE.running}`}@@ -62,10 +62,11 @@ export function StatusIcon({// Without a label, this icon is decorative (the status is already conveyed by// adjacent text): it must not have role="img" without an accessible name, or// a screen reader would announce it as an anonymous image.- {...(label ? { role: "img" as const, "aria-label": label } : { "aria-hidden": true })}+ {...(label+ ? { role: "img" as const, "aria-label": label, "data-tooltip": label }+ : { "aria-hidden": true })}className={`block shrink-0 ${TONE[state]}`}>- {label && <title>{label}</title>}<path d={GLYPH[state]} /></svg>);diff --git a/packages/web/src/components/ui/switch.tsx b/packages/web/src/components/ui/switch.tsxindex 5e1fe003..60d65ea0 100644--- a/packages/web/src/components/ui/switch.tsx+++ b/packages/web/src/components/ui/switch.tsx@@ -8,13 +8,15 @@* Geometry (all integer pixels): a 16px knob in the 36x20px track, inset 2px on every side* in both states (travel 2px -> 18px), and at either end concentric with the track's* end-cap circle (center 10px in from the edge), so the gap along the arcs matches the- * straight runs. The track draws a 1px inset hairline; the knob's hairline is a *border* —+ * straight runs. The knob is painted from the theme's two knob tokens, one per track: the on+ * track is the accent, and an accent can be near-white (a dark theme's neutral accent, a lifted+ * preset), where a white knob would vanish — the theme picks a knob that stays apart from each+ * track at every accent. The track draws a 1px inset hairline; the knob's hairline is a *border* —* inside its own 16px — not an outer ring: an outer ring would fill the gap on the near arc* and stack on the track hairline as one heavier line, reading as unequal spacing. Net* clearance between knob edge and outline is thus a uniform 1px all around. No offset* shadow (it reads as vertical asymmetry at this size); the hairlines keep the edges- * defined on any surface (the dark neutral accent is near-white, where the white knob would- * otherwise vanish); dark-mode aware; disabled dims and blocks. The focus ring is+ * defined on any surface; dark-mode aware; disabled dims and blocks. The focus ring is* accent-tinted and `focus-visible`-only, so keyboard focus shows it but a mouse click* doesn't leave a lingering halo. Sized for compact (sm) form rows, matching the dialogs'* controls.@@ -29,7 +31,7 @@ export interface SwitchProps extends Omit<onChange: (checked: boolean) => void;}-export function Switch({ checked, onChange, disabled, className, ...rest }: SwitchProps) {+export function Switch({ checked, onChange, disabled, className, title, ...rest }: SwitchProps) {return (<buttontype="button"@@ -41,17 +43,23 @@ export function Switch({ checked, onChange, disabled, className, ...rest }: Swit"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full " +"inset-ring inset-ring-black/10 dark:inset-ring-white/10 " +"transition-colors duration-200 ease-out " +- "focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent-bg)]/40 " ++ "focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 " +"disabled:cursor-not-allowed disabled:opacity-60 " +- (checked ? "bg-[var(--accent-bg)]" : "bg-gray-200 dark:bg-gray-700") ++ (checked ? "bg-accent" : "bg-gray-200 dark:bg-gray-700") +` ${className ?? ""}`}+ // A hover hint shows in the shared tooltip, never the browser's own `title`.+ data-tooltip={title}{...rest}><spanaria-hidden- className={`inline-block size-4 rounded-full border border-black/10 bg-white transition-transform duration-200 ease-out ${- checked ? "translate-x-[18px]" : "translate-x-0.5"+ className={`inline-block size-4 rounded-full border transition-transform duration-200 ease-out ${+ // The off knob sits on a pale track, so its edge is the theme's knob line (it carries the+ // 3:1 there); on the accent track the fill already contrasts and the edge stays faint.+ checked+ ? "translate-x-4.5 border-black/10 bg-(--ui-switch-knob-on)"+ : "translate-x-0.5 border-switch-knob-line bg-(--ui-switch-knob)"}`}/></button>diff --git a/packages/web/src/components/ui/tabs.tsx b/packages/web/src/components/ui/tabs.tsxindex 9f202c17..8d9fe9a3 100644--- a/packages/web/src/components/ui/tabs.tsx+++ b/packages/web/src/components/ui/tabs.tsx@@ -28,7 +28,9 @@ export function Tabs<K extends string>({<divrole="tablist"// overflow-y-hidden: only allow horizontal scroll on narrow screens, otherwise some browsers reserve a vertical scrollbar gutter for overflow-x-auto.- className="flex max-w-full gap-1 overflow-x-auto overflow-y-hidden border-b border-gray-200 dark:border-gray-800"+ // ui-underline-nav: the selected-tab marker is the theme's to draw (the recipes select the+ // tabs by role and aria-selected); in the default theme it is the border below.+ className="ui-underline-nav flex max-w-full gap-1 overflow-x-auto overflow-y-hidden border-b border-gray-200 dark:border-gray-800">{items.map((item) => {const badge = item.badge ?? null;@@ -38,7 +40,9 @@ export function Tabs<K extends string>({type="button"role="tab"aria-selected={item.key === active}- {...(badge !== null ? { title: badge, "aria-label": `${item.label} · ${badge}` } : {})}+ {...(badge !== null+ ? { "data-tooltip": badge, "aria-label": `${item.label} · ${badge}` }+ : {})}onClick={() => onChange(item.key)}className={`relative -mb-px whitespace-nowrap border-b-2 px-3 py-2 text-sm transition-colors duration-150 ${item.key === activediff --git a/packages/web/src/components/ui/toast.tsx b/packages/web/src/components/ui/toast.tsxindex 7a4b8863..b6271c0a 100644--- a/packages/web/src/components/ui/toast.tsx+++ b/packages/web/src/components/ui/toast.tsx@@ -76,6 +76,14 @@ const KIND_CLASS: Record<ToastKind, string> = {"border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200",};+/** A toast's kind in the `ui-notice` hook's vocabulary, so a theme can style it like any notice. */+const KIND_TONE: Record<ToastKind, "success" | "danger" | "info" | "warning"> = {+ success: "success",+ error: "danger",+ info: "info",+ attention: "warning",+};+/** Toast container: mount once at the app root. */export function Toaster() {const list = useStore(toastStore, (s) => s.items);@@ -87,9 +95,10 @@ export function Toaster() {key={t.id}type="button"onClick={() => dismiss(t.id)}- className={`pointer-events-auto max-w-lg break-words rounded-md border px-3 py-2 text-left text-sm shadow-lg ${t.leaving ? "anim-toast-out" : "anim-toast-in"} ${KIND_CLASS[t.kind]}`}+ data-tone={KIND_TONE[t.kind]}+ className={`ui-notice pointer-events-auto max-w-lg break-words rounded-md border px-3 py-2 text-left text-sm shadow-lg ${t.leaving ? "anim-toast-out" : "anim-toast-in"} ${KIND_CLASS[t.kind]}`}>- {t.text}+ <span data-slot="body">{t.text}</span></button>))}</div>,diff --git a/packages/web/src/components/ui/todo-notice.tsx b/packages/web/src/components/ui/todo-notice.tsxindex 750d21d9..cddc637d 100644--- a/packages/web/src/components/ui/todo-notice.tsx+++ b/packages/web/src/components/ui/todo-notice.tsx@@ -42,7 +42,7 @@import { Button } from "./button";import { UPDATE_DOT_INLINE } from "./update-dot";import { ICON_GAP } from "../../lib/icon-scale";-import { toneStrip } from "../../lib/tone";+import { NoticeStrip } from "./notice-strip";export function TodoNotice({text,@@ -72,11 +72,12 @@ export function TodoNotice({}) {const offersAction = actionLabel !== undefined && onAction !== undefined;return (- <div- className={`mt-3 flex items-center justify-between gap-4 rounded-lg border px-4 py-3 ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="mt-3 flex items-center justify-between gap-4 rounded-lg border px-4 py-3"><p className={`flex min-w-0 items-center text-xs ${ICON_GAP.menu}`}>- <span aria-hidden className={`shrink-0 ${UPDATE_DOT_INLINE}`} />+ <span aria-hidden data-slot="icon" className={`shrink-0 ${UPDATE_DOT_INLINE}`} /><span className="min-w-0">{text}</span></p>{/* The update sits to the RIGHT of the dismiss, which is where every ConfirmModal in the@@ -104,6 +105,6 @@ export function TodoNotice({</Button>)}</div>- </div>+ </NoticeStrip>);}diff --git a/packages/web/src/components/ui/token-donut.tsx b/packages/web/src/components/ui/token-donut.tsxindex 5ad2ed24..6b1f1769 100644--- a/packages/web/src/components/ui/token-donut.tsx+++ b/packages/web/src/components/ui/token-donut.tsx@@ -8,14 +8,14 @@* supply one). If all three buckets are 0, only the base ring is drawn; when* usage exceeds the limit, the ring is filled proportionally to usage and* colored by threshold (>80% amber / >95% red) to signal approaching/exceeding- * the limit; exact values are given via a `<title>` hover.- * Segments use the site-wide TOKEN_COLORS (works in both light/dark); the base+ * the limit; exact values show in the shared tooltip on hover.+ * Segments use the theme's Token-kind colours (useChartStyle); the base* ring uses a currentColor gray.* The context usage under the chat page's input box is a **single-color,* single-value** ring (total only), custom-drawn in context-gauge — it doesn't* use this component.*/-import { TOKEN_COLORS } from "../../lib/token-colors";+import { ChartArc } from "./chart";import { humanizeTokens } from "../../lib/format";import { S } from "../../lib/strings";import { toneInk } from "../../lib/tone";@@ -56,16 +56,16 @@ export function TokenDonut({{key: "cacheRead",value: cacheRead,- color: TOKEN_COLORS.cacheRead,+ role: "cacheRead" as const,label: S.usage.colCacheRead,},{key: "cacheWrite",value: cacheWrite,- color: TOKEN_COLORS.cacheWrite,+ role: "cacheWrite" as const,label: S.usage.colCacheWrite,},- { key: "output", value: output, color: TOKEN_COLORS.output, label: S.usage.colOutput },+ { key: "output", value: output, role: "output" as const, label: S.usage.colOutput },];const title =`${S.chat.contextUsage} ${humanizeTokens(total)}/${humanizeTokens(max)}` +@@ -76,39 +76,38 @@ export function TokenDonut({width={size}height={size}viewBox={`0 0 ${size} ${size}`}- className={`block shrink-0 ${ringTone}`}+ // ui-chart: a theme may redraw the parts (the track as the grid, each arc a series).+ className={`ui-chart block shrink-0 ${ringTone}`}role="img"aria-label={title}+ data-tooltip={title}>- <title>{title}</title>- {/* Base ring (empty ring / remainder) */}- <circle+ {/* Base ring (empty ring / remainder), in the svg's own ink: the near-limit tone above. */}+ <ChartArccx={center}cy={center}r={r}- fill="none"- stroke="currentColor"- strokeOpacity={0.35}- strokeWidth={strokeWidth}+ width={strokeWidth}+ paint={{ ink: "" }}+ track+ trackOpacity={0.35}/>- {/* Three arc segments: clockwise, starting at 12 o'clock (rotate -90), positioned via cumulative dashoffset per segment. */}+ {/* Three arc segments: clockwise, starting at 12 o'clock, each placed by the cumulative offset. */}{segs.map((seg) => {if (seg.value <= 0) return null;const len = (seg.value / denom) * c;const offset = -(acc / denom) * c;acc += seg.value;return (- <circle+ <ChartArckey={seg.key}cx={center}cy={center}r={r}- fill="none"- stroke={seg.color}- strokeWidth={strokeWidth}- strokeDasharray={`${len} ${c}`}- strokeDashoffset={offset}- transform={`rotate(-90 ${center} ${center})`}+ width={strokeWidth}+ paint={{ role: seg.role }}+ length={len}+ offset={offset}/>);})}diff --git a/packages/web/src/components/ui/tooltip.tsx b/packages/web/src/components/ui/tooltip.tsxindex ce190535..ae73c602 100644--- a/packages/web/src/components/ui/tooltip.tsx+++ b/packages/web/src/components/ui/tooltip.tsx@@ -1,11 +1,26 @@/**- * Hover/focus tooltip for a control whose visible form is an icon alone — and for a line of- * code a row truncates, whose full text has nowhere else to show (`content="code"`).+ * The app's one tooltip: a hover/focus panel for a control whose visible form is an icon+ * alone, for a line a row truncates (`content="code"` or `"text"`), and for any hint an+ * element offers on hover.*- * What it replaces is the native `title` attribute: that one waits about a second before it- * appears, cannot be styled, and never shows on keyboard focus — so an icon rail labeled- * only by `title` reads as unlabeled. A trigger must carry one or the other, never both, or- * two tooltips appear over each other.+ * What it replaces is the native `title` attribute, which the app does not use at all: that+ * one waits about a second before it appears, cannot be styled or themed, and never shows on+ * keyboard focus — so an icon rail labeled only by `title` reads as unlabeled. A guard test+ * fails on a `title` attribute on an intrinsic element.+ *+ * Either way in, a hint shows only for an element with no visible text of its own or one+ * whose visible text is cut off (`hintAllowed`, checked when the hint would open): a label the+ * reader can already read in full gets no tooltip.+ *+ * Two ways in, one panel:+ * - `<Tooltip label>` wraps its trigger in a measuring span — for a trigger that needs the+ * wrapper's extras (`suppressed`, a placement beside a rail).+ * - `data-tooltip="…"` on any element, read by the one `<TooltipLayer />` mounted at the app+ * root, which listens once on the document. It adds no wrapper, so it is what replaces a+ * `title` in place: a table cell, a truncated span or a flex child keeps its layout exactly.+ * `data-tooltip-content` picks the panel's kind, `data-tooltip-placement` its side+ * (default `bottom`). Unlike `title`, it names nothing to assistive technology, so an+ * element whose only name was its title carries an `aria-label` with the same words.** Portaled to document.body at fixed viewport coordinates, like every other overlay here* (see use-portal-panel.ts): an in-place absolute panel is a descendant of its trigger, so a@@ -53,20 +68,85 @@ export type TooltipPlacement = "right" | "bottom";* the row it stands for, and wider, because it is read rather than glanced at. It breaks* anywhere — a path or a run of flags has no space to wrap at — and keeps its own line* breaks, so a multi-line command reads the way it was written.+ * - `text`: prose a row truncated (a title, a description, an error). As wide as `code`, set+ * in the interface face, wrapping at words and keeping its own line breaks.*/-export type TooltipContent = "label" | "code";+export type TooltipContent = "label" | "code" | "text";const contentClass: Record<TooltipContent, string> = {label: "",code: "whitespace-pre-wrap wrap-anywhere font-mono",+ text: "whitespace-pre-wrap wrap-break-word",};/** The width each kind wraps at, before the room left on screen caps it further. */const contentMaxWidth: Record<TooltipContent, string> = {label: "16rem",code: "24rem",+ text: "24rem",};+/** The attribute `TooltipLayer` reads; its value is the panel's text. */+export const TOOLTIP_ATTR = "data-tooltip";++/** A box that may clip its content: the four numbers a truncation check reads. */+export interface ClipBox {+ scrollWidth: number;+ clientWidth: number;+ scrollHeight: number;+ clientHeight: number;+}++/** Layout reports up to a pixel of overflow for text that fits (line boxes, rounding). */+const CUT_SLACK_PX = 1;++/** Whether a box's content runs past its visible area: its text is cut off. */+export function isCutOff(box: ClipBox): boolean {+ return (+ box.scrollWidth > box.clientWidth + CUT_SLACK_PX ||+ box.scrollHeight > box.clientHeight + CUT_SLACK_PX+ );+}++/**+ * The tooltip rule: a hint shows only where its words are not already on screen — for an+ * element that shows no text of its own (an icon-only control, a chart mark, a status glyph)+ * or one whose visible text is cut off. An element whose text is fully visible gets no hint,+ * whatever it carries: a hint that repeats what the reader can see is noise, and one that+ * adds to it hides that information behind a hover. `boxes` are the element and its+ * descendants, measured when the hint would open, since a column resize can cut a label off+ * or give it back at any time.+ */+export function hintAllowed(visibleText: string, boxes: Iterable<ClipBox>): boolean {+ if (visibleText.trim() === "") return true;+ for (const box of boxes) if (isCutOff(box)) return true;+ return false;+}++/** Text a reader cannot see: screen-reader-only copy, or anything the page does not render. */+function unseen(node: Element | null): boolean {+ if (node === null) return false;+ if (node.closest(".sr-only") !== null) return true;+ const check = (node as { checkVisibility?: () => boolean }).checkVisibility;+ return check !== undefined && !check.call(node);+}++/** `hintAllowed`, with its inputs read off the element at the moment the hint would open. */+export function hintAllowedFor(el: Element): boolean {+ let text = "";+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {+ if (!unseen(node.parentElement)) text += node.textContent ?? "";+ }+ const boxes: ClipBox[] = [];+ for (const node of [el, ...el.querySelectorAll("*")]) {+ // An inline box or a hidden one has no area to clip, and a screen-reader-only span is+ // clipped on purpose — neither says the visible text was cut.+ if (node instanceof HTMLElement && node.clientWidth > 0 && !unseen(node)) boxes.push(node);+ }+ return hintAllowed(text, boxes);+}+/** The trigger's viewport box — the part of a DOMRect the geometry reads. */export type TriggerRect = Pick<DOMRect, "top" | "bottom" | "left" | "right" | "width" | "height">;@@ -164,8 +244,11 @@ export function Tooltip({if (suppressed === true || timerRef.current !== null) return;timerRef.current = setTimeout(() => {timerRef.current = null;- const rect = anchorRef.current?.getBoundingClientRect();- if (!rect) return;+ const anchor = anchorRef.current;+ // Measured now, not when the trigger rendered: whether its label is cut off depends on+ // the width it has at this moment.+ if (anchor === null || !hintAllowedFor(anchor)) return;+ const rect = anchor.getBoundingClientRect();const viewport = { width: window.innerWidth, height: window.innerHeight };setPosition(placement === "bottom" ? belowTrigger(rect, viewport) : besideTrigger(rect, viewport),@@ -211,24 +294,158 @@ export function Tooltip({onBlur={hide}>{children}- {position !== null &&- createPortal(- <div- data-testid="tooltip"- aria-hidden- style={{- position: "fixed",- top: position.top,- left: position.left,- right: position.right,- maxWidth: `min(${contentMaxWidth[content]}, ${position.room}px)`,- }}- className={`anim-fade pointer-events-none z-[60] w-max rounded-md border border-gray-200 bg-white px-2 py-1 text-xs text-gray-700 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 ${contentClass[content]} ${placement === "right" ? "-translate-y-1/2" : ""}`}- >- {label}- </div>,- document.body,- )}+ {position !== null && (+ <TooltipPanel label={label} position={position} content={content} placement={placement} />+ )}</span>);}++/** The panel itself, portaled to the body; both ways in render exactly this. */+function TooltipPanel({+ label,+ position,+ content,+ placement,+}: {+ label: string;+ position: PanelPosition;+ content: TooltipContent;+ placement: TooltipPlacement;+}) {+ return createPortal(+ <div+ data-testid="tooltip"+ aria-hidden+ style={{+ position: "fixed",+ top: position.top,+ left: position.left,+ right: position.right,+ maxWidth: `min(${contentMaxWidth[content]}, ${position.room}px)`,+ }}+ className={`ui-glass anim-fade pointer-events-none z-[60] w-max rounded-md border border-gray-200 bg-white px-2 py-1 text-xs text-gray-700 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 ${contentClass[content]} ${placement === "right" ? "-translate-y-1/2" : ""}`}+ >+ {label}+ </div>,+ document.body,+ );+}++export interface TooltipRequest {+ label: string;+ content: TooltipContent;+ placement: TooltipPlacement;+}++/** Reads an element's `data-tooltip` request, or null when it carries none (or an empty one). */+export function tooltipRequest(el: Pick<Element, "getAttribute">): TooltipRequest | null {+ const label = el.getAttribute(TOOLTIP_ATTR);+ if (label === null || label.trim() === "") return null;+ const content = el.getAttribute(`${TOOLTIP_ATTR}-content`);+ const placement = el.getAttribute(`${TOOLTIP_ATTR}-placement`);+ return {+ label,+ content: content === "code" || content === "text" ? content : "label",+ placement: placement === "right" ? "right" : "bottom",+ };+}++/**+ * The document-wide reader of `data-tooltip`, mounted once at the app root. One set of+ * listeners serves every element, so a hint costs an attribute rather than a wrapper and a set+ * of handlers per element. The innermost element carrying the attribute wins, the delay is+ * `<Tooltip>`'s, and the panel closes on leave, blur, Escape, any scroll, a resize and a press+ * — a press because the element is being used now, not asked about.+ */+export function TooltipLayer() {+ const [open, setOpen] = useState<(TooltipRequest & { position: PanelPosition }) | null>(null);++ useEffect(() => {+ let current: Element | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const close = () => {+ if (timer !== null) clearTimeout(timer);+ timer = null;+ current = null;+ setOpen(null);+ };+ const holder = (node: EventTarget | null): Element | null =>+ node instanceof Element ? node.closest(`[${TOOLTIP_ATTR}]`) : null;+ const start = (el: Element | null) => {+ if (el === current) return;+ close();+ if (el === null || tooltipRequest(el) === null) return;+ current = el;+ timer = setTimeout(() => {+ timer = null;+ const el = current;+ const request = el === null ? null : tooltipRequest(el);+ if (el === null || request === null || !el.isConnected || !hintAllowedFor(el)) return;+ const rect = el.getBoundingClientRect();+ const viewport = { width: window.innerWidth, height: window.innerHeight };+ setOpen({+ ...request,+ position:+ request.placement === "right"+ ? besideTrigger(rect, viewport)+ : belowTrigger(rect, viewport),+ });+ }, OPEN_DELAY_MS);+ };+ const onOver = (e: PointerEvent) => start(holder(e.target));+ const onOut = (e: PointerEvent) => {+ if (current === null) return;+ const next = e.relatedTarget;+ if (next instanceof Node && current.contains(next)) return;+ close();+ };+ const onFocusIn = (e: FocusEvent) => start(holder(e.target));+ const onKey = (e: KeyboardEvent) => {+ // Heard, not stopped: the panel is not a dismissible layer, so the same press still+ // reaches the dialog or menu behind it.+ if (e.key === "Escape") close();+ };+ document.addEventListener("pointerover", onOver);+ document.addEventListener("pointerout", onOut);+ document.addEventListener("pointerdown", close, true);+ document.addEventListener("focusin", onFocusIn);+ document.addEventListener("focusout", close);+ window.addEventListener("keydown", onKey, true);+ window.addEventListener("scroll", close, true);+ window.addEventListener("resize", close);+ return () => {+ close();+ document.removeEventListener("pointerover", onOver);+ document.removeEventListener("pointerout", onOut);+ document.removeEventListener("pointerdown", close, true);+ document.removeEventListener("focusin", onFocusIn);+ document.removeEventListener("focusout", close);+ window.removeEventListener("keydown", onKey, true);+ window.removeEventListener("scroll", close, true);+ window.removeEventListener("resize", close);+ };+ }, []);++ return open === null ? null : (+ <TooltipPanel+ label={open.label}+ position={open.position}+ content={open.content}+ placement={open.placement}+ />+ );+}++/**+ * The attributes of a mark whose only content is its hint — a chart segment, a glyph with no+ * words beside it: the hint shows in the shared tooltip, and the same words name the mark for+ * assistive technology, which a `data-tooltip` alone does not.+ */+export function namedHint(label: string): {+ role: "img";+ "aria-label": string;+ "data-tooltip": string;+} {+ return { role: "img", "aria-label": label, "data-tooltip": label };+}diff --git a/packages/web/src/components/ui/truncated.tsx b/packages/web/src/components/ui/truncated.tsxindex 3aef2251..63b491ad 100644--- a/packages/web/src/components/ui/truncated.tsx+++ b/packages/web/src/components/ui/truncated.tsx@@ -1,8 +1,9 @@/**- * Single-line truncated text: attaches `title` (hover to see the full text)- * **only when actually truncated**, and only where nothing else reveals the tail.+ * Single-line truncated text: attaches a tooltip (hover to see the full text, the shared+ * panel read from `data-tooltip`) **only when actually truncated**, and only where nothing+ * else reveals the tail.*- * The site-wide rule is "don't duplicate `title` when the element already shows+ * The site-wide rule is "don't duplicate a tooltip when the element already shows* the text", but text whose tail is cut off by `truncate` isn't fully shown —* this is the one exception. Whether it overflows must be measured* (`scrollWidth > clientWidth`), and re-measured whenever the container's size@@ -23,15 +24,13 @@* callers without `scrollReveal`, and scroll-reveal rows under reduced motion,* where the global `animation: none !important` block in styles.css disables the* keyframes outright and leaves the plain ellipsis. Where the reveal does run, no- * `title` is attached: having both put a tooltip over the very text sliding past+ * tooltip is attached: having both put a tooltip over the very text sliding past* underneath it (#570). The full text always stays in the DOM either way, so the* accessible name carries it whole no matter how much of it is visually clipped.*- * `codeTooltip` swaps the native `title` for the styled Tooltip panel, set as code, for a- * line that is a command rather than a name. A command runs long, and the native tooltip —- * slow to appear, unstyled, and laid out however the browser or the desktop shell sees fit —- * is no dependable way to read one whole. The same rule decides whether the panel may open:- * it is held shut while the text fits, exactly where no `title` would have been attached.+ * `codeTooltip` sets the panel as code, for a line that is a command rather than a name: a+ * command runs long, and reads whole only in monospace with its own line breaks. The same+ * rule decides whether the panel may open: it is held shut while the text fits.*/import { useLayoutEffect, useRef, useState } from "react";import type { CSSProperties } from "react";@@ -99,7 +98,9 @@ export function Truncated({} as CSSProperties,}: {})}- {...(disclosure === "tooltip" && !codeTooltip ? { title: text } : {})}+ {...(disclosure === "tooltip" && !codeTooltip+ ? { "data-tooltip": text, "data-tooltip-content": "text" }+ : {})}>{/* The scroll needs a child the keyframes can turn into an inline-block andtransform; at rest it renders inline, i.e. exactly like the bare text nodediff --git a/packages/web/src/features/agents/activity-sparkline.tsx b/packages/web/src/features/agents/activity-sparkline.tsxindex 9aaf4fbf..b03ea422 100644--- a/packages/web/src/features/agents/activity-sparkline.tsx+++ b/packages/web/src/features/agents/activity-sparkline.tsx@@ -2,9 +2,18 @@* Session activity sparkline (Agents list card, GitHub-repo-Pulse-graph style): a* polyline + faint fill of daily active Session counts over the last N days,* normalized to the max value within the window — shows only relative ups and downs,- * no scale/ticks. All-zero / empty data renders a flat baseline at the bottom. Pure- * SVG, no dependencies; color follows the light/dark theme.+ * no scale/ticks. All-zero / empty data renders a flat baseline at the bottom. Drawn+ * through the chart primitives at a sparkline's scale, so it takes the theme's curve, line+ * width and area fill; its colour is its own ink, which follows light and dark.*/+import { ChartArea, ChartLine, type ChartPaint } from "../../components/ui/chart";++/** The sparkline's paint: its own ink, the emerald the svg's text class sets. */+const INK: ChartPaint = { ink: "" };+/** Three quarters of the theme's line width (1.5px in the default theme). */+const LINE_SCALE = 0.75;+/** The fill under the line, a little stronger than a full chart's (0.12 in the default theme). */+const AREA_STRENGTH = 1.2;const W = 100;const H = 30;@@ -22,9 +31,11 @@ export function ActivitySparkline({const max = Math.max(1, ...data);const step = data.length > 1 ? (W - 2 * PAD) / (data.length - 1) : 0;const pts = data.map((v, i) => [PAD + i * step, H - PAD - (v / max) * (H - 2 * PAD)] as const);- const baseline = `${PAD},${H - PAD} ${W - PAD},${H - PAD}`;- const line = pts.length > 1 ? pts.map(([x, y]) => `${x},${y}`).join(" ") : baseline;- const area = pts.length > 1 ? `${line} ${W - PAD},${H - PAD} ${PAD},${H - PAD}` : null;+ const baseline = [+ [PAD, H - PAD],+ [W - PAD, H - PAD],+ ] as const;+ const line = pts.length > 1 ? pts : baseline;return (<svgwidth={W}@@ -32,18 +43,14 @@ export function ActivitySparkline({viewBox={`0 0 ${W} ${H}`}role="img"aria-label={label}- className={`text-emerald-600 dark:text-emerald-500 ${className}`}+ data-tooltip={label}+ // ui-chart: a theme may redraw the line and the fill under it.+ className={`ui-chart text-emerald-600 dark:text-emerald-500 ${className}`}>- <title>{label}</title>- {area !== null && <polygon points={area} fill="currentColor" fillOpacity="0.12" />}- <polyline- points={line}- fill="none"- stroke="currentColor"- strokeWidth="1.5"- strokeLinecap="round"- strokeLinejoin="round"- />+ {pts.length > 1 && (+ <ChartArea points={pts} baseY={H - PAD} paint={INK} strength={AREA_STRENGTH} />+ )}+ <ChartLine points={line} paint={INK} scale={LINE_SCALE} round /></svg>);}diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsxindex fcf4f7fb..c6160415 100644--- a/packages/web/src/features/agents/agent-settings-page.tsx+++ b/packages/web/src/features/agents/agent-settings-page.tsx@@ -497,7 +497,7 @@ function OverviewTab({</p><div className="flex items-start gap-1.5"><span- title={data.stateDir}+ data-tooltip={data.stateDir}className="min-w-0 flex-1 break-all font-mono text-xs leading-5">{data.stateDir}@@ -574,7 +574,7 @@ function OverviewTab({{/* Minimal outdated hint: icon + tooltip only (no textual alarm). */}<spanrole="img"- title={S.agent.kernelOutdatedHint}+ data-tooltip={S.agent.kernelOutdatedHint}aria-label={S.agent.kernelOutdatedHint}className="self-center text-gray-500 dark:text-gray-400">@@ -714,7 +714,7 @@ function PromptTab({ data, onSave }: { data: AgentConfigResponse; onSave: SaveFn<buttontype="button"onClick={() => insertPlaceholder(ph)}- title={S.agent.insertPlaceholder}+ data-tooltip={S.agent.insertPlaceholder}className="shrink-0 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono font-semibold text-gray-800 transition-colors duration-150 hover:border-gray-400 hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:border-gray-500 dark:hover:bg-gray-700">{ph}diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsxindex 866a36d9..0164c2c3 100644--- a/packages/web/src/features/agents/agents-page.tsx+++ b/packages/web/src/features/agents/agents-page.tsx@@ -483,7 +483,7 @@ export function AgentsPage() {header has the same shape. */}<div className="mb-4"><div className="flex flex-wrap items-center justify-between gap-2">- <h1 className="text-xl font-semibold">{S.agent.listTitle}</h1>+ <h1 className="ui-display text-xl font-semibold">{S.agent.listTitle}</h1>{/* Search plus the create pair, in the Models page header's shape: on a narrowscreen flex-wrap drops the pair onto its own line and the box shrinks with it,fixed width from sm up. Both controls take the form rung — CreateButtons defaults@@ -579,8 +579,8 @@ export function AgentsPage() {</span>{machineName !== null && (<span- className="shrink-0 font-mono text-[11px] normal-case text-gray-400 dark:text-gray-500"- title={elsewhereTitle}+ className="shrink-0 font-mono text-xs normal-case text-gray-400 dark:text-gray-500"+ data-tooltip={elsewhereTitle}>{S.chat.machineTag(machineName)}</span>@@ -619,7 +619,7 @@ export function AgentsPage() {<div className="mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-500 dark:text-gray-400"><spanclassName="inline-flex shrink-0 items-center gap-1 tabular-nums"- title={S.agent.sessionCount(a.sessionCount)}+ data-tooltip={S.agent.sessionCount(a.sessionCount)}><GlyphIcon d={CARD_ICONS.sessions} size={ICON_SIZE.inlineGlyph} />{a.sessionCount}@@ -628,7 +628,7 @@ export function AgentsPage() {type="button"className={STAT_LINK_CLASS}disabled={elsewhere}- title={S.agent.toolCount(a.toolCount)}+ data-tooltip={S.agent.toolCount(a.toolCount)}aria-label={S.agent.toolCount(a.toolCount)}onClick={() => openSettingsTab(a.agentId, "tools")}>@@ -639,7 +639,7 @@ export function AgentsPage() {type="button"className={STAT_LINK_CLASS}disabled={elsewhere}- title={S.skills.skillCount(a.skillCount)}+ data-tooltip={S.skills.skillCount(a.skillCount)}aria-label={S.skills.skillCount(a.skillCount)}onClick={() => openSettingsTab(a.agentId, "skills")}>@@ -650,7 +650,7 @@ export function AgentsPage() {type="button"className={STAT_LINK_CLASS}disabled={elsewhere}- title={S.hooks.hookCount(a.hookCount)}+ data-tooltip={S.hooks.hookCount(a.hookCount)}aria-label={S.hooks.hookCount(a.hookCount)}onClick={() => openSettingsTab(a.agentId, "hooks")}>@@ -661,7 +661,7 @@ export function AgentsPage() {type="button"className={STAT_LINK_CLASS}disabled={elsewhere}- title={S.agent.memoryCount(a.memoryCount)}+ data-tooltip={S.agent.memoryCount(a.memoryCount)}aria-label={S.agent.memoryCount(a.memoryCount)}onClick={() => openSettingsTab(a.agentId, "memory")}>@@ -672,7 +672,7 @@ export function AgentsPage() {type="button"className={STAT_LINK_CLASS}disabled={elsewhere}- title={S.agent.vaultKeyCount(a.vaultKeyCount)}+ data-tooltip={S.agent.vaultKeyCount(a.vaultKeyCount)}aria-label={S.agent.vaultKeyCount(a.vaultKeyCount)}onClick={() => openSettingsTab(a.agentId, "vault")}>@@ -683,7 +683,7 @@ export function AgentsPage() {type="button"className={STAT_LINK_CLASS}disabled={elsewhere}- title={S.agent.scheduleCount(a.scheduleCount)}+ data-tooltip={S.agent.scheduleCount(a.scheduleCount)}aria-label={S.agent.scheduleCount(a.scheduleCount)}onClick={() => openSettingsTab(a.agentId, "schedules")}>@@ -692,7 +692,7 @@ export function AgentsPage() {</button><spanclassName="inline-flex shrink-0 items-center gap-1"- title={`${S.agent.updatedAt} ${a.updatedAt ? formatDateTime(a.updatedAt) : "—"}`}+ data-tooltip={`${S.agent.updatedAt} ${a.updatedAt ? formatDateTime(a.updatedAt) : "—"}`}><GlyphIcon d={STAT_ICONS.elapsed} size={ICON_SIZE.inlineGlyph} />{a.updatedAt ? formatRelativeDays(a.updatedAt, locale) : "—"}@@ -749,7 +749,7 @@ export function AgentsPage() {{builtin ? (<spanrole="img"- title={S.agent.builtinUndeletable}+ data-tooltip={S.agent.builtinUndeletable}aria-label={S.agent.builtinUndeletable}className="inline-flex cursor-not-allowed items-center justify-center rounded-md border border-transparent p-1.5 text-gray-300 dark:text-gray-600">@@ -860,7 +860,7 @@ export function AgentsPage() {</span><buttontype="button"- title={S.agent.createSnapshotClear}+ data-tooltip={S.agent.createSnapshotClear}aria-label={S.agent.createSnapshotClear}disabled={busy}onClick={() => setSnapshotFile(null)}diff --git a/packages/web/src/features/agents/hooks-tab.tsx b/packages/web/src/features/agents/hooks-tab.tsxindex 6681f2cb..3a83af78 100644--- a/packages/web/src/features/agents/hooks-tab.tsx+++ b/packages/web/src/features/agents/hooks-tab.tsx@@ -269,7 +269,8 @@ export function HooksTab({<div className="flex flex-wrap items-center gap-x-1.5 gap-y-1"><spanclassName="max-w-full truncate font-mono text-[13px] font-semibold"- title={hook.name}+ data-tooltip={hook.name}+ data-tooltip-content="code">{hook.name}</span>@@ -280,7 +281,8 @@ export function HooksTab({{/* Description truncates to one line (the full text goes into title for hover reading). */}<pclassName="mt-0.5 truncate text-xs text-gray-500 dark:text-gray-400"- title={description}+ data-tooltip={description}+ data-tooltip-content="text">{description}</p>@@ -288,7 +290,7 @@ export function HooksTab({{hook.version !== "" && (<spanclassName="hidden shrink-0 text-[11px] text-gray-400 sm:block dark:text-gray-500"- title={hook.version}+ data-tooltip={hook.version}>{hook.version}</span>diff --git a/packages/web/src/features/agents/mcp-servers-section.tsx b/packages/web/src/features/agents/mcp-servers-section.tsxindex f7ff3897..5d104cfb 100644--- a/packages/web/src/features/agents/mcp-servers-section.tsx+++ b/packages/web/src/features/agents/mcp-servers-section.tsx@@ -94,7 +94,7 @@ function TestBadge({ result }: { result: RowTestResult | undefined }) {}return (<span- title={result.error}+ data-tooltip={result.error}className={`text-[11px] font-medium whitespace-nowrap ${toneInk.danger}`}>{S.agent.mcpTestBadgeFail}diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsxindex 83f6ba86..b2333a43 100644--- a/packages/web/src/features/agents/memory-tab.tsx+++ b/packages/web/src/features/agents/memory-tab.tsx@@ -33,7 +33,6 @@ import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { formatRelativeDate } from "../../lib/format";-import { toneStrip } from "../../lib/tone";import { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";import { useProject } from "../../state/project";@@ -66,6 +65,7 @@ import {import type { MemoryImportPlan } from "./memory-transfer";import { bodyWithoutFrontmatter } from "../../lib/frontmatter";+import { NoticeStrip } from "../../components/ui/notice-strip";/** Same breakpoint as the chat page's panels: \u22651024px the view opens as a side Drawer, below it as a bottom Sheet. */const DESKTOP_QUERY = "(min-width: 1024px)";@@ -566,14 +566,15 @@ export function MemoryTab({</div>{!templateHasMemory && (- <div- className={`flex items-center justify-between gap-4 rounded-lg border px-4 py-3 ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="flex items-center justify-between gap-4 rounded-lg border px-4 py-3"><p className="text-xs">{S.memory.templateMissing}</p><Button size="sm" onClick={() => void insertPlaceholder()}>{S.memory.insertPlaceholder}</Button>- </div>+ </NoticeStrip>)}{groups === null ? (@@ -641,7 +642,7 @@ export function MemoryTab({{isOwner && (<labelclassName={`${GHOST_LABEL_CLASS} shrink-0`}- title={S.memory.importScopeHint}+ data-tooltip={S.memory.importScopeHint}aria-label={S.memory.importScopeLabel(scopeTitle(scope))}><HiddenFileInput@@ -740,7 +741,7 @@ export function MemoryTab({token!,)}- title={S.memory.insertToken}+ data-tooltip={S.memory.insertToken}className="shrink-0 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono font-semibold text-gray-800 transition-colors duration-150 hover:border-gray-400 hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:border-gray-500 dark:hover:bg-gray-700">{token}diff --git a/packages/web/src/features/agents/prompt-injection-controls.tsx b/packages/web/src/features/agents/prompt-injection-controls.tsxindex 32df1ceb..c507e438 100644--- a/packages/web/src/features/agents/prompt-injection-controls.tsx+++ b/packages/web/src/features/agents/prompt-injection-controls.tsx@@ -37,8 +37,8 @@ import { Textarea } from "../../components/ui/input";import { Switch } from "../../components/ui/switch";import { useSaveConfirm } from "../../components/ui/confirm-modal";import { toastError, toastSuccess } from "../../components/ui/toast";-import { toneStrip } from "../../lib/tone";import { InfoPopover } from "../../components/ui/info-popover";+import { NoticeStrip } from "../../components/ui/notice-strip";export type PromptInjectionFeature = "skills" | "vault" | "schedules" | "hooks";@@ -225,8 +225,9 @@ export function usePromptInjection({// features that can report legacySectionPresent); everything else gets the plain insert.const legacy = state?.legacySectionPresent === true;const alertStrip = promptStrings !== null && state !== null && !state.templateHasPlaceholder && (- <div- className={`flex items-center justify-between gap-4 rounded-lg border px-4 py-3 ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="flex items-center justify-between gap-4 rounded-lg border px-4 py-3"><p className="text-xs">{legacy@@ -240,7 +241,7 @@ export function usePromptInjection({: promptStrings.insertPlaceholder}</Button>)}- </div>+ </NoticeStrip>);const promptSection = promptStrings !== null && state !== null && (@@ -271,7 +272,7 @@ export function usePromptInjection({type="button"disabled={!canEdit}onClick={() => insertPromptToken(promptRef, prompt, setPrompt, token!)}- title={S.memory.insertToken}+ data-tooltip={S.memory.insertToken}className="shrink-0 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono font-semibold text-gray-800 transition-colors duration-150 hover:border-gray-400 hover:bg-gray-100 disabled:pointer-events-none dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:border-gray-500 dark:hover:bg-gray-700">{token}diff --git a/packages/web/src/features/agents/schedules-tab.tsx b/packages/web/src/features/agents/schedules-tab.tsxindex c5565c8b..c990a04c 100644--- a/packages/web/src/features/agents/schedules-tab.tsx+++ b/packages/web/src/features/agents/schedules-tab.tsx@@ -198,12 +198,16 @@ export function SchedulesTab({className="border-b border-gray-100 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40">{/* Long text columns truncate with the full value on hover instead of wrapping. */}- <td className="max-w-40 truncate px-3 py-2 font-mono text-xs" title={item.name}>+ <td+ className="max-w-40 truncate px-3 py-2 font-mono text-xs"+ data-tooltip={item.name}+ data-tooltip-content="code"+ >{item.name}</td><td className="whitespace-nowrap px-3 py-2">{/* invalid reason is folded into the hover title. */}- <span title={item.invalidReason}>+ <span data-tooltip={item.invalidReason}><Badge tone={STATUS_TONE[item.status]}>{S.schedule.statusNames[item.status] ?? item.status}</Badge>@@ -218,7 +222,8 @@ export function SchedulesTab({</td><tdclassName="max-w-36 truncate px-3 py-2 text-xs text-gray-500 dark:text-gray-400"- title={item.sessionId}+ data-tooltip={item.sessionId}+ data-tooltip-content="text">{item.sessionId !== undefined ? (<span className="font-mono">{item.sessionId}</span>diff --git a/packages/web/src/features/agents/skills-tab.tsx b/packages/web/src/features/agents/skills-tab.tsxindex eaf681f1..d6a6336e 100644--- a/packages/web/src/features/agents/skills-tab.tsx+++ b/packages/web/src/features/agents/skills-tab.tsx@@ -263,14 +263,16 @@ export function SkillsTab({<div className="min-w-0 flex-1"><spanclassName="block truncate font-mono text-[13px] font-semibold"- title={skill.name}+ data-tooltip={skill.name}+ data-tooltip-content="code">{skill.name}</span>{/* Short description truncates to one line (full description goes into title for hover reading). */}<pclassName="mt-0.5 truncate text-xs text-gray-500 dark:text-gray-400"- title={skill.description}+ data-tooltip={skill.description}+ data-tooltip-content="text">{localizedShortText(locale, skill)}</p>@@ -278,7 +280,7 @@ export function SkillsTab({{metaLine(skill) !== "" && (<spanclassName="hidden shrink-0 text-[11px] text-gray-400 sm:block dark:text-gray-500"- title={metaLine(skill)}+ data-tooltip={metaLine(skill)}>{metaLine(skill)}</span>diff --git a/packages/web/src/features/agents/vault-tab.tsx b/packages/web/src/features/agents/vault-tab.tsxindex 1eb51717..f6f1a30d 100644--- a/packages/web/src/features/agents/vault-tab.tsx+++ b/packages/web/src/features/agents/vault-tab.tsx@@ -29,8 +29,8 @@ import { SkeletonList } from "../../components/ui/skeleton";import { toastError, toastSuccess } from "../../components/ui/toast";import { usePromptInjection } from "./prompt-injection-controls";import { HelpFold } from "../../components/ui/help-fold";-import { toneStrip } from "../../lib/tone";import { AiCreateModal, CreateButtons } from "../ai-create";+import { NoticeStrip } from "../../components/ui/notice-strip";/** Vault key naming rule (consistent with core/server): shell environment variable name. */const VAULT_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;@@ -290,9 +290,9 @@ export function VaultTab({onClose={() => setAiAdding(false)}title={S.vault.aiAddTitle}intro={- <div className={`rounded-md border px-2.5 py-1.5 ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" className="rounded-md border px-2.5 py-1.5">{S.vault.aiAddIntro}- </div>+ </NoticeStrip>}placeholder={S.vault.aiAddPlaceholder}examples={S.vault.aiAddExamples}diff --git a/packages/web/src/features/benchmark/benchmark-detail.tsx b/packages/web/src/features/benchmark/benchmark-detail.tsxindex 11644c51..7f24b556 100644--- a/packages/web/src/features/benchmark/benchmark-detail.tsx+++ b/packages/web/src/features/benchmark/benchmark-detail.tsx@@ -25,8 +25,9 @@ import { EmptyState } from "../../components/ui/empty-state";import { GlyphIcon } from "../../components/ui/glyph-icon";import { MAGIC_WAND_ICON } from "../../components/ui/icons";import { Modal } from "../../components/ui/modal";-import { NEUTRAL_SERIES, seriesColor } from "../../lib/category-colors";-import { makeRangeGeom, segmentPath } from "../usage/chart-geom";+import { NEUTRAL_SERIES } from "../../lib/category-colors";+import { makeRangeGeom, segmentPoints } from "../usage/chart-geom";+import { ChartLine, ChartPoint, ChartSwatch, type ChartPaint } from "../../components/ui/chart";import { ChartFrame, useChartWidth } from "../usage/chart-svg";import { AskAiModal } from "./ask-ai-modal";import { BenchmarkCaseBrowser } from "./benchmark-case-browser";@@ -43,6 +44,10 @@ import { askCaseExamples, askCaseTail } from "./benchmark-prompts";import type { AskCaseParams } from "./benchmark-prompts";import { EvaluationDetailModal } from "./evaluation-detail-modal";+/** A score series' paint: palette slot i, or the neutral for the evaluations with no label. */+const scoreSeriesPaint = (s: EvaluationSeries, i: number): ChartPaint =>+ s.unlabeled ? { ink: NEUTRAL_SERIES.text, swatch: NEUTRAL_SERIES.swatch } : { series: i };+/*** Score-over-time line chart: one x slot per evaluation in scoreboard order, labeled with its* timestamp. Scores remain valid on 0..100, while the visible y-axis is padded around the@@ -102,27 +107,23 @@ function ScoreTrendChart({>{series.map((s, si) => {const points = seriesPoints(evaluations, s);+ const paint = scoreSeriesPaint(s, si);return (- <g- key={s.unlabeled ? "unlabeled" : s.key}- className={(s.unlabeled ? NEUTRAL_SERIES : seriesColor(si)).text}- >+ <g key={s.unlabeled ? "unlabeled" : s.key}>{points.length > 1 && (- <path- d={segmentPath(geom, points)}- fill="none"- stroke="currentColor"- strokeWidth={2}+ <ChartLine+ points={segmentPoints(geom, points)}+ paint={paint}opacity={hover !== null ? 0.35 : 1}/>)}{points.map((p) => (- <circle+ <ChartPointkey={p.index}cx={geom.x(p.index)}cy={geom.y(p.value)}- r={hover === p.index ? 4 : 2.5}- className="fill-current"+ paint={paint}+ grow={hover === p.index}opacity={hover !== null && hover !== p.index ? 0.25 : 1}/>))}@@ -155,9 +156,7 @@ function TrendSection({ evaluations }: { evaluations: BenchmarkEvaluation[] }) {key={s.unlabeled ? "unlabeled" : s.key}className="flex items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-400">- <span- className={`inline-block h-2 w-2 shrink-0 rounded-sm ${(s.unlabeled ? NEUTRAL_SERIES : seriesColor(i)).swatch}`}- />+ <ChartSwatch paint={scoreSeriesPaint(s, i)} shape="block" /><span className="font-mono">{labelOf(s)}</span></span>))}@@ -230,7 +229,8 @@ function EvaluationRow({</td><tdclassName={`${CELL} max-w-40 truncate font-mono text-xs text-gray-500 dark:text-gray-400`}- title={evaluation.provider}+ data-tooltip={evaluation.provider}+ data-tooltip-content="code">{evaluation.modelId}</td>@@ -307,9 +307,7 @@ function CasesSection({<span className="block text-sm font-medium text-gray-800 dark:text-gray-200">{item.title}</span>- <span className="block truncate font-mono text-[11px] text-gray-400">- {item.id}- </span>+ <span className="block truncate font-mono text-xs text-gray-400">{item.id}</span></span>{/* Styled as the quiet gray action the Workspace download link is, not as alink: the row itself is the button, so an accent-colored label here read asdiff --git a/packages/web/src/features/benchmark/benchmark-page.tsx b/packages/web/src/features/benchmark/benchmark-page.tsxindex 8b8d1c6e..9a3060d9 100644--- a/packages/web/src/features/benchmark/benchmark-page.tsx+++ b/packages/web/src/features/benchmark/benchmark-page.tsx@@ -130,7 +130,7 @@ function TestedAgents({return (<divclassName="hidden shrink-0 items-center gap-1 sm:flex"- title={`${S.benchmark.testedAgents}: ${agentIds.map(nameOf).join(", ")}`}+ data-tooltip={`${S.benchmark.testedAgents}: ${agentIds.map(nameOf).join(", ")}`}>{shown.map((agentId) => (<AgentAvatar@@ -215,7 +215,7 @@ export function BenchmarkCard({{latest && (<spanclassName={`inline-flex shrink-0 items-center ${ICON_GAP.tight}`}- title={S.benchmark.lastEvaluated(formatRelativeShort(latest.time, locale))}+ data-tooltip={S.benchmark.lastEvaluated(formatRelativeShort(latest.time, locale))}><GlyphIcon d={STAT_ICONS.elapsed} size={ICON_SIZE.inlineGlyph} />{formatRelativeShort(latest.time, locale)}@@ -237,7 +237,7 @@ export function BenchmarkCard({<><spanclassName="block font-mono text-sm font-semibold tabular-nums"- title={S.benchmark.latestScoreLabel}+ data-tooltip={S.benchmark.latestScoreLabel}>{formatScore(latest.score)}</span>@@ -282,7 +282,7 @@ export function BenchmarkCard({{masked && (<divrole="note"- title={failed ? failedHint : S.benchmark.buildingHint}+ data-tooltip={failed ? failedHint : S.benchmark.buildingHint}className="absolute inset-0 flex cursor-not-allowed flex-col items-center justify-center gap-1 rounded-md bg-white/75 px-4 text-center backdrop-blur-[1px] dark:bg-gray-900/75">{/* A failed creation is the one thing here the user has to act on, so its title takes@@ -490,7 +490,7 @@ export function BenchmarkPage() {stays one gap — the Agents and Models headers have the same shape. */}<div className="mb-4"><div className="flex flex-wrap items-center justify-between gap-2">- <h1 className="text-xl font-semibold">{S.benchmark.title}</h1>+ <h1 className="ui-display text-xl font-semibold">{S.benchmark.title}</h1>{/* Search plus the two create entry points. Below sm the search box takes a line ofits own and the pair of buttons wraps under it: three controls sharing a phone'swidth would leave the box too narrow to read what was typed into it. */}@@ -524,7 +524,11 @@ export function BenchmarkPage() {size={ICON_SIZE.rowLead}className="shrink-0 rounded"/>- <span className="min-w-0 truncate" title={nameOf(filterAgentId)}>+ <span+ className="min-w-0 truncate"+ data-tooltip={nameOf(filterAgentId)}+ data-tooltip-content="text"+ >{S.benchmark.filterByAgent(filterAgentId)}</span><Button size="sm" variant="ghost" onClick={clearAgentFilter}>diff --git a/packages/web/src/features/benchmark/evaluation-detail-modal.tsx b/packages/web/src/features/benchmark/evaluation-detail-modal.tsxindex 68b3efb3..63c00b9c 100644--- a/packages/web/src/features/benchmark/evaluation-detail-modal.tsx+++ b/packages/web/src/features/benchmark/evaluation-detail-modal.tsx@@ -29,7 +29,7 @@ import type { AskEvaluationParams } from "./benchmark-prompts";function SessionCell({ sessionId }: { sessionId?: string }) {if (!sessionId) return <span className="text-gray-400">—</span>;return (- <span className="font-mono text-gray-600 dark:text-gray-300" title={sessionId}>+ <span className="font-mono text-gray-600 dark:text-gray-300" data-tooltip={sessionId}>{sessionId}</span>);diff --git a/packages/web/src/features/benchmark/score-sparkline.tsx b/packages/web/src/features/benchmark/score-sparkline.tsxindex b4b0b750..069a09ed 100644--- a/packages/web/src/features/benchmark/score-sparkline.tsx+++ b/packages/web/src/features/benchmark/score-sparkline.tsx@@ -3,8 +3,18 @@* newest point marked. Normalized to the observed range with a small floor, so a series that* moved from 60 to 90 fills the box and a flat one draws a level line through its middle* instead of collapsing onto an edge; there are no ticks — the number beside it is the value.- * A single score is a lone point. Pure SVG, its own geometry (outside the icon family).+ * A single score is a lone point. Pure SVG, its own geometry (outside the icon family), drawn+ * in the theme's chart style at a sparkline's scale: three quarters of the line width and four+ * fifths of the point radius, and the theme's curve.*/+import { ChartLine, ChartPoint, type ChartPaint } from "../../components/ui/chart";++/** The sparkline's paint: its own ink (a single series, no identity to tell apart). */+const INK: ChartPaint = { ink: "" };+/** A sparkline's scale of the theme's line width and point radius. */+const LINE_SCALE = 0.75;+const POINT_SCALE = 0.8;+const W = 72;const H = 22;const PAD = 2.5;@@ -36,20 +46,14 @@ export function ScoreSparkline({viewBox={`0 0 ${W} ${H}`}role="img"aria-label={label}- className={`text-gray-500 dark:text-gray-400 ${className}`}+ data-tooltip={label}+ // ui-chart: a theme may redraw the line and the newest point its own way.+ className={`ui-chart text-gray-500 dark:text-gray-400 ${className}`}>- <title>{label}</title>- {points.length > 1 && (- <polyline- points={points.map(([x, y]) => `${x},${y}`).join(" ")}- fill="none"- stroke="currentColor"- strokeWidth="1.5"- strokeLinecap="round"- strokeLinejoin="round"- />+ {points.length > 1 && <ChartLine points={points} paint={INK} scale={LINE_SCALE} round />}+ {last !== undefined && (+ <ChartPoint cx={last[0]} cy={last[1]} paint={INK} scale={POINT_SCALE} />)}- {last !== undefined && <circle cx={last[0]} cy={last[1]} r={2} fill="currentColor" />}</svg>);}diff --git a/packages/web/src/features/benchmark/use-benchmark-modal.tsx b/packages/web/src/features/benchmark/use-benchmark-modal.tsxindex eaf85e61..c25dd614 100644--- a/packages/web/src/features/benchmark/use-benchmark-modal.tsx+++ b/packages/web/src/features/benchmark/use-benchmark-modal.tsx@@ -27,7 +27,6 @@ import type {import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { formatScore } from "../../lib/format";-import { toneStrip } from "../../lib/tone";import { agentDisplayName, useProject } from "../../state/project";import { Button } from "../../components/ui/button";import { FieldHint, FieldLabel } from "../../components/ui/field";@@ -42,6 +41,7 @@ import { ModelSelect } from "../chat/model-select";import { defaultTargetScore, latestScoreOfAgent } from "./benchmark-metrics";import { MAX_RUNS, evaluateTail, optimizeTail } from "./benchmark-prompts";import type { EvaluateParams, OptimizeParams } from "./benchmark-prompts";+import { NoticeStrip } from "../../components/ui/notice-strip";/** The Skill the evaluator agent must carry; the dialog warns when the chosen agent lacks it. */const EVALUATION_SKILL = "agent-evaluation";@@ -215,7 +215,9 @@ export function UseBenchmarkModal({);const missingSkillStrip = (missing: boolean, message: string) =>missing ? (- <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}>{message}</div>+ <NoticeStrip tone="attention" className="rounded-md border px-3 py-2 text-xs">+ {message}+ </NoticeStrip>) : null;const testedAgentSelect = (hint: string) => (<Select@@ -306,9 +308,9 @@ export function UseBenchmarkModal({{S.benchmark.optimizeDescription}</p>{baseline === null ? (- <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" className="rounded-md border px-3 py-2 text-xs">{S.benchmark.noBaseline}- </div>+ </NoticeStrip>) : (<p className="text-xs text-gray-500 dark:text-gray-400">{S.benchmark.baselineLine(formatScore(baseline.score), optimizeParams.targetScore)}diff --git a/packages/web/src/features/builtin-browser/browser-tab-strip.tsx b/packages/web/src/features/builtin-browser/browser-tab-strip.tsxindex e1bd4756..330c7aea 100644--- a/packages/web/src/features/builtin-browser/browser-tab-strip.tsx+++ b/packages/web/src/features/builtin-browser/browser-tab-strip.tsx@@ -126,7 +126,7 @@ export function BrowserTabStrip({type="button"role="tab"aria-selected={active}- title={title}+ data-tooltip={title}onClick={() => onSelect(tab.id)}// A middle click closes a tab, as in every browser.onAuxClick={(event) => {@@ -155,7 +155,7 @@ export function BrowserTabStrip({</button><buttontype="button"- title={S.builtinBrowser.closeTab}+ data-tooltip={S.builtinBrowser.closeTab}aria-label={`${S.builtinBrowser.closeTab}: ${label}`}onClick={() => onClose(tab.id)}className="flex h-4 w-4 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"@@ -168,7 +168,7 @@ export function BrowserTabStrip({</div><buttontype="button"- title={S.builtinBrowser.newTab}+ data-tooltip={S.builtinBrowser.newTab}aria-label={S.builtinBrowser.newTab}data-testid="builtin-browser-new-tab"onClick={onNew}diff --git a/packages/web/src/features/chat/agent-topology-view.tsx b/packages/web/src/features/chat/agent-topology-view.tsxindex c683904c..8eee9a76 100644--- a/packages/web/src/features/chat/agent-topology-view.tsx+++ b/packages/web/src/features/chat/agent-topology-view.tsx@@ -65,7 +65,7 @@ export function AgentTopologyView({type="button"aria-label={`${label} · ${stateLabel}`}aria-pressed={selected}- title={tooltip}+ data-tooltip={tooltip}onClick={() => onSelect(node)}style={{ left: x, top: y, width: NODE_W, height: NODE_H }}className={`absolute flex flex-col justify-center gap-0.5 rounded-md border bg-white px-2 text-left transition-colors duration-150 dark:bg-gray-900 ${diff --git a/packages/web/src/features/chat/attached-files-banner.tsx b/packages/web/src/features/chat/attached-files-banner.tsxindex 88a8c534..a5cd4397 100644--- a/packages/web/src/features/chat/attached-files-banner.tsx+++ b/packages/web/src/features/chat/attached-files-banner.tsx@@ -21,7 +21,7 @@ export function AttachedFilesBanner({ files }: { files: string[] }) {// that has no fixed width of its own: several long names would otherwise wrap the banner// into a paragraph-tall block above the message. The full list stays reachable as a title.<p- title={label}+ data-tooltip={label}className="flex w-fit max-w-full items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-600 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-400"><GlyphIcon d={PAPERCLIP_ICON} className="shrink-0 text-gray-400 dark:text-gray-500" />diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 1ff33a92..661e3236 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -128,11 +128,12 @@ import { PAPERCLIP_ICON } from "./attached-files-banner";import { FileDropZone } from "./drop-zone";import { ContextGauge } from "./context-gauge";import { modelWindowBelowCompactionLimit } from "../../lib/context";-import { toneStrip } from "../../lib/tone";import { splitDroppedFiles } from "../../lib/file-drop";import { splitBySize } from "../../lib/upload-limits";import type { ComposerReference } from "../../lib/workspace-tree";import { ReferenceChip } from "./reference-chip";+import { NoticeStrip } from "../../components/ui/notice-strip";+import { ChoiceCheck, menuPanelClass, menuRowClass, menuRowTone } from "../../components/ui/field";/*** Agent candidate panel for the `/agent` switch picker, on the shared PickerList (search, scroll@@ -263,7 +264,7 @@ function ThinkingLevelSelect({button={<buttontype="button"- title={`${S.chat.thinkingLevel}:${label}`}+ data-tooltip={`${S.chat.thinkingLevel}:${label}`}aria-label={S.chat.thinkingLevel}disabled={disabled || value === null}onClick={() => setOpen(!open)}@@ -288,11 +289,7 @@ function ThinkingLevelSelect({onChange(level);setOpen(false);}}- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${- level === value- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-600 dark:text-gray-400"- }`}+ className={`flex items-center gap-2 ${menuRowClass} text-xs ${menuRowTone(level === value)}`}>{/* The one surface that annotates: a menu row is where the tier is CHOSEN, so itnames the wire value the pick will send. The trigger above stays the plain@@ -300,7 +297,7 @@ function ThinkingLevelSelect({<span className="min-w-0 flex-1 truncate">{S.chat.thinkingLevelMenuName(S.chat.thinkingLevelNames[level] ?? level, level)}</span>- <span className="w-3 shrink-0 text-center">{level === value ? "✓" : ""}</span>+ <ChoiceCheck on={level === value} /></button>))}{note && (@@ -349,7 +346,7 @@ function SteerModeRow({const modeButton = (mode: SteerMode, label: string, hint: string) => (<buttontype="button"- title={hint}+ data-tooltip={hint}aria-pressed={steerMode === mode}onClick={() => onChangeSteerMode(mode)}className={`h-5 rounded px-1.5 text-xs transition-colors duration-150 ${@@ -415,7 +412,7 @@ function SkillSelect({<buttontype="button"aria-label={S.chat.skillsSelect}- title={S.chat.skillsSelect}+ data-tooltip={S.chat.skillsSelect}disabled={disabled}// The panel is unmounted while closed, so its search box starts empty on every open.onClick={() => setOpen(!open)}@@ -492,7 +489,7 @@ function PlusMenu({<buttontype="button"aria-label={S.chat.plusMenu}- title={S.chat.plusMenu}+ data-tooltip={S.chat.plusMenu}onClick={() => setOpen(!open)}className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200">@@ -510,18 +507,14 @@ function PlusMenu({setOpen(false);item.onSelect();}}- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent dark:hover:bg-gray-800 dark:disabled:hover:bg-transparent ${- item.active- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-600 dark:text-gray-400"- }`}+ className={`flex items-center gap-2 ${menuRowClass} text-xs disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent dark:disabled:hover:bg-transparent ${menuRowTone(item.active)}`}><GlyphIcon d={item.icon} className="shrink-0 text-gray-400 dark:text-gray-500" /><span className="shrink-0">{item.label}</span><span className="min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500">{item.desc}</span>- <span className="w-3 shrink-0 text-center">{item.active ? "✓" : ""}</span>+ <ChoiceCheck on={item.active} /></button>))}{footer && (@@ -620,7 +613,7 @@ function QueuedMessageLine({<buttontype="button"aria-label={S.chat.recallQueued}- title={S.chat.recallQueuedTitle}+ data-tooltip={S.chat.recallQueuedTitle}disabled={disabled}onClick={onRecall}className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"@@ -2061,7 +2054,7 @@ export function ChatInput({{slashOpen && (<divstyle={{ maxHeight: upwardMaxH }}- className="anim-pop absolute bottom-full left-0 z-40 mb-1.5 w-80 max-w-[calc(100vw-2rem)] overflow-y-auto overscroll-contain rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900"+ className={`ui-glass ${menuPanelClass} absolute bottom-full left-0 z-40 mb-1.5 w-80 max-w-[calc(100vw-2rem)] overscroll-contain`}>{slashMatches.map((c, i) => (<button@@ -2077,7 +2070,8 @@ export function ChatInput({<span className="shrink-0 font-mono text-gray-800 dark:text-gray-200">{c.cmd}</span>{/* Overly long descriptions (skill descriptions) are truncated: full text goes into the title. */}<span- title={c.desc}+ data-tooltip={c.desc}+ data-tooltip-content="text"className="min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400">{c.desc}@@ -2153,7 +2147,7 @@ export function ChatInput({{attachments.map((file, i) => (<spankey={i}- title={file.name}+ data-tooltip={file.name}className={`anim-pop flex max-w-56 items-center ${ICON_GAP.tight} rounded-md border border-gray-200 bg-gray-50 py-1 pl-2 pr-1 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200`}><GlyphIcon@@ -2185,8 +2179,9 @@ export function ChatInput({waiting on the user. Dismissible, because keeping the threshold high on purpose is alegitimate answer and a notice with no way down stops being read. */}{windowNoticeOpen && contextWindow !== undefined && compactionLimit !== undefined && (- <div- className={`anim-fade mb-1 flex items-center justify-between gap-3 rounded-md border px-2.5 py-2 text-xs ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="anim-fade mb-1 flex items-center justify-between gap-3 rounded-md border px-2.5 py-2 text-xs"><p className="min-w-0">{S.chat.contextWindowUnderThreshold(@@ -2210,7 +2205,7 @@ export function ChatInput({</Button>)}</div>- </div>+ </NoticeStrip>)}{/* When the model doesn't support viewing images directly: images still upload as usual,@@ -2290,7 +2285,7 @@ export function ChatInput({(help text/button text visibility uses @md/@lg container breakpoints) — because thecard's width changes with the viewport and the Files panel squeezing it, viewportbreakpoints wouldn't judge it accurately. */}- <div className="@container rounded-lg border border-gray-300 bg-white px-2.5 pb-2 pt-2 transition-[border-color,box-shadow] duration-200 focus-within:border-gray-500 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-400">+ <div className="ui-glass @container rounded-lg border border-gray-300 bg-white px-2.5 pb-2 pt-2 transition-[border-color,box-shadow] duration-200 focus-within:border-gray-500 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-400">{/* Chip row above the text body: the staged switch target (an /agent handoff or a/model fork — never both), the selected skills, and whatever the Files panel hascontributed, all sharing the same chip look. Remove buttons recolor the x on hover@@ -2305,7 +2300,10 @@ export function ChatInput({fixed upward popover so it never covers the objective textarea below. */}{goalOn && (<span className="anim-pop flex max-w-full items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200">- <span className="flex shrink-0 items-center gap-1" title={S.chat.goalModeDesc}>+ <span+ className="flex shrink-0 items-center gap-1"+ data-tooltip={S.chat.goalModeDesc}+ ><GlyphIcon d={GOAL_ICON} size={13} className="text-gray-500 dark:text-gray-400" /><span>{S.chat.goalMode}</span></span>@@ -2359,7 +2357,7 @@ export function ChatInput({aria-invalid={goalBudgetDraftInvalid}aria-describedby="goal-budget-hint"{...noAutofill}- title={+ data-tooltip={goalBudgetDraftInvalid ? S.chat.goalBudgetInvalid : S.chat.goalBudgetHint}className={`min-w-0 flex-1 rounded-md border bg-white px-2 py-1 font-mono text-xs leading-5 placeholder:text-gray-400 focus:outline-none focus:ring-2 dark:bg-gray-950 dark:placeholder:text-gray-500 ${@@ -2371,7 +2369,7 @@ export function ChatInput({<buttontype="button"aria-label={S.chat.goalBudgetSave}- title={S.chat.goalBudgetSave}+ data-tooltip={S.chat.goalBudgetSave}disabled={goalBudgetDraftInvalid}onClick={saveGoalBudget}className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:opacity-35 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"@@ -2406,7 +2404,7 @@ export function ChatInput({Agent" without spelling the sentence out. */}{target !== null && (<span- title={S.chat.handoffTargetTitle(agentDisplayName(target))}+ data-tooltip={S.chat.handoffTargetTitle(agentDisplayName(target))}className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"><AgentAvatar@@ -2434,7 +2432,7 @@ export function ChatInput({model display; sending forks the conversation onto it. */}{pendingModel !== null && (<span- title={S.chat.modelSwitchTargetTitle(modelLabel(pendingModel))}+ data-tooltip={S.chat.modelSwitchTargetTitle(modelLabel(pendingModel))}className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"><ProviderLogo provider={pendingModel.provider} className="h-3.5 w-3.5 shrink-0" />@@ -2458,7 +2456,7 @@ export function ChatInput({<spankey={name}className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"- {...(meta ? { title: localizedShortText(locale, meta) } : {})}+ {...(meta ? { "data-tooltip": localizedShortText(locale, meta) } : {})}><SkillIconicon={meta?.icon}@@ -2535,7 +2533,7 @@ export function ChatInput({// text-base, not the sm rung the form controls take: this is a full-height typing// surface for prose the user composes and re-reads, not a field in a form, and the// toolbar under it is already text-xs so the two do not compete.- className="block max-h-44 min-h-[60px] w-full resize-none bg-transparent px-1 py-0.5 text-base leading-6 placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60 dark:placeholder:text-gray-500"+ className="block max-h-44 min-h-[60px] w-full resize-none bg-transparent px-1 py-0.5 font-sans text-base leading-6 placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60 dark:placeholder:text-gray-500"/>{/* Bottom toolbar row — one line, two groups: the settings controls sit left, the@@ -2640,7 +2638,8 @@ export function ChatInput({{/* Help text: shown only when the card is wide enough (@lg); it never competes forspace on phones, where the group scrolls instead. */}<span- title={S.chat.slashHint}+ data-tooltip={S.chat.slashHint}+ data-tooltip-content="text"className="hidden min-w-0 truncate text-gray-300 @lg:block dark:text-gray-600">{S.chat.slashHint}@@ -2697,7 +2696,7 @@ export function ChatInput({/* Subagent composer: the child runs whatever model it was spawned with, and no/model command exists here — so the badge is pure display, nothing to click. */<span- title={modelRef?.modelId ?? ""}+ data-tooltip={modelRef?.modelId ?? ""}className="flex h-8 min-w-0 max-w-44 shrink items-center gap-1.5 rounded-md px-1 text-gray-400 dark:text-gray-500"><ProviderLogo@@ -2713,7 +2712,7 @@ export function ChatInput({(the /model command) instead of doing nothing. */<buttontype="button"- title={modelRef?.modelId ?? ""}+ data-tooltip={modelRef?.modelId ?? ""}// Short accessible name (the toast carries the full hint): the long copy// contains the literal "发送"/"Send", which would collide with the send// button's accessible name for assistive tech and name-based test queries.@@ -2737,7 +2736,7 @@ export function ChatInput({Merging the pair keeps the running-state row within a 320px viewport. */}<buttontype="button"- title={stopAction ? S.chat.stop : running ? midRunSendLabel : S.chat.send}+ data-tooltip={stopAction ? S.chat.stop : running ? midRunSendLabel : S.chat.send}aria-label={stopAction ? S.chat.stop : running ? midRunSendLabel : S.chat.send}disabled={stopAction ? false : running ? !canMidRunSend : !canSend}onClick={() => (stopAction ? void onStop() : void send())}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 54fd7aee..fc898414 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -165,7 +165,7 @@ const PROCESS_POLL_MS = 15_000;function StatChip({ icon, value, label }: { icon: string; value: ReactNode; label: string }) {return (<span- title={label}+ data-tooltip={label}className={`flex shrink-0 items-center ${ICON_GAP.tight} font-mono text-xs text-gray-500 dark:text-gray-400`}><GlyphIcon d={icon} />@@ -2039,7 +2039,10 @@ export function ChatPage() {return (// data-dock-host: the docks' edge bands, drop preview and the bottom dock's height// ratio all measure this column (dock-drag.tsx / dock-panel.tsx).- <div data-dock-host className="relative flex h-full flex-col bg-white dark:bg-gray-950">+ // bg-canvas: the chat column is the page, so it takes the theme's page colour — white and+ // gray-950 in Primer, exactly what it painted before; paper in Console, the sheet in Frost —+ // and the transcript's sticky rows, painted in the same token, sit on it without a seam.+ <div data-dock-host className="relative flex h-full flex-col bg-canvas">{/* Workflow tabs: the Agent's own pages beside the chat. A workflow tab covers thechat (which stays mounted, so its state survives a look at the page) below thestrip; the strip is absent when the Agent has no workflow with a UI. */}@@ -2070,7 +2073,7 @@ export function ChatPage() {{selected && (<div className="flex shrink-0 items-center gap-2.5 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800"><div className="flex min-w-0 flex-1 items-center gap-3">- <h1 className="flex min-w-0 text-[15px] font-semibold">+ <h1 className="flex min-w-0 font-sans text-[15px] font-semibold"><Truncated text={selected.title ?? S.chat.defaultSessionTitle} /></h1>{/* Session-level state: a turning hourglass while the run is active, and nothing at@@ -2080,7 +2083,7 @@ export function ChatPage() {Below sm only the glyph remains so the title keeps its room. */}{headerActivity === "running" && (<span- title={sessionActivityLabel(headerActivity)}+ data-tooltip={sessionActivityLabel(headerActivity)}className="flex shrink-0 items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400"><SessionActivityIcon activity={headerActivity} />@@ -2119,7 +2122,7 @@ export function ChatPage() {button={<buttontype="button"- title={S.chat.infoPanel}+ data-tooltip={S.chat.infoPanel}aria-label={S.chat.infoPanel}aria-expanded={infoOpen}onClick={() => setInfoOpen(!infoOpen)}@@ -2163,7 +2166,7 @@ export function ChatPage() {wherever they appear; the title still names the count in words. */}{backgroundCount > 0 && (<span- title={S.chat.backgroundTasks(backgroundCount)}+ data-tooltip={S.chat.backgroundTasks(backgroundCount)}className={`flex shrink-0 items-center ${ICON_GAP.tight} font-mono text-xs ${toneInk.busy}`}><GlyphIcon d={BACKGROUND_TASKS_ICON} />@@ -2274,7 +2277,7 @@ export function ChatPage() {{exitedIds.length > 0 && (<buttontype="button"- title={S.chat.processClearExitedHint}+ data-tooltip={S.chat.processClearExitedHint}disabled={procBusy !== null}onClick={() => void onClearExitedProcesses()}className="shrink-0 cursor-pointer text-xs text-gray-400 transition-colors duration-150 hover:text-gray-600 disabled:cursor-default disabled:opacity-60 dark:text-gray-500 dark:hover:text-gray-300"@@ -2309,7 +2312,7 @@ export function ChatPage() {href={p.serviceUrl}target="_blank"rel="noopener noreferrer"- title={p.serviceUrl}+ data-tooltip={p.serviceUrl}className="text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-700 hover:decoration-gray-500 dark:text-gray-400 dark:decoration-gray-600 dark:hover:text-gray-200">{p.serviceUrl.replace(/^https?:\/\//i, "")}@@ -2342,7 +2345,7 @@ export function ChatPage() {says what leaves with it. */}<buttontype="button"- title={S.chat.processRemoveHint}+ data-tooltip={S.chat.processRemoveHint}disabled={procBusy !== null}onClick={() => void onRemoveProcess(p.processId)}className="shrink-0 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:cursor-default disabled:opacity-60 dark:border-gray-700 dark:text-gray-300 dark:hover:border-red-900 dark:hover:bg-red-950/40 dark:hover:text-red-400"@@ -2464,7 +2467,7 @@ export function ChatPage() {while that dock is hidden, and opens its panels in one click. */}<DockLauncher agentsPending={anySubagentPending} /></div>- <div className="shrink-0 border-t border-gray-200 bg-white px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3 dark:border-gray-800 dark:bg-gray-950">+ <div className="shrink-0 border-t border-gray-200 bg-canvas px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3 dark:border-gray-800"><div className="mx-auto max-w-3xl">{/* Goal banner docked above the composer: an in-flight goal's progress(restored on load while still active), or the terminal state reacheddiff --git a/packages/web/src/features/chat/context-gauge.tsx b/packages/web/src/features/chat/context-gauge.tsxindex a9d029aa..758595f5 100644--- a/packages/web/src/features/chat/context-gauge.tsx+++ b/packages/web/src/features/chat/context-gauge.tsx@@ -260,7 +260,7 @@ export function ContextGauge({if (sessionId === undefined) {return (- <span title={usageText} aria-label={usageText} role="img" className={shell}>+ <span data-tooltip={usageText} aria-label={usageText} role="img" className={shell}>{gauge}</span>);@@ -272,7 +272,7 @@ export function ContextGauge({<buttonref={triggerRef}type="button"- title={usageText}+ data-tooltip={usageText}aria-label={usageText}aria-expanded={open}aria-controls={panelId}@@ -472,7 +472,7 @@ function ContextPanel({<div aria-hidden className="absolute inset-0 bg-gray-200 dark:bg-gray-800">{beyondFraction !== null && beyondFraction < 1 && (<div- title={S.chat.contextBeyondThreshold}+ data-tooltip={S.chat.contextBeyondThreshold}className="context-hatch absolute inset-y-0 right-0"style={{ left: `${beyondFraction * 100}%` }}/>@@ -485,7 +485,7 @@ function ContextPanel({p.tokens > 0 ? (<spankey={p.key}- title={`${PART_LABELS[p.key]()} ~${humanizeTokens(p.tokens)} · ${p.percent}%`}+ data-tooltip={`${PART_LABELS[p.key]()} ~${humanizeTokens(p.tokens)} · ${p.percent}%`}onMouseEnter={() => setHovered(p.key)}onMouseLeave={() => setHovered(null)}onClick={() => togglePinned(p.key)}@@ -547,9 +547,10 @@ function ContextPanel({keeps the switch, so the Files view can say so itself. */}<div className="mt-2 flex items-center justify-between gap-2 border-t border-gray-100 pt-1.5 dark:border-gray-800"><p- title={+ data-tooltip={ranking === "tools" ? S.chat.contextTopToolsHint : S.chat.contextTopFilesHint}+ data-tooltip-content="text"className="min-w-0 truncate text-gray-400 dark:text-gray-500">{ranking === "tools" ? S.chat.contextTopTools : S.chat.contextTopFiles}@@ -729,7 +730,7 @@ function ThresholdCutter({aria-valuemax={Math.max(windowTokens, shown)}aria-valuenow={shown}aria-valuetext={humanizeTokens(shown)}- title={S.chat.contextThresholdHover(humanizeTokens(shown))}+ data-tooltip={S.chat.contextThresholdHover(humanizeTokens(shown))}onFocus={() => setFocused(true)}onBlur={() => {setFocused(false);@@ -747,7 +748,7 @@ function ThresholdCutter({// decorative, naming the threshold on hover, and nothing to focus.<divaria-hidden- title={S.chat.contextThresholdHover(humanizeTokens(shown))}+ data-tooltip={S.chat.contextThresholdHover(humanizeTokens(shown))}style={box}className="absolute flex justify-center">@@ -892,7 +893,8 @@ function ShareRow({<span aria-hidden className={`h-2 w-2 shrink-0 rounded-[2px] ${swatch}`} />)}<span- title={title ?? label}+ data-tooltip={title ?? label}+ data-tooltip-content="code"className={`min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300 ${mono ? "font-mono" : ""}`}>{label}diff --git a/packages/web/src/features/chat/conversation-outline.tsx b/packages/web/src/features/chat/conversation-outline.tsxindex 11d903a1..48e9bbed 100644--- a/packages/web/src/features/chat/conversation-outline.tsx+++ b/packages/web/src/features/chat/conversation-outline.tsx@@ -418,7 +418,7 @@ export function OutlineMenuButton({button={<buttontype="button"- title={S.chat.outlineTitle}+ data-tooltip={S.chat.outlineTitle}aria-label={S.chat.outlineTitle}onClick={() => setOpenComputing(!open)}className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"diff --git a/packages/web/src/features/chat/disclosure-row.tsx b/packages/web/src/features/chat/disclosure-row.tsxindex 0c43100a..8a2be015 100644--- a/packages/web/src/features/chat/disclosure-row.tsx+++ b/packages/web/src/features/chat/disclosure-row.tsx@@ -9,6 +9,7 @@import { useRef, useState } from "react";import type { ReactNode } from "react";import { Chevron } from "../../components/ui/chevron";+import type { RunState } from "../../components/ui/status-icon";/*** The row itself (collapsed and expanded state share it; the hover tone is the "open or@@ -82,6 +83,35 @@ export const DISCLOSURE_BODY_MD_CLASS =export const DISCLOSURE_CARD_CLASS ="anim-msg my-2 overflow-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900";+/**+ * What a work step is and where it stands, for the `ui-activity` hook: the transcript's thinking+ * and tool rows and the work group's header carry it, so a theme can render work in progress+ * its own way (a glow while running, a transcript line with a block progress bar).+ */+export interface ActivityMark {+ kind: "thinking" | "tool";+ state: "running" | "done" | "error";+}++/**+ * The run states the status icon shows, folded onto the three the activity hook knows. Waiting+ * on an approval is unfinished work, so it reads as running; a stopped step is settled.+ */+export function activityState(state: RunState): ActivityMark["state"] {+ if (state === "failed") return "error";+ return state === "running" || state === "waiting" ? "running" : "done";+}++/**+ * The activity hook's progress slot, rendered only while the step is actually executing (not+ * while it waits on an approval), empty and `hidden`: the default theme draws no bar, and a+ * hidden node leaves no gap in the row's flex spacing, so a theme that draws one sets its own+ * `display`.+ */+export function ActivityProgress({ running }: { running: boolean }) {+ return running ? <span data-slot="progress" aria-hidden className="hidden" /> : null;+}+export function DisclosureRow({icon,label,@@ -89,6 +119,7 @@ export function DisclosureRow({variant = "row",sticky = false,defaultOpen = false,+ activity,children,}: {/** Leading status icon slot (a StatusIcon, matching the thinking/tool rows). */@@ -105,6 +136,8 @@ export function DisclosureRow({/** Pins the row while its body scrolls: nested rows under the stuck group header, a header against the scrollport (per variant). */sticky?: boolean;defaultOpen?: boolean;+ /** A work step (the thinking row): the row carries the `ui-activity` hook with this mark. */+ activity?: ActivityMark;/** Expanded body; the caller styles it (md body, output <pre>, …). */children: ReactNode;}) {@@ -130,11 +163,16 @@ export function DisclosureRow({}}}aria-expanded={open}- className={`${sticky ? `${stickyClass} ` : ""}${rowClass}`}+ className={`${activity ? "ui-activity " : ""}${sticky ? `${stickyClass} ` : ""}${rowClass}`}+ data-kind={activity?.kind}+ data-state={activity?.state}>{icon}- <span className={labelClass}>{label}</span>+ <span className={labelClass} {...(activity ? { "data-slot": "label" } : {})}>+ {label}+ </span>{trailing}+ {activity && <ActivityProgress running={activity.state === "running"} />}<span className="min-w-0 flex-1" /><Chevron open={open} className="text-gray-400" /></button>diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 0fce9d69..1f14615d 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -98,6 +98,7 @@ import { effectiveThinkingLevel } from "./thinking-level";import { WorkspaceSelect, pillClass } from "./workspace-select";import { sameModelRef } from "../models/model-grouping";import { ICON_GAP } from "../../lib/icon-scale";+import { ChoiceCheck, menuRowClass, menuRowTone } from "../../components/ui/field";/** Coalescing window for writing body text to the cache: keystrokes are frequent, so a short batch accumulates before persisting (option changes are still written immediately). */const DRAFT_SAVE_DEBOUNCE_MS = 300;@@ -875,7 +876,7 @@ export function DraftView({padding, so a small margin is enough to sit visually close to the title. */}<div className="mb-10 text-center"><PenguinLogo className="mx-auto mb-1 h-36 w-36 rounded-3xl" />- <h1 className="text-3xl font-semibold tracking-tight text-gray-900 dark:text-gray-100">+ <h1 className="ui-display text-3xl font-semibold tracking-tight text-gray-900 dark:text-gray-100">{S.appName}</h1><p className="mt-2 text-base text-gray-400 dark:text-gray-500">{S.chat.draftSubtitle}</p>@@ -969,7 +970,7 @@ export function DraftView({<li key={task.id}><buttontype="button"- title={`${copy.desc}\n${S.chat.exampleFillHint}`}+ data-tooltip={`${copy.desc}\n${S.chat.exampleFillHint}`}disabled={!skillsLoaded}onClick={() => fillExample(task)}className={`flex w-full items-center gap-2 ${exampleRowClass}`}@@ -1066,7 +1067,7 @@ function VersionBadge() {<buttontype="button"onClick={openUpdateModal}- title={note}+ data-tooltip={note}aria-label={note}className={`${versionBadgeClass} hover:underline`}>@@ -1097,7 +1098,7 @@ function AgentSelect({button={<buttontype="button"- title={S.chat.chooseAgent}+ data-tooltip={S.chat.chooseAgent}aria-label={S.chat.chooseAgent}onClick={() => setOpen(!open)}className={pillClass}@@ -1130,7 +1131,7 @@ function AgentSelect({onSelect(a);setOpen(false);}}- className={`flex w-full items-center ${ICON_GAP.menu} px-3 py-1.5 text-left transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}+ className={`flex items-center ${ICON_GAP.menu} ${menuRowClass} ${menuRowTone(active)}`}><AgentAvatarid={a.agentId}@@ -1139,24 +1140,14 @@ function AgentSelect({className="shrink-0 rounded"/><span className="min-w-0 flex-1">- <span- className={`block truncate text-xs ${- active- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-700 dark:text-gray-300"- }`}- >- {agentDisplayName(a)}- </span>+ <span className="block truncate text-xs">{agentDisplayName(a)}</span>{a.description && (<span className="block truncate text-[11px] text-gray-400 dark:text-gray-500">{a.description}</span>)}</span>- <span className="w-4 shrink-0 text-center text-xs text-gray-500 dark:text-gray-400">- {active ? "✓" : ""}- </span>+ <ChoiceCheck on={active} /></button>);})}diff --git a/packages/web/src/features/chat/goal-banner.tsx b/packages/web/src/features/chat/goal-banner.tsxindex 66dc8095..106eafe6 100644--- a/packages/web/src/features/chat/goal-banner.tsx+++ b/packages/web/src/features/chat/goal-banner.tsx@@ -21,7 +21,11 @@ export function GoalStatusBanner({ goal }: { goal: GoalBannerState }) {return (<div className="anim-fade mb-2 flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-600 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-400"><GlyphIcon d={GOAL_ICON} className="shrink-0 text-gray-400 dark:text-gray-500" />- <span className="min-w-0 flex-1 truncate" title={goal.objective}>+ <span+ className="min-w-0 flex-1 truncate"+ data-tooltip={goal.objective}+ data-tooltip-content="text"+ >{goal.objective}</span><span className="shrink-0 text-gray-400 dark:text-gray-500">diff --git a/packages/web/src/features/chat/handoff-banner.tsx b/packages/web/src/features/chat/handoff-banner.tsxindex 339f5aa0..31406e84 100644--- a/packages/web/src/features/chat/handoff-banner.tsx+++ b/packages/web/src/features/chat/handoff-banner.tsx@@ -35,7 +35,7 @@ export function HandoffBanner({ origin }: { origin: HandoffOrigin }) {return (<buttontype="button"- title={S.chat.handoffBack(origin.sessionTitle)}+ data-tooltip={S.chat.handoffBack(origin.sessionTitle)}onClick={() => navigate(`/chat/${sessionId}`)}className={`${bannerFrame} transition-colors hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200`}>@@ -58,7 +58,7 @@ export function ModelSwitchBanner({ origin }: { origin: ModelSwitchOrigin }) {return (<buttontype="button"- title={S.chat.handoffBack(origin.sessionTitle)}+ data-tooltip={S.chat.handoffBack(origin.sessionTitle)}onClick={() => navigate(`/chat/${sessionId}`)}className={`${bannerFrame} transition-colors hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200`}>diff --git a/packages/web/src/features/chat/mcp-connect-banner.tsx b/packages/web/src/features/chat/mcp-connect-banner.tsxindex ce5f22fa..4fd9c05b 100644--- a/packages/web/src/features/chat/mcp-connect-banner.tsx+++ b/packages/web/src/features/chat/mcp-connect-banner.tsx@@ -87,7 +87,8 @@ function ServerGroup({ outcome, tools }: { outcome: McpServerOutcome; tools: Mcp</code>{tool.description !== undefined && (<span- title={tool.description}+ data-tooltip={tool.description}+ data-tooltip-content="text"className="min-w-0 truncate text-xs text-gray-400 dark:text-gray-500">{tool.description}diff --git a/packages/web/src/features/chat/md.tsx b/packages/web/src/features/chat/md.tsxindex 15957fe3..b2dd135a 100644--- a/packages/web/src/features/chat/md.tsx+++ b/packages/web/src/features/chat/md.tsx@@ -101,19 +101,21 @@ export function WorkspaceLinksProvider({* a Workspace file opens in the Files panel, an `#anchor` scrolls within the page, and a* relative href with nowhere to go stays put — a relative href resolves against the SPA's own* route, so a new tab on it is a second copy of the App on a page that does not exist.- * All other anchor props react-markdown supplies (`href`, `title` from `[text](url "title")`,- * ...) are forwarded as-is — only its non-DOM `node` prop is stripped — and the behaviour sits- * after the spread so it always wins. Long-URL wrapping is CSS (`.md-body a` in styles.css).+ * All other anchor props react-markdown supplies (`href`, ...) are forwarded as-is — only its+ * non-DOM `node` prop is stripped — and the behaviour sits after the spread so it always wins.+ * A link title (`[text](url "title")`) becomes the shared tooltip's text rather than a native+ * `title`, like every other hover hint in the app. Long-URL wrapping is CSS (`.md-body a` in styles.css).*/function MdLink({node: _node,children,+ title,...anchorProps}: ComponentPropsWithoutRef<"a"> & ExtraProps) {const links = useContext(WorkspaceLinksContext);const behavior = links === null ? NEW_TAB : replyLinkBehavior(anchorProps.href, links);return (- <a {...anchorProps} {...behavior}>+ <a {...anchorProps} data-tooltip={title} {...behavior}>{children}</a>);diff --git a/packages/web/src/features/chat/memory-changes-card.tsx b/packages/web/src/features/chat/memory-changes-card.tsxindex 6748fac5..b108d6aa 100644--- a/packages/web/src/features/chat/memory-changes-card.tsx+++ b/packages/web/src/features/chat/memory-changes-card.tsx@@ -19,6 +19,7 @@ import { memoryRowKey } from "../../lib/omni/memory-changes";import { PathLabel } from "./message-files-card";import { FILE_EDIT_ICON, FILE_WRITE_ICON, MEMORY_ICON } from "../../components/ui/icons";import { scopeGlyph } from "./memory-view";+import { namedHint } from "../../components/ui/tooltip";const MAX_VISIBLE = 3;@@ -47,14 +48,14 @@ export function MemoryChangesCard({const glyph = scopeGlyph(row.scope, row.scopeKey);return (<>- <span title={glyph.title} className="shrink-0 text-gray-400">+ <span data-tooltip={glyph.title} className="shrink-0 text-gray-400"><GlyphIcon d={glyph.d} size={ICON_SIZE.rowLead} /><span className="sr-only">{glyph.title}</span></span><PathLabel path={row.file} /><span className="min-w-0 flex-1" /><span- title={row.op === "write" ? S.chat.memoryOpWrite : S.chat.memoryOpEdit}+ {...namedHint(row.op === "write" ? S.chat.memoryOpWrite : S.chat.memoryOpEdit)}className="shrink-0 text-gray-400"><GlyphIcon@@ -94,7 +95,7 @@ export function MemoryChangesCard({<buttonkey={key}type="button"- title={S.chat.memoryRowOpen}+ data-tooltip={S.chat.memoryRowOpen}onClick={() => onLocateChange(row)}className="group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50">diff --git a/packages/web/src/features/chat/memory-view.tsx b/packages/web/src/features/chat/memory-view.tsxindex 21521b40..23a520a6 100644--- a/packages/web/src/features/chat/memory-view.tsx+++ b/packages/web/src/features/chat/memory-view.tsx@@ -137,13 +137,13 @@ export function ChatMemoryView({<buttontype="button"onClick={() => setMode(memoryNavBack())}- title={S.chat.memoryBack}+ data-tooltip={S.chat.memoryBack}className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200"><GlyphIcon d={BACK_ICON} size={ICON_SIZE.iconButton} /><span className="sr-only">{S.chat.memoryBack}</span></button>- <span title={glyph.title} className="shrink-0 text-gray-400">+ <span data-tooltip={glyph.title} className="shrink-0 text-gray-400"><GlyphIcon d={glyph.d} size={ICON_SIZE.rowLead} /><span className="sr-only">{glyph.title}</span></span>@@ -194,7 +194,7 @@ export function ChatMemoryView({<buttontype="button"onClick={onOpenSettings}- title={S.chat.openAgentMemory}+ data-tooltip={S.chat.openAgentMemory}className="flex min-w-0 cursor-pointer items-center gap-1 rounded-md px-1.5 py-1 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"><GlyphIcon d={OPEN_SETTINGS_ICON} size={ICON_SIZE.inlineGlyph} />@@ -225,7 +225,8 @@ export function ChatMemoryView({</span><pclassName="min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400"- title={group.workspacePath}+ data-tooltip={group.workspacePath}+ data-tooltip-content="text">{groupTitle(group)}</p>@@ -245,7 +246,7 @@ export function ChatMemoryView({<p className="flex items-center gap-1.5 truncate font-mono text-[13px] font-medium text-gray-800 dark:text-gray-200">{row.changed !== undefined && (<span- title={S.chat.memoryChangedMark}+ data-tooltip={S.chat.memoryChangedMark}className="h-1.5 w-1.5 shrink-0 rounded-full bg-brand-500"><span className="sr-only">{S.chat.memoryChangedMark}</span>diff --git a/packages/web/src/features/chat/message-files-card.tsx b/packages/web/src/features/chat/message-files-card.tsxindex f438dca8..8081c6dc 100644--- a/packages/web/src/features/chat/message-files-card.tsx+++ b/packages/web/src/features/chat/message-files-card.tsx@@ -125,7 +125,7 @@ export function MessageFilesCard({<buttonkey={path}type="button"- title={path}+ data-tooltip={path}onClick={() => onOpenFile(path)}className="group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50">diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsxindex c983c6f3..002f244b 100644--- a/packages/web/src/features/chat/message-item.tsx+++ b/packages/web/src/features/chat/message-item.tsx@@ -233,7 +233,7 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo<div className="anim-msg group my-4 flex flex-col items-end"><div className="max-w-[88%] rounded-lg bg-gray-100 px-4 py-2.5 md:max-w-[75%] dark:bg-gray-800">{/* wrap-anywhere: long unbroken strings like attachment paths/long URLs wrap within the bubble on narrow (mobile) screens instead of overflowing; unlike break-words it also shrinks min-content, so a pathological token can't stretch the flex bubble itself. Normal words still only break when a token can't fit on a line. */}- <p className="wrap-anywhere whitespace-pre-wrap text-base leading-relaxed text-gray-900 dark:text-gray-100">+ <p className="wrap-anywhere font-sans whitespace-pre-wrap text-base leading-relaxed text-gray-900 dark:text-gray-100">{text}</p></div>@@ -310,7 +310,7 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCod={USER_STEERING_ICON}className="mt-1 shrink-0 text-gray-400 dark:text-gray-500"/>- <p className="wrap-anywhere whitespace-pre-wrap text-sm leading-relaxed text-gray-800 dark:text-gray-100">+ <p className="wrap-anywhere font-sans whitespace-pre-wrap text-sm leading-relaxed text-gray-800 dark:text-gray-100"><span className="mr-1.5 text-xs font-semibold text-gray-500 dark:text-gray-400">{S.chat.userSteering}</span>@@ -363,7 +363,7 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo// line's copy grabs **all** of this turn's assistant text (see collectTaskAssistant),// which is more useful than copying segment by segment.return (- <div className="md-body anim-msg my-3 text-base leading-relaxed text-gray-800 dark:text-gray-100">+ <div className="md-body anim-msg my-3 font-sans text-base leading-relaxed text-gray-800 dark:text-gray-100">{/* Re-renders the accumulated text directly while streaming (a key point of the contract implementation); memoized so settled messages skip the re-parse, and code blocks highlight once on settle (see md.tsx). */}<Md text={item.text} streaming={item.streaming} />{item.streaming && <span className="animate-pulse text-gray-400">▌</span>}diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsxindex 555cb21d..b0a71de9 100644--- a/packages/web/src/features/chat/message-stream.tsx+++ b/packages/web/src/features/chat/message-stream.tsx@@ -496,7 +496,7 @@ export function MessageStream({<buttontype="button"aria-label={S.chat.jumpToLatest}- title={S.chat.jumpToLatest}+ data-tooltip={S.chat.jumpToLatest}onClick={jumpToLatest}className="anim-pop absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded-full border border-gray-300 bg-white p-1.5 text-gray-500 shadow-sm transition-colors duration-150 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100">diff --git a/packages/web/src/features/chat/model-picker-modal.tsx b/packages/web/src/features/chat/model-picker-modal.tsxindex 5c1dabe9..671adb0c 100644--- a/packages/web/src/features/chat/model-picker-modal.tsx+++ b/packages/web/src/features/chat/model-picker-modal.tsx@@ -6,7 +6,7 @@** - **Rows** read as the provider's logo, the model's name and its marks (pickerRowTags: the* models page's default / vision / fast / free / discount pills), then the no-key glyph and- * the ✓. The upstream id is not printed; it is the row's tooltip, which also tells apart two+ * Select's check. The upstream id is not printed; it is the row's tooltip, which also tells apart two* groups' models of the same name.* - **Opens on the current model**: its group is active and its row highlighted and scrolled* into view. With nothing chosen, the first group with a configured key is active.@@ -39,6 +39,7 @@ import { CloseButton } from "../../components/ui/icons";import { Modal } from "../../components/ui/modal";import { noAutofill, panelSearchClass } from "../../components/ui/input";import { ProviderLogo } from "../../components/ui/provider-logo";+import { ChoiceCheck } from "../../components/ui/field";import { hasConfiguredKey, sameModelRef } from "../models/model-grouping";import { loadModelGroupOrder } from "../models/model-group-order";import { TAG_SHAPE } from "../models/model-tags";@@ -98,7 +99,7 @@ export function ModelPickerModal({ open, onClose, title, ...body }: ModelPickerMheaderlessbare// Sized to its rows — a logo, a name and a few pills on one line — so the list does not- // open an empty band between a name and its ✓. Full screen on a phone: the rail needs a+ // open an empty band between a name and its check. Full screen on a phone: the rail needs a// strip of its own above the list, and a bottom sheet leaves too little height for both.widthClass="sm:max-w-xl max-sm:rounded-none max-sm:border-0">@@ -260,7 +261,7 @@ function ModelPickerBody({<buttontype="button"tabIndex={-1}- title={label === m.modelId ? label : `${label} · ${m.modelId}`}+ data-tooltip={label === m.modelId ? label : `${label} · ${m.modelId}`}// Mouse movement, not mouseenter: rows scrolling under a resting pointer while the// keyboard drives the list must not steal the highlight.onMouseMove={isHighlighted ? undefined : onHover}@@ -279,7 +280,7 @@ function ModelPickerBody({{pickerRowTags(m, defaultModel, now).map((tag) => (<spankey={tag.key}- title={tag.title}+ data-tooltip={tag.title}className={`${TAG_SHAPE} shrink-0 ${tag.className}`}>{tag.label}@@ -289,14 +290,14 @@ function ModelPickerBody({{!hasConfiguredKey(m) && (<spanrole="img"- title={S.models.noKey}+ data-tooltip={S.models.noKey}aria-label={S.models.noKey}className="shrink-0 text-gray-400 dark:text-gray-500"><GlyphIcon d={NO_KEY_ICON} size={ICON_SIZE.inlineGlyph} /></span>)}- <span className="w-3 shrink-0 text-center text-xs">{current ? "✓" : ""}</span>+ <ChoiceCheck on={current} /></button></li>);@@ -356,7 +357,7 @@ function ModelPickerBody({type="button"tabIndex={-1}aria-current={active ? "true" : undefined}- title={i < 9 ? `${g.provider.label} · ${mod}${i + 1}` : g.provider.label}+ data-tooltip={i < 9 ? `${g.provider.label} · ${mod}${i + 1}` : g.provider.label}onClick={() => activateGroup(i, "rail")}className={`flex shrink-0 items-center gap-2 whitespace-nowrap rounded-full border px-2.5 py-1 text-sm transition-colors duration-150 sm:w-full sm:rounded-md sm:border-transparent sm:py-1.5 sm:dark:border-transparent ${activediff --git a/packages/web/src/features/chat/model-select.tsx b/packages/web/src/features/chat/model-select.tsxindex c0b523b3..afb30260 100644--- a/packages/web/src/features/chat/model-select.tsx+++ b/packages/web/src/features/chat/model-select.tsx@@ -18,6 +18,7 @@ import { ProviderLogo } from "../../components/ui/provider-logo";import { sameModelRef } from "../models/model-grouping";import { modelLabel } from "./model-picker-logic";import { ModelPickerModal } from "./model-picker-modal";+import { ChoiceCheck, menuRowClass, menuRowTone } from "../../components/ui/field";// Re-exported for the pages that label models (the models page, the Project and company// dialogs); it lives beside the picker's pure logic so the dialog can share it without an@@ -114,14 +115,12 @@ export function PickerList<T>({type="button"ref={key === activeKey ? (el) => el?.scrollIntoView({ block: "nearest" }) : undefined}onClick={() => onPick(item)}- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${- current- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-600 dark:text-gray-400"- }${key === activeKey ? " bg-gray-100 dark:bg-gray-800" : ""}`}+ className={`flex items-center gap-2 ${menuRowClass} text-xs ${menuRowTone(current)}${+ key === activeKey ? " bg-gray-100 dark:bg-gray-800" : ""+ }`}>{renderRow(item)}- <span className="w-3 shrink-0 text-center text-xs">{current ? "✓" : ""}</span>+ <ChoiceCheck on={current} /></button>);})}@@ -225,7 +224,7 @@ export function ModelSelect({<><buttontype="button"- title={`${S.chat.chooseModel}:${label}`}+ data-tooltip={`${S.chat.chooseModel}:${label}`}aria-label={S.chat.chooseModel}aria-haspopup="dialog"aria-expanded={open}diff --git a/packages/web/src/features/chat/panels-toolbar.tsx b/packages/web/src/features/chat/panels-toolbar.tsxindex a4df565c..a5e35421 100644--- a/packages/web/src/features/chat/panels-toolbar.tsx+++ b/packages/web/src/features/chat/panels-toolbar.tsx@@ -60,7 +60,7 @@ export function PanelsToolbar({ agentsPending }: PanelsToolbarProps) {// Hiding a dock keeps every body mounted (dock-panel.tsx renders it at zero// size), so a tab holding unsaved work has nothing to lose and nothing to ask.onClick={() => toggleDock(position)}- title={title}+ data-tooltip={title}aria-label={label}data-testid={`dock-toggle-${position}`}className={triggerClass(isDockVisible(position))}diff --git a/packages/web/src/features/chat/permission-select.tsx b/packages/web/src/features/chat/permission-select.tsxindex b9b922ac..5178db67 100644--- a/packages/web/src/features/chat/permission-select.tsx+++ b/packages/web/src/features/chat/permission-select.tsx@@ -27,6 +27,7 @@ import {} from "../../lib/permission-level";import { useAuth } from "../../state/auth";import { SettingsDialog } from "../settings/settings-dialog";+import { ChoiceCheck, menuRowClass, menuRowTone } from "../../components/ui/field";const FS_MODES: SessionSandbox["mode"][] = ["read-only", "workspace-write", "danger-full-access"];const NETWORK_MODES: SessionSandbox["network"][] = ["open", "local", "none"];@@ -34,7 +35,7 @@ const NETWORK_MODES: SessionSandbox["network"][] = ["open", "local", "none"];/** A section's small heading inside the panel. */function Heading({ children }: { children: ReactNode }) {return (- <div className="px-3 pt-2 pb-1 text-[11px] font-medium text-gray-400 dark:text-gray-500">+ <div className="px-3 pt-2 pb-1 text-xs font-medium text-gray-400 dark:text-gray-500">{children}</div>);@@ -63,21 +64,15 @@ function Choice({aria-checked={selected}aria-disabled={off || undefined}disabled={off}- title={unavailable}+ data-tooltip={unavailable}onClick={onPick}- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 ${- off- ? "cursor-not-allowed text-gray-400 dark:text-gray-600"- : `hover:bg-gray-100 dark:hover:bg-gray-800 ${- selected- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-600 dark:text-gray-400"- }`+ className={`flex items-center gap-2 ${menuRowClass} text-xs ${+ off ? "cursor-not-allowed text-gray-400 dark:text-gray-600" : menuRowTone(selected)}`}><span className="min-w-0 flex-1 truncate whitespace-nowrap">{label}</span>- {off && <span className="shrink-0 text-[10px]">{S.chat.permission.unsupported}</span>}- <span className="w-3 shrink-0 text-center">{selected ? "✓" : ""}</span>+ {off && <span className="shrink-0 text-xs">{S.chat.permission.unsupported}</span>}+ <ChoiceCheck on={selected} /></button>);}@@ -152,7 +147,7 @@ export function PermissionSelect({<buttontype="button"aria-label={`${P.label}: ${levelName}`}- title={`${P.label}:${levelName}\n${summary}`}+ data-tooltip={`${P.label}:${levelName}\n${summary}`}data-level={level}disabled={disabled}onClick={() => setOpen((v) => !v)}@@ -227,7 +222,7 @@ export function PermissionSelect({setOpen(false);setSettingsOpen(true);}}- className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-gray-600 transition-colors duration-150 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"+ className={`flex items-center gap-2 ${menuRowClass} text-xs ${menuRowTone()}`}><span className="min-w-0 flex-1 truncate whitespace-nowrap">{P.more}</span></button>diff --git a/packages/web/src/features/chat/reference-chip.tsx b/packages/web/src/features/chat/reference-chip.tsxindex 624751a3..4920f4e1 100644--- a/packages/web/src/features/chat/reference-chip.tsx+++ b/packages/web/src/features/chat/reference-chip.tsx@@ -60,7 +60,7 @@ export function ReferenceChip({const title = referenceTitle(reference);return (<span- title={title}+ data-tooltip={title}className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"><GlyphIcon@@ -79,7 +79,7 @@ export function ReferenceChip({// far too long to announce as the name of a remove button.aria-label={`${S.files.removeReference} ${reference.kind === "excerpt" ? name : title}`}onClick={onRemove}- className="shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"+ className="shrink-0 rounded p-px text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200">×</button>diff --git a/packages/web/src/features/chat/shortcuts-folder.tsx b/packages/web/src/features/chat/shortcuts-folder.tsxindex 49f85fe1..e58aa3d5 100644--- a/packages/web/src/features/chat/shortcuts-folder.tsx+++ b/packages/web/src/features/chat/shortcuts-folder.tsx@@ -75,7 +75,7 @@ function RowAction({return (<buttontype="button"- title={label}+ data-tooltip={label}aria-label={label}onClick={onClick}className={`flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 dark:text-gray-500 ${@@ -172,7 +172,7 @@ export function ShortcutsFolder({<li key={shortcut.id} className="flex items-center gap-1"><buttontype="button"- title={`${shortcut.title}\n${S.chat.exampleFillHint}`}+ data-tooltip={`${shortcut.title}\n${S.chat.exampleFillHint}`}onClick={() => onFill(shortcut.prompt)}className={`flex min-w-0 flex-1 items-center gap-2 ${exampleRowClass}`}>@@ -197,7 +197,7 @@ export function ShortcutsFolder({<li><buttontype="button"- title={S.chat.shortcuts.newFromComposer}+ data-tooltip={S.chat.shortcuts.newFromComposer}onClick={startCreate}className={`flex w-full items-center gap-2 ${exampleRowClass}`}>diff --git a/packages/web/src/features/chat/step-banner.tsx b/packages/web/src/features/chat/step-banner.tsxindex 7c1f0399..5d95b5ae 100644--- a/packages/web/src/features/chat/step-banner.tsx+++ b/packages/web/src/features/chat/step-banner.tsx@@ -70,7 +70,11 @@ export function StepBanner({right edge. min-w-0 (not flex-1) lets a long detail truncate while a short onekeeps the duration snug against it. */}{detail !== undefined && (- <span title={detail} className="min-w-0 truncate font-mono text-xs text-gray-400">+ <span+ data-tooltip={detail}+ data-tooltip-content="code"+ className="min-w-0 truncate font-mono text-xs text-gray-400"+ >{detail}</span>)}diff --git a/packages/web/src/features/chat/subagent-chip.tsx b/packages/web/src/features/chat/subagent-chip.tsxindex 06f4fa9c..73c65bc4 100644--- a/packages/web/src/features/chat/subagent-chip.tsx+++ b/packages/web/src/features/chat/subagent-chip.tsx@@ -47,7 +47,7 @@ export function SubagentChip({<buttontype="button"aria-label={name}- title={name}+ data-tooltip={name}onClick={() => ctx.onOpenSubagent?.(sessionId, ctx.origin)}className="flex w-full items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-900/60 dark:hover:bg-gray-800/60">diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsxindex beb34e5d..c10affeb 100644--- a/packages/web/src/features/chat/subagents-view.tsx+++ b/packages/web/src/features/chat/subagents-view.tsx@@ -255,7 +255,7 @@ export function SubagentsView({{activeLabel}</span><span- title={active.sessionId}+ data-tooltip={active.sessionId}className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500">{shortSessionId(active.sessionId)}@@ -267,7 +267,7 @@ export function SubagentsView({{/* Jump out of the panel: the child conversation as a full Session. */}<buttontype="button"- title={S.subagentPanel.openAsSession}+ data-tooltip={S.subagentPanel.openAsSession}aria-label={S.subagentPanel.openAsSession}data-testid="subagent-open-session"onClick={openAsSession}diff --git a/packages/web/src/features/chat/task-stats-line.tsx b/packages/web/src/features/chat/task-stats-line.tsxindex 182a2e84..7d480047 100644--- a/packages/web/src/features/chat/task-stats-line.tsx+++ b/packages/web/src/features/chat/task-stats-line.tsx@@ -71,7 +71,7 @@ function StatChip({display?: string;}) {return (- <span title={label} aria-label={label} className={`${display} items-center gap-1`}>+ <span data-tooltip={label} aria-label={label} className={`${display} items-center gap-1`}><GlyphIcon d={icon} />{compactValue !== undefined && compactValue !== value ? (<>@@ -199,7 +199,7 @@ export function TaskStatsLine({<buttontype="button"disabled={forking}- title={S.chat.forkSession}+ data-tooltip={S.chat.forkSession}aria-label={S.chat.forkSession}onClick={() => setConfirmingFork(true)}className="flex h-5 w-5 shrink-0 items-center justify-center rounded transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 disabled:cursor-wait disabled:opacity-50 dark:hover:bg-gray-800 dark:hover:text-gray-300"diff --git a/packages/web/src/features/chat/thinking-block.tsx b/packages/web/src/features/chat/thinking-block.tsxindex 91f06bb2..29d66e84 100644--- a/packages/web/src/features/chat/thinking-block.tsx+++ b/packages/web/src/features/chat/thinking-block.tsx@@ -10,7 +10,7 @@ import { humanizeDuration } from "../../lib/format";import type { ThinkingItem } from "../../lib/omni/stream-model";import { StatusIcon } from "../../components/ui/status-icon";import type { RunState } from "../../components/ui/status-icon";-import { DISCLOSURE_BODY_MD_CLASS, DisclosureRow } from "./disclosure-row";+import { DISCLOSURE_BODY_MD_CLASS, DisclosureRow, activityState } from "./disclosure-row";import { LiveDuration } from "./live-duration";import { Md } from "./md";@@ -26,11 +26,15 @@ export function ThinkingBlock({ item }: { item: ThinkingItem }) {return (<DisclosureRowsticky+ activity={{ kind: "thinking", state: activityState(state) }}icon={<StatusIcon state={state} label={stateLabel} />}label={S.chat.thinking}trailing={<>- <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">+ <span+ data-slot="detail"+ className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400"+ >{item.streaming ? (<LiveDuration sinceMs={item.startedAtMs} />) : item.durationMs !== undefined ? (diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsxindex 60611138..57d75646 100644--- a/packages/web/src/features/chat/tool-call-card.tsx+++ b/packages/web/src/features/chat/tool-call-card.tsx@@ -24,9 +24,11 @@ import { approvalKey } from "../../lib/omni/stream-model";import type { ToolCallItem } from "../../lib/omni/stream-model";import { Chevron } from "../../components/ui/chevron";import {+ ActivityProgress,DISCLOSURE_OUTPUT_PRE_CLASS,DISCLOSURE_ROW_CLASS,DISCLOSURE_ROW_STICKY_CLASS,+ activityState,} from "./disclosure-row";import { ZoomableImage } from "../../components/ui/image-zoom";import { toneInk } from "../../lib/tone";@@ -414,8 +416,15 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRenA pending call gets no "awaiting approval" text either: the approval block below isalways on screen while one is pending — it names the tool, shows the arguments andcarries the Allow/Deny buttons — so the row would only repeat it. The amber hourglass- StatusIcon (labeled) marks the wait, at every breakpoint. */}- <div className={`${DISCLOSURE_ROW_STICKY_CLASS} ${DISCLOSURE_ROW_CLASS}`}>+ StatusIcon (labeled) marks the wait, at every breakpoint.++ ui-activity: the row is a work step, so a theme may render it running or settled its+ own way; the tool name is its label and the subtitle and duration its details. */}+ <div+ className={`ui-activity ${DISCLOSURE_ROW_STICKY_CLASS} ${DISCLOSURE_ROW_CLASS}`}+ data-kind="tool"+ data-state={activityState(state)}+ ><buttontype="button"aria-expanded={open}@@ -424,18 +433,26 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen><StatusIcon state={state} label={stateLabel} /><span- title={nameTitle}+ data-tooltip={nameTitle}+ data-tooltip-content="code"+ data-slot="label"className="shrink-0 truncate font-mono text-xs font-semibold text-gray-700 dark:text-gray-300">{displayName || S.chat.unknownTool}</span>{/* Human-readable subtitle: the model-written call description (command/subagent tools) or the file path (file tools). */}{subtitle && (- <span className="min-w-0 shrink truncate text-xs text-gray-500 dark:text-gray-400">+ <span+ data-slot="detail"+ className="min-w-0 shrink truncate text-xs text-gray-500 dark:text-gray-400"+ >{subtitle}</span>)}- <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">+ <span+ data-slot="detail"+ className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400"+ >{item.durationMs !== undefined ? (humanizeDuration(item.durationMs)) : executing ? (@@ -455,6 +472,7 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen)) : null}</span>+ <ActivityProgress running={state === "running"} /><span className="min-w-0 flex-1" /></button>{/* At the row's right end, on a call made with run_in_background or moved there: a@@ -493,7 +511,7 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRenctx.onSendToBackground && (<buttontype="button"- title={S.chat.sendToBackgroundHint}+ data-tooltip={S.chat.sendToBackgroundHint}onClick={() => void ctx.onSendToBackground?.(item.toolCallId)}className="shrink-0 text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300">@@ -525,7 +543,7 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen≥sm the row stays one line (the desktop column is wide enough in practice). */}<div className="mb-2 flex items-start gap-2 sm:items-center"><span- title={nameTitle}+ data-tooltip={nameTitle}className="shrink-0 rounded-md bg-white px-1.5 py-0.5 font-mono text-xs font-semibold text-gray-700 dark:bg-gray-900 dark:text-gray-300">{displayName || S.chat.unknownTool}diff --git a/packages/web/src/features/chat/work-group.tsx b/packages/web/src/features/chat/work-group.tsxindex 49fa39f8..be611360 100644--- a/packages/web/src/features/chat/work-group.tsx+++ b/packages/web/src/features/chat/work-group.tsx@@ -23,6 +23,7 @@ import { S } from "../../lib/strings";import { humanizeDuration } from "../../lib/format";import { Chevron } from "../../components/ui/chevron";import {+ ActivityProgress,DISCLOSURE_CARD_CLASS,DISCLOSURE_HEADER_ROW_CLASS,DISCLOSURE_HEADER_STICKY_CLASS,@@ -95,6 +96,9 @@ export function WorkGroup({// A pending approval must stay actionable: expand the group body regardless of collapsed state (the approval row lives inside it).const shown = open || pending;const { steps, durationMs, startMs } = summarizeWork(items);+ // The header is a work step of its own for the activity hook: a group of thinking only is+ // thinking, anything with a tool call in it is tool work.+ const activityKind = items.some((it) => it.kind === "tool_call") ? "tool" : "thinking";return (// overflow-clip (not overflow-hidden): the header below is position:sticky, and an@@ -103,7 +107,9 @@ export function WorkGroup({// the exact same clipping (rounded corners included) without creating a scroll// container, and a sticky element never leaves its containing block, so the stuck// header itself is never clipped.- <div ref={rootRef} className={DISCLOSURE_CARD_CLASS}>+ // ui-frame: the group is a framed box with a head (the header) and a body (the tree), so a+ // theme that draws its transcript without boxes can take this one away.+ <div ref={rootRef} className={`ui-frame ${DISCLOSURE_CARD_CLASS}`}>{/* Group header: a distinct title bar (solid background), on a separate layer from thestep rows below it. Sticky against the message list's scrollport so a long expandedgroup can be collapsed from anywhere inside it — without this, finding the start of@@ -136,11 +142,15 @@ export function WorkGroup({requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));}}}- className={`${DISCLOSURE_HEADER_STICKY_CLASS} ${DISCLOSURE_HEADER_ROW_CLASS}`}+ className={`ui-activity ${DISCLOSURE_HEADER_STICKY_CLASS} ${DISCLOSURE_HEADER_ROW_CLASS}`}+ data-slot="head"+ data-kind={activityKind}+ data-state={active ? "running" : "done"}><StatusIcon state={active ? "running" : "done"} />{/* The title doubles as status: "Running" while in progress, "Done" when finished. */}<span+ data-slot="label"className={`${DISCLOSURE_HEADER_TITLE_CLASS} ${active ? toneInk.busy : "text-gray-500 dark:text-gray-400"}`}>{active ? S.chat.workRunning : S.chat.workDone}@@ -149,7 +159,10 @@ export function WorkGroup({dropped entirely (title on the header carries nothing extra — the header must staya single uncut line on phones). */}{steps > 0 && (- <span className="hidden shrink-0 font-mono text-xs text-gray-400 sm:inline">+ <span+ data-slot="detail"+ className="hidden shrink-0 font-mono text-xs text-gray-400 sm:inline"+ >{S.chat.workGroupSteps(steps)}</span>)}@@ -165,12 +178,12 @@ export function WorkGroup({snap backwards the moment the group settles. */}{itemsRunning? startMs !== undefined && (- <span className="shrink-0 font-mono text-xs text-gray-400">+ <span data-slot="detail" className="shrink-0 font-mono text-xs text-gray-400"><LiveDuration sinceMs={startMs} /></span>): durationMs > 0 && (- <span className="shrink-0 font-mono text-xs text-gray-400">+ <span data-slot="detail" className="shrink-0 font-mono text-xs text-gray-400">{humanizeDuration(durationMs)}</span>)}@@ -187,19 +200,32 @@ export function WorkGroup({</span><spanrole="img"- title={S.chat.approvalWaiting}+ data-tooltip={S.chat.approvalWaiting}aria-label={S.chat.approvalWaiting}className={`h-1.5 w-1.5 shrink-0 rounded-full sm:hidden ${toneDot.attention}`}/></>)}+ <ActivityProgress running={itemsRunning} /><span className="min-w-0 flex-1" /><Chevron open={shown} className="text-gray-400" /></button>+ {/* ui-tree: the steps hang off the header one level down, so a theme may join them to+ it with connector rules instead of the box. Each step is wrapped rather than marked+ on its own root, because the thinking and tool rows also render outside a group. */}{shown && (- <div className="anim-fade divide-y divide-gray-100 border-t border-gray-200 dark:divide-gray-800/60 dark:border-gray-800">- {items.map((item) => (- <MessageItem key={item.id} item={item} ctx={ctx} />+ <div+ data-slot="body"+ className="ui-tree anim-fade divide-y divide-gray-100 border-t border-gray-200 dark:divide-gray-800/60 dark:border-gray-800"+ >+ {items.map((item, index) => (+ <div+ key={item.id}+ data-depth="1"+ {...(index === items.length - 1 ? { "data-last": "true" } : {})}+ >+ <MessageItem item={item} ctx={ctx} />+ </div>))}</div>)}diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex e317a64b..d3d07e6e 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -1775,7 +1775,7 @@ export function WorkspaceBrowser({<buttontype="button"aria-label={S.files.searchClear}- title={S.files.searchClear}+ data-tooltip={S.files.searchClear}onClick={() => setQuery("")}className="absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200">@@ -1909,7 +1909,7 @@ export function WorkspaceBrowser({// Before the first measurement there is no ceiling yet (clampTreeWidth applies none),// so the current width is the honest maximum for that frame.aria-valuemax={Math.max(maxTreeWidth(width), treeWidth)}- title={S.files.treeWidth}+ data-tooltip={S.files.treeWidth}tabIndex={0}{...treeResizeProps}onKeyDown={onDividerKey}@@ -1985,11 +1985,7 @@ export function WorkspaceBrowser({{/* Copies the text that was read, which is all of the file unless the preview was cut off. */}{sourceShown && preview.content !== undefined && (<>- <Tooltip- label={copied ? S.common.copied : S.chat.copyCode}- placement="bottom"- className="shrink-0"- >+ <Tooltip label={S.chat.copyCode} placement="bottom" className="shrink-0"><buttontype="button"aria-label={S.chat.copyCode}@@ -2331,7 +2327,7 @@ export function WorkspaceBrowser({{editor.changedOnDisk === true && (<spanclassName={`shrink-0 text-xs ${toneInk.attention}`}- title={S.files.changedOnDiskHint}+ data-tooltip={S.files.changedOnDiskHint}>{S.files.changedOnDisk}</span>@@ -2461,7 +2457,7 @@ export function WorkspaceBrowser({<buttontype="button"aria-pressed={treeVisible}- title={treeVisible ? S.files.hideTree : S.files.showTree}+ data-tooltip={treeVisible ? S.files.hideTree : S.files.showTree}aria-label={S.files.showTree}onClick={() => setTree(!treeVisible)}className={`flex h-6 w-6 shrink-0 items-center justify-center rounded transition-colors duration-150 ${@@ -2478,7 +2474,7 @@ export function WorkspaceBrowser({unsaved-changes guard. */}<divref={crumbsRef}- title={crumbPath}+ data-tooltip={crumbPath}className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden px-1 text-sm">{crumbFit.collapsed && (@@ -2584,7 +2580,12 @@ export function WorkspaceBrowser({</p><ul className="max-h-40 overflow-y-auto rounded-md border border-gray-200 px-3 py-1.5 dark:border-gray-800">{(pendingUpload?.clashes ?? []).map((name) => (- <li key={name} className="truncate py-0.5 font-mono text-xs" title={name}>+ <li+ key={name}+ className="truncate py-0.5 font-mono text-xs"+ data-tooltip={name}+ data-tooltip-content="code"+ >{name}</li>))}diff --git a/packages/web/src/features/chat/workspace-finder.tsx b/packages/web/src/features/chat/workspace-finder.tsxindex 150efd5a..8ad725a6 100644--- a/packages/web/src/features/chat/workspace-finder.tsx+++ b/packages/web/src/features/chat/workspace-finder.tsx@@ -34,7 +34,7 @@ import { isElectronRenderer } from "../../lib/desktop-renderer";import { formatDateTime } from "../../lib/format";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { STAT_ICONS } from "../../lib/stat-icons";-import { toneStrip } from "../../lib/tone";+import { NoticeStrip } from "../../components/ui/notice-strip";import { machineLabel, nameOnMachine, workspaceMachines } from "../../lib/workspace-machines";import type { WorkspaceMachine } from "../../lib/workspace-machines";import { useSessions } from "../../state/sessions";@@ -794,7 +794,7 @@ export function WorkspaceFinder({><buttontype="button"- title={fullTitle}+ data-tooltip={fullTitle}disabled={disabled}aria-current={active ? "location" : undefined}data-finder-focus@@ -820,7 +820,7 @@ export function WorkspaceFinder({<buttontype="button"aria-label={f.removeNamed(label)}- title={f.removeFromQuickAccess}+ data-tooltip={f.removeFromQuickAccess}onClick={onRemove}className="absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-gray-400 opacity-0 transition-opacity duration-150 hover:text-gray-800 focus-visible:opacity-100 group-hover:opacity-100 dark:text-gray-500 dark:hover:text-gray-200">@@ -862,7 +862,7 @@ export function WorkspaceFinder({<buttontype="button"aria-label={f.addCurrentToQuickAccess}- title={f.addCurrentToQuickAccess}+ data-tooltip={f.addCurrentToQuickAccess}onClick={() => editQuickAccess(currentFolder, machine, true)}className="rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-800 dark:text-gray-500 dark:hover:text-gray-200">@@ -1013,7 +1013,7 @@ export function WorkspaceFinder({<buttontype="button"aria-label={f.editPath}- title={`${f.editPath} (${editChord})`}+ data-tooltip={`${f.editPath} (${editChord})`}onClick={editAddress}className="flex h-full shrink-0 items-center pl-2.5 pr-1 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200">@@ -1040,7 +1040,10 @@ export function WorkspaceFinder({// path instead, like the rest of the bar.onClick={last ? editAddress : () => load(crumb.path)}{...(last- ? { "aria-current": "page" as const, title: `${f.editPath} (${editChord})` }+ ? {+ "aria-current": "page" as const,+ "data-tooltip": `${f.editPath} (${editChord})`,+ }: {})}className={`rounded px-1 py-0.5 transition-colors duration-150 ${last@@ -1060,7 +1063,7 @@ export function WorkspaceFinder({keyboard, and ⌘⇧G / Ctrl+Shift+G reaches it from anywhere. */}<divaria-hidden- title={`${f.editPath} (${editChord})`}+ data-tooltip={`${f.editPath} (${editChord})`}onClick={editAddress}className="h-full min-w-6 flex-1 cursor-text"/>@@ -1085,7 +1088,7 @@ export function WorkspaceFinder({type="button"className={navButtonClass}disabled={!canGoBack(history)}- title={`${f.back} (${shortcut("⌘[", "Ctrl+[")})`}+ data-tooltip={`${f.back} (${shortcut("⌘[", "Ctrl+[")})`}aria-label={f.back}onClick={() => step(-1)}>@@ -1095,7 +1098,7 @@ export function WorkspaceFinder({type="button"className={navButtonClass}disabled={!canGoForward(history)}- title={`${f.forward} (${shortcut("⌘]", "Ctrl+]")})`}+ data-tooltip={`${f.forward} (${shortcut("⌘]", "Ctrl+]")})`}aria-label={f.forward}onClick={() => step(1)}>@@ -1105,7 +1108,7 @@ export function WorkspaceFinder({type="button"className={navButtonClass}disabled={parentPath === null}- title={`${f.up} (${shortcut("⌘↑", "Alt+↑")})`}+ data-tooltip={`${f.up} (${shortcut("⌘↑", "Alt+↑")})`}aria-label={f.up}onClick={goParent}>@@ -1116,7 +1119,7 @@ export function WorkspaceFinder({type="button"className={`${navButtonClass} hidden sm:block`}disabled={currentFolder === null && view.error === null}- title={f.refresh}+ data-tooltip={f.refresh}aria-label={f.refresh}onClick={refresh}>@@ -1170,8 +1173,9 @@ export function WorkspaceFinder({const settingsPane = denied?.settings ?? null;body = (<div className="p-4">- <div- className={`rounded-md border px-3 py-2.5 text-sm ${toneStrip[denied !== null ? "attention" : "danger"]}`}+ <NoticeStrip+ tone={denied !== null ? "attention" : "danger"}+ className="rounded-md border px-3 py-2.5 text-sm"><p className="font-medium">{denied !== null ? f.deniedTitle : f.loadFailed}</p><p className="mt-1 text-xs leading-5">@@ -1204,7 +1208,7 @@ export function WorkspaceFinder({</Button>)}</div>- </div>+ </NoticeStrip></div>);} else if (view.listing === null) {@@ -1229,7 +1233,7 @@ export function WorkspaceFinder({aria-label={entry.name}aria-selected={isSel}aria-disabled={folder ? undefined : true}- title={folder ? entry.path : f.fileNotSelectable}+ data-tooltip={folder ? entry.path : f.fileNotSelectable}data-finder-path={entry.path}data-finder-kind={folder ? "folder" : "file"}onClick={() => {@@ -1243,7 +1247,7 @@ export function WorkspaceFinder({? "cursor-default text-gray-400 dark:text-gray-600": isSel? listFocused- ? "bg-[var(--accent-bg)] text-[var(--accent-fg)]"+ ? "bg-accent text-accent-fg": "bg-gray-200 text-gray-900 dark:bg-gray-700 dark:text-gray-100": "cursor-default text-gray-800 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-gray-800/60"}`}@@ -1267,7 +1271,7 @@ export function WorkspaceFinder({type="button"tabIndex={-1}aria-label={f.openFolder(entry.name)}- title={f.open}+ data-tooltip={f.open}onClick={(e) => {e.stopPropagation();openEntry(entry.path);diff --git a/packages/web/src/features/chat/workspace-select.tsx b/packages/web/src/features/chat/workspace-select.tsxindex 7b7c5cf5..fa32039d 100644--- a/packages/web/src/features/chat/workspace-select.tsx+++ b/packages/web/src/features/chat/workspace-select.tsx@@ -144,7 +144,7 @@ export function WorkspaceSelect({<><buttontype="button"- title={title}+ data-tooltip={title}aria-label={fieldName}aria-haspopup="dialog"aria-expanded={open}diff --git a/packages/web/src/features/company/beta-badge.tsx b/packages/web/src/features/company/beta-badge.tsxindex 13d59815..cb91ec8e 100644--- a/packages/web/src/features/company/beta-badge.tsx+++ b/packages/web/src/features/company/beta-badge.tsx@@ -60,7 +60,7 @@ export function markBetaNoticeShown(storage?: BetaNoticeStorage): void {export function BetaBadge() {return (<span- title={S.company.betaTitle}+ data-tooltip={S.company.betaTitle}className="whitespace-nowrap rounded-sm border border-gray-300 px-0.5 py-px text-[9px] font-medium leading-none text-gray-500 dark:border-gray-600 dark:text-gray-400">{S.company.beta}diff --git a/packages/web/src/features/company/calendar-page.tsx b/packages/web/src/features/company/calendar-page.tsxindex 3b95dee5..effd8990 100644--- a/packages/web/src/features/company/calendar-page.tsx+++ b/packages/web/src/features/company/calendar-page.tsx@@ -33,7 +33,7 @@ import { formatDateTime } from "../../lib/format";import { useDocumentTitle } from "../../lib/use-document-title";import { employeeColor } from "../../lib/category-colors";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";-import { toneInk, toneStrip } from "../../lib/tone";+import { toneInk } from "../../lib/tone";import type { Tone } from "../../lib/tone";import { useAuth } from "../../state/auth";import { useCompany } from "../../state/company";@@ -67,6 +67,7 @@ import {} from "./calendar-geom";import type { Cadence, CalendarView, EventInstance, GridDay } from "./calendar-geom";import { dismissHint, hintKey, isHintDismissed } from "./page-hints";+import { NoticeStrip } from "../../components/ui/notice-strip";const PREV_ICON = "M15 18 9 12l6-6";const NEXT_ICON = "m9 18 6-6-6-6";@@ -122,7 +123,7 @@ const PLUS_ICON = "M12 5v14M5 12h14";* hour row), and so is where the hint sits inside it.*/const CREATE_SLOT_CLASS =- "group/slot absolute rounded-sm transition-colors duration-150 hover:bg-[var(--accent-bg)]/[0.07] hover:ring-1 hover:ring-inset hover:ring-[var(--accent-bg)]/25 focus-visible:bg-[var(--accent-bg)]/[0.07] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--accent-bg)]/40 disabled:pointer-events-none";+ "group/slot absolute rounded-sm transition-colors duration-150 hover:bg-accent/[0.07] hover:ring-1 hover:ring-inset hover:ring-accent/25 focus-visible:bg-accent/[0.07] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/40 disabled:pointer-events-none";/*** What the slot under the pointer would do, spelled out inside it: a plus and 「新建日程」. It is@@ -410,7 +411,7 @@ export function CalendarPage() {<buttonkey={i.key}type="button"- title={title}+ data-tooltip={title}onClick={() => {opts.onOpen?.();openEdit(i.event);@@ -491,7 +492,7 @@ export function CalendarPage() {><buttontype="button"- title={createLabel}+ data-tooltip={createLabel}aria-label={createLabel}disabled={employees.length === 0}onClick={() => openCreate(createMs)}@@ -506,7 +507,7 @@ export function CalendarPage() {<spanclassName={`inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-[11px] tabular-nums ${isToday- ? "bg-[var(--accent-bg)] font-semibold text-[var(--accent-fg)]"+ ? "bg-accent font-semibold text-accent-fg": day.inMonth? "text-gray-600 dark:text-gray-300": "text-gray-400 dark:text-gray-600"@@ -557,7 +558,7 @@ export function CalendarPage() {<divkey={day.key}className={`relative border-l border-gray-100 dark:border-gray-800 ${- isToday ? "bg-[var(--accent-bg)]/[0.03]" : ""+ isToday ? "bg-accent/[0.03]" : ""}`}style={{ height: HOUR_PX * 24 }}>@@ -567,7 +568,7 @@ export function CalendarPage() {<buttonkey={h}type="button"- title={createLabel}+ data-tooltip={createLabel}aria-label={createLabel}disabled={employees.length === 0}className={`${CREATE_SLOT_CLASS} inset-x-0 flex items-center justify-center border-t border-gray-100 dark:border-gray-800`}@@ -586,8 +587,8 @@ export function CalendarPage() {className="pointer-events-none absolute inset-x-0 z-10 flex items-center"style={{ top: dayFraction(now) * HOUR_PX * 24 - 1 }}>- <span className="-ml-1 h-2 w-2 rounded-full bg-[var(--accent-bg)]" />- <span className="h-0.5 flex-1 bg-[var(--accent-bg)]" />+ <span className="-ml-1 h-2 w-2 rounded-full bg-accent" />+ <span className="h-0.5 flex-1 bg-accent" /></div>)}{slots.map(({ item, lane, lanes }) => (@@ -633,7 +634,7 @@ export function CalendarPage() {{S.company.calendar.weekdays[(d.getDay() + 6) % 7]}<spanclassName={`inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 tabular-nums ${- isToday ? "bg-[var(--accent-bg)] text-[var(--accent-fg)]" : ""+ isToday ? "bg-accent text-accent-fg" : ""}`}>{d.getDate()}@@ -762,7 +763,7 @@ export function CalendarPage() {<buttonkey={e.agentId}type="button"- title={+ data-tooltip={active ? S.company.calendar.allEmployees : S.company.calendar.legendFilter(e.name)}aria-pressed={active}@@ -785,7 +786,8 @@ export function CalendarPage() {</span><spanclassName={`truncate ${struck ? "text-gray-400 dark:text-gray-500" : "text-gray-500 dark:text-gray-400"}`}- title={cadences.join(" · ")}+ data-tooltip={cadences.join(" · ")}+ data-tooltip-content="text">{cadences.length === 0? S.company.calendar.legendEmpty@@ -798,19 +800,21 @@ export function CalendarPage() {)}{error !== null && (- <div- className={`mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}+ <NoticeStrip+ tone="danger"+ className="mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs"><span>{S.company.calendar.loadFailed(error)}</span><Button size="sm" onClick={() => void load()}>{S.common.retry}</Button>- </div>+ </NoticeStrip>)}{events !== null && events.length === 0 && invalidFiles.length === 0 && !hintDismissed && (- <div- className={`mb-3 flex items-center gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.muted}`}+ <NoticeStrip+ tone="muted"+ className="mb-3 flex items-center gap-2 rounded-md border px-3 py-2 text-xs"><span className="min-w-0 flex-1">{S.company.calendar.emptyHint}</span><Button@@ -826,13 +830,13 @@ export function CalendarPage() {><CloseIcon /></Button>- </div>+ </NoticeStrip>)}{events === null && error === null ? <CalendarSkeleton view={view} /> : grid}{invalidFiles.length > 0 && (- <div className={`mt-4 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" className="mt-4 rounded-md border px-3 py-2 text-xs"><p className="mb-1 font-medium">{S.company.calendar.invalidFiles}</p><ul className="space-y-0.5 font-mono">{invalidFiles.map((f) => (@@ -841,7 +845,7 @@ export function CalendarPage() {</li>))}</ul>- </div>+ </NoticeStrip>)}{/* Create / edit dialog: the scheduled-task form minus its target, the employee as a select. */}@@ -1080,7 +1084,7 @@ function DayOverflow({<buttonref={triggerRef}type="button"- title={label}+ data-tooltip={label}aria-label={label}aria-expanded={open}aria-controls={panelId}diff --git a/packages/web/src/features/company/channel-composer.tsx b/packages/web/src/features/company/channel-composer.tsxindex ba6ddbc5..d83d4157 100644--- a/packages/web/src/features/company/channel-composer.tsx+++ b/packages/web/src/features/company/channel-composer.tsx@@ -79,9 +79,9 @@ import type { DraftClip, DraftHistory, MentionDraft } from "./mention-draft";/*** The box grows with the draft up to this many pixels, then scrolls inside — the same cap the* development-mode composer sets in chat-input.tsx, and deliberately a pixel count rather than- * `max-h-40`: the root font is the reader's own (16 / 18 / 20px, theme.tsx FONT_PX), so a rem- * cap would let the box eat a different share of the stream at each scale. `max-h-40` is only- * the outer guard; this is the one that binds.+ * `max-h-40`: the root font is the reader's own (14 to 20px, `TEXT_SIZE_PX` in+ * @prismshadow/penguin-ui/boot), so a rem cap would let the box eat a different share of the+ * stream at each scale. `max-h-40` is only the outer guard; this is the one that binds.*/const MAX_BOX_PX = 160;diff --git a/packages/web/src/features/company/channel-header.tsx b/packages/web/src/features/company/channel-header.tsxindex d5c26886..fc9b8aba 100644--- a/packages/web/src/features/company/channel-header.tsx+++ b/packages/web/src/features/company/channel-header.tsx@@ -45,6 +45,7 @@ import { channelGlyph } from "./channel-sidebar";import { channelLabel, inviteCandidates, isAllHands } from "./channel-list";import type { InviteCandidate } from "./channel-list";import { parsePrincipal } from "./principals";+import { menuPanelClass, menuRowClass, menuRowTone } from "../../components/ui/field";/** Invite (lucide user-plus): the header's "add somebody to this channel" action. */const INVITE_ICON =@@ -108,7 +109,7 @@ function MemberPopover({<buttonref={triggerRef}type="button"- title={label}+ data-tooltip={label}aria-label={label}aria-haspopup="dialog"aria-expanded={open}@@ -142,7 +143,7 @@ function MemberPopover({left: position.left,width: PANEL_WIDTH,}}- className="z-[60] max-h-[60vh] overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900"+ className={`${menuPanelClass} z-[60] max-h-[60vh]`}>{members.length === 0 ? (<p className="px-2.5 py-1.5 text-xs text-gray-400 dark:text-gray-500">@@ -235,7 +236,7 @@ function InvitePicker({onQuery("");onPick(c);}}- className={`flex w-full items-center justify-between gap-3 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 disabled:opacity-60 dark:hover:bg-gray-800`}+ className={`flex items-center justify-between gap-3 ${menuRowClass} text-xs disabled:opacity-60 ${menuRowTone()}`}><span className={`flex min-w-0 items-center ${ICON_GAP.row}`}><MemberAvatar@@ -391,7 +392,7 @@ export function ChannelHeader({what test/disclosure-anchor.test.ts reads. The row clips rather than wraps: theserver caps a channel name at 100 characters and the tooltip carries it whole. */}<h1- title={label}+ data-tooltip={label}className={`flex min-w-0 items-center overflow-hidden whitespace-nowrap ${ICON_GAP.row} text-[15px] font-semibold`}><span className="shrink-0 text-gray-400 dark:text-gray-500">@@ -411,7 +412,8 @@ export function ChannelHeader({{/* The purpose reads as a subtitle on the same line, so the header stays one row. */}{purpose !== null && (<span- title={purpose}+ data-tooltip={purpose}+ data-tooltip-content="text"className="hidden min-w-0 flex-1 truncate text-xs text-gray-500 sm:block dark:text-gray-400">{purpose}@@ -454,7 +456,7 @@ export function ChannelHeader({button={<buttontype="button"- title={S.company.channels.channelMenu}+ data-tooltip={S.company.channels.channelMenu}aria-label={`${S.company.channels.channelMenu}: ${label}`}aria-haspopup="menu"aria-expanded={menuOpen}diff --git a/packages/web/src/features/company/channel-markdown.tsx b/packages/web/src/features/company/channel-markdown.tsxindex 263a82bf..e7dd43b1 100644--- a/packages/web/src/features/company/channel-markdown.tsx+++ b/packages/web/src/features/company/channel-markdown.tsx@@ -141,7 +141,7 @@ export function ChannelReaderProvider({export function MentionChip({ raw, label, me }: { raw: string; label: string; me: boolean }) {return (<span- title={raw}+ data-tooltip={raw}className={`rounded px-1 ${me? `font-semibold ${toneSurface.attention}`diff --git a/packages/web/src/features/company/channel-sidebar.tsx b/packages/web/src/features/company/channel-sidebar.tsxindex 62ff39f4..f426aa6b 100644--- a/packages/web/src/features/company/channel-sidebar.tsx+++ b/packages/web/src/features/company/channel-sidebar.tsx@@ -76,7 +76,7 @@ function NewChannelButton({<><buttontype="button"- title={label}+ data-tooltip={label}aria-label={label}onClick={() => setOpen(true)}className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"@@ -124,7 +124,7 @@ function ChannelRow({<NavLinkto={orgChannelPath(projectId, orgId, channel.channelId)}onClick={() => onNavigate?.()}- title={channel.purpose !== "" ? `${label} · ${channel.purpose}` : label}+ data-tooltip={channel.purpose !== "" ? `${label} · ${channel.purpose}` : label}aria-label={note !== null ? `${label} · ${note}` : label}className={({ isActive }) =>`flex min-w-0 flex-1 items-center ${ICON_GAP.row} rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${@@ -319,7 +319,8 @@ export function ChannelRailRows({ projectId, orgId }: { projectId: string; orgId<NavLinkkey={channel.channelId}to={orgChannelPath(projectId, orgId, channel.channelId)}- title={name}+ data-tooltip={name}+ data-tooltip-placement="right"aria-label={name}className={({ isActive }) =>`relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 ${diff --git a/packages/web/src/features/company/channel-view.tsx b/packages/web/src/features/company/channel-view.tsxindex 64257c78..fda1ae02 100644--- a/packages/web/src/features/company/channel-view.tsx+++ b/packages/web/src/features/company/channel-view.tsx@@ -48,7 +48,7 @@ import { apiErrorText } from "../../lib/api-error";import { formatDateTime } from "../../lib/format";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { useDocumentTitle } from "../../lib/use-document-title";-import { toneDot, toneInk, toneStrip } from "../../lib/tone";+import { toneDot, toneInk } from "../../lib/tone";import { useAuth } from "../../state/auth";import { useCompany, useCompanyEvents } from "../../state/company";import { AgentAvatar } from "../../components/ui/agent-avatar";@@ -91,6 +91,7 @@ import {} from "./channel-stream";import type { BubbleShape, ChannelDay, StreamItem } from "./channel-stream";import { parsePrincipal } from "./principals";+import { NoticeStrip } from "../../components/ui/notice-strip";/** What the first response fixes for this channel: today, the day list, and the read cursor the divider is drawn at. */interface StreamMeta {@@ -110,7 +111,7 @@ const RUN_AVATAR_PX = 28;* The two bubble surfaces. The reader's own takes the app's brand blue rather than a tone from* lib/tone.ts: which side of a conversation wrote a message is an identity, not a judgement,* and a status hue would announce a state the message does not have. It is also the only tint- * that stays clearly apart from the neutral bubble under every accent — `--accent-bg` is grey+ * that stays clearly apart from the neutral bubble under every accent — `--ui-accent` is grey* in the default neutral theme, where a wash of it is the neutral bubble again.*/const BUBBLE_SURFACE = {@@ -530,7 +531,7 @@ export function ChannelView() {return (<div key={m.id} id={m.id} className="my-2 flex justify-center"><p- title={formatDateTime(m.time)}+ data-tooltip={formatDateTime(m.time)}className="max-w-[85%] rounded-md border border-gray-200 bg-gray-50 px-3 py-1.5 text-center text-xs leading-relaxed text-gray-500 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-400"><span className="sr-only">{S.company.channels.systemMessage} </span>@@ -597,7 +598,7 @@ export function ChannelView() {"hop 3" alone tells a reader nothing about why a message arrived. */}{hopChipShown(item.hop) && (<span- title={S.company.channels.hopInfo}+ data-tooltip={S.company.channels.hopInfo}className="text-gray-500 dark:text-gray-400">{S.company.channels.hop(item.hop)}@@ -628,7 +629,7 @@ export function ChannelView() {{renderRefs(m)}</div><span- title={at}+ data-tooltip={at}className="shrink-0 text-[11px] tabular-nums text-gray-600 dark:text-gray-400"><span className="sr-only">{S.company.channels.sentAt(at)}</span>@@ -661,9 +662,9 @@ export function ChannelView() {}}/>{detailError !== null && detail === null && (- <p role="alert" className={`border-b px-4 py-1.5 text-xs ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" as="p" role="alert" className="border-b px-4 py-1.5 text-xs">{S.company.channels.channelLoadFailed} · {detailError}- </p>+ </NoticeStrip>)}<div className="flex min-h-0 flex-1 flex-col px-3 pb-3 md:px-4 md:pb-4"><div className="relative mx-auto flex min-h-0 w-full max-w-5xl flex-1 flex-col">@@ -721,7 +722,7 @@ export function ChannelView() {<buttontype="button"aria-label={S.chat.jumpToLatest}- title={S.chat.jumpToLatest}+ data-tooltip={S.chat.jumpToLatest}onClick={jumpToLatest}className={`anim-pop absolute bottom-3 left-1/2 z-10 inline-flex -translate-x-1/2 items-center ${ICON_GAP.tight} rounded-full border border-gray-300 bg-white py-1 pl-2.5 pr-2 text-xs text-gray-600 shadow-sm transition-colors duration-150 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}>@@ -734,15 +735,18 @@ export function ChannelView() {{canPost ? (<ChannelComposer candidates={candidates} names={names} onSend={send} />) : detail !== null && detail.archived ? (- <p- className={`mt-3 rounded-md border px-3 py-2 text-xs ${toneStrip.muted}`}+ <NoticeStrip+ tone="muted"+ as="p"+ className="mt-3 rounded-md border px-3 py-2 text-xs"role="status">{S.company.channels.archivedNotice}- </p>+ </NoticeStrip>) : detail !== null ? (- <div- className={`mt-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="mt-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 rounded-md border px-3 py-2 text-xs"><span>{S.company.channels.notMemberNotice}</span><Button@@ -753,7 +757,7 @@ export function ChannelView() {>{joining ? S.company.channels.joining : S.company.channels.join}</Button>- </div>+ </NoticeStrip>) : null}</div></div>@@ -788,7 +792,7 @@ function RefChip({return (<buttontype="button"- title={title}+ data-tooltip={title}onClick={onClick}className={`inline-flex items-center ${ICON_GAP.tight} rounded-full border border-gray-200 bg-white px-2 py-0.5 text-[11px] text-gray-600 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}>diff --git a/packages/web/src/features/company/chart-card.tsx b/packages/web/src/features/company/chart-card.tsxindex 90ff32df..2e63a2b7 100644--- a/packages/web/src/features/company/chart-card.tsx+++ b/packages/web/src/features/company/chart-card.tsx@@ -153,7 +153,7 @@ export function ChartCard({{/* The tooltip carries what the two truncating lines may have cut, and nothing else:the face has no click of its own, so it must not promise one either. */}<div- title={+ data-tooltip={flag !== undefined ? `${employee.name} · ${flag}` : `${employee.name} · ${employee.title}`}className={`absolute inset-0 flex flex-col rounded-lg border bg-white px-3 py-2.5 shadow-sm dark:bg-gray-900 ${@@ -180,7 +180,7 @@ export function ChartCard({<ChartStateDot state={state} /><spanclassName="flex min-w-0 flex-1 items-center gap-1 font-mono text-[10px] text-gray-400 dark:text-gray-500"- title={flag ?? employee.resolvedWorkspace ?? employee.workspace}+ data-tooltip={flag ?? employee.resolvedWorkspace ?? employee.workspace}>{flag !== undefined ? (<span className={toneInk.danger}>@@ -195,7 +195,7 @@ export function ChartCard({className={`shrink-0 tabular-nums ${tone === "attention" || tone === "danger" ? `font-medium ${toneInk[tone]}` : ""}`}- title={spendTitle}+ data-tooltip={spendTitle}>{spend}</span>@@ -229,7 +229,7 @@ export function ChartCard({button={<buttontype="button"- title={S.company.chart.nodeMenu}+ data-tooltip={S.company.chart.nodeMenu}aria-label={`${employee.name} · ${S.company.chart.nodeMenu}`}aria-haspopup="menu"aria-expanded={ctx.open}diff --git a/packages/web/src/features/company/finance-gauge.tsx b/packages/web/src/features/company/finance-gauge.tsxindex 4bf4f789..39736e43 100644--- a/packages/web/src/features/company/finance-gauge.tsx+++ b/packages/web/src/features/company/finance-gauge.tsx@@ -35,9 +35,9 @@ export function FinanceGauge({viewBox={`0 0 ${size} ${size}`}role="img"aria-label={label}+ data-tooltip={label}className={`block shrink-0 ${toneInk[tone]}`}>- <title>{label}</title><circlecx={center}cy={center}@@ -100,7 +100,7 @@ export function SpendMeter({aria-valuemin={0}aria-valuemax={100}aria-valuenow={Math.round(width)}- title={label}+ data-tooltip={label}className="relative block h-4 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800"><spandiff --git a/packages/web/src/features/company/finance-page.tsx b/packages/web/src/features/company/finance-page.tsxindex d4e36df4..0d2f01b7 100644--- a/packages/web/src/features/company/finance-page.tsx+++ b/packages/web/src/features/company/finance-page.tsx@@ -40,7 +40,7 @@ import { formatDateTime, formatMoney, formatPercent } from "../../lib/format";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { STAT_ICONS } from "../../lib/stat-icons";import { useDocumentTitle } from "../../lib/use-document-title";-import { toneDot, toneInk, toneStrip } from "../../lib/tone";+import { toneDot, toneInk } from "../../lib/tone";import type { Tone } from "../../lib/tone";import { useCompany } from "../../state/company";import { useTheme } from "../../state/theme";@@ -86,6 +86,7 @@ import {} from "./finance-tree";import type { SpendStateKey } from "./finance-tree";import { agentPrincipal } from "./principals";+import { NoticeStrip } from "../../components/ui/notice-strip";/** Pencil (lucide): the budget cell's edit affordance. */const PENCIL_ICON =@@ -236,7 +237,7 @@ function BudgetEditor({<MoneyPerMonthUnit currency={currency} /><buttontype="button"- title={S.company.finance.saveBudget}+ data-tooltip={S.company.finance.saveBudget}aria-label={S.company.finance.saveBudget}disabled={busy}onMouseDown={(e) => e.preventDefault()}@@ -247,7 +248,7 @@ function BudgetEditor({</button><buttontype="button"- title={S.company.finance.cancelEdit}+ data-tooltip={S.company.finance.cancelEdit}aria-label={S.company.finance.cancelEdit}onMouseDown={(e) => e.preventDefault()}onClick={onCancel}@@ -441,8 +442,9 @@ export function FinancePage() {return (<OrgPage title={S.nav.org.finance} info={S.company.finance.info} actions={periodSwitch}>{error !== null && (- <div- className={`mb-4 flex items-center justify-between gap-2 rounded-md border px-3 py-1.5 text-xs ${toneStrip.danger}`}+ <NoticeStrip+ tone="danger"+ className="mb-4 flex items-center justify-between gap-2 rounded-md border px-3 py-1.5 text-xs"><span>{S.company.finance.refreshFailed} · {error}@@ -450,7 +452,7 @@ export function FinancePage() {<Button size="sm" onClick={() => void load()}>{S.common.retry}</Button>- </div>+ </NoticeStrip>)}<div className={stale ? "opacity-60 transition-opacity" : "transition-opacity"}>{/* Top row: what the period cost against the budget, beside how it accumulated. */}@@ -548,7 +550,7 @@ export function FinancePage() {return (<trkey={employee.agentId}- title={spendRowTooltip(+ data-tooltip={spendRowTooltip(employee,{own: S.company.finance.own,@@ -630,7 +632,7 @@ export function FinancePage() {</span><buttontype="button"- title={S.company.finance.editBudget}+ data-tooltip={S.company.finance.editBudget}aria-label={S.company.finance.editBudgetOf(employee.name)}onClick={() => setEditingId(employee.agentId)}className={`group inline-flex items-center ${ICON_GAP.tight} rounded px-1 py-0.5 tabular-nums transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}@@ -695,7 +697,7 @@ export function FinancePage() {// tooltip: three columns the table cannot afford beside the spend tree.<trkey={ticket.ticketId}- title={ticketRowTooltip(+ data-tooltip={ticketRowTooltip(ticket,owner === undefined ? undefined : principalLabel(owner, names),{@@ -714,7 +716,7 @@ export function FinancePage() {<buttontype="button"aria-expanded={open}- title={+ data-tooltip={open? S.company.finance.collapseChildren: S.company.finance.expandChildrendiff --git a/packages/web/src/features/company/handbook-page.tsx b/packages/web/src/features/company/handbook-page.tsxindex 36109b3c..013972fc 100644--- a/packages/web/src/features/company/handbook-page.tsx+++ b/packages/web/src/features/company/handbook-page.tsx@@ -301,7 +301,7 @@ export function HandbookPage() {<><buttontype="button"- title={S.company.handbook.collapseAll}+ data-tooltip={S.company.handbook.collapseAll}aria-label={S.company.handbook.collapseAll}disabled={expanded.size === 0}onClick={() => {@@ -352,7 +352,7 @@ export function HandbookPage() {{selectedFile !== null && (<spanclassName="hidden shrink-0 text-[11px] text-gray-400 sm:inline dark:text-gray-500"- title={S.company.handbook.updatedAt(+ data-tooltip={S.company.handbook.updatedAt(formatDateTime(selectedFile.updatedAt),formatBytes(selectedFile.size),)}diff --git a/packages/web/src/features/company/org-chart-page.tsx b/packages/web/src/features/company/org-chart-page.tsxindex 42ebe0ee..c6d5a514 100644--- a/packages/web/src/features/company/org-chart-page.tsx+++ b/packages/web/src/features/company/org-chart-page.tsx@@ -33,7 +33,7 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";import { ICON_SIZE } from "../../lib/icon-scale";-import { toneInk, toneStrip } from "../../lib/tone";+import { toneInk } from "../../lib/tone";import { useCompany } from "../../state/company";import { useLiveSessionStatuses } from "../../state/sessions";import { useTheme } from "../../state/theme";@@ -68,6 +68,7 @@ import type { CanvasSize, CanvasView } from "./canvas-view";import { ChartCard, ChartLegend } from "./chart-card";import { DeskRenewDialog, EmployeeEditDialog, HireDialog } from "./employee-dialogs";import type { EmployeeEdit } from "./employee-dialogs";+import { NoticeStrip } from "../../components/ui/notice-strip";/** Node-menu glyphs (24x24 line paths): the open door of a desk session, a plus person for hiring, a coin for budget, an arrow for the line, a refresh for a fresh desk, a door out for leaving. */const MENU_ICONS = {@@ -421,7 +422,7 @@ export function OrgChartPage() {</Button><buttontype="button"- title={S.company.chart.zoomFit}+ data-tooltip={S.company.chart.zoomFit}aria-label={`${S.company.chart.zoomFit} · ${percent}%`}onClick={() => {setViewEpoch((n) => n + 1);@@ -453,19 +454,20 @@ export function OrgChartPage() {>{/* A refresh that failed while a chart is on screen: say so above it, keep the chart. */}{error !== null && (- <div- className={`mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-1.5 text-xs ${toneStrip.danger}`}+ <NoticeStrip+ tone="danger"+ className="mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-1.5 text-xs"><span>{S.company.chart.refreshFailed(error)}</span><Button size="sm" onClick={() => void load()}>{S.common.retry}</Button>- </div>+ </NoticeStrip>)}{layout.detached.length > 0 && (- <div className={`mb-3 rounded-md border px-3 py-1.5 text-xs ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" className="mb-3 rounded-md border px-3 py-1.5 text-xs">{S.company.chart.detachedNotice(layout.detached.length)}- </div>+ </NoticeStrip>)}{layout.nodes.length === 0 ? (<EmptyState title={S.company.chart.empty} />diff --git a/packages/web/src/features/company/org-dialogs.tsx b/packages/web/src/features/company/org-dialogs.tsxindex f34b6d2b..c32a7a39 100644--- a/packages/web/src/features/company/org-dialogs.tsx+++ b/packages/web/src/features/company/org-dialogs.tsx@@ -254,7 +254,8 @@ function MissionExamples({<buttonkey={example.id}type="button"- title={`${copy.mission}\n${S.company.missionExampleHint}`}+ data-tooltip={`${copy.mission}\n${S.company.missionExampleHint}`}+ data-tooltip-content="text"disabled={disabled}onClick={() => onPick(copy)}className="min-w-0 truncate rounded-md border border-gray-200 px-2 py-1 text-left text-[11px] text-gray-600 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 disabled:cursor-not-allowed disabled:opacity-60 dark:border-gray-700 dark:text-gray-400 dark:hover:border-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-100"diff --git a/packages/web/src/features/company/org-layout.tsx b/packages/web/src/features/company/org-layout.tsxindex 2c94db90..6120edb8 100644--- a/packages/web/src/features/company/org-layout.tsx+++ b/packages/web/src/features/company/org-layout.tsx@@ -159,7 +159,7 @@ function OrgEmptyLanding() {<li key={example.id} className="min-w-0"><buttontype="button"- title={copy.mission}+ data-tooltip={copy.mission}onClick={() => openCreate(copy)}className="flex h-full w-full flex-col rounded-md border border-gray-200 p-3 text-left transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-800 dark:hover:border-gray-700 dark:hover:bg-gray-800/60">diff --git a/packages/web/src/features/company/org-session-groups.tsx b/packages/web/src/features/company/org-session-groups.tsxindex f81309c9..145cc627 100644--- a/packages/web/src/features/company/org-session-groups.tsx+++ b/packages/web/src/features/company/org-session-groups.tsx@@ -195,7 +195,7 @@ function DeskRow({type="button"aria-current={active ? "true" : undefined}disabled={opening}- title={row.jobTitle !== "" ? `${row.name} · ${row.jobTitle}` : row.name}+ data-tooltip={row.jobTitle !== "" ? `${row.name} · ${row.jobTitle}` : row.name}aria-label={label}// A press-and-hold that opened the menu must not also open the desk: touch screens// replay the held press as a click once the finger lifts.@@ -216,7 +216,7 @@ function DeskRow({channel, the channel named in the tooltip and the screen-reader text. */}{messagingChannel !== undefined && (<span- title={S.messaging.enabledIndicator[messagingChannel]}+ data-tooltip={S.messaging.enabledIndicator[messagingChannel]}className="shrink-0 text-gray-400 dark:text-gray-500"><Icon d={MESSAGING_RELAY_ICON} size={ICON_SIZE.rowMark} />@@ -327,7 +327,7 @@ function TempRow({<buttontype="button"aria-current={row.active ? "true" : undefined}- title={`${row.name} · ${row.title}`}+ data-tooltip={`${row.name} · ${row.title}`}aria-label={label}onClick={onOpen}className={rowButton(row.active)}@@ -345,7 +345,7 @@ function TempRow({across the two groups. */}<buttontype="button"- title={remove}+ data-tooltip={remove}aria-label={remove}onClick={onDismiss}className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"@@ -378,7 +378,7 @@ export function TempSessionRailRows({ projectId, orgId }: { projectId: string; o<buttonkey={row.sessionId}type="button"- title={name}+ data-tooltip={name}aria-label={name}onClick={() => openSession(row.sessionId, row.agentId)}className="relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"@@ -528,7 +528,7 @@ export function DeskRailRows({ projectId, orgId }: { projectId: string; orgId: s<buttonkey={d.agentId}type="button"- title={name}+ data-tooltip={name}aria-label={name}disabled={opening === d.agentId}onClick={() => void openDesk(d.agentId, d.sessionId)}diff --git a/packages/web/src/features/company/org-switcher.tsx b/packages/web/src/features/company/org-switcher.tsxindex b064150c..0c9d5077 100644--- a/packages/web/src/features/company/org-switcher.tsx+++ b/packages/web/src/features/company/org-switcher.tsx@@ -31,8 +31,11 @@ import {useOrganizationCreated,} from "./org-dialogs";import { OrgStatusDot, OrgStatusPill, orgStatusText } from "./shared";+import { menuRowClass, menuRowTone } from "../../components/ui/field";-const menuItemClass = `flex w-full items-center ${ICON_GAP.menu} px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`;+/** The switcher's rows: the shared menu row, a list of organizations and the actions under it. */+const menuItemBase = `flex items-center ${ICON_GAP.menu} ${menuRowClass} text-sm`;+const menuItemClass = `${menuItemBase} ${menuRowTone()}`;export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {const navigate = useNavigate();@@ -89,7 +92,7 @@ export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {<buttontype="button"onClick={() => setOpen(!open)}- title={triggerLabel}+ data-tooltip={triggerLabel}// The count beside the name renders aria-hidden — it is a bare `@3` — so the// accessible name has to carry the same fact in words.aria-label={triggerLabel}@@ -153,13 +156,13 @@ export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {<buttonkey={key}type="button"- title={S.company.inProject(projectName(o.projectId), o.name)}+ data-tooltip={S.company.inProject(projectName(o.projectId), o.name)}aria-current={active ? "true" : undefined}onClick={() => {setOpen(false);go(orgPagePath(o.projectId, o.orgId, "overview"));}}- className={`${menuItemClass} ${active ? "font-semibold" : ""}`}+ className={`${menuItemBase} ${menuRowTone(active)}`}><OrgStatusDot org={o} /><span className="min-w-0 flex-1 truncate">{o.name}</span>diff --git a/packages/web/src/features/company/overview-page.tsx b/packages/web/src/features/company/overview-page.tsxindex 86f84f91..7c7b7181 100644--- a/packages/web/src/features/company/overview-page.tsx+++ b/packages/web/src/features/company/overview-page.tsx@@ -112,7 +112,7 @@ const rowClass = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-lef/** A small tone-marked count: the dot, the label, the number. */function ToneCount({ tone, label, value }: { tone: Tone; label: string; value: number }) {return (- <span className={`inline-flex items-center ${ICON_GAP.tight}`} title={label}>+ <span className={`inline-flex items-center ${ICON_GAP.tight}`} data-tooltip={label}><span className={`block h-1.5 w-1.5 rounded-full ${toneDot[tone]}`} /><span>{label}</span><span className="font-semibold tabular-nums text-gray-700 dark:text-gray-200">{value}</span>@@ -240,7 +240,7 @@ function MissionFold({ mission }: { mission: string }) {<buttontype="button"onClick={() => setExpanded((v) => !v)}- title={toggle}+ data-tooltip={toggle}aria-expanded={expanded}aria-controls={bodyId}className={`inline-flex shrink-0 items-center ${ICON_GAP.tight} rounded text-xs text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200`}@@ -554,7 +554,7 @@ export function OverviewPage() {.map((seg) => (<spankey={seg.status}- title={`${S.company.tickets.columns[seg.status] ?? seg.status} ${seg.count}`}+ data-tooltip={`${S.company.tickets.columns[seg.status] ?? seg.status} ${seg.count}`}className={`block h-full ${BOARD_FILL[seg.status]}`}style={{ width: `${seg.share * 100}%` }}/>@@ -568,7 +568,7 @@ export function OverviewPage() {<buttonkey={seg.status}type="button"- title={S.company.overview.openColumn(+ data-tooltip={S.company.overview.openColumn(S.company.tickets.columns[seg.status] ?? seg.status,)}onClick={() => page("tickets", `?column=${seg.status}`)}@@ -588,7 +588,7 @@ export function OverviewPage() {beside the five column counts and has to weigh the same as they do. */}<buttontype="button"- title={S.company.overview.openColumn(S.company.overview.blocked)}+ data-tooltip={S.company.overview.openColumn(S.company.overview.blocked)}onClick={() => page("tickets", "?blocked=1")}className={`inline-flex items-center ${ICON_GAP.tight} rounded px-1 text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}>@@ -746,7 +746,7 @@ export function OverviewPage() {)}<spanclassName="w-20 shrink-0 text-right text-xs tabular-nums text-gray-400 dark:text-gray-500"- {...(row.time !== null ? { title: formatDateTime(row.time) } : {})}+ {...(row.time !== null ? { "data-tooltip": formatDateTime(row.time) } : {})}>{row.time === null ? "—" : formatRelativeShort(row.time, locale)}</span>diff --git a/packages/web/src/features/company/path-capsule.tsx b/packages/web/src/features/company/path-capsule.tsxindex 84f64427..599165a5 100644--- a/packages/web/src/features/company/path-capsule.tsx+++ b/packages/web/src/features/company/path-capsule.tsx@@ -39,7 +39,7 @@ export function PathCapsule({ path }: { path: string }) {<><buttontype="button"- title={copied ? S.common.copied : S.company.pathCapsule.hint(path)}+ data-tooltip={copied ? S.common.copied : S.company.pathCapsule.hint(path)}aria-label={S.company.pathCapsule.copy(path)}onClick={() => flash(path)}// Baseline-aligned on the label, so the capsule sits on the sentence's line; the glyphdiff --git a/packages/web/src/features/company/shared.tsx b/packages/web/src/features/company/shared.tsxindex c015a3f9..23343783 100644--- a/packages/web/src/features/company/shared.tsx+++ b/packages/web/src/features/company/shared.tsx@@ -17,7 +17,7 @@ import type {import { S } from "../../lib/strings";import { formatMoney, formatPercent } from "../../lib/format";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";-import { toneDot, toneInk, toneStrip } from "../../lib/tone";+import { toneDot, toneInk } from "../../lib/tone";import type { Tone } from "../../lib/tone";import type { Currency } from "../../state/theme";import { AgentAvatar } from "../../components/ui/agent-avatar";@@ -32,6 +32,7 @@ import { budgetTone } from "./finance-tree";import { parsePrincipal } from "./principals";import { ORG_STATUS_TONE, orgStatusKind } from "./shell-org-status";import type { OrgStatusKind } from "./shell-org-status";+import { NoticeStrip } from "../../components/ui/notice-strip";/** Circled exclamation (lucide circle-alert): the mark of an invalid chart entry or ticket file, and of the finance page's alert count. */export const INVALID_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 8v4m0 4h.01";@@ -65,7 +66,7 @@ export function JumpButton({<buttontype="button"onClick={onClick}- title={label}+ data-tooltip={label}aria-label={label}className={`inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200 ${className}`}>@@ -100,7 +101,7 @@ export function TitleButton({<buttontype="button"onClick={onClick}- {...(title !== undefined ? { title } : {})}+ {...(title !== undefined ? { "data-tooltip": title } : {})}className={`min-w-0 text-left hover:underline focus-visible:underline ${className}`}>{children}@@ -129,7 +130,10 @@ const ORG_STATUS_BADGE: Record<OrgStatusKind, BadgeTone> = {export function OrgStatusPill({ org }: { org: { status: OrgStatus; invalid?: string } }) {const kind = orgStatusKind(org);return (- <span {...(org.invalid !== undefined ? { title: org.invalid } : {})} className="inline-flex">+ <span+ {...(org.invalid !== undefined ? { "data-tooltip": org.invalid } : {})}+ className="inline-flex"+ ><Badge tone={ORG_STATUS_BADGE[kind]}>{orgStatusLabel(kind)}</Badge></span>);@@ -140,7 +144,7 @@ export function OrgStatusDot({ org }: { org: { status: OrgStatus; invalid?: striconst kind = orgStatusKind(org);const label = orgStatusLabel(kind);return (- <span title={label} className="inline-flex shrink-0 items-center">+ <span data-tooltip={label} className="inline-flex shrink-0 items-center"><span className={`block h-1.5 w-1.5 rounded-full ${toneDot[ORG_STATUS_TONE[kind]]}`} /><span className="sr-only">{label}</span></span>@@ -165,20 +169,21 @@ export function ErrorLine({className?: string;}) {return (- <div+ <NoticeStrip+ tone="danger"role="alert"- className={`flex flex-wrap items-center justify-between gap-x-3 gap-y-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger} ${className}`}+ className={`flex flex-wrap items-center justify-between gap-x-3 gap-y-2 rounded-md border px-3 py-2 text-xs ${className}`}>- <span className="min-w-0">+ <span data-slot="body" className="min-w-0"><span className="font-medium">{message}</span>{detail !== undefined && detail !== message && (<span className="ml-2 opacity-80">{detail}</span>)}</span>- <Button size="sm" onClick={onRetry}>+ <Button size="sm" data-slot="actions" onClick={onRetry}>{S.common.retry}</Button>- </div>+ </NoticeStrip>);}@@ -219,9 +224,9 @@ export function SpendRing({viewBox={`0 0 ${size} ${size}`}role="img"aria-label={label}+ data-tooltip={label}className={`block shrink-0 ${ink}`}>- <title>{label}</title><circlecx={center}cy={center}@@ -294,7 +299,7 @@ export function BudgetBar({aria-valuemin={0}aria-valuemax={100}aria-valuenow={Math.round(width)}- title={label}+ data-tooltip={label}className="h-1.5 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800"><div className={`h-full rounded-full ${toneDot[tone]}`} style={{ width: `${width}%` }} />@@ -418,7 +423,10 @@ export function PriorityBadge({ priority }: { priority: OrgTicketPriority }) {/** The blocked mark: an attention pill whose tooltip carries the reason and who it waits on. */export function BlockedBadge({ reason, by }: { reason: string; by?: string }) {return (- <span title={S.company.tickets.blockedTooltip(reason, by ?? "—")} className="inline-flex">+ <span+ data-tooltip={S.company.tickets.blockedTooltip(reason, by ?? "—")}+ className="inline-flex"+ ><Badge tone="amber">{S.company.tickets.blocked}</Badge></span>);diff --git a/packages/web/src/features/company/ticket-dialog.tsx b/packages/web/src/features/company/ticket-dialog.tsxindex 59c81a1c..89cd9b1d 100644--- a/packages/web/src/features/company/ticket-dialog.tsx+++ b/packages/web/src/features/company/ticket-dialog.tsx@@ -41,7 +41,7 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { formatDateTime, formatMoney } from "../../lib/format";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";-import { toneInk, toneStrip } from "../../lib/tone";+import { toneInk } from "../../lib/tone";import { useAuth } from "../../state/auth";import { useCompany } from "../../state/company";import { useProject } from "../../state/project";@@ -79,6 +79,7 @@ import {} from "./ticket-board";import { ticketHistoryRows, ticketSummaryCounts } from "./ticket-history";import { dayKey } from "./calendar-geom";+import { NoticeStrip } from "../../components/ui/notice-strip";import { orgKey } from "./company-nav";import { deskRows } from "./org-sessions";import { chatPath, openTempSession } from "./temp-session";@@ -451,14 +452,15 @@ function TicketDialog({<div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-4 py-4 sm:px-6">{error !== null && detail === null ? (- <div- className={`flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}+ <NoticeStrip+ tone="danger"+ className="flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs"><span>{error}</span><Button size="sm" onClick={() => void load()}>{S.common.retry}</Button>- </div>+ </NoticeStrip>) : detail === null || !contextReady ? (<div className="space-y-5"><div className="flex gap-2">@@ -502,13 +504,14 @@ function TicketDialog({</span></div>{detail.invalid !== undefined && (- <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" className="rounded-md border px-3 py-2 text-xs">{detail.invalid}- </div>+ </NoticeStrip>)}{blocked && (- <div- className={`flex flex-wrap items-center gap-x-3 gap-y-1 rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-md border px-3 py-2 text-xs"><span><span className="font-medium">{S.company.tickets.blockedReason}:</span>{" "}@@ -520,7 +523,7 @@ function TicketDialog({<PrincipalChip principal={detail.blockedBy} names={names} /></span>)}- </div>+ </NoticeStrip>)}{/* Summary: the header fields as a definition list, a form while editing. */}@@ -752,7 +755,7 @@ function TicketDialog({{"cost" in c && (<spanclassName="shrink-0 font-mono text-[11px] tabular-nums text-gray-400 dark:text-gray-500"- title={S.company.tickets.cost}+ data-tooltip={S.company.tickets.cost}>{formatMoney(c.cost, currency)}</span>@@ -789,7 +792,8 @@ function TicketDialog({// becomes a Temporary entry.<spanclassName="truncate text-gray-400 dark:text-gray-500"- title={s.sessionId}+ data-tooltip={s.sessionId}+ data-tooltip-content="text">{s.title ?? s.sessionId}</span>@@ -835,7 +839,7 @@ function TicketDialog({<spankey="at"className="shrink-0 font-mono tabular-nums text-gray-400 dark:text-gray-500"- title={h.at}+ data-tooltip={h.at}>{formatDateTime(h.at)}</span>,diff --git a/packages/web/src/features/company/tickets-page.tsx b/packages/web/src/features/company/tickets-page.tsxindex babe96d0..2af3c41c 100644--- a/packages/web/src/features/company/tickets-page.tsx+++ b/packages/web/src/features/company/tickets-page.tsx@@ -39,7 +39,7 @@ import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";-import { toneDot, toneInk, toneStrip } from "../../lib/tone";+import { toneDot, toneInk } from "../../lib/tone";import { ICON_SIZE } from "../../lib/icon-scale";import { useAuth } from "../../state/auth";import { useCompany } from "../../state/company";@@ -79,6 +79,7 @@ import { MoveTicketConfirm } from "./ticket-dialog";import { dismissHint, hintKey, isHintDismissed } from "./page-hints";import { agentPrincipal, splitPrincipalList } from "./principals";import { dayKey } from "./calendar-geom";+import { NoticeStrip } from "../../components/ui/notice-strip";import { TICKET_COLUMN_ATTR, useTicketBoardDrag } from "./ticket-drag";const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];@@ -93,7 +94,7 @@ const DUE_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0-14v5l3 2";*/const COLUMN_BAR: Record<OrgTicketStatus, string> = {proposed: "bg-gray-300 dark:bg-gray-600",- in_progress: "bg-[var(--accent-bg)]",+ in_progress: "bg-accent",review: toneDot.attention,done: toneDot.success,rejected: toneDot.danger,@@ -243,7 +244,7 @@ export function TicketsPage() {<PriorityBadge priority={t.priority} /></span>{t.invalid !== undefined && (- <span className={`mt-0.5 shrink-0 ${toneInk.danger}`} title={t.invalid}>+ <span className={`mt-0.5 shrink-0 ${toneInk.danger}`} data-tooltip={t.invalid}><GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} /><span className="sr-only">{S.company.tickets.invalid}</span></span>@@ -256,7 +257,9 @@ export function TicketsPage() {{t.due !== undefined && (<spanclassName={`inline-flex items-center gap-1 font-mono tabular-nums ${overdue ? toneInk.danger : ""}`}- title={overdue ? `${S.company.tickets.overdue} · ${t.due}` : S.company.tickets.due}+ data-tooltip={+ overdue ? `${S.company.tickets.overdue} · ${t.due}` : S.company.tickets.due+ }><GlyphIcon d={DUE_ICON} size={ICON_SIZE.inlineGlyph} />{t.due}@@ -276,7 +279,8 @@ export function TicketsPage() {{t.parent !== undefined && (<spanclassName="mt-2 block truncate text-[11px] text-gray-400 dark:text-gray-500"- title={t.parent}+ data-tooltip={t.parent}+ data-tooltip-content="text">{S.company.tickets.parentLine(titles.get(t.parent) ?? t.parent)}</span>@@ -284,7 +288,7 @@ export function TicketsPage() {<span className="mt-2 flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400"><spanclassName="flex min-w-0 text-gray-700 dark:text-gray-200"- title={`${S.company.tickets.owner} ${principalLabel(t.owner, names)}`}+ data-tooltip={`${S.company.tickets.owner} ${principalLabel(t.owner, names)}`}><PrincipalChip principal={t.owner} names={names} size={ICON_SIZE.rowLead} /></span>@@ -311,7 +315,7 @@ export function TicketsPage() {key={t.ticketId}type="button"data-ticket-card={t.ticketId}- title={`${t.title} · ${t.ticketId} · ${S.company.tickets.dragHint}`}+ data-tooltip={`${t.title} · ${t.ticketId} · ${S.company.tickets.dragHint}`}{...drag.cardProps(t)}className={`${cardFrame(t)} cursor-pointer select-none transition-[border-color,opacity] duration-150 [-webkit-touch-callout:none] hover:border-gray-300 dark:hover:border-gray-600 ${lifted?.ticket.ticketId === t.ticketId ? "opacity-40" : ""@@ -359,22 +363,24 @@ export function TicketsPage() {}>{error !== null && (- <div- className={`mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}+ <NoticeStrip+ tone="danger"+ className="mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs"><span>{S.company.tickets.loadFailed(error)}</span><Button size="sm" onClick={() => void load()}>{S.common.retry}</Button>- </div>+ </NoticeStrip>)}{board !== null &&allTickets(board).length === 0 &&board.invalidFiles.length === 0 &&!hintDismissed && (- <div- className={`mb-3 flex items-center gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.muted}`}+ <NoticeStrip+ tone="muted"+ className="mb-3 flex items-center gap-2 rounded-md border px-3 py-2 text-xs"><span className="min-w-0 flex-1">{S.company.tickets.emptyHint}</span><Button@@ -390,7 +396,7 @@ export function TicketsPage() {><CloseIcon /></Button>- </div>+ </NoticeStrip>)}<div ref={drag.boardRef} className="overflow-x-auto pb-2">@@ -405,7 +411,7 @@ export function TicketsPage() {{...{ [TICKET_COLUMN_ATTR]: col.status }}className={`${columnClass} ${dropOver === col.status- ? "border-[var(--accent-bg)] ring-1 ring-[var(--accent-bg)]"+ ? "border-accent ring-1 ring-accent": highlightColumn === col.status && isTicketStatus(highlightColumn)? "border-gray-400 dark:border-gray-600": ""@@ -426,7 +432,7 @@ export function TicketsPage() {<divclassName={`flex min-h-20 flex-1 items-center justify-center rounded-md border border-dashed px-2 text-center text-[11px] ${dropOver === col.status- ? "border-[var(--accent-bg)] text-gray-600 dark:text-gray-300"+ ? "border-accent text-gray-600 dark:text-gray-300": "border-gray-300 text-gray-400 dark:border-gray-700 dark:text-gray-500"}`}>@@ -444,11 +450,13 @@ export function TicketsPage() {</div>{(invalids.length > 0 || (board !== null && board.invalidFiles.length > 0)) && (- <div className={`mt-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" className="mt-2 rounded-md border px-3 py-2 text-xs">{invalids.length > 0 && (<><p className="mb-1 flex items-center gap-1.5 font-medium">- <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />+ <span data-slot="icon" className="shrink-0">+ <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />+ </span>{S.company.tickets.invalidTickets}</p><ul className="mb-2 space-y-0.5">@@ -470,7 +478,9 @@ export function TicketsPage() {{board !== null && board.invalidFiles.length > 0 && (<><p className="mb-1 flex items-center gap-1.5 font-medium">- <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />+ <span data-slot="icon" className="shrink-0">+ <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />+ </span>{S.company.tickets.invalidFiles}</p><ul className="space-y-0.5 font-mono">@@ -482,7 +492,7 @@ export function TicketsPage() {</ul></>)}- </div>+ </NoticeStrip>)}{/* The lifted card's ghost: the card's own face at its own width, following the@@ -496,9 +506,7 @@ export function TicketsPage() {style={{ width: lifted.width, transform: drag.ghostTransform() }}className="pointer-events-none fixed left-0 top-0 z-[60]">- <div- className={`${cardFrame(lifted.ticket)} rotate-1 shadow-lg ring-1 ring-[var(--accent-bg)]`}- >+ <div className={`${cardFrame(lifted.ticket)} rotate-1 shadow-lg ring-1 ring-accent`}>{cardBody(lifted.ticket)}</div></div>,diff --git a/packages/web/src/features/dock/dock-launcher.tsx b/packages/web/src/features/dock/dock-launcher.tsxindex ace88754..34ee52b2 100644--- a/packages/web/src/features/dock/dock-launcher.tsx+++ b/packages/web/src/features/dock/dock-launcher.tsx@@ -153,7 +153,7 @@ interface FanEntry {// Every entry's box sits on the ball's centre; --fan-x / --fan-y carry it out to its place// on the arc, as both the resting transform and the entrance animation's end state.const ENTRY_CLASS =- "absolute flex items-center justify-center rounded-full border border-gray-200/80 bg-white/90 text-gray-600 shadow-[0_2px_8px_rgba(0,0,0,0.10)] backdrop-blur-md transition-colors duration-150 hover:bg-white hover:text-gray-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent-bg)] dark:border-white/10 dark:bg-gray-900/90 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";+ "absolute flex items-center justify-center rounded-full border border-gray-200/80 bg-white/90 text-gray-600 shadow-[0_2px_8px_rgba(0,0,0,0.10)] backdrop-blur-md transition-colors duration-150 hover:bg-white hover:text-gray-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:border-white/10 dark:bg-gray-900/90 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";/*** The one always-visible name, under the ball: a small pill on the same glass, with no@@ -164,7 +164,7 @@ const CAPTION_CLASS ="pointer-events-none absolute whitespace-nowrap rounded-md border border-gray-200/80 bg-white/85 px-2 py-0.5 text-[13px] font-medium leading-5 shadow-[0_1px_4px_rgba(0,0,0,0.08)] backdrop-blur-md transition-colors duration-150 dark:border-white/10 dark:bg-gray-900/85";const BALL_CLASS =- "anim-pop relative flex touch-none select-none items-center justify-center rounded-full border border-gray-200/80 text-gray-500 shadow-[0_2px_10px_rgba(0,0,0,0.10)] backdrop-blur-md transition-[background-color,color,opacity,box-shadow] duration-150 hover:bg-white/95 hover:text-gray-800 hover:opacity-100 hover:shadow-[0_4px_16px_rgba(0,0,0,0.14)] focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent-bg)] dark:border-white/10 dark:text-gray-400 dark:hover:bg-gray-800/95 dark:hover:text-gray-100";+ "anim-pop relative flex touch-none select-none items-center justify-center rounded-full border border-gray-200/80 text-gray-500 shadow-[0_2px_10px_rgba(0,0,0,0.10)] backdrop-blur-md transition-[background-color,color,opacity,box-shadow] duration-150 hover:bg-white/95 hover:text-gray-800 hover:opacity-100 hover:shadow-[0_4px_16px_rgba(0,0,0,0.14)] focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:border-white/10 dark:text-gray-400 dark:hover:bg-gray-800/95 dark:hover:text-gray-100";function LauncherBall({agentsPending,diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsxindex c0fb12da..7b659d3e 100644--- a/packages/web/src/features/dock/dock-panel.tsx+++ b/packages/web/src/features/dock/dock-panel.tsx@@ -119,7 +119,7 @@ function DockButton(props: {return (<buttontype="button"- title={props.label}+ data-tooltip={props.label}aria-label={props.label}data-testid={props.testId}onClick={props.onClick}@@ -168,7 +168,7 @@ function DockTabButton(props: {><buttontype="button"- title={props.title}+ data-tooltip={props.title}onClick={props.onSelect}className="flex h-full min-w-0 flex-1 items-center gap-1.5 pl-2 pr-1 text-left text-xs">@@ -182,7 +182,7 @@ function DockTabButton(props: {</button><buttontype="button"- title={+ data-tooltip={props.closeShortcut !== undefined? `${props.closeLabel} (${props.closeShortcut})`: props.closeLabel@@ -900,7 +900,7 @@ export function DockPanel({role="separator"aria-orientation="horizontal"aria-label={S.dock.resize}- title={S.dock.resize}+ data-tooltip={S.dock.resize}{...resizerDragProps}onDoubleClick={onResizerDoubleClick}className={`absolute -top-[3px] left-0 right-0 z-20 h-1.5 cursor-ns-resize transition-colors duration-150 ${@@ -932,7 +932,7 @@ export function DockPanel({role="separator"aria-orientation="vertical"aria-label={S.dock.resize}- title={S.dock.resize}+ data-tooltip={S.dock.resize}{...resizerDragProps}onDoubleClick={onResizerDoubleClick}className={`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 ${diff --git a/packages/web/src/features/harness/harness-history-overlay.tsx b/packages/web/src/features/harness/harness-history-overlay.tsxindex 514f6013..0f6dec01 100644--- a/packages/web/src/features/harness/harness-history-overlay.tsx+++ b/packages/web/src/features/harness/harness-history-overlay.tsx@@ -27,8 +27,8 @@ import { Badge } from "../../components/ui/badge";import { Skeleton } from "../../components/ui/skeleton";import { formatDateTime } from "../../lib/format";import { S } from "../../lib/strings";-import { toneStrip } from "../../lib/tone";import { ModuleTreeView } from "./module-tree-view";+import { NoticeStrip } from "../../components/ui/notice-strip";/** The last path segment without its extension: `store/platform/1a2b….mjs` → `1a2b…`. */function shortSha(pointer: string | null): string {@@ -99,7 +99,7 @@ function IfaceRow({ i }: { i: IfaceChange }) {const t = S.harnessHistory;return (<li className="rounded-md border border-gray-200 px-3 py-2 dark:border-gray-800">- <div className="flex items-center gap-2 font-mono text-sm" title={i.key}>+ <div className="flex items-center gap-2 font-mono text-sm" data-tooltip={i.key}><Badge tone={changeTone[i.change]}>{t.change[i.change]}</Badge>{i.key.slice(i.key.indexOf("#") + 1)}<span className="truncate text-xs text-gray-400 dark:text-gray-500">@@ -230,7 +230,8 @@ export function HarnessHistoryOverlay({ open, onClose }: { open: boolean; onClosreturn createPortal(<div// z-50 like Modal's overlay: a portaled menu or tooltip (z-[60]) opened from inside still paints above it.- className="anim-fade fixed inset-0 z-50 bg-black/45"+ // ui-scrim: the overlay is the dimmed layer, with the panel inside it.+ className="ui-scrim anim-fade fixed inset-0 z-50 bg-black/45"onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}@@ -243,7 +244,7 @@ export function HarnessHistoryOverlay({ open, onClose }: { open: boolean; onClosaria-label={t.title}tabIndex={-1}onKeyDown={onPanelKeyDown}- className="anim-pop absolute inset-3 flex flex-col overflow-hidden rounded-xl border border-gray-200 bg-white shadow-2xl dark:border-gray-800 dark:bg-gray-900"+ className="anim-pop absolute inset-3 flex flex-col overflow-hidden rounded-xl border border-gray-200 bg-white shadow-xl dark:border-gray-800 dark:bg-gray-900"><header className="flex items-start justify-between gap-4 border-b border-gray-200 px-5 py-3 dark:border-gray-800"><div>@@ -262,9 +263,9 @@ export function HarnessHistoryOverlay({ open, onClose }: { open: boolean; onClos<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4"><div className="mx-auto max-w-6xl">{error !== null && (- <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" className="mt-4 rounded-md border px-3 py-2 text-sm">{error}- </div>+ </NoticeStrip>)}{history === null ? (@@ -402,7 +403,7 @@ export function HarnessHistoryOverlay({ open, onClose }: { open: boolean; onClos)) : (<>- <h3 className="mt-6 text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">+ <h3 className="mt-6 text-sm font-semibold text-gray-500 dark:text-gray-400">{previous? t.changesSince(previous.source?.revision ??@@ -418,11 +419,12 @@ export function HarnessHistoryOverlay({ open, onClose }: { open: boolean; onClos) : diff.state === "loading" || diff.state === "idle" ? (<Skeleton className="mt-2 h-9 w-full" />) : diff.state === "error" ? (- <div- className={`mt-2 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}+ <NoticeStrip+ tone="danger"+ className="mt-2 rounded-md border px-3 py-2 text-sm">{diff.message}- </div>+ </NoticeStrip>) : diff.diff.modules.length + diff.diff.ifaces.length === 0 &&diff.diff.types.added +diff.diff.types.removed +diff --git a/packages/web/src/features/harness/module-tree-view.tsx b/packages/web/src/features/harness/module-tree-view.tsxindex 1f52e65d..840ca3f9 100644--- a/packages/web/src/features/harness/module-tree-view.tsx+++ b/packages/web/src/features/harness/module-tree-view.tsx@@ -8,7 +8,7 @@ import * as api from "../../api/endpoints";import { Badge } from "../../components/ui/badge";import { Skeleton } from "../../components/ui/skeleton";import { S } from "../../lib/strings";-import { toneStrip } from "../../lib/tone";+import { NoticeStrip } from "../../components/ui/notice-strip";interface Manifest {name: string;@@ -140,9 +140,9 @@ function Detail({ name, table }: { name: string; table: Table }) {req.length === 0 ? (<span className="text-gray-400">—</span>) : (- <ul className="flex flex-col gap-0.5 font-mono">+ <ul className="flex flex-col gap-px font-mono">{req.map(([f, r]) => (- <li key={f} title={r.iface}>+ <li key={f} data-tooltip={r.iface}>{f}: {short(r.iface)}{r.from ? <span className="text-gray-400"> ← {r.from}</span> : null}</li>@@ -155,9 +155,9 @@ function Detail({ name, table }: { name: string; table: Table }) {prov.length === 0 ? (<span className="text-gray-400">—</span>) : (- <ul className="flex flex-col gap-0.5 font-mono">+ <ul className="flex flex-col gap-px font-mono">{prov.map(([a, k]) => (- <li key={a} title={k}>+ <li key={a} data-tooltip={k}>{a}{a !== short(k) ? <span className="text-gray-400">: {short(k)}</span> : null}{kind === "group" && !exportsSet.has(a) ? (@@ -171,7 +171,7 @@ function Detail({ name, table }: { name: string; table: Table }) {{contrib.length > 0? row(t.contributes,- <ul className="flex flex-col gap-0.5 font-mono">+ <ul className="flex flex-col gap-px font-mono">{contrib.map(([slot, items]) => (<li key={slot}>{slot} × {items.length}@@ -215,7 +215,9 @@ export function ModuleTreeView({ hash }: { hash: string }) {}, [table]);if (error !== null)return (- <div className={`mt-2 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}>{error}</div>+ <NoticeStrip tone="danger" className="mt-2 rounded-md border px-3 py-2 text-sm">+ {error}+ </NoticeStrip>);if (table === null) return <Skeleton className="mt-2 h-9 w-full" />;return (diff --git a/packages/web/src/features/machines/machine-picker.tsx b/packages/web/src/features/machines/machine-picker.tsxindex b74ee770..934c350a 100644--- a/packages/web/src/features/machines/machine-picker.tsx+++ b/packages/web/src/features/machines/machine-picker.tsx@@ -10,8 +10,8 @@import { useState } from "react";import { Button } from "../../components/ui/button";import { Dropdown } from "../../components/ui/dropdown";-import { menuRowClass } from "../../components/ui/field";-import { CheckIcon, ChevronDown } from "../../components/ui/icons";+import { ChoiceCheck, menuRowClass, menuRowTone } from "../../components/ui/field";+import { ChevronDown } from "../../components/ui/icons";export interface MachineChoice {value: string;@@ -63,10 +63,10 @@ export function MachinePicker({setOpen(false);if (!selected) onChange(choice.value);}}- className={`${menuRowClass} flex items-center gap-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-800 ${selected ? "font-medium" : ""}`}+ className={`${menuRowClass} flex items-center gap-2 text-sm ${menuRowTone(selected)}`}><span className="min-w-0 flex-1 truncate">{choice.label}</span>- {selected && <CheckIcon className="shrink-0" />}+ <ChoiceCheck on={selected} /></button></li>);diff --git a/packages/web/src/features/machines/machines-page.tsx b/packages/web/src/features/machines/machines-page.tsxindex 302f5347..86459bcb 100644--- a/packages/web/src/features/machines/machines-page.tsx+++ b/packages/web/src/features/machines/machines-page.tsx@@ -32,7 +32,7 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";import { formatDateTime, formatMessageTime } from "../../lib/format";-import { toneDot, toneInk, toneStrip } from "../../lib/tone";+import { toneDot, toneInk } from "../../lib/tone";import { ICON_SIZE } from "../../lib/icon-scale";import { Button } from "../../components/ui/button";import { Dropdown } from "../../components/ui/dropdown";@@ -57,6 +57,7 @@ import { MAX_VISIBLE_MACHINES, highlightSegments, matchMachines } from "./machinimport { probeDelayMs, probeFingerprint } from "./probe-schedule";import { SshHostDialog } from "./ssh-host-dialog";import type { HostFormMode } from "./ssh-host-dialog";+import { NoticeStrip } from "../../components/ui/notice-strip";/** How often the page re-reads the list while a job is queued or running. */const POLL_MS = 1500;@@ -77,7 +78,7 @@ const CHEVRON_PATH = "M6 9l6 6 6-6";const SELECT_ALL_PATH = "M4 5h16v14H4zM8 12l3 3 5-6";const SELECT_NONE_PATH = "M4 5h16v14H4z";-const MONO = "font-mono text-[13px] tabular-nums";+const MONO = "font-mono text-xs tabular-nums";/** The reason a card gives under its name, when it has one: the far side's own words. */function reasonText(reading: MachineReading): string | null {@@ -325,7 +326,7 @@ export function MachinesPage() {<div className="h-full overflow-y-auto p-4 md:p-6"><div className="mx-auto max-w-3xl"><div className="flex flex-wrap items-center justify-between gap-2">- <h1 className="text-xl font-semibold">{S.machines.pageTitle}</h1>+ <h1 className="ui-display text-xl font-semibold">{S.machines.pageTitle}</h1><div className="flex items-center gap-2">{behind.length > 0 && (<Button@@ -381,10 +382,8 @@ export function MachinesPage() {<buttontype="button"onClick={() => toggleAdding(machine.id)}- className={`flex w-full min-w-0 items-center gap-2.5 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${- on- ? "bg-gray-100 shadow-[inset_3px_0_0_var(--accent-bg)] dark:bg-gray-800/60"- : ""+ className={`flex w-full min-w-0 items-center gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${+ on ? "bg-gray-100 dark:bg-gray-800/60" : ""}`}><span@@ -431,7 +430,7 @@ export function MachinesPage() {label={showAll ? S.machines.fewer : S.machines.expand}title={showAll ? S.machines.fewer : S.machines.allHosts(hiddenCount)}d={CHEVRON_PATH}- glyphClass={`transition-transform ${showAll ? "rotate-180" : ""}`}+ glyphClass={showAll ? "rotate-180" : ""}ariaExpanded={showAll}onClick={() => setShowAll((open) => !open)}/>@@ -483,14 +482,14 @@ export function MachinesPage() {)}{error !== null && (- <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" className="mt-4 rounded-md border px-3 py-2 text-sm">{error}- </div>+ </NoticeStrip>)}{noImage && error === null && (- <div className={`mt-4 rounded-md border px-3 py-2 text-sm ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" className="mt-4 rounded-md border px-3 py-2 text-sm">{S.machines.noImage}- </div>+ </NoticeStrip>)}{/* The selection bar: a fixed slot between the title and the cards, so the cards@@ -619,7 +618,7 @@ function Verb({<buttontype="button"disabled={disabled}- title={title ?? label}+ data-tooltip={title ?? label}aria-label={label}aria-expanded={ariaExpanded}onClick={click}@@ -669,10 +668,7 @@ function ExpandButton({}}className="rounded-md p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200">- <ChevronDown- size={ICON_SIZE.chevron}- className={`transition-transform ${open ? "rotate-180" : ""}`}- />+ <ChevronDown size={ICON_SIZE.chevron} className={open ? "rotate-180" : ""} /></button>);}@@ -681,15 +677,17 @@ function ExpandButton({function Stepper({ step, caption }: { step: number; caption: string }) {return (<div className="mt-1.5 w-44 max-w-full">- <div className="flex gap-0.5" aria-hidden="true">+ <div className="flex gap-px" aria-hidden="true">{MACHINE_PHASES.map((phase, index) => (<spankey={phase}+ // The segment being worked on pulses as a live signal, so a theme can re-time it.+ data-live={index === step ? "dot" : undefined}className={`h-[3px] flex-1 rounded-sm ${index < step? toneDot.busy: index === step- ? `${toneDot.busy} animate-pulse`+ ? `${toneDot.busy} ui-live animate-pulse`: "bg-gray-200 dark:bg-gray-700"}`}/>@@ -723,7 +721,7 @@ function LocalCard({<div className="min-w-0 flex-1"><div className="flex items-center gap-2"><span className={`${MONO} truncate font-medium`}>{machine.alias}</span>- <span className="shrink-0 rounded border border-gray-200 px-1.5 py-px text-[11px] text-gray-500 dark:border-gray-700">+ <span className="shrink-0 rounded border border-gray-200 px-1.5 py-px text-xs text-gray-500 dark:border-gray-700">{S.machines.localTitle}</span></div>@@ -798,7 +796,8 @@ function MachineCard({) : (<divclassName={`mt-0.5 truncate text-xs ${lineInk}`}- title={reasonText(reading) ?? undefined}+ data-tooltip={reasonText(reading) ?? undefined}+ data-tooltip-content="text">{stateLine(reading, machine, locale)}</div>@@ -808,7 +807,8 @@ function MachineCard({<Verb label={S.machines.use} d={PLUG_PATH} disabled={busy} onClick={() => onUse(false)} />)}<span- className={`h-1.5 w-1.5 shrink-0 rounded-full ${toneDot[tone]} ${moving ? "animate-pulse" : ""}`}+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${toneDot[tone]} ${moving ? "ui-live animate-pulse" : ""}`}+ data-live={moving ? "dot" : undefined}aria-hidden="true"/><ExpandButton alias={machine.alias} open={open} controls={id} onClick={onToggleOpen} />@@ -901,7 +901,7 @@ function Output({ job }: { job: MachineJob | null }) {return (<div className="mt-3"><div className="mb-1 text-xs text-gray-500">{S.machines.output}</div>- <pre className="max-h-64 overflow-auto rounded-md bg-gray-50 p-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-gray-500 dark:bg-gray-900">+ <pre className="max-h-64 overflow-auto rounded-md bg-gray-50 p-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-gray-500 dark:bg-gray-900">{job.log.slice(0, -1).join("\n")}{job.log.length > 1 ? "\n" : ""}<span className="text-gray-900 dark:text-gray-100">{job.log.at(-1)}</span>diff --git a/packages/web/src/features/machines/ssh-host-dialog.tsx b/packages/web/src/features/machines/ssh-host-dialog.tsxindex 55f0a2da..0ffad178 100644--- a/packages/web/src/features/machines/ssh-host-dialog.tsx+++ b/packages/web/src/features/machines/ssh-host-dialog.tsx@@ -19,11 +19,11 @@ import type {import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";-import { toneStrip } from "../../lib/tone";import { Button } from "../../components/ui/button";import { Input } from "../../components/ui/input";import { Modal } from "../../components/ui/modal";import { toastSuccess } from "../../components/ui/toast";+import { NoticeStrip } from "../../components/ui/notice-strip";type Field = "alias" | "hostName" | "user" | "port" | "identityFile";type Form = Record<Field, string>;@@ -163,9 +163,9 @@ export function SshHostDialog({><div className="space-y-3">{locked && (- <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" className="rounded-md border px-3 py-2 text-xs">{m.foreign}- </div>+ </NoticeStrip>)}<Inputsize="sm"diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex 26b56e3f..7ce2b5b2 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -705,7 +705,7 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })<div className="flex flex-wrap items-center gap-2 text-xs"><labelclassName="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300"- title={S.messaging.bindByEnableHint}+ data-tooltip={S.messaging.bindByEnableHint}><Switchchecked={facts.enabled}@@ -721,7 +721,8 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })</div>{facts.status.state === "error" && facts.status.lastError !== undefined && (<p- title={facts.status.lastError}+ data-tooltip={facts.status.lastError}+ data-tooltip-content="text"className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400">{facts.status.lastError}@@ -734,7 +735,8 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })left with the symptom and no trace of the cause. */}{facts.status.state !== "error" && facts.status.lastConnectionError !== undefined && (<p- title={facts.status.lastConnectionError.detail}+ data-tooltip={facts.status.lastConnectionError.detail}+ data-tooltip-content="text"className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400">{S.messaging.lastConnectionError(@@ -771,7 +773,8 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })live fault, and a title= is hover-only and unreachable on touch. */}{facts.status.lastDeliveryError !== undefined && (<p- title={facts.status.lastDeliveryError.detail}+ data-tooltip={facts.status.lastDeliveryError.detail}+ data-tooltip-content="text"className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400">{facts.status.lastDeliveryError.stage === "inbound"diff --git a/packages/web/src/features/models/key-auth-dialog.tsx b/packages/web/src/features/models/key-auth-dialog.tsxindex d79c4329..95f4d7cd 100644--- a/packages/web/src/features/models/key-auth-dialog.tsx+++ b/packages/web/src/features/models/key-auth-dialog.tsx@@ -11,6 +11,7 @@ import { Modal } from "../../components/ui/modal";import { apiErrorText } from "../../lib/api-error";import { isElectronRenderer } from "../../lib/desktop-renderer";import { S } from "../../lib/strings";+import { Spinner } from "@prismshadow/penguin-ui";const POLL_MS = 3_000;@@ -286,7 +287,7 @@ export function KeyAuthDialog({</p>{(phase === "starting" || phase === "waiting" || phase === "applying") && (<p className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">- <span className="inline-block h-2.5 w-2.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent" />+ <Spinner size="xs" label={S.common.loading} />{phase === "starting"? S.models.platformKeyStarting: phase === "applying"diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex 1dfee787..c912176c 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -141,10 +141,11 @@ import { TodoNotice } from "../../components/ui/todo-notice";import { buildImportedRows } from "./group-import";import { tpsTone, ttftTone } from "./speed-test";import type { SpeedResult, SpeedTone } from "./speed-test";-import { toneInk, toneStrip } from "../../lib/tone";+import { toneInk } from "../../lib/tone";import { InfoPopover } from "../../components/ui/info-popover";import { KeyAuthDialog } from "./key-auth-dialog";import type { KeyAuthTexts } from "./key-auth-dialog";+import { NoticeStrip } from "../../components/ui/notice-strip";/*** The authorization flows a group's "authorize a key" dialog can run, keyed by the flow named@@ -1160,7 +1161,7 @@ export function ModelsPage() {<div className="mx-auto max-w-5xl"><div className="mb-4"><div className="flex flex-wrap items-center justify-between gap-2">- <h1 className="flex items-center gap-1.5 text-xl font-semibold">+ <h1 className="ui-display flex items-center gap-1.5 text-xl font-semibold">{S.models.title}{!isOwner && (<InfoPopover label={S.models.title}>{S.models.readOnlyHint}</InfoPopover>@@ -1264,7 +1265,7 @@ export function ModelsPage() {{drag.dropEdge !== null && (<divaria-hidden- className={`pointer-events-none absolute inset-x-0 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${+ className={`pointer-events-none absolute inset-x-0 z-10 h-0.5 rounded-full bg-accent ${drag.dropEdge === "above" ? "-top-1.5" : "-bottom-1.5"}`}/>@@ -1461,7 +1462,7 @@ export function ModelsPage() {target="_blank"rel="noreferrer noopener"aria-label={`${S.models.getApiKey} ${group.provider.label}`}- title={S.models.getApiKey}+ data-tooltip={S.models.getApiKey}className="inline-flex shrink-0 items-center whitespace-nowrap p-1 text-xs text-brand-600 underline-offset-2 hover:underline @4xl:p-0 dark:text-brand-300"><GlyphIcon d={EXTERNAL_LINK_ICON} size={13} className="@4xl:hidden" />@@ -2070,7 +2071,7 @@ function AddGroupDialog({type="button"disabled={detecting || busy}onClick={() => void detect()}- title={S.models.detectProtocolHint}+ data-tooltip={S.models.detectProtocolHint}className="flex shrink-0 items-center gap-1 text-xs text-brand-600 underline-offset-2 hover:underline disabled:cursor-not-allowed disabled:text-gray-400 disabled:no-underline dark:text-brand-300 dark:disabled:text-gray-500">{detecting && (@@ -2234,7 +2235,7 @@ export function ModelCard({{speed.ttftMs !== undefined && (<spanclassName={`flex items-center gap-0.5 ${TONE_CLASS[ttftTone(speed.ttftMs)]}`}- title={S.models.ttftTitle}+ data-tooltip={S.models.ttftTitle}><GlyphIcon d={CLOCK_ICON} size={11} />{Math.round(speed.ttftMs)}ms@@ -2243,7 +2244,7 @@ export function ModelCard({{speed.tps !== undefined && (<spanclassName={`flex items-center gap-0.5 ${TONE_CLASS[tpsTone(speed.tps)]}`}- title={S.models.tpsTitle}+ data-tooltip={S.models.tpsTitle}><GlyphIcon d={ZAP_ICON} size={11} />{speed.tps} tok/s@@ -2253,7 +2254,7 @@ export function ModelCard({) : (<spanclassName="shrink-0 text-[11px] font-medium text-red-600 dark:text-red-400"- title={speed.message}+ data-tooltip={speed.message}>{S.models.speedFailed}</span>@@ -2284,7 +2285,7 @@ export function ModelCard({{usedTokens !== undefined && usedTokens > 0 && (<spanclassName="shrink-0 text-[10px] tabular-nums text-gray-400 dark:text-gray-500"- title={S.models.usedTokensTitle}+ data-tooltip={S.models.usedTokensTitle}>{S.models.usedTokens(humanizeTokens(usedTokens))}</span>@@ -2297,7 +2298,11 @@ export function ModelCard({the tags' own, so a card with marks and a card without are exactly as tall. */}<span className="flex min-h-[17px] w-full flex-wrap items-center gap-1">{tags.map((tag) => (- <span key={tag.key} title={tag.title} className={`${TAG_SHAPE} ${tag.className}`}>+ <span+ key={tag.key}+ data-tooltip={tag.title}+ className={`${TAG_SHAPE} ${tag.className}`}+ >{tag.label}</span>))}@@ -2321,8 +2326,9 @@ export function ModelCard({sync, or the move the config dialog's own button performs — so the owner lands wherethe problem is fixed rather than on a second explanation. */}{fix !== null && (- <div- className={`flex items-center justify-between gap-2 border-t px-3 py-2 text-[11px] ${toneStrip.attention}`}+ <NoticeStrip+ tone="attention"+ className="flex items-center justify-between gap-2 border-t px-3 py-2 text-[11px]"><span className="min-w-0">{fix === "sync" ? S.models.vendorRowStalePin : S.models.vendorRowUnroutable}@@ -2337,7 +2343,7 @@ export function ModelCard({{S.models.moveToCustomGroup}</Button>)}- </div>+ </NoticeStrip>)}</div>);@@ -3001,9 +3007,10 @@ function ModelDialog({{fieldErrors.modelId && <FieldError>{fieldErrors.modelId}</FieldError>}</label>{routingFix !== null && (- <div+ <NoticeStrip+ tone="attention"role="alert"- className={`flex items-center justify-between gap-3 rounded-md border px-2.5 py-2 text-xs ${toneStrip.attention}`}+ className="flex items-center justify-between gap-3 rounded-md border px-2.5 py-2 text-xs">{/* A built-in model whose stored entry lost its protocol pin needs the preset sync,not a move: the same split the card makes, so the two places the owner can read@@ -3031,7 +3038,7 @@ function ModelDialog({{S.models.useCustomGroup}</Button>)}- </div>+ </NoticeStrip>)}<div className="grid grid-cols-2 gap-2"><Input@@ -3378,7 +3385,7 @@ function ModelDialog({type="button"disabled={detecting}onClick={() => void detectFromButton()}- title={S.models.detectProtocolHint}+ data-tooltip={S.models.detectProtocolHint}className="flex shrink-0 items-center gap-1 text-xs text-brand-600 underline-offset-2 hover:underline disabled:cursor-not-allowed disabled:text-gray-400 disabled:no-underline dark:text-brand-300 dark:disabled:text-gray-500">{detecting && (@@ -3641,7 +3648,7 @@ function ModelDialog({type="button"disabled={visionDetecting}onClick={() => void detectVisionFromButton()}- title={S.models.detectVisionHint}+ data-tooltip={S.models.detectVisionHint}className="flex shrink-0 items-center gap-1 text-xs text-brand-600 underline-offset-2 hover:underline disabled:cursor-not-allowed disabled:text-gray-400 disabled:no-underline dark:text-brand-300 dark:disabled:text-gray-500">{visionDetecting && (@@ -3673,7 +3680,7 @@ function ModelDialog({<div className={toggleCellClass}><labelclassName={`inline-flex items-center gap-2 ${canEdit ? "cursor-pointer" : "cursor-not-allowed"}`}- title={S.models.fastModeHint}+ data-tooltip={S.models.fastModeHint}><span className="text-xs font-semibold text-gray-600 dark:text-gray-400">{S.models.fastMode}diff --git a/packages/web/src/features/models/protocol-suffix.tsx b/packages/web/src/features/models/protocol-suffix.tsxindex cf02851e..98cc2f31 100644--- a/packages/web/src/features/models/protocol-suffix.tsx+++ b/packages/web/src/features/models/protocol-suffix.tsx@@ -31,8 +31,8 @@*/import { useState } from "react";import { Dropdown } from "../../components/ui/dropdown";-import { CheckIcon, ChevronDown } from "../../components/ui/icons";-import { menuRowClass } from "../../components/ui/field";+import { ChevronDown } from "../../components/ui/icons";+import { ChoiceCheck, menuRowClass, menuRowTone } from "../../components/ui/field";// This menu is an OptionMenu by hand (its trigger lives inside the base URL field, which// OptionMenu cannot do), so it takes its row typography from OptionMenu's own records rather// than re-spelling them — a change to the family reaches it.@@ -86,7 +86,7 @@ export function ProtocolSuffixMenu({aria-haspopup="menu"aria-expanded={open}aria-label={`${S.models.protocol}: ${name}`}- title={S.models.protocolTriggerTitle(name)}+ data-tooltip={S.models.protocolTriggerTitle(name)}onClick={() => setOpen((v) => !v)}className={"flex items-center gap-1 rounded px-1 py-0.5 font-mono text-xs transition-colors duration-150 " +@@ -123,21 +123,13 @@ export function ProtocolSuffixMenu({setOpen(false);onPick(t);}}- className={`block ${menuRowClass} hover:bg-gray-100 dark:hover:bg-gray-800 ${- selected ? "bg-gray-100 dark:bg-gray-800" : ""- }`}+ className={`block ${menuRowClass} ${menuRowTone(selected)}`}><span className="flex items-center justify-between gap-2">- <span- className={`min-w-0 truncate ${sizeTextClass.sm} ${- selected- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-700 dark:text-gray-300"- }`}- >+ <span className={`min-w-0 truncate ${sizeTextClass.sm}`}>{S.models.protocolNames[t] ?? t}</span>- {selected && <CheckIcon className="text-gray-500 dark:text-gray-400" />}+ <ChoiceCheck on={selected} /></span>{/* The path this protocol appends: the same string the trigger shows, so themenu explains what the suffix in the field means. */}diff --git a/packages/web/src/features/palette/command-palette.tsx b/packages/web/src/features/palette/command-palette.tsxindex 717e113b..e9d944df 100644--- a/packages/web/src/features/palette/command-palette.tsx+++ b/packages/web/src/features/palette/command-palette.tsx@@ -68,7 +68,8 @@ export function CommandPalette({ actions }: { actions: readonly PaletteAction[]return createPortal(<div// z-50 like Modal's overlay: a portaled menu or tooltip (z-[60]) opened from inside still paints above it.- className="anim-fade fixed inset-0 z-50 flex justify-center bg-black/45 px-4 pt-[10vh]"+ // ui-scrim: the overlay is the dimmed layer, with the palette inside it.+ className="ui-scrim anim-fade fixed inset-0 z-50 flex justify-center bg-black/45 px-4 pt-[10vh]"onMouseDown={(e) => {if (e.target === e.currentTarget) setOpen(false);}}diff --git a/packages/web/src/features/plugins/plugin-detail-page.tsx b/packages/web/src/features/plugins/plugin-detail-page.tsxindex d850f820..5fb25ecb 100644--- a/packages/web/src/features/plugins/plugin-detail-page.tsx+++ b/packages/web/src/features/plugins/plugin-detail-page.tsx@@ -110,7 +110,7 @@ export function PluginDetailPage() {<buttontype="button"onClick={() => flash(entry.name)}- title={copied ? S.common.copied : S.pluginRegistry.copySpecifier}+ data-tooltip={S.pluginRegistry.copySpecifier}className="inline-flex items-center gap-1 rounded border border-gray-200 px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800"><CopyCheckGlyph copied={copied} size={12} />diff --git a/packages/web/src/features/plugins/plugins-page.tsx b/packages/web/src/features/plugins/plugins-page.tsxindex ab88e6b5..276a6085 100644--- a/packages/web/src/features/plugins/plugins-page.tsx+++ b/packages/web/src/features/plugins/plugins-page.tsx@@ -84,8 +84,9 @@ import { formatRelativeDate } from "../../lib/format";import { SkillTile } from "../skills/skill-icon-view";import { InfoPopover } from "../../components/ui/info-popover";import { ICON_SIZE } from "../../lib/icon-scale";-import { toneInk, toneStrip, toneSurface } from "../../lib/tone";+import { toneInk, toneSurface } from "../../lib/tone";import { Input } from "../../components/ui/input";+import { NoticeStrip } from "../../components/ui/notice-strip";/*** What one Agent has installed, by name → the installed copy's version (`YYYY.MM.DD.N`, or ""@@ -602,7 +603,7 @@ export function PluginsPage() {<div className="h-full overflow-y-auto p-4 [scrollbar-gutter:stable] md:p-6"><div className="mx-auto max-w-5xl"><div className="flex items-center justify-between gap-2">- <h1 className="flex items-center gap-1.5 text-xl font-semibold">+ <h1 className="ui-display flex items-center gap-1.5 text-xl font-semibold">{S.plugins.pageTitle}<InfoPopover label={S.plugins.pageTitle}>{S.plugins.pageDesc}</InfoPopover></h1>@@ -656,14 +657,14 @@ export function PluginsPage() {)}{remote !== null && "error" in remote && remote.machineId === viewMachine && (- <div className={`mt-4 rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" className="mt-4 rounded-md px-3 py-2 text-xs">{S.plugins.machineUnreadable(nameOf(remote.machineId), remote.error)}- </div>+ </NoticeStrip>)}{deployment !== null && viewIncludesHere && deployment.restartPending && (- <div className={`mt-4 rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" className="mt-4 rounded-md px-3 py-2 text-xs">{S.plugins.restartPending}- </div>+ </NoticeStrip>)}{error ? (@@ -1216,7 +1217,7 @@ function Tag({}) {return (<span- title={title}+ data-tooltip={title}className={`rounded-full bg-gray-100 px-2 py-0.5 dark:bg-gray-800 ${mono ? "font-mono text-gray-500 dark:text-gray-400" : "font-medium text-gray-600 dark:text-gray-300"}`}>{children}@@ -1319,14 +1320,16 @@ function PluginCard({<div className="min-w-0 flex-1"><spanclassName="block truncate font-mono text-[13px] font-semibold"- title={plugin.name}+ data-tooltip={plugin.name}+ data-tooltip-content="code">{plugin.name}</span>{/* Short description truncates to one line (full description goes into title for hover reading). */}<pclassName="mt-0.5 truncate text-xs leading-5 text-gray-500 dark:text-gray-400"- title={fullDescription}+ data-tooltip={fullDescription}+ data-tooltip-content="text">{description}</p>@@ -1334,7 +1337,11 @@ function PluginCard({</div>{/* Metadata line under the header (e.g. `v2026.08.29.1 · updated 3 days ago · used by2 agents`); what the plugin contains lives in the detail Modal this card opens. */}- <p className="mt-2.5 truncate text-[11px] text-gray-400 dark:text-gray-500" title={meta}>+ <p+ className="mt-2.5 truncate text-[11px] text-gray-400 dark:text-gray-500"+ data-tooltip={meta}+ data-tooltip-content="text"+ >{meta}</p>{/* Tag line: the category, "built in" (the library ships with the build), what it carries. */}@@ -1508,7 +1515,11 @@ function InstallRow({return (<div className="flex items-center gap-2 rounded-md px-1.5 py-1.5 transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/60"><AgentAvatar id={agentId} name={name} size={22} className="shrink-0 rounded" />- <span className="min-w-0 flex-1 truncate text-sm" title={agentId}>+ <span+ className="min-w-0 flex-1 truncate text-sm"+ data-tooltip={agentId}+ data-tooltip-content="text"+ >{name}</span>{installed && outdated && (@@ -1620,14 +1631,16 @@ function ModuleRow({<div className="flex items-baseline gap-2"><spanclassName="min-w-0 truncate font-mono text-[13px] font-semibold"- title={`${S.pluginRegistry.specifierHint}: ${specifier}`}+ data-tooltip={`${S.pluginRegistry.specifierHint}: ${specifier}`}+ data-tooltip-content="code">{specifier}</span></div><pclassName="mt-0.5 truncate text-xs leading-5 text-gray-500 dark:text-gray-400"- title={entry?.description}+ data-tooltip={entry?.description}+ data-tooltip-content="text">{entry?.description ?? S.plugins.shippedNoEntry}</p>@@ -1635,7 +1648,8 @@ function ModuleRow({</div><pclassName="mt-2.5 truncate text-[11px] text-gray-400 dark:text-gray-500"- title={`${meta}${meta === "" ? "" : " · "}${stateText}`}+ data-tooltip={`${meta}${meta === "" ? "" : " · "}${stateText}`}+ data-tooltip-content="text">{meta !== "" && <span>{meta} · </span>}<span@@ -1653,7 +1667,11 @@ function ModuleRow({</span></p>{state === "failed" && error !== undefined && (- <p className={`mt-1 truncate text-[11px] ${toneInk.danger}`} title={error}>+ <p+ className={`mt-1 truncate text-[11px] ${toneInk.danger}`}+ data-tooltip={error}+ data-tooltip-content="text"+ >{error}</p>)}diff --git a/packages/web/src/features/schedules/schedule-panel.tsx b/packages/web/src/features/schedules/schedule-panel.tsxindex df9d30a8..22b04fd7 100644--- a/packages/web/src/features/schedules/schedule-panel.tsx+++ b/packages/web/src/features/schedules/schedule-panel.tsx@@ -86,7 +86,7 @@ function StateGlyph({ item }: { item: ScheduleItem }) {? CHECK_ICON: INFO_ICON;return (- <span className={`shrink-0 ${tone}`} title={item.invalidReason ?? name}>+ <span className={`shrink-0 ${tone}`} data-tooltip={item.invalidReason ?? name}><GlyphIcon d={d} size={ICON_SIZE.rowLead} filled={glyph === "play"} /><span className="sr-only">{name}</span></span>@@ -109,7 +109,7 @@ function RowMenu({ onEdit, onDelete }: { onEdit: () => void; onDelete: () => voibutton={<buttontype="button"- title={S.schedule.rowActions}+ data-tooltip={S.schedule.rowActions}aria-label={S.schedule.rowActions}aria-haspopup="menu"aria-expanded={open}@@ -298,7 +298,8 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePa// The name leads the tooltip, not just the prompt: a task name is a// file name and truncates in a dock this narrow, and the panel would// otherwise be the one surface that cannot show it in full.- title={`${item.name}\n${item.prompt}`}+ data-tooltip={`${item.name}\n${item.prompt}`}+ data-tooltip-content="text">{item.name}</span>@@ -306,7 +307,8 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePa</div><divclassName="truncate text-xs text-gray-500 dark:text-gray-400"- title={item.invalidReason ?? line}+ data-tooltip={item.invalidReason ?? line}+ data-tooltip-content="text">{line}</div>diff --git a/packages/web/src/features/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsxindex 43d612be..85e78e65 100644--- a/packages/web/src/features/settings/appearance-section.tsx+++ b/packages/web/src/features/settings/appearance-section.tsx@@ -1,19 +1,23 @@/**- * Appearance page: the look-and-feel preferences that used to sit as rows in the sidebar- * user menu. Everything applies on the spot (the theme store persists per browser), so- * there is no Save button. The terminal keeps its own theme row because plenty of people- * pin a dark terminal inside a light app; it follows the app unless pinned (see- * TerminalThemeMode). The workbench launcher's row is here rather than with the chat's own- * settings because it is the same kind of choice: whether a piece of chrome is drawn. The- * tool short-name row is here for the same reason — it changes how a tool call is spelled- * on screen, never what runs. So is the tray-icon row, the one piece of chrome here that- * is not drawn by this page at all: it is the desktop shell's, and only the shell's own- * window may reach it (see isDesktopShellWindow), so the row is absent in a browser.+ * Appearance page: the look-and-feel preferences. Theme, light or dark, accent, text size and+ * font pairing come first, since each restyles the whole app. Everything applies on the spot+ * (the theme store persists per browser), so there is no Save button. The terminal keeps its+ * own theme row because plenty of people pin a dark terminal inside a light app; it follows+ * the app unless pinned (see TerminalThemeMode). The workbench launcher's row is here rather+ * than with the chat's own settings because it is the same kind of choice: whether a piece of+ * chrome is drawn. The tool short-name row is here for the same reason — it changes how a+ * tool call is spelled on screen, never what runs. So is the tray-icon row, the one piece of+ * chrome here that is not drawn by this page at all: it is the desktop shell's, and only the+ * shell's own window may reach it (see isDesktopShellWindow), so the row is absent in a+ * browser.*/import { useEffect, useState, useSyncExternalStore } from "react";+import { THEME_IDS } from "@prismshadow/penguin-ui";+import { FONT_CJK_OPTIONS, FONT_LATIN_OPTIONS, TEXT_SIZES } from "@prismshadow/penguin-ui/boot";import { S } from "../../lib/strings";import * as api from "../../api/endpoints";import { Segmented } from "../../components/ui/segmented";+import { Select } from "../../components/ui/select";import { Switch } from "../../components/ui/switch";import { isDesktopShellWindow } from "../../lib/account-menu";import {@@ -24,15 +28,89 @@ import {} from "../dock/dock-launcher-state";import { useAuth } from "../../state/auth";import { useTheme } from "../../state/theme";-import type { FontScale, TerminalThemeMode, ThemeMode } from "../../state/theme";+import type {+ FontCjk,+ FontLatin,+ TerminalThemeMode,+ TextSize,+ ThemeId,+ ThemeMode,+} from "../../state/theme";+import { FONT_FOLLOWS_THEME, effectiveAccent } from "../../state/theme-prefs";import { AccentPicker, PrefRow } from "./setting-row";+/**+ * A font select's choices: the theme's own face first — it is the default, and the named faces+ * are the opt-out — then the faces the package lists. The package names each bundled face by+ * its proper name, the same in both languages; "theme" and "system" are not names, so their+ * words come from this app's dictionaries.+ */+export function fontChoices<T extends string>(+ options: ReadonlyArray<{ id: T; label: string }>,+): Array<{ value: T; label: string }> {+ return [+ { value: FONT_FOLLOWS_THEME as T, label: S.settings.fontFollowTheme },+ ...options+ .filter((option) => option.id !== FONT_FOLLOWS_THEME)+ .map((option) => ({+ value: option.id,+ label: option.id === "system" ? S.settings.fontSystem : option.label,+ })),+ ];+}++/** One of the two font selects, with the short visible name that tells the pair apart. */+function FontSelect<T extends string>({+ name,+ value,+ choices,+ onChange,+}: {+ name: string;+ value: T;+ choices: ReadonlyArray<{ value: T; label: string }>;+ onChange: (next: T) => void;+}) {+ return (+ <span className="flex min-w-0 items-center gap-1.5">+ <span+ aria-hidden+ className="shrink-0 whitespace-nowrap text-xs text-gray-500 dark:text-gray-400"+ >+ {name}+ </span>+ <span className="w-36 min-w-0 shrink">+ <Select+ aria-label={`${S.settings.fonts} · ${name}`}+ value={value}+ onChange={(e) => {+ const next = choices.find((choice) => choice.value === e.target.value);+ if (next) onChange(next.value);+ }}+ >+ {choices.map((choice) => (+ <option key={choice.value} value={choice.value}>+ {choice.label}+ </option>+ ))}+ </Select>+ </span>+ </span>+ );+}+export function AppearanceSection() {const {mode,setMode,- fontScale,- setFontScale,+ themeId,+ setThemeId,+ textSize,+ setTextSize,+ fontLatin,+ setFontLatin,+ fontCjk,+ setFontCjk,accent,setAccent,terminalMode,@@ -80,25 +158,55 @@ export function AppearanceSection() {{ value: "light", label: S.settings.themeLight },{ value: "dark", label: S.settings.themeDark },];- const fontOptions: ReadonlyArray<{ value: FontScale; label: string }> = [- { value: "sm", label: S.settings.fontSmall },- { value: "md", label: S.settings.fontMedium },- { value: "lg", label: S.settings.fontLarge },- ];+ const themeIdOptions: ReadonlyArray<{ value: ThemeId; label: string }> = THEME_IDS.map((id) => ({+ value: id,+ label: S.settings.themeNames[id],+ }));+ const textSizeOptions: ReadonlyArray<{ value: TextSize; label: string }> = TEXT_SIZES.map(+ (size) => ({ value: size, label: S.settings.textSizeNames[size] }),+ );return (<div className="divide-y divide-gray-100 dark:divide-gray-800/60"><PrefRow label={S.settings.theme} info={S.settings.themeInfo}>+ <Segmented options={themeIdOptions} value={themeId} onChange={setThemeId} />+ </PrefRow>+ <PrefRow label={S.settings.colorMode} info={S.settings.colorModeInfo}><Segmented options={themeOptions} value={mode} onChange={setMode} /></PrefRow>- <PrefRow label={S.settings.terminalTheme} info={S.settings.terminalThemeInfo}>- <Segmented options={terminalThemeOptions} value={terminalMode} onChange={setTerminalMode} />+ {/* The swatches are the active theme's own; a stored preset it does not list is shown+ as the theme's own accent, which is what the page paints, and comes back with the+ theme that lists it. */}+ <PrefRow label={S.settings.accent} info={S.settings.accentInfo}>+ <AccentPicker+ themeId={themeId}+ value={effectiveAccent(themeId, accent)}+ onChange={setAccent}+ /></PrefRow><PrefRow label={S.settings.fontSize} info={S.settings.fontSizeInfo}>- <Segmented options={fontOptions} value={fontScale} onChange={setFontScale} />+ <Segmented options={textSizeOptions} value={textSize} onChange={setTextSize} cols={5} /></PrefRow>- <PrefRow label={S.settings.accent} info={S.settings.accentInfo}>- <AccentPicker value={accent} onChange={setAccent} />+ <PrefRow label={S.settings.fonts} info={S.settings.fontsInfo}>+ {/* One line always: the pair shrinks rather than wraps (a wrapped pair read as two+ settings under the stacked label a theme may give this row). */}+ <div className="flex min-w-0 items-center justify-end gap-x-3">+ <FontSelect<FontLatin>+ name={S.settings.fontLatin}+ value={fontLatin}+ choices={fontChoices(FONT_LATIN_OPTIONS)}+ onChange={setFontLatin}+ />+ <FontSelect<FontCjk>+ name={S.settings.fontCjk}+ value={fontCjk}+ choices={fontChoices(FONT_CJK_OPTIONS)}+ onChange={setFontCjk}+ />+ </div>+ </PrefRow>+ <PrefRow label={S.settings.terminalTheme} info={S.settings.terminalThemeInfo}>+ <Segmented options={terminalThemeOptions} value={terminalMode} onChange={setTerminalMode} /></PrefRow><PrefRow label={S.settings.launcher} info={S.settings.launcherInfo}><Switch checked={launcherShown} onChange={(shown) => writeLauncherHidden(!shown)} />diff --git a/packages/web/src/features/settings/credits-section.tsx b/packages/web/src/features/settings/credits-section.tsxnew file mode 100644index 00000000..c37d54f6--- /dev/null+++ b/packages/web/src/features/settings/credits-section.tsx@@ -0,0 +1,96 @@+/**+ * Credits page: the fonts the app bundles, which themes set them, and the licence each ships+ * under, with the licence's full text one click away. The list comes from the UI package's font+ * metadata (the same record its licence files and build scripts are checked against), so a face+ * added or dropped there appears or disappears here without an edit.+ *+ * MiSans's licence asks software that uses the face to credit it, and this page is where the+ * app does: the face is listed with its licence for every account and every backend, which is+ * why the page itself is visible to everyone, the desktop shell's window included. The page is+ * the list and nothing else; the rail already names it.+ *+ * Each licence text is a disclosure (the WAI-ARIA pattern: a real button with `aria-expanded`+ * and `aria-controls`, the panel kept in the DOM and `hidden` while folded). A licence runs to+ * pages, so the open panel scrolls inside a capped height rather than pushing the next font a+ * screen away.+ */+import { useId, useState } from "react";+import { FONT_CREDITS } from "@prismshadow/penguin-ui/fonts-credits";+import type { FontCredit } from "@prismshadow/penguin-ui/fonts-credits";+import type { ThemeId } from "@prismshadow/penguin-ui";+import { S } from "../../lib/strings";+import { ICON_GAP } from "../../lib/icon-scale";+import { Chevron } from "../../components/ui/chevron";++/** A theme id in the reader's words. */+function themeName(id: ThemeId): string {+ return S.settings.themeNames[id];+}++function LicenseText({ text }: { text: string }) {+ const [open, setOpen] = useState(false);+ const panelId = useId();+ return (+ <div className="mt-2">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={panelId}+ onClick={() => setOpen((v) => !v)}+ className={`flex items-center ${ICON_GAP.row} text-xs text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200`}+ >+ <Chevron open={open} size={12} />+ {S.settings.creditsLicenseText}+ </button>+ <pre+ id={panelId}+ hidden={!open}+ className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap rounded-md bg-gray-50 px-3 py-2 font-mono text-xs leading-5 text-gray-600 dark:bg-gray-900 dark:text-gray-300"+ >+ {text}+ </pre>+ </div>+ );+}++function CreditRow({ font }: { font: FontCredit }) {+ return (+ <li className="py-3.5 first:pt-0 last:pb-0">+ <p className="text-sm font-medium">{font.family}</p>+ <dl className="mt-1 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs">+ <dt className="text-gray-500 dark:text-gray-400">{S.settings.creditsThemes}</dt>+ {/* A face no theme sets by default (IBM Plex Sans Condensed) still ships, so it is+ listed and licensed like the rest, and says so rather than leaving the line blank. */}+ <dd>+ {font.themes.length > 0+ ? font.themes.map(themeName).join(" · ")+ : S.settings.creditsNoTheme}+ </dd>+ <dt className="text-gray-500 dark:text-gray-400">{S.settings.creditsLicense}</dt>+ <dd>{font.licenseTitle}</dd>+ <dt className="text-gray-500 dark:text-gray-400">{S.settings.creditsSource}</dt>+ <dd className="min-w-0 break-all">+ <a+ href={font.source}+ target="_blank"+ rel="noreferrer"+ className="text-link underline-offset-2 hover:underline"+ >+ {font.source}+ </a>+ </dd>+ </dl>+ <LicenseText text={font.licenseText} />+ </li>+ );+}++export function CreditsSection() {+ return (+ <ul className="divide-y divide-gray-100 dark:divide-gray-800/60">+ {FONT_CREDITS.map((font) => (+ <CreditRow key={font.id} font={font} />+ ))}+ </ul>+ );+}diff --git a/packages/web/src/features/settings/plugins-section.tsx b/packages/web/src/features/settings/plugins-section.tsxindex 46ffcf08..b992b15d 100644--- a/packages/web/src/features/settings/plugins-section.tsx+++ b/packages/web/src/features/settings/plugins-section.tsx@@ -33,10 +33,12 @@ import { PasswordInput } from "../../components/ui/password-input";import { Select } from "../../components/ui/select";import { Switch } from "../../components/ui/switch";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";-import { toneInk, toneStrip } from "../../lib/tone";+import { toneInk } from "../../lib/tone";import { SectionShell } from "./section-shell";import { useSessions } from "../../state/sessions";import { MachinePicker } from "../machines/machine-picker";+import { NoticeStrip } from "../../components/ui/notice-strip";+import { Spinner } from "@prismshadow/penguin-ui";/** The picker's value for this server; a machine id is never this short. */const THIS_SERVER = "*";@@ -494,7 +496,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {return (<div className="space-y-1.5"><div>- <p className={nested ? "text-[13px] font-semibold" : "text-sm font-semibold"}>+ <p className={nested ? "text-xs font-semibold" : "text-sm font-semibold"}>{localized(entry.configuration.title, entry.configuration.titleZh) ?? entry.name}</p><p className="font-mono text-xs text-gray-500 dark:text-gray-400">{entry.name}</p>@@ -527,16 +529,13 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {{(entry.notices ?? []).map((notice, i) =>notice.tone === "progress" ? (<p key={i} className={`flex items-center gap-2 text-xs ${toneInk.busy}`}>- <span- aria-hidden- className="inline-block size-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent"- />+ <Spinner size="sm" label={S.common.loading} /><span className="min-w-0 break-words">{localized(notice.text, notice.textZh)}</span></p>) : notice.tone === "attention" ? (- <p key={i} className={`rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" as="p" key={i} className="rounded-md px-3 py-2 text-xs">{localized(notice.text, notice.textZh)}- </p>+ </NoticeStrip>) : (<p key={i} className="text-xs text-gray-500 dark:text-gray-400">{localized(notice.text, notice.textZh)}@@ -555,9 +554,9 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {<SectionShell>{picker}{machine !== null && loadError !== null && (- <p className={`rounded-md px-3 py-2 text-xs ${toneStrip.attention}`}>+ <NoticeStrip tone="attention" as="p" className="rounded-md px-3 py-2 text-xs">{S.plugins.machineUnreadable(nameOf(machine), loadError)}- </p>+ </NoticeStrip>)}<FocusCard focus={focus} ready={entries.length > 0} />{cards.map((card) => {diff --git a/packages/web/src/features/settings/setting-row.tsx b/packages/web/src/features/settings/setting-row.tsxindex 4c94a8b1..28a2fd30 100644--- a/packages/web/src/features/settings/setting-row.tsx+++ b/packages/web/src/features/settings/setting-row.tsx@@ -9,8 +9,8 @@ import type { ReactNode } from "react";import { S } from "../../lib/strings";import { ICON_GAP } from "../../lib/icon-scale";import { InfoPopover } from "../../components/ui/info-popover";-import { ACCENT_SWATCHES } from "../../state/theme";-import type { Accent } from "../../state/theme";+import { accentSwatches, useTheme } from "../../state/theme";+import type { Accent, ThemeId } from "../../state/theme";export function PrefRow({label,@@ -30,8 +30,10 @@ export function PrefRow({children: ReactNode;}) {return (- <div className="flex items-center justify-between gap-4 py-3.5 first:pt-0 last:pb-0">- <div className="min-w-0">+ // ui-field: a theme may lay the label and the control out its own way (stacked, or as a+ // table row); the hint rides inside the label slot, under the label, in every theme.+ <div className="ui-field flex items-center justify-between gap-4 py-3.5 first:pt-0 last:pb-0">+ <div data-slot="label" className="min-w-0"><p className={`flex items-center ${ICON_GAP.row} text-sm font-medium`}>{label}{info !== undefined && <InfoPopover label={label}>{info}</InfoPopover>}@@ -40,26 +42,35 @@ export function PrefRow({<p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">{hint}</p>)}</div>- <div className="shrink-0">{children}</div>+ <div data-slot="control" className="shrink-0">+ {children}+ </div></div>);}-/** Accent color picker: a row of swatches, with a ring on the selected one. */+/**+ * Accent color picker: a row of swatches — the theme's own accent, then the active theme's+ * presets — with a ring on the one in effect.+ */export function AccentPicker({+ themeId,value,onChange,}: {+ themeId: ThemeId;+ /** The accent in effect under `themeId`, not merely the stored one. */value: Accent;onChange: (a: Accent) => void;}) {+ const { dark } = useTheme();return (<div className="flex items-center gap-1.5">- {ACCENT_SWATCHES.map((s) => (+ {accentSwatches(themeId, dark).map((s) => (<buttonkey={s.value}type="button"- title={S.settings.accentNames[s.value]}+ data-tooltip={S.settings.accentNames[s.value]}aria-label={S.settings.accentNames[s.value]}aria-pressed={value === s.value}onClick={() => onChange(s.value)}diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsxindex f6c3aebb..c9a63fe4 100644--- a/packages/web/src/features/settings/settings-dialog.tsx+++ b/packages/web/src/features/settings/settings-dialog.tsx@@ -30,6 +30,7 @@ import { UploadsSection } from "./uploads-section";import { CompanySection } from "./company-section";import { PluginsSection } from "./plugins-section";import { AdminUsersSection } from "../admin/admin-users-page";+import { CreditsSection } from "./credits-section";/** Rail glyphs, on the shared 24x24 stroke grid (see NAV_ICONS' conventions). */const SECTION_ICONS: Record<SettingsSectionKey, string> = {@@ -45,6 +46,8 @@ const SECTION_ICONS: Record<SettingsSectionKey, string> = {"M3 6h18a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zM6 9.5h.01M9.5 9.5h.01M13 9.5h.01M16.5 9.5h.01M6 12.5h.01M9.5 12.5h.01M13 12.5h.01M16.5 12.5h.01M8.5 15.5h7",/** Single person: the signed-in account. */account: "M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z",+ /** Circled C: credits and licences. */+ credits: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM15 9.5a3.5 3.5 0 1 0 0 5",/** Globe: outbound traffic. */proxy:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 0 0 0 18M12 3a15 15 0 0 1 0 18",@@ -100,6 +103,7 @@ export function SettingsDialog({appearance: S.settings.appearanceTitle,shortcuts: S.settings.shortcutsTitle,account: S.settings.accountTitle,+ credits: S.settings.creditsTitle,proxy: S.settings.proxyTitle,uploads: S.settings.uploadLimitsTitle,company: S.settings.companyModeTitle,@@ -149,6 +153,7 @@ export function SettingsDialog({{current === "appearance" && <AppearanceSection />}{current === "shortcuts" && <ShortcutsSection />}{current === "account" && <AccountSection />}+ {current === "credits" && <CreditsSection />}{current === "proxy" && <ProxySection />}{current === "uploads" && <UploadsSection />}{current === "company" && <CompanySection />}diff --git a/packages/web/src/features/settings/settings-request.ts b/packages/web/src/features/settings/settings-request.tsnew file mode 100644index 00000000..80af9932--- /dev/null+++ b/packages/web/src/features/settings/settings-request.ts@@ -0,0 +1,43 @@+/**+ * Opening the Settings dialog from outside the account menu that owns it.+ *+ * The dialog's open state lives in the one UserMenu the sidebar mounts (it is the menu's row+ * that opens it), so a caller elsewhere — a host that frames the app on a settings page, a+ * future command — asks through here rather than reaching for that state. A request made+ * before the menu has mounted (the app is still signing in, the layout is not up) is kept and+ * delivered the moment it subscribes, so "open Settings on Appearance" is honoured however+ * early it is asked.+ */+import type { SettingsSectionKey } from "../../lib/settings-sections";++export interface SettingsRequest {+ /** The page to open on; absent opens the viewer's first page, as the menu row does. */+ section?: SettingsSectionKey;+}++type Listener = (request: SettingsRequest) => void;++let listener: Listener | null = null;+let pending: SettingsRequest | null = null;++/** Asks the mounted account menu to open Settings; kept until one mounts if none has. */+export function requestSettings(request: SettingsRequest = {}): void {+ if (listener) listener(request);+ else pending = request;+}++/**+ * The account menu's side: answers requests for as long as it is mounted, and takes a request+ * made before it mounted at once. One listener at a time — the sidebar mounts one menu.+ */+export function onSettingsRequest(next: Listener): () => void {+ listener = next;+ if (pending) {+ const request = pending;+ pending = null;+ next(request);+ }+ return () => {+ if (listener === next) listener = null;+ };+}diff --git a/packages/web/src/features/settings/shortcut-recorder.tsx b/packages/web/src/features/settings/shortcut-recorder.tsxindex 2fb0f9d6..878b74ec 100644--- a/packages/web/src/features/settings/shortcut-recorder.tsx+++ b/packages/web/src/features/settings/shortcut-recorder.tsx@@ -86,7 +86,7 @@ export function ShortcutRecorder({<buttonref={buttonRef}type="button"- title={S.shortcuts.rebind}+ data-tooltip={S.shortcuts.rebind}aria-pressed={recording}onClick={() => {if (!recording) update(recorderStart());diff --git a/packages/web/src/features/settings/shortcuts-section.tsx b/packages/web/src/features/settings/shortcuts-section.tsxindex f9ae297f..24e519ec 100644--- a/packages/web/src/features/settings/shortcuts-section.tsx+++ b/packages/web/src/features/settings/shortcuts-section.tsx@@ -101,7 +101,7 @@ function ShortcutRow({{overridden && (<buttontype="button"- title={S.shortcuts.resetRow}+ data-tooltip={S.shortcuts.resetRow}aria-label={`${S.shortcuts.resetRow}: ${S.shortcuts.commands[cmd.id]}`}onClick={() => resetBinding(cmd.id)}className="flex h-6 w-6 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"diff --git a/packages/web/src/features/skills/skill-pick-list.tsx b/packages/web/src/features/skills/skill-pick-list.tsxindex eee0e770..ab2d825f 100644--- a/packages/web/src/features/skills/skill-pick-list.tsx+++ b/packages/web/src/features/skills/skill-pick-list.tsx@@ -24,6 +24,7 @@ import { ICON_SIZE } from "../../lib/icon-scale";import { menuSearchClass, noAutofill } from "../../components/ui/input";import { filterSkills, localizedShortText } from "../chat/skill-use";import { SkillIcon } from "./skill-icon-view";+import { ChoiceCheck, menuRowClass, menuRowTone } from "../../components/ui/field";/** A bulk-row action: a plain text button, sized to sit inside the panel's chrome without competing with the rows. */const bulkActionClass =@@ -110,11 +111,7 @@ export function SkillPickList({type="button"aria-pressed={on}onClick={() => onToggle(s.name)}- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${- on- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-600 dark:text-gray-400"- }`}+ className={`flex items-center gap-2 ${menuRowClass} text-xs ${menuRowTone(on)}`}>{/* Each row's icon (icon.svg, sanitized and inlined), else the kind's glyph. */}<SkillIcon@@ -128,7 +125,7 @@ export function SkillPickList({<span className="min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500">{localizedShortText(locale, s)}</span>- <span className="w-3 shrink-0 text-center">{on ? "✓" : ""}</span>+ <ChoiceCheck on={on} /></button>);})diff --git a/packages/web/src/features/terminal/terminal-appearance.ts b/packages/web/src/features/terminal/terminal-appearance.tsindex f344feb8..4be7d30f 100644--- a/packages/web/src/features/terminal/terminal-appearance.ts+++ b/packages/web/src/features/terminal/terminal-appearance.ts@@ -1,7 +1,7 @@/*** The terminal's chrome palette, resolved in JS rather than through Tailwind's `dark:`.*- * That variant is anchored on the root class (`&:where(.dark, .dark *)` in styles.css), so+ * That variant is anchored on the root class (`&:where(.dark, .dark *)` in @prismshadow/penguin-ui's theme.css), so* a subtree can opt IN to dark but never out of it — and the terminal's appearance is its* own setting (see TerminalThemeMode), which means a light terminal inside a dark app has* to be expressible. Hence whole class strings picked by a resolved boolean.diff --git a/packages/web/src/features/terminal/terminal-keybar.tsx b/packages/web/src/features/terminal/terminal-keybar.tsxindex 5f5c120d..d1a50a7f 100644--- a/packages/web/src/features/terminal/terminal-keybar.tsx+++ b/packages/web/src/features/terminal/terminal-keybar.tsx@@ -90,7 +90,7 @@ export function TerminalKeyBar({ control, modifiers, onModifiers, focused }: Tertype="button"data-testid={props.testId}aria-label={props.label}- title={props.label}+ data-tooltip={props.label}{...(props.pressed !== undefined ? { "aria-pressed": props.pressed } : {})}// Keeps focus (and the soft keyboard) on the terminal — see the file header.onMouseDown={(event) => event.preventDefault()}diff --git a/packages/web/src/features/terminal/terminal-page.tsx b/packages/web/src/features/terminal/terminal-page.tsxindex 429cf67c..73fcdcef 100644--- a/packages/web/src/features/terminal/terminal-page.tsx+++ b/packages/web/src/features/terminal/terminal-page.tsx@@ -205,8 +205,9 @@ export function TerminalPage() {data-testid="terminal-status"data-status={status}// The dot is the whole mark on a phone, so the sentence it stands for has to- // reach a screen reader from somewhere: the title carries it either way.- title={statusText}+ // reach a screen reader from somewhere: the sr-only copy carries it, and the+ // tooltip shows it on hover either way.+ data-tooltip={statusText}className={`flex shrink-0 items-center gap-1 ${status === "ready"? chrome.success@@ -224,7 +225,7 @@ export function TerminalPage() {data-testid="terminal-new-shell"onClick={restart}aria-label={S.terminal.newShell}- title={S.terminal.newShell}+ data-tooltip={S.terminal.newShell}className={`flex shrink-0 items-center gap-1 rounded border px-2 py-1 ${chrome.outlineButton}`}><GlyphIcon d={ADD_ICON} size={ICON_SIZE.rowLead} />diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsxindex ac279f1d..15845419 100644--- a/packages/web/src/features/terminal/terminal-view.tsx+++ b/packages/web/src/features/terminal/terminal-view.tsx@@ -65,8 +65,8 @@ export type TerminalStatus = "connecting" | "ready" | "exited" | "error";* The screen's own palette, one per appearance. Two things matter here.** The surface colours are the app's, not a terminal's: `#000000`/`#ffffff` are the body- * tones (styles.css overrides the neutral gray scale to pure black in dark mode), and the- * selection matches `::selection` there. A panel docked inside the app that brought its+ * tones (the default theme, `themes/github.css` in @prismshadow/penguin-ui, overrides the+ * neutral gray scale to pure black in dark mode), and the selection matches its `::selection`. A panel docked inside the app that brought its* own charcoal along read as a foreign window sitting on top of it.** The sixteen ANSI slots are NOT the app's palette and must not be: programs pick them bydiff --git a/packages/web/src/features/traces/timeline-chart.tsx b/packages/web/src/features/traces/timeline-chart.tsxindex d71fb4e0..ddbe4a2c 100644--- a/packages/web/src/features/traces/timeline-chart.tsx+++ b/packages/web/src/features/traces/timeline-chart.tsx@@ -33,6 +33,8 @@ import { S } from "../../lib/strings";import { humanizeDuration } from "../../lib/format";import { packToolLanes, toolSpanBounds } from "./lane-packing";import type { PackedLane } from "./lane-packing";+import { namedHint } from "../../components/ui/tooltip";+import { ChartSwatch, TimelineBar, type ChartPaint } from "../../components/ui/chart";/*** Linked highlighting: `ts` is the anchor shared by both sides; `key` /@@ -52,17 +54,27 @@ export interface TraceHighlight {rowKey?: string;}-/** Fixed color for each of the five bar kinds (solid fill, clear contrast; no gray/black/white/indigo — the muted-on-purpose `other` is exempt). */-const COLORS = {- thinking: "bg-violet-500 dark:bg-violet-400",- text: "bg-sky-500 dark:bg-sky-400",- toolgen: "bg-amber-500 dark:bg-amber-400",- approvalWait: "bg-rose-400 dark:bg-rose-300",- exec: "bg-emerald-500 dark:bg-emerald-400",- // Non-tool auxiliary phases (MCP connect): their own legend category, not tool- // execution — deliberately muted, background bookkeeping shouldn't outshine the work.- other: "bg-gray-400 dark:bg-gray-500",-} as const;+/**+ * The theme's palette slot each of the five bar kinds paints with (0-based; see+ * lib/chart-style.ts): thinking violet, model reply sky, tool-call generation amber, approval+ * wait rose, tool execution emerald. Identities, not judgements, so every theme keeps them and+ * picks its own shade of each.+ */+const KIND_SLOT = { thinking: 0, text: 2, toolgen: 1, approvalWait: 3, exec: 4 } as const;+type BarKind = keyof typeof KIND_SLOT | "other";++/**+ * Non-tool auxiliary phases (MCP connect) are their own legend category, not tool execution —+ * deliberately muted, since background bookkeeping should not outshine the work: the neutral+ * gray rather than a palette slot.+ */+const OTHER_CLASS = "bg-gray-400 dark:bg-gray-500";++/** A bar kind's paint: its palette slot, or the neutral for the auxiliary phases. */+const kindPaint = (kind: BarKind): ChartPaint =>+ kind === "other"+ ? { ink: "text-gray-400 dark:text-gray-500", swatch: OTHER_CLASS }+ : { series: KIND_SLOT[kind] };/*** Left-side label column: sticky-pinned to the far left during horizontal@@ -84,11 +96,11 @@ const MIN_WIN = 1 / ZOOM_MAX;const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));-/** Model-lane segment color: thinking / text (model reply) / tool_call (tool-call generation). */-function segmentColor(kind: TraceModelSegment["kind"]): string {- if (kind === "thinking") return COLORS.thinking;- if (kind === "text") return COLORS.text;- return COLORS.toolgen;+/** Model-lane segment kind: thinking / text (model reply) / tool_call (tool-call generation). */+function segmentKind(kind: TraceModelSegment["kind"]): BarKind {+ if (kind === "thinking") return "thinking";+ if (kind === "text") return "text";+ return "toolgen";}function segmentLabel(kind: TraceModelSegment["kind"]): string {@@ -245,7 +257,10 @@ function buildGroups(/** Track: the gray-background container for bars (no rounded corners; overflow-hidden keeps bars from overlapping adjacent text). */function Track({ children }: { children: ReactNode }) {return (- <div className="relative h-4 min-w-0 flex-1 overflow-hidden bg-gray-100 dark:bg-gray-800/60">+ <div+ data-part="grid"+ className="relative h-4 min-w-0 flex-1 overflow-hidden bg-gray-100 dark:bg-gray-800/60"+ >{children}</div>);@@ -254,7 +269,11 @@ function Track({ children }: { children: ReactNode }) {function Lane({ label, children }: { label: string; children: ReactNode }) {return (<div className="flex items-center">- <span className={`${LABEL_STICKY} text-gray-400 dark:text-gray-500`} title={label}>+ <span+ className={`${LABEL_STICKY} text-gray-400 dark:text-gray-500`}+ data-tooltip={label}+ data-tooltip-content="text"+ ><span className={LABEL_TEXT}>{label}</span></span><Track>{children}</Track>@@ -291,10 +310,14 @@ function Ticks({ total }: { total: number }) {);}+/** The default for a caller with no other spans: one shared array, so the grouping memo (and the+ * view effect keyed on it) stays put across renders instead of rerunning on a fresh `[]`. */+const NO_OTHER_SPANS: TraceOtherSpan[] = [];+export function TimelineChart({segments,toolSpans,- otherSpans = [],+ otherSpans = NO_OTHER_SPANS,highlight,onHighlight,onJump,@@ -370,7 +393,10 @@ export function TimelineChart({const el = scrollRef.current;if (!el) return;const sw = el.scrollWidth || 1;- setView({ left: el.scrollLeft / sw, width: Math.min(1, el.clientWidth / sw) });+ const left = el.scrollLeft / sw;+ const width = Math.min(1, el.clientWidth / sw);+ // Same window, same state object: a layout effect that measures must not re-render for nothing.+ setView((v) => (v.left === left && v.width === width ? v : { left, width }));}, []);useLayoutEffect(() => {@@ -430,13 +456,13 @@ export function TimelineChart({return { left: `${left}%`, width: `${width}%` };};- const legendChips: Array<{ key: string; className: string; label: string }> = [- { key: "thinking", className: COLORS.thinking, label: S.traces.kindThinking },- { key: "text", className: COLORS.text, label: S.traces.kindModelReply },- { key: "toolgen", className: COLORS.toolgen, label: S.traces.kindToolGen },- { key: "approvalWait", className: COLORS.approvalWait, label: S.traces.legendApprovalWait },- { key: "exec", className: COLORS.exec, label: S.traces.legendToolExec },- { key: "other", className: COLORS.other, label: S.traces.legendOther },+ const legendChips: Array<{ key: BarKind; label: string }> = [+ { key: "thinking", label: S.traces.kindThinking },+ { key: "text", label: S.traces.kindModelReply },+ { key: "toolgen", label: S.traces.kindToolGen },+ { key: "approvalWait", label: S.traces.legendApprovalWait },+ { key: "exec", label: S.traces.legendToolExec },+ { key: "other", label: S.traces.legendOther },];// —— Slider (Premiere-style): drag the body to pan, drag either handle to zoom, double-click to reset ——@@ -521,7 +547,8 @@ export function TimelineChart({};return (- <div className="space-y-3">+ // ui-chart: a theme may redraw the parts — the lane tracks (grid) and the bars.+ <div className="ui-chart space-y-3">{/* Timeline (horizontal scroll container; native scrollbar hidden in favor of the slider below). overflow-y-hidden avoids a spurious vertical scrollbar. */}<div ref={scrollRef} className="no-scrollbar overflow-x-auto overflow-y-hidden"><div className="space-y-4" style={{ width: `${zoom * 100}%` }}>@@ -547,14 +574,17 @@ export function TimelineChart({const barKey = `s-${g.taskIndex}-${i}`;const active = isActive(barKey);return (- <span+ <TimelineBarkey={i}onMouseEnter={() => enter(barKey, s.ts)}onMouseLeave={leave}onClick={() => onJump?.(s.ts)}- title={`${segmentLabel(s.kind)}${s.name ? ` ${s.name}` : ""} · ${humanizeDuration(s.endMs - s.startMs)}`}- className={`absolute inset-y-0 min-w-[2px] cursor-pointer ${segmentColor(s.kind)} ${dimClass(active, legendMatch)}`}- style={placeExact(s.startMs, s.endMs, g.t0, g.total)}+ {...namedHint(+ `${segmentLabel(s.kind)}${s.name ? ` ${s.name}` : ""} · ${humanizeDuration(s.endMs - s.startMs)}`,+ )}+ className={`cursor-pointer ${dimClass(active, legendMatch)}`}+ paint={kindPaint(segmentKind(s.kind))}+ place={placeExact(s.startMs, s.endMs, g.t0, g.total)}/>);})}@@ -565,7 +595,8 @@ export function TimelineChart({<div key={`${rowIdx}-${row.name}`} className="flex items-center"><spanclassName={`${LABEL_STICKY} text-gray-500 dark:text-gray-400`}- title={row.name}+ data-tooltip={row.name}+ data-tooltip-content="text"><span className={LABEL_TEXT}>{row.name}</span></span>@@ -580,16 +611,19 @@ export function TimelineChart({<Fragment key={s.toolCallId}>{/* Approval-wait segment (positioned exactly, flush against the execution segment) */}{s.approvalMs !== null && s.approvalMs > s.callMs && (- <span+ <TimelineBaronMouseEnter={() => enter(`w-${s.toolCallId}`, approvalTs)}onMouseLeave={leave}onClick={() => onJump?.(approvalTs)}- title={`${s.name} · ${S.traces.legendApprovalWait}${s.decision ? ` (${s.decision})` : ""} · ${humanizeDuration(s.approvalMs - s.callMs)}`}- className={`absolute inset-y-0 min-w-[2px] cursor-pointer ${COLORS.approvalWait} ${dimClass(+ {...namedHint(+ `${s.name} · ${S.traces.legendApprovalWait}${s.decision ? ` (${s.decision})` : ""} · ${humanizeDuration(s.approvalMs - s.callMs)}`,+ )}+ className={`cursor-pointer ${dimClass(isActive(`w-${s.toolCallId}`),legendKey === null || legendKey === "approvalWait",)}`}- style={placeExact(s.callMs, s.approvalMs, g.t0, g.total)}+ paint={kindPaint("approvalWait")}+ place={placeExact(s.callMs, s.approvalMs, g.t0, g.total)}/>)}{/* Whole-segment pulse while approval is pending / execution segment */}@@ -601,15 +635,16 @@ export function TimelineChart({legendKey === null || legendKey === "approvalWait",);return (- <span+ <TimelineBaronMouseEnter={() => enter(`p-${s.toolCallId}`, s.callTs)}onMouseLeave={leave}onClick={() => onJump?.(s.callTs)}- title={`${s.name} · ${S.traces.legendApprovalWait} · ${S.traces.inProgress}`}- className={`absolute inset-y-0 min-w-[2px] cursor-pointer ${COLORS.approvalWait} ${- dim || "animate-pulse"- }`}- style={placeExact(s.callMs, endMs, g.t0, g.total)}+ {...namedHint(+ `${s.name} · ${S.traces.legendApprovalWait} · ${S.traces.inProgress}`,+ )}+ className={`cursor-pointer ${dim || "animate-pulse"}`}+ paint={kindPaint("approvalWait")}+ place={placeExact(s.callMs, endMs, g.t0, g.total)}/>);})()@@ -621,19 +656,22 @@ export function TimelineChart({);const running = open && !dim;return (- <span+ <TimelineBaronMouseEnter={() => enter(`e-${s.toolCallId}`, execTs)}onMouseLeave={leave}onClick={() => onJump?.(execTs)}- title={`${s.name} · ${S.traces.legendToolExec} · ${- open- ? S.traces.inProgress- : humanizeDuration(endMs - execStart)- }${s.failed ? ` · ${s.status}` : ""}`}- className={`absolute inset-y-0 min-w-[2px] cursor-pointer ${COLORS.exec} ${+ {...namedHint(+ `${s.name} · ${S.traces.legendToolExec} · ${+ open+ ? S.traces.inProgress+ : humanizeDuration(endMs - execStart)+ }${s.failed ? ` · ${s.status}` : ""}`,+ )}+ className={`cursor-pointer ${s.failed ? "ring-1 ring-red-500" : ""} ${running ? "animate-pulse opacity-70" : dim}`}- style={placeExact(execStart, endMs, g.t0, g.total)}+ paint={kindPaint("exec")}+ place={placeExact(execStart, endMs, g.t0, g.total)}/>);})()}@@ -654,20 +692,24 @@ export function TimelineChart({<div key={o.key} className="flex items-center"><spanclassName={`${LABEL_STICKY} text-gray-500 dark:text-gray-400`}- title={o.name}+ data-tooltip={o.name}+ data-tooltip-content="text"><span className={LABEL_TEXT}>{o.name}</span></span><Track>- <span+ <TimelineBaronMouseEnter={() => enter(`o-${o.key}`, o.ts)}onMouseLeave={leave}onClick={() => onJump?.(o.ts)}- title={`${o.name} · ${S.traces.legendOther} · ${humanizeDuration(o.endMs - o.startMs)}`}- className={`absolute inset-y-0 min-w-[2px] cursor-pointer ${COLORS.other} ${+ {...namedHint(+ `${o.name} · ${S.traces.legendOther} · ${humanizeDuration(o.endMs - o.startMs)}`,+ )}+ className={`cursor-pointer ${o.failed ? "ring-1 ring-red-500" : ""} ${dim}`}- style={placeExact(o.startMs, o.endMs, g.t0, g.total)}+ paint={kindPaint("other")}+ place={placeExact(o.startMs, o.endMs, g.t0, g.total)}/></Track></div>@@ -694,7 +736,7 @@ export function TimelineChart({legendKey !== null && legendKey !== c.key ? "opacity-30" : ""}`}>- <span className={`inline-block h-2 w-3 rounded-sm ${c.className}`} />+ <ChartSwatch paint={kindPaint(c.key)} shape="chip" />{c.label}</button>))}@@ -706,7 +748,7 @@ export function TimelineChart({<buttontype="button"aria-label={S.traces.zoomOut}- title={S.traces.zoomOut}+ data-tooltip={S.traces.zoomOut}onClick={() => zoomStep(1 / 1.4)}className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800">@@ -715,7 +757,7 @@ export function TimelineChart({<divref={trackRef}onDoubleClick={resetZoom}- title={S.traces.zoomReset}+ data-tooltip={S.traces.zoomReset}className="relative h-3 min-w-0 flex-1 rounded bg-gray-100 dark:bg-gray-800"><div@@ -738,7 +780,7 @@ export function TimelineChart({<buttontype="button"aria-label={S.traces.zoomIn}- title={S.traces.zoomIn}+ data-tooltip={S.traces.zoomIn}onClick={() => zoomStep(1.4)}className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800">diff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsxindex d2698218..f3f0cc11 100644--- a/packages/web/src/features/traces/trace-file-view.tsx+++ b/packages/web/src/features/traces/trace-file-view.tsx@@ -124,7 +124,7 @@ function SummaryRow({ label, value, detail }: { label: string; value: string; deconst hasDetail = detail !== undefined && detail !== "";return (<div- title={hasDetail ? `${label}${detail}` : undefined}+ data-tooltip={hasDetail ? `${label}${detail}` : undefined}className="flex items-baseline justify-between gap-3 py-0.5"><span className="shrink-0 text-[11px] text-gray-400">{label}</span>@@ -147,7 +147,7 @@ const CHIP_CLASS =/** Icon + value; hover shows what this item is (plain text alone doesn't convey the meaning). */function StatChip({ icon, value, label }: { icon: string; value: string; label: string }) {return (- <span title={label} aria-label={label} className={`${CHIP_CLASS} gap-1`}>+ <span data-tooltip={label} aria-label={label} className={`${CHIP_CLASS} gap-1`}><GlyphIcon d={icon} className="text-gray-400" />{value}</span>@@ -171,11 +171,11 @@ function InputChip({ buckets }: { buckets: Buckets }) {aria-label={`${S.traces.taskInput} ${humanizeTokens(input)} · ${hitTitle}`}className={CHIP_CLASS}>- <span title={S.traces.taskInput} className="flex items-center gap-1">+ <span data-tooltip={S.traces.taskInput} className="flex items-center gap-1"><GlyphIcon d={STAT_ICONS.input} className="text-gray-400" />{humanizeTokens(input)}</span>- <span title={hitTitle} className="ml-1 flex items-center gap-0.5 text-gray-400">+ <span data-tooltip={hitTitle} className="ml-1 flex items-center gap-0.5 text-gray-400"><span>(</span><GlyphIcon d={STAT_ICONS.cacheHit} /><span>{humanizeTokens(buckets.cacheRead)}</span>diff --git a/packages/web/src/features/traces/trace-panel.tsx b/packages/web/src/features/traces/trace-panel.tsxindex 48540f69..97dd3274 100644--- a/packages/web/src/features/traces/trace-panel.tsx+++ b/packages/web/src/features/traces/trace-panel.tsx@@ -23,7 +23,6 @@ import { DownloadIcon } from "../../components/ui/icons";import { EmptyState } from "../../components/ui/empty-state";import { Skeleton } from "../../components/ui/skeleton";import { ICON_SIZE } from "../../lib/icon-scale";-import { toneStrip } from "../../lib/tone";import { TraceFileView } from "./trace-file-view";import {activeTraceFile,@@ -32,6 +31,7 @@ import {sortTraceFiles,} from "./trace-refresh";import type { TraceHighlight } from "./timeline-chart";+import { NoticeStrip } from "../../components/ui/notice-strip";/** File pills rendered before the "+N" overflow control expands them (a long Session can hold dozens of compaction shards). */const FILE_PILL_CAP = 6;@@ -142,9 +142,9 @@ export function TracePanel({{/* A re-list that failed keeps everything below it and says so here; the listing onscreen is the last one that arrived, so it may be a turn or two behind. */}{error !== null && (- <p className={`rounded-md border px-2.5 py-1.5 text-xs ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" as="p" className="rounded-md border px-2.5 py-1.5 text-xs">{S.tracePanel.loadFailed} · {error}- </p>+ </NoticeStrip>)}<div className="flex flex-wrap items-center gap-1.5"><span className="mr-1 text-xs text-gray-400">{S.traces.filesTitle}</span>@@ -153,7 +153,7 @@ export function TracePanel({key={f.index}type="button"onClick={() => setFileIndex(f.index)}- title={`${f.date} · ${formatBytes(f.sizeBytes)}`}+ data-tooltip={`${f.date} · ${formatBytes(f.sizeBytes)}`}className={`rounded-md border px-2 py-0.5 font-mono text-xs transition-colors duration-150 ${f.index === activeFile.index? "border-gray-400 bg-gray-200/70 font-semibold text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"@@ -166,7 +166,7 @@ export function TracePanel({{!showAllFiles && files.length > FILE_PILL_CAP && (<buttontype="button"- title={S.chat.loadMore}+ data-tooltip={S.chat.loadMore}aria-label={S.chat.loadMore}onClick={() => setShowAllFiles(true)}className="rounded-md border border-gray-200 px-2 py-0.5 font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"diff --git a/packages/web/src/features/usage/chart-geom.ts b/packages/web/src/features/usage/chart-geom.tsindex 9641a55f..8f29cf08 100644--- a/packages/web/src/features/usage/chart-geom.ts+++ b/packages/web/src/features/usage/chart-geom.ts@@ -3,14 +3,12 @@* JSX, easy to unit test (see test/usage-charts.test.ts). The time-series* charts (the requests + success-rate combo, the Token bar's three-segment* stack, the cost line) share one coordinate system — canvas width, padding,- * the x()/y() mapping, SVG paths, x-axis label indices. Bars fit the- * container (fitBarWidth — no horizontal scrolling), per-segment geometry- * (including per-segment hit bands) is produced by barSegments, and every line- * on the page — cost, cache hit rate, success rate — is drawn by linePath as- * straight segments between its points, with no smoothing anywhere; there's- * also hover-bubble placement (pointer- * lower-right, flipping at the edges). See chart-svg.tsx for the render- * skeleton.+ * the x()/y() mapping, series points, x-axis label indices. Per-segment+ * geometry (including per-segment hit bands) is produced by barSegments;+ * there's also hover-bubble placement (pointer lower-right, flipping at the+ * edges). How a bar fills its band and how a line runs between its points is+ * the theme's, and lives with the chart primitives (components/ui/chart/geom.ts).+ * See chart-svg.tsx for the render skeleton.** **Canvas width = the container's measured pixel width (1 canvas unit = 1* CSS pixel)**: the SVG no longer stretches/scales via a fixed viewBox —@@ -19,6 +17,7 @@* ~495px, a 0.77 factor), while requirements like "at least 25px wide" must* land on **real display pixels**. So the canvas width is supplied by the caller after measuring the container.*/+import { roundCoord as rnd } from "../../components/ui/chart/geom";/** Canvas height and padding (carried over from the original TrendChart constants; width is now measured from the container, see the file header). */export const CHART_H = 200;@@ -91,28 +90,11 @@ export function makeRangeGeom(};}-/** Line path: `M x0,y0 L x1,y1 …` (identical to the original TrendChart's cost line). */-export function linePath(geom: ChartGeom, values: number[]): string {- return values.map((v, i) => `${i === 0 ? "M" : "L"}${geom.x(i)},${geom.y(v)}`).join(" ");+/** A series' points in the plot's coordinates: bucket i at its cell's centre, value v at its height. */+export function seriesPoints(geom: ChartGeom, values: readonly number[]): Array<[number, number]> {+ return values.map((v, i) => [geom.x(i), geom.y(v)]);}-/** Area path: the line drops vertically to the baseline (y=0) at the end, then closes back along the baseline to the start; used by the cost line's fill layer. */-export function areaPath(geom: ChartGeom, values: number[]): string {- const n = values.length;- if (n === 0) return "";- const baseY = geom.y(0);- const parts: string[] = [];- for (let i = 0; i < n; i++)- parts.push(`${i === 0 ? "M" : "L"}${geom.x(i)},${geom.y(values[i]!)}`);- parts.push(`L${geom.x(n - 1)},${baseY}`);- parts.push(`L${geom.x(0)},${baseY}`);- parts.push("Z");- return parts.join(" ");-}--/** Path coordinates keep 2 decimal places: the path string stays short and readable, and is easy to assert on in unit tests. */-const rnd = (v: number): number => Math.round(v * 100) / 100;-/** A point of a line on an x axis several series share: the slot it sits in, and its value. */export interface LinePoint {index: number;@@ -120,6 +102,14 @@ export interface LinePoint {}/** Straight-line path through the given points in order (`M` + `L`s), whatever slots lie between them; a single point yields a bare `M` that strokes nothing, so callers draw its dot instead. */+/** A sparse series' points in the plot's coordinates, rounded like segmentPath's. */+export function segmentPoints(+ geom: ChartGeom,+ segment: readonly LinePoint[],+): Array<[number, number]> {+ return segment.map((p) => [rnd(geom.x(p.index)), rnd(geom.y(p.value))]);+}+export function segmentPath(geom: ChartGeom, segment: readonly LinePoint[]): string {return segment.map((p, i) => `${i === 0 ? "M" : "L"}${rnd(geom.x(p.index))},${rnd(geom.y(p.value))}`)@@ -193,13 +183,6 @@ export function bubblePosition(// —— Daily Token: bar + three-segment stack ——-/**- * Ceiling on bar width (**real CSS pixels**, since 1 canvas unit = 1 pixel):- * with few points the bars never balloon past this — the extra space goes to- * bar spacing.- */-export const BAR_W = 25;-/*** Minimum height of the per-segment hover hit band (canvas units = pixels,* innerH=168): in real data, output is often under 1% of the day's total@@ -212,17 +195,6 @@ export const BAR_W = 25;*/export const MIN_HIT_H = 8;-/**- * Bar width that always fits the container (**no horizontal scrolling**): 60%- * of the cell width — leaving ≥ 40% as spacing so adjacent bars never touch —- * capped at BAR_W (few points must not balloon into slabs) and floored at 1px:- * a dense range at fine granularity degrades to hairlines, not to overlap- * (only a degenerate sub-1.7px cell can make the 1px floor fill its cell).- */-export function fitBarWidth(step: number): number {- return Math.max(1, Math.min(BAR_W, Math.floor(step * 0.6)));-}-/** One segment within a stacked bar: the visual rectangle is drawn strictly to value, the hit band is computed separately (small segments are raised to be hoverable). */export interface StackSegment {/** Position in the values array the segment came from (zero values produce no segment, so this is not the segment's own index). */diff --git a/packages/web/src/features/usage/chart-svg.tsx b/packages/web/src/features/usage/chart-svg.tsxindex 1b297968..147053ef 100644--- a/packages/web/src/features/usage/chart-svg.tsx+++ b/packages/web/src/features/usage/chart-svg.tsx@@ -45,18 +45,23 @@ import {sparseLabelIdx,type ChartGeom,} from "./chart-geom";+import {+ ChartAxis,+ ChartAxisBreak,+ ChartCursor,+ ChartGrid,+ ChartHit,+} from "../../components/ui/chart";/** Height (CSS px) of the invisible band laid over a line series so it can be hovered: a 2px stroke is too thin to aim at. */export const LINE_HIT_H = 10;-/**- * Stroke width of every data line on the page — the cost line, the- * success-rate lines, the cache-hit-rate curve. One weight for all of them,- * so no line reads as more important than another just because it was written- * later. Chrome (grid lines, the hover indicator, axis-break marks) stays at- * 1 and is deliberately not this.+/*+ * Every data line on the page — the cost line, the success-rate lines, the cache-hit-rate+ * curve — is drawn at the theme's one line width (useChartStyle), so no line reads as more+ * important than another just because it was written later. Chrome (grid lines, the hover+ * indicator, axis-break marks) stays at 1 and is deliberately not that width.*/-export const DATA_STROKE_W = 2;/** Cell width (CSS px) below which axis-break marks are dropped: any narrower and successive marks sit closer together than they are wide, smearing into a hatched baseline. */const AXIS_BREAK_MIN_STEP = 8;@@ -84,14 +89,13 @@ export function LineHits({onLeave?: () => void;}) {return values.map((v, i) => (- <rect+ <ChartHitkey={i}x={geom.x(i) - geom.step / 2}y={geom.y(v) - LINE_HIT_H / 2}width={geom.step}height={LINE_HIT_H}- fill="transparent"- className="cursor-pointer"+ cursor="pointer"onMouseEnter={() => onEnter(i)}onMouseLeave={onLeave}/>@@ -232,7 +236,9 @@ export function ChartFrame({viewBox={`0 0 ${w} ${CHART_H}`}width={w}height={CHART_H}- className="text-gray-600 dark:text-gray-400"+ // ui-chart: a theme may redraw the parts, which carry data-part — the grid, the axis+ // labels and breaks here, the series, areas, bars and points in the caller's marks.+ className="ui-chart text-gray-600 dark:text-gray-400"role="img"onMouseLeave={() => {onHover(null);@@ -248,50 +254,23 @@ export function ChartFrame({{/* Grid lines and y-axis ticks (recessive gray) */}{gridLevels.map((v, i) => (<g key={i}>- <line- x1={PAD_L}- x2={w - geom.padR}- y1={y(v)}- y2={y(v)}- className="stroke-gray-200 dark:stroke-gray-800"- strokeWidth={1}- />- <text- x={PAD_L - 6}- y={y(v) + 3}- textAnchor="end"- className="fill-gray-400 dark:fill-gray-500"- fontSize={9}- >+ <ChartGrid x1={PAD_L} x2={w - geom.padR} y={y(v)} />+ <ChartAxis x={PAD_L - 6} y={y(v) + 3} anchor="end">{fmtY(v)}- </text>+ </ChartAxis></g>))}{/* Right-hand axis ticks (an overlay's own scale, e.g. a percentage) */}{rightAxis?.ticks.map((v) => (- <text- key={`r${v}`}- x={w - geom.padR + 6}- y={rightAxis.y(v) + 3}- textAnchor="start"- className="fill-gray-400 dark:fill-gray-500"- fontSize={9}- >+ <ChartAxis key={`r${v}`} x={w - geom.padR + 6} y={rightAxis.y(v) + 3} anchor="start">{rightAxis.fmt(v)}- </text>+ </ChartAxis>))}{/* Hover vertical indicator line (line-chart-only: the bar chart's bar itself is the x indicator, see hoverLine) */}{hoverLine && hover !== null && dates[hover] && (- <line- x1={x(hover)}- x2={x(hover)}- y1={PAD_T}- y2={PAD_T + innerH}- className="stroke-gray-300 dark:stroke-gray-700"- strokeWidth={1}- />+ <ChartCursor x={x(hover)} y1={PAD_T} y2={PAD_T + innerH} />)}{/* Data marks (provided by the caller) */}@@ -304,24 +283,7 @@ export function ChartFrame({{step >= AXIS_BREAK_MIN_STEP &&axisBreaks?.map((i) =>i + 1 < geom.n ? (- <g- key={`break-${i}`}- className="pointer-events-none stroke-gray-400 dark:stroke-gray-500"- strokeWidth={1}- >- {[-2, 2].map((dx) => {- const cx = (x(i) + x(i + 1)) / 2 + dx / 2;- return (- <line- key={dx}- x1={cx - 2}- y1={PAD_T + innerH + 3}- x2={cx + 2}- y2={PAD_T + innerH - 3}- />- );- })}- </g>+ <ChartAxisBreak key={`break-${i}`} x={(x(i) + x(i + 1)) / 2} y={PAD_T + innerH} />) : null,)}@@ -330,30 +292,21 @@ export function ChartFrame({const d = dates[i];if (!d) return null;return (- <text- key={i}- x={x(i)}- y={CHART_H - 6}- textAnchor="middle"- className="fill-gray-400 dark:fill-gray-500"- fontSize={9}- >+ <ChartAxis key={i} x={x(i)} y={CHART_H - 6} anchor="middle">{(fmtX ?? ((v: string) => v.slice(5)))(d)}- </text>+ </ChartAxis>);})}{/* Hover hit area (larger than the mark itself): whole column by default, the bar chart swaps in hitLayer for per-segment */}{hitLayer ??dates.map((_, i) => (- <rect+ <ChartHitkey={`hit-${i}`}x={PAD_L + step * i}y={PAD_T}width={step}height={innerH}- fill="transparent"- className="cursor-crosshair"onMouseEnter={() => onHover(i)}/>))}diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsxindex bcd8e9fa..43843b30 100644--- a/packages/web/src/features/usage/errors-panel.tsx+++ b/packages/web/src/features/usage/errors-panel.tsx@@ -319,7 +319,8 @@ export function ErrorsPanel({{/* One line by default; click to expand to the full message (wrapping), click again to collapse. */}<buttontype="button"- title={e.message}+ data-tooltip={e.message}+ data-tooltip-content="text"onClick={() => toggle(i)}className={`block w-full cursor-pointer text-left transition-colors hover:text-gray-700 dark:hover:text-gray-300 ${expanded.has(i) ? "whitespace-pre-wrap break-words" : "truncate"diff --git a/packages/web/src/features/usage/trend-chart.tsx b/packages/web/src/features/usage/trend-chart.tsxindex 08766b10..e1a1b2b9 100644--- a/packages/web/src/features/usage/trend-chart.tsx+++ b/packages/web/src/features/usage/trend-chart.tsx@@ -21,11 +21,18 @@ import { useState } from "react";import type { UsageGranularity, UsageSeriesPoint } from "@prismshadow/penguin-server/api";import { formatMoney } from "../../lib/format";import type { Currency } from "../../state/theme";-import { makeGeom, linePath, areaPath } from "./chart-geom";-import { ChartFrame, DATA_STROKE_W, useChartWidth } from "./chart-svg";+import { makeGeom, seriesPoints } from "./chart-geom";+import { ChartFrame, useChartWidth } from "./chart-svg";+import { ChartArea, ChartLine, ChartPoint, type ChartPaint } from "../../components/ui/chart";import { bucketAxisLabel, bucketFullLabel } from "./usage-controls";import { Empty } from "./usage-charts";+/**+ * The cost line's paint: the chart's own ink (the frame's text colour) — one series with no+ * identity to tell apart, so it takes no palette slot.+ */+const COST_PAINT: ChartPaint = { ink: "" };+/** Cell width (CSS pixels) below which per-point dots stop being drawn: 2.5px radius plus breathing room. */const MIN_DOT_STEP = 8;@@ -56,6 +63,7 @@ export function TrendChart({// (61 minute buckets in a half-width card sit ~7px apart). Below that the// line stands alone and only the hovered point gets its dot.const everyDot = geom.step >= MIN_DOT_STEP;+ const points = seriesPoints(geom, cost);return (<div ref={ref}>@@ -80,36 +88,31 @@ export function TrendChart({><g>{/* Area fill: the line closes down to the baseline, low opacity reinforces the trend's sense of "volume" */}- <path- d={areaPath(geom, cost)}- className="fill-current"- stroke="none"- opacity={hover !== null ? 0.06 : 0.1}- />- <path- d={linePath(geom, cost)}- fill="none"- stroke="currentColor"- strokeWidth={DATA_STROKE_W}- opacity={hover !== null ? 0.35 : 1}+ <ChartArea+ points={points}+ baseY={geom.y(0)}+ paint={COST_PAINT}+ // Dimmed while a point is singled out.+ strength={hover !== null ? 0.6 : 1}/>+ <ChartLine points={points} paint={COST_PAINT} opacity={hover !== null ? 0.35 : 1} />{everyDot &&series.map((p, i) => (- <circle+ <ChartPointkey={p.bucket}cx={geom.x(i)}cy={geom.y(cost[i] ?? 0)}- r={hover === i ? 4 : 2.5}- className="fill-current"+ paint={COST_PAINT}+ grow={hover === i}opacity={hover !== null && hover !== i ? 0.25 : 1}/>))}{!everyDot && hover !== null && (- <circle+ <ChartPointcx={geom.x(hover)}cy={geom.y(cost[hover] ?? 0)}- r={4}- className="fill-current"+ paint={COST_PAINT}+ grow/>)}</g>diff --git a/packages/web/src/features/usage/usage-charts.tsx b/packages/web/src/features/usage/usage-charts.tsxindex 603f3743..dbd9d3ed 100644--- a/packages/web/src/features/usage/usage-charts.tsx+++ b/packages/web/src/features/usage/usage-charts.tsx@@ -24,8 +24,9 @@* its place in that column — as a zero and a dash, not as a missing bucket.* `breaks` marks where the axis skipped an interval.*- * Every data line is drawn at DATA_STROKE_W, and a bucket with no rate to- * show is drawn at NO_RATE_PLOT so the stroke stays continuous. Neither is a+ * Every data line is drawn at the theme's line width (the chart primitives), and a+ * bucket with no rate to show is drawn at NO_RATE_PLOT so the stroke stays+ * continuous. Neither is a* claim about the data: the hover table prints a dash there.** Unified highlight interaction (a site-wide convention): highlight = fade@@ -39,20 +40,27 @@ import { useState } from "react";import type { UsageGranularity, UsageSeriesPoint } from "@prismshadow/penguin-server/api";import { S } from "../../lib/strings";import { formatPercent, humanizeTokens } from "../../lib/format";-import { TOKEN_COLORS } from "../../lib/token-colors";-import { NEUTRAL_SERIES, seriesColor, type SeriesColor } from "../../lib/category-colors";+import { NEUTRAL_SERIES } from "../../lib/category-colors";+import {+ ChartBar,+ ChartBarHit,+ ChartHit,+ ChartLine,+ ChartPoint,+ ChartSwatch,+ type ChartPaint,+} from "../../components/ui/chart";import {makeGeom,makeRangeGeom,autoLabelIdx,barSegments,- fitBarWidth,- linePath,+ seriesPoints,stackSegments,PAD_R_AXIS,type TokenBucketKey,} from "./chart-geom";-import { ChartFrame, DATA_STROKE_W, LineHits, useChartWidth } from "./chart-svg";+import { ChartFrame, LineHits, useChartWidth } from "./chart-svg";import {bucketAxisLabel,bucketFullLabel,@@ -93,11 +101,14 @@ function rateCell(v: number | null | undefined): string {return formatPercent(v == null ? null : v / 100);}-/** Text/swatch classes for the i-th drawn entity (the folded tail wears the neutral). */-function entityColor(s: EntitySeries, i: number): SeriesColor {- return s.other ? NEUTRAL_SERIES : seriesColor(i);+/** The i-th drawn entity's paint: palette slot i, or the neutral for the folded tail. */+function entityPaint(s: EntitySeries, i: number): ChartPaint {+ return s.other ? { ink: NEUTRAL_SERIES.text, swatch: NEUTRAL_SERIES.swatch } : { series: i };}+/** The neutral a line-shaped legend item wears when it names what the lines are, not whose. */+const NEUTRAL_PAINT: ChartPaint = { ink: NEUTRAL_SERIES.text, swatch: NEUTRAL_SERIES.swatch };+// —— Requests + success rate, broken down by entity ——/**@@ -140,15 +151,13 @@ function RequestsLegend({active != null && active !== i ? "opacity-30" : ""}`}>- <span- className={`inline-block h-2 w-2 shrink-0 rounded-[2px] ${entityColor(e, i).swatch}`}- />+ <ChartSwatch paint={entityPaint(e, i)} /><span className="max-w-40 truncate font-mono">{e.label}</span></button>))}{/* The lines wear each entity's own hue, so their legend item is about shape, not color: a neutral dash saying "the lines are the success rate, on the right axis". */}<span className="flex items-center gap-1.5">- <span className={`inline-block h-0.5 w-3 shrink-0 rounded-sm ${NEUTRAL_SERIES.swatch}`} />+ <ChartSwatch paint={NEUTRAL_PAINT} shape="dash" />{S.usage.legendSuccessRate}</span></div>@@ -209,7 +218,6 @@ export function RequestsChart({const lines = rates.map(plotRates);const geom = makeGeom(series.length, niceCountMax(...totals.requests), width, PAD_R_AXIS);const rateGeom = makeRangeGeom(series.length, 0, 100, width, PAD_R_AXIS);- const barW = fitBarWidth(geom.step);const buckets = series.map((p) => p.bucket);const segs = series.map((_, i) =>stackSegments(@@ -258,9 +266,7 @@ export function RequestsChart({mark?.entity === si ? "font-semibold" : ""}`}>- <span- className={`inline-block h-2 w-2 shrink-0 rounded-[2px] ${entityColor(e, si).swatch}`}- />+ <ChartSwatch paint={entityPaint(e, si)} /><span className="max-w-32 truncate">{e.label}</span><span className="ml-auto min-w-8 pl-2 text-right tabular-nums">{e.requests[i] ?? 0}@@ -287,14 +293,12 @@ export function RequestsChart({hitLayer={[// Column hits first (underneath): anywhere in the column reports the bucket....series.map((_, i) => (- <rect+ <ChartHitkey={`col-${buckets[i]}`}x={geom.x(i) - geom.step / 2}y={0}width={geom.step}height={geom.y(0)}- fill="transparent"- className="cursor-crosshair"onMouseEnter={() => {setHover(i);setMark(null);@@ -305,14 +309,12 @@ export function RequestsChart({// overlap and a minimum height, so a one-request segment is still reachable....series.map((_, i) =>segs[i]!.map((seg) => (- <rect+ <ChartBarHitkey={`seg-${buckets[i]}-${seg.index}`}- x={geom.x(i) - barW / 2}+ cx={geom.x(i)}+ band={geom.step}y={seg.hitY}- width={barW}height={seg.hitH}- fill="transparent"- className="cursor-pointer"onMouseEnter={() => {setHover(i);setMark({ entity: seg.index, bucket: i });@@ -337,14 +339,16 @@ export function RequestsChart({{/* Stacked request bars, bottom-up in list order (1px seams would over-fragment thin bars, so segments sit flush). */}{series.map((_, i) =>segs[i]!.map((seg) => (- <rect+ <ChartBarkey={`${buckets[i]}-${seg.index}`}- x={geom.x(i) - barW / 2}+ cx={geom.x(i)}+ band={geom.step}y={seg.y}- width={barW}height={seg.h}- className={`${entityColor(drawn[seg.index]!, seg.index).text} transition-opacity duration-150`}- fill="currentColor"+ paint={entityPaint(drawn[seg.index]!, seg.index)}+ // Only the stack's top rounds: the segments below meet flush.+ top={seg.y === Math.min(...segs[i]!.map((s) => s.y))}+ className="transition-opacity duration-150"opacity={barOpacity(seg.index, i)}/>)),@@ -355,14 +359,12 @@ export function RequestsChart({belongs to the right-hand percentage axis rather than to the bars — and here thelines share their entity's bar color, so shape is the only separator left. */}{drawn.map((e, si) => (- <path+ <ChartLinekey={`rate-${e.label}:${si}`}- d={linePath(rateGeom, lines[si]!)}- fill="none"- stroke="currentColor"- strokeWidth={DATA_STROKE_W}- strokeDasharray="4 3"- className={`${entityColor(e, si).text} pointer-events-none transition-opacity duration-150`}+ points={seriesPoints(rateGeom, lines[si]!)}+ paint={entityPaint(e, si)}+ dash="4 3"+ className="pointer-events-none transition-opacity duration-150"opacity={lineLit(si) ? 1 : 0.15}/>))}@@ -389,9 +391,11 @@ interface SegHover {key: TokenLegendKey | null;}-/** The hit-rate curve's color classes (amber — distinct from the bars' blue family, CVD-checked against sky in the series palette). */-const HIT_RATE_TEXT = "text-amber-500 dark:text-amber-600";-const HIT_RATE_SWATCH = "bg-amber-500 dark:bg-amber-600";+/** A Token kind's paint: the theme's colour for that kind. */+const tokenPaint = (key: TokenBucketKey): ChartPaint => ({ role: key });++/** The cache-hit-rate curve's paint: the theme's reference-line colour. */+const HIT_RATE_PAINT: ChartPaint = { role: "ref" };/*** Per-bucket Token buckets → a three-segment stacked bar (SVG, reusing the@@ -438,7 +442,6 @@ export function TokenBarChart({const max = Math.max(1, ...sums);const geom = makeGeom(series.length, max, width, PAD_R_AXIS);const rateGeom = makeRangeGeom(series.length, 0, 100, width, PAD_R_AXIS);- const barW = fitBarWidth(geom.step);const buckets = series.map((p) => p.bucket);const segs = series.map((p) => barSegments(geom, p));// As in the requests charts: `rates` keeps the nulls for the bubble, `line`@@ -486,22 +489,19 @@ export function TokenBarChart({bubble={(i) => {const p = series[i]!;const key = hover?.key ?? null;- const sq = (color: string) => (- <span- className="inline-block h-2 w-2 shrink-0 rounded-[2px]"- style={{ backgroundColor: color }}- />- );return (<><p className="text-gray-400">{bucketFullLabel(granularity, p.bucket)}</p>{(["cacheRead", "cacheWrite", "output"] as const).map((k) =>- bubbleRow(sq(TOKEN_COLORS[k]), bucketLabel(k), humanizeTokens(p[k]), key === k),+ bubbleRow(+ <ChartSwatch paint={tokenPaint(k)} />,+ bucketLabel(k),+ humanizeTokens(p[k]),+ key === k,+ ),)}{bubbleRow(- <span- className={`inline-block h-0.5 w-2 shrink-0 rounded-sm ${HIT_RATE_SWATCH}`}- />,+ <ChartSwatch paint={HIT_RATE_PAINT} shape="tick" />,S.usage.legendHitRate,rateCell(rates[i]),key === "hitRate",@@ -513,14 +513,12 @@ export function TokenBarChart({// Column-level hits first (underneath): anywhere in the column — the empty// space and the curve included — reports the whole bucket's bubble....series.map((p, i) => (- <rect+ <ChartHitkey={`col-${p.bucket}`}x={geom.x(i) - geom.step / 2}y={0}width={geom.step}height={geom.y(0)}- fill="transparent"- className="cursor-crosshair"onMouseEnter={() => setHover({ i, key: null })}/>)),@@ -530,14 +528,12 @@ export function TokenBarChart({// column hit underneath, so the bubble never flickers off inside the chart....series.map((p, i) =>segs[i]!.map((s) => (- <rect+ <ChartBarHitkey={`hit-${p.bucket}-${s.key}`}- x={geom.x(i) - barW / 2}+ cx={geom.x(i)}+ band={geom.step}y={s.hitY}- width={barW}height={s.hitH}- fill="transparent"- className="cursor-pointer"onMouseEnter={() => setHover({ i, key: s.key })}onMouseLeave={() =>setHover((h) => (h?.i === i && h.key === s.key ? { i, key: null } : h))@@ -556,13 +552,14 @@ export function TokenBarChart({>{series.map((p, i) =>segs[i]!.map((s) => (- <rect+ <ChartBarkey={`${p.bucket}-${s.key}`}- x={geom.x(i) - barW / 2}+ cx={geom.x(i)}+ band={geom.step}y={s.y}- width={barW}height={s.h}- fill={TOKEN_COLORS[s.key]}+ paint={tokenPaint(s.key)}+ top={s.y === Math.min(...segs[i]!.map((t) => t.y))}className="transition-opacity duration-150"opacity={dimmed(i, s.key) ? 0.2 : 1}/>@@ -571,22 +568,15 @@ export function TokenBarChart({{/* Cache-hit-rate curve, dashed, in front of the bars on the right-hand 0–100% scale.pointer-events-none: the column/segment hit rects stay hoverable through it. */}<g- className={`${HIT_RATE_TEXT} pointer-events-none transition-opacity duration-150`}+ className="pointer-events-none transition-opacity duration-150"opacity={curveDim ? 0.3 : 1}>- <path- d={linePath(rateGeom, line)}- fill="none"- stroke="currentColor"- strokeWidth={DATA_STROKE_W}- strokeDasharray="5 4"- />+ <ChartLine points={seriesPoints(rateGeom, line)} paint={HIT_RATE_PAINT} dash="5 4" />{hover !== null && (- <circle+ <ChartPointcx={rateGeom.x(hover.i)}cy={rateGeom.y(line[hover.i] ?? 0)}- r={2.5}- className="fill-current"+ paint={HIT_RATE_PAINT}/>)}</g>@@ -620,10 +610,7 @@ export function TokenLegend({onMouseLeave={() => onHover?.(null)}className={`flex items-center gap-1 text-[10px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${dim(key)}`}>- <span- className="inline-block h-2 w-3 rounded-sm"- style={{ backgroundColor: TOKEN_COLORS[key] }}- />+ <ChartSwatch paint={tokenPaint(key)} shape="chip" />{label}</button>))}@@ -634,7 +621,7 @@ export function TokenLegend({onMouseLeave={() => onHover?.(null)}className={`flex items-center gap-1 text-[10px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${dim("hitRate")}`}>- <span className={`inline-block h-0.5 w-3 rounded-sm ${HIT_RATE_SWATCH}`} />+ <ChartSwatch paint={HIT_RATE_PAINT} shape="dash" />{S.usage.legendHitRate}</button></div>diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsxindex 56a90944..e30e83a3 100644--- a/packages/web/src/features/usage/usage-page.tsx+++ b/packages/web/src/features/usage/usage-page.tsx@@ -282,7 +282,7 @@ export function UsagePage() {<div className="mx-auto max-w-5xl space-y-4">{/* Top filters: controls have no external title (the explanation is written into the "all …" option), so they're baseline-centered with the page title */}<div className="flex flex-wrap items-center justify-between gap-3">- <h1 className="text-xl font-semibold">{S.usage.title}</h1>+ <h1 className="ui-display text-xl font-semibold">{S.usage.title}</h1><div className="flex flex-wrap items-center gap-2"><div className="w-32"><Selectdiff --git a/packages/web/src/features/workflows/workflow-tabs.tsx b/packages/web/src/features/workflows/workflow-tabs.tsxindex d56f1dc0..4a4786c1 100644--- a/packages/web/src/features/workflows/workflow-tabs.tsx+++ b/packages/web/src/features/workflows/workflow-tabs.tsx@@ -16,7 +16,7 @@ import { Button } from "../../components/ui/button";import { formatDateTime } from "../../lib/format";import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";import { S } from "../../lib/strings";-import { toneInk, toneStrip } from "../../lib/tone";+import { toneInk } from "../../lib/tone";import { forwardFrameKeys, readDocumentTheme, themeWorkflowFrame } from "../../lib/workflow-theme";import {FILL_APP_MESSAGE,@@ -33,6 +33,7 @@ import {import { useLocale } from "../../state/locale";import { useTheme } from "../../state/theme";import { localizedText } from "../chat/skill-use";+import { NoticeStrip } from "../../components/ui/notice-strip";/** The Agent's workflow tabs, kept fresh by the server's `workflow_updated` events. */export function useWorkflowTabs(@@ -94,7 +95,7 @@ export function useWorkflowTabs(const FRAME_REVEAL_TIMEOUT_MS = 4000;const TAB_BASE =- "relative h-9 shrink-0 border-b-2 px-3 text-[13px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400";+ "relative h-9 shrink-0 border-b-2 px-3 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400";const TAB_ACTIVE = "border-[var(--accent-bg)] font-medium text-gray-900 dark:text-gray-100";const TAB_IDLE ="border-transparent text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200";@@ -116,16 +117,16 @@ export function WorkflowTabStrip({return (<>{notices.map((n) => (- <div+ <NoticeStripkey={n.workflowId}+ tone={n.error === null ? "muted" : "attention"}role="status"- className={`shrink-0 truncate px-3 py-1 text-xs ${- n.error === null ? toneStrip.muted : toneStrip.attention- }`}- title={n.error ?? n.hints.join("\n")}+ className="shrink-0 truncate px-3 py-1 text-xs"+ data-tooltip={n.error ?? n.hints.join("\n")}+ data-tooltip-content="text"><span className="font-mono">{n.workflowId}</span>: {n.error ?? n.hints[0]}- </div>+ </NoticeStrip>))}{tabs.length > 0 && (<div@@ -148,7 +149,7 @@ export function WorkflowTabStrip({type="button"role="tab"aria-selected={active === t.tabId}- title={t.error ?? undefined}+ data-tooltip={t.error ?? undefined}className={`${TAB_BASE} ${active === t.tabId ? TAB_ACTIVE : TAB_IDLE}`}onClick={() => onSelect(t.tabId)}>@@ -184,7 +185,7 @@ export function WorkflowFrame({/** The workflow and its versions are gone; the caller drops the tab (the list refetch confirms). */onRemoved: () => void;}) {- const { dark, accent, fontScale } = useTheme();+ const { dark, themeId, accent, textSize, fontLatin, fontCjk } = useTheme();const frameRef = useRef<HTMLIFrameElement | null>(null);const [busy, setBusy] = useState<"reload" | "rollback" | "remove" | null>(null);// Removal is armed by a first click and sent by the second; the arm drops when the tab changes.@@ -237,8 +238,8 @@ export function WorkflowFrame({}};- // The page is a separate document: the app's dark class, accent and root font size stop at- // the frame, so they are copied in (lib/workflow-theme.ts) on load and on every appearance+ // The page is a separate document: the app's dark class, theme, accent, fonts and root font+ // size stop at the frame, so they are copied in (lib/workflow-theme.ts) on load and on every appearance// change. Past the commit, because the provider that stamps them on the app's own document// is an ancestor and its effect runs after this one's.const applyTheme = useCallback(() => {@@ -247,7 +248,7 @@ export function WorkflowFrame({useEffect(() => {const id = requestAnimationFrame(applyTheme);return () => cancelAnimationFrame(id);- }, [applyTheme, dark, accent, fontScale, tab.uiRev]);+ }, [applyTheme, dark, themeId, accent, textSize, fontLatin, fontCjk, tab.uiRev]);// A page is its own document: until it has loaded and been themed it paints the browser's// white canvas, and then its own unstyled markup — a white flash in a dark app, on every@@ -371,12 +372,14 @@ export function WorkflowFrame({)}</div>{tab.error !== null && !bare && (- <div className={`shrink-0 px-3 py-1.5 text-xs ${toneStrip.danger}`}>+ <NoticeStrip tone="danger" className="shrink-0 px-3 py-1.5 text-xs">{S.workflows.loadError}: {tab.error}- </div>+ </NoticeStrip>)}{failure !== null && (- <div className={`shrink-0 px-3 py-1.5 text-xs ${toneStrip.danger}`}>{failure}</div>+ <NoticeStrip tone="danger" className="shrink-0 px-3 py-1.5 text-xs">+ {failure}+ </NoticeStrip>)}<divid={historyId}diff --git a/packages/web/src/lib/chart-style.ts b/packages/web/src/lib/chart-style.tsnew file mode 100644index 00000000..c7d3ed63--- /dev/null+++ b/packages/web/src/lib/chart-style.ts@@ -0,0 +1,179 @@+/**+ * How the active theme draws charts: the `--ui-chart-*` tokens, read off the root's computed+ * style, for the parts CSS cannot reach from outside an SVG's geometry — a bar's width and+ * corner radius, a line's width and curve, a point's radius, the fill under a line — and the+ * series palette those marks paint with.+ *+ * Only the chart primitives (components/ui/chart) read it: every chart draws its marks through+ * them, so a token turns into geometry and colour in one place. Components never ask which+ * theme is active. It is read once per+ * theme change, not per render: one MutationObserver on <html> (the attributes the theme+ * provider and the boot script write — class for the mode, data-theme, data-accent, and the+ * root font size in `style`) drops the cached record, and every chart subscribed through+ * `useChartStyle` re-renders with the new one.+ *+ * Slots are identities, fixed across themes: 1 violet, 2 amber, 3 sky, 4 rose, 5 emerald,+ * 6 fuchsia, 7 and 8 spare — each theme picks its own shade of each. A chart's series take the+ * slots in order; the Trace timeline maps its kinds onto slots 1, 3, 2, 4, 5.+ */+import { useSyncExternalStore } from "react";++export type ChartCurve = "linear" | "smooth" | "step";++export interface ChartStyle {+ /** The categorical palette, slots 1–8 in order. */+ series: readonly string[];+ /** Reference lines drawn over a chart's own series (the cache-hit-rate curve). */+ ref: string;+ /** The token kinds' own colours (the stacked Token bars and the context donut). */+ cacheRead: string;+ cacheWrite: string;+ output: string;+ /** The share of its band a bar takes, 0–1. */+ barFill: number;+ /** A bar's top corner radius, px. */+ barRadius: number;+ /** A bar's outline width, px (0 = no outline). */+ barStroke: number;+ /** The outline's colour, or "series" for the bar's own colour. */+ barStrokeColor: string;+ /** A bar's fill opacity, 0–1. */+ barOpacity: number;+ /** A series line's stroke width, px. */+ lineWidth: number;+ /** A data point's radius, px. */+ pointRadius: number;+ curve: ChartCurve;+ /** The fill under a line series, 0–1. */+ areaOpacity: number;+}++/**+ * What the charts draw with when no theme has answered (a document without the theme sheet,+ * server rendering in tests): the default theme's values, which are today's charts.+ */+export const DEFAULT_CHART_STYLE: ChartStyle = {+ series: ["#8b5cf6", "#f59e0b", "#0ea5e9", "#f43f5e", "#10b981", "#d946ef", "#64748b", "#14b8a6"],+ ref: "#f59e0b",+ cacheRead: "#7dd3fc",+ cacheWrite: "#0ea5e9",+ output: "#0369a1",+ barFill: 0.6,+ barRadius: 0,+ barStroke: 0,+ barStrokeColor: "series",+ barOpacity: 1,+ lineWidth: 2,+ pointRadius: 2.5,+ curve: "linear",+ areaOpacity: 0.1,+};++/** A number token, or the fallback when it is missing or not a number. */+function numberOf(raw: string, fallback: number): number {+ const value = Number.parseFloat(raw);+ return Number.isFinite(value) ? value : fallback;+}++/** A colour token, or the fallback when it is missing. */+function colourOf(raw: string, fallback: string): string {+ return raw.trim() === "" ? fallback : raw.trim();+}++/**+ * The record, from a reader of custom properties (`getPropertyValue` on the root's computed+ * style). Every value falls back to the default theme's on its own, so a theme that has not+ * defined a token yet draws the way the app always has.+ */+export function readChartStyle(read: (name: string) => string): ChartStyle {+ const d = DEFAULT_CHART_STYLE;+ const curve = read("--ui-chart-curve").trim();+ return {+ series: d.series.map((fallback, i) => colourOf(read(`--ui-chart-${i + 1}`), fallback)),+ ref: colourOf(read("--ui-chart-ref"), d.ref),+ cacheRead: colourOf(read("--ui-chart-cache-read"), d.cacheRead),+ cacheWrite: colourOf(read("--ui-chart-cache-write"), d.cacheWrite),+ output: colourOf(read("--ui-chart-output"), d.output),+ barFill: Math.min(1, Math.max(0.05, numberOf(read("--ui-chart-bar-fill"), d.barFill))),+ barRadius: Math.max(0, numberOf(read("--ui-chart-bar-radius"), d.barRadius)),+ barStroke: Math.max(0, numberOf(read("--ui-chart-bar-stroke"), d.barStroke)),+ barStrokeColor: colourOf(read("--ui-chart-bar-stroke-color"), d.barStrokeColor),+ barOpacity: Math.min(1, Math.max(0, numberOf(read("--ui-chart-bar-opacity"), d.barOpacity))),+ lineWidth: Math.max(0.5, numberOf(read("--ui-chart-line-width"), d.lineWidth)),+ pointRadius: Math.max(0, numberOf(read("--ui-chart-point-radius"), d.pointRadius)),+ curve: curve === "smooth" || curve === "step" ? curve : "linear",+ areaOpacity: Math.min(1, Math.max(0, numberOf(read("--ui-chart-area-opacity"), d.areaOpacity))),+ };+}++/** Series colour `i`, cycling through the palette. */+export function seriesStroke(style: ChartStyle, i: number): string {+ return style.series[i % style.series.length]!;+}++/** Whether two records draw the same charts: every value equal, the palette slot by slot. */+export function sameChartStyle(a: ChartStyle, b: ChartStyle): boolean {+ for (const key of Object.keys(a) as Array<keyof ChartStyle>) {+ if (key === "series") continue;+ if (a[key] !== b[key]) return false;+ }+ return a.series.length === b.series.length && a.series.every((c, i) => c === b.series[i]);+}++/**+ * The next record to hand out: `previous` itself when nothing a chart draws with changed, so+ * a subscriber sees the same object and React re-renders nothing. <html> changes for many+ * reasons that are not the theme (the root font size, a frame writing its height, a class a+ * library toggles); a new object on each of those would re-render every chart, and a chart+ * whose render changes <html> again would never settle.+ */+export function nextChartStyle(previous: ChartStyle | null, read: ChartStyle): ChartStyle {+ return previous !== null && sameChartStyle(previous, read) ? previous : read;+}++let cached: ChartStyle | null = null;+const listeners = new Set<() => void>();+let observer: MutationObserver | null = null;++/** Reads the root's tokens. Reading never writes: no state, no attribute, no style. */+function readRoot(): ChartStyle {+ const computed = getComputedStyle(document.documentElement);+ return readChartStyle((name) => computed.getPropertyValue(name));+}++function snapshot(): ChartStyle {+ if (cached === null) cached = readRoot();+ return cached;+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ if (observer === null) {+ // No one watched <html> while there were no charts: catch up once, keeping the same+ // object when nothing changed in the meantime.+ if (cached !== null) cached = nextChartStyle(cached, readRoot());+ observer = new MutationObserver(() => {+ const next = nextChartStyle(cached, readRoot());+ // Only a real change reaches the charts.+ if (next === cached) return;+ cached = next;+ for (const l of listeners) l();+ });+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class", "data-theme", "data-accent", "style"],+ });+ }+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) {+ observer?.disconnect();+ observer = null;+ }+ };+}++/** The active theme's chart style; charts re-render when the theme, mode or accent changes. */+export function useChartStyle(): ChartStyle {+ return useSyncExternalStore(subscribe, snapshot, () => DEFAULT_CHART_STYLE);+}diff --git a/packages/web/src/lib/icon-scale.ts b/packages/web/src/lib/icon-scale.tsindex 548ef97c..f1bbef03 100644--- a/packages/web/src/lib/icon-scale.ts+++ b/packages/web/src/lib/icon-scale.ts@@ -1,8 +1,9 @@/*** Icon sizes and icon-to-text gaps, named by the role the mark plays rather than by a number.*- * Every line icon in the app is drawn on a 24x24 grid at `strokeWidth` 1.7 and rendered through- * `components/ui/glyph-icon.tsx`, so the only thing a call site chooses is how big the box is —+ * Every line icon in the app is drawn on a 24x24 grid and rendered through+ * `components/ui/glyph-icon.tsx` at the theme's stroke weight (`--ui-icon-stroke`, 1.7 in the+ * default theme), so the only thing a call site chooses is how big the box is —* and structurally equivalent places must choose the same. Picking a rung by role is what keeps* two list rows, or two menu rows, from drifting a pixel apart.*diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.tsindex 2fa6656d..363bc3d9 100644--- a/packages/web/src/lib/install-scope.ts+++ b/packages/web/src/lib/install-scope.ts@@ -95,11 +95,35 @@ export const KEY_RULES: readonly KeyRule[] = [scope: "browser",why: "Colour-scheme choice for this browser; names nothing on the server.",},+ {+ kind: "exact",+ key: "penguin.themeId",+ scope: "browser",+ why: "Which theme renders the app (the key lives in @prismshadow/penguin-ui/boot); pure appearance.",+ },+ {+ kind: "exact",+ key: "penguin.textSize",+ scope: "browser",+ why: "Root text size (five steps) — a readability preference of this display.",+ },{kind: "exact",key: "penguin.fontScale",scope: "browser",- why: "Root font size — a readability preference of this display.",+ why: "The three-step text size of earlier releases; read once, migrated to penguin.textSize and removed.",+ },+ {+ kind: "exact",+ key: "penguin.fontLatin",+ scope: "browser",+ why: "Latin font face chosen over the theme's own; pure appearance.",+ },+ {+ kind: "exact",+ key: "penguin.fontCjk",+ scope: "browser",+ why: "CJK font face chosen over the theme's own; pure appearance.",},{kind: "exact",diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.tsindex 56025a7d..6d5c4bf0 100644--- a/packages/web/src/lib/settings-sections.ts+++ b/packages/web/src/lib/settings-sections.ts@@ -3,7 +3,8 @@** Server-global pages write through /api/admin/settings (or the admin user routes) and* belong to admins alone; the personal pages are per-user preferences every signed-in user- * owns. Two pages additionally depend on how this session runs: the account page only+ * owns (the credits page is one of them, open to everyone). Two pages additionally depend on+ * how this session runs: the account page only* exists where a password can be changed (see offersChangePassword), and user management* disappears in desktop mode, where the app is single-user. The profile page is neither — an* avatar and a nickname are display data, so every signed-in session may set them. Updating@@ -30,6 +31,7 @@ export type SettingsSectionKey =| "appearance"| "shortcuts"| "account"+ | "credits"| "proxy"| "uploads"| "company"@@ -66,6 +68,9 @@ const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsV// The desktop shell's own window has no password to change; a password-established// session against the same server still does. Same predicate as the old menu row.{ key: "account", group: "personal", visible: (v) => offersChangePassword(v) },+ // The bundled fonts and their licences. Every session, the desktop shell's own window+ // included: MiSans's licence asks the app to credit it wherever it runs.+ { key: "credits", group: "personal", visible: () => true },{ key: "proxy", group: "server", visible: (v) => v.isAdmin },{ key: "uploads", group: "server", visible: (v) => v.isAdmin },// The company-mode master switch: server-global like the proxy and upload limits.diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 2252d81a..f0c6934d 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -361,6 +361,13 @@ export const en: Strings = {languageInfo: "Interface language; can follow the browser.",/** Sidebar user-menu row opening the Settings dialog, and that dialog's title. */title: "Settings",+ /** The account menu's footer line: the credit MiSans's licence requires of software that ships the font. */+ creditsTitle: "Credits",+ creditsThemes: "Used by",+ creditsNoTheme: "Not a theme's default",+ creditsLicense: "License",+ creditsSource: "Source",+ creditsLicenseText: "Full license text",/** Rail headings: the viewer's own preferences vs. the whole server's. */groupPersonal: "Personal",groupServer: "Server",@@ -447,7 +454,11 @@ export const en: Strings = {`inline image enters the conversation and the Trace, where its size is paid again on ` +`every history page and resume.`,theme: "Theme",- themeInfo: "Light or dark look of the app.",+ themeInfo:+ "The app's overall style: layout, lines, type and motion change with it; content and every other setting stay as they are.",+ themeNames: { github: "Primer", modern: "Frost", geek: "Console" },+ colorMode: "Mode",+ colorModeInfo: "Light or dark look of the app.",themeLight: "Light",themeDark: "Dark",followSystem: "System",@@ -458,11 +469,17 @@ export const en: Strings = {langEn: "English",fontSize: "Font size",fontSizeInfo: "Overall interface font size.",- fontSmall: "S",- fontMedium: "M",- fontLarge: "L",+ textSizeNames: { xs: "XS", s: "S", m: "M", l: "L", xl: "XL" },+ fonts: "Fonts",+ fontsInfo:+ "The face for Latin text and the face for CJK text, each following the theme by default. Code and other monospaced text always keep the theme's monospaced face.",+ fontLatin: "Latin",+ fontCjk: "CJK",+ fontFollowTheme: "Theme's own",+ fontSystem: "System font",accent: "Accent",- accentInfo: "Interface accent color.",+ accentInfo:+ "Interface accent color. Each theme offers its own set; after a theme change, a color the new theme does not offer shows as the theme's own until you return.",launcher: "Shortcuts launcher",launcherInfo:"The round button floating on the conversation's right edge that fans out shortcuts to the workbench's panels and the terminal. Turning it off here removes it; the fan's \"Hide launcher\" entry does the same.",@@ -491,12 +508,23 @@ export const en: Strings = {companyModeServerInfo:"The server-wide master switch, off until an admin turns it on here. Off stops the organization scheduler and every organization route and hides the mode switch for everyone. Organizations on disk are untouched, and turning it back on backfills no missed trigger. Beta: it may be unstable; please report what you hit.",accentNames: {- neutral: "Neutral",+ neutral: "Theme's own",blue: "Blue",green: "Green",violet: "Violet",rose: "Rose",amber: "Amber",+ ocean: "Ocean",+ clay: "Clay",+ plum: "Plum",+ honey: "Honey",+ slate: "Slate",+ phosphor: "Phosphor",+ cyan: "Cyan",+ magenta: "Magenta",+ gold: "Gold",+ cobalt: "Cobalt",+ orange: "Orange",} as Record<string, string>,},diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex acff92e7..a7e3bbc9 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -427,6 +427,13 @@ export const zh = {languageInfo: "界面语言,可跟随浏览器设置。",/** Sidebar user-menu row opening the Settings dialog, and that dialog's title. */title: "设置",+ /** The account menu's footer line: the credit MiSans's licence requires of software that ships the font. */+ creditsTitle: "版权信息",+ creditsThemes: "用于",+ creditsNoTheme: "没有主题默认使用",+ creditsLicense: "许可",+ creditsSource: "来源",+ creditsLicenseText: "许可全文",/** Rail headings: the viewer's own preferences vs. the whole server's. */groupPersonal: "个人",groupServer: "服务器",@@ -507,7 +514,11 @@ export const zh = {`一条消息最多 ${count} 个附件;对话内嵌图片另有 ${imageMb}MB 上限,不随此设置变化——` +`图片会进入对话与轨迹,每次翻阅历史与恢复会话都要重新付出它的体积。`,theme: "主题",- themeInfo: "应用的明暗外观。",+ themeInfo: "应用的整体风格:布局、线条、字体与动效随之改变,内容与其他设置不受影响。",+ /** Display names of the three themes; the ids stay github / modern / geek. */+ themeNames: { github: "通用", modern: "白领", geek: "极客" },+ colorMode: "明暗",+ colorModeInfo: "应用的明暗外观。",themeLight: "浅色",themeDark: "深色",followSystem: "跟随系统",@@ -518,11 +529,16 @@ export const zh = {langEn: "English",fontSize: "字号",fontSizeInfo: "界面整体字号。",- fontSmall: "小",- fontMedium: "中",- fontLarge: "大",- accent: "主题色",- accentInfo: "界面强调色。",+ textSizeNames: { xs: "特小", s: "小", m: "中", l: "大", xl: "特大" },+ fonts: "字体",+ fontsInfo: "英文与中文各自的字体,默认随主题;代码与等宽文字始终使用主题的等宽字体。",+ fontLatin: "英文",+ fontCjk: "中文",+ fontFollowTheme: "随主题",+ fontSystem: "系统字体",+ accent: "强调色",+ accentInfo:+ "界面强调色。每个主题有自己的一组强调色,换主题后不在新主题里的颜色会暂时按「随主题」显示。",launcher: "快捷方式悬浮球",launcherInfo:"在对话正文右缘浮动的圆形按钮,展开后是工作台各块面板与终端的快捷方式;这里关掉后它就不再出现,展开里的「隐藏悬浮球」同样会关掉它。",@@ -551,12 +567,23 @@ export const zh = {companyModeServerInfo:"服务器总开关,缺省关闭,需由管理员在此打开。关闭即停用组织调度器与全部组织路由,并隐藏所有人的模式切换;磁盘上的组织不受影响,重新打开后不会补发错过的触发。内测功能:可能有不稳定的现象,遇到问题请反馈。",accentNames: {- neutral: "灰白",+ neutral: "随主题",blue: "蓝",green: "绿",violet: "紫",rose: "红",amber: "橙",+ ocean: "海蓝",+ clay: "陶土",+ plum: "梅紫",+ honey: "蜂蜜",+ slate: "石板灰",+ phosphor: "荧光绿",+ cyan: "青",+ magenta: "品红",+ gold: "金",+ cobalt: "钴蓝",+ orange: "橙红",} as Record<string, string>,},diff --git a/packages/web/src/lib/tone.ts b/packages/web/src/lib/tone.tsindex e3d9cb49..5cfefcf0 100644--- a/packages/web/src/lib/tone.ts+++ b/packages/web/src/lib/tone.ts@@ -41,9 +41,9 @@ export type Tone = "busy" | "attention" | "success" | "link" | "danger" | "muted/*** Ink for a glyph or a line of status text. Measured as WCAG 2.x contrast ratios against the* four surfaces these marks actually sit on — white and gray-50 in light (chat surfaces and the- * sidebar), and the neutral scale this app overrides in `styles.css` for dark: gray-950 `#000000`- * and gray-900 `#0d0d0d`. The lower number of each pair is the sidebar, which is the worse case- * in both themes:+ * sidebar), and the neutral scale the default theme overrides for dark (`@prismshadow/penguin-ui`+ * `themes/github.css`): gray-950 `#000000` and gray-900 `#0d0d0d`. The lower number of each pair+ * is the sidebar, which is the worse case in both themes:** - `busy` / `success` emerald-600 / emerald-400 …… 3.65–3.50 : 1 light, 10.83–10.03 : 1 dark* - `link` blue-600 / blue-400 …………… 5.17–4.95 : 1 light, 8.26–7.69 : 1 dark@@ -108,7 +108,8 @@ export const toneStrip: Record<Tone, string> = {"border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-300",success:"border-emerald-300 bg-emerald-50 text-emerald-800 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300",- link: "border-blue-300 bg-blue-50 text-blue-800 dark:border-blue-700 dark:bg-blue-950/40 dark:text-blue-300",+ // A filled tone box takes the neutral line: the tint alone says which tone it is.+ link: "border-gray-200 bg-blue-50 text-blue-800 dark:border-gray-800 dark:bg-blue-950/40 dark:text-blue-300",danger:"border-red-300 bg-red-50 text-red-800 dark:border-red-700 dark:bg-red-950/40 dark:text-red-300",muted:diff --git a/packages/web/src/pages/login.tsx b/packages/web/src/pages/login.tsxindex 0f3eb201..2eaaaee5 100644--- a/packages/web/src/pages/login.tsx+++ b/packages/web/src/pages/login.tsx@@ -101,7 +101,7 @@ export function LoginPage() {<div aria-label={S.settings.language}><Segmented options={langOptions} value={lang} onChange={setLang} /></div>- <div aria-label={S.settings.theme}>+ <div aria-label={S.settings.colorMode}><Segmented options={themeOptions} value={mode} onChange={setMode} /></div></div>diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsxindex 9d451a1b..30cf9aaf 100644--- a/packages/web/src/router.tsx+++ b/packages/web/src/router.tsx@@ -2,8 +2,13 @@* Router (react-router v7 declarative style): /login is public; all other routes go through* the RequireAuth guard (redirects to /login when not authenticated) and are wrapped in* ProjectProvider + AppLayout.+ *+ * The app normally routes on the browser's address bar. A host that mounts it inside another+ * document (the component gallery frames it against a mocked API) passes `initialPath`+ * instead: the router then runs in memory from that path, so the app navigates without+ * touching the host document's URL — the only seam the app needs to be mounted elsewhere.*/-import { BrowserRouter, Navigate, Route, Routes } from "react-router";+import { BrowserRouter, MemoryRouter, Navigate, Route, Routes } from "react-router";import { useAuth } from "./state/auth";import { ProjectProvider } from "./state/project";import { SessionsProvider } from "./state/sessions";@@ -95,25 +100,22 @@ function LoginRoute() {return <LoginPage />;}-export function AppRouter() {- return (- <BrowserRouter>- <Routes>- <Route path="/login" element={<LoginRoute />} />- <Route- path="/terminal"- element={- <RequireAuthBare>- <TerminalPage />- </RequireAuthBare>- }- />- {/* One workflow's page as the whole app: outside the shell, like the terminal; the- command palette it mounts is the way back. */}- {[- "/app/:projectId/:agentId/:workflowId",- "/app/:projectId/:agentId/:workflowId/:tabKey",- ].map((appPath) => (+export function AppRouter({ initialPath }: { initialPath?: string } = {}) {+ const routes = (+ <Routes>+ <Route path="/login" element={<LoginRoute />} />+ <Route+ path="/terminal"+ element={+ <RequireAuthBare>+ <TerminalPage />+ </RequireAuthBare>+ }+ />+ {/* One workflow's page as the whole app: outside the shell, like the terminal; the+ command palette it mounts is the way back. */}+ {["/app/:projectId/:agentId/:workflowId", "/app/:projectId/:agentId/:workflowId/:tabKey"].map(+ (appPath) => (<Routekey={appPath}path={appPath}@@ -123,36 +125,41 @@ export function AppRouter() {</RequireAuthBare>}/>+ ),+ )}+ <Route element={<RequireAuth />}>+ <Route index element={<Navigate to="/chat" replace />} />+ {/* Every page is a module.json entry (lib/pages.ts). Admin-only ones are refused+ server-side (403); the sidebar hides their row, so a member only ever reaches+ one by typing the URL. */}+ {PAGES.map((page) => (+ <Route key={page.id} path={page.path} element={renderPage(page)} />))}- <Route element={<RequireAuth />}>- <Route index element={<Navigate to="/chat" replace />} />- {/* Every page is a module.json entry (lib/pages.ts). Admin-only ones are refused- server-side (403); the sidebar hides their row, so a member only ever reaches- one by typing the URL. */}- {PAGES.map((page) => (- <Route key={page.id} path={page.path} element={renderPage(page)} />- ))}- {/* Company mode: /org resolves to an organization (or the empty landing), and an- organization opens on its overview — the page that says what the whole- organization is doing; its channels are the sidebar's own list beside it. Both- fall back to /chat while company mode is unavailable (see OrgLayout). */}- <Route path="/org" element={<OrgIndexRedirect />} />- <Route path="/org/:projectId/:orgId" element={<OrgLayout />}>- <Route index element={<Navigate to="overview" replace />} />- <Route path="overview" element={<OverviewPage />} />- <Route path="chart" element={<OrgChartPage />} />- <Route path="calendar" element={<CalendarPage />} />- <Route path="tickets" element={<TicketsPage />} />- <Route path="finance" element={<FinancePage />} />- <Route path="handbook" element={<HandbookPage />} />- <Route path="channels/:channelId" element={<ChannelView />} />- <Route path="*" element={<Navigate to="overview" replace />} />- </Route>- {/* Settings and user management live in the settings dialog now (see- SettingsDialog); their old routes fall through to the catch-all. */}- <Route path="*" element={<Navigate to="/chat" replace />} />+ {/* Company mode: /org resolves to an organization (or the empty landing), and an+ organization opens on its overview — the page that says what the whole+ organization is doing; its channels are the sidebar's own list beside it. Both+ fall back to /chat while company mode is unavailable (see OrgLayout). */}+ <Route path="/org" element={<OrgIndexRedirect />} />+ <Route path="/org/:projectId/:orgId" element={<OrgLayout />}>+ <Route index element={<Navigate to="overview" replace />} />+ <Route path="overview" element={<OverviewPage />} />+ <Route path="chart" element={<OrgChartPage />} />+ <Route path="calendar" element={<CalendarPage />} />+ <Route path="tickets" element={<TicketsPage />} />+ <Route path="finance" element={<FinancePage />} />+ <Route path="handbook" element={<HandbookPage />} />+ <Route path="channels/:channelId" element={<ChannelView />} />+ <Route path="*" element={<Navigate to="overview" replace />} /></Route>- </Routes>- </BrowserRouter>+ {/* Settings and user management live in the settings dialog now (see+ SettingsDialog); their old routes fall through to the catch-all. */}+ <Route path="*" element={<Navigate to="/chat" replace />} />+ </Route>+ </Routes>+ );+ return initialPath === undefined ? (+ <BrowserRouter>{routes}</BrowserRouter>+ ) : (+ <MemoryRouter initialEntries={[initialPath]}>{routes}</MemoryRouter>);}diff --git a/packages/web/src/state/theme-prefs.ts b/packages/web/src/state/theme-prefs.tsnew file mode 100644index 00000000..8fd0e236--- /dev/null+++ b/packages/web/src/state/theme-prefs.ts@@ -0,0 +1,96 @@+/**+ * The appearance preferences as stored values: reading them back from `localStorage` with the+ * same validation the pre-paint boot script applies, and the attribute set they put on <html>.+ *+ * Pure on purpose — no React, no `window` — so the one place that decides what a stored value+ * means is testable against an in-memory store, and the provider (theme.tsx) only holds state.+ * Every key and every value list comes from the shared UI package, which also owns the boot+ * script: the first frame and the running app then cannot disagree about a stored value.+ */+import {+ ACCENT_PRESET_IDS,+ DEFAULT_THEME_ID,+ THEME_IDS,+ resolveAccent,+} from "@prismshadow/penguin-ui";+import type { ThemeId } from "@prismshadow/penguin-ui";+import {+ FONT_CJK_OPTIONS,+ FONT_LATIN_OPTIONS,+ THEME_STORAGE_KEYS,+ readTextSize,+} from "@prismshadow/penguin-ui/boot";+import type {+ AccentChoice,+ FontCjk,+ FontLatin,+ TextSize,+ ThemeAttributes,+} from "@prismshadow/penguin-ui/boot";++export type { FontCjk, FontLatin, TextSize };++/** The storage a reader needs: `readTextSize` also writes, to retire the legacy key. */+export type PrefStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;++/** "Use the theme's own face" — stored like any other choice, applied as no attribute at all. */+export const FONT_FOLLOWS_THEME = "theme";++export function readThemeId(storage: PrefStorage): ThemeId {+ const stored = storage.getItem(THEME_STORAGE_KEYS.themeId);+ return THEME_IDS.find((id) => id === stored) ?? DEFAULT_THEME_ID;+}++/**+ * Any preset any theme lists is kept as stored: the theme files scope their presets to their own+ * root, so one the active theme does not list paints nothing (the theme's own accent shows) and+ * comes back when that theme is active again.+ */+export function readAccent(storage: PrefStorage): AccentChoice {+ const stored = storage.getItem(THEME_STORAGE_KEYS.accent);+ if (stored === "neutral") return stored;+ return ACCENT_PRESET_IDS.find((id) => id === stored) ?? "neutral";+}++/**+ * The accent a picker should mark under a theme: the stored preset when the theme lists it,+ * otherwise "neutral" — which is what the CSS paints in that case too.+ */+export function effectiveAccent(themeId: ThemeId, accent: AccentChoice): AccentChoice {+ return accent === "neutral" ? accent : (resolveAccent(themeId, accent) ?? "neutral");+}++export function readFontLatin(storage: PrefStorage): FontLatin {+ const stored = storage.getItem(THEME_STORAGE_KEYS.fontLatin);+ return (+ FONT_LATIN_OPTIONS.find((option) => option.id === stored)?.id ??+ (FONT_FOLLOWS_THEME as FontLatin)+ );+}++export function readFontCjk(storage: PrefStorage): FontCjk {+ const stored = storage.getItem(THEME_STORAGE_KEYS.fontCjk);+ return (+ FONT_CJK_OPTIONS.find((option) => option.id === stored)?.id ?? (FONT_FOLLOWS_THEME as FontCjk)+ );+}++/**+ * The stored preferences, which are exactly what they put on <html> — `applyThemeAttributes`+ * takes this object as it is. The mode is the one attribute not here: it is resolved against+ * the media query first.+ */+export type ThemePrefs = Omit<ThemeAttributes, "dark">;++export function readThemePrefs(storage: PrefStorage): ThemePrefs {+ return {+ themeId: readThemeId(storage),+ accent: readAccent(storage),+ // Migrates the three-step `penguin.fontScale` of earlier releases on the way: the package's+ // reader maps it by pixels (sm → m, md → l, lg → xl), writes the new key and drops the old+ // one, so this happens once per browser and every later read is a plain lookup.+ textSize: readTextSize(storage),+ fontLatin: readFontLatin(storage),+ fontCjk: readFontCjk(storage),+ };+}diff --git a/packages/web/src/state/theme.tsx b/packages/web/src/state/theme.tsxindex 04b70443..6b3c7347 100644--- a/packages/web/src/state/theme.tsx+++ b/packages/web/src/state/theme.tsx@@ -1,25 +1,41 @@/**- * Appearance context: light/dark theme (mode = light / dark / system) + font- * size + theme color (accent).- * - Theme: html.dark class + Tailwind dark: variant; system mode tracks prefers-color-scheme- * live. Dark mode defaults to pure black (styles.css overrides the neutral gray scale).- * - Font size: scales the root font-size (rem-based text-* utilities scale along with it).- * - Theme color: html[data-accent] overrides --accent-bg/--accent-fg; defaults to neutral- * (gray/white, follows light/dark).+ * Appearance context: light/dark mode (light / dark / system), theme, text size, font pairing+ * and accent.+ * - Mode: html.dark class + Tailwind dark: variant; system mode tracks prefers-color-scheme+ * live.+ * - Theme: html[data-theme] selects one of the shared UI package's themes (absent = the+ * default, Primer). Offered in Settings → Appearance.+ * - Text size: five steps that set the root font-size, so every rem-based type and density+ * token scales with it.+ * - Font pairing: html[data-font-latin] / [data-font-cjk] override the reading and interface+ * sans (Latin) and the CJK face; absent = the theme's own. The theme's mono face is untouched.+ * - Accent: html[data-accent] overrides the theme's accent tokens; "neutral" (no attribute) is+ * the theme's own accent. Each theme lists its own presets, and a stored preset the active+ * theme does not list paints nothing until a theme that lists it is active again.* - Tool short names: whether a tool-call card names the built-in tools by a short alias* instead of the name the model calls them by. Display-only, default on.* - Terminal theme: its own light/dark/follow-the-app setting, following the app unless* explicitly pinned — see TerminalThemeMode. It drives no class or variable here; the* terminal reads `terminalDark` and paints itself, because Tailwind's dark: variant is* anchored on html.dark and cannot express a light subtree inside a dark app.- * All preferences persist to localStorage.+ * All preferences persist to localStorage. Reading them back, with validation and the legacy+ * text-size migration, lives in theme-prefs.ts.+ * The pre-paint script in index.html (the package's BOOT_SCRIPT) applies mode, theme, accent,+ * text size and font pairing before the first frame; the effects here keep them in sync+ * afterwards, through the same applyThemeAttributes the package defines.*/import { createContext, useCallback, useContext, useEffect, useState } from "react";import type { ReactNode } from "react";+import { ACCENT_PRESETS, THEME_OWN_ACCENTS } from "@prismshadow/penguin-ui";+import type { ThemeId } from "@prismshadow/penguin-ui";+import { applyThemeAttributes, THEME_STORAGE_KEYS } from "@prismshadow/penguin-ui/boot";+import type { AccentChoice } from "@prismshadow/penguin-ui/boot";+import { readThemePrefs } from "./theme-prefs";+import type { FontCjk, FontLatin, TextSize } from "./theme-prefs";+export type { FontCjk, FontLatin, TextSize, ThemeId };export type ThemeMode = "light" | "dark" | "system";-export type FontScale = "sm" | "md" | "lg";-export type Accent = "neutral" | "blue" | "green" | "violet" | "rose" | "amber";+export type Accent = AccentChoice;/*** The terminal's appearance. By default it follows the app ("app"): switching the app* between light and dark carries the terminal along. Pinning "light" or "dark" decouples@@ -33,23 +49,33 @@ export type Currency = "USD" | "CNY";/** 1 USD ≈ 7 CNY (fixed conversion rate). */export const USD_TO_CNY = 7;-const MODE_KEY = "penguin.theme";-const FONT_KEY = "penguin.fontScale";-const ACCENT_KEY = "penguin.accent";+const MODE_KEY = THEME_STORAGE_KEYS.mode;+const THEME_ID_KEY = THEME_STORAGE_KEYS.themeId;+const TEXT_SIZE_KEY = THEME_STORAGE_KEYS.textSize;+const FONT_LATIN_KEY = THEME_STORAGE_KEYS.fontLatin;+const FONT_CJK_KEY = THEME_STORAGE_KEYS.fontCjk;+const ACCENT_KEY = THEME_STORAGE_KEYS.accent;const CURRENCY_KEY = "penguin.currency";const TERMINAL_KEY = "penguin.terminal.theme";const TOOL_ALIASES_KEY = "penguin.toolAliases";-/** Font size tier → root font-size (px): overall slightly larger than the system default for readability. */-const FONT_PX: Record<FontScale, string> = { sm: "16px", md: "18px", lg: "20px" };-interface ThemeContextValue {mode: ThemeMode;/** Resolved effective theme (system mode already resolved against the system preference). */dark: boolean;setMode: (mode: ThemeMode) => void;- fontScale: FontScale;- setFontScale: (scale: FontScale) => void;+ /** Which theme renders the app. */+ themeId: ThemeId;+ setThemeId: (themeId: ThemeId) => void;+ textSize: TextSize;+ setTextSize: (size: TextSize) => void;+ /** The Latin sans the theme's own is replaced with ("theme" = keep the theme's). */+ fontLatin: FontLatin;+ setFontLatin: (font: FontLatin) => void;+ /** The CJK face the theme's own is replaced with ("theme" = keep the theme's). */+ fontCjk: FontCjk;+ setFontCjk: (font: FontCjk) => void;+ /** The stored choice, which may name a preset the active theme does not list (see effectiveAccent). */accent: Accent;setAccent: (accent: Accent) => void;/** Display currency for prices (shared by Cost Center and Model Library; always stored as USD). */@@ -72,27 +98,6 @@ function initialMode(): ThemeMode {return "system";}-function initialFontScale(): FontScale {- const stored = localStorage.getItem(FONT_KEY);- if (stored === "sm" || stored === "md" || stored === "lg") return stored;- return "md";-}--function initialAccent(): Accent {- const stored = localStorage.getItem(ACCENT_KEY);- if (- stored === "neutral" ||- stored === "blue" ||- stored === "green" ||- stored === "violet" ||- stored === "rose" ||- stored === "amber"- ) {- return stored;- }- return "neutral";-}-function initialTerminalMode(): TerminalThemeMode {const stored = localStorage.getItem(TERMINAL_KEY);if (stored === "light" || stored === "dark" || stored === "app") return stored;@@ -115,8 +120,13 @@ function systemDark(): boolean {export function ThemeProvider({ children }: { children: ReactNode }) {const [mode, setModeState] = useState<ThemeMode>(initialMode);const [sysDark, setSysDark] = useState(systemDark);- const [fontScale, setFontScaleState] = useState<FontScale>(initialFontScale);- const [accent, setAccentState] = useState<Accent>(initialAccent);+ // One read for the lot, which also migrates the legacy text-size key.+ const [initial] = useState(() => readThemePrefs(localStorage));+ const [themeId, setThemeIdState] = useState<ThemeId>(initial.themeId);+ const [textSize, setTextSizeState] = useState<TextSize>(initial.textSize);+ const [fontLatin, setFontLatinState] = useState<FontLatin>(initial.fontLatin);+ const [fontCjk, setFontCjkState] = useState<FontCjk>(initial.fontCjk);+ const [accent, setAccentState] = useState<Accent>(initial.accent);const [currency, setCurrencyState] = useState<Currency>(initialCurrency);const [terminalMode, setTerminalModeState] = useState<TerminalThemeMode>(initialTerminalMode);const [toolAliases, setToolAliasesState] = useState<boolean>(initialToolAliases);@@ -125,17 +135,26 @@ export function ThemeProvider({ children }: { children: ReactNode }) {const terminalDark = terminalMode === "app" ? dark : terminalMode === "dark";useEffect(() => {- document.documentElement.classList.toggle("dark", dark);+ applyThemeAttributes(document.documentElement, { dark });}, [dark]);useEffect(() => {- document.documentElement.style.fontSize = FONT_PX[fontScale];- }, [fontScale]);+ // The default theme sets no data-theme: its selectors match a bare <html>.+ applyThemeAttributes(document.documentElement, { themeId });+ }, [themeId]);++ useEffect(() => {+ applyThemeAttributes(document.documentElement, { textSize });+ }, [textSize]);++ useEffect(() => {+ // "theme" removes the attribute: the theme's own face applies.+ applyThemeAttributes(document.documentElement, { fontLatin, fontCjk });+ }, [fontLatin, fontCjk]);useEffect(() => {- // neutral relies on the CSS default (follows light/dark) and sets no data-accent.- if (accent === "neutral") delete document.documentElement.dataset.accent;- else document.documentElement.dataset.accent = accent;+ // neutral leaves the theme's own accent (follows light/dark) and sets no data-accent.+ applyThemeAttributes(document.documentElement, { accent });}, [accent]);// system mode: track system preference changes.@@ -153,9 +172,24 @@ export function ThemeProvider({ children }: { children: ReactNode }) {setModeState(next);}, []);- const setFontScale = useCallback((next: FontScale) => {- localStorage.setItem(FONT_KEY, next);- setFontScaleState(next);+ const setThemeId = useCallback((next: ThemeId) => {+ localStorage.setItem(THEME_ID_KEY, next);+ setThemeIdState(next);+ }, []);++ const setTextSize = useCallback((next: TextSize) => {+ localStorage.setItem(TEXT_SIZE_KEY, next);+ setTextSizeState(next);+ }, []);++ const setFontLatin = useCallback((next: FontLatin) => {+ localStorage.setItem(FONT_LATIN_KEY, next);+ setFontLatinState(next);+ }, []);++ const setFontCjk = useCallback((next: FontCjk) => {+ localStorage.setItem(FONT_CJK_KEY, next);+ setFontCjkState(next);}, []);const setAccent = useCallback((next: Accent) => {@@ -184,8 +218,14 @@ export function ThemeProvider({ children }: { children: ReactNode }) {mode,dark,setMode,- fontScale,- setFontScale,+ themeId,+ setThemeId,+ textSize,+ setTextSize,+ fontLatin,+ setFontLatin,+ fontCjk,+ setFontCjk,accent,setAccent,currency,@@ -208,12 +248,20 @@ export function useTheme(): ThemeContextValue {return ctx;}-/** Display swatches for theme color presets (neutral uses a neutral gray). */-export const ACCENT_SWATCHES: ReadonlyArray<{ value: Accent; color: string }> = [- { value: "neutral", color: "#6b7280" },- { value: "blue", color: "#2563eb" },- { value: "green", color: "#15803d" },- { value: "violet", color: "#7c3aed" },- { value: "rose", color: "#be123c" },- { value: "amber", color: "#b45309" },-];+/**+ * The accent swatches a theme offers: "neutral" first (the theme's own accent, painted as a+ * plain gray because it is the absence of a choice, not a hue), then the theme's own presets in+ * its own order, painted in their light values.+ */+export function accentSwatches(+ themeId: ThemeId,+ dark = false,+): ReadonlyArray<{ value: Accent; color: string }> {+ // "Theme's own" paints the accent that choice resolves to — Console's and Primer's are black+ // (white in dark), Frost's its green — rather than a stand-in grey.+ const own = THEME_OWN_ACCENTS[themeId];+ return [+ { value: "neutral", color: dark ? own.dark : own.light },+ ...ACCENT_PRESETS[themeId].map((preset) => ({ value: preset.id, color: preset.swatch })),+ ];+}diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex dba6936f..5babbf75 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -4,13 +4,27 @@* no glassmorphism/gradients; the login page background is a circuit-trace animation (.login-trace, see* login-circuit.tsx). Dark theme is toggled via the html.dark class.*+ * Theming comes from the shared UI package (@prismshadow/penguin-ui): `theme.css` declares the+ * `dark` variant, the cascade layers, the token → utility bridge and the base rules that read+ * tokens (body colours and fonts, focus ring, selection, scrollbars); each `themes/*.css` holds+ * one theme's values, including the gray bridge the palette classes below resolve through. This+ * file keeps what is the app's own: the brand scale, layout invariants, animations and the+ * unlayered content rules.+ ** Stacking-context convention (to avoid contexts masking each other): chrome (top bar/navigation) does not* create a stacking context; dropdown/user menus use z-40; modal and drawer overlays use z-50.*/@import "tailwindcss";+@import "@prismshadow/penguin-ui/theme.css";+@import "@prismshadow/penguin-ui/themes/github.css";+@import "@prismshadow/penguin-ui/themes/modern.css";+@import "@prismshadow/penguin-ui/themes/geek.css";+@import "@prismshadow/penguin-ui/fonts.css";-/* Dark theme toggled via the html.dark class (Tailwind 4 custom variant). */-@custom-variant dark (&:where(.dark, .dark *));+/* Tailwind scans the Vite root only: the package's components carry class strings too. The test+ helpers are excluded, so the class patterns they spell never enter the app's sheet. */+@source "../../ui/src";+@source not "../../ui/src/testing";/* Brand color scale (Google blue family): generates utility classes like bg-brand-600 / text-brand-300. */@theme {@@ -30,51 +44,10 @@@layer base {:root {- color-scheme: light;/* The body font stack, named because KaTeX borrows it: math has to fall back to the same CJK- faces as the prose around it (see .katex .cjk_fallback below), and two copies would drift. */- --font-app-sans:- ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei",- sans-serif;- /* Theme color (accent): used for primary buttons, focus rings, etc. Defaults to gray/white (neutral,- switches with light/dark); selecting a specific color via data-accent overrides it (consistent across- light/dark, white text). */- --accent-bg: #111827; /* neutral light = gray-900 */- --accent-fg: #ffffff;- }- .dark {- color-scheme: dark;- /* Dark mode uses a pure-black base tone (no indigo tint): overrides the neutral gray scale with- true-neutral values — gray-950 pure black as the body background, gray-900/800/700 as near-black- surfaces and borders. */- --color-gray-950: #000000;- --color-gray-900: #0d0d0d;- --color-gray-800: #1f1f1f;- --color-gray-700: #303030;- /* neutral accent dark = gray-100 (light background, dark text button). */- --accent-bg: #f3f4f6;- --accent-fg: #111827;- }- /* Theme color presets (consistent across light/dark, white text): selecting data-accent overrides the neutral default. */- :root[data-accent="blue"] {- --accent-bg: #2563eb;- --accent-fg: #ffffff;- }- :root[data-accent="green"] {- --accent-bg: #15803d; /* green-700: contrast with white text >= AA */- --accent-fg: #ffffff;- }- :root[data-accent="violet"] {- --accent-bg: #7c3aed;- --accent-fg: #ffffff;- }- :root[data-accent="rose"] {- --accent-bg: #be123c; /* rose-700: contrast with white text >= AA */- --accent-fg: #ffffff;- }- :root[data-accent="amber"] {- --accent-bg: #b45309; /* amber-700: contrast with white text >= AA */- --accent-fg: #ffffff;+ faces as the prose around it (see .katex .cjk_fallback below). An alias of the theme's+ token, so the two cannot drift. */+ --font-app-sans: var(--ui-font-sans);}html,body,@@ -104,23 +77,6 @@.overflow-y-scroll {position: relative;}- body {- @apply bg-white text-gray-900 antialiased dark:bg-gray-950 dark:text-gray-100;- font-family: var(--font-app-sans);- }- code,- pre,- kbd {- font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;- }- /* Keyboard accessibility: soft brand-colored outer ring (input controls use their own focus ring, not stacked). */- button:focus-visible,- a:focus-visible,- [role="tab"]:focus-visible,- summary:focus-visible {- outline: 3px solid rgb(107 114 128 / 0.4);- outline-offset: 2px;- }/* Consistent pointer cursor for clickable buttons: Tailwind 4 preflight reverted button to the browser'sdefault arrow cursor (v3 used pointer); disabled state keeps the default. Explicit cursor-* utilityclasses (e.g. cursor-zoom-in) take precedence. */@@ -128,20 +84,6 @@[role="button"]:not(:disabled) {cursor: pointer;}- ::selection {- background: rgb(0 0 0 / 0.1);- }- .dark ::selection {- background: rgb(255 255 255 / 0.18);- }- /* Thin scrollbar. */- * {- scrollbar-width: thin;- scrollbar-color: rgb(60 64 67 / 0.28) transparent;- }- .dark * {- scrollbar-color: rgb(232 234 237 / 0.2) transparent;- }/* Hide the native scrollbar (replaced with custom controls, e.g. zoom/pan sliders in trace viewing). */.no-scrollbar {scrollbar-width: none;diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.tsindex 018405d3..ee37d803 100644--- a/packages/web/test/account-menu.test.ts+++ b/packages/web/test/account-menu.test.ts@@ -186,4 +186,10 @@ describe("the account menu", () => {expect(source).not.toContain("ServerUpdateRow");expect(source).not.toContain("DesktopUpdateRow");});++ it("leaves the font credit to the Settings dialog's credits page", () => {+ // The MiSans credit moved to Settings → Credits, which every account can open; the menu+ // keeps no second copy of it.+ expect(source).not.toContain("fontCredit");+ });});diff --git a/packages/web/test/autofill.test.ts b/packages/web/test/autofill.test.tsindex 8f19887f..4c0ca911 100644--- a/packages/web/test/autofill.test.ts+++ b/packages/web/test/autofill.test.ts@@ -6,6 +6,7 @@*/import { describe, it, expect } from "vitest";import { autofillProps } from "../src/components/ui/input";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";const IGNORES = {"data-1p-ignore": "",@@ -14,6 +15,14 @@ const IGNORES = {"data-form-type": "other",};+describe("autofill sources", () => {+ it("scan every source root, and find the policy in one place", () => {+ const scan = scanSources();+ expectEveryRootScanned(scan);+ expectSingleHome(scan, "packages/web/src/components/ui/input.tsx");+ });+});+describe("autofillProps", () => {it("opts an undeclared field out, extension attributes included", () => {expect(autofillProps(undefined, false)).toEqual({ autoComplete: "off", ...IGNORES });diff --git a/packages/web/test/avatar.test.ts b/packages/web/test/avatar.test.tsindex 445b263c..918c016d 100644--- a/packages/web/test/avatar.test.ts+++ b/packages/web/test/avatar.test.ts@@ -113,7 +113,7 @@ const hexRgb = (s: string) =>[1, 3, 5].map((i) => parseInt(s.slice(i, i + 2), 16) / 255) as [number, number, number];// App surfaces the tile sits on: light = white / gray-50 rows / gray-100 hover;-// dark = the true-neutral overrides in styles.css (gray-900/800/700).+// dark = the default theme's true-neutral overrides (penguin-ui themes/github.css: gray-900/800/700).const LIGHT_SURFACES = ["#ffffff", "#f9fafb", "#f3f4f6"].map(hexRgb);const DARK_SURFACES = ["#0d0d0d", "#1f1f1f", "#303030"].map(hexRgb);diff --git a/packages/web/test/channel-markdown.test.ts b/packages/web/test/channel-markdown.test.tsindex 3c832d3d..55a69bd5 100644--- a/packages/web/test/channel-markdown.test.ts+++ b/packages/web/test/channel-markdown.test.ts@@ -59,14 +59,14 @@ describe("channel message Markdown", () => {describe("mentions inside a message body", () => {it("resolves an employee's name and keeps the raw token in the tooltip", () => {const html = render("@ceo 先看一下");- expect(html).toContain('title="@ceo"');+ expect(html).toContain('data-tooltip="@ceo"');expect(html).toContain("@Ada CEO");expect(html).not.toContain(zh.company.channels.mentionsYou);});it("marks a mention that addresses the reader", () => {const html = render("@user:alice 这条是给你的");- expect(html).toContain('title="@user:alice"');+ expect(html).toContain('data-tooltip="@user:alice"');expect(html).toContain(zh.company.channels.mentionsYou);});diff --git a/packages/web/test/chart-marks.test.ts b/packages/web/test/chart-marks.test.tsnew file mode 100644index 00000000..940f96fd--- /dev/null+++ b/packages/web/test/chart-marks.test.ts@@ -0,0 +1,133 @@+/**+ * The chart primitives (components/ui/chart): what each draws in the default theme — the+ * record the server snapshot of useChartStyle hands out, which is today's charts — and a guard+ * that every chart draws its marks through them.+ */+import { createElement, type ReactElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import {+ ChartArea,+ ChartBar,+ ChartLine,+ ChartPoint,+ ChartSwatch,+ TimelineBar,+} from "../src/components/ui/chart";+import { barPath } from "../src/components/ui/chart/marks";+import { DEFAULT_CHART_STYLE } from "../src/lib/chart-style";+import { scanSources, sourceFile } from "./helpers/roots";++// Each primitive has its own props; the helper only renders one, so it takes any component.+const render = (type: (props: any) => ReactElement | null, props: object) =>+ renderToStaticMarkup(createElement(type, props));++describe("the chart primitives, in the default theme", () => {+ it("draw a bar at the theme's share of its band, square, unoutlined, in its slot's colour", () => {+ const html = render(ChartBar, { cx: 50, band: 20, y: 10, height: 30, paint: { series: 1 } });+ expect(html).toContain("<rect");+ expect(html).toContain('width="12"');+ expect(html).toContain('x="44"');+ expect(html).toContain('data-part="bar"');+ expect(html).toContain('data-series="2"');+ expect(html).toContain(`color:${DEFAULT_CHART_STYLE.series[1]}`);+ expect(html).not.toContain("stroke");+ expect(html).not.toContain("fill-opacity");+ });++ it("round a bar's top corners only when a theme gives a radius, clamped to the bar", () => {+ expect(barPath(0, 0, 10, 20, 0)).toBeNull();+ expect(barPath(0, 0, 10, 20, 3)).toBe("M0,20 V3 A3,3 0 0 1 3,0 H7 A3,3 0 0 1 10,3 V20 Z");+ expect(barPath(0, 0, 4, 20, 9)).toContain("A2,2");+ });++ it("draw a line straight at the theme's width, and a point as a round rect", () => {+ const line = render(ChartLine, {+ points: [+ [0, 10],+ [10, 20],+ ],+ paint: { role: "ref" },+ dash: "4 3",+ });+ expect(line).toContain('d="M0,10 L10,20"');+ expect(line).toContain('stroke-width="2"');+ expect(line).toContain('stroke-dasharray="4 3"');+ expect(line).toContain('data-part="series"');+ const point = render(ChartPoint, { cx: 10, cy: 10, paint: { ink: "" }, grow: true });+ expect(point).toContain('rx="4"');+ expect(point).toContain('width="8"');+ expect(point).toContain('data-part="point"');+ });++ it("fill under a line at the theme's area opacity, scaled by strength", () => {+ const area = render(ChartArea, {+ points: [+ [0, 10],+ [10, 20],+ ],+ baseY: 30,+ paint: { ink: "text-emerald-600" },+ strength: 0.6,+ });+ expect(area).toContain('d="M0,10 L10,20 L10,30 L0,30 Z"');+ expect(area).toMatch(/opacity="0\.06/);+ expect(area).toContain("text-emerald-600");+ });++ it("place a timeline bar where the chart says, in its slot's colour", () => {+ const html = render(TimelineBar, {+ paint: { series: 0 },+ place: { left: "10%", width: "5%" },+ className: "cursor-pointer",+ });+ expect(html).toContain("left:10%");+ expect(html).toContain(`background-color:${DEFAULT_CHART_STYLE.series[0]}`);+ expect(html).toContain('data-part="bar"');+ expect(html).not.toContain("box-shadow");+ expect(html).not.toContain("border-radius");+ });++ it("paint a swatch the way its mark is painted", () => {+ expect(render(ChartSwatch, { paint: { role: "cacheRead" } })).toContain(+ `background-color:${DEFAULT_CHART_STYLE.cacheRead}`,+ );+ expect(+ render(ChartSwatch, { paint: { ink: "text-gray-400", swatch: "bg-gray-400" } }),+ ).toContain("bg-gray-400");+ });+});++describe("every chart", () => {+ const scan = scanSources();+ const CHARTS = [+ "features/usage/usage-charts.tsx",+ "features/usage/trend-chart.tsx",+ "features/usage/chart-svg.tsx",+ "components/ui/token-donut.tsx",+ "features/benchmark/score-sparkline.tsx",+ "features/agents/activity-sparkline.tsx",+ "features/traces/timeline-chart.tsx",+ "features/benchmark/benchmark-detail.tsx",+ ];++ it("draws its marks through the primitives, never with its own shapes, paint or geometry", () => {+ const found: string[] = [];+ for (const id of CHARTS) {+ const code = sourceFile(scan, `packages/web/src/${id}`).text.replace(+ /\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,+ "",+ );+ for (const pattern of [+ /<(?:rect|path|circle|line|polyline|polygon|ellipse|text)\b/,+ /\b(?:fill|stroke|strokeWidth|strokeDasharray|fillOpacity|strokeOpacity)=/,+ /backgroundColor/,+ /useChartStyle\(/,+ ]) {+ const hit = code.match(pattern);+ if (hit) found.push(`${id}: ${hit[0]}`);+ }+ }+ expect(found).toEqual([]);+ });+});diff --git a/packages/web/test/chart-style.test.ts b/packages/web/test/chart-style.test.tsnew file mode 100644index 00000000..c31d7e23--- /dev/null+++ b/packages/web/test/chart-style.test.ts@@ -0,0 +1,118 @@+/**+ * The charts' theme reading (lib/chart-style.ts) and the geometry it drives (chart/geom.ts):+ * tokens parse into the record with the default theme's values as the fallback for each one,+ * and the default values draw exactly what the charts drew before they read tokens.+ */+import { describe, expect, it } from "vitest";+import {+ DEFAULT_CHART_STYLE,+ nextChartStyle,+ readChartStyle,+ seriesStroke,+} from "../src/lib/chart-style";+import { makeGeom, seriesPoints } from "../src/features/usage/chart-geom";+import { curvePath, fitBarWidth } from "../src/components/ui/chart/geom";++const reader = (tokens: Record<string, string>) => (name: string) => tokens[name] ?? "";++describe("readChartStyle", () => {+ it("reads every token a theme defines", () => {+ const style = readChartStyle(+ reader({+ "--ui-chart-1": "oklch(60% 0.2 290)",+ "--ui-chart-ref": " #f59e0b ",+ "--ui-chart-bar-fill": "0.8",+ "--ui-chart-bar-radius": "3px",+ "--ui-chart-line-width": "1.5px",+ "--ui-chart-point-radius": "3px",+ "--ui-chart-curve": " smooth",+ "--ui-chart-area-opacity": "0.2",+ }),+ );+ expect(style.series[0]).toBe("oklch(60% 0.2 290)");+ expect(style.ref).toBe("#f59e0b");+ expect(style).toMatchObject({+ barFill: 0.8,+ barRadius: 3,+ lineWidth: 1.5,+ pointRadius: 3,+ curve: "smooth",+ areaOpacity: 0.2,+ });+ });++ it("falls back token by token to the default theme's values", () => {+ expect(readChartStyle(reader({}))).toEqual(DEFAULT_CHART_STYLE);+ const odd = readChartStyle(+ reader({ "--ui-chart-curve": "wiggly", "--ui-chart-bar-fill": "x" }),+ );+ expect(odd.curve).toBe("linear");+ expect(odd.barFill).toBe(DEFAULT_CHART_STYLE.barFill);+ });++ it("reads the bar outline and fill opacity, with 'series' meaning the bar's own colour", () => {+ expect(readChartStyle(reader({}))).toMatchObject({+ barStroke: 0,+ barStrokeColor: "series",+ barOpacity: 1,+ });+ expect(+ readChartStyle(+ reader({+ "--ui-chart-bar-stroke": "1px",+ "--ui-chart-bar-stroke-color": " oklch(40% 0.1 250) ",+ "--ui-chart-bar-opacity": "0.85",+ }),+ ),+ ).toMatchObject({ barStroke: 1, barStrokeColor: "oklch(40% 0.1 250)", barOpacity: 0.85 });+ });++ it("hands out the same record while nothing a chart draws with changed", () => {+ // <html> changes for reasons that are not the theme (a frame writing its height, the root+ // font size); a new record each time would re-render every chart, and a chart whose render+ // touches <html> would never settle.+ const first = readChartStyle(reader({}));+ const again = readChartStyle(reader({}));+ expect(again).not.toBe(first);+ expect(nextChartStyle(first, again)).toBe(first);+ const changed = readChartStyle(reader({ "--ui-chart-line-width": "1px" }));+ expect(nextChartStyle(first, changed)).toBe(changed);+ const recoloured = readChartStyle(reader({ "--ui-chart-3": "#123456" }));+ expect(nextChartStyle(first, recoloured)).toBe(recoloured);+ expect(nextChartStyle(null, first)).toBe(first);+ });++ it("cycles the palette past its last slot", () => {+ expect(seriesStroke(DEFAULT_CHART_STYLE, 8)).toBe(DEFAULT_CHART_STYLE.series[0]);+ });+});++describe("the geometry the tokens drive", () => {+ const g = makeGeom(3, 100, 640);++ it("draws the default theme exactly as before: straight lines, 60% bars", () => {+ const points = seriesPoints(g, [0, 100, 50]);+ expect(curvePath(points)).toBe(curvePath(points, "linear"));+ expect(curvePath(seriesPoints(g, [0, 100]))).toMatch(/^M[\d.]+,[\d.]+ L[\d.]+,[\d.]+$/);+ expect(fitBarWidth(20)).toBe(fitBarWidth(20, DEFAULT_CHART_STYLE.barFill));+ });++ it("widens bars with the fill share, within the cap", () => {+ expect(fitBarWidth(20, 0.8)).toBe(16);+ expect(fitBarWidth(20, 0.3)).toBe(6);+ });++ it("steps and smooths without leaving the data's range", () => {+ const points = [+ [0, 50],+ [10, 10],+ [20, 30],+ ] as const;+ expect(curvePath(points, "step")).toBe("M0,50 H5 V10 H10 H15 V30 H20");+ const smooth = curvePath(points, "smooth");+ expect(smooth.startsWith("M0,50 C")).toBe(true);+ const ys = [...smooth.matchAll(/[\d.]+,([\d.]+)/g)].map((m) => Number(m[1]));+ expect(Math.min(...ys)).toBeGreaterThanOrEqual(10);+ expect(Math.max(...ys)).toBeLessThanOrEqual(50);+ });+});diff --git a/packages/web/test/company-beta.test.ts b/packages/web/test/company-beta.test.tsindex 87a4850f..11fa6883 100644--- a/packages/web/test/company-beta.test.ts+++ b/packages/web/test/company-beta.test.ts@@ -20,6 +20,7 @@ import {} from "../src/features/company/beta-badge";import { Segmented } from "../src/components/ui/segmented";import { zh } from "../src/lib/strings";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";/** The in-memory stand-in for localStorage (this package's vitest runs in Node, which has none). */function memoryStorage(initial: Record<string, string> = {}) {@@ -43,6 +44,16 @@ const throwingStorage = {},};+/** The modules rendered below, found by scanning web and the shared UI package (see roots.ts). */+describe("the beta marks' sources", () => {+ it("scan every source root, and find the badge and the switch in one place each", () => {+ const scan = scanSources();+ expectEveryRootScanned(scan);+ expectSingleHome(scan, "packages/web/src/features/company/beta-badge.tsx");+ expectSingleHome(scan, "packages/web/src/components/ui/segmented.tsx");+ });+});+describe("shouldShowBetaNotice", () => {it("is owed on a browser that has never seen it, and not after it is marked", () => {const storage = memoryStorage();@@ -107,7 +118,7 @@ describe("the beta tag on the work-mode switch", () => {expect(markup).toContain('aria-hidden="true"');expect(markup).toContain(zh.company.beta);// The tooltip is the one thing the tag still says on its own.- expect(markup).toContain(`title="${zh.company.betaTitle}"`);+ expect(markup).toContain(`data-tooltip="${zh.company.betaTitle}"`);});it("costs an option without one nothing", () => {diff --git a/packages/web/test/company-click-targets.test.ts b/packages/web/test/company-click-targets.test.tsindex 1f351791..51d1b5ba 100644--- a/packages/web/test/company-click-targets.test.ts+++ b/packages/web/test/company-click-targets.test.ts@@ -25,11 +25,10 @@* a prop. Those are on the reviewer.*/import { describe, expect, it } from "vitest";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import ts from "typescript";+import { expectEveryRootScanned, scanSources, sourceFile } from "./helpers/roots";-const SRC = fileURLToPath(new URL("../src", import.meta.url));+const SCAN = scanSources();/*** The company modules swept for the rule, relative to `src`. Every page whose surfaces have been@@ -112,10 +111,10 @@ function literalChunks(node: ts.Node, out: string[] = []): string[] {function findWholeAreaTargets(): string[] {const found: string[] = [];for (const rel of MODULES) {- const path = `${SRC}/${rel}`;+ const file = sourceFile(SCAN, `packages/web/src/${rel}`);const source = ts.createSourceFile(- path,- readFileSync(path, "utf8"),+ file.path,+ file.text,ts.ScriptTarget.Latest,/* setParentNodes */ true,ts.ScriptKind.TSX,@@ -156,6 +155,12 @@ function findWholeAreaTargets(): string[] {}describe("company pages", () => {+ it("scans every source root, and finds every swept module", () => {+ expectEveryRootScanned(SCAN);+ // A swept page that was renamed or moved must fail here rather than drop out of the sweep.+ for (const rel of MODULES) sourceFile(SCAN, `packages/web/src/${rel}`);+ });+it("navigate through named controls, never through a whole card, row or panel", () => {expect(findWholeAreaTargets()).toEqual([]);});diff --git a/packages/web/test/context-menu.test.ts b/packages/web/test/context-menu.test.tsindex 1c76265c..c35f7990 100644--- a/packages/web/test/context-menu.test.ts+++ b/packages/web/test/context-menu.test.ts@@ -20,9 +20,6 @@* contextmenu listener in the package, and that the one handler doing the suppressing* lives in the hook the row spreads onto itself (title-reveal.test.ts convention).*/-import { readFileSync, readdirSync } from "node:fs";-import { dirname, join, resolve, sep } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import {IDLE_HOLD,@@ -40,6 +37,7 @@ import {withinSettleWindow,} from "../src/lib/context-menu";import type { HoldEvent } from "../src/lib/context-menu";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";const ROW = { top: 100, bottom: 132, left: 8, right: 260 };@@ -287,45 +285,41 @@ describe("scrollMovesAnchor", () => {});});+/** Every .ts/.tsx under web and the shared UI package (test/helpers/roots.ts). */+const SCAN = scanSources([".ts", ".tsx"]);+/**- * Every .ts/.tsx under packages/web/src, as [relative path, source] pairs.+ * Every scanned file as [repo-relative id, source] pairs.*- * Paths are normalized to forward slashes here, once, rather than at each comparison:- * `join` yields `\` on Windows, so every `path === "components/ui/…"` in this file would- * silently match nothing there and collapse its assertions into "expected undefined to be- * defined" — green on Linux, red on the Windows CI job. Callers can rely on POSIX- * separators on every platform.+ * Ids use forward slashes on every platform: `join` yields `\` on Windows, so a comparison+ * against "packages/web/src/components/ui/…" would silently match nothing there and collapse+ * its assertions into "expected undefined to be defined" — green on Linux, red on the Windows+ * CI job. Callers can rely on POSIX separators on every platform.*/function sourceFiles(): Array<[string, string]> {- const root = resolve(dirname(fileURLToPath(import.meta.url)), "../src");- const out: Array<[string, string]> = [];- const walk = (dir: string) => {- for (const entry of readdirSync(dir, { withFileTypes: true })) {- const full = join(dir, entry.name);- if (entry.isDirectory()) walk(full);- else if (/\.tsx?$/.test(entry.name))- out.push([- full- .slice(root.length + 1)- .split(sep)- .join("/"),- readFileSync(full, "utf8"),- ]);- }- };- walk(root);- return out;+ return SCAN.files.map((file) => [file.id, file.text]);}+const DROPDOWN = "packages/web/src/components/ui/dropdown.tsx";+const CONTEXT_MENU = "packages/web/src/components/ui/context-menu.tsx";+const SIDEBAR = "packages/web/src/components/layout/sidebar.tsx";+describe("sourceFiles", () => {+ it("scans every source root, and finds the menu modules in one place each", () => {+ expectEveryRootScanned(SCAN);+ for (const id of [DROPDOWN, CONTEXT_MENU, "packages/web/src/lib/context-menu.ts"]) {+ expectSingleHome(SCAN, id);+ }+ });+it("reports POSIX-separated paths whatever the platform's separator is", () => {// Pins the contract the assertions below depend on. A no-op assertion on Linux, and// the one that fails first on Windows if the normalization is ever dropped.const paths = sourceFiles().map(([path]) => path);expect(paths.length).toBeGreaterThan(0);expect(paths.filter((p) => p.includes("\\"))).toEqual([]);- expect(paths).toContain("components/ui/context-menu.tsx");- expect(paths).toContain("components/layout/sidebar.tsx");+ expect(paths).toContain(CONTEXT_MENU);+ expect(paths).toContain(SIDEBAR);});});@@ -335,7 +329,7 @@ describe("anchored dismissal wiring", () => {// cannot reach is the component consulting it at all, and that is where this silently// breaks: drop the call and every assertion above still passes while the reported bug —// a streaming message list wiping a menu opened in the sidebar — comes straight back.- const dropdown = sourceFiles().find(([path]) => path === "components/ui/dropdown.tsx");+ const dropdown = sourceFiles().find(([path]) => path === DROPDOWN);expect(dropdown).toBeDefined();const onScroll = /const onScroll = \(e: Event\) => \{([\s\S]*?)\n {4}\};/.exec(dropdown![1]);expect(onScroll, "onScroll should be declared in dropdown.tsx").not.toBeNull();@@ -361,7 +355,7 @@ describe("native-menu suppression scope", () => {it("calls preventDefault inside the contextmenu handler itself, not somewhere adjacent", () => {// Tied to the handler rather than to the file: preventDefault also appears in// onKeyDown, so file-level presence would prove nothing about the native menu.- const hook = sourceFiles().find(([path]) => path === "components/ui/context-menu.tsx");+ const hook = sourceFiles().find(([path]) => path === CONTEXT_MENU);expect(hook).toBeDefined();const handler = /onContextMenu:\s*\(e\)\s*=>\s*\{([\s\S]*?)\n {4}\},/.exec(hook![1]);expect(handler).not.toBeNull();@@ -372,7 +366,7 @@ describe("native-menu suppression scope", () => {// React propagates through its own tree, so the Dropdown's body portal — a React child// of the row — would otherwise re-anchor the open menu when one of its items is// right-clicked. A DOM containment check separates the two trees.- const hook = sourceFiles().find(([path]) => path === "components/ui/context-menu.tsx");+ const hook = sourceFiles().find(([path]) => path === CONTEXT_MENU);const src = hook![1];expect(src).toContain("host.contains(e.target as Node)");for (const handler of ["onContextMenu", "onKeyDown", "onPointerDown"]) {@@ -385,7 +379,7 @@ describe("native-menu suppression scope", () => {});it("gives the sidebar row all three openers, so the menu is not mouse-only", () => {- const sidebar = sourceFiles().find(([path]) => path === "components/layout/sidebar.tsx");+ const sidebar = sourceFiles().find(([path]) => path === SIDEBAR);expect(sidebar).toBeDefined();// The row spreads the hook's handlers (contextmenu + Shift+F10 + press-and-hold) and// guards its own click against the one a hold replays.@@ -396,7 +390,7 @@ describe("native-menu suppression scope", () => {it("names the anchor's owner alongside the anchor, so the scroll rule has one to test", () => {// Without the wiring, scrollMovesAnchor is asked about a null owner on every scroll and// answers "dismiss" — the rule above would still pass while the bug was back.- const sidebar = sourceFiles().find(([path]) => path === "components/layout/sidebar.tsx");+ const sidebar = sourceFiles().find(([path]) => path === SIDEBAR);expect(sidebar![1]).toContain("anchorOwner={ctx.anchorOwner}");});});diff --git a/packages/web/test/control-size.test.ts b/packages/web/test/control-size.test.tsindex c3dc1e79..fa0e2182 100644--- a/packages/web/test/control-size.test.ts+++ b/packages/web/test/control-size.test.ts@@ -15,12 +15,12 @@* element owns the attribute, and a regex over the file cannot tell those apart.*/import { describe, expect, it } from "vitest";-import { readdirSync, readFileSync, statSync } from "node:fs";-import { join, sep } from "node:path";-import { fileURLToPath } from "node:url";import ts from "typescript";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";+import type { SourceFile } from "./helpers/roots";-const SRC = fileURLToPath(new URL("../src", import.meta.url));+/** Web and the shared UI package: a control that moves keeps its call sites under this check. */+const SCAN = scanSources();/** The controls that carry a `size` tier. A `className` on one of these may not set a font size. */const CONTROLS = new Set([@@ -39,14 +39,16 @@ const CONTROLS = new Set([*/const FONT_SIZE_CLASS = /\btext-(?:xs|sm|base|lg|xl|\d?xl|\[[^\]]+])(?![\w-])/;-function tsxFiles(dir = SRC, out: string[] = []): string[] {- for (const name of readdirSync(dir)) {- const path = join(dir, name);- if (statSync(path).isDirectory()) tsxFiles(path, out);- else if (name.endsWith(".tsx")) out.push(path);- }- return out;-}+const tsxFiles = (): SourceFile[] => SCAN.files.filter((file) => file.name.endsWith(".tsx"));++const parse = (file: SourceFile) =>+ ts.createSourceFile(+ file.path,+ file.text,+ ts.ScriptTarget.Latest,+ /* setParentNodes */ true,+ ts.ScriptKind.TSX,+ );const jsxTag = (node: ts.Node): string | null => {if (ts.isJsxSelfClosingElement(node)) return node.tagName.getText();@@ -86,14 +88,8 @@ function literalChunks(node: ts.Node, out: string[] = []): string[] {*/function findLooseFooterButtons(): string[] {const loose: string[] = [];- for (const path of tsxFiles()) {- const source = ts.createSourceFile(- path,- readFileSync(path, "utf8"),- ts.ScriptTarget.Latest,- /* setParentNodes */ true,- ts.ScriptKind.TSX,- );+ for (const file of tsxFiles()) {+ const source = parse(file);const visit = (node: ts.Node): void => {if (ts.isJsxAttribute(node) && node.name.getText() === "footer" && node.initializer) {const walk = (inner: ts.Node): void => {@@ -111,7 +107,7 @@ function findLooseFooterButtons(): string[] {: "<none>";if (rung !== '"sm"') {const line = source.getLineAndCharacterOfPosition(inner.getStart(source)).line + 1;- loose.push(`${path.slice(SRC.length + 1).replaceAll(sep, "/")}:${line} ${rung}`);+ loose.push(`${file.id}:${line} ${rung}`);}}ts.forEachChild(inner, walk);@@ -136,6 +132,7 @@ const DIALOG_BODY_MODULES = new Set(["features/settings/account-section.tsx","features/settings/profile-section.tsx","features/settings/appearance-section.tsx",+ "features/settings/credits-section.tsx","features/settings/general-section.tsx","features/settings/proxy-section.tsx","features/settings/section-shell.tsx",@@ -153,16 +150,9 @@ const DIALOG_BODY_MODULES = new Set([*/function findLooseDialogBodyButtons(): string[] {const loose: string[] = [];- for (const path of tsxFiles()) {- const rel = path.slice(SRC.length + 1).replaceAll(sep, "/");- if (!DIALOG_BODY_MODULES.has(rel)) continue;- const source = ts.createSourceFile(- path,- readFileSync(path, "utf8"),- ts.ScriptTarget.Latest,- /* setParentNodes */ true,- ts.ScriptKind.TSX,- );+ for (const file of tsxFiles()) {+ if (file.root !== "web" || !DIALOG_BODY_MODULES.has(file.rel)) continue;+ const source = parse(file);const visit = (node: ts.Node): void => {if (jsxTag(node) === "Button") {const attrs = (node as ts.JsxSelfClosingElement | ts.JsxOpeningElement).attributes@@ -176,7 +166,7 @@ function findLooseDialogBodyButtons(): string[] {: "<none>";if (rung !== '"sm"' && rung !== '"icon"') {const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;- loose.push(`${rel}:${line} ${rung}`);+ loose.push(`${file.rel}:${line} ${rung}`);}}ts.forEachChild(node, visit);@@ -189,14 +179,8 @@ function findLooseDialogBodyButtons(): string[] {/** Control call sites whose own `className` spells a font size, as "relative/path:line — class". */function findSpelledSizes(): string[] {const strays: string[] = [];- for (const path of tsxFiles()) {- const source = ts.createSourceFile(- path,- readFileSync(path, "utf8"),- ts.ScriptTarget.Latest,- /* setParentNodes */ true,- ts.ScriptKind.TSX,- );+ for (const file of tsxFiles()) {+ const source = parse(file);const visit = (node: ts.Node): void => {const tag = jsxTag(node);if (tag !== null && CONTROLS.has(tag)) {@@ -209,9 +193,7 @@ function findSpelledSizes(): string[] {const hit = FONT_SIZE_CLASS.exec(chunk);if (hit === null) continue;const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;- strays.push(- `${path.slice(SRC.length + 1).replaceAll(sep, "/")}:${line} <${tag}> ${hit[0]}`,- );+ strays.push(`${file.id}:${line} <${tag}> ${hit[0]}`);}}}@@ -223,6 +205,15 @@ function findSpelledSizes(): string[] {}describe("control font size", () => {+ it("scans every source root, and finds the control family and its dialog bodies", () => {+ expectEveryRootScanned(SCAN);+ for (const name of ["input.tsx", "select.tsx", "option-menu.tsx", "form-picker.tsx"]) {+ expectSingleHome(SCAN, `packages/web/src/components/ui/${name}`);+ }+ // A listed module that was renamed or moved would silently drop out of the dialog-body rule.+ for (const rel of DIALOG_BODY_MODULES) sourceFile(SCAN, `packages/web/src/${rel}`);+ });+it("is never spelled on a call site's className", () => {expect(findSpelledSizes(),@@ -308,14 +299,7 @@ describe("control font size", () => {// there is no rung below text-xs to step down to.// String literals only: a comment naming the shape it forbids must not trip its own guard.const spelled = (name: string): string[] => {- const path = join(SRC, "components/ui", name);- const source = ts.createSourceFile(- path,- readFileSync(path, "utf8"),- ts.ScriptTarget.Latest,- true,- ts.ScriptKind.TSX,- );+ const source = parse(sourceFile(SCAN, `packages/web/src/components/ui/${name}`));const found = new Set<string>();for (const chunk of literalChunks(source)) {for (const hit of chunk.matchAll(new RegExp(FONT_SIZE_CLASS, "g"))) found.add(hit[0]);diff --git a/packages/web/test/copy-button.test.ts b/packages/web/test/copy-button.test.tsindex 7cd0f339..60cc0c19 100644--- a/packages/web/test/copy-button.test.ts+++ b/packages/web/test/copy-button.test.ts@@ -1,7 +1,7 @@/**- * The copy button's feedback follows the WRITE: the check (and the tooltip's flip to the- * copied label) appears only once writeClipboard reports the text reached the clipboard,- * and a refused write leaves the control idle. clipboard.test.ts pins the entry itself; this+ * The copy button's feedback follows the WRITE: the check appears only once writeClipboard+ * reports the text reached the clipboard, and a refused write leaves the control idle. The+ * tooltip names the action throughout and never flips to the result. clipboard.test.ts pins the entry itself; this* pins the one place its answer is consumed, so dropping the `if (!ok) return;` guard in* useCopied (back to an unconditional check) fails here.*@@ -15,7 +15,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { ReactElement, ReactNode } from "react";import { CopyButton } from "../src/components/ui/copy-button";-import { S } from "../src/lib/strings";/** Hook slots in call order, the cursor rewound on each render, and every value `copied` was set to. */const hooks = vi.hoisted(() => ({@@ -51,7 +50,11 @@ const writeClipboard = vi.hoisted(() => vi.fn<(text: string) => Promise<boolean>vi.mock("../src/lib/clipboard", () => ({ writeClipboard }));-type Button = ReactElement<{ title: string; onClick: () => void }>;+type Button = ReactElement<{+ "data-tooltip": string;+ onClick: () => void;+ children: ReactElement<{ copied: boolean }>;+}>;const LABEL = "Copy session id";@@ -84,7 +87,8 @@ describe("CopyButton: the check follows the write", () => {it("shows no check when the write is refused", async () => {writeClipboard.mockResolvedValue(false);const idle = render();- expect(idle.props.title).toBe(LABEL);+ expect(idle.props["data-tooltip"]).toBe(LABEL);+ expect(idle.props.children.props.copied).toBe(false);idle.props.onClick();await settle();@@ -92,7 +96,7 @@ describe("CopyButton: the check follows the write", () => {expect(writeClipboard).toHaveBeenCalledTimes(1);expect(writeClipboard.mock.calls[0]?.[0]).toBe("sess-42");expect(hooks.copiedSets).not.toContain(true);- expect(render().props.title).toBe(LABEL);+ expect(render().props.children.props.copied).toBe(false);});it("shows the check once the write landed, and clears it after the window", async () => {@@ -101,10 +105,12 @@ describe("CopyButton: the check follows the write", () => {await settle();expect(hooks.copiedSets).toEqual([true]);- expect(render().props.title).toBe(S.common.copied);+ const copied = render();+ expect(copied.props.children.props.copied).toBe(true);+ expect(copied.props["data-tooltip"]).toBe(LABEL);vi.runAllTimers();expect(hooks.copiedSets).toEqual([true, false]);- expect(render().props.title).toBe(LABEL);+ expect(render().props.children.props.copied).toBe(false);});});diff --git a/packages/web/test/deslop.test.ts b/packages/web/test/deslop.test.tsnew file mode 100644index 00000000..ef6b2958--- /dev/null+++ b/packages/web/test/deslop.test.ts@@ -0,0 +1,230 @@+/**+ * The de-slop rules (K-redesign §3) over `packages/web/src`.+ *+ * The same checks the package holds itself to (`packages/ui/src/testing/deslop.ts`, run over+ * `packages/ui/src` by `packages/ui/test/deslop.test.ts`), run over the web app, where the tells+ * K-redesign §1.5 counts still stand: `transition-all`, a hover scale, pings and pulses on things+ * that are not live, thirteen hand-drawn spinners, one-hue notice boxes, 10–11 px text, uppercase+ * micro-titles. Each of those is in {@link ALLOWLIST} — per file, per rule, how many and the wave+ * that removes them — and nothing else may appear. The counts are exact both ways: a new hit fails+ * as new slop, and a hit that goes away fails until its entry shrinks, so the list only tightens and+ * every wave's PR shows its share of it leaving.+ *+ * Only the web root is judged here. A file a wave moves into the package leaves its entries behind+ * (they fail as stale) and is judged by the package suite, which allows nothing — which is how a+ * component is de-slopped when it moves, and not after.+ *+ * Rule 20 (palette classes, `dark:`, hex) is the package's: the web app speaks the palette until+ * each wave moves it to tokens. Rule 22 waits for a `PageHeader` (W4).+ */+import { describe, expect, it } from "vitest";+import {+ DESLOP_RULE_NUMBERS,+ DESLOP_RULES,+ PAGE_HEADER_COMPONENTS,+ allowlistProblems,+ analyzeFile,+ deslopHits,+} from "../../ui/src/testing/deslop";+import type { DeslopAllowlist, DeslopPolicy } from "../../ui/src/testing/deslop";+import { expectEveryRootScanned, scanSources } from "./helpers/roots";++const SCAN = scanSources();+const WEB = SCAN.files.filter((file) => file.root === "web");++/** The homes §3 names, as the web app spells them today. It has no Spinner of its own: W1 adds it. */+const POLICY: DeslopPolicy = {+ transformMotion: ["chevron.tsx", "sheet.tsx", "drawer.tsx", "dock-launcher.tsx"],+ entranceMotion: [],+ pulseHomes: ["dot.tsx", "skeleton.tsx", "streaming-caret.tsx"],+ spinnerHomes: [],+ tokensOnly: false,+ hexHomes: [],+};++/**+ * What the web app still holds, seeded from K-redesign §1.5, by path under `packages/web/src`:+ * `{ rule: [count, wave] }`. The wave is the one whose PR rewrites those lines — where §1.5 names+ * it (`transition-all`, spinners, pings → W1b; the hover scale → W2's SwatchPicker; one-hue boxes →+ * W4's Notice), that wave; otherwise the wave that moves or rebuilds the file (A-architecture §7:+ * W1 marks and actions, W2 forms, W3 overlays, W4 layout, navigation, notices and data display, W5+ * content, W6 chat, W7 files, shell and dock, W8 charts). `W1b+W7` splits an entry between two.+ * `W10` is the follow-up sweep of the code that landed on main while the waves were in flight.+ */+const ALLOWLIST: DeslopAllowlist = {+ "components/account/update-modal.tsx": {+ 1: [1, "W4"],+ 3: [1, "W4"],+ 6: [1, "W4"],+ 11: [2, "W1b"],+ },+ "components/account/update-row.tsx": { 11: [2, "W1b"] },+ "components/layout/app-layout.tsx": { 1: [1, "W7"] },+ "components/layout/project-dialogs.tsx": { 13: [1, "W3"] },+ "components/layout/sidebar.tsx": {+ 1: [5, "W1b+W7"],+ 12: [5, "W7"],+ 13: [3, "W7"],+ 14: [2, "W7"],+ },+ "components/ui/badge.tsx": { 13: [1, "W1"] },+ "components/ui/confirm-modal.tsx": { 7: [1, "W3"] },+ "components/ui/copy-button.tsx": { 12: [2, "W1"] },+ "components/ui/group-list.tsx": { 12: [1, "W4"], 13: [3, "W4"], 14: [2, "W4"] },+ "components/ui/input.tsx": { 9: [1, "W2"] },+ "components/ui/kbd.tsx": { 13: [1, "W10"] },+ "components/ui/option-menu.tsx": { 13: [1, "W2"] },+ "components/ui/paged-dialog.tsx": { 13: [1, "W3"], 14: [2, "W3"] },+ "components/ui/segmented.tsx": { 12: [2, "W2"] },+ "components/ui/session-row-menu.tsx": { 1: [1, "W1b"] },+ "components/ui/sheet.tsx": { 19: [1, "W3"] },+ "components/ui/status-icon.tsx": { 11: [2, "W1b"] },+ "components/ui/switch.tsx": { 1: [1, "W2"] },+ "components/ui/toast.tsx": { 9: [4, "W4"] },+ "components/ui/update-dot.tsx": { 13: [1, "W1"] },+ "features/agents/agent-settings-page.tsx": { 12: [3, "W4"] },+ "features/agents/hooks-tab.tsx": { 12: [1, "W4"], 13: [2, "W4"] },+ "features/agents/mcp-servers-section.tsx": { 13: [3, "W4"] },+ "features/agents/memory-tab.tsx": { 1: [1, "W4"], 4: [1, "W4"], 12: [8, "W4"], 13: [5, "W4"] },+ "features/agents/prompt-injection-controls.tsx": { 4: [1, "W4"], 12: [2, "W4"] },+ "features/agents/schedules-tab.tsx": { 12: [1, "W4"] },+ "features/agents/skills-tab.tsx": { 12: [1, "W4"], 13: [2, "W4"] },+ "features/ai-create/ai-create-panel.tsx": { 13: [1, "W4"] },+ "features/benchmark/benchmark-case-browser.tsx": { 13: [2, "W4"] },+ "features/benchmark/benchmark-detail.tsx": { 13: [2, "W4"] },+ "features/benchmark/benchmark-page.tsx": { 13: [2, "W4"], 18: [1, "W4"] },+ "features/benchmark/create-benchmark-modal.tsx": { 13: [1, "W3"] },+ "features/benchmark/evaluation-detail-modal.tsx": { 13: [2, "W3"] },+ "features/builtin-browser/browser-tab-strip.tsx": { 11: [2, "W10"], 12: [2, "W10"] },+ "features/chat/agent-topology-view.tsx": { 12: [1, "W6"], 13: [3, "W6"] },+ "features/chat/chat-input.tsx": { 7: [1, "W6"], 12: [7, "W6"], 13: [5, "W6"] },+ "features/chat/chat-page.tsx": { 6: [1, "W1b"], 12: [2, "W6"], 13: [3, "W6"], 15: [1, "W4"] },+ "features/chat/code-block.tsx": { 13: [1, "W5"] },+ "features/chat/context-gauge.tsx": { 12: [5, "W8"] },+ "features/chat/conversation-outline.tsx": { 1: [1, "W1b"], 6: [2, "W1b"], 12: [1, "W6"] },+ "features/chat/disclosure-row.tsx": { 13: [1, "W4"], 14: [2, "W4"] },+ "features/chat/draft-view.tsx": { 12: [1, "W6"], 13: [2, "W6"] },+ "features/chat/drop-zone.tsx": { 18: [1, "W7"] },+ "features/chat/live-duration.tsx": { 6: [1, "W4"] },+ "features/chat/memory-view.tsx": { 13: [2, "W6"] },+ "features/chat/message-item.tsx": { 4: [2, "W6"], 6: [1, "W6"], 13: [3, "W6"] },+ "features/chat/message-stream.tsx": { 11: [2, "W1b"] },+ "features/chat/model-picker-modal.tsx": { 12: [1, "W10"] },+ "features/chat/shortcuts-folder.tsx": { 12: [1, "W7"] },+ "features/chat/step-banner.tsx": { 13: [1, "W6"], 14: [2, "W6"] },+ "features/chat/subagent-chip.tsx": { 11: [2, "W1b"], 13: [1, "W6"] },+ "features/chat/subagents-view.tsx": { 13: [2, "W6"], 14: [2, "W6"] },+ "features/chat/task-stats-line.tsx": { 6: [1, "W1b"], 13: [1, "W6"], 15: [1, "W4"] },+ "features/chat/tool-call-card.tsx": { 6: [2, "W6"] },+ "features/chat/work-group.tsx": { 13: [1, "W6"] },+ "features/chat/workspace-browser.tsx": {+ 1: [1, "W7"],+ 11: [4, "W1b"],+ 12: [4, "W7"],+ 13: [1, "W7"],+ 18: [1, "W7"],+ },+ "features/chat/workspace-finder.tsx": { 12: [6, "W10"] },+ "features/chat/workspace-tree-view.tsx": { 13: [1, "W7"] },+ "features/company/beta-badge.tsx": { 13: [1, "W4"] },+ "features/company/calendar-page.tsx": { 12: [3, "W4"], 13: [10, "W4"] },+ "features/company/channel-composer.tsx": { 13: [2, "W6"] },+ "features/company/channel-header.tsx": { 13: [4, "W6"] },+ "features/company/channel-sidebar.tsx": { 12: [2, "W4"], 13: [6, "W4"], 14: [2, "W4"] },+ "features/company/channel-view.tsx": { 12: [1, "W6"], 13: [6, "W6"] },+ "features/company/chart-card.tsx": { 6: [1, "W1b"], 12: [1, "W8"], 13: [5, "W8"] },+ "features/company/employee-dialogs.tsx": { 12: [1, "W4"] },+ "features/company/finance-gauge.tsx": { 13: [1, "W8"] },+ "features/company/finance-page.tsx": { 12: [3, "W4"], 13: [6, "W4"] },+ "features/company/handbook-explorer.tsx": { 13: [1, "W4"] },+ "features/company/handbook-page.tsx": { 12: [2, "W4"], 13: [3, "W4"] },+ "features/company/org-chart-page.tsx": { 13: [2, "W4"] },+ "features/company/org-dialogs.tsx": { 13: [1, "W4"] },+ "features/company/org-layout.tsx": { 12: [1, "W4"], 13: [2, "W4"], 14: [2, "W4"] },+ "features/company/org-session-groups.tsx": { 12: [2, "W4+W10"], 13: [1, "W10"] },+ "features/company/org-switcher.tsx": { 13: [3, "W4"], 14: [2, "W4"] },+ "features/company/overview-page.tsx": { 12: [2, "W4"], 13: [2, "W4"], 14: [4, "W4"] },+ "features/company/shared.tsx": { 13: [3, "W4"] },+ "features/company/ticket-dialog.tsx": { 12: [6, "W4"], 13: [3, "W4"], 14: [2, "W4"] },+ "features/company/tickets-page.tsx": { 12: [4, "W4"], 13: [6, "W4"] },+ "features/dock/dock-drag.tsx": { 3: [1, "W7"], 12: [1, "W7"] },+ "features/dock/dock-launcher.tsx": { 13: [1, "W7"], 18: [3, "W7"], 19: [4, "W7"] },+ "features/dock/dock-panel.tsx": { 1: [2, "W7"], 12: [2, "W7"] },+ "features/models/model-tags.ts": { 13: [1, "W10"] },+ "features/models/models-page.tsx": { 1: [1, "W4"], 11: [8, "W1b"], 12: [7, "W4"], 13: [8, "W4"] },+ "features/models/protocol-suffix.tsx": { 11: [2, "W1b"] },+ "features/plugins/plugin-detail-page.tsx": { 13: [2, "W4"] },+ "features/plugins/plugin-detail.tsx": { 13: [1, "W4"] },+ "features/plugins/plugins-page.tsx": {+ 1: [1, "W4"],+ 12: [6, "W4"],+ 13: [11, "W4"],+ 14: [2, "W4"],+ },+ "features/schedules/schedule-form-modal.tsx": { 13: [2, "W2"] },+ "features/schedules/schedule-panel.tsx": { 12: [1, "W4"] },+ "features/schedules/schedule-suggestions.tsx": { 12: [1, "W4"], 13: [1, "W4"] },+ "features/semantic-id/semantic-id-field.tsx": { 11: [2, "W1b"] },+ "features/settings/proxy-section.tsx": { 13: [1, "W2"] },+ "features/settings/setting-row.tsx": { 1: [1, "W2"], 2: [1, "W2"] },+ "features/settings/shortcut-recorder.tsx": { 12: [1, "W10"], 13: [1, "W10"] },+ "features/settings/shortcuts-section.tsx": { 13: [1, "W10"] },+ "features/skills/skill-pick-list.tsx": { 12: [1, "W2"] },+ "features/terminal/terminal-appearance.ts": { 9: [1, "W10"] },+ "features/terminal/terminal-keybar.tsx": { 12: [1, "W10"] },+ "features/traces/timeline-chart.tsx": { 6: [2, "W8"], 13: [10, "W8"] },+ "features/traces/trace-event-row.tsx": { 12: [2, "W4"], 13: [1, "W4"] },+ "features/traces/trace-file-view.tsx": { 12: [2, "W4"], 13: [5, "W4"], 15: [1, "W4"] },+ "features/usage/usage-charts.tsx": { 13: [3, "W8"] },+ "features/usage/usage-page.tsx": { 12: [1, "W8"] },+ "lib/tone.ts": { 9: [4, "W4"] },+ "pages/login.tsx": { 9: [1, "W4"] },+};++const WAVES = /^W(?:1a?|1b|10|[2-9])(?:\+W(?:1a?|1b|10|[2-9]))*$/;+const relOf = (id: string) => id.slice("packages/web/src/".length);++describe("de-slop rules over packages/web/src", () => {+ it("scans every source root, and every allowlisted file is still in the web app", () => {+ expectEveryRootScanned(SCAN);+ const gone = Object.keys(ALLOWLIST).filter((rel) => !WEB.some((file) => file.rel === rel));+ expect(+ gone,+ "An allowlisted file that left packages/web/src moved into the package (whose suite allows " ++ "nothing) or was deleted: remove its entry.",+ ).toEqual([]);+ });++ it("names a planned wave in every entry", () => {+ const unplanned = Object.entries(ALLOWLIST).flatMap(([rel, rules]) =>+ Object.entries(rules).flatMap(([rule, entry]) =>+ entry !== undefined && WAVES.test(entry[1]) && entry[0] > 0 ? [] : [`${rel} rule ${rule}`],+ ),+ );+ expect(unplanned).toEqual([]);+ });++ for (const rule of DESLOP_RULE_NUMBERS) {+ const title = `rule ${rule}: ${DESLOP_RULES[rule]}`;+ if (rule === 20) {+ it.skip(`${title} — not applied to the web app: it moves off the palette wave by wave`, () => {});+ continue;+ }+ if (+ rule === 22 &&+ !WEB.some((file) =>+ analyzeFile(file).components.some((c) => PAGE_HEADER_COMPONENTS.includes(c.name)),+ )+ ) {+ it.skip(`${title} — PENDING: the web app has no PageHeader (W4 adds it to the package)`, () => {});+ continue;+ }+ it(title, () => {+ expect(+ allowlistProblems(deslopHits(WEB, rule, POLICY), rule, ALLOWLIST, (hit) => relOf(hit.file)),+ `K-redesign §3 rule ${rule}: ${DESLOP_RULES[rule]}. Fix a new hit rather than allowlisting ` ++ "it; when a hit goes away, shrink its entry.",+ ).toEqual([]);+ });+ }+});diff --git a/packages/web/test/disclosure-anchor.test.ts b/packages/web/test/disclosure-anchor.test.tsindex b6f72e4a..c1f5261f 100644--- a/packages/web/test/disclosure-anchor.test.ts+++ b/packages/web/test/disclosure-anchor.test.ts@@ -12,25 +12,15 @@* beside a "?" is a question about sibling nodes, and a regex cannot see siblings.*/import { describe, expect, it } from "vitest";-import { readdirSync, readFileSync, statSync } from "node:fs";-import { join, sep } from "node:path";-import { fileURLToPath } from "node:url";import ts from "typescript";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";-const SRC = fileURLToPath(new URL("../src", import.meta.url));+/** Web and the shared UI package: the rule follows InfoPopover's call sites wherever they live. */+const SCAN = scanSources();/** Components whose whole job is to render a field's or a section's title. */const TITLE_ELEMENTS = new Set(["FieldLabel"]);-function tsxFiles(dir = SRC, out: string[] = []): string[] {- for (const name of readdirSync(dir)) {- const path = join(dir, name);- if (statSync(path).isDirectory()) tsxFiles(path, out);- else if (name.endsWith(".tsx")) out.push(path);- }- return out;-}-const jsxTag = (node: ts.Node): string | null => {if (ts.isJsxSelfClosingElement(node)) return node.tagName.getText();if (ts.isJsxElement(node)) return node.openingElement.tagName.getText();@@ -68,10 +58,10 @@ function slotIn(node: ts.Node): { host: ts.JsxElement | ts.JsxFragment; slot: ts/** Every `<InfoPopover>` in the tree that has no title among its preceding siblings. */function findOrphans(): string[] {const orphans: string[] = [];- for (const path of tsxFiles()) {+ for (const file of SCAN.files.filter((f) => f.name.endsWith(".tsx"))) {const source = ts.createSourceFile(- path,- readFileSync(path, "utf8"),+ file.path,+ file.text,ts.ScriptTarget.Latest,/* setParentNodes */ true,ts.ScriptKind.TSX,@@ -86,7 +76,7 @@ function findOrphans(): string[] {.some(rendersTitle);if (!anchored) {const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;- orphans.push(`${path.slice(SRC.length + 1).replaceAll(sep, "/")}:${line}`);+ orphans.push(`${file.id}:${line}`);}}ts.forEachChild(node, visit);@@ -97,6 +87,12 @@ function findOrphans(): string[] {}describe("disclosure anchoring", () => {+ it("scans every source root, and finds the two disclosures in one place each", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, "packages/web/src/components/ui/info-popover.tsx");+ expectSingleHome(SCAN, "packages/web/src/components/ui/help-fold.tsx");+ });+it("never leaves an InfoPopover standing without a title beside it", () => {expect(findOrphans(),diff --git a/packages/web/test/disclosure-body.test.ts b/packages/web/test/disclosure-body.test.tsindex eb0a0186..59738bba 100644--- a/packages/web/test/disclosure-body.test.ts+++ b/packages/web/test/disclosure-body.test.ts@@ -16,27 +16,24 @@* rounded box the transcript uses for a quotation.*/import { describe, expect, it } from "vitest";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import {DISCLOSURE_BODY_MD_CLASS,DISCLOSURE_OUTPUT_PRE_CLASS,} from "../src/features/chat/disclosure-row";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";-const read = (rel: string) =>- readFileSync(fileURLToPath(new URL(`../src/${rel}`, import.meta.url)), "utf8");+const SCAN = scanSources();-const styles = read("styles.css");-const thinking = read("features/chat/thinking-block.tsx");-const compaction = read("features/chat/compaction-banner.tsx");+const thinking = sourceFile(SCAN, "packages/web/src/features/chat/thinking-block.tsx").text;+const compaction = sourceFile(SCAN, "packages/web/src/features/chat/compaction-banner.tsx").text;/**- * styles.css with every `@layer …{ }` block removed, i.e. only its unlayered rules.+ * One stylesheet with every `@layer …{ }` block removed, i.e. only its unlayered rules.* Comments go first: one of them names `@layer utilities` in prose, and the scan below* would take that for the start of a block and swallow the rules after it.*/-const unlayered = (() => {- let css = styles.replace(/\/\*[\s\S]*?\*\//g, "");+const unlayeredRules = (sheet: string) => {+ let css = sheet.replace(/\/\*[\s\S]*?\*\//g, "");for (;;) {const at = css.search(/@layer[^;{]*\{/);if (at === -1) return css;@@ -49,13 +46,29 @@ const unlayered = (() => {}css = css.slice(0, at) + css.slice(end + 1);}-})();+};++/**+ * The unlayered rules of every stylesheet under the scanned roots — styles.css today, the shared+ * package's component CSS once the Markdown body moves there — each file stripped on its own.+ */+const unlayered = SCAN.files+ .filter((file) => file.name.endsWith(".css"))+ .map((file) => unlayeredRules(file.text))+ .join("\n");++describe("the disclosure body's sources", () => {+ it("scan every source root, and find the shared classes in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, "packages/web/src/features/chat/disclosure-row.tsx");+ });+});/** Class list as a set, so an assertion does not depend on the order Prettier settles on. */const classes = (value: string) => new Set(value.split(" "));describe("the disclosure body's end margins", () => {- it("are reset by an unlayered rule in styles.css", () => {+ it("are reset by an unlayered rule in a stylesheet", () => {expect(classes(DISCLOSURE_BODY_MD_CLASS)).toContain("md-body-flush");// Written without whitespace so reformatting the stylesheet cannot break the match.const rules = unlayered.replace(/\s+/g, "");diff --git a/packages/web/test/esc-layers.test.ts b/packages/web/test/esc-layers.test.tsindex 583a801e..e880c20d 100644--- a/packages/web/test/esc-layers.test.ts+++ b/packages/web/test/esc-layers.test.ts@@ -6,6 +6,15 @@*/import { describe, expect, it } from "vitest";import { isTopEscLayer, popEscLayer, pushEscLayer } from "../src/components/ui/modal";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";++describe("esc layer sources", () => {+ it("scan every source root, and find the stack in one place", () => {+ const scan = scanSources();+ expectEveryRootScanned(scan);+ expectSingleHome(scan, "packages/web/src/components/ui/modal.tsx");+ });+});describe("esc layer stack", () => {it("only the topmost layer may act; popping restores the one below", () => {diff --git a/packages/web/test/group-list.test.ts b/packages/web/test/group-list.test.tsindex e9a0992d..6cc266a2 100644--- a/packages/web/test/group-list.test.ts+++ b/packages/web/test/group-list.test.ts@@ -13,9 +13,6 @@* its glyphs from the same map the two-icon header toggle uses, so a mode cannot end up* wearing one icon in the toggle and another in the menu.*/-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import {AGENT_GROUP_ICON,@@ -31,6 +28,16 @@ import type { GroupMode } from "../src/components/ui/group-list";import type { SessionSortMode } from "../src/lib/session-order";import { zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";++const SCAN = scanSources();++describe("the group list's sources", () => {+ it("scan every source root, and find the group list in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, "packages/web/src/components/ui/group-list.tsx");+ });+});describe("newEntityForGroupMode", () => {it("agent grouping creates an Agent; workspace grouping (the default) creates a Workspace", () => {@@ -61,9 +68,7 @@ describe("list-options glyphs", () => {// The claim worth pinning is not the map's contents but that nothing re-picks an icon// beside it: a hardcoded glyph at a call site is how a row and the mode it names would// drift apart. Node-only suite, so this reads the sources (title-reveal.test.ts).- const read = (p: string) =>- readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), p), "utf8");- const sidebar = read("../src/components/layout/sidebar.tsx");+ const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;for (const mode of ["workspace", "agent", "time"] satisfies GroupMode[])expect(sidebar).toContain(`icon={GROUP_MODE_ICONS.${mode}}`);for (const mode of ["recent", "manual"] satisfies SessionSortMode[])diff --git a/packages/web/test/handbook-explorer.test.ts b/packages/web/test/handbook-explorer.test.tsindex e2b771e6..bcc0039e 100644--- a/packages/web/test/handbook-explorer.test.ts+++ b/packages/web/test/handbook-explorer.test.ts@@ -77,7 +77,7 @@ describe("HandbookExplorer rows", () => {it("keeps the index's reason for being pinned out of the row and in its tooltip and name", () => {const [index] = rows();const expected = `${HANDBOOK_INDEX} · ${zh.company.handbook.indexLabel} · ${updatedAt(512)}`;- expect(attr(index!, "title")).toBe(expected);+ expect(attr(index!, "data-tooltip")).toBe(expected);expect(attr(index!, "aria-label")).toBe(expected);expect(visible(index!)).toContain(HANDBOOK_INDEX);expect(visible(index!)).not.toContain(zh.company.handbook.indexLabel);@@ -89,14 +89,14 @@ describe("HandbookExplorer rows", () => {it("gives a document row its path and write time, and no accessible name of its own", () => {const row = rows().find((r) => attr(r, "data-tree-path") === "conventions.md");- expect(attr(row!, "title")).toBe(`conventions.md · ${updatedAt(40)}`);+ expect(attr(row!, "data-tooltip")).toBe(`conventions.md · ${updatedAt(40)}`);expect(attr(row!, "aria-label")).toBeNull();expect(visible(row!)).toBe(`conventions.md${formatRelativeShort(UPDATED, "zh")}`);});it("gives a folder row its path and how many documents it holds", () => {const row = rows().find((r) => attr(r, "aria-expanded") !== null);- expect(attr(row!, "title")).toBe(`roles · ${zh.company.handbook.documentsInFolder(2)}`);+ expect(attr(row!, "data-tooltip")).toBe(`roles · ${zh.company.handbook.documentsInFolder(2)}`);expect(attr(row!, "aria-label")).toBeNull();expect(visible(row!)).toBe("roles2");});diff --git a/packages/web/test/help-fold.test.ts b/packages/web/test/help-fold.test.tsindex 8dd58b5e..b9888bc6 100644--- a/packages/web/test/help-fold.test.ts+++ b/packages/web/test/help-fold.test.ts@@ -8,9 +8,19 @@ import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { HelpFold } from "../src/components/ui/help-fold";import { S } from "../src/lib/strings";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";const DESC = "The vault stores values that commands can read at run time.";+/** The module rendered below, found by scanning web and the shared UI package (see roots.ts). */+describe("the fold's source", () => {+ it("scans every source root, and finds the fold in one place", () => {+ const scan = scanSources();+ expectEveryRootScanned(scan);+ expectSingleHome(scan, "packages/web/src/components/ui/help-fold.tsx");+ });+});+describe("HelpFold", () => {const html = renderToStaticMarkup(createElement(HelpFold, { children: DESC }));diff --git a/packages/web/test/helpers/roots.ts b/packages/web/test/helpers/roots.tsnew file mode 100644index 00000000..592bb08f--- /dev/null+++ b/packages/web/test/helpers/roots.ts@@ -0,0 +1,78 @@+/**+ * The source roots the web app's guard tests scan, and the assertions every roots-aware guard+ * makes about them.+ *+ * The theme work moves reusable components out of `packages/web/src` into the shared+ * `packages/ui/src` one wave at a time (A-architecture §7). A guard that walked only the web tree+ * would keep passing after its subject moved — over fewer files, with nothing left to find — so+ * every guard scans both roots and asserts two things before its own rule:+ *+ * - `expectEveryRootScanned`: each root yielded files. A mistyped or moved root fails here, by+ * name, instead of narrowing the guard to nothing.+ * - `expectSingleHome`: a module the guard is about lives in exactly one place across the roots,+ * the place the guard names. A copy left behind by a move — the web original beside the package+ * version — would otherwise keep the guard testing the stale one.+ *+ * Files are named by repo-relative id (`packages/web/src/components/ui/icons.tsx`), which stays+ * unambiguous across roots and reads the same on Windows.+ */+import { fileURLToPath } from "node:url";+import { expect } from "vitest";+import {+ filesNamed,+ findSourceFile,+ scanSourceRoots,+ unscannedRoots,+} from "../../../ui/src/testing/source-roots";+import type { SourceFile, SourceScan } from "../../../ui/src/testing/source-roots";++export type { SourceFile, SourceScan };++/** The monorepo root: the base of every {@link SourceFile.id}. */+export const REPO_ROOT = fileURLToPath(new URL("../../../../", import.meta.url));++/**+ * Every root a guard scans. The gallery (`packages/ui-gallery/src`) joins when that package lands;+ * its chrome is deliberately unthemed, so each guard decides then whether it applies there.+ */+export const SOURCE_ROOTS = {+ web: fileURLToPath(new URL("../../src", import.meta.url)),+ ui: fileURLToPath(new URL("../../../ui/src", import.meta.url)),+} as const;++/** `.ts`, `.tsx` and `.css` under every root. */+export function scanSources(extensions?: readonly string[]): SourceScan {+ return scanSourceRoots(SOURCE_ROOTS, { repoRoot: REPO_ROOT, extensions });+}++/** Fails, naming the root, when any root yielded no files. */+export function expectEveryRootScanned(scan: SourceScan): void {+ expect(+ unscannedRoots(scan),+ "Every source root must yield files; a root that yields none means a wrong path in " ++ "test/helpers/roots.ts or a package that moved, and the guard would pass over nothing.",+ ).toEqual([]);+}++/** The scanned file with this repo-relative id; fails the test when no root holds it. */+export function sourceFile(scan: SourceScan, id: string): SourceFile {+ const file = findSourceFile(scan, id);+ expect(+ file,+ `${id} is not under any scanned root (${Object.keys(SOURCE_ROOTS).join(", ")})`,+ ).toBeDefined();+ return file!;+}++/**+ * Asserts the file named by `id` is the only file with its name across every root. Call it for+ * each module a guard is about, so a moved module fails the guard until the guard names its new+ * home, and a leftover copy fails it until the copy is deleted.+ */+export function expectSingleHome(scan: SourceScan, id: string): void {+ const name = id.slice(id.lastIndexOf("/") + 1);+ expect(+ filesNamed(scan, name).map((file) => file.id),+ `${name} should live only at ${id}`,+ ).toEqual([id]);+}diff --git a/packages/web/test/icon-scale.test.ts b/packages/web/test/icon-scale.test.tsindex 5219bd2d..131e09c4 100644--- a/packages/web/test/icon-scale.test.ts+++ b/packages/web/test/icon-scale.test.ts@@ -5,35 +5,41 @@* one component's output — it is a new inline `<svg>` re-drawing a glyph the app already owns, at* a stroke weight nobody chose. The three paths asserted below each used to exist in five or six* hand-typed copies.+ *+ * The scans cover the web app and the shared UI package (test/helpers/roots.ts): a glyph that moves+ * into the package keeps its one home, and a copy re-typed on either side is still a second copy.*/+import { existsSync, readFileSync } from "node:fs";import { describe, expect, it } from "vitest";-import { readdirSync, readFileSync, statSync } from "node:fs";-import { join, sep } from "node:path";-import { fileURLToPath } from "node:url";-import { ICON_GAP, ICON_SIZE } from "../src/lib/icon-scale";--const SRC = fileURLToPath(new URL("../src", import.meta.url));--function sources(dir = SRC, out: string[] = []): string[] {- for (const name of readdirSync(dir)) {- const path = join(dir, name);- if (statSync(path).isDirectory()) sources(path, out);- else if (name.endsWith(".ts") || name.endsWith(".tsx")) out.push(path);- }- return out;-}--// Forward slashes whatever the platform separator is, so the expected paths below read the same-// on Windows as they do everywhere else.-const FILES = sources().map(- (path) => [path.slice(SRC.length + 1).replaceAll(sep, "/"), readFileSync(path, "utf8")] as const,-);--/** Every occurrence of `needle`, as "relative/path:count". */+import { ICON_SIZE, ICON_GAP } from "../src/lib/icon-scale";+import { DEFAULT_THEME_ID, THEME_IDS, THEME_MODES } from "../../ui/src/tokens";+import { analyzeThemeFile, resolveThemeValue } from "../../ui/src/testing/theme-tokens";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";++const SCAN = scanSources();++// Every file id is repo-relative with forward slashes whatever the platform separator is, so the+// expected paths below read the same on Windows as they do everywhere else.+const FILES = SCAN.files+ .filter((file) => file.name.endsWith(".ts") || file.name.endsWith(".tsx"))+ .map((file) => [file.id, file.text] as const);++/** Every file containing `needle`, by repo-relative id. */const occurrences = (needle: string) =>- FILES.filter(([, src]) => src.includes(needle)).map(([rel]) => rel);+ FILES.filter(([, src]) => src.includes(needle)).map(([id]) => id);++const ICONS = "packages/web/src/components/ui/icons.tsx";+const CHEVRON = "packages/web/src/components/ui/chevron.tsx";+const GLYPH_ICON = "packages/web/src/components/ui/glyph-icon.tsx";describe("icon scale", () => {+ it("scans every source root, and finds the icon modules in one place each", () => {+ expectEveryRootScanned(SCAN);+ for (const id of [ICONS, CHEVRON, GLYPH_ICON, "packages/web/src/lib/icon-scale.ts"]) {+ expectSingleHome(SCAN, id);+ }+ });+it("names every rung with a whole pixel value", () => {for (const [role, size] of Object.entries(ICON_SIZE)) {expect(Number.isInteger(size), `${role} must be a whole pixel`).toBe(true);@@ -49,55 +55,102 @@ describe("icon scale", () => {describe("one glyph, one home", () => {it("draws the form-control caret in exactly one place", () => {- expect(occurrences("M3 4.5l3 3 3-3")).toEqual(["components/ui/icons.tsx"]);+ expect(occurrences("M3 4.5l3 3 3-3")).toEqual([ICONS]);});it("draws the close cross in exactly one place", () => {- expect(occurrences("M2 2l10 10M12 2L2 12")).toEqual(["components/ui/icons.tsx"]);+ expect(occurrences("M2 2l10 10M12 2L2 12")).toEqual([ICONS]);});it("draws the collapse chevron in exactly one place", () => {- expect(occurrences("M9 5l7 7-7 7")).toEqual(["components/ui/chevron.tsx"]);+ expect(occurrences("M9 5l7 7-7 7")).toEqual([CHEVRON]);});// The two dock edges are drawn from two places at once — the chat toolbar's pull-open// buttons and the dock header's move-dock buttons — which is exactly how the marks above// accumulated their copies.it("draws the bottom-dock mark in exactly one place", () => {- expect(occurrences("M4 5h16v14H4zM4 14h16")).toEqual(["components/ui/icons.tsx"]);+ expect(occurrences("M4 5h16v14H4zM4 14h16")).toEqual([ICONS]);});it("draws the right-dock mark in exactly one place", () => {- expect(occurrences("M4 5h16v14H4zM14 5v14")).toEqual(["components/ui/icons.tsx"]);+ expect(occurrences("M4 5h16v14H4zM14 5v14")).toEqual([ICONS]);});it("draws the memory brain in exactly one place", () => {// The Memory mark was hand-typed three times — the dock's panel table, the memory-changes// card and the agent card's memory count — so a redraw moved one surface and left the others// on the old picture.- expect(occurrences("M5.15 8.05C5.05 9.75")).toEqual(["components/ui/icons.tsx"]);+ expect(occurrences("M5.15 8.05C5.05 9.75")).toEqual([ICONS]);});it("draws the background-task trace in exactly one place", () => {// Three surfaces draw it now — a session row, the chat header pill and a backgrounded// tool row — which is how the paths above ended up hand-typed five times each.- expect(occurrences("M2 12h4l3 9 6-18 3 9h4")).toEqual(["components/ui/icons.tsx"]);+ expect(occurrences("M2 12h4l3 9 6-18 3 9h4")).toEqual([ICONS]);});});describe("stroke weights", () => {- it("uses no weight outside the ones the family actually chose", () => {+ it("uses no literal weight outside the ones the family actually chose", () => {// 1.7 is the 24x24 line family; 1.5 belongs to the two marks drawn on their own smaller// grids (the caret and the close cross) and to chart rules; 2 is the checkmark, the ring// gauges and the send arrow on a filled button; 2.2 is the collapse chevron alone; 1 is the// login background art. Anything else — a 1.6 or a 1.8 — is a glyph nobody sized on purpose.+ // A theme's lighter or heavier line family (1.6, 1.4) is never a literal: it is the+ // `--ui-icon-stroke` token below, which GlyphIcon reads.const allowed = new Set(["1", "1.5", "1.7", "2", "2.2"]);const strays: string[] = [];- for (const [rel, src] of FILES) {+ for (const [id, src] of FILES) {for (const m of src.matchAll(/strokeWidth="([0-9.]+)"/g)) {- if (!allowed.has(m[1] ?? "")) strays.push(`${rel}: ${m[1]}`);+ if (!allowed.has(m[1] ?? "")) strays.push(`${id}: ${m[1]}`);}}expect(strays).toEqual([]);});++ it("draws the line family at the theme's stroke token, not at a literal", () => {+ const glyph = sourceFile(SCAN, GLYPH_ICON).text;+ expect(glyph).toContain('strokeWidth: "var(--ui-icon-stroke, 1.7)"');+ // The fallback is the default theme's weight; a literal attribute beside it would be dead code+ // that reads as the real weight.+ expect(glyph).not.toMatch(/strokeWidth="[0-9.]+"/);+ });++ describe("the --ui-icon-stroke token", () => {+ /** The weights a theme's line family may take: Primer 1.7, Frost 1.6, Console 1.4. */+ const LINE_FAMILY = new Set(["1.4", "1.6", "1.7"]);+ const themePath = (id: string) => new URL(`../../ui/src/themes/${id}.css`, import.meta.url);+ const analysis = (id: (typeof THEME_IDS)[number]) => {+ const path = themePath(id);+ if (!existsSync(path)) return null;+ const result = analyzeThemeFile(readFileSync(path, "utf8"), id);+ return result.isStub ? null : result;+ };+ const defaultTheme = analysis(DEFAULT_THEME_ID);++ for (const id of THEME_IDS) {+ const theme = analysis(id);+ if (theme === null || defaultTheme === null) {+ it.skip(`${id} — PENDING: themes/${id}.css declares no tokens yet`, () => {});+ continue;+ }+ it(`${id} sets a line-family weight in both modes`, () => {+ for (const mode of THEME_MODES) {+ const weight = resolveThemeValue("--ui-icon-stroke", mode, theme, defaultTheme);+ expect(LINE_FAMILY, `${id} ${mode}: --ui-icon-stroke = ${weight}`).toContain(weight);+ }+ });+ }++ if (defaultTheme !== null) {+ it("keeps the default theme at the weight GlyphIcon falls back to", () => {+ for (const mode of THEME_MODES) {+ expect(resolveThemeValue("--ui-icon-stroke", mode, defaultTheme, defaultTheme)).toBe(+ "1.7",+ );+ }+ });+ }+ });});diff --git a/packages/web/test/info-popover.test.ts b/packages/web/test/info-popover.test.tsindex 9f7a0a78..840346b4 100644--- a/packages/web/test/info-popover.test.ts+++ b/packages/web/test/info-popover.test.ts@@ -15,6 +15,25 @@ import { Input } from "../src/components/ui/input";import { Switch } from "../src/components/ui/switch";import { PrefRow } from "../src/features/settings/setting-row";import { S } from "../src/lib/strings";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";++/**+ * The modules rendered below, found by scanning web and the shared UI package: a component that+ * moves must be re-pointed here, and a copy left behind would otherwise stay the one under test.+ */+describe("the popover's sources", () => {+ it("scan every source root, and find each rendered module in one place", () => {+ const scan = scanSources();+ expectEveryRootScanned(scan);+ for (const id of [+ "packages/web/src/components/ui/info-popover.tsx",+ "packages/web/src/components/ui/field.tsx",+ "packages/web/src/features/settings/setting-row.tsx",+ ]) {+ expectSingleHome(scan, id);+ }+ });+});describe("InfoPopover", () => {const html = renderToStaticMarkup(@@ -25,7 +44,7 @@ describe("InfoPopover", () => {expect(html).toContain("<button");expect(html).toContain('type="button"');expect(html).toContain(`aria-label="${S.common.moreInfo}"`);- expect(html).toContain(`title="${S.common.moreInfo}"`);+ expect(html).toContain(`data-tooltip="${S.common.moreInfo}"`);});it("starts collapsed, and points at the panel it will open", () => {diff --git a/packages/web/test/inner-html-stability.test.ts b/packages/web/test/inner-html-stability.test.tsindex 3114949a..e4cdb419 100644--- a/packages/web/test/inner-html-stability.test.ts+++ b/packages/web/test/inner-html-stability.test.ts@@ -16,30 +16,28 @@* vitest runs node-only here (`environment: "node"`, no jsdom), so this asserts against the* source text rather than a rendered DOM.*/-import { readFileSync, readdirSync } from "node:fs";-import { dirname, join, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";+import { expectEveryRootScanned, scanSources } from "./helpers/roots";-const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "../src");+/** Every source file under web and the shared UI package (test/helpers/roots.ts). */+const SCAN = scanSources();-/** Every `.tsx` under src/, as [path relative to src, source text]. */-function sources(dir: string, rel = ""): Array<[string, string]> {- const out: Array<[string, string]> = [];- for (const entry of readdirSync(dir, { withFileTypes: true })) {- const next = join(dir, entry.name);- const label = rel === "" ? entry.name : `${rel}/${entry.name}`;- if (entry.isDirectory()) out.push(...sources(next, label));- else if (entry.name.endsWith(".tsx")) out.push([label, readFileSync(next, "utf8")]);- }- return out;+/** Every `.tsx` under the scanned roots, as [repo-relative id, source text]. */+function sources(): Array<[string, string]> {+ return SCAN.files+ .filter((file) => file.name.endsWith(".tsx"))+ .map((file) => [file.id, file.text]);}describe("dangerouslySetInnerHTML", () => {+ it("is looked for in every source root", () => {+ expectEveryRootScanned(SCAN);+ });+it("is never given an object literal built in the JSX", () => {// `dangerouslySetInnerHTML={{ __html: … }}` — the inline form, which is a new object every// render. The value has to come from a memo (or any other stable reference) instead.- const inline = sources(SRC)+ const inline = sources().filter(([, src]) => /dangerouslySetInnerHTML=\{\{/.test(src)).map(([path]) => path);expect(inline).toEqual([]);@@ -48,10 +46,13 @@ describe("dangerouslySetInnerHTML", () => {it("is used in exactly the two places that own untrusted markup", () => {// A third site is not forbidden, but it is worth noticing: each one is a place sanitisation// has to be argued, and each one carries the identity rule above.- const users = sources(SRC)+ const users = sources().filter(([, src]) => src.includes("dangerouslySetInnerHTML")).map(([path]) => path).sort();- expect(users).toEqual(["features/chat/code-block.tsx", "features/skills/skill-icon-view.tsx"]);+ expect(users).toEqual([+ "packages/web/src/features/chat/code-block.tsx",+ "packages/web/src/features/skills/skill-icon-view.tsx",+ ]);});});diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.tsindex 0edef0fa..58a06787 100644--- a/packages/web/test/install-scope.test.ts+++ b/packages/web/test/install-scope.test.ts@@ -70,7 +70,11 @@ function populated(): ReturnType<typeof memStorage> {'[{"sessionId":"session-2","agentId":"acme_dev","title":"Build the site"}]',"penguin.theme": "dark",+ "penguin.themeId": "geek",+ "penguin.textSize": "l","penguin.fontScale": "lg",+ "penguin.fontLatin": "mona-sans",+ "penguin.fontCjk": "noto-sans-sc","penguin.accent": "violet","penguin.currency": "CNY","penguin.terminal.theme": "dark",@@ -98,7 +102,11 @@ function snap(map: Map<string, string>): [string, string][] {const PREFERENCE_KEYS = ["penguin.theme",+ "penguin.themeId",+ "penguin.textSize","penguin.fontScale",+ "penguin.fontLatin",+ "penguin.fontCjk","penguin.accent","penguin.currency","penguin.terminal.theme",diff --git a/packages/web/test/md.test.ts b/packages/web/test/md.test.tsindex 16e17eea..97646f73 100644--- a/packages/web/test/md.test.ts+++ b/packages/web/test/md.test.ts@@ -76,12 +76,12 @@ describe("Md links", () => {expectNewTab(tags[0]);});- it('preserves the markdown link title from [text](url "title")', () => {+ it('shows the markdown link title from [text](url "title") in the shared tooltip', () => {const html = render('Read [docs](https://example.com "API docs") first.');const tags = anchors(html);expect(tags).toHaveLength(1);expect(tags[0]).toContain('href="https://example.com"');- expect(tags[0]).toContain('title="API docs"');+ expect(tags[0]).toContain('data-tooltip="API docs"');expectNewTab(tags[0]);});diff --git a/packages/web/test/menu-style.test.ts b/packages/web/test/menu-style.test.tsnew file mode 100644index 00000000..cc6e8fd5--- /dev/null+++ b/packages/web/test/menu-style.test.ts@@ -0,0 +1,42 @@+/**+ * One look for every picker and menu: Select's panel, row states and check mark+ * (components/ui/field.tsx: `menuPanelClass`, `menuRowTone`, `ChoiceCheck`), shared by Select,+ * OptionMenu, Dropdown and the pickers built on Dropdown. Checked as source, because the web+ * suite renders no DOM.+ */+import { renderToStaticMarkup } from "react-dom/server";+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ChoiceCheck, menuRowTone } from "../src/components/ui/field";+import { scanSources, sourceFile } from "./helpers/roots";++const SCAN = scanSources();+const text = (id: string) => sourceFile(SCAN, `packages/web/src/${id}`).text;++describe("menus and pickers", () => {+ it("open Select's panel", () => {+ for (const id of [+ "components/ui/select.tsx",+ "components/ui/option-menu.tsx",+ "components/ui/dropdown.tsx",+ ]) {+ expect(text(id), id).toContain("${menuPanelClass}");+ }+ });++ it("mark the current choice with Select's check, never a typed ✓", () => {+ const typed = SCAN.files+ .filter((file) => file.root === "web" && file.name.endsWith(".tsx"))+ .filter((file) => /["'`]✓["'`]/.test(file.text))+ .map((file) => file.id);+ expect(typed).toEqual([]);+ expect(renderToStaticMarkup(createElement(ChoiceCheck, { on: true }))).toContain("<svg");+ expect(renderToStaticMarkup(createElement(ChoiceCheck, { on: false }))).not.toContain("<svg");+ });++ it("fill the current choice and only hover the rest", () => {+ expect(menuRowTone(true)).toContain("font-medium");+ expect(menuRowTone(true)).not.toContain("hover:");+ expect(menuRowTone(false)).toContain("hover:bg-gray-100");+ });+});diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex 9544b611..741930a0 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -158,7 +158,7 @@ describe("MessagingBindingBody", () => {// reading "enable connection" does not say. It is semantics, so it is disclosed: on the// control, where nothing below has to move to make room for it.const html = render(stateOf("feishu"));- expect(html).toContain(`title="${S.messaging.bindByEnableHint}"`);+ expect(html).toContain(`data-tooltip="${S.messaging.bindByEnableHint}"`);expect(html).not.toContain(`>${S.messaging.bindByEnableHint}<`);});@@ -186,7 +186,7 @@ describe("MessagingBindingBody", () => {expect(html.slice(rowAt, html.indexOf(lastError, rowAt))).toContain("</div>");// Bounded so an error still cannot push the probes far, with the whole text on hover.expect(html).toContain("line-clamp-2");- expect(html).toContain(`title="${lastError}"`);+ expect(html).toContain(`data-tooltip="${lastError}"`);});it('closes the form with the delivery options, each explanation behind its label\'s "?"', () => {@@ -337,7 +337,7 @@ describe("MessagingBindingBody", () => {// record on a later success, so a rights problem fixed three days ago would otherwise// read as live — and a hover-only title is unreachable on a touch screen.expect(failed).toContain(`>${S.messaging.deliveryFailedSend(formatDateTime(at), detail)}</p>`);- expect(failed).toContain(`title="${detail}"`);+ expect(failed).toContain(`data-tooltip="${detail}"`);// Arrival is still reported: a send failure is not a delivery failure.expect(failed).toContain(S.messaging.inboundLastAt(formatDateTime("2026-08-26T09:30:00.000Z")));});diff --git a/packages/web/test/modal-focus.test.ts b/packages/web/test/modal-focus.test.tsindex 5fe3df80..98364b8f 100644--- a/packages/web/test/modal-focus.test.ts+++ b/packages/web/test/modal-focus.test.ts@@ -14,19 +14,23 @@* branch names only half the dialogs, and a restore target read one commit too late is a* dialog that hands focus back to itself.*/-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import { nextFocusIndex } from "../src/components/ui/modal";--const modal = readFileSync(- fileURLToPath(new URL("../src/components/ui/modal.tsx", import.meta.url)),- "utf8",-);-const dropdown = readFileSync(- fileURLToPath(new URL("../src/components/ui/dropdown.tsx", import.meta.url)),- "utf8",-);+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";++const SCAN = scanSources();+const MODAL = "packages/web/src/components/ui/modal.tsx";+const DROPDOWN = "packages/web/src/components/ui/dropdown.tsx";+const modal = sourceFile(SCAN, MODAL).text;+const dropdown = sourceFile(SCAN, DROPDOWN).text;++describe("the dialog primitives' sources", () => {+ it("scan every source root, and find Modal and Dropdown in one place each", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, MODAL);+ expectSingleHome(SCAN, DROPDOWN);+ });+});/** The panel div's opening tag — the element carrying the dialog's role and its focus wiring. */function panelTag(): string {diff --git a/packages/web/test/no-native-title.test.ts b/packages/web/test/no-native-title.test.tsnew file mode 100644index 00000000..be03346e--- /dev/null+++ b/packages/web/test/no-native-title.test.ts@@ -0,0 +1,261 @@+/**+ * No native `title` tooltips in the Web App.+ *+ * Every hover hint shows in the shared tooltip (components/ui/tooltip.tsx): through+ * `data-tooltip` on the element, read by the one `TooltipLayer`, or a `<Tooltip>` wrapper. A+ * native `title` waits about a second, cannot be themed and never shows on keyboard focus, so+ * one left behind is a hint that looks and behaves unlike every other in the app.+ *+ * The check parses the real JSX with the TypeScript parser, because whether `title` is an+ * attribute of a DOM element or a prop of a component (a Modal's heading, an EmptyState's) is a+ * question about the element it sits on, which a regex cannot answer. It fails on a `title`+ * attribute of an intrinsic element, written directly or inside a spread object literal.+ * Components that pass their own props through to a DOM element (Button, Input, Switch) turn+ * `title` into `data-tooltip` themselves.+ *+ * Exempt, because the platform needs them: `<iframe title>`, which names the frame to+ * assistive technology and shows no tooltip; and an SVG `<title>` child, which is an element,+ * not this attribute (the app's own icons use `data-tooltip` on the `<svg>` instead).+ */+import ts from "typescript";+import { describe, expect, it } from "vitest";+import { expectEveryRootScanned, scanSources } from "./helpers/roots";+import type { SourceFile } from "./helpers/roots";+import { tooltipRequest } from "../src/components/ui/tooltip";++/** Intrinsic elements whose `title` the platform needs. */+const TITLE_ALLOWED_ON = new Set(["iframe"]);++function nativeTitles(file: Pick<SourceFile, "path" | "text" | "id">): string[] {+ const source = ts.createSourceFile(+ file.path,+ file.text,+ ts.ScriptTarget.Latest,+ /* setParentNodes */ true,+ ts.ScriptKind.TSX,+ );+ const hits: string[] = [];+ const at = (node: ts.Node) =>+ `${file.id}:${source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1}`;+ const visit = (node: ts.Node): void => {+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {+ const tag = node.tagName.getText(source);+ const intrinsic = /^[a-z][\w-]*$/.test(tag);+ if (intrinsic && !TITLE_ALLOWED_ON.has(tag)) {+ for (const attr of node.attributes.properties) {+ if (ts.isJsxAttribute(attr) && attr.name.getText(source) === "title") {+ hits.push(`${at(attr)} <${tag} title>`);+ }+ if (ts.isJsxSpreadAttribute(attr)) {+ const spreadTitle = (n: ts.Node): void => {+ if (+ (ts.isPropertyAssignment(n) || ts.isShorthandPropertyAssignment(n)) &&+ n.name.getText(source).replace(/["']/g, "") === "title"+ ) {+ hits.push(`${at(n)} <${tag} {...{ title }}>`);+ }+ ts.forEachChild(n, spreadTitle);+ };+ spreadTitle(attr.expression);+ }+ }+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return hits;+}++/** Form controls take their name from a label element, which a static check cannot follow. */+const NAMED_BY_LABEL = new Set(["input", "textarea", "select"]);++/** Components that render marks, never words: an element holding only these has no text. */+const WORDLESS_COMPONENT = /^(?:\w*Icon|\w*Glyph\w*|Chevron\w*|\w*Avatar|UpdateDot|StatusIcon)$/;++type JsxTagged = ts.JsxElement | ts.JsxSelfClosingElement;++const openingOf = (node: JsxTagged) => (ts.isJsxElement(node) ? node.openingElement : node);++/** Whether an attribute list sets `name`, directly or in a spread object literal. */+function sets(attributes: ts.JsxAttributes, names: readonly string[], source: ts.SourceFile) {+ return attributes.properties.some((attr) => {+ if (ts.isJsxAttribute(attr)) return names.includes(attr.name.getText(source));+ if (!ts.isJsxSpreadAttribute(attr)) return false;+ let found = false;+ const walk = (n: ts.Node): void => {+ if (+ (ts.isPropertyAssignment(n) || ts.isShorthandPropertyAssignment(n)) &&+ names.includes(n.name.getText(source).replace(/["']/g, ""))+ ) {+ found = true;+ }+ ts.forEachChild(n, walk);+ };+ walk(attr.expression);+ return found;+ });+}++/** A spread of something other than an object literal: it may set anything, a name included. */+const opaqueSpread = (attributes: ts.JsxAttributes) =>+ attributes.properties.some(+ (attr) =>+ ts.isJsxSpreadAttribute(attr) &&+ !ts.isObjectLiteralExpression(attr.expression) &&+ !ts.isParenthesizedExpression(attr.expression),+ );++/** Whether the children put words (or a named element) in front of assistive technology. */+function hasContent(children: ts.NodeArray<ts.JsxChild>, source: ts.SourceFile): boolean {+ return children.some((child) => {+ if (ts.isJsxText(child)) return child.getText(source).trim() !== "";+ if (ts.isJsxExpression(child)) return child.expression !== undefined;+ if (ts.isJsxFragment(child)) return hasContent(child.children, source);+ if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child)) {+ const opening = openingOf(child);+ const tag = opening.tagName.getText(source);+ if (!/^[a-z]/.test(tag)) return !WORDLESS_COMPONENT.test(tag);+ if (sets(opening.attributes, ["aria-label", "aria-labelledby"], source)) return true;+ return ts.isJsxElement(child) && hasContent(child.children, source);+ }+ return false;+ });+}++/**+ * Elements whose hint is their only name: a `data-tooltip` on an element with no words in it+ * and no aria-label. The shared tooltip names nothing to assistive technology, so such an+ * element reads as unlabeled. An element inside an aria-hidden or role="img" ancestor is part+ * of a named or hidden whole, and is not asked for a name of its own.+ */+function unnamedHints(file: Pick<SourceFile, "path" | "text" | "id">): string[] {+ const source = ts.createSourceFile(+ file.path,+ file.text,+ ts.ScriptTarget.Latest,+ /* setParentNodes */ true,+ ts.ScriptKind.TSX,+ );+ const hits: string[] = [];+ const insideNamedWhole = (node: ts.Node): boolean => {+ for (let up = node.parent; up !== undefined; up = up.parent) {+ if (ts.isJsxElement(up)) {+ const attrs = up.openingElement.attributes;+ if (sets(attrs, ["aria-hidden"], source)) return true;+ const role = attrs.properties.find(+ (a) => ts.isJsxAttribute(a) && a.name.getText(source) === "role",+ );+ if (role !== undefined && role.getText(source).includes('"img"')) return true;+ }+ }+ return false;+ };+ const visit = (node: ts.Node): void => {+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {+ const opening = openingOf(node);+ const tag = opening.tagName.getText(source);+ const attrs = opening.attributes;+ if (+ /^[a-z]/.test(tag) &&+ !NAMED_BY_LABEL.has(tag) &&+ sets(attrs, ["data-tooltip"], source) &&+ !sets(attrs, ["aria-label", "aria-labelledby", "aria-hidden"], source) &&+ !opaqueSpread(attrs) &&+ !(ts.isJsxElement(node) && hasContent(node.children, source)) &&+ !insideNamedWhole(node)+ ) {+ const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;+ hits.push(`${file.id}:${line} <${tag} data-tooltip> with no words and no aria-label`);+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return hits;+}++describe("native title tooltips", () => {+ const scan = scanSources();++ it("are not used anywhere in the web app", () => {+ expectEveryRootScanned(scan);+ const hits = scan.files+ .filter((file) => file.root === "web" && file.name.endsWith(".tsx"))+ .flatMap(nativeTitles);+ expect(+ hits,+ "Use data-tooltip (read by TooltipLayer) or <Tooltip>, and an aria-label where the title " ++ "was the element's only name.",+ ).toEqual([]);+ });++ it("leave no element whose hint was its only name without an aria-label", () => {+ const hits = scan.files+ .filter((file) => file.root === "web" && file.name.endsWith(".tsx"))+ .flatMap(unnamedHints);+ expect(+ hits,+ "A data-tooltip names nothing to assistive technology: give a wordless element an " ++ "aria-label (namedHint() in tooltip.tsx does both for a mark), or show the words.",+ ).toEqual([]);+ });++ it("are found on known shapes, and a component's title prop is left alone", () => {+ const check = (text: string) => nativeTitles({ path: "/virtual/a.tsx", id: "a.tsx", text });+ expect(check('const A = () => <span title="x">y</span>;')).toHaveLength(1);+ expect(check("const A = () => <button {...(on ? { title: t } : {})} />;")).toHaveLength(1);+ expect(check("const A = () => <div {...{ title }} />;")).toHaveLength(1);+ expect(check('const A = () => <Modal title="Heading" />;')).toEqual([]);+ expect(check('const A = () => <iframe title="Preview" />;')).toEqual([]);+ expect(check('const A = () => <span data-tooltip="x" aria-label="x" />;')).toEqual([]);+ });++ it("asks a wordless hinted element for a name, and nothing more", () => {+ const check = (text: string) => unnamedHints({ path: "/virtual/a.tsx", id: "a.tsx", text });+ expect(+ check('const A = () => <button data-tooltip="Copy"><CopyIcon /></button>;'),+ ).toHaveLength(1);+ expect(check('const A = () => <span data-tooltip="Queued" className="dot" />;')).toHaveLength(+ 1,+ );+ expect(+ check('const A = () => <button data-tooltip="Copy" aria-label="Copy"><CopyIcon /></button>;'),+ ).toEqual([]);+ expect(check('const A = () => <button data-tooltip="More">{label}</button>;')).toEqual([]);+ expect(check('const A = () => <span {...namedHint("Bar 3")} />;')).toEqual([]);+ expect(+ check(+ 'const A = () => <div role="img" aria-label="Board"><span data-tooltip="Open 3" /></div>;',+ ),+ ).toEqual([]);+ });+});++describe("a data-tooltip request", () => {+ const el = (attrs: Record<string, string>) => ({+ getAttribute: (name: string) => attrs[name] ?? null,+ });++ it("reads the text, the kind and the side, defaulting to a label below", () => {+ expect(tooltipRequest(el({ "data-tooltip": "Rename" }))).toEqual({+ label: "Rename",+ content: "label",+ placement: "bottom",+ });+ expect(+ tooltipRequest(+ el({+ "data-tooltip": "npm run dev",+ "data-tooltip-content": "code",+ "data-tooltip-placement": "right",+ }),+ ),+ ).toEqual({ label: "npm run dev", content: "code", placement: "right" });+ });++ it("asks for nothing when the text is missing or blank", () => {+ expect(tooltipRequest(el({}))).toBeNull();+ expect(tooltipRequest(el({ "data-tooltip": " " }))).toBeNull();+ });+});diff --git a/packages/web/test/notice-chart-hooks.test.ts b/packages/web/test/notice-chart-hooks.test.tsnew file mode 100644index 00000000..59e8cca1--- /dev/null+++ b/packages/web/test/notice-chart-hooks.test.ts@@ -0,0 +1,146 @@+/**+ * The notice and chart hooks on the real app: every notice strip renders through NoticeStrip+ * (so it carries `ui-notice` and a `data-tone` in the hook's words), toasts carry the same hook,+ * and the charts' roots carry `ui-chart` with their parts named by literal `data-part` values.+ */+import ts from "typescript";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { NOTICE_TONE, NoticeStrip } from "../src/components/ui/notice-strip";+import { scanSources, sourceFile } from "./helpers/roots";++const SCAN = scanSources();+const text = (id: string) => sourceFile(SCAN, `packages/web/src/${id}`).text;++describe("notices", () => {+ it("render the hook with the tone in the hook's words", () => {+ const html = renderToStaticMarkup(+ createElement(NoticeStrip, { tone: "attention", className: "px-3" }, "Heads up"),+ );+ expect(html).toContain("ui-notice");+ expect(html).toContain('data-tone="warning"');+ expect(new Set(Object.values(NOTICE_TONE))).toEqual(+ new Set(["info", "success", "warning", "danger", "neutral"]),+ );+ });++ it("go through NoticeStrip, and toasts carry the hook too", () => {+ const inline = SCAN.files+ .filter((file) => file.root === "web" && file.name.endsWith(".tsx"))+ .filter((file) => !file.id.endsWith("components/ui/notice-strip.tsx"))+ .filter((file) => /toneStrip[.[]/.test(file.text.replace(/\/\*[\s\S]*?\*\//g, "")))+ .map((file) => file.id);+ expect(inline).toEqual([]);+ expect(text("components/ui/toast.tsx")).toContain("ui-notice");+ });+});++/** Icon renderers: a mark drawn by one of these is a glyph, not words. */+const ICON_TAG = /^(?:GlyphIcon|Glyph|\w+Icon)$/;++/**+ * Leading marks inside a NoticeStrip that do not sit in `data-slot="icon"`: a self-closing,+ * aria-hidden span (a dot) or an icon renderer, outside any button or link (an action's own+ * glyph is not the notice's mark). Frost and Console draw their own tone mark and hide the slot,+ * so a mark outside it would show twice.+ */+function unslottedMarks(file: { path: string; text: string; id: string }): string[] {+ const source = ts.createSourceFile(+ file.path,+ file.text,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );+ const hits: string[] = [];+ const tagOf = (n: ts.JsxElement | ts.JsxSelfClosingElement) =>+ (ts.isJsxElement(n) ? n.openingElement : n).tagName.getText(source);+ const attrsOf = (n: ts.JsxElement | ts.JsxSelfClosingElement) =>+ (ts.isJsxElement(n) ? n.openingElement : n).attributes;+ const has = (n: ts.JsxElement | ts.JsxSelfClosingElement, name: string, value?: string) =>+ attrsOf(n).properties.some(+ (a) =>+ ts.isJsxAttribute(a) &&+ a.name.getText(source) === name &&+ (value === undefined || a.initializer?.getText(source) === `"${value}"`),+ );+ const walk = (node: ts.Node, slotted: boolean, inAction: boolean): void => {+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {+ const tag = tagOf(node);+ const slot = slotted || has(node, "data-slot", "icon");+ const action = inAction || /^(?:button|a|Button)$/.test(tag);+ const dot = ts.isJsxSelfClosingElement(node) && tag === "span" && has(node, "aria-hidden");+ if (!slot && !action && (dot || ICON_TAG.test(tag))) {+ const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;+ hits.push(`${file.id}:${line} <${tag}> in a NoticeStrip without data-slot="icon"`);+ }+ ts.forEachChild(node, (child) => walk(child, slot, action));+ return;+ }+ ts.forEachChild(node, (child) => walk(child, slotted, inAction));+ };+ const visit = (node: ts.Node): void => {+ if (ts.isJsxElement(node) && tagOf(node) === "NoticeStrip") {+ for (const child of node.children) walk(child, false, false);+ return;+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return hits;+}++describe("a notice's own mark", () => {+ it("sits in the icon slot, so a theme that draws its own can hide it", () => {+ const hits = SCAN.files+ .filter((file) => file.root === "web" && file.name.endsWith(".tsx"))+ .flatMap(unslottedMarks);+ expect(hits).toEqual([]);+ });++ it("is found on known shapes", () => {+ const check = (text: string) => unslottedMarks({ path: "/v/a.tsx", id: "a.tsx", text });+ expect(+ check(+ 'const A = () => <NoticeStrip tone="danger"><span aria-hidden className="dot" />x</NoticeStrip>;',+ ),+ ).toHaveLength(1);+ expect(+ check(+ 'const A = () => <NoticeStrip tone="danger"><p><GlyphIcon d={D} />x</p></NoticeStrip>;',+ ),+ ).toHaveLength(1);+ expect(+ check(+ 'const A = () => <NoticeStrip tone="danger"><span data-slot="icon"><GlyphIcon d={D} /></span>x</NoticeStrip>;',+ ),+ ).toEqual([]);+ expect(+ check(+ 'const A = () => <NoticeStrip tone="danger">x<Button><CloseIcon /></Button></NoticeStrip>;',+ ),+ ).toEqual([]);+ });+});++describe("charts", () => {+ it("carry ui-chart on their roots and name their parts", () => {+ for (const id of [+ "features/usage/chart-svg.tsx",+ "components/ui/token-donut.tsx",+ "features/benchmark/score-sparkline.tsx",+ "features/traces/timeline-chart.tsx",+ "features/agents/activity-sparkline.tsx",+ ]) {+ expect(text(id), id).toContain("ui-chart");+ }+ // The parts are written by the chart primitives, the one place marks are drawn.+ const parts = ["components/ui/chart/marks.tsx", "components/ui/chart/timeline-bar.tsx"]+ .map(text)+ .join("\n");+ for (const part of ["series", "area", "bar", "point", "grid", "axis"]) {+ expect(parts, part).toMatch(new RegExp(`data-part(?:=|": )"${part}"`));+ }+ });+});diff --git a/packages/web/test/path-capsules.test.ts b/packages/web/test/path-capsules.test.tsindex 9e1fb34c..640c21e8 100644--- a/packages/web/test/path-capsules.test.ts+++ b/packages/web/test/path-capsules.test.ts@@ -230,7 +230,7 @@ describe("ticket Markdown with capsules", () => {const html = render(`结果在 ${LAB}/workspace/experiments/dep-eval/。`);expect(capsuleCount(html)).toBe(1);expect(html).toContain(">dep-eval</span></button>");- expect(html).toContain(`title="${LAB.replace(/</g, "<").replace(/>/g, ">")}`);+ expect(html).toContain(`data-tooltip="${LAB.replace(/</g, "<").replace(/>/g, ">")}`);expect(html).toContain("。");expect(html).not.toContain("organizations/co_research_paper_lab/workspace/experiments/dep-eval/。",diff --git a/packages/web/test/portal-panel-dismiss.test.ts b/packages/web/test/portal-panel-dismiss.test.tsindex 849483e0..85747f0e 100644--- a/packages/web/test/portal-panel-dismiss.test.ts+++ b/packages/web/test/portal-panel-dismiss.test.ts@@ -17,23 +17,12 @@* hook's consumers rather than listing them, and a fifth one is covered on the day it is* written.*/-import { readdirSync, readFileSync, statSync } from "node:fs";-import { join } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";-const SRC = fileURLToPath(new URL("../src", import.meta.url));-const HOOK = join(SRC, "components", "ui", "use-portal-panel.ts");--/** Every .ts/.tsx under src, as absolute paths (required-mark.test.ts convention). */-function sourceFiles(dir = SRC, out: string[] = []): string[] {- for (const name of readdirSync(dir)) {- const path = join(dir, name);- if (statSync(path).isDirectory()) sourceFiles(path, out);- else if (/\.tsx?$/.test(name)) out.push(path);- }- return out;-}+/** Every .ts/.tsx under web and the shared UI package: a consumer is covered on either side. */+const SCAN = scanSources([".ts", ".tsx"]);+const HOOK = "packages/web/src/components/ui/use-portal-panel.ts";/** The body of a handler declared as `const <name> = ...` up to its closing `};`. */function handler(src: string, name: string): string {@@ -43,7 +32,12 @@ function handler(src: string, name: string): string {}describe("use-portal-panel scroll dismissal", () => {- const hook = readFileSync(HOOK, "utf8");+ const hook = sourceFile(SCAN, HOOK).text;++ it("reads every source root, and finds the hook in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, HOOK);+ });it("asks whether the scroll moved this panel's trigger before closing", () => {const onScroll = handler(hook, "onScroll");@@ -69,22 +63,22 @@ describe("use-portal-panel scroll dismissal", () => {describe("use-portal-panel consumers", () => {/** Files that open a panel through the hook — the hook's own module excluded. */- const consumers = sourceFiles().filter(- (path) => path !== HOOK && readFileSync(path, "utf8").includes("usePortalPanel({"),- );+ const consumers = SCAN.files+ .filter((file) => file.id !== HOOK && file.text.includes("usePortalPanel({"))+ .map((file) => file.id);it("finds the call sites the rule has to cover, including the reported one", () => {// A scan that silently matched nothing would pass every assertion below. The context// ring is the panel the failure was reported against: it is opened to watch the context// fill while a run streams, which is exactly when the message list scrolls itself.expect(consumers.length).toBeGreaterThanOrEqual(4);- expect(consumers).toContain(join(SRC, "features", "chat", "context-gauge.tsx"));+ expect(consumers).toContain("packages/web/src/features/chat/context-gauge.tsx");});it("each attaches the hook's triggerRef, so the ownership test has an element to read", () => {- const missing = consumers- .filter((path) => !readFileSync(path, "utf8").includes("ref={triggerRef}"))- .map((path) => path.slice(SRC.length + 1));+ const missing = consumers.filter(+ (id) => !sourceFile(SCAN, id).text.includes("ref={triggerRef}"),+ );expect(missing).toEqual([]);});});diff --git a/packages/web/test/qq-scan-connect.test.ts b/packages/web/test/qq-scan-connect.test.tsindex 3179b584..b17d77a3 100644--- a/packages/web/test/qq-scan-connect.test.ts+++ b/packages/web/test/qq-scan-connect.test.ts@@ -82,8 +82,8 @@ describe("QQScanConnect", () => {expect(html).toContain("disabled=");// A rebind would swap the credentials under a live connector, so it is refused with a// reason rather than silently doing it.- expect(html).toContain(`title="${S.qq.scanDisableFirst}"`);- expect(render(false)).not.toContain(`title="${S.qq.scanDisableFirst}"`);+ expect(html).toContain(`data-tooltip="${S.qq.scanDisableFirst}"`);+ expect(render(false)).not.toContain(`data-tooltip="${S.qq.scanDisableFirst}"`);});});diff --git a/packages/web/test/required-mark.test.ts b/packages/web/test/required-mark.test.tsindex bbcefc79..d61ca0e0 100644--- a/packages/web/test/required-mark.test.ts+++ b/packages/web/test/required-mark.test.ts@@ -13,26 +13,17 @@import { describe, expect, it } from "vitest";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";-import { readdirSync, readFileSync, statSync } from "node:fs";-import { join, sep } from "node:path";-import { fileURLToPath } from "node:url";import ts from "typescript";import { Input } from "../src/components/ui/input";import { RequiredMark } from "../src/components/ui/field";import { zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";-const SRC = fileURLToPath(new URL("../src", import.meta.url));-const FIELD = join(SRC, "components", "ui", "field.tsx");--function tsxFiles(dir = SRC, out: string[] = []): string[] {- for (const name of readdirSync(dir)) {- const path = join(dir, name);- if (statSync(path).isDirectory()) tsxFiles(path, out);- else if (name.endsWith(".tsx")) out.push(path);- }- return out;-}+/** Web and the shared UI package: a hand-rolled mark is a second spelling on either side. */+const SCAN = scanSources();+/** The one place the mark is allowed to be spelled. */+const FIELD = "packages/web/src/components/ui/field.tsx";/*** Every string literal reachable from a node, joined. `className` is written four ways here —@@ -73,17 +64,20 @@ function childText(node: ts.JsxElement): string {.trim();}-/** Every element that paints a lone "*" in a red ink class — i.e. a hand-rolled required mark. */-function marksIn(path: string, text: string): string[] {+/**+ * Every element that paints a lone "*" in a red ink class — i.e. a hand-rolled required mark — as+ * "id:line".+ */+function marksIn(id: string, text: string): string[] {const found: string[] = [];- const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX);+ const source = ts.createSourceFile(id, text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX);const visit = (node: ts.Node): void => {// The children test is cheap and rejects all but a handful of the tree's ~2200 elements,// so it runs before the attribute walk.if (ts.isJsxElement(node) && childText(node) === "*") {if (classNameOf(node.openingElement).includes("text-red-")) {const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;- found.push(`${path.slice(SRC.length + 1).replaceAll(sep, "/")}:${line}`);+ found.push(`${id}:${line}`);}}ts.forEachChild(node, visit);@@ -94,9 +88,9 @@ function marksIn(path: string, text: string): string[] {function handRolledMarks(): string[] {const found: string[] = [];- for (const path of tsxFiles()) {- if (path === FIELD) continue; // the one place the mark is allowed to be spelled- found.push(...marksIn(path, readFileSync(path, "utf8")));+ for (const file of SCAN.files) {+ if (!file.name.endsWith(".tsx") || file.id === FIELD) continue;+ found.push(...marksIn(file.id, file.text));}return found.sort();}@@ -135,6 +129,11 @@ const PROSE_EXCEPTIONS: Record<"zh" | "en", ReadonlySet<string>> = {};describe("required mark", () => {+ it("scans every source root, and finds the field module in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, FIELD);+ });+it("renders only when the field is required", () => {const required = renderToStaticMarkup(createElement(Input, { label: "Name", required: true, value: "", readOnly: true }),@@ -177,7 +176,7 @@ describe("required mark", () => {it("finds a hand-rolled mark however its className is written", () => {// Without this the scan above could silently stop matching and still report a clean tree.- const probe = join(SRC, "probe.tsx");+ const probe = "packages/web/src/probe.tsx";const shapes = ['const a = <span className="ml-0.5 text-red-500">*</span>;',"const b = <span className={`ml-0.5 text-red-500`}>*</span>;",diff --git a/packages/web/test/session-activity.test.ts b/packages/web/test/session-activity.test.tsindex 3e5a1727..b0576562 100644--- a/packages/web/test/session-activity.test.ts+++ b/packages/web/test/session-activity.test.ts@@ -14,8 +14,16 @@ import { BACKGROUND_TASKS_ICON, SCHEDULE_ICON } from "../src/components/ui/iconsimport { ICON_SIZE } from "../src/lib/icon-scale";import { S } from "../src/lib/strings";import { toneInk } from "../src/lib/tone";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";++const SCAN = scanSources();++describe("the activity marks' sources", () => {+ it("scan every source root, and find the icon module in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, "packages/web/src/components/ui/session-activity-icon.tsx");+ });+});type Activity = Exclude<SessionActivity, null>;@@ -79,7 +87,7 @@ describe("BackgroundTasksMark", () => {it("names the count where it stands for a count", () => {const markup = render(S.chat.backgroundTasks(3), ICON_SIZE.rowMark);expect(markup).toContain(`aria-label="${S.chat.backgroundTasks(3)}"`);- expect(markup).toContain(`title="${S.chat.backgroundTasks(3)}"`);+ expect(markup).toContain(`data-tooltip="${S.chat.backgroundTasks(3)}"`);expect(markup).toContain('role="img"');expect(S.chat.backgroundTasks(3)).toContain("3");});@@ -113,7 +121,7 @@ describe("ScheduleMark", () => {expect(markup()).not.toContain(toneInk.busy);// Muted is the one tone allowed under 3:1, and only where the meaning is already in text.expect(markup()).toContain(`aria-label="${S.chat.sessionScheduled}"`);- expect(markup()).toContain(`title="${S.chat.sessionScheduled}"`);+ expect(markup()).toContain(`data-tooltip="${S.chat.sessionScheduled}"`);expect(markup()).toContain(`d="${SCHEDULE_ICON}"`);});});@@ -160,13 +168,13 @@ describe("SessionActivityIcon", () => {}});- it("gives the hourglass a hover tooltip through the svg title child", () => {+ it("gives every mark the shared hover tooltip", () => {for (const activity of ["running", "compacting"] as const) {- expect(render(activity)).toContain(`<title>${sessionActivityLabel(activity)}</title>`);+ expect(render(activity)).toContain(`data-tooltip="${sessionActivityLabel(activity)}"`);}- // The dot is an HTML span, so its tooltip is a plain title attribute.+ // The dot is an HTML span, so its tooltip is the shared one, read from data-tooltip.expect(render("completedUnread")).toContain(- `title="${sessionActivityLabel("completedUnread")}"`,+ `data-tooltip="${sessionActivityLabel("completedUnread")}"`,);});@@ -216,10 +224,7 @@ describe("SessionActivityIcon", () => {expect(markup).toMatch(/(height="12"|height:12px)/);}// The empty state's placeholder, read from the sidebar itself so it cannot drift apart.- const sidebar = readFileSync(- fileURLToPath(new URL("../src/components/layout/sidebar.tsx", import.meta.url)),- "utf8",- );+ const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;expect(sidebar).toMatch(/activity === null.*\n?.*className="block h-3 w-3 shrink-0"/);});});@@ -231,7 +236,11 @@ describe("SessionActivityIcon", () => {* traces in the same stylesheet need an explicit override for exactly that reason).*/describe("hourglass-turn reduced motion", () => {- const css = readFileSync(fileURLToPath(new URL("../src/styles.css", import.meta.url)), "utf8");+ // Every stylesheet under the scanned roots, so the keyframes are found wherever they move.+ const css = SCAN.files+ .filter((file) => file.name.endsWith(".css"))+ .map((file) => file.text)+ .join("\n");it("is an animation, so the global reduced-motion rule disables it", () => {expect(css).toMatch(/\.hourglass-turn\s*\{[^}]*animation:\s*hourglass-turn/);diff --git a/packages/web/test/session-row-menu.test.ts b/packages/web/test/session-row-menu.test.tsindex 890018fc..613b9eb3 100644--- a/packages/web/test/session-row-menu.test.ts+++ b/packages/web/test/session-row-menu.test.ts@@ -14,9 +14,6 @@* the exported manifests and label helpers rather than a rendered DOM* (title-reveal.test.ts convention).*/-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it } from "vitest";import {ARCHIVE_ICON,@@ -33,12 +30,23 @@ import { MESSAGING_RELAY_ICON } from "../src/components/ui/icons";import { STAT_ICONS } from "../src/lib/stat-icons";import { setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";++const SCAN = scanSources();+const ROW_MENU = "packages/web/src/components/ui/session-row-menu.tsx";/** Every test that switches locale puts the default (zh) back. */afterEach(() => setActiveStrings(zh));const RESTING = { archived: false, pinned: false };+describe("the row menu's sources", () => {+ it("scan every source root, and find the row menu in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, ROW_MENU);+ });+});+describe("HOVER_ROW_ACTIONS", () => {it("is archive alone — the ellipsis beside it is the menu's pointer entry, not an action", () => {expect([...HOVER_ROW_ACTIONS]).toEqual(["archive"]);@@ -98,10 +106,7 @@ describe("the hover buttons' CSS contract", () => {// Node-only suite, so this is asserted against the source text (title-reveal.test.ts// convention). It is worth pinning: an invisible button still takes taps, and these are// invisible for the whole of every touch session, delete included.- const source = readFileSync(- resolve(dirname(fileURLToPath(import.meta.url)), "../src/components/ui/session-row-menu.tsx"),- "utf8",- );+ const source = sourceFile(SCAN, ROW_MENU).text;it("gates pointer events on the same conditions as visibility, leaving no phantom tap target", () => {expect(source).toContain("pointer-events-none");diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.tsindex 723939cc..29ef809f 100644--- a/packages/web/test/settings-sections.test.ts+++ b/packages/web/test/settings-sections.test.ts@@ -57,6 +57,7 @@ describe("visibleSettingsSections", () => {"appearance","shortcuts","account",+ "credits","proxy","uploads","company",@@ -76,6 +77,7 @@ describe("visibleSettingsSections", () => {"appearance","shortcuts","account",+ "credits",]);});@@ -88,6 +90,7 @@ describe("visibleSettingsSections", () => {"general","appearance","shortcuts",+ "credits","proxy","uploads","company",@@ -104,6 +107,7 @@ describe("visibleSettingsSections", () => {"appearance","shortcuts","account",+ "credits","proxy","uploads","company",@@ -165,6 +169,22 @@ describe("the Settings dialog", () => {expect(source).not.toContain("SECTION_RULES");});+ it("renders the credits page, which lists the bundled fonts and nothing before them", () => {+ // MiSans's licence asks the app to credit it wherever it runs, so the page is visible to+ // every viewer (pinned above); the list is the whole page.+ expect(source).toContain('{current === "credits" && <CreditsSection />}');+ const credits = readFileSync(+ resolve(+ dirname(fileURLToPath(import.meta.url)),+ "../src/features/settings/credits-section.tsx",+ ),+ "utf8",+ );+ expect(credits).not.toContain("S.settings.fontCredit");+ expect(credits).toContain("FONT_CREDITS.map");+ expect(credits).toContain("aria-controls={panelId}");+ });+it("resolves the page it renders through the same gate on every render", () => {// The active page is a state value, not a right: a viewer who loses admin mid-dialog// must fall back to their own first page rather than keep rendering the admin form.diff --git a/packages/web/test/shortcuts-section.test.ts b/packages/web/test/shortcuts-section.test.tsindex 56b4bab0..8c9e204e 100644--- a/packages/web/test/shortcuts-section.test.ts+++ b/packages/web/test/shortcuts-section.test.ts@@ -81,14 +81,14 @@ describe("ShortcutsSection", () => {it("offers the per-row reset only on an overridden row, and Reset all only when something is", () => {const clean = render();- expect(count(clean, `title="${S.shortcuts.resetRow}"`)).toBe(0);+ expect(count(clean, `data-tooltip="${S.shortcuts.resetRow}"`)).toBe(0);expect(clean).toMatch(/<button[^>]* disabled=""[^>]*>[^<]*全部恢复默认/);configureKeybindingsStoreForTests({storage: memStorage({ v: 1, linux: { "editor.save": null } }),});const one = render();- expect(count(one, `title="${S.shortcuts.resetRow}"`)).toBe(1);+ expect(count(one, `data-tooltip="${S.shortcuts.resetRow}"`)).toBe(1);expect(one).toContain(S.shortcuts.unbound);expect(one).not.toMatch(/<button[^>]* disabled=""[^>]*>[^<]*全部恢复默认/);});diff --git a/packages/web/test/stream-selection-menu.test.ts b/packages/web/test/stream-selection-menu.test.tsindex 4abaf280..848cead0 100644--- a/packages/web/test/stream-selection-menu.test.ts+++ b/packages/web/test/stream-selection-menu.test.ts@@ -154,7 +154,7 @@ describe("Add to conversation", () => {);const name = excerptLabel(EXCERPT);expect(name.endsWith("…")).toBe(true);- expect(chip).toContain(`title="${EXCERPT}"`);+ expect(chip).toContain(`data-tooltip="${EXCERPT}"`);expect(chip).toContain(`>${name}</span>`);expect(chip).toContain(`d="${QUOTE_ICON}"`);expect(chip).toContain(`aria-label="${S.files.removeReference} ${name}"`);diff --git a/packages/web/test/theme-prefs.test.ts b/packages/web/test/theme-prefs.test.tsnew file mode 100644index 00000000..c8e199e7--- /dev/null+++ b/packages/web/test/theme-prefs.test.ts@@ -0,0 +1,217 @@+/**+ * The appearance preferences: what a stored value reads back as (theme, accent, text size with+ * the legacy migration, font pairing), what they put on <html>, and the Appearance section's+ * shape. The web suite runs in node with no DOM, so the root is a small fake that answers both+ * the `dataset` and the attribute API, and the section is checked as source.+ */+import fs from "node:fs";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";+import { ACCENT_PRESET_IDS, THEME_IDS } from "@prismshadow/penguin-ui";+import {+ FONT_CJK_OPTIONS,+ FONT_LATIN_OPTIONS,+ TEXT_SIZES,+ THEME_STORAGE_KEYS,+ applyThemeAttributes,+} from "@prismshadow/penguin-ui/boot";+import { effectiveAccent, readThemePrefs } from "../src/state/theme-prefs";+import type { PrefStorage } from "../src/state/theme-prefs";+import { fontChoices } from "../src/features/settings/appearance-section";+import { setActiveStrings, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++afterEach(() => setActiveStrings(zh));++/** The three-step size of earlier releases, spelled out: it is on disk whatever the code calls it. */+const LEGACY_TEXT_SIZE_KEY = "penguin.fontScale";++function memStorage(entries: Record<string, string> = {}): PrefStorage & {+ map: Map<string, string>;+} {+ const map = new Map(Object.entries(entries));+ return {+ map,+ getItem: (key) => map.get(key) ?? null,+ setItem: (key, value) => void map.set(key, value),+ removeItem: (key) => void map.delete(key),+ };+}++/** An <html> stand-in: attributes behind both `dataset` and get/set/removeAttribute. */+function fakeRoot() {+ const attrs = new Map<string, string>();+ const classes = new Set<string>();+ const attrOf = (key: string) => `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;+ const dataset = new Proxy({} as Record<string, string>, {+ get: (_, key) => (typeof key === "string" ? attrs.get(attrOf(key)) : undefined),+ set: (_, key, value) => {+ attrs.set(attrOf(String(key)), String(value));+ return true;+ },+ deleteProperty: (_, key) => {+ attrs.delete(attrOf(String(key)));+ return true;+ },+ has: (_, key) => attrs.has(attrOf(String(key))),+ });+ const style: Record<string, unknown> = {+ fontSize: "",+ setProperty: (name: string, value: string) => void (style[name] = value),+ removeProperty: (name: string) => void delete style[name],+ };+ const root = {+ dataset,+ style,+ classList: {+ toggle: (name: string, on?: boolean) => {+ const next = on ?? !classes.has(name);+ if (next) classes.add(name);+ else classes.delete(name);+ return next;+ },+ add: (name: string) => void classes.add(name),+ remove: (name: string) => void classes.delete(name),+ contains: (name: string) => classes.has(name),+ },+ setAttribute: (name: string, value: string) => void attrs.set(name, value),+ removeAttribute: (name: string) => void attrs.delete(name),+ getAttribute: (name: string) => attrs.get(name) ?? null,+ hasAttribute: (name: string) => attrs.has(name),+ };+ return { root: root as unknown as HTMLElement, attrs, style };+}++describe("reading the stored appearance", () => {+ it("falls back to the defaults on an empty store: Primer, its own accent, 16px, its own faces", () => {+ expect(readThemePrefs(memStorage())).toEqual({+ themeId: "github",+ accent: "neutral",+ textSize: "m",+ fontLatin: "theme",+ fontCjk: "theme",+ });+ });++ it("migrates the three-step font scale by pixels, once, and drops the old key", () => {+ for (const [legacy, size] of [+ ["sm", "m"],+ ["md", "l"],+ ["lg", "xl"],+ ] as const) {+ const storage = memStorage({ [LEGACY_TEXT_SIZE_KEY]: legacy });+ expect(readThemePrefs(storage).textSize).toBe(size);+ expect(storage.map.get(THEME_STORAGE_KEYS.textSize)).toBe(size);+ expect(storage.map.has(LEGACY_TEXT_SIZE_KEY)).toBe(false);+ // The second read is a plain lookup of what the first one wrote.+ expect(readThemePrefs(storage).textSize).toBe(size);+ }+ });++ it("keeps a stored text size and reads anything unknown as the default", () => {+ for (const size of TEXT_SIZES) {+ expect(readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.textSize]: size })).textSize).toBe(+ size,+ );+ }+ expect(readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.textSize]: "huge" })).textSize).toBe(+ "m",+ );+ });++ it("validates the theme and the font faces against the package's lists", () => {+ const storage = memStorage({+ [THEME_STORAGE_KEYS.themeId]: "geek",+ [THEME_STORAGE_KEYS.fontLatin]: FONT_LATIN_OPTIONS.at(-1)!.id,+ [THEME_STORAGE_KEYS.fontCjk]: "comic-sans",+ });+ const prefs = readThemePrefs(storage);+ expect(prefs.themeId).toBe("geek");+ expect(prefs.fontLatin).toBe(FONT_LATIN_OPTIONS.at(-1)!.id);+ expect(prefs.fontCjk).toBe("theme");+ expect(readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.themeId]: "neon" })).themeId).toBe(+ "github",+ );+ });++ it("keeps another theme's accent as stored, and marks the theme's own in effect", () => {+ const prefs = readThemePrefs(memStorage({ [THEME_STORAGE_KEYS.accent]: "ocean" }));+ expect(prefs.accent).toBe("ocean");+ expect(effectiveAccent("modern", prefs.accent)).toBe("ocean");+ expect(effectiveAccent("github", prefs.accent)).toBe("neutral");+ expect(effectiveAccent("github", "blue")).toBe("blue");+ });+});++describe("the attributes the preferences put on <html>", () => {+ it("names a chosen face on the root and leaves the theme's own as no attribute", () => {+ const { root, attrs, style } = fakeRoot();+ const latin = FONT_LATIN_OPTIONS.find((option) => option.id !== "theme")!.id;+ const cjk = FONT_CJK_OPTIONS.find((option) => option.id !== "theme")!.id;+ applyThemeAttributes(root, {+ ...readThemePrefs(memStorage()),+ fontLatin: latin,+ fontCjk: cjk,+ textSize: "xl",+ });+ expect(attrs.get("data-font-latin")).toBe(latin);+ expect(attrs.get("data-font-cjk")).toBe(cjk);+ expect(attrs.has("data-theme")).toBe(false);+ expect(style.fontSize).toBe("20px");++ applyThemeAttributes(root, { fontLatin: "theme", fontCjk: "theme", themeId: "modern" });+ expect(attrs.has("data-font-latin")).toBe(false);+ expect(attrs.has("data-font-cjk")).toBe(false);+ expect(attrs.get("data-theme")).toBe("modern");+ });+});++describe("the Appearance section", () => {+ const source = fs.readFileSync(+ fileURLToPath(new URL("../src/features/settings/appearance-section.tsx", import.meta.url)),+ "utf8",+ );++ it("offers theme, mode, accent, text size and fonts first, in that order", () => {+ const order = [+ "S.settings.theme}",+ "S.settings.colorMode}",+ "S.settings.accent}",+ "S.settings.fontSize}",+ "S.settings.fonts}",+ "S.settings.terminalTheme}",+ ].map((label) => source.indexOf(`label={${label}`));+ expect(order.every((at) => at > 0)).toBe(true);+ expect([...order].sort((a, b) => a - b)).toEqual(order);+ });++ it("builds every choice from the package's lists, and the swatches from the active theme", () => {+ expect(source).toContain("THEME_IDS.map");+ expect(source).toContain("TEXT_SIZES.map");+ expect(source).toContain("cols={5}");+ expect(source).toContain("fontChoices(FONT_LATIN_OPTIONS)");+ expect(source).toContain("fontChoices(FONT_CJK_OPTIONS)");+ expect(source).toContain("effectiveAccent(themeId, accent)");+ });++ it("names every theme, text size and accent preset in both languages", () => {+ for (const dict of [zh, en]) {+ for (const id of THEME_IDS) expect(dict.settings.themeNames[id]).toBeTruthy();+ for (const size of TEXT_SIZES) expect(dict.settings.textSizeNames[size]).toBeTruthy();+ for (const id of ["neutral", ...ACCENT_PRESET_IDS]) {+ expect(dict.settings.accentNames[id], id).toBeTruthy();+ }+ }+ });++ it("puts the theme's own face first, once, and words the non-names from the dictionary", () => {+ setActiveStrings(en);+ for (const options of [FONT_LATIN_OPTIONS, FONT_CJK_OPTIONS]) {+ const choices = fontChoices(options);+ expect(choices[0]).toEqual({ value: "theme", label: en.settings.fontFollowTheme });+ expect(choices.filter((choice) => choice.value === "theme")).toHaveLength(1);+ const system = choices.find((choice) => choice.value === "system");+ if (system !== undefined) expect(system.label).toBe(en.settings.fontSystem);+ }+ });+});diff --git a/packages/web/test/title-reveal.test.ts b/packages/web/test/title-reveal.test.tsindex 93b63140..aa665bfe 100644--- a/packages/web/test/title-reveal.test.ts+++ b/packages/web/test/title-reveal.test.ts@@ -15,9 +15,6 @@* (`environment: "node"`, no jsdom), so these assert against the source text* rather than a rendered DOM.*/-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import {OVERFLOW_TOLERANCE_PX,@@ -28,6 +25,7 @@ import {revealDurationMs,titleDisclosure,} from "../src/lib/title-reveal";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";describe("revealDistancePx", () => {it("reports 0 when the text fits", () => {@@ -74,12 +72,19 @@ describe("revealDurationMs", () => {});});-const src = resolve(dirname(fileURLToPath(import.meta.url)), "../src");-const read = (rel: string) => readFileSync(resolve(src, rel), "utf8");-const truncated = read("components/ui/truncated.tsx");-const sidebar = read("components/layout/sidebar.tsx");-/** styles.css with comments stripped and whitespace collapsed, so the assertions survive reformatting. */-const css = read("styles.css")+const SCAN = scanSources();+const TRUNCATED = "packages/web/src/components/ui/truncated.tsx";+const truncated = sourceFile(SCAN, TRUNCATED).text;+const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;+/**+ * Every stylesheet under the scanned roots — styles.css, and the shared package's CSS once the+ * reveal's rules move there — with comments stripped and whitespace collapsed, so the assertions+ * survive reformatting.+ */+const css = SCAN.files+ .filter((file) => file.name.endsWith(".css"))+ .map((file) => file.text)+ .join("\n").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ");/** The keyframes that carry the whole reveal. */@@ -88,6 +93,12 @@ const keyframes = css.match(/@keyframes title-scroll-reveal \{.*?\} \}/)?.[0] ??const trigger = css.match(/\[data-title-reveal\][^{]*\{[^}]*\}/)?.[0] ?? "";describe("the truncated-title reveal's CSS contract", () => {+ it("is read from every source root, with the reveal component in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, TRUNCATED);+ expectSingleHome(SCAN, "packages/web/src/lib/title-reveal.ts");+ });+it("triggers on the row attribute the sidebar rows actually render", () => {expect(sidebar).toContain("data-title-reveal");expect(trigger).toContain("[data-title-reveal]:is(:hover, :has(:focus-visible))");diff --git a/packages/web/test/todo-notice.test.ts b/packages/web/test/todo-notice.test.tsindex c4b41482..b7fd955c 100644--- a/packages/web/test/todo-notice.test.ts+++ b/packages/web/test/todo-notice.test.ts@@ -17,31 +17,28 @@* vitest runs node-only here, so the thing that decays is a call site, not a component's output.*/import { describe, expect, it } from "vitest";-import { readdirSync, readFileSync, statSync } from "node:fs";-import { join, sep } from "node:path";-import { fileURLToPath } from "node:url";import ts from "typescript";import { bulkOutcome, failedList, firstFailure, noticeCounts } from "../src/lib/bulk-update";import type { Todo } from "../src/lib/todo-badges";+import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";-const SRC = fileURLToPath(new URL("../src", import.meta.url));+/** Web and the shared UI package: the notice's call sites are counted wherever they live. */+const SCAN = scanSources();+const TODO_NOTICE = "packages/web/src/components/ui/todo-notice.tsx";-function tsxFiles(dir = SRC, out: string[] = []): string[] {- for (const name of readdirSync(dir)) {- const path = join(dir, name);- if (statSync(path).isDirectory()) tsxFiles(path, out);- else if (name.endsWith(".tsx")) out.push(path);- }- return out;-}--/** Every `<TodoNotice …>` in the app, as "relative/path" plus its attributes by name. */+/** Every `<TodoNotice …>` in the scanned roots, as its file's repo-relative id plus its attributes by name. */function noticeSites(): { file: string; attrs: Map<string, string>; source: string }[] {const sites: { file: string; attrs: Map<string, string>; source: string }[] = [];- for (const path of tsxFiles()) {- const rel = path.slice(SRC.length + 1).replaceAll(sep, "/");- const source = readFileSync(path, "utf8");- const sf = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ for (const file of SCAN.files.filter((f) => f.name.endsWith(".tsx"))) {+ const rel = file.id;+ const source = file.text;+ const sf = ts.createSourceFile(+ file.path,+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );const visit = (node: ts.Node): void => {const opening = ts.isJsxSelfClosingElement(node)? node@@ -60,19 +57,24 @@ function noticeSites(): { file: string; attrs: Map<string, string>; source: stri};visit(sf);}- // The component's own definition is not a call site.- return sites.filter((s) => s.file !== "components/ui/todo-notice.tsx");+ // The component's own definition is not a call site, wherever it lives.+ return sites.filter((s) => !s.file.endsWith("/todo-notice.tsx"));}describe("the notice block is the one shape on every page that has one", () => {const sites = noticeSites();+ it("is looked for in every source root, and defined in one place", () => {+ expectEveryRootScanned(SCAN);+ expectSingleHome(SCAN, TODO_NOTICE);+ });+it("is placed on all four dismissible trails and nowhere else", () => {expect(sites.map((s) => s.file).sort()).toEqual([- "features/agents/agents-page.tsx",- "features/models/models-page.tsx",- "features/plugins/plugins-page.tsx",- "features/usage/usage-page.tsx",+ "packages/web/src/features/agents/agents-page.tsx",+ "packages/web/src/features/models/models-page.tsx",+ "packages/web/src/features/plugins/plugins-page.tsx",+ "packages/web/src/features/usage/usage-page.tsx",]);});@@ -87,9 +89,9 @@ describe("the notice block is the one shape on every page that has one", () => {it("only the cost center omits the bulk action — nothing there can be updated", () => {const withAction = sites.filter((s) => s.attrs.has("onAction")).map((s) => s.file);expect(withAction.sort()).toEqual([- "features/agents/agents-page.tsx",- "features/models/models-page.tsx",- "features/plugins/plugins-page.tsx",+ "packages/web/src/features/agents/agents-page.tsx",+ "packages/web/src/features/models/models-page.tsx",+ "packages/web/src/features/plugins/plugins-page.tsx",]);});});diff --git a/packages/web/test/tone.test.ts b/packages/web/test/tone.test.tsindex e323c1f5..409d62c6 100644--- a/packages/web/test/tone.test.ts+++ b/packages/web/test/tone.test.ts@@ -5,17 +5,36 @@* in one file and `amber-500` in the next for the same "waiting" state.*/import { describe, expect, it } from "vitest";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import { toneDot, toneInk, toneStrip, toneSurface } from "../src/lib/tone";import type { Tone } from "../src/lib/tone";+import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";const TONES: Tone[] = ["busy", "attention", "success", "link", "danger", "muted"];-const read = (rel: string) =>- readFileSync(fileURLToPath(new URL(`../src/${rel}`, import.meta.url)), "utf8");+const SCAN = scanSources();++/** A source file's text by its repo-relative id; fails when no scanned root holds it. */+const read = (id: string) => sourceFile(SCAN, id).text;++/** The status files that take their colour from the tokens, wherever each one lives. */+const STATUS_FILES = [+ "packages/web/src/components/ui/status-icon.tsx",+ "packages/web/src/components/ui/session-activity-icon.tsx",+ "packages/web/src/components/ui/badge.tsx",+ "packages/web/src/features/chat/step-banner.tsx",+ "packages/web/src/features/chat/goal-banner.tsx",+ "packages/web/src/features/chat/subagent-chip.tsx",+ "packages/web/src/features/builtin-browser/browser-layer.tsx",+ "packages/web/src/features/builtin-browser/browser-tab-strip.tsx",+ "packages/web/src/features/builtin-browser/browser-toolbar.tsx",+];describe("tone tokens", () => {+ it("scans every source root, and finds the tone module and each status file in one place", () => {+ expectEveryRootScanned(SCAN);+ for (const id of ["packages/web/src/lib/tone.ts", ...STATUS_FILES]) expectSingleHome(SCAN, id);+ });+it("covers every tone in every map", () => {for (const map of [toneInk, toneSurface, toneDot, toneStrip]) {for (const tone of TONES) expect(map[tone]).toBeTruthy();@@ -51,25 +70,18 @@ describe("status marks take their colour from the tokens", () => {it("inks the two hourglass states with the same attention tone", () => {// The session list's running glyph and the stream's waiting-for-approval glyph are the same// state to a reader — unfinished, waiting — so they are the same colour.- expect(read("components/ui/status-icon.tsx")).toContain("waiting: toneInk.attention");- expect(read("components/ui/session-activity-icon.tsx")).toContain("toneInk.attention");+ expect(read("packages/web/src/components/ui/status-icon.tsx")).toContain(+ "waiting: toneInk.attention",+ );+ expect(read("packages/web/src/components/ui/session-activity-icon.tsx")).toContain(+ "toneInk.attention",+ );});it("leaves no status file spelling a palette class of its own", () => {// Categorical palettes (charts, per-skill tints, the terminal's own theme) are deliberately// out of scope and are not listed here.- const files = [- "components/ui/status-icon.tsx",- "components/ui/session-activity-icon.tsx",- "components/ui/badge.tsx",- "features/chat/step-banner.tsx",- "features/chat/goal-banner.tsx",- "features/chat/subagent-chip.tsx",- "features/builtin-browser/browser-layer.tsx",- "features/builtin-browser/browser-tab-strip.tsx",- "features/builtin-browser/browser-toolbar.tsx",- ];- for (const rel of files) {+ for (const rel of STATUS_FILES) {const src = read(rel);// badge.tsx keeps one deliberate exception, a yellow informational tag that must not read// as a warning; it says so at the definition.diff --git a/packages/web/test/tooltip-rule.test.ts b/packages/web/test/tooltip-rule.test.tsnew file mode 100644index 00000000..5a1dbbca--- /dev/null+++ b/packages/web/test/tooltip-rule.test.ts@@ -0,0 +1,42 @@+/**+ * The tooltip rule (components/ui/tooltip.tsx): a hint shows for an element with no visible+ * text of its own, or one whose visible text is cut off — never for a label the reader can+ * already read in full.+ */+import { describe, expect, it } from "vitest";+import { hintAllowed, isCutOff } from "../src/components/ui/tooltip";++const box = (scrollWidth: number, clientWidth: number, scrollHeight = 16, clientHeight = 16) => ({+ scrollWidth,+ clientWidth,+ scrollHeight,+ clientHeight,+});++describe("isCutOff", () => {+ it("reads overflow on either axis as cut off", () => {+ expect(isCutOff(box(240, 120))).toBe(true);+ expect(isCutOff(box(100, 100, 40, 20))).toBe(true);+ });++ it("forgives the pixel of overflow layout reports for text that fits", () => {+ expect(isCutOff(box(101, 100, 17, 16))).toBe(false);+ expect(isCutOff(box(100, 100))).toBe(false);+ });+});++describe("hintAllowed", () => {+ it("shows the hint of an element with no text of its own (an icon, a chart mark)", () => {+ expect(hintAllowed("", [box(24, 24)])).toBe(true);+ expect(hintAllowed(" ", [])).toBe(true);+ });++ it("shows the hint when the visible text is cut off anywhere inside", () => {+ expect(hintAllowed("A very long Session title", [box(200, 200), box(320, 180)])).toBe(true);+ });++ it("shows no hint for text that is fully visible, whatever the hint would add", () => {+ expect(hintAllowed("3 min ago", [box(60, 60), box(58, 60)])).toBe(false);+ expect(hintAllowed("Copy prompt", [])).toBe(false);+ });+});diff --git a/packages/web/test/trace-refresh.test.ts b/packages/web/test/trace-refresh.test.tsindex 5c72df85..1f718650 100644--- a/packages/web/test/trace-refresh.test.ts+++ b/packages/web/test/trace-refresh.test.ts@@ -178,7 +178,7 @@ describe("what a settled-turn refresh must leave alone", () => {// whole file view below them — collapsed rounds, pinned row and scroll position included.expect(listingFailure).not.toContain("setFiles");expect(listingFailure).toContain("setError(");- expect(panel).toMatch(/\{error !== null && \([\s\S]{0,200}toneStrip\.danger/);+ expect(panel).toMatch(/\{error !== null && \([\s\S]{0,200}<NoticeStrip tone="danger"/);});it("gives the panel over to the failure only when there is nothing to keep", () => {diff --git a/packages/web/test/usage-charts.test.ts b/packages/web/test/usage-charts.test.tsindex 798b3c4b..dbcbdc1a 100644--- a/packages/web/test/usage-charts.test.ts+++ b/packages/web/test/usage-charts.test.ts@@ -1,7 +1,8 @@/**- * Cost Center chart pure-function unit tests (chart-geom.ts): coordinate mapping, SVG path- * assembly (straight paths through the points given — every line on the page is straight- * segments, nothing is smoothed), container-fitting bar width (charts never scroll), stacked-bar+ * Cost Center chart pure-function unit tests (chart-geom.ts, and the bar width and path the+ * chart primitives take from components/ui/chart/geom.ts): coordinate mapping, SVG path+ * assembly (straight paths through the points given in the default theme), container-fitting+ * bar width (charts never scroll), stacked-bar* segment geometry and per-segment hit bands, and hover-bubble placement (pointer lower-right, flipping at the edges; the cache hit rate* shown in the cacheRead bubble is lib/format's shared cacheHitRate, tested in* format.test.ts). Component interaction isn't covered here (vitest runs in a node@@ -16,15 +17,12 @@ import { describe, expect, it } from "vitest";import {makeGeom,makeRangeGeom,- linePath,- areaPath,segmentPath,+ seriesPoints,sparseLabelIdx,autoLabelIdx,bubblePosition,- fitBarWidth,barSegments,- BAR_W,BUBBLE_OFFSET,CHART_H,MIN_HIT_H,@@ -32,6 +30,7 @@ import {PAD_R,PAD_R_AXIS,} from "../src/features/usage/chart-geom";+import { BAR_W, curvePath, fitBarWidth } from "../src/components/ui/chart/geom";describe("makeGeom", () => {it("x takes each slot's midpoint; y runs top-down with max as full scale", () => {@@ -68,19 +67,15 @@ describe("makeGeom", () => {});});-describe("linePath / areaPath", () => {+describe("seriesPoints + curvePath", () => {const g = makeGeom(2, 100, 640);it("line: M start + L per point (byte-identical to the old cost line)", () => {- expect(linePath(g, [100, 0])).toBe("M192.5,10 L485.5,178");- });-- it("area: the line's end drops to the baseline and closes back at the start", () => {- expect(areaPath(g, [100, 0])).toBe("M192.5,10 L485.5,178 L485.5,178 L192.5,178 Z");+ expect(curvePath(seriesPoints(g, [100, 0]))).toBe("M192.5,10 L485.5,178");});it("an empty series returns an empty string", () => {- expect(areaPath(g, [])).toBe("");+ expect(curvePath(seriesPoints(g, []))).toBe("");});});diff --git a/packages/web/test/wechat-scan-connect.test.ts b/packages/web/test/wechat-scan-connect.test.tsindex bdfbe805..eb2cf750 100644--- a/packages/web/test/wechat-scan-connect.test.ts+++ b/packages/web/test/wechat-scan-connect.test.ts@@ -58,8 +58,8 @@ describe("WeChatScanConnect", () => {expect(html).toContain("disabled=");// A rebind would swap the credential under a live connector, so it is refused with a// reason rather than silently done.- expect(html).toContain(`title="${S.wechat.scanDisableFirst}"`);- expect(render()).not.toContain(`title="${S.wechat.scanDisableFirst}"`);+ expect(html).toContain(`data-tooltip="${S.wechat.scanDisableFirst}"`);+ expect(render()).not.toContain(`data-tooltip="${S.wechat.scanDisableFirst}"`);});});diff --git a/packages/web/vite.config.ts b/packages/web/vite.config.tsindex a6d64528..b3e2168d 100644--- a/packages/web/vite.config.ts+++ b/packages/web/vite.config.ts@@ -8,11 +8,15 @@* transparently, no special config needed.* The vitest config is kept separate in vitest.config.ts (its embedded vite 5 types conflict with this* package's vite 7 plugin types, hence the separate file to avoid the clash).+ *+ * `penguinUi()` emits the licence texts of the shared UI package's bundled fonts beside the build+ * (`fonts-licenses/`). It is imported by relative path on purpose — see its module doc.*/import react from "@vitejs/plugin-react";import tailwindcss from "@tailwindcss/vite";import { defineConfig } from "vite";import type { Plugin } from "vite";+import { penguinUi } from "../ui/src/vite-plugin";/*** Resolves the `/api` proxy target: PENGUIN_API_PROXY replaces it outright, otherwise the@@ -66,7 +70,13 @@ function katexWoff2Only(): Plugin {}export default defineConfig({- plugins: [react(), tailwindcss(), katexWoff2Only()],+ plugins: [penguinUi(), react(), tailwindcss(), katexWoff2Only()],+ build: {+ // Never inline a font. Vite turns any asset under 4 KB into a data: URI, and a font slice the+ // stylesheet references would then ride inside the one render-blocking CSS file for every+ // session, whatever its theme. As its own file it is fetched only when some text needs it.+ assetsInlineLimit: (file) => (file.endsWith(".woff2") ? false : undefined),+ },// The highlighting worker loads its themes and each grammar with a dynamic import, so its// bundle has to be code-split — and Vite's default worker format, IIFE, cannot be. Without this// the build fails outright rather than shipping something subtly wrong, which is the good case.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d3e093d0..b9a29bb0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -482,11 +482,106 @@ importers:specifier: ^3.2.6version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ packages/ui:+ dependencies:+ '@fontsource-variable/ibm-plex-sans':+ specifier: ^5.3.0+ version: 5.3.0+ '@fontsource-variable/jetbrains-mono':+ specifier: ^5.3.0+ version: 5.3.0+ '@fontsource-variable/mona-sans':+ specifier: ^5.3.0+ version: 5.3.0+ '@fontsource-variable/noto-sans-sc':+ specifier: ^5.3.0+ version: 5.3.0+ '@fontsource/commit-mono':+ specifier: ^5.3.0+ version: 5.3.0+ '@fontsource/ibm-plex-sans-condensed':+ specifier: ^5.3.0+ version: 5.3.0+ devDependencies:+ '@types/node':+ specifier: ^24.0.0+ version: 24.13.3+ '@types/react':+ specifier: ^19.1.0+ version: 19.2.17+ '@types/react-dom':+ specifier: ^19.1.0+ version: 19.2.3(@types/[email protected])+ react:+ specifier: ^19.1.0+ version: 19.2.7+ react-dom:+ specifier: ^19.1.0+ version: 19.2.7([email protected])+ typescript:+ specifier: ^5.6.0+ version: 5.9.3+ vitest:+ specifier: ^3.2.6+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ packages/ui-gallery:+ dependencies:+ '@prismshadow/penguin-ui':+ specifier: workspace:*+ version: link:../ui+ react:+ specifier: ^19.1.0+ version: 19.2.7+ react-dom:+ specifier: ^19.1.0+ version: 19.2.7([email protected])+ devDependencies:+ '@playwright/test':+ specifier: ^1.61.1+ version: 1.61.1+ '@prismshadow/penguin-core':+ specifier: workspace:*+ version: file:packages/core([email protected])([email protected])+ '@prismshadow/penguin-web':+ specifier: workspace:*+ version: link:../web+ '@tailwindcss/vite':+ specifier: ^4.1.0+ version: 4.3.2([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@types/node':+ specifier: ^24.0.0+ version: 24.13.3+ '@types/react':+ specifier: ^19.1.0+ version: 19.2.17+ '@types/react-dom':+ specifier: ^19.1.0+ version: 19.2.3(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: ^4.5.0+ version: 4.7.0([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ tailwindcss:+ specifier: ^4.1.0+ version: 4.3.2+ typescript:+ specifier: ^5.6.0+ version: 5.9.3+ vite:+ specifier: ^7.0.0+ version: 7.3.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^3.2.6+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+packages/web:dependencies:'@prismshadow/penguin-core':specifier: workspace:*version: file:packages/core([email protected])([email protected])+ '@prismshadow/penguin-ui':+ specifier: workspace:*+ version: link:../ui'@shikijs/langs':specifier: ^4.3.1version: 4.3.1@@ -1215,6 +1310,24 @@ packages:cpu: [x64]os: [win32]+ '@fontsource-variable/[email protected]':+ resolution: {integrity: sha512-agG8tXFEo0hD9+J7npa4vbbWult52eMLVaQ6WQRlhs/iCAojrMAoejru85W9HTVXHfyUj96KM7gp/KGAS87XaQ==}++ '@fontsource-variable/[email protected]':+ resolution: {integrity: sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==}++ '@fontsource-variable/[email protected]':+ resolution: {integrity: sha512-PkxRB3KI4z9Gjpk7vVqgO3GMSyQuOIIj4TaRDbvbcDj8SzWwI38jvLTQxJM/cTRorhcT7h8qjcllR+qjRtM/Fg==}++ '@fontsource-variable/[email protected]':+ resolution: {integrity: sha512-lNar1dF7Ik/lHNPo/7JWG0TolXY29LtsqYgMvEysooZ5bsO9uH4shJmRrwyJ3PjyTPljhpMJEK0jDuLSU4vJ1w==}++ '@fontsource/[email protected]':+ resolution: {integrity: sha512-Bs+zlEWHDgk/cCVWEMJJaA7LbBU3Ixi5Zums+SSwMKdm2N7RJ4P7jCJTwsMHRt5WFiXYB0tu0q9HMfkn0YsLsQ==}++ '@fontsource/[email protected]':+ resolution: {integrity: sha512-fQyBpwbkguP4azjq7Cw8h/J3C/d8MFAzXOiSoFxyKCUK4x0XKrWEh3tGdTxhDM0HctVRQilQo1zGoyxDHLm5jQ==}+'@google/[email protected]':resolution: {integrity: sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==}engines: {node: '>=20.0.0'}@@ -5202,6 +5315,18 @@ snapshots:'@esbuild/[email protected]':optional: true+ '@fontsource-variable/[email protected]': {}++ '@fontsource-variable/[email protected]': {}++ '@fontsource-variable/[email protected]': {}++ '@fontsource-variable/[email protected]': {}++ '@fontsource/[email protected]': {}++ '@fontsource/[email protected]': {}+'@google/[email protected]([email protected])':dependencies:google-auth-library: 10.7.0([email protected])