A high-performance inference engine for AI models
app improvements (#1058)
uuuvnb6f37628fbc1
diff --git a/apps/mirai-gui/README.md b/apps/mirai-gui/README.mdindex 5d07f6049..7ccc3cd82 100644--- a/apps/mirai-gui/README.md+++ b/apps/mirai-gui/README.md@@ -23,6 +23,30 @@ pnpm web:dev # frontend in a browser without the engine: no models, no chats`pnpm check` runs typecheck, ESLint, client tests, clippy and Rust tests;`pnpm format` runs Prettier.+## Preview a fresh start++Quit Mirai, the CLI, and other apps using the shared model cache. From the+repository root, move the current state into a new backup directory:++```bash+python3 scripts/mirai-data.py backup ~/mirai-preview-backup+```++This moves chats, settings, logs, the model cache, and Mirai's WebView data+aside. Add `--keep-cache` to leave `~/.cache/mirai` available, for testing a+fresh app with existing models. Moves require the backup and data to be on+the same filesystem; model files are not copied.++After testing, quit the app and restore:++```bash+python3 scripts/mirai-data.py restore-overwrite ~/mirai-preview-backup+```++Restore replaces the test state and consumes the backup. If the backup used+`--keep-cache`, restore leaves the current cache untouched, including models+downloaded during testing. No live data is changed if the backup is incomplete.+## Signed builds without a releaseIn GitHub Actions, open **Build / release mirai-gui**, choose **Run workflow**,@@ -44,7 +68,7 @@ use this workflow to build and publish the app automatically.```textclient/src/ React app, shared by desktop and webcomponents/ app shell, icons and generic UI primitives (components/ui)- features/ chat, chat-history, local-models, settings, welcome, runtime; each owns its page+ features/ chat, chat-history, local-models, settings, runtime; each owns its pageroutes/ thin TanStack route glueplatform/ platform contract + tauri/web adapters, the only way to the backendstores/ zustand storesdiff --git a/apps/mirai-gui/client/src/components/footer-bar/index.tsx b/apps/mirai-gui/client/src/components/footer-bar/index.tsxindex bd2c83b06..e81ddfb99 100644--- a/apps/mirai-gui/client/src/components/footer-bar/index.tsx+++ b/apps/mirai-gui/client/src/components/footer-bar/index.tsx@@ -13,11 +13,11 @@ export const FooterBar = React.memo(({ className }: { className?: string }) => {return (<divclassName={twMerge(- "bg-bg-sidebar max-h-6 min-h-6 border-t border-cell-border flex items-center justify-between px-5 py-[5px] select-none",+ "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 items-center gap-2 overflow-clip">+ <div className="flex min-w-0 flex-1 items-center gap-2">{footerModel.visible && (<>{footerModel.status === "loading" || footerModel.status === "ejecting" ? (@@ -26,20 +26,22 @@ export const FooterBar = React.memo(({ className }: { className?: string }) => {textClassName="text-[11px]"iconWidth={8}iconHeight={8}- text={footerModel.status === "ejecting" ? "Ejecting…" : "Initializing model…"}+ text={footerModel.status === "ejecting" ? "Ejecting…" : "Loading model…"}/>) : (<><buttononClick={footerModel.onEject}disabled={!footerModel.canEject}- className="flex items-center gap-[5px] hover:text-label-title disabled:opacity-50 disabled:cursor-not-allowed"+ 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 items-center gap-1.5 truncate max-w-[220px]">- {footerModel.vendor && <ModelVendorIcon vendor={footerModel.vendor} size={12} className="h-3 w-3" />}+ <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>@@ -49,7 +51,7 @@ export const FooterBar = React.memo(({ className }: { className?: string }) => {</>)}</div>- {version && <div className="ml-auto text-[11px] font-[450] leading-[1.3] text-text-muted">{version}</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/icons/lightning-icon.tsx b/apps/mirai-gui/client/src/components/icons/lightning-icon.tsxdeleted file mode 100644index 8bd146eab..000000000--- a/apps/mirai-gui/client/src/components/icons/lightning-icon.tsx+++ /dev/null@@ -1,16 +0,0 @@-import React from "react";--type LightningIconProps = {- className?: string;-};--export const LightningIcon: React.FC<LightningIconProps> = ({ className }) => (- <svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none" className={className}>- <path- fillRule="evenodd"- clipRule="evenodd"- d="M7.81546 1.13128C8.053 1.2344 8.19413 1.48177 8.16201 1.73873L7.66063 5.74971H12.2498C12.4762 5.74971 12.6821 5.88064 12.7781 6.08562C12.8741 6.29059 12.8429 6.5326 12.698 6.70648L6.86464 13.7065C6.69886 13.9054 6.42177 13.9712 6.18423 13.8681C5.94669 13.765 5.80556 13.5176 5.83768 13.2607L6.33905 9.24971H1.74984C1.5235 9.24971 1.31759 9.11877 1.22158 8.9138C1.12558 8.70882 1.15681 8.46681 1.30172 8.29293L7.13505 1.29293C7.30083 1.094 7.57791 1.02817 7.81546 1.13128ZM2.99529 8.08304H6.99984C7.16716 8.08304 7.32643 8.15489 7.43716 8.28032C7.54789 8.40576 7.59943 8.5727 7.57867 8.73873L7.24213 11.4311L11.0044 6.91637H6.99984C6.83253 6.91637 6.67326 6.84453 6.56253 6.71909C6.4518 6.59366 6.40026 6.42671 6.42102 6.26069L6.75756 3.56831L2.99529 8.08304Z"- fill="currentColor"- />- </svg>-);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.tsxindex d65ac2e59..e2f7d95dd 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@@ -169,7 +169,7 @@ export function ChatPage() {isLoadingStream={isLoading}isTitleGeneratingForChat={isTitleGeneratingForChat}isModelLoading={isModelLoading}- hasResidentModel={Boolean(residentSession)}+ hasResidentModel={residentSession?.repoId === currentModelId}scrollTargetId={scrollTargetId}onScrolled={() => setScrollTargetId(null)}loadingMessageId={loadingMessageId}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.tsxindex 9a29ce680..b28ad7c14 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@@ -162,9 +162,8 @@ const MessageListComponent: React.FC<MessageListProps> = ({const lastAssistantIndex = messages.at(-1)?.sender === "assistant" ? messages.length - 1 : -1;- const showWaiting = !hasResidentModel && Boolean(isLoading) && !loadingMessageId;const isBusy = Boolean(isModelLoading || isLoading);- const loaderText = showWaiting ? "Waiting for the model to be ready…" : "Generating reply…";+ const loaderText = isModelLoading || !hasResidentModel ? "Loading model…" : "Prefilling…";return (<div className="relative flex flex-1 flex-col overflow-clip h-full">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.tsxindex ef1d7ff12..869aa2502 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@@ -23,6 +23,8 @@ function PerfStat({ value, label }: { value: string; label: string }) {}export function PerformanceDropdown({ perf, disabled = false }: PerformanceDropdownProps) {+ const tokensPerForwardPass = perf?.tokensPerForwardPass;+ const hasSpeculation = typeof tokensPerForwardPass === "number" && Number.isFinite(tokensPerForwardPass);return (<Popover className="w-fit"><PopoverButton@@ -46,9 +48,12 @@ export function PerformanceDropdown({ perf, disabled = false }: PerformanceDropdclassName="[--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 grid-cols-3 gap-3 text-center">+ <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>diff --git a/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.test.tsx b/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.test.tsxindex ab6b3686e..6442dde60 100644--- a/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.test.tsx+++ b/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.test.tsx@@ -175,14 +175,26 @@ describe("useLlmStream", () => {act(() => {emit({ type: "chunk", delta: "Hello" });emit({ type: "chunk", delta: " world" });- emit({ type: "done", text: "Hello world", stats, finishReason: "Stop", parsed: { response: "Hello world" } });+ emit({+ type: "done",+ text: "Hello world",+ stats: { ...stats, tokensPerForwardPass: 2.75 },+ finishReason: "Stop",+ parsed: { response: "Hello world" },+ });});await act(() => run);expect(messageText()).toBe("Hello world");const message = useChatStore.getState().messages.find((m) => m.id === MESSAGE_ID);expect(message?.output?.text?.parsed).toEqual({ chainOfThought: "let me think", response: "Hello world" });- expect(message?.perf).toEqual({ ttftSec: 0.25, totalSec: 2.25, tps: 20, tokensOut: 40 });+ expect(message?.perf).toEqual({+ ttftSec: 0.25,+ totalSec: 2.25,+ tps: 20,+ tokensOut: 40,+ tokensPerForwardPass: 2.75,+ });expect(finalizeAssistantMessage).toHaveBeenCalledWith(CHAT_ID,MESSAGE_ID,diff --git a/apps/mirai-gui/client/src/features/chat/services/run-metrics.ts b/apps/mirai-gui/client/src/features/chat/services/run-metrics.tsindex af6e7e937..06207e3b6 100644--- a/apps/mirai-gui/client/src/features/chat/services/run-metrics.ts+++ b/apps/mirai-gui/client/src/features/chat/services/run-metrics.ts@@ -5,6 +5,7 @@ export type RunMetrics = {totalSec?: number;tps?: number;tokensOut: number;+ tokensPerForwardPass?: number;};export function getRunMetrics(stats: SessionOutputStats): RunMetrics {@@ -13,5 +14,6 @@ export function getRunMetrics(stats: SessionOutputStats): RunMetrics {totalSec: stats.totalStats.duration,tps: stats.generateStats?.tokensPerSecond,tokensOut: stats.totalStats.tokensCountOutput,+ tokensPerForwardPass: stats.tokensPerForwardPass,};}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.tsxindex 9421d8353..cf148fa84 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@@ -4,12 +4,14 @@ import { useAppStore } from "@/stores/use-app-store";import { APP_STORE_KEY } from "@/stores/migrate-app-storage";import GeneralTab from "./general-tab";-vi.mock("@/platform/platform-singleton", () => ({- getPlatform: () => ({ system: { getCliStatus: () => Promise.resolve("installed") } }),+const cli = vi.hoisted(() => ({+ getCliStatus: vi.fn<() => Promise<"installed" | "missing">>(async () => "installed"),+ installCli: vi.fn<() => Promise<"installed" | "cancelled">>(async () => "installed"),}));+vi.mock("@/platform/platform-singleton", () => ({ getPlatform: () => ({ system: cli }) }));vi.mock("@/platform/platform-info", () => ({- platformInfo: { isTauri: true, features: { logExport: true } },+ platformInfo: { isTauri: true, features: { logExport: true, cliInstall: true } },}));const settings = {@@ -42,6 +44,8 @@ const appDefaults = useAppStore.getState();beforeEach(() => {vi.clearAllMocks();+ cli.getCliStatus.mockResolvedValue("installed");+ cli.installCli.mockResolvedValue("installed");vi.stubGlobal("ResizeObserver",class {@@ -59,6 +63,22 @@ afterEach(() => {vi.unstubAllGlobals();});+it("installs the CLI only on an explicit click and allows retry after cancelling the prompt", async () => {+ cli.getCliStatus.mockResolvedValue("missing");+ cli.installCli.mockResolvedValueOnce("cancelled");+ render(<GeneralTab />);+ const install = await screen.findByRole("button", { name: "Install" });+ expect(cli.installCli).not.toHaveBeenCalled();++ fireEvent.click(install);+ await waitFor(() => expect(cli.installCli).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(screen.getByRole("button", { name: "Install" }).hasAttribute("disabled")).toBe(false));++ fireEvent.click(screen.getByRole("button", { name: "Install" }));+ await waitFor(() => expect(cli.installCli).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.queryByRole("button", { name: "Install" })).toBeNull());+});+it("lets users disable model-provided chat names", () => {render(<GeneralTab />);const toggle = screen.getByRole("switch", { name: "Let models name chats via tool call" });diff --git a/apps/mirai-gui/client/src/features/welcome/components/welcome-page.tsx b/apps/mirai-gui/client/src/features/welcome/components/welcome-page.tsxdeleted file mode 100644index 90be8bccf..000000000--- a/apps/mirai-gui/client/src/features/welcome/components/welcome-page.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { useEffect, useState } from "react";-import WelcomeScreen from "./welcome-screen";--const waitFrames = (count: number): Promise<void> =>- new Promise<void>((resolve) => {- const step = (n: number): void => {- if (n <= 0) {- resolve();- return;- }- requestAnimationFrame(() => step(n - 1));- };- step(count);- });--export function WelcomePage() {- const [show, setShow] = useState(false);-- useEffect(() => {- let cancelled = false;- void document.fonts.ready- .catch(() => undefined)- .then(() => waitFrames(10))- .then(() => {- if (!cancelled) setShow(true);- });- return () => {- cancelled = true;- };- }, []);-- return (- <div className="relative w-screen h-screen flex items-start justify-center bg-background dark:bg-[linear-gradient(180deg,#1A1A1A_0%,#0A0A0A_100%)]">- {show ? <WelcomeScreen /> : null}- </div>- );-}diff --git a/apps/mirai-gui/client/src/features/welcome/components/welcome-screen.tsx b/apps/mirai-gui/client/src/features/welcome/components/welcome-screen.tsxdeleted file mode 100644index a80465275..000000000--- a/apps/mirai-gui/client/src/features/welcome/components/welcome-screen.tsx+++ /dev/null@@ -1,160 +0,0 @@-import { platformInfo } from "@/platform/platform-info";-import { useNavigate } from "@tanstack/react-router";-import { cubicBezier, motion } from "motion/react";-import { Lock, WifiOff } from "lucide-react";-import type { ReactNode } from "react";-import { twMerge } from "tailwind-merge";-import { useAppStore } from "@/stores/use-app-store";--import { LightningIcon } from "@/components/icons/lightning-icon";-import { Logo } from "@/components/icons/logo";-import { LogoLightMode } from "@/components/icons/logo-light-mode";-import { Button } from "@/components/ui/button";--const ease = cubicBezier(0.22, 1, 0.36, 1);--function WelcomeScreen() {- const completeWelcome = useAppStore((s) => s.completeWelcome);- const isDarkMode = useAppStore((s) => s.isDarkMode);- const navigate = useNavigate();-- const handleContinue = () => {- completeWelcome();- navigate({ to: platformInfo.isTauri ? "/local-models" : "/chats" });- };-- const featureItem = (icon: ReactNode, text: string, delayS: number) => (- <motion.div- className="flex items-center gap-2"- initial={{ y: 10, opacity: 0 }}- animate={{ y: 0, opacity: 1 }}- transition={{ duration: 1.5, ease, delay: delayS }}- >- <div className="text-label-title">{icon}</div>- <span className="text-[13px] leading-[130%] font-normal text-label-muted">{text}</span>- </motion.div>- );-- const renderAnimatedTitle = (text: string, baseDelay = 0.5, charDelay = 0.05) => {- const chars = Array.from(text);-- return (- <h1 className="text-[28px] leading-[130%] font-medium text-label-title">- {chars.map((ch, i) => (- <motion.span- key={`${i}-${ch}`}- style={{ display: "inline-block" }}- initial={{- opacity: 0,- y: 40,- scale: 2,- filter: "blur(30px)",- }}- animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}- transition={{- ease,- duration: 1.5,- delay: baseDelay + i * charDelay,- }}- >- {ch === " " ? "\u00A0" : ch}- </motion.span>- ))}- </h1>- );- };-- const renderAnimatedSubtitle = (lines: string[], baseDelay = 1, lineDelay = 0) => (- <div className="mt-4 md:mt-3 text-[16px] leading-[130%] font-[450] text-label-muted">- {lines.map((line, i) => (- <motion.div- key={`${i}-${line}`}- initial={{- opacity: 0,- scale: 0.5,- filter: "blur(50px)",- }}- animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}- transition={{- ease,- duration: 1.5,- delay: baseDelay + i * lineDelay,- }}- >- {line}- </motion.div>- ))}- </div>- );-- return (- <div className={twMerge("relative max-h-screen flex justify-center h-full", !isDarkMode && "bg-background")}>- <div className="w-full max-w-[500px] md:min-h-0 px-6 md:px-8 pt-10 md:pt-12 pb-8 md:pb-10 grid grid-rows-[auto_1fr_auto] md:flex md:flex-col md:justify-center">- <div className="contents">- <motion.div- className="flex md:justify-center"- initial={{ scale: 2, opacity: 0 }}- animate={{ scale: 1, opacity: 1 }}- transition={{ duration: 1.5, ease, delay: 0 }}- >- {isDarkMode ? (- <Logo- width={66}- height={57}- className="text-label-title"- style={{- willChange: "transform,opacity",- transform: "translateZ(0)",- }}- />- ) : (- <LogoLightMode- width={48}- height={24}- style={{- willChange: "transform,opacity",- transform: "translateZ(0)",- }}- />- )}- </motion.div>-- <div className="flex flex-col md:items-center justify-center md:text-center md:mt-[162px]">- {renderAnimatedTitle("Welcome to Mirai", 0.5, 0.05)}- {renderAnimatedSubtitle(- [- platformInfo.isWeb- ? "Your private AI assistant, accessible anywhere"- : "Try the full private and local AI potential of your Mac",- ],- 1,- 0,- )}- </div>-- <div className="flex flex-col items-start md:items-center w-full md:mt-[120px]">- <div className="flex flex-col md:flex-row md:items-center md:justify-center md:gap-6 gap-4">- {featureItem(<Lock size={14} />, "100% Private", 2.0)}- {featureItem(<LightningIcon className="w-[14px] h-[15px]" />, "Blazing Fast Responses", 2.2)}- {!platformInfo.isWeb && featureItem(<WifiOff size={14} />, "Works Offline", 2.4)}- </div>-- <div className="w-full mt-8">- <motion.div- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ duration: 2, ease, delay: 3.2 }}- >- <Button kind="primary" size="lg" fullWidth onClick={handleContinue}>- Get started- </Button>- </motion.div>- </div>- </div>- </div>- </div>- </div>- );-}--export default WelcomeScreen;diff --git a/apps/mirai-gui/client/src/hooks/use-app-initialization.ts b/apps/mirai-gui/client/src/hooks/use-app-initialization.tsindex cd112b563..ee67c12a1 100644--- a/apps/mirai-gui/client/src/hooks/use-app-initialization.ts+++ b/apps/mirai-gui/client/src/hooks/use-app-initialization.ts@@ -9,19 +9,18 @@ import { useDownloadWiring } from "./use-download-wiring";import { useUpdateInitialization } from "./use-update-initialization";import { useAppTheme } from "./use-app-theme";-export const useAppInitialization = (enabled: boolean = true) => {+export const useAppInitialization = () => {useAppTheme();- useSessionWiring(enabled);- useDownloadWiring(enabled);- useUpdateInitialization(enabled && platformInfo.features.autoUpdate);+ useSessionWiring();+ useDownloadWiring();+ useUpdateInitialization(platformInfo.features.autoUpdate);useEffect(() => {- if (!enabled) return;attachmentStorage.cleanup();void useModelParamsStore.getState().load();void useModelsStore.getState().fetchModels();if (platformInfo.isTauri) {void useAppStore.getState().fetchVersion();}- }, [enabled]);+ }, []);};diff --git a/apps/mirai-gui/client/src/hooks/use-app-theme.test.tsx b/apps/mirai-gui/client/src/hooks/use-app-theme.test.tsxindex ee6423daf..8c280f5b0 100644--- a/apps/mirai-gui/client/src/hooks/use-app-theme.test.tsx+++ b/apps/mirai-gui/client/src/hooks/use-app-theme.test.tsx@@ -2,13 +2,9 @@ import { act, cleanup, renderHook } from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";import { useAppStore } from "@/stores/use-app-store";import { useAppTheme } from "./use-app-theme";-import { useAppInitialization } from "./use-app-initialization";const setWindowTheme = vi.hoisted(() => vi.fn(async () => true));vi.mock("@/platform/platform-singleton", () => ({ getPlatform: () => ({ systemUi: { setWindowTheme } }) }));-vi.mock("./session-wiring", () => ({ useSessionWiring: vi.fn() }));-vi.mock("./use-download-wiring", () => ({ useDownloadWiring: vi.fn() }));-vi.mock("./use-update-initialization", () => ({ useUpdateInitialization: vi.fn() }));const defaults = useAppStore.getState();let systemDark = false;let listeners: Set<(event: { matches: boolean }) => void>;@@ -80,11 +76,3 @@ it("keeps explicit Light and Dark modes through OS changes, then resumes Systemexpect(useAppStore.getState().isDarkMode).toBe(true);expect(setWindowTheme).toHaveBeenLastCalledWith("system");});--it("still follows the system on the welcome screen while app initialization is disabled", () => {- renderHook(() => useAppInitialization(false));- changeSystemTheme(true);- expect(document.documentElement.classList.contains("dark")).toBe(true);- expect(useAppStore.getState().isDarkMode).toBe(true);- expect(setWindowTheme).toHaveBeenCalledWith("system");-});diff --git a/apps/mirai-gui/client/src/index.tsx b/apps/mirai-gui/client/src/index.tsxindex 8af534c3d..0cd5ce40f 100644--- a/apps/mirai-gui/client/src/index.tsx+++ b/apps/mirai-gui/client/src/index.tsx@@ -17,11 +17,6 @@ RuntimeLoader.setWasmUrl(riveWasmUrl);const appState = useAppStore.getState();document.documentElement.classList.toggle("dark", appState.isDarkMode);-const getInitialPath = (): string => {- if (!appState.skipWelcome) return "/welcome";- return platformInfo.isTauri ? "/local-models" : "/chats";-};-if (platformInfo.isTauri) {initPlatform(new TauriPlatformClient());} else {@@ -30,6 +25,6 @@ if (platformInfo.isTauri) {ReactDOM.createRoot(document.getElementById("root")!).render(<React.StrictMode>- <RouterProvider router={createAppRouter(getInitialPath())} />+ <RouterProvider router={createAppRouter()} /></React.StrictMode>,);diff --git a/apps/mirai-gui/client/src/platform/services/storage/markdown/parse.ts b/apps/mirai-gui/client/src/platform/services/storage/markdown/parse.tsindex 9819fb15f..a6b086421 100644--- a/apps/mirai-gui/client/src/platform/services/storage/markdown/parse.ts+++ b/apps/mirai-gui/client/src/platform/services/storage/markdown/parse.ts@@ -68,6 +68,7 @@ const parsePerf = (block: string): PerfStats | undefined => {tps: toNum(scope.match(/\*\*TPS:\*\*\s*([0-9]+(?:\.[0-9]+)?)/m)),totalSec: toNum(scope.match(/\*\*Total:\*\*\s*([0-9]+(?:\.[0-9]+)?)s/m)),tokensOut: toNum(scope.match(/\*\*TokensOut:\*\*\s*([0-9]+)/m)),+ tokensPerForwardPass: toNum(scope.match(/\*\*TokensPerForwardPass:\*\*\s*([0-9]+(?:\.[0-9]+)?)/m)),};return Object.values(perf).some((v) => typeof v === "number") ? perf : undefined;};diff --git a/apps/mirai-gui/client/src/platform/services/storage/markdown/roundtrip.test.ts b/apps/mirai-gui/client/src/platform/services/storage/markdown/roundtrip.test.tsindex e3580ca82..9dc298e4c 100644--- a/apps/mirai-gui/client/src/platform/services/storage/markdown/roundtrip.test.ts+++ b/apps/mirai-gui/client/src/platform/services/storage/markdown/roundtrip.test.ts@@ -42,6 +42,20 @@ it("keeps an empty assistant placeholder through a serialize/parse round-trip",expect(messages[1]).toMatchObject({ sender: "assistant", text: "" });});+it("preserves speculative acceptance for messages and versions without adding it to AR replies", () => {+ const original = { ...chat.messages[1]!, text: "Answer", perf: { ttftSec: 0.25, tokensPerForwardPass: 2.75 } };+ const versions = projectAssistantVersion(original, "model", "Model");+ versions[1] = { ...versions[1]!, text: "AR answer", perf: { ttftSec: 0.1 } };+ const markdown = serializeToMarkdown({+ ...chat,+ messages: [original, { ...original, id: "versioned", versions, currentVersionIndex: 1 }],+ });+ const messages = extractMessageBlocks(markdown).map(parseMessage);+ expect(messages[0]?.perf?.tokensPerForwardPass).toBe(2.75);+ expect(messages[1]?.versions?.[0]?.perf?.tokensPerForwardPass).toBe(2.75);+ expect(messages[1]?.versions?.[1]?.perf?.tokensPerForwardPass).toBeUndefined();+});+it("keeps ordered tool transcripts through saving and regeneration, including markup inside a turn", () => {const transcript: TranscriptItem[] = [{ type: "thinking", text: "Check the time", completed: true },diff --git a/apps/mirai-gui/client/src/platform/services/storage/markdown/serialize.ts b/apps/mirai-gui/client/src/platform/services/storage/markdown/serialize.tsindex 78e9c67fa..37acfc387 100644--- a/apps/mirai-gui/client/src/platform/services/storage/markdown/serialize.ts+++ b/apps/mirai-gui/client/src/platform/services/storage/markdown/serialize.ts@@ -17,6 +17,7 @@ const formatPerfToMarkdown = (perf?: PerfStats): string[] => {["TPS", perf.tps, (v: number) => `${Math.round(v)}`],["Total", perf.totalSec, (v: number) => `${v.toFixed(3)}s`],["TokensOut", perf.tokensOut, (v: number) => `${v}`],+ ["TokensPerForwardPass", perf.tokensPerForwardPass, (v: number) => `${v}`],] as const;const lines = entries.filter(([, value]) => typeof value === "number" && (value as number) > 0)diff --git a/apps/mirai-gui/client/src/route-tree.gen.ts b/apps/mirai-gui/client/src/route-tree.gen.tsindex d22989d1d..5ed8b160b 100644--- a/apps/mirai-gui/client/src/route-tree.gen.ts+++ b/apps/mirai-gui/client/src/route-tree.gen.ts@@ -13,7 +13,6 @@ 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({@@ -36,11 +35,6 @@ 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',@@ -52,7 +46,6 @@ export interface FileRoutesByFullPath {'/chats': typeof ChatsRoute'/local-models': typeof LocalModelsRoute'/settings': typeof SettingsRoute- '/welcome': typeof WelcomeRoute'/chat/$chatId': typeof ChatChatIdRoute}export interface FileRoutesByTo {@@ -60,7 +53,6 @@ export interface FileRoutesByTo {'/chats': typeof ChatsRoute'/local-models': typeof LocalModelsRoute'/settings': typeof SettingsRoute- '/welcome': typeof WelcomeRoute'/chat/$chatId': typeof ChatChatIdRoute}export interface FileRoutesById {@@ -69,33 +61,19 @@ 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'- | '/welcome'- | '/chat/$chatId'+ fullPaths: '/' | '/chats' | '/local-models' | '/settings' | '/chat/$chatId'fileRoutesByTo: FileRoutesByTo- to:- | '/'- | '/chats'- | '/local-models'- | '/settings'- | '/welcome'- | '/chat/$chatId'+ to: '/' | '/chats' | '/local-models' | '/settings' | '/chat/$chatId'id:| '__root__'| '/'| '/chats'| '/local-models'| '/settings'- | '/welcome'| '/chat/$chatId'fileRoutesById: FileRoutesById}@@ -104,7 +82,6 @@ export interface RootRouteChildren {ChatsRoute: typeof ChatsRouteLocalModelsRoute: typeof LocalModelsRouteSettingsRoute: typeof SettingsRoute- WelcomeRoute: typeof WelcomeRouteChatChatIdRoute: typeof ChatChatIdRoute}@@ -138,13 +115,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsRouteImportparentRoute: typeof rootRouteImport}- '/welcome': {- id: '/welcome'- path: '/welcome'- fullPath: '/welcome'- preLoaderRoute: typeof WelcomeRouteImport- parentRoute: typeof rootRouteImport- }'/chat/$chatId': {id: '/chat/$chatId'path: '/chat/$chatId'@@ -160,7 +130,6 @@ const rootRouteChildren: RootRouteChildren = {ChatsRoute: ChatsRoute,LocalModelsRoute: LocalModelsRoute,SettingsRoute: SettingsRoute,- WelcomeRoute: WelcomeRoute,ChatChatIdRoute: ChatChatIdRoute,}export const routeTree = rootRouteImportdiff --git a/apps/mirai-gui/client/src/router.ts b/apps/mirai-gui/client/src/router.tsindex 19eac161b..ce6f5374a 100644--- a/apps/mirai-gui/client/src/router.ts+++ b/apps/mirai-gui/client/src/router.ts@@ -1,9 +1,8 @@import { createBrowserHistory, createRouter } from "@tanstack/react-router";import { routeTree } from "./route-tree.gen";-export const createAppRouter = (initialPath: string) => {+export const createAppRouter = () => {const history = createBrowserHistory();- if (window.location.pathname === "/") history.replace(initialPath);return createRouter({ routeTree, history, notFoundMode: "root" });};diff --git a/apps/mirai-gui/client/src/routes/__root.tsx b/apps/mirai-gui/client/src/routes/__root.tsxindex 13fb4c104..ffe23f835 100644--- a/apps/mirai-gui/client/src/routes/__root.tsx+++ b/apps/mirai-gui/client/src/routes/__root.tsx@@ -4,9 +4,8 @@ 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 { platformInfo } from "@/platform/platform-info";import { useSidebarStore } from "@/stores/use-sidebar-store";-import { createRootRoute, Outlet, useLocation } from "@tanstack/react-router";+import { createRootRoute, Outlet } from "@tanstack/react-router";import { useEffect } from "react";import LeftBar from "@/components/left-bar";import { ToastProvider } from "@/components/ui/toast/toast-provider";@@ -18,12 +17,10 @@ export const Route = createRootRoute({});function RootComponent() {- const location = useLocation();- const isWelcome = location.pathname === "/welcome";const isMobile = useIsMobile();const setMobile = useSidebarStore((s) => s.setMobile);- useAppInitialization(!isWelcome);+ useAppInitialization();useGlobalDownloadToasts();useAppNavigationEvents();useSaveFailureToast();@@ -32,19 +29,6 @@ function RootComponent() {setMobile(isMobile);}, [isMobile, setMobile]);- if (location.pathname === "/welcome") {- return (- <div className="h-dvh overflow-clip">- <div- data-tauri-drag-region- style={platformInfo.isTauri ? { pointerEvents: "auto" } : undefined}- className="drag-layer fixed top-0 left-0 right-0 h-10 select-none"- />- <Outlet />- </div>- );- }-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" />diff --git a/apps/mirai-gui/client/src/routes/index.test.tsx b/apps/mirai-gui/client/src/routes/index.test.tsxnew file mode 100644index 000000000..5e8729081--- /dev/null+++ b/apps/mirai-gui/client/src/routes/index.test.tsx@@ -0,0 +1,116 @@+import { act, cleanup, render, screen } from "@testing-library/react";+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 { Route } from "./index";++const getModels = vi.hoisted(() => vi.fn());+vi.mock("@/platform/platform-singleton", () => ({ getPlatform: () => ({ models: { getModels } }) }));+vi.mock("@/platform/platform-info", () => ({ platformInfo: { isWeb: false } }));+vi.mock("@/components/loader", () => ({ Loader: ({ text }: { text: string }) => <div>{text}</div> }));+vi.mock("@tanstack/react-router", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-router")>()),+ Navigate: (props: object) => <div data-testid="destination">{JSON.stringify(props)}</div>,+}));++const HomePage = Route.options.component!;+const defaults = useModelsStore.getState();+const model = (phase: EngineModel["state"]["phase"]): EngineModel => ({+ identifier: "vendor/model",+ name: "Shared model",+ vendor: "Vendor",+ reasoning: { kind: "unsupported" },+ supportsTools: false,+ state: { phase, totalKbytes: 100, downloadedKbytes: 0, seq: 0 },+});+const destination = () => JSON.parse(screen.getByTestId("destination").textContent!);++beforeEach(() => {+ vi.clearAllMocks();+ useModelsStore.setState(defaults, true);+});+afterEach(cleanup);++it("waits for discovery and opens a new chat when a shared-cache download is found", async () => {+ render(<HomePage />);+ expect(screen.queryByTestId("destination")).toBeNull();++ getModels.mockResolvedValueOnce({ models: [], complete: false, refreshing: true });+ await act(() => useModelsStore.getState().fetchModels());+ expect(screen.queryByTestId("destination")).toBeNull();++ getModels.mockResolvedValueOnce({+ models: [model(modelDownloadPhases.initializing)],+ complete: true,+ refreshing: false,+ });+ await act(() => useModelsStore.getState().fetchModels());+ expect(screen.queryByTestId("destination")).toBeNull();++ act(() =>+ useModelsStore.getState().applyDownloadEvent({+ kind: "state",+ identifier: "vendor/model",+ phase: modelDownloadPhases.downloaded,+ completedBytes: 102400,+ totalBytes: 102400,+ error: null,+ seq: 1,+ }),+ );+ expect(destination()).toEqual({+ to: "/chat/$chatId",+ params: { chatId: expect.any(String) },+ search: { isNew: true },+ replace: true,+ });+});++it("opens a new chat from an installed model in the first snapshot without waiting for catalog refresh", async () => {+ getModels.mockResolvedValueOnce({+ models: [model(modelDownloadPhases.downloaded)],+ complete: false,+ refreshing: true,+ });+ render(<HomePage />);+ await act(() => useModelsStore.getState().fetchModels());+ expect(destination().to).toBe("/chat/$chatId");+});++it("opens Models only after pending downloads are confirmed absent", async () => {+ getModels.mockResolvedValueOnce({+ models: [model(modelDownloadPhases.initializing)],+ complete: true,+ refreshing: false,+ });+ render(<HomePage />);+ await act(() => useModelsStore.getState().fetchModels());+ expect(screen.queryByTestId("destination")).toBeNull();+ act(() =>+ useModelsStore.getState().applyDownloadEvent({+ kind: "state",+ identifier: "vendor/model",+ phase: modelDownloadPhases.notDownloaded,+ completedBytes: 0,+ totalBytes: 102400,+ error: null,+ seq: 1,+ }),+ );+ expect(destination()).toEqual({ to: "/local-models", replace: true });+});++it.each([true, false])("opens Models for an empty settled catalog (complete: %s)", async (complete) => {+ getModels.mockResolvedValueOnce({ models: [], complete, refreshing: false });+ render(<HomePage />);+ await act(() => useModelsStore.getState().fetchModels());+ expect(destination()).toEqual({ to: "/local-models", replace: true });+});++it("opens Models after discovery fails instead of waiting indefinitely", async () => {+ getModels.mockRejectedValueOnce(new Error("Catalog unavailable"));+ render(<HomePage />);+ await act(() => useModelsStore.getState().fetchModels());+ expect(destination()).toEqual({ to: "/local-models", replace: true });+});diff --git a/apps/mirai-gui/client/src/routes/index.tsx b/apps/mirai-gui/client/src/routes/index.tsxindex 511a100dc..2b6c9de6b 100644--- a/apps/mirai-gui/client/src/routes/index.tsx+++ b/apps/mirai-gui/client/src/routes/index.tsx@@ -1,10 +1,46 @@+import { Loader } from "@/components/loader";import { platformInfo } from "@/platform/platform-info";+import { useModelsStore } from "@/stores/use-models-store";+import { modelDownloadPhases } from "@/types/model-manager";import { createFileRoute, Navigate } from "@tanstack/react-router";+import { useState } from "react";+import { v4 as uuidv4 } from "uuid";export const Route = createFileRoute("/")({component: HomePage,});function HomePage() {- return <Navigate to={platformInfo.isWeb ? "/chats" : "/local-models"} />;+ const [chatId] = useState(() => uuidv4());+ const models = useModelsStore((s) => s.models);+ const modelPhasesById = useModelsStore((s) => s.modelPhasesById);+ const initialized = useModelsStore((s) => s.initialized);+ const catalogComplete = useModelsStore((s) => s.catalogComplete);+ const catalogRefreshing = useModelsStore((s) => s.catalogRefreshing);+ const error = useModelsStore((s) => s.error);++ if (platformInfo.isWeb) return <Navigate to="/chats" replace />;++ if (models.some((model) => modelPhasesById[model.repoId] === modelDownloadPhases.downloaded)) {+ return <Navigate to="/chat/$chatId" params={{ chatId }} search={{ isNew: true }} replace />;+ }++ const checkingModels =+ !initialized ||+ (!error &&+ ((!catalogComplete && catalogRefreshing) ||+ models.some((model) => {+ const phase = modelPhasesById[model.repoId];+ return phase === undefined || phase === modelDownloadPhases.initializing;+ })));++ if (checkingModels) {+ return (+ <div className="flex h-full items-center justify-center">+ <Loader text="Checking available models…" />+ </div>+ );+ }++ return <Navigate to="/local-models" replace />;}diff --git a/apps/mirai-gui/client/src/routes/welcome.tsx b/apps/mirai-gui/client/src/routes/welcome.tsxdeleted file mode 100644index dc766cff8..000000000--- a/apps/mirai-gui/client/src/routes/welcome.tsx+++ /dev/null@@ -1,6 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";-import { WelcomePage } from "@/features/welcome/components/welcome-page";--export const Route = createFileRoute("/welcome")({- component: WelcomePage,-});diff --git a/apps/mirai-gui/client/src/stores/migrate-app-storage.ts b/apps/mirai-gui/client/src/stores/migrate-app-storage.tsindex 134bcc079..6be88d374 100644--- a/apps/mirai-gui/client/src/stores/migrate-app-storage.ts+++ b/apps/mirai-gui/client/src/stores/migrate-app-storage.ts@@ -26,12 +26,9 @@ const migrateAppStorage = (): void => {}const legacyApp = readState(LEGACY_APP_STORE_KEY);- const legacyAuth = readState(LEGACY_AUTH_STORE_KEY);const state: Record<string, unknown> = {};if (typeof legacyApp?.isDarkMode === "boolean") state.isDarkMode = legacyApp.isDarkMode;- const skipWelcome = legacyApp?.skipWelcome ?? legacyAuth?.skipWelcome;- if (typeof skipWelcome === "boolean") state.skipWelcome = skipWelcome;if (Object.keys(state).length > 0) {localStorage.setItem(APP_STORE_KEY, JSON.stringify({ state, version: 0 }));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.tsindex 2295cc5a7..9708e7cf1 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@@ -13,11 +13,10 @@ afterEach(() => vi.unstubAllGlobals());it("defaults to Medium and persists the pixel width with existing preferences", () => {expect(useAppStore.getState().chatWidth).toBe(1000);- useAppStore.setState({ theme: "light", isDarkMode: false, skipWelcome: true });+ useAppStore.setState({ theme: "light", isDarkMode: false });useAppStore.getState().setChatWidth(1200);expect(JSON.parse(localStorage.getItem(APP_STORE_KEY)!).state).toEqual({theme: "light",- skipWelcome: true,chatWidth: 1200,});});@@ -32,12 +31,9 @@ it.each([800, 1000, 1200])("restores the saved %s pixel width on hydration", asyit.each([undefined, null, 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, skipWelcome: true }, version: 0 }),- );+ localStorage.setItem(APP_STORE_KEY, JSON.stringify({ state: { chatWidth, isDarkMode: false }, version: 0 }));await useAppStore.persist.rehydrate();- expect(useAppStore.getState()).toMatchObject({ chatWidth: 1000, isDarkMode: false, skipWelcome: true });+ expect(useAppStore.getState()).toMatchObject({ chatWidth: 1000, isDarkMode: false });},);@@ -47,12 +43,12 @@ it.each([799, 1201, Number.NaN, Number.POSITIVE_INFINITY])("rejects invalid settexpect(JSON.parse(localStorage.getItem(APP_STORE_KEY)!).state.chatWidth).toBe(1000);});-it("preserves legacy appearance and welcome migration while adding the wider default", async () => {+it("preserves legacy appearance and removes obsolete auth storage while adding the wider default", async () => {localStorage.setItem("mirai-electron-store", JSON.stringify({ state: { isDarkMode: false }, version: 0 }));- localStorage.setItem("mirai-auth-store", JSON.stringify({ state: { skipWelcome: true }, version: 0 }));+ localStorage.setItem("mirai-auth-store", JSON.stringify({ state: {}, version: 0 }));migrateAppStorage();await useAppStore.persist.rehydrate();- expect(useAppStore.getState()).toMatchObject({ chatWidth: 1000, isDarkMode: false, skipWelcome: true });+ expect(useAppStore.getState()).toMatchObject({ chatWidth: 1000, isDarkMode: false });expect(localStorage.getItem("mirai-electron-store")).toBeNull();expect(localStorage.getItem("mirai-auth-store")).toBeNull();});diff --git a/apps/mirai-gui/client/src/stores/use-app-store.ts b/apps/mirai-gui/client/src/stores/use-app-store.tsindex 706ea8116..98e739956 100644--- a/apps/mirai-gui/client/src/stores/use-app-store.ts+++ b/apps/mirai-gui/client/src/stores/use-app-store.ts@@ -23,8 +23,6 @@ export const isDarkTheme = (const isChatWidth = (value: unknown): value is ChatWidth => value === 800 || value === 1000 || value === 1200;type AppState = {- skipWelcome: boolean;- completeWelcome: () => void;isDarkMode: boolean;theme: ThemeMode;setTheme: (theme: ThemeMode) => void;@@ -41,13 +39,11 @@ migrateAppStorage();export const useAppStore = create<AppState>()(persist((set) => ({- skipWelcome: false,theme: "system",isDarkMode: isDarkTheme("system"),chatWidth: DEFAULT_CHAT_WIDTH,appVersion: "",- completeWelcome: () => set({ skipWelcome: true }),setChatWidth: (width) => set({ chatWidth: isChatWidth(width) ? width : DEFAULT_CHAT_WIDTH }),setTheme: (theme) => set({ theme, isDarkMode: isDarkTheme(theme) }),@@ -65,7 +61,6 @@ export const useAppStore = create<AppState>()(name: APP_STORE_KEY,partialize: (state) => ({theme: state.theme,- skipWelcome: state.skipWelcome,chatWidth: state.chatWidth,}),merge: (persisted, current) => {@@ -74,7 +69,6 @@ export const useAppStore = create<AppState>()(const { chatWidth } = stored;return {...current,- skipWelcome: stored.skipWelcome ?? current.skipWelcome,theme,isDarkMode: isDarkTheme(theme),chatWidth: isChatWidth(chatWidth) ? chatWidth : DEFAULT_CHAT_WIDTH,diff --git a/apps/mirai-gui/client/src/types/llm-stream.ts b/apps/mirai-gui/client/src/types/llm-stream.tsindex 3d4dfb0c7..0ac6195fb 100644--- a/apps/mirai-gui/client/src/types/llm-stream.ts+++ b/apps/mirai-gui/client/src/types/llm-stream.ts@@ -13,6 +13,7 @@ export type LlmRunParams = {};export type SessionOutputStats = {+ tokensPerForwardPass?: number;prefillStats: {duration: number;tokensCount: number;diff --git a/apps/mirai-gui/client/src/types/message.ts b/apps/mirai-gui/client/src/types/message.tsindex ae4cd9823..03722dd4b 100644--- a/apps/mirai-gui/client/src/types/message.ts+++ b/apps/mirai-gui/client/src/types/message.ts@@ -11,6 +11,7 @@ export type PerfStats = {totalSec?: number;tps?: number;tokensOut?: number;+ tokensPerForwardPass?: number;};export type MessageVersion = {diff --git a/apps/mirai-gui/desktop/src/chat/payloads.rs b/apps/mirai-gui/desktop/src/chat/payloads.rsindex 168447d0a..f10809d1e 100644--- a/apps/mirai-gui/desktop/src/chat/payloads.rs+++ b/apps/mirai-gui/desktop/src/chat/payloads.rs@@ -120,6 +120,8 @@ pub struct SessionOutputStats {pub prefill_stats: RunStatsSection,pub generate_stats: RunStatsSection,pub total_stats: TotalStats,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub tokens_per_forward_pass: Option<f64>,}#[derive(Serialize, Clone)]@@ -198,6 +200,7 @@ pub(super) fn map_reply_stats(reply: Option<&ChatReply>) -> SessionOutputStats {tokens_count_input: input_tokens,tokens_count_output: output_tokens,},+ tokens_per_forward_pass: stats.and_then(|s| s.speculator_stats.as_ref()).map(|s| s.tokens_per_forward_pass),}}@@ -261,6 +264,32 @@ pub(super) fn test_message(mod tests {use super::*;+ #[test]+ fn maps_inference_timing_and_optional_acceptance() {+ use uzu::types::session::chat::{ChatMessage, ChatReplySpeculatorStats, ChatReplyStats};++ let mut reply = ChatReply {+ message: ChatMessage::assistant(),+ stats: ChatReplyStats {+ duration: 2.25,+ time_to_first_token: Some(0.25),+ ..Default::default()+ },+ finish_reason: None,+ };+ let stats = map_reply_stats(Some(&reply));+ assert_eq!(stats.prefill_stats.duration, 0.25);+ assert_eq!(stats.generate_stats.duration, 2.0);+ assert!(serde_json::to_value(stats).unwrap().get("tokensPerForwardPass").is_none());++ reply.stats.speculator_stats = Some(ChatReplySpeculatorStats {+ tokens_per_forward_pass: 2.5,+ num_decode_forward_passes: 4,+ });+ let stats = serde_json::to_value(map_reply_stats(Some(&reply))).unwrap();+ assert_eq!(stats["tokensPerForwardPass"], 2.5);+ }+#[test]fn omitted_tool_preferences_remain_distinct_from_explicit_choices() {let payload = |extra: serde_json::Value| {diff --git a/apps/mirai-gui/desktop/src/cli_installer/mod.rs b/apps/mirai-gui/desktop/src/cli_installer/mod.rsindex d778e108a..fb92308c9 100644--- a/apps/mirai-gui/desktop/src/cli_installer/mod.rs+++ b/apps/mirai-gui/desktop/src/cli_installer/mod.rs@@ -103,25 +103,6 @@ fn install_wrapper() -> AppResult<()> {Ok(())}-fn install_declined() -> bool {- crate::storage::settings_load()- .ok()- .and_then(|s| s.get("cliInstallDeclined").and_then(|v| v.as_bool()))- .unwrap_or(false)-}--fn persist_declined(declined: bool) {- if let Err(e) = crate::storage::settings_merge(serde_json::Map::from_iter([(- "cliInstallDeclined".to_string(),- declined.into(),- )])) {- crate::logger::warn(- "cli-installer:settings-write-failed",- Some(serde_json::json!({ "declined": declined, "error": e })),- );- }-}-#[derive(Serialize)]#[serde(rename_all = "kebab-case")]pub enum CliStatus {@@ -166,7 +147,6 @@ pub async fn cli_install(app: AppHandle) -> AppResult<CliInstalled> {let result = tokio::task::spawn_blocking(install_wrapper).await.map_err(AppError::msg)?;match &result {Ok(()) => {- persist_declined(false);crate::logger::info("cli-installer:installed", Some(serde_json::json!({ "source": "settings" })));},Err(AppError::Authorization(AuthError::Cancelled)) => {@@ -188,42 +168,6 @@ pub async fn cli_install(app: AppHandle) -> AppResult<CliInstalled> {}}-pub fn trigger_if_needed(app: &AppHandle) {- if !available(app) {- return;- }- tauri::async_runtime::spawn(async move {- // Let the window come up before the admin prompt appears.- tokio::time::sleep(std::time::Duration::from_secs(3)).await;- match wrapper_state() {- WrapperState::Current => {- crate::logger::info("cli-installer:skip", Some(serde_json::json!({ "reason": "installed" })));- },- WrapperState::Foreign => {- crate::logger::warn("cli-installer:skip", Some(serde_json::json!({ "reason": "foreign-binary" })));- },- WrapperState::Missing => {- if install_declined() {- crate::logger::info("cli-installer:skip", Some(serde_json::json!({ "reason": "declined" })));- return;- }- crate::logger::info("cli-installer:prompt", Some(serde_json::json!({ "reason": "install" })));- match tokio::task::spawn_blocking(install_wrapper).await {- Ok(Ok(())) => crate::logger::info("cli-installer:installed", None),- Ok(Err(AppError::Authorization(AuthError::Cancelled))) => {- crate::logger::info("cli-installer:declined", None);- persist_declined(true);- },- Ok(Err(e)) => crate::logger::warn("cli-installer:failed", Some(serde_json::json!({ "error": e }))),- Err(e) => {- crate::logger::warn("cli-installer:failed", Some(serde_json::json!({ "error": e.to_string() })))- },- }- },- }- });-}-#[cfg(test)]mod tests {use super::{WRAPPER_MARKER, WrapperState, wrapper_state_at};diff --git a/apps/mirai-gui/desktop/src/lib.rs b/apps/mirai-gui/desktop/src/lib.rsindex 1a400973b..16db5bf5c 100644--- a/apps/mirai-gui/desktop/src/lib.rs+++ b/apps/mirai-gui/desktop/src/lib.rs@@ -95,7 +95,6 @@ pub fn run() {}chat::restore_auto_eject_config(app.handle());app.state::<analytics::AnalyticsState>().restore();- cli_installer::trigger_if_needed(app.handle());// Warm the engine so the first models/chat request doesn't pay init latency.tauri::async_runtime::spawn(async {let _ = engine::engine().await;diff --git a/crates/legacy/nagare/src/chat/token.rs b/crates/legacy/nagare/src/chat/token.rsindex a78c58545..d426217bf 100644--- a/crates/legacy/nagare/src/chat/token.rs+++ b/crates/legacy/nagare/src/chat/token.rs@@ -477,15 +477,7 @@ impl StreamingState<'_> {&mut self,last_stat: bool,) -> Result<ChatReplyStats, ChatSessionError> {- let speculator_stats = if let Some(metrics) = self.metrics.as_ref() {- let num_forward_passes = metrics.num_prefill_forward_passes + metrics.num_decode_forward_passes;- (num_forward_passes > 0).then(|| ChatReplySpeculatorStats {- tokens_per_forward_pass: metrics.num_tokens_accepted as f64 / num_forward_passes as f64,- num_decode_forward_passes: num_forward_passes as u32,- })- } else {- None- };+ let speculator_stats = self.metrics.as_ref().and_then(speculator_stats);let total_duration = self.time_last_token.unwrap_or(Instant::now()).duration_since(self.time_start);let ttft_duration =@@ -535,6 +527,14 @@ impl StreamingState<'_> {}}+fn speculator_stats(metrics: &TokenStreamMetrics) -> Option<ChatReplySpeculatorStats> {+ let num_forward_passes = metrics.num_prefill_forward_passes + metrics.num_decode_forward_passes;+ (num_forward_passes > 0 && metrics.num_tokens_proposed > num_forward_passes).then(|| ChatReplySpeculatorStats {+ tokens_per_forward_pass: metrics.num_tokens_accepted as f64 / num_forward_passes as f64,+ num_decode_forward_passes: num_forward_passes as u32,+ })+}+fn calculate_rate(tokens: usize,duration: Option<Duration>,@@ -550,3 +550,31 @@ fn calculate_rate(Some((tokens - 1) as f64 / duration.as_secs_f64())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn acceptance_is_reported_only_after_speculative_proposals() {+ assert!(speculator_stats(&TokenStreamMetrics::default()).is_none());+ let metrics = TokenStreamMetrics {+ num_prefill_forward_passes: 1,+ num_decode_forward_passes: 3,+ num_tokens_proposed: 4,+ num_tokens_accepted: 4,+ ..Default::default()+ };+ assert!(speculator_stats(&metrics).is_none());+ for accepted in [4, 10] {+ let speculative = TokenStreamMetrics {+ num_tokens_proposed: 16,+ num_tokens_accepted: accepted,+ ..metrics.clone()+ };+ let stats = speculator_stats(&speculative).unwrap();+ assert_eq!(stats.tokens_per_forward_pass, accepted as f64 / 4.0);+ assert_eq!(stats.num_decode_forward_passes, 4);+ }+ }+}diff --git a/scripts/mirai-data.py b/scripts/mirai-data.pynew file mode 100755index 000000000..0e7232558--- /dev/null+++ b/scripts/mirai-data.py@@ -0,0 +1,163 @@+#!/usr/bin/env python3+"""Move Mirai data aside for a fresh-start preview, then restore over test data."""++import argparse+import json+import os+from pathlib import Path+import shutil+import subprocess+import tempfile+++PATHS = {+ "app": "Library/Application Support/mirai",+ "cache": ".cache/mirai",+ "webview": "Library/WebKit/com.mirai.tech.chat",+ "webview-cache": "Library/Caches/com.mirai.tech.chat",+ "tauri": "Library/Application Support/com.mirai.tech.chat",+ "preferences": "Library/Preferences/com.mirai.tech.chat.plist",+ "window-state": "Library/Saved Application State/com.mirai.tech.chat.savedState",+}+MANIFEST = "manifest.json"+++def exists(path):+ return os.path.lexists(path)+++def check_location(data_home, backup_dir):+ for relative in PATHS.values():+ source = (data_home / relative).resolve()+ if source == backup_dir or source in backup_dir.parents or backup_dir in source.parents:+ raise ValueError(f"Backup directory overlaps Mirai data: {source}")+++def check_filesystem(paths, directory):+ device = directory.stat().st_dev+ for path in paths:+ if exists(path) and path.lstat().st_dev != device:+ raise ValueError(f"Choose a backup directory on the same filesystem as {path}")+++def move(source, destination, moved):+ if exists(destination):+ raise ValueError(f"Move destination already exists: {destination}")+ destination.parent.mkdir(parents=True, exist_ok=True)+ source.rename(destination)+ moved.append((source, destination))+++def rollback(moved):+ for source, destination in reversed(moved):+ if exists(source):+ raise ValueError(f"Cannot roll back over {source}; recovery data remains at {destination}")+ source.parent.mkdir(parents=True, exist_ok=True)+ destination.rename(source)+++def backup(data_home, backup_dir, keep_cache=False):+ check_location(data_home, backup_dir)+ entries = {+ name: exists(data_home / relative)+ for name, relative in PATHS.items()+ if not (keep_cache and name == "cache")+ }+ backup_dir.mkdir(mode=0o700, parents=True, exist_ok=False)+ moved = []+ try:+ check_filesystem((data_home / PATHS[name] for name in entries), backup_dir)+ for name, present in entries.items():+ if present:+ move(data_home / PATHS[name], backup_dir / name, moved)+ (backup_dir / MANIFEST).write_text(json.dumps({+ "version": 1,+ "home": str(data_home),+ "entries": entries,+ }, indent=2) + "\n")+ except BaseException:+ rollback(moved)+ (backup_dir / MANIFEST).unlink(missing_ok=True)+ backup_dir.rmdir()+ raise+ print(f"Moved Mirai data to {backup_dir}")+ if keep_cache:+ print("Left ~/.cache/mirai in place; restore will also leave it untouched.")+++def restore(data_home, backup_dir):+ check_location(data_home, backup_dir)+ manifest = json.loads((backup_dir / MANIFEST).read_text())+ if not isinstance(manifest, dict) or manifest.get("version") != 1 or manifest.get("home") != str(data_home):+ raise ValueError("Backup version or home directory does not match")+ entries = manifest.get("entries")+ if (+ not isinstance(entries, dict)+ or set(entries) not in (set(PATHS), set(PATHS) - {"cache"})+ or any(type(value) is not bool for value in entries.values())+ ):+ raise ValueError("Invalid backup manifest")+ expected = {MANIFEST} | {name for name, present in entries.items() if present}+ if {path.name for path in backup_dir.iterdir()} != expected:+ raise ValueError("Backup contents do not match the manifest; no current data was changed")++ staging = Path(tempfile.mkdtemp(prefix=".mirai-restore-", dir=backup_dir.parent))+ moved = []+ try:+ check_filesystem((data_home / PATHS[name] for name in entries), staging)+ check_filesystem((backup_dir / name for name, present in entries.items() if present), staging)+ for name in entries:+ current = data_home / PATHS[name]+ if exists(current):+ move(current, staging / name, moved)+ for name, present in entries.items():+ if present:+ move(backup_dir / name, data_home / PATHS[name], moved)+ move(backup_dir / MANIFEST, staging / MANIFEST, moved)+ backup_dir.rmdir()+ except BaseException:+ rollback(moved)+ staging.rmdir()+ raise+ shutil.rmtree(staging)+ print("Restored Mirai data, replacing the test data. Backup consumed.")+ if "cache" not in entries:+ print("Left the current ~/.cache/mirai untouched.")+++def main():+ parser = argparse.ArgumentParser(+ description=__doc__,+ epilog="Quit Mirai, the CLI, and other apps using its shared cache before either operation. "+ "Use a new backup directory on the same filesystem as the data. "+ "restore-overwrite discards current test data and consumes the backup.",+ )+ parser.add_argument("action", choices=("backup", "restore-overwrite"))+ parser.add_argument("backup_dir", type=Path)+ parser.add_argument(+ "--keep-cache", action="store_true",+ help="backup only: leave ~/.cache/mirai in place; restore preserves it too",+ )+ args = parser.parse_args()+ if args.keep_cache and args.action != "backup":+ parser.error("--keep-cache is only for backup; restore follows the saved manifest")+ data_home = Path.home().resolve()+ backup_dir = args.backup_dir.expanduser().resolve()+ try:+ running = subprocess.run(+ ["pgrep", "-x", "Mirai|mirai-gui|mirai|cli"], capture_output=True, text=True,+ )+ if running.returncode == 0:+ raise ValueError(f"Quit Mirai and the CLI first (PIDs: {', '.join(running.stdout.split())})")+ if running.returncode != 1:+ raise ValueError(f"Cannot check for running Mirai processes: {running.stderr.strip()}")+ if args.action == "backup":+ backup(data_home, backup_dir, args.keep_cache)+ else:+ restore(data_home, backup_dir)+ except (OSError, ValueError) as error:+ parser.exit(1, f"error: {error}\n")+++if __name__ == "__main__":+ main()