feat(web): React 19 + Vite + Tailwind v4 + shadcn foundation
- design tokens ported verbatim from the product design, data-theme light/dark - app shell: topbar, sidebar/rail/tabbar responsive nav, lang + theme menus - ui primitives (button/card/badge/dot/chip/tabs/dialog/sheet/toast/kv/seg/progress) - api client, reconnecting ws client, zustand stores, route guard to /connect - full zh/en dictionaries (key parity test), 32 vitest specs, dist committed
This commit is contained in:
1 parent
4e98ef8658
commit
5b55e622ea
63 files changed
+8466
No files matched your search
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/styles/app.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<link rel="icon" href="/pi2-nvim.png" />
|
||||
<meta name="theme-color" content="oklch(0.985 0.004 90)" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="oklch(0.145 0.008 60)" media="(prefers-color-scheme: dark)" />
|
||||
<title>pi2.nvim</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "pi2-web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "pi2 web console — React port of the pi2 web UI prototype",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-checkbox": "^1.4.1",
|
||||
"@radix-ui/react-dialog": "^1.3.1",
|
||||
"@radix-ui/react-dropdown-menu": "^2.2.1",
|
||||
"@radix-ui/react-progress": "^1.2.1",
|
||||
"@radix-ui/react-select": "^2.4.1",
|
||||
"@radix-ui/react-slot": "^1.5.0",
|
||||
"@radix-ui/react-switch": "^1.4.1",
|
||||
"@radix-ui/react-tabs": "^1.2.1",
|
||||
"@radix-ui/react-tooltip": "^1.4.1",
|
||||
"@tanstack/react-query": "^5.104.5",
|
||||
"@tanstack/react-router": "^1.170.45",
|
||||
"@tanstack/react-virtual": "^3.14.21",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"i18next": "^26.5.3",
|
||||
"lucide-react": "^1.60.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-i18next": "^17.1.0",
|
||||
"react-resizable-panels": "^4.14.8",
|
||||
"sonner": "^2.0.8",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"vaul": "^1.1.2",
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@testing-library/jest-dom": "^7.0.1",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@types/node": "^22.19.0",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"jsdom": "^30.1.3",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.3.7",
|
||||
"vitest": "^5.0.5"
|
||||
}
|
||||
}
|
||||
Generated
+3439
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
packages:
|
||||
- "."
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
minimumReleaseAgeExclude:
|
||||
- lucide-react@1.60.0
|
||||
- react-resizable-panels@4.14.8
|
||||
@@ -0,0 +1,5 @@
|
||||
export default {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 47 KiB |
@@ -0,0 +1,178 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon, type IconName } from "@/components/icons";
|
||||
import { LangMenu } from "@/components/shared/lang-menu";
|
||||
import { ServerChip } from "@/components/shared/server-chip";
|
||||
import { ThemeMenu } from "@/components/shared/theme-menu";
|
||||
import { SidebarItem } from "@/components/ui/sidebar-item";
|
||||
import { api } from "@/lib/api";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
import { Link, Outlet, useRouterState } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
interface NavItem {
|
||||
to: "/workspaces" | "/chat" | "/status";
|
||||
labelKey: string;
|
||||
icon: IconName;
|
||||
match: (pathname: string) => boolean;
|
||||
}
|
||||
|
||||
const NAV: NavItem[] = [
|
||||
{
|
||||
to: "/workspaces",
|
||||
labelKey: "nav.workspaces",
|
||||
icon: "folder",
|
||||
match: (p) => p === "/workspaces" || p.startsWith("/workspace/"),
|
||||
},
|
||||
{ to: "/chat", labelKey: "nav.chat", icon: "chat", match: (p) => p.startsWith("/chat") },
|
||||
{ to: "/status", labelKey: "nav.status", icon: "status", match: (p) => p.startsWith("/status") },
|
||||
];
|
||||
|
||||
function pageName(pathname: string): string {
|
||||
if (pathname.startsWith("/connect")) return "connect";
|
||||
if (pathname.startsWith("/status")) return "status";
|
||||
if (pathname.startsWith("/chat")) return "chat";
|
||||
return "workspaces";
|
||||
}
|
||||
|
||||
function RouteTitle({ pathname }: { pathname: string }) {
|
||||
const { t } = useTranslation();
|
||||
const server = useConnectionStore((state) => state.server);
|
||||
const workspaces = useWorkspacesStore((state) => state.items);
|
||||
const selectedSession = useSessionsStore((state) =>
|
||||
pathname.startsWith("/chat/") ? state.getSession(decodeURIComponent(pathname.slice("/chat/".length))) : undefined,
|
||||
);
|
||||
|
||||
const workspaceId = pathname.startsWith("/workspace/")
|
||||
? decodeURIComponent(pathname.slice("/workspace/".length))
|
||||
: selectedSession?.workspaceId;
|
||||
const workspace = workspaces.find((w) => w.workspaceId === workspaceId);
|
||||
|
||||
let crumbs: string[] = [];
|
||||
let title = t("nav.workspaces");
|
||||
|
||||
if (pathname.startsWith("/connect")) {
|
||||
title = t("connect.title");
|
||||
} else if (pathname.startsWith("/status")) {
|
||||
crumbs = server?.name ? [server.name] : [];
|
||||
title = t("nav.status");
|
||||
} else if (pathname === "/chat") {
|
||||
title = t("nav.chat");
|
||||
} else if (pathname.startsWith("/chat/")) {
|
||||
crumbs = workspace?.name ? [workspace.name] : [];
|
||||
title = selectedSession?.name ?? decodeURIComponent(pathname.slice("/chat/".length));
|
||||
} else if (pathname.startsWith("/workspace/")) {
|
||||
crumbs = [t("nav.workspaces")];
|
||||
title = workspace?.name ?? workspaceId ?? pathname;
|
||||
} else {
|
||||
crumbs = server?.name ? [server.name] : [];
|
||||
title = t("nav.workspaces");
|
||||
}
|
||||
|
||||
const parts = [...crumbs, title].filter((part): part is string => Boolean(part));
|
||||
return (
|
||||
<nav className="crumbs" aria-label={t("shell.navLabel")}>
|
||||
{parts.map((part, index) => {
|
||||
const last = index === parts.length - 1;
|
||||
return (
|
||||
<span key={`${part}-${index}`} className="contents">
|
||||
{index > 0 ? <span className="sep">/</span> : null}
|
||||
<span className={last ? "truncate" : undefined}>{part}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
function NavLinks({ pathname }: { pathname: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{NAV.map((item) => (
|
||||
<SidebarItem key={item.to} active={item.match(pathname)} asChild>
|
||||
<Link to={item.to}>
|
||||
<Icon name={item.icon} />
|
||||
<span>{t(item.labelKey)}</span>
|
||||
</Link>
|
||||
</SidebarItem>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppShell() {
|
||||
const { t } = useTranslation();
|
||||
const pathname = useRouterState({ select: (state) => state.location.pathname });
|
||||
const paired = useConnectionStore((state) => state.paired);
|
||||
const setServer = useConnectionStore((state) => state.setServer);
|
||||
const isConnect = pathname.startsWith("/connect");
|
||||
const page = pageName(pathname);
|
||||
|
||||
const info = useQuery({
|
||||
queryKey: ["info"],
|
||||
queryFn: ({ signal }) => api.info(signal),
|
||||
enabled: paired && !isConnect,
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (info.data) setServer(info.data);
|
||||
}, [info.data, setServer]);
|
||||
|
||||
useEffect(() => {
|
||||
document.body.dataset.page = page;
|
||||
}, [page]);
|
||||
|
||||
return (
|
||||
<div className="shell bg-background text-foreground">
|
||||
<header className="topbar">
|
||||
<Link to="/workspaces" className="brand">
|
||||
<img
|
||||
className="brand__logo"
|
||||
src="/pi2-nvim.png"
|
||||
alt=""
|
||||
width={24}
|
||||
height={24}
|
||||
decoding="async"
|
||||
/>
|
||||
<span className="brand__text">pi2.nvim</span>
|
||||
</Link>
|
||||
<RouteTitle pathname={pathname} />
|
||||
<div className="spacer" />
|
||||
<div className="actions">
|
||||
{isConnect ? null : <ServerChip />}
|
||||
<LangMenu />
|
||||
<ThemeMenu />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="body">
|
||||
{isConnect ? null : (
|
||||
<>
|
||||
<aside className="sidebar">
|
||||
<div className="nav-label">{t("shell.navLabel")}</div>
|
||||
<NavLinks pathname={pathname} />
|
||||
</aside>
|
||||
<aside className="rail">
|
||||
<NavLinks pathname={pathname} />
|
||||
</aside>
|
||||
</>
|
||||
)}
|
||||
<main className="main">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{isConnect ? null : (
|
||||
<nav className="tabbar">
|
||||
<NavLinks pathname={pathname} />
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import {
|
||||
Activity,
|
||||
Ban,
|
||||
Boxes,
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Circle,
|
||||
Clock,
|
||||
Copy,
|
||||
Cpu,
|
||||
Eye,
|
||||
File,
|
||||
Folder,
|
||||
GitBranch,
|
||||
Globe,
|
||||
HardDrive,
|
||||
Laptop,
|
||||
LayoutGrid,
|
||||
ListTodo,
|
||||
MemoryStick,
|
||||
MessageSquare,
|
||||
Monitor,
|
||||
Moon,
|
||||
MoreHorizontal,
|
||||
Pencil,
|
||||
Play,
|
||||
Plug,
|
||||
Plus,
|
||||
QrCode,
|
||||
RefreshCw,
|
||||
ScanLine,
|
||||
Search,
|
||||
Send,
|
||||
Server,
|
||||
Settings,
|
||||
Smartphone,
|
||||
Square,
|
||||
Sun,
|
||||
Tablet,
|
||||
Terminal,
|
||||
Trash2,
|
||||
TriangleAlert,
|
||||
X,
|
||||
Zap,
|
||||
} from "lucide-react";
|
||||
import type { ComponentType } from "react";
|
||||
|
||||
export type IconName =
|
||||
| "logo"
|
||||
| "server"
|
||||
| "plus"
|
||||
| "scan"
|
||||
| "qr"
|
||||
| "folder"
|
||||
| "chat"
|
||||
| "status"
|
||||
| "search"
|
||||
| "chevron-down"
|
||||
| "chevron-right"
|
||||
| "send"
|
||||
| "stop"
|
||||
| "x"
|
||||
| "check"
|
||||
| "alert"
|
||||
| "clock"
|
||||
| "cpu"
|
||||
| "mem"
|
||||
| "disk"
|
||||
| "model"
|
||||
| "phone"
|
||||
| "laptop"
|
||||
| "tablet"
|
||||
| "copy"
|
||||
| "revoke"
|
||||
| "refresh"
|
||||
| "play"
|
||||
| "terminal"
|
||||
| "todo"
|
||||
| "branch"
|
||||
| "eye"
|
||||
| "edit"
|
||||
| "trash"
|
||||
| "more"
|
||||
| "settings"
|
||||
| "sun"
|
||||
| "moon"
|
||||
| "monitor"
|
||||
| "dot"
|
||||
| "globe"
|
||||
| "plug"
|
||||
| "file"
|
||||
| "zap";
|
||||
|
||||
type IconComponent = ComponentType<{ size?: number | string; strokeWidth?: number; className?: string; "aria-hidden"?: boolean }>;
|
||||
|
||||
/** 1:1 name map for the prototype's `App.icon(name)` (Lucide, 24 viewBox, stroke 1.75). */
|
||||
const ICONS: Record<IconName, IconComponent> = {
|
||||
logo: LayoutGrid,
|
||||
server: Server,
|
||||
plus: Plus,
|
||||
scan: ScanLine,
|
||||
qr: QrCode,
|
||||
folder: Folder,
|
||||
chat: MessageSquare,
|
||||
status: Activity,
|
||||
search: Search,
|
||||
"chevron-down": ChevronDown,
|
||||
"chevron-right": ChevronRight,
|
||||
send: Send,
|
||||
stop: Square,
|
||||
x: X,
|
||||
check: Check,
|
||||
alert: TriangleAlert,
|
||||
clock: Clock,
|
||||
cpu: Cpu,
|
||||
mem: MemoryStick,
|
||||
disk: HardDrive,
|
||||
model: Boxes,
|
||||
phone: Smartphone,
|
||||
laptop: Laptop,
|
||||
tablet: Tablet,
|
||||
copy: Copy,
|
||||
revoke: Ban,
|
||||
refresh: RefreshCw,
|
||||
play: Play,
|
||||
terminal: Terminal,
|
||||
todo: ListTodo,
|
||||
branch: GitBranch,
|
||||
eye: Eye,
|
||||
edit: Pencil,
|
||||
trash: Trash2,
|
||||
more: MoreHorizontal,
|
||||
settings: Settings,
|
||||
sun: Sun,
|
||||
moon: Moon,
|
||||
monitor: Monitor,
|
||||
dot: Circle,
|
||||
globe: Globe,
|
||||
plug: Plug,
|
||||
file: File,
|
||||
zap: Zap,
|
||||
};
|
||||
|
||||
export interface IconProps {
|
||||
name: IconName;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Icon({ name, size = 16, strokeWidth = 1.75, className }: IconProps) {
|
||||
const Component = ICONS[name] ?? Circle;
|
||||
return <Component size={size} strokeWidth={strokeWidth} className={className} aria-hidden={true} />;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
|
||||
export interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description?: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
danger?: boolean;
|
||||
onConfirm: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
/** Destructive-action confirmation (base.css modal + two actions). */
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmLabel,
|
||||
cancelLabel,
|
||||
danger = true,
|
||||
onConfirm,
|
||||
}: ConfirmDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function confirm() {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await onConfirm();
|
||||
onOpenChange(false);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={title}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||
{cancelLabel ?? t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant={danger ? "danger" : "primary"} onClick={() => void confirm()} disabled={busy}>
|
||||
{confirmLabel ?? t("common.confirm")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{description ? <p className="muted">{description}</p> : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { Empty as EmptyState, type EmptyProps } from "@/components/ui/empty";
|
||||
@@ -0,0 +1,72 @@
|
||||
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
LANGUAGES,
|
||||
isLanguage,
|
||||
languageLabel,
|
||||
languageShort,
|
||||
setLanguage,
|
||||
type Language,
|
||||
} from "@/lib/i18n";
|
||||
|
||||
/** Topbar language menu (globe + current language + caret), persisted to `pi2-lang`. */
|
||||
export function LangMenu() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const current: Language = isLanguage(i18n.language) ? i18n.language : "zh";
|
||||
|
||||
return (
|
||||
<DropdownMenu.Root>
|
||||
<DropdownMenu.Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--sm btn--ghost lang-switch"
|
||||
title={t("shell.language")}
|
||||
aria-label={`${t("shell.language")}: ${languageLabel(current)}`}
|
||||
>
|
||||
<Icon name="globe" />
|
||||
<span className="lang-switch__full">{languageLabel(current)}</span>
|
||||
<span className="lang-switch__short">{languageShort(current)}</span>
|
||||
<span className="lang-switch__caret">
|
||||
<Icon name="chevron-down" />
|
||||
</span>
|
||||
</button>
|
||||
</DropdownMenu.Trigger>
|
||||
<DropdownMenu.Portal>
|
||||
<DropdownMenu.Content
|
||||
className="menu-popover"
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
aria-label={t("shell.language")}
|
||||
>
|
||||
<DropdownMenu.RadioGroup
|
||||
value={current}
|
||||
onValueChange={(value) => {
|
||||
if (isLanguage(value)) void setLanguage(value);
|
||||
}}
|
||||
>
|
||||
{LANGUAGES.map((language) => {
|
||||
const active = language === current;
|
||||
return (
|
||||
<DropdownMenu.RadioItem
|
||||
key={language}
|
||||
value={language}
|
||||
className={cn("menu__item", active && "is-active")}
|
||||
>
|
||||
<span className="grow">{languageLabel(language)}</span>
|
||||
{active ? (
|
||||
<span className="menu__check">
|
||||
<Icon name="check" />
|
||||
</span>
|
||||
) : null}
|
||||
</DropdownMenu.RadioItem>
|
||||
);
|
||||
})}
|
||||
</DropdownMenu.RadioGroup>
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
</DropdownMenu.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as React from "react";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface PageHeaderProps {
|
||||
title: React.ReactNode;
|
||||
subtitle?: React.ReactNode;
|
||||
/** Right-hand actions (buttons, links). */
|
||||
actions?: React.ReactNode;
|
||||
/** Optional extra row under the subtitle. */
|
||||
children?: React.ReactNode;
|
||||
size?: "default" | "lg";
|
||||
/** Title used for `document.title` when `title` is not a plain string. */
|
||||
docTitle?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared page header from workspaces.html/status.html:
|
||||
* h1 + muted subtitle, actions on the right (wrapping under <600px).
|
||||
*/
|
||||
export function PageHeader({ title, subtitle, actions, children, size = "default", docTitle, className }: PageHeaderProps) {
|
||||
useEffect(() => {
|
||||
if (typeof document === "undefined") return;
|
||||
const label = docTitle ?? (typeof title === "string" ? title : "");
|
||||
document.title = label ? `${label} — pi2.nvim` : "pi2.nvim";
|
||||
}, [docTitle, title]);
|
||||
|
||||
return (
|
||||
<header className={cn("page-head", size === "lg" && "page-head--lg", className)}>
|
||||
<div className="page-head__text">
|
||||
<h1 className="page-head__title">{title}</h1>
|
||||
{subtitle ? <p className="page-head__sub">{subtitle}</p> : null}
|
||||
{children}
|
||||
</div>
|
||||
{actions ? <div className="page-head__actions">{actions}</div> : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useEffect, useReducer } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { currentLanguage, localeFor } from "@/lib/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Translator = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
/** Relative time exactly as `App.fmt.rel` (just now / N minutes / N hours / N days). */
|
||||
export function formatRelative(ts: number, t: Translator, now = Date.now()): string {
|
||||
const seconds = Math.max(0, (now - ts) / 1000);
|
||||
if (seconds < 60) return t("time.justNow");
|
||||
if (seconds < 3600) return t("time.minutesAgo", { n: Math.floor(seconds / 60) });
|
||||
if (seconds < 86400) return t("time.hoursAgo", { n: Math.floor(seconds / 3600) });
|
||||
return t("time.daysAgo", { n: Math.floor(seconds / 86400) });
|
||||
}
|
||||
|
||||
export interface RelativeTimeProps {
|
||||
ts: number | null | undefined;
|
||||
className?: string;
|
||||
/** Refresh once a minute (default true). */
|
||||
live?: boolean;
|
||||
}
|
||||
|
||||
export function RelativeTime({ ts, className, live = true }: RelativeTimeProps) {
|
||||
const { t } = useTranslation();
|
||||
const [, tick] = useReducer((n: number) => n + 1, 0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!live) return;
|
||||
const timer = setInterval(tick, 30_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [live]);
|
||||
|
||||
if (ts == null || !Number.isFinite(ts)) return <span className={cn("muted", className)}>—</span>;
|
||||
|
||||
return (
|
||||
<time
|
||||
className={className}
|
||||
dateTime={new Date(ts).toISOString()}
|
||||
title={new Date(ts).toLocaleString(localeFor(currentLanguage()))}
|
||||
>
|
||||
{formatRelative(ts, t)}
|
||||
</time>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { StatusDot, serverDotClass } from "@/components/ui/status-dot";
|
||||
import type { InfoResponse } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
export interface ServerChipProps {
|
||||
server?: InfoResponse | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-server identity chip in the topbar: status dot + server name + hostname,
|
||||
* linking to /status. Never a server picker (single-server invariant).
|
||||
*/
|
||||
export function ServerChip({ server: override, className }: ServerChipProps) {
|
||||
const { t } = useTranslation();
|
||||
const stored = useConnectionStore((state) => state.server);
|
||||
const server = override ?? stored;
|
||||
|
||||
const name = server?.name ?? "pi2.nvim";
|
||||
const hostname =
|
||||
server?.hostname ?? (typeof window !== "undefined" ? window.location.hostname || "localhost" : "localhost");
|
||||
const status = server?.status ?? "offline";
|
||||
const dot = serverDotClass(status);
|
||||
const dotStatus = dot.replace("dot--", "") as "ok" | "attention" | "exited" | "idle";
|
||||
|
||||
return (
|
||||
<Link
|
||||
to="/status"
|
||||
className={cn("server-chip", className)}
|
||||
title={t("shell.serverChip", { name })}
|
||||
>
|
||||
<StatusDot status={dotStatus} title={t(`state.${status}`)} />
|
||||
<span className="server-chip__name">{name}</span>
|
||||
<span className="server-chip__host mono">{hostname}</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Seg, type SegOption } from "@/components/ui/seg";
|
||||
|
||||
type ThemeValue = "light" | "dark" | "system";
|
||||
|
||||
const THEMES: ThemeValue[] = ["light", "dark", "system"];
|
||||
|
||||
function isThemeValue(value: string | undefined): value is ThemeValue {
|
||||
return value === "light" || value === "dark" || value === "system";
|
||||
}
|
||||
|
||||
/** Topbar light/dark/system segment; next-themes persists it to `pi2-theme`. */
|
||||
export function ThemeMenu() {
|
||||
const { t } = useTranslation();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
const value: ThemeValue = mounted && isThemeValue(theme) ? theme : "system";
|
||||
const options: SegOption<ThemeValue>[] = THEMES.map((item) => ({
|
||||
value: item,
|
||||
label: t(`shell.${item}`),
|
||||
}));
|
||||
|
||||
return (
|
||||
<Seg
|
||||
value={value}
|
||||
options={options}
|
||||
onChange={setTheme}
|
||||
ariaLabel={t("shell.theme")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const badgeVariants = cva("badge", {
|
||||
variants: {
|
||||
tone: {
|
||||
default: "",
|
||||
ok: "badge--ok",
|
||||
warn: "badge--warn",
|
||||
err: "badge--err",
|
||||
info: "badge--info",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
tone: "default",
|
||||
},
|
||||
});
|
||||
|
||||
export interface BadgeProps extends React.HTMLAttributes<HTMLSpanElement>, VariantProps<typeof badgeVariants> {}
|
||||
|
||||
export function Badge({ className, tone, ...props }: BadgeProps) {
|
||||
return <span className={cn(badgeVariants({ tone }), className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const buttonVariants = cva("btn", {
|
||||
variants: {
|
||||
variant: {
|
||||
default: "",
|
||||
primary: "btn--primary",
|
||||
ghost: "btn--ghost",
|
||||
danger: "btn--danger",
|
||||
},
|
||||
size: {
|
||||
default: "",
|
||||
sm: "btn--sm",
|
||||
icon: "btn--icon",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
});
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(function Button(
|
||||
{ className, variant, size, asChild = false, type, ...props },
|
||||
ref,
|
||||
) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
className={cn(buttonVariants({ variant, size }), className)}
|
||||
{...(!asChild ? { type: type ?? "button" } : {})}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & { hover?: boolean }>(
|
||||
function Card({ className, hover = false, ...props }, ref) {
|
||||
return <div ref={ref} className={cn("card", hover && "card--hover", className)} {...props} />;
|
||||
},
|
||||
);
|
||||
|
||||
export function CardHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("card__head", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardTitle({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("card__title", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardSub({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("card__sub", className)} {...props} />;
|
||||
}
|
||||
|
||||
export const Panel = React.forwardRef<HTMLElement, React.HTMLAttributes<HTMLElement>>(function Panel(
|
||||
{ className, ...props },
|
||||
ref,
|
||||
) {
|
||||
return <section ref={ref} className={cn("panel", className)} {...props} />;
|
||||
});
|
||||
|
||||
export function PanelHead({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("panel__head", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function PanelBody({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("panel__body", className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Chip({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) {
|
||||
return <span className={cn("chip", className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { X } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const Dialog = DialogPrimitive.Root;
|
||||
export const DialogTrigger = DialogPrimitive.Trigger;
|
||||
export const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
export interface ModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
footer?: React.ReactNode;
|
||||
/** `wide` is the content overlay (≥60vw) used for subagent conversations. */
|
||||
size?: "default" | "wide";
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
}
|
||||
|
||||
/** Radix dialog styled as the base.css `.modal-backdrop > .modal` (bottom sheet <600px). */
|
||||
export function Modal({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
footer,
|
||||
size = "default",
|
||||
className,
|
||||
contentClassName,
|
||||
}: ModalProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPrimitive.Portal>
|
||||
<DialogPrimitive.Overlay className={cn("modal-backdrop", className)} />
|
||||
<DialogPrimitive.Content
|
||||
className={cn("modal", size === "wide" && "modal--wide", "modal-content", contentClassName)}
|
||||
>
|
||||
<DialogPrimitive.Title asChild>
|
||||
<h3>
|
||||
<span>{title}</span>
|
||||
<DialogPrimitive.Close asChild>
|
||||
<button type="button" className="btn btn--ghost btn--sm" aria-label={t("common.close")}>
|
||||
<X size={16} aria-hidden="true" />
|
||||
</button>
|
||||
</DialogPrimitive.Close>
|
||||
</h3>
|
||||
</DialogPrimitive.Title>
|
||||
{description ? (
|
||||
<DialogPrimitive.Description className="muted">{description}</DialogPrimitive.Description>
|
||||
) : null}
|
||||
{children}
|
||||
{footer ? <div className="modal-actions">{footer}</div> : null}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPrimitive.Portal>
|
||||
</DialogPrimitive.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface EmptyProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "title"> {
|
||||
icon?: React.ReactNode;
|
||||
title?: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
action?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Empty({ icon, title, description, action, className, children, ...props }: EmptyProps) {
|
||||
return (
|
||||
<div className={cn("empty", className)} {...props}>
|
||||
{icon}
|
||||
{title ? <div className="t">{title}</div> : null}
|
||||
{description ? <p className="muted">{description}</p> : null}
|
||||
{children}
|
||||
{action ? <div className="mt-4 flex justify-center">{action}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(function Input(
|
||||
{ className, type = "text", ...props },
|
||||
ref,
|
||||
) {
|
||||
return <input ref={ref} type={type} className={cn("input", className)} {...props} />;
|
||||
});
|
||||
|
||||
export const Textarea = React.forwardRef<HTMLTextAreaElement, React.ComponentProps<"textarea">>(function Textarea(
|
||||
{ className, ...props },
|
||||
ref,
|
||||
) {
|
||||
return <textarea ref={ref} className={cn("textarea", className)} {...props} />;
|
||||
});
|
||||
|
||||
export interface FieldProps {
|
||||
label: React.ReactNode;
|
||||
htmlFor?: string;
|
||||
hint?: React.ReactNode;
|
||||
error?: React.ReactNode;
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/** Label + control + hint/error (base.css `.field`). */
|
||||
export function Field({ label, htmlFor, hint, error, className, children }: FieldProps) {
|
||||
return (
|
||||
<div className={cn("field", error && "field--invalid", className)}>
|
||||
<label htmlFor={htmlFor}>{label}</label>
|
||||
{children}
|
||||
{error ? (
|
||||
<div className="hint is-err" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : hint ? (
|
||||
<div className="hint">{hint}</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface KVProps {
|
||||
label: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
/** Render the value with the mono font. */
|
||||
mono?: boolean;
|
||||
className?: string;
|
||||
valueClassName?: string;
|
||||
}
|
||||
|
||||
/** Key/value row from base.css (`.kv > k + v`); rendered with spans for valid JSX. */
|
||||
export function KV({ label, children, mono, className, valueClassName }: KVProps) {
|
||||
return (
|
||||
<div className={cn("kv", className)}>
|
||||
<span className="kv-key">{label}</span>
|
||||
<span className={cn("kv-val", mono && "mono", valueClassName)}>{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function KVList({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("kv-list", className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ProgressProps {
|
||||
value: number;
|
||||
max?: number;
|
||||
tone?: "default" | "warn" | "err";
|
||||
size?: "default" | "lg";
|
||||
className?: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function Progress({ value, max = 100, tone = "default", size = "default", className, label }: ProgressProps) {
|
||||
const pct = max > 0 ? Math.max(0, Math.min(100, (value / max) * 100)) : 0;
|
||||
return (
|
||||
<div
|
||||
className={cn("progress", tone === "warn" && "progress--warn", tone === "err" && "progress--err", size === "lg" && "progress--lg", className)}
|
||||
role="progressbar"
|
||||
aria-valuenow={Math.round(pct)}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-label={label}
|
||||
>
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface SegOption<T extends string> {
|
||||
value: T;
|
||||
label: React.ReactNode;
|
||||
}
|
||||
|
||||
export interface SegProps<T extends string> {
|
||||
value: T;
|
||||
options: readonly SegOption<T>[];
|
||||
onChange: (value: T) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Segmented control (base.css `.seg > button.active`). */
|
||||
export function Seg<T extends string>({ value, options, onChange, ariaLabel, className }: SegProps<T>) {
|
||||
return (
|
||||
<div className={cn("seg", className)} role="group" aria-label={ariaLabel}>
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
className={option.value === value ? "active" : undefined}
|
||||
aria-pressed={option.value === value}
|
||||
onClick={() => onChange(option.value)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { Check, ChevronDown } from "lucide-react";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const Select = SelectPrimitive.Root;
|
||||
export const SelectGroup = SelectPrimitive.Group;
|
||||
export const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
export const SelectTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(function SelectTrigger({ className, children, ...props }, ref) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger ref={ref} className={cn("select select-trigger", className)} {...props}>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown size={14} aria-hidden="true" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
});
|
||||
|
||||
export const SelectContent = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(function SelectContent({ className, children, position = "popper", ...props }, ref) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
position={position}
|
||||
sideOffset={4}
|
||||
className={cn("select-content", className)}
|
||||
{...props}
|
||||
>
|
||||
<SelectPrimitive.Viewport className="select-viewport">{children}</SelectPrimitive.Viewport>
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
});
|
||||
|
||||
export const SelectItem = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(function SelectItem({ className, children, ...props }, ref) {
|
||||
return (
|
||||
<SelectPrimitive.Item ref={ref} className={cn("select-item", className)} {...props}>
|
||||
<span className="select-item__indicator">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check size={14} aria-hidden="true" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
});
|
||||
|
||||
export const SelectLabel = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(function SelectLabel({ className, ...props }, ref) {
|
||||
return <SelectPrimitive.Label ref={ref} className={cn("px-3 py-1 text-xs text-muted-foreground", className)} {...props} />;
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as React from "react";
|
||||
import { Drawer } from "vaul";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const Sheet = Drawer.Root;
|
||||
export const SheetTrigger = Drawer.Trigger;
|
||||
export const SheetClose = Drawer.Close;
|
||||
export const SheetTitle = Drawer.Title;
|
||||
export const SheetDescription = Drawer.Description;
|
||||
|
||||
export interface SheetContentProps extends React.ComponentPropsWithoutRef<typeof Drawer.Content> {
|
||||
showHandle?: boolean;
|
||||
}
|
||||
|
||||
/** Mobile drawer (vaul), visually aligned with the design's `.sheet`. */
|
||||
export function SheetContent({ className, children, showHandle = true, ...props }: SheetContentProps) {
|
||||
return (
|
||||
<Drawer.Portal>
|
||||
<Drawer.Overlay className="sheet-overlay" />
|
||||
<Drawer.Content className={cn("sheet-content", className)} {...props}>
|
||||
{showHandle ? <div className="sheet-handle" aria-hidden="true" /> : null}
|
||||
{children}
|
||||
</Drawer.Content>
|
||||
</Drawer.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export function SheetHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("mb-4 flex flex-col gap-1", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function SheetFooter({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("mt-5 flex justify-end gap-2", className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface SidebarItemProps extends React.HTMLAttributes<HTMLElement> {
|
||||
active?: boolean;
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
/** Sidebar / rail / tabbar navigation row; compose the link or button as a child. */
|
||||
export function SidebarItem({ active, asChild = false, className, children, ...props }: SidebarItemProps) {
|
||||
const Comp = asChild ? Slot : "a";
|
||||
return (
|
||||
<Comp className={cn("nav-item", active && "active", className)} aria-current={active ? "page" : undefined} {...props}>
|
||||
{children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Spinner({ className, label }: { className?: string; label?: string }) {
|
||||
return <span className={cn("spinner", className)} role="status" aria-label={label} />;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Status-dot vocabulary from the design's `:PiSessions` state matrix. */
|
||||
export type DotStatus = "busy" | "compacting" | "idle" | "ok" | "err" | "attention" | "exited";
|
||||
|
||||
export const DOT_CLASS: Record<DotStatus, string> = {
|
||||
busy: "dot--busy",
|
||||
compacting: "dot--compacting",
|
||||
idle: "dot--idle",
|
||||
ok: "dot--ok",
|
||||
err: "dot--err",
|
||||
attention: "dot--attention",
|
||||
exited: "dot--exited",
|
||||
};
|
||||
|
||||
export type ServerStatus = "online" | "degraded" | "offline";
|
||||
|
||||
/** Server / connection status mapping (online → ok, degraded → attention, else exited). */
|
||||
export function serverDotClass(status: ServerStatus | string | null | undefined): string {
|
||||
if (status === "online") return DOT_CLASS.ok;
|
||||
if (status === "degraded" || status === "attention" || status === "compacting") return DOT_CLASS.attention;
|
||||
if (status === "offline" || status === "exited" || status === "unpaired") return DOT_CLASS.exited;
|
||||
if (status === "busy" || status === "connecting" || status === "pairing") return DOT_CLASS.busy;
|
||||
return DOT_CLASS.idle;
|
||||
}
|
||||
|
||||
export type SubagentStatus = "active" | "completed" | "failed" | "interrupted" | "dormant";
|
||||
|
||||
export function subagentDotClass(status: SubagentStatus | string): string {
|
||||
switch (status) {
|
||||
case "active":
|
||||
return DOT_CLASS.busy;
|
||||
case "completed":
|
||||
return DOT_CLASS.ok;
|
||||
case "failed":
|
||||
return DOT_CLASS.err;
|
||||
case "interrupted":
|
||||
return DOT_CLASS.attention;
|
||||
case "dormant":
|
||||
return DOT_CLASS.exited;
|
||||
default:
|
||||
return DOT_CLASS.idle;
|
||||
}
|
||||
}
|
||||
|
||||
export type SessionStatus = "starting" | "busy" | "compacting" | "idle" | "exited" | "interrupted" | "attention" | "done" | "error";
|
||||
|
||||
export function sessionDotClass(status: SessionStatus | string): string {
|
||||
switch (status) {
|
||||
case "busy":
|
||||
case "starting":
|
||||
return DOT_CLASS.busy;
|
||||
case "compacting":
|
||||
return DOT_CLASS.compacting;
|
||||
case "interrupted":
|
||||
case "attention":
|
||||
return DOT_CLASS.attention;
|
||||
case "done":
|
||||
return DOT_CLASS.ok;
|
||||
case "error":
|
||||
return DOT_CLASS.err;
|
||||
case "exited":
|
||||
return DOT_CLASS.exited;
|
||||
case "idle":
|
||||
return DOT_CLASS.idle;
|
||||
default:
|
||||
return DOT_CLASS.idle;
|
||||
}
|
||||
}
|
||||
|
||||
export interface StatusDotProps {
|
||||
status: DotStatus;
|
||||
title?: string;
|
||||
className?: string;
|
||||
/** Decorative by default; pass a title to expose the state to assistive tech. */
|
||||
"aria-hidden"?: boolean;
|
||||
}
|
||||
|
||||
export function StatusDot({ status, title, className, ...rest }: StatusDotProps) {
|
||||
return (
|
||||
<span
|
||||
className={cn("dot", DOT_CLASS[status], className)}
|
||||
title={title}
|
||||
aria-label={title}
|
||||
aria-hidden={title ? undefined : true}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const Tabs = TabsPrimitive.Root;
|
||||
|
||||
export const TabsList = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
>(function TabsList({ className, ...props }, ref) {
|
||||
return <TabsPrimitive.List ref={ref} className={cn("tabs", className)} {...props} />;
|
||||
});
|
||||
|
||||
export const TabsTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
>(function TabsTrigger({ className, ...props }, ref) {
|
||||
return <TabsPrimitive.Trigger ref={ref} className={cn("tab", className)} {...props} />;
|
||||
});
|
||||
|
||||
export const TabsContent = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
>(function TabsContent({ className, ...props }, ref) {
|
||||
return <TabsPrimitive.Content ref={ref} className={cn("mt-3 outline-none", className)} {...props} />;
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Toaster as SonnerToaster, toast } from "sonner";
|
||||
|
||||
export { toast };
|
||||
|
||||
/** App-wide toast host (sonner), styled with the design tokens in app.css. */
|
||||
export function Toaster() {
|
||||
return (
|
||||
<SonnerToaster
|
||||
position="bottom-right"
|
||||
theme="system"
|
||||
richColors={false}
|
||||
closeButton={false}
|
||||
duration={2600}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Toolbar({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("toolbar", className)} role="toolbar" {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import type {
|
||||
ContextUsage,
|
||||
Entry,
|
||||
ErrorBody,
|
||||
ModelRef,
|
||||
SessionState,
|
||||
TaskItem,
|
||||
TodoItem,
|
||||
UsageTotals,
|
||||
WorkspaceInfo,
|
||||
} from "./protocol";
|
||||
|
||||
/** Storage key shared with the prototype and the pairing flow. */
|
||||
export const TOKEN_STORAGE_KEY = "pi2-device-token";
|
||||
|
||||
export function getDeviceToken(): string | null {
|
||||
try {
|
||||
return localStorage.getItem(TOKEN_STORAGE_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setDeviceToken(token: string | null): void {
|
||||
try {
|
||||
if (token) localStorage.setItem(TOKEN_STORAGE_KEY, token.toLowerCase().startsWith("bearer ") ? token : `Bearer ${token}`);
|
||||
else localStorage.removeItem(TOKEN_STORAGE_KEY);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
/** Bearer header value; accepts a token with or without the `Bearer ` prefix. */
|
||||
function authHeader(): Record<string, string> {
|
||||
const raw = getDeviceToken()?.replace(/^Bearer\s+/i, "").trim();
|
||||
return raw ? { Authorization: `Bearer ${raw}` } : {};
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly code: string;
|
||||
readonly status: number;
|
||||
readonly retryable: boolean;
|
||||
readonly details?: Record<string, unknown>;
|
||||
|
||||
constructor(input: { code: string; message: string; status: number; retryable?: boolean; details?: Record<string, unknown> }) {
|
||||
super(input.message);
|
||||
this.name = "ApiError";
|
||||
this.code = input.code;
|
||||
this.status = input.status;
|
||||
this.retryable = input.retryable ?? false;
|
||||
this.details = input.details;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable error code → i18n key. The daemon's `message` is English/debug only;
|
||||
* the browser translates the code (docs/protocol.md §3).
|
||||
*/
|
||||
export const ERROR_I18N_KEYS: Record<string, string> = {
|
||||
E_BAD_REQUEST: "errors.badRequest",
|
||||
E_UNAUTHORIZED: "errors.unauthorized",
|
||||
E_FORBIDDEN: "errors.forbidden",
|
||||
E_NOT_FOUND: "errors.notFound",
|
||||
E_METHOD_NOT_ALLOWED: "errors.methodNotAllowed",
|
||||
E_PROTOCOL_VERSION: "errors.protocolVersion",
|
||||
E_PAYLOAD_TOO_LARGE: "errors.payloadTooLarge",
|
||||
E_RATE_LIMITED: "errors.rateLimited",
|
||||
E_INSTANCE_STARTING: "errors.instanceStarting",
|
||||
E_INSTANCE_UNMANAGED: "errors.instanceUnmanaged",
|
||||
E_INSTANCE_UNAVAILABLE: "errors.instanceUnavailable",
|
||||
E_LEASE: "errors.lease",
|
||||
E_EXTERNAL_SESSION: "errors.externalSession",
|
||||
E_SESSION_NOT_FOUND: "errors.sessionNotFound",
|
||||
E_ATTENTION_RESOLVED: "errors.attentionResolved",
|
||||
E_UNSUPPORTED: "errors.unsupported",
|
||||
E_INTERNAL: "errors.internal",
|
||||
E_NETWORK: "errors.network",
|
||||
E_TIMEOUT: "errors.timeout",
|
||||
E_UNKNOWN: "errors.unknown",
|
||||
};
|
||||
|
||||
export function errorI18nKey(code: string | undefined): string {
|
||||
return (code && ERROR_I18N_KEYS[code]) || "errors.unknown";
|
||||
}
|
||||
|
||||
function statusCode(status: number): string {
|
||||
switch (status) {
|
||||
case 400:
|
||||
return "E_BAD_REQUEST";
|
||||
case 401:
|
||||
return "E_UNAUTHORIZED";
|
||||
case 403:
|
||||
return "E_FORBIDDEN";
|
||||
case 404:
|
||||
return "E_NOT_FOUND";
|
||||
case 405:
|
||||
return "E_METHOD_NOT_ALLOWED";
|
||||
case 409:
|
||||
return "E_LEASE";
|
||||
case 413:
|
||||
return "E_PAYLOAD_TOO_LARGE";
|
||||
case 429:
|
||||
return "E_RATE_LIMITED";
|
||||
case 426:
|
||||
return "E_PROTOCOL_VERSION";
|
||||
case 501:
|
||||
return "E_UNSUPPORTED";
|
||||
default:
|
||||
return status >= 500 ? "E_INTERNAL" : "E_UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
headers?: Record<string, string>;
|
||||
/** Absolute URL for pairing (before a device token exists). */
|
||||
baseUrl?: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = "GET", body, signal, headers = {}, baseUrl = "", timeoutMs = 20_000 } = options;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(new DOMException("Request timed out", "TimeoutError")), timeoutMs);
|
||||
const onAbort = () => controller.abort(signal?.reason);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
method,
|
||||
credentials: "same-origin",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||
...authHeader(),
|
||||
...headers,
|
||||
},
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (response.status === 204) return undefined as T;
|
||||
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
const payload: unknown = contentType.includes("application/json") ? await response.json() : await response.text();
|
||||
|
||||
if (!response.ok) {
|
||||
const errorBody = extractErrorBody(payload);
|
||||
throw new ApiError({
|
||||
code: errorBody?.code ?? statusCode(response.status),
|
||||
message: errorBody?.message ?? (response.statusText || `HTTP ${response.status}`),
|
||||
status: response.status,
|
||||
retryable: errorBody?.retryable ?? response.status >= 500,
|
||||
details: errorBody?.details,
|
||||
});
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) throw error;
|
||||
if (error instanceof DOMException && (error.name === "AbortError" || error.name === "TimeoutError")) {
|
||||
throw new ApiError({ code: "E_TIMEOUT", message: "Request aborted", status: 0, retryable: true });
|
||||
}
|
||||
throw new ApiError({
|
||||
code: "E_NETWORK",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
status: 0,
|
||||
retryable: true,
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
function extractErrorBody(payload: unknown): (ErrorBody & { error?: ErrorBody }) | undefined {
|
||||
if (!payload || typeof payload !== "object") return undefined;
|
||||
const record = payload as Record<string, unknown>;
|
||||
const nested = record.error;
|
||||
if (nested && typeof nested === "object") {
|
||||
const err = nested as Record<string, unknown>;
|
||||
return {
|
||||
code: String(err.code ?? "E_UNKNOWN"),
|
||||
message: String(err.message ?? ""),
|
||||
retryable: Boolean(err.retryable),
|
||||
details: err.details as Record<string, unknown> | undefined,
|
||||
};
|
||||
}
|
||||
if (typeof record.code === "string") {
|
||||
return {
|
||||
code: record.code,
|
||||
message: String(record.message ?? ""),
|
||||
retryable: Boolean(record.retryable),
|
||||
details: record.details as Record<string, unknown> | undefined,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Wire responses */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface InfoResponse {
|
||||
v?: number;
|
||||
daemonId?: string;
|
||||
machineId?: string;
|
||||
platform?: string;
|
||||
capabilities?: string[];
|
||||
limits?: Record<string, number>;
|
||||
/** Optional identity fields the status page shows when the daemon provides them. */
|
||||
name?: string;
|
||||
hostname?: string;
|
||||
version?: string;
|
||||
pluginVersion?: string;
|
||||
host?: string;
|
||||
port?: number;
|
||||
status?: "online" | "degraded" | "offline";
|
||||
}
|
||||
|
||||
export interface ServerLike {
|
||||
name: string;
|
||||
hostname: string;
|
||||
host: string;
|
||||
port: number;
|
||||
version: string;
|
||||
pluginVersion: string;
|
||||
status: "online" | "degraded" | "offline";
|
||||
}
|
||||
|
||||
export interface HealthResponse {
|
||||
ok?: boolean;
|
||||
checkedAt?: number;
|
||||
items: { name: string; ok: boolean; detail?: string }[];
|
||||
}
|
||||
|
||||
export interface DeviceInfo {
|
||||
deviceId: string;
|
||||
name: string;
|
||||
kind: "phone" | "laptop" | "tablet";
|
||||
scopes: string[];
|
||||
lastActiveAt: number | null;
|
||||
}
|
||||
|
||||
export interface ModelInfo {
|
||||
provider: string;
|
||||
models: { id: string; contextWindow: number; reasoning: boolean }[];
|
||||
}
|
||||
|
||||
export interface ResourcesResponse {
|
||||
instances: { workspaceId: string; instanceId: string; nvimPid: number | null; rssBytes: number | null; sessions: number; hasUI: boolean }[];
|
||||
totalRssBytes: number;
|
||||
physicalMemoryBytes: number;
|
||||
warn: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface DiagnosticsResponse {
|
||||
connections?: unknown[];
|
||||
instances?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PairRequest {
|
||||
code?: string;
|
||||
token?: string;
|
||||
deviceName?: string;
|
||||
}
|
||||
|
||||
export interface PairResponse {
|
||||
token?: string;
|
||||
deviceId?: string;
|
||||
scopes?: string[];
|
||||
server?: Partial<InfoResponse>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type { ContextUsage, Entry, ModelRef, SessionState, TaskItem, TodoItem, UsageTotals, WorkspaceInfo };
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Endpoints (docs/protocol.md §3.1/§3.2) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export const api = {
|
||||
info: (signal?: AbortSignal) => request<InfoResponse>("/api/v1/info", { signal }),
|
||||
health: (signal?: AbortSignal) => request<HealthResponse>("/api/v1/health", { signal }),
|
||||
workspaces: (signal?: AbortSignal) => request<WorkspaceInfo[]>("/api/v1/workspaces", { signal }),
|
||||
sessions: (workspaceId: string, signal?: AbortSignal) =>
|
||||
request<SessionState[]>(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/sessions`, { signal }),
|
||||
entries: (sessionId: string, options: { before?: number; limit?: number; signal?: AbortSignal } = {}) => {
|
||||
const params = new URLSearchParams();
|
||||
if (options.before !== undefined) params.set("before", String(options.before));
|
||||
if (options.limit !== undefined) params.set("limit", String(options.limit));
|
||||
const query = params.size ? `?${params.toString()}` : "";
|
||||
return request<Entry[]>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries${query}`, { signal: options.signal });
|
||||
},
|
||||
attention: (workspaceId: string, signal?: AbortSignal) =>
|
||||
request<unknown[]>(`/api/v1/attention?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }),
|
||||
devices: (signal?: AbortSignal) => request<DeviceInfo[]>("/api/v1/devices", { signal }),
|
||||
revokeDevice: (deviceId: string, signal?: AbortSignal) =>
|
||||
request<void>(`/api/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE", signal }),
|
||||
models: (workspaceId: string, signal?: AbortSignal) =>
|
||||
request<ModelInfo[]>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }),
|
||||
resources: (signal?: AbortSignal) => request<ResourcesResponse>("/api/v1/resources", { signal }),
|
||||
diagnostics: (signal?: AbortSignal) => request<DiagnosticsResponse>("/api/v1/diagnostics", { signal }),
|
||||
command: (body: { method: string; params?: Record<string, unknown>; sessionId?: string; clientRequestId?: string }, signal?: AbortSignal) =>
|
||||
request<{ accepted: boolean; disposition?: string }>("/api/v1/cmd", { method: "POST", body, signal }),
|
||||
pairCreate: (baseUrl?: string, signal?: AbortSignal) =>
|
||||
request<PairResponse>("/api/v1/pair", { method: "POST", body: {}, baseUrl, signal }),
|
||||
pairRedeem: (body: PairRequest, baseUrl?: string, signal?: AbortSignal) =>
|
||||
request<PairResponse>("/api/v1/pair/redeem", { method: "POST", body, baseUrl, signal }),
|
||||
};
|
||||
|
||||
export { request as apiRequest };
|
||||
@@ -0,0 +1,98 @@
|
||||
import i18n from "i18next";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
|
||||
import en from "@/locales/en.json";
|
||||
import zh from "@/locales/zh.json";
|
||||
|
||||
export const LANGUAGES = ["zh", "en"] as const;
|
||||
export type Language = (typeof LANGUAGES)[number];
|
||||
|
||||
export const LANGUAGE_STORAGE_KEY = "pi2-lang";
|
||||
const SHORT: Record<Language, string> = { zh: "中", en: "EN" };
|
||||
|
||||
export function isLanguage(value: unknown): value is Language {
|
||||
return typeof value === "string" && (LANGUAGES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/** `pi2-lang` wins; otherwise follow the browser (zh* → zh, anything else → en). */
|
||||
export function detectLanguage(): Language {
|
||||
try {
|
||||
const saved = localStorage.getItem(LANGUAGE_STORAGE_KEY);
|
||||
if (isLanguage(saved)) return saved;
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
const nav = String(navigator.language || "zh").toLowerCase();
|
||||
return nav.startsWith("zh") ? "zh" : "en";
|
||||
}
|
||||
|
||||
export function localeFor(language: Language): string {
|
||||
return language === "zh" ? "zh-CN" : "en-US";
|
||||
}
|
||||
|
||||
void i18n.use(initReactI18next).init({
|
||||
resources: {
|
||||
zh: { translation: zh },
|
||||
en: { translation: en },
|
||||
},
|
||||
lng: detectLanguage(),
|
||||
fallbackLng: "zh",
|
||||
supportedLngs: [...LANGUAGES],
|
||||
load: "currentOnly",
|
||||
// The design catalog is flat and uses dotted keys, so disable i18next's separators.
|
||||
keySeparator: false,
|
||||
nsSeparator: false,
|
||||
// The design catalog interpolates with single braces: "{n} minutes ago".
|
||||
interpolation: { prefix: "{", suffix: "}", escapeValue: false },
|
||||
returnNull: false,
|
||||
returnEmptyString: false,
|
||||
});
|
||||
|
||||
if (typeof document !== "undefined") {
|
||||
document.documentElement.lang = localeFor(i18n.language as Language);
|
||||
}
|
||||
|
||||
/** Switch language and persist it to `pi2-lang` (the design's storage key). */
|
||||
export async function setLanguage(language: Language): Promise<void> {
|
||||
if (!isLanguage(language)) return;
|
||||
await i18n.changeLanguage(language);
|
||||
try {
|
||||
localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
if (typeof document !== "undefined") {
|
||||
document.documentElement.lang = localeFor(language);
|
||||
}
|
||||
}
|
||||
|
||||
export function currentLanguage(): Language {
|
||||
return isLanguage(i18n.language) ? i18n.language : "zh";
|
||||
}
|
||||
|
||||
/** Localized language name, e.g. Chinese UI → 中文 / 英文; English UI → Chinese / English. */
|
||||
export function languageLabel(language: Language): string {
|
||||
return i18n.t(`language.${language}`);
|
||||
}
|
||||
|
||||
export function languageShort(language: Language): string {
|
||||
return SHORT[language];
|
||||
}
|
||||
|
||||
/**
|
||||
* Port of the prototype's `I18N.plural`: pick `key.one` / `key.other` through
|
||||
* `Intl.PluralRules`, falling back to the base key when the suffix is absent.
|
||||
*/
|
||||
export function plural(key: string, n: number, params?: Record<string, unknown>): string {
|
||||
let category = n === 1 ? "one" : "other";
|
||||
try {
|
||||
category = new Intl.PluralRules(localeFor(currentLanguage())).select(n);
|
||||
} catch {
|
||||
/* fall back to one/other */
|
||||
}
|
||||
const suffixed = `${key}.${category}`;
|
||||
const values = { ...params, n };
|
||||
return i18n.exists(suffixed) ? i18n.t(suffixed, values) : i18n.t(key, values);
|
||||
}
|
||||
|
||||
export default i18n;
|
||||
@@ -0,0 +1,306 @@
|
||||
// synced from pi2d/src/protocol/types.ts — do not edit by hand; re-copy when the wire types change.
|
||||
/**
|
||||
* pi2 wire protocol — shared types.
|
||||
*
|
||||
* Three surfaces, one vocabulary:
|
||||
* browser <-> daemon (HTTP + WS)
|
||||
* plugin <-> daemon (JSONL over unix socket)
|
||||
* daemon <-> plugin (same JSONL envelope, reversed direction)
|
||||
*
|
||||
* The plugin is the single source of truth for session state; the daemon only
|
||||
* routes, the browser only renders.
|
||||
*/
|
||||
|
||||
export const PROTOCOL_VERSION = 1;
|
||||
|
||||
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
||||
|
||||
export type SessionStatus = "starting" | "busy" | "compacting" | "idle" | "exited" | "interrupted";
|
||||
|
||||
export type ClientKind = "nvim" | "web" | "cli" | "daemon" | "system";
|
||||
|
||||
export interface ClientRef {
|
||||
clientId: string;
|
||||
kind: ClientKind;
|
||||
}
|
||||
|
||||
export interface ModelRef {
|
||||
provider: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface UsageTotals {
|
||||
input: number;
|
||||
output: number;
|
||||
cacheRead: number;
|
||||
cacheWrite: number;
|
||||
cost: number;
|
||||
}
|
||||
|
||||
export interface ContextUsage {
|
||||
tokens: number;
|
||||
window: number;
|
||||
percent: number;
|
||||
}
|
||||
|
||||
export interface ToolOutput {
|
||||
text?: string;
|
||||
details?: unknown;
|
||||
isError?: boolean;
|
||||
}
|
||||
|
||||
export type Block =
|
||||
| { type: "text"; text: string }
|
||||
| { type: "thinking"; text: string; redacted?: boolean }
|
||||
| {
|
||||
type: "tool";
|
||||
toolCallId: string;
|
||||
name: string;
|
||||
args?: unknown;
|
||||
output?: ToolOutput;
|
||||
state: "pending" | "running" | "done" | "error";
|
||||
durationMs?: number;
|
||||
}
|
||||
| { type: "error"; text: string };
|
||||
|
||||
export type EntryRole = "user" | "assistant" | "system" | "notice";
|
||||
|
||||
export interface Entry {
|
||||
id: string;
|
||||
role: EntryRole;
|
||||
ts: number;
|
||||
blocks: Block[];
|
||||
done: boolean;
|
||||
messageId?: string;
|
||||
images?: { mimeType: string; data: string }[];
|
||||
}
|
||||
|
||||
export interface TodoItem {
|
||||
content: string;
|
||||
status: "pending" | "in_progress" | "completed";
|
||||
activeForm?: string;
|
||||
}
|
||||
|
||||
export interface QueueItem {
|
||||
id: string;
|
||||
text: string;
|
||||
steer: boolean;
|
||||
}
|
||||
|
||||
export interface TaskItem {
|
||||
id: string;
|
||||
command: string;
|
||||
status: "running" | "completed" | "failed" | "stopped";
|
||||
startTime: number;
|
||||
durationMs?: number;
|
||||
exitCode?: number | null;
|
||||
outputFile?: string;
|
||||
}
|
||||
|
||||
export type BatchItemStatus = "queued" | "spawning" | "running" | "ok" | "failed" | "cancelled";
|
||||
|
||||
export interface BatchItem {
|
||||
ref: string;
|
||||
name?: string;
|
||||
status: BatchItemStatus;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface BatchItemCounts {
|
||||
total: number;
|
||||
done: number;
|
||||
ok: number;
|
||||
failed: number;
|
||||
cancelled: number;
|
||||
running: number;
|
||||
}
|
||||
|
||||
export interface Batch {
|
||||
batchId: string;
|
||||
status: "running" | "completed" | "partial" | "failed" | "cancelled";
|
||||
items: BatchItem[];
|
||||
summary?: BatchItemCounts;
|
||||
}
|
||||
|
||||
export interface Subagent {
|
||||
id: string;
|
||||
name?: string;
|
||||
status: "active" | "completed" | "failed" | "interrupted" | "dormant";
|
||||
model?: string;
|
||||
thinking?: ThinkingLevel;
|
||||
task?: string;
|
||||
createdAt?: number;
|
||||
lastActiveAt?: number;
|
||||
live?: boolean;
|
||||
children?: Subagent[];
|
||||
}
|
||||
|
||||
export interface AttentionOption {
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface AttentionItem {
|
||||
requestId: string;
|
||||
method: string;
|
||||
title?: string;
|
||||
message?: string;
|
||||
options?: AttentionOption[];
|
||||
/** Free-form payload; `diff` requests carry `{files:[{path,before,after}]}`. */
|
||||
payload?: unknown;
|
||||
timeoutSec?: number;
|
||||
createdAt: number;
|
||||
receivedAt: number;
|
||||
}
|
||||
|
||||
export interface SessionFlags {
|
||||
attention: boolean;
|
||||
done: boolean;
|
||||
error: boolean;
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
sessionId: string;
|
||||
workspaceId: string;
|
||||
cwd: string;
|
||||
name: string | null;
|
||||
status: SessionStatus;
|
||||
flags: SessionFlags;
|
||||
model: ModelRef | null;
|
||||
thinking: ThinkingLevel | null;
|
||||
usage: UsageTotals;
|
||||
contextUsage: ContextUsage | null;
|
||||
queue: QueueItem[];
|
||||
todos: TodoItem[];
|
||||
tasks: TaskItem[];
|
||||
batches: Batch[];
|
||||
subagents: Subagent[];
|
||||
attention: AttentionItem[];
|
||||
entries: Entry[];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Events */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* Pi native events are relayed verbatim (`message_start`, `message_update`,
|
||||
* `tool_execution_*`, `queue_update`, `agent_*`, `turn_*`, `compaction_*`,
|
||||
* `session_info_changed`, `thinking_level_changed`, `entry_appended`).
|
||||
*
|
||||
* Derived events are prefixed `pi2:` and are computed by the plugin only.
|
||||
*/
|
||||
export type SessionEventType =
|
||||
| "agent_start"
|
||||
| "agent_end"
|
||||
| "agent_settled"
|
||||
| "turn_start"
|
||||
| "turn_end"
|
||||
| "message_start"
|
||||
| "message_update"
|
||||
| "message_end"
|
||||
| "tool_execution_start"
|
||||
| "tool_execution_update"
|
||||
| "tool_execution_end"
|
||||
| "queue_update"
|
||||
| "session_info_changed"
|
||||
| "thinking_level_changed"
|
||||
| "entry_appended"
|
||||
| "compaction_start"
|
||||
| "compaction_end"
|
||||
| "pi2:session"
|
||||
| "pi2:todo"
|
||||
| "pi2:batch"
|
||||
| "pi2:task"
|
||||
| "pi2:subagents"
|
||||
| "pi2:attention_request"
|
||||
| "pi2:attention_resolved"
|
||||
| "pi2:process_exit"
|
||||
| "pi2:error";
|
||||
|
||||
export interface SessionEvent {
|
||||
type: SessionEventType | string;
|
||||
ts: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Envelopes */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface InstanceState {
|
||||
workspaceId: string;
|
||||
instanceId: string;
|
||||
status: "starting" | "ready" | "degraded" | "stopping" | "stopped" | "unmanaged";
|
||||
nvimPid: number | null;
|
||||
pluginVersion: string | null;
|
||||
hasUI: boolean;
|
||||
attachedClients: number;
|
||||
listenAddr: string | null;
|
||||
startedAt: number | null;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface WorkspaceInfo {
|
||||
workspaceId: string;
|
||||
cwd: string;
|
||||
name: string;
|
||||
alias?: string | null;
|
||||
pinned?: boolean;
|
||||
hidden?: boolean;
|
||||
trusted: boolean;
|
||||
exists: boolean;
|
||||
/** Number of session files discovered on disk (header scan). */
|
||||
sessionCount: number;
|
||||
/** Number of live sessions reported by the instance, if any. */
|
||||
liveCount: number;
|
||||
lastActiveAt: number | null;
|
||||
instance: InstanceState | null;
|
||||
}
|
||||
|
||||
export type DaemonCommandMethod =
|
||||
| "instance.ensure"
|
||||
| "instance.shutdown"
|
||||
| "workspace.add"
|
||||
| "workspace.update"
|
||||
| "workspace.remove"
|
||||
| "workspace.refresh"
|
||||
| "pair.create"
|
||||
| "pair.redeem"
|
||||
| "device.revoke"
|
||||
| "session.create"
|
||||
| "session.open"
|
||||
| "session.close"
|
||||
| "session.resume"
|
||||
| "session.rename"
|
||||
| "session.fork"
|
||||
| "session.compact"
|
||||
| "session.setModel"
|
||||
| "session.setThinking"
|
||||
| "session.hibernate"
|
||||
| "prompt.send"
|
||||
| "prompt.abort"
|
||||
| "queue.remove"
|
||||
| "queue.setSteer"
|
||||
| "attention.respond"
|
||||
| "subagent.dispatch"
|
||||
| "subagent.stop"
|
||||
| "subagent.steer"
|
||||
| "subagent.read"
|
||||
| "task.stop"
|
||||
| "system.doctor"
|
||||
| "system.shutdown";
|
||||
|
||||
export interface CommandRequest {
|
||||
method: DaemonCommandMethod | string;
|
||||
params?: Record<string, unknown>;
|
||||
sessionId?: string;
|
||||
clientRequestId?: string;
|
||||
}
|
||||
|
||||
export interface ErrorBody {
|
||||
code: string;
|
||||
message: string;
|
||||
retryable: boolean;
|
||||
details?: Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Route guard helpers. `next` is restricted to the three navigation pages
|
||||
* (plus the /workspace and /chat detail routes) — everything else falls back
|
||||
* to /workspaces, matching `App.safeNext` in the prototype.
|
||||
*/
|
||||
|
||||
export const NEXT_FALLBACK = "/workspaces";
|
||||
export const CONNECT_PATH = "/connect";
|
||||
|
||||
const EXACT = new Set(["/workspaces", "/status", "/chat"]);
|
||||
const PREFIXES = ["/chat/", "/workspace/"];
|
||||
|
||||
/** Validate and normalize a post-connect return path. */
|
||||
export function safeNext(path: string | null | undefined, fallback = NEXT_FALLBACK): string {
|
||||
const fb = isAllowed(fallback) ? fallback : NEXT_FALLBACK;
|
||||
if (!path) return fb;
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(String(path), "http://pi2.local");
|
||||
} catch {
|
||||
return fb;
|
||||
}
|
||||
if (!isAllowed(url.pathname)) return fb;
|
||||
return `${url.pathname}${url.search}`;
|
||||
}
|
||||
|
||||
export function isAllowed(pathname: string): boolean {
|
||||
const normalized = pathname.replace(/\/+$/, "") || "/";
|
||||
if (EXACT.has(normalized)) return true;
|
||||
return PREFIXES.some((prefix) => normalized.startsWith(prefix));
|
||||
}
|
||||
|
||||
export function connectHref(next: string): string {
|
||||
return `${CONNECT_PATH}?next=${encodeURIComponent(safeNext(next))}`;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
/** Merge conditional class names, letting later Tailwind utilities win. */
|
||||
export function cn(...inputs: ClassValue[]): string {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
/**
|
||||
* Reconnecting WebSocket client for the pi2 daemon.
|
||||
*
|
||||
* Frame flow (docs/protocol.md §1/§3.3):
|
||||
* connect → socket open → auth frame → hello_ack → open (subscriptions flush)
|
||||
* snapshot replaces the render cache and establishes `seq`
|
||||
* event increments `seq`; reconnect resubscribes with `sinceSeq` for a lossless resume
|
||||
*
|
||||
* The frame envelope is shared with the daemon (`v`, `type`, `id`, `payload`).
|
||||
* The auth frame is the first frame on every socket, before any subscribe.
|
||||
*/
|
||||
|
||||
export type WsConnectionState = "idle" | "connecting" | "authenticating" | "open" | "reconnecting" | "closed";
|
||||
|
||||
export interface WsFrame {
|
||||
v?: number;
|
||||
type: string;
|
||||
id?: string;
|
||||
workspaceId?: string;
|
||||
sessionId?: string;
|
||||
epoch?: string;
|
||||
seq?: number;
|
||||
ts?: number;
|
||||
payload?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface WsSnapshotMessage {
|
||||
sessionId: string;
|
||||
epoch?: string;
|
||||
seq: number;
|
||||
payload: unknown;
|
||||
}
|
||||
|
||||
export interface WsEventMessage {
|
||||
sessionId: string;
|
||||
epoch?: string;
|
||||
seq: number;
|
||||
payload: unknown;
|
||||
ts?: number;
|
||||
}
|
||||
|
||||
export interface WsHandlers {
|
||||
onState?: (state: WsConnectionState) => void;
|
||||
onHelloAck?: () => void;
|
||||
onSnapshot?: (snapshot: WsSnapshotMessage) => void;
|
||||
onEvent?: (event: WsEventMessage) => void;
|
||||
onResyncRequired?: (frame: WsFrame) => void;
|
||||
onError?: (error: Error, frame?: WsFrame) => void;
|
||||
}
|
||||
|
||||
/** Minimal surface the client needs; lets tests inject a fake socket. */
|
||||
export interface WebSocketLike {
|
||||
readyState: number;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
onopen: ((event: unknown) => void) | null;
|
||||
onmessage: ((event: { data: unknown }) => void) | null;
|
||||
onclose: ((event: { code?: number; reason?: string }) => void) | null;
|
||||
onerror: ((event: unknown) => void) | null;
|
||||
}
|
||||
|
||||
export type SocketFactory = (url: string) => WebSocketLike;
|
||||
|
||||
export interface PiWsOptions {
|
||||
url: string;
|
||||
token?: string | null;
|
||||
socketFactory?: SocketFactory;
|
||||
initialBackoffMs?: number;
|
||||
maxBackoffMs?: number;
|
||||
backoffMultiplier?: number;
|
||||
authTimeoutMs?: number;
|
||||
/** 0 disables the keep-alive ping. */
|
||||
heartbeatMs?: number;
|
||||
handlers?: WsHandlers;
|
||||
}
|
||||
|
||||
const AUTH_FRAME_TYPE = "auth";
|
||||
|
||||
function defaultFactory(url: string): WebSocketLike {
|
||||
return new WebSocket(url) as unknown as WebSocketLike;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object";
|
||||
}
|
||||
|
||||
export class PiWsClient {
|
||||
private readonly url: string;
|
||||
private readonly socketFactory: SocketFactory;
|
||||
private readonly initialBackoffMs: number;
|
||||
private readonly maxBackoffMs: number;
|
||||
private readonly backoffMultiplier: number;
|
||||
private readonly authTimeoutMs: number;
|
||||
private readonly heartbeatMs: number;
|
||||
|
||||
private handlers: WsHandlers;
|
||||
private socket: WebSocketLike | null = null;
|
||||
private state: WsConnectionState = "idle";
|
||||
private token: string | null;
|
||||
private attempt = 0;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private authTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private manuallyClosed = false;
|
||||
private readonly subscriptions = new Set<string>();
|
||||
private readonly lastSeq = new Map<string, number>();
|
||||
private readonly epochs = new Map<string, string>();
|
||||
|
||||
constructor(options: PiWsOptions) {
|
||||
this.url = options.url;
|
||||
this.token = options.token ?? null;
|
||||
this.socketFactory = options.socketFactory ?? defaultFactory;
|
||||
this.initialBackoffMs = options.initialBackoffMs ?? 200;
|
||||
this.maxBackoffMs = options.maxBackoffMs ?? 5_000;
|
||||
this.backoffMultiplier = options.backoffMultiplier ?? 2;
|
||||
this.authTimeoutMs = options.authTimeoutMs ?? 8_000;
|
||||
this.heartbeatMs = options.heartbeatMs ?? 25_000;
|
||||
this.handlers = options.handlers ?? {};
|
||||
}
|
||||
|
||||
getState(): WsConnectionState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
getLastSeq(sessionId: string): number | undefined {
|
||||
return this.lastSeq.get(sessionId);
|
||||
}
|
||||
|
||||
getEpoch(sessionId: string): string | undefined {
|
||||
return this.epochs.get(sessionId);
|
||||
}
|
||||
|
||||
setHandlers(handlers: WsHandlers): void {
|
||||
this.handlers = { ...this.handlers, ...handlers };
|
||||
}
|
||||
|
||||
setToken(token: string | null): void {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
if (this.state === "connecting" || this.state === "authenticating" || this.state === "open") return;
|
||||
this.manuallyClosed = false;
|
||||
this.openSocket();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop reconnecting and close the socket. A later `connect()` starts over
|
||||
* (used by the connection store when the user re-pairs).
|
||||
*/
|
||||
close(): void {
|
||||
this.manuallyClosed = true;
|
||||
this.clearReconnectTimer();
|
||||
this.clearAuthTimer();
|
||||
this.stopHeartbeat();
|
||||
const socket = this.socket;
|
||||
this.socket = null;
|
||||
if (socket) {
|
||||
socket.onopen = null;
|
||||
socket.onmessage = null;
|
||||
socket.onclose = null;
|
||||
socket.onerror = null;
|
||||
try {
|
||||
socket.close(1000, "client closed");
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
this.setState("closed");
|
||||
}
|
||||
|
||||
/** Subscribe to one or more sessions; queued until the socket is authenticated. */
|
||||
subscribe(sessionIds: string | string[]): void {
|
||||
const ids = Array.isArray(sessionIds) ? sessionIds : [sessionIds];
|
||||
for (const id of ids) if (id) this.subscriptions.add(id);
|
||||
if (this.state === "open") this.sendSubscribe(ids.filter(Boolean));
|
||||
}
|
||||
|
||||
unsubscribe(sessionIds: string | string[]): void {
|
||||
const ids = Array.isArray(sessionIds) ? sessionIds : [sessionIds];
|
||||
for (const id of ids) {
|
||||
this.subscriptions.delete(id);
|
||||
this.lastSeq.delete(id);
|
||||
this.epochs.delete(id);
|
||||
}
|
||||
if (this.state === "open" && ids.length) {
|
||||
this.send({ v: 1, type: "unsubscribe", payload: { sessionIds: ids } });
|
||||
}
|
||||
}
|
||||
|
||||
getSubscriptions(): string[] {
|
||||
return [...this.subscriptions];
|
||||
}
|
||||
|
||||
private setState(next: WsConnectionState): void {
|
||||
if (this.state === next) return;
|
||||
this.state = next;
|
||||
this.handlers.onState?.(next);
|
||||
}
|
||||
|
||||
private openSocket(): void {
|
||||
this.clearReconnectTimer();
|
||||
this.setState(this.attempt > 0 ? "reconnecting" : "connecting");
|
||||
|
||||
let socket: WebSocketLike;
|
||||
try {
|
||||
socket = this.socketFactory(this.url);
|
||||
} catch (error) {
|
||||
this.handlers.onError?.(error instanceof Error ? error : new Error(String(error)));
|
||||
this.scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
this.socket = socket;
|
||||
|
||||
socket.onopen = () => {
|
||||
if (this.socket !== socket) return;
|
||||
this.setState("authenticating");
|
||||
this.send({ v: 1, type: AUTH_FRAME_TYPE, payload: { token: this.token ?? undefined } });
|
||||
this.authTimer = setTimeout(() => {
|
||||
if (this.state !== "authenticating" || this.socket !== socket) return;
|
||||
this.handlers.onError?.(new Error("WebSocket auth timed out"));
|
||||
this.dropSocket(socket);
|
||||
this.scheduleReconnect();
|
||||
}, this.authTimeoutMs);
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
if (this.socket !== socket) return;
|
||||
this.handleMessage(event.data);
|
||||
};
|
||||
|
||||
socket.onerror = () => {
|
||||
this.handlers.onError?.(new Error("WebSocket transport error"));
|
||||
};
|
||||
|
||||
socket.onclose = (event) => {
|
||||
if (this.socket !== socket) return;
|
||||
this.socket = null;
|
||||
this.clearAuthTimer();
|
||||
this.stopHeartbeat();
|
||||
if (this.manuallyClosed) {
|
||||
this.setState("closed");
|
||||
return;
|
||||
}
|
||||
this.handlers.onError?.(new Error(`WebSocket closed (${event.code ?? 1006})`));
|
||||
this.scheduleReconnect();
|
||||
};
|
||||
}
|
||||
|
||||
private dropSocket(socket: WebSocketLike): void {
|
||||
if (this.socket === socket) this.socket = null;
|
||||
socket.onopen = null;
|
||||
socket.onmessage = null;
|
||||
socket.onclose = null;
|
||||
socket.onerror = null;
|
||||
try {
|
||||
socket.close(4000, "client reset");
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
this.clearReconnectTimer();
|
||||
this.setState("reconnecting");
|
||||
const delay = Math.min(this.initialBackoffMs * this.backoffMultiplier ** this.attempt, this.maxBackoffMs);
|
||||
this.attempt += 1;
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.openSocket();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private clearReconnectTimer(): void {
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private clearAuthTimer(): void {
|
||||
if (this.authTimer) {
|
||||
clearTimeout(this.authTimer);
|
||||
this.authTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private startHeartbeat(): void {
|
||||
this.stopHeartbeat();
|
||||
if (this.heartbeatMs <= 0) return;
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
if (this.state === "open") this.send({ v: 1, type: "ping" });
|
||||
}, this.heartbeatMs);
|
||||
}
|
||||
|
||||
private stopHeartbeat(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private send(frame: WsFrame): boolean {
|
||||
if (!this.socket) return false;
|
||||
try {
|
||||
this.socket.send(JSON.stringify(frame));
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handlers.onError?.(error instanceof Error ? error : new Error(String(error)));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sendSubscribe(sessionIds: string[]): void {
|
||||
if (!sessionIds.length) return;
|
||||
const sinceSeq: Record<string, number> = {};
|
||||
for (const id of sessionIds) {
|
||||
const seq = this.lastSeq.get(id);
|
||||
if (seq !== undefined) sinceSeq[id] = seq;
|
||||
}
|
||||
this.send({
|
||||
v: 1,
|
||||
type: "subscribe",
|
||||
payload: {
|
||||
sessionIds,
|
||||
...(Object.keys(sinceSeq).length ? { sinceSeq } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private flushSubscriptions(): void {
|
||||
if (this.subscriptions.size) this.sendSubscribe([...this.subscriptions]);
|
||||
}
|
||||
|
||||
private handleMessage(raw: unknown): void {
|
||||
let frame: WsFrame;
|
||||
try {
|
||||
const parsed: unknown = typeof raw === "string" ? JSON.parse(raw) : raw;
|
||||
if (!isRecord(parsed) || typeof parsed.type !== "string") return;
|
||||
frame = parsed as WsFrame;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (frame.type) {
|
||||
case "hello_ack": {
|
||||
this.clearAuthTimer();
|
||||
this.attempt = 0;
|
||||
this.setState("open");
|
||||
this.startHeartbeat();
|
||||
this.handlers.onHelloAck?.();
|
||||
this.flushSubscriptions();
|
||||
break;
|
||||
}
|
||||
case "snapshot": {
|
||||
const sessionId = String(frame.sessionId ?? "");
|
||||
if (!sessionId) return;
|
||||
const seq = Number(frame.seq ?? 0);
|
||||
if (frame.epoch) this.epochs.set(sessionId, String(frame.epoch));
|
||||
this.lastSeq.set(sessionId, seq);
|
||||
this.handlers.onSnapshot?.({
|
||||
sessionId,
|
||||
epoch: frame.epoch ? String(frame.epoch) : undefined,
|
||||
seq,
|
||||
payload: frame.payload,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "event": {
|
||||
const sessionId = String(frame.sessionId ?? "");
|
||||
if (!sessionId) return;
|
||||
const seq = Number(frame.seq ?? 0);
|
||||
const previous = this.lastSeq.get(sessionId);
|
||||
if (previous !== undefined && Number.isFinite(seq) && seq <= previous) return;
|
||||
if (Number.isFinite(seq)) this.lastSeq.set(sessionId, seq);
|
||||
if (frame.epoch) this.epochs.set(sessionId, String(frame.epoch));
|
||||
this.handlers.onEvent?.({
|
||||
sessionId,
|
||||
epoch: frame.epoch ? String(frame.epoch) : undefined,
|
||||
seq,
|
||||
payload: frame.payload,
|
||||
ts: typeof frame.ts === "number" ? frame.ts : undefined,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "resync_required": {
|
||||
const sessionId = String(frame.sessionId ?? "");
|
||||
if (sessionId) {
|
||||
this.lastSeq.delete(sessionId);
|
||||
this.epochs.delete(sessionId);
|
||||
}
|
||||
this.handlers.onResyncRequired?.(frame);
|
||||
break;
|
||||
}
|
||||
case "error": {
|
||||
const payload = isRecord(frame.payload) ? frame.payload : {};
|
||||
const code = String(payload.code ?? "E_UNKNOWN");
|
||||
const message = String(payload.message ?? code);
|
||||
this.handlers.onError?.(Object.assign(new Error(message), { code, frame }), frame);
|
||||
if (code === "E_UNAUTHORIZED" || code === "E_PROTOCOL_VERSION") {
|
||||
this.manuallyClosed = true;
|
||||
this.clearReconnectTimer();
|
||||
this.close();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "pong":
|
||||
case "presence":
|
||||
case "dropped":
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Build the default WS URL for the current origin (vite.config proxies /ws to the daemon). */
|
||||
export function defaultWsUrl(path = "/ws"): string {
|
||||
if (typeof window === "undefined") return path;
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${protocol}//${window.location.host}${path}`;
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
{
|
||||
"chat.abort": "Abort",
|
||||
"chat.abortSent": "Abort sent",
|
||||
"chat.abortTitle": "Abort current run",
|
||||
"chat.accept": "Accept",
|
||||
"chat.acceptAll": "Accept all",
|
||||
"chat.accepted": "Accepted changes: {path}",
|
||||
"chat.acceptedAll": "Accepted all {n} files",
|
||||
"chat.addAttachment": "Add attachment",
|
||||
"chat.allowOnce": "Allow once",
|
||||
"chat.allowedOnce": "Allowed once: rm -rf build/",
|
||||
"chat.always": "Always",
|
||||
"chat.alwaysAllowed": "Tool permission remembered",
|
||||
"chat.attachNote": "Attachments are sent with the next message to pi2 (prototype demo only).",
|
||||
"chat.attachTitle": "Add attachment",
|
||||
"chat.attachmentAdded": "Added attachment {name}",
|
||||
"chat.attentionQuestion": "Subagent requests confirmation: allow running ",
|
||||
"chat.attentionTimedOut": "Request timed out and was auto-denied",
|
||||
"chat.attentionTimeout": "Auto-deny on timeout · ",
|
||||
"chat.attentionTitle": "Needs your attention · Extension request",
|
||||
"chat.backToLatest": "Back to latest",
|
||||
"chat.backToParent": "Back to parent",
|
||||
"chat.batchDispatch": "Batch dispatch · {done}/{total}",
|
||||
"chat.batchFailed": "{n} failed",
|
||||
"chat.batchRunning": "{n} running",
|
||||
"chat.cancelSiblingsLabel": "Cancel sibling subagents on failure (cancel_siblings_on_fail)",
|
||||
"chat.closePanel": "Close panel",
|
||||
"chat.closeProcess": "Close process",
|
||||
"chat.closeSessionText": "This ends the pi process for session \"{name}\". History is kept and it can be revived.",
|
||||
"chat.closeTree": "Close session tree",
|
||||
"chat.closedProcess": "Closed process: {name}",
|
||||
"chat.collapse": "Collapse",
|
||||
"chat.collapseTree": "Collapse / expand session tree",
|
||||
"chat.command": "Command",
|
||||
"chat.composerAria": "Message input",
|
||||
"chat.currentSubagents": "Subagents in this session · {n}",
|
||||
"chat.denied": "Request denied",
|
||||
"chat.deny": "Deny",
|
||||
"chat.dispatch": "Dispatch",
|
||||
"chat.dispatchTitle": "Dispatch subagent",
|
||||
"chat.dispatched": "Dispatched subagent {name}",
|
||||
"chat.dropHint": "Drop images / files here, or click to choose",
|
||||
"chat.dropNote": "Demo only: local mock, nothing is uploaded",
|
||||
"chat.duration": "Duration",
|
||||
"chat.emptyText": "Start a conversation below",
|
||||
"chat.emptyTitle": "No messages yet",
|
||||
"chat.error": "Error",
|
||||
"chat.latest": "↓ Latest",
|
||||
"chat.mockReply": "Got it, I'll take care of it.",
|
||||
"chat.model": "Model",
|
||||
"chat.modelLabel": "Model",
|
||||
"chat.modelSwitched": "Switched model: {model}",
|
||||
"chat.moreItems": "+ {n} more",
|
||||
"chat.name": "Name",
|
||||
"chat.nameLabel": "Name",
|
||||
"chat.nameRequired": "Name is required",
|
||||
"chat.newSession": "New session",
|
||||
"chat.newSessionDemo": "New session demo: created session 01a16a2f",
|
||||
"chat.noMatch": "No matching sessions",
|
||||
"chat.noOutput": "(no output)",
|
||||
"chat.noSubagents": "No subagents yet",
|
||||
"chat.noSubagentsText": "Use \"+ Dispatch\" to hand a task to a subagent",
|
||||
"chat.noTasks": "No background tasks",
|
||||
"chat.noTasksText": "Background commands run by the agent appear here",
|
||||
"chat.noTodo": "No todos yet · maintained by the agent",
|
||||
"chat.noTodoText": "The agent will maintain the task breakdown here",
|
||||
"chat.panel": "Panel",
|
||||
"chat.parentSession": "Parent session",
|
||||
"chat.pending": "{n} pending",
|
||||
"chat.preview": "Read-only preview",
|
||||
"chat.previewCompleted": "Done. The result was reported to the parent session; you can continue.",
|
||||
"chat.previewDormant": "Process is dormant; wake it to continue this task.",
|
||||
"chat.previewFailed": "Failed: could not converge on reproduction steps; error details were sent to the parent session.",
|
||||
"chat.previewInterrupted": "Interrupted: received an abort signal from the parent and stopped the current tool call.",
|
||||
"chat.previewNote": "Read-only preview · subagent messages are not written to the parent session",
|
||||
"chat.previewReply": "Got it. I'll run with {model} at thinking={thinking} and report the result back to the parent session.",
|
||||
"chat.previewRunning": "Running…",
|
||||
"chat.previewSubagent": "Preview subagent",
|
||||
"chat.progress": "Progress {done}/{total}",
|
||||
"chat.queueRemoved": "Queued message removed",
|
||||
"chat.reject": "Reject",
|
||||
"chat.rejected": "Rejected changes: {path}",
|
||||
"chat.removeQueued": "Remove queued message",
|
||||
"chat.rename": "Rename",
|
||||
"chat.renameSession": "Rename session",
|
||||
"chat.renameSessionHint": "The name is shown as the session title in the tree and top bar.",
|
||||
"chat.renameSubagentAria": "Rename subagent",
|
||||
"chat.renameSubagentHint": "Local display only; the subagent process is unchanged.",
|
||||
"chat.renamed": "Renamed: {name}",
|
||||
"chat.returnedParent": "Returned to parent session: {name}",
|
||||
"chat.search": "Search sessions…",
|
||||
"chat.searchAria": "Search sessions",
|
||||
"chat.send": "Send",
|
||||
"chat.sendTitle": "Send (Enter)",
|
||||
"chat.sessions": "Sessions",
|
||||
"chat.source": "Source: {name}",
|
||||
"chat.status": "Status",
|
||||
"chat.steer": "Steer",
|
||||
"chat.steerOff": "Steer disabled",
|
||||
"chat.steerOn": "Steer insertion enabled",
|
||||
"chat.steerPlaceholder": "Send a steer instruction to this subagent…",
|
||||
"chat.steerRequired": "Enter a steer instruction",
|
||||
"chat.steerSent": "Steer sent: {text}",
|
||||
"chat.stopTask": "Stop task",
|
||||
"chat.stopTaskText": "Stop background task \"{command}\"?",
|
||||
"chat.streamAria": "Message stream",
|
||||
"chat.subReport": "Subagent report",
|
||||
"chat.subagentCount": "{n} subagents",
|
||||
"chat.subagentName": "Subagent name",
|
||||
"chat.subagentNamePlaceholder": "e.g. ui-research",
|
||||
"chat.subagentTitle": "Subagent · {name}",
|
||||
"chat.tabSubagents": "Subagents",
|
||||
"chat.tabTasks": "Tasks",
|
||||
"chat.tabTodo": "Todo",
|
||||
"chat.task": "Task",
|
||||
"chat.taskLabel": "Task *",
|
||||
"chat.taskOutput": "Task output · {id}",
|
||||
"chat.taskPlaceholder": "Describe the task for the subagent (required)",
|
||||
"chat.taskRequired": "Task description is required",
|
||||
"chat.taskRunning": "Task is still running…",
|
||||
"chat.taskStopped": "Stopped task {id}",
|
||||
"chat.thinking": "Thinking",
|
||||
"chat.thinkingAria": "Thinking level",
|
||||
"chat.thinkingSet": "thinking set to {level}",
|
||||
"chat.toTop": "Back to top",
|
||||
"chat.todoNote": "Todos are maintained by the agent and shown read-only.",
|
||||
"chat.toggleAll": "Collapse / expand all",
|
||||
"chat.toggleAllAria": "Collapse or expand all",
|
||||
"chat.top": "↑ Top",
|
||||
"chat.treeAria": "Session tree",
|
||||
"chat.tryOther": "Try another keyword",
|
||||
"chat.viewSubagent": "View subagent {name}",
|
||||
"chat.waitLabel": "Wait for the subagent to finish (wait)",
|
||||
"chat.workspaceCrumb": "Workspace",
|
||||
"chat.you": "You",
|
||||
"common.add": "Add",
|
||||
"common.cancel": "Cancel",
|
||||
"common.close": "Close",
|
||||
"common.confirm": "Confirm",
|
||||
"common.copied": "{label} copied",
|
||||
"common.copy": "Copy {label}",
|
||||
"common.copyFailed": "Copy failed. Select the text manually.",
|
||||
"common.delete": "Delete",
|
||||
"common.manage": "Manage",
|
||||
"common.open": "Open",
|
||||
"common.optional": "Optional",
|
||||
"common.readonly": "Read-only",
|
||||
"common.required": "{label} is required",
|
||||
"common.retry": "Retry",
|
||||
"common.save": "Save",
|
||||
"common.stop": "Stop",
|
||||
"connect.addTitle": "Connection settings",
|
||||
"connect.address": "Address",
|
||||
"connect.aim": "Point the back camera at the QR code on the pi2 server",
|
||||
"connect.backToWorkspaces": "Back to workspaces",
|
||||
"connect.cameraFailed": "Could not open the camera (no device available). Paste the pairing link instead.",
|
||||
"connect.cameraPreview": "Camera preview",
|
||||
"connect.cameraUnsupported": "This browser does not support camera access. Paste the pairing link below.",
|
||||
"connect.cantScan": "Can't scan? Paste the pairing link",
|
||||
"connect.confirmTitle": "Confirm connection",
|
||||
"connect.connect": "Connect",
|
||||
"connect.connected": "Connected: {name}",
|
||||
"connect.connecting": "Connecting…",
|
||||
"connect.demoScan": "Demo: simulate scan",
|
||||
"connect.device": "Device",
|
||||
"connect.deviceName": "Device name",
|
||||
"connect.deviceNamePlaceholder": "e.g. My browser",
|
||||
"connect.disconnect": "Disconnect",
|
||||
"connect.disconnectText": "This clears the saved connection and token in this browser; you will need to pair again.",
|
||||
"connect.disconnectTitle": "Disconnect",
|
||||
"connect.disconnected": "Disconnected",
|
||||
"connect.emptyText": "Enter the address, or scan a pi2 pairing code to get started.",
|
||||
"connect.emptyTitle": "Connect your pi2 server",
|
||||
"connect.endpoint": "Endpoint",
|
||||
"connect.failed": "Connection failed. Check the address and token.",
|
||||
"connect.host": "Host",
|
||||
"connect.hostPlaceholder": "192.168.2.10 or http://…:4321",
|
||||
"connect.hostRequired": "Enter the server address",
|
||||
"connect.hostname": "Hostname",
|
||||
"connect.identify": "Identify",
|
||||
"connect.invalidLink": "Could not parse it. Paste the full pi2://pair link.",
|
||||
"connect.lastConnected": "Last connected",
|
||||
"connect.manual": "Connect manually",
|
||||
"connect.name": "Name",
|
||||
"connect.noAutoDetect": "Camera is on. This browser cannot decode QR codes automatically; paste the pairing link.",
|
||||
"connect.notPairQr": "Not a pi2 pairing QR code. Try another.",
|
||||
"connect.pairHint": "Scan the pairing QR code shown by the pi2 server; you will confirm before connecting.",
|
||||
"connect.pairingLink": "Pairing link",
|
||||
"connect.pastePlaceholder": "Paste a pi2://pair?… pairing link",
|
||||
"connect.permissionDenied": "Camera permission was denied. Allow access in browser settings and try again.",
|
||||
"connect.piVersion": "pi version",
|
||||
"connect.pluginVersion": "Plugin version",
|
||||
"connect.port": "Port",
|
||||
"connect.portInvalid": "Port must be 1–65535",
|
||||
"connect.recognized": "QR code recognized",
|
||||
"connect.reconnect": "Re-pair",
|
||||
"connect.retryCamera": "Retry camera",
|
||||
"connect.scan": "Scan to pair",
|
||||
"connect.scanHint": "Scan the pairing QR code shown by the pi2 server. You'll confirm before connecting.",
|
||||
"connect.scanLead": "Found a pi2 pairing payload. Make sure the QR code comes from a device you trust.",
|
||||
"connect.scanTitle": "Scan pairing code",
|
||||
"connect.scanWarning": "After connecting, this device can read and write sessions and dispatch subagents.",
|
||||
"connect.scannedNote": "Scanned pairing",
|
||||
"connect.scopes": "Scopes",
|
||||
"connect.secureNote": "Camera access requires HTTPS (or localhost); the token is stored only in this browser.",
|
||||
"connect.secureRequired": "Camera access requires HTTPS (or localhost). Paste the pairing link below instead.",
|
||||
"connect.server": "Server",
|
||||
"connect.startingCamera": "Starting camera…",
|
||||
"connect.statePaired": "Connected",
|
||||
"connect.stateUnpaired": "Not connected",
|
||||
"connect.subtitle": "Connect this browser to your pi2 instance and review pairing details.",
|
||||
"connect.success": "Connected to {name}",
|
||||
"connect.summary": "Current connection",
|
||||
"connect.title": "Connect to pi2",
|
||||
"connect.token": "Token",
|
||||
"connect.tokenHint": "The token is stored only in this browser.",
|
||||
"connect.tokenPlaceholder": "Pairing token (pkt_…)",
|
||||
"connect.tokenRequired": "Enter the pairing token",
|
||||
"connect.version": "Version",
|
||||
"errors.attentionResolved": "This request was already resolved",
|
||||
"errors.badRequest": "Invalid request",
|
||||
"errors.externalSession": "External session",
|
||||
"errors.forbidden": "Forbidden",
|
||||
"errors.instanceStarting": "Instance is starting",
|
||||
"errors.instanceUnavailable": "Instance unavailable",
|
||||
"errors.instanceUnmanaged": "Instance is unmanaged",
|
||||
"errors.internal": "Internal server error",
|
||||
"errors.lease": "Session is owned by another instance",
|
||||
"errors.methodNotAllowed": "Method not allowed",
|
||||
"errors.network": "Cannot reach the server",
|
||||
"errors.notFound": "Not found",
|
||||
"errors.payloadTooLarge": "Payload too large",
|
||||
"errors.protocolVersion": "Incompatible protocol version",
|
||||
"errors.rateLimited": "Too many requests. Try again later.",
|
||||
"errors.sessionNotFound": "Session not found",
|
||||
"errors.timeout": "Request timed out",
|
||||
"errors.unauthorized": "Unauthorized: missing or invalid device token",
|
||||
"errors.unknown": "Unknown error",
|
||||
"errors.unsupported": "Unsupported operation",
|
||||
"language.en": "English",
|
||||
"language.zh": "Chinese",
|
||||
"nav.chat": "Chat",
|
||||
"nav.status": "Status",
|
||||
"nav.workspaces": "Workspaces",
|
||||
"shell.dark": "Dark",
|
||||
"shell.language": "Language",
|
||||
"shell.light": "Light",
|
||||
"shell.navLabel": "Console",
|
||||
"shell.serverChip": "Server: {name}, view status",
|
||||
"shell.switchLanguage": "Switch to {lang}",
|
||||
"shell.system": "Auto",
|
||||
"shell.theme": "Theme",
|
||||
"shell.toChinese": "Switch to Chinese",
|
||||
"shell.toEnglish": "Switch to English",
|
||||
"state.active": "Running",
|
||||
"state.attention": "Needs attention",
|
||||
"state.busy": "Busy",
|
||||
"state.compacting": "Compacting",
|
||||
"state.completed": "Completed",
|
||||
"state.degraded": "Degraded",
|
||||
"state.done": "Done",
|
||||
"state.dormant": "Process closed",
|
||||
"state.error": "Error",
|
||||
"state.exited": "Exited",
|
||||
"state.failed": "Failed",
|
||||
"state.idle": "Idle",
|
||||
"state.interrupted": "Interrupted",
|
||||
"state.offline": "Offline",
|
||||
"state.online": "Online",
|
||||
"state.queued": "Queued",
|
||||
"state.running": "Running",
|
||||
"state.stopped": "Stopped",
|
||||
"state.unknown": "Unknown",
|
||||
"status.batchCount": "Batches",
|
||||
"status.bindAddress": "Bind address",
|
||||
"status.connected": "Connected",
|
||||
"status.connection": "Connection",
|
||||
"status.created": "Created",
|
||||
"status.deviceCount": "{n}",
|
||||
"status.devices": "Paired devices",
|
||||
"status.disconnected": "Disconnected",
|
||||
"status.disk": "Disk",
|
||||
"status.fail": "Fail",
|
||||
"status.health": "Health checks",
|
||||
"status.healthy": "Healthy",
|
||||
"status.lastActive": "Last active",
|
||||
"status.lastConnected": "Last connected",
|
||||
"status.lastHeartbeat": "Last heartbeat",
|
||||
"status.local": "Local",
|
||||
"status.localAddress": "Local address",
|
||||
"status.mdns": "mDNS name",
|
||||
"status.memory": "Memory",
|
||||
"status.modelSearchAria": "Search models or providers",
|
||||
"status.modelSearchPlaceholder": "Search models or providers…",
|
||||
"status.models": "Models & providers",
|
||||
"status.network": "Network",
|
||||
"status.networkAddress": "Network address",
|
||||
"status.noDevicesText": "Devices appear here after pairing from the phone.",
|
||||
"status.noDevicesTitle": "No paired devices",
|
||||
"status.noHealthText": "Waiting for the server to report health checks.",
|
||||
"status.noHealthTitle": "No health data yet",
|
||||
"status.noModelsText": "Try another keyword or clear the search.",
|
||||
"status.noModelsTitle": "No matching models",
|
||||
"status.noTasksText": "Long-running commands from chats appear here.",
|
||||
"status.noTasksTitle": "No background tasks",
|
||||
"status.notConnectedText": "Pair your pi2 server on the connect page first.",
|
||||
"status.notConnectedTitle": "No server connected",
|
||||
"status.os": "OS",
|
||||
"status.pairHint": "Open the pi2 app on your phone and scan to pair",
|
||||
"status.pass": "Pass",
|
||||
"status.piVersion": "PI version",
|
||||
"status.pluginVersion": "Plugin version",
|
||||
"status.qrAria": "Pairing QR code",
|
||||
"status.resources": "Resources",
|
||||
"status.revoke": "Revoke",
|
||||
"status.revokeText": "Revoke access for \"{name}\"? The phone's next request will fail.",
|
||||
"status.revokeTitle": "Revoke device",
|
||||
"status.revoked": "Revoked \"{name}\"",
|
||||
"status.securityExpiry": "Pairing code expires in {n} minutes",
|
||||
"status.securityLocal": "Listens on 127.0.0.1 by default; bind a network address for cross-device access.",
|
||||
"status.securityToken": "Every request requires a token; revoking a device invalidates it immediately.",
|
||||
"status.serverInfo": "Server info",
|
||||
"status.sessions": "Sessions",
|
||||
"status.subagentConcurrency": "Subagent concurrency",
|
||||
"status.taskCount": "{n}",
|
||||
"status.tasks": "Background tasks",
|
||||
"status.title": "Server status",
|
||||
"status.tokenScopes": "Token scopes",
|
||||
"status.uptime": "Uptime",
|
||||
"status.workspaces": "Workspaces",
|
||||
"status.wsStatus": "WS status",
|
||||
"time.daysAgo": "{n}d ago",
|
||||
"time.hoursAgo": "{n}h ago",
|
||||
"time.justNow": "just now",
|
||||
"time.minutesAgo": "{n}m ago",
|
||||
"workspaces.activeRecently": "Active in the last hour",
|
||||
"workspaces.contextAria": "Current server",
|
||||
"workspaces.count": "{n} workspaces",
|
||||
"workspaces.count.one": "{n} workspace",
|
||||
"workspaces.count.other": "{n} workspaces",
|
||||
"workspaces.crumb": "Console",
|
||||
"workspaces.cwdAria": "Working directory path",
|
||||
"workspaces.defaultNamePlaceholder": "Defaults to the last path segment",
|
||||
"workspaces.displayName": "Display name",
|
||||
"workspaces.emptyText": "Open a working directory (cwd) to get started.",
|
||||
"workspaces.emptyTitle": "No workspaces yet",
|
||||
"workspaces.enter": "Enter →",
|
||||
"workspaces.idle": "Idle",
|
||||
"workspaces.nameHint": "Optional; defaults to the last path segment",
|
||||
"workspaces.new": "Open new workspace",
|
||||
"workspaces.newTitle": "Open new workspace",
|
||||
"workspaces.openStatus": "Server status",
|
||||
"workspaces.opened": "Opened workspace {name}",
|
||||
"workspaces.path": "Path",
|
||||
"workspaces.pathHint": "Absolute or ~ path to a Neovim working directory (sessions are isolated by cwd)",
|
||||
"workspaces.pathRequired": "Enter a working directory path",
|
||||
"workspaces.sessionCount": "{n} sessions",
|
||||
"workspaces.sessionCount.one": "{n} session",
|
||||
"workspaces.sessionCount.other": "{n} sessions",
|
||||
"workspaces.subtitle": "A workspace is a Neovim working directory (cwd); sessions are isolated per cwd.",
|
||||
"workspaces.title": "Workspaces",
|
||||
"workspaces.unnamed": "Untitled"
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
{
|
||||
"chat.abort": "中止",
|
||||
"chat.abortSent": "已发送中止",
|
||||
"chat.abortTitle": "中止当前执行",
|
||||
"chat.accept": "接受",
|
||||
"chat.acceptAll": "全部接受",
|
||||
"chat.accepted": "已接受变更:{path}",
|
||||
"chat.acceptedAll": "已接受全部 {n} 个文件",
|
||||
"chat.addAttachment": "添加附件",
|
||||
"chat.allowOnce": "允许一次",
|
||||
"chat.allowedOnce": "已允许一次:rm -rf build/",
|
||||
"chat.always": "始终允许",
|
||||
"chat.alwaysAllowed": "已记住该工具授权",
|
||||
"chat.attachNote": "附件会随下一条消息发送给 pi2(原型仅为交互演示)。",
|
||||
"chat.attachTitle": "添加附件",
|
||||
"chat.attachmentAdded": "已添加附件 {name}",
|
||||
"chat.attentionQuestion": "子代理请求确认:允许执行 ",
|
||||
"chat.attentionTimedOut": "请求超时,已自动拒绝",
|
||||
"chat.attentionTimeout": "超时后自动拒绝 · 剩余 ",
|
||||
"chat.attentionTitle": "需要你的注意 · 扩展请求",
|
||||
"chat.backToLatest": "回到最新",
|
||||
"chat.backToParent": "返回父会话",
|
||||
"chat.batchDispatch": "批量派发 · {done}/{total}",
|
||||
"chat.batchFailed": "{n} 失败",
|
||||
"chat.batchRunning": "{n} 运行中",
|
||||
"chat.cancelSiblingsLabel": "失败时取消同级子代理(cancel_siblings_on_fail)",
|
||||
"chat.closePanel": "关闭面板",
|
||||
"chat.closeProcess": "关闭进程",
|
||||
"chat.closeSessionText": "将结束 session「{name}」的 pi 进程。会话历史仍保留,可重新唤醒。",
|
||||
"chat.closeTree": "关闭 session 树",
|
||||
"chat.closedProcess": "已关闭进程:{name}",
|
||||
"chat.collapse": "收起",
|
||||
"chat.collapseTree": "收起 / 展开 session 树",
|
||||
"chat.command": "命令",
|
||||
"chat.composerAria": "输入消息",
|
||||
"chat.currentSubagents": "当前 session 的子代理 · {n}",
|
||||
"chat.denied": "已拒绝该请求",
|
||||
"chat.deny": "拒绝",
|
||||
"chat.dispatch": "派发",
|
||||
"chat.dispatchTitle": "派发子代理",
|
||||
"chat.dispatched": "已派发子代理 {name}",
|
||||
"chat.dropHint": "拖放图片 / 文件到此处,或点击选择",
|
||||
"chat.dropNote": "演示用:仅本地 mock,不会真正上传",
|
||||
"chat.duration": "耗时",
|
||||
"chat.emptyText": "在输入框里开始对话吧",
|
||||
"chat.emptyTitle": "还没有消息",
|
||||
"chat.error": "错误",
|
||||
"chat.latest": "↓ 回到最新",
|
||||
"chat.mockReply": "收到,我来处理。",
|
||||
"chat.model": "模型",
|
||||
"chat.modelLabel": "模型 model",
|
||||
"chat.modelSwitched": "已切换模型:{model}",
|
||||
"chat.moreItems": "+ {n} 项",
|
||||
"chat.name": "名称",
|
||||
"chat.nameLabel": "名称 name",
|
||||
"chat.nameRequired": "名称不能为空",
|
||||
"chat.newSession": "新 session",
|
||||
"chat.newSessionDemo": "新建 session 演示:已创建 session 01a16a2f",
|
||||
"chat.noMatch": "没有匹配的 session",
|
||||
"chat.noOutput": "(无输出)",
|
||||
"chat.noSubagents": "暂无子代理",
|
||||
"chat.noSubagentsText": "点击「+ 派发」把任务交给子代理",
|
||||
"chat.noTasks": "暂无后台任务",
|
||||
"chat.noTasksText": "agent 执行的后台命令会出现在这里",
|
||||
"chat.noTodo": "暂无 todo · 由 agent 维护",
|
||||
"chat.noTodoText": "agent 会在这里维护当前任务的拆解",
|
||||
"chat.panel": "面板",
|
||||
"chat.parentSession": "父会话",
|
||||
"chat.pending": "{n} 待处理",
|
||||
"chat.preview": "只读预览",
|
||||
"chat.previewCompleted": "完成。结论已通过 report 回传给父会话,可继续下一步。",
|
||||
"chat.previewDormant": "进程已休眠,可重新唤醒继续该任务。",
|
||||
"chat.previewFailed": "执行失败:无法收敛复现步骤,已把错误详情回传给父会话。",
|
||||
"chat.previewInterrupted": "被中断:收到父会话的中止信号,已停止当前工具调用。",
|
||||
"chat.previewNote": "只读预览 · 子代理对话不会写入父会话",
|
||||
"chat.previewReply": "收到。我会在 {model} 上以 thinking={thinking} 执行,并把结论回传给父会话。",
|
||||
"chat.previewRunning": "正在执行…",
|
||||
"chat.previewSubagent": "预览子代理",
|
||||
"chat.progress": "进度 {done}/{total}",
|
||||
"chat.queueRemoved": "已删除排队消息",
|
||||
"chat.reject": "拒绝",
|
||||
"chat.rejected": "已拒绝变更:{path}",
|
||||
"chat.removeQueued": "删除排队消息",
|
||||
"chat.rename": "重命名",
|
||||
"chat.renameSession": "重命名 session",
|
||||
"chat.renameSessionHint": "名称会作为会话标题显示在树与顶栏。",
|
||||
"chat.renameSubagentAria": "重命名子代理",
|
||||
"chat.renameSubagentHint": "仅影响本地显示,不会改变子代理进程。",
|
||||
"chat.renamed": "已重命名:{name}",
|
||||
"chat.returnedParent": "已返回父会话:{name}",
|
||||
"chat.search": "搜索 session…",
|
||||
"chat.searchAria": "搜索 session",
|
||||
"chat.send": "发送",
|
||||
"chat.sendTitle": "发送(Enter)",
|
||||
"chat.sessions": "会话",
|
||||
"chat.source": "来源:{name}",
|
||||
"chat.status": "状态",
|
||||
"chat.steer": "Steer",
|
||||
"chat.steerOff": "已取消 steer",
|
||||
"chat.steerOn": "已设为 steer 插入",
|
||||
"chat.steerPlaceholder": "发送 steer 指令给该子代理…",
|
||||
"chat.steerRequired": "请输入 steer 指令",
|
||||
"chat.steerSent": "已发送 steer 指令:{text}",
|
||||
"chat.stopTask": "停止任务",
|
||||
"chat.stopTaskText": "确认停止后台任务「{command}」?",
|
||||
"chat.streamAria": "消息流",
|
||||
"chat.subReport": "子代理报告",
|
||||
"chat.subagentCount": "{n} 个子代理",
|
||||
"chat.subagentName": "子代理名称",
|
||||
"chat.subagentNamePlaceholder": "例如 ui-research",
|
||||
"chat.subagentTitle": "子代理 · {name}",
|
||||
"chat.tabSubagents": "子代理",
|
||||
"chat.tabTasks": "任务",
|
||||
"chat.tabTodo": "待办",
|
||||
"chat.task": "任务",
|
||||
"chat.taskLabel": "任务 task *",
|
||||
"chat.taskOutput": "任务输出 · {id}",
|
||||
"chat.taskPlaceholder": "描述要交给子代理的任务(必填)",
|
||||
"chat.taskRequired": "任务描述为必填项",
|
||||
"chat.taskRunning": "任务仍在运行…",
|
||||
"chat.taskStopped": "已停止任务 {id}",
|
||||
"chat.thinking": "思考",
|
||||
"chat.thinkingAria": "思考级别",
|
||||
"chat.thinkingSet": "thinking 已设为 {level}",
|
||||
"chat.toTop": "到顶部",
|
||||
"chat.todoNote": "Todo 由 agent 维护,此处仅供查看。",
|
||||
"chat.toggleAll": "折叠 / 展开全部",
|
||||
"chat.toggleAllAria": "折叠或展开全部",
|
||||
"chat.top": "↑ 顶部",
|
||||
"chat.treeAria": "session 树",
|
||||
"chat.tryOther": "试试其他关键字",
|
||||
"chat.viewSubagent": "查看子代理 {name}",
|
||||
"chat.waitLabel": "等待子代理完成(wait)",
|
||||
"chat.workspaceCrumb": "工作空间",
|
||||
"chat.you": "你",
|
||||
"common.add": "添加",
|
||||
"common.cancel": "取消",
|
||||
"common.close": "关闭",
|
||||
"common.confirm": "确认",
|
||||
"common.copied": "{label}已复制",
|
||||
"common.copy": "复制{label}",
|
||||
"common.copyFailed": "复制失败,请手动选择文本",
|
||||
"common.delete": "删除",
|
||||
"common.manage": "管理",
|
||||
"common.open": "打开",
|
||||
"common.optional": "可选",
|
||||
"common.readonly": "只读",
|
||||
"common.required": "{label}不能为空",
|
||||
"common.retry": "重试",
|
||||
"common.save": "保存",
|
||||
"common.stop": "停止",
|
||||
"connect.addTitle": "连接设置",
|
||||
"connect.address": "地址",
|
||||
"connect.aim": "将设备背面对准 pi2 服务器上的二维码",
|
||||
"connect.backToWorkspaces": "返回工作空间",
|
||||
"connect.cameraFailed": "无法打开摄像头(可能没有可用设备)。请改用配对链接。",
|
||||
"connect.cameraPreview": "摄像头预览",
|
||||
"connect.cameraUnsupported": "当前浏览器不支持摄像头,请改用下方配对链接。",
|
||||
"connect.cantScan": "无法扫码?粘贴配对链接",
|
||||
"connect.confirmTitle": "确认连接",
|
||||
"connect.connect": "连接",
|
||||
"connect.connected": "已连接:{name}",
|
||||
"connect.connecting": "正在连接…",
|
||||
"connect.demoScan": "演示:模拟扫码",
|
||||
"connect.device": "设备",
|
||||
"connect.deviceName": "设备名",
|
||||
"connect.deviceNamePlaceholder": "例如 我的浏览器",
|
||||
"connect.disconnect": "断开连接",
|
||||
"connect.disconnectText": "将清除此浏览器保存的连接与 Token,需要重新配对才能继续。",
|
||||
"connect.disconnectTitle": "断开连接",
|
||||
"connect.disconnected": "已断开连接",
|
||||
"connect.emptyText": "填写地址,或扫码配对 pi2 服务器后即可开始。",
|
||||
"connect.emptyTitle": "连接 pi2 服务器",
|
||||
"connect.endpoint": "地址",
|
||||
"connect.failed": "连接失败,请检查地址与 Token",
|
||||
"connect.host": "Host",
|
||||
"connect.hostPlaceholder": "192.168.2.10 或 http://…:4321",
|
||||
"connect.hostRequired": "请输入服务器地址",
|
||||
"connect.hostname": "Hostname",
|
||||
"connect.identify": "识别",
|
||||
"connect.invalidLink": "无法识别,请粘贴完整的 pi2://pair 链接",
|
||||
"connect.lastConnected": "最后连接",
|
||||
"connect.manual": "手动连接",
|
||||
"connect.name": "名称",
|
||||
"connect.noAutoDetect": "摄像头已开启。当前浏览器不支持自动识别,请粘贴配对链接。",
|
||||
"connect.notPairQr": "这不是 pi2 配对二维码,请换一个",
|
||||
"connect.pairHint": "扫描 pi2 服务器显示的配对二维码,识别后需二次确认。",
|
||||
"connect.pairingLink": "配对链接",
|
||||
"connect.pastePlaceholder": "粘贴 pi2://pair?… 配对链接",
|
||||
"connect.permissionDenied": "摄像头权限被拒绝。请在浏览器设置中允许访问后重试。",
|
||||
"connect.piVersion": "pi 版本",
|
||||
"connect.pluginVersion": "插件版本",
|
||||
"connect.port": "端口",
|
||||
"connect.portInvalid": "端口必须是 1–65535",
|
||||
"connect.recognized": "已识别二维码",
|
||||
"connect.reconnect": "重新配对",
|
||||
"connect.retryCamera": "重试摄像头",
|
||||
"connect.scan": "扫码配对",
|
||||
"connect.scanHint": "扫描 pi2 服务器显示的配对二维码,识别后需二次确认。",
|
||||
"connect.scanLead": "已识别到 pi2 配对信息。请确认二维码来自你信任的设备。",
|
||||
"connect.scanTitle": "扫码配对",
|
||||
"connect.scanWarning": "连接后该设备可读写会话并派发子代理。",
|
||||
"connect.scannedNote": "扫码配对",
|
||||
"connect.scopes": "权限",
|
||||
"connect.secureNote": "摄像头需要 HTTPS(或 localhost);Token 仅保存在此浏览器。",
|
||||
"connect.secureRequired": "摄像头需要 HTTPS(或 localhost)安全环境,请改用下方配对链接。",
|
||||
"connect.server": "服务器",
|
||||
"connect.startingCamera": "正在启动摄像头…",
|
||||
"connect.statePaired": "已连接",
|
||||
"connect.stateUnpaired": "未连接",
|
||||
"connect.subtitle": "连接本机 pi2 实例,查看配对与连接信息。",
|
||||
"connect.success": "已连接 {name}",
|
||||
"connect.summary": "当前连接",
|
||||
"connect.title": "连接 pi2 服务器",
|
||||
"connect.token": "Token",
|
||||
"connect.tokenHint": "Token 只保存在此浏览器",
|
||||
"connect.tokenPlaceholder": "配对令牌(pkt_…)",
|
||||
"connect.tokenRequired": "请输入配对 Token",
|
||||
"connect.version": "版本",
|
||||
"errors.attentionResolved": "该请求已被处理",
|
||||
"errors.badRequest": "请求无效",
|
||||
"errors.externalSession": "外部会话",
|
||||
"errors.forbidden": "没有权限",
|
||||
"errors.instanceStarting": "实例正在启动",
|
||||
"errors.instanceUnavailable": "实例不可用",
|
||||
"errors.instanceUnmanaged": "实例未被托管",
|
||||
"errors.internal": "服务器内部错误",
|
||||
"errors.lease": "会话被其他实例占用",
|
||||
"errors.methodNotAllowed": "不支持的方法",
|
||||
"errors.network": "无法连接服务器",
|
||||
"errors.notFound": "未找到",
|
||||
"errors.payloadTooLarge": "请求体过大",
|
||||
"errors.protocolVersion": "协议版本不兼容",
|
||||
"errors.rateLimited": "请求过于频繁,请稍后重试",
|
||||
"errors.sessionNotFound": "会话不存在",
|
||||
"errors.timeout": "请求超时",
|
||||
"errors.unauthorized": "未授权:设备 Token 无效或缺失",
|
||||
"errors.unknown": "未知错误",
|
||||
"errors.unsupported": "不支持的操作",
|
||||
"language.en": "英文",
|
||||
"language.zh": "中文",
|
||||
"nav.chat": "对话",
|
||||
"nav.status": "状态",
|
||||
"nav.workspaces": "工作空间",
|
||||
"shell.dark": "暗",
|
||||
"shell.language": "语言",
|
||||
"shell.light": "亮",
|
||||
"shell.navLabel": "控制台",
|
||||
"shell.serverChip": "服务器:{name},查看状态",
|
||||
"shell.switchLanguage": "切换到{lang}",
|
||||
"shell.system": "自动",
|
||||
"shell.theme": "主题",
|
||||
"shell.toChinese": "切换到中文",
|
||||
"shell.toEnglish": "切换到英文",
|
||||
"state.active": "运行中",
|
||||
"state.attention": "需要关注",
|
||||
"state.busy": "忙碌",
|
||||
"state.compacting": "压缩上下文",
|
||||
"state.completed": "已完成",
|
||||
"state.degraded": "降级",
|
||||
"state.done": "已完成",
|
||||
"state.dormant": "进程已关闭",
|
||||
"state.error": "错误",
|
||||
"state.exited": "已退出",
|
||||
"state.failed": "失败",
|
||||
"state.idle": "空闲",
|
||||
"state.interrupted": "已中断",
|
||||
"state.offline": "离线",
|
||||
"state.online": "在线",
|
||||
"state.queued": "队列中",
|
||||
"state.running": "运行中",
|
||||
"state.stopped": "已停止",
|
||||
"state.unknown": "未知",
|
||||
"status.batchCount": "Batch 批次",
|
||||
"status.bindAddress": "绑定地址",
|
||||
"status.connected": "已连接",
|
||||
"status.connection": "连接信息",
|
||||
"status.created": "创建",
|
||||
"status.deviceCount": "{n} 台",
|
||||
"status.devices": "已配对设备",
|
||||
"status.disconnected": "已断开",
|
||||
"status.disk": "磁盘",
|
||||
"status.fail": "失败",
|
||||
"status.health": "健康检查",
|
||||
"status.healthy": "健康",
|
||||
"status.lastActive": "最后活跃",
|
||||
"status.lastConnected": "最后连接",
|
||||
"status.lastHeartbeat": "最后心跳",
|
||||
"status.local": "Local",
|
||||
"status.localAddress": "Local 地址",
|
||||
"status.mdns": "mDNS 名",
|
||||
"status.memory": "内存",
|
||||
"status.modelSearchAria": "搜索模型或 provider",
|
||||
"status.modelSearchPlaceholder": "搜索模型或 provider…",
|
||||
"status.models": "模型与 Provider",
|
||||
"status.network": "Network",
|
||||
"status.networkAddress": "Network 地址",
|
||||
"status.noDevicesText": "在手机端扫码配对后,设备会显示在这里。",
|
||||
"status.noDevicesTitle": "没有已配对设备",
|
||||
"status.noHealthText": "等待服务器上报健康检查结果。",
|
||||
"status.noHealthTitle": "暂无健康数据",
|
||||
"status.noModelsText": "换一个关键词,或清空搜索。",
|
||||
"status.noModelsTitle": "没有匹配的模型",
|
||||
"status.noTasksText": "在对话中运行的长命令会出现在这里。",
|
||||
"status.noTasksTitle": "没有后台任务",
|
||||
"status.notConnectedText": "请先在连接页配对 pi2 服务器。",
|
||||
"status.notConnectedTitle": "未连接服务器",
|
||||
"status.os": "操作系统",
|
||||
"status.pairHint": "在手机上打开 pi2 App 扫码配对",
|
||||
"status.pass": "通过",
|
||||
"status.piVersion": "PI 版本",
|
||||
"status.pluginVersion": "插件版本",
|
||||
"status.qrAria": "配对二维码",
|
||||
"status.resources": "资源占用",
|
||||
"status.revoke": "撤销",
|
||||
"status.revokeText": "将撤销「{name}」的访问权限,手机端下次请求将失效。",
|
||||
"status.revokeTitle": "撤销设备",
|
||||
"status.revoked": "已撤销「{name}」",
|
||||
"status.securityExpiry": "配对码 {n} 分钟后过期",
|
||||
"status.securityLocal": "默认仅监听 127.0.0.1,跨设备访问需显式绑定网络地址",
|
||||
"status.securityToken": "所有请求均需 Token 鉴权,撤销设备后立即失效",
|
||||
"status.serverInfo": "服务器信息",
|
||||
"status.sessions": "会话数",
|
||||
"status.subagentConcurrency": "子代理并发",
|
||||
"status.taskCount": "{n} 个",
|
||||
"status.tasks": "后台任务",
|
||||
"status.title": "服务器状态",
|
||||
"status.tokenScopes": "Token 权限",
|
||||
"status.uptime": "已运行时长",
|
||||
"status.workspaces": "工作空间数",
|
||||
"status.wsStatus": "WS 状态",
|
||||
"time.daysAgo": "{n} 天前",
|
||||
"time.hoursAgo": "{n} 小时前",
|
||||
"time.justNow": "刚刚",
|
||||
"time.minutesAgo": "{n} 分钟前",
|
||||
"workspaces.activeRecently": "最近 1 小时有活动",
|
||||
"workspaces.contextAria": "当前服务器",
|
||||
"workspaces.count": "{n} 个工作空间",
|
||||
"workspaces.count.one": "{n} 个工作空间",
|
||||
"workspaces.count.other": "{n} 个工作空间",
|
||||
"workspaces.crumb": "控制台",
|
||||
"workspaces.cwdAria": "工作目录路径",
|
||||
"workspaces.defaultNamePlaceholder": "默认取路径末段",
|
||||
"workspaces.displayName": "显示名",
|
||||
"workspaces.emptyText": "打开一个工作目录(cwd)开始。",
|
||||
"workspaces.emptyTitle": "还没有工作空间",
|
||||
"workspaces.enter": "进入 →",
|
||||
"workspaces.idle": "空闲",
|
||||
"workspaces.nameHint": "可选,留空则取路径末段",
|
||||
"workspaces.new": "打开新工作空间",
|
||||
"workspaces.newTitle": "打开新工作空间",
|
||||
"workspaces.openStatus": "服务器状态",
|
||||
"workspaces.opened": "已打开工作空间 {name}",
|
||||
"workspaces.path": "路径",
|
||||
"workspaces.pathHint": "Neovim 工作目录的绝对路径或 ~ 路径(= 该工作空间的会话隔离边界)",
|
||||
"workspaces.pathRequired": "请输入工作目录路径",
|
||||
"workspaces.sessionCount": "{n} 个会话",
|
||||
"workspaces.sessionCount.one": "{n} 个会话",
|
||||
"workspaces.sessionCount.other": "{n} 个会话",
|
||||
"workspaces.subtitle": "工作空间 = Neovim 工作目录(cwd),会话严格按 cwd 隔离。",
|
||||
"workspaces.title": "工作空间",
|
||||
"workspaces.unnamed": "未命名"
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { ThemeProvider } from "next-themes";
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
import "@/styles/app.css";
|
||||
import "@/lib/i18n";
|
||||
|
||||
import { Toaster } from "@/components/ui/toast";
|
||||
import { router } from "@/router";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 10_000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<StrictMode>
|
||||
<ThemeProvider
|
||||
attribute="data-theme"
|
||||
storageKey="pi2-theme"
|
||||
defaultTheme="system"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster />
|
||||
</QueryClientProvider>
|
||||
</ThemeProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
}
|
||||
|
||||
const container = document.getElementById("root");
|
||||
if (!container) throw new Error("Missing #root element");
|
||||
createRoot(container).render(<App />);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
|
||||
/** Placeholder for the chat route; the session tree/message stream land in W7c. */
|
||||
export function ChatPage() {
|
||||
const { t } = useTranslation();
|
||||
const { sessionId } = useParams({ strict: false });
|
||||
const session = useSessionsStore((state) => (sessionId ? state.getSession(sessionId) : undefined));
|
||||
|
||||
return (
|
||||
<PageHeader
|
||||
title={session?.name ?? t("nav.chat")}
|
||||
subtitle={sessionId}
|
||||
docTitle={t("nav.chat")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatIndexPage() {
|
||||
const { t } = useTranslation();
|
||||
return <PageHeader title={t("nav.chat")} subtitle={t("chat.search")} docTitle={t("nav.chat")} />;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
|
||||
/** Placeholder for the pairing entry page; W7b builds the manual/scan flows. */
|
||||
export function ConnectPage() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-[32rem]">
|
||||
<PageHeader
|
||||
title={t("connect.title")}
|
||||
subtitle={t("connect.subtitle")}
|
||||
docTitle={t("connect.title")}
|
||||
>
|
||||
<p className="muted mt-3 flex items-start gap-2 text-[.8125rem]">
|
||||
<Icon name="alert" className="mt-0.5 shrink-0" />
|
||||
<span>{t("connect.secureNote")}</span>
|
||||
</p>
|
||||
</PageHeader>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
/** Placeholder for the single-server status page; W7b fills the cards. */
|
||||
export function StatusPage() {
|
||||
const { t } = useTranslation();
|
||||
const server = useConnectionStore((state) => state.server);
|
||||
const subtitle = server ? `${server.name ?? "pi2.nvim"} · ${server.hostname ?? ""}` : t("status.notConnectedText");
|
||||
|
||||
return <PageHeader title={t("status.title")} subtitle={subtitle} docTitle={t("nav.status")} size="lg" />;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
|
||||
/** Placeholder for the workspace detail route; W7b/W7c fill the content. */
|
||||
export function WorkspacePage() {
|
||||
const { t } = useTranslation();
|
||||
const { workspaceId } = useParams({ strict: false });
|
||||
const workspace = useWorkspacesStore((state) => state.items.find((item) => item.workspaceId === workspaceId));
|
||||
|
||||
return (
|
||||
<PageHeader
|
||||
title={workspace?.name ?? t("workspaces.title")}
|
||||
subtitle={workspace?.cwd ?? workspaceId}
|
||||
docTitle={t("workspaces.title")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
|
||||
export function WorkspacesPage() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<PageHeader
|
||||
title={t("workspaces.title")}
|
||||
subtitle={t("workspaces.subtitle")}
|
||||
docTitle={t("nav.workspaces")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Link, createRootRoute, createRoute, createRouter, redirect } from "@tanstack/react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { AppShell } from "@/components/app-shell";
|
||||
import { CONNECT_PATH, safeNext } from "@/lib/routing";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
import { ChatIndexPage, ChatPage } from "@/pages/chat";
|
||||
import { ConnectPage } from "@/pages/connect";
|
||||
import { StatusPage } from "@/pages/status";
|
||||
import { WorkspacePage } from "@/pages/workspace";
|
||||
import { WorkspacesPage } from "@/pages/workspaces";
|
||||
|
||||
function requirePaired({ location }: { location: { href: string } }): void {
|
||||
if (!useConnectionStore.getState().paired) {
|
||||
const next = safeNext(location.href);
|
||||
throw redirect({ href: `${CONNECT_PATH}?next=${encodeURIComponent(next)}` });
|
||||
}
|
||||
}
|
||||
|
||||
function NotFoundPage() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="empty">
|
||||
<div className="t">{t("errors.notFound")}</div>
|
||||
<Link to="/workspaces" className="btn btn--primary mt-4">
|
||||
{t("connect.backToWorkspaces")}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const rootRoute = createRootRoute({
|
||||
component: AppShell,
|
||||
notFoundComponent: NotFoundPage,
|
||||
});
|
||||
|
||||
const indexRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/",
|
||||
beforeLoad: () => {
|
||||
throw redirect({ href: "/workspaces" });
|
||||
},
|
||||
});
|
||||
|
||||
const workspacesRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/workspaces",
|
||||
beforeLoad: requirePaired,
|
||||
component: WorkspacesPage,
|
||||
});
|
||||
|
||||
const workspaceRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/workspace/$workspaceId",
|
||||
beforeLoad: requirePaired,
|
||||
component: WorkspacePage,
|
||||
});
|
||||
|
||||
const chatIndexRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/chat",
|
||||
beforeLoad: requirePaired,
|
||||
component: ChatIndexPage,
|
||||
});
|
||||
|
||||
const chatRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/chat/$sessionId",
|
||||
beforeLoad: requirePaired,
|
||||
component: ChatPage,
|
||||
});
|
||||
|
||||
const statusRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/status",
|
||||
beforeLoad: requirePaired,
|
||||
component: StatusPage,
|
||||
});
|
||||
|
||||
const connectRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/connect",
|
||||
validateSearch: (search: Record<string, unknown>): { next?: string } => ({
|
||||
next: typeof search.next === "string" ? safeNext(search.next) : undefined,
|
||||
}),
|
||||
component: ConnectPage,
|
||||
});
|
||||
|
||||
const routeTree = rootRoute.addChildren([
|
||||
indexRoute,
|
||||
workspacesRoute,
|
||||
workspaceRoute,
|
||||
chatIndexRoute,
|
||||
chatRoute,
|
||||
statusRoute,
|
||||
connectRoute,
|
||||
]);
|
||||
|
||||
export const router = createRouter({
|
||||
routeTree,
|
||||
defaultPreload: "intent",
|
||||
scrollRestoration: true,
|
||||
});
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: typeof router;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
import type { InfoResponse } from "@/lib/api";
|
||||
import { getDeviceToken, setDeviceToken } from "@/lib/api";
|
||||
import type { WsConnectionState } from "@/lib/ws";
|
||||
|
||||
export const CONNECTION_KEY = "pi2-connection";
|
||||
export const ENDPOINT_KEY = "pi2-endpoint";
|
||||
export const DEVICE_KEY = "pi2-device";
|
||||
export const CONNECTED_AT_KEY = "pi2-connected-at";
|
||||
|
||||
function read(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function write(key: string, value: string): void {
|
||||
try {
|
||||
localStorage.setItem(key, value);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
function drop(key: string): void {
|
||||
try {
|
||||
localStorage.removeItem(key);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
export type PairingState = "paired" | "unpaired";
|
||||
|
||||
export interface ConnectionStore {
|
||||
/** Mirror of the prototype's `pi2-connection` marker. */
|
||||
paired: boolean;
|
||||
endpoint: string;
|
||||
deviceName: string;
|
||||
connectedAt: number;
|
||||
token: string | null;
|
||||
server: InfoResponse | null;
|
||||
wsState: WsConnectionState;
|
||||
|
||||
isPaired: () => boolean;
|
||||
refreshFromStorage: () => void;
|
||||
connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null }) => void;
|
||||
disconnect: () => void;
|
||||
setServer: (server: InfoResponse | null) => void;
|
||||
setWsState: (state: WsConnectionState) => void;
|
||||
setToken: (token: string | null) => void;
|
||||
}
|
||||
|
||||
function initialState() {
|
||||
return {
|
||||
paired: read(CONNECTION_KEY) === "paired",
|
||||
endpoint: read(ENDPOINT_KEY) ?? "",
|
||||
deviceName: read(DEVICE_KEY) ?? "",
|
||||
connectedAt: Number(read(CONNECTED_AT_KEY)) || 0,
|
||||
token: getDeviceToken(),
|
||||
server: null as InfoResponse | null,
|
||||
wsState: "idle" as WsConnectionState,
|
||||
};
|
||||
}
|
||||
|
||||
export const useConnectionStore = create<ConnectionStore>((set, get) => ({
|
||||
...initialState(),
|
||||
|
||||
isPaired: () => get().paired,
|
||||
|
||||
refreshFromStorage: () => set(initialState()),
|
||||
|
||||
connect: ({ endpoint, deviceName, token } = {}) => {
|
||||
const now = Date.now();
|
||||
if (endpoint) write(ENDPOINT_KEY, endpoint);
|
||||
if (deviceName) write(DEVICE_KEY, deviceName);
|
||||
if (token !== undefined) setDeviceToken(token);
|
||||
write(CONNECTED_AT_KEY, String(now));
|
||||
write(CONNECTION_KEY, "paired");
|
||||
set({
|
||||
paired: true,
|
||||
endpoint: endpoint ?? get().endpoint,
|
||||
deviceName: deviceName ?? get().deviceName,
|
||||
connectedAt: now,
|
||||
token: getDeviceToken(),
|
||||
});
|
||||
},
|
||||
|
||||
disconnect: () => {
|
||||
drop(ENDPOINT_KEY);
|
||||
drop(DEVICE_KEY);
|
||||
drop(CONNECTED_AT_KEY);
|
||||
setDeviceToken(null);
|
||||
write(CONNECTION_KEY, "unpaired");
|
||||
set({
|
||||
paired: false,
|
||||
endpoint: "",
|
||||
deviceName: "",
|
||||
connectedAt: 0,
|
||||
token: null,
|
||||
server: null,
|
||||
wsState: "idle",
|
||||
});
|
||||
},
|
||||
|
||||
setServer: (server) => set({ server }),
|
||||
setWsState: (wsState) => set({ wsState }),
|
||||
setToken: (token) => {
|
||||
setDeviceToken(token);
|
||||
set({ token: getDeviceToken() });
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,71 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
import type { SessionState } from "@/lib/protocol";
|
||||
|
||||
export interface SessionsStore {
|
||||
/** Sessions grouped by workspace — the chat tree is per workspace. */
|
||||
byWorkspace: Record<string, SessionState[]>;
|
||||
selectedSessionId: string | null;
|
||||
status: "idle" | "loading" | "error";
|
||||
error: string | null;
|
||||
|
||||
setSessions: (workspaceId: string, sessions: SessionState[]) => void;
|
||||
upsertSession: (session: SessionState) => void;
|
||||
removeSession: (sessionId: string) => void;
|
||||
selectSession: (sessionId: string | null) => void;
|
||||
listFor: (workspaceId: string) => SessionState[];
|
||||
getSession: (sessionId: string) => SessionState | undefined;
|
||||
setStatus: (status: "idle" | "loading" | "error", error?: string | null) => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const initial = {
|
||||
byWorkspace: {} as Record<string, SessionState[]>,
|
||||
selectedSessionId: null as string | null,
|
||||
status: "idle" as const,
|
||||
error: null as string | null,
|
||||
};
|
||||
|
||||
export const useSessionsStore = create<SessionsStore>((set, get) => ({
|
||||
...initial,
|
||||
|
||||
setSessions: (workspaceId, sessions) =>
|
||||
set((state) => ({
|
||||
byWorkspace: { ...state.byWorkspace, [workspaceId]: sessions },
|
||||
status: "idle",
|
||||
error: null,
|
||||
})),
|
||||
|
||||
upsertSession: (session) =>
|
||||
set((state) => {
|
||||
const list = state.byWorkspace[session.workspaceId] ?? [];
|
||||
const index = list.findIndex((s) => s.sessionId === session.sessionId);
|
||||
const next = index === -1 ? [...list, session] : list.map((s, i) => (i === index ? session : s));
|
||||
return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } };
|
||||
}),
|
||||
|
||||
removeSession: (sessionId) =>
|
||||
set((state) => {
|
||||
const byWorkspace: Record<string, SessionState[]> = {};
|
||||
for (const [workspaceId, list] of Object.entries(state.byWorkspace)) {
|
||||
byWorkspace[workspaceId] = list.filter((s) => s.sessionId !== sessionId);
|
||||
}
|
||||
return { byWorkspace, selectedSessionId: state.selectedSessionId === sessionId ? null : state.selectedSessionId };
|
||||
}),
|
||||
|
||||
selectSession: (selectedSessionId) => set({ selectedSessionId }),
|
||||
|
||||
listFor: (workspaceId) => get().byWorkspace[workspaceId] ?? [],
|
||||
|
||||
getSession: (sessionId) => {
|
||||
for (const list of Object.values(get().byWorkspace)) {
|
||||
const found = list.find((s) => s.sessionId === sessionId);
|
||||
if (found) return found;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
|
||||
setStatus: (status, error = null) => set({ status, error }),
|
||||
|
||||
reset: () => set(initial),
|
||||
}));
|
||||
@@ -0,0 +1,53 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
|
||||
export type LoadStatus = "idle" | "loading" | "error" | "ready";
|
||||
|
||||
export interface WorkspacesStore {
|
||||
items: WorkspaceInfo[];
|
||||
status: LoadStatus;
|
||||
error: string | null;
|
||||
selectedId: string | null;
|
||||
|
||||
setWorkspaces: (items: WorkspaceInfo[]) => void;
|
||||
upsert: (item: WorkspaceInfo) => void;
|
||||
remove: (workspaceId: string) => void;
|
||||
select: (workspaceId: string | null) => void;
|
||||
setStatus: (status: LoadStatus, error?: string | null) => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const initial = {
|
||||
items: [] as WorkspaceInfo[],
|
||||
status: "idle" as LoadStatus,
|
||||
error: null as string | null,
|
||||
selectedId: null as string | null,
|
||||
};
|
||||
|
||||
export const useWorkspacesStore = create<WorkspacesStore>((set) => ({
|
||||
...initial,
|
||||
|
||||
setWorkspaces: (items) => set({ items, status: "ready", error: null }),
|
||||
|
||||
upsert: (item) =>
|
||||
set((state) => {
|
||||
const index = state.items.findIndex((w) => w.workspaceId === item.workspaceId);
|
||||
if (index === -1) return { items: [...state.items, item] };
|
||||
const items = state.items.slice();
|
||||
items[index] = item;
|
||||
return { items };
|
||||
}),
|
||||
|
||||
remove: (workspaceId) =>
|
||||
set((state) => ({
|
||||
items: state.items.filter((w) => w.workspaceId !== workspaceId),
|
||||
selectedId: state.selectedId === workspaceId ? null : state.selectedId,
|
||||
})),
|
||||
|
||||
select: (selectedId) => set({ selectedId }),
|
||||
|
||||
setStatus: (status, error = null) => set({ status, error }),
|
||||
|
||||
reset: () => set(initial),
|
||||
}));
|
||||
@@ -0,0 +1,487 @@
|
||||
@import "tailwindcss";
|
||||
@import "./tokens.css";
|
||||
|
||||
/* Tailwind v4 dark variant follows the token switch (next-themes writes data-theme). */
|
||||
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
|
||||
|
||||
/* Semantic token -> Tailwind utility mapping, per the design contract:
|
||||
bg-background, text-muted-foreground, border-border, bg-sidebar, text-role-user, ...
|
||||
`inline` is required because the values are runtime CSS variables (light/dark switch). */
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-role-user: var(--role-user);
|
||||
--color-role-agent: var(--role-agent);
|
||||
--color-role-thinking: var(--role-thinking);
|
||||
--color-role-error: var(--role-error);
|
||||
--color-ok: var(--ok);
|
||||
--color-warn: var(--warn);
|
||||
--color-err: var(--err);
|
||||
--color-info: var(--info);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
pi2 console — base components & app shell (ported from web/styles/base.css)
|
||||
============================================================ */
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
* { margin: 0; }
|
||||
|
||||
html, body, #root { height: 100%; }
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
font-size: .9375rem;
|
||||
line-height: 1.55;
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
a { color: var(--info); text-decoration: none; }
|
||||
button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
|
||||
input, select, textarea { font: inherit; color: inherit; }
|
||||
code, pre, .mono { font-family: var(--font-mono); font-size: .8125em; }
|
||||
|
||||
/* ---------- shell ---------- */
|
||||
.shell { min-height: 100dvh; display: flex; flex-direction: column; }
|
||||
|
||||
.topbar {
|
||||
position: sticky; top: 0; z-index: 40;
|
||||
height: var(--topbar-h);
|
||||
display: flex; align-items: center; gap: var(--space-3);
|
||||
padding: 0 var(--space-4);
|
||||
background: var(--card);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.topbar .brand { display: flex; align-items: center; gap: var(--space-2); font-weight: 700; letter-spacing: -.01em; color: var(--foreground); }
|
||||
.topbar .brand__logo { width: 1.5rem; height: 1.5rem; display: block; flex: none; object-fit: contain; }
|
||||
.topbar .crumbs { display: flex; align-items: center; gap: var(--space-2); color: var(--muted-foreground); font-size: .8125rem; min-width: 0; }
|
||||
.topbar .crumbs .sep { opacity: .5; }
|
||||
.topbar .spacer { flex: 1; }
|
||||
.topbar .actions { display: flex; align-items: center; gap: var(--space-2); }
|
||||
|
||||
.body { flex: 1; display: flex; min-height: 0; }
|
||||
|
||||
/* sidebar >=840 */
|
||||
.sidebar {
|
||||
display: none;
|
||||
width: var(--sidebar-w); flex: none;
|
||||
background: var(--sidebar);
|
||||
border-right: 1px solid var(--border);
|
||||
padding: var(--space-3);
|
||||
position: sticky; top: var(--topbar-h);
|
||||
height: calc(100dvh - var(--topbar-h));
|
||||
overflow-y: auto;
|
||||
}
|
||||
/* rail 600-839 */
|
||||
.rail {
|
||||
display: none;
|
||||
width: var(--rail-w); flex: none;
|
||||
flex-direction: column; align-items: center; gap: var(--space-1);
|
||||
padding: var(--space-3) 0;
|
||||
background: var(--sidebar);
|
||||
border-right: 1px solid var(--border);
|
||||
position: sticky; top: var(--topbar-h);
|
||||
height: calc(100dvh - var(--topbar-h));
|
||||
}
|
||||
/* tabbar <600 */
|
||||
.tabbar {
|
||||
display: none;
|
||||
position: fixed; left: 0; right: 0; bottom: 0; z-index: 40;
|
||||
height: calc(var(--tabbar-h) + env(safe-area-inset-bottom));
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
background: var(--card);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: var(--space-3);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: var(--radius);
|
||||
color: var(--sidebar-foreground);
|
||||
font-size: .875rem; font-weight: 500;
|
||||
}
|
||||
.nav-item:hover { background: var(--sidebar-accent); text-decoration: none; }
|
||||
.nav-item.active { background: var(--sidebar-accent); color: var(--foreground); font-weight: 650; }
|
||||
.nav-item svg { flex: none; }
|
||||
.sidebar .nav-label { font-size: .6875rem; font-weight: 650; text-transform: uppercase; letter-spacing: .07em; color: var(--muted-foreground); padding: var(--space-3) var(--space-3) var(--space-1); }
|
||||
.rail .nav-item { flex-direction: column; gap: 2px; width: 4rem; padding: var(--space-2) 0; font-size: .625rem; border-radius: var(--radius-lg); }
|
||||
.tabbar .nav-item { flex: 1; flex-direction: column; justify-content: center; gap: 2px; border-radius: 0; font-size: .625rem; color: var(--muted-foreground); }
|
||||
.tabbar .nav-item.active { color: var(--primary); background: none; }
|
||||
|
||||
.main { flex: 1; min-width: 0; padding: var(--space-6); padding-bottom: calc(var(--tabbar-h) + var(--space-6)); }
|
||||
@media (min-width: 840px) { .sidebar { display: block; } }
|
||||
@media (min-width: 600px) and (max-width: 839px) { .rail { display: flex; } }
|
||||
@media (min-width: 600px) { .main { padding-bottom: var(--space-6); } }
|
||||
@media (max-width: 599px) { .tabbar { display: flex; } }
|
||||
@media (max-height: 480px) { .rail .nav-item span, .tabbar .nav-item span { display: none; } }
|
||||
@media (max-height: 480px) { .rail .nav-item, .sidebar .nav-item { min-height: 2.5rem; } }
|
||||
|
||||
/* <600 顶栏收敛(品牌文字/面包屑/主题分段不再挤压溢出)。 */
|
||||
@media (max-width: 599px) {
|
||||
.topbar { gap: var(--space-2); padding: 0 var(--space-3); }
|
||||
.topbar .brand { flex: none; white-space: nowrap; }
|
||||
.topbar .brand .brand__text { display: none; }
|
||||
.topbar .crumbs { display: none; }
|
||||
.topbar .actions { flex: none; gap: var(--space-1); }
|
||||
.topbar .actions .badge { white-space: nowrap; }
|
||||
.topbar .seg { flex: none; }
|
||||
.topbar .seg button { white-space: nowrap; padding: 3px var(--space-2); }
|
||||
}
|
||||
|
||||
/* 移动/平板触控目标 ≥40px */
|
||||
@media (max-width: 839px) {
|
||||
.btn--sm, .tab, .topbar .seg button { min-height: 2.5rem; }
|
||||
.btn--icon { min-width: 2.5rem; min-height: 2.5rem; }
|
||||
.topbar .seg button { min-width: 2.5rem; }
|
||||
.topbar .brand { min-width: 2.5rem; min-height: 2.5rem; justify-content: center; }
|
||||
}
|
||||
@media (max-height: 480px) and (min-width: 840px) {
|
||||
.sidebar { width: var(--rail-w); padding: var(--space-3) 0; }
|
||||
.sidebar .nav-label { display: none; }
|
||||
.sidebar .nav-item { flex-direction: column; gap: 2px; width: 4rem; margin: 0 auto; padding: var(--space-2) 0; font-size: .625rem; }
|
||||
.sidebar .nav-item span { display: none; }
|
||||
}
|
||||
.topbar .actions .btn { min-width: 0; }
|
||||
|
||||
/* lang dropdown (topbar) */
|
||||
.lang-menu { position: relative; }
|
||||
.lang-switch { gap: 5px; padding-inline: var(--space-2); }
|
||||
.lang-switch__short { display: none; }
|
||||
.lang-switch__caret { display: inline-flex; color: var(--muted-foreground); transition: transform .18s ease; }
|
||||
.lang-menu.open .lang-switch__caret,
|
||||
.lang-switch[data-state="open"] .lang-switch__caret { transform: rotate(180deg); }
|
||||
.lang-menu__list {
|
||||
position: absolute; top: calc(100% + var(--space-1)); right: 0; z-index: 70;
|
||||
min-width: 9.5rem; padding: var(--space-1);
|
||||
background: var(--popover); color: var(--popover-foreground);
|
||||
border: 1px solid var(--border); border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
@keyframes menu-in { from { opacity: 0; transform: translateY(-4px); } }
|
||||
.lang-menu__list:not([hidden]) { animation: menu-in .16s ease; }
|
||||
.menu__item {
|
||||
display: flex; align-items: center; gap: var(--space-2); width: 100%;
|
||||
padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm);
|
||||
font-size: .875rem; text-align: left;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.menu__item:hover, .menu__item:focus-visible, .menu__item[data-highlighted] { background: var(--accent); outline: none; }
|
||||
.menu__item.is-active { font-weight: 600; }
|
||||
.menu__check { display: inline-flex; color: var(--primary); }
|
||||
@media (max-width: 599px) {
|
||||
.lang-switch__full { display: none; }
|
||||
.lang-switch__short { display: inline; }
|
||||
}
|
||||
|
||||
/* Radix popper surface used by the language menu / select. */
|
||||
.menu-popover {
|
||||
z-index: 70; min-width: 9.5rem; padding: var(--space-1);
|
||||
background: var(--popover); color: var(--popover-foreground);
|
||||
border: 1px solid var(--border); border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-lg);
|
||||
animation: menu-in .16s ease;
|
||||
}
|
||||
.menu-popover:focus { outline: none; }
|
||||
|
||||
/* ---------- buttons ---------- */
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2);
|
||||
padding: var(--space-2) var(--space-4);
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--card);
|
||||
font-size: .875rem; font-weight: 550; white-space: nowrap;
|
||||
transition: background .15s ease, filter .15s ease, transform .1s ease;
|
||||
}
|
||||
.btn:hover { background: var(--accent); }
|
||||
.btn:active { transform: scale(.98); }
|
||||
.btn--primary { background: var(--primary); border-color: var(--primary); color: var(--primary-foreground); }
|
||||
.btn--primary:hover { background: var(--primary); filter: brightness(1.07); }
|
||||
.btn--ghost { border-color: transparent; background: transparent; }
|
||||
.btn--ghost:hover { background: var(--accent); }
|
||||
.btn--danger { color: var(--destructive); }
|
||||
.btn--danger:hover { background: var(--destructive); border-color: var(--destructive); color: var(--destructive-foreground); }
|
||||
.btn--sm { padding: var(--space-1) var(--space-3); font-size: .8125rem; border-radius: var(--radius-sm); }
|
||||
.btn--icon { padding: var(--space-2); }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
|
||||
.icon-btn {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 1.75rem; height: 1.75rem; flex: none;
|
||||
border-radius: var(--radius-sm); color: var(--muted-foreground);
|
||||
transition: background .15s ease, color .15s ease;
|
||||
}
|
||||
.icon-btn:hover { background: var(--accent); color: var(--foreground); }
|
||||
|
||||
/* ---------- badges / dots / chips ---------- */
|
||||
.badge {
|
||||
display: inline-flex; align-items: center; gap: 4px;
|
||||
padding: 1px var(--space-2);
|
||||
border-radius: 999px;
|
||||
font-size: .6875rem; font-weight: 600; letter-spacing: .02em;
|
||||
background: var(--secondary); color: var(--secondary-foreground);
|
||||
}
|
||||
.badge--ok { background: color-mix(in oklch, var(--ok) 15%, transparent); color: color-mix(in oklch, var(--ok) 62%, var(--foreground)); }
|
||||
.badge--warn { background: color-mix(in oklch, var(--warn) 16%, transparent); color: color-mix(in oklch, var(--warn) 55%, var(--foreground)); }
|
||||
.badge--err { background: color-mix(in oklch, var(--err) 13%, transparent); color: var(--err); }
|
||||
.badge--info { background: color-mix(in oklch, var(--info) 12%, transparent); color: var(--info); }
|
||||
|
||||
.dot { width: .5rem; height: .5rem; border-radius: 50%; background: var(--muted-foreground); flex: none; }
|
||||
.dot--busy { background: var(--warn); animation: pulse 1s ease-in-out infinite; }
|
||||
.dot--compacting { background: var(--info); animation: pulse 2s ease-in-out infinite; }
|
||||
.dot--idle { background: var(--muted-foreground); }
|
||||
.dot--ok { background: var(--ok); }
|
||||
.dot--err { background: var(--err); animation: pulse 1s ease-in-out infinite; }
|
||||
.dot--attention { background: var(--warn); }
|
||||
.dot--exited { background: transparent; box-shadow: inset 0 0 0 1.5px var(--muted-foreground); }
|
||||
@keyframes pulse { 50% { opacity: .35; } }
|
||||
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: var(--space-2);
|
||||
padding: var(--space-1) var(--space-3);
|
||||
border-radius: 999px; max-width: 100%;
|
||||
background: var(--secondary); color: var(--secondary-foreground);
|
||||
font-size: .8125rem;
|
||||
}
|
||||
|
||||
/* 顶栏单服务器身份指示(状态点 + 服务器名 + hostname),链接到 /status。 */
|
||||
.server-chip {
|
||||
display: inline-flex; align-items: center; gap: 8px;
|
||||
padding: 4px 10px; border-radius: 999px;
|
||||
background: var(--secondary); color: var(--secondary-foreground);
|
||||
font-size: .8125rem; text-decoration: none;
|
||||
max-width: 100%; min-width: 0;
|
||||
transition: background .18s ease, color .18s ease;
|
||||
}
|
||||
.server-chip:hover { background: var(--accent); color: var(--foreground); text-decoration: none; }
|
||||
.server-chip__name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.server-chip__host { color: var(--muted-foreground); white-space: nowrap; }
|
||||
@media (max-width: 839px) {
|
||||
.server-chip__host { display: none; }
|
||||
}
|
||||
@media (max-width: 599px) {
|
||||
.server-chip { padding: 4px 8px; }
|
||||
.server-chip__name { display: none; }
|
||||
}
|
||||
|
||||
.seg { display: inline-flex; gap: 2px; padding: 2px; background: var(--muted); border-radius: var(--radius); }
|
||||
.seg button { padding: 3px var(--space-3); border-radius: calc(var(--radius) - 2px); font-size: .8125rem; color: var(--muted-foreground); }
|
||||
.seg button.active { background: var(--card); color: var(--foreground); box-shadow: var(--shadow-sm); }
|
||||
.seg button:hover { color: var(--foreground); }
|
||||
.tab:hover { color: var(--foreground); background: var(--accent); }
|
||||
|
||||
/* ---------- cards / panels ---------- */
|
||||
.card {
|
||||
background: var(--card); color: var(--card-foreground);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--space-5);
|
||||
}
|
||||
.card--hover { transition: transform .2s ease, box-shadow .2s ease, border-color .2s ease; }
|
||||
.card--hover:hover { transform: translateY(-2px); box-shadow: var(--shadow); border-color: var(--input); }
|
||||
.card__head { display: flex; align-items: center; gap: var(--space-3); margin-bottom: var(--space-3); }
|
||||
.card__title { font-weight: 640; display: flex; align-items: center; gap: var(--space-2); }
|
||||
.card__sub { color: var(--muted-foreground); font-size: .8125rem; }
|
||||
|
||||
.panel { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden; }
|
||||
.panel__head { display: flex; align-items: center; gap: var(--space-2); padding: var(--space-3) var(--space-4); border-bottom: 1px solid var(--border); font-weight: 600; font-size: .875rem; }
|
||||
.panel__body { padding: var(--space-4); }
|
||||
|
||||
/* ---------- forms ---------- */
|
||||
.input, .select, .textarea {
|
||||
width: 100%; padding: var(--space-2) var(--space-3);
|
||||
border-radius: var(--radius); border: 1px solid var(--input);
|
||||
background: var(--card); outline: none;
|
||||
}
|
||||
.input:focus, .select:focus, .textarea:focus { border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in oklch, var(--ring) 25%, transparent); }
|
||||
.field { margin-bottom: var(--space-4); }
|
||||
.field > label { display: block; font-size: .8125rem; font-weight: 550; margin-bottom: var(--space-1); }
|
||||
.field .hint { font-size: .75rem; color: var(--muted-foreground); margin-top: 4px; }
|
||||
.field .hint.is-err { color: var(--err); }
|
||||
.field--invalid .input, .field--invalid .textarea, .field--invalid .select { border-color: var(--err); }
|
||||
|
||||
/* ---------- tabs / progress / kv / misc ---------- */
|
||||
.tabs { display: flex; gap: var(--space-1); border-bottom: 1px solid var(--border); }
|
||||
.tab { padding: var(--space-2) var(--space-3); font-size: .875rem; font-weight: 550; color: var(--muted-foreground); border-bottom: 2px solid transparent; margin-bottom: -1px; }
|
||||
.tab.active, .tab[data-state="active"] { color: var(--foreground); border-bottom-color: var(--primary); }
|
||||
|
||||
.progress { height: .375rem; border-radius: 999px; background: var(--muted); overflow: hidden; }
|
||||
.progress > i { display: block; height: 100%; border-radius: inherit; background: var(--info); transition: width .3s ease; }
|
||||
.progress--warn > i { background: var(--warn); }
|
||||
.progress--err > i { background: var(--err); }
|
||||
.progress--lg { height: .4375rem; }
|
||||
|
||||
.kv { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-4); padding: var(--space-1) 0; font-size: .875rem; }
|
||||
.kv > k, .kv > .kv-key { color: var(--muted-foreground); flex: none; }
|
||||
.kv > v, .kv > .kv-val { text-align: right; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.kv-list { display: flex; flex-direction: column; }
|
||||
.kv-list .kv { padding: 3px 0; }
|
||||
|
||||
.empty { text-align: center; padding: var(--space-10) var(--space-6); color: var(--muted-foreground); }
|
||||
.empty svg { opacity: .4; margin-bottom: var(--space-3); }
|
||||
.empty .t { font-size: 1rem; font-weight: 600; color: var(--foreground); margin-bottom: var(--space-1); }
|
||||
|
||||
.toolbar { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; margin-bottom: var(--space-4); }
|
||||
|
||||
.spinner { width: 1rem; height: 1rem; border-radius: 50%; border: 2px solid var(--muted); border-top-color: var(--role-agent); animation: spin .7s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.row { display: flex; align-items: center; gap: var(--space-3); }
|
||||
.grow { flex: 1; min-width: 0; }
|
||||
.spacer { flex: 1; }
|
||||
.muted { color: var(--muted-foreground); }
|
||||
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.stack { display: flex; flex-direction: column; }
|
||||
.stack > * + * { margin-top: var(--space-3); }
|
||||
.ico { display: inline-flex; align-items: center; }
|
||||
|
||||
/* ---------- modal & sheet & toast ---------- */
|
||||
.modal-backdrop {
|
||||
position: fixed; inset: 0; z-index: 60;
|
||||
background: oklch(0.1 0.01 60 / 55%);
|
||||
backdrop-filter: blur(2px);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
padding: var(--space-4);
|
||||
opacity: 0; pointer-events: none; transition: opacity .18s ease;
|
||||
}
|
||||
.modal-backdrop.open { opacity: 1; pointer-events: auto; }
|
||||
.modal-backdrop[data-state="open"] { opacity: 1; pointer-events: auto; }
|
||||
.modal {
|
||||
width: min(26rem, 100%); max-height: 88dvh; overflow: auto;
|
||||
background: var(--popover); color: var(--popover-foreground);
|
||||
border-radius: var(--radius-xl); box-shadow: var(--shadow-lg);
|
||||
padding: var(--space-6);
|
||||
transform: translateY(10px); transition: transform .18s ease;
|
||||
}
|
||||
.modal--wide { width: max(60vw, 26rem); max-width: 100%; }
|
||||
.modal-backdrop.open .modal,
|
||||
.modal-backdrop[data-state="open"] .modal,
|
||||
.modal[data-state="open"] { transform: none; }
|
||||
.modal h3 { font-size: 1.0625rem; font-weight: 650; margin-bottom: var(--space-4); display: flex; justify-content: space-between; align-items: center; }
|
||||
.modal .modal-actions { display: flex; justify-content: flex-end; gap: var(--space-2); margin-top: var(--space-5); }
|
||||
.modal:focus { outline: none; }
|
||||
@media (max-width: 599px) {
|
||||
.modal-backdrop { align-items: flex-end; padding: 0; }
|
||||
.modal { width: 100%; border-radius: var(--radius-xl) var(--radius-xl) 0 0; transform: translateY(28px); padding-bottom: calc(var(--space-6) + env(safe-area-inset-bottom)); }
|
||||
.modal--wide { width: 100%; }
|
||||
}
|
||||
|
||||
/* vaul drawer (mobile sheet) */
|
||||
.sheet-overlay { position: fixed; inset: 0; z-index: 60; background: oklch(0.1 0.01 60 / 55%); backdrop-filter: blur(2px); }
|
||||
.sheet-content {
|
||||
position: fixed; left: 0; right: 0; bottom: 0; z-index: 61;
|
||||
display: flex; flex-direction: column;
|
||||
max-height: 88dvh; overflow: auto;
|
||||
background: var(--popover); color: var(--popover-foreground);
|
||||
border-radius: var(--radius-xl) var(--radius-xl) 0 0;
|
||||
box-shadow: var(--shadow-lg);
|
||||
padding: var(--space-6);
|
||||
padding-bottom: calc(var(--space-6) + env(safe-area-inset-bottom));
|
||||
}
|
||||
.sheet-handle { width: 2.5rem; height: .3125rem; border-radius: 999px; background: var(--border); margin: 0 auto var(--space-4); flex: none; }
|
||||
|
||||
.toasts { position: fixed; right: var(--space-4); bottom: calc(var(--space-4) + var(--tabbar-h)); z-index: 80; display: flex; flex-direction: column; gap: var(--space-2); }
|
||||
@media (min-width: 600px) { .toasts { bottom: var(--space-4); } }
|
||||
.toast {
|
||||
display: flex; align-items: center; gap: var(--space-2);
|
||||
background: var(--popover); color: var(--popover-foreground);
|
||||
border: 1px solid var(--border); border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow); padding: var(--space-3) var(--space-4); font-size: .875rem;
|
||||
animation: toast-in .22s ease;
|
||||
}
|
||||
.toast--ok { border-left: 3px solid var(--ok); }
|
||||
.toast--err { border-left: 3px solid var(--err); }
|
||||
@keyframes toast-in { from { opacity: 0; transform: translateY(8px); } }
|
||||
|
||||
/* sonner surfaces follow the design tokens */
|
||||
[data-sonner-toaster] { font-family: var(--font-sans); }
|
||||
[data-sonner-toast] {
|
||||
background: var(--popover) !important;
|
||||
color: var(--popover-foreground) !important;
|
||||
border: 1px solid var(--border) !important;
|
||||
border-radius: var(--radius-lg) !important;
|
||||
box-shadow: var(--shadow) !important;
|
||||
font-size: .875rem !important;
|
||||
}
|
||||
[data-sonner-toast][data-type="success"] { border-left: 3px solid var(--ok) !important; }
|
||||
[data-sonner-toast][data-type="error"] { border-left: 3px solid var(--err) !important; }
|
||||
[data-sonner-toast][data-type="info"] { border-left: 3px solid var(--info) !important; }
|
||||
|
||||
/* ---------- tree ---------- */
|
||||
.tree, .tree ul { list-style: none; padding: 0; margin: 0; }
|
||||
.tree ul { padding-left: var(--space-5); margin-left: .5rem; }
|
||||
.tree-row {
|
||||
display: flex; align-items: center; gap: var(--space-2);
|
||||
padding: var(--space-2); border-radius: var(--radius); cursor: pointer; min-width: 0;
|
||||
}
|
||||
.tree-row:hover { background: var(--accent); }
|
||||
.tree-row.selected { background: var(--sidebar-accent); }
|
||||
.tree-row .t-name { flex: 1; min-width: 0; font-size: .875rem; font-weight: 500; }
|
||||
.tree-row .t-sub { font-size: .75rem; color: var(--muted-foreground); font-weight: 400; margin-left: var(--space-2); }
|
||||
.tree-row .t-meta { font-size: .75rem; color: var(--muted-foreground); flex: none; }
|
||||
.tree-toggle { width: 1.1rem; flex: none; color: var(--muted-foreground); display: inline-flex; justify-content: center; transition: transform .15s ease; }
|
||||
.tree-toggle.open { transform: rotate(90deg); }
|
||||
.tree-toggle.leaf { visibility: hidden; }
|
||||
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
|
||||
|
||||
/* ---------- page header (shared by all pages) ---------- */
|
||||
.page-head {
|
||||
display: flex; align-items: flex-start; flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
.page-head__text { flex: 1 1 14rem; min-width: 0; }
|
||||
.page-head__title { font-size: 1.25rem; font-weight: 650; letter-spacing: -.01em; }
|
||||
.page-head__sub { font-size: .875rem; margin-top: var(--space-1); color: var(--muted-foreground); }
|
||||
.page-head__actions { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; flex: none; margin-left: auto; }
|
||||
.page-head--lg { align-items: flex-end; margin-bottom: var(--space-5); }
|
||||
.page-head--lg .page-head__title { font-size: 1.375rem; font-weight: 680; }
|
||||
.page-head--lg .page-head__sub { margin-top: 2px; }
|
||||
@media (max-width: 599px) {
|
||||
.page-head { align-items: center; }
|
||||
.page-head__actions { margin-left: 0; }
|
||||
}
|
||||
|
||||
/* ---------- Radix select ---------- */
|
||||
.select-trigger {
|
||||
display: inline-flex; align-items: center; justify-content: space-between;
|
||||
gap: var(--space-2); text-align: left; cursor: pointer;
|
||||
}
|
||||
.select-content {
|
||||
z-index: 70; min-width: var(--radix-select-trigger-width);
|
||||
max-height: var(--radix-select-content-available-height);
|
||||
overflow: hidden;
|
||||
background: var(--popover); color: var(--popover-foreground);
|
||||
border: 1px solid var(--border); border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
.select-viewport { padding: var(--space-1); }
|
||||
.select-item {
|
||||
display: flex; align-items: center; gap: var(--space-2);
|
||||
padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm);
|
||||
font-size: .875rem; cursor: pointer; outline: none;
|
||||
}
|
||||
.select-item[data-highlighted] { background: var(--accent); }
|
||||
.select-item[data-state="checked"] { font-weight: 600; }
|
||||
.select-item__indicator { display: inline-flex; color: var(--primary); }
|
||||
@@ -0,0 +1,155 @@
|
||||
/* ============================================================
|
||||
pi2 console — design tokens (light default, dark override)
|
||||
默认跟随系统;html[data-theme="light|dark"] 手动覆盖。
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* surfaces */
|
||||
--background: oklch(0.985 0.004 90);
|
||||
--foreground: oklch(0.21 0.02 60);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.21 0.02 60);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.21 0.02 60);
|
||||
--muted: oklch(0.955 0.006 90);
|
||||
--muted-foreground: oklch(0.50 0.015 60);
|
||||
--accent: oklch(0.94 0.012 85);
|
||||
--accent-foreground: oklch(0.25 0.02 60);
|
||||
--secondary: oklch(0.945 0.01 90);
|
||||
--secondary-foreground: oklch(0.38 0.02 60);
|
||||
--sidebar: oklch(0.972 0.005 90);
|
||||
--sidebar-foreground: oklch(0.32 0.02 60);
|
||||
--sidebar-accent: oklch(0.93 0.01 85);
|
||||
--destructive: oklch(0.55 0.20 27);
|
||||
--destructive-foreground: oklch(0.985 0.005 27);
|
||||
|
||||
/* borders & focus */
|
||||
--border: oklch(0.21 0.02 60 / 13%);
|
||||
--input: oklch(0.21 0.02 60 / 18%);
|
||||
--ring: oklch(0.55 0.14 255 / 50%);
|
||||
|
||||
/* primary / selection */
|
||||
--primary: oklch(0.50 0.15 258);
|
||||
--primary-foreground: oklch(0.985 0.005 258);
|
||||
|
||||
/* role hues — pi2.nvim DESIGN.md 六角色 */
|
||||
--role-user: oklch(0.50 0.16 262); /* indigo */
|
||||
--role-agent: oklch(0.55 0.13 165); /* emerald */
|
||||
--role-thinking: oklch(0.54 0.17 295); /* violet */
|
||||
--role-error: var(--destructive);
|
||||
|
||||
/* semantic status */
|
||||
--ok: oklch(0.60 0.15 155);
|
||||
--warn: oklch(0.72 0.15 85);
|
||||
--err: var(--destructive);
|
||||
--info: var(--primary);
|
||||
|
||||
/* radius & space */
|
||||
--radius-sm: 0.375rem;
|
||||
--radius: 0.625rem;
|
||||
--radius-lg: 0.875rem;
|
||||
--radius-xl: 1.25rem;
|
||||
--space-1: 0.25rem; --space-2: 0.5rem; --space-3: 0.75rem;
|
||||
--space-4: 1rem; --space-5: 1.25rem; --space-6: 1.5rem;
|
||||
--space-8: 2rem; --space-10: 2.5rem;
|
||||
|
||||
/* type */
|
||||
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
|
||||
"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
||||
--font-mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
|
||||
|
||||
/* elevation */
|
||||
--shadow-sm: 0 1px 2px oklch(0.21 0.02 60 / 7%);
|
||||
--shadow: 0 4px 14px oklch(0.21 0.02 60 / 9%), 0 1px 3px oklch(0.21 0.02 60 / 7%);
|
||||
--shadow-lg: 0 14px 44px oklch(0.21 0.02 60 / 17%), 0 3px 9px oklch(0.21 0.02 60 / 9%);
|
||||
|
||||
/* layout */
|
||||
--topbar-h: 3.5rem;
|
||||
--sidebar-w: 17.5rem;
|
||||
--rail-w: 4.5rem;
|
||||
--tabbar-h: 3.75rem;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] {
|
||||
--background: oklch(0.145 0.008 60);
|
||||
--foreground: oklch(0.925 0.008 80);
|
||||
--card: oklch(0.205 0.010 60);
|
||||
--card-foreground: oklch(0.925 0.008 80);
|
||||
--popover: oklch(0.235 0.012 60);
|
||||
--popover-foreground: oklch(0.925 0.008 80);
|
||||
--muted: oklch(0.265 0.010 60);
|
||||
--muted-foreground: oklch(0.66 0.012 70);
|
||||
--accent: oklch(0.28 0.013 70);
|
||||
--accent-foreground: oklch(0.925 0.008 80);
|
||||
--secondary: oklch(0.26 0.011 60);
|
||||
--secondary-foreground: oklch(0.78 0.012 70);
|
||||
--sidebar: oklch(0.178 0.008 60);
|
||||
--sidebar-foreground: oklch(0.76 0.012 70);
|
||||
--sidebar-accent: oklch(0.25 0.012 70);
|
||||
--destructive: oklch(0.63 0.20 27);
|
||||
--destructive-foreground: oklch(0.985 0.005 27);
|
||||
|
||||
--border: oklch(1 0 0 / 10%); /* 半透明白 */
|
||||
--input: oklch(1 0 0 / 16%);
|
||||
--ring: oklch(0.62 0.14 260 / 55%);
|
||||
|
||||
--primary: oklch(0.68 0.14 260);
|
||||
--primary-foreground: oklch(0.16 0.02 260);
|
||||
|
||||
--role-user: oklch(0.72 0.14 264);
|
||||
--role-agent: oklch(0.78 0.13 165);
|
||||
--role-thinking: oklch(0.74 0.15 295);
|
||||
|
||||
--ok: oklch(0.76 0.14 160);
|
||||
--warn: oklch(0.82 0.14 90);
|
||||
--err: var(--destructive);
|
||||
--info: var(--primary);
|
||||
|
||||
--shadow-sm: 0 1px 2px oklch(0 0 0 / 40%);
|
||||
--shadow: 0 4px 14px oklch(0 0 0 / 45%), 0 1px 3px oklch(0 0 0 / 40%);
|
||||
--shadow-lg: 0 14px 44px oklch(0 0 0 / 55%), 0 3px 9px oklch(0 0 0 / 45%);
|
||||
}
|
||||
|
||||
/* verify-fix: C1 — JS 未执行时(无 data-theme)由系统 prefers-color-scheme 回退到暗色。
|
||||
与上方 html[data-theme="dark"] 的 token 值保持一致;手动选择 light/dark 时优先级更高。 */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html:not([data-theme]) {
|
||||
--background: oklch(0.145 0.008 60);
|
||||
--foreground: oklch(0.925 0.008 80);
|
||||
--card: oklch(0.205 0.010 60);
|
||||
--card-foreground: oklch(0.925 0.008 80);
|
||||
--popover: oklch(0.235 0.012 60);
|
||||
--popover-foreground: oklch(0.925 0.008 80);
|
||||
--muted: oklch(0.265 0.010 60);
|
||||
--muted-foreground: oklch(0.66 0.012 70);
|
||||
--accent: oklch(0.28 0.013 70);
|
||||
--accent-foreground: oklch(0.925 0.008 80);
|
||||
--secondary: oklch(0.26 0.011 60);
|
||||
--secondary-foreground: oklch(0.78 0.012 70);
|
||||
--sidebar: oklch(0.178 0.008 60);
|
||||
--sidebar-foreground: oklch(0.76 0.012 70);
|
||||
--sidebar-accent: oklch(0.25 0.012 70);
|
||||
--destructive: oklch(0.63 0.20 27);
|
||||
--destructive-foreground: oklch(0.985 0.005 27);
|
||||
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 16%);
|
||||
--ring: oklch(0.62 0.14 260 / 55%);
|
||||
|
||||
--primary: oklch(0.68 0.14 260);
|
||||
--primary-foreground: oklch(0.16 0.02 260);
|
||||
|
||||
--role-user: oklch(0.72 0.14 264);
|
||||
--role-agent: oklch(0.78 0.13 165);
|
||||
--role-thinking: oklch(0.74 0.15 295);
|
||||
|
||||
--ok: oklch(0.76 0.14 160);
|
||||
--warn: oklch(0.82 0.14 90);
|
||||
--err: var(--destructive);
|
||||
--info: var(--primary);
|
||||
|
||||
--shadow-sm: 0 1px 2px oklch(0 0 0 / 40%);
|
||||
--shadow: 0 4px 14px oklch(0 0 0 / 45%), 0 1px 3px oklch(0 0 0 / 40%);
|
||||
--shadow-lg: 0 14px 44px oklch(0 0 0 / 55%), 0 3px 9px oklch(0 0 0 / 45%);
|
||||
}
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,76 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardSub, CardTitle } from "@/components/ui/card";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
|
||||
describe("Button", () => {
|
||||
it("renders the base class and default variant", () => {
|
||||
render(<Button>Open</Button>);
|
||||
const button = screen.getByRole("button", { name: "Open" });
|
||||
expect(button).toHaveClass("btn");
|
||||
expect(button).toHaveAttribute("type", "button");
|
||||
});
|
||||
|
||||
it("applies variant and size classes", () => {
|
||||
render(
|
||||
<Button variant="primary" size="sm">
|
||||
Save
|
||||
</Button>,
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Save" })).toHaveClass("btn", "btn--primary", "btn--sm");
|
||||
});
|
||||
|
||||
it("supports disabled state", () => {
|
||||
render(<Button disabled>Stop</Button>);
|
||||
expect(screen.getByRole("button", { name: "Stop" })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Card", () => {
|
||||
it("renders the card surface with title/sub", () => {
|
||||
render(
|
||||
<Card>
|
||||
<CardTitle>Server info</CardTitle>
|
||||
<CardSub>hostname</CardSub>
|
||||
</Card>,
|
||||
);
|
||||
expect(screen.getByText("Server info").closest(".card")).toBeInTheDocument();
|
||||
expect(screen.getByText("Server info")).toHaveClass("card__title");
|
||||
expect(screen.getByText("hostname")).toHaveClass("card__sub");
|
||||
});
|
||||
|
||||
it("renders the hover variant", () => {
|
||||
const { container } = render(<Card hover>hover</Card>);
|
||||
expect(container.firstElementChild).toHaveClass("card", "card--hover");
|
||||
});
|
||||
});
|
||||
|
||||
describe("StatusDot", () => {
|
||||
it.each([
|
||||
["busy", "dot--busy"],
|
||||
["compacting", "dot--compacting"],
|
||||
["idle", "dot--idle"],
|
||||
["ok", "dot--ok"],
|
||||
["err", "dot--err"],
|
||||
["attention", "dot--attention"],
|
||||
["exited", "dot--exited"],
|
||||
] as const)("maps %s to %s", (status, expected) => {
|
||||
const { container } = render(<StatusDot status={status} />);
|
||||
expect(container.firstElementChild).toHaveClass("dot", expected);
|
||||
});
|
||||
|
||||
it("exposes the state label when a title is provided", () => {
|
||||
render(<StatusDot status="ok" title="Online" />);
|
||||
expect(screen.getByLabelText("Online")).toHaveAttribute("title", "Online");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Badge", () => {
|
||||
it("maps semantic tones", () => {
|
||||
const { container } = render(<Badge tone="warn">degraded</Badge>);
|
||||
expect(container.firstElementChild).toHaveClass("badge", "badge--warn");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import en from "@/locales/en.json";
|
||||
import zh from "@/locales/zh.json";
|
||||
|
||||
type Catalog = Record<string, string>;
|
||||
|
||||
function flatten(value: unknown, prefix = ""): Record<string, string> {
|
||||
if (!value || typeof value !== "object") return {};
|
||||
const out: Record<string, string> = {};
|
||||
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
||||
const path = prefix ? `${prefix}.${key}` : key;
|
||||
if (typeof child === "string") out[path] = child;
|
||||
else if (child && typeof child === "object") Object.assign(out, flatten(child, path));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const zhFlat = flatten(zh as Catalog);
|
||||
const enFlat = flatten(en as Catalog);
|
||||
|
||||
describe("i18n catalogs", () => {
|
||||
it("have identical key sets", () => {
|
||||
const zhKeys = new Set(Object.keys(zhFlat));
|
||||
const enKeys = new Set(Object.keys(enFlat));
|
||||
expect([...zhKeys].filter((key) => !enKeys.has(key))).toEqual([]);
|
||||
expect([...enKeys].filter((key) => !zhKeys.has(key))).toEqual([]);
|
||||
expect(zhKeys.size).toBeGreaterThan(300);
|
||||
console.log(`i18n key parity: ${zhKeys.size} zh / ${enKeys.size} en`);
|
||||
});
|
||||
|
||||
it("have a non-empty string for every key", () => {
|
||||
for (const [key, value] of Object.entries(zhFlat)) {
|
||||
expect(typeof value, key).toBe("string");
|
||||
expect(value.length, key).toBeGreaterThan(0);
|
||||
}
|
||||
for (const [key, value] of Object.entries(enFlat)) {
|
||||
expect(typeof value, key).toBe("string");
|
||||
expect(value.length, key).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("covers every prototype namespace", () => {
|
||||
for (const prefix of [
|
||||
"common.",
|
||||
"shell.",
|
||||
"language.",
|
||||
"nav.",
|
||||
"time.",
|
||||
"state.",
|
||||
"connect.",
|
||||
"workspaces.",
|
||||
"status.",
|
||||
"chat.",
|
||||
]) {
|
||||
expect(Object.keys(zhFlat).some((key) => key.startsWith(prefix)), prefix).toBe(true);
|
||||
expect(Object.keys(enFlat).some((key) => key.startsWith(prefix)), prefix).toBe(true);
|
||||
}
|
||||
// The prototype's English plural variants are mirrored in zh for parity.
|
||||
for (const key of [
|
||||
"workspaces.count.one",
|
||||
"workspaces.count.other",
|
||||
"workspaces.sessionCount.one",
|
||||
"workspaces.sessionCount.other",
|
||||
]) {
|
||||
expect(zhFlat[key], key).toBeTruthy();
|
||||
expect(enFlat[key], key).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the copy contract for key shell strings", () => {
|
||||
expect(zhFlat["nav.workspaces"]).toBe("工作空间");
|
||||
expect(enFlat["nav.workspaces"]).toBe("Workspaces");
|
||||
expect(zhFlat["connect.title"]).toBe("连接 pi2 服务器");
|
||||
expect(enFlat["status.title"]).toBe("Server status");
|
||||
expect(zhFlat["chat.tabSubagents"]).toBe("子代理");
|
||||
expect(enFlat["chat.tabTodo"]).toBe("Todo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("i18n runtime", () => {
|
||||
it("interpolates single-brace params and switches languages", async () => {
|
||||
const { default: i18n, plural, setLanguage } = await import("@/lib/i18n");
|
||||
|
||||
await setLanguage("zh");
|
||||
expect(i18n.t("time.minutesAgo", { n: 3 })).toBe("3 分钟前");
|
||||
expect(i18n.t("shell.serverChip", { name: "ThinkPad" })).toBe("服务器:ThinkPad,查看状态");
|
||||
|
||||
await setLanguage("en");
|
||||
expect(i18n.t("time.minutesAgo", { n: 3 })).toBe("3m ago");
|
||||
expect(i18n.t("shell.serverChip", { name: "ThinkPad" })).toBe("Server: ThinkPad, view status");
|
||||
|
||||
await setLanguage("zh");
|
||||
expect(plural("workspaces.count", 2)).toBe("2 个工作空间");
|
||||
expect(plural("workspaces.sessionCount", 1)).toBe("1 个会话");
|
||||
|
||||
await setLanguage("en");
|
||||
expect(plural("workspaces.count", 2)).toBe("2 workspaces");
|
||||
expect(plural("workspaces.count", 1)).toBe("1 workspace");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { connectHref, safeNext } from "@/lib/routing";
|
||||
|
||||
describe("safeNext", () => {
|
||||
it("keeps whitelisted navigation routes with their query", () => {
|
||||
expect(safeNext("/workspaces")).toBe("/workspaces");
|
||||
expect(safeNext("/status?tab=devices")).toBe("/status?tab=devices");
|
||||
expect(safeNext("/chat/01a15368")).toBe("/chat/01a15368");
|
||||
expect(safeNext("/workspace/ws-pi2?x=1")).toBe("/workspace/ws-pi2?x=1");
|
||||
});
|
||||
|
||||
it("falls back for unknown or unsafe targets", () => {
|
||||
expect(safeNext(undefined)).toBe("/workspaces");
|
||||
expect(safeNext("/servers")).toBe("/workspaces");
|
||||
expect(safeNext("/connect")).toBe("/workspaces");
|
||||
expect(safeNext("javascript:alert(1)")).toBe("/workspaces");
|
||||
expect(safeNext("https://evil.example/not-a-page")).toBe("/workspaces");
|
||||
});
|
||||
|
||||
it("builds an encoded connect redirect", () => {
|
||||
expect(connectHref("/chat/01a1?tab=todo")).toBe("/connect?next=%2Fchat%2F01a1%3Ftab%3Dtodo");
|
||||
expect(connectHref("/nope")).toBe("/connect?next=%2Fworkspaces");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach, vi } from "vitest";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
localStorage.clear();
|
||||
document.documentElement.removeAttribute("data-theme");
|
||||
});
|
||||
|
||||
// next-themes / responsive helpers expect these in jsdom.
|
||||
if (!window.matchMedia) {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
if (!globalThis.ResizeObserver) {
|
||||
class ResizeObserverStub {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
globalThis.ResizeObserver = ResizeObserverStub;
|
||||
}
|
||||
|
||||
if (!Element.prototype.scrollIntoView) {
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import appCss from "@/styles/app.css?raw";
|
||||
import tokensCss from "@/styles/tokens.css?raw";
|
||||
|
||||
function block(source: string, selector: string): string {
|
||||
const start = source.indexOf(selector);
|
||||
expect(start, `missing selector ${selector}`).toBeGreaterThanOrEqual(0);
|
||||
const open = source.indexOf("{", start);
|
||||
let depth = 0;
|
||||
for (let i = open; i < source.length; i += 1) {
|
||||
if (source[i] === "{") depth += 1;
|
||||
if (source[i] === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) return source.slice(open + 1, i);
|
||||
}
|
||||
}
|
||||
throw new Error(`unclosed block ${selector}`);
|
||||
}
|
||||
|
||||
function customProps(source: string): Record<string, string> {
|
||||
const props: Record<string, string> = {};
|
||||
for (const match of source.matchAll(/--([\w-]+)\s*:\s*([^;]+);/g)) {
|
||||
const name = match[1];
|
||||
const value = match[2];
|
||||
if (name && value) props[name] = value.trim();
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
describe("design tokens", () => {
|
||||
const light = customProps(block(tokensCss, ":root"));
|
||||
const dark = customProps(block(tokensCss, 'html[data-theme="dark"]'));
|
||||
|
||||
it("defines the contract's semantic token names in :root", () => {
|
||||
for (const name of [
|
||||
"background",
|
||||
"foreground",
|
||||
"card",
|
||||
"card-foreground",
|
||||
"popover",
|
||||
"muted",
|
||||
"muted-foreground",
|
||||
"accent",
|
||||
"primary",
|
||||
"primary-foreground",
|
||||
"secondary",
|
||||
"destructive",
|
||||
"border",
|
||||
"input",
|
||||
"ring",
|
||||
"sidebar",
|
||||
"sidebar-foreground",
|
||||
"sidebar-accent",
|
||||
"role-user",
|
||||
"role-agent",
|
||||
"role-thinking",
|
||||
"role-error",
|
||||
"ok",
|
||||
"warn",
|
||||
"err",
|
||||
"info",
|
||||
"radius-sm",
|
||||
"radius",
|
||||
"radius-lg",
|
||||
"space-1",
|
||||
"space-8",
|
||||
"font-sans",
|
||||
"font-mono",
|
||||
"topbar-h",
|
||||
"sidebar-w",
|
||||
"rail-w",
|
||||
"tabbar-h",
|
||||
]) {
|
||||
expect(light[name], `--${name}`).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("overrides the same surfaces in the dark data-theme block", () => {
|
||||
expect(light.background).toBe("oklch(0.985 0.004 90)");
|
||||
expect(dark.background).toBe("oklch(0.145 0.008 60)");
|
||||
expect(light.foreground).not.toBe(dark.foreground);
|
||||
for (const name of ["background", "foreground", "card", "muted", "muted-foreground", "primary", "border", "input", "ok", "warn", "role-user", "role-agent", "role-thinking"]) {
|
||||
expect(dark[name], `--${name} dark override`).toBeTruthy();
|
||||
}
|
||||
// Dark borders are translucent white per the contract.
|
||||
expect(dark.border).toContain("oklch(1 0 0");
|
||||
});
|
||||
|
||||
it("maps every semantic token to a Tailwind color utility", () => {
|
||||
const theme = block(appCss, "@theme inline");
|
||||
const mapped = customProps(theme);
|
||||
const expected: Record<string, string> = {
|
||||
"color-background": "--background",
|
||||
"color-foreground": "--foreground",
|
||||
"color-card": "--card",
|
||||
"color-card-foreground": "--card-foreground",
|
||||
"color-popover": "--popover",
|
||||
"color-muted": "--muted",
|
||||
"color-muted-foreground": "--muted-foreground",
|
||||
"color-accent": "--accent",
|
||||
"color-primary": "--primary",
|
||||
"color-primary-foreground": "--primary-foreground",
|
||||
"color-secondary": "--secondary",
|
||||
"color-destructive": "--destructive",
|
||||
"color-border": "--border",
|
||||
"color-input": "--input",
|
||||
"color-ring": "--ring",
|
||||
"color-sidebar": "--sidebar",
|
||||
"color-sidebar-foreground": "--sidebar-foreground",
|
||||
"color-sidebar-accent": "--sidebar-accent",
|
||||
"color-role-user": "--role-user",
|
||||
"color-role-agent": "--role-agent",
|
||||
"color-role-thinking": "--role-thinking",
|
||||
"color-role-error": "--role-error",
|
||||
"color-ok": "--ok",
|
||||
"color-warn": "--warn",
|
||||
"color-err": "--err",
|
||||
"color-info": "--info",
|
||||
};
|
||||
for (const [utility, token] of Object.entries(expected)) {
|
||||
expect(mapped[utility], `--${utility}`).toBe(`var(${token})`);
|
||||
}
|
||||
expect(appCss).toContain("@custom-variant dark");
|
||||
});
|
||||
|
||||
it("switches computed values with data-theme", () => {
|
||||
const style = document.createElement("style");
|
||||
style.textContent = tokensCss;
|
||||
document.head.appendChild(style);
|
||||
|
||||
document.documentElement.dataset.theme = "light";
|
||||
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).toBe(
|
||||
"oklch(0.985 0.004 90)",
|
||||
);
|
||||
|
||||
document.documentElement.dataset.theme = "dark";
|
||||
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).toBe(
|
||||
"oklch(0.145 0.008 60)",
|
||||
);
|
||||
|
||||
style.remove();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PiWsClient, type WebSocketLike, type WsFrame } from "@/lib/ws";
|
||||
|
||||
class FakeSocket implements WebSocketLike {
|
||||
readyState = 0;
|
||||
sent: WsFrame[] = [];
|
||||
closed = false;
|
||||
onopen: ((event: unknown) => void) | null = null;
|
||||
onmessage: ((event: { data: unknown }) => void) | null = null;
|
||||
onclose: ((event: { code?: number; reason?: string }) => void) | null = null;
|
||||
onerror: ((event: unknown) => void) | null = null;
|
||||
|
||||
send(data: string): void {
|
||||
this.sent.push(JSON.parse(data) as WsFrame);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.readyState = 3;
|
||||
this.onclose?.({ code: 1000, reason: "closed" });
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.readyState = 1;
|
||||
this.onopen?.({});
|
||||
}
|
||||
|
||||
receive(frame: Record<string, unknown>): void {
|
||||
this.onmessage?.({ data: JSON.stringify(frame) });
|
||||
}
|
||||
|
||||
serverClose(code = 1006): void {
|
||||
this.readyState = 3;
|
||||
this.onclose?.({ code });
|
||||
}
|
||||
|
||||
frames(type: string): WsFrame[] {
|
||||
return this.sent.filter((frame) => frame.type === type);
|
||||
}
|
||||
}
|
||||
|
||||
function createClient(token = "pkt_test") {
|
||||
const sockets: FakeSocket[] = [];
|
||||
const states: string[] = [];
|
||||
const snapshots: unknown[] = [];
|
||||
const events: unknown[] = [];
|
||||
const client = new PiWsClient({
|
||||
url: "ws://127.0.0.1:7676/api/v1/ws",
|
||||
token,
|
||||
heartbeatMs: 0,
|
||||
socketFactory: () => {
|
||||
const socket = new FakeSocket();
|
||||
sockets.push(socket);
|
||||
return socket;
|
||||
},
|
||||
handlers: {
|
||||
onState: (state) => states.push(state),
|
||||
onSnapshot: (snapshot) => snapshots.push(snapshot),
|
||||
onEvent: (event) => events.push(event),
|
||||
},
|
||||
});
|
||||
return { client, sockets, states, snapshots, events };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("PiWsClient", () => {
|
||||
it("sends the auth frame first, then flushes subscriptions on hello_ack", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets, states } = createClient();
|
||||
client.connect();
|
||||
expect(sockets).toHaveLength(1);
|
||||
expect(states).toEqual(["connecting"]);
|
||||
|
||||
const socket = sockets[0]!;
|
||||
socket.open();
|
||||
expect(states).toEqual(["connecting", "authenticating"]);
|
||||
expect(socket.sent[0]).toEqual({ v: 1, type: "auth", payload: { token: "pkt_test" } });
|
||||
|
||||
// Queued before authentication.
|
||||
client.subscribe("s1");
|
||||
expect(socket.frames("subscribe")).toHaveLength(0);
|
||||
|
||||
socket.receive({ v: 1, type: "hello_ack" });
|
||||
expect(client.getState()).toBe("open");
|
||||
expect(socket.frames("subscribe")).toEqual([
|
||||
{ v: 1, type: "subscribe", payload: { sessionIds: ["s1"] } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("reconnects with exponential backoff and resumes with sinceSeq", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets, states, snapshots } = createClient();
|
||||
client.connect();
|
||||
sockets[0]!.open();
|
||||
sockets[0]!.receive({ type: "hello_ack" });
|
||||
client.subscribe(["s1"]);
|
||||
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", epoch: "e1", seq: 10, payload: { ok: true } });
|
||||
expect(client.getLastSeq("s1")).toBe(10);
|
||||
expect(snapshots).toHaveLength(1);
|
||||
|
||||
sockets[0]!.serverClose(1006);
|
||||
expect(client.getState()).toBe("reconnecting");
|
||||
|
||||
vi.advanceTimersByTime(199);
|
||||
expect(sockets).toHaveLength(1);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(sockets).toHaveLength(2);
|
||||
|
||||
sockets[1]!.open();
|
||||
expect(sockets[1]!.sent[0]?.type).toBe("auth");
|
||||
sockets[1]!.receive({ type: "hello_ack" });
|
||||
expect(client.getState()).toBe("open");
|
||||
expect(sockets[1]!.frames("subscribe")).toEqual([
|
||||
{ v: 1, type: "subscribe", payload: { sessionIds: ["s1"], sinceSeq: { s1: 10 } } },
|
||||
]);
|
||||
|
||||
// A successful hello_ack resets the backoff, so the next retry is 200ms again.
|
||||
sockets[1]!.serverClose(1006);
|
||||
vi.advanceTimersByTime(199);
|
||||
expect(sockets).toHaveLength(2);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(sockets).toHaveLength(3);
|
||||
expect(states).toContain("authenticating");
|
||||
});
|
||||
|
||||
it("tracks event seq and ignores duplicates", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets, events } = createClient();
|
||||
client.connect();
|
||||
sockets[0]!.open();
|
||||
sockets[0]!.receive({ type: "hello_ack" });
|
||||
client.subscribe("s1");
|
||||
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", seq: 4, payload: {} });
|
||||
sockets[0]!.receive({ type: "event", sessionId: "s1", seq: 5, payload: { kind: "a" } });
|
||||
sockets[0]!.receive({ type: "event", sessionId: "s1", seq: 5, payload: { kind: "duplicate" } });
|
||||
sockets[0]!.receive({ type: "event", sessionId: "s1", seq: 6, payload: { kind: "b" } });
|
||||
expect(client.getLastSeq("s1")).toBe(6);
|
||||
expect(events).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("clears the resume cursor on resync_required", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets } = createClient();
|
||||
client.connect();
|
||||
sockets[0]!.open();
|
||||
sockets[0]!.receive({ type: "hello_ack" });
|
||||
client.subscribe("s1");
|
||||
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", epoch: "e1", seq: 10, payload: {} });
|
||||
sockets[0]!.receive({ type: "resync_required", sessionId: "s1" });
|
||||
expect(client.getLastSeq("s1")).toBeUndefined();
|
||||
expect(client.getEpoch("s1")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("stops reconnecting after close()", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets } = createClient();
|
||||
client.connect();
|
||||
sockets[0]!.open();
|
||||
sockets[0]!.receive({ type: "hello_ack" });
|
||||
client.close();
|
||||
expect(client.getState()).toBe("closed");
|
||||
expect(sockets[0]!.closed).toBe(true);
|
||||
vi.advanceTimersByTime(10_000);
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("caps backoff at maxBackoffMs", () => {
|
||||
vi.useFakeTimers();
|
||||
const sockets: FakeSocket[] = [];
|
||||
const client = new PiWsClient({
|
||||
url: "ws://x",
|
||||
token: "t",
|
||||
heartbeatMs: 0,
|
||||
initialBackoffMs: 200,
|
||||
maxBackoffMs: 500,
|
||||
socketFactory: () => {
|
||||
const socket = new FakeSocket();
|
||||
sockets.push(socket);
|
||||
return socket;
|
||||
},
|
||||
});
|
||||
client.connect();
|
||||
// Fail four times without authenticating.
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
sockets[i]!.serverClose(1006);
|
||||
vi.advanceTimersByTime(500);
|
||||
}
|
||||
expect(sockets.length).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": false,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
"types": ["vite/client", "vitest/globals", "@testing-library/jest-dom"]
|
||||
},
|
||||
"include": ["src", "tests", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import path from "node:path";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
const DAEMON = "http://127.0.0.1:7676";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(import.meta.dirname, "src"),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: false,
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: DAEMON,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/ws": {
|
||||
target: DAEMON,
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
proxy: {
|
||||
"/api": { target: DAEMON, changeOrigin: true },
|
||||
"/ws": { target: DAEMON, changeOrigin: true, ws: true },
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: "jsdom",
|
||||
globals: true,
|
||||
setupFiles: ["./tests/setup.ts"],
|
||||
include: ["tests/**/*.test.{ts,tsx}"],
|
||||
css: true,
|
||||
restoreMocks: true,
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user