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.

Studio: Projects recency by chat activity, less polling behind projects and sources (#14586)

Michael Han265aa0d851d9
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index ec28e290750..97a284b2f09 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -1305,11 +1305,16 @@ def delete_attachment(
def list_projects(
include_archived: bool = Query(False), current_subject: str = Depends(get_current_subject)
):
+ # Backfill only projects without a recorded root; the rest are ensured where their files are used.
return ChatProjectListResponse(
projects = [
ChatProject(
**{
- **(ensure_chat_project_workspace(project["id"]) or project),
+ **(
+ project
+ if project.get("rootPath")
+ else (ensure_chat_project_workspace(project["id"]) or project)
+ ),
"lastActivityAt": project["lastActivityAt"],
}
)
diff --git a/studio/backend/tests/test_project_list_workspace.py b/studio/backend/tests/test_project_list_workspace.py
new file mode 100644
index 00000000000..6bc01f0fa87
--- /dev/null
+++ b/studio/backend/tests/test_project_list_workspace.py
@@ -0,0 +1,56 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""GET /api/chat/projects backfills a missing workspace, and only that.
+
+The sidebar, the Projects page and every gallery menu list projects, so ensuring each row's
+workspace on every list cost several connections and mkdirs per project per call.
+"""
+
+from routes import chat_history
+
+
+def _row(id, root_path):
+ return {
+ "id": id,
+ "name": id,
+ "instructions": "",
+ "rootPath": root_path,
+ "sandboxPath": f"{root_path}/sandbox" if root_path else None,
+ "workingFolder": None,
+ "archived": False,
+ "createdAt": 1,
+ "updatedAt": 2,
+ "lastActivityAt": 5,
+ }
+
+
+def test_only_a_project_without_a_root_is_ensured(monkeypatch):
+ rows = [_row("rooted", "/tmp/rooted"), _row("legacy", None)]
+ monkeypatch.setattr(chat_history, "list_chat_projects", lambda include_archived = False: rows)
+ ensured = []
+
+ def ensure(project_id):
+ ensured.append(project_id)
+ return {**_row(project_id, "/tmp/backfilled"), "lastActivityAt": None}
+
+ monkeypatch.setattr(chat_history, "ensure_chat_project_workspace", ensure)
+
+ projects = chat_history.list_projects(include_archived = False, current_subject = "owner").projects
+
+ assert ensured == ["legacy"]
+ by_id = {project.id: project for project in projects}
+ assert by_id["rooted"].rootPath == "/tmp/rooted"
+ assert by_id["legacy"].rootPath == "/tmp/backfilled"
+ # Activity comes from the listing, which the ensured record does not carry.
+ assert by_id["legacy"].lastActivityAt == 5
+
+
+def test_a_row_deleted_mid_backfill_still_lists(monkeypatch):
+ rows = [_row("gone", None)]
+ monkeypatch.setattr(chat_history, "list_chat_projects", lambda include_archived = False: rows)
+ monkeypatch.setattr(chat_history, "ensure_chat_project_workspace", lambda project_id: None)
+
+ projects = chat_history.list_projects(include_archived = False, current_subject = "owner").projects
+
+ assert [project.id for project in projects] == ["gone"]
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index e4d7f45b776..472abdc3ba7 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -356,8 +356,11 @@ export const BUDGET = {
// Chat fork affordances (the sidebar fork mark, the "Forked from" divider and the shared fork toasts) in the
// eager chat chunk: +1_460 B raw / +361 B transfer against 77e742c8e2 (6_879_345 -> 6_880_805 raw,
// 2_071_823 -> 2_072_184 transfer, 97 chunks). Raised by that growth.
- transferBytes: 2_072_373,
- rawBytes: 6_881_049,
+ // Projects recency and the polling cuts behind projects and sources (#14586) live in the eager chat chunk:
+ // +505 B raw / +309 B transfer (6,879,331 -> 6,879,836 B raw, 2,071,848 -> 2,072,157 B transfer against
+ // 2749eeedaa, one machine and build, Node 26, 97 chunks). Raised by that, on top of the fork affordances above.
+ transferBytes: 2_072_682,
+ rawBytes: 6_881_554,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 1c697c97fd0..21d36583bd7 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -178,7 +178,10 @@ import {
} from "@/features/chat/api/prompts-api";
import { PromptCountBadge } from "@/features/chat/prompt-storage/prompt-count-badge";
import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
-import { useChatProjects } from "@/features/chat/hooks/use-chat-projects";
+import {
+ sortProjectsByActivity,
+ useChatProjects,
+} from "@/features/chat/hooks/use-chat-projects";
import { NewProjectDialog } from "@/features/chat/components/new-project-dialog";
import { ResearchMessage } from "@/features/chat/components/research-message";
import {
@@ -6998,11 +7001,8 @@ const ComposerToolsMenu: FC<{
externalSelection?.modelId,
) !== true) ||
incognito;
- // Three most recently updated projects for the quick-access submenu.
const { projects } = useChatProjects();
- const recentProjects = [...projects]
- .sort((a, b) => b.updatedAt - a.updatedAt)
- .slice(0, 3);
+ const recentProjects = sortProjectsByActivity(projects).slice(0, 3);
const openProject = (projectId: string) => {
useChatRuntimeStore.getState().setActiveProjectId(projectId);
navigate({ to: "/chat", search: { project: projectId } });
diff --git a/studio/frontend/src/features/chat/components/project-switcher.tsx b/studio/frontend/src/features/chat/components/project-switcher.tsx
index d61bff91c39..c019152c69e 100644
--- a/studio/frontend/src/features/chat/components/project-switcher.tsx
+++ b/studio/frontend/src/features/chat/components/project-switcher.tsx
@@ -13,10 +13,11 @@ import { Tick02Icon } from "@/lib/tick-icon";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { type ReactElement, useMemo, useState } from "react";
+import { sortProjectsByActivity } from "../hooks/use-chat-projects";
import { useChatActive } from "../runtime-provider";
import type { ProjectRecord } from "../types";
-/** Rows before "View all projects". The list arrives newest first, so these are the recent ones. */
+/** Rows before "View all projects": the most recently used. */
const RECENT_PROJECT_LIMIT = 6;
export function ProjectSwitcher({
@@ -39,12 +40,12 @@ export function ProjectSwitcher({
}): ReactElement {
// A switcher, not the list: the rest are a click away under "View all projects".
const recentProjects = useMemo(() => {
- const recent = projects.slice(0, RECENT_PROJECT_LIMIT);
+ // The server lists by edit time, which a chat never moves: most recently used is what recent means.
+ const recent = sortProjectsByActivity(projects).slice(0, RECENT_PROJECT_LIMIT);
if (!currentProject || recent.some((p) => p.id === currentProject.id)) {
return recent;
}
- // A project's own updatedAt only moves when it is edited, so the open one is often not among
- // the newest. It keeps its place here: without it the switcher shows no tick at all.
+ // The open one keeps its place: without it the switcher shows no tick at all.
return [...recent.slice(0, RECENT_PROJECT_LIMIT - 1), currentProject];
}, [projects, currentProject]);
const showLoadingRow = isLoading && projects.length === 0;
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index ebcbfca0f0e..4615d655b93 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -388,6 +388,9 @@ const LORA_SUFFIX_RE = /_(\d{9,})$/;
const CLI_LOAD_POLL_IDLE_MS = 60_000;
const CLI_LOAD_POLL_MAX_MS = 600_000;
+const CLI_LOAD_POLL_FAST_MS = 5_000;
+const CLI_LOAD_POLL_FAST_INTERVAL_MS = 500;
+const CLI_LOAD_POLL_IDLE_INTERVAL_MS = 2_000;
async function waitForServerModel(signal?: AbortSignal): Promise<void> {
const started = Date.now();
@@ -429,7 +432,15 @@ async function waitForServerModel(signal?: AbortSignal): Promise<void> {
const elapsed = Date.now() - started;
if (!sawLoad && elapsed >= CLI_LOAD_POLL_IDLE_MS) return;
if (elapsed >= CLI_LOAD_POLL_MAX_MS) return;
- await new Promise((resolve) => setTimeout(resolve, 500));
+ // Runs for a minute per chat open with nothing loaded: fast first, then slow for an idle page.
+ await new Promise((resolve) =>
+ setTimeout(
+ resolve,
+ sawLoad || elapsed < CLI_LOAD_POLL_FAST_MS
+ ? CLI_LOAD_POLL_FAST_INTERVAL_MS
+ : CLI_LOAD_POLL_IDLE_INTERVAL_MS,
+ ),
+ );
}
}
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-projects.ts b/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
index 40a53653611..062cc5141f4 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
@@ -26,6 +26,9 @@ let projectsRefreshPending = false;
let lastProjectsUpdateEvent: Event | null = null;
const projectSubscribers = new Set<() => void>();
const ACTIVITY_REFRESH_DEBOUNCE_MS = 2000;
+// Mounts refetch only past this age: a gallery mounts a project menu per tile.
+const MOUNT_REVALIDATE_AFTER_MS = 5000;
+let projectsLoadedAt = 0;
let activityRefreshTimer: ReturnType<typeof setTimeout> | null = null;
function onChatActivity(): void {
@@ -46,6 +49,7 @@ function getProjectsSnapshot(): ProjectRecord[] {
}
function publishProjects(projects: ProjectRecord[]): void {
+ projectsLoadedAt = Date.now();
if (projectsLoaded && JSON.stringify(projects) === JSON.stringify(cachedProjects)) return;
cachedProjects = projects;
projectsLoaded = true;
@@ -136,7 +140,9 @@ export function useChatProjects(): {
// browser tab or API client.
// one function per consumer: a shared reference is one DOM listener the first unmount would remove
const onActivity = () => onChatActivity();
- void refresh(projectsLoaded);
+ void refresh(
+ projectsLoaded && Date.now() - projectsLoadedAt > MOUNT_REVALIDATE_AFTER_MS,
+ );
window.addEventListener(CHAT_PROJECTS_UPDATED_EVENT, onProjectsUpdated);
window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, onActivity);
return () => {
@@ -149,6 +155,16 @@ export function useChatProjects(): {
return { projects, isLoading, hasLoaded };
}
+/** Newest chat or own last edit: `updatedAt` alone moves only on a rename or instructions change. */
+export function projectActivityAt(project: ProjectRecord): number {
+ return Math.max(project.lastActivityAt ?? 0, project.updatedAt);
+}
+
+/** Most recently used first, the order the sidebar shows. */
+export function sortProjectsByActivity(projects: readonly ProjectRecord[]): ProjectRecord[] {
+ return [...projects].sort((a, b) => projectActivityAt(b) - projectActivityAt(a));
+}
+
export async function createChatProject(
name: string,
nativePathLease?: string,
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 908c779e326..532b27834d0 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -576,7 +576,9 @@ export {
createChatProject,
deleteChatProject,
moveChatItemToProject,
+ projectActivityAt,
renameChatProject,
+ sortProjectsByActivity,
updateChatProjectInstructions,
useChatProjects,
} from "./hooks/use-chat-projects";
diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsx
index c0fb8f8727e..e6385752120 100644
--- a/studio/frontend/src/features/chat/projects-page.tsx
+++ b/studio/frontend/src/features/chat/projects-page.tsx
@@ -49,6 +49,7 @@ import {
useChatNavigationStore,
useChatPreferencesStore,
useChatProjects,
+ projectActivityAt,
useChatRuntimeStore,
usePinnedChatsStore,
usePinnedProjectsStore,
@@ -97,6 +98,7 @@ import {
listStoredChatThreads,
} from "./utils/chat-history-storage";
import { CHAT_HISTORY_UPDATED_EVENT } from "./api/chat-api";
+import { isCoalescedHistoryEvent } from "./utils/chat-history-revision";
import { groupThreads, type SidebarItem } from "./hooks/use-chat-sidebar-items";
import { ProjectMenuItems } from "./components/project-menu-items";
import { SectionNameDialog } from "./components/section-name-dialog";
@@ -111,6 +113,8 @@ import { runChatImport } from "./utils/import-chats";
const PROJECTS_PAGE_STEP = 12;
// A streaming chat fires the history event per chunk; one reload per quiet window is enough.
const PROJECT_CHATS_REFRESH_DEBOUNCE_MS = 300;
+// Chunk saves are spaced wider than that on a slow CPU model, so they wait for a longer lull.
+const PROJECT_CHATS_STREAM_REFRESH_DEBOUNCE_MS = 2000;
// Visible count before the fit-to-height measurement runs.
const PROJECTS_INITIAL_FALLBACK = 8;
// Approx list row height in px, used to estimate how many rows fit the page.
@@ -265,7 +269,7 @@ export function ProjectsPage() {
}, [openProjectIds]);
useEffect(() => {
let timer: ReturnType<typeof setTimeout> | null = null;
- const refresh = () => {
+ const refresh = (event: Event) => {
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
@@ -280,7 +284,9 @@ export function ProjectsPage() {
return kept;
});
for (const id of open) loadProjectChats(id, true);
- }, PROJECT_CHATS_REFRESH_DEBOUNCE_MS);
+ }, isCoalescedHistoryEvent(event)
+ ? PROJECT_CHATS_STREAM_REFRESH_DEBOUNCE_MS
+ : PROJECT_CHATS_REFRESH_DEBOUNCE_MS);
};
window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, refresh);
return () => {
@@ -310,7 +316,7 @@ export function ProjectsPage() {
try {
const selected = await pickNativeChatImport();
if (!selected) return;
- setImportTargetId(projects[0]?.id ?? null);
+ setImportTargetId(null);
setImportFile(nativeImportSource(selected));
} catch (error) {
toast.error("Import failed.", {
@@ -332,8 +338,11 @@ export function ProjectsPage() {
const filtered = trimmed
? projects.filter((p) => p.name.toLowerCase().includes(trimmed))
: projects.slice();
+ // By last use, as the sidebar orders them: a project's updatedAt only moves on an edit.
filtered.sort((a, b) =>
- sortDir === "asc" ? a.updatedAt - b.updatedAt : b.updatedAt - a.updatedAt,
+ sortDir === "asc"
+ ? projectActivityAt(a) - projectActivityAt(b)
+ : projectActivityAt(b) - projectActivityAt(a),
);
return filtered;
}, [projects, query, sortDir]);
@@ -447,18 +456,12 @@ export function ProjectsPage() {
merged: boolean,
) {
try {
- let threads;
- if (scope === "projects") {
- threads = (
- await Promise.all(
- projects.map((p) =>
- listStoredChatThreads({ projectId: p.id, includeArchived: false }),
- ),
- )
- ).flat();
- } else {
- threads = await listStoredChatThreads({ includeArchived: false });
- }
+ const listed = await listStoredChatThreads({ includeArchived: false });
+ const projectIds = new Set(projects.map((p) => p.id));
+ const threads =
+ scope === "projects"
+ ? listed.filter((t) => t.projectId && projectIds.has(t.projectId))
+ : listed;
const ids = [...new Set(threads.map((t) => t.id))];
if (ids.length === 0) { toast.info("No conversations to export."); return; }
const ts = new Date().toISOString().slice(0, 10);
@@ -563,6 +566,10 @@ export function ProjectsPage() {
setDeleteFilesOnDelete(false);
try {
await deleteChatProject(target.id, { deleteFiles });
+ // As the sidebar's delete: its chats went with it, and the runtime must not reopen it.
+ notifyChatHistoryUpdated();
+ const runtime = useChatRuntimeStore.getState();
+ if (runtime.activeProjectId === target.id) runtime.setActiveProjectId(null);
} catch (err) {
toast.error("Failed to delete project", {
description: err instanceof Error ? err.message : undefined,
@@ -582,7 +589,7 @@ export function ProjectsPage() {
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
- setImportTargetId(projects[0]?.id ?? null);
+ setImportTargetId(null);
setImportFile(fileImportSource(file));
}
e.target.value = "";
@@ -603,6 +610,12 @@ export function ProjectsPage() {
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape" && query) {
+ e.preventDefault();
+ setQuery("");
+ }
+ }}
placeholder="Search projects"
className="h-9 w-full rounded-full border-none bg-muted pl-10 pr-4 shadow-none dark:bg-card"
aria-label="Search projects"
@@ -716,14 +729,24 @@ export function ProjectsPage() {
? "No projects yet."
: "No projects match your search."}
</p>
- {projects.length === 0 && (
- <Button
- variant="outline"
- className="mt-2 border-none bg-background shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-card dark:shadow-none"
- onClick={() => setCreating(true)}
- >
- <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />
- Create your first project
+ {projects.length === 0 ? (
+ <>
+ <p className="max-w-sm text-sm">
+ A project keeps related chats together, with shared instructions and sources
+ every chat in it can use.
+ </p>
+ <Button
+ variant="outline"
+ className="mt-2 border-none bg-background shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-card dark:shadow-none"
+ onClick={() => setCreating(true)}
+ >
+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />
+ Create your first project
+ </Button>
+ </>
+ ) : (
+ <Button variant="ghost" size="sm" onClick={() => setQuery("")}>
+ Clear search
</Button>
)}
</div>
@@ -821,7 +844,7 @@ export function ProjectsPage() {
/>
</span>
<span className="hidden w-40 shrink-0 text-sm text-muted-foreground sm:block">
- {formatUpdated(project.updatedAt)}
+ {formatUpdated(projectActivityAt(project))}
</span>
{/* Pinning is one click here, as it is on a sidebar row. */}
<button
@@ -924,7 +947,15 @@ export function ProjectsPage() {
strokeWidth={1.75}
className="size-4 shrink-0"
/>
- <span className="min-w-0 flex-1 truncate">{chat.title}</span>
+ <span className="min-w-0 truncate">{chat.title}</span>
+ {chatUnread ? (
+ <span
+ role="img"
+ aria-label="Unread"
+ className="size-2 shrink-0 rounded-full bg-primary"
+ />
+ ) : null}
+ <span className="flex-1" />
{/* Same widths as a project row, so the columns line up under it, and
gone with it below sm, where a nested row has no room for both. */}
<span className="hidden w-40 shrink-0 sm:block">
@@ -1078,7 +1109,6 @@ export function ProjectsPage() {
{/* Create project (name + drag-and-drop sources) */}
<NewProjectDialog open={creating} onOpenChange={setCreating} />
- {/* Edit project (name + instructions + source folders), the sidebar's dialog. */}
<SectionNameDialog
open={sectionFor !== null}
mode="create"
@@ -1090,6 +1120,7 @@ export function ProjectsPage() {
}
}}
/>
+ {/* Edit project (name + instructions + source folders), the sidebar's dialog. */}
<EditProjectDialog
project={editing}
onOpenChange={(open) => {
diff --git a/studio/frontend/src/features/rag/components/project-sources-panel.tsx b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
index aef92e8d024..5f07a022a24 100644
--- a/studio/frontend/src/features/rag/components/project-sources-panel.tsx
+++ b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
@@ -10,12 +10,11 @@ import { FolderPlusIcon } from "@/lib/hugeicons-derived";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useCallback, useEffect, useMemo, useRef } from "react";
+import { useCallback, useMemo, useRef } from "react";
import {
announceProjectSourcesUpdated,
invalidateProjectSources,
listProjectDocuments,
- subscribeProjectSourcesUpdated,
} from "../api/rag-api";
import { isLinkedFolderManaged } from "../types/rag";
import { DocumentStatusChip } from "./document-status-chip";
@@ -49,7 +48,6 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
documents,
loading,
uploading,
- refresh,
upload,
remove,
retry,
@@ -139,21 +137,10 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
},
[projectId, remove],
);
+ // No refresh here: useRagDocuments refetches on this announce, and a second one doubles each sync tick.
const handleLinkedSourcesChanged = useCallback(() => {
announceProjectSourcesUpdated(projectId);
- void refresh({ quiet: true });
- }, [projectId, refresh]);
-
- // External mutators (sidebar/thread saves, deletes elsewhere) announce when they are done;
- // refresh the mounted list so a source saved from a chat shows up here without a remount. The
- // list only polls while a row it already knows is indexing, so nothing else would ever fetch it.
- useEffect(
- () =>
- subscribeProjectSourcesUpdated(projectId, () => {
- void refresh({ quiet: true });
- }),
- [projectId, refresh],
- );
+ }, [projectId]);
const empty = documents.length === 0;
diff --git a/studio/frontend/src/features/rag/components/use-linked-folders.ts b/studio/frontend/src/features/rag/components/use-linked-folders.ts
index 35423acf279..681326186dd 100644
--- a/studio/frontend/src/features/rag/components/use-linked-folders.ts
+++ b/studio/frontend/src/features/rag/components/use-linked-folders.ts
@@ -31,6 +31,11 @@ import {
linkedFolderSourcesChanged,
retainActiveFolderJobs,
} from "../types/rag";
+
+const LINKED_FOLDERS_BUSY_POLL_MS = 4_000;
+// Matches the backend's folder scan interval.
+const LINKED_FOLDERS_IDLE_POLL_MS = 30_000;
+
export function useLinkedFolders(
scope?: LinkedFolderScope,
onSourcesChanged?: () => void,
@@ -255,14 +260,30 @@ export function useLinkedFolders(
folderSnapshot.current = null;
notifiedJobs.current.clear();
const initialRefresh = window.setTimeout(() => void refresh(), 0);
- const interval = window.setInterval(
- () => void refresh({ quiet: true }),
- 4000,
- );
+ // Fast only while a sync runs; idle folders only need to notice the backend's scan timer.
+ let lastPoll = Date.now();
+ const poll = () => {
+ lastPoll = Date.now();
+ void refresh({ quiet: true });
+ };
+ const interval = window.setInterval(() => {
+ if (document.hidden) return;
+ const busy =
+ controllers.current.size > 0 ||
+ (folderSnapshot.current ?? []).some(
+ (folder) => folder.status === "syncing" || folder.activeJobId,
+ );
+ if (busy || Date.now() - lastPoll >= LINKED_FOLDERS_IDLE_POLL_MS) poll();
+ }, LINKED_FOLDERS_BUSY_POLL_MS);
+ const onVisible = () => {
+ if (!document.hidden) poll();
+ };
+ document.addEventListener("visibilitychange", onVisible);
const activeControllers = controllers.current;
return () => {
window.clearTimeout(initialRefresh);
window.clearInterval(interval);
+ document.removeEventListener("visibilitychange", onVisible);
for (const controller of activeControllers.values()) controller.abort();
activeControllers.clear();
};
diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.ts
index 1f642690728..18207385d72 100644
--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts
+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts
@@ -68,6 +68,18 @@ export function uploadItemFromIntent(intent: NativeIntent): RagUploadItem {
};
}
+export function sameDocument(a: TrackedDocument, b: TrackedDocument): boolean {
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
+ for (const key of keys) {
+ if (
+ a[key as keyof TrackedDocument] !== b[key as keyof TrackedDocument]
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
function itemName(item: RagUploadItem): string {
return item.kind === "file" ? item.file.name : item.name;
}
@@ -305,13 +317,17 @@ export function useRagDocuments(
);
if (refreshSeq.current !== requestId) return true;
setDocuments((prev) => {
+ // A synced folder lists thousands of rows per poll: index once, keep unchanged rows by identity.
+ const prevById = new Map(prev.map((p) => [p.id, p]));
const merged = rows.map((row) => {
- const tracked = prev.find((p) => p.id === row.id);
- return tracked &&
+ const tracked = prevById.get(row.id);
+ const next =
+ tracked &&
tracked.progress != null &&
row.status !== "completed"
- ? { ...row, progress: tracked.progress, stage: tracked.stage }
- : row;
+ ? { ...row, progress: tracked.progress, stage: tracked.stage }
+ : row;
+ return tracked && sameDocument(tracked, next) ? tracked : next;
});
// Keep optimistic chips (not yet listed) so a refresh racing an upload
// can't make them vanish, and failed rows this session can still retry.
@@ -322,7 +338,11 @@ export function useRagDocuments(
(row.id.startsWith("pending_") ||
(row.status === "failed" && retryItems.current.has(row.id))),
);
- return [...merged, ...pendingLocal];
+ const next = [...merged, ...pendingLocal];
+ return next.length === prev.length &&
+ next.every((row, i) => row === prev[i])
+ ? prev
+ : next;
});
return true;
} catch (err) {
diff --git a/studio/frontend/tests/project-source-save.test.ts b/studio/frontend/tests/project-source-save.test.ts
index fe34a930839..67acc213185 100644
--- a/studio/frontend/tests/project-source-save.test.ts
+++ b/studio/frontend/tests/project-source-save.test.ts
@@ -247,16 +247,19 @@ test("unsubscribing stops the refetch, so an unmounted panel cannot set state",
assert.equal(refreshed, 0);
});
-test("the panel subscribes, and does not resurrect a row it just deleted", async () => {
+test("the panel's list refetches once per change, and does not resurrect a row it just deleted", async () => {
const src = await readSrcAsync("features/rag/components/project-sources-panel.tsx");
+ const hook = await readSrcAsync("features/rag/components/use-rag-documents.ts");
+ // Only the hook listens: a panel subscription on top doubled every refetch.
assert.match(
- src,
- /subscribeProjectSourcesUpdated\(projectId, \(\) => \{\n\s*void refresh\(\{ quiet: true \}\);\n\s*\}\),/,
+ hook,
+ /window\.addEventListener\(PROJECT_SOURCES_CHANGED_EVENT, onChanged\)/,
"the mounted list no longer refreshes when a source is saved elsewhere",
);
assert.ok(
- !src.includes("PROJECT_SOURCES_UPDATED_EVENT"),
- "the panel listens for the raw event again, bypassing the tested subscription",
+ !src.includes("subscribeProjectSourcesUpdated") &&
+ !/void refresh\(/.test(src),
+ "the panel refetches on top of the hook's own listener again",
);
// handleRemove drops the row optimistically and *then* invalidates, so an
// invalidate that also refetched would re-list the row before the DELETE went
diff --git a/studio/frontend/tests/project-switcher-recent-limit.test.ts b/studio/frontend/tests/project-switcher-recent-limit.test.ts
index d55d1b7046b..0d037df913b 100644
--- a/studio/frontend/tests/project-switcher-recent-limit.test.ts
+++ b/studio/frontend/tests/project-switcher-recent-limit.test.ts
@@ -12,7 +12,11 @@ const SWITCHER = await readSrcAsync("features/chat/components/project-switcher.t
test("the switcher lists the six most recent projects, not all of them", () => {
assert.match(SWITCHER, /const RECENT_PROJECT_LIMIT = 6;/);
- assert.match(SWITCHER, /const recent = projects\.slice\(0, RECENT_PROJECT_LIMIT\);/);
+ // By chat activity: the server's order is by edit time, which a chat never moves.
+ assert.match(
+ SWITCHER,
+ /const recent = sortProjectsByActivity\(projects\)\.slice\(0, RECENT_PROJECT_LIMIT\);/,
+ );
// The menu draws the capped list, not the prop.
assert.match(SWITCHER, /\{recentProjects\.map\(\(project\) => \{/);
assert.ok(
diff --git a/studio/frontend/tests/projects-activity-and-polling.test.ts b/studio/frontend/tests/projects-activity-and-polling.test.ts
new file mode 100644
index 00000000000..b24c7bb8ced
--- /dev/null
+++ b/studio/frontend/tests/projects-activity-and-polling.test.ts
@@ -0,0 +1,80 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const PAGE = readSrc("features/chat/projects-page.tsx");
+const PROJECTS = readSrc("features/chat/hooks/use-chat-projects.ts");
+const THREAD = readSrc("components/assistant-ui/thread.tsx");
+const LINKED = readSrc("features/rag/components/use-linked-folders.ts");
+const DOCS = readSrc("features/rag/components/use-rag-documents.ts");
+
+test("project recency is chat activity, everywhere a recent list is drawn", () => {
+ assert.match(
+ PROJECTS,
+ /return Math\.max\(project\.lastActivityAt \?\? 0, project\.updatedAt\);/,
+ );
+ assert.match(PAGE, /projectActivityAt\(b\) - projectActivityAt\(a\)/);
+ assert.match(PAGE, /formatUpdated\(projectActivityAt\(project\)\)/);
+ assert.ok(!PAGE.includes("b.updatedAt - a.updatedAt : "), "the page still sorts by edit time");
+ assert.match(THREAD, /sortProjectsByActivity\(projects\)\.slice\(0, 3\)/);
+});
+
+test("deleting a project on the Projects page clears what the sidebar's delete clears", () => {
+ assert.match(
+ PAGE,
+ /await deleteChatProject\(target\.id, \{ deleteFiles \}\);[\s\S]{0,300}notifyChatHistoryUpdated\(\);[\s\S]{0,200}runtime\.activeProjectId === target\.id\) runtime\.setActiveProjectId\(null\);/,
+ );
+});
+
+test("an import defaults to Recents, not whichever project the server listed first", () => {
+ assert.ok(!PAGE.includes("setImportTargetId(projects[0]"));
+ assert.equal(PAGE.match(/setImportTargetId\(null\);/g)?.length, 2);
+});
+
+test("exporting every project lists chats once, not once per project", () => {
+ assert.ok(!/projects\.map\(\(p\) =>\s*listStoredChatThreads/.test(PAGE));
+});
+
+test("streamed chunk saves reload open project rows on a longer lull", () => {
+ assert.match(PAGE, /isCoalescedHistoryEvent\(event\)\n\s*\? PROJECT_CHATS_STREAM_REFRESH_DEBOUNCE_MS/);
+});
+
+test("a mount reuses a fresh project list instead of refetching it", () => {
+ assert.match(
+ PROJECTS,
+ /projectsLoaded && Date\.now\(\) - projectsLoadedAt > MOUNT_REVALIDATE_AFTER_MS/,
+ );
+});
+
+test("linked folders poll fast only while syncing, and not from a hidden tab", () => {
+ assert.match(LINKED, /if \(document\.hidden\) return;/);
+ assert.match(LINKED, /folder\.status === "syncing" \|\| folder\.activeJobId/);
+ assert.match(LINKED, /if \(busy \|\| Date\.now\(\) - lastPoll >= LINKED_FOLDERS_IDLE_POLL_MS\) poll\(\);/);
+ assert.match(LINKED, /document\.addEventListener\("visibilitychange", onVisible\);/);
+ assert.match(LINKED, /document\.removeEventListener\("visibilitychange", onVisible\);/);
+});
+
+test("an idle chat page backs off its wait for a CLI-started model", () => {
+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");
+ assert.match(
+ runtime,
+ /sawLoad \|\| elapsed < CLI_LOAD_POLL_FAST_MS\n\s*\? CLI_LOAD_POLL_FAST_INTERVAL_MS\n\s*: CLI_LOAD_POLL_IDLE_INTERVAL_MS,/,
+ );
+ assert.match(runtime, /const CLI_LOAD_POLL_IDLE_INTERVAL_MS = 2_000;/);
+ assert.ok(
+ !runtime.includes("setTimeout(resolve, 500)"),
+ "the wait polls twice a second for its whole minute again",
+ );
+});
+
+test("a document refresh indexes the previous rows and keeps unchanged ones", () => {
+ assert.ok(!DOCS.includes("prev.find((p) => p.id === row.id)"), "the merge is quadratic again");
+ assert.match(DOCS, /const prevById = new Map\(prev\.map\(\(p\) => \[p\.id, p\]\)\);/);
+ assert.match(DOCS, /return tracked && sameDocument\(tracked, next\) \? tracked : next;/);
+ assert.match(DOCS, /next\.every\(\(row, i\) => row === prev\[i\]\)\n\s*\? prev/);
+});
diff --git a/studio/frontend/tests/projects-page-rows.test.ts b/studio/frontend/tests/projects-page-rows.test.ts
index f737b3a3e23..7e0d8478033 100644
--- a/studio/frontend/tests/projects-page-rows.test.ts
+++ b/studio/frontend/tests/projects-page-rows.test.ts
@@ -32,7 +32,8 @@ test("a project row opens its chats in place", () => {
);
assert.match(PAGE, /window\.addEventListener\(CHAT_HISTORY_UPDATED_EVENT, refresh\);/);
// Debounced, since streaming fires the event per chunk, and open rows reload in place.
- assert.match(PAGE, /timer = setTimeout\(\(\) => \{[\s\S]*?for \(const id of open\) loadProjectChats\(id, true\);\n\s*\}, PROJECT_CHATS_REFRESH_DEBOUNCE_MS\);/);
+ // A chunk save waits for a longer lull than a structural change.
+ assert.match(PAGE, /timer = setTimeout\(\(\) => \{[\s\S]*?for \(const id of open\) loadProjectChats\(id, true\);\n\s*\}, isCoalescedHistoryEvent\(event\)\n\s*\? PROJECT_CHATS_STREAM_REFRESH_DEBOUNCE_MS\n\s*: PROJECT_CHATS_REFRESH_DEBOUNCE_MS\);/);
assert.match(PAGE, /if \(!silent\) \{\n\s*setProjectChats\(\(prev\) => \(\{ \.\.\.prev, \[projectId\]: "loading" \}\)\);/);
// A closed project's pending load is invalidated with its cache entry.
assert.match(PAGE, /for \(const \[id, seq\] of loadSeqRef\.current\) \{\n\s*if \(!open\.has\(id\)\) loadSeqRef\.current\.set\(id, seq \+ 1\);/);
@@ -146,7 +147,7 @@ test("the Updated column names the list's order and turns it around", () => {
assert.match(PAGE, /sortDir === "asc" && "rotate-180",/);
assert.match(
PAGE,
- /sortDir === "asc" \? a\.updatedAt - b\.updatedAt : b\.updatedAt - a\.updatedAt,/,
+ /sortDir === "asc"\n\s*\? projectActivityAt\(a\) - projectActivityAt\(b\)\n\s*: projectActivityAt\(b\) - projectActivityAt\(a\),/,
);
// The Sort by control it replaces is gone, with the mode it carried.
assert.ok(!PAGE.includes("Sort by"), "the sort control is still in the header");