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.

47.3 KB
Raw Blame
// 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 { register } from "node:module";
import test from "node:test";

import {
  planSidebarDrop,
  sectionRingKey,
  STAY,
  type SidebarDragItem,
  type SidebarDropContext,
  type SidebarDropOutcome,
  type SidebarDropPlan,
  type SidebarDropZone,
} from "../src/features/chat/lib/sidebar-drag.ts";
import {
  customSectionIdOf,
  customSectionScope,
  mergePersistedOrganization,
  normalizeSectionName,
  PINNED_ORDER_SCOPE,
  projectOrderScope,
  RECENTS_ORDER_SCOPE,
  PROJECT_ORDER_SCOPE,
  PINNED_SECTION_KEY,
  PROJECTS_SECTION_KEY,
  resolveSectionOrder,
  SIDEBAR_ORGANIZATION_STORAGE_KEY,
  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 EN = await readSrcAsync("i18n/locales/en.ts");

function plannedDrop(outcome: SidebarDropOutcome): SidebarDropPlan {
  assert.ok(
    outcome !== null && outcome !== STAY,
    `expected a drop plan, got ${String(outcome)}`,
  );
  return outcome;
}

function resetStore() {
  const initial = useSidebarOrganizationStore.getInitialState();
  useSidebarOrganizationStore.setState({
    customSections: initial.customSections,
    sectionByChatId: initial.sectionByChatId,
    sectionByProjectId: initial.sectionByProjectId,
    sectionByPageId: initial.sectionByPageId,
    hiddenSections: initial.hiddenSections,
    sectionOrder: initial.sectionOrder,
    pendingNewChatSection: null,
    manualOrder: {},
  });
}

test("a new sidebar has no custom sections and hides nothing", () => {
  const fresh = useSidebarOrganizationStore.getInitialState();
  assert.deepEqual(fresh.customSections, []);
  assert.deepEqual({ ...fresh.sectionByChatId }, {});
  assert.deepEqual({ ...fresh.sectionByProjectId }, {});
  assert.deepEqual(fresh.hiddenSections, []);
});

test("a section is created newest first, named, and manual by default", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const first = store.createCustomSection("  Research  ");
  const second = store.createCustomSection("Work\n  stuff");
  assert.ok(first && second && first !== second);
  const { customSections } = useSidebarOrganizationStore.getState();
  assert.deepEqual(
    customSections.map((section) => [section.name, section.sort]),
    [
      ["Work stuff", "manual"],
      ["Research", "manual"],
    ],
  );
});

test("a blank name makes no section and renames nothing", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  assert.equal(store.createCustomSection("   "), null);
  const id = store.createCustomSection("Keep")!;
  store.renameCustomSection(id, " \t ");
  assert.equal(useSidebarOrganizationStore.getState().customSections[0].name, "Keep");
  store.renameCustomSection(id, "Kept");
  assert.equal(useSidebarOrganizationStore.getState().customSections[0].name, "Kept");
  assert.equal(normalizeSectionName("x".repeat(200)).length, 60);
});

test("rows file into a section, move between sections, and come back out", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const a = store.createCustomSection("A")!;
  const b = store.createCustomSection("B")!;
  store.setChatsSection(["c1", "c2"], a);
  store.setProjectsSection(["p1"], a);
  store.setChatsSection(["c2"], b);
  let state = useSidebarOrganizationStore.getState();
  assert.deepEqual({ ...state.sectionByChatId }, { c1: a, c2: b });
  assert.deepEqual({ ...state.sectionByProjectId }, { p1: a });
  store.setChatsSection(["c1"], null);
  state = useSidebarOrganizationStore.getState();
  assert.deepEqual({ ...state.sectionByChatId }, { c2: b });
  store.setChatsSection(["c3"], "missing");
  assert.equal(useSidebarOrganizationStore.getState().sectionByChatId.c3, undefined);
});

test("a section records when it was made, and renames and filings stamp it", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const a = store.createCustomSection("A")!;
  const b = store.createCustomSection("B")!;
  const stamp = (id: string, at: number) =>
    useSidebarOrganizationStore.setState((state) => ({
      customSections: state.customSections.map((section) =>
        section.id === id ? { ...section, modifiedAt: at } : section,
      ),
    }));
  const section = (id: string) =>
    useSidebarOrganizationStore.getState().customSections.find((entry) => entry.id === id)!;
  assert.ok(section(a).createdAt && section(a).modifiedAt);
  stamp(a, 1);
  stamp(b, 1);
  store.renameCustomSection(a, "A");
  store.setChatsSection(["c1"], a);
  assert.ok(section(a).modifiedAt! > 1);
  stamp(a, 1);
  store.setChatsSection(["c1"], a);
  assert.equal(section(a).modifiedAt, 1);
  store.setChatsSection(["c1"], b);
  assert.ok(section(a).modifiedAt! > 1 && section(b).modifiedAt! > 1);
  stamp(a, 1);
  store.setProjectsSection(["p1"], a);
  assert.ok(section(a).modifiedAt! > 1);
});

test("deleting a section returns its rows and forgets its order and visibility", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const gone = store.createCustomSection("Gone")!;
  const kept = store.createCustomSection("Kept")!;
  store.setChatsSection(["c1"], gone);
  store.setChatsSection(["c2"], kept);
  store.setProjectsSection(["p1"], gone);
  store.setManualOrder(customSectionScope(gone), ["c1", "p1"]);
  store.setSectionHidden(gone, true);
  store.deleteCustomSection(gone);
  const state = useSidebarOrganizationStore.getState();
  assert.deepEqual(state.customSections.map((section) => section.id), [kept]);
  assert.deepEqual({ ...state.sectionByChatId }, { c2: kept });
  assert.deepEqual({ ...state.sectionByProjectId }, {});
  assert.equal(state.manualOrder[customSectionScope(gone)], undefined);
  assert.ok(!state.hiddenSections.includes(gone));
});

test("a section moves by dragging alone, and new sections open among the user's own", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const c = store.createCustomSection("C")!;
  const b = store.createCustomSection("B")!;
  const a = store.createCustomSection("A")!;
  const order = () => {
    const state = useSidebarOrganizationStore.getState();
    return resolveSectionOrder(state.sectionOrder, state.customSections);
  };
  const P = PINNED_SECTION_KEY;
  const J = PROJECTS_SECTION_KEY;
  assert.deepEqual(order(), [P, a, b, c, J]);
  store.moveSection(c, P, "top");
  assert.deepEqual(order(), [c, P, a, b, J]);
  assert.deepEqual(
    useSidebarOrganizationStore.getState().customSections.map((section) => section.id),
    [c, a, b],
  );
  assert.equal("moveCustomSection" in useSidebarOrganizationStore.getState(), false);
  assert.doesNotMatch(APP_SIDEBAR, /\bmoveSectionUp\b|\bmoveSectionDown\b|\bmoveCustomSection\b/);
});

