From 87f870a22b76a00837e8ead223fddb1c50d97fae Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 17 Nov 2026 09:37:41 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(web):=20=E5=9C=A8=20VM=20=E9=A1=B5?= =?UTF-8?q?=E9=9D=A2=E7=BB=9F=E4=B8=80=E7=AE=A1=E7=90=86=20Gemini=20?= =?UTF-8?q?=E5=AE=BF=E4=B8=BB=E8=B4=A6=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/components/platform-chip.tsx | 6 +- .../import/gemini-environments.test.tsx | 13 +- .../features/import/gemini-environments.tsx | 129 ++++++++++-------- web/src/features/import/index.tsx | 18 ++- web/src/features/proxies/proxy-chip.tsx | 20 ++- web/src/features/vm/fleet-pulse.tsx | 1 + web/src/features/vm/gemini-slot.ts | 40 ++++++ web/src/features/vm/list-page.tsx | 29 +++- web/src/features/vm/vm-account-identity.tsx | 17 ++- web/src/features/vm/vm-action-menu.tsx | 14 ++ web/src/features/vm/vm-actions-provider.tsx | 30 +++- web/src/features/vm/vm-list-table.test.tsx | 53 +++++++ web/src/features/vm/vm-list-table.tsx | 47 +++++-- web/src/features/vm/vm-rack-blade.tsx | 33 ++++- web/src/features/vm/vm-rack-unit.tsx | 7 +- web/src/features/vm/vm-table.tsx | 46 ++++--- web/src/routes/_authenticated/import.tsx | 3 + web/src/types/panel-vm.ts | 2 + 18 files changed, 395 insertions(+), 113 deletions(-) create mode 100644 web/src/features/vm/gemini-slot.ts diff --git a/web/src/components/platform-chip.tsx b/web/src/components/platform-chip.tsx index 14f96b245..31c25dd55 100644 --- a/web/src/components/platform-chip.tsx +++ b/web/src/components/platform-chip.tsx @@ -20,10 +20,10 @@ export function PlatformChip({ className, }: { vm?: Vm - kind?: VmKind + kind?: VmKind | 'gemini' className?: string }) { - const resolved = kind ?? (vm ? vmKindOf(vm) : 'claude') + const resolved = kind ?? (vm?.gemini ? 'gemini' : vmKindOf(vm)) const gpt = resolved === 'codex' return ( - {platformLabelOf(resolved)} + {resolved === 'gemini' ? 'Gemini' : platformLabelOf(resolved)} ) } diff --git a/web/src/features/import/gemini-environments.test.tsx b/web/src/features/import/gemini-environments.test.tsx index a5e1471d4..64cac74d4 100644 --- a/web/src/features/import/gemini-environments.test.tsx +++ b/web/src/features/import/gemini-environments.test.tsx @@ -64,7 +64,9 @@ function showGemini(available: boolean, view: 'import' | 'vm' = 'import') { }) return renderToStaticMarkup( - + ) } @@ -75,7 +77,7 @@ test('Gemini is unavailable without the separate host service', () => { expect(html).not.toContain('创建 Gemini 环境') }) -test('Gemini import displays only platform SOCKS5 and separates authorization from paid readiness', () => { +test('Gemini import only displays eligible platform SOCKS5 and leaves inventory management to VM', () => { const html = showGemini(true) expect(html).toContain('不创建虚拟机') expect(html).toContain('首次创建时自动校验并安装') @@ -83,14 +85,15 @@ test('Gemini import displays only platform SOCKS5 and separates authorization fr expect(html).toContain('允许的平台代理') expect(html).not.toContain('租户代理') expect(html).not.toContain('宿主直连') - expect(html).toContain('已授权') - expect(html).toContain('运行未就绪') - expect(html).toContain('官方计费未核实') + expect(html).not.toContain('fixture@example.test') }) test('VM page renders Gemini inventory and measured data without treating the host as a VM slot', () => { const html = showGemini(true, 'vm') expect(html).toContain('Gemini 宿主环境') + expect(html).toContain('已授权') + expect(html).toContain('当前载荷未启用推理') + expect(html).toContain('缺少官方逐回合结算') expect(html).toContain('fixture@example.test') expect(html).toContain('fixture-project') expect(html).toContain('Google AI Pro') diff --git a/web/src/features/import/gemini-environments.tsx b/web/src/features/import/gemini-environments.tsx index d6c4c888f..ed6f5265e 100644 --- a/web/src/features/import/gemini-environments.tsx +++ b/web/src/features/import/gemini-environments.tsx @@ -1,5 +1,10 @@ import { useState } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { + queryOptions, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/react-query' import { Link } from '@tanstack/react-router' import { api } from '@/lib/api' import { Button } from '@/components/ui/button' @@ -9,7 +14,7 @@ import { Label } from '@/components/ui/label' const ROOT = '/api/panel/gemini' const QUERY_KEY = ['panel', 'gemini-environments'] as const -type Environment = { +export type GeminiEnvironment = { id: string name: string proxy_id: string @@ -43,7 +48,7 @@ type Inventory = { available: boolean payload_state?: 'installed' | 'install_on_create' | 'not_configured' | 'invalid' - environments: Environment[] + environments: GeminiEnvironment[] } type Authorization = { url: string; attempt_id: string } type Proxy = { @@ -57,7 +62,7 @@ type Proxy = { blocked_reason?: string } -const AUTH_LABELS: Record = { +const AUTH_LABELS: Record = { unverified: '未授权', authorizing: '等待 Google 授权', authorized: '已授权', @@ -78,10 +83,24 @@ function localTime(value?: string | null) { return Number.isNaN(date.getTime()) ? '—' : date.toLocaleString() } -function EnvironmentData({ environment }: { environment: Environment }) { +function EnvironmentData({ environment }: { environment: GeminiEnvironment }) { const account = environment.account return (
+
+
凭证
+
{AUTH_LABELS[environment.auth_state]}
+
+
+
推理
+
{environment.runtime_ready ? '就绪' : '当前载荷未启用推理'}
+
+
+
付费调用
+
+ {environment.billing_ready ? '可用' : '关闭 · 缺少官方逐回合结算'} +
+
环境 ID
{environment.id}
@@ -157,13 +176,8 @@ function EnvironmentData({ environment }: { environment: Environment }) { ) } -export function GeminiEnvironments({ - view = 'import', -}: { - view?: 'import' | 'vm' -}) { - const client = useQueryClient() - const inventory = useQuery({ +export function geminiInventoryOptions() { + return queryOptions({ queryKey: QUERY_KEY, queryFn: () => api(ROOT), retry: false, @@ -174,10 +188,20 @@ export function GeminiEnvironments({ ? 1500 : false, }) +} + +export function GeminiEnvironments({ + environmentId, +}: { + environmentId?: string +}) { + const isImport = !environmentId + const client = useQueryClient() + const inventory = useQuery(geminiInventoryOptions()) const proxies = useQuery({ queryKey: ['panel', 'gemini-egress-options'], queryFn: () => api<{ proxies: Proxy[] }>('/api/panel/proxies'), - enabled: view === 'import' && inventory.data?.available === true, + enabled: isImport && inventory.data?.available === true, }) const exits = (proxies.data?.proxies ?? []).filter( (proxy) => @@ -192,13 +216,14 @@ export function GeminiEnvironments({ const [name, setName] = useState('') const [proxyId, setProxyId] = useState('') const [authMethod, setAuthMethod] = - useState('oauth') + useState('oauth') const [apiKey, setApiKey] = useState('') const [challenge, setChallenge] = useState< (Authorization & { id: string }) | null >(null) const [code, setCode] = useState('') const [deleteId, setDeleteId] = useState(null) + const [createdId, setCreatedId] = useState(null) const operation = useMutation({ mutationFn: async (action: { @@ -208,7 +233,7 @@ export function GeminiEnvironments({ }) => { const resource = `${ROOT}/environments${action.id ? `/${encodeURIComponent(action.id)}` : ''}` if (action.type === 'create') { - const environment = await api(resource, { + const environment = await api(resource, { method: 'POST', body: JSON.stringify({ name, @@ -228,6 +253,7 @@ export function GeminiEnvironments({ ) setName('') setApiKey('') + setCreatedId(environment.id) return } if (action.type === 'authorize' && action.id) { @@ -242,7 +268,7 @@ export function GeminiEnvironments({ if (!challenge || challenge.id !== action.id) { throw new Error('授权会话已失效,请重新发起 Google 授权。') } - await api(`${resource}/authorization`, { + await api(`${resource}/authorization`, { method: 'PUT', body: JSON.stringify({ attempt_id: challenge.attempt_id, @@ -262,12 +288,11 @@ export function GeminiEnvironments({ onSettled: () => client.invalidateQueries({ queryKey: QUERY_KEY }), }) - if (inventory.isPending && view === 'import') + if (inventory.isPending) return

正在检测 Gemini 宿主机服务…

- if (inventory.isError && view === 'import') - return

读取 Gemini 环境失败。

+ if (inventory.isError) return

读取 Gemini 环境失败。

if (!inventory.data?.available) - return view === 'vm' ? null : ( + return (

此宿主机尚未启用 Gemini。请先在宿主运行{' '} deploy/install.sh prepare-gemini,再刷新面板。 @@ -275,30 +300,22 @@ export function GeminiEnvironments({ ) const payloadState = inventory.data.payload_state const canInstall = payloadState !== 'not_configured' + const selectedId = environmentId || createdId + const environment = inventory.data.environments.find( + (item) => item.id === selectedId + ) return ( -

- {view === 'vm' ? ( -
-

Gemini 宿主环境

- - 导入 Gemini - -
+
+ {isImport ? ( +

+ 在宿主机创建环境,不创建虚拟机。必须绑定 IPv4 SOCKS5 代理。已有账号在{' '} + + 虚拟机 + {' '} + 管理。 +

) : null} -

- 在宿主机创建环境,不创建虚拟机。支持 Google 授权和 Gemini API - Key,必须绑定 IPv4 SOCKS5 代理。 -

{payloadState === 'install_on_create' ? (

首次创建时自动校验并安装 Gemini 内核和官方 CLI。

) : null} @@ -308,7 +325,7 @@ export function GeminiEnvironments({ {payloadState === 'invalid' ? (

Gemini 载荷校验失败,请检查安装源及宿主服务日志。

) : null} - {view === 'import' ? ( + {isImport ? (
{ @@ -401,27 +418,21 @@ export function GeminiEnvironments({ 创建 Gemini 环境
- ) : !inventory.data.environments.length ? ( -

尚无 Gemini 环境。

+ ) : !environment ? ( +

+ Gemini 环境已删除或不可用。 +

) : null} {operation.isError ? (

{operation.error.message}

) : null} - {inventory.data.environments.map((environment) => ( -
-

{environment.name}

-

- {environment.auth_method === 'api_key' ? 'API Key' : 'Google OAuth'}{' '} - · 代理 {environment.proxy_id} ·{' '} - {AUTH_LABELS[environment.auth_state]} ·{' '} - {environment.runtime_ready ? '运行就绪' : '运行未就绪'} ·{' '} - {environment.billing_ready ? '计费可用' : '官方计费未核实'} -

+ {environment ? ( +
+ {isImport ? ( +

{environment.name}

+ ) : null}
{environment.auth_method !== 'api_key' ? ( @@ -522,8 +533,8 @@ export function GeminiEnvironments({ ) : null} -
- ))} +
+ ) : null} ) } diff --git a/web/src/features/import/index.tsx b/web/src/features/import/index.tsx index 5df4e0b3a..39568d493 100644 --- a/web/src/features/import/index.tsx +++ b/web/src/features/import/index.tsx @@ -1,5 +1,6 @@ import { useState } from 'react' import { useQuery } from '@tanstack/react-query' +import { useSearch } from '@tanstack/react-router' import { VIEW_TITLES } from '@/config/nav' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { PageHeader } from '@/components/page-header' @@ -15,9 +16,18 @@ export function ImportPage() { const dash = useQuery(dashboardQueryOptions()) const me = useQuery(meQueryOptions()) const isAdmin = me.data?.role === 'admin' - const [tab, setTab] = useState(() => - window.location.hash === '#gemini' ? 'gemini' : 'onboard' - ) + const requested = useSearch({ + from: '/_authenticated/import', + select: (search) => search.tab, + }) + const [selected, setSelected] = useState<{ + requested?: string + tab: string + }>() + const tab = + selected && selected.requested === requested + ? selected.tab + : requested || 'onboard' return ( setSelected({ requested, tab })} className='max-w-6xl gap-6' > diff --git a/web/src/features/proxies/proxy-chip.tsx b/web/src/features/proxies/proxy-chip.tsx index 77c8fc985..9b8a8b443 100644 --- a/web/src/features/proxies/proxy-chip.tsx +++ b/web/src/features/proxies/proxy-chip.tsx @@ -45,7 +45,10 @@ export function ProxyChip({ // (集群槽经节点本机出网),返回真实的出口 IP 与地理。接口只对 admin 开放; // 未绑定或被策略封禁的槽位没有可测的出口。 const canProbe = - me.data?.role === 'admin' && bound && !vm.proxy?.blocked_reason + !vm.gemini && + me.data?.role === 'admin' && + bound && + !vm.proxy?.blocked_reason const probe = useMutation({ onMutate: () => toast.loading('正在探测出口…'), mutationFn: () => @@ -86,6 +89,21 @@ export function ProxyChip({ ? named : label + if (vm.gemini) { + return ( + + + {vm.gemini.proxy_id} + + ) + } + return (
toast.error(error.message), }) const vms: Vm[] = vmsQ.data?.items || [] + const slots = + isAdmin && gemini.data?.available + ? [...vms, ...gemini.data.environments.map(geminiSlot)] + : vms const poolQueue = vmsQ.data?.pool_queue const accounts = usage.data?.accounts const canCreate = me.data?.role === 'admin' || (me.data?.role === 'user' && (me.data.vm_create_quota || 0) > 0) const perms = vmPermsFor(me.data?.role) - const scoped = filterVms(vms, '', 'all', kind) - const list = sortVms(filterVms(vms, q, filter, kind), sort, dir, accounts) + const scoped = filterVms(slots, '', 'all', kind) + const list = sortVms(filterVms(slots, q, filter, kind), sort, dir, accounts) const deletePlan = deleteTarget ? planDeleteActiveVm(deleteTarget, vms) : { kind: 'normal' as const } @@ -202,6 +210,13 @@ export function VmListPage() { 全局排队 {poolQueue.global_queue_depth}/{poolQueue.queue_max} ) : null} + {isAdmin ? ( + + ) : null} {canCreate ? ( ) : null} @@ -222,7 +237,12 @@ export function VmListPage() { onFilter={setFilter} />
- + - {me.data?.role === 'admin' ? : null} { diff --git a/web/src/features/vm/vm-account-identity.tsx b/web/src/features/vm/vm-account-identity.tsx index 6d9189b79..e240c9962 100644 --- a/web/src/features/vm/vm-account-identity.tsx +++ b/web/src/features/vm/vm-account-identity.tsx @@ -1,5 +1,6 @@ import type { Vm } from '@/types/panel-vm' import ClaudeColor from '@lobehub/icons/es/Claude/components/Color' +import GeminiColor from '@lobehub/icons/es/Gemini/components/Color' import OpenAI from '@lobehub/icons/es/OpenAI/components/Mono' import { credentialRegistrationOf } from '@/lib/cred-type' import { tierVisual } from '@/lib/tier-visual' @@ -11,8 +12,8 @@ import { VmRentedMark } from '@/features/vm/vm-owner-line' export function PlatformMark({ vm }: { vm: Vm }) { const gpt = isCodexVm(vm) - const Icon = gpt ? OpenAI : ClaudeColor - const label = gpt ? 'openai' : 'anthropic' + const Icon = vm.gemini ? GeminiColor : gpt ? OpenAI : ClaudeColor + const label = vm.gemini ? 'Gemini' : gpt ? 'openai' : 'anthropic' return ( - {vm.id} + {vm.gemini ? vm.name : vm.id}
@@ -51,10 +52,14 @@ export function VmAccountIdentity({ vm }: { vm: Vm }) { - {claudeTier(vm).label} + {vm.gemini + ? vm.gemini.account?.plan || 'Gemini' + : claudeTier(vm).label} - {vm.runtime_type === 'kvm' ? 'kvm' : 'vm'} + + {vm.gemini ? '宿主机' : vm.runtime_type === 'kvm' ? 'kvm' : 'vm'} + {registration === 'none' ? '无凭证' : registration} @@ -69,7 +74,7 @@ export function VmAccountIdentity({ vm }: { vm: Vm }) { )} title='当前内核' > - {crag ? 'crag' : '默认'} + {vm.gemini ? 'CRAGAnti' : crag ? 'crag' : '默认'} {node} diff --git a/web/src/features/vm/vm-action-menu.tsx b/web/src/features/vm/vm-action-menu.tsx index cf622b7a4..cfe41c3d5 100644 --- a/web/src/features/vm/vm-action-menu.tsx +++ b/web/src/features/vm/vm-action-menu.tsx @@ -59,6 +59,20 @@ export function VmActionMenu({ const restricted = restrictionTitle(vm) const admin = me.data?.role === 'admin' const perms = useVmPerms() + if (vm.gemini) { + return ( + + ) + } return ( <> diff --git a/web/src/features/vm/vm-actions-provider.tsx b/web/src/features/vm/vm-actions-provider.tsx index 4209533da..bc7b3f902 100644 --- a/web/src/features/vm/vm-actions-provider.tsx +++ b/web/src/features/vm/vm-actions-provider.tsx @@ -4,8 +4,16 @@ import type { UsageAccountRow } from '@/types/panel-usage' import type { Vm } from '@/types/panel-vm' import { toast } from 'sonner' import { api } from '@/lib/api' +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog' import { ConfirmDialog } from '@/components/confirm-dialog' import { meQueryOptions } from '@/features/auth/queries' +import { GeminiEnvironments } from '@/features/import/gemini-environments' import { dashboardQueryOptions } from '@/features/overview/queries' import { clearVmRestriction } from '@/features/vm/clear-restriction' import { vmQueryOptions, vmsListQueryOptions } from '@/features/vm/queries' @@ -47,6 +55,7 @@ export function VmActionsProvider({ const isAdmin = me.data?.role === 'admin' const list = useQuery(vmsListQueryOptions()) const [detailId, setDetailId] = useState(null) + const [geminiTarget, setGeminiTarget] = useState(null) const [testId, setTestId] = useState(null) const [statsId, setStatsId] = useState(null) // 首次打开后保持挂载,关闭动画照常播放。 @@ -145,7 +154,10 @@ export function VmActionsProvider({ const actions = useMemo( () => ({ - openDetail: (vm) => setDetailId(vm.id), + openDetail: (vm) => { + if (vm.gemini) setGeminiTarget(vm) + else setDetailId(vm.id) + }, openTest: (vm) => setTestId(vm.id), openStats: (vm) => setStatsId(vm.id), openReauth: (vm) => setReauthId(vm.id), @@ -194,6 +206,22 @@ export function VmActionsProvider({ return ( {children} + {isAdmin && geminiTarget ? ( + !open && setGeminiTarget(null)}> + + + {geminiTarget.name || geminiTarget.id} + + Gemini 宿主机账号 · {geminiTarget.proxy_id} + + + + + + ) : null} ({ useVmActions: () => ({}) })) vi.mock('./vm-action-menu', () => ({ VmActionMenu: () => null })) @@ -88,6 +91,56 @@ describe('VM row interaction and health', () => { }) describe('VM account column kernel label', () => { + it('shares the VM table and rack with a host Gemini account without VM controls or fake readiness', () => { + const gemini = geminiSlot({ + id: 'gemini-fixture', + name: 'Gemini account', + proxy_id: 'px-011f7746', + auth_state: 'authorized', + runtime_ready: false, + billing_ready: false, + auth_method: 'oauth', + kernel_version: '0.3.0-rc.1', + created_at: null, + updated_at: null, + models: [], + account: null, + }) + expect(filterVms([gemini], 'px-011f', 'dead', 'gemini')).toEqual([gemini]) + expect(filterVms([gemini], '', 'all', 'gpt')).toEqual([]) + expect(filterVms([gemini], '', 'all', 'claude')).toEqual([]) + + const openai = { id: 'vm-02', platform: 'openai', has_token: true } + const renderSlots = (nodes: ReactNode) => + renderToStaticMarkup( + + {nodes} + + ) + const table = renderSlots() + expect(table).toContain('aria-label="openai"') + expect(table).toContain('data-vm-table') + for (const html of [ + table, + renderSlots(), + ]) { + for (const label of [ + 'Gemini account', + 'CRAGAnti', + '宿主机', + '已授权', + '载荷未启用推理', + 'px-011f7746', + ]) { + expect(html).toContain(label) + } + expect(html).not.toContain('运行就绪') + } + const hostOnly = renderSlots() + expect(hostOnly).not.toContain('role="switch"') + expect(hostOnly).not.toContain('24h 无请求') + }) + it.each(['wrap', 'cc'] as const)( 'renders %s as a silver standard kernel', (dataplane) => { diff --git a/web/src/features/vm/vm-list-table.tsx b/web/src/features/vm/vm-list-table.tsx index 1bb471882..6d2fa38a8 100644 --- a/web/src/features/vm/vm-list-table.tsx +++ b/web/src/features/vm/vm-list-table.tsx @@ -56,6 +56,7 @@ import { riskFg, RISK_SOLID, riskLevel } from '@/features/vm/usage-meter' import { PlatformMark } from '@/features/vm/vm-account-identity' import { VmActionMenu } from '@/features/vm/vm-action-menu' import { useVmActions } from '@/features/vm/vm-actions-context' +import { GeminiSlotStatus } from '@/features/vm/vm-rack-blade' import { vmWindows, type WindowKey, @@ -103,6 +104,7 @@ const STATE_ICON_FG: Partial> = { } function SchedCell({ vm }: { vm: Vm }) { + if (vm.gemini) return const level = Number(vm.schedule_level) const levelOk = Number.isInteger(level) && level >= 1 && level <= 10 const manual = vm.schedule_level_mode === 'manual' @@ -486,6 +488,7 @@ const COLS: Col[] = [ function ProdCell({ vm }: { vm: Vm }) { const tier = claudeTier(vm) + const plan = vm.gemini ? vm.gemini.account?.plan : tier.label const crag = (vm.resolved_dataplane ?? vm.dataplane) === 'crag' const registration = credentialRegistrationOf(vm) const node = vm.node_name || vm.node_id || 'local' @@ -493,19 +496,22 @@ function ProdCell({ vm }: { vm: Vm }) { <> - {vm.id} + {vm.gemini ? vm.name : vm.id} - {tier.label && tier.label !== '—' ? ( + {plan && plan !== '—' ? ( - {tier.label} + {plan} ) : null} - {crag ? 'crag' : '默认'} + {vm.gemini ? 'CRAGAnti' : crag ? 'crag' : '默认'} - {vm.runtime_type === 'kvm' ? 'kvm' : 'vm'} + + {vm.gemini ? '宿主机' : vm.runtime_type === 'kvm' ? 'kvm' : 'vm'} + · {registration === 'none' ? '无凭证' : registration} · @@ -1012,7 +1020,11 @@ export function VmTable({ dim && i > 0 && 'opacity-50' )} > - {c.cell(r, now)} + {vm.gemini && i > 0 ? ( + — + ) : ( + c.cell(r, now) + )}
))}
- {open ? ( + {open && vm.gemini ? ( +
+ {vm.email || '未提供邮箱'} + + {vm.gemini.account?.plan || '未提供订阅'} + + + +
+ ) : open ? ( e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()} > - + {vm.gemini ? null : } ) } +export function GeminiSlotStatus({ vm }: { vm: Vm }) { + const environment = vm.gemini + if (!environment) return null + const labels = { + authorized: '已授权', + authorizing: '等待 Google 授权', + unverified: '未授权', + reauth_required: '需要重新授权', + disabled: '已停用', + } + const detail = + environment.auth_state === 'authorized' ? vm.unschedulable_text : null + const tone = + environment.auth_state === 'authorized' + ? { key: 'ok', cls: 'ok' as const, text: labels.authorized } + : poolStatus(vm) + return ( + + + {detail ? {detail} : null} + + ) +} + /** * 席位容量:一条按「已用 / 设置上限」缩放的定宽条。 * 已用只含正在跑的请求,以及已排在这台 VM 上的后续请求。对话结束即释放。 @@ -437,7 +464,9 @@ export const VmBlade = memo(function VmBlade({ ) : null} - {state === 'live' ? ( + {vm.gemini ? ( + + ) : state === 'live' ? ( ) : state === 'unprobed' ? (
diff --git a/web/src/features/vm/vm-rack-unit.tsx b/web/src/features/vm/vm-rack-unit.tsx index cb9313a6a..6ecb8e5bb 100644 --- a/web/src/features/vm/vm-rack-unit.tsx +++ b/web/src/features/vm/vm-rack-unit.tsx @@ -10,6 +10,7 @@ import { VmAccountIdentity } from '@/features/vm/vm-account-identity' import { BLADE_STATE_CLASS, BladeControls, + GeminiSlotStatus, tierStyle, useOpenOnKey, VmSeats, @@ -96,7 +97,11 @@ export const VmUnit = memo(function VmUnit({
- {state === 'live' ? ( + {vm.gemini ? ( +
+ +
+ ) : state === 'live' ? ( {vmWindows(vm).map((w) => ( diff --git a/web/src/features/vm/vm-table.tsx b/web/src/features/vm/vm-table.tsx index bc46f91a9..0df638a6b 100644 --- a/web/src/features/vm/vm-table.tsx +++ b/web/src/features/vm/vm-table.tsx @@ -95,6 +95,8 @@ export function sortVms( const db = vmCredDead(b) if (da !== db) return da ? 1 : -1 if (da && db) return deadCmp(a, b) + if (key === 'remain' && !!a.gemini !== !!b.gemini) return a.gemini ? 1 : -1 + if (key === 'remain' && a.gemini && b.gemini) return deadCmp(a, b) const av = val(a) const bv = val(b) if (typeof av === 'string' || typeof bv === 'string') { @@ -109,10 +111,11 @@ export function sortVms( * 等级与凭证类型仍参与全文搜索(可以直接搜 "Max" / "OAuth")。 * `kind` 切 Claude / GPT 凭证面,默认全部。 */ -export type VmKindFilter = 'all' | 'claude' | 'gpt' +export type VmKindFilter = 'all' | 'claude' | 'gpt' | 'gemini' export function matchesKind(vm: Vm, kind: VmKindFilter): boolean { if (kind === 'all') return true + if (vm.gemini) return kind === 'gemini' return isCodexVm(vm) ? kind === 'gpt' : kind === 'claude' } @@ -120,38 +123,45 @@ export function KindFilterChips({ vms, kind, onChange, + showGemini = false, }: { vms: Vm[] kind: VmKindFilter onChange: (kind: VmKindFilter) => void + showGemini?: boolean }) { let claude = 0 let openai = 0 + let gemini = 0 for (const vm of vms) { - if (isCodexVm(vm)) openai += 1 + if (vm.gemini) gemini += 1 + else if (isCodexVm(vm)) openai += 1 else claude += 1 } const chips = [ ['claude', 'claude', claude, '筛选 Claude'], ['gpt', 'codex', openai, '筛选 OpenAI'], + ['gemini', 'gemini', gemini, '筛选 Gemini'], ] as const return ( <> - {chips.map(([key, chipKind, n, label]) => ( - - ))} + {chips + .filter(([key]) => key !== 'gemini' || showGemini) + .map(([key, chipKind, n, label]) => ( + + ))} ) } @@ -176,7 +186,7 @@ export function filterVms( vm.kernel, vm.proxy_id, claudeTier(vm).label, - platformLabel(vm), + vm.gemini ? 'Gemini Google craganti' : platformLabel(vm), credTypeLabel(credTypeOf(vm)), ] .map((x) => String(x || '').toLowerCase()) diff --git a/web/src/routes/_authenticated/import.tsx b/web/src/routes/_authenticated/import.tsx index 0b8236a27..f39d503a6 100644 --- a/web/src/routes/_authenticated/import.tsx +++ b/web/src/routes/_authenticated/import.tsx @@ -2,5 +2,8 @@ import { createFileRoute } from '@tanstack/react-router' import { ImportPage } from '@/features/import' export const Route = createFileRoute('/_authenticated/import')({ + validateSearch: (search: Record) => ({ + tab: search.tab === 'gemini' ? ('gemini' as const) : undefined, + }), component: ImportPage, }) diff --git a/web/src/types/panel-vm.ts b/web/src/types/panel-vm.ts index d305872b5..f6e9a40ff 100644 --- a/web/src/types/panel-vm.ts +++ b/web/src/types/panel-vm.ts @@ -1,3 +1,4 @@ +import type { GeminiEnvironment } from '@/features/import/gemini-environments' import type { WindowEstimate } from './panel-pricing' /** @@ -247,6 +248,7 @@ export type ScheduleState = 'on' | 'off' | 'unschedulable' | 'restricted' export type Vm = { id: string + gemini?: GeminiEnvironment name?: string owner_user_id?: string | null /** 所在集群节点;null / 缺省 = 本机。 */ From e7545f180603a6e62dbe4c3376fc0986e2d7a7e4 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 17 Nov 2026 09:37:41 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat(gemini):=20=E5=A2=9E=E5=8A=A0=E4=B8=93?= =?UTF-8?q?=E7=94=A8=E5=AF=86=E9=92=A5=E5=B9=B6=E9=9A=94=E7=A6=BB=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E8=8C=83=E5=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/gemini-host.md | 4 +- src/lib/admin/key-scope.mjs | 25 ++++++++---- src/lib/admin/panel-routes.mjs | 21 +++++++++-- src/lib/gemini/routes.mjs | 22 +++++++++-- src/server.mjs | 20 +++++++++- test/e2e/api-keys.e2e.test.mjs | 42 +++++++++++++++++++++ test/unit/gemini-host.test.mjs | 31 +++++++++++++-- test/unit/key-scope.test.mjs | 16 ++++++++ web/src/features/keys/index.tsx | 1 + web/src/features/keys/key-limits-dialog.tsx | 25 +++++++++--- web/src/features/keys/key-payload.test.ts | 22 +++++++++++ web/src/features/keys/key-payload.ts | 17 +++++++-- web/src/features/keys/key-stats-dialog.tsx | 4 +- web/src/types/panel-keys.ts | 2 +- 14 files changed, 221 insertions(+), 31 deletions(-) diff --git a/docs/gemini-host.md b/docs/gemini-host.md index 67d92c437..085155cdd 100644 --- a/docs/gemini-host.md +++ b/docs/gemini-host.md @@ -1,6 +1,6 @@ # Gemini 宿主机候选 -「导入 → Gemini」管理宿主机环境。「虚拟机」页的 Gemini 宿主环境区展示相同的数据,不创建 VM、Docker 槽、VM 调度记录或 `vm.json`。默认不启用,仅管理员可操作。服务运行在 Linux amd64 宿主,Docker 控制面通过只读挂载的 Unix socket 目录连接;ARM64 和远端集群不受支持。 +「导入 → Gemini」创建宿主机环境。「虚拟机」页将 Gemini 账号显示在同一机架和列表中,管理员可按平台筛选,并从账号详情授权或刷新。不创建 VM、Docker 槽、VM 调度记录或 `vm.json`。默认不启用,仅管理员可操作。服务运行在 Linux amd64 宿主,Docker 控制面通过只读挂载的 Unix socket 目录连接;ARM64 和远端集群不受支持。 ## 启用服务与自动安装 @@ -19,4 +19,4 @@ - `0.3.0-rc.1` 已用真实 `agy` 验证受管 PTY 和隔离回环上游 SSE。自动安装和数据读取可用本地夹具验证;真实 Google 换票和 OAuth 推理未验收,不标记推理就绪。 - 可使用非 root 账号运行 `bash test/deploy/gemini-host-egress-smoke.sh /absolute/path/kin-egress`,在一次性 Linux 命名空间用 `iptables` 模拟 Docker 的默认转发丢弃策略,检查选定 SOCKS5 的透明转发、转发器退出后失败和网络清理。该测试不访问 Google 或主机代理池。 - 有测试签名产物时,可在带 Node 和 Python 的一次性 Linux amd64 容器内以 root 运行 `bash test/deploy/gemini-host-install-smoke.sh /path/to/signed-payload /path/to/public-key`。禁用容器网络即可验证 Unix socket 启动、签名失败不建环境、首次创建自动安装和重启持久化。 -- `/v1/gemini/sessions` 命名空间保持付费关闭,鉴权后返回 `gemini_official_billing_unavailable`,不分配会话或扣费。没有逐回合可核销的官方金额,不启用 Gemini 专用调用密钥、对外推理或美元结算;不把订阅等级、Token 数或余额变化当成实扣凭证。 +- 管理员可生成 `Gemini · CRAGAnti` 专用密钥,只能访问 Gemini 会话入口及密钥查询,不会落入 Claude、Codex 或 API 直连。当前二进制的推理桥仅验收过 Gemini API Key provider;即使 Google OAuth 已授权,`/v1/gemini/sessions` 也会返回 `gemini_runtime_not_supported`,不会分配会话或扣费。对外推理还需支持 OAuth 的载荷及逐回合可核销的官方结算;不把订阅等级、Token 数或余额变化当成实扣凭证。 diff --git a/src/lib/admin/key-scope.mjs b/src/lib/admin/key-scope.mjs index 4c18d8ba6..dc2ba0821 100644 --- a/src/lib/admin/key-scope.mjs +++ b/src/lib/admin/key-scope.mjs @@ -43,7 +43,7 @@ export function parseAllowedVms(value) { ] } -/** null when the value is present but not all/anthropic/openai. Empty uses fallback. */ +/** Empty uses fallback; an unsupported platform returns null. */ export function normalizeGroupType(value, { fallback = 'all' } = {}) { if (value == null || value === '') return fallback if (value === 'pool') return null @@ -51,6 +51,7 @@ export function normalizeGroupType(value, { fallback = 'all' } = {}) { if (v === 'all') return 'all' if (v === 'anthropic' || v === 'claude') return 'anthropic' if (v === 'openai' || v === 'gpt' || v === 'codex') return 'openai' + if (v === 'gemini') return 'gemini' return null } @@ -71,10 +72,10 @@ function poolIdOf(value) { export function keyScopeFromRecord(rec) { if (!rec) return { group_type: 'all', allowed_vms: [], vm_pool_id: null } const group_type = normalizeGroupType(rec.group_type) || 'all' - const vm_pool_id = poolIdOf(rec.vm_pool_id) + const vm_pool_id = group_type === 'gemini' ? null : poolIdOf(rec.vm_pool_id) return { group_type, - allowed_vms: vm_pool_id || group_type === 'all' ? [] : parseAllowedVms(rec.allowed_vms), + allowed_vms: vm_pool_id || group_type === 'all' || group_type === 'gemini' ? [] : parseAllowedVms(rec.allowed_vms), vm_pool_id, } } @@ -109,6 +110,7 @@ export function vmPoolDenial(scope) { } export function keyAllowsVm(scope, vm) { + if (scope?.group_type === 'gemini') return false if (scope?.vm_pool_id) { if (scope.vm_pool_error) return false if (!vm?.id || !(scope.allowed_vms || []).includes(vm.id)) return false @@ -133,14 +135,14 @@ export function normalizeKeyScope(input = {}, { partial = false, current = null, const hasType = input.group_type != null && input.group_type !== '' const hasVms = input.allowed_vms != null const hasPool = Object.prototype.hasOwnProperty.call(input, 'vm_pool_id') - if (partial && !hasType && !hasVms && !hasPool) return null - const base = current ? keyScopeFromRecord(current) : { group_type: 'all', allowed_vms: [], vm_pool_id: null } let group_type = !partial && !hasType ? 'all' : base.group_type if (hasType) { const parsed = normalizeGroupType(input.group_type, { fallback: null }) if (!parsed) { - throw Object.assign(new Error('group_type 只能是 all、anthropic 或 openai'), { code: 'invalid_group_type' }) + throw Object.assign(new Error('group_type 只能是 all、anthropic、openai 或 gemini'), { + code: 'invalid_group_type', + }) } group_type = parsed } @@ -149,6 +151,15 @@ export function normalizeKeyScope(input = {}, { partial = false, current = null, String(input.category || current?.category || '') .trim() .toLowerCase() === 'api' + if (group_type === 'gemini') { + if (apiMode || (hasVms && parseAllowedVms(input.allowed_vms).length) || (hasPool && input.vm_pool_id)) { + throw Object.assign(new Error('Gemini 密钥只能使用宿主机 OAuth 池,不能绑定 VM、账号池或 API 渠道'), { + code: 'invalid_gemini_key_scope', + }) + } + return { group_type, allowed_vms: [], vm_pool_id: null } + } + if (partial && !hasType && !hasVms && !hasPool) return null let allowed_vms = hasVms ? parseAllowedVms(input.allowed_vms) : !partial && !hasType ? [] : base.allowed_vms let vm_pool_id = hasPool ? parsePoolId(input.vm_pool_id) : base.vm_pool_id if (apiMode) { @@ -168,7 +179,7 @@ export function normalizeKeyScope(input = {}, { partial = false, current = null, /** Panel check: every id is a live VM of the chosen platform. Pool membership is checked separately. */ export function assertVmScope(vms, scope) { - if (!scope || scope.group_type === 'all' || scope.vm_pool_id) return [] + if (!scope || scope.group_type === 'all' || scope.group_type === 'gemini' || scope.vm_pool_id) return [] const byId = new Map((vms || []).map((vm) => [vm.id, vm])) for (const id of scope.allowed_vms) { const vm = byId.get(id) diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index 0e887fe99..b55c957c4 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -88,7 +88,7 @@ import { readCatalogSync, syncClaudeCatalog, syncGptCatalog } from './catalog-mo import { setPriceOverride, listPriceOverrides, syncModelsDev } from './price-catalog.mjs' import { buildPricing } from './pricing-view.mjs' import { publicKeyView } from './api-keys.mjs' -import { assertVmScope, normalizeKeyScope } from './key-scope.mjs' +import { assertVmScope, normalizeGroupType, normalizeKeyScope } from './key-scope.mjs' import { assertVmPoolExists, createVmPool, @@ -2007,6 +2007,12 @@ export function createPanelHandler(ctx) { if (req.method === 'POST' && p === '/api/panel/api-keys') { const body = await readBody(req, API_KEY_BODY_MAX).catch(() => ({})) const ident = panelIdentity(req) + if (ident.role !== 'admin' && normalizeGroupType(body?.group_type) === 'gemini') { + return json(res, 403, { + ok: false, + error: { code: 'gemini_key_forbidden', message: '只有管理员可以生成 Gemini 密钥' }, + }) + } if (ident.role !== 'admin' && body?.vm_pool_id != null && String(body.vm_pool_id).trim() !== '') { return json(res, 403, { ok: false, @@ -2086,6 +2092,16 @@ export function createPanelHandler(ctx) { if (denyIfUserMissesKey(req, res, { apiKeyStore, json, keyId: id })) return true const body = await readBody(req, API_KEY_BODY_MAX).catch(() => ({})) const ident = panelIdentity(req) + const currentRec = apiKeyStore.getById(id) + if ( + ident.role !== 'admin' && + (normalizeGroupType(body?.group_type) === 'gemini' || currentRec?.group_type === 'gemini') + ) { + return json(res, 403, { + ok: false, + error: { code: 'gemini_key_forbidden', message: '只有管理员可以修改 Gemini 密钥' }, + }) + } if (ident.role !== 'admin' && body?.vm_pool_id != null && String(body.vm_pool_id).trim() !== '') { return json(res, 403, { ok: false, @@ -2100,7 +2116,6 @@ export function createPanelHandler(ctx) { } try { const input = normalizePanelApiKeyInput(body || {}, req) - const currentRec = apiKeyStore.getById(id) const isApi = isApiCategory(body?.category ?? currentRec?.category) if (Object.hasOwn(input, 'api_endpoint_id')) { input.api_endpoint_id = validateKeyEndpoint(input.api_endpoint_id, isApi, currentRec?.api_endpoint_id) @@ -2108,7 +2123,7 @@ export function createPanelHandler(ctx) { const scopeInput = { group_type: body?.group_type, allowed_vms: body?.allowed_vms, - ...(isApi ? { category: 'api' } : {}), + category: isApi ? 'api' : 'oauth', } if (ident.role === 'admin' && Object.prototype.hasOwnProperty.call(body || {}, 'vm_pool_id')) { scopeInput.vm_pool_id = body.vm_pool_id diff --git a/src/lib/gemini/routes.mjs b/src/lib/gemini/routes.mjs index 66f9feee4..6856e7541 100644 --- a/src/lib/gemini/routes.mjs +++ b/src/lib/gemini/routes.mjs @@ -30,6 +30,13 @@ export function isGeminiPublicPath(value) { return value === PUBLIC_PATH || value.startsWith(`${PUBLIC_PATH}/`) } +export function geminiKeyAllowsPath(pathname, method) { + return ( + isGeminiPublicPath(pathname) || + (method === 'GET' && ['/models', '/v1/models', '/v1/usage', '/v1/me/quota', '/v1/me/usage'].includes(pathname)) + ) +} + function hostError(code, status = 503) { return Object.assign(new Error(code), { code, status }) } @@ -327,13 +334,22 @@ export function createGeminiPanelHandler({ } } -export function geminiBillingUnavailable(json, res) { +export function handleGeminiPublic(req, res, json) { res.setHeader('Cache-Control', 'no-store') + if (req.apiKeyKind !== 'managed' || req.apiKeyRecord?.group_type !== 'gemini') { + return json(res, 403, { + error: { + type: 'permission_error', + code: 'gemini_key_required', + message: 'This endpoint requires a dedicated Gemini API key.', + }, + }) + } return json(res, 503, { error: { type: 'service_unavailable', - code: 'gemini_official_billing_unavailable', - message: 'Gemini paid inference is disabled until verified per-turn official settlement is available.', + code: 'gemini_runtime_not_supported', + message: 'The current CRAGAnti payload does not support Google OAuth inference.', }, }) } diff --git a/src/server.mjs b/src/server.mjs index be98d6d64..dea8dc3ac 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -11,7 +11,7 @@ import http from 'node:http' import fs from 'node:fs' import path from 'node:path' import { loadConfig, reloadActiveVm, routingConfigFile } from './lib/core/config.mjs' -import { geminiBillingUnavailable, isGeminiPublicPath } from './lib/gemini/routes.mjs' +import { geminiKeyAllowsPath, handleGeminiPublic, isGeminiPublicPath } from './lib/gemini/routes.mjs' import { extractApiKey, timingSafeEqualStr, @@ -822,6 +822,21 @@ function requireAuth(req, res, { keyGate = true, buyer = false, optionalBuyer = }), ) } + if ( + managed.record.group_type === 'gemini' && + !geminiKeyAllowsPath(parseRequestUrl(req)?.pathname || '', req.method) + ) { + return rejectAuth( + req, + res, + makeError({ + type: ErrorType.PERMISSION, + code: 'key_group_mismatch', + message: 'This key can only call Gemini endpoints.', + status: 403, + }), + ) + } const gate = keyGate ? apiKeyStore.canAccept(managed.record) : { ok: true } if (!gate.ok) { const type = @@ -1325,6 +1340,7 @@ const server = http.createServer(async (req, res) => { if (req.method === 'GET' && (p === '/v1/models' || p === '/models')) { if (!requireAuth(req, res)) return const groupType = keyScopeFromRequest(req).group_type + if (groupType === 'gemini') return json(res, 200, { object: 'list', data: [] }) if (resolveInferenceBackend(req) === 'api') { return json(res, 200, filterModelCatalogForKey(apiScheduler.catalog(apiScheduleScope(req, groupType)), req)) } @@ -1356,7 +1372,7 @@ const server = http.createServer(async (req, res) => { if (isGeminiPublicPath(p)) { if (!requireAuth(req, res)) return - return geminiBillingUnavailable(json, res) + return handleGeminiPublic(req, res, json) } if (req.method === 'POST' && (p === '/v1/chat/completions' || p === '/chat/completions')) { diff --git a/test/e2e/api-keys.e2e.test.mjs b/test/e2e/api-keys.e2e.test.mjs index a2c06cbce..d03b65669 100644 --- a/test/e2e/api-keys.e2e.test.mjs +++ b/test/e2e/api-keys.e2e.test.mjs @@ -29,6 +29,16 @@ test('real admin and user sessions cannot list or operate each other personal ke const userKey = await personal(userCookie, 'POST', '/api/panel/api-keys', { name: 'user-key' }) assert.equal(userKey.status, 201, userKey.text) assert.equal(userKey.json.item.user_id, userId) + const deniedGeminiKey = await personal(userCookie, 'POST', '/api/panel/api-keys', { + name: 'tenant-gemini', + group_type: 'Gemini', + }) + assert.equal(deniedGeminiKey.status, 403) + assert.equal(deniedGeminiKey.json.error.code, 'gemini_key_forbidden') + const deniedGeminiPatch = await personal(userCookie, 'PATCH', `/api/panel/api-keys/${userKey.json.item.id}`, { + group_type: 'gemini', + }) + assert.equal(deniedGeminiPatch.status, 403) const adminKey = await personal(adminCookie, 'POST', '/api/panel/api-keys', { name: 'admin-key', user_id: userId }) assert.equal(adminKey.status, 201, adminKey.text) assert.ok(adminKey.json.item.user_id) @@ -102,6 +112,38 @@ test('panel creates managed key; key can call /v1/messages', async () => { } }) +test('Gemini keys persist, remain isolated and fail closed without an OAuth runtime', async () => { + const gw = await startGateway() + try { + const created = await api(gw, 'POST', '/api/panel/api-keys', { body: { name: 'host-oauth', group_type: 'gemini' } }) + assert.equal(created.status, 201, created.text) + const { id, key } = created.json.item + assert.equal(created.json.item.group_type, 'gemini') + const updated = await api(gw, 'PATCH', `/api/panel/api-keys/${id}`, { body: { rpm: 2 } }) + assert.equal(updated.status, 200, updated.text) + assert.equal(updated.json.item.group_type, 'gemini') + const wrongCategory = await api(gw, 'PATCH', `/api/panel/api-keys/${id}`, { body: { category: 'api' } }) + assert.equal(wrongCategory.status, 400, wrongCategory.text) + assert.equal(wrongCategory.json.error.code, 'invalid_gemini_key_scope') + const headers = { authorization: `Bearer ${key}` } + + const wrongKey = await api(gw, 'POST', '/v1/gemini/sessions', { body: {} }) + assert.equal(wrongKey.status, 403, wrongKey.text) + assert.equal(wrongKey.json.error.code, 'gemini_key_required') + const unavailable = await api(gw, 'POST', '/v1/gemini/sessions', { headers, body: {} }) + assert.equal(unavailable.status, 503, unavailable.text) + assert.equal(unavailable.json.error.code, 'gemini_runtime_not_supported') + const models = await api(gw, 'GET', '/v1/models', { headers }) + assert.equal(models.status, 200, models.text) + assert.deepEqual(models.json.data, []) + const messages = await api(gw, 'POST', '/v1/messages', { headers, body: {} }) + assert.equal(messages.status, 403, messages.text) + assert.equal(messages.json.error.code, 'key_group_mismatch') + } finally { + await gw.stop() + } +}) + test('panel re-reveals a used key; rotate swaps the plaintext', async () => { const gw = await startGateway({ mockText: 'copyable' }) try { diff --git a/test/unit/gemini-host.test.mjs b/test/unit/gemini-host.test.mjs index d9a61e5c7..46c8d083d 100644 --- a/test/unit/gemini-host.test.mjs +++ b/test/unit/gemini-host.test.mjs @@ -8,7 +8,8 @@ import { authorizePanelRoute } from '../../src/lib/admin/panel-acl.mjs' import { AGY_SHA256, installGeminiPayload, readSignedGeminiManifest } from '../../src/lib/gemini/payload.mjs' import { createGeminiPanelHandler, - geminiBillingUnavailable, + geminiKeyAllowsPath, + handleGeminiPublic, officialGeminiAuthUrl, } from '../../src/lib/gemini/routes.mjs' @@ -173,9 +174,33 @@ test('official login links are validated and code is returned only to its select }) test('missing official settlement cannot be enabled by a host response or a paid route request', () => { - const result = geminiBillingUnavailable((_res, status, body) => ({ status, body }), { setHeader() {} }) + const respond = (_res, status, body) => ({ status, body }) + const res = { setHeader() {} } + for (const group_type of ['all', 'anthropic', 'openai']) { + const denied = handleGeminiPublic({ apiKeyKind: 'managed', apiKeyRecord: { group_type } }, res, respond) + assert.equal(denied.status, 403) + assert.equal(denied.body.error.code, 'gemini_key_required') + } + assert.equal(handleGeminiPublic({ apiKeyKind: 'master' }, res, respond).status, 403) + const result = handleGeminiPublic({ apiKeyKind: 'managed', apiKeyRecord: { group_type: 'gemini' } }, res, respond) assert.equal(result.status, 503) - assert.equal(result.body.error.code, 'gemini_official_billing_unavailable') + assert.equal(result.body.error.code, 'gemini_runtime_not_supported') +}) + +test('Gemini keys cannot reach other inference endpoints via HTTP or WebSocket', () => { + for (const route of [ + '/v1/responses', + '/responses', + '/v1/chat/completions', + '/v1/messages', + '/v1/images/edits', + '/admin/models/refresh', + ]) { + assert.equal(geminiKeyAllowsPath(route, 'POST'), false) + assert.equal(geminiKeyAllowsPath(route, 'GET'), false) + } + assert.equal(geminiKeyAllowsPath('/v1/gemini/sessions', 'POST'), true) + assert.equal(geminiKeyAllowsPath('/v1/me/quota', 'GET'), true) }) test('host installer refuses an unsigned manifest and never activates damaged payload members', async (t) => { diff --git a/test/unit/key-scope.test.mjs b/test/unit/key-scope.test.mjs index 1fe9f0610..38fdc182e 100644 --- a/test/unit/key-scope.test.mjs +++ b/test/unit/key-scope.test.mjs @@ -89,3 +89,19 @@ test('api category allows anthropic and openai groups without VMs', () => { const patched = normalizeKeyScope({ group_type: 'openai' }, { partial: true, current }) assert.deepEqual(patched, { group_type: 'openai', allowed_vms: [], vm_pool_id: null }) }) + +test('Gemini is a dedicated OAuth scope and cannot inherit VM or API access', () => { + const scope = normalizeKeyScope({ group_type: ' Gemini ' }) + assert.deepEqual(scope, { group_type: 'gemini', allowed_vms: [], vm_pool_id: null }) + assert.deepEqual(keyScopeFromRecord({ ...scope, allowed_vms: [codex.id], vm_pool_id: 'pool_abcd1234' }), scope) + assert.equal(keyAllowsVm({ ...scope, allowed_vms: [codex.id] }, codex), false) + assert.throws(() => normalizeKeyScope({ group_type: 'gemini', allowed_vms: [codex.id] }), { + code: 'invalid_gemini_key_scope', + }) + assert.throws(() => normalizeKeyScope({ group_type: 'gemini', vm_pool_id: 'pool_abcd1234' }), { + code: 'invalid_gemini_key_scope', + }) + assert.throws(() => normalizeKeyScope({ category: 'api' }, { partial: true, current: scope }), { + code: 'invalid_gemini_key_scope', + }) +}) diff --git a/web/src/features/keys/index.tsx b/web/src/features/keys/index.tsx index 3b14696fc..dc228a94d 100644 --- a/web/src/features/keys/index.tsx +++ b/web/src/features/keys/index.tsx @@ -474,6 +474,7 @@ function KeyRow({ } function scopeText(item: ApiKeyItem): string { + if (item.group_type === 'gemini') return 'Gemini · CRAGAnti' if (item.vm_pool_id) return `账号池 · ${item.vm_pool_name || item.vm_pool_id}` if (item.group_type === 'anthropic') return `Anthropic · ${item.allowed_vms?.length || 0} 台` diff --git a/web/src/features/keys/key-limits-dialog.tsx b/web/src/features/keys/key-limits-dialog.tsx index 08e6b516c..7c0a4b9cc 100644 --- a/web/src/features/keys/key-limits-dialog.tsx +++ b/web/src/features/keys/key-limits-dialog.tsx @@ -160,7 +160,9 @@ export function KeyLimitsDialog({ !(legacyApi && !draft.api_endpoint_id) : draft.group_type === 'pool' ? !draft.vm_pool_id - : draft.group_type !== 'all' && draft.allowed_vms.length === 0 + : draft.group_type !== 'all' && + draft.group_type !== 'gemini' && + draft.allowed_vms.length === 0 return ( @@ -202,7 +204,8 @@ export function KeyLimitsDialog({ category: v === 'api' ? 'api' : 'oauth', api_endpoint_id: v === 'api' ? d.api_endpoint_id : '', group_type: - v === 'api' && d.group_type === 'pool' + v === 'api' && + (d.group_type === 'pool' || d.group_type === 'gemini') ? 'all' : d.group_type, allowed_vms: v === 'api' ? [] : d.allowed_vms, @@ -326,7 +329,7 @@ export function KeyLimitsDialog({
) : null} {!isApi || (legacyApi && !draft.api_endpoint_id) ? ( - + @@ -394,6 +403,11 @@ export function KeyLimitsDialog({ + ) : draft.group_type === 'gemini' ? ( +

+ 仅用于 Gemini 宿主机 OAuth,不使用 VM + 或直连渠道。当前载荷尚不支持 Google OAuth 推理。 +

) : draft.group_type === 'all' ? (

all 是最高权限,不再选择 VM。 @@ -497,7 +511,8 @@ function blankDraft(): KeyLimitsDraft { } function groupOf(value: string | undefined): KeyGroupType { - if (value === 'anthropic' || value === 'openai') return value + if (value === 'anthropic' || value === 'openai' || value === 'gemini') + return value return 'all' } diff --git a/web/src/features/keys/key-payload.test.ts b/web/src/features/keys/key-payload.test.ts index 1e563231c..a8b671236 100644 --- a/web/src/features/keys/key-payload.test.ts +++ b/web/src/features/keys/key-payload.test.ts @@ -19,6 +19,28 @@ const draft: KeyLimitsDraft = { } describe('API key limit payload', () => { + it('saves Gemini as admin-only OAuth without a VM scope', () => { + const gemini = { + ...draft, + category: 'oauth', + group_type: 'gemini', + vm_pool_id: '', + } as const + for (const mode of ['create', 'edit'] as const) { + expect(keyLimitsPayload(gemini, mode)).toMatchObject({ + group_type: 'gemini', + category: 'oauth', + allowed_vms: [], + vm_pool_id: null, + }) + } + expect(() => + keyLimitsPayload(gemini, 'create', { isAdmin: false }) + ).toThrow('只允许管理员') + expect(() => + keyLimitsPayload({ ...gemini, category: 'api' }, 'create') + ).toThrow('宿主机 OAuth') + }) it('keeps request and USD quotas separate', () => { expect(keyLimitsPayload(draft, 'create')).toEqual({ name: 'ops', diff --git a/web/src/features/keys/key-payload.ts b/web/src/features/keys/key-payload.ts index fc9a5a00c..746485902 100644 --- a/web/src/features/keys/key-payload.ts +++ b/web/src/features/keys/key-payload.ts @@ -1,4 +1,4 @@ -export type KeyGroupType = 'all' | 'anthropic' | 'openai' | 'pool' +export type KeyGroupType = 'all' | 'anthropic' | 'openai' | 'gemini' | 'pool' export const KEY_ALLOWED_MODELS_MAX = 200 @@ -37,7 +37,8 @@ export function parseModelList(text: string): string[] { } function groupTypeOf(value: string): KeyGroupType { - if (value === 'anthropic' || value === 'openai') return value + if (value === 'anthropic' || value === 'openai' || value === 'gemini') + return value return 'all' } @@ -56,6 +57,9 @@ export function keyLimitsPayload( rpm: nonNegative(draft.rpm, 'RPM'), } const isApi = draft.category === 'api' + if (draft.group_type === 'gemini' && (!isAdmin || isApi)) { + throw new Error('Gemini 平台只允许管理员创建宿主机 OAuth 密钥') + } // API 直连不经过槽位,只有管理员可以设置 if (isAdmin) body.category = draft.category if (isAdmin && isApi && draft.api_endpoint_id !== undefined) { @@ -72,10 +76,15 @@ export function keyLimitsPayload( } else { const group_type = groupTypeOf(draft.group_type) const allowed_vms = - group_type === 'all' + group_type === 'all' || group_type === 'gemini' ? [] : [...new Set(draft.allowed_vms.map((id) => id.trim()).filter(Boolean))] - if (!isApi && group_type !== 'all' && allowed_vms.length === 0) { + if ( + !isApi && + group_type !== 'all' && + group_type !== 'gemini' && + allowed_vms.length === 0 + ) { throw new Error('至少选择一台 VM') } body.group_type = group_type diff --git a/web/src/features/keys/key-stats-dialog.tsx b/web/src/features/keys/key-stats-dialog.tsx index c242393e2..286c8457f 100644 --- a/web/src/features/keys/key-stats-dialog.tsx +++ b/web/src/features/keys/key-stats-dialog.tsx @@ -84,7 +84,9 @@ function StatsBody({ item, vms }: { item: ApiKeyItem; vms: Vm[] }) { ? 'Anthropic' : item.group_type === 'openai' ? 'OpenAI' - : '全局'} + : item.group_type === 'gemini' + ? 'Gemini' + : '全局'} {' · '}近 {usage?.days ?? 30} 天 · 官方价 {q.isLoading ? ( diff --git a/web/src/types/panel-keys.ts b/web/src/types/panel-keys.ts index 880502536..21a807049 100644 --- a/web/src/types/panel-keys.ts +++ b/web/src/types/panel-keys.ts @@ -29,7 +29,7 @@ export type ApiKeyItem = { requests?: number inflight?: number /** all = 全局可调度。anthropic / openai 必须带 allowed_vms。 */ - group_type?: 'all' | 'anthropic' | 'openai' + group_type?: 'all' | 'anthropic' | 'openai' | 'gemini' allowed_vms?: string[] vm_pool_id?: string | null vm_pool_name?: string | null