Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Drag the models page's provider groups into your own order (#467)

Yaowei Zheng9c2eafff2a0c
diff --git a/changelog/unreleased/2026-08-25-model-group-order.md b/changelog/unreleased/2026-08-25-model-group-order.md
new file mode 100644
index 00000000..1c560088
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-model-group-order.md
@@ -0,0 +1,46 @@
+# Drag the models page's provider groups into your own order
+
+- **Date:** 2026-08-25
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#467](https://github.com/Prism-Shadow/penguin-harness/pull/467)
+
+[中文版](2026-08-25-model-group-order.zh.md)
+
+The model library's provider groups can be dragged into a manual order, the way the chat
+sidebar's groups already could. The order is kept per Project, survives a reload, and the chat
+page's model picker follows it.
+
+## Details
+
+- Dragging a group is itself the intent: there is no sort toggle and no pinning. A Project with
+ nothing stored renders exactly the built-in catalog order it did before.
+- A group with no stored position TRAILS, keeping its automatic order among the other unplaced
+ groups. The control that creates a user-defined group sits below every group on the page, so a
+ new group appears where it was made rather than leaping over the whole arrangement — and it
+ matches the automatic order, which already puts user-defined groups after the built-in ones.
+ (This is the opposite of the sidebar's rule, where an unplaced group is a Workspace or Agent
+ that would otherwise be lost at the bottom of a long list.)
+- A drop is committed against **every group the library could show**, including the built-in
+ groups that hold no models and are therefore not rendered. A provider that gains its first
+ model appears at its catalog place instead of arriving at the top as a newcomer.
+- The custom group keeps its own rules — always shown when there is no search query, so it can
+ host the "add model" entry point — at whatever position the order gives it.
+- The group order and the group expansion set are separate arrays under separate storage keys
+ (`penguin.modelsGroupOrder.<projectId>` beside `penguin.modelsExpandedGroups.<projectId>`), so
+ dragging a group never folds or unfolds one.
+- The group header is the drag handle and the drop indicator is drawn against the whole group, so
+ "below" means after that group and its model cards. It costs no layout width, and the header
+ keeps its up-to-five actions at every width.
+- Dragging is refused while a search query is active: the query filters the page to matches, and
+ an arrangement made against that subset is not the arrangement of the library.
+- The gesture needs a pointer that can drag, so it is offered only where one exists — HTML5
+ drag-and-drop never fires from touch. A stored order still applies on a touch device: there is
+ no mode to degrade, so a phone renders the arrangement its owner made at a desk.
+- The chat page's model picker already mirrored the library page's order; it now reads the same
+ stored array, so the two stay in agreement.
+- The drag payload carries its own private MIME type, distinct from the sidebar's group drag: the
+ sidebar renders alongside the models page, and one shared type would let a group dragged out of
+ the conversation list paint a drop line here.
+- Stored keys that match no group are ignored and are never pruned; a group that returns under the
+ same key resumes its place. A malformed stored value degrades to the catalog order.
diff --git a/changelog/unreleased/2026-08-25-model-group-order.zh.md b/changelog/unreleased/2026-08-25-model-group-order.zh.md
new file mode 100644
index 00000000..d180a1f3
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-model-group-order.zh.md
@@ -0,0 +1,32 @@
+# 模型库的 Provider 分组可以拖动排序
+
+- **Date:** 2026-08-25
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#467](https://github.com/Prism-Shadow/penguin-harness/pull/467)
+
+[English](2026-08-25-model-group-order.md)
+
+模型库的 Provider 分组可以拖动成自定义顺序,与对话侧边栏的分组一致。顺序按 Project 保存、刷新后仍在,
+对话页的模型拾取器也会跟随。
+
+## 细节
+
+- 拖动本身就是意图:没有排序开关,也没有置顶。未存过顺序的 Project 渲染的仍是内置目录原本的顺序。
+- 没有存过位置的分组排在**末尾**,彼此之间保持自动顺序。创建自定义分组的入口位于所有分组的下方,因此新建
+ 的分组出现在创建它的位置,而不会越过整个排列跳到顶部;这也与自动顺序一致——用户自定义分组本就排在内置
+ 分组之后。(这与侧边栏的规则相反:在那里,未定位的分组是 Workspace 或智能体,沉到长列表底部会被埋没。)
+- 一次拖放提交的是**模型库可能展示的全部分组**,包括当前没有模型、因而未渲染的内置分组。某个 Provider
+ 新增第一个模型时会出现在它的目录位置,而不是作为新成员出现在顶部。
+- custom 分组保留自己的规则——没有搜索词时始终显示,以承载「新增模型」入口——位置由顺序决定。
+- 分组顺序与分组展开状态是两个独立数组、两个独立存储键(`penguin.modelsGroupOrder.<projectId>` 与
+ `penguin.modelsExpandedGroups.<projectId>` 并列),因此拖动分组不会顺带展开或折叠它。
+- 分组头即拖动手柄,落点指示线画在整个分组上,因此「下方」表示排在该分组及其模型卡片之后。指示线不占布局
+ 宽度,分组头在各种宽度下仍保留最多五个动作。
+- 搜索期间不允许拖动:搜索把页面过滤成匹配项,对该子集做出的排列并不是模型库的排列。
+- 该手势需要能拖动的指针,因此只在存在这种指针的设备上提供——HTML5 拖放在触屏上不触发。已存的顺序在触屏
+ 设备上照常生效:没有需要降级的模式,手机渲染的就是其主人在桌面端排好的顺序。
+- 对话页的模型拾取器本就沿用模型库页的顺序,现在读取同一个存储数组,两者保持一致。
+- 拖动载荷使用自己的私有 MIME 类型,与侧边栏的分组拖动区分开:侧边栏与模型库页同屏渲染,共用一个类型会让
+ 从对话列表拖出的分组在这里画出落点指示线。
+- 匹配不到分组的存量键会被忽略,且不做清理;分组以相同的键回来时会回到原位。存储值损坏时降级为目录顺序。
diff --git a/packages/web/src/features/chat/model-select.tsx b/packages/web/src/features/chat/model-select.tsx
index 259ba509..00a86525 100644
--- a/packages/web/src/features/chat/model-select.tsx
+++ b/packages/web/src/features/chat/model-select.tsx
@@ -9,7 +9,7 @@
* expander) shared by the draft dropdown and the in-session `/model` switch picker;
* - ModelSelect: the dropdown trigger (provider logo + name + chevron), pill or form style.
*/
-import { useState } from "react";
+import { useMemo, useState } from "react";
import type { KeyboardEvent, ReactNode } from "react";
import type { ModelInfo, ModelRefDto } from "@prismshadow/penguin-server/api";
import { S } from "../../lib/strings";
@@ -27,6 +27,8 @@ import {
sameModelRef,
visibleChatModels,
} from "../models/model-grouping";
+import { loadModelGroupOrder } from "../models/model-group-order";
+import { useProject } from "../../state/project";
/** Display label for a model: the display name, or falls back to the upstream id (model_id is the raw field, no prefix parsing). */
export function modelLabel(m: ModelInfo): string {
@@ -180,12 +182,32 @@ export function ModelMenuList({
const [query, setQuery] = useState("");
// Expanded "show all" state: collapses back to key-configured models on each open (remount).
const [showAll, setShowAll] = useState(false);
- const visible = visibleChatModels(models, { showAll, query, selected: value, defaultModel });
+ // The model page's dragged group order, so "mirrors the model library page" keeps holding
+ // once a user has arranged their groups. Read here rather than threaded through every call
+ // site, once per open (both hosts render the panel only while open, so opening it remounts
+ // this) — an order changed on that page, in this tab or another, is picked up on the next
+ // open without a reload. Not on every render: the search box below re-renders this panel
+ // on each keystroke, and the Project context does so for reasons of its own.
+ const { currentProject } = useProject();
+ const projectId = currentProject?.projectId ?? null;
+ const groupOrder = useMemo(() => loadModelGroupOrder(projectId), [projectId]);
+ const visible = visibleChatModels(models, {
+ showAll,
+ query,
+ selected: value,
+ defaultModel,
+ groupOrder,
+ });
// How many models the key filter hides under the current query (0 when expanded): drives the bottom "show all" row.
const hiddenCount = showAll
? 0
- : visibleChatModels(models, { showAll: true, query, selected: value, defaultModel }).length -
- visible.length;
+ : visibleChatModels(models, {
+ showAll: true,
+ query,
+ selected: value,
+ defaultModel,
+ groupOrder,
+ }).length - visible.length;
return (
<PickerList
items={visible}
diff --git a/packages/web/src/features/models/model-group-order.ts b/packages/web/src/features/models/model-group-order.ts
new file mode 100644
index 00000000..ab55b06f
--- /dev/null
+++ b/packages/web/src/features/models/model-group-order.ts
@@ -0,0 +1,118 @@
+/**
+ * Manual order of the models page's provider GROUPS: where the arrangement is stored, and
+ * the two halves of the rule that reads and writes it.
+ *
+ * The page renders provider groups in the built-in catalog's order (model-grouping.ts).
+ * That order is a curated default, not everyone's: a user who only ever reaches for two
+ * providers can drag those groups to the top and leave the rest below. Dragging IS the
+ * intent — there is no sort toggle and no pinning, so a Project with nothing stored
+ * renders exactly the catalog order it always did (an empty order is the identity).
+ *
+ * - **One array per Project**, keyed like its neighbour `penguin.modelsExpandedGroups`
+ * — the model table is per Project, so the arrangement of its groups is too.
+ * - **Unplaced groups TRAIL**, keeping their automatic order among themselves. This is
+ * the opposite of the sidebar's rule (session-order.ts's applyManualOrder surfaces an
+ * unplaced group so a Workspace used for the first time is not lost at the bottom of a
+ * long list), and the difference is what an unplaced group MEANS on each side. Here it
+ * is almost always one the user just created, through a control that sits below every
+ * group: a new group that jumps to the top leaves the part of the page being looked at.
+ * Trailing is also what the automatic order already does — user-defined groups follow
+ * the built-in ones.
+ * - **A drop commits against every group the library could show**, empty built-ins
+ * included (`allGroupKeys`), not the groups currently on screen. groupModelRows drops
+ * a built-in group holding no models, so committing only what renders would leave the
+ * empty ones unplaced and make each one a newcomer the day a model is added to it.
+ * - **Stale keys are inert, and nothing prunes them.** A key matching no group is only
+ * a failed membership lookup. A provider that leaves the catalog and returns resumes
+ * its place, which is the honest reading of "same key, same group"; the cost of
+ * keeping it is one map entry.
+ *
+ * orderModelGroups and commitModelGroupOrder are one rule stated twice — where an
+ * unplaced group renders, and where a drop writes it — so they live side by side: a drop
+ * that materialised unplaced groups at the other end would shove groups the user never
+ * touched. The splice itself is session-order.ts's `moveInSequence`, including its
+ * identity return for a drop that moves nothing.
+ *
+ * Storage is injectable (model-group-expansion.ts convention: vitest runs in Node, no
+ * localStorage); malformed values degrade to an empty order, i.e. the catalog sequence.
+ */
+import { moveInSequence, readStringArray, writeStringArray } from "../../lib/session-order";
+import type { SessionOrderStorage } from "../../lib/session-order";
+
+/** Minimal storage interface, shared with session-order.ts; tests inject an in-memory implementation. */
+export type ModelGroupOrderStorage = SessionOrderStorage;
+
+/** Storage key of one Project's manual group order (`penguin.modelsExpandedGroups.<projectId>` naming convention). */
+export const modelGroupOrderKey = (projectId: string): string =>
+ `penguin.modelsGroupOrder.${projectId}`;
+
+/**
+ * Reads a Project's manual group order. No Project, nothing stored, or corrupted storage
+ * all degrade to empty — the identity for groupModelRows, i.e. the catalog order. Junk
+ * array elements are dropped.
+ */
+export function loadModelGroupOrder(
+ projectId: string | null,
+ storage?: ModelGroupOrderStorage,
+): string[] {
+ if (projectId === null) return [];
+ return readStringArray(modelGroupOrderKey(projectId), storage);
+}
+
+/** Writes a Project's manual group order on every drop; no Project writes nothing. */
+export function saveModelGroupOrder(
+ projectId: string | null,
+ order: readonly string[],
+ storage?: ModelGroupOrderStorage,
+): void {
+ if (projectId === null) return;
+ writeStringArray(modelGroupOrderKey(projectId), order, storage);
+}
+
+/**
+ * Applies a stored order to the library's groups: the groups it names take its sequence,
+ * the groups it does not keep their automatic (catalog) order and follow at the END. An
+ * empty order is the identity — the automatic order, untouched.
+ */
+export function orderModelGroups<T>(
+ groups: readonly T[],
+ keyOf: (group: T) => string,
+ order: readonly string[],
+): T[] {
+ if (order.length === 0) return [...groups];
+ const pos = new Map(order.map((key, i) => [key, i]));
+ const placed: T[] = [];
+ const unplaced: T[] = [];
+ for (const group of groups) (pos.has(keyOf(group)) ? placed : unplaced).push(group);
+ placed.sort((a, b) => (pos.get(keyOf(a)) ?? 0) - (pos.get(keyOf(b)) ?? 0));
+ return [...placed, ...unplaced];
+}
+
+/**
+ * Commits one drop into the stored order, as a SPLICE rather than a rewrite: materialise
+ * every group key into the stored array where it already RENDERS — placed ones from the
+ * order, the rest trailing, matching orderModelGroups — then move the dragged key beside
+ * its target. Keys that are stored but no longer name a group keep their positions
+ * relative to everything else.
+ *
+ * `all` is every group the library could show (allGroupKeys), not the groups on screen:
+ * a built-in provider holding no models is not rendered, and leaving it out would make it
+ * a newcomer the day a model is added to it.
+ *
+ * Returns the INPUT array unchanged (same reference) when the drop moves nothing, so the
+ * caller can skip the state update and the storage write.
+ */
+export function commitModelGroupOrder(
+ order: readonly string[],
+ all: readonly string[],
+ dragKey: string,
+ targetKey: string,
+ after: boolean,
+): readonly string[] {
+ const stored = new Set(order);
+ const materialised = [...order, ...all.filter((key) => !stored.has(key))];
+ const next = moveInSequence(materialised, dragKey, targetKey, after);
+ // moveInSequence hands back its input for every no-op (self-drop, missing key, or a
+ // landing that changes nothing): nothing moved, so nothing is worth persisting.
+ return next === materialised ? order : next;
+}
diff --git a/packages/web/src/features/models/model-grouping.ts b/packages/web/src/features/models/model-grouping.ts
index e391d1c7..04587d0d 100644
--- a/packages/web/src/features/models/model-grouping.ts
+++ b/packages/web/src/features/models/model-grouping.ts
@@ -9,10 +9,18 @@
* the MODEL_PROVIDERS definition. Empty groups aren't returned, except the custom group,
* which is always shown when there's no search query (rendered even when empty, to host
* the generic "add model" entry point).
+ *
+ * That automatic sequence is the DEFAULT, not the last word: every entry point takes an
+ * optional `groupOrder` — the user's dragged arrangement, stored per Project by
+ * model-group-order.ts — and applies it to the assembled group list. An empty order is
+ * the identity, so a profile that has never dragged a group sees exactly the catalog
+ * order. Storage stays out of this module: the caller loads the array and passes it in.
*/
import { MODEL_PROVIDERS } from "@prismshadow/penguin-core/model-catalog";
import type { ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";
+import { orderModelGroups } from "./model-group-order";
+
/** Paired model reference (same shape as the server DTO's ModelRefDto; a model is always referenced as (provider, modelId)). */
export interface ModelRefValue {
provider: string;
@@ -54,6 +62,24 @@ export function matchesQuery(row: ModelRowLike, query: string): boolean {
);
}
+/** The user-defined group ids present in `rows` (anything not in the catalog list), sorted by name. */
+function userGroupIds(rows: readonly ModelRowLike[]): string[] {
+ return [
+ ...new Set(rows.map((r) => r.provider).filter((p) => !MODEL_PROVIDERS.some((k) => k.id === p))),
+ ].sort();
+}
+
+/**
+ * Every group key the library can show, in its automatic order: the built-in providers in
+ * MODEL_PROVIDERS order — **including the ones holding no models**, which groupModelRows
+ * drops from the render — then the user-defined groups. This is the sequence a group drop
+ * is committed against, so a group that happens to be empty today keeps its catalog place
+ * instead of arriving as a newcomer the first time a model is added to it.
+ */
+export function allGroupKeys(rows: readonly ModelRowLike[]): string[] {
+ return [...MODEL_PROVIDERS.map((p) => p.id), ...userGroupIds(rows)];
+}
+
export interface ProviderGroup<T extends ModelRowLike> {
provider: ModelProviderInfo;
rows: T[];
@@ -64,10 +90,17 @@ export interface ProviderGroup<T extends ModelRowLike> {
* follow MODEL_PROVIDERS order (the custom group is returned even when empty, when there's
* no search query); user-defined groups each form their own group, sorted by name and
* appended after custom.
+ *
+ * `groupOrder` then rearranges that list: groups it names take its order, groups it does
+ * not keep their automatic order and TRAIL (orderModelGroups — a group the user just
+ * created appears where the control that created it sits, at the bottom of the page).
+ * Reordering happens before empty groups are dropped, so a stored key for a group holding
+ * no models costs nothing and is not visible.
*/
export function groupModelRows<T extends ModelRowLike>(
rows: T[],
query: string,
+ groupOrder: readonly string[] = [],
): ProviderGroup<T>[] {
const searching = query.trim() !== "";
const filtered = rows.filter((r) => matchesQuery(r, query));
@@ -75,28 +108,26 @@ export function groupModelRows<T extends ModelRowLike>(
provider,
rows: filtered.filter((r) => r.provider === provider.id),
}));
- const extraIds = [
- ...new Set(
- filtered.map((r) => r.provider).filter((p) => !MODEL_PROVIDERS.some((k) => k.id === p)),
- ),
- ].sort();
- const extras = extraIds.map((id) => ({
+ const extras = userGroupIds(filtered).map((id) => ({
provider: userProviderInfo(id),
rows: filtered.filter((r) => r.provider === id),
}));
- return [...builtin, ...extras].filter(
- (g) => g.rows.length > 0 || (!searching && g.provider.id === "custom"),
- );
+ const ordered = orderModelGroups([...builtin, ...extras], (g) => g.provider.id, groupOrder);
+ return ordered.filter((g) => g.rows.length > 0 || (!searching && g.provider.id === "custom"));
}
/**
* Flattens the library grouping into one ordered list (the chat model dropdown uses this):
* rows ordered exactly as the model page shows them — built-in provider groups in
- * MODEL_PROVIDERS order, then user-defined groups, custom last; in-group row order
- * preserved.
+ * MODEL_PROVIDERS order (custom last), then user-defined groups, with `groupOrder` applied
+ * on top; in-group row order preserved. Passing the page's stored order here is what keeps
+ * "exactly as the model page shows them" true once a user has dragged their groups.
*/
-export function orderModelsLikeLibrary<T extends ModelRowLike>(rows: T[]): T[] {
- return groupModelRows(rows, "").flatMap((g) => g.rows);
+export function orderModelsLikeLibrary<T extends ModelRowLike>(
+ rows: T[],
+ groupOrder: readonly string[] = [],
+): T[] {
+ return groupModelRows(rows, "", groupOrder).flatMap((g) => g.rows);
}
/**
@@ -150,6 +181,8 @@ export interface VisibleChatModelsOptions {
selected?: ModelRefValue | null;
/** Project default model: always visible even without a configured key. */
defaultModel?: ModelRefValue | null;
+ /** The models page's stored group order; omitted = the catalog's automatic order. */
+ groupOrder?: readonly string[];
}
/**
@@ -160,9 +193,9 @@ export interface VisibleChatModelsOptions {
*/
export function visibleChatModels<T extends ModelCredentialRowLike>(
models: T[],
- { showAll, query, selected, defaultModel }: VisibleChatModelsOptions,
+ { showAll, query, selected, defaultModel, groupOrder }: VisibleChatModelsOptions,
): T[] {
- const ordered = orderModelsLikeLibrary(models);
+ const ordered = orderModelsLikeLibrary(models, groupOrder);
const keep =
showAll || !ordered.some(hasConfiguredKey)
? ordered
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index d67a9850..4cd11f21 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -30,6 +30,7 @@
* means keep the existing value); only the owner can edit.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { DragEvent as ReactDragEvent } from "react";
import type {
CredentialInfo,
ModelProtocolDetectRequest,
@@ -76,12 +77,18 @@ import {
} from "@prismshadow/penguin-core/model-catalog";
import type { FastModeProtocol, ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";
import {
+ allGroupKeys,
groupModelRows,
hasConfiguredKey,
isFreeModel,
sameModelRef,
userProviderInfo,
} from "./model-grouping";
+import {
+ commitModelGroupOrder,
+ loadModelGroupOrder,
+ saveModelGroupOrder,
+} from "./model-group-order";
import { protocolPathForModel } from "./protocol-path";
import { ProtocolSuffixMenu } from "./protocol-suffix";
import {
@@ -495,6 +502,26 @@ export function rowToEntry(row: RowState): ModelUpdateEntry {
return entry;
}
+/**
+ * Private drag payload type of a provider-group reorder. Deliberately NOT the sidebar's
+ * group MIME: the sidebar renders alongside this page, so one shared type would let a
+ * group dragged out of the conversation list paint a drop line here (and vice versa) —
+ * two unrelated orders that happen to be dragged the same way.
+ */
+const MODEL_GROUP_DRAG_MIME = "application/x-penguin-model-group";
+
+/**
+ * Is the drag in flight one of our group reorders? `types` is readable during dragover
+ * (unlike getData), so the payload authorizes the drop rather than React state alone:
+ * without it, a `dragGroup` left behind by a header that unmounted mid-drag would make the
+ * page swallow an unrelated drag, paint a phantom line, and commit on release.
+ */
+const isModelGroupDrag = (e: ReactDragEvent): boolean =>
+ e.dataTransfer.types.includes(MODEL_GROUP_DRAG_MIME);
+
+/** Dragging a group needs a pointer that can drag — HTML5 drag-and-drop never fires from touch (the sidebar's query). */
+const DRAG_POINTER_QUERY = "(hover: hover) and (pointer: fine)";
+
export function ModelsPage() {
useDocumentTitle(S.models.title);
const { currentProject } = useProject();
@@ -529,6 +556,31 @@ export function ModelsPage() {
useEffect(() => {
setExpanded(loadExpandedProviders(projectId));
}, [projectId]);
+ /**
+ * This Project's manual group order (empty = the catalog's own sequence). Hydrated and
+ * re-hydrated exactly like the expansion set above, and written back on every drop.
+ */
+ const [groupOrder, setGroupOrder] = useState<readonly string[]>(() =>
+ loadModelGroupOrder(projectId),
+ );
+ useEffect(() => {
+ setGroupOrder(loadModelGroupOrder(projectId));
+ }, [projectId]);
+ /**
+ * Whether the reorder gesture is offered at all. A stored order still APPLIES without
+ * it: the arrangement is per Project and implicit, so there is nothing to degrade —
+ * a phone renders what its owner arranged at a desk.
+ */
+ const [canDrag, setCanDrag] = useState(() => window.matchMedia(DRAG_POINTER_QUERY).matches);
+ useEffect(() => {
+ const mq = window.matchMedia(DRAG_POINTER_QUERY);
+ const onChange = (e: MediaQueryListEvent) => setCanDrag(e.matches);
+ mq.addEventListener("change", onChange);
+ return () => mq.removeEventListener("change", onChange);
+ }, []);
+ /** Group header being dragged (its provider id) and the live drop hint (target group + which edge). */
+ const [dragGroup, setDragGroup] = useState<string | null>(null);
+ const [groupDropHint, setGroupDropHint] = useState<{ key: string; after: boolean } | null>(null);
/** Vendor group (provider id) currently having its API key configured in bulk. */
const [groupKeyFor, setGroupKeyFor] = useState<string | null>(null);
/** User-defined group (provider id) whose delete confirmation is open (built-in groups never offer this). */
@@ -608,7 +660,16 @@ export function ModelsPage() {
}
};
- const groups = useMemo(() => (rows ? groupModelRows(rows, query) : []), [rows, query]);
+ const groups = useMemo(
+ () => (rows ? groupModelRows(rows, query, groupOrder) : []),
+ [rows, query, groupOrder],
+ );
+ /**
+ * Every group the library could show, empty built-ins included — the sequence a drop is
+ * committed against, so a provider currently holding no models keeps its catalog place
+ * rather than arriving as a newcomer the day one is added to it.
+ */
+ const allKeys = useMemo(() => allGroupKeys(rows ?? []), [rows]);
/** Env-fallback variables the server reported a value for: the only ones a key hint may promise. */
const envKeysDetected = useMemo(() => detectedEnvKeys(rows ?? []), [rows]);
/** Non-empty search query: groups are filtered to matches and force-opened while it lasts. */
@@ -724,6 +785,86 @@ export function ModelsPage() {
saveExpandedProviders(projectId, next);
};
+ /**
+ * Drag-reorder wiring of one group header. Returns the props the header row spreads and
+ * the edge a drop would land on, or nothing at all when the gesture is not offered:
+ * without a drag-capable pointer, and while a search query is active — the query filters
+ * the list to matches, so a drop there would commit an arrangement made against a subset
+ * the user is about to dismiss.
+ */
+ const groupDragProps = (key: string) => {
+ if (!canDrag || searching) {
+ return { header: {}, dropEdge: null as "above" | "below" | null };
+ }
+ const dragging = dragGroup;
+ /** Which half of the header the pointer is in — the edge the drop would land on. */
+ const edgeOf = (e: ReactDragEvent) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ return e.clientY - rect.top > rect.height / 2;
+ };
+ const acceptsDrop = dragging !== null && dragging !== key;
+ return {
+ header: {
+ draggable: true,
+ onDragStart: (e: ReactDragEvent) => {
+ // dragstart fires AT the source node, so target === currentTarget exactly when
+ // the header row itself is what the browser picked up. The row also carries the
+ // provider's external key link, which is natively draggable: a drag begun there
+ // is a link drag, and claiming it would overwrite the link's payload and effect
+ // and turn a release over any other header into a silent reorder.
+ if (e.target !== e.currentTarget) return;
+ e.dataTransfer.setData(MODEL_GROUP_DRAG_MIME, key);
+ e.dataTransfer.effectAllowed = "move" as const;
+ setDragGroup(key);
+ },
+ onDragEnd: () => {
+ setDragGroup(null);
+ setGroupDropHint(null);
+ },
+ onDragOver: (e: ReactDragEvent) => {
+ if (!acceptsDrop || !isModelGroupDrag(e)) return;
+ e.preventDefault();
+ // preventDefault alone only says "a drop may land here"; the effect still has to
+ // be one effectAllowed permits, or a modifier held during the drag resolves it to
+ // "none" and the drop event never fires.
+ e.dataTransfer.dropEffect = "move";
+ const after = edgeOf(e);
+ setGroupDropHint((prev) =>
+ prev?.key === key && prev.after === after ? prev : { key, after },
+ );
+ },
+ // dragleave also fires when the pointer merely crosses onto one of the header's OWN
+ // children — the collapse button spans most of the row, and up to five actions
+ // follow it — so clearing unconditionally strobes the indicator. relatedTarget is
+ // where the drag is going: still inside means nothing changed.
+ onDragLeave: (e: ReactDragEvent) => {
+ const to = e.relatedTarget;
+ if (to instanceof Node && e.currentTarget.contains(to)) return;
+ setGroupDropHint((prev) => (prev?.key === key ? null : prev));
+ },
+ onDrop: (e: ReactDragEvent) => {
+ if (!acceptsDrop || dragging === null || !isModelGroupDrag(e)) return;
+ e.preventDefault();
+ const next = commitModelGroupOrder(groupOrder, allKeys, dragging, key, edgeOf(e));
+ // commitModelGroupOrder hands back its input for a drop that moves nothing: no state
+ // update, and no freshly allocated identical array written to storage.
+ if (next !== groupOrder) {
+ setGroupOrder(next);
+ saveModelGroupOrder(projectId, next);
+ }
+ setDragGroup(null);
+ setGroupDropHint(null);
+ },
+ },
+ dropEdge:
+ acceptsDrop && groupDropHint?.key === key
+ ? groupDropHint.after
+ ? ("below" as const)
+ : ("above" as const)
+ : null,
+ };
+ };
+
return (
<div className="h-full overflow-y-auto p-4 md:p-6">
<div className="mx-auto max-w-5xl">
@@ -772,176 +913,194 @@ export function ModelsPage() {
<div className="space-y-3">
{groups.map((group) => {
const open = isGroupExpanded(expanded, group.provider.id, searching);
+ const drag = groupDragProps(group.provider.id);
return (
- <section
- key={group.provider.id}
- className="overflow-hidden rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900"
- >
- {/* Group header: collapse button (logo + vendor name + count) + group-level
+ // The drop indicator is drawn against the WHOLE group, so "below" reads as
+ // after this group and its model cards rather than between the header and
+ // its own first card. It needs this wrapper to live in: the section clips
+ // its children (overflow-hidden carries the expand/collapse transition).
+ // Absolutely positioned, so it costs no layout width and cannot push the
+ // header's up-to-five actions out of a narrow page.
+ <div key={group.provider.id} className="relative">
+ {drag.dropEdge !== null && (
+ <div
+ aria-hidden
+ className={`pointer-events-none absolute inset-x-0 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${
+ drag.dropEdge === "above" ? "-top-1.5" : "-bottom-1.5"
+ }`}
+ />
+ )}
+ <section className="overflow-hidden rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
+ {/* Group header: collapse button (logo + vendor name + count) + group-level
actions on the right. Actions are separate elements because buttons can't
nest. The row is a size container: the sidebar can narrow it while the
viewport remains desktop-sized, so action labels must respond to this
row's actual width rather than viewport breakpoints. Narrow rows never
hide an action — each one keeps its icon (with aria-label + title) and
- only sheds its text label. */}
- <div className="@container flex items-center gap-2 bg-gray-50 pr-2 transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60">
- <button
- type="button"
- aria-expanded={open}
- onClick={() => toggleGroup(group.provider.id)}
- className="flex min-w-0 flex-1 items-center gap-2.5 px-3 py-2.5 text-left"
+ only sheds its text label. The row is also the drag handle for
+ reordering the group (groupDragProps). */}
+ <div
+ {...drag.header}
+ className={`@container flex items-center gap-2 bg-gray-50 pr-2 transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60${canDrag && !searching ? " cursor-grab" : ""}`}
>
- <ProviderLogo
- provider={group.provider.id}
- className="h-5 w-5 shrink-0 text-gray-700 dark:text-gray-300"
- />
- {/* Vendor name can truncate (min-w-0): the actions on the right must not
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => toggleGroup(group.provider.id)}
+ className="flex min-w-0 flex-1 items-center gap-2.5 px-3 py-2.5 text-left"
+ >
+ <ProviderLogo
+ provider={group.provider.id}
+ className="h-5 w-5 shrink-0 text-gray-700 dark:text-gray-300"
+ />
+ {/* Vendor name can truncate (min-w-0): the actions on the right must not
shrink, otherwise on narrow screens it would get pushed out of the
button box and overlap the action text. */}
- <span className="min-w-0 truncate text-sm font-semibold">
- {group.provider.label}
- </span>
- <span className="shrink-0 whitespace-nowrap font-mono text-xs text-gray-400">
- {S.models.modelCount(group.rows.length)}
- </span>
- </button>
- {isOwner && (
- // Add-model entry point: present on every group header (including
- // custom), new models belong to that group. Narrow rows never hide a
- // group action — they drop its label and keep the icon (same pattern
- // for every action in this row), so the button stays reachable.
- <Button
- size="sm"
- variant="ghost"
- className="shrink-0"
- disabled={busy}
- aria-label={`${S.models.addToGroup} ${group.provider.label}`}
- title={S.models.addToGroup}
- onClick={() => setAddingTo(group.provider.id)}
- >
- <GlyphIcon d={PLUS_ICON} size={13} />
- <span className="hidden @3xl:inline">{S.models.addToGroup}</span>
- </Button>
- )}
- {isOwner && group.provider.id !== "custom" && (
- // Bulk key action: icon-only while this row is narrow, labeled from
- // @3xl up. The button itself never disappears — aria-label + title
- // carry the name while the visible label is dropped.
- <Button
- size="sm"
- variant="ghost"
- className="shrink-0"
- disabled={busy}
- aria-label={`${S.models.groupApiKey} ${group.provider.label}`}
- title={S.models.groupApiKey}
- onClick={() => setGroupKeyFor(group.provider.id)}
- >
- <GlyphIcon d={KEY_ICON} size={13} />
- <span className="hidden @3xl:inline">{S.models.groupApiKey}</span>
- </Button>
- )}
- {isOwner && (
- <Button
- size="sm"
- variant="ghost"
- className="shrink-0"
- disabled={busy || speedRunning !== null}
- aria-label={`${S.models.speedTest} ${group.provider.label}`}
- title={
- speedRunning === group.provider.id
- ? S.models.speedPending
- : S.models.speedTest
- }
- onClick={() => setSpeedFor(group.provider.id)}
- >
- <GlyphIcon d={GAUGE_ICON} size={13} />
- {/* Compact rows keep this accessible action icon-only. */}
- <span className="hidden @3xl:inline">
- {speedRunning === group.provider.id
- ? S.models.speedPending
- : S.models.speedTest}
+ <span className="min-w-0 truncate text-sm font-semibold">
+ {group.provider.label}
</span>
- </Button>
- )}
- {isOwner && !MODEL_PROVIDERS.some((p) => p.id === group.provider.id) && (
- // Whole-group delete, user-defined groups only: a built-in group is
- // catalog identity (its rows delete one by one), a user-defined group
- // exists solely through its rows and can go as a unit.
- <Button
- size="sm"
- variant="ghost"
- className="shrink-0"
- disabled={busy}
- aria-label={`${S.models.deleteGroup} ${group.provider.label}`}
- title={S.models.deleteGroup}
- onClick={() => setDeleteGroupFor(group.provider.id)}
- >
- <GlyphIcon d={TRASH_ICON} size={13} />
- <span className="hidden @3xl:inline">{S.models.deleteGroup}</span>
- </Button>
- )}
- {group.provider.apiKeyUrl && (
- // External link: its label is the last one admitted as space grows
- // (@4xl); below that it collapses to the external-link glyph with a
- // small padding bump for a usable touch target.
- <a
- href={group.provider.apiKeyUrl}
- target="_blank"
- rel="noreferrer noopener"
- aria-label={`${S.models.getApiKey} ${group.provider.label}`}
- title={S.models.getApiKey}
- className="inline-flex shrink-0 items-center whitespace-nowrap p-1 text-xs text-brand-600 underline-offset-2 hover:underline @4xl:p-0 dark:text-brand-300"
+ <span className="shrink-0 whitespace-nowrap font-mono text-xs text-gray-400">
+ {S.models.modelCount(group.rows.length)}
+ </span>
+ </button>
+ {isOwner && (
+ // Add-model entry point: present on every group header (including
+ // custom), new models belong to that group. Narrow rows never hide a
+ // group action — they drop its label and keep the icon (same pattern
+ // for every action in this row), so the button stays reachable.
+ <Button
+ size="sm"
+ variant="ghost"
+ className="shrink-0"
+ disabled={busy}
+ aria-label={`${S.models.addToGroup} ${group.provider.label}`}
+ title={S.models.addToGroup}
+ onClick={() => setAddingTo(group.provider.id)}
+ >
+ <GlyphIcon d={PLUS_ICON} size={13} />
+ <span className="hidden @3xl:inline">{S.models.addToGroup}</span>
+ </Button>
+ )}
+ {isOwner && group.provider.id !== "custom" && (
+ // Bulk key action: icon-only while this row is narrow, labeled from
+ // @3xl up. The button itself never disappears — aria-label + title
+ // carry the name while the visible label is dropped.
+ <Button
+ size="sm"
+ variant="ghost"
+ className="shrink-0"
+ disabled={busy}
+ aria-label={`${S.models.groupApiKey} ${group.provider.label}`}
+ title={S.models.groupApiKey}
+ onClick={() => setGroupKeyFor(group.provider.id)}
+ >
+ <GlyphIcon d={KEY_ICON} size={13} />
+ <span className="hidden @3xl:inline">{S.models.groupApiKey}</span>
+ </Button>
+ )}
+ {isOwner && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="shrink-0"
+ disabled={busy || speedRunning !== null}
+ aria-label={`${S.models.speedTest} ${group.provider.label}`}
+ title={
+ speedRunning === group.provider.id
+ ? S.models.speedPending
+ : S.models.speedTest
+ }
+ onClick={() => setSpeedFor(group.provider.id)}
+ >
+ <GlyphIcon d={GAUGE_ICON} size={13} />
+ {/* Compact rows keep this accessible action icon-only. */}
+ <span className="hidden @3xl:inline">
+ {speedRunning === group.provider.id
+ ? S.models.speedPending
+ : S.models.speedTest}
+ </span>
+ </Button>
+ )}
+ {isOwner && !MODEL_PROVIDERS.some((p) => p.id === group.provider.id) && (
+ // Whole-group delete, user-defined groups only: a built-in group is
+ // catalog identity (its rows delete one by one), a user-defined group
+ // exists solely through its rows and can go as a unit.
+ <Button
+ size="sm"
+ variant="ghost"
+ className="shrink-0"
+ disabled={busy}
+ aria-label={`${S.models.deleteGroup} ${group.provider.label}`}
+ title={S.models.deleteGroup}
+ onClick={() => setDeleteGroupFor(group.provider.id)}
+ >
+ <GlyphIcon d={TRASH_ICON} size={13} />
+ <span className="hidden @3xl:inline">{S.models.deleteGroup}</span>
+ </Button>
+ )}
+ {group.provider.apiKeyUrl && (
+ // External link: its label is the last one admitted as space grows
+ // (@4xl); below that it collapses to the external-link glyph with a
+ // small padding bump for a usable touch target.
+ <a
+ href={group.provider.apiKeyUrl}
+ target="_blank"
+ rel="noreferrer noopener"
+ aria-label={`${S.models.getApiKey} ${group.provider.label}`}
+ title={S.models.getApiKey}
+ className="inline-flex shrink-0 items-center whitespace-nowrap p-1 text-xs text-brand-600 underline-offset-2 hover:underline @4xl:p-0 dark:text-brand-300"
+ >
+ <GlyphIcon d={EXTERNAL_LINK_ICON} size={13} className="@4xl:hidden" />
+ <span className="hidden @4xl:inline">{S.models.getApiKey} ↗</span>
+ </a>
+ )}
+ {/* Collapse arrow sits at the far right of the header (after group actions); it too can be clicked to collapse. */}
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-label={group.provider.label}
+ onClick={() => toggleGroup(group.provider.id)}
+ className="shrink-0 p-1.5"
>
- <GlyphIcon d={EXTERNAL_LINK_ICON} size={13} className="@4xl:hidden" />
- <span className="hidden @4xl:inline">{S.models.getApiKey} ↗</span>
- </a>
- )}
- {/* Collapse arrow sits at the far right of the header (after group actions); it too can be clicked to collapse. */}
- <button
- type="button"
- aria-expanded={open}
- aria-label={group.provider.label}
- onClick={() => toggleGroup(group.provider.id)}
- className="shrink-0 p-1.5"
- >
- <Chevron open={open} className="text-gray-400" />
- </button>
- </div>
+ <Chevron open={open} className="text-gray-400" />
+ </button>
+ </div>
- {/* Expand/collapse height transition: grid-template-rows tweens between
+ {/* Expand/collapse height transition: grid-template-rows tweens between
0fr and 1fr, with the inner overflow-hidden handling clipping — pure
CSS, no need to measure content height. Content stays in the DOM while
collapsed (height is 0), so both directions animate. */}
- <div
- className={`grid transition-[grid-template-rows] duration-200 ease-out ${open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}
- >
- {/* inert while collapsed: a card with zero height shouldn't still be Tab-focusable or clickable. */}
- <div className="overflow-hidden" inert={!open}>
- <div
- className={`grid grid-cols-1 gap-2 border-t border-gray-200 p-2.5 transition-opacity duration-200 sm:grid-cols-2 lg:grid-cols-3 dark:border-gray-800 ${open ? "opacity-100" : "opacity-0"}`}
- >
- {group.rows.length === 0 ? (
- // An empty group only ever occurs for custom (always shown when there's no search query, to host the add entry point).
- <p className="col-span-full py-1 text-center text-xs text-gray-400 dark:text-gray-500">
- {S.models.groupEmptyHint}
- </p>
- ) : (
- group.rows.map((row) => (
- <ModelCard
- key={`${row.provider}:${row.modelId}`}
- row={row}
- currency={currency}
- isDefault={sameModelRef(rowRef(row), defaultModel)}
- isVisionModel={sameModelRef(rowRef(row), visionModel)}
- speed={speedResults.get(speedKey(row.provider, row.modelId))}
- onOpen={() => setEditing(rowRef(row))}
- />
- ))
- )}
+ <div
+ className={`grid transition-[grid-template-rows] duration-200 ease-out ${open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}
+ >
+ {/* inert while collapsed: a card with zero height shouldn't still be Tab-focusable or clickable. */}
+ <div className="overflow-hidden" inert={!open}>
+ <div
+ className={`grid grid-cols-1 gap-2 border-t border-gray-200 p-2.5 transition-opacity duration-200 sm:grid-cols-2 lg:grid-cols-3 dark:border-gray-800 ${open ? "opacity-100" : "opacity-0"}`}
+ >
+ {group.rows.length === 0 ? (
+ // An empty group only ever occurs for custom (always shown when there's no search query, to host the add entry point).
+ <p className="col-span-full py-1 text-center text-xs text-gray-400 dark:text-gray-500">
+ {S.models.groupEmptyHint}
+ </p>
+ ) : (
+ group.rows.map((row) => (
+ <ModelCard
+ key={`${row.provider}:${row.modelId}`}
+ row={row}
+ currency={currency}
+ isDefault={sameModelRef(rowRef(row), defaultModel)}
+ isVisionModel={sameModelRef(rowRef(row), visionModel)}
+ speed={speedResults.get(speedKey(row.provider, row.modelId))}
+ onOpen={() => setEditing(rowRef(row))}
+ />
+ ))
+ )}
+ </div>
</div>
</div>
- </div>
- </section>
+ </section>
+ </div>
);
})}
{isOwner && query.trim() === "" && (
diff --git a/packages/web/test/model-group-order.test.ts b/packages/web/test/model-group-order.test.ts
new file mode 100644
index 00000000..bebbbe85
--- /dev/null
+++ b/packages/web/test/model-group-order.test.ts
@@ -0,0 +1,295 @@
+/**
+ * model-group-order.ts unit tests plus the ordering behaviour it drives in
+ * model-grouping.ts: the models page's manual order of the PROVIDER GROUPS.
+ *
+ * Dragging is the whole intent — no sort toggle and no pinning — so an empty stored
+ * order must be the identity: a Project that has never been dragged renders exactly the
+ * built-in catalog sequence. Beyond that: one array per Project, groups with no stored
+ * place TRAILING (a group is created from a control below every group, so a new one must
+ * not jump to the top), stale keys inert, the always-visible custom group still obeying
+ * its own rule, and a drop committed against every group the library could show so an
+ * empty built-in keeps its catalog place.
+ *
+ * Provider ids are read from MODEL_PROVIDERS rather than spelled out: this file is about
+ * the ordering algebra, and the catalog's own membership is model-catalog.test.ts's.
+ */
+import { describe, expect, it } from "vitest";
+import { MODEL_PROVIDERS } from "@prismshadow/penguin-core/model-catalog";
+
+import {
+ commitModelGroupOrder,
+ loadModelGroupOrder,
+ modelGroupOrderKey,
+ orderModelGroups,
+ saveModelGroupOrder,
+} from "../src/features/models/model-group-order";
+import type { ModelGroupOrderStorage } from "../src/features/models/model-group-order";
+import {
+ allGroupKeys,
+ groupModelRows,
+ orderModelsLikeLibrary,
+ visibleChatModels,
+} from "../src/features/models/model-grouping";
+import type { ModelRowLike } from "../src/features/models/model-grouping";
+
+/** In-memory storage (vitest runs in a Node environment, no localStorage; group-order.test.ts convention). */
+function memStorage(): ModelGroupOrderStorage & { map: Map<string, string> } {
+ const map = new Map<string, string>();
+ return {
+ map,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ };
+}
+
+const CATALOG_IDS = MODEL_PROVIDERS.map((p) => p.id);
+
+const rows: ModelRowLike[] = [
+ { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ { provider: "moonshot", modelId: "kimi-k2.6" },
+ { provider: "minimax", modelId: "MiniMax-M3" },
+ { provider: "custom", modelId: "my-proxy-model" },
+ { provider: "zeta-vendor", modelId: "weird-model" },
+ { provider: "alpha-vendor", modelId: "other-model" },
+];
+
+describe("model group order storage", () => {
+ it("one array per Project, under the models page's key namespace", () => {
+ const s = memStorage();
+ expect(modelGroupOrderKey("p1")).toBe("penguin.modelsGroupOrder.p1");
+ saveModelGroupOrder("p1", ["minimax", "anthropic"], s);
+ saveModelGroupOrder("p2", ["moonshot"], s);
+ expect(loadModelGroupOrder("p1", s)).toEqual(["minimax", "anthropic"]);
+ expect(loadModelGroupOrder("p2", s)).toEqual(["moonshot"]);
+ // A Project switch cannot leak one arrangement into another.
+ expect([...s.map.keys()].sort()).toEqual([
+ "penguin.modelsGroupOrder.p1",
+ "penguin.modelsGroupOrder.p2",
+ ]);
+ });
+
+ it("no Project reads and writes nothing (the page renders before one resolves)", () => {
+ const s = memStorage();
+ saveModelGroupOrder(null, ["minimax"], s);
+ expect(s.map.size).toBe(0);
+ expect(loadModelGroupOrder(null, s)).toEqual([]);
+ });
+
+ it("nothing stored, or anything malformed, degrades to the empty order (i.e. the catalog sequence)", () => {
+ const s = memStorage();
+ expect(loadModelGroupOrder("p1", s)).toEqual([]);
+ for (const raw of ["{not json", '"minimax"', "42", "null", "{}", ""]) {
+ s.map.set(modelGroupOrderKey("p1"), raw);
+ expect(loadModelGroupOrder("p1", s)).toEqual([]);
+ }
+ // Junk elements are dropped, the string ids around them survive.
+ s.map.set(modelGroupOrderKey("p1"), '["minimax", 7, null, {"x": 1}, "anthropic"]');
+ expect(loadModelGroupOrder("p1", s)).toEqual(["minimax", "anthropic"]);
+ });
+
+ it("storage that throws degrades instead of escaping — load runs from a useState initializer", () => {
+ const hostile = {
+ get getItem(): never {
+ throw new Error("SecurityError");
+ },
+ setItem: () => undefined,
+ } as unknown as ModelGroupOrderStorage;
+ expect(() => loadModelGroupOrder("p1", hostile)).not.toThrow();
+ expect(loadModelGroupOrder("p1", hostile)).toEqual([]);
+ const broken: ModelGroupOrderStorage = {
+ getItem: () => {
+ throw new Error("denied");
+ },
+ setItem: () => {
+ throw new Error("denied");
+ },
+ };
+ expect(() => saveModelGroupOrder("p1", ["minimax"], broken)).not.toThrow();
+ });
+
+ it("with NO storage injected, resolving localStorage is itself inside the try", () => {
+ // vitest runs this package in Node, where `localStorage` is not defined at all — the
+ // same shape as a browser that throws on touching it. Omitting the argument is the
+ // only way to reach that branch, and it is the one the page's useState initializer
+ // takes, where an escaping throw would take the first render down.
+ expect(() => loadModelGroupOrder("p1")).not.toThrow();
+ expect(loadModelGroupOrder("p1")).toEqual([]);
+ expect(() => saveModelGroupOrder("p1", ["minimax"])).not.toThrow();
+ });
+});
+
+describe("allGroupKeys (the sequence a drop is committed against)", () => {
+ it("every built-in provider — empty ones included — then the user-defined groups, sorted", () => {
+ expect(allGroupKeys(rows)).toEqual([...CATALOG_IDS, "alpha-vendor", "zeta-vendor"]);
+ // Holding no models at all still yields the full built-in list: that is the point —
+ // a provider gaining its first model must not arrive as a newcomer.
+ expect(allGroupKeys([])).toEqual(CATALOG_IDS);
+ });
+});
+
+describe("groupModelRows with a manual group order", () => {
+ const idsOf = (order: readonly string[] = []) =>
+ groupModelRows(rows, "", order).map((g) => g.provider.id);
+
+ it("an empty order is the identity: the catalog sequence, user-defined groups last", () => {
+ expect(idsOf()).toEqual([
+ "anthropic",
+ "moonshot",
+ "minimax",
+ "custom",
+ "alpha-vendor",
+ "zeta-vendor",
+ ]);
+ });
+
+ it("named groups take the stored order; unnamed ones keep their catalog order and TRAIL", () => {
+ // minimax and anthropic are placed; the rest are unplaced and follow them, keeping
+ // their own relative catalog order.
+ expect(idsOf(["minimax", "anthropic"])).toEqual([
+ "minimax",
+ "anthropic",
+ "moonshot",
+ "custom",
+ "alpha-vendor",
+ "zeta-vendor",
+ ]);
+ });
+
+ it("a group created after the order was stored appears at the BOTTOM, not the top", () => {
+ // The control that creates a user-defined group sits below every group on the page, so
+ // the group it makes must not leap over the whole arrangement.
+ const stored = commitModelGroupOrder([], allGroupKeys(rows), "minimax", "anthropic", false);
+ const ids = groupModelRows([...rows, { provider: "brand-new", modelId: "m1" }], "", stored).map(
+ (g) => g.provider.id,
+ );
+ expect(ids.at(-1)).toBe("brand-new");
+ // Being unplaced is what puts it last, not its name — with no order stored, the
+ // automatic sort files it between the two user-defined groups already on the page.
+ const automatic = groupModelRows(
+ [...rows, { provider: "brand-new", modelId: "m1" }],
+ "",
+ [],
+ ).map((g) => g.provider.id);
+ expect(automatic.at(-1)).toBe("zeta-vendor");
+ expect(automatic.indexOf("brand-new")).toBeLessThan(automatic.indexOf("zeta-vendor"));
+ });
+
+ it("a user-defined group can be dragged above the built-ins", () => {
+ expect(idsOf(["zeta-vendor", ...CATALOG_IDS, "alpha-vendor"])).toEqual([
+ "zeta-vendor",
+ "anthropic",
+ "moonshot",
+ "minimax",
+ "custom",
+ "alpha-vendor",
+ ]);
+ });
+
+ it("stale keys are inert — a stored group that no longer exists changes nothing", () => {
+ expect(idsOf(["gone-vendor", "minimax", "also-gone"])).toEqual(idsOf(["minimax"]));
+ });
+
+ it("custom keeps its own rule: shown even when empty, at whatever place the order gives it", () => {
+ const withoutCustomRows = rows.filter((r) => r.provider !== "custom");
+ // Unplaced and empty: still rendered (it hosts the add entry point), in catalog order.
+ expect(groupModelRows(withoutCustomRows, "", []).map((g) => g.provider.id)).toContain("custom");
+ // Dragged to the front while still empty. Every group is named in the order, so none
+ // is unplaced and surfacing above it.
+ const keys = allGroupKeys(withoutCustomRows);
+ const ordered = groupModelRows(withoutCustomRows, "", [
+ "custom",
+ ...keys.filter((id) => id !== "custom"),
+ ]);
+ expect(ordered[0]!.provider.id).toBe("custom");
+ expect(ordered[0]!.rows).toEqual([]);
+ });
+
+ it("a search query still filters to matches, and empty groups other than custom stay dropped", () => {
+ const found = groupModelRows(rows, "kimi", ["minimax", "anthropic"]);
+ expect(found.map((g) => g.provider.id)).toEqual(["moonshot"]);
+ });
+});
+
+describe("the chat model picker follows the same order", () => {
+ it("orderModelsLikeLibrary and visibleChatModels both take the stored order", () => {
+ const order = ["minimax", "anthropic"];
+ expect(orderModelsLikeLibrary(rows, order).map((r) => r.provider)).toEqual([
+ "minimax",
+ "anthropic",
+ "moonshot",
+ "custom",
+ "alpha-vendor",
+ "zeta-vendor",
+ ]);
+ // No model here has a key, so the key filter degrades to "show everything" and the
+ // group order is the only thing deciding the sequence.
+ const visible = visibleChatModels(rows, { showAll: false, query: "", groupOrder: order });
+ expect(visible.map((r) => r.provider)).toEqual(
+ orderModelsLikeLibrary(rows, order).map((r) => r.provider),
+ );
+ });
+});
+
+describe("orderModelGroups (the placement rule the commit half has to match)", () => {
+ const keys = ["a", "b", "c", "d"];
+ const id = (x: string) => x;
+
+ it("an empty order is the identity", () => {
+ expect(orderModelGroups(keys, id, [])).toEqual(keys);
+ });
+
+ it("placed keys take the stored sequence, unplaced ones trail in their input order", () => {
+ expect(orderModelGroups(keys, id, ["d", "b"])).toEqual(["d", "b", "a", "c"]);
+ });
+
+ it("stored keys naming nothing are simply absent from the result", () => {
+ expect(orderModelGroups(keys, id, ["gone", "c"])).toEqual(["c", "a", "b", "d"]);
+ });
+});
+
+describe("committing a drop against the full group list", () => {
+ it("the first drop materialises the catalog order with one group moved", () => {
+ const keys = allGroupKeys(rows);
+ const first = keys[0]!;
+ const third = keys[2]!;
+ const stored = commitModelGroupOrder([], keys, first, third, true);
+ expect(stored).toEqual([keys[1], keys[2], first, ...keys.slice(3)]);
+ // Everything is placed, so nothing surfaces to the top on the next render.
+ expect(groupModelRows(rows, "", stored).map((g) => g.provider.id)).toEqual(
+ (stored as string[]).filter((id) =>
+ groupModelRows(rows, "", []).some((g) => g.provider.id === id),
+ ),
+ );
+ });
+
+ it("a provider holding no models keeps its catalog place, and appears there once it gains one", () => {
+ const keys = allGroupKeys(rows);
+ // The LAST built-in group with no rows in the fixture: it never renders today, and it
+ // sits late enough in the catalog that "did not jump to the front" is a real claim.
+ const empty = [...CATALOG_IDS]
+ .reverse()
+ .find((id) => id !== "custom" && !rows.some((r) => r.provider === id))!;
+ const stored = commitModelGroupOrder([], keys, "minimax", "anthropic", false);
+ expect(stored).toContain(empty);
+ const before = groupModelRows(rows, "", stored).map((g) => g.provider.id);
+ const after = groupModelRows(
+ [...rows, { provider: empty, modelId: "newly-added" }],
+ "",
+ stored,
+ ).map((g) => g.provider.id);
+ // It slots into the arrangement instead of arriving at the top as an unplaced newcomer,
+ // and disturbs nothing already on screen.
+ expect(after[0]).not.toBe(empty);
+ expect(after.filter((id) => id !== empty)).toEqual(before);
+ // The render is the stored order, filtered to the groups that have something to show.
+ expect(after).toEqual((stored as string[]).filter((id) => after.includes(id)));
+ });
+
+ it("a drop that moves nothing returns the input array, so nothing is persisted", () => {
+ const keys = allGroupKeys(rows);
+ const order = [...keys];
+ expect(commitModelGroupOrder(order, keys, keys[0]!, keys[0]!, false)).toBe(order);
+ // Dropping just above the neighbour it already sits above changes no sequence.
+ expect(commitModelGroupOrder(order, keys, keys[0]!, keys[1]!, false)).toBe(order);
+ });
+});