test("no sidebar list sorts by priority", () => {
  assert.doesNotMatch(APP_SIDEBAR, /"priority"|PINNED_SORT_OPTIONS/);
  assert.match(
    APP_SIDEBAR,
    /\}> = \[\n  \{ value: "updated", key: "shell\.organize\.lastUpdated" \},\n  \{ value: "manual", key: "shell\.organize\.manualOrder" \},\n\];/,
  );
  const merged = mergePersistedOrganization(
    {
      pinnedSort: "priority",
      chatSort: "priority",
      customSections: [{ id: "s", name: "S", sort: "priority" }],
    },
    useSidebarOrganizationStore.getInitialState(),
  );
  assert.equal(merged.pinnedSort, "manual");
  assert.equal(merged.chatSort, "updated");
  assert.equal(merged.customSections[0]?.sort, "manual");
});

test("a dragged section lands on the edge it was dropped against", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const s = store.createCustomSection("S")!;
  const P = PINNED_SECTION_KEY;
  const J = PROJECTS_SECTION_KEY;
  const order = () => {
    const state = useSidebarOrganizationStore.getState();
    return resolveSectionOrder(state.sectionOrder, state.customSections);
  };
  assert.deepEqual(order(), [P, s, J]);
  store.moveSection(J, P, "top");
  assert.deepEqual(order(), [J, P, s]);
  store.moveSection(P, s, "bottom");
  assert.deepEqual(order(), [J, s, P]);
  const before = useSidebarOrganizationStore.getState();
  store.moveSection(s, P, "top");
  assert.equal(useSidebarOrganizationStore.getState(), before);
  const t2 = store.createCustomSection("T")!;
  assert.deepEqual(order(), [J, t2, s, P]);
  store.deleteCustomSection(s);
  assert.deepEqual(order(), [J, t2, P]);
});

test("a saved order is read over the sections that exist now", () => {
  const sections = [
    { id: "a", name: "A", sort: "manual" as const },
    { id: "b", name: "B", sort: "manual" as const },
  ];
  assert.deepEqual(resolveSectionOrder(["b", "gone", PROJECTS_SECTION_KEY, "b"], sections), [
    PINNED_SECTION_KEY,
    "b",
    "a",
    PROJECTS_SECTION_KEY,
  ]);
  assert.deepEqual(resolveSectionOrder([], []), [PINNED_SECTION_KEY, PROJECTS_SECTION_KEY]);
  assert.ok(!resolveSectionOrder(["recents"], sections).includes("recents"));
  const merged = mergePersistedOrganization(
    { customSections: sections, sectionOrder: [PROJECTS_SECTION_KEY, "a", 7, "zzz"] },
    useSidebarOrganizationStore.getInitialState(),
  );
  assert.deepEqual(merged.sectionOrder, [PINNED_SECTION_KEY, "b", PROJECTS_SECTION_KEY, "a"]);
});

test("Show toggles hide Projects and custom sections independently, never Pinned", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const id = store.createCustomSection("S")!;
  store.setSectionHidden(id, true);
  store.setSectionHidden(id, true);
  assert.deepEqual(useSidebarOrganizationStore.getState().hiddenSections, [id]);
  store.setSectionHidden(PROJECTS_SECTION_KEY, true);
  store.setSectionHidden(id, false);
  assert.deepEqual(useSidebarOrganizationStore.getState().hiddenSections, [
    PROJECTS_SECTION_KEY,
  ]);
  const merged = mergePersistedOrganization(
    { hiddenSections: ["pinned", PROJECTS_SECTION_KEY] },
    useSidebarOrganizationStore.getState(),
  );
  assert.deepEqual(merged.hiddenSections, [PROJECTS_SECTION_KEY]);
});

test("a saved payload keeps only well-formed sections and assignments to them", () => {
  const merged = mergePersistedOrganization(
    {
      customSections: [
        { id: "s1", name: " Reading ", sort: "updated" },
        { id: "s1", name: "Duplicate" },
        { id: "s2", name: "   " },
        { id: 7, name: "Bad id" },
        { id: "s3", name: "Loose", sort: "sideways" },
        null,
      ],
      sectionByChatId: { c1: "s1", c2: "s2", c3: 4 },
      sectionByProjectId: { p1: "s3", p2: "nope" },
      hiddenSections: ["pinned", "s3", "s3", "recents", "nope", 1],
    },
    useSidebarOrganizationStore.getInitialState(),
  );
  assert.deepEqual(merged.customSections, [
    { id: "s1", name: "Reading", sort: "updated" },
    { id: "s3", name: "Loose", sort: "manual" },
  ]);
  assert.deepEqual({ ...merged.sectionByChatId }, { c1: "s1" });
  assert.deepEqual({ ...merged.sectionByProjectId }, { p1: "s3" });
  assert.deepEqual(merged.hiddenSections, ["s3"]);
  assert.equal(SIDEBAR_ORGANIZATION_STORAGE_KEY, "unsloth_sidebar_organization");
});

test("a section's scope cannot be mistaken for a built-in list", () => {
  assert.equal(customSectionIdOf(customSectionScope("abc")), "abc");
  for (const scope of [
    RECENTS_ORDER_SCOPE,
    PINNED_ORDER_SCOPE,
    PROJECT_ORDER_SCOPE,
    projectOrderScope("section:abc"),
  ]) {
    assert.equal(customSectionIdOf(scope), null, scope);
  }
});

// Section S holds folder "lab" and chat s1; chat p1 is pinned; r1 and r2 are Recents rows;
// folder "home" is under Projects with chat c3.
const S = "s";
const SCOPE = customSectionScope(S);

function context(overrides: Partial<SidebarDropContext> = {}): SidebarDropContext {
  return {
    organizeBy: "project",
    chatSort: "updated",
    pinnedSort: "manual",
    projectSort: "manual",
    pinnedChatIds: new Set(["p1"]),
    pinnedProjectIds: new Set(),
    sectionByChatId: { s1: S },
    sectionByProjectId: { lab: S },
    sectionByPageId: {},
    sectionSort: () => "manual",
    orders: {
      pinned: ["p1"],
      projects: ["home"],
      recents: ["r1", "r2"],
      projectChats: (projectId) => ({ home: ["c3"], lab: ["l1"] })[projectId] ?? [],
      sections: (sectionId) => (sectionId === S ? ["lab", "s1"] : []),
    },
    ...overrides,
  };
}

const chat = (
  id: string,
  section: SidebarDragItem["section"],
  scope: string,
  projectId: string | null = null,
): SidebarDragItem => ({ kind: "chat", id, section, scope, projectId });
const chatRow = (
  section: SidebarDropZone["section"],
  scope: string,
  id: string,
  folderId?: string,
): SidebarDropZone => ({ section, row: { id, kind: "chat", scope }, folderId });

