Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Mac app fixes and improvements (part 2) (#920)

uuuvnb5ceffeb7f92
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 5577a3828..48baac5bf 100644
--- a/apps/mirai-gui/client/src/components/left-bar/index.tsx
+++ b/apps/mirai-gui/client/src/components/left-bar/index.tsx
@@ -82,7 +82,7 @@ function LeftBar() {
<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-[200px]" : "w-0",
+ !isMobile && isSidebarOpen ? "w-62" : "w-0",
)}
>
{toggleSidebarButton}
@@ -100,7 +100,7 @@ function LeftBar() {
data-tauri-drag-region
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-[200px]",
+ isMobile ? "fixed top-0 left-0 h-dvh w-[280px] z-50" : "h-full w-62",
isSidebarOpen ? "translate-x-0" : "-translate-x-full",
)}
>
diff --git a/apps/mirai-gui/client/src/components/ui/button/constants.ts b/apps/mirai-gui/client/src/components/ui/button/constants.ts
index 38db3bde6..08bee0b00 100644
--- a/apps/mirai-gui/client/src/components/ui/button/constants.ts
+++ b/apps/mirai-gui/client/src/components/ui/button/constants.ts
@@ -26,7 +26,7 @@ export const KIND_STYLES: Record<ButtonKind, string> = {
export const DISABLED_STYLES = "opacity-50 cursor-not-allowed pointer-events-none";
export const LOADING_STYLES = "cursor-wait pointer-events-none";
export const BASE_STYLES =
- "inline-flex shrink-0 items-center justify-center whitespace-nowrap select-none outline-hidden antialiased transition-all duration-150 ease-out will-change-transform touch-manipulation focus-visible:shadow-focus [&_svg]:pointer-events-none [&_svg]:shrink-0";
+ "inline-flex shrink-0 items-center justify-center whitespace-nowrap select-none outline-hidden antialiased transition-all duration-150 ease-out will-change-transform touch-manipulation data-[focus]:shadow-focus [&_svg]:pointer-events-none [&_svg]:shrink-0";
export const FULL_WIDTH_STYLES = "w-full";
export const SPINNER_SIZE_MAP: Record<ButtonSize, number> = {
diff --git a/apps/mirai-gui/client/src/components/ui/button/index.test.tsx b/apps/mirai-gui/client/src/components/ui/button/index.test.tsx
new file mode 100644
index 000000000..91c97d492
--- /dev/null
+++ b/apps/mirai-gui/client/src/components/ui/button/index.test.tsx
@@ -0,0 +1,89 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { createRef } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { Button } from ".";
+
+afterEach(cleanup);
+
+it("restores focus after pointer interaction without showing a keyboard ring", () => {
+ const onFocus = vi.fn();
+ const ref = createRef<HTMLButtonElement>();
+ render(
+ <>
+ <Button ref={ref} onFocus={onFocus}>
+ Settings
+ </Button>
+ <button type="button">Close</button>
+ </>,
+ );
+ const trigger = screen.getByRole("button", { name: "Settings" });
+ const close = screen.getByRole("button", { name: "Close" });
+
+ fireEvent.mouseDown(trigger);
+ act(() => trigger.focus());
+ fireEvent.mouseDown(close);
+ act(() => close.focus());
+ act(() => ref.current?.focus());
+
+ expect(document.activeElement).toBe(trigger);
+ expect(trigger.hasAttribute("data-focus")).toBe(false);
+ expect(onFocus).toHaveBeenCalledTimes(2);
+});
+
+it("keeps keyboard-restored focus visible until pointer interaction", () => {
+ render(
+ <>
+ <Button>Settings</Button>
+ <button type="button">Close</button>
+ </>,
+ );
+ const trigger = screen.getByRole("button", { name: "Settings" });
+ const close = screen.getByRole("button", { name: "Close" });
+
+ fireEvent.keyDown(document, { key: "Tab" });
+ act(() => trigger.focus());
+ act(() => close.focus());
+ fireEvent.keyDown(close, { key: "Escape" });
+ act(() => trigger.focus());
+
+ expect(document.activeElement).toBe(trigger);
+ expect(trigger.hasAttribute("data-focus")).toBe(true);
+ fireEvent.mouseDown(trigger);
+ expect(trigger.hasAttribute("data-focus")).toBe(false);
+});
+
+it("preserves anchor refs, keyboard focus, and disabled/loading behavior", () => {
+ const ref = createRef<HTMLAnchorElement>();
+ const onClick = vi.fn();
+ const { rerender } = render(
+ <Button href="/settings" ref={ref} onClick={onClick}>
+ Settings
+ </Button>,
+ );
+ const link = screen.getByRole("link", { name: "Settings" });
+
+ fireEvent.keyDown(document, { key: "Tab" });
+ act(() => ref.current?.focus());
+ expect(document.activeElement).toBe(link);
+ expect(link.hasAttribute("data-focus")).toBe(true);
+
+ rerender(
+ <Button href="/settings" ref={ref} onClick={onClick} loading>
+ Settings
+ </Button>,
+ );
+ expect(ref.current?.hasAttribute("href")).toBe(false);
+ expect(ref.current?.tabIndex).toBe(-1);
+ fireEvent.click(ref.current!);
+ expect(onClick).not.toHaveBeenCalled();
+
+ rerender(
+ <Button disabled onClick={onClick}>
+ Settings
+ </Button>,
+ );
+ const button = screen.getByRole("button", { name: "Settings" }) as HTMLButtonElement;
+ expect(button.disabled).toBe(true);
+ fireEvent.click(button);
+ expect(onClick).not.toHaveBeenCalled();
+});
diff --git a/apps/mirai-gui/client/src/components/ui/button/index.tsx b/apps/mirai-gui/client/src/components/ui/button/index.tsx
index 3a826dbe5..28f0841cd 100644
--- a/apps/mirai-gui/client/src/components/ui/button/index.tsx
+++ b/apps/mirai-gui/client/src/components/ui/button/index.tsx
@@ -1,4 +1,5 @@
import { forwardRef } from "react";
+import { Button as HeadlessButton, DataInteractive } from "@headlessui/react";
import { twMerge } from "tailwind-merge";
import { Spinner } from "../spinner";
import {
@@ -92,16 +93,18 @@ export const Button = forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonPr
const linkRel = target === "_blank" && !rel ? "noopener noreferrer" : rel;
const linkProps = isLinkInteractive ? { href, target, rel: linkRel, onClick } : { tabIndex: -1 };
return (
- <a ref={ref as React.Ref<HTMLAnchorElement>} {...linkProps} {...commonProps} {...restLinkProps}>
- {content}
- </a>
+ <DataInteractive>
+ <a ref={ref as React.Ref<HTMLAnchorElement>} {...linkProps} {...commonProps} {...restLinkProps}>
+ {content}
+ </a>
+ </DataInteractive>
);
}
const { type = "button", onClick, ...restButtonProps } = rest as ButtonPassthroughProps;
return (
- <button
+ <HeadlessButton
ref={ref as React.Ref<HTMLButtonElement>}
type={type}
disabled={disabled || loading}
@@ -110,6 +113,6 @@ export const Button = forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonPr
{...restButtonProps}
>
{content}
- </button>
+ </HeadlessButton>
);
});
diff --git a/apps/mirai-gui/client/src/components/ui/checkbox/constants.ts b/apps/mirai-gui/client/src/components/ui/checkbox/constants.ts
index 95f432bce..18703c4ff 100644
--- a/apps/mirai-gui/client/src/components/ui/checkbox/constants.ts
+++ b/apps/mirai-gui/client/src/components/ui/checkbox/constants.ts
@@ -11,4 +11,4 @@ export const CHECKED_BORDER = "border-primary";
export const UNCHECKED_BORDER = "border-border-strong";
-export const FOCUS_RING = "focus-visible:shadow-focus";
+export const FOCUS_RING = "data-[focus]:shadow-focus";
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 e54107f07..8dc9e3e3d 100644
--- a/apps/mirai-gui/client/src/components/ui/checkbox/index.tsx
+++ b/apps/mirai-gui/client/src/components/ui/checkbox/index.tsx
@@ -1,4 +1,5 @@
import { twMerge } from "tailwind-merge";
+import { DataInteractive } from "@headlessui/react";
import { IconCheckmark } from "../../icons/checkmark-icon";
import { CHECKBOX_SIZE, CHECKED_BG, CHECKED_BORDER, FOCUS_RING, UNCHECKED_BORDER } from "./constants";
import type { CheckboxProps } from "./types";
@@ -24,15 +25,17 @@ export function Checkbox({
return (
<span className="relative inline-flex shrink-0 items-center justify-center">
- <input
- type="checkbox"
- className={boxClasses}
- checked={checked}
- onChange={(e) => onChange(e.target.checked)}
- disabled={disabled}
- aria-checked={checked}
- aria-label={ariaLabel}
- />
+ <DataInteractive>
+ <input
+ type="checkbox"
+ className={boxClasses}
+ checked={checked}
+ onChange={(e) => onChange(e.target.checked)}
+ disabled={disabled}
+ aria-checked={checked}
+ aria-label={ariaLabel}
+ />
+ </DataInteractive>
<IconCheckmark
strokeWidth={2.5}
size={sizeConfig.icon}
diff --git a/apps/mirai-gui/client/src/components/ui/icon-button.tsx b/apps/mirai-gui/client/src/components/ui/icon-button.tsx
index 40f66701d..37b2c0d9b 100644
--- a/apps/mirai-gui/client/src/components/ui/icon-button.tsx
+++ b/apps/mirai-gui/client/src/components/ui/icon-button.tsx
@@ -1,4 +1,5 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
+import { Button as HeadlessButton } from "@headlessui/react";
import { twMerge } from "tailwind-merge";
export type IconButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children"> & {
@@ -8,16 +9,16 @@ export type IconButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "chi
export function IconButton({ icon, children, className, ...rest }: IconButtonProps) {
return (
- <button
+ <HeadlessButton
{...rest}
className={twMerge(
- "inline-flex items-center gap-1 rounded-md p-0.5 bg-transparent text-gray-1000 outline-hidden focus-visible:shadow-focus",
+ "inline-flex items-center gap-1 rounded-md p-0.5 bg-transparent text-gray-1000 outline-hidden data-[focus]:shadow-focus",
"hover:text-gray-1200 active:scale-[0.97] disabled:opacity-50 transition-colors duration-200",
className,
)}
>
{icon && <span className="grid place-items-center">{icon}</span>}
{children}
- </button>
+ </HeadlessButton>
);
}
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 6e5f3edea..3981af91b 100644
--- a/apps/mirai-gui/client/src/components/ui/modal/index.tsx
+++ b/apps/mirai-gui/client/src/components/ui/modal/index.tsx
@@ -1,5 +1,12 @@
import { X } from "lucide-react";
-import { Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from "@headlessui/react";
+import {
+ Button as HeadlessButton,
+ Dialog,
+ DialogPanel,
+ DialogTitle,
+ Transition,
+ TransitionChild,
+} from "@headlessui/react";
import { Fragment } from "react";
import { twMerge } from "tailwind-merge";
import { Button } from "../button";
@@ -68,14 +75,14 @@ export function Modal(props: ModalProps) {
{title}
</Text>
</DialogTitle>
- <button
+ <HeadlessButton
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 focus-visible:shadow-focus cursor-pointer"
+ 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"
>
<X size={16} />
- </button>
+ </HeadlessButton>
</div>
{description && (
<Text as="p" color="muted" opticalSize={20} className="mt-1.5 text-[15px] font-[450] leading-[1.6]">
diff --git a/apps/mirai-gui/client/src/components/ui/toggle.tsx b/apps/mirai-gui/client/src/components/ui/toggle.tsx
index f7e0b000a..398e4f69f 100644
--- a/apps/mirai-gui/client/src/components/ui/toggle.tsx
+++ b/apps/mirai-gui/client/src/components/ui/toggle.tsx
@@ -1,4 +1,5 @@
import React from "react";
+import { Button as HeadlessButton } from "@headlessui/react";
import { twMerge } from "tailwind-merge";
type ToggleProps = {
@@ -12,7 +13,7 @@ type ToggleProps = {
export const Toggle: React.FC<ToggleProps> = ({ label, checked, onChange, disabled = false, className }) => {
return (
- <button
+ <HeadlessButton
type="button"
role="switch"
aria-label={label}
@@ -20,7 +21,7 @@ export const Toggle: React.FC<ToggleProps> = ({ label, checked, onChange, disabl
disabled={disabled}
onClick={() => !disabled && onChange(!checked)}
className={twMerge(
- "relative inline-flex min-h-6 min-w-11 items-center rounded-full transition-colors outline-hidden focus-visible:shadow-focus",
+ "relative inline-flex min-h-6 min-w-11 items-center rounded-full transition-colors outline-hidden data-[focus]:shadow-focus",
checked ? "bg-label-title" : "bg-button-border",
disabled && "opacity-50 cursor-not-allowed",
!disabled && "cursor-pointer",
@@ -33,6 +34,6 @@ export const Toggle: React.FC<ToggleProps> = ({ label, checked, onChange, disabl
checked ? "translate-x-[22px]" : "translate-x-[2px]",
)}
/>
- </button>
+ </HeadlessButton>
);
};
diff --git a/apps/mirai-gui/client/src/constants/chat.ts b/apps/mirai-gui/client/src/constants/chat.ts
index da6994f3c..4e961b141 100644
--- a/apps/mirai-gui/client/src/constants/chat.ts
+++ b/apps/mirai-gui/client/src/constants/chat.ts
@@ -1,4 +1 @@
export const UNTITLED_CHAT_TITLE = "Untitled";
-export const DEFAULT_CHAT_TITLE = "General Chat";
-export const CHAT_TITLE_MIN_LENGTH = 3;
-export const CHAT_TITLE_MAX_LENGTH = 50;
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 35a1b94d9..5188aff92 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,8 +1,8 @@
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 { CardContainer } from "@/components/ui/card-container";
import { twMerge } from "tailwind-merge";
type ChatCardProps = {
@@ -29,7 +29,8 @@ const ChatCard: React.FC<ChatCardProps> = ({
const timeAgo = formatDistanceToNow(updatedAt, { addSuffix: true });
return (
- <CardContainer
+ <DataInteractive
+ as="div"
key={id}
onClick={onClick}
// In select mode the checkbox is the focusable control, so the card must not
@@ -46,8 +47,8 @@ const ChatCard: React.FC<ChatCardProps> = ({
},
})}
className={twMerge(
- "bg-background cursor-pointer transition-colors border-[0.5px] border-cell-border",
- !selectMode && "outline-hidden focus-visible:shadow-focus",
+ "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" : "",
)}
@@ -76,7 +77,7 @@ const ChatCard: React.FC<ChatCardProps> = ({
<span className="text-xs text-label-muted font-mono whitespace-nowrap">{timeAgo}</span>
</div>
</div>
- </CardContainer>
+ </DataInteractive>
);
};
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 2f8f34163..fb60c2e14 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
@@ -165,7 +165,7 @@ export function ChatHistoryPage() {
<Button
kind="secondary"
size="sm"
- className="text-label-muted h-8 px-3 rounded-[8px] border border-cell-border text-sm leading-[150%]"
+ className="text-label-muted h-8 px-3 rounded-[8px] text-sm leading-[150%]"
onClick={() => setIsSelectionMode(true)}
>
Select
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/chat-rename-modal.test.tsx b/apps/mirai-gui/client/src/features/chat-history/components/chat-rename-modal.test.tsx
new file mode 100644
index 000000000..7f96329a8
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat-history/components/chat-rename-modal.test.tsx
@@ -0,0 +1,45 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { ChatRenameModal } from "./chat-rename-modal";
+
+afterEach(cleanup);
+
+it("accepts a title longer than the former hard limit without cutting it", async () => {
+ const onConfirm = vi.fn(async () => {});
+ render(<ChatRenameModal isOpen onClose={vi.fn()} onConfirm={onConfirm} currentName="Original title" />);
+ const title = "Detailed comparison of model throughput, response latency, and energy usage";
+ const input = screen.getByRole("textbox", { name: "Chat name" });
+ expect(input.getAttribute("maxlength")).toBeNull();
+ fireEvent.change(input, { target: { value: title } });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledWith(title));
+});
+
+it("preserves edits when the generated title changes, and refreshes it when reopened", async () => {
+ const onConfirm = vi.fn(async () => {});
+ const props = {
+ isOpen: true,
+ onClose: vi.fn(),
+ onConfirm,
+ currentName: "Original title",
+ };
+ const view = render(<ChatRenameModal {...props} />);
+ fireEvent.change(screen.getByRole("textbox", { name: "Chat name" }), { target: { value: " Mine " } });
+ const currentName = "Model rename";
+ view.rerender(<ChatRenameModal {...props} currentName={currentName} />);
+ expect((screen.getByRole("textbox", { name: "Chat name" }) as HTMLInputElement).value).toBe(" Mine ");
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledWith("Mine"));
+ view.rerender(<ChatRenameModal {...props} isOpen={false} currentName={currentName} />);
+ view.rerender(<ChatRenameModal {...props} currentName={currentName} />);
+ expect((screen.getByRole("textbox", { name: "Chat name" }) as HTMLInputElement).value).toBe("Model rename");
+});
+
+it("requires a nonempty title", async () => {
+ const onConfirm = vi.fn(async () => {});
+ render(<ChatRenameModal isOpen onClose={vi.fn()} onConfirm={onConfirm} currentName="Original title" />);
+ fireEvent.change(screen.getByRole("textbox", { name: "Chat name" }), { target: { value: " " } });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ expect(await screen.findByText("Name cannot be empty")).toBeDefined();
+ expect(onConfirm).not.toHaveBeenCalled();
+});
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/chat-rename-modal.tsx b/apps/mirai-gui/client/src/features/chat-history/components/chat-rename-modal.tsx
index 57c78b091..a9d791b5c 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/chat-rename-modal.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/chat-rename-modal.tsx
@@ -1,7 +1,6 @@
import { Modal } from "@/components/ui/modal";
import { TextField } from "@/components/ui/text-field";
import { useEffect, useRef, useState } from "react";
-import { CHAT_TITLE_MAX_LENGTH, CHAT_TITLE_MIN_LENGTH } from "@/constants/chat";
type ChatRenameModalProps = {
isOpen: boolean;
@@ -15,12 +14,14 @@ export const ChatRenameModal: React.FC<ChatRenameModalProps> = ({ isOpen, onClos
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
+ const wasOpen = useRef(false);
useEffect(() => {
- if (isOpen) {
+ if (isOpen && !wasOpen.current) {
setName(currentName);
setError("");
}
+ wasOpen.current = isOpen;
}, [isOpen, currentName]);
const submit = async () => {
@@ -29,14 +30,6 @@ export const ChatRenameModal: React.FC<ChatRenameModalProps> = ({ isOpen, onClos
setError("Name cannot be empty");
return;
}
- if (trimmed.length < CHAT_TITLE_MIN_LENGTH) {
- setError(`Name must be at least ${CHAT_TITLE_MIN_LENGTH} characters long`);
- return;
- }
- if (trimmed.length > CHAT_TITLE_MAX_LENGTH) {
- setError(`Name must be at most ${CHAT_TITLE_MAX_LENGTH} characters long`);
- return;
- }
try {
setIsSubmitting(true);
await onConfirm(trimmed);
@@ -75,12 +68,12 @@ export const ChatRenameModal: React.FC<ChatRenameModalProps> = ({ isOpen, onClos
error={error || undefined}
controlProps={{
ref: inputRef,
+ "aria-label": "Chat name",
value: name,
onChange: (e) => setName(e.target.value),
// The input mounts after open; select on the focus the dialog gives it.
onFocus: (e) => e.currentTarget.select(),
placeholder: "Enter chat name",
- maxLength: CHAT_TITLE_MAX_LENGTH,
disabled: isSubmitting,
fullWidth: true,
}}
diff --git a/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.test.tsx b/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.test.tsx
index 75d8d2dd9..8aac403dd 100644
--- a/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat-history/components/saved-chats.test.tsx
@@ -7,7 +7,7 @@ const { chatStore, navigate } = vi.hoisted(() => ({
savedChats: [{ id: "saved-chat", title: "Saved chat", createdAt: 0, updatedAt: 0, messageCount: 2 }],
loadSavedChats: vi.fn(),
deleteChat: vi.fn(async () => {}),
- updateChatTitle: vi.fn(),
+ updateChatTitle: vi.fn(async () => true),
},
navigate: vi.fn(),
}));
@@ -54,6 +54,16 @@ async function openMenu() {
return screen.findByRole("menu");
}
+it("renames inline without enforcing a minimum beyond a nonempty title", async () => {
+ render(<SavedChats />);
+ fireEvent.doubleClick(screen.getByText("Saved chat"));
+ const input = screen.getByRole("textbox");
+ fireEvent.change(input, { target: { value: "A" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ await waitFor(() => expect(chatStore.updateChatTitle).toHaveBeenCalledWith("saved-chat", "A"));
+});
+
it("keeps the open menu mounted while Shift is pressed and released", async () => {
const menu = await openMenu();
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 33c1b0519..d16c8fd28 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,10 +1,9 @@
import { Menu, MenuButton, MenuItem, MenuItems } from "@headlessui/react";
import { useNavigate, useParams } from "@tanstack/react-router";
import { Edit3, MoreHorizontal, Trash2 } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useChatStore } from "@/stores/use-chat-store";
import { useSidebarStore } from "@/stores/use-sidebar-store";
-import { CHAT_TITLE_MAX_LENGTH, CHAT_TITLE_MIN_LENGTH } from "@/constants/chat";
import { useShiftHeld } from "@/hooks/use-shift-held";
import { ChatDeleteModal } from "@/features/chat-history/components/chat-delete-modal";
import type { ChatMetadata } from "@/platform/services/storage";
@@ -27,11 +26,23 @@ export default function SavedChats() {
// Keep the measurement while collapsed so the title and sidebar start
// their transitions together when reopened.
- useEffect(() => {
- setChatVisibility(null);
+ useLayoutEffect(() => {
const root = scrollViewportRef.current;
const row = currentChatRowRef.current;
- if (!currentChatId || !currentChatExists || !root || !row || typeof IntersectionObserver === "undefined") return;
+ if (!currentChatId) {
+ setChatVisibility(null);
+ return;
+ }
+ if (!currentChatExists || !root || !row || typeof IntersectionObserver === "undefined") {
+ setChatVisibility({ chatId: currentChatId, ratio: 0 });
+ return;
+ }
+ // The observer's first callback can arrive after paint when entering a chat.
+ // Measure now so an already-visible sidebar title never flashes in the header.
+ const viewport = root.getBoundingClientRect();
+ const bounds = row.getBoundingClientRect();
+ const visibleHeight = Math.max(0, Math.min(bounds.bottom, viewport.bottom) - Math.max(bounds.top, viewport.top));
+ setChatVisibility({ chatId: currentChatId, ratio: bounds.height > 0 ? visibleHeight / bounds.height : 0 });
let active = true;
const observer = new IntersectionObserver(
([entry]) => {
@@ -89,12 +100,7 @@ export default function SavedChats() {
const chat = savedChats.find((c) => c.id === editingChatId);
const newTitle = draftTitle.trim();
cancelRename();
- if (
- !chat ||
- newTitle === chat.title ||
- newTitle.length < CHAT_TITLE_MIN_LENGTH ||
- newTitle.length > CHAT_TITLE_MAX_LENGTH
- ) {
+ if (!chat || !newTitle || newTitle === chat.title) {
return;
}
try {
@@ -168,14 +174,13 @@ export default function SavedChats() {
e.stopPropagation();
startRename(chat);
}}
- className={`flex items-center gap-3 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={`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"}`}
>
<div className="flex-1 min-w-0">
{editingChatId === chat.id ? (
<input
ref={renameInputRef}
value={draftTitle}
- maxLength={CHAT_TITLE_MAX_LENGTH}
onChange={(e) => setDraftTitle(e.target.value)}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
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
index 556002cff..9b9b0277d 100644
--- 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
@@ -6,7 +6,7 @@ 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" }));
+const route = vi.hoisted(() => ({ chatId: "first" as string | undefined }));
vi.mock("@tanstack/react-router", () => ({
useParams: () => route,
useNavigate: () => vi.fn(),
@@ -41,7 +41,7 @@ const Harness = () => {
return (
<>
<SavedChats />
- <ChatHeader title={`Chat ${route.chatId}`} isSidebarOpen={isOpen} />
+ {route.chatId && <ChatHeader title={`Chat ${route.chatId}`} isSidebarOpen={isOpen} />}
</>
);
};
@@ -71,6 +71,7 @@ beforeEach(() => {
afterEach(() => {
cleanup();
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
useChatStore.setState(chatDefaults, true);
useSidebarStore.setState(sidebarDefaults, true);
@@ -148,13 +149,55 @@ it("tracks the new active row on chat switches and clears visibility when it dis
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).toBeNull();
+ 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).toBeNull();
+ 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", () => {
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
index f341ab9dc..4bc714c23 100644
--- a/apps/mirai-gui/client/src/features/chat/components/chat-header.tsx
+++ b/apps/mirai-gui/client/src/features/chat/components/chat-header.tsx
@@ -20,8 +20,11 @@ export const ChatHeader = ({
}) => {
const { chatId } = useParams({ strict: false }) as { chatId?: string };
const chatVisibility = useSidebarStore((s) => s.chatVisibility);
- const sidebarVisibility =
- isSidebarOpen && chatVisibility && chatVisibility.chatId === chatId ? chatVisibility.ratio : 0;
+ 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);
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 887f9b278..52a6b6286 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,3 +1,4 @@
+import { Button } from "@headlessui/react";
import { Settings } from "lucide-react";
import { useCallback, useRef } from "react";
import { twMerge } from "tailwind-merge";
@@ -100,15 +101,15 @@ export function ChatInput({
) : null}
{onModelSettingsClick ? (
<span className="relative inline-flex shrink-0">
- <button
+ <Button
type="button"
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 focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-50"
+ 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"
>
<Settings size={16} />
- </button>
+ </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 81c50aeed..833da13ba 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
@@ -70,7 +70,7 @@ export function ModelPicker({
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:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface-tertiary"
+ 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"
>
{activeModel && (
<span className="shrink-0 flex items-center justify-center w-3.5 h-3.5 [&>svg]:w-3.5 [&>svg]:h-3.5">
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 f02ca6973..32c41eec3 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
@@ -65,7 +65,7 @@ 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:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface-tertiary"
+ 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"
>
<Brain size={14} aria-hidden="true" />
<span>{label}</span>
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 3719ad540..122d2c30c 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
@@ -9,6 +9,7 @@ import { AnimatePresence, motion } from "motion/react";
import { useEffect, useState, useId } from "react";
import { Toggle } from "@/components/ui/toggle";
import { RotateCcw } from "lucide-react";
+import { Button } from "@headlessui/react";
const TOP_K_MIN = 1;
const TOP_K_MAX = 4096;
@@ -54,15 +55,15 @@ const SectionHeading = ({ name, changed, onReset }: { name: string; changed: boo
<div className="flex h-5 items-center gap-1">
<span className="text-[12px] font-[450] text-label-muted">{name}</span>
{changed && (
- <button
+ <Button
type="button"
onClick={onReset}
aria-label={`Reset ${name.toLowerCase()} to defaults`}
title={`Reset ${name.toLowerCase()} to defaults`}
- className="inline-flex size-5 items-center justify-center rounded text-red-500 transition-colors hover:bg-red-500/10 outline-hidden focus-visible:shadow-focus"
+ className="inline-flex size-5 items-center justify-center rounded text-red-500 transition-colors hover:bg-red-500/10 outline-hidden data-[focus]:shadow-focus"
>
<RotateCcw aria-hidden="true" className="size-3" />
- </button>
+ </Button>
)}
</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 1b8e5ed77..265088e91 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
@@ -1,6 +1,6 @@
import { useInstalledPickerModels } from "../../hooks/use-picker-models";
import { useChatStore } from "@/stores/use-chat-store";
-import { Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from "@headlessui/react";
+import { Button, Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from "@headlessui/react";
import { ModelPicker } from "./chat-input/model-picker";
import { X } from "lucide-react";
import { Fragment, useEffect, useState } from "react";
@@ -74,13 +74,13 @@ export const ModelParamsDrawer = ({ open, chatId, repoId, onClose }: ModelParams
<DialogTitle as="h3" className="text-[17px] font-medium leading-[130%] text-label-title">
Edit parameters
</DialogTitle>
- <button
+ <Button
onClick={onClose}
- className="text-label-muted transition-colors hover:text-label-title"
+ className="text-label-muted transition-colors hover:text-label-title outline-hidden data-[focus]:shadow-focus"
aria-label="Close"
>
<X className="h-5 w-5" />
- </button>
+ </Button>
</div>
<div className="mt-4">
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
new file mode 100644
index 000000000..4c33310a5
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.test.tsx
@@ -0,0 +1,144 @@
+import { cleanup, render } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { memo, type ComponentProps } from "react";
+import { Block, useIsCodeFenceIncomplete, type BlockProps } from "streamdown";
+import { MarkdownBlock } from "./markdown-block";
+import { MarkdownRenderer } from "./markdown-renderer";
+
+const control = vi.hoisted(() => ({ stock: false }));
+const parsedBlocks = vi.hoisted(() => vi.fn());
+vi.mock("streamdown", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("streamdown")>();
+ const MeasuredBlock = memo(function MeasuredBlock(props: ComponentProps<typeof actual.Block>) {
+ parsedBlocks(props.content);
+ return <actual.Block {...props} />;
+ });
+ return {
+ ...actual,
+ Block: MeasuredBlock,
+ Streamdown: (props: ComponentProps<typeof actual.Streamdown>) => (
+ <actual.Streamdown {...props} BlockComponent={control.stock ? actual.Block : props.BlockComponent} />
+ ),
+ };
+});
+
+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, "><");
+ cleanup();
+ return output;
+};
+
+const fixtures = {
+ "one loose list item with many paragraphs": "- First paragraph.\n\n Second paragraph.\n\n Third paragraph.",
+ "multiple loose items": "- First.\n\n Another paragraph.\n\n- Second.\n\n More.",
+ "ordered list starting at five": "5. First.\n\n More.\n\n6. Second.\n\n More.",
+ "ordered list starting at zero": "0. First.\n\n More.\n\n1. Second.\n\n More.",
+ "tight lists": "- One\n- Two\n- Three",
+ "nested loose lists": "- Parent.\n\n - Child.\n\n Another paragraph.\n\n - Other child.\n\n- Other parent.",
+ "nested ordered and unordered lists": "3. Parent.\n\n - Child.\n\n Paragraph.\n\n - Other.\n\n4. Next.",
+ "tight list inside loose list": "- Parent.\n\n - One\n - Two\n\n Final paragraph.",
+ "task lists": "- [x] Done.\n\n Explanation.\n\n- [ ] Pending.",
+ "code fence": "- Explanation.\n\n ```text\n a < b\n next\n ```\n\n Conclusion.",
+ "headings and inline formatting": "- ## Heading\n\n Paragraph with **bold**, *italic*, and `code`.\n\n More.",
+ math: "- Formula.\n\n $$\n x^2 + y^2 = 1\n $$\n\n Inline $$a + b$$.",
+ links: "- [Mirai](https://trymirai.com).\n\n More at https://example.com.",
+ "reference definitions": "- [Mirai][m].\n\n More.\n\n[m]: https://trymirai.com",
+ "definition inside list": "- [Mirai][m].\n\n [m]: https://trymirai.com\n\n More.",
+ footnotes: "- Some text[^note].\n\n More.\n\n[^note]: Footnote.",
+ "footnotes with multiple paragraphs":
+ "- Intro.\n\n [^a]: first paragraph\n\n second paragraph\n\n This is a footnote[^a].",
+ "footnotes shared across items": "- Intro[^a].\n\n More.\n\n- Second[^a].\n\n [^a]: Shared footnote.",
+ "unfinished display math": "- Intro.\n\n $$\n a + b\n\n c + d\n\n End.",
+ "raw HTML": "- First.\n\n <div>\n **Literal**\n </div>\n\n More.",
+ "inline HTML": "- First.\n\n <span>Inline</span> content.\n\n More.",
+ "nested quote": "- Parent.\n\n > Quoted **text**.\n >\n > Another quoted paragraph.\n\n Final.",
+ "lazy continuation": "- First line.\nLazy continuation.\n\n Another paragraph.\nStill inside the item.",
+ "indented code": "- First.\n\n indented code\n second line\n\n More.",
+ "multiple digit ordered list": "12. First.\n\n Paragraph.\n\n13. Next.",
+ "tab-indented paragraph": "- First.\n\n\t Another paragraph.\n\n Final.",
+ "tab after list marker": "-\tFirst.\n\n\tSecond paragraph.",
+ "Arabic paragraphs": "- الفقرة الأولى.\n\n الفقرة الثانية مع **نص غامق**.\n\n النص الأخير.",
+ "Hebrew paragraphs": "- הפסקה הראשונה.\n\n הפסקה השנייה עם **טקסט מודגש**.\n\n טקסט אחרון.",
+ "nested task list": "- Parent.\n\n - [x] Child.\n\n Final.",
+ table: "- Parent.\n\n | Name | Value |\n | --- | --- |\n | First | 1 |\n\n Final.",
+};
+
+it.each(Object.entries(fixtures))("preserves existing markup and styles for %s", (_name, markdown) => {
+ for (const small of [false, true]) {
+ expect(html(markdown, false, small)).toBe(html(markdown, true, small));
+ }
+});
+
+it("only reparses the active paragraph inside a growing long list item", () => {
+ control.stock = false;
+ const beginning = "- Opening paragraph.\n\n";
+ const completed = Array.from({ length: 80 }, (_, i) => ` Paragraph ${i}: ${"completed words ".repeat(12)}\n\n`).join(
+ "",
+ );
+ const content = `${beginning}${completed} Still thinking`;
+ const view = render(<MarkdownRenderer content={content} useOneFontSize />);
+ const firstParagraph = view.container.querySelector("p");
+ parsedBlocks.mockClear();
+
+ view.rerender(<MarkdownRenderer content={`${content} about the answer.`} useOneFontSize />);
+
+ expect(view.container.querySelectorAll("ul").length).toBe(1);
+ expect(view.container.querySelectorAll("li").length).toBe(1);
+ expect(view.container.querySelector("p")).toBe(firstParagraph);
+ expect(view.container.textContent).toContain("Still thinking about the answer.");
+ expect(parsedBlocks).toHaveBeenCalledTimes(1);
+ expect(parsedBlocks.mock.calls[0]?.[0]).toContain("Still thinking about the answer.");
+ expect(parsedBlocks.mock.calls[0]?.[0].length).toBeLessThan(100);
+});
+
+it("keeps the same output while a list changes between tight and loose during streaming", () => {
+ const stages = [
+ "- Start",
+ "- Start\n\n More",
+ "- Start\n\n More\n\n- Next",
+ "- Start\n\n More\n\n- Next\n\n Final",
+ ];
+ for (const content of stages) expect(html(content, false, true)).toBe(html(content, true, true));
+});
+
+it("updates code-fence context when the final list block completes", () => {
+ const Code = (props: object) => (
+ <code data-incomplete={useIsCodeFenceIncomplete()}>
+ {"children" in props && typeof props.children === "string" ? props.children : null}
+ </code>
+ );
+ const props: BlockProps = {
+ content: "- First.\n\n ```text\n completed\n ```\n\n ```text\n arriving\n ```",
+ index: 0,
+ isIncomplete: true,
+ shouldParseIncompleteMarkdown: true,
+ shouldNormalizeHtmlIndentation: true,
+ components: { code: Code },
+ };
+ const view = render(<MarkdownBlock {...props} />);
+ expect(view.container.querySelectorAll('code[data-incomplete="true"]')).toHaveLength(2);
+
+ view.rerender(<MarkdownBlock {...props} isIncomplete={false} />);
+ expect(view.container.querySelectorAll('code[data-incomplete="false"]')).toHaveLength(2);
+ expect(view.container.textContent).toContain("arriving");
+});
+
+it("keeps explicit direction on the entire list including its markers", () => {
+ const props: BlockProps = {
+ content: "- الفقرة الأولى.\n\n الفقرة الثانية.",
+ index: 0,
+ isIncomplete: false,
+ shouldParseIncompleteMarkdown: true,
+ shouldNormalizeHtmlIndentation: true,
+ dir: "rtl",
+ };
+ const optimized = render(<MarkdownBlock {...props} />);
+ const actual = optimized.container.innerHTML.replace(/>\n+</g, "><");
+ cleanup();
+ const stock = render(<Block {...props} />);
+ expect(actual).toBe(stock.container.innerHTML.replace(/>\n+</g, "><"));
+});
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.tsx b/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.tsx
new file mode 100644
index 000000000..4dc3745ac
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/markdown-block.tsx
@@ -0,0 +1,52 @@
+import { Lexer, walkTokens, type Tokens } from "marked";
+import { createElement, memo } from "react";
+import { Block, defaultComponents, parseMarkdownIntoBlocks, type BlockProps } from "streamdown";
+
+const looseList = (content: string): Tokens.List | undefined => {
+ // Dedenting an item changes the column that determines tab indentation.
+ if (content.includes("\t")) return;
+ // Marked does not track footnote scope or unfinished display-math blocks.
+ if (content.includes("[^") || content.includes("$$")) return;
+ const lexer = new Lexer({ gfm: true });
+ const tokens = lexer.lex(content);
+ const blocks = tokens.filter((token) => token.type !== "space");
+ const list = blocks[0];
+ if (blocks.length !== 1 || list?.type !== "list" || !list.loose) return;
+ if (Object.keys(tokens.links).length > 0) return;
+ let supported = true;
+ walkTokens(tokens, (token) => {
+ if (token.type === "html" || token.type === "def" || (token.type === "list_item" && token.task)) supported = false;
+ });
+ return supported ? (list as Tokens.List) : undefined;
+};
+
+// Streamdown normally treats a whole list as one Markdown block. A single
+// list item can contain an entire long reply, so keep its container while
+// letting Streamdown cache the completed paragraphs and fences inside it.
+export const MarkdownBlock = memo(function MarkdownBlock(props: BlockProps) {
+ // Direction belongs to the whole block, including its list markers.
+ if (props.dir) return <Block {...props} />;
+ const list = looseList(props.content);
+ if (!list) return <Block {...props} />;
+
+ const Item = props.components?.li ?? defaultComponents.li;
+ const children = list.items.map((item, itemIndex) =>
+ createElement(
+ Item,
+ { key: itemIndex },
+ parseMarkdownIntoBlocks(item.text).map((content, index) => (
+ <MarkdownBlock key={index} {...props} content={content} index={index} />
+ )),
+ ),
+ );
+ if (list.ordered) {
+ const OrderedList = props.components?.ol ?? defaultComponents.ol;
+ return createElement(
+ OrderedList,
+ { start: typeof list.start === "number" && list.start !== 1 ? list.start : undefined },
+ children,
+ );
+ }
+ const UnorderedList = props.components?.ul ?? defaultComponents.ul;
+ return createElement(UnorderedList, {}, children);
+});
diff --git a/apps/mirai-gui/client/src/features/chat/components/message/markdown-renderer-performance.test.tsx b/apps/mirai-gui/client/src/features/chat/components/message/markdown-renderer-performance.test.tsx
new file mode 100644
index 000000000..6506e8440
--- /dev/null
+++ b/apps/mirai-gui/client/src/features/chat/components/message/markdown-renderer-performance.test.tsx
@@ -0,0 +1,43 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { memo, Profiler, type ComponentProps } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { MarkdownRenderer } from "./markdown-renderer";
+
+const renderBlock = vi.hoisted(() => vi.fn());
+vi.mock("streamdown", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("streamdown")>();
+ const MeasuredBlock = memo(function MeasuredBlock(props: ComponentProps<typeof actual.Block>) {
+ return (
+ <Profiler id={props.content} onRender={renderBlock}>
+ <actual.Block {...props} />
+ </Profiler>
+ );
+ });
+ return {
+ ...actual,
+ Streamdown: (props: ComponentProps<typeof actual.Streamdown>) => (
+ <actual.Streamdown {...props} BlockComponent={MeasuredBlock} />
+ ),
+ };
+});
+
+afterEach(() => {
+ cleanup();
+ renderBlock.mockClear();
+});
+
+it("does not revisit completed code blocks when more prose streams into the response", async () => {
+ const code = "```typescript\nconst answer = 42;\n```\n\n";
+ const view = render(<MarkdownRenderer content={`${code}Answer`} streaming />);
+ await waitFor(() => expect(view.container.querySelector("pre code span[style]")).toBeTruthy());
+ renderBlock.mockClear();
+
+ for (let i = 1; i <= 20; i++) {
+ view.rerender(<MarkdownRenderer content={`${code}Answer${" more".repeat(i)}`} streaming />);
+ }
+
+ expect(view.container.textContent).toContain(`Answer${" more".repeat(20)}`);
+ // The lazy highlighter may finish once; appending prose must not repeatedly
+ // revisit the completed code block through a changing plugin context.
+ expect(renderBlock.mock.calls.filter(([content]) => content.includes("const answer")).length).toBeLessThanOrEqual(1);
+});
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 b33d1f371..e5ce4d733 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
@@ -10,6 +10,7 @@ import "katex/dist/katex.min.css";
import React, { useMemo, useRef } from "react";
import type { BundledTheme } from "shiki";
import { Streamdown } from "streamdown";
+import { MarkdownBlock } from "./markdown-block";
type MarkdownRendererProps = {
content: string;
@@ -299,12 +300,12 @@ const OneFontSizeComponents = {
),
};
-export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
+export const MarkdownRenderer = React.memo(function MarkdownRenderer({
content,
useOneFontSize = false,
className = "max-w-none text-label-title markdown-body",
streaming = false,
-}) => {
+}: MarkdownRendererProps) {
const isDarkMode = useAppStore((s) => s.isDarkMode);
const codePlugin = useMemo(() => {
@@ -313,9 +314,13 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
: ["github-light", "github-light"];
return createCodePlugin({ themes });
}, [isDarkMode]);
+ // This is a context value in Streamdown; replacing it wakes completed code
+ // blocks even when only the trailing prose changed.
+ const plugins = useMemo(() => ({ code: codePlugin, math, cjk }), [codePlugin]);
return (
- <div className={className}>
+ <div className={`wrap-break-word ${className}`}>
<Streamdown
+ BlockComponent={MarkdownBlock}
mode="streaming"
isAnimating={streaming}
parseIncompleteMarkdown
@@ -324,10 +329,10 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
linkSafety={LINK_SAFETY}
remend={REMEND}
components={useOneFontSize ? OneFontSizeComponents : CustomComponents}
- plugins={{ code: codePlugin, math, cjk }}
+ plugins={plugins}
>
{content}
</Streamdown>
</div>
);
-};
+});
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 dbc04e060..51e62451d 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
@@ -209,10 +209,9 @@ const MessageListComponent: React.FC<MessageListProps> = ({
ref={(el) => {
itemRefs.current[message.id] = el;
}}
- className={[
- isLastAssistant ? "flex flex-col min-h-8" : "",
- idx > 0 ? (message.sender === "user" ? "mt-3" : "mt-1") : "",
- ].join(" ")}
+ 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">
@@ -255,11 +254,11 @@ const MessageListComponent: React.FC<MessageListProps> = ({
</div>
)}
{lastAssistantIndex === -1 && isBusy && !loadingMessageId && (
- <div className="mt-1 flex items-center gap-2 text-left text-[15px] leading-[18px] text-label-muted">
+ <div className="mt-6 flex items-center gap-2 text-left text-[15px] leading-[18px] text-label-muted">
<Loader text={loaderText} />
</div>
)}
- <div ref={messagesEndRef} className="h-4 shrink-0" />
+ <div ref={messagesEndRef} className="h-6 shrink-0" />
</div>
</div>
);
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 f893f1bbe..92fec6bd2 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
@@ -191,8 +191,11 @@ const AssistantMessage: React.FC<MessageProps> = ({
: messageFromStore?.modelName;
return (
- <div className="pb-3 text-label-title relative w-full rounded-[5px] text-[15px] leading-[140%]">
- <div ref={messageRef}>
+ <div className="text-label-title relative w-full rounded-[5px] text-[15px] leading-[140%]">
+ <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]"
+ >
{transcript !== undefined ? (
transcript.map((item, index) => {
const key = `${currentMsgVersion?.id ?? id}:${index}`;
@@ -253,7 +256,7 @@ const AssistantMessage: React.FC<MessageProps> = ({
</div>
{(hasVersions ||
(!streamInProgress && (isStreamFinished || isCanceled || text.length === 0 || !!visibleChainOfThought))) && (
- <div className="flex flex-wrap items-center gap-1 mt-4">
+ <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} />
)}
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 b90e6757d..061699580 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
@@ -40,7 +40,7 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({ selectedModel, onM
<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 focus-visible:shadow-focus disabled:opacity-60 disabled:cursor-not-allowed"
+ 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>
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 551ee9d81..ef1d7ff12 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
@@ -29,7 +29,7 @@ export function PerformanceDropdown({ perf, disabled = false }: PerformanceDropd
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 focus-visible:shadow-focus disabled:opacity-60 disabled:cursor-not-allowed"
+ 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>
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 453496c4c..994fb1cdc 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,6 +1,6 @@
import { Transition } from "@headlessui/react";
import { ChevronDownIcon } from "lucide-react";
-import { useCallback, useEffect, useRef, useState, type UIEvent } from "react";
+import { memo, useCallback, useEffect, useRef, useState, type UIEvent } from "react";
import { twMerge } from "tailwind-merge";
import { ThinkingBubbleIcon } from "@/components/icons/thinking-bubble";
import { MarkdownRenderer } from "./markdown-renderer";
@@ -11,7 +11,11 @@ const FADE_RAMP_PX = 32;
const MAX_FADE_HEIGHT_PX = 42;
const END_FADE_HEIGHT_PX = MAX_FADE_HEIGHT_PX / 2;
-export const ThinkingBlock = ({ text, reasoningInProgress, isThinking = reasoningInProgress }: Props) => {
+export const ThinkingBlock = memo(function ThinkingBlock({
+ text,
+ reasoningInProgress,
+ isThinking = reasoningInProgress,
+}: Props) {
const [isReasoningVisible, setIsReasoningVisible] = useState(false);
const wasReasoningInProgressRef = useRef(false);
const userToggledRef = useRef(false);
@@ -118,7 +122,7 @@ export const ThinkingBlock = ({ text, reasoningInProgress, isThinking = reasonin
leaveTo="grid-rows-[0fr]"
>
<div className="grid">
- <div className="min-h-0 overflow-clip">
+ <div className="min-h-0 min-w-0 overflow-clip">
<div className="relative contain-layout">
<div
ref={setReasoningScrollElement}
@@ -155,4 +159,4 @@ export const ThinkingBlock = ({ text, reasoningInProgress, isThinking = reasonin
</Transition>
</button>
);
-};
+});
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 2fafa429a..09a17ca08 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,5 +1,6 @@
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";
@@ -113,20 +114,20 @@ export const UserMessage = ({ id, text, attachmentIds, canEdit = false, onEdit }
<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">
{text}
</div>
- <div className="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">
+ <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">
<CopyButton className="[&_svg]:size-4" onCopy={copy} />
{onEdit && (
- <button
+ <HeadlessButton
ref={editButtonRef}
type="button"
aria-label="Edit message"
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 focus-visible:shadow-focus disabled:opacity-50"
+ 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"
>
<Pencil className="size-4" />
- </button>
+ </HeadlessButton>
)}
</div>
</>
diff --git a/apps/mirai-gui/client/src/features/chat/hooks/reopen-mid-stream.test.tsx b/apps/mirai-gui/client/src/features/chat/hooks/reopen-mid-stream.test.tsx
index b5f947229..e302e8246 100644
--- a/apps/mirai-gui/client/src/features/chat/hooks/reopen-mid-stream.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat/hooks/reopen-mid-stream.test.tsx
@@ -16,6 +16,7 @@ vi.mock("@/platform/platform-singleton", () => ({
storage: {
loadChat: async (id: string) => mocks.chats.get(id) ?? null,
listChats: async () => [...mocks.chats.values()].map((c) => c.metadata),
+ updateStoredMessage: async () => {},
},
}),
}));
@@ -118,4 +119,16 @@ it("keeps streaming into the message after leaving and reopening the chat", asyn
act(() => emit({ type: "transcriptDelta", index: 3, delta: "!" }));
await waitFor(() => expect(useChatStore.getState().messages.at(-1)?.text).toBe("Hello\n\nworld!"));
+
+ let messageUpdates = 0;
+ const unsubscribe = useChatStore.subscribe((state, previous) => {
+ if (state.messages !== previous.messages) messageUpdates++;
+ });
+ act(() => {
+ for (let i = 0; i < 100; i++) emit({ type: "transcriptDelta", index: 3, delta: "!" });
+ });
+ await waitFor(() => expect(useChatStore.getState().messages.at(-1)?.text).toBe(`Hello\n\nworld${"!".repeat(101)}`));
+ expect(messageUpdates).toBe(1);
+ unsubscribe();
+ await act(() => page.result.current.cancel());
});
diff --git a/apps/mirai-gui/client/src/features/chat/hooks/use-active-assistant-buffer.ts b/apps/mirai-gui/client/src/features/chat/hooks/use-active-assistant-buffer.ts
index a2745e393..019c23d48 100644
--- a/apps/mirai-gui/client/src/features/chat/hooks/use-active-assistant-buffer.ts
+++ b/apps/mirai-gui/client/src/features/chat/hooks/use-active-assistant-buffer.ts
@@ -7,18 +7,24 @@ import { patchActiveVersion } from "../services/regenerate-versions";
// Replays the buffered streaming text into the in-memory message so a mid-stream
// chat switch or page remount keeps showing the partial output until finalize arrives.
export const useActiveAssistantBuffer = (chatId: string): (() => void) => {
- const generatingHere = useChatSessionStore((s) => isChatGenerating(s, chatId));
- const activeAssistantMessageId = useChatSessionStore((s) => s.activeAssistantMessageId);
- const activeAssistantMessageText = useChatSessionStore((s) => s.activeAssistantMessageText);
- const activeAssistantMessageOutput = useChatSessionStore((s) => s.activeAssistantMessageOutput);
-
const apply = useCallback(() => {
- if (!chatId || !generatingHere || !activeAssistantMessageId) return;
+ const session = useChatSessionStore.getState();
+ const { activeAssistantMessageId, activeAssistantMessageText, activeAssistantMessageOutput } = session;
+ if (!chatId || !isChatGenerating(session, chatId) || !activeAssistantMessageId) return;
if (activeAssistantMessageText === null && activeAssistantMessageOutput === null) return;
const s = useChatStore.getState();
const msg = s.messages.find((m) => m.id === activeAssistantMessageId);
if (!msg) return;
const hasVersions = Array.isArray(msg.versions) && msg.versions.length > 0;
+ const active = msg.versions?.at(-1) ?? msg;
+ // The live stream already updates a loaded message. Replay only when a
+ // chat load has replaced it with the older copy from storage.
+ if (
+ (activeAssistantMessageText === null || active.text === activeAssistantMessageText) &&
+ (activeAssistantMessageOutput === null || active.output === activeAssistantMessageOutput)
+ ) {
+ return;
+ }
const patch = {
...(activeAssistantMessageText !== null ? { text: activeAssistantMessageText } : {}),
...(activeAssistantMessageOutput !== null ? { output: activeAssistantMessageOutput } : {}),
@@ -27,10 +33,11 @@ export const useActiveAssistantBuffer = (chatId: string): (() => void) => {
...patch,
...(hasVersions ? { versions: patchActiveVersion(msg.versions, patch) } : {}),
});
- }, [chatId, generatingHere, activeAssistantMessageId, activeAssistantMessageText, activeAssistantMessageOutput]);
+ }, [chatId]);
useEffect(() => {
apply();
+ return useChatSessionStore.subscribe(apply);
}, [apply]);
return apply;
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.tsx
index 594c35054..ab6b3686e 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
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { runLlmStream, type RunEvent, type RunTransport } from "@/platform/services/chat/run-stream";
import { useChatSessionStore } from "@/stores/use-chat-session-store";
import { useChatStore } from "@/stores/use-chat-store";
+import type { ChatMetadata } from "@/platform/services/storage";
import { Roles } from "@/types/chat";
import type { SessionOutputStats, TranscriptItem } from "@/types/llm-stream";
import type { Message } from "@/types/message";
@@ -12,7 +13,8 @@ const mocks = vi.hoisted(() => ({
getModelChatNamingEnabled: vi.fn(async () => true),
cancelRun: vi.fn(async () => {}),
updateStoredMessage: vi.fn(async () => {}),
- updateChatTitle: vi.fn<(id: string, name: string, expected?: string) => Promise<void>>(async () => {}),
+ updateChatTitle: vi.fn<(id: string, name: string, expected?: string) => Promise<boolean>>(async () => true),
+ listChats: vi.fn<() => Promise<ChatMetadata[]>>(async () => []),
loadChat: vi.fn<() => Promise<{ metadata: { title: string }; messages?: Message[] }>>(async () => ({
metadata: { title: "Untitled" },
})),
@@ -25,7 +27,7 @@ vi.mock("@/platform/platform-singleton", () => ({
updateStoredMessage: mocks.updateStoredMessage,
loadChat: mocks.loadChat,
updateChatTitle: mocks.updateChatTitle,
- listChats: async () => [],
+ listChats: mocks.listChats,
},
}),
}));
@@ -97,6 +99,7 @@ describe("useLlmStream", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getModelChatNamingEnabled.mockResolvedValue(true);
+ mocks.listChats.mockResolvedValue([]);
mocks.loadChat.mockResolvedValue({ metadata: { title: "Untitled" } });
useChatSessionStore.setState(sessionDefaults, true);
useChatStore.setState(chatDefaults, true);
@@ -251,8 +254,9 @@ describe("useLlmStream", () => {
emit({ type: "transcript", items: [...transcript.slice(0, -1), { type: "text", text: "" }] });
emit({ type: "transcriptDelta", index: 3, delta: "A long response. ".repeat(100) });
});
- expect(messageText()).toBe(fullText);
- expect(useChatSessionStore.getState().activeAssistantMessageText).toBe(fullText);
+ // The last delta is still waiting for a paint; either terminal path must
+ // flush it before saving, even if that frame never runs.
+ expect(messageText()).toBe("Before the tool.");
if (end === "cancel") await act(() => hook.result.current.cancel());
else act(() => emit({ type: "error", error: "Model failed" }));
await act(() => run);
@@ -282,10 +286,12 @@ describe("useLlmStream", () => {
emit({ type: "transcript", items: [{ type: "thinking", text: "Visible" }] });
emit({ type: "transcriptDelta", index: 0, delta: " answer" });
});
- expect(useChatStore.getState().messages[0]?.output?.text?.parsed).toEqual({
- response: "",
- chainOfThought: "Visible answer",
- });
+ await waitFor(() =>
+ expect(useChatStore.getState().messages[0]?.output?.text?.parsed).toEqual({
+ response: "",
+ chainOfThought: "Visible answer",
+ }),
+ );
act(() => emit({ type: "transcript", items: [{ type: "text", text: "Visible answer" }] }));
expect(useChatStore.getState().messages[0]?.output?.text?.parsed).toEqual({
response: "Visible answer",
@@ -513,7 +519,9 @@ describe("useLlmStream", () => {
it("keeps a manual rename made during a run", async () => {
let storedName = "Untitled";
mocks.updateChatTitle.mockImplementationOnce(async (_id, name, expected) => {
- if (storedName === expected) storedName = name;
+ if (storedName !== expected) return false;
+ storedName = name;
+ return true;
});
const { hook, start, options, emit } = setup();
let run!: Promise<unknown>;
@@ -532,6 +540,25 @@ describe("useLlmStream", () => {
expect(storedName).toBe("My chosen name");
});
+ it("stops automatic renaming after a rejected update even if its candidate matches a manual rename", async () => {
+ const { hook, start, options, emit } = setup();
+ let run!: Promise<unknown>;
+ act(() => {
+ run = start(options);
+ });
+ await waitFor(() => expect(hook.result.current.isStreaming).toBe(true));
+ mocks.updateChatTitle.mockResolvedValueOnce(false);
+
+ act(() => {
+ emit({ type: "chatName", name: "My manual title" });
+ emit({ type: "chatName", name: "Another automatic title" });
+ emit({ type: "done", text: "Answer", stats, chatName: "Another automatic title" });
+ });
+ await act(() => run);
+
+ expect(mocks.updateChatTitle).toHaveBeenCalledExactlyOnceWith(CHAT_ID, "My manual title", "Untitled");
+ });
+
it("reports a failed name save without losing the response", async () => {
mocks.updateChatTitle.mockRejectedValueOnce(new Error("disk full"));
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -556,6 +583,56 @@ describe("useLlmStream", () => {
}
});
+ it("keeps the saved title visible and accepts the next correction after the chat list refresh fails", async () => {
+ const { hook, start, options, emit } = setup();
+ const metadata: ChatMetadata = {
+ id: CHAT_ID,
+ title: "Untitled",
+ createdAt: 1,
+ updatedAt: 1,
+ messageCount: 2,
+ };
+ const other = { ...metadata, id: "other-chat", title: "Other chat" };
+ useChatStore.setState({ savedChats: [metadata, other] });
+ let storedTitle = "Untitled";
+ const saveTitle = async (_id: string, next: string, expected?: string) => {
+ if (expected !== storedTitle) return false;
+ storedTitle = next;
+ return true;
+ };
+ mocks.updateChatTitle.mockImplementationOnce(saveTitle).mockImplementationOnce(saveTitle);
+ const first = "First accepted title";
+ const corrected = "Corrected title";
+ const refreshed = [other, { ...metadata, title: corrected, updatedAt: 2 }];
+ mocks.listChats.mockRejectedValueOnce(new Error("read failed")).mockResolvedValueOnce(refreshed);
+ const warned = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ let run!: Promise<unknown>;
+ act(() => {
+ run = start(options);
+ });
+ await waitFor(() => expect(hook.result.current.isStreaming).toBe(true));
+ act(() => emit({ type: "chatName", name: first }));
+ await waitFor(() => expect(warned).toHaveBeenCalledOnce());
+
+ expect(useChatStore.getState().savedChats).toEqual([{ ...metadata, title: first }, other]);
+ expect(useChatStore.getState().saveFailureCount).toBe(0);
+
+ act(() => {
+ emit({ type: "chatName", name: corrected });
+ emit({ type: "done", text: "Answer", stats, chatName: corrected });
+ });
+ await act(() => run);
+
+ expect(mocks.updateChatTitle).toHaveBeenLastCalledWith(CHAT_ID, corrected, first);
+ expect(storedTitle).toEqual(corrected);
+ expect(useChatStore.getState().savedChats).toEqual(refreshed);
+ expect(useChatStore.getState().saveFailureCount).toBe(0);
+ } finally {
+ warned.mockRestore();
+ }
+ });
+
it("keeps a name already set when the response is canceled", async () => {
const { hook, start, options, emit } = setup();
let run!: Promise<unknown>;
diff --git a/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.ts b/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.ts
index 07f36dfca..9c9bc0205 100644
--- a/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.ts
+++ b/apps/mirai-gui/client/src/features/chat/hooks/use-llm-stream.ts
@@ -36,13 +36,16 @@ const outputPatch = (message: Message, output: OutputShape, text?: string): Part
const versionIndex = activeVersionIndex(message);
const patch = { output, ...(text !== undefined ? { text } : {}) };
if (versionIndex === undefined) return patch;
- return { versions: message.versions?.map((v, i) => (i === versionIndex ? { ...v, ...patch } : v)) };
+ return {
+ ...(text !== undefined ? { text } : {}),
+ versions: message.versions?.map((v, i) => (i === versionIndex ? { ...v, ...patch } : v)),
+ };
};
-const applyOutput = (messageId: string, output: OutputShape): void => {
+const applyOutput = (messageId: string, output: OutputShape, text?: string): void => {
const store = useChatStore.getState();
const target = store.messages.find((m) => m.id === messageId);
- if (target) store.updateMessage(messageId, outputPatch(target, output));
+ if (target) store.updateMessage(messageId, outputPatch(target, output, text));
};
const applyPerf = (messageId: string, stats: SessionOutputStats): void => {
@@ -179,8 +182,8 @@ export const useLlmStream = (chatId: string) => {
titleUpdates = titleUpdates.then(async () => {
if (expectedTitle === undefined) return;
try {
- await useChatStore.getState().updateChatTitle(chatId, name, expectedTitle);
- expectedTitle = name;
+ const updated = await useChatStore.getState().updateChatTitle(chatId, name, expectedTitle);
+ expectedTitle = updated ? name : undefined;
} catch (error) {
console.error("[storage] failed to save model chat name", { chatId }, error);
useChatStore.setState((s) => ({ saveFailureCount: s.saveFailureCount + 1 }));
@@ -191,10 +194,13 @@ export const useLlmStream = (chatId: string) => {
// Reasoning arrives as parsed patches before any text does.
let hasContent = false;
let output: OutputShape = {};
- const updateOutput = (next: OutputShape) => {
+ const updateOutput = (next: OutputShape, text?: string) => {
output = next;
- applyOutput(messageId, output);
- session.setActiveAssistantMessageOutput(output);
+ applyOutput(messageId, output, text);
+ useChatSessionStore.setState({
+ activeAssistantMessageOutput: output,
+ ...(text !== undefined ? { activeAssistantMessageText: text } : {}),
+ });
};
const offParsed = llm.onParsed((patch) => {
if (!hasContent && (patch.chainOfThought || patch.response)) {
@@ -217,9 +223,10 @@ export const useLlmStream = (chatId: string) => {
const chainOfThought = items
.flatMap((item) => (item.type === "thinking" && item.text.length > 0 ? [item.text] : []))
.join("\n\n");
- options.updateText(messageId, transcriptText);
- session.setActiveAssistantMessageText(transcriptText);
- updateOutput({ ...withParsedOutput(output, { response: transcriptText, chainOfThought }), transcript: items });
+ updateOutput(
+ { ...withParsedOutput(output, { response: transcriptText, chainOfThought }), transcript: items },
+ transcriptText,
+ );
});
setIsStreaming(true);
diff --git a/apps/mirai-gui/client/src/features/chat/hooks/use-send-chat-message.test.tsx b/apps/mirai-gui/client/src/features/chat/hooks/use-send-chat-message.test.tsx
index 4e6da65c1..0bb776b54 100644
--- a/apps/mirai-gui/client/src/features/chat/hooks/use-send-chat-message.test.tsx
+++ b/apps/mirai-gui/client/src/features/chat/hooks/use-send-chat-message.test.tsx
@@ -79,9 +79,10 @@ const editUserMessage = vi.fn(async (id: string, messageId: string, text: string
});
const updateChatTitle = vi.fn(async (id: string, title: string, expectedTitle?: string) => {
const chat = chats.get(id);
- if (!chat) return;
- if (expectedTitle !== undefined && chat.metadata.title !== expectedTitle) return;
+ if (!chat) return false;
+ if (expectedTitle !== undefined && chat.metadata.title !== expectedTitle) return false;
chat.metadata.title = title;
+ return true;
});
const deferred = <T,>() => {
@@ -316,6 +317,19 @@ it("does not start a reply for a chat deleted during title generation", async ()
expect(chats.has(CHAT_A)).toBe(false);
});
+it("does not launch fallback naming after Stop while loading the existing title", async () => {
+ const loaded = deferred<ChatData | null>();
+ const storage = mocks.platform.storage as { loadChat: ReturnType<typeof vi.fn> };
+ storage.loadChat.mockReturnValueOnce(loaded.promise);
+ const naming = useChatStore.getState().generateChatTitle(CHAT_A, "hello");
+ await waitFor(() => expect(storage.loadChat).toHaveBeenCalled());
+ await useChatSessionStore.getState().cancelActiveRunForChat(CHAT_A);
+ loaded.resolve({ metadata, messages: [] });
+ await naming;
+ expect(generateTitle).not.toHaveBeenCalled();
+ expect(updateChatTitle).not.toHaveBeenCalled();
+});
+
it("keeps a manual rename made while the title was generating", async () => {
const title = deferred<string>();
generateTitle.mockReturnValueOnce(title.promise);
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 be26c8fcc..e39812821 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
@@ -1,4 +1,5 @@
import { ChevronRight } from "lucide-react";
+import { Button } from "@headlessui/react";
import type { ReactNode } from "react";
import { twMerge } from "tailwind-merge";
import { Text } from "@/components/ui/typography";
@@ -75,33 +76,33 @@ export function FamilyCard({ vendorIcon, familyName, vendorName, badges, onClick
if (compact) {
return (
- <button
+ <Button
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 focus-visible:shadow-focus hover:bg-surface-tertiary text-left"
+ 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"
>
<div className="flex items-center gap-3 min-w-0">
{heading}
{chevron}
</div>
{chips && chips.length > 0 && <div className="flex items-center gap-1.5 flex-wrap">{chips}</div>}
- </button>
+ </Button>
);
}
return (
- <button
+ <Button
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 focus-visible:shadow-focus hover:bg-surface-tertiary"
+ 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"
>
{heading}
<div className="flex items-center gap-1.5 shrink-0">
{chips}
<span className="ml-1">{chevron}</span>
</div>
- </button>
+ </Button>
);
}
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 cbf477d4c..129f59528 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
@@ -1,4 +1,5 @@
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";
@@ -27,10 +28,11 @@ export function ModelCardRow({
const { status, isDownloading, isDownloaded, isPaused, isError, progress } = deriveModelCardState(state);
return (
- <div
+ <DataInteractive
+ as="div"
className={twMerge(
"relative py-2.5 transition-colors duration-150",
- isDownloaded && "cursor-pointer hover:bg-surface-tertiary outline-hidden focus-visible:shadow-focus",
+ isDownloaded && "cursor-pointer hover:bg-surface-tertiary outline-hidden data-[focus]:shadow-focus",
isError && "bg-danger-bg",
)}
{...(isDownloaded && onOpen
@@ -112,7 +114,7 @@ export function ModelCardRow({
<IconCheckStroke />
</div>
</Tooltip>
- <button
+ <Button
type="button"
aria-label={`Delete ${name}`}
title="Delete model (hold Shift to skip confirmation)"
@@ -120,10 +122,10 @@ 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 focus-visible:shadow-focus"
+ 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"
>
<Trash2 size={14} />
- </button>
+ </Button>
</>
)}
</div>
@@ -142,6 +144,6 @@ export function ModelCardRow({
</div>
</div>
)}
- </div>
+ </DataInteractive>
);
}
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 5bd7e86a4..9421d8353 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
@@ -164,7 +164,7 @@ it("updates and persists chat width from General settings", () => {
}
});
-it("persists System, Light, and Dark choices through the custom theme selector", async () => {
+it("persists System, Dark, and Light choices through the custom theme selector", async () => {
render(<GeneralTab />);
let selectedLabel = "System";
for (const [mode, label] of [
@@ -174,9 +174,10 @@ it("persists System, Light, and Dark choices through the custom theme selector",
] as const) {
fireEvent.click(screen.getByRole("button", { name: `Theme: ${selectedLabel}` }));
const popup = await screen.findByRole("listbox", { name: `Theme: ${selectedLabel}` });
+ expect(screen.getAllByRole("option").map((option) => option.textContent)).toEqual(["System", "Dark", "Light"]);
expect(screen.getByRole("option", { name: selectedLabel }).getAttribute("aria-selected")).toBe("true");
const option = screen.getByRole("option", { name: label });
- if (mode === "dark") {
+ if (mode === "light") {
fireEvent.keyDown(popup, { key: "End" });
await waitFor(() => expect(popup.getAttribute("aria-activedescendant")).toBe(option.id));
fireEvent.keyDown(popup, { key: "Enter" });
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 09fc6824f..c21478062 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
@@ -8,8 +8,8 @@ import type { ThemeMode } from "@/stores/use-app-store";
const THEMES: { value: ThemeMode; label: string }[] = [
{ value: "system", label: "System" },
- { value: "light", label: "Light" },
{ value: "dark", label: "Dark" },
+ { value: "light", label: "Light" },
];
type Props = { value: ThemeMode; onChange: (theme: ThemeMode) => void };
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 f567e07b8..3aaae5d0e 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
@@ -45,7 +45,7 @@ export function SettingsPage() {
{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 ${s.key === tab ? "bg-bg-hover dark:bg-bg-hover" : ""} hover:bg-bg-hover `}
+ 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>
@@ -56,7 +56,7 @@ export function SettingsPage() {
<section
className={twMerge(
- "flex-1 min-w-0 lg:px-0 h-full overflow-y-auto overscroll-y-contain thin-scrollbar [scrollbar-gutter:stable]",
+ "flex-1 min-w-0 lg:px-0 h-full overflow-y-scroll overscroll-y-contain thin-scrollbar",
"pt-5 lg:pt-5",
)}
>
diff --git a/apps/mirai-gui/client/src/platform/services/chat/index.ts b/apps/mirai-gui/client/src/platform/services/chat/index.ts
index 2d54acb1d..4cddca91b 100644
--- a/apps/mirai-gui/client/src/platform/services/chat/index.ts
+++ b/apps/mirai-gui/client/src/platform/services/chat/index.ts
@@ -3,7 +3,7 @@ import type { SamplingPolicyPayload } from "@/types/sampling";
export type TitleGenParams = {
repoId: string;
- messages: Array<{ role: "system" | "user" | "assistant"; content: string }>;
+ userText: string;
};
export type SamplingDefaults = Exclude<SamplingPolicyPayload, { type: "Default" }>;
diff --git a/apps/mirai-gui/client/src/platform/services/chat/run-stream.test.ts b/apps/mirai-gui/client/src/platform/services/chat/run-stream.test.ts
index fc14e324e..06cd8bcea 100644
--- a/apps/mirai-gui/client/src/platform/services/chat/run-stream.test.ts
+++ b/apps/mirai-gui/client/src/platform/services/chat/run-stream.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { LlmRunParams, SessionOutputStats, TranscriptItem } from "@/types/llm-stream";
import { runLlmStream, type RunEvent, type RunTransport } from "./run-stream";
@@ -37,6 +37,9 @@ const readAll = async (stream: ReadableStream<string>): Promise<string> => {
};
describe("runLlmStream", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
it("replays ordered transcript snapshots including explicit naming calls", async () => {
const initial: TranscriptItem[] = [
{ type: "thinking", text: "Check the clock", completed: true },
@@ -66,6 +69,7 @@ describe("runLlmStream", () => {
run.onTranscript((items) => snapshots.push(items));
emit({ type: "transcript", items: initial });
emit({ type: "transcriptDelta", index: 0, delta: "える 🧠" });
+ vi.advanceTimersToNextFrame();
emit({ type: "transcriptDelta", index: 2, delta: ", თბილისი 👋" });
emit({ type: "done", text: "Hello, თბილისი 👋", stats });
@@ -110,6 +114,7 @@ describe("runLlmStream", () => {
});
emit({ type: "transcript", items: [{ type: "text", text: "Revised" }] });
emit({ type: "transcriptDelta", index: 0, delta: " answer" });
+ vi.advanceTimersToNextFrame();
expect(listener).toHaveBeenLastCalledWith([{ type: "text", text: "Revised answer" }]);
const final: TranscriptItem[] = [{ type: "text", text: "Final answer" }];
emit({ type: "done", text: "Final answer", stats, transcript: final });
@@ -144,7 +149,6 @@ describe("runLlmStream", () => {
run.onTranscript(listener);
emit({ type: "transcript", items: [...items.slice(0, -1), { type: "text", text: "It is" }] });
emit({ type: "transcriptDelta", index: 2, delta: " noon." });
- expect(listener).toHaveBeenLastCalledWith(items);
listener.mockClear();
if (end === "done") emit({ type: "done", text: "Checking.\n\nIt is noon.", stats });
else {
@@ -154,13 +158,37 @@ describe("runLlmStream", () => {
await expect(readAll(run.stream)).rejects.toThrow("Stopped");
}
}
+ expect(listener).toHaveBeenCalledExactlyOnceWith(items);
+ listener.mockClear();
emit({ type: "transcript", items: [] });
emit({ type: "transcriptDelta", index: 2, delta: " Ignore this." });
+ vi.advanceTimersToNextFrame();
expect(listener).not.toHaveBeenCalled();
expect((await run.result).transcript).toEqual(items);
},
);
+ it("publishes a burst of tokens once per frame and keeps unchanged items by reference", async () => {
+ const { transport, emit } = fakeTransport();
+ const run = runLlmStream(transport, params);
+ const completed: TranscriptItem = { type: "text", text: "Earlier reply" };
+ emit({ type: "transcript", items: [completed, { type: "thinking", text: "" }] });
+ const listener = vi.fn();
+ run.onTranscript(listener);
+ listener.mockClear();
+ for (let i = 0; i < 1000; i++) emit({ type: "transcriptDelta", index: 1, delta: "考" });
+ expect(listener).not.toHaveBeenCalled();
+ vi.advanceTimersToNextFrame();
+ expect(listener).toHaveBeenCalledExactlyOnceWith([completed, { type: "thinking", text: "考".repeat(1000) }]);
+ expect(listener.mock.calls[0]?.[0][0]).toBe(completed);
+ emit({ type: "transcriptDelta", index: 1, delta: " done" });
+ await run.stream.getReader().cancel();
+ expect((await run.result).transcript?.[1]).toEqual({ type: "thinking", text: "考".repeat(1000) + " done" });
+ expect(listener).toHaveBeenCalledTimes(2);
+ vi.advanceTimersToNextFrame();
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+
it("streams chunks, closes on done and resolves the result", async () => {
const { transport, emit } = fakeTransport();
const run = runLlmStream(transport, params);
diff --git a/apps/mirai-gui/client/src/platform/services/chat/run-stream.ts b/apps/mirai-gui/client/src/platform/services/chat/run-stream.ts
index d71316199..0401e4471 100644
--- a/apps/mirai-gui/client/src/platform/services/chat/run-stream.ts
+++ b/apps/mirai-gui/client/src/platform/services/chat/run-stream.ts
@@ -39,6 +39,8 @@ export function runLlmStream(transport: RunTransport, params: LlmRunParams): Llm
const transcriptListeners = new Set<(items: TranscriptItem[]) => void>();
let chatName: string | undefined;
let transcript: TranscriptItem[] | undefined;
+ const pendingDeltas = new Map<number, string[]>();
+ let transcriptFrame: number | undefined;
let settled = false;
let resolveResult!: (result: LlmRunResult) => void;
const result = new Promise<LlmRunResult>((resolve) => {
@@ -48,6 +50,7 @@ export function runLlmStream(transport: RunTransport, params: LlmRunParams): Llm
// The first terminal outcome wins; anything the backend sends afterwards is dropped.
const settle = (outcome: LlmRunResult): boolean => {
if (settled) return false;
+ flushTranscript();
settled = true;
resolveResult({
...outcome,
@@ -71,10 +74,28 @@ export function runLlmStream(transport: RunTransport, params: LlmRunParams): Llm
};
const notifyTranscript = (items: TranscriptItem[]) => {
+ if (transcriptFrame !== undefined) cancelAnimationFrame(transcriptFrame);
+ transcriptFrame = undefined;
+ pendingDeltas.clear();
transcript = items;
transcriptListeners.forEach((listener) => listener(items));
};
+ // IPC can deliver many tokens before the browser gets a chance to paint.
+ // Keep that work proportional to the deltas; publish one immutable snapshot
+ // per frame, and always publish the final tail before settling the run.
+ const flushTranscript = () => {
+ if (!transcript || pendingDeltas.size === 0) return;
+ const items = [...transcript];
+ for (const [index, deltas] of pendingDeltas) {
+ const item = items[index];
+ if (item?.type === "text" || item?.type === "thinking") {
+ items[index] = { ...item, text: item.text + deltas.join("") };
+ }
+ }
+ notifyTranscript(items);
+ };
+
const stream = new ReadableStream<string>({
start(controller) {
const fail = (message: string) => {
@@ -101,9 +122,10 @@ export function runLlmStream(transport: RunTransport, params: LlmRunParams): Llm
fail(`Invalid transcript delta at index ${event.index}`);
return;
}
- const items = [...transcript];
- items[event.index] = { ...item, text: item.text + event.delta };
- notifyTranscript(items);
+ const deltas = pendingDeltas.get(event.index);
+ if (deltas) deltas.push(event.delta);
+ else pendingDeltas.set(event.index, [event.delta]);
+ transcriptFrame ??= requestAnimationFrame(flushTranscript);
return;
}
case "done":
@@ -153,6 +175,7 @@ export function runLlmStream(transport: RunTransport, params: LlmRunParams): Llm
return () => chatNameListeners.delete(listener);
},
onTranscript: (listener) => {
+ flushTranscript();
transcriptListeners.add(listener);
if (transcript !== undefined) listener(transcript);
return () => transcriptListeners.delete(listener);
diff --git a/apps/mirai-gui/client/src/platform/services/chat/tauri.ts b/apps/mirai-gui/client/src/platform/services/chat/tauri.ts
index 27c230de4..7f39cd8f3 100644
--- a/apps/mirai-gui/client/src/platform/services/chat/tauri.ts
+++ b/apps/mirai-gui/client/src/platform/services/chat/tauri.ts
@@ -21,8 +21,7 @@ export const tauriChat: ChatService = {
runStream: (params: LlmRunParams) => runLlmStream(tauriRunTransport, params),
cancelRun,
- generateTitle: (params: TitleGenParams) =>
- invoke<string>("title_gen", { payload: { repoId: params.repoId, messages: params.messages } }),
+ generateTitle: (params: TitleGenParams) => invoke<string>("title_gen", { payload: params }),
cancelTitleGen: async () => {
await invoke("cancel_title_gen");
diff --git a/apps/mirai-gui/client/src/platform/services/storage/chat-repository.test.ts b/apps/mirai-gui/client/src/platform/services/storage/chat-repository.test.ts
index f1f1c91e7..609aaf35d 100644
--- a/apps/mirai-gui/client/src/platform/services/storage/chat-repository.test.ts
+++ b/apps/mirai-gui/client/src/platform/services/storage/chat-repository.test.ts
@@ -132,3 +132,56 @@ describe("editUserMessage", () => {
await expect(webStorage.editUserMessage("chat", "u2", "Edit")).rejects.toBeInstanceOf(ChatNotFoundError);
});
});
+
+describe("updateChatTitle", () => {
+ const generated = "Generated title";
+
+ it("updates the title when the stored value matches", async () => {
+ const before = (await chatRepository.loadChat("chat"))!;
+ expect(await chatRepository.updateChatTitle("chat", generated, original.metadata.title)).toBe(true);
+ const saved = (await chatRepository.loadChat("chat"))!;
+
+ expect(saved.metadata).toEqual({ ...before.metadata, title: generated, updatedAt: now });
+ expect(saved.messages).toEqual(before.messages);
+ expect(files.save).toHaveBeenCalledOnce();
+ });
+
+ it("does not overwrite the title if the expected value changed", async () => {
+ expect(await chatRepository.updateChatTitle("chat", generated, "Different title")).toBe(false);
+
+ expect((await chatRepository.loadChat("chat"))?.metadata).toMatchObject(original.metadata);
+ expect(files.save).not.toHaveBeenCalled();
+ });
+
+ it("reports a rejected CAS even when the proposed title happens to match a manual rename", async () => {
+ const renamed = "My chosen title";
+ expect(await chatRepository.updateChatTitle("chat", renamed)).toBe(true);
+ expect(await chatRepository.updateChatTitle("chat", renamed, original.metadata.title)).toBe(false);
+ // A rejected write must not advance the caller's expected title to `renamed`.
+ expect(await chatRepository.updateChatTitle("chat", generated, original.metadata.title)).toBe(false);
+
+ expect((await chatRepository.loadChat("chat"))?.metadata.title).toBe(renamed);
+ expect(files.save).toHaveBeenCalledOnce();
+ });
+
+ it("reports missing chats and the browser provider as unapplied updates", async () => {
+ expect(await chatRepository.updateChatTitle("missing-chat", generated)).toBe(false);
+ expect(await webStorage.updateChatTitle("chat", generated)).toBe(false);
+ expect(files.save).not.toHaveBeenCalled();
+ });
+
+ it("preserves a manual rename when a stale generated title and a message save are queued", async () => {
+ const renamed = "My chosen title";
+ const message = { id: "a3", sender: "assistant" as const, text: "New answer", timestamp: now };
+ await Promise.all([
+ chatRepository.updateChatTitle("chat", renamed),
+ chatRepository.updateChatTitle("chat", generated, original.metadata.title),
+ chatRepository.appendMessage("chat", message),
+ ]);
+
+ const saved = (await chatRepository.loadChat("chat"))!;
+ expect(saved.metadata).toMatchObject({ title: renamed, messageCount: 5 });
+ expect(saved.messages.at(-1)).toMatchObject(message);
+ expect(files.save).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/mirai-gui/client/src/platform/services/storage/chat-repository.ts b/apps/mirai-gui/client/src/platform/services/storage/chat-repository.ts
index 04adf4310..5ac25c2d6 100644
--- a/apps/mirai-gui/client/src/platform/services/storage/chat-repository.ts
+++ b/apps/mirai-gui/client/src/platform/services/storage/chat-repository.ts
@@ -136,12 +136,13 @@ export const chatRepository: ChatRepository = {
updateChatTitle(chatId, title, expectedTitle) {
return withChatLock(chatId, async () => {
const existing = await loadChat(chatId);
- if (!existing) return;
- if (expectedTitle !== undefined && existing.metadata.title !== expectedTitle) return;
+ if (!existing) return false;
+ if (expectedTitle !== undefined && existing.metadata.title !== expectedTitle) return false;
await writeChat({
...existing,
metadata: { ...existing.metadata, title, updatedAt: Date.now() },
});
+ return true;
});
},
diff --git a/apps/mirai-gui/client/src/platform/services/storage/index.ts b/apps/mirai-gui/client/src/platform/services/storage/index.ts
index 8191f1d01..9c0afe486 100644
--- a/apps/mirai-gui/client/src/platform/services/storage/index.ts
+++ b/apps/mirai-gui/client/src/platform/services/storage/index.ts
@@ -38,8 +38,8 @@ export type StorageService = {
/** Edits a user message and removes all later messages in one stored update. */
editUserMessage(chatId: string, messageId: string, text: string): Promise<ChatData>;
removeMessage(chatId: string, messageId: string): Promise<void>;
- /** With `expectedTitle`, writes only while the stored title is still that one. */
- updateChatTitle(chatId: string, title: string, expectedTitle?: string): Promise<void>;
+ /** Returns whether the title was saved; with `expectedTitle`, the stored title must still match. */
+ updateChatTitle(chatId: string, title: string, expectedTitle?: string): Promise<boolean>;
deleteChat(chatId: string): Promise<void>;
exportAllChatsZip(): Promise<Uint8Array | null>;
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.ts
index b0d60168a..9819fb15f 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
@@ -197,9 +197,10 @@ export const extractMessageBlocks = (markdown: string): string[] => {
};
export const parseMetadata = (markdown: string, chatId: string, messagesCount: number): ChatMetadata => {
+ const header = markdown.split(/\r?\n---\r?\n/, 1)[0] ?? markdown;
return {
id: chatId,
- title: markdown.match(/^# (.+)$/m)?.[1] ?? "Untitled",
+ title: header.match(/^# (.+)$/m)?.[1] ?? "Untitled",
modelId: markdown.match(/\*\*ModelId:\*\* (.+)$/m)?.[1],
modelName: markdown.match(/\*\*Model:\*\* (.+)$/m)?.[1],
createdAt: parseDate(markdown.match(/\*\*Created:\*\* (.+)$/m)?.[1]),
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.ts
index 2c521b719..e3580ca82 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
@@ -1,6 +1,6 @@
import { expect, it } from "vitest";
import type { ChatData } from "..";
-import { extractMessageBlocks, parseMessage } from "./parse";
+import { extractMessageBlocks, parseMessage, parseMetadata } from "./parse";
import { serializeToMarkdown } from "./serialize";
import { projectAssistantVersion } from "@/features/chat/services/regenerate-versions";
import type { TranscriptItem } from "@/types/llm-stream";
@@ -21,6 +21,19 @@ const chat: ChatData = {
],
};
+it("round-trips an over-budget title in the original Markdown heading without truncating it", () => {
+ const title = "Understanding GPU memory ownership and asynchronous lifetimes";
+ const markdown = serializeToMarkdown({ ...chat, metadata: { ...chat.metadata, title } });
+
+ expect(markdown.startsWith(`# ${title}\n\n**Model:**`)).toBe(true);
+ expect(parseMetadata(markdown, "chat", 2)).toEqual({ ...chat.metadata, title });
+});
+
+it("does not use a heading from message content as a missing chat title", () => {
+ const markdown = "**Model:** Model\n\n---\n\n# Heading in a message";
+ expect(parseMetadata(markdown, "chat", 0).title).toBe("Untitled");
+});
+
it("keeps an empty assistant placeholder through a serialize/parse round-trip", () => {
const markdown = serializeToMarkdown(chat);
const messages = extractMessageBlocks(markdown).map(parseMessage);
diff --git a/apps/mirai-gui/client/src/platform/services/storage/web.ts b/apps/mirai-gui/client/src/platform/services/storage/web.ts
index aade3f10d..5eb4fa4c4 100644
--- a/apps/mirai-gui/client/src/platform/services/storage/web.ts
+++ b/apps/mirai-gui/client/src/platform/services/storage/web.ts
@@ -11,7 +11,7 @@ export const webStorage: StorageService = {
updateStoredMessage: () => Promise.resolve(),
editUserMessage: (chatId) => Promise.reject(new ChatNotFoundError(chatId)),
removeMessage: () => Promise.resolve(),
- updateChatTitle: () => Promise.resolve(),
+ updateChatTitle: () => Promise.resolve(false),
deleteChat: () => Promise.resolve(),
exportAllChatsZip: () => Promise.resolve(null),
diff --git a/apps/mirai-gui/client/src/stores/chat/persistence.test.ts b/apps/mirai-gui/client/src/stores/chat/persistence.test.ts
index 132e368af..e977b1d32 100644
--- a/apps/mirai-gui/client/src/stores/chat/persistence.test.ts
+++ b/apps/mirai-gui/client/src/stores/chat/persistence.test.ts
@@ -1,5 +1,5 @@
import { beforeEach, expect, it, vi } from "vitest";
-import type { ChatData, ChatMetadata } from "@/platform/services/storage";
+import { ChatNotFoundError, type ChatData, type ChatMetadata } from "@/platform/services/storage";
import { serializeToMarkdown } from "@/platform/services/storage/markdown/serialize";
import { extractMessageBlocks, parseMessage } from "@/platform/services/storage/markdown/parse";
import { useChatStore } from "@/stores/use-chat-store";
@@ -49,6 +49,19 @@ beforeEach(() => {
mocks.storage = inMemoryStorage();
});
+it("keeps the known title when recovering a missing chat file", async () => {
+ const storage = mocks.storage as ReturnType<typeof inMemoryStorage>;
+ const title = "Chosen title";
+ useChatStore.setState({ savedChats: [{ ...metadata, title }] });
+ storage.appendMessage.mockRejectedValueOnce(new ChatNotFoundError(CHAT_A));
+ const id = useChatStore.getState().addMessageTo(CHAT_A, { sender: Roles.User, text: "Question" }).id;
+
+ await useChatStore.getState().persistMessage(CHAT_A, id);
+
+ expect(storage.chats.get(CHAT_A)?.metadata.title).toBe(title);
+ expect(useChatStore.getState().savedChats[0]?.title).toBe(title);
+});
+
it("does not recreate an existing chat when reading it fails", async () => {
mocks.storage = tauriStorage as unknown as Record<string, unknown>;
mocks.invoke.mockImplementation(async (cmd: string) => {
diff --git a/apps/mirai-gui/client/src/stores/chat/persistence.ts b/apps/mirai-gui/client/src/stores/chat/persistence.ts
index 636a05241..0953883e4 100644
--- a/apps/mirai-gui/client/src/stores/chat/persistence.ts
+++ b/apps/mirai-gui/client/src/stores/chat/persistence.ts
@@ -26,10 +26,11 @@ export const persistMessage = async (
} catch (e) {
if (!(e instanceof ChatNotFoundError)) throw e;
const chatModel = get().chatModels[chatId];
+ const savedMetadata = get().savedChats.find((chat) => chat.id === chatId);
const now = Date.now();
const fallbackMetadata: ChatMetadata = {
id: chatId,
- title: UNTITLED_CHAT_TITLE,
+ title: savedMetadata?.title ?? UNTITLED_CHAT_TITLE,
modelId: chatModel?.modelId,
modelName: chatModel?.modelName,
createdAt: now,
diff --git a/apps/mirai-gui/client/src/stores/chat/title-generation.ts b/apps/mirai-gui/client/src/stores/chat/title-generation.ts
index fac040f06..52cc156fc 100644
--- a/apps/mirai-gui/client/src/stores/chat/title-generation.ts
+++ b/apps/mirai-gui/client/src/stores/chat/title-generation.ts
@@ -1,18 +1,7 @@
import { getPlatform } from "@/platform/platform-singleton";
import { useChatSessionStore } from "@/stores/use-chat-session-store";
-import { CHAT_TITLE_MAX_LENGTH, DEFAULT_CHAT_TITLE, UNTITLED_CHAT_TITLE } from "@/constants/chat";
-import { Roles } from "@/types/chat";
import type { ChatStoreApi } from "./types";
-const sanitizeChatTitle = (raw: string): string => {
- if (!raw) return "";
- let title = raw.trim();
- title = title.replace(/[\r\n]+/g, " ");
- title = title.replace(/\s+/g, " ").trim();
- title = title.replace(/^["'`]+|["'`]+$/g, "");
- return title;
-};
-
const isPlaceholderChatTitle = (title?: string | null): boolean => {
const normalized = (title ?? "").trim().toLowerCase();
return normalized.length === 0 || normalized === "untitled" || normalized === "new chat";
@@ -30,33 +19,22 @@ export const runChatTitleGeneration = async (
if (!chatId || userText.trim().length === 0) return;
const chatData = await getPlatform().storage.loadChat(chatId);
- const existingTitle = chatData?.metadata.title ?? UNTITLED_CHAT_TITLE;
- if (!isPlaceholderChatTitle(existingTitle)) return;
+ if (useChatSessionStore.getState().titleGenAbortChatId === chatId) return;
+ const existingTitle = chatData?.metadata.title;
+ if (existingTitle === undefined || !isPlaceholderChatTitle(existingTitle)) return;
const repoIdToUse = chatModel?.modelId || chatData?.metadata.modelId;
if (!repoIdToUse) return;
- const firstUserQuoted = userText.replace(/\s+/g, " ").trim().replace(/"/g, '\\"');
- // Small models copy a fallback phrase from the prompt instead of titling.
- const userOnlyInstruction =
- `Write a chat title of 2 to 4 words for the message below. Reply with the title only, no quotes, no punctuation at the end. ` +
- `Message: "${firstUserQuoted}"`;
-
const title = await getPlatform().chat.generateTitle({
repoId: repoIdToUse,
- messages: [{ role: Roles.User, content: userOnlyInstruction }],
+ userText,
});
- // A cancelled generation returns whatever came out before the cancel, usually
- // nothing; writing that or the default here would stop the next message from
- // generating a real title.
- if (useChatSessionStore.getState().titleGenAbortChatId === chatId) return;
-
- const candidateRaw = sanitizeChatTitle(title);
- // Longer than a manual rename allows means the model answered instead of titling.
- const candidate = candidateRaw.length > CHAT_TITLE_MAX_LENGTH ? "New chat" : candidateRaw || DEFAULT_CHAT_TITLE;
+ // A late result after Stop must not prevent the next message from trying again.
+ if (!title || useChatSessionStore.getState().titleGenAbortChatId === chatId) return;
const { storage } = getPlatform();
// The user may have renamed the chat while the model was thinking.
- await storage.updateChatTitle(chatId, candidate, existingTitle);
+ await storage.updateChatTitle(chatId, title, existingTitle);
const savedChats = await storage.listChats();
set({ savedChats });
};
diff --git a/apps/mirai-gui/client/src/stores/use-chat-session-store.ts b/apps/mirai-gui/client/src/stores/use-chat-session-store.ts
index 99df96070..2c76bfc81 100644
--- a/apps/mirai-gui/client/src/stores/use-chat-session-store.ts
+++ b/apps/mirai-gui/client/src/stores/use-chat-session-store.ts
@@ -52,7 +52,6 @@ type SessionStoreState = {
setActiveGenerating: (chatId: string, assistantMessageId: string) => void;
clearActiveGenerating: () => void;
setActiveAssistantMessageText: (text: string | null) => void;
- setActiveAssistantMessageOutput: (output: OutputShape | null) => void;
cancelTitleGen: () => Promise<boolean>;
activeRunId: string | null;
setActiveRunId: (runId: string | null) => void;
@@ -137,7 +136,6 @@ export const useChatSessionStore = create<SessionStoreState>((set, get) => ({
activeRunId: null,
}),
setActiveAssistantMessageText: (text) => set({ activeAssistantMessageText: text }),
- setActiveAssistantMessageOutput: (output) => set({ activeAssistantMessageOutput: output }),
activeRunId: null,
setActiveRunId: (runId) => set({ activeRunId: runId }),
diff --git a/apps/mirai-gui/client/src/stores/use-chat-store.ts b/apps/mirai-gui/client/src/stores/use-chat-store.ts
index 88b785973..9267f0b46 100644
--- a/apps/mirai-gui/client/src/stores/use-chat-store.ts
+++ b/apps/mirai-gui/client/src/stores/use-chat-store.ts
@@ -66,7 +66,7 @@ export type ChatState = {
loadSavedChats: () => Promise<void>;
deleteChat: (chatId: string) => Promise<void>;
createNewChat: (chatId: string) => void;
- updateChatTitle: (chatId: string, title: string, expectedTitle?: string) => Promise<void>;
+ updateChatTitle: (chatId: string, title: string, expectedTitle?: string) => Promise<boolean>;
generateChatTitle: (chatId: string, userText: string) => Promise<{ ok: boolean; error?: string }>;
suppressAutoSelect: (chatId: string, value: boolean) => void;
@@ -255,9 +255,18 @@ export const useChatStore = create<ChatState>((set, get) => ({
updateChatTitle: async (chatId: string, title: string, expectedTitle?: string) => {
const { storage } = getPlatform();
- await storage.updateChatTitle(chatId, title, expectedTitle);
- const savedChats = await storage.listChats();
- set({ savedChats });
+ const updated = await storage.updateChatTitle(chatId, title, expectedTitle);
+ if (updated) {
+ set((state) => ({
+ savedChats: state.savedChats.map((chat) => (chat.id === chatId ? { ...chat, title } : chat)),
+ }));
+ }
+ try {
+ set({ savedChats: await storage.listChats() });
+ } catch (error) {
+ console.warn("[storage] failed to refresh chats after title update", { chatId }, error);
+ }
+ return updated;
},
generateChatTitle: async (chatId: string, userText: string): Promise<{ ok: boolean; error?: string }> => {
diff --git a/apps/mirai-gui/desktop/src/chat/messages.rs b/apps/mirai-gui/desktop/src/chat/messages.rs
index 751085487..5d4f757c5 100644
--- a/apps/mirai-gui/desktop/src/chat/messages.rs
+++ b/apps/mirai-gui/desktop/src/chat/messages.rs
@@ -18,18 +18,14 @@ pub(super) fn sanitize(s: &str) -> String {
.collect()
}
-pub(super) fn build_non_system_message(
- message: &MsgIn,
- include_reasoning: bool,
-) -> ChatMessage {
+fn build_non_system_message(message: &MsgIn) -> ChatMessage {
let content = message.content.clone();
if matches!(message.role, ChatRole::User {}) {
return ChatMessage::user().with_text(content);
}
let mut assistant = ChatMessage::assistant();
- if include_reasoning && let Some(reasoning) = message.reasoning_content.as_deref().filter(|value| !value.is_empty())
- {
+ if let Some(reasoning) = message.reasoning_content.as_deref().filter(|value| !value.is_empty()) {
assistant = assistant.with_reasoning(reasoning.to_string());
}
assistant.with_text(content)
@@ -44,7 +40,7 @@ pub(super) fn build_messages(
.iter()
.map(|m| match m.role {
ChatRole::System {} => ChatMessage::system().with_text(m.content.clone()),
- _ => build_non_system_message(m, false),
+ _ => build_non_system_message(m),
})
.collect();
@@ -60,7 +56,7 @@ pub(super) fn build_messages(
// uzu rejects another system message in an accumulated session.
pub(super) fn build_tail_messages(tail: &[MsgIn]) -> Vec<ChatMessage> {
- tail.iter().filter(|m| !matches!(m.role, ChatRole::System {})).map(|m| build_non_system_message(m, true)).collect()
+ tail.iter().filter(|m| !matches!(m.role, ChatRole::System {})).map(build_non_system_message).collect()
}
pub(super) fn assistant_history_message(
@@ -73,9 +69,8 @@ pub(super) fn assistant_history_message(
}
let content = sanitize(text);
let reasoning_content = sanitize(reasoning.trim());
- if content != text || reasoning_content != reasoning {
- return None;
- }
+ // Match the final text/parsed fields sent to the client. The resident session
+ // keeps the original reasoning bytes and internal tool messages.
Some(MsgIn {
role: ChatRole::Assistant {},
content,
@@ -125,17 +120,15 @@ mod tests {
}
#[test]
- fn full_replay_omits_assistant_reasoning_blocks() {
+ fn full_replay_keeps_assistant_reasoning_blocks() {
let messages = build_messages(&[test_message(ChatRole::Assistant {}, "answer", Some("reasoning"))], None);
assert_eq!(messages[0].text().as_deref(), Some("answer"));
- assert_eq!(messages[0].reasoning(), None);
+ assert_eq!(messages[0].reasoning().as_deref(), Some("reasoning"));
}
#[test]
- fn unsafe_generated_history_is_not_reused() {
- assert!(assistant_history_message("broken \u{FFFD}", "", false).is_none());
- assert!(assistant_history_message("emoji \u{2764}\u{FE0F}", "", false).is_some());
- assert!(assistant_history_message("answer", " reasoning ", false).is_none());
+ fn incomplete_or_promoted_generated_history_is_not_reused() {
+ assert!(assistant_history_message("\n ", "reasoning", false).is_none());
assert!(assistant_history_message("answer", "reasoning", true).is_none());
}
diff --git a/apps/mirai-gui/desktop/src/chat/mod.rs b/apps/mirai-gui/desktop/src/chat/mod.rs
index 4cd4f24c6..d14698595 100644
--- a/apps/mirai-gui/desktop/src/chat/mod.rs
+++ b/apps/mirai-gui/desktop/src/chat/mod.rs
@@ -389,6 +389,36 @@ mod tests {
use super::{payloads::test_message, *};
+ #[test]
+ fn normalized_client_history_continues_the_resident_session() {
+ let state = ChatState::default();
+ let question = test_message(ChatRole::User {}, "question", None);
+ let raw_text = "An\u{0000} answer\u{FFFD} 👩\u{200D}💻\n";
+ let raw_reasoning = "\nConsider\u{FEFF} this\u{FFFD}.\n";
+ let projected = messages::assistant_history_message(raw_text, raw_reasoning, false).unwrap();
+ assert_eq!(projected.content, "An answer 👩\u{200D}💻\n");
+ assert_eq!(projected.reasoning_content.as_deref(), Some("Consider this."));
+ state.remember_history("model", vec![question.clone(), projected], Some(ReasoningEffort::Medium));
+
+ // The next request uses the finalized client fields, not raw engine output.
+ let parsed = messages::parsed_from(raw_text, raw_reasoning).unwrap();
+ let next_question = test_message(ChatRole::User {}, "next", None);
+ let request = vec![
+ question,
+ test_message(ChatRole::Assistant {}, &messages::sanitize(raw_text), parsed.chain_of_thought.as_deref()),
+ next_question.clone(),
+ ];
+ match state.plan_run("model", &request, Some(ReasoningEffort::Medium)) {
+ RunPlan::Continue {
+ tail,
+ } => assert!(tail == vec![next_question]),
+ RunPlan::Replay => panic!("client normalization should not discard the resident session"),
+ }
+
+ assert!(matches!(state.plan_run("other-model", &request, Some(ReasoningEffort::Medium)), RunPlan::Replay));
+ assert!(matches!(state.plan_run("model", &request, Some(ReasoningEffort::High)), RunPlan::Replay));
+ }
+
#[test]
fn continues_only_when_reasoning_prefix_matches() {
let state = ChatState::default();
diff --git a/apps/mirai-gui/desktop/src/chat/naming.rs b/apps/mirai-gui/desktop/src/chat/naming.rs
index 9daac6bf1..256299597 100644
--- a/apps/mirai-gui/desktop/src/chat/naming.rs
+++ b/apps/mirai-gui/desktop/src/chat/naming.rs
@@ -11,7 +11,26 @@ use uzu::{
use super::payloads::RunEvent;
-const NAMING_INSTRUCTION: &str = "Use set_chat_name to give this chat a concise, descriptive name in your first turn. Update the name when the conversation's main topic changes or the user asks you to rename it. Choose a short name of 3 to 50 characters. Set hidden to true for autonomous naming housekeeping, and false when the user explicitly asks you to name or rename the chat. Answer the user's request normally; do not mention autonomous housekeeping or ask for permission to name the chat.";
+// Approximate prose budget for the sidebar's 186px label at 13px Inter.
+// Glyph widths vary, so wider characters still rely on the UI's ellipsis.
+pub(super) const TITLE_TARGET_LENGTH: usize = 25;
+const TITLE_SOFT_LIMIT: usize = 28;
+pub(super) const TITLE_STYLE_INSTRUCTION: &str = "Write a natural, human-readable phrase with normal capitalization and spaces between words. \
+ Do not format it as a hashtag, an underscore-separated identifier, a hyphen-separated slug, or a CamelCase identifier. \
+ If the user explicitly supplies an exact name, preserve it.";
+
+fn naming_instruction() -> String {
+ format!(
+ "Use set_chat_name to give this chat a concise, descriptive name in your first turn. \
+ Update the name when the conversation's main topic changes or the user asks you to rename it. \
+ {TITLE_STYLE_INSTRUCTION} \
+ Aim for about {TITLE_TARGET_LENGTH} characters so the name fits in the sidebar. \
+ This is an approximate display budget, not a required length. \
+ If the tool warns that the name is too long, call it again with a shorter name before finishing this reply. \
+ Set hidden to true for autonomous naming housekeeping, and false when the user explicitly asks you to name or rename the chat. \
+ Answer the user's request normally; do not mention autonomous housekeeping or ask for permission to name the chat."
+ )
+}
#[derive(Default)]
struct ActiveRun {
@@ -41,7 +60,9 @@ impl ChatNaming {
uzu_tool_closure! {
/// Set or update the name of the current chat.
set_chat_name: async move |
- /// A concise, descriptive chat name of 3 to 50 characters.
+ /// A short, human-readable phrase with normal capitalization and spaces between words.
+ /// Avoid hashtags, underscore-separated identifiers, hyphen-separated slugs, and CamelCase identifiers.
+ /// Preserve an explicitly requested exact name; otherwise aim to fit the provided character budget.
name: String,
/// True for autonomous housekeeping; false when the user explicitly requests naming or renaming.
hidden: bool
@@ -49,11 +70,12 @@ impl ChatNaming {
// The transcript reads visibility from the recorded call.
let _ = hidden;
let name = normalize_name(&name)?;
+ let warning = title_length_warning(&name);
let mut run = state.lock().expect("chat naming mutex poisoned");
let channel = run.channel.as_ref().ok_or("No chat is currently running")?;
channel.send(RunEvent::ChatName { name: name.clone() })?;
run.name = Some(name);
- Ok("Chat name accepted.".to_string())
+ Ok(warning.unwrap_or_else(|| "Chat name accepted.".to_string()))
}
}
}
@@ -71,21 +93,33 @@ impl Drop for NamingRun {
}
}
-fn normalize_name(name: &str) -> Result<String, ErrorFuture> {
- let name = name.split_whitespace().collect::<Vec<_>>().join(" ");
- let name = name.trim_matches(['"', '\'', '`']).trim();
- // Match JavaScript's string length and the manual rename limit.
- if !(3..=50).contains(&name.encode_utf16().count()) || name.chars().any(char::is_control) {
- return Err("Chat names must contain 3 to 50 characters without control characters".into());
+pub(super) fn normalize_name(title: &str) -> Result<String, ErrorFuture> {
+ let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
+ let title = title.trim_matches(['"', '\'', '`']).trim();
+ if title.is_empty() || title.chars().any(char::is_control) {
+ return Err("Chat names must not be empty or contain control characters".into());
}
- Ok(name.to_string())
+ Ok(title.to_string())
+}
+
+fn title_length_warning(title: &str) -> Option<String> {
+ let length = title.chars().count();
+ (length > TITLE_SOFT_LIMIT).then(|| {
+ format!(
+ "Name saved, but may be clipped: it has {length} characters, above the {TITLE_SOFT_LIMIT}-character display budget. \
+ Aim for about {TITLE_TARGET_LENGTH} characters. \
+ Call set_chat_name again with a shorter phrase before finishing your reply; shorten the wording, keeping normal spaces. \
+ If you finish without replacing it, this name will be used and clipped in the interface as needed."
+ )
+ })
}
pub(super) fn add_naming_instruction(messages: &mut Vec<ChatMessage>) {
+ let instruction = naming_instruction();
if let Some(system) = messages.iter_mut().find(|message| message.role == (ChatRole::System {})) {
- *system = system.with_text(format!("\n\n{NAMING_INSTRUCTION}"));
+ *system = system.with_text(format!("\n\n{instruction}"));
} else {
- messages.insert(0, ChatMessage::system().with_text(NAMING_INSTRUCTION.to_string()));
+ messages.insert(0, ChatMessage::system().with_text(instruction));
}
}
@@ -93,15 +127,35 @@ pub(super) fn add_naming_instruction(messages: &mut Vec<ChatMessage>) {
mod tests {
use super::*;
+ fn arguments(name: &str) -> serde_json::Value {
+ serde_json::json!({ "name": name, "hidden": true })
+ }
+
+ fn capture(naming: &ChatNaming) -> (NamingRun, Arc<Mutex<Vec<serde_json::Value>>>) {
+ let received = Arc::new(Mutex::new(Vec::new()));
+ let events = received.clone();
+ let run = naming.begin(Channel::new(move |body| {
+ let tauri::ipc::InvokeResponseBody::Json(json) = body else {
+ panic!("Expected JSON event")
+ };
+ events.lock().unwrap().push(serde_json::from_str(&json).unwrap());
+ Ok(())
+ }));
+ (run, received)
+ }
+
#[test]
- fn normalizes_names_and_matches_manual_rename_limits() {
+ fn normalization_does_not_treat_the_display_budget_as_a_hard_limit() {
assert_eq!(normalize_name(" `Exploring\n London` ").unwrap(), "Exploring London");
assert!(normalize_name("\" \"").is_err());
- assert!(normalize_name("ab").is_err());
- assert!(normalize_name(&"x".repeat(51)).is_err());
- assert!(normalize_name(&"😀".repeat(25)).is_ok());
- assert!(normalize_name(&"😀".repeat(26)).is_err());
- assert!(normalize_name("bad\0name").is_err());
+ assert_eq!(normalize_name("X").unwrap(), "X");
+ assert!(normalize_name(&"x".repeat(TITLE_SOFT_LIMIT + 1)).is_ok());
+ assert!(normalize_name(&"x".repeat(51)).is_ok());
+ assert!(normalize_name("bad\0title").is_err());
+ assert!(title_length_warning(&"😀".repeat(TITLE_SOFT_LIMIT)).is_none());
+ let warning = title_length_warning(&"x".repeat(TITLE_SOFT_LIMIT + 3)).unwrap();
+ assert!(warning.contains(&format!("has {} characters", TITLE_SOFT_LIMIT + 3)));
+ assert!(warning.contains("before finishing your reply"));
}
#[test]
@@ -109,42 +163,101 @@ mod tests {
let mut messages = vec![ChatMessage::system().with_text("Be helpful.".to_string())];
add_naming_instruction(&mut messages);
assert_eq!(messages.len(), 1);
- assert_eq!(messages[0].text().unwrap(), format!("Be helpful.\n\n{NAMING_INSTRUCTION}"));
+ assert_eq!(messages[0].text().unwrap(), format!("Be helpful.\n\n{}", naming_instruction()));
+ }
+
+ #[test]
+ fn title_guidance_allows_some_room_above_the_target() {
+ assert!(naming_instruction().contains("Aim for about 25 characters"));
+ assert!(title_length_warning(&"x".repeat(25)).is_none());
+ assert!(title_length_warning(&"😀".repeat(28)).is_none());
+ let warning = title_length_warning(&"😀".repeat(29)).unwrap();
+ assert!(warning.contains("has 29 characters"));
+ assert!(warning.contains("above the 28-character display budget"));
+ assert!(warning.contains("Aim for about 25 characters"));
}
#[tokio::test]
- async fn tool_only_names_the_active_run_and_rejects_invalid_names() {
+ async fn tool_only_names_the_active_run_and_requires_name_and_visibility() {
let naming = ChatNaming::default();
let tool = naming.tool();
- let arguments = |name: &str| serde_json::json!({ "name": name, "hidden": true }).into();
- assert!(tool.execute(arguments("Before run")).await.is_err());
- let received = Arc::new(Mutex::new(Vec::new()));
- let events = received.clone();
- let run = naming.begin(Channel::new(move |body| {
- events.lock().unwrap().push(body);
- Ok(())
- }));
- assert!(tool.execute(arguments("x")).await.is_err());
+ assert!(tool.execute(arguments("Before run").into()).await.is_err());
+ let (run, received) = capture(&naming);
+ assert!(tool.execute(arguments("").into()).await.is_err());
assert!(run.name().is_none());
- assert!(tool.execute(serde_json::json!({ "name": "Missing flag" }).into()).await.is_err());
- assert!(tool.execute(serde_json::json!({ "name": "Bad flag", "hidden": "maybe" }).into()).await.is_err());
- tool.execute(arguments(" First\nname ")).await.unwrap();
- assert_eq!(run.name().as_deref(), Some("First name"));
+ for invalid in [
+ serde_json::json!({ "hidden": true }),
+ serde_json::json!({ "name": "Name" }),
+ serde_json::json!({ "name": "Name", "hidden": "maybe" }),
+ ] {
+ assert!(tool.execute(invalid.into()).await.is_err());
+ }
+ tool.execute(arguments(" First\nname ").into()).await.unwrap();
tool.execute(serde_json::json!({ "name": "Changed name", "hidden": false }).into()).await.unwrap();
assert_eq!(run.name().as_deref(), Some("Changed name"));
assert_eq!(received.lock().unwrap().len(), 2);
+ assert_eq!(received.lock().unwrap()[0], serde_json::json!({ "type": "chatName", "name": "First name" }));
drop(run);
- assert!(tool.execute(arguments("After run")).await.is_err());
+ assert!(tool.execute(arguments("After run").into()).await.is_err());
let next = naming.begin(Channel::new(|_| Ok(())));
assert!(next.name().is_none());
}
+ #[tokio::test]
+ async fn over_budget_names_remain_replaceable_across_tool_continuations() {
+ let naming = ChatNaming::default();
+ let tool = naming.tool();
+ let (run, received) = capture(&naming);
+ let too_long = "x".repeat(TITLE_SOFT_LIMIT + 1);
+ let result = tool.execute(arguments(&too_long).into()).await.unwrap();
+ let feedback = serde_json::Value::try_from(result).unwrap();
+ assert!(feedback.as_str().unwrap().contains("Call set_chat_name again"));
+ assert_eq!(received.lock().unwrap().len(), 1);
+ assert_eq!(run.name().as_deref(), Some(too_long.as_str()));
+ // A second automatic tool continuation is still inside the same run.
+ tool.execute(arguments("Shorter name").into()).await.unwrap();
+ assert_eq!(run.name().as_deref(), Some("Shorter name"));
+ drop(run);
+ assert_eq!(received.lock().unwrap().len(), 2);
+ }
+
+ #[tokio::test]
+ async fn keeps_the_latest_over_budget_name_without_truncating_it() {
+ let naming = ChatNaming::default();
+ let tool = naming.tool();
+ let (run, received) = capture(&naming);
+ tool.execute(arguments("Initial name").into()).await.unwrap();
+ tool.execute(arguments(&"x".repeat(TITLE_SOFT_LIMIT + 2)).into()).await.unwrap();
+ let latest = "x".repeat(TITLE_SOFT_LIMIT + 1);
+ tool.execute(arguments(&latest).into()).await.unwrap();
+ assert_eq!(run.name().as_deref(), Some(latest.as_str()));
+ drop(run);
+ assert_eq!(received.lock().unwrap().len(), 3);
+ }
+
+ #[tokio::test]
+ async fn accepted_names_are_already_published_when_a_run_is_interrupted() {
+ let naming = ChatNaming::default();
+ let tool = naming.tool();
+ let (run, received) = capture(&naming);
+ let too_long = "x".repeat(TITLE_SOFT_LIMIT + 1);
+ tool.execute(arguments(&too_long).into()).await.unwrap();
+ // A client may stop accepting events immediately after cancellation.
+ assert_eq!(received.lock().unwrap().len(), 1);
+ drop(run);
+ assert_eq!(received.lock().unwrap().len(), 1);
+ assert_eq!(received.lock().unwrap()[0]["name"], too_long);
+ assert!(tool.execute(arguments("After run").into()).await.is_err());
+ }
+
#[tokio::test]
async fn naming_tool_requires_hidden_and_accepts_the_standard_boolean_coercion() {
let naming = ChatNaming::default();
let tool = naming.tool();
let schema: serde_json::Value = tool.parameters.clone().unwrap().try_into().unwrap();
- assert!(schema["required"].as_array().unwrap().contains(&serde_json::json!("hidden")));
+ for field in ["name", "hidden"] {
+ assert!(schema["required"].as_array().unwrap().contains(&serde_json::json!(field)));
+ }
let run = naming.begin(Channel::new(|_| Ok(())));
tool.execute(serde_json::json!({ "name": "Markup name", "hidden": " TRUE " }).into()).await.unwrap();
assert_eq!(run.name().as_deref(), Some("Markup name"));
diff --git a/apps/mirai-gui/desktop/src/chat/payloads.rs b/apps/mirai-gui/desktop/src/chat/payloads.rs
index 359a1b685..168447d0a 100644
--- a/apps/mirai-gui/desktop/src/chat/payloads.rs
+++ b/apps/mirai-gui/desktop/src/chat/payloads.rs
@@ -241,8 +241,7 @@ pub(super) fn sampling_policy(payload: &Option<SamplingPolicyPayload>) -> Sampli
#[serde(rename_all = "camelCase")]
pub struct TitleGenPayload {
pub repo_id: String,
- #[serde(default)]
- pub messages: Vec<MsgIn>,
+ pub user_text: String,
}
#[cfg(test)]
diff --git a/apps/mirai-gui/desktop/src/chat/session.rs b/apps/mirai-gui/desktop/src/chat/session.rs
index 1fb83ebda..dfdf49d12 100644
--- a/apps/mirai-gui/desktop/src/chat/session.rs
+++ b/apps/mirai-gui/desktop/src/chat/session.rs
@@ -182,10 +182,15 @@ async fn create_session(
Ok((session, naming))
}
-/// Returns current date and time in RFC 3339 format: YYYY-MM-DDTHH:MM:SSZ
+/// Returns the current date and time in UTC and the device's local time, with explicit UTC offsets.
#[uzu_tool_function]
fn get_current_date_time() -> String {
- chrono::Local::now().to_rfc3339()
+ let now = chrono::Local::now();
+ format!(
+ "Current UTC date and time: {}.\nDevice local date and time: {}.",
+ now.with_timezone(&chrono::Utc).format("%A, %-d %B %Y at %H:%M:%S (UTC%:z)"),
+ now.format("%A, %-d %B %Y at %H:%M:%S (UTC%:z)"),
+ )
}
#[cfg(test)]
@@ -221,15 +226,23 @@ mod tests {
}
#[tokio::test]
- async fn date_time_tool_returns_the_current_local_rfc3339_timestamp() {
+ async fn date_time_tool_returns_the_same_current_instant_in_utc_and_local_time() {
let tool: ToolDescriptor = get_current_date_time.into();
assert_eq!(tool.name, "get_current_date_time");
let before = chrono::Local::now();
let result = tool.execute(serde_json::json!({}).into()).await.unwrap();
let after = chrono::Local::now();
let value: serde_json::Value = result.try_into().unwrap();
- let date = chrono::DateTime::parse_from_rfc3339(value.as_str().unwrap()).unwrap();
- assert!(date >= before && date <= after);
- assert_eq!(date.offset(), before.offset());
+ let (utc, local) = value.as_str().unwrap().split_once('\n').unwrap();
+ let utc =
+ chrono::DateTime::parse_from_str(utc, "Current UTC date and time: %A, %-d %B %Y at %H:%M:%S (UTC%:z).")
+ .unwrap();
+ let local =
+ chrono::DateTime::parse_from_str(local, "Device local date and time: %A, %-d %B %Y at %H:%M:%S (UTC%:z).")
+ .unwrap();
+ assert_eq!(utc, local);
+ assert!(utc.timestamp() >= before.timestamp() && utc.timestamp() <= after.timestamp());
+ assert_eq!(utc.offset().local_minus_utc(), 0);
+ assert_eq!(local.offset(), local.with_timezone(&chrono::Local).offset());
}
}
diff --git a/apps/mirai-gui/desktop/src/chat/title.rs b/apps/mirai-gui/desktop/src/chat/title.rs
index 84e7db630..df5daf97e 100644
--- a/apps/mirai-gui/desktop/src/chat/title.rs
+++ b/apps/mirai-gui/desktop/src/chat/title.rs
@@ -10,7 +10,8 @@ use uzu::{
use super::{
ChatState,
messages::{build_messages, sanitize},
- payloads::TitleGenPayload,
+ naming::{TITLE_STYLE_INSTRUCTION, TITLE_TARGET_LENGTH, normalize_name},
+ payloads::{MsgIn, TitleGenPayload},
session::ensure_session,
};
use crate::{error::AppResult, models::ReasoningSupport};
@@ -37,7 +38,14 @@ pub(super) async fn title_gen_inner(
);
return Ok(String::new());
}
- let messages = build_messages(&payload.messages, support.cheapest());
+ let messages = build_messages(
+ &[MsgIn {
+ role: uzu::types::session::chat::ChatRole::User {},
+ content: title_prompt(&payload.user_text),
+ reasoning_content: None,
+ }],
+ support.cheapest(),
+ );
let reply_config = ChatReplyConfig::create()
.with_token_limit(Some(DEFAULT_TITLE_GEN_TOKENS_LIMIT))
@@ -81,5 +89,28 @@ pub(super) async fn title_gen_inner(
"reasoningLen": reasoning.chars().count(),
})),
);
- Ok(sanitize(text.trim()))
+ if state.cancel_requested(TITLE_GEN_RUN_ID) {
+ return Ok(String::new());
+ }
+ Ok(normalize_name(&sanitize(text.trim())).unwrap_or_default())
+}
+
+fn title_prompt(user_text: &str) -> String {
+ format!(
+ "Give this chat a concise, descriptive title. {TITLE_STYLE_INSTRUCTION} Aim for about {TITLE_TARGET_LENGTH} characters \
+ so it fits in the sidebar. Reply with only the title, without quotes or explanation.\n\nMessage: {}",
+ serde_json::to_string(user_text).expect("serialize user message"),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn fallback_prompt_uses_the_same_target_length_as_the_naming_tool() {
+ let prompt = title_prompt("One\n\"two\"");
+ assert!(prompt.contains("Aim for about 25 characters"));
+ assert!(prompt.contains(r#""One\n\"two\"""#));
+ }
}
diff --git a/apps/mirai-gui/package.json b/apps/mirai-gui/package.json
index 40afd5b6c..8dbc44610 100644
--- a/apps/mirai-gui/package.json
+++ b/apps/mirai-gui/package.json
@@ -72,6 +72,7 @@
"jszip": "^3.10.2",
"katex": "^0.16.47",
"lucide-react": "^0.544.0",
+ "marked": "^18.0.14",
"motion": "^12.43.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
diff --git a/apps/mirai-gui/pnpm-lock.yaml b/apps/mirai-gui/pnpm-lock.yaml
index 6057bd468..37dae9e52 100644
--- a/apps/mirai-gui/pnpm-lock.yaml
+++ b/apps/mirai-gui/pnpm-lock.yaml
@@ -53,6 +53,9 @@ importers:
lucide-react:
specifier: ^0.544.0
version: 0.544.0([email protected])
+ marked:
+ specifier: ^18.0.14
+ version: 18.0.14
motion:
specifier: ^12.43.0
diff --git a/crates/legacy/cli/src/interactive/sessions/chat.rs b/crates/legacy/cli/src/interactive/sessions/chat.rs
index ab058f165..de45530bf 100644
--- a/crates/legacy/cli/src/interactive/sessions/chat.rs
+++ b/crates/legacy/cli/src/interactive/sessions/chat.rs
@@ -332,10 +332,15 @@ fn chat_state_mut(state: &mut ApplicationState) -> Option<&mut ChatSessionState>
.and_then(|session_state| session_state.as_any_mut().downcast_mut::<ChatSessionState>())
}
-/// Returns current date and time in RFC 3339 format: YYYY-MM-DDTHH:MM:SSZ
+/// Returns the current date and time in UTC and the device's local time, with explicit UTC offsets.
#[uzu_tool_function]
fn get_current_date_time() -> String {
- Local::now().to_rfc3339()
+ let now = Local::now();
+ format!(
+ "Current UTC date and time: {}.\nDevice local date and time: {}.",
+ now.with_timezone(&chrono::Utc).format("%A, %-d %B %Y at %H:%M:%S (UTC%:z)"),
+ now.format("%A, %-d %B %Y at %H:%M:%S (UTC%:z)"),
+ )
}
/// Sleeps for the given number of seconds before responding, at most 60 seconds.