Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): drag an order row by its number on the Tools page (#3082)

Call Whitee879742c5f62
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 1578527e1..a6048bf47 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -177,14 +177,14 @@
"avibe/localized-user-text": 1
},
"src/components/settings/models/ToolsTab.tsx": {
- "avibe/localized-user-text": 2
+ "avibe/localized-user-text": 1
},
"src/components/settings/models/UsageTab.tsx": {
"avibe/localized-user-text": 5,
"react-hooks/set-state-in-effect": 5
},
"src/components/settings/models/WebFetchOrder.tsx": {
- "avibe/localized-user-text": 2
+ "avibe/localized-user-text": 1
},
"src/components/settings/models/modelsApi.ts": {
"no-useless-assignment": 1
diff --git a/ui/src/components/settings/models/SortableOrderList.tsx b/ui/src/components/settings/models/SortableOrderList.tsx
new file mode 100644
index 000000000..538e67b1f
--- /dev/null
+++ b/ui/src/components/settings/models/SortableOrderList.tsx
@@ -0,0 +1,156 @@
+// An executor order list whose rows can be dragged by their ordinal (Models › Tools): the search, fetch and X search
+// orders. The sensors, keyboard keys and announcements follow the workbench project list (SortableProjectList), so
+// reordering feels the same across Avibe. Only switched-on rows move; switched-off rows stay at the end, outside the
+// sortable set. A drop saves once, and the dropped order shows until that save settles.
+import * as React from 'react';
+import {
+ DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors, type Modifier,
+} from '@dnd-kit/core';
+import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import { useReducedMotion } from 'framer-motion';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+
+/** What the row's drag handle (its ordinal) spreads onto itself; null for a row that does not move. */
+export type OrderDragHandle = React.ComponentPropsWithRef<'button'> | null;
+
+const verticalOnly: Modifier = ({ transform }) => ({ ...transform, x: 0 });
+
+const SortableRow: React.FC<{
+ id: string;
+ /** No drag can start now (a save is out); the handle stays mounted, so a keyboard user keeps their place. */
+ disabled: boolean;
+ /** The row has a handle at all: a list of one has nothing to reorder. */
+ handled: boolean;
+ className: string;
+ attrs: Record<string, string>;
+ children: (handle: OrderDragHandle) => React.ReactNode;
+}> = ({ id, disabled, handled, className, attrs, children }) => {
+ const reducedMotion = useReducedMotion();
+ const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
+ id,
+ disabled,
+ transition: reducedMotion ? null : { duration: 220, easing: 'ease' },
+ });
+ return (
+ <li
+ ref={setNodeRef}
+ {...attrs}
+ className={cn(className, isDragging && 'is-dragging')}
+ style={{ transform: CSS.Translate.toString(transform), transition }}
+ >
+ {/* Disabled, the handle keeps its node and focus with no listeners and aria-disabled set. */}
+ {children(handled ? { ...attributes, ...listeners, ref: setActivatorNodeRef } : null)}
+ </li>
+ );
+};
+
+export function SortableOrderList<Row>({
+ rows, idOf, nameOf, isOn, pending, label, listRef, rowClassName, rowAttrs, onReorder, children,
+}: {
+ /** In the server's order, switched-off rows last. */
+ rows: readonly Row[];
+ idOf: (row: Row) => string;
+ nameOf: (row: Row) => string;
+ isOn: (row: Row) => boolean;
+ /** A write for this list is out: nothing moves until the server answers it. */
+ pending: boolean;
+ label: string;
+ listRef?: React.Ref<HTMLOListElement>;
+ rowClassName: (row: Row) => string;
+ rowAttrs: (row: Row) => Record<string, string>;
+ /** A drop: the switched-on rows' ids before it, and the row's move within them. */
+ onReorder: (shown: string[], from: number, to: number) => void;
+ children: (row: Row, index: number, handle: OrderDragHandle) => React.ReactNode;
+}) {
+ const { t } = useTranslation();
+ const sensors = useSensors(
+ useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),
+ useSensor(TouchSensor, { activationConstraint: { delay: 300, tolerance: 8 } }),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ keyboardCodes: { start: ['Space'], cancel: ['Escape'], end: ['Space'] },
+ }),
+ );
+ const on = rows.filter(isOn);
+ const off = rows.filter((row) => !isOn(row));
+ const served = on.map(idOf);
+ // The dropped order, shown while its save is out, so the row does not jump back first. Once the server shows it,
+ // or the save has been out and settled (refused, or answered with another order), the server's order is shown.
+ const [dropped, setDropped] = React.useState<{ order: string[]; sent: boolean } | null>(null);
+ if (dropped !== null) {
+ if (dropped.order.join('\n') === served.join('\n')) setDropped(null);
+ else if (pending && !dropped.sent) setDropped({ ...dropped, sent: true });
+ else if (!pending && dropped.sent) setDropped(null);
+ }
+ const ids = dropped !== null && dropped.order.length === served.length && dropped.order.every((id) => served.includes(id)) ? dropped.order : served;
+ const byId = new Map(on.map((row) => [idOf(row), row] as const));
+ const name = (id: string | number) => {
+ const row = byId.get(String(id));
+ return row ? nameOf(row) : '';
+ };
+ const handled = ids.length >= 2;
+ return (
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ modifiers={[verticalOnly]}
+ accessibility={{
+ screenReaderInstructions: { draggable: t('settings.models.tools.order.dragInstructions') },
+ announcements: {
+ onDragStart: ({ active }) => t('settings.models.tools.order.dragPickedUp', { source: name(active.id) }),
+ onDragOver: ({ active, over }) => over
+ ? t('settings.models.tools.order.dragPosition', { source: name(active.id), position: ids.indexOf(String(over.id)) + 1, count: ids.length })
+ : undefined,
+ onDragEnd: ({ active }) => t('settings.models.tools.order.dragDropped', { source: name(active.id) }),
+ onDragCancel: ({ active }) => t('settings.models.tools.order.dragCancelled', { source: name(active.id) }),
+ },
+ }}
+ onDragEnd={({ active, over }) => {
+ const from = ids.indexOf(String(active.id));
+ const to = ids.indexOf(String(over?.id));
+ if (from < 0 || to < 0 || from === to) return;
+ const next = [...ids];
+ next.splice(to, 0, ...next.splice(from, 1));
+ setDropped({ order: next, sent: false });
+ onReorder(ids, from, to);
+ }}
+ >
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
+ <ol ref={listRef} className="flex flex-col gap-1.5" aria-label={label}>
+ {ids.map((id, index) => {
+ const row = byId.get(id)!;
+ return (
+ <SortableRow key={id} id={id} disabled={pending || !handled} handled={handled} className={rowClassName(row)} attrs={rowAttrs(row)}>
+ {(handle) => children(row, index, handle)}
+ </SortableRow>
+ );
+ })}
+ {off.map((row, index) => (
+ <li key={idOf(row)} {...rowAttrs(row)} className={rowClassName(row)}>{children(row, ids.length + index, null)}</li>
+ ))}
+ </ol>
+ </SortableContext>
+ </DndContext>
+ );
+}
+
+/** A row's position: its ordinal, which is also its drag handle while the row can move. */
+export const OrderOrdinal: React.FC<{ index: number; off: boolean; handle: OrderDragHandle; name: string }> = ({ index, off, handle, name }) => {
+ const { t } = useTranslation();
+ const className = cn('model-hub-order-ordinal', index === 0 && !off && 'is-first');
+ if (off) return <span className={className}>{t('settings.models.tools.order.offPosition')}</span>;
+ if (!handle) return <span className={className}>{index + 1}</span>;
+ return (
+ <button
+ type="button"
+ {...handle}
+ className={cn(className, 'is-handle')}
+ aria-label={t('settings.models.tools.order.dragHandle', { source: name, position: index + 1 }) as string}
+ >
+ {index + 1}
+ </button>
+ );
+};
diff --git a/ui/src/components/settings/models/ToolsTab.test.tsx b/ui/src/components/settings/models/ToolsTab.test.tsx
index a28e0512b..0a7b2f3c6 100644
--- a/ui/src/components/settings/models/ToolsTab.test.tsx
+++ b/ui/src/components/settings/models/ToolsTab.test.tsx
@@ -384,7 +384,8 @@ describe('ToolsTab executor order', () => {
const writing = new Set<HostedToolName>(['web_search']);
const { rerender } = render(view(before));
await openAdvanced(user, 'Web search');
- const status = screen.getByRole('status');
+ // A drag has its own live region; this is the arrows' announcement.
+ const status = screen.getAllByRole('status').find((node) => node.hasAttribute('data-order-moved'))!;
// Refused: nothing moved, so nothing is announced and nothing waits to take focus.
await user.click(screen.getByRole('button', { name: 'Move relay-gpt up' }));
diff --git a/ui/src/components/settings/models/ToolsTab.tsx b/ui/src/components/settings/models/ToolsTab.tsx
index bddb43165..f41107f7b 100644
--- a/ui/src/components/settings/models/ToolsTab.tsx
+++ b/ui/src/components/settings/models/ToolsTab.tsx
@@ -14,11 +14,12 @@ import { Select } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { ToggleSwitch } from '../SettingsPrimitives';
import { cooldownTime, formatMonthDay, formatNameList, formatSmallUsd } from './format';
-import { executorOrderAfterMove, imageModelCopyKey, pairEvidence, refusalSummary, type PairEvidence, type RefusalSummary } from './hostedTools';
+import { executorOrderAfterMove, executorOrderAfterReorder, imageModelCopyKey, pairEvidence, refusalSummary, type PairEvidence, type RefusalSummary } from './hostedTools';
import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
import { KEYLESS_EXA_SOURCE_ID, candidateEnabled, searchServicesActive, serviceVendorForSource, webSearchTool } from './searchServices';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { OrderStepper } from './OrderStepper';
+import { OrderOrdinal, SortableOrderList } from './SortableOrderList';
import { OrderPrice, SearchCandidateStatus, SearchServiceOrderPrice, SearchVendorGlyph } from './SearchServiceParts';
import { WebFetchOrder } from './WebFetchOrder';
import { fetchVendorForSource, webFetchTool } from './webFetch';
@@ -183,6 +184,14 @@ const ExecutorOrder: React.FC<{ tool: HostedSearchToolStatus; lookup: SourceLook
const candidates = tool.executor_candidates;
const movable = candidates.filter(candidateEnabled);
const custom = tool.executor_order !== null;
+ const candidateName = (candidate: HostedExecutorCandidate): string => {
+ if (candidate.kind === 'service' && candidate.source_id === KEYLESS_EXA_SOURCE_ID) return t('settings.models.searchServices.vendorName.exa-mcp') as string;
+ const vendor = candidate.kind === 'service'
+ ? activeWeb?.service_vendors?.find((item) => item.source_ids.includes(candidate.source_id))
+ : undefined;
+ return lookup.source(candidate.source_id)?.display_name
+ ?? (vendor ? t(`settings.models.searchServices.vendorName.${vendor.id}`, { defaultValue: vendor.name }) as string : lookup.name(candidate.source_id));
+ };
// A move is announced, and focus follows the moved row, only once the server's
// order shows it. One that did not land (refused, or lost and reconciled to
// another order) is dropped once its write has been out and settled, without
@@ -250,15 +259,25 @@ const ExecutorOrder: React.FC<{ tool: HostedSearchToolStatus; lookup: SourceLook
{candidates.length === 0
? <p className="model-hub-tool-note flex items-start gap-2"><Info className="mt-px size-[13px] shrink-0" aria-hidden />{t('settings.models.tools.order.empty', { toolInline })}</p>
: (
- <ol ref={list} className="flex flex-col gap-1.5" aria-label={t(activeWeb ? 'settings.models.searchServices.order' : 'settings.models.tools.order.title') as string}>
- {candidates.map((candidate, index) => {
+ <SortableOrderList
+ rows={candidates}
+ idOf={(candidate) => candidate.source_id}
+ nameOf={candidateName}
+ isOn={candidateEnabled}
+ pending={pending}
+ label={t(activeWeb ? 'settings.models.searchServices.order' : 'settings.models.tools.order.title') as string}
+ listRef={list}
+ rowClassName={(candidate) => cn('model-hub-tool-executor-row grid items-center rounded-lg border border-border bg-background', !candidateEnabled(candidate) && 'is-off')}
+ rowAttrs={(candidate) => ({ 'data-executor': candidate.source_id })}
+ onReorder={(shown, from, to) => { setRequested(null); onSave(tool.name, { executor_order: executorOrderAfterReorder(tool.executor_order, shown, from, to) }); }}
+ >
+ {(candidate, index, handle) => {
const source = lookup.source(candidate.source_id);
const vendor = candidate.kind === 'service'
? activeWeb?.service_vendors?.find((item) => item.source_ids.includes(candidate.source_id))
: undefined;
const keyless = candidate.kind === 'service' && candidate.source_id === KEYLESS_EXA_SOURCE_ID;
- const name = keyless ? t('settings.models.searchServices.vendorName.exa-mcp') as string : source?.display_name
- ?? (vendor ? t(`settings.models.searchServices.vendorName.${vendor.id}`, { defaultValue: vendor.name }) as string : lookup.name(candidate.source_id));
+ const name = candidateName(candidate);
const cooldown = candidate.kind === 'service' && candidate.cooldown_until !== null
? cooldownTime(candidate.cooldown_until, i18n.language)
: null;
@@ -280,8 +299,8 @@ const ExecutorOrder: React.FC<{ tool: HostedSearchToolStatus; lookup: SourceLook
/>
);
return (
- <li key={candidate.source_id} className={cn('model-hub-tool-executor-row grid items-center rounded-lg border border-border bg-background', switchedOff && 'is-off')} data-executor={candidate.source_id}>
- <span className="flex items-center gap-1.5">{stepper}<span className={cn('model-hub-order-ordinal', index === 0 && !switchedOff && 'is-first')}>{switchedOff ? '—' : index + 1}</span></span>
+ <>
+ <span className="flex items-center gap-1.5">{stepper}<OrderOrdinal index={index} off={switchedOff} handle={handle} name={name} /></span>
{activeWeb ? <div className="flex min-w-0 items-center gap-3">
{source ? <SearchVendorGlyph vendor={source.vendor} /> : candidate.kind === 'service' ? <SearchVendorGlyph vendor={vendor?.id ?? candidate.model_id} /> : <SourceGlyph source={source} />}
<div className="flex min-w-0 flex-col gap-0.5">
@@ -312,12 +331,13 @@ const ExecutorOrder: React.FC<{ tool: HostedSearchToolStatus; lookup: SourceLook
: { executors: { [candidate.source_id]: { enabled: switchedOff } } })}
/>
)}</span>
- </li>
+ </>
);
- })}
- </ol>
+ }}
+ </SortableOrderList>
)}
- <span role="status" className="sr-only">{landed && t('settings.models.tools.order.moved', { source: lookup.name(requested.sourceId), position: requested.position, count: requested.count })}</span>
+ {/* The arrows' announcement; a drag is announced by the drag context's own live region. */}
+ <span role="status" data-order-moved className="sr-only">{landed && t('settings.models.tools.order.moved', { source: lookup.name(requested.sourceId), position: requested.position, count: requested.count })}</span>
</div>
);
};
diff --git a/ui/src/components/settings/models/WebFetch.test.tsx b/ui/src/components/settings/models/WebFetch.test.tsx
index 3f354ae23..d8004f430 100644
--- a/ui/src/components/settings/models/WebFetch.test.tsx
+++ b/ui/src/components/settings/models/WebFetch.test.tsx
@@ -3,8 +3,8 @@
// Search-only tests cannot catch fetch becoming a saved search override or a
// catalog badge invented for a search-only Source.
import * as React from 'react';
-import { afterEach, expect, it, vi } from 'vitest';
-import { cleanup, render, screen, within } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { I18nextProvider } from 'react-i18next';
import i18n from '@/i18n';
@@ -99,3 +99,85 @@ it.each([false, true])('adds only catalog-backed Search/Fetch badges, active=%s'
expect(within(builtin).queryByRole('button', { name: /添加/ })).toBeNull();
}
});
+
+
+describe('dragging an order by its ordinal', () => {
+ // jsdom lays nothing out; give each order row the box it would have, one under the other, so the drag's keyboard
+ // sensor can find the row below.
+ const layout = () => vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
+ const row = this.closest('[data-executor]');
+ const index = row ? [...row.parentElement!.children].indexOf(row) : -1;
+ const top = index < 0 ? 0 : index * 60;
+ return { x: 0, y: top, top, left: 0, width: 600, height: index < 0 ? 0 : 52, right: 600, bottom: top + (index < 0 ? 0 : 52), toJSON: () => ({}) } as DOMRect;
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it('makes each switched-on row\'s number its handle, and a switched-off row has none', () => {
+ const tool = structuredClone(fetch);
+ tool.executor_candidates[3].settings.enabled = false;
+ render(wrap(<ToolsTab read={readyRegion({ tools: [tool] })} sources={SEARCH_SOURCES} pending={new Set()} onSave={vi.fn()} onClear={vi.fn()} onRetry={vi.fn()} />));
+ const rows = within(screen.getByRole('list', { name: '读取顺序' })).getAllByRole('listitem');
+ const handle = within(rows[0]).getByRole('button', { name: '拖动调整 本机 的位置,当前第 1 位' });
+ expect(handle.textContent).toBe('1');
+ expect(handle.getAttribute('aria-roledescription')).toBe('sortable');
+ expect(within(rows[3]).queryByRole('button', { name: /^拖动调整/ })).toBeNull();
+ expect(within(rows[3]).getByText('—')).toBeTruthy();
+ });
+
+ it('holds the order still while a save is out, keeping each handle in place', () => {
+ render(wrap(<ToolsTab read={readyRegion({ tools: [fetch] })} sources={SEARCH_SOURCES} pending={new Set(['web_fetch'] as const)} onSave={vi.fn()} onClear={vi.fn()} onRetry={vi.fn()} />));
+ const handles = within(screen.getByRole('list', { name: '读取顺序' })).getAllByRole('button', { name: /^拖动调整/ });
+ expect(handles.map((handle) => handle.getAttribute('aria-disabled'))).toEqual(['true', 'true', 'true', 'true']);
+ });
+
+ it('keeps a keyboard user on the dropped row\'s handle through the save', async () => {
+ layout();
+ // The page marks the tool pending while its write is out, then shows the order the server answers.
+ const Page: React.FC = () => {
+ const [state, setState] = React.useState({ tool: fetch, pending: false });
+ const save = (_tool: string, body: { executor_order?: string[] | null }) => {
+ setState((current) => ({ ...current, pending: true }));
+ setTimeout(() => setState({
+ pending: false,
+ tool: { ...fetch, executor_order: body.executor_order ?? null, executor_candidates: body.executor_order!.map((id) => fetch.executor_candidates.find((row) => row.source_id === id)!) },
+ }), 0);
+ };
+ return <ToolsTab read={readyRegion({ tools: [state.tool] })} sources={SEARCH_SOURCES} pending={new Set(state.pending ? ['web_fetch' as const] : [])} onSave={save as never} onClear={vi.fn()} onRetry={vi.fn()} />;
+ };
+ render(wrap(<Page />));
+ const list = screen.getByRole('list', { name: '读取顺序' });
+ within(list).getByRole('button', { name: '拖动调整 本机 的位置,当前第 1 位' }).focus();
+ await userEvent.keyboard(' ');
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.keyboard(' ');
+ // While the save is out, and once it settles, focus stays on the moved row's handle.
+ expect(document.activeElement?.getAttribute('aria-label')).toBe('拖动调整 本机 的位置,当前第 2 位');
+ await waitFor(() => expect(within(list).getAllByRole('listitem')[1].getAttribute('data-executor')).toBe('src_localfetch'));
+ await waitFor(() => expect(document.activeElement?.getAttribute('aria-disabled')).toBe('false'));
+ expect(document.activeElement?.getAttribute('aria-label')).toBe('拖动调整 本机 的位置,当前第 2 位');
+ // So the next move needs no trip back to the row.
+ await userEvent.keyboard(' ');
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.keyboard(' ');
+ await waitFor(() => expect(within(list).getAllByRole('listitem')[2].getAttribute('data-executor')).toBe('src_localfetch'));
+ });
+
+ it('picks a row up with Space, moves it with the arrows, and saves once on drop', async () => {
+ layout();
+ const save = vi.fn();
+ render(wrap(<ToolsTab read={readyRegion({ tools: [fetch] })} sources={SEARCH_SOURCES} pending={new Set()} onSave={save} onClear={vi.fn()} onRetry={vi.fn()} />));
+ const list = screen.getByRole('list', { name: '读取顺序' });
+ within(list).getByRole('button', { name: '拖动调整 本机 的位置,当前第 1 位' }).focus();
+ await userEvent.keyboard(' ');
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.keyboard('{ArrowDown}');
+ expect(save).not.toHaveBeenCalled();
+ await userEvent.keyboard(' ');
+ expect(save.mock.calls).toEqual([
+ ['web_fetch', { executor_order: ['src_tavily01', 'src_exakeyless', 'src_localfetch', 'src_jinakeyless'] }],
+ ]);
+ // The dropped order shows while the save is out, instead of jumping back first.
+ expect(within(list).getAllByRole('listitem').map((row) => row.getAttribute('data-executor')))
+ .toEqual(['src_tavily01', 'src_exakeyless', 'src_localfetch', 'src_jinakeyless']);
+ });
+});
diff --git a/ui/src/components/settings/models/WebFetchOrder.tsx b/ui/src/components/settings/models/WebFetchOrder.tsx
index 2316b20ea..095d86263 100644
--- a/ui/src/components/settings/models/WebFetchOrder.tsx
+++ b/ui/src/components/settings/models/WebFetchOrder.tsx
@@ -8,7 +8,8 @@ import { cn } from '@/lib/utils';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { OrderPrice, SearchVendorGlyph } from './SearchServiceParts';
import { OrderStepper } from './OrderStepper';
-import { executorOrderAfterMove } from './hostedTools';
+import { executorOrderAfterMove, executorOrderAfterReorder } from './hostedTools';
+import { OrderOrdinal, SortableOrderList } from './SortableOrderList';
import { cooldownTime, formatMonthDay, formatSmallUsd } from './format';
import { sourceStatePresentation } from './sourceStatePresentation';
import { fetchVendorForSource } from './webFetch';
@@ -116,15 +117,26 @@ export const WebFetchOrder: React.FC<{
</div>
{tool.executor_order !== null && <Button variant="outline" size="xs" disabled={pending} onClick={() => onSave({ executor_order: null })}><RotateCcw aria-hidden />{t('settings.models.tools.order.reset')}</Button>}
</div>
- <ol ref={list} className="flex flex-col gap-1.5" aria-label={t('settings.models.webFetch.order')}>
- {rows.map((row, index) => {
+ <SortableOrderList
+ rows={rows}
+ idOf={(row) => row.source_id}
+ nameOf={(row) => name(row.source_id)}
+ isOn={(row) => row.settings.enabled}
+ pending={pending}
+ label={t('settings.models.webFetch.order')}
+ listRef={list}
+ rowClassName={(row) => cn('model-hub-tool-executor-row grid items-center rounded-lg border border-border bg-background', !row.settings.enabled && 'is-off')}
+ rowAttrs={(row) => ({ 'data-executor': row.source_id })}
+ onReorder={(shown, from, to) => onSave({ executor_order: executorOrderAfterReorder(tool.executor_order, shown, from, to) })}
+ >
+ {(row, index, handle) => {
const vendor = fetchVendorForSource(tool, row.source_id);
const label = name(row.source_id);
const off = !row.settings.enabled;
- return <li key={row.source_id} data-executor={row.source_id} className={cn('model-hub-tool-executor-row grid items-center rounded-lg border border-border bg-background', off && 'is-off')}>
+ return <>
<span className="flex items-center gap-1.5">
<OrderStepper label={label} canUp={!off && index > 0} canDown={!off && index < enabled.length - 1} pending={pending} onMove={(direction) => move(index, direction)} />
- <span className={cn('model-hub-order-ordinal', index === 0 && !off && 'is-first')}>{off ? '—' : index + 1}</span>
+ <OrderOrdinal index={index} off={off} handle={handle} name={label} />
</span>
<div className="flex min-w-0 items-center gap-3"><SearchVendorGlyph vendor={vendor?.id ?? 'local'} /><div className="flex min-w-0 flex-col gap-0.5">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1"><button type="button" data-search-source={row.source_id} className="truncate text-left font-semibold hover:underline" onClick={(event) => vendor?.facts.built_in && vendor.id !== 'exa-mcp' ? setDetail(row.source_id) : onOpen?.(row.source_id, event.currentTarget)}>{label}</button><FetchStatus candidate={row} tool={tool} inRow /></div>
@@ -133,9 +145,9 @@ export const WebFetchOrder: React.FC<{
</div></div>
<FetchOrderPrice candidate={row} />
<span className="model-hub-order-switch"><ToggleSwitch enabled={!off} disabled={pending} label={t('settings.models.webFetch.use')} onClick={() => onSave({ services: { [row.source_id]: { enabled: off } } })} /></span>
- </li>;
- })}
- </ol>
+ </>;
+ }}
+ </SortableOrderList>
<div className="flex flex-wrap items-center justify-between gap-3"><Button variant="outline" size="sm" disabled={pending} onClick={(event) => onAdd?.(event.currentTarget)}><Plus aria-hidden />{t('settings.models.webFetch.add')}</Button><p className="model-hub-tool-note flex items-center gap-1.5" title={t('settings.models.webFetch.custody') as string}><LockKeyhole className="size-3.5 shrink-0" aria-hidden />{t('settings.models.searchServices.custodyShort')}</p></div>
{detail && <Dialog open onOpenChange={(open) => { if (!open) setDetail(null); }}><DialogContent className="max-w-xl border-border-strong bg-surface" closeLabel={t('common.close')}><DialogHeader><DialogTitle>{name(detail)}</DialogTitle><DialogDescription>{t('settings.models.webFetch.custody')}</DialogDescription></DialogHeader><FetchServiceSettings sourceId={detail} tool={tool} pending={pending} onSave={onSave} onRetry={(id) => onRetry?.(id)} /></DialogContent></Dialog>}
</div>;
diff --git a/ui/src/components/settings/models/hostedTools.test.ts b/ui/src/components/settings/models/hostedTools.test.ts
index 5a7a7452d..552fa7892 100644
--- a/ui/src/components/settings/models/hostedTools.test.ts
+++ b/ui/src/components/settings/models/hostedTools.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { executorOrderAfterMove, modelCapabilities, pairEvidence, refusalSummary } from './hostedTools';
+import { executorOrderAfterMove, executorOrderAfterReorder, modelCapabilities, pairEvidence, refusalSummary } from './hostedTools';
import type { HostedRefusal, HostedSuccess, HostedToolRunStatus, HostedToolsStatus } from './types';
const RELAY = 'src_relay001';
@@ -96,6 +96,9 @@ describe('hosted-tool status projection', () => {
// H is saved but not shown now (refused, or gone for a while); C is shown but not saved.
expect(executorOrderAfterMove(['A', 'H', 'B'], ['A', 'B', 'C'], 2, -1)).toEqual(['A', 'H', 'C', 'B']);
expect(executorOrderAfterMove(['H', 'A', 'B'], ['A', 'B'], 1, -1)).toEqual(['H', 'B', 'A']);
+ // A drag moves one executor any distance, keeping hidden ids where they were.
+ expect(executorOrderAfterReorder(null, ['A', 'B', 'C', 'D'], 0, 2)).toEqual(['B', 'C', 'A', 'D']);
+ expect(executorOrderAfterReorder(['A', 'H', 'B', 'C'], ['A', 'B', 'C'], 2, 0)).toEqual(['C', 'H', 'A', 'B']);
// Automatic: the shown order is the whole order.
expect(executorOrderAfterMove(null, ['A', 'B'], 0, 1)).toEqual(['B', 'A']);
});
diff --git a/ui/src/components/settings/models/hostedTools.ts b/ui/src/components/settings/models/hostedTools.ts
index 7a82b6c5c..b842251ce 100644
--- a/ui/src/components/settings/models/hostedTools.ts
+++ b/ui/src/components/settings/models/hostedTools.ts
@@ -103,21 +103,22 @@ export const modelCapabilities = (status: HostedToolsStatus, sourceId: string, m
});
/**
- * The executor order to save after moving one shown executor. The saved order may
- * name Sources the read does not show now (refused, or gone for a while); the
- * server keeps those on purpose and skips them, so a move rearranges only the
- * shown ones within the saved list and leaves every hidden id where it was. A
- * shown executor the saved list lacks follows the list, in its new place.
+ * The executor order to save after moving one shown executor from position `from`
+ * to `to` (a drag, or one step of an arrow). The saved order may name Sources the
+ * read does not show now (refused, or gone for a while); the server keeps those on
+ * purpose and skips them, so a move rearranges only the shown ones within the
+ * saved list and leaves every hidden id where it was. A shown executor the saved
+ * list lacks follows the list, in its new place.
*/
-export const executorOrderAfterMove = (
+export const executorOrderAfterReorder = (
saved: readonly string[] | null,
shown: readonly string[],
- index: number,
- direction: -1 | 1,
+ from: number,
+ to: number,
): string[] => {
const moved = [...shown];
- const [item] = moved.splice(index, 1);
- moved.splice(index + direction, 0, item);
+ const [item] = moved.splice(from, 1);
+ moved.splice(to, 0, item);
if (saved === null) return moved;
const visible = new Set(shown);
const next = moved[Symbol.iterator]();
@@ -125,6 +126,14 @@ export const executorOrderAfterMove = (
return [...merged, ...next];
};
+/** One arrow step: the move from `index` to its neighbor in `direction`. */
+export const executorOrderAfterMove = (
+ saved: readonly string[] | null,
+ shown: readonly string[],
+ index: number,
+ direction: -1 | 1,
+): string[] => executorOrderAfterReorder(saved, shown, index, index + direction);
+
/**
* The copy key under `settings.models.tools.image.description` for an image model
* id. A dot separates i18n key segments, so the id's dots become underscores.
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 584b8a91b..e5078fc1b 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -2068,6 +2068,23 @@
font-weight: 400;
}
.model-hub-order-ordinal.is-first { background: var(--mint-soft); color: var(--mint-ink); }
+/* A row that can move is dragged by its ordinal: it reads as the position, and invites a grab on hover. */
+.model-hub-order-ordinal.is-handle {
+ border: 0;
+ cursor: grab;
+ touch-action: manipulation;
+ transition: background-color 120ms ease, color 120ms ease;
+}
+.model-hub-order-ordinal.is-handle[aria-disabled='true'] { cursor: default; }
+.model-hub-order-ordinal.is-handle:not([aria-disabled='true']):hover { background: var(--model-hub-wash-14); color: var(--foreground); }
+.model-hub-order-ordinal.is-handle.is-first:not([aria-disabled='true']):hover { background: var(--mint-soft); color: var(--mint-ink); box-shadow: inset 0 0 0 1px var(--mint-ink); }
+.model-hub-order-ordinal.is-handle:focus-visible { outline: 2px solid var(--mint); outline-offset: 1px; }
+.model-hub-tool-executor-row.is-dragging {
+ position: relative;
+ z-index: 10;
+ box-shadow: var(--model-hub-menu-shadow);
+}
+.model-hub-tool-executor-row.is-dragging .model-hub-order-ordinal.is-handle { cursor: grabbing; }
.model-hub-order-name {
--model-hub-order-name-size: 12.5px;
font-size: var(--model-hub-order-name-size);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 51e0485f4..7a89b01f1 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2504,7 +2504,15 @@
"moveUp": "Move {{source}} up",
"moveDown": "Move {{source}} down",
"moved_one": "Moved {{source}} to position {{position}} of {{count}}.",
- "moved_other": "Moved {{source}} to position {{position}} of {{count}}."
+ "moved_other": "Moved {{source}} to position {{position}} of {{count}}.",
+ "dragHandle": "Drag to reorder {{source}}, now position {{position}}",
+ "dragInstructions": "Press Space to pick up, the arrow keys to move, and Space to drop; Escape cancels. You can also drag the number with the mouse.",
+ "dragPickedUp": "Picked up {{source}}.",
+ "dragDropped": "Dropped {{source}}.",
+ "dragCancelled": "Cancelled moving {{source}}.",
+ "dragPosition_one": "{{source}}, position {{position}} of {{count}}.",
+ "dragPosition_other": "{{source}}, position {{position}} of {{count}}.",
+ "offPosition": "—"
},
"sources": {
"title": "Status by Source",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index a3d608f93..accc4a2f6 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2504,7 +2504,15 @@
"moveUp": "上移 {{source}}",
"moveDown": "下移 {{source}}",
"moved_one": "已将 {{source}} 移到第 {{position}} 位,共 {{count}} 位。",
- "moved_other": "已将 {{source}} 移到第 {{position}} 位,共 {{count}} 位。"
+ "moved_other": "已将 {{source}} 移到第 {{position}} 位,共 {{count}} 位。",
+ "dragHandle": "拖动调整 {{source}} 的位置,当前第 {{position}} 位",
+ "dragInstructions": "按空格键抓起,方向键移动,再按空格键放下,Escape 取消。也可以用鼠标按住序号拖动。",
+ "dragPickedUp": "已抓起 {{source}}。",
+ "dragDropped": "已放下 {{source}}。",
+ "dragCancelled": "已取消移动 {{source}}。",
+ "dragPosition_one": "{{source}},第 {{position}} 位,共 {{count}} 位。",
+ "dragPosition_other": "{{source}},第 {{position}} 位,共 {{count}} 位。",
+ "offPosition": "—"
},
"sources": {
"title": "各供应商状态",