1
0
forked from boos/BoosAPI

Add site filters for manual connection selection (#328)

This commit is contained in:
Cita
2026-03-30 16:32:48 +08:00
committed by GitHub
parent 0d2c4501c2
commit 7d91823f6c
7 changed files with 239 additions and 36 deletions
@@ -138,6 +138,34 @@ describe('search routes', () => {
});
});
it('returns site matches for platform keywords in global search', async () => {
const site = await db.insert(schema.sites).values({
name: 'Direct Workspace',
url: 'https://workspace.example.com',
platform: 'codex',
}).returning().get();
const response = await app.inject({
method: 'POST',
url: '/api/search',
payload: {
query: 'codex',
limit: 20,
},
});
expect(response.statusCode).toBe(200);
expect(response.json()).toMatchObject({
sites: [
expect.objectContaining({
id: site.id,
name: 'Direct Workspace',
url: 'https://workspace.example.com',
}),
],
});
});
it('includes oauth direct-account model availability in model search results', async () => {
const site = await db.insert(schema.sites).values({
name: 'codex site',
+9 -8
View File
@@ -46,14 +46,13 @@ export async function searchRoutes(app: FastifyInstance) {
const perCategory = Math.min(Math.ceil(limit / 6), 10);
// Search sites
const sites = (await db.select().from(schema.sites)
.where(like(schema.sites.name, q))
.limit(perCategory).all())
.concat(
await db.select().from(schema.sites)
.where(like(schema.sites.url, q))
.limit(perCategory).all()
);
const sites = await db.select().from(schema.sites)
.where(or(
like(schema.sites.name, q),
like(schema.sites.url, q),
like(schema.sites.platform, q),
))
.limit(perCategory).all();
// Deduplicate by id
const uniqueSites = [...new Map(sites.map(s => [s.id, s])).values()].slice(0, perCategory);
@@ -63,6 +62,7 @@ export async function searchRoutes(app: FastifyInstance) {
.where(or(
like(schema.accounts.username, q),
like(schema.sites.name, q),
like(schema.sites.platform, q),
))
.limit(perCategory).all();
const apiKeyLabelMatches = matchesApiKeyDisplayLabel(query);
@@ -91,6 +91,7 @@ export async function searchRoutes(app: FastifyInstance) {
like(schema.accountTokens.tokenGroup, q),
like(schema.accounts.username, q),
like(schema.sites.name, q),
like(schema.sites.platform, q),
))
.orderBy(desc(schema.accountTokens.updatedAt))
.limit(perCategory)
+62 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { create } from 'react-test-renderer';
import { act, create, type ReactTestInstance } from 'react-test-renderer';
import ModernSelect from './ModernSelect.js';
function collectText(node: ReturnType<typeof create>['root']): string {
@@ -9,6 +9,14 @@ function collectText(node: ReturnType<typeof create>['root']): string {
.join('');
}
function collectInstanceText(node: ReactTestInstance): string {
const children = node.children || [];
return children.map((child) => {
if (typeof child === 'string') return child;
return collectInstanceText(child);
}).join('');
}
describe('ModernSelect', () => {
it('renders icon nodes for the selected option', () => {
const root = create(
@@ -29,4 +37,57 @@ describe('ModernSelect', () => {
expect(collectText(root.root)).toContain('🟢');
expect(collectText(root.root)).toContain('NVIDIA');
});
it('filters searchable options by label and description keywords', async () => {
const root = create(
<ModernSelect
searchable
searchPlaceholder="筛选站点"
value=""
onChange={() => {}}
options={[
{ value: 'alpha', label: 'Alpha Mirror', description: 'https://alpha.example.com' },
{ value: 'beta', label: 'Beta Relay (codex)', description: 'https://beta.example.com' },
{ value: 'gamma', label: 'Gamma API', description: 'https://third.example.com' },
]}
/>,
);
const trigger = root.root.find((node) => (
node.type === 'button'
&& typeof node.props.className === 'string'
&& node.props.className.includes('modern-select-trigger')
));
await act(async () => {
trigger.props.onClick();
});
const searchInput = root.root.find((node) => (
node.type === 'input'
&& node.props.placeholder === '筛选站点'
));
await act(async () => {
searchInput.props.onChange({ target: { value: 'codex' } });
});
let optionButtons = root.root.findAll((node) => (
node.type === 'button'
&& typeof node.props.className === 'string'
&& node.props.className.includes('modern-select-option')
));
expect(optionButtons.map((node) => collectInstanceText(node))).toEqual(['Beta Relay (codex)https://beta.example.com']);
await act(async () => {
searchInput.props.onChange({ target: { value: 'third.example.com' } });
});
optionButtons = root.root.findAll((node) => (
node.type === 'button'
&& typeof node.props.className === 'string'
&& node.props.className.includes('modern-select-option')
));
expect(optionButtons.map((node) => collectInstanceText(node))).toEqual(['Gamma APIhttps://third.example.com']);
});
});
+43 -2
View File
@@ -20,6 +20,8 @@ type ModernSelectProps = {
menuMaxHeight?: number;
className?: string;
size?: 'md' | 'sm';
searchable?: boolean;
searchPlaceholder?: string;
};
export default function ModernSelect({
@@ -32,8 +34,11 @@ export default function ModernSelect({
menuMaxHeight = 280,
className = '',
size = 'md',
searchable = false,
searchPlaceholder = 'Search...',
}: ModernSelectProps) {
const [open, setOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const rootRef = useRef<HTMLDivElement>(null);
const selected = useMemo(
@@ -41,8 +46,26 @@ export default function ModernSelect({
[options, value],
);
const visibleOptions = useMemo(() => {
const query = searchQuery.trim().toLowerCase();
if (!searchable || !query) return options;
return options.filter((item) => {
const haystack = [
item.label,
item.description,
item.value,
]
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
.join(' ')
.toLowerCase();
return haystack.includes(query);
});
}, [options, searchQuery, searchable]);
useEffect(() => {
if (!open) return;
if (typeof document === 'undefined') return;
const handleOutsideClick = (event: MouseEvent) => {
if (!rootRef.current) return;
@@ -67,6 +90,12 @@ export default function ModernSelect({
if (disabled) setOpen(false);
}, [disabled]);
useEffect(() => {
if (!open && searchQuery) {
setSearchQuery('');
}
}, [open, searchQuery]);
const renderOptionIcon = (item: ModernSelectOption) => {
if (item.iconNode) {
return item.iconNode;
@@ -117,10 +146,22 @@ export default function ModernSelect({
</button>
<div className="modern-select-panel" style={{ maxHeight: menuMaxHeight }}>
{options.length === 0 ? (
{searchable && (
<div className="modern-select-search-shell">
<input
type="text"
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder={searchPlaceholder}
className="modern-select-search-input"
/>
</div>
)}
{visibleOptions.length === 0 ? (
<div className="modern-select-empty">{emptyLabel}</div>
) : (
options.map((item) => {
visibleOptions.map((item) => {
const active = item.value === value;
return (
<button
+33
View File
@@ -3573,6 +3573,39 @@ textarea {
pointer-events: auto;
}
.modern-select-search-shell {
position: sticky;
top: -6px;
z-index: 1;
padding: 0 0 6px;
margin: -6px -6px 6px;
background: var(--color-bg-card);
border-bottom: 1px solid color-mix(in srgb, var(--color-border) 70%, transparent);
}
.modern-select-search-input {
width: calc(100% - 12px);
margin: 6px;
min-height: 34px;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
background: var(--color-bg);
color: var(--color-text-primary);
padding: 0 10px;
font-size: 12px;
outline: none;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
.modern-select-search-input:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12);
}
.modern-select-search-input::placeholder {
color: var(--color-text-muted);
}
.modern-select-option {
width: 100%;
border: none;
+22 -21
View File
@@ -43,6 +43,8 @@ const ACCOUNT_SEGMENTS: Array<{
{ value: 'tokens', label: '账号令牌管理', tooltip: '从账号同步或手动维护,供路由实际调用', tooltipSide: 'bottom', tooltipAlign: 'end' },
];
const SITE_SELECT_SEARCH_PLACEHOLDER = '筛选站点(名称 / 平台 / URL)';
function createLoginForm() {
return { siteId: 0, username: '', password: '' };
}
@@ -172,6 +174,17 @@ export default function Accounts() {
() => sites.find((item) => item.id === tokenForm.siteId) || null,
[sites, tokenForm.siteId],
);
const siteSelectOptions = useMemo(
() => [
{ value: '0', label: '选择站点' },
...sites.map((site: any) => ({
value: String(site.id),
label: `${site.name} (${site.platform})`,
description: site.url || undefined,
})),
],
[sites],
);
const isSub2ApiSelected = (selectedTokenSite?.platform || '').toLowerCase() === 'sub2api';
const activeAddCredentialMode = activeSegment === 'apikey' ? 'apikey' : 'session';
@@ -1176,14 +1189,10 @@ export default function Accounts() {
setTokenForm((f) => ({ ...f, siteId: nextSiteId }));
setVerifyResult(null);
}}
options={[
{ value: '0', label: '选择站点' },
...sites.map((s: any) => ({
value: String(s.id),
label: `${s.name} (${s.platform})`,
})),
]}
options={siteSelectOptions}
placeholder="选择站点"
searchable
searchPlaceholder={SITE_SELECT_SEARCH_PLACEHOLDER}
/>
<input
placeholder="连接名称(可选)"
@@ -1303,14 +1312,10 @@ export default function Accounts() {
const nextSiteId = Number.parseInt(nextValue, 10) || 0;
setLoginForm((f) => ({ ...f, siteId: nextSiteId }));
}}
options={[
{ value: '0', label: '选择站点' },
...sites.map((s: any) => ({
value: String(s.id),
label: `${s.name} (${s.platform})`,
})),
]}
options={siteSelectOptions}
placeholder="选择站点"
searchable
searchPlaceholder={SITE_SELECT_SEARCH_PLACEHOLDER}
/>
<input placeholder="用户名" value={loginForm.username} onChange={(e) => setLoginForm((f) => ({ ...f, username: e.target.value }))} style={inputStyle} />
<input type="password" placeholder="密码" value={loginForm.password} onChange={(e) => setLoginForm((f) => ({ ...f, password: e.target.value }))} onKeyDown={(e) => e.key === 'Enter' && handleLoginAdd()} style={inputStyle} />
@@ -1332,14 +1337,10 @@ export default function Accounts() {
setTokenForm((f) => ({ ...f, siteId: nextSiteId, credentialMode: 'apikey' }));
setVerifyResult(null);
}}
options={[
{ value: '0', label: '选择站点' },
...sites.map((s: any) => ({
value: String(s.id),
label: `${s.name} (${s.platform})`,
})),
]}
options={siteSelectOptions}
placeholder="选择站点"
searchable
searchPlaceholder={SITE_SELECT_SEARCH_PLACEHOLDER}
/>
<input
placeholder="连接名称(可选)"
+42 -4
View File
@@ -24,11 +24,14 @@ async function flushMicrotasks() {
});
}
async function renderAccounts(initialEntry: string) {
apiMock.getAccounts.mockResolvedValue([]);
apiMock.getSites.mockResolvedValue([
async function renderAccounts(
initialEntry: string,
sites: Array<{ id: number; name: string; url?: string; platform: string; status: string }> = [
{ id: 10, name: 'Demo Site', platform: 'new-api', status: 'active' },
]);
],
) {
apiMock.getAccounts.mockResolvedValue([]);
apiMock.getSites.mockResolvedValue(sites);
apiMock.getAccountTokens.mockResolvedValue([]);
let root!: WebTestRenderer;
@@ -81,6 +84,41 @@ describe('Accounts create intent handling', () => {
}
});
it('uses searchable site selectors for manual connection creation', async () => {
const root = await renderAccounts('/accounts', [
{ id: 10, name: 'Demo Site', url: 'https://demo.example.com', platform: 'new-api', status: 'active' },
{ id: 11, name: 'Codex Workspace', url: 'https://workspace.example.com', platform: 'codex', status: 'active' },
]);
try {
const addButton = root.root.find((node) => (
node.type === 'button'
&& typeof node.props.onClick === 'function'
&& typeof node.props.className === 'string'
&& node.props.className.includes('btn btn-primary')
));
await act(async () => {
addButton.props.onClick();
});
await flushMicrotasks();
const selects = root.root.findAllByType(ModernSelect);
expect(selects[1]?.props.searchable).toBe(true);
expect(selects[1]?.props.searchPlaceholder).toBe('筛选站点(名称 / 平台 / URL)');
expect(selects[1]?.props.options).toEqual(
expect.arrayContaining([
expect.objectContaining({
value: '11',
label: 'Codex Workspace (codex)',
description: 'https://workspace.example.com',
}),
]),
);
} finally {
root?.unmount();
}
});
it('ignores create intent in the tokens segment', async () => {
const root = await renderAccounts('/accounts?segment=tokens&create=1&siteId=10');
try {