unsloth/studio/frontend/tests/sidebar-selection-coverage.test.ts
Michael Han 2643d0ef6f
Studio: keep project chats in Recents, add a Projects sidebar section (#8932)
* Studio: keep project chats in Recents, add a Projects sidebar section

Filing a chat under a project removed it from Recents (#5725), so a new
project chat looked like it went nowhere. Recents is the whole history
again, project chats included, and only pinned chats are held back since
the Pinned section renders those.

Projects is now its own section listing every project as a folder with
its chats nested underneath, rather than folders only appearing once a
project was pinned. Pinning sorts a project to the top of that list.

Each list header (Pinned, Projects, Recents) reveals actions on hover:
a "..." menu, plus "+" on Projects and a compose button on Recents.
The menu carries Organize sidebar (By project, In one list) and a sort
(Priority, Last updated, Manual order). Pinned sorts on its own and
defaults to manual, since pin order already is a manual order.

Manual order is dragged into place and is per list, so reordering a
chat inside a project cannot move it in Recents.

* Studio: drag project folders to reorder them

Folders drag regardless of the chat sort, the way the chat rows do under
Manual order. A dragged order outranks the pinned-first-then-activity
rule; projects never dragged keep that rule and stay on top.

Pulls the drag handlers out of the chat row into one helper both rows
use, and replaces the manual-sort comparator with a shared
applyManualOrder. That also fixes Pinned: an undragged pinned chat now
keeps pin order instead of falling back to last updated.

* Studio: address review on sidebar ordering

- Order projects by their chats' activity. A project's own updatedAt only
  moves when its name, instructions or archived flag change, so an old
  project with a busy chat was sorting below one that was merely renamed.
- Add Move up and Move down to the row menus. Touch browsers never fire
  dragstart and a keyboard cannot drag, so manual order was unreachable
  there. moveIdBy is tested to agree with dragging onto the neighbour.
- Build each list's id array once instead of per row, and pass the row
  index in, so rendering N rows no longer allocates N arrays of length N.
- Key the new menu strings and add them to all 11 locale overlays.
- Paint the drop indicator on the edge the row actually lands on. Dragging
  down inserts after the target, so a cue always drawn above it was wrong.
  dropEdgeFor is checked against reorderIds for every pair.
- Re-measure the scroll fade when regrouping, collapsing a folder or
  revealing more projects changes the row count.

* Studio: let touch reach the project folder menu

The folder's actions lacked sidebar-touch-reveal, and the coarse-pointer
rule only un-hides row actions carrying it, so the Project options menu
was inert on touch. That menu is the only reorder path there, since touch
never fires dragstart, leaving folders unorderable on a touch sidebar.

Reveals both folder actions on touch and reserves the same padding hover
does, or the name runs under them. Test covers the rule, the rows that
carry reorder controls, and the padding.

* Studio: select multiple chats for bulk actions

Cmd click (ctrl on Windows and Linux) toggles a row, shift click takes
the block from the anchor. Right click opens Pin chats, Archive chats,
Mark as unread and Delete chats over the whole selection, and Escape or
any plain click clears it.

The modifier is read off the browser rather than the platform store,
which the backend corrects: a Mac browser on a Linux host still uses cmd,
and ctrl stays free on macOS where ctrl click is the right click chord.

Selection holds ids and resolves against the live rows, so a chat deleted
elsewhere leaves nothing behind to act on. Ranges are per list, since one
chat can sit in both a project and Recents.

Mark as unread writes to the same session-level unread state the sidebar
already keeps, so it clears on reload like the rest of it.

* Studio: make the Projects section a setting, drop the selection outline

Project chats no longer appear in both their folder and Recents. With the
Projects section on they stay in the folder; with it off there is no
section and they list in Recents, so a new project chat is still visible
somewhere. Appearance settings carries the switch, and the header menu
writes the same preference.

A selected row now takes the plain hover fill, with no outline.

* Studio: setting to always delete a chat's files with it

Data settings gains an Always delete files switch. With it on, the delete
dialog opens with the files toggle already set, so what will happen is
visible and can still be turned off for one delete, and the paths that
skip the dialog remove the folder too.

All three chat delete paths read it: the sidebar, the chat page and the
archived chats dialog. Deleting a project keeps asking from scratch,
since removing a whole workspace is a bigger thing than one sandbox.

Off by default, and a preferences payload written before this setting
existed reads as off, so no install starts deleting files on its own.

* Studio: pin Video in the sidebar, under Images

Video ships as a top-level row again instead of sitting in the More
flyout. It lands under Images, where SIDEBAR_NAV_ITEM_IDS already puts
it, so the media tabs stay together.

The backend default moves with it, since a record predating sidebarNav is
served the backend's own layout, and the parity test compares the two.

Recorded the version 6 layout as a shipped default and bumped the store
to 7, so an install still on that layout adopts this one while a sidebar
the user arranged themselves is left alone.

* Studio: carry the delete-files preference to clear-all and dictations

Two more paths delete chats and both ignored the setting. Clear all chats
left every sandbox behind, and after it there is no chat row left to
reach those folders from. Deleting a chat from Voice, Recent Dictations
did the same for one chat.

The DELETE endpoint already takes delete_files; only clearAllChats and
clearStoredChats dropped it on the way through, so both now pass it on.

The test that covers this now names all five delete paths, and checks
each hop of the clear-all chain, since a dropped hop still compiles.

* Studio: move the projects setting to Chat, select folders in bulk

The Show projects section switch is a chat setting, not an appearance
one, so it moves to the Chat tab and its keys move with it.

Project folders now select like chat rows: cmd click toggles, shift click
takes a block, and right click offers Pin projects and Delete projects
over the selection. Folders and chats select separately, since a mixed
selection has no action they share, so picking one kind drops the other.

Test names the lists that hand rows a selection context. The argument is
optional, so dropping it compiles and only stops the row selecting.

* Studio: re-measure the fade when the Pinned section changes

Pinning a project chat adds a Pinned row while Recents never held it and
the folder still counts it, so no dependency of the fade effect moved and
the bottom fade kept a stale value.

Regrouping has the same hole when the projects hold no chats: the folder
rows appear and disappear while every count stays at zero.

Test names every row-count input the effect must depend on. This is the
second time a missing one has gone unnoticed, and it never shows up as a
failure, only as a fade that is wrong until the next scroll.

* Studio: finish bulk project delete, sync the Video default

Deleting folders in bulk skipped the cleanup the single delete does, so
member chats stayed as rows and a user on a deleted project's page was
left there. The batch now refreshes history once and redirects if any
deleted project was the open one.

Pinning Video also never reached a synced profile. Remote hydration runs
the same migration with the personalization version on both sides, which
short-circuits and then replaces the local store with the stored layout.
That version moves to 4 so the migration runs.

Tests cover both: the bulk branch ends like the single one, and a stored
v6 layout at the old version adopts the new default.

* Studio: redirect only off projects that were actually deleted

The batch built its id set from every requested project, so a delete that
failed still bounced the user off a project that is still there. The set
now fills as each delete succeeds, matching the single delete, which
redirects inside its try.

The history refresh stays unconditional: a delete that threw may still
have removed member chats on its way out.

* Studio: translate the bulk archive failure toast

The key already exists and data-tab uses it.

* Studio: drop the other kind of selection on every right-click

Folders stayed highlighted when a chat menu opened.

* Studio: reset the sidebar layout key, and finish a partly failed archive

* Studio: translate the sidebar Show more labels

* Studio: show the file switch in every chat delete confirmation

Two dialogs deleted files the preference had turned on without saying so.

* Studio: show the file switch when clearing chats and deleting a linked dictation

---------

Co-authored-by: shimmyshimmer <michaelhan@Michaels-MacBook-Pro.local>
2026-08-15 22:48:11 -07:00

161 lines
6.6 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
// 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.
async function sidebarSource(): Promise<string> {
return readFile(
new URL("../src/components/app-sidebar.tsx", import.meta.url),
"utf8",
);
}
test("every chat list hands its rows a selection list", async () => {
const source = await sidebarSource();
for (const list of [
/\{ scope: PINNED_ORDER_SCOPE, ids: pinnedRowIds \}/,
/\{ scope: RECENTS_ORDER_SCOPE, ids: recentRowIds \}/,
/scope: projectOrderScope\(project\.id\),\s*ids: projectChatIds,/,
]) {
assert.match(source, list);
}
});
test("folder rows select too, and open their own bulk menu", async () => {
const source = await sidebarSource();
assert.match(source, /handleProjectSelectionClick\(event, project\.id\)/);
assert.match(source, /selectProjectForContextMenu\(project\.id\)/);
assert.match(source, /\{renderProjectContextMenu\(\)\}/);
assert.match(source, /selectedProjectIds\.has\(project\.id\)/);
});
function bodyOf(source: string, name: string): string {
const found = new RegExp(`function ${name}\\(([\\s\\S]*?)\\n \\}`).exec(
source,
);
assert.ok(found, `no ${name}`);
return found[1];
}
test("picking one kind of row drops the other", async () => {
// Chats and folders have no shared bulk action, so a mixed selection would
// leave the menu unable to say what it acts on. All four entry points, since
// one that skips it is what puts the sidebar in that state.
const source = await sidebarSource();
for (const [name, drop] of [
["handleSelectionClick", "dropProjectSelection()"],
["selectForContextMenu", "dropProjectSelection()"],
["handleProjectSelectionClick", "dropChatSelection()"],
["selectProjectForContextMenu", "dropChatSelection()"],
]) {
assert.ok(
bodyOf(source, name).includes(drop),
`${name} leaves the other kind of row selected`,
);
}
});
test("a right-click drops the other kind even on an already-selected row", async () => {
// Both menus return early when the row is already selected. Dropping after
// that return would keep a mixed selection alive for exactly the rows a bulk
// action is most likely to run on.
const source = await sidebarSource();
for (const [name, drop] of [
["selectForContextMenu", "dropProjectSelection()"],
["selectProjectForContextMenu", "dropChatSelection()"],
]) {
const body = bodyOf(source, name);
const dropAt = body.indexOf(drop);
const returnAt = body.search(/if \(selected\w+\.has\([\w.]+\)\) return;/);
assert.ok(dropAt >= 0, `${name} does not drop the other kind`);
assert.ok(returnAt >= 0, `${name} lost its early return`);
assert.ok(
dropAt < returnAt,
`${name} drops the other kind only after its early return`,
);
}
});
test("dropping a selection clears its anchor too", async () => {
// A kept anchor shift-selects a range from a row that no longer looks
// selected, which is how a cleared list grows again on the next click.
const source = await sidebarSource();
assert.match(
source,
/const dropChatSelection = useCallback\(\(\) => \{\s*selectionAnchorRef\.current = null;/,
);
assert.match(
source,
/const dropProjectSelection = useCallback\(\(\) => \{\s*projectAnchorRef\.current = null;/,
);
});
test("the bulk archive failure reads a translated string", async () => {
// Its wording already exists as a key, so a literal here would be the one
// English toast in an otherwise translated flow.
const source = await sidebarSource();
const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);
assert.ok(archive, "no archiveSelected");
assert.match(archive[1], /translate\("settings\.data\.failedToArchiveChats"\)/);
});
test("one failed archive does not abandon the rest of the batch", async () => {
// The selection is cleared up front, so chats skipped by an early exit are
// left unarchived with nothing left highlighted to retry from. The other two
// bulk loops catch per item; this one has to as well.
const source = await sidebarSource();
const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);
assert.ok(archive, "no archiveSelected");
const body = archive[1];
const loopAt = body.indexOf("for (const item of items)");
const tryAt = body.indexOf("try {");
assert.ok(loopAt >= 0, "no batch loop");
assert.ok(tryAt > loopAt, "archiveSelected catches around the loop, not in it");
// Reported on what got through, not on whether the loop threw.
assert.match(body, /archived \+= 1/);
assert.match(body, /if \(archived > 0\) showArchivedChatsToast\(\)/);
assert.match(body, /if \(archived < items\.length\)/);
});
test("deleting folders in bulk cleans up like deleting one", async () => {
// Both branches end the same way, or a batch leaves stale chat rows behind
// and strands the user on a page whose project is gone.
const source = await sidebarSource();
const branch = /if \(target\.kind === "projects"\) \{([\s\S]*?)\n return;/.exec(
source,
);
assert.ok(branch, "no bulk project delete branch");
assert.match(branch[1], /notifyChatHistoryUpdated\(\)/);
assert.match(branch[1], /setActiveProjectId\(null\)/);
assert.match(branch[1], /navigate\(\{ to: "\/chat"/);
// The redirect reads what was actually deleted. Built from the requested
// list instead, a delete that failed would still throw the user off a
// project that is still there.
assert.match(branch[1], /deletedIds\.add\(project\.id\)/);
assert.equal(
/new Set\(target\.projects\.map/.test(branch[1]),
false,
"deletedIds is built from the requested projects, not the deleted ones",
);
});
test("both sidebar expanders read translated labels", async () => {
// The two sit one control apart, so an English literal next to a translated
// twin is the visible half of the omission.
// Comments name the control too, so match the rendered ternary, not the words.
const source = await sidebarSource();
assert.equal(
/\?\s*"Show less"\s*:\s*"Show more"/.test(source),
false,
"a sidebar expander still hard-codes its label",
);
const uses = source.match(/shell\.navigation\.show(More|Less)/g) ?? [];
assert.equal(uses.length, 4, "both expanders read both keys");
});