diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index d3f8b5d9a9..bd9b1b0419 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -680,7 +680,9 @@ func lockAndMergeAccountProbeExtra( false ), extra -> 'opencode_go_usage_auto_refresh', - extra -> 'opencode_go_usage_snapshot' + extra -> 'opencode_go_usage_snapshot', + extra -> 'grok_observed_models', + extra -> 'upstream_model_metadata' FROM accounts WHERE id = $1 AND deleted_at IS NULL FOR NO KEY UPDATE @@ -709,6 +711,8 @@ func lockAndMergeAccountProbeExtra( currentOllamaSnapshot []byte currentOpenCodeAutoRefresh []byte currentOpenCodeSnapshot []byte + currentGrokObservedModels []byte + currentUpstreamModelMetadata []byte ) if err := rows.Scan( &identityUnchanged, @@ -723,6 +727,8 @@ func lockAndMergeAccountProbeExtra( &opencodeGroupIdentityUnchanged, ¤tOpenCodeAutoRefresh, ¤tOpenCodeSnapshot, + ¤tGrokObservedModels, + ¤tUpstreamModelMetadata, ); err != nil { return nil, err } @@ -836,6 +842,21 @@ func lockAndMergeAccountProbeExtra( } } } + // Grok 目录和能力 metadata 是同步写入的受管状态。普通更新在行锁内采用最新 + // 数据库值,忽略表单旧值、缺键和注入。来源身份变化不删除已有成功快照。 + for key, raw := range map[string][]byte{ + "grok_observed_models": currentGrokObservedModels, + service.UpstreamModelMetadataExtraKey: currentUpstreamModelMetadata, + } { + delete(extra, key) + value, ok, err := decodeAccountExtraJSON(raw) + if err != nil { + return nil, err + } + if ok { + extra[key] = value + } + } return extra, nil } diff --git a/backend/internal/repository/account_repo_grok_managed_extra_integration_test.go b/backend/internal/repository/account_repo_grok_managed_extra_integration_test.go new file mode 100644 index 0000000000..84edfd5623 --- /dev/null +++ b/backend/internal/repository/account_repo_grok_managed_extra_integration_test.go @@ -0,0 +1,326 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestGrokManagedExtraSurvivesOrdinaryUpdate(t *testing.T) { + freshModels := map[string]any{ + "models": []any{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + } + freshMetadata := map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + } + failedModels := map[string]any{ + "models": []any{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + "last_attempt": map[string]any{ + "status": "failed", + "error_code": "transport", + "started_at": "2026-10-25T13:00:00Z", + "finished_at": "2026-10-25T13:00:01Z", + }, + } + oldModels := map[string]any{ + "models": []any{"old-model"}, + "fetched_at": "2026-10-24T12:00:00Z", + } + oldMetadata := map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + } + + tests := []struct { + name string + accountType string + credentials map[string]any + storedExtra map[string]any + updateExtra map[string]any + updateCreds map[string]any + wantModels map[string]any + wantMetadata map[string]any + wantBaseURL string + }{ + { + name: "oauth old form", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": freshModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": oldModels, + service.UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "apikey missing keys", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep", "base_url": "https://api.example.test/v1"}, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": freshModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "injection when absent", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{"unrelated": "keep"}, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": oldModels, + service.UpstreamModelMetadataExtraKey: oldMetadata, + }, + }, + { + name: "failed attempt", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": failedModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": oldModels, + service.UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: failedModels, + wantMetadata: freshMetadata, + }, + { + name: "source identity change keeps success", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{ + "access_token": "token-keep", + "base_url": "https://old.example.test/v1", + }, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": freshModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": nil, + }, + updateCreds: map[string]any{ + "access_token": "token-keep", + "base_url": "https://new.example.test/v1", + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + wantBaseURL: "https://new.example.test/v1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "grok-managed-" + tt.name, + Platform: service.PlatformGrok, + Type: tt.accountType, + Credentials: tt.credentials, + Extra: tt.storedExtra, + }) + account.Name = "renamed" + account.Extra = tt.updateExtra + if tt.updateCreds != nil { + account.Credentials = tt.updateCreds + } + + require.NoError(t, repo.Update(context.Background(), account)) + + got := readGrokManagedExtra(t, tx, account.ID) + require.Equal(t, "renamed", got.name) + require.Equal(t, "from-form", got.note) + require.Equal(t, "keep", got.unrelated) + require.Equal(t, tt.wantModels, got.models) + require.Equal(t, tt.wantMetadata, got.metadata) + if tt.wantBaseURL != "" { + require.Equal(t, tt.wantBaseURL, got.baseURL) + } + }) + } +} + +func TestGrokManagedExtraUpdateOverlapsCatalogCAS(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + account := mustCreateGrokCatalogAccount(t, testEntClient(t), "grok-managed-overlap") + t.Cleanup(func() { + cleanupCtx := context.Background() + _, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM scheduler_outbox WHERE account_id = $1", account.ID) + _, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM accounts WHERE id = $1", account.ID) + }) + + freshModels := `{"models":["fresh-model"],"fetched_at":"2026-10-25T12:00:00Z","last_attempt":{"status":"failed","error_code":"transport","started_at":"2026-10-25T13:00:00Z","finished_at":"2026-10-25T13:00:01Z"}}` + freshMetadata := `{"models":{"fresh-model":{"id":"fresh-model"}}}` + + tx, err := integrationEntClient.Tx(ctx) + require.NoError(t, err) + t.Cleanup(func() { _ = tx.Rollback() }) + + locked := make(chan struct{}) + release := make(chan struct{}) + holderDone := make(chan struct{}) + var holderErr error + go func() { + defer close(holderDone) + rows, queryErr := tx.QueryContext(ctx, `SELECT id FROM accounts WHERE id = $1 FOR NO KEY UPDATE`, account.ID) + if queryErr != nil { + holderErr = queryErr + return + } + if !rows.Next() { + holderErr = rows.Err() + if holderErr == nil { + holderErr = errors.New("catalog account row was not locked") + } + _ = rows.Close() + return + } + var id int64 + if scanErr := rows.Scan(&id); scanErr != nil { + holderErr = scanErr + _ = rows.Close() + return + } + if closeErr := rows.Close(); closeErr != nil { + holderErr = closeErr + return + } + close(locked) + select { + case <-release: + case <-ctx.Done(): + holderErr = ctx.Err() + return + } + _, execErr := tx.ExecContext(ctx, ` + UPDATE accounts + SET extra = jsonb_set( + jsonb_set(COALESCE(extra, '{}'::jsonb), '{grok_observed_models}', $2::jsonb, true), + '{upstream_model_metadata}', $3::jsonb, true) + WHERE id = $1`, account.ID, freshModels, freshMetadata) + if execErr != nil { + holderErr = execErr + return + } + holderErr = tx.Commit() + }() + + select { + case <-locked: + case <-holderDone: + t.Fatalf("catalog lock holder finished early: %v", holderErr) + case <-ctx.Done(): + t.Fatal("timed out waiting for the catalog row lock") + } + + updateDone := make(chan error, 1) + go func() { + repo := newAccountRepositoryWithSQL(integrationEntClient, integrationDB, nil) + account.Name = "saved-during-cas" + account.Extra = map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"old-model"}, "fetched_at": "2026-10-24T12:00:00Z", + }, + service.UpstreamModelMetadataExtraKey: map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + }, + } + updateDone <- repo.Update(ctx, account) + }() + close(release) + + select { + case err = <-updateDone: + require.NoError(t, err) + case <-ctx.Done(): + t.Fatal("timed out waiting for the overlapping account update") + } + <-holderDone + require.NoError(t, holderErr) + + got := readGrokManagedExtra(t, integrationDB, account.ID) + require.Equal(t, "saved-during-cas", got.name) + require.Equal(t, "from-form", got.note) + require.Equal(t, "keep", got.unrelated) + require.Equal(t, []any{"fresh-model"}, got.models["models"]) + require.Equal(t, "2026-10-25T12:00:00Z", got.models["fetched_at"]) + attempt, ok := got.models["last_attempt"].(map[string]any) + require.True(t, ok) + require.Equal(t, "failed", attempt["status"]) + require.Equal(t, "transport", attempt["error_code"]) + require.Equal(t, map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, got.metadata) +} + +type grokManagedExtraRow struct { + name string + note string + unrelated string + baseURL string + models map[string]any + metadata map[string]any +} + +func readGrokManagedExtra(t *testing.T, q grokCatalogSQL, id int64) grokManagedExtraRow { + t.Helper() + rows, err := q.QueryContext(context.Background(), ` + SELECT name, + COALESCE(extra->>'note', ''), + COALESCE(extra->>'unrelated', ''), + COALESCE(credentials->>'base_url', ''), + COALESCE((extra->'grok_observed_models')::text, 'null'), + COALESCE((extra->'upstream_model_metadata')::text, 'null') + FROM accounts + WHERE id = $1`, id) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + require.True(t, rows.Next()) + var row grokManagedExtraRow + var modelsRaw, metadataRaw string + require.NoError(t, rows.Scan(&row.name, &row.note, &row.unrelated, &row.baseURL, &modelsRaw, &metadataRaw)) + require.NoError(t, rows.Err()) + if modelsRaw != "null" { + require.NoError(t, json.Unmarshal([]byte(modelsRaw), &row.models)) + } + if metadataRaw != "null" { + require.NoError(t, json.Unmarshal([]byte(metadataRaw), &row.metadata)) + } + return row +} diff --git a/backend/internal/repository/account_repo_grok_managed_extra_test.go b/backend/internal/repository/account_repo_grok_managed_extra_test.go new file mode 100644 index 0000000000..ff224d210b --- /dev/null +++ b/backend/internal/repository/account_repo_grok_managed_extra_test.go @@ -0,0 +1,171 @@ +package repository + +import ( + "context" + "encoding/json" + "regexp" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestLockAndMergeAccountProbeExtraKeepsLatestGrokManagedKeys(t *testing.T) { + freshModels := []byte(`{"fetched_at":"2026-10-25T12:00:00Z","models":["fresh-model"]}`) + freshMetadata := []byte(`{"models":{"fresh-model":{"id":"fresh-model"}}}`) + failedModels := []byte(`{"fetched_at":"2026-10-25T12:00:00Z","last_attempt":{"error_code":"transport","finished_at":"2026-10-25T13:00:01Z","started_at":"2026-10-25T13:00:00Z","status":"failed"},"models":["fresh-model"]}`) + + tests := []struct { + name string + accountType string + credentials map[string]any + inputExtra map[string]any + databaseModels []byte + databaseMetadata []byte + wantModels map[string]any + wantMetadata map[string]any + }{ + { + name: "old client snapshot and metadata lose to the locked row", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"old-model"}, "fetched_at": "2026-10-24T12:00:00Z", + }, + service.UpstreamModelMetadataExtraKey: map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + }, + }, + databaseModels: freshModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + { + name: "apikey payload that omits the keys still restores them", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + inputExtra: map[string]any{"note": "from-form"}, + databaseModels: freshModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + { + name: "injection does not create keys missing from the locked row", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"injected"}, "fetched_at": "2026-10-25T12:00:00Z", + }, + service.UpstreamModelMetadataExtraKey: map[string]any{"models": map[string]any{}}, + }, + }, + { + name: "failed attempt is kept when the client sends an older success", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"old-model"}, "fetched_at": "2026-10-24T12:00:00Z", + }, + }, + databaseModels: failedModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + "last_attempt": map[string]any{ + "error_code": "transport", + "finished_at": "2026-10-25T13:00:01Z", + "started_at": "2026-10-25T13:00:00Z", + "status": "failed", + }, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + { + name: "credential identity change still keeps the locked success", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-new", "base_url": "https://new.example.test/v1"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": nil, + }, + databaseModels: freshModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close() }) + + credentials, err := json.Marshal(normalizeJSONMap(tt.credentials)) + require.NoError(t, err) + mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). + WithArgs(int64(41), service.PlatformGrok, tt.accountType, string(credentials), nil). + WillReturnRows(sqlmock.NewRows([]string{ + "identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", + "enabled", "rate_sync_enabled", "snapshot", + "ollama_session", "ollama_auto", "ollama_snapshot", + "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", + "grok_observed_models", "upstream_model_metadata", + }).AddRow(false, false, true, nil, nil, nil, nil, nil, nil, false, nil, nil, tt.databaseModels, tt.databaseMetadata)) + + account := &service.Account{ + ID: 41, + Platform: service.PlatformGrok, + Type: tt.accountType, + Credentials: tt.credentials, + Extra: tt.inputExtra, + } + got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil) + require.NoError(t, err) + require.Equal(t, "from-form", got["note"]) + if tt.wantModels == nil { + require.NotContains(t, got, "grok_observed_models") + } else { + require.Equal(t, tt.wantModels, got["grok_observed_models"]) + } + if tt.wantMetadata == nil { + require.NotContains(t, got, service.UpstreamModelMetadataExtraKey) + } else { + require.Equal(t, tt.wantMetadata, got[service.UpstreamModelMetadataExtraKey]) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/repository/account_repo_opencode_go_usage_test.go b/backend/internal/repository/account_repo_opencode_go_usage_test.go index 8a5add8ffd..43581ec231 100644 --- a/backend/internal/repository/account_repo_opencode_go_usage_test.go +++ b/backend/internal/repository/account_repo_opencode_go_usage_test.go @@ -76,6 +76,7 @@ func openCodeGoMergeMockColumns() []string { "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", + "grok_observed_models", "upstream_model_metadata", } } @@ -188,7 +189,7 @@ func TestLockAndMergeAccountProbeExtraPreservesOpenCodeGoManagedState(t *testing mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(tt.account.ID, tt.account.Platform, tt.account.Type, string(credentials), nil). WillReturnRows(sqlmock.NewRows(openCodeGoMergeMockColumns()). - AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot)) + AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot, nil, nil)) got, err := lockAndMergeAccountProbeExtra(context.Background(), client, tt.account, nil, nil) require.NoError(t, err) diff --git a/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go b/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go index d3778ac00f..15bccacf79 100644 --- a/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go +++ b/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go @@ -81,8 +81,8 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil, nil, nil)) account := &service.Account{ ID: 27, @@ -172,8 +172,8 @@ func TestLockAndMergeAccountProbeExtraNeverInfersProbeFromRateSync(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(31), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil, nil, nil)) account := &service.Account{ ID: 31, @@ -211,8 +211,8 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(29), service.PlatformAnthropic, service.AccountTypeAPIKey, `{"api_key":"key","base_url":"https://ollama.com"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil, nil, nil)) account := &service.Account{ ID: 29, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, @@ -371,8 +371,8 @@ func TestUpdateWithAccountBillingSettingsRollsBackWhenOutboxFails(t *testing.T) mock.ExpectBegin() mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil, nil, nil)) mock.ExpectExec(`(?s)UPDATE .*accounts.*SET.*WHERE .*id.*`). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`(?s)SELECT .* FROM "accounts" WHERE "id" = \$1`). diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index b5545ee18e..0521f7a90b 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -687,6 +687,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U delete(normalizedExtra, OllamaCloudUsageSnapshotExtraKey) delete(normalizedExtra, OpenCodeGoUsageAutoRefreshExtraKey) delete(normalizedExtra, OpenCodeGoUsageSnapshotExtraKey) + // 目录观察和能力 metadata 只由同步写入。表单里的旧值或注入值不能进入本次更新。 + delete(normalizedExtra, grokObservedModelsExtraKey) + delete(normalizedExtra, UpstreamModelMetadataExtraKey) // 保留配额用量和专用服务受管字段,防止普通账号编辑意外覆盖。 for _, key := range []string{ "quota_used", @@ -695,6 +698,8 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U "quota_weekly_used", "quota_weekly_start", grokBillingExtraKey, + grokObservedModelsExtraKey, + UpstreamModelMetadataExtraKey, UpstreamBillingProbeEnabledExtraKey, UpstreamBillingRateSyncEnabledExtraKey, UpstreamBillingProbeExtraKey, diff --git a/backend/internal/service/admin_account_grok_catalog_test.go b/backend/internal/service/admin_account_grok_catalog_test.go new file mode 100644 index 0000000000..209f04fcbf --- /dev/null +++ b/backend/internal/service/admin_account_grok_catalog_test.go @@ -0,0 +1,176 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestUpdateAccountKeepsGrokCatalogManagedByDatabase(t *testing.T) { + freshModels := map[string]any{ + "models": []string{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + } + freshMetadata := map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + } + failedSnapshot := map[string]any{ + "models": []string{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + "last_attempt": map[string]any{ + "started_at": "2026-10-25T13:00:00Z", + "finished_at": "2026-10-25T13:00:01Z", + "status": "failed", + "error_code": "transport", + }, + } + oldModels := map[string]any{ + "models": []string{"old-model"}, + "fetched_at": "2026-10-24T12:00:00Z", + } + oldMetadata := map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + } + + tests := []struct { + name string + accountType string + credentials map[string]any + storedExtra map[string]any + inputExtra map[string]any + inputCreds map[string]any + wantModels any + wantMetadata any + wantBaseURL string + }{ + { + name: "oauth stale form does not replace fresh snapshot or metadata", + accountType: AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: freshModels, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + "grok_client_tool_cache_enabled": true, + grokObservedModelsExtraKey: oldModels, + UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "apikey form opened without keys does not delete them", + accountType: AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep", "base_url": "https://api.example.test/v1"}, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: freshModels, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + "grok_client_tool_cache_enabled": true, + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "injected catalog is ignored when the account has none", + accountType: AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{"note": "keep"}, + inputExtra: map[string]any{ + "note": "from-form", + grokObservedModelsExtraKey: oldModels, + UpstreamModelMetadataExtraKey: oldMetadata, + }, + }, + { + name: "failed attempt is not rolled back to an older success", + accountType: AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: failedSnapshot, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + grokObservedModelsExtraKey: oldModels, + UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: failedSnapshot, + wantMetadata: freshMetadata, + }, + { + name: "changing the saved endpoint keeps the old success", + accountType: AccountTypeOAuth, + credentials: map[string]any{ + "access_token": "token-keep", + "base_url": "https://old.example.test/v1", + }, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: freshModels, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + grokObservedModelsExtraKey: nil, + }, + inputCreds: map[string]any{ + "base_url": "https://new.example.test/v1", + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + wantBaseURL: "https://new.example.test/v1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + const accountID = int64(25) + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{ + accountID: { + ID: accountID, + Name: "grok", + Platform: PlatformGrok, + Type: tt.accountType, + Status: StatusActive, + Credentials: tt.credentials, + Extra: tt.storedExtra, + }, + }} + + got, err := (&adminServiceImpl{accountRepo: repo}).UpdateAccount(context.Background(), accountID, &UpdateAccountInput{ + Extra: tt.inputExtra, + Credentials: tt.inputCreds, + }) + require.NoError(t, err) + if tt.wantModels == nil { + require.NotContains(t, got.Extra, grokObservedModelsExtraKey) + } else { + require.Equal(t, tt.wantModels, got.Extra[grokObservedModelsExtraKey]) + } + if tt.wantMetadata == nil { + require.NotContains(t, got.Extra, UpstreamModelMetadataExtraKey) + } else { + require.Equal(t, tt.wantMetadata, got.Extra[UpstreamModelMetadataExtraKey]) + } + if _, ok := tt.inputExtra["grok_client_tool_cache_enabled"]; ok { + require.Equal(t, true, got.Extra["grok_client_tool_cache_enabled"]) + } + if tt.wantBaseURL != "" { + require.Equal(t, tt.wantBaseURL, got.GetCredential("base_url")) + require.Equal(t, "token-keep", got.GetCredential("access_token")) + oldScope, scopeErr := NewGrokCatalogScope(accountID, tt.accountType, "https://old.example.test/v1/models") + require.NoError(t, scopeErr) + current, scopeErr := NewGrokCatalogScope(accountID, tt.accountType, "https://new.example.test/v1/models") + require.NoError(t, scopeErr) + snapshot := parseGrokObservedModels(got.Extra) + require.NotNil(t, snapshot) + snapshot.Scope = oldScope + diag := EvaluateGrokModelDiagnostics(got, current, snapshot, time.Date(2026, 10, 25, 18, 0, 0, 0, time.UTC)) + require.Equal(t, "source_changed", diag.State) + require.Equal(t, []string{"fresh-model"}, diag.Models) + } + }) + } +} diff --git a/backend/internal/service/grok_observed_models.go b/backend/internal/service/grok_observed_models.go index ba23d28ff7..23700bdd19 100644 --- a/backend/internal/service/grok_observed_models.go +++ b/backend/internal/service/grok_observed_models.go @@ -43,7 +43,12 @@ func (s *GrokQuotaService) scheduleGrokObservedModelsSync(account *Account) { ctx, cancel := context.WithTimeout(context.Background(), grokObservedModelsTimeout) defer cancel() if err := s.syncGrokObservedModels(ctx, &acc); err != nil { - slog.Debug("grok_observed_models_sync_failed", "account_id", id, "error", err) + kind, statusCode := grokObservedModelsSyncLogFields(err) + slog.Debug("grok_observed_models_sync_failed", + "account_id", id, + "error_kind", kind, + "status_code", statusCode, + ) } }() } @@ -243,6 +248,14 @@ func grokCatalogScopeFromRequest(account *Account, req *http.Request) *GrokCatal return scope } +func grokObservedModelsSyncLogFields(err error) (string, int) { + var syncErr *UpstreamModelSyncError + if errors.As(err, &syncErr) { + return string(syncErr.Kind), syncErr.StatusCode + } + return "transport", 0 +} + func grokCatalogErrorCode(err error) string { if errors.Is(err, errGrokCatalogEmpty) { return "empty_catalog" diff --git a/backend/internal/service/grok_observed_models_log_test.go b/backend/internal/service/grok_observed_models_log_test.go new file mode 100644 index 0000000000..f62eb98410 --- /dev/null +++ b/backend/internal/service/grok_observed_models_log_test.go @@ -0,0 +1,137 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "net/http" + "net/url" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/stretchr/testify/require" +) + +type grokCatalogLogProxyRepo struct { + ProxyRepository + proxy *Proxy +} + +func (r grokCatalogLogProxyRepo) GetByID(context.Context, int64) (*Proxy, error) { + return r.proxy, nil +} + +type grokCatalogLoggingUpstream struct { + proxyURL string + request *http.Request +} + +func (u *grokCatalogLoggingUpstream) Do(req *http.Request, proxyURL string, _ int64, _ int) (*http.Response, error) { + u.proxyURL = proxyURL + u.request = req + // net/http puts the request URL on *url.Error. Include query and userinfo + // here because a custom endpoint can carry both, while the proxy failure is + // attached separately and may contain proxy credentials. + return nil, &url.Error{ + Op: "Get", + URL: "https://relay-user:query-userinfo-secret@relay.example.test/v1/models?api_key=review-query-marker", + Err: fmt.Errorf("proxy %s: dial failed", proxyURL), + } +} + +func (u *grokCatalogLoggingUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, accountConcurrency) +} + +type grokCatalogLogHandler struct { + inner slog.Handler + done chan struct{} +} + +func (h *grokCatalogLogHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.inner.Enabled(ctx, level) +} + +func (h *grokCatalogLogHandler) Handle(ctx context.Context, record slog.Record) error { + err := h.inner.Handle(ctx, record) + if record.Message == "grok_observed_models_sync_failed" { + select { + case h.done <- struct{}{}: + default: + } + } + return err +} + +func (h *grokCatalogLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &grokCatalogLogHandler{inner: h.inner.WithAttrs(attrs), done: h.done} +} + +func (h *grokCatalogLogHandler) WithGroup(name string) slog.Handler { + return &grokCatalogLogHandler{inner: h.inner.WithGroup(name), done: h.done} +} + +func TestGrokBackgroundCatalogLogDoesNotExpandTransportURL(t *testing.T) { + var buf bytes.Buffer + handler := &grokCatalogLogHandler{ + inner: slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}), + done: make(chan struct{}, 1), + } + previous := slog.Default() + slog.SetDefault(slog.New(handler)) + t.Cleanup(func() { slog.SetDefault(previous) }) + + account := grokOAuthModelSyncTestAccount("https://relay-user:query-userinfo-secret@relay.example.test/v1?api_key=review-query-marker") + account.ID = 917283 + proxyID := int64(7) + account.ProxyID = &proxyID + proxy := &Proxy{ + ID: proxyID, + Protocol: "http", + Host: "proxy.example.test", + Port: 3128, + Username: "proxy-user", + Password: "proxy-pass-marker", + Status: StatusActive, + } + repo := newGrokCatalogMemoryRepo(account) + upstream := &grokCatalogLoggingUpstream{} + svc := &GrokQuotaService{ + accountRepo: repo, + proxyRepo: grokCatalogLogProxyRepo{proxy: proxy}, + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + } + + svc.scheduleGrokObservedModelsSync(account) + select { + case <-handler.done: + case <-time.After(5 * time.Second): + t.Fatal("background catalog log missing") + } + + logged := buf.String() + require.NotContains(t, logged, "review-query-marker") + require.NotContains(t, logged, "query-userinfo-secret") + require.NotContains(t, logged, "proxy-pass-marker") + require.NotContains(t, logged, "relay-user") + require.Contains(t, logged, "account_id=917283") + require.Contains(t, logged, "error_kind=upstream") + require.Contains(t, logged, "status_code=0") + require.NotContains(t, logged, "error=") + require.NotNil(t, upstream.request) + require.Contains(t, upstream.proxyURL, "proxy-pass-marker") + + stored, err := repo.GetByID(context.Background(), account.ID) + require.NoError(t, err) + snapshot := parseGrokObservedModels(stored.Extra) + require.NotNil(t, snapshot) + require.NotNil(t, snapshot.LastAttempt) + require.Equal(t, grokCatalogStatusFailed, snapshot.LastAttempt.Status) + require.Equal(t, "transport", snapshot.LastAttempt.ErrorCode) + require.Empty(t, snapshot.Models) +} diff --git a/frontend/src/components/account/GrokModelDiagnosticsPanel.vue b/frontend/src/components/account/GrokModelDiagnosticsPanel.vue index 5230ac4f93..3e54ab3689 100644 --- a/frontend/src/components/account/GrokModelDiagnosticsPanel.vue +++ b/frontend/src/components/account/GrokModelDiagnosticsPanel.vue @@ -119,7 +119,7 @@ const emit = defineEmits<{ const { t } = useI18n() const nowMs = ref(Date.now()) -const RFC3339_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/ +const RFC3339_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/ let timer: ReturnType | undefined onMounted(() => { @@ -132,11 +132,35 @@ onBeforeUnmount(() => { if (timer !== undefined) clearInterval(timer) }) +function daysInMonth(year: number, month: number): number { + if (month === 2) { + const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 + return leap ? 29 : 28 + } + return [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0 +} + function parseCatalogTime(value: string | undefined): number | null { if (!value) return null - const trimmed = value.trim() - if (!RFC3339_RE.test(trimmed)) return null - const parsed = Date.parse(trimmed) + const match = RFC3339_RE.exec(value.trim()) + if (!match) return null + const year = Number(match[1]) + const month = Number(match[2]) + const day = Number(match[3]) + const hour = Number(match[4]) + const minute = Number(match[5]) + const second = Number(match[6]) + const offsetHour = match[7] === undefined ? 0 : Number(match[7]) + const offsetMinute = match[8] === undefined ? 0 : Number(match[8]) + if ( + month < 1 || month > 12 || + day < 1 || day > daysInMonth(year, month) || + hour > 23 || minute > 59 || second > 59 || + offsetHour > 23 || offsetMinute > 59 + ) { + return null + } + const parsed = Date.parse(match[0]) return Number.isFinite(parsed) ? parsed : null } diff --git a/frontend/src/components/account/__tests__/GrokModelDiagnosticsPanel.spec.ts b/frontend/src/components/account/__tests__/GrokModelDiagnosticsPanel.spec.ts index 76d77f05ab..fa50902e02 100644 --- a/frontend/src/components/account/__tests__/GrokModelDiagnosticsPanel.spec.ts +++ b/frontend/src/components/account/__tests__/GrokModelDiagnosticsPanel.spec.ts @@ -226,6 +226,60 @@ describe('GrokModelDiagnosticsPanel', () => { expect(text).not.toContain('当前有效') }) + it.each([ + '2026-02-29T12:00:00Z', + '2026-02-30T12:00:00Z', + '2026-10-25T24:00:00Z', + '2026-10-25T12:60:00Z', + '2026-10-25T12:00:60Z', + '2026-10-25T12:00:00+24:00', + '2026-10-25T12:00:00+08:60' + ])('does not present an impossible catalog time %s as a successful observation', (invalid) => { + vi.useFakeTimers() + vi.setSystemTime(START) + const normalized = formatDateTime(invalid) + const wrapper = track(mountPanel({ + diagnostics: freshDiagnostics({ + state: 'fresh', + fetched_at: invalid, + expires_at: invalid, + mappings: [ + { requested: 'composer-2.5', upstream: 'grok-composer-2.5-fast', status: 'not_listed' } + ] + }) + })) + const text = wrapper.text() + expect(text).toContain('未知') + expect(text).not.toContain(invalid) + if (normalized) expect(text).not.toContain(normalized) + expect(text).not.toContain(NOT_LISTED_ZH) + expect(text).not.toContain('当前有效') + expect(text).not.toContain('历史目录') + expect(text).not.toContain('来源已变更') + }) + + it('keeps a real leap day, numeric offset, and fractional second as the last success', () => { + vi.useFakeTimers() + vi.setSystemTime(START) + const leapDay = '2024-02-29T23:30:00.5+08:00' + const expiresAt = '2026-10-25T20:00:00.123+08:00' + const wrapper = track(mountPanel({ + diagnostics: freshDiagnostics({ + state: 'fresh', + fetched_at: leapDay, + expires_at: expiresAt, + mappings: [ + { requested: 'composer-2.5', upstream: 'grok-composer-2.5-fast', status: 'not_listed' } + ] + }) + })) + const text = wrapper.text() + expect(text).toContain('当前有效') + expect(text).toContain(formatDateTime(leapDay)) + expect(text).toContain(NOT_LISTED_ZH) + expect(text).not.toContain('未知') + }) + it('does not present a future fetched_at echo as a successful observation', () => { vi.useFakeTimers() vi.setSystemTime(START)