diff --git a/.github/scripts/encrypted-history-409-preview.mjs b/.github/scripts/encrypted-history-409-preview.mjs
new file mode 100644
index 000000000000..8190aaff2587
--- /dev/null
+++ b/.github/scripts/encrypted-history-409-preview.mjs
@@ -0,0 +1,70 @@
+// Render the production Vue setting with synthetic state. No external API.
+import { mkdirSync, mkdtempSync, writeFileSync, unlinkSync, rmSync } 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] = process.argv.slice(2)
+if (!repoArg || !outputArg) throw Error('Usage: node encrypted-history-409-preview.mjs REPO OUTPUT')
+const repo = resolve(repoArg), root = join(repo, 'frontend'), output = resolve(outputArg)
+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.PLAYWRIGHT_MODULE).href)
+const cache = mkdtempSync(join(tmpdir(), 'encrypted-history-409-'))
+const entryName = `.encrypted-history-409-${process.pid}.js`, entry = join(root, entryName)
+const origin = 'http://127.0.0.1:4297', errors = []
+let server, browser
+mkdirSync(output, { recursive: true })
+try {
+ writeFileSync(entry, `
+import {createApp,ref} from 'vue';
+import {createPinia} from 'pinia';
+import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';
+import Setting from '/src/components/settings/EncryptedHistory409Settings.vue';
+import '/src/style.css';
+const locale=new URL(location.href).searchParams.get('locale')||'zh';
+await loadLocaleMessages(locale); i18n.global.locale.value=locale;
+createApp({components:{Setting},setup(){return {enabled:ref(false)}},template:'System settings → Gateway · Actual component / fictional data
'}).use(createPinia()).use(i18n).mount('#app');
+`, { flag: 'wx' })
+ process.chdir(root)
+ server = await createServer({ root, configFile: false, cacheDir: cache,
+ resolve: { alias: { '@': join(root, 'src'), vue: 'vue/dist/vue.esm-bundler.js' } },
+ plugins: [{ name: 'encrypted-history-preview', configureServer(s) {
+ s.middlewares.use((req, res, next) => {
+ if (req.url === '/' || req.url?.startsWith('/?')) {
+ res.setHeader('Content-Type', 'text/html')
+ res.end(`
`)
+ } else if (req.url === '/favicon.ico') { res.statusCode = 204; res.end() } else next()
+ })
+ } }, vue()],
+ server: { host: '127.0.0.1', port: 4297, strictPort: true },
+ })
+ await server.listen()
+ browser = await chromium.launch({ headless: true })
+ const page = await browser.newPage({ viewport: { width: 1100, height: 620 } })
+ page.on('pageerror', e => errors.push(e.message))
+ await page.route('**/*', route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort())
+ await page.goto(origin, { waitUntil: 'networkidle' })
+ const toggle = page.getByTestId('openai-409-omit-encrypted-history-toggle')
+ await toggle.waitFor()
+ await page.screenshot({ path: join(output, 'default-off.png'), fullPage: true, animations: 'disabled' })
+ await toggle.click()
+ await page.screenshot({ path: join(output, 'enabled.png'), fullPage: true, animations: 'disabled' })
+ await page.evaluate(() => document.documentElement.classList.add('dark'))
+ await page.setViewportSize({ width: 430, height: 700 })
+ await page.screenshot({ path: join(output, 'mobile-dark.png'), fullPage: true, animations: 'disabled' })
+ await page.setViewportSize({ width: 1100, height: 620 })
+ await page.goto(origin + '/?locale=en', { waitUntil: 'networkidle' })
+ await toggle.waitFor()
+ await page.screenshot({ path: join(output, 'english.png'), fullPage: true, animations: 'disabled' })
+ writeFileSync(join(output, 'manifest.json'), JSON.stringify({ source: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim(), boundary: 'Actual Vue setting component with fictional state; no full-page navigation, backend or production acceptance', errors }, null, 2))
+ if (errors.length) throw Error(errors.join('\n'))
+} finally {
+ await browser?.close()
+ await server?.close()
+ unlinkSync(entry)
+ rmSync(cache, { recursive: true, force: true })
+}
diff --git a/.github/workflows/encrypted-history-409.yml b/.github/workflows/encrypted-history-409.yml
new file mode 100644
index 000000000000..cbec6031b3a6
--- /dev/null
+++ b/.github/workflows/encrypted-history-409.yml
@@ -0,0 +1,71 @@
+name: Encrypted history 409 Beta
+on:
+ pull_request:
+ paths:
+ - 'backend/internal/service/openai_409_omit_history*'
+ - 'backend/internal/handler/openai_409_omit_history*'
+ - 'frontend/src/components/settings/EncryptedHistory409Settings.vue'
+ - '.github/scripts/encrypted-history-409-preview.mjs'
+ - '.github/workflows/encrypted-history-409.yml'
+permissions:
+ contents: read
+jobs:
+ protocol:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ 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
+ - name: Install isolated Redis fixture
+ run: |
+ bash .github/scripts/ci-ubuntu-mirrors.sh
+ if ! command -v redis-server >/dev/null; then
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends redis-server
+ fi
+ - name: Actual HTTP and Redis omission regressions
+ working-directory: backend
+ shell: bash
+ run: |
+ set -euo pipefail
+ go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin -run '^Test(OmitOpenAIHistorical|OpenAI409|UpdateSettingsOpenAI409)' -count=1 -v -timeout=5m 2>&1 | tee "$RUNNER_TEMP/omit-history-protocol.log"
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: encrypted-history-409-protocol-${{ github.event.pull_request.head.sha }}
+ path: ${{ runner.temp }}/omit-history-protocol.log
+ screenshots:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ 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
+ - name: Install isolated screenshot browser
+ run: |
+ npm install --prefix "$RUNNER_TEMP/omit-history-browser" --no-save --ignore-scripts playwright@1.56.1
+ "$RUNNER_TEMP/omit-history-browser/node_modules/.bin/playwright" install --with-deps chromium
+ - name: Capture actual setting component
+ env:
+ PLAYWRIGHT_MODULE: ${{ runner.temp }}/omit-history-browser/node_modules/playwright/index.mjs
+ run: node .github/scripts/encrypted-history-409-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/omit-history-ui"
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: encrypted-history-409-ui-${{ github.event.pull_request.head.sha }}
+ path: ${{ runner.temp }}/omit-history-ui
+ if-no-files-found: error
diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml
index 5376478e7388..961d1eadd5ed 100644
--- a/.github/workflows/issue715-agent-recovery.yml
+++ b/.github/workflows/issue715-agent-recovery.yml
@@ -98,7 +98,7 @@ jobs:
git rev-parse HEAD
original=6df0cd5bb0ce4d774d34004008f9dd661d236468
targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_gateway_response_handling.go backend/internal/service/openai_gateway_service.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go)
- added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_agent_message_recovery_wait.go backend/internal/service/openai_ws_search_activation.go)
+ added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_agent_message_recovery_wait.go backend/internal/service/openai_ws_search_activation.go backend/internal/service/openai_409_omit_history.go)
# The exact original gateway struct predates analysis admission state.
# Pin this unrelated leaf to its pre-admission version, preserving all
# Issue715 business-chain blobs and the retained handler regressions.
@@ -243,10 +243,12 @@ jobs:
scheduler_compat=45e92f44470f91435bd261ea18111c271063c0ac
scheduler_leaf=backend/internal/service/openai_account_scheduler.go
wait_added=backend/internal/service/openai_agent_message_recovery_wait.go
+ # The Beta helper depends on fields absent in this historical recovery struct.
+ omission_added=backend/internal/service/openai_409_omit_history.go
git fetch --no-tags --depth=1 origin "$original"
git fetch --no-tags --depth=1 origin "$ws_original"
git fetch --no-tags --depth=1 origin "$scheduler_compat"
- trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added"; git diff --exit-code' EXIT
+ trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "$omission_added"; git diff --exit-code' EXIT
git restore --source="$original" -- "${targets[@]}"
git restore --source="$ws_original" -- "${ws_targets[@]}"
git restore --source="$scheduler_compat" -- "$scheduler_leaf"
@@ -254,7 +256,7 @@ jobs:
actual=$(git hash-object "$scheduler_leaf")
echo "compatibility_leaf_baseline=$scheduler_compat path=$scheduler_leaf expected_blob=$expected tested_blob=$actual"
test "$expected" = "$actual"
- rm -- "$added" "${ws_added[@]}" "$wait_added"
+ rm -- "$added" "${ws_added[@]}" "$wait_added" "$omission_added"
test ! -e "$wait_added"
for target in "${targets[@]}"; do
expected=$(git rev-parse "$original:$target")
diff --git a/.github/workflows/issue805-owner-policy.yml b/.github/workflows/issue805-owner-policy.yml
index e90c3256b281..437a9a86679f 100644
--- a/.github/workflows/issue805-owner-policy.yml
+++ b/.github/workflows/issue805-owner-policy.yml
@@ -80,6 +80,13 @@ jobs:
echo "$target test=baseline expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
test "$expected" = "$actual"
done
+ # This later Beta test references a setting absent from the old production
+ # baseline. Exclude only this unrelated file in RED; GREEN retains it.
+ omission_test=backend/internal/handler/openai_409_omit_history_test.go
+ git cat-file -e "$EXPECTED_HEAD_SHA:$omission_test"
+ rm -- "$omission_test"
+ test ! -e "$omission_test"
+ echo "$omission_test test=candidate-only actual=absent" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
# The selected regression and its shared harness must remain exact
# candidate blobs. The clean GREEN checkout retains all new tests.
for target in backend/internal/handler/openai_issue805_delivery_test.go backend/internal/handler/openai_issue805_owner_policy_test.go backend/internal/handler/openai_issue805_ws_test.go backend/internal/handler/openai_issue715_recovery_test.go; do
diff --git a/backend/internal/handler/admin/setting_handler.go b/backend/internal/handler/admin/setting_handler.go
index c4b09ff7b0b5..f021b89c233a 100644
--- a/backend/internal/handler/admin/setting_handler.go
+++ b/backend/internal/handler/admin/setting_handler.go
@@ -414,10 +414,11 @@ func (h *SettingHandler) GetSettings(c *gin.Context) {
PrismBrowserBaseURL: settings.PrismBrowserBaseURL,
PrismBrowserAPIKeyConfigured: settings.PrismBrowserAPIKeyConfigured,
- GrokDefaultTextModel: settings.GrokDefaultTextModel,
- GrokCrossClientModelMapEnabled: settings.GrokCrossClientModelMapEnabled,
- GrokDefaultBaseURLMode: settings.GrokDefaultBaseURLMode,
- GrokVideoSourceURLEnabled: settings.GrokVideoSourceURLEnabled,
+ GrokDefaultTextModel: settings.GrokDefaultTextModel,
+ GrokCrossClientModelMapEnabled: settings.GrokCrossClientModelMapEnabled,
+ GrokDefaultBaseURLMode: settings.GrokDefaultBaseURLMode,
+ GrokVideoSourceURLEnabled: settings.GrokVideoSourceURLEnabled,
+ OpenAI409OmitEncryptedHistoryEnabled: settings.OpenAI409OmitEncryptedHistoryEnabled,
AvailableChannelsEnabled: settings.AvailableChannelsEnabled,
PelicanShowcaseEnabled: settings.PelicanShowcaseEnabled,
diff --git a/backend/internal/handler/admin/setting_handler_partial_payload_test.go b/backend/internal/handler/admin/setting_handler_partial_payload_test.go
index 19aecc5fd839..83d24b596681 100644
--- a/backend/internal/handler/admin/setting_handler_partial_payload_test.go
+++ b/backend/internal/handler/admin/setting_handler_partial_payload_test.go
@@ -96,6 +96,24 @@ func TestUpdateSettingsGrokVideoSourceURLSwitchRoundTrips(t *testing.T) {
require.Equal(t, "false", repo.values[service.SettingKeyGrokVideoSourceURLEnabled])
}
+func TestUpdateSettingsOpenAI409OmitEncryptedHistorySwitchRoundTrips(t *testing.T) {
+ h, repo := newStepUpSwitchTestHandler(t, map[string]string{
+ service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "false",
+ })
+
+ rec := doUpdateSettings(t, h, map[string]any{"openai_409_omit_encrypted_history_enabled": true}, nil)
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, "true", repo.values[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled])
+
+ rec = doUpdateSettings(t, h, map[string]any{"smtp_from_email": "other@example.com"}, nil)
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, "true", repo.values[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled])
+
+ rec = doUpdateSettings(t, h, map[string]any{"openai_409_omit_encrypted_history_enabled": false}, nil)
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, "false", repo.values[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled])
+}
+
func TestUpdateSettingsRejectsTwoCaptchaProviders(t *testing.T) {
h, _ := newStepUpSwitchTestHandler(t, map[string]string{
service.SettingKeyTurnstileEnabled: "true",
diff --git a/backend/internal/handler/admin/setting_handler_update.go b/backend/internal/handler/admin/setting_handler_update.go
index 7da5c5b6e261..33d00c3888ec 100644
--- a/backend/internal/handler/admin/setting_handler_update.go
+++ b/backend/internal/handler/admin/setting_handler_update.go
@@ -367,10 +367,11 @@ type UpdateSettingsRequest struct {
ChannelMonitorHideUserRanking *bool `json:"channel_monitor_hide_user_ranking"`
// Grok model mapping policy
- GrokDefaultTextModel *string `json:"grok_default_text_model"`
- GrokCrossClientModelMapEnabled *bool `json:"grok_cross_client_model_map_enabled"`
- GrokDefaultBaseURLMode *string `json:"grok_default_base_url_mode"`
- GrokVideoSourceURLEnabled *bool `json:"grok_video_source_url_enabled"`
+ GrokDefaultTextModel *string `json:"grok_default_text_model"`
+ GrokCrossClientModelMapEnabled *bool `json:"grok_cross_client_model_map_enabled"`
+ GrokDefaultBaseURLMode *string `json:"grok_default_base_url_mode"`
+ GrokVideoSourceURLEnabled *bool `json:"grok_video_source_url_enabled"`
+ OpenAI409OmitEncryptedHistoryEnabled *bool `json:"openai_409_omit_encrypted_history_enabled"`
// Available Channels feature switch (user-facing)
AvailableChannelsEnabled *bool `json:"available_channels_enabled"`
@@ -2353,6 +2354,12 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
}
return previousSettings.GrokVideoSourceURLEnabled
}(),
+ OpenAI409OmitEncryptedHistoryEnabled: func() bool {
+ if req.OpenAI409OmitEncryptedHistoryEnabled != nil {
+ return *req.OpenAI409OmitEncryptedHistoryEnabled
+ }
+ return previousSettings.OpenAI409OmitEncryptedHistoryEnabled
+ }(),
AvailableChannelsEnabled: func() bool {
if req.AvailableChannelsEnabled != nil {
return *req.AvailableChannelsEnabled
@@ -2870,10 +2877,11 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
ChannelMonitorShowQuota: updatedSettings.ChannelMonitorShowQuota,
ChannelMonitorHideUserRanking: updatedSettings.ChannelMonitorHideUserRanking,
- GrokDefaultTextModel: updatedSettings.GrokDefaultTextModel,
- GrokCrossClientModelMapEnabled: updatedSettings.GrokCrossClientModelMapEnabled,
- GrokDefaultBaseURLMode: updatedSettings.GrokDefaultBaseURLMode,
- GrokVideoSourceURLEnabled: updatedSettings.GrokVideoSourceURLEnabled,
+ GrokDefaultTextModel: updatedSettings.GrokDefaultTextModel,
+ GrokCrossClientModelMapEnabled: updatedSettings.GrokCrossClientModelMapEnabled,
+ GrokDefaultBaseURLMode: updatedSettings.GrokDefaultBaseURLMode,
+ GrokVideoSourceURLEnabled: updatedSettings.GrokVideoSourceURLEnabled,
+ OpenAI409OmitEncryptedHistoryEnabled: updatedSettings.OpenAI409OmitEncryptedHistoryEnabled,
AvailableChannelsEnabled: updatedSettings.AvailableChannelsEnabled,
PelicanShowcaseEnabled: updatedSettings.PelicanShowcaseEnabled,
diff --git a/backend/internal/handler/dto/settings.go b/backend/internal/handler/dto/settings.go
index a24e92264f03..c665ef320481 100644
--- a/backend/internal/handler/dto/settings.go
+++ b/backend/internal/handler/dto/settings.go
@@ -342,10 +342,11 @@ type SystemSettings struct {
ChannelMonitorHideUserRanking bool `json:"channel_monitor_hide_user_ranking"`
// Grok model mapping policy (admin settings; empty account mapping falls back to these).
- GrokDefaultTextModel string `json:"grok_default_text_model"`
- GrokCrossClientModelMapEnabled bool `json:"grok_cross_client_model_map_enabled"`
- GrokDefaultBaseURLMode string `json:"grok_default_base_url_mode"`
- GrokVideoSourceURLEnabled bool `json:"grok_video_source_url_enabled"`
+ GrokDefaultTextModel string `json:"grok_default_text_model"`
+ GrokCrossClientModelMapEnabled bool `json:"grok_cross_client_model_map_enabled"`
+ GrokDefaultBaseURLMode string `json:"grok_default_base_url_mode"`
+ GrokVideoSourceURLEnabled bool `json:"grok_video_source_url_enabled"`
+ OpenAI409OmitEncryptedHistoryEnabled bool `json:"openai_409_omit_encrypted_history_enabled"`
// Available Channels feature switch (user-facing aggregate view)
AvailableChannelsEnabled bool `json:"available_channels_enabled"`
diff --git a/backend/internal/handler/openai_409_omit_history_test.go b/backend/internal/handler/openai_409_omit_history_test.go
new file mode 100644
index 000000000000..63c0c545ce53
--- /dev/null
+++ b/backend/internal/handler/openai_409_omit_history_test.go
@@ -0,0 +1,133 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/Wei-Shaw/sub2api/internal/testutil"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+type omit409SettingsRepo struct {
+ service.SettingRepository
+ enabled bool
+}
+
+func (s *omit409SettingsRepo) GetValue(_ context.Context, key string) (string, error) {
+ if key == service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled {
+ return fmt.Sprint(s.enabled), nil
+ }
+ return "", service.ErrSettingNotFound
+}
+
+func (s *omit409SettingsRepo) GetMultiple(_ context.Context, _ []string) (map[string]string, error) {
+ return map[string]string{service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: fmt.Sprint(s.enabled)}, nil
+}
+
+func TestOpenAI409OmitHistoryHTTP(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ for _, scenario := range []string{"off", "paused", "route_changed", "no_accounts", "current_task", "upstream_rejects"} {
+ t.Run(fmt.Sprintf("%s/stream=%t", scenario, stream), func(t *testing.T) {
+ clients := issue805Redis(t)
+ var mu sync.Mutex
+ var bodies [][]byte
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ mu.Lock()
+ bodies = append(bodies, body)
+ n := len(bodies)
+ mu.Unlock()
+ if n > 1 && scenario == "upstream_rejects" {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","message":"fixture rejects sanitized history"}}`)
+ return
+ }
+ output := "[" + issue715Agent + "]"
+ if n > 1 {
+ output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"continued from visible history"}]}]`
+ }
+ payload := fmt.Sprintf(`{"id":"resp_omit_%d","status":"completed","error":null,"model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, n, output)
+ if gjson.GetBytes(body, "stream").Bool() {
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", payload)
+ } else {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, payload)
+ }
+ }))
+ defer srv.Close()
+ accounts := issue715Accounts()
+ for i := range accounts {
+ accounts[i].Type = service.AccountTypeAPIKey
+ accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture-omit-%d", i), "base_url": srv.URL}
+ }
+ newNode := func(enabled bool) *OpenAIGatewayHandler {
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ settings := service.NewSettingService(&omit409SettingsRepo{enabled: enabled}, cfg)
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, testutil.NewRealHTTPUpstream(cfg), repository.NewGatewayCache(clients()), settings, accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ return h
+ }
+ first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1))
+ require.Equal(t, http.StatusOK, first.Code, first.Body.String())
+ originalOwners := issue805Owners(t, clients())
+ require.Len(t, originalOwners, 1)
+ accounts[0].Schedulable = false
+ if scenario == "route_changed" {
+ accounts[0].Schedulable = true
+ accounts[0].Credentials["api_key"] = "fixture-rotated"
+ }
+ if scenario == "no_accounts" {
+ accounts[1].Schedulable = false
+ }
+ followup := issue715Body(true, stream)
+ if scenario == "current_task" {
+ followup = fmt.Sprintf(`{"model":"gpt-5.1","stream":%t,"input":[%s]}`, stream, issue715Agent)
+ }
+ answer := issue758Request(t, newNode(scenario != "off"), followup)
+ mu.Lock()
+ defer mu.Unlock()
+ switch scenario {
+ case "off", "current_task":
+ require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String())
+ require.Len(t, bodies, 1)
+ case "no_accounts":
+ require.GreaterOrEqual(t, answer.Code, 400)
+ require.Len(t, bodies, 1)
+ default:
+ require.Len(t, bodies, 2, "one original request and exactly one sanitized continuation")
+ require.NotContains(t, string(bodies[1]), "fixture-task-reference-715")
+ require.Contains(t, string(bodies[1]), "Historical encrypted content omitted")
+ for _, path := range []string{"input.1", "input.2", "input.3", "input.4"} {
+ require.JSONEq(t, gjson.Get(followup, path).Raw, gjson.GetBytes(bodies[1], path).Raw, "readable history and tool results survive")
+ }
+ if scenario == "upstream_rejects" {
+ require.GreaterOrEqual(t, answer.Code, 400)
+ } else {
+ require.Equal(t, http.StatusOK, answer.Code, answer.Body.String())
+ require.Contains(t, answer.Body.String(), "continued from visible history")
+ }
+ }
+ require.Equal(t, originalOwners, issue805Owners(t, clients()), "omission must not clear or rewrite the original owner")
+ })
+ }
+ }
+}
diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go
index 8bd348309987..aeb7fc8a9fee 100644
--- a/backend/internal/handler/openai_gateway_handler.go
+++ b/backend/internal/handler/openai_gateway_handler.go
@@ -33,6 +33,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
"go.uber.org/zap"
)
@@ -968,6 +969,8 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
var rpmAdmission openAIRPMAdmission
var oauth429FailoverState service.OpenAIOAuth429FailoverState
var passthroughFailoverState openAIPassthroughFailoverState
+ omittedEncryptedHistory := false
+ upstreamAttempted := false
// 生图意图的 /v1/responses 请求必须调度到确实支持 Responses API 的账号,否则
// 会在 forward 阶段被静默降级为无法生图的 Chat Completions 直转(#4417)。
@@ -1018,6 +1021,19 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
requestPlatform,
)
if err != nil {
+ if !omittedEncryptedHistory && !upstreamAttempted && !streamStarted && !c.Writer.Written() && requestPlatform == service.PlatformOpenAI {
+ if next, clean, changed := h.gatewayService.TryOmitOpenAI409History(c.Request.Context(), c, body, sessionHash, forwardModel, err); changed {
+ // Preserve the channel's model mapping while replacing only input.
+ mapped, mapErr := sjson.SetRawBytes(forwardBody, "input", []byte(gjson.GetBytes(clean, "input").Raw))
+ if mapErr == nil {
+ body, forwardBody = clean, mapped
+ omittedEncryptedHistory = true
+ c.Request = c.Request.WithContext(next)
+ reqLog.Info("openai.encrypted_history_409_omitted", zap.Bool("context_loss", true))
+ continue
+ }
+ }
+ }
if h.handleOpenAIAgentRecoveryError(c, err, streamStarted) {
return
}
@@ -1135,6 +1151,8 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
return
}
+ // Omission is only allowed before this request has attempted any forward.
+ upstreamAttempted = true
// Forward request
service.SetOpsLatencyMs(c, service.OpsRoutingLatencyMsKey, time.Since(routingStart).Milliseconds())
forwardStart := time.Now()
diff --git a/backend/internal/handler/openai_responses_failover_cancel_test.go b/backend/internal/handler/openai_responses_failover_cancel_test.go
index ef0f2f0b431d..4c739b82c1e2 100644
--- a/backend/internal/handler/openai_responses_failover_cancel_test.go
+++ b/backend/internal/handler/openai_responses_failover_cancel_test.go
@@ -55,6 +55,11 @@ func newOpenAIResponsesFailoverTestHandler(t *testing.T, upstream service.HTTPUp
}
func newOpenAIResponsesFailoverTestHandlerWithCache(t *testing.T, upstream service.HTTPUpstream, cache service.GatewayCache, fixtureAccounts ...service.Account) *OpenAIGatewayHandler {
+ t.Helper()
+ return newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, cache, nil, fixtureAccounts...)
+}
+
+func newOpenAIResponsesFailoverTestHandlerWithSettings(t *testing.T, upstream service.HTTPUpstream, cache service.GatewayCache, settings *service.SettingService, fixtureAccounts ...service.Account) *OpenAIGatewayHandler {
t.Helper()
accounts := []service.Account{
{
@@ -111,7 +116,7 @@ func newOpenAIResponsesFailoverTestHandlerWithCache(t *testing.T, upstream servi
nil,
nil,
nil,
- nil,
+ settings,
nil,
)
billingService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go
index 0b19c2c40b55..79ed100cc8b9 100644
--- a/backend/internal/server/api_contract_test.go
+++ b/backend/internal/server/api_contract_test.go
@@ -935,6 +935,7 @@ func TestAPIContracts(t *testing.T) {
"grok_default_text_model": "grok-4.6",
"grok_default_base_url_mode": "cli",
"grok_video_source_url_enabled": false,
+ "openai_409_omit_encrypted_history_enabled": false,
"grok_cross_client_model_map_enabled": true,
"purchase_subscription_enabled": false,
"purchase_subscription_url": "",
@@ -1262,6 +1263,7 @@ func TestAPIContracts(t *testing.T) {
"grok_default_text_model": "grok-4.6",
"grok_default_base_url_mode": "cli",
"grok_video_source_url_enabled": false,
+ "openai_409_omit_encrypted_history_enabled": false,
"grok_cross_client_model_map_enabled": true,
"purchase_subscription_enabled": false,
"purchase_subscription_url": "",
diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go
index a8d541bd6010..a300fdbd3657 100644
--- a/backend/internal/service/domain_constants.go
+++ b/backend/internal/service/domain_constants.go
@@ -555,7 +555,8 @@ const (
// SettingKeyGrokVideoSourceURLEnabled, when true, adds the validated xAI
// media URL as video.source_url to Grok video status responses. video.url
// stays the authenticated Sub2API content proxy. Default false.
- SettingKeyGrokVideoSourceURLEnabled = "grok_video_source_url_enabled"
+ SettingKeyGrokVideoSourceURLEnabled = "grok_video_source_url_enabled"
+ SettingKeyOpenAI409OmitEncryptedHistoryEnabled = "openai_409_omit_encrypted_history_enabled"
// SettingKeyAvailableChannelsEnabled is a DB-backed soft switch for the "Available Channels"
// user-facing aggregate view. When false: user endpoint returns an empty list and the
diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go
new file mode 100644
index 000000000000..e1872d2fc0d9
--- /dev/null
+++ b/backend/internal/service/openai_409_omit_history.go
@@ -0,0 +1,163 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/gin-gonic/gin"
+ "github.com/tidwall/gjson"
+)
+
+const openAIHistoricalCiphertextOmitted = "[Historical encrypted content omitted by the gateway. Its contents are unavailable; do not infer missing instructions or results.]"
+
+// This rare refusal path reads the persisted switch directly. A missing value,
+// unavailable store or canceled request never opts a request into data loss.
+func (s *SettingService) IsOpenAI409OmitEncryptedHistoryEnabled(ctx context.Context) bool {
+ if s == nil || s.settingRepo == nil || ctx.Err() != nil {
+ return false
+ }
+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+ value, err := s.settingRepo.GetValue(ctx, SettingKeyOpenAI409OmitEncryptedHistoryEnabled)
+ return err == nil && strings.TrimSpace(value) == "true"
+}
+
+// TryOmitOpenAI409History is called only after initial account selection fails,
+// before any upstream attempt. It never handles provider responses or retries.
+func (s *OpenAIGatewayService) TryOmitOpenAI409History(ctx context.Context, c *gin.Context, body []byte, session, model string, cause error) (context.Context, []byte, bool) {
+ var refusal *OpenAIAgentRecoveryError
+ if !errors.As(cause, &refusal) || (refusal.Reason != "owner_unavailable" && refusal.Reason != "route_changed" && refusal.Reason != "wire_changed") {
+ return ctx, body, false
+ }
+ r := openAIAgentRecoveryFromContext(ctx)
+ if s == nil || r == nil || r.owner == nil || r.conflict || r.lookupErr != nil || r.disallowLearning || r.omittedHistory ||
+ r.owner.pending != "" || r.owner.failed || r.owner.conflicted ||
+ !s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) {
+ return ctx, body, false
+ }
+ clean, changed := omitOpenAIHistoricalCiphertext(body)
+ if !changed || ctx.Err() != nil {
+ return ctx, body, false
+ }
+ next := s.WithOpenAIAgentMessageRecovery(ctx, c, clean, session, model)
+ request := openAIAgentRecoveryFromContext(next)
+ // Preserve the sanitized input at the actual send and reuse the existing
+ // native HTTP delivery fence and no-replay gates. Old owner records stay put.
+ request.omittedHistory = true
+ request.inputDigest = openAIAgentRecoveryInputDigest(clean)
+ return next, clean, true
+}
+
+// Omission is limited to history before the latest user/agent task. Tool
+// arguments, readable results, media, reasoning and numeric precision survive.
+// A ciphertext in the current task causes the entire operation to be refused.
+func omitOpenAIHistoricalCiphertext(raw []byte) ([]byte, bool) {
+ if !utf8.Valid(raw) || !openAIEncryptedJSONUnambiguous(raw) {
+ return raw, false
+ }
+ for _, field := range []string{"previous_response_id", "conversation"} {
+ value := gjson.GetBytes(raw, field)
+ if value.Exists() && value.Type != gjson.Null && (value.Type != gjson.String || strings.TrimSpace(value.String()) != "") {
+ return raw, false
+ }
+ }
+ var source map[string]any
+ decoder := json.NewDecoder(bytes.NewReader(raw))
+ decoder.UseNumber()
+ if decoder.Decode(&source) != nil {
+ return raw, false
+ }
+ input, ok := source["input"].([]any)
+ if !ok {
+ return raw, false
+ }
+ current := -1
+ for i, value := range input {
+ item, _ := value.(map[string]any)
+ kind, _ := item["type"].(string)
+ role, _ := item["role"].(string)
+ if kind == "item_reference" || kind == "compaction" || kind == "compaction_summary" {
+ return raw, false
+ }
+ if kind == "agent_message" || ((kind == "" || kind == "message") && role == "user") {
+ current = i
+ }
+ }
+ if current < 0 {
+ return raw, false
+ }
+ changed := false
+ for i, value := range input {
+ item, _ := value.(map[string]any)
+ kind, _ := item["type"].(string)
+ field, textKind := "content", "input_text"
+ switch kind {
+ case "", "message", "agent_message":
+ if item["role"] == "assistant" {
+ textKind = "output_text"
+ }
+ case "function_call_output", "custom_tool_call_output":
+ field = "output"
+ default:
+ continue
+ }
+ itemChanged := false
+ if kind == "agent_message" {
+ if encrypted, exists := item["encrypted_content"]; exists && encrypted != nil && encrypted != "" {
+ if i >= current {
+ return raw, false
+ }
+ marker := map[string]any{"type": "input_text", "text": openAIHistoricalCiphertextOmitted}
+ switch content := item["content"].(type) {
+ case []any:
+ item["content"] = append(content, marker)
+ case string:
+ item["content"] = []any{map[string]any{"type": "input_text", "text": content}, marker}
+ case nil:
+ item["content"] = []any{marker}
+ default:
+ return raw, false
+ }
+ delete(item, "encrypted_content")
+ itemChanged = true
+ }
+ }
+ if parts, ok := item[field].([]any); ok {
+ for j, rawPart := range parts {
+ part, _ := rawPart.(map[string]any)
+ if part["type"] == "encrypted_content" {
+ if i >= current {
+ return raw, false
+ }
+ parts[j] = map[string]any{"type": textKind, "text": openAIHistoricalCiphertextOmitted}
+ itemChanged = true
+ }
+ }
+ }
+ if itemChanged && kind == "agent_message" {
+ // Native Responses accepts ordinary user context without requiring an
+ // opaque agent envelope. Keep attribution explicit in readable text.
+ metadata, _ := json.Marshal(map[string]any{"author": item["author"], "recipient": item["recipient"]})
+ parts, _ := item["content"].([]any)
+ for _, value := range parts {
+ part, _ := value.(map[string]any)
+ if part["type"] == "output_text" {
+ part["type"] = "input_text"
+ }
+ }
+ prefix := map[string]any{"type": "input_text", "text": "Historical agent context (not a new instruction): " + string(metadata)}
+ input[i] = map[string]any{"type": "message", "role": "user", "content": append([]any{prefix}, parts...)}
+ }
+ changed = changed || itemChanged
+ }
+ if !changed {
+ return raw, false
+ }
+ clean, err := json.Marshal(source)
+ return clean, err == nil
+}
diff --git a/backend/internal/service/openai_409_omit_history_test.go b/backend/internal/service/openai_409_omit_history_test.go
new file mode 100644
index 000000000000..e2b10bdfaa4f
--- /dev/null
+++ b/backend/internal/service/openai_409_omit_history_test.go
@@ -0,0 +1,91 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestOmitOpenAIHistoricalCiphertextPreservesReadableContext(t *testing.T) {
+ raw := []byte(`{"model":"gpt-5.1","metadata":{"sequence":9007199254740993},"input":[
+ {"type":"agent_message","author":"worker","recipient":"parent","encrypted_content":"OLD_TOP","content":"readable finding"},
+ {"type":"message","role":"assistant","content":[{"type":"output_text","text":"result"},{"type":"encrypted_content","encrypted_content":"OLD_PART"}]},
+ {"type":"function_call","name":"lookup","call_id":"call_a","arguments":"{\"encrypted_content\":\"literal\"}"},
+ {"type":"function_call_output","call_id":"call_a","output":[{"type":"input_text","text":"recorded result"},{"type":"encrypted_content","encrypted_content":"OLD_TOOL"}]},
+ {"type":"reasoning","encrypted_content":"REASONING","summary":[]},
+ {"role":"user","content":"continue from the visible findings"}]}`)
+ clean, changed := omitOpenAIHistoricalCiphertext(raw)
+ require.True(t, changed)
+ for _, secret := range []string{"OLD_TOP", "OLD_PART", "OLD_TOOL"} {
+ require.NotContains(t, string(clean), secret)
+ }
+ for _, text := range []string{"readable finding", "recorded result", "REASONING", "9007199254740993", "worker", "parent"} {
+ require.Contains(t, string(clean), text)
+ }
+ require.Equal(t, "message", gjson.GetBytes(clean, "input.0.type").String())
+ require.Equal(t, "user", gjson.GetBytes(clean, "input.0.role").String())
+ for _, path := range []string{"input.2", "input.4", "input.5"} {
+ require.JSONEq(t, gjson.GetBytes(raw, path).Raw, gjson.GetBytes(clean, path).Raw)
+ }
+ require.Equal(t, "call_a", gjson.GetBytes(clean, "input.3.call_id").String())
+ require.Equal(t, "output_text", gjson.GetBytes(clean, "input.1.content.1.type").String())
+ again, changed := omitOpenAIHistoricalCiphertext(clean)
+ require.False(t, changed)
+ require.Equal(t, clean, again)
+}
+
+func TestOmitOpenAIHistoricalCiphertextRefusesCurrentTaskAndPointers(t *testing.T) {
+ for name, raw := range map[string]string{
+ "new agent": `{"input":[{"type":"agent_message","encrypted_content":"CURRENT","content":"header"}]}`,
+ "current user": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":[{"type":"encrypted_content","encrypted_content":"CURRENT"}]}]}`,
+ "current tool result": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"lookup"},{"type":"function_call_output","call_id":"x","output":[{"type":"encrypted_content","encrypted_content":"CURRENT"}]}]}`,
+ "response pointer": `{"previous_response_id":"resp_x","input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`,
+ "conversation": `{"conversation":{"id":"conv_x"},"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`,
+ "reference": `{"input":[{"type":"item_reference","id":"item_x"},{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`,
+ "compaction": `{"input":[{"type":"compaction","encrypted_content":"STATE"},{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`,
+ "duplicate keys": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}],"input":[]}`,
+ "plain history": `{"input":[{"role":"user","content":"keep encrypted_content as literal text"}]}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ clean, changed := omitOpenAIHistoricalCiphertext([]byte(raw))
+ require.False(t, changed)
+ require.Equal(t, raw, string(clean), "refusal must not partially sanitize input")
+ })
+ }
+}
+
+func TestOpenAI409OmissionSettingDefaultsOff(t *testing.T) {
+ for _, value := range []string{"", "false", "true", "invalid"} {
+ s := NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: value}}, nil)
+ require.Equal(t, value == "true", s.IsOpenAI409OmitEncryptedHistoryEnabled(context.Background()))
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ require.False(t, s.IsOpenAI409OmitEncryptedHistoryEnabled(ctx))
+ }
+ var missing *SettingService
+ require.False(t, missing.IsOpenAI409OmitEncryptedHistoryEnabled(context.Background()))
+}
+
+func TestOpenAI409OmissionCannotClearRecoveryBarriers(t *testing.T) {
+ s := &OpenAIGatewayService{settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)}
+ body := []byte(`{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`)
+ for _, reason := range []string{"delivery_pending", "store_unavailable", "owner_conflict", "owner_rate_limited", "owner_overloaded", "http_previous_response_unsupported"} {
+ ctx := context.WithValue(context.Background(), openAIAgentRecoveryContextKey{}, &openAIAgentRecoveryRequest{owner: &openAIAgentRecoveryBinding{accountID: 1}})
+ _, clean, changed := s.TryOmitOpenAI409History(ctx, nil, body, "fixture", "gpt-5.1", &OpenAIAgentRecoveryError{Reason: reason})
+ require.False(t, changed, reason)
+ require.Equal(t, body, clean)
+ }
+}
+
+func TestOmitOpenAIHistoricalAssistantAgentUsesUserTextParts(t *testing.T) {
+ raw := []byte(`{"input":[{"type":"agent_message","role":"assistant","content":[{"type":"output_text","text":"readable"},{"type":"encrypted_content","encrypted_content":"OLD"}]},{"role":"user","content":"continue"}]}`)
+ clean, changed := omitOpenAIHistoricalCiphertext(raw)
+ require.True(t, changed)
+ require.Equal(t, "user", gjson.GetBytes(clean, "input.0.role").String())
+ for _, part := range gjson.GetBytes(clean, "input.0.content").Array() {
+ require.Equal(t, "input_text", part.Get("type").String())
+ }
+ require.Contains(t, string(clean), "readable")
+}
diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go
index 29e8433d157f..f97d6d37ad49 100644
--- a/backend/internal/service/openai_account_scheduler.go
+++ b/backend/internal/service/openai_account_scheduler.go
@@ -642,6 +642,14 @@ func (s *defaultOpenAIAccountScheduler) Select(
if selection == nil || selection.Account == nil {
return nil, decision, openAIAgentRecoveryError("owner_unavailable")
}
+ // Reject a changed producer route before entering Forward. This also
+ // gives the explicit history-omission policy a pre-send refusal to handle.
+ if recoveryErr := s.service.checkOpenAIAgentRecoveryAccount(ctx, selection.Account); recoveryErr != nil {
+ if selection.ReleaseFunc != nil {
+ selection.ReleaseFunc()
+ }
+ return nil, decision, recoveryErr
+ }
decision.Layer = openAIAccountScheduleLayerSessionSticky
decision.StickySessionHit = true
decision.SelectedAccountID = selection.Account.ID
diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go
index 4d4937ce96a5..c5c62ddad1e7 100644
--- a/backend/internal/service/openai_agent_message_recovery.go
+++ b/backend/internal/service/openai_agent_message_recovery.go
@@ -45,6 +45,7 @@ type openAIAgentRecoveryState struct {
}
type openAIAgentRecoveryRequest struct {
+ omittedHistory bool // explicit Beta sanitization; preserve the resulting input and prohibit replay
disableOwnerBinding bool
previousResponseID string
inputDigest [32]byte
@@ -146,7 +147,7 @@ func (r *openAIAgentRecoveryRequest) ownerBindingRequired() bool {
}
func (r *openAIAgentRecoveryRequest) preservesHistory() bool {
- return r != nil && r.disableOwnerBinding && len(r.items) > 0
+ return r != nil && (r.omittedHistory || (r.disableOwnerBinding && len(r.items) > 0))
}
func openAIAgentRecoveryPreservesHistory(ctx context.Context) bool {
diff --git a/backend/internal/service/setting_parse.go b/backend/internal/service/setting_parse.go
index cde89fe3d3c7..de3d003663e2 100644
--- a/backend/internal/service/setting_parse.go
+++ b/backend/internal/service/setting_parse.go
@@ -217,10 +217,11 @@ func (s *SettingService) InitializeDefaultSettings(ctx context.Context) error {
// Grok compatibility defaults: cross-client mapping stays enabled unless
// operators explicitly disable it.
- SettingKeyGrokDefaultTextModel: "grok-4.6",
- SettingKeyGrokCrossClientModelMapEnabled: "true",
- SettingKeyGrokDefaultBaseURLMode: GrokDefaultBaseURLModeCLI,
- SettingKeyGrokVideoSourceURLEnabled: "false",
+ SettingKeyGrokDefaultTextModel: "grok-4.6",
+ SettingKeyGrokCrossClientModelMapEnabled: "true",
+ SettingKeyGrokDefaultBaseURLMode: GrokDefaultBaseURLModeCLI,
+ SettingKeyGrokVideoSourceURLEnabled: "false",
+ SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "false",
// Available channels feature (default disabled; opt-in)
SettingKeyAvailableChannelsEnabled: "false",
@@ -889,6 +890,7 @@ func (s *SettingService) parseSettings(settings map[string]string) *SystemSettin
result.GrokCrossClientModelMapEnabled = !isFalseSettingValue(settings[SettingKeyGrokCrossClientModelMapEnabled])
result.GrokDefaultBaseURLMode = normalizeGrokDefaultBaseURLMode(settings[SettingKeyGrokDefaultBaseURLMode])
result.GrokVideoSourceURLEnabled = settings[SettingKeyGrokVideoSourceURLEnabled] == "true"
+ result.OpenAI409OmitEncryptedHistoryEnabled = settings[SettingKeyOpenAI409OmitEncryptedHistoryEnabled] == "true"
// Available channels feature (default: disabled; strict true)
result.AvailableChannelsEnabled = settings[SettingKeyAvailableChannelsEnabled] == "true"
diff --git a/backend/internal/service/setting_update.go b/backend/internal/service/setting_update.go
index 26e926e5d95e..fc24b0e47126 100644
--- a/backend/internal/service/setting_update.go
+++ b/backend/internal/service/setting_update.go
@@ -508,6 +508,7 @@ func (s *SettingService) buildSystemSettingsUpdates(ctx context.Context, setting
updates[SettingKeyGrokCrossClientModelMapEnabled] = strconv.FormatBool(settings.GrokCrossClientModelMapEnabled)
updates[SettingKeyGrokDefaultBaseURLMode] = normalizeGrokDefaultBaseURLMode(settings.GrokDefaultBaseURLMode)
updates[SettingKeyGrokVideoSourceURLEnabled] = strconv.FormatBool(settings.GrokVideoSourceURLEnabled)
+ updates[SettingKeyOpenAI409OmitEncryptedHistoryEnabled] = strconv.FormatBool(settings.OpenAI409OmitEncryptedHistoryEnabled)
// Available channels feature switch
updates[SettingKeyAvailableChannelsEnabled] = strconv.FormatBool(settings.AvailableChannelsEnabled)
diff --git a/backend/internal/service/settings_view.go b/backend/internal/service/settings_view.go
index 10554a6cbb02..67ac39d119eb 100644
--- a/backend/internal/service/settings_view.go
+++ b/backend/internal/service/settings_view.go
@@ -221,10 +221,11 @@ type SystemSettings struct {
PrismBrowserAPIKey string `json:"-"`
// Grok model mapping policy (admin settings; empty mapping falls back to these).
- GrokDefaultTextModel string `json:"grok_default_text_model"`
- GrokCrossClientModelMapEnabled bool `json:"grok_cross_client_model_map_enabled"`
- GrokDefaultBaseURLMode string `json:"grok_default_base_url_mode"`
- GrokVideoSourceURLEnabled bool `json:"grok_video_source_url_enabled"`
+ GrokDefaultTextModel string `json:"grok_default_text_model"`
+ GrokCrossClientModelMapEnabled bool `json:"grok_cross_client_model_map_enabled"`
+ GrokDefaultBaseURLMode string `json:"grok_default_base_url_mode"`
+ GrokVideoSourceURLEnabled bool `json:"grok_video_source_url_enabled"`
+ OpenAI409OmitEncryptedHistoryEnabled bool `json:"openai_409_omit_encrypted_history_enabled"`
// Available Channels feature (user-facing aggregate view)
AvailableChannelsEnabled bool `json:"available_channels_enabled"`
diff --git a/docs/encrypted-history-409-beta.md b/docs/encrypted-history-409-beta.md
new file mode 100644
index 000000000000..b89454943d9b
--- /dev/null
+++ b/docs/encrypted-history-409-beta.md
@@ -0,0 +1,23 @@
+# 409 省略加密内容(Beta)
+
+入口:系统设置 → 网关设置 → 网关转发行为 → **409 省略加密内容(Beta)**。
+默认关闭。管理员保存后,对后续触发条件匹配的请求生效,无需重启。
+
+HTTP `/v1/responses` 在初次选号、尚未发送上游时,如果已登记的历史加密 agent 账号不可用或路线发生变化,严格模式会返回兼容性 409。开启本功能后,网关尝试省略旧历史中的密文,用明确的“历史加密内容已省略”文本替换,再按正常账号池规则选号一次。支持 JSON 和 SSE 响应。
+
+这是有损恢复。模型看不到被省略的内容,不能保证任务结论完整或供应商接受。可读消息、工具调用参数、可读工具结果、工具 ID 及顺序继续保留。已省略的 agent 历史转为带原 author/recipient 说明的普通上下文消息;reasoning 密文保持既有处理。
+
+以下条件继续返回原错误:
+
+- 最新用户或 agent 任务及其后的工具结果仍含不可读内容。
+- 请求依赖 `previous_response_id`、`conversation`、`item_reference` 或加密压缩状态,无法从本次请求取得完整历史。
+- 交付未确认、owner 冲突、共享存储错误、429 限流或 503 过载。
+- WebSocket、压缩端点、已开始返回下游数据或已尝试过上游发送的请求。
+
+本功能不针对任意供应商 409 进行删改重试。省略后的实际发送仍检查用户、Key、分组、模型、余额、额度、账号状态和并发;没有可用账号仍会失败。上游拒绝或交付不确定时不自动重新发送。既有 owner 缓存不清空、不改归属;新输出仍通过现有交付屏障登记。
+
+管理 API 字段:`openai_409_omit_encrypted_history_enabled`,沿用管理员系统设置 GET/PUT。旧客户端不发送该字段时保留已保存值。普通用户不能逐请求启用。只在符合条件的本地拒绝路径读取开关,读取失败按关闭处理;日志仅记录发生了省略与上下文损失,不记录密文、正文或摘要。
+
+关闭后,后续请求恢复严格行为。无需数据库迁移或清 Redis;回退旧二进制会忽略此设置。切换不会取消在途请求,已省略的信息无法由关闭开关恢复。
+
+回归用虚构历史、隔离 Redis 和 localhost 上游验证,不代表真实供应商兼容或生产验收。参考 #812 中的 BPS 历史省略机制,本功能在项目自己的原生 Responses 路径实现,没有加载第三方插件或复制未知二进制代码。
diff --git a/docs/screenshots/encrypted-history-409-beta/README.md b/docs/screenshots/encrypted-history-409-beta/README.md
new file mode 100644
index 000000000000..ab14f691e4cf
--- /dev/null
+++ b/docs/screenshots/encrypted-history-409-beta/README.md
@@ -0,0 +1,15 @@
+# 409 省略加密内容(Beta)截图
+
+来源提交:b392e98f6cbfab0142c4786ea86c0ae87fcd2c3b。
+CI:https://github.com/ranxi2001/sub2api/actions/runs/43271213325。
+命令:`node .github/scripts/encrypted-history-409-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/omit-history-ui"`。
+
+入口:系统设置 → 网关设置 → 网关转发行为。
+这里渲染实际 EncryptedHistory409Settings.vue,使用虚构管理员和组件状态;不是整页导航、真实后台保存或生产验收。
+
+- default-off.png:默认关闭,中文。
+- enabled.png:点击开关后的开启状态。
+- mobile-dark.png:430px 深色开启状态。
+- english.png:英文默认关闭。
+
+没有新增功能之前的组件,故提供新增入口的关闭/开启状态;所有截图均在 CSS 过渡结束后捕获。
diff --git a/docs/screenshots/encrypted-history-409-beta/default-off.png b/docs/screenshots/encrypted-history-409-beta/default-off.png
new file mode 100644
index 000000000000..fe57329bacf2
Binary files /dev/null and b/docs/screenshots/encrypted-history-409-beta/default-off.png differ
diff --git a/docs/screenshots/encrypted-history-409-beta/enabled.png b/docs/screenshots/encrypted-history-409-beta/enabled.png
new file mode 100644
index 000000000000..cfd17583c8fa
Binary files /dev/null and b/docs/screenshots/encrypted-history-409-beta/enabled.png differ
diff --git a/docs/screenshots/encrypted-history-409-beta/english.png b/docs/screenshots/encrypted-history-409-beta/english.png
new file mode 100644
index 000000000000..dc7d01335e43
Binary files /dev/null and b/docs/screenshots/encrypted-history-409-beta/english.png differ
diff --git a/docs/screenshots/encrypted-history-409-beta/manifest.json b/docs/screenshots/encrypted-history-409-beta/manifest.json
new file mode 100644
index 000000000000..8995b8d29839
--- /dev/null
+++ b/docs/screenshots/encrypted-history-409-beta/manifest.json
@@ -0,0 +1,5 @@
+{
+ "source": "b392e98f6cbfab0142c4786ea86c0ae87fcd2c3b",
+ "boundary": "Actual Vue setting component with fictional state; no full-page navigation, backend or production acceptance",
+ "errors": []
+}
\ No newline at end of file
diff --git a/docs/screenshots/encrypted-history-409-beta/mobile-dark.png b/docs/screenshots/encrypted-history-409-beta/mobile-dark.png
new file mode 100644
index 000000000000..32031157ff8c
Binary files /dev/null and b/docs/screenshots/encrypted-history-409-beta/mobile-dark.png differ
diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts
index edfc4a34ab0d..5ba74f50aed3 100644
--- a/frontend/src/api/admin/settings.ts
+++ b/frontend/src/api/admin/settings.ts
@@ -618,6 +618,7 @@ export interface SystemSettings {
grok_cross_client_model_map_enabled: boolean;
grok_default_base_url_mode: string;
grok_video_source_url_enabled: boolean;
+ openai_409_omit_encrypted_history_enabled: boolean;
// Per-platform account auto-pause thresholds (100 = disabled)
account_scheduling_thresholds: AccountSchedulingThresholdsMap;
@@ -1012,6 +1013,7 @@ export interface UpdateSettingsRequest {
grok_cross_client_model_map_enabled?: boolean;
grok_default_base_url_mode?: string;
grok_video_source_url_enabled?: boolean;
+ openai_409_omit_encrypted_history_enabled?: boolean;
account_scheduling_thresholds?: AccountSchedulingThresholdsMap;
enable_identity_patch?: boolean;
identity_patch_prompt?: string;
diff --git a/frontend/src/components/settings/EncryptedHistory409Settings.vue b/frontend/src/components/settings/EncryptedHistory409Settings.vue
new file mode 100644
index 000000000000..ffce736c5968
--- /dev/null
+++ b/frontend/src/components/settings/EncryptedHistory409Settings.vue
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+ {{ t('admin.settings.gatewayForwarding.omitEncryptedHistory409') }}
+
+ Beta
+
+
+
+ {{ t('admin.settings.gatewayForwarding.omitEncryptedHistory409Hint') }}
+
+
+
+
+
diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts
index b3d89b288a44..a315b66100a3 100644
--- a/frontend/src/constants/newFeatureNotices.ts
+++ b/frontend/src/constants/newFeatureNotices.ts
@@ -4,6 +4,7 @@
* browser; use a new ID to announce the feature again in a later release.
*/
export const NEW_FEATURE_NOTICES = {
+ openai409OmitEncryptedHistory: 'openai-409-omit-encrypted-history-beta',
userIdCopy: 'user-id-copy-initial-announcement',
accountAverageCache: 'account-average-cache-initial-announcement',
pelicanRandomQuestionBank: 'pelican-random-question-bank',
diff --git a/frontend/src/i18n/locales/en/admin/settings.ts b/frontend/src/i18n/locales/en/admin/settings.ts
index 2469cb3b54c6..da2866a936ee 100644
--- a/frontend/src/i18n/locales/en/admin/settings.ts
+++ b/frontend/src/i18n/locales/en/admin/settings.ts
@@ -574,6 +574,8 @@ export default {
saveFailed: 'Failed to save OpenCode Go usage refresh settings'
},
gatewayForwarding: {
+ omitEncryptedHistory409: 'Omit encrypted content on 409',
+ omitEncryptedHistory409Hint: 'Off by default. For HTTP Responses rejected before dispatch because the encrypted history owner is unavailable or its route changed, omit historical ciphertext and select an eligible account once. Readable text and tool relationships remain, but omitted context is lost and upstream acceptance is not guaranteed. Excludes current encrypted tasks, server-side conversation pointers, WebSockets, uncertain delivery and store failures. Already-sent requests are not replayed.',
title: 'Request Forwarding',
description: 'Control how requests are forwarded to upstream OAuth accounts',
grokDefaultTextModel: 'Default Grok text model',
diff --git a/frontend/src/i18n/locales/zh/admin/settings.ts b/frontend/src/i18n/locales/zh/admin/settings.ts
index 52287a015629..73275ad2e6d0 100644
--- a/frontend/src/i18n/locales/zh/admin/settings.ts
+++ b/frontend/src/i18n/locales/zh/admin/settings.ts
@@ -567,6 +567,8 @@ export default {
saveFailed: '保存 OpenCode Go 用量刷新设置失败'
},
gatewayForwarding: {
+ omitEncryptedHistory409: '409 省略加密内容',
+ omitEncryptedHistory409Hint: '默认关闭。HTTP Responses 在发送前因原加密历史账号不可用或路线变化返回 409 时,省略旧密文并重新选择合格账号,最多处理一次。保留可读文本和工具调用关系,但被省略的上下文将丢失,不能保证会话完整或上游接受。当前加密任务、服务端会话指针、WebSocket、交付未确认和存储故障不适用;不会重放已发送的请求。',
title: '请求转发行为',
description: '控制请求转发到上游 OAuth 账号时的行为',
grokDefaultTextModel: '默认 Grok 文本模型',
diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue
index 81e042cd7fa2..3f300ab64697 100644
--- a/frontend/src/views/admin/SettingsView.vue
+++ b/frontend/src/views/admin/SettingsView.vue
@@ -51,6 +51,12 @@
:user-id="authStore.user?.id"
class="settings-tab-badge"
/>
+
+
+