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: Chats library in the Library (#12122)

Michael Han4b98af852553
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 9c6f014a1fa..0cc01bbc9d4 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -71,6 +71,7 @@ from storage.studio_db import (
list_chat_settings,
list_chat_messages,
list_chat_messages_for_threads,
+ count_chat_messages_for_threads,
list_chat_threads,
remap_chat_thread_document_ids,
sync_chat_messages,
@@ -184,6 +185,8 @@ class ChatThread(BaseModel):
forkedFromMessageId: Optional[str] = None
forkBoundaryMessageId: Optional[str] = None
forkTitleBase: Optional[str] = None
+ # Server-set on rename, move or (un)archive.
+ modifiedAt: Optional[int] = None
settings: Optional[ChatThreadSettings] = None
@field_serializer("settings")
@@ -596,6 +599,10 @@ class ChatMessagesBatchResponse(BaseModel):
messagesByThreadId: dict[str, list[ChatMessage]]
+class ChatMessageCountsResponse(BaseModel):
+ countsByThreadId: dict[str, int]
+
+
class ChatImportLedgerResponse(BaseModel):
threadIds: list[str]
@@ -1409,6 +1416,16 @@ def batch_thread_messages(
return ChatMessagesBatchResponse(messagesByThreadId = by_thread)
[email protected]("/messages:counts", response_model = ChatMessageCountsResponse)
+def count_thread_messages(
+ payload: ChatMessagesBatchRequest, current_subject: str = Depends(get_current_subject)
+):
+ """Per-thread message counts, without message bodies."""
+ return ChatMessageCountsResponse(
+ countsByThreadId = count_chat_messages_for_threads(payload.threadIds)
+ )
+
+
@router.get("/threads/{thread_id}/messages/{message_id}", response_model = ChatMessage)
def get_thread_message(
thread_id: str,
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 3bd41d56b82..fed9a9d3054 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -18,6 +18,7 @@ import re
import shutil
import sqlite3
import threading
+import time
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
@@ -446,6 +447,7 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
fork_boundary_message_id TEXT,
fork_title_base TEXT,
settings_json TEXT,
+ modified_at INTEGER,
FOREIGN KEY(project_id) REFERENCES chat_projects(id) ON DELETE CASCADE
)
"""
@@ -482,6 +484,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
# Null on every earlier row, which then numbers from its whole title.
if "fork_title_base" not in chat_thread_cols:
conn.execute("ALTER TABLE chat_threads ADD COLUMN fork_title_base TEXT")
+ # Last rename, move or (un)archive. Null until then.
+ if "modified_at" not in chat_thread_cols:
+ conn.execute("ALTER TABLE chat_threads ADD COLUMN modified_at INTEGER")
if "updated_at" not in chat_thread_cols:
conn.execute("ALTER TABLE chat_threads ADD COLUMN updated_at INTEGER")
# Floor at created_at: forked threads copy older ancestor messages, so the fork's creation time wins.
@@ -1993,6 +1998,7 @@ def _chat_thread_from_row(row: sqlite3.Row, include_settings: bool = True) -> di
"forkedFromMessageId": data.get("forked_from_message_id"),
"forkBoundaryMessageId": data.get("fork_boundary_message_id"),
"forkTitleBase": data.get("fork_title_base"),
+ "modifiedAt": data.get("modified_at"),
}
if include_settings:
thread["settings"] = _json_loads(data.get("settings_json"), None)
@@ -2191,6 +2197,17 @@ def update_chat_thread(
"fork_title_base = CASE WHEN title = ? THEN fork_title_base ELSE NULL END"
)
values.append(patch.get("title"))
+ # Stamp real renames, moves and (un)archives. The CASE reads the pre-update row.
+ edited = [
+ (column, value)
+ for key, (column, value) in allowed.items()
+ if key in patch and key in ("title", "projectId", "archived")
+ ]
+ if edited:
+ changed = " OR ".join(f"{column} IS NOT ?" for column, _ in edited)
+ assignments.append(f"modified_at = CASE WHEN {changed} THEN ? ELSE modified_at END")
+ values.extend(value for _, value in edited)
+ values.append(int(time.time() * 1000))
if not assignments and settings_write is None:
return get_chat_thread(id)
@@ -4774,6 +4791,49 @@ def delete_chat_attachment(message_id: str, attachment_id: str) -> bool:
conn.close()
+def count_chat_messages_for_threads(thread_ids: list[str]) -> dict[str, int]:
+ """User and assistant messages per thread on its newest branch, without reading bodies.
+
+ Mirrors the frontend's ``summarizeChatMessages``. Unknown ids count 0.
+ """
+ unique_thread_ids = list(dict.fromkeys(thread_ids))
+ rows_by_thread: dict[str, list[tuple[str, Optional[str], str, int]]] = {
+ tid: [] for tid in unique_thread_ids
+ }
+ if not unique_thread_ids:
+ return {}
+ conn = get_connection()
+ try:
+ for start in range(0, len(unique_thread_ids), _SQLITE_IN_CHUNK_SIZE):
+ chunk = unique_thread_ids[start : start + _SQLITE_IN_CHUNK_SIZE]
+ placeholders = ",".join("?" for _ in chunk)
+ for row in conn.execute(
+ f"""
+ SELECT thread_id, id, parent_id, role, created_at FROM chat_messages
+ WHERE thread_id IN ({placeholders})
+ ORDER BY created_at ASC, id ASC
+ """,
+ chunk,
+ ):
+ rows_by_thread[row[0]].append((row[1], row[2], row[3], row[4]))
+ finally:
+ conn.close()
+ counts: dict[str, int] = {}
+ for tid, rows in rows_by_thread.items():
+ path = rows
+ if any(parent for _, parent, _, _ in rows):
+ by_id = {row[0]: row for row in rows}
+ # First newest message, matching the frontend.
+ at = max(rows, key = lambda row: row[3]) if rows else None
+ path, seen = [], set()
+ while at is not None and at[0] not in seen:
+ seen.add(at[0])
+ path.append(at)
+ at = by_id.get(at[1]) if at[1] else None
+ counts[tid] = sum(1 for _, _, role, _ in path if role in ("user", "assistant"))
+ return counts
+
+
def list_chat_messages_for_threads(thread_ids: list[str]) -> list[dict]:
if not thread_ids:
return []
diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.py
index d2844954fef..384cd54a1e5 100644
--- a/studio/backend/tests/test_chat_history_storage.py
+++ b/studio/backend/tests/test_chat_history_storage.py
@@ -728,6 +728,57 @@ def test_list_chat_messages_for_threads_chunks_over_900_ids(tmp_path, monkeypatc
assert {m["threadId"] for m in out} == {f"t-{i}" for i in range(n)}
+def test_chat_thread_modified_at_stamps_only_real_edits(tmp_path, monkeypatch):
+ """Rename, move and archive stamp modified_at; a no-op patch or other field does not."""
+ _reset_studio_db(tmp_path, monkeypatch)
+ studio_db.upsert_chat_thread(_thread("t"))
+ assert studio_db.get_chat_thread("t")["modifiedAt"] is None
+
+ studio_db.update_chat_thread("t", {"title": "Test Chat"})
+ studio_db.update_chat_thread("t", {"archived": False, "modelId": "other"})
+ assert studio_db.get_chat_thread("t")["modifiedAt"] is None
+
+ renamed = studio_db.update_chat_thread("t", {"title": "Renamed"})
+ assert renamed["modifiedAt"] is not None
+
+ with sqlite3.connect(studio_db_path()) as conn:
+ conn.execute("UPDATE chat_threads SET modified_at = 1 WHERE id = 't'")
+ archived = studio_db.update_chat_thread("t", {"archived": True})
+ assert archived["modifiedAt"] > 1
+
+
+def test_count_chat_messages_for_threads_follows_the_newest_branch(tmp_path, monkeypatch):
+ """Counts user/assistant rows; a branched thread counts only its newest path."""
+ _reset_studio_db(tmp_path, monkeypatch)
+ for tid in ("flat", "branched", "empty"):
+ studio_db.upsert_chat_thread(_thread(tid))
+
+ def msg(tid, mid, parent, role, at):
+ studio_db.upsert_chat_message(
+ {
+ "id": mid,
+ "threadId": tid,
+ "parentId": parent,
+ "role": role,
+ "content": [{"type": "text", "text": "x"}],
+ "createdAt": at,
+ }
+ )
+
+ msg("flat", "f1", None, "user", 1)
+ msg("flat", "f2", None, "assistant", 2)
+ msg("flat", "f3", None, "system", 3)
+ # b1 -> b2 (old reply) and b1 -> b3 (regenerated, newest) -> b4
+ msg("branched", "b1", None, "user", 10)
+ msg("branched", "b2", "b1", "assistant", 11)
+ msg("branched", "b3", "b1", "assistant", 12)
+ msg("branched", "b4", "b3", "user", 13)
+
+ counts = studio_db.count_chat_messages_for_threads(["flat", "branched", "empty", "missing"])
+ assert counts == {"flat": 2, "branched": 3, "empty": 0, "missing": 0}
+ assert studio_db.count_chat_messages_for_threads([]) == {}
+
+
# ---------------------------------------------------------------------------
# Legacy Dexie import ledger
# ---------------------------------------------------------------------------
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index cc1d8237e89..cbe20977bce 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -98,7 +98,6 @@ import {
Download01Icon,
Edit03Icon,
FolderExportIcon,
- FolderOpenIcon,
Folder01Icon,
Folder02Icon,
FlimSlateIcon,
@@ -152,10 +151,7 @@ import {
ChatSearchDialog,
clearNewChatDraft,
canForkChatRow,
- chatExportOptions,
EditProjectDialog,
- OpenChatFolderUnavailableItem,
- exportConversationByFormat,
forkChatRow,
showForkCreatedToast,
getSidebarItemThreadIds,
@@ -163,7 +159,6 @@ import {
sandboxSessionIdsHolding,
deleteChatProject,
deleteChatItem,
- listStoredChatThreads,
moveChatItemToProject,
notifyChatHistoryUpdated,
renameChatItem,
@@ -191,9 +186,7 @@ import {
customSectionIdOf,
PROJECTS_SECTION_KEY,
PINNED_SECTION_KEY,
- inSectionOrder,
resolveSectionOrder,
- assignmentMap,
type SidebarChatSort,
type SidebarCustomSection,
type SidebarOrganizeBy,
@@ -208,13 +201,11 @@ import {
recentChatItemAtSlot,
useChatNavigationStore,
SectionNameDialog,
+ removeCustomSectionWithUndo,
sectionKeyLanding,
useSectionDrag,
} from "@/features/chat";
import { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";
-import {
- revealSandbox,
-} from "@/components/assistant-ui/sandbox-reveal";
import { NewProjectDialog } from "@/features/chat/components/new-project-dialog";
import {
sidebarNavRowPinned,
@@ -266,7 +257,6 @@ import {
type ComponentType,
type ReactNode,
} from "react";
-import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import {
folderRingKey,
@@ -1222,9 +1212,6 @@ export function AppSidebar() {
const renameCustomSection = useSidebarOrganizationStore(
(s) => s.renameCustomSection,
);
- const deleteCustomSection = useSidebarOrganizationStore(
- (s) => s.deleteCustomSection,
- );
const setCustomSectionSort = useSidebarOrganizationStore(
(s) => s.setCustomSectionSort,
);
@@ -3529,56 +3516,9 @@ export function AppSidebar() {
/** Deletes a section. Nothing in it is deleted: its rows go back where they came from, and the
* toast can put the section back with them. */
function removeCustomSection(section: SidebarCustomSection) {
- const state = useSidebarOrganizationStore.getState();
- const index = state.customSections.findIndex((s) => s.id === section.id);
- const chatIds = Object.keys(state.sectionByChatId).filter(
- (id) => state.sectionByChatId[id] === section.id,
- );
- const projectIds = Object.keys(state.sectionByProjectId).filter(
- (id) => state.sectionByProjectId[id] === section.id,
- );
- const order = state.manualOrder[customSectionScope(section.id)];
- const hidden = state.hiddenSections.includes(section.id);
- // The sections drawn after it, so undo can put it back above the first one still there.
- const drawnOrder = resolveSectionOrder(state.sectionOrder, state.customSections);
- const followers = drawnOrder.slice(drawnOrder.indexOf(section.id) + 1);
- deleteCustomSection(section.id);
+ const undo = removeCustomSectionWithUndo(section);
toast.success(t("shell.sections.deleted", { name: section.name }), {
- action: {
- label: t("shell.sections.undo"),
- onClick: () => {
- useSidebarOrganizationStore.setState((now) => {
- if (now.customSections.some((s) => s.id === section.id)) return now;
- const restored = [...now.customSections];
- restored.splice(Math.min(index, restored.length), 0, section);
- const sectionByChatId = assignmentMap(now.sectionByChatId);
- for (const id of chatIds) sectionByChatId[id] ??= section.id;
- const sectionByProjectId = assignmentMap(now.sectionByProjectId);
- for (const id of projectIds) sectionByProjectId[id] ??= section.id;
- const sectionOrder = resolveSectionOrder(now.sectionOrder, now.customSections);
- const follower = followers.find((key) => sectionOrder.includes(key));
- sectionOrder.splice(
- follower === undefined ? sectionOrder.length : sectionOrder.indexOf(follower),
- 0,
- section.id,
- );
- return {
- // In the order the sidebar now draws them, which the sections left behind may have
- // been dragged out of since: the Show and Section lists read top to bottom like it.
- customSections: inSectionOrder(restored, sectionOrder),
- sectionOrder,
- sectionByChatId,
- sectionByProjectId,
- hiddenSections: hidden
- ? [...now.hiddenSections, section.id]
- : now.hiddenSections,
- manualOrder: order
- ? { ...now.manualOrder, [customSectionScope(section.id)]: order }
- : now.manualOrder,
- };
- });
- },
- },
+ action: { label: t("shell.sections.undo"), onClick: undo },
});
}
@@ -4365,12 +4305,9 @@ export function AppSidebar() {
) {
const threadIds = getSidebarItemThreadIds(item);
const isPinned = pinnedIdSet.has(item.id);
- // A compare row outside a project spans two sandboxes, and there is no
- // honest single folder to offer for it.
- const sandboxSessionId =
- item.type === "single" || item.projectId
- ? sandboxSessionIdFor(threadIds[0] ?? item.id, item.projectId)
- : undefined;
+ const alreadyUnread = threadIds.some((threadId) =>
+ unreadThreadIds.has(threadId),
+ );
// A compare row's id is the pair id while runningByThreadId is per pane thread; aggregate.
const isGenerating =
item.type === "compare"
@@ -4388,6 +4325,22 @@ export function AppSidebar() {
<HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
<span>{isPinned ? "Unpin" : "Pin"}</span>
</P.Item>
+ <P.Item
+ onSelect={() =>
+ alreadyUnread
+ ? clearThreadsUnread(threadIds)
+ : markThreadsUnread(threadIds, rowIdByThreadId)
+ }
+ >
+ <HugeiconsIcon icon={alreadyUnread ? ViewIcon : ViewOffSlashIcon} strokeWidth={1.75} className="size-icon" />
+ <span>
+ {alreadyUnread
+ ? t("shell.selection.markRead")
+ : t("shell.selection.markUnread")}
+ </span>
+ </P.Item>
+ {/* Above: edits the row. Below: copies or moves the chat. */}
+ <P.Separator />
<P.Item
disabled={!canForkChatRow(item) || isGenerating || forkInFlight}
title="Copy this chat into a new one, from its last message"
@@ -4396,47 +4349,6 @@ export function AppSidebar() {
<GitBranchIcon strokeWidth={1.75} className="size-icon" />
<span>Fork</span>
</P.Item>
- {/* Rename through Fork act on the row; the rule sets off what reaches outside it. */}
- <P.Separator />
- {sandboxSessionId ? (
- isTauri ? (
- <P.Item
- title="Open the folder this chat's tool calls read and write"
- onSelect={() => {
- void (async () => {
- try {
- // A chat moved between projects keeps the sandbox it wrote to, so its own
- // history names the folder, not current membership. A failed read is
- // reported below rather than caught per pane.
- const ids =
- threadIds.length > 0 ? threadIds : [item.id];
- const distinct = await sandboxSessionIdsHolding(ids);
- if (distinct.length > 1) {
- toast.error("This chat wrote to more than one folder.", {
- description:
- "It ran tools on both sides of a move, so open the folder from a tool card instead.",
- });
- return;
- }
- await revealSandbox(distinct[0] ?? sandboxSessionId);
- } catch (error) {
- toast.error("Could not open the chat folder.", {
- description:
- error instanceof Error
- ? error.message
- : String(error),
- });
- }
- })();
- }}
- >
- <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
- <span>Open chat folder</span>
- </P.Item>
- ) : (
- <OpenChatFolderUnavailableItem Item={P.Item} />
- )
- ) : null}
{/* Projects and sections in one place: both are where the chat is kept. */}
<P.Sub>
<P.SubTrigger>
@@ -4496,44 +4408,6 @@ export function AppSidebar() {
})}
</P.SubContent>
</P.Sub>
- <P.Sub>
- <P.SubTrigger>
- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
- <span>Export</span>
- </P.SubTrigger>
- <P.SubContent {...sidebarSubmenuOffsets} className="unsloth-plus-menu sidebar-row-menu sidebar-menu w-48">
- {chatExportOptions().map(({ label, format }) => (
- <P.Item
- key={label}
- onSelect={async () => {
- try {
- const ids = item.type === "single"
- ? [item.id]
- : (await listStoredChatThreads({ pairId: item.id })).map((t) => t.id);
- for (const id of ids) {
- await exportConversationByFormat(id, format);
- }
- } catch (error) {
- if (!isDownloadCancelled(error)) {
- toast.error("Export failed.");
- }
- }
- }}
- >
- {label}
- </P.Item>
- ))}
- <P.Separator />
- {/* Bulk export and import live in Settings -> Data. */}
- <P.Item
- onSelect={() =>
- useSettingsDialogStore.getState().openDialog("data")
- }
- >
- Export all chats…
- </P.Item>
- </P.SubContent>
- </P.Sub>
<P.Separator />
<P.Item onSelect={() => void handleArchiveThread(item)}>
<HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-reveal.ts b/studio/frontend/src/components/assistant-ui/sandbox-reveal.ts
index edbc2b94bc1..f00c8577aaa 100644
--- a/studio/frontend/src/components/assistant-ui/sandbox-reveal.ts
+++ b/studio/frontend/src/components/assistant-ui/sandbox-reveal.ts
@@ -49,6 +49,9 @@ export async function revealSandbox(sessionId: string): Promise<void> {
} catch {
// A non-JSON error body leaves the status as the only thing to report.
}
- throw new Error(detail || `Request failed (${response.status})`);
+ // Status lets callers tell "no folder yet" (404) from a failure.
+ throw Object.assign(new Error(detail || `Request failed (${response.status})`), {
+ status: response.status,
+ });
}
}
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 1e3aef0abab..09e0db14eae 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1192,6 +1192,23 @@ export async function batchListChatMessages(
return out;
}
+/** Message counts per thread, without bodies. Null on an older server without the route. */
+export async function batchCountChatMessages(
+ threadIds: string[],
+): Promise<Map<string, number> | null> {
+ const out = new Map<string, number>();
+ if (threadIds.length === 0) return out;
+ const response = await authFetch("/api/chat/messages:counts", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ threadIds }),
+ });
+ if (response.status === 404 || response.status === 405) return null;
+ const data = await parseJsonOrThrow<{ countsByThreadId: Record<string, number> }>(response);
+ for (const id of threadIds) out.set(id, data.countsByThreadId[id] ?? 0);
+ return out;
+}
+
export async function getChatMessage(
threadId: string,
messageId: string,
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index f2d2d9ec8e5..7441f2ffe1d 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -177,7 +177,13 @@ import {
useChatSidebarItems,
} from "./hooks/use-chat-sidebar-items";
import { usePinnedChatsStore } from "./stores/pinned-chats-store";
-import { usePinnedProjectsStore } from "./stores/pinned-projects-store";
+import {
+ normalizeSectionName,
+ useSidebarOrganizationStore,
+} from "./stores/sidebar-organization-store";
+import { SectionNameDialog } from "./components/section-name-dialog";
+import { ProjectMenuItems } from "./components/project-menu-items";
+import { useFileProjectInSection } from "./hooks/use-file-project-in-section";
import {
clearTrainingCompareHandoff,
getTrainingCompareHandoff,
@@ -1393,26 +1399,11 @@ function ProjectLanding({
} | null>(null);
// Project-level options (the header kebab menu).
- const pinnedProjectIds = usePinnedProjectsStore((s) => s.pinnedIds);
- const togglePinProject = usePinnedProjectsStore((s) => s.togglePin);
- const projectPinned = pinnedProjectIds.includes(projectId);
const [editingProject, setEditingProject] = useState(false);
const [deletingProject, setDeletingProject] = useState(false);
-
- async function handleProjectExport(
- format: ProjectChatExportFormat,
- ): Promise<void> {
- try {
- const threads = await listStoredChatThreads({
- projectId,
- includeArchived: false,
- });
- const ids = [...new Set(threads.map((t) => t.id))];
- for (const id of ids) await exportProjectConversation(id, format);
- } catch (error) {
- if (!isDownloadCancelled(error)) toast.error("Export failed.");
- }
- }
+ const createCustomSection = useSidebarOrganizationStore((s) => s.createCustomSection);
+ const fileProjectInSection = useFileProjectInSection();
+ const [creatingSection, setCreatingSection] = useState(false);
/** A project workspace is a bigger thing to remove than a chat's sandbox, so it asks from
* scratch rather than following the chat preference, as the sidebar does it. */
@@ -1762,38 +1753,14 @@ function ProjectLanding({
</button>
)}
>
- <DropdownMenuItem onSelect={() => setEditingProject(true)}>
- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
- <span>Edit project</span>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => togglePinProject(projectId)}>
- <HugeiconsIcon icon={projectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
- <span>{projectPinned ? "Unpin project" : "Pin project"}</span>
- </DropdownMenuItem>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
- <span>Export</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="unsloth-plus-menu w-48">
- {PROJECT_CHAT_EXPORT_OPTIONS.map(({ label, format }) => (
- <DropdownMenuItem
- key={format}
- onSelect={() => void handleProjectExport(format)}
- >
- {label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onSelect={() => openProjectDelete()}
- >
- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
- <span>Delete project</span>
- </DropdownMenuItem>
+ <ProjectMenuItems
+ project={{ id: projectId, name: projectName }}
+ chatCount={items.length}
+ onEdit={() => setEditingProject(true)}
+ onDelete={() => openProjectDelete()}
+ onNewSection={() => setCreatingSection(true)}
+ subClassName="unsloth-plus-menu"
+ />
</NonModalDropdownMenu>
</div>
@@ -1843,7 +1810,7 @@ function ProjectLanding({
return (
<div
key={`${item.type}:${item.id}`}
- className="flex min-h-[calc(58px*var(--ui-space-scale,1))] w-full items-center rounded-full px-4 py-2"
+ className="flex min-h-[calc(58px*var(--ui-space-scale,1))] w-full items-center rounded-[14px] px-4 py-2"
>
<div className="min-w-0 flex-1">
<input
@@ -1881,7 +1848,7 @@ function ProjectLanding({
onFocus={(event) => event.currentTarget.select()}
maxLength={120}
aria-label="Rename chat"
- className="w-full border-0 bg-transparent text-ui-15 font-semibold leading-5 text-foreground outline-none"
+ className="w-full border-0 bg-transparent text-ui-15 leading-5 text-foreground outline-none"
/>
</div>
</div>
@@ -1890,7 +1857,7 @@ function ProjectLanding({
return (
<div
key={`${item.type}:${item.id}`}
- className="group relative flex min-h-[calc(58px*var(--ui-space-scale,1))] w-full items-center rounded-full transition-colors hover:bg-nav-surface-hover has-[[data-state=open]]:bg-nav-surface-hover"
+ className="group relative flex min-h-[calc(58px*var(--ui-space-scale,1))] w-full items-center rounded-[14px] transition-colors hover:bg-nav-surface-hover has-[[data-state=open]]:bg-nav-surface-hover"
>
<button
type="button"
@@ -1903,10 +1870,10 @@ function ProjectLanding({
: { compare: item.id, project: projectId },
});
}}
- className="flex min-h-[calc(58px*var(--ui-space-scale,1))] min-w-0 flex-1 items-center gap-4 rounded-full px-4 py-2 text-left"
+ className="flex min-h-[calc(58px*var(--ui-space-scale,1))] min-w-0 flex-1 items-center gap-4 rounded-[14px] px-4 py-2 text-left"
>
<div className="min-w-0 flex-1">
- <div className="truncate text-ui-15 font-semibold leading-5 text-foreground">
+ <div className="truncate text-ui-15 leading-5 text-foreground">
{displayTitle}
</div>
</div>
@@ -2098,6 +2065,17 @@ function ProjectLanding({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+ <SectionNameDialog
+ open={active && creatingSection}
+ mode="create"
+ onOpenChange={(open) => !open && setCreatingSection(false)}
+ onSubmit={(name) => {
+ const sectionId = createCustomSection(name);
+ if (sectionId) {
+ fileProjectInSection({ id: projectId, name: projectName }, sectionId, normalizeSectionName(name));
+ }
+ }}
+ />
{/* The sidebar's dialog, so a project is edited the same way wherever it is opened from.
Delete hands back here, which owns the confirmation below. */}
<EditProjectDialog
diff --git a/studio/frontend/src/features/chat/components/bulk-export-items.tsx b/studio/frontend/src/features/chat/components/bulk-export-items.tsx
new file mode 100644
index 00000000000..369089b2b29
--- /dev/null
+++ b/studio/frontend/src/features/chat/components/bulk-export-items.tsx
@@ -0,0 +1,52 @@
+// 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 { DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
+import { useT } from "@/i18n";
+import {
+ COMBINED_EXPORT_FORMATS_LIST,
+ type ConvExportFormat,
+ EXPORT_FORMATS_LIST,
+ exportBulkConversationsMerged,
+ exportBulkConversationsSeparate,
+} from "../prompt-storage/prompt-storage-dialog";
+
+/** Export choices for several chats: one combined file, or one per chat. */
+export function BulkExportItems({
+ onExport,
+}: {
+ onExport: (format: ConvExportFormat, merged: boolean) => void;
+}) {
+ const t = useT();
+ return (
+ <>
+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
+ <DropdownMenuItem key={`merged-${fmt}`} onSelect={() => onExport(fmt, true)}>
+ {label} {t("settings.chat.exportCombinedSuffix")}
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator className="mx-3" />
+ {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
+ <DropdownMenuItem key={`separate-${fmt}`} onSelect={() => onExport(fmt, false)}>
+ {label} {t("settings.chat.exportPerChatSuffix")}
+ </DropdownMenuItem>
+ ))}
+ </>
+ );
+}
+
+/** Exports threads as chosen in BulkExportItems; a lone thread is one file either way. */
+export async function exportThreads(
+ threadIds: string[],
+ format: ConvExportFormat,
+ merged: boolean,
+ name: string,
+): Promise<void> {
+ const stem = name.replace(/[^\p{L}\p{N}_-]+/gu, "_").slice(0, 48);
+ const basename = `${stem || "chats"}-${new Date().toISOString().slice(0, 10)}`;
+ if (merged || threadIds.length === 1) {
+ await exportBulkConversationsMerged(threadIds, format, basename);
+ } else {
+ await exportBulkConversationsSeparate(threadIds, format, basename);
+ }
+}
diff --git a/studio/frontend/src/features/chat/components/open-chat-folder-item.tsx b/studio/frontend/src/features/chat/components/open-chat-folder-item.tsx
index b12f02fba60..dcb5c9aef35 100644
--- a/studio/frontend/src/features/chat/components/open-chat-folder-item.tsx
+++ b/studio/frontend/src/features/chat/components/open-chat-folder-item.tsx
@@ -1,6 +1,8 @@
// 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 { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";
+import { revealSandbox } from "@/components/assistant-ui/sandbox-reveal";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
Tooltip,
@@ -9,7 +11,110 @@ import {
} from "@/components/ui/tooltip";
import { FolderOpenIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
+import { toast } from "@/lib/toast";
import { useState, type ComponentProps, type ComponentType } from "react";
+import type { SidebarItem } from "../hooks/use-chat-sidebar-items";
+import { getSidebarItemThreadIds, sandboxSessionIdsHolding } from "./chat-row-menu";
+
+/** A 404 means no folder yet (made on a tool's first write), not a failure. */
+function reportRevealError(
+ error: unknown,
+ t: ReturnType<typeof useT>,
+ kind: "chat" | "project",
+): void {
+ if ((error as { status?: number } | null)?.status === 404) {
+ toast.info(t(`library.chats.folder.${kind}Missing` as const), {
+ description: t("library.chats.folder.missingDescription"),
+ });
+ return;
+ }
+ toast.error(t(`library.chats.folder.${kind}Failed` as const), {
+ description: error instanceof Error ? error.message : String(error),
+ });
+}
+
+/**
+ * "Open chat folder" (desktop app only). A compare chat outside a project spans two
+ * sandboxes, so it gets no item.
+ */
+export function OpenChatFolderItem({
+ item,
+ Item = DropdownMenuItem,
+}: {
+ item: SidebarItem;
+ Item?: ComponentType<ComponentProps<typeof DropdownMenuItem>>;
+}) {
+ const t = useT();
+ const threadIds = getSidebarItemThreadIds(item);
+ const sandboxSessionId =
+ item.type === "single" || item.projectId
+ ? sandboxSessionIdFor(threadIds[0] ?? item.id, item.projectId)
+ : undefined;
+ if (!sandboxSessionId) return null;
+ if (!isTauri) return <OpenChatFolderUnavailableItem Item={Item} />;
+ return (
+ <Item
+ title={t("library.chats.folder.openChatTitle")}
+ onSelect={() => {
+ void (async () => {
+ try {
+ // Read from history: a chat moved between projects keeps its old sandbox.
+ const ids = threadIds.length > 0 ? threadIds : [item.id];
+ const distinct = await sandboxSessionIdsHolding(ids);
+ if (distinct.length > 1) {
+ toast.error(t("library.chats.folder.manyFolders"), {
+ description: t("library.chats.folder.manyFoldersDescription"),
+ });
+ return;
+ }
+ await revealSandbox(distinct[0] ?? sandboxSessionId);
+ } catch (error) {
+ reportRevealError(error, t, "chat");
+ }
+ })();
+ }}
+ >
+ <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("library.chats.folder.openChat")}</span>
+ </Item>
+ );
+}
+
+export function OpenProjectFolderItem({
+ projectId,
+ Item = DropdownMenuItem,
+}: {
+ projectId: string;
+ Item?: ComponentType<ComponentProps<typeof DropdownMenuItem>>;
+}) {
+ const t = useT();
+ const sandboxSessionId = sandboxSessionIdFor(undefined, projectId);
+ if (!sandboxSessionId) return null;
+ if (!isTauri) {
+ return (
+ <OpenChatFolderUnavailableItem
+ Item={Item}
+ label={t("library.chats.folder.openProject")}
+ hint={t("library.chats.folder.projectHint")}
+ />
+ );
+ }
+ return (
+ <Item
+ title={t("library.chats.folder.openProjectTitle")}
+ onSelect={() => {
+ void revealSandbox(sandboxSessionId).catch((error: unknown) =>
+ reportRevealError(error, t, "project"),
+ );
+ }}
+ >
+ <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("library.chats.folder.openProject")}</span>
+ </Item>
+ );
+}
/**
* "Open chat folder" for a browser session, where the backend's file manager is not the user's.
@@ -22,15 +127,21 @@ import { useState, type ComponentProps, type ComponentType } from "react";
export function OpenChatFolderUnavailableItem({
// The sidebar renders this row into its right-click menu too, which is a different Radix set.
Item = DropdownMenuItem,
+ label,
+ hint: hintOverride,
}: {
Item?: ComponentType<ComponentProps<typeof DropdownMenuItem>>;
+ label?: string;
+ hint?: string;
} = {}) {
+ const t = useT();
const [hintOpen, setHintOpen] = useState(false);
+ const hint = hintOverride ?? t("library.chats.folder.chatHint");
return (
<Item
aria-disabled={true}
- title="Only the desktop app can open a chat's files folder. In a browser, download a file from the tool result that wrote it."
+ title={hint}
className="relative opacity-50"
onSelect={(event) => {
event.preventDefault();
@@ -42,7 +153,7 @@ export function OpenChatFolderUnavailableItem({
onBlur={() => setHintOpen(false)}
>
<HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
- <span>Open chat folder</span>
+ <span>{label ?? t("library.chats.folder.openChat")}</span>
<Tooltip open={hintOpen}>
{/* Our wrapper, not the raw primitive: it registers the trigger element,
without which the tooltip counts itself blocked by the open menu. */}
@@ -53,8 +164,7 @@ export function OpenChatFolderUnavailableItem({
/>
</TooltipTrigger>
<TooltipContent side="right" className="max-w-[calc(220px*var(--ui-space-scale,1))]">
- Only the desktop app can open a chat&apos;s files folder. In a browser, download a
- file from the tool result that wrote it.
+ {hint}
</TooltipContent>
</Tooltip>
</Item>
diff --git a/studio/frontend/src/features/chat/components/project-menu-items.tsx b/studio/frontend/src/features/chat/components/project-menu-items.tsx
new file mode 100644
index 00000000000..70de32cb74b
--- /dev/null
+++ b/studio/frontend/src/features/chat/components/project-menu-items.tsx
@@ -0,0 +1,191 @@
+// 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 {
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useChatFavoritesStore } from "@/features/library/chats/favorites-store";
+import { useT } from "@/i18n";
+import { StarPointedIcon } from "@/lib/hugeicons-derived";
+import { isDownloadCancelled } from "@/lib/native-files";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import {
+ Cancel01Icon,
+ Delete02Icon,
+ Download01Icon,
+ FolderExportIcon,
+ LayerIcon,
+ PencilEdit02Icon,
+ PinIcon,
+ PinOffIcon,
+ PlusSignIcon,
+ Settings02Icon,
+ Upload01Icon,
+} from "@hugeicons/core-free-icons";
+import { type IconSvgElement, HugeiconsIcon } from "@hugeicons/react";
+import type { ReactNode } from "react";
+import { useFileProjectInSection } from "../hooks/use-file-project-in-section";
+import { usePinnedProjectsStore } from "../stores/pinned-projects-store";
+import { useSidebarOrganizationStore } from "../stores/sidebar-organization-store";
+import { listStoredChatThreads } from "../utils/chat-history-storage";
+import { pickAndImportChats } from "../utils/import-chats";
+import { BulkExportItems, exportThreads } from "./bulk-export-items";
+import { OpenProjectFolderItem } from "./open-chat-folder-item";
+
+function Item({
+ icon,
+ onSelect,
+ destructive,
+ children,
+}: {
+ icon: IconSvgElement;
+ onSelect: () => void;
+ destructive?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <DropdownMenuItem onSelect={onSelect} variant={destructive ? "destructive" : "default"}>
+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">{children}</span>
+ </DropdownMenuItem>
+ );
+}
+
+/**
+ * The Library's project menu, for the project's home and the Projects page. With onNewChat it
+ * opens with it and the folder, as in the Library; the home puts the folder under Export.
+ */
+export function ProjectMenuItems({
+ project,
+ chatCount,
+ onNewChat,
+ onEdit,
+ onDelete,
+ onNewSection,
+ subClassName,
+}: {
+ project: { id: string; name: string };
+ /** Off Export at 0; unknown (undefined) leaves it on. */
+ chatCount?: number;
+ onNewChat?: () => void;
+ onEdit: () => void;
+ onDelete: () => void;
+ onNewSection: () => void;
+ subClassName?: string;
+}) {
+ const t = useT();
+ const pinned = usePinnedProjectsStore((s) => s.pinnedIds.includes(project.id));
+ const togglePin = usePinnedProjectsStore((s) => s.togglePin);
+ const favorite = useChatFavoritesStore((s) => s.projectIds.includes(project.id));
+ const setFavorites = useChatFavoritesStore((s) => s.setProjects);
+ const sections = useSidebarOrganizationStore((s) => s.customSections);
+ const sectionId = useSidebarOrganizationStore((s) => s.sectionByProjectId[project.id] ?? null);
+ const fileProjectInSection = useFileProjectInSection();
+ const leaving = sections.find((section) => section.id === sectionId);
+ const opening = Boolean(onNewChat);
+
+ async function exportProject(format: Parameters<typeof exportThreads>[1], merged: boolean) {
+ try {
+ const threads = await listStoredChatThreads({ projectId: project.id, includeArchived: false });
+ const ids = [...new Set(threads.map((thread) => thread.id))];
+ if (ids.length > 0) await exportThreads(ids, format, merged, `project-${project.name}`);
+ } catch (error) {
+ if (!isDownloadCancelled(error)) toast.error(t("settings.data.exportFailed"));
+ }
+ }
+
+ return (
+ <>
+ {opening && (
+ <>
+ {onNewChat && (
+ <Item icon={PencilEdit02Icon} onSelect={onNewChat}>
+ {t("library.chats.menu.newChatInProject")}
+ </Item>
+ )}
+ <OpenProjectFolderItem projectId={project.id} />
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <Item icon={Settings02Icon} onSelect={onEdit}>
+ {t("library.chats.menu.edit")}
+ </Item>
+ <Item icon={pinned ? PinOffIcon : PinIcon} onSelect={() => togglePin(project.id)}>
+ {t(pinned ? "settings.data.library.unpin" : "settings.data.library.pin")}
+ </Item>
+ <DropdownMenuItem onSelect={() => setFavorites([project.id], !favorite)}>
+ <HugeiconsIcon
+ icon={StarPointedIcon}
+ strokeWidth={1.75}
+ className={cn("size-icon", favorite && "[&_path]:fill-current")}
+ />
+ <span>{t(favorite ? "library.menu.removeFromFavorites" : "library.menu.addToFavorites")}</span>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {/* Sections only: projects never nest. */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.sections.moveTo")}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ className={cn(
+ "max-h-[var(--radix-dropdown-menu-content-available-height)] w-56 overflow-y-auto",
+ subClassName,
+ )}
+ >
+ <DropdownMenuLabel className="font-normal text-muted-foreground">
+ {t("shell.sections.sectionsHeading")}
+ </DropdownMenuLabel>
+ <Item icon={PlusSignIcon} onSelect={onNewSection}>
+ {t("shell.sections.newSection")}
+ </Item>
+ {sections
+ .filter((section) => section.id !== sectionId)
+ .map((section) => (
+ <Item
+ key={section.id}
+ icon={LayerIcon}
+ onSelect={() => fileProjectInSection(project, section.id)}
+ >
+ {section.name}
+ </Item>
+ ))}
+ {sectionId && (
+ <Item icon={Cancel01Icon} onSelect={() => fileProjectInSection(project, null)}>
+ {leaving
+ ? t("shell.sections.removeFrom", { name: leaving.name })
+ : t("shell.sections.removeFromSection")}
+ </Item>
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger disabled={chatCount === 0}>
+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("common.export")}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className={cn("w-56", subClassName)}>
+ <BulkExportItems onExport={(format, merged) => void exportProject(format, merged)} />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <Item
+ icon={Upload01Icon}
+ onSelect={() => void pickAndImportChats({ projectId: project.id, name: project.name })}
+ >
+ {t("settings.chat.importChats")}
+ </Item>
+ {!opening && <OpenProjectFolderItem projectId={project.id} />}
+ <DropdownMenuSeparator />
+ <Item icon={Delete02Icon} destructive onSelect={onDelete}>
+ {t("library.chats.menu.deleteProject")}
+ </Item>
+ </>
+ );
+}
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 b4da8732b7f..ec4310a272f 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
@@ -34,6 +34,9 @@ export interface SidebarItem {
title: string;
createdAt: number;
updatedAt: number;
+ /** Last rename, move or (un)archive. */
+ modifiedAt?: number;
+ modelIds?: string[];
isFork?: boolean;
projectId?: string | null;
}
@@ -61,6 +64,10 @@ export function groupThreads(
if (existing) {
existing.createdAt = Math.max(existing.createdAt, t.createdAt);
existing.updatedAt = Math.max(existing.updatedAt, lastActivityAt(t));
+ if (t.modifiedAt) existing.modifiedAt = Math.max(existing.modifiedAt ?? 0, t.modifiedAt);
+ if (t.modelId && !existing.modelIds?.includes(t.modelId)) {
+ existing.modelIds = [...(existing.modelIds ?? []), t.modelId];
+ }
existing.threadIds?.push(t.id);
continue;
}
@@ -71,6 +78,8 @@ export function groupThreads(
title: t.title,
createdAt: t.createdAt,
updatedAt: lastActivityAt(t),
+ ...(t.modifiedAt ? { modifiedAt: t.modifiedAt } : {}),
+ ...(t.modelId ? { modelIds: [t.modelId] } : {}),
projectId: t.projectId ?? null,
};
pairItems.set(t.pairId, item);
@@ -83,6 +92,8 @@ export function groupThreads(
title: t.title,
createdAt: t.createdAt,
updatedAt: lastActivityAt(t),
+ ...(t.modifiedAt ? { modifiedAt: t.modifiedAt } : {}),
+ ...(t.modelId ? { modelIds: [t.modelId] } : {}),
isFork: Boolean(t.forkedFromThreadId),
projectId: t.projectId ?? null,
});
diff --git a/studio/frontend/src/features/chat/hooks/use-file-project-in-section.ts b/studio/frontend/src/features/chat/hooks/use-file-project-in-section.ts
new file mode 100644
index 00000000000..67e61d269ef
--- /dev/null
+++ b/studio/frontend/src/features/chat/hooks/use-file-project-in-section.ts
@@ -0,0 +1,43 @@
+// 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 { useT } from "@/i18n";
+import { toast } from "@/lib/toast";
+import { useCallback } from "react";
+import { usePinnedProjectsStore } from "../stores/pinned-projects-store";
+import { useSidebarOrganizationStore } from "../stores/sidebar-organization-store";
+
+/** Files a project in a section (null unfiles). Filing unpins, since Pinned would still show it. */
+export function useFileProjectInSection(): (
+ project: { id: string; name: string },
+ sectionId: string | null,
+ sectionName?: string,
+) => void {
+ const t = useT();
+ return useCallback(
+ (project, sectionId, sectionName) => {
+ const organization = useSidebarOrganizationStore.getState();
+ const leaving = organization.sectionByProjectId[project.id];
+ const nameOf = (id: string | undefined) =>
+ organization.customSections.find((section) => section.id === id)?.name ?? "";
+ organization.setProjectsSection([project.id], sectionId);
+ if (sectionId) {
+ const pins = usePinnedProjectsStore.getState();
+ if (pins.pinnedIds.includes(project.id)) pins.unpin(project.id);
+ organization.setSectionHidden(sectionId, false);
+ }
+ toast.success(
+ sectionId
+ ? t("library.chats.toast.projectMoved", {
+ project: project.name,
+ section: sectionName ?? nameOf(sectionId),
+ })
+ : t("library.chats.toast.projectUnfiled", {
+ project: project.name,
+ section: nameOf(leaving),
+ }),
+ );
+ },
+ [t],
+ );
+}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index abb9d8744ec..ec26d44932e 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -185,6 +185,7 @@ export type {
} from "./stores/sidebar-organization-store";
export { useChatPreferencesStore } from "./stores/chat-preferences-store";
export { SectionNameDialog } from "./components/section-name-dialog";
+export { removeCustomSectionWithUndo } from "./stores/remove-custom-section";
export {
usePromptQueueUI,
type PromptQueueUIEntry,
@@ -326,7 +327,14 @@ export {
sandboxSessionIdsHolding,
type ConversationExportFormat,
} from "./components/chat-row-menu";
-export { OpenChatFolderUnavailableItem } from "./components/open-chat-folder-item";
+export {
+ OpenChatFolderItem,
+ OpenChatFolderUnavailableItem,
+ OpenProjectFolderItem,
+} from "./components/open-chat-folder-item";
+export { BulkExportItems, exportThreads } from "./components/bulk-export-items";
+export { useFileProjectInSection } from "./hooks/use-file-project-in-section";
+export { pickAndImportChats } from "./utils/import-chats";
export { useForkInFlight } from "./utils/fork-in-flight";
export { showForkCreatedToast } from "./utils/fork-toast";
export { clearAllChats, countAllChats } from "./utils/clear-all-chats";
@@ -370,6 +378,8 @@ export {
getStoredChatThread,
isThreadIncognito,
listStoredChatMessages,
+ listStoredChatMessagesMany,
+ countStoredChatMessages,
listStoredChatProjects,
listStoredChatThreads,
markThreadIncognito,
diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsx
index 0f79bd9ccc6..d385b376207 100644
--- a/studio/frontend/src/features/chat/projects-page.tsx
+++ b/studio/frontend/src/features/chat/projects-page.tsx
@@ -38,7 +38,7 @@ import { toast } from "@/lib/toast";
import {
chatExportOptions,
DeleteChatFilesSwitch,
- OpenChatFolderUnavailableItem,
+ OpenChatFolderItem,
archiveChatItem,
deleteChatItem,
deleteChatProject,
@@ -46,7 +46,7 @@ import {
getSidebarItemThreadIds,
notifyChatHistoryUpdated,
renameChatItem,
- sandboxSessionIdsHolding,
+ useChatNavigationStore,
useChatPreferencesStore,
useChatProjects,
useChatRuntimeStore,
@@ -56,8 +56,7 @@ import {
type ProjectRecord,
} from "@/features/chat";
import { useSettingsDialogStore } from "@/features/settings";
-import { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";
-import { revealSandbox } from "@/components/assistant-ui/sandbox-reveal";
+import { useT } from "@/i18n";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { buildProjectsTourSteps } from "./tour";
import { EditProjectDialog } from "./components/edit-project-dialog";
@@ -69,11 +68,12 @@ import {
Edit03Icon,
Folder02Icon,
FolderAddIcon,
- FolderOpenIcon,
PinIcon,
PinOffIcon,
Search01Icon,
Upload01Icon,
+ ViewIcon,
+ ViewOffSlashIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { ArrowDownIcon, ChevronDownIcon, MoreHorizontalIcon } from "lucide-react";
@@ -82,7 +82,6 @@ import { useNavigate } from "@tanstack/react-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
COMBINED_EXPORT_FORMATS_LIST,
- exportProjectConversations,
exportBulkConversationsMerged,
exportBulkConversationsSeparate,
EXPORT_FORMATS_LIST,
@@ -90,7 +89,6 @@ import {
} from "./prompt-storage/prompt-storage-dialog";
import {
fileImportSource,
- importConversationsFromSource,
nativeImportSource,
type ImportSource,
} from "./utils/chat-import";
@@ -99,6 +97,15 @@ import {
} from "./utils/chat-history-storage";
import { CHAT_HISTORY_UPDATED_EVENT } from "./api/chat-api";
import { groupThreads, type SidebarItem } from "./hooks/use-chat-sidebar-items";
+import { ProjectMenuItems } from "./components/project-menu-items";
+import { SectionNameDialog } from "./components/section-name-dialog";
+import { useFileProjectInSection } from "./hooks/use-file-project-in-section";
+import {
+ normalizeSectionName,
+ useSidebarOrganizationStore,
+} from "./stores/sidebar-organization-store";
+import { clearNewChatDraft } from "./utils/composer-draft";
+import { runChatImport } from "./utils/import-chats";
// Reveal this many more projects each time the user scrolls near the bottom.
const PROJECTS_PAGE_STEP = 12;
@@ -137,6 +144,7 @@ function formatUpdated(ts: number): string {
}
export function ProjectsPage() {
+ const t = useT();
const signalReady = useAppShellReadySignal();
const navigate = useNavigate();
const { projects, hasLoaded } = useChatProjects();
@@ -156,6 +164,9 @@ export function ProjectsPage() {
() => new Set(pinnedProjectIds),
[pinnedProjectIds],
);
+ const unreadThreadIds = useChatNavigationStore((s) => s.unreadThreadIds);
+ const markThreadsUnread = useChatNavigationStore((s) => s.markThreadsUnread);
+ const clearThreadsUnread = useChatNavigationStore((s) => s.clearThreadsUnread);
const confirmDeleteChats = useChatPreferencesStore((s) => s.confirmDeleteChats);
const alwaysDeleteChatFiles = useChatPreferencesStore(
(s) => s.alwaysDeleteChatFiles,
@@ -167,6 +178,9 @@ export function ProjectsPage() {
const [creating, setCreating] = useState(false);
const [editing, setEditing] = useState<ProjectRecord | null>(null);
+ const [sectionFor, setSectionFor] = useState<ProjectRecord | null>(null);
+ const createCustomSection = useSidebarOrganizationStore((s) => s.createCustomSection);
+ const fileProjectInSection = useFileProjectInSection();
const [deleting, setDeleting] = useState<ProjectRecord | null>(null);
const [renamingChat, setRenamingChat] = useState<SidebarItem | null>(null);
const [chatNameDraft, setChatNameDraft] = useState("");
@@ -175,7 +189,6 @@ export function ProjectsPage() {
const [deleteFilesOnDelete, setDeleteFilesOnDelete] = useState(false);
const globalImportRef = useRef<HTMLInputElement>(null);
- const projectImportRefs = useRef<Map<string, HTMLInputElement>>(new Map());
const [importFile, setImportFile] = useState<ImportSource | null>(null);
// A second pick mid-import would interleave two streams into one history.
const [importing, setImporting] = useState(false);
@@ -277,56 +290,17 @@ export function ProjectsPage() {
}, [loadProjectChats]);
async function handleImport(source: ImportSource, projectId: string | null) {
- // Counts up while it runs: a large export takes minutes of writes.
setImporting(true);
- const toastId = toast.loading("Importing chats...");
try {
- const { imported, failed } = await importConversationsFromSource(
- source,
+ await runChatImport(source, {
projectId,
- {
- onProgress: ({ imported: done, bytesRead, totalBytes }) => {
- const percent = totalBytes
- ? Math.min(100, Math.round((bytesRead / totalBytes) * 100))
- : 0;
- toast.loading(`Importing chats: ${done} so far (${percent}%)...`, {
- id: toastId,
- });
- },
- },
- );
- if (imported === 0 && failed === 0) {
- toast.info("No conversations found in file.", { id: toastId });
- return;
- }
- if (imported === 0) {
- // Nothing was created, so however the count is phrased this is a failure.
- toast.error("Import failed.", {
- id: toastId,
- description: `${failed} conversation${failed === 1 ? "" : "s"} could not be saved.`,
- });
- return;
- }
- const dest = projectId
- ? (projects.find((p) => p.id === projectId)?.name ?? "project")
- : "Recents";
- toast.success(
- failed > 0
- ? `Imported ${imported} conversation${imported === 1 ? "" : "s"} to ${dest}; ${failed} could not be saved.`
- : `Imported ${imported} conversation${imported === 1 ? "" : "s"} to ${dest}.`,
- { id: toastId },
- );
- } catch (error) {
- toast.error("Import failed.", {
- id: toastId,
- description: error instanceof Error ? error.message : undefined,
+ name: projectId ? (projects.find((p) => p.id === projectId)?.name ?? "project") : undefined,
});
} finally {
setImporting(false);
}
}
-
async function selectGlobalImportFile() {
if (importing) return;
if (!isTauri) {
@@ -345,23 +319,6 @@ export function ProjectsPage() {
}
}
- async function selectProjectImportFile(projectId: string) {
- if (importing) return;
- if (!isTauri) {
- projectImportRefs.current.get(projectId)?.click();
- return;
- }
- try {
- const selected = await pickNativeChatImport();
- if (!selected) return;
- await handleImport(nativeImportSource(selected), projectId);
- } catch (error) {
- toast.error("Import failed.", {
- description: error instanceof Error ? error.message : String(error),
- });
- }
- }
-
async function commitImport() {
if (!importFile) return;
const file = importFile;
@@ -478,16 +435,11 @@ export function ProjectsPage() {
navigate({ to: "/chat", search: { project: projectId } });
}
- async function handleProjectExport(project: ProjectRecord, fmt: ConvExportFormat) {
- try {
- const threads = await listStoredChatThreads({ projectId: project.id, includeArchived: false });
- const ids = [...new Set(threads.map((t) => t.id))];
- await exportProjectConversations(ids, fmt, project.name);
- } catch (error) {
- if (!isDownloadCancelled(error)) {
- toast.error("Export failed.");
- }
- }
+ // A saved chat with an empty composer, as the sidebar's New chat.
+ function newChatInProject(projectId: string) {
+ clearNewChatDraft();
+ useChatRuntimeStore.getState().setIncognito(false);
+ openProject(projectId);
}
async function handleBulkProjectExport(
@@ -589,26 +541,6 @@ export function ProjectsPage() {
await deleteChat(target, deleteFiles);
}
- /** The folder this chat's tool calls wrote to, or a refusal when it wrote to two. */
- async function openChatFolder(chat: SidebarItem, fallback: string) {
- try {
- const ids = getSidebarItemThreadIds(chat);
- const distinct = await sandboxSessionIdsHolding(ids);
- if (distinct.length > 1) {
- toast.error("This chat wrote to more than one folder.", {
- description:
- "It ran tools on both sides of a move, so open the folder from a tool card instead.",
- });
- return;
- }
- await revealSandbox(distinct[0] ?? fallback);
- } catch (error) {
- toast.error("Could not open the chat folder.", {
- description: error instanceof Error ? error.message : String(error),
- });
- }
- }
-
async function handleChatExport(
chat: SidebarItem,
format: ConversationExportFormat,
@@ -832,21 +764,6 @@ export function ProjectsPage() {
const chats = projectChats[project.id];
return (
<div key={`wrap-${project.id}`}>
- <input
- key={`import-${project.id}`}
- type="file"
- accept=".json,.jsonl,.ndjson,.csv"
- className="hidden"
- ref={(el) => {
- if (el) projectImportRefs.current.set(project.id, el);
- else projectImportRefs.current.delete(project.id);
- }}
- onChange={(e) => {
- const file = e.target.files?.[0];
- if (file) void handleImport(fileImportSource(file), project.id);
- e.target.value = "";
- }}
- />
<div
key={project.id}
className="group/project-row relative flex items-center gap-3 rounded-xl px-5 py-4 text-left transition-colors duration-150 hover:bg-muted/70 dark:hover:bg-[rgb(255_255_255_/_calc(0.055*var(--contrast-wash-gain,1)))]"
@@ -894,6 +811,13 @@ export function ProjectsPage() {
)}
/>
</button>
+ {/* biome-ignore lint/a11y/useKeyWithClickEvents: the chevron is the keyboard target */}
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: a wider mouse target for the chevron */}
+ <span
+ aria-hidden="true"
+ onClick={() => toggleProjectChats(project.id)}
+ className="-my-4 min-w-0 flex-1 cursor-pointer self-stretch"
+ />
</span>
<span className="hidden w-40 shrink-0 text-sm text-muted-foreground sm:block">
{formatUpdated(project.updatedAt)}
@@ -934,50 +858,15 @@ export function ProjectsPage() {
sideOffset={0}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
- className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-44 py-2 font-heading rounded-[14px] border-0"
+ className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-52 py-2 font-heading rounded-[14px] border-0"
>
- {/* No pin item: the row's own button does it. Edit opens the sidebar's
- dialog, which owns the name, instructions and source folders. */}
- <DropdownMenuItem onSelect={() => setEditing(project)}>
- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
- <span>Edit</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={(e) => {
- e.stopPropagation();
- void selectProjectImportFile(project.id);
- }}
- >
- <HugeiconsIcon icon={Upload01Icon} strokeWidth={1.75} className="size-icon" />
- <span>Import chats</span>
- </DropdownMenuItem>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon mr-1" />
- <span>Export</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-52">
- {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
- <DropdownMenuItem
- key={fmt}
- onSelect={(e) => {
- e.stopPropagation();
- void handleProjectExport(project, fmt);
- }}
- >
- {label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onSelect={() => openProjectDelete(project)}
- >
- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
- <span>Delete</span>
- </DropdownMenuItem>
+ <ProjectMenuItems
+ project={project}
+ onNewChat={() => newChatInProject(project.id)}
+ onEdit={() => setEditing(project)}
+ onDelete={() => openProjectDelete(project)}
+ onNewSection={() => setSectionFor(project)}
+ />
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -1001,10 +890,8 @@ export function ProjectsPage() {
{chats.map((chat) => {
const chatPinned = pinnedChatIdSet.has(chat.id);
const chatThreadIds = getSidebarItemThreadIds(chat);
- // Every chat here sits in a project, so the folder is the project's.
- const chatSandboxId = sandboxSessionIdFor(
- chatThreadIds[0] ?? chat.id,
- project.id,
+ const chatUnread = chatThreadIds.some((id) =>
+ unreadThreadIds.has(id),
);
return (
<div
@@ -1079,21 +966,23 @@ export function ProjectsPage() {
<HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
<span>Rename</span>
</DropdownMenuItem>
- {chatSandboxId ? (
- isTauri ? (
- <DropdownMenuItem
- title="Open the folder this chat's tool calls read and write"
- onSelect={() =>
- void openChatFolder(chat, chatSandboxId)
- }
- >
- <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
- <span>Open chat folder</span>
- </DropdownMenuItem>
- ) : (
- <OpenChatFolderUnavailableItem />
- )
- ) : null}
+ <DropdownMenuItem
+ onSelect={() =>
+ chatUnread
+ ? clearThreadsUnread(chatThreadIds)
+ : markThreadsUnread(
+ chatThreadIds,
+ Object.fromEntries(
+ chatThreadIds.map((id) => [id, chat.id]),
+ ),
+ )
+ }
+ >
+ <HugeiconsIcon icon={chatUnread ? ViewIcon : ViewOffSlashIcon} strokeWidth={1.75} className="size-icon" />
+ <span>
+ {t(chatUnread ? "shell.selection.markRead" : "shell.selection.markUnread")}
+ </span>
+ </DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon mr-1" />
@@ -1124,6 +1013,7 @@ export function ProjectsPage() {
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ <OpenChatFolderItem item={chat} />
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => void archiveChat(chat)}>
<HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
@@ -1173,6 +1063,17 @@ export function ProjectsPage() {
<NewProjectDialog open={creating} onOpenChange={setCreating} />
{/* Edit project (name + instructions + source folders), the sidebar's dialog. */}
+ <SectionNameDialog
+ open={sectionFor !== null}
+ mode="create"
+ onOpenChange={(open) => !open && setSectionFor(null)}
+ onSubmit={(name) => {
+ const sectionId = createCustomSection(name);
+ if (sectionId && sectionFor) {
+ fileProjectInSection(sectionFor, sectionId, normalizeSectionName(name));
+ }
+ }}
+ />
<EditProjectDialog
project={editing}
onOpenChange={(open) => {
diff --git a/studio/frontend/src/features/chat/stores/remove-custom-section.ts b/studio/frontend/src/features/chat/stores/remove-custom-section.ts
new file mode 100644
index 00000000000..90a8781a0f7
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/remove-custom-section.ts
@@ -0,0 +1,60 @@
+// 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 {
+ type SidebarCustomSection,
+ assignmentMap,
+ customSectionScope,
+ inSectionOrder,
+ resolveSectionOrder,
+ useSidebarOrganizationStore,
+} from "./sidebar-organization-store";
+
+/** Deletes a section (not its rows); returns an undo that restores it in place. */
+export function removeCustomSectionWithUndo(section: SidebarCustomSection): () => void {
+ const state = useSidebarOrganizationStore.getState();
+ const index = state.customSections.findIndex((s) => s.id === section.id);
+ const chatIds = Object.keys(state.sectionByChatId).filter(
+ (id) => state.sectionByChatId[id] === section.id,
+ );
+ const projectIds = Object.keys(state.sectionByProjectId).filter(
+ (id) => state.sectionByProjectId[id] === section.id,
+ );
+ const order = state.manualOrder[customSectionScope(section.id)];
+ const hidden = state.hiddenSections.includes(section.id);
+ // Undo reinserts it above the first of these that still exists.
+ const drawnOrder = resolveSectionOrder(state.sectionOrder, state.customSections);
+ const followers = drawnOrder.slice(drawnOrder.indexOf(section.id) + 1);
+ state.deleteCustomSection(section.id);
+ return () => {
+ useSidebarOrganizationStore.setState((now) => {
+ if (now.customSections.some((s) => s.id === section.id)) return now;
+ const restored = [...now.customSections];
+ restored.splice(Math.min(index, restored.length), 0, section);
+ const sectionByChatId = assignmentMap(now.sectionByChatId);
+ for (const id of chatIds) sectionByChatId[id] ??= section.id;
+ const sectionByProjectId = assignmentMap(now.sectionByProjectId);
+ for (const id of projectIds) sectionByProjectId[id] ??= section.id;
+ const sectionOrder = resolveSectionOrder(now.sectionOrder, now.customSections);
+ const follower = followers.find((key) => sectionOrder.includes(key));
+ sectionOrder.splice(
+ follower === undefined ? sectionOrder.length : sectionOrder.indexOf(follower),
+ 0,
+ section.id,
+ );
+ return {
+ // Match the sidebar's current order, which may have changed since the delete.
+ customSections: inSectionOrder(restored, sectionOrder),
+ sectionOrder,
+ sectionByChatId,
+ sectionByProjectId,
+ hiddenSections: hidden
+ ? [...now.hiddenSections, section.id]
+ : now.hiddenSections,
+ manualOrder: order
+ ? { ...now.manualOrder, [customSectionScope(section.id)]: order }
+ : now.manualOrder,
+ };
+ });
+ };
+}
diff --git a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
index cd16807409e..189ca52f43a 100644
--- a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
+++ b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
@@ -36,6 +36,10 @@ export interface SidebarCustomSection {
name: string;
/** How its chats are ordered. Manual by default, like Pinned: it is a list the user built. */
sort: SidebarChatSort;
+ /** Absent on sections made before these were recorded. */
+ createdAt?: number;
+ /** Last rename, or chat or project filed in or out. */
+ modifiedAt?: number;
}
/** The fixed section the "Show" toggles can hide, beside the user's own. Pinned always shows, as
@@ -174,6 +178,19 @@ export interface SidebarOrganizationState {
}
/** Trims and bounds a section name. Empty when there is nothing to name it with. */
+function readTime(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
+}
+
+function touchSections(
+ sections: SidebarCustomSection[],
+ ids: ReadonlySet<string>,
+): SidebarCustomSection[] {
+ if (ids.size === 0) return sections;
+ const now = Date.now();
+ return sections.map((section) => (ids.has(section.id) ? { ...section, modifiedAt: now } : section));
+}
+
export function normalizeSectionName(name: string): string {
return name.replace(/\s+/g, " ").trim().slice(0, CUSTOM_SECTION_NAME_MAX);
}
@@ -341,6 +358,8 @@ export function mergePersistedOrganization(
id: entry.id,
name,
sort: readSort(entry.sort, "manual"),
+ ...(readTime(entry.createdAt) ? { createdAt: entry.createdAt } : {}),
+ ...(readTime(entry.modifiedAt) ? { modifiedAt: entry.modifiedAt } : {}),
});
}
}
@@ -424,7 +443,10 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
);
const at = firstCustom !== -1 ? firstCustom : order.indexOf(PINNED_SECTION_KEY) + 1;
return {
- customSections: [{ id, name: clean, sort: "manual" }, ...state.customSections],
+ customSections: [
+ { id, name: clean, sort: "manual", createdAt: Date.now(), modifiedAt: Date.now() },
+ ...state.customSections,
+ ],
sectionOrder: [...order.slice(0, at), id, ...order.slice(at)],
};
});
@@ -435,7 +457,9 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
if (!clean) return;
set((state) => ({
customSections: state.customSections.map((section) =>
- section.id === sectionId ? { ...section, name: clean } : section,
+ section.id === sectionId && section.name !== clean
+ ? { ...section, name: clean, modifiedAt: Date.now() }
+ : section,
),
}));
},
@@ -476,11 +500,20 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
return state;
}
const next = assignmentMap(state.sectionByChatId);
+ const touched = new Set<string>();
for (const id of chatIds) {
- if (sectionId) next[id] = sectionId;
- else delete next[id];
+ const from = next[id];
+ if (from === (sectionId ?? undefined)) continue;
+ if (from) touched.add(from);
+ if (sectionId) {
+ next[id] = sectionId;
+ touched.add(sectionId);
+ } else delete next[id];
}
- return { sectionByChatId: next };
+ return {
+ sectionByChatId: next,
+ customSections: touchSections(state.customSections, touched),
+ };
}),
setProjectsSection: (projectIds, sectionId) =>
set((state) => {
@@ -488,11 +521,20 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
return state;
}
const next = assignmentMap(state.sectionByProjectId);
+ const touched = new Set<string>();
for (const id of projectIds) {
- if (sectionId) next[id] = sectionId;
- else delete next[id];
+ const from = next[id];
+ if (from === (sectionId ?? undefined)) continue;
+ if (from) touched.add(from);
+ if (sectionId) {
+ next[id] = sectionId;
+ touched.add(sectionId);
+ } else delete next[id];
}
- return { sectionByProjectId: next };
+ return {
+ sectionByProjectId: next,
+ customSections: touchSections(state.customSections, touched),
+ };
}),
setSectionHidden: (key, hidden) =>
set((state) => {
diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.ts
index 4b389354928..c17f426284f 100644
--- a/studio/frontend/src/features/chat/types.ts
+++ b/studio/frontend/src/features/chat/types.ts
@@ -59,6 +59,8 @@ export interface ThreadRecord {
/** The name this thread's generated title numbers from, so the next fork of it is the next
* number. Cleared on rename, and null on anything the user named. */
forkTitleBase?: string | null;
+ /** Last rename, move or (un)archive (server-set). */
+ modifiedAt?: number | null;
/** this chat's own settings, applied when it is opened; absent means the global ones. */
settings?:
| import("./utils/thread-scoped-settings").ThreadScopedSettings
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 710833ba9dd..92e84a80f36 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -4,6 +4,7 @@
import {
ChatMessageProtectedError,
ChatThreadDeletedError,
+ batchCountChatMessages,
batchListChatMessages,
buildBackendChatExport,
clearBackendChats,
@@ -1179,6 +1180,44 @@ export async function updateStoredChatThread(
return updateChatThread(threadId, patch, options);
}
+/** Message counts in one request. Threads the server has none for count legacy local messages.
+ * Null on an older server. */
+export async function countStoredChatMessages(
+ threadIds: string[],
+): Promise<Map<string, number> | null> {
+ const ids = threadIds.filter((id) => !isThreadIncognito(id) && !isChatThreadDeleted(id));
+ const counts = await batchCountChatMessages(ids);
+ if (!counts) return null;
+ await Promise.all(
+ ids
+ .filter((id) => (counts.get(id) ?? 0) === 0)
+ .map(async (id) => {
+ const legacy = await readLegacyStore(
+ () => db.messages.where("threadId").equals(id).toArray(),
+ [] as MessageRecord[],
+ );
+ const n = legacy.filter((m) => m.role === "user" || m.role === "assistant").length;
+ if (n > 0) counts.set(id, n);
+ }),
+ );
+ return counts;
+}
+
+/** Messages for many threads in one request; a thread the batch has nothing for falls back to
+ * its per-thread read, which also covers legacy local history. */
+export async function listStoredChatMessagesMany(
+ threadIds: string[],
+): Promise<Map<string, MessageRecord[]>> {
+ const ids = threadIds.filter((id) => !isThreadIncognito(id) && !isChatThreadDeleted(id));
+ const out = await batchListChatMessages(ids).catch(() => new Map<string, MessageRecord[]>());
+ await Promise.all(
+ ids
+ .filter((id) => (out.get(id)?.length ?? 0) === 0)
+ .map(async (id) => out.set(id, await listStoredChatMessages(id).catch(() => []))),
+ );
+ return out;
+}
+
/** Thread ids whose sandbox still holds files, passed through from the route. */
export async function deleteStoredChatThreads(
idsToDelete: string[],
diff --git a/studio/frontend/src/features/chat/utils/chat-import.ts b/studio/frontend/src/features/chat/utils/chat-import.ts
index 687f4e244be..fbc4b5b7129 100644
--- a/studio/frontend/src/features/chat/utils/chat-import.ts
+++ b/studio/frontend/src/features/chat/utils/chat-import.ts
@@ -63,6 +63,8 @@ export interface ImportProgress {
export interface ImportOptions {
onProgress?: (progress: ImportProgress) => void;
+ /** Each chat saved, by its row id (a comparison's pair id), so a caller can file it. */
+ onSaved?: (rowId: string) => void;
}
export interface ImportResult {
@@ -445,12 +447,15 @@ export async function importConversationsFromSource(
totalBytes: source.size,
};
const report = () => options.onProgress?.({ ...progress });
+ const saved = (conversation: { threadId: string; thread?: { pairId?: string } }) =>
+ options.onSaved?.(conversation.thread?.pairId ?? conversation.threadId);
if (/\.csv$/i.test(source.name)) {
const text = await readAllText(source, CSV_MAX_BYTES, "CSV");
for (const conversation of parseImportText(text, source.name)) {
await writeConversation(conversation, projectId);
progress.imported++;
+ saved(conversation);
}
if (progress.imported > 0) notifyChatHistoryUpdated();
report();
@@ -497,6 +502,7 @@ export async function importConversationsFromSource(
const task = writeConversation(conversation, projectId)
.then(() => {
progress.imported++;
+ saved(conversation);
})
.catch(() => {
// Keep importing after one conversation fails to save.
@@ -524,6 +530,7 @@ export async function importConversationsFromSource(
try {
await writeConversation(conversation, projectId);
progress.imported++;
+ saved(conversation);
} catch {
progress.failed++;
}
diff --git a/studio/frontend/src/features/chat/utils/import-chats.ts b/studio/frontend/src/features/chat/utils/import-chats.ts
new file mode 100644
index 00000000000..67886960409
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/import-chats.ts
@@ -0,0 +1,105 @@
+// 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 { isTauri } from "@/lib/api-base";
+import { pickNativeChatImport } from "@/lib/native-files";
+import { toast } from "@/lib/toast";
+import { useSidebarOrganizationStore } from "../stores/sidebar-organization-store";
+import {
+ type ImportSource,
+ fileImportSource,
+ importConversationsFromSource,
+ nativeImportSource,
+} from "./chat-import";
+
+export const CHAT_IMPORT_ACCEPT = ".json,.jsonl,.ndjson,.csv";
+
+/** Where imported chats land: a project (null for none), optionally filed in a section. */
+export interface ChatImportTarget {
+ projectId: string | null;
+ sectionId?: string;
+ /** Named in the toast; "Recents" when there is no project or section. */
+ name?: string;
+}
+
+// One import at a time, whichever menu started it.
+let running = false;
+
+/** Imports a file, counting up in a toast; the chats are filed in the target's section. */
+export async function runChatImport(source: ImportSource, target: ChatImportTarget): Promise<void> {
+ running = true;
+ const toastId = toast.loading("Importing chats...");
+ try {
+ const threadIds: string[] = [];
+ const { imported, failed } = await importConversationsFromSource(
+ source,
+ target.projectId,
+ {
+ onSaved: (threadId) => threadIds.push(threadId),
+ onProgress: ({ imported: done, bytesRead, totalBytes }) => {
+ const percent = totalBytes
+ ? Math.min(100, Math.round((bytesRead / totalBytes) * 100))
+ : 0;
+ toast.loading(`Importing chats: ${done} so far (${percent}%)...`, { id: toastId });
+ },
+ },
+ );
+ if (imported === 0 && failed === 0) {
+ toast.info("No conversations found in file.", { id: toastId });
+ return;
+ }
+ if (imported === 0) {
+ // Nothing was created, so however the count is phrased this is a failure.
+ toast.error("Import failed.", {
+ id: toastId,
+ description: `${failed} conversation${failed === 1 ? "" : "s"} could not be saved.`,
+ });
+ return;
+ }
+ if (target.sectionId) {
+ useSidebarOrganizationStore.getState().setChatsSection([...new Set(threadIds)], target.sectionId);
+ }
+ const dest = target.name ?? "Recents";
+ toast.success(
+ failed > 0
+ ? `Imported ${imported} conversation${imported === 1 ? "" : "s"} to ${dest}; ${failed} could not be saved.`
+ : `Imported ${imported} conversation${imported === 1 ? "" : "s"} to ${dest}.`,
+ { id: toastId },
+ );
+ } catch (error) {
+ toast.error("Import failed.", {
+ id: toastId,
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ running = false;
+ }
+}
+
+export function isChatImportRunning(): boolean {
+ return running;
+}
+
+/** Asks for a file (the native picker in the desktop app), then imports it into the target. */
+export async function pickAndImportChats(target: ChatImportTarget): Promise<void> {
+ if (running) return;
+ if (!isTauri) {
+ const input = document.createElement("input");
+ input.type = "file";
+ input.accept = CHAT_IMPORT_ACCEPT;
+ input.onchange = () => {
+ const file = input.files?.[0];
+ if (file) void runChatImport(fileImportSource(file), target);
+ };
+ input.click();
+ return;
+ }
+ try {
+ const selected = await pickNativeChatImport();
+ if (selected) await runChatImport(nativeImportSource(selected), target);
+ } catch (error) {
+ toast.error("Import failed.", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
diff --git a/studio/frontend/src/features/library/chats/chats-items.tsx b/studio/frontend/src/features/library/chats/chats-items.tsx
new file mode 100644
index 00000000000..d5b4e53b8a8
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/chats-items.tsx
@@ -0,0 +1,1881 @@
+// 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 { Checkbox } from "@/components/ui/checkbox";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ BulkExportItems,
+ type ConvExportFormat,
+ type ConversationExportFormat,
+ chatExportOptions,
+ type ProjectRecord,
+ type SidebarCustomSection,
+ type SidebarItem,
+ OpenChatFolderItem,
+ OpenProjectFolderItem,
+ canForkChatRow,
+ pickAndImportChats,
+ useChatNavigationStore,
+ useChatRuntimeStore,
+ useForkInFlight,
+ compareModelDisplayName,
+} from "@/features/chat";
+import { type TranslationKey, useLocale, useT } from "@/i18n";
+import {
+ ChevronDownStandardIcon,
+ ChevronRightStandardIcon,
+} from "@/lib/chevron-icons";
+import { MessageCircleIcon, StarPointedIcon } from "@/lib/hugeicons-derived";
+import { cn } from "@/lib/utils";
+import {
+ Archive03Icon,
+ ArchiveRestoreIcon,
+ Cancel01Icon,
+ Delete02Icon,
+ Download01Icon,
+ Edit03Icon,
+ FolderAddIcon,
+ Folder02Icon,
+ FolderExportIcon,
+ LayerIcon,
+ MoreHorizontalIcon,
+ PencilEdit02Icon,
+ PinIcon,
+ PinOffIcon,
+ PlusSignIcon,
+ Settings02Icon,
+ Upload01Icon,
+ ViewIcon,
+ ViewOffSlashIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
+import {
+ ArrowDownIcon,
+ ArrowUpIcon,
+ Columns2Icon,
+ GitBranchIcon,
+} from "lucide-react";
+import { type ReactNode, createContext, useContext } from "react";
+import { formatActivityTime, formatCardTime } from "../format";
+import {
+ CARD_ICON_CLASS as FILE_CARD_ICON_CLASS,
+ CARD_SURFACE as FILE_CARD_SURFACE,
+} from "../components/library-cards";
+import { FILE_LIST_COLUMNS } from "../components/library-list";
+import { useLibrarySettingsStore } from "../settings-store";
+import { SortRadio } from "../components/library-toolbar";
+import { CARD_SHADOW, OVERLAY_CONTROL, RAISED_SURFACE } from "../surface";
+
+// No overflow-hidden, so a two-line name grows its row instead of clipping; the row stretches to match.
+const CARD = cn(
+ RAISED_SURFACE,
+ CARD_SHADOW,
+ "group/chat relative flex aspect-[8/7] cursor-pointer flex-col gap-2.5 self-stretch rounded-xl px-5 pb-3.5 pt-5 transition hover:bg-neutral-100 hover:shadow-none dark:hover:bg-accent/60",
+);
+import {
+ type ChatContents,
+ type ChatSort,
+ type ChatSortKey,
+ type DateBucket,
+ type DateField,
+ type ProjectStats,
+ type SectionStats,
+ chatTime,
+ projectTime,
+ sectionTime,
+} from "./model";
+
+const ICON = "size-icon";
+const MENU = "library-actions-menu";
+// Fits the window, and each group scrolls past ~7 rows so Sections stays reachable.
+const MOVE_TO_MENU =
+ "max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto";
+const MOVE_TO_LIST =
+ "no-scrollbar -my-0.5 max-h-[calc(260px*var(--ui-space-scale,1))] overflow-y-auto overscroll-contain";
+const MENU_LABEL = "px-3 pb-1 pt-2 font-normal text-muted-foreground";
+
+export type ChatExportChoice =
+ | { kind: "chat"; format: ConversationExportFormat }
+ | { kind: "bulk"; format: ConvExportFormat; merged: boolean };
+
+/** Move target; a null project or section id removes the chat from its current one. */
+export type ChatDestination =
+ | { kind: "project"; id: string | null }
+ | { kind: "section"; id: string | null }
+ | { kind: "newProject" }
+ | { kind: "newSection" };
+
+export interface ChatsActions {
+ projects: ProjectRecord[];
+ projectNames: ReadonlyMap<string, string>;
+ pinned: ReadonlySet<string>;
+ pinnedProjects: ReadonlySet<string>;
+ favorites: ReadonlySet<string>;
+ favoriteProjects: ReadonlySet<string>;
+ favoriteSections: ReadonlySet<string>;
+ /** Off in Favorites, where every entry is starred. */
+ favoriteMarks: boolean;
+ /** False in Favorites, where chats do not share the file selection. */
+ selectable: boolean;
+ models: ReadonlyMap<string, string[]>;
+ sections: readonly SidebarCustomSection[];
+ sectionOf: ReadonlyMap<string, string>;
+ projectSectionOf: ReadonlyMap<string, string>;
+ dateField: DateField;
+ chatContents: ReadonlyMap<string, ChatContents>;
+ selection: ReadonlySet<string>;
+ /** `range`: shift-click, from the last toggled row. */
+ toggleSelected: (id: string, range?: boolean) => void;
+ open: (chat: SidebarItem) => void;
+ rename: (chat: SidebarItem) => void;
+ togglePin: (chat: SidebarItem) => void;
+ setFavorite: (chats: SidebarItem[], favorite: boolean) => void;
+ toggleFavoriteProject: (projectId: string) => void;
+ toggleFavoriteSection: (sectionId: string) => void;
+ fork: (chat: SidebarItem) => void;
+ move: (chats: SidebarItem[], destination: ChatDestination) => void;
+ /** Moves a project into or out of a section; projects never nest. */
+ moveProject: (project: ProjectRecord, destination: ChatDestination) => void;
+ /** Narrows the list to one section. Omitted where there are no filters (Favorites). */
+ viewSection: (sectionId: string) => void;
+ newChatInSection: (sectionId: string) => void;
+ /** New project dialog; the project is filed in the section. */
+ newProjectInSection: (sectionId: string) => void;
+ renameSection: (section: SidebarCustomSection) => void;
+ removeSection: (section: SidebarCustomSection) => void;
+ exportSection: (section: SidebarCustomSection, choice: ChatExportChoice) => void;
+ archive: (chats: SidebarItem[]) => void;
+ unarchive: (chats: SidebarItem[]) => void;
+ exportChats: (chats: SidebarItem[], choice: ChatExportChoice) => void;
+ remove: (chats: SidebarItem[]) => void;
+ viewProject: (projectId: string) => void;
+ filterProject: (projectId: string) => void;
+ newChatIn: (projectId: string | null) => void;
+ editProject: (project: ProjectRecord) => void;
+ togglePinProject: (projectId: string) => void;
+ exportProject: (project: ProjectRecord, choice: ChatExportChoice) => void;
+ projectChatCounts: ReadonlyMap<string, number>;
+ sectionChatCounts: ReadonlyMap<string, number>;
+ deleteProject: (project: ProjectRecord) => void;
+}
+
+const ChatsActionsContext = createContext<ChatsActions | null>(null);
+export const ChatsActionsProvider = ChatsActionsContext.Provider;
+
+function useChatsActions(): ChatsActions {
+ const actions = useContext(ChatsActionsContext);
+ if (!actions) throw new Error("useChatsActions outside ChatsActionsProvider");
+ return actions;
+}
+
+function MenuItem({
+ icon,
+ label,
+ onSelect,
+ destructive,
+ disabled,
+}: {
+ icon: IconSvgElement;
+ label: string;
+ onSelect: () => void;
+ destructive?: boolean;
+ disabled?: boolean;
+}) {
+ return (
+ <DropdownMenuItem
+ onSelect={onSelect}
+ disabled={disabled}
+ variant={destructive ? "destructive" : "default"}
+ >
+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className={ICON} />
+ <span className="truncate">{label}</span>
+ </DropdownMenuItem>
+ );
+}
+
+export function ExportSubmenu({
+ onExport,
+ bulk = false,
+ disabled = false,
+}: {
+ onExport: (choice: ChatExportChoice) => void;
+ bulk?: boolean;
+ disabled?: boolean;
+}) {
+ const t = useT();
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="gap-2.5" disabled={disabled}>
+ <HugeiconsIcon
+ icon={Download01Icon}
+ strokeWidth={1.75}
+ className={ICON}
+ />
+ {t("common.export")}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className={cn(MENU, bulk ? "w-56" : "w-48")}>
+ {bulk ? (
+ <BulkExportItems onExport={(format, merged) => onExport({ kind: "bulk", format, merged })} />
+ ) : (
+ chatExportOptions().map(({ label, format }) => (
+ <DropdownMenuItem key={format} onSelect={() => onExport({ kind: "chat", format })}>
+ {label}
+ </DropdownMenuItem>
+ ))
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
+/** "Move to" menu, as in the sidebar. The current location is omitted, not greyed out. */
+export function MoveSubmenu({
+ project,
+ section,
+ onMove,
+ sectionsOnly = false,
+}: {
+ /** Shared project of the moved chats (null for none); undefined when they differ. */
+ project?: string | null;
+ section?: string | null;
+ onMove: (destination: ChatDestination) => void;
+ /** Sections only, for moving a project (projects never nest). */
+ sectionsOnly?: boolean;
+}) {
+ const t = useT();
+ const { projects, projectNames, sections } = useChatsActions();
+ const projectTargets = projects.filter((entry) => entry.id !== project);
+ const sectionTargets = sections.filter((entry) => entry.id !== section);
+ const leavingSection = section
+ ? sections.find((entry) => entry.id === section)
+ : undefined;
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="gap-2.5">
+ <HugeiconsIcon
+ icon={FolderExportIcon}
+ strokeWidth={1.75}
+ className={ICON}
+ />
+ {t("shell.sections.moveTo")}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className={cn(MENU, MOVE_TO_MENU, "w-56")}>
+ {!sectionsOnly && (
+ <>
+ <DropdownMenuLabel className={MENU_LABEL}>
+ {t("shell.navigation.projects")}
+ </DropdownMenuLabel>
+ <MenuItem
+ icon={PlusSignIcon}
+ label={t("library.chats.toolbar.newProject")}
+ onSelect={() => onMove({ kind: "newProject" })}
+ />
+ {projectTargets.length > 0 && (
+ <div className={MOVE_TO_LIST}>
+ {projectTargets.map((entry) => (
+ <MenuItem
+ key={entry.id}
+ icon={Folder02Icon}
+ label={entry.name}
+ onSelect={() => onMove({ kind: "project", id: entry.id })}
+ />
+ ))}
+ </div>
+ )}
+ {project !== null && (
+ <MenuItem
+ icon={Cancel01Icon}
+ label={
+ project && projectNames.has(project)
+ ? t("shell.sections.removeFrom", {
+ name: projectNames.get(project) ?? "",
+ })
+ : t("shell.sections.removeFromProject")
+ }
+ onSelect={() => onMove({ kind: "project", id: null })}
+ />
+ )}
+ <DropdownMenuSeparator className="mx-3" />
+ </>
+ )}
+ <DropdownMenuLabel className={MENU_LABEL}>
+ {t("shell.sections.sectionsHeading")}
+ </DropdownMenuLabel>
+ <MenuItem
+ icon={PlusSignIcon}
+ label={t("shell.sections.newSection")}
+ onSelect={() => onMove({ kind: "newSection" })}
+ />
+ {sectionTargets.length > 0 && (
+ <div className={MOVE_TO_LIST}>
+ {sectionTargets.map((entry) => (
+ <MenuItem
+ key={entry.id}
+ icon={LayerIcon}
+ label={entry.name}
+ onSelect={() => onMove({ kind: "section", id: entry.id })}
+ />
+ ))}
+ </div>
+ )}
+ {section !== null && (
+ <MenuItem
+ icon={Cancel01Icon}
+ label={
+ leavingSection
+ ? t("shell.sections.removeFrom", { name: leavingSection.name })
+ : t("shell.sections.removeFromSection")
+ }
+ onSelect={() => onMove({ kind: "section", id: null })}
+ />
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
+/** Off while generating or forking, as in the sidebar. Mounts only when the menu opens. */
+function ForkItem({ chat }: { chat: SidebarItem }) {
+ const t = useT();
+ const actions = useChatsActions();
+ const generating = useChatRuntimeStore((s) => Boolean(s.runningByThreadId[chat.id]));
+ const forking = useForkInFlight((s) => s.forking);
+ return (
+ <DropdownMenuItem
+ disabled={!canForkChatRow(chat) || generating || forking}
+ onSelect={() => actions.fork(chat)}
+ >
+ <GitBranchIcon strokeWidth={1.75} className={ICON} />
+ {t("library.chats.menu.fork")}
+ </DropdownMenuItem>
+ );
+}
+
+function MenuTrigger({ variant }: { variant: "row" | "card" }) {
+ const t = useT();
+ return (
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={t("library.menu.moreActions")}
+ className={cn(
+ "flex size-8 shrink-0 items-center justify-center rounded-full outline-none transition-opacity focus-visible:opacity-100 data-[state=open]:opacity-100",
+ variant === "row"
+ ? "text-muted-foreground opacity-0 hover:bg-accent hover:text-foreground group-hover/chat:opacity-100"
+ : cn(
+ OVERLAY_CONTROL,
+ "text-muted-foreground opacity-0 hover:text-foreground group-hover/chat:opacity-100 dark:text-white dark:hover:bg-neutral-600",
+ ),
+ )}
+ >
+ <HugeiconsIcon
+ icon={MoreHorizontalIcon}
+ strokeWidth={1.75}
+ className="size-5"
+ />
+ </button>
+ </DropdownMenuTrigger>
+ );
+}
+
+function FavoriteItem({
+ favorite,
+ onToggle,
+}: {
+ favorite: boolean;
+ onToggle: () => void;
+}) {
+ const t = useT();
+ return (
+ <DropdownMenuItem onSelect={onToggle}>
+ <HugeiconsIcon
+ icon={StarPointedIcon}
+ strokeWidth={1.75}
+ className={cn(ICON, favorite && "[&_path]:fill-current")}
+ />
+ {t(
+ favorite
+ ? "library.menu.removeFromFavorites"
+ : "library.menu.addToFavorites",
+ )}
+ </DropdownMenuItem>
+ );
+}
+
+function FavoriteMark() {
+ const t = useT();
+ if (!useChatsActions().favoriteMarks) return null;
+ return (
+ <HugeiconsIcon
+ icon={StarPointedIcon}
+ role="img"
+ aria-label={t("library.list.favorite")}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0 text-muted-foreground [&_path]:fill-current"
+ />
+ );
+}
+
+/** Stops clicks here (portals included) from opening the chat underneath. */
+function Isolate({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: only swallows bubbling clicks
+ <span className={className} onClick={(event) => event.stopPropagation()}>
+ {children}
+ </span>
+ );
+}
+
+function ChatMenu({
+ chat,
+ archived,
+ variant,
+}: {
+ chat: SidebarItem;
+ archived: boolean;
+ variant: "row" | "card";
+}) {
+ const t = useT();
+ const actions = useChatsActions();
+ const pinned = actions.pinned.has(chat.id);
+ const threadIds = chat.threadIds?.length ? chat.threadIds : [chat.id];
+ const unread = useChatNavigationStore((s) =>
+ threadIds.some((id) => s.unreadThreadIds.has(id)),
+ );
+ return (
+ <Isolate
+ className={cn(variant === "card" && "absolute end-2 top-2 z-10")}
+ >
+ <DropdownMenu>
+ <MenuTrigger variant={variant} />
+ {/* No Open chat: clicking the chat opens it. */}
+ <DropdownMenuContent align="end" className={cn(MENU, "w-52")}>
+ <MenuItem
+ icon={Edit03Icon}
+ label={t("common.rename")}
+ onSelect={() => actions.rename(chat)}
+ />
+ {!archived && (
+ <>
+ <MenuItem
+ icon={pinned ? PinOffIcon : PinIcon}
+ label={t(
+ pinned
+ ? "settings.data.library.unpin"
+ : "settings.data.library.pin",
+ )}
+ onSelect={() => actions.togglePin(chat)}
+ />
+ <FavoriteItem
+ favorite={actions.favorites.has(chat.id)}
+ onToggle={() =>
+ actions.setFavorite([chat], !actions.favorites.has(chat.id))
+ }
+ />
+ <MenuItem
+ icon={unread ? ViewIcon : ViewOffSlashIcon}
+ label={t(
+ unread
+ ? "shell.selection.markRead"
+ : "shell.selection.markUnread",
+ )}
+ onSelect={() => {
+ const store = useChatNavigationStore.getState();
+ if (unread) store.clearThreadsUnread(threadIds);
+ else
+ store.markThreadsUnread(
+ threadIds,
+ Object.fromEntries(threadIds.map((id) => [id, chat.id])),
+ );
+ }}
+ />
+ </>
+ )}
+ <DropdownMenuSeparator className="mx-3" />
+ {!archived && (
+ <>
+ {chat.type === "single" && <ForkItem chat={chat} />}
+ <MoveSubmenu
+ project={chat.projectId ?? null}
+ section={actions.sectionOf.get(chat.id) ?? null}
+ onMove={(destination) => actions.move([chat], destination)}
+ />
+ </>
+ )}
+ <ExportSubmenu onExport={(choice) => actions.exportChats([chat], choice)} />
+ {!archived && <OpenChatFolderItem item={chat} />}
+ <DropdownMenuSeparator className="mx-3" />
+ {archived ? (
+ <MenuItem
+ icon={ArchiveRestoreIcon}
+ label={t("settings.data.library.unarchive")}
+ onSelect={() => actions.unarchive([chat])}
+ />
+ ) : (
+ <MenuItem
+ icon={Archive03Icon}
+ label={t("settings.data.library.archive")}
+ onSelect={() => actions.archive([chat])}
+ />
+ )}
+ <MenuItem
+ icon={Delete02Icon}
+ label={t("common.delete")}
+ destructive
+ onSelect={() => actions.remove([chat])}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Isolate>
+ );
+}
+
+const TILE =
+ "flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-muted text-foreground/70 transition-colors group-hover/chat:bg-primary/10 group-hover/chat:text-primary";
+const TILE_ICON = "size-5";
+
+function ChatTile({
+ chat,
+ className,
+}: {
+ chat: SidebarItem;
+ className?: string;
+}) {
+ return (
+ <div className={cn(TILE, className)}>
+ {chat.type === "compare" ? (
+ <Columns2Icon strokeWidth={1.75} className={TILE_ICON} />
+ ) : chat.isFork ? (
+ <GitBranchIcon strokeWidth={1.75} className={TILE_ICON} />
+ ) : (
+ <HugeiconsIcon
+ icon={MessageCircleIcon}
+ strokeWidth={1.75}
+ className={TILE_ICON}
+ />
+ )}
+ </div>
+ );
+}
+
+function Badge({ children }: { children: ReactNode }) {
+ return (
+ <span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-ui-11 font-medium text-muted-foreground">
+ {children}
+ </span>
+ );
+}
+
+function PinMark() {
+ const t = useT();
+ return (
+ <HugeiconsIcon
+ icon={PinIcon}
+ role="img"
+ aria-label={t("library.chats.badges.pinned")}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ );
+}
+
+function ChatBadges({ chat, marksOnly = false }: { chat: SidebarItem; marksOnly?: boolean }) {
+ const t = useT();
+ const { pinned, favorites } = useChatsActions();
+ return (
+ <>
+ {favorites.has(chat.id) && <FavoriteMark />}
+ {pinned.has(chat.id) && <PinMark />}
+ {!marksOnly && chat.isFork && <Badge>{t("library.chats.badges.fork")}</Badge>}
+ {!marksOnly && chat.type === "compare" && (
+ <Badge>{t("library.chats.badges.compare")}</Badge>
+ )}
+ </>
+ );
+}
+
+function chatTitle(chat: SidebarItem, t: ReturnType<typeof useT>): string {
+ return chat.title?.trim() || t("settings.data.library.untitled");
+}
+
+function modelLabel(
+ chat: SidebarItem,
+ models: ReadonlyMap<string, string[]>,
+): string {
+ return (models.get(chat.id) ?? []).map(compareModelDisplayName).join(" · ");
+}
+
+// Plain text, not a pill: a pill inside a hovered row looked like a second row.
+const CHIP =
+ "inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-sm text-left outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring";
+
+function ChatLocation({
+ chat,
+ showProject,
+ showSection,
+ plain = false,
+}: {
+ chat: SidebarItem;
+ showProject: boolean;
+ showSection: boolean;
+ plain?: boolean;
+}) {
+ const t = useT();
+ const { projectNames, filterProject, sectionOf, sections, viewSection } =
+ useChatsActions();
+ const projectId = showProject ? chat.projectId : null;
+ const sectionId = showSection ? sectionOf.get(chat.id) : undefined;
+ const section = sectionId
+ ? sections.find((entry) => entry.id === sectionId)
+ : undefined;
+ if (!projectId && !section) return null;
+ const projectName = projectId
+ ? (projectNames.get(projectId) ??
+ t("settings.data.library.unavailableProject"))
+ : "";
+ if (plain) {
+ return (
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ if (projectId) filterProject(projectId);
+ else if (section) viewSection(section.id);
+ }}
+ // Icon first, so a location is not read as a count.
+ className={cn(CHIP, "max-w-full")}
+ >
+ <HugeiconsIcon
+ icon={projectId ? Folder02Icon : LayerIcon}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0"
+ />
+ <span className="truncate">{projectId ? projectName : section?.name}</span>
+ </button>
+ );
+ }
+ return (
+ <span className="flex min-w-0 items-center gap-3">
+ {projectId && (
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ filterProject(projectId);
+ }}
+ className={cn(CHIP, "shrink")}
+ >
+ <HugeiconsIcon
+ icon={Folder02Icon}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0"
+ />
+ <span className="truncate">{projectName}</span>
+ </button>
+ )}
+ {section && (
+ <SectionChip
+ section={section}
+ onView={viewSection}
+ // The project name truncates first so a short section name stays whole.
+ className={projectId ? "max-w-[55%] shrink-0" : "shrink"}
+ />
+ )}
+ </span>
+ );
+}
+
+function SectionChip({
+ section,
+ onView,
+ className,
+}: {
+ section: SidebarCustomSection;
+ onView: (sectionId: string) => void;
+ className?: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ onView(section.id);
+ }}
+ className={cn(CHIP, className)}
+ >
+ <HugeiconsIcon
+ icon={LayerIcon}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0"
+ />
+ <span className="truncate">{section.name}</span>
+ </button>
+ );
+}
+
+/** "own": under its own header; "files": among files; object: among chats (All). */
+export type CollectionRowLayout = "own" | "files" | { showLocation: boolean };
+
+function FileColumns({ modified }: { modified: number }) {
+ const locale = useLocale();
+ return (
+ <>
+ <span className={cn(FILE_LIST_COLUMNS.modified, FILE_LIST_COLUMNS.cell)}>
+ {modified ? formatCardTime(modified, locale) : ""}
+ </span>
+ <span className={cn(FILE_LIST_COLUMNS.size, FILE_LIST_COLUMNS.cell)} />
+ </>
+ );
+}
+
+function CollectionCount({ children }: { children: ReactNode }) {
+ return (
+ <span className="shrink-0 text-ui-13 text-muted-foreground">
+ {children}
+ </span>
+ );
+}
+
+/** Time inside a date group, which already names the day: so no relative "6 hr. ago". */
+function groupedTime(
+ ts: number,
+ bucket: DateBucket["kind"],
+ locale: string,
+): string {
+ const date = new Date(ts);
+ if (bucket === "today" || bucket === "yesterday") {
+ return date.toLocaleTimeString(locale, {
+ hour: "numeric",
+ minute: "2-digit",
+ });
+ }
+ if (bucket === "week") {
+ return date.toLocaleDateString(locale, { weekday: "long" });
+ }
+ return date.toLocaleDateString(locale, {
+ month: "short",
+ day: "numeric",
+ year:
+ date.getFullYear() === new Date().getFullYear() ? undefined : "numeric",
+ });
+}
+
+export interface RowTimes {
+ bucket?: DateBucket["kind"];
+}
+
+function formatDate(
+ ts: number,
+ field: DateField,
+ times: RowTimes,
+ locale: ReturnType<typeof useLocale>,
+ t: ReturnType<typeof useT>,
+): string {
+ if (!ts) return "";
+ if (times.bucket) return groupedTime(ts, times.bucket, locale);
+ return field === "created"
+ ? formatCardTime(ts, locale)
+ : formatActivityTime(ts, locale, t);
+}
+
+function countLabel(
+ count: number,
+ one: TranslationKey,
+ many: TranslationKey,
+ t: ReturnType<typeof useT>,
+): string {
+ return count === 1 ? t(one) : t(many, { count });
+}
+
+function chatContentsLabel(
+ contents: ChatContents | undefined,
+ t: ReturnType<typeof useT>,
+): string {
+ if (!contents) return "";
+ return countLabel(
+ contents.messages,
+ "library.chats.list.oneMessage",
+ "library.chats.list.messageCount",
+ t,
+ );
+}
+
+const DATE_LABELS: Record<DateField, TranslationKey> = {
+ created: "library.chats.list.created",
+ updated: "library.chats.list.lastActive",
+ modified: "library.chats.list.lastModified",
+};
+
+export function DateHeader({
+ fields,
+ field,
+ sortKey,
+ desc,
+ onFieldChange,
+ onToggle,
+}: {
+ fields: readonly DateField[];
+ field: DateField;
+ sortKey: string;
+ desc: boolean;
+ onFieldChange: (field: DateField) => void;
+ onToggle: () => void;
+}) {
+ const t = useT();
+ const active = sortKey === field;
+ const Arrow = active && !desc ? ArrowUpIcon : ArrowDownIcon;
+ const label = t(DATE_LABELS[field]);
+ return (
+ <span className={cn(DATE_COLUMN, "items-center gap-1 @xl:flex")}>
+ {fields.length > 1 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className={cn(
+ "group/date flex items-center gap-1 outline-none transition-colors hover:text-foreground focus-visible:text-foreground data-[state=open]:text-foreground",
+ active && "text-foreground",
+ )}
+ >
+ {label}
+ <HugeiconsIcon
+ icon={ChevronDownStandardIcon}
+ strokeWidth={2}
+ className="size-3 opacity-0 transition-opacity group-hover/date:opacity-100 group-focus-visible/date:opacity-100 group-data-[state=open]/date:opacity-100"
+ />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className={cn(MENU, "w-44")}
+ // Focus returning to the title after a pick left a ring around it.
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ >
+ {fields.map((option) => (
+ <SortRadio
+ key={option}
+ label={t(DATE_LABELS[option])}
+ checked={option === field}
+ onSelect={() => onFieldChange(option)}
+ />
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <span className={cn(active && "text-foreground")}>{label}</span>
+ )}
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-label={t(
+ active && desc
+ ? "library.toolbar.sortAscending"
+ : "library.toolbar.sortDescending",
+ )}
+ className={cn(
+ "flex size-5 items-center justify-center rounded-full outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
+ active ? "text-foreground" : "opacity-50",
+ )}
+ >
+ <Arrow className="size-3.5" strokeWidth={2} />
+ </button>
+ </span>
+ );
+}
+
+export interface DateColumn {
+ fields: readonly DateField[];
+ sortKey: string;
+ desc: boolean;
+ onFieldChange: (field: DateField) => void;
+ onToggle: () => void;
+}
+
+function SelectBox({
+ chat,
+ visible,
+ className,
+}: {
+ chat: SidebarItem;
+ visible: boolean;
+ className?: string;
+}) {
+ const t = useT();
+ const { selection, toggleSelected, selectable } = useChatsActions();
+ if (!selectable) return null;
+ return (
+ <Isolate className={className}>
+ <Checkbox
+ checked={selection.has(chat.id)}
+ // onClick to read shift.
+ onClick={(event) => {
+ event.preventDefault();
+ toggleSelected(chat.id, event.shiftKey);
+ }}
+ aria-label={t("settings.data.library.selectItem", {
+ title: chatTitle(chat, t),
+ })}
+ className={cn(
+ "rounded-full border-neutral-300 opacity-0 transition-opacity focus-visible:opacity-100 group-hover/chat:opacity-100 dark:border-input",
+ visible && "opacity-100",
+ )}
+ />
+ </Isolate>
+ );
+}
+
+const ROW_INSET = "pl-4 pr-6";
+const CELL = "truncate text-ui-13 text-muted-foreground";
+// Columns follow the list's width, not the window's; the date column hides last.
+const DATE_COLUMN = "hidden w-32 shrink-0 @xl:block";
+const CONTENTS_COLUMN = "hidden w-36 shrink-0 @3xl:block";
+const LOCATION_COLUMN = "hidden w-40 shrink-0 @4xl:block";
+
+function SortHeader({
+ column,
+ label,
+ sort,
+ onSortChange,
+ className,
+}: {
+ column: ChatSortKey;
+ label: string;
+ sort: ChatSort;
+ onSortChange: (key: ChatSortKey) => void;
+ className?: string;
+}) {
+ const t = useT();
+ const active = sort.key === column;
+ const Arrow = sort.desc ? ArrowDownIcon : ArrowUpIcon;
+ // aria-sort needs a columnheader, so the state goes in the label.
+ const direction = t(sort.desc ? "library.toolbar.sortDescending" : "library.toolbar.sortAscending");
+ return (
+ <button
+ type="button"
+ onClick={() => onSortChange(column)}
+ aria-pressed={active}
+ aria-label={active ? `${label}, ${direction}` : undefined}
+ className={cn(
+ "flex items-center gap-1 text-left transition-colors hover:text-foreground",
+ active && "text-foreground",
+ className,
+ )}
+ >
+ {label}
+ {active && <Arrow className="size-3.5" strokeWidth={2} />}
+ </button>
+ );
+}
+
+export function ChatListHeader({
+ sort,
+ onSortChange,
+ date,
+ showLocation,
+ allSelected,
+ selecting,
+ onToggleAll,
+}: {
+ sort: ChatSort;
+ onSortChange: (key: ChatSortKey) => void;
+ date: DateColumn;
+ showLocation: boolean;
+ allSelected: boolean;
+ selecting: boolean;
+ onToggleAll: () => void;
+}) {
+ const t = useT();
+ const { selectable, dateField } = useChatsActions();
+ return (
+ <div className="pb-2">
+ <div
+ className={cn(
+ "group/chat relative flex items-center gap-4 text-ui-13 text-muted-foreground",
+ ROW_INSET,
+ )}
+ >
+ {selectable && (
+ <div className="absolute end-full top-1/2 me-3 flex -translate-y-1/2">
+ <Checkbox
+ checked={allSelected}
+ onCheckedChange={onToggleAll}
+ aria-label={t("settings.data.library.selectAll")}
+ className={cn(
+ "rounded-full border-neutral-300 opacity-0 transition-opacity focus-visible:opacity-100 group-hover/chat:opacity-100 dark:border-input",
+ selecting && "opacity-100",
+ )}
+ />
+ </div>
+ )}
+ <span className="min-w-0 flex-1">
+ <SortHeader
+ column="name"
+ label={t("library.list.name")}
+ sort={sort}
+ onSortChange={onSortChange}
+ />
+ </span>
+ {showLocation && (
+ <span className={LOCATION_COLUMN}>
+ {t("library.chats.list.location")}
+ </span>
+ )}
+ <span className={CONTENTS_COLUMN}>
+ {t("library.chats.list.contents")}
+ </span>
+ <DateHeader {...date} field={dateField} />
+ <span className="w-8 shrink-0" />
+ </div>
+ </div>
+ );
+}
+
+export function ChatRow({
+ chat,
+ archived,
+ showProject,
+ showSection,
+ locationColumn = showProject || showSection,
+ fileColumns = false,
+ times = {},
+}: {
+ chat: SidebarItem;
+ archived: boolean;
+ /** Off inside a project or when grouped by it (sections likewise). */
+ showProject: boolean;
+ showSection: boolean;
+ locationColumn?: boolean;
+ fileColumns?: boolean;
+ times?: RowTimes;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const actions = useChatsActions();
+ const selected = actions.selection.has(chat.id);
+ const model = modelLabel(chat, actions.models);
+ return (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the title button is the keyboard target
+ <div
+ onClick={(event) =>
+ actions.selection.size > 0
+ ? actions.toggleSelected(chat.id, event.shiftKey)
+ : actions.open(chat)
+ }
+ className={cn(
+ "group/chat relative flex cursor-pointer items-center gap-4 rounded-[14px] transition-colors hover:bg-muted dark:hover:bg-muted/60",
+ ROW_INSET,
+ selected && "bg-muted dark:bg-muted/60",
+ )}
+ >
+ <SelectBox
+ chat={chat}
+ visible={actions.selection.size > 0}
+ className="absolute end-full top-1/2 me-3 flex -translate-y-1/2"
+ />
+ <div className="flex min-w-0 flex-1 items-center gap-4 py-2">
+ <ChatTile chat={chat} />
+ <div className="flex min-w-0 flex-col">
+ <span className="flex min-w-0 items-center gap-2">
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ if (actions.selection.size > 0) actions.toggleSelected(chat.id, event.shiftKey);
+ else actions.open(chat);
+ }}
+ className="truncate rounded text-left text-ui-14 text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {chatTitle(chat, t)}
+ </button>
+ <ChatBadges chat={chat} />
+ </span>
+ {model && (
+ <span className="truncate text-ui-12 text-muted-foreground">
+ {model}
+ </span>
+ )}
+ </div>
+ </div>
+ {fileColumns ? (
+ <FileColumns modified={chatTime(chat, "modified")} />
+ ) : (
+ <>
+ {locationColumn && (
+ <span className={cn(LOCATION_COLUMN, CELL)}>
+ <ChatLocation
+ chat={chat}
+ showProject={showProject}
+ showSection={showSection}
+ />
+ </span>
+ )}
+ <span className={cn(CONTENTS_COLUMN, CELL)}>
+ {chatContentsLabel(actions.chatContents.get(chat.id), t)}
+ </span>
+ <span className={cn(DATE_COLUMN, CELL)}>
+ {formatDate(
+ chatTime(chat, actions.dateField),
+ actions.dateField,
+ times,
+ locale,
+ t,
+ )}
+ </span>
+ </>
+ )}
+ <ChatMenu chat={chat} archived={archived} variant="row" />
+ </div>
+ );
+}
+
+export function ChatCard({
+ chat,
+ archived,
+ showProject,
+ showSection,
+ times = {},
+}: {
+ chat: SidebarItem;
+ archived: boolean;
+ showProject: boolean;
+ showSection: boolean;
+ times?: RowTimes;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const actions = useChatsActions();
+ const selected = actions.selection.has(chat.id);
+ const selecting = actions.selection.size > 0;
+ const location =
+ (showProject && chat.projectId) ||
+ (showSection && actions.sections.some((entry) => entry.id === actions.sectionOf.get(chat.id))) ? (
+ <ChatLocation chat={chat} showProject={showProject} showSection={showSection} plain />
+ ) : undefined;
+ return (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the title button is the keyboard target
+ <div
+ onClick={(event) =>
+ selecting ? actions.toggleSelected(chat.id, event.shiftKey) : actions.open(chat)
+ }
+ className={cn(CARD, selected && "ring-2 ring-foreground")}
+ >
+ <div className="flex items-center gap-2">
+ <ChatTile chat={chat} />
+ <ChatBadges chat={chat} marksOnly />
+ </div>
+ <ChatMenu chat={chat} archived={archived} variant="card" />
+ <SelectBox chat={chat} visible={selecting} className="absolute bottom-3.5 end-4 flex" />
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ if (selecting) actions.toggleSelected(chat.id, event.shiftKey);
+ else actions.open(chat);
+ }}
+ className={CARD_TITLE}
+ >
+ {/* Clamp an inner span: buttons ignore line-clamp. */}
+ <span className="line-clamp-2">{chatTitle(chat, t)}</span>
+ </button>
+ <CardFooter
+ meta={location}
+ date={formatDate(chatTime(chat, actions.dateField), actions.dateField, times, locale, t)}
+ className={selecting ? "pe-7" : undefined}
+ />
+ </div>
+ );
+}
+
+function CardFooter({ meta, date, className }: { meta?: ReactNode; date: string; className?: string }) {
+ return (
+ <div
+ className={cn(
+ "mt-auto flex min-w-0 flex-col items-start gap-1 text-ui-12 text-muted-foreground",
+ className,
+ )}
+ >
+ {meta && <span className="w-full min-w-0 truncate">{meta}</span>}
+ <span className="truncate">{date}</span>
+ </div>
+ );
+}
+
+const CARD_TITLE =
+ "block w-full rounded text-left font-medium text-ui-14 leading-snug text-foreground outline-none [overflow-wrap:anywhere] focus-visible:ring-2 focus-visible:ring-ring";
+
+/** Group name and count in words; a bare number beside "Today" read as part of the name. */
+export function GroupHeading({
+ children,
+ count,
+ countLabel,
+}: {
+ children: ReactNode;
+ count: number;
+ countLabel?: string;
+}) {
+ const t = useT();
+ return (
+ <h3 className="mb-1 mt-7 flex items-baseline gap-2 pl-4 font-sans text-ui-13 first:mt-3">
+ <span className="font-medium text-foreground">{children}</span>
+ <span className="text-ui-12 text-muted-foreground">
+ {countLabel ?? chatCount(count, t)}
+ </span>
+ </h3>
+ );
+}
+
+function CollectionTile({ icon }: { icon: IconSvgElement }) {
+ return (
+ <span className={TILE}>
+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className={TILE_ICON} />
+ </span>
+ );
+}
+
+export function CollectionHeader({
+ icon,
+ name,
+ parent,
+ onParent,
+ marks,
+ description,
+ actions,
+}: {
+ icon: IconSvgElement;
+ name: string;
+ parent: string;
+ onParent: () => void;
+ marks?: ReactNode;
+ description?: string;
+ actions: ReactNode;
+}) {
+ const t = useT();
+ return (
+ <div className="flex flex-col gap-4">
+ <nav
+ aria-label={t("library.breadcrumb")}
+ className="flex items-center gap-1.5 text-ui-14"
+ >
+ <button
+ type="button"
+ onClick={onParent}
+ className="rounded text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {parent}
+ </button>
+ <HugeiconsIcon
+ icon={ChevronRightStandardIcon}
+ strokeWidth={2}
+ className="size-3.5 shrink-0 text-muted-foreground rtl:rotate-180"
+ />
+ <span aria-current="page" className="truncate text-foreground">
+ {name}
+ </span>
+ </nav>
+ <div className="flex items-center gap-4">
+ <span className="flex size-13 shrink-0 items-center justify-center rounded-[18px] bg-muted text-foreground/80">
+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-6.5" />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <h2 className="flex min-w-0 items-center gap-2.5 text-ui-30 font-medium leading-tight text-foreground">
+ <span className="truncate">{name}</span>
+ {marks}
+ </h2>
+ {description && (
+ <p className="line-clamp-2 max-w-3xl text-ui-14 text-muted-foreground">
+ {description}
+ </p>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-2">{actions}</div>
+ </div>
+ </div>
+ );
+}
+
+export const HEADER_MORE_BUTTON =
+ "inline-flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:bg-muted data-[state=open]:text-foreground";
+
+function ProjectMenu({
+ project,
+ variant,
+}: {
+ project: ProjectRecord;
+ variant: "row" | "card";
+}) {
+ const t = useT();
+ const actions = useChatsActions();
+ const pinned = actions.pinnedProjects.has(project.id);
+ return (
+ <Isolate
+ className={cn(variant === "card" && "absolute end-2 top-2 z-10")}
+ >
+ <DropdownMenu>
+ <MenuTrigger variant={variant} />
+ <DropdownMenuContent align="end" className={cn(MENU, "w-52")}>
+ <MenuItem
+ icon={PencilEdit02Icon}
+ label={t("library.chats.menu.newChatInProject")}
+ onSelect={() => actions.newChatIn(project.id)}
+ />
+ <OpenProjectFolderItem projectId={project.id} />
+ <DropdownMenuSeparator className="mx-3" />
+ <MenuItem
+ icon={Settings02Icon}
+ label={t("library.chats.menu.edit")}
+ onSelect={() => actions.editProject(project)}
+ />
+ <MenuItem
+ icon={pinned ? PinOffIcon : PinIcon}
+ label={t(
+ pinned
+ ? "settings.data.library.unpin"
+ : "settings.data.library.pin",
+ )}
+ onSelect={() => actions.togglePinProject(project.id)}
+ />
+ <FavoriteItem
+ favorite={actions.favoriteProjects.has(project.id)}
+ onToggle={() => actions.toggleFavoriteProject(project.id)}
+ />
+ <DropdownMenuSeparator className="mx-3" />
+ <MoveSubmenu
+ sectionsOnly
+ section={actions.projectSectionOf.get(project.id) ?? null}
+ onMove={(destination) => actions.moveProject(project, destination)}
+ />
+ <ExportSubmenu
+ bulk
+ disabled={!actions.projectChatCounts.get(project.id)}
+ onExport={(choice) => actions.exportProject(project, choice)}
+ />
+ <MenuItem
+ icon={Upload01Icon}
+ label={t("settings.chat.importChats")}
+ onSelect={() => void pickAndImportChats({ projectId: project.id, name: project.name })}
+ />
+ <DropdownMenuSeparator className="mx-3" />
+ <MenuItem
+ icon={Delete02Icon}
+ label={t("library.chats.menu.deleteProject")}
+ destructive
+ onSelect={() => actions.deleteProject(project)}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Isolate>
+ );
+}
+
+function chatCount(count: number, t: ReturnType<typeof useT>): string {
+ return count === 1
+ ? t("settings.data.library.oneChat")
+ : t("settings.data.library.chatCount", { count });
+}
+
+export function ProjectCard({
+ project,
+ stats,
+}: {
+ project: ProjectRecord;
+ stats?: ProjectStats;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const actions = useChatsActions();
+ const pinned = actions.pinnedProjects.has(project.id);
+ return (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the name button is the keyboard target
+ <div
+ onClick={() => actions.viewProject(project.id)}
+ className={CARD}
+ >
+ <div className="flex items-center gap-2">
+ <CollectionTile icon={Folder02Icon} />
+ {actions.favoriteProjects.has(project.id) && <FavoriteMark />}
+ {pinned && <PinMark />}
+ </div>
+ <ProjectMenu project={project} variant="card" />
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ actions.viewProject(project.id);
+ }}
+ className={CARD_TITLE}
+ >
+ <span className="line-clamp-2">{project.name}</span>
+ </button>
+ <CardFooter
+ meta={chatCount(stats?.chats ?? 0, t)}
+ date={formatDate(projectTime(project, stats, actions.dateField), actions.dateField, {}, locale, t)}
+ />
+ </div>
+ );
+}
+
+export function ProjectRow({
+ project,
+ stats,
+ layout = "own",
+}: {
+ project: ProjectRecord;
+ stats?: ProjectStats;
+ layout?: CollectionRowLayout;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const actions = useChatsActions();
+ const pinned = actions.pinnedProjects.has(project.id);
+ const sectionId = actions.projectSectionOf.get(project.id);
+ const section = sectionId
+ ? actions.sections.find((entry) => entry.id === sectionId)
+ : undefined;
+ return (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the name button is the keyboard target
+ <div
+ onClick={() => actions.viewProject(project.id)}
+ className={cn(
+ "group/chat relative flex cursor-pointer items-center gap-4 rounded-[14px] transition-colors hover:bg-muted dark:hover:bg-muted/60",
+ ROW_INSET,
+ )}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-4 py-2">
+ <CollectionTile icon={Folder02Icon} />
+ <div className="flex min-w-0 flex-col">
+ <span className="flex min-w-0 items-center gap-2">
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ actions.viewProject(project.id);
+ }}
+ className="truncate rounded text-left text-ui-14 text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {project.name}
+ </button>
+ {actions.favoriteProjects.has(project.id) && <FavoriteMark />}
+ {pinned && (
+ <HugeiconsIcon
+ icon={PinIcon}
+ role="img"
+ aria-label={t("library.chats.badges.pinned")}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ )}
+ {layout === "files" && (
+ <CollectionCount>
+ {chatCount(stats?.chats ?? 0, t)}
+ </CollectionCount>
+ )}
+ </span>
+ {project.instructions?.trim() && (
+ <span className="truncate text-ui-12 text-muted-foreground">
+ {project.instructions.trim()}
+ </span>
+ )}
+ </div>
+ </div>
+ {layout !== "files" && layout !== "own" && layout.showLocation && (
+ <span className={cn(LOCATION_COLUMN, CELL)}>
+ {section && (
+ <SectionChip
+ section={section}
+ onView={actions.viewSection}
+ className="shrink"
+ />
+ )}
+ </span>
+ )}
+ {layout === "files" ? (
+ <FileColumns modified={projectTime(project, stats, "modified")} />
+ ) : (
+ <>
+ <span className={cn(CONTENTS_COLUMN, CELL)}>
+ {chatCount(stats?.chats ?? 0, t)}
+ </span>
+ <span className={cn(DATE_COLUMN, CELL)}>
+ {formatDate(
+ projectTime(project, stats, actions.dateField),
+ actions.dateField,
+ {},
+ locale,
+ t,
+ )}
+ </span>
+ </>
+ )}
+ <ProjectMenu project={project} variant="row" />
+ </div>
+ );
+}
+
+export function ProjectListHeader({ date }: { date: DateColumn }) {
+ const t = useT();
+ const { dateField } = useChatsActions();
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-4 pb-2 text-ui-13 text-muted-foreground",
+ ROW_INSET,
+ )}
+ >
+ <span className="min-w-0 flex-1">{t("library.list.name")}</span>
+ <span className={CONTENTS_COLUMN}>
+ {t("library.chats.list.contents")}
+ </span>
+ <DateHeader {...date} field={dateField} />
+ <span className="w-8 shrink-0" />
+ </div>
+ );
+}
+
+function SectionMenu({
+ section,
+ variant,
+}: {
+ section: SidebarCustomSection;
+ variant: "row" | "card";
+}) {
+ return (
+ <Isolate
+ className={cn(variant === "card" && "absolute end-2 top-2 z-10")}
+ >
+ <DropdownMenu>
+ <MenuTrigger variant={variant} />
+ <DropdownMenuContent align="end" className={cn(MENU, "w-52")}>
+ <SectionMenuItems section={section} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Isolate>
+ );
+}
+
+export function SectionMenuItems({
+ section,
+ onPage = false,
+}: {
+ section: SidebarCustomSection;
+ onPage?: boolean;
+}) {
+ const t = useT();
+ const actions = useChatsActions();
+ return (
+ <>
+ {!onPage && (
+ <>
+ <MenuItem
+ icon={PencilEdit02Icon}
+ label={t("library.chats.toolbar.newChat")}
+ onSelect={() => actions.newChatInSection(section.id)}
+ />
+ <MenuItem
+ icon={FolderAddIcon}
+ label={t("library.chats.toolbar.newProject")}
+ onSelect={() => actions.newProjectInSection(section.id)}
+ />
+ </>
+ )}
+ <MenuItem
+ icon={Settings02Icon}
+ label={t("shell.sections.edit")}
+ onSelect={() => actions.renameSection(section)}
+ />
+ <FavoriteItem
+ favorite={actions.favoriteSections.has(section.id)}
+ onToggle={() => actions.toggleFavoriteSection(section.id)}
+ />
+ <ExportSubmenu
+ bulk
+ disabled={!actions.sectionChatCounts.get(section.id)}
+ onExport={(choice) => actions.exportSection(section, choice)}
+ />
+ {/* Into no project, filed in the section. */}
+ <MenuItem
+ icon={Upload01Icon}
+ label={t("settings.chat.importChats")}
+ onSelect={() =>
+ void pickAndImportChats({ projectId: null, sectionId: section.id, name: section.name })
+ }
+ />
+ <DropdownMenuSeparator className="mx-3" />
+ <MenuItem
+ icon={Delete02Icon}
+ label={t("shell.sections.remove")}
+ destructive
+ onSelect={() => actions.removeSection(section)}
+ />
+ </>
+ );
+}
+
+function sectionCountLabel(
+ stats: SectionStats | undefined,
+ t: ReturnType<typeof useT>,
+): string {
+ const chats = chatCount(stats?.chats ?? 0, t);
+ const projects = stats?.projects ?? 0;
+ if (projects === 0) return chats;
+ return `${countLabel(projects, "library.chats.project.oneProject", "library.chats.project.projectCount", t)} · ${chats}`;
+}
+
+export function SectionCard({
+ section,
+ stats,
+}: {
+ section: SidebarCustomSection;
+ stats?: SectionStats;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const actions = useChatsActions();
+ return (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the name button is the keyboard target
+ <div
+ onClick={() => actions.viewSection(section.id)}
+ className={CARD}
+ >
+ <div className="flex items-center gap-2">
+ <CollectionTile icon={LayerIcon} />
+ {actions.favoriteSections.has(section.id) && <FavoriteMark />}
+ </div>
+ <SectionMenu section={section} variant="card" />
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ actions.viewSection(section.id);
+ }}
+ className={CARD_TITLE}
+ >
+ <span className="line-clamp-2">{section.name}</span>
+ </button>
+ <CardFooter
+ meta={sectionCountLabel(stats, t)}
+ date={formatDate(sectionTime(section, stats, actions.dateField), actions.dateField, {}, locale, t)}
+ />
+ </div>
+ );
+}
+
+export function SectionRow({
+ section,
+ stats,
+ layout = "own",
+}: {
+ section: SidebarCustomSection;
+ stats?: SectionStats;
+ layout?: CollectionRowLayout;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const actions = useChatsActions();
+ return (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the name button is the keyboard target
+ <div
+ onClick={() => actions.viewSection(section.id)}
+ className={cn(
+ "group/chat relative flex cursor-pointer items-center gap-4 rounded-[14px] transition-colors hover:bg-muted dark:hover:bg-muted/60",
+ ROW_INSET,
+ )}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-4 py-2">
+ <CollectionTile icon={LayerIcon} />
+ <span className="flex min-w-0 items-center gap-2">
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ actions.viewSection(section.id);
+ }}
+ className="truncate rounded text-left text-ui-14 text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {section.name}
+ </button>
+ {actions.favoriteSections.has(section.id) && <FavoriteMark />}
+ {layout === "files" && (
+ <CollectionCount>{sectionCountLabel(stats, t)}</CollectionCount>
+ )}
+ </span>
+ </div>
+ {layout === "files" ? (
+ <FileColumns modified={sectionTime(section, stats, "modified")} />
+ ) : (
+ <>
+ {layout !== "own" && layout.showLocation && (
+ <span className={LOCATION_COLUMN} />
+ )}
+ <span className={cn(CONTENTS_COLUMN, CELL)}>
+ {sectionCountLabel(stats, t)}
+ </span>
+ <span className={cn(DATE_COLUMN, CELL)}>
+ {formatDate(
+ sectionTime(section, stats, actions.dateField),
+ actions.dateField,
+ {},
+ locale,
+ t,
+ )}
+ </span>
+ </>
+ )}
+ <SectionMenu section={section} variant="row" />
+ </div>
+ );
+}
+
+export function SectionListHeader({ date }: { date: DateColumn }) {
+ const t = useT();
+ const { dateField } = useChatsActions();
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-4 pb-2 text-ui-13 text-muted-foreground",
+ ROW_INSET,
+ )}
+ >
+ <span className="min-w-0 flex-1">{t("library.list.name")}</span>
+ <span className={CONTENTS_COLUMN}>
+ {t("library.chats.list.contents")}
+ </span>
+ <DateHeader {...date} field={dateField} />
+ <span className="w-8 shrink-0" />
+ </div>
+ );
+}
+
+function FavoriteTile({
+ title,
+ icon,
+ time,
+ onOpen,
+ menu,
+}: {
+ title: string;
+ icon: ReactNode;
+ time: number;
+ onOpen: () => void;
+ menu: ReactNode;
+}) {
+ const locale = useLocale();
+ const showTime = useLibrarySettingsStore((s) => s.showCardDates);
+ return (
+ <div className="group/library-card group/chat relative">
+ <button
+ type="button"
+ aria-label={title}
+ onClick={onOpen}
+ className={cn(
+ "block w-full overflow-hidden rounded-xl text-left outline-none transition focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
+ FILE_CARD_SURFACE,
+ )}
+ >
+ <div className="flex aspect-square flex-col px-5 pb-3.5 pt-5">
+ <p className="line-clamp-2 break-words pr-7 font-medium text-ui-14 leading-snug text-foreground">
+ {title}
+ </p>
+ <div className="flex flex-1 items-center justify-center text-foreground">
+ {icon}
+ </div>
+ <p className="truncate pr-6 text-ui-13 text-muted-foreground">
+ {showTime && time ? formatCardTime(time, locale) : ""}
+ </p>
+ </div>
+ </button>
+ {menu}
+ </div>
+ );
+}
+
+export function FavoriteChatTile({ chat }: { chat: SidebarItem }) {
+ const t = useT();
+ const actions = useChatsActions();
+ const icon =
+ chat.type === "compare" ? (
+ <Columns2Icon strokeWidth={1.5} className={FILE_CARD_ICON_CLASS} />
+ ) : chat.isFork ? (
+ <GitBranchIcon strokeWidth={1.5} className={FILE_CARD_ICON_CLASS} />
+ ) : (
+ <HugeiconsIcon
+ icon={MessageCircleIcon}
+ strokeWidth={1.5}
+ className={FILE_CARD_ICON_CLASS}
+ />
+ );
+ return (
+ <FavoriteTile
+ title={chatTitle(chat, t)}
+ icon={icon}
+ time={chatTime(chat, "modified")}
+ onOpen={() => actions.open(chat)}
+ menu={<ChatMenu chat={chat} archived={false} variant="card" />}
+ />
+ );
+}
+
+export function FavoriteProjectTile({
+ project,
+ stats,
+}: {
+ project: ProjectRecord;
+ stats?: ProjectStats;
+}) {
+ const actions = useChatsActions();
+ return (
+ <FavoriteTile
+ title={project.name}
+ icon={
+ <HugeiconsIcon
+ icon={Folder02Icon}
+ strokeWidth={1.5}
+ className={FILE_CARD_ICON_CLASS}
+ />
+ }
+ time={projectTime(project, stats, "modified")}
+ onOpen={() => actions.viewProject(project.id)}
+ menu={<ProjectMenu project={project} variant="card" />}
+ />
+ );
+}
+
+export function FavoriteSectionTile({
+ section,
+ stats,
+}: {
+ section: SidebarCustomSection;
+ stats?: SectionStats;
+}) {
+ const actions = useChatsActions();
+ return (
+ <FavoriteTile
+ title={section.name}
+ icon={
+ <HugeiconsIcon
+ icon={LayerIcon}
+ strokeWidth={1.5}
+ className={FILE_CARD_ICON_CLASS}
+ />
+ }
+ time={sectionTime(section, stats, "modified")}
+ onOpen={() => actions.viewSection(section.id)}
+ menu={<SectionMenu section={section} variant="card" />}
+ />
+ );
+}
diff --git a/studio/frontend/src/features/library/chats/chats-library.tsx b/studio/frontend/src/features/library/chats/chats-library.tsx
new file mode 100644
index 00000000000..b7649494035
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/chats-library.tsx
@@ -0,0 +1,1767 @@
+// 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 {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import {
+ exportConversationByFormat,
+ DeleteChatFilesSwitch,
+ EditProjectDialog,
+ NewProjectDialog,
+ type ProjectRecord,
+ SectionNameDialog,
+ type SidebarCustomSection,
+ type SidebarItem,
+ archiveChatItems,
+ clearNewChatDraft,
+ compareModelDisplayName,
+ deleteChatItems,
+ deleteChatProject,
+ exportThreads,
+ forkChatRow,
+ moveChatItemToProject,
+ normalizeSectionName,
+ notifyChatHistoryUpdated,
+ rangeBetween,
+ removeCustomSectionWithUndo,
+ renameChatItem,
+ showForkCreatedToast,
+ unarchiveChatItem,
+ useChatPreferencesStore,
+ useChatProjects,
+ useChatRuntimeStore,
+ useChatSidebarItems,
+ useForkInFlight,
+ usePinnedChatsStore,
+ usePinnedProjectsStore,
+ useSidebarOrganizationStore,
+ useFileProjectInSection,
+} from "@/features/chat";
+import { type TranslationKey, useLocale, useT } from "@/i18n";
+import { MessageCircleIcon, StarPointedIcon } from "@/lib/hugeicons-derived";
+import { isDownloadCancelled } from "@/lib/native-files";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import {
+ Archive03Icon,
+ ArchiveRestoreIcon,
+ Cancel01Icon,
+ CheckmarkSquare02Icon,
+ Delete02Icon,
+ Folder02Icon,
+ FolderAddIcon,
+ LayerIcon,
+ MoreHorizontalIcon,
+ PencilEdit02Icon,
+ PinIcon,
+ PinOffIcon,
+ PlusSignIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
+import { useNavigate } from "@tanstack/react-router";
+import {
+ type ReactNode,
+ type SetStateAction,
+ useCallback,
+ useDeferredValue,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { NameDialog } from "../components/library-dialogs";
+import { type HeaderTab, LibraryHeader } from "../components/library-header";
+import type { LibrarySearch } from "../search";
+import { CardGrid } from "../components/library-cards";
+import { LIST_ROW_GAP } from "../components/library-list";
+import type { LibraryView } from "../settings-store";
+import {
+ ChatCard,
+ ChatListHeader,
+ type ChatDestination,
+ type ChatExportChoice,
+ ChatRow,
+ type ChatsActions,
+ ChatsActionsProvider,
+ CollectionHeader,
+ type DateColumn,
+ ExportSubmenu,
+ FavoriteChatTile,
+ FavoriteProjectTile,
+ FavoriteSectionTile,
+ HEADER_MORE_BUTTON,
+ GroupHeading,
+ MoveSubmenu,
+ ProjectCard,
+ ProjectListHeader,
+ ProjectRow,
+ SectionCard,
+ SectionListHeader,
+ SectionMenuItems,
+ SectionRow,
+} from "./chats-items";
+import { ChatsToolbar, type SortChoice, SortMenu } from "./chats-toolbar";
+import {
+ type ChatFilters,
+ type ChatGroup,
+ type ChatGroupBy,
+ type ChatSortKey,
+ type ChatsSection,
+ type DateBucket,
+ DATE_FIELDS,
+ type DateField,
+ EMPTY_CHAT_FILTERS,
+ NO_PROJECT,
+ NO_SECTION,
+ type ProjectSortKey,
+ chatFiltersActive,
+ filterChats,
+ groupChats,
+ matchesTerms,
+ mixEntries,
+ modelFacets,
+ modelsByChat,
+ CHATS_SECTIONS,
+ type SectionSortKey,
+ projectStats,
+ searchTerms,
+ sectionStats,
+ sortChats,
+ sortProjects,
+ sortSections,
+} from "./model";
+import { useChatContents } from "./contents";
+import { useChatFavoritesStore } from "./favorites-store";
+import { useChatsPrefsStore } from "./prefs-store";
+
+const PAGE_SIZE = 150;
+
+const BAR_PILL =
+ "flex h-9 items-center gap-2 rounded-full px-4 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50";
+const BAR_ROUND =
+ "flex size-9 items-center justify-center rounded-full outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring";
+const BAR_OUTLINE =
+ "border border-border transition-colors hover:bg-sidebar-accent dark:border-transparent dark:bg-accent/60 dark:hover:bg-accent";
+
+const CHAT_SORTS: SortChoice<ChatSortKey>[] = [
+ { value: "updated", label: "library.chats.list.lastActive" },
+ { value: "modified", label: "library.chats.list.lastModified" },
+ { value: "created", label: "library.chats.list.created" },
+ { value: "name", label: "library.list.name" },
+];
+
+const PROJECT_SORTS: SortChoice<ProjectSortKey>[] = [
+ { value: "updated", label: "library.chats.list.lastActive" },
+ { value: "modified", label: "library.chats.list.lastModified" },
+ { value: "created", label: "library.chats.list.created" },
+ { value: "name", label: "library.list.name" },
+ { value: "chats", label: "library.chats.toolbar.sortChats" },
+];
+
+const BUCKET_LABELS: Record<"today" | "yesterday" | "week" | "month", TranslationKey> = {
+ today: "library.chats.groups.today",
+ yesterday: "library.chats.groups.yesterday",
+ week: "library.chats.groups.week",
+ month: "library.chats.groups.month",
+};
+
+const SECTION_LABELS: Record<ChatsSection, TranslationKey> = {
+ all: "library.tabs.all",
+ chats: "library.chats.sections.chats",
+ projects: "library.chats.sections.projects",
+ sections: "shell.sections.sectionsHeading",
+ archived: "library.chats.sections.archived",
+};
+
+const SECTION_ICONS: Partial<Record<ChatsSection, IconSvgElement>> = {
+ chats: MessageCircleIcon,
+ projects: Folder02Icon,
+ sections: LayerIcon,
+ archived: Archive03Icon,
+};
+
+const SECTION_SORTS: SortChoice<SectionSortKey>[] = [
+ { value: "updated", label: "library.chats.list.lastActive" },
+ { value: "modified", label: "library.chats.list.lastModified" },
+ { value: "created", label: "library.chats.list.created" },
+ { value: "name", label: "library.list.name" },
+ { value: "chats", label: "library.chats.toolbar.sortChats" },
+];
+
+const NO_CHATS: SidebarItem[] = [];
+
+function isDateField(key: string): key is DateField {
+ return (DATE_FIELDS as readonly string[]).includes(key);
+}
+
+type HeaderTabs = { items: HeaderTab[]; active: string; onChange: (key: string) => void };
+
+type PendingDelete =
+ | { kind: "chats"; chats: SidebarItem[]; deleteFiles: boolean }
+ | { kind: "project"; project: ProjectRecord; deleteFiles: boolean };
+
+function EmptyState({
+ icon,
+ title,
+ description,
+ action,
+}: {
+ icon: IconSvgElement;
+ title: string;
+ description: string;
+ action?: ReactNode;
+}) {
+ return (
+ <div className="mx-auto mt-16 flex max-w-md flex-col items-center gap-2 text-center">
+ <HugeiconsIcon icon={icon} strokeWidth={1.5} className="mb-2 size-7" />
+ <h2 className="font-medium font-sans text-ui-21 text-foreground">{title}</h2>
+ <p className="text-ui-15 text-muted-foreground">{description}</p>
+ {action && <div className="mt-3">{action}</div>}
+ </div>
+ );
+}
+
+function LoadingRows() {
+ return (
+ <div className="mt-6 flex flex-col gap-2">
+ {Array.from({ length: 8 }, (_, index) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: fixed placeholders with no identity
+ <Skeleton key={index} className="h-12 rounded-[14px]" />
+ ))}
+ </div>
+ );
+}
+
+function errorDescription(err: unknown): string | undefined {
+ return err instanceof Error ? err.message : undefined;
+}
+
+export interface FavoriteChatEntries {
+ rows: ReactNode[];
+ cards: { key: string; node: ReactNode }[];
+}
+
+/** The Chats tab. `embedded`: starred items only, for Favorites, with no header or filters. */
+export function ChatsLibrary({
+ search,
+ title,
+ tabs,
+ embedded,
+}: {
+ search: LibrarySearch;
+ title?: ReactNode;
+ tabs?: HeaderTabs;
+ embedded?: {
+ query: string;
+ view: LibraryView;
+ render: (entries: FavoriteChatEntries) => ReactNode;
+ };
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const navigate = useNavigate();
+
+ const section: ChatsSection = search.chatSection ? "chats" : (search.chatView ?? "all");
+ // Open section page; `section` is the pill. Projects have no page here: they open in Chat.
+ const openSectionId = search.chatSection ?? null;
+
+ // Metadata only, like the sidebar. The default reads every message.
+ const {
+ items,
+ archivedItems,
+ loaded,
+ } = useChatSidebarItems({ requireMessages: false });
+ const { projects, hasLoaded: projectsLoaded } = useChatProjects();
+ const pinnedIds = usePinnedChatsStore((s) => s.pinnedIds);
+ const togglePinned = usePinnedChatsStore((s) => s.togglePin);
+ const setPinned = usePinnedChatsStore((s) => s.setPinned);
+ const pinnedProjectIds = usePinnedProjectsStore((s) => s.pinnedIds);
+ const togglePinProject = usePinnedProjectsStore((s) => s.togglePin);
+ const unpinProject = usePinnedProjectsStore((s) => s.unpin);
+ const alwaysDeleteChatFiles = useChatPreferencesStore((s) => s.alwaysDeleteChatFiles);
+ const confirmDeleteChats = useChatPreferencesStore((s) => s.confirmDeleteChats);
+ // Shared with the sidebar: filing a chat here files it there.
+ const sections = useSidebarOrganizationStore((s) => s.customSections);
+ const sectionByChatId = useSidebarOrganizationStore((s) => s.sectionByChatId);
+ const setChatsSection = useSidebarOrganizationStore((s) => s.setChatsSection);
+ const createCustomSection = useSidebarOrganizationStore((s) => s.createCustomSection);
+ const setSectionHidden = useSidebarOrganizationStore((s) => s.setSectionHidden);
+ const sectionByProjectId = useSidebarOrganizationStore((s) => s.sectionByProjectId);
+ const renameCustomSection = useSidebarOrganizationStore((s) => s.renameCustomSection);
+ const setPendingNewChatSection = useSidebarOrganizationStore((s) => s.setPendingNewChatSection);
+ const prefs = useChatsPrefsStore();
+ const favoriteIds = useChatFavoritesStore((s) => s.chatIds);
+ const favoriteProjectIds = useChatFavoritesStore((s) => s.projectIds);
+ const setFavoriteChats = useChatFavoritesStore((s) => s.setChats);
+ const setFavoriteProjects = useChatFavoritesStore((s) => s.setProjects);
+ const favoriteSectionIds = useChatFavoritesStore((s) => s.sectionIds);
+ const setFavoriteSections = useChatFavoritesStore((s) => s.setSections);
+ const view = embedded ? embedded.view : prefs.view;
+
+ const pinned = useMemo(() => new Set(pinnedIds), [pinnedIds]);
+ const pinnedProjects = useMemo(() => new Set(pinnedProjectIds), [pinnedProjectIds]);
+ const favorites = useMemo(() => new Set(favoriteIds), [favoriteIds]);
+ const favoriteProjects = useMemo(() => new Set(favoriteProjectIds), [favoriteProjectIds]);
+ const favoriteSections = useMemo(() => new Set(favoriteSectionIds), [favoriteSectionIds]);
+ const projectNames = useMemo(() => new Map(projects.map((p) => [p.id, p.name])), [projects]);
+ const sectionNames = useMemo(() => new Map(sections.map((s) => [s.id, s.name])), [sections]);
+ const currentSection = openSectionId
+ ? (sections.find((entry) => entry.id === openSectionId) ?? null)
+ : null;
+ const sectionOf = useMemo(
+ () =>
+ new Map(Object.entries(sectionByChatId).filter(([, sectionId]) => sectionNames.has(sectionId))),
+ [sectionByChatId, sectionNames],
+ );
+
+ const models = useMemo(
+ () => modelsByChat([...items, ...archivedItems]),
+ [items, archivedItems],
+ );
+
+ const [ownQuery, setQuery] = useState("");
+ const query = embedded ? embedded.query : ownQuery;
+ const listQuery = useDeferredValue(query);
+ const [filters, setFilters] = useState<ChatFilters>(EMPTY_CHAT_FILTERS);
+ const [selection, setSelectionState] = useState<Set<string>>(new Set());
+ const selectionAnchor = useRef<string | null>(null);
+ // Clearing drops the shift-click anchor too, or the next range reaches a row no longer selected.
+ const setSelection = useCallback((next: SetStateAction<Set<string>>) => {
+ if (typeof next !== "function" && next.size === 0) selectionAnchor.current = null;
+ setSelectionState(next);
+ }, []);
+ const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
+ const [renaming, setRenaming] = useState<SidebarItem | null>(null);
+ const [editing, setEditing] = useState<ProjectRecord | null>(null);
+ const [creatingProject, setCreatingProject] = useState(false);
+ // Section a project made from its menu is filed in.
+ const [newProjectSection, setNewProjectSection] = useState<string | null>(null);
+ const newProjectInSection = (sectionId: string) => {
+ setNewProjectSection(sectionId);
+ setCreatingProject(true);
+ };
+ const [pendingDelete, setPendingDelete] = useState<PendingDelete | null>(null);
+ const [movingIntoNew, setMovingIntoNew] = useState<{
+ kind: "project" | "section";
+ chats: SidebarItem[];
+ project?: ProjectRecord;
+ } | null>(null);
+ // Just-created section: its store update lands a render after the page opens.
+ const [awaitedSection, setAwaitedSection] = useState<string | null>(null);
+ const [renamingSection, setRenamingSection] = useState<SidebarCustomSection | null>(null);
+ if (awaitedSection !== null && sections.some((entry) => entry.id === awaitedSection)) {
+ setAwaitedSection(null);
+ }
+
+ const scope = `${section}:${openSectionId ?? ""}`;
+ const [shownScope, setShownScope] = useState(scope);
+ if (shownScope !== scope) {
+ setShownScope(scope);
+ setQuery("");
+ setFilters(EMPTY_CHAT_FILTERS);
+ setSelection(new Set());
+ setVisibleCount(PAGE_SIZE);
+ }
+
+ const go = (next: Partial<LibrarySearch>, replace = false) =>
+ void navigate({
+ to: "/library",
+ search: { show: "chats", ...next },
+ replace,
+ });
+
+ const sectionGone = openSectionId !== null && currentSection === null && openSectionId !== awaitedSection;
+ useEffect(() => {
+ if (sectionGone) void navigate({ to: "/library", search: { show: "chats", chatView: "sections" }, replace: true });
+ }, [sectionGone, navigate]);
+
+ const archived = section === "archived";
+ const pool = useMemo(
+ () =>
+ embedded
+ ? items.filter((chat) => favorites.has(chat.id))
+ : archived
+ ? archivedItems
+ : items,
+ [embedded, items, archivedItems, archived, favorites],
+ );
+ const scoped = useMemo(
+ () =>
+ openSectionId ? pool.filter((chat) => sectionOf.get(chat.id) === openSectionId) : pool,
+ [pool, openSectionId, sectionOf],
+ );
+ const context = useMemo(
+ () => ({ pinned, favorites, projectNames, models, sectionOf, sectionNames }),
+ [pinned, favorites, projectNames, models, sectionOf, sectionNames],
+ );
+ const groupOptions: ChatGroupBy[] = [
+ "none",
+ "date",
+ "project",
+ ...(sections.length > 0 && !openSectionId ? (["section"] as const) : []),
+ ];
+ const ungrouped = embedded || section === "all";
+ const groupBy = !ungrouped && groupOptions.includes(prefs.groupBy) ? prefs.groupBy : "none";
+ // Pinned chats get their own group; floating them within groups broke time order.
+ const pinnedFirst = prefs.pinnedFirst && !archived && !embedded;
+ const visibleChats = useMemo(() => {
+ const matched = filterChats(scoped, listQuery, filters, context);
+ return sortChats(matched, prefs.sort, pinned, pinnedFirst, locale);
+ }, [scoped, listQuery, filters, context, prefs.sort, pinnedFirst, pinned, locale]);
+ const stats = useMemo(
+ () => projectStats(projects, items, archivedItems),
+ [projects, items, archivedItems],
+ );
+ const { projectChatCounts, sectionChatCounts } = useMemo(() => {
+ const byProject = new Map<string, number>();
+ const bySection = new Map<string, number>();
+ for (const chat of items) {
+ if (chat.projectId) byProject.set(chat.projectId, (byProject.get(chat.projectId) ?? 0) + 1);
+ const sectionId = sectionOf.get(chat.id);
+ if (sectionId) bySection.set(sectionId, (bySection.get(sectionId) ?? 0) + 1);
+ }
+ return { projectChatCounts: byProject, sectionChatCounts: bySection };
+ }, [items, sectionOf]);
+ const visibleProjects = useMemo(() => {
+ const terms = searchTerms(query);
+ const matched = projects.filter(
+ (p) => (!embedded || favoriteProjects.has(p.id)) && matchesTerms(terms, p.name, p.instructions),
+ );
+ return sortProjects(matched, prefs.projectSort, stats, pinnedProjects, locale);
+ }, [projects, query, prefs.projectSort, stats, pinnedProjects, locale, embedded, favoriteProjects]);
+
+ const projectIdSet = useMemo(() => new Set(projects.map((p) => p.id)), [projects]);
+ const projectSectionOf = useMemo(
+ () => new Map(Object.entries(sectionByProjectId)),
+ [sectionByProjectId],
+ );
+ const sectionStatsById = useMemo(
+ () => sectionStats(sections, items, sectionOf, projectSectionOf, projectIdSet),
+ [sections, items, sectionOf, projectSectionOf, projectIdSet],
+ );
+ const visibleSections = useMemo(() => {
+ const terms = searchTerms(query);
+ const matched = sections.filter(
+ (entry) => (!embedded || favoriteSections.has(entry.id)) && matchesTerms(terms, entry.name),
+ );
+ return sortSections(matched, prefs.sectionSort, sectionStatsById, locale);
+ }, [sections, query, prefs.sectionSort, sectionStatsById, locale, embedded, favoriteSections]);
+ const mixed = section === "all" && !embedded;
+ const allEntries = useMemo(
+ () =>
+ mixed
+ ? mixEntries(visibleChats, visibleProjects, visibleSections, {
+ sort: prefs.sort,
+ projectStats: stats,
+ sectionStats: sectionStatsById,
+ pinned,
+ pinnedProjects,
+ pinnedFirst,
+ locale,
+ })
+ : null,
+ [
+ mixed,
+ visibleChats,
+ visibleProjects,
+ visibleSections,
+ prefs.sort,
+ stats,
+ sectionStatsById,
+ pinned,
+ pinnedProjects,
+ pinnedFirst,
+ locale,
+ ],
+ );
+ const shownEntries = useMemo(
+ () => allEntries?.slice(0, visibleCount) ?? null,
+ [allEntries, visibleCount],
+ );
+ const shownChats = useMemo(
+ () =>
+ shownEntries
+ ? shownEntries.flatMap((entry) => (entry.kind === "chat" ? [entry.item] : []))
+ : visibleChats.slice(0, visibleCount),
+ [shownEntries, visibleChats, visibleCount],
+ );
+ const groupTime = prefs.dateField;
+ const groupingOptions = useMemo(
+ () => ({
+ time: groupTime,
+ oldestFirst: prefs.sort.key !== "name" && !prefs.sort.desc,
+ pinned: pinnedFirst && !ungrouped ? pinned : undefined,
+ sectionOf,
+ }),
+ [groupTime, prefs.sort, pinnedFirst, ungrouped, pinned, sectionOf],
+ );
+ const groups = useMemo(
+ () => groupChats(shownChats, groupBy, groupingOptions),
+ [shownChats, groupBy, groupingOptions],
+ );
+ const shownOrder = useMemo(
+ () => groups.flatMap((group) => group.items.map((chat) => chat.id)),
+ [groups],
+ );
+ // Headings count all matches, not just the loaded page.
+ const groupTotals = useMemo(
+ () =>
+ groupBy === "none"
+ ? new Map<string, number>()
+ : new Map(
+ groupChats(visibleChats, groupBy, groupingOptions).map((g) => [g.key, g.items.length]),
+ ),
+ [visibleChats, groupBy, groupingOptions],
+ );
+
+ const sectionProjects = useMemo(() => {
+ if (!openSectionId) return [];
+ const terms = searchTerms(query);
+ return sortProjects(
+ projects.filter(
+ (p) => projectSectionOf.get(p.id) === openSectionId && matchesTerms(terms, p.name, p.instructions),
+ ),
+ prefs.projectSort,
+ stats,
+ pinnedProjects,
+ locale,
+ );
+ }, [openSectionId, projects, projectSectionOf, query, prefs.projectSort, stats, pinnedProjects, locale]);
+
+ const allModelFacets = useMemo(() => modelFacets(scoped, models), [scoped, models]);
+ const facets = useMemo(
+ () => ({
+ showProjects: true,
+ projects: projects.map((p) => ({ id: p.id, name: p.name })),
+ sections: openSectionId ? [] : sections.map((s) => ({ id: s.id, name: s.name })),
+ models: allModelFacets
+ .filter((facet, index) => index < 20 || filters.models.has(facet.model))
+ .map(({ model, count }) => ({ model, count, label: compareModelDisplayName(model) })),
+ }),
+ [openSectionId, projects, sections, allModelFacets, filters.models],
+ );
+
+ // Drop ticked filters whose project, section or model is gone: they can't be unticked.
+ if (loaded && projectsLoaded) {
+ const liveProjects = [...filters.projects].filter((id) => id === NO_PROJECT || projectNames.has(id));
+ const liveSections = [...filters.sections].filter(
+ (id) => sections.length > 0 && (id === NO_SECTION || sectionNames.has(id)),
+ );
+ const liveModels = [...filters.models].filter((model) =>
+ allModelFacets.some((f) => f.model === model),
+ );
+ if (
+ liveProjects.length !== filters.projects.size ||
+ liveSections.length !== filters.sections.size ||
+ liveModels.length !== filters.models.size
+ ) {
+ setFilters({
+ ...filters,
+ projects: new Set(liveProjects),
+ sections: new Set(liveSections),
+ models: new Set(liveModels),
+ });
+ }
+ }
+
+ const visibleIds = useMemo(() => new Set(shownChats.map((chat) => chat.id)), [shownChats]);
+ if ([...selection].some((id) => !visibleIds.has(id))) {
+ setSelection(new Set([...selection].filter((id) => visibleIds.has(id))));
+ }
+ const selectedChats = shownChats.filter((chat) => selection.has(chat.id));
+
+ useEffect(() => {
+ if (selection.size === 0) return;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || event.defaultPrevented) return;
+ if (event.target instanceof HTMLElement && event.target.closest("input, textarea")) return;
+ if (document.querySelector('[role="menu"], [role="dialog"], [role="alertdialog"]')) return;
+ setSelection(new Set());
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [selection.size]);
+
+ const activeChatId = () => useChatRuntimeStore.getState().activeThreadId ?? undefined;
+
+ const openProject = (id: string) => {
+ const runtime = useChatRuntimeStore.getState();
+ runtime.setActiveThreadId(null);
+ runtime.setActiveProjectId(id);
+ void navigate({ to: "/chat", search: { project: id } });
+ };
+
+ const openChat = (chat: SidebarItem) => {
+ const runtime = useChatRuntimeStore.getState();
+ runtime.setActiveProjectId(chat.projectId ?? null);
+ const project = chat.projectId ? { project: chat.projectId } : {};
+ if (chat.type === "compare") {
+ runtime.setActiveThreadId(null);
+ void navigate({ to: "/chat", search: { compare: chat.id, ...project } });
+ } else {
+ runtime.setActiveThreadId(chat.id);
+ void navigate({ to: "/chat", search: { thread: chat.id, ...project } });
+ }
+ };
+
+ /** Files the new chat on its first send; the sidebar watches for the mark set here. */
+ const newChatInSection = (sectionId: string) => {
+ const nonce = crypto.randomUUID();
+ clearNewChatDraft();
+ const runtime = useChatRuntimeStore.getState();
+ runtime.setActiveThreadId(null);
+ runtime.setActiveProjectId(null);
+ runtime.setIncognito(false);
+ setPendingNewChatSection(null);
+ void navigate({ to: "/chat", search: { new: nonce } }).then(() =>
+ setPendingNewChatSection({ sectionId, nonce }),
+ );
+ };
+
+ const newChatIn = (id: string | null) => {
+ clearNewChatDraft();
+ const runtime = useChatRuntimeStore.getState();
+ runtime.setActiveThreadId(null);
+ runtime.setActiveProjectId(id);
+ runtime.setIncognito(false);
+ void navigate({
+ to: "/chat",
+ search: id ? { project: id } : { new: crypto.randomUUID() },
+ });
+ };
+
+ async function run(action: () => Promise<unknown>, success: string | null, failure: string) {
+ try {
+ await action();
+ if (success) toast.success(success);
+ } catch (err) {
+ toast.error(failure, { description: errorDescription(err) });
+ }
+ }
+
+ const moveToProject = (chats: SidebarItem[], destination: string | null, name?: string) => {
+ setSelection(new Set());
+ void run(
+ async () => {
+ await Promise.all(chats.map((chat) => moveChatItemToProject(chat, destination)));
+ notifyChatHistoryUpdated();
+ },
+ destination
+ ? t("settings.data.library.movedChatsToProject", {
+ count: chats.length,
+ project:
+ name ?? projectNames.get(destination) ?? t("settings.data.library.unavailableProject"),
+ })
+ : t("settings.data.library.movedChatsToRecents", { count: chats.length }),
+ t("settings.data.library.moveFailed"),
+ );
+ };
+
+ /** null unfiles. Filing unpins (Pinned would still show it) and unhides the section. */
+ const fileInSection = (chats: SidebarItem[], sectionId: string | null, name?: string) => {
+ const ids = chats.map((chat) => chat.id);
+ setSelection(new Set());
+ setChatsSection(ids, sectionId);
+ if (sectionId) {
+ setPinned(
+ ids.filter((id) => pinned.has(id)),
+ false,
+ );
+ setSectionHidden(sectionId, false);
+ }
+ toast.success(
+ sectionId
+ ? t("settings.data.library.movedChatsToProject", {
+ count: chats.length,
+ project: name ?? sectionNames.get(sectionId) ?? "",
+ })
+ : t("library.chats.toast.removedFromSection", { count: chats.length }),
+ );
+ };
+
+ const moveChats = (chats: SidebarItem[], destination: ChatDestination) => {
+ if (destination.kind === "project") moveToProject(chats, destination.id);
+ else if (destination.kind === "section") fileInSection(chats, destination.id);
+ else if (destination.kind === "newProject") {
+ setMovingIntoNew({ kind: "project", chats });
+ setCreatingProject(true);
+ } else setMovingIntoNew({ kind: "section", chats });
+ };
+
+ const fileProjectInSection = useFileProjectInSection();
+
+ const moveProject = (project: ProjectRecord, destination: ChatDestination) => {
+ if (destination.kind === "section") fileProjectInSection(project, destination.id);
+ else if (destination.kind === "newSection") setMovingIntoNew({ kind: "section", chats: [], project });
+ };
+
+ async function eachChat(
+ chats: SidebarItem[],
+ act: (chat: SidebarItem) => Promise<unknown>,
+ success: (count: number) => string,
+ failure: string,
+ ) {
+ let done = 0;
+ let error: unknown;
+ for (const chat of chats) {
+ try {
+ await act(chat);
+ done += 1;
+ } catch (err) {
+ error = err;
+ }
+ }
+ if (done > 0) toast.success(success(done));
+ if (done < chats.length) toast.error(failure, { description: errorDescription(error) });
+ }
+
+ const archiveChats = (chats: SidebarItem[]) => {
+ setSelection(new Set());
+ void eachChat(
+ chats,
+ (chat) => archiveChatItems([chat], activeChatId(), () => {}),
+ (count) =>
+ count === 1
+ ? t("settings.data.archivedOneChat")
+ : t("settings.data.archivedChatCount", { count }),
+ t("settings.data.failedToArchiveChats"),
+ );
+ };
+
+ const unarchiveChats = (chats: SidebarItem[]) => {
+ setSelection(new Set());
+ void eachChat(
+ chats,
+ unarchiveChatItem,
+ (count) => t("settings.data.library.restoredChats", { count }),
+ t("settings.data.library.restoreFailed"),
+ );
+ };
+
+ const setChatsPinned = (chats: SidebarItem[], next: boolean) => {
+ setPinned(
+ chats.map((chat) => chat.id),
+ next,
+ );
+ setSelection(new Set());
+ toast.success(
+ t(next ? "settings.data.library.pinnedChats" : "settings.data.library.unpinnedChats", {
+ count: chats.length,
+ }),
+ );
+ };
+
+ const exportChats = async (chats: SidebarItem[], choice: ChatExportChoice, name?: string) => {
+ const threadIds = [...new Set(chats.flatMap((chat) => chat.threadIds ?? [chat.id]))];
+ try {
+ if (choice.kind === "chat") {
+ for (const id of threadIds) await exportConversationByFormat(id, choice.format);
+ } else {
+ const stem = name ?? (chats.length === 1 ? (chats[0]?.title ?? "chats") : "chats");
+ await exportThreads(threadIds, choice.format, choice.merged, stem);
+ }
+ } catch (err) {
+ if (!isDownloadCancelled(err)) toast.error(t("settings.data.exportFailed"));
+ }
+ };
+
+ const forkChat = async (chat: SidebarItem) => {
+ const inFlight = useForkInFlight.getState();
+ if (inFlight.forking) return;
+ inFlight.setForking(true);
+ try {
+ const result = await forkChatRow(chat);
+ notifyChatHistoryUpdated();
+ showForkCreatedToast(result.containerSnapshotWarning);
+ } catch (err) {
+ if ((err as { unslothForkRefused?: boolean } | null)?.unslothForkRefused) {
+ toast.info(err instanceof Error ? err.message : t("library.chats.toast.forkFailed"));
+ } else {
+ toast.error(t("library.chats.toast.forkFailed"), { description: errorDescription(err) });
+ }
+ } finally {
+ inFlight.setForking(false);
+ }
+ };
+
+ async function confirmDelete(target: PendingDelete) {
+ setPendingDelete(null);
+ setSelection(new Set());
+ if (target.kind === "chats") {
+ await run(
+ async () => {
+ await deleteChatItems(target.chats, activeChatId(), () => {}, {
+ deleteFiles: target.deleteFiles,
+ });
+ // After the delete: a failed one restores the chats with their marks.
+ const ids = target.chats.map((chat) => chat.id);
+ setFavoriteChats(ids, false);
+ setPinned(ids, false);
+ },
+ t("settings.data.library.deletedChats", { count: target.chats.length }),
+ t("settings.data.library.deleteFailed"),
+ );
+ return;
+ }
+ const { project } = target;
+ await run(
+ async () => {
+ await deleteChatProject(project.id, { deleteFiles: target.deleteFiles });
+ unpinProject(project.id);
+ setFavoriteProjects([project.id], false);
+ if (useChatRuntimeStore.getState().activeProjectId === project.id) {
+ useChatRuntimeStore.getState().setActiveProjectId(null);
+ }
+ notifyChatHistoryUpdated();
+ },
+ t("library.chats.toast.projectDeleted", { name: project.name }),
+ t("library.chats.toast.projectDeleteFailed"),
+ );
+ }
+
+ const listed = view === "list" && !embedded;
+ const chatContents = useChatContents(listed ? shownChats : NO_CHATS);
+
+ const dateColumn = <K extends string>(
+ sort: { key: K; desc: boolean },
+ setSort: (next: { key: DateField; desc: boolean }) => void,
+ fields: readonly DateField[],
+ field: DateField,
+ ): DateColumn => ({
+ fields,
+ sortKey: sort.key,
+ desc: sort.desc,
+ onFieldChange: (next) => {
+ prefs.set({ dateField: next });
+ setSort({ key: next, desc: isDateField(sort.key) ? sort.desc : true });
+ },
+ onToggle: () =>
+ setSort({ key: field, desc: sort.key === field ? !sort.desc : true }),
+ });
+ const chatDateColumn = dateColumn(
+ prefs.sort,
+ (sort) => prefs.set({ sort }),
+ DATE_FIELDS,
+ prefs.dateField,
+ );
+ const projectDateColumn = dateColumn(
+ prefs.projectSort,
+ (projectSort) => prefs.set({ projectSort }),
+ DATE_FIELDS,
+ prefs.dateField,
+ );
+ const sectionDateColumn = dateColumn(
+ prefs.sectionSort,
+ (sectionSort) => prefs.set({ sectionSort }),
+ DATE_FIELDS,
+ prefs.dateField,
+ );
+
+ const actions: ChatsActions = {
+ projects,
+ projectNames,
+ pinned,
+ pinnedProjects,
+ favorites,
+ favoriteProjects,
+ favoriteSections,
+ favoriteMarks: !embedded,
+ selectable: !embedded,
+ models,
+ selection,
+ toggleSelected: (id, range = false) => {
+ // Anchor on an id: the list can re-sort between clicks.
+ const anchor = selectionAnchor.current;
+ const ids = range && anchor ? rangeBetween(shownOrder, anchor, id) : [id];
+ const on = !selection.has(id);
+ setSelection((current) => {
+ const next = new Set(current);
+ for (const each of ids) {
+ if (on) next.add(each);
+ else next.delete(each);
+ }
+ return next;
+ });
+ selectionAnchor.current = id;
+ },
+ open: openChat,
+ rename: setRenaming,
+ togglePin: (chat) => togglePinned(chat.id),
+ setFavorite: (chats, favorite) => {
+ setFavoriteChats(
+ chats.map((chat) => chat.id),
+ favorite,
+ );
+ setSelection(new Set());
+ },
+ toggleFavoriteProject: (id) => setFavoriteProjects([id], !favoriteProjects.has(id)),
+ toggleFavoriteSection: (id) => setFavoriteSections([id], !favoriteSections.has(id)),
+ fork: (chat) => void forkChat(chat),
+ move: moveChats,
+ moveProject,
+ archive: archiveChats,
+ unarchive: unarchiveChats,
+ exportChats: (chats, choice) => void exportChats(chats, choice),
+ remove: (chats) => {
+ const target = { kind: "chats", chats, deleteFiles: alwaysDeleteChatFiles } as const;
+ if (confirmDeleteChats) setPendingDelete(target);
+ else void confirmDelete(target);
+ },
+ viewProject: openProject,
+ filterProject: embedded
+ ? openProject
+ : (id) => setFilters((current) => ({ ...current, projects: new Set([id]) })),
+ sections,
+ sectionOf,
+ projectSectionOf,
+ dateField: prefs.dateField,
+ chatContents,
+ viewSection: (id) => go({ chatSection: id }),
+ newChatInSection: (id) => newChatInSection(id),
+ newProjectInSection,
+ renameSection: setRenamingSection,
+ removeSection: (entry) => {
+ const undo = removeCustomSectionWithUndo(entry);
+ toast.success(t("shell.sections.deleted", { name: entry.name }), {
+ action: { label: t("shell.sections.undo"), onClick: undo },
+ });
+ if (openSectionId === entry.id) go({ chatView: "sections" }, true);
+ },
+ exportSection: (entry, choice) =>
+ void exportChats(
+ items.filter((chat) => sectionOf.get(chat.id) === entry.id),
+ choice,
+ `section-${entry.name}`,
+ ),
+ newChatIn,
+ editProject: setEditing,
+ togglePinProject,
+ projectChatCounts,
+ sectionChatCounts,
+ exportProject: (project, choice) =>
+ void exportChats(
+ items.filter((chat) => chat.projectId === project.id),
+ choice,
+ `project-${project.name}`,
+ ),
+ // Off by default: the workspace may hold the user's own files.
+ deleteProject: (project) => setPendingDelete({ kind: "project", project, deleteFiles: false }),
+ };
+
+ const narrowed = Boolean(query.trim()) || chatFiltersActive(filters);
+ const showProject =
+ groupBy !== "project" && shownChats.some((chat) => chat.projectId);
+ const showSection =
+ !openSectionId && groupBy !== "section" && shownChats.some((chat) => sectionOf.has(chat.id));
+ const allSelected = shownChats.length > 0 && shownChats.every((chat) => selection.has(chat.id));
+
+ function groupLabel(group: ChatGroup<SidebarItem>): string {
+ if (group.pinned) return t("library.chats.toolbar.pinned");
+ if (group.sectionId !== undefined) {
+ return group.sectionId === null
+ ? t("library.chats.toolbar.withoutSection")
+ : (sectionNames.get(group.sectionId) ?? "");
+ }
+ if (group.bucket) {
+ const bucket = group.bucket;
+ if (bucket.kind !== "older") return t(BUCKET_LABELS[bucket.kind]);
+ return new Date(bucket.year, bucket.month, 1).toLocaleDateString(locale, {
+ month: "long",
+ year: "numeric",
+ });
+ }
+ if (group.projectId === null) return t("settings.data.library.noProject");
+ return (
+ projectNames.get(group.projectId ?? "") ?? t("settings.data.library.unavailableProject")
+ );
+ }
+
+ function renderChats() {
+ if (!loaded) return <LoadingRows />;
+ const filedProjects = renderSectionProjects();
+ if (visibleChats.length === 0 && filedProjects) return filedProjects;
+ if (visibleChats.length === 0) {
+ if (narrowed) {
+ return (
+ <EmptyState
+ icon={MessageCircleIcon}
+ title={t("library.empty.noMatchesTitle")}
+ description={t("library.empty.noMatchesDescription")}
+ />
+ );
+ }
+ if (archived) {
+ return (
+ <EmptyState
+ icon={Archive03Icon}
+ title={t("library.chats.empty.archivedTitle")}
+ description={t("library.chats.empty.archivedDescription")}
+ />
+ );
+ }
+ if (openSectionId) {
+ return (
+ <EmptyState
+ icon={LayerIcon}
+ title={t("library.chats.empty.sectionTitle")}
+ description={t("library.chats.empty.sectionDescription")}
+ action={
+ <Button
+ variant="muted"
+ className="rounded-full px-5"
+ onClick={() => newChatInSection(openSectionId)}
+ >
+ {t("library.chats.toolbar.newChat")}
+ </Button>
+ }
+ />
+ );
+ }
+ return (
+ <EmptyState
+ icon={MessageCircleIcon}
+ title={t("library.chats.empty.chatsTitle")}
+ description={t("library.chats.empty.chatsDescription")}
+ action={
+ <Button variant="muted" className="rounded-full px-5" onClick={() => newChatIn(null)}>
+ {t("library.chats.toolbar.newChat")}
+ </Button>
+ }
+ />
+ );
+ }
+ return (
+ <>
+ {filedProjects}
+ {filedProjects && (
+ <div className="mt-2">
+ <GroupHeading count={visibleChats.length}>{t("library.chats.sections.chats")}</GroupHeading>
+ </div>
+ )}
+ {chatListing()}
+ </>
+ );
+ }
+
+ function chatListing(spaced = !embedded) {
+ const list = view === "list";
+ const collectionLocation =
+ shownEntries !== null && visibleProjects.some((project) => projectSectionOf.has(project.id));
+ const locationColumn = showProject || showSection || collectionLocation;
+ const layout = { showLocation: locationColumn };
+ const total = allEntries?.length ?? visibleChats.length;
+ const chatRow = (chat: SidebarItem, bucket?: DateBucket["kind"]) =>
+ list ? (
+ <ChatRow
+ key={chat.id}
+ chat={chat}
+ archived={archived}
+ showProject={showProject}
+ showSection={showSection}
+ locationColumn={locationColumn}
+ times={{ bucket }}
+ />
+ ) : (
+ <ChatCard
+ key={chat.id}
+ chat={chat}
+ archived={archived}
+ showProject={showProject}
+ showSection={showSection}
+ times={{ bucket }}
+ />
+ );
+ const entryRow = (entry: NonNullable<typeof shownEntries>[number]) => {
+ if (entry.kind === "chat") return chatRow(entry.item);
+ if (entry.kind === "project") {
+ const key = `project:${entry.item.id}`;
+ return list ? (
+ <ProjectRow key={key} project={entry.item} stats={stats.get(entry.item.id)} layout={layout} />
+ ) : (
+ <ProjectCard key={key} project={entry.item} stats={stats.get(entry.item.id)} />
+ );
+ }
+ const key = `section:${entry.item.id}`;
+ const sectionStat = sectionStatsById.get(entry.item.id);
+ return list ? (
+ <SectionRow key={key} section={entry.item} stats={sectionStat} layout={layout} />
+ ) : (
+ <SectionCard key={key} section={entry.item} stats={sectionStat} />
+ );
+ };
+ return (
+ <div className={cn("@container", spaced && "mt-6")}>
+ {list && (
+ <ChatListHeader
+ sort={prefs.sort}
+ onSortChange={(key) =>
+ prefs.set({
+ sort:
+ prefs.sort.key === key
+ ? { key, desc: !prefs.sort.desc }
+ : { key, desc: key !== "name" },
+ })
+ }
+ date={chatDateColumn}
+ showLocation={locationColumn}
+ allSelected={allSelected}
+ selecting={selection.size > 0}
+ onToggleAll={() =>
+ setSelection(allSelected ? new Set() : new Set(shownChats.map((chat) => chat.id)))
+ }
+ />
+ )}
+ {shownEntries ? (
+ list ? (
+ <div className={cn("mt-1 flex flex-col", LIST_ROW_GAP)}>{shownEntries.map(entryRow)}</div>
+ ) : (
+ <CardGrid>{shownEntries.map(entryRow)}</CardGrid>
+ )
+ ) : (
+ groups.map((group) => (
+ <section key={group.key} aria-label={groupBy === "none" ? undefined : groupLabel(group)}>
+ {groupBy !== "none" && (
+ <GroupHeading count={groupTotals.get(group.key) ?? group.items.length}>
+ {groupLabel(group)}
+ </GroupHeading>
+ )}
+ {list ? (
+ <div className={cn("flex flex-col", LIST_ROW_GAP, groupBy === "none" && "mt-1")}>
+ {group.items.map((chat) => chatRow(chat, group.bucket?.kind))}
+ </div>
+ ) : (
+ <CardGrid>{group.items.map((chat) => chatRow(chat, group.bucket?.kind))}</CardGrid>
+ )}
+ </section>
+ ))
+ )}
+ {total > visibleCount && (
+ <div className="mt-6 flex justify-center">
+ <Button
+ variant="muted"
+ className="rounded-full px-5"
+ onClick={() => setVisibleCount((count) => count + PAGE_SIZE)}
+ >
+ {t("library.chats.list.showMore", { count: total - visibleCount })}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ function renderSections() {
+ if (!loaded) return <LoadingRows />;
+ if (visibleSections.length === 0) {
+ return query.trim() ? (
+ <EmptyState
+ icon={LayerIcon}
+ title={t("library.empty.noMatchesTitle")}
+ description={t("library.empty.noMatchesDescription")}
+ />
+ ) : (
+ <EmptyState
+ icon={LayerIcon}
+ title={t("library.chats.empty.sectionsTitle")}
+ description={t("library.chats.empty.sectionsDescription")}
+ action={
+ <Button
+ variant="dark"
+ className="rounded-full px-5"
+ onClick={() => setMovingIntoNew({ kind: "section", chats: [] })}
+ >
+ {t("shell.sections.newSection")}
+ </Button>
+ }
+ />
+ );
+ }
+ return <div className="mt-6">{sectionListing()}</div>;
+ }
+
+ function sectionListing() {
+ if (view === "list") {
+ return (
+ <div className="@container">
+ <SectionListHeader date={sectionDateColumn} />
+ <div className={cn("mt-1 flex flex-col", LIST_ROW_GAP)}>
+ {visibleSections.map((entry) => (
+ <SectionRow key={entry.id} section={entry} stats={sectionStatsById.get(entry.id)} />
+ ))}
+ </div>
+ </div>
+ );
+ }
+ return (
+ <CardGrid>
+ <button
+ type="button"
+ onClick={() => setMovingIntoNew({ kind: "section", chats: [] })}
+ className="flex min-h-40 flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border text-ui-14 text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground"
+ >
+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.5} className="size-6" />
+ {t("shell.sections.newSection")}
+ </button>
+ {visibleSections.map((entry) => (
+ <SectionCard key={entry.id} section={entry} stats={sectionStatsById.get(entry.id)} />
+ ))}
+ </CardGrid>
+ );
+ }
+
+ function renderAll() {
+ if (!loaded || !projectsLoaded) return <LoadingRows />;
+ const nothing =
+ visibleProjects.length === 0 && visibleSections.length === 0 && visibleChats.length === 0;
+ if (nothing) return renderChats();
+ return chatListing(true);
+ }
+
+ function renderSectionProjects() {
+ if (sectionProjects.length === 0) return null;
+ return (
+ <div className="@container mt-6">
+ <GroupHeading
+ count={sectionProjects.length}
+ countLabel={t(
+ sectionProjects.length === 1
+ ? "library.chats.project.oneProject"
+ : "library.chats.project.projectCount",
+ { count: sectionProjects.length },
+ )}
+ >
+ {t("library.chats.sections.projects")}
+ </GroupHeading>
+ {view === "list" ? (
+ <div className={cn("flex flex-col", LIST_ROW_GAP)}>
+ {sectionProjects.map((project) => (
+ <ProjectRow key={project.id} project={project} stats={stats.get(project.id)} />
+ ))}
+ </div>
+ ) : (
+ <CardGrid>
+ {sectionProjects.map((project) => (
+ <ProjectCard key={project.id} project={project} stats={stats.get(project.id)} />
+ ))}
+ </CardGrid>
+ )}
+ </div>
+ );
+ }
+
+ function renderProjects() {
+ if (!projectsLoaded || !loaded) return <LoadingRows />;
+ if (visibleProjects.length === 0) {
+ return query.trim() ? (
+ <EmptyState
+ icon={Folder02Icon}
+ title={t("library.empty.noMatchesTitle")}
+ description={t("library.empty.noMatchesDescription")}
+ />
+ ) : (
+ <EmptyState
+ icon={Folder02Icon}
+ title={t("library.chats.empty.projectsTitle")}
+ description={t("library.chats.empty.projectsDescription")}
+ action={
+ <Button variant="dark" className="rounded-full px-5" onClick={() => setCreatingProject(true)}>
+ {t("library.chats.toolbar.newProject")}
+ </Button>
+ }
+ />
+ );
+ }
+ return <div className="mt-6">{projectListing()}</div>;
+ }
+
+ function projectListing() {
+ if (view === "list") {
+ return (
+ <div className="@container">
+ <ProjectListHeader date={projectDateColumn} />
+ <div className={cn("mt-1 flex flex-col", LIST_ROW_GAP)}>
+ {visibleProjects.map((project) => (
+ <ProjectRow key={project.id} project={project} stats={stats.get(project.id)} />
+ ))}
+ </div>
+ </div>
+ );
+ }
+ return (
+ <CardGrid>
+ {!embedded && (
+ <button
+ type="button"
+ onClick={() => setCreatingProject(true)}
+ className="flex min-h-44 flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border text-ui-14 text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground"
+ >
+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.5} className="size-6" />
+ {t("library.chats.toolbar.newProject")}
+ </button>
+ )}
+ {visibleProjects.map((project) => (
+ <ProjectCard key={project.id} project={project} stats={stats.get(project.id)} />
+ ))}
+ </CardGrid>
+ );
+ }
+
+ const sectionPills = (
+ <nav aria-label={t("library.chats.sections.ariaLabel")} className="flex flex-wrap items-center gap-x-8 gap-y-2 pl-3.5">
+ {CHATS_SECTIONS.map((entry) => {
+ const active = openSectionId ? entry === "sections" : entry === section;
+ return (
+ <button
+ key={entry}
+ type="button"
+ aria-current={active ? "page" : undefined}
+ onClick={() => go(entry === "all" ? {} : { chatView: entry })}
+ className={cn(
+ "flex h-8 items-center gap-2 rounded-sm font-heading text-ui-14 text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
+ active && "font-medium text-foreground",
+ )}
+ >
+ {SECTION_ICONS[entry] && (
+ <HugeiconsIcon icon={SECTION_ICONS[entry]} strokeWidth={1.75} className="size-4 shrink-0" />
+ )}
+ {t(SECTION_LABELS[entry])}
+ </button>
+ );
+ })}
+ </nav>
+ );
+
+ const sectionHeader = currentSection && (
+ <CollectionHeader
+ icon={LayerIcon}
+ name={currentSection.name}
+ parent={t("shell.sections.sectionsHeading")}
+ onParent={() => go({ chatView: "sections" })}
+ actions={
+ <>
+ <Button variant="muted" className="rounded-full px-4" onClick={() => newChatInSection(currentSection.id)}>
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-4" />
+ {t("library.chats.toolbar.newChat")}
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button type="button" aria-label={t("library.menu.moreActions")} className={HEADER_MORE_BUTTON}>
+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="library-actions-menu w-52">
+ <SectionMenuItems section={currentSection} onPage />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </>
+ }
+ />
+ );
+
+ const searchPlaceholder =
+ currentSection
+ ? t("library.chats.search.project", { project: currentSection.name })
+ : t(
+ section === "projects"
+ ? "library.chats.search.projects"
+ : section === "sections"
+ ? "library.chats.search.sections"
+ : archived
+ ? "library.chats.search.archived"
+ : "library.chats.search.chats",
+ );
+
+ const sortControl =
+ section === "sections" ? (
+ <SortMenu
+ options={SECTION_SORTS}
+ value={prefs.sectionSort.key}
+ desc={prefs.sectionSort.desc}
+ onChange={(key, desc) =>
+ prefs.set({ sectionSort: { key, desc }, ...(isDateField(key) ? { dateField: key } : {}) })
+ }
+ />
+ ) : section === "projects" ? (
+ <SortMenu
+ options={PROJECT_SORTS}
+ value={prefs.projectSort.key}
+ desc={prefs.projectSort.desc}
+ onChange={(key, desc) =>
+ prefs.set({
+ projectSort: { key, desc },
+ ...(isDateField(key) ? { dateField: key } : {}),
+ })
+ }
+ />
+ ) : (
+ <SortMenu
+ options={CHAT_SORTS}
+ value={prefs.sort.key}
+ desc={prefs.sort.desc}
+ onChange={(key, desc) =>
+ prefs.set({ sort: { key, desc }, ...(isDateField(key) ? { dateField: key } : {}) })
+ }
+ groupBy={section === "all" ? undefined : groupBy}
+ groupOptions={groupOptions}
+ onGroupByChange={(next) => prefs.set({ groupBy: next })}
+ pinnedFirst={archived ? undefined : prefs.pinnedFirst}
+ onPinnedFirstChange={(next) => prefs.set({ pinnedFirst: next })}
+ />
+ );
+
+ const selectedPinned = selectedChats.length > 0 && selectedChats.every((chat) => pinned.has(chat.id));
+ const selectedFavorite =
+ selectedChats.length > 0 && selectedChats.every((chat) => favorites.has(chat.id));
+ const shared = <T,>(of: (chat: SidebarItem) => T): T | undefined => {
+ const first = selectedChats[0];
+ if (!first) return undefined;
+ const value = of(first);
+ return selectedChats.every((chat) => of(chat) === value) ? value : undefined;
+ };
+ const sharedProject = shared((chat) => chat.projectId ?? null);
+ const sharedSection = shared((chat) => sectionOf.get(chat.id) ?? null);
+
+ const deleteCopy = (() => {
+ if (!pendingDelete) return null;
+ if (pendingDelete.kind === "project") {
+ return {
+ title: t("library.dialog.deleteTitle", { name: pendingDelete.project.name }),
+ description: t("library.chats.dialog.deleteProjectDescription", {
+ // Archived chats are deleted with the project too.
+ count:
+ (stats.get(pendingDelete.project.id)?.chats ?? 0) +
+ (stats.get(pendingDelete.project.id)?.archived ?? 0),
+ }),
+ filesLabel: t("library.chats.dialog.deleteProjectFilesLabel"),
+ files: pendingDelete.project.rootPath ?? t("library.chats.dialog.deleteProjectFiles"),
+ };
+ }
+ const { chats } = pendingDelete;
+ return chats.length === 1
+ ? {
+ title: t("library.dialog.deleteTitle", {
+ name: chats[0]?.title || t("settings.data.library.untitled"),
+ }),
+ description: t("library.chats.dialog.deleteChatDescription"),
+ filesLabel: undefined,
+ files: undefined,
+ }
+ : {
+ title: t("settings.data.library.deleteChatsTitle", { count: chats.length }),
+ description: t("settings.data.library.deleteChatsWarning", { count: chats.length }),
+ filesLabel: undefined,
+ files: t("library.chats.dialog.deleteFilesMany"),
+ };
+ })();
+
+ function favoriteEntries(): FavoriteChatEntries {
+ const projectsShown = loaded && projectsLoaded ? visibleProjects : [];
+ const sectionsShown = loaded ? visibleSections : [];
+ const chatsShown = loaded ? visibleChats : [];
+ return {
+ rows: [
+ ...projectsShown.map((project) => (
+ <ProjectRow
+ key={`project:${project.id}`}
+ project={project}
+ stats={stats.get(project.id)}
+ layout="files"
+ />
+ )),
+ ...sectionsShown.map((entry) => (
+ <SectionRow
+ key={`section:${entry.id}`}
+ section={entry}
+ stats={sectionStatsById.get(entry.id)}
+ layout="files"
+ />
+ )),
+ ...chatsShown.map((chat) => (
+ <ChatRow
+ key={`chat:${chat.id}`}
+ chat={chat}
+ archived={false}
+ showProject={false}
+ showSection={false}
+ fileColumns
+ />
+ )),
+ ],
+ cards: [
+ ...projectsShown.map((project) => ({
+ key: `project:${project.id}`,
+ node: <FavoriteProjectTile project={project} stats={stats.get(project.id)} />,
+ })),
+ ...sectionsShown.map((entry) => ({
+ key: `section:${entry.id}`,
+ node: <FavoriteSectionTile section={entry} stats={sectionStatsById.get(entry.id)} />,
+ })),
+ ...chatsShown.map((chat) => ({
+ key: `chat:${chat.id}`,
+ node: <FavoriteChatTile chat={chat} />,
+ })),
+ ],
+ };
+ }
+
+ return (
+ <ChatsActionsProvider value={actions}>
+ {embedded ? (
+ embedded.render(favoriteEntries())
+ ) : (
+ <main className="relative mx-auto w-full max-w-[calc(1560px*var(--ui-space-scale,1))] px-6 pb-24 pt-8 font-heading sm:px-10">
+ <LibraryHeader
+ title={title}
+ controls={
+ <ChatsToolbar
+ filters={section === "projects" || section === "sections" ? undefined : filters}
+ onFiltersChange={setFilters}
+ facets={facets}
+ sort={sortControl}
+ view={view}
+ onViewChange={(view) => prefs.set({ view })}
+ search={query}
+ onSearchChange={setQuery}
+ searchPlaceholder={searchPlaceholder}
+ onNewChat={() => (openSectionId ? newChatInSection(openSectionId) : newChatIn(null))}
+ onNewProject={() =>
+ openSectionId ? newProjectInSection(openSectionId) : setCreatingProject(true)
+ }
+ onNewSection={() => setMovingIntoNew({ kind: "section", chats: [] })}
+ />
+ }
+ tabs={tabs ?? null}
+ />
+ <div className="flex flex-col gap-5 pl-3 font-sans">
+ {sectionPills}
+ {sectionHeader && <div className="mt-3">{sectionHeader}</div>}
+ </div>
+ <div className="pl-3 font-sans">
+ {section === "all"
+ ? renderAll()
+ : section === "projects"
+ ? renderProjects()
+ : section === "sections"
+ ? renderSections()
+ : renderChats()}
+ </div>
+
+ {selectedChats.length > 0 && (
+ <div
+ role="toolbar"
+ aria-label={t("shell.selection.countSelected", { count: selectedChats.length })}
+ className="fixed bottom-8 left-1/2 z-30 flex font-sans -translate-x-1/2 items-center gap-2 rounded-full bg-sidebar py-2 pl-6 pr-2 text-sidebar-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:shadow-[0_8px_28px_-6px_var(--background)]"
+ >
+ <span aria-live="polite" className="mr-4 whitespace-nowrap text-sm font-medium">
+ {t("shell.selection.countSelected", { count: selectedChats.length })}
+ </span>
+ {archived ? (
+ <button
+ type="button"
+ onClick={() => unarchiveChats(selectedChats)}
+ className={cn(BAR_PILL, "bg-foreground text-background transition-opacity hover:opacity-85")}
+ >
+ <HugeiconsIcon icon={ArchiveRestoreIcon} strokeWidth={1.75} className="size-4" />
+ {t("settings.data.library.unarchive")}
+ </button>
+ ) : (
+ <>
+ <button
+ type="button"
+ onClick={() => setChatsPinned(selectedChats, !selectedPinned)}
+ className={cn(BAR_PILL, BAR_OUTLINE)}
+ >
+ <HugeiconsIcon icon={selectedPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-4" />
+ {t(selectedPinned ? "settings.data.library.unpin" : "settings.data.library.pin")}
+ </button>
+ <button
+ type="button"
+ onClick={() => archiveChats(selectedChats)}
+ className={cn(BAR_PILL, BAR_OUTLINE)}
+ >
+ <HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-4" />
+ {t("settings.data.library.archive")}
+ </button>
+ </>
+ )}
+ <button
+ type="button"
+ onClick={() => actions.remove(selectedChats)}
+ className={cn(
+ BAR_PILL,
+ "border border-red-500/70 text-red-600 transition-colors hover:bg-red-500/15 dark:text-red-400",
+ )}
+ >
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-4" />
+ {t("common.delete")}
+ </button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={t("library.menu.moreActions")}
+ className={cn(BAR_ROUND, "data-[state=open]:bg-sidebar-accent")}
+ >
+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="center" side="top" className="library-actions-menu w-52">
+ {selectedChats.length < shownChats.length && (
+ <DropdownMenuItem
+ onSelect={() => setSelection(new Set(shownChats.map((chat) => chat.id)))}
+ >
+ <HugeiconsIcon icon={CheckmarkSquare02Icon} strokeWidth={1.75} className="size-icon" />
+ {t("settings.data.library.selectAll")}
+ </DropdownMenuItem>
+ )}
+ {!archived && (
+ <DropdownMenuItem onSelect={() => actions.setFavorite(selectedChats, !selectedFavorite)}>
+ <HugeiconsIcon
+ icon={StarPointedIcon}
+ strokeWidth={1.75}
+ className={cn("size-icon", selectedFavorite && "[&_path]:fill-current")}
+ />
+ {t(selectedFavorite ? "library.menu.removeFromFavorites" : "library.menu.addToFavorites")}
+ </DropdownMenuItem>
+ )}
+ {!archived && (
+ <MoveSubmenu
+ project={sharedProject}
+ section={sharedSection}
+ onMove={(destination) => moveChats(selectedChats, destination)}
+ />
+ )}
+ <ExportSubmenu
+ bulk={selectedChats.length > 1}
+ onExport={(choice) => void exportChats(selectedChats, choice)}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <button
+ type="button"
+ aria-label={t("library.selection.clear")}
+ onClick={() => setSelection(new Set())}
+ className={BAR_ROUND}
+ >
+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-5" />
+ </button>
+ </div>
+ )}
+ </main>
+ )}
+
+ <NameDialog
+ open={renaming !== null}
+ title={t("library.chats.dialog.renameChat")}
+ submitLabel={t("common.rename")}
+ initialValue={renaming?.title ?? ""}
+ onSubmit={async (name) => {
+ if (!renaming) return;
+ try {
+ await renameChatItem(renaming, name);
+ notifyChatHistoryUpdated();
+ } catch (err) {
+ toast.error(t("library.toast.renameFailed"), { description: errorDescription(err) });
+ throw err;
+ }
+ }}
+ onOpenChange={(open) => !open && setRenaming(null)}
+ />
+ <EditProjectDialog
+ project={editing}
+ onOpenChange={(open) => !open && setEditing(null)}
+ onDelete={(project) => {
+ setEditing(null);
+ actions.deleteProject(project);
+ }}
+ />
+ <NewProjectDialog
+ open={creatingProject}
+ onOpenChange={(open) => {
+ setCreatingProject(open);
+ if (!open && movingIntoNew?.kind === "project") setMovingIntoNew(null);
+ if (!open) setNewProjectSection(null);
+ }}
+ title={t("library.chats.toolbar.newProject")}
+ submitLabel={t("library.dialog.create")}
+ onCreated={(project) => {
+ if (movingIntoNew?.kind === "project") {
+ moveToProject(movingIntoNew.chats, project.id, project.name);
+ setMovingIntoNew(null);
+ return;
+ }
+ if (newProjectSection) fileProjectInSection(project, newProjectSection);
+ openProject(project.id);
+ }}
+ />
+ <SectionNameDialog
+ open={movingIntoNew?.kind === "section"}
+ mode="create"
+ onOpenChange={(open) => !open && setMovingIntoNew(null)}
+ onSubmit={(name) => {
+ const sectionId = createCustomSection(name);
+ if (!sectionId || !movingIntoNew) return;
+ if (movingIntoNew.project) {
+ fileProjectInSection(movingIntoNew.project, sectionId, normalizeSectionName(name));
+ return;
+ }
+ if (movingIntoNew.chats.length === 0) {
+ setAwaitedSection(sectionId);
+ go({ chatSection: sectionId });
+ return;
+ }
+ fileInSection(movingIntoNew.chats, sectionId, normalizeSectionName(name));
+ }}
+ />
+ <SectionNameDialog
+ open={renamingSection !== null}
+ mode="rename"
+ initialName={renamingSection?.name ?? ""}
+ onOpenChange={(open) => !open && setRenamingSection(null)}
+ onSubmit={(name) => renamingSection && renameCustomSection(renamingSection.id, name)}
+ />
+ <AlertDialog open={pendingDelete !== null} onOpenChange={(open) => !open && setPendingDelete(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle className="break-words">{deleteCopy?.title}</AlertDialogTitle>
+ <AlertDialogDescription>{deleteCopy?.description}</AlertDialogDescription>
+ </AlertDialogHeader>
+ {pendingDelete && (
+ <DeleteChatFilesSwitch
+ id="library-chats-delete-files"
+ checked={pendingDelete.deleteFiles}
+ onCheckedChange={(deleteFiles) => setPendingDelete({ ...pendingDelete, deleteFiles })}
+ label={deleteCopy?.filesLabel}
+ description={deleteCopy?.files}
+ />
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => pendingDelete && void confirmDelete(pendingDelete)}
+ >
+ {t("common.delete")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </ChatsActionsProvider>
+ );
+}
diff --git a/studio/frontend/src/features/library/chats/chats-toolbar.tsx b/studio/frontend/src/features/library/chats/chats-toolbar.tsx
new file mode 100644
index 00000000000..bc77a4595b5
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/chats-toolbar.tsx
@@ -0,0 +1,427 @@
+// 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 {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { type TranslationKey, useT } from "@/i18n";
+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
+import { StarPointedIcon } from "@/lib/hugeicons-derived";
+import { cn } from "@/lib/utils";
+import {
+ FilterMailIcon,
+ Folder02Icon,
+ FolderAddIcon,
+ LayerIcon,
+ PencilEdit02Icon,
+ PinIcon,
+ Search01Icon,
+ Tick02Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { ArrowDownUpIcon, Columns2Icon, GitBranchIcon } from "lucide-react";
+import type { ReactNode } from "react";
+import { ROUND_BUTTON, SortRadio, VIEW_OPTIONS } from "../components/library-toolbar";
+import type { LibraryView } from "../settings-store";
+import {
+ type ChatFilters,
+ type ChatFlag,
+ type ChatGroupBy,
+ EMPTY_CHAT_FILTERS,
+ NO_PROJECT,
+ NO_SECTION,
+ chatFiltersActive,
+} from "./model";
+
+const ICON = "size-icon";
+const MENU_LABEL = "px-3 pb-1 pt-2 text-muted-foreground font-normal";
+
+const FLAG_OPTIONS: { value: ChatFlag; label: TranslationKey; icon: ReactNode }[] = [
+ {
+ value: "favorite",
+ label: "library.tabs.favorites",
+ icon: <HugeiconsIcon icon={StarPointedIcon} strokeWidth={1.75} className={ICON} />,
+ },
+ {
+ value: "pinned",
+ label: "library.chats.toolbar.pinned",
+ icon: <HugeiconsIcon icon={PinIcon} strokeWidth={1.75} className={ICON} />,
+ },
+ {
+ value: "forks",
+ label: "library.chats.toolbar.forks",
+ icon: <GitBranchIcon strokeWidth={1.75} className={ICON} />,
+ },
+ {
+ value: "compare",
+ label: "library.chats.toolbar.comparisons",
+ icon: <Columns2Icon strokeWidth={1.75} className={ICON} />,
+ },
+];
+
+const GROUP_OPTIONS: { value: ChatGroupBy; label: TranslationKey }[] = [
+ { value: "none", label: "library.chats.toolbar.groupNone" },
+ { value: "date", label: "library.chats.toolbar.groupDate" },
+ { value: "project", label: "library.chats.toolbar.groupProject" },
+ { value: "section", label: "shell.sections.section" },
+];
+
+function toggled<T>(set: ReadonlySet<T>, value: T): Set<T> {
+ const next = new Set(set);
+ if (!next.delete(value)) next.add(value);
+ return next;
+}
+
+function CheckItem({
+ icon,
+ label,
+ hint,
+ checked,
+ onToggle,
+}: {
+ icon?: ReactNode;
+ label: string;
+ hint?: string;
+ checked: boolean;
+ onToggle: () => void;
+}) {
+ return (
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ onToggle();
+ }}
+ >
+ {icon}
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {hint && <span className="ml-3 text-xs text-muted-foreground tabular-nums">{hint}</span>}
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ strokeWidth={2}
+ className={cn("ml-2 size-4 shrink-0", !checked && "invisible")}
+ />
+ </DropdownMenuItem>
+ );
+}
+
+export interface FilterFacets {
+ projects: { id: string; name: string }[];
+ sections: { id: string; name: string }[];
+ models: { model: string; label: string; count: number }[];
+ showProjects: boolean;
+}
+
+function FilterMenu({
+ filters,
+ onChange,
+ facets,
+}: {
+ filters: ChatFilters;
+ onChange: (next: ChatFilters) => void;
+ facets: FilterFacets;
+}) {
+ const t = useT();
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={t("library.toolbar.filter")}
+ data-active={chatFiltersActive(filters)}
+ className={ROUND_BUTTON}
+ >
+ <HugeiconsIcon icon={FilterMailIcon} strokeWidth={1.75} className="size-5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ sideOffset={4}
+ className="library-actions-menu max-h-[min(--spacing(120),var(--radix-dropdown-menu-content-available-height))] w-64"
+ >
+ <DropdownMenuLabel className={MENU_LABEL}>{t("library.chats.toolbar.show")}</DropdownMenuLabel>
+ {FLAG_OPTIONS.map(({ value, label, icon }) => (
+ <CheckItem
+ key={value}
+ icon={icon}
+ label={t(label)}
+ checked={filters.flags.has(value)}
+ onToggle={() => onChange({ ...filters, flags: toggled(filters.flags, value) })}
+ />
+ ))}
+ {facets.showProjects && (
+ <>
+ <DropdownMenuSeparator className="mx-3" />
+ <DropdownMenuLabel className={MENU_LABEL}>
+ {t("library.chats.toolbar.project")}
+ </DropdownMenuLabel>
+ <CheckItem
+ label={t("settings.data.library.noProject")}
+ checked={filters.projects.has(NO_PROJECT)}
+ onToggle={() => onChange({ ...filters, projects: toggled(filters.projects, NO_PROJECT) })}
+ />
+ {facets.projects.map((project) => (
+ <CheckItem
+ key={project.id}
+ icon={<HugeiconsIcon icon={Folder02Icon} strokeWidth={1.75} className={ICON} />}
+ label={project.name}
+ checked={filters.projects.has(project.id)}
+ onToggle={() =>
+ onChange({ ...filters, projects: toggled(filters.projects, project.id) })
+ }
+ />
+ ))}
+ </>
+ )}
+ {facets.sections.length > 0 && (
+ <>
+ <DropdownMenuSeparator className="mx-3" />
+ <DropdownMenuLabel className={MENU_LABEL}>{t("shell.sections.section")}</DropdownMenuLabel>
+ <CheckItem
+ label={t("library.chats.toolbar.withoutSection")}
+ checked={filters.sections.has(NO_SECTION)}
+ onToggle={() => onChange({ ...filters, sections: toggled(filters.sections, NO_SECTION) })}
+ />
+ {facets.sections.map((section) => (
+ <CheckItem
+ key={section.id}
+ icon={<HugeiconsIcon icon={LayerIcon} strokeWidth={1.75} className={ICON} />}
+ label={section.name}
+ checked={filters.sections.has(section.id)}
+ onToggle={() =>
+ onChange({ ...filters, sections: toggled(filters.sections, section.id) })
+ }
+ />
+ ))}
+ </>
+ )}
+ {facets.models.length > 0 && (
+ <>
+ <DropdownMenuSeparator className="mx-3" />
+ <DropdownMenuLabel className={MENU_LABEL}>
+ {t("library.chats.toolbar.model")}
+ </DropdownMenuLabel>
+ {facets.models.map(({ model, label, count }) => (
+ <CheckItem
+ key={model}
+ label={label}
+ hint={String(count)}
+ checked={filters.models.has(model)}
+ onToggle={() => onChange({ ...filters, models: toggled(filters.models, model) })}
+ />
+ ))}
+ </>
+ )}
+ {chatFiltersActive(filters) && (
+ <>
+ <DropdownMenuSeparator className="mx-3" />
+ <DropdownMenuItem onSelect={() => onChange(EMPTY_CHAT_FILTERS)}>
+ <span className="text-muted-foreground">{t("library.toolbar.clearFilters")}</span>
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+export interface SortChoice<K extends string> {
+ value: K;
+ label: TranslationKey;
+}
+
+export function SortMenu<K extends string>({
+ options,
+ value,
+ desc,
+ onChange,
+ groupBy,
+ groupOptions = GROUP_OPTIONS.map((option) => option.value),
+ onGroupByChange,
+ pinnedFirst,
+ onPinnedFirstChange,
+}: {
+ options: SortChoice<K>[];
+ value: K;
+ desc: boolean;
+ onChange: (value: K, desc: boolean) => void;
+ groupBy?: ChatGroupBy;
+ groupOptions?: ChatGroupBy[];
+ onGroupByChange?: (groupBy: ChatGroupBy) => void;
+ pinnedFirst?: boolean;
+ onPinnedFirstChange?: (pinnedFirst: boolean) => void;
+}) {
+ const t = useT();
+ const current = options.find((option) => option.value === value);
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-full px-3 text-ui-14 text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-open:bg-muted data-open:text-foreground dark:text-foreground/70"
+ >
+ <ArrowDownUpIcon strokeWidth={1.75} className="size-[calc(16px*var(--ui-space-scale,1))]" />
+ {current ? t(current.label) : t("library.toolbar.sort")}
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" sideOffset={4} className="library-actions-menu w-max min-w-44">
+ <DropdownMenuLabel className={MENU_LABEL}>{t("library.toolbar.sort")}</DropdownMenuLabel>
+ {options.map((option) => (
+ <SortRadio
+ key={option.value}
+ label={t(option.label)}
+ checked={option.value === value}
+ // Name defaults to A-Z, times to newest first; re-picking keeps the direction.
+ onSelect={() =>
+ onChange(option.value, option.value === value ? desc : option.value !== "name")
+ }
+ />
+ ))}
+ <DropdownMenuSeparator className="mx-3" />
+ <SortRadio
+ label={t("library.toolbar.sortAscending")}
+ checked={!desc}
+ onSelect={() => onChange(value, false)}
+ />
+ <SortRadio
+ label={t("library.toolbar.sortDescending")}
+ checked={desc}
+ onSelect={() => onChange(value, true)}
+ />
+ {groupBy !== undefined && onGroupByChange && (
+ <>
+ <DropdownMenuSeparator className="mx-3" />
+ <DropdownMenuLabel className={MENU_LABEL}>{t("library.chats.toolbar.groupBy")}</DropdownMenuLabel>
+ {GROUP_OPTIONS.filter((option) => groupOptions.includes(option.value)).map((option) => (
+ <SortRadio
+ key={option.value}
+ label={t(option.label)}
+ checked={groupBy === option.value}
+ onSelect={() => onGroupByChange(option.value)}
+ />
+ ))}
+ </>
+ )}
+ {pinnedFirst !== undefined && onPinnedFirstChange && (
+ <>
+ <DropdownMenuSeparator className="mx-3" />
+ <CheckItem
+ icon={<HugeiconsIcon icon={PinIcon} strokeWidth={1.75} className={ICON} />}
+ label={t("library.chats.toolbar.pinnedFirst")}
+ checked={pinnedFirst}
+ onToggle={() => onPinnedFirstChange(!pinnedFirst)}
+ />
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function NewMenu({
+ onNewChat,
+ onNewProject,
+ onNewSection,
+}: {
+ onNewChat: () => void;
+ onNewProject: () => void;
+ onNewSection: () => void;
+}) {
+ const t = useT();
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-full bg-foreground pl-4 pr-3 font-medium text-ui-14 text-background outline-none transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {t("common.new")}
+ <HugeiconsIcon icon={ChevronDownStandardIcon} strokeWidth={2} className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="library-actions-menu w-44">
+ <DropdownMenuItem onSelect={onNewChat}>
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className={ICON} />
+ {t("library.chats.toolbar.newChat")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onNewProject}>
+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className={ICON} />
+ {t("library.chats.toolbar.newProject")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onNewSection}>
+ <HugeiconsIcon icon={LayerIcon} strokeWidth={1.75} className={ICON} />
+ {t("shell.sections.newSection")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+export function ChatsToolbar({
+ filters,
+ onFiltersChange,
+ facets,
+ sort,
+ view,
+ onViewChange,
+ search,
+ onSearchChange,
+ searchPlaceholder,
+ onNewChat,
+ onNewProject,
+ onNewSection,
+}: {
+ filters?: ChatFilters;
+ onFiltersChange: (next: ChatFilters) => void;
+ facets: FilterFacets;
+ sort: ReactNode;
+ view: LibraryView;
+ onViewChange: (view: LibraryView) => void;
+ search: string;
+ onSearchChange: (value: string) => void;
+ searchPlaceholder: string;
+ onNewChat: () => void;
+ onNewProject: () => void;
+ onNewSection: () => void;
+}) {
+ const t = useT();
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ {filters && <FilterMenu filters={filters} onChange={onFiltersChange} facets={facets} />}
+ {sort}
+ {VIEW_OPTIONS.map(({ value, label, icon }) => (
+ <button
+ key={value}
+ type="button"
+ aria-label={t(label)}
+ data-active={view === value}
+ aria-pressed={view === value}
+ onClick={() => onViewChange(value)}
+ className={ROUND_BUTTON}
+ >
+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-5" />
+ </button>
+ ))}
+ <label className="relative ml-2 flex h-9 w-[min(15rem,24vw)] min-w-40 items-center rounded-full border border-border px-4 focus-within:border-ring dark:border-transparent dark:bg-card dark:focus-within:border-ring">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ strokeWidth={1.75}
+ className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0 text-muted-foreground dark:text-foreground/70"
+ />
+ <input
+ type="search"
+ value={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ placeholder={searchPlaceholder}
+ aria-label={searchPlaceholder}
+ className="ml-2.5 min-w-0 flex-1 bg-transparent text-ui-14 outline-none placeholder:text-muted-foreground dark:placeholder:text-foreground/55 [&::-webkit-search-cancel-button]:hidden"
+ />
+ </label>
+ <NewMenu onNewChat={onNewChat} onNewProject={onNewProject} onNewSection={onNewSection} />
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/library/chats/contents.ts b/studio/frontend/src/features/library/chats/contents.ts
new file mode 100644
index 00000000000..d4130317502
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/contents.ts
@@ -0,0 +1,102 @@
+// 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 {
+ type SidebarItem,
+ countStoredChatMessages,
+ listStoredChatMessagesMany,
+} from "@/features/chat";
+import { useEffect, useMemo, useState } from "react";
+import { type ChatContents, summarizeChatMessages } from "./model";
+
+// Keyed by chat version (`updatedAt`). Module-level to survive tab switches; capped.
+const cache = new Map<string, ChatContents>();
+const MAX_CACHED = 5000;
+// Keys in flight or failed, so re-renders never re-request. A failed key retries on a new version.
+const pending = new Set<string>();
+const failed = new Set<string>();
+const listeners = new Set<() => void>();
+// Counts are tiny; the older-server fallback reads whole messages.
+const BATCH = 100;
+const FALLBACK_BATCH = 20;
+
+function cacheKey(chat: SidebarItem): string {
+ return `${chat.id}:${chat.updatedAt}`;
+}
+
+function threadIdsOf(chat: SidebarItem): string[] {
+ return chat.threadIds?.length ? chat.threadIds : [chat.id];
+}
+
+function remember(key: string, value: ChatContents): void {
+ cache.set(key, value);
+ if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value as string);
+}
+
+function needsRead(chat: SidebarItem): boolean {
+ const key = cacheKey(chat);
+ return !cache.has(key) && !pending.has(key) && !failed.has(key);
+}
+
+/** A compare chat counts its fullest pane: the panes share the user's messages. */
+function combine(counts: number[]): ChatContents {
+ return { messages: counts.reduce((best, next) => Math.max(best, next), 0) };
+}
+
+async function readCounts(chats: SidebarItem[]): Promise<(threadId: string) => number> {
+ const ids = chats.flatMap(threadIdsOf);
+ const counts = await countStoredChatMessages(ids);
+ if (counts) return (id) => counts.get(id) ?? 0;
+ const byThread = new Map<string, number>();
+ for (let i = 0; i < ids.length; i += FALLBACK_BATCH) {
+ const read = await listStoredChatMessagesMany(ids.slice(i, i + FALLBACK_BATCH));
+ for (const [id, messages] of read) byThread.set(id, summarizeChatMessages(messages).messages);
+ }
+ return (id) => byThread.get(id) ?? 0;
+}
+
+async function readContents(chats: SidebarItem[]): Promise<void> {
+ const keys = chats.map(cacheKey);
+ for (const key of keys) pending.add(key);
+ try {
+ for (let i = 0; i < chats.length; i += BATCH) {
+ const batch = chats.slice(i, i + BATCH);
+ try {
+ const count = await readCounts(batch);
+ for (const chat of batch) remember(cacheKey(chat), combine(threadIdsOf(chat).map(count)));
+ } catch {
+ for (const chat of batch) failed.add(cacheKey(chat));
+ }
+ for (const listener of listeners) listener();
+ }
+ } finally {
+ for (const key of keys) pending.delete(key);
+ }
+}
+
+export function useChatContents(chats: readonly SidebarItem[]): ReadonlyMap<string, ChatContents> {
+ const [version, setVersion] = useState(0);
+ useEffect(() => {
+ const listener = () => setVersion((v) => v + 1);
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ }, []);
+ const missingKey = chats.filter(needsRead).map(cacheKey).join(",");
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the missing keys are the cue to read
+ useEffect(() => {
+ const missing = chats.filter(needsRead);
+ // Not cancelled: a read in flight still fills the shared cache.
+ if (missing.length > 0) void readContents(missing);
+ }, [missingKey]);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: version marks new cache entries
+ return useMemo(() => {
+ const out = new Map<string, ChatContents>();
+ for (const chat of chats) {
+ const entry = cache.get(cacheKey(chat));
+ if (entry) out.set(chat.id, entry);
+ }
+ return out;
+ }, [chats, version]);
+}
diff --git a/studio/frontend/src/features/library/chats/favorites-store.ts b/studio/frontend/src/features/library/chats/favorites-store.ts
new file mode 100644
index 00000000000..8f3f063b3cd
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/favorites-store.ts
@@ -0,0 +1,59 @@
+// 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 { create } from "zustand";
+import { persist } from "zustand/middleware";
+
+export const LIBRARY_CHAT_FAVORITES_STORAGE_KEY = "unsloth_library_chat_favorites";
+
+// Starred chats, projects and sections, stored locally like pins. Listed only in Favorites and Chats.
+export interface ChatFavoritesState {
+ /** Chat row ids: a thread id, or a compare pair's id. Newest star first. */
+ chatIds: string[];
+ projectIds: string[];
+ sectionIds: string[];
+ setChats: (ids: string[], favorite: boolean) => void;
+ setProjects: (ids: string[], favorite: boolean) => void;
+ setSections: (ids: string[], favorite: boolean) => void;
+}
+
+function withIds(current: string[], ids: string[], on: boolean): string[] {
+ if (!on) {
+ const dropping = new Set(ids);
+ return current.filter((id) => !dropping.has(id));
+ }
+ const additions = ids.filter((id) => !current.includes(id));
+ return additions.length ? [...additions, ...current] : current;
+}
+
+function readIds(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [];
+}
+
+export const useChatFavoritesStore = create<ChatFavoritesState>()(
+ persist(
+ (set) => ({
+ chatIds: [],
+ projectIds: [],
+ sectionIds: [],
+ setChats: (ids, favorite) =>
+ set((state) => ({ chatIds: withIds(state.chatIds, ids, favorite) })),
+ setProjects: (ids, favorite) =>
+ set((state) => ({ projectIds: withIds(state.projectIds, ids, favorite) })),
+ setSections: (ids, favorite) =>
+ set((state) => ({ sectionIds: withIds(state.sectionIds, ids, favorite) })),
+ }),
+ {
+ name: LIBRARY_CHAT_FAVORITES_STORAGE_KEY,
+ merge: (persisted, current) => {
+ const saved = persisted as Partial<ChatFavoritesState> | undefined;
+ return {
+ ...current,
+ chatIds: readIds(saved?.chatIds),
+ projectIds: readIds(saved?.projectIds),
+ sectionIds: readIds(saved?.sectionIds),
+ };
+ },
+ },
+ ),
+);
diff --git a/studio/frontend/src/features/library/chats/favorites.ts b/studio/frontend/src/features/library/chats/favorites.ts
new file mode 100644
index 00000000000..570aa826763
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/favorites.ts
@@ -0,0 +1,46 @@
+// 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 { useChatProjects, useChatSidebarItems, useSidebarOrganizationStore } from "@/features/chat";
+import { useMemo } from "react";
+import { useChatFavoritesStore } from "./favorites-store";
+import { matchesTerms, searchTerms } from "./model";
+
+/** Starred chats, projects and sections Favorites lists for `query`, excluding archived chats. */
+export function useFavoriteChatMatches(query: string, enabled: boolean): number {
+ const { items } = useChatSidebarItems({ enabled, requireMessages: false });
+ const { projects } = useChatProjects();
+ const sections = useSidebarOrganizationStore((s) => s.customSections);
+ const sectionByChatId = useSidebarOrganizationStore((s) => s.sectionByChatId);
+ const chatIds = useChatFavoritesStore((s) => s.chatIds);
+ const projectIds = useChatFavoritesStore((s) => s.projectIds);
+ const sectionIds = useChatFavoritesStore((s) => s.sectionIds);
+ return useMemo(() => {
+ if (!enabled || chatIds.length + projectIds.length + sectionIds.length === 0) return 0;
+ const terms = searchTerms(query);
+ const starredChats = new Set(chatIds);
+ const starredProjects = new Set(projectIds);
+ const starredSections = new Set(sectionIds);
+ const names = new Map(projects.map((project) => [project.id, project.name]));
+ const sectionNames = new Map(sections.map((section) => [section.id, section.name]));
+ const chats = items.filter((chat) => {
+ if (!starredChats.has(chat.id)) return false;
+ const sectionId = sectionByChatId[chat.id];
+ return matchesTerms(
+ terms,
+ chat.title,
+ chat.projectId ? names.get(chat.projectId) : undefined,
+ sectionId ? sectionNames.get(sectionId) : undefined,
+ ...(chat.modelIds ?? []),
+ );
+ }).length;
+ const folders = projects.filter(
+ (project) =>
+ starredProjects.has(project.id) && matchesTerms(terms, project.name, project.instructions),
+ ).length;
+ const filed = sections.filter(
+ (section) => starredSections.has(section.id) && matchesTerms(terms, section.name),
+ ).length;
+ return chats + folders + filed;
+ }, [enabled, query, items, projects, sections, sectionByChatId, chatIds, projectIds, sectionIds]);
+}
diff --git a/studio/frontend/src/features/library/chats/model.ts b/studio/frontend/src/features/library/chats/model.ts
new file mode 100644
index 00000000000..52b2448ee5a
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/model.ts
@@ -0,0 +1,504 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Chats tab data model. Reads chat history, so chats never enter the Library item list.
+
+export const CHATS_SECTIONS = ["all", "chats", "projects", "sections", "archived"] as const;
+export type ChatsSection = (typeof CHATS_SECTIONS)[number];
+
+export interface ChatEntry {
+ id: string;
+ type: "single" | "compare";
+ threadIds?: string[];
+ title: string;
+ createdAt: number;
+ updatedAt: number;
+ isFork?: boolean;
+ projectId?: string | null;
+ /** Last rename, move or archive, when later than `updatedAt`. */
+ modifiedAt?: number;
+}
+
+export interface ProjectEntry {
+ id: string;
+ name: string;
+ instructions?: string;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export const DATE_FIELDS = ["created", "updated", "modified"] as const;
+export type DateField = (typeof DATE_FIELDS)[number];
+
+export type ChatSortKey = "name" | DateField;
+export type ChatSort = { key: ChatSortKey; desc: boolean };
+export type ProjectSortKey = "name" | DateField | "chats";
+export type ProjectSort = { key: ProjectSortKey; desc: boolean };
+/** "updated" is a section's latest chat; "chats" is how many it holds. */
+export type SectionSortKey = "name" | DateField | "chats";
+export type SectionSort = { key: SectionSortKey; desc: boolean };
+export type ChatGroupBy = "none" | "project" | "section" | "date";
+
+export type ChatFlag = "favorite" | "pinned" | "forks" | "compare";
+export const CHAT_FLAGS: ChatFlag[] = ["favorite", "pinned", "forks", "compare"];
+
+export const NO_PROJECT = "none";
+export const NO_SECTION = "none";
+
+export interface ChatFilters {
+ flags: Set<ChatFlag>;
+ projects: Set<string>;
+ sections: Set<string>;
+ models: Set<string>;
+}
+
+export const EMPTY_CHAT_FILTERS: ChatFilters = {
+ flags: new Set(),
+ projects: new Set(),
+ sections: new Set(),
+ models: new Set(),
+};
+
+export function chatFiltersActive(filters: ChatFilters): boolean {
+ return (
+ filters.flags.size > 0 ||
+ filters.projects.size > 0 ||
+ filters.sections.size > 0 ||
+ filters.models.size > 0
+ );
+}
+
+function searchable(value: string): string {
+ return value.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase();
+}
+
+export function searchTerms(query: string): string[] {
+ return searchable(query).trim().split(/\s+/).filter(Boolean);
+}
+
+export function matchesTerms(terms: string[], ...fields: (string | undefined | null)[]): boolean {
+ if (terms.length === 0) return true;
+ const haystack = searchable(fields.filter(Boolean).join(" "));
+ return terms.every((term) => haystack.includes(term));
+}
+
+export interface ChatContext {
+ pinned: ReadonlySet<string>;
+ favorites?: ReadonlySet<string>;
+ projectNames: ReadonlyMap<string, string>;
+ models: ReadonlyMap<string, string[]>;
+ sectionOf?: ReadonlyMap<string, string>;
+ sectionNames?: ReadonlyMap<string, string>;
+}
+
+/** Flags must all match; projects, sections and models each match any ticked value. */
+export function filterChats<T extends ChatEntry>(
+ chats: readonly T[],
+ query: string,
+ filters: ChatFilters,
+ context: ChatContext,
+): T[] {
+ const terms = searchTerms(query);
+ return chats.filter((chat) => {
+ if (filters.flags.has("favorite") && !context.favorites?.has(chat.id)) return false;
+ if (filters.flags.has("pinned") && !context.pinned.has(chat.id)) return false;
+ if (filters.flags.has("forks") && !chat.isFork) return false;
+ if (filters.flags.has("compare") && chat.type !== "compare") return false;
+ if (filters.projects.size > 0 && !filters.projects.has(chat.projectId || NO_PROJECT)) {
+ return false;
+ }
+ const sectionId = context.sectionOf?.get(chat.id);
+ if (filters.sections.size > 0 && !filters.sections.has(sectionId || NO_SECTION)) {
+ return false;
+ }
+ const models = context.models.get(chat.id) ?? [];
+ if (filters.models.size > 0 && !models.some((model) => filters.models.has(model))) {
+ return false;
+ }
+ const project = chat.projectId ? context.projectNames.get(chat.projectId) : undefined;
+ const section = sectionId ? context.sectionNames?.get(sectionId) : undefined;
+ return matchesTerms(terms, chat.title, project, section, ...models);
+ });
+}
+
+export function chatTime(chat: ChatEntry, field: DateField): number {
+ if (field === "created") return chat.createdAt;
+ if (field === "modified") return Math.max(chat.updatedAt, chat.modifiedAt ?? 0);
+ return chat.updatedAt;
+}
+
+/** "updated" is the latest chat in it; "modified" the project's own last edit. */
+export function projectTime(
+ project: ProjectEntry,
+ stats: ProjectStats | undefined,
+ field: DateField,
+): number {
+ if (field === "created") return project.createdAt;
+ if (field === "modified") return project.updatedAt;
+ return stats?.lastActive ?? project.updatedAt;
+}
+
+export function compareChats(
+ sort: ChatSort,
+ locale?: string,
+): (a: ChatEntry, b: ChatEntry) => number {
+ const collate = new Intl.Collator(locale, { numeric: true, sensitivity: "base" }).compare;
+ const ascending = (a: ChatEntry, b: ChatEntry) => {
+ if (sort.key === "name") return collate(a.title, b.title);
+ return (chatTime(a, sort.key) || 0) - (chatTime(b, sort.key) || 0);
+ };
+ return (a, b) => {
+ const primary = sort.desc ? ascending(b, a) : ascending(a, b);
+ return primary || b.updatedAt - a.updatedAt || a.id.localeCompare(b.id);
+ };
+}
+
+/** Pinned chats sort first whatever the order, as in the sidebar. */
+export function sortChats<T extends ChatEntry>(
+ chats: readonly T[],
+ sort: ChatSort,
+ pinned: ReadonlySet<string>,
+ pinnedFirst: boolean,
+ locale?: string,
+): T[] {
+ const compare = compareChats(sort, locale);
+ return [...chats].sort((a, b) => {
+ if (pinnedFirst) {
+ const byPin = Number(pinned.has(b.id)) - Number(pinned.has(a.id));
+ if (byPin) return byPin;
+ }
+ return compare(a, b);
+ });
+}
+
+export interface ProjectStats {
+ chats: number;
+ archived: number;
+ lastActive: number;
+}
+
+export function projectStats(
+ projects: readonly ProjectEntry[],
+ chats: readonly ChatEntry[],
+ archived: readonly ChatEntry[],
+): Map<string, ProjectStats> {
+ const stats = new Map<string, ProjectStats>(
+ projects.map((project) => [project.id, { chats: 0, archived: 0, lastActive: project.updatedAt }]),
+ );
+ for (const chat of chats) {
+ const entry = chat.projectId ? stats.get(chat.projectId) : undefined;
+ if (!entry) continue;
+ entry.chats += 1;
+ entry.lastActive = Math.max(entry.lastActive, chat.updatedAt);
+ }
+ for (const chat of archived) {
+ const entry = chat.projectId ? stats.get(chat.projectId) : undefined;
+ if (entry) entry.archived += 1;
+ }
+ return stats;
+}
+
+export function sortProjects<T extends ProjectEntry>(
+ projects: readonly T[],
+ sort: ProjectSort,
+ stats: ReadonlyMap<string, ProjectStats>,
+ pinned: ReadonlySet<string>,
+ locale?: string,
+): T[] {
+ const collate = new Intl.Collator(locale, { numeric: true, sensitivity: "base" }).compare;
+ const value = (project: T) => {
+ const entry = stats.get(project.id);
+ if (sort.key === "chats") return entry?.chats ?? 0;
+ if (sort.key === "name") return 0;
+ return projectTime(project, entry, sort.key);
+ };
+ return [...projects].sort((a, b) => {
+ const byPin = Number(pinned.has(b.id)) - Number(pinned.has(a.id));
+ if (byPin) return byPin;
+ const ascending = sort.key === "name" ? collate(a.name, b.name) : value(a) - value(b);
+ return (sort.desc ? -ascending : ascending) || collate(a.name, b.name);
+ });
+}
+
+export type MixedEntry<C, P, S> =
+ | { kind: "chat"; item: C }
+ | { kind: "project"; item: P }
+ | { kind: "section"; item: S };
+
+/** All: chats, projects and sections as one list on the chat sort. Pinned chats and projects
+ * lead when `pinnedFirst`. */
+export function mixEntries<
+ C extends ChatEntry,
+ P extends ProjectEntry,
+ S extends SectionEntry,
+>(
+ chats: readonly C[],
+ projects: readonly P[],
+ sections: readonly S[],
+ options: {
+ sort: ChatSort;
+ projectStats: ReadonlyMap<string, ProjectStats>;
+ sectionStats: ReadonlyMap<string, SectionStats>;
+ pinned: ReadonlySet<string>;
+ pinnedProjects: ReadonlySet<string>;
+ pinnedFirst: boolean;
+ locale?: string;
+ },
+): MixedEntry<C, P, S>[] {
+ const { sort, pinnedFirst } = options;
+ const collate = new Intl.Collator(options.locale, { numeric: true, sensitivity: "base" }).compare;
+ const rows = [
+ ...chats.map((item) => ({
+ entry: { kind: "chat", item } as const,
+ name: item.title,
+ time: sort.key === "name" ? 0 : chatTime(item, sort.key),
+ pin: options.pinned.has(item.id),
+ })),
+ ...projects.map((item) => ({
+ entry: { kind: "project", item } as const,
+ name: item.name,
+ time:
+ sort.key === "name" ? 0 : projectTime(item, options.projectStats.get(item.id), sort.key),
+ pin: options.pinnedProjects.has(item.id),
+ })),
+ ...sections.map((item) => ({
+ entry: { kind: "section", item } as const,
+ name: item.name,
+ time:
+ sort.key === "name" ? 0 : sectionTime(item, options.sectionStats.get(item.id), sort.key),
+ pin: false,
+ })),
+ ];
+ rows.sort((a, b) => {
+ if (pinnedFirst && a.pin !== b.pin) return a.pin ? -1 : 1;
+ const ascending = sort.key === "name" ? collate(a.name, b.name) : a.time - b.time;
+ return (sort.desc ? -ascending : ascending) || collate(a.name, b.name);
+ });
+ return rows.map((row) => row.entry);
+}
+
+export interface SectionStats {
+ chats: number;
+ projects: number;
+ lastActive: number;
+}
+
+export function sectionStats(
+ sections: readonly { id: string }[],
+ chats: readonly ChatEntry[],
+ sectionOf: ReadonlyMap<string, string>,
+ projectSectionOf: ReadonlyMap<string, string>,
+ projectIds: ReadonlySet<string>,
+): Map<string, SectionStats> {
+ const out = new Map<string, SectionStats>(
+ sections.map((section) => [section.id, { chats: 0, projects: 0, lastActive: 0 }]),
+ );
+ for (const chat of chats) {
+ const stats = out.get(sectionOf.get(chat.id) ?? "");
+ if (!stats) continue;
+ stats.chats += 1;
+ stats.lastActive = Math.max(stats.lastActive, chat.updatedAt);
+ }
+ for (const [projectId, sectionId] of projectSectionOf) {
+ const stats = out.get(sectionId);
+ if (stats && projectIds.has(projectId)) stats.projects += 1;
+ }
+ return out;
+}
+
+export interface SectionEntry {
+ id: string;
+ name: string;
+ createdAt?: number;
+ modifiedAt?: number;
+}
+
+/** "updated" is its latest chat; "modified" its own last edit, or that chat if later. */
+export function sectionTime(
+ section: SectionEntry,
+ stats: SectionStats | undefined,
+ field: DateField,
+): number {
+ const lastActive = stats?.lastActive ?? 0;
+ if (field === "created") return section.createdAt ?? 0;
+ if (field === "modified") return Math.max(section.modifiedAt ?? 0, lastActive);
+ return lastActive;
+}
+
+export function sortSections<T extends SectionEntry>(
+ sections: readonly T[],
+ sort: SectionSort,
+ stats: ReadonlyMap<string, SectionStats>,
+ locale?: string,
+): T[] {
+ const collate = new Intl.Collator(locale, { numeric: true, sensitivity: "base" }).compare;
+ const value = (section: T) => {
+ const entry = stats.get(section.id);
+ if (sort.key === "chats") return entry?.chats ?? 0;
+ if (sort.key === "name") return 0;
+ return sectionTime(section, entry, sort.key);
+ };
+ return [...sections].sort((a, b) => {
+ const ascending = sort.key === "name" ? collate(a.name, b.name) : value(a) - value(b);
+ return (sort.desc ? -ascending : ascending) || collate(a.name, b.name);
+ });
+}
+
+export type DateBucket =
+ | { kind: "today" }
+ | { kind: "yesterday" }
+ | { kind: "week" }
+ | { kind: "month" }
+ | { kind: "older"; year: number; month: number };
+
+const DAY_MS = 86_400_000;
+
+function startOfDay(ms: number): number {
+ const date = new Date(ms);
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
+}
+
+export function dateBucket(ts: number, now: number = Date.now()): DateBucket {
+ // Rounded: DST days are 23 or 25 hours long.
+ const days = Math.round((startOfDay(now) - startOfDay(ts)) / DAY_MS);
+ if (days <= 0) return { kind: "today" };
+ if (days === 1) return { kind: "yesterday" };
+ if (days < 7) return { kind: "week" };
+ if (days < 30) return { kind: "month" };
+ const date = new Date(ts);
+ return { kind: "older", year: date.getFullYear(), month: date.getMonth() };
+}
+
+export function dateBucketKey(bucket: DateBucket): string {
+ return bucket.kind === "older" ? `older:${bucket.year}-${bucket.month}` : bucket.kind;
+}
+
+export interface ChatGroup<T> {
+ key: string;
+ items: T[];
+ projectId?: string | null;
+ sectionId?: string | null;
+ bucket?: DateBucket;
+ pinned?: boolean;
+}
+
+/** Keeps input order within groups. Date groups run newest first (or `oldestFirst`) regardless
+ * of sort; other groups follow their first chat, "none" last. `pinned` adds a leading group. */
+export function groupChats<T extends ChatEntry>(
+ chats: readonly T[],
+ by: ChatGroupBy,
+ options: {
+ time?: DateField;
+ oldestFirst?: boolean;
+ now?: number;
+ pinned?: ReadonlySet<string>;
+ sectionOf?: ReadonlyMap<string, string>;
+ } = {},
+): ChatGroup<T>[] {
+ if (by === "none") return chats.length ? [{ key: "all", items: [...chats] }] : [];
+ const { time = "updated", oldestFirst = false, now = Date.now(), pinned, sectionOf } = options;
+ const pinnedItems = pinned ? chats.filter((chat) => pinned.has(chat.id)) : [];
+ const rest = pinnedItems.length ? chats.filter((chat) => !pinned?.has(chat.id)) : chats;
+ const groups = new Map<string, { group: ChatGroup<T>; latest: number }>();
+ for (const chat of rest) {
+ const ts = chatTime(chat, time);
+ let key: string;
+ let group: Omit<ChatGroup<T>, "items">;
+ if (by === "project") {
+ const projectId = chat.projectId || null;
+ key = `project:${projectId ?? NO_PROJECT}`;
+ group = { key, projectId };
+ } else if (by === "section") {
+ const sectionId = sectionOf?.get(chat.id) || null;
+ key = `section:${sectionId ?? NO_SECTION}`;
+ group = { key, sectionId };
+ } else {
+ const bucket = dateBucket(ts, now);
+ key = dateBucketKey(bucket);
+ group = { key, bucket };
+ }
+ let existing = groups.get(key);
+ if (!existing) {
+ existing = { group: { ...group, items: [] }, latest: ts };
+ groups.set(key, existing);
+ }
+ existing.latest = Math.max(existing.latest, ts);
+ existing.group.items.push(chat);
+ }
+ const out = [...groups.values()];
+ if (by === "date") {
+ out.sort((a, b) => (oldestFirst ? a.latest - b.latest : b.latest - a.latest));
+ } else {
+ const outside = ({ group }: { group: ChatGroup<T> }) =>
+ Number(by === "project" ? group.projectId === null : group.sectionId === null);
+ out.sort((a, b) => outside(a) - outside(b));
+ }
+ const grouped = out.map(({ group }) => group);
+ return pinnedItems.length
+ ? [{ key: "pinned", pinned: true, items: pinnedItems }, ...grouped]
+ : grouped;
+}
+
+export function modelFacets(
+ chats: readonly ChatEntry[],
+ models: ReadonlyMap<string, string[]>,
+): { model: string; count: number }[] {
+ const counts = new Map<string, number>();
+ for (const chat of chats) {
+ for (const model of new Set(models.get(chat.id) ?? [])) {
+ counts.set(model, (counts.get(model) ?? 0) + 1);
+ }
+ }
+ return [...counts.entries()]
+ .map(([model, count]) => ({ model, count }))
+ .sort((a, b) => b.count - a.count || a.model.localeCompare(b.model));
+}
+
+/** Model ids per chat row; a compare pair is keyed by its pair id. */
+export function modelsByChat(
+ chats: readonly { id: string; modelIds?: readonly string[] }[],
+): Map<string, string[]> {
+ const out = new Map<string, string[]>();
+ for (const chat of chats) {
+ if (chat.modelIds?.length) out.set(chat.id, [...chat.modelIds]);
+ }
+ return out;
+}
+
+export function validateChatsSection(value: unknown): ChatsSection | undefined {
+ return CHATS_SECTIONS.find((section) => section === value);
+}
+
+export interface ChatContents {
+ messages: number;
+}
+
+/** Messages along the shown branch: from the newest message back through its parents. */
+export function summarizeChatMessages(
+ messages: readonly {
+ id: string;
+ parentId?: string | null;
+ role?: string;
+ createdAt: number;
+ }[],
+): ChatContents {
+ const byId = new Map(messages.map((message) => [message.id, message]));
+ const branched = messages.some((message) => message.parentId);
+ let path: (typeof messages)[number][] = [...messages];
+ if (branched && messages.length > 0) {
+ path = [];
+ const seen = new Set<string>();
+ let at = messages.reduce((a, b) => (b.createdAt > a.createdAt ? b : a)) as
+ | (typeof messages)[number]
+ | undefined;
+ while (at && !seen.has(at.id)) {
+ seen.add(at.id);
+ path.push(at);
+ at = at.parentId ? byId.get(at.parentId) : undefined;
+ }
+ }
+ return {
+ messages: path.filter((message) => message.role === "user" || message.role === "assistant")
+ .length,
+ };
+}
diff --git a/studio/frontend/src/features/library/chats/prefs-store.ts b/studio/frontend/src/features/library/chats/prefs-store.ts
new file mode 100644
index 00000000000..63dfdef36f9
--- /dev/null
+++ b/studio/frontend/src/features/library/chats/prefs-store.ts
@@ -0,0 +1,59 @@
+// 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 { create } from "zustand";
+import { persist } from "zustand/middleware";
+import type { LibraryView } from "../settings-store";
+import type { ChatGroupBy, ChatSort, DateField, ProjectSort, SectionSort } from "./model";
+
+export const LIBRARY_CHATS_PREFS_STORAGE_KEY = "unsloth_library_chats_prefs";
+
+export interface ChatsPrefs {
+ view: LibraryView;
+ sort: ChatSort;
+ projectSort: ProjectSort;
+ sectionSort: SectionSort;
+ dateField: DateField;
+ groupBy: ChatGroupBy;
+ pinnedFirst: boolean;
+}
+
+export const DEFAULT_CHATS_PREFS: ChatsPrefs = {
+ view: "list",
+ sort: { key: "modified", desc: true },
+ projectSort: { key: "modified", desc: true },
+ sectionSort: { key: "modified", desc: true },
+ dateField: "modified",
+ groupBy: "date",
+ pinnedFirst: true,
+};
+
+// Separate from the Library store so file-tab view and sort settings never apply to chats.
+export const useChatsPrefsStore = create<ChatsPrefs & { set: (patch: Partial<ChatsPrefs>) => void }>()(
+ persist(
+ (set) => ({
+ ...DEFAULT_CHATS_PREFS,
+ set: (patch) => set(patch),
+ }),
+ {
+ name: LIBRARY_CHATS_PREFS_STORAGE_KEY,
+ version: 3,
+ // v2: list is the default view. v3: Last modified is the default date, so an untouched
+ // Last active moves with it.
+ migrate: (persisted, version) => {
+ const saved = { ...((persisted ?? {}) as Partial<ChatsPrefs>) };
+ if (version < 2) saved.view = "list";
+ if (version < 3) {
+ const modified = { key: "modified", desc: true } as const;
+ const untouched = (sort?: { key: string; desc: boolean }) =>
+ !sort || (sort.key === "updated" && sort.desc);
+ if (!saved.dateField || saved.dateField === "updated") saved.dateField = "modified";
+ if (untouched(saved.sort)) saved.sort = modified;
+ if (untouched(saved.projectSort)) saved.projectSort = modified;
+ if (untouched(saved.sectionSort)) saved.sectionSort = modified;
+ }
+ return saved;
+ },
+ },
+ ),
+);
diff --git a/studio/frontend/src/features/library/components/library-cards.tsx b/studio/frontend/src/features/library/components/library-cards.tsx
index 8f2965ead25..efff5792e08 100644
--- a/studio/frontend/src/features/library/components/library-cards.tsx
+++ b/studio/frontend/src/features/library/components/library-cards.tsx
@@ -18,14 +18,17 @@ import { formatCardTime, formatItemCount } from "../format";
import { useColumnCount, useLibraryThumbnail, useSeen } from "../hooks";
import { useLibraryActions } from "../actions-context";
import { CARD_COLUMNS, useLibrarySettingsStore } from "../settings-store";
-import { GLASS_CONTROL, GLASS_SURFACE, OVERLAY_CONTROL, RAISED_SURFACE } from "../surface";
+import {
+ CARD_SHADOW,
+ GLASS_CONTROL,
+ GLASS_SURFACE,
+ OVERLAY_CONTROL,
+ RAISED_SURFACE,
+} from "../surface";
import { CardSelectionContext } from "./card-selection";
import { LibraryActionsMenu } from "./library-actions";
-const CARD_SHADOW =
- "shadow-[0_1px_2px_rgba(0,0,0,0.04),0_4px_16px_rgba(0,0,0,0.06)] dark:shadow-none";
-
-const CARD_SURFACE = cn(
+export const CARD_SURFACE = cn(
RAISED_SURFACE,
CARD_SHADOW,
"group-hover/library-card:bg-neutral-100 group-hover/library-card:shadow-none dark:group-hover/library-card:bg-accent/60",
@@ -43,7 +46,7 @@ export function KindIcon({ item, className }: { item: LibraryItem; className?: s
}
// Audio and code glyphs are thin line art, so they get a larger size.
-const CARD_ICON_CLASS = "size-7";
+export const CARD_ICON_CLASS = "size-7";
const LARGE_CARD_ICON_CLASS = "size-8.5";
function cardIconClass(item: LibraryItem): string {
@@ -252,6 +255,9 @@ function FolderCard({
);
}
+// Extra row spacing only; card width is unchanged.
+const CARD_ROW_GAP = "gap-y-6";
+
function useCardColumns(container: RefObject<HTMLDivElement | null>): number {
const { minWidth, max } = CARD_COLUMNS[useLibrarySettingsStore((s) => s.cardSize)];
return useColumnCount(container, minWidth, max);
@@ -273,7 +279,7 @@ export function Masonry<T>({
return (
<div ref={container} className="flex items-start gap-5">
{buckets.map((bucket, column) => (
- <div key={column} className="flex min-w-0 flex-1 flex-col gap-5">
+ <div key={column} className={cn("flex min-w-0 flex-1 flex-col", CARD_ROW_GAP)}>
{bucket.map((item) => (
<div key={getKey(item)}>{render(item)}</div>
))}
@@ -283,6 +289,20 @@ export function Masonry<T>({
);
}
+export function CardGrid({ children }: { children: ReactNode }) {
+ const container = useRef<HTMLDivElement>(null);
+ const columns = useCardColumns(container);
+ return (
+ <div
+ ref={container}
+ className={cn("grid gap-x-5", CARD_ROW_GAP)}
+ style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
+ >
+ {children}
+ </div>
+ );
+}
+
export function FolderGrid({
folders,
counts,
@@ -290,18 +310,12 @@ export function FolderGrid({
folders: LibraryFolder[];
counts: Map<string, number>;
}) {
- const container = useRef<HTMLDivElement>(null);
- const columns = useCardColumns(container);
return (
- <div
- ref={container}
- className="grid gap-5"
- style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
- >
+ <CardGrid>
{folders.map((folder) => (
<FolderCard key={folder.id} folder={folder} itemCount={counts.get(folder.id) ?? 0} />
))}
- </div>
+ </CardGrid>
);
}
diff --git a/studio/frontend/src/features/library/components/library-header.tsx b/studio/frontend/src/features/library/components/library-header.tsx
index 7d0d69c3de3..d1f725279f5 100644
--- a/studio/frontend/src/features/library/components/library-header.tsx
+++ b/studio/frontend/src/features/library/components/library-header.tsx
@@ -167,19 +167,26 @@ export function LibraryHeader({
tabs: { items: HeaderTab[]; active: string; onChange: (key: string) => void } | null;
}) {
const controlsRef = useRef<HTMLDivElement>(null);
+ const titleRef = useRef<HTMLDivElement>(null);
const rowRef = useRef<HTMLDivElement>(null);
const [controlsWidth, setControlsWidth] = useState(0);
const [covered, setCovered] = useState(false);
+ const [stuck, setStuck] = useState(false);
useEffect(() => {
const controlsNode = controlsRef.current;
const row = rowRef.current;
- if (!controlsNode || !row) return;
+ const titleNode = titleRef.current;
+ if (!controlsNode || !row || !titleNode) return;
let frame = 0;
const update = () => {
frame = 0;
setControlsWidth(controlsNode.getBoundingClientRect().width);
- setCovered(row.getBoundingClientRect().top < controlsNode.getBoundingClientRect().bottom);
+ const top = row.getBoundingClientRect().top;
+ setCovered(top < controlsNode.getBoundingClientRect().bottom);
+ // Stuck once the title scrolls on past the row's margin.
+ const gap = top - titleNode.getBoundingClientRect().bottom;
+ setStuck(gap > Number.parseFloat(getComputedStyle(row).marginTop) + 1);
};
const schedule = () => {
if (!frame) frame = requestAnimationFrame(update);
@@ -207,6 +214,7 @@ export function LibraryHeader({
</div>
</div>
<div
+ ref={titleRef}
className="flex h-9 min-w-0 items-center"
style={{ paddingRight: controlsWidth + GAP_PX }}
>
@@ -214,7 +222,8 @@ export function LibraryHeader({
</div>
<div
ref={rowRef}
- className="sticky top-0 z-20 -mx-6 mt-2 bg-background px-6 py-4 sm:-mx-10 sm:px-10"
+ data-stuck={stuck || undefined}
+ className="library-header-row sticky top-0 z-20 -mx-6 mt-2 bg-background px-6 py-4 transition-shadow sm:-mx-10 sm:px-10"
>
{tabs ? (
<div className="pl-3">
diff --git a/studio/frontend/src/features/library/components/library-list.tsx b/studio/frontend/src/features/library/components/library-list.tsx
index aab56740dbd..9239ddf6df7 100644
--- a/studio/frontend/src/features/library/components/library-list.tsx
+++ b/studio/frontend/src/features/library/components/library-list.tsx
@@ -22,6 +22,8 @@ function targetKey(target: LibraryTarget): string {
}
const ROW_INSET = "pl-4 pr-6";
+// Gap, not padding, so each row's hover area keeps its width.
+export const LIST_ROW_GAP = "gap-1";
const CELL = "hidden text-ui-13 text-muted-foreground sm:block";
const ACTIVITY_COLUMN = "w-48 shrink-0";
@@ -30,6 +32,7 @@ const SIZE_COLUMN = "w-28 shrink-0";
const ACTIVITY_COLUMNS: [LibrarySortKey, TranslationKey, string][] = [
["modified", "library.list.lastActivity", ACTIVITY_COLUMN],
];
+export const FILE_LIST_COLUMNS = { cell: CELL, modified: MODIFIED_COLUMN, size: SIZE_COLUMN };
const COLUMNS: [LibrarySortKey, TranslationKey, string][] = [
["modified", "library.list.modifiedColumn", MODIFIED_COLUMN],
["size", "library.preview.size", SIZE_COLUMN],
@@ -176,6 +179,8 @@ export function LibraryList({
sort,
onSortChange,
activity,
+ leading,
+ favoriteMarks = true,
}: {
folders: LibraryFolder[];
items: LibraryItem[];
@@ -185,6 +190,9 @@ export function LibraryList({
sort: LibrarySortState;
onSortChange: (key: LibrarySortKey) => void;
activity: boolean;
+ /** Rows listed first, with own menus and no selection (Favorites' starred chats). */
+ leading?: ReactNode;
+ favoriteMarks?: boolean;
}) {
const t = useT();
const actions = useLibraryActions();
@@ -238,7 +246,8 @@ export function LibraryList({
<span className="w-8 shrink-0" />
</div>
</div>
- <div className="mt-1 flex flex-col">
+ <div className={cn("mt-1 flex flex-col", LIST_ROW_GAP)}>
+ {leading}
{folders.map((folder) => (
<Row
key={folder.id}
@@ -281,7 +290,7 @@ export function LibraryList({
{t(modelLabelKey(item)!)}
</span>
)}
- {item.favorite && (
+ {favoriteMarks && item.favorite && (
<HugeiconsIcon
icon={StarPointedIcon}
aria-label={t("library.list.favorite")}
diff --git a/studio/frontend/src/features/library/components/library-toolbar.tsx b/studio/frontend/src/features/library/components/library-toolbar.tsx
index 2c2001d1ffc..4e10b4bea20 100644
--- a/studio/frontend/src/features/library/components/library-toolbar.tsx
+++ b/studio/frontend/src/features/library/components/library-toolbar.tsx
@@ -28,17 +28,18 @@ import {
Upload01Icon,
} from "@hugeicons/core-free-icons";
import { type TranslationKey, useT } from "@/i18n";
+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { SheetIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
import { cn } from "@/lib/utils";
import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
-import { ArrowDownUpIcon, ChevronDownIcon } from "lucide-react";
+import { ArrowDownUpIcon } from "lucide-react";
import type { LibrarySource } from "../api";
import type { LibraryTypeFilter } from "../file-kind";
import { EMPTY_FILTERS, type LibraryFilters, filtersActive } from "../filters";
import type { LibrarySortKey, LibraryView } from "../settings-store";
const ICON = "size-icon";
-const ROUND_BUTTON =
+export const ROUND_BUTTON =
"flex size-9 shrink-0 items-center justify-center rounded-full text-foreground outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring data-[active=true]:bg-white data-[active=true]:shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:data-[active=true]:bg-card dark:data-[active=true]:shadow-none data-open:bg-muted";
interface MenuOption<T extends string> {
@@ -62,7 +63,7 @@ const TYPE_OPTIONS: MenuOption<LibraryTypeFilter>[] = [
{ value: "pdfs", label: "library.toolbar.pdfs", icon: Pdf01Icon },
];
-const VIEW_OPTIONS = [
+export const VIEW_OPTIONS = [
{ value: "grid", label: "library.toolbar.gridView", icon: GridViewIcon },
{ value: "list", label: "library.toolbar.listView", icon: LeftToRightListBulletIcon },
] satisfies MenuOption<LibraryView>[];
@@ -139,7 +140,7 @@ function FilterMenu({
<HugeiconsIcon icon={FilterMailIcon} strokeWidth={1.75} className="size-5" />
</button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" sideOffset={4} className="w-max min-w-36">
+ <DropdownMenuContent align="end" sideOffset={4} className="library-menu w-max min-w-36">
{showTypes && (
<>
<DropdownMenuLabel className="px-3 pb-1 pt-2 text-muted-foreground font-normal">
@@ -176,7 +177,7 @@ function FilterMenu({
);
}
-function SortRadio({
+export function SortRadio({
label,
checked,
onSelect,
@@ -229,7 +230,7 @@ function SortMenu({
{value === "default" || !current ? t("library.toolbar.sort") : t(current.label)}
</button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" sideOffset={4} className="w-max min-w-36">
+ <DropdownMenuContent align="start" sideOffset={4} className="library-menu w-max min-w-36">
{options.map(({ value: option, label }) => (
<SortRadio
key={option}
@@ -286,10 +287,10 @@ function NewMenu({ onSelect }: { onSelect: (action: NewAction) => void }) {
className="flex h-9 shrink-0 items-center gap-1.5 rounded-full bg-foreground pl-4 pr-3 font-medium text-ui-14 text-background outline-none transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring"
>
{t("common.new")}
- <ChevronDownIcon className="size-4" strokeWidth={2} />
+ <HugeiconsIcon icon={ChevronDownStandardIcon} strokeWidth={2} className="size-4" />
</button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuContent align="end" className="library-menu w-44">
{NEW_OPTIONS.map(({ value, label, icon }) => (
<DropdownMenuItem key={value} onSelect={() => onSelect(value)}>
<HugeiconsIcon icon={icon} strokeWidth={1.75} className={ICON} />
diff --git a/studio/frontend/src/features/library/index.ts b/studio/frontend/src/features/library/index.ts
index b3111e827b4..466e23b176c 100644
--- a/studio/frontend/src/features/library/index.ts
+++ b/studio/frontend/src/features/library/index.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
export { useLibraryChatHandoffStore } from "./chat-handoff-store";
+export { LIBRARY_CHATS_PREFS_STORAGE_KEY } from "./chats/prefs-store";
export { useLibraryFavorites } from "./favorites-store";
export { chatAboutMedia, startLibraryChat } from "./start-chat";
export { revealInFolder, useRevealLabel } from "./reveal";
diff --git a/studio/frontend/src/features/library/library-page.tsx b/studio/frontend/src/features/library/library-page.tsx
index e4e19ad8c10..7eeaf61f713 100644
--- a/studio/frontend/src/features/library/library-page.tsx
+++ b/studio/frontend/src/features/library/library-page.tsx
@@ -36,7 +36,7 @@ import {
Upload01Icon,
} from "@hugeicons/core-free-icons";
import { ChevronRightStandardIcon } from "@/lib/chevron-icons";
-import { StarPointedIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
+import { MessageCircleIcon, StarPointedIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate, useRouter, useSearch } from "@tanstack/react-router";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -59,6 +59,9 @@ import {
LibraryActionsProvider,
type LibraryTarget,
} from "./actions-context";
+import { ChatsLibrary } from "./chats/chats-library";
+import { useFavoriteChatMatches } from "./chats/favorites";
+import { useChatFavoritesStore } from "./chats/favorites-store";
import { CardSelectionContext } from "./components/card-selection";
import { FolderGrid, ItemCard, Masonry } from "./components/library-cards";
import { ConfirmDeleteDialog, NameDialog } from "./components/library-dialogs";
@@ -94,6 +97,7 @@ const TAB_LABELS: Record<LibraryTab, TranslationKey> = {
audio: "library.tabs.audio",
models: "library.tabs.models",
all: "library.tabs.all",
+ chats: "library.tabs.chats",
};
type EmptyCopy = [icon: typeof Folder01Icon, title: TranslationKey, description: TranslationKey];
@@ -106,6 +110,7 @@ const EMPTY_COPY: Record<LibraryTab, EmptyCopy> = {
audio: [AudioWave01Icon, "library.empty.audioTitle", "library.empty.audioDescription"],
models: [TestTubeOutlineIcon, "library.empty.modelsTitle", "library.empty.modelsDescription"],
all: [Upload01Icon, "library.empty.suggestedTitle", "library.empty.suggestedDescription"],
+ chats: [MessageCircleIcon, "library.chats.empty.chatsTitle", "library.chats.empty.chatsDescription"],
};
const EMPTY_LINKS = {
@@ -235,9 +240,24 @@ function LibraryView({ search }: { search: LibrarySearch }) {
const [preferred] = useState(() =>
settings.startTab === "last" ? settings.lastTab : settings.startTab,
);
+ // No files or folders: open on Chats, since every file tab is empty. Decided once on load so
+ // the tab does not jump when a file lands later. Starred chats keep a Favorites start.
+ const [emptyOnLoad, setEmptyOnLoad] = useState<boolean | null>(null);
+ if (emptyOnLoad === null && loaded) setEmptyOnLoad(items.length === 0 && folders.length === 0);
+ const hasStarredChats = useChatFavoritesStore(
+ (s) => s.chatIds.length + s.projectIds.length + s.sectionIds.length > 0,
+ );
+ const nothingButChats =
+ emptyOnLoad === true &&
+ tabVisible("chats") &&
+ !(preferred === "favorites" && hasStarredChats);
const tab: LibraryTab =
search.show ??
- (tabVisible(preferred) ? preferred : (LIBRARY_TABS.find(tabVisible) ?? "all"));
+ (nothingButChats
+ ? "chats"
+ : tabVisible(preferred)
+ ? preferred
+ : (LIBRARY_TABS.find(tabVisible) ?? "all"));
const sort = SORT_STATES[search.sort ?? settings.sort];
const folderId = search.folder ?? null;
const folderById = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders]);
@@ -294,6 +314,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
}, [items, folders]);
const needle = query.trim().toLowerCase();
+ const favoriteChats = useFavoriteChatMatches(query, tab === "favorites" && !folderId);
const kindFilter = folderId ? undefined : KIND_TABS[tab];
// Folders have no filter menu, so tab filters do not apply inside them.
@@ -735,6 +756,48 @@ function LibraryView({ search }: { search: LibrarySearch }) {
);
}
+ function renderFavorites() {
+ return (
+ <ChatsLibrary
+ search={{}}
+ embedded={{
+ query,
+ view,
+ render: (entries) =>
+ view === "list" ? (
+ <div className="mt-6">
+ <LibraryList
+ folders={[]}
+ items={visibleItems}
+ counts={counts}
+ selection={selection}
+ onSelectionChange={setSelection}
+ sort={sort}
+ onSortChange={(key) => go({ ...search, sort: sortParam(nextSort(sort, key)) }, true)}
+ activity={false}
+ leading={entries.rows}
+ favoriteMarks={false}
+ />
+ </div>
+ ) : (
+ <div className="mt-6">
+ <CardSelectionContext.Provider value={cardSelection}>
+ <Masonry
+ items={[
+ ...entries.cards,
+ ...visibleItems.map((item) => ({ key: item.id, node: <ItemCard item={item} /> })),
+ ]}
+ getKey={(entry) => entry.key}
+ render={(entry) => entry.node}
+ />
+ </CardSelectionContext.Provider>
+ </div>
+ ),
+ }}
+ />
+ );
+ }
+
function renderBody() {
if (status === "loading" || status === "idle") return <LoadingGrid />;
if (status === "error") {
@@ -753,6 +816,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
}
const empty = visibleItems.length === 0 && visibleFolders.length === 0;
const narrowed = Boolean(needle) || filtersActive(filters);
+ if (favoriteChats > 0) return renderFavorites();
if (empty && narrowed) {
return (
<EmptyState
@@ -794,6 +858,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
sort={sort}
onSortChange={(key) => go({ ...search, sort: sortParam(nextSort(sort, key)) }, true)}
activity={tab === "suggested" && !folderId}
+ favoriteMarks={tab !== "favorites"}
/>
</div>
);
@@ -857,6 +922,17 @@ function LibraryView({ search }: { search: LibrarySearch }) {
selectedTargets().filter((t) => t.kind === "folder" || isDeletable(t.item));
const deleteText = pendingDelete ? deleteCopy(pendingDelete) : null;
+ const headerTabs = {
+ items: shownTabs.map((key) => ({ key, label: t(TAB_LABELS[key]) })),
+ active: tab,
+ onChange: (next: string) => go({ show: next as LibraryTab }),
+ };
+
+ // Chats use their own view and data; the file listing, filters and selection never apply.
+ if (tab === "chats" && !folderId) {
+ return <ChatsLibrary search={search} title={title} tabs={headerTabs} />;
+ }
+
return (
<LibraryActionsProvider value={actions}>
<main
@@ -891,15 +967,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
onSettings={() => openSettings("library")}
/>
}
- tabs={
- folderId
- ? null
- : {
- items: shownTabs.map((key) => ({ key, label: t(TAB_LABELS[key]) })),
- active: tab,
- onChange: (next) => go({ show: next as LibraryTab }),
- }
- }
+ tabs={folderId ? null : headerTabs}
/>
<div className="pl-3">{renderBody()}</div>
@@ -964,13 +1032,13 @@ function LibraryView({ search }: { search: LibrarySearch }) {
<HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />
</button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="center" side="top" className="w-48">
+ <DropdownMenuContent align="center" side="top" className="library-menu w-48">
<DropdownMenuSub>
<DropdownMenuSubTrigger className="gap-2.5">
<HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
{t("library.selection.move")}
</DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-[min(--spacing(80),var(--radix-dropdown-menu-content-available-height))] w-56">
+ <DropdownMenuSubContent className="library-menu max-h-[min(--spacing(80),var(--radix-dropdown-menu-content-available-height))] w-56">
<DropdownMenuItem onSelect={() => bulkMove(null)}>
<HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
{t("library.menu.noFolder")}
diff --git a/studio/frontend/src/features/library/search.ts b/studio/frontend/src/features/library/search.ts
index 2e3ea96a0a2..9e2f85f3a0b 100644
--- a/studio/frontend/src/features/library/search.ts
+++ b/studio/frontend/src/features/library/search.ts
@@ -1,6 +1,7 @@
// 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 { type ChatsSection, validateChatsSection } from "./chats/model";
import { LIBRARY_URL_SORTS, type LibraryUrlSort } from "./settings-store";
// Kept apart from the page so the route can validate its URL without loading the page chunk.
@@ -8,6 +9,8 @@ export const LIBRARY_TABS = [
"suggested",
"favorites",
"folders",
+ // Chats show only here and in Favorites (when starred), never in All or file tabs.
+ "chats",
"images",
"videos",
"audio",
@@ -22,6 +25,9 @@ export interface LibrarySearch {
item?: string;
sort?: LibraryUrlSort;
filter?: "files";
+ chatView?: ChatsSection;
+ /** Section page id. Not `section`: the Hub route already uses that name. */
+ chatSection?: string;
}
export function validateLibrarySearch(search: Record<string, unknown>): LibrarySearch {
@@ -34,5 +40,7 @@ export function validateLibrarySearch(search: Record<string, unknown>): LibraryS
? { sort: search.sort as LibraryUrlSort }
: {}),
...(search.filter === "files" ? { filter: "files" as const } : {}),
+ ...(validateChatsSection(search.chatView) ? { chatView: validateChatsSection(search.chatView) } : {}),
+ ...(typeof search.chatSection === "string" ? { chatSection: search.chatSection } : {}),
};
}
diff --git a/studio/frontend/src/features/library/settings-store.ts b/studio/frontend/src/features/library/settings-store.ts
index ecb21b4e562..9e99576f67c 100644
--- a/studio/frontend/src/features/library/settings-store.ts
+++ b/studio/frontend/src/features/library/settings-store.ts
@@ -16,7 +16,7 @@ export interface LibrarySettings {
imageLayout: "masonry" | "square";
showCardDates: boolean;
sort: LibrarySort;
- startTab: "last" | "suggested" | "favorites" | "folders" | "all";
+ startTab: "last" | "suggested" | "favorites" | "folders" | "all" | "chats";
lastTab: LibraryTab;
tabs: Record<LibraryTab, LibraryTabVisibility>;
suggestedLimit: number;
@@ -38,11 +38,12 @@ export const DEFAULT_LIBRARY_SETTINGS: LibrarySettings = {
suggested: "always",
favorites: "always",
folders: "always",
- images: "auto",
+ images: "always",
videos: "auto",
audio: "auto",
models: "auto",
all: "always",
+ chats: "always",
},
suggestedLimit: 40,
showChatAttachments: true,
@@ -81,7 +82,7 @@ interface LibrarySettingsState extends LibrarySettings {
}
/** v1 had one mediaTabs switch for Images, Videos and Audio together; before v3, Fine-tunes
- * always showed. */
+ * always showed; before v4, Images showed only once there were images. */
export function migrateLibrarySettings(persisted: unknown, version: number): Record<string, unknown> {
const state = { ...(persisted as Record<string, unknown>) };
if (version < 2) {
@@ -93,6 +94,10 @@ export function migrateLibrarySettings(persisted: unknown, version: number): Rec
const tabs = state.tabs as Record<string, string> | undefined;
if (tabs?.models === "always") state.tabs = { ...tabs, models: "auto" };
}
+ if (version < 4) {
+ const tabs = state.tabs as Record<string, string> | undefined;
+ if (tabs?.images === "auto") state.tabs = { ...tabs, images: "always" };
+ }
return state;
}
@@ -105,7 +110,7 @@ export const useLibrarySettingsStore = create<LibrarySettingsState>()(
}),
{
name: LIBRARY_SETTINGS_STORAGE_KEY,
- version: 3,
+ version: 4,
migrate: (persisted, version) =>
migrateLibrarySettings(persisted, version) as unknown as LibrarySettingsState,
},
diff --git a/studio/frontend/src/features/library/surface.ts b/studio/frontend/src/features/library/surface.ts
index ffebf04bb82..a719ac45e6e 100644
--- a/studio/frontend/src/features/library/surface.ts
+++ b/studio/frontend/src/features/library/surface.ts
@@ -4,6 +4,9 @@
export const RAISED_SURFACE =
"bg-white shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-card dark:shadow-none";
+export const CARD_SHADOW =
+ "shadow-[0_1px_2px_rgba(0,0,0,0.04),0_4px_16px_rgba(0,0,0,0.06)] dark:shadow-none";
+
export const OVERLAY_CONTROL =
"bg-white shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-neutral-700 dark:shadow-none";
diff --git a/studio/frontend/src/features/settings/components/manage-chats-view.tsx b/studio/frontend/src/features/settings/components/manage-chats-view.tsx
deleted file mode 100644
index af4fae8f108..00000000000
--- a/studio/frontend/src/features/settings/components/manage-chats-view.tsx
+++ /dev/null
@@ -1,524 +0,0 @@
-// 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 {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
-import { Button } from "@/components/ui/button";
-import { Checkbox } from "@/components/ui/checkbox";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import {
- COMBINED_EXPORT_FORMATS_LIST,
- type ConvExportFormat,
- EXPORT_FORMATS_LIST,
- type SidebarItem,
- archiveChatItems,
- deleteChatItems,
- exportBulkConversationsMerged,
- exportBulkConversationsSeparate,
- moveChatItemToProject,
- rangeBetween,
- useChatPreferencesStore,
- useChatProjects,
- useChatRuntimeStore,
- useChatSidebarItems,
- usePinnedChatsStore,
-} from "@/features/chat";
-import { isDownloadCancelled } from "@/lib/native-files";
-import { useLocale, useT } from "@/i18n";
-import { toast } from "@/lib/toast";
-import {
- Archive02Icon,
- Delete02Icon,
- Download01Icon,
- Folder01Icon,
- PinIcon,
-} from "@hugeicons/core-free-icons";
-import { MessageCircleIcon } from "@/lib/hugeicons-derived";
-import { HugeiconsIcon } from "@hugeicons/react";
-import { useNavigate, useRouterState } from "@tanstack/react-router";
-import { useMemo, useRef, useState } from "react";
-import { useSettingsDialogStore } from "../stores/settings-dialog-store";
-
-import { useLibraryProjectLabels } from "./use-library-project-labels";
-import {
- DEFAULT_LIBRARY_FILTERS,
- filterLibraryItems,
- groupLibraryItems,
- type LibraryFilters,
-} from "./data-library";
-import {
- ChatLibraryGroups,
- LibraryRow,
- LibraryToolbar,
-} from "./data-library-controls";
-
-const MANAGE_PAGE_SIZE = 20;
-
-export function ManageChatsView() {
- const t = useT();
- const locale = useLocale();
- const labels = useLibraryProjectLabels();
- const chatCount = (count: number) =>
- t(
- count === 1
- ? "settings.data.library.oneChat"
- : "settings.data.library.chatCount",
- { count },
- );
- const { items } = useChatSidebarItems({ requireMessages: false });
- const { projects } = useChatProjects();
- const navigate = useNavigate();
- const closeSettings = useSettingsDialogStore((s) => s.closeDialog);
- const storeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
- // Open chat id from the route: compare panes only live in the search params.
- const openChatId = useRouterState({
- select: (s) => {
- if (!s.location.pathname.startsWith("/chat")) return undefined;
- const search = s.location.search as Record<string, string | undefined>;
- return search.thread ?? search.compare ?? storeThreadId ?? undefined;
- },
- });
- const pinnedIds = usePinnedChatsStore((s) => s.pinnedIds);
- const setPinned = usePinnedChatsStore((s) => s.setPinned);
- const alwaysDeleteChatFiles = useChatPreferencesStore(
- (s) => s.alwaysDeleteChatFiles,
- );
-
- const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
- const [visibleCount, setVisibleCount] = useState(MANAGE_PAGE_SIZE);
- const [confirmingDelete, setConfirmingDelete] = useState(false);
- const [busy, setBusy] = useState(false);
- const lastToggledId = useRef<string | null>(null);
-
- const [filters, setFilters] = useState(DEFAULT_LIBRARY_FILTERS);
- const projectNames = useMemo(
- () => new Map(projects.map((p) => [p.id, p.name])),
- [projects],
- );
- const filtered = useMemo(
- () => filterLibraryItems(items, filters, projectNames, labels, locale),
- [items, filters, projectNames, labels, locale],
- );
- const visible = groupLibraryItems(
- filtered.slice(0, visibleCount),
- projectNames,
- labels,
- ).flatMap((group) => group.items);
- const selectedItems = items.filter((item) => selectedIds.has(item.id));
-
- function changeFilters(next: LibraryFilters) {
- setFilters(next);
- setSelectedIds(new Set());
- lastToggledId.current = null;
- setVisibleCount(MANAGE_PAGE_SIZE);
- }
- const selectedCount = selectedItems.length;
- const visibleSelectedCount = visible.filter((item) =>
- selectedIds.has(item.id),
- ).length;
- const allVisibleSelected =
- visible.length > 0 && visibleSelectedCount === visible.length;
- const allSelectedPinned =
- selectedCount > 0 &&
- selectedItems.every((item) => pinnedIds.includes(item.id));
-
- function toggleRow(index: number, shiftKey: boolean) {
- if (busy) return;
- const rowId = visible[index].id;
- const target = !selectedIds.has(rowId);
- const anchorId = lastToggledId.current;
- // Anchor on the chat id, not the row index: the list re-sorts by updatedAt,
- // so an index anchor would range over rows the user never picked.
- const ids =
- shiftKey && anchorId !== null
- ? rangeBetween(
- visible.map((item) => item.id),
- anchorId,
- rowId,
- )
- : [rowId];
- setSelectedIds((prev) => {
- const next = new Set(prev);
- for (const id of ids) {
- if (target) next.add(id);
- else next.delete(id);
- }
- return next;
- });
- lastToggledId.current = rowId;
- }
-
- function toggleAllVisible() {
- if (busy) return;
- setSelectedIds((previous) => {
- const next = new Set(previous);
- for (const item of visible) {
- if (allVisibleSelected) next.delete(item.id);
- else next.add(item.id);
- }
- return next;
- });
- lastToggledId.current = null;
- }
-
- function openChat(item: SidebarItem) {
- // Carry the row's project, as the sidebar does: without it ChatPage briefly
- // runs the chat under the project it was already on.
- const project = item.projectId ? { project: item.projectId } : {};
- navigate({
- to: "/chat",
- search:
- item.type === "single"
- ? { thread: item.id, ...project }
- : { compare: item.id, ...project },
- });
- closeSettings();
- }
-
- function resetView(view: { newThreadNonce: string }) {
- navigate({ to: "/chat", search: { new: view.newThreadNonce } });
- }
-
- async function run(
- action: () => Promise<void>,
- success: string,
- failure: string,
- ) {
- setBusy(true);
- try {
- await action();
- setSelectedIds(new Set());
- toast.success(success);
- } catch (err) {
- toast.error(failure, {
- description: err instanceof Error ? err.message : undefined,
- });
- } finally {
- setBusy(false);
- }
- }
-
- const handleArchive = () =>
- run(
- () => archiveChatItems(selectedItems, openChatId, resetView),
- t(
- selectedCount === 1
- ? "settings.data.archivedOneChat"
- : "settings.data.archivedChatCount",
- { count: selectedCount },
- ),
- t("settings.data.failedToArchiveChats"),
- );
-
- const handleDelete = () =>
- run(
- () =>
- // Honour the same preference as the sidebar delete, or the selected
- // chats leave orphan sandbox folders behind.
- deleteChatItems(selectedItems, openChatId, resetView, {
- deleteFiles: alwaysDeleteChatFiles,
- }),
- t("settings.data.library.deletedChats", { count: selectedCount }),
- t("settings.data.library.deleteFailed"),
- );
-
- const handleMove = (projectId: string | null) =>
- run(
- async () => {
- await Promise.all(
- selectedItems.map((item) => moveChatItemToProject(item, projectId)),
- );
- },
- projectId
- ? t("settings.data.library.movedChatsToProject", {
- count: selectedCount,
- project: projectNames.get(projectId) ?? labels.unavailableProject,
- })
- : t("settings.data.library.movedChatsToRecents", {
- count: selectedCount,
- }),
- t("settings.data.library.moveFailed"),
- );
-
- function handleTogglePin() {
- const ids = selectedItems.map((item) => item.id);
- setPinned(ids, !allSelectedPinned);
- toast.success(
- t(
- allSelectedPinned
- ? "settings.data.library.unpinnedChats"
- : "settings.data.library.pinnedChats",
- { count: ids.length },
- ),
- );
- setSelectedIds(new Set());
- }
-
- async function handleExport(format: ConvExportFormat, merged: boolean) {
- const threadIds = selectedItems.flatMap(
- (item) => item.threadIds ?? [item.id],
- );
- const basename = `selected-chats-${new Date().toISOString().slice(0, 10)}`;
- try {
- if (merged) {
- await exportBulkConversationsMerged(threadIds, format, basename);
- } else {
- await exportBulkConversationsSeparate(threadIds, format, basename);
- }
- } catch (error) {
- if (!isDownloadCancelled(error))
- toast.error(t("settings.data.exportFailed"));
- }
- }
-
- const actionsDisabled = busy || selectedCount === 0;
-
- return (
- <div className="flex flex-col gap-4">
- <LibraryToolbar
- filters={filters}
- onChange={changeFilters}
- placeholder={t("settings.data.library.searchChats")}
- projects={projectNames}
- disabled={busy}
- />
- <div className="flex flex-wrap items-center gap-2">
- <div className="flex flex-1 items-center gap-3 px-1">
- <Checkbox
- checked={
- allVisibleSelected
- ? true
- : visibleSelectedCount > 0
- ? "indeterminate"
- : false
- }
- disabled={busy || visible.length === 0}
- onCheckedChange={toggleAllVisible}
- aria-label={t("settings.data.library.selectAll")}
- title={t("settings.data.library.selectAll")}
- />
- <span className="text-xs text-muted-foreground">
- {selectedCount > 0
- ? t("settings.data.library.selectedChats", {
- count: selectedCount,
- })
- : chatCount(filtered.length)}
- </span>
- </div>
- {selectedCount > 0 && (
- <>
- <DropdownMenu>
- <DropdownMenuTrigger asChild={true}>
- <Button variant="outline" size="sm" disabled={actionsDisabled}>
- <HugeiconsIcon
- icon={Folder01Icon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- {t("settings.data.library.move")}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-52">
- <DropdownMenuItem
- disabled={selectedItems.every((item) => !item.projectId)}
- onSelect={() => void handleMove(null)}
- >
- {t("shell.navigation.recents")}
- </DropdownMenuItem>
- {projects.map((project) => (
- <DropdownMenuItem
- key={project.id}
- onSelect={() => void handleMove(project.id)}
- >
- <HugeiconsIcon
- icon={Folder01Icon}
- strokeWidth={1.75}
- className="size-4"
- />
- <span className="truncate">{project.name}</span>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <Button
- variant="outline"
- size="sm"
- disabled={actionsDisabled}
- onClick={handleTogglePin}
- >
- <HugeiconsIcon
- icon={PinIcon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- {allSelectedPinned
- ? t("settings.data.library.unpin")
- : t("settings.data.library.pin")}
- </Button>
- <Button
- variant="outline"
- size="sm"
- disabled={actionsDisabled}
- onClick={() => void handleArchive()}
- >
- <HugeiconsIcon
- icon={Archive02Icon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- {t("settings.data.library.archive")}
- </Button>
- <DropdownMenu>
- <DropdownMenuTrigger asChild={true}>
- <Button variant="outline" size="sm" disabled={actionsDisabled}>
- <HugeiconsIcon
- icon={Download01Icon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- {t("common.export")}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-56">
- {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
- <DropdownMenuItem
- key={`m-${fmt}`}
- onSelect={() => void handleExport(fmt, true)}
- >
- {label} {t("settings.chat.exportCombinedSuffix")}
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
- <DropdownMenuItem
- key={`s-${fmt}`}
- onSelect={() => void handleExport(fmt, false)}
- >
- {label} {t("settings.chat.exportPerChatSuffix")}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <Button
- variant="outline"
- size="sm"
- disabled={actionsDisabled}
- onClick={() => setConfirmingDelete(true)}
- className="text-destructive hover:text-destructive hover:border-destructive/60"
- >
- <HugeiconsIcon
- icon={Delete02Icon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- {t("common.delete")}
- </Button>
- </>
- )}
- </div>
-
- {filtered.length === 0 ? (
- <p
- role="status"
- className="py-8 text-center text-sm text-muted-foreground"
- >
- {t("settings.data.library.noChats")}
- </p>
- ) : (
- <ChatLibraryGroups items={visible} projects={projectNames}>
- {(item) => (
- <LibraryRow
- title={item.title}
- date={
- filters.sort === "updated" ? item.updatedAt : item.createdAt
- }
- onOpen={() => openChat(item)}
- leading={
- <>
- <Checkbox
- checked={selectedIds.has(item.id)}
- disabled={busy}
- onClick={(event) =>
- toggleRow(
- visible.findIndex((row) => row.id === item.id),
- event.shiftKey,
- )
- }
- aria-label={t("settings.data.library.selectItem", {
- title: item.title,
- })}
- />
- <HugeiconsIcon
- icon={MessageCircleIcon}
- className="size-4 shrink-0 text-muted-foreground"
- />
- </>
- }
- />
- )}
- </ChatLibraryGroups>
- )}
- {filtered.length > visibleCount && (
- <div className="flex justify-center">
- <Button
- variant="outline"
- size="sm"
- onClick={() => setVisibleCount((count) => count + MANAGE_PAGE_SIZE)}
- >
- {t("settings.voice.recents.showMore", {
- count: filtered.length - visibleCount,
- })}
- </Button>
- </div>
- )}
-
- <AlertDialog
- open={confirmingDelete}
- onOpenChange={(o) => {
- if (!o) setConfirmingDelete(false);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t("settings.data.library.deleteChatsTitle", {
- count: selectedCount,
- })}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t("settings.data.library.deleteChatsWarning", {
- count: selectedCount,
- })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
- <AlertDialogAction
- variant="destructive"
- onClick={() => {
- setConfirmingDelete(false);
- void handleDelete();
- }}
- >
- {t("common.delete")}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 27860abd330..8a20b8d2169 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -117,6 +117,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"composerSettings.showContext",
"settings.chat.pastedTextThreshold",
"settings.chat.groups.conversations.title",
+ "settings.chat.library.label",
"settings.chat.groups.display.title",
"settings.chat.modelSelection.title",
"settings.chat.currentDate.label",
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index b0a275452df..9e8cafc394a 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -1,6 +1,7 @@
// 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 { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
@@ -33,11 +34,13 @@ import {
Download01Icon,
FileDatabaseIcon,
Folder01Icon,
+ LibrariesIcon,
McpServerIcon,
PencilRulerIcon,
Scroll01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { useNavigate } from "@tanstack/react-router";
import { Columns2Icon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
@@ -145,6 +148,7 @@ const PLUS_MENU_SETTINGS: {
export function ChatTab() {
const t = useT();
+ const navigate = useNavigate();
const plusPins = usePlusMenuPrefsStore((state) => state.pins);
const togglePlusPin = usePlusMenuPrefsStore((state) => state.togglePin);
const autoTitle = useChatRuntimeStore((state) => state.autoTitle);
@@ -352,6 +356,25 @@ export function ChatTab() {
</h1>
</header>
+ <SettingsSection title={t("settings.chat.library.label")} hideHeading>
+ <SettingsRow
+ label={t("settings.chat.library.label")}
+ description={t("settings.chat.library.description")}
+ >
+ <Button
+ variant="outline"
+ className="px-3.5"
+ onClick={() => {
+ useSettingsDialogStore.getState().closeDialog();
+ void navigate({ to: "/library", search: { show: "chats" } });
+ }}
+ >
+ <HugeiconsIcon icon={LibrariesIcon} strokeWidth={1.75} className="size-4" />
+ {t("settings.chat.library.action")}
+ </Button>
+ </SettingsRow>
+ </SettingsSection>
+
<SettingsSection title={t("settings.general.chatDefaults")}>
<ComposerSettings embedded={true} />
<SettingsRow
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index ab9adb1ed54..c56d247c13c 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -95,7 +95,6 @@ import {
type ArchivedMediaKind,
ArchivedMediaView,
} from "../components/archived-media-dialog";
-import { ManageChatsView } from "../components/manage-chats-view";
import { DocumentsRagSection } from "../components/documents-rag-section";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
@@ -186,7 +185,6 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {
// Subpages swap the Data tab body instead of opening nested dialogs.
const [subpage, setSubpage] = useState<
| "main"
- | "manage"
| "archived"
| "archived-images"
| "archived-videos"
@@ -594,35 +592,6 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {
}
};
- if (subpage === "manage") {
- return (
- <div className="settings-page">
- <header className="flex items-center gap-2">
- <button
- type="button"
- onClick={() => setSubpage("main")}
- aria-label={t("settings.data.backToData")}
- className="settings-back-button inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- >
- <ChevronLeftIcon className="size-4 rtl:rotate-180" />
- </button>
- <h1 className="text-xl font-semibold font-heading">
- {t("settings.data.title")}
- </h1>
- </header>
- <div className="flex flex-col gap-1">
- <h2 className="settings-heading text-sm font-semibold">
- {t("settings.data.manageChats")}
- </h2>
- <p className="text-xs text-muted-foreground">
- {t("settings.data.manageChatsDescription")}
- </p>
- </div>
- <ManageChatsView />
- </div>
- );
- }
-
if (subpage === "archived") {
return (
<div className="settings-page">
@@ -765,18 +734,6 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {
</header>
<SettingsSection title={t("settings.data.chatsSection")}>
- <SettingsRow
- label={t("settings.data.manageChats")}
- description={t("settings.data.manageChatsDescription")}
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setSubpage("manage")}
- >
- {t("settings.data.manageAction")}
- </Button>
- </SettingsRow>
<div
data-settings-label={t("settings.data.archives")}
className="py-3"
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index e26ea4979c3..e9bbd723a0b 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -62,6 +62,7 @@ import { loadCloseToTray, updateCloseToTray } from "../api/close-to-tray";
import { loadLaunchAtLogin, updateLaunchAtLogin } from "../api/launch-at-login";
import { useIsAccountOwner } from "@/features/auth";
import {
+ LIBRARY_CHATS_PREFS_STORAGE_KEY,
LIBRARY_SETTINGS_STORAGE_KEY,
LIBRARY_VIEW_STORAGE_KEY,
} from "@/features/library";
@@ -102,6 +103,7 @@ const PREFS_KEYS: string[] = [
"unsloth_sidebar_navigate_open",
LIBRARY_SETTINGS_STORAGE_KEY,
LIBRARY_VIEW_STORAGE_KEY,
+ LIBRARY_CHATS_PREFS_STORAGE_KEY,
// Grouping, sort and the manual row order.
SIDEBAR_ORGANIZATION_STORAGE_KEY,
"unsloth_settings_active_tab",
diff --git a/studio/frontend/src/features/settings/tabs/library-tab.tsx b/studio/frontend/src/features/settings/tabs/library-tab.tsx
index 3a99ff56692..947ba030956 100644
--- a/studio/frontend/src/features/settings/tabs/library-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/library-tab.tsx
@@ -70,6 +70,7 @@ const TAB_LABELS: Record<LibraryTabId, TranslationKey> = {
audio: STORAGE_LABELS.audio,
models: STORAGE_LABELS.fineTunes,
all: "settings.library.all",
+ chats: "library.tabs.chats",
};
const CHOICES: {
@@ -86,7 +87,7 @@ const CHOICES: {
],
startTab: [
["last", "settings.library.lastVisited"],
- ...(["suggested", "favorites", "folders", "all"] as const).map((tab): [typeof tab, TranslationKey] => [tab, TAB_LABELS[tab]]),
+ ...(["suggested", "favorites", "folders", "chats", "all"] as const).map((tab): [typeof tab, TranslationKey] => [tab, TAB_LABELS[tab]]),
],
sort: [
["recent", "settings.library.recent"],
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 477418a7db2..6389006c0e1 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1766,6 +1766,11 @@ export const ar = {
advanced: { title: "إعدادات متقدمة" },
contextTitle: "السياق",
},
+ library: {
+ label: "إدارة المحادثات",
+ description: "ابحث في المحادثات والمشاريع والأقسام، ورتّبها، ونظّمها.",
+ action: "فتح المكتبة",
+ },
projectAttachmentsHint:
"يمكن تغيير هذا الإعداد لكل دردشة من قائمة المرفقات الخاصة بها.",
rememberParamsPerModelHint:
@@ -2037,9 +2042,6 @@ export const ar = {
archivedAudio: "الصوتيات المؤرشفة",
archivedAudioDescription: "اعرض المقاطع الصوتية التي أرشفتها وأدرها.",
manageAction: "إدارة",
- manageChats: "إدارة المحادثات",
- manageChatsDescription:
- "حدد عدة محادثات لنقلها أو تثبيتها أو أرشفتها أو تصديرها أو حذفها.",
exportArchivedChats: "تصدير",
exportingArchivedChats: "جارٍ التصدير...",
exportedOneArchivedChat: "تم تصدير محادثة مؤرشفة واحدة",
@@ -3073,6 +3075,116 @@ export const ar = {
audio: "الصوت",
models: "النماذج المضبوطة",
all: "الكل",
+ chats: "المحادثات",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "المحادثات",
+ projects: "المشاريع",
+ archived: "المؤرشفة",
+ ariaLabel: "أقسام المحادثات",
+ },
+ search: {
+ chats: "البحث في المحادثات",
+ projects: "البحث في المشاريع",
+ archived: "البحث في المحادثات المؤرشفة",
+ project: "البحث في «{project}»",
+ sections: "البحث في الأقسام",
+ },
+ toolbar: {
+ show: "عرض",
+ pinned: "المثبتة",
+ forks: "التفرعات",
+ comparisons: "المقارنات",
+ project: "المشروع",
+ model: "النموذج",
+ groupBy: "التجميع حسب",
+ groupNone: "بدون تجميع",
+ groupDate: "التاريخ",
+ groupProject: "المشروع",
+ pinnedFirst: "المثبتة أولاً",
+ newChat: "محادثة جديدة",
+ newProject: "مشروع جديد",
+ sortChats: "عدد المحادثات",
+ withoutSection: "بلا قسم",
+ },
+ groups: {
+ today: "اليوم",
+ yesterday: "أمس",
+ week: "آخر 7 أيام",
+ month: "آخر 30 يومًا",
+ },
+ list: {
+ created: "تاريخ الإنشاء",
+ lastActive: "آخر نشاط",
+ location: "الموقع",
+ lastModified: "آخر تعديل",
+ contents: "المحتويات",
+ oneMessage: "رسالة واحدة",
+ messageCount: "عدد الرسائل: {count}",
+ showMore: "عرض المزيد ({count})",
+ },
+ badges: {
+ pinned: "مثبتة",
+ fork: "تفرع",
+ compare: "مقارنة",
+ },
+ menu: {
+ fork: "إنشاء تفرع",
+ moveTo: "نقل إلى مشروع",
+ newChatInProject: "محادثة جديدة في المشروع",
+ edit: "تعديل",
+ deleteProject: "حذف المشروع",
+ newChatInSection: "محادثة جديدة في القسم",
+ },
+ project: {
+ oneProject: "مشروع واحد",
+ projectCount: "عدد المشاريع: {count}",
+ },
+ empty: {
+ chatsTitle: "لا توجد محادثات بعد",
+ chatsDescription: "تظهر محادثاتك هنا، منفصلة عن ملفاتك.",
+ projectsTitle: "لا توجد مشاريع بعد",
+ projectsDescription: "تجمع المشاريع المحادثات المرتبطة وتشارك التعليمات بينها.",
+ archivedTitle: "لا يوجد شيء مؤرشف",
+ archivedDescription: "تظهر هنا المحادثات التي تؤرشفها.",
+ sectionsTitle: "لا توجد أقسام بعد",
+ sectionsDescription: "تجمع الأقسام المحادثات والمشاريع في الشريط الجانبي كما تشاء.",
+ sectionTitle: "لا شيء في هذا القسم بعد",
+ sectionDescription: "انقل المحادثات إلى هنا من قائمتها، أو ابدأ محادثة جديدة في هذا القسم.",
+ },
+ dialog: {
+ renameChat: "إعادة تسمية المحادثة",
+ deleteChatDescription: "سيتم حذف هذه المحادثة نهائيًا. لا يمكن التراجع عن ذلك.",
+ deleteProjectDescription: "سيتم حذف المشروع ومحادثاته ({count}) نهائيًا. لا يمكن التراجع عن ذلك.",
+ deleteFilesMany: "احذف أيضًا الملفات ومجلدات بيئة الاختبار التي أنشأتها هذه المحادثات.",
+ deleteProjectFilesLabel: "حذف مجلد مساحة عمل المشروع",
+ deleteProjectFiles: "ستتم إزالة مجلد مساحة عمل المشروع من القرص.",
+ },
+ toast: {
+ projectMoved: "تم نقل {project} إلى {section}",
+ projectUnfiled: "تمت إزالة {project} من {section}",
+ forkFailed: "تعذر إنشاء التفرع",
+ projectDeleted: "تم حذف «{name}»",
+ projectDeleteFailed: "تعذر حذف المشروع",
+ removedFromSection: "أُزيلت من القسم: {count}",
+ },
+ folder: {
+ openChat: "فتح مجلد المحادثة",
+ openChatTitle: "فتح المجلد الذي تقرأ منه أدوات هذه المحادثة وتكتب فيه",
+ openProject: "فتح مجلد المشروع",
+ openProjectTitle: "فتح المجلد الذي تقرأ منه محادثات هذا المشروع وتكتب فيه",
+ chatHint: "يمكن لتطبيق سطح المكتب فقط فتح مجلد ملفات المحادثة. في المتصفح، نزّل الملف من نتيجة الأداة التي كتبته.",
+ projectHint: "يمكن لتطبيق سطح المكتب فقط فتح مجلد المشروع. في المتصفح، نزّل الملفات من نتائج الأدوات التي كتبتها.",
+ manyFolders: "كتبت هذه المحادثة في أكثر من مجلد.",
+ manyFoldersDescription: "شغّلت أدوات قبل النقل وبعده، لذا افتح المجلد من بطاقة أداة بدلًا من ذلك.",
+ chatFailed: "تعذّر فتح مجلد المحادثة.",
+ projectFailed: "تعذّر فتح مجلد المشروع.",
+ chatMissing: "لا يوجد مجلد لهذه المحادثة بعد.",
+ projectMissing: "لا يوجد مجلد لهذا المشروع بعد.",
+ missingDescription: "يُنشأ عندما تكتب أداة ملفًا لأول مرة.",
+ },
},
empty: {
suggestedTitle: "مكتبتك فارغة",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 55b982bc712..141299594bf 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1804,6 +1804,11 @@ export const de = {
advanced: { title: "Erweitert" },
contextTitle: "Kontext",
},
+ library: {
+ label: "Chats verwalten",
+ description: "Chats, Projekte und Abschnitte durchsuchen, sortieren und ordnen.",
+ action: "Bibliothek öffnen",
+ },
projectAttachmentsHint:
"Diese Einstellung lässt sich im Anhangmenü jedes Chats einzeln ändern.",
rememberParamsPerModelHint:
@@ -2078,9 +2083,6 @@ export const de = {
archivedAudio: "Archivierte Audioclips",
archivedAudioDescription: "Audioclips anzeigen und verwalten, die du archiviert hast.",
manageAction: "Verwalten",
- manageChats: "Chats verwalten",
- manageChatsDescription:
- "Wählen Sie mehrere Chats aus, um sie zu verschieben, anzupinnen, zu archivieren, zu exportieren oder zu löschen.",
exportArchivedChats: "Exportieren",
exportingArchivedChats: "Wird exportiert...",
exportedOneArchivedChat: "1 archivierter Chat exportiert",
@@ -3142,6 +3144,116 @@ export const de = {
audio: "Audio",
models: "Fine-Tunes",
all: "Alle",
+ chats: "Chats",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "Chats",
+ projects: "Projekte",
+ archived: "Archiviert",
+ ariaLabel: "Chat-Bereiche",
+ },
+ search: {
+ chats: "Chats durchsuchen",
+ projects: "Projekte durchsuchen",
+ archived: "Archivierte Chats durchsuchen",
+ project: "In „{project}“ suchen",
+ sections: "Abschnitte durchsuchen",
+ },
+ toolbar: {
+ show: "Anzeigen",
+ pinned: "Angeheftet",
+ forks: "Forks",
+ comparisons: "Vergleiche",
+ project: "Projekt",
+ model: "Modell",
+ groupBy: "Gruppieren nach",
+ groupNone: "Keine Gruppierung",
+ groupDate: "Datum",
+ groupProject: "Projekt",
+ pinnedFirst: "Angeheftete zuerst",
+ newChat: "Neuer Chat",
+ newProject: "Neues Projekt",
+ sortChats: "Anzahl der Chats",
+ withoutSection: "Kein Abschnitt",
+ },
+ groups: {
+ today: "Heute",
+ yesterday: "Gestern",
+ week: "Letzte 7 Tage",
+ month: "Letzte 30 Tage",
+ },
+ list: {
+ created: "Erstellt",
+ lastActive: "Zuletzt aktiv",
+ location: "Ort",
+ lastModified: "Zuletzt geändert",
+ contents: "Inhalt",
+ oneMessage: "1 Nachricht",
+ messageCount: "{count} Nachrichten",
+ showMore: "Mehr anzeigen ({count})",
+ },
+ badges: {
+ pinned: "Angeheftet",
+ fork: "Fork",
+ compare: "Vergleich",
+ },
+ menu: {
+ fork: "Forken",
+ moveTo: "In Projekt verschieben",
+ newChatInProject: "Neuer Chat im Projekt",
+ edit: "Bearbeiten",
+ deleteProject: "Projekt löschen",
+ newChatInSection: "Neuer Chat im Abschnitt",
+ },
+ project: {
+ oneProject: "1 Projekt",
+ projectCount: "{count} Projekte",
+ },
+ empty: {
+ chatsTitle: "Noch keine Chats",
+ chatsDescription: "Deine Unterhaltungen erscheinen hier, getrennt von deinen Dateien.",
+ projectsTitle: "Noch keine Projekte",
+ projectsDescription: "Projekte bündeln zusammengehörige Chats mit gemeinsamen Anweisungen.",
+ archivedTitle: "Nichts archiviert",
+ archivedDescription: "Chats, die du archivierst, erscheinen hier.",
+ sectionsTitle: "Noch keine Abschnitte",
+ sectionsDescription: "Abschnitte gruppieren Chats und Projekte in der Seitenleiste, wie du möchtest.",
+ sectionTitle: "Noch nichts in diesem Abschnitt",
+ sectionDescription: "Verschiebe Chats über ihr Menü hierher oder starte einen neuen Chat in diesem Abschnitt.",
+ },
+ dialog: {
+ renameChat: "Chat umbenennen",
+ deleteChatDescription: "Dieser Chat wird endgültig gelöscht. Dies kann nicht rückgängig gemacht werden.",
+ deleteProjectDescription: "Das Projekt und seine Chats ({count}) werden endgültig gelöscht. Dies kann nicht rückgängig gemacht werden.",
+ deleteFilesMany: "Auch die Dateien und Sandbox-Ordner entfernen, die diese Chats erstellt haben.",
+ deleteProjectFilesLabel: "Projekt-Arbeitsordner löschen",
+ deleteProjectFiles: "Der Arbeitsordner des Projekts wird von der Festplatte entfernt.",
+ },
+ toast: {
+ projectMoved: "{project} nach {section} verschoben",
+ projectUnfiled: "{project} aus {section} entfernt",
+ forkFailed: "Forken fehlgeschlagen",
+ projectDeleted: "„{name}“ gelöscht",
+ projectDeleteFailed: "Projekt konnte nicht gelöscht werden",
+ removedFromSection: "Aus Abschnitt entfernt: {count}",
+ },
+ folder: {
+ openChat: "Chat-Ordner öffnen",
+ openChatTitle: "Den Ordner öffnen, den die Tool-Aufrufe dieses Chats lesen und schreiben",
+ openProject: "Projektordner öffnen",
+ openProjectTitle: "Den Ordner öffnen, den die Chats dieses Projekts lesen und schreiben",
+ chatHint: "Nur die Desktop-App kann den Dateiordner eines Chats öffnen. Laden Sie im Browser die Datei aus dem Tool-Ergebnis herunter, das sie geschrieben hat.",
+ projectHint: "Nur die Desktop-App kann den Ordner eines Projekts öffnen. Laden Sie im Browser die Dateien aus den Tool-Ergebnissen herunter, die sie geschrieben haben.",
+ manyFolders: "Dieser Chat hat in mehr als einen Ordner geschrieben.",
+ manyFoldersDescription: "Er hat Tools vor und nach einem Verschieben ausgeführt. Öffnen Sie den Ordner stattdessen über eine Tool-Karte.",
+ chatFailed: "Der Chat-Ordner konnte nicht geöffnet werden.",
+ projectFailed: "Der Projektordner konnte nicht geöffnet werden.",
+ chatMissing: "Dieser Chat hat noch keinen Ordner.",
+ projectMissing: "Dieses Projekt hat noch keinen Ordner.",
+ missingDescription: "Er wird angelegt, sobald ein Tool zum ersten Mal eine Datei schreibt.",
+ },
},
empty: {
suggestedTitle: "Ihre Bibliothek ist leer",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 581a1c82c2d..7bcd0866a62 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1765,6 +1765,11 @@ export const en = {
advanced: { title: "Advanced" },
contextTitle: "Context",
},
+ library: {
+ label: "Manage chats",
+ description: "Search, sort, and organize chats, projects, and sections.",
+ action: "Open Library",
+ },
projectAttachmentsHint:
"Override this setting from each chat's attachment menu.",
rememberParamsPerModelHint:
@@ -2033,9 +2038,6 @@ export const en = {
archivedAudio: "Archived audio",
archivedAudioDescription: "View and manage audio clips you have archived.",
manageAction: "Manage",
- manageChats: "Manage chats",
- manageChatsDescription:
- "Select multiple chats to move, pin, archive, export, or delete.",
exportArchivedChats: "Export",
exportingArchivedChats: "Exporting...",
exportedOneArchivedChat: "Exported 1 archived chat",
@@ -3059,6 +3061,116 @@ export const en = {
audio: "Audio",
models: "Fine-tunes",
all: "All",
+ chats: "Chats",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "Chats",
+ projects: "Projects",
+ archived: "Archived",
+ ariaLabel: "Chat sections",
+ },
+ search: {
+ chats: "Search chats",
+ projects: "Search projects",
+ archived: "Search archived chats",
+ project: "Search in \"{project}\"",
+ sections: "Search sections",
+ },
+ toolbar: {
+ show: "Show",
+ pinned: "Pinned",
+ forks: "Forks",
+ comparisons: "Comparisons",
+ project: "Project",
+ model: "Model",
+ groupBy: "Group by",
+ groupNone: "No grouping",
+ groupDate: "Date",
+ groupProject: "Project",
+ pinnedFirst: "Pinned first",
+ newChat: "New chat",
+ newProject: "New project",
+ sortChats: "Number of chats",
+ withoutSection: "No section",
+ },
+ groups: {
+ today: "Today",
+ yesterday: "Yesterday",
+ week: "Previous 7 days",
+ month: "Previous 30 days",
+ },
+ list: {
+ created: "Created",
+ lastActive: "Last active",
+ location: "Location",
+ lastModified: "Last modified",
+ contents: "Contents",
+ oneMessage: "1 message",
+ messageCount: "{count} messages",
+ showMore: "Show more ({count})",
+ },
+ badges: {
+ pinned: "Pinned",
+ fork: "Fork",
+ compare: "Compare",
+ },
+ menu: {
+ fork: "Fork",
+ moveTo: "Move to project",
+ newChatInProject: "New chat in project",
+ edit: "Edit",
+ deleteProject: "Delete project",
+ newChatInSection: "New chat in section",
+ },
+ project: {
+ oneProject: "1 project",
+ projectCount: "{count} projects",
+ },
+ empty: {
+ chatsTitle: "No chats yet",
+ chatsDescription: "Your conversations show up here, kept apart from your files.",
+ projectsTitle: "No projects yet",
+ projectsDescription: "Projects group related chats and share instructions between them.",
+ archivedTitle: "Nothing archived",
+ archivedDescription: "Chats you archive show up here.",
+ sectionsTitle: "No sections yet",
+ sectionsDescription: "Sections group chats and projects in the sidebar however you like.",
+ sectionTitle: "Nothing in this section yet",
+ sectionDescription: "Move chats here from their menu, or start a new chat in this section.",
+ },
+ dialog: {
+ renameChat: "Rename chat",
+ deleteChatDescription: "This chat will be permanently deleted. This cannot be undone.",
+ deleteProjectDescription: "The project and its chats ({count}) will be permanently deleted. This cannot be undone.",
+ deleteFilesMany: "Also remove the files and sandbox folders these chats created.",
+ deleteProjectFilesLabel: "Delete project workspace folder",
+ deleteProjectFiles: "The project workspace folder will be removed from disk.",
+ },
+ toast: {
+ projectMoved: "Moved {project} to {section}",
+ projectUnfiled: "Removed {project} from {section}",
+ forkFailed: "Failed to fork",
+ projectDeleted: "Deleted \"{name}\"",
+ projectDeleteFailed: "Failed to delete project",
+ removedFromSection: "Removed from section: {count}",
+ },
+ folder: {
+ openChat: "Open chat folder",
+ openChatTitle: "Open the folder this chat's tool calls read and write",
+ openProject: "Open project folder",
+ openProjectTitle: "Open the folder this project's chats read and write",
+ chatHint: "Only the desktop app can open a chat's files folder. In a browser, download a file from the tool result that wrote it.",
+ projectHint: "Only the desktop app can open a project's folder. In a browser, download files from the tool results that wrote them.",
+ manyFolders: "This chat wrote to more than one folder.",
+ manyFoldersDescription: "It ran tools on both sides of a move, so open the folder from a tool card instead.",
+ chatFailed: "Could not open the chat folder.",
+ projectFailed: "Could not open the project folder.",
+ chatMissing: "This chat has no folder yet.",
+ projectMissing: "This project has no folder yet.",
+ missingDescription: "It is created the first time a tool writes a file.",
+ },
},
// One title and description per tab, shown when it has nothing yet.
empty: {
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 842f47109e2..d1ad0bf4475 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1795,6 +1795,11 @@ export const es = {
advanced: { title: "Avanzado" },
contextTitle: "Contexto",
},
+ library: {
+ label: "Gestionar chats",
+ description: "Busca, ordena y organiza chats, proyectos y secciones.",
+ action: "Abrir Biblioteca",
+ },
projectAttachmentsHint:
"Cambia este ajuste para cada chat desde su menú de archivos adjuntos.",
rememberParamsPerModelHint:
@@ -2068,9 +2073,6 @@ export const es = {
archivedAudio: "Audio archivado",
archivedAudioDescription: "Consulta y gestiona los clips de audio que has archivado.",
manageAction: "Gestionar",
- manageChats: "Gestionar chats",
- manageChatsDescription:
- "Selecciona varios chats para moverlos, fijarlos, archivarlos, exportarlos o eliminarlos.",
exportArchivedChats: "Exportar",
exportingArchivedChats: "Exportando...",
exportedOneArchivedChat: "Se exportó 1 chat archivado",
@@ -3139,6 +3141,116 @@ export const es = {
audio: "Audio",
models: "Fine-tunes",
all: "Todo",
+ chats: "Chats",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "Chats",
+ projects: "Proyectos",
+ archived: "Archivados",
+ ariaLabel: "Secciones de chats",
+ },
+ search: {
+ chats: "Buscar chats",
+ projects: "Buscar proyectos",
+ archived: "Buscar chats archivados",
+ project: "Buscar en «{project}»",
+ sections: "Buscar secciones",
+ },
+ toolbar: {
+ show: "Mostrar",
+ pinned: "Fijados",
+ forks: "Bifurcaciones",
+ comparisons: "Comparaciones",
+ project: "Proyecto",
+ model: "Modelo",
+ groupBy: "Agrupar por",
+ groupNone: "Sin agrupar",
+ groupDate: "Fecha",
+ groupProject: "Proyecto",
+ pinnedFirst: "Fijados primero",
+ newChat: "Nuevo chat",
+ newProject: "Nuevo proyecto",
+ sortChats: "Número de chats",
+ withoutSection: "Sin sección",
+ },
+ groups: {
+ today: "Hoy",
+ yesterday: "Ayer",
+ week: "Últimos 7 días",
+ month: "Últimos 30 días",
+ },
+ list: {
+ created: "Creado",
+ lastActive: "Última actividad",
+ location: "Ubicación",
+ lastModified: "Última modificación",
+ contents: "Contenido",
+ oneMessage: "1 mensaje",
+ messageCount: "{count} mensajes",
+ showMore: "Mostrar más ({count})",
+ },
+ badges: {
+ pinned: "Fijado",
+ fork: "Bifurcación",
+ compare: "Comparación",
+ },
+ menu: {
+ fork: "Bifurcar",
+ moveTo: "Mover a proyecto",
+ newChatInProject: "Nuevo chat en el proyecto",
+ edit: "Editar",
+ deleteProject: "Eliminar proyecto",
+ newChatInSection: "Nuevo chat en la sección",
+ },
+ project: {
+ oneProject: "1 proyecto",
+ projectCount: "{count} proyectos",
+ },
+ empty: {
+ chatsTitle: "Aún no hay chats",
+ chatsDescription: "Tus conversaciones aparecen aquí, separadas de tus archivos.",
+ projectsTitle: "Aún no hay proyectos",
+ projectsDescription: "Los proyectos agrupan chats relacionados y comparten instrucciones entre ellos.",
+ archivedTitle: "Nada archivado",
+ archivedDescription: "Los chats que archives aparecen aquí.",
+ sectionsTitle: "Aún no hay secciones",
+ sectionsDescription: "Las secciones agrupan chats y proyectos en la barra lateral como quieras.",
+ sectionTitle: "Aún no hay nada en esta sección",
+ sectionDescription: "Mueve chats aquí desde su menú o inicia un chat nuevo en esta sección.",
+ },
+ dialog: {
+ renameChat: "Renombrar chat",
+ deleteChatDescription: "Este chat se eliminará de forma permanente. Esta acción no se puede deshacer.",
+ deleteProjectDescription: "El proyecto y sus chats ({count}) se eliminarán de forma permanente. Esta acción no se puede deshacer.",
+ deleteFilesMany: "Eliminar también los archivos y carpetas de sandbox que crearon estos chats.",
+ deleteProjectFilesLabel: "Eliminar la carpeta de trabajo del proyecto",
+ deleteProjectFiles: "La carpeta de trabajo del proyecto se eliminará del disco.",
+ },
+ toast: {
+ projectMoved: "{project} se movió a {section}",
+ projectUnfiled: "{project} se quitó de {section}",
+ forkFailed: "No se pudo bifurcar",
+ projectDeleted: "Se eliminó «{name}»",
+ projectDeleteFailed: "No se pudo eliminar el proyecto",
+ removedFromSection: "Quitados de la sección: {count}",
+ },
+ folder: {
+ openChat: "Abrir carpeta del chat",
+ openChatTitle: "Abrir la carpeta que leen y escriben las herramientas de este chat",
+ openProject: "Abrir carpeta del proyecto",
+ openProjectTitle: "Abrir la carpeta que leen y escriben los chats de este proyecto",
+ chatHint: "Solo la app de escritorio puede abrir la carpeta de archivos de un chat. En el navegador, descarga el archivo desde el resultado de la herramienta que lo escribió.",
+ projectHint: "Solo la app de escritorio puede abrir la carpeta de un proyecto. En el navegador, descarga los archivos desde los resultados de las herramientas que los escribieron.",
+ manyFolders: "Este chat escribió en más de una carpeta.",
+ manyFoldersDescription: "Ejecutó herramientas antes y después de moverse, así que abre la carpeta desde una tarjeta de herramienta.",
+ chatFailed: "No se pudo abrir la carpeta del chat.",
+ projectFailed: "No se pudo abrir la carpeta del proyecto.",
+ chatMissing: "Este chat aún no tiene carpeta.",
+ projectMissing: "Este proyecto aún no tiene carpeta.",
+ missingDescription: "Se crea la primera vez que una herramienta escribe un archivo.",
+ },
},
empty: {
suggestedTitle: "Tu biblioteca está vacía",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index d64fde032db..072bcd0f5be 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1801,6 +1801,11 @@ export const fr = {
advanced: { title: "Avancé" },
contextTitle: "Contexte",
},
+ library: {
+ label: "Gérer les discussions",
+ description: "Recherchez, triez et organisez discussions, projets et sections.",
+ action: "Ouvrir la Bibliothèque",
+ },
projectAttachmentsHint:
"Modifiez ce réglage pour chaque chat dans son menu de pièces jointes.",
rememberParamsPerModelHint:
@@ -2076,9 +2081,6 @@ export const fr = {
archivedAudio: "Audio archivé",
archivedAudioDescription: "Consultez et gérez les clips audio que vous avez archivés.",
manageAction: "Gérer",
- manageChats: "Gérer les discussions",
- manageChatsDescription:
- "Sélectionnez plusieurs discussions pour les déplacer, les épingler, les archiver, les exporter ou les supprimer.",
exportArchivedChats: "Exporter",
exportingArchivedChats: "Exportation...",
exportedOneArchivedChat: "1 discussion archivée a été exportée",
@@ -3153,6 +3155,116 @@ export const fr = {
audio: "Audio",
models: "Fine-tunes",
all: "Tout",
+ chats: "Discussions",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "Discussions",
+ projects: "Projets",
+ archived: "Archivés",
+ ariaLabel: "Sections des discussions",
+ },
+ search: {
+ chats: "Rechercher des discussions",
+ projects: "Rechercher des projets",
+ archived: "Rechercher dans les discussions archivées",
+ project: "Rechercher dans « {project} »",
+ sections: "Rechercher des sections",
+ },
+ toolbar: {
+ show: "Afficher",
+ pinned: "Épinglés",
+ forks: "Forks",
+ comparisons: "Comparaisons",
+ project: "Projet",
+ model: "Modèle",
+ groupBy: "Grouper par",
+ groupNone: "Aucun regroupement",
+ groupDate: "Date",
+ groupProject: "Projet",
+ pinnedFirst: "Épinglés en premier",
+ newChat: "Nouvelle discussion",
+ newProject: "Nouveau projet",
+ sortChats: "Nombre de discussions",
+ withoutSection: "Aucune section",
+ },
+ groups: {
+ today: "Aujourd’hui",
+ yesterday: "Hier",
+ week: "7 derniers jours",
+ month: "30 derniers jours",
+ },
+ list: {
+ created: "Créé",
+ lastActive: "Dernière activité",
+ location: "Emplacement",
+ lastModified: "Dernière modification",
+ contents: "Contenu",
+ oneMessage: "1 message",
+ messageCount: "{count} messages",
+ showMore: "Afficher plus ({count})",
+ },
+ badges: {
+ pinned: "Épinglé",
+ fork: "Fork",
+ compare: "Comparaison",
+ },
+ menu: {
+ fork: "Forker",
+ moveTo: "Déplacer vers un projet",
+ newChatInProject: "Nouvelle discussion dans le projet",
+ edit: "Modifier",
+ deleteProject: "Supprimer le projet",
+ newChatInSection: "Nouvelle discussion dans la section",
+ },
+ project: {
+ oneProject: "1 projet",
+ projectCount: "{count} projets",
+ },
+ empty: {
+ chatsTitle: "Aucune discussion pour l’instant",
+ chatsDescription: "Vos conversations apparaissent ici, séparées de vos fichiers.",
+ projectsTitle: "Aucun projet pour l’instant",
+ projectsDescription: "Les projets regroupent des discussions liées et partagent des instructions entre elles.",
+ archivedTitle: "Rien d’archivé",
+ archivedDescription: "Les discussions que vous archivez apparaissent ici.",
+ sectionsTitle: "Aucune section pour l’instant",
+ sectionsDescription: "Les sections regroupent discussions et projets dans la barre latérale comme vous le souhaitez.",
+ sectionTitle: "Rien dans cette section pour l’instant",
+ sectionDescription: "Déplacez des discussions ici depuis leur menu, ou démarrez une nouvelle discussion dans cette section.",
+ },
+ dialog: {
+ renameChat: "Renommer la discussion",
+ deleteChatDescription: "Cette discussion sera définitivement supprimée. Cette action est irréversible.",
+ deleteProjectDescription: "Le projet et ses discussions ({count}) seront définitivement supprimés. Cette action est irréversible.",
+ deleteFilesMany: "Supprimer aussi les fichiers et dossiers sandbox créés par ces discussions.",
+ deleteProjectFilesLabel: "Supprimer le dossier de travail du projet",
+ deleteProjectFiles: "Le dossier de travail du projet sera supprimé du disque.",
+ },
+ toast: {
+ projectMoved: "{project} déplacé vers {section}",
+ projectUnfiled: "{project} retiré de {section}",
+ forkFailed: "Échec du fork",
+ projectDeleted: "« {name} » supprimé",
+ projectDeleteFailed: "Impossible de supprimer le projet",
+ removedFromSection: "Retirées de la section : {count}",
+ },
+ folder: {
+ openChat: "Ouvrir le dossier de la discussion",
+ openChatTitle: "Ouvrir le dossier que lisent et écrivent les outils de cette discussion",
+ openProject: "Ouvrir le dossier du projet",
+ openProjectTitle: "Ouvrir le dossier que lisent et écrivent les discussions de ce projet",
+ chatHint: "Seule l’application de bureau peut ouvrir le dossier de fichiers d’une discussion. Dans un navigateur, téléchargez le fichier depuis le résultat de l’outil qui l’a écrit.",
+ projectHint: "Seule l’application de bureau peut ouvrir le dossier d’un projet. Dans un navigateur, téléchargez les fichiers depuis les résultats des outils qui les ont écrits.",
+ manyFolders: "Cette discussion a écrit dans plusieurs dossiers.",
+ manyFoldersDescription: "Elle a exécuté des outils avant et après un déplacement : ouvrez plutôt le dossier depuis une carte d’outil.",
+ chatFailed: "Impossible d’ouvrir le dossier de la discussion.",
+ projectFailed: "Impossible d’ouvrir le dossier du projet.",
+ chatMissing: "Cette discussion n’a pas encore de dossier.",
+ projectMissing: "Ce projet n’a pas encore de dossier.",
+ missingDescription: "Il est créé la première fois qu’un outil écrit un fichier.",
+ },
},
empty: {
suggestedTitle: "Votre bibliothèque est vide",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index b79ac454e08..724c73ac171 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1772,6 +1772,11 @@ export const hi = {
advanced: { title: "उन्नत" },
contextTitle: "संदर्भ",
},
+ library: {
+ label: "चैट प्रबंधित करें",
+ description: "चैट, प्रोजेक्ट और सेक्शन खोजें, क्रमबद्ध करें और व्यवस्थित करें।",
+ action: "लाइब्रेरी खोलें",
+ },
projectAttachmentsHint:
"हर चैट के अटैचमेंट मेन्यू से इस सेटिंग को अलग से बदलें।",
rememberParamsPerModelHint:
@@ -2043,9 +2048,6 @@ export const hi = {
archivedAudio: "संग्रहित ऑडियो",
archivedAudioDescription: "आपके द्वारा संग्रहित किए गए ऑडियो क्लिप देखें और प्रबंधित करें।",
manageAction: "प्रबंधित करें",
- manageChats: "चैट प्रबंधित करें",
- manageChatsDescription:
- "कई चैट चुनें और उन्हें स्थानांतरित, पिन, संग्रहित, निर्यात या हटाएं।",
exportArchivedChats: "एक्सपोर्ट करें",
exportingArchivedChats: "एक्सपोर्ट हो रहा है...",
exportedOneArchivedChat: "1 संग्रहित चैट एक्सपोर्ट की गई",
@@ -3080,6 +3082,116 @@ export const hi = {
audio: "ऑडियो",
models: "फ़ाइन-ट्यून",
all: "सभी",
+ chats: "चैट",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "चैट",
+ projects: "प्रोजेक्ट",
+ archived: "आर्काइव",
+ ariaLabel: "चैट सेक्शन",
+ },
+ search: {
+ chats: "चैट खोजें",
+ projects: "प्रोजेक्ट खोजें",
+ archived: "आर्काइव की गई चैट खोजें",
+ project: "“{project}” में खोजें",
+ sections: "सेक्शन खोजें",
+ },
+ toolbar: {
+ show: "दिखाएँ",
+ pinned: "पिन की गई",
+ forks: "फ़ॉर्क",
+ comparisons: "तुलनाएँ",
+ project: "प्रोजेक्ट",
+ model: "मॉडल",
+ groupBy: "इसके अनुसार समूह बनाएँ",
+ groupNone: "कोई समूह नहीं",
+ groupDate: "तारीख",
+ groupProject: "प्रोजेक्ट",
+ pinnedFirst: "पिन की गई पहले",
+ newChat: "नई चैट",
+ newProject: "नया प्रोजेक्ट",
+ sortChats: "चैट की संख्या",
+ withoutSection: "कोई सेक्शन नहीं",
+ },
+ groups: {
+ today: "आज",
+ yesterday: "कल",
+ week: "पिछले 7 दिन",
+ month: "पिछले 30 दिन",
+ },
+ list: {
+ created: "बनाई गई",
+ lastActive: "आख़िरी गतिविधि",
+ location: "स्थान",
+ lastModified: "अंतिम बदलाव",
+ contents: "सामग्री",
+ oneMessage: "1 संदेश",
+ messageCount: "{count} संदेश",
+ showMore: "और दिखाएँ ({count})",
+ },
+ badges: {
+ pinned: "पिन की गई",
+ fork: "फ़ॉर्क",
+ compare: "तुलना",
+ },
+ menu: {
+ fork: "फ़ॉर्क करें",
+ moveTo: "प्रोजेक्ट में ले जाएँ",
+ newChatInProject: "प्रोजेक्ट में नई चैट",
+ edit: "संपादित करें",
+ deleteProject: "प्रोजेक्ट हटाएँ",
+ newChatInSection: "सेक्शन में नई चैट",
+ },
+ project: {
+ oneProject: "1 प्रोजेक्ट",
+ projectCount: "{count} प्रोजेक्ट",
+ },
+ empty: {
+ chatsTitle: "अभी तक कोई चैट नहीं",
+ chatsDescription: "आपकी बातचीत यहाँ दिखती है, आपकी फ़ाइलों से अलग।",
+ projectsTitle: "अभी तक कोई प्रोजेक्ट नहीं",
+ projectsDescription: "प्रोजेक्ट संबंधित चैट को एक साथ रखते हैं और उनके बीच निर्देश साझा करते हैं।",
+ archivedTitle: "कुछ भी आर्काइव नहीं",
+ archivedDescription: "आप जो चैट आर्काइव करते हैं, वे यहाँ दिखती हैं।",
+ sectionsTitle: "अभी कोई सेक्शन नहीं",
+ sectionsDescription: "सेक्शन साइडबार में चैट और प्रोजेक्ट को आपकी पसंद से समूहित करते हैं।",
+ sectionTitle: "इस सेक्शन में अभी कुछ नहीं",
+ sectionDescription: "चैट को उनके मेन्यू से यहाँ ले आएँ, या इस सेक्शन में नई चैट शुरू करें।",
+ },
+ dialog: {
+ renameChat: "चैट का नाम बदलें",
+ deleteChatDescription: "यह चैट हमेशा के लिए हटा दी जाएगी। इसे पूर्ववत नहीं किया जा सकता।",
+ deleteProjectDescription: "प्रोजेक्ट और उसकी चैट ({count}) हमेशा के लिए हटा दी जाएँगी। इसे पूर्ववत नहीं किया जा सकता।",
+ deleteFilesMany: "इन चैट द्वारा बनाई गई फ़ाइलें और सैंडबॉक्स फ़ोल्डर भी हटाएँ।",
+ deleteProjectFilesLabel: "प्रोजेक्ट का वर्कस्पेस फ़ोल्डर हटाएँ",
+ deleteProjectFiles: "प्रोजेक्ट का वर्कस्पेस फ़ोल्डर डिस्क से हटा दिया जाएगा।",
+ },
+ toast: {
+ projectMoved: "{project} को {section} में ले जाया गया",
+ projectUnfiled: "{project} को {section} से हटाया गया",
+ forkFailed: "फ़ॉर्क नहीं किया जा सका",
+ projectDeleted: "“{name}” हटाया गया",
+ projectDeleteFailed: "प्रोजेक्ट नहीं हटाया जा सका",
+ removedFromSection: "सेक्शन से हटाई गईं: {count}",
+ },
+ folder: {
+ openChat: "चैट फ़ोल्डर खोलें",
+ openChatTitle: "वह फ़ोल्डर खोलें जिसे इस चैट के टूल कॉल पढ़ते और लिखते हैं",
+ openProject: "प्रोजेक्ट फ़ोल्डर खोलें",
+ openProjectTitle: "वह फ़ोल्डर खोलें जिसे इस प्रोजेक्ट की चैट पढ़ती और लिखती हैं",
+ chatHint: "केवल डेस्कटॉप ऐप ही चैट का फ़ाइल फ़ोल्डर खोल सकता है। ब्राउज़र में, फ़ाइल को उस टूल परिणाम से डाउनलोड करें जिसने उसे लिखा।",
+ projectHint: "केवल डेस्कटॉप ऐप ही प्रोजेक्ट का फ़ोल्डर खोल सकता है। ब्राउज़र में, फ़ाइलें उन टूल परिणामों से डाउनलोड करें जिन्होंने उन्हें लिखा।",
+ manyFolders: "इस चैट ने एक से अधिक फ़ोल्डर में लिखा।",
+ manyFoldersDescription: "इसने स्थानांतरण के पहले और बाद में टूल चलाए, इसलिए फ़ोल्डर किसी टूल कार्ड से खोलें।",
+ chatFailed: "चैट फ़ोल्डर नहीं खोला जा सका।",
+ projectFailed: "प्रोजेक्ट फ़ोल्डर नहीं खोला जा सका।",
+ chatMissing: "इस चैट का अभी कोई फ़ोल्डर नहीं है।",
+ projectMissing: "इस प्रोजेक्ट का अभी कोई फ़ोल्डर नहीं है।",
+ missingDescription: "यह तब बनता है जब कोई टूल पहली बार कोई फ़ाइल लिखता है।",
+ },
},
empty: {
suggestedTitle: "आपकी लाइब्रेरी खाली है",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index dfe0528d1ad..3e952185bb7 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1764,6 +1764,11 @@ export const it = {
advanced: { title: "Avanzate" },
contextTitle: "Contesto",
},
+ library: {
+ label: "Gestisci chat",
+ description: "Cerca, ordina e organizza chat, progetti e sezioni.",
+ action: "Apri Libreria",
+ },
projectAttachmentsHint:
"Modifica questa impostazione per ogni chat dal relativo menu degli allegati.",
rememberParamsPerModelHint:
@@ -2037,9 +2042,6 @@ export const it = {
archivedAudio: "Audio archiviati",
archivedAudioDescription: "Visualizza e gestisci le clip audio che hai archiviato.",
manageAction: "Gestisci",
- manageChats: "Gestisci chat",
- manageChatsDescription:
- "Seleziona più chat da spostare, fissare, archiviare, esportare o eliminare.",
exportArchivedChats: "Esporta",
exportingArchivedChats: "Esportazione...",
exportedOneArchivedChat: "1 chat archiviata esportata",
@@ -3140,6 +3142,116 @@ export const it = {
audio: "Audio",
models: "Fine-tune",
all: "Tutti",
+ chats: "Chat",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "Chat",
+ projects: "Progetti",
+ archived: "Archiviate",
+ ariaLabel: "Sezioni delle chat",
+ },
+ search: {
+ chats: "Cerca chat",
+ projects: "Cerca progetti",
+ archived: "Cerca chat archiviate",
+ project: "Cerca in «{project}»",
+ sections: "Cerca sezioni",
+ },
+ toolbar: {
+ show: "Mostra",
+ pinned: "Fissate",
+ forks: "Fork",
+ comparisons: "Confronti",
+ project: "Progetto",
+ model: "Modello",
+ groupBy: "Raggruppa per",
+ groupNone: "Nessun raggruppamento",
+ groupDate: "Data",
+ groupProject: "Progetto",
+ pinnedFirst: "Prima le fissate",
+ newChat: "Nuova chat",
+ newProject: "Nuovo progetto",
+ sortChats: "Numero di chat",
+ withoutSection: "Nessuna sezione",
+ },
+ groups: {
+ today: "Oggi",
+ yesterday: "Ieri",
+ week: "Ultimi 7 giorni",
+ month: "Ultimi 30 giorni",
+ },
+ list: {
+ created: "Creata",
+ lastActive: "Ultima attività",
+ location: "Posizione",
+ lastModified: "Ultima modifica",
+ contents: "Contenuto",
+ oneMessage: "1 messaggio",
+ messageCount: "{count} messaggi",
+ showMore: "Mostra altro ({count})",
+ },
+ badges: {
+ pinned: "Fissata",
+ fork: "Fork",
+ compare: "Confronto",
+ },
+ menu: {
+ fork: "Crea fork",
+ moveTo: "Sposta nel progetto",
+ newChatInProject: "Nuova chat nel progetto",
+ edit: "Modifica",
+ deleteProject: "Elimina progetto",
+ newChatInSection: "Nuova chat nella sezione",
+ },
+ project: {
+ oneProject: "1 progetto",
+ projectCount: "{count} progetti",
+ },
+ empty: {
+ chatsTitle: "Ancora nessuna chat",
+ chatsDescription: "Le tue conversazioni compaiono qui, separate dai tuoi file.",
+ projectsTitle: "Ancora nessun progetto",
+ projectsDescription: "I progetti raggruppano chat correlate e condividono le istruzioni tra loro.",
+ archivedTitle: "Nessun elemento archiviato",
+ archivedDescription: "Le chat che archivi compaiono qui.",
+ sectionsTitle: "Ancora nessuna sezione",
+ sectionsDescription: "Le sezioni raggruppano chat e progetti nella barra laterale come preferisci.",
+ sectionTitle: "Ancora niente in questa sezione",
+ sectionDescription: "Sposta qui le chat dal loro menu o avvia una nuova chat in questa sezione.",
+ },
+ dialog: {
+ renameChat: "Rinomina chat",
+ deleteChatDescription: "Questa chat verrà eliminata definitivamente. L’operazione non può essere annullata.",
+ deleteProjectDescription: "Il progetto e le sue chat ({count}) verranno eliminati definitivamente. L’operazione non può essere annullata.",
+ deleteFilesMany: "Rimuovi anche i file e le cartelle sandbox create da queste chat.",
+ deleteProjectFilesLabel: "Elimina la cartella di lavoro del progetto",
+ deleteProjectFiles: "La cartella di lavoro del progetto verrà rimossa dal disco.",
+ },
+ toast: {
+ projectMoved: "{project} spostato in {section}",
+ projectUnfiled: "{project} rimosso da {section}",
+ forkFailed: "Impossibile creare il fork",
+ projectDeleted: "«{name}» eliminato",
+ projectDeleteFailed: "Impossibile eliminare il progetto",
+ removedFromSection: "Rimosse dalla sezione: {count}",
+ },
+ folder: {
+ openChat: "Apri cartella della chat",
+ openChatTitle: "Apri la cartella che gli strumenti di questa chat leggono e scrivono",
+ openProject: "Apri cartella del progetto",
+ openProjectTitle: "Apri la cartella che le chat di questo progetto leggono e scrivono",
+ chatHint: "Solo l’app desktop può aprire la cartella dei file di una chat. Nel browser, scarica il file dal risultato dello strumento che lo ha scritto.",
+ projectHint: "Solo l’app desktop può aprire la cartella di un progetto. Nel browser, scarica i file dai risultati degli strumenti che li hanno scritti.",
+ manyFolders: "Questa chat ha scritto in più di una cartella.",
+ manyFoldersDescription: "Ha eseguito strumenti prima e dopo uno spostamento, quindi apri la cartella da una scheda dello strumento.",
+ chatFailed: "Impossibile aprire la cartella della chat.",
+ projectFailed: "Impossibile aprire la cartella del progetto.",
+ chatMissing: "Questa chat non ha ancora una cartella.",
+ projectMissing: "Questo progetto non ha ancora una cartella.",
+ missingDescription: "Viene creata la prima volta che uno strumento scrive un file.",
+ },
},
empty: {
suggestedTitle: "La tua libreria è vuota",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 578276c3c43..6c79ac2efd3 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1753,6 +1753,11 @@ export const ja = {
advanced: { title: "詳細設定" },
contextTitle: "コンテキスト",
},
+ library: {
+ label: "チャットを管理",
+ description: "チャット、プロジェクト、セクションを検索、並べ替え、整理します。",
+ action: "ライブラリを開く",
+ },
projectAttachmentsHint: "各チャットの添付メニューで個別に変更できます。",
rememberParamsPerModelHint:
"オフの場合、すべてのモデルで同じ設定を使います。",
@@ -2009,9 +2014,6 @@ export const ja = {
archivedAudio: "アーカイブした音声",
archivedAudioDescription: "アーカイブした音声クリップを表示・管理します。",
manageAction: "管理",
- manageChats: "チャットを管理",
- manageChatsDescription:
- "複数のチャットを選択して移動、ピン留め、アーカイブ、エクスポート、削除できます。",
exportArchivedChats: "エクスポート",
exportingArchivedChats: "エクスポート中...",
exportedOneArchivedChat: "アーカイブ済みチャット 1 件をエクスポートしました",
@@ -3021,6 +3023,116 @@ export const ja = {
audio: "音声",
models: "ファインチューン",
all: "すべて",
+ chats: "チャット",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "チャット",
+ projects: "プロジェクト",
+ archived: "アーカイブ",
+ ariaLabel: "チャットのセクション",
+ },
+ search: {
+ chats: "チャットを検索",
+ projects: "プロジェクトを検索",
+ archived: "アーカイブ済みのチャットを検索",
+ project: "「{project}」内を検索",
+ sections: "セクションを検索",
+ },
+ toolbar: {
+ show: "表示",
+ pinned: "ピン留め",
+ forks: "フォーク",
+ comparisons: "比較",
+ project: "プロジェクト",
+ model: "モデル",
+ groupBy: "グループ化",
+ groupNone: "グループ化しない",
+ groupDate: "日付",
+ groupProject: "プロジェクト",
+ pinnedFirst: "ピン留めを先頭に",
+ newChat: "新しいチャット",
+ newProject: "新しいプロジェクト",
+ sortChats: "チャット数",
+ withoutSection: "セクションなし",
+ },
+ groups: {
+ today: "今日",
+ yesterday: "昨日",
+ week: "過去 7 日間",
+ month: "過去 30 日間",
+ },
+ list: {
+ created: "作成日",
+ lastActive: "最終アクティビティ",
+ location: "場所",
+ lastModified: "最終更新",
+ contents: "内容",
+ oneMessage: "1 件のメッセージ",
+ messageCount: "{count} 件のメッセージ",
+ showMore: "さらに表示({count})",
+ },
+ badges: {
+ pinned: "ピン留め",
+ fork: "フォーク",
+ compare: "比較",
+ },
+ menu: {
+ fork: "フォーク",
+ moveTo: "プロジェクトに移動",
+ newChatInProject: "プロジェクトで新しいチャット",
+ edit: "編集",
+ deleteProject: "プロジェクトを削除",
+ newChatInSection: "セクションで新しいチャット",
+ },
+ project: {
+ oneProject: "1 件のプロジェクト",
+ projectCount: "{count} 件のプロジェクト",
+ },
+ empty: {
+ chatsTitle: "まだチャットはありません",
+ chatsDescription: "会話はファイルとは別にここに表示されます。",
+ projectsTitle: "まだプロジェクトはありません",
+ projectsDescription: "プロジェクトは関連するチャットをまとめ、指示を共有します。",
+ archivedTitle: "アーカイブはありません",
+ archivedDescription: "アーカイブしたチャットがここに表示されます。",
+ sectionsTitle: "セクションはまだありません",
+ sectionsDescription: "セクションでは、サイドバーのチャットやプロジェクトを自由にまとめられます。",
+ sectionTitle: "このセクションにはまだ何もありません",
+ sectionDescription: "メニューからチャットをここへ移動するか、このセクションで新しいチャットを始めましょう。",
+ },
+ dialog: {
+ renameChat: "チャットの名前を変更",
+ deleteChatDescription: "このチャットは完全に削除されます。この操作は取り消せません。",
+ deleteProjectDescription: "プロジェクトとそのチャット({count} 件)は完全に削除されます。この操作は取り消せません。",
+ deleteFilesMany: "これらのチャットが作成したファイルとサンドボックスフォルダも削除します。",
+ deleteProjectFilesLabel: "プロジェクトの作業フォルダを削除",
+ deleteProjectFiles: "プロジェクトの作業フォルダはディスクから削除されます。",
+ },
+ toast: {
+ projectMoved: "{project} を {section} に移動しました",
+ projectUnfiled: "{project} を {section} から外しました",
+ forkFailed: "フォークできませんでした",
+ projectDeleted: "「{name}」を削除しました",
+ projectDeleteFailed: "プロジェクトを削除できませんでした",
+ removedFromSection: "セクションから外しました: {count}",
+ },
+ folder: {
+ openChat: "チャットフォルダを開く",
+ openChatTitle: "このチャットのツール呼び出しが読み書きするフォルダを開きます",
+ openProject: "プロジェクトフォルダを開く",
+ openProjectTitle: "このプロジェクトのチャットが読み書きするフォルダを開きます",
+ chatHint: "チャットのファイルフォルダを開けるのはデスクトップアプリだけです。ブラウザでは、ファイルを書き込んだツール結果からダウンロードしてください。",
+ projectHint: "プロジェクトのフォルダを開けるのはデスクトップアプリだけです。ブラウザでは、ファイルを書き込んだツール結果からダウンロードしてください。",
+ manyFolders: "このチャットは複数のフォルダに書き込みました。",
+ manyFoldersDescription: "移動の前後でツールを実行したため、ツールカードからフォルダを開いてください。",
+ chatFailed: "チャットフォルダを開けませんでした。",
+ projectFailed: "プロジェクトフォルダを開けませんでした。",
+ chatMissing: "このチャットにはまだフォルダがありません。",
+ projectMissing: "このプロジェクトにはまだフォルダがありません。",
+ missingDescription: "ツールが初めてファイルを書き込んだときに作成されます。",
+ },
},
empty: {
suggestedTitle: "ライブラリは空です",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 99625a0ed7c..9a50159ec41 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1763,6 +1763,11 @@ export const ko = {
advanced: { title: "고급" },
contextTitle: "컨텍스트",
},
+ library: {
+ label: "채팅 관리",
+ description: "채팅, 프로젝트, 섹션을 검색, 정렬하고 정리하세요.",
+ action: "라이브러리 열기",
+ },
projectAttachmentsHint:
"각 채팅의 첨부 메뉴에서 이 설정을 개별적으로 변경할 수 있습니다.",
rememberParamsPerModelHint: "끄면 모든 모델에 같은 설정을 사용합니다.",
@@ -2032,9 +2037,6 @@ export const ko = {
archivedAudio: "보관된 오디오",
archivedAudioDescription: "보관한 오디오 클립을 확인하고 관리합니다.",
manageAction: "관리",
- manageChats: "채팅 관리",
- manageChatsDescription:
- "여러 채팅을 선택해 이동, 고정, 보관, 내보내기 또는 삭제할 수 있습니다.",
exportArchivedChats: "내보내기",
exportingArchivedChats: "내보내는 중...",
exportedOneArchivedChat: "보관된 채팅 1개를 내보냈습니다",
@@ -3067,6 +3069,116 @@ export const ko = {
audio: "오디오",
models: "파인튜닝",
all: "전체",
+ chats: "채팅",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "채팅",
+ projects: "프로젝트",
+ archived: "보관됨",
+ ariaLabel: "채팅 섹션",
+ },
+ search: {
+ chats: "채팅 검색",
+ projects: "프로젝트 검색",
+ archived: "보관된 채팅 검색",
+ project: "“{project}”에서 검색",
+ sections: "섹션 검색",
+ },
+ toolbar: {
+ show: "표시",
+ pinned: "고정됨",
+ forks: "포크",
+ comparisons: "비교",
+ project: "프로젝트",
+ model: "모델",
+ groupBy: "그룹화 기준",
+ groupNone: "그룹화 안 함",
+ groupDate: "날짜",
+ groupProject: "프로젝트",
+ pinnedFirst: "고정 항목 먼저",
+ newChat: "새 채팅",
+ newProject: "새 프로젝트",
+ sortChats: "채팅 수",
+ withoutSection: "섹션 없음",
+ },
+ groups: {
+ today: "오늘",
+ yesterday: "어제",
+ week: "지난 7일",
+ month: "지난 30일",
+ },
+ list: {
+ created: "생성일",
+ lastActive: "마지막 활동",
+ location: "위치",
+ lastModified: "마지막 수정",
+ contents: "내용",
+ oneMessage: "메시지 1개",
+ messageCount: "메시지 {count}개",
+ showMore: "더 보기 ({count})",
+ },
+ badges: {
+ pinned: "고정됨",
+ fork: "포크",
+ compare: "비교",
+ },
+ menu: {
+ fork: "포크",
+ moveTo: "프로젝트로 이동",
+ newChatInProject: "프로젝트에서 새 채팅",
+ edit: "편집",
+ deleteProject: "프로젝트 삭제",
+ newChatInSection: "섹션에서 새 채팅",
+ },
+ project: {
+ oneProject: "프로젝트 1개",
+ projectCount: "프로젝트 {count}개",
+ },
+ empty: {
+ chatsTitle: "아직 채팅이 없습니다",
+ chatsDescription: "대화는 파일과 분리되어 여기에 표시됩니다.",
+ projectsTitle: "아직 프로젝트가 없습니다",
+ projectsDescription: "프로젝트는 관련 채팅을 묶고 지침을 공유합니다.",
+ archivedTitle: "보관된 항목 없음",
+ archivedDescription: "보관한 채팅이 여기에 표시됩니다.",
+ sectionsTitle: "아직 섹션이 없습니다",
+ sectionsDescription: "섹션으로 사이드바의 채팅과 프로젝트를 원하는 대로 묶을 수 있습니다.",
+ sectionTitle: "이 섹션에 아직 아무것도 없습니다",
+ sectionDescription: "메뉴에서 채팅을 이곳으로 옮기거나 이 섹션에서 새 채팅을 시작하세요.",
+ },
+ dialog: {
+ renameChat: "채팅 이름 변경",
+ deleteChatDescription: "이 채팅은 영구적으로 삭제됩니다. 이 작업은 되돌릴 수 없습니다.",
+ deleteProjectDescription: "프로젝트와 채팅({count}개)이 영구적으로 삭제됩니다. 이 작업은 되돌릴 수 없습니다.",
+ deleteFilesMany: "이 채팅들이 만든 파일과 샌드박스 폴더도 삭제합니다.",
+ deleteProjectFilesLabel: "프로젝트 작업 폴더 삭제",
+ deleteProjectFiles: "프로젝트 작업 폴더가 디스크에서 삭제됩니다.",
+ },
+ toast: {
+ projectMoved: "{project}을(를) {section}(으)로 이동했습니다",
+ projectUnfiled: "{project}을(를) {section}에서 제거했습니다",
+ forkFailed: "포크하지 못했습니다",
+ projectDeleted: "“{name}” 삭제됨",
+ projectDeleteFailed: "프로젝트를 삭제하지 못했습니다",
+ removedFromSection: "섹션에서 제거됨: {count}",
+ },
+ folder: {
+ openChat: "채팅 폴더 열기",
+ openChatTitle: "이 채팅의 도구 호출이 읽고 쓰는 폴더를 엽니다",
+ openProject: "프로젝트 폴더 열기",
+ openProjectTitle: "이 프로젝트의 채팅이 읽고 쓰는 폴더를 엽니다",
+ chatHint: "채팅의 파일 폴더는 데스크톱 앱에서만 열 수 있습니다. 브라우저에서는 파일을 작성한 도구 결과에서 다운로드하세요.",
+ projectHint: "프로젝트 폴더는 데스크톱 앱에서만 열 수 있습니다. 브라우저에서는 파일을 작성한 도구 결과에서 다운로드하세요.",
+ manyFolders: "이 채팅은 둘 이상의 폴더에 기록했습니다.",
+ manyFoldersDescription: "이동 전후로 도구를 실행했으므로 도구 카드에서 폴더를 여세요.",
+ chatFailed: "채팅 폴더를 열 수 없습니다.",
+ projectFailed: "프로젝트 폴더를 열 수 없습니다.",
+ chatMissing: "이 채팅에는 아직 폴더가 없습니다.",
+ projectMissing: "이 프로젝트에는 아직 폴더가 없습니다.",
+ missingDescription: "도구가 처음 파일을 쓸 때 만들어집니다.",
+ },
},
empty: {
suggestedTitle: "라이브러리가 비어 있습니다",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index b3851d55d67..4c4225539c8 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1783,6 +1783,11 @@ export const ptBR = {
advanced: { title: "Avançado" },
contextTitle: "Contexto",
},
+ library: {
+ label: "Gerenciar chats",
+ description: "Pesquise, ordene e organize chats, projetos e seções.",
+ action: "Abrir Biblioteca",
+ },
projectAttachmentsHint:
"Altere esta configuração para cada chat pelo menu de anexos.",
rememberParamsPerModelHint:
@@ -2052,9 +2057,6 @@ export const ptBR = {
archivedAudio: "Áudios arquivados",
archivedAudioDescription: "Veja e gerencie os clipes de áudio que você arquivou.",
manageAction: "Gerenciar",
- manageChats: "Gerenciar chats",
- manageChatsDescription:
- "Selecione vários chats para mover, fixar, arquivar, exportar ou excluir.",
exportArchivedChats: "Exportar",
exportingArchivedChats: "Exportando...",
exportedOneArchivedChat: "1 chat arquivado exportado",
@@ -3101,6 +3103,116 @@ export const ptBR = {
audio: "Áudio",
models: "Fine-tunes",
all: "Tudo",
+ chats: "Chats",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "Chats",
+ projects: "Projetos",
+ archived: "Arquivados",
+ ariaLabel: "Seções de chats",
+ },
+ search: {
+ chats: "Pesquisar chats",
+ projects: "Pesquisar projetos",
+ archived: "Pesquisar chats arquivados",
+ project: "Pesquisar em “{project}”",
+ sections: "Pesquisar seções",
+ },
+ toolbar: {
+ show: "Mostrar",
+ pinned: "Fixados",
+ forks: "Forks",
+ comparisons: "Comparações",
+ project: "Projeto",
+ model: "Modelo",
+ groupBy: "Agrupar por",
+ groupNone: "Sem agrupamento",
+ groupDate: "Data",
+ groupProject: "Projeto",
+ pinnedFirst: "Fixados primeiro",
+ newChat: "Novo chat",
+ newProject: "Novo projeto",
+ sortChats: "Número de chats",
+ withoutSection: "Sem seção",
+ },
+ groups: {
+ today: "Hoje",
+ yesterday: "Ontem",
+ week: "Últimos 7 dias",
+ month: "Últimos 30 dias",
+ },
+ list: {
+ created: "Criado",
+ lastActive: "Última atividade",
+ location: "Local",
+ lastModified: "Última modificação",
+ contents: "Conteúdo",
+ oneMessage: "1 mensagem",
+ messageCount: "{count} mensagens",
+ showMore: "Mostrar mais ({count})",
+ },
+ badges: {
+ pinned: "Fixado",
+ fork: "Fork",
+ compare: "Comparação",
+ },
+ menu: {
+ fork: "Criar fork",
+ moveTo: "Mover para projeto",
+ newChatInProject: "Novo chat no projeto",
+ edit: "Editar",
+ deleteProject: "Excluir projeto",
+ newChatInSection: "Novo chat na seção",
+ },
+ project: {
+ oneProject: "1 projeto",
+ projectCount: "{count} projetos",
+ },
+ empty: {
+ chatsTitle: "Nenhum chat ainda",
+ chatsDescription: "Suas conversas aparecem aqui, separadas dos seus arquivos.",
+ projectsTitle: "Nenhum projeto ainda",
+ projectsDescription: "Projetos agrupam chats relacionados e compartilham instruções entre eles.",
+ archivedTitle: "Nada arquivado",
+ archivedDescription: "Os chats que você arquivar aparecem aqui.",
+ sectionsTitle: "Nenhuma seção ainda",
+ sectionsDescription: "As seções agrupam chats e projetos na barra lateral como você quiser.",
+ sectionTitle: "Nada nesta seção ainda",
+ sectionDescription: "Mova chats para cá pelo menu deles ou inicie um novo chat nesta seção.",
+ },
+ dialog: {
+ renameChat: "Renomear chat",
+ deleteChatDescription: "Este chat será excluído permanentemente. Isso não pode ser desfeito.",
+ deleteProjectDescription: "O projeto e seus chats ({count}) serão excluídos permanentemente. Isso não pode ser desfeito.",
+ deleteFilesMany: "Remover também os arquivos e pastas de sandbox criados por esses chats.",
+ deleteProjectFilesLabel: "Excluir a pasta de trabalho do projeto",
+ deleteProjectFiles: "A pasta de trabalho do projeto será removida do disco.",
+ },
+ toast: {
+ projectMoved: "{project} movido para {section}",
+ projectUnfiled: "{project} removido de {section}",
+ forkFailed: "Falha ao criar fork",
+ projectDeleted: "“{name}” excluído",
+ projectDeleteFailed: "Falha ao excluir o projeto",
+ removedFromSection: "Removidos da seção: {count}",
+ },
+ folder: {
+ openChat: "Abrir pasta do chat",
+ openChatTitle: "Abrir a pasta que as ferramentas deste chat leem e escrevem",
+ openProject: "Abrir pasta do projeto",
+ openProjectTitle: "Abrir a pasta que os chats deste projeto leem e escrevem",
+ chatHint: "Só o app para desktop pode abrir a pasta de arquivos de um chat. No navegador, baixe o arquivo pelo resultado da ferramenta que o escreveu.",
+ projectHint: "Só o app para desktop pode abrir a pasta de um projeto. No navegador, baixe os arquivos pelos resultados das ferramentas que os escreveram.",
+ manyFolders: "Este chat escreveu em mais de uma pasta.",
+ manyFoldersDescription: "Ele executou ferramentas antes e depois de ser movido, então abra a pasta por um cartão de ferramenta.",
+ chatFailed: "Não foi possível abrir a pasta do chat.",
+ projectFailed: "Não foi possível abrir a pasta do projeto.",
+ chatMissing: "Este chat ainda não tem pasta.",
+ projectMissing: "Este projeto ainda não tem pasta.",
+ missingDescription: "Ela é criada na primeira vez que uma ferramenta escreve um arquivo.",
+ },
},
empty: {
suggestedTitle: "Sua biblioteca está vazia",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index c1d4e87f777..3918c8fd0c1 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1779,6 +1779,11 @@ export const ru = {
advanced: { title: "Дополнительно" },
contextTitle: "Контекст",
},
+ library: {
+ label: "Управление чатами",
+ description: "Ищите, сортируйте и упорядочивайте чаты, проекты и разделы.",
+ action: "Открыть Библиотеку",
+ },
projectAttachmentsHint:
"Для отдельного чата настройку можно изменить в его меню вложений.",
rememberParamsPerModelHint:
@@ -2048,9 +2053,6 @@ export const ru = {
archivedAudio: "Архивированные аудио",
archivedAudioDescription: "Просмотр и управление аудиоклипами, которые вы архивировали.",
manageAction: "Управлять",
- manageChats: "Управление чатами",
- manageChatsDescription:
- "Выберите несколько чатов, чтобы переместить, закрепить, архивировать, экспортировать или удалить их.",
exportArchivedChats: "Экспорт",
exportingArchivedChats: "Экспорт…",
exportedOneArchivedChat: "Экспортирован 1 архивный чат",
@@ -3100,6 +3102,116 @@ export const ru = {
audio: "Аудио",
models: "Дообученные",
all: "Все",
+ chats: "Чаты",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "Чаты",
+ projects: "Проекты",
+ archived: "Архив",
+ ariaLabel: "Разделы чатов",
+ },
+ search: {
+ chats: "Поиск по чатам",
+ projects: "Поиск по проектам",
+ archived: "Поиск по архивным чатам",
+ project: "Поиск в «{project}»",
+ sections: "Поиск разделов",
+ },
+ toolbar: {
+ show: "Показать",
+ pinned: "Закреплённые",
+ forks: "Ответвления",
+ comparisons: "Сравнения",
+ project: "Проект",
+ model: "Модель",
+ groupBy: "Группировать по",
+ groupNone: "Без группировки",
+ groupDate: "Дате",
+ groupProject: "Проекту",
+ pinnedFirst: "Закреплённые сначала",
+ newChat: "Новый чат",
+ newProject: "Новый проект",
+ sortChats: "Количеству чатов",
+ withoutSection: "Без раздела",
+ },
+ groups: {
+ today: "Сегодня",
+ yesterday: "Вчера",
+ week: "Последние 7 дней",
+ month: "Последние 30 дней",
+ },
+ list: {
+ created: "Создан",
+ lastActive: "Последняя активность",
+ location: "Расположение",
+ lastModified: "Последнее изменение",
+ contents: "Содержимое",
+ oneMessage: "1 сообщение",
+ messageCount: "Сообщений: {count}",
+ showMore: "Показать ещё ({count})",
+ },
+ badges: {
+ pinned: "Закреплён",
+ fork: "Ответвление",
+ compare: "Сравнение",
+ },
+ menu: {
+ fork: "Создать ответвление",
+ moveTo: "Переместить в проект",
+ newChatInProject: "Новый чат в проекте",
+ edit: "Изменить",
+ deleteProject: "Удалить проект",
+ newChatInSection: "Новый чат в разделе",
+ },
+ project: {
+ oneProject: "1 проект",
+ projectCount: "Проектов: {count}",
+ },
+ empty: {
+ chatsTitle: "Чатов пока нет",
+ chatsDescription: "Здесь появляются ваши разговоры, отдельно от файлов.",
+ projectsTitle: "Проектов пока нет",
+ projectsDescription: "Проекты объединяют связанные чаты с общими инструкциями.",
+ archivedTitle: "Архив пуст",
+ archivedDescription: "Здесь появляются чаты, которые вы архивируете.",
+ sectionsTitle: "Разделов пока нет",
+ sectionsDescription: "Разделы группируют чаты и проекты на боковой панели так, как вам удобно.",
+ sectionTitle: "В этом разделе пока ничего нет",
+ sectionDescription: "Переместите чаты сюда через их меню или начните новый чат в этом разделе.",
+ },
+ dialog: {
+ renameChat: "Переименовать чат",
+ deleteChatDescription: "Этот чат будет удалён без возможности восстановления.",
+ deleteProjectDescription: "Проект и его чаты ({count}) будут удалены без возможности восстановления.",
+ deleteFilesMany: "Также удалить файлы и папки песочницы, созданные этими чатами.",
+ deleteProjectFilesLabel: "Удалить рабочую папку проекта",
+ deleteProjectFiles: "Рабочая папка проекта будет удалена с диска.",
+ },
+ toast: {
+ projectMoved: "{project} перемещён в {section}",
+ projectUnfiled: "{project} убран из {section}",
+ forkFailed: "Не удалось создать ответвление",
+ projectDeleted: "«{name}» удалён",
+ projectDeleteFailed: "Не удалось удалить проект",
+ removedFromSection: "Убрано из раздела: {count}",
+ },
+ folder: {
+ openChat: "Открыть папку чата",
+ openChatTitle: "Открыть папку, которую читают и пишут инструменты этого чата",
+ openProject: "Открыть папку проекта",
+ openProjectTitle: "Открыть папку, которую читают и пишут чаты этого проекта",
+ chatHint: "Открыть папку файлов чата можно только в настольном приложении. В браузере скачайте файл из результата инструмента, который его записал.",
+ projectHint: "Открыть папку проекта можно только в настольном приложении. В браузере скачайте файлы из результатов инструментов, которые их записали.",
+ manyFolders: "Этот чат записывал в несколько папок.",
+ manyFoldersDescription: "Он запускал инструменты до и после перемещения, поэтому откройте папку из карточки инструмента.",
+ chatFailed: "Не удалось открыть папку чата.",
+ projectFailed: "Не удалось открыть папку проекта.",
+ chatMissing: "У этого чата пока нет папки.",
+ projectMissing: "У этого проекта пока нет папки.",
+ missingDescription: "Она создаётся, когда инструмент впервые записывает файл.",
+ },
},
empty: {
suggestedTitle: "Ваша библиотека пуста",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 446ace57398..225e6aee113 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1730,6 +1730,11 @@ export const zhCN = {
advanced: { title: "高级" },
contextTitle: "上下文",
},
+ library: {
+ label: "管理聊天",
+ description: "搜索、排序并整理聊天、项目和分组。",
+ action: "打开资料库",
+ },
projectAttachmentsHint: "可在各聊天的附件菜单中单独调整此设置。",
rememberParamsPerModelHint: "关闭后,所有模型使用同一套设置。",
autoCompactHint: "仅适用于本地 GGUF 聊天。被移出的轮次会建立索引,模型可以再检索回来;重置时会原文保留放得下的长期指令,优先保留最早和最新的,而不是中间的。归档需要已保存的聊天和向量索引,两者缺一时较早的轮次会被直接丢弃。依据你设置的上下文长度,而不是可用显存。",
@@ -1992,8 +1997,6 @@ export const zhCN = {
archivedAudio: "已归档的音频",
archivedAudioDescription: "查看和管理你归档的音频片段。",
manageAction: "管理",
- manageChats: "管理聊天",
- manageChatsDescription: "选择多个聊天进行移动、置顶、归档、导出或删除。",
exportArchivedChats: "导出",
exportingArchivedChats: "正在导出...",
exportedOneArchivedChat: "已导出 1 个归档聊天",
@@ -2980,6 +2983,116 @@ export const zhCN = {
audio: "音频",
models: "微调模型",
all: "全部",
+ chats: "聊天",
+ },
+ // The Chats tab: conversations and projects, kept apart from every file tab.
+ chats: {
+ sections: {
+ chats: "聊天",
+ projects: "项目",
+ archived: "已归档",
+ ariaLabel: "聊天分区",
+ },
+ search: {
+ chats: "搜索聊天",
+ projects: "搜索项目",
+ archived: "搜索已归档的聊天",
+ project: "在“{project}”中搜索",
+ sections: "搜索分区",
+ },
+ toolbar: {
+ show: "显示",
+ pinned: "已置顶",
+ forks: "分支",
+ comparisons: "对比",
+ project: "项目",
+ model: "模型",
+ groupBy: "分组方式",
+ groupNone: "不分组",
+ groupDate: "日期",
+ groupProject: "项目",
+ pinnedFirst: "置顶优先",
+ newChat: "新建聊天",
+ newProject: "新建项目",
+ sortChats: "聊天数量",
+ withoutSection: "无分区",
+ },
+ groups: {
+ today: "今天",
+ yesterday: "昨天",
+ week: "过去 7 天",
+ month: "过去 30 天",
+ },
+ list: {
+ created: "创建时间",
+ lastActive: "最近活动",
+ location: "位置",
+ lastModified: "上次修改",
+ contents: "内容",
+ oneMessage: "1 条消息",
+ messageCount: "{count} 条消息",
+ showMore: "显示更多({count})",
+ },
+ badges: {
+ pinned: "已置顶",
+ fork: "分支",
+ compare: "对比",
+ },
+ menu: {
+ fork: "创建分支",
+ moveTo: "移动到项目",
+ newChatInProject: "在项目中新建聊天",
+ edit: "编辑",
+ deleteProject: "删除项目",
+ newChatInSection: "在分区中新建聊天",
+ },
+ project: {
+ oneProject: "1 个项目",
+ projectCount: "{count} 个项目",
+ },
+ empty: {
+ chatsTitle: "还没有聊天",
+ chatsDescription: "你的对话会显示在这里,与文件分开存放。",
+ projectsTitle: "还没有项目",
+ projectsDescription: "项目将相关聊天归为一组,并共享指令。",
+ archivedTitle: "没有已归档内容",
+ archivedDescription: "你归档的聊天会显示在这里。",
+ sectionsTitle: "还没有分区",
+ sectionsDescription: "分区可按你的方式在侧边栏中归类聊天和项目。",
+ sectionTitle: "此分区中还没有内容",
+ sectionDescription: "从聊天的菜单将其移到这里,或在此分区中开始新聊天。",
+ },
+ dialog: {
+ renameChat: "重命名聊天",
+ deleteChatDescription: "此聊天将被永久删除,且无法撤销。",
+ deleteProjectDescription: "该项目及其聊天({count} 个)将被永久删除,且无法撤销。",
+ deleteFilesMany: "同时删除这些聊天创建的文件和沙盒文件夹。",
+ deleteProjectFilesLabel: "删除项目工作文件夹",
+ deleteProjectFiles: "项目工作文件夹将从磁盘中删除。",
+ },
+ toast: {
+ projectMoved: "已将 {project} 移到 {section}",
+ projectUnfiled: "已将 {project} 从 {section} 中移除",
+ forkFailed: "创建分支失败",
+ projectDeleted: "已删除“{name}”",
+ projectDeleteFailed: "无法删除项目",
+ removedFromSection: "已移出分区:{count}",
+ },
+ folder: {
+ openChat: "打开聊天文件夹",
+ openChatTitle: "打开此聊天的工具调用读写的文件夹",
+ openProject: "打开项目文件夹",
+ openProjectTitle: "打开此项目的聊天读写的文件夹",
+ chatHint: "只有桌面应用可以打开聊天的文件文件夹。在浏览器中,请从写入该文件的工具结果中下载。",
+ projectHint: "只有桌面应用可以打开项目文件夹。在浏览器中,请从写入这些文件的工具结果中下载。",
+ manyFolders: "此聊天写入了多个文件夹。",
+ manyFoldersDescription: "它在移动前后都运行了工具,请改为从工具卡片打开文件夹。",
+ chatFailed: "无法打开聊天文件夹。",
+ projectFailed: "无法打开项目文件夹。",
+ chatMissing: "此聊天还没有文件夹。",
+ projectMissing: "此项目还没有文件夹。",
+ missingDescription: "工具首次写入文件时会创建它。",
+ },
},
empty: {
suggestedTitle: "资料库为空",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index e2b3dcf5039..840423e7a2a 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -2997,11 +2997,28 @@ html[data-chat-font] .aui-root {
box-shadow: 0 8px 28px -6px var(--background) !important;
}
- /* Library card menus: match the card menu button so they stand off the cards. */
- .dark [data-slot="dropdown-menu-content"].library-actions-menu,
- .dark [data-slot="dropdown-menu-sub-content"].library-actions-menu {
- --accent: var(--color-neutral-600);
- background-color: var(--color-neutral-700);
+ /* Library menus in dark: the sidebar menus' surface, text, hover, dividers and red. */
+ .dark :is([data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-sub-content"]):is(.library-actions-menu, .library-menu) {
+ --library-menu-surface: color-mix(in srgb, var(--card), white 7%);
+ --accent: color-mix(in srgb, var(--library-menu-surface), white 10%);
+ --accent-foreground: #fff;
+ --destructive: #ed716a;
+ background-color: var(--library-menu-surface);
+ color: #fff;
+ box-shadow: 0 4px 14px var(--background) !important;
+ }
+
+ .dark :is(.library-actions-menu, .library-menu) [data-slot="dropdown-menu-separator"] {
+ background-color: color-mix(in srgb, var(--card), white 16%);
+ }
+
+ /* Library header row once stuck: a lighter take on the composer's shadow, cast below only. */
+ .library-header-row[data-stuck] {
+ box-shadow: 0 2px 6px -3px rgba(0, 0, 0, 0.1);
+ clip-path: inset(0 0 -40px 0);
+ }
+ .dark .library-header-row[data-stuck] {
+ box-shadow: 0 2px 10px -2px var(--background);
}
/* Model selector: tighter than the menus above so it lifts off the
diff --git a/studio/frontend/tests/library-chats.test.ts b/studio/frontend/tests/library-chats.test.ts
new file mode 100644
index 00000000000..53d578432db
--- /dev/null
+++ b/studio/frontend/tests/library-chats.test.ts
@@ -0,0 +1,686 @@
+// 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 {
+ type ChatEntry,
+ EMPTY_CHAT_FILTERS,
+ NO_PROJECT,
+ NO_SECTION,
+ chatFiltersActive,
+ chatTime,
+ dateBucket,
+ filterChats,
+ groupChats,
+ mixEntries,
+ modelFacets,
+ modelsByChat,
+ projectStats,
+ sectionStats,
+ sectionTime,
+ sortChats,
+ sortSections,
+ sortProjects,
+ summarizeChatMessages,
+ validateChatsSection,
+} from "../src/features/library/chats/model.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const DAY = 86_400_000;
+const now = new Date(2026, 8, 27, 12).getTime();
+
+const chats: ChatEntry[] = [
+ { id: "a", type: "single", title: "Café planning", createdAt: now - 40 * DAY, updatedAt: now - 1 * DAY, projectId: "p1" },
+ { id: "b", type: "single", title: "bug triage", createdAt: now - 3 * DAY, updatedAt: now, isFork: true },
+ { id: "c", type: "compare", title: "Model shootout", createdAt: now - 2 * DAY, updatedAt: now - 2 * DAY, projectId: "p2" },
+ { id: "d", type: "single", title: "Archive me", createdAt: now - 90 * DAY, updatedAt: now - 60 * DAY },
+];
+
+const context = {
+ pinned: new Set(["c"]),
+ projectNames: new Map([
+ ["p1", "Research"],
+ ["p2", "Evals"],
+ ]),
+ models: new Map([
+ ["a", ["unsloth/Qwen3-4B-GGUF"]],
+ ["c", ["unsloth/Qwen3-4B-GGUF", "openai/gpt-5"]],
+ ]),
+ sectionOf: new Map([
+ ["b", "s1"],
+ ["d", "s1"],
+ ]),
+ sectionNames: new Map([["s1", "Weekend reading"]]),
+};
+
+const ids = (list: { id: string }[]) => list.map((entry) => entry.id);
+
+test("search matches titles, project and section names and models, ignoring accents and case", () => {
+ assert.deepEqual(ids(filterChats(chats, "cafe", EMPTY_CHAT_FILTERS, context)), ["a"]);
+ assert.deepEqual(ids(filterChats(chats, "research", EMPTY_CHAT_FILTERS, context)), ["a"]);
+ assert.deepEqual(ids(filterChats(chats, "gpt-5", EMPTY_CHAT_FILTERS, context)), ["c"]);
+ assert.deepEqual(ids(filterChats(chats, "BUG tri", EMPTY_CHAT_FILTERS, context)), ["b"]);
+ assert.deepEqual(ids(filterChats(chats, "weekend", EMPTY_CHAT_FILTERS, context)), ["b", "d"]);
+});
+
+test("flags narrow, projects, sections and models widen within themselves", () => {
+ const flags = (...values: ("pinned" | "forks" | "compare")[]) => ({
+ ...EMPTY_CHAT_FILTERS,
+ flags: new Set(values),
+ });
+ assert.deepEqual(ids(filterChats(chats, "", flags("pinned"), context)), ["c"]);
+ assert.deepEqual(ids(filterChats(chats, "", flags("forks"), context)), ["b"]);
+ assert.deepEqual(ids(filterChats(chats, "", flags("forks", "compare"), context)), []);
+ const projects = { ...EMPTY_CHAT_FILTERS, projects: new Set(["p1", NO_PROJECT]) };
+ assert.deepEqual(ids(filterChats(chats, "", projects, context)), ["a", "b", "d"]);
+ const sections = { ...EMPTY_CHAT_FILTERS, sections: new Set([NO_SECTION]) };
+ assert.deepEqual(ids(filterChats(chats, "", sections, context)), ["a", "c"]);
+ assert.equal(chatFiltersActive(sections), true);
+ const models = { ...EMPTY_CHAT_FILTERS, models: new Set(["unsloth/Qwen3-4B-GGUF"]) };
+ assert.deepEqual(ids(filterChats(chats, "", models, context)), ["a", "c"]);
+ assert.equal(chatFiltersActive(EMPTY_CHAT_FILTERS), false);
+ assert.equal(chatFiltersActive(models), true);
+});
+
+test("sorting honours key, direction and pinned-first", () => {
+ const byName = sortChats(chats, { key: "name", desc: false }, context.pinned, false);
+ assert.deepEqual(ids(byName), ["d", "b", "a", "c"]);
+ const recent = sortChats(chats, { key: "updated", desc: true }, context.pinned, false);
+ assert.deepEqual(ids(recent), ["b", "a", "c", "d"]);
+ const pinnedFirst = sortChats(chats, { key: "updated", desc: true }, context.pinned, true);
+ assert.deepEqual(ids(pinnedFirst), ["c", "b", "a", "d"]);
+ const oldestCreated = sortChats(chats, { key: "created", desc: false }, context.pinned, false);
+ assert.deepEqual(ids(oldestCreated), ["d", "a", "b", "c"]);
+});
+
+test("date buckets and groups keep time order even under a name sort", () => {
+ assert.equal(dateBucket(now, now).kind, "today");
+ assert.equal(dateBucket(now - DAY, now).kind, "yesterday");
+ assert.equal(dateBucket(now - 3 * DAY, now).kind, "week");
+ assert.equal(dateBucket(now - 20 * DAY, now).kind, "month");
+ assert.deepEqual(dateBucket(now - 60 * DAY, now), { kind: "older", year: 2026, month: 6 });
+
+ const byName = sortChats(chats, { key: "name", desc: false }, new Set(), false);
+ const groups = groupChats(byName, "date", { now });
+ assert.deepEqual(
+ groups.map((group) => group.key),
+ ["today", "yesterday", "week", "older:2026-6"],
+ );
+ const oldest = groupChats(byName, "date", { now, oldestFirst: true });
+ assert.equal(oldest[0]?.key, "older:2026-6");
+});
+
+test("project groups put chats outside any project last", () => {
+ const groups = groupChats(chats, "project", { now });
+ assert.deepEqual(
+ groups.map((group) => group.projectId),
+ ["p1", "p2", null],
+ );
+ assert.deepEqual(ids(groups[2]?.items ?? []), ["b", "d"]);
+ assert.deepEqual(groupChats([], "none"), []);
+});
+
+test("section groups put unfiled chats last, and pinned chats lead in their own group", () => {
+ const bySection = groupChats(chats, "section", { now, sectionOf: context.sectionOf });
+ assert.deepEqual(
+ bySection.map((group) => [group.sectionId, ids(group.items)]),
+ [
+ ["s1", ["b", "d"]],
+ [null, ["a", "c"]],
+ ],
+ );
+ // Pinned "c" gets its own group instead of reordering "week".
+ const byDate = groupChats(chats, "date", { now, pinned: context.pinned });
+ assert.deepEqual(
+ byDate.map((group) => group.key),
+ ["pinned", "today", "yesterday", "older:2026-6"],
+ );
+ assert.deepEqual(ids(byDate[0]?.items ?? []), ["c"]);
+ assert.equal(byDate[0]?.pinned, true);
+ assert.deepEqual(groupChats(chats, "none", { pinned: context.pinned })[0]?.items.length, 4);
+});
+
+test("project stats count live and archived chats and track last activity", () => {
+ const projects = [
+ { id: "p1", name: "Research", createdAt: 1, updatedAt: 2 },
+ { id: "p2", name: "evals", createdAt: 5, updatedAt: 3 },
+ { id: "p3", name: "Empty", createdAt: 9, updatedAt: 4 },
+ ];
+ const archived: ChatEntry[] = [
+ { id: "z", type: "single", title: "old", createdAt: 0, updatedAt: 0, projectId: "p1" },
+ ];
+ const stats = projectStats(projects, chats, archived);
+ assert.deepEqual(stats.get("p1"), { chats: 1, archived: 1, lastActive: now - DAY });
+ assert.deepEqual(stats.get("p3"), { chats: 0, archived: 0, lastActive: 4 });
+ const byChats = sortProjects(projects, { key: "chats", desc: true }, stats, new Set());
+ assert.deepEqual(ids(byChats), ["p2", "p1", "p3"]);
+ const pinnedFirst = sortProjects(projects, { key: "name", desc: false }, stats, new Set(["p3"]));
+ assert.deepEqual(ids(pinnedFirst), ["p3", "p2", "p1"]);
+});
+
+test("models key compare pairs by pair id and rank facets by use", () => {
+ const models = modelsByChat([
+ { id: "t1", modelIds: ["m1"] },
+ { id: "pair", modelIds: ["m1", "m2"] },
+ { id: "t4" },
+ ]);
+ assert.deepEqual(models.get("pair"), ["m1", "m2"]);
+ assert.equal(models.has("t4"), false);
+ const facets = modelFacets(
+ [
+ { id: "t1", type: "single", title: "", createdAt: 0, updatedAt: 0 },
+ { id: "pair", type: "compare", title: "", createdAt: 0, updatedAt: 0 },
+ ],
+ models,
+ );
+ assert.deepEqual(facets, [
+ { model: "m1", count: 2 },
+ { model: "m2", count: 1 },
+ ]);
+});
+
+test("chats tab validates its view and sits between Folders and Images", () => {
+ assert.equal(validateChatsSection("archived"), "archived");
+ assert.equal(validateChatsSection("latest"), undefined);
+ const search = readSrc("features/library/search.ts");
+ const tabs = search.slice(search.indexOf("LIBRARY_TABS = ["), search.indexOf("] as const"));
+ assert.match(tabs, /"folders",\s*\/\/[^\n]*\n\s*"chats",\s*"images",/);
+ assert.doesNotMatch(readSrc("features/library/components/library-header.tsx"), /separated/);
+});
+
+test("a starred chat narrows by the Favorites flag and lists in the Favorites tab alone", () => {
+ const favorites = { ...context, favorites: new Set(["a", "d"]) };
+ const starred = { ...EMPTY_CHAT_FILTERS, flags: new Set(["favorite" as const]) };
+ assert.deepEqual(ids(filterChats(chats, "", starred, favorites)), ["a", "d"]);
+ assert.deepEqual(ids(filterChats(chats, "", starred, context)), []);
+ const page = readSrc("features/library/library-page.tsx");
+ assert.match(page, /useFavoriteChatMatches\(query, tab === "favorites" && !folderId\)/);
+ assert.match(page, /if \(favoriteChats > 0\) return renderFavorites\(\);/);
+ assert.match(page, /leading=\{entries\.rows\}/);
+ assert.match(page, /\.\.\.entries\.cards,/);
+});
+
+test("section stats count filed chats and live projects, and sections sort by them", () => {
+ const sections = [
+ { id: "s1", name: "Weekend reading", sort: "manual" },
+ { id: "s2", name: "archive", sort: "manual" },
+ ];
+ const stats = sectionStats(
+ sections,
+ chats,
+ context.sectionOf,
+ new Map([
+ ["p1", "s2"],
+ ["gone", "s2"],
+ ]),
+ new Set(["p1"]),
+ );
+ assert.deepEqual(stats.get("s1"), { chats: 2, projects: 0, lastActive: now });
+ assert.deepEqual(stats.get("s2"), { chats: 0, projects: 1, lastActive: 0 });
+ assert.deepEqual(ids(sortSections(sections, { key: "updated", desc: true }, stats)), ["s1", "s2"]);
+ assert.deepEqual(ids(sortSections(sections, { key: "name", desc: false }, stats)), ["s2", "s1"]);
+ assert.equal(validateChatsSection("sections"), "sections");
+ const search = readSrc("features/library/search.ts");
+ assert.match(search, /typeof search\.chatSection === "string" \? \{ chatSection: search\.chatSection \}/);
+});
+
+test("chats never enter the file listing that every other tab reads", () => {
+ // File tabs read the library API; chat history must not feed it.
+ for (const file of ["api.ts", "store.ts", "file-kind.ts", "filters.ts"]) {
+ const source = readSrc(`features/library/${file}`);
+ assert.doesNotMatch(source, /useChatSidebarItems|listStoredChatThreads|chats\/model/, file);
+ }
+ const page = readSrc("features/library/library-page.tsx");
+ assert.match(page, /if \(tab === "chats" && !folderId\) \{\s*return <ChatsLibrary/);
+});
+
+test("the Chats tab opens on All, and a project opens its home in Chat", () => {
+ assert.equal(validateChatsSection("all"), "all");
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ assert.match(library, /search\.chatSection \? "chats" : \(search\.chatView \?\? "all"\)/);
+ assert.match(library, /go\(entry === "all" \? \{\} : \{ chatView: entry \}\)/);
+ assert.match(library, /void navigate\(\{ to: "\/chat", search: \{ project: id \} \}\)/);
+ assert.doesNotMatch(readSrc("features/library/search.ts"), /project\?: string/);
+ assert.doesNotMatch(readSrc("features/settings/tabs/data-tab.tsx"), /manageChats/);
+ assert.match(
+ readSrc("features/settings/tabs/chat-tab.tsx"),
+ /void navigate\(\{ to: "\/library", search: \{ show: "chats" \} \}\)/,
+ );
+ assert.match(library, /return chatListing\(true\);/);
+ assert.match(library, /mixEntries\(visibleChats, visibleProjects, visibleSections, \{/);
+ assert.match(library, /const ungrouped = embedded \|\| section === "all";/);
+ assert.match(library, /pinned: pinnedFirst && !ungrouped \? pinned : undefined,/);
+ assert.match(readSrc("features/library/chats/chats-items.tsx"), /<OpenChatFolderItem item=\{chat\} \/>/);
+});
+
+test("contents count messages on the shown branch", () => {
+ const message = (id: string, parentId: string | null, role: string, createdAt: number) => ({
+ id,
+ parentId,
+ role,
+ createdAt,
+ });
+ const summary = summarizeChatMessages([
+ message("u1", null, "user", 1),
+ message("a1", "u1", "assistant", 2),
+ // An older sibling of a1, from a regenerate: not on the shown branch.
+ message("a0", "u1", "assistant", 1.5),
+ message("u2", "a1", "user", 3),
+ message("s", null, "system", 0),
+ ]);
+ assert.deepEqual(summary, { messages: 3 });
+ assert.deepEqual(summarizeChatMessages([]), { messages: 0 });
+});
+
+test("one date column picks created, last active or last modified", () => {
+ const chat = { ...chats[0]!, createdAt: 1, updatedAt: 5, modifiedAt: 9 };
+ assert.equal(chatTime(chat, "created"), 1);
+ assert.equal(chatTime(chat, "updated"), 5);
+ assert.equal(chatTime(chat, "modified"), 9);
+ // A rename older than the last message leaves modified at the last message.
+ assert.equal(chatTime({ ...chat, modifiedAt: 2 }, "modified"), 5);
+ const older = { ...chat, id: "older", modifiedAt: 3 };
+ const sorted = sortChats([older, chat], { key: "modified", desc: true }, new Set(), false);
+ assert.deepEqual(ids(sorted), [chat.id, "older"]);
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /export function DateHeader\(/);
+ assert.doesNotMatch(items, /CREATED_COLUMN/);
+});
+
+test("Favorites draws starred chats, projects and sections as file cards, without a star", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /export function FavoriteSectionTile\(/);
+ assert.match(items, /if \(!useChatsActions\(\)\.favoriteMarks\) return null;/);
+ assert.match(readSrc("features/library/chats/favorites-store.ts"), /sectionIds: readIds\(saved\?\.sectionIds\)/);
+ assert.match(readSrc("features/library/library-page.tsx"), /favoriteMarks=\{tab !== "favorites"\}/);
+});
+
+test("the Library chat menu marks a chat read or unread", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /unread \? ViewIcon : ViewOffSlashIcon/);
+ assert.match(items, /"shell\.selection\.markRead"/);
+});
+
+test("the Library lists chat metadata and counts messages without reading them", () => {
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ assert.match(library, /useChatSidebarItems\(\{ requireMessages: false \}\)/);
+ assert.match(
+ readSrc("features/library/chats/favorites.ts"),
+ /useChatSidebarItems\(\{ enabled, requireMessages: false \}\)/,
+ );
+ const contents = readSrc("features/library/chats/contents.ts");
+ assert.match(contents, /await countStoredChatMessages\(ids\)/);
+ // A re-render must not cancel a read in flight and ask for the same batch again.
+ assert.doesNotMatch(contents, /let cancelled/);
+ assert.match(contents, /!pending\.has\(key\)/);
+});
+
+test("last modified is the server's, stamped by renames, moves and archiving", () => {
+ const sidebar = readSrc("features/chat/hooks/use-chat-sidebar-items.ts");
+ assert.match(sidebar, /\.\.\.\(t\.modifiedAt \? \{ modifiedAt: t\.modifiedAt \} : \{\}\)/);
+ assert.doesNotMatch(readSrc("features/chat/index.ts"), /useChatModifiedStore/);
+});
+
+test("deleting clears stars and pins only once the chats are gone", () => {
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ const start = library.indexOf("async function confirmDelete(");
+ const block = library.slice(start, library.indexOf("const { project } = target;", start));
+ const deleted = block.indexOf("await deleteChatItems(");
+ assert.ok(deleted !== -1);
+ assert.ok(block.indexOf("setFavoriteChats(ids, false)") > deleted);
+ assert.ok(block.indexOf("setPinned(ids, false)") > deleted);
+ assert.match(library, /if \(confirmDeleteChats\) setPendingDelete\(target\);/);
+});
+
+test("shift-click selects a range anchored on a chat id", () => {
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ assert.match(library, /const selectionAnchor = useRef<string \| null>\(null\);/);
+ assert.match(library, /range && anchor \? rangeBetween\(shownOrder, anchor, id\) : \[id\]/);
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /toggleSelected\(chat\.id, event\.shiftKey\)/);
+});
+
+test("a chat exports per pane with Markdown, several chats combined or per chat", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /chatExportOptions\(\)\.map/);
+ assert.match(items, /<BulkExportItems onExport=/);
+ assert.match(readSrc("features/chat/components/bulk-export-items.tsx"), /COMBINED_EXPORT_FORMATS_LIST\.map/);
+ assert.match(items, /disabled=\{!actions\.projectChatCounts\.get\(project\.id\)\}/);
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ assert.match(library, /for \(const id of threadIds\) await exportConversationByFormat\(id, choice\.format\);/);
+});
+
+test("fork is off while the chat generates or another fork runs", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /disabled=\{!canForkChatRow\(chat\) \|\| generating \|\| forking\}/);
+});
+
+test("All sorts chats, projects and sections together, pinned first", () => {
+ const project = { id: "p1", name: "Research", createdAt: now - 5 * DAY, updatedAt: now - 5 * DAY };
+ const section = { id: "s1", name: "Weekend reading" };
+ const options = {
+ sort: { key: "updated", desc: true } as const,
+ projectStats: new Map([["p1", { chats: 1, archived: 0, lastActive: now - 1.5 * DAY }]]),
+ sectionStats: new Map([["s1", { chats: 2, projects: 0, lastActive: now - 0.5 * DAY }]]),
+ pinned: new Set<string>(),
+ pinnedProjects: new Set<string>(),
+ pinnedFirst: true,
+ };
+ const key = (entries: { kind: string; item: { id: string } }[]) =>
+ entries.map((entry) => `${entry.kind}:${entry.item.id}`);
+ assert.deepEqual(key(mixEntries(chats, [project], [section], options)), [
+ "chat:b",
+ "section:s1",
+ "chat:a",
+ "project:p1",
+ "chat:c",
+ "chat:d",
+ ]);
+ const pinned = mixEntries(chats, [project], [section], {
+ ...options,
+ pinnedProjects: new Set(["p1"]),
+ });
+ assert.equal(key(pinned)[0], "project:p1");
+ const byName = mixEntries(chats, [project], [section], {
+ ...options,
+ sort: { key: "name", desc: false },
+ });
+ assert.deepEqual(key(byName).slice(0, 3), ["chat:d", "chat:b", "chat:a"]);
+});
+
+test("an empty Library opens on Chats whatever the start tab", () => {
+ const page = readSrc("features/library/library-page.tsx");
+ assert.match(page, /if \(emptyOnLoad === null && loaded\) setEmptyOnLoad\(items\.length === 0 && folders\.length === 0\);/);
+ assert.doesNotMatch(page, /settings\.startTab === "last" &&\n\s*tabVisible\("chats"\)/);
+ assert.match(page, /!\(preferred === "favorites" && hasStarredChats\)/);
+});
+
+test("sections have created and last modified dates, and Last modified is the default", async () => {
+ const stats = { chats: 1, projects: 0, lastActive: 50 };
+ const section = { id: "s", name: "S", createdAt: 10, modifiedAt: 80 };
+ assert.equal(sectionTime(section, stats, "created"), 10);
+ assert.equal(sectionTime(section, stats, "updated"), 50);
+ assert.equal(sectionTime(section, stats, "modified"), 80);
+ // A newer chat counts as a change, as it does for chats; old sections have no created date.
+ assert.equal(sectionTime({ id: "o", name: "O" }, stats, "modified"), 50);
+ assert.equal(sectionTime({ id: "o", name: "O" }, stats, "created"), 0);
+ const sorted = sortSections(
+ [section, { id: "t", name: "T", modifiedAt: 90 }],
+ { key: "modified", desc: true },
+ new Map([["s", stats]]),
+ );
+ assert.deepEqual(ids(sorted), ["t", "s"]);
+ const prefs = readSrc("features/library/chats/prefs-store.ts");
+ assert.match(prefs, /dateField: "modified",/);
+ assert.match(prefs, /sort: \{ key: "modified", desc: true \},/);
+ assert.doesNotMatch(readSrc("features/library/chats/chats-items.tsx"), /field="updated"/);
+});
+
+test("chat, project and section cards are a little shorter than square, dated bottom left", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ const card = items.slice(items.indexOf("const CARD = cn("), items.indexOf("const ICON ="));
+ assert.match(card, /aspect-\[8\/7\]/);
+ assert.doesNotMatch(card, /overflow-hidden/);
+ assert.match(card, /self-stretch/);
+ assert.doesNotMatch(items, /cn\(CARD, "min-h-/);
+ assert.doesNotMatch(items, /justify-between gap-2 text-ui-12 text-muted-foreground/);
+});
+
+test("chat, project and section tiles share one box and hover tint", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /const TILE =\s*"[^"]*bg-muted[^"]*group-hover\/chat:bg-primary\/10 group-hover\/chat:text-primary"/);
+ assert.equal(items.split("group-hover/chat:bg-primary/10").length - 1, 1, "one tile style");
+ assert.match(items, /<div className=\{cn\(TILE, className\)\}>/);
+ assert.match(items, /<span className=\{TILE\}>/);
+ assert.doesNotMatch(items, /group-hover\/chat:opacity-0/);
+});
+
+test("grid cards share a two-line title and a footer of contents over date", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /const CARD_TITLE =\s*"[^"]*\[overflow-wrap:anywhere\]/);
+ assert.match(items, /const CARD_TITLE =\s*"[^"]*font-medium text-ui-14 /);
+ const footer = items.slice(items.indexOf("function CardFooter("), items.indexOf("const CARD_TITLE"));
+ assert.match(footer, /flex-col items-start/);
+ assert.match(footer, /\{meta && <span className="w-full min-w-0 truncate">\{meta\}<\/span>\}\s*<span className="truncate">\{date\}<\/span>/);
+ assert.doesNotMatch(footer, /·/);
+ const cardOf = (start: string, end: string) =>
+ items.slice(items.indexOf(start), items.indexOf(end));
+ const cards = [
+ cardOf("export function ChatCard(", "export function GroupHeading("),
+ cardOf("export function ProjectCard(", "export function ProjectRow("),
+ cardOf("export function SectionCard(", "export function SectionRow("),
+ ];
+ for (const card of cards) {
+ assert.match(card, /className=\{CARD_TITLE\}/);
+ assert.match(card, /<span className="line-clamp-2">/);
+ assert.match(card, /<CardFooter/);
+ }
+ assert.doesNotMatch(cards[0], /modelLabel|model &&/);
+ assert.match(cards[0], /<ChatBadges chat=\{chat\} marksOnly \/>/);
+ assert.doesNotMatch(cards[1], /archived/);
+ assert.match(cards[0], /<ChatLocation[^>]*plain/);
+});
+
+test("project cards in the grid leave out the instructions", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ const card = items.slice(items.indexOf("export function ProjectCard("), items.indexOf("export function ProjectRow("));
+ assert.doesNotMatch(card, /instructions/);
+});
+
+test("library menus take the sidebar menu look, with a shadow, in dark mode", () => {
+ const css = readSrc("index.css");
+ const menu = css.slice(css.indexOf("/* Library menus in dark"), css.indexOf("/* Library header row"));
+ assert.match(menu, /--library-menu-surface: color-mix\(in srgb, var\(--card\), white 7%\)/);
+ assert.match(menu, /--accent: color-mix\(in srgb, var\(--library-menu-surface\), white 10%\)/);
+ assert.match(menu, /--destructive: #ed716a/);
+ assert.match(menu, /box-shadow: 0 4px 14px var\(--background\) !important/);
+ assert.match(menu, /\[data-slot="dropdown-menu-separator"\] \{\s*background-color: color-mix\(in srgb, var\(--card\), white 16%\)/);
+ const toolbar = readSrc("features/library/components/library-toolbar.tsx");
+ assert.equal(toolbar.match(/className="library-menu /g)?.length, 3);
+ const page = readSrc("features/library/library-page.tsx");
+ assert.equal(page.match(/className="library-menu /g)?.length, 2);
+});
+
+test("the library header row casts a light shadow once stuck", () => {
+ const css = readSrc("index.css");
+ assert.match(
+ css,
+ /\.library-header-row\[data-stuck\] \{\s*box-shadow: 0 2px 6px -3px rgba\(0, 0, 0, 0\.1\);\s*clip-path: inset\(0 0 -40px 0\);/,
+ );
+ assert.match(
+ css,
+ /\.dark \.library-header-row\[data-stuck\] \{\s*box-shadow: 0 2px 10px -2px var\(--background\);/,
+ );
+ const header = readSrc("features/library/components/library-header.tsx");
+ assert.match(header, /data-stuck=\{stuck \|\| undefined\}/);
+ assert.match(header, /setStuck\(gap > /);
+});
+
+test("a favorite project tile uses the open project folder, not the file folder", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ const tile = items.slice(
+ items.indexOf("export function FavoriteProjectTile("),
+ items.indexOf("}", items.indexOf("menu={<ProjectMenu", items.indexOf("export function FavoriteProjectTile("))),
+ );
+ assert.match(tile, /icon=\{Folder02Icon\}/);
+ assert.doesNotMatch(tile, /Folder01Icon/);
+});
+
+test("a project's home and the Projects page use the Library project menu", () => {
+ const items = readSrc("features/chat/components/project-menu-items.tsx");
+ const order = [
+ "onNewChat && (",
+ "<OpenProjectFolderItem projectId={project.id} />",
+ "onSelect={onEdit}",
+ "togglePin(project.id)",
+ "setFavorites([project.id], !favorite)",
+ "shell.sections.moveTo",
+ "<BulkExportItems",
+ "settings.chat.importChats",
+ "{!opening && <OpenProjectFolderItem",
+ "onSelect={onDelete}",
+ ];
+ let at = -1;
+ for (const marker of order) {
+ const next = items.indexOf(marker);
+ assert.ok(next > at, `${marker} in order`);
+ at = next;
+ }
+ const page = readSrc("features/chat/chat-page.tsx");
+ const homeMenu = page.slice(page.indexOf("<ProjectMenuItems"), page.indexOf("/>", page.indexOf("<ProjectMenuItems")));
+ assert.match(homeMenu, /project=\{\{ id: projectId, name: projectName \}\}\s+chatCount=\{items\.length\}/);
+ assert.doesNotMatch(homeMenu, /onNewChat/);
+ assert.match(page, /<SectionNameDialog\s+open=\{active && creatingSection\}/);
+ const projects = readSrc("features/chat/projects-page.tsx");
+ assert.match(projects, /<ProjectMenuItems\s+project=\{project\}\s+onNewChat=/);
+ assert.match(projects, /onNewChat=\{\(\) => newChatInProject\(project\.id\)\}/);
+ for (const source of [page, projects, readSrc("features/library/chats/chats-library.tsx"), items]) {
+ assert.match(source, /useFileProjectInSection\(\)/);
+ }
+});
+
+test("Edit and Pin read the same, with the sidebar's icon, in the project menus", () => {
+ const menu = readSrc("features/chat/components/project-menu-items.tsx");
+ assert.match(menu, /<Item icon=\{Settings02Icon\} onSelect=\{onEdit\}>\s*\{t\("library\.chats\.menu\.edit"\)\}/);
+ assert.match(menu, /t\(pinned \? "settings\.data\.library\.unpin" : "settings\.data\.library\.pin"\)/);
+ assert.doesNotMatch(menu, /Edit project|Pin project|Edit03Icon/);
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /icon=\{Settings02Icon\}\s*label=\{t\("library\.chats\.menu\.edit"\)\}/);
+ assert.match(readSrc("i18n/locales/en.ts"), /\n edit: "Edit",/);
+});
+
+test("Import chats sits in the project and section menus", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /pickAndImportChats\(\{ projectId: project\.id, name: project\.name \}\)/);
+ assert.match(items, /pickAndImportChats\(\{ projectId: null, sectionId: section\.id, name: section\.name \}\)/);
+ const runner = readSrc("features/chat/utils/import-chats.ts");
+ assert.match(runner, /onSaved: \(threadId\) => threadIds\.push\(threadId\)/);
+ assert.match(runner, /setChatsSection\(\[\.\.\.new Set\(threadIds\)\], target\.sectionId\)/);
+ assert.match(readSrc("features/chat/projects-page.tsx"), /await runChatImport\(source, \{/);
+});
+
+test("the empty space in a Projects page row opens its chats", () => {
+ const page = readSrc("features/chat/projects-page.tsx");
+ assert.match(page, /<span\s+aria-hidden="true"\s+onClick=\{\(\) => toggleProjectChats\(project\.id\)\}\s+className="-my-4 min-w-0 flex-1 cursor-pointer self-stretch"/);
+ const chevron = page.indexOf("<ChevronDownIcon");
+ const spacer = page.indexOf('className="-my-4 min-w-0 flex-1 cursor-pointer self-stretch"');
+ const updated = page.indexOf('className="hidden w-40 shrink-0 text-sm text-muted-foreground sm:block"');
+ assert.ok(chevron < spacer && spacer < updated);
+});
+
+test("filing a project in a section unpins it and shows the section", () => {
+ const hook = readSrc("features/chat/hooks/use-file-project-in-section.ts");
+ assert.match(hook, /if \(pins\.pinnedIds\.includes\(project\.id\)\) pins\.unpin\(project\.id\);/);
+ assert.match(hook, /organization\.setSectionHidden\(sectionId, false\);/);
+});
+
+test("clearing the selection drops the shift-click anchor", () => {
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ assert.match(
+ library,
+ /const setSelection = useCallback\(\(next: SetStateAction<Set<string>>\) => \{\n\s*if \(typeof next !== "function" && next\.size === 0\) selectionAnchor\.current = null;/,
+ );
+ // Every emptying write goes through the wrapper, never the raw state setter.
+ assert.doesNotMatch(library, /setSelectionState\(new Set\(\)\)/);
+});
+
+test("a section's menu reads New chat, New project and Edit", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ const menu = items.slice(items.indexOf("export function SectionMenuItems("), items.indexOf("function sectionCountLabel("));
+ assert.match(menu, /label=\{t\("library\.chats\.toolbar\.newChat"\)\}/);
+ assert.match(menu, /icon=\{FolderAddIcon\}\s*label=\{t\("library\.chats\.toolbar\.newProject"\)\}\s*onSelect=\{\(\) => actions\.newProjectInSection\(section\.id\)\}/);
+ assert.match(menu, /icon=\{Settings02Icon\}\s*label=\{t\("shell\.sections\.edit"\)\}/);
+ assert.doesNotMatch(menu, /newChatInSection"\)|renameTitle/);
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ assert.match(library, /if \(newProjectSection\) fileProjectInSection\(project, newProjectSection\);/);
+ assert.match(library, /openSectionId \? newProjectInSection\(openSectionId\) : setCreatingProject\(true\)/);
+});
+
+test("a chat card's location has its project or section icon; menus leave out View chats", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ const plain = items.slice(items.indexOf(" if (plain) {"), items.indexOf('<span className="flex min-w-0 items-center gap-3">'));
+ assert.match(plain, /icon=\{projectId \? Folder02Icon : LayerIcon\}/);
+ assert.match(plain, /<span className="truncate">\{projectId \? projectName : section\?\.name\}<\/span>/);
+ // No View chats anywhere: clicking a project or section already shows its chats.
+ for (const file of [
+ "features/library/chats/chats-items.tsx",
+ "features/chat/components/project-menu-items.tsx",
+ "features/chat/projects-page.tsx",
+ ]) {
+ assert.doesNotMatch(readSrc(file), /viewChats/, file);
+ }
+ assert.doesNotMatch(readSrc("features/chat/components/project-menu-items.tsx"), /onView/);
+ assert.doesNotMatch(readSrc("i18n/locales/en.ts"), /viewChats/);
+});
+
+test("the Chats library draws every project with the open project folder", () => {
+ for (const file of ["chats-library.tsx", "chats-toolbar.tsx", "chats-items.tsx"]) {
+ assert.doesNotMatch(readSrc(`features/library/chats/${file}`), /Folder01Icon/, file);
+ }
+ assert.match(readSrc("features/library/chats/chats-library.tsx"), /projects: Folder02Icon,/);
+});
+
+test("a chat's menu has no Open chat, and its folder sits under Export", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ const menu = items.slice(items.indexOf("function ChatMenu("), items.indexOf("const TILE ="));
+ assert.doesNotMatch(menu, /library\.chats\.menu\.open"/);
+ const exportAt = menu.indexOf("<ExportSubmenu");
+ const folderAt = menu.indexOf("<OpenChatFolderItem");
+ assert.ok(exportAt !== -1 && folderAt > exportAt, "folder under Export");
+ assert.ok(!menu.slice(exportAt, folderAt).includes("DropdownMenuSeparator"), "same group as Export");
+ const projects = readSrc("features/chat/projects-page.tsx");
+ assert.ok(projects.indexOf("<OpenChatFolderItem item={chat} />") > projects.indexOf("Export all chats…"));
+});
+
+test("the Library's New chat is a saved chat with an empty composer, like the sidebar's", () => {
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ const newChatIn = library.slice(library.indexOf("const newChatIn = "), library.indexOf("async function run("));
+ assert.match(newChatIn, /clearNewChatDraft\(\);/);
+ assert.match(newChatIn, /runtime\.setIncognito\(false\);/);
+});
+
+test("a chat among Favorites files dates from its last edit, as the Chats view does", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.match(items, /<FileColumns modified=\{chatTime\(chat, "modified"\)\} \/>/);
+});
+
+test("Reset all local preferences clears the Chats library preferences", () => {
+ const general = readSrc("features/settings/tabs/general-tab.tsx");
+ const keys = general.slice(general.indexOf("const PREFS_KEYS"), general.indexOf("];", general.indexOf("const PREFS_KEYS")));
+ assert.match(keys, /LIBRARY_CHATS_PREFS_STORAGE_KEY/);
+});
+
+test("a New chat from a project's menu on the Projects page is a saved chat with an empty composer", () => {
+ const page = readSrc("features/chat/projects-page.tsx");
+ const body = page.slice(page.indexOf("function newChatInProject("), page.indexOf("function newChatInProject(") + 300);
+ assert.match(body, /clearNewChatDraft\(\);/);
+ assert.match(body, /setIncognito\(false\)/);
+});
+
+test("imported comparisons are filed under their pair id, the row the section lists", () => {
+ const source = readSrc("features/chat/utils/chat-import.ts");
+ assert.match(source, /options\.onSaved\?\.\(conversation\.thread\?\.pairId \?\? conversation\.threadId\)/);
+ assert.doesNotMatch(source, /saved\(conversation\.threadId\)/);
+});
+
+test("a favorite chat card dates from its last edit", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.doesNotMatch(items, /time=\{chat\.updatedAt\}/);
+});
+
+test("a favorite section card dates as its list row does", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ const tile = items.slice(items.indexOf("export function FavoriteSectionTile("));
+ assert.match(tile.slice(0, 800), /time=\{sectionTime\(section, stats, "modified"\)\}/);
+});
+
+test("a favorite project dates from its own last edit, as the Projects view does", () => {
+ const items = readSrc("features/library/chats/chats-items.tsx");
+ assert.doesNotMatch(items, /stats\?\.lastActive \?\? project\.updatedAt/);
+});
+
+test("a date sort on Sections also picks the date the rows show", () => {
+ const library = readSrc("features/library/chats/chats-library.tsx");
+ assert.match(library, /sectionSort: \{ key, desc \}, \.\.\.\(isDateField\(key\) \? \{ dateField: key \} : \{\}\)/);
+});
diff --git a/studio/frontend/tests/library-helpers.test.ts b/studio/frontend/tests/library-helpers.test.ts
index 942007903bd..a5350419173 100644
--- a/studio/frontend/tests/library-helpers.test.ts
+++ b/studio/frontend/tests/library-helpers.test.ts
@@ -307,6 +307,17 @@ test("an empty Fine-tunes tab hides by default, and for settings saved before th
assert.equal((migrateLibrarySettings({ tabs: hidden }, 2).tabs as typeof saved).models, "hidden");
});
+test("the Images tab shows by default, and for settings saved before that", () => {
+ assert.equal(DEFAULT_LIBRARY_SETTINGS.tabs.images, "always");
+ const saved = { ...DEFAULT_LIBRARY_SETTINGS.tabs, images: "auto" };
+ assert.equal((migrateLibrarySettings({ tabs: saved }, 3).tabs as typeof saved).images, "always");
+ const hidden = { ...saved, images: "hidden" };
+ assert.equal((migrateLibrarySettings({ tabs: hidden }, 3).tabs as typeof saved).images, "hidden");
+ // The v1 media switch left on auto lands on always too.
+ assert.equal((migrateLibrarySettings({ mediaTabs: "auto" }, 1).tabs as typeof saved).images, "always");
+ assert.equal((migrateLibrarySettings({ mediaTabs: "auto" }, 1).tabs as typeof saved).videos, "auto");
+});
+
test("a card's date shows on hover, on keyboard focus and always on touch", () => {
const date = /"([^"]*)",\s*\)}\s*>\s*\{formatCardTime/.exec(readSrc("features/library/components/library-cards.tsx"))?.[1].split(" ");
for (const reveal of [
diff --git a/studio/frontend/tests/manage-chats-bulk-selection.test.ts b/studio/frontend/tests/manage-chats-bulk-selection.test.ts
index 82ada592584..7ed00cfe89a 100644
--- a/studio/frontend/tests/manage-chats-bulk-selection.test.ts
+++ b/studio/frontend/tests/manage-chats-bulk-selection.test.ts
@@ -1,16 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// Bulk pin/unpin ordering, and the scope the header checkbox claims. The .tsx
-// view pulls in the whole app, so it is read as text; the store runs for real.
-
import assert from "node:assert/strict";
import test from "node:test";
-import { en } from "../src/i18n/locales/en.ts";
import {
installLocalStorageFake,
- readSrcAsync,
registerBundlerResolver,
} from "./helpers/kit.ts";
@@ -24,12 +19,6 @@ const { rangeBetween } = await import(
"../src/features/chat/utils/row-selection.ts"
);
-async function manageChatsSource(): Promise<string> {
- return await readSrcAsync(
- "features/settings/components/manage-chats-view.tsx",
- );
-}
-
function reset(ids: string[] = []): void {
usePinnedChatsStore.setState({ pinnedIds: ids });
}
@@ -80,34 +69,3 @@ test("a shift range survives the list re-sorting between the two clicks", () =>
assert.equal(after[1], "a");
assert.deepEqual(rangeBetween(after, after[1], "c"), ["a", "b", "c"]);
});
-
-test("the shift anchor is stored as a chat id, not a row index", async () => {
- const src = await manageChatsSource();
- assert.match(src, /useRef<string \| null>\(null\)/);
- assert.match(src, /rangeBetween\(/);
- // An index anchor addresses whatever row now sits at the saved position.
- assert.doesNotMatch(src, /lastToggledIndex/);
-});
-
-test("bulk delete passes the always-delete-files preference through", async () => {
- const src = await manageChatsSource();
- // Without this, deleteChatItems defaults args to {} and sends
- // delete_files:false, keeping every selected chat's sandbox.
- assert.match(
- src,
- /useChatPreferencesStore\(\s*\(s\) => s\.alwaysDeleteChatFiles,?\s*\)/,
- );
- assert.match(
- src,
- /deleteChatItems\(selectedItems, openChatId, resetView, \{\s*deleteFiles: alwaysDeleteChatFiles,\s*\}\)/,
- );
-});
-
-test("the header checkbox says it selects the visible chats, which is what it does", async () => {
- const src = await manageChatsSource();
- // rows sit behind "show more", so the label must not promise the whole list.
- assert.match(src, /onCheckedChange=\{toggleAllVisible\}/);
- assert.match(src, /aria-label=\{t\("settings\.data\.library\.selectAll"\)\}/);
- assert.equal(en.settings.data.library.selectAll, "Select all visible chats");
- assert.doesNotMatch(src, /aria-label="Select all chats"/);
-});
diff --git a/studio/frontend/tests/manage-chats-open-project.test.ts b/studio/frontend/tests/manage-chats-open-project.test.ts
deleted file mode 100644
index 066b69e9077..00000000000
--- a/studio/frontend/tests/manage-chats-open-project.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-// Opening a managed row must carry the row's project the way the sidebar does.
-// The .tsx view pulls in the whole app, so it is read as text.
-
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { readSrcAsync } from "./helpers/kit.ts";
-
-async function openChatSource(): Promise<string> {
- const src = await readSrcAsync(
- "features/settings/components/manage-chats-view.tsx",
- );
- const start = src.indexOf("function openChat(");
- assert.ok(start !== -1, "openChat not found in manage-chats-view.tsx");
- const end = src.indexOf("\n }", start);
- assert.ok(end !== -1, "openChat body not delimited");
- return src.slice(start, end);
-}
-
-test("openChat passes the row's project so ChatPage does not reuse the old one", async () => {
- const body = await openChatSource();
- assert.match(body, /item\.projectId/);
- assert.match(body, /project:/);
-});
-
-test("openChat carries the project for both single and compare rows", async () => {
- const body = await openChatSource();
- for (const key of ["thread:", "compare:"]) {
- const at = body.indexOf(key);
- assert.ok(at !== -1, `${key} branch not found`);
- // The spread that adds the project sits in the same object literal.
- assert.match(body.slice(at, at + 120), /\.\.\.project/);
- }
-});
diff --git a/studio/frontend/tests/projects-page-rows.test.ts b/studio/frontend/tests/projects-page-rows.test.ts
index 4ea9127f74f..f737b3a3e23 100644
--- a/studio/frontend/tests/projects-page-rows.test.ts
+++ b/studio/frontend/tests/projects-page-rows.test.ts
@@ -6,7 +6,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { readSrcAsync } from "./helpers/kit.ts";
+import { readSrc, readSrcAsync } from "./helpers/kit.ts";
import { formatWorkedFor } from "../src/lib/format-worked-for.ts";
const PAGE = await readSrcAsync("features/chat/projects-page.tsx");
@@ -82,8 +82,8 @@ test("the disclosure sits with the name it opens", () => {
// One project, two lists: the page edits it through the dialog the sidebar opens.
test("the row menu edits a project rather than only renaming it", () => {
assert.match(PAGE, /import \{ EditProjectDialog \} from "\.\/components\/edit-project-dialog";/);
- assert.match(PAGE, /onSelect=\{\(\) => setEditing\(project\)\}/);
- assert.match(PAGE, /<span>Edit<\/span>/);
+ assert.match(PAGE, /onEdit=\{\(\) => setEditing\(project\)\}/);
+ assert.match(readSrc("features/chat/components/project-menu-items.tsx"), /<Item icon=\{Settings02Icon\} onSelect=\{onEdit\}>/);
assert.match(PAGE, /<EditProjectDialog\n\s*project=\{editing\}/);
// Delete still routes to this page's own confirmation.
assert.match(PAGE, /onDelete=\{\(project\) => openProjectDelete\(project\)\}/);
@@ -278,12 +278,8 @@ test("the chat menu carries the sidebar's items, without the move", () => {
]) {
assert.ok(menu.includes(label), `${label} is missing from the chat menu`);
}
- assert.ok(!menu.includes("Mark as unread"));
- assert.ok(!menu.includes("Mark as read"));
- assert.match(menu, /<span>Open chat folder<\/span>/);
- // Desktop opens the folder; the browser says why it cannot.
- assert.match(menu, /isTauri \? \(/);
- assert.match(menu, /<OpenChatFolderUnavailableItem \/>/);
+ assert.match(menu, /chatUnread \? "shell\.selection\.markRead" : "shell\.selection\.markUnread"/);
+ assert.match(menu, /<OpenChatFolderItem item=\{chat\} \/>/);
// The chats listed here are already in this project.
assert.ok(!menu.includes("<span>Project</span>"));
assert.ok(!menu.includes("moveChatToProject"));
diff --git a/studio/frontend/tests/sandbox-reveal-path.test.ts b/studio/frontend/tests/sandbox-reveal-path.test.ts
index 69f8c5665d4..d541bc2df16 100644
--- a/studio/frontend/tests/sandbox-reveal-path.test.ts
+++ b/studio/frontend/tests/sandbox-reveal-path.test.ts
@@ -110,6 +110,12 @@ const ROW_MENU = readFileSync(
),
"utf-8",
);
+const OPEN_CHAT_FOLDER = readFileSync(
+ fileURLToPath(
+ new URL("../src/features/chat/components/open-chat-folder-item.tsx", import.meta.url),
+ ),
+ "utf-8",
+);
const PROJECTS_PAGE = readFileSync(
fileURLToPath(new URL("../src/features/chat/projects-page.tsx", import.meta.url)),
"utf-8",
@@ -146,8 +152,10 @@ test("one thread that outlived a move counts as two folders, not one", () => {
/recorded\.push\(\n\s*\.\.\.allRecordedSandboxSessionIds\(await listStoredChatMessages\(threadId\)\),\n\s*\);/,
);
// Every action refuses on more than one, rather than picking a folder.
- assert.equal(SIDEBAR.split("distinct.length > 1").length - 1, 2);
- assert.equal(PROJECTS_PAGE.split("distinct.length > 1").length - 1, 1);
+ assert.equal(SIDEBAR.split("distinct.length > 1").length - 1, 1);
+ assert.equal(OPEN_CHAT_FOLDER.split("distinct.length > 1").length - 1, 1);
+ // The Projects page draws the shared item, so it has no refusal of its own.
+ assert.equal(PROJECTS_PAGE.split("distinct.length > 1").length - 1, 0);
});
test("a sandbox holding files is told apart from one that was never written", async () => {
@@ -224,17 +232,19 @@ test("both the folder and the session id are answered from the same probe", () =
// Copy session id answered a legacy chat that had since joined a project with
// project-<id>, a folder it had never written to, and called it a success.
const callers = SIDEBAR.match(/await sandboxSessionIdsHolding\(/g) ?? [];
- assert.equal(callers.length, 2);
- for (const action of ["copyChatSessionId", "Open chat folder"]) {
- const at = SIDEBAR.indexOf(action);
- assert.notEqual(at, -1, `${action} moved`);
- }
- // The Projects page draws the same action, and reads it from the same probe.
+ assert.equal(callers.length, 1);
+ assert.notEqual(SIDEBAR.indexOf("copyChatSessionId"), -1, "copyChatSessionId moved");
assert.equal(
- (PROJECTS_PAGE.match(/await sandboxSessionIdsHolding\(/g) ?? []).length,
+ (OPEN_CHAT_FOLDER.match(/await sandboxSessionIdsHolding\(/g) ?? []).length,
1,
);
- assert.notEqual(PROJECTS_PAGE.indexOf("Open chat folder"), -1);
+ assert.notEqual(OPEN_CHAT_FOLDER.indexOf('t("library.chats.folder.openChat")'), -1);
+ // The Projects page draws the same item, so it reads the same probe.
+ assert.equal(
+ (PROJECTS_PAGE.match(/await sandboxSessionIdsHolding\(/g) ?? []).length,
+ 0,
+ );
+ assert.match(PROJECTS_PAGE, /<OpenChatFolderItem item=\{chat\} \/>/);
// Neither may reach past it to the recorded ids alone.
const copyAt = SIDEBAR.indexOf("async function copyChatSessionId");
const copy = SIDEBAR.slice(copyAt, SIDEBAR.indexOf("\n }\n", copyAt));
diff --git a/studio/frontend/tests/shortcut-dispatch-guards.test.ts b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
index fcaa659e19f..e0770e9deeb 100644
--- a/studio/frontend/tests/shortcut-dispatch-guards.test.ts
+++ b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
@@ -31,6 +31,7 @@ const SRC__ROOT = readSrc("app/routes/__root.tsx");
const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");
// The chat row menu's shared parts, drawn by the sidebar and by the Projects page.
const CHAT_ROW_MENU = readSrc("features/chat/components/chat-row-menu.ts");
+const OPEN_CHAT_FOLDER = readSrc("features/chat/components/open-chat-folder-item.tsx");
const THREAD = readSrc("components/assistant-ui/thread.tsx");
const CHAT_PAGE = readSrc("features/chat/chat-page.tsx");
const USE_SHORTCUT = readSrc("features/settings/hooks/use-shortcut.ts");
@@ -386,7 +387,8 @@ test("the sandbox probe leaves the shared project folder alone", async () => {
// them reported a second folder for any chat that joined a used project.
assert.doesNotMatch(body, /sandboxSessionIdFor\(/);
assert.doesNotMatch(body, /candidates\.add\(/);
- assert.equal(APP_SIDEBAR.split("sandboxSessionIdsHolding(ids)").length - 1, 2);
+ assert.equal(APP_SIDEBAR.split("sandboxSessionIdsHolding(ids)").length - 1, 1);
+ assert.equal(OPEN_CHAT_FOLDER.split("sandboxSessionIdsHolding(ids)").length - 1, 1);
});
// Loading a model that drops the level in force leaves the effort set to one
diff --git a/studio/frontend/tests/sidebar-custom-sections.test.ts b/studio/frontend/tests/sidebar-custom-sections.test.ts
index 3e6ff11c6f1..9fbe5564c95 100644
--- a/studio/frontend/tests/sidebar-custom-sections.test.ts
+++ b/studio/frontend/tests/sidebar-custom-sections.test.ts
@@ -117,6 +117,35 @@ test("rows file into a section, move between sections, and come back out", () =>
assert.equal(useSidebarOrganizationStore.getState().sectionByChatId.c3, undefined);
});
+test("a section records when it was made, and renames and filings stamp it", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ const a = store.createCustomSection("A")!;
+ const b = store.createCustomSection("B")!;
+ const stamp = (id: string, at: number) =>
+ useSidebarOrganizationStore.setState((state) => ({
+ customSections: state.customSections.map((section) =>
+ section.id === id ? { ...section, modifiedAt: at } : section,
+ ),
+ }));
+ const section = (id: string) =>
+ useSidebarOrganizationStore.getState().customSections.find((entry) => entry.id === id)!;
+ assert.ok(section(a).createdAt && section(a).modifiedAt);
+ stamp(a, 1);
+ stamp(b, 1);
+ store.renameCustomSection(a, "A");
+ store.setChatsSection(["c1"], a);
+ assert.ok(section(a).modifiedAt! > 1);
+ stamp(a, 1);
+ store.setChatsSection(["c1"], a);
+ assert.equal(section(a).modifiedAt, 1);
+ store.setChatsSection(["c1"], b);
+ assert.ok(section(a).modifiedAt! > 1 && section(b).modifiedAt! > 1);
+ stamp(a, 1);
+ store.setProjectsSection(["p1"], a);
+ assert.ok(section(a).modifiedAt! > 1);
+});
+
test("deleting a section returns its rows and forgets its order and visibility", () => {
resetStore();
const store = useSidebarOrganizationStore.getState();
@@ -690,7 +719,7 @@ test("the sidebar and account menus share one flat surface and type; other menus
);
assert.match(css, /\.app-user-menu\.sidebar-menu :is\([\s\S]*?\) \{\n\s*@apply text-ui-14;\n\s*font-weight: 400;/);
// Every sidebar menu is marked, the account menu and its Help submenu included.
- assert.equal((APP_SIDEBAR.match(/"unsloth-plus-menu sidebar-row-menu sidebar-menu/g) ?? []).length, 13);
+ assert.equal((APP_SIDEBAR.match(/"unsloth-plus-menu sidebar-row-menu sidebar-menu/g) ?? []).length, 12);
assert.match(APP_SIDEBAR, /className="app-user-menu sidebar-menu menu-soft-surface-up/);
});
@@ -771,7 +800,7 @@ test("sidebar and account submenus open clear of their menu, first rows level",
/sideOffset: Math\.round\(SIDEBAR_MENU_PAD_X \* uiSpaceScale \+ SUBMENU_GAP_PX\),\n\s*alignOffset: -Math\.round\(SIDEBAR_MENU_PAD_Y \* uiSpaceScale \+ MENU_ROW_MARGIN_PX\),/,
);
assert.match(APP_SIDEBAR, /sideOffset: ACCOUNT_MENU_PAD_X \+ SUBMENU_GAP_PX,/);
- assert.equal((APP_SIDEBAR.match(/\{\.\.\.sidebarSubmenuOffsets\}/g) ?? []).length, 5);
+ assert.equal((APP_SIDEBAR.match(/\{\.\.\.sidebarSubmenuOffsets\}/g) ?? []).length, 4);
assert.equal((APP_SIDEBAR.match(/\{\.\.\.accountSubmenuOffsets\}/g) ?? []).length, 1);
// No sidebar submenu keeps a hand-set offset that would overlap its menu.
assert.doesNotMatch(APP_SIDEBAR, /SubContent[^>]*sideOffset=\{[0-9]+\}[^>]*sidebar-menu/);
@@ -788,9 +817,9 @@ test("sidebar and account menus read white on a lighter surface in dark mode", a
});
-test("undoing a removed section puts it back where it was drawn", () => {
- const start = APP_SIDEBAR.indexOf("function removeCustomSection(");
- const body = APP_SIDEBAR.slice(start, APP_SIDEBAR.indexOf("function renderSortSubmenu", start));
+test("undoing a removed section puts it back where it was drawn", async () => {
+ assert.match(APP_SIDEBAR, /const undo = removeCustomSectionWithUndo\(section\);/);
+ const body = await readSrcAsync("features/chat/stores/remove-custom-section.ts");
assert.match(body, /const followers = drawnOrder\.slice\(drawnOrder\.indexOf\(section\.id\) \+ 1\);/);
assert.match(body, /const follower = followers\.find\(\(key\) => sectionOrder\.includes\(key\)\);/);
assert.match(body, /customSections: inSectionOrder\(restored, sectionOrder\),\n\s*sectionOrder,/);
diff --git a/studio/frontend/tests/sidebar-items-group.test.ts b/studio/frontend/tests/sidebar-items-group.test.ts
new file mode 100644
index 00000000000..f287eaf776d
--- /dev/null
+++ b/studio/frontend/tests/sidebar-items-group.test.ts
@@ -0,0 +1,30 @@
+// 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 Library reads models and last-modified times off the sidebar rows, not a second thread read.
+
+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 { groupThreads } = await import("../src/features/chat/hooks/use-chat-sidebar-items.ts");
+
+const base = { title: "T", modelType: "base", archived: false, createdAt: 1 } as const;
+
+test("a compare row carries each pane's model once and its latest edit", () => {
+ const [row] = groupThreads([
+ { ...base, id: "a", pairId: "pair", modelId: "m1", modifiedAt: 5 },
+ { ...base, id: "b", pairId: "pair", modelId: "m2", modifiedAt: 9 },
+ { ...base, id: "c", pairId: "pair", modelId: "m1" },
+ ]);
+ assert.deepEqual(row?.modelIds, ["m1", "m2"]);
+ assert.equal(row?.modifiedAt, 9);
+});
+
+test("a never edited chat has no modified time", () => {
+ const [row] = groupThreads([{ ...base, id: "a", modelId: "m1", modifiedAt: null }]);
+ assert.deepEqual(row?.modelIds, ["m1"]);
+ assert.equal("modifiedAt" in (row ?? {}), false);
+});
diff --git a/studio/frontend/tests/sidebar-row-actions.test.ts b/studio/frontend/tests/sidebar-row-actions.test.ts
index 17e44245915..83f3746d12e 100644
--- a/studio/frontend/tests/sidebar-row-actions.test.ts
+++ b/studio/frontend/tests/sidebar-row-actions.test.ts
@@ -10,6 +10,7 @@ import test from "node:test";
import vm from "node:vm";
import ts from "typescript";
import * as liveThreadHead from "../src/features/chat/utils/live-thread-head.ts";
+import { en } from "../src/i18n/locales/en.ts";
import { readSrcAsync } from "./helpers/kit.ts";
const APP_SIDEBAR = await readSrcAsync("components/app-sidebar.tsx");
@@ -110,14 +111,38 @@ test("double-clicking a chat title renames it in place", () => {
);
});
-// A single chat's menu carries no read or unread item; the bulk menu keeps it.
-test("a chat row menu does not offer mark as read or unread", () => {
- const start = APP_SIDEBAR.indexOf("function renderChatRowMenuItems(");
- assert.notEqual(start, -1);
- const rowMenu = APP_SIDEBAR.slice(start, APP_SIDEBAR.indexOf("\n }\n", start));
- assert.ok(!rowMenu.includes("markThreadsUnread"));
- assert.ok(!rowMenu.includes("shell.selection.markUnread"));
- assert.ok(!rowMenu.includes("shell.selection.markRead"));
+// Regression: per-row Mark as unread/read, and the dot must be removable.
+test("a chat row marks itself read or unread from its own menu", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /onSelect=\{\(\) =>\n\s*alreadyUnread\n\s*\? clearThreadsUnread\(threadIds\)\n\s*: markThreadsUnread\(threadIds, rowIdByThreadId\)\n\s*\}/,
+ );
+ assert.ok(
+ !APP_SIDEBAR.includes("disabled={alreadyUnread}"),
+ "the item is still disabled on a row that carries the dot",
+ );
+ // The same strings the bulk menu uses, so the two cannot drift apart.
+ for (const key of ["markUnread", "markRead"]) {
+ assert.equal(
+ (APP_SIDEBAR.match(new RegExp(`t\\("shell\\.selection\\.${key}"\\)`, "g")) ?? [])
+ .length,
+ 2,
+ `the row and bulk menus no longer say the same thing for ${key}`,
+ );
+ }
+ assert.match(
+ APP_SIDEBAR,
+ /const alreadyUnread = threadIds\.some\(\(threadId\) =>\n\s*unreadThreadIds\.has\(threadId\),\n\s*\);/,
+ );
+ assert.equal(
+ (
+ APP_SIDEBAR.match(
+ /icon=\{(alreadyUnread|allSelectedUnread) \? ViewIcon : ViewOffSlashIcon\}/g,
+ ) ?? []
+ ).length,
+ 2,
+ "a read or unread item stopped naming the state it moves to",
+ );
});
// The bulk menu only ever added dots, so a selection of read rows had no way back.
@@ -189,21 +214,19 @@ test("a section's chevron appears on hovering anywhere in it", () => {
test("the chat-folder hint names what to click instead", async () => {
// The item is shared with the Projects page's chat rows, so the hint lives with it.
const item = await readSrcAsync("features/chat/components/open-chat-folder-item.tsx");
+ const hint = en.library.chats.folder.chatHint;
assert.ok(
- !item.includes("card that created it"),
+ !hint.includes("card that created it"),
"the hint still sends the user to a card it never identifies",
);
assert.ok(
- item.includes("download a file from the tool result that wrote it"),
+ hint.includes("download a file from the tool result that wrote it"),
"the hint no longer says where the files can be had",
);
- // Carried twice on purpose: the tooltip is for the pointer, the title for everything else.
- assert.equal(
- (item.match(/Only the desktop app can open a chat('|&apos;)s files folder/g) ??
- []).length,
- 2,
- "the hint is no longer stated for both the pointer and the screen reader",
- );
+ // One hint, used twice on purpose: tooltip for the pointer, title for everything else.
+ assert.match(item, /hintOverride \?\? t\("library\.chats\.folder\.chatHint"\)/);
+ assert.match(item, /title=\{hint\}/);
+ assert.match(item, /<TooltipContent[^>]*>\s*\{hint\}\s*<\/TooltipContent>/);
});
// Forking was reachable only from a message in the open thread, so copying a chat meant opening
@@ -212,12 +235,19 @@ test("a chat row forks from its own menu", async () => {
const ROW_MENU = await readSrcAsync(
"features/chat/components/chat-row-menu.ts",
);
- // Below Pin, and before the rule that sets off the rest.
assert.match(
APP_SIDEBAR,
- /<span>\{isPinned \? "Unpin" : "Pin"\}<\/span>\n\s*<\/P\.Item>\n\s*<P\.Item\n\s*disabled=\{!canForkChatRow\(item\)/,
+ /t\("shell\.selection\.markUnread"\)\}\n\s*<\/span>\n\s*<\/P\.Item>\n\s*\{\/\*[^]*?\*\/\}\n\s*<P\.Separator \/>\n\s*<P\.Item\n\s*disabled=\{!canForkChatRow\(item\)/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /<P\.Item\n\s*disabled=\{!canForkChatRow\(item\)[^]*?<span>Fork<\/span>\n\s*<\/P\.Item>\n\s*\{\/\* Projects and sections in one place[^]*?\*\/\}\n\s*<P\.Sub>/,
+ );
+ const rowMenu = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("function renderChatRowMenuItems("),
+ APP_SIDEBAR.indexOf("function renderChatSidebarItem("),
);
- assert.match(APP_SIDEBAR, /<span>Fork<\/span>\n\s*<\/P\.Item>\n\s*\{\/\*[^]*?\*\/\}\n\s*<P\.Separator \/>/);
+ assert.doesNotMatch(rowMenu, /<span>Export<\/span>|Export all chats/);
// A comparison has two threads and no single tip to fork from.
assert.match(ROW_MENU, /export function canForkChatRow[^]*?return item\.type === "single";/);
// The fork carries the settings on screen, not the ones the row was last written with.
diff --git a/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts b/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts
index daccefdc3e0..d5f73fb3839 100644
--- a/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts
+++ b/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts
@@ -351,8 +351,7 @@ test("the project page edits through the same dialog the sidebar opens", async (
const page = await readSrcAsync("features/chat/chat-page.tsx");
assert.ok(!page.includes("Rename project"), "the rename-only dialog is still there");
assert.ok(!page.includes("commitProjectRename"), "the rename call is still there");
- assert.match(page, /onSelect=\{\(\) => setEditingProject\(true\)\}/);
- assert.match(page, /<span>Edit project<\/span>/);
+ assert.match(page, /onEdit=\{\(\) => setEditingProject\(true\)\}/);
// The record behind the header, and the dialog it feeds.
assert.match(
page,
diff --git a/studio/frontend/tests/sidebar-selection-coverage.test.ts b/studio/frontend/tests/sidebar-selection-coverage.test.ts
index 45a2bb4df06..7b117a199ab 100644
--- a/studio/frontend/tests/sidebar-selection-coverage.test.ts
+++ b/studio/frontend/tests/sidebar-selection-coverage.test.ts
@@ -223,8 +223,7 @@ test("the shared menu items are written against the injected family", () => {
);
assert.match(body, /<P\.Item/);
}
- // The helper these bodies call takes the family too, rather than hardcoding the dropdown.
- assert.match(APP_SIDEBAR, /<OpenChatFolderUnavailableItem Item=\{P\.Item\} \/>/);
+ assert.doesNotMatch(APP_SIDEBAR, /OpenChatFolder/);
});
diff --git a/tests/studio/playwright_data_settings.py b/tests/studio/playwright_data_settings.py
index ee7005fb15d..1628326b6cb 100644
--- a/tests/studio/playwright_data_settings.py
+++ b/tests/studio/playwright_data_settings.py
@@ -287,7 +287,6 @@ def run(page):
for source, target in itertools.product(
[
- "Manage chats",
"Uploaded files",
"Archived chats",
"Archived images",
@@ -345,7 +344,6 @@ def run(page):
checks.extend(run_libraries(page))
checks.extend(run_library_locales(page))
- checks.extend(run_library_selection(page))
checks.extend(run_library_collation(page))
checks.extend(run_restore_notifications(page))
checks.extend(run_thumbnail_retention(page))
@@ -389,22 +387,13 @@ def run_libraries(page):
if (options.reorderDates) {
for (const kind of ['images', 'videos', 'audio']) f.media[kind][300].created_at = kind === 'images' ? 1900000000 : new Date(1900000000000).toISOString();
}
- if (shelf === 'manage') window.__settingsSmoke.open('data');
- else window.__settingsSmoke.openArchived(shelf);
+ window.__settingsSmoke.openArchived(shelf);
}""",
{"shelf": shelf, "options": options},
)
- if shelf == "manage":
- page.locator('[data-settings-label="Manage chats"]').get_by_role(
- "button", name = "Manage", exact = True
- ).click()
- label = "Search chats or projects"
- else:
- label = (
- "Search archived chats or projects"
- if shelf == "chats"
- else f"Search archived {shelf}"
- )
+ label = (
+ "Search archived chats or projects" if shelf == "chats" else f"Search archived {shelf}"
+ )
search = page.get_by_role("searchbox", name = label, exact = True)
search.wait_for()
page.evaluate("window.dispatchEvent(new Event('unsloth-chat-projects-updated'))")
@@ -419,21 +408,14 @@ def run_libraries(page):
"window.__dataFixture.requests.filter(r => ['PATCH', 'DELETE'].includes(r.method))"
)
- for shelf in ["manage", "chats"]:
+ for shelf in ["chats"]:
search = seed(shelf)
search.fill(" RESEARCH cafe ")
expect(page.get_by_role("button", name = "Café needle", exact = True)).to_be_visible()
expect(page.get_by_role("button", name = "Zulu sample", exact = True)).to_have_count(0)
checks.append(f"{shelf}-search-title-and-project-across-pages-unicode")
search.fill("missing query")
- expect(
- page.get_by_text(
- "No chats match your search."
- if shelf == "manage"
- else "No archived chats match your search.",
- exact = True,
- )
- ).to_be_visible()
+ expect(page.get_by_text("No archived chats match your search.", exact = True)).to_be_visible()
search.fill("")
page.get_by_role("button", name = "Filter by project", exact = True).click()
page.get_by_role("combobox", name = "Search projects", exact = True).fill("Research")
@@ -467,24 +449,6 @@ def run_libraries(page):
expect(page.get_by_role("button", name = "Chat 31", exact = True)).to_be_visible()
checks.append("archive-search-includes-archived-project-names")
- search = seed("manage")
- page.get_by_role("checkbox", name = "Select all visible chats", exact = True).click()
- expect(page.get_by_text("Selected chats: 20", exact = True)).to_be_visible()
- search.fill("needle")
- expect(
- page.get_by_role("checkbox", name = 'Select "Café needle"', exact = True)
- ).not_to_be_checked()
- expect(page.get_by_role("button", name = "Archive", exact = True)).to_have_count(0)
- assert not mutation_requests()
- checks.append("manage-filter-clears-hidden-selection")
- page.get_by_role("checkbox", name = 'Select "Café needle"', exact = True).click()
- page.get_by_role("button", name = "Archive", exact = True).click()
- page.wait_for_function(
- "window.__dataFixture.rows.find(r => r.title === 'Café needle').archived === true"
- )
- assert len(mutation_requests()) == 1
- checks.append("manage-filtered-archive-scope")
-
search = seed("chats", holdMutation = True)
search.fill("Compare models")
page.get_by_role("button", name = "Delete results", exact = True).click()
@@ -680,8 +644,6 @@ def run_library_locales(page):
}
return {
...api.messages[locale].settings.data.library,
- manage: api.translate('settings.data.manageChats'),
- manageAction: api.translate('settings.data.manageAction'),
cancel: api.translate('common.cancel'),
delete: api.translate('common.delete'),
deleteAll: api.translate('settings.data.deleteAllAction'),
@@ -694,7 +656,7 @@ def run_library_locales(page):
)
if locale == "es":
assert text["noProject"] == "Sin proyecto"
- for shelf in ["manage", "chats", "images", "videos", "audio"]:
+ for shelf in ["chats", "images", "videos", "audio"]:
page.evaluate("window.__settingsSmoke.close()")
expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
page.evaluate(
@@ -711,18 +673,12 @@ def run_library_locales(page):
id: 'locale-media', prompt: 'Sample media', url: '/unused',
created_at: kind === 'images' ? 1700000000 : '2023-11-14T22:13:20Z',
}]]));
- if (shelf === 'manage') window.__settingsSmoke.open('data');
- else window.__settingsSmoke.openArchived(shelf);
+ window.__settingsSmoke.openArchived(shelf);
}""",
shelf,
)
- if shelf == "manage":
- page.locator(f'[data-settings-label="{text["manage"]}"]').get_by_role(
- "button", name = text["manageAction"], exact = True
- ).click()
placeholder = text[
{
- "manage": "searchChats",
"chats": "searchArchivedChats",
"images": "searchImages",
"videos": "searchVideos",
@@ -736,12 +692,12 @@ def run_library_locales(page):
expect(
page.get_by_role("menuitemradio", name = text["alphabetical"], exact = True)
).to_be_visible()
- if shelf in ["manage", "chats"]:
+ if shelf == "chats":
expect(
page.get_by_role("menuitemradio", name = text["singleChats"], exact = True)
).to_be_visible()
page.keyboard.press("Escape")
- if shelf in ["manage", "chats"]:
+ if shelf == "chats":
expect(page.get_by_role("button", name = "Sample 0", exact = True)).to_be_visible()
search.fill(text["noProject"])
expect(page.get_by_role("button", name = "Sample 0", exact = True)).to_be_visible()
@@ -758,20 +714,10 @@ def run_library_locales(page):
page.get_by_role("heading", name = text["noProject"], exact = True)
).to_be_visible()
expect(page.get_by_role("button", name = "Sample 1", exact = True)).to_have_count(0)
- if shelf == "manage":
- page.get_by_role("checkbox", name = text["selectAll"], exact = True).click()
- expect(
- page.get_by_role("button", name = text["archive"], exact = True)
- ).to_be_visible()
- page.get_by_role("button", name = text["delete"], exact = True).click()
- expect(page.get_by_role("alertdialog")).to_contain_text(
- text["deleteChatsWarning"].replace("{count}", "1")
- )
- else:
- page.get_by_role("button", name = text["deleteResults"], exact = True).click()
- expect(page.get_by_role("alertdialog")).to_contain_text(
- text["deleteArchivedWarning"].replace("{count}", "1")
- )
+ page.get_by_role("button", name = text["deleteResults"], exact = True).click()
+ expect(page.get_by_role("alertdialog")).to_contain_text(
+ text["deleteArchivedWarning"].replace("{count}", "1")
+ )
else:
row = page.locator("[data-archived-id]")
expect(row).to_contain_text("Sample media")
@@ -799,13 +745,7 @@ def run_library_locales(page):
"window.__dataFixture.requests.some(r => r.method === 'DELETE' || r.method === 'PATCH')"
)
search.fill("NoMatchingTitle")
- empty_key = (
- "noChats"
- if shelf == "manage"
- else "noArchivedMatches"
- if shelf == "chats"
- else "noMediaMatches"
- )
+ empty_key = "noArchivedMatches" if shelf == "chats" else "noMediaMatches"
expect(page.get_by_text(text[empty_key], exact = True)).to_be_visible()
if locale == "es" and shelf == "chats":
search_to(page, text["archived"])
@@ -823,78 +763,10 @@ def run_library_locales(page):
return checks
-def run_library_selection(page):
- page.evaluate("window.__settingsSmoke.close()")
- expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
- page.evaluate("""() => {
- const f = window.__dataFixture;
- Object.assign(f, {requests: [], failMutation: false, holdMutation: false, listFail: false});
- f.rows = Array.from({length: 32}, (_, i) => ({
- id: `selection-${i}`, title: `Chat ${i}`, modelType: 'base', modelId: 'test',
- createdAt: 1700000000000, updatedAt: 1700000000000 + (32-i)*1000,
- }));
- window.__settingsSmoke.open('data');
- }""")
- page.locator('[data-settings-label="Manage chats"]').get_by_role(
- "button", name = "Manage", exact = True
- ).click()
- target = page.get_by_role("checkbox", name = 'Select "Chat 19"', exact = True)
- target.click()
- expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
- page.evaluate("""() => {
- window.__dataFixture.rows[20].updatedAt = 1900000000000;
- window.dispatchEvent(new Event('unsloth-chat-history-updated'));
- }""")
- expect(target).to_have_count(0)
- expect(page.get_by_role("button", name = "Chat 20", exact = True)).to_be_visible()
- expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
- checks = ["selected-chat-survives-live-page-reorder"]
- select_all = page.get_by_role("checkbox", name = "Select all visible chats", exact = True)
- expect(select_all).not_to_be_checked()
- select_all.click()
- expect(page.get_by_text("Selected chats: 21", exact = True)).to_be_visible()
- select_all.click()
- expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
- checks.append("select-visible-preserves-hidden-selection")
- page.get_by_role("button", name = "Show more (12)", exact = True).click()
- expect(target).to_be_checked()
- checks.append("revealed-chat-keeps-its-selection")
- page.evaluate("""() => {
- const f = window.__dataFixture;
- f.rows.push(...Array.from({length: 40}, (_, i) => ({
- id: `incoming-${i}`, title: `Incoming ${i}`, modelType: 'base', modelId: 'test',
- createdAt: 1700000000000, updatedAt: 1900000000000 + i + 1,
- })));
- window.dispatchEvent(new Event('unsloth-chat-history-updated'));
- }""")
- expect(target).to_have_count(0)
- expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
- page.get_by_role("button", name = "Delete", exact = True).click()
- expect(page.get_by_role("alertdialog").get_by_role("heading")).to_have_text("Delete chats (1)")
- page.get_by_role("alertdialog").get_by_role("button", name = "Cancel", exact = True).click()
- page.get_by_role("button", name = "Archive", exact = True).click()
- page.wait_for_function(
- "window.__dataFixture.rows.find(r => r.id === 'selection-19').archived === true"
- )
- assert page.evaluate(
- "window.__dataFixture.requests.filter(r => r.method === 'PATCH').map(r => r.path)"
- ) == ["/api/chat/threads/selection-19"]
- checks.append("bulk-action-retains-original-selected-id")
- # Explicit filter changes still clear selections.
- page.get_by_role("checkbox", name = 'Select "Incoming 18"', exact = True).click()
- page.get_by_role("searchbox", name = "Search chats or projects", exact = True).fill("Incoming 18")
- expect(
- page.get_by_role("checkbox", name = 'Select "Incoming 18"', exact = True)
- ).not_to_be_checked()
- expect(page.get_by_role("button", name = "Archive", exact = True)).to_have_count(0)
- checks.append("explicit-filter-change-clears-selection")
- return checks
-
-
def run_library_collation(page):
checks = []
titles = ["阿", "八", "中", "张", "曾", "Zebra", "苹果", "橙子", "東京", "大阪"]
- for shelf in ["manage", "chats", "images", "videos", "audio"]:
+ for shelf in ["chats", "images", "videos", "audio"]:
page.evaluate("window.__settingsSmoke.close()")
expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
page.evaluate(
@@ -909,15 +781,10 @@ def run_library_collation(page):
id: `${kind}-${i}`, prompt, url: '/unused',
created_at: kind === 'images' ? 1700000000 : '2023-11-14T22:13:20Z',
}))]));
- if(shelf === 'manage') window.__settingsSmoke.open('data');
- else window.__settingsSmoke.openArchived(shelf);
+ window.__settingsSmoke.openArchived(shelf);
}""",
{"shelf": shelf, "titles": titles},
)
- if shelf == "manage":
- page.locator('[data-settings-label="Manage chats"]').get_by_role(
- "button", name = "Manage", exact = True
- ).click()
page.get_by_role("button", name = "Filter and sort", exact = True).click()
page.get_by_role("menuitemradio", name = "Alphabetical", exact = True).click()
for locale in ["en", "zh-CN", "ja"]:
@@ -930,13 +797,13 @@ def run_library_collation(page):
}""",
{"locale": locale, "titles": titles},
)
- if shelf in ["manage", "chats"]:
+ if shelf == "chats":
rows = page.locator("main section .divide-y button[title]:not([aria-label])")
else:
rows = page.locator("[data-archived-id] p[title]")
expect(rows).to_have_text(info["expected"])
checks.append(f"{shelf}-alphabetical-{locale}")
- if shelf in ["manage", "chats"]:
+ if shelf == "chats":
page.get_by_role("button", name = info["projectFilter"], exact = True).click()
assert page.get_by_role("option").all_text_contents()[2:] == info["expected"]
page.keyboard.press("Escape")