test("a Recents chat dropped on a section is filed there, in the slot shown", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      chat("r1", "recents", RECENTS_ORDER_SCOPE),
      chatRow(SCOPE, SCOPE, "s1"),
      "top",
      context(),
    ),
  );
  assert.deepEqual(plan.action, { kind: "section", sectionId: S });
  assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "r1", sectionId: S });
  assert.deepEqual(plan.effects.orders, [{ scope: SCOPE, ids: ["lab", "r1", "s1"] }]);
  assert.equal(plan.effects.unpinChat, undefined);
});

test("a pinned chat dropped on a section loses its pin", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      chat("p1", "pinned", PINNED_ORDER_SCOPE),
      { section: SCOPE },
      "bottom",
      context(),
    ),
  );
  assert.equal(plan.effects.unpinChat, "p1");
  assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "p1", sectionId: S });
  assert.deepEqual(plan.effects.orders[0].ids, ["lab", "s1", "p1"]);
});

test("an empty section takes a drop anywhere in it, and rings itself", () => {
  const empty = context({ sectionByChatId: {}, sectionByProjectId: {} });
  const plan = plannedDrop(
    planSidebarDrop(chat("r2", "recents", RECENTS_ORDER_SCOPE), { section: SCOPE }, "top", {
      ...empty,
      orders: { ...empty.orders, sections: () => [] },
    }),
  );
  assert.deepEqual(plan.cue, { ring: sectionRingKey(SCOPE) });
  assert.deepEqual(plan.effects.orders, [{ scope: SCOPE, ids: ["r2"] }]);
});

test("a folder dropped on a section is filed with its chats", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      { kind: "project", id: "home", section: "projects", scope: PROJECT_ORDER_SCOPE, projectId: null },
      chatRow(SCOPE, SCOPE, "s1"),
      "bottom",
      context(),
    ),
  );
  assert.deepEqual(plan.effects.fileInSection, {
    kind: "project",
    id: "home",
    sectionId: S,
  });
  assert.deepEqual(plan.effects.orders[0].ids, ["lab", "s1", "home"]);
});

test("a row already in the section reorders, switching a sorted section to Manual", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      chat("s1", SCOPE, SCOPE),
      { section: SCOPE, row: { id: "lab", kind: "project", scope: SCOPE }, folderId: "lab" },
      "top",
      context({ sectionSort: () => "updated" }),
    ),
  );
  assert.equal(plan.action.kind, "reorder");
  assert.equal(plan.effects.fileInSection, undefined);
  assert.deepEqual(plan.effects.orders, [{ scope: SCOPE, ids: ["s1", "lab"] }]);
  assert.equal(plan.effects.switchSort, SCOPE);
});

test("a section's chat dragged to Recents leaves the section", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      chat("s1", SCOPE, SCOPE),
      chatRow("recents", RECENTS_ORDER_SCOPE, "r1"),
      "bottom",
      context(),
    ),
  );
  assert.deepEqual(plan.action, { kind: "section", sectionId: null });
  assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
  assert.deepEqual(plan.effects.orders[0].ids, ["r1", "s1", "r2"]);
});

test("a section's chat dragged into a folder moves there and leaves the section", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      chat("s1", SCOPE, SCOPE),
      chatRow("projects", projectOrderScope("home"), "c3", "home"),
      "bottom",
      context(),
    ),
  );
  assert.deepEqual(plan.effects.moveChat, { chatId: "s1", projectId: "home" });
  assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
  assert.equal(plan.effects.unpinChat, undefined);
});

test("a section's chat dropped back on its own folder only leaves the section", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      chat("s1", SCOPE, SCOPE, "home"),
      chatRow("projects", projectOrderScope("home"), "c3", "home"),
      "top",
      context(),
    ),
  );
  assert.deepEqual(plan.action, { kind: "section", sectionId: null });
  assert.equal(plan.effects.moveChat, undefined);
  assert.equal(plan.effects.unpinChat, undefined);
  assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
});

test("a section's folder dragged to Projects leaves the section", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      { kind: "project", id: "lab", section: SCOPE, scope: SCOPE, projectId: null },
      { section: "projects", row: { id: "home", kind: "project", scope: PROJECT_ORDER_SCOPE }, folderId: "home" },
      "bottom",
      context(),
    ),
  );
  assert.deepEqual(plan.action, { kind: "section", sectionId: null });
  assert.equal(plan.effects.unpinProject, undefined);
  assert.deepEqual(plan.effects.fileInSection, { kind: "project", id: "lab", sectionId: null });
  assert.deepEqual(plan.effects.orders[0].ids, ["home", "lab"]);
});

test("a chat dropped on a section's folder files into the project, not the section", () => {
  const plan = plannedDrop(
    planSidebarDrop(
      chat("r1", "recents", RECENTS_ORDER_SCOPE),
      chatRow(SCOPE, projectOrderScope("lab"), "l1", "lab"),
      "bottom",
      context(),
    ),
  );
  assert.deepEqual(plan.effects.moveChat, { chatId: "r1", projectId: "lab" });
  assert.equal(plan.effects.fileInSection, undefined);
});

test("reordering Pinned keeps a pinned row's section for when it is unpinned", () => {
  const ctx = context({
    pinnedChatIds: new Set(["p1", "s1"]),
    orders: { ...context().orders, pinned: ["p1", "s1"] },
  });
  const plan = plannedDrop(
    planSidebarDrop(
      chat("s1", "pinned", PINNED_ORDER_SCOPE),
      chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
      "top",
      ctx,
    ),
  );
  assert.equal(plan.action.kind, "reorder");
  assert.equal(plan.effects.fileInSection, undefined);
});

