Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): design frames rendered from product components (#3125)
Call White5f546a860523
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 1b4b349f2..081ecc567 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -193,6 +193,8 @@ jobs:npm run lint# Production tsc excludes test files, and vitest only strips types.npm run typecheck:tests+ # Design frames (ui/design) are not part of the production build.+ npm run typecheck:design- part: testscommands: |npm test@@ -241,6 +243,8 @@ jobs:npm run test:workbench-general -- sidebar-floating.spec.ts desktop-window-chrome.spec.ts composer-route-trigger.spec.ts skills-dialog.spec.ts bots.spec.tsnpm run test:chat-interactionsnpm run test:pdf-preview+ # Renders every design frame in both themes; fails on any console error.+ npm run design:shotsteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0diff --git a/AGENTS.md b/AGENTS.mdindex 7d544d712..23f74f0b1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -304,7 +304,7 @@ there rather than expanding this index.- source lives in `ui/`; build with `cd ui && npm run build`; `ui/dist/` is served by `vibe/ui_server.py`- follow the reuse ladder for UI and shared backend logic: inventory existing patterns -> reuse (`ui/src/components/ui/` primitives such as `Button`, `Badge`, `Card`, `Input`, `Popover`, `Dialog` first) -> extend via variants/sizes/props -> promote near-duplicates -> create a reusable unit only when needed; extract on the third repeat-- `../avibe-docs/design.pen` is the visual source of truth; map spacing, type, radius, color, and shadow to exact tokens/classes, add missing tokens instead of hardcoding, and verify against the exported frame when visual fidelity matters+- `ui/design/` is the UI design source (rules in `ui/design/AGENTS.md`): design new and changed surfaces there as frames that render the product's own components and tokens, check them with `npm run design:shot`, and present them in a Show Page with `npm run design:export`. Map spacing, type, radius, color, and shadow to exact tokens/classes and add missing tokens instead of hardcoding- installed `vibe` uses packaged UI assets, not raw repo `ui/dist/`; for packaged CLI/UI preview, build UI and reinstall from a normal wheel — never `uv tool install --force --editable .`, and never an editable install against system Python## 7. Testing and Validationdiff --git a/docs/plans/design-frames.md b/docs/plans/design-frames.mdnew file mode 100644index 000000000..e212e98a0--- /dev/null+++ b/docs/plans/design-frames.md@@ -0,0 +1,53 @@+# Design frames++Status: adopted (2026-11-02). Avibe's UI designs live in `ui/design/` as frames; working rules are in+`ui/design/AGENTS.md`.++## Goals++- **Fidelity.** A frame renders the shipped components, tokens, and copy, so a design of a shipped surface+ cannot drift from the product, and a proposal built from the same tokens and primitives is implemented by+ assembly rather than translation.+- **Collaboration.** Frames are small TSX files in the repository. Everyone designs locally with their own+ Agent, reviews through PRs, and merges like code; there is one design source and no per-seat tool.+- **Focus.** Frames are static. A designer, person or Agent, works on layout and style from fixtures, checks+ the result by screenshot, and never writes interaction logic.++## Design++- `ui/design/frames/<area>/<name>.design.tsx` default-exports the frames of one surface, one per state, each+ with a title, a size, its themes, and a status (`proposed`, `approved`, `shipped`). A frame renders the+ shipped component with fixtures; what is not shipped yet is drawn with `ui/design/kit/` components that use+ only product tokens and assets, and switches to the shipped component when it ships.+- `DesignShell` serves the providers Workbench surfaces read (router, toast, authorization, unsaved changes,+ window manager, Inbox, project tree) from fixtures, and runs the real `ApiProvider` and `BotsProvider`.+ `fetch` and `EventSource` are answered in the page from the frame's API fixtures (by path and query, then by+ path), so no frame reaches a server; paths a frame fetched without a fixture are reported. Each frame gets+ fresh in-memory Web Storage (seeded by its `storage` fixture) and a fixed clock, so a viewer's remembered+ preferences and the date never change a frame. No product code changes for this.+- The canvas (`ui/design.html`, not part of the production build) shows every frame, each in its own iframe so+ themes, portals, and routing never leak between frames. `?frame=<id>&theme=light|dark&lang=zh|en` renders one+ frame at its size.+- `npm run design:shot` renders frames with Playwright (2x PNG, animations off, portals included, an optional+ hover) once fonts are loaded and the network is quiet, and fails on any console error. CI runs it with the+ browser checks, and `typecheck:design` with the static checks, so a product change that breaks a frame fails+ its PR.+- `npm run design:export` copies the canvas, the screenshots, and `frames.json` into the current Session's Show+ Page and writes `<DesignFrame>`, which embeds frames live (crisp, interactive) without any Show Page change.+ Each shot keeps the language it was exported in. While the Show Page's annotation is on, `<DesignFrame>` draws+ each frame as its screenshot through the overlay's public window API, so annotations reach it and name the+ frame.++## Known by design++- A frame embedded in a Show Page is an iframe: the overlay annotates its screenshot, not its elements, and the+ Show proxy's annotation script logs a harmless error inside it (no import map in a non-entry document). A child+ frame mode in `vibe-show-runtime` would lift both; not needed yet.+- A surface whose markup and data hooks live in one component (`WorkbenchSidebar`) can be drawn whole, but a+ partial redesign of it can only be drawn beside it in `kit/`. Splitting such components into a view (props+ only) and a container makes them fully drawable and simpler to fixture.+- Kit copy is draft copy; it moves to `ui/src/i18n` when the component ships.++## Follow-ups++- Draw `avibe-bot-backend` surfaces (the avibe.bot site and console) the same way in that repository.diff --git a/ui/.gitignore b/ui/.gitignoreindex 28ee874bc..8f5323b60 100644--- a/ui/.gitignore+++ b/ui/.gitignore@@ -30,3 +30,5 @@ playwright-reporttest-resultsblob-report.playwright+design/.shots/+design/.dist/diff --git a/ui/design.html b/ui/design.htmlnew file mode 100644index 000000000..41e96dd93--- /dev/null+++ b/ui/design.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Avibe Design</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/design/main.tsx"></script>+ </body>+</html>diff --git a/ui/design/AGENTS.md b/ui/design/AGENTS.mdnew file mode 100644index 000000000..81c1295a3--- /dev/null+++ b/ui/design/AGENTS.md@@ -0,0 +1,38 @@+# Design frames++Avibe's UI designs live here. A frame is a static React render of one surface in one state, built from the product's own components, tokens, assets, and copy, so a design and the shipped UI cannot drift apart. Frames are reviewed and merged like code. The design system and its decisions: `docs/plans/design-frames.md`.++## Layout++- `frames/<area>/<name>.design.tsx`: one file per surface; it default-exports `frames([...])`, one frame per state. A frame id is `<area>/<name>/<state>`.+- `kit/`: components a design proposes that are not shipped yet. They use only product tokens (Tailwind classes from `src/index.css`), assets, and `src/components/ui` primitives.+- `shell/`: the providers frames render in (`DesignShell`), fixture builders (`fixtures.ts`), the fixed clock, frame-local Web Storage, and the network stub.++## Rules++- Draw shipped surfaces with the shipped component (`@/components/...`) and fixtures; never redraw them.+- Draw what does not exist yet in `kit/`. When it ships, the frame switches to the shipped component, the kit copy is deleted, and the status becomes `shipped`.+- Frames hold no logic: no handlers, no effects, no fetching. State comes from fixtures (`WorkbenchFixtures`): a provider that reads the API gets its response from `fixtures.api` or a typed fixture field, and a remembered preference comes from `fixtures.storage`. Add a fixture field rather than mocking inside a frame.+- Tokens only: no raw colors, sizes, or shadows that `src/index.css` does not define. Add a token there if one is missing.+- Each frame states its size, its themes (default both), and its status: `proposed` (being designed), `approved` (signed off, ready to build), or `shipped` (renders shipped components only). A proposal becomes `approved` in the PR the owner approves.+- Kit copy is draft copy and may be written inline; it moves to `src/i18n` when the component ships.+- When a shipped component mixes data hooks and markup, draw it whole; to redesign part of it, prefer splitting it into a view (props only) and a container, then draw the view.+- Size a frame to include any popover, menu, or card it shows; set `hover` to capture a hover state.+- Code that implements a design names its frame id (`ui/design: sidebar/bots/three`), not a description of a drawing.++## Loop++- `npm run design`: the canvas with every frame in both themes, hot-reloading.+- `npm run design:shot -- <id prefix>`: PNGs in `design/.shots/<id>.<theme>.png` (2x); read them to check your work. One JSON line per shot lists API paths the frame touched without a fixture (`unfixtured`) and console errors; any error exits 1. CI runs it for every frame.+- `npm run typecheck:design`: frames type-check against the product's current props, so a product change that breaks a frame fails CI.+- `npm run design:build -- --out <dir>`: the canvas as static files.++## Presenting a design++Show designs in your own Session's Show Page, next to your explanation:++1. `npm run design:export -- <id prefix>` copies the live canvas, a screenshot of each frame, and `frames.json` into `public/design/` of this Session's Show Page, and writes `src/design/DesignFrame.tsx` there.+2. In a page: `import { DesignFrame } from "../design/DesignFrame"`, then `<DesignFrame id="sidebar/bots/three" />`. Each frame runs the real components in an iframe (crisp, scalable, hover and popovers work) and links to its screenshot.+3. While the Show Page's annotation is on, each frame is drawn as its screenshot so the overlay can reach it; an annotation names the frame (`设计帧 <id>`) and theme. Read it back to the frame file before you change anything.++The repository is the source: never edit designs in a Show Page.diff --git a/ui/design/Canvas.tsx b/ui/design/Canvas.tsxnew file mode 100644index 000000000..02a29758d--- /dev/null+++ b/ui/design/Canvas.tsx@@ -0,0 +1,99 @@+import { useEffect, type ReactNode } from 'react';++import type { DesignLang, DesignTheme, Frame } from './frame';+import { ALL_FRAMES } from './registry';+import { DesignShell } from './shell/DesignShell';+import { designNetwork } from './shell/network';++function FrameBox({ frame, theme }: { frame: Frame; theme: DesignTheme }) {+ return (+ <div+ data-theme={theme}+ data-frame-root={frame.id}+ className="relative overflow-hidden bg-background text-foreground"+ style={{ width: frame.width, height: frame.height }}+ >+ <DesignShell fixtures={frame.fixtures} route={frame.route}>+ {frame.render()}+ </DesignShell>+ </div>+ );+}++/** One frame at its exact size: what the screenshot tool captures. */+function Single({ frame, theme }: { frame: Frame; theme: DesignTheme }) {+ useEffect(() => {+ document.documentElement.setAttribute('data-theme', theme);+ let cancelled = false;+ // Ready once fonts are in and the providers' fixture reads have settled.+ void document.fonts.ready+ .then(() => designNetwork.quiet())+ .then(() => {+ if (!cancelled) document.body.dataset.designReady = 'true';+ });+ return () => {+ cancelled = true;+ };+ }, [theme]);+ return <FrameBox frame={frame} theme={theme} />;+}++const STATUS_CLASS: Record<string, string> = {+ proposed: 'border-gold/40 text-gold-ink',+ approved: 'border-cyan/40 text-cyan-ink',+ shipped: 'border-mint/40 text-mint-ink',+};++/** Every frame, grouped by file, each theme side by side: the artboards. */+function Canvas({ lang }: { lang: DesignLang }) {+ const files = [...new Set(ALL_FRAMES.map((f) => f.file))];+ return (+ <div data-theme="light" className="min-h-screen bg-muted-soft px-10 py-8 text-foreground">+ <h1 className="text-[22px] font-bold">Avibe Design</h1>+ <p className="mt-1 text-[13px] text-muted">+ {ALL_FRAMES.length} frames · ?frame=<id>&theme=light|dark&lang=zh|en renders one frame at its size+ </p>+ {files.map((file) => (+ <section key={file} className="mt-10">+ <h2 className="font-mono text-[12px] font-bold uppercase tracking-[0.16em] text-muted">{file}</h2>+ <div className="mt-4 flex flex-wrap items-start gap-10">+ {ALL_FRAMES.filter((f) => f.file === file).map((frame) => (+ <figure key={frame.id} className="flex flex-col gap-2">+ <figcaption className="flex items-center gap-2 text-[12px]">+ <span className="font-semibold">{frame.title}</span>+ <span className={`rounded border px-1.5 py-px font-mono text-[10px] ${STATUS_CLASS[frame.status]}`}>{frame.status}</span>+ <a className="font-mono text-[10px] text-muted hover:text-foreground" href={`?frame=${encodeURIComponent(frame.id)}&theme=light&lang=${lang}`}>+ {frame.id}+ </a>+ </figcaption>+ <div className="flex items-start gap-4">+ {(frame.themes ?? ['light', 'dark']).map((theme) => (+ // Each frame is its own document, so its theme, portals (popovers,+ // dialogs), and router never leak into another frame.+ <iframe+ key={theme}+ title={`${frame.id} ${theme}`}+ src={`?frame=${encodeURIComponent(frame.id)}&theme=${theme}&lang=${lang}`}+ className="rounded-xl border border-border bg-background shadow-sm"+ style={{ width: frame.width, height: frame.height }}+ />+ ))}+ </div>+ </figure>+ ))}+ </div>+ </section>+ ))}+ </div>+ );+}++/** The canvas, or one frame when the URL names it (`?frame=<id>&theme=light|dark`). */+export function DesignRoot({ params }: { params: URLSearchParams }): ReactNode {+ const lang: DesignLang = params.get('lang') === 'en' ? 'en' : 'zh';+ const id = params.get('frame');+ if (!id) return <Canvas lang={lang} />;+ const frame = ALL_FRAMES.find((f) => f.id === id);+ if (!frame) return <p>Unknown frame {id}</p>;+ return <Single frame={frame} theme={params.get('theme') === 'dark' ? 'dark' : 'light'} />;+}diff --git a/ui/design/export/DesignFrame.test.tsx b/ui/design/export/DesignFrame.test.tsxnew file mode 100644index 000000000..0d394636a--- /dev/null+++ b/ui/design/export/DesignFrame.test.tsx@@ -0,0 +1,80 @@+/* @vitest-environment jsdom */++import { act, cleanup, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { DesignFrame } from './DesignFrame';++type State = { enabled: boolean };++// The Show Page's public annotation API, as the overlay attaches it (contract §2).+function installAnnotationApi(initial: boolean) {+ let state: State = { enabled: initial };+ const listeners = new Set<(next: State) => void>();+ (globalThis as Record<string, unknown>).__AVIBE_SHOW__ = {+ annotation: {+ api: {+ getState: () => state,+ subscribe: (callback: (next: State) => void) => {+ listeners.add(callback);+ return () => listeners.delete(callback);+ },+ },+ },+ };+ return (enabled: boolean) => {+ state = { enabled };+ act(() => listeners.forEach((listener) => listener(state)));+ };+}++const index = {+ lang: 'zh',+ shots: [+ { id: 'sidebar/bots/three', title: '伙伴 · 3 个伙伴', status: 'approved', theme: 'light', width: 248, height: 190, hash: 'h1', src: 'shots/sidebar/bots/three.light.png' },+ { id: 'sidebar/bots/three', title: '伙伴 · 3 个伙伴', status: 'approved', theme: 'dark', lang: 'en', width: 248, height: 190, hash: 'h2', src: 'shots/sidebar/bots/three.dark.png' },+ ],+};++beforeEach(() => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(index))));+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ disconnect() {}+ },+ );+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ delete (globalThis as Record<string, unknown>).__AVIBE_SHOW__;+});++describe('DesignFrame', () => {+ it('runs each theme live, and shows screenshots the overlay can reach while annotation is on', async () => {+ const setAnnotating = installAnnotationApi(false);+ render(<DesignFrame id="sidebar/bots/three" />);++ const frames = await screen.findAllByTitle(/伙伴 · 3 个伙伴/);+ expect(frames.map((frame) => frame.getAttribute('src'))).toEqual([+ './design/canvas/design.html?frame=sidebar%2Fbots%2Fthree&theme=light&lang=zh',+ // A shot exported in another language keeps it (partial exports merge).+ './design/canvas/design.html?frame=sidebar%2Fbots%2Fthree&theme=dark&lang=en',+ ]);++ setAnnotating(true);+ const shots = screen.getAllByRole('img');+ expect(shots.map((shot) => [shot.getAttribute('src'), shot.getAttribute('data-frame-id')])).toEqual([+ ['./design/shots/sidebar/bots/three.light.png?v=h1', 'sidebar/bots/three'],+ ['./design/shots/sidebar/bots/three.dark.png?v=h2', 'sidebar/bots/three'],+ ]);+ expect(document.querySelector('iframe')).toBeNull();++ setAnnotating(false);+ expect(screen.getAllByTitle(/伙伴 · 3 个伙伴/)).toHaveLength(2);+ expect(screen.queryAllByRole('img')).toHaveLength(0);+ });+});diff --git a/ui/design/export/DesignFrame.tsx b/ui/design/export/DesignFrame.tsxnew file mode 100644index 000000000..9413f6154--- /dev/null+++ b/ui/design/export/DesignFrame.tsx@@ -0,0 +1,122 @@+// avibe-design-frame: shows one avibe/ui design frame live in a Show Page.+// Written by `npm run design:export`; it imports nothing from the product, only the files the+// export put in public/design/ (the live canvas, screenshots, and frames.json).+//+// import { DesignFrame } from "../design/DesignFrame"+// <DesignFrame id="sidebar/bots/three" /> light, then dark+// <DesignFrame id="sidebar/bots/three" themes={["dark"]} />+//+// A live frame is an iframe, which the Show Page's annotation overlay cannot reach. While+// annotation is on, each frame is drawn as its screenshot instead, in the same place and size,+// so it can be annotated like any image; the image's alt names the frame and theme.+import { useEffect, useRef, useState } from "react"++type Shot = { id: string; title: string; status: string; theme: "light" | "dark"; lang?: string; width: number; height: number; hash: string; src: string }+type Index = { lang: string; shots: Shot[] }++let index: Promise<Index> | null = null+const loadIndex = () => (index ??= fetch(new URL("./design/frames.json", document.baseURI)).then((r) => r.json()))++const STATUS: Record<string, string> = { proposed: "提案", approved: "已定稿", shipped: "已上线" }++type AnnotationApi = { getState(): { enabled: boolean }; subscribe(callback: (state: { enabled: boolean }) => void): () => void }++/** Whether the Show Page's annotation overlay is on, through its public window API. */+function useAnnotating(): boolean {+ const [annotating, setAnnotating] = useState(false)+ useEffect(() => {+ let unsubscribe: (() => void) | undefined+ let timer: ReturnType<typeof setTimeout> | undefined+ let attempts = 0+ // The overlay attaches its API after the page has loaded, so look for it for a while.+ const attach = () => {+ const api = (globalThis as { __AVIBE_SHOW__?: { annotation?: { api?: AnnotationApi } } }).__AVIBE_SHOW__?.annotation?.api+ if (api) {+ setAnnotating(api.getState().enabled)+ unsubscribe = api.subscribe((state) => setAnnotating(state.enabled))+ } else if (attempts++ < 40) {+ timer = setTimeout(attach, 250)+ }+ }+ attach()+ return () => {+ clearTimeout(timer)+ unsubscribe?.()+ }+ }, [])+ return annotating+}++export function DesignFrame({ id, themes = ["light", "dark"] }: { id: string; themes?: ("light" | "dark")[] }) {+ const [data, setData] = useState<Index | null>(null)+ const annotating = useAnnotating()+ useEffect(() => {+ void loadIndex().then(setData)+ }, [])+ const shots = (data?.shots ?? []).filter((s) => s.id === id && themes.includes(s.theme))+ shots.sort((a, b) => themes.indexOf(a.theme) - themes.indexOf(b.theme))+ if (!data) return null+ if (shots.length === 0) return <p className="text-sm text-red-600">设计稿里没有这一帧:{id}(先运行 npm run design:export)</p>+ const first = shots[0]+ return (+ <figure className="flex max-w-full flex-col gap-2" data-frame-id={id}>+ <figcaption className="flex flex-wrap items-center gap-2 text-xs">+ <span className="font-semibold">{first.title}</span>+ <span className="rounded border px-1.5 font-mono text-[10px] text-muted-foreground">{STATUS[first.status] ?? first.status}</span>+ <span className="font-mono text-[10px] text-muted-foreground">{id}</span>+ </figcaption>+ <div className="flex max-w-full flex-wrap items-start gap-3">+ {shots.map((shot) => (+ <Live key={shot.theme} shot={shot} lang={data.lang} still={annotating} />+ ))}+ </div>+ </figure>+ )+}++/** The frame itself, running the real components; scaled down to fit narrow screens. */+function Live({ shot, lang, still }: { shot: Shot; lang: string; still: boolean }) {+ const box = useRef<HTMLDivElement>(null)+ const [scale, setScale] = useState(1)+ useEffect(() => {+ const parent = box.current?.parentElement+ if (!parent) return+ const fit = () => setScale(Math.min(1, parent.clientWidth / shot.width))+ fit()+ const observer = new ResizeObserver(fit)+ observer.observe(parent)+ return () => observer.disconnect()+ }, [shot.width])+ const src = `./design/canvas/design.html?frame=${encodeURIComponent(shot.id)}&theme=${shot.theme}&lang=${shot.lang ?? lang}`+ const image = `./design/${shot.src}?v=${shot.hash}`+ return (+ <div ref={box} className="flex flex-col gap-1" style={{ width: shot.width * scale }}>+ <div className="overflow-hidden rounded-lg border shadow-sm" style={{ height: shot.height * scale }}>+ {still ? (+ <img+ src={image}+ alt={`设计帧 ${shot.id}(${shot.title},${shot.theme === "dark" ? "深色" : "浅色"})`}+ data-frame-id={shot.id}+ data-theme={shot.theme}+ style={{ width: shot.width * scale, height: shot.height * scale, display: "block" }}+ />+ ) : (+ <iframe+ title={`${shot.title} · ${shot.theme}`}+ src={src}+ loading="lazy"+ data-agent-hidden+ style={{ width: shot.width, height: shot.height, border: 0, transform: `scale(${scale})`, transformOrigin: "0 0" }}+ />+ )}+ </div>+ <div className="flex gap-3 text-[10px] text-muted-foreground">+ <span>{shot.theme === "dark" ? "深色" : "浅色"}{still ? " · 批注中,显示截图" : ""}</span>+ <a href={src} target="_blank" rel="noreferrer" className="hover:underline">单独打开</a>+ <a href={image} target="_blank" rel="noreferrer" className="hover:underline">+ 截图+ </a>+ </div>+ </div>+ )+}diff --git a/ui/design/frame.ts b/ui/design/frame.tsnew file mode 100644index 000000000..acf13edaa--- /dev/null+++ b/ui/design/frame.ts@@ -0,0 +1,34 @@+import type { ReactNode } from 'react';++import type { WorkbenchFixtures } from './shell/fixtures';++export type DesignTheme = 'light' | 'dark';+export type DesignLang = 'zh' | 'en';+/** proposed: still being designed; approved: the owner signed it off; shipped: it renders the shipped components only. */+export type FrameStatus = 'proposed' | 'approved' | 'shipped';++export interface FrameSpec {+ /** Unique within its file; the frame id is `<file path under frames/>/<name>`. */+ name: string;+ title: string;+ width: number;+ height: number;+ status: FrameStatus;+ /** Defaults to both themes. */+ themes?: DesignTheme[];+ /** Data the real providers serve to the frame. */+ fixtures?: WorkbenchFixtures;+ /** Initial route for components that read the location. */+ route?: string;+ /** A CSS selector the screenshot hovers before capturing, for hover states (cards, menus). */+ hover?: string;+ render: () => ReactNode;+}++export interface Frame extends FrameSpec {+ id: string;+ file: string;+}++/** A design file default-exports the frames it draws, usually one per state. */+export const frames = (specs: FrameSpec[]): FrameSpec[] => specs;diff --git a/ui/design/frames/sidebar/bots.design.tsx b/ui/design/frames/sidebar/bots.design.tsxnew file mode 100644index 000000000..c57f86eb1--- /dev/null+++ b/ui/design/frames/sidebar/bots.design.tsx@@ -0,0 +1,64 @@+// Bots in the sidebar (docs/plans/bots.md D5): the shipped strip, hover card, and Inbox icon,+// drawn by the shipped sidebar from fixtures.+import { WorkbenchSidebar } from '@/components/workbench/WorkbenchSidebar';++import { frames } from '../../frame';+import { demoBots, demoProjects, inboxRow, mainBot, type WorkbenchFixtures } from '../../shell/fixtures';+import { SidebarColumn } from '../../shell/SidebarColumn';++const sidebar = () => (+ <SidebarColumn>+ <WorkbenchSidebar />+ </SidebarColumn>+);++const team: WorkbenchFixtures = {+ projects: demoProjects,+ bots: demoBots,+ botStatus: { ses_pm: 'running' },+ unreadBySession: { ses_cso: 2, ses_demo_cache: 3 },+ inboxSessions: [inboxRow('ses_cso', null, '首席安全官', 'avault 依赖里发现 2 个高危漏洞', 20, 2)],+ // The hover card reads the Bot's latest message when it opens.+ api: {+ '/api/inbox?limit=1&session=ses_pm': {+ sessions: [inboxRow('ses_pm', null, '产品经理', '需求池按优先级排好了,前三项需要你拍板。', 2)],+ },+ },+};++const designFrames = frames([+ {+ name: 'new-user',+ title: '伙伴 · 只有歪比',+ width: 248,+ height: 360,+ status: 'shipped',+ fixtures: { projects: demoProjects, bots: [mainBot] },+ render: sidebar,+ },+ {+ name: 'three',+ title: '伙伴 · 3 个伙伴:未读、运行中',+ width: 248,+ height: 360,+ status: 'shipped',+ fixtures: team,+ render: sidebar,+ },+ {+ name: 'hover-card',+ title: '伙伴 · 悬停卡片',+ width: 520,+ height: 360,+ status: 'shipped',+ fixtures: team,+ hover: '[data-bot-handle="pm"]',+ render: () => (+ <div className="h-full w-[248px]">+ {sidebar()}+ </div>+ ),+ },+]);++export default designFrames;diff --git a/ui/design/frames/sidebar/inbox-popover.design.tsx b/ui/design/frames/sidebar/inbox-popover.design.tsxnew file mode 100644index 000000000..9c0eb069b--- /dev/null+++ b/ui/design/frames/sidebar/inbox-popover.design.tsx@@ -0,0 +1,41 @@+// The shipped Inbox hover popover (a portaled overlay), opened next to the shipped sidebar.+import { Popover, PopoverAnchor } from '@/components/ui/popover';+import { InboxHoverPopover } from '@/components/workbench/WorkbenchSidebar';++import { frames } from '../../frame';+import { inboxRow, mainBot } from '../../shell/fixtures';++const rows = [+ inboxRow('ses_demo_cache', 'avibe', '修复中途断缓存', '定位到清理旧工具结果时前缀断开,PR 已开。', 5, 3),+ inboxRow('ses_demo_pr', 'avibe', 'PR #3073 交付', 'CI 失败:unit-tests (2/8)。', 30, 2),+ inboxRow('ses_demo_audit', 'chainbot', '合约审计', '三个函数的权限检查已补齐,测试全绿。', 90),+];++const designFrames = frames([+ {+ name: 'open',+ title: '收件箱浮层 · 现状',+ width: 420,+ height: 460,+ status: 'shipped',+ fixtures: { bots: [mainBot] },+ render: () => (+ <Popover open>+ <PopoverAnchor className="absolute left-0 top-4 size-px" />+ <InboxHoverPopover+ sessions={rows}+ unreadBySession={{ ses_demo_cache: 3, ses_demo_pr: 2 }}+ unreadSessions={2}+ totalUnread={5}+ canMarkRead+ onItemClick={() => {}}+ onMarkAllRead={() => {}}+ onMouseEnter={() => {}}+ onMouseLeave={() => {}}+ />+ </Popover>+ ),+ },+]);++export default designFrames;diff --git a/ui/design/frames/sidebar/workbench-sidebar.design.tsx b/ui/design/frames/sidebar/workbench-sidebar.design.tsxnew file mode 100644index 000000000..e353ffbdf--- /dev/null+++ b/ui/design/frames/sidebar/workbench-sidebar.design.tsx@@ -0,0 +1,45 @@+// The shipped sidebar, rendered by the shipped component from fixtures.+import { WorkbenchSidebar } from '@/components/workbench/WorkbenchSidebar';++import { frames } from '../../frame';+import { demoProjects, demoSessions, inboxRow, mainBot } from '../../shell/fixtures';+import { SidebarColumn } from '../../shell/SidebarColumn';++const sidebar = () => (+ <SidebarColumn>+ <WorkbenchSidebar />+ </SidebarColumn>+);++const designFrames = frames([+ {+ name: 'default',+ title: '侧边栏 · 现状',+ width: 248,+ height: 640,+ status: 'shipped',+ fixtures: { projects: demoProjects, bots: [mainBot] },+ render: sidebar,+ },+ {+ name: 'unread-expanded',+ title: '侧边栏 · 现状 · 有未读、展开项目',+ width: 248,+ height: 640,+ status: 'shipped',+ fixtures: {+ projects: demoProjects,+ bots: [mainBot],+ sessionsByProject: demoSessions,+ expandedProjects: ['proj_avibe'],+ unreadBySession: { ses_demo_cache: 3, ses_demo_pr: 2 },+ inboxSessions: [+ inboxRow('ses_demo_cache', 'avibe', '修复中途断缓存', '定位到清理旧工具结果时前缀断开,PR 已开。', 5, 3),+ inboxRow('ses_demo_pr', 'avibe', 'PR #3073 交付', 'CI 失败:unit-tests (2/8)。', 30, 2),+ ],+ },+ render: sidebar,+ },+]);++export default designFrames;diff --git a/ui/design/main.tsx b/ui/design/main.tsxnew file mode 100644index 000000000..6847fda28--- /dev/null+++ b/ui/design/main.tsx@@ -0,0 +1,48 @@+// First: frames get their own storage before any product module reads it.+import { designStorage } from './shell/storage';++import { StrictMode } from 'react';+import { createRoot } from 'react-dom/client';++import i18n from '@/i18n';+import '@/index.css';++import { DesignRoot } from './Canvas';+import type { DesignLang, DesignTheme } from './frame';+import { ALL_FRAMES } from './registry';+import { installFixedClock } from './shell/clock';+import { apiResponses } from './shell/fixtures';+import { designNetwork, installDesignNetwork } from './shell/network';++installFixedClock();+installDesignNetwork();++const params = new URLSearchParams(window.location.search);+const lang = (params.get('lang') === 'en' ? 'en' : 'zh') as DesignLang;+void i18n.changeLanguage(lang);+// One document draws one frame (the canvas puts each in its own iframe), so its API+// fixtures are in place before any provider can fetch.+const shown = ALL_FRAMES.find((f) => f.id === params.get('frame'));+designNetwork.setResponses(apiResponses(shown?.fixtures));+designStorage.seed(shown?.fixtures?.storage);++declare global {+ interface Window {+ __DESIGN__?: {+ frames: { id: string; file: string; title: string; status: string; width: number; height: number; themes: DesignTheme[]; hover?: string }[];+ unfixtured: () => string[];+ quiet: () => Promise<void>;+ };+ }+}+window.__DESIGN__ = {+ frames: ALL_FRAMES.map((f) => ({ id: f.id, file: f.file, title: f.title, status: f.status, width: f.width, height: f.height, themes: f.themes ?? ['light', 'dark'], hover: f.hover })),+ unfixtured: () => designNetwork.unfixtured(),+ quiet: () => designNetwork.quiet(),+};++createRoot(document.getElementById('root')!).render(+ <StrictMode>+ <DesignRoot params={params} />+ </StrictMode>,+);diff --git a/ui/design/registry.ts b/ui/design/registry.tsnew file mode 100644index 000000000..b8ace0431--- /dev/null+++ b/ui/design/registry.ts@@ -0,0 +1,10 @@+import type { Frame, FrameSpec } from './frame';++const modules = import.meta.glob<{ default: FrameSpec[] }>('./frames/**/*.design.tsx', { eager: true });++export const ALL_FRAMES: Frame[] = Object.entries(modules)+ .flatMap(([path, module]) => {+ const file = path.replace('./frames/', '').replace(/\.design\.tsx$/, '');+ return module.default.map((spec) => ({ ...spec, file, id: `${file}/${spec.name}` }));+ })+ .sort((a, b) => a.id.localeCompare(b.id));diff --git a/ui/design/shell/DesignShell.tsx b/ui/design/shell/DesignShell.tsxnew file mode 100644index 000000000..31557ea2e--- /dev/null+++ b/ui/design/shell/DesignShell.tsx@@ -0,0 +1,93 @@+import { useMemo, type ReactNode } from 'react';+import { MemoryRouter } from 'react-router-dom';++import { ApiProvider } from '@/context/ApiContext';+import { BotsProvider } from '@/context/BotsProvider';+import { InstanceAuthorizationContext } from '@/context/InstanceAuthorizationContext';+import { ToastProvider } from '@/context/ToastProvider';+import { UnsavedChangesContext } from '@/context/unsavedChangesContext';+import { WindowManagerContext, type WindowManagerValue } from '@/context/WindowManagerContext';+import { WorkbenchInboxContext, type InboxState } from '@/context/WorkbenchInboxContext';+import { WorkbenchProjectsContext, type WorkbenchProjectsTree } from '@/context/WorkbenchProjectsContext';++import { owner, type WorkbenchFixtures } from './fixtures';++/** Any member a frame does not set is a no-op: functions resolve to null, nothing throws. */+function inert<T extends object>(known: Partial<T>): T {+ return new Proxy(known, {+ get(target, key) {+ if (key in target) return target[key as keyof typeof target];+ return () => Promise.resolve(null);+ },+ }) as T;+}++function inboxValue(fixtures: WorkbenchFixtures): InboxState {+ const unreadBySession = fixtures.unreadBySession ?? {};+ const counts = Object.values(unreadBySession);+ return inert<InboxState>({+ inboxSessions: fixtures.inboxSessions ?? [],+ unreadBySession,+ unreadLoaded: true,+ totalUnread: counts.reduce((sum, n) => sum + n, 0),+ unreadSessions: counts.filter((n) => n > 0).length,+ nextCursor: null,+ loading: false,+ loadingMore: false,+ activateFeed: () => () => {},+ });+}++function projectsValue(fixtures: WorkbenchFixtures): WorkbenchProjectsTree {+ const expanded = new Set(fixtures.expandedProjects ?? []);+ return inert<WorkbenchProjectsTree>({+ projects: fixtures.projects ?? [],+ projectsError: null,+ activate: () => () => {},+ sessionsOf: (projectId: string) => ({+ sessions: fixtures.sessionsByProject?.[projectId] ?? [],+ loading: false,+ loadingMore: false,+ cursor: null,+ error: false,+ }),+ expanded,+ isExpanded: (projectId: string) => expanded.has(projectId),+ toggleExpanded: () => {},+ loadMore: () => {},+ reloadSessions: () => {},+ creatingSession: () => false,+ isReorderingProjects: false,+ isSavingDefaultAgent: () => false,+ });+}++/** The providers the Workbench surfaces read, served from fixtures. The API and Bots providers are the+ * real ones, reading the frame's API fixtures through the network stub (`apiResponses`). */+export function DesignShell({ fixtures = {}, route = '/', children }: { fixtures?: WorkbenchFixtures; route?: string; children: ReactNode }) {+ const inbox = useMemo(() => inboxValue(fixtures), [fixtures]);+ const projects = useMemo(() => projectsValue(fixtures), [fixtures]);+ const authorization = useMemo(+ () => ({ remote: false, instanceKind: null, instanceRole: 'owner' as const, capabilities: fixtures.capabilities ?? owner }),+ [fixtures],+ );+ return (+ <MemoryRouter initialEntries={[route]}>+ <ToastProvider>+ <ApiProvider>+ <InstanceAuthorizationContext.Provider value={authorization}>+ <UnsavedChangesContext.Provider value={{ setRegistration: () => {}, authorizeRouteAction: () => null }}>+ <WindowManagerContext.Provider value={inert<WindowManagerValue>({ windows: [], focusedId: null, gestureActive: false })}>+ <WorkbenchInboxContext.Provider value={inbox}>+ <WorkbenchProjectsContext.Provider value={projects}>+ <BotsProvider>{children}</BotsProvider>+ </WorkbenchProjectsContext.Provider>+ </WorkbenchInboxContext.Provider>+ </WindowManagerContext.Provider>+ </UnsavedChangesContext.Provider>+ </InstanceAuthorizationContext.Provider>+ </ApiProvider>+ </ToastProvider>+ </MemoryRouter>+ );+}diff --git a/ui/design/shell/SidebarColumn.tsx b/ui/design/shell/SidebarColumn.tsxnew file mode 100644index 000000000..edcff464c--- /dev/null+++ b/ui/design/shell/SidebarColumn.tsx@@ -0,0 +1,10 @@+import type { ReactNode } from 'react';++/** The desktop sidebar column as AppShell draws it (aside classes, without the bottom cluster). */+export function SidebarColumn({ children }: { children: ReactNode }) {+ return (+ <aside className="flex h-full w-full flex-col justify-between gap-6 border-r border-border bg-[var(--sidebar-background)] px-4 pb-4 pt-[0.625rem]">+ <div className="flex min-h-0 flex-1 flex-col">{children}</div>+ </aside>+ );+}diff --git a/ui/design/shell/clock.ts b/ui/design/shell/clock.tsnew file mode 100644index 000000000..f7abe3bff--- /dev/null+++ b/ui/design/shell/clock.ts@@ -0,0 +1,17 @@+// Frames show relative times ("8 minutes ago"), so the design clock is fixed:+// a screenshot taken today and one taken next month are the same picture.+export const DESIGN_NOW = Date.UTC(2026, 10, 1, 8, 0);++export function installFixedClock() {+ const RealDate = Date;+ class FixedDate extends RealDate {+ constructor(...args: ConstructorParameters<typeof Date> | []) {+ if (args.length === 0) super(DESIGN_NOW);+ else super(...(args as ConstructorParameters<typeof Date>));+ }+ static now() {+ return DESIGN_NOW;+ }+ }+ globalThis.Date = FixedDate as DateConstructor;+}diff --git a/ui/design/shell/fixtures.ts b/ui/design/shell/fixtures.tsnew file mode 100644index 000000000..8d9c1056b--- /dev/null+++ b/ui/design/shell/fixtures.ts@@ -0,0 +1,135 @@+import type { InboxSession, InstanceCapabilities, WorkbenchProject, WorkbenchSession } from '@/context/ApiContext';+import type { BotRuntimeStatus } from '@/context/BotsContext';+import type { Bot, BotAvatar } from '@/lib/bots';+import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';++import { DESIGN_NOW } from './clock';++/** What a frame can set. Everything is optional; omitted parts are empty, not loading. */+export interface WorkbenchFixtures {+ capabilities?: InstanceCapabilities;+ projects?: WorkbenchProject[];+ sessionsByProject?: Record<string, WorkbenchSession[]>;+ expandedProjects?: string[];+ inboxSessions?: InboxSession[];+ unreadBySession?: Record<string, number>;+ /** The Owner's Bots, served as `GET /api/bots` to the real Bots provider. */+ bots?: Bot[];+ /** Agent status of Bot Sessions, by Session id (the running dot). */+ botStatus?: Record<string, BotRuntimeStatus>;+ /** Web Storage entries the frame starts with (a remembered preference, such as a collapsed section). */+ storage?: Record<string, string>;+ /** API responses by path plus query (`/api/inbox?session=ses_pm&limit=1`) or by path, for anything else a frame fetches. */+ api?: Record<string, unknown>;+}++/** Everything the frame's providers fetch, as the network stub serves it. */+export function apiResponses(fixtures: WorkbenchFixtures = {}): Record<string, unknown> {+ const responses: Record<string, unknown> = {};+ if (fixtures.bots) responses['/api/bots'] = { ok: true, bots: fixtures.bots };+ // Every Bot Session is read for its status dot; idle unless the frame says otherwise.+ for (const { session_id: sessionId } of fixtures.bots ?? []) {+ const status = fixtures.botStatus?.[sessionId] ?? 'idle';+ responses[`/api/sessions/${sessionId}`] = session(sessionId, '', '', { scope_id: null, project_id: null, agent_status: status });+ }+ return { ...responses, ...fixtures.api };+}++export const owner = OWNER_INSTANCE_CAPABILITIES;++const at = (minutesAgo: number) => new Date(DESIGN_NOW - minutesAgo * 60_000).toISOString();++export const project = (id: string, name: string, extra: Partial<WorkbenchProject> = {}): WorkbenchProject => ({+ id,+ scope_id: `avibe::project::${id}`,+ display_name: name,+ folder_path: `/Users/demo/${name}`,+ created_at: at(60 * 24 * 30),+ last_active_at: at(30),+ archived: false,+ capabilities: { can_chat: true, has_folder: true },+ ...extra,+});++export const session = (id: string, projectId: string, title: string, extra: Partial<WorkbenchSession> = {}): WorkbenchSession => ({+ id,+ scope_id: `avibe::project::${projectId}`,+ project_id: projectId,+ title,+ agent_id: 'agent_vibey',+ agent_name: 'vibey',+ agent_backend: 'vibey',+ agent_variant: 'vibey',+ model: 'gpt-6-astra',+ reasoning_effort: 'high',+ status: 'active',+ visibility: 'foreground',+ pinned: false,+ agent_status: 'idle',+ workdir: null,+ native_session_id: null,+ created_at: at(600),+ updated_at: at(20),+ last_active_at: at(20),+ metadata: {},+ ...extra,+});++export const inboxRow = (+ sessionId: string,+ projectName: string | null,+ title: string,+ preview: string,+ minutesAgo: number,+ unread = 0,+): InboxSession => ({+ session_id: sessionId,+ scope_id: null,+ project_id: null,+ project_name: projectName,+ title,+ last_activity_at: at(minutesAgo),+ last_message_author: 'agent',+ replied: false,+ preview_text: preview,+ preview_at: at(minutesAgo),+ unread_count: unread,+ unread: unread > 0,+});++/** The project list the sidebar frames share. */+export const demoProjects = [+ project('proj_avibe', 'avibe'),+ project('proj_chainbot', 'chainbot'),+ project('proj_relay', 'ai-relay'),+ project('proj_work', 'ai-work'),+ project('proj_article', 'x-article'),+ project('proj_askill', 'askill-workspace'),+];++export const demoSessions: Record<string, WorkbenchSession[]> = {+ proj_avibe: [+ session('ses_demo_cache', 'proj_avibe', '修复中途断缓存', { agent_status: 'running' }),+ session('ses_demo_inbox', 'proj_avibe', '收件箱分类设计'),+ session('ses_demo_pr', 'proj_avibe', 'PR #3073 交付', { agent_status: 'failed' }),+ ],+};++export const bot = (handle: string, displayName: string, role: string, avatar: BotAvatar | null, position: number): Bot => ({+ handle,+ display_name: displayName,+ avatar,+ role,+ agent_name: handle,+ session_id: `ses_${handle}`,+ position,+ builtin: handle === 'main',+});++/** The main Bot as a new install has it: the mascot, and the localized default name. */+export const mainBot = bot('main', '', "The user's main Bot and first point of contact.", { kind: 'mascot' }, 0);+export const demoBots = [+ mainBot,+ bot('cso', '首席安全官', '依赖与权限的安全审计,每周汇报', { kind: 'emoji', emoji: '🛡️', hue: 200 }, 1),+ bot('pm', '产品经理', '需求池整理与优先级', { kind: 'emoji', emoji: '🧭', hue: 42 }, 2),+];diff --git a/ui/design/shell/network.ts b/ui/design/shell/network.tsnew file mode 100644index 000000000..02e0f77a9--- /dev/null+++ b/ui/design/shell/network.ts@@ -0,0 +1,63 @@+// Design frames never reach a server. Every request is answered here: from the+// frame's API fixtures (keyed by path plus query, else by path), else with an empty+// object. Paths a frame touched without a fixture are recorded, so the screenshot+// tool can report what a frame depends on.++const touched = new Set<string>();+let responses: Record<string, unknown> = {};+let inflight = 0;++export const designNetwork = {+ setResponses(next: Record<string, unknown>) {+ responses = next;+ },+ unfixtured(): string[] {+ return [...touched].sort();+ },+ /** Resolves once no request has been in flight for two consecutive frames (at most `limitMs`). */+ async quiet(limitMs = 3000): Promise<void> {+ const deadline = performance.now() + limitMs;+ let calm = 0;+ while (calm < 2 && performance.now() < deadline) {+ await new Promise((resolve) => requestAnimationFrame(resolve));+ calm = inflight === 0 ? calm + 1 : 0;+ }+ },+};++function urlOf(input: RequestInfo | URL): URL {+ const raw = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ return new URL(raw, window.location.href);+}++export function installDesignNetwork() {+ window.fetch = async (input: RequestInfo | URL) => {+ inflight += 1;+ try {+ const url = urlOf(input);+ const key = [`${url.pathname}${url.search}`, url.pathname].find((candidate) => candidate in responses);+ if (key === undefined) touched.add(url.pathname);+ const body = key === undefined ? {} : responses[key];+ return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });+ } finally {+ // Let the caller's continuation run before the request counts as settled.+ setTimeout(() => {+ inflight -= 1;+ }, 0);+ }+ };+ class SilentEventSource extends EventTarget {+ readonly url: string;+ readonly readyState = 0;+ readonly withCredentials = false;+ onopen = null;+ onmessage = null;+ onerror = null;+ constructor(url: string | URL) {+ super();+ this.url = String(url);+ }+ close() {}+ }+ window.EventSource = SilentEventSource as unknown as typeof EventSource;+}diff --git a/ui/design/shell/storage.ts b/ui/design/shell/storage.tsnew file mode 100644index 000000000..ac38cc46c--- /dev/null+++ b/ui/design/shell/storage.ts@@ -0,0 +1,38 @@+// Product components keep preferences (collapsed sidebar sections, the last-used+// Agent) in Web Storage, which every frame and Show Page on one origin shares. A+// frame's state must come from its fixtures alone, so each design document gets+// fresh in-memory storage before any product module loads (main.tsx imports this+// first); a frame that draws a remembered preference seeds it as a fixture.++class MemoryStorage implements Storage {+ private items = new Map<string, string>();+ get length() {+ return this.items.size;+ }+ clear() {+ this.items.clear();+ }+ getItem(key: string) {+ return this.items.get(key) ?? null;+ }+ key(index: number) {+ return [...this.items.keys()][index] ?? null;+ }+ removeItem(key: string) {+ this.items.delete(key);+ }+ setItem(key: string, value: string) {+ this.items.set(key, String(value));+ }+}++const local = new MemoryStorage();+for (const [name, storage] of [['localStorage', local], ['sessionStorage', new MemoryStorage()]] as const) {+ Object.defineProperty(window, name, { configurable: true, get: () => storage });+}++export const designStorage = {+ seed(entries: Record<string, string> = {}) {+ for (const [key, value] of Object.entries(entries)) local.setItem(key, value);+ },+};diff --git a/ui/design/tsconfig.json b/ui/design/tsconfig.jsonnew file mode 100644index 000000000..a8ac7db46--- /dev/null+++ b/ui/design/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "../tsconfig.app.json",+ "compilerOptions": {+ "tsBuildInfoFile": "../node_modules/.tmp/tsconfig.design.tsbuildinfo",+ "baseUrl": "..",+ "paths": { "@/*": ["./src/*"] }+ },+ "include": ["./**/*.ts", "./**/*.tsx", "../agentation.d.ts"]+}diff --git a/ui/package.json b/ui/package.jsonindex 6b35b3d39..503937d70 100644--- a/ui/package.json+++ b/ui/package.json@@ -8,6 +8,11 @@},"scripts": {"dev": "vite",+ "design": "vite --open /design.html",+ "design:shot": "node scripts/design-shot.mjs",+ "design:build": "node scripts/design-build.mjs",+ "design:export": "node scripts/design-export.mjs",+ "typecheck:design": "tsc -p design/tsconfig.json --noEmit","validate:imports": "node scripts/validate-out-of-tree-imports.mjs","build": "npm run validate:imports && tsc -b && vite build","lint": "node scripts/lint-baseline.mjs",diff --git a/ui/scripts/design-build.mjs b/ui/scripts/design-build.mjsnew file mode 100644index 000000000..26ae0acb3--- /dev/null+++ b/ui/scripts/design-build.mjs@@ -0,0 +1,20 @@+#!/usr/bin/env node+// Build the design canvas as static files: `npm run design:build -- --out <dir>`.+// Paths are relative, so the output works under any base, such as a Show Page's public/ folder.+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { build } from 'vite';++const uiRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const index = process.argv.indexOf('--out');+const outDir = resolve(index === -1 ? join(uiRoot, 'design', '.dist') : process.argv[index + 1]);++await build({+ root: uiRoot,+ base: './',+ logLevel: 'warn',+ publicDir: false,+ build: { outDir, emptyOutDir: true, rollupOptions: { input: join(uiRoot, 'design.html') } },+});+console.log(outDir);diff --git a/ui/scripts/design-export.mjs b/ui/scripts/design-export.mjsnew file mode 100644index 000000000..b0ec18e53--- /dev/null+++ b/ui/scripts/design-export.mjs@@ -0,0 +1,33 @@+#!/usr/bin/env node+// Export design frames for a Show Page: the live canvas (real components, interactive),+// a screenshot of each frame, frames.json, and the <DesignFrame> component that embeds them.+//+// npm run design:export -- sidebar/bots into this Agent Session's Show Page+// npm run design:export -- sidebar/bots --show <workspace> into another Show Page workspace+//+// Then, in a page of that Show workspace:+// import { DesignFrame } from "../design/DesignFrame"+// <DesignFrame id="sidebar/bots/three" />+import { execFileSync } from 'node:child_process';+import { copyFile, mkdir } from 'node:fs/promises';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const uiRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const args = process.argv.slice(2);+const index = args.indexOf('--show');+const show = resolve(index === -1 ? JSON.parse(execFileSync('vibe', ['show', 'path'], { encoding: 'utf8' })).path : args.splice(index, 2)[1]);+const out = join(show, 'public', 'design');+const node = (script, extra) => execFileSync(process.execPath, [join(uiRoot, 'scripts', script), ...extra], { stdio: ['ignore', 'ignore', 'inherit'] });++node('design-build.mjs', ['--out', join(out, 'canvas')]);+let failed = false;+try {+ node('design-shot.mjs', ['--out', join(out, 'shots'), '--manifest', join(out, 'frames.json'), ...args]);+} catch {+ failed = true;+}+await mkdir(join(show, 'src', 'design'), { recursive: true });+await copyFile(join(uiRoot, 'design', 'export', 'DesignFrame.tsx'), join(show, 'src', 'design', 'DesignFrame.tsx'));+console.log(`Exported to ${out}\nIn a page of ${show}:\n import { DesignFrame } from "../design/DesignFrame"\n <DesignFrame id="<frame id>" />`);+process.exit(failed ? 1 : 0);diff --git a/ui/scripts/design-shot.mjs b/ui/scripts/design-shot.mjsnew file mode 100644index 000000000..00e893ab5--- /dev/null+++ b/ui/scripts/design-shot.mjs@@ -0,0 +1,104 @@+#!/usr/bin/env node+// Render design frames and save one PNG per frame and theme.+//+// npm run design:shot every frame, every theme it declares+// npm run design:shot -- sidebar/bots frames whose id starts with the argument+// npm run design:shot -- --theme dark --lang en --out /tmp/shots+// --manifest <file> also merge a JSON index of the shots into <file>+//+// Exits 1 when a frame logs a console error or fails to render, so it doubles as `design:check`.+import { createHash } from 'node:crypto';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { dirname, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { chromium } from '@playwright/test';+import { createServer } from 'vite';++const uiRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const args = process.argv.slice(2);+const option = (name, fallback) => {+ const index = args.indexOf(`--${name}`);+ if (index === -1) return fallback;+ const [value] = args.splice(index, 2).slice(1);+ return value;+};+const theme = option('theme', null);+const lang = option('lang', 'zh');+const out = resolve(option('out', join(uiRoot, 'design', '.shots')));+const manifestPath = option('manifest', null);+const prefixes = args;++const server = await createServer({ root: uiRoot, logLevel: 'error', server: { port: 0, strictPort: false } });+await server.listen();+const base = server.resolvedUrls.local[0];+const browser = await chromium.launch();+const page = await browser.newPage({ deviceScaleFactor: 2 });+const errors = [];+page.on('console', (message) => {+ if (message.type() === 'error') errors.push(message.text());+});+page.on('pageerror', (error) => errors.push(String(error)));++let failed = false;+const shots = [];+let all = [];+try {+ await page.goto(`${base}design.html?lang=${lang}`);+ await page.waitForFunction(() => window.__DESIGN__);+ all = await page.evaluate(() => window.__DESIGN__.frames);+ const selected = all.filter((f) => prefixes.length === 0 || prefixes.some((p) => f.id.startsWith(p)));+ if (selected.length === 0) throw new Error(`no frame matches ${prefixes.join(', ')}`);+ for (const frame of selected) {+ for (const t of theme ? [theme] : frame.themes) {+ errors.length = 0;+ const started = Date.now();+ await page.setViewportSize({ width: frame.width, height: frame.height });+ await page.goto(`${base}design.html?frame=${encodeURIComponent(frame.id)}&theme=${t}&lang=${lang}`);+ await page.waitForSelector('body[data-design-ready]', { timeout: 15_000 });+ if (frame.hover) {+ // Hover states open on a delay and may fetch; wait them out.+ await page.hover(frame.hover);+ await page.waitForTimeout(800);+ await page.evaluate(() => window.__DESIGN__.quiet());+ }+ const file = join(out, `${frame.id}.${t}.png`);+ await mkdir(dirname(file), { recursive: true });+ // The viewport is the frame, so popovers and dialogs portaled to <body> are captured too.+ const png = await page.screenshot({ path: file, animations: 'disabled', clip: { x: 0, y: 0, width: frame.width, height: frame.height } });+ const unfixtured = await page.evaluate(() => window.__DESIGN__.unfixtured());+ const result = { frame: frame.id, theme: t, file, ms: Date.now() - started, unfixtured, errors: [...errors] };+ if (errors.length) failed = true;+ shots.push({ ...frame, theme: t, png: file, hash: createHash('sha1').update(png).digest('hex').slice(0, 10) });+ console.log(JSON.stringify(result));+ }+ }+} catch (error) {+ failed = true;+ console.error(String(error));+} finally {+ await browser.close();+ await server.close();+}++if (manifestPath && shots.length) {+ // Merge: re-rendered shots replace their entries, frames that no longer exist drop out.+ const known = new Set(all.map((f) => f.id));+ let previous = [];+ try {+ previous = JSON.parse(await readFile(manifestPath, 'utf8')).shots ?? [];+ } catch {+ previous = [];+ }+ const key = (s) => `${s.id}.${s.theme}`;+ const fresh = new Map(+ shots.map((s) => [+ key(s),+ { id: s.id, file: s.file, title: s.title, status: s.status, theme: s.theme, lang, width: s.width, height: s.height, hash: s.hash, src: relative(dirname(out), s.png).split('\\').join('/') },+ ]),+ );+ const merged = [...previous.filter((s) => known.has(s.id) && !fresh.has(key(s))), ...fresh.values()].sort((a, b) => key(a).localeCompare(key(b)));+ await mkdir(dirname(manifestPath), { recursive: true });+ await writeFile(manifestPath, JSON.stringify({ generatedAt: new Date().toISOString(), lang, shots: merged }, null, 2));+}+process.exit(failed ? 1 : 0);