Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

fix chat search dialog stutter on open (#8514)

Maheswar Kumar367d5bf8bf0a
diff --git a/studio/frontend/src/features/auth/index.ts b/studio/frontend/src/features/auth/index.ts
index d45c2dc2c77..0c566cc715a 100644
--- a/studio/frontend/src/features/auth/index.ts
+++ b/studio/frontend/src/features/auth/index.ts
@@ -6,8 +6,9 @@ export { ChangePasswordPage } from "./change-password-page";
export { authFetch, logout, refreshSession } from "./api";
export {
AUTH_SESSION_CLEARED_EVENT,
-
+ AUTH_SESSION_MARK_KEY,
AUTH_SESSION_STORED_EVENT,
+ AUTH_TOKEN_KEY,
clearAuthTokens,
getAuthToken,
getAuthSessionEpoch,
diff --git a/studio/frontend/src/features/auth/session.ts b/studio/frontend/src/features/auth/session.ts
index 0983891c289..0f820ff2994 100644
--- a/studio/frontend/src/features/auth/session.ts
+++ b/studio/frontend/src/features/auth/session.ts
@@ -13,6 +13,13 @@ export { AUTH_SESSION_CLEARED_EVENT, AUTH_SESSION_STORED_EVENT } from "./session
export const AUTH_TOKEN_KEY = "unsloth_auth_token";
export const AUTH_REFRESH_TOKEN_KEY = "unsloth_auth_refresh_token";
export const AUTH_MUST_CHANGE_PASSWORD_KEY = "unsloth_auth_must_change_password";
+/**
+ * The cross-document counterpart to `authSessionEpoch`, which is per-document memory and so
+ * says nothing to another tab. Written when a session begins, removed when it ends, never on
+ * a refresh, so a `storage` listener can tell an account switch from an hourly rotation. The
+ * value is opaque: it marks a session boundary, not the account.
+ */
+export const AUTH_SESSION_MARK_KEY = "unsloth_auth_session_mark";
let authSessionEpoch = 0;
@@ -61,7 +68,20 @@ export function storeAuthTokens(
localStorage.setItem(AUTH_REFRESH_TOKEN_KEY, refreshToken);
if (sessionStarted) {
authSessionEpoch += 1;
+ localStorage.setItem(
+ AUTH_SESSION_MARK_KEY,
+ `${Date.now()}.${Math.random()}`,
+ );
window.dispatchEvent(new Event(AUTH_SESSION_STORED_EVENT));
+ } else if (!localStorage.getItem(AUTH_SESSION_MARK_KEY)) {
+ // A session signed in before this key existed. Written on its next refresh so a later
+ // sign-out has a key to remove, since removing an absent one raises no storage event and
+ // would leave the other tabs on a signed-out account's titles. Not a new session, so no
+ // epoch bump: the tokens here are a rotation.
+ localStorage.setItem(
+ AUTH_SESSION_MARK_KEY,
+ `${Date.now()}.${Math.random()}`,
+ );
}
}
@@ -71,6 +91,7 @@ export function clearAuthTokens(): void {
localStorage.removeItem(AUTH_TOKEN_KEY);
localStorage.removeItem(AUTH_REFRESH_TOKEN_KEY);
localStorage.removeItem(AUTH_MUST_CHANGE_PASSWORD_KEY);
+ localStorage.removeItem(AUTH_SESSION_MARK_KEY);
window.dispatchEvent(new Event(AUTH_SESSION_CLEARED_EVENT));
}
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 1d04c8f0bf1..1bba081a951 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -38,6 +38,7 @@ import type {
UnloadModelRequest,
ValidateModelResponse,
} from "../types/api";
+import { publishChatHistoryRevision } from "../utils/chat-history-revision";
import {
type GgufVariantsRequestOptions,
ggufVariantsQuery,
@@ -46,6 +47,9 @@ import {
import { assertCompletedPaddedBody } from "./padded-response";
export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
+// Bumped alongside that event so other tabs, which never receive it, can drop caches
+// they built from a history this one has just changed.
+export { CHAT_HISTORY_REVISION_KEY } from "../utils/chat-history-revision";
export const CHAT_PROJECTS_UPDATED_EVENT = "unsloth-chat-projects-updated";
// bounds the request itself so a wedged socket cannot stall every reader waiting on the write
@@ -108,9 +112,23 @@ export class GenerationLengthError extends Error {
}
}
-export function notifyChatHistoryUpdated(): void {
+/**
+ * Announces a history change to this document and, through localStorage, to the others.
+ *
+ * `coalesce` is for the per-chunk streaming path alone: it holds the cross-tab write until
+ * the writes stop. Structural changes must not use it.
+ */
+export function notifyChatHistoryUpdated(options?: {
+ coalesce?: boolean;
+}): void {
if (typeof window !== "undefined") {
- window.dispatchEvent(new Event(CHAT_HISTORY_UPDATED_EVENT));
+ const coalesce = options?.coalesce === true;
+ // detail lets a listener tell a chunk save from a structural change (isCoalescedHistoryEvent)
+ window.dispatchEvent(
+ new CustomEvent(CHAT_HISTORY_UPDATED_EVENT, { detail: { coalesce } }),
+ );
+ // The event above is same-document; a storage write is what crosses.
+ publishChatHistoryRevision(coalesce);
}
}
@@ -838,6 +856,12 @@ export interface UpdateChatThreadOptions {
expectedTitle?: string;
/** And only while this is still the thread's opening user message. */
expectedOpeningMessageId?: string;
+ /**
+ * Off for one update inside a bulk action, which announces itself once at the end. Every
+ * notification is a synchronous localStorage write that wakes the other tabs, so Archive
+ * All would otherwise send one per thread.
+ */
+ notify?: boolean;
/** Give up on the write; used to stand a superseded settings PATCH down. */
signal?: AbortSignal;
}
@@ -875,7 +899,7 @@ export async function updateChatThread(
options.signal,
);
const thread = await parseJsonOrThrow<ThreadRecord>(response);
- notifyChatHistoryUpdated();
+ if (options.notify !== false) notifyChatHistoryUpdated();
return thread;
}
@@ -1063,6 +1087,7 @@ export async function getChatMessage(
export async function saveChatMessage(
message: MessageRecord,
+ options: { coalesce?: boolean } = {},
): Promise<MessageRecord> {
const response = await authFetch(
`/api/chat/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.id)}`,
@@ -1073,7 +1098,9 @@ export async function saveChatMessage(
},
);
const savedMessage = await parseJsonOrThrow<MessageRecord>(response);
- notifyChatHistoryUpdated();
+ // Coalescing is the streaming autosave's alone, since it lands here per chunk. A manual
+ // edit is one deliberate change and publishes at once.
+ notifyChatHistoryUpdated({ coalesce: options.coalesce === true });
return savedMessage;
}
@@ -1094,7 +1121,9 @@ export async function syncChatMessages(
},
);
const data = await parseJsonOrThrow<{ messages: MessageRecord[] }>(response);
- notifyChatHistoryUpdated();
+ // Pruning is how a message is deleted, which no other tab should keep matching for a
+ // whole unrelated generation. Without it this is the batched streaming autosave.
+ notifyChatHistoryUpdated({ coalesce: options.pruneMissing !== true });
return data.messages;
}
diff --git a/studio/frontend/src/features/chat/components/chat-search-dialog.tsx b/studio/frontend/src/features/chat/components/chat-search-dialog.tsx
index d7631a2f3c1..755a4482489 100644
--- a/studio/frontend/src/features/chat/components/chat-search-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/chat-search-dialog.tsx
@@ -9,13 +9,27 @@ import {
CommandList,
} from "@/components/ui/command";
import { useShortcut } from "@/features/settings/hooks/use-shortcut";
-import { Cancel01Icon, Message01Icon, Search01Icon } from "@hugeicons/core-free-icons";
+import { cn } from "@/lib/utils";
+import {
+ Cancel01Icon,
+ Message01Icon,
+ Search01Icon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate } from "@tanstack/react-router";
import { Command as CommandPrimitive } from "cmdk";
-import { useEffect, useMemo, useState } from "react";
-import { useChatSearchIndex } from "../hooks/use-chat-search-index";
+import { useDeferredValue, useEffect, useMemo, useState } from "react";
+import {
+ chatSearchIndexHasRows,
+ useChatSearchIndex,
+} from "../hooks/use-chat-search-index";
import { useChatSearchStore } from "../stores/chat-search-store";
+import { isCompactChatSearchList } from "../utils/chat-search-list-height";
+
+// Rows mounted while the dialog animates open; the rest follow once it settles, so a long
+// history never lays out hundreds of rows mid-transition.
+const INITIAL_ROW_COUNT = 24;
+const FULL_ROW_REVEAL_MS = 220;
// Lowercased whitespace tokens of the query (haystacks are lowercased in the index).
function queryTokens(search: string): string[] {
@@ -36,7 +50,9 @@ export function selectVisibleChats<
>(items: T[], search: string): T[] {
const tokens = queryTokens(search);
if (tokens.length === 0) return items;
- const userHits = items.filter((it) => haystackMatches(it.userSearchText, tokens));
+ const userHits = items.filter((it) =>
+ haystackMatches(it.userSearchText, tokens),
+ );
if (userHits.length > 0) return userHits;
return items.filter((it) => haystackMatches(it.searchText, tokens));
}
@@ -57,14 +73,48 @@ export function ChatSearchDialog() {
const navigate = useNavigate();
const { items, loading } = useChatSearchIndex(isOpen);
const [query, setQuery] = useState("");
+ // Filtering scans every conversation's text, so keep it off the keystroke path.
+ const deferredQuery = useDeferredValue(query);
+ // An empty query needs no scan, and the deferred value must not hold a previous filter
+ // over a reopened dialog.
+ const activeQuery = query === "" ? "" : deferredQuery;
+ const [rowLimit, setRowLimit] = useState(INITIAL_ROW_COUNT);
+ // Centered, so the height is decided per open and only ever relaxed compact -> fixed.
+ const [compactList, setCompactList] = useState(() =>
+ isCompactChatSearchList(true, chatSearchIndexHasRows()),
+ );
+
+ // Reset in the opening render, not an effect: Radix mounts the portal as this render
+ // commits, so an effect would trim rows only after the previous set was in the DOM.
+ // Resetting on close instead would tear rows down inside the exit animation.
+ const [wasOpen, setWasOpen] = useState(isOpen);
+ if (isOpen !== wasOpen) {
+ setWasOpen(isOpen);
+ if (isOpen) {
+ setQuery("");
+ setRowLimit(INITIAL_ROW_COUNT);
+ setCompactList(isCompactChatSearchList(true, chatSearchIndexHasRows()));
+ }
+ } else if (
+ compactList !== isCompactChatSearchList(compactList, items.length > 0)
+ ) {
+ // Backstop for an open with no hint at all: the fixed height is taken when the first
+ // build lands.
+ setCompactList(false);
+ }
const visibleItems = useMemo(
- () => selectVisibleChats(items, query),
- [items, query],
+ () => selectVisibleChats(items, activeQuery),
+ [items, activeQuery],
);
useEffect(() => {
- if (!isOpen) setQuery("");
+ if (!isOpen) return;
+ const timer = setTimeout(
+ () => setRowLimit(Number.POSITIVE_INFINITY),
+ FULL_ROW_REVEAL_MS,
+ );
+ return () => clearTimeout(timer);
}, [isOpen]);
// skipInTextFields keeps the composer's own ⌘K (and any browser find) intact
@@ -77,7 +127,7 @@ export function ChatSearchDialog() {
<CommandDialog
open={isOpen}
onOpenChange={setOpen}
- className="chat-search-surface rounded-3xl! max-sm:rounded-none! top-1/2 -translate-y-1/2 w-[635px] max-w-[calc(100%-2rem)] gap-0 p-0 ring-0 sm:max-w-[635px]"
+ className="chat-search-surface rounded-3xl! max-sm:rounded-none! top-1/2 -translate-y-1/2 w-[635px] max-w-[calc(100%-2rem)] gap-0 p-0 ring-0 duration-[180ms] ease-[cubic-bezier(0.16,1,0.3,1)] sm:max-w-[635px]"
overlayClassName="bg-transparent supports-backdrop-filter:backdrop-blur-none"
>
<Command className="rounded-3xl p-0" shouldFilter={false}>
@@ -89,6 +139,9 @@ export function ChatSearchDialog() {
/>
<CommandPrimitive.Input
placeholder="Search chats..."
+ // Controlled: reopening inside the exit animation reuses the mounted tree, so
+ // cmdk would keep the previous text while the filter state is clear.
+ value={query}
onValueChange={setQuery}
className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
@@ -98,10 +151,19 @@ export function ChatSearchDialog() {
className="flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
aria-label="Close"
>
- <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} className="size-4" />
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ strokeWidth={2}
+ className="size-4"
+ />
</button>
</div>
- <CommandList className="cmd-native-scrollbar hover-scrollbar max-h-[420px] p-1">
+ <CommandList
+ className={cn(
+ "cmd-native-scrollbar hover-scrollbar p-1",
+ compactList ? "max-h-[420px]" : "h-[420px] max-h-[60dvh]",
+ )}
+ >
<CommandEmpty className="py-6 text-center text-xs text-muted-foreground">
{loading
? "Loading…"
@@ -110,22 +172,36 @@ export function ChatSearchDialog() {
: "No chats match."}
</CommandEmpty>
<CommandGroup className="p-0">
- {visibleItems.map((item) => (
+ {visibleItems.slice(0, rowLimit).map((item) => (
<CommandPrimitive.Item
key={item.id}
value={item.id}
onSelect={() => {
+ // The list can trail the input by a render, so a row is activatable only
+ // if the live query still matches it. Scanned on activation, not per key.
+ if (
+ query !== activeQuery &&
+ !selectVisibleChats(items, query).some(
+ (live) => live.id === item.id,
+ )
+ ) {
+ return;
+ }
navigate({
to: "/chat",
search:
item.type === "single"
? {
thread: item.id,
- ...(item.projectId ? { project: item.projectId } : {}),
+ ...(item.projectId
+ ? { project: item.projectId }
+ : {}),
}
: {
compare: item.id,
- ...(item.projectId ? { project: item.projectId } : {}),
+ ...(item.projectId
+ ? { project: item.projectId }
+ : {}),
},
});
close();
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts b/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts
index d6086c25915..fedace70fd3 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts
@@ -1,14 +1,33 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import {
+ AUTH_SESSION_CLEARED_EVENT,
+ AUTH_SESSION_MARK_KEY,
+ AUTH_TOKEN_KEY,
+ getAuthSessionEpoch,
+} from "@/features/auth";
import { useEffect, useRef, useState } from "react";
-import { batchListChatMessages, CHAT_HISTORY_UPDATED_EVENT } from "../api/chat-api";
+import {
+ CHAT_HISTORY_REVISION_KEY,
+ CHAT_HISTORY_UPDATED_EVENT,
+ batchListChatMessages,
+} from "../api/chat-api";
import type { MessageRecord } from "../types";
+import { isCoalescedHistoryEvent } from "../utils/chat-history-revision";
import {
listStoredChatMessages,
listStoredChatThreads,
} from "../utils/chat-history-storage";
-import { formatMcpToolName, mcpServerFromProvenance } from "../utils/mcp-tool-name";
+import {
+ chatSearchHadRows,
+ forgetChatSearchHasRows,
+ rememberChatSearchHasRows,
+} from "../utils/chat-search-history-hint";
+import {
+ formatMcpToolName,
+ mcpServerFromProvenance,
+} from "../utils/mcp-tool-name";
import { attachmentsPastedText } from "../utils/pasted-text.ts";
export interface ChatSearchItem {
@@ -26,6 +45,8 @@ export interface ChatSearchItem {
const THREAD_LIMIT = 200;
const SEARCH_REBUILD_DEBOUNCE_MS = 300;
+// Past the dialog's 180ms exit, so releasing uncached rows never lands mid-animation.
+const ROW_RELEASE_DELAY_MS = 300;
// Keys whose values are base64 image/audio payloads, not searchable text.
const BINARY_KEY = /b64|base64|^(images?|audio|video)$/i;
@@ -95,7 +116,10 @@ function extractText(message: MessageRecord): string {
for (const part of content) {
if (!part || typeof part !== "object") continue;
const p = part as Record<string, unknown>;
- if ((p.type === "text" || p.type === "reasoning") && typeof p.text === "string") {
+ if (
+ (p.type === "text" || p.type === "reasoning") &&
+ typeof p.text === "string"
+ ) {
parts.push(p.text);
} else if (p.type === "thinking") {
const t = typeof p.thinking === "string" ? p.thinking : p.text;
@@ -107,21 +131,33 @@ function extractText(message: MessageRecord): string {
parts.push(mcpServer);
// Index the rendered "Server · tool" label too, so pasting it matches.
const label =
- typeof p.toolName === "string" ? formatMcpToolName(p.toolName, mcpServer) : null;
+ typeof p.toolName === "string"
+ ? formatMcpToolName(p.toolName, mcpServer)
+ : null;
if (label) parts.push(label);
}
- const args = searchableText(typeof p.argsText === "string" ? p.argsText : p.args);
+ const args = searchableText(
+ typeof p.argsText === "string" ? p.argsText : p.args,
+ );
if (args) parts.push(args);
const result = searchableText(p.result);
if (result) parts.push(result);
} else if (p.type === "source") {
- for (const v of [p.title, p.url]) if (typeof v === "string") parts.push(v);
+ for (const v of [p.title, p.url])
+ if (typeof v === "string") parts.push(v);
}
}
return parts.join(" ").replace(/\s+/g, " ").trim();
}
-async function buildIndex(): Promise<ChatSearchItem[]> {
+interface ChatSearchIndexBuild {
+ items: ChatSearchItem[];
+ complete: boolean;
+}
+
+// Exported for the bare-node cache harness: it needs to prove that a failed read is not
+// indistinguishable from a completed empty history.
+export async function buildChatSearchIndex(): Promise<ChatSearchIndexBuild> {
const active = (
await listStoredChatThreads({ includeArchived: false })
).slice(0, THREAD_LIMIT);
@@ -173,6 +209,7 @@ async function buildIndex(): Promise<ChatSearchItem[]> {
let messagesByThread = await batchListChatMessages(allThreadIds).catch(
() => new Map<string, MessageRecord[]>(),
);
+ let complete = true;
// Legacy-only chats can exist before server-side history import finishes.
// Fill only the missing ids via the legacy path instead of one request per
@@ -182,10 +219,16 @@ async function buildIndex(): Promise<ChatSearchItem[]> {
);
if (missingThreadIds.length > 0) {
const legacyEntries = await Promise.all(
- missingThreadIds.map(async (threadId) => [
- threadId,
- await listStoredChatMessages(threadId).catch(() => []),
- ] as const),
+ missingThreadIds.map(
+ async (threadId) =>
+ [
+ threadId,
+ await listStoredChatMessages(threadId).catch(() => {
+ complete = false;
+ return [];
+ }),
+ ] as const,
+ ),
);
messagesByThread = new Map(messagesByThread);
for (const [threadId, messages] of legacyEntries) {
@@ -221,39 +264,213 @@ async function buildIndex(): Promise<ChatSearchItem[]> {
}
results.sort((a, b) => b.createdAt - a.createdAt);
- return results;
+ return { items: results, complete };
+}
+
+// THREAD_LIMIT bounds rows, not bytes: a tool-heavy history would otherwise hold tens of
+// megabytes behind a closed dialog. Past this the index is rebuilt on each open.
+const MAX_CACHED_SEARCH_TEXT_CHARS = 4_000_000;
+
+// Last built index, kept across opens so reopening paints the previous rows at
+// once and revalidates in place instead of collapsing back to the empty state.
+let cachedIndex: ChatSearchItem[] | null = null;
+let cachedIndexEpoch = -1;
+
+// Scoped to the auth session: a web logout only navigates, and a second account must never
+// open onto the previous user's chats.
+function readCachedIndex(): ChatSearchItem[] | null {
+ if (cachedIndexEpoch !== getAuthSessionEpoch()) {
+ // The next account's history is unknown, so the previous one's hint cannot size it
+ // either. -1 is "nothing cached yet", every page load, and leaves this account's alone.
+ if (cachedIndexEpoch !== -1) forgetChatSearchHasRows();
+ cachedIndex = null;
+ cachedIndexEpoch = getAuthSessionEpoch();
+ }
+ return cachedIndex;
+}
+
+function cachedSearchTextChars(items: ChatSearchItem[]): number {
+ let total = 0;
+ for (const item of items) total += item.searchText.length;
+ return total;
+}
+
+// Exported for tests, which drive the real bookkeeping rather than a stand-in.
+export function writeCachedIndex(next: ChatSearchItem[] | null): void {
+ cachedIndexEpoch = getAuthSessionEpoch();
+ cachedIndex =
+ next !== null && cachedSearchTextChars(next) > MAX_CACHED_SEARCH_TEXT_CHARS
+ ? null
+ : next;
+ // A build answers outright. An invalidation only says the history changed: a remembered
+ // ROWS answer still holds, an EMPTY one may be about to gain its first chat.
+ if (next !== null) rememberChatSearchHasRows(next.length > 0);
+ else if (chatSearchHadRows() === false) forgetChatSearchHasRows();
+}
+
+// A partial build is useful for this open, but it is not an answer about whether the history
+// has rows. In particular, recording [] after every message read failed would make the next
+// page load open compact and then grow mid-animation once connectivity recovered.
+export function publishChatSearchBuild(
+ build: ChatSearchIndexBuild,
+): ChatSearchItem[] {
+ if (build.complete) {
+ writeCachedIndex(build.items);
+ } else {
+ cachedIndexEpoch = getAuthSessionEpoch();
+ cachedIndex = null;
+ // An incomplete build cannot preserve a previous empty answer: partial rows already
+ // disprove it, while no rows only mean the history could not be read. A positive partial
+ // answer is safe and keeps the next open from starting compact again.
+ if (build.items.length > 0) rememberChatSearchHasRows(true);
+ else forgetChatSearchHasRows();
+ }
+ return build.items;
+}
+
+// Once a structural refresh has a deadline, stream chunks may join that refresh but must not
+// keep moving it. If the deadline already fired (no timer remains), a later chunk schedules
+// the usual follow-up so the in-flight snapshot is eventually refreshed.
+export function shouldPostponeSearchRebuild(
+ structuralRebuildPending: boolean,
+ event: Event,
+): boolean {
+ return !(structuralRebuildPending && isCoalescedHistoryEvent(event));
+}
+
+// An account change made elsewhere. Private: it reaches an open dialog's request sequence,
+// which nothing outside can see.
+const SEARCH_SESSION_CHANGED_EVENT = "unsloth-chat-search-session-changed";
+
+// A history change in another tab or from an API client never reaches this document, so the
+// cache would otherwise open onto rows that no longer exist and navigate to a dead thread.
+if (typeof window !== "undefined") {
+ window.addEventListener("storage", (event) => {
+ // An account switch elsewhere arrives as a storage write alone: the epoch and its events
+ // are both this document's. The mark moves on a session boundary and not on an hourly
+ // refresh, which must not cost a warm cache.
+ if (
+ event.key === AUTH_SESSION_MARK_KEY ||
+ (event.key === AUTH_TOKEN_KEY && event.newValue === null)
+ ) {
+ writeCachedIndex(null);
+ // Shared by every account on the origin, so it cannot answer for the new one.
+ forgetChatSearchHasRows();
+ // History first, for the sidebar. Then the account change, which the epoch check
+ // cannot see: an open dialog restarts at once, superseding the rebuild just queued.
+ window.dispatchEvent(new Event(CHAT_HISTORY_UPDATED_EVENT));
+ window.dispatchEvent(new Event(SEARCH_SESSION_CHANGED_EVENT));
+ return;
+ }
+ if (event.key !== CHAT_HISTORY_REVISION_KEY) return;
+ writeCachedIndex(null);
+ // Dropping the cache alone leaves an open dialog on pre-change rows with nothing
+ // scheduled. Re-raised locally so every in-tab listener treats it as a local change.
+ window.dispatchEvent(new Event(CHAT_HISTORY_UPDATED_EVENT));
+ });
+ // The hint outlives the page, so a logout takes it: otherwise the next account to sign in
+ // after a reload is sized by the previous one's history.
+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {
+ forgetChatSearchHasRows();
+ });
+}
+
+// Whether to size for rows, readable during render so the dialog picks a height before its
+// opening paint. A built cache answers exactly; otherwise the last build's hint does, which
+// is all the first open of a page load has. null means genuinely unknown.
+export function chatSearchIndexHasRows(): boolean | null {
+ const cached = readCachedIndex();
+ if (cached !== null) return cached.length > 0;
+ return chatSearchHadRows();
}
export function useChatSearchIndex(enabled: boolean): {
items: ChatSearchItem[];
loading: boolean;
} {
- const [items, setItems] = useState<ChatSearchItem[]>([]);
+ const [items, setItems] = useState<ChatSearchItem[]>(
+ () => readCachedIndex() ?? [],
+ );
const [loading, setLoading] = useState(false);
const requestSeqRef = useRef(0);
+ // Discarded in the opening render, not in the effect that rebuilds: that runs after the
+ // commit, so the invalidated rows would paint first.
+ const [wasEnabled, setWasEnabled] = useState(enabled);
+ if (enabled !== wasEnabled) {
+ setWasEnabled(enabled);
+ if (enabled && readCachedIndex() === null) {
+ if (items.length > 0) setItems([]);
+ if (!loading) setLoading(true);
+ }
+ }
+
useEffect(() => {
if (!enabled) {
- // Clear stale results so the next open doesn't flash old items.
- setItems([]);
setLoading(false);
- return;
+ // With nothing cached these rows are the last thing holding the conversation text.
+ // Released after the exit, not during the closing render: the portal stays mounted for
+ // the animation, and emptying it there is the teardown this dialog exists to avoid.
+ let release: ReturnType<typeof setTimeout> | null = null;
+ const scheduleRelease = () => {
+ // Never postponed: a stream invalidates per chunk, and restarting would hold the
+ // index for the whole generation.
+ if (release !== null) return;
+ release = setTimeout(() => {
+ release = null;
+ if (readCachedIndex() !== null) return;
+ // Same reference when there is nothing to release, so no needless re-render.
+ setItems((prev) => (prev.length > 0 ? [] : prev));
+ }, ROW_RELEASE_DELAY_MS);
+ };
+ scheduleRelease();
+ // History can change while closed, so drop the cache rather than reopening onto chats
+ // that no longer exist. Only the cache: clearing state re-renders per streaming chunk.
+ const invalidate = () => {
+ writeCachedIndex(null);
+ // The release above may already have run while the cache was still there.
+ scheduleRelease();
+ };
+ window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, invalidate);
+ return () => {
+ if (release !== null) clearTimeout(release);
+ window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, invalidate);
+ };
}
let cancelled = false;
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
+ // Set by a history event, cleared once its rebuild lands, so a close in between knows
+ // the cached snapshot is stale.
+ let rebuildPending = false;
+ let structuralRebuildPending = false;
const run = () => {
const seq = ++requestSeqRef.current;
- setLoading(true);
- buildIndex()
- .then((result) => {
- // Drop out-of-order responses so a slower rebuild can't clobber a fresher one.
+ // A build straddling a logout describes the account it started under.
+ const epoch = getAuthSessionEpoch();
+ // Only the first build has nothing to show; later ones refresh silently.
+ if (readCachedIndex() === null) setLoading(true);
+ buildChatSearchIndex()
+ .then((build) => {
+ // Drop out-of-order responses, and never repopulate a cache already dropped.
if (cancelled || seq !== requestSeqRef.current) return;
+ if (epoch !== getAuthSessionEpoch()) return;
+ const result = publishChatSearchBuild(build);
+ // A build older than the history event does not satisfy it, so the flag only
+ // clears once nothing is queued.
+ if (debounceTimer === null) {
+ rebuildPending = false;
+ structuralRebuildPending = false;
+ }
setItems(result);
})
.catch(() => {
if (cancelled || seq !== requestSeqRef.current) return;
- setItems([]);
+ // A rebuild that failed leaves nothing fresher, and what is cached is the snapshot
+ // it was called to replace: keeping it would offer a deleted chat as a live result
+ // for as long as the dialog stays open.
+ if (rebuildPending) writeCachedIndex(null);
+ setItems(readCachedIndex() ?? []);
})
.finally(() => {
if (cancelled || seq !== requestSeqRef.current) return;
@@ -261,20 +478,59 @@ export function useChatSearchIndex(enabled: boolean): {
});
};
- const scheduleRebuild = () => {
+ const scheduleRebuild = (event: Event) => {
+ rebuildPending = true;
+ const structural = !isCoalescedHistoryEvent(event);
+ // retires a build that read the history before this change, which would else republish it
+ if (structural) {
+ structuralRebuildPending = true;
+ requestSeqRef.current += 1;
+ }
+ if (
+ debounceTimer !== null &&
+ !shouldPostponeSearchRebuild(structuralRebuildPending, event)
+ ) {
+ return;
+ }
if (debounceTimer !== null) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
debounceTimer = null;
+ // The structural deadline has now been honored. Stream events arriving while this
+ // rebuild runs should return to quiet-window coalescing instead of forcing another
+ // rebuild every debounce interval for the rest of the generation.
+ structuralRebuildPending = false;
if (!cancelled) run();
}, SEARCH_REBUILD_DEBOUNCE_MS);
};
+ // Not a history change: the rows on screen belong to whoever was signed in a moment ago,
+ // so they go now. Rebuilding at once also advances the request sequence, retiring a build
+ // still in flight for that account.
+ const onSessionChanged = () => {
+ if (cancelled) return;
+ if (debounceTimer !== null) {
+ clearTimeout(debounceTimer);
+ debounceTimer = null;
+ }
+ setItems([]);
+ run();
+ };
+
run();
window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, scheduleRebuild);
+ window.addEventListener(SEARCH_SESSION_CHANGED_EVENT, onSessionChanged);
return () => {
cancelled = true;
if (debounceTimer !== null) clearTimeout(debounceTimer);
+ // Closing cancels a queued rebuild, so the snapshot left behind is stale and must not
+ // survive the next open. The rendered rows stay: clearing them here tears the list down
+ // inside the exit animation.
+ if (rebuildPending) writeCachedIndex(null);
window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, scheduleRebuild);
+ window.removeEventListener(
+ SEARCH_SESSION_CHANGED_EVENT,
+ onSessionChanged,
+ );
};
}, [enabled]);
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
index f59ff9be720..9968e3913d0 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
@@ -264,9 +264,21 @@ export async function archiveAllChatItems(
requestPromptQueueStop(toArchive.map((thread) => thread.id));
for (const t of toArchive) cancelIfRunning(t.id);
- await Promise.all(
- toArchive.map((t) => updateStoredChatThread(t.id, { archived: true })),
+ // allSettled, not all: Promise.all rejects while slower siblings are still writing silently.
+ const writes = await Promise.allSettled(
+ toArchive.map((t) =>
+ updateStoredChatThread(t.id, { archived: true }, { notify: false }),
+ ),
+ );
+ const failure = writes.find(
+ (write): write is PromiseRejectedResult => write.status === "rejected",
);
+ if (failure) {
+ // Silent updates mean a partial batch announces itself nowhere, so whatever did
+ // archive would stay listed here and in every other tab until some later change.
+ notifyChatHistoryUpdated();
+ throw failure.reason;
+ }
// Reset only when this action archived the active single thread or compare
// pair. An already-archived chat opened from the archive is not in
diff --git a/studio/frontend/src/features/chat/utils/chat-history-revision.ts b/studio/frontend/src/features/chat/utils/chat-history-revision.ts
new file mode 100644
index 00000000000..24480b9eb2f
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/chat-history-revision.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// How a history change crosses documents: the event chat-api raises alongside it is
+// same-document. Only that something changed is published, never a chat id or any text.
+export const CHAT_HISTORY_REVISION_KEY = "unsloth_chat_history_revision";
+
+// Long enough to swallow a generation's per-chunk saves, short enough that a tab going
+// quiet publishes before anyone reads a stale row. Exported for the tests.
+export const CROSS_TAB_REVISION_DEBOUNCE_MS = 500;
+
+let revisionWriteTimer: ReturnType<typeof setTimeout> | null = null;
+
+/**
+ * Whether a same-document history event came from the coalesced streaming autosave rather than
+ * a structural change.
+ *
+ * A listener that retires work on a history change needs the difference: chunk saves arrive
+ * faster than any debounce, so treating one as structural starves that work for a whole
+ * generation. Anything without the detail counts as structural, including the event the
+ * cross-tab listener re-raises, since a revision write only lands once changes have settled.
+ */
+export function isCoalescedHistoryEvent(event: Event): boolean {
+ return (event as CustomEvent<{ coalesce?: boolean }>).detail?.coalesce === true;
+}
+
+function storage(): Storage | null {
+ // no window under node, and the localStorage getter itself throws in some privacy modes
+ try {
+ if (typeof window === "undefined") return null;
+ return window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+function writeRevision(): void {
+ const store = storage();
+ if (!store) return;
+ try {
+ store.setItem(CHAT_HISTORY_REVISION_KEY, `${Date.now()}.${Math.random()}`);
+ } catch {
+ // A full quota costs one stale open, not correctness: other tabs revalidate anyway.
+ }
+}
+
+function clearPending(): boolean {
+ if (revisionWriteTimer === null) return false;
+ clearTimeout(revisionWriteTimer);
+ revisionWriteTimer = null;
+ return true;
+}
+
+/**
+ * Publishes a history change to the other documents.
+ *
+ * `coalesce` is for the per-chunk streaming path alone, where a write per chunk would block
+ * this tab and wake every other one. A structural change must not use it: sharing the
+ * stream's quiet window leaves a deleted chat live in another tab for a whole generation.
+ */
+export function publishChatHistoryRevision(coalesce: boolean): void {
+ if (!coalesce) {
+ // Anything still waiting says no more than this does.
+ clearPending();
+ writeRevision();
+ return;
+ }
+ // Rescheduled rather than left to run, so a generation collapses into one write instead
+ // of one per debounce period.
+ clearPending();
+ revisionWriteTimer = setTimeout(() => {
+ revisionWriteTimer = null;
+ writeRevision();
+ }, CROSS_TAB_REVISION_DEBOUNCE_MS);
+}
+
+/** Publishes a coalesced write that is still waiting. Nothing to do when none is. */
+export function flushChatHistoryRevision(): void {
+ if (clearPending()) writeRevision();
+}
+
+// A coalesced write would otherwise leave with the page, stranding the other tabs.
+if (typeof window !== "undefined") {
+ window.addEventListener("pagehide", flushChatHistoryRevision);
+}
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index 7a8368f2b78..5fe311df714 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -956,7 +956,8 @@ export async function saveStoredChatMessage(
throw new Error(`Thread ${message.threadId} was deleted`);
}
await ensureStoredChatThread(message.threadId);
- return saveChatMessage(message);
+ // The per-chunk autosave behind a streaming response.
+ return saveChatMessage(message, { coalesce: true });
}
export async function syncStoredChatMessages(
@@ -990,7 +991,7 @@ export async function saveStoredChatThread(
export async function updateStoredChatThread(
threadId: string,
patch: ChatThreadWritePatch,
- options: { signal?: AbortSignal } = {},
+ options: { notify?: boolean; signal?: AbortSignal } = {},
): Promise<ThreadRecord | undefined> {
if (isThreadIncognito(threadId)) return undefined;
// Same bound and same signal as the write it precedes: a stall here left the settings
diff --git a/studio/frontend/src/features/chat/utils/chat-search-history-hint.ts b/studio/frontend/src/features/chat/utils/chat-search-history-hint.ts
new file mode 100644
index 00000000000..5c0e506af5d
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/chat-search-history-hint.ts
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Whether the last build found any chats, remembered across page loads. The index is built
+// only while the dialog is open, so without this the first open of a page load cannot tell
+// "no chats" from "not looked yet". A bare flag: never a count, never any chat text.
+const CHAT_SEARCH_HAS_ROWS_KEY = "unsloth_chat_search_has_rows";
+
+// Only the empty answer is aged out, and it carries the time it was written. Chats created
+// on another device or through the API never reach this tab, so emptiness cannot stay
+// authoritative: a stale "has rows" costs a full-height dialog over a short history, while a
+// stale "empty" sizes a populated one compact and then grows it mid-open, which is the
+// stutter the hint exists to prevent. Long enough to survive a restart within a working day.
+const EMPTY_HINT_TTL_MS = 12 * 60 * 60 * 1000;
+
+function storage(): Storage | null {
+ // no window under node, and the localStorage getter itself throws in some privacy modes
+ try {
+ if (typeof window === "undefined") return null;
+ return window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+export function rememberChatSearchHasRows(hasRows: boolean): void {
+ const store = storage();
+ if (!store) return;
+ try {
+ store.setItem(CHAT_SEARCH_HAS_ROWS_KEY, hasRows ? "1" : `0.${Date.now()}`);
+ } catch {
+ // A hint, not state: a full quota costs a resize on one open, not correctness.
+ }
+}
+
+export function forgetChatSearchHasRows(): void {
+ const store = storage();
+ if (!store) return;
+ try {
+ store.removeItem(CHAT_SEARCH_HAS_ROWS_KEY);
+ } catch {
+ // As above.
+ }
+}
+
+/**
+ * The last completed build's answer, or null when unknown: never built here, forgotten on a
+ * session change, an empty answer past its window, or no localStorage. Unknown must stay
+ * distinct from known-empty, since only known-empty can size compact without risking a
+ * mid-open resize.
+ */
+export function chatSearchHadRows(): boolean | null {
+ const store = storage();
+ if (!store) return null;
+ try {
+ const raw = store.getItem(CHAT_SEARCH_HAS_ROWS_KEY);
+ if (raw === null) return null;
+ if (raw === "1") return true;
+ // A bare "0" was written before the stamp existed, so its age is unknown.
+ if (!raw.startsWith("0.")) return null;
+ const writtenAt = Number(raw.slice(2));
+ if (!Number.isFinite(writtenAt)) return null;
+ // A negative age is a clock change, which says as little as an expired one.
+ const age = Date.now() - writtenAt;
+ if (age < 0 || age > EMPTY_HINT_TTL_MS) return null;
+ return false;
+ } catch {
+ return null;
+ }
+}
diff --git a/studio/frontend/src/features/chat/utils/chat-search-list-height.ts b/studio/frontend/src/features/chat/utils/chat-search-list-height.ts
new file mode 100644
index 00000000000..01716113ff3
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/chat-search-list-height.ts
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The dialog holds one list height for a whole open: compact only when the history is known
+// to have no rows, given up as soon as rows arrive, so filtering never resizes it. `hasRows`
+// must therefore answer for a history not yet indexed (see chatSearchIndexHasRows): reading
+// that as "no rows" sizes a populated dialog compact and then grows it mid-open.
+export function isCompactChatSearchList(
+ wasCompact: boolean,
+ hasRows: boolean | null,
+): boolean {
+ // null is "unknown", which only a completed build settles. Compact is wrong for a history
+ // that turns out to have rows, so unknown takes the fixed height.
+ return wasCompact && hasRows === false;
+}
diff --git a/studio/frontend/tests/archive-all-partial-failure.test.ts b/studio/frontend/tests/archive-all-partial-failure.test.ts
new file mode 100644
index 00000000000..d7fcb600062
--- /dev/null
+++ b/studio/frontend/tests/archive-all-partial-failure.test.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Archive All sends every PATCH with { notify: false } and relies on one batch notification
+// afterwards. Promise.all rejects on the first failure, so without a catch that notification
+// never runs: whatever did archive stays listed here and in every other tab until some
+// unrelated history change.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register("./sidebar-items-resolver.mjs", import.meta.url);
+
+const { recorder, resetRecorder } = await import(
+ "./helpers/store-stubs/sidebar-items-deps.ts"
+);
+const { archiveAllChatItems } = await import(
+ "../src/features/chat/hooks/use-chat-sidebar-items.ts"
+);
+
+const threads = [{ id: "a" }, { id: "b" }, { id: "c" }];
+
+test("a partially failed Archive All still announces what did archive", async () => {
+ resetRecorder(threads, ["b"]);
+
+ await assert.rejects(() => archiveAllChatItems(), /PATCH failed for b/);
+
+ assert.deepEqual(
+ recorder.patched.sort(),
+ ["a", "c"],
+ "the other two threads should still have been archived",
+ );
+ assert.equal(
+ recorder.notifications,
+ 1,
+ "the batch must announce itself even though the batch threw",
+ );
+});
+
+test("a partially failed Archive All announces only after every write settles", async () => {
+ // "b" rejects straight away while "c" is still writing, which is what Promise.all cannot wait for.
+ resetRecorder(threads, ["b"], ["c"]);
+
+ await assert.rejects(() => archiveAllChatItems(), /PATCH failed for b/);
+
+ assert.deepEqual(recorder.patched.sort(), ["a", "c"]);
+ assert.deepEqual(
+ recorder.events,
+ ["patch:a", "fail:b", "patch:c", "notify"],
+ "a silent write landing after the notification is never published to this or any other tab",
+ );
+});
+
+test("a fully successful Archive All announces exactly once", async () => {
+ resetRecorder(threads);
+
+ const archived = await archiveAllChatItems();
+
+ assert.equal(archived, 3);
+ assert.deepEqual(recorder.patched.sort(), ["a", "b", "c"]);
+ assert.equal(
+ recorder.notifications,
+ 1,
+ "the per-thread updates stay silent, so exactly one batch notification",
+ );
+});
+
+test("Archive All with nothing to archive does not notify", async () => {
+ resetRecorder([{ id: "a", archived: true }]);
+
+ assert.equal(await archiveAllChatItems(), 0);
+ assert.equal(recorder.notifications, 0);
+ assert.deepEqual(recorder.patched, []);
+});
diff --git a/studio/frontend/tests/chat-history-revision.test.ts b/studio/frontend/tests/chat-history-revision.test.ts
new file mode 100644
index 00000000000..ced35d1941f
--- /dev/null
+++ b/studio/frontend/tests/chat-history-revision.test.ts
@@ -0,0 +1,149 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The two channels: a structural change goes at once, the per-chunk streaming path waits for
+// its quiet window. Sharing one timer leaves a delete unannounced for a whole generation.
+
+import assert from "node:assert/strict";
+import test, { mock } from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const { store } = installLocalStorageFake();
+
+const {
+ CHAT_HISTORY_REVISION_KEY,
+ CROSS_TAB_REVISION_DEBOUNCE_MS,
+ flushChatHistoryRevision,
+ isCoalescedHistoryEvent,
+ publishChatHistoryRevision,
+} = await import("../src/features/chat/utils/chat-history-revision.ts");
+
+const revision = () => store.get(CHAT_HISTORY_REVISION_KEY) ?? null;
+
+test("a structural change publishes without waiting", () => {
+ store.clear();
+ publishChatHistoryRevision(false);
+ assert.notEqual(
+ revision(),
+ null,
+ "another tab must not hold a deleted chat as a live row",
+ );
+});
+
+test("the streaming path waits for its quiet window", () => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ store.clear();
+ publishChatHistoryRevision(true);
+ mock.timers.tick(CROSS_TAB_REVISION_DEBOUNCE_MS - 1);
+ assert.equal(
+ revision(),
+ null,
+ "no write while the chunks are still arriving",
+ );
+
+ mock.timers.tick(1);
+ assert.notEqual(revision(), null, "the quiet window publishes once");
+ } finally {
+ mock.timers.reset();
+ }
+});
+
+test("a stream collapses into one write rather than one per window", () => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ store.clear();
+ // Two seconds of chunks at 50ms, which under a throttle would have published four times.
+ for (let i = 0; i < 40; i += 1) {
+ publishChatHistoryRevision(true);
+ mock.timers.tick(50);
+ }
+ assert.equal(
+ revision(),
+ null,
+ "a continuous stream publishes nothing mid-flight",
+ );
+
+ mock.timers.tick(CROSS_TAB_REVISION_DEBOUNCE_MS);
+ assert.notEqual(revision(), null);
+ } finally {
+ mock.timers.reset();
+ }
+});
+
+test("a structural change during a stream does not wait for it", () => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ store.clear();
+ publishChatHistoryRevision(true);
+ mock.timers.tick(100);
+ // Under a shared timer the chunks that follow would push this back to the end.
+ publishChatHistoryRevision(false);
+ const published = revision();
+ assert.notEqual(published, null, "the delete publishes on its own");
+
+ for (let i = 0; i < 10; i += 1) {
+ publishChatHistoryRevision(true);
+ mock.timers.tick(50);
+ }
+ assert.equal(
+ revision(),
+ published,
+ "and the stream that follows does not publish again mid-flight",
+ );
+ } finally {
+ mock.timers.reset();
+ }
+});
+
+test("a pending write is published before the tab goes away", () => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ store.clear();
+ publishChatHistoryRevision(true);
+ assert.equal(revision(), null);
+
+ // What the pagehide handler calls: otherwise the write leaves with the page.
+ flushChatHistoryRevision();
+ assert.notEqual(revision(), null);
+
+ const published = revision();
+ mock.timers.tick(CROSS_TAB_REVISION_DEBOUNCE_MS);
+ assert.equal(
+ revision(),
+ published,
+ "and the flushed timer does not fire again",
+ );
+ } finally {
+ mock.timers.reset();
+ }
+});
+
+test("flushing with nothing pending writes nothing", () => {
+ store.clear();
+ flushChatHistoryRevision();
+ assert.equal(revision(), null);
+});
+
+// misreading a chunk save as structural starves a retiring listener for a whole generation
+test("a coalesced streaming update is distinguishable from a structural change", () => {
+ assert.equal(
+ isCoalescedHistoryEvent(
+ new CustomEvent("x", { detail: { coalesce: true } }),
+ ),
+ true,
+ );
+ assert.equal(
+ isCoalescedHistoryEvent(
+ new CustomEvent("x", { detail: { coalesce: false } }),
+ ),
+ false,
+ );
+});
+
+test("an undetailed history event counts as structural", () => {
+ // what the cross-tab listener re-raises, and what any caller that skips the detail sends
+ assert.equal(isCoalescedHistoryEvent(new Event("x")), false);
+ assert.equal(isCoalescedHistoryEvent(new CustomEvent("x")), false);
+});
diff --git a/studio/frontend/tests/chat-search-compact-list.test.ts b/studio/frontend/tests/chat-search-compact-list.test.ts
new file mode 100644
index 00000000000..ab0db04c983
--- /dev/null
+++ b/studio/frontend/tests/chat-search-compact-list.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The dialog sizes its list before its opening paint, so the answer must be synchronous. On
+// the first open of a page load the in-memory cache is empty whatever the history holds, so
+// the persisted hint is what tells an empty history from an unread one.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const { isCompactChatSearchList } = await import(
+ "../src/features/chat/utils/chat-search-list-height.ts"
+);
+const {
+ chatSearchHadRows,
+ forgetChatSearchHasRows,
+ rememberChatSearchHasRows,
+} = await import("../src/features/chat/utils/chat-search-history-hint.ts");
+
+test("a history known to have no rows opens compact", () => {
+ assert.equal(isCompactChatSearchList(true, false), true);
+});
+
+test("a history known to have rows opens at the fixed height", () => {
+ assert.equal(isCompactChatSearchList(true, true), false);
+});
+
+// The point of the fixed height: once the list has rows, narrowing it must not resize.
+test("a populated open keeps the fixed height while a query narrows it", () => {
+ assert.equal(isCompactChatSearchList(false, true), false);
+ assert.equal(isCompactChatSearchList(false, false), false);
+});
+
+// Backstop for a browser that has never built the index: the compact height is given up when
+// the first build lands and held for the rest of that open.
+test("rows arriving mid-open take the fixed height for the rest of that open", () => {
+ const afterBuild = isCompactChatSearchList(true, true);
+ assert.equal(afterBuild, false);
+ assert.equal(isCompactChatSearchList(afterBuild, false), false);
+});
+
+test("a completed build with rows is remembered, so the next page load opens fixed", () => {
+ store.clear();
+ // Nothing recorded yet reads as unknown, which is not the same as a history known to
+ // be empty: only the latter may be sized compact.
+ assert.equal(chatSearchHadRows(), null);
+ rememberChatSearchHasRows(true);
+ assert.equal(chatSearchHadRows(), true);
+ // The regression: with 150 stored chats and a cache that has not been built yet, the
+ // opening render must NOT pick compact and then grow to 420px when the rows land.
+ assert.equal(isCompactChatSearchList(true, chatSearchHadRows()), false);
+});
+
+test("a completed build with no rows keeps the first open compact", () => {
+ store.clear();
+ rememberChatSearchHasRows(true);
+ rememberChatSearchHasRows(false);
+ assert.equal(chatSearchHadRows(), false);
+ assert.equal(isCompactChatSearchList(true, chatSearchHadRows()), true);
+});
+
+test("an empty answer stops being trusted once it is old", () => {
+ store.clear();
+ rememberChatSearchHasRows(false);
+ assert.equal(chatSearchHadRows(), false);
+
+ // Chats made on another device or through the API never reach this tab, so this answer
+ // cannot stand indefinitely: past its window it goes back to unknown rather than sizing a
+ // populated dialog compact and growing it mid-open.
+ const raw = store.get("unsloth_chat_search_has_rows") ?? "";
+ const stale = Date.now() - (12 * 60 * 60 * 1000 + 1000);
+ store.set("unsloth_chat_search_has_rows", `0.${stale}`);
+ assert.notEqual(raw, "");
+ assert.equal(chatSearchHadRows(), null);
+ assert.equal(isCompactChatSearchList(true, chatSearchHadRows()), false);
+
+ // A rows answer has no such risk: sizing an emptied history at the fixed height costs
+ // nothing, so it is not aged out.
+ rememberChatSearchHasRows(true);
+ assert.equal(chatSearchHadRows(), true);
+});
+
+test("an empty answer written before the stamp existed reads as unknown", () => {
+ store.clear();
+ // What an upgrade finds in storage.
+ store.set("unsloth_chat_search_has_rows", "0");
+ assert.equal(chatSearchHadRows(), null);
+ store.set("unsloth_chat_search_has_rows", "0.not-a-time");
+ assert.equal(chatSearchHadRows(), null);
+ // A clock moved backwards leaves an answer that cannot be aged, so it says as little.
+ store.set("unsloth_chat_search_has_rows", `0.${Date.now() + 60_000}`);
+ assert.equal(chatSearchHadRows(), null);
+});
+
+test("a session change drops the hint, so the next account never inherits it", () => {
+ store.clear();
+ rememberChatSearchHasRows(true);
+ forgetChatSearchHasRows();
+ assert.equal(chatSearchHadRows(), null);
+ // Unknown, so the next account reserves the fixed height rather than opening compact
+ // on the strength of the previous account's history.
+ assert.equal(isCompactChatSearchList(true, chatSearchHadRows()), false);
+});
diff --git a/studio/frontend/tests/chat-search-index-hint.test.ts b/studio/frontend/tests/chat-search-index-hint.test.ts
new file mode 100644
index 00000000000..e85cfb895f4
--- /dev/null
+++ b/studio/frontend/tests/chat-search-index-hint.test.ts
@@ -0,0 +1,469 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The wiring, as opposed to the leaf helpers: chatSearchIndexHasRows has to answer for a
+// history not yet indexed, which is the first open of every page load.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+register("./chat-search-index-resolver.mjs", import.meta.url);
+const { store } = installLocalStorageFake();
+
+// The shared fake's addEventListener is a no-op, so the module-level listeners would register
+// into nothing. Swapped before the import below registers them. dispatchEvent routes by type,
+// since the storage listener re-raises the history event through it.
+type Listener = (event: {
+ key?: string | null;
+ newValue?: string | null;
+ type?: string;
+}) => void;
+const listeners = new Map<string, Set<Listener>>();
+Object.assign(globalThis.window as object, {
+ addEventListener: (type: string, fn: Listener) => {
+ const forType = listeners.get(type) ?? new Set<Listener>();
+ forType.add(fn);
+ listeners.set(type, forType);
+ },
+ removeEventListener: (type: string, fn: Listener) => {
+ listeners.get(type)?.delete(fn);
+ },
+ dispatchEvent: (event: { type: string }) => {
+ for (const fn of listeners.get(event.type) ?? []) fn(event);
+ return true;
+ },
+});
+const fire = (
+ type: string,
+ event: { key?: string | null; newValue?: string | null } = {},
+) => {
+ for (const fn of listeners.get(type) ?? []) fn({ type, ...event });
+};
+const fireStorage = (key: string | null, newValue: string | null = "value") =>
+ fire("storage", { key, newValue });
+
+const {
+ buildChatSearchIndex,
+ chatSearchIndexHasRows,
+ publishChatSearchBuild,
+ shouldPostponeSearchRebuild,
+ writeCachedIndex,
+} = await import("../src/features/chat/hooks/use-chat-search-index.ts");
+const { CHAT_HISTORY_REVISION_KEY, CHAT_HISTORY_UPDATED_EVENT } = await import(
+ "./helpers/store-stubs/chat-search-history.ts"
+);
+const { configureChatSearchHistoryStub } = await import(
+ "./helpers/store-stubs/chat-search-history.ts"
+);
+const { rememberChatSearchHasRows } = await import(
+ "../src/features/chat/utils/chat-search-history-hint.ts"
+);
+const {
+ AUTH_SESSION_CLEARED_EVENT,
+ AUTH_SESSION_MARK_KEY,
+ AUTH_TOKEN_KEY,
+ setAuthSessionEpochForTest,
+} = await import("./helpers/store-stubs/chat-search-auth.ts");
+
+const row = {
+ type: "single" as const,
+ id: "t1",
+ title: "Acme roadmap",
+ userSearchText: "acme roadmap",
+ searchText: "acme roadmap",
+ createdAt: 1,
+};
+
+test("an unbuilt index falls back to the last completed build's hint", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex(null);
+ // Nothing ever built, so the history is unknown rather than known-empty.
+ assert.equal(chatSearchIndexHasRows(), null);
+
+ // A completed build with rows, then the page reloads: the module cache is gone.
+ writeCachedIndex([row]);
+ assert.equal(chatSearchIndexHasRows(), true);
+ writeCachedIndex(null);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ true,
+ "150 stored chats must not read as an empty history on the next page load",
+ );
+});
+
+test("an invalidated cache keeps a rows answer and drops an empty one", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+
+ // Invalidation says stale, not empty.
+ writeCachedIndex(null);
+ assert.equal(chatSearchIndexHasRows(), true);
+
+ // A completed build that found nothing is the one thing that means "no chats".
+ writeCachedIndex([]);
+ assert.equal(chatSearchIndexHasRows(), false);
+ // ...but the next change may be that history's first chat, so it goes back to unknown.
+ writeCachedIndex(null);
+ assert.equal(chatSearchIndexHasRows(), null);
+});
+
+test("a session change inside one page load drops the previous account's hint", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+ assert.equal(chatSearchIndexHasRows(), true);
+
+ setAuthSessionEpochForTest(1);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ null,
+ "the next account must not be sized by the previous one's history",
+ );
+});
+
+test("an unbuilt index with no hint reads as unknown, not as empty", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex(null);
+ // A profile that has never built the index, and one upgrading from before the hint
+ // existed, both land here. Reading this as "empty" is what sized a populated dialog
+ // compact and then grew it mid-open.
+ assert.equal(chatSearchIndexHasRows(), null);
+});
+
+test("a completed empty build is remembered as empty, not as unknown", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([]);
+ writeCachedIndex(null);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ null,
+ "a history that just changed is unknown again, not still empty",
+ );
+ writeCachedIndex([]);
+ assert.equal(chatSearchIndexHasRows(), false);
+});
+
+test("another tab's history change drops the cached rows", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+ // Make the hint disagree with the cache so the two are distinguishable: cached rows answer
+ // first, and only once dropped does the hint show through.
+ rememberChatSearchHasRows(false);
+ assert.equal(chatSearchIndexHasRows(), true);
+
+ fireStorage(CHAT_HISTORY_REVISION_KEY);
+ // Rows gone, so the next open rebuilds instead of offering a deleted chat, and the stale
+ // hint goes with them. Without the listener this still reads true.
+ assert.equal(chatSearchIndexHasRows(), null);
+});
+
+test("another tab's history change reaches an open dialog's rebuild", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+
+ // What an open dialog subscribes to: dropping the cache alone leaves it on pre-change rows
+ // with nothing scheduled.
+ let rebuilds = 0;
+ const onHistory = () => {
+ rebuilds += 1;
+ };
+ (globalThis.window as Window).addEventListener(
+ CHAT_HISTORY_UPDATED_EVENT,
+ onHistory,
+ );
+ try {
+ fireStorage(CHAT_HISTORY_REVISION_KEY);
+ assert.equal(
+ rebuilds,
+ 1,
+ "the cross-tab change has to re-raise as a local one",
+ );
+ } finally {
+ (globalThis.window as Window).removeEventListener(
+ CHAT_HISTORY_UPDATED_EVENT,
+ onHistory,
+ );
+ }
+});
+
+test("another tab's account switch drops this tab's rows and hint", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+ assert.equal(chatSearchIndexHasRows(), true);
+
+ // The epoch and its events are both this document's, so a sign-in elsewhere arrives as a
+ // storage write alone and the epoch still matches: hence the cache would still answer.
+ let rebuilds = 0;
+ const onHistory = () => {
+ rebuilds += 1;
+ };
+ // Mirrors the module-private event name. An open dialog listens for it to retire a build
+ // in flight for the previous account, which the epoch check cannot do.
+ let sessionChanges = 0;
+ const onSession = () => {
+ sessionChanges += 1;
+ };
+ const win = globalThis.window as Window;
+ win.addEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistory);
+ win.addEventListener("unsloth-chat-search-session-changed", onSession);
+ try {
+ fireStorage(AUTH_SESSION_MARK_KEY);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ null,
+ "the previous account's titles must not survive the switch",
+ );
+ assert.equal(rebuilds, 1, "everything showing that account has to refresh");
+ assert.equal(
+ sessionChanges,
+ 1,
+ "a build in flight for the previous account has to be retired",
+ );
+ } finally {
+ win.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistory);
+ win.removeEventListener("unsloth-chat-search-session-changed", onSession);
+ }
+});
+
+test("a token refresh in another tab costs nothing", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+
+ // refreshSession rewrites the token hourly with the session unchanged. Reading that as a
+ // switch would throw away a warm cache for nothing.
+ let sessionChanges = 0;
+ const onSession = () => {
+ sessionChanges += 1;
+ };
+ const win = globalThis.window as Window;
+ win.addEventListener("unsloth-chat-search-session-changed", onSession);
+ try {
+ fireStorage(AUTH_TOKEN_KEY);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ true,
+ "the cache survives a rotation",
+ );
+ assert.equal(sessionChanges, 0);
+ } finally {
+ win.removeEventListener("unsloth-chat-search-session-changed", onSession);
+ }
+});
+
+test("a legacy session logout in another tab drops cached rows", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+
+ let rebuilds = 0;
+ const onHistory = () => {
+ rebuilds += 1;
+ };
+ let sessionChanges = 0;
+ const onSession = () => {
+ sessionChanges += 1;
+ };
+ const win = globalThis.window as Window;
+ win.addEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistory);
+ win.addEventListener("unsloth-chat-search-session-changed", onSession);
+ try {
+ fireStorage(AUTH_TOKEN_KEY, null);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ null,
+ "a session created before the marker existed still clears on logout",
+ );
+ assert.equal(rebuilds, 1);
+ assert.equal(sessionChanges, 1);
+ } finally {
+ win.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistory);
+ win.removeEventListener("unsloth-chat-search-session-changed", onSession);
+ }
+});
+
+test("a history change in another tab is not treated as a session change", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+
+ // A delete elsewhere must not tear rows out from under an open dialog: it schedules a
+ // rebuild and lets the current rows stand.
+ let sessionChanges = 0;
+ const onSession = () => {
+ sessionChanges += 1;
+ };
+ const win = globalThis.window as Window;
+ win.addEventListener("unsloth-chat-search-session-changed", onSession);
+ try {
+ fireStorage(CHAT_HISTORY_REVISION_KEY);
+ assert.equal(sessionChanges, 0);
+ } finally {
+ win.removeEventListener("unsloth-chat-search-session-changed", onSession);
+ }
+});
+
+test("a logout takes the persisted hint with it", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+ writeCachedIndex(null);
+ assert.equal(chatSearchIndexHasRows(), true);
+
+ // The hint outlives the page, so a reload on the login screen would hand this account's
+ // history to whoever signs in next.
+ fire(AUTH_SESSION_CLEARED_EVENT);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ null,
+ "the next account's first open must not be sized by the previous one",
+ );
+});
+
+test("an unrelated storage key leaves the cache alone", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+ fireStorage("unsloth_theme");
+ assert.equal(chatSearchIndexHasRows(), true);
+});
+
+test("an index too large to hold is rebuilt rather than cached", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ const heavy = Array.from({ length: 40 }, (_, i) => ({
+ ...row,
+ id: `t${i}`,
+ // A tool-heavy thread: 200k characters of conversation text apiece.
+ searchText: "x".repeat(200_000),
+ }));
+ writeCachedIndex(heavy);
+ // The hint still answers, so the dialog sizes correctly without holding 8M characters.
+ assert.equal(chatSearchIndexHasRows(), true);
+
+ rememberChatSearchHasRows(false);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ false,
+ "the rows were not retained, so the hint is what answers",
+ );
+});
+
+test("an index within the budget is still cached", () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([row]);
+ rememberChatSearchHasRows(false);
+ assert.equal(chatSearchIndexHasRows(), true, "the cached rows still answer");
+});
+
+test("stream chunks do not postpone an already scheduled structural rebuild", () => {
+ const structural = new Event(CHAT_HISTORY_UPDATED_EVENT);
+ const stream = new CustomEvent(CHAT_HISTORY_UPDATED_EVENT, {
+ detail: { coalesce: true },
+ });
+ assert.equal(shouldPostponeSearchRebuild(false, stream), true);
+ assert.equal(shouldPostponeSearchRebuild(true, structural), true);
+ assert.equal(
+ shouldPostponeSearchRebuild(true, stream),
+ false,
+ "a stream chunk must keep the structural rebuild's original deadline",
+ );
+ assert.equal(
+ shouldPostponeSearchRebuild(false, stream),
+ true,
+ "once that deadline fires, later chunks return to quiet-window coalescing",
+ );
+});
+
+test("failed message reads are not persisted as a completed empty history", async () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([]);
+ assert.equal(chatSearchIndexHasRows(), false);
+ configureChatSearchHistoryStub({
+ threads: [
+ {
+ id: "unreadable-thread",
+ title: "History still exists",
+ modelType: "text",
+ archived: false,
+ createdAt: 1,
+ },
+ ],
+ batchFails: true,
+ messageReadsFail: true,
+ });
+
+ const build = await buildChatSearchIndex();
+ assert.deepEqual(build, { items: [], complete: false });
+ publishChatSearchBuild(build);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ null,
+ "a transient total read failure is unknown, not a known-empty history",
+ );
+ configureChatSearchHistoryStub({});
+});
+
+test("partial builds replace a stale empty hint with a rows answer", async () => {
+ store.clear();
+ setAuthSessionEpochForTest(0);
+ writeCachedIndex([]);
+ assert.equal(chatSearchIndexHasRows(), false);
+ configureChatSearchHistoryStub({
+ threads: [
+ {
+ id: "readable-thread",
+ title: "Visible history",
+ modelType: "text",
+ archived: false,
+ createdAt: 2,
+ },
+ {
+ id: "unreadable-thread",
+ title: "Unreadable history",
+ modelType: "text",
+ archived: false,
+ createdAt: 1,
+ },
+ ],
+ messagesByThread: new Map([
+ [
+ "readable-thread",
+ [
+ {
+ id: "readable-message",
+ threadId: "readable-thread",
+ role: "user",
+ content: [{ type: "text", text: "Recovered row" }],
+ createdAt: 2,
+ },
+ ],
+ ],
+ ]),
+ batchFails: true,
+ messageReadFailures: new Set(["unreadable-thread"]),
+ });
+
+ const build = await buildChatSearchIndex();
+ assert.equal(build.complete, false);
+ assert.equal(build.items.length, 1);
+ publishChatSearchBuild(build);
+ assert.equal(
+ chatSearchIndexHasRows(),
+ true,
+ "visible partial rows disprove the older completed-empty hint",
+ );
+ configureChatSearchHistoryStub({});
+});
diff --git a/studio/frontend/tests/chat-search-index-resolver.mjs b/studio/frontend/tests/chat-search-index-resolver.mjs
new file mode 100644
index 00000000000..1ce38d6efb9
--- /dev/null
+++ b/studio/frontend/tests/chat-search-index-resolver.mjs
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// use-chat-search-index pulls Dexie and the chat API transitively, neither of which loads in
+// bare node. Only those are stubbed, so the real cache and hint bookkeeping runs.
+import { resolve as resolveBundler } from "./bundler-resolver.mjs";
+
+const STUBS = new Map([
+ ["@/features/auth", "./helpers/store-stubs/chat-search-auth.ts"],
+ ["../api/chat-api", "./helpers/store-stubs/chat-search-history.ts"],
+ ["../utils/chat-history-storage", "./helpers/store-stubs/chat-search-history.ts"],
+]);
+
+export function resolve(specifier, context, next) {
+ const stub = STUBS.get(specifier);
+ if (stub) return next(new URL(stub, import.meta.url).href, context);
+ return resolveBundler(specifier, context, next);
+}
diff --git a/studio/frontend/tests/helpers/store-stubs/chat-search-auth.ts b/studio/frontend/tests/helpers/store-stubs/chat-search-auth.ts
new file mode 100644
index 00000000000..113915eaaf7
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/chat-search-auth.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Mirrors features/auth/session-events, which the real module re-exports.
+export const AUTH_SESSION_CLEARED_EVENT = "unsloth:auth-session-cleared";
+export const AUTH_SESSION_MARK_KEY = "unsloth_auth_session_mark";
+// Not imported by the module under test: a test asserts a refresh of this key is ignored.
+export const AUTH_TOKEN_KEY = "unsloth_auth_token";
+
+/** The auth session epoch, driveable so a test can simulate a sign-out inside one page load. */
+let epoch = 0;
+
+export function getAuthSessionEpoch(): number {
+ return epoch;
+}
+
+export function setAuthSessionEpochForTest(next: number): void {
+ epoch = next;
+}
diff --git a/studio/frontend/tests/helpers/store-stubs/chat-search-history.ts b/studio/frontend/tests/helpers/store-stubs/chat-search-history.ts
new file mode 100644
index 00000000000..72194eab39a
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/chat-search-history.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+let threads: unknown[] = [];
+let messagesByThread = new Map<string, unknown[]>();
+let batchFails = false;
+let messageReadsFail = false;
+let messageReadFailures = new Set<string>();
+
+export function listStoredChatThreads(): Promise<unknown[]> {
+ return Promise.resolve(threads);
+}
+
+export function listStoredChatMessages(threadId: string): Promise<unknown[]> {
+ if (messageReadsFail || messageReadFailures.has(threadId)) {
+ return Promise.reject(new Error("message read failed"));
+ }
+ return Promise.resolve(messagesByThread.get(threadId) ?? []);
+}
+
+export function batchListChatMessages(): Promise<Map<string, unknown[]>> {
+ if (batchFails) {
+ return Promise.reject(new Error("batch read failed"));
+ }
+ return Promise.resolve(new Map(messagesByThread));
+}
+
+export function configureChatSearchHistoryStub(options: {
+ threads?: unknown[];
+ messagesByThread?: Map<string, unknown[]>;
+ batchFails?: boolean;
+ messageReadsFail?: boolean;
+ messageReadFailures?: Set<string>;
+}): void {
+ threads = options.threads ?? [];
+ messagesByThread = options.messagesByThread ?? new Map();
+ batchFails = options.batchFails ?? false;
+ messageReadsFail = options.messageReadsFail ?? false;
+ messageReadFailures = options.messageReadFailures ?? new Set();
+}
+
+export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
+// Must match the real chat-api constant: the cross-tab listener keys off it.
+export const CHAT_HISTORY_REVISION_KEY = "unsloth_chat_history_revision";
diff --git a/studio/frontend/tests/helpers/store-stubs/sidebar-items-deps.ts b/studio/frontend/tests/helpers/store-stubs/sidebar-items-deps.ts
new file mode 100644
index 00000000000..630f2840510
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/sidebar-items-deps.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The transitive weight of use-chat-sidebar-items: the chat API, Dexie-backed storage and
+// the zustand stores. Only the calls archiveAllChatItems makes are modelled; everything
+// else is an inert stub so the real batching and notification bookkeeping runs.
+
+export interface StubThread {
+ id: string;
+ archived?: boolean;
+ pairId?: string;
+ title?: string;
+ updatedAt?: number;
+}
+
+interface Recorder {
+ notifications: number;
+ patched: string[];
+ /** Ordered "patch:<id>" / "fail:<id>" / "notify" log, for asserting when the batch announces. */
+ events: string[];
+ threads: StubThread[];
+ failOn: Set<string>;
+ slowOn: Set<string>;
+}
+
+export const recorder: Recorder = {
+ notifications: 0,
+ patched: [],
+ events: [],
+ threads: [],
+ failOn: new Set(),
+ slowOn: new Set(),
+};
+
+export function resetRecorder(
+ threads: StubThread[],
+ failOn: string[] = [],
+ slowOn: string[] = [],
+) {
+ recorder.notifications = 0;
+ recorder.patched = [];
+ recorder.events = [];
+ recorder.threads = threads;
+ recorder.failOn = new Set(failOn);
+ recorder.slowOn = new Set(slowOn);
+}
+
+export const CHAT_HISTORY_UPDATED_EVENT = "unsloth:chat-history-updated";
+
+export function notifyChatHistoryUpdated(): void {
+ recorder.notifications += 1;
+ recorder.events.push("notify");
+}
+
+export async function listStoredChatThreads(): Promise<StubThread[]> {
+ return recorder.threads;
+}
+
+export async function updateStoredChatThread(
+ threadId: string,
+ _patch: unknown,
+ options: { notify?: boolean } = {},
+): Promise<StubThread> {
+ // a slow thread settles a macrotask later, so a rejecting sibling resolves well ahead of it
+ if (recorder.slowOn.has(threadId)) {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ if (recorder.failOn.has(threadId)) {
+ recorder.events.push(`fail:${threadId}`);
+ throw new Error(`PATCH failed for ${threadId}`);
+ }
+ recorder.patched.push(threadId);
+ recorder.events.push(`patch:${threadId}`);
+ if (options.notify !== false) notifyChatHistoryUpdated();
+ return { id: threadId, archived: true };
+}
+
+export async function listStoredChatThreadsWithMessages(): Promise<StubThread[]> {
+ return [];
+}
+export async function deleteStoredChatThreads(): Promise<void> {}
+export function isExpectedBackgroundChatStorageError(): boolean {
+ return false;
+}
+export function clearComposerDraft(): void {}
+export async function offerToDeleteKeptSandboxes(): Promise<void> {}
+export async function stopChatThread(): Promise<void> {}
+export function markChatThreadsDeleted(): void {}
+export function removeChatThreadTombstones(): void {}
+export function requestPromptQueueStop(): void {}
+export async function repairLegacyChatTitles(): Promise<void> {}
+
+const inertStore = {
+ getState: () => ({
+ setActiveThreadId: () => {},
+ cancelIfRunning: () => {},
+ }),
+};
+export const useChatRuntimeStore = inertStore;
+export const useChatArtifactsStore = inertStore;
diff --git a/studio/frontend/tests/sidebar-items-resolver.mjs b/studio/frontend/tests/sidebar-items-resolver.mjs
new file mode 100644
index 00000000000..3768a3887d5
--- /dev/null
+++ b/studio/frontend/tests/sidebar-items-resolver.mjs
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// use-chat-sidebar-items pulls the chat API, Dexie-backed storage and the zustand stores,
+// none of which load in bare node. One stub module answers for all of them so the real
+// archiveAllChatItems body runs.
+import { resolve as resolveBundler } from "./bundler-resolver.mjs";
+
+const DEPS = "./helpers/store-stubs/sidebar-items-deps.ts";
+const STUBS = new Map([
+ ["../api/chat-api", DEPS],
+ ["../artifacts/store", DEPS],
+ ["../stores/chat-runtime-store", DEPS],
+ ["../utils/chat-history-storage", DEPS],
+ ["../utils/composer-draft", DEPS],
+ ["../utils/offer-kept-sandbox-files", DEPS],
+ ["../utils/stop-chat-thread", DEPS],
+ ["../utils/chat-thread-tombstones", DEPS],
+ ["../utils/prompt-queue-boundary", DEPS],
+ ["../utils/repair-legacy-chat-titles", DEPS],
+]);
+
+export function resolve(specifier, context, next) {
+ const stub = STUBS.get(specifier);
+ if (stub) return next(new URL(stub, import.meta.url).href, context);
+ return resolveBundler(specifier, context, next);
+}