Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

mirai-gui: new ui (#1074)

alex-at-miraiaa1596f89314
diff --git a/apps/mirai-gui/.prettierignore b/apps/mirai-gui/.prettierignore
index 6e875511a..712924aab 100644
--- a/apps/mirai-gui/.prettierignore
+++ b/apps/mirai-gui/.prettierignore
@@ -3,3 +3,5 @@ client/dist-*/
desktop/target/
desktop/gen/
pnpm-lock.yaml
+# Written by Icon Composer in its own JSON style; it rewrites the file on every save.
+desktop/icons/*.icon/
diff --git a/apps/mirai-gui/client/index.html b/apps/mirai-gui/client/index.html
index 4a13eb47f..5c1f7d450 100644
--- a/apps/mirai-gui/client/index.html
+++ b/apps/mirai-gui/client/index.html
@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mirai</title>
<link rel="icon" type="image/png" href="/icons/icon_mirai_app.png" />
+ <link rel="preload" href="/fonts/InterVariable.woff2" as="font" type="font/woff2" crossorigin />
<script>
{
let theme = "system";
diff --git a/apps/mirai-gui/client/public/icons/icon_mirai_app.png b/apps/mirai-gui/client/public/icons/icon_mirai_app.png
index 77e5edffc..ebedc839d 100644
Binary files a/apps/mirai-gui/client/public/icons/icon_mirai_app.png and b/apps/mirai-gui/client/public/icons/icon_mirai_app.png differ
diff --git a/apps/mirai-gui/client/src/components/error-page.tsx b/apps/mirai-gui/client/src/components/error-page.tsx
index 8eae43cef..e695bf7fa 100644
--- a/apps/mirai-gui/client/src/components/error-page.tsx
+++ b/apps/mirai-gui/client/src/components/error-page.tsx
@@ -4,7 +4,7 @@ import { useRouter } from "@tanstack/react-router";
import { ArrowLeft } from "lucide-react";
import { Logo } from "./icons/logo";
import { LogoLightMode } from "./icons/logo-light-mode";
-import { ErrorIcon } from "./icons/error-icon";
+import { UzuCat } from "./uzu-cat";
export function ErrorPage() {
const isDarkMode = useAppStore((s) => s.isDarkMode);
@@ -22,9 +22,9 @@ export function ErrorPage() {
</div>
<div className="flex-1 min-h-0 overflow-y-auto overscroll-y-contain px-4">
<div className="flex min-h-full flex-col items-center justify-center gap-10 py-4">
- <ErrorIcon color="#FF2020" />
+ <UzuCat state="idle" size={96} className="text-text-primary" label="uzu, looking around" />
<div className="flex flex-col items-center justify-center gap-3 text-center">
- <h1 className="text-2xl font-bold">Page Not Found</h1>
+ <h1 className="text-2xl font-bold">Page not found</h1>
<p className="text-base text-label-muted">An unexpected error occurred</p>
</div>
<Button kind="primary" icon={<ArrowLeft size={16} />} onClick={handleAction}>
diff --git a/apps/mirai-gui/client/src/components/footer-bar/index.tsx b/apps/mirai-gui/client/src/components/footer-bar/index.tsx
index e81ddfb99..c63e27582 100644
--- a/apps/mirai-gui/client/src/components/footer-bar/index.tsx
+++ b/apps/mirai-gui/client/src/components/footer-bar/index.tsx
@@ -1,57 +1,75 @@
import { useFooterRuntimeModel } from "./use-footer-runtime-model";
import { useAppStore } from "@/stores/use-app-store";
-import { ModelVendorIcon } from "@/components/model-vendor-icon";
-import React from "react";
+import React, { type ReactNode } from "react";
import { twMerge } from "tailwind-merge";
import { EjectIcon } from "../icons/eject-icon";
-import { Loader } from "../loader";
+import { TextShimmer } from "../ui/text-shimmer";
+import { UzuCat } from "../uzu-cat";
+import { Tooltip } from "../ui/tooltip";
+import { ModelName, splitModelName } from "../model-name";
-export const FooterBar = React.memo(({ className }: { className?: string }) => {
+// The loaded model, named like the composer's model pill: the model, then its quantization (muted
+// in the tooltip).
+const shortModelName = (name: string) => {
+ const { base, variant } = splitModelName(name);
+ return variant ? `${base} ${variant}` : base;
+};
+
+export const FooterBar = React.memo(({ className, leading }: { className?: string; leading?: ReactNode }) => {
const version = useAppStore((s) => s.appVersion);
const footerModel = useFooterRuntimeModel();
+ if (!leading && !footerModel.visible && !version) return null;
+
+ // The foot of the sidebar: whatever leads on the left (the Settings gear), then on the right the
+ // loaded model's state with its one action, and the version. The model's full name lives in the
+ // tooltip.
return (
- <div
- className={twMerge(
- "bg-bg-sidebar min-h-6 shrink-0 border-t border-cell-border flex items-center justify-between gap-3 px-5 py-[5px] select-none",
- className,
- )}
- >
- <div className="flex min-w-0 flex-1 items-center gap-2">
- {footerModel.visible && (
- <>
- {footerModel.status === "loading" || footerModel.status === "ejecting" ? (
- <Loader
- showText
- textClassName="text-[11px]"
- iconWidth={8}
- iconHeight={8}
- text={footerModel.status === "ejecting" ? "Ejecting…" : "Loading model…"}
+ <div className={twMerge("h-11 shrink-0 flex items-center justify-between gap-2 px-3 select-none", className)}>
+ {leading ?? <span />}
+ <div className="flex min-w-0 items-center gap-1">
+ {footerModel.visible ? (
+ footerModel.status === "loading" || footerModel.status === "ejecting" ? (
+ <span key={footerModel.status} className="flex h-6 items-center gap-1.5 px-1.5 animate-uzu-swap">
+ <UzuCat
+ state={footerModel.status === "ejecting" ? "freeing" : "loading"}
+ size={16}
+ className="text-text-primary"
/>
- ) : (
- <>
- <button
- onClick={footerModel.onEject}
- disabled={!footerModel.canEject}
- className="flex shrink-0 items-center gap-[5px] whitespace-nowrap hover:text-label-title disabled:opacity-50 disabled:cursor-not-allowed"
- >
- <EjectIcon className="text-label-title" />
- <span className="text-[11px] font-[350] leading-[120%]">Eject model</span>
- </button>
- <span className="flex min-w-0 items-center gap-1.5" title={footerModel.label}>
- {footerModel.vendor && (
- <ModelVendorIcon vendor={footerModel.vendor} size={12} className="h-3 w-3 shrink-0" />
- )}
- <span className="text-[11px] font-[450] leading-[1.3] truncate text-text-secondary">
- {footerModel.label}
- </span>
+ <TextShimmer duration={1.6} className="text-[11px] font-[450] leading-[1.3]">
+ {footerModel.status === "ejecting" ? "Ejecting…" : "Loading…"}
+ </TextShimmer>
+ </span>
+ ) : (
+ <Tooltip
+ content={
+ <span className="flex items-baseline gap-1">
+ Eject
+ <ModelName name={footerModel.label} />
</span>
- </>
- )}
- </>
- )}
+ }
+ side="top"
+ >
+ <button
+ key="resident"
+ type="button"
+ onClick={footerModel.onEject}
+ disabled={!footerModel.canEject}
+ aria-label={`Eject ${shortModelName(footerModel.label)}`}
+ className="flex h-6 items-center gap-1.5 whitespace-nowrap rounded-md px-1.5 text-[11px] font-[450] leading-[1.3] text-text-muted transition-colors duration-150 ease-out hover:bg-sidebar-chat-hover hover:text-text-primary disabled:opacity-50 disabled:cursor-not-allowed outline-hidden focus-visible:shadow-focus animate-uzu-swap"
+ >
+ <EjectIcon className="shrink-0" />
+ <span>Eject model</span>
+ </button>
+ </Tooltip>
+ )
+ ) : null}
+ {version ? (
+ <div className="shrink-0 px-1.5 text-[11px] font-[450] leading-[1.3] text-text-muted tabular-nums">
+ {version}
+ </div>
+ ) : null}
</div>
- {version && <div className="shrink-0 text-[11px] font-[450] leading-[1.3] text-text-muted">{version}</div>}
</div>
);
});
diff --git a/apps/mirai-gui/client/src/components/footer-bar/use-footer-runtime-model.ts b/apps/mirai-gui/client/src/components/footer-bar/use-footer-runtime-model.tsx
similarity index 86%
rename from apps/mirai-gui/client/src/components/footer-bar/use-footer-runtime-model.ts
rename to apps/mirai-gui/client/src/components/footer-bar/use-footer-runtime-model.tsx
index bbb42bac5..51219a3bc 100644
--- a/apps/mirai-gui/client/src/components/footer-bar/use-footer-runtime-model.ts
+++ b/apps/mirai-gui/client/src/components/footer-bar/use-footer-runtime-model.tsx
@@ -1,3 +1,4 @@
+import { InlineModelName } from "@/components/model-name";
import { useToast } from "@/components/ui/toast/use-toast";
import { ejectRuntimeSessionAndWait } from "@/features/runtime/eject-runtime-session";
import { useModelsStore } from "@/stores/use-models-store";
@@ -62,14 +63,23 @@ export const useFooterRuntimeModel = (): FooterRuntimeModel => {
reason: runtimeSessionEjectReasons.user,
});
if (ok) {
- toast.success("Model ejected successfully");
+ toast.success(
+ <>
+ Ejected <InlineModelName name={label} />
+ </>,
+ );
}
} catch (error) {
- toast.error(error instanceof Error ? error.message : "Failed to eject model");
+ toast.error(
+ <>
+ Couldn't eject <InlineModelName name={label} />
+ </>,
+ { description: error instanceof Error ? error.message : undefined },
+ );
} finally {
setEjectAwaiting(false);
}
- }, [residentSession, toast]);
+ }, [residentSession, label, toast]);
if (!activeSession || status === "hidden") {
return {
diff --git a/apps/mirai-gui/client/src/components/icons/app-icons.tsx b/apps/mirai-gui/client/src/components/icons/app-icons.tsx
new file mode 100644
index 000000000..89b27e47f
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/icons/app-icons.tsx
@@ -0,0 +1,253 @@
+import { type SVGProps, useId } from "react";
+
+/*
+ * The interface icons, as local SVG components (24px grid, 2px round strokes). Each takes `size`
+ * (16, 20, ...) and any SVG prop; they are decorative by default (`aria-hidden`), so a button
+ * names itself with `aria-label`. Colour comes from `currentColor`.
+ */
+
+export type IconProps = Omit<SVGProps<SVGSVGElement>, "children"> & { size?: number | string };
+
+function Svg({ size = 24, children, ...rest }: IconProps & { children: React.ReactNode }) {
+ return (
+ <svg
+ aria-hidden
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ {...rest}
+ >
+ {children}
+ </svg>
+ );
+}
+
+export function CircleArrowDownIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M12 8V16M12 16L15 13M12 16L9 13"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </Svg>
+ );
+}
+
+/** Regenerate: a clockwise arrow round a circle (the Figma regenerate icon, scaled from its 32px grid). */
+export function RotateCwIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M21 12C21 13.78 20.4721 15.5201 19.4832 17.0001C18.4943 18.4802 17.0887 19.6337 15.4441 20.3149C13.7996 20.9961 11.99 21.1743 10.2442 20.827C8.4984 20.4798 6.8947 19.6226 5.636 18.364C4.3774 17.1053 3.5202 15.5017 3.1729 13.7558C2.8257 12.01 3.0039 10.2004 3.6851 8.5558C4.3663 6.9113 5.5198 5.5057 6.9999 4.5168C8.4799 3.5278 10.22 3 12 3C14.52 3 16.93 4 18.74 5.74L21 8"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M21 3V8H16.0001" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ </Svg>
+ );
+}
+
+export function InfoIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M11 11H12V16M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M12 7.25C11.5858 7.25 11.25 7.58579 11.25 8C11.25 8.41421 11.5858 8.75 12 8.75C12.4142 8.75 12.75 8.41421 12.75 8C12.75 7.58579 12.4142 7.25 12 7.25Z"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeWidth="0.5"
+ />
+ </Svg>
+ );
+}
+
+export function XIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path d="M8 8L16 16M16 8L8 16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
+ </Svg>
+ );
+}
+
+export function EllipsisIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M12 13C12.5523 13 13 12.5523 13 12C13 11.4477 12.5523 11 12 11C11.4477 11 11 11.4477 11 12C11 12.5523 11.4477 13 12 13Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M20 13C20.5523 13 21 12.5523 21 12C21 11.4477 20.5523 11 20 11C19.4477 11 19 11.4477 19 12C19 12.5523 19.4477 13 20 13Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M4 13C4.55228 13 5 12.5523 5 12C5 11.4477 4.55228 11 4 11C3.44772 11 3 11.4477 3 12C3 12.5523 3.44772 13 4 13Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </Svg>
+ );
+}
+
+/** Alert: an exclamation mark in a circle (the Figma alert icon, scaled from its 32px grid). Used
+ * for every alert, warnings and errors alike; the colour tells them apart. */
+export function CircleAlertIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M12 22C17.5229 22 22.0001 17.5229 22.0001 12C22.0001 6.4771 17.5229 2 12 2C6.4772 2 2 6.4771 2 12C2 17.5229 6.4772 22 12 22Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M12 8V12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ <path d="M12 16H12.01" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ </Svg>
+ );
+}
+
+/** A lightning bolt, for speed (the Figma speed icon). */
+export function ZapIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M15.914 4C16.0271 3.67936 16.028 3.3298 15.9164 3.00861C15.8049 2.68743 15.5875 2.41367 15.2999 2.23224C15.0124 2.0508 14.6717 1.97244 14.3338 2.01001C13.9958 2.04757 13.6807 2.19884 13.44 2.439L4.43999 11.439C4.23013 11.6487 4.08718 11.916 4.02921 12.2069C3.97125 12.4979 4.00087 12.7995 4.11433 13.0737C4.2278 13.3478 4.42001 13.5821 4.66665 13.747C4.9133 13.9119 5.2033 13.9999 5.49999 14H9.50199C9.58186 14.0001 9.66055 14.0193 9.73147 14.0561C9.80238 14.0929 9.86345 14.1461 9.90958 14.2113C9.9557 14.2765 9.98552 14.3518 9.99655 14.4309C10.0076 14.5101 9.9995 14.5907 9.97299 14.666L8.08599 20C7.97279 20.3207 7.97198 20.6704 8.08366 20.9917C8.19535 21.313 8.41291 21.5868 8.70066 21.7681C8.9884 21.9495 9.32925 22.0277 9.66727 21.9899C10.0053 21.9521 10.3204 21.8005 10.561 21.56L19.561 12.56C19.7706 12.3502 19.9132 12.0829 19.971 11.792C20.0287 11.5011 19.9989 11.1997 19.8854 10.9257C19.7718 10.6517 19.5796 10.4176 19.333 10.2528C19.0864 10.088 18.7966 10.0001 18.5 10H14.503C14.4229 10.0001 14.344 9.98099 14.2728 9.94424C14.2017 9.90749 14.1404 9.85419 14.0941 9.78882C14.0479 9.72345 14.018 9.64793 14.007 9.56861C13.996 9.48928 14.0042 9.40848 14.031 9.333L15.914 4Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </Svg>
+ );
+}
+
+export function FileTextIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M5 6C5 4.34315 6.34315 3 8 3H16C17.6569 3 19 4.34315 19 6V18C19 19.6569 17.6569 21 16 21H8C6.34315 21 5 19.6569 5 18V6Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M9 7H15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ <path d="M9 11H15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ <path d="M9 15H11" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ </Svg>
+ );
+}
+
+/** Rename: a rounded pencil (the Figma rename icon, scaled from its 20px grid), the same pencil as
+ * the sidebar's New chat without the line under it. */
+export function PencilIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M20.2213 4.1213L20.4787 4.3787C21.6503 5.5503 21.6503 7.4498 20.4787 8.6214L8.9787 20.1214C8.4161 20.684 7.653 21 6.8574 21H3.6V17.7427C3.6 16.947 3.9161 16.184 4.4787 15.6214L15.9787 4.1214C17.1503 2.9498 19.0496 2.9498 20.2213 4.1213Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </Svg>
+ );
+}
+
+export function PlusIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M12 5.5V12M12 12V18.5M12 12H5.5M12 12H18.5"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ />
+ </Svg>
+ );
+}
+
+/** Copy: a square over the corner of the one behind it (the Figma copy icon, scaled from its 32px grid). */
+export function CopyIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M20 8H10C8.8955 8 8 8.8955 8 10V20C8 21.1045 8.8955 22 10 22H20C21.1045 22 22.0001 21.1045 22.0001 20V10C22.0001 8.8955 21.1045 8 20 8Z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M4 16C2.9 16 2 15.1 2 14V4C2 2.9 2.9 2 4 2H14C15.1001 2 16.0001 2.9 16.0001 4"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </Svg>
+ );
+}
+
+/** Download: an arrow dropping into a tray. */
+export function DownloadIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <path
+ d="M4 14C4.55228 14 5 14.4477 5 15V17C5 18.1046 5.89543 19 7 19H17C18.1046 19 19 18.1046 19 17V15C19 14.4477 19.4477 14 20 14C20.5523 14 21 14.4477 21 15V17C21 19.2091 19.2091 21 17 21H7C4.79086 21 3 19.2091 3 17V15C3 14.4477 3.44772 14 4 14Z"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ fill="currentColor"
+ />
+ <path
+ d="M12 15.5C12.2652 15.5 12.5196 15.3946 12.7071 15.2071L16.2071 11.7071C16.5976 11.3166 16.5976 10.6834 16.2071 10.2929C15.8166 9.90237 15.1834 9.90237 14.7929 10.2929L13 12.0858V4C13 3.44771 12.5523 3 12 3C11.4477 3 11 3.44771 11 4V12.0858L9.20711 10.2929C8.81658 9.90237 8.18342 9.90237 7.79289 10.2929C7.40237 10.6834 7.40237 11.3166 7.79289 11.7071L11.2929 15.2071C11.4804 15.3946 11.7348 15.5 12 15.5Z"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ fill="currentColor"
+ />
+ </Svg>
+ );
+}
+
+/** The circle-check, filled: a solid disc with the check cut out of it. Shown after a copy. */
+export function CircleCheckIcon({ size = 16, ...rest }: IconProps) {
+ const maskId = useId();
+ return (
+ <Svg size={size} {...rest}>
+ <mask id={maskId} maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
+ <rect width="24" height="24" fill="#fff" />
+ <path d="M15 9.5L10.5 15L8.5 13" stroke="#000" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />
+ </mask>
+ <circle cx="12" cy="12" r="10" fill="currentColor" mask={`url(#${maskId})`} />
+ </Svg>
+ );
+}
diff --git a/apps/mirai-gui/client/src/components/icons/send-icon.tsx b/apps/mirai-gui/client/src/components/icons/arrow-up-icon.tsx
similarity index 68%
rename from apps/mirai-gui/client/src/components/icons/send-icon.tsx
rename to apps/mirai-gui/client/src/components/icons/arrow-up-icon.tsx
index ca2e429d2..0a749af1a 100644
--- a/apps/mirai-gui/client/src/components/icons/send-icon.tsx
+++ b/apps/mirai-gui/client/src/components/icons/arrow-up-icon.tsx
@@ -1,8 +1,8 @@
import type { SVGProps } from "react";
-export type IconSendProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
+export type ArrowUpIconProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
-export function IconSend({ size = 16, color = "currentColor", ...props }: IconSendProps) {
+export function ArrowUpIcon({ size = 16, color = "currentColor", ...props }: ArrowUpIconProps) {
return (
<svg width={size} height={size} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
<path d="M8 3V12" stroke={color} strokeWidth="1.33333" strokeLinecap="round" strokeLinejoin="round" />
diff --git a/apps/mirai-gui/client/src/components/icons/chats-icon.tsx b/apps/mirai-gui/client/src/components/icons/chats-icon.tsx
deleted file mode 100644
index 690449728..000000000
--- a/apps/mirai-gui/client/src/components/icons/chats-icon.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import React from "react";
-
-type ChatsIconProps = React.SVGProps<SVGSVGElement>;
-
-export function ChatsIcon(props: ChatsIconProps) {
- return (
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none" {...props}>
- <path
- d="M13.8681 13.5282C13.8681 13.5282 13.9195 13.4916 14.0015 13.4289C15.2301 12.4789 16.0015 11.1022 16.0015 9.56955C16.0015 6.71222 13.3148 4.39355 10.0015 4.39355C6.68813 4.39355 4.00146 6.71222 4.00146 9.56955C4.00146 12.4282 6.68813 14.6669 10.0015 14.6669C10.2841 14.6669 10.7481 14.6482 11.3935 14.6109C12.2348 15.1576 13.4628 15.6062 14.5375 15.6062C14.8701 15.6062 15.0268 15.3329 14.8135 15.0542C14.4895 14.6569 14.0428 14.0202 13.8695 13.5276L13.8681 13.5282Z"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- );
-}
diff --git a/apps/mirai-gui/client/src/components/icons/check-circle-filled-icon.tsx b/apps/mirai-gui/client/src/components/icons/check-circle-filled-icon.tsx
deleted file mode 100644
index 740760ee5..000000000
--- a/apps/mirai-gui/client/src/components/icons/check-circle-filled-icon.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import type { SVGProps } from "react";
-
-export type IconCheckCircleFilledProps = SVGProps<SVGSVGElement> & {
- size?: number;
- color?: string;
-};
-
-export function IconCheckCircleFilled({ size = 16, color = "currentColor", ...props }: IconCheckCircleFilledProps) {
- return (
- <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 16 16" fill="none" {...props}>
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M7.99967 1.33337C11.6815 1.33337 14.6663 4.31814 14.6663 8.00004C14.6663 11.6819 11.6815 14.6667 7.99967 14.6667C4.31777 14.6667 1.33301 11.6819 1.33301 8.00004C1.33301 4.31814 4.31777 1.33337 7.99967 1.33337ZM10.3721 5.44731C10.0667 5.24177 9.65261 5.32241 9.44694 5.62765L6.98147 9.28911L5.80436 8.11204C5.54401 7.85164 5.122 7.85164 4.86165 8.11204C4.6013 8.37237 4.6013 8.79437 4.86165 9.05471L6.61165 10.8047C6.75254 10.9456 6.94921 11.016 7.14747 10.9968C7.34554 10.9775 7.52454 10.8708 7.63574 10.7058L10.5524 6.37243C10.7579 6.06707 10.6773 5.65295 10.3721 5.44731Z"
- fill={color}
- />
- </svg>
- );
-}
diff --git a/apps/mirai-gui/client/src/components/icons/check-stroke-icon.tsx b/apps/mirai-gui/client/src/components/icons/check-icon.tsx
similarity index 59%
rename from apps/mirai-gui/client/src/components/icons/check-stroke-icon.tsx
rename to apps/mirai-gui/client/src/components/icons/check-icon.tsx
index 1b3f82941..6250467af 100644
--- a/apps/mirai-gui/client/src/components/icons/check-stroke-icon.tsx
+++ b/apps/mirai-gui/client/src/components/icons/check-icon.tsx
@@ -1,8 +1,8 @@
import type { SVGProps } from "react";
-export type IconCheckStrokeProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
+export type CheckIconProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
-export function IconCheckStroke({ size = 16, color = "currentColor", ...props }: IconCheckStrokeProps) {
+export function CheckIcon({ size = 16, color = "currentColor", ...props }: CheckIconProps) {
return (
<svg width={size} height={size} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
<path d="M3 9L6 12L13 4" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
diff --git a/apps/mirai-gui/client/src/components/icons/checkmark-icon.tsx b/apps/mirai-gui/client/src/components/icons/checkmark-icon.tsx
index b4ca2be7a..20ab53d9e 100644
--- a/apps/mirai-gui/client/src/components/icons/checkmark-icon.tsx
+++ b/apps/mirai-gui/client/src/components/icons/checkmark-icon.tsx
@@ -1,11 +1,11 @@
import type { SVGProps } from "react";
-export type IconCheckmarkProps = SVGProps<SVGSVGElement> & {
+export type CheckmarkIconProps = SVGProps<SVGSVGElement> & {
size?: number;
color?: string;
};
-export function IconCheckmark({ size = 16, color = "currentColor", strokeWidth, ...props }: IconCheckmarkProps) {
+export function CheckmarkIcon({ size = 16, color = "currentColor", strokeWidth, ...props }: CheckmarkIconProps) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 20 20" fill="none" {...props}>
<path
diff --git a/apps/mirai-gui/client/src/components/icons/error-icon.tsx b/apps/mirai-gui/client/src/components/icons/error-icon.tsx
deleted file mode 100644
index 718e523bd..000000000
--- a/apps/mirai-gui/client/src/components/icons/error-icon.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-type Props = {
- color: string;
- width?: number;
- height?: number;
-};
-
-export function ErrorIcon({ color, width = 97, height = 96 }: Props) {
- return (
- <svg xmlns="http://www.w3.org/2000/svg" width={width} height={height} viewBox="0 0 97 96" fill="none">
- <path
- d="M48.5107 57.2459L67.3772 89.8375L59.8192 94.1005L41.0016 61.5171L40.5134 60.6709L36.8524 62.7537L21.0775 71.7354L13.5195 58.7429L32.9555 47.6216L13.5195 14.2087L21.0775 9.9375L40.5134 43.4479L48.7629 38.6885L56.2395 34.3687L59.8192 32.3022L60.3643 33.2459L67.3772 45.2947L47.9412 56.2696L48.5107 57.2459Z"
- fill={color}
- fillOpacity="0.08"
- stroke={color}
- strokeWidth="0.813559"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M41.0022 61.5181L37.3493 63.6008L21.0781 71.7364L36.853 62.7547L40.5141 60.6719L41.0022 61.5181Z"
- fill={color}
- fillOpacity="0.08"
- stroke={color}
- strokeWidth="0.813559"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M83.6495 37.1595L67.3783 45.295L60.3654 33.2462L59.8203 32.3026L76.0915 24.167L83.6495 37.1595Z"
- fill={color}
- fillOpacity="0.08"
- stroke={color}
- strokeWidth="0.813559"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M83.6485 81.7026L75.8709 85.5914L67.3773 89.8382L48.5109 57.2466L47.9414 56.2704L64.2126 48.1348L83.6485 81.7026Z"
- fill={color}
- fillOpacity="0.08"
- stroke={color}
- strokeWidth="0.813559"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M83.6495 81.7021L76.0915 85.9652L59.8203 94.1008L67.3783 89.8377L75.8718 85.591L83.6495 81.7021Z"
- fill={color}
- fillOpacity="0.08"
- stroke={color}
- strokeWidth="0.813559"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M83.6485 37.1602L64.2126 48.1351L47.9414 56.2707L67.3773 45.2957L83.6485 37.1602Z"
- fill={color}
- fillOpacity="0.08"
- stroke={color}
- strokeWidth="0.813559"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M56.2402 34.3695L48.7635 38.6894L40.5141 43.4488L21.0781 9.93834L37.3493 1.80273L56.2402 34.3695Z"
- fill={color}
- fillOpacity="0.08"
- stroke={color}
- strokeWidth="0.813559"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- );
-}
diff --git a/apps/mirai-gui/client/src/components/icons/models-icon.tsx b/apps/mirai-gui/client/src/components/icons/models-icon.tsx
deleted file mode 100644
index b4c708302..000000000
--- a/apps/mirai-gui/client/src/components/icons/models-icon.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import React from "react";
-
-type ModelsIconProps = React.SVGProps<SVGSVGElement>;
-
-export function ModelsIcon(props: ModelsIconProps) {
- return (
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none" {...props}>
- <path
- d="M6.41667 7.33366L3.75 10.0003L6.41667 12.667M13.0833 7.33366L15.75 10.0003L13.0833 12.667M11.0833 4.66699L8.41667 15.3337"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- );
-}
diff --git a/apps/mirai-gui/client/src/components/icons/pause-filled-icon.tsx b/apps/mirai-gui/client/src/components/icons/pause-icon.tsx
similarity index 74%
rename from apps/mirai-gui/client/src/components/icons/pause-filled-icon.tsx
rename to apps/mirai-gui/client/src/components/icons/pause-icon.tsx
index 4915a8fc1..f40c86537 100644
--- a/apps/mirai-gui/client/src/components/icons/pause-filled-icon.tsx
+++ b/apps/mirai-gui/client/src/components/icons/pause-icon.tsx
@@ -1,8 +1,8 @@
import type { SVGProps } from "react";
-export type IconPauseFilledProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
+export type PauseIconProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
-export function IconPauseFilled({ size = 16, color = "currentColor", ...props }: IconPauseFilledProps) {
+export function PauseIcon({ size = 16, color = "currentColor", ...props }: PauseIconProps) {
return (
<svg width={size} height={size} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
<path
diff --git a/apps/mirai-gui/client/src/components/icons/play-filled-icon.tsx b/apps/mirai-gui/client/src/components/icons/play-icon.tsx
similarity index 67%
rename from apps/mirai-gui/client/src/components/icons/play-filled-icon.tsx
rename to apps/mirai-gui/client/src/components/icons/play-icon.tsx
index 4b6d23f40..1bfdbd45c 100644
--- a/apps/mirai-gui/client/src/components/icons/play-filled-icon.tsx
+++ b/apps/mirai-gui/client/src/components/icons/play-icon.tsx
@@ -1,8 +1,8 @@
import type { SVGProps } from "react";
-export type IconPlayFilledProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
+export type PlayIconProps = SVGProps<SVGSVGElement> & { size?: number; color?: string };
-export function IconPlayFilled({ size = 16, color = "currentColor", ...props }: IconPlayFilledProps) {
+export function PlayIcon({ size = 16, color = "currentColor", ...props }: PlayIconProps) {
return (
<svg width={size} height={size} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
<path
diff --git a/apps/mirai-gui/client/src/components/icons/rename-icon.tsx b/apps/mirai-gui/client/src/components/icons/rename-icon.tsx
deleted file mode 100644
index 6919cd908..000000000
--- a/apps/mirai-gui/client/src/components/icons/rename-icon.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import React from "react";
-
-type Props = {
- className?: string;
-};
-
-export const RenameIcon: React.FC<Props> = ({ className }) => (
- <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
- <path
- d="M7.33329 2.66602H5.86663C4.74652 2.66602 4.18647 2.66602 3.75865 2.884C3.38232 3.07575 3.07636 3.38171 2.88461 3.75804C2.66663 4.18586 2.66663 4.74591 2.66663 5.86602V10.1327C2.66663 11.2528 2.66663 11.8128 2.88461 12.2407C3.07636 12.617 3.38232 12.9229 3.75865 13.1147C4.18647 13.3327 4.74652 13.3327 5.86663 13.3327H10.1333C11.2534 13.3327 11.8134 13.3327 12.2413 13.1147C12.6176 12.9229 12.9236 12.617 13.1153 12.2407C13.3333 11.8128 13.3333 11.2528 13.3333 10.1327V8.66602"
- stroke="currentColor"
- strokeWidth="1.33333"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M6 10.0002V8.27629C6 8.09949 6.07024 7.92989 6.19526 7.80489L11.5 2.50015C12.0523 1.94787 12.9477 1.94787 13.5 2.50015C14.0523 3.05243 14.0523 3.94786 13.5 4.50015L8.19527 9.80489C8.07027 9.92989 7.90067 10.0002 7.72387 10.0002H6Z"
- stroke="currentColor"
- strokeWidth="1.33333"
- strokeLinecap="square"
- strokeLinejoin="round"
- />
- </svg>
-);
-
-export default RenameIcon;
diff --git a/apps/mirai-gui/client/src/components/icons/sidebar-toggle-icon.tsx b/apps/mirai-gui/client/src/components/icons/sidebar-toggle-icon.tsx
deleted file mode 100644
index 767775369..000000000
--- a/apps/mirai-gui/client/src/components/icons/sidebar-toggle-icon.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import React from "react";
-
-const SidebarToggleIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none" {...props}>
- <path
- d="M7.75 4V16M4 5.5C4 5.10218 4.15804 4.72064 4.43934 4.43934C4.72064 4.15804 5.10218 4 5.5 4H14.5C14.8978 4 15.2794 4.15804 15.5607 4.43934C15.842 4.72064 16 5.10218 16 5.5V14.5C16 14.8978 15.842 15.2794 15.5607 15.5607C15.2794 15.842 14.8978 16 14.5 16H5.5C5.10218 16 4.72064 15.842 4.43934 15.5607C4.15804 15.2794 4 14.8978 4 14.5V5.5Z"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
-);
-
-export default SidebarToggleIcon;
diff --git a/apps/mirai-gui/client/src/components/icons/player-stop-filled-icon.tsx b/apps/mirai-gui/client/src/components/icons/square-icon.tsx
similarity index 60%
rename from apps/mirai-gui/client/src/components/icons/player-stop-filled-icon.tsx
rename to apps/mirai-gui/client/src/components/icons/square-icon.tsx
index 80c9be6ea..843eed264 100644
--- a/apps/mirai-gui/client/src/components/icons/player-stop-filled-icon.tsx
+++ b/apps/mirai-gui/client/src/components/icons/square-icon.tsx
@@ -1,11 +1,11 @@
import type { SVGProps } from "react";
-export type IconPlayerStopFilledProps = SVGProps<SVGSVGElement> & {
+export type SquareIconProps = SVGProps<SVGSVGElement> & {
size?: number;
color?: string;
};
-export function IconPlayerStopFilled({ size = 16, color = "currentColor", ...props }: IconPlayerStopFilledProps) {
+export function SquareIcon({ size = 16, color = "currentColor", ...props }: SquareIconProps) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill={color} {...props}>
<rect x="3" y="3" width="18" height="18" rx="3" />
diff --git a/apps/mirai-gui/client/src/components/icons/thinking-bubble.tsx b/apps/mirai-gui/client/src/components/icons/thinking-bubble.tsx
deleted file mode 100644
index 99a81c64e..000000000
--- a/apps/mirai-gui/client/src/components/icons/thinking-bubble.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import React from "react";
-
-export const ThinkingBubbleIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
- <svg viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
- <path
- d="M6.40727 3.05139C6.22778 3.22339 5.97187 3.29849 5.72697 3.25586C5.57912 3.23013 5.42705 3.21672 5.27188 3.21672C3.81005 3.21672 2.625 4.40689 2.625 5.87505C2.625 6.69763 2.99702 7.43298 3.58131 7.92058C3.72927 8.04408 3.8265 8.21989 3.8523 8.41088C4.02762 9.70833 5.13503 10.7083 6.475 10.7083C7.11638 10.7083 7.70449 10.4792 8.16258 10.0981C8.34178 9.94895 8.58136 9.88589 8.81014 9.9304C8.98899 9.96517 9.17367 9.98343 9.36256 9.98343C10.9573 9.98343 12.2501 8.68504 12.2501 7.08338C12.2501 6.30427 11.9442 5.5969 11.4463 5.07585C11.3426 4.9673 11.274 4.82929 11.2501 4.68109C11.0269 3.30244 9.83587 2.25 8.40012 2.25C7.62737 2.25 6.92551 2.55487 6.40727 3.05139Z"
- stroke="currentColor"
- strokeWidth="1.1"
- strokeLinejoin="round"
- />
- <path
- d="M3.49935 12.1667C3.49935 12.811 2.97701 13.3333 2.33268 13.3333C1.68835 13.3333 1.16602 12.811 1.16602 12.1667C1.16602 11.5223 1.68835 11 2.33268 11C2.97701 11 3.49935 11.5223 3.49935 12.1667Z"
- stroke="currentColor"
- strokeWidth="1.1"
- />
- </svg>
-);
diff --git a/apps/mirai-gui/client/src/components/icons/trash-icon.tsx b/apps/mirai-gui/client/src/components/icons/trash-icon.tsx
deleted file mode 100644
index 0f6851764..000000000
--- a/apps/mirai-gui/client/src/components/icons/trash-icon.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import React from "react";
-
-type Props = {
- className?: string;
-};
-
-export const TrashIcon: React.FC<Props> = ({ className }) => (
- <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
- <path
- d="M3.33337 4.33398L3.8716 12.1383C3.94392 13.1869 4.81569 14.0007 5.86686 14.0007H10.1332C11.1844 14.0007 12.0562 13.1869 12.1285 12.1383L12.6667 4.33398"
- stroke="currentColor"
- strokeWidth="1.33333"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M6.66663 7.33398V10.6673"
- stroke="currentColor"
- strokeWidth="1.33333"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M9.33337 7.33398V10.6673"
- stroke="currentColor"
- strokeWidth="1.33333"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M2.33337 4H13.6667"
- stroke="currentColor"
- strokeWidth="1.33333"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- <path
- d="M5.38049 3.83016C5.61553 2.59765 6.69888 1.66602 7.99988 1.66602C9.30088 1.66602 10.3842 2.59765 10.6193 3.83016"
- stroke="currentColor"
- strokeWidth="1.33333"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
-);
-
-export default TrashIcon;
diff --git a/apps/mirai-gui/client/src/components/left-bar/index.tsx b/apps/mirai-gui/client/src/components/left-bar/index.tsx
index 48baac5bf..887705514 100644
--- a/apps/mirai-gui/client/src/components/left-bar/index.tsx
+++ b/apps/mirai-gui/client/src/components/left-bar/index.tsx
@@ -1,27 +1,31 @@
+import { useEffect, useRef, useState } from "react";
import { useIsMobile } from "@/hooks/use-media-query";
+import { useNativeFullscreen } from "@/hooks/use-native-fullscreen";
import { platformInfo } from "@/platform/platform-info";
import { useChatStore } from "@/stores/use-chat-store";
import { useSidebarStore } from "@/stores/use-sidebar-store";
import { useLocation, useNavigate } from "@tanstack/react-router";
-import { Plus } from "lucide-react";
+import { ChatsIcon, ModelsIcon, NewChatIcon, SidebarIcon } from "./nav-icons";
import { twMerge } from "tailwind-merge";
import { v4 as uuidv4 } from "uuid";
-import { ChatsIcon } from "../icons/chats-icon";
-import { ModelsIcon } from "../icons/models-icon";
-import SidebarToggleIcon from "../icons/sidebar-toggle-icon";
import MenuItem from "./menu-item";
import SavedChats from "@/features/chat-history/components/saved-chats";
import Settings from "./settings";
+import { FooterBar } from "../footer-bar";
+import { SidebarResizer } from "./sidebar-resizer";
function LeftBar() {
const location = useLocation();
const navigate = useNavigate();
const createNewChat = useChatStore((s) => s.createNewChat);
const isMobile = useIsMobile();
+ const isFullscreen = useNativeFullscreen();
const isSidebarOpen = useSidebarStore((s) => s.isOpen);
const toggleSidebar = useSidebarStore((s) => s.toggle);
const closeOnMobile = useSidebarStore((s) => s.closeOnMobile);
+ const sidebarWidth = useSidebarStore((s) => s.width);
+ const [resizing, setResizing] = useState(false);
const mainItems = [
...(platformInfo.features.localModelDownloads
@@ -41,8 +45,8 @@ function LeftBar() {
isActive: location.pathname.startsWith("/chats"),
},
{
- icon: Plus,
- title: "New Chat",
+ icon: NewChatIcon,
+ title: "New chat",
onClick: () => {
const newChatId = uuidv4();
createNewChat(newChatId);
@@ -56,57 +60,120 @@ function LeftBar() {
},
];
+ // Narrow windows: the sidebar floats over the content instead of pushing it. Hovering the button
+ // peeks it in, leaving lets it go again after a moment; a click keeps it open.
+ const [peek, setPeek] = useState(false);
+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const holdPeek = () => {
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ closeTimer.current = null;
+ };
+ const releasePeek = () => {
+ holdPeek();
+ closeTimer.current = setTimeout(() => setPeek(false), 220);
+ };
+ useEffect(() => () => holdPeek(), []);
+ useEffect(() => setPeek(false), [location.pathname, isMobile]);
+ const floating = isMobile;
+ const visible = isSidebarOpen || (floating && peek);
+ useEffect(() => {
+ if (!floating || !visible) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== "Escape") return;
+ setPeek(false);
+ closeOnMobile();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [floating, visible, closeOnMobile]);
+
const toggleSidebarButton = (
<button
type="button"
- aria-label={isSidebarOpen ? "Close sidebar" : "Open sidebar"}
- aria-expanded={isSidebarOpen}
+ aria-label={visible ? "Close sidebar" : "Open sidebar"}
+ aria-expanded={visible}
aria-controls="sidebar"
- onClick={toggleSidebar}
+ onClick={() => {
+ if (floating && peek && !isSidebarOpen) {
+ // Already showing from the hover: the click keeps it.
+ setPeek(false);
+ toggleSidebar();
+ return;
+ }
+ setPeek(false);
+ toggleSidebar();
+ }}
+ onPointerEnter={() => {
+ if (!floating || isSidebarOpen) return;
+ holdPeek();
+ setPeek(true);
+ }}
+ onPointerLeave={() => {
+ if (floating && peek) releasePeek();
+ }}
className={twMerge(
- "overlay-button p-1 rounded-lg hover:bg-bg-hover transition-colors duration-300 ease-in-out motion-reduce:transition-none absolute top-[10px]",
- isMobile && platformInfo.features.nativeTitleBar
- ? "left-20 translate-x-0"
- : isMobile
- ? "left-4 translate-x-0"
- : platformInfo.features.nativeTitleBar
- ? "translate-x-[92px]"
- : "left-3 translate-x-0",
+ "overlay-button flex size-8 items-center justify-center rounded-lg hover:bg-bg-hover transition-[background-color,translate] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none absolute",
+ // The same place at every window width. In the Mac app it sits beside the traffic lights;
+ // on the web, and in full screen where macOS hides the lights, it lines up with the sidebar
+ // icons (its icon starts 18px in, like theirs), or 8px in from the content panel's corner when
+ // the sidebar is out of the way.
+ platformInfo.features.nativeTitleBar && !isFullscreen
+ ? "top-2.5 translate-x-[90px]"
+ : !floating && isSidebarOpen
+ ? "top-4 left-3 translate-x-0"
+ : "top-4 left-3 translate-x-1",
)}
>
- <SidebarToggleIcon className="w-6 h-6 text-label-muted" />
+ {/* The sidebar's real state, not a hover peek. In narrow windows, where hovering opens the
+ floating sidebar, the icon always keeps its divider and doesn't change on tap. */}
+ <SidebarIcon size={20} open={floating || isSidebarOpen} className="text-label-title" />
</button>
);
return (
<div
className={twMerge(
- "relative z-30 h-full min-h-0 shrink-0 transition-[width] duration-300 ease-in-out motion-reduce:transition-none",
- !isMobile && isSidebarOpen ? "w-62" : "w-0",
+ "relative z-30 h-full min-h-0 shrink-0 motion-reduce:transition-none",
+ // Follows the pointer while its edge is dragged; glides when toggled.
+ !resizing && "transition-[width] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]",
)}
+ style={{ width: !floating && isSidebarOpen ? sidebarWidth : 0 }}
>
{toggleSidebarButton}
+ {!floating && <SidebarResizer onDraggingChange={setResizing} />}
- {isMobile && isSidebarOpen && (
- <div className="fixed top-0 right-0 bottom-0 left-[280px] bg-black/50 z-40 md:hidden" onClick={closeOnMobile} />
- )}
+ {/* Opened with a click: clicking anywhere else puts it away. No dimming, as in Claude. */}
+ {floating && isSidebarOpen && <div className="fixed inset-0 z-40" onClick={closeOnMobile} aria-hidden />}
<div
id="sidebar"
ref={(element) => {
- if (element) element.inert = !isSidebarOpen;
+ if (element) element.inert = !visible;
}}
- aria-hidden={!isSidebarOpen}
+ aria-hidden={!visible}
+ style={floating ? undefined : { width: sidebarWidth }}
data-tauri-drag-region
+ onPointerEnter={() => {
+ if (floating && peek) holdPeek();
+ }}
+ onPointerLeave={() => {
+ if (floating && peek) releasePeek();
+ }}
className={twMerge(
- "relative min-h-0 bg-bg-sidebar border-[1px] border-cell-border border-b-0 border-t-0 flex flex-col py-3 overflow-clip transition-transform duration-300 ease-in-out motion-reduce:transition-none",
- isMobile ? "fixed top-0 left-0 h-dvh w-[280px] z-50" : "h-full w-62",
- isSidebarOpen ? "translate-x-0" : "-translate-x-full",
+ "relative min-h-0 bg-bg-sidebar flex flex-col pt-2 overflow-clip motion-reduce:transition-none",
+ floating
+ ? "fixed top-2 left-2 bottom-2 w-[280px] z-50 rounded-2xl shadow-[0_0_0_0.5px_var(--color-border-default),0_24px_48px_-12px_rgb(0_0_0/0.28),0_8px_16px_-8px_rgb(0_0_0/0.12)] transition-[translate,opacity]"
+ : "h-full transition-transform",
+ visible
+ ? "translate-x-0 opacity-100 duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]"
+ : floating
+ ? "-translate-x-[calc(100%+1rem)] opacity-0 duration-200 ease-[cubic-bezier(0.32,0.72,0,1)]"
+ : "-translate-x-full duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]",
)}
>
- <div className="flex-1 min-h-0 flex flex-col overflow-clip mt-10">
+ <div className="flex-1 min-h-0 flex flex-col overflow-clip mt-12">
<div className="flex-shrink-0">
- <nav className="flex flex-col gap-2">
+ <nav className="flex flex-col gap-px">
{mainItems.map((item) => (
<MenuItem
key={item.title}
@@ -119,13 +186,28 @@ function LeftBar() {
))}
</nav>
- <div className="mt-3 mb-2 border-t border-cell-border" />
+ <h2 className="px-[18px] pt-5 pb-1.5 text-[14px] font-[500] leading-[1.3] text-label-muted">Recent</h2>
</div>
<SavedChats />
- <div className="shrink-0">
- <Settings />
+ {/* The footer floats over the end of the chat list: the whole block is one fade, the
+ sidebar colour melting to clear upward with a blur that fades the same way, so chats
+ scroll down behind it. The settings button sits 12px in from the left and the bottom,
+ with as much room above it. */}
+ <div className="relative z-10 -mt-14 shrink-0">
+ {/* Two layers: the blur fades out through a mask, the colour on top of it unmasked, so
+ the lower part stays fully solid behind the buttons. The fade starts 40px above the
+ block and turns solid 34px from the bottom, around the button's middle. */}
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 -top-10 backdrop-blur-[3px] [mask-image:linear-gradient(to_top,black_34px,transparent)]"
+ />
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 -top-10 bg-[linear-gradient(to_top,var(--color-bg-sidebar)_34px,transparent)]"
+ />
+ <FooterBar leading={<Settings />} className="relative h-14" />
</div>
</div>
</div>
diff --git a/apps/mirai-gui/client/src/components/left-bar/menu-item.tsx b/apps/mirai-gui/client/src/components/left-bar/menu-item.tsx
index 89ef0aa94..d6b92d0f7 100644
--- a/apps/mirai-gui/client/src/components/left-bar/menu-item.tsx
+++ b/apps/mirai-gui/client/src/components/left-bar/menu-item.tsx
@@ -1,9 +1,10 @@
import { Link } from "@tanstack/react-router";
import { useSidebarStore } from "@/stores/use-sidebar-store";
import { useIsMobile } from "@/hooks/use-media-query";
+import { useState } from "react";
type MenuItemProps = {
- icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
+ icon: React.ComponentType<{ className?: string; size?: number; active?: boolean }>;
title: string;
url?: string;
onClick?: () => void;
@@ -13,6 +14,8 @@ type MenuItemProps = {
function MenuItem({ icon: Icon, title, url, onClick, isActive }: MenuItemProps) {
const isMobile = useIsMobile();
const closeOnMobile = useSidebarStore((s) => s.closeOnMobile);
+ // Mouse hover only: the icon's small motion is feedback for a pointer, not for keyboard focus.
+ const [hovered, setHovered] = useState(false);
const handleClick = () => {
if (onClick) {
@@ -23,12 +26,16 @@ function MenuItem({ icon: Icon, title, url, onClick, isActive }: MenuItemProps)
};
const content = (
- <div className="flex px-2">
+ <div
+ className="flex px-2"
+ onPointerEnter={(e) => e.pointerType === "mouse" && setHovered(true)}
+ onPointerLeave={() => setHovered(false)}
+ >
<div
- className={`flex items-center gap-2 px-2 py-[6px] w-full rounded-md transition-colors duration-150 ${isActive ? "bg-sidebar-chat-selected" : "hover:bg-sidebar-chat-hover"}`}
+ className={`flex h-9 items-center gap-2.5 px-2.5 w-full rounded-[10px] transition-colors duration-150 ease-out ${isActive ? "bg-sidebar-chat-selected" : "hover:bg-sidebar-chat-hover"}`}
>
- <Icon className="w-5 h-5 flex-shrink-0 text-label-muted" />
- <p className="text-[13px] font-[350] leading-[150%] text-label-title truncate min-w-0">{title}</p>
+ <Icon size={20} active={hovered} className="flex-shrink-0 text-label-title" />
+ <p className="text-[14px] font-[450] leading-[1.3] text-label-title truncate min-w-0">{title}</p>
</div>
</div>
);
diff --git a/apps/mirai-gui/client/src/components/left-bar/nav-icons.tsx b/apps/mirai-gui/client/src/components/left-bar/nav-icons.tsx
new file mode 100644
index 000000000..3063c0277
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/left-bar/nav-icons.tsx
@@ -0,0 +1,162 @@
+import { motion, useReducedMotion } from "motion/react";
+import { useEffect, useRef, useState } from "react";
+
+/*
+ * The sidebar's icons, drawn like the rest of the app's icons (components/icons/app-icons: 24px
+ * grid, 2px round strokes) and split into parts so one part can move when the row is hovered. Each motion is a small nudge that
+ * says what the item does, on a spring so leaving halfway simply turns back. Pointer hover only:
+ * keyboard focus doesn't animate, and reduced motion keeps every icon still.
+ */
+
+type NavIconProps = { size?: number; className?: string; active?: boolean };
+
+// Quick and nearly flat: hover feedback, not a show. The bubble gets a touch more bounce.
+const SPRING = { type: "spring", visualDuration: 0.3, bounce: 0.2 } as const;
+const WOBBLE = { type: "spring", visualDuration: 0.32, bounce: 0.35 } as const;
+const TURN = { type: "spring", visualDuration: 0.45, bounce: 0.15 } as const;
+
+function Svg({ size = 20, className, children }: { size?: number; className?: string; children: React.ReactNode }) {
+ return (
+ <svg
+ aria-hidden
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ className={className}
+ style={{ overflow: "visible" }}
+ >
+ {children}
+ </svg>
+ );
+}
+
+/** Models: a rounded square that turns a little about its centre, on the same spring and by the same
+ * angle as the New chat pencil. */
+export function ModelsIcon({ size, className, active = false }: NavIconProps) {
+ const still = useReducedMotion();
+ const on = active && !still;
+ return (
+ <Svg size={size} className={className}>
+ <motion.path
+ d="M17 4H7C5.34315 4 4 5.34315 4 7V17C4 18.6569 5.34315 20 7 20H17C18.6569 20 20 18.6569 20 17V7C20 5.34315 18.6569 4 17 4Z"
+ strokeLinejoin="round"
+ style={{ originX: 0.5, originY: 0.5 }}
+ initial={false}
+ animate={{ rotate: on ? -9 : 0 }}
+ transition={SPRING}
+ />
+ </Svg>
+ );
+}
+
+/** Chats: a round bubble with a square corner for its tail (the Figma "Icons / Chat" shape, drawn
+ * as a filled outline), which tips up from that corner, as if it just popped in. */
+export function ChatsIcon({ size, className, active = false }: NavIconProps) {
+ const still = useReducedMotion();
+ const on = active && !still;
+ return (
+ <Svg size={size} className={className}>
+ <motion.path
+ d="M12.375 1.875C9.78998 1.87773 7.31161 2.90584 5.48372 4.73372C3.65584 6.56161 2.62773 9.03998 2.625 11.625V19.5C2.625 19.9973 2.82254 20.4742 3.17417 20.8258C3.52581 21.1775 4.00272 21.375 4.5 21.375H12.375C14.9609 21.375 17.4408 20.3478 19.2693 18.5193C21.0978 16.6908 22.125 14.2109 22.125 11.625C22.125 9.03914 21.0978 6.55919 19.2693 4.73071C17.4408 2.90223 14.9609 1.875 12.375 1.875ZM12.375 19.125H4.875V11.625C4.875 10.1416 5.31487 8.69159 6.13898 7.45822C6.96309 6.22485 8.13443 5.26356 9.50487 4.6959C10.8753 4.12825 12.3833 3.97972 13.8382 4.26911C15.293 4.5585 16.6294 5.27281 17.6783 6.3217C18.7272 7.37059 19.4415 8.70697 19.7309 10.1618C20.0203 11.6167 19.8718 13.1247 19.3041 14.4951C18.7364 15.8656 17.7751 17.0369 16.5418 17.861C15.3084 18.6851 13.8584 19.125 12.375 19.125Z"
+ fill="currentColor"
+ stroke="none"
+ style={{ originX: 0.05, originY: 0.95 }}
+ initial={false}
+ animate={{ rotate: on ? -7 : 0, scale: on ? 1.04 : 1 }}
+ transition={WOBBLE}
+ />
+ </Svg>
+ );
+}
+
+/** New chat: the pencil tilts on its tip, as if to start writing. */
+export function NewChatIcon({ size, className, active = false }: NavIconProps) {
+ const still = useReducedMotion();
+ const on = active && !still;
+ return (
+ <Svg size={size} className={className}>
+ <motion.path
+ d="M19.6213 4.12135L19.8787 4.37872C21.0503 5.55029 21.0503 7.44978 19.8787 8.62136L8.37868 20.1214C7.81607 20.684 7.05301 21 6.25736 21H3V17.7427C3 16.947 3.31607 16.184 3.87868 15.6214L15.3787 4.12136C16.5503 2.94978 18.4497 2.94978 19.6213 4.12135Z"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ style={{ originX: 0, originY: 1 }}
+ initial={false}
+ animate={{ rotate: on ? -9 : 0 }}
+ transition={SPRING}
+ />
+ <path d="M14 21H21" strokeLinecap="round" />
+ </Svg>
+ );
+}
+
+/**
+ * Settings: a rounded six-lobed gear (the Figma settings icon) that turns one notch. It has six
+ * lobes, so 60° lands on the same shape; each hover turns it further the same way, like a dial,
+ * rather than winding back.
+ */
+export function SettingsIcon({ size, className, active = false }: NavIconProps) {
+ const still = useReducedMotion();
+ const [turns, setTurns] = useState(0);
+ const wasActive = useRef(active);
+ useEffect(() => {
+ if (active && !wasActive.current && !still) setTurns((n) => n + 1);
+ wasActive.current = active;
+ }, [active, still]);
+ return (
+ <Svg size={size} className={className}>
+ <motion.g
+ style={{ originX: 0.5, originY: 0.5 }}
+ initial={false}
+ animate={{ rotate: turns * 60 }}
+ transition={TURN}
+ >
+ <path
+ d="M9.671 4.136C9.7261 3.55634 9.99533 3.01804 10.4261 2.62628C10.8569 2.23451 11.4182 2.01743 12.0005 2.01743C12.5828 2.01743 13.1441 2.23451 13.5749 2.62628C14.0057 3.01804 14.2749 3.55634 14.33 4.136C14.3631 4.51045 14.486 4.87142 14.6881 5.18834C14.8903 5.50526 15.1659 5.76881 15.4915 5.95668C15.8171 6.14454 16.1831 6.2512 16.5587 6.26762C16.9343 6.28404 17.3082 6.20973 17.649 6.051C18.1781 5.81078 18.7777 5.77602 19.331 5.95348C19.8843 6.13095 20.3518 6.50795 20.6425 7.0111C20.9332 7.51426 21.0263 8.10757 20.9036 8.67557C20.781 9.24357 20.4514 9.74561 19.979 10.084C19.6714 10.2998 19.4203 10.5866 19.2469 10.92C19.0736 11.2534 18.983 11.6237 18.983 11.9995C18.983 12.3753 19.0736 12.7456 19.2469 13.079C19.4203 13.4124 19.6714 13.6992 19.979 13.915C20.4514 14.2534 20.781 14.7554 20.9036 15.3234C21.0263 15.8914 20.9332 16.4847 20.6425 16.9879C20.3518 17.491 19.8843 17.868 19.331 18.0455C18.7777 18.223 18.1781 18.1882 17.649 17.948C17.3082 17.7893 16.9343 17.715 16.5587 17.7314C16.1831 17.7478 15.8171 17.8545 15.4915 18.0423C15.1659 18.2302 14.8903 18.4937 14.6881 18.8107C14.486 19.1276 14.3631 19.4885 14.33 19.863C14.2749 20.4427 14.0057 20.981 13.5749 21.3727C13.1441 21.7645 12.5828 21.9816 12.0005 21.9816C11.4182 21.9816 10.8569 21.7645 10.4261 21.3727C9.99533 20.981 9.7261 20.4427 9.671 19.863C9.63794 19.4884 9.5151 19.1273 9.31286 18.8103C9.11063 18.4932 8.83497 18.2296 8.50923 18.0417C8.18349 17.8538 7.81727 17.7472 7.44158 17.7309C7.06589 17.7146 6.6918 17.7891 6.351 17.948C5.82189 18.1882 5.22233 18.223 4.669 18.0455C4.11567 17.868 3.64817 17.491 3.35748 16.9879C3.06679 16.4847 2.97371 15.8914 3.09636 15.3234C3.219 14.7554 3.5486 14.2534 4.021 13.915C4.32862 13.6992 4.57973 13.4124 4.75309 13.079C4.92645 12.7456 5.01695 12.3753 5.01695 11.9995C5.01695 11.6237 4.92645 11.2534 4.75309 10.92C4.57973 10.5866 4.32862 10.2998 4.021 10.084C3.54926 9.74544 3.22025 9.24359 3.0979 8.67598C2.97555 8.10837 3.06861 7.51554 3.35898 7.01271C3.64936 6.50988 4.11631 6.13298 4.66909 5.95524C5.22187 5.7775 5.82098 5.81163 6.35 6.051C6.69076 6.20973 7.06474 6.28404 7.4403 6.26762C7.81586 6.2512 8.18193 6.14454 8.50754 5.95668C8.83314 5.76881 9.10869 5.50526 9.31086 5.18834C9.51304 4.87142 9.63588 4.51045 9.669 4.136"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M12 15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15Z"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </motion.g>
+ </Svg>
+ );
+}
+
+/**
+ * Sidebar toggle. The divider shows where the sidebar edge is: there when the sidebar is open, slid
+ * into the left edge and faded when it's closed. It moves only when the sidebar opens or closes,
+ * never on hover. Under reduced motion it changes without sliding.
+ */
+export function SidebarIcon({ size, className, open }: Omit<NavIconProps, "active"> & { open: boolean }) {
+ const still = useReducedMotion();
+ const shown = open;
+ // Open, the divider stands a third of the way in; closed, it slides into the frame's left edge.
+ const x = shown ? 9 : 3.36;
+ return (
+ <Svg size={size} className={className}>
+ {/* The Figma sidebar icon, scaled from its 20px grid; its frame is drawn a touch lighter than
+ the divider, as there. */}
+ <rect x="3.36" y="5.16" width="17.28" height="13.68" rx="2.64" strokeWidth={1.92} />
+ <motion.path
+ strokeLinejoin="round"
+ initial={false}
+ animate={{ d: `M${x} 5V19`, opacity: shown ? 1 : 0 }}
+ transition={
+ still
+ ? { duration: 0 }
+ : {
+ d: SPRING,
+ // Gone by the time it reaches the edge, back in as soon as it leaves it.
+ opacity: shown ? { duration: 0.12, ease: "easeOut" } : { duration: 0.2, ease: "easeIn", delay: 0.06 },
+ }
+ }
+ />
+ </Svg>
+ );
+}
diff --git a/apps/mirai-gui/client/src/components/left-bar/settings.tsx b/apps/mirai-gui/client/src/components/left-bar/settings.tsx
index cf0f3360d..ca11112c5 100644
--- a/apps/mirai-gui/client/src/components/left-bar/settings.tsx
+++ b/apps/mirai-gui/client/src/components/left-bar/settings.tsx
@@ -1,26 +1,22 @@
import { Link } from "@tanstack/react-router";
-import { Settings as SettingsIcon } from "lucide-react";
+import { useState } from "react";
+import { SettingsIcon } from "./nav-icons";
+/** Settings as a gear in the sidebar's bottom-left corner, lined up with the nav icons above. */
function Settings() {
+ const [hovered, setHovered] = useState(false);
return (
- <div>
- <div className="border-t border-cell-border mb-2" />
- <Link
- to="/settings"
- search={{ tab: "general" }}
- className="flex px-2"
- activeOptions={{ includeSearch: false, exact: true }}
- >
- {({ isActive }) => (
- <div
- className={`flex items-center gap-2 px-2 py-[6px] w-full rounded-md transition-colors duration-150 ${isActive ? "bg-sidebar-chat-selected" : "hover:bg-sidebar-chat-hover"}`}
- >
- <SettingsIcon aria-hidden="true" className="size-5 shrink-0 text-label-muted" />
- <span className="text-[13px] font-[350] leading-[150%] text-label-title">Settings</span>
- </div>
- )}
- </Link>
- </div>
+ <Link
+ to="/settings"
+ search={{ tab: "general" }}
+ aria-label="Settings"
+ activeOptions={{ includeSearch: false, exact: true }}
+ onPointerEnter={(e) => e.pointerType === "mouse" && setHovered(true)}
+ onPointerLeave={() => setHovered(false)}
+ className="flex size-8 shrink-0 items-center justify-center rounded-[10px] text-label-title outline-hidden transition-colors duration-150 ease-out hover:bg-sidebar-chat-hover focus-visible:shadow-focus data-[status=active]:bg-sidebar-chat-selected"
+ >
+ <SettingsIcon size={20} active={hovered} />
+ </Link>
);
}
diff --git a/apps/mirai-gui/client/src/components/left-bar/sidebar-resizer.tsx b/apps/mirai-gui/client/src/components/left-bar/sidebar-resizer.tsx
new file mode 100644
index 000000000..1d2bdfdf1
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/left-bar/sidebar-resizer.tsx
@@ -0,0 +1,104 @@
+import { type KeyboardEvent, type PointerEvent, useRef, useState } from "react";
+import { twMerge } from "tailwind-merge";
+import {
+ SIDEBAR_DEFAULT_WIDTH,
+ SIDEBAR_MAX_WIDTH,
+ SIDEBAR_MIN_WIDTH,
+ useSidebarStore,
+} from "@/stores/use-sidebar-store";
+
+// Dragged this far past the minimum width, the sidebar lets go and hides; dragged back out from the
+// edge, it opens again. As in Claude and Codex.
+const COLLAPSE_BELOW = SIDEBAR_MIN_WIDTH - 60;
+const KEY_STEP = 16;
+
+/**
+ * The sidebar's right edge, as a handle: drag to resize, drag fully left to hide, drag out from the
+ * window edge to bring it back, double-click to reset the width. Also a focusable separator: the
+ * arrow keys resize it. A thin line shows where it is while hovered or held.
+ */
+export function SidebarResizer({ onDraggingChange }: { onDraggingChange: (dragging: boolean) => void }) {
+ const isOpen = useSidebarStore((s) => s.isOpen);
+ const width = useSidebarStore((s) => s.width);
+ const setOpen = useSidebarStore((s) => s.setOpen);
+ const setWidth = useSidebarStore((s) => s.setWidth);
+ const drag = useRef<{ startX: number; startWidth: number } | null>(null);
+ const [active, setActive] = useState(false);
+
+ const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ drag.current = { startX: event.clientX, startWidth: isOpen ? width : 0 };
+ setActive(true);
+ onDraggingChange(true);
+ document.body.style.cursor = "col-resize";
+ };
+
+ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
+ if (!drag.current) return;
+ const next = drag.current.startWidth + (event.clientX - drag.current.startX);
+ if (next < COLLAPSE_BELOW) {
+ if (isOpen) setOpen(false);
+ return;
+ }
+ if (!isOpen) setOpen(true);
+ setWidth(next);
+ };
+
+ const endDrag = (event: PointerEvent<HTMLDivElement>) => {
+ if (!drag.current) return;
+ drag.current = null;
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ setActive(false);
+ onDraggingChange(false);
+ document.body.style.cursor = "";
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
+ event.preventDefault();
+ const delta = event.key === "ArrowRight" ? KEY_STEP : -KEY_STEP;
+ if (!isOpen) {
+ if (delta > 0) setOpen(true);
+ return;
+ }
+ if (width + delta < SIDEBAR_MIN_WIDTH) setOpen(false);
+ else setWidth(width + delta);
+ };
+
+ return (
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ aria-label="Resize sidebar"
+ aria-valuemin={0}
+ aria-valuemax={SIDEBAR_MAX_WIDTH}
+ aria-valuenow={isOpen ? width : 0}
+ tabIndex={0}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={endDrag}
+ onPointerCancel={endDrag}
+ onDoubleClick={() => {
+ setOpen(true);
+ setWidth(SIDEBAR_DEFAULT_WIDTH);
+ }}
+ onKeyDown={onKeyDown}
+ className="group absolute inset-y-0 -right-1.5 z-40 flex w-3 cursor-col-resize justify-center outline-hidden touch-none"
+ >
+ {/* Shown after a short rest on hover (so passing the edge doesn't flash it), at once while held
+ or focused from the keyboard. Stops short of the ends, clear of the content panel's rounded
+ corners. */}
+ <span
+ aria-hidden
+ className={twMerge(
+ "my-6 w-0.5 rounded-full bg-blue opacity-0 transition-opacity duration-150 ease-out group-hover:opacity-100 group-hover:delay-150 group-focus-visible:opacity-100",
+ active && "opacity-100 delay-0",
+ )}
+ />
+ </div>
+ );
+}
diff --git a/apps/mirai-gui/client/src/components/loader.tsx b/apps/mirai-gui/client/src/components/loader.tsx
index 8b3d62a5d..2ade31b31 100644
--- a/apps/mirai-gui/client/src/components/loader.tsx
+++ b/apps/mirai-gui/client/src/components/loader.tsx
@@ -3,6 +3,7 @@ import { useRive } from "@rive-app/react-canvas";
import React, { type HTMLAttributes } from "react";
import { twMerge } from "tailwind-merge";
import { TextShimmer } from "./ui/text-shimmer";
+import { UzuCat } from "./uzu-cat";
type LoaderProps = {
showText?: boolean;
@@ -40,7 +41,7 @@ export const Loader: React.FC<LoaderProps> = ({
}) => {
return (
<div className={twMerge("flex items-center justify-center gap-2", className)}>
- <LoaderIcon width={iconWidth} height={iconHeight} />
+ <UzuCat state="loading" size={Math.max(16, iconWidth, iconHeight)} className="text-text-primary" />
{showText && text && (
<div className="flex items-baseline gap-[2px]">
<TextShimmer
diff --git a/apps/mirai-gui/client/src/components/model-name.tsx b/apps/mirai-gui/client/src/components/model-name.tsx
new file mode 100644
index 000000000..aecb207ca
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/model-name.tsx
@@ -0,0 +1,37 @@
+import { twMerge } from "tailwind-merge";
+
+// Catalog names carry the quantization as a long suffix ("Qwen3.5 2B Mirai Medium Quantization").
+// The model is the first part; the variant is shortened to "Mirai M" and set quietly after it.
+const VARIANT_SUFFIX = /^(.+?)\s+Mirai\s+(\S+)(?:\s+Quantization)?$/i;
+
+export function splitModelName(name: string): { base: string; variant: string | null } {
+ const match = VARIANT_SUFFIX.exec(name.trim());
+ return match?.[1] && match[2]
+ ? { base: match[1], variant: `Mirai ${match[2].charAt(0).toUpperCase()}` }
+ : { base: name, variant: null };
+}
+
+/** A model's name with its quantization, shortened, as muted text after it. */
+export function ModelName({ name, className }: { name: string; className?: string }) {
+ const { base, variant } = splitModelName(name);
+ return (
+ <span className={twMerge("flex min-w-0 items-baseline gap-1.5", className)} title={name}>
+ <span className="min-w-0 truncate">{base}</span>
+ {variant ? <span className="shrink-0 whitespace-nowrap text-text-muted">{variant}</span> : null}
+ </span>
+ );
+}
+
+/**
+ * The same name set inline, for a sentence ("Couldn't download Qwen3.5 2B Mirai M"): wraps with the
+ * text around it instead of truncating, the variant still muted.
+ */
+export function InlineModelName({ name }: { name: string }) {
+ const { base, variant } = splitModelName(name);
+ return (
+ <>
+ {base}
+ {variant ? <span className="whitespace-nowrap text-text-muted"> {variant}</span> : null}
+ </>
+ );
+}
diff --git a/apps/mirai-gui/client/src/components/page-title-bar.tsx b/apps/mirai-gui/client/src/components/page-title-bar.tsx
new file mode 100644
index 000000000..9665bce95
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/page-title-bar.tsx
@@ -0,0 +1,81 @@
+import { type ReactNode, type Ref, useLayoutEffect, useRef, useState } from "react";
+import { twMerge } from "tailwind-merge";
+import { useIsMobile } from "@/hooks/use-media-query";
+
+/**
+ * The title row at the top of a page. Content passes under it through a fade: the page colour at
+ * the top melting to clear, with a blur that fades out the same way, so nothing is cut off at a hard
+ * edge. The fade stops short of the right edge, where macOS draws its overlay scrollbar, so the
+ * scrollbar stays visible over it. Give it to a PageScroller as its header.
+ */
+export function PageTitleBar({ children, className }: { children: ReactNode; className?: string }) {
+ // Narrow windows have no sidebar beside the page: the sidebar button sits over the page's top-left
+ // corner (beside the traffic lights in the Mac app), so the title starts lower, clear of it.
+ const narrow = useIsMobile();
+ return (
+ // Only the row itself takes the pointer: the strip around it belongs to the scroller below, so its
+ // scrollbar can still be grabbed at the top.
+ <div data-tauri-drag-region="deep" className="pointer-events-none relative isolate">
+ <div
+ aria-hidden
+ className="absolute left-0 right-3 top-0 -bottom-6 -z-10 bg-linear-to-b from-background from-45% to-transparent backdrop-blur-md [mask-image:linear-gradient(to_bottom,black_55%,transparent)]"
+ />
+ <div
+ className={twMerge(
+ "pointer-events-auto flex min-h-[72px] items-center gap-3 px-5 pt-7 pb-3 w-full max-w-[calc(var(--chat-width)+2.5rem)] mx-auto min-w-0",
+ narrow && "pt-14",
+ className,
+ )}
+ >
+ {children}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * A page that scrolls under a fixed header. The header sits over the scroller rather than inside it,
+ * so the rubber-band bounce at either end moves only the content and the header never leaves its
+ * place. The scroller is padded by the header's height, for the first content and for focus that
+ * scrolls into view.
+ */
+export function PageScroller({
+ header,
+ children,
+ className,
+ scrollRef,
+}: {
+ header: ReactNode;
+ children: ReactNode;
+ className?: string;
+ scrollRef?: Ref<HTMLDivElement>;
+}) {
+ const headerRef = useRef<HTMLDivElement>(null);
+ const [headerHeight, setHeaderHeight] = useState(72);
+
+ useLayoutEffect(() => {
+ const element = headerRef.current;
+ if (!element) return;
+ const update = () => setHeaderHeight(element.offsetHeight);
+ update();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(update);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
+ return (
+ <div className="relative h-full min-h-0 w-full flex-1">
+ <div
+ ref={scrollRef}
+ className={twMerge("h-full w-full overflow-y-auto overscroll-y-contain page-scrollbar", className)}
+ style={{ paddingTop: headerHeight, scrollPaddingTop: headerHeight }}
+ >
+ {children}
+ </div>
+ <div ref={headerRef} className="absolute inset-x-0 top-0 z-20">
+ {header}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/mirai-gui/client/src/components/ui/checkbox/index.tsx b/apps/mirai-gui/client/src/components/ui/checkbox/index.tsx
index 8dc9e3e3d..296e90bdc 100644
--- a/apps/mirai-gui/client/src/components/ui/checkbox/index.tsx
+++ b/apps/mirai-gui/client/src/components/ui/checkbox/index.tsx
@@ -1,6 +1,6 @@
import { twMerge } from "tailwind-merge";
import { DataInteractive } from "@headlessui/react";
-import { IconCheckmark } from "../../icons/checkmark-icon";
+import { CheckmarkIcon } from "../../icons/checkmark-icon";
import { CHECKBOX_SIZE, CHECKED_BG, CHECKED_BORDER, FOCUS_RING, UNCHECKED_BORDER } from "./constants";
import type { CheckboxProps } from "./types";
@@ -36,7 +36,7 @@ export function Checkbox({
aria-label={ariaLabel}
/>
</DataInteractive>
- <IconCheckmark
+ <CheckmarkIcon
strokeWidth={2.5}
size={sizeConfig.icon}
className={twMerge(
diff --git a/apps/mirai-gui/client/src/components/ui/copy-button.tsx b/apps/mirai-gui/client/src/components/ui/copy-button.tsx
index 4e12bc332..01d1e9e33 100644
--- a/apps/mirai-gui/client/src/components/ui/copy-button.tsx
+++ b/apps/mirai-gui/client/src/components/ui/copy-button.tsx
@@ -1,8 +1,7 @@
import { IconButton } from "./icon-button";
import { useToast } from "./toast/use-toast";
-import { Transition } from "@headlessui/react";
-import { Check, Copy } from "lucide-react";
-import { Fragment, useState } from "react";
+import { CircleCheckIcon, CopyIcon } from "@/components/icons/app-icons";
+import { useEffect, useRef, useState } from "react";
import { twMerge } from "tailwind-merge";
type CopyButtonProps = {
@@ -10,51 +9,56 @@ type CopyButtonProps = {
className?: string;
};
-const COPIED_FEEDBACK_MS = 1000;
+const COPIED_FEEDBACK_MS = 1200;
+// The same plain button as the other actions under an answer. `active:scale-100` cancels the shared
+// icon button's own press shrink, which made the row jump on a tap.
const BUTTON_CLASSES =
- "relative min-w-8 min-h-8 flex items-center justify-center p-[6px] rounded-[5px] text-label-muted hover:bg-card-hover hover:text-label-title active:scale-100";
+ "relative size-8 flex items-center justify-center p-0 rounded-lg text-label-muted transition-colors duration-150 ease-out hover:bg-bg-hover hover:text-label-title active:scale-100";
+
+// Both icons sit in the same spot at full size and cross-fade, with 2px of blur bridging the two so
+// the eye reads one icon changing rather than two objects trading places. CSS transitions, so a
+// second click mid-swap simply turns it back. Each layer keeps its own GPU layer and rests at
+// blur(0px), never `none`: WebKit drops the layer when the filter goes away and the icon snaps by a
+// subpixel, which read as a jump at the end of the swap.
+const LAYER =
+ "absolute inset-0 flex items-center justify-center will-change-[opacity,filter] transition-[opacity,filter] duration-200 ease-out motion-reduce:transition-none";
+const SHOWN = "opacity-100 [filter:blur(0px)]";
+const HIDDEN = "opacity-0 [filter:blur(2px)]";
export function CopyButton({ onCopy, className }: CopyButtonProps) {
const [copied, setCopied] = useState(false);
const toast = useToast();
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(() => () => clearTimeout(timer.current ?? undefined), []);
const handleCopy = async () => {
try {
await onCopy();
setCopied(true);
- setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS);
+ clearTimeout(timer.current ?? undefined);
+ timer.current = setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS);
} catch {
toast.error("Copy failed. Please try again.");
}
};
return (
- <IconButton aria-label="Copy" onClick={handleCopy} className={twMerge(BUTTON_CLASSES, className)}>
- <Transition
- as={Fragment}
- show={!copied}
- enter="transition-opacity duration-500"
- enterFrom="opacity-0"
- enterTo="opacity-100"
- leave="transition-opacity duration-500"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
- >
- <Copy className="w-[14px] h-[14px] absolute" />
- </Transition>
- <Transition
- as={Fragment}
- show={copied}
- enter="transition-opacity duration-500"
- enterFrom="opacity-0"
- enterTo="opacity-100"
- leave="transition-opacity duration-500"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
- >
- <Check className="w-[14px] h-[14px] absolute" />
- </Transition>
+ <IconButton
+ aria-label={copied ? "Copied" : "Copy"}
+ onClick={handleCopy}
+ className={twMerge(BUTTON_CLASSES, className)}
+ >
+ <span className="relative block size-4">
+ <span aria-hidden className={twMerge(LAYER, copied ? HIDDEN : SHOWN)}>
+ <CopyIcon size={16} />
+ </span>
+ {/* The check keeps the bright, hovered colour while it shows, whether or not the pointer
+ is still on the button. */}
+ <span aria-hidden className={twMerge(LAYER, "text-label-title", copied ? SHOWN : HIDDEN)}>
+ <CircleCheckIcon size={16} />
+ </span>
+ </span>
</IconButton>
);
}
diff --git a/apps/mirai-gui/client/src/components/ui/group-button.tsx b/apps/mirai-gui/client/src/components/ui/group-button.tsx
index 2e718b88b..c41498e1b 100644
--- a/apps/mirai-gui/client/src/components/ui/group-button.tsx
+++ b/apps/mirai-gui/client/src/components/ui/group-button.tsx
@@ -12,30 +12,21 @@ type SegmentProps = {
disabled?: boolean;
children: React.ReactNode;
ariaLabel?: string;
- leftDivider?: boolean;
+ /** A square segment holding just an icon. */
+ icon?: boolean;
};
+// The same filled pill track as the search field and the segmented control beside it; segments are
+// pills on it that only show a fill under the pointer.
const Base: React.FC<GroupButtonProps> = ({ className, children }) => {
return (
- <div
- className={twMerge(
- "h-8 flex items-center rounded-lg overflow-clip border border-cell-border bg-transparent",
- className,
- )}
- >
+ <div className={twMerge("inline-flex h-8 items-center gap-0.5 rounded-full bg-control-fill p-0.5", className)}>
{children}
</div>
);
};
-const Segment: React.FC<SegmentProps> = ({
- className,
- onClick,
- disabled = false,
- children,
- ariaLabel,
- leftDivider = false,
-}) => {
+const Segment: React.FC<SegmentProps> = ({ className, onClick, disabled = false, children, ariaLabel, icon }) => {
return (
<button
type="button"
@@ -46,10 +37,10 @@ const Segment: React.FC<SegmentProps> = ({
}}
disabled={disabled}
className={twMerge(
- "px-2 h-8 flex items-center gap-2 transition-colors select-none",
- "disabled:opacity-50 disabled:cursor-not-allowed",
- "hover:bg-card-hover",
- leftDivider && "border-l-[0.5px] border-button-border",
+ "flex h-7 items-center gap-2 rounded-full text-[13px] font-[450] text-text-muted outline-hidden select-none",
+ "transition-[background-color,color] duration-150 ease-out hover:bg-control-fill-hover hover:text-text-primary focus-visible:shadow-focus",
+ "disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent disabled:hover:text-text-muted",
+ icon ? "w-7 justify-center" : "pl-2 pr-3",
className,
)}
>
diff --git a/apps/mirai-gui/client/src/components/ui/icon-action.tsx b/apps/mirai-gui/client/src/components/ui/icon-action.tsx
index b08746f7a..facb54f42 100644
--- a/apps/mirai-gui/client/src/components/ui/icon-action.tsx
+++ b/apps/mirai-gui/client/src/components/ui/icon-action.tsx
@@ -24,7 +24,7 @@ export function IconAction({ label, icon, onClick, className }: IconActionProps)
onClick={handleClick}
className={
className ??
- "size-7 rounded-md bg-transparent text-text-muted hover:bg-border-default hover:text-text-primary active:bg-border-default"
+ "size-7 rounded-full bg-transparent text-text-muted hover:bg-border-default hover:text-text-primary active:bg-border-default"
}
/>
);
diff --git a/apps/mirai-gui/client/src/components/ui/modal/constants.ts b/apps/mirai-gui/client/src/components/ui/modal/constants.ts
new file mode 100644
index 000000000..a61d6ebf4
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/ui/modal/constants.ts
@@ -0,0 +1,10 @@
+// Buttons on a floating surface (dialogs, the update notice): full pills like the composer's, with
+// the quiet choice as a translucent fill so it reads on the lifted surface in both themes.
+export const SURFACE_BUTTON_CLASSNAME = "rounded-full h-9 px-4 text-[14px] font-[500] active:scale-[0.96]";
+export const SURFACE_BUTTON_SMALL_CLASSNAME = "rounded-full h-8 px-3.5 text-[13px] font-[500] active:scale-[0.96]";
+export const SURFACE_SOFT_BUTTON_CLASSNAME =
+ "bg-black/[0.05] text-text-primary shadow-none hover:bg-black/[0.08] hover:shadow-none active:bg-black/[0.1] dark:bg-white/[0.08] dark:hover:bg-white/[0.12] dark:active:bg-white/[0.14]";
+
+// The round close button in a surface's corner, with a hit area a little larger than it looks.
+export const SURFACE_CLOSE_CLASSNAME =
+ "relative shrink-0 flex items-center justify-center size-7 rounded-full text-text-muted outline-hidden cursor-pointer transition-colors duration-150 ease-out hover:bg-black/[0.06] hover:text-text-primary dark:hover:bg-white/[0.08] data-[focus]:shadow-focus focus-visible:shadow-focus before:absolute before:-inset-1.5";
diff --git a/apps/mirai-gui/client/src/components/ui/modal/index.tsx b/apps/mirai-gui/client/src/components/ui/modal/index.tsx
index 3981af91b..4feb0e4d4 100644
--- a/apps/mirai-gui/client/src/components/ui/modal/index.tsx
+++ b/apps/mirai-gui/client/src/components/ui/modal/index.tsx
@@ -1,4 +1,4 @@
-import { X } from "lucide-react";
+import { XIcon } from "@/components/icons/app-icons";
import {
Button as HeadlessButton,
Dialog,
@@ -11,6 +11,7 @@ import { Fragment } from "react";
import { twMerge } from "tailwind-merge";
import { Button } from "../button";
import { Text } from "../typography";
+import { SURFACE_BUTTON_CLASSNAME, SURFACE_CLOSE_CLASSNAME, SURFACE_SOFT_BUTTON_CLASSNAME } from "./constants";
import type { ModalProps } from "./types";
const SPRING_ENTER =
@@ -50,7 +51,7 @@ export function Modal(props: ModalProps) {
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
- <div className="fixed inset-0 bg-overlay" />
+ <div className="fixed inset-0 bg-overlay motion-reduce:transition-none" />
</TransitionChild>
<div className="fixed inset-0 flex items-center justify-center p-4">
@@ -63,15 +64,17 @@ export function Modal(props: ModalProps) {
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-[0.96]"
>
- <DialogPanel
- className={twMerge(
- "rounded-lg bg-surface-elevated border border-border-default p-4 text-text-primary",
- "w-[468px]",
- )}
- >
+ {/* The same lifted surface as menus and toasts, so a dialog is one more layer of the
+ app rather than a different kind of window. */}
+ <DialogPanel className="w-[440px] max-w-full rounded-2xl bg-surface-popover shadow-popover p-5 text-text-primary motion-reduce:transition-none">
<div className="flex items-start justify-between gap-3">
- <DialogTitle className="flex-1 min-w-0">
- <Text as="span" color="primary" opticalSize={14} className="text-[18px] font-[450] leading-[28px]">
+ <DialogTitle className="flex-1 min-w-0 pt-0.5">
+ <Text
+ as="span"
+ color="primary"
+ opticalSize={16}
+ className="block text-[16px] font-[500] leading-[1.35] text-balance"
+ >
{title}
</Text>
</DialogTitle>
@@ -79,25 +82,41 @@ export function Modal(props: ModalProps) {
type="button"
aria-label="Close"
onClick={onClose}
- className="shrink-0 flex items-center justify-center size-7 rounded-md text-text-muted hover:text-text-primary hover:bg-tertiary-hover transition-colors duration-150 ease-out outline-hidden data-[focus]:shadow-focus cursor-pointer"
+ className={twMerge(SURFACE_CLOSE_CLASSNAME, "-mr-1 -mt-0.5")}
>
- <X size={16} />
+ <XIcon size={18} aria-hidden />
</HeadlessButton>
</div>
{description && (
- <Text as="p" color="muted" opticalSize={20} className="mt-1.5 text-[15px] font-[450] leading-[1.6]">
+ <Text
+ as="p"
+ color="secondary"
+ opticalSize={14}
+ className="mt-1.5 text-[14px] font-[400] leading-[1.5] text-pretty [overflow-wrap:anywhere]"
+ >
{description}
</Text>
)}
- {children && <div className="mt-5">{children}</div>}
+ {children && <div className="mt-4">{children}</div>}
<div className="mt-6 flex justify-end gap-2 flex-wrap">
- <Button kind="secondary" size="sm" onClick={handleSecondary}>
+ <Button
+ kind="secondary"
+ size="sm"
+ onClick={handleSecondary}
+ className={twMerge(SURFACE_BUTTON_CLASSNAME, SURFACE_SOFT_BUTTON_CLASSNAME)}
+ >
{secondaryLabel}
</Button>
{hasPrimary && (
- <Button kind={primaryKind} size="sm" onClick={handlePrimary} disabled={primaryDisabled}>
+ <Button
+ kind={primaryKind}
+ size="sm"
+ onClick={handlePrimary}
+ disabled={primaryDisabled}
+ className={SURFACE_BUTTON_CLASSNAME}
+ >
{primaryLabel}
</Button>
)}
diff --git a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/index.tsx b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/index.tsx
index c46aab88c..e60ed99d2 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/index.tsx
+++ b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/index.tsx
@@ -3,7 +3,14 @@ import { cloneElement, useContext, useEffect, useId, useRef } from "react";
import { HoverPopoverContext } from "./provider";
import type { HoverPopoverProps } from "./types";
-export function HoverPopover({ items, trigger, side = "bottom", align = "end" }: HoverPopoverProps) {
+export function HoverPopover({
+ items,
+ footerItems,
+ maxVisibleItems,
+ trigger,
+ side = "bottom",
+ align = "end",
+}: HoverPopoverProps) {
const context = useContext(HoverPopoverContext);
if (!context) throw new Error("HoverPopover must be rendered inside a HoverPopoverProvider.");
const { show, hide, contains } = context;
@@ -15,7 +22,8 @@ export function HoverPopover({ items, trigger, side = "bottom", align = "end" }:
useEffect(() => () => hide(id), [hide, id]);
const open = (options?: { focusPanel?: boolean }) => {
- if (triggerNodeRef.current) show({ id, triggerNode: triggerNodeRef.current, items, side, align }, options);
+ if (triggerNodeRef.current)
+ show({ id, triggerNode: triggerNodeRef.current, items, footerItems, maxVisibleItems, side, align }, options);
};
const mergedTrigger = cloneElement(trigger, {
@@ -23,6 +31,14 @@ export function HoverPopover({ items, trigger, side = "bottom", align = "end" }:
triggerNodeRef.current = node;
},
"aria-haspopup": "menu",
+ // The trigger can do its own thing on click (Regenerate reruns the answer); the menu then
+ // closes, since that choice is made.
+ onClick: (event: MouseEvent<HTMLButtonElement>) => {
+ const own = (trigger.props as { onClick?: (event: MouseEvent<HTMLButtonElement>) => void }).onClick;
+ if (!own) return;
+ own(event);
+ hide(id);
+ },
onMouseEnter: () => open(),
onMouseLeave: (event: MouseEvent<HTMLElement>) => {
if (!contains(event.relatedTarget as Node | null)) hide(id);
diff --git a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/panel.tsx b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/panel.tsx
index 682dd447f..c34a9b0ca 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/panel.tsx
+++ b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/panel.tsx
@@ -7,7 +7,7 @@ import type {
RefCallback,
RefObject,
} from "react";
-import { Fragment } from "react";
+import { Fragment, useState } from "react";
import { twMerge } from "tailwind-merge";
import { PopoverItemLabel } from "../shared/item-label";
import { PopoverSurface } from "../shared/surface";
@@ -22,6 +22,8 @@ type HoverPopoverPanelProps = {
afterLeave?: () => void;
close: () => void;
items: ReadonlyArray<PopoverItem>;
+ footerItems?: ReadonlyArray<PopoverItem>;
+ maxVisibleItems?: number;
side: HoverPopoverSide;
align: HoverPopoverAlign;
sideOffsetPx: number;
@@ -33,8 +35,11 @@ type HoverPopoverPanelProps = {
restoreFocusRef?: RefObject<HTMLElement | null>;
};
-const ENTER = "transition-[opacity,transform] duration-[120ms] ease-spring";
-const LEAVE = "transition-[opacity,transform] duration-[80ms] ease-spring";
+// A row's height (min-h-8), for limiting the list to a number of rows.
+const ROW_HEIGHT_PX = 32;
+
+const ENTER = "transition-[opacity,transform] duration-200 ease-spring motion-reduce:transition-none";
+const LEAVE = "transition-[opacity,transform] duration-[140ms] ease-spring motion-reduce:transition-none";
export function HoverPopoverPanel({
floatingStyle,
@@ -43,6 +48,8 @@ export function HoverPopoverPanel({
afterLeave,
close,
items,
+ footerItems,
+ maxVisibleItems,
side,
align,
sideOffsetPx,
@@ -58,6 +65,31 @@ export function HoverPopoverPanel({
...(side === "top" ? { paddingBottom: sideOffsetPx } : { paddingTop: sideOffsetPx }),
} satisfies CSSProperties;
+ const [moreBelow, setMoreBelow] = useState(false);
+
+ const renderItem = (item: PopoverItem) => (
+ <button
+ key={item.id}
+ type="button"
+ role="menuitem"
+ disabled={!open || item.disabled === true}
+ className={twMerge(
+ "flex min-h-8 items-center gap-2.5 w-full px-2 py-1.5 rounded-lg bg-transparent border-none outline-hidden text-left transition-colors duration-100 ease-out hover:bg-selection-hover focus:bg-selection-hover",
+ item.disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer",
+ item.danger ? "text-red-500" : "text-text-primary",
+ )}
+ onClick={(event) => {
+ if (item.disabled) return;
+ restoreFocusRef?.current?.focus({ preventScroll: true });
+ item.onClick?.(event);
+ close();
+ }}
+ >
+ {item.icon && <span className="shrink-0">{item.icon}</span>}
+ <PopoverItemLabel label={item.label} />
+ </button>
+ );
+
return (
<div
ref={setFloatingRef}
@@ -74,36 +106,40 @@ export function HoverPopoverPanel({
<TransitionChild
as="div"
enter={ENTER}
- enterFrom="opacity-0 scale-90"
+ enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave={LEAVE}
leaveFrom="opacity-100 scale-100"
- leaveTo="opacity-0 scale-90"
+ leaveTo="opacity-0 scale-95"
className={getOriginClassName(side, align)}
>
<PopoverSurface open side={side} align={align} animated={false}>
- {items.map((item) => (
- <button
- key={item.id}
- type="button"
- role="menuitem"
- disabled={!open || item.disabled === true}
- className={twMerge(
- "flex items-center gap-2 w-full px-2.5 py-2 rounded-md bg-transparent border-none outline-hidden text-left hover:bg-surface-tertiary focus:bg-surface-tertiary",
- item.disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer",
- item.danger ? "text-red-500" : "text-text-primary",
- )}
- onClick={(event) => {
- if (item.disabled) return;
- restoreFocusRef?.current?.focus({ preventScroll: true });
- item.onClick?.(event);
- close();
- }}
- >
- {item.icon && <span className="shrink-0">{item.icon}</span>}
- <PopoverItemLabel label={item.label} />
- </button>
- ))}
+ {/* Long lists scroll inside the panel (a fixed number of rows when asked for) instead of
+ running off the window. When more rows wait below, half of the next one shows and
+ fades out, so the list reads as scrollable; the fade goes once the end is reached.
+ Footer rows stay put under a hairline. */}
+ <div
+ ref={(node) => {
+ if (node) setMoreBelow(node.scrollHeight - node.clientHeight - node.scrollTop > 1);
+ }}
+ onScroll={(event) => {
+ const node = event.currentTarget;
+ setMoreBelow(node.scrollHeight - node.clientHeight - node.scrollTop > 1);
+ }}
+ className={twMerge(
+ "max-h-[min(20rem,calc(100vh-6rem))] overflow-y-auto overscroll-contain",
+ moreBelow && "[mask-image:linear-gradient(to_bottom,black_calc(100%-1.5rem),transparent)]",
+ )}
+ style={maxVisibleItems ? { maxHeight: `${(maxVisibleItems + 0.5) * ROW_HEIGHT_PX}px` } : undefined}
+ >
+ {items.map(renderItem)}
+ </div>
+ {footerItems?.length ? (
+ <>
+ <div aria-hidden className="mx-2 my-1 h-px bg-border-default" />
+ {footerItems.map(renderItem)}
+ </>
+ ) : null}
</PopoverSurface>
</TransitionChild>
</Transition>
diff --git a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/provider.tsx b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/provider.tsx
index b0bbe85f4..3aeaa4f10 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/provider.tsx
+++ b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/provider.tsx
@@ -1,5 +1,6 @@
import { createContext, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { usePopoverFloating } from "../shared/use-popover-floating";
+import { PANEL_GAP_PX } from "../../tooltip/provider";
import type { HoverPopoverContextValue, HoverPopoverPayload, HoverPopoverProviderProps } from "./types";
import { HoverPopoverPanel } from "./panel";
@@ -90,9 +91,11 @@ export function HoverPopoverProvider({ children }: HoverPopoverProviderProps) {
afterLeave={handleAfterLeave}
close={() => hide(active.id)}
items={active.items}
+ footerItems={active.footerItems}
+ maxVisibleItems={active.maxVisibleItems}
side={active.side}
align={active.align}
- sideOffsetPx={4}
+ sideOffsetPx={PANEL_GAP_PX}
onMouseEnter={() => setVisible(true)}
onMouseLeave={(event) => {
if (contains(event.relatedTarget as Node | null)) return;
diff --git a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/types.ts b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/types.ts
index d474714c3..9b549a97f 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/hover-popover/types.ts
+++ b/apps/mirai-gui/client/src/components/ui/popover/hover-popover/types.ts
@@ -11,6 +11,10 @@ export type HoverPopoverProviderProps = {
export type HoverPopoverProps = {
items: ReadonlyArray<HoverPopoverItem>;
+ /** Rows under the list that stay put while it scrolls, e.g. "Download models". */
+ footerItems?: ReadonlyArray<HoverPopoverItem>;
+ /** How many rows of `items` show in full before the list scrolls; half of the next one peeks. */
+ maxVisibleItems?: number;
trigger: ReactElement;
side?: HoverPopoverSide;
align?: HoverPopoverAlign;
@@ -20,6 +24,8 @@ export type HoverPopoverPayload = {
id: string;
triggerNode: HTMLButtonElement;
items: ReadonlyArray<HoverPopoverItem>;
+ footerItems?: ReadonlyArray<HoverPopoverItem>;
+ maxVisibleItems?: number;
side: HoverPopoverSide;
align: HoverPopoverAlign;
};
diff --git a/apps/mirai-gui/client/src/components/ui/popover/popover-menu/panel.tsx b/apps/mirai-gui/client/src/components/ui/popover/popover-menu/panel.tsx
index 8d9878d19..c8e8f7287 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/popover-menu/panel.tsx
+++ b/apps/mirai-gui/client/src/components/ui/popover/popover-menu/panel.tsx
@@ -44,7 +44,7 @@ export function PopoverMenuPanel({
disabled={item.disabled ?? false}
className={({ focus, disabled }) =>
twMerge(
- "flex items-center gap-2 w-full px-2.5 py-2 rounded-md bg-transparent border-none outline-hidden text-left",
+ "flex min-h-8 items-center gap-2.5 w-full px-2 py-1.5 rounded-lg bg-transparent border-none outline-hidden text-left transition-colors duration-100 ease-out",
focus ? "bg-surface-tertiary" : undefined,
disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer",
item.danger ? "text-red-500" : "text-text-primary",
diff --git a/apps/mirai-gui/client/src/components/ui/popover/shared/constants.ts b/apps/mirai-gui/client/src/components/ui/popover/shared/constants.ts
index 531fef3f3..7a873dbb2 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/shared/constants.ts
+++ b/apps/mirai-gui/client/src/components/ui/popover/shared/constants.ts
@@ -1,4 +1,2 @@
export const TEXT_13 = "text-[13px] font-[450] leading-[1.3]";
export const TEXT_13_STYLE = { fontVariationSettings: "'opsz' 14" } as const;
-
-export const TRANSITION_BASE = "transition-[opacity,transform] ease-spring";
diff --git a/apps/mirai-gui/client/src/components/ui/popover/shared/surface.tsx b/apps/mirai-gui/client/src/components/ui/popover/shared/surface.tsx
index b6d60c921..61f43badb 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/shared/surface.tsx
+++ b/apps/mirai-gui/client/src/components/ui/popover/shared/surface.tsx
@@ -1,6 +1,6 @@
import type { ReactNode } from "react";
import { twMerge } from "tailwind-merge";
-import { getAnimationClassName, getOriginClassName } from "./utils";
+import { getOriginClassName } from "./utils";
import type { PopoverAlign, PopoverSide } from "./types";
type PopoverSurfaceProps = {
@@ -16,9 +16,10 @@ export function PopoverSurface({ open, side, align, className, children, animate
return (
<div
className={twMerge(
- "rounded-lg bg-surface-elevated shadow-sm p-1.5 min-w-[140px]",
+ "rounded-xl bg-surface-popover shadow-popover p-1 min-w-[180px]",
+ // The panel mounts already open, so the entrance is a keyframe rather than a transition.
animated ? getOriginClassName(side, align) : undefined,
- animated ? getAnimationClassName(open) : undefined,
+ animated && open ? "animate-uzu-pop" : undefined,
className,
)}
>
diff --git a/apps/mirai-gui/client/src/components/ui/popover/shared/utils.ts b/apps/mirai-gui/client/src/components/ui/popover/shared/utils.ts
index fc6f6e18c..9f6ddd753 100644
--- a/apps/mirai-gui/client/src/components/ui/popover/shared/utils.ts
+++ b/apps/mirai-gui/client/src/components/ui/popover/shared/utils.ts
@@ -1,5 +1,3 @@
-import { twMerge } from "tailwind-merge";
-import { TRANSITION_BASE } from "./constants";
import type { PopoverAlign, PopoverSide } from "./types";
export const isPlainTextLabel = (value: unknown): value is string | number =>
@@ -12,10 +10,3 @@ export const getOriginClassName = (side: PopoverSide, align: PopoverAlign) => {
return align === "start" ? "origin-top-left" : "origin-top-right";
};
-
-export const getAnimationClassName = (open: boolean) =>
- twMerge(
- TRANSITION_BASE,
- open ? "duration-[120ms]" : "duration-[80ms]",
- open ? "opacity-100 scale-100" : "opacity-0 scale-90",
- );
diff --git a/apps/mirai-gui/client/src/components/ui/search-input.tsx b/apps/mirai-gui/client/src/components/ui/search-input.tsx
index 735b0eddf..5e6cd0867 100644
--- a/apps/mirai-gui/client/src/components/ui/search-input.tsx
+++ b/apps/mirai-gui/client/src/components/ui/search-input.tsx
@@ -1,4 +1,5 @@
import { Search } from "lucide-react";
+import { twMerge } from "tailwind-merge";
import { Input } from "./input";
export type SearchInputProps = {
@@ -11,13 +12,17 @@ export type SearchInputProps = {
export function SearchInput({ value, onChange, placeholder = "Search", className }: SearchInputProps) {
return (
<Input
- size="sm"
+ size="md"
fullWidth
- leftIcon={<Search size={14} />}
+ leftIcon={<Search size={15} />}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
- className={className}
+ // A filled pill rather than an outlined box: it sits on the page like the other controls.
+ className={twMerge(
+ "h-8 rounded-full border-transparent bg-control-fill hover:border-transparent focus-within:border-border-outlined",
+ className,
+ )}
/>
);
}
diff --git a/apps/mirai-gui/client/src/components/ui/segmented-control.tsx b/apps/mirai-gui/client/src/components/ui/segmented-control.tsx
index 0dd3a0175..a13b16f6a 100644
--- a/apps/mirai-gui/client/src/components/ui/segmented-control.tsx
+++ b/apps/mirai-gui/client/src/components/ui/segmented-control.tsx
@@ -16,8 +16,8 @@ export type SegmentedControlProps = {
ariaLabel: string;
};
-const CONTAINER_CLASSES =
- "inline-flex w-fit h-7 items-center rounded-lg overflow-clip border border-border-default bg-transparent";
+// A pill track; the chosen segment sits raised on it, like a key pressed into place.
+const CONTAINER_CLASSES = "inline-flex w-fit h-8 items-center gap-0.5 rounded-full bg-control-fill p-0.5";
export function SegmentedControl({ value, onChange, options, ariaLabel }: SegmentedControlProps) {
const handleSelect = (option: SegmentedControlOption) => {
@@ -27,12 +27,13 @@ export function SegmentedControl({ value, onChange, options, ariaLabel }: Segmen
return (
<div role="radiogroup" aria-label={ariaLabel} className={CONTAINER_CLASSES}>
- {options.map((option, index) => {
+ {options.map((option) => {
const isSelected = option.value === value;
const segmentClasses = twMerge(
- "h-full px-2 inline-flex items-center gap-2 text-xs transition-colors select-none",
- index > 0 ? "border-l border-border-default" : undefined,
- isSelected ? "bg-surface-tertiary text-text-primary" : "text-text-muted hover:bg-surface-tertiary",
+ "h-full px-3 inline-flex items-center gap-2 rounded-full text-[13px] font-[450] transition-[background-color,color,box-shadow] duration-150 ease-out select-none outline-hidden focus-visible:shadow-focus",
+ isSelected
+ ? "bg-control-selected text-text-primary shadow-[0_1px_2px_rgb(0_0_0/0.08),0_0_0_0.5px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)]"
+ : "text-text-muted hover:text-text-primary",
option.disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer",
);
diff --git a/apps/mirai-gui/client/src/components/ui/select/constants.ts b/apps/mirai-gui/client/src/components/ui/select/constants.ts
index 53fa0f138..47b4489a4 100644
--- a/apps/mirai-gui/client/src/components/ui/select/constants.ts
+++ b/apps/mirai-gui/client/src/components/ui/select/constants.ts
@@ -1,4 +1,5 @@
-export const SELECT_ROW_BASE_CLASSNAME = "text-xs leading-[130%] cursor-pointer select-none rounded-md p-2";
+export const SELECT_ROW_BASE_CLASSNAME =
+ "text-xs leading-[130%] cursor-pointer select-none rounded-lg min-h-8 px-2 py-1.5 flex items-center transition-colors duration-100 ease-out";
export const SELECT_ROW_ACTIVE_CLASSNAME = "bg-selection-hover hover:bg-selection-hover";
export const SELECT_ROW_SELECTED_CLASSNAME = "bg-selection-selected hover:bg-selection-selected";
diff --git a/apps/mirai-gui/client/src/components/ui/select/selection-panel.tsx b/apps/mirai-gui/client/src/components/ui/select/selection-panel.tsx
index 8e8c2d1e6..8ad091da4 100644
--- a/apps/mirai-gui/client/src/components/ui/select/selection-panel.tsx
+++ b/apps/mirai-gui/client/src/components/ui/select/selection-panel.tsx
@@ -6,7 +6,7 @@ type SelectionPanelProps = ComponentPropsWithoutRef<"div">;
export function SelectionPanel({ className, ...props }: SelectionPanelProps) {
return (
<div
- className={twMerge("rounded-lg bg-surface-elevated shadow-sm outline-hidden origin-bottom-right", className)}
+ className={twMerge("rounded-xl bg-surface-popover shadow-popover outline-hidden origin-bottom-right", className)}
{...props}
/>
);
diff --git a/apps/mirai-gui/client/src/components/ui/select/selection-section.tsx b/apps/mirai-gui/client/src/components/ui/select/selection-section.tsx
index 6b9a43297..516c1bbd4 100644
--- a/apps/mirai-gui/client/src/components/ui/select/selection-section.tsx
+++ b/apps/mirai-gui/client/src/components/ui/select/selection-section.tsx
@@ -9,8 +9,10 @@ export function SelectionSection({ divided = false, className, ...props }: Selec
return (
<div
className={twMerge(
- "px-1.5 flex flex-col gap-0.5",
- divided ? "border-t border-border-default mt-1" : undefined,
+ "px-1 flex flex-col gap-px",
+ divided
+ ? "mt-1 pt-1 relative before:absolute before:inset-x-3 before:top-0 before:h-px before:bg-border-default"
+ : undefined,
className,
)}
{...props}
diff --git a/apps/mirai-gui/client/src/components/ui/text-shimmer.tsx b/apps/mirai-gui/client/src/components/ui/text-shimmer.tsx
index 03a21c3ce..7f5a029aa 100644
--- a/apps/mirai-gui/client/src/components/ui/text-shimmer.tsx
+++ b/apps/mirai-gui/client/src/components/ui/text-shimmer.tsx
@@ -16,9 +16,11 @@ function TextShimmerComponent({ children, className, duration = 2, spread = 2 }:
<motion.p
className={twMerge(
"relative inline-block bg-[length:250%_100%,auto] bg-clip-text",
- "text-transparent [--base-color:#a1a1aa] [--base-gradient-color:#000]",
+ // The resting colour is the muted label colour in both themes, so shimmering text matches the
+ // muted text around it (the reasoning under "Thinking…"); only the moving highlight differs.
+ "text-transparent [--base-color:var(--color-label-muted)] [--base-gradient-color:#000]",
"[background-repeat:no-repeat,padding-box] [--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))]",
- "dark:[--base-color:#71717a] dark:[--base-gradient-color:#ffffff] dark:[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))]",
+ "dark:[--base-gradient-color:#ffffff] dark:[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))]",
className,
)}
initial={{ backgroundPosition: "100% center" }}
diff --git a/apps/mirai-gui/client/src/components/ui/toast/custom-toast.tsx b/apps/mirai-gui/client/src/components/ui/toast/custom-toast.tsx
index 5f0a76eee..9ac007deb 100644
--- a/apps/mirai-gui/client/src/components/ui/toast/custom-toast.tsx
+++ b/apps/mirai-gui/client/src/components/ui/toast/custom-toast.tsx
@@ -1,45 +1,45 @@
-import { Info, TriangleAlert, X } from "lucide-react";
-import type { ReactNode } from "react";
+import { CircleCheckIcon, InfoIcon, XIcon, CircleAlertIcon } from "@/components/icons/app-icons";
+import type { ComponentType, ReactNode } from "react";
import type { Toast } from "react-hot-toast";
import toast from "react-hot-toast";
import { twMerge } from "tailwind-merge";
-import { IconButton } from "../icon-button";
-import { IconCheckCircleFilled } from "../../icons/check-circle-filled-icon";
import type { ToastType } from "./types";
export type CustomToastProps = {
t: Toast;
message: ReactNode;
+ description?: string;
type: ToastType;
onClick?: () => void;
};
-type ToastIconConfig = {
- Icon: (props: { className?: string; size?: number }) => ReactNode;
- className: string;
+const TOAST_ICON_BY_TYPE: Record<
+ ToastType,
+ { Icon: ComponentType<{ size?: number; className?: string }>; tone: string }
+> = {
+ success: { Icon: CircleCheckIcon, tone: "text-success" },
+ info: { Icon: InfoIcon, tone: "text-text-muted" },
+ warning: { Icon: CircleAlertIcon, tone: "text-amber-500" },
+ error: { Icon: CircleAlertIcon, tone: "text-danger" },
};
-const TOAST_ICON_BY_TYPE: Record<ToastType, ToastIconConfig> = {
- success: { Icon: IconCheckCircleFilled, className: "text-success" },
- info: { Icon: Info, className: "text-blue-500" },
- warning: { Icon: TriangleAlert, className: "text-yellow-500" },
- error: { Icon: TriangleAlert, className: "text-error" },
-};
-
-function ToastIcon({ type }: { type: ToastType }) {
- const { Icon, className } = TOAST_ICON_BY_TYPE[type];
- return <Icon className={className} size={20} />;
-}
-
-export function CustomToast({ t, message, type, onClick }: CustomToastProps) {
+/**
+ * A note in the corner: the same floating surface as menus, one small coloured icon for the kind of
+ * message, and the text, with an optional quieter line under it. The icon and the close button line
+ * up with the first line, however many lines follow. It comes into focus from just above and leaves a
+ * little faster than it came.
+ */
+export function CustomToast({ t, message, description, type, onClick }: CustomToastProps) {
const isClickable = onClick !== undefined;
+ const { Icon, tone } = TOAST_ICON_BY_TYPE[type];
return (
<div
className={twMerge(
- "flex items-center justify-between rounded-lg border border-gray-500 bg-surface-elevated py-2 pl-3 pr-2 shadow-custom transition-opacity",
- t.visible ? "opacity-100" : "opacity-0",
- isClickable && "cursor-pointer hover:bg-surface-tertiary",
+ // The same card as the update notice beside it: 12px corners on the floating surface.
+ "pointer-events-auto flex min-h-11 max-w-[min(360px,calc(100vw-2rem))] items-start gap-2.5 rounded-[12px] bg-surface-popover py-2 pl-3.5 pr-2 shadow-popover",
+ t.visible ? "animate-uzu-toast-in" : "animate-uzu-toast-out",
+ isClickable && "cursor-pointer transition-colors duration-150 ease-out hover:bg-selection-hover",
)}
onClick={isClickable ? onClick : undefined}
onKeyDown={
@@ -53,22 +53,31 @@ export function CustomToast({ t, message, type, onClick }: CustomToastProps) {
}
: undefined
}
- role={isClickable ? "button" : undefined}
+ role={isClickable ? "button" : "status"}
tabIndex={isClickable ? 0 : undefined}
>
- <div className="flex min-w-0 items-center">
- <ToastIcon type={type} />
- <span className="ml-2 mr-5 min-w-0 truncate text-sm font-medium text-text-primary">{message}</span>
- </div>
- <IconButton
+ <span className="flex h-7 shrink-0 items-center">
+ <Icon size={16} className={tone} aria-hidden />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5 py-1.5">
+ <span className="text-[13px] font-[450] leading-4 text-text-primary text-pretty">{message}</span>
+ {description ? (
+ <span className="line-clamp-3 text-[12px] font-[400] leading-4 text-text-muted text-pretty">
+ {description}
+ </span>
+ ) : null}
+ </span>
+ <button
+ type="button"
onClick={(e) => {
e.stopPropagation();
toast.dismiss(t.id);
}}
- className="text-text-muted hover:text-text-primary"
- icon={<X size={20} />}
- aria-label="Dismiss toast"
- />
+ aria-label="Dismiss"
+ className="relative mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-md text-text-muted outline-hidden transition-colors duration-150 ease-out hover:bg-selection-hover hover:text-text-primary focus-visible:shadow-focus before:absolute before:-inset-2"
+ >
+ <XIcon size={16} aria-hidden />
+ </button>
</div>
);
}
diff --git a/apps/mirai-gui/client/src/components/ui/toast/toast-provider.tsx b/apps/mirai-gui/client/src/components/ui/toast/toast-provider.tsx
index c40c8e8a1..a954bc553 100644
--- a/apps/mirai-gui/client/src/components/ui/toast/toast-provider.tsx
+++ b/apps/mirai-gui/client/src/components/ui/toast/toast-provider.tsx
@@ -5,11 +5,14 @@ export function ToastProvider() {
<Toaster
position="top-right"
toastOptions={{ duration: 3000 }}
+ gutter={8}
+ // The chat block sits 8px inside the window with a 12px corner. Toasts sit the same 8px inside the
+ // block, with a 4px corner (12 − 8), so their corner runs parallel to the block's.
containerStyle={{
- top: 20,
- right: 20,
- bottom: 20,
- left: 20,
+ top: 16,
+ right: 16,
+ bottom: 16,
+ left: 16,
}}
/>
);
diff --git a/apps/mirai-gui/client/src/components/ui/toast/types.ts b/apps/mirai-gui/client/src/components/ui/toast/types.ts
index aeb66914f..265ee7b30 100644
--- a/apps/mirai-gui/client/src/components/ui/toast/types.ts
+++ b/apps/mirai-gui/client/src/components/ui/toast/types.ts
@@ -3,4 +3,6 @@ export type ToastType = "success" | "error" | "info" | "warning";
export type ToastOptions = {
id?: string;
onClick?: () => void;
+ /** A quieter second line: what to do next, or the details of an error. */
+ description?: string;
};
diff --git a/apps/mirai-gui/client/src/components/ui/toast/use-toast.tsx b/apps/mirai-gui/client/src/components/ui/toast/use-toast.tsx
index bf38b5153..0ca5c2e88 100644
--- a/apps/mirai-gui/client/src/components/ui/toast/use-toast.tsx
+++ b/apps/mirai-gui/client/src/components/ui/toast/use-toast.tsx
@@ -1,20 +1,26 @@
+import type { ReactNode } from "react";
import toast from "react-hot-toast";
import { CustomToast } from "./custom-toast";
import type { ToastOptions, ToastType } from "./types";
-function showToast(message: string, type: ToastType, options?: ToastOptions) {
- return toast.custom((t) => <CustomToast t={t} message={message} type={type} onClick={options?.onClick} />, {
- id: options?.id,
- duration: 4000,
- position: "top-right",
- });
+function showToast(message: ReactNode, type: ToastType, options?: ToastOptions) {
+ return toast.custom(
+ (t) => (
+ <CustomToast t={t} message={message} description={options?.description} type={type} onClick={options?.onClick} />
+ ),
+ {
+ id: options?.id,
+ duration: 4000,
+ position: "top-right",
+ },
+ );
}
const toastApi = {
- success: (message: string, options?: ToastOptions) => showToast(message, "success", options),
- error: (message: string, options?: ToastOptions) => showToast(message, "error", options),
- info: (message: string, options?: ToastOptions) => showToast(message, "info", options),
- warning: (message: string, options?: ToastOptions) => showToast(message, "warning", options),
+ success: (message: ReactNode, options?: ToastOptions) => showToast(message, "success", options),
+ error: (message: ReactNode, options?: ToastOptions) => showToast(message, "error", options),
+ info: (message: ReactNode, options?: ToastOptions) => showToast(message, "info", options),
+ warning: (message: ReactNode, options?: ToastOptions) => showToast(message, "warning", options),
dismiss: toast.dismiss,
};
diff --git a/apps/mirai-gui/client/src/components/ui/tooltip/bubble.tsx b/apps/mirai-gui/client/src/components/ui/tooltip/bubble.tsx
index 6b30ae163..3a266d0dc 100644
--- a/apps/mirai-gui/client/src/components/ui/tooltip/bubble.tsx
+++ b/apps/mirai-gui/client/src/components/ui/tooltip/bubble.tsx
@@ -4,12 +4,27 @@ import type { TooltipProps } from "./types";
type TooltipBubbleProps = {
tooltipId: string;
+ side: NonNullable<TooltipProps["side"]>;
+ align: NonNullable<TooltipProps["align"]>;
+ variant: NonNullable<TooltipProps["variant"]>;
+ instant: boolean;
content: TooltipProps["content"];
floatingStyles: CSSProperties;
+ positioned: boolean;
setFloating: (node: HTMLDivElement | null) => void;
};
-export function TooltipBubble({ tooltipId, content, floatingStyles, setFloating }: TooltipBubbleProps) {
+export function TooltipBubble({
+ tooltipId,
+ side,
+ align,
+ variant,
+ instant,
+ content,
+ floatingStyles,
+ positioned,
+ setFloating,
+}: TooltipBubbleProps) {
return (
<div
ref={setFloating}
@@ -18,14 +33,29 @@ export function TooltipBubble({ tooltipId, content, floatingStyles, setFloating
className="pointer-events-none fixed z-50"
style={{
...floatingStyles,
- opacity: 1,
+ // Hidden until it has been placed against its trigger, so it can't flash somewhere else.
+ visibility: positioned ? "visible" : "hidden",
}}
>
+ {/* The same floating surface as menus, so it matches the theme it appears in. */}
<div
+ data-side={side}
className={twMerge(
- "rounded-md bg-surface-tertiary shadow-sm text-text-primary [font-variation-settings:'opsz'_18]",
- "px-2 py-1 text-[11px] font-[450] leading-[1.3]",
- "whitespace-nowrap",
+ "bg-surface-popover text-text-primary shadow-popover whitespace-nowrap tabular-nums",
+ // A panel matches the hover menus (12px corners, text 12px in from the edge); a label is a
+ // small tip.
+ variant === "panel"
+ ? "rounded-xl px-3 py-2.5"
+ : "rounded-lg px-2.5 py-1.5 text-[12px] font-[500] leading-[16px]",
+ // Grows from the trigger: its middle, or its corner when lined up with its edge.
+ side === "top"
+ ? align === "start"
+ ? "origin-bottom-left"
+ : "origin-bottom"
+ : align === "start"
+ ? "origin-top-left"
+ : "origin-top",
+ instant ? undefined : side === "top" ? "animate-uzu-tip-up" : "animate-uzu-tip-down",
)}
>
{content}
diff --git a/apps/mirai-gui/client/src/components/ui/tooltip/index.tsx b/apps/mirai-gui/client/src/components/ui/tooltip/index.tsx
index 54548ed6f..ccca018f1 100644
--- a/apps/mirai-gui/client/src/components/ui/tooltip/index.tsx
+++ b/apps/mirai-gui/client/src/components/ui/tooltip/index.tsx
@@ -3,7 +3,15 @@ import { TooltipContext } from "./context";
import { useTooltipAria } from "./use-tooltip-aria";
import type { TooltipContextValue, TooltipProps } from "./types";
-function TooltipShared({ content, side = "top", children, context }: TooltipProps & { context: TooltipContextValue }) {
+function TooltipShared({
+ content,
+ side = "top",
+ delay,
+ align,
+ variant,
+ children,
+ context,
+}: TooltipProps & { context: TooltipContextValue }) {
const instanceId = useId();
const wrapperRef = useRef<HTMLSpanElement | null>(null);
const visible = context.activeId === instanceId;
@@ -18,8 +26,11 @@ function TooltipShared({ content, side = "top", children, context }: TooltipProp
reference: wrapperRef.current,
content,
side,
+ delay,
+ align,
+ variant,
});
- }, [content, context, instanceId, side]);
+ }, [align, content, context, delay, instanceId, side, variant]);
const hide = useCallback(() => {
context.hide(instanceId);
@@ -42,7 +53,9 @@ function TooltipShared({ content, side = "top", children, context }: TooltipProp
onFocus={show}
onBlur={hide}
onPointerDown={(event) => {
- if (event.button === 0) hide();
+ // A label tip gets out of the way of a click; a panel (the speed figures) is what the
+ // button is for, so pressing it keeps the panel open.
+ if (event.button === 0 && variant !== "panel") hide();
}}
>
{children}
diff --git a/apps/mirai-gui/client/src/components/ui/tooltip/provider.tsx b/apps/mirai-gui/client/src/components/ui/tooltip/provider.tsx
index 47eab6dcc..f69adf91c 100644
--- a/apps/mirai-gui/client/src/components/ui/tooltip/provider.tsx
+++ b/apps/mirai-gui/client/src/components/ui/tooltip/provider.tsx
@@ -1,14 +1,24 @@
import { flip, offset, shift, useFloating } from "@floating-ui/react-dom";
import type { ReferenceType } from "@floating-ui/react-dom";
-import { useCallback, useEffect, useId, useMemo, useState } from "react";
+import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { TooltipContext } from "./context";
import type { TooltipContextValue, TooltipPayload, TooltipProviderProps } from "./types";
import { autoUpdateWithDetach } from "./utils";
import { TooltipBubble } from "./bubble";
+// The first tooltip waits so it doesn't flash on a passing cursor; once one has been shown, its
+// neighbours open at once and without an entrance, until the pointer has been away a moment.
+const OPEN_DELAY_MS = 400;
+const WARM_FOR_MS = 300;
+export const PANEL_GAP_PX = 6;
+
export function TooltipProvider({ children }: TooltipProviderProps) {
const [activeTooltip, setActiveTooltip] = useState<TooltipPayload | null>(null);
+ const [instant, setInstant] = useState(false);
const tooltipId = useId();
+ const openTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const warmUntilRef = useRef(0);
+ const visibleRef = useRef(false);
const whileElementsMounted = useCallback(
(reference: ReferenceType, floating: HTMLElement, update: () => void) =>
@@ -18,23 +28,52 @@ export function TooltipProvider({ children }: TooltipProviderProps) {
[],
);
- const { refs, floatingStyles } = useFloating({
- placement: activeTooltip?.side ?? "top",
+ const { refs, floatingStyles, isPositioned } = useFloating({
+ placement: activeTooltip
+ ? activeTooltip.align === "start"
+ ? (`${activeTooltip.side}-start` as const)
+ : activeTooltip.side
+ : "top",
strategy: "fixed",
+ // Lets `isPositioned` fall back to false between tooltips, so each one waits for its own place.
+ open: activeTooltip !== null,
whileElementsMounted,
- middleware: [offset(8), flip(), shift({ padding: 8 })],
+ // Panels sit as close to their trigger as the hover menus do (PANEL_GAP_PX); label tips a touch further.
+ middleware: [offset(activeTooltip?.variant === "panel" ? PANEL_GAP_PX : 8), flip(), shift({ padding: 8 })],
});
- useEffect(() => {
+ // Before paint, so a tooltip is never measured against the previous trigger (it showed up out of
+ // place on the first hover of a new one).
+ useLayoutEffect(() => {
refs.setReference(activeTooltip?.reference ?? null);
}, [activeTooltip, refs]);
+ useEffect(() => {
+ visibleRef.current = activeTooltip !== null;
+ }, [activeTooltip]);
+ useEffect(() => () => clearTimeout(openTimerRef.current ?? undefined), []);
+
const show = useCallback((payload: TooltipPayload) => {
- setActiveTooltip(payload);
+ clearTimeout(openTimerRef.current ?? undefined);
+ const warm = visibleRef.current || performance.now() < warmUntilRef.current;
+ if (warm) {
+ setInstant(true);
+ setActiveTooltip(payload);
+ return;
+ }
+ openTimerRef.current = setTimeout(() => {
+ setInstant(false);
+ setActiveTooltip(payload);
+ }, payload.delay ?? OPEN_DELAY_MS);
}, []);
const hide = useCallback((id: string) => {
- setActiveTooltip((current) => (current?.id === id ? null : current));
+ clearTimeout(openTimerRef.current ?? undefined);
+ setActiveTooltip((current) => {
+ if (current?.id !== id) return current;
+ warmUntilRef.current = performance.now() + WARM_FOR_MS;
+ return null;
+ });
}, []);
const contextValue = useMemo<TooltipContextValue>(
@@ -52,9 +91,15 @@ export function TooltipProvider({ children }: TooltipProviderProps) {
{children}
{activeTooltip && (
<TooltipBubble
+ key={activeTooltip.id}
+ side={activeTooltip.side}
+ align={activeTooltip.align ?? "center"}
+ variant={activeTooltip.variant ?? "label"}
+ instant={instant}
tooltipId={tooltipId}
content={activeTooltip.content}
floatingStyles={floatingStyles}
+ positioned={isPositioned}
setFloating={refs.setFloating}
/>
)}
diff --git a/apps/mirai-gui/client/src/components/ui/tooltip/types.ts b/apps/mirai-gui/client/src/components/ui/tooltip/types.ts
index 3a6b2dd75..2f090944d 100644
--- a/apps/mirai-gui/client/src/components/ui/tooltip/types.ts
+++ b/apps/mirai-gui/client/src/components/ui/tooltip/types.ts
@@ -9,6 +9,14 @@ export type TooltipProviderProps = {
export type TooltipProps = {
content: ReactNode;
side?: TooltipSide;
+ /** How long the pointer rests before the first tooltip opens. Defaults to the shared 400ms; a tip
+ * that carries real content (not a label) can open at once, like a hover menu. */
+ delay?: number;
+ /** Centred on the trigger by default; "start" lines its edge up with the trigger's, like a menu. */
+ align?: "center" | "start";
+ /** "label" is the small text tip. "panel" carries real content and takes the hover menus' shape:
+ * the same corners, inset and distance from the trigger, so the two read as one family. */
+ variant?: "label" | "panel";
children: ReactNode;
};
@@ -17,6 +25,9 @@ export type TooltipPayload = {
reference: HTMLSpanElement;
content: TooltipProps["content"];
side: NonNullable<TooltipProps["side"]>;
+ delay?: number;
+ align?: TooltipProps["align"];
+ variant?: TooltipProps["variant"];
};
export type TooltipContextValue = {
diff --git a/apps/mirai-gui/client/src/components/update-toast/index.tsx b/apps/mirai-gui/client/src/components/update-toast/index.tsx
index 2d62013c4..8117b26dd 100644
--- a/apps/mirai-gui/client/src/components/update-toast/index.tsx
+++ b/apps/mirai-gui/client/src/components/update-toast/index.tsx
@@ -1,7 +1,12 @@
import React from "react";
import { twMerge } from "tailwind-merge";
+import { CircleArrowDownIcon, XIcon } from "@/components/icons/app-icons";
import { Button } from "@/components/ui/button";
-import { X } from "lucide-react";
+import {
+ SURFACE_BUTTON_SMALL_CLASSNAME,
+ SURFACE_CLOSE_CLASSNAME,
+ SURFACE_SOFT_BUTTON_CLASSNAME,
+} from "@/components/ui/modal/constants";
export type UpdateToastProps = {
version: string;
@@ -9,35 +14,65 @@ export type UpdateToastProps = {
onLater: () => void;
errorMessage?: string;
onClose?: () => void;
+ visible?: boolean;
};
-export const UpdateToast: React.FC<UpdateToastProps> = ({ version, onApplyNow, onLater, errorMessage, onClose }) => {
+/**
+ * The update notice in the corner: the same lifted surface and motion as the other toasts, with the
+ * two choices as pills under the text.
+ */
+export const UpdateToast: React.FC<UpdateToastProps> = ({
+ version,
+ onApplyNow,
+ onLater,
+ errorMessage,
+ onClose,
+ visible = true,
+}) => {
return (
<div
+ role="status"
className={twMerge(
- "w-[560px] max-w-[90vw] bg-bg-modal border border-button-border rounded-xl p-4 shadow-lg",
- "flex flex-col gap-3",
+ "pointer-events-auto flex w-[360px] max-w-[calc(100vw-2rem)] gap-3 rounded-[12px] bg-surface-popover p-4 pr-3 shadow-popover",
+ visible ? "animate-uzu-toast-in" : "animate-uzu-toast-out",
)}
>
- <div className="flex items-start justify-between gap-3">
- <div className="flex flex-col">
- <div className="text-label-title font-semibold">Update {version} is ready</div>
- <div className="text-label-muted text-sm mt-1">Restart to apply the update.</div>
- {errorMessage ? <div className="text-sm mt-2 text-error">{errorMessage}</div> : null}
+ <CircleArrowDownIcon size={18} aria-hidden className="mt-px shrink-0 text-text-secondary" />
+
+ <div className="flex min-w-0 flex-1 flex-col">
+ <p className="text-[14px] font-[500] leading-[1.35] text-text-primary tabular-nums">
+ Update {version} is ready
+ </p>
+ <p className="mt-0.5 text-[13px] font-[400] leading-[1.45] text-text-secondary text-pretty">
+ Restart to finish installing it.
+ </p>
+ {errorMessage ? (
+ <p className="mt-1.5 text-[13px] font-[400] leading-[1.45] text-danger text-pretty">{errorMessage}</p>
+ ) : null}
+
+ <div className="mt-3 flex items-center gap-2">
+ <Button size="sm" kind="primary" onClick={onApplyNow} className={SURFACE_BUTTON_SMALL_CLASSNAME}>
+ Restart now
+ </Button>
+ <Button
+ size="sm"
+ kind="secondary"
+ onClick={onLater}
+ className={twMerge(SURFACE_BUTTON_SMALL_CLASSNAME, SURFACE_SOFT_BUTTON_CLASSNAME)}
+ >
+ Later
+ </Button>
</div>
- <button onClick={onClose} className="text-label-muted hover:text-label-title p-1 rounded" aria-label="Close">
- <X size={18} />
- </button>
</div>
- <div className="flex items-center gap-2 mt-1">
- <Button size="sm" kind="primary" onClick={onApplyNow}>
- Restart now
- </Button>
- <Button size="sm" kind="secondary" onClick={onLater}>
- Later
- </Button>
- </div>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Dismiss"
+ className={twMerge(SURFACE_CLOSE_CLASSNAME, "-mt-1 size-6")}
+ >
+ <XIcon size={16} aria-hidden />
+ </button>
</div>
);
};
diff --git a/apps/mirai-gui/client/src/components/update-toast/notifications.tsx b/apps/mirai-gui/client/src/components/update-toast/notifications.tsx
index 3cf72edda..26f4f0a73 100644
--- a/apps/mirai-gui/client/src/components/update-toast/notifications.tsx
+++ b/apps/mirai-gui/client/src/components/update-toast/notifications.tsx
@@ -1,7 +1,7 @@
import { UpdateToast } from "@/components/update-toast";
import { toast } from "react-hot-toast";
-const toastPosition = "bottom-right" as const;
+const toastPosition = "top-right" as const;
type ReadyToastParams = {
version: string;
@@ -23,8 +23,9 @@ export const showReadyUpdateToast = ({
errorMessage,
}: ReadyToastParams): void => {
toast.custom(
- () => (
+ (t) => (
<UpdateToast
+ visible={t.visible}
version={version}
onApplyNow={onApplyNow}
onLater={onLater}
diff --git a/apps/mirai-gui/client/src/components/uzu-cat/engine.ts b/apps/mirai-gui/client/src/components/uzu-cat/engine.ts
new file mode 100644
index 000000000..57c31850f
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/uzu-cat/engine.ts
@@ -0,0 +1,751 @@
+import { type RefObject, useEffect, useRef, useState } from "react";
+import { useMediaQuery } from "@/hooks/use-media-query";
+
+/*
+ * The behaviour engine for the matrix face. It moves like a face, not like a UI:
+ * - Gaze moves in saccades: a fast jump, then a fixation that holds.
+ * - Blinks are lids, not a squash: the top lid travels most of the way down, the bottom one a
+ * little up. ~75 ms to close, a 25 ms hold, ~150 ms to open with a hair of overshoot. The right
+ * eye trails by 12 ms, a quarter of blinks come in pairs, and blinks like to ride on a glance.
+ * - Expressions ease, so one state melts into the next.
+ *
+ * The Story is uzu's day as an inference engine: what it is doing, as a feeling.
+ */
+
+export type StateId =
+ | "resting"
+ | "waking"
+ | "loading"
+ | "warming"
+ | "reading"
+ | "thinking"
+ | "drafting"
+ | "writing"
+ | "tool"
+ | "memory"
+ | "freeing"
+ | "done"
+ | "local"
+ | "idle"
+ | "follow"
+ | "ready"
+ | "welcome"
+ | "watch"
+ | "grumpy";
+
+export const STATE_LABEL: Record<StateId, string> = {
+ resting: "Resting",
+ waking: "Waking up",
+ loading: "Loading model",
+ warming: "Warming up",
+ reading: "Reading prompt",
+ thinking: "Thinking",
+ drafting: "Drafting tokens",
+ writing: "Writing answer",
+ tool: "Calling a tool",
+ memory: "Memory tight",
+ freeing: "Freeing memory",
+ done: "Done",
+ local: "Stays on device",
+ idle: "Idle",
+ follow: "Watching you",
+ ready: "Ready for you",
+ welcome: "Introducing uzu by mirai labs",
+ watch: "Watching you type",
+ grumpy: "Not pleased",
+};
+
+/** Tab names where they differ from the caption. */
+export const TAB_LABEL: Partial<Record<StateId, string>> = { welcome: "Welcome" };
+
+/** About forty seconds: a model wakes, loads, reads, thinks, answers, and goes back to rest. */
+export const STORY: ReadonlyArray<[StateId, number]> = [
+ ["resting", 3.2],
+ ["waking", 3.4],
+ ["loading", 3.6],
+ ["warming", 2.2],
+ ["reading", 3.8],
+ ["thinking", 2.8],
+ ["drafting", 2.6],
+ ["writing", 3.6],
+ ["tool", 2.4],
+ ["memory", 2.2],
+ ["freeing", 2.2],
+ ["writing", 2.4],
+ ["done", 2.6],
+ ["local", 7.6],
+ ["resting", 3.6],
+];
+const STORY_LENGTH = STORY.reduce((sum, [, d]) => sum + d, 0);
+
+export type Look = "eyes" | "text";
+
+export type Face = {
+ gx: number;
+ gy: number;
+ blinkL: number; // 0 open .. 1 closed
+ blinkR: number;
+ squint: number;
+ happy: number;
+ size: number; // eye scale
+ fill: number; // < 0: solid eyes; 0..1: outlined eyes filling from the bottom
+ turn: number; // -1..1, a hint of head turn: the near eye widens
+ lift: number; // vertical offset of the eyes, in box units
+ bracketL: number; // extra outward offset per bracket, in box units
+ bracketR: number;
+ asym: number; // the right eye narrows while thinking
+ sleep: number;
+ jitter: number;
+ /** What the eyes are drawn as. Switches happen behind a blink. */
+ look: Look;
+ /** Writing: tokens written so far (carried across visits until the next prompt). */
+ text: number;
+ /** Whole-face sideways offset, for trembling, in box units. */
+ shake: number;
+ /** Stays on device: how far the face has turned into an iPhone, and into a Mac (0..1 each). */
+ phone: number;
+ mac: number;
+ /** Head tilt in degrees, around the face's centre. */
+ tilt: number;
+ /** Whole-face vertical offset (hops, purring), in box units. */
+ bob: number;
+ /** Reading: square glasses, 0 off .. 1 on. */
+ glasses: number;
+ /** Cat ears: height scale, outward tilt per ear in degrees (flicks included). */
+ earH: number;
+ earL: number;
+ earR: number;
+ caption: string;
+ state: StateId;
+ t: number;
+ zs: ReadonlyArray<{ id: number; age: number }>;
+ /** A slow breathing cycle, -1..1. */
+ breath: number;
+ /** Calling a tool: the eyes' rotation in degrees, as gears. */
+ spin: number;
+};
+
+export const REST: Face = {
+ gx: 0,
+ gy: 0,
+ blinkL: 0,
+ blinkR: 0,
+ squint: 0,
+ happy: 0,
+ size: 1,
+ fill: -1,
+ turn: 0,
+ lift: 0,
+ bracketL: 0,
+ bracketR: 0,
+ asym: 0,
+ sleep: 0,
+ jitter: 0,
+ look: "eyes",
+ text: 0,
+ shake: 0,
+ phone: 0,
+ mac: 0,
+ tilt: 0,
+ bob: 0,
+ glasses: 0,
+ earH: 1,
+ earL: 0,
+ earR: 0,
+ caption: "",
+ state: "idle",
+ t: 0,
+ zs: [],
+ breath: 0,
+ spin: 0,
+};
+
+export function stateAt(state: string, t: number): { id: StateId; local: number; duration: number } {
+ if (state !== "story") return { id: state as StateId, local: t, duration: Infinity };
+ let at = t % STORY_LENGTH;
+ for (const [id, d] of STORY) {
+ if (at < d) return { id, local: at, duration: d };
+ at -= d;
+ }
+ return { id: "idle", local: 0, duration: Infinity };
+}
+
+const approach = (from: number, to: number, rate: number, dt: number) =>
+ from + (to - from) * (1 - Math.exp(-rate * dt));
+const easeIn = (x: number) => x * x * x;
+const easeOutBack = (x: number) => {
+ const c = 1.2;
+ return 1 + (c + 1) * (x - 1) ** 3 + c * (x - 1) ** 2;
+};
+
+/** A lid: 100 ms close, 50 ms hold, 220 ms open with a touch of overshoot past open. */
+const LID_CLOSED_AT = 0.1;
+function lid(since: number) {
+ if (since < 0) return 0;
+ if (since < 0.1) return easeIn(since / 0.1);
+ if (since < 0.15) return 1;
+ if (since < 0.37) return 1 - easeOutBack((since - 0.15) / 0.22);
+ return 0;
+}
+
+/** An ear flick: 60 ms out, 140 ms back. */
+function flick(since: number) {
+ if (since < 0 || since > 0.2) return 0;
+ return since < 0.06 ? since / 0.06 : 1 - easeIn((since - 0.06) / 0.14) ** 0.5;
+}
+
+const LOOK: Partial<Record<StateId, Look>> = { writing: "text" };
+
+export type EngineOptions = {
+ state: string;
+ blinkRate: number;
+ gazeRange: number;
+ speed: number;
+ restartKey: number;
+ /** For the 'watch' state: where to look, -1..1 each way (x right, y down) from the face. */
+ lookAt?: { x: number; y: number } | null;
+ /** For the 'loading' state: real progress 0..1 fills the eyes; without it they fill over time. */
+ progress?: number | null;
+};
+
+export function useFace(opts: EngineOptions, stage: RefObject<HTMLElement | null>): Face {
+ const [face, setFace] = useState<Face>(REST);
+ const optsRef = useRef(opts);
+ optsRef.current = opts;
+ const reduced = useMediaQuery("(prefers-reduced-motion: reduce)");
+ // With reduced motion the face is posed once per state instead of animated.
+ const poseKey = reduced ? `${opts.state}:${opts.progress ?? ""}` : "";
+
+ useEffect(() => {
+ const pointer = { x: 0, y: 0, at: -Infinity };
+ const onMove = (e: PointerEvent) => {
+ const el = stage.current;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ pointer.x = Math.max(-1, Math.min(1, (e.clientX - (r.left + r.width / 2)) / (r.width * 0.6)));
+ pointer.y = Math.max(-1, Math.min(1, (e.clientY - (r.top + r.height / 2)) / (r.height * 0.6)));
+ pointer.at = performance.now() / 1000;
+ };
+ window.addEventListener("pointermove", onMove);
+
+ const sim: Face = { ...REST, zs: [] };
+ const zs: Array<{ id: number; age: number }> = [];
+ let target = { x: 0, y: 0 };
+ let nextSaccade = 0;
+ let nextBlink = 1;
+ let blinkAt = -10;
+ let pairAt = -1;
+ let nextZ = 0;
+ let zid = 0;
+ let nextToken = 0;
+ let lookAt = -1;
+ // Ear flicks: a fast flick outward and back, one ear at a time, every few seconds.
+ let flickL = -10;
+ let flickR = -10;
+ let nextFlick = 2.5;
+ let tiltL = 0;
+ let tiltR = 0;
+ let nextLook: Look = "eyes";
+ let lastState: StateId | null = null;
+ let enteredAt = 0;
+ // Scripted moments fire once per visit to a state, whatever the frame rate.
+ const fired = new Set<string>();
+ const once = (key: string, when: boolean) => {
+ if (!when || fired.has(key)) return false;
+ fired.add(key);
+ return true;
+ };
+
+ const blink = (t: number) => {
+ blinkAt = t;
+ if (Math.random() < 0.12) pairAt = t + 0.45;
+ };
+
+ const step = (dtReal: number) => {
+ const o = optsRef.current;
+ const dt = dtReal * o.speed;
+ sim.t += dt;
+ const t = sim.t;
+ const { id, local, duration } = stateAt(o.state, t);
+ if (id !== lastState) {
+ lastState = id;
+ enteredAt = t;
+ fired.clear();
+ // Entering a state is a moment: a glance and sometimes a blink go with it. When the eyes
+ // change into something else (lines of text), the change happens behind a blink.
+ nextSaccade = t + 0.2;
+ const look = LOOK[id] ?? "eyes";
+ if (look !== nextLook) {
+ nextLook = look;
+ blinkAt = t;
+ pairAt = -1;
+ lookAt = t + LID_CLOSED_AT;
+ } else if (id !== "resting" && id !== "loading" && id !== "waking" && Math.random() < 0.3) blink(t + 0.08);
+ if (id === "reading") sim.text = 0;
+ nextBlink = Math.max(nextBlink, t + 1.5);
+ }
+ if (lookAt > 0 && t >= lookAt) {
+ sim.look = nextLook;
+ lookAt = -1;
+ }
+ const since = t - enteredAt;
+ // Progress through the state; a state held on its own tab loops at its story length.
+ const loop = STORY.find(([sid]) => sid === id)?.[1] ?? 3;
+ const p = Number.isFinite(duration) ? local / duration : (since % loop) / loop;
+ sim.state = id;
+ sim.caption = STATE_LABEL[id];
+
+ // Targets for this moment.
+ let gx = 0;
+ let gy = 0;
+ let squint = 0;
+ let happy = 0;
+ let size = 1;
+ let fill = -1;
+ let bracketL = 0;
+ let bracketR = 0;
+ let asym = 0;
+ let sleep = 0;
+ const jitter = 0;
+ let lift = 0;
+ let saccades = false;
+ let saccadeGap = 2;
+ let blinks = true;
+ let gazeRate = 14;
+ let sleepRate = 10;
+ let glasses = 0;
+ let shake = 0;
+ let spin = 0;
+ let phone = 0;
+ let mac = 0;
+ let tilt = 0;
+ let bob = 0;
+ let earH = 1;
+ let earTiltL = 0;
+ let earTiltR = 0;
+ let flicks = true;
+
+ switch (id) {
+ case "resting":
+ sleep = 1;
+ blinks = false;
+ gy = 0.35;
+ break;
+ case "waking": {
+ // Slow: still asleep, lids half open and heavy, a drowsy look around, one blink, awake.
+ sleep = since < 0.7 ? 1 : since < 2.1 ? 0.5 : 0;
+ sleepRate = since < 2.1 ? 3 : 5;
+ gazeRate = 4;
+ gx = since < 1.2 ? 0 : since < 2.4 ? -0.35 : 0.3;
+ gy = since < 2.1 ? 0.3 : 0;
+ if (once("awake", since > 1.95)) blinkAt = t;
+ blinks = false;
+ break;
+ }
+ case "loading":
+ fill = o.progress != null ? Math.max(0, Math.min(1, o.progress)) : Math.min(1, easeIn(p) * 0.15 + p * 0.85);
+ gy = 0.55;
+ blinks = false;
+ if (once("loaded", p > 0.95)) blink(t);
+ break;
+ case "warming":
+ saccades = true;
+ saccadeGap = 0.75;
+ squint = 0.12;
+ break;
+ case "reading": {
+ // Glasses on, then two lines with four fixations each and a return sweep.
+ glasses = 1; // the drawing shrinks the eyes to fit the lenses
+ const q = Math.max(0, since - 0.5) / Math.max(1, (Number.isFinite(duration) ? duration : 3.8) - 0.9);
+ const line = Math.floor(q * 2) % 2;
+ const pos = (q * 2) % 1;
+ gx = since < 0.5 ? 0 : pos > 0.9 ? -1 : -1 + Math.floor(pos * 4) * (2 / 3);
+ gy = since < 0.5 ? 0 : -0.45 + line * 0.9;
+ gazeRate = 18;
+ blinks = false;
+ break;
+ }
+ case "thinking": {
+ // Daydreaming: eyes up and to the side, drifting slowly as if following a thought,
+ // lids a little heavy, the right eye narrower. Same at every size; small sizes get the
+ // full room inside the brackets so the look up still reads.
+ const full = 1 / Math.max(0.3, o.gazeRange);
+ gx = (0.5 + 0.2 * Math.sin(since * 0.75)) * full * 0.9;
+ gy = (-0.85 - 0.12 * Math.sin(since * 1.1 + 1)) * full * 0.9;
+ gazeRate = 3.5;
+ squint = 0.3;
+ asym = 1;
+ blinks = since > 1.6;
+ break;
+ }
+ case "drafting":
+ // Speculative decoding: a draft glance, then verify on the other side.
+ gx = Math.floor(since / 0.65) % 2 === 0 ? -0.7 : 0.7;
+ gy = 0.1;
+ squint = 0.1;
+ break;
+ case "writing":
+ // Eyes become two columns of text; tokens land one by one with a block cursor.
+ if (sim.look === "text" && t > nextToken) {
+ sim.text += 1;
+ nextToken = t + 0.09 + Math.random() * 0.07;
+ }
+ blinks = false;
+ break;
+ case "tool": {
+ // Calling a tool, as clockwork: the eyes tick round a notch at a time like two meshing
+ // gears (left one way, right the other), while the face holds still and attentive.
+ const step = 0.55;
+ const u = Math.min(1, (since % step) / 0.22);
+ spin = 45 * (Math.floor(since / step) + (1 - (1 - u) ** 3));
+ size = 0.9;
+ gazeRate = 8;
+ blinks = false;
+ break;
+ }
+ case "memory": {
+ // Tight on memory: wide eyes, squeezed brackets, flat ears, and trembling like a cold
+ // cat, fast small shivers of the whole face in bursts.
+ size = 1.06;
+ bracketL = -6;
+ bracketR = -6;
+ blinks = false;
+ const k = since % 1.15;
+ const envelope = k < 0.8 ? Math.sin((k / 0.8) * Math.PI) : 0;
+ shake = 1.2 * envelope * Math.sin(t * Math.PI * 2 * 15);
+ break;
+ }
+ case "freeing": {
+ // Relief: the shiver fades, a long slow blink like an exhale, the brackets breathe out
+ // past their rest and settle.
+ const k = since % 3;
+ shake = k < 0.4 ? 1.2 * (1 - k / 0.4) * Math.sin(t * Math.PI * 2 * 15) : 0;
+ size = k < 0.4 ? 1.06 : 1;
+ sleep = k > 0.45 && k < 0.95 ? 1 : 0;
+ sleepRate = 7;
+ bracketL = k < 0.5 ? -6 : k < 1.3 ? 2.5 : 0;
+ bracketR = bracketL;
+ blinks = false;
+ break;
+ }
+ case "done":
+ happy = 1;
+ lift = -2 * Math.abs(Math.sin(since * 4.5)) * Math.max(0, 1 - since / 1.2);
+ blinks = false;
+ break;
+ case "local": {
+ // Stays on device: the brackets close into an iPhone for a couple of seconds, widen
+ // into a Mac, then open back into the face, with a trusting blink on each screen.
+ const loop = Math.floor(since / 7.6);
+ const k = since % 7.6;
+ phone = k > 0.6 && k < 3.2 ? 1 : 0;
+ mac = k >= 3.2 && k < 6.0 ? 1 : 0;
+ gy = phone ? 0.15 : 0;
+ gx = mac ? (k < 4.6 ? -0.35 : 0.35) : 0;
+ gazeRate = 6;
+ if (once(`phone-blink-${loop}`, k > 1.9)) blinkAt = t;
+ if (once(`mac-blink-${loop}`, k > 5.2)) blinkAt = t;
+ if (once(`home-${loop}`, k > 6.9)) blinkAt = t;
+ blinks = false;
+ break;
+ }
+ case "watch": {
+ // Watching something it's been pointed at (the caret as you type): eyes on it, steady,
+ // using the full room inside the brackets, a touch of focus in the lids.
+ const full = 1 / Math.max(0.3, o.gazeRange);
+ gx = Math.max(-1, Math.min(1, o.lookAt?.x ?? 0)) * full;
+ gy = Math.max(-1, Math.min(1, o.lookAt?.y ?? 0.8)) * full;
+ gazeRate = 12;
+ squint = 0.06;
+ break;
+ }
+ case "grumpy": {
+ // Asked to work with nothing to work with: lids drop to a flat stare and the head gives a
+ // quick "no" shake, then the eyes go pointedly to what's missing (lookAt, the model picker).
+ const full = 1 / Math.max(0.3, o.gazeRange);
+ squint = 0.5;
+ blinks = false;
+ gazeRate = 12;
+ shake = since < 0.55 ? 3.2 * Math.sin(since * Math.PI * 2 * 3.6) * (1 - since / 0.55) : 0;
+ if (since > 0.6) {
+ gx = Math.max(-1, Math.min(1, o.lookAt?.x ?? 0.6)) * full;
+ gy = Math.max(-1, Math.min(1, o.lookAt?.y ?? 0.6)) * full;
+ }
+ break;
+ }
+ case "follow":
+ if (performance.now() / 1000 - pointer.at < 2.5) {
+ gx = pointer.x;
+ gy = pointer.y;
+ } else saccades = true;
+ break;
+ case "ready": {
+ // The empty state, an eight-second loop: a slow blink at you, a glance down at the box
+ // where you'd type, ears up, a happy hello with a small hop and brackets opening like
+ // arms, then quiet breathing and a look around. A moving cursor always wins.
+ const loop = Math.floor(since / 8);
+ const k = since % 8;
+ gazeRate = 7;
+ blinks = false;
+ if (once(`slow-${loop}`, k > 0.6)) blinkAt = t;
+ // Glances use the full room inside the brackets, whatever the gaze range is set to.
+ const full = 1 / Math.max(0.3, o.gazeRange);
+ if (k < 1.3) [gx, gy] = [0, 0];
+ else if (k < 2.4) {
+ // Looking down at the box: eyes drop to the floor of the brackets, upper lids lower.
+ [gx, gy] = [-0.15 * full, full];
+ squint = 0.3;
+ lift = 2.5;
+ } else if (k < 3.2) [gx, gy] = [0, 0];
+ else if (k < 4.5) {
+ [gx, gy] = [0, 0];
+ happy = 1;
+ const hop = Math.max(0, Math.sin(((k - 3.3) / 0.9) * Math.PI * 2));
+ lift = k < 4.2 ? -3.2 * hop : 0;
+ bracketL = bracketR = 3;
+ } else if (k < 6) {
+ lift = Math.sin((k - 4.5) * Math.PI * 1.2) * 0.9;
+ if (once(`settle-${loop}`, k > 5.3)) blinkAt = t;
+ } else if (k < 7.2) [gx, gy] = [0.9 * full, -0.3 * full];
+ else [gx, gy] = [0, 0];
+ if (performance.now() / 1000 - pointer.at < 2) {
+ gx = pointer.x;
+ gy = pointer.y;
+ gazeRate = 16;
+ }
+ break;
+ }
+ case "welcome": {
+ // A happy cat greeting its owner, on a 7.2 s loop of slow, readable beats:
+ // 0.0 notices you: eyes wide, ears up, head pops up a little
+ // 0.6 meow: ^ ^ eyes and a little hop
+ // 1.5 head rubs: the cheek rubs one way, then the other (the face slides and leans)
+ // 3.3 purr: a slow blink while the face vibrates softly
+ // 4.9 curious: a head tilt with one ear twitching, then settle with a happy blink
+ const loop = Math.floor(since / 7.2);
+ const k = since % 7.2;
+ const bump = (from: number, len: number) =>
+ k >= from && k < from + len ? Math.sin(((k - from) / len) * Math.PI) : 0;
+ gazeRate = 7;
+ blinks = false;
+ if (k < 0.6) {
+ size = 1.12;
+ bob = -2.5 * bump(0, 0.6);
+ } else if (k < 1.5) {
+ happy = 1;
+ bob = -3.2 * bump(0.75, 0.4);
+ } else if (k < 3.3) {
+ // Two cheek rubs: left, then right. Eased in and out, no jitter.
+ const left = bump(1.5, 0.9);
+ const right = bump(2.4, 0.9);
+ happy = 1;
+ shake = -7 * left + 7 * right;
+ tilt = -11 * left + 11 * right;
+ } else if (k < 4.9) {
+ // Purring: eyes close slowly, a soft fast vibration.
+ sleep = k > 3.35 && k < 4.7 ? 1 : 0;
+ sleepRate = 3.5;
+ bob = 0.45 * Math.sin(t * Math.PI * 2 * 22) * bump(3.3, 1.6);
+ } else if (k < 6.2) {
+ tilt = 10;
+ gx = 0.25;
+ gy = -0.15;
+ } else if (once(`welcome-blink-${loop}`, k > 6.5)) blinkAt = t;
+ if (performance.now() / 1000 - pointer.at < 2) {
+ gx = pointer.x;
+ gy = pointer.y;
+ gazeRate = 16;
+ }
+ break;
+ }
+ default:
+ saccades = true;
+ saccadeGap = 2;
+ }
+
+ // Ears, per state. Positive tilt leans an ear outward; negative leans it forward.
+ switch (id) {
+ case "resting":
+ earH = 0.84;
+ earTiltL = earTiltR = 9;
+ break;
+ case "waking":
+ earH = since < 2.1 ? 0.86 : 1.06;
+ earTiltL = earTiltR = since < 2.1 ? 8 : -3;
+ if (once("ear-awake", since > 2.15)) flickR = t;
+ break;
+ case "reading":
+ earTiltL = earTiltR = -4;
+ break;
+ case "thinking":
+ earTiltR = 22;
+ earTiltL = -2;
+ break;
+ case "drafting":
+ earTiltL = earTiltR = 0;
+ earTiltL += gx < 0 ? -8 : 6;
+ earTiltR += gx > 0 ? -8 : 6;
+ break;
+ case "tool":
+ earH = 1.06;
+ earTiltL = earTiltR = -6;
+ break;
+ case "grumpy":
+ // Ears pinned back and out: annoyed, not scared.
+ earH = 0.72;
+ earTiltL = earTiltR = 30;
+ flicks = false;
+ break;
+ case "memory":
+ // Airplane ears: flat and back while it is tight.
+ earH = 0.6;
+ earTiltL = earTiltR = 38;
+ flicks = false;
+ break;
+ case "freeing": {
+ const k = since % 3;
+ earH = k < 0.5 ? 0.6 : k < 1.3 ? 1.1 : 1;
+ earTiltL = earTiltR = k < 0.5 ? 38 : 0;
+ if (once(`ear-relief-${Math.floor(since / 3)}`, k > 1.0)) flickL = t;
+ break;
+ }
+ case "done":
+ earH = 1.12;
+ earTiltL = earTiltR = -6;
+ break;
+ case "local": {
+ // Real cat ears are mostly still: on each device they sit a touch forward, flick once
+ // shortly after it appears, and on the Mac one ear turns slightly toward where it looks.
+ const loop = Math.floor(since / 7.6);
+ const k = since % 7.6;
+ flicks = false;
+ earTiltL = earTiltR = -3;
+ if (k >= 4.6 && k < 6.0) earTiltR = -8;
+ if (once(`local-phone-${loop}`, k > 1.6)) flickR = t;
+ if (once(`local-mac-${loop}`, k > 4.0)) flickL = t;
+ break;
+ }
+ case "welcome": {
+ const loop = Math.floor(since / 7.2);
+ const k = since % 7.2;
+ const bump = (from: number, len: number) =>
+ k >= from && k < from + len ? Math.sin(((k - from) / len) * Math.PI) : 0;
+ // Up and forward on seeing you; during each cheek rub the ear on that side folds back;
+ // relaxed and a little out while purring; one ear forward with the curious tilt.
+ earH = k < 1.5 ? 1.18 : k >= 3.3 && k < 4.9 ? 0.92 : 1;
+ earTiltL = k < 1.5 ? -7 : k < 3.3 ? 26 * bump(1.5, 0.9) : k < 4.9 ? 9 : 0;
+ earTiltR = k < 1.5 ? -7 : k < 3.3 ? 26 * bump(2.4, 0.9) : k < 4.9 ? 9 : k < 6.2 ? -10 : 0;
+ if (once(`welcome-pop-l-${loop}`, k > 0.05)) flickL = t;
+ if (once(`welcome-pop-r-${loop}`, k > 0.15)) flickR = t;
+ if (once(`welcome-curious-${loop}`, k > 5.3)) flickR = t;
+ if (once(`welcome-settle-${loop}`, k > 6.8)) flickL = t;
+ flicks = false;
+ break;
+ }
+ case "ready": {
+ const loop = Math.floor(since / 8);
+ const k = since % 8;
+ // Ears perk before the hello and stay up through it, with one flick on the way.
+ earH = k > 2.5 && k < 4.6 ? 1.12 : 1;
+ earTiltL = earTiltR = k > 2.5 && k < 4.6 ? -5 : 0;
+ if (once(`ready-flick-${loop}`, k > 2.55)) flickL = t;
+ if (once(`ready-flick-r-${loop}`, k > 2.75)) flickR = t;
+ break;
+ }
+ default:
+ }
+ if (flicks && t > nextFlick) {
+ if (Math.random() < 0.5) flickL = t;
+ else flickR = t;
+ // Sometimes the other ear answers a beat later.
+ if (Math.random() < 0.2) {
+ if (flickL === t) flickR = t + 0.18;
+ else flickL = t + 0.18;
+ }
+ nextFlick = t + (id === "resting" ? 7 : 3.5) + Math.random() * 5;
+ }
+
+ if (saccades && t > nextSaccade) {
+ const a = Math.random() * Math.PI * 2;
+ const r = Math.sqrt(Math.random());
+ target = { x: Math.cos(a) * r, y: Math.sin(a) * r * 0.7 };
+ nextSaccade = t + saccadeGap * (0.4 + Math.random() * 1.2);
+ if (Math.random() < 0.15) blink(t);
+ }
+ if (saccades) {
+ gx = target.x;
+ gy = target.y;
+ }
+
+ const range = o.gazeRange;
+ sim.gx = approach(sim.gx, gx * range, gazeRate, dt);
+ sim.gy = approach(sim.gy, gy * range, gazeRate, dt);
+ sim.turn = approach(sim.turn, gx * range, 6, dt);
+ sim.squint = approach(sim.squint, squint, 6, dt);
+ sim.glasses = approach(sim.glasses, glasses, 7, dt);
+ sim.earH = approach(sim.earH, earH, 9, dt);
+ tiltL = approach(tiltL, earTiltL, 9, dt);
+ tiltR = approach(tiltR, earTiltR, 9, dt);
+ sim.earL = tiltL + 26 * flick(t - flickL);
+ sim.earR = tiltR + 26 * flick(t - flickR);
+ sim.shake = shake;
+ sim.tilt = approach(sim.tilt, tilt, 7, dt);
+ sim.bob = bob;
+ sim.phone = approach(sim.phone, phone, 6, dt);
+ sim.mac = approach(sim.mac, mac, 6, dt);
+ // Gears turn only while calling a tool; after, the eyes settle to the nearest upright turn.
+ sim.spin = id === "tool" ? spin : approach(sim.spin, Math.round(sim.spin / 180) * 180, 8, dt);
+ sim.happy = approach(sim.happy, happy, 10, dt);
+ sim.size = approach(sim.size, size, id === "memory" ? 6 : 9, dt);
+ sim.asym = approach(sim.asym, asym, 6, dt);
+ sim.sleep = approach(sim.sleep, sleep, id === "resting" ? 1.8 : sleepRate, dt);
+ sim.bracketL = approach(sim.bracketL, bracketL, 9, dt);
+ sim.bracketR = approach(sim.bracketR, bracketR, 9, dt);
+ sim.jitter = jitter ? (Math.random() - 0.5) * jitter : approach(sim.jitter, 0, 20, dt);
+ sim.lift = lift ? lift : approach(sim.lift, 0, 20, dt);
+ sim.fill = fill;
+
+ if (blinks && t > nextBlink) {
+ blink(t);
+ nextBlink = t + (3 + Math.random() * 4) / Math.max(0.1, o.blinkRate);
+ }
+ if (pairAt > 0 && t > pairAt) {
+ blinkAt = t;
+ pairAt = -1;
+ }
+ sim.blinkL = lid(t - blinkAt);
+ sim.blinkR = lid(t - blinkAt - 0.012);
+
+ // Resting: small squares drift up, one every ~1.2 s.
+ for (const z of zs) z.age += dt;
+ while (zs.length && zs[0]!.age > 3) zs.shift();
+ if (id === "resting" && sim.sleep > 0.7 && t > nextZ) {
+ zs.push({ id: (zid += 1), age: 0 });
+ nextZ = t + 1.2;
+ }
+ sim.zs = zs.map((z) => ({ ...z }));
+ sim.breath = Math.sin((t / 3.6) * Math.PI * 2);
+ };
+
+ let frame = 0;
+ let last = performance.now();
+ if (reduced) {
+ for (let i = 0; i < 90; i += 1) step(1 / 30);
+ setFace({ ...sim, blinkL: 0, blinkR: 0 });
+ return () => window.removeEventListener("pointermove", onMove);
+ }
+ const tick = (now: number) => {
+ step(Math.min(now - last, 64) / 1000);
+ last = now;
+ setFace({ ...sim });
+ frame = requestAnimationFrame(tick);
+ };
+ frame = requestAnimationFrame(tick);
+ return () => {
+ cancelAnimationFrame(frame);
+ window.removeEventListener("pointermove", onMove);
+ };
+ }, [stage, opts.restartKey, reduced, poseKey]);
+
+ return face;
+}
diff --git a/apps/mirai-gui/client/src/components/uzu-cat/face.tsx b/apps/mirai-gui/client/src/components/uzu-cat/face.tsx
new file mode 100644
index 000000000..1aff37bed
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/uzu-cat/face.tsx
@@ -0,0 +1,1120 @@
+import type { ReactNode } from "react";
+import type { Face } from "./engine";
+
+/*
+ * The uzu cat: a matrix face, [ eyes ] in square brackets, with cat ears on the bracket corners.
+ * It lives in a 160 box. The engine (engine.ts) decides what the face does; this file draws it.
+ */
+
+export type Settings = {
+ state: string;
+ brackets: string;
+ eyeShape: string;
+ weight: number;
+ eyeSize: number;
+ gap: number;
+ spread: number;
+ bracketHeight: number;
+ blinkRate: number;
+ gazeRange: number;
+ speed: number;
+ /** Eye corner radius as a share of the eye's short side. */
+ eyeRadius: number;
+ /** Happy eyes: 'caret' (^), 'vee' (v) or 'bar' (a flat squint). */
+ happyShape: string;
+ /** Cat ears on the bracket corners: 'none', 'cat' (outline) or 'cat-solid'. */
+ ears: string;
+ /** How much detail survives: 'full', or simplified drawings for 'medium' and 'tiny' sizes. */
+ detail?: string;
+ /** Eye width as a share of its height (1 = square). */
+ eyeAspect?: number;
+ /** Ear size multiplier. */
+ earScale?: number;
+ /** Outline ears: draw the bracket's top arm under the ear (closed) or leave it open. */
+ earBase?: boolean;
+ /** Ear height as a share of its width. */
+ earRise?: number;
+ /** Where the tip sits over the base: 0 straight above the outer foot, 1 above the inner foot. */
+ earTip?: number;
+ /** How far the ear sits in from the bracket's corner, in box units. */
+ earInset?: number;
+ /** Ears react to the states (flatten, perk up, flick); off keeps them still. */
+ earMotion?: boolean;
+ /** Corner radius for the brackets, on the line's centre, in box units. */
+ cornerRadius?: number;
+ /** Corner radius for the ears (tip and feet); falls back to the bracket radius when unset. */
+ earRadius?: number;
+ /** Round the open ends of the bracket arms instead of cutting them square. */
+ roundEnds?: boolean;
+ /** Box units per screen pixel at the size being drawn (set by forSize); keeps gaps ≥ ~1 px. */
+ unit?: number;
+ /** The top line runs on past the ear (true) or stops where the ear ends (false). */
+ earArm?: boolean;
+ /** Eye symbol: 'block' (solid), 'zero' (outlined), 'slashed' (0 with a slash), 'dotted' (0 with a dot). */
+ eyeSymbol?: string;
+ /** Separate eyelids: a lid line over each eye, with a gap below it. */
+ eyelids?: boolean;
+ /** How much of the eye the lids cover at rest, 0..0.7. */
+ lidSize?: number;
+ /** Pixel zeros: grid columns and rows, top and bottom bar widths, side thickness (all in
+ * pixels), and the gap between pixels as a share of a pixel (0 = solid, >0 = LED matrix). */
+ pxCols?: number;
+ pxRows?: number;
+ pxTop?: number;
+ pxBottom?: number;
+ pxSide?: number;
+ pxGap?: number;
+ /** Pixel zeros: corner radius of each pixel, as a share of the pixel (0..0.5). */
+ pxRound?: number;
+ /** Internal, set during the device morph: a fixed ear base width, and how far the line past
+ * the ear has grown toward the middle (0..1) when `earArm` is off. */
+ earB?: number;
+ armGrow?: number;
+};
+
+export type CharacterProps = {
+ f: Face;
+ s: Settings;
+ ink: string;
+ paper: string;
+ /** Unique per rendered SVG, for clip ids. */
+ uid?: string;
+ /** Fill the inside of the outline (head and ears) with this colour, e.g. for a sticker's die-cut. */
+ backing?: string;
+};
+export type Character = {
+ id: string;
+ name: string;
+ draw: (p: CharacterProps) => ReactNode;
+};
+
+const f1 = (n: number) => Math.round(n * 10) / 10;
+
+/* ------------------------------------------------------------------ rounded corners */
+
+type Pt = [number, number];
+
+/**
+ * A polyline with its corners filleted at radius `r` (on the line's centre), so a stroke keeps an
+ * even weight round the bend: outer edge r + w/2, inner edge r - w/2. Each fillet takes at most
+ * half of a shared segment, so tight corners (an ear's tip) shrink their radius instead of
+ * overlapping. `roundAt` picks which vertices get rounded.
+ */
+function roundedPath(
+ pts: Pt[],
+ r: number | ((i: number) => number),
+ closed = false,
+ roundAt: (i: number) => boolean = () => true,
+): string {
+ const n = pts.length;
+ const p = (q: Pt) => `${f1(q[0])} ${f1(q[1])}`;
+ // One radius for every corner, or a radius per vertex.
+ const radiusAt = typeof r === "function" ? r : () => r;
+ if (typeof r === "number" && r <= 0.05) return `M${pts.map(p).join(" L")}${closed ? " Z" : ""}`;
+ let d = "";
+ for (let i = 0; i < n; i += 1) {
+ const P = pts[i]!;
+ const end = !closed && (i === 0 || i === n - 1);
+ const A = pts[(i - 1 + n) % n]!;
+ const B = pts[(i + 1) % n]!;
+ const la = Math.hypot(A[0] - P[0], A[1] - P[1]);
+ const lb = Math.hypot(B[0] - P[0], B[1] - P[1]);
+ const plain = () => {
+ d += `${d ? " L" : "M"}${p(P)}`;
+ };
+ const ri = radiusAt(i);
+ if (end || !roundAt(i) || ri <= 0.05 || la < 1e-6 || lb < 1e-6) {
+ plain();
+ continue;
+ }
+ const da: Pt = [(A[0] - P[0]) / la, (A[1] - P[1]) / la];
+ const db: Pt = [(B[0] - P[0]) / lb, (B[1] - P[1]) / lb];
+ const angle = Math.acos(Math.max(-1, Math.min(1, da[0] * db[0] + da[1] * db[1])));
+ if (angle > Math.PI - 0.01) {
+ plain(); // straight through
+ continue;
+ }
+ const half = Math.tan(angle / 2);
+ const maxA = closed || i - 1 > 0 ? la / 2 : la;
+ const maxB = closed || i + 1 < n - 1 ? lb / 2 : lb;
+ const tan = Math.min(ri / half, maxA, maxB);
+ const rr = tan * half;
+ const P1: Pt = [P[0] + da[0] * tan, P[1] + da[1] * tan];
+ const P2: Pt = [P[0] + db[0] * tan, P[1] + db[1] * tan];
+ // Turning clockwise on screen (y down) is a positive cross product: sweep 1.
+ const sweep = (P[0] - A[0]) * (B[1] - P[1]) - (P[1] - A[1]) * (B[0] - P[0]) > 0 ? 1 : 0;
+ d += `${d ? " L" : "M"}${p(P1)} A${f1(rr)} ${f1(rr)} 0 0 ${sweep} ${p(P2)}`;
+ }
+ return closed ? `${d} Z` : d;
+}
+
+/* ------------------------------------------------------------------ brackets */
+
+function bracket(
+ style: string,
+ side: -1 | 1,
+ cx: number,
+ h: number,
+ w: number,
+ ink: string,
+ key: string,
+ radius = 0,
+ roundEnds = false,
+ armLen?: number,
+) {
+ const top = 80 - h / 2;
+ const bottom = 80 + h / 2;
+ const x = cx; // the bracket's spine
+ const arm = (armLen ?? Math.max(w * 1.6, h * 0.2)) * -side; // arms point inward
+ const common = {
+ stroke: ink,
+ strokeWidth: w,
+ fill: "none",
+ strokeLinejoin: "miter" as const,
+ strokeMiterlimit: 10,
+ };
+ if (style === "none") return null;
+ if (style === "bars") return <path key={key} d={`M${f1(x)} ${f1(top)} V${f1(bottom)}`} {...common} />;
+ if (style === "round") {
+ return (
+ <path
+ key={key}
+ d={`M${f1(x + arm)} ${f1(top)} Q${f1(x - arm * 0.6)} 80 ${f1(x + arm)} ${f1(bottom)}`}
+ {...common}
+ strokeLinecap="round"
+ />
+ );
+ }
+ if (style === "angle")
+ return <path key={key} d={`M${f1(x + arm)} ${f1(top)} L${f1(x)} 80 L${f1(x + arm)} ${f1(bottom)}`} {...common} />;
+ if (style === "curly") {
+ const a = arm * 0.9;
+ return (
+ <path
+ key={key}
+ d={`M${f1(x + a)} ${f1(top)} C${f1(x)} ${f1(top)} ${f1(x + a * 0.15)} ${f1(top + h * 0.12)} ${f1(x + a * 0.15)} ${f1(80 - h * 0.14)} C${f1(x + a * 0.15)} ${f1(80 - h * 0.04)} ${f1(x - a * 0.55)} 80 ${f1(x - a * 0.55)} 80 C${f1(x - a * 0.55)} 80 ${f1(x + a * 0.15)} ${f1(80 + h * 0.04)} ${f1(x + a * 0.15)} ${f1(80 + h * 0.14)} C${f1(x + a * 0.15)} ${f1(bottom - h * 0.12)} ${f1(x)} ${f1(bottom)} ${f1(x + a)} ${f1(bottom)}`}
+ {...common}
+ strokeLinecap="round"
+ />
+ );
+ }
+ // Square: a spine with short arms, square-ended like matrix notation.
+ const pts: Pt[] = [
+ [x + arm, top + w / 2],
+ [x, top + w / 2],
+ [x, bottom - w / 2],
+ [x + arm, bottom - w / 2],
+ ];
+ return <path key={key} d={roundedPath(pts, radius)} {...common} strokeLinecap={roundEnds ? "round" : "butt"} />;
+}
+
+/** How far the face sits below centre to look optically centred (ears add height on top). */
+export function faceShift(s: Settings) {
+ return s.ears !== "none" && s.brackets === "square" ? earSize(s).rise * 0.42 : 0;
+}
+
+/* ------------------------------------------------------------------ cat ears */
+
+/**
+ * Cat ear proportions, on the stroke's centreline. The base runs from the spine inward; at rest the
+ * tip sits straight above the spine, so the outer edge is the spine carried on up and only the
+ * inner edge is angled.
+ */
+export function earSize(s: Settings) {
+ // Small drawings carry heavier lines, so the ear's minimum is held back to keep it an ear, not a
+ // block: the face stays the main shape.
+ const k = s.earScale ?? 1;
+ const B =
+ s.earB ??
+ k *
+ (s.detail === "tiny"
+ ? Math.max(s.weight * 2.2, s.bracketHeight * 0.34)
+ : s.detail === "medium"
+ ? Math.max(s.weight * 3, s.bracketHeight * 0.4)
+ : Math.max(s.weight * 3.6, s.bracketHeight * 0.42));
+ return {
+ B,
+ rise: B * (s.earRise ?? 0.8),
+ tip: s.earTip ?? 0,
+ inset: s.earInset ?? 0,
+ };
+}
+
+/**
+ * A square bracket wearing a cat ear, drawn as one stroke so every join is a true miter: up the
+ * spine and straight on to the ear's tip, down its angled inner edge, then on along the top arm,
+ * which also runs under the ear. The solid version fills the ear too.
+ */
+function catBracket(
+ side: -1 | 1,
+ x: number,
+ h: number,
+ f: Face,
+ s: Settings,
+ ink: string,
+ armLen?: number,
+ backing?: string,
+) {
+ const w = s.weight;
+ const topC = 80 - h / 2 + w / 2;
+ const botC = 80 + h / 2 - w / 2;
+ const arm = armLen ?? Math.max(w * 1.6, h * 0.2);
+ const ear = earSize(s);
+ const { rise, tip: tipAt } = ear;
+ // While the brackets close into a device (armLen given), nothing on the top line may reach past
+ // the middle: the folded ear and the arm's end stop at the centre, where the other half takes
+ // over, so the top edge ends exactly at the device's sides instead of overhanging like a shelf.
+ const reach = armLen !== undefined ? Math.abs(80 - x) : Infinity;
+ const inset = Math.min(ear.inset, reach);
+ const B = Math.min(ear.B, reach - inset);
+ const inward = -side;
+ const foot = x + inward * inset; // the ear's outer foot on the top arm
+ const inner = foot + inward * B;
+ // The tip pivots on the outer foot. At rest it sits `tipAt` of the way along the base; the
+ // engine leans it out or forward and makes it shorter or taller.
+ const moving = s.earMotion !== false;
+ const lean = moving ? ((side < 0 ? f.earL : f.earR) * Math.PI) / 180 : 0;
+ const u0 = tipAt * B;
+ const h0 = rise * (moving ? f.earH : 1);
+ const u = u0 * Math.cos(lean) - h0 * Math.sin(lean);
+ const v = u0 * Math.sin(lean) + h0 * Math.cos(lean);
+ const tip: [number, number] = [foot + inward * u, topC - v];
+ const solid = s.ears === "cat-solid" || s.detail === "tiny";
+ const baseOn = solid || s.earBase !== false;
+ // The line past the ear: on by default; off ends the line where the ear ends. On a device it
+ // grows back in toward the middle so the outline still closes.
+ const afterOff =
+ s.earArm === false ? (s.armGrow ?? 0) * Math.max(0, (Number.isFinite(reach) ? reach : 0) - B - inset) : 0;
+ const hasArm = s.earArm !== false || afterOff > 0.05;
+ const topArmEnd =
+ s.earArm !== false
+ ? x + inward * Math.min(reach, B + inset + Math.max(w * 1.2, arm - B - inset))
+ : inner + inward * afterOff;
+ const r = s.cornerRadius ?? 0;
+ // The ear has its own radius (tip and both feet); the bracket's corners keep theirs. With no
+ // inset the top corner is the ear's outer foot, so it takes the ear's radius.
+ const earR = s.earRadius ?? r;
+ const common = {
+ stroke: ink,
+ strokeWidth: w,
+ strokeLinejoin: "miter" as const,
+ strokeMiterlimit: 12,
+ strokeLinecap: s.roundEnds ? ("round" as const) : ("butt" as const),
+ };
+ // The contour: bottom arm, spine, (along the top arm to the ear), up to the tip, down, top arm.
+ // With no line past the ear and a base under it, the stroke turns at the inner foot and runs
+ // back along the base, so that corner is a true miter instead of a cut end.
+ const tail: Pt[] = hasArm ? [[topArmEnd, topC]] : baseOn ? [[foot, topC]] : [];
+ const pts: Pt[] = [
+ [x + inward * arm, botC],
+ [x, botC],
+ [x, topC],
+ ...(inset > 0.05 ? [[foot, topC] as Pt] : []),
+ tip,
+ [inner, topC],
+ ...tail,
+ ];
+ const earStart = inset > 0.05 ? 3 : 2;
+ // The run under the ear starts where the top corner's rounding ends, so it never squares a
+ // rounded corner back up, and runs on to the arm's end so the ear's feet stay filled below.
+ const cornerAt = inset > 0.05 ? Math.min(r, inset / 2) : 0;
+ const baseFrom = x + inward * cornerAt;
+ const base = baseOn && hasArm ? ` M${f1(baseFrom)} ${f1(topC)} H${f1(topArmEnd)}` : "";
+ return (
+ <g key={side}>
+ {backing ? (
+ <path d={roundedPath([[foot, topC], tip, [inner, topC]], earR, true, (i) => i === 1)} fill={backing} />
+ ) : null}
+ {solid ? (
+ <path d={roundedPath([[foot, topC], tip, [inner, topC]], earR, true, (i) => i === 1)} fill={ink} />
+ ) : null}
+ {/* One path: the contour plus the arm under the ear as a second run inside the contour's own
+ band, so the joins stay true miters (or even fillets) and nothing meets on a seam. */}
+ <path d={`${roundedPath(pts, (i) => (i >= earStart ? earR : r))}${base}`} fill="none" {...common} />
+ </g>
+ );
+}
+
+function Brackets({
+ f,
+ s,
+ ink,
+ spread,
+ height,
+ left = 0,
+ right = 0,
+ arm,
+ backing,
+}: {
+ f: Face;
+ s: Settings;
+ ink: string;
+ spread: number;
+ height: number;
+ left?: number;
+ right?: number;
+ arm?: number;
+ backing?: string;
+}) {
+ const h = height * (1 + 0.012 * f.breath);
+ const cat = s.ears !== "none" && s.brackets === "square";
+ // Small sizes exaggerate the bracket moves so they still read at a few pixels.
+ const k = s.detail === "tiny" ? 1.8 : s.detail === "medium" ? 1.4 : 1;
+ const xl = 80 - spread - left * k;
+ const xr = 80 + spread + right * k;
+ if (cat) {
+ return (
+ <>
+ {backing ? (
+ <rect
+ x={f1(xl - s.weight / 2)}
+ y={f1(80 - h / 2)}
+ width={f1(xr - xl + s.weight)}
+ height={f1(h)}
+ rx={f1((s.cornerRadius ?? 0) + s.weight / 2)}
+ fill={backing}
+ />
+ ) : null}
+ {catBracket(-1, xl, h, f, s, ink, arm, backing)}
+ {catBracket(1, xr, h, f, s, ink, arm, backing)}
+ </>
+ );
+ }
+ return (
+ <>
+ {backing ? (
+ <rect
+ x={f1(xl - s.weight / 2)}
+ y={f1(80 - h / 2)}
+ width={f1(xr - xl + s.weight)}
+ height={f1(h)}
+ rx={f1((s.cornerRadius ?? 0) + s.weight / 2)}
+ fill={backing}
+ />
+ ) : null}
+ {bracket(s.brackets, -1, xl, h, s.weight, ink, "l", s.cornerRadius ?? 0, s.roundEnds, arm)}
+ {bracket(s.brackets, 1, xr, h, s.weight, ink, "r", s.cornerRadius ?? 0, s.roundEnds, arm)}
+ </>
+ );
+}
+
+/**
+ * Stays on device: the face turns into an iPhone (a plain outline, no island), then a Mac. The brackets move to the device's
+ * width and height and their arms grow until they meet in the middle, closing the outline, while
+ * the eyes shrink onto the screen. The ears stay on: same size as on the face, sitting at the
+ * device's top corners, pulled in only if a narrow phone needs the room. Corners stay as sharp
+ * as the face's own corner radius setting.
+ */
+const PHONE = { half: 30, height: 100, eyes: 0.6 };
+const MAC = { half: 60, height: 70, eyes: 0.85 };
+function withDevice(s: Settings, f: Face) {
+ const phone = f.phone ?? 0;
+ const mac = f.mac ?? 0;
+ const closing = Math.min(1, phone + mac);
+ if (closing < 0.001) return { s, phone: 0, mac: 0, arm: undefined, devY: 0 };
+ const ease = (x: number) => x * x * (3 - 2 * x);
+ const shape = ease(closing);
+ // Which device we're heading to (or between, during phone to Mac), scaled by how far along.
+ const phoneW = (phone / closing) * shape;
+ const macW = (mac / closing) * shape;
+ const spread = s.spread + (PHONE.half - s.spread) * phoneW + (MAC.half - s.spread) * macW;
+ const bracketHeight =
+ s.bracketHeight + (PHONE.height - s.bracketHeight) * phoneW + (MAC.height - s.bracketHeight) * macW;
+ const scale = 1 - (1 - PHONE.eyes) * phoneW - (1 - MAC.eyes) * macW;
+ // Ears keep the face's size; on a device narrower than the ears' span they move in together.
+ const ear = earSize(s);
+ const span = ear.inset + ear.B;
+ const room = (half: number) => Math.min(1, (half - Math.max(s.weight * 1.2, 4)) / Math.max(1, span));
+ const fit = 1 - (1 - room(PHONE.half)) * phoneW - (1 - room(MAC.half)) * macW;
+ const out: Settings = {
+ ...s,
+ spread,
+ bracketHeight,
+ eyeSize: s.eyeSize * scale,
+ gap: s.gap * scale,
+ earB: ear.B * fit,
+ earInset: ear.inset * fit,
+ armGrow: shape,
+ };
+ const arm = lerp(Math.max(s.weight * 1.6, bracketHeight * 0.2), spread, shape);
+ return { s: out, phone: phoneW, mac: macW, arm, devY: -5 * macW };
+}
+
+/* ------------------------------------------------------------------ eye illustrations */
+
+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+const hash = (n: number) => {
+ const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;
+ return x - Math.floor(x);
+};
+
+/**
+ * Writing: the eyes become one page of text spanning the whole face, bracket to bracket. Tokens
+ * land whole, a block cursor follows the last one, a paragraph's last line runs short, and the
+ * page scrolls a line at a time.
+ */
+function lineTokens(j: number, W: number, gap: number, small = false) {
+ const short = j % 3 === 2; // a paragraph ends every third line
+ const n = small
+ ? short
+ ? 1
+ : 2 + (hash(j) > 0.5 ? 1 : 0)
+ : short
+ ? 2 + (hash(j) > 0.5 ? 1 : 0)
+ : 3 + Math.floor(hash(j) * 3);
+ const raw = Array.from({ length: n }, (_, k) => 0.55 + hash(j * 7 + k + 1));
+ const sum = raw.reduce((a, b) => a + b, 0);
+ const room = W * (short ? 0.5 : 1) - gap * (n - 1);
+ return raw.map((r) => (r / sum) * room);
+}
+
+function textBlock(
+ x0: number,
+ x1: number,
+ cy: number,
+ E: number,
+ written: number,
+ ink: string,
+ small = false,
+ round = 0,
+): ReactNode {
+ // Small sizes: two thick lines instead of three, fewer and longer tokens.
+ const rows = small ? 2 : 3;
+ const W = x1 - x0;
+ const gap = Math.max(2, E * (small ? 0.12 : 0.08));
+ const th = E * (small ? 0.3 : 0.17);
+ const pitch = small ? E - th : E * 0.33;
+ // Find the line being written and how many of its tokens are down.
+ let left = Math.floor(written);
+ let L = 0;
+ for (;;) {
+ const n = lineTokens(L, W, gap, small).length;
+ if (left < n) break;
+ left -= n;
+ L += 1;
+ }
+ const first = Math.max(0, L - (rows - 1));
+ const bars: ReactNode[] = [];
+ for (let l = first; l <= L; l += 1) {
+ const widths = lineTokens(l, W, gap, small);
+ const shown = l < L ? widths.length : left;
+ const y = cy - E / 2 + (small ? 0 : E * 0.085) + (l - first) * pitch;
+ let x = x0;
+ for (let k = 0; k < shown; k += 1) {
+ bars.push(
+ <rect
+ key={`${l}-${k}`}
+ x={f1(x)}
+ y={f1(y)}
+ width={f1(widths[k]!)}
+ height={f1(th)}
+ rx={f1((th / 2) * round)}
+ fill={ink}
+ />,
+ );
+ x += widths[k]! + gap;
+ }
+ if (l === L)
+ bars.push(
+ <rect
+ key="cursor"
+ x={f1(x)}
+ y={f1(y)}
+ width={f1(th * 0.9)}
+ height={f1(th)}
+ rx={f1((th / 2) * round)}
+ fill={ink}
+ />,
+ );
+ }
+ return bars;
+}
+
+/* ------------------------------------------------------------------ pixel zeros */
+
+/** Pixel zeros, as in pixel monospace fonts. Which inner mark each pixel symbol carries. */
+const PIXEL_KINDS: Record<string, "none" | "slash" | "dot"> = {
+ pixel: "none",
+ "pixel-slashed": "slash",
+ "pixel-dotted": "dot",
+};
+
+/**
+ * A bitmap zero on a cols x rows grid: a top bar and a bottom bar (centred, their own widths, so
+ * narrower bars cut the corners like a pixel font), sides of the given thickness, and an
+ * optional slash (bottom-left to top-right) or centre dot inside.
+ */
+function pixelZero(s: Settings, inner: "none" | "slash" | "dot"): string[] {
+ const cols = Math.round(Math.min(9, Math.max(3, s.pxCols ?? 5)));
+ const rows = Math.round(Math.min(11, Math.max(4, s.pxRows ?? 7)));
+ const side = Math.round(Math.min(Math.floor((cols - 1) / 2), Math.max(1, s.pxSide ?? 1)));
+ const topW = Math.round(Math.min(cols, Math.max(1, s.pxTop ?? cols - 2)));
+ const botW = Math.round(Math.min(cols, Math.max(1, s.pxBottom ?? cols - 2)));
+ const g = Array.from({ length: rows }, () => Array.from({ length: cols }, () => "."));
+ const run = (r: number, w: number) => {
+ const from = Math.floor((cols - w) / 2);
+ for (let c = from; c < from + w; c += 1) g[r]![c] = "#";
+ };
+ for (let r = 0; r < side; r += 1) run(r, topW);
+ for (let r = rows - side; r < rows; r += 1) run(r, botW);
+ for (let r = side; r < rows - side; r += 1) {
+ for (let k = 0; k < side; k += 1) {
+ g[r]![k] = "#";
+ g[r]![cols - 1 - k] = "#";
+ }
+ }
+ const first = side;
+ const last = rows - side - 1;
+ const left = side;
+ const right = cols - side - 1;
+ if (inner === "slash" && right >= left && last > first) {
+ // Leave the interior rows next to the bars clear when there's room, as fonts do.
+ const a = last - first >= 4 ? first + 1 : first;
+ const b = last - first >= 4 ? last - 1 : last;
+ for (let r = a; r <= b; r += 1) {
+ const u = b === a ? 0.5 : (b - r) / (b - a);
+ g[r]![left + Math.round(u * (right - left))] = "#";
+ }
+ }
+ if (inner === "dot" && right >= left && last >= first) {
+ const rs =
+ (last - first) % 2 === 0 ? [(first + last) / 2] : [Math.floor((first + last) / 2), Math.ceil((first + last) / 2)];
+ const cs =
+ (right - left) % 2 === 0 ? [(left + right) / 2] : [Math.floor((left + right) / 2), Math.ceil((left + right) / 2)];
+ rs.forEach((r) => cs.forEach((cc) => (g[r]![cc] = "#")));
+ }
+ return g.map((row) => row.join(""));
+}
+
+/**
+ * One filled path for a glyph. With no gap, each row's runs merge so neighbouring pixels never
+ * show seams; with a gap, every pixel is its own square, like an LED matrix.
+ */
+function pixelPath(rows: string[], x: number, y: number, cell: number, gap = 0, round = 0) {
+ let d = "";
+ const inset = (cell * gap) / 2;
+ // Rounded pixels: every pixel is its own rounded square (radius as a share of the pixel).
+ const r = Math.max(0, Math.min(0.5, round)) * (cell - 2 * inset);
+ const separate = gap > 0 || r > 0.01;
+ rows.forEach((row, ri) => {
+ let c = 0;
+ while (c < row.length) {
+ if (row[c] !== "#") {
+ c += 1;
+ continue;
+ }
+ let end = c + 1;
+ if (!separate) while (end < row.length && row[end] === "#") end += 1;
+ const x0 = x + c * cell + inset;
+ const y0 = y + ri * cell + inset;
+ const x1 = x + end * cell - inset;
+ const y1 = y + (ri + 1) * cell - inset;
+ d +=
+ r > 0.01
+ ? `M${f1(x0 + r)} ${f1(y0)}H${f1(x1 - r)}A${f1(r)} ${f1(r)} 0 0 1 ${f1(x1)} ${f1(y0 + r)}V${f1(y1 - r)}A${f1(r)} ${f1(r)} 0 0 1 ${f1(x1 - r)} ${f1(y1)}H${f1(x0 + r)}A${f1(r)} ${f1(r)} 0 0 1 ${f1(x0)} ${f1(y1 - r)}V${f1(y0 + r)}A${f1(r)} ${f1(r)} 0 0 1 ${f1(x0 + r)} ${f1(y0)}Z`
+ : `M${f1(x0)} ${f1(y0)}H${f1(x1)}V${f1(y1)}H${f1(x0)}Z`;
+ c = end;
+ }
+ });
+ return d;
+}
+
+/* ------------------------------------------------------------------ 1. matrix face */
+
+/*
+ * Everything here is a rectangle. Expressions are lids: the top lid travels most of a blink, the
+ * bottom one rises to make the happy squint. Loading turns the eyes into outlines that fill.
+ */
+const matrixFace: Character = {
+ id: "matrix",
+ name: "Matrix face",
+ draw({ f, s: base, ink, paper, uid = "stage", backing }) {
+ const device = withDevice(base, f);
+ const s = device.s;
+ const spread = s.spread;
+ const aspect = s.eyeAspect ?? 1;
+ const restW = s.eyeSize * aspect;
+ const small = s.detail === "medium" || s.detail === "tiny";
+ const tiny = s.detail === "tiny";
+ // One line weight for everything drawn as a line: brackets, ears, glasses, loader outlines.
+ const line = s.weight;
+ const cat = s.ears !== "none" && s.brackets === "square";
+ // Ears add height on top, so the whole face drops to sit optically centred in its box.
+ const shift = cat ? earSize(s).rise * 0.42 : 0;
+ // Reading goggles: the eyes themselves become the lenses. Each eye hollows out into an
+ // outline a touch bigger than the eye, a solid pupil inside scans the lines, a bridge joins
+ // the lenses and straps run out to the brackets on both sides. The lenses hold still while
+ // reading; only the pupils move. Gaps stay at least about a pixel at the size being drawn.
+ const G = f.glasses;
+ const grow = 1 - (1 - G) ** 3;
+ const unit = s.unit ?? 0.4; // box units per pixel
+ const clear = Math.max(2.5, unit * 1.1);
+ const E = s.eyeSize * f.size * (1 + 0.1 * grow);
+ // Lenses keep the eye's own shape (tall, with its corner rounding) but get wider than the eye,
+ // up to ~0.72 of its height, so a pupil fits; the eyes move out to the lens centres to make
+ // that room. The pupil is a small copy of the eye, same proportions, so it still reads as uzu.
+ const innerHalf = spread - line / 2 - clear - line * 0.5;
+ const bridgeMin = Math.max(line * 1.2, 4, unit * 1.5);
+ const lensW = Math.max(E * aspect, Math.min(E * 0.72, innerHalf - bridgeMin / 2));
+ const lensC = Math.min(Math.max(s.gap / 2, bridgeMin / 2 + lensW / 2), innerHalf - lensW / 2);
+ const W = lerp(E * aspect, lensW, grow);
+ const openX = W - 2 * line - 2 * clear;
+ const openY = E - 2 * line - 2 * clear;
+ const pupilH = Math.max(0, Math.min(openY * 0.74, (openX * 0.88) / Math.max(0.2, aspect)));
+ const pupilW = pupilH * aspect;
+ const showPupil = pupilW > unit * 0.8;
+ const pupilX = Math.max(0, (openX - pupilW) / 2);
+ const pupilY = Math.max(0, (openY - pupilH) / 2);
+ const ox = Math.max(1.5, spread - s.weight - restW / 2 - s.gap / 2 - 3) * (1 - grow);
+ const oy = Math.max(1.5, s.bracketHeight / 2 - s.weight - s.eyeSize / 2 - 3) * (1 - grow);
+ const eyeC = lerp(s.gap / 2, lensC, grow);
+ const minH = Math.max(2, s.weight * 0.55);
+ const eyes = [-1, 1].map((side) => {
+ const b = side < 0 ? f.blinkL : f.blinkR;
+ const closed = Math.max(b, f.sleep);
+ const squint = f.squint + (side === 1 ? 0.18 * f.asym : 0);
+ // A hint of head turn: the eye on the side being looked at gets a little wider.
+ const w = W * (1 + 0.1 * f.turn * side) * (1 + 0.05 * f.happy) * (1 + 0.03 * b);
+ const cx = 80 + side * eyeC + f.gx * ox + f.jitter;
+ const cy = 80 + f.gy * oy + f.lift - E * 0.05 * f.happy;
+ const h = E;
+ const bar = s.happyShape === "bar" ? f.happy : 0;
+ let top = cy - h / 2 + h * (0.8 * closed + 0.2 * squint);
+ let bottom = cy + h / 2 - h * (0.12 * closed + 0.15 * squint + 0.62 * bar);
+ if (bottom - top < minH) {
+ const mid = (top + bottom) / 2;
+ top = mid - minH / 2;
+ bottom = mid + minH / 2;
+ }
+ // Separate eyelids: the lid comes down from the top as its own line (a gap under it), resting
+ // at the lid size and closing all the way for blinks and sleep. Only the top lid moves.
+ let lid: { y: number; top: number; bottom: number } | null = null;
+ if (s.eyelids) {
+ const rest = Math.min(0.7, Math.max(0, s.lidSize ?? 0.3));
+ const L = Math.min(1, rest + (1 - rest) * closed + 0.2 * squint);
+ const lidY = cy - h / 2 + h * L;
+ const gapUnder = Math.max(2, unit);
+ lid = {
+ y: lidY,
+ top: lidY + line / 2 + gapUnder,
+ bottom: cy + h / 2 - h * (0.15 * squint + 0.62 * bar),
+ };
+ }
+ return {
+ side,
+ x: cx - w / 2,
+ y: top,
+ w,
+ h: bottom - top,
+ cx,
+ cy,
+ closed: Math.max(closed, b),
+ lid,
+ };
+ });
+ // Calling a tool: each eye turns round its own centre, and shrinks just enough at every angle
+ // that its turned width stays inside the space between the eyes, so the two never touch.
+ const gearTransform = (e: { side: number; w: number; h: number; cx: number; cy: number }) => {
+ const spin = f.spin ?? 0;
+ if (Math.abs(spin % 180) < 0.05) return undefined;
+ const a = (spin * e.side * Math.PI) / 180;
+ const turned = e.w * Math.abs(Math.cos(a)) + e.h * Math.abs(Math.sin(a));
+ const room = s.gap - Math.max(3, line, unit * 1.2);
+ const k = turned > room ? Math.max(0.2, room / turned) : 1;
+ return `rotate(${f1(spin * e.side)} ${f1(e.cx)} ${f1(e.cy)}) translate(${f1(e.cx)} ${f1(e.cy)}) scale(${k.toFixed(3)}) translate(${f1(-e.cx)} ${f1(-e.cy)})`;
+ };
+ // Lids reach a little past the eye on both sides, but never so far that the two lids meet.
+ const lidOver = Math.max(
+ 0,
+ Math.min(line * 0.6, (eyes[1]!.x - (eyes[0]!.x + eyes[0]!.w) - Math.max(2, unit * 1.2)) / 2),
+ );
+ // The eye's symbol in a box: a solid block, or a zero (outlined, optionally slashed or dotted).
+ // A zero squashed thinner than its own outline (mid-blink) is drawn solid, like a closed eye.
+ const symbol = (
+ box: { x: number; y: number; w: number; h: number },
+ key: string | number,
+ full?: { x: number; y: number; w: number; h: number },
+ ) => {
+ if (box.h < 0.3 || box.w < 0.3) return null;
+ let kind = s.eyeSymbol ?? "block";
+ if (kind === "none") return null; // icons draw their own symbol in place of the eyes
+ // Heart eyes: a heart sized to the eye's height (and no wider than the space between the
+ // eyes allows), centred on the eye. Half-closed (a blink) it reads as a closed eye.
+ if (kind === "heart") {
+ const area = full ?? box;
+ if (box.h < area.h * 0.5)
+ return (
+ <rect key={key} x={f1(box.x)} y={f1(box.y)} width={f1(box.w)} height={f1(box.h)} rx={rx(box)} fill={ink} />
+ );
+ const z = Math.min(area.h * 1.05, s.gap - Math.max(3, line, unit * 1.2), Math.max(area.w, area.h) * 1.1);
+ const hx = box.x + box.w / 2;
+ const hy = area.y + area.h / 2 + z * 0.06;
+ return (
+ <path
+ key={key}
+ d={`M${f1(hx)} ${f1(hy + z * 0.42)} C${f1(hx - z * 0.62)} ${f1(hy + z * 0.02)} ${f1(hx - z * 0.5)} ${f1(hy - z * 0.52)} ${f1(hx)} ${f1(hy - z * 0.2)} C${f1(hx + z * 0.5)} ${f1(hy - z * 0.52)} ${f1(hx + z * 0.62)} ${f1(hy + z * 0.02)} ${f1(hx)} ${f1(hy + z * 0.42)} Z`}
+ fill={ink}
+ />
+ );
+ }
+ // Pixel zeros: a 5x7 bitmap glyph with square pixels, laid out in the eye's full box and
+ // cut by the lid (blink, eyelids) row by row rather than squashed. Too small to read (a
+ // pixel under ~1.2 screen px) and they fall back to the outlined zero.
+ const pk = PIXEL_KINDS[kind];
+ if (pk) {
+ const glyph = pixelZero(s, pk);
+ const cols = glyph[0]!.length;
+ const rowsN = glyph.length;
+ const area = full ?? box;
+ const cell = Math.min(area.w / cols, area.h / rowsN);
+ if (cell >= unit * 1.2) {
+ if (box.h < cell * 1.2)
+ return <rect key={key} x={f1(box.x)} y={f1(box.y)} width={f1(box.w)} height={f1(box.h)} fill={ink} />;
+ const gx0 = area.x + (area.w - cell * cols) / 2;
+ const gy0 = area.y + (area.h - cell * rowsN) / 2;
+ const id = `uzu-px-${uid}-${key}`;
+ return (
+ <g key={key}>
+ <clipPath id={id}>
+ <rect x={f1(box.x - 1)} y={f1(box.y)} width={f1(box.w + 2)} height={f1(box.h)} />
+ </clipPath>
+ <path
+ d={pixelPath(glyph, gx0, gy0, cell, Math.min(0.45, Math.max(0, s.pxGap ?? 0)), s.pxRound ?? 0)}
+ fill={ink}
+ clipPath={`url(#${id})`}
+ />
+ </g>
+ );
+ }
+ kind = "zero";
+ }
+ const solid = kind === "block" || box.h < 2 * line + 1.2 || box.w < 2 * line + 1.2;
+ if (solid)
+ return (
+ <rect key={key} x={f1(box.x)} y={f1(box.y)} width={f1(box.w)} height={f1(box.h)} rx={rx(box)} fill={ink} />
+ );
+ const innerW = box.w - 2 * line;
+ const innerH = box.h - 2 * line;
+ const detail = tiny ? "zero" : kind;
+ const dot = Math.min(innerW, innerH) * 0.42;
+ return (
+ <g key={key}>
+ <rect
+ x={f1(box.x + line / 2)}
+ y={f1(box.y + line / 2)}
+ width={f1(box.w - line)}
+ height={f1(box.h - line)}
+ rx={outlineRx(box)}
+ fill="none"
+ stroke={ink}
+ strokeWidth={f1(line)}
+ />
+ {detail === "slashed" && innerW > line * 1.5 && innerH > line * 1.5 ? (
+ <path
+ d={`M${f1(box.x + line)} ${f1(box.y + box.h - line)} L${f1(box.x + box.w - line)} ${f1(box.y + line)}`}
+ stroke={ink}
+ strokeWidth={f1(line * 0.9)}
+ />
+ ) : null}
+ {detail === "dotted" && dot > unit ? (
+ <rect
+ x={f1(box.x + box.w / 2 - dot / 2)}
+ y={f1(box.y + box.h / 2 - dot / 2)}
+ width={f1(dot)}
+ height={f1(dot)}
+ fill={ink}
+ />
+ ) : null}
+ </g>
+ );
+ };
+ // Happy as a chevron: the eye's six outline points slide to a ^ (or v) of the same width.
+ // Both arms keep one perpendicular thickness, so the tip is a true miter, not a lump.
+ const chevron = s.happyShape === "caret" || s.happyShape === "vee" ? f.happy : 0;
+ // Rounded eyes stay rounded through the morph: the shape is drawn inset by half of a round
+ // stroke `k` and then stroked with round joins and caps, which is exactly a rounded shape. At
+ // the start k matches the eye's own corner radius (a pill stays a pill); at the end it is the
+ // v's full thickness, so the happy eye is a soft v with round ends and a round tip.
+ const eyePath = (e: { x: number; y: number; w: number; h: number; cx: number; cy: number }) => {
+ const dir = s.happyShape === "vee" ? 1 : -1;
+ const A = E * 0.5;
+ const thick = Math.max(line * 1.6, E * 0.17, minH * 1.3);
+ const cosA = Math.cos(Math.atan2(A, e.w / 2));
+ const rRect = Math.min(Math.min(e.w, e.h) * s.eyeRadius, Math.min(e.w, e.h) / 2);
+ const k = s.eyeRadius > 0 ? lerp(2 * rRect, Math.min(thick, 2 * rRect + thick * 0.5), chevron) : 0;
+ const t = Math.max(0, thick / cosA - k / cosA);
+ const armsY = e.cy - (dir * A) / 2;
+ const apexY = e.cy + (dir * A) / 2;
+ const x0 = e.x + k / 2;
+ const x1 = e.x + e.w - k / 2;
+ const y0 = e.y + k / 2;
+ const y1 = e.y + e.h - k / 2;
+ const from: Array<[number, number]> = [
+ [x0, y0],
+ [e.cx, y0],
+ [x1, y0],
+ [x1, y1],
+ [e.cx, y1],
+ [x0, y1],
+ ];
+ const to: Array<[number, number]> = [
+ [x0, armsY - t / 2],
+ [e.cx, apexY - t / 2],
+ [x1, armsY - t / 2],
+ [x1, armsY + t / 2],
+ [e.cx, apexY + t / 2],
+ [x0, armsY + t / 2],
+ ];
+ const pts = from.map(
+ ([fx, fy], i) => [fx + (to[i]![0] - fx) * chevron, fy + (to[i]![1] - fy) * chevron] as [number, number],
+ );
+ return {
+ d: `M${pts.map(([x, y]) => `${f1(x)} ${f1(y)}`).join(" L")} Z`,
+ k,
+ };
+ };
+ // Soft styles (pill eyes, round line ends, rounded brackets) round the small parts too:
+ // lids, text lines, the MacBook base get round ends; the tool square and sleep squares follow
+ // the eye's roundness.
+ const soft = s.roundEnds === true || s.eyeRadius >= 0.25 || (s.cornerRadius ?? 0) >= 6 ? 1 : 0;
+ const dotR = (size: number) => f1(size * Math.min(0.5, s.eyeRadius));
+ const rx = (e: { w: number; h: number }) => f1(Math.min(e.w, e.h) * s.eyeRadius);
+ // An outlined eye (loader, goggle lens): the stroke sits half a line inside the eye's box, so
+ // its radius is the eye's radius less half a line, and the outside matches the solid eye.
+ const outlineRx = (e: { w: number; h: number }) => f1(Math.max(0, Math.min(e.w, e.h) * s.eyeRadius - line / 2));
+ const loading = f.fill >= 0;
+ // Whole-face tremble, a little larger on small drawings so it still reads in pixels.
+ const shake = f.shake * (tiny ? 6 : small ? 3 : 1);
+ const bob = (f.bob ?? 0) * (tiny ? 3 : small ? 2 : 1);
+ // Resting squares drift up from above the right ear (or the right bracket's corner).
+ const zx = cat ? 80 + spread - earSize(s).inset - earSize(s).tip * earSize(s).B + line : 80 + spread - 4;
+ const zy = 80 - s.bracketHeight / 2 - (cat ? earSize(s).rise + line : 2);
+ const zScale = tiny ? 2.6 : small ? 1.7 : 1;
+ return (
+ <g
+ transform={
+ shift || shake || bob || device.devY || f.tilt
+ ? `translate(${f1(shake)} ${f1(shift + device.devY + bob)}) rotate(${f1(f.tilt ?? 0)} 80 80)`
+ : undefined
+ }
+ >
+ <Brackets
+ f={f}
+ s={s}
+ ink={ink}
+ spread={spread}
+ height={s.bracketHeight}
+ left={f.bracketL}
+ right={f.bracketR}
+ arm={device.arm}
+ backing={backing}
+ />
+ {device.mac > 0.6 ? (
+ // The MacBook's base: a plain, wider bar under the screen.
+ <g>
+ <rect
+ x={f1(80 - spread - 11 * ((device.mac - 0.6) / 0.4))}
+ y={f1(80 + s.bracketHeight / 2 + 2.5)}
+ width={f1(2 * spread + 22 * ((device.mac - 0.6) / 0.4))}
+ height={f1(line * 1.1)}
+ rx={f1(line * 0.55 * soft)}
+ fill={ink}
+ />
+ </g>
+ ) : null}
+ {eyes.map((e) =>
+ f.look !== "eyes" && e.closed < 0.6 ? (
+ // One page across the whole face (drawn once, with the left eye), revealed by the lids.
+ e.side < 0 ? (
+ <g key={e.side}>
+ <clipPath id={`uzu-lid-${uid}`}>
+ <rect x={f1(80 - spread)} y={f1(e.y)} width={f1(2 * spread)} height={f1(e.h)} />
+ </clipPath>
+ <g clipPath={`url(#uzu-lid-${uid})`}>
+ {textBlock(
+ 80 - spread + line / 2 + Math.max(4, line, unit * 1.2),
+ 80 + spread - line / 2 - Math.max(4, line, unit * 1.2),
+ e.cy,
+ E,
+ f.text,
+ ink,
+ small,
+ soft,
+ )}
+ </g>
+ </g>
+ ) : null
+ ) : G > 0.02 ? (
+ // A goggle lens: the eye's own box as an outline, the eye shrinking into the pupil.
+ <g key={e.side}>
+ <rect
+ x={f1(e.x + line / 2)}
+ y={f1(e.y + line / 2)}
+ width={f1(Math.max(0, e.w - line))}
+ height={f1(Math.max(0, e.h - line))}
+ rx={outlineRx(e)}
+ fill={paper}
+ stroke={ink}
+ strokeWidth={f1(line)}
+ />
+ {(() => {
+ const pw = lerp(e.w, showPupil ? pupilW : 0, grow);
+ const ph = lerp(e.h, showPupil ? pupilH : 0, grow);
+ if (pw < 0.3 || ph < 0.3) return null;
+ const pcx = e.cx + f.gx * pupilX * grow;
+ const pcy = e.cy + f.gy * pupilY * grow;
+ return (
+ <rect
+ x={f1(pcx - pw / 2)}
+ y={f1(pcy - ph / 2)}
+ width={f1(pw)}
+ height={f1(ph)}
+ rx={rx({ w: pw, h: ph })}
+ fill={ink}
+ />
+ );
+ })()}
+ </g>
+ ) : loading ? (
+ <g key={e.side}>
+ {/* The fill rises inside the eye's own rounded shape: flat on top, corners below. */}
+ <clipPath id={`uzu-load-${uid}-${e.side}`}>
+ <rect x={f1(e.x)} y={f1(e.y)} width={f1(e.w)} height={f1(e.h)} rx={rx(e)} />
+ </clipPath>
+ <rect
+ x={f1(e.x + line / 2)}
+ y={f1(e.y + line / 2)}
+ width={f1(Math.max(0, e.w - line))}
+ height={f1(Math.max(0, e.h - line))}
+ rx={outlineRx(e)}
+ fill={paper}
+ stroke={ink}
+ strokeWidth={f1(line)}
+ />
+ <rect
+ x={f1(e.x)}
+ y={f1(e.y + e.h * (1 - f.fill))}
+ width={f1(e.w)}
+ height={f1(e.h * f.fill)}
+ fill={ink}
+ clipPath={`url(#uzu-load-${uid}-${e.side})`}
+ />
+ </g>
+ ) : chevron > 0.001 ? (
+ (() => {
+ const shape = eyePath(e);
+ return shape.k > 0.05 ? (
+ <path
+ key={e.side}
+ d={shape.d}
+ fill={ink}
+ stroke={ink}
+ strokeWidth={f1(shape.k)}
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ ) : (
+ <path key={e.side} d={shape.d} fill={ink} />
+ );
+ })()
+ ) : (
+ // Calling a tool: the eyes turn like two meshing gears, each round its own centre.
+ <g key={e.side} transform={gearTransform(e)}>
+ {e.lid
+ ? symbol(
+ {
+ x: e.x,
+ y: e.lid.top,
+ w: e.w,
+ h: Math.max(0, e.lid.bottom - e.lid.top),
+ },
+ e.side,
+ { x: e.x, y: e.cy - E / 2, w: e.w, h: E },
+ )
+ : symbol(e, e.side, { x: e.x, y: e.cy - E / 2, w: e.w, h: E })}
+ {e.lid
+ ? (() => {
+ // Over a pixel zero the lid spans the glyph, not the wider eye box.
+ const pc = Math.round(s.pxCols ?? 5);
+ const cell = Math.min(e.w / pc, E / Math.round(s.pxRows ?? 7));
+ const lw = PIXEL_KINDS[s.eyeSymbol ?? ""] && cell >= unit * 1.2 ? cell * pc : e.w;
+ return (
+ <rect
+ x={f1(e.cx - lw / 2 - lidOver)}
+ y={f1(e.lid.y - line / 2)}
+ width={f1(lw + lidOver * 2)}
+ height={f1(line)}
+ rx={f1((line / 2) * soft)}
+ fill={ink}
+ />
+ );
+ })()
+ : null}
+ </g>
+ ),
+ )}
+ {G > 0.5
+ ? (() => {
+ // Bridge between the lenses and straps out to the brackets, growing in once the
+ // lenses have formed.
+ const k = Math.min(1, (G - 0.5) / 0.45);
+ const [l, r] = [eyes[0]!, eyes[1]!];
+ const y = (l.cy + r.cy) / 2 - line / 2;
+ const bk = s.detail === "tiny" ? 1.8 : s.detail === "medium" ? 1.4 : 1;
+ const spineL = 80 - spread - f.bracketL * bk + line / 2;
+ const spineR = 80 + spread + f.bracketR * bk - line / 2;
+ const gapIn = r.x - (l.x + l.w);
+ const outL = l.x - spineL;
+ const outR = spineR - (r.x + r.w);
+ return (
+ <g>
+ {gapIn > 0.2 ? (
+ <rect
+ x={f1((l.x + l.w + r.x) / 2 - (gapIn * k) / 2 - 0.3)}
+ y={f1(y)}
+ width={f1(gapIn * k + 0.6)}
+ height={f1(line)}
+ fill={ink}
+ />
+ ) : null}
+ {outL > 0.2 ? (
+ <rect
+ x={f1(l.x - outL * k - 0.3)}
+ y={f1(y)}
+ width={f1(outL * k + 0.6)}
+ height={f1(line)}
+ fill={ink}
+ />
+ ) : null}
+ {outR > 0.2 ? (
+ <rect x={f1(r.x + r.w - 0.3)} y={f1(y)} width={f1(outR * k + 0.6)} height={f1(line)} fill={ink} />
+ ) : null}
+ </g>
+ );
+ })()
+ : null}
+ {f.zs.map((z) => {
+ // Resting: small squares drift up and away, solid ink, growing in and shrinking out.
+ const u = z.age / 3;
+ const size = Math.max(0, 4.2 * zScale * Math.min(1, u * 6) * Math.min(1, (1 - u) * 4)) * (0.8 + 0.5 * u);
+ if (size < 0.4) return null;
+ const x = zx + 8 * u + Math.sin(z.age * 2) * 2;
+ const y = zy - 30 * u;
+ return (
+ <rect
+ key={z.id}
+ x={f1(x - size / 2)}
+ y={f1(y - size / 2)}
+ width={f1(size)}
+ height={f1(size)}
+ rx={dotR(size)}
+ fill={ink}
+ />
+ );
+ })}
+ </g>
+ );
+ },
+};
+
+export const drawFace = matrixFace.draw;
diff --git a/apps/mirai-gui/client/src/components/uzu-cat/index.tsx b/apps/mirai-gui/client/src/components/uzu-cat/index.tsx
new file mode 100644
index 000000000..390c09bfe
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/uzu-cat/index.tsx
@@ -0,0 +1,83 @@
+import { type RefObject, useId, useRef } from "react";
+import { twMerge } from "tailwind-merge";
+import { useAppStore } from "@/stores/use-app-store";
+import { drawFace } from "./face";
+import { type Face, type StateId, useFace } from "./engine";
+import { type PoseId, poseFace } from "./poses";
+import { FAVOURITE, forSize } from "./settings";
+
+export type { StateId as UzuCatState } from "./engine";
+
+/** The app background in each theme: empty loader eyes are filled with what the cat sits on. */
+const PAPER = { light: "#fcfcfc", dark: "#1c1c1c" } as const;
+
+type DrawProps = {
+ face: Face;
+ size: number;
+ /** The surface under the cat, when it is not the app background (a card, the composer). */
+ paper?: string;
+ label?: string;
+ className?: string;
+};
+
+function CatSvg({ face, size, paper, label, className }: DrawProps) {
+ const uid = useId().replace(/[^a-zA-Z0-9]/g, "");
+ const isDarkMode = useAppStore((s) => s.isDarkMode);
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 160 160"
+ fill="none"
+ className={twMerge("shrink-0 select-none pointer-events-none", className)}
+ role={label ? "img" : undefined}
+ aria-label={label}
+ aria-hidden={label ? undefined : true}
+ >
+ {drawFace({
+ f: face,
+ s: forSize(FAVOURITE, size),
+ ink: "currentColor",
+ paper: paper ?? PAPER[isDarkMode ? "dark" : "light"],
+ uid,
+ })}
+ </svg>
+ );
+}
+
+type UzuCatProps = Omit<DrawProps, "face"> & {
+ state: StateId;
+ /** For "watch": where to look, -1..1 each way from the cat (x right, y down). */
+ lookAt?: { x: number; y: number } | null;
+ /** For "loading": real progress 0..1. */
+ progress?: number | null;
+ /** The element the cat is measured from (for following the pointer); defaults to its own box. */
+ anchorRef?: RefObject<HTMLElement | null>;
+};
+
+/** The live uzu cat: blinks, glances and moves through its states. */
+export function UzuCat({ state, lookAt, progress, anchorRef, size, ...draw }: UzuCatProps) {
+ const ownRef = useRef<HTMLSpanElement>(null);
+ const face = useFace(
+ {
+ state,
+ blinkRate: FAVOURITE.blinkRate,
+ gazeRange: FAVOURITE.gazeRange,
+ speed: FAVOURITE.speed,
+ restartKey: 0,
+ lookAt,
+ progress,
+ },
+ anchorRef ?? ownRef,
+ );
+ return (
+ <span ref={ownRef} className="inline-flex shrink-0">
+ <CatSvg face={face} size={size} {...draw} />
+ </span>
+ );
+}
+
+/** The cat holding one still pose, for places that should not move (history, icons). */
+export function UzuCatStill({ pose = "default", ...draw }: Omit<DrawProps, "face"> & { pose?: PoseId }) {
+ return <CatSvg face={poseFace(pose)} {...draw} />;
+}
diff --git a/apps/mirai-gui/client/src/components/uzu-cat/poses.ts b/apps/mirai-gui/client/src/components/uzu-cat/poses.ts
new file mode 100644
index 000000000..b7d6590bb
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/uzu-cat/poses.ts
@@ -0,0 +1,22 @@
+import { type Face, REST } from "./engine";
+
+/** Still faces for icons, avatars and patterns: one frame, no engine. Gaze values are final. */
+export type PoseId =
+ "default" | "happy" | "wink" | "thinking" | "sleepy" | "goggles" | "loading" | "listening" | "lookLeft" | "lookRight";
+
+export const POSES: Record<PoseId, { label: string; face: Partial<Face> }> = {
+ default: { label: "Default", face: {} },
+ happy: { label: "Happy", face: { happy: 1 } },
+ wink: { label: "Wink", face: { blinkR: 1 } },
+ thinking: { label: "Thinking", face: { gx: 0.35, gy: -0.65, squint: 0.3, asym: 1, turn: 0.3 } },
+ sleepy: { label: "Asleep", face: { sleep: 1 } },
+ goggles: { label: "Goggles", face: { glasses: 1 } },
+ loading: { label: "Loading", face: { fill: 0.6 } },
+ listening: { label: "Listening", face: { size: 1.08, earH: 1.15, earL: -6, earR: -6 } },
+ lookLeft: { label: "Looking left", face: { gx: -0.6, turn: -0.5 } },
+ lookRight: { label: "Looking right", face: { gx: 0.6, turn: 0.5 } },
+};
+
+export function poseFace(id: PoseId, extra: Partial<Face> = {}): Face {
+ return { ...REST, ...POSES[id].face, ...extra };
+}
diff --git a/apps/mirai-gui/client/src/components/uzu-cat/settings.ts b/apps/mirai-gui/client/src/components/uzu-cat/settings.ts
new file mode 100644
index 000000000..2d4329029
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/uzu-cat/settings.ts
@@ -0,0 +1,81 @@
+import { earSize, type Settings } from "./face";
+
+/** The uzu cat: soft and rounded, pill eyes, rounded brackets with round ends, set-in cat ears
+ * with slightly rounded tips, v when happy. */
+export const FAVOURITE: Settings = {
+ state: "story",
+ detail: "full",
+ brackets: "square",
+ eyeShape: "square",
+ eyeRadius: 0.5,
+ happyShape: "vee",
+ ears: "cat",
+ earBase: false,
+ earScale: 0.8,
+ eyeAspect: 0.54,
+ weight: 5,
+ eyeSize: 38,
+ gap: 30,
+ spread: 50,
+ bracketHeight: 64,
+ gazeRange: 0.7,
+ blinkRate: 1,
+ speed: 1,
+ earTip: 0.3,
+ earInset: 11,
+ earRise: 1,
+ earMotion: true,
+ earArm: true,
+ eyeSymbol: "block",
+ eyelids: false,
+ lidSize: 0.3,
+ cornerRadius: 10,
+ roundEnds: true,
+ pxCols: 5,
+ pxRows: 7,
+ pxTop: 3,
+ pxBottom: 3,
+ pxSide: 1,
+ pxGap: 0,
+ pxRound: 0,
+ earRadius: 2,
+};
+
+/**
+ * The same face, adapted to a size in pixels. Below 96 px every line is kept to at least
+ * ~1.25-1.5 px, every gap (eye to eye, eye to bracket) to at least ~1 px, and below 28 px the
+ * drawing switches to its tiny version: solid ears and two lines of text.
+ */
+export function forSize(s: Settings, px: number): Settings {
+ const unit = 160 / px; // viewBox units per pixel
+ if (px >= 96) return { ...s, detail: "full", unit };
+ const tiny = px < 28;
+ const weight = Math.max(s.weight, (tiny ? 1.5 : 1.25) * unit);
+ // Eye to eye (horizontal sizes go through the eye's width).
+ const aspect = s.eyeAspect ?? 1;
+ // Only when the design has a gap at all: eyes set to touch or overlap stay that way.
+ let eyeSize = s.eyeSize;
+ if (s.gap > s.eyeSize * aspect)
+ eyeSize = Math.max(unit * 3, Math.min(eyeSize, (s.gap - (tiny ? 1.4 : 1.2) * unit) / aspect));
+ // Eye to spine.
+ const sideRoom = s.spread - weight / 2 - (s.gap / 2 + (eyeSize * aspect) / 2);
+ if (sideRoom < unit) eyeSize -= (2 * (unit - sideRoom)) / aspect;
+ // Eye to the bracket arms: grow the brackets rather than shrink the eyes further.
+ const bracketHeight = Math.max(s.bracketHeight, 2 * (weight + eyeSize / 2 + unit));
+ const adapted: Settings = {
+ ...s,
+ weight,
+ eyeSize,
+ bracketHeight,
+ detail: tiny ? "tiny" : "medium",
+ unit,
+ ears: s.ears === "none" ? "none" : tiny ? "cat-solid" : s.ears,
+ };
+ // Keep the ears inside the box: trim the brackets if the ear tips would leave it.
+ if (adapted.ears !== "none") {
+ const { rise } = earSize(adapted);
+ const over = 80 - bracketHeight / 2 - rise * 0.58 - weight - 2;
+ if (over < 0) adapted.bracketHeight = Math.max(2 * (weight + eyeSize / 2), bracketHeight + over * 1.2);
+ }
+ return adapted;
+}
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/chat-card.tsx b/apps/mirai-gui/client/src/features/chat-history/components/chat-card.tsx
index 5188aff92..4e212d3f0 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/chat-card.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/chat-card.tsx
@@ -1,7 +1,6 @@
import React from "react";
import { DataInteractive } from "@headlessui/react";
import { formatDistanceToNow } from "date-fns";
-import { ChatsIcon } from "@/components/icons/chats-icon";
import { Checkbox } from "@/components/ui/checkbox";
import { twMerge } from "tailwind-merge";
@@ -47,34 +46,32 @@ const ChatCard: React.FC<ChatCardProps> = ({
},
})}
className={twMerge(
- "rounded-lg overflow-clip bg-background cursor-pointer transition-colors border-[0.5px] border-cell-border",
- !selectMode && "outline-hidden data-[focus]:shadow-focus",
- selectMode ? "hover:bg-card-hover" : "hover:bg-card-hover",
- selected ? "bg-bg-modal border-button-border" : "",
+ "rounded-xl bg-surface-soft cursor-pointer transition-colors duration-150 ease-out",
+ !selectMode && "outline-hidden data-[focus]:bg-surface-tertiary",
+ // Two steps, as in the menus: the pointer lifts a card a little, choosing it a step more.
+ selected ? "bg-selection-selected" : "hover:bg-surface-tertiary",
)}
>
- <div className="grid grid-cols-[auto_1fr_auto] items-center gap-3 p-3 w-full">
- <div className="flex-shrink-0 w-5 h-5 flex items-center justify-center">
- {selectMode ? (
- <span onClick={(e) => e.stopPropagation()}>
- <Checkbox
- checked={checked}
- onChange={() => onCheckedChange?.()}
- size="sm"
- aria-label={`Select ${title}`}
- />
- </span>
- ) : (
- <ChatsIcon className="w-5 h-5 text-label-title" />
- )}
- </div>
+ {/* The title alone leads; the checkbox takes the leading slot only while selecting. */}
+ <div
+ className={twMerge(
+ "grid items-center gap-3 h-14 px-4 w-full",
+ selectMode ? "grid-cols-[auto_1fr_auto]" : "grid-cols-[1fr_auto]",
+ )}
+ >
+ {selectMode ? (
+ // A flex box, not an inline span: inline, the box sat on the text baseline, below centre.
+ <div className="flex size-4 shrink-0 items-center justify-center" onClick={(e) => e.stopPropagation()}>
+ <Checkbox checked={checked} onChange={() => onCheckedChange?.()} size="sm" aria-label={`Select ${title}`} />
+ </div>
+ ) : null}
<div className="min-w-0">
- <h3 className="text-[15px] leading-[150%] font-[350] text-label-title overflow-clip text-ellipsis whitespace-nowrap">
+ <h3 className="text-[14px] leading-[1.35] font-[450] text-label-title overflow-clip text-ellipsis whitespace-nowrap">
{title}
</h3>
</div>
<div className="flex-shrink-0 ml-2">
- <span className="text-xs text-label-muted font-mono whitespace-nowrap">{timeAgo}</span>
+ <span className="text-[13px] text-label-muted tabular-nums whitespace-nowrap">{timeAgo}</span>
</div>
</div>
</DataInteractive>
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/chat-delete-modal.tsx b/apps/mirai-gui/client/src/features/chat-history/components/chat-delete-modal.tsx
index 612e859f0..1ccfd6fbe 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/chat-delete-modal.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/chat-delete-modal.tsx
@@ -19,9 +19,9 @@ export const ChatDeleteModal: React.FC<ChatDeleteModalProps> = ({
}) => {
const isBulk = typeof count === "number" && count > 0 && !chatName;
const description = chatName
- ? `Are you sure you want to delete chat "${chatName}"? This action cannot be undone.`
+ ? `“${chatName}” will be deleted from this device. This can’t be undone.`
: isBulk
- ? `Are you sure you want to delete ${count} ${count === 1 ? "chat" : "chats"}? This action cannot be undone.`
+ ? `${count} ${count === 1 ? "chat" : "chats"} will be deleted from this device. This can’t be undone.`
: "";
return (
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/chat-history-page.tsx b/apps/mirai-gui/client/src/features/chat-history/components/chat-history-page.tsx
index fb60c2e14..7a8784bd1 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/chat-history-page.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/chat-history-page.tsx
@@ -1,12 +1,13 @@
-import RenameIcon from "@/components/icons/rename-icon";
-import TrashIcon from "@/components/icons/trash-icon";
+import { PencilIcon } from "@/components/icons/app-icons";
import ChatCard from "./chat-card";
import { ChatDeleteModal } from "./chat-delete-modal";
import { ChatRenameModal } from "./chat-rename-modal";
-import GlobalInstructions from "./global-instructions";
import { GroupButton } from "@/components/ui/group-button";
import { useNavigate } from "@tanstack/react-router";
-import { X } from "lucide-react";
+import { Plus, Trash2, X } from "lucide-react";
+import { v4 as uuidv4 } from "uuid";
+import { UzuCat } from "@/components/uzu-cat";
+import { PageScroller, PageTitleBar } from "@/components/page-title-bar";
import { type CSSProperties, useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
@@ -14,7 +15,6 @@ import { SearchInput } from "@/components/ui/search-input";
import { useToast } from "@/components/ui/toast/use-toast";
import { useChatStore } from "@/stores/use-chat-store";
import { useAppStore } from "@/stores/use-app-store";
-import { useGlobalInstructionsStore } from "@/stores/use-global-instructions-store";
export function ChatHistoryPage() {
const navigate = useNavigate();
@@ -24,9 +24,7 @@ export function ChatHistoryPage() {
const savedChats = useChatStore((s) => s.savedChats);
const loadSavedChats = useChatStore((s) => s.loadSavedChats);
const deleteChat = useChatStore((s) => s.deleteChat);
- const instructions = useGlobalInstructionsStore((s) => s.instructions);
- const loadInstructions = useGlobalInstructionsStore((s) => s.loadInstructions);
- const saveInstructions = useGlobalInstructionsStore((s) => s.saveInstructions);
+ const createNewChat = useChatStore((s) => s.createNewChat);
const [isSelectionMode, setIsSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
@@ -36,8 +34,7 @@ export function ChatHistoryPage() {
useEffect(() => {
loadSavedChats();
- loadInstructions();
- }, [loadSavedChats, loadInstructions]);
+ }, [loadSavedChats]);
const filteredChats = useMemo(() => {
const searchLower = searchQuery.toLowerCase();
@@ -67,6 +64,12 @@ export function ChatHistoryPage() {
});
};
+ const startNewChat = () => {
+ const chatId = uuidv4();
+ createNewChat(chatId);
+ navigate({ to: "/chat/$chatId", params: { chatId }, search: { isNew: true } });
+ };
+
const confirmBulkDelete = async () => {
setIsDeleting(true);
try {
@@ -92,100 +95,96 @@ export function ChatHistoryPage() {
return (
<div className="flex h-full min-h-0 flex-col" style={{ "--chat-width": `${chatWidth}px` } as CSSProperties}>
- <div className="shrink-0 z-10">
- <div className="w-full bg-bg-modal">
- <div className="pt-7 pb-7 flex flex-col justify-center px-5 w-full max-w-[calc(var(--chat-width)+2.5rem)] mx-auto gap-6 lg:gap-0">
- <h1 className="leading-[130%] text-xl font-medium text-label-title text-center lg:text-left">
- Chat history
- </h1>
- </div>
-
- <div className="px-5 pt-4 pb-7 w-full max-w-[calc(var(--chat-width)+2.5rem)] mx-auto">
- <GlobalInstructions instructions={instructions} onSave={saveInstructions} />
- </div>
- <div className="h-[1px] bg-cell-border" />
- </div>
+ <PageScroller
+ className="bg-background"
+ header={
+ <PageTitleBar className="justify-between">
+ <h1 className="text-[20px] font-[600] leading-[1.2] tracking-[-0.01em] text-label-title">Chat history</h1>
+ {/* Search and selection only once there is something to search or select. */}
+ {savedChats.length > 0 ? (
+ <div className="flex items-center gap-2">
+ <SearchInput
+ value={searchQuery}
+ onChange={setSearchQuery}
+ placeholder="Search"
+ className="w-full max-w-[210px] lg:min-w-[240px] lg:max-w-[240px]"
+ />
+ {isSelectionMode ? (
+ <GroupButton>
+ <GroupButton.Segment ariaLabel="Select all" onClick={() => toggleSelectAll()}>
+ <Checkbox
+ checked={isAllSelected}
+ onChange={() => {}}
+ size="sm"
+ disabled
+ className="pointer-events-none opacity-100"
+ />
+ <span className={showActive ? "text-text-primary" : undefined}>{labelText}</span>
+ </GroupButton.Segment>
+
+ {!isAllSelected && singleSelectedChat && (
+ <GroupButton.Segment icon ariaLabel="Rename" onClick={() => setIsRenameOpen(true)}>
+ <PencilIcon size={16} />
+ </GroupButton.Segment>
+ )}
- <div className="w-full bg-background">
- <div className="px-5 pt-5 pb-2.5 flex items-center justify-between w-full max-w-[calc(var(--chat-width)+2.5rem)] mx-auto">
- <h2 className="text-sm font-[350] text-label-title">Your chats</h2>
- <div className="flex items-center gap-2">
- <SearchInput
- value={searchQuery}
- onChange={setSearchQuery}
- placeholder="Search"
- className="w-full max-w-[210px] lg:min-w-[240px] lg:max-w-[240px]"
- />
- {isSelectionMode ? (
- <GroupButton>
- <GroupButton.Segment ariaLabel="Select all" onClick={() => toggleSelectAll()} className="gap-2">
- <Checkbox
- checked={isAllSelected}
- onChange={() => {}}
- size="sm"
- disabled
- className="pointer-events-none opacity-100"
- />
- <span className={showActive ? "text-[12px] text-label-title" : "text-[12px] text-label-muted"}>
- {labelText}
- </span>
- </GroupButton.Segment>
-
- {!isAllSelected && singleSelectedChat && (
<GroupButton.Segment
- leftDivider
- ariaLabel="Rename"
- onClick={() => setIsRenameOpen(true)}
- className={showActive ? "text-label-title" : "text-label-muted"}
+ icon
+ ariaLabel="Delete"
+ onClick={() => setIsConfirmOpen(true)}
+ disabled={selectedIds.length === 0}
>
- <RenameIcon className="w-4 h-4" />
+ <Trash2 className="size-4" aria-hidden />
</GroupButton.Segment>
- )}
-
- <GroupButton.Segment
- leftDivider
- ariaLabel="Delete"
- onClick={() => setIsConfirmOpen(true)}
- disabled={selectedIds.length === 0}
- className={showActive ? "text-label-title" : "text-label-muted"}
- >
- <TrashIcon className="w-4 h-4" />
- </GroupButton.Segment>
-
- <GroupButton.Segment
- leftDivider
- ariaLabel="Exit selection"
- onClick={exitSelectionMode}
- className={showActive ? "text-label-title" : "text-label-muted"}
+
+ <GroupButton.Segment icon ariaLabel="Exit selection" onClick={exitSelectionMode}>
+ <X className="size-4" />
+ </GroupButton.Segment>
+ </GroupButton>
+ ) : (
+ <Button
+ kind="secondary"
+ size="sm"
+ className="h-8 px-3.5 rounded-full bg-control-fill shadow-none text-[13px] font-[450] text-text-muted hover:bg-control-fill-hover hover:text-text-primary"
+ onClick={() => setIsSelectionMode(true)}
>
- <X className="w-4 h-4" />
- </GroupButton.Segment>
- </GroupButton>
- ) : (
- <Button
- kind="secondary"
- size="sm"
- className="text-label-muted h-8 px-3 rounded-[8px] text-sm leading-[150%]"
- onClick={() => setIsSelectionMode(true)}
- >
- Select
- </Button>
- )}
+ Select
+ </Button>
+ )}
+ </div>
+ ) : null}
+ </PageTitleBar>
+ }
+ >
+ <div className="px-5 overflow-visible w-full min-h-full flex flex-col max-w-[calc(var(--chat-width)+2.5rem)] mx-auto">
+ {filteredChats.length === 0 && !searchQuery ? (
+ <div className="flex flex-1 flex-col items-center justify-center pb-16 text-center animate-uzu-in">
+ <div className="mb-1">
+ <UzuCat state="resting" size={112} className="text-text-primary" label="uzu, asleep" />
+ </div>
+ <div className="flex flex-col gap-1">
+ <p className="text-[15px] font-[500] text-label-title">No chats yet</p>
+ <p className="text-[13px] text-label-muted">Conversations stay on this device</p>
+ </div>
+ {/* As far below the words as the cat sits above them. */}
+ <Button kind="primary" size="sm" icon={<Plus size={16} />} onClick={startNewChat} className="mt-7">
+ New chat
+ </Button>
</div>
- </div>
- </div>
- </div>
-
- <div className="flex-1 min-h-0 w-full overflow-y-auto overscroll-y-contain thin-scrollbar bg-background">
- <div className="px-5 overflow-visible w-full max-w-[calc(var(--chat-width)+2.5rem)] mx-auto">
- {filteredChats.length === 0 ? (
- <div className="text-center py-8">
- <p className="text-label-muted">
- {searchQuery ? "No chats found matching your search." : "No chats yet. Start a new conversation!"}
- </p>
+ ) : filteredChats.length === 0 ? (
+ // Laid out like the empty state; the cat is reading, glasses on, scanning for a match.
+ <div className="flex flex-1 flex-col items-center justify-center pb-16 text-center animate-uzu-in">
+ <div className="mb-1">
+ <UzuCat state="reading" size={112} className="text-text-primary" label="uzu, searching" />
+ </div>
+ <div className="flex max-w-[320px] flex-col gap-1">
+ <p className="text-[15px] font-[500] text-label-title">No matching chats</p>
+ <p className="truncate text-[13px] text-label-muted">Nothing found for “{searchQuery.trim()}”</p>
+ </div>
</div>
) : (
- <div className="space-y-3 pb-6 w-full">
+ <div className="mt-4 mb-10 w-full flex flex-col gap-2 animate-uzu-in">
+ {/* The list comes in once as a whole, like the settings page, not card by card. */}
{filteredChats.map((chat) => (
<div key={chat.id} className="relative">
<ChatCard
@@ -203,7 +202,7 @@ export function ChatHistoryPage() {
</div>
)}
</div>
- </div>
+ </PageScroller>
<ChatDeleteModal
isOpen={isConfirmOpen}
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.test.tsx b/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.test.tsx
index ba3b50520..2dcee4715 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.test.tsx
@@ -47,3 +47,10 @@ it("still writes a clear typed while the previous save is in flight", async () =
await Promise.resolve();
expect(onSave).toHaveBeenCalledTimes(2);
});
+
+it("offers to add instructions until some are saved, then to change them", () => {
+ const view = render(<GlobalInstructions instructions="" onSave={vi.fn(async () => true)} />);
+ expect(screen.getByRole("button", { name: /Add instructions to all chats/ })).toBeTruthy();
+ view.rerender(<GlobalInstructions instructions="Be brief" onSave={vi.fn(async () => true)} />);
+ expect(screen.getByRole("button", { name: /Change instructions for all chats/ })).toBeTruthy();
+});
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.tsx b/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.tsx
index 07cebc421..6a13383d2 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/global-instructions.tsx
@@ -1,7 +1,6 @@
import { Textarea as HeadlessTextarea } from "@headlessui/react";
import { Plus } from "lucide-react";
import React, { useCallback, useEffect, useRef, useState } from "react";
-import { CardContainer } from "@/components/ui/card-container";
import { useToast } from "@/components/ui/toast/use-toast";
type GlobalInstructionsProps = {
@@ -9,6 +8,11 @@ type GlobalInstructionsProps = {
onSave: (instructions: string) => Promise<boolean>;
};
+const LABELS = [
+ { hasInstructions: false, text: "Add instructions to all chats" },
+ { hasInstructions: true, text: "Change instructions for all chats" },
+] as const;
+
const GlobalInstructions: React.FC<GlobalInstructionsProps> = ({ instructions, onSave }) => {
const toast = useToast();
const [isExpanded, setIsExpanded] = useState(false);
@@ -103,46 +107,63 @@ const GlobalInstructions: React.FC<GlobalInstructionsProps> = ({ instructions, o
[scheduleSave],
);
+ const hasInstructions = instructions.trim() !== "";
+
return (
- <div>
- <CardContainer>
- <button
- className="w-full group flex items-center gap-3 p-3 text-left lg:justify-between"
- onClick={handleToggleExpand}
- >
- <div className="flex items-center gap-3 flex-1 min-w-0 lg:flex-initial">
- <Plus
- className={`w-5 h-5 shrink-0 text-label-muted transition-transform duration-200 ${isExpanded ? "rotate-45" : ""}`}
- />
- <div className="flex-1 min-w-0 lg:flex-initial">
- <h3 className="text-sm font-[350] leading-[150%] text-label-title">Add instructions to all chats</h3>
- <span className="block text-[13px] font-[350] leading-[130%] text-label-muted lg:hidden">
- Tailor the way the model responds
+ <div className="rounded-2xl bg-surface-soft">
+ <button
+ type="button"
+ aria-expanded={isExpanded}
+ className="group flex min-h-12 w-full items-center gap-3 rounded-2xl pl-3 pr-4 py-2.5 text-left outline-hidden focus-visible:shadow-focus"
+ onClick={handleToggleExpand}
+ >
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-control-fill text-label-muted transition-colors duration-150 ease-out group-hover:bg-control-fill-hover group-hover:text-label-title">
+ <Plus
+ aria-hidden
+ className={`size-4 transition-transform duration-200 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none ${isExpanded ? "rotate-45" : ""}`}
+ />
+ </span>
+ {/* Saved instructions, not the draft, so the label doesn't flip while typing the first word.
+ Both labels share one grid cell and cross-fade with a touch of blur, like the copy button's
+ icons; the hidden one is left out of the button's name. */}
+ <span className="grid flex-1 min-w-0 text-[14px] font-[450] leading-[1.3] text-label-title">
+ {LABELS.map((label) => {
+ const shown = label.hasInstructions === hasInstructions;
+ return (
+ <span
+ key={label.text}
+ aria-hidden={!shown}
+ className={`[grid-area:1/1] transition-[opacity,filter] duration-200 ease-out will-change-[opacity,filter] motion-reduce:transition-none ${shown ? "opacity-100 [filter:blur(0px)]" : "opacity-0 [filter:blur(2px)]"}`}
+ >
+ {label.text}
</span>
- </div>
- </div>
-
- <span className="hidden lg:block text-[13px] font-[350] leading-[130%] text-label-muted text-right">
- Tailor the way the model responds
- </span>
- </button>
- </CardContainer>
+ );
+ })}
+ </span>
+ <span className="hidden sm:block text-[13px] leading-[1.3] text-label-muted">
+ Tailor the way the model responds
+ </span>
+ </button>
- <CardContainer
- className={`overflow-clip transition-all duration-300 ease-in-out ${isExpanded ? "max-h-96 opacity-100 mt-3" : "max-h-0 opacity-0"}`}
+ {/* Opens in place: the card grows from its own row instead of a second box appearing. */}
+ <div
+ className={`grid transition-[grid-template-rows,opacity] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none ${isExpanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"}`}
>
- <div className="p-3">
- <HeadlessTextarea
- ref={textareaRef}
- value={localInstructions}
- onChange={handleChange}
- onBlur={flushSave}
- placeholder="Add instructions to all chats"
- className="w-full p-1 bg-bg-modal rounded-md text-sm leading-[150%] text-label-title placeholder:text-label-muted focus:outline-hidden focus:border-primary resize-none overscroll-y-auto thin-scrollbar"
- rows={7}
- />
+ <div className="min-h-0 overflow-clip">
+ <div className="px-4 pb-4">
+ <HeadlessTextarea
+ ref={textareaRef}
+ value={localInstructions}
+ onChange={handleChange}
+ onBlur={flushSave}
+ placeholder="Add instructions to all chats"
+ tabIndex={isExpanded ? 0 : -1}
+ className="w-full rounded-xl bg-control-fill px-3 py-2.5 text-[14px] leading-[1.5] text-label-title placeholder:text-label-muted focus:outline-hidden resize-none overscroll-y-auto thin-scrollbar"
+ rows={6}
+ />
+ </div>
</div>
- </CardContainer>
+ </div>
</div>
);
};
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.tsx b/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.tsx
index 56e68b4ee..de2008402 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.tsx
@@ -1,6 +1,7 @@
import { Menu, MenuButton, MenuItem, MenuItems } from "@headlessui/react";
import { useNavigate, useParams } from "@tanstack/react-router";
-import { Edit3, MoreHorizontal, Trash2 } from "lucide-react";
+import { Trash2 } from "lucide-react";
+import { EllipsisIcon, PencilIcon } from "@/components/icons/app-icons";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useChatStore } from "@/stores/use-chat-store";
import { useSidebarStore } from "@/stores/use-sidebar-store";
@@ -8,6 +9,20 @@ import { useShiftHeld } from "@/hooks/use-shift-held";
import { ChatDeleteModal } from "@/features/chat-history/components/chat-delete-modal";
import type { ChatMetadata } from "@/platform/services/storage";
+// The row's own fill changes with hover and selection, so its buttons darken whatever is under them
+// rather than painting a fixed grey that vanishes on the selected row.
+const ROW_BUTTON_CLASSNAME =
+ "absolute right-1.5 top-1/2 -translate-y-1/2 flex size-6 items-center justify-center rounded-md text-label-muted outline-hidden transition-[opacity,background-color,color] duration-150 ease-out hover:bg-black/[0.07] hover:text-label-title dark:hover:bg-white/[0.08] data-[focus]:shadow-focus";
+// Long titles fade out at the row's end instead of ending in "…". On hover (or with the menu open)
+// the options button sits over the end of the row, so the fade ends just before it.
+const TITLE_FADE_UNDER_BUTTON =
+ "[mask-image:linear-gradient(to_right,black_calc(100%-2.75rem),transparent_calc(100%-1.625rem))]";
+const TITLE_FADE =
+ "[mask-image:linear-gradient(to_right,black_calc(100%-1.5rem),transparent)] group-hover:[mask-image:linear-gradient(to_right,black_calc(100%-2.75rem),transparent_calc(100%-1.625rem))] group-focus-within:[mask-image:linear-gradient(to_right,black_calc(100%-2.75rem),transparent_calc(100%-1.625rem))]";
+// Set like the sidebar's own rows (Models, Chats, New chat): 14px at 450, a 36px row, 10px corners.
+const MENU_ROW_CLASSNAME =
+ "flex w-full h-9 items-center gap-2.5 rounded-[10px] px-2.5 text-[14px] font-[450] leading-[1.3] outline-hidden cursor-pointer transition-colors duration-100 ease-out";
+
const VISIBILITY_THRESHOLDS = Array.from({ length: 101 }, (_, index) => index / 100);
export default function SavedChats() {
@@ -143,9 +158,9 @@ export default function SavedChats() {
return (
<div ref={scrollViewportRef} className="flex-1 overflow-y-auto overscroll-y-contain min-h-0 scrollbar-hide">
- <div className="flex flex-col gap-1">
+ <div className="flex flex-col gap-px pb-20">
{savedChats.length === 0 ? (
- <div className="px-4 py-2 text-[13px] font-[350] leading-[150%] text-label-muted">No chats yet</div>
+ <div className="px-[18px] py-2 text-[14px] font-[400] leading-[1.3] text-label-muted">No chats yet</div>
) : (
savedChats.map((chat: ChatMetadata) => (
<div
@@ -174,7 +189,7 @@ export default function SavedChats() {
e.stopPropagation();
startRename(chat);
}}
- className={`flex items-center gap-2 py-[6px] px-2 w-full rounded-md group transition-colors duration-150 ${currentChatId === chat.id ? "bg-sidebar-chat-selected" : editingChatId === chat.id || open ? "bg-sidebar-chat-hover" : "hover:bg-sidebar-chat-hover"}`}
+ className={`relative flex h-9 items-center pl-2.5 pr-2 w-full rounded-[10px] group transition-colors duration-150 ease-out ${currentChatId === chat.id ? "bg-sidebar-chat-selected" : editingChatId === chat.id || open ? "bg-sidebar-chat-hover" : "hover:bg-sidebar-chat-hover"}`}
>
<div className="flex-1 min-w-0">
{editingChatId === chat.id ? (
@@ -189,10 +204,12 @@ export default function SavedChats() {
if (e.key === "Escape") cancelRename();
}}
onBlur={() => void commitRename()}
- className="block w-full text-left text-[13px] font-[350] leading-[150%] text-label-title bg-transparent outline-hidden border-none p-0"
+ className="block w-full text-left text-[14px] font-[400] leading-[1.3] text-label-title bg-transparent outline-hidden border-none p-0 pr-6"
/>
) : (
- <p className="w-full text-left text-[13px] font-[350] leading-[150%] text-label-title truncate">
+ <p
+ className={`w-full text-left text-[14px] font-[400] leading-[1.3] text-label-title overflow-hidden whitespace-nowrap ${open ? TITLE_FADE_UNDER_BUTTON : TITLE_FADE}`}
+ >
{chat.title}
</p>
)}
@@ -206,9 +223,9 @@ export default function SavedChats() {
void performDelete(chat);
}}
onDoubleClick={(e) => e.stopPropagation()}
- className="opacity-0 group-hover:opacity-100 hover:bg-bg-hover p-1 rounded transition-opacity"
+ className={`${ROW_BUTTON_CLASSNAME} opacity-0 group-hover:opacity-100 text-danger hover:text-danger`}
>
- <Trash2 className="w-3 h-3 text-error" />
+ <Trash2 aria-hidden size={16} />
</button>
) : (
<>
@@ -216,40 +233,39 @@ export default function SavedChats() {
aria-label={`Options for ${chat.title}`}
onClick={(e) => e?.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
- className={`${open ? "opacity-100 bg-bg-hover dark:bg-bg-hover" : "opacity-0 group-hover:opacity-100 data-[focus]:opacity-100"} hover:bg-bg-hover p-1 rounded transition-opacity outline-hidden data-[focus]:shadow-focus`}
+ className={`${ROW_BUTTON_CLASSNAME} ${open ? "opacity-100 bg-black/[0.07] text-label-title dark:bg-white/[0.08]" : "opacity-0 group-hover:opacity-100 data-[focus]:opacity-100"}`}
>
- <MoreHorizontal className="w-3 h-3 text-label-muted" />
+ <EllipsisIcon aria-hidden size={16} />
</MenuButton>
<MenuItems
+ transition
anchor="bottom end"
- className="w-32 rounded-lg border border-cell-border bg-bg-modal [--anchor-gap:4px] outline-hidden focus:outline-hidden focus:ring-0 z-50 translate-x-2"
+ className="w-44 rounded-[14px] bg-surface-popover p-1 shadow-popover [--anchor-gap:4px] origin-top-right transition-[opacity,scale] duration-150 ease-out data-[closed]:scale-95 data-[closed]:opacity-0 data-[leave]:duration-100 motion-reduce:transition-none outline-hidden z-50 translate-x-1"
>
<MenuItem>
<button
+ type="button"
onClick={(e) => {
e.stopPropagation();
startRename(chat);
}}
- className="group/item flex w-full p-1 outline-hidden"
+ className={`${MENU_ROW_CLASSNAME} text-text-primary data-[focus]:bg-selection-hover`}
>
- <div className="flex grow rounded-md py-1.5 px-2 gap-2 w-full items-center hover:bg-card-hover group-data-[focus]/item:bg-card-hover transition-colors">
- <Edit3 className="w-3 h-3 text-label-title" />
- <span className="text-xs text-label-title">Rename</span>
- </div>
+ <PencilIcon aria-hidden size={18} className="shrink-0 text-text-secondary" />
+ Rename
</button>
</MenuItem>
<MenuItem>
<button
+ type="button"
onClick={(e) => {
e.stopPropagation();
handleDeleteChat(chat, e.shiftKey || shiftHeld);
}}
- className="group/item flex w-full p-1 outline-hidden"
+ className={`${MENU_ROW_CLASSNAME} text-danger data-[focus]:bg-danger-bg`}
>
- <div className="flex grow rounded-md py-1.5 px-2 gap-2 w-full items-center hover:bg-card-hover group-data-[focus]/item:bg-card-hover transition-colors">
- <Trash2 className="w-3 h-3 text-error" />
- <span className="text-xs text-error">Delete</span>
- </div>
+ <Trash2 aria-hidden size={18} className="shrink-0" />
+ Delete
</button>
</MenuItem>
</MenuItems>
diff --git a/apps/mirai-gui/client/src/features/chat/components/chat-header.test.tsx b/apps/mirai-gui/client/src/features/chat/components/chat-header.test.tsx
deleted file mode 100644
index 9b9b0277d..000000000
--- a/apps/mirai-gui/client/src/features/chat/components/chat-header.test.tsx
+++ /dev/null
@@ -1,222 +0,0 @@
-import { act, cleanup, render, screen } from "@testing-library/react";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { useSidebarStore } from "@/stores/use-sidebar-store";
-import { useChatStore } from "@/stores/use-chat-store";
-import SavedChats from "@/features/chat-history/components/saved-chats";
-import { ChatHeader } from "./chat-header";
-import { UNTITLED_CHAT_TITLE } from "@/constants/chat";
-
-const route = vi.hoisted(() => ({ chatId: "first" as string | undefined }));
-vi.mock("@tanstack/react-router", () => ({
- useParams: () => route,
- useNavigate: () => vi.fn(),
-}));
-
-const chatDefaults = useChatStore.getState();
-const sidebarDefaults = useSidebarStore.getState();
-const observers: Observer[] = [];
-
-class Observer {
- observed: Element | undefined;
- disconnect = vi.fn();
- constructor(
- readonly callback: IntersectionObserverCallback,
- readonly options: IntersectionObserverInit,
- ) {
- observers.push(this);
- }
- observe(element: Element) {
- this.observed = element;
- }
- emit(ratio: number) {
- this.callback(
- [{ target: this.observed, isIntersecting: ratio > 0, intersectionRatio: ratio } as IntersectionObserverEntry],
- this as unknown as IntersectionObserver,
- );
- }
-}
-
-const Harness = () => {
- const isOpen = useSidebarStore((state) => state.isOpen);
- return (
- <>
- <SavedChats />
- {route.chatId && <ChatHeader title={`Chat ${route.chatId}`} isSidebarOpen={isOpen} />}
- </>
- );
-};
-
-const titleWrapper = () => screen.getByRole("heading", { hidden: true }).parentElement!;
-
-beforeEach(() => {
- observers.length = 0;
- route.chatId = "first";
- vi.stubGlobal("IntersectionObserver", Observer);
- useSidebarStore.setState({ ...sidebarDefaults, isOpen: true, chatVisibility: null }, true);
- useChatStore.setState(
- {
- ...chatDefaults,
- loadSavedChats: vi.fn(async () => {}),
- savedChats: ["first", "second"].map((id) => ({
- id,
- title: `Chat ${id}`,
- createdAt: 1,
- updatedAt: 1,
- messageCount: 2,
- })),
- },
- true,
- );
-});
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
- useChatStore.setState(chatDefaults, true);
- useSidebarStore.setState(sidebarDefaults, true);
-});
-
-it("fades the title smoothly between 15% and 75% of the selected row being clipped", () => {
- render(<Harness />);
- const row = screen.getByRole("button", { name: "Chat first" });
- const observer = observers[0]!;
- expect(observer.observed).toBe(row);
- expect(observer.options.root).toBe(row.parentElement!.parentElement);
- expect(observer.options.threshold).toEqual(Array.from({ length: 101 }, (_, index) => index / 100));
- expect(observer.options.root).toHaveProperty("className", expect.stringContaining("overflow-y-auto"));
- const heading = screen.getByRole("heading");
- const wrapper = titleWrapper();
- expect(wrapper.style.opacity).toBe("1");
-
- act(() => observer.emit(1));
- expect(wrapper.style.opacity).toBe("0");
- expect(wrapper.getAttribute("aria-hidden")).toBe("true");
- expect(screen.getByRole("heading", { hidden: true })).toBe(heading);
- expect(wrapper.className).toContain("transition-[padding-left,opacity]");
- expect(wrapper.className).toContain("duration-300");
- expect(wrapper.className).toContain("motion-reduce:transition-none");
-
- for (const ratio of [0.9, 0.85]) {
- act(() => observer.emit(ratio));
- expect(wrapper.style.opacity).toBe("0");
- expect(wrapper.getAttribute("aria-hidden")).toBe("true");
- }
- for (const [ratio, opacity] of [
- [0.7, 0.15625],
- [0.55, 0.5],
- [0.4, 0.84375],
- ] as const) {
- act(() => observer.emit(ratio));
- expect(Number(wrapper.style.opacity)).toBeCloseTo(opacity);
- }
- expect(wrapper.getAttribute("aria-hidden")).toBe("false");
- act(() => observer.emit(0.25));
- expect(wrapper.style.opacity).toBe("1");
- act(() => observer.emit(0));
- expect(wrapper.style.opacity).toBe("1");
- act(() => observer.emit(1));
- expect(wrapper.style.opacity).toBe("0");
-});
-
-it("retains row visibility while closed so reopening starts the title fade with the sidebar", () => {
- render(<Harness />);
- const observer = observers[0]!;
- act(() => observer.emit(1));
- expect(titleWrapper().style.opacity).toBe("0");
- act(() => useSidebarStore.getState().toggle());
- expect(observer.disconnect).not.toHaveBeenCalled();
- expect(titleWrapper().style.opacity).toBe("1");
- expect(useSidebarStore.getState().chatVisibility).toEqual({ chatId: "first", ratio: 1 });
-
- act(() => useSidebarStore.getState().toggle());
- expect(observers).toHaveLength(1);
- expect(titleWrapper().style.opacity).toBe("0");
-
- act(() => useSidebarStore.getState().toggle());
- act(() => observer.emit(0.55));
- expect(titleWrapper().style.opacity).toBe("1");
- act(() => useSidebarStore.getState().toggle());
- expect(Number(titleWrapper().style.opacity)).toBeCloseTo(0.5);
-});
-
-it("tracks the new active row on chat switches and clears visibility when it disappears", () => {
- const view = render(<Harness />);
- const old = observers[0]!;
- act(() => old.emit(1));
- route.chatId = "second";
- view.rerender(<Harness />);
- expect(titleWrapper().style.opacity).toBe("1");
- expect(observers.at(-1)!.observed).toBe(screen.getByRole("button", { name: "Chat second" }));
- act(() => old.emit(1));
- expect(useSidebarStore.getState().chatVisibility).toEqual({ chatId: "second", ratio: 0 });
- act(() => observers.at(-1)!.emit(1));
- expect(titleWrapper().style.opacity).toBe("0");
-
- act(() => useChatStore.setState({ savedChats: [] }));
- expect(titleWrapper().style.opacity).toBe("1");
- expect(useSidebarStore.getState().chatVisibility).toEqual({ chatId: "second", ratio: 0 });
-});
-
-const measureRowAt = (top: number) => {
- vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
- return this.getAttribute("role") === "button" ? new DOMRect(0, top, 200, 20) : new DOMRect(0, 100, 200, 200);
- });
-};
-
-it.each(["Models", "Chats"])("does not flash a visible sidebar title when entering from %s", () => {
- measureRowAt(140);
- route.chatId = undefined;
- const view = render(<Harness />);
- expect(screen.queryByRole("heading", { hidden: true })).toBeNull();
- route.chatId = "first";
- view.rerender(<Harness />);
-
- // No IntersectionObserver callback has been delivered yet.
- expect(useSidebarStore.getState().chatVisibility).toEqual({ chatId: "first", ratio: 1 });
- expect(titleWrapper().style.opacity).toBe("0");
- act(() => observers[0]!.emit(1));
- expect(titleWrapper().style.opacity).toBe("0");
-});
-
-it("initializes clipped rows before the first observer callback", () => {
- measureRowAt(91);
- const view = render(<Harness />);
- expect(useSidebarStore.getState().chatVisibility).toEqual({ chatId: "first", ratio: 0.55 });
- expect(Number(titleWrapper().style.opacity)).toBeCloseTo(0.5);
-
- measureRowAt(400);
- route.chatId = "second";
- view.rerender(<Harness />);
- expect(titleWrapper().style.opacity).toBe("1");
-});
-
-it("waits for current-row visibility only while the sidebar is open", () => {
- const view = render(<ChatHeader title="Cities" isSidebarOpen />);
- expect(titleWrapper().style.opacity).toBe("0");
- act(() => useSidebarStore.getState().setChatVisibility({ chatId: "another", ratio: 0 }));
- expect(titleWrapper().style.opacity).toBe("0");
- view.rerender(<ChatHeader title="Cities" isSidebarOpen={false} />);
- expect(titleWrapper().style.opacity).toBe("1");
-});
-
-it("keeps the title visible when its row is not mounted or observation is unavailable", () => {
- route.chatId = "unsaved";
- const view = render(<Harness />);
- expect(observers).toHaveLength(0);
- expect(titleWrapper().style.opacity).toBe("1");
- vi.stubGlobal("IntersectionObserver", undefined);
- route.chatId = "first";
- view.rerender(<Harness />);
- expect(observers).toHaveLength(0);
- expect(titleWrapper().style.opacity).toBe("1");
-});
-
-it("keeps the new-chat placeholder hidden until the chat has a name", () => {
- const view = render(<ChatHeader title={UNTITLED_CHAT_TITLE} isSidebarOpen={false} />);
- expect(titleWrapper().getAttribute("aria-hidden")).toBe("true");
- expect(titleWrapper().style.opacity).toBe("0");
- view.rerender(<ChatHeader title="Cities" isSidebarOpen={false} />);
- expect(titleWrapper().getAttribute("aria-hidden")).toBe("false");
- expect(titleWrapper().style.opacity).toBe("1");
-});
diff --git a/apps/mirai-gui/client/src/features/chat/components/chat-header.tsx b/apps/mirai-gui/client/src/features/chat/components/chat-header.tsx
deleted file mode 100644
index 4bc714c23..000000000
--- a/apps/mirai-gui/client/src/features/chat/components/chat-header.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { twMerge } from "tailwind-merge";
-import { LoaderIcon } from "@/components/loader";
-import { platformInfo } from "@/platform/platform-info";
-import { useSidebarStore } from "@/stores/use-sidebar-store";
-import { useParams } from "@tanstack/react-router";
-import { UNTITLED_CHAT_TITLE } from "@/constants/chat";
-
-const HEADER_LEFT_RESERVE_PX = platformInfo.features.nativeTitleBar ? 120 : 56;
-
-export const ChatHeader = ({
- title,
- isSidebarOpen,
- isTitleGenerating,
- className,
-}: {
- title: string;
- isSidebarOpen: boolean;
- isTitleGenerating?: boolean;
- className?: string;
-}) => {
- const { chatId } = useParams({ strict: false }) as { chatId?: string };
- const chatVisibility = useSidebarStore((s) => s.chatVisibility);
- const sidebarVisibility = isSidebarOpen
- ? chatVisibility && chatVisibility.chatId === chatId
- ? chatVisibility.ratio
- : 1
- : 0;
- // Fade smoothly between 15% and 75% clipped, staying flat at either end.
- const fadeProgress = Math.max(0, Math.min(1, (0.85 - sidebarVisibility) / 0.6));
- const opacity = title === UNTITLED_CHAT_TITLE ? 0 : fadeProgress * fadeProgress * (3 - 2 * fadeProgress);
- return (
- <div
- data-tauri-drag-region="deep"
- className={twMerge("flex items-center justify-between pb-4 text-center lg:text-left", className)}
- >
- <div
- aria-hidden={opacity === 0}
- className="flex items-center gap-1 w-auto lg:w-auto justify-center lg:justify-start min-w-0 transition-[padding-left,opacity] duration-300 ease-in-out motion-reduce:transition-none"
- style={{ paddingLeft: isSidebarOpen ? 0 : HEADER_LEFT_RESERVE_PX, opacity }}
- >
- <h1
- className={twMerge(
- "text-[13px] font-[350] text-label-muted line-clamp-1",
- !isSidebarOpen && "lg:text-center",
- )}
- >
- {title}
- </h1>
- {isTitleGenerating ? <LoaderIcon width={8} height={8} /> : null}
- </div>
- </div>
- );
-};
diff --git a/apps/mirai-gui/client/src/features/chat/components/chat-page.tsx b/apps/mirai-gui/client/src/features/chat/components/chat-page.tsx
index e2f7d95dd..7bc4de05f 100644
--- a/apps/mirai-gui/client/src/features/chat/components/chat-page.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/chat-page.tsx
@@ -1,16 +1,12 @@
-import { useCallback, useEffect, useState, type CSSProperties } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from "react";
import { useParams, useSearch } from "@tanstack/react-router";
-import { ChatHeader } from "./chat-header";
-import { UNTITLED_CHAT_TITLE } from "@/constants/chat";
import { useToast } from "@/components/ui/toast/use-toast";
-import { useRuntimeSessionStore } from "@/stores/use-runtime-session-store";
import { useChatSessionStore } from "@/stores/use-chat-session-store";
import { useChatStore } from "@/stores/use-chat-store";
import { useModelsStore } from "@/stores/use-models-store";
import { useAppStore } from "@/stores/use-app-store";
import { useGlobalInstructionsStore } from "@/stores/use-global-instructions-store";
-import { useSidebarStore } from "@/stores/use-sidebar-store";
import { isChatGenerating } from "@/features/runtime/runtime-busy";
import { useChatModelSelector } from "../hooks/use-chat-model-selector";
import { useLlmStream } from "../hooks/use-llm-stream";
@@ -28,6 +24,8 @@ import { useModelSwitch } from "../hooks/use-model-switch";
import { useRegenerateMessage } from "../hooks/use-regenerate-message";
import { useSendChatMessage } from "../hooks/use-send-chat-message";
import { useStopChatRun } from "../hooks/use-stop-chat-run";
+import { useIsMobile, useMediaQuery } from "@/hooks/use-media-query";
+import { useSidebarStore } from "@/stores/use-sidebar-store";
type ChatSearchParams = {
isNew?: boolean;
@@ -41,11 +39,14 @@ export function ChatPage() {
const toast = useToast();
- const isSidebarOpen = useSidebarStore((s) => s.isOpen);
const chatWidth = useAppStore((s) => s.chatWidth);
+ // With the sidebar hidden (or floating, in a narrow window), its button and the traffic lights sit
+ // over the conversation's top-left corner, so the top of the list fades under them.
+ const isMobile = useIsMobile();
+ const isSidebarOpen = useSidebarStore((s) => s.isOpen);
+ const chromeOverChat = isMobile || !isSidebarOpen;
const globalInstructions = useGlobalInstructionsStore((s) => s.instructions);
const loadInstructions = useGlobalInstructionsStore((s) => s.loadInstructions);
- const residentSession = useRuntimeSessionStore((s) => s.residentSession);
const isModelLoading = useChatSessionStore((s) => s.isModelLoading);
const isSessionBusy = useChatSessionStore(
(s) => s.operationState !== "idle" || s.isGenerating || s.isTitleGenerating || s.isModelLoading || s.isEjecting,
@@ -53,7 +54,6 @@ export function ChatPage() {
const isTitleGenerating = useChatSessionStore((s) => s.isTitleGenerating);
const titleGenChatId = useChatSessionStore((s) => s.titleGenChatId);
const isTitleGeneratingForChat = isTitleGenerating && titleGenChatId === chatId;
- const savedChats = useChatStore((s) => s.savedChats);
const isChatStreaming = useChatSessionStore((s) => isChatGenerating(s, chatId));
const loadingMessageId = useChatSessionStore((s) =>
s.loadingMessage?.chatId === chatId ? s.loadingMessage.messageId : null,
@@ -85,6 +85,12 @@ export function ChatPage() {
setScrollTargetId(null);
}, []);
+ // A new chat is a place to type: put the cursor in the composer so you can start right away.
+ useEffect(() => {
+ if (!search.isNew) return;
+ document.querySelector<HTMLTextAreaElement>("textarea[data-composer-input]")?.focus({ preventScroll: true });
+ }, [chatId, search.isNew]);
+
useChatSwitchEffect({
chatId,
isNewChat: !!search.isNew,
@@ -98,8 +104,6 @@ export function ChatPage() {
const runStatus = useChatRunStatus({ chatId, modelId: currentModelId });
- const currentChatTitle = savedChats.find((c) => c.id === chatId)?.title || UNTITLED_CHAT_TITLE;
-
useEjectDrivenModelReset({
chatId,
selectedModelId: selectedChatModel.modelId,
@@ -149,27 +153,99 @@ export function ChatPage() {
);
const modelParamsModified = isCustomParams(selectedModelParams, globalModelChatNamingEnabled, selectedModelSize);
+ // A new, empty chat puts the composer in the middle of the page, under the cat. Once the first
+ // message goes out the composer settles at the bottom, gliding there rather than jumping.
+ const hasMessages = useChatStore((s) => s.messages.length > 0);
+ const centered = !!search.isNew && !hasMessages && !isLoading && !isModelLoading;
+ const composerRef = useRef<HTMLDivElement>(null);
+ const composerTopRef = useRef<number | null>(null);
+ // The conversation runs behind the composer to the panel's edge, so the fade and the room at the
+ // end of the list follow the composer's height.
+ const [composerHeight, setComposerHeight] = useState(0);
+ useLayoutEffect(() => {
+ const el = composerRef.current;
+ if (!el) return;
+ const update = () => setComposerHeight(el.offsetHeight);
+ update();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(update);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+ const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
+ // The glide belongs to one moment only: the first message going out in this same new chat.
+ // Arriving at a chat, from wherever, never animates; the composer is simply where it belongs.
+ const settledFromRef = useRef<{ chatId: string; centered: boolean } | null>(null);
+ useLayoutEffect(() => {
+ const el = composerRef.current;
+ const before = composerTopRef.current;
+ const last = settledFromRef.current;
+ settledFromRef.current = { chatId, centered };
+ const sentFirstMessage = last?.chatId === chatId && last.centered && !centered;
+ if (!el || before === null || reducedMotion || !sentFirstMessage) return;
+ const delta = before - el.getBoundingClientRect().top;
+ if (Math.abs(delta) < 2) return;
+ el.animate([{ transform: `translateY(${delta}px)` }, { transform: "none" }], {
+ duration: 520,
+ easing: "cubic-bezier(0.32, 0.72, 0, 1)",
+ });
+ }, [centered, chatId, reducedMotion]);
+ useLayoutEffect(() => {
+ composerTopRef.current = composerRef.current?.getBoundingClientRect().top ?? null;
+ });
+
+ // Sending with no model chosen: the cat is not pleased and glares at the picker, which nudges.
+ const [missingModelAt, setMissingModelAt] = useState(0);
+ const handleMissingModel = () => {
+ setMissingModelAt(Date.now());
+ if (reducedMotion) return;
+ document
+ .querySelector("[data-model-picker]")
+ ?.animate(
+ [
+ { transform: "translateX(0)" },
+ { transform: "translateX(-3px)" },
+ { transform: "translateX(3px)" },
+ { transform: "translateX(-2px)" },
+ { transform: "translateX(0)" },
+ ],
+ { duration: 360, delay: 450, easing: "cubic-bezier(0.32, 0.72, 0, 1)" },
+ );
+ };
+
return (
<div
- className="flex flex-col h-full min-h-0 bg-background pt-4 pb-5 px-5"
- style={{ "--chat-width": `${chatWidth}px` } as CSSProperties}
+ className="flex flex-col h-full min-h-0 bg-background px-5 pb-5"
+ style={
+ {
+ "--chat-width": `${chatWidth}px`,
+ "--composer-h": `${composerHeight}px`,
+ // Room for the top fade, so the first message starts below it.
+ "--chat-list-top": chromeOverChat ? "3.5rem" : "2rem",
+ } as CSSProperties
+ }
>
<div className="w-full flex flex-col h-full min-h-0">
- <ChatHeader
- className="shrink-0"
- title={currentChatTitle}
- isSidebarOpen={isSidebarOpen}
- isTitleGenerating={isTitleGeneratingForChat}
- />
-
- <div className="flex-1 overflow-clip min-h-0 -mx-5">
+ {/* A new chat: the cat and its words (about 197px with the air above the ears, plus 32px of
+ room above them) sit at the bottom of this area, and the leftover height is shared
+ equally above that block and
+ below the composer. The space below starts 64px larger, so the group sits 32px above
+ the true middle, where the eye expects it. */}
+
+ {/* In a conversation the list reaches behind the composer and the gap under it to the panel's
+ edge. A fade covers that stretch: solid page colour in the gap below the composer,
+ clearing toward its top edge, so text beside the composer (the cat, wide content) fades
+ out as it goes down instead of being cut off. */}
+ <div
+ className={`${centered ? "flex-[1_1_229px]" : "flex-1"} relative overflow-clip min-h-0 -mx-5`}
+ style={centered ? undefined : { marginBottom: "calc(-1 * (var(--composer-h) + 1.25rem))" }}
+ >
<ChatMessageList
isNewChat={!!search.isNew}
isChatStreaming={isChatStreaming}
isLoadingStream={isLoading}
isTitleGeneratingForChat={isTitleGeneratingForChat}
isModelLoading={isModelLoading}
- hasResidentModel={residentSession?.repoId === currentModelId}
scrollTargetId={scrollTargetId}
onScrolled={() => setScrollTargetId(null)}
loadingMessageId={loadingMessageId}
@@ -177,10 +253,36 @@ export function ChatPage() {
onMessageModelSelect={handleMessageModelSelect}
onEditMessage={handleEditMessage}
canEditMessages={runStatus.canRun && !isSessionBusy}
+ draft={composer.draft}
+ missingModelAt={missingModelAt}
/>
+ {!centered && (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 h-[calc(var(--composer-h)+1.25rem)] bg-[linear-gradient(to_top,var(--color-background)_1.25rem,transparent)]"
+ />
+ )}
+ {/* The same fade at the top, while the sidebar button sits over it: page colour at the edge,
+ fading to clear over its whole height, with a light blur that clears the same way. */}
+ {!centered && (
+ <>
+ <div
+ aria-hidden
+ className={`pointer-events-none absolute inset-x-0 top-0 h-14 backdrop-blur-[3px] [mask-image:linear-gradient(to_bottom,black,transparent)] transition-opacity duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none ${chromeOverChat ? "opacity-100" : "opacity-0"}`}
+ />
+ <div
+ aria-hidden
+ className={`pointer-events-none absolute inset-x-0 top-0 h-14 bg-[linear-gradient(to_bottom,var(--color-background),transparent)] transition-opacity duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none ${chromeOverChat ? "opacity-100" : "opacity-0"}`}
+ />
+ </>
+ )}
</div>
- <div className="flex-shrink-0 w-full max-w-[var(--chat-width)] mx-auto">
+ {/* 8px wider than the text column on each side. */}
+ <div
+ ref={composerRef}
+ className="relative z-10 flex-shrink-0 self-center w-[calc(100%+1rem)] max-w-[calc(var(--chat-width)+1rem)]"
+ >
<ChatComposer
chatId={chatId}
isChatStreaming={isChatStreaming}
@@ -200,8 +302,10 @@ export function ChatPage() {
onRemoveFile={composer.removeFile}
onOpenModelParams={() => setParamsDrawerOpen(true)}
modelParamsModified={modelParamsModified}
+ onMissingModel={handleMissingModel}
/>
</div>
+ <div aria-hidden className={centered ? "flex-[1_1_76px] min-h-0" : "flex-[0]"} />
</div>
<ModelParamsDrawer
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/chat-composer.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/chat-composer.tsx
index ae9b8d56f..e12af053a 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/chat-composer.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/chat-composer.tsx
@@ -1,3 +1,4 @@
+import { useHeldTrue } from "@/hooks/use-held-true";
import { useToast } from "@/components/ui/toast/use-toast";
import { useInstalledPickerModels } from "../../hooks/use-picker-models";
import { useChatSessionStore } from "@/stores/use-chat-session-store";
@@ -7,6 +8,8 @@ import { MAX_FILES_PER_MESSAGE, SUPPORTED_FILE_TYPES } from "@/constants/attachm
import { isValidFileSize, isValidFileType, processFile } from "../../services/attachment-files";
import { ChatInput } from "./chat-input";
+const UNLOCK_HOLD_MS = 300;
+
type ChatComposerProps = {
chatId: string;
isChatStreaming: boolean;
@@ -26,6 +29,8 @@ type ChatComposerProps = {
onRemoveFile: (fileId: string) => void;
onOpenModelParams: () => void;
modelParamsModified: boolean;
+ /** Called when a message can't go out because no model is chosen. */
+ onMissingModel?: () => void;
};
const ATTACH_ACCEPT = SUPPORTED_FILE_TYPES.text.join(",");
@@ -49,6 +54,7 @@ export const ChatComposer = ({
onRemoveFile,
onOpenModelParams,
modelParamsModified,
+ onMissingModel,
}: ChatComposerProps) => {
const toast = useToast();
@@ -63,8 +69,11 @@ export const ChatComposer = ({
? "A response is already generating in another chat."
: undefined;
- const isLoading = isLoadingStream || isTitleGeneratingForChat;
- const isStreaming = isChatStreaming || isTitleGeneratingForChat;
+ // After an answer the chat is named, but only once the answer has fully finished; for a frame or
+ // two in between nothing is running, and the model picker and send button flickered to enabled and
+ // back. They now unlock only once they have stayed unlocked for a moment.
+ const isLoading = useHeldTrue(isLoadingStream || isTitleGeneratingForChat, UNLOCK_HOLD_MS);
+ const isStreaming = useHeldTrue(isChatStreaming || isTitleGeneratingForChat, UNLOCK_HOLD_MS);
const busy = isStreaming || isLoading || isEjecting;
const handleAttach = async (file: File) => {
@@ -103,7 +112,8 @@ export const ChatComposer = ({
if (files.length > 0) toast.error("Add a message to send attachments");
return;
}
- toast.error(blockedMessage || "Sending is blocked right now");
+ if (!selectedModelId || autoSelectSuppressed) onMissingModel?.();
+ toast.warning(blockedMessage || "Sending is blocked right now");
}}
streaming={isStreaming}
onStop={onStopResponse}
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/attach-menu.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/attach-menu.tsx
index 524954177..28ae96428 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/attach-menu.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/attach-menu.tsx
@@ -1,4 +1,4 @@
-import { File as FileIcon, Plus } from "lucide-react";
+import { FileTextIcon, PlusIcon } from "@/components/icons/app-icons";
import { Button } from "@/components/ui/button";
import { PopoverMenu } from "@/components/ui/popover/popover-menu";
import { Text } from "@/components/ui/typography";
@@ -12,29 +12,29 @@ export function AttachMenu({ onSelectFile }: AttachMenuProps) {
<PopoverMenu
side="top"
align="start"
- sideOffsetPx={4}
- className="min-w-[280px]"
- itemClassName="gap-3 px-2 py-2"
+ sideOffsetPx={8}
+ className="min-w-[260px]"
+ itemClassName="gap-3 px-2.5 py-2"
trigger={
<Button
size="xs"
kind="ghost"
iconOnly
ariaLabel="Attach file"
- icon={<Plus size={18} />}
- className="bg-surface-tertiary text-text-muted hover:bg-control-surface-hover hover:text-text-primary"
+ icon={<PlusIcon size={18} aria-hidden />}
+ className="rounded-full bg-control-fill text-text-secondary hover:bg-control-fill-hover hover:text-text-primary"
/>
}
items={[
{
id: "upload",
- icon: <FileIcon size={16} className="text-text-muted shrink-0" />,
+ icon: <FileTextIcon size={18} className="text-text-muted shrink-0" aria-hidden />,
label: (
<span>
- <Text as="span" color="primary" opticalSize={14} className="block text-[13px] font-[450] leading-[1.3]">
+ <Text as="span" color="primary" className="block text-[13px] font-[500] leading-[1.3]">
Upload a file
</Text>
- <Text as="span" color="muted" className="block text-[11px] leading-[1.4]">
+ <Text as="span" color="muted" className="mt-0.5 block text-[12px] leading-[1.35]">
Supports TXT, MD, JSON, CSV, YAML
</Text>
</span>
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/file-chip.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/file-chip.tsx
index d8342e307..e1bb4ef9a 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/file-chip.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/file-chip.tsx
@@ -25,7 +25,7 @@ export function FileChip({ file, onRemove }: FileChipProps) {
return (
<div
- className="relative group flex items-center gap-2 rounded-md bg-surface-tertiary px-2 py-2 min-w-[80px]"
+ className="relative group flex items-center gap-2 rounded-md bg-control-fill px-2 py-2 min-w-[80px]"
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/index.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/index.tsx
index 52a6b6286..4b011e3de 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/index.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/index.tsx
@@ -1,5 +1,5 @@
+import { SettingsIcon } from "@/components/left-bar/nav-icons";
import { Button } from "@headlessui/react";
-import { Settings } from "lucide-react";
import { useCallback, useRef } from "react";
import { twMerge } from "tailwind-merge";
import { TextArea } from "@/components/ui/text-area";
@@ -50,7 +50,7 @@ export function ChatInput({
}, []);
return (
- <div className="rounded-xl bg-surface-elevated shadow-md p-4 w-full">
+ <div className="rounded-[20px] bg-surface-elevated shadow-md px-4 pt-4 pb-3 w-full transition-shadow duration-150 ease-out focus-within:shadow-lg dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)] dark:focus-within:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.18)]">
<input
ref={fileInputRef}
type="file"
@@ -75,6 +75,7 @@ export function ChatInput({
<TextArea
ref={controller.textareaRef}
+ data-composer-input
value={value}
onChange={onChange}
onKeyDown={controller.handleKeyDown}
@@ -106,9 +107,10 @@ export function ChatInput({
onClick={onModelSettingsClick}
disabled={settingsDisabled}
aria-label="Model settings"
- className="flex size-7 shrink-0 items-center justify-center rounded-md bg-surface-tertiary text-text-muted outline-hidden transition-colors duration-150 ease-out hover:bg-control-surface-hover hover:text-text-primary data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-50"
+ className="flex size-7 shrink-0 items-center justify-center rounded-full bg-control-fill text-text-secondary outline-hidden transition-colors duration-150 ease-out hover:bg-control-fill-hover hover:text-text-primary data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-50"
>
- <Settings size={16} />
+ {/* Lands half a point low on Retina screens; lifted back to the circle's centre. */}
+ <SettingsIcon size={16} aria-hidden />
</Button>
{settingsModified && (
<span className="pointer-events-none absolute right-0.5 top-0.5 size-1.5 rounded-full bg-danger ring-1 ring-surface-elevated" />
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/model-picker.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/model-picker.tsx
index 833da13ba..e2859ece0 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/model-picker.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/model-picker.tsx
@@ -1,11 +1,12 @@
import { Link } from "@tanstack/react-router";
-import { ChevronDown } from "lucide-react";
+import { ChevronDown, ChevronRight } from "lucide-react";
import { Menu, MenuButton, MenuItem, MenuItems, Transition } from "@headlessui/react";
import { forwardRef, Fragment } from "react";
import { SelectionItem } from "@/components/ui/select/selection-item";
import { SelectionPanel } from "@/components/ui/select/selection-panel";
import { SelectionSection } from "@/components/ui/select/selection-section";
import { Text } from "@/components/ui/typography";
+import { ModelName } from "@/components/model-name";
import type { ChatInputModel, ChatInputMoreModelsLink } from "./types";
export type ModelPickerProps = {
@@ -67,10 +68,11 @@ export function ModelPicker({
{({ close }) => (
<div className="relative">
<MenuButton
+ data-model-picker
as="button"
type="button"
disabled={disabled}
- className="group/model flex items-center gap-2 h-7 px-2 max-w-full rounded-md bg-surface-tertiary hover:bg-control-surface-hover data-[headlessui-state~=open]:bg-control-surface-active data-[focus]:bg-control-surface-hover cursor-pointer border-none outline-hidden data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-40"
+ className="group/model flex items-center gap-2 h-7 px-2.5 max-w-full rounded-full bg-control-fill hover:bg-control-fill-hover data-[headlessui-state~=open]:bg-control-fill-hover data-[focus]:bg-control-fill-hover cursor-pointer border-none outline-hidden data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-40"
>
{activeModel && (
<span className="shrink-0 flex items-center justify-center w-3.5 h-3.5 [&>svg]:w-3.5 [&>svg]:h-3.5">
@@ -81,36 +83,36 @@ export function ModelPicker({
as="span"
color="muted"
opticalSize={14}
- className={`min-w-0 truncate ${TEXT_13_CLASSNAME} group-hover/model:text-text-primary group-data-[focus]/model:text-text-primary group-data-[headlessui-state~=open]/model:text-text-primary`}
+ className={`min-w-0 truncate ${TEXT_13_CLASSNAME} text-text-secondary group-hover/model:text-text-primary group-data-[focus]/model:text-text-primary group-data-[headlessui-state~=open]/model:text-text-primary`}
>
- {activeModel ? activeModel.name : "Select model"}
+ {activeModel ? <ModelName name={activeModel.name} /> : "Select model"}
</Text>
<ChevronDown
size={16}
- className="shrink-0 text-text-muted group-hover/model:text-text-primary group-data-[focus]/model:text-text-primary group-data-[headlessui-state~=open]/model:text-text-primary"
+ className="shrink-0 text-text-secondary group-hover/model:text-text-primary group-data-[focus]/model:text-text-primary group-data-[headlessui-state~=open]/model:text-text-primary"
/>
</MenuButton>
<Transition
as={Fragment}
- enter="transition-[opacity,scale] duration-[120ms] ease-spring"
- enterFrom="opacity-0 scale-90"
+ enter="transition-[opacity,scale] duration-200 ease-spring motion-reduce:transition-none"
+ enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
- leave="transition-[opacity,scale] duration-[80ms] ease-spring"
+ leave="transition-[opacity,scale] duration-[140ms] ease-spring motion-reduce:transition-none"
leaveFrom="opacity-100 scale-100"
- leaveTo="opacity-0 scale-90"
+ leaveTo="opacity-0 scale-95"
>
<div
className={
menuPlacement === "up"
- ? "absolute right-0 bottom-full pb-1 z-50 origin-bottom-right"
- : "absolute right-0 top-full pt-1 z-50 origin-top-right"
+ ? "absolute right-0 bottom-full pb-2 z-50 origin-bottom-right"
+ : "absolute right-0 top-full pt-2 z-50 origin-top-right"
}
>
<MenuItems className="outline-hidden">
- <SelectionPanel className="pt-1.5 min-w-[240px]">
- {/* Reserve the scrollbar width before WebKit measures the popup. */}
- <SelectionSection className="max-h-[280px] overflow-y-scroll overscroll-y-contain thin-scrollbar">
+ <SelectionPanel className="py-1 min-w-[240px]">
+ {/* No reserved scrollbar gutter: it made the right inset wider than the left. */}
+ <SelectionSection className="max-h-[280px] overflow-y-auto overscroll-y-contain scrollbar-hide">
{models?.map((model) => (
<MenuItem key={model.id}>
{({ focus }) => (
@@ -129,9 +131,9 @@ export function ModelPicker({
as="span"
color="primary"
opticalSize={14}
- className={`whitespace-nowrap ${TEXT_13_CLASSNAME}`}
+ className={`min-w-0 flex-1 ${TEXT_13_CLASSNAME}`}
>
- {model.name}
+ <ModelName name={model.name} />
</Text>
</SelectionRow>
)}
@@ -140,7 +142,7 @@ export function ModelPicker({
</SelectionSection>
{moreModelsLink && (
- <SelectionSection divided className="py-1.5">
+ <SelectionSection divided>
<MenuItem>
{({ focus }) => (
<SelectionItem
@@ -151,11 +153,13 @@ export function ModelPicker({
moreModelsLink.onClick?.();
close();
}}
- className="flex items-center w-full bg-transparent text-text-primary"
+ className="flex items-center justify-between gap-2.5 w-full bg-transparent text-text-primary"
>
+ {/* Same row as the Regenerate menu's: the label, then a chevron to the Models page. */}
<Text as="span" color="primary" opticalSize={14} className={TEXT_13_CLASSNAME}>
- Download more models
+ Download models
</Text>
+ <ChevronRight className="size-4 shrink-0 text-label-muted" aria-hidden />
</SelectionItem>
)}
</MenuItem>
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/reasoning-selector.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/reasoning-selector.tsx
index 32c41eec3..e77ec7dc9 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/reasoning-selector.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/reasoning-selector.tsx
@@ -1,5 +1,5 @@
import { Menu, MenuButton, MenuItem, MenuItems, Transition } from "@headlessui/react";
-import { Brain, ChevronDown } from "lucide-react";
+import { ChevronDown } from "lucide-react";
import { Fragment } from "react";
import { SelectionItem } from "@/components/ui/select/selection-item";
import { SelectionPanel } from "@/components/ui/select/selection-panel";
@@ -65,24 +65,23 @@ export const ReasoningSelector = ({ repoId, disabled = false }: ReasoningSelecto
disabled={disabled}
aria-label={selected ? `Reasoning: ${label}${isDefault ? ", model default" : ""}` : "Reasoning"}
title={selected ? `Reasoning: ${label}` : "Reasoning"}
- className="flex h-7 items-center gap-1.5 rounded-md bg-surface-tertiary px-2 text-text-muted text-[13px] font-[450] leading-[1.3] outline-hidden hover:bg-control-surface-hover hover:text-text-primary data-[headlessui-state~=open]:bg-control-surface-active data-[headlessui-state~=open]:text-text-primary data-[focus]:bg-control-surface-hover data-[focus]:text-text-primary data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-40"
+ className="flex h-7 items-center gap-1.5 rounded-full bg-control-fill pl-3 pr-2 text-text-secondary text-[13px] font-[450] leading-[1.3] outline-hidden hover:bg-control-fill-hover hover:text-text-primary data-[headlessui-state~=open]:bg-control-fill-hover data-[headlessui-state~=open]:text-text-primary data-[focus]:bg-control-fill-hover data-[focus]:text-text-primary data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-40"
>
- <Brain size={14} aria-hidden="true" />
<span>{label}</span>
<ChevronDown size={16} aria-hidden="true" />
</MenuButton>
<Transition
as={Fragment}
- enter="transition-[opacity,scale] duration-[120ms] ease-spring"
- enterFrom="opacity-0 scale-90"
+ enter="transition-[opacity,scale] duration-200 ease-spring motion-reduce:transition-none"
+ enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
- leave="transition-[opacity,scale] duration-[80ms] ease-spring"
+ leave="transition-[opacity,scale] duration-[140ms] ease-spring motion-reduce:transition-none"
leaveFrom="opacity-100 scale-100"
- leaveTo="opacity-0 scale-90"
+ leaveTo="opacity-0 scale-95"
>
- <div className="absolute right-0 bottom-full pb-1 z-50 origin-bottom-right">
+ <div className="absolute right-0 bottom-full pb-2 z-50 origin-bottom-right">
<MenuItems aria-label="Reasoning" className="outline-hidden">
- <SelectionPanel className="min-w-[160px] pt-1.5">
+ <SelectionPanel className="min-w-[160px] py-1">
<SelectionSection>
{options.map((option) => (
<MenuItem key={option} disabled={disabled}>
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/send-button.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/send-button.tsx
index 1721be45d..282496fdf 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/send-button.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/chat-input/send-button.tsx
@@ -1,7 +1,7 @@
import { twMerge } from "tailwind-merge";
import { Button } from "@/components/ui/button";
-import { IconPlayerStopFilled } from "@/components/icons/player-stop-filled-icon";
-import { IconSend } from "@/components/icons/send-icon";
+import { SquareIcon } from "@/components/icons/square-icon";
+import { ArrowUpIcon } from "@/components/icons/arrow-up-icon";
export type SendButtonProps = {
disabled: boolean;
@@ -19,9 +19,13 @@ export function SendButton({ disabled, hasContent, onClick, streaming = false, o
kind="primary"
iconOnly
ariaLabel="Stop generating"
- icon={<IconPlayerStopFilled size={14} />}
+ icon={
+ <span key="stop" className="flex animate-uzu-swap">
+ <SquareIcon size={14} />
+ </span>
+ }
onClick={onStop}
- className="active:scale-100"
+ className="rounded-full active:scale-100"
/>
);
}
@@ -32,12 +36,16 @@ export function SendButton({ disabled, hasContent, onClick, streaming = false, o
kind={hasContent ? "primary" : "ghost"}
iconOnly
ariaLabel="Send message"
- icon={<IconSend />}
+ icon={
+ <span key="send" className="flex animate-uzu-swap">
+ <ArrowUpIcon />
+ </span>
+ }
disabled={disabled}
onClick={onClick}
className={twMerge(
- "active:scale-100",
- hasContent ? "" : "bg-surface-tertiary text-text-disabled cursor-not-allowed opacity-100",
+ "rounded-full active:scale-100",
+ hasContent ? "" : "bg-control-fill text-text-disabled cursor-not-allowed opacity-100",
)}
/>
);
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/model-params-controls.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/model-params-controls.tsx
index 122d2c30c..c983d0f3d 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/model-params-controls.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/model-params-controls.tsx
@@ -53,7 +53,7 @@ const ChangedMarker = () => (
const SectionHeading = ({ name, changed, onReset }: { name: string; changed: boolean; onReset: () => void }) => (
<div className="flex h-5 items-center gap-1">
- <span className="text-[12px] font-[450] text-label-muted">{name}</span>
+ <span className="text-[13px] font-[500] text-label-muted">{name}</span>
{changed && (
<Button
type="button"
@@ -164,8 +164,8 @@ export const ModelParamsControls = ({ repoId, samplingDefaults: modelDefaults }:
};
return (
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-1.5">
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-2">
<SectionHeading name="Sampling" changed={samplingChanged} onReset={resetSampling} />
<SegmentedControl
ariaLabel="Sampling"
@@ -195,7 +195,7 @@ export const ModelParamsControls = ({ repoId, samplingDefaults: modelDefaults }:
transition={{ duration: 0.2, ease: "easeInOut" }}
className="overflow-clip"
>
- <div className="flex flex-col gap-3 pt-3">
+ <div className="flex flex-col gap-4 pt-1">
<NumberSliderRow
label="Temperature"
changed={fieldChanged("temperature")}
@@ -279,21 +279,25 @@ export const ModelParamsControls = ({ repoId, samplingDefaults: modelDefaults }:
)}
</AnimatePresence>
- <div className="flex flex-col gap-3 border-t border-cell-border pt-3">
+ <div className="flex flex-col gap-4 pt-3">
<SectionHeading
name="Tools"
changed={dateTimeChanged || chartChanged || chatNamingChanged}
onReset={resetTools}
/>
{!supportsTools && (
- <p className="text-[12px] leading-relaxed text-label-muted">This model does not support tool calls.</p>
+ <p className="text-[13px] leading-[1.45] text-label-muted text-pretty">
+ This model does not support tool calls.
+ </p>
)}
<div className="flex items-start justify-between gap-3">
<div className="flex flex-col gap-1">
- <span className="text-[13px] text-label-title">
+ <span className="text-[14px] font-[450] text-label-title">
Current date and time{dateTimeChanged && <ChangedMarker />}
</span>
- <p className="text-[12px] leading-relaxed text-label-muted">Look up the current local date and time.</p>
+ <p className="text-[13px] leading-[1.45] text-label-muted text-pretty">
+ Look up the current local date and time.
+ </p>
</div>
<Toggle
label="Current date and time"
@@ -304,8 +308,10 @@ export const ModelParamsControls = ({ repoId, samplingDefaults: modelDefaults }:
</div>
<div className="flex items-start justify-between gap-3">
<div className="flex flex-col gap-1">
- <span className="text-[13px] text-label-title">Draw charts{chartChanged && <ChangedMarker />}</span>
- <p className="text-[12px] leading-relaxed text-label-muted">Show charts in replies.</p>
+ <span className="text-[14px] font-[450] text-label-title">
+ Draw charts{chartChanged && <ChangedMarker />}
+ </span>
+ <p className="text-[13px] leading-[1.45] text-label-muted text-pretty">Show charts in replies.</p>
</div>
<Toggle
label="Draw charts"
@@ -317,8 +323,10 @@ export const ModelParamsControls = ({ repoId, samplingDefaults: modelDefaults }:
{globalModelChatNamingEnabled && (
<div className="flex items-start justify-between gap-3">
<div className="flex flex-col gap-1">
- <span className="text-[13px] text-label-title">Name chat{chatNamingChanged && <ChangedMarker />}</span>
- <p className="text-[12px] leading-relaxed text-label-muted">
+ <span className="text-[14px] font-[450] text-label-title">
+ Name chat{chatNamingChanged && <ChangedMarker />}
+ </span>
+ <p className="text-[13px] leading-[1.45] text-label-muted text-pretty">
Name and rename the chat using a tool call.
</p>
</div>
@@ -393,7 +401,7 @@ const NumberSliderRow = ({
<div className="flex items-center justify-between gap-3">
<div className="flex items-center">
<div className="flex items-center gap-2">
- <span id={labelId} className="text-[13px] text-label-title">
+ <span id={labelId} className="text-[14px] font-[450] text-label-title">
{label}
</span>
{optional && (
@@ -408,7 +416,7 @@ const NumberSliderRow = ({
aria-labelledby={labelId}
inputMode="decimal"
disabled={!active}
- className="w-20"
+ className="w-20 rounded-lg border-transparent bg-control-fill hover:border-transparent focus-within:border-border-outlined tabular-nums"
value={active ? draft : ""}
onChange={(e) => onInput(e.target.value)}
onBlur={onBlur}
@@ -423,7 +431,7 @@ const NumberSliderRow = ({
step={step}
value={value}
onChange={(e) => onChange(Number(e.target.value))}
- className="my-1 h-1.5 w-full cursor-pointer appearance-none rounded-full bg-slider-track [&::-webkit-slider-thumb]:size-3 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-text-primary"
+ className="my-1.5 h-1 w-full cursor-pointer appearance-none rounded-full bg-slider-track outline-hidden [&::-webkit-slider-thumb]:size-4 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-surface-popover [&::-webkit-slider-thumb]:shadow-[0_0_0_0.5px_rgb(0_0_0/0.12),0_1px_3px_rgb(0_0_0/0.18)] dark:[&::-webkit-slider-thumb]:shadow-[0_0_0_0.5px_rgb(255_255_255/0.2),0_1px_3px_rgb(0_0_0/0.5)] [&::-webkit-slider-thumb]:transition-transform [&::-webkit-slider-thumb]:duration-150 active:[&::-webkit-slider-thumb]:scale-110 focus-visible:[&::-webkit-slider-thumb]:shadow-focus"
/>
)}
</div>
diff --git a/apps/mirai-gui/client/src/features/chat/components/composer/model-params-drawer.tsx b/apps/mirai-gui/client/src/features/chat/components/composer/model-params-drawer.tsx
index 265088e91..13af6976a 100644
--- a/apps/mirai-gui/client/src/features/chat/components/composer/model-params-drawer.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/composer/model-params-drawer.tsx
@@ -56,30 +56,31 @@ export const ModelParamsDrawer = ({ open, chatId, repoId, onClose }: ModelParams
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
- <div className="fixed inset-0 bg-black/25" />
+ <div className="fixed inset-0 bg-black/20" />
</TransitionChild>
- <div className="fixed inset-y-0 right-0 flex max-w-full">
+ {/* A floating sheet inset from the window edges, on the same surface as menus. */}
+ <div className="fixed inset-y-2 right-2 flex max-w-[calc(100%-1rem)]">
<TransitionChild
as={Fragment}
- enter="transform transition ease-out duration-300"
- enterFrom="translate-x-full"
+ enter="transition-transform duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none"
+ enterFrom="translate-x-[calc(100%+0.5rem)]"
enterTo="translate-x-0"
- leave="transform transition ease-in duration-200"
+ leave="transition-transform duration-200 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none"
leaveFrom="translate-x-0"
- leaveTo="translate-x-full"
+ leaveTo="translate-x-[calc(100%+0.5rem)]"
>
- <DialogPanel className="flex h-full w-[320px] flex-col border-l border-cell-border bg-bg-modal px-5 pb-6 pt-[18px] shadow-xl">
+ <DialogPanel className="flex h-full w-[340px] flex-col overflow-clip rounded-2xl bg-surface-popover px-5 pt-4 shadow-popover">
<div className="flex items-center justify-between gap-3">
- <DialogTitle as="h3" className="text-[17px] font-medium leading-[130%] text-label-title">
+ <DialogTitle as="h3" className="text-[16px] font-[600] leading-[1.3] text-label-title">
Edit parameters
</DialogTitle>
<Button
onClick={onClose}
- className="text-label-muted transition-colors hover:text-label-title outline-hidden data-[focus]:shadow-focus"
+ className="-mr-1.5 flex size-8 items-center justify-center rounded-full text-label-muted transition-colors duration-150 ease-out hover:bg-control-fill-hover hover:text-label-title outline-hidden data-[focus]:shadow-focus"
aria-label="Close"
>
- <X className="h-5 w-5" />
+ <X className="size-[18px]" />
</Button>
</div>
@@ -93,7 +94,8 @@ export const ModelParamsDrawer = ({ open, chatId, repoId, onClose }: ModelParams
/>
</div>
- <div className="mt-4 flex-1 min-h-0 overflow-y-auto overscroll-y-contain">
+ {/* Runs to the panel's bottom edge; the closing padding scrolls with the list. */}
+ <div className="mt-5 -mx-5 px-5 pb-5 flex-1 min-h-0 overflow-y-auto overscroll-y-contain thin-scrollbar">
{repoId &&
(defaults?.repoId === repoId ? (
<ModelParamsControls
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/assistant-cat.tsx b/apps/mirai-gui/client/src/features/chat/components/message/assistant-cat.tsx
new file mode 100644
index 000000000..5a79f31ad
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/assistant-cat.tsx
@@ -0,0 +1,79 @@
+import { useEffect, useRef, useState } from "react";
+import { UzuCat, UzuCatStill, type UzuCatState } from "@/components/uzu-cat";
+import { TextShimmer } from "@/components/ui/text-shimmer";
+
+/** What the run behind an assistant message is doing right now. */
+export type AssistantPhase =
+ "loadingModel" | "reading" | "thinking" | "tool" | "writing" | "done" | "stopped" | "error" | "outOfMemory";
+
+const CAT: Record<AssistantPhase, UzuCatState> = {
+ loadingModel: "loading",
+ reading: "reading",
+ thinking: "thinking",
+ tool: "tool",
+ writing: "writing",
+ done: "done",
+ stopped: "idle",
+ error: "idle",
+ outOfMemory: "memory",
+};
+
+/** Before the first token, the cat's row carries the status in words too. */
+export const PENDING_LABEL: Partial<Record<AssistantPhase, string>> = {
+ loadingModel: "Loading the model…",
+ reading: "Reading your message…",
+};
+
+export const CAT_SIZE = 28;
+
+/**
+ * The cat beside an answer. The newest answer gets the live cat, which follows the run (goggles
+ * while the prompt is read, a daydream while thinking, gears for tools, lines of text while
+ * writing), is pleased for a moment when it finishes, and then looks at you. Older answers keep a
+ * still cat so the history stays calm.
+ */
+export function AssistantCat({ phase, live }: { phase: AssistantPhase; live: boolean }) {
+ // Pleased only when an answer finishes in front of you, not when an old chat is opened.
+ const [cheering, setCheering] = useState(false);
+ const previous = useRef(phase);
+ useEffect(() => {
+ const finished = phase === "done" && previous.current !== "done";
+ previous.current = phase;
+ if (!finished) return;
+ setCheering(true);
+ const timer = setTimeout(() => setCheering(false), 1800);
+ return () => clearTimeout(timer);
+ }, [phase]);
+
+ if (!live) return <UzuCatStill size={CAT_SIZE} className="text-text-primary" />;
+ const state: UzuCatState = phase === "done" ? (cheering ? "done" : "follow") : CAT[phase];
+ return (
+ <UzuCat state={state} size={CAT_SIZE} className="text-text-primary" label={`uzu, ${LABEL[state] ?? "ready"}`} />
+ );
+}
+
+const LABEL: Partial<Record<UzuCatState, string>> = {
+ loading: "loading the model",
+ reading: "reading",
+ thinking: "thinking",
+ tool: "using a tool",
+ writing: "writing",
+ done: "done",
+ memory: "short on memory",
+};
+
+/** The status row shown before an answer has any content. */
+export function PendingStatus({ phase }: { phase: AssistantPhase }) {
+ const label = PENDING_LABEL[phase];
+ if (!label) return null;
+ return (
+ <span key={phase} className="flex h-7 items-center animate-uzu-swap">
+ <TextShimmer
+ duration={1.6}
+ className="text-[15px] font-[400] leading-[1.3] [--base-color:var(--color-label-muted)]"
+ >
+ {label}
+ </TextShimmer>
+ </span>
+ );
+}
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/chat-message-list.tsx b/apps/mirai-gui/client/src/features/chat/components/message/chat-message-list.tsx
index 520cec491..873bf4f5b 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/chat-message-list.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/chat-message-list.tsx
@@ -6,7 +6,6 @@ type ChatMessageListProps = {
isLoadingStream: boolean;
isTitleGeneratingForChat: boolean;
isModelLoading: boolean;
- hasResidentModel: boolean;
scrollTargetId: string | null;
onScrolled: () => void;
loadingMessageId: string | null;
@@ -14,6 +13,8 @@ type ChatMessageListProps = {
onMessageModelSelect: (messageId: string, modelId: string, modelName: string) => void;
onEditMessage: (messageId: string, text: string, onSaved: () => void) => Promise<void>;
canEditMessages: boolean;
+ draft: string;
+ missingModelAt: number;
};
export const ChatMessageList = ({
@@ -22,7 +23,6 @@ export const ChatMessageList = ({
isLoadingStream,
isTitleGeneratingForChat,
isModelLoading,
- hasResidentModel,
scrollTargetId,
onScrolled,
loadingMessageId,
@@ -30,6 +30,8 @@ export const ChatMessageList = ({
onMessageModelSelect,
onEditMessage,
canEditMessages,
+ draft,
+ missingModelAt,
}: ChatMessageListProps) => (
<MessageList
isNew={isNewChat}
@@ -43,6 +45,7 @@ export const ChatMessageList = ({
loadingMessageId={loadingMessageId}
canceledMessageId={canceledMessageId}
isModelLoading={isModelLoading}
- hasResidentModel={hasResidentModel}
+ draft={draft}
+ missingModelAt={missingModelAt}
/>
);
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.test.tsx b/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.test.tsx
index 4c33310a5..912d404b0 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.test.tsx
@@ -27,7 +27,11 @@ afterEach(cleanup);
const html = (content: string, stock: boolean, small: boolean) => {
control.stock = stock;
const view = render(<MarkdownRenderer content={content} useOneFontSize={small} />);
- const output = view.container.innerHTML.replace(/ node="\[object Object\]"/g, "").replace(/>\n+</g, "><");
+ const output = view.container.innerHTML
+ .replace(/ node="\[object Object\]"/g, "")
+ .replace(/>\n+</g, "><")
+ // Icons name their masks with useId, which differs from one render to the next.
+ .replace(/:r[0-9a-z]+:/g, ":id:");
cleanup();
return output;
};
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/markdown-renderer.tsx b/apps/mirai-gui/client/src/features/chat/components/message/markdown-renderer.tsx
index e5ce4d733..4a5f118c0 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/markdown-renderer.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/markdown-renderer.tsx
@@ -1,3 +1,4 @@
+import { DownloadIcon, CircleCheckIcon, CopyIcon } from "@/components/icons/app-icons";
import { CopyButton } from "@/components/ui/copy-button";
import { Checkbox } from "@/components/ui/checkbox";
import { useAppStore } from "@/stores/use-app-store";
@@ -26,6 +27,14 @@ type MarkdownRendererProps = {
const LINK_SAFETY = { enabled: false } as const;
// The default placeholder href gets sanitized into "[blocked]" mid-stream.
const REMEND = { linkMode: "text-only" } as const;
+// Code blocks keep Streamdown's own buttons and copy/download behaviour, with our icons in them: the
+// copy icon and filled check from under messages, and the tray for download. Streamdown asks for
+// 14px; ours are drawn for 16.
+const CODE_BLOCK_ICONS = {
+ CopyIcon: () => <CopyIcon size={16} />,
+ CheckIcon: () => <CircleCheckIcon size={16} className="text-label-title" />,
+ DownloadIcon: () => <DownloadIcon size={16} />,
+};
type MarkdownComponentProps<K extends keyof JSX.IntrinsicElements> = JSX.IntrinsicElements[K] & { node?: Element };
@@ -106,13 +115,13 @@ const CustomComponents = {
</h6>
),
p: ({ children, ...props }: MarkdownComponentProps<"p">) => (
- <p className="mb-3 mt-2 text-[15px] font-[350] leading-[150%]" {...props}>
+ <p className="mb-3 mt-2 text-[15px] font-[400] leading-[1.6]" {...props}>
{children}
</p>
),
ul: ({ children, ...props }: MarkdownComponentProps<"ul">) => (
<ul
- className="mb-3 ml-[9px] list-disc text-[15px] font-[350] leading-[150%] text-label-title space-y-3 mt-3 pl-[10px]"
+ className="mb-3 ml-[9px] list-disc text-[15px] font-[400] leading-[1.6] text-label-title space-y-3 mt-3 pl-[10px]"
{...props}
>
{children}
@@ -120,7 +129,7 @@ const CustomComponents = {
),
ol: ({ children, ...props }: MarkdownComponentProps<"ol">) => (
<ol
- className="mb-3 list-decimal list-inside text-[15px] font-[350] leading-[150%] text-label-title space-y-3 mt-3 tabular-nums marker:[font-variant-numeric:tabular-nums]"
+ className="mb-3 list-decimal list-inside text-[15px] font-[400] leading-[1.6] text-label-title space-y-3 mt-3 tabular-nums marker:[font-variant-numeric:tabular-nums]"
{...props}
>
{children}
@@ -128,7 +137,7 @@ const CustomComponents = {
),
li: ({ children, ...props }: MarkdownComponentProps<"li">) => (
<li
- className="text-[15px] font-[350] leading-[150%] text-label-title mb-3 last:mb-0 tabular-nums [&>p:first-child]:inline [&>p:first-child]:m-0"
+ className="text-[15px] font-[400] leading-[1.6] text-label-title mb-3 last:mb-0 tabular-nums [&>p:first-child]:inline [&>p:first-child]:m-0"
{...props}
>
{children}
@@ -136,7 +145,7 @@ const CustomComponents = {
),
blockquote: ({ children, ...props }: MarkdownComponentProps<"blockquote">) => (
<blockquote
- className="border-l-[4px] border-button-border pl-3 text-[15px] font-[350] leading-[150%] text-label-title my-3"
+ className="border-l-[4px] border-button-border pl-3 text-[15px] font-[400] leading-[1.6] text-label-title my-3"
{...props}
>
{children}
@@ -156,14 +165,14 @@ const CustomComponents = {
),
th: ({ children, ...props }: MarkdownComponentProps<"th">) => (
<th
- className="px-2 py-3 first:pl-0 last:pr-0 text-left text-[15px] font-[350] leading-[150%] text-label-title"
+ className="px-2 py-3 first:pl-0 last:pr-0 text-left text-[15px] font-[400] leading-[1.6] text-label-title"
{...props}
>
{children}
</th>
),
td: ({ children, ...props }: MarkdownComponentProps<"td">) => (
- <td className="px-2 py-3 first:pl-0 last:pr-0 text-[15px] font-[350] leading-[150%] text-label-title" {...props}>
+ <td className="px-2 py-3 first:pl-0 last:pr-0 text-[15px] font-[400] leading-[1.6] text-label-title" {...props}>
{children}
</td>
),
@@ -182,12 +191,12 @@ const CustomComponents = {
return <input type={type} {...props} />;
},
strong: ({ children, ...props }: MarkdownComponentProps<"strong">) => (
- <strong className="text-[15px] font-medium leading-[150%] tracking-[0.2px] text-label-title" {...props}>
+ <strong className="text-[15px] font-medium leading-[1.6] tracking-[0.2px] text-label-title" {...props}>
{children}
</strong>
),
em: ({ children, ...props }: MarkdownComponentProps<"em">) => (
- <em className="text-[15px] italic font-normal leading-[150%] text-label-title" {...props}>
+ <em className="text-[15px] italic font-normal leading-[1.6] text-label-title" {...props}>
{children}
</em>
),
@@ -195,60 +204,63 @@ const CustomComponents = {
const OneFontSizeComponents = {
h1: ({ children, ...props }: MarkdownComponentProps<"h1">) => (
- <h1 className="text-xs font-medium mb-1" {...props}>
+ <h1 className="font-medium mb-1" {...props}>
{children}
</h1>
),
h2: ({ children, ...props }: MarkdownComponentProps<"h2">) => (
- <h2 className="text-xs font-medium mb-1" {...props}>
+ <h2 className="font-medium mb-1" {...props}>
{children}
</h2>
),
h3: ({ children, ...props }: MarkdownComponentProps<"h3">) => (
- <h3 className="text-xs font-medium mb-1" {...props}>
+ <h3 className="font-medium mb-1" {...props}>
{children}
</h3>
),
h4: ({ children, ...props }: MarkdownComponentProps<"h4">) => (
- <h4 className="text-xs font-medium mb-1" {...props}>
+ <h4 className="font-medium mb-1" {...props}>
{children}
</h4>
),
h5: ({ children, ...props }: MarkdownComponentProps<"h5">) => (
- <h5 className="text-xs font-medium mb-1" {...props}>
+ <h5 className="font-medium mb-1" {...props}>
{children}
</h5>
),
h6: ({ children, ...props }: MarkdownComponentProps<"h6">) => (
- <h6 className="text-xs font-medium mb-1" {...props}>
+ <h6 className="font-medium mb-1" {...props}>
{children}
</h6>
),
p: ({ children, ...props }: MarkdownComponentProps<"p">) => (
- <p className="mb-1 mt-1 text-xs font-[350]" {...props}>
+ <p className="mb-1 mt-1 font-[inherit]" {...props}>
{children}
</p>
),
ul: ({ children, ...props }: MarkdownComponentProps<"ul">) => (
- <ul className="mb-2 ml-[9px] list-disc text-xs font-[350] space-y-2 mt-2 pl-[10px]" {...props}>
+ <ul className="mb-2 ml-[9px] list-disc font-[inherit] space-y-2 mt-2 pl-[10px]" {...props}>
{children}
</ul>
),
ol: ({ children, ...props }: MarkdownComponentProps<"ol">) => (
<ol
- className="mb-2 list-decimal list-inside text-xs font-[350] space-y-2 mt-2 tabular-nums marker:[font-variant-numeric:tabular-nums]"
+ className="mb-2 list-decimal list-inside font-[inherit] space-y-2 mt-2 tabular-nums marker:[font-variant-numeric:tabular-nums]"
{...props}
>
{children}
</ol>
),
li: ({ children, ...props }: MarkdownComponentProps<"li">) => (
- <li className="font-[350] mb-2 last:mb-0 tabular-nums [&>p:first-child]:inline [&>p:first-child]:m-0" {...props}>
+ <li
+ className="font-[inherit] mb-2 last:mb-0 tabular-nums [&>p:first-child]:inline [&>p:first-child]:m-0"
+ {...props}
+ >
{children}
</li>
),
blockquote: ({ children, ...props }: MarkdownComponentProps<"blockquote">) => (
- <blockquote className="border-l-[4px] border-button-border pl-2 text-xs font-[350] my-3" {...props}>
+ <blockquote className="border-l-[4px] border-button-border pl-2 font-[inherit] my-3" {...props}>
{children}
</blockquote>
),
@@ -265,12 +277,12 @@ const OneFontSizeComponents = {
</tr>
),
th: ({ children, ...props }: MarkdownComponentProps<"th">) => (
- <th className="px-2 py-2 first:pl-0 last:pr-0 text-left text-xs font-[350]" {...props}>
+ <th className="px-2 py-2 first:pl-0 last:pr-0 text-left font-[inherit]" {...props}>
{children}
</th>
),
td: ({ children, ...props }: MarkdownComponentProps<"td">) => (
- <td className="px-2 py-2 first:pl-0 last:pr-0 text-xs font-[350]" {...props}>
+ <td className="px-2 py-2 first:pl-0 last:pr-0 font-[inherit]" {...props}>
{children}
</td>
),
@@ -289,12 +301,12 @@ const OneFontSizeComponents = {
return <input type={type} {...props} />;
},
strong: ({ children, ...props }: MarkdownComponentProps<"strong">) => (
- <strong className="text-xs font-medium tracking-[0.2px]" {...props}>
+ <strong className="font-medium tracking-[0.2px]" {...props}>
{children}
</strong>
),
em: ({ children, ...props }: MarkdownComponentProps<"em">) => (
- <em className="text-xs italic font-normal" {...props}>
+ <em className="italic font-normal" {...props}>
{children}
</em>
),
@@ -327,6 +339,7 @@ export const MarkdownRenderer = React.memo(function MarkdownRenderer({
lineNumbers={false}
codeBlockMaxHeight="none"
linkSafety={LINK_SAFETY}
+ icons={CODE_BLOCK_ICONS}
remend={REMEND}
components={useOneFontSize ? OneFontSizeComponents : CustomComponents}
plugins={plugins}
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/message-list.tsx b/apps/mirai-gui/client/src/features/chat/components/message/message-list.tsx
index b28ad7c14..e0c924644 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/message-list.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/message-list.tsx
@@ -1,9 +1,11 @@
-import { Transition } from "@headlessui/react";
import { useParams } from "@tanstack/react-router";
-import React, { useEffect, useLayoutEffect, useRef } from "react";
+import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useChatStore } from "@/stores/use-chat-store";
-import { Loader, LoaderIcon } from "@/components/loader";
+import { Loader } from "@/components/loader";
+import { AssistantCat, PendingStatus } from "./assistant-cat";
import { Message } from "./message";
+import { NewChatCat } from "./new-chat-cat";
+import { UzuBirdHost } from "./uzu-bird";
type MessageListProps = {
isNew?: boolean;
@@ -17,7 +19,10 @@ type MessageListProps = {
loadingMessageId?: string | null;
canceledMessageId?: string | null;
isModelLoading?: boolean;
- hasResidentModel?: boolean;
+ /** The composer's text, which the empty chat's cat watches being typed. */
+ draft?: string;
+ /** When a send last failed for want of a model (the empty chat's cat reacts to it). */
+ missingModelAt?: number;
};
const MessageListComponent: React.FC<MessageListProps> = ({
@@ -32,7 +37,8 @@ const MessageListComponent: React.FC<MessageListProps> = ({
loadingMessageId,
canceledMessageId,
isModelLoading,
- hasResidentModel,
+ draft = "",
+ missingModelAt = 0,
}) => {
const messages = useChatStore((s) => s.messages);
const messagesEndRef = useRef<HTMLDivElement>(null);
@@ -160,16 +166,44 @@ const MessageListComponent: React.FC<MessageListProps> = ({
requestAnimationFrame(tryScroll);
}, [scrollToMessageId, onScrolled]);
+ // Messages already there when a chat opens are simply shown; ones that arrive while you watch
+ // come into focus. A new chat starts with nothing on record, so everything in it arrives.
+ const shownRef = useRef<{ chatId: string; ids: Set<string> | null }>({ chatId, ids: null });
+ if (shownRef.current.chatId !== chatId) shownRef.current = { chatId, ids: null };
+ if (!shownRef.current.ids && (isNew || messages.length > 0)) {
+ shownRef.current.ids = new Set(isNew ? [] : messages.map((m) => m.id));
+ }
+ const arrived = (id: string) => !shownRef.current.ids?.has(id);
+
+ // With room in the margin the cat hangs outside the column, so answers line up with the
+ // composer and your messages; on narrow windows it sits inline beside the answer.
+ const [catHangs, setCatHangs] = useState(false);
+ useEffect(() => {
+ const container = scrollContainerRef.current;
+ if (!container || typeof ResizeObserver === "undefined") return;
+ const measure = () => {
+ const column = parseFloat(getComputedStyle(container).getPropertyValue("--chat-width")) || Infinity;
+ setCatHangs((container.clientWidth - column) / 2 >= 48);
+ };
+ const observer = new ResizeObserver(measure);
+ observer.observe(container);
+ measure();
+ return () => observer.disconnect();
+ }, [chatId]);
+
const lastAssistantIndex = messages.at(-1)?.sender === "assistant" ? messages.length - 1 : -1;
const isBusy = Boolean(isModelLoading || isLoading);
- const loaderText = isModelLoading || !hasResidentModel ? "Loading model…" : "Prefilling…";
+ // "Loading the model" only when the engine says it is loading one; otherwise the prompt is being
+ // read. Guessing from what the interface last knew flashed "loading" on every first message.
+ const pendingPhase = isModelLoading ? "loadingModel" : "reading";
return (
<div className="relative flex flex-1 flex-col overflow-clip h-full">
<div
ref={scrollContainerRef}
- className="absolute inset-0 flex flex-col overflow-y-auto overscroll-y-contain scrollbar-hide"
+ data-cat-hang={catHangs || undefined}
+ className="absolute inset-0 flex flex-col overflow-y-auto overscroll-y-contain scrollbar-hide pt-[var(--chat-list-top,2rem)]"
style={{ paddingInline: "max(1.25rem, calc((100% - var(--chat-width)) / 2))" }}
>
{messages.length > 0 ? (
@@ -194,72 +228,67 @@ const MessageListComponent: React.FC<MessageListProps> = ({
const showInlineLoader = isLoadingThisMessage && !hasVisibleParsed;
- const showAssistantLoader = !loadingMessageId && isLastAssistant && isBusy;
+ // Only before the answer has anything to show. Once thinking or text has arrived the
+ // message tells its own state; on fast models the engine can still read as busy between
+ // thinking and the first words, which brought "Reading your message" back mid-answer.
+ const showAssistantLoader = !loadingMessageId && isLastAssistant && isBusy && !hasVisibleParsed;
return (
- <Transition
+ <div
key={message.id}
- appear
- show={true}
- enter="transition-opacity duration-200 ease-out"
- enterFrom="opacity-0"
- enterTo="opacity-100"
+ ref={(el) => {
+ itemRefs.current[message.id] = el;
+ }}
+ className={[
+ "shrink-0",
+ isLastAssistant ? "flex flex-col min-h-8" : "",
+ idx > 0 ? "mt-6" : "",
+ arrived(message.id) ? "animate-uzu-in" : "",
+ ].join(" ")}
>
- <div
- ref={(el) => {
- itemRefs.current[message.id] = el;
- }}
- className={["shrink-0", isLastAssistant ? "flex flex-col min-h-8" : "", idx > 0 ? "mt-6" : ""].join(
- " ",
- )}
- >
- {showAssistantLoader ? (
- <div className="flex items-center gap-2 text-left text-[15px] leading-[18px] text-label-muted">
- <Loader text={loaderText} />
- </div>
- ) : null}
- {showInlineLoader ? (
- <div className="flex items-center gap-2 text-left text-[15px] leading-[18px] text-label-muted">
- <Loader text={loaderText} />
- </div>
- ) : null}
- <Message
- key={`${message.id}_${message.currentVersionIndex ?? 0}_${message.versions?.length ?? 0}`}
- isLoading={isLoadingThisMessage}
- chatId={chatId}
- isLast={idx === lastAssistantIndex}
- isUiStreaming={Boolean(isUiStreaming && isLastAssistant)}
- isCanceled={canceledMessageId === message.id}
- onModelSelect={onMessageModelSelect}
- onEdit={onEditMessage}
- canEdit={canEditMessages}
- {...message}
- />
- </div>
- </Transition>
+ <Message
+ key={`${message.id}_${message.currentVersionIndex ?? 0}_${message.versions?.length ?? 0}`}
+ isLoading={isLoadingThisMessage}
+ chatId={chatId}
+ isLast={idx === lastAssistantIndex}
+ isUiStreaming={Boolean(isUiStreaming && isLastAssistant)}
+ isCanceled={canceledMessageId === message.id}
+ onModelSelect={onMessageModelSelect}
+ onEdit={onEditMessage}
+ canEdit={canEditMessages}
+ pendingPhase={showAssistantLoader || showInlineLoader ? pendingPhase : null}
+ {...message}
+ />
+ </div>
);
})
+ ) : isNew ? (
+ // A new chat sits in the middle of the page with the composer right under it.
+ <div className="flex flex-col items-center justify-end h-full relative pb-7">
+ {/* Keyed by chat, so each new chat gets its own greeting. */}
+ <NewChatCat key={chatId} draft={draft} missingModelAt={missingModelAt} />
+ </div>
) : (
<div className="flex gap-2 items-center justify-center h-full relative">
- {isNew ? (
- <>
- <span className="text-label-muted text-[13px] font-[350]">
- Start your new private and local conversation
- </span>
- <LoaderIcon />
- </>
- ) : (
- <Loader />
- )}
+ <Loader />
</div>
)}
{lastAssistantIndex === -1 && isBusy && !loadingMessageId && (
- <div className="mt-6 flex items-center gap-2 text-left text-[15px] leading-[18px] text-label-muted">
- <Loader text={loaderText} />
+ <div className="relative mt-6 flex gap-3 animate-uzu-in in-data-cat-hang:block">
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center in-data-cat-hang:absolute in-data-cat-hang:-left-10 in-data-cat-hang:top-0">
+ <AssistantCat phase={pendingPhase} live />
+ </div>
+ <PendingStatus phase={pendingPhase} />
</div>
)}
- <div ref={messagesEndRef} className="h-6 shrink-0" />
+ {/* Room for the composer and the gap under it, which the list runs behind, plus 24px above. */}
+ <div
+ ref={messagesEndRef}
+ className="shrink-0"
+ style={{ height: messages.length > 0 ? "calc(var(--composer-h, 0px) + 1.25rem + 1.5rem)" : "1.5rem" }}
+ />
</div>
+ <UzuBirdHost />
</div>
);
};
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/message-version-controls.tsx b/apps/mirai-gui/client/src/features/chat/components/message/message-version-controls.tsx
index 7e5259898..46804c13e 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/message-version-controls.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/message-version-controls.tsx
@@ -2,6 +2,10 @@ import React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { twMerge } from "tailwind-merge";
+// The same square as the Copy, Regenerate and speed buttons beside it: hover fills it, focus rings it.
+const ARROW_CLASSNAME =
+ "flex size-8 items-center justify-center rounded-lg text-label-muted transition-colors duration-150 ease-out enabled:hover:bg-bg-hover enabled:hover:text-label-title outline-hidden focus-visible:shadow-focus disabled:opacity-40 disabled:cursor-not-allowed";
+
type MessageVersionControlsProps = {
currentVersion: number;
totalVersions: number;
@@ -39,35 +43,32 @@ export const MessageVersionControls: React.FC<MessageVersionControlsProps> = ({
}
return (
- <div className={twMerge("flex items-center gap-1.5", className)}>
+ <div className={twMerge("flex items-center", className)}>
<button
+ type="button"
onClick={handlePrevious}
disabled={!canGoPrevious}
aria-label="Previous response"
- title="Previous response"
- className={twMerge(
- "p-1 rounded transition-colors",
- canGoPrevious ? "text-label-muted hover:text-label-title" : "text-label-muted/50 cursor-not-allowed",
- )}
+ className={ARROW_CLASSNAME}
>
- <ChevronLeft className="w-4 h-4" />
+ <ChevronLeft aria-hidden className="size-4" />
</button>
- <span className="text-sm text-label-muted" title={currentModelName || undefined}>
+ <span
+ className="min-w-7 text-center text-[13px] font-[450] leading-[1.3] text-label-muted tabular-nums"
+ title={currentModelName || undefined}
+ >
{currentVersion + 1}/{totalVersions}
</span>
<button
+ type="button"
onClick={handleNext}
disabled={!canGoNext}
aria-label="Next response"
- title="Next response"
- className={twMerge(
- "p-1 rounded transition-colors",
- canGoNext ? "text-label-muted hover:text-label-title" : "text-label-muted/50 cursor-not-allowed",
- )}
+ className={ARROW_CLASSNAME}
>
- <ChevronRight className="w-4 h-4" />
+ <ChevronRight aria-hidden className="size-4" />
</button>
</div>
);
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/message.test.tsx b/apps/mirai-gui/client/src/features/chat/components/message/message.test.tsx
index 00579df84..7602874d6 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/message.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/message.test.tsx
@@ -82,17 +82,17 @@ it("copies chart-only replies as readable data instead of an empty canvas", asyn
expect(await read("text/plain")).toContain("Category\tMonthly spending\nRent\t900\nFood\t350");
});
-it("changes Thinking... to Thinking when this response finishes", () => {
+it("changes Thinking… to Thought when this response finishes", () => {
useChatSessionStore.setState({
isGenerating: true,
activeGeneratingChatId: "chat",
activeAssistantMessageId: message.id,
});
render(<Message {...message} chatId="chat" isLast isUiStreaming />);
- expect(screen.getByText("Thinking...")).toBeTruthy();
+ expect(screen.getByText("Thinking…")).toBeTruthy();
act(() => useChatSessionStore.getState().setGenerating(false));
- expect(screen.getByText("Thinking")).toBeTruthy();
+ expect(screen.getByText(/^Thought/)).toBeTruthy();
});
it("tracks the actual message when regenerating an earlier response", () => {
@@ -109,7 +109,10 @@ it("tracks the actual message when regenerating an earlier response", () => {
<Message {...later} chatId="chat" isLast isUiStreaming />
</>,
);
- expect(screen.getAllByText(/^Thinking/).map((element) => element.textContent)).toEqual(["Thinking...", "Thinking"]);
+ expect(screen.getAllByText(/^Th(inking|ought)/).map((element) => element.textContent)).toEqual([
+ "Thinking…",
+ expect.stringMatching(/^Thought/),
+ ]);
});
it("keeps an older version and other chats marked finished", () => {
@@ -121,11 +124,11 @@ it("keeps an older version and other chats marked finished", () => {
activeAssistantMessageId: message.id,
});
const view = render(<Message {...message} chatId="chat" isLast isUiStreaming />);
- expect(screen.getByText("Thinking")).toBeTruthy();
+ expect(screen.getByText(/^Thought/)).toBeTruthy();
act(() => useChatStore.setState({ messages: [message] }));
view.rerender(<Message {...message} chatId="other-chat" isLast isUiStreaming />);
- expect(screen.getByText("Thinking")).toBeTruthy();
+ expect(screen.getByText(/^Thought/)).toBeTruthy();
});
const renderThinkingMessage = () => {
@@ -141,7 +144,7 @@ const renderThinkingMessage = () => {
activeAssistantMessageId: message.id,
});
const view = render(<Message {...thinkingMessage} chatId="chat" isLast isUiStreaming />);
- return { view, thinkingMessage, toggle: screen.getByRole("button", { name: /^Thinking/ }) };
+ return { view, thinkingMessage, toggle: screen.getByRole("button", { name: /^(Thinking|Thought)/ }) };
};
it("opens during reasoning, collapses when the answer starts, and allows reopening", () => {
@@ -212,7 +215,7 @@ it("renders each reasoning, text and tool turn in order and collapses reasoning
activeAssistantMessageId: message.id,
});
const view = render(<Message {...message} chatId="chat" isLast isUiStreaming />);
- const firstToggle = screen.getByRole("button", { name: /^Thinking/ });
+ const firstToggle = screen.getByRole("button", { name: /^(Thinking|Thought)/ });
expect(firstToggle.getAttribute("aria-expanded")).toBe("true");
const firstTurn: TranscriptItem[] = [
@@ -222,7 +225,7 @@ it("renders each reasoning, text and tool turn in order and collapses reasoning
];
update(firstTurn);
expect(firstToggle.getAttribute("aria-expanded")).toBe("false");
- expect(view.container.textContent).toContain("Checking the date and time...");
+ expect(view.container.textContent).toContain("Checking the date and time…");
expect(view.container.textContent).not.toContain("Renaming the chat");
expect(view.container.textContent).not.toContain("Response");
const answerNode = screen.getByText("Checking the time.");
@@ -234,8 +237,8 @@ it("renders each reasoning, text and tool turn in order and collapses reasoning
];
update(nextTurn);
expect(screen.getByText("Checking the time.")).toBe(answerNode);
- expect(view.container.textContent).toMatch(/Checking the time\..*Checked the date and time.*Thinking\.\.\./s);
- const secondToggle = screen.getAllByRole("button", { name: /^Thinking/ })[1]!;
+ expect(view.container.textContent).toMatch(/Checking the time\..*Checked the date and time.*Thinking…/s);
+ const secondToggle = screen.getAllByRole("button", { name: /^(Thinking|Thought)/ })[1]!;
expect(secondToggle.getAttribute("aria-expanded")).toBe("true");
fireEvent.click(firstToggle);
expect(firstToggle.getAttribute("aria-expanded")).toBe("true");
@@ -253,6 +256,26 @@ it("renders each reasoning, text and tool turn in order and collapses reasoning
expect(secondToggle.getAttribute("aria-expanded")).toBe("true");
});
+it("folds a run of reasoning and tool calls into one step", () => {
+ useChatStore.getState().updateMessage(message.id, {
+ output: {
+ transcript: [
+ { type: "thinking", text: "Try a chart", completed: true },
+ { type: "toolCall", name: "show_chart", called: false, failed: true },
+ { type: "thinking", text: "Try again", completed: true },
+ { type: "toolCall", name: "show_chart", called: false, failed: true },
+ { type: "thinking", text: "Answer in text", completed: true },
+ { type: "text", text: "Here it is." },
+ ],
+ },
+ });
+ render(<Message {...message} chatId="chat" isLast />);
+ const toggles = screen.getAllByRole("button", { name: /^(Thinking|Thought)/ });
+ expect(toggles).toHaveLength(1);
+ expect(toggles[0]!.textContent).toContain("2 tool calls");
+ expect(screen.getByText("Here it is.")).toBeTruthy();
+});
+
it("keeps one reasoning block across hidden housekeeping and preserves manual toggles", () => {
useChatStore.getState().updateMessage(message.id, {
output: { transcript: [{ type: "thinking", text: "Choose a title", completed: false }] },
@@ -263,7 +286,7 @@ it("keeps one reasoning block across hidden housekeeping and preserves manual to
activeAssistantMessageId: message.id,
});
render(<Message {...message} chatId="chat" isLast isUiStreaming />);
- const toggle = screen.getByRole("button", { name: /^Thinking/ });
+ const toggle = screen.getByRole("button", { name: /^(Thinking|Thought)/ });
expect(toggle.getAttribute("aria-expanded")).toBe("true");
fireEvent.click(toggle);
expect(toggle.getAttribute("aria-expanded")).toBe("false");
@@ -274,7 +297,7 @@ it("keeps one reasoning block across hidden housekeeping and preserves manual to
},
}),
);
- expect(screen.getAllByRole("button", { name: /^Thinking/ })).toEqual([toggle]);
+ expect(screen.getAllByRole("button", { name: /^(Thinking|Thought)/ })).toEqual([toggle]);
expect(toggle.getAttribute("aria-expanded")).toBe("false");
fireEvent.click(toggle);
expect(toggle.getAttribute("aria-expanded")).toBe("true");
@@ -289,7 +312,7 @@ it("keeps one reasoning block across hidden housekeeping and preserves manual to
}),
);
expect(toggle.getAttribute("aria-expanded")).toBe("false");
- expect(screen.getByText("Thinking")).toBeTruthy();
+ expect(screen.getByText(/^Thought/)).toBeTruthy();
});
it("shows a chat naming tool requested explicitly by the user", () => {
@@ -307,7 +330,7 @@ it("keeps interrupted tool calls visible without claiming they are still running
});
const view = render(<Message {...message} chatId="chat" isCanceled />);
expect(view.container.textContent).toContain("Stopped checking the date and time");
- expect(view.container.textContent).not.toContain("Checking the date and time...");
+ expect(view.container.textContent).not.toContain("Checking the date and time…");
});
it("does not claim a failed tool call succeeded", () => {
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/message.tsx b/apps/mirai-gui/client/src/features/chat/components/message/message.tsx
index 92fec6bd2..6b56a5fc9 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/message.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/message.tsx
@@ -1,7 +1,6 @@
import { useChatSessionStore } from "@/stores/use-chat-session-store";
import { isOtherChatGenerating } from "@/features/runtime/runtime-busy";
import { writeItemsWithFocus } from "@/utils/clipboard";
-import { WrenchIcon } from "lucide-react";
import React, { lazy, Suspense, useRef } from "react";
import type { MessageVersion } from "@/types/message";
import type { TranscriptItem } from "@/types/llm-stream";
@@ -13,6 +12,9 @@ import { MessageVersionControls } from "./message-version-controls";
import { ModelSelector } from "./model-selector";
import { PerformanceDropdown } from "./performance-dropdown";
import { UserMessage, type UserMessageProps } from "./user-message";
+import { TextShimmer } from "@/components/ui/text-shimmer";
+import { AssistantCat, PendingStatus, type AssistantPhase } from "./assistant-cat";
+import { UzuBirdAnswerSync, useUzuBirdTaps } from "./uzu-bird";
const ChartMessage = lazy(() => import("./chart-message"));
@@ -20,7 +22,7 @@ const toolLabels = new Map([
[
"show_chart",
{
- running: "Drawing a chart...",
+ running: "Drawing a chart…",
done: "Drew a chart",
failed: "Couldn't draw the chart",
stopped: "Stopped drawing the chart",
@@ -29,7 +31,7 @@ const toolLabels = new Map([
[
"get_current_date_time",
{
- running: "Checking the date and time...",
+ running: "Checking the date and time…",
done: "Checked the date and time",
failed: "Couldn't check the date and time",
stopped: "Stopped checking the date and time",
@@ -38,7 +40,7 @@ const toolLabels = new Map([
[
"set_chat_name",
{
- running: "Renaming the chat...",
+ running: "Renaming the chat…",
done: "Renamed the chat",
failed: "Couldn't rename the chat",
stopped: "Stopped renaming the chat",
@@ -57,13 +59,35 @@ function toolCallLabel(tool: Extract<TranscriptItem, { type: "toolCall" }>, isRu
.replace(/[_-]+/g, " ")
.trim() || "tool";
return {
- running: `Using ${name}...`,
+ running: `Using ${name}…`,
done: `Used ${name}`,
failed: `Couldn't use ${name}`,
stopped: `Stopped using ${name}`,
}[state];
}
+type TranscriptSegment = { kind: "item"; index: number } | { kind: "steps"; start: number; end: number };
+
+/** Groups the transcript for display: each thinking item starts a "steps" segment that takes in
+ * the tool calls and further thinking after it, up to the next text or chart. Tool calls before
+ * any thinking stay on their own. */
+function segmentTranscript(items: TranscriptItem[]): TranscriptSegment[] {
+ const segments: TranscriptSegment[] = [];
+ for (let i = 0; i < items.length; i += 1) {
+ if (items[i]!.type !== "thinking") {
+ segments.push({ kind: "item", index: i });
+ continue;
+ }
+ let end = i;
+ while (end + 1 < items.length && (items[end + 1]!.type === "thinking" || items[end + 1]!.type === "toolCall")) {
+ end += 1;
+ }
+ segments.push({ kind: "steps", start: i, end });
+ i = end;
+ }
+ return segments;
+}
+
export type MessageType = {
text: string;
id: string;
@@ -85,6 +109,8 @@ type MessageProps = MessageType & {
onModelSelect?: (messageId: string, modelId: string, modelName: string) => void;
canEdit?: boolean;
onEdit?: UserMessageProps["onEdit"];
+ /** Set while the answer has no content yet: the model is loading or the prompt is being read. */
+ pendingPhase?: Extract<AssistantPhase, "loadingModel" | "reading"> | null;
};
const AssistantMessage: React.FC<MessageProps> = ({
@@ -98,6 +124,7 @@ const AssistantMessage: React.FC<MessageProps> = ({
isLast,
isUiStreaming,
isCanceled = false,
+ pendingPhase = null,
}) => {
const getEffectiveModelForMessage = useChatStore((s) => s.getEffectiveModelForMessage);
const switchMessageVersion = useChatStore((s) => s.switchMessageVersion);
@@ -186,97 +213,170 @@ const AssistantMessage: React.FC<MessageProps> = ({
const isEjecting = useChatSessionStore((s) => s.isEjecting);
const blockedByOtherChat = useChatSessionStore((s) => isOtherChatGenerating(s, chatId));
+ const lastItem = transcript?.at(-1);
+ const phase: AssistantPhase = pendingPhase
+ ? pendingPhase
+ : hasError
+ ? /memory/i.test(errorText ?? "")
+ ? "outOfMemory"
+ : "error"
+ : isCanceled
+ ? "stopped"
+ : !isThinking
+ ? "done"
+ : transcript !== undefined
+ ? lastItem?.type === "thinking" && !lastItem.completed
+ ? "thinking"
+ : lastItem?.type === "toolCall" && !lastItem.called
+ ? "tool"
+ : lastItem?.type === "text"
+ ? "writing"
+ : "reading"
+ : reasoningInProgress
+ ? "thinking"
+ : visibleResponseText
+ ? "writing"
+ : "reading";
+
+ const birdTaps = useUzuBirdTaps();
+
const currentVersionModelName = hasVersions
? versions?.[currentVersionIndex || 0]?.modelName
: messageFromStore?.modelName;
return (
- <div className="text-label-title relative w-full rounded-[5px] text-[15px] leading-[140%]">
+ <div className="relative flex gap-3 in-data-cat-hang:block">
<div
- ref={messageRef}
- className="[&>:last-child]:mb-0 [&>.markdown-body:last-child>div>:last-child]:mb-0 [&>[data-message-reasoning]:has(+.markdown-body>div>*)]:mb-[7px]"
+ {...birdTaps}
+ className="flex h-7 w-7 shrink-0 select-none items-center justify-center in-data-cat-hang:absolute in-data-cat-hang:-left-10 in-data-cat-hang:top-0"
>
- {transcript !== undefined ? (
- transcript.map((item, index) => {
- const key = `${currentMsgVersion?.id ?? id}:${index}`;
- switch (item.type) {
- case "thinking":
+ <AssistantCat phase={phase} live={!!isLast} />
+ </div>
+ <div className="text-label-title relative min-w-0 flex-1 rounded-[5px] text-[15px] leading-[1.6]">
+ {pendingPhase ? <PendingStatus phase={pendingPhase} /> : null}
+ {isLast ? <UzuBirdAnswerSync answerReady={phase === "done"} /> : null}
+ <div
+ ref={messageRef}
+ className="[&>:last-child]:mb-0 [&>.markdown-body:last-child>div>:last-child]:mb-0 [&>[data-message-reasoning]:has(+.markdown-body>div>*)]:mb-[7px] [&>.markdown-body:first-child]:pt-[3.5px]"
+ >
+ {transcript !== undefined ? (
+ segmentTranscript(transcript).map((segment) => {
+ if (segment.kind === "steps") {
+ // A run of thinking and tool calls reads as one step of work: one row, with each
+ // tool call in place inside the reasoning.
+ const steps = transcript.slice(segment.start, segment.end + 1);
+ const last = steps[steps.length - 1]!;
+ const stillWorking =
+ last.type === "thinking" ? !last.completed : last.type === "toolCall" && !last.called && !last.failed;
return (
<ThinkingBlock
- key={key}
- text={item.text}
- reasoningInProgress={isThinking && !item.completed && index === transcript.length - 1}
- />
- );
- case "text":
- return (
- <MarkdownRenderer
- key={key}
- content={item.text}
- streaming={isThinking && index === transcript.length - 1}
+ key={`${currentMsgVersion?.id ?? id}:${segment.start}`}
+ text={steps
+ .map((step) =>
+ step.type === "toolCall"
+ ? `_${toolCallLabel(step, isThinking)}_`
+ : step.type === "thinking"
+ ? step.text
+ : "",
+ )
+ .filter(Boolean)
+ .join("\n\n")}
+ toolCalls={steps.filter((step) => step.type === "toolCall").length}
+ reasoningInProgress={isThinking && stillWorking && segment.end === transcript.length - 1}
/>
);
- case "toolCall":
- return (
- <div
- key={key}
- data-tool-call
- className="mt-1 mb-2 flex items-center gap-2 pl-1 text-[13px] text-label-muted"
- >
- <WrenchIcon className="size-3.5 shrink-0" />
- <span>{toolCallLabel(item, isThinking)}</span>
- </div>
- );
- case "chart":
- return (
- <Suspense key={key} fallback={<div className="my-3 h-96 text-label-muted">Loading chart...</div>}>
- <ChartMessage chart={item.chart} />
- </Suspense>
- );
- }
- })
- ) : (
- <>
- {visibleChainOfThought && (
- <ThinkingBlock
- key={currentMsgVersion?.id ?? id}
- text={visibleChainOfThought}
- reasoningInProgress={reasoningInProgress}
- isThinking={isThinking}
+ }
+ const index = segment.index;
+ const item = transcript[index]!;
+ const key = `${currentMsgVersion?.id ?? id}:${index}`;
+ switch (item.type) {
+ case "thinking":
+ return (
+ <ThinkingBlock
+ key={key}
+ text={item.text}
+ reasoningInProgress={isThinking && !item.completed && index === transcript.length - 1}
+ />
+ );
+ case "text":
+ return (
+ <MarkdownRenderer
+ key={key}
+ content={item.text}
+ streaming={isThinking && index === transcript.length - 1}
+ />
+ );
+ case "toolCall":
+ return (
+ <div
+ key={key}
+ data-tool-call
+ className="mt-1 mb-2 flex h-6 items-center text-[13px] text-label-muted animate-uzu-in"
+ >
+ {!item.called && !item.failed && isThinking ? (
+ <TextShimmer duration={1.6} className="[--base-color:var(--color-label-muted)]">
+ {toolCallLabel(item, isThinking)}
+ </TextShimmer>
+ ) : (
+ <span key="settled" className="animate-uzu-swap">
+ {toolCallLabel(item, isThinking)}
+ </span>
+ )}
+ </div>
+ );
+ case "chart":
+ return (
+ <Suspense key={key} fallback={<div className="my-3 h-96 text-label-muted">Loading chart...</div>}>
+ <ChartMessage chart={item.chart} />
+ </Suspense>
+ );
+ }
+ })
+ ) : (
+ <>
+ {visibleChainOfThought && (
+ <ThinkingBlock
+ key={currentMsgVersion?.id ?? id}
+ text={visibleChainOfThought}
+ reasoningInProgress={reasoningInProgress}
+ isThinking={isThinking}
+ />
+ )}
+ <MarkdownRenderer content={visibleResponseText} streaming={streamInProgress} />
+ </>
+ )}
+ {hasError && (
+ <div role="alert" className="mt-4 p-3 rounded-md border border-error/30 bg-error/10">
+ <span className="text-[13px] leading-[150%] text-error">{errorText}</span>
+ </div>
+ )}
+ </div>
+ {(hasVersions ||
+ (!streamInProgress && (isStreamFinished || isCanceled || text.length === 0 || !!visibleChainOfThought))) && (
+ <div className="flex flex-wrap items-center gap-1 mt-2">
+ {(visibleResponseText.length !== 0 || hasError || transcript?.some((item) => item.type === "chart")) && (
+ <CopyButton className="[&_svg]:size-4" onCopy={handleMessageCopy} />
+ )}
+ <ModelSelector
+ selectedModel={effectiveModelId || ""}
+ onModelSelect={handleModelSelect}
+ disabled={(anyStreamInProgress && hasVersions) || isEjecting || blockedByOtherChat}
+ />
+ {shouldShowPerf && (
+ <PerformanceDropdown perf={effectivePerf} disabled={anyStreamInProgress && hasVersions} />
+ )}
+ {hasVersions && (
+ <MessageVersionControls
+ currentVersion={currentVersionIndex}
+ totalVersions={totalVersions}
+ onVersionChange={handleVersionChange}
+ disabledPrevious={anyStreamInProgress}
+ currentModelName={currentVersionModelName || effectiveModelName || ""}
/>
)}
- <MarkdownRenderer content={visibleResponseText} streaming={streamInProgress} />
- </>
- )}
- {hasError && (
- <div role="alert" className="mt-4 p-3 rounded-md border border-error/30 bg-error/10">
- <span className="text-[13px] leading-[150%] text-error">{errorText}</span>
</div>
)}
</div>
- {(hasVersions ||
- (!streamInProgress && (isStreamFinished || isCanceled || text.length === 0 || !!visibleChainOfThought))) && (
- <div className="flex flex-wrap items-center gap-1 mt-2">
- {(visibleResponseText.length !== 0 || hasError || transcript?.some((item) => item.type === "chart")) && (
- <CopyButton className="[&_svg]:size-4" onCopy={handleMessageCopy} />
- )}
- <ModelSelector
- selectedModel={effectiveModelId || ""}
- onModelSelect={handleModelSelect}
- disabled={(anyStreamInProgress && hasVersions) || isEjecting || blockedByOtherChat}
- />
- {shouldShowPerf && <PerformanceDropdown perf={effectivePerf} disabled={anyStreamInProgress && hasVersions} />}
- {hasVersions && (
- <MessageVersionControls
- currentVersion={currentVersionIndex}
- totalVersions={totalVersions}
- onVersionChange={handleVersionChange}
- disabledPrevious={anyStreamInProgress}
- currentModelName={currentVersionModelName || effectiveModelName || ""}
- />
- )}
- </div>
- )}
</div>
);
};
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/model-selector.tsx b/apps/mirai-gui/client/src/features/chat/components/message/model-selector.tsx
index 061699580..aa5563071 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/model-selector.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/model-selector.tsx
@@ -1,11 +1,16 @@
-import { Listbox, ListboxButton, ListboxOption, ListboxOptions, Transition } from "@headlessui/react";
-import { ChevronRight, RefreshCw } from "lucide-react";
+import { Check, ChevronRight } from "lucide-react";
+import { RotateCwIcon } from "@/components/icons/app-icons";
import { useNavigate } from "@tanstack/react-router";
import React from "react";
+import { HoverPopover } from "@/components/ui/popover/hover-popover";
+import type { PopoverItem } from "@/components/ui/popover/shared/types";
import { twMerge } from "tailwind-merge";
+import { ModelName } from "@/components/model-name";
import { useModelsStore } from "@/stores/use-models-store";
import { modelDownloadPhases } from "@/types/model-manager";
-import { ModelVendorIcon } from "@/components/model-vendor-icon";
+
+const ACTION_CLASSNAME =
+ "flex size-8 items-center justify-center rounded-lg text-label-muted transition-colors duration-150 ease-out enabled:hover:bg-bg-hover enabled:hover:text-label-title outline-hidden focus-visible:shadow-focus disabled:opacity-60 disabled:cursor-not-allowed";
type ModelSelectorProps = {
selectedModel?: string;
@@ -33,73 +38,72 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({ selectedModel, onM
navigate({ to: "/local-models" });
};
- return (
- <div className="w-fit">
- <Listbox value={selectedModel || ""} onChange={handleModelSelect} disabled={disabled}>
- <div>
- <ListboxButton
- aria-label="Regenerate with model"
- title="Regenerate with model"
- className="flex size-8 items-center justify-center rounded-md text-label-muted transition-colors enabled:hover:bg-bg-hover enabled:hover:text-label-title focus:outline-hidden data-[focus]:shadow-focus disabled:opacity-60 disabled:cursor-not-allowed"
- >
- <RefreshCw className="size-4" aria-hidden="true" />
- </ListboxButton>
-
- <Transition
- enter="transition duration-100 ease-out"
- enterFrom="transform scale-95 opacity-0"
- enterTo="transform scale-100 opacity-100"
- leave="transition duration-75 ease-out"
- leaveFrom="transform scale-100 opacity-100"
- leaveTo="transform scale-95 opacity-0"
- >
- <ListboxOptions
- anchor="bottom start"
- className="overscroll-y-contain thin-scrollbar [--anchor-gap:8px] [--anchor-max-height:360px] bg-bg-modal border border-cell-border rounded-[6px] z-50 pointer-events-auto focus:outline-hidden focus:ring-0"
- >
- <div className="p-[6px] flex flex-col gap-2">
- {loadingModels ? (
- <div className="px-[14px] py-2 leading-[130%] text-sm text-label-muted">Loading models...</div>
- ) : installedModelsList.length > 0 ? (
- installedModelsList.map((model) => {
- const isSelected = model.repoId === selectedModel;
- return (
- <ListboxOption
- key={model.repoId}
- value={model.repoId}
- className={twMerge(
- "w-full flex items-center gap-2 px-[14px] py-2 rounded-md text-left transition-colors cursor-pointer hover:bg-bg-hover focus:outline-hidden focus:ring-0",
- isSelected ? "bg-bg-sub" : "",
- )}
- >
- <ModelVendorIcon vendor={model.vendor} />
- <span className="text-sm leading-[130%] text-label-title flex items-center gap-2">
- {model.name}
- </span>
- <span className="text-label-muted text-[10px]">Local</span>
- </ListboxOption>
- );
- })
- ) : (
- <div className="px-[14px] py-2 leading-[130%] text-sm text-label-muted">No models available</div>
+ // Opens on hover, like a tooltip, with the models to regenerate with: names only, three at a time
+ // with the rest scrolling, and "Download models" fixed under them. Above the button: the answer's
+ // actions sit near the composer and the window's bottom, where a long list would run off. Keyboard: Enter or ↓ opens
+ // it, Esc closes it (handled by HoverPopover).
+ const items: PopoverItem[] = loadingModels
+ ? [{ id: "loading", label: "Loading models…", disabled: true }]
+ : installedModelsList.length > 0
+ ? installedModelsList.map((model) => ({
+ id: model.repoId,
+ label: (
+ <span className="flex min-w-0 flex-1 items-center gap-2.5">
+ <ModelName name={model.name} className="flex-1 text-[13px] font-[450] leading-[1.3] text-label-title" />
+ <Check
+ aria-hidden
+ className={twMerge(
+ "size-4 shrink-0 text-label-title",
+ model.repoId === selectedModel ? "opacity-100" : "opacity-0",
)}
- </div>
+ />
+ </span>
+ ),
+ onClick: () => handleModelSelect(model.repoId),
+ }))
+ : [{ id: "none", label: "No models available", disabled: true }];
+ const footerItems: PopoverItem[] = [
+ {
+ id: "more",
+ label: (
+ <span className="flex flex-1 items-center justify-between gap-2.5 text-[13px] font-[450] leading-[1.3] text-label-title">
+ Download models
+ <ChevronRight className="size-4 text-label-muted" aria-hidden />
+ </span>
+ ),
+ onClick: handleMoreModelsClick,
+ },
+ ];
- <div className="h-[1px] bg-cell-border" />
+ // Clicking Regenerate itself reruns the answer with the model that has the check (the one that
+ // wrote it); the menu that opens on hover picks a different one.
+ const handleRegenerateClick = () => {
+ const current = installedModelsList.find((model) => model.repoId === selectedModel);
+ if (current) onModelSelect?.(current.repoId, current.name);
+ };
+
+ const button = (
+ <button
+ type="button"
+ aria-label="Regenerate"
+ disabled={disabled}
+ onClick={handleRegenerateClick}
+ className={ACTION_CLASSNAME}
+ >
+ <RotateCwIcon size={16} aria-hidden />
+ </button>
+ );
- <div className="p-[10px]">
- <button
- onClick={handleMoreModelsClick}
- className="w-full flex items-center justify-between px-[14px] py-2 rounded-md hover:bg-bg-hover transition-colors text-label-title focus:outline-hidden focus:ring-0"
- >
- <span className="text-sm text-label-title">More models</span>
- <ChevronRight className="h-4 w-4 text-label-muted" />
- </button>
- </div>
- </ListboxOptions>
- </Transition>
- </div>
- </Listbox>
- </div>
+ return disabled ? (
+ button
+ ) : (
+ <HoverPopover
+ trigger={button}
+ items={items}
+ footerItems={footerItems}
+ maxVisibleItems={3}
+ side="top"
+ align="start"
+ />
);
};
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/new-chat-cat.tsx b/apps/mirai-gui/client/src/features/chat/components/message/new-chat-cat.tsx
new file mode 100644
index 000000000..091ec97de
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/new-chat-cat.tsx
@@ -0,0 +1,112 @@
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { UzuCat } from "@/components/uzu-cat";
+import { chooseGreeting, rememberGreeting } from "./new-chat-greeting";
+
+const COMPOSER_SELECTOR = "textarea[data-composer-input]";
+
+/** Where the caret of a textarea is on screen, measured with an invisible copy of its text. */
+function caretPoint(textarea: HTMLTextAreaElement): { x: number; y: number } {
+ const style = window.getComputedStyle(textarea);
+ const mirror = document.createElement("div");
+ for (const prop of [
+ "boxSizing",
+ "width",
+ "paddingTop",
+ "paddingRight",
+ "paddingBottom",
+ "paddingLeft",
+ "borderTopWidth",
+ "borderRightWidth",
+ "borderBottomWidth",
+ "borderLeftWidth",
+ "fontFamily",
+ "fontSize",
+ "fontWeight",
+ "fontVariationSettings",
+ "lineHeight",
+ "letterSpacing",
+ "wordSpacing",
+ "tabSize",
+ ] as const) {
+ mirror.style[prop] = style[prop];
+ }
+ Object.assign(mirror.style, {
+ position: "fixed",
+ top: "0",
+ left: "-9999px",
+ visibility: "hidden",
+ whiteSpace: "pre-wrap",
+ overflowWrap: "break-word",
+ });
+ mirror.textContent = textarea.value.slice(0, textarea.selectionEnd ?? textarea.value.length);
+ const marker = document.createElement("span");
+ marker.textContent = "​";
+ mirror.appendChild(marker);
+ document.body.appendChild(mirror);
+ const box = textarea.getBoundingClientRect();
+ const x = box.left + marker.offsetLeft - textarea.scrollLeft;
+ const y = box.top + marker.offsetTop - textarea.scrollTop + marker.offsetHeight / 2;
+ mirror.remove();
+ return { x, y };
+}
+
+/** Where to look, -1..1 each way, from the cat toward a target on screen. Scaled so something a few
+ * hundred pixels away already reads as "over there". */
+function gazeToward(target: DOMRect, face: DOMRect): { x: number; y: number } {
+ const clamp = (v: number) => Math.max(-1, Math.min(1, v));
+ return {
+ x: clamp((target.left + target.width / 2 - (face.left + face.width / 2)) / 320),
+ y: clamp((target.top + target.height / 2 - (face.top + face.height / 2)) / 160),
+ };
+}
+
+/**
+ * The empty state of a new chat: the cat says something (see new-chat-greeting), waits for you
+ * glancing at the box, and while you type it watches the caret move along the line.
+ */
+export function NewChatCat({ draft, missingModelAt = 0 }: { draft: string; missingModelAt?: number }) {
+ const catRef = useRef<HTMLSpanElement>(null);
+ // What uzu says this time: chosen once when the page opens, so it doesn't change while you type.
+ const [choice] = useState(() => chooseGreeting());
+ useEffect(() => rememberGreeting(choice), [choice]);
+ const [lookAt, setLookAt] = useState<{ x: number; y: number } | null>(null);
+
+ // Asked with no model chosen: not pleased for a couple of seconds, glaring at the picker.
+ const [grumpy, setGrumpy] = useState(false);
+ const [glareAt, setGlareAt] = useState<{ x: number; y: number } | null>(null);
+ useEffect(() => {
+ if (!missingModelAt) return;
+ const picker = document.querySelector("[data-model-picker]");
+ const cat = catRef.current;
+ if (picker && cat) setGlareAt(gazeToward(picker.getBoundingClientRect(), cat.getBoundingClientRect()));
+ setGrumpy(true);
+ const timer = setTimeout(() => setGrumpy(false), 2200);
+ return () => clearTimeout(timer);
+ }, [missingModelAt]);
+
+ useLayoutEffect(() => {
+ const textarea = document.querySelector<HTMLTextAreaElement>(COMPOSER_SELECTOR);
+ const cat = catRef.current;
+ if (!draft || !textarea || !cat) return;
+ const caret = caretPoint(textarea);
+ setLookAt(gazeToward(new DOMRect(caret.x, caret.y, 0, 0), cat.getBoundingClientRect()));
+ }, [draft]);
+
+ return (
+ <div className="flex flex-col items-center animate-uzu-in">
+ <span ref={catRef} className="mb-1 flex text-text-primary">
+ <UzuCat
+ state={grumpy ? "grumpy" : draft ? "watch" : "ready"}
+ lookAt={grumpy ? glareAt : lookAt}
+ anchorRef={catRef}
+ size={112}
+ label={grumpy ? "uzu, waiting for a model" : draft ? "uzu, watching you type" : "uzu, ready"}
+ />
+ </span>
+ <div className="flex flex-col gap-1 text-center">
+ <h2 className="text-[15px] font-[500] leading-[1.35] text-label-title text-balance">{choice.greeting.title}</h2>
+ <p className="text-[13px] leading-[1.45] text-label-muted text-pretty">{choice.greeting.subtitle}</p>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/new-chat-greeting.test.ts b/apps/mirai-gui/client/src/features/chat/components/message/new-chat-greeting.test.ts
new file mode 100644
index 000000000..f45ed0c26
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/new-chat-greeting.test.ts
@@ -0,0 +1,22 @@
+import { afterEach, expect, it } from "vitest";
+import { chooseGreeting, FIRST_GREETING, GREETINGS, rememberGreeting } from "./new-chat-greeting";
+
+afterEach(() => localStorage.clear());
+
+it("introduces itself the first time, and keeps doing so until a greeting has been shown", () => {
+ expect(chooseGreeting().greeting).toEqual(FIRST_GREETING);
+ expect(chooseGreeting().greeting).toEqual(FIRST_GREETING);
+});
+
+it("says something else once the introduction has been shown", () => {
+ rememberGreeting(chooseGreeting());
+ const next = chooseGreeting(() => 0);
+ expect(next.index).toBe(0);
+ expect(next.greeting).toEqual(GREETINGS[0]);
+});
+
+it("never repeats the line it said last", () => {
+ rememberGreeting(chooseGreeting());
+ rememberGreeting(chooseGreeting(() => 0));
+ expect(chooseGreeting(() => 0).index).toBe(1);
+});
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/new-chat-greeting.ts b/apps/mirai-gui/client/src/features/chat/components/message/new-chat-greeting.ts
new file mode 100644
index 000000000..c69020d2f
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/new-chat-greeting.ts
@@ -0,0 +1,57 @@
+/*
+ * What uzu says above an empty new chat. The first new chat ever gets the plain introduction; after
+ * that it's a different line each time, never the same one twice in a row, the way a friend doesn't
+ * say hello the same way every time. Lines stay short, in uzu's voice, and promise nothing beyond
+ * what the introduction does: the chat stays on this device.
+ */
+
+export type Greeting = { title: string; subtitle: string };
+
+export const FIRST_GREETING: Greeting = { title: "Start a private chat", subtitle: "It stays fully on your device" };
+
+export const GREETINGS: readonly Greeting[] = [
+ { title: "What's on your mind?", subtitle: "I'm all ears, and they stay right here" },
+ { title: "Purr-fectly private", subtitle: "Everything we say stays on this device" },
+ { title: "Back for more?", subtitle: "I kept your spot warm" },
+ { title: "Ready when you are", subtitle: "Just you, me, and your device" },
+ { title: "I was napping", subtitle: "But I'm up now. What's new?" },
+ { title: "Ask me anything", subtitle: "I'll think it over right here" },
+ { title: "Let's figure it out", subtitle: "Two heads, one device" },
+ { title: "Psst, it's just us", subtitle: "No cloud listening in" },
+ { title: "Fresh page, fresh paws", subtitle: "Where should we start?" },
+ { title: "Curious about something?", subtitle: "So am I. Let's look into it" },
+ { title: "Tell me everything", subtitle: "It won't leave this device" },
+ { title: "Let's think it through", subtitle: "Slowly, privately, together" },
+];
+
+const SEEN_KEY = "mirai.greeting-seen";
+const LAST_KEY = "mirai.greeting-last";
+
+/** -1 is the first-time introduction; otherwise an index into GREETINGS. */
+export type GreetingChoice = { index: number; greeting: Greeting };
+
+/**
+ * Chooses without writing anything, so it can run during render (and twice, under React's strict
+ * mode) without spending the first-time introduction. `rememberGreeting` records what was shown.
+ */
+export function chooseGreeting(random: () => number = Math.random): GreetingChoice {
+ try {
+ if (localStorage.getItem(SEEN_KEY) !== "1") return { index: -1, greeting: FIRST_GREETING };
+ const last = Number(localStorage.getItem(LAST_KEY) ?? -1);
+ let index = Math.floor(random() * GREETINGS.length);
+ if (index === last) index = (index + 1) % GREETINGS.length;
+ return { index, greeting: GREETINGS[index] ?? FIRST_GREETING };
+ } catch {
+ // Storage unavailable: the introduction is always a fine thing to say.
+ return { index: -1, greeting: FIRST_GREETING };
+ }
+}
+
+export function rememberGreeting(choice: GreetingChoice): void {
+ try {
+ localStorage.setItem(SEEN_KEY, "1");
+ if (choice.index >= 0) localStorage.setItem(LAST_KEY, String(choice.index));
+ } catch {
+ // Nothing to keep; the next new chat simply chooses again.
+ }
+}
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/performance-dropdown.tsx b/apps/mirai-gui/client/src/features/chat/components/message/performance-dropdown.tsx
index 869aa2502..0d723e709 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/performance-dropdown.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/performance-dropdown.tsx
@@ -1,5 +1,6 @@
-import { Popover, PopoverButton, PopoverPanel, Transition } from "@headlessui/react";
-import { Activity } from "lucide-react";
+import { ZapIcon } from "@/components/icons/app-icons";
+import { Fragment } from "react";
+import { Tooltip } from "@/components/ui/tooltip";
import type { PerfStats } from "@/types/message";
type PerformanceDropdownProps = {
@@ -8,57 +9,67 @@ type PerformanceDropdownProps = {
};
const formatSeconds = (seconds?: number): string =>
- typeof seconds === "number" && Number.isFinite(seconds) ? `${seconds.toFixed(3)}s` : "—";
+ typeof seconds === "number" && Number.isFinite(seconds) ? `${seconds.toFixed(3)} s` : "—";
const formatTps = (tps?: number): string =>
- typeof tps === "number" && Number.isFinite(tps) ? `${Math.round(tps)}` : "—";
+ typeof tps === "number" && Number.isFinite(tps) ? `${Math.round(tps)} tok/s` : "—";
-function PerfStat({ value, label }: { value: string; label: string }) {
- return (
- <div className="flex flex-col items-center">
- <div className="text-[15px] leading-[120%] text-label-title">{value}</div>
- <div className="text-[11px] leading-[120%] text-label-muted mt-1">{label}</div>
- </div>
- );
-}
+type Metric = { value: string; short: string; full: string };
+/**
+ * The run's speed figures in our tooltip, opened at once on hover and lined up above the button like
+ * the Regenerate menu beside it. One figure per line, everything aligned left: the number with its
+ * unit (always spelled the same way: s, tok/s, tok/pass), then its short name in lowercase; the
+ * full name stays on the abbreviation for screen readers and the title.
+ */
export function PerformanceDropdown({ perf, disabled = false }: PerformanceDropdownProps) {
const tokensPerForwardPass = perf?.tokensPerForwardPass;
- const hasSpeculation = typeof tokensPerForwardPass === "number" && Number.isFinite(tokensPerForwardPass);
+ const metrics: Metric[] = [
+ { value: formatSeconds(perf?.ttftSec), short: "ttft", full: "Time to first token" },
+ { value: formatTps(perf?.tps), short: "tps", full: "Tokens per second" },
+ ...(typeof tokensPerForwardPass === "number" && Number.isFinite(tokensPerForwardPass)
+ ? [{ value: `${tokensPerForwardPass.toFixed(2)} tok/pass`, short: "mal", full: "Mean accepted length" }]
+ : []),
+ { value: formatSeconds(perf?.totalSec), short: "time", full: "Total time" },
+ ];
+
+ const button = (
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label="Performance"
+ className="flex size-8 items-center justify-center rounded-lg text-label-muted transition-colors duration-150 ease-out enabled:hover:bg-bg-hover enabled:hover:text-label-title outline-hidden focus-visible:shadow-focus disabled:opacity-60 disabled:cursor-not-allowed"
+ >
+ <ZapIcon size={16} aria-hidden />
+ </button>
+ );
+ if (disabled) return button;
return (
- <Popover className="w-fit">
- <PopoverButton
- disabled={disabled}
- aria-label="Performance"
- title="Performance"
- className="flex size-8 items-center justify-center rounded-md text-label-muted transition-colors enabled:hover:bg-bg-hover enabled:hover:text-label-title focus:outline-hidden data-[focus]:shadow-focus disabled:opacity-60 disabled:cursor-not-allowed"
- >
- <Activity className="size-4" aria-hidden="true" />
- </PopoverButton>
- <Transition
- enter="transition duration-100 ease-out"
- enterFrom="transform scale-95 opacity-0"
- enterTo="transform scale-100 opacity-100"
- leave="transition duration-75 ease-out"
- leaveFrom="transform scale-100 opacity-100"
- leaveTo="transform scale-95 opacity-0"
- >
- <PopoverPanel
- anchor="top start"
- className="[--anchor-gap:8px] bg-bg-modal border border-cell-border rounded-[6px] z-50 pointer-events-auto focus:outline-hidden focus:ring-0"
- >
- <div className="p-[10px]">
- <div className={`grid ${hasSpeculation ? "grid-cols-4" : "grid-cols-3"} gap-3 text-center`}>
- <PerfStat value={formatSeconds(perf?.ttftSec)} label="Time to first token" />
- <PerfStat value={formatTps(perf?.tps)} label="Tokens per second" />
- {hasSpeculation && (
- <PerfStat value={`${tokensPerForwardPass.toFixed(2)} tok/pass`} label="Acceptance rate" />
- )}
- <PerfStat value={formatSeconds(perf?.totalSec)} label="Total time" />
- </div>
- </div>
- </PopoverPanel>
- </Transition>
- </Popover>
+ <Tooltip
+ side="top"
+ align="start"
+ variant="panel"
+ delay={0}
+ content={
+ <div className="grid grid-cols-[auto_auto] items-baseline gap-x-3 gap-y-2 text-[13px] leading-[18px]">
+ {metrics.map((metric) => (
+ <Fragment key={metric.short}>
+ <span className="font-[500] text-text-primary tabular-nums">{metric.value}</span>
+ <span className="font-[400] text-text-muted">
+ {metric.short === metric.full ? (
+ metric.short
+ ) : (
+ <abbr title={metric.full} className="no-underline">
+ {metric.short}
+ </abbr>
+ )}
+ </span>
+ </Fragment>
+ ))}
+ </div>
+ }
+ >
+ {button}
+ </Tooltip>
);
}
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.test.tsx b/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.test.tsx
index 86e0b830f..c1e3285b9 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.test.tsx
@@ -53,9 +53,10 @@ const settleScrolling = () =>
const measure = (element: HTMLDivElement, height: number, contentHeight: number) => {
const geometry = { height, contentHeight, top: 0 };
Object.defineProperties(element, {
- clientHeight: { get: () => geometry.height },
- scrollHeight: { get: () => geometry.contentHeight },
+ clientHeight: { configurable: true, get: () => geometry.height },
+ scrollHeight: { configurable: true, get: () => geometry.contentHeight },
scrollTop: {
+ configurable: true,
get: () => geometry.top,
set: (value: number) => {
geometry.top = Math.max(0, Math.min(value, geometry.contentHeight - geometry.height));
@@ -144,8 +145,9 @@ it("recalculates fades after a completed block is reopened", async () => {
const { view, scroll, fade } = await renderBlock();
scroll(0);
view.rerender(<ThinkingBlock text="Reasoning" reasoningInProgress={false} />);
- await waitFor(() => expect(view.container.querySelector(".overflow-y-auto")).toBeNull());
- fireEvent.click(screen.getByRole("button", { name: "Thinking" }));
+ // Closed reasoning stays mounted, hidden, so reopening doesn't have to render it again.
+ await waitFor(() => expect(view.container.querySelector(".overflow-y-auto")?.closest("[hidden]")).not.toBeNull());
+ fireEvent.click(screen.getByRole("button", { name: /^Thought/ }));
const scroller = view.container.querySelector<HTMLDivElement>(".overflow-y-auto")!;
measure(scroller, 100, 240);
resize(scroller);
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.tsx b/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.tsx
index 994fb1cdc..82cc66ff3 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/thinking-block.tsx
@@ -1,11 +1,17 @@
import { Transition } from "@headlessui/react";
-import { ChevronDownIcon } from "lucide-react";
+import { ChevronRightIcon } from "lucide-react";
import { memo, useCallback, useEffect, useRef, useState, type UIEvent } from "react";
import { twMerge } from "tailwind-merge";
-import { ThinkingBubbleIcon } from "@/components/icons/thinking-bubble";
+import { TextShimmer } from "@/components/ui/text-shimmer";
import { MarkdownRenderer } from "./markdown-renderer";
-type Props = { text: string; reasoningInProgress: boolean; isThinking?: boolean };
+type Props = {
+ text: string;
+ reasoningInProgress: boolean;
+ isThinking?: boolean;
+ /** Tool calls made within this run of thinking; named in the summary once it is done. */
+ toolCalls?: number;
+};
const FADE_RAMP_PX = 32;
const MAX_FADE_HEIGHT_PX = 42;
@@ -15,8 +21,21 @@ export const ThinkingBlock = memo(function ThinkingBlock({
text,
reasoningInProgress,
isThinking = reasoningInProgress,
+ toolCalls = 0,
}: Props) {
const [isReasoningVisible, setIsReasoningVisible] = useState(false);
+ // How long it thought, measured while you watched; reopened chats just say it thought.
+ const [seconds, setSeconds] = useState<number | null>(null);
+ const thinkingSinceRef = useRef<number | null>(null);
+ useEffect(() => {
+ if (isThinking) {
+ thinkingSinceRef.current ??= performance.now();
+ return;
+ }
+ if (thinkingSinceRef.current === null) return;
+ setSeconds(Math.max(1, Math.round((performance.now() - thinkingSinceRef.current) / 1000)));
+ thinkingSinceRef.current = null;
+ }, [isThinking]);
const wasReasoningInProgressRef = useRef(false);
const userToggledRef = useRef(false);
@@ -93,33 +112,40 @@ export const ThinkingBlock = memo(function ThinkingBlock({
userToggledRef.current = true;
setIsReasoningVisible((v) => !v);
}}
- className={twMerge(
- "group mb-1 px-3 pt-2 border border-cell-border w-full rounded-[8px] transition-colors duration-150",
- "hover:[background-color:rgba(0,0,0,0.01)] dark:hover:[background-color:rgba(255,255,255,0.01)]",
- )}
+ // A line of text, not a box: the cat beside the answer already shows that it is thinking.
+ className="group mb-1 block w-full text-left [--fade:var(--color-background)] outline-hidden data-[focus]:shadow-focus rounded-md"
>
- <div className="flex pb-2 items-center justify-between p-0 group hover:bg-transparent text-label-title">
- <span className="flex items-center gap-2">
- <ThinkingBubbleIcon className="w-[14px] h-[14px]" />
-
- <span className="text-[13px] font-[400] leading-[130%]">{isThinking ? "Thinking..." : "Thinking"}</span>
- </span>
- <ChevronDownIcon
+ <span className="flex h-7 items-center gap-1 text-[15px] font-[400] leading-[1.3] text-label-muted transition-colors duration-150 ease-out group-hover:text-label-title">
+ {isThinking ? (
+ <TextShimmer duration={1.6} className="[--base-color:var(--color-label-muted)]">
+ Thinking…
+ </TextShimmer>
+ ) : (
+ <span key="done" className="animate-uzu-swap tabular-nums">
+ {seconds !== null ? `Thought for ${seconds} s` : "Thought"}
+ {toolCalls > 0 ? ` · ${toolCalls} ${toolCalls === 1 ? "tool call" : "tool calls"}` : ""}
+ </span>
+ )}
+ <ChevronRightIcon
+ aria-hidden
className={twMerge(
- "w-[12px] h-[12px] text-label-muted transition-transform transition-colors duration-150",
- isReasoningVisible && "rotate-180",
+ "size-3.5 shrink-0 transition-transform duration-250 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none",
+ isReasoningVisible && "rotate-90",
)}
/>
- </div>
+ </span>
+ {/* Opens on the same curve as the chevron, the text fading in as the height grows. It stays
+ mounted while closed, so opening never has to render the whole reasoning in its first
+ frame, which is what made it stutter. */}
<Transition
show={isReasoningVisible}
- appear
- enter="transition-[grid-template-rows] duration-200 ease-in-out motion-reduce:transition-none"
- enterFrom="grid-rows-[0fr]"
- enterTo="grid-rows-[1fr]"
- leave="transition-[grid-template-rows] duration-200 ease-in-out motion-reduce:transition-none"
- leaveFrom="grid-rows-[1fr]"
- leaveTo="grid-rows-[0fr]"
+ unmount={false}
+ enter="transition-[grid-template-rows,opacity] duration-250 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none"
+ enterFrom="grid-rows-[0fr] opacity-0"
+ enterTo="grid-rows-[1fr] opacity-100"
+ leave="transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none"
+ leaveFrom="grid-rows-[1fr] opacity-100"
+ leaveTo="grid-rows-[0fr] opacity-0"
>
<div className="grid">
<div className="min-h-0 min-w-0 overflow-clip">
@@ -127,12 +153,12 @@ export const ThinkingBlock = memo(function ThinkingBlock({
<div
ref={setReasoningScrollElement}
onScroll={onReasoningScroll}
- className="pb-2 text-left max-h-[180px] overflow-y-auto overscroll-y-auto thin-scrollbar"
+ className="pb-2 pt-0.5 text-left max-h-[180px] overflow-y-auto overscroll-y-auto thin-scrollbar"
>
<MarkdownRenderer
content={text || ""}
useOneFontSize={true}
- className="text-[12px] leading-[150%] font-mono text-label-muted [&_p]:mb-1 [&_p]:mt-1"
+ className="text-[15px] leading-[1.6] text-label-muted [&_p]:mb-2 [&_p]:mt-0"
/>
</div>
<div
@@ -142,7 +168,7 @@ export const ThinkingBlock = memo(function ThinkingBlock({
height: Math.min(MAX_FADE_HEIGHT_PX * fades.top, fades.viewportHeight / 2),
opacity: (2 / 3) * fades.top,
}}
- className="pointer-events-none absolute top-0 inset-x-0 z-10 [background:linear-gradient(180deg,#FFFFFF_0%,rgba(255,255,255,0)_100%)] dark:[background:linear-gradient(180deg,#0A0A0A_0%,rgba(10,10,10,0)_100%)]"
+ className="pointer-events-none absolute top-0 inset-x-0 z-10 bg-linear-to-b from-(--fade) to-transparent"
/>
<div
data-reasoning-fade="bottom"
@@ -151,7 +177,7 @@ export const ThinkingBlock = memo(function ThinkingBlock({
height: Math.min(END_FADE_HEIGHT_PX + END_FADE_HEIGHT_PX * fades.bottom, fades.viewportHeight / 2),
opacity: (1 + fades.bottom) / 3,
}}
- className="pointer-events-none absolute bottom-0 inset-x-0 z-10 [background:linear-gradient(180deg,rgba(255,255,255,0)_0%,#FFFFFF_100%)] dark:[background:linear-gradient(180deg,rgba(10,10,10,0)_0%,#0A0A0A_100%)]"
+ className="pointer-events-none absolute bottom-0 inset-x-0 z-10 bg-linear-to-b from-transparent to-(--fade)"
/>
</div>
</div>
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/user-message.test.tsx b/apps/mirai-gui/client/src/features/chat/components/message/user-message.test.tsx
index 4b648bd64..efa664a28 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/user-message.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/user-message.test.tsx
@@ -107,7 +107,7 @@ it("prevents duplicate submissions and closes after storage succeeds while gener
render(<UserMessage {...props} />);
edit();
save();
- expect((screen.getByRole("button", { name: "Saving..." }) as HTMLButtonElement).disabled).toBe(true);
+ expect((screen.getByRole("button", { name: "Saving…" }) as HTMLButtonElement).disabled).toBe(true);
expect((screen.getByRole("button", { name: "Cancel" }) as HTMLButtonElement).disabled).toBe(true);
fireEvent.keyDown(draft(), { key: "Enter", metaKey: true });
expect(onEdit).toHaveBeenCalledOnce();
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/user-message.tsx b/apps/mirai-gui/client/src/features/chat/components/message/user-message.tsx
index 09a17ca08..0a2739535 100644
--- a/apps/mirai-gui/client/src/features/chat/components/message/user-message.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/message/user-message.tsx
@@ -1,9 +1,8 @@
import { CopyButton } from "@/components/ui/copy-button";
-import { Button } from "@/components/ui/button";
import { Button as HeadlessButton } from "@headlessui/react";
import { TextArea } from "@/components/ui/text-area";
import { writeItemsWithFocus } from "@/utils/clipboard";
-import { Pencil } from "lucide-react";
+import { PencilIcon } from "@/components/icons/app-icons";
import { useId, useRef, useState } from "react";
import { attachmentStorage } from "../../services/attachment-storage";
import { AttachedFilesDisplay } from "../composer/attached-files-display";
@@ -64,23 +63,31 @@ export const UserMessage = ({ id, text, attachmentIds, canEdit = false, onEdit }
};
return (
- <div className="group/user">
+ <div className="group/user relative">
{hasAttachments && (
<div className="mb-3 ml-auto w-fit">
<AttachedFilesDisplay files={attachmentStorage.getFiles(attachmentIds ?? [])} />
</div>
)}
{editing ? (
- <div className="ml-auto flex w-full flex-col gap-3 rounded-lg bg-bg-hover p-3">
+ // Drawn like the message box below, since that's what it becomes for a moment: the same
+ // card, the text in the same place, and its actions in one row along the bottom.
+ <div className="ml-auto flex w-full flex-col rounded-[20px] bg-surface-elevated px-4 pt-4 pb-3 shadow-md transition-shadow duration-150 ease-out focus-within:shadow-lg dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)] dark:focus-within:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.18)]">
<TextArea
aria-label="Edit message"
aria-describedby={descriptionId}
autoFocus
+ // Opens with the caret after the text, ready to add to it.
+ onFocus={(event) => {
+ const end = event.currentTarget.value.length;
+ event.currentTarget.setSelectionRange(end, end);
+ }}
value={draft}
onChange={setDraft}
disabled={saving}
+ rows={1}
maxHeightPx={320}
- className="bg-transparent text-[15px] leading-[140%]"
+ className="bg-transparent text-[15px] leading-[1.5]"
onKeyDown={(event) => {
if (event.nativeEvent.isComposing) return;
if (event.key === "Escape") {
@@ -92,29 +99,42 @@ export const UserMessage = ({ id, text, attachmentIds, canEdit = false, onEdit }
}
}}
/>
- <p id={descriptionId} className="text-[12px] text-label-muted">
- Saving removes all later messages.
- </p>
{error && (
- <p role="alert" className="text-[13px] text-error">
+ <p role="alert" className="mt-2 text-[13px] text-error">
{error}
</p>
)}
- <div className="flex justify-end gap-2">
- <Button type="button" size="sm" kind="ghost" disabled={saving} onClick={cancel}>
- Cancel
- </Button>
- <Button type="button" size="sm" disabled={!canSave} onClick={() => void save()}>
- {saving ? "Saving..." : "Save & send"}
- </Button>
+ <div className="mt-4 flex items-center justify-between gap-3">
+ <p id={descriptionId} className="min-w-0 text-[12px] leading-[1.4] text-label-muted text-pretty">
+ Saving removes all later messages.
+ </p>
+ <div className="flex shrink-0 items-center gap-1.5">
+ <button
+ type="button"
+ disabled={saving}
+ onClick={cancel}
+ className="h-7 rounded-full px-3 text-[13px] font-[450] text-text-secondary outline-hidden transition-colors duration-150 ease-out hover:bg-control-fill hover:text-text-primary focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ disabled={!canSave}
+ onClick={() => void save()}
+ className="h-7 rounded-full bg-primary px-3 text-[13px] font-[500] text-primary-contrast outline-hidden transition-[background-color,scale] duration-150 ease-out hover:bg-primary-hover active:scale-[0.97] focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-40"
+ >
+ {saving ? "Saving…" : "Save & send"}
+ </button>
+ </div>
</div>
</div>
) : (
<>
- <div className="font-[350] text-label-title relative w-fit max-w-full whitespace-pre-wrap [overflow-wrap:anywhere] rounded-[5px] text-[15px] leading-[140%] px-2.5 py-[6px] bg-bg-hover ml-auto">
+ <div className="font-[400] text-user-bubble-text relative w-fit max-w-full whitespace-pre-wrap [overflow-wrap:anywhere] rounded-[18px] text-[15px] leading-[1.5] px-3.5 py-2 bg-user-bubble ml-auto">
{text}
</div>
- <div className="mt-2 flex h-8 items-center justify-end gap-1 opacity-0 transition-opacity group-hover/user:opacity-100 group-focus-within/user:opacity-100 [@media(hover:none)]:opacity-100">
+ {/* Floats under the bubble on hover rather than holding an empty row open below it. */}
+ <div className="absolute right-0 top-full z-10 mt-1 flex h-8 items-center justify-end gap-1 opacity-0 transition-opacity group-hover/user:opacity-100 group-focus-within/user:opacity-100 [@media(hover:none)]:opacity-100">
<CopyButton className="[&_svg]:size-4" onCopy={copy} />
{onEdit && (
<HeadlessButton
@@ -124,9 +144,9 @@ export const UserMessage = ({ id, text, attachmentIds, canEdit = false, onEdit }
title="Edit message"
disabled={!canEdit}
onClick={startEditing}
- className="flex min-h-8 min-w-8 items-center justify-center rounded-[5px] p-[6px] text-label-muted outline-hidden transition-colors hover:bg-card-hover hover:text-label-title data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-50"
+ className="flex min-h-8 min-w-8 items-center justify-center rounded-lg p-[6px] text-label-muted outline-hidden transition-colors hover:bg-card-hover hover:text-label-title data-[focus]:shadow-focus disabled:pointer-events-none disabled:opacity-50"
>
- <Pencil className="size-4" />
+ <PencilIcon size={16} />
</HeadlessButton>
)}
</div>
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/uzu-bird.tsx b/apps/mirai-gui/client/src/features/chat/components/message/uzu-bird.tsx
new file mode 100644
index 000000000..074849f52
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/uzu-bird.tsx
@@ -0,0 +1,351 @@
+import { twMerge } from "tailwind-merge";
+import { Dialog, DialogPanel, DialogTitle } from "@headlessui/react";
+import { X } from "lucide-react";
+import React, { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { UzuCat, UzuCatStill } from "@/components/uzu-cat";
+
+/*
+ * Uzu bird: a tiny flappy game to pass a long think. The cat is the bird; the pipes are drawn like
+ * its brackets. Space, click or tap to flap.
+ */
+
+const W = 360;
+const H = 360;
+const CAT = 40;
+const CAT_X = 72;
+const HIT = 24; // forgiving hitbox inside the drawing
+const GRAVITY = 1500; // px/s²
+const FLAP = -430; // px/s
+const SPEED = 140; // px/s
+const PIPE_W = 52;
+const GAP = 138;
+const SPACING = 190;
+const BEST_KEY = "mirai.uzuBird.best";
+
+type Pipe = { x: number; gapY: number; passed: boolean };
+type Phase = "playing" | "over";
+
+const readBest = () => {
+ try {
+ return Number(localStorage.getItem(BEST_KEY)) || 0;
+ } catch {
+ return 0;
+ }
+};
+const saveBest = (best: number) => {
+ try {
+ localStorage.setItem(BEST_KEY, String(best));
+ } catch {
+ // Private windows and blocked storage: the best score lasts for this session only.
+ }
+};
+
+const newPipe = (x: number): Pipe => ({ x, gapY: 90 + Math.random() * (H - 180 - GAP), passed: false });
+
+function Game({
+ answerReady,
+ onBack,
+ jumpRef,
+}: {
+ answerReady: boolean;
+ onBack: () => void;
+ /** Filled with the flap action, so the "Space to jump" button outside the field can use it. */
+ jumpRef: { current: (() => void) | null };
+}) {
+ // It starts the moment the window opens, already on its way up.
+ const [phase, setPhase] = useState<Phase>("playing");
+ const [score, setScore] = useState(0);
+ const [best, setBest] = useState(readBest);
+ const [, setFrame] = useState(0);
+ const world = useRef({ y: H / 2 - CAT / 2, vy: FLAP, pipes: [newPipe(W + 40), newPipe(W + 40 + SPACING)] });
+ const flappedAt = useRef(performance.now());
+ const phaseRef = useRef<Phase>("playing");
+ phaseRef.current = phase;
+
+ const reset = useCallback(() => {
+ world.current = { y: H / 2 - CAT / 2, vy: FLAP, pipes: [newPipe(W + 40), newPipe(W + 40 + SPACING)] };
+ flappedAt.current = performance.now();
+ setScore(0);
+ setPhase("playing");
+ }, []);
+
+ const flap = useCallback(() => {
+ if (phaseRef.current === "over") return;
+ world.current.vy = FLAP;
+ flappedAt.current = performance.now();
+ }, []);
+
+ useEffect(() => {
+ if (phase !== "playing") return;
+ let frame = 0;
+ let last = performance.now();
+ const tick = (now: number) => {
+ const dt = Math.min(0.05, (now - last) / 1000);
+ last = now;
+ const w = world.current;
+ w.vy += GRAVITY * dt;
+ w.y += w.vy * dt;
+ for (const pipe of w.pipes) pipe.x -= SPEED * dt;
+ if (w.pipes[0]!.x < -PIPE_W) {
+ w.pipes.shift();
+ w.pipes.push(newPipe(w.pipes[w.pipes.length - 1]!.x + SPACING));
+ }
+ const cx = CAT_X + CAT / 2;
+ const cy = w.y + CAT / 2;
+ let crashed = cy - HIT / 2 < 0 || cy + HIT / 2 > H;
+ for (const pipe of w.pipes) {
+ const overlapsX = cx + HIT / 2 > pipe.x && cx - HIT / 2 < pipe.x + PIPE_W;
+ if (overlapsX && (cy - HIT / 2 < pipe.gapY || cy + HIT / 2 > pipe.gapY + GAP)) crashed = true;
+ if (!pipe.passed && pipe.x + PIPE_W < cx) {
+ pipe.passed = true;
+ setScore((s) => s + 1);
+ }
+ }
+ if (crashed) {
+ setPhase("over");
+ return;
+ }
+ setFrame((f) => f + 1);
+ frame = requestAnimationFrame(tick);
+ };
+ frame = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(frame);
+ }, [phase]);
+
+ useEffect(() => {
+ if (phase !== "over" || score <= best) return;
+ setBest(score);
+ saveBest(score);
+ }, [phase, score, best]);
+
+ useEffect(() => {
+ jumpRef.current = () => (phaseRef.current === "over" ? reset() : flap());
+ return () => {
+ jumpRef.current = null;
+ };
+ }, [jumpRef, flap, reset]);
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.code !== "Space" && e.code !== "ArrowUp") return;
+ e.preventDefault();
+ if (e.repeat) return;
+ if (phaseRef.current === "over") reset();
+ else flap();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [flap, reset]);
+
+ const w = world.current;
+ const justFlapped = performance.now() - flappedAt.current < 220;
+
+ const tilt = phase === "playing" ? Math.max(-25, Math.min(60, w.vy / 9)) : 0;
+
+ return (
+ <div
+ role="application"
+ aria-label="Uzu bird game"
+ onPointerDown={(e) => {
+ if (e.button !== 0) return;
+ if (phase === "over") return;
+ flap();
+ }}
+ className="relative overflow-hidden rounded-xl bg-surface-soft select-none touch-none"
+ style={{ width: W, height: H }}
+ >
+ {w.pipes.map((pipe, i) => (
+ <div key={i} aria-hidden>
+ <div
+ className="absolute rounded-b-[14px] border-[5px] border-t-0 border-text-primary"
+ style={{ left: pipe.x, top: -6, width: PIPE_W, height: pipe.gapY + 6 }}
+ />
+ <div
+ className="absolute rounded-t-[14px] border-[5px] border-b-0 border-text-primary"
+ style={{ left: pipe.x, top: pipe.gapY + GAP, width: PIPE_W, height: H - pipe.gapY - GAP + 6 }}
+ />
+ </div>
+ ))}
+
+ <div
+ className="absolute text-text-primary"
+ style={{ left: CAT_X, top: w.y, width: CAT, height: CAT, transform: `rotate(${tilt}deg)` }}
+ >
+ {/* Flying, the cat holds still with its normal eyes (no blinking), pleased on each flap;
+ only a crash brings the live, trembling face. */}
+ {phase === "over" ? (
+ <UzuCat state="memory" size={CAT} />
+ ) : (
+ <UzuCatStill pose={justFlapped ? "happy" : "default"} size={CAT} />
+ )}
+ </div>
+
+ <div className="absolute inset-x-0 top-4 text-center text-[28px] font-[600] tabular-nums text-text-primary">
+ {score}
+ </div>
+
+ {phase === "over" ? (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 bg-surface-soft/70 backdrop-blur-[2px] animate-uzu-in">
+ <p className="text-[15px] font-[500] text-label-title">Score {score}</p>
+ <p className="text-[13px] text-label-muted tabular-nums">Best {Math.max(best, score)}</p>
+ <button
+ type="button"
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={reset}
+ className="mt-4 h-8 rounded-full bg-primary px-4 text-[13px] font-[500] text-primary-contrast outline-hidden transition-[scale] duration-150 ease-out active:scale-[0.97] focus-visible:shadow-focus"
+ >
+ Play again
+ </button>
+ </div>
+ ) : null}
+
+ {answerReady ? (
+ <div className="absolute inset-x-3 bottom-3 flex items-center justify-between gap-2 rounded-xl bg-surface-popover px-3 py-2 shadow-popover animate-uzu-in">
+ <span className="text-[13px] font-[450] text-label-title">Your answer is ready</span>
+ <button
+ type="button"
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={onBack}
+ className="flex h-7 items-center gap-1.5 rounded-full bg-primary pl-3 pr-1 text-[12px] font-[500] text-primary-contrast outline-hidden focus-visible:shadow-focus"
+ >
+ Back to chat
+ <kbd className="rounded-full bg-primary-contrast/15 px-2 py-0.5 font-sans text-[11px] font-[500]">Esc</kbd>
+ </button>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+/** A key hint that is also the action, for pointer users. */
+function HintButton({
+ keyLabel,
+ onClick,
+ children,
+ className,
+}: {
+ keyLabel: string;
+ onClick: () => void;
+ children: string;
+ className?: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={twMerge(
+ "flex h-7 items-center gap-1.5 rounded-full bg-control-fill pl-1 pr-3 text-[12px] font-[450] text-text-secondary outline-hidden transition-colors duration-150 ease-out hover:bg-control-fill-hover hover:text-label-title focus-visible:shadow-focus",
+ className,
+ )}
+ >
+ <kbd className="rounded-full bg-control-selected px-2 py-0.5 font-sans text-[11px] font-[500] text-label-title shadow-[0_0_0_0.5px_rgb(0_0_0/0.08)] dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)]">
+ {keyLabel}
+ </kbd>
+ {children}
+ </button>
+ );
+}
+
+/** The game window. */
+export function UzuBirdDialog({
+ open,
+ onClose,
+ answerReady,
+}: {
+ open: boolean;
+ onClose: () => void;
+ answerReady: boolean;
+}) {
+ const jumpRef = useRef<(() => void) | null>(null);
+ return (
+ <Dialog open={open} onClose={onClose} className="relative z-50">
+ <div className="fixed inset-0 bg-black/20 backdrop-blur-[6px]" aria-hidden />
+ <div className="fixed inset-0 flex items-center justify-center p-4">
+ <DialogPanel className="rounded-2xl bg-surface-popover p-3 shadow-popover animate-uzu-in">
+ <div className="flex items-center justify-between px-1 pb-3">
+ <DialogTitle className="text-[15px] font-[600] text-label-title">Uzu bird</DialogTitle>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="flex size-7 items-center justify-center rounded-full text-label-muted outline-hidden transition-colors duration-150 ease-out hover:bg-surface-tertiary hover:text-label-title focus-visible:shadow-focus"
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ <Game answerReady={answerReady} onBack={onClose} jumpRef={jumpRef} />
+ <div className="flex items-center justify-center gap-2 pt-3">
+ <HintButton keyLabel="Space" onClick={() => jumpRef.current?.()}>
+ to jump
+ </HintButton>
+ <HintButton keyLabel="Esc" onClick={onClose}>
+ to close
+ </HintButton>
+ </div>
+ </DialogPanel>
+ </div>
+ </Dialog>
+ );
+}
+
+/*
+ * Whether the game is open lives outside the message that offered it. When the answer lands, the
+ * in-progress message is replaced by the finished one; the game must outlive that swap, so the
+ * window is drawn by UzuBirdHost in the message list and only told here that the answer is ready.
+ */
+type BirdState = { open: boolean; answerReady: boolean };
+let birdState: BirdState = { open: false, answerReady: false };
+const birdListeners = new Set<() => void>();
+function setBird(patch: Partial<BirdState>) {
+ const next = { ...birdState, ...patch };
+ if (next.open === birdState.open && next.answerReady === birdState.answerReady) return;
+ birdState = next;
+ birdListeners.forEach((listener) => listener());
+}
+function subscribeBird(listener: () => void) {
+ birdListeners.add(listener);
+ return () => birdListeners.delete(listener);
+}
+const getBird = () => birdState;
+const useBird = () => useSyncExternalStore(subscribeBird, getBird, getBird);
+
+/** Tells the game whether the newest answer has landed, so it can offer the way back. */
+export function UzuBirdAnswerSync({ answerReady }: { answerReady: boolean }) {
+ useEffect(() => {
+ setBird({ answerReady });
+ }, [answerReady]);
+ return null;
+}
+
+const TAPS = 2;
+const TAP_WINDOW_MS = 500;
+
+/**
+ * The way in is hidden: a double tap on a cat beside an answer. Returns handlers for the cat's
+ * box. Opening clears "answer ready", so a game started after the answer only offers the way back
+ * once a new answer lands.
+ */
+export function useUzuBirdTaps() {
+ const taps = useRef<number[]>([]);
+ return {
+ // Repeated clicks would otherwise select the text beside the cat.
+ onMouseDown: (e: React.MouseEvent) => {
+ if (e.detail > 1) e.preventDefault();
+ },
+ onClick: () => {
+ const now = performance.now();
+ taps.current = [...taps.current.filter((t) => now - t < TAP_WINDOW_MS), now];
+ if (taps.current.length < TAPS) return;
+ taps.current = [];
+ setBird({ open: true, answerReady: false });
+ },
+ };
+}
+
+/** The game window, mounted once with the message list so it stays open while the answer lands. */
+export function UzuBirdHost() {
+ const { open, answerReady } = useBird();
+ // Leaving the chat closes the game rather than leaving it waiting for the next one.
+ useEffect(() => () => setBird({ open: false }), []);
+ return <UzuBirdDialog open={open} onClose={() => setBird({ open: false })} answerReady={answerReady} />;
+}
diff --git a/apps/mirai-gui/client/src/features/local-models/components/family-card.tsx b/apps/mirai-gui/client/src/features/local-models/components/family-card.tsx
index e39812821..9a0214a45 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/family-card.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/family-card.tsx
@@ -20,32 +20,27 @@ export type FamilyCardProps = {
compact?: boolean;
};
+// Raised off the card like the row buttons, so the badges read on the soft fill.
+const RAISED =
+ "bg-surface-popover shadow-[0_0_0_0.5px_rgb(0_0_0/0.08),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)]";
+
+// Every badge is the same raised pill; success only adds a green dot and lifts the text a step.
const TONE_CLASSES: Record<FamilyCardBadgeTone, { border: string; text: string }> = {
- neutral: {
- border: "border-border-outlined",
- text: "text-text-muted",
- },
- success: {
- border: "border-success-border",
- text: "text-success",
- },
+ neutral: { border: RAISED, text: "text-text-muted" },
+ success: { border: twMerge(RAISED, "gap-1.5 pl-2"), text: "text-text-secondary" },
};
-function Chip({ badge }: { badge: FamilyCardBadge }) {
+export function FamilyBadge({ badge }: { badge: FamilyCardBadge }) {
const { label, tone = "neutral" } = badge;
const tones = TONE_CLASSES[tone];
return (
- <div
- className={twMerge(
- "flex items-center justify-center h-7 px-2 py-0.5 rounded border-[0.5px] bg-transparent cursor-default",
- tones.border,
- )}
- >
+ <div className={twMerge("flex items-center justify-center h-6 px-2.5 rounded-full cursor-default", tones.border)}>
+ {tone === "success" && <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-success-strong" />}
<Text
as="span"
opticalSize={14}
- className={twMerge("text-[13px] font-[450] leading-[1.3] whitespace-nowrap", tones.text)}
+ className={twMerge("text-[12px] font-[450] leading-[1.3] whitespace-nowrap tabular-nums", tones.text)}
>
{label}
</Text>
@@ -70,7 +65,7 @@ export function FamilyCard({ vendorIcon, familyName, vendorName, badges, onClick
</div>
);
- const chips = badges?.map((badge, idx) => <Chip key={idx} badge={badge} />);
+ const chips = badges?.map((badge, idx) => <FamilyBadge key={idx} badge={badge} />);
const chevron = <ChevronRight size={14} className="text-text-muted shrink-0" />;
@@ -80,7 +75,7 @@ export function FamilyCard({ vendorIcon, familyName, vendorName, badges, onClick
type="button"
onClick={onClick}
aria-label={fallbackAria}
- className="w-full flex flex-col items-stretch gap-3 px-4 py-3 rounded-lg border-[0.5px] border-border-default bg-surface-elevated transition-colors duration-150 cursor-pointer outline-hidden data-[focus]:shadow-focus hover:bg-surface-tertiary text-left"
+ className="w-full flex flex-col items-stretch gap-3 px-4 py-3 rounded-xl bg-surface-soft transition-colors duration-150 ease-out cursor-pointer outline-hidden data-[focus]:shadow-focus hover:bg-surface-tertiary text-left"
>
<div className="flex items-center gap-3 min-w-0">
{heading}
@@ -96,7 +91,7 @@ export function FamilyCard({ vendorIcon, familyName, vendorName, badges, onClick
type="button"
onClick={onClick}
aria-label={fallbackAria}
- className="w-full flex items-center justify-between gap-4 h-12 pl-4 pr-3 rounded-lg border-[0.5px] border-border-default bg-surface-elevated transition-colors duration-150 cursor-pointer outline-hidden data-[focus]:shadow-focus hover:bg-surface-tertiary"
+ className="w-full flex items-center justify-between gap-4 h-14 pl-4 pr-3 rounded-xl bg-surface-soft transition-colors duration-150 ease-out cursor-pointer outline-hidden data-[focus]:shadow-focus hover:bg-surface-tertiary"
>
{heading}
<div className="flex items-center gap-1.5 shrink-0">
diff --git a/apps/mirai-gui/client/src/features/local-models/components/family-detail-page.tsx b/apps/mirai-gui/client/src/features/local-models/components/family-detail-page.tsx
index 33f9de2c2..cd8354c35 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/family-detail-page.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/family-detail-page.tsx
@@ -84,7 +84,7 @@ export function FamilyDetailPage({
}
return (
- <div className="flex flex-col gap-6">
+ <div className="flex flex-col gap-10">
{detail.installed.length > 0 && (
<ModelTable title="Downloaded" compact={isMobile}>
{detail.installed.map((m) => renderRow(m))}
diff --git a/apps/mirai-gui/client/src/features/local-models/components/local-models-page/index.tsx b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/index.tsx
index 4fd16e0e2..9318332b5 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/local-models-page/index.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/index.tsx
@@ -13,7 +13,10 @@ import { Modal } from "@/components/ui/modal";
import { Text } from "@/components/ui/typography";
import { TooltipProvider } from "@/components/ui/tooltip/provider";
import { RefreshCcw } from "lucide-react";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useAppStore } from "@/stores/use-app-store";
+import { LocalModelsHero } from "./local-models-hero";
+import { PageScroller } from "@/components/page-title-bar";
import { v4 as uuidv4 } from "uuid";
import { buildFamiliesView, formatParamRange, type FamilyEntry } from "../../lib/view";
import { FamilyDetailPage } from "../family-detail-page";
@@ -26,18 +29,24 @@ const TEXT_14_STYLE = { fontVariationSettings: "'opsz' 20" } as const;
export function LocalModelsPage() {
const navigate = useNavigate();
const isMobile = useIsMobile();
+ const chatWidth = useAppStore((s) => s.chatWidth);
const createNewChat = useChatStore((s) => s.createNewChat);
const { handleDownload, handlePause, handleResume, handleCancel } = useDownloadManager();
- const [searchQuery, setSearchQuery] = useState("");
- const [modelsSearch, setModelsSearch] = useState("");
const [selectedFamilyId, setSelectedFamilyId] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
+ // Which way the last move went, so the new level slides in from that side. Null on first load:
+ // the page just appears.
+ const [direction, setDirection] = useState<"forward" | "back" | null>(null);
+ const scrollRef = useRef<HTMLDivElement>(null);
const selectFamily = useCallback((id: string | null) => {
+ setDirection(id ? "forward" : "back");
setSelectedFamilyId(id);
- setModelsSearch("");
+ scrollRef.current?.scrollTo({ top: 0 });
}, []);
+ const levelAnimation =
+ direction === "forward" ? "animate-uzu-forward" : direction === "back" ? "animate-uzu-back" : undefined;
const models = useModelsStore((s) => s.models);
const loadingModels = useModelsStore((s) => s.loading);
@@ -74,11 +83,9 @@ export function LocalModelsPage() {
[getSize, newestTextModelComparator],
);
- const searchLower = searchQuery.trim().toLowerCase();
-
const families: FamilyEntry[] = useMemo(
- () => buildFamiliesView({ models, modelPhasesById, installedAtById, searchLower }),
- [models, modelPhasesById, installedAtById, searchLower],
+ () => buildFamiliesView({ models, modelPhasesById, installedAtById, searchLower: "" }),
+ [models, modelPhasesById, installedAtById],
);
const selectedFamily = useMemo(
@@ -122,24 +129,64 @@ export function LocalModelsPage() {
);
}
+ const familyList = (
+ <div className="flex flex-col gap-2">
+ {families.map((family) => {
+ const sizeRange = formatParamRange(family.paramRange?.min, family.paramRange?.max);
+ const badges: FamilyCardBadge[] = [
+ ...(family.installedCount > 0
+ ? [
+ {
+ label: `${family.installedCount} downloaded`,
+ tone: "success" as const,
+ },
+ ]
+ : []),
+ {
+ label: `${family.totalCount} ${family.totalCount === 1 ? "model" : "models"}`,
+ },
+ ...(sizeRange ? [{ label: sizeRange }] : []),
+ ];
+ return (
+ <FamilyCard
+ key={family.familyIdentifier}
+ compact={isMobile}
+ vendorIcon={<ModelVendorIcon vendor={family.vendor} size={16} className="h-4 w-4" />}
+ familyName={family.familyName}
+ vendorName={family.vendor}
+ badges={badges}
+ onClick={() => selectFamily(family.familyIdentifier)}
+ />
+ );
+ })}
+ </div>
+ );
+
return (
<TooltipProvider>
- <div className="flex h-full min-h-0 flex-col bg-background">
- <div className="w-full flex h-full min-h-0 overflow-clip bg-surface-elevated">
+ <div
+ className="flex h-full min-h-0 flex-col bg-background"
+ style={{ "--chat-width": `${chatWidth}px` } as CSSProperties}
+ >
+ <div className="w-full flex h-full min-h-0 overflow-clip">
<div className="flex-1 min-w-0 min-h-0 flex flex-col">
- <LocalModelsHeader
- selectedFamily={selectedFamily}
- isMobile={isMobile}
- searchQuery={searchQuery}
- modelsSearch={modelsSearch}
- onSearchQueryChange={setSearchQuery}
- onModelsSearchChange={setModelsSearch}
- onBack={() => selectFamily(null)}
- />
- <div style={{ borderBottom: "0.5px solid var(--color-border-default)" }}></div>
-
- <div className="flex-1 min-h-0 overflow-y-auto overscroll-y-contain scrollbar-hide">
- <div className="px-4 py-4">
+ <PageScroller
+ scrollRef={scrollRef}
+ className="scrollbar-hide"
+ header={
+ <LocalModelsHeader
+ selectedFamily={selectedFamily}
+ isMobile={isMobile}
+ onBack={() => selectFamily(null)}
+ animationClassName={levelAnimation}
+ />
+ }
+ >
+ <div
+ key={selectedFamilyId ?? "families"}
+ className={`px-5 pt-4 pb-8 w-full max-w-[calc(var(--chat-width)+2.5rem)] mx-auto ${levelAnimation ?? ""}`}
+ >
+ {!selectedFamily && models.length > 0 ? <LocalModelsHero /> : null}
{(modelsError || incompleteCatalog) && (
<div className="my-4">
<div className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-900/20">
@@ -180,7 +227,7 @@ export function LocalModelsPage() {
) : selectedFamily ? (
<FamilyDetailPage
family={selectedFamily}
- searchQuery={modelsSearch}
+ searchQuery=""
sortModels={sortModels}
onDownload={handleDownload}
onPause={handlePause}
@@ -191,44 +238,13 @@ export function LocalModelsPage() {
/>
) : families.length === 0 ? (
<div className="flex min-h-[200px] items-center justify-center">
- <span className="text-[13px] text-text-muted">
- {searchQuery ? `No families matching "${searchQuery}"` : "No model families"}
- </span>
+ <span className="text-[13px] text-text-muted">No model families</span>
</div>
) : (
- <div className="flex flex-col gap-1.5">
- {families.map((family) => {
- const sizeRange = formatParamRange(family.paramRange?.min, family.paramRange?.max);
- const badges: FamilyCardBadge[] = [
- ...(family.installedCount > 0
- ? [
- {
- label: `${family.installedCount} downloaded ${family.installedCount === 1 ? "model" : "models"}`,
- tone: "success" as const,
- },
- ]
- : []),
- {
- label: `${family.totalCount} ${family.totalCount === 1 ? "model" : "models"}`,
- },
- ...(sizeRange ? [{ label: sizeRange }] : []),
- ];
- return (
- <FamilyCard
- key={family.familyIdentifier}
- compact={isMobile}
- vendorIcon={<ModelVendorIcon vendor={family.vendor} size={16} className="h-4 w-4" />}
- familyName={family.familyName}
- vendorName={family.vendor}
- badges={badges}
- onClick={() => selectFamily(family.familyIdentifier)}
- />
- );
- })}
- </div>
+ familyList
)}
</div>
- </div>
+ </PageScroller>
</div>
</div>
<Modal
diff --git a/apps/mirai-gui/client/src/features/local-models/components/local-models-page/local-models-header.tsx b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/local-models-header.tsx
index 2fb63abbf..9645cc242 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/local-models-page/local-models-header.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/local-models-header.tsx
@@ -1,92 +1,61 @@
-import { ChevronLeft, MonitorSmartphone } from "lucide-react";
-import { PageHeader } from "@/components/page-header";
+import { ChevronLeft } from "lucide-react";
+import { PageTitleBar } from "@/components/page-title-bar";
import type { FamilyEntry } from "../../lib/view";
import { IconAction } from "@/components/ui/icon-action";
-import { SearchInput } from "@/components/ui/search-input";
import { Tooltip } from "@/components/ui/tooltip";
import { ModelVendorIcon } from "@/components/model-vendor-icon";
-
-const TEXT_14 = "text-[14px] font-[450] leading-[1.5]";
-const TEXT_14_STYLE = { fontVariationSettings: "'opsz' 20" } as const;
+import { FamilyBadge } from "../family-card";
+import { formatParamRange } from "../../lib/view";
type LocalModelsHeaderProps = {
selectedFamily?: FamilyEntry;
isMobile: boolean;
- searchQuery: string;
- modelsSearch: string;
- onSearchQueryChange: (value: string) => void;
- onModelsSearchChange: (value: string) => void;
onBack: () => void;
+ /** Slides the title in with the page when moving between the families and a family. */
+ animationClassName?: string;
};
-export function LocalModelsHeader({
- selectedFamily,
- isMobile,
- searchQuery,
- modelsSearch,
- onSearchQueryChange,
- onModelsSearchChange,
- onBack,
-}: LocalModelsHeaderProps) {
- const search = selectedFamily
- ? { value: modelsSearch, onChange: onModelsSearchChange, placeholder: "Search models" }
- : { value: searchQuery, onChange: onSearchQueryChange, placeholder: "Search families" };
-
+/** The page title, set like the chats page: in the column, at the top. A family adds a way back. */
+export function LocalModelsHeader({ selectedFamily, isMobile, onBack, animationClassName }: LocalModelsHeaderProps) {
+ const range = selectedFamily
+ ? formatParamRange(selectedFamily.paramRange?.min, selectedFamily.paramRange?.max)
+ : undefined;
return (
- <>
- <PageHeader
- title={
- <div data-tauri-drag-region="deep" className="flex h-[52px] shrink-0 items-center gap-2 px-4 min-w-0">
- {selectedFamily ? (
- <>
- <Tooltip content="Back to families" side="bottom">
- <span className="shrink-0">
- <IconAction label="Back to families" icon={<ChevronLeft size={16} />} onClick={onBack} />
- </span>
- </Tooltip>
- <ModelVendorIcon vendor={selectedFamily.vendor} size={16} className="h-4 w-4" />
- <span className={`${TEXT_14} text-text-primary truncate`} style={TEXT_14_STYLE}>
- {selectedFamily.familyName}
- </span>
- {!isMobile && (
- <span className={`${TEXT_14} text-text-muted truncate`} style={TEXT_14_STYLE}>
- from {selectedFamily.vendor}
- </span>
- )}
- </>
- ) : (
- <>
- <MonitorSmartphone size={16} className="text-text-primary shrink-0" />
- <span className={`${TEXT_14} text-text-primary truncate`} style={TEXT_14_STYLE}>
- Choose a model to chat
- </span>
- </>
- )}
- <div className="flex-1" />
- {!isMobile && (
- <SearchInput
- value={search.value}
- onChange={search.onChange}
- placeholder={search.placeholder}
- className="w-[260px] shrink-0"
- />
- )}
- </div>
- }
- />
- {isMobile && (
- <div
- className="flex shrink-0 items-center gap-2 px-4 py-2"
- style={{ borderTop: "0.5px solid var(--color-border-default)" }}
- >
- <SearchInput
- value={search.value}
- onChange={search.onChange}
- placeholder={search.placeholder}
- className="min-w-0 flex-1"
- />
- </div>
- )}
- </>
+ <PageTitleBar>
+ <div
+ key={selectedFamily?.familyIdentifier ?? "families"}
+ className={`flex min-w-0 flex-1 items-center gap-2 ${animationClassName ?? ""}`}
+ >
+ {selectedFamily ? (
+ <>
+ <Tooltip content="Back to models" side="bottom">
+ <span className="shrink-0 -ml-1.5">
+ <IconAction label="Back to models" icon={<ChevronLeft size={18} />} onClick={onBack} />
+ </span>
+ </Tooltip>
+ <ModelVendorIcon vendor={selectedFamily.vendor} size={20} className="size-5" />
+ <h1 className="text-[20px] font-[600] leading-[1.2] tracking-[-0.01em] text-label-title truncate">
+ {selectedFamily.familyName}
+ </h1>
+ {/* Who made it and what's inside, as the same pills the family list uses. */}
+ <div className="ml-auto flex shrink-0 items-center gap-1.5">
+ {[
+ { label: selectedFamily.vendor },
+ ...(isMobile
+ ? []
+ : [
+ { label: `${selectedFamily.totalCount} ${selectedFamily.totalCount === 1 ? "model" : "models"}` },
+ ...(range ? [{ label: range }] : []),
+ ]),
+ ].map((badge) => (
+ <FamilyBadge key={badge.label} badge={badge} />
+ ))}
+ </div>
+ </>
+ ) : (
+ <h1 className="text-[20px] font-[600] leading-[1.2] tracking-[-0.01em] text-label-title">Models</h1>
+ )}
+ </div>
+ </PageTitleBar>
);
}
diff --git a/apps/mirai-gui/client/src/features/local-models/components/local-models-page/local-models-hero.tsx b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/local-models-hero.tsx
new file mode 100644
index 000000000..68da704da
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/local-models-hero.tsx
@@ -0,0 +1,19 @@
+import { UzuCat } from "@/components/uzu-cat";
+
+/**
+ * Above the catalog: the cat shows where these models live. Its brackets close into an iPhone,
+ * widen into a Mac, and open back into its face, on a loop.
+ */
+export function LocalModelsHero() {
+ return (
+ <div className="flex flex-col items-center pb-8 text-center animate-uzu-in">
+ <div className="mb-1">
+ <UzuCat state="local" size={112} className="text-text-primary" label="uzu, becoming an iPhone and a Mac" />
+ </div>
+ <div className="flex flex-col gap-1">
+ <h2 className="text-[15px] font-[500] leading-[1.35] text-label-title text-balance">Pick a model to chat</h2>
+ <p className="text-[13px] leading-[1.45] text-label-muted text-pretty">It runs right here, on your device</p>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/mirai-gui/client/src/features/local-models/components/local-models-page/use-model-deletion.ts b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/use-model-deletion.tsx
similarity index 85%
rename from apps/mirai-gui/client/src/features/local-models/components/local-models-page/use-model-deletion.ts
rename to apps/mirai-gui/client/src/features/local-models/components/local-models-page/use-model-deletion.tsx
index e965a2b3b..e9304e73f 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/local-models-page/use-model-deletion.ts
+++ b/apps/mirai-gui/client/src/features/local-models/components/local-models-page/use-model-deletion.tsx
@@ -1,3 +1,4 @@
+import { InlineModelName } from "@/components/model-name";
import { useToast } from "@/components/ui/toast/use-toast";
import { ejectRuntimeSessionAndWait } from "@/features/runtime/eject-runtime-session";
import { useModelsStore } from "@/stores/use-models-store";
@@ -27,9 +28,18 @@ export function useModelDeletion(fetchModels: () => Promise<void>): ModelDeletio
}
await useModelsStore.getState().deleteLocalModel(model.repoId);
- toast.success(`Deleted ${model.name}`);
+ toast.success(
+ <>
+ Deleted <InlineModelName name={model.name} />
+ </>,
+ );
} catch (error) {
- toast.error(`Failed to uninstall ${model.name}`);
+ toast.error(
+ <>
+ Couldn't delete <InlineModelName name={model.name} />
+ </>,
+ { description: error instanceof Error ? error.message : undefined },
+ );
console.error(error);
} finally {
await fetchModels();
diff --git a/apps/mirai-gui/client/src/features/local-models/components/model-card/chip.tsx b/apps/mirai-gui/client/src/features/local-models/components/model-card/chip.tsx
index f47d91106..983e858a6 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/model-card/chip.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/model-card/chip.tsx
@@ -6,7 +6,7 @@ function Chip({ children, className }: { children: ReactNode; className?: string
return (
<div
className={twMerge(
- "group/chip flex items-center justify-center h-7 px-2 py-0.5 rounded border-[0.5px] border-border-outlined bg-transparent hover:border-border-outlined-hover",
+ "group/chip flex items-center justify-center h-6 px-2.5 rounded-full bg-surface-popover shadow-[0_0_0_0.5px_rgb(0_0_0/0.08),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)]",
className,
)}
>
@@ -18,12 +18,7 @@ function Chip({ children, className }: { children: ReactNode; className?: string
export function ChipText({ children }: { children: ReactNode }) {
return (
<Chip>
- <Text
- as="span"
- color="muted"
- opticalSize={14}
- className="text-[13px] font-[450] leading-[1.3] group-hover/chip:text-text-primary"
- >
+ <Text as="span" color="muted" opticalSize={14} className="text-[12px] font-[450] leading-[1.3] tabular-nums">
{children}
</Text>
</Chip>
diff --git a/apps/mirai-gui/client/src/features/local-models/components/model-card/download-actions.tsx b/apps/mirai-gui/client/src/features/local-models/components/model-card/download-actions.tsx
index 191c0345c..a72e5264a 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/model-card/download-actions.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/model-card/download-actions.tsx
@@ -1,12 +1,14 @@
-import { Download, LoaderCircle, RefreshCw, X } from "lucide-react";
+import { DownloadIcon } from "@/components/icons/app-icons";
+import { LoaderCircle, RefreshCw, X } from "lucide-react";
import { IconAction } from "@/components/ui/icon-action";
-import { IconPauseFilled } from "@/components/icons/pause-filled-icon";
-import { IconPlayFilled } from "@/components/icons/play-filled-icon";
+import { PauseIcon } from "@/components/icons/pause-icon";
+import { PlayIcon } from "@/components/icons/play-icon";
import { Tooltip } from "@/components/ui/tooltip";
import type { ModelCardStatus } from "./types";
const ACTION_BUTTON_CLASS =
- "h-7 px-1.5 py-0.5 rounded bg-border-default text-text-primary hover:bg-control-surface-hover active:bg-control-surface-active";
+ // Raised off the card (a lighter surface and a hairline) so it reads on the soft fill.
+ "size-7 flex items-center justify-center rounded-full bg-surface-popover shadow-[0_0_0_0.5px_rgb(0_0_0/0.08),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)] text-text-primary transition-colors duration-150 ease-out hover:bg-surface-tertiary active:bg-control-surface-active";
type DownloadActionsProps = {
status: ModelCardStatus;
@@ -58,7 +60,7 @@ export function DownloadActions({
<span>
<IconAction
label="Download model"
- icon={<Download size={16} />}
+ icon={<DownloadIcon size={16} />}
onClick={onDownload}
className={ACTION_BUTTON_CLASS}
/>
@@ -71,7 +73,7 @@ export function DownloadActions({
<span>
<IconAction
label={isPaused ? "Resume download" : "Pause download"}
- icon={isPaused ? <IconPlayFilled /> : <IconPauseFilled />}
+ icon={isPaused ? <PlayIcon /> : <PauseIcon />}
onClick={onPause}
className={ACTION_BUTTON_CLASS}
/>
diff --git a/apps/mirai-gui/client/src/features/local-models/components/model-card/model-card-row.tsx b/apps/mirai-gui/client/src/features/local-models/components/model-card/model-card-row.tsx
index 129f59528..bcfcf4bed 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/model-card/model-card-row.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/model-card/model-card-row.tsx
@@ -2,7 +2,7 @@ import type { KeyboardEvent } from "react";
import { Button, DataInteractive } from "@headlessui/react";
import { Trash2 } from "lucide-react";
import { twMerge } from "tailwind-merge";
-import { IconCheckStroke } from "@/components/icons/check-stroke-icon";
+import { CheckIcon } from "@/components/icons/check-icon";
import { Tooltip } from "@/components/ui/tooltip";
import { Text } from "@/components/ui/typography";
import type { ModelCardProps } from "./types";
@@ -31,7 +31,7 @@ export function ModelCardRow({
<DataInteractive
as="div"
className={twMerge(
- "relative py-2.5 transition-colors duration-150",
+ "relative rounded-xl bg-surface-soft py-3.5 transition-colors duration-150 ease-out",
isDownloaded && "cursor-pointer hover:bg-surface-tertiary outline-hidden data-[focus]:shadow-focus",
isError && "bg-danger-bg",
)}
@@ -52,36 +52,36 @@ export function ModelCardRow({
<div
className={twMerge(
"grid gap-3 pl-4 pr-3 items-center",
- compact ? "grid-cols-[minmax(0,1fr)_auto]" : "grid-cols-[minmax(0,1fr)_80px_200px_120px]",
+ compact ? "grid-cols-[minmax(0,1fr)_auto]" : "grid-cols-[minmax(0,1fr)_128px_64px_96px]",
)}
>
<ModelHeading name={name} logo={logo} />
{!compact && (
- <div className="text-left">
- {size && (
+ <div className="text-left min-w-0">
+ {parameters && (
<Text
as="span"
color="muted"
opticalSize={14}
- className="text-[13px] font-[450] leading-[1.3] tabular-nums"
+ className="text-[13px] font-[450] leading-[1.3] truncate block"
>
- {size}
+ {parameters}
</Text>
)}
</div>
)}
{!compact && (
- <div className="text-left min-w-0">
- {parameters && (
+ <div className="text-left">
+ {size && (
<Text
as="span"
color="muted"
opticalSize={14}
- className="text-[13px] font-[450] leading-[1.3] truncate block"
+ className="text-[13px] font-[450] leading-[1.3] tabular-nums"
>
- {parameters}
+ {size}
</Text>
)}
</div>
@@ -110,8 +110,8 @@ export function ModelCardRow({
{isDownloaded && (
<>
<Tooltip content="Downloaded" side="top">
- <div className="flex items-center justify-center h-7 w-7 rounded border-[0.5px] border-border-outlined text-success">
- <IconCheckStroke />
+ <div className="flex items-center justify-center size-7 rounded-full text-success-strong bg-surface-popover shadow-[0_0_0_0.5px_rgb(0_0_0/0.08),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)]">
+ <CheckIcon />
</div>
</Tooltip>
<Button
@@ -122,7 +122,7 @@ export function ModelCardRow({
event.stopPropagation();
onDelete?.(event);
}}
- className="flex items-center justify-center h-7 w-7 rounded cursor-pointer text-text-muted hover:text-danger bg-transparent hover:border-border-outlined-hover border-[0.5px] border-border-outlined outline-hidden data-[focus]:shadow-focus"
+ className="flex items-center justify-center size-7 rounded-full cursor-pointer text-text-muted bg-surface-popover shadow-[0_0_0_0.5px_rgb(0_0_0/0.08),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_0_0_0.5px_rgb(255_255_255/0.1)] transition-colors duration-150 ease-out hover:bg-danger-bg hover:text-danger outline-hidden data-[focus]:shadow-focus"
>
<Trash2 size={14} />
</Button>
@@ -139,8 +139,11 @@ export function ModelCardRow({
{isDownloading && (
<div className="mt-2.5 pl-4 pr-3">
- <div className="h-0.5 bg-border-default rounded overflow-clip">
- <div className="h-full bg-primary transition-[width] duration-200" style={{ width: `${progress}%` }} />
+ <div className="h-1 bg-border-default rounded-full overflow-clip">
+ <div
+ className="h-full origin-left bg-primary transition-transform duration-200 ease-out motion-reduce:transition-none"
+ style={{ transform: `scaleX(${progress / 100})` }}
+ />
</div>
</div>
)}
diff --git a/apps/mirai-gui/client/src/features/local-models/components/model-card/model-heading.tsx b/apps/mirai-gui/client/src/features/local-models/components/model-card/model-heading.tsx
index 4a3d62c75..29f12efd6 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/model-card/model-heading.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/model-card/model-heading.tsx
@@ -1,3 +1,4 @@
+import { splitModelName } from "@/components/model-name";
import type { ReactNode } from "react";
import { Text } from "@/components/ui/typography";
@@ -10,8 +11,11 @@ export function ModelHeading({ name, logo }: ModelHeadingProps) {
return (
<div className="flex items-center gap-3 min-w-0">
<span className="shrink-0 flex items-center justify-center w-4 h-4 [&>svg]:w-4 [&>svg]:h-4">{logo}</span>
- <Text as="span" size="sm" color="primary" opticalSize={14} className="truncate leading-[1.5] font-[450]">
- {name}
+ <Text as="span" size="sm" color="primary" opticalSize={14} className="min-w-0 leading-[1.5] font-[450]">
+ {/* The quantization has its own column here, so the name stands alone. */}
+ <span className="block truncate" title={name}>
+ {splitModelName(name).base}
+ </span>
</Text>
</div>
);
diff --git a/apps/mirai-gui/client/src/features/local-models/components/model-table.tsx b/apps/mirai-gui/client/src/features/local-models/components/model-table.tsx
index d89400750..65829f3d2 100644
--- a/apps/mirai-gui/client/src/features/local-models/components/model-table.tsx
+++ b/apps/mirai-gui/client/src/features/local-models/components/model-table.tsx
@@ -1,3 +1,4 @@
+import { twMerge } from "tailwind-merge";
import type { ReactNode } from "react";
export type ModelTableProps = {
@@ -6,9 +7,9 @@ export type ModelTableProps = {
compact?: boolean;
};
-const HEADER_CELL_CLS = "text-[11px] font-medium uppercase tracking-[0.06em] text-text-muted";
+const HEADER_CELL_CLS = "text-[13px] font-[500] leading-[1.3] text-text-muted whitespace-nowrap truncate";
-const GRID_TEMPLATE = "grid grid-cols-[minmax(0,1fr)_80px_200px_120px] gap-3 pl-4 pr-3";
+const GRID_TEMPLATE = "grid grid-cols-[minmax(0,1fr)_128px_64px_96px] gap-3 pl-4 pr-3";
const GRID_TEMPLATE_COMPACT = "grid grid-cols-[minmax(0,1fr)_auto] gap-3 pl-4 pr-3";
export function ModelTable({ title, children, compact = false }: ModelTableProps) {
@@ -17,16 +18,16 @@ export function ModelTable({ title, children, compact = false }: ModelTableProps
return (
<div className="flex flex-col gap-2">
- <div className={`${gridTemplate} pb-1`}>
+ {/* The heading starts at the cards' edge, like the settings section headings; the other
+ columns are sized from the right, so they still sit over the rows' values. */}
+ <div className={twMerge(gridTemplate, "pb-1 pl-1")}>
<span className={HEADER_CELL_CLS}>{firstHeader}</span>
- {!compact && <span className={HEADER_CELL_CLS}>Size</span>}
{!compact && <span className={HEADER_CELL_CLS}>Quantization</span>}
+ {!compact && <span className={HEADER_CELL_CLS}>Size</span>}
<span aria-hidden />
</div>
- <div className="rounded-md border-[0.5px] border-border-default overflow-clip divide-y-[0.5px] divide-border-default bg-surface-elevated">
- {children}
- </div>
+ <div className="flex flex-col gap-2">{children}</div>
</div>
);
}
diff --git a/apps/mirai-gui/client/src/features/local-models/hooks/use-download-manager.ts b/apps/mirai-gui/client/src/features/local-models/hooks/use-download-manager.tsx
similarity index 78%
rename from apps/mirai-gui/client/src/features/local-models/hooks/use-download-manager.ts
rename to apps/mirai-gui/client/src/features/local-models/hooks/use-download-manager.tsx
index ba234d1f8..48e8b2b39 100644
--- a/apps/mirai-gui/client/src/features/local-models/hooks/use-download-manager.ts
+++ b/apps/mirai-gui/client/src/features/local-models/hooks/use-download-manager.tsx
@@ -1,3 +1,4 @@
+import { InlineModelName } from "@/components/model-name";
import { useToast } from "@/components/ui/toast/use-toast";
import type { PlatformModel } from "@/types/models";
import { useCallback } from "react";
@@ -6,8 +7,8 @@ import { modelDownloadPhases } from "@/types/model-manager";
import { getPlatform } from "@/platform/platform-singleton";
const failureCopy = {
- start: (name: string) => `Failed to start download for ${name}`,
- resume: (name: string) => `Failed to resume ${name}`,
+ start: "Couldn't start downloading",
+ resume: "Couldn't resume",
} as const;
const errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e));
@@ -33,7 +34,12 @@ export const useDownloadManager = () => {
} catch (e) {
const error = errorText(e);
updateModelState(model.repoId, { phase: modelDownloadPhases.error, error });
- toast.error(`${failureCopy[action](model.name)}: ${error}`);
+ toast.error(
+ <>
+ {failureCopy[action]} <InlineModelName name={model.name} />
+ </>,
+ { description: error },
+ );
}
},
[toast],
@@ -47,7 +53,12 @@ export const useDownloadManager = () => {
try {
await getPlatform().models.pauseDownload(model.repoId);
} catch (e) {
- toast.error(`Failed to pause ${model.name}: ${errorText(e)}`);
+ toast.error(
+ <>
+ Couldn't pause <InlineModelName name={model.name} />
+ </>,
+ { description: errorText(e) },
+ );
}
},
[toast],
@@ -60,7 +71,12 @@ export const useDownloadManager = () => {
} catch (e) {
const error = errorText(e);
useModelsStore.getState().updateModelState(model.repoId, { phase: modelDownloadPhases.error, error });
- toast.error(`Failed to cancel ${model.name}: ${error}`);
+ toast.error(
+ <>
+ Couldn't cancel <InlineModelName name={model.name} />
+ </>,
+ { description: error },
+ );
}
},
[toast],
diff --git a/apps/mirai-gui/client/src/features/local-models/lib/view.ts b/apps/mirai-gui/client/src/features/local-models/lib/view.ts
index 1fc0162d2..3dc6be24a 100644
--- a/apps/mirai-gui/client/src/features/local-models/lib/view.ts
+++ b/apps/mirai-gui/client/src/features/local-models/lib/view.ts
@@ -41,7 +41,10 @@ export function formatParamRange(min?: number, max?: number): string | undefined
export function formatQuantization(model: { quantization?: string | null; quantizationBits?: number }): string {
if (!model.quantization) return "Unquantized";
- const method = model.quantization.toUpperCase();
+ // Mirai's own quantizations read as "Mirai M" / "Mirai L", like the model menus; others keep
+ // their upper-case method name.
+ const mirai = /^mirai-(\w+)$/i.exec(model.quantization);
+ const method = mirai?.[1] ? `Mirai ${mirai[1].toUpperCase()}` : model.quantization.toUpperCase();
return typeof model.quantizationBits === "number" ? `${method} · ${model.quantizationBits}-bit` : method;
}
@@ -127,21 +130,22 @@ export function buildFamiliesView(params: {
return filtered.sort((a, b) => a.familyName.localeCompare(b.familyName));
}
- // Families with a downloaded model first, by most recent install; then the rest
- // by family ordering (Llama-3 above Llama-2, Qwen3 above Qwen-2, etc).
- const active: FamilyEntry[] = [];
- const others: FamilyEntry[] = [];
- for (const entry of filtered) {
- if (entry.lastActiveAt > 0) {
- active.push(entry);
- } else {
- others.push(entry);
- }
- }
- active.sort((a, b) => b.lastActiveAt - a.lastActiveAt || a.familyName.localeCompare(b.familyName));
+ // A fixed order: Qwen first, then LFM, then Glimmer, then anything else. Within one line, the
+ // newest version first (Qwen3.8 above Qwen3.6 above Qwen3.5), whether or not it is downloaded.
const compareModels = createNewestTextModelComparator();
- others.sort((a, b) => compareModels(a.representative, b.representative));
- return [...active, ...others];
+ return filtered.sort(
+ (a, b) =>
+ familyRank(a.familyName) - familyRank(b.familyName) ||
+ b.familyName.localeCompare(a.familyName, undefined, { numeric: true }) ||
+ compareModels(a.representative, b.representative),
+ );
+}
+
+const FAMILY_ORDER = [/^qwen/i, /^lfm/i, /glimmer/i];
+
+function familyRank(familyName: string): number {
+ const rank = FAMILY_ORDER.findIndex((pattern) => pattern.test(familyName));
+ return rank === -1 ? FAMILY_ORDER.length : rank;
}
export type FamilyDetailView = {
@@ -167,13 +171,9 @@ export function buildFamilyDetailView(params: {
const haystack = `${model.name} ${formatQuantization(model)}`.toLowerCase();
if (!haystack.includes(searchLower)) continue;
}
- const phase = modelPhasesById[model.repoId];
- const isActive =
- phase === modelDownloadPhases.downloaded ||
- phase === modelDownloadPhases.downloading ||
- phase === modelDownloadPhases.paused ||
- phase === modelDownloadPhases.error;
- if (isActive) installed.push(model);
+ // Only a finished download is usable, so only it moves up to Downloaded; one still downloading,
+ // paused or failed stays in Available, where its row shows the progress.
+ if (modelPhasesById[model.repoId] === modelDownloadPhases.downloaded) installed.push(model);
else available.push(model);
}
diff --git a/apps/mirai-gui/client/src/features/settings/components/about-tab.tsx b/apps/mirai-gui/client/src/features/settings/components/about-tab.tsx
index 582ce8147..d511f07ca 100644
--- a/apps/mirai-gui/client/src/features/settings/components/about-tab.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/about-tab.tsx
@@ -1,20 +1,23 @@
-import { ChevronRight, Heart } from "lucide-react";
+import { ArrowUpRight, ChevronRight } from "lucide-react";
+import { Link } from "@tanstack/react-router";
+import { platformInfo } from "@/platform/platform-info";
+import { UzuCat } from "@/components/uzu-cat";
+import { SettingGroup } from "./general/setting-row";
import { Button } from "@/components/ui/button";
-const links = [
- {
- title: "Website",
- url: "https://trymirai.com/",
- },
+const connectLinks = [
+ { title: "Website", url: "https://trymirai.com/" },
+ { title: "About us", url: "https://trymirai.com/about-us" },
{ title: "GitHub", url: "https://github.com/trymirai" },
- { title: "Vision", url: "https://trymirai.com/about-us" },
- { title: "Docs", url: "https://docs.trymirai.com/" },
+ { title: "Hugging Face", url: "https://huggingface.co/trymirai" },
+ { title: "Discord", url: "https://discord.gg/trymirai" },
];
-const productLinks = [
+const moreLinks = [
+ { title: "Metrics", description: "uzu against MLX, MTPLX and llama.cpp.", url: "https://trymirai.com/metrics" },
{
- title: "Mirai platform",
- description: "A web console for setting up the SDK in your product.",
- url: "https://platform.trymirai.com",
+ title: "Models",
+ description: "25 Mirai checkpoints with per-device benchmarks.",
+ url: "https://trymirai.com/models",
},
{
title: "Command-line interface",
@@ -26,6 +29,7 @@ const productLinks = [
description: "Runs models on the hardware they were built for.",
url: "https://github.com/trymirai/uzu",
},
+ { title: "Careers", description: "Explore open positions.", url: "https://trymirai.com/careers" },
];
const legalLinks = [
@@ -39,90 +43,91 @@ const legalLinks = [
},
];
-export default function AboutTab() {
+function LinkRow({ title, description, url }: { title: string; description?: string; url: string }) {
return (
- <div className="h-full flex flex-col justify-between">
- <div className="flex flex-col">
- <div className="flex flex-col gap-4 px-5 lg:max-w-[800px] mx-auto w-full">
- <Heart className="w-6 h-6 text-blue" />
- <div className="flex flex-wrap items-center justify-between gap-4">
- <h3 className="text-[18px] font-medium leading-[130%] tracking-[0.2px] text-label-title">
- Built by a team that shares a vision for <br />
- accessible and powerful local AI.
- </h3>
- <Button
- size="sm"
- href="https://discord.gg/trymirai"
- target="_blank"
- className="bg-blue/10 text-blue hover:bg-blue/20 active:bg-blue/25"
- >
- Join our Discord
- </Button>
- </div>
- </div>
- <div className="mt-5 h-[1px] bg-cell-border" />
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="group flex items-center justify-between gap-4 px-4 py-3.5 transition-colors duration-150 ease-out hover:bg-surface-tertiary outline-hidden focus-visible:shadow-focus"
+ >
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="text-[14px] font-[500] leading-[1.35] text-label-title">{title}</span>
+ {description ? (
+ <span className="text-[13px] leading-[1.45] text-label-muted text-pretty">{description}</span>
+ ) : null}
+ </span>
+ <ArrowUpRight
+ aria-hidden
+ className="size-4 shrink-0 text-label-muted transition-[color,translate] duration-150 ease-out group-hover:text-label-title group-hover:translate-x-px group-hover:-translate-y-px"
+ />
+ </a>
+ );
+}
- <div className="grid grid-cols-4 lg:max-w-[800px] mx-auto w-full">
- {links.map((link) => (
- <a
- key={link.url}
- href={link.url}
- target="_blank"
- rel="noopener noreferrer"
- className="hover:bg-bg-sub flex items-center justify-between px-5 py-5 border-r last:border-r-0 border-cell-border"
- >
- <h4 className="min-w-0 text-[15px] font-[350] leading-[150%] text-label-title overflow-clip">
- {link.title}
- </h4>
- <ChevronRight className="w-[14px] h-[14px] text-label-muted" />
- </a>
- ))}
- </div>
+/** Opens the first-run welcome again, to see what a new install shows. */
+function WelcomeRow() {
+ return (
+ <Link
+ to="/welcome"
+ className="group flex items-center justify-between gap-4 px-4 py-3.5 transition-colors duration-150 ease-out hover:bg-surface-tertiary outline-hidden focus-visible:shadow-focus"
+ >
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="text-[14px] font-[500] leading-[1.35] text-label-title">Welcome screen</span>
+ <span className="text-[13px] leading-[1.45] text-label-muted text-pretty">What a new install shows first.</span>
+ </span>
+ <ChevronRight
+ aria-hidden
+ className="size-4 shrink-0 text-label-muted transition-[color,translate] duration-150 ease-out group-hover:text-label-title group-hover:translate-x-px"
+ />
+ </Link>
+ );
+}
- <div className="mb-5 h-[1px] bg-cell-border" />
+export default function AboutTab() {
+ return (
+ <div className="flex flex-col gap-7 pb-8">
+ <div className="flex flex-col items-center text-center">
+ <div className="mb-1">
+ <UzuCat state="welcome" size={96} className="text-text-primary" label="uzu, saying hello" />
+ </div>
+ <h3 className="max-w-[440px] text-[15px] font-[500] leading-[1.35] text-label-title text-balance">
+ Built by a small, senior team building the full on-device stack to achieve realtime local intelligence.
+ </h3>
+ <Button
+ size="sm"
+ href="https://x.com/trymirai"
+ target="_blank"
+ className="mt-5 rounded-full bg-blue/10 text-blue hover:bg-blue/20 active:bg-blue/25"
+ >
+ Connect with us on X
+ </Button>
</div>
- <div>
- <h3 className="lg:max-w-[800px] mx-auto w-full text-xs font-mono leading-[130%] text-label-muted px-5">
- Our products
- </h3>
- <div className="flex flex-col w-full mt-3">
- {productLinks.map((link, index) => (
- <div key={link.url} className="w-full">
- <a
- href={link.url}
- target="_blank"
- rel="noopener noreferrer"
- className="lg:max-w-[800px] mx-auto w-full hover:bg-bg-sub flex items-center justify-between px-5 py-5"
- >
- <div className="flex flex-col gap-1">
- <h4 className="text-[15px] font-[350] leading-[150%] text-label-title overflow-clip">{link.title}</h4>
- <p className="text-[13px] font-[350] leading-[150%] text-label-muted">{link.description}</p>
- </div>
+ <SettingGroup title="Connect">
+ {connectLinks.map((link) => (
+ <LinkRow key={link.url} title={link.title} url={link.url} />
+ ))}
+ </SettingGroup>
- <ChevronRight className="w-[14px] h-[14px] text-label-muted" />
- </a>
- {index < productLinks.length - 1 && <div className="h-[1px] bg-cell-border" />}
- </div>
- ))}
- </div>
+ <SettingGroup title="More from Mirai Labs">
+ {moreLinks.map((link) => (
+ <LinkRow key={link.url} title={link.title} description={link.description} url={link.url} />
+ ))}
+ </SettingGroup>
- <div className="h-[1px] bg-cell-border" />
- <div className="grid grid-cols-2 lg:max-w-[800px] mx-auto w-full">
- {legalLinks.map((link) => (
- <a
- key={link.url}
- href={link.url}
- target="_blank"
- rel="noopener noreferrer"
- className="hover:bg-bg-sub flex items-center justify-between px-5 py-5 border-r last:border-r-0 border-cell-border"
- >
- <h4 className="text-[15px] font-[350] leading-[150%] text-label-title">{link.title}</h4>
- <ChevronRight className="w-[14px] h-[14px] text-label-muted" />
- </a>
- ))}
- </div>
- </div>
+ <SettingGroup title="Legal">
+ {legalLinks.map((link) => (
+ <LinkRow key={link.url} title={link.title} url={link.url} />
+ ))}
+ </SettingGroup>
+
+ {/* The welcome belongs to the desktop app, which is where it appears on first launch. */}
+ {platformInfo.features.localModelDownloads ? (
+ <SettingGroup title="Preview">
+ <WelcomeRow />
+ </SettingGroup>
+ ) : null}
</div>
);
}
diff --git a/apps/mirai-gui/client/src/features/settings/components/general-tab.test.tsx b/apps/mirai-gui/client/src/features/settings/components/general-tab.test.tsx
index cf148fa84..1af6cff08 100644
--- a/apps/mirai-gui/client/src/features/settings/components/general-tab.test.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/general-tab.test.tsx
@@ -172,7 +172,7 @@ it("updates and persists chat width from General settings", () => {
expect(screen.getByRole("radio", { name: "Medium" }).getAttribute("aria-checked")).toBe("true");
for (const [label, width] of [
- ["Narrow", 800],
+ ["Narrow", 768],
["Wide", 1200],
["Medium", 1000],
] as const) {
diff --git a/apps/mirai-gui/client/src/features/settings/components/general-tab.tsx b/apps/mirai-gui/client/src/features/settings/components/general-tab.tsx
index 5d536d1e9..d1e0b28ab 100644
--- a/apps/mirai-gui/client/src/features/settings/components/general-tab.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/general-tab.tsx
@@ -1,16 +1,16 @@
import GlobalInstructions from "@/features/chat-history/components/global-instructions";
+import { useGlobalInstructionsStore } from "@/stores/use-global-instructions-store";
import { Toggle } from "@/components/ui/toggle";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { platformInfo } from "@/platform/platform-info";
import { useAppStore } from "@/stores/use-app-store";
-import { useGlobalInstructionsStore } from "@/stores/use-global-instructions-store";
import { useSettingsStore } from "@/stores/use-settings-store";
import { useEffect } from "react";
import { AnalyticsSetting } from "./general/analytics-setting";
import { AutoEjectSetting } from "./general/auto-eject-setting";
import { CliInstallSetting } from "./general/cli-install-setting";
import { DataSettings } from "./general/data-settings";
-import { SettingDivider, SettingRow } from "./general/setting-row";
+import { SettingGroup, SettingRow } from "./general/setting-row";
import { ThemeSelector } from "./general/theme-selector";
export default function GeneralTab() {
@@ -26,35 +26,27 @@ export default function GeneralTab() {
setAutoEjectMinutes,
} = useSettingsStore();
- const instructions = useGlobalInstructionsStore((s) => s.instructions);
- const loadInstructions = useGlobalInstructionsStore((s) => s.loadInstructions);
- const saveInstructions = useGlobalInstructionsStore((s) => s.saveInstructions);
-
const theme = useAppStore((s) => s.theme);
const setTheme = useAppStore((s) => s.setTheme);
const chatWidth = useAppStore((s) => s.chatWidth);
const setChatWidth = useAppStore((s) => s.setChatWidth);
+ const instructions = useGlobalInstructionsStore((s) => s.instructions);
+ const loadInstructions = useGlobalInstructionsStore((s) => s.loadInstructions);
+ const saveInstructions = useGlobalInstructionsStore((s) => s.saveInstructions);
useEffect(() => {
- loadInstructions();
fetchSettings();
- }, [loadInstructions, fetchSettings]);
+ loadInstructions();
+ }, [fetchSettings, loadInstructions]);
return (
- <div className="h-full flex flex-col">
- <div className="flex flex-col gap-5 pb-5">
- <div className="flex flex-col gap-2 px-5 lg:max-w-[800px] mx-auto w-full">
- <GlobalInstructions instructions={instructions} onSave={saveInstructions} />
- </div>
-
- <SettingDivider />
+ <div className="flex flex-col gap-7 pb-8">
+ <SettingGroup title="Appearance">
<SettingRow
title="Theme"
description="Choose an appearance or follow your system settings"
control={<ThemeSelector value={theme} onChange={setTheme} />}
/>
-
- <SettingDivider />
<SettingRow
title="Chat width"
description="Maximum width of messages, the message box, and chat history. Adapts to fit smaller windows."
@@ -65,7 +57,7 @@ export default function GeneralTab() {
value={String(chatWidth)}
onChange={(value) => setChatWidth(Number(value))}
options={[
- { value: "800", label: "Narrow" },
+ { value: "768", label: "Narrow" },
{ value: "1000", label: "Medium" },
{ value: "1200", label: "Wide" },
]}
@@ -73,10 +65,9 @@ export default function GeneralTab() {
</div>
}
/>
+ </SettingGroup>
- <CliInstallSetting />
-
- <SettingDivider />
+ <SettingGroup title="Models">
<SettingRow
title="Let models name chats via tool call"
description="Enabled by default for supported models with 2B or more parameters. Otherwise, the same model is asked to name the chat separately."
@@ -88,24 +79,31 @@ export default function GeneralTab() {
/>
}
/>
-
{platformInfo.features.autoEject && (
- <>
- <SettingDivider />
- <AutoEjectSetting
- autoEjectEnabled={autoEjectEnabled}
- autoEjectMinutes={autoEjectMinutes}
- setAutoEjectEnabled={setAutoEjectEnabled}
- setAutoEjectMinutes={setAutoEjectMinutes}
- />
- </>
+ <AutoEjectSetting
+ autoEjectEnabled={autoEjectEnabled}
+ autoEjectMinutes={autoEjectMinutes}
+ setAutoEjectEnabled={setAutoEjectEnabled}
+ setAutoEjectMinutes={setAutoEjectMinutes}
+ />
)}
+ <CliInstallSetting />
+ </SettingGroup>
+
+ {/* What the model is told in every chat. Its own card, so it sits under a group heading
+ rather than inside a group. */}
+ <section className="flex flex-col gap-2">
+ <h3 className="px-1 text-[13px] font-[500] leading-[1.3] text-label-muted">Instructions</h3>
+ <GlobalInstructions instructions={instructions} onSave={saveInstructions} />
+ </section>
- <SettingDivider />
+ <SettingGroup title="Privacy">
<AnalyticsSetting enabled={analyticsEnabled} onChange={setAnalyticsEnabled} />
+ </SettingGroup>
+ <SettingGroup title="Data">
<DataSettings />
- </div>
+ </SettingGroup>
</div>
);
}
diff --git a/apps/mirai-gui/client/src/features/settings/components/general/auto-eject-setting.tsx b/apps/mirai-gui/client/src/features/settings/components/general/auto-eject-setting.tsx
index 5c18f87f8..9ea6ccb0e 100644
--- a/apps/mirai-gui/client/src/features/settings/components/general/auto-eject-setting.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/general/auto-eject-setting.tsx
@@ -39,7 +39,7 @@ export function AutoEjectSetting({
inputMode="numeric"
value={minutesInput}
className={twMerge(
- "max-w-[72px] px-2 py-1 text-[13px] border border-cell-border bg-background placeholder:text-label-muted rounded-[8px] focus:outline-hidden",
+ "h-8 w-[72px] px-3 text-[13px] tabular-nums text-text-primary rounded-lg border-[0.5px] border-transparent bg-control-fill placeholder:text-label-muted outline-hidden transition-colors duration-150 ease-out focus:border-border-outlined",
!autoEjectEnabled ? "opacity-60 cursor-not-allowed" : "",
)}
onChange={(e) => {
diff --git a/apps/mirai-gui/client/src/features/settings/components/general/cli-install-setting.tsx b/apps/mirai-gui/client/src/features/settings/components/general/cli-install-setting.tsx
index 6e4477ea7..870334438 100644
--- a/apps/mirai-gui/client/src/features/settings/components/general/cli-install-setting.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/general/cli-install-setting.tsx
@@ -3,7 +3,7 @@ import { getPlatform } from "@/platform/platform-singleton";
import { platformInfo } from "@/platform/platform-info";
import { Button } from "@/components/ui/button";
import { useEffect, useState } from "react";
-import { SettingDivider, SettingRow } from "./setting-row";
+import { SettingRow } from "./setting-row";
export function CliInstallSetting() {
const [isInstalling, setIsInstalling] = useState(false);
@@ -38,7 +38,6 @@ export function CliInstallSetting() {
return (
<>
- <SettingDivider />
<SettingRow
title="Command line tool"
description="Install the mirai command to use Mirai from the terminal"
diff --git a/apps/mirai-gui/client/src/features/settings/components/general/data-settings.tsx b/apps/mirai-gui/client/src/features/settings/components/general/data-settings.tsx
index a21bad6a2..222142a17 100644
--- a/apps/mirai-gui/client/src/features/settings/components/general/data-settings.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/general/data-settings.tsx
@@ -6,7 +6,7 @@ import { exportAllChatsZip } from "@/features/chat/services/export-chats";
import { platformInfo } from "@/platform/platform-info";
import { useSettingsStore } from "@/stores/use-settings-store";
import { ClearDataDialog } from "../clear-data-dialog";
-import { SettingDivider, SettingRow } from "./setting-row";
+import { SettingRow } from "./setting-row";
export function DataSettings() {
const [isExporting, setIsExporting] = useState(false);
@@ -40,7 +40,6 @@ export function DataSettings() {
return (
<>
- <SettingDivider />
<SettingRow
title="Export all your chats"
description="As Markdown files in a ZIP archive"
@@ -59,7 +58,6 @@ export function DataSettings() {
/>
{platformInfo.features.logExport && (
<>
- <SettingDivider />
<SettingRow
title="Export logs"
description="Save the current Mirai log file for debugging"
@@ -78,7 +76,6 @@ export function DataSettings() {
/>
</>
)}
- <SettingDivider />
<SettingRow
title="Clear data"
description="Delete chats, models, or logs"
diff --git a/apps/mirai-gui/client/src/features/settings/components/general/setting-row.tsx b/apps/mirai-gui/client/src/features/settings/components/general/setting-row.tsx
index aef9ca95f..100dc9953 100644
--- a/apps/mirai-gui/client/src/features/settings/components/general/setting-row.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/general/setting-row.tsx
@@ -1,7 +1,16 @@
import type { ReactNode } from "react";
-export function SettingDivider() {
- return <div className="h-[1px] bg-cell-border" />;
+/** A titled group of settings: a small heading over one soft card, rows split by hairlines. The
+ * card does not clip, so menus opened from a row (the theme picker) can spill past it. */
+export function SettingGroup({ title, children }: { title?: string; children: ReactNode }) {
+ return (
+ <section className="flex flex-col gap-2">
+ {title ? <h3 className="px-1 text-[13px] font-[500] leading-[1.3] text-label-muted">{title}</h3> : null}
+ <div className="rounded-2xl bg-surface-soft divide-y-[0.5px] divide-border-default [&>*:first-child]:rounded-t-2xl [&>*:last-child]:rounded-b-2xl">
+ {children}
+ </div>
+ </section>
+ );
}
export function SettingRow({
@@ -16,11 +25,11 @@ export function SettingRow({
children?: ReactNode;
}) {
return (
- <div className="px-5 lg:max-w-[800px] mx-auto w-full">
- <div className="flex items-center justify-between gap-3">
- <div className="flex flex-col gap-1">
- <h4 className="text-[15px] font-[350] leading-[150%] text-label-title overflow-clip">{title}</h4>
- <p className="text-[13px] text-label-muted">{description}</p>
+ <div className="px-4 py-3.5">
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <h4 className="text-[14px] font-[500] leading-[1.35] text-label-title">{title}</h4>
+ <p className="text-[13px] leading-[1.45] text-label-muted text-pretty">{description}</p>
</div>
{control}
</div>
diff --git a/apps/mirai-gui/client/src/features/settings/components/general/theme-selector.tsx b/apps/mirai-gui/client/src/features/settings/components/general/theme-selector.tsx
index c21478062..50936dd19 100644
--- a/apps/mirai-gui/client/src/features/settings/components/general/theme-selector.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/general/theme-selector.tsx
@@ -21,7 +21,7 @@ export const ThemeSelector = ({ value, onChange }: Props) => {
<ListboxButton
type="button"
aria-label={`Theme: ${label}`}
- className="flex h-8 min-w-[110px] items-center justify-between gap-3 rounded-md bg-surface-tertiary px-2.5 text-[13px] font-[450] leading-[1.3] text-text-muted outline-hidden hover:bg-control-surface-hover hover:text-text-primary data-[headlessui-state~=open]:bg-control-surface-active data-[headlessui-state~=open]:text-text-primary data-[focus]:bg-control-surface-hover data-[focus]:text-text-primary data-[focus]:shadow-focus"
+ className="flex h-8 min-w-[110px] items-center justify-between gap-3 rounded-full bg-control-fill px-3 text-[13px] font-[450] leading-[1.3] text-text-primary outline-hidden transition-colors duration-150 ease-out hover:bg-control-fill-hover data-[headlessui-state~=open]:bg-control-fill-hover data-[focus]:bg-control-fill-hover data-[focus]:shadow-focus"
>
<span>{label}</span>
<ChevronDown size={16} aria-hidden="true" />
@@ -37,7 +37,7 @@ export const ThemeSelector = ({ value, onChange }: Props) => {
>
<div className="absolute right-0 top-full z-50 origin-top-right pt-1">
<ListboxOptions className="outline-hidden">
- <SelectionPanel className="min-w-[160px] origin-top-right py-1.5">
+ <SelectionPanel className="min-w-[160px] origin-top-right py-1">
<SelectionSection>
{THEMES.map((theme) => (
<ListboxOption key={theme.value} value={theme.value} as={Fragment}>
diff --git a/apps/mirai-gui/client/src/features/settings/components/settings-page.tsx b/apps/mirai-gui/client/src/features/settings/components/settings-page.tsx
index 3aaae5d0e..baca4ae4f 100644
--- a/apps/mirai-gui/client/src/features/settings/components/settings-page.tsx
+++ b/apps/mirai-gui/client/src/features/settings/components/settings-page.tsx
@@ -1,69 +1,46 @@
-import { Link, useSearch } from "@tanstack/react-router";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+import type { CSSProperties } from "react";
import GeneralTab from "./general-tab";
import AboutTab from "./about-tab";
-import { PageHeader } from "@/components/page-header";
-import { Button } from "@/components/ui/button";
-import { twMerge } from "tailwind-merge";
+import { SegmentedControl } from "@/components/ui/segmented-control";
+import { PageScroller, PageTitleBar } from "@/components/page-title-bar";
+import { useAppStore } from "@/stores/use-app-store";
export type SettingsTab = "general" | "about";
+const SECTIONS: { value: SettingsTab; label: string }[] = [
+ { value: "general", label: "General" },
+ { value: "about", label: "About" },
+];
+
+/** Set like the chats page: the title at the top of the column, the two sections as one switch. */
export function SettingsPage() {
const { tab } = useSearch({ from: "/settings" });
- const sections: { key: SettingsTab; label: string }[] = [
- { key: "general", label: "General" },
- { key: "about", label: "About" },
- ];
-
- const tabComponents: Record<SettingsTab, React.ReactNode> = {
- general: <GeneralTab />,
- about: <AboutTab />,
- };
+ const navigate = useNavigate();
+ const chatWidth = useAppStore((s) => s.chatWidth);
return (
- <div className="h-full min-h-0 w-full bg-background text-label-title pt-4">
- <div className="h-full min-h-0 flex flex-col">
- <div className="px-5 shrink-0 z-10 bg-background">
- <PageHeader title={<h1 className="text-[15px] leading-[150%] font-medium mb-4">Settings</h1>} />
- </div>
- <div className="h-[1px] shrink-0 bg-cell-border" />
-
- <div className="lg:hidden px-5 py-4 shrink-0 z-10 bg-background">
- <div className="flex gap-2 overflow-x-auto overscroll-x-contain overscroll-y-auto thin-scrollbar">
- {sections.map((s) => (
- <Link key={s.key} to="/settings" search={{ tab: s.key }} className="flex-shrink-0">
- <Button kind={s.key === tab ? "primary" : "ghost"} size="sm" className="whitespace-nowrap">
- {s.label}
- </Button>
- </Link>
- ))}
- </div>
- </div>
-
- <div className="flex flex-1 min-h-0">
- <aside className="hidden lg:block w-[152px] flex-shrink-0 h-full pt-2 overflow-y-auto thin-scrollbar border-r border-cell-border">
- <nav className="flex flex-col gap-2">
- {sections.map((s) => (
- <Link key={s.key} to="/settings" search={{ tab: s.key }} className="flex px-3">
- <div
- className={`flex items-center gap-3 px-2 py-[6px] w-full rounded-md transition-colors duration-150 ${s.key === tab ? "bg-sidebar-chat-selected" : "hover:bg-sidebar-chat-hover"}`}
- >
- <span className="text-[13px] font-[350] leading-[150%] text-label-title">{s.label}</span>
- </div>
- </Link>
- ))}
- </nav>
- </aside>
-
- <section
- className={twMerge(
- "flex-1 min-w-0 lg:px-0 h-full overflow-y-scroll overscroll-y-contain thin-scrollbar",
- "pt-5 lg:pt-5",
- )}
- >
- {tabComponents[tab]}
- </section>
- </div>
- </div>
+ <div
+ className="h-full min-h-0 w-full bg-background text-label-title"
+ style={{ "--chat-width": `${chatWidth}px` } as CSSProperties}
+ >
+ <PageScroller
+ header={
+ <PageTitleBar className="justify-between">
+ <h1 className="text-[20px] font-[600] leading-[1.2] tracking-[-0.01em] text-label-title">Settings</h1>
+ <SegmentedControl
+ ariaLabel="Settings section"
+ value={tab}
+ onChange={(value) => navigate({ to: "/settings", search: { tab: value as SettingsTab } })}
+ options={SECTIONS}
+ />
+ </PageTitleBar>
+ }
+ >
+ <section key={tab} className="px-5 pt-4 w-full max-w-[calc(var(--chat-width)+2.5rem)] mx-auto animate-uzu-in">
+ {tab === "about" ? <AboutTab /> : <GeneralTab />}
+ </section>
+ </PageScroller>
</div>
);
}
diff --git a/apps/mirai-gui/client/src/features/welcome/welcome-screen.tsx b/apps/mirai-gui/client/src/features/welcome/welcome-screen.tsx
new file mode 100644
index 000000000..3f2b3dc6a
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/welcome/welcome-screen.tsx
@@ -0,0 +1,116 @@
+import { Field, Label } from "@headlessui/react";
+import { InfoIcon } from "@/components/icons/app-icons";
+import { useNavigate } from "@tanstack/react-router";
+import { type CSSProperties, useEffect, useState } from "react";
+import { twMerge } from "tailwind-merge";
+import { UzuCat } from "@/components/uzu-cat";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Tooltip } from "@/components/ui/tooltip";
+import { useMediaQuery } from "@/hooks/use-media-query";
+import { useSettingsStore } from "@/stores/use-settings-store";
+import { markWelcomeSeen } from "./welcome-seen";
+
+// Each part comes into focus a beat after the one above it, out of a deep blur: a screen seen once
+// can take its time (about 1.4 s in all). Under reduced motion the entrance is off.
+const STEP_MS = 120;
+const arrive = (step: number): CSSProperties => ({ animationDelay: `${step * STEP_MS}ms` });
+const LEAVE_MS = 260;
+
+/**
+ * The first thing a new install shows, before the app itself: the cat says hello, what Mirai is
+ * in one line, and the way in. Usage data sharing is the real setting, so it can be
+ * decided here or later in Settings.
+ */
+export function WelcomeScreen() {
+ const navigate = useNavigate();
+ const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
+ const analyticsEnabled = useSettingsStore((s) => s.analyticsEnabled);
+ const setAnalyticsEnabled = useSettingsStore((s) => s.setAnalyticsEnabled);
+ const fetchSettings = useSettingsStore((s) => s.fetch);
+ const [eager, setEager] = useState(false);
+ const [leaving, setLeaving] = useState(false);
+
+ useEffect(() => {
+ void fetchSettings();
+ }, [fetchSettings]);
+
+ const getStarted = () => {
+ if (leaving) return;
+ markWelcomeSeen();
+ if (reducedMotion) {
+ void navigate({ to: "/", replace: true });
+ return;
+ }
+ setLeaving(true);
+ window.setTimeout(() => void navigate({ to: "/", replace: true }), LEAVE_MS);
+ };
+
+ return (
+ <div
+ data-tauri-drag-region
+ className="flex h-full w-full items-center justify-center overflow-y-auto bg-background px-6 py-16"
+ >
+ <div
+ className={twMerge(
+ "flex w-full max-w-[520px] flex-col items-center text-center transition-[opacity,scale,filter] ease-[cubic-bezier(0.32,0.72,0,1)]",
+ leaving && "scale-[0.98] opacity-0 blur-[6px]",
+ )}
+ style={{ transitionDuration: `${LEAVE_MS}ms` }}
+ >
+ <div className="mb-4 animate-uzu-welcome-cat" style={arrive(0)}>
+ <UzuCat
+ state={eager ? "ready" : "welcome"}
+ size={128}
+ className="text-text-primary"
+ label="uzu, saying hello"
+ />
+ </div>
+
+ <h1
+ className="text-[32px] font-[620] leading-[1.1] tracking-[-0.025em] text-text-primary text-balance animate-uzu-welcome"
+ style={arrive(1)}
+ >
+ Welcome to Mirai
+ </h1>
+ <p
+ className="mt-3 text-[16px] leading-[1.5] text-text-secondary text-pretty animate-uzu-welcome"
+ style={arrive(2)}
+ >
+ Try the full private and local AI potential of your Mac
+ </p>
+
+ <button
+ type="button"
+ // The first thing to press: Enter goes straight in.
+ autoFocus
+ onClick={getStarted}
+ // Only a pointer makes the cat eager: the button has focus from the start, and switching the
+ // cat's pose then would break its greeting mid-entrance.
+ onPointerEnter={() => setEager(true)}
+ onPointerLeave={() => setEager(false)}
+ className="mt-10 h-11 min-w-[220px] rounded-full bg-primary px-7 text-[15px] font-[500] text-primary-contrast outline-hidden transition-[background-color,scale] duration-150 ease-out hover:bg-primary-hover active:scale-[0.96] focus-visible:shadow-focus animate-uzu-welcome"
+ style={arrive(3)}
+ >
+ Get started
+ </button>
+
+ <Field className="mt-5 flex items-center gap-2 animate-uzu-welcome" style={arrive(4)}>
+ <Checkbox checked={analyticsEnabled} onChange={(checked) => void setAnalyticsEnabled(checked)} />
+ <Label className="cursor-pointer select-none text-[13px] text-text-muted">Share anonymous usage data</Label>
+ <Tooltip
+ content="Model activity, performance measurements, OS/CPU/RAM, app versions, and a temporary session ID. You can change this later in Settings."
+ side="top"
+ >
+ <span
+ tabIndex={0}
+ aria-label="What is shared"
+ className="flex size-5 cursor-help items-center justify-center rounded-full text-text-muted outline-hidden transition-colors duration-150 ease-out hover:text-text-primary focus-visible:shadow-focus"
+ >
+ <InfoIcon size={16} aria-hidden />
+ </span>
+ </Tooltip>
+ </Field>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/mirai-gui/client/src/features/welcome/welcome-seen.ts b/apps/mirai-gui/client/src/features/welcome/welcome-seen.ts
new file mode 100644
index 000000000..378fc4745
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/welcome/welcome-seen.ts
@@ -0,0 +1,19 @@
+// Whether this device has been through the welcome. A per-device first-run flag, so local storage is
+// enough; if it can't be read the welcome is simply shown again, which is harmless.
+const KEY = "mirai.welcome-seen";
+
+export function hasSeenWelcome(): boolean {
+ try {
+ return localStorage.getItem(KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+export function markWelcomeSeen(): void {
+ try {
+ localStorage.setItem(KEY, "1");
+ } catch {
+ // Nothing to do: the welcome shows once more next launch.
+ }
+}
diff --git a/apps/mirai-gui/client/src/hooks/use-global-download-toasts.ts b/apps/mirai-gui/client/src/hooks/use-global-download-toasts.tsx
similarity index 65%
rename from apps/mirai-gui/client/src/hooks/use-global-download-toasts.ts
rename to apps/mirai-gui/client/src/hooks/use-global-download-toasts.tsx
index 4f6ac3549..5fd04ef2e 100644
--- a/apps/mirai-gui/client/src/hooks/use-global-download-toasts.ts
+++ b/apps/mirai-gui/client/src/hooks/use-global-download-toasts.tsx
@@ -1,3 +1,4 @@
+import { InlineModelName } from "@/components/model-name";
import { useToast } from "@/components/ui/toast/use-toast";
import { getPlatform } from "@/platform/platform-singleton";
import { navigationRequestTypes } from "@/platform/platform-client";
@@ -24,13 +25,28 @@ export const useGlobalDownloadToasts = (): void => {
const name = modelName(event.identifier);
switch (event.kind) {
case "done":
- toast.success(`Downloaded ${name}`, { onClick: () => openChatForModel(event.identifier) });
+ toast.success(
+ <>
+ <InlineModelName name={name} /> is ready
+ </>,
+ { onClick: () => openChatForModel(event.identifier) },
+ );
return;
case "error":
- toast.error(`Failed to download ${name}: ${event.error}`);
+ toast.error(
+ <>
+ Couldn't download <InlineModelName name={name} />
+ </>,
+ { description: event.error },
+ );
return;
case "locked":
- toast.info(`${name} download is locked by another process (${event.lockedBy}).`);
+ toast.info(
+ <>
+ <InlineModelName name={name} /> is downloading in another app
+ </>,
+ { description: `Held by ${event.lockedBy}` },
+ );
return;
}
}),
diff --git a/apps/mirai-gui/client/src/hooks/use-held-true.ts b/apps/mirai-gui/client/src/hooks/use-held-true.ts
new file mode 100644
index 000000000..e9fe7ea2f
--- /dev/null
+++ b/apps/mirai-gui/client/src/hooks/use-held-true.ts
@@ -0,0 +1,19 @@
+import { useEffect, useState } from "react";
+
+/**
+ * `value`, except that once true it stays true until it has been false for `holdMs`. For states
+ * that hand off from one task to the next (the answer streams, then the chat is named): without the
+ * hold the gap between them shows as a one-frame flicker of whatever the state controls.
+ */
+export function useHeldTrue(value: boolean, holdMs: number): boolean {
+ const [held, setHeld] = useState(value);
+ useEffect(() => {
+ if (value) {
+ setHeld(true);
+ return;
+ }
+ const timer = setTimeout(() => setHeld(false), holdMs);
+ return () => clearTimeout(timer);
+ }, [value, holdMs]);
+ return value || held;
+}
diff --git a/apps/mirai-gui/client/src/hooks/use-media-query.ts b/apps/mirai-gui/client/src/hooks/use-media-query.ts
index e54777933..4ba76cbcf 100644
--- a/apps/mirai-gui/client/src/hooks/use-media-query.ts
+++ b/apps/mirai-gui/client/src/hooks/use-media-query.ts
@@ -1,11 +1,13 @@
import { useState, useEffect } from "react";
+// Absent in some test environments (jsdom).
+const canMatchMedia = () => typeof window !== "undefined" && typeof window.matchMedia === "function";
+
export function useMediaQuery(query: string): boolean {
- const [matches, setMatches] = useState(() =>
- typeof window !== "undefined" ? window.matchMedia(query).matches : false,
- );
+ const [matches, setMatches] = useState(() => (canMatchMedia() ? window.matchMedia(query).matches : false));
useEffect(() => {
+ if (!canMatchMedia()) return;
const media = window.matchMedia(query);
setMatches(media.matches);
diff --git a/apps/mirai-gui/client/src/hooks/use-native-fullscreen.ts b/apps/mirai-gui/client/src/hooks/use-native-fullscreen.ts
new file mode 100644
index 000000000..378bef2db
--- /dev/null
+++ b/apps/mirai-gui/client/src/hooks/use-native-fullscreen.ts
@@ -0,0 +1,45 @@
+import { useEffect, useState } from "react";
+import { platformInfo } from "@/platform/platform-info";
+
+/**
+ * True while the desktop app is in native full screen, where macOS hides the traffic lights. Asked
+ * of the window itself on every resize: the window's size can't tell, since full screen may keep
+ * the menu bar on screen and so cover less than the display.
+ */
+export function useNativeFullscreen(): boolean {
+ const enabled = platformInfo.features.nativeTitleBar;
+ const [fullscreen, setFullscreen] = useState(false);
+
+ useEffect(() => {
+ if (!enabled) return;
+ let cancelled = false;
+ let unlisten: (() => void) | undefined;
+ let settle: ReturnType<typeof setTimeout> | undefined;
+
+ void import("@tauri-apps/api/window").then(async ({ getCurrentWindow }) => {
+ const appWindow = getCurrentWindow();
+ const update = async () => {
+ const next = await appWindow.isFullscreen();
+ if (!cancelled) setFullscreen(next);
+ };
+ await update();
+ // Resize events arrive while the full-screen animation is still running, so ask again once it
+ // has settled.
+ const stop = await appWindow.onResized(() => {
+ void update();
+ clearTimeout(settle);
+ settle = setTimeout(() => void update(), 700);
+ });
+ if (cancelled) stop();
+ else unlisten = stop;
+ });
+
+ return () => {
+ cancelled = true;
+ clearTimeout(settle);
+ unlisten?.();
+ };
+ }, [enabled]);
+
+ return fullscreen;
+}
diff --git a/apps/mirai-gui/client/src/hooks/use-update-initialization.ts b/apps/mirai-gui/client/src/hooks/use-update-initialization.ts
index 5a10e0c6c..f05cbb387 100644
--- a/apps/mirai-gui/client/src/hooks/use-update-initialization.ts
+++ b/apps/mirai-gui/client/src/hooks/use-update-initialization.ts
@@ -1,5 +1,5 @@
import { useEffect } from "react";
-import { toast } from "react-hot-toast";
+import { useToast } from "@/components/ui/toast/use-toast";
import { dismissUpdateToast, showReadyUpdateToast } from "@/components/update-toast/notifications";
import { UpdateCheckOutcome, UpdatePhase, useUpdateStore } from "@/stores/use-update-store";
@@ -27,6 +27,7 @@ const startUpdateChecks = (): (() => void) => {
};
export const useUpdateInitialization = (enabled: boolean = true) => {
+ const toast = useToast();
const status = useUpdateStore((s) => s.status);
const { startDownload, applyUpdate, dismiss } = useUpdateStore.getState();
@@ -37,7 +38,9 @@ export const useUpdateInitialization = (enabled: boolean = true) => {
if (status.phase === UpdatePhase.Idle) {
dismissUpdateToast(UPDATE_TOAST_ID);
if (status.downloadError) {
- toast.error(`Update download failed: ${status.downloadError}`);
+ // In the app's own toast, not react-hot-toast's default one; the raw error code is for the log.
+ console.warn("[update] download failed", status.downloadError);
+ toast.error("Couldn't download the update", { id: "update-download-failed" });
useUpdateStore.setState({ status: { phase: UpdatePhase.Idle } });
}
return;
@@ -57,5 +60,5 @@ export const useUpdateInitialization = (enabled: boolean = true) => {
onLater: () => dismiss(),
});
}
- }, [status, startDownload, applyUpdate, dismiss]);
+ }, [status, startDownload, applyUpdate, dismiss, toast]);
};
diff --git a/apps/mirai-gui/client/src/index.css b/apps/mirai-gui/client/src/index.css
index 031193e81..c4b363b50 100644
--- a/apps/mirai-gui/client/src/index.css
+++ b/apps/mirai-gui/client/src/index.css
@@ -34,18 +34,20 @@
overflow: clip;
}
+/* A page's own scroller. On macOS the scrollbar overlays the content and fades out when idle; when
+ the system is set to always show scrollbars it takes real width instead, so the gutter is
+ reserved on both edges: filtering a list down never makes the content jump sideways, and the
+ centred column stays centred. */
+@utility page-scrollbar {
+ @apply thin-scrollbar;
+ scrollbar-gutter: stable both-edges;
+}
+
+/* The standard properties only, never ::-webkit-scrollbar: styling that pseudo-element makes
+ WebKit swap the native overlay scrollbar (which hides when you stop scrolling) for a classic one
+ that is always on screen. */
@utility thin-scrollbar {
- &::-webkit-scrollbar {
- width: 6px;
- height: 6px;
- }
- &::-webkit-scrollbar-track {
- background-color: transparent;
- }
- &::-webkit-scrollbar-thumb {
- background-color: var(--color-gray-500);
- border-radius: 9999px;
- }
+ scrollbar-width: thin;
}
@layer base {
@@ -96,6 +98,10 @@
body {
@apply bg-background text-label-title font-sans;
font-family: InterVariable, Inter, system-ui, "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
+ /* Inter Variable carries an optical size axis: small UI text opens up, large text tightens. */
+ font-optical-sizing: auto;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
}
code,
kbd,
@@ -136,23 +142,37 @@
content-visibility: visible !important;
}
+ /* No divider under the header: the language label and the buttons sit on the block itself. */
[data-streamdown="code-block-header"] {
- @apply relative border-b border-cell-border bg-bg-modal px-3 py-2 text-xs text-label-muted;
+ @apply relative bg-bg-modal px-3 py-2 text-xs text-label-muted;
+ border-bottom: 0 !important;
padding-right: 2.5rem;
}
+ /* The two buttons sit close: 4px between their hover squares. */
[data-streamdown="code-block-actions"] {
border: 0 !important;
padding: 0 !important;
+ gap: 4px !important;
backdrop-filter: none !important;
}
+ /* The same square as the actions under a message: hover fills it, focus rings it. */
[data-streamdown="code-block-actions"] button {
- @apply min-w-6 min-h-6;
+ @apply flex size-8 items-center justify-center rounded-lg p-0 text-label-muted outline-hidden transition-colors duration-150 ease-out;
+ }
+ /* The block is already a raised grey, so hover uses the stronger fill from menus to show on it. */
+ [data-streamdown="code-block-actions"] button:enabled:hover {
+ @apply bg-selection-hover text-label-title;
+ }
+ [data-streamdown="code-block-actions"] button:focus-visible {
+ @apply shadow-focus;
}
+ /* The code starts as far below the language label as the label sits below the block's top edge. */
[data-streamdown="code-block-body"] {
@apply p-4;
+ padding-top: 1px !important;
/* Horizontal code scrolling stays local; vertical gestures scroll the chat. */
overscroll-behavior: contain auto;
background: transparent !important;
@@ -200,6 +220,204 @@
}
}
+/* Arrivals: things the user caused (a new message, a step, a status) come into focus rather than
+ pop in. Short, soft blur plus a few pixels of travel; skipped entirely under reduced motion. */
+@keyframes uzu-in {
+ from {
+ opacity: 0;
+ filter: blur(6px);
+ transform: translateY(4px) scale(0.985);
+ }
+ to {
+ opacity: 1;
+ filter: blur(0);
+ transform: none;
+ }
+}
+/* The first-run welcome: a slower, deeper version of the arrival for a screen seen once. Each part
+ starts out of focus, a little low and small, and settles over most of a second. The cat starts
+ softer and smaller still, so it reads as waking into view. Blur stays under 20px. */
+@keyframes uzu-welcome {
+ from {
+ opacity: 0;
+ filter: blur(12px);
+ transform: translateY(10px) scale(0.97);
+ }
+ 60% {
+ opacity: 1;
+ }
+ to {
+ opacity: 1;
+ filter: none;
+ transform: none;
+ }
+}
+@keyframes uzu-welcome-cat {
+ from {
+ opacity: 0;
+ filter: blur(16px);
+ transform: scale(0.88);
+ }
+ 55% {
+ opacity: 1;
+ }
+ to {
+ opacity: 1;
+ filter: none;
+ transform: none;
+ }
+}
+/* Swaps in place (an icon or a label changing): blur and scale, no travel. */
+@keyframes uzu-swap {
+ from {
+ opacity: 0;
+ filter: blur(3px);
+ transform: scale(0.8);
+ }
+ to {
+ opacity: 1;
+ filter: blur(0);
+ transform: none;
+ }
+}
+
+/* Tooltips grow out of their trigger: from 0.95, nudged 4px toward it. */
+@keyframes uzu-tip {
+ from {
+ opacity: 0;
+ transform: translateY(var(--tip-from, 4px)) scale(0.95);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+@utility animate-uzu-tip-up {
+ --tip-from: 4px;
+ animation: uzu-tip 160ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+@utility animate-uzu-tip-down {
+ --tip-from: -4px;
+ animation: uzu-tip 160ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+
+/* Menus and pickers grow out of their trigger (set transform-origin on the element). */
+@keyframes uzu-pop {
+ from {
+ opacity: 0;
+ transform: scale(0.96);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+@utility animate-uzu-pop {
+ animation: uzu-pop 180ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+
+/* Toasts drop into focus from just above, and leave faster and quieter than they came. */
+@keyframes uzu-toast-in {
+ from {
+ opacity: 0;
+ filter: blur(4px);
+ transform: translateY(-8px) scale(0.96);
+ }
+ to {
+ opacity: 1;
+ filter: blur(0);
+ transform: none;
+ }
+}
+@keyframes uzu-toast-out {
+ to {
+ opacity: 0;
+ filter: blur(2px);
+ transform: translateY(-4px) scale(0.98);
+ }
+}
+@utility animate-uzu-toast-in {
+ animation: uzu-toast-in 320ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+@utility animate-uzu-toast-out {
+ animation: uzu-toast-out 180ms ease-in both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ opacity: 0;
+ }
+}
+
+/* Moving between levels (a model family and its models): the new level slides in from the side
+ you are heading toward, coming into focus as it arrives. */
+@keyframes uzu-push {
+ from {
+ opacity: 0;
+ filter: blur(4px);
+ transform: translateX(var(--push-from, 16px));
+ }
+ to {
+ opacity: 1;
+ filter: blur(0);
+ transform: none;
+ }
+}
+@utility animate-uzu-forward {
+ --push-from: 16px;
+ animation: uzu-push 280ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+@utility animate-uzu-back {
+ --push-from: -16px;
+ animation: uzu-push 280ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+
+/* Fills backwards only, so once done the element is exactly its resting self; and it keeps its own
+ layer, so WebKit doesn't hand the text back to ordinary rendering at the last frame (a visible
+ flash as it re-sharpens). */
+@utility animate-uzu-welcome {
+ animation: uzu-welcome 900ms cubic-bezier(0.22, 1, 0.36, 1) backwards;
+ will-change: transform, filter, opacity;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+@utility animate-uzu-welcome-cat {
+ animation: uzu-welcome-cat 1100ms cubic-bezier(0.22, 1, 0.36, 1) backwards;
+ will-change: transform, filter, opacity;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+@utility animate-uzu-in {
+ animation: uzu-in 360ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+@utility animate-uzu-swap {
+ animation: uzu-swap 180ms cubic-bezier(0.32, 0.72, 0, 1) both;
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+}
+
@layer components {
.scrollbar-hide {
scrollbar-width: none;
diff --git a/apps/mirai-gui/client/src/index.tsx b/apps/mirai-gui/client/src/index.tsx
index 0cd5ce40f..33ac9bd78 100644
--- a/apps/mirai-gui/client/src/index.tsx
+++ b/apps/mirai-gui/client/src/index.tsx
@@ -17,14 +17,21 @@ RuntimeLoader.setWasmUrl(riveWasmUrl);
const appState = useAppStore.getState();
document.documentElement.classList.toggle("dark", appState.isDarkMode);
-if (platformInfo.isTauri) {
- initPlatform(new TauriPlatformClient());
-} else {
- initPlatform(new WebPlatformClient());
+async function boot() {
+ if (platformInfo.isTauri) {
+ initPlatform(new TauriPlatformClient());
+ } else if (platformInfo.isDemo) {
+ const { DemoPlatformClient } = await import("./platform/demo-platform-client");
+ initPlatform(new DemoPlatformClient());
+ } else {
+ initPlatform(new WebPlatformClient());
+ }
+
+ ReactDOM.createRoot(document.getElementById("root")!).render(
+ <React.StrictMode>
+ <RouterProvider router={createAppRouter()} />
+ </React.StrictMode>,
+ );
}
-ReactDOM.createRoot(document.getElementById("root")!).render(
- <React.StrictMode>
- <RouterProvider router={createAppRouter()} />
- </React.StrictMode>,
-);
+void boot();
diff --git a/apps/mirai-gui/client/src/platform/demo-platform-client.ts b/apps/mirai-gui/client/src/platform/demo-platform-client.ts
new file mode 100644
index 000000000..38383e754
--- /dev/null
+++ b/apps/mirai-gui/client/src/platform/demo-platform-client.ts
@@ -0,0 +1,507 @@
+import type { PlatformClient } from "./platform-client";
+import type { ChatService } from "./services/chat";
+import { runLlmStream, type RunEvent, type RunTransport } from "./services/chat/run-stream";
+import type { DownloadEvent, ModelsService } from "./services/models";
+import type { SessionLoadingPayload, SessionService, SessionStatePayload } from "./services/session";
+import { ChatNotFoundError, type ChatData, type StorageService } from "./services/storage";
+import { webDialogs } from "./services/dialogs/web";
+import { webSettings } from "./services/settings/web";
+import { webSystem } from "./services/system/web";
+import { webSystemUi } from "./services/system-ui/web";
+import { webUpdater } from "./services/updater/web";
+import type { EngineModel } from "@/types/model-manager";
+import type { LlmRunParams, SessionOutputStats, TranscriptItem } from "@/types/llm-stream";
+
+/*
+ * `pnpm demo:dev`: the browser build with a pretend engine, for design work and recordings.
+ * Models download in a few seconds, the first message loads its model, and every answer runs
+ * through the same events the desktop backend sends: reading the prompt, thinking, a tool call,
+ * then the answer word by word. Chats live in memory until the tab closes.
+ */
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/* ------------------------------------------------------------------ models */
+
+const GB = 1024 ** 3;
+
+type DemoModel = Omit<EngineModel, "state"> & { bytes: number; downloaded: boolean };
+
+// Vendor icons as the model registry serves them.
+const REGISTRY_ICONS = "https://assets.trymirai.com/registry/icons";
+const ICONS = {
+ Alibaba: {
+ light: `${REGISTRY_ICONS}/alibaba/796fd6ea01ca351f6397e2579d9412162293c410f14cdd3f70e99c4181d68bcd.svg`,
+ dark: `${REGISTRY_ICONS}/alibaba/796fd6ea01ca351f6397e2579d9412162293c410f14cdd3f70e99c4181d68bcd.svg`,
+ },
+ LiquidAI: {
+ light: `${REGISTRY_ICONS}/liquidai/858e1f116f012f80f1901198e41684a9f82e8416ccad716dc3fc981dcd2fdcba.svg`,
+ dark: `${REGISTRY_ICONS}/liquidai/da45e2a75d8405a12071c24d97137c568ed2d2d72f95805ee83f523c37435168.svg`,
+ },
+ Meta: {
+ light: `${REGISTRY_ICONS}/meta/1b4bfe85e334335d96e7881bdf5755024b9a2ae47395f009a586635f518ee4d2.svg`,
+ dark: `${REGISTRY_ICONS}/meta/1b4bfe85e334335d96e7881bdf5755024b9a2ae47395f009a586635f518ee4d2.svg`,
+ },
+ Google: {
+ light: `${REGISTRY_ICONS}/google/422ca3c3cc6d48c1a8339c7d5fe6f3545da84e5f64916126eb6144b947697b5f.svg`,
+ dark: `${REGISTRY_ICONS}/google/422ca3c3cc6d48c1a8339c7d5fe6f3545da84e5f64916126eb6144b947697b5f.svg`,
+ },
+};
+
+const reasoning = { kind: "toggle", defaultEffort: "default" } as const;
+
+const MODELS: DemoModel[] = [
+ {
+ identifier: "Qwen/Qwen3.8-27B-MIRAI-M",
+ vendor: "Alibaba",
+ vendorIcons: ICONS.Alibaba,
+ name: "Qwen3.8 27B Mirai Medium",
+ familyIdentifier: "qwen3.8",
+ familyName: "Qwen3.8",
+ paramSize: 27e9,
+ reasoning,
+ supportsTools: true,
+ quantization: "MIRAI-M",
+ quantizationBits: 4,
+ bytes: 16 * GB,
+ downloaded: true,
+ },
+ {
+ identifier: "Qwen/Qwen3.8-27B-MIRAI-L",
+ vendor: "Alibaba",
+ vendorIcons: ICONS.Alibaba,
+ name: "Qwen3.8 27B Mirai Large",
+ familyIdentifier: "qwen3.8",
+ familyName: "Qwen3.8",
+ paramSize: 27e9,
+ reasoning,
+ supportsTools: true,
+ quantization: "MIRAI-L",
+ quantizationBits: 8,
+ bytes: 29 * GB,
+ downloaded: false,
+ },
+ {
+ identifier: "LiquidAI/LFM2.5-1.2B-Instruct",
+ vendor: "LiquidAI",
+ vendorIcons: ICONS.LiquidAI,
+ name: "LFM2.5 1.2B Instruct",
+ familyIdentifier: "lfm2.5",
+ familyName: "LFM2.5",
+ paramSize: 1.2e9,
+ reasoning: { kind: "unsupported" },
+ supportsTools: true,
+ bytes: 1.3 * GB,
+ downloaded: true,
+ },
+ {
+ identifier: "LiquidAI/LFM2.5-2.6B-Instruct",
+ vendor: "LiquidAI",
+ vendorIcons: ICONS.LiquidAI,
+ name: "LFM2.5 2.6B Instruct",
+ familyIdentifier: "lfm2.5",
+ familyName: "LFM2.5",
+ paramSize: 2.6e9,
+ reasoning: { kind: "unsupported" },
+ supportsTools: true,
+ bytes: 2.8 * GB,
+ downloaded: false,
+ },
+ {
+ identifier: "Qwen/Qwen3.5-9B",
+ vendor: "Alibaba",
+ vendorIcons: ICONS.Alibaba,
+ name: "Qwen3.5 9B",
+ familyIdentifier: "qwen3.5",
+ familyName: "Qwen3.5",
+ paramSize: 9e9,
+ reasoning,
+ supportsTools: true,
+ quantization: "MIRAI-M",
+ quantizationBits: 4,
+ bytes: 5.4 * GB,
+ downloaded: false,
+ },
+ {
+ identifier: "meta-llama/Llama-3.2-3B-Instruct",
+ vendor: "Meta",
+ vendorIcons: ICONS.Meta,
+ name: "Llama 3.2 3B Instruct",
+ familyIdentifier: "llama-3.2",
+ familyName: "Llama-3.2",
+ paramSize: 3e9,
+ reasoning: { kind: "unsupported" },
+ supportsTools: true,
+ bytes: 2.1 * GB,
+ downloaded: false,
+ },
+ {
+ identifier: "google/gemma-3-4b-it",
+ vendor: "Google",
+ vendorIcons: ICONS.Google,
+ name: "Gemma 3 4B It",
+ familyIdentifier: "gemma-3",
+ familyName: "Gemma-3",
+ paramSize: 4e9,
+ reasoning: { kind: "unsupported" },
+ supportsTools: false,
+ bytes: 2.6 * GB,
+ downloaded: false,
+ },
+];
+
+type Download = { completed: number; paused: boolean; seq: number };
+const downloads = new Map<string, Download>();
+const downloadListeners = new Set<(event: DownloadEvent) => void>();
+const catalogListeners = new Set<() => void>();
+const emitDownload = (event: DownloadEvent) => downloadListeners.forEach((listener) => listener(event));
+
+const engineModel = ({ bytes, downloaded, ...model }: DemoModel): EngineModel => {
+ const download = downloads.get(model.identifier);
+ const completed = downloaded ? bytes : (download?.completed ?? 0);
+ const phase = downloaded ? "Downloaded" : !download ? "NotDownloaded" : download.paused ? "Paused" : "Downloading";
+ return {
+ ...model,
+ repoId: model.identifier,
+ state: {
+ phase,
+ totalKbytes: bytes / 1024,
+ downloadedKbytes: completed / 1024,
+ seq: download?.seq ?? 0,
+ },
+ };
+};
+
+const runDownload = async (identifier: string) => {
+ const model = MODELS.find((m) => m.identifier === identifier);
+ const download = downloads.get(identifier);
+ if (!model || !download) return;
+ // About eight seconds whatever the size, in uneven steps like a real connection.
+ while (!download.paused && download.completed < model.bytes) {
+ await sleep(120);
+ if (download.paused || downloads.get(identifier) !== download) return;
+ download.completed = Math.min(model.bytes, download.completed + (model.bytes / 66) * (0.6 + Math.random() * 0.8));
+ download.seq += 1;
+ emitDownload({
+ identifier,
+ seq: download.seq,
+ kind: "progress",
+ completedBytes: download.completed,
+ totalBytes: model.bytes,
+ });
+ }
+ if (download.completed < model.bytes) return;
+ model.downloaded = true;
+ download.seq += 1;
+ emitDownload({ identifier, seq: download.seq, kind: "done" });
+ catalogListeners.forEach((listener) => listener());
+};
+
+const demoModels: ModelsService = {
+ getModels: async () => ({ models: MODELS.map(engineModel), complete: true, refreshing: false }),
+ refreshModels: async () => {},
+ startDownload: async (identifier) => {
+ const previous = downloads.get(identifier);
+ const download = { completed: previous?.completed ?? 0, paused: false, seq: (previous?.seq ?? 0) + 1 };
+ downloads.set(identifier, download);
+ emitDownload({ identifier, seq: download.seq, kind: "resumed" });
+ void runDownload(identifier);
+ },
+ pauseDownload: async (identifier) => {
+ const download = downloads.get(identifier);
+ if (!download) return;
+ download.paused = true;
+ download.seq += 1;
+ emitDownload({ identifier, seq: download.seq, kind: "paused" });
+ },
+ resumeDownload: (identifier) => demoModels.startDownload(identifier),
+ deleteModel: async (identifier) => {
+ const model = MODELS.find((m) => m.identifier === identifier);
+ if (model) model.downloaded = false;
+ const seq = (downloads.get(identifier)?.seq ?? 0) + 1;
+ downloads.delete(identifier);
+ emitDownload({ identifier, seq, kind: "deleted" });
+ catalogListeners.forEach((listener) => listener());
+ },
+ onDownloadEvent: (listener) => {
+ downloadListeners.add(listener);
+ return () => downloadListeners.delete(listener);
+ },
+ onModelsChanged: (listener) => {
+ catalogListeners.add(listener);
+ return () => catalogListeners.delete(listener);
+ },
+};
+
+/* ------------------------------------------------------------------ session */
+
+let resident: string | null = null;
+const stateListeners = new Set<(payload: SessionStatePayload) => void>();
+const loadingListeners = new Set<(payload: SessionLoadingPayload) => void>();
+const emitState = (payload: SessionStatePayload) => stateListeners.forEach((listener) => listener(payload));
+
+const demoSession: SessionService = {
+ onSessionState: (listener) => {
+ stateListeners.add(listener);
+ return () => stateListeners.delete(listener);
+ },
+ onSessionLoading: (listener) => {
+ loadingListeners.add(listener);
+ return () => loadingListeners.delete(listener);
+ },
+ ejectSession: async ({ repoId }) => {
+ emitState({ active: true, repoId, isEjecting: true });
+ await sleep(900);
+ resident = null;
+ emitState({ active: false, repoId, isEjecting: false });
+ },
+};
+
+const loadModel = async (repoId: string) => {
+ if (resident === repoId) return;
+ if (resident) emitState({ active: false, repoId: resident });
+ loadingListeners.forEach((listener) => listener({ status: "start", repoId }));
+ await sleep(2400);
+ resident = repoId;
+ emitState({ active: true, repoId });
+};
+
+/* ------------------------------------------------------------------ answers */
+
+type Script = {
+ name: string;
+ thinking: string;
+ tool?: string;
+ answer: string;
+};
+
+const SCRIPTS: Array<{ match: RegExp; script: Script }> = [
+ {
+ match: /track_caller/i,
+ script: {
+ name: "Track caller on trait fn",
+ thinking:
+ "The question is whether an attribute on a trait method declaration reaches the implementations. track_caller is special: the reference says it applies to the trait's prototype and every implementation inherits it. Worth checking the dyn case, which goes through a shim.",
+ tool: "search_rust_reference",
+ answer: [
+ "Yes. Put `#[track_caller]` on the method in the trait declaration and every implementation picks it up, including ones that override a default method. The impls don't need the attribute themselves.",
+ '```rust\nuse std::panic::Location;\n\ntrait Report {\n #[track_caller]\n fn report(&self);\n}\n\nstruct S;\n\nimpl Report for S {\n fn report(&self) {\n // No #[track_caller] here: it comes from the trait.\n eprintln!("called from {}", Location::caller());\n }\n}\n```',
+ "One caveat: calls through `dyn Report` or a function pointer go through a shim, so they lose the real caller and report the function's own definition instead. Direct, statically dispatched calls keep it.",
+ ].join("\n\n"),
+ },
+ },
+ {
+ match: /version|since when|since what/i,
+ script: {
+ name: "Rust release",
+ thinking: "When did this land? It came with the stabilisation of track_caller itself, in 1.46.",
+ tool: "search_release_notes",
+ answer:
+ "Since Rust 1.46.0, released on 27 August 2020, the same release that stabilized `#[track_caller]`.\n\nInheriting it from the trait declaration was part of that from the start, so there's no separate version to wait for.",
+ },
+ },
+ {
+ // A long think, for trying what the app offers while you wait.
+ match: /think hard|take your time|count to/i,
+ script: {
+ name: "A long think",
+ thinking: Array.from(
+ { length: 14 },
+ (_, i) =>
+ `Step ${i + 1}: weighing another way to approach this, checking it against what came before, and keeping only what holds up.`,
+ ).join(" "),
+ answer:
+ "That took a while. In the desktop app a long think like this is uzu working through the problem on your Mac, one token at a time.",
+ },
+ },
+ {
+ match: /date|time|today|day is it/i,
+ script: {
+ name: "Today",
+ thinking: "I need the current date, and there's a tool for that.",
+ tool: "get_current_date_time",
+ answer: `It's ${new Date().toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", year: "numeric" })}, ${new Date().toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })} on this Mac.`,
+ },
+ },
+];
+
+const fallback = (prompt: string): Script => ({
+ name: prompt.split(/\s+/).slice(0, 5).join(" ") || "New chat",
+ thinking:
+ "Let me read that carefully and answer plainly. Nothing here needs to leave the device, so I can work from what I know.",
+ answer: [
+ "This is the demo engine, so the answer is a stand-in, but everything around it is real: the model loaded on this machine, read your prompt, thought it through, and is now writing word by word.",
+ "In the desktop app the same steps come from **uzu**, running the model on Apple silicon. Nothing you type is sent anywhere.",
+ "- Reading: the cat puts its goggles on\n- Thinking: it looks up and drifts\n- Tools: its eyes turn like gears\n- Writing: its eyes become lines of text",
+ ].join("\n\n"),
+});
+
+const words = (text: string) => text.match(/\S+\s*|\s+/g) ?? [];
+
+const stats = (input: number, output: number, ms: number): SessionOutputStats => ({
+ tokensPerForwardPass: 2.4,
+ prefillStats: { duration: 0.38, tokensCount: input, tokensPerSecond: input / 0.38 },
+ generateStats: { duration: ms / 1000, tokensCount: output, tokensPerSecond: output / (ms / 1000) },
+ totalStats: { duration: 0.38 + ms / 1000, tokensCountInput: input, tokensCountOutput: output },
+});
+
+const canceled = new Set<string>();
+
+const demoTransport: RunTransport = {
+ start: async (runId: string, params: LlmRunParams, onEvent: (event: RunEvent) => void) => {
+ const live = () => !canceled.has(runId);
+ const prompt = params.messages.filter((m) => m.role === "user").at(-1)?.content ?? "";
+ const script = SCRIPTS.find(({ match }) => match.test(prompt))?.script ?? fallback(prompt);
+
+ await loadModel(params.repoId);
+ if (!live()) return;
+ // Prefill: the prompt is read before anything is shown.
+ await sleep(900 + Math.min(1200, prompt.length * 6));
+ if (!live()) return;
+ if (params.modelChatNamingEnabled) onEvent({ type: "chatName", name: script.name });
+
+ const items: TranscriptItem[] = [];
+ const push = (item: TranscriptItem) => {
+ items.push(item);
+ onEvent({ type: "transcript", items: [...items] });
+ };
+ const stream = async (index: number, text: string, pace: number) => {
+ for (const word of words(text)) {
+ if (!live()) return;
+ onEvent({ type: "transcriptDelta", index, delta: word });
+ const item = items[index];
+ if (item && (item.type === "text" || item.type === "thinking"))
+ items[index] = { ...item, text: item.text + word };
+ await sleep(pace + Math.random() * pace);
+ }
+ };
+
+ const thinks = params.reasoningEffort !== "disabled";
+ if (thinks) {
+ push({ type: "thinking", text: "" });
+ await stream(items.length - 1, script.thinking, 45);
+ if (!live()) return;
+ items[items.length - 1] = { type: "thinking", text: script.thinking, completed: true };
+ onEvent({ type: "transcript", items: [...items] });
+ }
+ if (script.tool) {
+ push({ type: "toolCall", name: script.tool, called: false });
+ await sleep(1800);
+ if (!live()) return;
+ items[items.length - 1] = { type: "toolCall", name: script.tool, called: true };
+ onEvent({ type: "transcript", items: [...items] });
+ await sleep(300);
+ }
+ const started = performance.now();
+ push({ type: "text", text: "" });
+ await stream(items.length - 1, script.answer, 22);
+ if (!live()) return;
+ const output = words(script.answer).length;
+ onEvent({
+ type: "done",
+ text: script.answer,
+ finishReason: "Stop",
+ stats: stats(Math.ceil(prompt.length / 4) + 24, output, performance.now() - started),
+ transcript: [...items],
+ ...(params.modelChatNamingEnabled ? { chatName: script.name } : {}),
+ });
+ },
+ cancel: async (runId) => {
+ canceled.add(runId);
+ },
+};
+
+const demoChat: ChatService = {
+ runStream: (params) => runLlmStream(demoTransport, params),
+ cancelRun: (runId) => demoTransport.cancel(runId),
+ generateTitle: async ({ userText }) => fallback(userText).name,
+ cancelTitleGen: async () => {},
+ getSamplingDefaults: async () => ({
+ type: "Stochastic",
+ temperature: 0.6,
+ topK: 20,
+ topP: 0.95,
+ minP: null,
+ repetitionPenalty: 1.1,
+ suffixRepetitionLength: 1024,
+ }),
+};
+
+/* ------------------------------------------------------------------ storage */
+
+const chats = new Map<string, ChatData>();
+let globalInstructions: string | null = null;
+
+const touch = (chat: ChatData) => {
+ chat.metadata.updatedAt = Date.now();
+ chat.metadata.messageCount = chat.messages.length;
+};
+
+const demoStorage: StorageService = {
+ listChats: async () => [...chats.values()].map((chat) => ({ ...chat.metadata })),
+ loadChat: async (chatId) => structuredClone(chats.get(chatId) ?? null),
+ createOrReplaceChat: async (chat) => {
+ chats.set(chat.metadata.id, structuredClone(chat));
+ },
+ appendMessage: async (chatId, message) => {
+ const chat = chats.get(chatId);
+ if (!chat) throw new ChatNotFoundError(chatId);
+ chat.messages.push(structuredClone(message));
+ touch(chat);
+ },
+ updateStoredMessage: async (chatId, messageId, patch) => {
+ const chat = chats.get(chatId);
+ const index = chat?.messages.findIndex((m) => m.id === messageId) ?? -1;
+ if (!chat || index < 0) return;
+ chat.messages[index] = { ...chat.messages[index]!, ...structuredClone(patch) };
+ touch(chat);
+ },
+ editUserMessage: async (chatId, messageId, text) => {
+ const chat = chats.get(chatId);
+ const index = chat?.messages.findIndex((m) => m.id === messageId) ?? -1;
+ if (!chat || index < 0) throw new ChatNotFoundError(chatId);
+ chat.messages = [...chat.messages.slice(0, index), { ...chat.messages[index]!, text }];
+ touch(chat);
+ return structuredClone(chat);
+ },
+ removeMessage: async (chatId, messageId) => {
+ const chat = chats.get(chatId);
+ if (!chat) return;
+ chat.messages = chat.messages.filter((m) => m.id !== messageId);
+ touch(chat);
+ },
+ updateChatTitle: async (chatId, title, expectedTitle) => {
+ const chat = chats.get(chatId);
+ if (!chat || (expectedTitle !== undefined && chat.metadata.title !== expectedTitle)) return false;
+ chat.metadata.title = title;
+ touch(chat);
+ return true;
+ },
+ deleteChat: async (chatId) => {
+ chats.delete(chatId);
+ },
+ exportAllChatsZip: async () => null,
+ saveBinaryFile: async () => false,
+ saveGlobalInstructions: async (content) => {
+ globalInstructions = content;
+ },
+ loadGlobalInstructions: async () => globalInstructions,
+ previewCleanup: async () => ({
+ dialogs: { count: chats.size, sizeBytes: 0 },
+ models: { count: 0, sizeBytes: 0 },
+ logs: { sizeBytes: 0 },
+ }),
+ executeCleanup: async (categories) => ({ executed: categories, modelsSkipped: [] }),
+};
+
+export class DemoPlatformClient implements PlatformClient {
+ readonly chat = demoChat;
+ readonly session = demoSession;
+ readonly models = demoModels;
+ readonly storage = demoStorage;
+ readonly settings = webSettings;
+ readonly system = webSystem;
+ readonly systemUi = webSystemUi;
+ readonly updater = webUpdater;
+ readonly dialogs = webDialogs;
+}
diff --git a/apps/mirai-gui/client/src/platform/platform-info.ts b/apps/mirai-gui/client/src/platform/platform-info.ts
index 5b406cfca..c7c02a03a 100644
--- a/apps/mirai-gui/client/src/platform/platform-info.ts
+++ b/apps/mirai-gui/client/src/platform/platform-info.ts
@@ -1,11 +1,13 @@
export const platformInfo = {
isWeb: __PLATFORM__ === "web",
isTauri: __PLATFORM__ === "tauri",
+ /** The browser build with a pretend engine, for design work and recordings. */
+ isDemo: __PLATFORM__ === "demo",
features: {
autoUpdate: __PLATFORM__ === "tauri",
fileSystem: __PLATFORM__ === "tauri",
logExport: __PLATFORM__ === "tauri",
- localModelDownloads: __PLATFORM__ === "tauri",
+ localModelDownloads: __PLATFORM__ === "tauri" || __PLATFORM__ === "demo",
autoEject: __PLATFORM__ === "tauri",
cliInstall: __PLATFORM__ === "tauri",
// Overlay title bar with in-content macOS traffic lights: UI must reserve
diff --git a/apps/mirai-gui/client/src/route-tree.gen.ts b/apps/mirai-gui/client/src/route-tree.gen.ts
index 5ed8b160b..d22989d1d 100644
--- a/apps/mirai-gui/client/src/route-tree.gen.ts
+++ b/apps/mirai-gui/client/src/route-tree.gen.ts
@@ -13,6 +13,7 @@ import { Route as IndexRouteImport } from './routes/index'
import { Route as ChatsRouteImport } from './routes/chats'
import { Route as LocalModelsRouteImport } from './routes/local-models'
import { Route as SettingsRouteImport } from './routes/settings'
+import { Route as WelcomeRouteImport } from './routes/welcome'
import { Route as ChatChatIdRouteImport } from './routes/chat/$chatId'
const IndexRoute = IndexRouteImport.update({
@@ -35,6 +36,11 @@ const SettingsRoute = SettingsRouteImport.update({
path: '/settings',
getParentRoute: () => rootRouteImport,
} as any)
+const WelcomeRoute = WelcomeRouteImport.update({
+ id: '/welcome',
+ path: '/welcome',
+ getParentRoute: () => rootRouteImport,
+} as any)
const ChatChatIdRoute = ChatChatIdRouteImport.update({
id: '/chat/$chatId',
path: '/chat/$chatId',
@@ -46,6 +52,7 @@ export interface FileRoutesByFullPath {
'/chats': typeof ChatsRoute
'/local-models': typeof LocalModelsRoute
'/settings': typeof SettingsRoute
+ '/welcome': typeof WelcomeRoute
'/chat/$chatId': typeof ChatChatIdRoute
}
export interface FileRoutesByTo {
@@ -53,6 +60,7 @@ export interface FileRoutesByTo {
'/chats': typeof ChatsRoute
'/local-models': typeof LocalModelsRoute
'/settings': typeof SettingsRoute
+ '/welcome': typeof WelcomeRoute
'/chat/$chatId': typeof ChatChatIdRoute
}
export interface FileRoutesById {
@@ -61,19 +69,33 @@ export interface FileRoutesById {
'/chats': typeof ChatsRoute
'/local-models': typeof LocalModelsRoute
'/settings': typeof SettingsRoute
+ '/welcome': typeof WelcomeRoute
'/chat/$chatId': typeof ChatChatIdRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
- fullPaths: '/' | '/chats' | '/local-models' | '/settings' | '/chat/$chatId'
+ fullPaths:
+ | '/'
+ | '/chats'
+ | '/local-models'
+ | '/settings'
+ | '/welcome'
+ | '/chat/$chatId'
fileRoutesByTo: FileRoutesByTo
- to: '/' | '/chats' | '/local-models' | '/settings' | '/chat/$chatId'
+ to:
+ | '/'
+ | '/chats'
+ | '/local-models'
+ | '/settings'
+ | '/welcome'
+ | '/chat/$chatId'
id:
| '__root__'
| '/'
| '/chats'
| '/local-models'
| '/settings'
+ | '/welcome'
| '/chat/$chatId'
fileRoutesById: FileRoutesById
}
@@ -82,6 +104,7 @@ export interface RootRouteChildren {
ChatsRoute: typeof ChatsRoute
LocalModelsRoute: typeof LocalModelsRoute
SettingsRoute: typeof SettingsRoute
+ WelcomeRoute: typeof WelcomeRoute
ChatChatIdRoute: typeof ChatChatIdRoute
}
@@ -115,6 +138,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsRouteImport
parentRoute: typeof rootRouteImport
}
+ '/welcome': {
+ id: '/welcome'
+ path: '/welcome'
+ fullPath: '/welcome'
+ preLoaderRoute: typeof WelcomeRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/chat/$chatId': {
id: '/chat/$chatId'
path: '/chat/$chatId'
@@ -130,6 +160,7 @@ const rootRouteChildren: RootRouteChildren = {
ChatsRoute: ChatsRoute,
LocalModelsRoute: LocalModelsRoute,
SettingsRoute: SettingsRoute,
+ WelcomeRoute: WelcomeRoute,
ChatChatIdRoute: ChatChatIdRoute,
}
export const routeTree = rootRouteImport
diff --git a/apps/mirai-gui/client/src/routes/__root.tsx b/apps/mirai-gui/client/src/routes/__root.tsx
index ffe23f835..087d6db26 100644
--- a/apps/mirai-gui/client/src/routes/__root.tsx
+++ b/apps/mirai-gui/client/src/routes/__root.tsx
@@ -1,14 +1,16 @@
import { ErrorPage } from "@/components/error-page";
-import { FooterBar } from "@/components/footer-bar";
import { useAppNavigationEvents } from "@/hooks/use-app-navigation-events";
import { useSaveFailureToast } from "@/hooks/use-save-failure-toast";
import { useIsMobile } from "@/hooks/use-media-query";
import { useGlobalDownloadToasts } from "@/hooks/use-global-download-toasts";
import { useSidebarStore } from "@/stores/use-sidebar-store";
-import { createRootRoute, Outlet } from "@tanstack/react-router";
+import { createRootRoute, Outlet, useLocation } from "@tanstack/react-router";
import { useEffect } from "react";
+import { twMerge } from "tailwind-merge";
import LeftBar from "@/components/left-bar";
import { ToastProvider } from "@/components/ui/toast/toast-provider";
+import { TooltipProvider } from "@/components/ui/tooltip/provider";
+import { HoverPopoverProvider } from "@/components/ui/popover/hover-popover/provider";
import { useAppInitialization } from "@/hooks/use-app-initialization";
export const Route = createRootRoute({
@@ -19,6 +21,8 @@ export const Route = createRootRoute({
function RootComponent() {
const isMobile = useIsMobile();
const setMobile = useSidebarStore((s) => s.setMobile);
+ const isSidebarOpen = useSidebarStore((s) => s.isOpen);
+ const { pathname } = useLocation();
useAppInitialization();
useGlobalDownloadToasts();
@@ -29,17 +33,44 @@ function RootComponent() {
setMobile(isMobile);
}, [isMobile, setMobile]);
+ // The welcome is its own full window, before the app: no sidebar, no panel.
+ if (pathname === "/welcome") {
+ return (
+ <TooltipProvider>
+ <HoverPopoverProvider>
+ <div className="h-dvh overflow-clip bg-background text-label-title">
+ <div className="drag-layer fixed top-0 left-0 right-0 h-10 select-none" />
+ <Outlet />
+ <ToastProvider />
+ </div>
+ </HoverPopoverProvider>
+ </TooltipProvider>
+ );
+ }
+
return (
- <div className="h-dvh overflow-clip bg-background text-label-title flex">
- <div className="drag-layer fixed top-0 left-0 right-0 h-10 select-none" />
- <LeftBar />
- <div className="relative flex-1 min-w-0 flex flex-col overflow-clip">
- <main className="flex-1 min-h-0 overflow-clip">
- <Outlet />
- </main>
- <FooterBar />
- </div>
- <ToastProvider />
- </div>
+ <TooltipProvider>
+ <HoverPopoverProvider>
+ <div className="h-dvh overflow-clip bg-bg-sidebar text-label-title flex">
+ <div className="drag-layer fixed top-0 left-0 right-0 h-10 select-none" />
+ <LeftBar />
+ {/* Content sits in an inset, rounded panel on the window's own surface, like a sheet of
+ paper on a desk: the panel's edge separates it from the sidebar, so neither needs a line. */}
+ {/* The margin around the panel is window chrome: dragging it moves the window. */}
+ <div
+ data-tauri-drag-region
+ className={twMerge(
+ "relative flex-1 min-w-0 flex flex-col overflow-clip py-2 pr-2 transition-[padding] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none",
+ isSidebarOpen && !isMobile ? "pl-0" : "pl-2",
+ )}
+ >
+ <main className="flex-1 min-h-0 overflow-clip rounded-[12px] border-[0.5px] border-border-default bg-background shadow-[0_1px_2px_0_rgb(0_0_0/0.03)]">
+ <Outlet />
+ </main>
+ </div>
+ <ToastProvider />
+ </div>
+ </HoverPopoverProvider>
+ </TooltipProvider>
);
}
diff --git a/apps/mirai-gui/client/src/routes/index.test.tsx b/apps/mirai-gui/client/src/routes/index.test.tsx
index 5e8729081..b21171ea7 100644
--- a/apps/mirai-gui/client/src/routes/index.test.tsx
+++ b/apps/mirai-gui/client/src/routes/index.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { useModelsStore } from "@/stores/use-models-store";
import type { EngineModel } from "@/types/model-manager";
import { modelDownloadPhases } from "@/types/model-manager";
+import { markWelcomeSeen } from "@/features/welcome/welcome-seen";
import { Route } from "./index";
const getModels = vi.hoisted(() => vi.fn());
@@ -29,8 +30,19 @@ const destination = () => JSON.parse(screen.getByTestId("destination").textConte
beforeEach(() => {
vi.clearAllMocks();
useModelsStore.setState(defaults, true);
+ // These are returning users; the welcome is covered on its own below.
+ markWelcomeSeen();
+});
+afterEach(() => {
+ cleanup();
+ localStorage.clear();
+});
+
+it("opens the welcome first on a new install", () => {
+ localStorage.clear();
+ render(<HomePage />);
+ expect(destination()).toEqual({ to: "/welcome", replace: true });
});
-afterEach(cleanup);
it("waits for discovery and opens a new chat when a shared-cache download is found", async () => {
render(<HomePage />);
diff --git a/apps/mirai-gui/client/src/routes/index.tsx b/apps/mirai-gui/client/src/routes/index.tsx
index 2b6c9de6b..5dc8aca73 100644
--- a/apps/mirai-gui/client/src/routes/index.tsx
+++ b/apps/mirai-gui/client/src/routes/index.tsx
@@ -1,5 +1,6 @@
import { Loader } from "@/components/loader";
import { platformInfo } from "@/platform/platform-info";
+import { hasSeenWelcome } from "@/features/welcome/welcome-seen";
import { useModelsStore } from "@/stores/use-models-store";
import { modelDownloadPhases } from "@/types/model-manager";
import { createFileRoute, Navigate } from "@tanstack/react-router";
@@ -21,6 +22,9 @@ function HomePage() {
if (platformInfo.isWeb) return <Navigate to="/chats" replace />;
+ // A new install says hello first.
+ if (!hasSeenWelcome()) return <Navigate to="/welcome" replace />;
+
if (models.some((model) => modelPhasesById[model.repoId] === modelDownloadPhases.downloaded)) {
return <Navigate to="/chat/$chatId" params={{ chatId }} search={{ isNew: true }} replace />;
}
diff --git a/apps/mirai-gui/client/src/routes/welcome.tsx b/apps/mirai-gui/client/src/routes/welcome.tsx
new file mode 100644
index 000000000..0f6f6ec60
--- /dev/null
+++ b/apps/mirai-gui/client/src/routes/welcome.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { WelcomeScreen } from "@/features/welcome/welcome-screen";
+
+export const Route = createFileRoute("/welcome")({
+ component: WelcomeScreen,
+});
diff --git a/apps/mirai-gui/client/src/stores/use-app-store.test.ts b/apps/mirai-gui/client/src/stores/use-app-store.test.ts
index 9708e7cf1..fef09cf87 100644
--- a/apps/mirai-gui/client/src/stores/use-app-store.test.ts
+++ b/apps/mirai-gui/client/src/stores/use-app-store.test.ts
@@ -21,14 +21,20 @@ it("defaults to Medium and persists the pixel width with existing preferences",
});
});
-it.each([800, 1000, 1200])("restores the saved %s pixel width on hydration", async (chatWidth) => {
+it.each([768, 1000, 1200])("restores the saved %s pixel width on hydration", async (chatWidth) => {
localStorage.setItem(APP_STORE_KEY, JSON.stringify({ state: { chatWidth }, version: 0 }));
await useAppStore.persist.rehydrate();
expect(useAppStore.getState().chatWidth).toBe(chatWidth);
expect(useAppStore.getState().theme).toBe("system");
});
-it.each([undefined, null, 799, 1201, "1000"])(
+it("keeps Narrow saved under its old 800 pixel width as Narrow", async () => {
+ localStorage.setItem(APP_STORE_KEY, JSON.stringify({ state: { chatWidth: 800 }, version: 0 }));
+ await useAppStore.persist.rehydrate();
+ expect(useAppStore.getState().chatWidth).toBe(768);
+});
+
+it.each([undefined, null, 767, 799, 1201, "1000"])(
"uses Medium for missing or invalid stored width %s",
async (chatWidth) => {
localStorage.setItem(APP_STORE_KEY, JSON.stringify({ state: { chatWidth, isDarkMode: false }, version: 0 }));
@@ -37,7 +43,7 @@ it.each([undefined, null, 799, 1201, "1000"])(
},
);
-it.each([799, 1201, Number.NaN, Number.POSITIVE_INFINITY])("rejects invalid setter value %s", (width) => {
+it.each([767, 800, 1201, Number.NaN, Number.POSITIVE_INFINITY])("rejects invalid setter value %s", (width) => {
useAppStore.getState().setChatWidth(width);
expect(useAppStore.getState().chatWidth).toBe(1000);
expect(JSON.parse(localStorage.getItem(APP_STORE_KEY)!).state.chatWidth).toBe(1000);
diff --git a/apps/mirai-gui/client/src/stores/use-app-store.ts b/apps/mirai-gui/client/src/stores/use-app-store.ts
index 98e739956..f6fbd19d3 100644
--- a/apps/mirai-gui/client/src/stores/use-app-store.ts
+++ b/apps/mirai-gui/client/src/stores/use-app-store.ts
@@ -3,7 +3,7 @@ import { APP_STORE_KEY, migrateAppStorage } from "./migrate-app-storage";
import { create } from "zustand";
import { persist } from "zustand/middleware";
-export type ChatWidth = 800 | 1000 | 1200;
+export type ChatWidth = 768 | 1000 | 1200;
export const DEFAULT_CHAT_WIDTH: ChatWidth = 1000;
export type ThemeMode = "system" | "light" | "dark";
@@ -20,7 +20,10 @@ export const isDarkTheme = (
systemDark = typeof window !== "undefined" && (window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false),
): boolean => theme === "dark" || (theme === "system" && systemDark);
-const isChatWidth = (value: unknown): value is ChatWidth => value === 800 || value === 1000 || value === 1200;
+const isChatWidth = (value: unknown): value is ChatWidth => value === 768 || value === 1000 || value === 1200;
+
+// Narrow used to be 800px; it's 768px now (as in ChatGPT). A saved 800 stays Narrow.
+const LEGACY_NARROW_WIDTH = 800;
type AppState = {
isDarkMode: boolean;
@@ -66,7 +69,7 @@ export const useAppStore = create<AppState>()(
merge: (persisted, current) => {
const stored = (persisted ?? {}) as Partial<Omit<AppState, "chatWidth">> & { chatWidth?: unknown };
const theme = resolveTheme(stored);
- const { chatWidth } = stored;
+ const chatWidth = stored.chatWidth === LEGACY_NARROW_WIDTH ? 768 : stored.chatWidth;
return {
...current,
theme,
diff --git a/apps/mirai-gui/client/src/stores/use-sidebar-store.ts b/apps/mirai-gui/client/src/stores/use-sidebar-store.ts
index e59812f7e..39faafb9a 100644
--- a/apps/mirai-gui/client/src/stores/use-sidebar-store.ts
+++ b/apps/mirai-gui/client/src/stores/use-sidebar-store.ts
@@ -1,12 +1,20 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
+export const SIDEBAR_DEFAULT_WIDTH = 248;
+export const SIDEBAR_MIN_WIDTH = 224;
+export const SIDEBAR_MAX_WIDTH = 400;
+
type SidebarState = {
isOpen: boolean;
+ /** The width the sidebar opens at, set by dragging its edge; kept while it's hidden. */
+ width: number;
isMobile: boolean;
chatVisibility: { chatId: string; ratio: number } | null;
setChatVisibility: (visibility: SidebarState["chatVisibility"]) => void;
toggle: () => void;
+ setOpen: (isOpen: boolean) => void;
+ setWidth: (width: number) => void;
setMobile: (isMobile: boolean) => void;
closeOnMobile: () => void;
};
@@ -15,10 +23,13 @@ export const useSidebarStore = create<SidebarState>()(
persist(
(set, get) => ({
isOpen: true,
+ width: SIDEBAR_DEFAULT_WIDTH,
isMobile: false,
chatVisibility: null,
setChatVisibility: (chatVisibility) => set({ chatVisibility }),
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
+ setOpen: (isOpen) => set({ isOpen }),
+ setWidth: (width) => set({ width: Math.round(Math.min(SIDEBAR_MAX_WIDTH, Math.max(SIDEBAR_MIN_WIDTH, width))) }),
setMobile: (isMobile: boolean) => {
const currentState = get();
const wasMobile = currentState.isMobile;
@@ -43,6 +54,7 @@ export const useSidebarStore = create<SidebarState>()(
partialize: (state: SidebarState) => ({
isOpen: state.isOpen,
isMobile: state.isMobile,
+ width: state.width,
}),
},
),
diff --git a/apps/mirai-gui/client/src/stores/use-update-store.ts b/apps/mirai-gui/client/src/stores/use-update-store.ts
index 9e1ca82ee..4680f40c8 100644
--- a/apps/mirai-gui/client/src/stores/use-update-store.ts
+++ b/apps/mirai-gui/client/src/stores/use-update-store.ts
@@ -124,6 +124,12 @@ export const useUpdateStore = create<UpdateState>()((set, get) => ({
get().watchDownload(version);
const result = await updater.startUpdateDownload(version);
+ // A download is already running (a second start for the same update, e.g. an effect run
+ // twice): not a failure. Keep watching it, as after a webview reload.
+ if (!result.ok && result.error === "already-in-progress") {
+ await get()._reconcileDownload(version);
+ return;
+ }
if (!result.ok) {
get()._downloadListenersCleanup?.();
set({ status: { phase: UpdatePhase.Idle, downloadError: result.error } });
diff --git a/apps/mirai-gui/client/src/styles/theme.css b/apps/mirai-gui/client/src/styles/theme.css
index 2ef9f9ab5..5434277f1 100644
--- a/apps/mirai-gui/client/src/styles/theme.css
+++ b/apps/mirai-gui/client/src/styles/theme.css
@@ -49,6 +49,8 @@
--color-success: var(--color-green-500);
--color-success-bg: rgb(from var(--color-green-500) r g b / 0.08);
--color-success-border: rgb(from var(--color-green-500) r g b / 0.4);
+ /* Green for small marks on a light fill (dots, checks): deep enough to read on white. */
+ --color-success-strong: #00873c;
--color-text-primary: var(--color-gray-1200);
--color-text-secondary: var(--color-gray-1100);
--color-text-muted: var(--color-gray-1000);
@@ -58,9 +60,22 @@
--color-border-outlined: rgb(from var(--color-black) r g b / 0.15);
--color-border-outlined-hover: rgb(from var(--color-black) r g b / 0.22);
--color-slider-track: var(--color-gray-500);
+ /* Fills for controls that sit on a card or panel (selects, inputs, segmented tracks). Translucent,
+ so they always step away from whatever surface is under them instead of matching it. */
+ --color-control-fill: rgb(from var(--color-black) r g b / 0.06);
+ --color-control-fill-hover: rgb(from var(--color-black) r g b / 0.09);
+ --color-control-selected: #ffffff;
+ /* Your own messages: a quiet grey bubble with the strongest text. */
+ --color-user-bubble: var(--color-bg-hover);
+ --color-user-bubble-text: var(--color-label-title);
--color-surface-secondary: var(--color-gray-100);
--color-surface-tertiary: var(--color-gray-300);
--color-surface-elevated: var(--color-gray-50);
+ /* Anything floating above the page (menus, pickers, toasts) is lifted a step off every surface
+ under it, so it never melts into the composer or a card it overlaps. */
+ --color-surface-popover: #ffffff;
+ /* A quiet fill for blocks inside the conversation (reasoning, code): shape without a border. */
+ --color-surface-soft: color-mix(in srgb, var(--color-surface-tertiary) 65%, var(--color-background));
--color-selection-selected: #e1e1e1;
--color-selection-hover: #ededed;
--color-overlay: rgba(0, 0, 0, 0.4);
@@ -96,49 +111,72 @@
0px 0px 0px 1px rgb(from var(--color-black) r g b / 0.04),
0px 8px 16px -4px rgb(from var(--color-black) r g b / 0.08),
0px 16px 32px -8px rgb(from var(--color-black) r g b / 0.1);
+ /* Floating surfaces (menus, pickers): a hairline to hold the edge, a wide soft lift, and a
+ tight shadow underneath so it reads as above the page rather than drawn on it. */
+ --shadow-popover:
+ 0 0 0 0.5px rgb(from var(--color-black) r g b / 0.08), 0 8px 40px 0 rgb(from var(--color-black) r g b / 0.06),
+ 0 12px 32px -16px rgb(from var(--color-black) r g b / 0.18);
--shadow-custom: var(--shadow-sm);
--shadow-custom-hover: var(--shadow-md);
--shadow-focus: 0 0 0 2px #fff, 0 0 0 4px #0969da;
}
.dark {
- --color-gray-50: #0f0f0f;
- --color-gray-100: #111;
- --color-gray-200: #191919;
- --color-gray-300: #222;
- --color-gray-500: #313131;
- --color-gray-600: #3a3a3a;
- --color-gray-700: #484848;
- --color-gray-1000: #7b7b7b;
+ /* Soft charcoal rather than black, as in Claude desktop: the sidebar is the deepest layer, the
+ content panel a step up, and everything sitting on it (composer, cards, menus) steps lighter. */
+ --color-gray-50: #262626;
+ --color-gray-100: #2e2e2e;
+ --color-gray-200: #333333;
+ --color-gray-300: #383838;
+ --color-gray-500: #444444;
+ --color-gray-600: #454545;
+ --color-gray-700: #555555;
+ --color-gray-1000: #8c8c8c;
--color-gray-1100: #b5b5b5;
--color-gray-1200: #eee;
- --color-background: #0a0a0a;
+ --color-background: #1c1c1c;
--color-border-default: rgb(from var(--color-white) r g b / 0.07);
--color-border-strong: rgb(from var(--color-white) r g b / 0.2);
--color-border-outlined: rgb(from var(--color-white) r g b / 0.12);
--color-border-outlined-hover: rgb(from var(--color-white) r g b / 0.2);
- --color-surface-tertiary: var(--color-gray-200);
+ /* Neutral greys only (no blue cast), and a hover step light enough to show on the soft cards
+ and on the lifted menu surface alike. */
+ --color-surface-tertiary: #3a3a3a;
--color-surface-elevated: var(--color-gray-100);
- --color-selection-selected: color-mix(in srgb, var(--color-surface-elevated), var(--color-text-primary) 8%);
- --color-selection-hover: color-mix(in srgb, var(--color-surface-elevated), var(--color-text-primary) 4%);
+ --color-surface-popover: #353535;
+ --color-success-strong: #3fd17f;
+ --color-control-fill: rgb(from var(--color-white) r g b / 0.08);
+ --color-control-fill-hover: rgb(from var(--color-white) r g b / 0.12);
+ --color-control-selected: rgb(from var(--color-white) r g b / 0.14);
+ --color-slider-track: #505050;
+ /* In the dark the bubble steps up to the composer's surface and the text softens from pure white,
+ so the pair reads calmly instead of glaring. */
+ --color-user-bubble: var(--color-surface-elevated);
+ --color-user-bubble-text: var(--color-text-primary);
+ /* Menu rows sit on the lifted popover, so their states step up from it, not from the page. */
+ --color-selection-selected: #474747;
+ --color-selection-hover: #404040;
--color-overlay: rgba(0, 0, 0, 0.7);
- --color-bg-sidebar: #050506;
- --color-bg-hover: #181a1b;
- --color-sidebar-chat-selected: #1c1e1f;
- --color-sidebar-chat-hover: #101213;
- --color-bg-sub: #1f1f1f;
- --color-bg-modal: #141414;
- --color-card-hover: #1f1f1f;
- --color-button-border: #343434;
- --color-cell-border: #212227;
+ --color-bg-sidebar: #161616;
+ --color-bg-hover: #262626;
+ --color-sidebar-chat-selected: #282828;
+ --color-sidebar-chat-hover: #202020;
+ --color-bg-sub: #262626;
+ --color-bg-modal: #242424;
+ --color-card-hover: #333333;
+ --color-button-border: #3d3d3d;
+ --color-cell-border: #2c2c2c;
--color-label-title: #ffffff;
- --color-label-muted: #9198a1;
+ --color-label-muted: #949494;
--shadow-sm: 0 0 0 1px rgb(from var(--color-white) r g b / 0.1);
--shadow-md: 0 0 0 1px rgb(from var(--color-white) r g b / 0.15);
--shadow-lg: 0 0 0 1px rgb(from var(--color-white) r g b / 0.1);
--shadow-xl: 0 0 0 1px rgb(from var(--color-white) r g b / 0.1);
- --shadow-focus: 0 0 0 2px #0b0b0b, 0 0 0 4px #58a6ff;
+ --shadow-focus: 0 0 0 2px #1c1c1c, 0 0 0 4px #58a6ff;
+ --shadow-popover:
+ inset 0 0 0 0.5px rgb(from var(--color-white) r g b / 0.12), 0 8px 40px 0 rgb(0 0 0 / 0.45),
+ 0 12px 32px -12px rgb(0 0 0 / 0.6);
}
diff --git a/apps/mirai-gui/client/src/vite-env.d.ts b/apps/mirai-gui/client/src/vite-env.d.ts
index f8745d3de..c9eaabf83 100644
--- a/apps/mirai-gui/client/src/vite-env.d.ts
+++ b/apps/mirai-gui/client/src/vite-env.d.ts
@@ -1,3 +1,3 @@
/// <reference types="vite/client" />
-declare const __PLATFORM__: "web" | "tauri";
+declare const __PLATFORM__: "web" | "tauri" | "demo";
diff --git a/apps/mirai-gui/desktop/Info.plist b/apps/mirai-gui/desktop/Info.plist
new file mode 100644
index 000000000..1de817d78
--- /dev/null
+++ b/apps/mirai-gui/desktop/Info.plist
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- The Liquid Glass icon in Resources/Assets.car, compiled from icons/AppIcon.icon (Icon Composer). -->
+ <key>CFBundleIconName</key>
+ <string>AppIcon</string>
+</dict>
+</plist>
diff --git a/apps/mirai-gui/desktop/icons/AppIcon.icon/Assets/SVG Image 4.svg b/apps/mirai-gui/desktop/icons/AppIcon.icon/Assets/SVG Image 4.svg
new file mode 100644
index 000000000..fde63be20
--- /dev/null
+++ b/apps/mirai-gui/desktop/icons/AppIcon.icon/Assets/SVG Image 4.svg
@@ -0,0 +1,6 @@
+<svg width="160" height="127" viewBox="0 0 160 127" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M0 106.839V41.5889C2.42462e-05 38.0748 1.39602 34.7046 3.88086 32.2197C6.36571 29.7349 9.7359 28.3389 13.25 28.3389H17.7559L24.667 5.63283L24.6758 5.60158L24.6865 5.57033C25.1317 4.17394 25.9519 2.92687 27.0576 1.96486L27.2676 1.7881C28.3322 0.924174 29.6027 0.347423 30.957 0.115248L31.2275 0.0732562C32.5861 -0.111986 33.971 0.055392 35.249 0.560561C36.5271 1.06578 37.6519 1.89098 38.5166 2.95509L38.6865 3.17091L38.7393 3.24025L38.7891 3.31251L56.3955 28.3389H62.75C65.5114 28.3389 67.75 30.5775 67.75 33.3389C67.75 36.1003 65.5114 38.3389 62.75 38.3389H55.1611L55.0723 38.336C53.7956 38.2905 52.548 37.9398 51.4346 37.3135C50.3666 36.7128 49.4539 35.8735 48.7617 34.8643L48.7607 34.8662L33.0283 12.5029L26.8701 32.7393C26.361 34.358 25.3495 35.7727 23.9834 36.7793C22.6173 37.7859 20.9664 38.3322 19.2695 38.3389H13.25C12.3881 38.3389 11.5616 38.6816 10.9521 39.291C10.3427 39.9005 10 40.727 10 41.5889V106.839C10 109.491 11.0534 112.035 12.9287 113.91C14.8041 115.786 17.3478 116.839 20 116.839H24.2002C26.9615 116.839 29.2001 119.078 29.2002 121.839C29.2002 124.6 26.9615 126.839 24.2002 126.839H20C14.6957 126.839 9.60815 124.732 5.85742 120.981C2.10672 117.231 0 112.143 0 106.839Z" fill="#0A0A0A"/>
+<path d="M150 106.839V41.5886C150 40.7267 149.657 39.9002 149.048 39.2908C148.438 38.6813 147.612 38.3386 146.75 38.3386H140.73C139.034 38.3319 137.383 37.7856 136.017 36.779C134.65 35.7724 133.639 34.3578 133.13 32.739L126.971 12.5027L111.239 34.866L111.237 34.864C110.545 35.873 109.633 36.7126 108.565 37.3132C107.452 37.9396 106.204 38.2902 104.928 38.3357L104.839 38.3386H97.25C94.4886 38.3386 92.25 36.1 92.25 33.3386C92.25 30.5772 94.4886 28.3386 97.25 28.3386H103.604L121.211 3.31224L121.261 3.23998L121.313 3.17064C122.198 2.00211 123.388 1.09913 124.751 0.560291L125.008 0.463611C126.299 0.00367308 127.689 -0.11711 129.043 0.114978C130.488 0.362624 131.837 1.0025 132.942 1.96459C134.048 2.92665 134.868 4.17374 135.313 5.57006L135.324 5.60131L135.333 5.63256L142.244 28.3386H146.75C150.264 28.3386 153.634 29.7346 156.119 32.2195C158.604 34.7043 160 38.0745 160 41.5886V106.839C160 112.143 157.893 117.23 154.143 120.981C150.392 124.732 145.304 126.839 140 126.839H135.8C133.038 126.839 130.8 124.6 130.8 121.839C130.8 119.077 133.038 116.839 135.8 116.839H140C142.652 116.839 145.196 115.785 147.071 113.91C148.947 112.035 150 109.491 150 106.839Z" fill="#0A0A0A"/>
+<path d="M75 63.9722C75 55.2006 68.5081 48.0898 60.5 48.0898C52.4919 48.0898 46 55.2006 46 63.9722V86.2075C46 94.9791 52.4919 102.09 60.5 102.09C68.5081 102.09 75 94.9791 75 86.2075V63.9722Z" fill="#0A0A0A"/>
+<path d="M114 63.9722C114 55.2006 107.508 48.0898 99.5 48.0898C91.4919 48.0898 85 55.2006 85 63.9722V86.2075C85 94.9791 91.4919 102.09 99.5 102.09C107.508 102.09 114 94.9791 114 86.2075V63.9722Z" fill="#0A0A0A"/>
+</svg>
diff --git a/apps/mirai-gui/desktop/icons/AppIcon.icon/icon.json b/apps/mirai-gui/desktop/icons/AppIcon.icon/icon.json
new file mode 100644
index 000000000..5cce766fb
--- /dev/null
+++ b/apps/mirai-gui/desktop/icons/AppIcon.icon/icon.json
@@ -0,0 +1,64 @@
+{
+ "fill" : "system-light",
+ "groups" : [
+ {
+ "layers" : [
+ {
+ "blend-mode-specializations" : [
+ {
+ "value" : "soft-light"
+ },
+ {
+ "appearance" : "tinted",
+ "value" : "normal"
+ }
+ ],
+ "fill-specializations" : [
+ {
+ "value" : {
+ "solid" : "srgb:0.00000,0.00000,0.00000,1.00000"
+ }
+ },
+ {
+ "appearance" : "dark",
+ "value" : {
+ "automatic-gradient" : "srgb:1.00000,1.00000,1.00000,1.00000"
+ }
+ },
+ {
+ "appearance" : "tinted",
+ "value" : {
+ "solid" : "srgb:1.00000,1.00000,1.00000,1.00000"
+ }
+ }
+ ],
+ "glass" : false,
+ "hidden" : false,
+ "image-name" : "SVG Image 4.svg",
+ "name" : "SVG Image 4",
+ "position" : {
+ "scale" : 5.1,
+ "translation-in-points" : [
+ -8.526512829121202e-14,
+ -20
+ ]
+ }
+ }
+ ],
+ "shadow" : {
+ "kind" : "neutral",
+ "opacity" : 0.5
+ },
+ "translucency" : {
+ "enabled" : true,
+ "value" : 0.5
+ }
+ }
+ ],
+ "supported-platforms" : {
+ "circles" : [
+ "watchOS"
+ ],
+ "squares" : "shared"
+ }
+}
\ No newline at end of file
diff --git a/apps/mirai-gui/desktop/icons/Assets.car b/apps/mirai-gui/desktop/icons/Assets.car
new file mode 100644
index 000000000..5315fffa0
Binary files /dev/null and b/apps/mirai-gui/desktop/icons/Assets.car differ
diff --git a/apps/mirai-gui/desktop/icons/icon.icns b/apps/mirai-gui/desktop/icons/icon.icns
index 11e81b24d..e5d1a7856 100644
Binary files a/apps/mirai-gui/desktop/icons/icon.icns and b/apps/mirai-gui/desktop/icons/icon.icns differ
diff --git a/apps/mirai-gui/desktop/icons/icon.png b/apps/mirai-gui/desktop/icons/icon.png
index ab1e605dc..ebedc839d 100644
Binary files a/apps/mirai-gui/desktop/icons/icon.png and b/apps/mirai-gui/desktop/icons/icon.png differ
diff --git a/apps/mirai-gui/desktop/tauri.conf.json b/apps/mirai-gui/desktop/tauri.conf.json
index 6d4940026..ccee2d9ff 100644
--- a/apps/mirai-gui/desktop/tauri.conf.json
+++ b/apps/mirai-gui/desktop/tauri.conf.json
@@ -29,6 +29,7 @@
"icon": ["icons/icon.png", "icons/icon.icns"],
"category": "public.app-category.productivity",
"macOS": {
+ "files": { "Resources/Assets.car": "icons/Assets.car" },
"signingIdentity": "-",
"minimumSystemVersion": "26.4",
"dmg": {
diff --git a/apps/mirai-gui/package.json b/apps/mirai-gui/package.json
index 75ce12519..72bbf47b4 100644
--- a/apps/mirai-gui/package.json
+++ b/apps/mirai-gui/package.json
@@ -11,6 +11,7 @@
"client:build": "vite build",
"web:dev": "vite --mode web",
"web:build": "vite build --mode web",
+ "demo:dev": "vite --mode demo",
"typecheck": "tsc -p client/tsconfig.json --noEmit",
"lint": "eslint .",
"test": "vitest run",
diff --git a/apps/mirai-gui/vite.config.ts b/apps/mirai-gui/vite.config.ts
index bbcb679f1..141f16939 100644
--- a/apps/mirai-gui/vite.config.ts
+++ b/apps/mirai-gui/vite.config.ts
@@ -4,9 +4,10 @@ import react from "@vitejs/plugin-react";
import path from "path";
import { defineConfig } from "vitest/config";
-// `--mode web` builds the browser variant; vitest runs with mode "test".
+// `--mode web` builds the browser variant, `--mode demo` the browser variant with a pretend
+// engine (see platform/demo-platform-client.ts); vitest runs with mode "test".
export default defineConfig(({ mode }) => {
- const platform = mode === "web" || mode === "test" ? "web" : "tauri";
+ const platform = mode === "web" || mode === "test" ? "web" : mode === "demo" ? "demo" : "tauri";
return {
plugins: [
react(),
@@ -26,7 +27,7 @@ export default defineConfig(({ mode }) => {
outDir: path.join(__dirname, `client/dist-${platform}`),
emptyOutDir: true,
},
- server: { port: platform === "web" ? 3001 : 3002, strictPort: true },
+ server: { port: { web: 3001, tauri: 3002, demo: 3003 }[platform], strictPort: true },
resolve: { alias: { "@": path.resolve(__dirname, "client/src") } },
define: { __PLATFORM__: JSON.stringify(platform) },
optimizeDeps: { include: ["shiki"] },