From da53f30508305f8d4f830b2232ce261688b8d8cc Mon Sep 17 00:00:00 2001 From: Silkage Date: Fri, 23 Oct 2026 18:12:09 +0800 Subject: [PATCH 1/2] feat: wake idle account usage windows --- README.md | 24 +++++ docs/architecture.md | 23 ++++- docs/compatibility.md | 6 ++ docs/security.md | 4 + internal/accountusage/service.go | 24 +++-- internal/accountusage/service_test.go | 18 ++++ internal/app/app.go | 79 +++++++++++++++ internal/codexusage/runner.go | 141 ++++++++++++++++++++------ internal/codexusage/runner_test.go | 53 ++++++++++ 9 files changed, 331 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 8effd2d..ba1903a 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ codex-switch account add work --device-auth # Inspect and switch. Close Codex before switching, then restart it. codex-switch account list codex-switch account usage work +codex-switch account wake work codex-switch use work codex-switch current @@ -122,6 +123,23 @@ shows exact local reset times plus each returned earned-reset grant and expiry. The authoritative earned-reset count can be present even when the service omits or caps its detail rows. +To start an idle quota window without switching accounts, explicitly send one +minimal request: + +```bash +codex-switch account wake work +# Equivalent, more descriptive spelling: +codex-switch account start-window work +``` + +The command always targets exactly one saved alias and intentionally consumes a +small amount of that account's Codex allowance. It does not retry the model +request. Codex runs with a fixed short prompt, minimal reasoning, no persisted +session, an empty temporary workspace, a read-only sandbox, and no user config, +rules, plugins, or MCP servers. After the request completes, `codex-switch` +refreshes the usage snapshot so the returned reset time can be inspected. The +service, not `codex-switch`, remains authoritative about when a window starts. + ## Commands ```text @@ -138,6 +156,7 @@ codex-switch account add codex-switch account import-current codex-switch account list [--refresh|--cached] codex-switch account usage [alias] [--all] [--cached] +codex-switch account wake codex-switch account show codex-switch account rename codex-switch account reauth @@ -186,6 +205,11 @@ back to the encrypted vault. If the queried profile is active, the same generation is safely reconciled into `$CODEX_HOME/auth.json`; no account selection or Codex-owned state changes. +`account wake` has the same credential-isolation behavior, but additionally +creates one ephemeral Codex turn for the selected saved profile and records its +`lastUsedAt` timestamp. It never replaces the selected live account or writes a +session into the shared `CODEX_HOME`. + Initialization may make a one-time, backed-up change to `$CODEX_HOME/config.toml` to set `cli_auth_credentials_store = "file"`. `codex-switch` does not rewrite session history or Codex configuration during a diff --git a/docs/architecture.md b/docs/architecture.md index 9ae4dec..2feaa8c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -25,7 +25,8 @@ drift, safely synchronizes known profiles, prepares a journal, performs compare-before-replace, and records the selected profile. - `codexusage` runs the official Codex App Server in an isolated temporary - `CODEX_HOME` and reads the stable account, rate-limit, and token-usage methods. + `CODEX_HOME`, optionally sends one minimal ephemeral request, and reads the + stable account, rate-limit, and token-usage methods. - `accountusage` queries up to four profiles concurrently, reconciles credential refresh generations, and coordinates with switching through the same lock. - `usagecache` stores credential-free successful snapshots separately from the @@ -97,6 +98,26 @@ backoff using the newest validated credential generation returned by the prior attempt. Multi-account refreshes are intentionally sequential so independent App Server processes do not compete for startup or authentication resources. +## Isolated quota-window wake + +```text +acquire shared operation lock + -> decrypt and validate exactly one selected profile + -> create a temporary CODEX_HOME and an unrelated empty workspace + -> run one non-interactive, ephemeral Codex turn with a fixed short prompt + -> disable user config and rules; use minimal reasoning and a read-only sandbox + -> do not retry the turn + -> query the account usage through App Server in the same temporary home + -> reconcile any rotated credential generation and cache the new snapshot + -> delete both temporary directories +``` + +The wake path uses the same identity, generation, and active-file reconciliation +checks as a normal usage query. It does not project the target profile into the +shared `CODEX_HOME` and does not persist a Codex session. A successful turn is +real quota usage; the subsequent snapshot is the evidence available for whether +the service started or advanced a quota window. + ## Data locations `CODEX_HOME` resolution: diff --git a/docs/compatibility.md b/docs/compatibility.md index 4076347..1e771a6 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -69,6 +69,12 @@ Usage querying initializes `codex app-server` and calls: - `account/rateLimits/read` - `account/usage/read` +`account wake` additionally requires the installed CLI's non-interactive +`codex exec` mode and its `--ephemeral`, `--ignore-user-config`, +`--ignore-rules`, and read-only sandbox options. The wake turn uses the CLI's +default ChatGPT-plan Codex model so it affects the ordinary Codex allowance +rather than selecting a separately metered model family. + When returned by `account/rateLimits/read`, the client also preserves `rateLimitResetCredits.availableCount` and its optional grant/expiration detail rows. Older services that omit this optional object remain supported. diff --git a/docs/security.md b/docs/security.md index 56356a3..c7d93af 100644 --- a/docs/security.md +++ b/docs/security.md @@ -40,6 +40,10 @@ focuses on: - JSON output is intentionally based on dedicated public view types. - Usage queries create per-profile temporary homes with mode `0700` and credential files with mode `0600`, then remove them after the App Server exits. +- Quota-window wake requests use the same temporary credential home plus a + separate empty workspace. They run one fixed prompt with an ephemeral session, + minimal reasoning, ignored user config and rules, a read-only sandbox, and no + automatic retry. Child stdout and diagnostics are never exposed or cached. - The usage cache contains rate limits, earned-reset counts and metadata, aggregate token statistics, timestamps, and public account metadata only. It never contains authentication documents. diff --git a/internal/accountusage/service.go b/internal/accountusage/service.go index 7398473..49b9af6 100644 --- a/internal/accountusage/service.go +++ b/internal/accountusage/service.go @@ -32,12 +32,14 @@ type QueryRunner interface { } type Service struct { - Home codexhome.Home - Paths appconfig.Paths - Vault *vault.Manager - Runner QueryRunner + Home codexhome.Home + Paths appconfig.Paths + Vault *vault.Manager + Runner QueryRunner + QueryTimeout time.Duration + QueryAttempts int + RecordUse bool - queryAttempts int retryBaseDelay time.Duration } @@ -153,6 +155,10 @@ func (service Service) Refresh(ctx context.Context, profileIDs []string) (map[st } if results[profileID].Error == "" { cache.Profiles[profileID] = results[profileID].Snapshot + if service.RecordUse { + profile.LastUsedAt = time.Now().UTC() + vaultChanged = true + } } saved, parseErr := authschema.Parse(profile.Auth) if parseErr != nil { @@ -227,10 +233,14 @@ func (service Service) Refresh(ctx context.Context, profileIDs []string) (map[st } func (service Service) queryWithRetry(ctx context.Context, auth json.RawMessage) (codexusage.Snapshot, json.RawMessage, int, error) { - attemptLimit := service.queryAttempts + attemptLimit := service.QueryAttempts if attemptLimit <= 0 { attemptLimit = defaultQueryAttempts } + timeout := service.QueryTimeout + if timeout <= 0 { + timeout = queryTimeout + } baseDelay := service.retryBaseDelay if baseDelay <= 0 { baseDelay = defaultRetryBaseDelay @@ -242,7 +252,7 @@ func (service Service) queryWithRetry(ctx context.Context, auth json.RawMessage) if err := ctx.Err(); err != nil { return codexusage.Snapshot{}, nil, attempt - 1, err } - queryContext, cancel := context.WithTimeout(ctx, queryTimeout) + queryContext, cancel := context.WithTimeout(ctx, timeout) snapshot, updatedAuth, err := service.Runner.Query(queryContext, currentAuth) cancel() if len(updatedAuth) > 0 { diff --git a/internal/accountusage/service_test.go b/internal/accountusage/service_test.go index d1a331b..2f31d92 100644 --- a/internal/accountusage/service_test.go +++ b/internal/accountusage/service_test.go @@ -48,6 +48,7 @@ func (runner fakeRunner) Query(context.Context, json.RawMessage) (codexusage.Sna func TestRefreshCachesUsageAndAdoptsRotatedCredentials(t *testing.T) { service, manager, profile := testService(t, false) + service.RecordUse = true updated := authBytes("account-a", "refresh-new", "2026-08-20T01:00:00Z") lifetime := int64(1234) service.Runner = fakeRunner{ @@ -70,12 +71,29 @@ func TestRefreshCachesUsageAndAdoptsRotatedCredentials(t *testing.T) { if document.Tokens.RefreshToken != "refresh-new" { t.Fatal("rotated credential was not saved") } + if saved.LastUsedAt.IsZero() || !saved.LastUsedAt.After(profile.LastUsedAt) { + t.Fatalf("successful wake did not record account use: %#v", saved.LastUsedAt) + } cache, err := service.Cached() if err != nil || cache.Profiles[profile.ID].PlanType != "pro" { t.Fatalf("usage was not cached: %#v, %v", cache, err) } } +func TestRefreshCanDisableRetriesForOneShotRequests(t *testing.T) { + service, _, profile := testService(t, false) + runner := &retryRunner{failures: 3, auth: authBytes("account-a", "refresh-new", "2026-08-20T01:00:00Z")} + service.Runner = runner + service.QueryAttempts = 1 + results, err := service.Refresh(context.Background(), []string{profile.ID}) + if err != nil { + t.Fatal(err) + } + if runner.calls != 1 || results[profile.ID].Attempts != 1 { + t.Fatalf("one-shot refresh retried: calls=%d result=%#v", runner.calls, results[profile.ID]) + } +} + func TestRefreshRetriesAndClearsPersistedFailure(t *testing.T) { service, _, profile := testService(t, false) runner := &retryRunner{ diff --git a/internal/app/app.go b/internal/app/app.go index a323e1c..855ed93 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -77,6 +77,11 @@ type usageView struct { Attempts int `json:"attempts,omitempty"` } +type wakeView struct { + Account accountView `json:"account"` + RequestSent bool `json:"requestSent"` +} + const usageFreshness = 5 * time.Minute func NewCommand(version string) *cobra.Command { @@ -155,6 +160,7 @@ func newAccountCommand(options *Options) *cobra.Command { newAccountAddCommand(options, false), newAccountListCommand(options), newAccountUsageCommand(options), + newAccountWakeCommand(options), newAccountShowCommand(options), newAccountRenameCommand(options), newAccountRemoveCommand(options), @@ -450,6 +456,62 @@ func newAccountUsageCommand(options *Options) *cobra.Command { return command } +func newAccountWakeCommand(options *Options) *cobra.Command { + return &cobra.Command{ + Use: "wake ", + Aliases: []string{"start-window"}, + Short: "Send one minimal Codex request to start an idle usage window", + Args: cobra.ExactArgs(1), + RunE: func(_ *cobra.Command, args []string) error { + runtime, err := options.loadRuntime(false) + if err != nil { + return err + } + data, err := runtime.manager.Load() + if err != nil { + return err + } + profile, err := data.Find(args[0]) + if err != nil { + return err + } + results, err := runtime.wakeService(options.Version).Refresh(context.Background(), []string{profile.ID}) + if err != nil { + return err + } + result := results[profile.ID] + if result.Error != "" { + return fmt.Errorf("wake request for %q failed: %s", profile.Alias, result.Error) + } + data, err = runtime.manager.Load() + if err != nil { + return err + } + profile, err = data.Find(profile.ID) + if err != nil { + return err + } + observation, err := runtime.switcher().Observe() + if err != nil { + return err + } + cache, err := runtime.usageService(options.Version).Cached() + if err != nil { + return err + } + view := toView(*profile, observation.Managed && observation.ProfileID == profile.ID) + view.Usage = usageFromCache(cache, profile.ID, "", time.Now()) + wake := wakeView{Account: view, RequestSent: true} + if options.JSON { + return options.render(wake, "") + } + _, _ = fmt.Fprintf(options.Output, "Sent one minimal Codex request for %q without changing the active account.\n", profile.Alias) + _, _ = fmt.Fprintln(options.Output, formatUsage(view, time.Now())) + return nil + }, + } +} + func newAccountShowCommand(options *Options) *cobra.Command { return &cobra.Command{ Use: "show ", @@ -984,6 +1046,23 @@ func (runtime runtimeState) usageService(version string) accountusage.Service { } } +func (runtime runtimeState) wakeService(version string) accountusage.Service { + return accountusage.Service{ + Home: runtime.home, + Paths: runtime.paths, + Vault: runtime.manager, + QueryTimeout: 90 * time.Second, + QueryAttempts: 1, + RecordUse: true, + Runner: codexusage.Runner{ + Binary: runtime.bin, + BinaryError: runtime.binErr, + ClientVersion: version, + Wake: true, + }, + } +} + func (options *Options) currentView() (accountView, error) { runtime, err := options.loadRuntime(false) if err != nil { diff --git a/internal/codexusage/runner.go b/internal/codexusage/runner.go index 7616de8..7ed34a0 100644 --- a/internal/codexusage/runner.go +++ b/internal/codexusage/runner.go @@ -25,6 +25,7 @@ type Runner struct { Binary string BinaryError error ClientVersion string + Wake bool command func(context.Context, string, ...string) *exec.Cmd } @@ -70,7 +71,30 @@ func (runner Runner) Query(ctx context.Context, auth json.RawMessage) (Snapshot, if err := atomicfile.Write(filepath.Join(temporaryHome, "auth.json"), append(append([]byte(nil), document.Raw...), '\n'), 0o600); err != nil { return Snapshot{}, nil, err } + if runner.Wake { + if err := runner.runWake(ctx, temporaryHome); err != nil { + updated, updateErr := readUpdatedAuth(temporaryHome, document) + if updateErr != nil { + return Snapshot{}, nil, errors.Join(err, updateErr) + } + return Snapshot{}, updated, err + } + } + snapshot, queryErr := runner.queryHome(ctx, temporaryHome) + updated, updateErr := readUpdatedAuth(temporaryHome, document) + if updateErr != nil { + return Snapshot{}, nil, updateErr + } + if queryErr != nil { + if runner.Wake { + queryErr = fmt.Errorf("minimal Codex request completed but usage verification failed: %w", queryErr) + } + return Snapshot{}, updated, queryErr + } + return snapshot, updated, nil +} +func (runner Runner) queryHome(ctx context.Context, temporaryHome string) (Snapshot, error) { commandFactory := runner.command if commandFactory == nil { commandFactory = exec.CommandContext @@ -83,16 +107,16 @@ func (runner Runner) Query(ctx context.Context, auth json.RawMessage) (Snapshot, command.Env = withEnvironment(environment, "CODEX_HOME", temporaryHome) stdin, err := command.StdinPipe() if err != nil { - return Snapshot{}, nil, err + return Snapshot{}, err } stdout, err := command.StdoutPipe() if err != nil { - return Snapshot{}, nil, err + return Snapshot{}, err } var stderr limitedBuffer command.Stderr = &stderr if err := command.Start(); err != nil { - return Snapshot{}, nil, fmt.Errorf("start Codex app server: %w", err) + return Snapshot{}, fmt.Errorf("start Codex app server: %w", err) } waited := false defer func() { @@ -113,70 +137,59 @@ func (runner Runner) Query(ctx context.Context, auth json.RawMessage) (Snapshot, if err := sendRequest(encoder, 0, "initialize", map[string]any{ "clientInfo": map[string]string{"name": "codex_switch", "title": "codex-switch", "version": version}, }); err != nil { - return Snapshot{}, nil, err + return Snapshot{}, err } initialize, err := readResponse(scanner, 0) if err != nil { - return Snapshot{}, nil, protocolError("initialize", err, stderr.String()) + return Snapshot{}, protocolError("initialize", err, stderr.String()) } if initialize.Error != nil { - return Snapshot{}, nil, responseError("initialize", initialize.Error) + return Snapshot{}, responseError("initialize", initialize.Error) } if err := encoder.Encode(rpcRequest{Method: "initialized", Params: map[string]any{}}); err != nil { - return Snapshot{}, nil, fmt.Errorf("send initialized notification: %w", err) + return Snapshot{}, fmt.Errorf("send initialized notification: %w", err) } if err := sendRequest(encoder, 1, "account/read", map[string]bool{"refreshToken": false}); err != nil { - return Snapshot{}, nil, err + return Snapshot{}, err } accountResponse, err := readResponse(scanner, 1) if err != nil { - return Snapshot{}, nil, protocolError("read account", err, stderr.String()) + return Snapshot{}, protocolError("read account", err, stderr.String()) } if accountResponse.Error != nil { - return Snapshot{}, nil, responseError("account/read", accountResponse.Error) + return Snapshot{}, responseError("account/read", accountResponse.Error) } var account AccountResponse if err := json.Unmarshal(accountResponse.Result, &account); err != nil { - return Snapshot{}, nil, fmt.Errorf("decode account/read response: %w", err) + return Snapshot{}, fmt.Errorf("decode account/read response: %w", err) } if account.Account == nil || account.Account.Type != "chatgpt" { - return Snapshot{}, nil, errors.New("saved profile is not recognized as a ChatGPT account by Codex") + return Snapshot{}, errors.New("saved profile is not recognized as a ChatGPT account by Codex") } if err := sendRequest(encoder, 2, "account/rateLimits/read", nil); err != nil { - return Snapshot{}, nil, err + return Snapshot{}, err } rateLimitsResponse, err := readResponse(scanner, 2) if err != nil { - return Snapshot{}, nil, protocolError("read account rate limits", err, stderr.String()) + return Snapshot{}, protocolError("read account rate limits", err, stderr.String()) } if err := sendRequest(encoder, 3, "account/usage/read", nil); err != nil { - return Snapshot{}, nil, err + return Snapshot{}, err } tokenUsageResponse, err := readResponse(scanner, 3) if err != nil { - return Snapshot{}, nil, protocolError("read account token usage", err, stderr.String()) + return Snapshot{}, protocolError("read account token usage", err, stderr.String()) } _ = stdin.Close() if err := command.Wait(); err != nil { waited = true if ctx.Err() != nil { - return Snapshot{}, nil, fmt.Errorf("query account usage: %w", ctx.Err()) + return Snapshot{}, fmt.Errorf("query account usage: %w", ctx.Err()) } - return Snapshot{}, nil, protocolError("Codex app server exited", err, stderr.String()) + return Snapshot{}, protocolError("Codex app server exited", err, stderr.String()) } waited = true - updated, err := atomicfile.ReadLimited(filepath.Join(temporaryHome, "auth.json"), 2<<20) - if err != nil { - return Snapshot{}, nil, fmt.Errorf("read refreshed account credentials: %w", err) - } - updatedDocument, err := authschema.Parse(updated) - if err != nil { - return Snapshot{}, nil, fmt.Errorf("validate refreshed account credentials: %w", err) - } - if updatedDocument.Tokens.AccountID != document.Tokens.AccountID { - return Snapshot{}, nil, errors.New("codex returned credentials for a different account") - } snapshot := Snapshot{FetchedAt: time.Now().UTC(), PlanType: account.Account.PlanType} if rateLimitsResponse.Error != nil { @@ -184,7 +197,7 @@ func (runner Runner) Query(ctx context.Context, auth json.RawMessage) (Snapshot, } else { var value RateLimits if err := json.Unmarshal(rateLimitsResponse.Result, &value); err != nil { - return Snapshot{}, nil, fmt.Errorf("decode account/rateLimits/read response: %w", err) + return Snapshot{}, fmt.Errorf("decode account/rateLimits/read response: %w", err) } snapshot.RateLimits = &value } @@ -193,17 +206,79 @@ func (runner Runner) Query(ctx context.Context, auth json.RawMessage) (Snapshot, } else { var value TokenUsage if err := json.Unmarshal(tokenUsageResponse.Result, &value); err != nil { - return Snapshot{}, nil, fmt.Errorf("decode account/usage/read response: %w", err) + return Snapshot{}, fmt.Errorf("decode account/usage/read response: %w", err) } snapshot.TokenUsage = &value } if snapshot.RateLimits == nil && snapshot.TokenUsage == nil { - return Snapshot{}, updatedDocument.Raw, fmt.Errorf("account usage requests failed: %w", errors.Join( + return Snapshot{}, fmt.Errorf("account usage requests failed: %w", errors.Join( responseError("account/rateLimits/read", rateLimitsResponse.Error), responseError("account/usage/read", tokenUsageResponse.Error), )) } - return snapshot, updatedDocument.Raw, nil + return snapshot, nil +} + +func (runner Runner) runWake(ctx context.Context, temporaryHome string) error { + workspace, err := os.MkdirTemp("", "codex-switch-wake-*") + if err != nil { + return fmt.Errorf("create temporary wake workspace: %w", err) + } + defer func() { _ = os.RemoveAll(workspace) }() + if err := os.Chmod(workspace, 0o700); err != nil { + return fmt.Errorf("protect temporary wake workspace: %w", err) + } + commandFactory := runner.command + if commandFactory == nil { + commandFactory = exec.CommandContext + } + command := commandFactory(ctx, runner.Binary, + "exec", + "--ephemeral", + "--ignore-user-config", + "--ignore-rules", + "--skip-git-repo-check", + "--sandbox", "read-only", + "--color", "never", + "-c", `approval_policy="never"`, + "-c", `model_reasoning_effort="minimal"`, + "--cd", workspace, + "Reply with exactly OK. Do not use tools.", + ) + environment := command.Env + if environment == nil { + environment = os.Environ() + } + command.Env = withEnvironment(environment, "CODEX_HOME", temporaryHome) + var stdout limitedBuffer + var stderr limitedBuffer + command.Stdout = &stdout + command.Stderr = &stderr + if err := command.Run(); err != nil { + if ctx.Err() != nil { + return fmt.Errorf("send minimal Codex request: %w", ctx.Err()) + } + if strings.TrimSpace(stderr.String()) != "" { + return fmt.Errorf("minimal Codex request failed: %w (Codex diagnostics redacted)", err) + } + return fmt.Errorf("minimal Codex request failed: %w", err) + } + return nil +} + +func readUpdatedAuth(temporaryHome string, original authschema.Document) (json.RawMessage, error) { + updated, err := atomicfile.ReadLimited(filepath.Join(temporaryHome, "auth.json"), 2<<20) + if err != nil { + return nil, fmt.Errorf("read refreshed account credentials: %w", err) + } + updatedDocument, err := authschema.Parse(updated) + if err != nil { + return nil, fmt.Errorf("validate refreshed account credentials: %w", err) + } + if updatedDocument.Tokens.AccountID != original.Tokens.AccountID { + return nil, errors.New("codex returned credentials for a different account") + } + return updatedDocument.Raw, nil } func sendRequest(encoder *json.Encoder, id int, method string, params any) error { diff --git a/internal/codexusage/runner_test.go b/internal/codexusage/runner_test.go index 7b3bd95..3ad7196 100644 --- a/internal/codexusage/runner_test.go +++ b/internal/codexusage/runner_test.go @@ -89,6 +89,59 @@ func TestRunnerReturnsBinaryDiscoveryError(t *testing.T) { } } +func TestRunnerWakeSendsOneMinimalIsolatedRequestBeforeQuery(t *testing.T) { + var invocations [][]string + runner := helperRunner(t, false) + runner.Wake = true + runner.command = func(ctx context.Context, binary string, args ...string) *exec.Cmd { + invocations = append(invocations, append([]string(nil), args...)) + command := exec.CommandContext(ctx, binary, "-test.run=TestCodexUsageHelperProcess", "--") + command.Env = append(os.Environ(), "CODEX_USAGE_HELPER=1") + return command + } + snapshot, updated, err := runner.Query(context.Background(), testAuth("account-a", "refresh-old", "2026-08-20T00:00:00Z")) + if err != nil { + t.Fatal(err) + } + if snapshot.PlanType != "pro" || !strings.Contains(string(updated), "refresh-new") { + t.Fatalf("unexpected wake result: snapshot=%#v auth=%s", snapshot, updated) + } + if len(invocations) != 2 { + t.Fatalf("got %d Codex invocations, want wake plus usage query", len(invocations)) + } + wake := strings.Join(invocations[0], " ") + for _, expected := range []string{ + "exec", + "--ephemeral", + "--ignore-user-config", + "--ignore-rules", + "--skip-git-repo-check", + "--sandbox read-only", + `approval_policy="never"`, + `model_reasoning_effort="minimal"`, + "Reply with exactly OK. Do not use tools.", + } { + if !strings.Contains(wake, expected) { + t.Fatalf("wake invocation %q does not contain %q", wake, expected) + } + } + if len(invocations[1]) != 1 || invocations[1][0] != "app-server" { + t.Fatalf("second invocation = %#v, want app-server", invocations[1]) + } +} + +func TestRunnerWakeReportsCompletedRequestWhenUsageVerificationFails(t *testing.T) { + runner := helperRunnerMode(t, false, true) + runner.Wake = true + _, updated, err := runner.Query(context.Background(), testAuth("account-a", "refresh-old", "2026-08-20T00:00:00Z")) + if err == nil || !strings.Contains(err.Error(), "minimal Codex request completed but usage verification failed") { + t.Fatalf("unexpected wake verification error: %v", err) + } + if !strings.Contains(string(updated), "refresh-new") { + t.Fatalf("rotated credentials were lost after wake verification failure: %s", updated) + } +} + func helperRunner(t *testing.T, partial bool) Runner { return helperRunnerMode(t, partial, false) } From dc3894b2a622026d21f092c51aeb3a7e5b3c5446 Mon Sep 17 00:00:00 2001 From: Silkage Date: Fri, 23 Oct 2026 18:16:23 +0800 Subject: [PATCH 2/2] build: update Go to 1.26.10 --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index bde5693..02d65b7 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/SilkageNet/codex-switch -go 1.26.7 +go 1.26.10 require ( github.com/minio/selfupdate v0.6.0