diff --git a/.github/scripts/gateway-models-ui.mjs b/.github/scripts/gateway-models-ui.mjs new file mode 100644 index 000000000000..c4c0db79a651 --- /dev/null +++ b/.github/scripts/gateway-models-ui.mjs @@ -0,0 +1,471 @@ +// Remote CI only: original full application entries/CSS, canonical mocked HTTP. +// This proves browser behavior and request contracts, never real DB persistence. +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { createServer } from 'node:http' +import { readFileSync, writeFileSync, existsSync } from 'node:fs' +import { resolve, join, extname } from 'node:path' +import { pathToFileURL } from 'node:url' + +const output = process.env.EVIDENCE_DIR, origin = 'http://127.0.0.1:4198' +if (process.env.GITHUB_ACTIONS !== 'true' || !output || !process.env.BASELINE || !process.env.CANDIDATE) throw Error('Exact remote CI inputs required') +const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim() +const candidate = git('rev-parse', 'HEAD'), baseline = git('-C', '.gateway-models-baseline', 'rev-parse', 'HEAD') +assert.equal(candidate, process.env.CANDIDATE) +assert.equal(baseline, process.env.BASELINE) +const clone = value => structuredClone(value) +const A = 'cross-platform-gateway-accounts', B = 'gateway-account-model-sync-20261122' +const manifest = { + candidate, baseline, complete: false, + notice_ids: { A, B, C: 'fixture-gateway-models-future-announcement-C' }, + boundary: 'Unmodified complete baseline/candidate index.html, App, router, AccountsView, Create/Edit dialogs, shared components, stores and project Vite/Tailwind/CSS. Playwright intercepts canonical same-origin APIs with synthetic data, including auth and a server-side saved-key fixture. Saves/readbacks are mock contract assertions, not real service/repository/PostgreSQL evidence. Backend persistence/security are separate remote Go tests. No production, real upstream, paid model calls or external requests. The auxiliary announcement epoch page renders the real badge/store; actual B checks use all three product entrypoints. No target component stubs or source overlays.', + source_blobs: {}, screenshots: [], assertions: [], requests: [], saves: [], readbacks: [], computed_css: [], errors: [], unexpected: [], external: [], +} +const sourcePaths = [ + 'frontend/index.html', 'frontend/src/main.ts', 'frontend/src/App.vue', + 'frontend/src/views/admin/AccountsView.vue', 'frontend/src/components/account/CreateAccountModal.vue', + 'frontend/src/components/account/EditAccountModal.vue', 'frontend/src/components/account/GatewayAccountFields.vue', + 'frontend/src/components/account/GatewayModelSettings.vue', 'frontend/src/components/account/ModelWhitelistSelector.vue', + 'frontend/src/components/common/BaseDialog.vue', 'frontend/src/components/common/NewFeatureBadge.vue', + 'frontend/src/stores/newFeatureNotices.ts', 'frontend/src/constants/newFeatureNotices.ts', + 'frontend/src/composables/useModelWhitelist.ts', 'frontend/src/i18n/locales/en/admin/accounts.ts', 'frontend/src/i18n/locales/zh/admin/accounts.ts', + 'frontend/src/style.css', 'frontend/tailwind.config.js', 'frontend/vite.config.ts', +] +for (const [mode, ref] of [['before', baseline], ['after', candidate]]) { + const paths = new Set(git('ls-tree', '-r', '--name-only', ref).split('\n')) + manifest.source_blobs[mode] = { commit: ref, paths: Object.fromEntries(sourcePaths.map(path => [path, paths.has(path) ? git('rev-parse', `${ref}:${path}`) : 'absent'])) } +} +let mode = 'before', browser, activePage, activeCase +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2' } +const server = createServer((req, res) => { + const pathname = new URL(req.url, origin).pathname + if (/^\/(?:api\/|setup\/)/.test(pathname)) { res.writeHead(500); res.end('API must be intercepted by the audited fixture'); return } + const root = resolve(output, mode + '-dist') + let file = resolve(root, '.' + decodeURIComponent(pathname)) + if (!file.startsWith(root + '/')) { res.writeHead(403); res.end(); return } + if (!existsSync(file) || !extname(file)) file = join(root, 'index.html') + res.setHeader('Content-Type', mime[extname(file)] || 'application/octet-stream') + res.setHeader('Cache-Control', 'no-store') + res.end(readFileSync(file)) +}) +await new Promise(done => server.listen(4198, '127.0.0.1', done)) +const { chromium } = await import(pathToFileURL(process.env.SUB2API_PLAYWRIGHT_MODULE)) +const user = { id: 1003, role: 'admin', status: 'active', email: 'reviewer@example.invalid', username: 'Fixture administrator', balance: 0, concurrency: 1, run_mode: 'standard' } +const groups = [ + { id: 101, name: 'Fixture OpenAI restricted', platform: 'openai', model_allowlist: { enabled: true, models: ['live'] } }, + { id: 102, name: 'Fixture Anthropic', platform: 'anthropic', model_allowlist: { enabled: false, models: [] } }, + { id: 103, name: 'Fixture OAuth only', platform: 'openai', require_oauth_only: true }, +].map(group => ({ status: 'active', rate_multiplier: 1, account_count: 1, subscription_type: 'standard', require_oauth_only: false, ...group })) +const proxies = [7, 8].map(id => ({ id, name: `Fixture proxy ${id}`, protocol: 'http', host: 'proxy.example.invalid', port: 8080, status: 'active' })) +const publicSettings = { site_name: 'Sub2API', site_logo: '', subscription_enabled: false, support_ticket_enabled: false, + payment_enabled: false, risk_control_enabled: false, custom_menu_items: [], custom_endpoints: [], registration_enabled: false } +const initialAccount = (kind, id) => ({ id, name: `Fixture ${kind}`, platform: 'gateway', type: 'gateway', status: 'active', + schedulable: true, concurrency: 2, priority: 50, rate_multiplier: 1, cost_multiplier: 1, proxy_id: 7, group_ids: [101], + groups: [groups[0]], account_groups: [{ group_id: 101, priority: 50, allowed_models: [] }], + credentials: { upstream_kind: kind, base_url: `https://${kind.replace('_', '-')}.example.invalid/tenant`, api_key: `synthetic-saved-${kind}`, model_mapping: { live: 'live', public: 'live' }, unrelated_option: { keep: true } }, + extra: {}, notes: '', auto_pause_on_expired: false, created_at: '2026-11-22T00:00:00Z', updated_at: '2026-11-22T00:00:00Z' }) +const labels = { + en: { create: 'Create Account', edit: 'Edit', from: 'Request model', to: 'Target model', addMapping: 'Add Mapping', custom: 'Enter custom model name', add: 'Add' }, + zh: { create: '添加账号', edit: '编辑', from: '请求模型', to: '目标模型', addMapping: '添加映射', custom: '输入自定义模型名称', add: '填入' }, +} +const tick = page => page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))) +function stateForCase() { + return { rows: new Map([['new_api', 51], ['sub2api', 52]].map(([kind, id]) => [id, initialAccount(kind, id)])), nextID: 60, + previewPlan: null, applyPlan: null, pending: null, previews: [], applies: [], groupSnapshot: clone(groups) } +} +const redacted = value => { const copy = clone(value); delete copy.credentials.api_key; return copy } +function recordRequest(request, path) { + const data = request.postData() ? request.postDataJSON() : undefined + const safe = data ? clone(data) : undefined + if (safe?.api_key) safe.api_key = '' + if (safe?.credentials?.api_key) safe.credentials.api_key = '' + if (safe?.password) safe.password = '' + manifest.requests.push({ case: activeCase, mode, method: request.method(), path, body: safe }) + return data +} +async function routeAPI(route, state) { + const request = route.request(), url = new URL(request.url()), path = url.pathname.replace(/^\/api\/v1/, ''), method = request.method() + const body = recordRequest(request, path) + const ok = data => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ code: 0, message: 'success', data }) }) + const fail = (status, message) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify({ code: status, message }) }) + if (path === '/setup/status') return ok({ needs_setup: false, step: 'complete' }) + if (path === '/auth/me') return ok(user) + if (path === '/auth/login') return ok({ access_token: 'synthetic-ui-session', token_type: 'Bearer', expires_in: 3600, user }) + if (path === '/settings/public') return ok(publicSettings) + if (path === '/admin/system/check-updates') return ok({ current_version: 'fixture', latest_version: 'fixture', has_update: false, cached: true, build_type: 'source' }) + if (path === '/admin/accounts/antigravity/default-model-mapping') return ok({}) + if (path === '/keys') return ok({ items: [], total: 0, page: 1, pages: 0, page_size: 20 }) + if (path === '/admin/compliance') return ok({ required: false, version: 'fixture' }) + if (path === '/announcements' || path === '/subscriptions/active') return ok([]) + if (path === '/admin/settings') return ok({ ops_monitoring_enabled: false, ops_realtime_monitoring_enabled: false, custom_menu_items: [], web_search_emulation_enabled: false }) + if (path === '/admin/payment/config') return ok({ enabled: false }) + if (path === '/admin/settings/web-search-emulation') return ok({ enabled: false, providers: [] }) + if (path === '/admin/account-ops/token-guard-v2/encryption') return ok({ configured: true, source: 'server_config' }) + if (path === '/admin/account-ops/auto-config') return ok({ enabled: false, platform: 'openai', group_ids: [], concurrency: 1, priority: 50, load_factor: 1, revision: 'fixture' }) + if (path === '/admin/accounts/management-capabilities') return ok({ web_search_enabled: false, account_quota_notify_enabled: false, concurrency_upgrade_enabled: false }) + if (path === '/admin/accounts/upstream-billing-probe/settings') return ok({ enabled: false, interval_minutes: 30 }) + if (path === '/admin/accounts/upstream-billing-rates') return ok({ rates: {}, account_rates: {}, items: [], enabled: false }) + if (path === '/admin/ops/settings/metric-thresholds') return ok({ upstream_error_rate_percent_max: null }) + if (path === '/admin/accounts/performance') return ok({}) + if (path === '/admin/accounts/today-stats/batch') return ok({ stats: {} }) + if (path === '/admin/accounts/usage/batch') return ok({ accounts: {}, usage: {} }) + if (path === '/admin/proxies/all') return ok(proxies) + if (path === '/admin/groups/all') return ok(groups) + if (path === '/admin/groups') return ok({ items: groups, total: groups.length, page: 1, pages: 1, page_size: 100 }) + if (path === '/admin/tls-fingerprint-profiles') return ok([]) + if (path === '/admin/upstream-channels') return ok({ items: [], total: 0 }) + if (path === '/admin/upstream-channel-bindings') return ok({ items: [] }) + if (path === '/admin/accounts/check-mixed-channel') return ok({ has_risk: false }) + if (/^\/admin\/accounts\/\d+\/schedulable-timers$/.test(path)) return ok({ tasks: [], history: [], server_now: '2026-11-22T00:00:00Z', poll_seconds: 30, open_grace_seconds: 900, max_delay_minutes: 100 }) + if (path === '/admin/accounts/models/sync-upstream-preview') { + assert.equal(body.platform, 'gateway'); assert.equal(body.type, 'gateway') + assert(['new_api', 'sub2api'].includes(body.upstream_kind)) + const saved = body.account_id ? state.rows.get(body.account_id) : null + const resolvedKey = body.api_key || saved?.credentials.api_key + assert(resolvedKey, 'the synthetic server resolves a saved key when the browser leaves it blank') + assert(/^https:\/\/[^/]+\.example\.invalid(?:\/|$)/.test(body.base_url)) + assert([7, 8].includes(body.proxy_id), 'the selected fixture proxy must reach the HTTP contract') + state.previews.push({ ...clone(body), resolvedKey }) + const plan = state.previewPlan; state.previewPlan = null + if (plan === 'hold') await new Promise(done => { state.pending = done }) + if (plan === 'error') return fail(502, 'Synthetic upstream catalog unavailable') + return ok({ models: plan === 'hold' ? ['stale-result'] : ['live', 'removable'], discovery_source: 'upstream' }) + } + const sync = path.match(/^\/admin\/accounts\/(\d+)\/models\/sync-upstream$/) + if (sync) { + const row = state.rows.get(Number(sync[1])); assert(row) + assert.deepEqual(body, { apply: true, whitelist_only: true }) + if (state.applyPlan === 'hold') { + state.applyPlan = null + await new Promise(done => { state.pending = done }) + } + const mapping = { live: 'live', 'saved-fetched': 'saved-fetched' } + for (const [from, to] of Object.entries(row.credentials.model_mapping)) if (from !== to && to === 'live') mapping[from] = to + row.credentials.model_mapping = mapping + state.applies.push(row.id) + return ok({ models: ['live', 'saved-fetched'], applied: true, changed: true, discovery_source: 'upstream' }) + } + if (path === '/admin/accounts' && method === 'GET') { + const rows = [...state.rows.values()].map(redacted) + return ok({ items: rows, total: rows.length, page: 1, pages: 1, page_size: 20 }) + } + const accountPath = path.match(/^\/admin\/accounts\/(\d+)$/) + if (accountPath && method === 'GET') { + const row = state.rows.get(Number(accountPath[1])); assert(row) + manifest.readbacks.push({ case: activeCase, id: row.id, boundary: 'canonical HTTP fixture', mapping: clone(row.credentials.model_mapping), group_ids: clone(row.group_ids) }) + return ok(redacted(row)) + } + if ((path === '/admin/accounts' && method === 'POST') || (accountPath && method === 'PUT')) { + assert.equal(body.credentials.upstream_kind === 'new_api' || body.credentials.upstream_kind === 'sub2api', true) + const previous = accountPath ? state.rows.get(Number(accountPath[1])) : null + const id = previous?.id || state.nextID++ + const row = { ...(previous || initialAccount(body.credentials.upstream_kind, id)), ...clone(body), id, + credentials: { ...previous?.credentials, ...clone(body.credentials) } } + row.account_groups = row.group_ids.map(group_id => ({ group_id, priority: 50, allowed_models: clone(body.group_allowed_models?.[group_id] || []) })) + row.groups = groups.filter(group => row.group_ids.includes(group.id)) + assert(!row.group_ids.includes(103), 'OAuth-only groups are excluded by the actual selector') + state.rows.set(id, row) + manifest.saves.push({ case: activeCase, method, id, name: row.name, group_ids: clone(row.group_ids), mapping: clone(row.credentials.model_mapping), group_allowed_models: clone(body.group_allowed_models || {}), unrelated_preserved: row.credentials.unrelated_option?.keep === true, boundary: 'mock HTTP save, not database evidence' }) + return ok(redacted(row)) + } + manifest.unexpected.push({ case: activeCase, method, path }) + return fail(500, `Unexpected fixture endpoint: ${method} ${path}`) +} +const dialog = page => page.getByRole('dialog').filter({ has: page.locator('#create-account-form, #edit-account-form') }) +const settings = page => dialog(page).getByTestId('gateway-model-settings') +const fields = page => dialog(page).getByTestId('gateway-account-fields') +const rowFor = (page, name) => page.getByRole('row').filter({ hasText: name }) +const modelChip = (page, model) => settings(page).locator('span.inline-flex').filter({ has: page.getByText(model, { exact: true }) }) +const modelValues = page => settings(page).locator('span.inline-flex > span > span.truncate').allTextContents() +async function settle(page) { + await tick(page) + await page.waitForFunction(() => !document.querySelector('.modal-enter-active, .modal-leave-active')) +} +async function shot(page, name, locator) { + await locator.scrollIntoViewIfNeeded(); await settle(page) + await page.evaluate(() => document.fonts.ready) + await locator.screenshot({ path: join(output, name), animations: 'disabled' }) + manifest.screenshots.push({ name, case: activeCase, mode, actual_frontend_sha: mode === 'before' ? baseline : candidate, api: 'synthetic fixture' }) +} +async function openCreate(page, lang) { + assert.equal(await page.locator('#create-account-form').count(), 0, 'the real dialog starts closed') + await page.getByRole('button', { name: labels[lang].create, exact: true }).click() + await page.locator('#create-account-form').waitFor() + await page.getByTestId('platform-button-gateway').click() + await fields(page).waitFor(); await settle(page) +} +async function close(page) { + await dialog(page).getByRole('button', { name: 'Close modal', exact: true }).click() + await dialog(page).waitFor({ state: 'hidden' }); await settle(page) +} +async function openEdit(page, lang, name) { + assert.equal(await page.locator('#edit-account-form').count(), 0) + await rowFor(page, name).getByRole('button', { name: labels[lang].edit, exact: true }).click() + await page.locator('#edit-account-form').waitFor(); await fields(page).waitFor(); await settle(page) + assert.equal(await fields(page).locator('input[type=password]').inputValue(), '', 'saved calling key is never returned to the browser') +} +async function selectProxy(page, id) { + await dialog(page).locator('button.select-trigger').filter({ hasText: /Fixture proxy|No Proxy|不使用代理|无代理/ }).first().click() + await dialog(page).locator('.select-option').filter({ hasText: `Fixture proxy ${id}` }).click() +} +async function syncPreview(page, state) { + const count = state.previews.length + const response = page.waitForResponse(r => r.url().endsWith('/models/sync-upstream-preview')) + await settings(page).getByTestId('sync-upstream-models').click() + await response; await settle(page) + assert.equal(state.previews.length, count + 1) +} +async function save(page, method) { + const response = page.waitForResponse(r => /^\/api\/v1\/admin\/accounts(?:\/\d+)?$/.test(new URL(r.url()).pathname) && r.request().method() === method) + await page.locator(`button[type=submit][form="${method === 'POST' ? 'create' : 'edit'}-account-form"]`).click() + const actual = await response; assert.equal(actual.status(), 200) + const body = await actual.json(); assert.equal(body.code, 0) + await dialog(page).waitFor({ state: 'hidden' }); await settle(page) + return body.data.id +} +async function css(page, tag) { + const values = await settings(page).evaluate(node => { + const input = node.querySelector('input'), action = node.querySelector('[data-testid="sync-upstream-models"]') + const style = getComputedStyle(node), rect = node.getBoundingClientRect(), inputStyle = getComputedStyle(input) + return { width: rect.width, left: rect.left, right: rect.right, viewport: innerWidth, display: style.display, + inputBorder: inputStyle.borderTopWidth, inputBackground: inputStyle.backgroundColor, actionEnabled: !action.disabled, + dark: document.documentElement.classList.contains('dark') } + }) + assert(values.width > 250); assert(values.left >= 0 && values.right <= values.viewport) + assert.notEqual(values.inputBorder, '0px'); assert.equal(values.display, 'block'); assert(values.actionEnabled) + manifest.computed_css.push({ case: activeCase, tag, ...values }) + return values +} +try { + browser = await chromium.launch({ headless: true }) + for (const lang of ['en', 'zh']) { + activeCase = `${lang}-desktop` + const state = stateForCase() + const context = await browser.newContext({ viewport: { width: 1440, height: 1050 }, locale: lang === 'en' ? 'en-US' : 'zh-CN', serviceWorkers: 'block' }) + await context.addInitScript(({ user, lang, publicSettings }) => { + // Synthetic authenticated browser fixture, not a claim of real login. + if (!sessionStorage.getItem('gateway-fixture-initialized')) { + localStorage.setItem('auth_token', 'synthetic-ui-session'); localStorage.setItem('auth_user', JSON.stringify(user)) + localStorage.setItem('theme', 'light'); sessionStorage.setItem('gateway-fixture-initialized', 'true') + } + localStorage.setItem('sub2api_locale', lang) + localStorage.setItem('account-auto-refresh', JSON.stringify({ enabled: false })) + localStorage.setItem('admin_guide_1003_admin_v4_interactive', 'true') + localStorage.setItem('account-hidden-columns', JSON.stringify(['usage', 'today_stats', 'upstream_billing_rate', 'notes', 'scheduler_score', 'rate_multiplier'])) + window.__APP_CONFIG__ = publicSettings + }, { user, lang, publicSettings }) + await context.route('**/*', async route => { + const url = new URL(route.request().url()) + if (url.origin !== origin && !['data:', 'blob:', 'about:'].includes(url.protocol)) { + manifest.external.push({ origin: url.origin, path: url.pathname }); return route.abort('blockedbyclient') + } + if (url.pathname.startsWith('/api/v1/') || url.pathname.startsWith('/setup/')) { + try { + return await routeAPI(route, state) + } catch (error) { + manifest.errors.push({ case: activeCase, mode, path: url.pathname, message: error.message, stack: error.stack }) + return route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ code: 500, message: 'Fixture contract assertion failed' }) }) + } + } + return route.continue() + }) + const page = await context.newPage(); activePage = page; page.setDefaultTimeout(20000) + page.on('pageerror', error => manifest.errors.push({ case: activeCase, mode, message: error.message, stack: error.stack })) + mode = 'before'; await page.goto(origin + '/admin/accounts') + await page.getByRole('button', { name: labels[lang].create, exact: true }).waitFor() + for (const kind of ['new_api', 'sub2api']) { + await openCreate(page, lang); await fields(page).locator('select').selectOption(kind) + assert.equal(await settings(page).count(), 0) + assert.equal(await dialog(page).getByTestId('sync-upstream-models').count(), 0) + await shot(page, `before-create-${kind}-${lang}.png`, fields(page)); await close(page) + await openEdit(page, lang, `Fixture ${kind}`) + assert.equal(await settings(page).count(), 0) + await shot(page, `before-edit-${kind}-${lang}.png`, fields(page)); await close(page) + } + assert.equal(await page.getByTestId('gateway-sync-saved').count(), 0) + manifest.assertions.push({ case: activeCase, baseline_gateway_controls_absent: true }) + + mode = 'after'; await page.reload() + await page.getByTestId('gateway-sync-saved').first().waitFor() + if (lang === 'en') { + await page.goto(`${origin}/pr838-notices.html?phase=a&user=1003`) + await page.getByTestId('notice-A-0').getByTestId('new-feature-badge').click() + await page.goto(origin + '/admin/accounts') + } + for (const kind of ['new_api', 'sub2api']) { + await openCreate(page, lang) + await fields(page).locator('select').selectOption(kind) + const name = `Untouched ${kind} ${lang}` + await page.locator('[data-tour="account-form-name"]').fill(name) + await fields(page).locator('input[type=url]').fill('https://untouched.example.invalid') + await fields(page).locator('input[type=password]').fill('synthetic-untouched-key') + await selectProxy(page, 7) + await dialog(page).locator('[data-tour="account-form-groups"] input[value="101"]').check() + const previewsBefore = state.previews.length + assert.deepEqual(await modelValues(page), [], 'gateway model defaults must remain unrestricted') + assert.equal(await settings(page).getByRole('textbox', { name: labels[lang].from, exact: true }).count(), 0) + await shot(page, `after-create-untouched-${kind}-${lang}.png`, settings(page)) + const id = await save(page, 'POST') + assert.deepEqual(state.rows.get(id).credentials.model_mapping, {}) + assert.equal(state.previews.length, previewsBefore, 'untouched create must not fetch models') + await openEdit(page, lang, name) + assert.deepEqual(await modelValues(page), []) + await close(page) + manifest.assertions.push({ lang, kind, untouched_create_empty_mapping: true, mock_readback_unrestricted: true }) + } + for (const kind of ['new_api', 'sub2api']) { + await openCreate(page, lang) + await fields(page).locator('select').selectOption(kind) + await page.locator('[data-tour="account-form-name"]').fill(`Created ${kind} ${lang}`) + await fields(page).locator('input[type=url]').fill(`https://${kind.replace('_', '-')}.example.invalid/create`) + await fields(page).locator('input[type=password]').fill(`synthetic-create-${kind}`) + await selectProxy(page, 7) + const groupScope = dialog(page).locator('[data-tour="account-form-groups"]') + assert.equal(await groupScope.locator('input[value="103"]').count(), 0) + await groupScope.locator('input[value="101"]').check() + assert.equal(await settings(page).getByTestId('sync-upstream-models').isEnabled(), true) + if (kind === 'new_api') { + state.previewPlan = 'hold' + const received = page.waitForRequest(r => r.url().endsWith('/models/sync-upstream-preview')) + await settings(page).getByTestId('sync-upstream-models').click(); await received + await page.waitForFunction(() => document.querySelector('[data-testid="gateway-model-settings"] [data-testid="sync-upstream-models"]').disabled) + await shot(page, `after-loading-${lang}.png`, settings(page)) + await fields(page).locator('input[type=url]').fill('https://changed.example.invalid/create') + assert(await settings(page).getByTestId('sync-upstream-models').isEnabled()) + const staleResponse = page.waitForResponse(r => r.url().endsWith('/models/sync-upstream-preview')) + assert(state.pending); state.pending(); state.pending = null; await staleResponse; await settle(page) + assert.deepEqual(await modelValues(page), [], 'old connection response must not alter the new draft') + state.previewPlan = 'error'; await syncPreview(page, state) + assert.deepEqual(await modelValues(page), []) + await page.getByText(/Synthetic upstream catalog unavailable/).waitFor() + await shot(page, `after-error-${lang}.png`, page.locator('body')) + } + await syncPreview(page, state) + assert.equal(state.previews.at(-1).upstream_kind, kind) + assert.equal(state.previews.at(-1).api_key, `synthetic-create-${kind}`) + assert.deepEqual(await modelValues(page), ['live', 'removable']) + await modelChip(page, 'removable').getByRole('button').click() + await settings(page).getByPlaceholder(labels[lang].custom, { exact: true }).fill('manual') + await settings(page).getByRole('button', { name: labels[lang].add, exact: true }).click() + await settings(page).getByRole('button', { name: labels[lang].addMapping, exact: true }).click() + await settings(page).getByRole('textbox', { name: labels[lang].from, exact: true }).fill('public') + await settings(page).getByRole('textbox', { name: labels[lang].to, exact: true }).fill('live') + assert.deepEqual(await modelValues(page), ['live', 'manual']) + await css(page, 'desktop-light') + await shot(page, `after-create-configured-${kind}-${lang}.png`, settings(page)) + const id = await save(page, 'POST') + assert.deepEqual(state.rows.get(id).credentials.model_mapping, { live: 'live', manual: 'manual', public: 'live' }) + await openEdit(page, lang, `Created ${kind} ${lang}`) + assert.deepEqual(await modelValues(page), ['live', 'manual']) + assert.equal(await settings(page).getByRole('textbox', { name: labels[lang].from, exact: true }).inputValue(), 'public') + await close(page) + await openEdit(page, lang, `Fixture ${kind}`) + await fields(page).locator('input[type=url]').fill(`https://edited.example.invalid/${kind}`) + await selectProxy(page, 8) + await syncPreview(page, state) + const preview = state.previews.at(-1) + assert.equal(preview.account_id, kind === 'new_api' ? 51 : 52) + assert.equal(preview.api_key, ''); assert.equal(preview.resolvedKey, `synthetic-saved-${kind}`) + assert.equal(preview.proxy_id, 8) + await fields(page).locator('input[type=password]').fill(`synthetic-rotated-${kind}`) + await syncPreview(page, state) + assert.equal(state.previews.at(-1).resolvedKey, `synthetic-rotated-${kind}`) + await settings(page).getByRole('textbox', { name: labels[lang].from, exact: true }).fill('public-edited') + await modelChip(page, 'removable').getByRole('button').click() + await dialog(page).locator('[data-tour="account-form-groups"] input[value="101"]').uncheck() + await dialog(page).locator('[data-tour="account-form-groups"] input[value="102"]').check() + const binding = dialog(page).getByTestId('group-model-limit-102') + await binding.getByTestId('group-model-limit-selected').click() + await binding.getByPlaceholder(labels[lang].custom, { exact: true }).fill('live') + await binding.getByRole('button', { name: labels[lang].add, exact: true }).click() + await shot(page, `after-edit-configured-${kind}-${lang}.png`, settings(page)) + const editedID = await save(page, 'PUT') + assert.deepEqual(state.rows.get(editedID).credentials.model_mapping, { live: 'live', 'public-edited': 'live' }) + assert.deepEqual(state.rows.get(editedID).credentials.unrelated_option, { keep: true }) + assert.deepEqual(state.rows.get(editedID).group_ids, [102]) + assert.deepEqual(state.rows.get(editedID).account_groups[0].allowed_models, ['live']) + await openEdit(page, lang, `Fixture ${kind}`) + assert.deepEqual(await modelValues(page), ['live']) + assert.equal(await settings(page).getByRole('textbox', { name: labels[lang].from, exact: true }).inputValue(), 'public-edited') + assert.equal(await dialog(page).getByTestId('group-model-limit-102').getByText('live', { exact: true }).count(), 1) + await close(page) + const before = state.applies.length + const applied = page.waitForResponse(r => r.url().includes(`/${editedID}/models/sync-upstream`)) + if (kind === 'new_api') state.applyPlan = 'hold' + await rowFor(page, `Fixture ${kind}`).getByTestId('gateway-sync-saved').click() + if (kind === 'new_api') { + await page.waitForFunction(name => [...document.querySelectorAll('[data-testid="gateway-sync-saved"]')] + .some(button => button.closest('tr')?.textContent.includes(name) && button.disabled), `Fixture ${kind}`) + await shot(page, `after-saved-action-loading-${lang}.png`, rowFor(page, `Fixture ${kind}`)) + assert(state.pending); state.pending(); state.pending = null + } + await applied + await settle(page); assert.equal(state.applies.length, before + 1) + await openEdit(page, lang, `Fixture ${kind}`) + assert.deepEqual(await modelValues(page), ['live', 'saved-fetched']) + assert.equal(await settings(page).getByRole('textbox', { name: labels[lang].from, exact: true }).inputValue(), 'public-edited') + await shot(page, `after-saved-action-readback-${kind}-${lang}.png`, settings(page)); await close(page) + } + assert.deepEqual(groups, state.groupSnapshot, 'HTTP fixture never distributes a fetched list to joined groups') + await openCreate(page, lang) + await fields(page).locator('input[type=password]').fill('synthetic-style-key') + await selectProxy(page, 7) + const light = await css(page, 'light-before-dark') + if (lang === 'en') { + assert.equal(await settings(page).getByTestId('new-feature-badge').count(), 1, 'new B remains visible after actual A dismissal') + const listNotice = rowFor(page, 'Fixture new_api').locator('[data-testid="gateway-sync-saved"] + [data-testid="new-feature-badge"]') + assert.equal(await listNotice.count(), 1, 'list entry shares B before dismissal') + await settings(page).getByTestId('new-feature-badge').click(); await close(page) + await listNotice.waitFor({ state: 'detached' }) + await openEdit(page, lang, 'Fixture new_api') + assert.equal(await settings(page).getByTestId('new-feature-badge').count(), 0, 'same dismissal hides actual Edit entry') + await close(page); await page.reload(); await openCreate(page, lang) + assert.equal(await settings(page).getByTestId('new-feature-badge').count(), 0) + await close(page) + await page.evaluate(() => { localStorage.removeItem('auth_token'); localStorage.removeItem('auth_user') }) + await page.goto(origin + '/login?redirect=/admin/accounts') + await page.locator('#email').fill('reviewer@example.invalid'); await page.locator('#password').fill('synthetic-login-password') + await page.locator('button[type=submit]').click(); await page.waitForURL(url => url.pathname !== '/login') + await page.goto(origin + '/admin/accounts'); await openEdit(page, lang, 'Fixture new_api') + assert.equal(await settings(page).getByTestId('new-feature-badge').count(), 0) + await close(page) + await page.goto(`${origin}/pr838-notices.html?phase=c&user=1003`) + assert.equal(await page.getByTestId('notice-A-0').getByTestId('new-feature-badge').count(), 0) + assert.equal(await page.getByTestId('notice-B-1').getByTestId('new-feature-badge').count(), 0) + await page.getByTestId('notice-C-3').getByTestId('new-feature-badge').waitFor() + await shot(page, 'after-notice-future-C.png', page.locator('main')) + await page.goto(origin + '/admin/accounts'); await openCreate(page, lang) + manifest.assertions.push({ notice_actual_create_edit_list_shared: true, refresh_and_mock_relogin_persistent: true, A_B_C_independent: true }) + } + await fields(page).locator('input[type=url]').fill('https://narrow.example.invalid') + await fields(page).locator('input[type=password]').fill('synthetic-narrow-key'); await selectProxy(page, 7) + await page.evaluate(() => { localStorage.setItem('theme', 'dark'); document.documentElement.classList.add('dark') }) + await page.setViewportSize({ width: 430, height: 950 }); activeCase = `${lang}-narrow-dark` + // Wait for the input's real color transition before sampling and capturing it. + await settings(page).locator('input').first().evaluate(async input => { + getComputedStyle(input).backgroundColor + await Promise.all(input.getAnimations().map(animation => animation.finished)) + }) + const dark = await css(page, 'narrow-dark'); assert(dark.dark); assert.notEqual(light.inputBackground, dark.inputBackground) + await shot(page, `after-narrow-dark-${lang}.png`, settings(page)) + await syncPreview(page, state); assert.deepEqual(await modelValues(page), ['live', 'removable']) + await close(page) + manifest.assertions.push({ lang, both_kinds: true, closed_open_transitions: true, previews_own_connection: true, + whitelist_remove_add: true, alias_edit: true, mock_save_readback: true, saved_action: true, + errors_loading_stale_response: true, OAuth_only_group_hidden: true, group_config_unchanged: true }) + await context.close(); activePage = null + } + assert.deepEqual(manifest.unexpected, []); assert.deepEqual(manifest.errors, []); assert.deepEqual(manifest.external, []) + manifest.complete = true +} catch (error) { + manifest.errors.push({ case: activeCase, mode, message: error.message, stack: error.stack }) + if (activePage) { + writeFileSync(join(output, 'failure.txt'), await activePage.locator('body').innerText()) + await activePage.screenshot({ path: join(output, 'failure.png'), fullPage: true }) + } + throw error +} finally { + writeFileSync(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n') + if (browser) await browser.close() + await new Promise(done => server.close(done)) +} diff --git a/.github/scripts/pr838-ui-build.mjs b/.github/scripts/pr838-ui-build.mjs index d9193fe5141b..17d4e1f5a0c8 100644 --- a/.github/scripts/pr838-ui-build.mjs +++ b/.github/scripts/pr838-ui-build.mjs @@ -6,10 +6,14 @@ import { pathToFileURL } from 'node:url' const repo = resolve('.'), output = process.env.EVIDENCE_DIR if (!output || process.env.GITHUB_ACTIONS !== 'true') throw Error('Isolated CI only') +const baselineRoot = resolve(process.env.BASELINE_FRONTEND_ROOT || '.pr838-baseline/frontend') +const noticeKeys = process.env.EVIDENCE_SCENARIO === 'gateway-models' + ? { A: 'crossPlatformGatewayAccounts', B: 'gatewayModelSync', C: 'fixture-gateway-models-future-announcement-C' } + : { A: 'vipAutoCredit', B: 'tempUnschedStreamCountWindow', C: 'fixture-pr838-future-announcement-C' } mkdirSync(output, { recursive: true }) const { build } = await import(pathToFileURL(join(repo, 'frontend/node_modules/vite/dist/node/index.js'))) for (const mode of ['before', 'after']) { - const root = join(repo, mode === 'before' ? '.pr838-baseline/frontend' : 'frontend') + const root = mode === 'before' ? baselineRoot : join(repo, 'frontend') const extra = join(root, 'pr838-notices.html'), entry = join(root, '.pr838-notices.js') try { if (mode === 'after') { @@ -22,7 +26,9 @@ import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';import '/src/style.cs async function mountNotices(){ await loadLocaleMessages('en');i18n.global.locale.value='en'; // Future C is deliberately a test-only registered ID, not a product announcement. -const registry={A:ids.vipAutoCredit,B:ids.tempUnschedStreamCountWindow,C:'fixture-pr838-future-announcement-C'}; +const keys=${JSON.stringify(noticeKeys)}; +const registry={A:ids[keys.A],B:ids[keys.B],C:keys.C}; +if(!registry.A||!registry.B)throw Error('Requested notice IDs must exist in the actual candidate registry'); const p=new URLSearchParams(location.search), phase=p.get('phase')||'a',user=Number(p.get('user')); if(!Number.isSafeInteger(user)||user<1)throw Error('Fictional fixture administrator required'); const entries=phase==='a'?['A']:phase==='b'?['A','B','B']:['A','B','B','C']; diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 0fce8d978b67..70c57af98c84 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -10,6 +10,7 @@ on: - 'backend/internal/handler/admin/account*' - 'backend/internal/handler/dto/account_mapper_redact_test.go' - 'backend/internal/repository/account_repo.go' + - 'backend/internal/repository/account_repo_upstream_model_sync*' - 'backend/internal/repository/group_repo.go' - 'backend/internal/repository/gateway_account*' - 'backend/internal/repository/gateway_request_admission*' @@ -84,7 +85,7 @@ jobs: run: | set -euo pipefail go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin ./internal/handler/dto ./internal/repository \ - -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayProtocol|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \ + -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayProtocol|GatewayUpstreamModels|AccountHandlerGatewayModels|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/unit-race.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/unit-race.log; then exit 1 @@ -94,6 +95,9 @@ jobs: grep -F -- '--- PASS: TestUsagePlatformSnapshotsSelectedAccount' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementForwardingRemainsClosed' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayUpstreamModelsDiscoveryAndApply' ../evidence/unit-race.log + grep -F -- '--- PASS: TestAccountHandlerGatewayModelsDraftAndSavedConnection' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolCatalogSavedModelsAndGroupPrecedence' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolOpenAIAuthoritativeAdmission' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolOpenAIRejectsFinalAuthorityChanges' ../evidence/unit-race.log @@ -148,6 +152,16 @@ jobs: grep -F -- '--- PASS: TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge' ../evidence/procurement-cost.log grep -F -- '--- PASS: TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns' ../evidence/procurement-cost.log grep -F -- '--- PASS: TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched' ../evidence/procurement-cost.log + - name: Gateway account-only model persistence + working-directory: backend + shell: bash + run: | + set -euo pipefail + go test -race -tags=integration ./internal/repository \ + -run '^Test(GatewayUpstreamModelsPersistOnlyAccountMapping|ApplyUpstreamModelsPreservesCredentialsAndInvalidatesScheduler)$' \ + -count=1 -v -timeout=10m 2>&1 | tee ../evidence/gateway-model-persistence.log + if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/gateway-model-persistence.log; then exit 1; fi + grep -F -- '--- PASS: TestGatewayUpstreamModelsPersistOnlyAccountMapping' ../evidence/gateway-model-persistence.log - uses: actions/upload-artifact@v7 if: always() with: diff --git a/.github/workflows/pr838-ui-acceptance.yml b/.github/workflows/pr838-ui-acceptance.yml index cab87e34d0af..0da73ec8f5e6 100644 --- a/.github/workflows/pr838-ui-acceptance.yml +++ b/.github/workflows/pr838-ui-acceptance.yml @@ -1,5 +1,16 @@ name: PR838 isolated administration acceptance on: + workflow_dispatch: + inputs: + scenario: + type: choice + options: [pr838, gateway-models] + default: gateway-models + description: Actual application acceptance scenario + candidate: + type: string + required: true + description: Exact candidate commit SHA (must match the dispatched workflow ref) pull_request: branches: [production] paths: @@ -7,6 +18,7 @@ on: - 'frontend/src/stores/newFeatureNotices.ts' - '.github/fixtures/pr838-ui/**' - '.github/scripts/pr838-ui-*.mjs' + - '.github/scripts/gateway-models-ui.mjs' - '.github/workflows/pr838-ui-acceptance.yml' permissions: contents: read @@ -15,10 +27,11 @@ concurrency: cancel-in-progress: true jobs: administration: + if: github.event_name == 'pull_request' || inputs.scenario == 'pr838' runs-on: ubuntu-24.04 timeout-minutes: 40 env: - CANDIDATE: ${{ github.event.pull_request.head.sha }} + CANDIDATE: ${{ github.event.pull_request.head.sha || inputs.candidate }} # Full production frontend before this feature; never overlay components. BASELINE: b347249687db84dac3f5272189fda6cf86eb9035 steps: @@ -114,3 +127,122 @@ jobs: ${{ runner.temp }}/pr838-ui/*.png if-no-files-found: error retention-days: 30 + + gateway-models: + if: github.event_name == 'workflow_dispatch' && inputs.scenario == 'gateway-models' + runs-on: ubuntu-24.04 + timeout-minutes: 35 + env: + CANDIDATE: ${{ inputs.candidate }} + BASELINE: c76d8d3de146408e35b79814955088b355c66135 + EVIDENCE_SCENARIO: gateway-models + NODE_OPTIONS: --max-old-space-size=6144 + steps: + - name: Require immutable candidate from the selected workflow revision + env: + WORKFLOW_SHA: ${{ github.sha }} + run: | + set -euo pipefail + [[ "$CANDIDATE" =~ ^[0-9a-f]{40}$ ]] + test "$CANDIDATE" = "$WORKFLOW_SHA" + - uses: actions/checkout@v6 + with: + ref: ${{ env.CANDIDATE }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/checkout@v6 + with: + ref: ${{ env.BASELINE }} + path: .gateway-models-baseline + persist-credentials: false + - uses: pnpm/action-setup@v6 + with: + version: 9 + - uses: actions/setup-node@v6 + with: + node-version: '22' + cache: pnpm + cache-dependency-path: frontend/pnpm-lock.yaml + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Configure isolated evidence and verify original source trees + run: | + set -euo pipefail + printf 'EVIDENCE_DIR=%s/gateway-models-evidence\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + printf 'BASELINE_FRONTEND_ROOT=%s/.gateway-models-baseline/frontend\n' "$GITHUB_WORKSPACE" >> "$GITHUB_ENV" + printf 'SUB2API_PLAYWRIGHT_MODULE=%s/gateway-models-browser/node_modules/playwright/index.mjs\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + test "$(git rev-parse HEAD)" = "$CANDIDATE" + test "$(git -C .gateway-models-baseline rev-parse HEAD)" = "$BASELINE" + cmp frontend/package.json .gateway-models-baseline/frontend/package.json + cmp frontend/pnpm-lock.yaml .gateway-models-baseline/frontend/pnpm-lock.yaml + - name: Prepare locked frontend and isolated browser on remote runner only + run: | + set -euo pipefail + mkdir -p "$EVIDENCE_DIR" + git rev-parse HEAD > "$EVIDENCE_DIR/candidate.txt" + git -C .gateway-models-baseline rev-parse HEAD > "$EVIDENCE_DIR/baseline.txt" + pnpm --dir frontend install --frozen-lockfile + npm install --prefix "$RUNNER_TEMP/gateway-models-browser" --no-save --ignore-scripts playwright@1.56.1 + node "$RUNNER_TEMP/gateway-models-browser/node_modules/playwright/cli.js" install --with-deps chromium + - name: Same gateway discovery oracle on candidate and disposable original base + shell: bash + run: | + set -euo pipefail + oracle=backend/internal/service/gateway_upstream_models_test.go + sha256sum "$oracle" > "$EVIDENCE_DIR/oracle.sha256" + git -C .gateway-models-baseline status --porcelain > "$EVIDENCE_DIR/baseline-before-oracle.txt" + test ! -s "$EVIDENCE_DIR/baseline-before-oracle.txt" + cp "$oracle" ".gateway-models-baseline/$oracle" + status=0 + (cd .gateway-models-baseline/backend && go test -tags=unit ./internal/service -run '^TestGatewayUpstreamModelsDiscoveryAndApply$' -count=1 -v -timeout=10m) > "$EVIDENCE_DIR/discovery-red.log" 2>&1 || status=$? + printf '%s\n' "$status" > "$EVIDENCE_DIR/discovery-red-exit.txt" + cat "$EVIDENCE_DIR/discovery-red.log" + test "$status" -ne 0 + grep -F 'Unsupported platform for upstream model sync: gateway' "$EVIDENCE_DIR/discovery-red.log" + if grep -Eq 'build failed|setup failed|undefined:|no tests to run|--- SKIP:|panic:|WARNING: DATA RACE' "$EVIDENCE_DIR/discovery-red.log"; then exit 1; fi + for kind in new_api sub2api; do + for action in discovery apply; do + grep -F -- "--- FAIL: TestGatewayUpstreamModelsDiscoveryAndApply/$kind/$action" "$EVIDENCE_DIR/discovery-red.log" + done + done + status=0 + (cd backend && go test -tags=unit ./internal/service -run '^TestGatewayUpstreamModelsDiscoveryAndApply$' -count=1 -v -timeout=10m) > "$EVIDENCE_DIR/discovery-green.log" 2>&1 || status=$? + printf '%s\n' "$status" > "$EVIDENCE_DIR/discovery-green-exit.txt" + cat "$EVIDENCE_DIR/discovery-green.log" + test "$status" -eq 0 + if grep -Eq 'no tests to run|--- SKIP:' "$EVIDENCE_DIR/discovery-green.log"; then exit 1; fi + for kind in new_api sub2api; do + for action in discovery apply; do + grep -F -- "--- PASS: TestGatewayUpstreamModelsDiscoveryAndApply/$kind/$action" "$EVIDENCE_DIR/discovery-green.log" + done + done + - name: Render complete original before and candidate applications with project CSS + id: gateway-build + if: ${{ !cancelled() }} + run: | + set -euo pipefail + ln -s "$GITHUB_WORKSPACE/frontend/node_modules" .gateway-models-baseline/frontend/node_modules + node .github/scripts/pr838-ui-build.mjs 2>&1 | tee "$EVIDENCE_DIR/build.log" + - name: Real dialog transitions with canonical synthetic API fixtures + if: ${{ !cancelled() && steps.gateway-build.outcome == 'success' }} + run: | + set -euo pipefail + status=0 + node .github/scripts/gateway-models-ui.mjs > "$EVIDENCE_DIR/browser.log" 2>&1 || status=$? + printf '%s\n' "$status" > "$EVIDENCE_DIR/browser-exit.txt" + cat "$EVIDENCE_DIR/browser.log" + exit "$status" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: gateway-models-${{ env.CANDIDATE }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/gateway-models-evidence/*.json + ${{ runner.temp }}/gateway-models-evidence/*.txt + ${{ runner.temp }}/gateway-models-evidence/*.log + ${{ runner.temp }}/gateway-models-evidence/*.sha256 + ${{ runner.temp }}/gateway-models-evidence/*.png + if-no-files-found: error + retention-days: 30 diff --git a/Makefile b/Makefile index 75004f36c0e3..272c45c77a70 100644 --- a/Makefile +++ b/Makefile @@ -84,6 +84,7 @@ FRONTEND_CRITICAL_VITEST := \ src/views/admin/__tests__/AccountQualityView.spec.ts \ src/views/admin/__tests__/AccountsView.bulkEdit.spec.ts \ src/views/admin/__tests__/AccountsView.declarationRefresh.spec.ts \ + src/views/admin/__tests__/AccountsView.newAPIConfig.spec.ts \ src/utils/__tests__/accountUpstreamModelAutoSync.spec.ts \ src/utils/__tests__/qualityRulePatch.spec.ts \ src/components/admin/operations/__tests__/QualityOwnershipReview.spec.ts \ diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 858ed72e44f0..0eb9fc4f2026 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -3415,14 +3415,36 @@ func (h *AccountHandler) SyncUpstreamModelsPreview(c *gin.Context) { Platform string `json:"platform" binding:"required"` Type string `json:"type" binding:"required"` BaseURL string `json:"base_url"` - APIKey string `json:"api_key" binding:"required"` + APIKey string `json:"api_key"` + AccountID *int64 `json:"account_id" binding:"omitempty,gt=0"` ProxyID *int64 `json:"proxy_id" binding:"omitempty,gte=0"` ModelMapping map[string]string `json:"model_mapping"` + UpstreamKind string `json:"upstream_kind"` } if err := c.ShouldBindJSON(&req); err != nil { response.BadRequest(c, "Invalid request: "+err.Error()) return } + // Gateway edits may preview a draft URL/proxy without returning the saved + // calling key to the browser. Resolve only an accessible gateway account. + if req.AccountID != nil { + if _, observer := service.ObserverGroupIDs(c.Request.Context()); observer { + response.ErrorFrom(c, service.ErrObserverScope) + return + } + account, err := h.adminService.GetAccount(c.Request.Context(), *req.AccountID) + if err != nil || account == nil || !account.IsGateway() || req.Platform != service.PlatformGateway || req.Type != service.AccountTypeGateway { + response.BadRequest(c, "Invalid gateway preview account") + return + } + if strings.TrimSpace(req.APIKey) == "" { + req.APIKey = account.GetCredential("api_key") + } + } + if strings.TrimSpace(req.APIKey) == "" { + response.BadRequest(c, "API key is required") + return + } modelMapping := make(map[string]any, len(req.ModelMapping)) for sourceModel, upstreamModel := range req.ModelMapping { modelMapping[sourceModel] = upstreamModel @@ -3432,6 +3454,7 @@ func (h *AccountHandler) SyncUpstreamModelsPreview(c *gin.Context) { Platform: req.Platform, Type: req.Type, Credentials: map[string]any{ + "upstream_kind": req.UpstreamKind, "api_key": req.APIKey, "base_url": req.BaseURL, "model_mapping": modelMapping, diff --git a/backend/internal/handler/admin/account_handler_gateway_models_test.go b/backend/internal/handler/admin/account_handler_gateway_models_test.go new file mode 100644 index 000000000000..7f17b2b8c3c4 --- /dev/null +++ b/backend/internal/handler/admin/account_handler_gateway_models_test.go @@ -0,0 +1,100 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +type gatewayPreviewAdminService struct { + *availableModelsAdminService +} + +func (s *gatewayPreviewAdminService) GetProxy(context.Context, int64) (*service.Proxy, error) { + return nil, nil +} + +func TestAccountHandlerGatewayModelsDraftAndSavedConnection(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + for _, draft := range []bool{false, true} { + t.Run(kind+map[bool]string{false: "/saved", true: "/draft"}[draft], func(t *testing.T) { + svc := &availableModelsAdminService{stubAdminService: newStubAdminService(), account: service.Account{ + ID: 1003, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": kind, "base_url": "https://saved.example/v1", "api_key": "saved-synthetic-key"}, + }} + upstream := &syncUpstreamHTTPUpstream{resp: &http.Response{StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"live"}]}`))}} + router := setupSyncUpstreamModelsRouter(svc, upstream) + path, payload := "/api/v1/admin/accounts/1003/models/sync-upstream", map[string]any{} + if draft { + path = "/api/v1/admin/accounts/models/sync-upstream-preview" + payload = map[string]any{"platform": "gateway", "type": "gateway", "upstream_kind": kind, + "account_id": 1003, "base_url": "https://draft.example/tenant", "api_key": ""} + } + body, err := json.Marshal(payload) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(body))) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Len(t, upstream.requests, 1) + wantURL := "https://saved.example/v1/models" + if draft { + wantURL = "https://draft.example/tenant/v1/models" + } + require.Equal(t, wantURL, upstream.requests[0].URL.String()) + require.Equal(t, "Bearer saved-synthetic-key", upstream.requests[0].Header.Get("Authorization")) + require.Contains(t, rec.Body.String(), `"discovery_source":"upstream"`) + require.NotContains(t, rec.Body.String(), "saved-synthetic-key") + }) + } + } +} + +func TestAccountHandlerGatewayModelsPreviewRejectsObserverAndMissingProxy(t *testing.T) { + for _, scenario := range []string{"observer", "proxy", "invalid-kind", "missing-key"} { + t.Run(scenario, func(t *testing.T) { + svc := &availableModelsAdminService{stubAdminService: newStubAdminService(), account: service.Account{ + ID: 1003, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://saved.example", "api_key": "synthetic-key"}, + }} + payload := map[string]any{"platform": "gateway", "type": "gateway", "upstream_kind": "new_api", + "base_url": "https://draft.example", "api_key": "synthetic-key"} + want := http.StatusBadRequest + switch scenario { + case "observer": + payload["account_id"] = 1003 + want = http.StatusForbidden + case "proxy": + payload["proxy_id"] = 7 + case "invalid-kind": + payload["upstream_kind"] = "other" + case "missing-key": + delete(payload, "api_key") + } + upstream := &syncUpstreamHTTPUpstream{} + router := setupSyncUpstreamModelsRouter(&gatewayPreviewAdminService{availableModelsAdminService: svc}, upstream) + body, err := json.Marshal(payload) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/models/sync-upstream-preview", strings.NewReader(string(body))) + req.Header.Set("Content-Type", "application/json") + if scenario == "observer" { + req = req.WithContext(service.WithObserverScope(req.Context(), []int64{1})) + } + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + require.Equal(t, want, rec.Code, rec.Body.String()) + require.Empty(t, upstream.requests) + }) + } +} diff --git a/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go b/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go index 2dadb9336fde..8902247ef54e 100644 --- a/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go +++ b/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go @@ -88,6 +88,40 @@ func TestApplyUpstreamModelsPreservesCredentialsAndInvalidatesScheduler(t *testi require.Len(t, cache.setAccounts, 1, "a skipped CAS must not publish a stale scheduler snapshot") } +func TestGatewayUpstreamModelsPersistOnlyAccountMapping(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + t.Run(kind, func(t *testing.T) { + ctx := t.Context() + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "gateway-model-sync", Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": kind, "api_key": "synthetic-key", "base_url": "https://relay.example", + "unrelated": map[string]any{"keep": true}, "model_mapping": map[string]any{"old": "old"}}, + }) + group, err := tx.Client().Group.Create().SetName("gateway-model-group").SetPlatform(service.PlatformOpenAI).Save(ctx) + require.NoError(t, err) + require.NoError(t, repo.BindGroups(ctx, account.ID, []int64{group.ID})) + beforeGroup, err := tx.Client().Group.Get(ctx, group.ID) + require.NoError(t, err) + expected, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + applied, err := repo.UpdateUpstreamModelMappingIfUnchanged(ctx, expected, map[string]string{"live": "live", "public": "live"}) + require.NoError(t, err) + require.True(t, applied) + latest, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, "synthetic-key", latest.GetCredential("api_key")) + require.Equal(t, map[string]any{"keep": true}, latest.Credentials["unrelated"]) + require.Equal(t, map[string]any{"live": "live", "public": "live"}, latest.Credentials["model_mapping"]) + require.Equal(t, []int64{group.ID}, latest.GroupIDs) + afterGroup, err := tx.Client().Group.Get(ctx, group.ID) + require.NoError(t, err) + require.Equal(t, beforeGroup.ModelAllowlist, afterGroup.ModelAllowlist, "fetch/apply must never distribute models into groups") + }) + } +} + func TestOAuthDegradationNativeModelSyncFencesAccountAvailabilityChanges(t *testing.T) { for _, change := range []string{"scheduling paused", "status changed"} { t.Run(change, func(t *testing.T) { diff --git a/backend/internal/service/gateway_account_management_test.go b/backend/internal/service/gateway_account_management_test.go index 0420cee59e62..619c32e41865 100644 --- a/backend/internal/service/gateway_account_management_test.go +++ b/backend/internal/service/gateway_account_management_test.go @@ -108,6 +108,8 @@ func TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups(t *t func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *testing.T) { a := gatewayManagementFixture() + a.Credentials["model_mapping"] = map[string]any{"public": "upstream"} + a.Credentials["unknown_option"] = map[string]any{"keep": true} repo := &gatewayManagementAtomicRepo{accountRepoStubForBulkUpdate: &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{959: a}}} svc := &adminServiceImpl{accountRepo: repo} updated, err := svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{ @@ -116,6 +118,14 @@ func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *test require.Equal(t, 1, repo.transactions) require.Equal(t, "synthetic-key", updated.Credentials["api_key"]) require.Equal(t, "new_api", updated.Credentials["upstream_kind"]) + require.Equal(t, map[string]any{"public": "upstream"}, updated.Credentials["model_mapping"]) + require.Equal(t, map[string]any{"keep": true}, updated.Credentials["unknown_option"]) + _, err = svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{Credentials: map[string]any{"api_key": "rotated-synthetic-key"}}) + require.NoError(t, err) + _, err = svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{GroupIDs: &[]int64{}}) + require.NoError(t, err) + require.Equal(t, map[string]any{"public": "upstream"}, a.Credentials["model_mapping"]) + require.Equal(t, map[string]any{"keep": true}, a.Credentials["unknown_option"]) for _, input := range []*UpdateAccountInput{{Platform: PlatformOpenAI}, {Type: AccountTypeAPIKey}, {Credentials: map[string]any{"upstream_kind": "unknown"}}} { repo.updatedAccounts = nil _, err := svc.UpdateAccount(context.Background(), 959, input) diff --git a/backend/internal/service/gateway_messages_selection_test.go b/backend/internal/service/gateway_messages_selection_test.go index ef19bcb6db69..aac689ca0aea 100644 --- a/backend/internal/service/gateway_messages_selection_test.go +++ b/backend/internal/service/gateway_messages_selection_test.go @@ -194,6 +194,27 @@ func TestGatewayProtocolCatalogFollowsLiveBindings(t *testing.T) { require.Empty(t, svc.GetAvailableModels(ctx, &base.group.ID, PlatformOpenAI)) } +func TestGatewayProtocolCatalogSavedModelsAndGroupPrecedence(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformOpenAI) + base.account.Credentials["model_mapping"] = map[string]any{"saved": "wire", "other": "other"} + svc := &GatewayService{accountRepo: &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base}} + models, err := svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Equal(t, []string{"other", "saved"}, models, "saved IDs replace platform defaults") + base.group.ModelAllowlist = GroupModelAllowlist{Enabled: true, Models: []string{"saved"}} + models, err = svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Equal(t, []string{"saved"}, models) + base.account.Credentials["model_mapping"] = map[string]any{"*": "wire"} + models, err = svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Equal(t, []string{"saved"}, models, "explicit group IDs seed wildcard account mappings") + base.account.AccountGroups[0].AllowedModels = []string{"other"} + models, err = svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Empty(t, models, "a fetched catalog must not bypass binding admission") +} + func TestGatewayProtocolOpenAIChannelModelKeepsBinding(t *testing.T) { base, ctx := gatewayProtocolFixture(PlatformOpenAI) ctx = WithGatewayOpenAISelection(ctx, "public", "public") diff --git a/backend/internal/service/gateway_model_catalog.go b/backend/internal/service/gateway_model_catalog.go index 02da6b61fa9a..cdadc135818b 100644 --- a/backend/internal/service/gateway_model_catalog.go +++ b/backend/internal/service/gateway_model_catalog.go @@ -77,6 +77,11 @@ func (catalog gatewayModelCatalog) directModels(target string) []string { for name := range account.GetModelMapping() { models = append(models, name) } + // Concrete group entries also seed wildcard account mappings. The same + // admission below remains authoritative for both group and account policy. + if group.ModelAllowlist.Enabled { + models = append(models, group.ModelAllowlist.Models...) + } if len(models) == 0 { models = append(models, group.ModelAllowlist.Models...) if !IsMultiProtocolAPIKeyProvider(target) { diff --git a/backend/internal/service/gateway_protocol_admission_test.go b/backend/internal/service/gateway_protocol_admission_test.go index c3e55f7f758a..094d9828f85c 100644 --- a/backend/internal/service/gateway_protocol_admission_test.go +++ b/backend/internal/service/gateway_protocol_admission_test.go @@ -32,6 +32,34 @@ func gatewayProtocolFixture(target string) (*gatewayProtocolAdmissionRepo, conte return &gatewayProtocolAdmissionRepo{account: a, group: g}, context.WithValue(context.Background(), ctxkey.Group, g) } +func TestGatewayProtocolAdmissionUntouchedModelMappingRemainsUnrestricted(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + for _, scenario := range []struct { + platform string + family domain.PlatformGateway + model string + }{ + {PlatformOpenAI, domain.PlatformGatewayOpenAI, "gpt-6.1-sol"}, + {PlatformGemini, domain.PlatformGatewayGemini, "gemini-3.1-pro"}, + } { + t.Run(kind+"/"+scenario.platform, func(t *testing.T) { + repo, ctx := gatewayProtocolFixture(scenario.platform) + repo.account.Credentials["upstream_kind"] = kind + // The untouched create form saves an empty mapping: no provider's + // built-in whitelist may narrow this explicitly bound gateway. + repo.account.Credentials["model_mapping"] = map[string]any{} + view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, scenario.family, scenario.model) + require.NoError(t, err) + require.Equal(t, scenario.model, view.GetMappedModel(scenario.model)) + // Explicit administrator restrictions still govern the same model. + repo.account.Credentials["model_mapping"] = map[string]any{"claude-sonnet-4": "claude-sonnet-4"} + _, err = prepareGatewayProtocolAccount(ctx, repo.account, repo, scenario.family, scenario.model) + require.ErrorIs(t, err, ErrGatewayAccountGroup) + }) + } + } +} + func TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity(t *testing.T) { for _, spec := range domain.Platforms() { for _, composite := range []bool{false, true} { diff --git a/backend/internal/service/gateway_upstream_models_test.go b/backend/internal/service/gateway_upstream_models_test.go new file mode 100644 index 000000000000..6a4c18b2698d --- /dev/null +++ b/backend/internal/service/gateway_upstream_models_test.go @@ -0,0 +1,124 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGatewayUpstreamModelsDiscoveryAndApply(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + for _, apply := range []bool{false, true} { + t.Run(kind+map[bool]string{false: "/discovery", true: "/apply"}[apply], func(t *testing.T) { + svc, repo, upstream := modelMappingSyncFixture(http.StatusOK, `{"data":[{"id":"new"},{"id":"new"}]}`) + readOnlyRepo := &batchWhitelistReadOnlyRepo{upstreamModelMappingRepoStub: repo} + svc.accountRepo = readOnlyRepo + a := repo.account + a.Platform, a.Type = PlatformGateway, AccountTypeGateway + a.Credentials["upstream_kind"] = kind + a.Credentials["unrelated"] = "keep" + proxyID := int64(7) + a.ProxyID = &proxyID + a.Proxy = &Proxy{ID: proxyID, Protocol: "http", Host: "proxy.example", Port: 8080} + before := cloneTestCredentials(a.Credentials) + // Record metadata/health writes separately from explicit mapping + // application. Discovery must only issue the authenticated listing. + catalog, err := svc.SyncUpstreamModelCatalogWithOptions(context.Background(), a, UpstreamModelSyncOptions{Apply: apply}) + require.NoError(t, err) + require.Equal(t, []string{"new"}, catalog.Models) + require.Equal(t, "upstream", catalog.DiscoverySource) + require.Len(t, upstream.requests, 1, "no provider registry request") + require.Equal(t, "https://provider.example/v1/models", upstream.lastReq.URL.String()) + require.Equal(t, http.MethodGet, upstream.lastReq.Method) + require.Equal(t, "Bearer test-key", upstream.lastReq.Header.Get("Authorization")) + require.Equal(t, "http://proxy.example:8080", upstream.lastProxyURL) + require.Equal(t, before, a.Credentials) + require.Zero(t, repo.claimCalls) + require.Zero(t, readOnlyRepo.extraWrites.Load()) + require.Zero(t, readOnlyRepo.credentialWrites.Load()) + require.Zero(t, readOnlyRepo.authErrors.Load()) + require.Zero(t, readOnlyRepo.tempUnsched.Load()) + if apply { + require.True(t, catalog.Applied) + require.Equal(t, map[string]string{"new": "new", "public-new": "new"}, repo.mapping) + require.Equal(t, 1, repo.applyCalls) + } else { + require.Zero(t, repo.applyCalls) + } + }) + } + } +} + +func cloneTestCredentials(in map[string]any) map[string]any { + out := make(map[string]any, len(in)) + for key, value := range in { + out[key] = value + } + return out +} + +func TestGatewayUpstreamModelsRejectInvalidConnection(t *testing.T) { + for _, scenario := range []string{"kind", "key", "http", "userinfo", "query", "fragment", "allowlist", "private", "proxy", "type"} { + t.Run(scenario, func(t *testing.T) { + a := gatewayManagementFixture() + upstream := &httpUpstreamRecorder{} + svc := &AccountTestService{httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + switch scenario { + case "kind": + a.Credentials["upstream_kind"] = "other" + case "key": + a.Credentials["api_key"] = "" + case "http": + a.Credentials["base_url"] = "http://gateway.example" + case "userinfo": + a.Credentials["base_url"] = "https://user:secret@gateway.example" + case "query": + a.Credentials["base_url"] = "https://gateway.example?key=secret" + case "fragment": + a.Credentials["base_url"] = "https://gateway.example/#secret" + case "allowlist": + svc.cfg.Security.URLAllowlist.Enabled = true + svc.cfg.Security.URLAllowlist.UpstreamHosts = []string{"allowed.example"} + case "private": + a.Credentials["base_url"] = "https://127.0.0.1" + svc.cfg.Security.URLAllowlist.Enabled = true + svc.cfg.Security.URLAllowlist.UpstreamHosts = []string{"127.0.0.1"} + case "proxy": + id := int64(7) + a.ProxyID = &id + case "type": + a.Type = AccountTypeAPIKey + } + _, err := svc.SyncUpstreamModelCatalog(context.Background(), a) + require.Error(t, err) + require.Empty(t, upstream.requests) + }) + } +} + +func TestGatewayUpstreamModelsFailureKeepsMapping(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusTooManyRequests, http.StatusBadGateway} { + svc, repo, _ := modelMappingSyncFixture(status, `{"error":"private-detail"}`) + repo.account.Platform, repo.account.Type = PlatformGateway, AccountTypeGateway + repo.account.Credentials["upstream_kind"] = "sub2api" + _, err := svc.SyncUpstreamModelCatalogWithOptions(context.Background(), repo.account, UpstreamModelSyncOptions{Apply: true}) + require.Error(t, err) + require.Zero(t, repo.applyCalls) + } + for _, body := range []string{`not-json`, `{"data":[]}`, `{"data":[{"id":"new"}],"has_more":true}`} { + svc, repo, upstream := modelMappingSyncFixture(http.StatusOK, body) + repo.account.Platform, repo.account.Type = PlatformGateway, AccountTypeGateway + repo.account.Credentials["upstream_kind"] = "new_api" + upstream.resp.Body = io.NopCloser(strings.NewReader(body)) + catalog, err := svc.SyncUpstreamModelCatalogWithOptions(context.Background(), repo.account, UpstreamModelSyncOptions{Apply: true}) + require.True(t, err != nil || catalog.Skipped == "unverified_catalog") + require.Zero(t, repo.applyCalls) + } +} diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 2d0ad2e3f03a..08fbf9ab59c5 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -237,6 +237,11 @@ func visibleUpstreamModelIDs(account *Account, models []string) []string { // snapshot. When no model is complete, the existing account snapshot is left // untouched. func (s *AccountTestService) SyncUpstreamModelCatalog(ctx context.Context, account *Account) (*UpstreamModelCatalog, error) { + // A gateway aggregates providers. Discovery must neither infer provider + // capabilities nor write metadata/health state; only explicit apply saves IDs. + if account != nil && (account.IsGateway() || account.Platform == PlatformGateway) { + return s.fetchWhitelistCatalog(ctx, account) + } fetched, err := s.fetchUpstreamModelListWithObservation(ctx, account) var ( models []string @@ -1035,6 +1040,8 @@ func listVertexGeminiPublisherModels(location string, fetchPage func(page int, l func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) { switch { + case account.IsGateway() || account.Platform == PlatformGateway: + return s.buildGatewayUpstreamModelsRequest(ctx, account) case account.Platform == PlatformAntigravity: return s.buildAntigravityAPIKeyModelsRequest(ctx, account) case account.IsGrok(): @@ -1053,6 +1060,26 @@ func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, acc } } +func (s *AccountTestService) buildGatewayUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) { + if err := ValidateGatewayAccountIdentity(account.Platform, account.Type, account.Credentials); err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid gateway account credentials", err) + } + if account.ProxyID != nil && *account.ProxyID > 0 && account.Proxy == nil { + return nil, newUpstreamModelSyncConfigError("Selected proxy is unavailable", nil) + } + baseURL, err := s.validateUpstreamBaseURL(account.GetCredential("base_url")) + if err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid gateway base URL", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildV1ModelsURL(baseURL), nil) + if err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid gateway model list URL", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(account.GetCredential("api_key"))) + return req, nil +} + func (s *AccountTestService) buildGrokUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) { if account == nil { return nil, newUpstreamModelSyncConfigError("Account is required", nil) diff --git a/frontend/src/api/admin/accounts.ts b/frontend/src/api/admin/accounts.ts index bfaf8b93bfac..33e8288106ce 100644 --- a/frontend/src/api/admin/accounts.ts +++ b/frontend/src/api/admin/accounts.ts @@ -685,6 +685,8 @@ export async function syncUpstreamModels( export interface SyncUpstreamPreviewParams { platform: string type: string + upstream_kind?: 'sub2api' | 'new_api' + account_id?: number base_url?: string api_key: string proxy_id?: number diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 95b7d122e1f4..a35c96afd96b 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -280,6 +280,8 @@ + @@ -4449,6 +4451,7 @@ import ProxySelector from '@/components/common/ProxySelector.vue' import ProxyAdBanner from '@/components/common/ProxyAdBanner.vue' import GroupSelector from '@/components/common/GroupSelector.vue' import ModelWhitelistSelector from '@/components/account/ModelWhitelistSelector.vue' +import GatewayModelSettings from '@/components/account/GatewayModelSettings.vue' import AccountAutoBPSSection from '@/components/account/AccountAutoBPSSection.vue' import QuotaLimitCard from '@/components/account/QuotaLimitCard.vue' import Toggle from '@/components/common/Toggle.vue' @@ -5004,6 +5007,11 @@ const openAICompactModelMappings = ref([]) const modelRestrictionMode = ref<'whitelist' | 'mapping'>('whitelist') const allowedModels = ref([]) const upstreamModelsPreviewed = ref(false) +const gatewaySyncCredentials = computed(() => gatewayApiKey.value.trim() ? { + platform: 'gateway', type: 'gateway', upstream_kind: gatewayKind.value, + base_url: gatewayBaseUrl.value.trim(), api_key: gatewayApiKey.value.trim(), + proxy_id: authStore.isObserver ? undefined : form.proxy_id ?? undefined +} : undefined) const DEFAULT_POOL_MODE_RETRY_COUNT = 3 const MAX_POOL_MODE_RETRY_COUNT = 10 const DEFAULT_POOL_MODE_RETRY_STATUS_CODES = [401, 403, 429] @@ -6558,7 +6566,8 @@ const handleSubmit = async () => { await createAccountAndFinish('gateway', 'gateway', { upstream_kind: gatewayKind.value, base_url: gatewayBaseUrl.value, - api_key: gatewayApiKey.value + api_key: gatewayApiKey.value, + model_mapping: buildModelMappingObject('combined', allowedModels.value, modelMappings.value) ?? {} }) return } diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 3e17e759925d..acd41b11bb30 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -33,6 +33,8 @@ +
@@ -3921,6 +3923,7 @@ import ProxySelector from '@/components/common/ProxySelector.vue' import ProxyAdBanner from '@/components/common/ProxyAdBanner.vue' import GroupSelector from '@/components/common/GroupSelector.vue' import ModelWhitelistSelector from '@/components/account/ModelWhitelistSelector.vue' +import GatewayModelSettings from '@/components/account/GatewayModelSettings.vue' import AccountGroupModelLimits from '@/components/account/AccountGroupModelLimits.vue' import AccountAutoBPSSection from '@/components/account/AccountAutoBPSSection.vue' import { @@ -5254,6 +5257,12 @@ const loadModelRestrictionFromMapping = (rawMapping?: Record) = const buildModelRestrictionMapping = () => buildModelMappingObject('combined', allowedModels.value, modelMappings.value) +const gatewaySyncCredentials = computed(() => editingAccount.value?.type === 'gateway' ? { + platform: 'gateway', type: 'gateway', upstream_kind: gatewayKind.value, + account_id: editingAccount.value.id, base_url: editBaseUrl.value.trim(), api_key: editApiKey.value.trim(), + proxy_id: authStore.isObserver ? undefined : form.proxy_id ?? undefined +} : undefined) + const applyOpenAIModelMappingCredentials = (credentials: Record) => { if (editingAccount.value?.type === 'oauth' && !isSparkShadow.value) { credentials.model_mapping_mode = openaiModelAliases.value ? 'aliases' : 'whitelist' @@ -5776,6 +5785,7 @@ const syncFormFromAccount = (newAccount: Account | null) => { } else if (newAccount.type === 'gateway') { gatewayKind.value = newAccount.credentials?.upstream_kind === 'new_api' ? 'new_api' : 'sub2api' editBaseUrl.value = String(newAccount.credentials?.base_url || '') + loadModelRestrictionFromMapping(newAccount.credentials?.model_mapping as Record | undefined) } else if (newAccount.type === 'upstream' && newAccount.credentials) { const credentials = newAccount.credentials as Record editBaseUrl.value = (credentials.base_url as string) || '' @@ -6755,6 +6765,7 @@ const handleSubmit = async () => { updatePayload.credentials = { upstream_kind: gatewayKind.value, base_url: editBaseUrl.value.trim(), + model_mapping: buildModelRestrictionMapping() ?? {}, ...(editApiKey.value.trim() ? { api_key: editApiKey.value.trim() } : {}) } if (gatewayKind.value === 'sub2api') updatePayload.upstream_billing_probe_enabled = upstreamBillingAutoProbeEnabled.value diff --git a/frontend/src/components/account/GatewayModelSettings.vue b/frontend/src/components/account/GatewayModelSettings.vue new file mode 100644 index 000000000000..536b255e0a7d --- /dev/null +++ b/frontend/src/components/account/GatewayModelSettings.vue @@ -0,0 +1,33 @@ + + + diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue index e0f7d60fd698..82ed377fbf6c 100644 --- a/frontend/src/components/account/ModelWhitelistSelector.vue +++ b/frontend/src/components/account/ModelWhitelistSelector.vue @@ -192,6 +192,8 @@ watch( () => props.accountId, () => props.syncCredentials?.platform, () => props.syncCredentials?.type, + () => props.syncCredentials?.upstream_kind, + () => props.syncCredentials?.account_id, () => props.syncCredentials?.base_url, () => props.syncCredentials?.api_key, () => props.syncCredentials?.proxy_id diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index a9aa724283f8..5f0720417ed8 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -96,6 +96,7 @@ vi.mock('@/api/admin', () => ({ vi.mock('@/api/admin/accounts', () => ({ getAntigravityDefaultModelMapping: vi.fn().mockResolvedValue([]), + accountsAPI: { syncUpstreamModels: vi.fn(), syncUpstreamModelsPreview: vi.fn() }, })) vi.mock('@/api/admin/accountTokenGuardV2', () => ({ @@ -111,6 +112,8 @@ vi.mock('vue-i18n', async () => { }) import CreateAccountModal from '../CreateAccountModal.vue' +import ModelWhitelistSelector from '../ModelWhitelistSelector.vue' +import { accountsAPI } from '@/api/admin/accounts' import BPSProxyRoutingSettings from '../BPSProxyRoutingSettings.vue' import OpenAITwoFAImport from '../OpenAITwoFAImport.vue' @@ -189,7 +192,7 @@ const ModelWhitelistSelectorStub = defineComponent({ >models`, }) -function mountModal(groups: any[] = [], realDialog = false, proxies: any[] = []) { +function mountModal(groups: any[] = [], realDialog = false, proxies: any[] = [], realGatewayControls = false) { return mount(CreateAccountModal, { attachTo: realDialog ? document.body : undefined, props: { show: true, proxies, groups }, @@ -204,8 +207,8 @@ function mountModal(groups: any[] = [], realDialog = false, proxies: any[] = []) PlatformIcon: true, ProxySelector: true, ProxyAdBanner: true, - GroupSelector: GroupSelectorStub, - ModelWhitelistSelector: ModelWhitelistSelectorStub, + GroupSelector: realGatewayControls ? false : GroupSelectorStub, + ModelWhitelistSelector: realGatewayControls ? false : ModelWhitelistSelectorStub, QuotaLimitCard: true, }, }, @@ -2176,21 +2179,62 @@ describe('mature provider import entry', () => { }) }) -it('creates a cross-platform gateway with the selected provider and one calling key', async () => { +it.each(['new_api', 'sub2api'])('creates an unrestricted %s gateway when models are untouched', async (kind) => { + const groups = [{ id: 1, name: 'Fixture OpenAI', platform: 'openai', status: 'active', rate_multiplier: 1, require_oauth_only: false }] + createAccountMock.mockReset().mockResolvedValue({ id: 1003, platform: 'gateway', type: 'gateway' }) + syncUpstreamModelsMock.mockClear() + vi.mocked(accountsAPI.syncUpstreamModels).mockClear() + vi.mocked(accountsAPI.syncUpstreamModelsPreview).mockClear() + const wrapper = mountModal(groups, false, [], true) + await wrapper.get('[data-testid="platform-button-gateway"]').trigger('click') + await wrapper.get('[data-tour="account-form-name"]').setValue('Untouched gateway') + const fields = wrapper.get('[data-testid="gateway-account-fields"]') + await fields.get('select').setValue(kind) + await fields.get('input[type="url"]').setValue('https://relay.example.com') + await fields.get('input[type="password"]').setValue('synthetic-key') + await wrapper.get('[data-tour="account-form-groups"] input[value="1"]').setValue(true) + await flushPromises() + const selector = wrapper.getComponent(ModelWhitelistSelector) + expect(selector.props('modelValue')).toEqual([]) + expect(selector.props('modelMappings')).toEqual([]) + await wrapper.get('#create-account-form').trigger('submit.prevent') + await flushPromises() + expect(createAccountMock).toHaveBeenCalledOnce() + expect(createAccountMock).toHaveBeenCalledWith(expect.objectContaining({ + platform: 'gateway', type: 'gateway', group_ids: [1], + credentials: { + upstream_kind: kind, base_url: 'https://relay.example.com', api_key: 'synthetic-key', model_mapping: {} + } + })) + expect(syncUpstreamModelsMock).not.toHaveBeenCalled() + expect(accountsAPI.syncUpstreamModels).not.toHaveBeenCalled() + expect(accountsAPI.syncUpstreamModelsPreview).not.toHaveBeenCalled() +}) + +it.each(['new_api', 'sub2api'])('creates a %s gateway with editable account models and one calling key', async (kind) => { const wrapper = mountModal() await wrapper.get('[data-testid="platform-button-gateway"]').trigger('click') await wrapper.get('[data-tour="account-form-name"]').setValue('fixture gateway') const fields = wrapper.get('[data-testid="gateway-account-fields"]') - await fields.get('select').setValue('new_api') + await fields.get('select').setValue(kind) await fields.get('input[type="url"]').setValue('https://relay.example.com') await fields.get('input[type="password"]').setValue('fixture-only') + const selector = wrapper.getComponent(ModelWhitelistSelectorStub) + expect(selector.props('syncCredentials')).toMatchObject({ + platform: 'gateway', type: 'gateway', upstream_kind: kind, + base_url: 'https://relay.example.com', api_key: 'fixture-only' + }) + selector.vm.$emit('update:modelValue', ['live']) + selector.vm.$emit('update:modelMappings', [{ from: 'public', to: 'live' }]) + await flushPromises() await wrapper.get('#create-account-form').trigger('submit.prevent') await flushPromises() expect(createAccountMock).toHaveBeenCalledWith(expect.objectContaining({ platform: 'gateway', type: 'gateway', credentials: expect.objectContaining({ - upstream_kind: 'new_api', base_url: 'https://relay.example.com', api_key: 'fixture-only' + upstream_kind: kind, base_url: 'https://relay.example.com', api_key: 'fixture-only', + model_mapping: { live: 'live', public: 'live' } }) })) }) diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 4e2f4f932a55..fb6abc9d2b7b 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -100,6 +100,7 @@ const BaseDialogStub = defineComponent({ const ModelWhitelistSelectorStub = defineComponent({ name: 'ModelWhitelistSelector', props: { + syncCredentials: Object, modelMappings: { type: Array, default: () => [] }, modelValue: { type: Array, @@ -356,6 +357,60 @@ function mountModal(account = buildAccount(), renderGroupSelector = false) { } describe('EditAccountModal', () => { + it('announces gateway model settings independently and shares persistent dismissal', async () => { + localStorage.removeItem('sub2api:new-feature-notices:v1:41') + const pinia = createPinia() + setActivePinia(pinia) + const notices = useNewFeatureNoticeStore() + notices.dismiss(41, NEW_FEATURE_NOTICES.crossPlatformGatewayAccounts) + const account = { ...buildAccount(), platform: 'gateway', type: 'gateway', + credentials: { upstream_kind: 'new_api', base_url: 'https://relay.example.com' } } as any + const wrapper = mountModal(account) + await flushPromises() + const badge = wrapper.findAllComponents(NewFeatureBadge).find(item => item.props('noticeId') === NEW_FEATURE_NOTICES.gatewayModelSync)! + expect(badge.find('button').exists()).toBe(true) + const sibling = mount(NewFeatureBadge, { props: { noticeId: NEW_FEATURE_NOTICES.gatewayModelSync, userId: 41 }, global: { plugins: [pinia] } }) + await badge.get('button').trigger('click') + expect(sibling.find('button').exists()).toBe(false) + wrapper.unmount() + sibling.unmount() + setActivePinia(createPinia()) + const reloaded = mountModal(account) + await flushPromises() + const reloadedBadge = reloaded.findAllComponents(NewFeatureBadge).find(item => item.props('noticeId') === NEW_FEATURE_NOTICES.gatewayModelSync)! + expect(reloadedBadge.find('button').exists()).toBe(false) + expect(useNewFeatureNoticeStore().isDismissed(41, NEW_FEATURE_NOTICES.crossPlatformGatewayAccounts)).toBe(true) + const future = mount(NewFeatureBadge, { props: { noticeId: 'fixture-future-gateway-notice-C', userId: 41 } }) + expect(future.find('button').exists()).toBe(true) + future.unmount() + }) + + it.each(['new_api', 'sub2api'])('keeps %s gateway models across connection and group edits', async (kind) => { + const account = { ...buildAccount(), platform: 'gateway', type: 'gateway', group_ids: [10], + credentials: { upstream_kind: kind, base_url: 'https://relay.example.com', + model_mapping: { live: 'live', public: 'live' }, unknown_option: { keep: true } } } as any + updateAccountMock.mockReset().mockResolvedValue(account) + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + const wrapper = mountModal(account) + await flushPromises() + const selector = wrapper.getComponent(ModelWhitelistSelectorStub) + expect(selector.props('modelValue')).toEqual(['live']) + expect(selector.props('modelMappings')).toEqual([{ from: 'public', to: 'live' }]) + const fields = wrapper.get('[data-testid="gateway-account-fields"]') + await fields.get('input[type="url"]').setValue('https://edited.example.com') + await fields.get('input[type="password"]').setValue('synthetic-new-key') + wrapper.getComponent(GroupSelectorStub).vm.$emit('update:modelValue', [20]) + await flushPromises() + expect(selector.props('syncCredentials')).toMatchObject({ account_id: account.id, + upstream_kind: kind, base_url: 'https://edited.example.com', api_key: 'synthetic-new-key' }) + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + await flushPromises() + expect(updateAccountMock.mock.calls[0]?.[1]).toMatchObject({ group_ids: [20], credentials: { + upstream_kind: kind, base_url: 'https://edited.example.com', api_key: 'synthetic-new-key', + model_mapping: account.credentials.model_mapping + } }) + }) + it('keeps the target platform announcement independent, shared and persistent', async () => { const noticeId = NEW_FEATURE_NOTICES.accountEditPlatform localStorage.removeItem('sub2api:new-feature-notices:v1:41') diff --git a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts index 2f63c3497f63..e8db1a4544c2 100644 --- a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts +++ b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts @@ -105,6 +105,20 @@ function findModelRow(wrapper: ReturnType, modelId: string } describe('ModelWhitelistSelector', () => { + it.each(['new_api', 'sub2api'] as const)('fetches %s gateway preview into an editable whitelist and preserves live aliases', async (kind) => { + syncUpstreamModelsPreview.mockResolvedValue({ models: ['live', 'new'], discovery_source: 'upstream' }) + const credentials = { platform: 'gateway', type: 'gateway', upstream_kind: kind, + account_id: 46, api_key: '', base_url: 'https://draft.example', proxy_id: 7 } + const wrapper = mountSelector({ platform: 'gateway', modelValue: ['old'], + modelMappings: [{ from: 'public', to: 'live' }], syncCredentials: credentials }) + await syncButton(wrapper).trigger('click') + await flushPromises() + expect(syncUpstreamModelsPreview).toHaveBeenCalledWith(credentials) + expect(syncUpstreamModels).not.toHaveBeenCalled() + expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual([['live', 'new']]) + expect(wrapper.emitted('update:modelMappings')?.at(-1)).toEqual([[{ from: 'public', to: 'live' }]]) + }) + beforeEach(() => { copyToClipboard.mockClear() showError.mockReset() @@ -119,7 +133,7 @@ describe('ModelWhitelistSelector', () => { resetPlatformCatalog() }) - it.each(['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'command_code', 'cline', 'mistral'])( + it.each(['gateway', 'anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'command_code', 'cline', 'mistral'])( 'supports upstream sync for %s saved accounts and creation previews', (platform) => { const wrappers = [ diff --git a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts index 17732fc100b7..aa73a1d414e8 100644 --- a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts +++ b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts @@ -8,6 +8,12 @@ import { buildModelMappingObject, getModelsByPlatform, getPresetMappingsByPlatfo import { BUILTIN_PLATFORM_CATALOG, resetPlatformCatalog, setPlatformCatalog } from '@/constants/platformCatalog' describe('useModelWhitelist', () => { + it('leaves gateway model defaults unrestricted without changing legacy platform defaults', () => { + expect(getModelsByPlatform('gateway')).toEqual([]) + expect(getModelsByPlatform('anthropic').length).toBeGreaterThan(0) + expect(getModelsByPlatform('bedrock')).toEqual(getModelsByPlatform('anthropic')) + }) + it('平台清单中没有内置模型列表的多协议供应商不预填白名单', () => { setPlatformCatalog({ ...BUILTIN_PLATFORM_CATALOG, diff --git a/frontend/src/composables/useModelWhitelist.ts b/frontend/src/composables/useModelWhitelist.ts index e2559144d4b0..c24206216b7c 100644 --- a/frontend/src/composables/useModelWhitelist.ts +++ b/frontend/src/composables/useModelWhitelist.ts @@ -512,6 +512,9 @@ export const commonErrorCodes = [ // 按平台获取模型 export function getModelsByPlatform(platform: string): string[] { switch (platform) { + // A gateway has no provider-specific defaults. Leave its whitelist + // unrestricted until the administrator fetches or selects models. + case 'gateway': return [] case 'openai': return openaiModels case 'anthropic': case 'claude': return claudeModels diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index ef99f72337c5..03ada7d0986e 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -12,6 +12,7 @@ export const NEW_FEATURE_NOTICES = { channelConfig: 'channel-configuration-20261119', imageUsageBilling: 'image-usage-minimum-charge-20261119', crossPlatformGatewayAccounts: 'cross-platform-gateway-accounts', + gatewayModelSync: 'gateway-account-model-sync-20261122', newAPICostConversion: 'new-api-cost-conversion-20261119', accountOpsBalanceNotification: 'account-ops-per-account-balance-notification-20261119', channelUltrafastPricing: 'channel-ultrafast-pricing-initial-announcement', diff --git a/frontend/src/constants/platformCatalog.ts b/frontend/src/constants/platformCatalog.ts index bb988dec3a00..ffb04c7ae2ee 100644 --- a/frontend/src/constants/platformCatalog.ts +++ b/frontend/src/constants/platformCatalog.ts @@ -87,6 +87,7 @@ export function isKnownPlatform(platform: string | null | undefined): boolean { /** 与后端 buildUpstreamModelsRequest 支持的平台保持一致。 */ export function supportsUpstreamModelSync(platform: string | null | undefined): boolean { + if (platform?.trim().toLowerCase() === 'gateway') return true const spec = getPlatformSpec(platform?.trim().toLowerCase()) if (!spec) return false return !!spec.multi_protocol || ['anthropic', 'openai', 'gemini', 'antigravity', 'grok'].includes(spec.id) diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index 08ea21b4e16f..1c8473f69fa9 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -494,6 +494,13 @@