feat: refine admin UI and add EAS release workflow

This commit is contained in:
xuhongbin
2026-03-07 23:33:33 +08:00
parent 299ec1c4ec
commit 5120458712
53 changed files with 6229 additions and 396 deletions

View File

@@ -1,9 +1,17 @@
import { Tabs } from 'expo-router';
import { ActivitySquare, ChartNoAxesCombined, Users } from 'lucide-react-native';
import { ChartNoAxesCombined, Settings2, Users } from 'lucide-react-native';
import { adminConfigState } from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
export default function TabsLayout() {
const config = useSnapshot(adminConfigState);
const hasAccount = Boolean(config.baseUrl.trim());
return (
<Tabs
initialRouteName={hasAccount ? 'monitor' : 'settings'}
screenOptions={{
headerShown: false,
tabBarActiveTintColor: '#1d5f55',
@@ -19,6 +27,12 @@ export default function TabsLayout() {
>
<Tabs.Screen
name="index"
options={{
href: null,
}}
/>
<Tabs.Screen
name="monitor"
options={{
title: '概览',
tabBarIcon: ({ color, size }) => <ChartNoAxesCombined color={color} size={size} />,
@@ -32,13 +46,12 @@ export default function TabsLayout() {
}}
/>
<Tabs.Screen
name="monitor"
name="settings"
options={{
title: '运维监控',
tabBarIcon: ({ color, size }) => <ActivitySquare color={color} size={size} />,
title: '服务器',
tabBarIcon: ({ color, size }) => <Settings2 color={color} size={size} />,
}}
/>
<Tabs.Screen name="settings" options={{ href: null }} />
<Tabs.Screen name="groups" options={{ href: null }} />
<Tabs.Screen name="keys" options={{ href: null }} />
<Tabs.Screen name="accounts" options={{ href: null }} />

View File

@@ -1,17 +1,32 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { KeyRound, Search, ShieldCheck, ShieldOff } from 'lucide-react-native';
import { router } from 'expo-router';
import { useMemo, useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';
import { useCallback, useMemo, useState } from 'react';
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
import { getAccount, getAccountTodayStats, getDashboardTrend, listAccounts, setAccountSchedulable, testAccount } from '@/src/services/admin';
function getDateRange() {
const end = new Date();
const start = new Date();
start.setDate(end.getDate() - 6);
const toDate = (value: Date) => value.toISOString().slice(0, 10);
return {
start_date: toDate(start),
end_date: toDate(end),
};
}
export default function AccountsScreen() {
const [search, setSearch] = useState('');
const keyword = useMemo(() => search.trim(), [search]);
const [searchText, setSearchText] = useState('');
const keyword = useDebouncedValue(searchText.trim(), 300);
const queryClient = useQueryClient();
const range = getDateRange();
const accountsQuery = useQuery({
queryKey: ['accounts', keyword],
@@ -26,64 +41,103 @@ export default function AccountsScreen() {
const items = accountsQuery.data?.items ?? [];
const errorMessage = accountsQuery.error instanceof Error ? accountsQuery.error.message : '';
const listHeader = useMemo(
() => (
<View className="pb-4">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
defaultValue=""
onChangeText={setSearchText}
placeholder="搜索 key 名称"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
</View>
),
[]
);
const renderItem = useCallback(
({ item: account }: { item: (typeof items)[number] }) => (
<Pressable
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['account', account.id], queryFn: () => getAccount(account.id) });
void queryClient.prefetchQuery({ queryKey: ['account-today-stats', account.id], queryFn: () => getAccountTodayStats(account.id) });
void queryClient.prefetchQuery({
queryKey: ['account-trend', account.id, range.start_date, range.end_date],
queryFn: () => getDashboardTrend({ ...range, granularity: 'day', account_id: account.id }),
});
router.push(`/accounts/${account.id}`);
}}
>
<ListCard
title={account.name}
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
badge={account.status || 'unknown'}
icon={KeyRound}
>
<View className="flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
{account.schedulable ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
<Text className="text-sm text-[#7d7468]">{account.schedulable ? '可调度' : '暂停调度'}</Text>
</View>
<View className="flex-row gap-2">
<Pressable
className="rounded-full bg-[#1b1d1f] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
testAccount(account.id).catch(() => undefined);
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#f6f1e8]"></Text>
</Pressable>
<Pressable
className="rounded-full bg-[#e7dfcf] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
toggleMutation.mutate({
accountId: account.id,
schedulable: !account.schedulable,
});
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]"></Text>
</Pressable>
</View>
</View>
</ListCard>
</Pressable>
),
[queryClient, range.end_date, range.start_date, toggleMutation]
);
const emptyState = useMemo(
() => <ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />,
[errorMessage]
);
return (
<ScreenShell title="API 密钥" subtitle="管理您的 API 密钥和访问令牌">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
value={search}
onChangeText={setSearch}
placeholder="搜索 key 名称"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
{items.length === 0 ? (
<ListCard title="暂无 Key" meta={errorMessage || '连上后这里会展示 key 列表。'} icon={KeyRound} />
) : (
items.map((account) => (
<Pressable key={account.id} onPress={() => router.push(`/accounts/${account.id}`)}>
<ListCard
title={account.name}
meta={`${account.platform} · ${account.type} · 优先级 ${account.priority ?? 0}`}
badge={account.status || 'unknown'}
icon={KeyRound}
>
<View className="flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
{account.schedulable ? <ShieldCheck color="#7d7468" size={14} /> : <ShieldOff color="#7d7468" size={14} />}
<Text className="text-sm text-[#7d7468]">{account.schedulable ? '可调度' : '暂停调度'}</Text>
</View>
<View className="flex-row gap-2">
<Pressable
className="rounded-full bg-[#1b1d1f] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
testAccount(account.id).catch(() => undefined);
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#f6f1e8]"></Text>
</Pressable>
<Pressable
className="rounded-full bg-[#e7dfcf] px-4 py-2"
onPress={(event) => {
event.stopPropagation();
toggleMutation.mutate({
accountId: account.id,
schedulable: !account.schedulable,
});
}}
>
<Text className="text-xs font-semibold uppercase tracking-[1.2px] text-[#4e463e]"></Text>
</Pressable>
</View>
</View>
</ListCard>
</Pressable>
))
)}
<ScreenShell
title="API 密钥"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
variant="minimal"
scroll={false}
>
<FlatList
data={items}
renderItem={renderItem}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
ListHeaderComponent={listHeader}
ListEmptyComponent={emptyState}
ItemSeparatorComponent={() => <View className="h-4" />}
keyboardShouldPersistTaps="handled"
removeClippedSubviews
initialNumToRender={8}
maxToRenderPerBatch={8}
windowSize={5}
/>
</ScreenShell>
);
}

View File

@@ -1,15 +1,16 @@
import { useQuery } from '@tanstack/react-query';
import { FolderKanban, Layers3, Search } from 'lucide-react-native';
import { useMemo, useState } from 'react';
import { Text, TextInput, View } from 'react-native';
import { useCallback, useMemo, useState } from 'react';
import { FlatList, Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
import { listGroups } from '@/src/services/admin';
export default function GroupsScreen() {
const [search, setSearch] = useState('');
const keyword = useMemo(() => search.trim(), [search]);
const [searchText, setSearchText] = useState('');
const keyword = useDebouncedValue(searchText.trim(), 300);
const groupsQuery = useQuery({
queryKey: ['groups', keyword],
@@ -18,40 +19,68 @@ export default function GroupsScreen() {
const items = groupsQuery.data?.items ?? [];
const errorMessage = groupsQuery.error instanceof Error ? groupsQuery.error.message : '';
const listHeader = useMemo(
() => (
<View className="pb-4">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
defaultValue=""
onChangeText={setSearchText}
placeholder="搜索分组名称"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
</View>
),
[]
);
const renderItem = useCallback(
({ item: group }: { item: (typeof items)[number] }) => (
<ListCard
title={group.name}
meta={`${group.platform} · 倍率 ${group.rate_multiplier ?? 1} · ${group.subscription_type || 'standard'}`}
badge={group.status || 'active'}
icon={FolderKanban}
>
<View className="flex-row items-center gap-2">
<Layers3 color="#7d7468" size={14} />
<Text className="text-sm text-[#7d7468]">
{group.account_count ?? 0} · {group.is_exclusive ? '独占分组' : '共享分组'}
</Text>
</View>
</ListCard>
),
[]
);
const emptyState = useMemo(
() => <ListCard title="暂无分组" meta={errorMessage || '连上 Sub2API 后,这里会展示分组列表。'} icon={FolderKanban} />,
[errorMessage]
);
return (
<ScreenShell title="分组管理" subtitle="分组决定调度、价格倍率和账号归属,是后台的核心配置之一。">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
value={search}
onChangeText={setSearch}
placeholder="搜索分组名称"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
{items.length === 0 ? (
<ListCard title="暂无分组" meta={errorMessage || '连上 Sub2API 后,这里会展示分组列表。'} icon={FolderKanban} />
) : (
items.map((group) => (
<ListCard
key={group.id}
title={group.name}
meta={`${group.platform} · 倍率 ${group.rate_multiplier ?? 1} · ${group.subscription_type || 'standard'}`}
badge={group.status || 'active'}
icon={FolderKanban}
>
<View className="flex-row items-center gap-2">
<Layers3 color="#7d7468" size={14} />
<Text className="text-sm text-[#7d7468]">
{group.account_count ?? 0} · {group.is_exclusive ? '独占分组' : '共享分组'}
</Text>
</View>
</ListCard>
))
)}
<ScreenShell
title="分组管理"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
variant="minimal"
scroll={false}
>
<FlatList
data={items}
renderItem={renderItem}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
ListHeaderComponent={listHeader}
ListEmptyComponent={emptyState}
ItemSeparatorComponent={() => <View className="h-4" />}
keyboardShouldPersistTaps="handled"
removeClippedSubviews
initialNumToRender={8}
maxToRenderPerBatch={8}
windowSize={5}
/>
</ScreenShell>
);
}

View File

@@ -1,101 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { Activity, Coins, RefreshCw, Rows3, Zap } from 'lucide-react-native';
import { Pressable, Text, View } from 'react-native';
import { Redirect } from 'expo-router';
import { LineTrendChart } from '@/src/components/line-trend-chart';
import { ScreenShell } from '@/src/components/screen-shell';
import { StatCard } from '@/src/components/stat-card';
import { getAdminSettings, getDashboardStats, getDashboardTrend } from '@/src/services/admin';
function getDateRange() {
const end = new Date();
const start = new Date();
start.setDate(end.getDate() - 6);
const toDate = (value: Date) => value.toISOString().slice(0, 10);
return {
start_date: toDate(start),
end_date: toDate(end),
};
}
export default function DashboardScreen() {
const range = getDateRange();
const statsQuery = useQuery({
queryKey: ['dashboard-stats'],
queryFn: getDashboardStats,
});
const trendQuery = useQuery({
queryKey: ['dashboard-trend', range.start_date, range.end_date],
queryFn: () => getDashboardTrend({ ...range, granularity: 'day' }),
});
const settingsQuery = useQuery({
queryKey: ['admin-settings'],
queryFn: getAdminSettings,
});
const stats = statsQuery.data;
const errorMessage = statsQuery.error instanceof Error ? statsQuery.error.message : '';
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
label: item.date.slice(5),
value: item.total_tokens,
}));
return (
<ScreenShell
title={siteName}
subtitle="把最常看的管理指标和关键动作先搬到手机里,方便随时巡检。"
right={
<Pressable
className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]"
onPress={() => {
statsQuery.refetch();
trendQuery.refetch();
}}
>
<RefreshCw color="#f6f1e8" size={18} />
</Pressable>
}
>
<View className="flex-row gap-4">
<View className="flex-1">
<StatCard label="今日 Token" value={stats ? `${Math.round((stats.today_tokens ?? 0) / 1000)}k` : '--'} tone="dark" trend="up" icon={Zap} />
</View>
<View className="flex-1">
<StatCard label="今日成本" value={stats ? `$${Number(stats.today_cost ?? 0).toFixed(2)}` : '--'} icon={Coins} />
</View>
</View>
<View className="flex-row gap-4">
<View className="flex-1">
<StatCard label="输出 Token" value={stats ? `${Math.round((stats.today_output_tokens ?? 0) / 1000)}k` : '--'} trend="up" icon={Rows3} />
</View>
<View className="flex-1">
<StatCard label="吞吐 TPM" value={String(stats?.tpm ?? '--')} icon={Activity} />
</View>
</View>
{trendPoints.length > 1 ? (
<LineTrendChart
title="近 7 天 Token 趋势"
subtitle="聚焦 token 消耗,而不是大 banner"
points={trendPoints}
formatValue={(value) => `${Math.round(value / 1000)}k`}
/>
) : null}
<View className="rounded-[24px] border border-[#e6dece] bg-[#fbf8f2] p-4">
<Text className="text-sm leading-6 text-[#7d7468]">
{stats
? `今日请求 ${stats.today_requests} · 活跃用户 ${stats.active_users} · 总账号 ${stats.total_accounts}`
: errorMessage || '正在等待代理或后台连接。'}
</Text>
</View>
</ScreenShell>
);
export default function IndexScreen() {
return <Redirect href="/monitor" />;
}

View File

@@ -1,105 +1,387 @@
import { useQuery } from '@tanstack/react-query';
import { AlertTriangle, Gauge, Layers3, Wrench } from 'lucide-react-native';
import { Text, View } from 'react-native';
import { AlertTriangle, Coins, Gauge, RefreshCw, Rows3, Wrench, Zap } from 'lucide-react-native';
import { useMemo, useState } from 'react';
import { Platform, Pressable, Text, View, useWindowDimensions } from 'react-native';
import { BarChartCard } from '@/src/components/bar-chart-card';
import { DonutChartCard } from '@/src/components/donut-chart-card';
import { LineTrendChart } from '@/src/components/line-trend-chart';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { StatCard } from '@/src/components/stat-card';
import { getDashboardModels, getDashboardStats, getDashboardTrend, listAccounts } from '@/src/services/admin';
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
import { formatTokenValue } from '@/src/lib/formatters';
import { getAdminSettings, getDashboardModels, getDashboardStats, getDashboardTrend, listAccounts } from '@/src/services/admin';
import { adminConfigState } from '@/src/store/admin-config';
function getDateRange() {
const { useSnapshot } = require('valtio/react');
type RangeKey = '24h' | '7d' | '30d';
function getDateRange(rangeKey: RangeKey) {
const end = new Date();
const start = new Date();
start.setDate(end.getDate() - 6);
if (rangeKey === '24h') {
start.setHours(end.getHours() - 23, 0, 0, 0);
} else if (rangeKey === '30d') {
start.setDate(end.getDate() - 29);
} else {
start.setDate(end.getDate() - 6);
}
const toDate = (value: Date) => value.toISOString().slice(0, 10);
return {
start_date: toDate(start),
end_date: toDate(end),
granularity: rangeKey === '24h' ? ('hour' as const) : ('day' as const),
};
}
const RANGE_OPTIONS: Array<{ key: RangeKey; label: string }> = [
{ key: '24h', label: '24H' },
{ key: '7d', label: '7D' },
{ key: '30d', label: '30D' },
];
function getPointLabel(value: string, rangeKey: RangeKey) {
if (rangeKey === '24h') {
return value.slice(11, 13);
}
return value.slice(5, 10);
}
export default function MonitorScreen() {
const range = getDateRange();
useScreenInteractive('monitor_interactive');
const config = useSnapshot(adminConfigState);
const { width } = useWindowDimensions();
const contentWidth = Math.max(width - 24, 280);
const [rangeKey, setRangeKey] = useState<RangeKey>('7d');
const range = useMemo(() => getDateRange(rangeKey), [rangeKey]);
const hasAccount = Boolean(config.baseUrl.trim());
const statsQuery = useQuery({
queryKey: ['monitor-stats'],
queryFn: getDashboardStats,
enabled: hasAccount,
});
const trendQuery = useQuery({
queryKey: ['monitor-trend', range.start_date, range.end_date],
queryFn: () => getDashboardTrend({ ...range, granularity: 'day' }),
queryKey: ['monitor-trend', rangeKey, range.start_date, range.end_date, range.granularity],
queryFn: () => getDashboardTrend(range),
enabled: hasAccount,
});
const modelsQuery = useQuery({
queryKey: ['monitor-models', range.start_date, range.end_date],
queryKey: ['monitor-models', rangeKey, range.start_date, range.end_date],
queryFn: () => getDashboardModels(range),
enabled: hasAccount,
});
const settingsQuery = useQuery({
queryKey: ['admin-settings'],
queryFn: getAdminSettings,
enabled: hasAccount,
});
const accountsQuery = useQuery({
queryKey: ['monitor-accounts'],
queryFn: () => listAccounts(''),
enabled: hasAccount,
});
const stats = statsQuery.data;
const trendPoints = (trendQuery.data?.trend ?? []).map((item) => ({
label: item.date.slice(5),
value: item.total_tokens,
}));
const topModels = (modelsQuery.data?.models ?? []).slice(0, 3);
const incidentAccounts = (accountsQuery.data?.items ?? []).filter((item) => item.status === 'error' || item.error_message).slice(0, 5);
const trend = trendQuery.data?.trend ?? [];
const accounts = accountsQuery.data?.items ?? [];
const siteName = settingsQuery.data?.site_name?.trim() || '管理控制台';
const throughputPoints = useMemo(
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.total_tokens })),
[rangeKey, trend]
);
const requestPoints = useMemo(
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.requests })),
[rangeKey, trend]
);
const costPoints = useMemo(
() => trend.map((item) => ({ label: getPointLabel(item.date, rangeKey), value: item.cost })),
[rangeKey, trend]
);
const topModels = useMemo(() => (modelsQuery.data?.models ?? []).slice(0, 5), [modelsQuery.data?.models]);
const incidentAccounts = useMemo(
() => accounts.filter((item) => item.status === 'error' || item.error_message).slice(0, 5),
[accounts]
);
const totalInputTokens = useMemo(() => trend.reduce((sum, item) => sum + item.input_tokens, 0), [trend]);
const totalOutputTokens = useMemo(() => trend.reduce((sum, item) => sum + item.output_tokens, 0), [trend]);
const totalCacheReadTokens = useMemo(() => trend.reduce((sum, item) => sum + item.cache_read_tokens, 0), [trend]);
const busyAccounts = useMemo(
() => accounts.filter((item) => (item.current_concurrency ?? 0) > 0 && item.status !== 'error' && !item.error_message).length,
[accounts]
);
const pausedAccounts = useMemo(
() => accounts.filter((item) => item.schedulable === false && item.status !== 'error' && !item.error_message).length,
[accounts]
);
const errorAccounts = useMemo(
() => accounts.filter((item) => item.status === 'error' || item.error_message).length,
[accounts]
);
const healthyAccounts = Math.max(accounts.length - busyAccounts - pausedAccounts - errorAccounts, 0);
const summaryCards = [
{
label: 'Token',
value: stats ? formatTokenValue(stats.today_tokens ?? 0) : '--',
icon: Zap,
tone: 'dark' as const,
},
{
label: '成本',
value: stats ? `$${Number(stats.today_cost ?? 0).toFixed(2)}` : '--',
icon: Coins,
},
{
label: '输出',
value: stats ? formatTokenValue(stats.today_output_tokens ?? 0) : '--',
icon: Rows3,
},
{
label: '账号',
value: String(accounts.length || stats?.total_accounts || 0),
detail: `${errorAccounts} 异常 / ${pausedAccounts} 暂停`,
icon: Rows3,
},
{
label: 'TPM',
value: String(stats?.tpm ?? '--'),
icon: Gauge,
},
{
label: '健康',
value: String(healthyAccounts),
detail: `${busyAccounts} 繁忙`,
icon: AlertTriangle,
},
];
const summaryRows = [0, 3].map((index) => summaryCards.slice(index, index + 3));
const useMasonry = Platform.OS === 'web' || width >= 640;
const summaryCardWidth = Math.floor((contentWidth - 16) / 3);
const cards = [
{
key: 'throughput',
node: throughputPoints.length > 1 ? (
<LineTrendChart
title="Token 吞吐"
subtitle="整体负载曲线"
points={throughputPoints}
color="#a34d2d"
formatValue={formatTokenValue}
compact={useMasonry}
/>
) : null,
},
{
key: 'requests',
node: requestPoints.length > 1 ? (
<LineTrendChart
title="请求趋势"
subtitle="调用波峰变化"
points={requestPoints}
color="#1d5f55"
compact={useMasonry}
/>
) : null,
},
{
key: 'cost',
node: costPoints.length > 1 ? (
<LineTrendChart
title="成本趋势"
subtitle="花费变化"
points={costPoints}
color="#7651c8"
formatValue={(value) => `$${value.toFixed(2)}`}
compact={useMasonry}
/>
) : null,
},
{
key: 'token-structure',
node: (
<BarChartCard
title="Token 结构"
subtitle="输入、输出、缓存读占比"
items={[
{
label: '输入 Token',
value: totalInputTokens,
color: '#1d5f55',
hint: '输入 Token 指请求进入模型前消耗的 token通常由提示词、上下文和历史消息组成。',
},
{
label: '输出 Token',
value: totalOutputTokens,
color: '#d38b36',
hint: '输出 Token 指模型返回内容消耗的 token越长通常代表生成内容越多、成本越高。',
},
{
label: '缓存读取 Token',
value: totalCacheReadTokens,
color: '#7d7468',
hint: '缓存读取 Token 表示命中缓存后复用的 token数值越高通常意味着缓存策略更有效。',
},
]}
formatValue={formatTokenValue}
/>
),
},
{
key: 'health',
node: (
<DonutChartCard
title="账号健康"
subtitle="健康、繁忙、暂停、异常"
centerLabel="总账号"
centerValue={String(accounts.length || stats?.total_accounts || 0)}
segments={[
{ label: '健康', value: healthyAccounts, color: '#1d5f55' },
{ label: '繁忙', value: busyAccounts, color: '#d38b36' },
{ label: '暂停', value: pausedAccounts, color: '#7d7468' },
{ label: '异常', value: errorAccounts, color: '#a34d2d' },
]}
/>
),
},
{
key: 'models',
node: (
<BarChartCard
title="热点模型"
subtitle="模型负载分布"
items={topModels.map((item) => ({
label: item.model,
value: item.total_tokens,
color: '#a34d2d',
meta: `请求 ${item.requests} · 成本 $${Number(item.cost).toFixed(2)}`,
}))}
formatValue={formatTokenValue}
/>
),
},
{
key: 'incidents',
node: (
<ListCard title="排障列表" meta="优先关注状态异常或带错误信息的上游账号" icon={Wrench}>
<View className="gap-3">
{incidentAccounts.map((item) => (
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Text className="text-sm font-semibold text-[#16181a]">{item.name}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{item.platform} · {item.status || 'unknown'} · {item.schedulable ? '可调度' : '暂停调度'}</Text>
<Text className="mt-2 text-xs text-[#a34d2d]">{item.error_message || '状态异常,建议从运维视角继续排查这个上游账号'}</Text>
</View>
))}
{incidentAccounts.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
</View>
</ListCard>
),
},
].filter((item) => item.node);
const leftColumn = cards.filter((_, index) => index % 2 === 0);
const rightColumn = cards.filter((_, index) => index % 2 === 1);
return (
<ScreenShell title="运维监控" subtitle="运维监控与排障">
<View className="flex-row gap-4">
<View className="flex-1">
<StatCard label="异常账号" value={String(stats?.error_accounts ?? incidentAccounts.length ?? '--')} tone="dark" trend="down" icon={AlertTriangle} />
</View>
<View className="flex-1">
<StatCard label="实时 TPM" value={String(stats?.tpm ?? '--')} icon={Gauge} />
<ScreenShell
title="概览"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]">{siteName} </Text>}
variant="minimal"
horizontalInsetClassName="px-3"
contentGapClassName="mt-3 gap-2"
right={
<View className="flex-row items-center gap-2">
<View className="flex-row items-center rounded-full bg-[#ece3d6] p-1">
{RANGE_OPTIONS.map((item) => {
const active = item.key === rangeKey;
return (
<Pressable
key={item.key}
className={active ? 'rounded-full bg-[#1d5f55] px-3 py-1.5' : 'rounded-full bg-transparent px-3 py-1.5'}
onPress={() => setRangeKey(item.key)}
>
<Text className={active ? 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-white' : 'text-[10px] font-semibold uppercase leading-4 tracking-[1px] text-[#7d7468]'}>
{item.label}
</Text>
</Pressable>
);
})}
</View>
<Pressable
className="h-10 w-10 items-center justify-center rounded-full bg-[#2d3134]"
onPress={() => {
statsQuery.refetch();
trendQuery.refetch();
modelsQuery.refetch();
accountsQuery.refetch();
settingsQuery.refetch();
}}
>
<RefreshCw color="#f6f1e8" size={16} />
</Pressable>
</View>
}
>
<View className="gap-2">
{summaryRows.map((row, rowIndex) => (
<View key={`summary-row-${rowIndex}`} className="flex-row gap-2">
{row.map((item) => {
const Icon = item.icon;
return (
<View
key={item.label}
className={item.tone === 'dark' ? 'rounded-[18px] bg-[#1d5f55] px-2.5 py-2.5' : 'rounded-[18px] bg-[#fbf8f2] px-2.5 py-2.5'}
style={{ width: summaryCardWidth }}
>
<View className="flex-row items-center justify-between gap-2">
<Text className={item.tone === 'dark' ? 'text-[10px] uppercase tracking-[1.1px] text-[#d8efe7]' : 'text-[10px] uppercase tracking-[1.1px] text-[#8a8072]'}>
{item.label}
</Text>
<Icon color={item.tone === 'dark' ? '#d8efe7' : '#7d7468'} size={13} />
</View>
<Text className={item.tone === 'dark' ? 'mt-2 text-[17px] font-bold text-white' : 'mt-2 text-[17px] font-bold text-[#16181a]'}>
{item.value}
</Text>
{'detail' in item && item.detail ? (
<Text numberOfLines={1} className={item.tone === 'dark' ? 'mt-1 text-[10px] text-[#d8efe7]' : 'mt-1 text-[10px] text-[#8a8072]'}>
{item.detail}
</Text>
) : null}
</View>
);
})}
</View>
))}
</View>
{trendPoints.length > 1 ? (
<LineTrendChart
title="Token 监控"
subtitle="最近 7 天总 token 吞吐"
points={trendPoints}
color="#a34d2d"
formatValue={(value) => `${Math.round(value / 1000)}k`}
/>
) : null}
<ListCard title="热点模型" meta="按请求与 token 用量排序" icon={Layers3}>
<View className="gap-3">
{topModels.map((item) => (
<View key={item.model} className="flex-row items-center justify-between border-b border-[#eee6d7] pb-3 last:border-b-0 last:pb-0">
<View className="flex-1 pr-4">
<Text className="text-sm font-semibold text-[#16181a]">{item.model}</Text>
<Text className="mt-1 text-xs text-[#7d7468]"> {item.requests} · Token {Math.round(item.total_tokens / 1000)}k</Text>
</View>
<Text className="text-sm font-semibold text-[#4e463e]">${Number(item.cost).toFixed(2)}</Text>
</View>
))}
{topModels.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
{useMasonry ? (
<View className="flex-row items-start gap-3">
<View className="flex-1 gap-3">
{leftColumn.map((item) => (
<View key={item.key}>{item.node}</View>
))}
</View>
<View className="flex-1 gap-3">
{rightColumn.map((item) => (
<View key={item.key}>{item.node}</View>
))}
</View>
</View>
</ListCard>
<ListCard title="排障列表" meta="优先关注状态异常或带错误信息的上游账号" icon={Wrench}>
<View className="gap-3">
{incidentAccounts.map((item) => (
<View key={item.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Text className="text-sm font-semibold text-[#16181a]">{item.name}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{item.platform} · {item.status || 'unknown'} · {item.schedulable ? '可调度' : '暂停调度'}</Text>
<Text className="mt-2 text-xs text-[#a34d2d]">{item.error_message || '状态异常,建议从运维视角继续排查这个上游账号'}</Text>
</View>
))}
{incidentAccounts.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
</View>
</ListCard>
) : (
cards.map((item) => <View key={item.key}>{item.node}</View>)
)}
</ScreenShell>
);
}

197
app/(tabs)/settings.tsx Normal file
View File

@@ -0,0 +1,197 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { Controller, useForm } from 'react-hook-form';
import { Pressable, Text, TextInput, View } from 'react-native';
import { z } from 'zod';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
import { queryClient } from '@/src/lib/query-client';
import {
adminConfigState,
logoutAdminAccount,
removeAdminAccount,
saveAdminConfig,
setAdminAccountEnabled,
switchAdminAccount,
type AdminAccountProfile,
} from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
const schema = z
.object({
baseUrl: z.string().min(1, '请输入 Host'),
adminApiKey: z.string(),
})
.superRefine((values, ctx) => {
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
ctx.addIssue({
code: 'custom',
path: ['adminApiKey'],
message: '请输入 Admin Token',
});
}
});
type FormValues = z.infer<typeof schema>;
export default function SettingsScreen() {
const config = useSnapshot(adminConfigState);
const { control, handleSubmit, formState, reset } = useForm<FormValues>({
resolver: zodResolver(schema),
values: {
baseUrl: config.baseUrl,
adminApiKey: config.adminApiKey,
},
});
async function handleSwitch(account: AdminAccountProfile) {
await switchAdminAccount(account.id);
queryClient.clear();
reset({ baseUrl: account.baseUrl, adminApiKey: account.adminApiKey });
}
async function handleDelete(account: AdminAccountProfile) {
await removeAdminAccount(account.id);
queryClient.clear();
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
}
async function handleLogout() {
await logoutAdminAccount();
queryClient.clear();
reset({ baseUrl: '', adminApiKey: '' });
}
async function handleToggleEnabled(account: AdminAccountProfile) {
await setAdminAccountEnabled(account.id, account.enabled === false);
queryClient.clear();
reset({ baseUrl: adminConfigState.baseUrl, adminApiKey: adminConfigState.adminApiKey });
}
return (
<ScreenShell
title="服务器"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"> Sub2API </Text>}
variant="minimal"
>
<ListCard title="当前连接" meta={config.baseUrl || '未连接'}>
<View className="gap-3">
<Text className="text-sm text-[#6f665c]">
{config.baseUrl || '当前没有激活服务器,可在下方直接新增或切换。'}
</Text>
<View className="flex-row gap-3">
<Pressable className="flex-1 rounded-[18px] bg-[#1d5f55] px-4 py-3" onPress={handleSubmit(async (values) => {
await saveAdminConfig(values);
queryClient.clear();
})}>
<Text className="text-center text-sm font-semibold text-white"></Text>
</Pressable>
<Pressable className="flex-1 rounded-[18px] bg-[#e7dfcf] px-4 py-3" onPress={handleLogout}>
<Text className="text-center text-sm font-semibold text-[#4e463e]">退</Text>
</Pressable>
</View>
</View>
</ListCard>
<ListCard title="连接配置" meta="Host 与 Admin Token 合并配置">
<View className="gap-3">
<View>
<Text className="mb-2 text-[11px] text-[#7d7468]">Host</Text>
<Controller
control={control}
name="baseUrl"
render={({ field: { onChange, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
placeholder="http://localhost:8787"
placeholderTextColor="#9b9081"
autoCapitalize="none"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
/>
)}
/>
</View>
<View>
<Text className="mb-2 text-[11px] text-[#7d7468]">Admin Token</Text>
<Controller
control={control}
name="adminApiKey"
render={({ field: { onChange, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
placeholder="admin-xxxxxxxx"
placeholderTextColor="#9b9081"
autoCapitalize="none"
className="rounded-[18px] bg-[#f1ece2] px-4 py-4 text-base text-[#16181a]"
/>
)}
/>
</View>
<Text className="text-[11px] text-[#8a8072]">使 token</Text>
{(formState.errors.baseUrl || formState.errors.adminApiKey) ? (
<View className="rounded-[16px] bg-[#fbf1eb] px-4 py-3">
<Text className="text-sm text-[#c25d35]">{formState.errors.baseUrl?.message || formState.errors.adminApiKey?.message}</Text>
</View>
) : null}
</View>
</ListCard>
<ListCard title="已保存服务器" meta={`${config.accounts.length}`}>
<View className="gap-3">
{config.accounts.map((account: AdminAccountProfile) => {
const active = account.id === config.activeAccountId;
const enabled = account.enabled !== false;
return (
<View key={account.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1">
<Text className="text-sm font-semibold text-[#16181a]">{account.label}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{account.baseUrl}</Text>
</View>
{active ? (
<View className="rounded-full bg-[#1d5f55] px-3 py-1">
<Text className="text-[10px] font-semibold uppercase tracking-[1px] text-white"></Text>
</View>
) : !enabled ? (
<View className="rounded-full bg-[#cfc5b7] px-3 py-1">
<Text className="text-[10px] font-semibold uppercase tracking-[1px] text-[#6f665c]"></Text>
</View>
) : null}
</View>
<View className="mt-3 flex-row gap-3">
<Pressable
className={active ? 'flex-1 rounded-[16px] bg-[#d7eee4] px-3 py-2.5' : !enabled ? 'flex-1 rounded-[16px] bg-[#d8d1c4] px-3 py-2.5' : 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-2.5'}
onPress={() => handleSwitch(account)}
disabled={!enabled}
>
<Text className={active ? 'text-center text-xs font-semibold text-[#1d5f55]' : !enabled ? 'text-center text-xs font-semibold text-[#7d7468]' : 'text-center text-xs font-semibold text-white'}>
{active ? '使用中' : '启用连接'}
</Text>
</Pressable>
<Pressable className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5" onPress={() => handleToggleEnabled(account)}>
<Text className="text-center text-xs font-semibold text-[#4e463e]">{enabled ? '禁用' : '启用'}</Text>
</Pressable>
<Pressable className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5" onPress={() => handleDelete(account)}>
<Text className="text-center text-xs font-semibold text-[#7a3d31]"></Text>
</Pressable>
</View>
</View>
);
})}
{config.accounts.length === 0 ? <Text className="text-sm text-[#7d7468]"></Text> : null}
</View>
</ListCard>
</ScreenShell>
);
}

View File

@@ -1,57 +1,264 @@
import { useQuery } from '@tanstack/react-query';
import { Activity, Search, UserRound } from 'lucide-react-native';
import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import * as Clipboard from 'expo-clipboard';
import { Copy, Search, UserRound } from 'lucide-react-native';
import { router } from 'expo-router';
import { useMemo, useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';
import { useCallback, useMemo, useState } from 'react';
import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { listUsers } from '@/src/services/admin';
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
import { getUser, getUserUsage, listUserApiKeys, listUsers } from '@/src/services/admin';
import { adminConfigState } from '@/src/store/admin-config';
import type { AdminApiKey, AdminUser, UserUsageSummary } from '@/src/types/admin';
const { useSnapshot } = require('valtio/react');
type UserSupplement = {
usage?: UserUsageSummary;
apiKeys: AdminApiKey[];
};
function getUserTitle(user: AdminUser) {
return user.username?.trim() || user.email;
}
function getUserSortValue(user: AdminUser) {
const raw = user.updated_at || user.created_at || '';
const value = raw ? new Date(raw).getTime() : 0;
return Number.isNaN(value) ? 0 : value;
}
function formatQuotaValue(value: number) {
return `$${value.toFixed(2)}`;
}
export default function UsersScreen() {
const [search, setSearch] = useState('');
const keyword = useMemo(() => search.trim(), [search]);
useScreenInteractive('users_interactive');
const config = useSnapshot(adminConfigState);
const [searchText, setSearchText] = useState('');
const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
const keyword = useDebouncedValue(searchText.trim(), 300);
const queryClient = useQueryClient();
const hasAccount = Boolean(config.baseUrl.trim());
const usersQuery = useQuery({
queryKey: ['users', keyword],
queryFn: () => listUsers(keyword),
enabled: hasAccount,
});
const items = usersQuery.data?.items ?? [];
const userDetailQueries = useQueries({
queries: items.map((user) => ({
queryKey: ['user-list-supplement', user.id],
queryFn: async () => {
const [usage, apiKeysData] = await Promise.all([getUserUsage(user.id), listUserApiKeys(user.id)]);
return {
usage,
apiKeys: apiKeysData.items ?? [],
} satisfies UserSupplement;
},
enabled: hasAccount,
staleTime: 60_000,
})),
});
const errorMessage = usersQuery.error instanceof Error ? usersQuery.error.message : '';
const supplementsByUserId = useMemo(
() =>
items.reduce<Record<number, UserSupplement | undefined>>((result, user, index) => {
result[user.id] = userDetailQueries[index]?.data;
return result;
}, {}),
[items, userDetailQueries]
);
const sortedItems = useMemo(
() =>
[...items].sort((left, right) => {
const delta = getUserSortValue(right) - getUserSortValue(left);
return sortOrder === 'desc' ? delta : -delta;
}),
[items, sortOrder]
);
async function copyKey(keyId: number, value: string) {
await Clipboard.setStringAsync(value);
setCopiedKeyId(keyId);
setTimeout(() => setCopiedKeyId((current) => (current === keyId ? null : current)), 1600);
}
const renderItem = useCallback(
({ item: user }: { item: (typeof sortedItems)[number] }) => {
const keyItems = (supplementsByUserId[user.id]?.apiKeys ?? []).slice(0, 3);
return (
<Pressable
className="px-1"
onPress={() => {
void queryClient.prefetchQuery({ queryKey: ['user', user.id], queryFn: () => getUser(user.id) });
void queryClient.prefetchQuery({ queryKey: ['user-usage', user.id], queryFn: () => getUserUsage(user.id) });
void queryClient.prefetchQuery({ queryKey: ['user-api-keys', user.id], queryFn: () => listUserApiKeys(user.id) });
router.push(`/users/${user.id}`);
}}
>
<ListCard title={getUserTitle(user)} meta={user.email} badge={user.status || 'active'} icon={UserRound}>
<View className="gap-2">
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2.5">
<View className="flex-row items-center justify-between">
<Text className="text-[11px] text-[#6f665c]"></Text>
<Text className="text-sm font-semibold text-[#16181a]">${Number(user.balance ?? 0).toFixed(2)}</Text>
</View>
</View>
<View className="rounded-[14px] bg-[#f7f2e9] px-3 py-2">
<View className="mb-1.5 flex-row items-center justify-between">
<Text className="text-[11px] text-[#6f665c]">Keys</Text>
<Text className="text-[10px] text-[#8a8072]">{keyItems.length} </Text>
</View>
<View className="gap-0">
{keyItems.map((apiKey, index) => (
<View
key={apiKey.id}
style={{ paddingVertical: 4 }}
>
{(() => {
const quota = Number(apiKey.quota ?? 0);
const used = Number(apiKey.quota_used ?? 0);
const isUnlimited = quota <= 0;
const progressWidth = isUnlimited ? '16%' : (`${Math.max(Math.min((used / quota) * 100, 100), 6)}%` as `${number}%`);
return (
<>
<View className="flex-row items-center gap-2">
<Text numberOfLines={1} className="flex-1 text-[11px] font-semibold text-[#16181a]">
{apiKey.name}
</Text>
<Text numberOfLines={1} className="text-[10px] text-[#6f665c]">
{isUnlimited ? `${formatQuotaValue(used)} / 无限` : `${formatQuotaValue(used)} / ${formatQuotaValue(quota)}`}
</Text>
<Pressable
className="rounded-full bg-[#e7dfcf] p-1.5"
onPress={(event) => {
event.stopPropagation();
void copyKey(apiKey.id, apiKey.key);
}}
>
<Copy color="#4e463e" size={11} />
</Pressable>
</View>
<View className="h-1.5 overflow-hidden rounded-full bg-[#ddd2c0]" style={{ marginTop: 3 }}>
<View
className={
isUnlimited
? 'h-full rounded-full bg-[#7d7468]'
: used / Math.max(quota, 1) >= 0.85
? 'h-full rounded-full bg-[#c25d35]'
: used / Math.max(quota, 1) >= 0.6
? 'h-full rounded-full bg-[#d38b36]'
: 'h-full rounded-full bg-[#1d5f55]'
}
style={{ width: progressWidth }}
/>
</View>
{copiedKeyId === apiKey.id ? <Text className="text-[10px] text-[#1d5f55]" style={{ paddingTop: 3 }}></Text> : null}
</>
);
})()}
</View>
))}
{keyItems.length === 0 ? (
<View className="py-[10px]">
<Text className="text-[11px] text-[#6f665c]"> token </Text>
</View>
) : null}
</View>
</View>
</View>
</ListCard>
</Pressable>
);
},
[copiedKeyId, queryClient, sortedItems, supplementsByUserId]
);
const emptyState = useMemo(
() => (
<ListCard
title={hasAccount ? '暂无匹配用户' : '未连接服务器'}
meta={hasAccount ? errorMessage || '调整搜索词后再试。' : '请先前往服务器标签连接 Sub2API。'}
icon={UserRound}
/>
),
[errorMessage, hasAccount]
);
return (
<ScreenShell title="用户管理" subtitle="搜索用户、查看详情,并在详情页里做余额调整。">
<View className="flex-row items-center rounded-[24px] bg-[#fbf8f2] px-4 py-3">
<Search color="#7d7468" size={18} />
<TextInput
value={search}
onChangeText={setSearch}
placeholder="搜索邮箱或用户名"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
{items.length === 0 ? (
<ListCard title="暂无数据" meta={errorMessage || '配置好后台连接后,这里会展示管理员用户列表。'} icon={UserRound} />
) : (
items.map((user) => (
<Pressable key={user.id} onPress={() => router.push(`/users/${user.id}`)}>
<ListCard
title={user.username || user.email}
meta={`${user.email} · 余额 ${Number(user.balance ?? 0).toFixed(2)} · 并发 ${user.concurrency ?? 0}`}
badge={user.status || 'active'}
icon={UserRound}
<ScreenShell
title="用户管理"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"> {sortedItems.length}</Text>}
variant="minimal"
scroll={false}
bottomInsetClassName="pb-12"
>
<View className="flex-1">
<View className="rounded-[16px] bg-[#fbf8f2] px-2.5 py-2.5">
<View className="flex-row items-center gap-2">
<View className="flex-1 flex-row items-center rounded-[14px] bg-[#f1ece2] px-3 py-2.5">
<Search color="#7d7468" size={18} />
<TextInput
value={searchText}
onChangeText={setSearchText}
placeholder="搜索邮箱或用户名"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-base text-[#16181a]"
/>
</View>
<Pressable
className={sortOrder === 'desc' ? 'rounded-[14px] bg-[#1d5f55] px-3 py-2.5' : 'rounded-[14px] bg-[#e7dfcf] px-3 py-2.5'}
onPress={() => setSortOrder('desc')}
>
<View className="flex-row items-center gap-2">
<Activity color="#7d7468" size={14} />
<Text className="text-sm text-[#7d7468]"> {user.current_concurrency ?? 0}</Text>
</View>
</ListCard>
</Pressable>
))
)}
<Text className={sortOrder === 'desc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
</Text>
</Pressable>
<Pressable
className={sortOrder === 'asc' ? 'rounded-[14px] bg-[#1d5f55] px-3 py-2.5' : 'rounded-[14px] bg-[#e7dfcf] px-3 py-2.5'}
onPress={() => setSortOrder('asc')}
>
<Text className={sortOrder === 'asc' ? 'text-[11px] font-semibold text-white' : 'text-[11px] font-semibold text-[#4e463e]'}>
</Text>
</Pressable>
</View>
</View>
<View className="mt-2.5 flex-1">
<FlatList
data={sortedItems}
renderItem={renderItem}
keyExtractor={(item) => `${item.id}`}
showsVerticalScrollIndicator={false}
ListHeaderComponent={() => <View className="h-2" />}
ListEmptyComponent={emptyState}
ListFooterComponent={() => <View className="h-4" />}
ItemSeparatorComponent={() => <View className="h-3" />}
keyboardShouldPersistTaps="handled"
removeClippedSubviews
initialNumToRender={8}
maxToRenderPerBatch={8}
windowSize={5}
/>
</View>
</View>
</ScreenShell>
);
}

View File

@@ -7,19 +7,20 @@ import { ActivityIndicator, View } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { queryClient } from '@/src/lib/query-client';
import { markPerformance } from '@/src/lib/performance';
import { adminConfigState, hydrateAdminConfig } from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
export default function RootLayout() {
const config = useSnapshot(adminConfigState);
useEffect(() => {
hydrateAdminConfig().catch(() => undefined);
hydrateAdminConfig()
.then(() => markPerformance('config_hydrated'))
.catch(() => undefined);
}, []);
const config = useSnapshot(adminConfigState);
const isReady = config.hydrated;
const isAuthenticated = Boolean(config.baseUrl.trim() && config.adminApiKey.trim());
return (
<GestureHandlerRootView style={{ flex: 1 }}>
@@ -30,8 +31,9 @@ export default function RootLayout() {
</View>
) : (
<Stack screenOptions={{ headerShown: false }}>
{isAuthenticated ? <Stack.Screen name="(tabs)" /> : <Stack.Screen name="login" />}
<Stack.Screen name="users/[id]" />
<Stack.Screen name="(tabs)" />
<Stack.Screen name="login" />
<Stack.Screen name="users/[id]" options={{ animation: 'slide_from_right', presentation: 'card' }} />
<Stack.Screen name="accounts/[id]" options={{ presentation: 'card' }} />
</Stack>
)}

View File

@@ -6,6 +6,7 @@ import { Pressable, Text, View } from 'react-native';
import { DetailRow } from '@/src/components/detail-row';
import { LineTrendChart } from '@/src/components/line-trend-chart';
import { ListCard } from '@/src/components/list-card';
import { formatDisplayTime, formatTokenValue } from '@/src/lib/formatters';
import { ScreenShell } from '@/src/components/screen-shell';
import { getAccount, getAccountTodayStats, getDashboardTrend, refreshAccount, setAccountSchedulable, testAccount } from '@/src/services/admin';
@@ -81,11 +82,11 @@ export default function AccountDetailScreen() {
<DetailRow label="优先级" value={`${account?.priority ?? 0}`} />
<DetailRow label="并发" value={`${account?.concurrency ?? 0}`} />
<DetailRow label="当前并发" value={`${account?.current_concurrency ?? 0}`} />
<DetailRow label="最后使用" value={account?.last_used_at || '--'} />
<DetailRow label="最后使用" value={formatDisplayTime(account?.last_used_at)} />
</ListCard>
<ListCard title="今日统计" meta="真实数据来自 /accounts/:id/today-stats" icon={ShieldCheck}>
<DetailRow label="Token" value={`${todayStats?.tokens ?? 0}`} />
<DetailRow label="Token" value={formatTokenValue(todayStats?.tokens ?? 0)} />
<DetailRow label="请求数" value={`${todayStats?.requests ?? 0}`} />
<DetailRow label="成本" value={`$${Number(todayStats?.cost ?? 0).toFixed(4)}`} />
</ListCard>
@@ -96,7 +97,7 @@ export default function AccountDetailScreen() {
subtitle="按账号过滤后的真实 token 趋势"
points={trendPoints}
color="#c96d43"
formatValue={(value) => `${Math.round(value / 1000)}k`}
formatValue={formatTokenValue}
/>
) : null}

View File

@@ -1,3 +1,4 @@
import { router } from 'expo-router';
import { zodResolver } from '@hookform/resolvers/zod';
import { Globe, KeyRound } from 'lucide-react-native';
import { Controller, useForm } from 'react-hook-form';
@@ -6,18 +7,32 @@ import { z } from 'zod';
import { ListCard } from '@/src/components/list-card';
import { ScreenShell } from '@/src/components/screen-shell';
import { adminConfigState, saveAdminConfig } from '@/src/store/admin-config';
import { useScreenInteractive } from '@/src/hooks/use-screen-interactive';
import { isLocalProxyBaseUrl } from '@/src/lib/admin-fetch';
import { queryClient } from '@/src/lib/query-client';
import { adminConfigState, removeAdminAccount, saveAdminConfig, setAdminAccountEnabled, switchAdminAccount, type AdminAccountProfile } from '@/src/store/admin-config';
const { useSnapshot } = require('valtio/react');
const schema = z.object({
baseUrl: z.string().min(1, '请输入 Host'),
adminApiKey: z.string().min(1, '请输入 Admin Token'),
});
const schema = z
.object({
baseUrl: z.string().min(1, '请输入 Host'),
adminApiKey: z.string(),
})
.superRefine((values, ctx) => {
if (!isLocalProxyBaseUrl(values.baseUrl.trim()) && !values.adminApiKey.trim()) {
ctx.addIssue({
code: 'custom',
path: ['adminApiKey'],
message: '请输入 Admin Token',
});
}
});
type FormValues = z.infer<typeof schema>;
export default function LoginScreen() {
useScreenInteractive('login_interactive');
const config = useSnapshot(adminConfigState);
const { control, handleSubmit, formState } = useForm<FormValues>({
resolver: zodResolver(schema),
@@ -28,7 +43,61 @@ export default function LoginScreen() {
});
return (
<ScreenShell title="登录" subtitle="输入 host 和 adminToken 后开始管理。">
<ScreenShell
title="登录"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"> Sub2API </Text>}
variant="minimal"
>
{config.accounts.length > 0 ? (
<ListCard title="已保存账号" meta="可直接切换到其他 Sub2API 账号">
<View className="gap-3">
{config.accounts.map((account: AdminAccountProfile) => {
const active = account.id === config.activeAccountId;
const enabled = account.enabled !== false;
return (
<View key={account.id} className="rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Text className="text-sm font-semibold text-[#16181a]">{account.label}</Text>
<Text className="mt-1 text-xs text-[#7d7468]">{account.baseUrl}</Text>
<View className="mt-3 flex-row gap-3">
<Pressable
className={active ? 'flex-1 rounded-[16px] bg-[#d7eee4] px-3 py-2.5' : !enabled ? 'flex-1 rounded-[16px] bg-[#d8d1c4] px-3 py-2.5' : 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-2.5'}
onPress={async () => {
await switchAdminAccount(account.id);
queryClient.clear();
router.replace('/monitor');
}}
disabled={!enabled}
>
<Text className={active ? 'text-center text-xs font-semibold text-[#1d5f55]' : !enabled ? 'text-center text-xs font-semibold text-[#7d7468]' : 'text-center text-xs font-semibold text-white'}>
{active ? '使用中' : '切换账号'}
</Text>
</Pressable>
<Pressable
className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5"
onPress={async () => {
await setAdminAccountEnabled(account.id, account.enabled === false);
}}
>
<Text className="text-center text-xs font-semibold text-[#4e463e]">{enabled ? '禁用' : '启用'}</Text>
</Pressable>
<Pressable
className="rounded-[16px] bg-[#e7dfcf] px-4 py-2.5"
onPress={async () => {
await removeAdminAccount(account.id);
}}
>
<Text className="text-center text-xs font-semibold text-[#7a3d31]"></Text>
</Pressable>
</View>
</View>
);
})}
</View>
</ListCard>
) : null}
<ListCard title="Host" meta="当前站点或管理代理地址" icon={Globe}>
<Controller
control={control}
@@ -46,7 +115,7 @@ export default function LoginScreen() {
/>
</ListCard>
<ListCard title="Admin Token" meta="管理员 token" icon={KeyRound}>
<ListCard title="Admin Token" meta="直连上游时必填;使用本地代理可留空" icon={KeyRound}>
<Controller
control={control}
name="adminApiKey"
@@ -73,6 +142,8 @@ export default function LoginScreen() {
className="rounded-[20px] bg-[#1d5f55] px-4 py-4"
onPress={handleSubmit(async (values) => {
await saveAdminConfig(values);
queryClient.clear();
router.replace('/monitor');
})}
>
<Text className="text-center text-sm font-semibold tracking-[1.2px] text-white">

View File

@@ -1,16 +1,18 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { zodResolver } from '@hookform/resolvers/zod';
import * as Clipboard from 'expo-clipboard';
import { ArrowLeftRight, ChevronLeft, Copy, Eye, EyeOff, KeyRound, Search, Wallet } from 'lucide-react-native';
import { ArrowLeftRight, ChevronLeft, Copy, KeyRound, Search, Wallet } from 'lucide-react-native';
import { router, useLocalSearchParams } from 'expo-router';
import { useState } from 'react';
import { useMemo, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { Pressable, Text, TextInput, View } from 'react-native';
import { z } from 'zod';
import { DetailRow } from '@/src/components/detail-row';
import { ListCard } from '@/src/components/list-card';
import { formatDisplayTime } from '@/src/lib/formatters';
import { ScreenShell } from '@/src/components/screen-shell';
import { useDebouncedValue } from '@/src/hooks/use-debounced-value';
import { getUser, getUserUsage, listUserApiKeys, updateUserBalance } from '@/src/services/admin';
import type { BalanceOperation } from '@/src/types/admin';
@@ -26,10 +28,10 @@ export default function UserDetailScreen() {
const userId = Number(id);
const queryClient = useQueryClient();
const [operation, setOperation] = useState<BalanceOperation>('add');
const [keySearch, setKeySearch] = useState('');
const [keySearchText, setKeySearchText] = useState('');
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
const [visibleKeys, setVisibleKeys] = useState<Record<number, boolean>>({});
const [copiedKeyId, setCopiedKeyId] = useState<number | null>(null);
const keySearch = useDebouncedValue(keySearchText.trim().toLowerCase(), 250);
const { control, handleSubmit, reset, formState } = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
@@ -73,19 +75,22 @@ export default function UserDetailScreen() {
const user = userQuery.data;
const usage = usageQuery.data;
const apiKeys = apiKeysQuery.data?.items ?? [];
const filteredApiKeys = apiKeys.filter((item) => {
const matchesStatus = statusFilter === 'all' ? true : item.status === statusFilter;
const keyword = keySearch.trim().toLowerCase();
const matchesSearch = !keyword
? true
: [item.name, item.key, item.group?.name]
.filter(Boolean)
.join(' ')
.toLowerCase()
.includes(keyword);
const filteredApiKeys = useMemo(
() =>
apiKeys.filter((item) => {
const matchesStatus = statusFilter === 'all' ? true : item.status === statusFilter;
const matchesSearch = !keySearch
? true
: [item.name, item.key, item.group?.name]
.filter(Boolean)
.join(' ')
.toLowerCase()
.includes(keySearch);
return matchesStatus && matchesSearch;
});
return matchesStatus && matchesSearch;
}),
[apiKeys, keySearch, statusFilter]
);
function maskKey(value: string) {
if (!value || value.length < 16) {
@@ -104,7 +109,9 @@ export default function UserDetailScreen() {
return (
<ScreenShell
title={user?.username || user?.email || '用户详情'}
subtitle="核心看余额和 token 用量,其他内容尽量保持轻量。"
subtitle=""
titleAside={<Text className="text-[11px] text-[#a2988a]"></Text>}
variant="minimal"
right={
<Pressable className="h-11 w-11 items-center justify-center rounded-full bg-[#2d3134]" onPress={() => router.back()}>
<ChevronLeft color="#f6f1e8" size={18} />
@@ -115,7 +122,7 @@ export default function UserDetailScreen() {
<DetailRow label="角色" value={user?.role || '--'} />
<DetailRow label="余额" value={Number(user?.balance ?? 0).toFixed(2)} />
<DetailRow label="并发" value={`${user?.concurrency ?? 0}`} />
<DetailRow label="更新时间" value={user?.updated_at || '--'} />
<DetailRow label="更新时间" value={formatDisplayTime(user?.updated_at)} />
</ListCard>
<ListCard title="月度用量" meta="真实数据来自 /users/:id/usage" icon={ArrowLeftRight}>
@@ -129,8 +136,8 @@ export default function UserDetailScreen() {
<View className="flex-row items-center rounded-[18px] bg-[#f1ece2] px-4 py-3">
<Search color="#7d7468" size={16} />
<TextInput
value={keySearch}
onChangeText={setKeySearch}
defaultValue=""
onChangeText={setKeySearchText}
placeholder="搜索 key 名称或分组"
placeholderTextColor="#9b9081"
className="ml-3 flex-1 text-sm text-[#16181a]"
@@ -156,19 +163,16 @@ export default function UserDetailScreen() {
<Text className="text-xs uppercase tracking-[1.2px] text-[#7d7468]">{item.status}</Text>
</View>
<View className="mt-2 flex-row items-center gap-2">
<Text className="flex-1 text-xs text-[#7d7468]">{visibleKeys[item.id] ? item.key : maskKey(item.key)}</Text>
<Text className="flex-1 text-xs text-[#7d7468]">{maskKey(item.key)}</Text>
<Pressable
className="rounded-full bg-[#e7dfcf] p-2"
onPress={() => setVisibleKeys((current) => ({ ...current, [item.id]: !current[item.id] }))}
onPress={() => copyKey(item.id, item.key)}
>
{visibleKeys[item.id] ? <EyeOff color="#4e463e" size={14} /> : <Eye color="#4e463e" size={14} />}
</Pressable>
<Pressable className="rounded-full bg-[#1b1d1f] p-2" onPress={() => copyKey(item.id, item.key)}>
<Copy color="#f6f1e8" size={14} />
<Copy color="#4e463e" size={14} />
</Pressable>
</View>
<Text className="mt-2 text-xs text-[#7d7468]">
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${item.last_used_at || '--'}`}
{copiedKeyId === item.id ? '已复制到剪贴板' : `最近使用 ${formatDisplayTime(item.last_used_at)}`}
</Text>
<Text className="mt-2 text-xs text-[#7d7468]">
${Number(item.quota_used ?? 0).toFixed(2)} / {item.quota ? `$${Number(item.quota).toFixed(2)}` : '无限制'}
@@ -202,14 +206,14 @@ export default function UserDetailScreen() {
{(['add', 'subtract', 'set'] as BalanceOperation[]).map((item) => (
<Pressable
key={item}
className={operation === item ? 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-3' : 'flex-1 rounded-[16px] bg-[#e7dfcf] px-3 py-3'}
onPress={() => setOperation(item)}
>
<Text className={operation === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
{item === 'add' ? '增加' : item === 'subtract' ? '扣减' : '设为'}
</Text>
</Pressable>
))}
className={operation === item ? 'flex-1 rounded-[16px] bg-[#1d5f55] px-3 py-3' : 'flex-1 rounded-[16px] bg-[#e7dfcf] px-3 py-3'}
onPress={() => setOperation(item)}
>
<Text className={operation === item ? 'text-center text-sm font-semibold text-white' : 'text-center text-sm font-semibold text-[#4e463e]'}>
{item === 'add' ? '增加' : item === 'subtract' ? '扣减' : '设为'}
</Text>
</Pressable>
))}
</View>
<Controller
control={control}