test("a section's row dragged into Pinned keeps its section for when it is unpinned", () => {
  const chatPlan = plannedDrop(
    planSidebarDrop(chat("s1", SCOPE, SCOPE), chatRow("pinned", PINNED_ORDER_SCOPE, "p1"), "bottom", context()),
  );
  assert.equal(chatPlan.action.kind, "pin");
  assert.equal(chatPlan.effects.pinChat, "s1");
  assert.equal(chatPlan.effects.fileInSection, undefined);
  const folderPlan = plannedDrop(
    planSidebarDrop(
      { kind: "project", id: "lab", section: SCOPE, scope: SCOPE, projectId: null },
      chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
      "bottom",
      context(),
    ),
  );
  assert.equal(folderPlan.action.kind, "pin");
  assert.equal(folderPlan.effects.pinProject, "lab");
  assert.equal(folderPlan.effects.fileInSection, undefined);
  const intoFolder = plannedDrop(
    planSidebarDrop(
      chat("s1", SCOPE, SCOPE),
      chatRow("pinned", projectOrderScope("home"), "c3", "home"),
      "top",
      context({ pinnedProjectIds: new Set(["home"]), orders: { ...context().orders, pinned: ["p1", "home"] } }),
    ),
  );
  assert.equal(intoFolder.action.kind, "move");
  assert.deepEqual(intoFolder.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
});

test("each list header's menu carries only what that list is about, as in ChatGPT", () => {
  const menu = APP_SIDEBAR.slice(
    APP_SIDEBAR.indexOf("function renderSidebarHeaderMenu("),
    APP_SIDEBAR.indexOf("function renderSectionItems("),
  );
  const branch = (from: string, to: string) =>
    menu.slice(menu.indexOf(from), to ? menu.indexOf(to) : undefined);
  const pinned = branch('if (options.kind === "pinned")', '} else if (options.kind === "projects")');
  const projects = branch('} else if (options.kind === "projects")', '} else if (options.kind === "recents")');
  const recents = branch('} else if (options.kind === "recents")', '} else if (options.kind === "section")');
  const section = branch('} else if (options.kind === "section")', "return (\n      <NonModalDropdownMenu");
  assert.match(pinned, /value=\{pinnedSort\}/);
  assert.doesNotMatch(pinned, /organizeSubmenu|renderSortSubmenu|setSectionHidden|mode: "create"/);
  assert.match(projects, /\{organizeSubmenu\}/);
  assert.match(projects, /shell\.organize\.sortChatsBy/);
  assert.doesNotMatch(projects, /sortProjectsBy/);
  assert.match(menu, /className=\{cn\("unsloth-plus-menu sidebar-row-menu sidebar-menu"/);
  assert.match(menu, /<NonModalDropdownMenu\n\s*side="bottom"\n\s*align="start"/);
  assert.doesNotMatch(menu, /className="unsloth-plus-menu w-/);
  assert.match(menu, /icon=\{PanelLeftIcon\}/);
  assert.match(APP_SIDEBAR, /value: "project", key: "shell\.organize\.byProject", icon: ProjectIcon/);
  assert.match(APP_SIDEBAR, /value: "list", key: "shell\.organize\.inOneList", icon: LeftToRightListBulletIcon/);
  assert.doesNotMatch(projects, /setSectionHidden|mode: "create"/);
  assert.match(recents, /\{organizeSubmenu\}[\s\S]*shell\.organize\.sortChatsBy/);
  assert.match(recents, /t\("shell\.organize\.show"\)/);
  assert.match(recents, /setSectionHidden\(PROJECTS_SECTION_KEY, !on\)/);
  assert.match(recents, /setSectionHidden\(candidate\.id, !on\)/);
  assert.match(recents, /setSectionDialog\(\{ mode: "create" \}\)/);
  assert.doesNotMatch(APP_SIDEBAR, /setSectionHidden\(PINNED_SECTION_KEY/);
  assert.match(section, /mode: "rename", section/);
  assert.match(section, /removeCustomSection\(section\)/);
  assert.doesNotMatch(section, /organizeSubmenu|setSectionHidden|mode: "create"/);
  for (const kind of ["pinned", "projects", "recents", "section"]) {
    assert.match(APP_SIDEBAR, new RegExp(`renderSidebarHeaderMenu\\(\\{\\n[^}]*kind: "${kind}",`));
  }
  assert.ok(!APP_SIDEBAR.includes("includeOrganize"));
});

test("chat and folder menus, and bulk selections, can file into a section", () => {
  assert.match(APP_SIDEBAR, /target: \{ chatIds: \[item\.id\] \},/);
  assert.match(APP_SIDEBAR, /target: \{ projectIds: \[project\.id\] \},/);
  assert.match(APP_SIDEBAR, /renderBulkSectionSubmenu\(\n\s*"chat",/);
  assert.match(APP_SIDEBAR, /renderBulkSectionSubmenu\(\n\s*"project",/);
});

test("a drop's filing is committed with its slot", () => {
  const commit = APP_SIDEBAR.slice(
    APP_SIDEBAR.indexOf("function commitDrop("),
    APP_SIDEBAR.indexOf("function dropCueClass("),
  );
  assert.match(commit, /if \(filing\.kind === "chat"\) setChatsSection\(\[filing\.id\], filing\.sectionId\);/);
  assert.match(commit, /setCustomSectionSort\(sortedSection, "manual"\);/);
});

test("the section strings exist in English", () => {
  for (const key of [
    'createTitle: "New section"',
    'createDescription: "Group chats and projects however you like"',
    'namePlaceholder: "Section name"',
    'create: "Create section"',
  ]) {
    assert.ok(EN.includes(key), key);
  }
});

test("a section's header starts a chat that is filed there on its first send", () => {
  const section = APP_SIDEBAR.slice(
    APP_SIDEBAR.indexOf("function renderCustomSection("),
    APP_SIDEBAR.indexOf("function renderProjectsSection("),
  );
  assert.match(section, /onClick=\{\(\) => openNewChatInSection\(section\.id\)\}/);
  assert.match(section, /icon=\{PencilEdit02Icon\}/);
  assert.match(
    APP_SIDEBAR,
    /navigate\(\{ to: "\/chat", search: \{ new: nonce \} \}\)\.then\(\(\) =>\n\s*setPendingNewChatSection\(\{ sectionId, nonce \}\),/,
  );
  const effect = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("if (!pendingNewChatSection) return;"));
  assert.match(effect, /const fresh = isChatRoute && !search\.thread && !search\.project;/);
  assert.match(
    effect,
    /if \(fresh && search\.new === nonce && !search\.compare\) \{\n\s*if \(storeThreadId\) \{\n\s*setChatsSection\(\[storeThreadId\], sectionId\);\n\s*setPendingNewChatSection\(null\);/,
  );
  assert.match(
    effect,
    /fresh &&\n\s*!search\.new &&\n\s*search\.compare &&\n\s*!allChatItems\.some\(\(item\) => item\.id === search\.compare\)/,
  );
  assert.match(effect, /setPendingNewChatSection\(newCompare \? \{ sectionId, nonce, compare: newCompare \} : null\);/);
  assert.match(effect, /if \(!\(fresh && !search\.new && search\.compare === compare\)\) \{\n\s*setPendingNewChatSection\(null\);/);
  assert.match(
    effect,
    /allChatItems\.some\(\(item\) => item\.type === "compare" && item\.id === compare\)\) \{\n\s*setChatsSection\(\[compare\], sectionId\);/,
  );
  const store = useSidebarOrganizationStore.getInitialState();
  assert.equal(store.pendingNewChatSection, null);
});

test("sections above Recents drag by their headers, and Recents stays last", async () => {
  assert.match(
    APP_SIDEBAR,
    /\{orderedSectionKeys\.map\(\(key\) => \(\n\s*<Fragment key=\{key\}>\{renderOrderedSection\(key\)\}<\/Fragment>/,
  );
  assert.match(APP_SIDEBAR, /data-sidebar-section=\{key\}\n\s*onPointerDown=\{\(event\) => startSectionDrag\(event, key\)\}/);
  assert.match(
    APP_SIDEBAR,
    /useSectionDrag\(\{\n\s*onDrop: \(key, landing\) => moveSection\(key, landing\.target, landing\.edge\),/,
  );
  const drag = await readSrcAsync("features/chat/hooks/use-section-drag.ts");
  // Not by touch, which scrolls.
  assert.match(drag, /event\.pointerType === "touch"/);
  assert.match(drag, /const HEADER_SELECTOR = '\[data-sidebar="group-label"\]';/);
  assert.match(drag, /if \(pressed\.closest\(HEADER_ACTION_SELECTOR\)\) return;/);
  // The release lands on the header, which must not fold the section it moved.
  assert.match(drag, /window\.addEventListener\("click", stop, \{ capture: true, once: true \}\)/);
  assert.match(drag, /optionsRef\.current\.onDrop\(key, dropped\);/);
});


test("the sidebar and account menus share one flat surface and type; other menus keep theirs", async () => {
  const css = await readSrcAsync("index.css");
  assert.match(css, /\.dark \.unsloth-plus-menu\[data-slot\] \{\n\s*background-color: var\(--card\);/);
  assert.match(
    css,
    /\.unsloth-plus-menu\[data-slot\] \{[\s\S]*?box-shadow: 0 2px 8px -2px rgba\(0, 0, 0, 0\.16\);\n\s*\}/,
  );
  const tagged = ":is\\(\\.unsloth-plus-menu, \\.app-user-menu\\)\\.sidebar-menu\\[data-slot\\]";
  // No shadow in dark mode, over the shared menu shadow's !important. Light mode keeps it.
  assert.match(css, new RegExp(`\\.dark ${tagged},\\n\\s*\\.dark \\.app-user-menu\\.menu-soft-surface-up \\{\\n\\s*box-shadow: none !important;`));
  assert.doesNotMatch(css, new RegExp(`\\n\\t${tagged} \\{\\n\\s*box-shadow: none`));
  assert.match(
    css,
    new RegExp(
      `\\.dark ${tagged} \\{\\n\\s*background-color: color-mix\\(in srgb, var\\(--card\\), white 6\\.5%\\);\\n\\s*color: #fff;`,
    ),
  );
  assert.match(css, new RegExp(`${tagged} \\{\\n\\s*font-family: ui-sans-serif,`));
  assert.match(
    css,
    /\.unsloth-plus-menu\.sidebar-row-menu\.sidebar-menu :is\([\s\S]*?\) \{\n\s*@apply py-2 text-ui-14;/,
  );
  assert.match(css, /\.app-user-menu\.sidebar-menu :is\([\s\S]*?\) \{\n\s*@apply text-ui-14;\n\s*font-weight: 400;/);
  assert.equal((APP_SIDEBAR.match(/"unsloth-plus-menu sidebar-row-menu sidebar-menu/g) ?? []).length, 12);
  assert.match(APP_SIDEBAR, /className="app-user-menu sidebar-menu menu-soft-surface-up/);
});

test("a custom section's menu edits it, acts on its chats, and removes it", () => {
  const menu = APP_SIDEBAR.slice(
    APP_SIDEBAR.indexOf('} else if (options.kind === "section") {'),
    APP_SIDEBAR.indexOf("    return (\n      // Opens out to the right"),
  );
  const labels = [...menu.matchAll(/t\("(shell\.[\w.]+)"\)/g)].map((match) => match[1]);
  assert.deepEqual(labels, [
    "shell.sections.edit",
    "shell.sections.markAllRead",
    "shell.selection.archiveChats",
    "shell.sections.remove",
  ]);
  assert.equal((menu.match(/<DropdownMenuSeparator \/>/g) ?? []).length, 2);
  assert.match(menu, /row\.kind === "chat" \? \[row\.item\] : \[\]/);
  // the whole section's unread chats, not only its loaded pages
  assert.match(menu, /disabled=\{unreadInSection\.length === 0\}/);
  assert.match(menu, /onSelect=\{\(\) => clearThreadsUnread\(unreadInSection\)\}/);
  assert.match(menu, /disabled=\{chats\.length === 0\}\n\s*onSelect=\{\(\) => void archiveSection\(\)\.catch\(\(\) => undefined\)\}/);
  assert.match(menu, /await archiveChatItems\(all\);/);
  assert.match(menu, /icon=\{Settings01Icon\}[\s\S]*icon=\{Tick02Icon\}[\s\S]*icon=\{ArchiveIcon\}[\s\S]*icon=\{Cancel01Icon\}/);
  assert.doesNotMatch(menu, /variant="destructive"|renderSortSubmenu/);
});

test("a section drag draws itself, so the sidebar re-renders only on the drop", async () => {
  const drag = await readSrcAsync("features/chat/hooks/use-section-drag.ts");
  assert.doesNotMatch(drag, /useState|setState/);
  assert.match(drag, /block\.setAttribute\(SECTION_DRAGGING_ATTR, ""\);/);
  // Drawn in the drag layer: removing a body child mid-drag restyled the whole page.
  assert.match(drag, /dragLayer\(\)\.append\(ghost, line\);/);
  assert.doesNotMatch(drag, /document\.body\.append/);
  assert.match(drag, /ghostTop = textRect\.top - 6;\n\s*Object\.assign\(ghost\.style, \{\n\s*top: `\$\{ghostTop\}px`,/);
  assert.match(drag, /translate3d\(0, \$\{Math\.round\(top - ghostTop\)\}px, 0\)/);
  assert.match(drag, /line\.style\.top = `\$\{y - 0\.75\}px`|top: `\$\{y - 0\.75\}px`/);
  // Marked on the sidebar, not the body, whose every change restyles the page.
  assert.match(drag, /markDragging\(sidebarOf\(list\), true\);/);
  assert.match(drag, /markDragging\(null, false\);/);
  assert.doesNotMatch(APP_SIDEBAR, /sectionDrag\b|setSectionDrag/);
  assert.match(drag, /document\.body\.setPointerCapture\(pointerId\);/);
  assert.match(drag, /frame = requestAnimationFrame\(onFrame\);\n\s*edgeScroll\(\);\n\s*place\(\);/);
  assert.match(drag, /if \(moved\.pointerId !== pointerId \|\| escaped\) return;/);
  assert.match(drag, /escaped = true;\n\s*putDown\(\);/);
  const css = await readSrcAsync("index.css");
  assert.match(css, /\[data-sidebar-section\]\[data-section-dragging\] \{\n\s*opacity: 0\.4;/);
  assert.match(css, /\.sidebar-section-drop-line \{[\s\S]*?border-top: 1\.5px solid var\(--foreground\);/);
});

test("a carried section lands against the nearest gap, and only a real move draws a line", async () => {
  const { sectionLandingAt, landingMoves } = await import("../src/features/chat/hooks/use-section-drag.ts");
  const blocks = [
    { key: "pinned", top: 0, bottom: 100 },
    { key: "a", top: 100, bottom: 400 },
    { key: "projects", top: 400, bottom: 500 },
  ];
  assert.deepEqual(sectionLandingAt(blocks, 40), { target: "pinned", edge: "top" });
  assert.deepEqual(sectionLandingAt(blocks, 240), { target: "a", edge: "top" });
  assert.deepEqual(sectionLandingAt(blocks, 260), { target: "projects", edge: "top" });
  assert.deepEqual(sectionLandingAt(blocks, 480), { target: "projects", edge: "bottom" });
  assert.equal(sectionLandingAt([], 10), null);
  const drawn = ["pinned", "b", "a", "projects"];
  assert.equal(landingMoves(drawn, "b", { target: "a", edge: "top" }), false);
  assert.equal(landingMoves(drawn, "b", { target: "pinned", edge: "bottom" }), false);
  assert.equal(landingMoves(drawn, "b", { target: "pinned", edge: "top" }), true);
  assert.equal(landingMoves(drawn, "b", { target: "projects", edge: "bottom" }), true);
});

test("sidebar and account submenus open clear of their menu, first rows level", () => {
  // Radix measures sideOffset from the trigger row, inside the menu's padding.
  assert.match(
    APP_SIDEBAR,
    /sideOffset: Math\.round\(SIDEBAR_MENU_PAD_X \* uiSpaceScale \+ SUBMENU_GAP_PX\),\n\s*alignOffset: -Math\.round\(SIDEBAR_MENU_PAD_Y \* uiSpaceScale \+ MENU_ROW_MARGIN_PX\),/,
  );
  assert.match(APP_SIDEBAR, /sideOffset: ACCOUNT_MENU_PAD_X \+ SUBMENU_GAP_PX,/);
  assert.equal((APP_SIDEBAR.match(/\{\.\.\.sidebarSubmenuOffsets\}/g) ?? []).length, 4);
  assert.equal((APP_SIDEBAR.match(/\{\.\.\.accountSubmenuOffsets\}/g) ?? []).length, 1);
  assert.doesNotMatch(APP_SIDEBAR, /SubContent[^>]*sideOffset=\{[0-9]+\}[^>]*sidebar-menu/);
});

test("sidebar and account menus read white on a lighter surface in dark mode", async () => {
  const css = await readSrcAsync("index.css");
  assert.match(
    css,
    /\.dark \.app-user-menu\.sidebar-menu :is\([\s\S]*?\):is\(:focus, \[data-state="open"\]\) \{\n\s*background-color: rgb\(255 255 255 \/ calc\(0\.1 \* var\(--contrast-wash-gain, 1\)\)\);\n\s*color: #fff;/,
  );
  assert.match(css, /\[data-slot="dropdown-menu-radio-item-indicator"\]\n\s*\) \{\n\s*@apply right-2\.5;/);
});


test("undoing a removed section puts it back where it was drawn", async () => {
  assert.match(APP_SIDEBAR, /const undo = removeCustomSectionWithUndo\(section\);/);
  const body = await readSrcAsync("features/chat/stores/remove-custom-section.ts");
  assert.match(body, /const followers = drawnOrder\.slice\(drawnOrder\.indexOf\(section\.id\) \+ 1\);/);
  assert.match(body, /const follower = followers\.find\(\(key\) => sectionOrder\.includes\(key\)\);/);
  assert.match(body, /customSections: inSectionOrder\(restored, sectionOrder\),\n\s*sectionOrder,/);
});

test("the section name dialog keeps its mode while it closes", async () => {
  const dialog = await readSrcAsync("features/chat/components/section-name-dialog.tsx");
  assert.match(dialog, /if \(open && \(shown\.mode !== mode \|\| shown\.initialName !== initialName\)\)/);
  assert.match(dialog, /mode=\{shown\.mode\}\n\s*initialName=\{shown\.initialName\}/);
});

// Row ids are arbitrary; on a plain object "constructor" would read as filed.
test("a row id named like an object built-in is unfiled until it is filed", () => {
  resetStore();
  const ids = ["constructor", "toString", "hasOwnProperty", "__proto__"];
  const views = () => {
    const state = useSidebarOrganizationStore.getState();
    return [state.sectionByChatId, state.sectionByProjectId];
  };
  for (const map of views()) for (const id of ids) assert.equal(map[id], undefined);
  const store = useSidebarOrganizationStore.getState();
  const a = store.createCustomSection("A")!;
  store.setChatsSection(ids, a);
  store.setProjectsSection(ids, a);
  for (const map of views()) for (const id of ids) assert.equal(map[id], a);
  assert.deepEqual(Object.keys(views()[0]).sort(), [...ids].sort());
  store.setChatsSection(ids, null);
  for (const id of ids) assert.equal(views()[0][id], undefined);
  const merged = mergePersistedOrganization(
    JSON.parse(
      '{"customSections":[{"id":"s","name":"S","sort":"manual"}],"sectionByChatId":{"__proto__":"s","toString":"s"},"sectionByProjectId":{}}',
    ),
    useSidebarOrganizationStore.getInitialState(),
  );
  assert.equal(merged.sectionByChatId["__proto__"], "s");
  assert.equal(merged.sectionByChatId.toString, "s" as unknown);
  assert.equal(merged.sectionByChatId.constructor, undefined);
  assert.equal(merged.sectionByProjectId.hasOwnProperty, undefined);
  store.deleteCustomSection(a);
  for (const map of views()) for (const id of ids) assert.equal(map[id], undefined);
  resetStore();
});

// A later drop of a chat supersedes the earlier drop's pending move.
test("a later drop of a chat supersedes its earlier drop's pending move", () => {
  const commit = APP_SIDEBAR.slice(
    APP_SIDEBAR.indexOf("function commitDrop("),
    APP_SIDEBAR.indexOf("/** The insertion line for a row, on the landing edge. */"),
  );
  assert.match(commit, /function commitDrop\(plan: SidebarDropPlan, dragged: SidebarDragItem\) \{/);
  assert.match(
    commit,
    /const pendingMove = dragged\.kind === "chat" \? chatMovesRef\.current\.get\(dragged\.id\) : undefined;\n\s*if \(pendingMove && !effects\.moveChat\) \{\n\s*chatMovesRef\.current\.set\(dragged\.id, \{\n\s*generation: pendingMove\.generation \+ 1,\n\s*chain: pendingMove\.chain,/,
  );
  assert.ok(commit.indexOf("const pendingMove") < commit.indexOf("if (!move) {"));
  assert.match(commit, /if \(!moved \|\| moves\.get\(item\.id\)\?\.generation !== generation\) return;/);
});

test("a chat moved into a project from its menu leaves its section, as a drop does", () => {
  const fn = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("async function moveChatToProjectFromMenu("));
  assert.match(fn, /if \(!\(await moveChatToProject\(item, projectId\)\) \|\| filedSince\) return;/);
  assert.match(fn, /filedSince \|\|= now\.sectionByChatId\[item\.id\] !== before\.sectionByChatId\[item\.id\];/);
  assert.match(fn, /now\.organizeBy === "project" &&\n\s*!usePinnedChatsStore\.getState\(\)\.pinnedIds\.includes\(item\.id\)\n\s*\) \{\n\s*setChatsSection\(\[item\.id\], null\);/);
  assert.match(fn, /\} finally \{\n\s*stopWatching\(\);/);
  assert.match(APP_SIDEBAR, /onSelect=\{\(\) => void moveChatToProjectFromMenu\(item, project\.id\)\}/);
  assert.match(APP_SIDEBAR, /await moveChatToProjectFromMenu\(moveTarget, project\.id\);/);
  assert.doesNotMatch(APP_SIDEBAR, /onSelect=\{\(\) => void moveChatToProject\(item, project\.id\)\}/);
});

test("a saved section keyed like Pinned or Projects is dropped, and so are its rows' filings", () => {
  const merged = mergePersistedOrganization(
    {
      customSections: [
        { id: PROJECTS_SECTION_KEY, name: "Impostor", sort: "manual" },
        { id: PINNED_SECTION_KEY, name: "Impostor", sort: "manual" },
        { id: "real", name: "Real", sort: "manual" },
      ],
      sectionByChatId: { c1: PROJECTS_SECTION_KEY, c2: "real" },
      sectionByProjectId: { p1: PINNED_SECTION_KEY },
    },
    useSidebarOrganizationStore.getInitialState(),
  );
  assert.deepEqual(merged.customSections.map((section) => section.id), ["real"]);
  assert.deepEqual({ ...merged.sectionByChatId }, { c2: "real" });
  assert.deepEqual({ ...merged.sectionByProjectId }, {});
});

test("a saved automatic project sort, no longer offered, falls back to Manual", () => {
  for (const projectSort of ["updated", "name", "created", "manual", "bogus"]) {
    const merged = mergePersistedOrganization(
      { projectSort },
      useSidebarOrganizationStore.getInitialState(),
    );
    assert.equal(merged.projectSort, "manual", projectSort);
  }
});

test("a chat filed from its menu while its drop into a folder is in flight keeps that filing", () => {
  assert.match(
    APP_SIDEBAR,
    /filedSince \|\|= now\.sectionByChatId\[item\.id\] !== before\.sectionByChatId\[item\.id\];/,
  );
  assert.match(APP_SIDEBAR, /if \(!filedSince\) applyFiling\(\);\n\s*applyOrders\(ordersBefore, sortPicked\);/);
});

test("custom sections re-measure the bottom fade when they change the list's height", () => {
  assert.match(APP_SIDEBAR, /for \(const section of el\.children\) observer\.observe\(section\);/);
});

test("Alt + arrow on a section's header moves it, as it moves a row", async () => {
  const hook = await readSrcAsync("features/chat/hooks/use-section-drag.ts");
  assert.match(hook, /export function sectionKeyLanding\(/);
  assert.match(hook, /const header = pressed\.closest\(HEADER_SELECTOR\);/);
  assert.match(hook, /if \(pressed\.closest\(HEADER_ACTION_SELECTOR\)\) return null;/);
  assert.match(hook, /return neighbour \? \{ target: neighbour, edge: up \? "top" : "bottom" \} : null;/);
  assert.match(
    APP_SIDEBAR,
    /onKeyDown=\{\(event\) => \{\n\s*const landing = sectionKeyLanding\(event, key\);\n\s*if \(!landing\) return;\n\s*event\.preventDefault\(\);\n\s*moveSection\(key, landing\.target, landing\.edge\);/,
  );
});

test("a pinned row can be filed back into the section it kept while pinned", () => {
  assert.match(APP_SIDEBAR, /current: pinnedIdSet\.has\(item\.id\) \? null : sectionByChatId\[item\.id\] \?\? null,/);
  assert.match(
    APP_SIDEBAR,
    /current: pinnedProjectIdSet\.has\(project\.id\) \? null : sectionByProjectId\[project\.id\] \?\? null,/,
  );
  assert.match(
    APP_SIDEBAR,
    /new Set\(ids\.map\(\(id\) => \(pinned\.has\(id\) \? null : assignments\[id\] \?\? null\)\)\)/,
  );
});

test("a hidden Projects section's chats are not walked or selected", () => {
  assert.match(
    APP_SIDEBAR,
    /folderChatItems\(projectsSectionRendered && projectsOpen, visibleProjectRecords\)/,
  );
});

test("signing in as another account drops the previous account's sections", async () => {
  const { transitionBrowserAccount, BROWSER_ACCOUNT_KEY } = await import(
    "../src/lib/account-transition.ts"
  );
  const memory = (): Storage => {
    const map = new Map<string, string>();
    return {
      get length() {
        return map.size;
      },
      key: (index: number) => [...map.keys()][index] ?? null,
      getItem: (key: string) => map.get(key) ?? null,
      setItem: (key: string, value: string) => void map.set(key, value),
      removeItem: (key: string) => void map.delete(key),
      clear: () => map.clear(),
    };
  };
  const localStorage = memory();
  localStorage.setItem(BROWSER_ACCOUNT_KEY, "account:a1:alice");
  localStorage.setItem(
    SIDEBAR_ORGANIZATION_STORAGE_KEY,
    JSON.stringify({ state: { customSections: [{ id: "s1", name: "Alice's", sort: "manual" }] } }),
  );
  let reloadedTo = "";
  const indexedDB = {
    deleteDatabase() {
      const request: { onsuccess?: () => void } = {};
      queueMicrotask(() => request.onsuccess?.());
      return request;
    },
  } as unknown as IDBFactory;
  const changed = await transitionBrowserAccount({ username: "bob", accountId: "b2" }, "/chat", () => {}, {
    localStorage,
    sessionStorage: memory(),
    indexedDB,
    location: { replace: (url: string) => void (reloadedTo = url) } as Location,
  });
  assert.equal(changed, true);
  assert.equal(localStorage.getItem(SIDEBAR_ORGANIZATION_STORAGE_KEY), null);
  assert.equal(reloadedTo, "/chat");
});

test("a row's section menu offers Remove from section only when it is in one", async () => {
  assert.match(
    APP_SIDEBAR,
    /\{config\.anyFiled && \(\n\s*<P\.Item onSelect=\{\(\) => fileSectionTarget\(target, null\)\}>/,
  );
  assert.doesNotMatch(APP_SIDEBAR, /disabled=\{!config\.anyFiled\}/);
  assert.match(APP_SIDEBAR, /anyFiled: !pinnedIdSet\.has\(item\.id\) && Boolean\(sectionByChatId\[item\.id\]\),/);
  assert.match(
    APP_SIDEBAR,
    /anyFiled: !pinnedProjectIdSet\.has\(project\.id\) && Boolean\(sectionByProjectId\[project\.id\]\),/,
  );
  assert.match(APP_SIDEBAR, /anyFiled: ids\.some\(\(id\) => !pinned\.has\(id\) && Boolean\(assignments\[id\]\)\),/);
  for (const locale of ["en", "de", "ja"]) {
    const source = await readSrcAsync(`i18n/locales/${locale}.ts`);
    assert.match(source, /removeFromSection: "/, locale);
    assert.doesNotMatch(source, /noSection:/, locale);
  }
});

// ---------------------------------------------------------------------------------------------
// Pinned pages drag like chats

const page = (id: string, section: SidebarDragItem["section"], scope: string): SidebarDragItem => ({
  kind: "page",
  id,
  section,
  scope,
  projectId: null,
});

test("a pinned page reorders among Pinned's chats, and a sorted Pinned switches to Manual", () => {
  const ctx = context({ orders: { ...context().orders, pinned: ["p1", "pg"] } });
  const plan = plannedDrop(
    planSidebarDrop(page("pg", "pinned", PINNED_ORDER_SCOPE), chatRow("pinned", PINNED_ORDER_SCOPE, "p1"), "top", ctx),
  );
  assert.deepEqual(plan.action, { kind: "reorder" });
  assert.deepEqual(plan.effects.orders, [{ scope: PINNED_ORDER_SCOPE, ids: ["pg", "p1"] }]);
  const sorted = plannedDrop(
    planSidebarDrop(page("pg", "pinned", PINNED_ORDER_SCOPE), chatRow("pinned", PINNED_ORDER_SCOPE, "p1"), "top", {
      ...ctx,
      pinnedSort: "updated",
    }),
  );
  assert.equal(sorted.effects.switchSort, "pinned");
});

test("a pinned page files into a custom section and comes back to Pinned", () => {
  const into = plannedDrop(
    planSidebarDrop(page("pg", "pinned", PINNED_ORDER_SCOPE), chatRow(SCOPE, SCOPE, "s1"), "bottom", context()),
  );
  assert.deepEqual(into.action, { kind: "section", sectionId: S });
  assert.deepEqual(into.effects.fileInSection, { kind: "page", id: "pg", sectionId: S });
  assert.deepEqual(into.effects.orders, [{ scope: SCOPE, ids: ["lab", "s1", "pg"] }]);
  assert.equal(into.effects.unpinChat, undefined);

  const filed = context({
    sectionByPageId: { pg: S },
    orders: { ...context().orders, sections: (sectionId) => (sectionId === S ? ["lab", "s1", "pg"] : []) },
  });
  const back = plannedDrop(
    planSidebarDrop(page("pg", SCOPE, SCOPE), chatRow("pinned", PINNED_ORDER_SCOPE, "p1"), "top", filed),
  );
  assert.deepEqual(back.action, { kind: "pin" });
  assert.deepEqual(back.effects.fileInSection, { kind: "page", id: "pg", sectionId: null });
  assert.deepEqual(back.effects.orders, [{ scope: PINNED_ORDER_SCOPE, ids: ["pg", "p1"] }]);
  const reorder = plannedDrop(planSidebarDrop(page("pg", SCOPE, SCOPE), chatRow(SCOPE, SCOPE, "s1"), "top", filed));
  assert.deepEqual(reorder.action, { kind: "reorder" });
  assert.deepEqual(reorder.effects.orders, [{ scope: SCOPE, ids: ["lab", "pg", "s1"] }]);
});

test("a pinned page has no place in Recents, Projects or a folder", () => {
  const drag = page("pg", "pinned", PINNED_ORDER_SCOPE);
  assert.equal(planSidebarDrop(drag, chatRow("recents", RECENTS_ORDER_SCOPE, "r1"), "top", context()), null);
  assert.equal(planSidebarDrop(drag, { section: "projects" }, "top", context()), null);
  assert.equal(
    planSidebarDrop(drag, chatRow("projects", projectOrderScope("home"), "c3", "home"), "top", context()),
    null,
  );
});

test("pages file into sections, and a deleted section gives them back to Pinned", () => {
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const gone = store.createCustomSection("Gone")!;
  const kept = store.createCustomSection("Kept")!;
  store.setPagesSection(["a", "b"], gone);
  store.setPagesSection(["b"], kept);
  assert.deepEqual({ ...useSidebarOrganizationStore.getState().sectionByPageId }, { a: gone, b: kept });
  store.deleteCustomSection(gone);
  assert.deepEqual({ ...useSidebarOrganizationStore.getState().sectionByPageId }, { b: kept });
  store.setPagesSection(["b"], null);
  assert.deepEqual({ ...useSidebarOrganizationStore.getState().sectionByPageId }, {});
});

test("an empty Pinned takes a dragged page as its first row", () => {
  const empty = context({
    sectionByPageId: { pg: S },
    orders: { ...context().orders, pinned: [], sections: (sectionId) => (sectionId === S ? ["pg"] : []) },
  });
  for (const zone of [{ section: "pinned" as const }, { section: "pinned" as const, header: true }]) {
    const plan = plannedDrop(planSidebarDrop(page("pg", SCOPE, SCOPE), zone, "bottom", empty));
    assert.deepEqual(plan.cue, { ring: sectionRingKey("pinned") });
    assert.deepEqual(plan.effects.orders, [{ scope: PINNED_ORDER_SCOPE, ids: ["pg"] }]);
    assert.deepEqual(plan.effects.fileInSection, { kind: "page", id: "pg", sectionId: null });
  }
});

test("undoing a removed section files its pages back into it", async () => {
  // remove-custom-section.ts imports without an extension.
  const resolver = `export function resolve(specifier, context, next) {
    if (specifier === "./sidebar-organization-store") return next(specifier + ".ts", context);
    return next(specifier, context);
  }`;
  register(`data:text/javascript,${encodeURIComponent(resolver)}`);
  const { removeCustomSectionWithUndo } = await import("../src/features/chat/stores/remove-custom-section.ts");
  resetStore();
  const store = useSidebarOrganizationStore.getState();
  const id = store.createCustomSection("Reading")!;
  store.setPagesSection(["pg"], id);
  const section = useSidebarOrganizationStore.getState().customSections.find((s) => s.id === id)!;
  const undo = removeCustomSectionWithUndo(section);
  assert.deepEqual({ ...useSidebarOrganizationStore.getState().sectionByPageId }, {});
  undo();
  assert.deepEqual({ ...useSidebarOrganizationStore.getState().sectionByPageId }, { pg: id });
});