diff --git a/.github/scripts/bps-search-preview.mjs b/.github/scripts/bps-search-preview.mjs new file mode 100644 index 000000000000..38412e704273 --- /dev/null +++ b/.github/scripts/bps-search-preview.mjs @@ -0,0 +1,73 @@ +// Render the actual Vue component in CI with a fictional administrator. +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { execFileSync } from 'node:child_process' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +const [repoArg, outputArg, baseline = ''] = process.argv.slice(2) +const repo = resolve(repoArg), output = resolve(outputArg), root = join(repo, 'frontend') +const require = createRequire(join(root, 'package.json')) +const { createServer } = await import(pathToFileURL(join(dirname(require.resolve('vite/package.json')), 'dist/node/index.js')).href) +const vue = (await import(pathToFileURL(require.resolve('@vitejs/plugin-vue')).href)).default +const { chromium } = await import(pathToFileURL(process.env.SUB2API_PLAYWRIGHT_MODULE).href) +const entry = '.bps-search-preview.js', cacheDir = mkdtempSync(join(tmpdir(), 'bps-search-preview-')) +let server, browser +mkdirSync(output, { recursive: true }) +try { + writeFileSync(join(root, entry), ` +import {mount} from '@vue/test-utils'; +import {createPinia,setActivePinia} from 'pinia'; +import {i18n,loadLocaleMessages} from '/src/i18n/index.ts'; +import {useAuthStore} from '/src/stores/auth.ts'; +import View from '/src/components/admin/operations/BPSDefaultsCard.vue'; +import {defaultExcelBPSDefaults} from '/src/utils/excelBPSDefaults.ts'; +import '/src/style.css'; +await loadLocaleMessages('zh');i18n.global.locale.value='zh'; +const pinia=createPinia();setActivePinia(pinia);useAuthStore().user={id:42,role:'admin',username:'demo'}; +document.querySelector('#app').innerHTML='
OAuth 自动配置 → BPS 默认模板 · 实际组件 / 虚构管理员
'; +window.preview=mount(View,{attachTo:'#preview',props:{groups:[],modelValue:{...defaultExcelBPSDefaults(),all_models:true},'onUpdate:modelValue':value=>window.preview.setProps({modelValue:value})},global:{plugins:[pinia,i18n]}}); +`) + process.chdir(root) + server = await createServer({ root, configFile: false, cacheDir, + resolve: { alias: { '@': join(root, 'src') } }, + plugins: [{ name: 'bps-search-fixture', enforce: 'pre', load(id) { + if (baseline && id === join(root,'src/components/admin/operations/BPSDefaultsCard.vue')) return execFileSync('git',['show',baseline+':frontend/src/components/admin/operations/BPSDefaultsCard.vue'],{cwd:repo,encoding:'utf8'}) + }, configureServer(vite) { vite.middlewares.use((request, response, next) => { + if (request.url === '/') { response.setHeader('Content-Type','text/html'); response.end('') } + else if (request.url === '/favicon.ico') { response.statusCode = 204; response.end() } + else next() + }) } }, vue()], server: { host: '127.0.0.1', port: 4299, strictPort: true }, + optimizeDeps: { entries: [], include: ['vue','pinia','vue-i18n','axios','@vue/test-utils'] } }) + await server.listen(); browser = await chromium.launch({ headless: true }) + const page = await browser.newPage({ viewport: { width: 1100, height: 1000 } }), errors = [] + page.on('pageerror', error => errors.push(error.message)) + await page.route('**/*', route => new URL(route.request().url()).origin === 'http://127.0.0.1:4299' ? route.continue() : route.abort()) + await page.goto('http://127.0.0.1:4299', { waitUntil: 'networkidle' }) + await page.getByTestId('bps-all-models').waitFor() + if (baseline) { + if (await page.getByTestId('bps-search-options').count()) throw Error('Baseline unexpectedly includes search options') + await page.screenshot({path:join(output,'before.png'),fullPage:true}) + } else { + await page.getByTestId('bps-search-options').waitFor() + await page.screenshot({ path: join(output,'default-off.png'), fullPage: true }) + await page.getByTestId('excel-bps-web-search').check() + await page.getByTestId('excel-bps-web-search-auto').check() + await page.waitForFunction(() => window.preview.props('modelValue').web_search && window.preview.props('modelValue').web_search_auto) + await page.screenshot({ path: join(output,'search-and-auto.png'), fullPage: true }) + await page.evaluate(() => document.documentElement.classList.add('dark')) + await page.screenshot({ path: join(output,'dark.png'), fullPage: true }) + await page.setViewportSize({ width: 390, height: 700 }) + await page.screenshot({ path: join(output,'mobile.png'), fullPage: true }) + await page.getByTestId('excel-bps-web-search').uncheck() + await page.waitForFunction(() => !window.preview.props('modelValue').web_search && !window.preview.props('modelValue').web_search_auto) + if (await page.getByTestId('excel-bps-web-search-auto').isChecked()) throw Error('Automatic search remained enabled') + const saved = await page.evaluate(() => window.preview.props('modelValue')) + if (saved.web_search || saved.web_search_auto) throw Error('Template model retained disabled search options') + } + if (errors.length) throw Error(JSON.stringify(errors)) + writeFileSync(join(output,'evidence.json'),JSON.stringify({ source:execFileSync('git',['rev-parse','HEAD'],{cwd:repo,encoding:'utf8'}).trim(),baseline:baseline||null,fixture:true,errors,states:baseline?['before']:['default-off','search-and-auto','dark','mobile'],production:false },null,2)) +} finally { + await browser?.close(); await server?.close() + rmSync(join(root,entry),{force:true}); rmSync(cacheDir,{recursive:true,force:true}) +} diff --git a/.github/workflows/bps-search.yml b/.github/workflows/bps-search.yml new file mode 100644 index 000000000000..c12447915b43 --- /dev/null +++ b/.github/workflows/bps-search.yml @@ -0,0 +1,68 @@ +name: BPS search protocol and settings +on: + pull_request: + paths: + - backend/internal/service/basispoints/web_search* + - backend/internal/service/openai_excel_bps_search* + - backend/internal/service/bps_search_settings_test.go + - frontend/src/components/account/ExcelBPSSearchOptions.vue + - frontend/src/components/account/__tests__/ExcelBPSSearchOptions.spec.ts + - frontend/src/utils/excelBPSDefaults.ts + - .github/scripts/bps-search-preview.mjs + - .github/workflows/bps-search.yml +permissions: + contents: read +jobs: + search-protocol: + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - working-directory: backend + run: go test -race ./internal/service/basispoints -run 'Test(WebSearch|AlphaSearch|ToolChoice|CurrentEncrypted|CompactionPolicy)' -count=1 -v + - working-directory: backend + run: go test -race -tags=unit ./internal/service -run 'Test(ExcelBPSAccountSearch|ExcelBPSSearch|BPSSearchDefaults)' -count=1 -v -timeout=10m + - working-directory: backend + run: go test -tags=integration ./internal/repository -run '^TestQuality(BPSSnapshotEqualDefaultsAndManualChanges|EnableBPSRestoreAfterAccountEditorSave|BPSSearchRestorePreservesManualChanges)$' -count=1 -v -timeout=10m + search-ui: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + - 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 + - run: pnpm --dir frontend install --frozen-lockfile + - run: pnpm --dir frontend exec vitest run src/components/account/__tests__/ExcelBPSSearchOptions.spec.ts src/components/common/__tests__/NewFeatureBadge.spec.ts src/components/account/__tests__/EditAccountModal.spec.ts src/components/account/__tests__/BulkEditAccountModal.spec.ts src/views/admin/__tests__/AutoConfigView.spec.ts src/composables/__tests__/useExcelBPSDefaults.spec.ts src/utils/__tests__/qualityRulePatch.spec.ts src/i18n/__tests__/localeKeyCompleteness.spec.ts + - run: pnpm --dir frontend typecheck + - name: Install isolated screenshot browser + run: | + npm install --prefix "$RUNNER_TEMP/bps-search-browser" --no-save --ignore-scripts playwright@1.56.1 + node "$RUNNER_TEMP/bps-search-browser/node_modules/playwright/cli.js" install --with-deps chromium + - name: Fetch immutable before UI + run: git fetch --no-tags --depth=1 origin 713cb0f3efe3f838d159cd57998128c2cdaa84b1 + - name: Render actual BPS search settings + env: + SUB2API_PLAYWRIGHT_MODULE: ${{ runner.temp }}/bps-search-browser/node_modules/playwright/index.mjs + run: | + node .github/scripts/bps-search-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/bps-search-evidence/before" 713cb0f3efe3f838d159cd57998128c2cdaa84b1 + node .github/scripts/bps-search-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/bps-search-evidence/after" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: bps-search-evidence-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/bps-search-evidence + retention-days: 30 diff --git a/backend/internal/handler/channel_monitor_v3_handler_test.go b/backend/internal/handler/channel_monitor_v3_handler_test.go index e63adb3cec56..64736e4c85e2 100644 --- a/backend/internal/handler/channel_monitor_v3_handler_test.go +++ b/backend/internal/handler/channel_monitor_v3_handler_test.go @@ -133,7 +133,33 @@ func TestChannelMonitorV3StatusScopesOrdinaryUsersServerSide(t *testing.T) { require.NotNil(t, last) require.Equal(t, service.ChannelMonitorV3StatusDown, last.Status) require.Zero(t, last.Requests) - require.NotContains(t, recorder.Body.String(), "4321", "request volume never reaches users") + // Inspect field names, not decimal substrings that can occur in timestamps + // or public success rates. Check the wire JSON so even zero-valued private + // fields cannot silently become part of the ordinary-user response. + var wire map[string]any + require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &wire)) + var checkPrivateFields func(any) + checkPrivateFields = func(value any) { + switch value := value.(type) { + case map[string]any: + for _, field := range []string{"requests", "errors", "ignored_errors", "probes", "successes"} { + require.NotContains(t, value, field, "request volume never reaches users") + } + for _, child := range value { + checkPrivateFields(child) + } + case []any: + for _, child := range value { + checkPrivateFields(child) + } + } + } + checkPrivateFields(wire) + // The exact timestamp that caused the CI failure is legitimate public data. + data, ok := wire["data"].(map[string]any) + require.True(t, ok, "status envelope must contain an object") + data["generated_at"] = "2026-11-14T19:24:11.151432152Z" + checkPrivateFields(wire) } func TestChannelMonitorV3StatusShowsAdminsEverything(t *testing.T) { diff --git a/backend/internal/repository/account_quality_bps.go b/backend/internal/repository/account_quality_bps.go index 2c59165ed67a..a8f7b1c543df 100644 --- a/backend/internal/repository/account_quality_bps.go +++ b/backend/internal/repository/account_quality_bps.go @@ -264,7 +264,7 @@ func qualityBPSDefaultJSON(key string) json.RawMessage { case service.ExcelBPS403RecoveryIntervalMinutesKey: return json.RawMessage(`60`) case "openai_excel_bps", service.ExcelBPSOmitUnsupportedToolsKey, - service.ExcelBPSIgnoreEncryptedContentKey, + service.ExcelBPSIgnoreEncryptedContentKey, service.ExcelBPSWebSearchKey, service.ExcelBPSWebSearchAutoKey, "openai_excel_bps_auto_disable_on_403", service.ExcelBPSAutoRecoverOn403Key, service.ExcelBPSAutoMoveOn403Key, "openai_excel_bps_mihomo", "openai_excel_bps_cache_creation_as_input": return json.RawMessage(`false`) diff --git a/backend/internal/repository/account_quality_bps_integration_test.go b/backend/internal/repository/account_quality_bps_integration_test.go index 95c6d5250109..97ccaa8c6299 100644 --- a/backend/internal/repository/account_quality_bps_integration_test.go +++ b/backend/internal/repository/account_quality_bps_integration_test.go @@ -316,3 +316,19 @@ func TestQualityEnableBPSRequiresExcelAuthorization(t *testing.T) { f.exec(`INSERT INTO openai_excel_oauth_credentials(account_id,credentials_ciphertext) VALUES($1,'test-encrypted-grant')`) // The worker callback, tested separately, clears preparation automatically. } + +func TestQualityBPSSearchRestorePreservesManualChanges(t *testing.T) { + for _, key := range []string{service.ExcelBPSWebSearchKey, service.ExcelBPSWebSearchAutoKey} { + t.Run(key, func(t *testing.T) { + f := newQualityBPSFixture(t, `{}`, &service.QualityPolicy{Action: service.QualityActionEnableBPS, AutoRestore: true, BPS: &service.QualityBPSPolicy{FailureThreshold: 1, PassThreshold: 1, AllModels: true, WebSearch: true, WebSearchAuto: true}}) + require.Equal(t, "bps_enabled", f.apply("failed")) + require.Equal(t, true, f.extra()[key]) + repo := newAccountRepositoryWithSQL(testEntClient(t), integrationDB, nil) + account, err := repo.GetByID(context.Background(), f.account) + require.NoError(t, err) + delete(account.Extra, key) + require.NoError(t, repo.Update(context.Background(), account)) + require.Equal(t, "restore_conflict", f.apply("passed"), "manually disabling an enabled search option must retain the ownership conflict") + }) + } +} diff --git a/backend/internal/repository/account_quality_bps_test.go b/backend/internal/repository/account_quality_bps_test.go index beceaf7f62d4..b3afef2835d5 100644 --- a/backend/internal/repository/account_quality_bps_test.go +++ b/backend/internal/repository/account_quality_bps_test.go @@ -14,6 +14,9 @@ func TestQualityBPSSnapshotEqualDefaultsAndManualChanges(t *testing.T) { equal bool }{ {"omitted false switches", map[string]any{"openai_excel_bps": true, "openai_excel_bps_cache_creation_as_input": false, "openai_excel_bps_mihomo": false}, map[string]any{"openai_excel_bps": true}, true}, + {"omitted search switches", map[string]any{"openai_excel_bps_web_search": false, "openai_excel_bps_web_search_auto": false}, nil, true}, + {"manual search disable", map[string]any{"openai_excel_bps_web_search": true}, nil, false}, + {"manual automatic search disable", map[string]any{"openai_excel_bps_web_search_auto": true}, nil, false}, {"default recovery interval", map[string]any{"openai_excel_bps_403_recovery_interval_minutes": 60}, nil, true}, {"custom recovery interval", map[string]any{"openai_excel_bps_403_recovery_interval_minutes": 30}, nil, false}, {"default proxy", map[string]any{"openai_excel_bps_proxy_source": "mihomo"}, nil, true}, diff --git a/backend/internal/service/account_quality_bps.go b/backend/internal/service/account_quality_bps.go index 746236509b8a..2736a49ea1d0 100644 --- a/backend/internal/service/account_quality_bps.go +++ b/backend/internal/service/account_quality_bps.go @@ -26,6 +26,8 @@ type QualityBPSPolicy struct { AllModels bool `json:"all_models"` Models []string `json:"models"` OmitUnsupportedTools bool `json:"omit_unsupported_tools"` + WebSearch bool `json:"web_search"` + WebSearchAuto bool `json:"web_search_auto"` IgnoreEncryptedContent bool `json:"ignore_encrypted_content"` AutoDisableOn403 bool `json:"auto_disable_on_403"` AutoRecoverOn403 bool `json:"auto_recover_on_403"` @@ -44,6 +46,8 @@ var QualityBPSManagedKeys = []string{ "openai_excel_bps_models", ExcelBPSOmitUnsupportedToolsKey, ExcelBPSIgnoreEncryptedContentKey, + ExcelBPSWebSearchKey, + ExcelBPSWebSearchAutoKey, "openai_excel_bps_auto_disable_on_403", ExcelBPSAutoRecoverOn403Key, ExcelBPS403RecoveryIntervalMinutesKey, @@ -127,6 +131,8 @@ func QualityBPSExtra(b *QualityBPSPolicy) map[string]any { interval = *b.RecoveryIntervalMinutes } extra := map[string]any{ + ExcelBPSWebSearchKey: b.WebSearch, + ExcelBPSWebSearchAutoKey: b.WebSearch && b.WebSearchAuto, ExcelBPS403RecoveryIntervalMinutesKey: interval, "openai_excel_bps": true, "openai_excel_bps_models": nil, diff --git a/backend/internal/service/basispoints/WEB_SEARCH.md b/backend/internal/service/basispoints/WEB_SEARCH.md index ab114cdeebed..a29f5f9ef85b 100644 --- a/backend/internal/service/basispoints/WEB_SEARCH.md +++ b/backend/internal/service/basispoints/WEB_SEARCH.md @@ -54,3 +54,11 @@ provide an established billable token contract here; no synthetic token charge is invented for it. Any provider-side search cost/entitlement needs separate operational verification before enabling accounts. No real paid call is part of CI or local validation. + +## Management entry points + +The account editor, bulk editor, OAuth BPS defaults card and quality-rule BPS +settings share the same search controls. Automatic search is disabled and cleared +when its parent search switch is off. Quality-rule snapshots manage both fields. +The notice ID `bps-account-search-initial-announcement` is shared across these +entry points and dismissed per administrator/browser using existing localStorage. diff --git a/backend/internal/service/bps_search_settings_test.go b/backend/internal/service/bps_search_settings_test.go new file mode 100644 index 000000000000..de07b56d2cd2 --- /dev/null +++ b/backend/internal/service/bps_search_settings_test.go @@ -0,0 +1,32 @@ +package service + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBPSSearchDefaultsAndQualityPolicyRoundTrip(t *testing.T) { + defaults := DefaultExcelBPSDefaults() + require.False(t, defaults.WebSearch) + require.False(t, defaults.WebSearchAuto) + for _, enabled := range []bool{false, true} { + defaults.WebSearch, defaults.WebSearchAuto = enabled, true + raw, err := json.Marshal(defaults) + require.NoError(t, err) + var restored ExcelBPSDefaults + require.NoError(t, json.Unmarshal(raw, &restored)) + require.Equal(t, enabled, restored.extra()[ExcelBPSWebSearchKey]) + require.Equal(t, enabled, restored.extra()[ExcelBPSWebSearchAutoKey]) + extra := QualityBPSExtra(&QualityBPSPolicy{WebSearch: enabled, WebSearchAuto: true}) + require.Equal(t, enabled, extra[ExcelBPSWebSearchKey]) + require.Equal(t, enabled, extra[ExcelBPSWebSearchAutoKey]) + } + require.Contains(t, QualityBPSManagedKeys, ExcelBPSWebSearchKey) + require.Contains(t, QualityBPSManagedKeys, ExcelBPSWebSearchAutoKey) + var legacy ExcelBPSDefaults + require.NoError(t, json.Unmarshal([]byte(`{"models":["gpt-6-astra"]}`), &legacy)) + require.False(t, legacy.WebSearch) + require.False(t, legacy.WebSearchAuto) +} diff --git a/backend/internal/service/oauth_auto_config_bps.go b/backend/internal/service/oauth_auto_config_bps.go index a1d6485062b5..b2fa8e5551ea 100644 --- a/backend/internal/service/oauth_auto_config_bps.go +++ b/backend/internal/service/oauth_auto_config_bps.go @@ -13,6 +13,8 @@ type ExcelBPSDefaults struct { AllModels bool `json:"all_models"` Models []string `json:"models"` OmitUnsupportedTools bool `json:"omit_unsupported_tools"` + WebSearch bool `json:"web_search"` + WebSearchAuto bool `json:"web_search_auto"` IgnoreEncryptedContent bool `json:"ignore_encrypted_content"` AutoDisableOn403 bool `json:"auto_disable_on_403"` AutoRecoverOn403 bool `json:"auto_recover_on_403"` @@ -63,6 +65,8 @@ func validateExcelBPSDefaults(b ExcelBPSDefaults) error { func (b ExcelBPSDefaults) extra() map[string]any { extra := map[string]any{ + ExcelBPSWebSearchKey: b.WebSearch, + ExcelBPSWebSearchAutoKey: b.WebSearch && b.WebSearchAuto, "openai_excel_bps": true, "openai_excel_bps_omit_unsupported_tools": b.OmitUnsupportedTools, "openai_excel_bps_ignore_encrypted_content": b.IgnoreEncryptedContent, diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index 9a11746ebd7a..12e9996ffcf7 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -66,6 +66,7 @@{{ t('admin.accounts.openai.excelBPSModelsHint') }}
{{ t('admin.accounts.openai.excelBPSNotice') }}
+{{ t('admin.accounts.openai.excelBPSNotice') }}
+