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: drag sidebar rows into place, and make a project row do more (#11373)

Michael Han35a4b312806d
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 69ceba73e92..82ad3503ea1 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -29,6 +29,7 @@ import {
} from "@/components/ui/context-menu";
import {
DropdownMenu,
+ DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
@@ -76,7 +77,6 @@ import { useWebUpdateCheck } from "@/hooks/use-web-update-check";
import {
Archive03Icon,
BadgeInfoIcon,
- BubbleChatIcon,
ChefHatIcon,
CloudIcon,
CpuIcon,
@@ -85,6 +85,7 @@ import {
AudioWave01Icon,
Delete02Icon,
Download01Icon,
+ DragDropVerticalIcon,
DownloadSquare01Icon,
Edit03Icon,
FolderAddIcon,
@@ -112,9 +113,14 @@ import {
Settings02Icon,
Sun03Icon,
UserCircleIcon,
+ ViewIcon,
+ ViewOffSlashIcon,
ZapIcon,
} from "@hugeicons/core-free-icons";
-import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
+import {
+ MessageCircleIcon,
+ TestTubeOutlineIcon,
+} from "@/lib/hugeicons-derived";
import {
Tooltip,
TooltipContent,
@@ -122,13 +128,7 @@ import {
} from "@/components/ui/tooltip";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import { HugeiconsIcon } from "@hugeicons/react";
-import {
- ArrowRightIcon,
- ChevronDown,
- ChevronDownIcon,
- ChevronUpIcon,
- Moon,
-} from "lucide-react";
+import { ArrowRightIcon, ChevronDown, ChevronUp, Moon } from "lucide-react";
import {
Link,
useNavigate,
@@ -160,11 +160,10 @@ import {
usePromptQueueUI,
useSidebarOrganizationStore,
applyManualOrder,
- dropEdgeFor,
showsInRecents,
moveIdBy,
+ placeIdAt,
projectOrderScope,
- reorderIds,
PINNED_ORDER_SCOPE,
PINNED_PROJECT_ORDER_SCOPE,
PROJECT_ORDER_SCOPE,
@@ -232,8 +231,20 @@ import {
useState,
type ReactNode,
} from "react";
+import { createPortal } from "react-dom";
import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
+import { useIsCoarsePointer } from "@/hooks/use-mobile";
+import {
+ folderRingKey,
+ sectionRingKey,
+ useSidebarDrag,
+ type SidebarDragItem,
+ type SidebarDropContext,
+ type SidebarDropEffects,
+ type SidebarDropPlan,
+ type SidebarSection,
+} from "@/features/chat";
import { ShutdownDialog } from "@/components/shutdown-dialog";
import { translate, useT, type TranslationKey } from "@/i18n";
@@ -307,6 +318,9 @@ const PROJECT_CHAT_LIMIT = 4;
const SIDEBAR_PROJECT_LIMIT = 5;
// The shared radio item ticks on the right; these read as settings, so tick first.
+// Check on the left, like the radio dot, so both kinds of item line up.
+const menuCheckItemClass =
+ "pl-9 pr-3 [&>[data-slot=dropdown-menu-checkbox-item-indicator]]:right-auto [&>[data-slot=dropdown-menu-checkbox-item-indicator]]:left-3";
const menuRadioItemClass =
"pl-9 pr-3 [&>[data-slot=dropdown-menu-radio-item-indicator]]:right-auto [&>[data-slot=dropdown-menu-radio-item-indicator]]:left-3";
@@ -317,11 +331,45 @@ const SELECT_WITH_META =
typeof navigator !== "undefined" &&
/mac/i.test(navigator.platform || navigator.userAgent);
-// Insertion cue on the edge the row will land on, inset to the pill.
+// Insertion line on the landing edge, drawn inside the row: a section's collapsible clips its
+// overflow, and the first and last rows are exactly where a row is dragged to.
const DROP_CUE_BASE =
- "before:absolute before:inset-x-2 before:h-0.5 before:rounded-full before:bg-primary/70 before:content-['']";
-const DROP_CUE_TOP = `${DROP_CUE_BASE} before:-top-px`;
-const DROP_CUE_BOTTOM = `${DROP_CUE_BASE} before:-bottom-px`;
+ "before:pointer-events-none before:absolute before:inset-x-2 before:z-10 before:h-0.5 before:rounded-full before:bg-primary before:content-['']";
+const DROP_CUE_TOP = `${DROP_CUE_BASE} before:top-0`;
+const DROP_CUE_BOTTOM = `${DROP_CUE_BASE} before:bottom-0`;
+// A row dropped onto a folder or section joins it, so the whole target is tinted and outlined.
+// Kept inside the box for the same clipping reason.
+const DROP_INTO_CUE =
+ "before:pointer-events-none before:absolute before:inset-x-1 before:inset-y-0 before:rounded-2xl before:bg-primary/8 before:ring-1 before:ring-inset before:ring-primary/70 before:content-['']";
+// The menu keeps a 1px gap between rows. A pointer resting on that gap would hit the section
+// instead, which answers with its last slot, so each row's box reaches over the gap below it.
+const DROP_ROW_HIT = "pb-px -mb-px";
+/** The order a landing writes once its move has gone through: the snapshot from the drop,
+ * unless that list was reordered meanwhile, in which case the chat takes its slot in the list
+ * as it stands now. `before` is that list's manual order when the drop began. */
+function landedOrder(
+ order: SidebarDropEffects["orders"][number],
+ before: string[] | undefined,
+): string[] {
+ const current = useSidebarOrganizationStore.getState().manualOrder[order.scope];
+ if (!order.place || !current || current === before) return order.ids;
+ return placeIdAt(current, order.place.id, order.place.targetId, order.place.edge);
+}
+
+// A closed section has no body to light, so its header takes the tint.
+const DROP_INTO_HEADER_CUE =
+ "rounded-full bg-primary/8 ring-1 ring-inset ring-primary/70";
+
+// The sort a list is on and its setter: a reorder switches a sorted list to Manual, or the
+// sort would undo the drop.
+type RowSort = {
+ value: SidebarChatSort;
+ set: (next: SidebarChatSort) => void;
+};
+// One row of the Pinned list, which holds folders and chats together.
+type PinnedRow =
+ | { kind: "project"; id: string; project: ProjectRecord }
+ | { kind: "chat"; id: string; item: SidebarItem };
// The kebab shows itself while its menu is open; the quick-action beside it was hover-only, so
// it slid in over the title. The row reserves room for both, so reveal both.
@@ -330,14 +378,29 @@ const REVEAL_WITH_OPEN_MENU_PROJECT_CHAT =
const REVEAL_WITH_OPEN_MENU_RECENT =
"group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-100 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pointer-events-auto";
-// Every list offers the same three orders.
+// Every list offers the same three orders. Each says what it actually does under its name: the
+// three read as synonyms otherwise, and Manual order in particular is a rule the user writes by
+// dragging rather than one the list applies.
const CHAT_SORT_OPTIONS: Array<{
value: SidebarChatSort;
key: TranslationKey;
+ hint: TranslationKey;
}> = [
- { value: "priority", key: "shell.organize.priority" },
- { value: "updated", key: "shell.organize.lastUpdated" },
- { value: "manual", key: "shell.organize.manualOrder" },
+ {
+ value: "priority",
+ key: "shell.organize.priority",
+ hint: "shell.organize.priorityHint",
+ },
+ {
+ value: "updated",
+ key: "shell.organize.lastUpdated",
+ hint: "shell.organize.lastUpdatedHint",
+ },
+ {
+ value: "manual",
+ key: "shell.organize.manualOrder",
+ hint: "shell.organize.manualOrderHint",
+ },
];
const ORGANIZE_OPTIONS: Array<{
value: SidebarOrganizeBy;
@@ -449,7 +512,7 @@ function OpenChatFolderUnavailableItem() {
return (
<DropdownMenuItem
aria-disabled={true}
- title="Opening the folder needs the desktop app. In a browser, save a file from the card that created it."
+ 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."
className="relative opacity-50"
onSelect={(event) => {
event.preventDefault();
@@ -472,8 +535,8 @@ function OpenChatFolderUnavailableItem() {
/>
</TooltipTrigger>
<TooltipContent side="right" className="max-w-[220px]">
- Opening the folder needs the desktop app. In a browser, save a file
- from the card that created it.
+ Only the desktop app can open a chat's files folder. In a browser,
+ download a file from the tool result that wrote it.
</TooltipContent>
</Tooltip>
</DropdownMenuItem>
@@ -1059,15 +1122,17 @@ export function AppSidebar() {
return map;
}, [allChatItems]);
const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);
+ // Whether the sidebar is set up to list folders at all, which is what the nav row answers to.
+ const projectsSectionConfigured =
+ organizeBy === "project" && projects.length > 0;
const projectsSectionRendered =
- !isStudioRoute &&
- !showTrainingRecents &&
- organizeBy === "project" &&
- projects.length > 0;
- // The icon rail hides the section in CSS without unmounting it, so the nav row only stands
- // down while the section is really on screen.
+ !isStudioRoute && !showTrainingRecents && projectsSectionConfigured;
+ // Deliberately not the rendered flag: Train and Recipes swap the section for their runs, and a
+ // row reappearing there reads as a setting turning itself back on. The icon rail is the one
+ // exception, since it hides the section in CSS without unmounting it and the row is then the
+ // only way to reach projects.
const projectsSectionShowing =
- projectsSectionRendered && (isMobile || sidebarState !== "collapsed");
+ projectsSectionConfigured && (isMobile || sidebarState !== "collapsed");
const chatSort = useSidebarOrganizationStore((s) => s.chatSort);
const pinnedSort = useSidebarOrganizationStore((s) => s.pinnedSort);
const manualOrder = useSidebarOrganizationStore((s) => s.manualOrder);
@@ -1117,8 +1182,9 @@ export function AppSidebar() {
list.sort((a, b) => b.updatedAt - a.updatedAt);
return map;
}, [allChatItems]);
- // Pinned folders, in pin order then manual order. They render in Pinned, so they carry its scope.
- const pinnedProjectRecords = useMemo(() => {
+ // Pinned folders in pin order, then the order they were dragged into while Pinned kept
+ // folders apart from its chats. Pinned is one list now; this only seeds it.
+ const pinnedProjectBase = useMemo(() => {
const byId = new Map(projects.map((p) => [p.id, p]));
const pinned = pinnedProjectIds
.map((id) => byId.get(id))
@@ -1330,10 +1396,32 @@ export function AppSidebar() {
() => sortedRecentChatItems.map((item) => item.id),
[sortedRecentChatItems],
);
- const pinnedRowIds = useMemo(
+ // Chats only, for shift-click ranges among them.
+ const pinnedChatRowIds = useMemo(
() => sortedPinnedChatItems.map((item) => item.id),
[sortedPinnedChatItems],
);
+ // Pinned is one list of folders and chats, in the order they were dropped into. Folders lead
+ // until a drop says otherwise; a chat sort other than Manual keeps the chats after them.
+ const pinnedRows = useMemo(() => {
+ const rows: PinnedRow[] = [];
+ if (organizeBy === "project") {
+ for (const project of pinnedProjectBase) {
+ rows.push({ kind: "project", id: project.id, project });
+ }
+ }
+ for (const item of sortedPinnedChatItems) {
+ rows.push({ kind: "chat", id: item.id, item });
+ }
+ return pinnedSort === "manual"
+ ? applyManualOrder(rows, manualOrder[PINNED_ORDER_SCOPE], (row) => row.id)
+ : rows;
+ }, [organizeBy, pinnedProjectBase, sortedPinnedChatItems, pinnedSort, manualOrder]);
+ const pinnedRowIds = useMemo(() => pinnedRows.map((row) => row.id), [pinnedRows]);
+ const pinnedProjectRecords = useMemo(
+ () => pinnedRows.flatMap((row) => (row.kind === "project" ? [row.project] : [])),
+ [pinnedRows],
+ );
// Whole lists, not the visible slices, so a drop cannot lose what a collapsed "Show more" is
// hiding, plus the project chats actually on screen: grouping by project keeps them out of Recents,
// so without those the chords cannot see them at all. All three chat groups leave the tree on
@@ -1374,28 +1462,28 @@ export function AppSidebar() {
sortedChatsByProjectId,
],
);
- const pinnedProjectChatItems = useMemo(
- () => folderChatItems(pinnedOpen, pinnedProjectRecords),
- [folderChatItems, pinnedOpen, pinnedProjectRecords],
- );
const sectionProjectChatItems = useMemo(
() => folderChatItems(projectsOpen, visibleProjectRecords),
[folderChatItems, projectsOpen, visibleProjectRecords],
);
// A collapsed section is not on screen either, so its rows are not walked or
// selected any more than a collapsed folder's are.
- const visiblePinnedItems = useMemo(
- () => (chatListsOnScreen && pinnedOpen ? sortedPinnedChatItems : []),
- [chatListsOnScreen, pinnedOpen, sortedPinnedChatItems],
- );
const visibleRecentItems = useMemo(
() => (chatListsOnScreen && chatOpen ? sortedRecentChatItems : []),
[chatListsOnScreen, chatOpen, sortedRecentChatItems],
);
- // Pinned draws its folders above its chats, so the section's rows read in that order.
+ // Pinned draws folders and chats in one order, so the section's chats read in that order,
+ // each open folder's chats right under its row.
const pinnedSectionChatItems = useMemo(
- () => [...pinnedProjectChatItems, ...visiblePinnedItems],
- [pinnedProjectChatItems, visiblePinnedItems],
+ () =>
+ chatListsOnScreen && pinnedOpen
+ ? pinnedRows.flatMap((row) =>
+ row.kind === "project"
+ ? folderChatItems(true, [row.project])
+ : [row.item],
+ )
+ : [],
+ [chatListsOnScreen, pinnedOpen, pinnedRows, folderChatItems],
);
// Every chat row on screen, in draw order: Pinned, then the Projects folders, then Recents.
// The arrays above already fold in each section's disclosure, each folder's, and the
@@ -1741,6 +1829,21 @@ export function AppSidebar() {
markThreadsUnread(threadIds, rowIdByThreadId);
}
+ // Every selected row already carries a dot, so the only move left is taking them off.
+ const allSelectedUnread =
+ selectionCount > 0 &&
+ selectedChatItems.every((item) =>
+ getSidebarItemThreadIds(item).some((threadId) =>
+ unreadThreadIds.has(threadId),
+ ),
+ );
+
+ function markSelectedRead() {
+ const threadIds = selectedChatItems.flatMap(getSidebarItemThreadIds);
+ clearSelection();
+ clearThreadsUnread(threadIds);
+ }
+
async function archiveSelected() {
const items = selectedChatItems;
clearSelection();
@@ -1792,99 +1895,264 @@ export function AppSidebar() {
})();
}
- // A row must know which list it is dragged within: the same chat can sit in
- // its project and in Recents, and each list keeps its own order.
- const [draggingRow, setDraggingRow] = useState<{
- id: string;
- scope: string;
- } | null>(null);
- const [dropTargetRowId, setDropTargetRowId] = useState<string | null>(null);
- const manualDragEnabled = chatSort === "manual";
- const pinnedDragEnabled = pinnedSort === "manual";
-
- function dropCueClass(
- scope: string | undefined,
- orderedIds: string[] | undefined,
- rowId: string,
- ): string | undefined {
- if (
- scope === undefined ||
- dropTargetRowId !== rowId ||
- draggingRow?.scope !== scope ||
- draggingRow.id === rowId
- ) {
- return undefined;
+ // Drag-and-drop. lib/sidebar-drag.ts plans each drop; the hook paints the plan and hands it
+ // back on drop. Each preference is a way the gesture can get in the way.
+ const dragHints = useSidebarOrganizationStore((s) => s.dragHints);
+ const reorderSwitchesSort = useSidebarOrganizationStore(
+ (s) => s.reorderSwitchesSort,
+ );
+ const dragOpensFolders = useSidebarOrganizationStore((s) => s.dragOpensFolders);
+ const setDragHints = useSidebarOrganizationStore((s) => s.setDragHints);
+ const setReorderSwitchesSort = useSidebarOrganizationStore(
+ (s) => s.setReorderSwitchesSort,
+ );
+ const setDragOpensFolders = useSidebarOrganizationStore(
+ (s) => s.setDragOpensFolders,
+ );
+ // Read at event time, so a plan sees the lists as drawn.
+ const dropContext = useCallback(
+ (): SidebarDropContext => ({
+ organizeBy,
+ chatSort,
+ pinnedSort,
+ pinnedChatIds: pinnedIdSet,
+ pinnedProjectIds: pinnedProjectIdSet,
+ orders: {
+ pinned: pinnedRowIds,
+ projects: projectRowIds,
+ recents: recentRowIds,
+ projectChats: (projectId) => projectChatRowIds.get(projectId) ?? [],
+ },
+ reorderSwitchesSort,
+ }),
+ [
+ organizeBy,
+ chatSort,
+ pinnedSort,
+ pinnedIdSet,
+ pinnedProjectIdSet,
+ pinnedRowIds,
+ projectRowIds,
+ recentRowIds,
+ projectChatRowIds,
+ reorderSwitchesSort,
+ ],
+ );
+ const dropHintRef = useRef<HTMLDivElement | null>(null);
+ // A chat's row stays on screen while its move is written, so it can be dropped again before
+ // the first move lands. Moves of one chat run one after another, and only the latest drop
+ // commits its slot and pin, so an earlier drop cannot land after, or on top of, a later one.
+ const chatMovesRef = useRef(
+ new Map<string, { generation: number; chain: Promise<unknown> }>(),
+ );
+ // A touch browser never fires dragstart, so its row menus keep Move up and Move down.
+ const coarsePointer = useIsCoarsePointer();
+ const dnd = useSidebarDrag({
+ context: dropContext,
+ springOpen: dragOpensFolders,
+ hintRef: dropHintRef,
+ // A closed folder or section the pointer rests on opens.
+ onSpringOpen: (zone) => {
+ if (zone.folderId) {
+ if (collapsedProjectIds.has(zone.folderId)) {
+ toggleProjectCollapsed(zone.folderId);
+ }
+ return;
+ }
+ if (zone.section === "pinned") setPinnedOpen(true);
+ else if (zone.section === "projects") setProjectsOpen(true);
+ else setChatOpen(true);
+ },
+ onDrop: (plan) => commitDrop(plan),
+ });
+ const draggingRow = dnd.drag;
+
+ /** Runs a plan. Pin toggles are guarded against a stale plan; a sorted list that would undo
+ * the drop switches to Manual and says so. */
+ function commitDrop(plan: SidebarDropPlan) {
+ const { effects } = plan;
+ if (effects.pinChat && !pinnedIdSet.has(effects.pinChat)) {
+ togglePinnedChat(effects.pinChat);
+ }
+ if (effects.unpinChat && !effects.moveChat && pinnedIdSet.has(effects.unpinChat)) {
+ togglePinnedChat(effects.unpinChat);
+ }
+ if (effects.pinProject && !pinnedProjectIdSet.has(effects.pinProject)) {
+ toggleProjectPin(effects.pinProject);
+ }
+ if (effects.unpinProject && pinnedProjectIdSet.has(effects.unpinProject)) {
+ toggleProjectPin(effects.unpinProject);
+ }
+ const applyOrders = (before?: Record<string, string[]>) => {
+ for (const order of effects.orders) {
+ setManualOrder(
+ order.scope,
+ before ? landedOrder(order, before[order.scope]) : order.ids,
+ );
+ }
+ if (effects.switchSort === "chats" && chatSort !== "manual") {
+ setChatSort("manual");
+ toast.info(t("shell.organize.switchedToManual"));
+ }
+ if (effects.switchSort === "pinned" && pinnedSort !== "manual") {
+ setPinnedSort("manual");
+ toast.info(t("shell.organize.switchedToManual"));
+ }
+ };
+ const move = effects.moveChat;
+ if (!move) {
+ applyOrders();
+ return;
}
- return dropEdgeFor(orderedIds ?? [], draggingRow.id, rowId) === "bottom"
- ? DROP_CUE_BOTTOM
- : DROP_CUE_TOP;
+ const item = allChatItems.find((candidate) => candidate.id === move.chatId);
+ if (!item) return;
+ // The move can fail. Its slot in the new list and the pin it sheds both wait for it, so a
+ // failed move leaves nothing behind in the list the chat never reached. A slow move can
+ // also be overtaken by a reorder of that list, so the slot is re-aimed once it lands.
+ const unpinAfter = effects.unpinChat;
+ const ordersBefore = useSidebarOrganizationStore.getState().manualOrder;
+ const moves = chatMovesRef.current;
+ const previous = moves.get(item.id);
+ const generation = (previous?.generation ?? 0) + 1;
+ const chain = (previous?.chain ?? Promise.resolve())
+ .then(() => moveChatToProject(item, move.projectId))
+ .then((moved) => {
+ if (!moved || moves.get(item.id)?.generation !== generation) return;
+ applyOrders(ordersBefore);
+ if (unpinAfter) usePinnedChatsStore.getState().unpin(unpinAfter);
+ });
+ moves.set(item.id, { generation, chain });
}
- /** Menu path to the same reorder dragging does. Touch browsers never fire dragstart and a keyboard
- * cannot drag, so a manually ordered list is unreorderable without this. */
- function renderMoveRowItems(
- scope: string,
+ /** The insertion line for a row, on the landing edge. */
+ function dropCueClass(scope: string, rowId: string): string | undefined {
+ const edge = dnd.lineEdge(scope, rowId);
+ if (!edge) return undefined;
+ return edge === "bottom" ? DROP_CUE_BOTTOM : DROP_CUE_TOP;
+ }
+
+ /** Moves a row one slot without a pointer, under the same sort rule as a drop. */
+ function reorderRowBy(
+ item: SidebarDragItem,
orderedIds: string[],
- rowId: string,
- // Passed in, not searched for: this runs for every row on every render.
- at: number,
+ sort: RowSort | undefined,
+ delta: number,
) {
- const move = (delta: number) => {
- const next = moveIdBy(orderedIds, rowId, delta);
- if (next !== orderedIds) setManualOrder(scope, next);
+ const next = moveIdBy(orderedIds, item.id, delta);
+ if (next === orderedIds) return;
+ const resorts = sort !== undefined && sort.value !== "manual";
+ if (resorts && !reorderSwitchesSort) return;
+ setManualOrder(item.scope, next);
+ if (resorts) {
+ sort.set("manual");
+ toast.info(t("shell.organize.switchedToManual"));
+ }
+ }
+
+ /** Makes a row draggable, plus alt + arrow to reorder it from the keyboard. */
+ function rowDragProps(config: {
+ item: SidebarDragItem;
+ orderedIds: string[];
+ sort?: RowSort;
+ }) {
+ const { item, orderedIds, sort } = config;
+ return {
+ ...dnd.dragHandleProps(item),
+ onKeyDown: (event: React.KeyboardEvent) => {
+ if (
+ !event.altKey ||
+ (event.key !== "ArrowUp" && event.key !== "ArrowDown")
+ ) {
+ return;
+ }
+ event.preventDefault();
+ reorderRowBy(item, orderedIds, sort, event.key === "ArrowDown" ? 1 : -1);
+ },
};
+ }
+
+ /** Move up and Move down in a row menu, for touch screens only: the browser starts no drag
+ * there, and a list would be stuck in its order. */
+ function renderMoveRowItems(
+ item: SidebarDragItem,
+ orderedIds: string[],
+ sort?: RowSort,
+ ) {
+ if (!coarsePointer) return null;
+ const at = orderedIds.indexOf(item.id);
return (
<>
- <DropdownMenuItem disabled={at <= 0} onSelect={() => move(-1)}>
- <ChevronUpIcon strokeWidth={1.75} className="size-icon" />
+ <DropdownMenuItem
+ disabled={at <= 0}
+ onSelect={() => reorderRowBy(item, orderedIds, sort, -1)}
+ >
+ <ChevronUp strokeWidth={1.75} className="size-icon" />
<span>{t("shell.organize.moveUp")}</span>
</DropdownMenuItem>
<DropdownMenuItem
disabled={at === -1 || at >= orderedIds.length - 1}
- onSelect={() => move(1)}
+ onSelect={() => reorderRowBy(item, orderedIds, sort, 1)}
>
- <ChevronDownIcon strokeWidth={1.75} className="size-icon" />
+ <ChevronDown strokeWidth={1.75} className="size-icon" />
<span>{t("shell.organize.moveDown")}</span>
</DropdownMenuItem>
</>
);
}
- function rowDragProps(scope: string, orderedIds: string[], rowId: string) {
- return {
- draggable: true,
- onDragStart: (event: React.DragEvent) => {
- // Firefox needs a payload to drag at all.
- event.dataTransfer.effectAllowed = "move";
- event.dataTransfer.setData("text/plain", rowId);
- setDraggingRow({ id: rowId, scope });
- },
- onDragEnd: () => {
- setDraggingRow(null);
- setDropTargetRowId(null);
- },
- onDragOver: (event: React.DragEvent) => {
- if (draggingRow?.scope !== scope) return;
- event.preventDefault();
- event.dataTransfer.dropEffect = "move";
- if (dropTargetRowId !== rowId) setDropTargetRowId(rowId);
- },
- onDragLeave: () => {
- setDropTargetRowId((prev) => (prev === rowId ? null : prev));
- },
- onDrop: (event: React.DragEvent) => {
- event.preventDefault();
- const dragged = draggingRow;
- setDraggingRow(null);
- setDropTargetRowId(null);
- // Cross-list drops are ignored: the row is not in this list's order.
- if (!dragged || dragged.scope !== scope) return;
- const next = reorderIds(orderedIds, dragged.id, rowId);
- if (next !== orderedIds) setManualOrder(scope, next);
- },
- };
+ /** The hint beside the cursor: what the drop would do. */
+ function dropHint(plan: SidebarDropPlan): {
+ icon: typeof PinIcon;
+ text: string;
+ } {
+ switch (plan.action.kind) {
+ case "pin":
+ return { icon: PinIcon, text: t("shell.drag.pin") };
+ case "unpin":
+ return { icon: PinOffIcon, text: t("shell.drag.unpin") };
+ case "reorder":
+ return { icon: DragDropVerticalIcon, text: t("shell.drag.reorder") };
+ case "move": {
+ const projectId = plan.action.projectId;
+ if (projectId === null) {
+ return { icon: Message01Icon, text: t("shell.drag.moveToRecents") };
+ }
+ const name = projects.find((project) => project.id === projectId)?.name ?? "";
+ return { icon: Folder01Icon, text: t("shell.drag.moveTo", { name }) };
+ }
+ }
}
+ /** The hint, in a portal so the sidebar cannot clip it. Positioned through the ref, hidden
+ * between answers rather than unmounted. No inline style: a re-render would write it back
+ * over the transform the pointer set. */
+ const dropHintPortal =
+ draggingRow && dragHints && typeof document !== "undefined"
+ ? createPortal(
+ <div
+ ref={dropHintRef}
+ data-testid="sidebar-drop-hint"
+ aria-hidden
+ className={cn(
+ "pointer-events-none fixed left-0 top-0 z-[100] flex items-center gap-1.5 rounded-full border border-border bg-popover px-2.5 py-1 text-ui-12 leading-ui-16 font-medium text-popover-foreground shadow-md transition-opacity duration-100",
+ dnd.plan ? "opacity-100" : "opacity-0",
+ )}
+ >
+ {dnd.plan && (
+ <>
+ <HugeiconsIcon
+ icon={dropHint(dnd.plan).icon}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0"
+ />
+ <span className="max-w-48 truncate">{dropHint(dnd.plan).text}</span>
+ </>
+ )}
+ </div>,
+ document.body,
+ )
+ : null;
+
useEffect(() => {
const activeVisibleThreadIdSet = new Set(
activeVisibleThreadIdKey ? activeVisibleThreadIdKey.split("\n") : [],
@@ -2549,17 +2817,23 @@ export function AppSidebar() {
}
}
- async function moveChatToProject(item: SidebarItem, projectId: string | null) {
- if (item.projectId === projectId) return;
+ /** Resolves false when the move failed. */
+ async function moveChatToProject(
+ item: SidebarItem,
+ projectId: string | null,
+ ): Promise<boolean> {
+ if (item.projectId === projectId) return true;
try {
await moveChatItemToProject(item, projectId);
if (activeThreadId === item.id) {
useChatRuntimeStore.getState().setActiveProjectId(projectId);
}
+ return true;
} catch (err) {
toast.error("Failed to move chat", {
description: err instanceof Error ? err.message : undefined,
});
+ return false;
}
}
@@ -2913,6 +3187,25 @@ export function AppSidebar() {
// The "..." every list header carries. Only chat lists regroup, so that half
// is opt-in; Pinned takes the sort half alone.
+ // The drag-and-drop preferences, as the Organize menus list them.
+ const DRAG_OPTIONS: Array<{
+ key: TranslationKey;
+ get: () => boolean;
+ set: (value: boolean) => void;
+ }> = [
+ { key: "shell.organize.dragHints", get: () => dragHints, set: setDragHints },
+ {
+ key: "shell.organize.reorderSwitchesSort",
+ get: () => reorderSwitchesSort,
+ set: setReorderSwitchesSort,
+ },
+ {
+ key: "shell.organize.dragOpensFolders",
+ get: () => dragOpensFolders,
+ set: setDragOpensFolders,
+ },
+ ];
+
function renderSidebarHeaderMenu(options: {
ariaLabel: string;
sortLabel: string;
@@ -2925,7 +3218,8 @@ export function AppSidebar() {
side="bottom"
align="end"
sideOffset={2}
- className="unsloth-plus-menu w-56"
+ // Wide enough for the drag-and-drop items to fit on one line.
+ className="unsloth-plus-menu w-64"
trigger={(triggerRef) => (
<button
ref={triggerRef}
@@ -2971,12 +3265,33 @@ export function AppSidebar() {
<DropdownMenuRadioItem
key={option.value}
value={option.value}
- className={menuRadioItemClass}
+ className={cn(menuRadioItemClass, "items-start py-1.5")}
>
- {t(option.key)}
+ <span className="flex flex-col gap-0.5">
+ <span>{t(option.key)}</span>
+ <span className="text-ui-12 leading-ui-16 text-muted-foreground">
+ {t(option.hint)}
+ </span>
+ </span>
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
+ {options.includeOrganize && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>{t("shell.organize.dragDrop")}</DropdownMenuLabel>
+ {DRAG_OPTIONS.map((option) => (
+ <DropdownMenuCheckboxItem
+ key={option.key}
+ checked={option.get()}
+ onCheckedChange={(checked) => option.set(checked === true)}
+ className={menuCheckItemClass}
+ >
+ {t(option.key)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </>
+ )}
</NonModalDropdownMenu>
);
}
@@ -3037,9 +3352,17 @@ export function AppSidebar() {
<HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
<span>{t("shell.selection.archiveChats")}</span>
</ContextMenuItem>
- <ContextMenuItem onSelect={() => markSelectedUnread()}>
- <HugeiconsIcon icon={BubbleChatIcon} strokeWidth={1.75} className="size-icon" />
- <span>{t("shell.selection.markUnread")}</span>
+ <ContextMenuItem
+ onSelect={() =>
+ allSelectedUnread ? markSelectedRead() : markSelectedUnread()
+ }
+ >
+ <HugeiconsIcon icon={allSelectedUnread ? ViewIcon : ViewOffSlashIcon} strokeWidth={1.75} className="size-icon" />
+ <span>
+ {allSelectedUnread
+ ? t("shell.selection.markRead")
+ : t("shell.selection.markUnread")}
+ </span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem variant="destructive" onSelect={() => deleteSelected()}>
@@ -3053,12 +3376,21 @@ export function AppSidebar() {
function renderChatSidebarItem(
item: SidebarItem,
variant: "project" | "recent",
- // Manual order only: the list this row drags within, its ids to reorder,
- // and this row's slot in them.
- drag?: { scope: string; orderedIds: string[]; index: number },
- // The list this row is rendered in, for shift-click ranges. Always passed;
- // `drag` only turns up when the list is manually ordered.
- list?: { scope: string; ids: string[] },
+ // The list this row is rendered in: its ids, for shift-click ranges and for the order a drag
+ // rewrites; the sort a drop switches to Manual; and, where the list is a folder's or Recents',
+ // the project a chat dragged in from elsewhere joins.
+ list: {
+ scope: string;
+ ids: string[];
+ /** The section the row is drawn in, and its folder when it is a folder's chat. */
+ section: SidebarSection;
+ folderId?: string;
+ /** The last row drawn in the folder's block, for a line landing below it. */
+ blockEnd?: { scope: string; id: string };
+ /** The list a drag reorders, when it is wider than `ids`: Pinned mixes in folders. */
+ orderIds?: string[];
+ sort?: RowSort;
+ },
) {
const threadIds = getSidebarItemThreadIds(item);
const isPinned = pinnedIdSet.has(item.id);
@@ -3081,16 +3413,17 @@ export function AppSidebar() {
// Active generation and queued work share the in-row spinner slot so they cannot drift.
const showQueuedActivity = hasQueuedActivity && !isGenerating;
const showWorkSpinner = isGenerating || showQueuedActivity;
+ const alreadyUnread = threadIds.some((threadId) =>
+ unreadThreadIds.has(threadId),
+ );
const hasUnreadActivity =
- !isGenerating &&
- !hasQueuedActivity &&
- threadIds.some((threadId) => unreadThreadIds.has(threadId));
- const hasSecondaryRowAction =
- variant === "project" || (variant === "recent" && isPinned);
- const itemClass =
+ !isGenerating && !hasQueuedActivity && alreadyUnread;
+ const itemClass = cn(
variant === "project"
? "group/project-chat-item relative"
- : "group/recent-item relative";
+ : "group/recent-item relative",
+ DROP_ROW_HIT,
+ );
const actionClass =
variant === "project"
? "sidebar-row-action sidebar-touch-reveal group-hover/project-chat-item:opacity-100 group-hover/project-chat-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
@@ -3101,35 +3434,24 @@ export function AppSidebar() {
variant === "project" ? "pl-[39px]" : "pl-3",
// Pinned chats carry a chat icon, so add the nav-item icon gap.
isPinned && variant !== "project" && "gap-[8.5px]",
- showWorkSpinner
- ? hasSecondaryRowAction
- ? "pr-16"
- : undefined
- : hasUnreadActivity
- ? "pr-7"
- : undefined,
+ // A spinner glyph cannot truncate, and the pin and the kebab overlay that same edge, so a
+ // working row holds their room open whether or not it is hovered.
+ showWorkSpinner ? "pr-16" : hasUnreadActivity ? "pr-7" : undefined,
variant === "project"
? showWorkSpinner
? undefined
: // Room for the pin quick-action plus the kebab, and the same room with the menu open:
// a narrower gutter there let the title run under them.
"group-hover/project-chat-item:pr-14 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:pr-14 [@media(pointer:coarse)]:pr-14"
- : isPinned
- ? showWorkSpinner
- ? undefined
- : // Pinned rows add an unpin button, so reserve the room on hover and while open.
- "group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-16 [@media(pointer:coarse)]:pr-16"
- : showWorkSpinner
- ? // A spinner glyph cannot truncate, so clear the kebab's 30px inset (pr-1.5 + size-6).
- "group-hover/recent-item:pr-8 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-10"
- : // Clear the full menu circle only while it is visible.
- "group-hover/recent-item:pr-8 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-10",
+ : showWorkSpinner
+ ? undefined
+ : // A chat row carries a pin and a kebab, so reserve the room for both on hover and
+ // while the menu is open.
+ "group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-16 [@media(pointer:coarse)]:pr-16",
// Keyboard focus reveals the action without hover.
variant === "project"
? "group-has-[.sidebar-row-action:focus-visible]/project-chat-item:pr-14"
- : isPinned
- ? "group-has-[.sidebar-row-action:focus-visible]/recent-item:pr-16"
- : "group-has-[.sidebar-row-action:focus-visible]/recent-item:pr-8",
+ : "group-has-[.sidebar-row-action:focus-visible]/recent-item:pr-16",
);
const isRenamingThis =
@@ -3169,12 +3491,30 @@ export function AppSidebar() {
className={cn(
itemClass,
draggingRow?.id === item.id && "opacity-50",
- dropCueClass(drag?.scope, drag?.orderedIds, item.id),
+ dropCueClass(list.scope, item.id),
)}
onContextMenu={() => list && selectForContextMenu(item, list)}
- {...(drag
- ? rowDragProps(drag.scope, drag.orderedIds, item.id)
- : undefined)}
+ {...rowDragProps({
+ item: {
+ kind: "chat",
+ id: item.id,
+ section: list.section,
+ scope: list.scope,
+ projectId: item.projectId ?? null,
+ },
+ orderedIds: list.orderIds ?? list.ids,
+ sort: list.sort,
+ })}
+ {...dnd.dropZoneProps({
+ section: list.section,
+ row: { id: item.id, kind: "chat", scope: list.scope },
+ folderId: list.folderId,
+ blockEnd: list.blockEnd,
+ // A folder's chats are its block; a folder dragged over them lands against it.
+ block: list.folderId
+ ? { index: list.ids.indexOf(item.id), count: list.ids.length }
+ : undefined,
+ })}
>
<SidebarMenuButton
data-testid="recent-thread"
@@ -3189,9 +3529,16 @@ export function AppSidebar() {
if (list && handleSelectionClick(event, item, list)) return;
openChatItem(item);
}}
+ // The chat opens on the first click and the pill opens on the second, which is
+ // what double-clicking a title does everywhere else it renames one.
+ onDoubleClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openRenameChat(item, true, list?.scope);
+ }}
>
{isPinned && variant !== "project" && (
- <HugeiconsIcon icon={BubbleChatIcon} strokeWidth={1.75} className="size-icon! shrink-0" />
+ <HugeiconsIcon icon={MessageCircleIcon} strokeWidth={1.75} className="size-icon! shrink-0" />
)}
<span className="truncate">
{pendingRename?.id === item.id ? pendingRename.title : item.title}
@@ -3241,21 +3588,23 @@ export function AppSidebar() {
</span>
</button>
)}
- {variant === "recent" && isPinned && (
+ {/* Pinning is a one-click action on every chat row, not one the pinned rows alone
+ offer: finding it in the menu is the slow way to do the sidebar's commonest edit. */}
+ {variant === "recent" && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
togglePinnedChat(item.id);
}}
- aria-label="Unpin chat"
+ aria-label={isPinned ? "Unpin chat" : "Pin chat"}
className={cn(
"sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",
REVEAL_WITH_OPEN_MENU_RECENT,
)}
>
<span className="sidebar-row-action-glyph">
- <HugeiconsIcon icon={PinOffIcon} strokeWidth={1.75} className="size-icon" />
+ <HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
</span>
</button>
)}
@@ -3286,15 +3635,34 @@ export function AppSidebar() {
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => togglePinnedChat(item.id)}>
<HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
- <span>{isPinned ? "Unpin chat" : "Pin chat"}</span>
+ <span>{isPinned ? "Unpin" : "Pin"}</span>
+ </DropdownMenuItem>
+ {renderMoveRowItems(
+ {
+ kind: "chat",
+ id: item.id,
+ section: list.section,
+ scope: list.scope,
+ projectId: item.projectId ?? null,
+ },
+ list.orderIds ?? list.ids,
+ list.sort,
+ )}
+ {/* The dot a finished reply leaves, put back or taken off by hand. */}
+ <DropdownMenuItem
+ 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>
</DropdownMenuItem>
- {drag &&
- renderMoveRowItems(
- drag.scope,
- drag.orderedIds,
- item.id,
- drag.index,
- )}
{sandboxSessionId ? (
isTauri ? (
<DropdownMenuItem
@@ -3467,8 +3835,15 @@ export function AppSidebar() {
* unpinned folder, Pinned for a pinned one, so neither renumbers the other. */
function renderProjectFolderRow(
project: ProjectRecord,
- index: number,
- order: { scope: string; orderedIds: string[] },
+ order: {
+ scope: string;
+ orderedIds: string[];
+ section: SidebarSection;
+ /** The folders alone, for shift-click ranges, where the list holds chats too. */
+ selectionIds?: string[];
+ /** The list's sort, where a reorder has to switch it to Manual. */
+ sort?: RowSort;
+ },
) {
const projectChats =
sortedChatsByProjectId.get(project.id) ?? [];
@@ -3483,28 +3858,50 @@ export function AppSidebar() {
const isProjectPinned = pinnedProjectIdSet.has(
project.id,
);
+ // Where a line landing below this folder's block is drawn: its last row on screen.
+ const blockEnd =
+ expanded && visibleChats.length > 0
+ ? {
+ scope: projectOrderScope(project.id),
+ id: visibleChats[visibleChats.length - 1].id,
+ }
+ : { scope: order.scope, id: project.id };
return (
<Fragment key={project.id}>
- {/* Folders drag to reorder whatever the chat sort is. */}
+ {/* Folders drag to reorder whatever the chat sort is, and take a chat dragged onto them. */}
<ContextMenu>
<ContextMenuTrigger asChild>
<SidebarMenuItem
className={cn(
"group/recent-item relative",
+ DROP_ROW_HIT,
draggingRow?.id === project.id && "opacity-50",
- dropCueClass(
- order.scope,
- order.orderedIds,
- project.id,
- ),
+ dropCueClass(order.scope, project.id),
+ // Lit while a chat is over the folder row or any of the chats inside it.
+ dnd.ringLit(folderRingKey(project.id)) && DROP_INTO_CUE,
)}
onContextMenu={() =>
selectProjectForContextMenu(project.id)
}
- {...rowDragProps(
- order.scope,
- order.orderedIds,
- project.id,
+ {...rowDragProps({
+ item: {
+ kind: "project",
+ id: project.id,
+ section: order.section,
+ scope: order.scope,
+ projectId: null,
+ },
+ orderedIds: order.orderedIds,
+ sort: order.sort,
+ })}
+ {...dnd.dropZoneProps(
+ {
+ section: order.section,
+ row: { id: project.id, kind: "project", scope: order.scope },
+ folderId: project.id,
+ blockEnd,
+ },
+ { closed: !expanded },
)}
>
<SidebarMenuButton
@@ -3517,7 +3914,11 @@ export function AppSidebar() {
}
onClick={(event) => {
if (
- handleProjectSelectionClick(event, project.id, order.orderedIds)
+ handleProjectSelectionClick(
+ event,
+ project.id,
+ order.selectionIds ?? order.orderedIds,
+ )
)
return;
clearSelection();
@@ -3578,7 +3979,7 @@ export function AppSidebar() {
{/* No "New chat" here: the row's own pencil does it. */}
<DropdownMenuItem onSelect={() => toggleProjectPin(project.id)}>
<HugeiconsIcon icon={isProjectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
- <span>{isProjectPinned ? "Unpin project" : "Pin project"}</span>
+ <span>{isProjectPinned ? "Unpin" : "Pin"}</span>
</DropdownMenuItem>
{/* Name, instructions and folders are one dialog, so Edit rather than Rename. */}
<DropdownMenuItem onSelect={() => setEditingProject(project)}>
@@ -3586,10 +3987,15 @@ export function AppSidebar() {
<span>Edit</span>
</DropdownMenuItem>
{renderMoveRowItems(
- order.scope,
+ {
+ kind: "project",
+ id: project.id,
+ section: order.section,
+ scope: order.scope,
+ projectId: null,
+ },
order.orderedIds,
- project.id,
- index,
+ order.sort,
)}
<DropdownMenuSeparator />
<DropdownMenuItem
@@ -3608,26 +4014,22 @@ export function AppSidebar() {
{renderProjectContextMenu()}
</ContextMenu>
{expanded &&
- visibleChats.map((chat, index) =>
- renderChatSidebarItem(
- chat,
- "project",
- manualDragEnabled
- ? {
- scope: projectOrderScope(project.id),
- orderedIds: projectChatIds,
- index,
- }
- : undefined,
- {
- scope: projectOrderScope(project.id),
- ids: projectChatIds,
- },
- ),
+ visibleChats.map((chat) =>
+ renderChatSidebarItem(chat, "project", {
+ scope: projectOrderScope(project.id),
+ ids: projectChatIds,
+ section: order.section,
+ folderId: project.id,
+ blockEnd,
+ sort: { value: chatSort, set: setChatSort },
+ }),
)}
- {/* An open folder with nothing in it says so. Muted and static: nothing here to click. */}
+ {/* An open folder with nothing in it says so. Muted and static apart from the drop: an empty
+ folder is exactly where a chat is dragged, and it has no row of its own to land on. */}
{expanded && projectChats.length === 0 && (
- <SidebarMenuItem>
+ <SidebarMenuItem
+ {...dnd.dropZoneProps({ section: order.section, folderId: project.id, blockEnd })}
+ >
<p className="flex h-[30px] items-center pl-9 pr-4 text-ui-13 leading-ui-18 tracking-nav text-nav-fg-muted">
{t("shell.navigation.noChats")}
</p>
@@ -3635,7 +4037,10 @@ export function AppSidebar() {
)}
{expanded &&
projectChats.length > PROJECT_CHAT_LIMIT && (
- <SidebarMenuItem>
+ <SidebarMenuItem
+ // Still the folder's block.
+ {...dnd.dropZoneProps({ section: order.section, folderId: project.id, blockEnd })}
+ >
<SidebarMenuButton
onClick={() => toggleProjectShowAll(project.id)}
// Force the muted token: .sidebar-nav-btn's own color rule outweighs a plain text utility,
@@ -3659,6 +4064,7 @@ export function AppSidebar() {
return (
<>
{slotShortcuts}
+ {dropHintPortal}
<Sidebar
collapsible="icon"
collapseToZero={isTauri}
@@ -4070,17 +4476,33 @@ export function AppSidebar() {
</SidebarGroupContent>
</SidebarGroup>
- {/* Pinned: the folders pinned to it, then the pinned chats */}
- {!isStudioRoute &&
- !showTrainingRecents &&
- (pinnedChatItems.length > 0 ||
- (organizeBy === "project" && pinnedProjectRecords.length > 0)) && (
+ {/* Pinned: folders and chats in one list, in the order they were dropped into. */}
+ {!isStudioRoute && !showTrainingRecents && pinnedRows.length > 0 && (
<Collapsible open={pinnedOpen} onOpenChange={setPinnedOpen} asChild>
- <SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">
- <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1", headerRightPadding, scrolled && "is-scrolled")}>
+ <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0">
+ {/* The header takes drops too: above the first row, or into a closed section. */}
+ <SidebarGroupLabel
+ className={cn(
+ "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
+ headerRightPadding,
+ scrolled && "is-scrolled",
+ )}
+ {...dnd.dropZoneProps(
+ {
+ section: "pinned",
+ header: true,
+ row: {
+ id: pinnedRows[0].id,
+ kind: pinnedRows[0].kind,
+ scope: PINNED_ORDER_SCOPE,
+ },
+ },
+ { closed: !pinnedOpen },
+ )}
+ >
<CollapsibleTrigger className="cursor-pointer flex min-w-0 flex-1 items-center gap-1 group/sb-collap">
Pinned
- <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-section:opacity-100 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
</CollapsibleTrigger>
{/* Pinning is the grouping, so no organize half and no "+". */}
{renderSidebarHeaderMenu({
@@ -4091,29 +4513,28 @@ export function AppSidebar() {
})}
</SidebarGroupLabel>
<CollapsibleContent>
- <SidebarGroupContent className={unrailedRowPadding}>
+ {/* The space under the rows lands a drop last. */}
+ <SidebarGroupContent
+ className={cn(unrailedRowPadding, "relative")}
+ {...dnd.dropZoneProps({ section: "pinned" })}
+ >
<SidebarMenu>
- {/* Folders first: a folder carries its own chats. */}
- {organizeBy === "project" &&
- pinnedProjectRecords.map((project, projectIndex) =>
- renderProjectFolderRow(project, projectIndex, {
- scope: PINNED_PROJECT_ORDER_SCOPE,
- orderedIds: pinnedProjectRowIds,
- }),
- )}
- {sortedPinnedChatItems.map((item, index) =>
- renderChatSidebarItem(
- item,
- "recent",
- pinnedDragEnabled
- ? {
- scope: PINNED_ORDER_SCOPE,
- orderedIds: pinnedRowIds,
- index,
- }
- : undefined,
- { scope: PINNED_ORDER_SCOPE, ids: pinnedRowIds },
- ),
+ {pinnedRows.map((row) =>
+ row.kind === "project"
+ ? renderProjectFolderRow(row.project, {
+ scope: PINNED_ORDER_SCOPE,
+ orderedIds: pinnedRowIds,
+ selectionIds: pinnedProjectRowIds,
+ section: "pinned",
+ sort: { value: pinnedSort, set: setPinnedSort },
+ })
+ : renderChatSidebarItem(row.item, "recent", {
+ scope: PINNED_ORDER_SCOPE,
+ ids: pinnedChatRowIds,
+ orderIds: pinnedRowIds,
+ section: "pinned",
+ sort: { value: pinnedSort, set: setPinnedSort },
+ }),
)}
</SidebarMenu>
</SidebarGroupContent>
@@ -4130,20 +4551,37 @@ export function AppSidebar() {
onOpenChange={setProjectsOpen}
asChild
>
- <SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">
- {/* Trigger takes the free space; the actions reveal beside it. */}
- <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1", headerRightPadding, scrolled && "is-scrolled")}>
+ <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0">
+ {/* Trigger takes the free space; the actions reveal beside it. The header also
+ takes a pinned folder dragged back while the section is closed. */}
+ <SidebarGroupLabel
+ className={cn(
+ "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
+ headerRightPadding,
+ scrolled && "is-scrolled",
+ !projectsOpen &&
+ dnd.ringLit(sectionRingKey("projects")) &&
+ DROP_INTO_HEADER_CUE,
+ )}
+ {...dnd.dropZoneProps(
+ {
+ section: "projects",
+ header: true,
+ row: visibleProjectRecords[0]
+ ? {
+ id: visibleProjectRecords[0].id,
+ kind: "project",
+ scope: PROJECT_ORDER_SCOPE,
+ }
+ : undefined,
+ },
+ { closed: !projectsOpen },
+ )}
+ >
<CollapsibleTrigger className="cursor-pointer flex min-w-0 flex-1 items-center gap-1 group/sb-collap">
{t("shell.navigation.projects")}
- <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-section:opacity-100 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
</CollapsibleTrigger>
- {renderSidebarHeaderMenu({
- ariaLabel: t("shell.organize.organizeProjects"),
- includeOrganize: true,
- sortLabel: t("shell.organize.sortChatsBy"),
- sortValue: chatSort,
- onSortChange: setChatSort,
- })}
<button
type="button"
aria-label="New project"
@@ -4155,14 +4593,30 @@ export function AppSidebar() {
>
<HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.75} className="size-icon" />
</button>
+ {renderSidebarHeaderMenu({
+ ariaLabel: t("shell.organize.organizeProjects"),
+ includeOrganize: true,
+ sortLabel: t("shell.organize.sortChatsBy"),
+ sortValue: chatSort,
+ onSortChange: setChatSort,
+ })}
</SidebarGroupLabel>
<CollapsibleContent>
- <SidebarGroupContent className={unrailedRowPadding}>
+ {/* The section itself takes a pinned folder dragged back, landing last. */}
+ <SidebarGroupContent
+ className={cn(
+ unrailedRowPadding,
+ "relative",
+ dnd.ringLit(sectionRingKey("projects")) && DROP_INTO_CUE,
+ )}
+ {...dnd.dropZoneProps({ section: "projects" })}
+ >
<SidebarMenu>
- {visibleProjectRecords.map((project, projectIndex) =>
- renderProjectFolderRow(project, projectIndex, {
+ {visibleProjectRecords.map((project) =>
+ renderProjectFolderRow(project, {
scope: PROJECT_ORDER_SCOPE,
orderedIds: projectRowIds,
+ section: "projects",
}),
)}
{/* Long project lists stay one row deep until asked. */}
@@ -4191,26 +4645,36 @@ export function AppSidebar() {
{!isStudioRoute && !showTrainingRecents && (
<Collapsible open={chatOpen} onOpenChange={setChatOpen} asChild>
- <SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">
+ <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0">
<SidebarGroupLabel
className={cn(
"sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
recentsHeaderRightPadding,
scrolled && "is-scrolled",
usesDesktopTitlebar && "translate-x-[2px]",
+ !chatOpen &&
+ dnd.ringLit(sectionRingKey("recents")) &&
+ DROP_INTO_HEADER_CUE,
+ )}
+ {...dnd.dropZoneProps(
+ {
+ section: "recents",
+ header: true,
+ row: sortedRecentChatItems[0]
+ ? {
+ id: sortedRecentChatItems[0].id,
+ kind: "chat",
+ scope: RECENTS_ORDER_SCOPE,
+ }
+ : undefined,
+ },
+ { closed: !chatOpen },
)}
>
<CollapsibleTrigger className="cursor-pointer flex min-w-0 flex-1 items-center gap-1 group/sb-collap">
{t("shell.navigation.recents")}
- <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-section:opacity-100 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
</CollapsibleTrigger>
- {renderSidebarHeaderMenu({
- ariaLabel: t("shell.organize.organizeChats"),
- includeOrganize: true,
- sortLabel: t("shell.organize.sortChatsBy"),
- sortValue: chatSort,
- onSortChange: setChatSort,
- })}
{/* Starts a chat outside any project, whatever page is open. */}
<button
type="button"
@@ -4220,23 +4684,33 @@ export function AppSidebar() {
>
<HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />
</button>
+ {renderSidebarHeaderMenu({
+ ariaLabel: t("shell.organize.organizeChats"),
+ includeOrganize: true,
+ sortLabel: t("shell.organize.sortChatsBy"),
+ sortValue: chatSort,
+ onSortChange: setChatSort,
+ })}
</SidebarGroupLabel>
<CollapsibleContent>
- <SidebarGroupContent className={unrailedRowPadding}>
+ {/* The section as a whole takes the drop, so a chat dragged out of a folder has
+ somewhere to land even when Recents is empty. */}
+ <SidebarGroupContent
+ className={cn(
+ unrailedRowPadding,
+ "relative",
+ dnd.ringLit(sectionRingKey("recents")) && DROP_INTO_CUE,
+ )}
+ {...dnd.dropZoneProps({ section: "recents" })}
+ >
<SidebarMenu>
- {sortedRecentChatItems.map((item, index) =>
- renderChatSidebarItem(
- item,
- "recent",
- manualDragEnabled
- ? {
- scope: RECENTS_ORDER_SCOPE,
- orderedIds: recentRowIds,
- index,
- }
- : undefined,
- { scope: RECENTS_ORDER_SCOPE, ids: recentRowIds },
- ),
+ {sortedRecentChatItems.map((item) =>
+ renderChatSidebarItem(item, "recent", {
+ scope: RECENTS_ORDER_SCOPE,
+ ids: recentRowIds,
+ section: "recents",
+ sort: { value: chatSort, set: setChatSort },
+ }),
)}
</SidebarMenu>
{/* "No chats yet" only when there is truly no history:
@@ -4257,11 +4731,11 @@ export function AppSidebar() {
{showTrainingRecents && (
<Collapsible open={runsOpen} onOpenChange={setRunsOpen} asChild>
- <SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">
+ <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0">
<SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following", scrolled && "is-scrolled")} asChild>
<CollapsibleTrigger className="cursor-pointer flex w-full items-center gap-1 group/sb-collap">
{t("shell.navigation.recents")}
- <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-section:opacity-100 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
</CollapsibleTrigger>
</SidebarGroupLabel>
<CollapsibleContent>
diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsx
index 684e2fe0202..b6c3233104e 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx
+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx
@@ -30,14 +30,32 @@ import {
UnmeasuredCollapsibleTrigger,
} from "@/components/ui/unmeasured-collapsible";
import {
+ clearReasoningRound,
resolveReasoningGroupDuration,
resolveReasoningOpen,
resolveReasoningToggle,
+ setReasoningRoundOpen,
startsNewReasoningRound,
useChatPreferencesStore,
+ useChatRuntimeStore,
+ useReasoningRoundStore,
} from "@/features/chat";
+import {
+ countFoldedToolParts,
+ endsFoldedSpan,
+ foldEnd,
+ foldedToolSummary,
+ foldedTurnDuration,
+ isBlankTextPart,
+ isFoldedReasoningGroup,
+ leadReasoningEnd,
+ reasoningRoundKey,
+} from "@/components/assistant-ui/thinking-fold";
+import { toolRunIsExempt } from "@/components/assistant-ui/tool-fold-exemptions";
import { isRenderableRenderHtmlToolPart } from "@/features/chat/artifacts/html-fences";
+import { useDetachThreadFromBottom } from "@/components/assistant-ui/use-intent-aware-autoscroll";
import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";
+import { formatWorkedFor } from "@/lib/format-worked-for";
import { cn } from "@/lib/utils";
import {
type ReasoningGroupComponent,
@@ -47,15 +65,17 @@ import {
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { type VariantProps, cva } from "class-variance-authority";
import { ChevronDownIcon, CopyIcon } from "lucide-react";
-import { BulbIcon } from "@/lib/bulb-icon";
import { Tick02Icon } from "@/lib/tick-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import {
type CSSProperties,
type ComponentProps,
+ type ReactNode,
+ type RefObject,
memo,
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -79,7 +99,9 @@ function selectionIntersectsElement(
return false;
}
-export const reasoningVariants = cva("aui-reasoning-root mt-3 mb-4 w-full", {
+// Plain text in the message column: a header line and, when open, the thoughts
+// under it. No box, no icon. Outer spacing comes from the message body's rhythm.
+export const reasoningVariants = cva("aui-reasoning-root w-full", {
variants: {
variant: {
outline: "rounded-lg border px-3 py-2",
@@ -88,7 +110,7 @@ export const reasoningVariants = cva("aui-reasoning-root mt-3 mb-4 w-full", {
},
},
defaultVariants: {
- variant: "outline",
+ variant: "ghost",
},
});
@@ -166,12 +188,16 @@ function ReasoningRoot({
function ReasoningTrigger({
active,
duration,
+ foldedToolCount = 0,
className,
...props
}: ComponentProps<typeof CollapsibleTrigger> & {
active?: boolean;
duration?: number;
+ /** Tool calls hidden under this block, named so a closed block is not silent about them. */
+ foldedToolCount?: number;
}) {
+ const foldedSummary = foldedToolSummary(foldedToolCount);
const Trigger = GRID_COLLAPSE_REASONING_ENABLED
? UnmeasuredCollapsibleTrigger
: CollapsibleTrigger;
@@ -179,27 +205,45 @@ function ReasoningTrigger({
return (
<Trigger
data-slot="reasoning-trigger"
+ data-active={active ? "" : undefined}
className={cn(
- "aui-reasoning-trigger group/trigger flex min-w-0 flex-1 cursor-pointer items-center gap-2 py-1 text-muted-foreground text-sm transition-colors hover:text-foreground",
+ "aui-reasoning-trigger group/trigger flex min-h-5 min-w-0 cursor-pointer items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",
className,
)}
{...props}
>
- <BulbIcon className="aui-reasoning-trigger-icon size-4 shrink-0" />
+ {/* No overflow clipping: with leading-none the line box is the font size, and hidden
+ overflow cuts the descenders off "Thinking" and "Worked". */}
<span
data-slot="reasoning-trigger-label"
- className="aui-reasoning-trigger-label-wrapper relative inline-block leading-none"
+ className="aui-reasoning-trigger-label-wrapper relative inline-block whitespace-nowrap leading-none"
>
{active ? (
- <span className="text-sm">Thinking...</span>
+ <span>Thinking</span>
) : (
- <span>Thought for {duration ?? 0} {duration === 1 ? "second" : "seconds"}</span>
+ <span>Worked for {formatWorkedFor(duration ?? 0)}</span>
+ )}
+ {active && (
+ <span
+ aria-hidden={true}
+ data-slot="reasoning-trigger-shimmer"
+ className="aui-reasoning-trigger-shimmer shimmer pointer-events-none absolute inset-0 motion-reduce:animate-none"
+ >
+ Thinking
+ </span>
)}
</span>
+ {/* Outside the label so it reads while the block is still working and closed. */}
+ {foldedSummary ? (
+ <span className="whitespace-nowrap leading-none text-muted-foreground/70">
+ {"\u00b7 "}
+ {foldedSummary}
+ </span>
+ ) : null}
<ChevronDownIcon
data-slot="reasoning-trigger-chevron"
className={cn(
- "aui-reasoning-trigger-chevron mt-0.5 size-3.5 shrink-0",
+ "aui-reasoning-trigger-chevron size-3.5 shrink-0",
"transition-transform duration-(--animation-duration) ease-out",
"group-data-[state=closed]/trigger:-rotate-90",
"group-data-[state=open]/trigger:rotate-0",
@@ -216,7 +260,7 @@ function ReasoningContent({
...props
}: ComponentProps<typeof CollapsibleContent> & { streaming?: boolean }) {
const shared = cn(
- "aui-reasoning-content relative overflow-hidden text-foreground/85 text-ui-13p5 outline-none",
+ "aui-reasoning-content relative overflow-hidden text-[#0d0d0d] dark:text-foreground outline-none",
"group/collapsible-content ease-out",
"data-[state=closed]:pointer-events-none",
);
@@ -341,9 +385,12 @@ function ReasoningText({
<div
ref={scrollRef}
data-slot="reasoning-text"
+ data-streaming={streaming ? "" : undefined}
className={cn(
- "aui-reasoning-text relative z-0 overflow-y-auto pt-2 pb-0 pl-0 leading-relaxed",
- streaming ? "max-h-64" : "",
+ // Reads like the answer: same size and colour, flush with the header, no cap and no
+ // fade. The thread's own follow-scroll tracks it while it streams.
+ "aui-reasoning-text relative z-0 pt-4 pb-0 leading-relaxed",
+ "[&_p]:my-0 [&_p+p]:mt-4 [&_ul]:my-4 [&_ol]:my-4 [&_pre]:my-4",
"transform-gpu transition-[transform,opacity]",
"group-data-[state=open]/collapsible-content:animate-in",
"group-data-[state=closed]/collapsible-content:animate-out",
@@ -481,55 +528,19 @@ function ReasoningCopyButton({
);
}
-const ReasoningGroupImpl: ReasoningGroupComponent = ({
- children,
- startIndex,
- endIndex,
-}) => {
- const isReasoningStreaming = useAuiState(({ message }) => {
- if (message.status?.type !== "running") {
- return false;
- }
- const parts = message.parts;
- const len = parts.length;
- if (len === 0) {
- return false;
- }
-
- let groupHasReasoning = false;
- for (let i = startIndex; i <= endIndex && i < len; i += 1) {
- if (parts[i]?.type === "reasoning") {
- groupHasReasoning = true;
- break;
- }
- }
- if (!groupHasReasoning) {
- return false;
- }
- for (let i = endIndex + 1; i < len; i += 1) {
- if (parts[i]?.type !== "tool-call") {
- return false;
- }
- }
- return true;
- });
-
- const messageId = useAuiState(({ message }) => message.id);
-
- const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>
- message.parts.some(isRenderableRenderHtmlToolPart),
- );
-
- const reasoningContentRef = useRef<HTMLDivElement>(null);
-
- const reasoningDocuments = useAuiState(
- useShallow(({ message }) =>
- message.parts
- .slice(startIndex, endIndex + 1)
- .filter((part) => part.type === "reasoning")
- .map((part) => ("text" in part ? (part as { text: string }).text : "")),
- ),
- );
+// Paging for a long trace, shared by the lead block and the rounds folded inside it so a long
+// later round is protected the same way the first one is.
+function useReasoningPages({
+ messageId,
+ reasoningDocuments,
+ isStreaming,
+ reasoningContentRef,
+}: {
+ messageId: string;
+ reasoningDocuments: readonly string[];
+ isStreaming: boolean;
+ reasoningContentRef: RefObject<HTMLDivElement | null>;
+}) {
const reasoningText = reasoningDocuments.join("");
const wantsPagination = shouldPaginateReasoning(reasoningText);
const [storedPaginationSession, setPaginationSession] = useState(() => ({
@@ -611,10 +622,10 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({
end: paginationActive ? selectedEnd : reasoningText.length,
streaming:
- paginationActive && isReasoningStreaming && selectedEnd === null,
+ paginationActive && isStreaming && selectedEnd === null,
}),
[
- isReasoningStreaming,
+ isStreaming,
pageSelector,
paginationActive,
reasoningDocuments,
@@ -653,12 +664,253 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({
);
}, [messageId]);
+ return {
+ reasoningText,
+ paginationActive,
+ page,
+ viewingLatestPage,
+ showEarlierPage,
+ showNewerPage,
+ showLatestPage,
+ };
+}
+
+type ReasoningPages = ReturnType<typeof useReasoningPages>;
+
+function ReasoningBody({
+ pages,
+ messageId,
+ messageHasRenderableRenderHtmlTool,
+ isStreaming,
+ retainStreamingHeight = false,
+ textClassName,
+ children,
+}: {
+ pages: ReasoningPages;
+ messageId: string;
+ messageHasRenderableRenderHtmlTool: boolean;
+ isStreaming: boolean;
+ retainStreamingHeight?: boolean;
+ textClassName?: string;
+ children: ReactNode;
+}) {
+ const { page, paginationActive, reasoningText, viewingLatestPage } = pages;
+ return (
+ <>
+ {paginationActive && (
+ <ReasoningPageNavigation
+ hasEarlier={page.hasEarlier}
+ hasNewer={page.hasNewer}
+ onEarlier={pages.showEarlierPage}
+ onNewer={pages.showNewerPage}
+ onLatest={pages.showLatestPage}
+ start={page.start}
+ end={page.end}
+ total={reasoningText.length}
+ />
+ )}
+ <ReasoningText
+ autoScroll={viewingLatestPage}
+ className={textClassName}
+ pageKey={paginationActive ? `${page.start}:${page.end}` : undefined}
+ streaming={isStreaming || retainStreamingHeight}
+ >
+ {paginationActive ? (
+ <>
+ {page.oversizedCode ? (
+ <OversizedReasoningCode source={page.markdown} />
+ ) : (
+ <SearchImagesEnabledContext.Provider value={false}>
+ <MarkdownTextSource
+ key={`${page.documentIndex}:${page.start}`}
+ messageHasRenderableRenderHtmlTool={
+ messageHasRenderableRenderHtmlTool
+ }
+ messageId={messageId}
+ sourceText={page.markdown}
+ streaming={isStreaming && viewingLatestPage}
+ />
+ </SearchImagesEnabledContext.Provider>
+ )}
+ </>
+ ) : (
+ children
+ )}
+ </ReasoningText>
+ </>
+ );
+}
+
+// With the fold preference on, the first Thinking block of a turn heads everything before the
+// answer. Later reasoning groups in that span render as plain rounds inside it, following its
+// open state, and the tool groups between them do the same (see tool-group.tsx).
+const ReasoningGroupImpl: ReasoningGroupComponent = (props) => {
+ const foldToolActivity = useChatPreferencesStore(
+ (state) => state.foldToolActivityIntoThinking,
+ );
+ const folded = useAuiState(
+ ({ message }) =>
+ foldToolActivity && isFoldedReasoningGroup(message.parts, props.startIndex),
+ );
+ if (folded) {
+ return <FoldedReasoningRound {...props} />;
+ }
+ return <ReasoningGroupBlock {...props} foldTurn={foldToolActivity} />;
+};
+
+// A thin line closing the trace when the answer comes right after it, so the two do not read
+// as one text. Rendered inside whatever is last under the header, so it hides with it.
+function ReasoningEndRule() {
+ return (
+ <div
+ data-slot="reasoning-end-rule"
+ aria-hidden={true}
+ className="mt-4 border-border/60 border-t"
+ />
+ );
+}
+
+const FoldedReasoningRound: ReasoningGroupComponent = ({
+ children,
+ startIndex,
+ endIndex,
+}) => {
+ const messageId = useAuiState(({ message }) => message.id);
+ const roundKey = useAuiState(({ message }) => {
+ const lead = leadReasoningEnd(message.parts, startIndex);
+ return lead === null ? null : reasoningRoundKey(message.id, lead);
+ });
+ const open = useReasoningRoundStore(
+ (state) => roundKey !== null && (state.open[roundKey] ?? false),
+ );
+ // Streaming while this round is the last thinking so far and only calls follow it.
+ const isStreaming = useAuiState(({ message }) => {
+ if (message.status?.type !== "running") return false;
+ const parts = message.parts;
+ for (let i = endIndex + 1; i < parts.length; i += 1) {
+ if (parts[i]?.type !== "tool-call") return false;
+ }
+ return true;
+ });
+ const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>
+ message.parts.some(isRenderableRenderHtmlToolPart),
+ );
+ const reasoningContentRef = useRef<HTMLDivElement>(null);
+ const reasoningDocuments = useAuiState(
+ useShallow(({ message }) =>
+ message.parts
+ .slice(startIndex, endIndex + 1)
+ .filter((part) => part.type === "reasoning")
+ .map((part) => ("text" in part ? (part as { text: string }).text : "")),
+ ),
+ );
+ const pages = useReasoningPages({
+ messageId,
+ reasoningDocuments,
+ isStreaming,
+ reasoningContentRef,
+ });
+ const closesTrace = useAuiState(({ message }) =>
+ endsFoldedSpan(message.parts, endIndex),
+ );
+ // Hidden, not unmounted, so the text keeps streaming in while the lead is closed.
+ return (
+ <div
+ ref={reasoningContentRef}
+ data-slot="reasoning-folded-round"
+ className={cn(!open && "hidden")}
+ >
+ <ReasoningBody
+ pages={pages}
+ messageId={messageId}
+ messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}
+ isStreaming={isStreaming}
+ textClassName="pt-0"
+ >
+ {children}
+ </ReasoningBody>
+ {closesTrace && <ReasoningEndRule />}
+ </div>
+ );
+};
+
+const ReasoningGroupBlock = ({
+ children,
+ startIndex,
+ endIndex,
+ foldTurn,
+}: ComponentProps<ReasoningGroupComponent> & { foldTurn: boolean }) => {
+ // The lead of a folded span: its first Thinking block.
+ const foldLead = useAuiState(
+ ({ message }) =>
+ foldTurn && leadReasoningEnd(message.parts, endIndex) === endIndex,
+ );
+ const isReasoningStreaming = useAuiState(({ message }) => {
+ if (message.status?.type !== "running") {
+ return false;
+ }
+ const parts = message.parts;
+ const len = parts.length;
+ if (len === 0) {
+ return false;
+ }
+
+ let groupHasReasoning = false;
+ for (let i = startIndex; i <= endIndex && i < len; i += 1) {
+ if (parts[i]?.type === "reasoning") {
+ groupHasReasoning = true;
+ break;
+ }
+ }
+ if (!groupHasReasoning) {
+ return false;
+ }
+ // The lead of a folded span keeps working through later thinking and blank text too,
+ // until the answer.
+ for (let i = endIndex + 1; i < len; i += 1) {
+ const part = parts[i];
+ if (part?.type === "tool-call") continue;
+ if (foldLead && (part?.type === "reasoning" || isBlankTextPart(part))) {
+ continue;
+ }
+ return false;
+ }
+ return true;
+ });
+
+ const messageId = useAuiState(({ message }) => message.id);
+
+ const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>
+ message.parts.some(isRenderableRenderHtmlToolPart),
+ );
+
+ const reasoningContentRef = useRef<HTMLDivElement>(null);
+
+ const reasoningDocuments = useAuiState(
+ useShallow(({ message }) =>
+ message.parts
+ .slice(startIndex, endIndex + 1)
+ .filter((part) => part.type === "reasoning")
+ .map((part) => ("text" in part ? (part as { text: string }).text : "")),
+ ),
+ );
+ const pages = useReasoningPages({
+ messageId,
+ reasoningDocuments,
+ isStreaming: isReasoningStreaming,
+ reasoningContentRef,
+ });
+
const persistedDuration = useAuiState(({ message }) => {
- return resolveReasoningGroupDuration(
- message.parts,
- startIndex,
- message.metadata?.custom as Record<string, unknown> | undefined,
- );
+ const custom = message.metadata?.custom as
+ | Record<string, unknown>
+ | undefined;
+ if (foldLead) {
+ return foldedTurnDuration(message.parts, endIndex, (parts, start) =>
+ resolveReasoningGroupDuration(parts, start, custom),
+ );
+ }
+ return resolveReasoningGroupDuration(message.parts, startIndex, custom);
});
const collapseByDefault = useChatPreferencesStore(
@@ -722,11 +974,42 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({
dismissedWhileStreaming,
manualOpen,
});
- const variant = isOpen ? "outline" : "ghost";
+ // Publish the lead's open state for everything folded under it, and count the tool calls for
+ // its header. A layout effect, so the folded parts settle before the frame the user sees.
+ const roundKey = reasoningRoundKey(messageId, endIndex);
+ const toolConfirmations = useChatRuntimeStore((s) => s.toolConfirmations);
+ const foldedToolCount = useAuiState(({ message }) =>
+ foldLead
+ ? countFoldedToolParts(message.parts, endIndex, (start, end) =>
+ toolRunIsExempt(message.parts, start, end, toolConfirmations),
+ )
+ : 0,
+ );
+ // Copy reaches the rounds folded in here too: they have no Copy of their own.
+ const copyEndIndex = useAuiState(({ message }) =>
+ foldLead ? foldEnd(message.parts, endIndex) - 1 : endIndex,
+ );
+ // The answer follows this block directly, with nothing folded in between.
+ const closesTrace = useAuiState(({ message }) =>
+ foldLead
+ ? endsFoldedSpan(message.parts, endIndex)
+ : message.parts[endIndex + 1]?.type === "text",
+ );
+ useLayoutEffect(() => {
+ if (!foldLead) return;
+ setReasoningRoundOpen(roundKey, isOpen);
+ }, [foldLead, isOpen, roundKey]);
+ useLayoutEffect(() => () => clearReasoningRound(roundKey), [roundKey]);
- // Allow closing during streaming (matches ChatGPT).
+ // Opening by hand grows the block downward and leaves the header where it is. The viewport
+ // would otherwise treat the growth as new content and pin the bottom, which shoves the header
+ // up. Streaming keeps following: the auto-open is not a click and the stream should track.
+ const detachFromBottom = useDetachThreadFromBottom();
const handleOpenChange = useCallback(
(open: boolean) => {
+ if (open && !isReasoningStreaming) {
+ detachFromBottom();
+ }
const next = resolveReasoningToggle(open, {
isStreaming: isReasoningStreaming,
collapseByDefault,
@@ -739,72 +1022,46 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({
setDismissedWhileStreaming(next.dismissedWhileStreaming);
}
},
- [isReasoningStreaming, collapseByDefault],
+ [isReasoningStreaming, collapseByDefault, detachFromBottom],
);
return (
- <ReasoningRoot
- open={isOpen}
- onOpenChange={handleOpenChange}
- variant={variant}
- >
- <div className="flex min-w-0 items-center gap-2">
+ <ReasoningRoot open={isOpen} onOpenChange={handleOpenChange}>
+ <div
+ data-slot="reasoning-header"
+ className="flex min-w-0 items-center gap-2"
+ >
<ReasoningTrigger
- className="min-w-0 flex-1"
+ className="min-w-0"
active={isReasoningStreaming}
// Prefer server timing when available.
duration={persistedDuration ?? duration}
+ foldedToolCount={isOpen ? 0 : foldedToolCount}
/>
- <div className="flex w-16 shrink-0 justify-end">
- {isOpen && !isReasoningStreaming && (
- <ReasoningCopyButton startIndex={startIndex} endIndex={endIndex} />
- )}
- </div>
+ {isOpen && !isReasoningStreaming && (
+ <span className="ml-auto flex items-center leading-none">
+ <ReasoningCopyButton
+ startIndex={startIndex}
+ endIndex={copyEndIndex}
+ />
+ </span>
+ )}
</div>
<ReasoningContent
aria-busy={isReasoningStreaming}
streaming={isReasoningStreaming}
ref={reasoningContentRef}
>
- {paginationActive && (
- <ReasoningPageNavigation
- hasEarlier={page.hasEarlier}
- hasNewer={page.hasNewer}
- onEarlier={showEarlierPage}
- onNewer={showNewerPage}
- onLatest={showLatestPage}
- start={page.start}
- end={page.end}
- total={reasoningText.length}
- />
- )}
- <ReasoningText
- autoScroll={viewingLatestPage}
- pageKey={paginationActive ? `${page.start}:${page.end}` : undefined}
- streaming={isReasoningStreaming || retainStreamingHeight}
+ <ReasoningBody
+ pages={pages}
+ messageId={messageId}
+ messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}
+ isStreaming={isReasoningStreaming}
+ retainStreamingHeight={retainStreamingHeight}
>
- {paginationActive ? (
- <>
- {page.oversizedCode ? (
- <OversizedReasoningCode source={page.markdown} />
- ) : (
- <SearchImagesEnabledContext.Provider value={false}>
- <MarkdownTextSource
- key={`${page.documentIndex}:${page.start}`}
- messageHasRenderableRenderHtmlTool={
- messageHasRenderableRenderHtmlTool
- }
- messageId={messageId}
- sourceText={page.markdown}
- streaming={isReasoningStreaming && viewingLatestPage}
- />
- </SearchImagesEnabledContext.Provider>
- )}
- </>
- ) : (
- children
- )}
- </ReasoningText>
+ {children}
+ </ReasoningBody>
+ {closesTrace && <ReasoningEndRule />}
</ReasoningContent>
</ReasoningRoot>
);
diff --git a/studio/frontend/src/components/assistant-ui/thinking-fold.ts b/studio/frontend/src/components/assistant-ui/thinking-fold.ts
new file mode 100644
index 00000000000..cbae87e0d85
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/thinking-fold.ts
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// With the fold preference on, one Thinking block holds a span's whole run-up to the answer: its
+// own thoughts, every tool call, and any thinking that follows those calls. The parts are grouped
+// by type, so those pieces render as siblings of the block; these helpers say which of them it
+// holds and which stay where they are.
+//
+// A span is a maximal run of thinking, tool calls and blank text, and is led by its first
+// reasoning group. Only answer text with something in it ends a span: the whitespace a provider
+// leaves between a closed think block and its tool call is not an answer, and neither is the
+// previous reply a continuation is seeded with, which sits before the new round rather than
+// ending it. A message can therefore hold several spans, each folded under its own lead.
+
+interface PartLike {
+ readonly type: string;
+ readonly text?: unknown;
+}
+
+/** One Thinking block, named by the message and the last part of its reasoning group. */
+export function reasoningRoundKey(messageId: string, endIndex: number): string {
+ return `${messageId}:${endIndex}`;
+}
+
+/** A text part with nothing to read in it. Text of an unexpected shape is not assumed blank. */
+export function isBlankTextPart(part: PartLike | undefined): boolean {
+ return (
+ part?.type === "text" &&
+ typeof part.text === "string" &&
+ part.text.trim() === ""
+ );
+}
+
+function belongsToRun(part: PartLike | undefined): boolean {
+ const type = part?.type;
+ return type === "reasoning" || type === "tool-call" || isBlankTextPart(part);
+}
+
+/** `[start, end)` of the run of thinking, tool calls and blank text around `index`, or null
+ * when `index` is answer text. */
+export function foldRun(
+ parts: readonly PartLike[],
+ index: number,
+): { start: number; end: number } | null {
+ if (index < 0 || index >= parts.length || !belongsToRun(parts[index])) {
+ return null;
+ }
+ let start = index;
+ while (start > 0 && belongsToRun(parts[start - 1])) start -= 1;
+ let end = index + 1;
+ while (end < parts.length && belongsToRun(parts[end])) end += 1;
+ return { start, end };
+}
+
+/** Last part of the first reasoning group in the run around `index`: the block that heads it.
+ * Null when the run has no thinking, or `index` is not in a run. */
+export function leadReasoningEnd(
+ parts: readonly PartLike[],
+ index: number,
+): number | null {
+ const run = foldRun(parts, index);
+ if (run === null) return null;
+ let end: number | null = null;
+ for (let i = run.start; i < run.end; i += 1) {
+ if (parts[i]?.type === "reasoning") {
+ end = i;
+ continue;
+ }
+ if (end !== null) break;
+ }
+ return end;
+}
+
+/** Index just past the run the lead heads: where the answer starts, or the end of the parts. */
+export function foldEnd(parts: readonly PartLike[], leadEnd: number): number {
+ return foldRun(parts, leadEnd)?.end ?? leadEnd + 1;
+}
+
+/** The block a group at `startIndex` folds under: its run's lead, when the group comes after
+ * it. Null for the lead itself, for calls with no thinking before them in the run, and for
+ * anything outside a run. */
+export function governingReasoningEnd(
+ parts: readonly PartLike[],
+ startIndex: number,
+): number | null {
+ const lead = leadReasoningEnd(parts, startIndex);
+ if (lead === null || startIndex <= lead) return null;
+ return lead;
+}
+
+/** A later reasoning group that shows inside its lead instead of heading its own block. */
+export function isFoldedReasoningGroup(
+ parts: readonly PartLike[],
+ startIndex: number,
+): boolean {
+ return governingReasoningEnd(parts, startIndex) !== null;
+}
+
+/** Tool calls the lead is holding, for its collapsed header. A run the thread keeps visible
+ * (see tool-fold-exemptions.ts) is left out, so the header never claims a call that is on
+ * screen below it. */
+export function countFoldedToolParts(
+ parts: readonly PartLike[],
+ leadEnd: number,
+ runIsExempt: (start: number, end: number) => boolean = () => false,
+): number {
+ const end = foldEnd(parts, leadEnd);
+ let count = 0;
+ let i = leadEnd + 1;
+ while (i < end) {
+ if (parts[i]?.type !== "tool-call") {
+ i += 1;
+ continue;
+ }
+ let runEnd = i;
+ while (runEnd + 1 < end && parts[runEnd + 1]?.type === "tool-call") {
+ runEnd += 1;
+ }
+ if (!runIsExempt(i, runEnd)) count += runEnd - i + 1;
+ i = runEnd + 1;
+ }
+ return count;
+}
+
+/** Time the lead reports: every reasoning group in its run, added up. Rounds with no saved
+ * duration are left out rather than zeroing the total: a reply saved with only the legacy
+ * last-round duration still reports that. Undefined only when no round is known, so the
+ * caller falls back to its own clock. */
+export function foldedTurnDuration(
+ parts: readonly PartLike[],
+ leadEnd: number,
+ resolve: (
+ parts: readonly PartLike[],
+ startIndex: number,
+ ) => number | undefined,
+): number | undefined {
+ const run = foldRun(parts, leadEnd);
+ if (run === null) return undefined;
+ let total: number | undefined;
+ let previousWasReasoning = false;
+ for (let i = run.start; i < run.end; i += 1) {
+ const isReasoning = parts[i]?.type === "reasoning";
+ if (isReasoning && !previousWasReasoning) {
+ const duration = resolve(parts, i);
+ if (duration !== undefined) total = (total ?? 0) + duration;
+ }
+ previousWasReasoning = isReasoning;
+ }
+ return total;
+}
+
+/** Whether the part at `endIndex` is the last thing shown under its lead and the answer comes
+ * right after: where the rule that closes the trace goes. */
+export function endsFoldedSpan(
+ parts: readonly PartLike[],
+ endIndex: number,
+): boolean {
+ const run = foldRun(parts, endIndex);
+ if (run === null || run.end >= parts.length) return false;
+ if (isBlankTextPart(parts[endIndex])) return false;
+ if (leadReasoningEnd(parts, endIndex) === null) return false;
+ let last = run.end - 1;
+ while (last > endIndex && isBlankTextPart(parts[last])) last -= 1;
+ return last === endIndex;
+}
+
+/** What the header says it is holding while closed. Same wording as the tool group trigger, so
+ * the count reads the same once the block is open. */
+export function foldedToolSummary(count: number): string | null {
+ if (count <= 0) return null;
+ return `${count} tool ${count === 1 ? "call" : "calls"}`;
+}
diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
index 80ad7e8ced5..ce77c661a0a 100644
--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
@@ -11,6 +11,7 @@ import {
import { Spinner } from "@/components/ui/spinner";
// eslint-disable-next-line no-restricted-imports -- the feature barrel imports this component
import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
+import { useDetachThreadFromBottom } from "@/components/assistant-ui/use-intent-aware-autoscroll";
import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";
import {
formatMcpToolName,
@@ -22,6 +23,7 @@ import { cn } from "@/lib/utils";
import {
type ToolCallMessagePartComponent,
type ToolCallMessagePartStatus,
+ useAuiState,
} from "@assistant-ui/react";
import {
AlertCircleIcon,
@@ -99,10 +101,17 @@ function ToolFallbackRoot({
awaitingApproval ||
(isControlled ? controlledOpen : syncedUncontrolledState.open);
+ // Opening by hand grows the card downward; see the same note in reasoning.tsx.
+ const detachFromBottom = useDetachThreadFromBottom();
+ const messageRunning = useAuiState(
+ ({ message }) => message.status?.type === "running",
+ );
const handleOpenChange = useCallback(
(open: boolean) => {
if (!open) {
lockScroll();
+ } else if (!messageRunning) {
+ detachFromBottom();
}
if (!isControlled) {
setUncontrolledState({
@@ -112,7 +121,14 @@ function ToolFallbackRoot({
}
controlledOnOpenChange?.(open);
},
- [collapseByDefault, lockScroll, isControlled, controlledOnOpenChange],
+ [
+ collapseByDefault,
+ lockScroll,
+ isControlled,
+ controlledOnOpenChange,
+ detachFromBottom,
+ messageRunning,
+ ],
);
return (
@@ -122,7 +138,7 @@ function ToolFallbackRoot({
open={isOpen}
onOpenChange={handleOpenChange}
className={cn(
- "aui-tool-fallback-root group/tool-fallback-root w-full py-1",
+ "aui-tool-fallback-root group/tool-fallback-root w-full",
className,
)}
style={
@@ -183,7 +199,7 @@ function ToolFallbackTrigger({
<CollapsibleTrigger
data-slot="tool-fallback-trigger"
className={cn(
- "aui-tool-fallback-trigger group/trigger flex w-full cursor-pointer items-center gap-2 py-1.5 text-sm transition-colors",
+ "aui-tool-fallback-trigger group/trigger flex w-full cursor-pointer items-center gap-2 text-sm transition-colors",
className,
)}
{...props}
@@ -271,7 +287,7 @@ function ToolFallbackContent({
)}
{...props}
>
- <div className="mt-1 flex flex-col gap-2 pl-5">{children}</div>
+ <div className="mt-2 flex flex-col gap-2 pl-5">{children}</div>
</CollapsibleContent>
);
}
diff --git a/studio/frontend/src/components/assistant-ui/tool-fold-exemptions.ts b/studio/frontend/src/components/assistant-ui/tool-fold-exemptions.ts
new file mode 100644
index 00000000000..a15b9fa037d
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/tool-fold-exemptions.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Which tool calls stay visible whatever the fold and collapse preferences say. One place for the
+// rule, so the tool group that shows the run and the Thinking header that counts it agree.
+
+import { hasCreatedFiles } from "./sandbox-files.ts";
+
+export interface ToolPartLike {
+ readonly type: string;
+ readonly toolName?: string;
+ readonly toolCallId?: string;
+ readonly result?: unknown;
+}
+
+/** An MCP-style result with images in it, the shape the fallback card shows previews for. */
+export function carriesImages(result: unknown): boolean {
+ if (typeof result !== "object" || result === null) {
+ return false;
+ }
+ const v = result as { text?: unknown; images?: unknown };
+ return (
+ typeof v.text === "string" &&
+ Array.isArray(v.images) &&
+ v.images.length > 0 &&
+ v.images.every(
+ (img: unknown) =>
+ typeof img === "object" &&
+ img !== null &&
+ typeof (img as { data?: unknown }).data === "string" &&
+ typeof (img as { mimeType?: unknown }).mimeType === "string",
+ )
+ );
+}
+
+/** Canvases, Python, generated images, results that carry images and anything that wrote a
+ * file: their output lives only in the card, so it is never tucked away. */
+export function holdsOwnOutput(part: ToolPartLike): boolean {
+ return (
+ part.type === "tool-call" &&
+ (part.toolName === "render_html" ||
+ part.toolName === "python" ||
+ part.toolName === "image_generation" ||
+ carriesImages(part.result) ||
+ hasCreatedFiles(part.toolName, part.result))
+ );
+}
+
+/** A blocking allow or deny prompt must never sit behind a collapsed header. */
+export function awaitsConfirmation(
+ part: ToolPartLike,
+ toolConfirmations: Record<string, unknown>,
+): boolean {
+ return (
+ part.type === "tool-call" &&
+ part.toolCallId !== undefined &&
+ Object.prototype.hasOwnProperty.call(toolConfirmations, part.toolCallId)
+ );
+}
+
+/** Whether the run of calls at [start, end] stays visible instead of folding. */
+export function toolRunIsExempt(
+ parts: readonly ToolPartLike[],
+ start: number,
+ end: number,
+ toolConfirmations: Record<string, unknown>,
+): boolean {
+ for (let i = start; i <= end && i < parts.length; i += 1) {
+ const part = parts[i];
+ if (!part) {
+ continue;
+ }
+ if (holdsOwnOutput(part) || awaitsConfirmation(part, toolConfirmations)) {
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/studio/frontend/src/components/assistant-ui/tool-group.tsx b/studio/frontend/src/components/assistant-ui/tool-group.tsx
index ba67f744bcc..c4b2c974646 100644
--- a/studio/frontend/src/components/assistant-ui/tool-group.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-group.tsx
@@ -11,6 +11,13 @@ import {
import { useAuiState } from "@assistant-ui/react";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
+// eslint-disable-next-line no-restricted-imports -- this file is in the startup cycle; the chat barrel closes it.
+import { useReasoningRoundStore } from "@/features/chat/stores/reasoning-round-store";
+import {
+ endsFoldedSpan,
+ governingReasoningEnd,
+ reasoningRoundKey,
+} from "./thinking-fold";
import {
toolOutputKey,
useToolPaneScope,
@@ -25,10 +32,11 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
+import { useDetachThreadFromBottom } from "@/components/assistant-ui/use-intent-aware-autoscroll";
import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";
import { cn } from "@/lib/utils";
import { Spinner } from "@/components/ui/spinner";
-import { hasCreatedFiles } from "./sandbox-files";
+import { awaitsConfirmation, holdsOwnOutput } from "./tool-fold-exemptions";
import { syncToolActivityPreference } from "./tool-activity-open-state";
const ANIMATION_DURATION = 200;
@@ -37,7 +45,7 @@ const toolGroupVariants = cva("aui-tool-group-root group/tool-group w-full", {
variants: {
variant: {
outline: "corner-squircle rounded-lg border py-3",
- ghost: "py-2",
+ ghost: "",
muted:
"corner-squircle rounded-lg border border-muted-foreground/30 bg-muted/30 py-3",
},
@@ -88,17 +96,31 @@ function ToolGroupRoot({
const isControlled = controlledOpen !== undefined;
const isOpen = isControlled ? controlledOpen : syncedUncontrolledState.open;
+ // Opening by hand grows the group downward; see the same note in reasoning.tsx.
+ const detachFromBottom = useDetachThreadFromBottom();
+ const messageRunning = useAuiState(
+ ({ message }) => message.status?.type === "running",
+ );
const handleOpenChange = useCallback(
(open: boolean) => {
if (!open) {
lockScroll();
+ } else if (!messageRunning) {
+ detachFromBottom();
}
if (!isControlled) {
setUncontrolledState({ collapseByDefault, open });
}
controlledOnOpenChange?.(open);
},
- [collapseByDefault, lockScroll, isControlled, controlledOnOpenChange],
+ [
+ collapseByDefault,
+ lockScroll,
+ isControlled,
+ controlledOnOpenChange,
+ detachFromBottom,
+ messageRunning,
+ ],
);
return (
@@ -214,7 +236,7 @@ function ToolGroupContent({
"mt-2 flex flex-col gap-2",
"group-data-[variant=outline]/tool-group-root:mt-3 group-data-[variant=outline]/tool-group-root:border-t group-data-[variant=outline]/tool-group-root:px-4 group-data-[variant=outline]/tool-group-root:pt-3",
"group-data-[variant=muted]/tool-group-root:mt-3 group-data-[variant=muted]/tool-group-root:border-t group-data-[variant=muted]/tool-group-root:px-4 group-data-[variant=muted]/tool-group-root:pt-3",
- "group-data-[variant=ghost]/tool-group-root:mt-1 group-data-[variant=ghost]/tool-group-root:gap-1",
+ "group-data-[variant=ghost]/tool-group-root:mt-3 group-data-[variant=ghost]/tool-group-root:gap-3",
)}
>
{children}
@@ -236,15 +258,7 @@ const ToolGroupImpl: FC<
> = ({ children, startIndex, endIndex }) => {
const toolCount = endIndex - startIndex + 1;
const containsUngroupedTool = useAuiState(({ message }) =>
- message.parts
- .slice(startIndex, endIndex + 1)
- .some(
- (part) =>
- part.type === "tool-call" &&
- (part.toolName === "render_html" ||
- part.toolName === "python" ||
- hasCreatedFiles(part.toolName, part.result)),
- ),
+ message.parts.slice(startIndex, endIndex + 1).some(holdsOwnOutput),
);
// A blocking allow/deny prompt must never be hidden inside a collapsed
// group, so force the group open while any of its calls awaits confirmation.
@@ -252,14 +266,7 @@ const ToolGroupImpl: FC<
const hasPendingConfirmation = useAuiState(({ message }) =>
message.parts
.slice(startIndex, endIndex + 1)
- .some(
- (part) =>
- part.type === "tool-call" &&
- Object.prototype.hasOwnProperty.call(
- toolConfirmations,
- part.toolCallId,
- ),
- ),
+ .some((part) => awaitsConfirmation(part, toolConfirmations)),
);
const messageRunning = useAuiState(
({ message }) => message.status?.type === "running",
@@ -303,17 +310,62 @@ const ToolGroupImpl: FC<
((hasLiveOutput && messageRunning) ||
(forcedOpenRef.current && messageRunning)));
+ // With the fold preference on, this run of calls belongs to the turn's first thinking block
+ // and shows only while that block is open. Calls that hold their own output, and any awaiting
+ // an allow or deny, are never folded away.
+ const foldToolActivity = useChatPreferencesStore(
+ (state) => state.foldToolActivityIntoThinking,
+ );
+ const roundKey = useAuiState(({ message }) => {
+ const reasoningEnd = governingReasoningEnd(message.parts, startIndex);
+ return reasoningEnd === null
+ ? null
+ : reasoningRoundKey(message.id, reasoningEnd);
+ });
+ const roundOpen = useReasoningRoundStore((state) =>
+ roundKey === null ? true : (state.open[roundKey] ?? false),
+ );
+ const underThinking = foldToolActivity && roundKey !== null;
+ const exempt = containsUngroupedTool || hasPendingConfirmation;
+ // Last thing under the block, with the answer right after: close the trace with a rule.
+ const closesTrace = useAuiState(({ message }) =>
+ endsFoldedSpan(message.parts, endIndex),
+ );
+
// Render single calls, canvases, Python scripts, and calls that created files
// directly so their persistent content never hides in a collapsed group.
- if (toolCount <= 1 || containsUngroupedTool) {
- return <>{children}</>;
+ const group =
+ toolCount <= 1 || containsUngroupedTool ? (
+ <>{children}</>
+ ) : (
+ <ToolGroupRoot open={forceOpen ? true : undefined}>
+ <ToolGroupTrigger count={toolCount} />
+ <ToolGroupContent>{children}</ToolGroupContent>
+ </ToolGroupRoot>
+ );
+
+ if (!underThinking) {
+ return group;
}
+ // Hidden rather than unmounted: a folded run keeps its cards, its scroll positions and any
+ // output still streaming into it, so opening the block is instant and loses nothing. The
+ // wrapper stays while the run is under a block, exempt or not, so an approval arriving or
+ // clearing only changes visibility and never remounts the cards.
return (
- <ToolGroupRoot open={forceOpen ? true : undefined}>
- <ToolGroupTrigger count={toolCount} />
- <ToolGroupContent>{children}</ToolGroupContent>
- </ToolGroupRoot>
+ <div
+ data-slot="tool-run-under-thinking"
+ className={cn(!(roundOpen || exempt) && "hidden")}
+ >
+ {group}
+ {closesTrace && (
+ <div
+ data-slot="reasoning-end-rule"
+ aria-hidden={true}
+ className={cn("mt-4 border-border/60 border-t", !roundOpen && "hidden")}
+ />
+ )}
+ </div>
);
};
diff --git a/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx b/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx
index eb905b6625e..8ac3cd6b4e9 100644
--- a/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx
+++ b/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx
@@ -125,6 +125,12 @@ export function useAdjustForContentInsertedAbove(): (deltaPx: number) => void {
return useContext(AutoScrollContext).adjustForContentInsertedAbove;
}
+/** See AutoScrollContextValue.detachFromBottom. Opening a collapsible by hand near the bottom
+ * must grow it downward, not pin the bottom and shove the header up. */
+export function useDetachThreadFromBottom(): () => void {
+ return useContext(AutoScrollContext).detachFromBottom;
+}
+
export function useIsThreadAtBottom(): boolean {
const ctx = useContext(AutoScrollContext);
return useSyncExternalStore(ctx.subscribe, ctx.getIsAtBottom, () => true);
diff --git a/studio/frontend/src/features/chat/components/edit-project-dialog.tsx b/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
index 59245a2f6dc..5ce5d21348b 100644
--- a/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
@@ -96,7 +96,18 @@ export function EditProjectDialog({
close();
}}
>
- <DialogContent className="corner-squircle dialog-soft-surface gap-5 sm:max-w-lg">
+ <DialogContent
+ className="corner-squircle dialog-soft-surface gap-5 sm:max-w-lg"
+ // Enter saves from the name field, which a multi-line instructions box cannot do; the
+ // chord saves from either. The menus and confirmations inside portal out of here, so
+ // their own keys never reach this.
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ void save();
+ }
+ }}
+ >
<DialogHeader>
<DialogTitle className="text-ui-21">Edit project</DialogTitle>
<DialogDescription className="sr-only">
@@ -113,13 +124,17 @@ export function EditProjectDialog({
className="size-5"
/>
</span>
- <span aria-hidden="true" className="my-3 w-px bg-border" />
+ {/* The rule that separates the icon from the field. The container drops its border in
+ dark mode, where --border goes with it, so the rule carries its own tint there. */}
+ <span aria-hidden="true" className="my-3 w-px bg-border dark:bg-white/10" />
<input
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
+ // The chord would reach the dialog's handler too and save twice.
+ e.stopPropagation();
void save();
}
}}
@@ -131,7 +146,7 @@ export function EditProjectDialog({
className="min-w-0 flex-1 bg-transparent py-4 pr-4 pl-2.5 text-base outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
/>
</div>
- <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-1.5">
<label
htmlFor="edit-project-instructions"
className="text-ui-15 font-medium text-foreground"
@@ -148,26 +163,33 @@ export function EditProjectDialog({
disabled={busy}
rows={4}
placeholder="How should the model answer in this project?"
- className="resize-none rounded-[16px]"
+ className="mt-0.5 resize-none rounded-[16px]"
/>
</div>
{/* The Sources tab's own manager, so a folder linked here is linked there. */}
- <div className="rounded-[18px] bg-muted/30 px-4 py-3.5">
- <LinkedFoldersManager
- scope={{ type: "project", id: project.id }}
- compact={true}
- />
+ <div className="flex flex-col gap-1.5">
+ <h3 className="text-ui-15 font-medium text-foreground">
+ Source folders
+ </h3>
+ <p className="text-ui-13 text-muted-foreground">
+ Indexed and kept in sync, for every chat in this project to search.
+ </p>
+ <div className="mt-0.5">
+ <LinkedFoldersManager
+ scope={{ type: "project", id: project.id }}
+ variant="card"
+ />
+ </div>
</div>
<DialogFooter className="flex-wrap gap-2 sm:justify-between">
<Button
type="button"
- variant="ghost"
+ variant="destructive"
disabled={busy}
onClick={() => {
onOpenChange(false);
onDelete(project);
}}
- className="text-destructive hover:bg-destructive/10 hover:text-destructive"
>
Delete project
</Button>
diff --git a/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
new file mode 100644
index 00000000000..ffe13368aea
--- /dev/null
+++ b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
@@ -0,0 +1,238 @@
+// 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 React side of sidebar drag-and-drop: the lifted row, the plan under the pointer, and the
+// native drag events that feed both. What a drop does is decided in lib/sidebar-drag.ts.
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import {
+ dropEdgeAt,
+ planKey,
+ planSidebarDrop,
+ rowKey,
+ STAY,
+ type DropEdge,
+ type SidebarDragItem,
+ type SidebarDropContext,
+ type SidebarDropPlan,
+ type SidebarDropZone,
+} from "../lib/sidebar-drag.ts";
+import {
+ setSidebarDragSource,
+ sidebarDragSource,
+} from "../stores/sidebar-drag-source.ts";
+
+/** How long the pointer rests on a closed folder or section before it opens. */
+export const SPRING_OPEN_DELAY_MS = 450;
+
+// Zones nest (row in folder block in section). The first zone to answer a dragover marks the
+// event here; outer zones stand down, and the document listener reads the same mark to know
+// whether anything answered. Marking instead of stopping propagation keeps the document
+// listener, which moves the hint, in the loop.
+let lastHandledEvent: Event | null = null;
+
+export interface UseSidebarDragOptions {
+ /** Read at event time, so a plan sees the lists as they stand. */
+ context: () => SidebarDropContext;
+ /** Commits the plan the row was dropped on. */
+ onDrop: (plan: SidebarDropPlan, drag: SidebarDragItem) => void;
+ /** Opens the closed folder or section the pointer rested on. */
+ onSpringOpen?: (zone: SidebarDropZone) => void;
+ /** Whether resting on a closed folder or section opens it. */
+ springOpen: boolean;
+ /** The hint element. Positioned directly, so pointer moves do not re-render the sidebar. */
+ hintRef?: React.RefObject<HTMLDivElement | null>;
+}
+
+export interface SidebarDragApi {
+ /** The lifted row, for painting it faded. Null between drags. */
+ drag: SidebarDragItem | null;
+ /** What the drop under the pointer would do. */
+ plan: SidebarDropPlan | null;
+ /** Props that let a row be picked up. */
+ dragHandleProps: (item: SidebarDragItem) => {
+ draggable: true;
+ onDragStart: (event: React.DragEvent) => void;
+ onDragEnd: () => void;
+ };
+ /** Props that let a spot take a drop. `closed` marks a collapsed folder or section. */
+ dropZoneProps: (
+ zone: SidebarDropZone,
+ options?: { closed?: boolean },
+ ) => {
+ onDragOver: (event: React.DragEvent) => void;
+ onDrop: (event: React.DragEvent) => void;
+ };
+ /** The edge the insertion line is drawn on for this row in this list, if any. */
+ lineEdge: (scope: string, id: string) => DropEdge | undefined;
+ /** Whether the whole target under this key is lit. */
+ ringLit: (key: string) => boolean;
+}
+
+export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
+ const [drag, setDrag] = useState<SidebarDragItem | null>(null);
+ const [plan, setPlan] = useState<SidebarDropPlan | null>(null);
+ const planRef = useRef<{ key: string; plan: SidebarDropPlan | null }>({
+ key: "",
+ plan: null,
+ });
+ // Handlers are made once and read the latest options at event time.
+ const optionsRef = useRef(options);
+ useEffect(() => {
+ optionsRef.current = options;
+ });
+ const spring = useRef<{ key: string; timer: number } | null>(null);
+
+ const cancelSpring = useCallback(() => {
+ if (spring.current) {
+ window.clearTimeout(spring.current.timer);
+ spring.current = null;
+ }
+ }, []);
+
+ const showPlan = useCallback((next: SidebarDropPlan | null) => {
+ const key = planKey(next);
+ if (planRef.current.key === key) return;
+ planRef.current = { key, plan: next };
+ setPlan(next);
+ }, []);
+
+ const clear = useCallback(() => {
+ setSidebarDragSource(null);
+ cancelSpring();
+ setDrag(null);
+ showPlan(null);
+ }, [cancelSpring, showPlan]);
+
+ // One listener per drag: moves the hint, and clears the cue when nothing answered the
+ // dragover. `dragleave` fires for every child crossed, so it cannot be trusted for that.
+ useEffect(() => {
+ if (!drag) return;
+ const onDragOver = (event: DragEvent) => {
+ const hint = optionsRef.current.hintRef?.current;
+ if (hint) {
+ hint.style.transform = `translate(${event.clientX + 14}px, ${event.clientY + 18}px)`;
+ }
+ if (lastHandledEvent !== event) {
+ cancelSpring();
+ showPlan(null);
+ }
+ };
+ // A drop that unmounts the lifted row loses its dragend, so drop ends the gesture too.
+ const onEnd = () => clear();
+ document.addEventListener("dragover", onDragOver);
+ document.addEventListener("dragend", onEnd);
+ document.addEventListener("drop", onEnd);
+ return () => {
+ document.removeEventListener("dragover", onDragOver);
+ document.removeEventListener("dragend", onEnd);
+ document.removeEventListener("drop", onEnd);
+ };
+ }, [drag, cancelSpring, clear, showPlan]);
+
+ useEffect(() => cancelSpring, [cancelSpring]);
+
+ const dragHandleProps = useCallback(
+ (item: SidebarDragItem) => ({
+ draggable: true as const,
+ onDragStart: (event: React.DragEvent) => {
+ // Firefox needs a payload to drag at all.
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("text/plain", item.id);
+ event.stopPropagation();
+ setSidebarDragSource(item);
+ setDrag(item);
+ },
+ onDragEnd: clear,
+ }),
+ [clear],
+ );
+
+ const dropZoneProps = useCallback(
+ (zone: SidebarDropZone, zoneOptions?: { closed?: boolean }) => {
+ const springKey = zone.folderId
+ ? `folder:${zone.folderId}`
+ : `section:${zone.section}`;
+ return {
+ onDragOver: (event: React.DragEvent) => {
+ const dragged = sidebarDragSource();
+ if (!dragged || lastHandledEvent === event.nativeEvent) return;
+ const next = planSidebarDrop(
+ dragged,
+ zone,
+ dropEdgeAt(event.currentTarget.getBoundingClientRect(), event.clientY),
+ optionsRef.current.context(),
+ );
+ // No answer here lets the zone around it answer instead.
+ if (!next) return;
+ event.preventDefault();
+ lastHandledEvent = event.nativeEvent;
+ event.dataTransfer.dropEffect = "move";
+ if (next === STAY) {
+ // Already here: nothing to paint, and nothing for the outer zones to add.
+ cancelSpring();
+ showPlan(null);
+ return;
+ }
+ showPlan(next);
+ if (zoneOptions?.closed && optionsRef.current.springOpen) {
+ if (spring.current?.key !== springKey) {
+ cancelSpring();
+ spring.current = {
+ key: springKey,
+ timer: window.setTimeout(() => {
+ spring.current = null;
+ optionsRef.current.onSpringOpen?.(zone);
+ }, SPRING_OPEN_DELAY_MS),
+ };
+ }
+ } else if (spring.current?.key !== springKey) {
+ cancelSpring();
+ }
+ },
+ onDrop: (event: React.DragEvent) => {
+ const dragged = sidebarDragSource();
+ if (!dragged || lastHandledEvent === event.nativeEvent) return;
+ const next = planSidebarDrop(
+ dragged,
+ zone,
+ dropEdgeAt(event.currentTarget.getBoundingClientRect(), event.clientY),
+ optionsRef.current.context(),
+ );
+ if (!next) return;
+ event.preventDefault();
+ lastHandledEvent = event.nativeEvent;
+ clear();
+ if (next !== STAY) optionsRef.current.onDrop(next, dragged);
+ },
+ };
+ },
+ [cancelSpring, clear, showPlan],
+ );
+
+ const lineEdge = useCallback(
+ (scope: string, id: string): DropEdge | undefined => {
+ if (!plan || !("line" in plan.cue)) return undefined;
+ return plan.cue.line.rowKey === rowKey(scope, id)
+ ? plan.cue.line.edge
+ : undefined;
+ },
+ [plan],
+ );
+
+ const ringLit = useCallback(
+ (key: string): boolean =>
+ Boolean(plan && "ring" in plan.cue && plan.cue.ring === key),
+ [plan],
+ );
+
+ return {
+ drag,
+ plan,
+ dragHandleProps,
+ dropZoneProps,
+ lineEdge,
+ ringLit,
+ };
+}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 71edac18717..215f66ed23e 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -97,19 +97,53 @@ export {
useChatNavigationStore,
visibleChatItems,
} from "./stores/chat-navigation-store";
+export {
+ setSidebarDragSource,
+ sidebarDragSource,
+ type SidebarDragSource,
+ type SidebarRowKind,
+} from "./stores/sidebar-drag-source";
+export {
+ clearReasoningRound,
+ setReasoningRoundOpen,
+ useReasoningRoundStore,
+ type ReasoningRoundState,
+} from "./stores/reasoning-round-store";
+export {
+ folderRingKey,
+ planKey,
+ planSidebarDrop,
+ rowKey,
+ sectionRingKey,
+ STAY,
+ type DropEdge,
+ type SidebarDragItem,
+ type SidebarDropAction,
+ type SidebarDropContext,
+ type SidebarDropCue,
+ type SidebarDropEffects,
+ type SidebarDropOutcome,
+ type SidebarDropPlace,
+ type SidebarDropPlan,
+ type SidebarDropZone,
+ type SidebarSection,
+} from "./lib/sidebar-drag";
+export { useSidebarDrag, SPRING_OPEN_DELAY_MS } from "./hooks/use-sidebar-drag";
export { usePinnedChatsStore } from "./stores/pinned-chats-store";
export { usePinnedProjectsStore } from "./stores/pinned-projects-store";
export {
applyManualOrder,
- dropEdgeFor,
+ dropEdgeAt,
+ folderDropTarget,
+ insertIdAt,
moveIdBy,
+ placeIdAt,
showsInRecents,
PINNED_ORDER_SCOPE,
PINNED_PROJECT_ORDER_SCOPE,
PROJECT_ORDER_SCOPE,
projectOrderScope,
RECENTS_ORDER_SCOPE,
- reorderIds,
SIDEBAR_ORGANIZATION_STORAGE_KEY,
useSidebarOrganizationStore,
} from "./stores/sidebar-organization-store";
diff --git a/studio/frontend/src/features/chat/lib/sidebar-drag.ts b/studio/frontend/src/features/chat/lib/sidebar-drag.ts
new file mode 100644
index 00000000000..f7de336b23e
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/sidebar-drag.ts
@@ -0,0 +1,457 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Decides what a sidebar drop does. Pure: no DOM, no React, so the hover cue, the hint and the
+// drop itself all read the same answer.
+
+import {
+ dropEdgeAt,
+ insertIdAt,
+ PINNED_ORDER_SCOPE,
+ placeIdAt,
+ PROJECT_ORDER_SCOPE,
+ projectOrderScope,
+ RECENTS_ORDER_SCOPE,
+ type SidebarChatSort,
+ type SidebarOrganizeBy,
+} from "../stores/sidebar-organization-store.ts";
+
+export type SidebarRowKind = "chat" | "project";
+export type SidebarSection = "pinned" | "projects" | "recents";
+export type DropEdge = "top" | "bottom";
+
+/** The row being carried. */
+export interface SidebarDragItem {
+ kind: SidebarRowKind;
+ id: string;
+ /** Section it was picked up from. */
+ section: SidebarSection;
+ /** Order scope of the list it was picked up from. */
+ scope: string;
+ /** For a chat, the folder it is filed in. Null outside every folder, and for a folder. */
+ projectId: string | null;
+}
+
+/** A spot a row can be dropped on: a row, a folder block, a section body or a section header. */
+export interface SidebarDropZone {
+ section: SidebarSection;
+ /** The row under the pointer, if any, with the scope it is drawn in. */
+ row?: { id: string; kind: SidebarRowKind; scope: string };
+ /** The folder this spot belongs to: its row, a chat under it, or its empty line. */
+ folderId?: string;
+ /** For a chat under a folder: its place in the folder's block. */
+ block?: { index: number; count: number };
+ /** The last row drawn in that folder's block, where a line landing below the block goes. */
+ blockEnd?: { scope: string; id: string };
+ /** The section header. It stands for the top of its first row (given as `row`), so the gap
+ * above the first row is not dead space, and takes a drop while the section is collapsed. */
+ header?: boolean;
+}
+
+/** The sidebar as it stands, as far as a drop needs to know. */
+export interface SidebarDropContext {
+ organizeBy: SidebarOrganizeBy;
+ chatSort: SidebarChatSort;
+ pinnedSort: SidebarChatSort;
+ pinnedChatIds: ReadonlySet<string>;
+ pinnedProjectIds: ReadonlySet<string>;
+ /** Row ids per list, in drawn order. Pinned is one list of folders and chats. */
+ orders: {
+ pinned: string[];
+ projects: string[];
+ recents: string[];
+ projectChats: (projectId: string) => string[];
+ };
+ /** Whether a reorder in a Priority or Last updated list is taken (switching it to Manual)
+ * or refused. */
+ reorderSwitchesSort: boolean;
+}
+
+/** What the drop does, for the hint. */
+export type SidebarDropAction =
+ | { kind: "reorder" }
+ | { kind: "pin" }
+ | { kind: "unpin" }
+ | { kind: "move"; projectId: string | null };
+
+/** What to paint: a line on one edge of a row, or a ring around a whole target. Row keys are
+ * `scope:id`, since one chat can be drawn in two lists. */
+export type SidebarDropCue =
+ | { line: { rowKey: string; edge: DropEdge } }
+ | { ring: string };
+
+/** Where a chat from another list lands: its slot against a row of that list. Kept beside the
+ * order snapshot, so a move that finishes after the list was reordered can re-aim the slot
+ * instead of writing the snapshot over the newer order. */
+export interface SidebarDropPlace {
+ id: string;
+ targetId: string;
+ edge: DropEdge;
+}
+
+/** Everything the drop changes. */
+export interface SidebarDropEffects {
+ orders: Array<{ scope: string; ids: string[]; place?: SidebarDropPlace }>;
+ pinChat?: string;
+ unpinChat?: string;
+ pinProject?: string;
+ unpinProject?: string;
+ moveChat?: { chatId: string; projectId: string | null };
+ /** The list to switch to Manual, or its own rule undoes the drop. */
+ switchSort?: "chats" | "pinned";
+}
+
+export interface SidebarDropPlan {
+ action: SidebarDropAction;
+ cue: SidebarDropCue;
+ effects: SidebarDropEffects;
+}
+
+/** The row is already in the slot under the pointer: its own row, or the edge it sits on.
+ * Nothing is painted and a drop does nothing, but the spot still claims the drag, so the
+ * section around it does not answer with its last slot instead. */
+export const STAY = "stay";
+export type SidebarDropOutcome = SidebarDropPlan | typeof STAY | null;
+
+export const rowKey = (scope: string, id: string): string => `${scope}:${id}`;
+export const sectionRingKey = (section: SidebarSection): string =>
+ `section:${section}`;
+export const folderRingKey = (projectId: string): string =>
+ `folder:${projectId}`;
+
+const line = (scope: string, id: string, edge: DropEdge): SidebarDropCue => ({
+ line: { rowKey: rowKey(scope, id), edge },
+});
+const ring = (key: string): SidebarDropCue => ({ ring: key });
+
+export { dropEdgeAt };
+
+/** The plan for dropping `drag` on `zone`, STAY when the row is already there, or null when
+ * this spot has no answer and the zone around it may. */
+export function planSidebarDrop(
+ drag: SidebarDragItem,
+ zone: SidebarDropZone,
+ edge: DropEdge,
+ ctx: SidebarDropContext,
+): SidebarDropOutcome {
+ if (zone.header) {
+ // Pinned holds both kinds in one order; the other sections hold one each.
+ const first =
+ zone.row && (zone.section === "pinned" || zone.row.kind === drag.kind)
+ ? zone.row
+ : undefined;
+ zone = {
+ section: zone.section,
+ header: true,
+ row: first,
+ folderId: first?.kind === "project" ? first.id : undefined,
+ };
+ edge = "top";
+ }
+ if (zone.section === "pinned") return planPinnedDrop(drag, zone, edge, ctx);
+ return drag.kind === "project"
+ ? planFolderDrop(drag, zone, edge, ctx)
+ : planChatDrop(drag, zone, edge, ctx);
+}
+
+/** The line for landing against a folder: above its row, or below the last row of its block. */
+function folderLine(
+ scope: string,
+ folderId: string,
+ edge: DropEdge,
+ zone: SidebarDropZone,
+): SidebarDropCue {
+ if (edge === "bottom" && zone.blockEnd) {
+ return line(zone.blockEnd.scope, zone.blockEnd.id, "bottom");
+ }
+ return line(scope, folderId, edge);
+}
+
+// Pinned is one list: folders and chats in the order they were dropped into. A row of either
+// kind lands in the slot the line shows. A chat still files into a pinned folder by landing on
+// that folder's chats, or on the lower half of its row.
+function planPinnedDrop(
+ drag: SidebarDragItem,
+ zone: SidebarDropZone,
+ edge: DropEdge,
+ ctx: SidebarDropContext,
+): SidebarDropOutcome {
+ if (zone.folderId === drag.id) return STAY;
+ if (
+ drag.kind === "chat" &&
+ zone.folderId &&
+ (zone.row?.kind !== "project" || edge === "bottom")
+ ) {
+ return planChatDrop(drag, zone, edge, ctx);
+ }
+ const ids = ctx.orders.pinned;
+ const inList =
+ drag.kind === "project"
+ ? ctx.pinnedProjectIds.has(drag.id)
+ : ctx.pinnedChatIds.has(drag.id);
+ let target: { id: string; edge: DropEdge } | null = null;
+ if (zone.row) {
+ if (zone.folderId && zone.row.kind === "chat" && zone.block) {
+ // A folder over another folder's chats aims at that folder; the block's middle decides.
+ target = { id: zone.folderId, edge: blockEdge(zone.block, edge) };
+ } else {
+ target = { id: zone.row.id, edge };
+ }
+ } else if (zone.folderId) {
+ // A folder block's own rows (Show more, or an empty folder) are its tail: below it.
+ target = { id: zone.folderId, edge: "bottom" };
+ } else if (ids.length > 0) {
+ // The section's own space: last.
+ target = { id: ids[ids.length - 1], edge: "bottom" };
+ }
+ if (!target) return null;
+ if (target.id === drag.id) return STAY;
+ const resorts = ctx.pinnedSort !== "manual";
+ if (inList && resorts && !ctx.reorderSwitchesSort) return null;
+ const next = inList
+ ? insertIdAt(ids, drag.id, target.id, target.edge)
+ : placeIdAt(ids, drag.id, target.id, target.edge);
+ if (next === ids) return STAY;
+ const cue =
+ zone.folderId && target.id === zone.folderId
+ ? folderLine(PINNED_ORDER_SCOPE, target.id, target.edge, zone)
+ : line(PINNED_ORDER_SCOPE, target.id, target.edge);
+ const effects: SidebarDropEffects = {
+ orders: [{ scope: PINNED_ORDER_SCOPE, ids: next }],
+ switchSort: resorts ? "pinned" : undefined,
+ };
+ if (inList) return { action: { kind: "reorder" }, cue, effects };
+ if (drag.kind === "project") effects.pinProject = drag.id;
+ else effects.pinChat = drag.id;
+ return { action: { kind: "pin" }, cue, effects };
+}
+
+// A folder over Projects: reorders among its folders, or comes back out of Pinned. A folder's
+// block (its row plus its chats) is one target, aimed at the folder.
+function planFolderDrop(
+ drag: SidebarDragItem,
+ zone: SidebarDropZone,
+ edge: DropEdge,
+ ctx: SidebarDropContext,
+): SidebarDropOutcome {
+ if (zone.section === "recents") return null;
+ if (zone.folderId === drag.id) return STAY;
+ const ids = ctx.orders.projects;
+ let target: { id: string; edge: DropEdge } | null = null;
+ if (zone.folderId) {
+ target =
+ zone.block && zone.row?.kind === "chat"
+ ? { id: zone.folderId, edge: blockEdge(zone.block, edge) }
+ : { id: zone.folderId, edge };
+ }
+ if (!ctx.pinnedProjectIds.has(drag.id)) {
+ // Same list: only a folder is a slot to land against.
+ if (!target) return null;
+ const next = insertIdAt(ids, drag.id, target.id, target.edge);
+ if (next === ids) return STAY;
+ return {
+ action: { kind: "reorder" },
+ cue: folderLine(PROJECT_ORDER_SCOPE, target.id, target.edge, zone),
+ effects: { orders: [{ scope: PROJECT_ORDER_SCOPE, ids: next }] },
+ };
+ }
+ // Out of Pinned: unpinned, landing against a folder or last.
+ const next = placeIdAt(ids, drag.id, target?.id ?? null, target?.edge ?? "bottom");
+ return {
+ action: { kind: "unpin" },
+ cue: target
+ ? folderLine(PROJECT_ORDER_SCOPE, target.id, target.edge, zone)
+ : ring(sectionRingKey("projects")),
+ effects: {
+ orders: [{ scope: PROJECT_ORDER_SCOPE, ids: next }],
+ unpinProject: drag.id,
+ },
+ };
+}
+
+/** Which end of a folder the pointer aims at from inside its block: the line flips once, at
+ * the block's middle. */
+function blockEdge(block: { index: number; count: number }, edge: DropEdge): DropEdge {
+ const at = block.index + (edge === "bottom" ? 1 : 0);
+ return at * 2 >= block.count ? "bottom" : "top";
+}
+
+function planChatDrop(
+ drag: SidebarDragItem,
+ zone: SidebarDropZone,
+ edge: DropEdge,
+ ctx: SidebarDropContext,
+): SidebarDropOutcome {
+ const pinned = ctx.pinnedChatIds.has(drag.id);
+ // Picked up from the Pinned list itself, not from inside a pinned folder.
+ const fromPinnedList = drag.scope === PINNED_ORDER_SCOPE;
+
+ if (zone.folderId) {
+ const folderId = zone.folderId;
+ const sameFolder = drag.projectId === folderId;
+ if (fromPinnedList) {
+ // A pinned folder keeps the pin; a folder under Projects takes it away.
+ if (zone.section === "pinned") {
+ return sameFolder ? STAY : moveChat(drag, zone, edge, ctx, folderId, false);
+ }
+ if (!sameFolder) return moveChat(drag, zone, edge, ctx, folderId, true);
+ const landing = landingIn(
+ projectOrderScope(folderId),
+ ctx.orders.projectChats(folderId),
+ drag.id,
+ zone,
+ edge,
+ ctx.chatSort,
+ );
+ return {
+ action: { kind: "unpin" },
+ cue: landing?.cue ?? ring(folderRingKey(folderId)),
+ effects: {
+ orders: landing ? [landing.order] : [],
+ unpinChat: drag.id,
+ },
+ };
+ }
+ if (!sameFolder) return moveChat(drag, zone, edge, ctx, folderId, false);
+ // Its own folder's row: already filed here.
+ if (zone.row?.kind !== "chat") return STAY;
+ return reorder(
+ drag,
+ projectOrderScope(folderId),
+ ctx.orders.projectChats(folderId),
+ zone.row.id,
+ edge,
+ "chats",
+ ctx,
+ );
+ }
+
+ if (zone.section === "recents") {
+ // Recents holds chats that are neither pinned nor filed, so landing here takes both away.
+ // With folders off every chat is a Recents row, and only the pin goes.
+ const filed = drag.projectId !== null && ctx.organizeBy === "project";
+ if (pinned || filed) {
+ const landing = landingIn(
+ RECENTS_ORDER_SCOPE,
+ ctx.orders.recents,
+ drag.id,
+ zone,
+ edge,
+ ctx.chatSort,
+ );
+ return {
+ action: filed ? { kind: "move", projectId: null } : { kind: "unpin" },
+ cue: landing?.cue ?? ring(sectionRingKey("recents")),
+ effects: {
+ orders: landing ? [landing.order] : [],
+ unpinChat: pinned ? drag.id : undefined,
+ moveChat: filed ? { chatId: drag.id, projectId: null } : undefined,
+ },
+ };
+ }
+ if (zone.row?.kind !== "chat") return null;
+ return reorder(
+ drag,
+ RECENTS_ORDER_SCOPE,
+ ctx.orders.recents,
+ zone.row.id,
+ edge,
+ "chats",
+ ctx,
+ );
+ }
+
+ // Projects outside any folder has nothing to file a chat into.
+ return null;
+}
+
+/** Files a chat into `projectId`, in a slot when the folder is on Manual order. */
+function moveChat(
+ drag: SidebarDragItem,
+ zone: SidebarDropZone,
+ edge: DropEdge,
+ ctx: SidebarDropContext,
+ projectId: string,
+ unpin: boolean,
+): SidebarDropPlan {
+ const landing = landingIn(
+ projectOrderScope(projectId),
+ ctx.orders.projectChats(projectId),
+ drag.id,
+ zone,
+ edge,
+ ctx.chatSort,
+ );
+ return {
+ action: { kind: "move", projectId },
+ cue: landing?.cue ?? ring(folderRingKey(projectId)),
+ effects: {
+ orders: landing ? [landing.order] : [],
+ moveChat: { chatId: drag.id, projectId },
+ unpinChat: unpin ? drag.id : undefined,
+ },
+ };
+}
+
+/** Where a chat from another list lands here. Only a list on Manual order has slots; the
+ * caller lights the whole target otherwise. */
+function landingIn(
+ scope: string,
+ ids: string[],
+ chatId: string,
+ zone: SidebarDropZone,
+ edge: DropEdge,
+ sort: SidebarChatSort,
+): { cue: SidebarDropCue; order: SidebarDropEffects["orders"][number] } | null {
+ if (sort !== "manual" || zone.row?.kind !== "chat" || zone.row.scope !== scope) {
+ return null;
+ }
+ if (zone.row.id === chatId) return null;
+ return {
+ cue: line(scope, zone.row.id, edge),
+ order: {
+ scope,
+ ids: placeIdAt(ids, chatId, zone.row.id, edge),
+ place: { id: chatId, targetId: zone.row.id, edge },
+ },
+ };
+}
+
+/** Reorders a chat within its list. A sorted list switches to Manual, or refuses when the
+ * user turned that off. */
+function reorder(
+ drag: SidebarDragItem,
+ scope: string,
+ ids: string[],
+ targetId: string,
+ edge: DropEdge,
+ sortKey: "chats" | "pinned",
+ ctx: SidebarDropContext,
+): SidebarDropOutcome {
+ const sort = sortKey === "pinned" ? ctx.pinnedSort : ctx.chatSort;
+ if (sort !== "manual" && !ctx.reorderSwitchesSort) return null;
+ const next = insertIdAt(ids, drag.id, targetId, edge);
+ if (next === ids) return STAY;
+ return {
+ action: { kind: "reorder" },
+ cue: line(scope, targetId, edge),
+ effects: {
+ orders: [{ scope, ids: next }],
+ switchSort: sort === "manual" ? undefined : sortKey,
+ },
+ };
+}
+
+/** Changes exactly when the painted state does, so equal plans skip a re-render. */
+export function planKey(plan: SidebarDropPlan | null): string {
+ if (!plan) return "";
+ const cue =
+ "line" in plan.cue
+ ? `line:${plan.cue.line.rowKey}:${plan.cue.line.edge}`
+ : `ring:${plan.cue.ring}`;
+ const action =
+ plan.action.kind === "move"
+ ? `move:${plan.action.projectId ?? ""}`
+ : plan.action.kind;
+ return `${action}|${cue}`;
+}
diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsx
index bd9bd955465..f5dc73204aa 100644
--- a/studio/frontend/src/features/chat/projects-page.tsx
+++ b/studio/frontend/src/features/chat/projects-page.tsx
@@ -32,6 +32,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { isTauri } from "@/lib/api-base";
+import { cn } from "@/lib/utils";
import { isDownloadCancelled, pickNativeChatImport } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import {
@@ -57,9 +58,10 @@ import {
Upload01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { MoreHorizontalIcon } from "lucide-react";
+import { ChevronDownIcon, MoreHorizontalIcon } from "lucide-react";
+import { MessageCircleIcon } from "@/lib/hugeicons-derived";
import { useNavigate } from "@tanstack/react-router";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
COMBINED_EXPORT_FORMATS_LIST,
exportProjectConversations,
@@ -77,11 +79,15 @@ import {
import {
listStoredChatThreads,
} from "./utils/chat-history-storage";
+import { CHAT_HISTORY_UPDATED_EVENT } from "./api/chat-api";
+import { groupThreads, type SidebarItem } from "./hooks/use-chat-sidebar-items";
type SortMode = "activity" | "name";
// Reveal this many more projects each time the user scrolls near the bottom.
const PROJECTS_PAGE_STEP = 12;
+// A streaming chat fires the history event per chunk; one reload per quiet window is enough.
+const PROJECT_CHATS_REFRESH_DEBOUNCE_MS = 300;
// Visible count before the fit-to-height measurement runs.
const PROJECTS_INITIAL_FALLBACK = 8;
// Approx list row height in px, used to estimate how many rows fit the page.
@@ -146,6 +152,100 @@ export function ProjectsPage() {
const [importing, setImporting] = useState(false);
// null = Recents
const [importTargetId, setImportTargetId] = useState<string | null>(null);
+ // Rows open their own chats in place, loaded the first time they are opened.
+ const [openProjectIds, setOpenProjectIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ // Grouped as the sidebar groups them, so a comparison is one row that opens as one.
+ // "error" is a failed first load: the row says so and offers a retry, and reopening it loads
+ // again rather than trusting the entry.
+ const [projectChats, setProjectChats] = useState<
+ Record<string, SidebarItem[] | "loading" | "error">
+ >({});
+ // Rows kept on screen after a reload failed: they may miss a chat or show one that is gone,
+ // so the row says so, and its next open asks again.
+ const [staleProjectIds, setStaleProjectIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const setStale = useCallback((projectId: string, stale: boolean) => {
+ setStaleProjectIds((prev) => {
+ if (prev.has(projectId) === stale) return prev;
+ const next = new Set(prev);
+ if (stale) next.add(projectId);
+ else next.delete(projectId);
+ return next;
+ });
+ }, []);
+
+ // One sequence per project: a response that a newer request overtook is dropped, so a chat
+ // moved or deleted mid-flight cannot come back.
+ const loadSeqRef = useRef(new Map<string, number>());
+ const loadProjectChats = useCallback((projectId: string, silent = false) => {
+ const seq = (loadSeqRef.current.get(projectId) ?? 0) + 1;
+ loadSeqRef.current.set(projectId, seq);
+ // A reload keeps the rows on screen; only a first load shows the skeleton.
+ if (!silent) {
+ setProjectChats((prev) => ({ ...prev, [projectId]: "loading" }));
+ }
+ void listStoredChatThreads({ projectId, includeArchived: false })
+ .then((threads) => {
+ if (loadSeqRef.current.get(projectId) !== seq) return;
+ setStale(projectId, false);
+ setProjectChats((prev) => ({
+ ...prev,
+ [projectId]: groupThreads(threads).sort(
+ (a, b) => b.updatedAt - a.updatedAt,
+ ),
+ }));
+ })
+ .catch(() => {
+ if (loadSeqRef.current.get(projectId) !== seq) return;
+ // A failed reload keeps rows already showing, marked stale; anything else becomes a
+ // retryable error, including a first load this reload overtook while it was still
+ // pending, and a folder loaded as empty, which the reload may have been about to fill.
+ setProjectChats((prev) => {
+ const rows = prev[projectId];
+ if (silent && Array.isArray(rows) && rows.length > 0) {
+ setStale(projectId, true);
+ return prev;
+ }
+ return { ...prev, [projectId]: "error" };
+ });
+ });
+ }, [setStale]);
+
+ // A loaded list goes stale when chats are imported, moved or deleted. Streaming fires the
+ // event per chunk, so the reload is debounced: open rows reload in place, the rest load
+ // again on their next open.
+ const openProjectIdsRef = useRef(openProjectIds);
+ useEffect(() => {
+ openProjectIdsRef.current = openProjectIds;
+ }, [openProjectIds]);
+ useEffect(() => {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const refresh = () => {
+ if (timer !== null) clearTimeout(timer);
+ timer = setTimeout(() => {
+ timer = null;
+ const open = openProjectIdsRef.current;
+ // A closed project's load may still be in flight; its answer must not refill the cache.
+ for (const [id, seq] of loadSeqRef.current) {
+ if (!open.has(id)) loadSeqRef.current.set(id, seq + 1);
+ }
+ setProjectChats((prev) => {
+ const kept: typeof prev = {};
+ for (const id of open) if (prev[id] !== undefined) kept[id] = prev[id];
+ return kept;
+ });
+ for (const id of open) loadProjectChats(id, true);
+ }, PROJECT_CHATS_REFRESH_DEBOUNCE_MS);
+ };
+ window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, refresh);
+ return () => {
+ if (timer !== null) clearTimeout(timer);
+ window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, refresh);
+ };
+ }, [loadProjectChats]);
async function handleImport(source: ImportSource, projectId: string | null) {
// Counts up while it runs: a large export takes minutes of writes.
@@ -313,6 +413,37 @@ export function ProjectsPage() {
// (IntersectionObserver does not re-fire on a steady intersection).
}, [hasMore, visibleCount]);
+ function toggleProjectChats(projectId: string) {
+ const opening = !openProjectIds.has(projectId);
+ setOpenProjectIds((prev) => {
+ const next = new Set(prev);
+ if (opening) next.add(projectId);
+ else next.delete(projectId);
+ return next;
+ });
+ // Only an open asks: a close after a failed load must not start a request the reopen
+ // then waits on.
+ if (!opening) return;
+ const cached = projectChats[projectId];
+ const loaded = cached !== undefined && cached !== "error";
+ if (loaded && !staleProjectIds.has(projectId)) return;
+ // Stale rows stay on screen while the retry runs.
+ loadProjectChats(projectId, loaded);
+ }
+
+ function openChat(item: SidebarItem, projectId: string) {
+ const runtime = useChatRuntimeStore.getState();
+ runtime.setActiveProjectId(projectId);
+ // A comparison restores from its pair id; a pane opened as a thread is half of it.
+ if (item.type === "compare") {
+ runtime.setActiveThreadId(null);
+ navigate({ to: "/chat", search: { compare: item.id, project: projectId } });
+ return;
+ }
+ runtime.setActiveThreadId(item.id);
+ navigate({ to: "/chat", search: { thread: item.id, project: projectId } });
+ }
+
function openProject(projectId: string) {
const runtime = useChatRuntimeStore.getState();
runtime.setActiveThreadId(null);
@@ -575,6 +706,8 @@ export function ProjectsPage() {
<div ref={listRef} data-tour="projects-list">
{visibleProjects.map((project) => {
const pinned = pinnedProjectIdSet.has(project.id);
+ const chatsOpen = openProjectIds.has(project.id);
+ const chats = projectChats[project.id];
return (
<div key={`wrap-${project.id}`}>
<input
@@ -598,6 +731,8 @@ export function ProjectsPage() {
tabIndex={0}
onClick={() => openProject(project.id)}
onKeyDown={(e) => {
+ // A key pressed on a control inside the row is that control's.
+ if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
openProject(project.id);
@@ -615,18 +750,54 @@ export function ProjectsPage() {
<span className="min-w-0 flex-1 truncate text-ui-15 font-semibold text-foreground">
{project.name}
</span>
+ {/* Opens the project's chats in place, without leaving the list. */}
+ <button
+ type="button"
+ aria-label={chatsOpen ? "Hide chats" : "Show chats"}
+ aria-expanded={chatsOpen}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleProjectChats(project.id);
+ }}
+ className={cn(
+ "flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition hover:bg-black/5 hover:text-foreground focus-visible:opacity-100 group-hover/project-row:opacity-100 dark:hover:bg-white/10",
+ chatsOpen ? "opacity-100" : "opacity-0",
+ )}
+ >
+ <ChevronDownIcon
+ strokeWidth={1.75}
+ className={cn(
+ "size-4 transition-transform",
+ !chatsOpen && "-rotate-90",
+ )}
+ />
+ </button>
<span className="w-40 shrink-0 text-sm text-muted-foreground">
{formatModified(project.updatedAt)}
</span>
+ {/* Pinning is one click here, as it is on a sidebar row. */}
+ <button
+ type="button"
+ aria-label={pinned ? "Unpin project" : "Pin project"}
+ onClick={(e) => {
+ e.stopPropagation();
+ togglePinProject(project.id);
+ }}
+ className={cn(
+ "flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition hover:bg-black/5 hover:text-foreground focus-visible:opacity-100 group-hover/project-row:opacity-100 dark:hover:bg-white/10",
+ pinned ? "opacity-100" : "opacity-0",
+ )}
+ >
+ <HugeiconsIcon
+ icon={pinned ? PinOffIcon : PinIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
<div className="relative flex w-8 shrink-0 items-center justify-end">
{/* Pin fades out and the kebab fades in on hover, focus, or
menu open. Absolute + opacity gating keeps them from
overlapping while leaving the button keyboard-focusable. */}
- {pinned && (
- <span className="text-muted-foreground transition-opacity group-hover/project-row:opacity-0 group-focus-within/project-row:opacity-0 group-has-[[data-state=open]]/project-row:opacity-0">
- <HugeiconsIcon icon={PinIcon} strokeWidth={1.75} className="size-4" />
- </span>
- )}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
@@ -654,7 +825,7 @@ export function ProjectsPage() {
strokeWidth={1.75}
className="size-icon"
/>
- <span>{pinned ? "Unpin project" : "Pin project"}</span>
+ <span>{pinned ? "Unpin" : "Pin"}</span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => {
@@ -705,6 +876,50 @@ export function ProjectsPage() {
</DropdownMenu>
</div>
</div>
+ {chatsOpen && (
+ <div className="mb-2 flex flex-col gap-0.5 pl-[76px] pr-5">
+ {chats === undefined || chats === "loading" ? (
+ <Skeleton className="h-6 w-48 rounded-[8px]" />
+ ) : chats === "error" ? (
+ <button
+ type="button"
+ onClick={() => loadProjectChats(project.id)}
+ className="cursor-pointer self-start py-1 text-left text-sm text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
+ >
+ Could not load chats. Retry
+ </button>
+ ) : chats.length === 0 ? (
+ <p className="py-1 text-sm text-muted-foreground">No chats</p>
+ ) : (
+ <>
+ {chats.map((chat) => (
+ <button
+ key={chat.id}
+ type="button"
+ onClick={() => openChat(chat, project.id)}
+ className="flex cursor-pointer items-center gap-2 truncate rounded-lg px-2 py-1.5 text-left text-sm text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground dark:hover:bg-white/[0.055]"
+ >
+ <HugeiconsIcon
+ icon={MessageCircleIcon}
+ strokeWidth={1.75}
+ className="size-4 shrink-0"
+ />
+ <span className="truncate">{chat.title}</span>
+ </button>
+ ))}
+ {staleProjectIds.has(project.id) && (
+ <button
+ type="button"
+ onClick={() => loadProjectChats(project.id, true)}
+ className="cursor-pointer self-start py-1 text-left text-sm text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
+ >
+ Could not refresh chats. Retry
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ )}
</div>
);
})}
diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
index 5faea98714c..a13beee4e73 100644
--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
@@ -17,6 +17,7 @@ import {
// the delete confirm dialog. alwaysDeleteChatFiles: on also removes the sandbox folder.
// showModelDisclaimer: off hides the "LLMs can make mistakes" footer. showResponseModel: on shows
// the producing model on responses. collapseThinkingByDefault: on keeps thinking collapsed.
+// foldToolActivityIntoThinking: on hides a round's tool calls until its thinking block is opened.
// pastedTextMinChars: paste length that becomes a .txt attachment; 0 is off.
export interface ChatPreferencesState {
plainTextComposer: boolean;
@@ -39,6 +40,8 @@ export interface ChatPreferencesState {
setCollapseThinkingByDefault: (value: boolean) => void;
collapseToolActivityByDefault: boolean;
setCollapseToolActivityByDefault: (value: boolean) => void;
+ foldToolActivityIntoThinking: boolean;
+ setFoldToolActivityIntoThinking: (value: boolean) => void;
pastedTextMinChars: number;
setPastedTextMinChars: (value: number) => void;
}
@@ -79,6 +82,10 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
collapseToolActivityByDefault: true,
setCollapseToolActivityByDefault: (collapseToolActivityByDefault) =>
set({ collapseToolActivityByDefault }),
+ // Off by default: it hides rows the thread shows today, so it stays opt in.
+ foldToolActivityIntoThinking: false,
+ setFoldToolActivityIntoThinking: (foldToolActivityIntoThinking) =>
+ set({ foldToolActivityIntoThinking }),
pastedTextMinChars: PASTED_TEXT_DEFAULT_MIN_CHARS,
setPastedTextMinChars: (pastedTextMinChars) =>
set({ pastedTextMinChars }),
@@ -97,6 +104,8 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
collapseThinkingByDefault: saved?.collapseThinkingByDefault ?? false,
collapseToolActivityByDefault:
saved?.collapseToolActivityByDefault ?? true,
+ foldToolActivityIntoThinking:
+ saved?.foldToolActivityIntoThinking ?? false,
pastedTextMinChars: normalisePastedTextMinChars(
saved?.pastedTextMinChars,
),
diff --git a/studio/frontend/src/features/chat/stores/reasoning-round-store.ts b/studio/frontend/src/features/chat/stores/reasoning-round-store.ts
new file mode 100644
index 00000000000..4eac9d51035
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/reasoning-round-store.ts
@@ -0,0 +1,42 @@
+// 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";
+
+// Which thinking rounds are open, so the tool calls folded under one can follow it. Session only:
+// it tracks what is on screen now, and a reloaded thread starts from the collapse preference.
+// A round missing here counts as closed, so tools never flash on screen before the block that
+// owns them has published its state.
+export interface ReasoningRoundState {
+ /** Round key (see reasoningRoundKey) -> whether its thinking block is open. */
+ open: Record<string, boolean>;
+ setRoundOpen: (key: string, open: boolean) => void;
+ clearRound: (key: string) => void;
+}
+
+export const useReasoningRoundStore = create<ReasoningRoundState>()((set) => ({
+ open: {},
+ setRoundOpen: (key, open) =>
+ set((state) =>
+ state.open[key] === open
+ ? state
+ : { open: { ...state.open, [key]: open } },
+ ),
+ clearRound: (key) =>
+ set((state) => {
+ if (!(key in state.open)) return state;
+ const open: Record<string, boolean> = {};
+ for (const [id, value] of Object.entries(state.open)) {
+ if (id !== key) open[id] = value;
+ }
+ return { open };
+ }),
+}));
+
+export function setReasoningRoundOpen(key: string, open: boolean): void {
+ useReasoningRoundStore.getState().setRoundOpen(key, open);
+}
+
+export function clearReasoningRound(key: string): void {
+ useReasoningRoundStore.getState().clearRound(key);
+}
diff --git a/studio/frontend/src/features/chat/stores/sidebar-drag-source.ts b/studio/frontend/src/features/chat/stores/sidebar-drag-source.ts
new file mode 100644
index 00000000000..c1ef58b355a
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/sidebar-drag-source.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { SidebarDragItem } from "../lib/sidebar-drag.ts";
+
+export type { SidebarDragItem as SidebarDragSource } from "../lib/sidebar-drag.ts";
+
+// A dragover can fire in the same frame as its dragstart, before React state commits, so the
+// dragged row is held here and read synchronously. State holds a copy for painting only.
+let source: SidebarDragItem | null = null;
+
+export function setSidebarDragSource(next: SidebarDragItem | null): void {
+ source = next;
+}
+
+export function sidebarDragSource(): SidebarDragItem | null {
+ return source;
+}
+export type { SidebarRowKind } from "../lib/sidebar-drag.ts";
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 67a76ff1fea..502746e0b6f 100644
--- a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
+++ b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
@@ -36,26 +36,48 @@ export interface SidebarOrganizationState {
pinnedSort: SidebarChatSort;
/** Scope key -> row ids, in the order the user dragged them into. */
manualOrder: Record<string, string[]>;
+ /** Drag-and-drop preferences: the hint beside the cursor, whether a reorder switches a
+ * sorted list to Manual, and whether folders open under a resting pointer. */
+ dragHints: boolean;
+ reorderSwitchesSort: boolean;
+ dragOpensFolders: boolean;
setOrganizeBy: (value: SidebarOrganizeBy) => void;
setChatSort: (value: SidebarChatSort) => void;
setPinnedSort: (value: SidebarChatSort) => void;
setManualOrder: (scope: string, ids: string[]) => void;
+ setDragHints: (value: boolean) => void;
+ setReorderSwitchesSort: (value: boolean) => void;
+ setDragOpensFolders: (value: boolean) => void;
}
-/** Moves `draggedId` into `targetId`'s slot, keeping the rest in order. Returns `ids` itself
- * when either row is missing, so a stale drop is a no-op. */
-export function reorderIds(
+/** Drops `draggedId` against the `edge` side of `targetId`, keeping the rest in order. The edge
+ * comes from which half of the target row the pointer is over, so the row lands exactly where
+ * the insertion line was drawn. Returns `ids` itself when a row is missing or the drop changes
+ * nothing, so a stale or pointless drop is a no-op the caller can skip persisting. */
+export function insertIdAt(
ids: string[],
draggedId: string,
targetId: string,
+ edge: "top" | "bottom",
): string[] {
if (draggedId === targetId) return ids;
- const from = ids.indexOf(draggedId);
- const to = ids.indexOf(targetId);
- if (from === -1 || to === -1) return ids;
- const next = [...ids];
- next.splice(from, 1);
- next.splice(to, 0, draggedId);
+ if (!ids.includes(draggedId) || !ids.includes(targetId)) return ids;
+ const next = placeIdAt(ids, draggedId, targetId, edge);
+ return next.every((id, index) => id === ids[index]) ? ids : next;
+}
+
+/** The same landing for a row the list does not hold yet, which is what a chat dropped into
+ * Pinned is. An unknown target puts it last, since there is no slot to aim at. */
+export function placeIdAt(
+ ids: string[],
+ id: string,
+ targetId: string | null,
+ edge: "top" | "bottom",
+): string[] {
+ const next = ids.filter((existing) => existing !== id);
+ const at = targetId === null ? -1 : next.indexOf(targetId);
+ if (at === -1) return [...next, id];
+ next.splice(at + (edge === "bottom" ? 1 : 0), 0, id);
return next;
}
@@ -68,20 +90,47 @@ export function showsInRecents(
return organizeBy === "list" || !projectId;
}
-/** Which edge of the target row the drop indicator belongs on, matching where `reorderIds`
- * actually lands the row: after the target when dragging down, before it when dragging up. */
-export function dropEdgeFor(
- ids: string[],
- draggedId: string,
- targetId: string,
+/** Where a folder dragged over another folder's chats lands. A folder's rows are the folder row
+ * and the chats under it, and in Pinned those chats separate one folder from the next: without
+ * this the only target is the folder row itself, with a whole block of rows between two of them
+ * that answer nothing. The block is read as one strip: how far down it the pointer is decides
+ * which end of the folder the drop lands on, so the line flips once, in the middle, rather than
+ * at every row. Returns null when the row belongs to the dragged folder or the drop would move
+ * nothing. */
+export function folderDropTarget(params: {
+ /** The folder being dragged. */
+ draggedId: string;
+ /** The folder order it drags within: Projects' or Pinned's. */
+ folderIds: string[];
+ /** The folder whose block the pointer is over. */
+ folderId: string;
+ /** The hovered chat's place among that folder's chats, and which half of it the pointer is
+ * over: a folder holding one chat has to answer both ends from that row alone. */
+ rowIndex: number;
+ rowCount: number;
+ pointerEdge: "top" | "bottom";
+}): { edge: "top" | "bottom"; next: string[] } | null {
+ const { draggedId, folderIds, folderId, rowIndex, rowCount } = params;
+ if (draggedId === folderId || rowIndex < 0) return null;
+ // How many row-halves down the block the pointer is, against its length.
+ const at = rowIndex + (params.pointerEdge === "bottom" ? 1 : 0);
+ const edge = at * 2 >= rowCount ? "bottom" : ("top" as const);
+ const next = insertIdAt(folderIds, draggedId, folderId, edge);
+ return next === folderIds ? null : { edge, next };
+}
+
+/** Which half of a row the pointer is over, which is the edge the row being dragged will land
+ * on. Read off the row's own box, so the insertion line follows the cursor rather than the
+ * two rows' index order. */
+export function dropEdgeAt(
+ rect: { top: number; height: number },
+ pointerY: number,
): "top" | "bottom" {
- const from = ids.indexOf(draggedId);
- const to = ids.indexOf(targetId);
- return from !== -1 && to !== -1 && from < to ? "bottom" : "top";
+ return pointerY >= rect.top + rect.height / 2 ? "bottom" : "top";
}
-/** Moves a row one slot up or down. The menu path to the same reorder that dragging does, for
- * touch and keyboard, which never see a `dragstart`. */
+/** Moves a row one slot up or down. The keyboard path to the same reorder that dragging does:
+ * a keyboard never sees a `dragstart`, so alt + arrow drives this instead. */
export function moveIdBy(
ids: string[],
id: string,
@@ -120,6 +169,9 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
chatSort: "priority",
pinnedSort: "manual",
manualOrder: {},
+ dragHints: true,
+ reorderSwitchesSort: true,
+ dragOpensFolders: true,
setOrganizeBy: (value) => set({ organizeBy: value }),
setChatSort: (value) => set({ chatSort: value }),
setPinnedSort: (value) => set({ pinnedSort: value }),
@@ -127,6 +179,9 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
set((state) => ({
manualOrder: { ...state.manualOrder, [scope]: ids },
})),
+ setDragHints: (value) => set({ dragHints: value }),
+ setReorderSwitchesSort: (value) => set({ reorderSwitchesSort: value }),
+ setDragOpensFolders: (value) => set({ dragOpensFolders: value }),
}),
{
name: SIDEBAR_ORGANIZATION_STORAGE_KEY,
@@ -156,7 +211,18 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
}
}
}
- return { ...current, organizeBy, chatSort, pinnedSort, manualOrder };
+ const readFlag = (value: unknown, fallback: boolean): boolean =>
+ typeof value === "boolean" ? value : fallback;
+ return {
+ ...current,
+ organizeBy,
+ chatSort,
+ pinnedSort,
+ manualOrder,
+ dragHints: readFlag(saved?.dragHints, true),
+ reorderSwitchesSort: readFlag(saved?.reorderSwitchesSort, true),
+ dragOpensFolders: readFlag(saved?.dragOpensFolders, true),
+ };
},
},
),
diff --git a/studio/frontend/src/features/rag/components/linked-folders-manager.tsx b/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
index 9e8fd817eae..b204e28efee 100644
--- a/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
+++ b/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
@@ -22,7 +22,7 @@ import {
import { Progress } from "@/components/ui/progress";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
-import { FolderSyncIcon } from "@hugeicons/core-free-icons";
+import { FolderAddIcon, FolderSyncIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { MoreHorizontalIcon, RotateCwIcon } from "lucide-react";
import { useState } from "react";
@@ -52,10 +52,14 @@ function jobSummary(job: FolderSyncJob): string {
export function LinkedFoldersManager({
scope,
compact = false,
+ variant = "panel",
onSourcesChanged,
}: {
scope?: LinkedFolderScope;
compact?: boolean;
+ /** "panel" is the settings-style block with its own heading and Link folder button. "card" is
+ * the grouped list a dialog shows: one row per folder, an Add folder row at the foot of it. */
+ variant?: "panel" | "card";
onSourcesChanged?: () => void;
}) {
const manager = useLinkedFolders(scope, onSourcesChanged);
@@ -64,6 +68,216 @@ export function LinkedFoldersManager({
name: string;
} | null>(null);
+ /** Whether the folder has a sync in flight, which is what the row reports while it does. */
+ function runningJob(folderId: string): FolderSyncJob | undefined {
+ const job = manager.jobs[folderId];
+ return job?.status === "pending" || job?.status === "running"
+ ? job
+ : undefined;
+ }
+
+ /** The row's own actions, identical in both layouts: a card row's "×" would have to drop three
+ * of them, and syncing a folder by hand is the reason most people open this list. */
+ function folderMenu(folder: (typeof manager.folders)[number], running: boolean) {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ className="shrink-0 rounded-full"
+ aria-label={`Actions for ${folder.displayName}`}
+ >
+ {running ? (
+ <Spinner className="size-3.5" />
+ ) : (
+ <MoreHorizontalIcon className="size-4" />
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ disabled={running}
+ onSelect={() => void manager.sync(folder.id)}
+ >
+ <HugeiconsIcon icon={FolderSyncIcon} strokeWidth={1.75} className="size-3.5" /> Sync changes
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={running}
+ onSelect={() => void manager.rebuild(folder.id)}
+ >
+ <RotateCwIcon className="size-3.5" /> Rebuild index
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => void manager.remove(folder.id, false)}
+ >
+ Unlink and keep indexed files
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onSelect={() =>
+ setRemoveIndexFolder({
+ id: folder.id,
+ name: folder.displayName,
+ })
+ }
+ >
+ Unlink and remove indexed files
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ }
+
+ /** The confirmation the destructive unlink opens. Mounted by whichever layout rendered. */
+ const removeIndexConfirm = (
+ <AlertDialog
+ open={removeIndexFolder !== null}
+ onOpenChange={(open) => {
+ if (!open) setRemoveIndexFolder(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Unlink folder and remove files?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will unlink &quot;{removeIndexFolder?.name}&quot; and remove all
+ documents it manages from the index. The files on disk will not be
+ changed.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ const folder = removeIndexFolder;
+ setRemoveIndexFolder(null);
+ if (folder) void manager.remove(folder.id, true);
+ }}
+ >
+ Unlink and remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+
+ // One grouped card: the folders, then the row that adds another. A dialog has a name field
+ // above it in the same shape, so the two read as one stack rather than a panel inside a panel.
+ if (variant === "card") {
+ const rowClass =
+ "flex min-w-0 items-center gap-3 px-3.5 py-2.5 border-t border-border/60 first:border-t-0 dark:border-white/[0.08]";
+ return (
+ <section className="flex min-w-0 flex-col gap-2">
+ <div className="overflow-hidden rounded-[16px] border border-border bg-background dark:border-transparent dark:bg-white/[0.06]">
+ {manager.loading && manager.folders.length === 0 ? (
+ <div className={cn(rowClass, "text-ui-13 text-muted-foreground")}>
+ <Spinner className="size-4 shrink-0" />
+ <span>Loading folders…</span>
+ </div>
+ ) : (
+ manager.folders.map((folder) => {
+ const job = manager.jobs[folder.id];
+ const running = runningJob(folder.id) !== undefined;
+ const failed =
+ folder.status === "error" || job?.status === "failed";
+ // A settled row is its name alone, the way a list of folders reads. The detail line
+ // is for the states that need one; what is indexed stays on the row's tooltip.
+ const detail = running
+ ? jobSummary(job as FolderSyncJob)
+ : failed
+ ? (job?.status === "failed" ? job.error : folder.error) ||
+ "Sync failed"
+ : null;
+ return (
+ <div
+ key={folder.id}
+ className={rowClass}
+ title={
+ folder.lastSyncedAt
+ ? `${folder.displayName}: last synced ${new Date(folder.lastSyncedAt).toLocaleString()}`
+ : `${folder.displayName}: ${folder.documentCount ?? 0} indexed documents`
+ }
+ >
+ <HugeiconsIcon
+ icon={FolderSyncIcon}
+ strokeWidth={1.75}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ <div className="min-w-0 flex-1">
+ <span className="block truncate text-sm">
+ {folder.displayName}
+ </span>
+ {detail ? (
+ <p
+ className={cn(
+ "truncate text-ui-11 text-muted-foreground",
+ failed && "text-destructive",
+ )}
+ >
+ {detail}
+ </p>
+ ) : null}
+ {running ? (
+ <Progress
+ value={percent(job?.progress) ?? 0}
+ aria-label={`Sync progress for ${folder.displayName}`}
+ className="mt-1.5 h-1"
+ />
+ ) : null}
+ </div>
+ {folderMenu(folder, running)}
+ </div>
+ );
+ })
+ )}
+ {scope ? (
+ <button
+ type="button"
+ disabled={!manager.desktopSupported || manager.mutating}
+ onClick={() => void manager.link()}
+ // Named for what it does; the title is the tooltip saying why it cannot, which
+ // would otherwise be read out as the row's name.
+ aria-label="Add folder"
+ title={
+ manager.desktopSupported
+ ? "Choose a local folder"
+ : "Requires the managed desktop backend"
+ }
+ className={cn(
+ rowClass,
+ "w-full cursor-pointer py-3 text-left text-sm transition-colors hover:bg-muted/60 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent",
+ )}
+ >
+ {manager.mutating ? (
+ <Spinner className="size-4 shrink-0" />
+ ) : (
+ <HugeiconsIcon
+ icon={FolderAddIcon}
+ strokeWidth={1.75}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ )}
+ <span>Add folder</span>
+ </button>
+ ) : null}
+ </div>
+ {/* Only where it changes what the row above can do: in the browser build there is no
+ native folder picker, and the rows already linked keep syncing regardless. */}
+ {!manager.desktopSupported ? (
+ <p className="px-1 text-ui-11 text-muted-foreground">
+ Linking a folder needs the managed desktop backend. Folders already
+ linked stay synced.
+ </p>
+ ) : null}
+ {removeIndexConfirm}
+ </section>
+ );
+ }
+
return (
<section className={cn("flex min-w-0 flex-col gap-3", compact && "gap-2")}>
<div className="flex items-start justify-between gap-3">
@@ -165,89 +379,13 @@ export function LinkedFoldersManager({
/>
) : null}
</div>
- <DropdownMenu>
- <DropdownMenuTrigger asChild={true}>
- <Button
- type="button"
- size="icon-sm"
- variant="ghost"
- className="shrink-0 rounded-full"
- aria-label={`Actions for ${folder.displayName}`}
- >
- {running ? (
- <Spinner className="size-3.5" />
- ) : (
- <MoreHorizontalIcon className="size-4" />
- )}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- disabled={running}
- onSelect={() => void manager.sync(folder.id)}
- >
- <HugeiconsIcon icon={FolderSyncIcon} strokeWidth={1.75} className="size-3.5" /> Sync changes
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={running}
- onSelect={() => void manager.rebuild(folder.id)}
- >
- <RotateCwIcon className="size-3.5" /> Rebuild index
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={() => void manager.remove(folder.id, false)}
- >
- Unlink and keep indexed files
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- onSelect={() =>
- setRemoveIndexFolder({
- id: folder.id,
- name: folder.displayName,
- })
- }
- >
- Unlink and remove indexed files
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ {folderMenu(folder, running)}
</li>
);
})}
</ul>
)}
- <AlertDialog
- open={removeIndexFolder !== null}
- onOpenChange={(open) => {
- if (!open) setRemoveIndexFolder(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Unlink folder and remove files?</AlertDialogTitle>
- <AlertDialogDescription>
- This will unlink &quot;{removeIndexFolder?.name}&quot; and remove
- all documents it manages from the index. The files on disk will
- not be changed.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- variant="destructive"
- onClick={() => {
- const folder = removeIndexFolder;
- setRemoveIndexFolder(null);
- if (folder) void manager.remove(folder.id, true);
- }}
- >
- Unlink and remove
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ {removeIndexConfirm}
</section>
);
}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 036b0bb84a4..674940db963 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -114,6 +114,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.profile.greetingSloth",
"settings.chat.thinking.collapseByDefault",
"settings.chat.tools.collapseByDefault",
+ "settings.chat.tools.foldIntoThinking",
"settings.chat.artifacts.title",
"settings.chat.artifacts.collapseHtmlBlocks",
"settings.chat.artifacts.allowNetworkAccess",
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index 2abbc2709b0..b9137b5eb3d 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -266,6 +266,12 @@ export function ChatTab() {
const setCollapseToolActivityByDefault = useChatPreferencesStore(
(state) => state.setCollapseToolActivityByDefault,
);
+ const foldToolActivityIntoThinking = useChatPreferencesStore(
+ (state) => state.foldToolActivityIntoThinking,
+ );
+ const setFoldToolActivityIntoThinking = useChatPreferencesStore(
+ (state) => state.setFoldToolActivityIntoThinking,
+ );
const pastedTextMinChars = useChatPreferencesStore(
(state) => state.pastedTextMinChars,
);
@@ -517,6 +523,16 @@ export function ChatTab() {
onCheckedChange={setCollapseToolActivityByDefault}
/>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.chat.tools.foldIntoThinking")}
+ description={t("settings.chat.tools.foldIntoThinkingDescription")}
+ >
+ <Switch
+ aria-label={t("settings.chat.tools.foldIntoThinking")}
+ checked={foldToolActivityIntoThinking}
+ onCheckedChange={setFoldToolActivityIntoThinking}
+ />
+ </SettingsRow>
<SettingsRow
label={t("settings.chat.showResponseModel")}
description={t("settings.chat.showResponseModelDescription")}
diff --git a/studio/frontend/src/hooks/use-mobile.ts b/studio/frontend/src/hooks/use-mobile.ts
index d4236c96dbb..74e352903b4 100644
--- a/studio/frontend/src/hooks/use-mobile.ts
+++ b/studio/frontend/src/hooks/use-mobile.ts
@@ -27,6 +27,26 @@ export function useIsMobile(): boolean {
return useSyncExternalStore(subscribe, getSnapshot, () => false);
}
+// any-pointer, not pointer: a laptop with a touchscreen and a trackpad still has a finger.
+const COARSE_POINTER_QUERY = "(any-pointer: coarse)";
+
+function getCoarseSnapshot(): boolean {
+ if (typeof window === "undefined") return false;
+ return window.matchMedia(COARSE_POINTER_QUERY).matches;
+}
+
+function subscribeCoarse(callback: () => void): () => void {
+ if (typeof window === "undefined") return () => {};
+ const mql = window.matchMedia(COARSE_POINTER_QUERY);
+ mql.addEventListener("change", callback);
+ return () => mql.removeEventListener("change", callback);
+}
+
+/** A touch screen is present, where the browser never starts a native drag from it. */
+export function useIsCoarsePointer(): boolean {
+ return useSyncExternalStore(subscribeCoarse, getCoarseSnapshot, () => false);
+}
+
/**
* Whether to swap in the mobile shell: a sheet sidebar over a dimmed page, its
* own width, its own header. Never in the desktop app, where a narrowed window
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index c09da9b132f..8c95a8aa954 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -194,6 +194,7 @@ export const ar = {
unpinChats: "إلغاء تثبيت المحادثات",
archiveChats: "أرشفة المحادثات",
markUnread: "وضع علامة كغير مقروءة",
+ markRead: "وضع علامة كمقروءة",
deleteChats: "حذف المحادثات",
deleteTitle: "حذف المحادثات",
deleteDescription: "هل تريد حذف {count} محادثة؟ لا يمكن التراجع عن ذلك.",
@@ -212,11 +213,26 @@ export const ar = {
priority: "الأولوية",
lastUpdated: "آخر تحديث",
manualOrder: "ترتيب يدوي",
- moveUp: "تحريك لأعلى",
- moveDown: "تحريك لأسفل",
+ priorityHint: "النشطة وغير المقروءة أولاً",
+ lastUpdatedHint: "الأحدث أولاً",
+ manualOrderHint: "اسحب الصفوف لإعادة ترتيبها",
+ switchedToManual: "الترتيب يدوي الآن: اسحب الصفوف لإعادة ترتيبها",
organizeChats: "تنظيم المحادثات",
organizeProjects: "تنظيم المشاريع",
sortPinnedChats: "ترتيب المحادثات المثبتة",
+ dragDrop: "السحب والإفلات",
+ dragHints: "إظهار تلميح أثناء السحب",
+ reorderSwitchesSort: "إعادة الترتيب تبدّل إلى الترتيب اليدوي",
+ dragOpensFolders: "فتح المجلدات أسفل المؤشر",
+ moveUp: "تحريك لأعلى",
+ moveDown: "تحريك لأسفل",
+ },
+ drag: {
+ reorder: "إعادة ترتيب",
+ pin: "تثبيت",
+ unpin: "إلغاء التثبيت",
+ moveTo: "نقل إلى {name}",
+ moveToRecents: "نقل إلى الأخيرة",
},
dialog: {
deleteChat: {
@@ -1598,6 +1614,9 @@ export const ar = {
collapseByDefault: "طيّ نشاط الأدوات افتراضيًا",
collapseByDefaultDescription:
"إبقاء مدخلات الأدوات ومخرجاتها مطوية أثناء التشغيل. وسّع أي صف أداة لفحصه.",
+ foldIntoThinking: "طيّ استدعاءات الأدوات داخل التفكير",
+ foldIntoThinkingDescription:
+ "إخفاء استدعاءات الأدوات في الدور حتى فتح كتلة التفكير.",
},
webSearch: {
title: "البحث على الويب",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 5b9f7830245..f803b24053e 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -197,6 +197,7 @@ export const de = {
unpinChats: "Chats lösen",
archiveChats: "Chats archivieren",
markUnread: "Als ungelesen markieren",
+ markRead: "Als gelesen markieren",
deleteChats: "Chats löschen",
deleteTitle: "Chats löschen",
deleteDescription: "{count} Chats löschen? Das lässt sich nicht rückgängig machen.",
@@ -215,11 +216,26 @@ export const de = {
priority: "Priorität",
lastUpdated: "Zuletzt aktualisiert",
manualOrder: "Manuelle Reihenfolge",
- moveUp: "Nach oben",
- moveDown: "Nach unten",
+ priorityHint: "Aktive und ungelesene zuerst",
+ lastUpdatedHint: "Neueste zuerst",
+ manualOrderHint: "Zeilen zum Umordnen ziehen",
+ switchedToManual: "Manuell sortiert: Zeilen zum Umordnen ziehen",
organizeChats: "Chats organisieren",
organizeProjects: "Projekte organisieren",
sortPinnedChats: "Angeheftete Chats sortieren",
+ dragDrop: "Ziehen und Ablegen",
+ dragHints: "Hinweis beim Ziehen anzeigen",
+ reorderSwitchesSort: "Umordnen wechselt zu manueller Reihenfolge",
+ dragOpensFolders: "Ordner unter dem Zeiger öffnen",
+ moveUp: "Nach oben",
+ moveDown: "Nach unten",
+ },
+ drag: {
+ reorder: "Umordnen",
+ pin: "Anheften",
+ unpin: "Lösen",
+ moveTo: "Verschieben nach {name}",
+ moveToRecents: "Zu Zuletzt verschieben",
},
dialog: {
deleteChat: {
@@ -1638,6 +1654,9 @@ export const de = {
collapseByDefault: "Tool-Aktivität standardmäßig einklappen",
collapseByDefaultDescription:
"Tool-Eingaben und -Ausgaben bleiben während der Ausführung eingeklappt. Zum Prüfen eine Tool-Zeile ausklappen.",
+ foldIntoThinking: "Tool-Aufrufe ins Denken einklappen",
+ foldIntoThinkingDescription:
+ "Tool-Aufrufe eines Zuges ausblenden, bis der Denken-Block geöffnet wird.",
},
webSearch: {
title: "Websuche",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 831cc81ae73..4993a4fb10f 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -198,6 +198,7 @@ export const en = {
unpinChats: "Unpin chats",
archiveChats: "Archive chats",
markUnread: "Mark as unread",
+ markRead: "Mark as read",
deleteChats: "Delete chats",
deleteTitle: "Delete chats",
deleteDescription: "Delete {count} chats? This cannot be undone.",
@@ -217,11 +218,26 @@ export const en = {
priority: "Priority",
lastUpdated: "Last updated",
manualOrder: "Manual order",
- moveUp: "Move up",
- moveDown: "Move down",
+ priorityHint: "Active and unread first",
+ lastUpdatedHint: "Newest first",
+ manualOrderHint: "Drag rows to reorder",
+ switchedToManual: "Sorted manually: drag rows to reorder",
organizeChats: "Organize chats",
organizeProjects: "Organize projects",
sortPinnedChats: "Sort pinned chats",
+ dragDrop: "Drag and drop",
+ dragHints: "Show a hint while dragging",
+ reorderSwitchesSort: "Reordering sets Manual order",
+ dragOpensFolders: "Open folders while hovering",
+ moveUp: "Move up",
+ moveDown: "Move down",
+ },
+ drag: {
+ reorder: "Reorder",
+ pin: "Pin",
+ unpin: "Unpin",
+ moveTo: "Move to {name}",
+ moveToRecents: "Move to Recents",
},
dialog: {
deleteChat: {
@@ -1593,6 +1609,9 @@ export const en = {
collapseByDefault: "Collapse tool activity by default",
collapseByDefaultDescription:
"Keep tool details collapsed. Expand a row to inspect it.",
+ foldIntoThinking: "Fold tool calls into Thinking",
+ foldIntoThinkingDescription:
+ "Hide a turn's tool calls until its Thinking block is opened.",
},
webSearch: {
title: "Web search",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index a0b5cbcfd4e..f63f30f0f37 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -196,6 +196,7 @@ export const es = {
unpinChats: "Dejar de fijar chats",
archiveChats: "Archivar chats",
markUnread: "Marcar como no leído",
+ markRead: "Marcar como leído",
deleteChats: "Eliminar chats",
deleteTitle: "Eliminar chats",
deleteDescription: "¿Eliminar {count} chats? Esta acción no se puede deshacer.",
@@ -214,11 +215,26 @@ export const es = {
priority: "Prioridad",
lastUpdated: "Última actualización",
manualOrder: "Orden manual",
- moveUp: "Subir",
- moveDown: "Bajar",
+ priorityHint: "Activos y no leídos primero",
+ lastUpdatedHint: "Más recientes primero",
+ manualOrderHint: "Arrastra las filas para reordenarlas",
+ switchedToManual: "Orden manual: arrastra las filas para reordenarlas",
organizeChats: "Organizar chats",
organizeProjects: "Organizar proyectos",
sortPinnedChats: "Ordenar chats fijados",
+ dragDrop: "Arrastrar y soltar",
+ dragHints: "Mostrar una pista al arrastrar",
+ reorderSwitchesSort: "Reordenar cambia a orden manual",
+ dragOpensFolders: "Abrir carpetas bajo el puntero",
+ moveUp: "Subir",
+ moveDown: "Bajar",
+ },
+ drag: {
+ reorder: "Reordenar",
+ pin: "Fijar",
+ unpin: "Desfijar",
+ moveTo: "Mover a {name}",
+ moveToRecents: "Mover a Recientes",
},
dialog: {
deleteChat: {
@@ -1629,6 +1645,9 @@ export const es = {
collapseByDefault: "Contraer la actividad de herramientas por defecto",
collapseByDefaultDescription:
"Mantén contraídas las entradas y salidas de las herramientas mientras se ejecutan. Expande cualquier fila para inspeccionarla.",
+ foldIntoThinking: "Plegar las llamadas de herramientas en Pensamiento",
+ foldIntoThinkingDescription:
+ "Oculta las llamadas de herramientas de un turno hasta abrir su bloque de Pensamiento.",
},
webSearch: {
title: "Búsqueda web",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 8375013c692..46d9708f865 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -197,6 +197,7 @@ export const fr = {
unpinChats: "Détacher les discussions",
archiveChats: "Archiver les discussions",
markUnread: "Marquer comme non lu",
+ markRead: "Marquer comme lu",
deleteChats: "Supprimer les discussions",
deleteTitle: "Supprimer les discussions",
deleteDescription: "Supprimer {count} discussions ? Cette action est irréversible.",
@@ -215,11 +216,26 @@ export const fr = {
priority: "Priorité",
lastUpdated: "Dernière mise à jour",
manualOrder: "Ordre manuel",
- moveUp: "Monter",
- moveDown: "Descendre",
+ priorityHint: "Actifs et non lus en premier",
+ lastUpdatedHint: "Les plus récents en premier",
+ manualOrderHint: "Faites glisser les lignes pour les réorganiser",
+ switchedToManual: "Tri manuel : faites glisser les lignes pour les réorganiser",
organizeChats: "Organiser les discussions",
organizeProjects: "Organiser les projets",
sortPinnedChats: "Trier les discussions épinglées",
+ dragDrop: "Glisser-déposer",
+ dragHints: "Afficher une indication pendant le glissement",
+ reorderSwitchesSort: "Réordonner passe en ordre manuel",
+ dragOpensFolders: "Ouvrir les dossiers sous le pointeur",
+ moveUp: "Monter",
+ moveDown: "Descendre",
+ },
+ drag: {
+ reorder: "Réordonner",
+ pin: "Épingler",
+ unpin: "Désépingler",
+ moveTo: "Déplacer vers {name}",
+ moveToRecents: "Déplacer vers Récents",
},
dialog: {
deleteChat: {
@@ -1635,6 +1651,9 @@ export const fr = {
collapseByDefault: "Replier l’activité des outils par défaut",
collapseByDefaultDescription:
"Garde les entrées et sorties des outils repliées pendant leur exécution. Dépliez une ligne d’outil pour l’examiner.",
+ foldIntoThinking: "Replier les appels d'outils dans la Réflexion",
+ foldIntoThinkingDescription:
+ "Masque les appels d'outils d'un tour jusqu'à l'ouverture de son bloc de Réflexion.",
},
webSearch: {
title: "Recherche web",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 6ac3a496b15..eb20b52fe88 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -197,6 +197,7 @@ export const hi = {
unpinChats: "चैट अनपिन करें",
archiveChats: "चैट संग्रहित करें",
markUnread: "अपठित के रूप में चिह्नित करें",
+ markRead: "पढ़ा हुआ चिह्नित करें",
deleteChats: "चैट हटाएँ",
deleteTitle: "चैट हटाएँ",
deleteDescription: "{count} चैट हटाएँ? इसे पूर्ववत नहीं किया जा सकता।",
@@ -215,11 +216,26 @@ export const hi = {
priority: "प्राथमिकता",
lastUpdated: "अंतिम अपडेट",
manualOrder: "मैन्युअल क्रम",
- moveUp: "ऊपर ले जाएँ",
- moveDown: "नीचे ले जाएँ",
+ priorityHint: "सक्रिय और अपठित पहले",
+ lastUpdatedHint: "सबसे नए पहले",
+ manualOrderHint: "पंक्तियाँ खींचकर क्रम बदलें",
+ switchedToManual: "अब मैन्युअल क्रम: पंक्तियाँ खींचकर क्रम बदलें",
organizeChats: "चैट व्यवस्थित करें",
organizeProjects: "प्रोजेक्ट व्यवस्थित करें",
sortPinnedChats: "पिन की गई चैट क्रमबद्ध करें",
+ dragDrop: "खींचें और छोड़ें",
+ dragHints: "खींचते समय संकेत दिखाएँ",
+ reorderSwitchesSort: "क्रम बदलने पर मैन्युअल क्रम पर स्विच करें",
+ dragOpensFolders: "पॉइंटर के नीचे फ़ोल्डर खोलें",
+ moveUp: "ऊपर ले जाएँ",
+ moveDown: "नीचे ले जाएँ",
+ },
+ drag: {
+ reorder: "क्रम बदलें",
+ pin: "पिन करें",
+ unpin: "अनपिन करें",
+ moveTo: "{name} में ले जाएँ",
+ moveToRecents: "हाल के में ले जाएँ",
},
dialog: {
deleteChat: {
@@ -1605,6 +1621,9 @@ export const hi = {
collapseByDefault: "टूल गतिविधि को डिफ़ॉल्ट रूप से संक्षिप्त रखें",
collapseByDefaultDescription:
"टूल चलते समय उनके इनपुट और आउटपुट संक्षिप्त रखें। जाँचने के लिए किसी भी टूल पंक्ति को विस्तृत करें।",
+ foldIntoThinking: "टूल कॉल को थिंकिंग में समेटें",
+ foldIntoThinkingDescription:
+ "किसी टर्न के टूल कॉल तब तक छिपाएँ जब तक उसका थिंकिंग ब्लॉक न खोला जाए।",
},
webSearch: {
title: "वेब खोज",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 7e3b44ca0da..6f6ef1617fd 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -161,6 +161,7 @@ export const it = {
unpinChats: "Rimuovi le chat fissate",
archiveChats: "Archivia le chat",
markUnread: "Segna come non letta",
+ markRead: "Segna come letta",
deleteChats: "Elimina le chat",
deleteTitle: "Elimina le chat",
deleteDescription: "Eliminare {count} chat? L'operazione non è reversibile.",
@@ -179,11 +180,26 @@ export const it = {
priority: "Priorità",
lastUpdated: "Ultimo aggiornamento",
manualOrder: "Ordine manuale",
- moveUp: "Sposta su",
- moveDown: "Sposta giù",
+ priorityHint: "Prima attive e non lette",
+ lastUpdatedHint: "Prima le più recenti",
+ manualOrderHint: "Trascina le righe per riordinarle",
+ switchedToManual: "Ordinamento manuale: trascina le righe per riordinarle",
organizeChats: "Organizza le chat",
organizeProjects: "Organizza i progetti",
sortPinnedChats: "Ordina le chat fissate",
+ dragDrop: "Trascina e rilascia",
+ dragHints: "Mostra un suggerimento durante il trascinamento",
+ reorderSwitchesSort: "Riordinare passa all'ordine manuale",
+ dragOpensFolders: "Apri le cartelle sotto il puntatore",
+ moveUp: "Sposta su",
+ moveDown: "Sposta giù",
+ },
+ drag: {
+ reorder: "Riordina",
+ pin: "Fissa",
+ unpin: "Sblocca",
+ moveTo: "Sposta in {name}",
+ moveToRecents: "Sposta in Recenti",
},
dialog: {
deleteChat: {
@@ -1603,6 +1619,9 @@ export const it = {
collapseByDefault: "Comprimi l’attività degli strumenti per impostazione predefinita",
collapseByDefaultDescription:
"Mantieni compressi input e output degli strumenti durante l’esecuzione. Espandi una riga per esaminarla.",
+ foldIntoThinking: "Comprimi le chiamate agli strumenti nel Ragionamento",
+ foldIntoThinkingDescription:
+ "Nasconde le chiamate agli strumenti di un turno finché non si apre il blocco Ragionamento.",
},
webSearch: {
title: "Ricerca web",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 27d94bc7f00..97c9ffe45e3 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -196,6 +196,7 @@ export const ja = {
unpinChats: "ピン留めを解除",
archiveChats: "チャットをアーカイブ",
markUnread: "未読にする",
+ markRead: "既読にする",
deleteChats: "チャットを削除",
deleteTitle: "チャットを削除",
deleteDescription: "{count} 件のチャットを削除しますか。元に戻せません。",
@@ -214,11 +215,26 @@ export const ja = {
priority: "優先度",
lastUpdated: "最終更新",
manualOrder: "手動で並べ替え",
- moveUp: "上へ移動",
- moveDown: "下へ移動",
+ priorityHint: "実行中・未読が先頭",
+ lastUpdatedHint: "新しい順",
+ manualOrderHint: "行をドラッグして並べ替えます",
+ switchedToManual: "手動の並び順に切り替えました。行をドラッグして並べ替えます",
organizeChats: "チャットを整理",
organizeProjects: "プロジェクトを整理",
sortPinnedChats: "ピン留めチャットを並べ替え",
+ dragDrop: "ドラッグ&ドロップ",
+ dragHints: "ドラッグ中にヒントを表示",
+ reorderSwitchesSort: "並べ替えると手動順序に切り替える",
+ dragOpensFolders: "ポインターの下のフォルダーを開く",
+ moveUp: "上へ移動",
+ moveDown: "下へ移動",
+ },
+ drag: {
+ reorder: "並べ替え",
+ pin: "ピン留め",
+ unpin: "ピン留めを解除",
+ moveTo: "{name} に移動",
+ moveToRecents: "最近に移動",
},
dialog: {
deleteChat: {
@@ -1581,6 +1597,9 @@ export const ja = {
collapseByDefault: "ツールの動作をデフォルトで折りたたむ",
collapseByDefaultDescription:
"ツールの実行中は入力と出力を折りたたんだままにします。確認するにはツール行を展開してください。",
+ foldIntoThinking: "ツール呼び出しを思考に折りたたむ",
+ foldIntoThinkingDescription:
+ "思考ブロックを開くまで、そのターンのツール呼び出しを隠します。",
},
webSearch: {
title: "ウェブ検索",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 4bd48d0f9a8..9842daa1fe9 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -194,6 +194,7 @@ export const ko = {
unpinChats: "채팅 고정 해제",
archiveChats: "채팅 보관",
markUnread: "읽지 않음으로 표시",
+ markRead: "읽음으로 표시",
deleteChats: "채팅 삭제",
deleteTitle: "채팅 삭제",
deleteDescription: "채팅 {count}개를 삭제할까요? 되돌릴 수 없습니다.",
@@ -212,11 +213,26 @@ export const ko = {
priority: "우선순위",
lastUpdated: "최근 업데이트",
manualOrder: "수동 정렬",
- moveUp: "위로 이동",
- moveDown: "아래로 이동",
+ priorityHint: "진행 중·읽지 않음 우선",
+ lastUpdatedHint: "최신순",
+ manualOrderHint: "행을 끌어 순서를 바꾸세요",
+ switchedToManual: "수동 정렬로 전환됨: 행을 끌어 순서를 바꾸세요",
organizeChats: "채팅 정리",
organizeProjects: "프로젝트 정리",
sortPinnedChats: "고정된 채팅 정렬",
+ dragDrop: "드래그 앤 드롭",
+ dragHints: "드래그 중 힌트 표시",
+ reorderSwitchesSort: "순서 변경 시 수동 정렬로 전환",
+ dragOpensFolders: "포인터 아래 폴더 열기",
+ moveUp: "위로 이동",
+ moveDown: "아래로 이동",
+ },
+ drag: {
+ reorder: "순서 변경",
+ pin: "고정",
+ unpin: "고정 해제",
+ moveTo: "{name}(으)로 이동",
+ moveToRecents: "최근으로 이동",
},
dialog: {
deleteChat: {
@@ -1593,6 +1609,9 @@ export const ko = {
collapseByDefault: "기본적으로 도구 활동 접기",
collapseByDefaultDescription:
"도구가 실행되는 동안 입력과 출력을 접어 둡니다. 확인하려면 도구 행을 펼치세요.",
+ foldIntoThinking: "도구 호출을 생각 안으로 접기",
+ foldIntoThinkingDescription:
+ "생각 블록을 열기 전까지 해당 턴의 도구 호출을 숨깁니다.",
},
webSearch: {
title: "웹 검색",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index ed9df4d96cc..a18b6e94be2 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -196,6 +196,7 @@ export const ptBR = {
unpinChats: "Desafixar conversas",
archiveChats: "Arquivar conversas",
markUnread: "Marcar como não lida",
+ markRead: "Marcar como lida",
deleteChats: "Excluir conversas",
deleteTitle: "Excluir conversas",
deleteDescription: "Excluir {count} conversas? Esta ação não pode ser desfeita.",
@@ -214,11 +215,26 @@ export const ptBR = {
priority: "Prioridade",
lastUpdated: "Última atualização",
manualOrder: "Ordem manual",
- moveUp: "Mover para cima",
- moveDown: "Mover para baixo",
+ priorityHint: "Ativos e não lidos primeiro",
+ lastUpdatedHint: "Mais recentes primeiro",
+ manualOrderHint: "Arraste as linhas para reordenar",
+ switchedToManual: "Ordem manual: arraste as linhas para reordenar",
organizeChats: "Organizar conversas",
organizeProjects: "Organizar projetos",
sortPinnedChats: "Ordenar conversas fixadas",
+ dragDrop: "Arrastar e soltar",
+ dragHints: "Mostrar uma dica ao arrastar",
+ reorderSwitchesSort: "Reordenar muda para ordem manual",
+ dragOpensFolders: "Abrir pastas sob o ponteiro",
+ moveUp: "Mover para cima",
+ moveDown: "Mover para baixo",
+ },
+ drag: {
+ reorder: "Reordenar",
+ pin: "Fixar",
+ unpin: "Desafixar",
+ moveTo: "Mover para {name}",
+ moveToRecents: "Mover para Recentes",
},
dialog: {
deleteChat: {
@@ -1616,6 +1632,9 @@ export const ptBR = {
collapseByDefault: "Recolher atividade de ferramentas por padrão",
collapseByDefaultDescription:
"Mantém entradas e saídas das ferramentas recolhidas durante a execução. Expanda uma linha para inspecioná-la.",
+ foldIntoThinking: "Recolher chamadas de ferramentas no Pensamento",
+ foldIntoThinkingDescription:
+ "Oculta as chamadas de ferramentas de um turno até abrir o bloco de Pensamento.",
},
webSearch: {
title: "Busca na web",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index a737730399a..e9ae0560bdb 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -196,6 +196,7 @@ export const ru = {
unpinChats: "Открепить чаты",
archiveChats: "Архивировать чаты",
markUnread: "Отметить как непрочитанное",
+ markRead: "Отметить как прочитанное",
deleteChats: "Удалить чаты",
deleteTitle: "Удалить чаты",
deleteDescription: "Удалить чаты ({count})? Это действие необратимо.",
@@ -214,11 +215,26 @@ export const ru = {
priority: "Приоритету",
lastUpdated: "Последнему обновлению",
manualOrder: "Вручную",
- moveUp: "Переместить вверх",
- moveDown: "Переместить вниз",
+ priorityHint: "Сначала активные и непрочитанные",
+ lastUpdatedHint: "Сначала новые",
+ manualOrderHint: "Перетащите строки, чтобы изменить порядок",
+ switchedToManual: "Ручной порядок: перетащите строки, чтобы изменить порядок",
organizeChats: "Настроить чаты",
organizeProjects: "Настроить проекты",
sortPinnedChats: "Сортировать закреплённые чаты",
+ dragDrop: "Перетаскивание",
+ dragHints: "Показывать подсказку при перетаскивании",
+ reorderSwitchesSort: "Перестановка включает ручной порядок",
+ dragOpensFolders: "Открывать папки под указателем",
+ moveUp: "Переместить вверх",
+ moveDown: "Переместить вниз",
+ },
+ drag: {
+ reorder: "Переставить",
+ pin: "Закрепить",
+ unpin: "Открепить",
+ moveTo: "Переместить в {name}",
+ moveToRecents: "Переместить в Недавние",
},
dialog: {
deleteChat: {
@@ -1613,6 +1629,9 @@ export const ru = {
collapseByDefault: "Сворачивать действия инструментов по умолчанию",
collapseByDefaultDescription:
"Входные и выходные данные инструментов остаются свёрнутыми во время работы. Разверните строку инструмента для просмотра.",
+ foldIntoThinking: "Сворачивать вызовы инструментов в Размышление",
+ foldIntoThinkingDescription:
+ "Скрывает вызовы инструментов хода, пока не открыт блок размышления.",
},
webSearch: {
title: "Веб-поиск",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 04c281afb40..abc79bbe5f8 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -192,6 +192,7 @@ export const zhCN = {
unpinChats: "取消置顶",
archiveChats: "归档对话",
markUnread: "标记为未读",
+ markRead: "标记为已读",
deleteChats: "删除对话",
deleteTitle: "删除对话",
deleteDescription: "删除 {count} 个对话?此操作无法撤销。",
@@ -210,11 +211,26 @@ export const zhCN = {
priority: "优先级",
lastUpdated: "最近更新",
manualOrder: "手动排序",
- moveUp: "上移",
- moveDown: "下移",
+ priorityHint: "进行中和未读优先",
+ lastUpdatedHint: "最新优先",
+ manualOrderHint: "拖动行即可重新排序",
+ switchedToManual: "已改为手动排序,拖动行即可重新排序",
organizeChats: "整理对话",
organizeProjects: "整理项目",
sortPinnedChats: "对置顶对话排序",
+ dragDrop: "拖放",
+ dragHints: "拖动时显示提示",
+ reorderSwitchesSort: "重新排序时切换为手动排序",
+ dragOpensFolders: "打开指针下方的文件夹",
+ moveUp: "上移",
+ moveDown: "下移",
+ },
+ drag: {
+ reorder: "重新排序",
+ pin: "固定",
+ unpin: "取消固定",
+ moveTo: "移动到 {name}",
+ moveToRecents: "移动到最近",
},
dialog: {
deleteChat: {
@@ -1562,6 +1578,9 @@ export const zhCN = {
collapseByDefault: "默认折叠工具活动",
collapseByDefaultDescription:
"工具运行时保持输入和输出折叠。需要检查时展开对应工具行。",
+ foldIntoThinking: "将工具调用折叠进思考",
+ foldIntoThinkingDescription:
+ "在展开思考块之前隐藏该轮的工具调用。",
},
webSearch: {
title: "网页搜索",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 7d56e136cf7..1b9ab3ab879 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -2788,6 +2788,19 @@ html[data-chat-font] .aui-root {
margin-bottom: 0 !important;
}
+ /* One vertical rhythm for everything stacked inside an assistant reply: text, thinking
+ headers, tool-call groups and single tool rows all sit 1rem apart, the same gap
+ streamdown puts between two paragraphs. The parts themselves own no outer margin or
+ padding, so a header next to a paragraph reads the same as a paragraph next to a
+ paragraph. `:where()` keeps this at zero specificity so a part that does set its own
+ `mt-*` still wins. The first real child follows a zero-height badge anchor and gets none. */
+ :where(.aui-assistant-message-content > * + *) {
+ margin-top: 1rem;
+ }
+ :where(.aui-assistant-message-content > .h-0 + *) {
+ margin-top: 0;
+ }
+
/* The streamdown code-block wrapper carries `my-4` (16px top + 16px
bottom margin). The bottom margin is what stretches the gap
between the code-block box and the action-bar below it on a
diff --git a/studio/frontend/src/lib/format-worked-for.ts b/studio/frontend/src/lib/format-worked-for.ts
new file mode 100644
index 00000000000..ac93ff97b82
--- /dev/null
+++ b/studio/frontend/src/lib/format-worked-for.ts
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Elapsed time as a run reads it: "45s", "3m 36s", "1h 4m". Whole seconds past an hour are
+ * noise, so the hour form drops them. */
+export function formatWorkedFor(seconds: number): string {
+ const total = Math.max(0, Math.round(seconds));
+ if (total < 60) return `${total}s`;
+ const minutes = Math.floor(total / 60);
+ if (minutes < 60) return `${minutes}m ${total % 60}s`;
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
+}
diff --git a/studio/frontend/src/lib/hugeicons-derived.ts b/studio/frontend/src/lib/hugeicons-derived.ts
index 97059ff11a8..f67de6bc7ec 100644
--- a/studio/frontend/src/lib/hugeicons-derived.ts
+++ b/studio/frontend/src/lib/hugeicons-derived.ts
@@ -3,10 +3,18 @@
// Derived HugeIcons shared between the sidebar and page tabs, so the same visual language appears everywhere.
-import { TestTube01Icon } from "@hugeicons/core-free-icons";
+import { BubbleChatIcon, TestTube01Icon } from "@hugeicons/core-free-icons";
// TestTube01Icon's last 2 paths are interior bubbles; slice to the first 3 (outline + cap + liquid line). Original export untouched.
export const TestTubeOutlineIcon = TestTube01Icon.slice(
0,
3,
) as typeof TestTube01Icon;
+
+// HugeIcons' own message-circle, which this icon set does not ship: BubbleChatIcon is that same
+// round bubble with a second path drawing the three dots inside it, so the first path alone is it.
+// A chat row is one row of a list and reads better without the speckle. Original export untouched.
+export const MessageCircleIcon = BubbleChatIcon.slice(
+ 0,
+ 1,
+) as typeof BubbleChatIcon;
diff --git a/studio/frontend/tests/edit-project-dialog.test.ts b/studio/frontend/tests/edit-project-dialog.test.ts
new file mode 100644
index 00000000000..6fb2712d78e
--- /dev/null
+++ b/studio/frontend/tests/edit-project-dialog.test.ts
@@ -0,0 +1,130 @@
+// 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 project Edit dialog: one stack of name, instructions and a grouped list of source folders.
+// What it must not do is lose an edit: the two writes are separate, and the draft belongs to the
+// project that is open, not the one that was.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readSrcAsync } from "./helpers/kit.ts";
+
+const DIALOG = await readSrcAsync(
+ "features/chat/components/edit-project-dialog.tsx",
+);
+const FOLDERS = await readSrcAsync(
+ "features/rag/components/linked-folders-manager.tsx",
+);
+
+// The folders used to be a settings panel (heading, blurb and its own button) dropped inside a
+// muted box under two fields that were bordered cards. Now all three read as one stack.
+test("the dialog shows its folders as a grouped card, not a nested panel", () => {
+ assert.match(
+ DIALOG,
+ /<LinkedFoldersManager\n\s*scope=\{\{ type: "project", id: project\.id \}\}\n\s*variant="card"\n\s*\/>/,
+ );
+ assert.ok(
+ !DIALOG.includes('compact={true}'),
+ "the dialog still asks for the panel layout",
+ );
+ assert.match(DIALOG, /<h3 className="[^"]*">\n\s*Source folders\n\s*<\/h3>/);
+});
+
+// The card's last row adds a folder, where the panel had a button in its header.
+test("the card ends in an Add folder row that says when it cannot", () => {
+ const card = FOLDERS.slice(
+ FOLDERS.indexOf('if (variant === "card") {'),
+ FOLDERS.indexOf(" return (\n <section"),
+ );
+ assert.ok(card.length > 0, "the card layout moved");
+ assert.match(card, /<span>Add folder<\/span>/);
+ assert.match(card, /disabled=\{!manager\.desktopSupported \|\| manager\.mutating\}/);
+ assert.match(card, /onClick=\{\(\) => void manager\.link\(\)\}/);
+ // A folder list with no scope has nothing to link into, so it shows no row that cannot work.
+ assert.match(card, /\{scope \? \(\n\s*<button/);
+ // And the reason the row is dead is only spelled out when it is.
+ assert.match(card, /\{!manager\.desktopSupported \? \(/);
+});
+
+// Both layouts drive the same hook and the same actions: a card row that dropped Sync changes or
+// the two unlinks would be a quieter list that can do less.
+test("a card row keeps every action the panel row has", () => {
+ assert.match(FOLDERS, /function folderMenu\(/);
+ assert.equal(
+ (FOLDERS.match(/\{folderMenu\(folder, running\)\}/g) ?? []).length,
+ 2,
+ "one of the two layouts stopped using the shared row menu",
+ );
+ // One confirmation, mounted by whichever layout rendered.
+ assert.match(FOLDERS, /const removeIndexConfirm = \(/);
+ assert.equal(
+ (FOLDERS.match(/\{removeIndexConfirm\}/g) ?? []).length,
+ 2,
+ "a layout can unlink-and-remove without confirming it",
+ );
+});
+
+// The panel is what Settings, the knowledge-base dialog and the Sources tab render, and none of
+// them asked for a card.
+test("the other folder lists keep the panel layout", async () => {
+ for (const path of [
+ "features/settings/tabs/data-tab.tsx",
+ "features/rag/components/knowledge-base-dialog.tsx",
+ "features/rag/components/project-sources-panel.tsx",
+ ]) {
+ const source = await readSrcAsync(path);
+ assert.ok(
+ !source.includes('variant="card"'),
+ `${path} was switched to the dialog's card layout`,
+ );
+ }
+ assert.match(FOLDERS, /variant = "panel",/);
+});
+
+// A failed rename must not take the instructions with it, and neither write should run when its
+// own field is untouched.
+test("name and instructions are saved as separate writes", () => {
+ assert.match(DIALOG, /if \(nameChanged\) await renameChatProject\(target\.id, trimmedName\);/);
+ assert.match(
+ DIALOG,
+ /if \(instructionsChanged\) \{\n\s*await updateChatProjectInstructions\(target\.id, trimmedInstructions\);/,
+ );
+ // Nothing edited is not a write at all, just a close.
+ assert.match(DIALOG, /if \(!dirty\) \{\n\s*onOpenChange\(false\);/);
+ // An empty name is not a rename: it would leave the folder row with nothing to show.
+ assert.match(DIALOG, /if \(busy \|\| !trimmedName\) return;/);
+ assert.match(DIALOG, /disabled=\{busy \|\| !trimmedName\}/);
+});
+
+// The draft is the open project's. Reseeding on id keeps the last project's text from being saved
+// over this one when the dialog is reopened from another row.
+test("the draft follows whichever project is open", () => {
+ assert.match(
+ DIALOG,
+ /if \(\(project\?\.id \?\? null\) !== seededFor\) \{\n\s*setSeededFor\(project\?\.id \?\? null\);\n\s*setName\(project\?\.name \?\? ""\);\n\s*setInstructions\(project\?\.instructions \?\? ""\);/,
+ );
+ // And a save in flight cannot be escaped out from under.
+ assert.match(DIALOG, /function close\(\) \{\n\s*if \(busy\) return;/);
+});
+
+// Enter commits the name field; the instructions box needs its newlines, so the chord commits
+// from either.
+test("the dialog commits on Enter and on the chord", () => {
+ assert.match(
+ DIALOG,
+ /if \(e\.key === "Enter" && \(e\.metaKey \|\| e\.ctrlKey\)\) \{\n\s*e\.preventDefault\(\);\n\s*void save\(\);/,
+ );
+ assert.match(
+ DIALOG,
+ /onKeyDown=\{\(e\) => \{\n\s*if \(e\.key === "Enter"\) \{\n\s*e\.preventDefault\(\);\n(?:\s*\/\/.*\n)*\s*e\.stopPropagation\(\);\n\s*void save\(\);/,
+ );
+});
+
+// Delete is the one action here that cannot be undone, so it reads as the tinted destructive it
+// is rather than as plain red text beside Cancel.
+test("delete is a destructive button, and the caller still confirms it", () => {
+ assert.match(
+ DIALOG,
+ /<Button\n\s*type="button"\n\s*variant="destructive"\n\s*disabled=\{busy\}\n\s*onClick=\{\(\) => \{\n\s*onOpenChange\(false\);\n\s*onDelete\(project\);/,
+ );
+});
diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.ts
index 4d6493497a7..1b744699ab8 100644
--- a/studio/frontend/tests/keyboard-shortcuts.test.ts
+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts
@@ -1260,9 +1260,10 @@ test("the composer chords outlive the recording bar", async () => {
test("a collapsed sidebar section is not published for the chords", async () => {
// Navigation and Select all walk what is on screen, so a section the user
// closed counts as gone, the same as a closed project folder.
+ // Pinned is walked in its drawn order, folders and chats together, behind its disclosure.
assert.match(
APP_SIDEBAR,
- /chatListsOnScreen && pinnedOpen \? sortedPinnedChatItems/,
+ /chatListsOnScreen && pinnedOpen\n\s*\? pinnedRows\.flatMap\(/,
);
assert.match(
APP_SIDEBAR,
@@ -1272,7 +1273,7 @@ test("a collapsed sidebar section is not published for the chords", async () =>
// with Projects, so neither disclosure speaks for the other's rows.
assert.match(
APP_SIDEBAR,
- /folderChatItems\(pinnedOpen, pinnedProjectRecords\)/,
+ /folderChatItems\(true, \[row\.project\]\)/,
);
assert.match(
APP_SIDEBAR,
@@ -1598,7 +1599,7 @@ test("the published chat lists stop where the sidebar stops", async () => {
);
for (const group of [
/if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !open\) return \[\];/,
- /\(chatListsOnScreen && pinnedOpen \? sortedPinnedChatItems : \[\]\)/,
+ /chatListsOnScreen && pinnedOpen\n\s*\? pinnedRows\.flatMap\([\s\S]*?: \[\],/,
/\(chatListsOnScreen && chatOpen \? sortedRecentChatItems : \[\]\)/,
]) {
assert.match(APP_SIDEBAR, group);
@@ -1617,10 +1618,9 @@ test("the published chat lists stop where the sidebar stops", async () => {
// Gating the arrays is enough because nothing renders from them.
const rendered = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("return (", selectAll));
for (const name of [
- "visiblePinnedItems",
+ "pinnedSectionChatItems",
"visibleRecentItems",
"renderedChatItems",
- "pinnedProjectChatItems",
"sectionProjectChatItems",
]) {
assert.ok(!rendered.includes(name), `${name} is read by the JSX too`);
@@ -1822,9 +1822,8 @@ test("a parked tool request is keyed by its own approval, not call_0", async ()
test("the rows the selection guard reads keep their identity", async () => {
for (const name of [
"visibleProjectRecords",
- "visiblePinnedItems",
+ "pinnedRows",
"visibleRecentItems",
- "pinnedProjectChatItems",
"sectionProjectChatItems",
"pinnedSectionChatItems",
"renderedChatItems",
diff --git a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
index 14c9391fb52..a64a659806f 100644
--- a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
+++ b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
@@ -640,10 +640,12 @@ test("list header actions end where a hovered row's action does", () => {
test("all three list headers take the same alignment", () => {
// Pinned and Projects share one class string; Recents has its own because of
// the translate. Two of the first, one of the second.
- const shared =
- SIDEBAR.split(
- '"sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1", headerRightPadding,',
- ).length - 1;
+ // Both headers are drop zones now, so the class list is spread over lines.
+ const shared = (
+ SIDEBAR.match(
+ /"sidebar-sticky-label sidebar-sticky-label-following group\/sidebar-header gap-1",\n\s*headerRightPadding,/g,
+ ) ?? []
+ ).length;
assert.equal(shared, 2, "Pinned and Projects");
assert.ok(
SIDEBAR.includes("recentsHeaderRightPadding,"),
diff --git a/studio/frontend/tests/projects-page-rows.test.ts b/studio/frontend/tests/projects-page-rows.test.ts
new file mode 100644
index 00000000000..c0068c5a019
--- /dev/null
+++ b/studio/frontend/tests/projects-page-rows.test.ts
@@ -0,0 +1,76 @@
+// 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 Projects page is a list of folders with nothing to say about what is in them: opening a
+// project was the only way to find out, and pinning one meant going through a menu.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readSrcAsync } from "./helpers/kit.ts";
+import { formatWorkedFor } from "../src/lib/format-worked-for.ts";
+
+const PAGE = await readSrcAsync("features/chat/projects-page.tsx");
+
+test("a project row opens its chats in place", () => {
+ assert.match(PAGE, /aria-label=\{chatsOpen \? "Hide chats" : "Show chats"\}/);
+ assert.match(PAGE, /aria-expanded=\{chatsOpen\}/);
+ // Loaded the first time the row is opened, and again when chat history changes.
+ // Only an open loads; a close after a failed load must not.
+ assert.match(PAGE, /if \(!opening\) return;\n\s*const cached = projectChats\[projectId\];\n\s*const loaded = cached !== undefined && cached !== "error";\n\s*if \(loaded && !staleProjectIds\.has\(projectId\)\) return;\n[^\n]*\n\s*loadProjectChats\(projectId, loaded\);/);
+ // A failed reload keeps loaded rows, when there are some: an empty folder may have just gained
+ // the chat the reload was for. A pending or failed first load becomes a retryable error.
+ assert.match(PAGE, /const rows = prev\[projectId\];\n\s*if \(silent && Array\.isArray\(rows\) && rows\.length > 0\) \{\n\s*setStale\(projectId, true\);\n\s*return prev;\n\s*\}\n\s*return \{ \.\.\.prev, \[projectId\]: "error" \};/);
+ // Kept rows are marked stale: the row says so, offers a retry, and its next open asks again.
+ assert.match(PAGE, /setStale\(projectId, false\);\n\s*setProjectChats/);
+ assert.match(PAGE, /\{staleProjectIds\.has\(project\.id\) && \(/);
+ assert.match(PAGE, /Could not refresh chats\. Retry/);
+ assert.match(PAGE, /Could not load chats\. Retry/);
+ assert.ok(!PAGE.includes("[projectId]: [] }"), "a failed load is still cached as an empty list");
+ assert.match(
+ PAGE,
+ /listStoredChatThreads\(\{ projectId, includeArchived: false \}\)/,
+ );
+ assert.match(PAGE, /window\.addEventListener\(CHAT_HISTORY_UPDATED_EVENT, refresh\);/);
+ // Debounced, since streaming fires the event per chunk, and open rows reload in place.
+ assert.match(PAGE, /timer = setTimeout\(\(\) => \{[\s\S]*?for \(const id of open\) loadProjectChats\(id, true\);\n\s*\}, PROJECT_CHATS_REFRESH_DEBOUNCE_MS\);/);
+ assert.match(PAGE, /if \(!silent\) \{\n\s*setProjectChats\(\(prev\) => \(\{ \.\.\.prev, \[projectId\]: "loading" \}\)\);/);
+ // A closed project's pending load is invalidated with its cache entry.
+ assert.match(PAGE, /for \(const \[id, seq\] of loadSeqRef\.current\) \{\n\s*if \(!open\.has\(id\)\) loadSeqRef\.current\.set\(id, seq \+ 1\);/);
+ // A response a newer request overtook is dropped.
+ assert.match(PAGE, /if \(loadSeqRef\.current\.get\(projectId\) !== seq\) return;\n\s*setStale\(projectId, false\);\n\s*setProjectChats/);
+ // Grouped as the sidebar groups them, newest first, and a row with none says so.
+ assert.match(PAGE, /groupThreads\(threads\)\.sort\(\n\s*\(a, b\) => b\.updatedAt - a\.updatedAt,/);
+ assert.match(PAGE, /No chats<\/p>/);
+ // Each one opens the chat it names; a comparison opens as one.
+ assert.match(PAGE, /onClick=\{\(\) => openChat\(chat, project\.id\)\}/);
+ assert.match(PAGE, /search: \{ compare: item\.id, project: projectId \}/);
+ // A key on a control inside the row is that control's, not the row's.
+ assert.match(PAGE, /if \(e\.target !== e\.currentTarget\) return;\n\s*if \(e\.key === "Enter" \|\| e\.key === " "\)/);
+});
+
+test("pinning a project takes one click, and says which way it goes", () => {
+ assert.match(PAGE, /aria-label=\{pinned \? "Unpin project" : "Pin project"\}/);
+ assert.match(PAGE, /togglePinProject\(project\.id\);/);
+ // A pinned row keeps its pin showing; the rest reveal on hover.
+ assert.match(PAGE, /pinned \? "opacity-100" : "opacity-0",/);
+ // And the menu no longer repeats the noun the row already is.
+ assert.match(PAGE, /<span>\{pinned \? "Unpin" : "Pin"\}<\/span>/);
+});
+
+// "Thought for 216 seconds" is neither what the model did nor a readable duration.
+test("a finished run says how long it worked, in units that read", () => {
+ assert.equal(formatWorkedFor(0), "0s");
+ assert.equal(formatWorkedFor(45), "45s");
+ assert.equal(formatWorkedFor(60), "1m 0s");
+ assert.equal(formatWorkedFor(216), "3m 36s");
+ assert.equal(formatWorkedFor(3600), "1h 0m");
+ assert.equal(formatWorkedFor(3840), "1h 4m");
+ // Never a negative, whatever the clock did.
+ assert.equal(formatWorkedFor(-5), "0s");
+});
+
+test("the reasoning header says Worked for", async () => {
+ const reasoning = await readSrcAsync("components/assistant-ui/reasoning.tsx");
+ assert.match(reasoning, /Worked for \{formatWorkedFor\(duration \?\? 0\)\}/);
+ assert.ok(!reasoning.includes("Thought for"), "the old label is still rendered");
+});
diff --git a/studio/frontend/tests/sidebar-organization-store.test.ts b/studio/frontend/tests/sidebar-organization-store.test.ts
index 1cfceb11252..3ccf0b9075f 100644
--- a/studio/frontend/tests/sidebar-organization-store.test.ts
+++ b/studio/frontend/tests/sidebar-organization-store.test.ts
@@ -6,12 +6,13 @@ import test from "node:test";
import {
applyManualOrder,
- dropEdgeFor,
+ dropEdgeAt,
+ folderDropTarget,
+ insertIdAt,
moveIdBy,
PROJECT_ORDER_SCOPE,
projectOrderScope,
RECENTS_ORDER_SCOPE,
- reorderIds,
showsInRecents,
SIDEBAR_ORGANIZATION_STORAGE_KEY,
useSidebarOrganizationStore,
@@ -21,14 +22,28 @@ import { readSrcAsync } from "./helpers/kit.ts";
const ids = (rows: Array<{ id: string }>) => rows.map((row) => row.id);
-test("a dragged chat takes the target's slot and pushes the rest along", () => {
- assert.deepEqual(reorderIds(["a", "b", "c", "d"], "d", "b"), [
+test("a dragged row lands on the edge the insertion line was drawn on", () => {
+ // Above the target, dragging either way.
+ assert.deepEqual(insertIdAt(["a", "b", "c", "d"], "d", "b", "top"), [
"a",
"d",
"b",
"c",
]);
- assert.deepEqual(reorderIds(["a", "b", "c", "d"], "a", "c"), [
+ assert.deepEqual(insertIdAt(["a", "b", "c", "d"], "a", "c", "top"), [
+ "b",
+ "a",
+ "c",
+ "d",
+ ]);
+ // And below it, which the index-derived edge could never express on its own.
+ assert.deepEqual(insertIdAt(["a", "b", "c", "d"], "d", "b", "bottom"), [
+ "a",
+ "b",
+ "d",
+ "c",
+ ]);
+ assert.deepEqual(insertIdAt(["a", "b", "c", "d"], "a", "c", "bottom"), [
"b",
"c",
"a",
@@ -36,13 +51,15 @@ test("a dragged chat takes the target's slot and pushes the rest along", () => {
]);
});
-test("a drop that cannot be resolved leaves the order alone", () => {
+test("a drop that changes nothing leaves the order alone", () => {
const ids = ["a", "b", "c"];
- // Same row, and rows the list no longer holds: each returns the input array
- // itself, which is what tells the caller there is nothing to persist.
- assert.equal(reorderIds(ids, "b", "b"), ids);
- assert.equal(reorderIds(ids, "gone", "b"), ids);
- assert.equal(reorderIds(ids, "b", "gone"), ids);
+ // Same row, rows the list no longer holds, and a landing that is where the row already was:
+ // each returns the input array itself, which is what tells the caller not to persist it.
+ assert.equal(insertIdAt(ids, "b", "b", "top"), ids);
+ assert.equal(insertIdAt(ids, "gone", "b", "top"), ids);
+ assert.equal(insertIdAt(ids, "b", "gone", "top"), ids);
+ assert.equal(insertIdAt(ids, "b", "a", "bottom"), ids);
+ assert.equal(insertIdAt(ids, "b", "c", "top"), ids);
});
test("a project chat shows in Recents only when the folders are off", () => {
@@ -57,25 +74,131 @@ test("a project chat shows in Recents only when the folders are off", () => {
});
test("the drop indicator names the edge the row actually lands on", () => {
- // Painting the cue on the wrong edge is a lie about where the drop goes, so
- // check every pair against what reorderIds really does.
+ // Painting the cue on the wrong edge is a lie about where the drop goes, so check every pair
+ // against what insertIdAt really does with the edge the pointer picked.
const rows = ["a", "b", "c", "d"];
for (const dragged of rows) {
for (const target of rows) {
if (dragged === target) continue;
- const next = reorderIds(rows, dragged, target);
- const landed = next.indexOf(dragged);
- const targetAt = next.indexOf(target);
- const edge = dropEdgeFor(rows, dragged, target);
- assert.equal(
- landed,
- edge === "bottom" ? targetAt + 1 : targetAt - 1,
- `${dragged} onto ${target} drew ${edge} but landed at ${landed}`,
- );
+ for (const edge of ["top", "bottom"] as const) {
+ const next = insertIdAt(rows, dragged, target, edge);
+ if (next === rows) continue; // The row was already on that side.
+ const landed = next.indexOf(dragged);
+ const targetAt = next.indexOf(target);
+ assert.equal(
+ landed,
+ edge === "bottom" ? targetAt + 1 : targetAt - 1,
+ `${dragged} onto ${target}'s ${edge} edge landed at ${landed}`,
+ );
+ }
}
}
});
+// Pinned draws each folder followed by the chats inside it, so two folder rows can be a whole
+// block apart. With only the folder rows answering, the drag reads as doing nothing: most of the
+// distance between them refuses the drop, and the near edge of the other folder is the one that
+// moves nothing. The chats answer for the folder they belong to instead.
+test("a folder dragged over another folder's chats lands against that folder", () => {
+ const folderIds = ["a", "b"];
+ // Folder b holds a single chat, so that one row has to answer both ends of the block: the
+ // lower half of it puts a after b.
+ assert.deepEqual(
+ folderDropTarget({
+ draggedId: "a",
+ folderIds,
+ folderId: "b",
+ rowIndex: 0,
+ rowCount: 1,
+ pointerEdge: "bottom",
+ }),
+ { edge: "bottom", next: ["b", "a"] },
+ );
+ // Its upper half means above b, which is where a already is.
+ assert.equal(
+ folderDropTarget({
+ draggedId: "a",
+ folderIds,
+ folderId: "b",
+ rowIndex: 0,
+ rowCount: 1,
+ pointerEdge: "top",
+ }),
+ null,
+ );
+ // Folder a holds four. The top of the block puts b above a; the bottom would put it back
+ // where it already is, which is not a drop at all.
+ assert.deepEqual(
+ folderDropTarget({
+ draggedId: "b",
+ folderIds,
+ folderId: "a",
+ rowIndex: 0,
+ rowCount: 4,
+ pointerEdge: "top",
+ }),
+ { edge: "top", next: ["b", "a"] },
+ );
+ assert.equal(
+ folderDropTarget({
+ draggedId: "b",
+ folderIds,
+ folderId: "a",
+ rowIndex: 3,
+ rowCount: 4,
+ pointerEdge: "bottom",
+ }),
+ null,
+ );
+ // A folder's own chats are not a target: it cannot land against itself.
+ assert.equal(
+ folderDropTarget({
+ draggedId: "a",
+ folderIds,
+ folderId: "a",
+ rowIndex: 0,
+ rowCount: 4,
+ pointerEdge: "top",
+ }),
+ null,
+ );
+});
+
+// The edge is the row's place in the block, not the pointer's place in the row: reading it off
+// the cursor would flip the line from one end of the folder to the other at every chat.
+test("the edge holds for every row in the same half of a block", () => {
+ const folderIds = ["a", "b", "c"];
+ const edgeAt = (rowIndex: number, pointerEdge: "top" | "bottom" = "top") =>
+ folderDropTarget({
+ draggedId: "c",
+ folderIds,
+ folderId: "a",
+ rowIndex,
+ rowCount: 6,
+ pointerEdge,
+ })?.edge;
+ assert.deepEqual([0, 1, 2].map((at) => edgeAt(at)), ["top", "top", "top"]);
+ assert.deepEqual(
+ [3, 4, 5].map((at) => edgeAt(at)),
+ ["bottom", "bottom", "bottom"],
+ );
+ // The one row the answer changes inside is the middle of the block, not every row.
+ assert.equal(edgeAt(2, "bottom"), "bottom");
+ assert.equal(edgeAt(3, "top"), "bottom");
+});
+
+// The edge follows the cursor, not the two rows' index order: dragging a row down and letting go
+// over the top half of a row has to insert above it, or the line moves and the row does not.
+test("the pointer's half of a row is the edge it drops on", () => {
+ const rect = { top: 100, height: 30 };
+ assert.equal(dropEdgeAt(rect, 101), "top");
+ assert.equal(dropEdgeAt(rect, 114), "top");
+ assert.equal(dropEdgeAt(rect, 115), "bottom");
+ assert.equal(dropEdgeAt(rect, 129), "bottom");
+});
+
+// Alt + arrow is what a keyboard has instead of a drag, now that the row menu no longer carries
+// Move up and Move down.
test("a row moves one slot at a time and stops at the ends", () => {
assert.deepEqual(moveIdBy(["a", "b", "c"], "a", 1), ["b", "a", "c"]);
assert.deepEqual(moveIdBy(["a", "b", "c"], "c", -1), ["a", "c", "b"]);
@@ -86,11 +209,11 @@ test("a row moves one slot at a time and stops at the ends", () => {
assert.equal(moveIdBy(ids, "gone", 1), ids);
});
-test("moving by menu matches dragging onto the neighbour", () => {
- // The two paths must agree, or the same gesture gives two different orders.
+test("moving by keyboard matches dragging onto the neighbour", () => {
+ // The two paths must agree, or the same move gives two different orders.
const rows = ["a", "b", "c", "d"];
- assert.deepEqual(moveIdBy(rows, "b", 1), reorderIds(rows, "b", "c"));
- assert.deepEqual(moveIdBy(rows, "c", -1), reorderIds(rows, "c", "b"));
+ assert.deepEqual(moveIdBy(rows, "b", 1), insertIdAt(rows, "b", "c", "bottom"));
+ assert.deepEqual(moveIdBy(rows, "c", -1), insertIdAt(rows, "c", "b", "top"));
});
test("a saved order applies, and undragged rows stay on top in list order", () => {
diff --git a/studio/frontend/tests/sidebar-projects-nav-auto.test.ts b/studio/frontend/tests/sidebar-projects-nav-auto.test.ts
index e6531a825d1..d152592b99d 100644
--- a/studio/frontend/tests/sidebar-projects-nav-auto.test.ts
+++ b/studio/frontend/tests/sidebar-projects-nav-auto.test.ts
@@ -111,7 +111,7 @@ test("the rail keeps the Projects row, since the section is hidden there", async
const sidebar = await readSrcAsync("components/app-sidebar.tsx");
assert.match(
sidebar,
- /const projectsSectionShowing =\n\s*projectsSectionRendered && \(isMobile \|\| sidebarState !== "collapsed"\);/,
+ /const projectsSectionShowing =\n\s*projectsSectionConfigured && \(isMobile \|\| sidebarState !== "collapsed"\);/,
);
// The section itself still mounts on the rail, as it did before, and CSS hides it.
assert.match(sidebar, /\{projectsSectionRendered && \(/);
@@ -136,7 +136,7 @@ test("folders range-select within the list the row is in", async () => {
assert.match(sidebar, /rangeBetween\(orderedIds, anchorId, projectId\)/);
assert.match(
sidebar,
- /handleProjectSelectionClick\(event, project\.id, order\.orderedIds\)/,
+ /handleProjectSelectionClick\(\n\s*event,\n\s*project\.id,\n\s*order\.selectionIds \?\? order\.orderedIds,\n\s*\)/,
);
// Nothing reaches for the Projects list from inside the handler any more.
const handler = sidebar.slice(
@@ -165,3 +165,41 @@ test("the sidebar and the customizer resolve the row the same way", async () =>
/sidebarNavAuto: sidebarNavAutoAfterChoice\(sidebarNavAuto, item\.id\)/,
);
});
+
+// Train and Recipes list their runs where the folders go. The row read that as the section being
+// gone and pinned itself back to the top, so walking to Train turned a row the user had put away
+// back on, and walking back turned it off again.
+test("a route that borrows the section does not bring the row back", async () => {
+ const sidebar = await readSrcAsync("components/app-sidebar.tsx");
+ assert.match(
+ sidebar,
+ /const projectsSectionConfigured =\n\s*organizeBy === "project" && projects\.length > 0;/,
+ );
+ // The section itself still stands down on those routes; only the row stopped following it.
+ assert.match(
+ sidebar,
+ /const projectsSectionRendered =\n\s*!isStudioRoute && !showTrainingRecents && projectsSectionConfigured;/,
+ );
+ const showing = sidebar.slice(
+ sidebar.indexOf("const projectsSectionShowing ="),
+ sidebar.indexOf("const chatSort ="),
+ );
+ for (const route of ["isStudioRoute", "showTrainingRecents"]) {
+ assert.ok(
+ !showing.includes(route),
+ `the row still reads ${route}`,
+ );
+ }
+});
+
+// Both the sidebar and Customize sidebar decide the row's place, and a switch that disagrees with
+// the sidebar beside it is the bug in another form.
+test("the customizer reads the setting the same way", async () => {
+ const customizer = await readSrcAsync(
+ "features/settings/components/sidebar-nav-customizer.tsx",
+ );
+ assert.match(
+ customizer,
+ /const projectsSectionShowing =\n\s*organizeBy === "project" && projects\.length > 0;/,
+ );
+});
diff --git a/studio/frontend/tests/sidebar-row-actions.test.ts b/studio/frontend/tests/sidebar-row-actions.test.ts
new file mode 100644
index 00000000000..b8cc3093900
--- /dev/null
+++ b/studio/frontend/tests/sidebar-row-actions.test.ts
@@ -0,0 +1,192 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What a sidebar row offers without opening its menu, and what the menu says when it is opened.
+// A row action that only some rows carry, or a label that repeats the row it is on, is the kind
+// of thing that reads as missing rather than as absent.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readSrcAsync } from "./helpers/kit.ts";
+
+const APP_SIDEBAR = await readSrcAsync("components/app-sidebar.tsx");
+
+// The pin used to appear on a Recents row only once it was pinned, so the only way to pin one was
+// through the menu, while the project rows beside it had the one-click affordance all along.
+test("every chat row offers the pin without opening a menu", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /\{variant === "recent" && \(\n\s*<button\n\s*type="button"\n\s*onClick=\{\(e\) => \{\n\s*e\.stopPropagation\(\);\n\s*togglePinnedChat\(item\.id\);/,
+ );
+ // It says which way it goes, in its glyph and to a screen reader.
+ assert.ok(
+ !APP_SIDEBAR.includes('{variant === "recent" && isPinned && ('),
+ "the Recents pin is still gated on the row already being pinned",
+ );
+ assert.equal(
+ (
+ APP_SIDEBAR.match(
+ /aria-label=\{isPinned \? "Unpin chat" : "Pin chat"\}/g,
+ ) ?? []
+ ).length,
+ 2,
+ "a pin action stopped naming the state it moves to",
+ );
+ assert.equal(
+ (
+ APP_SIDEBAR.match(
+ /icon=\{isPinned \? PinOffIcon : PinIcon\} strokeWidth=\{1\.75\} className="size-icon"/g,
+ ) ?? []
+ ).length,
+ 3,
+ "a pin glyph no longer follows the row's state",
+ );
+});
+
+// Two actions overlay the right edge of every chat row now, so the room they need is the same on
+// every one of them rather than something the pinned rows alone reserved.
+test("a chat row reserves one gutter, whatever its state", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /showWorkSpinner \? "pr-16" : hasUnreadActivity \? "pr-7" : undefined,/,
+ );
+ assert.ok(
+ !APP_SIDEBAR.includes("hasSecondaryRowAction"),
+ "the gutter still branches on whether the row has a second action",
+ );
+ // One hover gutter for Recents and Pinned, one for the project rows, and one for the folders.
+ assert.equal(
+ (APP_SIDEBAR.match(/group-hover\/recent-item:pr-16/g) ?? []).length,
+ 2,
+ "the Recents gutter branched again",
+ );
+});
+
+// Renaming from the menu is two clicks and a read; the title is right there.
+test("double-clicking a chat title renames it in place", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /onDoubleClick=\{\(event\) => \{\n\s*event\.preventDefault\(\);\n\s*event\.stopPropagation\(\);\n\s*openRenameChat\(item, true, list\?\.scope\);\n\s*\}\}/,
+ );
+});
+
+// Marking one chat unread was only reachable by selecting it first and using the bulk menu, and
+// the dot could never be taken off again: the item was disabled on the rows that carried one.
+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}`,
+ );
+ }
+ // Both go by the dot the row already draws.
+ assert.match(
+ APP_SIDEBAR,
+ /const alreadyUnread = threadIds\.some\(\(threadId\) =>\n\s*unreadThreadIds\.has\(threadId\),\n\s*\);/,
+ );
+ // An eye that is open once the row is read, crossed out while it is not.
+ 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.
+test("a selection of unread rows can be marked read", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /const allSelectedUnread =\n\s*selectionCount > 0 &&\n\s*selectedChatItems\.every\(/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /function markSelectedRead\(\) \{\n\s*const threadIds = selectedChatItems\.flatMap\(getSidebarItemThreadIds\);\n\s*clearSelection\(\);\n\s*clearThreadsUnread\(threadIds\);\n\s*\}/,
+ );
+});
+
+// Two headers carrying the same pair of actions in opposite orders is the kind of thing the eye
+// catches without being able to name it.
+test("a section header puts its own action before the menu", () => {
+ const projects = APP_SIDEBAR.indexOf('aria-label="New project"');
+ const projectsMenu = APP_SIDEBAR.indexOf(
+ 't("shell.organize.organizeProjects")',
+ );
+ assert.ok(projects > 0 && projectsMenu > 0);
+ assert.ok(projects < projectsMenu, "Projects still opens with its menu");
+ const newChat = APP_SIDEBAR.indexOf(
+ 'aria-label={t("shell.navigation.newChat")}',
+ );
+ const recentsMenu = APP_SIDEBAR.indexOf('t("shell.organize.organizeChats")');
+ assert.ok(newChat > 0 && recentsMenu > 0);
+ assert.ok(newChat < recentsMenu, "Recents still opens with its menu");
+});
+
+// A menu opened from a chat row is already about that chat: "Pin chat" there only repeats what
+// the pointer just pointed at.
+test("the pin item says Pin, not what it is pinning", () => {
+ assert.match(APP_SIDEBAR, /<span>\{isPinned \? "Unpin" : "Pin"\}<\/span>/);
+ assert.match(
+ APP_SIDEBAR,
+ /<span>\{isProjectPinned \? "Unpin" : "Pin"\}<\/span>/,
+ );
+ for (const gone of [
+ '<span>{isPinned ? "Unpin chat" : "Pin chat"}</span>',
+ '<span>{isProjectPinned ? "Unpin project" : "Pin project"}</span>',
+ ]) {
+ assert.ok(!APP_SIDEBAR.includes(gone), `${gone} is still in a menu`);
+ }
+});
+
+// The disclosure is the section's, so the section is what reveals it: hunting for a chevron means
+// travelling to the header when the pointer is already in the list it collapses.
+test("a section's chevron appears on hovering anywhere in it", () => {
+ assert.equal(
+ (APP_SIDEBAR.match(/group\/sb-section/g) ?? []).length,
+ 4,
+ "a collapsible section is not its own hover group",
+ );
+ assert.equal(
+ (APP_SIDEBAR.match(/group-hover\/sb-section:opacity-100/g) ?? []).length,
+ 4,
+ "a section chevron still waits for its header to be hovered",
+ );
+ // Hovering the header itself still counts, and so does reaching it by keyboard.
+ assert.match(
+ APP_SIDEBAR,
+ /group-hover\/sb-section:opacity-100 group-hover\/sb-collap:opacity-100 group-focus-visible\/sb-collap:opacity-100/,
+ );
+});
+
+// "the card that created it" named nothing the user can point at.
+test("the chat-folder hint names what to click instead", () => {
+ assert.ok(
+ !APP_SIDEBAR.includes("card that created it"),
+ "the hint still sends the user to a card it never identifies",
+ );
+ assert.ok(
+ APP_SIDEBAR.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(
+ (APP_SIDEBAR.match(/Only the desktop app can open a chat's files folder/g) ??
+ []).length,
+ 2,
+ "the hint is no longer stated for both the pointer and the screen reader",
+ );
+});
diff --git a/studio/frontend/tests/sidebar-row-drag.test.ts b/studio/frontend/tests/sidebar-row-drag.test.ts
new file mode 100644
index 00000000000..f9ed6a43691
--- /dev/null
+++ b/studio/frontend/tests/sidebar-row-drag.test.ts
@@ -0,0 +1,840 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Dragging reorders sidebar rows and moves them between lists. One planner decides every drop,
+// so these ask it directly, then check the sidebar wires every row and section to it.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ dropEdgeAt,
+ folderRingKey,
+ planKey,
+ planSidebarDrop,
+ rowKey,
+ sectionRingKey,
+ STAY,
+ type SidebarDragItem,
+ type SidebarDropContext,
+ type SidebarDropZone,
+} from "../src/features/chat/lib/sidebar-drag.ts";
+import {
+ PINNED_ORDER_SCOPE,
+ PROJECT_ORDER_SCOPE,
+ projectOrderScope,
+ RECENTS_ORDER_SCOPE,
+ useSidebarOrganizationStore,
+} from "../src/features/chat/stores/sidebar-organization-store.ts";
+import { readSrcAsync } from "./helpers/kit.ts";
+
+const APP_SIDEBAR = await readSrcAsync("components/app-sidebar.tsx");
+const HOOK = await readSrcAsync("features/chat/hooks/use-sidebar-drag.ts");
+const EN = await readSrcAsync("i18n/locales/en.ts");
+
+// Two folders, "work" pinned and "home" not; chats c1 and c2 in work, c3 in home, r1 and r2 in
+// Recents, and p1 pinned from Recents. Pinned is one list: the folder, then the chat.
+function context(
+ overrides: Partial<SidebarDropContext> = {},
+): SidebarDropContext {
+ return {
+ organizeBy: "project",
+ chatSort: "priority",
+ pinnedSort: "manual",
+ pinnedChatIds: new Set(["p1"]),
+ pinnedProjectIds: new Set(["work"]),
+ orders: {
+ pinned: ["work", "p1"],
+ projects: ["home", "misc"],
+ recents: ["r1", "r2"],
+ projectChats: (projectId) =>
+ ({ work: ["c1", "c2"], home: ["c3"], misc: [] })[projectId] ?? [],
+ },
+ reorderSwitchesSort: true,
+ ...overrides,
+ };
+}
+
+const chat = (
+ id: string,
+ section: SidebarDragItem["section"],
+ scope: string,
+ projectId: string | null,
+): SidebarDragItem => ({ kind: "chat", id, section, scope, projectId });
+const folder = (
+ id: string,
+ section: SidebarDragItem["section"],
+ scope: string,
+): SidebarDragItem => ({ kind: "project", id, section, scope, projectId: null });
+
+const chatRow = (
+ section: SidebarDropZone["section"],
+ scope: string,
+ id: string,
+ folderId?: string,
+ block?: { index: number; count: number },
+): SidebarDropZone => ({
+ section,
+ row: { id, kind: "chat", scope },
+ folderId,
+ block,
+});
+const folderRow = (
+ section: SidebarDropZone["section"],
+ scope: string,
+ id: string,
+): SidebarDropZone => ({
+ section,
+ row: { id, kind: "project", scope },
+ folderId: id,
+});
+
+test("the edge is which half of the row the pointer is over", () => {
+ assert.equal(dropEdgeAt({ top: 100, height: 30 }, 110), "top");
+ assert.equal(dropEdgeAt({ top: 100, height: 30 }, 115), "bottom");
+ assert.equal(dropEdgeAt({ top: 100, height: 30 }, 129), "bottom");
+});
+
+test("a chat reorders within its own list, on the edge under the pointer", () => {
+ const plan = planSidebarDrop(
+ chat("r2", "recents", RECENTS_ORDER_SCOPE, null),
+ chatRow("recents", RECENTS_ORDER_SCOPE, "r1"),
+ "top",
+ context({ chatSort: "manual" }),
+ );
+ assert.ok(plan);
+ assert.deepEqual(plan.action, { kind: "reorder" });
+ assert.deepEqual(plan.cue, {
+ line: { rowKey: rowKey(RECENTS_ORDER_SCOPE, "r1"), edge: "top" },
+ });
+ assert.deepEqual(plan.effects.orders, [
+ { scope: RECENTS_ORDER_SCOPE, ids: ["r2", "r1"] },
+ ]);
+ assert.equal(plan.effects.switchSort, undefined);
+});
+
+// A sorted list would undo the drop, so it switches to Manual, unless the user turned that off.
+test("a reorder in a sorted list switches it to Manual order, or is refused", () => {
+ const drag = chat("r2", "recents", RECENTS_ORDER_SCOPE, null);
+ const zone = chatRow("recents", RECENTS_ORDER_SCOPE, "r1");
+ const switching = planSidebarDrop(drag, zone, "top", context());
+ assert.equal(switching?.effects.switchSort, "chats");
+ const pinnedDrag = chat("p1", "pinned", PINNED_ORDER_SCOPE, null);
+ const pinnedZone = chatRow("pinned", PINNED_ORDER_SCOPE, "p2");
+ const pinnedSwitch = planSidebarDrop(
+ pinnedDrag,
+ pinnedZone,
+ "bottom",
+ context({
+ pinnedSort: "updated",
+ pinnedChatIds: new Set(["p1", "p2"]),
+ orders: { ...context().orders, pinned: ["work", "p1", "p2"] },
+ }),
+ );
+ assert.equal(pinnedSwitch?.effects.switchSort, "pinned");
+ assert.equal(
+ planSidebarDrop(drag, zone, "top", context({ reorderSwitchesSort: false })),
+ null,
+ );
+ // And a list already on Manual never asks.
+ assert.equal(
+ planSidebarDrop(
+ drag,
+ zone,
+ "top",
+ context({ chatSort: "manual", reorderSwitchesSort: false }),
+ )?.action.kind,
+ "reorder",
+ );
+});
+
+// An edge the row is already on is not a move, and a line there would promise one. The spot
+// still answers, with STAY, so the section around it does not offer its last slot instead.
+test("an edge that moves nothing stays, and still claims the drag", () => {
+ const ctx = context({ chatSort: "manual" });
+ assert.equal(
+ planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE, null),
+ chatRow("recents", RECENTS_ORDER_SCOPE, "r2"),
+ "top",
+ ctx,
+ ),
+ STAY,
+ );
+ assert.equal(
+ planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE, null),
+ chatRow("recents", RECENTS_ORDER_SCOPE, "r1"),
+ "bottom",
+ ctx,
+ ),
+ STAY,
+ );
+ // A pinned row over its own row, or a folder over its own block, is where it already is.
+ assert.equal(
+ planSidebarDrop(
+ chat("p1", "pinned", PINNED_ORDER_SCOPE, null),
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "top",
+ ctx,
+ ),
+ STAY,
+ );
+ assert.equal(
+ planSidebarDrop(
+ folder("work", "pinned", PINNED_ORDER_SCOPE),
+ folderRow("pinned", PINNED_ORDER_SCOPE, "work"),
+ "bottom",
+ ctx,
+ ),
+ STAY,
+ );
+});
+
+test("a chat dropped on a folder, its chats or its empty line is filed there", () => {
+ const drag = chat("r1", "recents", RECENTS_ORDER_SCOPE, null);
+ for (const zone of [
+ folderRow("projects", PROJECT_ORDER_SCOPE, "home"),
+ chatRow("projects", projectOrderScope("home"), "c3", "home", {
+ index: 0,
+ count: 1,
+ }),
+ { section: "projects", folderId: "misc" } as SidebarDropZone,
+ // A pinned folder files it from its chats, or from the lower half of its row.
+ chatRow("pinned", projectOrderScope("work"), "c1", "work", { index: 0, count: 2 }),
+ { ...folderRow("pinned", PINNED_ORDER_SCOPE, "work"), edge: "bottom" },
+ ] as Array<SidebarDropZone & { edge?: "top" | "bottom" }>) {
+ const plan = planSidebarDrop(drag, zone, zone.edge ?? "top", context());
+ assert.ok(plan, `no plan for ${JSON.stringify(zone)}`);
+ assert.deepEqual(plan.action, { kind: "move", projectId: zone.folderId });
+ assert.deepEqual(plan.cue, { ring: folderRingKey(zone.folderId!) });
+ assert.deepEqual(plan.effects.moveChat, {
+ chatId: "r1",
+ projectId: zone.folderId,
+ });
+ assert.equal(plan.effects.unpinChat, undefined);
+ }
+ // Dropped on the folder it is already in, it stays: no move, and the folder is not lit.
+ assert.equal(
+ planSidebarDrop(
+ chat("c3", "projects", projectOrderScope("home"), "home"),
+ folderRow("projects", PROJECT_ORDER_SCOPE, "home"),
+ "top",
+ context(),
+ ),
+ STAY,
+ );
+});
+
+// A folder on Manual order has real slots, so an arriving chat lands in the one under the pointer.
+test("a chat filed into a folder on Manual order lands in the slot it dropped on", () => {
+ const plan = planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE, null),
+ chatRow("pinned", projectOrderScope("work"), "c2", "work", {
+ index: 1,
+ count: 2,
+ }),
+ "top",
+ context({ chatSort: "manual" }),
+ );
+ assert.ok(plan);
+ assert.deepEqual(plan.cue, {
+ line: { rowKey: rowKey(projectOrderScope("work"), "c2"), edge: "top" },
+ });
+ // The slot travels with the snapshot, so a move that lands late can re-aim it.
+ assert.deepEqual(plan.effects.orders, [
+ {
+ scope: projectOrderScope("work"),
+ ids: ["c1", "r1", "c2"],
+ place: { id: "r1", targetId: "c2", edge: "top" },
+ },
+ ]);
+});
+
+test("a chat dropped on Recents leaves its folder and its pin", () => {
+ // Out of a folder.
+ const unfiled = planSidebarDrop(
+ chat("c3", "projects", projectOrderScope("home"), "home"),
+ { section: "recents" },
+ "top",
+ context(),
+ );
+ assert.ok(unfiled);
+ assert.deepEqual(unfiled.action, { kind: "move", projectId: null });
+ assert.deepEqual(unfiled.cue, { ring: sectionRingKey("recents") });
+ assert.deepEqual(unfiled.effects.moveChat, { chatId: "c3", projectId: null });
+ // Out of Pinned: the pin goes, and so does the folder that would keep it out of Recents.
+ const unpinned = planSidebarDrop(
+ chat("p1", "pinned", PINNED_ORDER_SCOPE, "home"),
+ chatRow("recents", RECENTS_ORDER_SCOPE, "r1"),
+ "top",
+ context(),
+ );
+ assert.ok(unpinned);
+ assert.equal(unpinned.effects.unpinChat, "p1");
+ assert.deepEqual(unpinned.effects.moveChat, { chatId: "p1", projectId: null });
+ // With folders off every chat is already a Recents row, so only the pin goes.
+ const listMode = planSidebarDrop(
+ chat("p1", "pinned", PINNED_ORDER_SCOPE, "home"),
+ { section: "recents", header: true },
+ "top",
+ context({ organizeBy: "list" }),
+ );
+ assert.deepEqual(listMode?.action, { kind: "unpin" });
+ assert.equal(listMode?.effects.moveChat, undefined);
+ // A Recents row dropped on the section itself has no slot to move to.
+ assert.equal(
+ planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE, null),
+ { section: "recents" },
+ "top",
+ context(),
+ ),
+ null,
+ );
+});
+
+test("a chat dropped into Pinned is pinned where it lands", () => {
+ const drag = chat("r1", "recents", RECENTS_ORDER_SCOPE, null);
+ const onRow = planSidebarDrop(
+ drag,
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "top",
+ context(),
+ );
+ assert.ok(onRow);
+ assert.deepEqual(onRow.action, { kind: "pin" });
+ assert.equal(onRow.effects.pinChat, "r1");
+ assert.deepEqual(onRow.cue, {
+ line: { rowKey: rowKey(PINNED_ORDER_SCOPE, "p1"), edge: "top" },
+ });
+ assert.deepEqual(onRow.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["work", "r1", "p1"] },
+ ]);
+ // Pinned is one list, so the very top is above its first row whatever kind that is: the
+ // header, or the upper half of a folder row, both draw the line there.
+ for (const zone of [
+ { section: "pinned", header: true, row: { id: "work", kind: "project", scope: PINNED_ORDER_SCOPE } },
+ folderRow("pinned", PINNED_ORDER_SCOPE, "work"),
+ ] as SidebarDropZone[]) {
+ const plan = planSidebarDrop(drag, zone, "top", context());
+ assert.deepEqual(plan?.action, { kind: "pin" });
+ assert.deepEqual(plan?.cue, {
+ line: { rowKey: rowKey(PINNED_ORDER_SCOPE, "work"), edge: "top" },
+ });
+ assert.deepEqual(plan?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["r1", "work", "p1"] },
+ ]);
+ }
+ // The space under the rows lands it last, with a line under the last row, never a ring.
+ const under = planSidebarDrop(drag, { section: "pinned" }, "bottom", context());
+ assert.deepEqual(under?.cue, {
+ line: { rowKey: rowKey(PINNED_ORDER_SCOPE, "p1"), edge: "bottom" },
+ });
+ assert.deepEqual(under?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["work", "p1", "r1"] },
+ ]);
+ // Pinned sorted by a rule would move the row again, so the drop takes it to Manual.
+ assert.equal(
+ planSidebarDrop(drag, { section: "pinned" }, "bottom", context({ pinnedSort: "updated" }))
+ ?.effects.switchSort,
+ "pinned",
+ );
+ // A chat already pinned is not pinned again: it reorders, and the last row stays last.
+ assert.equal(
+ planSidebarDrop(
+ chat("p1", "pinned", PINNED_ORDER_SCOPE, null),
+ { section: "pinned" },
+ "bottom",
+ context(),
+ ),
+ STAY,
+ );
+});
+
+// Dragging a pinned chat onto a folder under Projects unpins it, and files it when the folder
+// is another one. Onto a pinned folder it keeps its pin.
+test("a pinned chat dragged onto a folder is unpinned, and filed when the folder is new", () => {
+ const ctx = context({
+ pinnedChatIds: new Set(["p1", "c3"]),
+ orders: { ...context().orders, pinned: ["work", "p1", "c3"] },
+ });
+ const ownFolder = planSidebarDrop(
+ chat("c3", "pinned", PINNED_ORDER_SCOPE, "home"),
+ folderRow("projects", PROJECT_ORDER_SCOPE, "home"),
+ "top",
+ ctx,
+ );
+ assert.deepEqual(ownFolder?.action, { kind: "unpin" });
+ assert.equal(ownFolder?.effects.unpinChat, "c3");
+ assert.equal(ownFolder?.effects.moveChat, undefined);
+ const otherFolder = planSidebarDrop(
+ chat("c3", "pinned", PINNED_ORDER_SCOPE, "home"),
+ folderRow("projects", PROJECT_ORDER_SCOPE, "misc"),
+ "top",
+ ctx,
+ );
+ assert.deepEqual(otherFolder?.action, { kind: "move", projectId: "misc" });
+ assert.equal(otherFolder?.effects.unpinChat, "c3");
+ // In Pinned the folder row's upper half is a slot, so the file lands on its lower half.
+ const pinnedFolder = planSidebarDrop(
+ chat("c3", "pinned", PINNED_ORDER_SCOPE, "home"),
+ folderRow("pinned", PINNED_ORDER_SCOPE, "work"),
+ "bottom",
+ ctx,
+ );
+ assert.deepEqual(pinnedFolder?.action, { kind: "move", projectId: "work" });
+ assert.equal(pinnedFolder?.effects.unpinChat, undefined);
+});
+
+test("a folder reorders among its own list, and the block under it aims at it", () => {
+ const ctx = context({
+ pinnedProjectIds: new Set(["work", "play"]),
+ orders: { ...context().orders, pinned: ["work", "p1", "play"] },
+ });
+ // Over the other folder's row.
+ const onRow = planSidebarDrop(
+ folder("play", "pinned", PINNED_ORDER_SCOPE),
+ folderRow("pinned", PINNED_ORDER_SCOPE, "work"),
+ "top",
+ ctx,
+ );
+ assert.deepEqual(onRow?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["play", "work", "p1"] },
+ ]);
+ // Over the chats under it: the top half of the block aims above the folder, the bottom half
+ // below it, so the line flips once, in the middle. Below draws under the block's last row.
+ const upper = planSidebarDrop(
+ folder("play", "pinned", PINNED_ORDER_SCOPE),
+ chatRow("pinned", projectOrderScope("work"), "c1", "work", { index: 0, count: 2 }),
+ "top",
+ ctx,
+ );
+ assert.deepEqual(upper?.cue, {
+ line: { rowKey: rowKey(PINNED_ORDER_SCOPE, "work"), edge: "top" },
+ });
+ const lower = planSidebarDrop(
+ folder("play", "pinned", PINNED_ORDER_SCOPE),
+ {
+ ...chatRow("pinned", projectOrderScope("work"), "c2", "work", { index: 1, count: 2 }),
+ blockEnd: { scope: projectOrderScope("work"), id: "c2" },
+ },
+ "bottom",
+ ctx,
+ );
+ assert.deepEqual(lower?.cue, {
+ line: { rowKey: rowKey(projectOrderScope("work"), "c2"), edge: "bottom" },
+ });
+ assert.deepEqual(lower?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["work", "play", "p1"] },
+ ]);
+ // Over a block's own rows, Show more or an empty folder, it lands below that folder.
+ const tail = planSidebarDrop(
+ folder("play", "pinned", PINNED_ORDER_SCOPE),
+ {
+ section: "pinned",
+ folderId: "work",
+ blockEnd: { scope: projectOrderScope("work"), id: "c2" },
+ },
+ "top",
+ ctx,
+ );
+ assert.deepEqual(tail?.cue, {
+ line: { rowKey: rowKey(projectOrderScope("work"), "c2"), edge: "bottom" },
+ });
+ assert.deepEqual(tail?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["work", "play", "p1"] },
+ ]);
+ // A folder lands between pinned chats too: Pinned is one list.
+ const belowChat = planSidebarDrop(
+ folder("work", "pinned", PINNED_ORDER_SCOPE),
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "bottom",
+ ctx,
+ );
+ assert.deepEqual(belowChat?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["p1", "work", "play"] },
+ ]);
+ // Its own block keeps it where it is, and Recents is no target at all.
+ assert.equal(
+ planSidebarDrop(
+ folder("work", "pinned", PINNED_ORDER_SCOPE),
+ chatRow("pinned", projectOrderScope("work"), "c1", "work", { index: 0, count: 2 }),
+ "top",
+ ctx,
+ ),
+ STAY,
+ );
+ assert.equal(
+ planSidebarDrop(
+ folder("work", "pinned", PINNED_ORDER_SCOPE),
+ chatRow("recents", RECENTS_ORDER_SCOPE, "r1"),
+ "top",
+ ctx,
+ ),
+ null,
+ );
+});
+
+test("a folder dragged into Pinned is pinned where it lands, and back out is unpinned", () => {
+ const pin = planSidebarDrop(
+ folder("home", "projects", PROJECT_ORDER_SCOPE),
+ folderRow("pinned", PINNED_ORDER_SCOPE, "work"),
+ "top",
+ context(),
+ );
+ assert.deepEqual(pin?.action, { kind: "pin" });
+ assert.equal(pin?.effects.pinProject, "home");
+ assert.deepEqual(pin?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["home", "work", "p1"] },
+ ]);
+ // Over a pinned chat: the slot the line shows, since Pinned is one list.
+ const onChat = planSidebarDrop(
+ folder("home", "projects", PROJECT_ORDER_SCOPE),
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "top",
+ context(),
+ );
+ assert.deepEqual(onChat?.cue, {
+ line: { rowKey: rowKey(PINNED_ORDER_SCOPE, "p1"), edge: "top" },
+ });
+ assert.deepEqual(onChat?.effects.orders, [
+ { scope: PINNED_ORDER_SCOPE, ids: ["work", "home", "p1"] },
+ ]);
+ // Pinned sorted by a rule would move the row again, so the drop takes it to Manual.
+ assert.equal(
+ planSidebarDrop(
+ folder("home", "projects", PROJECT_ORDER_SCOPE),
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "top",
+ context({ pinnedSort: "updated" }),
+ )?.effects.switchSort,
+ "pinned",
+ );
+ const unpin = planSidebarDrop(
+ folder("work", "pinned", PINNED_ORDER_SCOPE),
+ folderRow("projects", PROJECT_ORDER_SCOPE, "misc"),
+ "bottom",
+ context(),
+ );
+ assert.deepEqual(unpin?.action, { kind: "unpin" });
+ assert.equal(unpin?.effects.unpinProject, "work");
+ assert.deepEqual(unpin?.effects.orders, [
+ { scope: PROJECT_ORDER_SCOPE, ids: ["home", "misc", "work"] },
+ ]);
+ const unpinOnHeader = planSidebarDrop(
+ folder("work", "pinned", PINNED_ORDER_SCOPE),
+ { section: "projects", header: true },
+ "top",
+ context(),
+ );
+ assert.deepEqual(unpinOnHeader?.cue, { ring: sectionRingKey("projects") });
+});
+
+// The gap between a header and its first row is where "above the first row" is aimed, so the
+// header stands for that edge for a drag of the same kind, and for the bare section otherwise.
+test("a section header stands for the top of its first row", () => {
+ const ctx = context({ chatSort: "manual" });
+ const aboveFirstChat = planSidebarDrop(
+ chat("r2", "recents", RECENTS_ORDER_SCOPE, null),
+ { section: "recents", header: true, row: { id: "r1", kind: "chat", scope: RECENTS_ORDER_SCOPE } },
+ "bottom",
+ ctx,
+ );
+ assert.deepEqual(aboveFirstChat?.cue, {
+ line: { rowKey: rowKey(RECENTS_ORDER_SCOPE, "r1"), edge: "top" },
+ });
+ assert.deepEqual(aboveFirstChat?.effects.orders, [
+ { scope: RECENTS_ORDER_SCOPE, ids: ["r2", "r1"] },
+ ]);
+ const aboveFirstFolder = planSidebarDrop(
+ folder("misc", "projects", PROJECT_ORDER_SCOPE),
+ { section: "projects", header: true, row: { id: "home", kind: "project", scope: PROJECT_ORDER_SCOPE } },
+ "bottom",
+ ctx,
+ );
+ assert.deepEqual(aboveFirstFolder?.cue, {
+ line: { rowKey: rowKey(PROJECT_ORDER_SCOPE, "home"), edge: "top" },
+ });
+ // A chat over the Projects header does not file into the first folder.
+ assert.equal(
+ planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE, null),
+ { section: "projects", header: true, row: { id: "home", kind: "project", scope: PROJECT_ORDER_SCOPE } },
+ "top",
+ ctx,
+ ),
+ null,
+ );
+ // Pinned is not conjured up for a drag: it is on screen only when it has rows.
+ assert.ok(!APP_SIDEBAR.includes("pinnedTakesDrag"));
+ assert.ok(!APP_SIDEBAR.includes("dropToPin"));
+ assert.ok(!EN.includes("dropToPin:"));
+});
+
+// Equal plans must not re-render the sidebar.
+test("a plan's key changes exactly when what it paints or says does", () => {
+ const ctx = context();
+ const a = planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE, null),
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "top",
+ ctx,
+ );
+ const b = planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE, null),
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "bottom",
+ ctx,
+ );
+ assert.equal(planKey(a), planKey({ ...a! }));
+ assert.notEqual(planKey(a), planKey(b));
+ assert.equal(planKey(null), "");
+});
+
+// Every row and section describes itself to the same planner.
+test("every row and section is wired to the planner", () => {
+ // Chat rows carry their section and folder, and their place in the folder's block.
+ assert.match(
+ APP_SIDEBAR,
+ /\{\.\.\.dnd\.dropZoneProps\(\{\n\s*section: list\.section,\n\s*row: \{ id: item\.id, kind: "chat", scope: list\.scope \},\n\s*folderId: list\.folderId,/,
+ );
+ // Folder rows are a zone of their folder, and open under a resting pointer while closed.
+ assert.match(
+ APP_SIDEBAR,
+ /row: \{ id: project\.id, kind: "project", scope: order\.scope \},\n\s*folderId: project\.id,\n\s*blockEnd,\n\s*\},\n\s*\{ closed: !expanded \},/,
+ );
+ // An empty folder's line and its "Show more" row are the folder's block too.
+ assert.equal(
+ (
+ APP_SIDEBAR.match(
+ /\{\.\.\.dnd\.dropZoneProps\(\{ section: order\.section, folderId: project\.id, blockEnd \}\)\}/g,
+ ) ?? []
+ ).length,
+ 2,
+ );
+ // Each section's body and its header, which stands for the top of its first row.
+ for (const section of ["pinned", "projects", "recents"]) {
+ assert.ok(
+ APP_SIDEBAR.includes(`{...dnd.dropZoneProps({ section: "${section}" })}`),
+ `${section} body is not a zone`,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ new RegExp(`section: "${section}",\\n\\s*header: true,\\n\\s*row:`),
+ `${section} header is not a zone`,
+ );
+ }
+ // Each list hands its rows the section they are drawn in.
+ for (const wiring of [
+ // Pinned is one list: its folders and chats share the order a drag rewrites.
+ 'scope: PINNED_ORDER_SCOPE,\n orderedIds: pinnedRowIds,\n selectionIds: pinnedProjectRowIds,\n section: "pinned",',
+ 'scope: PINNED_ORDER_SCOPE,\n ids: pinnedChatRowIds,\n orderIds: pinnedRowIds,\n section: "pinned",',
+ 'scope: RECENTS_ORDER_SCOPE,\n ids: recentRowIds,\n section: "recents",',
+ 'orderedIds: projectRowIds,\n section: "projects",',
+ ]) {
+ assert.ok(APP_SIDEBAR.includes(wiring), `missing ${wiring}`);
+ }
+});
+
+// A dragover can land in the same frame as its dragstart, before state commits.
+test("the dragged row is known before React re-renders", async () => {
+ const store = await readSrcAsync("features/chat/stores/sidebar-drag-source.ts");
+ assert.match(store, /let source: SidebarDragItem \| null = null;/);
+ assert.match(HOOK, /setSidebarDragSource\(item\);\n\s*setDrag\(item\);/);
+ // Every handler reads it from there; the state is only what paints.
+ assert.equal((HOOK.match(/const dragged = sidebarDragSource\(\);/g) ?? []).length, 2);
+ assert.ok(!/const dragged = drag;/.test(HOOK));
+});
+
+// dragleave fires for every child crossed, so one document listener clears the cue instead.
+test("a cue over nothing is cleared without trusting dragleave", () => {
+ assert.ok(!HOOK.includes("onDragLeave"));
+ assert.ok(!APP_SIDEBAR.includes("onDragLeave"));
+ assert.match(HOOK, /lastHandledEvent = event\.nativeEvent;/);
+ assert.match(HOOK, /if \(lastHandledEvent !== event\) \{\n\s*cancelSpring\(\);\n\s*showPlan\(null\);/);
+ // No answer lets the outer zone answer; an answer marks the event rather than stopping it.
+ assert.match(HOOK, /if \(!next\) return;\n\s*event\.preventDefault\(\);\n\s*lastHandledEvent = event\.nativeEvent;/);
+ assert.ok(!HOOK.includes("event.stopPropagation();\n lastHandledEvent"));
+ assert.match(HOOK, /if \(!dragged \|\| lastHandledEvent === event\.nativeEvent\) return;/);
+});
+
+// Over its own row a lifted row is already home. The row claims the drag and paints nothing,
+// so the section body never gets to offer its last slot for it.
+test("a row over itself claims the drag and paints nothing", () => {
+ assert.match(
+ HOOK,
+ /if \(next === STAY\) \{\n\s*\/\/[^\n]*\n\s*cancelSpring\(\);\n\s*showPlan\(null\);\n\s*return;\n\s*\}/,
+ );
+ assert.match(HOOK, /if \(next !== STAY\) optionsRef\.current\.onDrop\(next, dragged\);/);
+});
+
+// A chat's row stays on screen while its move is written, so it can be dropped again before the
+// first move lands. Moves of one chat run in order, and only the latest drop commits its slot and
+// pin, so an earlier drop cannot land after a later one or park its order in a folder the chat
+// never finally joined.
+test("a chat dropped again before its move lands keeps only the latest drop", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /const chatMovesRef = useRef\(\n\s*new Map<string, \{ generation: number; chain: Promise<unknown> \}>\(\),\n\s*\);/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /const generation = \(previous\?\.generation \?\? 0\) \+ 1;\n\s*const chain = \(previous\?\.chain \?\? Promise\.resolve\(\)\)\n\s*\.then\(\(\) => moveChatToProject\(item, move\.projectId\)\)/,
+ );
+ assert.match(APP_SIDEBAR, /moves\.set\(item\.id, \{ generation, chain \}\);/);
+});
+
+// The menu keeps a 1px gap between rows. A pointer on it would hit the section, whose answer
+// is its last slot, so every draggable row's box reaches over the gap below it.
+test("rows cover the gap between them, so the section never answers for it", () => {
+ assert.match(APP_SIDEBAR, /const DROP_ROW_HIT = "pb-px -mb-px";/);
+ assert.match(
+ APP_SIDEBAR,
+ /: "group\/recent-item relative",\n\s*DROP_ROW_HIT,\n\s*\);/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /"group\/recent-item relative",\n\s*DROP_ROW_HIT,\n\s*draggingRow\?\.id === project\.id/,
+ );
+});
+
+// A section's collapsible clips its overflow, so cues stay inside the row.
+test("every drop cue is drawn inside its row", () => {
+ for (const cue of [
+ "${DROP_CUE_BASE} before:top-0",
+ "${DROP_CUE_BASE} before:bottom-0",
+ "before:inset-x-1 before:inset-y-0 ",
+ // A ring is drawn outside its box unless inset, and the first row's box ends at the clip.
+ "before:ring-1 before:ring-inset",
+ ]) {
+ assert.ok(APP_SIDEBAR.includes(cue), `no cue is drawn at ${cue}`);
+ }
+ assert.ok(
+ !/before:-inset-y-px|before:-top-px|before:-bottom-px/.test(APP_SIDEBAR),
+ "a cue still hangs outside its row, where a clipped section cuts it off",
+ );
+});
+
+// Alt + arrow is the keyboard's reorder.
+test("alt and an arrow reorder a row without a pointer", async () => {
+ assert.match(
+ APP_SIDEBAR,
+ /onKeyDown: \(event: React\.KeyboardEvent\) => \{\n\s*if \(\n\s*!event\.altKey \|\|\n\s*\(event\.key !== "ArrowUp" && event\.key !== "ArrowDown"\)\n\s*\)/,
+ );
+ assert.match(APP_SIDEBAR, /reorderRowBy\(item, orderedIds, sort, event\.key === "ArrowDown" \? 1 : -1\);/);
+ // Same rule as a drop.
+ assert.match(APP_SIDEBAR, /if \(resorts && !reorderSwitchesSort\) return;/);
+ // A touch browser starts no drag, so its row menus keep Move up and Move down.
+ assert.match(APP_SIDEBAR, /function renderMoveRowItems\(/);
+ // A pinned folder moves under Pinned's sort rule, from the keyboard and the touch menu alike:
+ // a sorted list switches to Manual, or refuses, exactly as a drop does.
+ assert.match(
+ APP_SIDEBAR,
+ /orderedIds: order\.orderedIds,\n\s*sort: order\.sort,\n\s*\}\)\}/,
+ );
+ assert.match(APP_SIDEBAR, /order\.orderedIds,\n\s*order\.sort,\n\s*\)\}/);
+ assert.match(
+ APP_SIDEBAR,
+ /selectionIds: pinnedProjectRowIds,\n\s*section: "pinned",\n\s*sort: \{ value: pinnedSort, set: setPinnedSort \},/,
+ );
+ assert.match(APP_SIDEBAR, /if \(!coarsePointer\) return null;/);
+ assert.match(APP_SIDEBAR, /const coarsePointer = useIsCoarsePointer\(\);/);
+ // Any touch pointer counts: a laptop with a touchscreen keeps the items too.
+ const MOBILE = await readSrcAsync("hooks/use-mobile.ts");
+ assert.match(MOBILE, /const COARSE_POINTER_QUERY = "\(any-pointer: coarse\)";/);
+ for (const key of ["moveUp", "moveDown"]) {
+ assert.ok(EN.includes(`${key}:`), `${key} is missing from the en locale`);
+ }
+ // Both paths share the reorder, so both honour the sort rule.
+ assert.equal((APP_SIDEBAR.match(/reorderRowBy\(item, orderedIds, sort, /g) ?? []).length, 3);
+});
+
+// The hint names every kind of drop.
+test("the hint beside the cursor names every kind of drop", () => {
+ for (const key of ["reorder", "pin", "unpin", "moveTo", "moveToRecents"]) {
+ assert.ok(EN.includes(`${key}:`), `${key} is missing from the en locale`);
+ }
+ for (const use of [
+ 't("shell.drag.pin")',
+ 't("shell.drag.unpin")',
+ 't("shell.drag.reorder")',
+ 't("shell.drag.moveToRecents")',
+ 't("shell.drag.moveTo", { name })',
+ ]) {
+ assert.ok(APP_SIDEBAR.includes(use), `${use} is never rendered`);
+ }
+ // In a portal, and only while the user wants it.
+ assert.match(APP_SIDEBAR, /draggingRow && dragHints && typeof document !== "undefined"\n\s*\? createPortal\(/);
+ assert.ok(APP_SIDEBAR.includes('data-testid="sidebar-drop-hint"'));
+});
+
+// The three preferences persist and sit in the Organize menu.
+test("drag-and-drop preferences persist and show in the Organize menu", () => {
+ const state = useSidebarOrganizationStore.getState();
+ assert.equal(state.dragHints, true);
+ assert.equal(state.reorderSwitchesSort, true);
+ assert.equal(state.dragOpensFolders, true);
+ state.setDragHints(false);
+ state.setReorderSwitchesSort(false);
+ state.setDragOpensFolders(false);
+ const next = useSidebarOrganizationStore.getState();
+ assert.equal(next.dragHints, false);
+ assert.equal(next.reorderSwitchesSort, false);
+ assert.equal(next.dragOpensFolders, false);
+ for (const key of ["dragDrop", "dragHints", "reorderSwitchesSort", "dragOpensFolders"]) {
+ assert.ok(EN.includes(`${key}:`), `${key} is missing from the en locale`);
+ assert.ok(APP_SIDEBAR.includes(`shell.organize.${key}`), `${key} is never rendered`);
+ }
+ assert.match(APP_SIDEBAR, /<DropdownMenuCheckboxItem\n\s*key=\{option\.key\}\n\s*checked=\{option\.get\(\)\}/);
+});
+
+// Resting on a closed folder or section opens it.
+test("a closed folder or section opens under a resting pointer", () => {
+ assert.match(HOOK, /export const SPRING_OPEN_DELAY_MS = \d+;/);
+ assert.match(
+ APP_SIDEBAR,
+ /onSpringOpen: \(zone\) => \{\n\s*if \(zone\.folderId\) \{\n\s*if \(collapsedProjectIds\.has\(zone\.folderId\)\) \{\n\s*toggleProjectCollapsed\(zone\.folderId\);/,
+ );
+ assert.match(APP_SIDEBAR, /if \(zone\.section === "pinned"\) setPinnedOpen\(true\);/);
+ assert.match(APP_SIDEBAR, /springOpen: dragOpensFolders,/);
+});
+
+// A chat dropped into a folder or Recents is moved, and the move can fail. Its slot in the new
+// list and the pin it sheds both wait for the move, or a failed drop would leave the chat
+// unpinned, or parked in the manual order of a list it never reached.
+test("a drop that moves writes its slot and takes the pin off after the move", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /if \(effects\.unpinChat && !effects\.moveChat && pinnedIdSet\.has\(effects\.unpinChat\)\)/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /const move = effects\.moveChat;\n\s*if \(!move\) \{\n\s*applyOrders\(\);\n\s*return;\n\s*\}/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /\.then\(\(\) => moveChatToProject\(item, move\.projectId\)\)\n\s*\.then\(\(moved\) => \{\n\s*if \(!moved \|\| moves\.get\(item\.id\)\?\.generation !== generation\) return;\n\s*applyOrders\(ordersBefore\);\n\s*if \(unpinAfter\) usePinnedChatsStore\.getState\(\)\.unpin\(unpinAfter\);/,
+ );
+ // And nothing else in commitDrop writes an order on its own.
+ const commit = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("function commitDrop("),
+ APP_SIDEBAR.indexOf("function dropCueClass("),
+ );
+ assert.equal((commit.match(/setManualOrder\(/g) ?? []).length, 1);
+ // A slow move can be overtaken by a reorder of the list it lands in. The slot is re-aimed at
+ // the list as it stands then, not written from the snapshot taken at the drop.
+ assert.match(
+ APP_SIDEBAR,
+ /const ordersBefore = useSidebarOrganizationStore\.getState\(\)\.manualOrder;\n\s*const moves = chatMovesRef\.current;/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /before \? landedOrder\(order, before\[order\.scope\]\) : order\.ids,/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /if \(!order\.place \|\| !current \|\| current === before\) return order\.ids;\n\s*return placeIdAt\(current, order\.place\.id, order\.place\.targetId, order\.place\.edge\);/,
+ );
+ assert.match(APP_SIDEBAR, /\): Promise<boolean> \{\n\s*if \(item\.projectId === projectId\) return true;/);
+});
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 97b46f681a7..f130877c8ac 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
@@ -39,8 +39,10 @@ test("an open row menu reserves the same gutter hover does", () => {
);
seen.push(`${openGroup}:${openPad}`);
}
- // Project chat, pinned chat, spinner, plain recents and folder rows.
- assert.ok(seen.length >= 5, `only ${seen.length} rows carry both gutters`);
+ // Project chat rows, every row of Pinned and Recents, and the folder rows. The chat rows'
+ // branches collapsed into one when the pin became a fixture of every row rather than of the
+ // pinned ones, so this counts kinds of row, not branches.
+ assert.ok(seen.length >= 3, `only ${seen.length} rows carry both gutters`);
});
// The kebab reveals itself while its menu is open, but the quick-action beside it was
@@ -91,7 +93,7 @@ test("a folder row's icon follows its disclosure", () => {
test("an empty open folder says it is empty", () => {
assert.match(
APP_SIDEBAR,
- /\{expanded && projectChats\.length === 0 && \(\n\s*<SidebarMenuItem>\n\s*<p className="[^"]*text-nav-fg-muted">\n\s*\{t\("shell\.navigation\.noChats"\)\}/,
+ /\{expanded && projectChats\.length === 0 && \(\n\s*<SidebarMenuItem\n\s*\{\.\.\.dnd\.dropZoneProps\(\{ section: order\.section, folderId: project\.id, blockEnd \}\)\}\n\s*>\n\s*<p className="[^"]*text-nav-fg-muted">\n\s*\{t\("shell\.navigation\.noChats"\)\}/,
);
// And it is a row, so the bottom fade has to count it like the "Show more" one.
assert.match(APP_SIDEBAR, /if \(chats\.length === 0\) rows \+= 1;/);
@@ -132,9 +134,9 @@ test("the folder menu leads with where to go, then what to change", async () =>
APP_SIDEBAR.indexOf("<span>Delete project</span>"),
);
assert.ok(menu.length > 0, "the folder menu moved");
- const pin = menu.indexOf('{isProjectPinned ? "Unpin project" : "Pin project"}');
+ const pin = menu.indexOf('{isProjectPinned ? "Unpin" : "Pin"}');
const edit = menu.indexOf("<span>Edit</span>");
- assert.notEqual(pin, -1, "Pin project left the folder menu");
+ assert.notEqual(pin, -1, "the pin toggle left the folder menu");
assert.notEqual(edit, -1, "Edit is not in the folder menu");
assert.ok(pin < edit, "Pin project is not directly under Project home");
assert.ok(
@@ -169,15 +171,15 @@ test("the folder menu leads with where to go, then what to change", async () =>
// Pinning a folder used to sort it to the top of Projects, beside a Pinned section of chats.
test("a pinned folder is a row of Pinned, not of Projects", () => {
- // Pinned renders the folders, in the Pinned section's own order scope.
+ // Pinned renders the folders among its chats, in the Pinned section's own order scope.
assert.match(
APP_SIDEBAR,
- /pinnedProjectRecords\.map\(\(project, projectIndex\) =>\n\s*renderProjectFolderRow\(project, projectIndex, \{\n\s*scope: PINNED_PROJECT_ORDER_SCOPE,\n\s*orderedIds: pinnedProjectRowIds,/,
+ /row\.kind === "project"\n\s*\? renderProjectFolderRow\(row\.project, \{\n\s*scope: PINNED_ORDER_SCOPE,\n\s*orderedIds: pinnedRowIds,/,
);
// Projects renders what is left, in its own.
assert.match(
APP_SIDEBAR,
- /visibleProjectRecords\.map\(\(project, projectIndex\) =>\n\s*renderProjectFolderRow\(project, projectIndex, \{\n\s*scope: PROJECT_ORDER_SCOPE,\n\s*orderedIds: projectRowIds,/,
+ /visibleProjectRecords\.map\(\(project\) =>\n\s*renderProjectFolderRow\(project, \{\n\s*scope: PROJECT_ORDER_SCOPE,\n\s*orderedIds: projectRowIds,/,
);
// And the Projects list no longer carries them, so a folder is never in both sections.
const records = APP_SIDEBAR.slice(
@@ -192,7 +194,11 @@ test("a pinned folder is a row of Pinned, not of Projects", () => {
// The header owns "New project", so its test counts every project, pinned or not.
assert.match(
APP_SIDEBAR,
- /const projectsSectionRendered =\n[\s\S]{0,200}?organizeBy === "project" &&\n\s*projects\.length > 0;/,
+ /const projectsSectionConfigured =\n\s*organizeBy === "project" && projects\.length > 0;/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /const projectsSectionRendered =\n[\s\S]{0,200}?projectsSectionConfigured;/,
);
assert.match(APP_SIDEBAR, /\{projectsSectionRendered && \(/);
});
@@ -243,10 +249,11 @@ test("the walk reads the rows in the order Pinned draws them", () => {
visibleChatItems(useChatNavigationStore.getState()).map((i) => i.id),
["folder-1", "folder-2", "pin-1", "proj-1", "recent-1"],
);
- // The sidebar publishes that block whole, and leaves the section's own chats to projectItems.
+ // The sidebar publishes Pinned in its drawn order, folders and chats interleaved with each open
+ // folder's chats under its row, and leaves the section's own chats to projectItems.
assert.match(
APP_SIDEBAR,
- /const pinnedSectionChatItems = useMemo\(\n\s*\(\) => \[\.\.\.pinnedProjectChatItems, \.\.\.visiblePinnedItems\],/,
+ /const pinnedSectionChatItems = useMemo\(\n\s*\(\) =>\n\s*chatListsOnScreen && pinnedOpen\n\s*\? pinnedRows\.flatMap\(\(row\) =>\n\s*row\.kind === "project"\n\s*\? folderChatItems\(true, \[row\.project\]\)\n\s*: \[row\.item\],/,
);
assert.match(
APP_SIDEBAR,
diff --git a/studio/frontend/tests/sidebar-selection-coverage.test.ts b/studio/frontend/tests/sidebar-selection-coverage.test.ts
index 4a871a4e511..4a156101067 100644
--- a/studio/frontend/tests/sidebar-selection-coverage.test.ts
+++ b/studio/frontend/tests/sidebar-selection-coverage.test.ts
@@ -8,15 +8,16 @@ import { readSrc } from "./helpers/kit.ts";
const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");
-// A row is only selectable if it is handed the list it belongs to. Dropping
-// that argument still compiles, since it is optional, and the row just stops
-// responding to cmd and shift click.
+// A row is only selectable if it is handed the list it belongs to. The same argument carries the
+// ids a drag reorders, so a list that loses it stops responding to cmd and shift click and stops
+// being draggable at once.
test("every chat list hands its rows a selection list", async () => {
const source = APP_SIDEBAR;
for (const list of [
- /\{ scope: PINNED_ORDER_SCOPE, ids: pinnedRowIds \}/,
- /\{ scope: RECENTS_ORDER_SCOPE, ids: recentRowIds \}/,
+ // Pinned chat rows select among chats and reorder within the whole Pinned list.
+ /scope: PINNED_ORDER_SCOPE,\s*ids: pinnedChatRowIds,\s*orderIds: pinnedRowIds,/,
+ /scope: RECENTS_ORDER_SCOPE,\s*ids: recentRowIds,/,
/scope: projectOrderScope\(project\.id\),\s*ids: projectChatIds,/,
]) {
assert.match(source, list);
@@ -25,10 +26,11 @@ test("every chat list hands its rows a selection list", async () => {
test("folder rows select too, and open their own bulk menu", async () => {
const source = APP_SIDEBAR;
- // The row hands in its own list: Pinned holds folders too, with ids of its own.
+ // The row hands in its own list. Pinned is folders and chats in one order, so it
+ // ranges over its folder ids alone.
assert.match(
source,
- /handleProjectSelectionClick\(event, project\.id, order\.orderedIds\)/,
+ /handleProjectSelectionClick\(\n\s*event,\n\s*project\.id,\n\s*order\.selectionIds \?\? order\.orderedIds,\n\s*\)/,
);
assert.match(source, /selectProjectForContextMenu\(project\.id\)/);
assert.match(source, /\{renderProjectContextMenu\(\)\}/);
diff --git a/studio/frontend/tests/sidebar-spinner-column.test.ts b/studio/frontend/tests/sidebar-spinner-column.test.ts
index 2b8518b48a4..36a1041f241 100644
--- a/studio/frontend/tests/sidebar-spinner-column.test.ts
+++ b/studio/frontend/tests/sidebar-spinner-column.test.ts
@@ -72,27 +72,24 @@ test("a working Recents row clears the kebab on hover", async () => {
inset(grab(css, /\.sidebar-row-action-glyph \{\s*@apply ([^;]*);/, "action glyph"), "size");
assert.equal(kebabInset, 30);
+ // The row holds that room open at rest rather than on hover: a spinner sits against the same
+ // edge the actions reveal over, so there is nothing to reclaim by waiting for the pointer.
const working = grab(
source,
- // Anchor on the branch comment so nested spinner ternaries cannot redirect
- // the match to a pinned or project row.
- /A spinner glyph cannot truncate[\s\S]{0,120}?"(group-hover\/recent-item:pr-[^"]*)"/,
- "the showWorkSpinner padding branch",
+ /A spinner glyph cannot truncate[\s\S]{0,240}?showWorkSpinner \? "pr-([0-9.]+)"/,
+ "the showWorkSpinner padding",
);
- // hover, menu-open and coarse-pointer all reveal the kebab, so all must clear it
- const pads = [...working.matchAll(/:pr-([0-9.]+)(?: |$)/g)].map(
- (m) => Number(m[1]) * TAILWIND_UNIT,
+ assert.ok(
+ Number(working) * TAILWIND_UNIT >= kebabInset,
+ `${Number(working) * TAILWIND_UNIT}px padding, needs ${kebabInset}px to clear the kebab`,
);
- assert.ok(pads.length >= 3, `expected hover, open and coarse paddings, got ${pads.length}`);
- for (const pad of pads) {
- assert.ok(pad >= kebabInset, `${pad}px padding, needs ${kebabInset}px to clear the kebab`);
- }
- // focus-visible reveals the kebab without hover, so every spinner row reserves room there too.
+ // focus-visible reveals the actions without hover, so every row reserves room there too: one
+ // padding for the project rows and one for every row of Pinned and Recents.
const focusPads = [...source.matchAll(/:focus-visible\]\/[a-z-]+:pr-([0-9.]+)/g)].map(
(m) => Number(m[1]) * TAILWIND_UNIT,
);
- assert.equal(focusPads.length, 3, `expected 3 focus paddings, got ${focusPads.length}`);
+ assert.equal(focusPads.length, 2, `expected 2 focus paddings, got ${focusPads.length}`);
for (const pad of focusPads) {
assert.ok(pad >= kebabInset, `${pad}px focus padding, needs ${kebabInset}px`);
}
diff --git a/studio/frontend/tests/thinking-fold.test.ts b/studio/frontend/tests/thinking-fold.test.ts
new file mode 100644
index 00000000000..cd48b85769a
--- /dev/null
+++ b/studio/frontend/tests/thinking-fold.test.ts
@@ -0,0 +1,455 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Folding a turn's run-up under its first Thinking block. The parts are grouped by type, so the
+// tool calls and later thinking render as siblings of that block rather than inside it: what
+// these assertions protect is which siblings the block holds, and the calls it must never hide.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ countFoldedToolParts,
+ endsFoldedSpan,
+ foldEnd,
+ foldedToolSummary,
+ foldedTurnDuration,
+ foldRun,
+ governingReasoningEnd,
+ isBlankTextPart,
+ isFoldedReasoningGroup,
+ leadReasoningEnd,
+ reasoningRoundKey,
+} from "../src/components/assistant-ui/thinking-fold.ts";
+import {
+ awaitsConfirmation,
+ holdsOwnOutput,
+ toolRunIsExempt,
+} from "../src/components/assistant-ui/tool-fold-exemptions.ts";
+import { en } from "../src/i18n/locales/en.ts";
+import { SETTINGS_SEARCH_INDEX } from "../src/features/settings/settings-search.ts";
+import { readSrc, readSrcAsync } from "./helpers/kit.ts";
+
+const parts = (types: string[]) => types.map((type) => ({ type }));
+
+// reasoning, tools, reasoning, tools, answer, one more call after the answer.
+const twoRounds = parts([
+ "reasoning",
+ "tool-call",
+ "tool-call",
+ "reasoning",
+ "reasoning",
+ "tool-call",
+ "text",
+ "tool-call",
+]);
+
+test("the first thinking block of a span heads it", () => {
+ assert.equal(leadReasoningEnd(twoRounds, 0), 0);
+ assert.equal(leadReasoningEnd(twoRounds, 5), 0);
+ // Two reasoning parts in a row are one block.
+ assert.equal(
+ leadReasoningEnd(parts(["reasoning", "reasoning", "text"]), 1),
+ 1,
+ );
+ // A call before any thinking does not stop the first block from leading.
+ assert.equal(
+ leadReasoningEnd(parts(["tool-call", "reasoning", "text"]), 0),
+ 1,
+ );
+ // Answer text is not in any span, and a run with no thinking has no lead.
+ assert.equal(leadReasoningEnd(parts(["text", "reasoning"]), 0), null);
+ assert.equal(leadReasoningEnd(parts(["tool-call", "text"]), 0), null);
+ // The call after the answer sits in a span of its own with nothing to lead it.
+ assert.equal(leadReasoningEnd(twoRounds, 7), null);
+});
+
+test("a span runs from its lead to the answer", () => {
+ assert.deepEqual(foldRun(twoRounds, 0), { start: 0, end: 6 });
+ assert.deepEqual(foldRun(twoRounds, 7), { start: 7, end: 8 });
+ assert.equal(foldRun(twoRounds, 6), null);
+ assert.equal(foldEnd(twoRounds, 0), 6);
+ assert.equal(foldEnd(parts(["reasoning", "tool-call"]), 0), 2);
+});
+
+test("blank text between thinking and a call does not end the span", () => {
+ // A provider can leave a newline between a closed think block and its native tool event.
+ const blank = [
+ { type: "reasoning" },
+ { type: "text", text: "\n" },
+ { type: "tool-call" },
+ { type: "reasoning" },
+ { type: "text", text: "The answer." },
+ ];
+ assert.equal(isBlankTextPart(blank[1]), true);
+ assert.equal(isBlankTextPart(blank[4]), false);
+ assert.equal(isBlankTextPart({ type: "reasoning" }), false);
+ assert.deepEqual(foldRun(blank, 0), { start: 0, end: 4 });
+ assert.equal(governingReasoningEnd(blank, 2), 0);
+ assert.equal(isFoldedReasoningGroup(blank, 3), true);
+ assert.equal(countFoldedToolParts(blank, 0), 1);
+ // The rule closes the last thing shown, not a trailing blank.
+ const trailing = [
+ { type: "reasoning" },
+ { type: "tool-call" },
+ { type: "text", text: " " },
+ { type: "text", text: "The answer." },
+ ];
+ assert.equal(endsFoldedSpan(trailing, 1), true);
+ assert.equal(endsFoldedSpan(trailing, 2), false);
+});
+
+test("a continuation's seeded reply sits before the new round, not in it", () => {
+ // Continue seeds the new message with the previous reply as its first text part.
+ const continued = [
+ { type: "text", text: "What I had so far." },
+ { type: "reasoning" },
+ { type: "tool-call" },
+ { type: "tool-call" },
+ { type: "reasoning" },
+ { type: "text", text: "And the rest." },
+ ];
+ assert.equal(leadReasoningEnd(continued, 1), 1);
+ assert.equal(governingReasoningEnd(continued, 2), 1);
+ assert.equal(isFoldedReasoningGroup(continued, 4), true);
+ assert.equal(countFoldedToolParts(continued, 1), 2);
+ assert.equal(endsFoldedSpan(continued, 4), true);
+ // Two answers, two spans, each with its own lead.
+ const twoSpans = [
+ { type: "reasoning" },
+ { type: "tool-call" },
+ { type: "text", text: "First." },
+ { type: "reasoning" },
+ { type: "tool-call" },
+ { type: "text", text: "Second." },
+ ];
+ assert.equal(leadReasoningEnd(twoSpans, 1), 0);
+ assert.equal(leadReasoningEnd(twoSpans, 4), 3);
+ assert.equal(governingReasoningEnd(twoSpans, 4), 3);
+ assert.equal(countFoldedToolParts(twoSpans, 3), 1);
+});
+
+test("every group before the answer folds under the lead", () => {
+ for (const start of [1, 2, 3, 5]) {
+ assert.equal(governingReasoningEnd(twoRounds, start), 0);
+ }
+ // The lead itself heads the fold rather than joining it.
+ assert.equal(governingReasoningEnd(twoRounds, 0), null);
+ assert.equal(isFoldedReasoningGroup(twoRounds, 3), true);
+ assert.equal(isFoldedReasoningGroup(twoRounds, 0), false);
+});
+
+test("calls with no thinking before them, or after the answer, stay put", () => {
+ assert.equal(governingReasoningEnd(parts(["tool-call"]), 0), null);
+ assert.equal(
+ governingReasoningEnd(parts(["tool-call", "reasoning"]), 0),
+ null,
+ );
+ assert.equal(governingReasoningEnd(twoRounds, 7), null);
+ // Thinking after the answer keeps its own block.
+ assert.equal(
+ isFoldedReasoningGroup(parts(["reasoning", "text", "reasoning"]), 2),
+ false,
+ );
+});
+
+test("the lead counts every call it holds and none after the answer", () => {
+ assert.equal(countFoldedToolParts(twoRounds, 0), 3);
+ assert.equal(countFoldedToolParts(parts(["reasoning", "text"]), 0), 0);
+});
+
+test("a run the thread keeps visible is not counted as held", () => {
+ // The first run (parts 1..2) is exempt, say a call awaiting approval; the second is not.
+ const exempt = (start: number) => start === 1;
+ assert.equal(countFoldedToolParts(twoRounds, 0, exempt), 1);
+ assert.equal(
+ countFoldedToolParts(twoRounds, 0, () => true),
+ 0,
+ );
+ // Runs are passed whole, as the tool group sees them.
+ const seen: [number, number][] = [];
+ countFoldedToolParts(twoRounds, 0, (start, end) => {
+ seen.push([start, end]);
+ return false;
+ });
+ assert.deepEqual(seen, [
+ [1, 2],
+ [5, 5],
+ ]);
+});
+
+test("calls whose output lives only in their card stay visible", () => {
+ const call = (toolName: string, result?: unknown) => ({
+ type: "tool-call",
+ toolName,
+ toolCallId: `c-${toolName}`,
+ result,
+ });
+ // A generated image has no message part of its own: hide the card and the image is gone.
+ assert.equal(holdsOwnOutput(call("image_generation")), true);
+ assert.equal(holdsOwnOutput(call("render_html")), true);
+ assert.equal(holdsOwnOutput(call("python")), true);
+ assert.equal(
+ holdsOwnOutput(
+ call("terminal", {
+ text: "",
+ images: [],
+ sessionId: "s",
+ files: [{ name: "a.txt", size: 3 }],
+ }),
+ ),
+ true,
+ );
+ // An MCP tool that returned images shows them only in its card.
+ const mcpImages = {
+ text: "two charts",
+ images: [{ data: "iVBORw0KGgo=", mimeType: "image/png" }],
+ };
+ assert.equal(holdsOwnOutput(call("mcp__charts__plot", mcpImages)), true);
+ assert.equal(
+ holdsOwnOutput(call("mcp__charts__plot", { text: "none", images: [] })),
+ false,
+ );
+ assert.equal(
+ holdsOwnOutput(call("mcp__charts__plot", { text: "bad", images: ["x"] })),
+ false,
+ );
+ assert.equal(holdsOwnOutput(call("web_search")), false);
+ assert.equal(holdsOwnOutput(call("terminal", "plain output")), false);
+ assert.equal(holdsOwnOutput({ type: "reasoning" }), false);
+ // An approval prompt keeps its run visible; a resolved one does not.
+ assert.equal(
+ awaitsConfirmation(call("terminal"), { "c-terminal": {} }),
+ true,
+ );
+ assert.equal(awaitsConfirmation(call("terminal"), {}), false);
+ const run = [
+ call("web_search"),
+ call("image_generation"),
+ call("web_search"),
+ ];
+ assert.equal(toolRunIsExempt(run, 0, 2, {}), true);
+ assert.equal(toolRunIsExempt(run, 0, 0, {}), false);
+ assert.equal(toolRunIsExempt(run, 0, 0, { "c-web_search": {} }), true);
+});
+
+test("the tool group and the header share one exemption rule", () => {
+ const rules = readSrc("components/assistant-ui/tool-fold-exemptions.ts");
+ assert.match(rules, /export function holdsOwnOutput/);
+ assert.match(rules, /export function awaitsConfirmation/);
+ assert.match(rules, /export function toolRunIsExempt/);
+ const toolGroup = readSrc("components/assistant-ui/tool-group.tsx");
+ assert.match(toolGroup, /\.some\(holdsOwnOutput\)/);
+ assert.match(toolGroup, /awaitsConfirmation\(part, toolConfirmations\)/);
+ const reasoning = readSrc("components/assistant-ui/reasoning.tsx");
+ assert.match(
+ reasoning,
+ /countFoldedToolParts\(message\.parts, endIndex, \(start, end\) =>\n\s*toolRunIsExempt\(message\.parts, start, end, toolConfirmations\),/,
+ );
+});
+
+test("the rule that closes the trace goes on the last thing before the answer", () => {
+ // Part 5 is the last call before the answer at 6.
+ assert.equal(endsFoldedSpan(twoRounds, 5), true);
+ assert.equal(endsFoldedSpan(twoRounds, 3), false);
+ assert.equal(endsFoldedSpan(twoRounds, 4), false);
+ assert.equal(endsFoldedSpan(twoRounds, 7), false);
+ // A lone block with the answer right after it closes itself.
+ assert.equal(endsFoldedSpan(parts(["reasoning", "text"]), 0), true);
+ // Nothing follows, nothing to separate from.
+ assert.equal(endsFoldedSpan(parts(["reasoning", "tool-call"]), 1), false);
+ const reasoning = readSrc("components/assistant-ui/reasoning.tsx");
+ const toolGroup = readSrc("components/assistant-ui/tool-group.tsx");
+ // Every candidate for last place renders the rule: the lead, a folded round, a tool run.
+ assert.equal(
+ reasoning.match(/closesTrace && <ReasoningEndRule \/>/g)?.length,
+ 2,
+ );
+ assert.match(
+ toolGroup,
+ /closesTrace && \(\n\s*<div\n\s*data-slot="reasoning-end-rule"/,
+ );
+ // Without the fold, the lead asks whether the answer is next.
+ assert.match(
+ reasoning,
+ /: message\.parts\[endIndex \+ 1\]\?\.type === "text",/,
+ );
+});
+
+test("opening by hand grows the block downward instead of pinning the bottom", () => {
+ // The viewport follows content growth while attached to the bottom. A click that opens a
+ // block, a tool group or a tool card first detaches, so the header stays put. A stream still
+ // follows: its auto-open is not a click.
+ const reasoning = readSrc("components/assistant-ui/reasoning.tsx");
+ assert.match(
+ reasoning,
+ /if \(open && !isReasoningStreaming\) \{\n\s*detachFromBottom\(\);\n\s*\}/,
+ );
+ for (const file of ["tool-group.tsx", "tool-fallback.tsx"]) {
+ const source = readSrc(`components/assistant-ui/${file}`);
+ assert.match(
+ source,
+ /if \(!open\) \{\n\s*lockScroll\(\);\n\s*\} else if \(!messageRunning\) \{\n\s*detachFromBottom\(\);\n\s*\}/,
+ file,
+ );
+ }
+ const hook = readSrc(
+ "components/assistant-ui/use-intent-aware-autoscroll.tsx",
+ );
+ assert.match(
+ hook,
+ /export function useDetachThreadFromBottom\(\): \(\) => void/,
+ );
+});
+
+test("the header row keeps its height when Copy appears", () => {
+ const reasoning = readSrc("components/assistant-ui/reasoning.tsx");
+ // A bare span would take the paragraph line-height and push the label down when opened.
+ assert.match(
+ reasoning,
+ /<span className="ml-auto flex items-center leading-none">\n\s*<ReasoningCopyButton/,
+ );
+});
+
+test("the lead reports the turn's thinking time added up", () => {
+ const byStart: Record<number, number | undefined> = { 0: 4, 3: 6 };
+ const resolve = (_parts: readonly { type: string }[], start: number) =>
+ byStart[start];
+ assert.equal(foldedTurnDuration(twoRounds, 0, resolve), 10);
+ // A reply saved with only the legacy last-round duration still reports it.
+ assert.equal(
+ foldedTurnDuration(twoRounds, 0, (_p, start) =>
+ start === 3 ? 6 : undefined,
+ ),
+ 6,
+ );
+ // Nothing known and the caller keeps its own clock.
+ assert.equal(
+ foldedTurnDuration(twoRounds, 0, () => undefined),
+ undefined,
+ );
+ assert.equal(foldedTurnDuration(parts(["text"]), 0, resolve), undefined);
+});
+
+test("the header says how many calls it is holding", () => {
+ assert.equal(foldedToolSummary(0), null);
+ assert.equal(foldedToolSummary(1), "1 tool call");
+ assert.equal(foldedToolSummary(12), "12 tool calls");
+ // The same wording the tool group trigger uses, so the count reads the same once unfolded.
+ const toolGroup = readSrc("components/assistant-ui/tool-group.tsx");
+ assert.match(
+ toolGroup,
+ /const label = `\$\{count\} tool \$\{count === 1 \? "call" : "calls"\}`;/,
+ );
+});
+
+test("two blocks in one message stay apart", () => {
+ assert.notEqual(reasoningRoundKey("m1", 0), reasoningRoundKey("m1", 3));
+ assert.notEqual(reasoningRoundKey("m1", 0), reasoningRoundKey("m2", 0));
+});
+
+// The lead publishes its open state for the parts folded under it. In a layout effect: they
+// render after the block in the same commit, so a plain effect would show them for one frame.
+test("the lead publishes its open state before the frame", async () => {
+ const reasoning = await readSrcAsync("components/assistant-ui/reasoning.tsx");
+ assert.match(
+ reasoning,
+ /useLayoutEffect\(\(\) => \{\n\s*if \(!foldLead\) return;\n\s*setReasoningRoundOpen\(roundKey, isOpen\);\n\s*\}, \[foldLead, isOpen, roundKey\]\);/,
+ );
+ assert.match(
+ reasoning,
+ /useLayoutEffect\(\(\) => \(\) => clearReasoningRound\(roundKey\), \[roundKey\]\);/,
+ );
+ // A block nobody has published counts as closed, so nothing flashes before it is read.
+ const store = readSrc("features/chat/stores/reasoning-round-store.ts");
+ assert.match(store, /open: Record<string, boolean>;/);
+ const toolGroup = readSrc("components/assistant-ui/tool-group.tsx");
+ assert.match(toolGroup, /state\.open\[roundKey\] \?\? false/);
+ assert.match(reasoning, /state\.open\[roundKey\] \?\? false/);
+});
+
+test("later thinking rounds render inside the lead, with no header of their own", async () => {
+ const reasoning = await readSrcAsync("components/assistant-ui/reasoning.tsx");
+ assert.match(
+ reasoning,
+ /if \(folded\) \{\n\s*return <FoldedReasoningRound \{\.\.\.props\} \/>;\n\s*\}/,
+ );
+ assert.match(reasoning, /data-slot="reasoning-folded-round"/);
+ // A folded round pages a long trace the same way the lead does.
+ const foldedRound = reasoning.slice(
+ reasoning.indexOf("const FoldedReasoningRound"),
+ reasoning.indexOf("const ReasoningGroupBlock"),
+ );
+ assert.match(foldedRound, /const pages = useReasoningPages\(/);
+ assert.match(foldedRound, /<ReasoningBody\n/);
+ // Copy on the lead reaches the folded rounds, which have no Copy of their own.
+ assert.match(
+ reasoning,
+ /foldLead \? foldEnd\(message\.parts, endIndex\) - 1 : endIndex/,
+ );
+ assert.match(reasoning, /endIndex=\{copyEndIndex\}/);
+ // The count sits outside the label, so it shows while the block is still working.
+ const trigger = reasoning.slice(
+ reasoning.indexOf("function ReasoningTrigger"),
+ reasoning.indexOf("function ReasoningContent"),
+ );
+ assert.ok(
+ trigger.indexOf("{foldedSummary ? (") >
+ trigger.indexOf("</span>\n {/*"),
+ "the count is inside the label and lost while active",
+ );
+ // The lead keeps working through those rounds, so its clock covers the whole turn.
+ assert.match(
+ reasoning,
+ /if \(foldLead && \(part\?\.type === "reasoning" \|\| isBlankTextPart\(part\)\)\)/,
+ );
+});
+
+test("a folded run is hidden, not unmounted", () => {
+ const toolGroup = readSrc("components/assistant-ui/tool-group.tsx");
+ // One wrapper whether the run is exempt or not: an approval arriving or clearing changes
+ // visibility only, so the cards keep their state, their scroll and any live output.
+ assert.match(
+ toolGroup,
+ /className=\{cn\(!\(roundOpen \|\| exempt\) && "hidden"\)\}/,
+ );
+ assert.match(toolGroup, /data-slot="tool-run-under-thinking"/);
+ const reasoning = readSrc("components/assistant-ui/reasoning.tsx");
+ assert.match(reasoning, /!open && "hidden"/);
+});
+
+test("output and approvals are never folded away", () => {
+ const toolGroup = readSrc("components/assistant-ui/tool-group.tsx");
+ assert.match(
+ toolGroup,
+ /const underThinking = foldToolActivity && roundKey !== null;\n\s*const exempt = containsUngroupedTool \|\| hasPendingConfirmation;/,
+ );
+ // With the preference off the tree is exactly what it was, wrapper included.
+ assert.match(toolGroup, /if \(!underThinking\) \{\n\s*return group;\n\s*\}/);
+});
+
+test("the preference ships off and survives a reload", () => {
+ const prefs = readSrc("features/chat/stores/chat-preferences-store.ts");
+ assert.match(prefs, /foldToolActivityIntoThinking: false,/);
+ assert.match(
+ prefs,
+ /foldToolActivityIntoThinking:\n\s*saved\?\.foldToolActivityIntoThinking \?\? false,/,
+ );
+});
+
+test("the setting is in the Chat tab and findable", () => {
+ const chatTab = readSrc("features/settings/tabs/chat-tab.tsx");
+ assert.match(chatTab, /t\("settings\.chat\.tools\.foldIntoThinking"\)/);
+ assert.match(
+ chatTab,
+ /checked=\{foldToolActivityIntoThinking\}\n\s*onCheckedChange=\{setFoldToolActivityIntoThinking\}/,
+ );
+ assert.ok(
+ SETTINGS_SEARCH_INDEX.chat.includes("settings.chat.tools.foldIntoThinking"),
+ "the setting cannot be found by search",
+ );
+ assert.equal(
+ en.settings.chat.tools.foldIntoThinking,
+ "Fold tool calls into Thinking",
+ );
+ assert.ok(en.settings.chat.tools.foldIntoThinkingDescription.length > 0);
+});
diff --git a/studio/frontend/tests/tool-activity-preference.test.ts b/studio/frontend/tests/tool-activity-preference.test.ts
index 291bec123f5..3a9f0a1d464 100644
--- a/studio/frontend/tests/tool-activity-preference.test.ts
+++ b/studio/frontend/tests/tool-activity-preference.test.ts
@@ -694,11 +694,19 @@ test("a call that created files keeps its group from collapsing", async () => {
false,
);
- const source = await sourceOf(
+ // The rule lives in tool-fold-exemptions.ts; the group asks it per part.
+ const group = await sourceOf(
"../src/components/assistant-ui/tool-group.tsx",
);
+ assert.match(
+ initializerOf(group, "containsUngroupedTool").getText(),
+ /\.some\(holdsOwnOutput\)/,
+ );
+ const source = await sourceOf(
+ "../src/components/assistant-ui/tool-fold-exemptions.ts",
+ );
const call = find(
- initializerOf(source, "containsUngroupedTool"),
+ source,
(node) =>
ts.isCallExpression(node) &&
ts.isIdentifier(node.expression) &&