From d9a367d32bdb4b08aefd718181cca4637ca6eaac Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Tue, 17 Nov 2026 02:06:09 -0500 Subject: [PATCH] accounts: show accounts per service, with rotation and a sign-out that never refuses People saw providers, profiles and accounts side by side and could not tell whether they were removing a provider or an account. The web settings page and the TUI now list accounts grouped by service (Claude, ChatGPT, Gemini, other sign-ins, API keys); profiles move under Advanced. API: Account gains email, plan and needs_sign_in. Provider profiles gain rotation (failover, spread, first). DELETE /auth/accounts/{id} no longer refuses a saved account: pins go back to automatic and the id leaves every account_ids list. Daemon: - Sign-ins are labelled with their email. An account is a user in a workspace (Codex user@chatgpt_account_id, Claude account:organization), never an email, so personal and business accounts on one email stay separate. - A model sign-in joins its service: it creates the first profile, appends to rotating profiles and turns automatic ones into lists. - Every mode keeps a session on its account until it is limited or needs sign-in. spread starts each new session on the account handed out longest ago. Session affinity lives in a daemon-wide table, pruned on session delete and agent close. - Claude limits are recorded from quota polls and 429 headers, and a 429 moves the request to the next ready account. - A refused renewal marks the account needs_sign_in instead of deleting it. Web: AccountsSettings replaces ProvidersSettings, with inline sign-in, per-service rotation, sign-out confirmations and a first-run state. TUI: /accounts (alias /login) with one section per service, inline sign-in, tab/alt+arrows for rotation and order, and ctrl+x sign-out. The old list is under advanced. --- cli/internal/config/config.go | 33 +- cli/internal/daemon/auth.go | 16 +- cli/internal/daemon/models.go | 2 +- cli/internal/daemon/protocol/api.gen.go | 23 +- cli/internal/daemon/protocol/digest.gen.go | 2 +- cli/internal/daemon/rotation.go | 117 ++ cli/internal/daemon/rotation_test.go | 64 + cli/internal/daemon/settings.go | 5 +- cli/internal/daemon/settings_bedrock_test.go | 4 +- cli/internal/tui/accounts.go | 978 +++++++++++++ cli/internal/tui/app_commands.go | 2 +- cli/internal/tui/chat_input.go | 6 +- cli/internal/tui/commands.go | 3 +- cli/internal/tui/list_view.go | 14 +- cli/internal/tui/login.go | 156 +- cli/internal/tui/login_accounts.go | 113 +- cli/internal/tui/login_pick.go | 2 +- cli/internal/tui/login_profile.go | 5 + cli/internal/tui/login_provider.go | 8 +- cli/internal/tui/login_test.go | 217 ++- cli/internal/tui/login_view.go | 59 +- cli/internal/tui/session_viewer.go | 2 +- cli/internal/tui/session_viewer_view.go | 4 +- cli/internal/tui/shot_accounts_test.go | 170 +++ cli/internal/tui/shot_login_test.go | 28 +- cli/internal/tui/terms.go | 2 +- cli/test/e2e/tui_login_test.go | 79 +- docs/openapi.yaml | 79 +- packages/albedo_model/src/albedo_model.gleam | 5 + .../src/albedo_model_stream/http.gleam | 8 +- .../albedo_sdk/src/albedo_sdk/accounts.gleam | 213 ++- .../src/albedo_sdk/auth_accounts.gleam | 293 +++- .../src/albedo_sdk/credential_store.gleam | 131 +- .../src/albedo_sdk/credentials.gleam | 83 +- .../src/albedo_sdk/google_oauth.gleam | 89 +- .../src/albedo_sdk/key_accounts.gleam | 66 +- .../albedo_sdk/src/albedo_sdk/oauth.gleam | 60 +- .../src/albedo_sdk/oauth_flows.gleam | 126 +- robot-docs/auth.md | 123 +- robot-docs/quota.md | 5 +- robot-docs/settings.md | 14 +- robot-docs/tui.md | 30 + robot-docs/web.md | 32 +- src/albedo/daemon/api_digest.gleam | 2 +- src/albedo/daemon/events.gleam | 1 + src/albedo/daemon/http_auth.gleam | 32 + src/albedo/daemon/registry.gleam | 3 + src/albedo/daemon/session.gleam | 2 + src/albedo/daemon/session_deletion.gleam | 2 + src/albedo/daemon/settings.gleam | 22 +- src/albedo/daemon/stream_trace.gleam | 7 +- .../extensions/antigravity/extension.gleam | 29 +- .../harness/extensions/claude/accounts.gleam | 359 ++++- .../harness/extensions/claude/extension.gleam | 108 +- .../harness/extensions/codex/accounts.gleam | 362 ++--- .../harness/extensions/codex/extension.gleam | 34 +- .../harness/extensions/colab/extension.gleam | 7 +- .../extensions/github_copilot/extension.gleam | 6 +- src/albedo/harness/extensions/mcp/oauth.gleam | 2 +- .../extensions/mistral/extension.gleam | 4 +- .../extensions/opencode_go/extension.gleam | 13 +- .../harness/extensions/proxy/chat.gleam | 1 + src/albedo/harness/settings/projection.gleam | 12 + test/e2e/account_rotation_test.py | 78 +- test/e2e/fast_mode_test.py | 49 +- test/e2e/opencode_go_login_test.py | 16 + .../albedo_mistral_sign_in_test_support.erl | 5 +- test/harness/codex_test.gleam | 147 +- test/harness/google_oauth_test.gleam | 16 +- test/harness/oauth_test.gleam | 147 +- test/harness/rotation_test.gleam | 355 ++++- web/scripts/accounts.test.mjs | 182 +++ web/src/App.svelte | 2 +- web/src/lib/Settings.svelte | 14 +- web/src/lib/api.gen.d.ts | 23 +- web/src/lib/settings/AccountsSettings.svelte | 1285 +++++++++++++++++ web/src/lib/settings/ConnectProvider.svelte | 11 +- web/src/lib/settings/ProviderCard.svelte | 8 +- web/src/lib/settings/ProvidersSettings.svelte | 418 ------ web/src/lib/settings/SignInRow.svelte | 273 ++++ web/src/lib/settings/accounts.ts | 223 +++ web/src/lib/settings/providers.ts | 16 + 82 files changed, 6490 insertions(+), 1257 deletions(-) create mode 100644 cli/internal/daemon/rotation.go create mode 100644 cli/internal/daemon/rotation_test.go create mode 100644 cli/internal/tui/accounts.go create mode 100644 cli/internal/tui/shot_accounts_test.go create mode 100644 web/scripts/accounts.test.mjs create mode 100644 web/src/lib/settings/AccountsSettings.svelte delete mode 100644 web/src/lib/settings/ProvidersSettings.svelte create mode 100644 web/src/lib/settings/SignInRow.svelte create mode 100644 web/src/lib/settings/accounts.ts diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go index 235c252c1..e65b6bfe0 100644 --- a/cli/internal/config/config.go +++ b/cli/internal/config/config.go @@ -34,20 +34,23 @@ func HomeDir() string { // daemon's credential store. APIKey carries a newly entered draft value; // HasKey is presence metadata returned by the daemon. type Settings struct { - ProfileName string `json:"-"` - Effort *string `json:"effort,omitempty"` - ImageEdge *int `json:"image_edge,omitempty"` - AccountID *string `json:"account_id,omitempty"` - AccountIDs []string `json:"account_ids,omitempty"` - Project *string `json:"project,omitempty"` - Location *string `json:"location,omitempty"` - Extension string `json:"extension,omitempty"` - API string `json:"api,omitempty"` - BaseURL string `json:"baseUrl,omitempty"` - APIKey string `json:"apiKey,omitempty"` - Model string `json:"model"` - Protocol string `json:"protocol"` - HasKey bool `json:"hasKey,omitempty"` + ProfileName string `json:"-"` + Effort *string `json:"effort,omitempty"` + ImageEdge *int `json:"image_edge,omitempty"` + AccountID *string `json:"account_id,omitempty"` + Project *string `json:"project,omitempty"` + Location *string `json:"location,omitempty"` + // Rotation is how AccountIDs is used: failover, spread or first. Empty + // is the daemon's default, failover. + Rotation string `json:"rotation,omitempty"` + Extension string `json:"extension,omitempty"` + API string `json:"api,omitempty"` + BaseURL string `json:"baseUrl,omitempty"` + APIKey string `json:"apiKey,omitempty"` + Model string `json:"model"` + Protocol string `json:"protocol"` + AccountIDs []string `json:"account_ids,omitempty"` + HasKey bool `json:"hasKey,omitempty"` } func validateModel(value string) (string, error) { @@ -95,7 +98,7 @@ func (s Settings) Validate() (Settings, error) { } return Settings{ - ProfileName: s.ProfileName, Effort: s.Effort, ImageEdge: s.ImageEdge, AccountID: s.AccountID, AccountIDs: s.AccountIDs, Project: s.Project, Location: s.Location, + ProfileName: s.ProfileName, Effort: s.Effort, ImageEdge: s.ImageEdge, AccountID: s.AccountID, AccountIDs: s.AccountIDs, Rotation: s.Rotation, Project: s.Project, Location: s.Location, Extension: ext, API: s.API, BaseURL: endpoint, diff --git a/cli/internal/daemon/auth.go b/cli/internal/daemon/auth.go index 84c878f06..bb1641a89 100644 --- a/cli/internal/daemon/auth.go +++ b/cli/internal/daemon/auth.go @@ -27,11 +27,17 @@ type Terms struct { Paragraphs []string } type Account struct { - Provider, ID, Label, Detail, Kind, Source, LimitedUntil string Endpoint *string - RotatedByProfiles []string - Selected bool - SelectedByProfiles []string + Provider, ID, Label, Detail, Kind, Source, LimitedUntil string + // Email and Plan are what the provider reported for a sign-in; empty + // when it reported nothing. + Email, Plan string + RotatedByProfiles []string + SelectedByProfiles []string + Selected bool + // NeedsSignIn marks a saved sign-in the provider no longer accepts; it + // works again after signing in again. + NeedsSignIn bool } type SignIns struct { Logins []SignIn @@ -44,7 +50,7 @@ type SignInStatus struct { } func accountValue(w protocol.Account) Account { - return Account{Provider: string(w.Provider), ID: string(w.ID), Label: w.Label, Detail: w.Detail, Kind: w.Kind, Source: w.Source, Endpoint: w.Endpoint, LimitedUntil: value(w.LimitedUntil), RotatedByProfiles: idsToStrings(w.RotatedByProfiles), Selected: len(w.SelectedByProfiles) > 0, SelectedByProfiles: idsToStrings(w.SelectedByProfiles)} + return Account{Provider: string(w.Provider), ID: string(w.ID), Label: w.Label, Detail: w.Detail, Kind: w.Kind, Source: w.Source, Endpoint: w.Endpoint, LimitedUntil: value(w.LimitedUntil), Email: value(w.Email), Plan: value(w.Plan), NeedsSignIn: w.NeedsSignIn, RotatedByProfiles: idsToStrings(w.RotatedByProfiles), Selected: len(w.SelectedByProfiles) > 0, SelectedByProfiles: idsToStrings(w.SelectedByProfiles)} } func idsToStrings(ids []protocol.ID) []string { if len(ids) == 0 { diff --git a/cli/internal/daemon/models.go b/cli/internal/daemon/models.go index 20b50e57f..ad28a694b 100644 --- a/cli/internal/daemon/models.go +++ b/cli/internal/daemon/models.go @@ -336,7 +336,7 @@ func ResolveSessionModel(profiles config.Profiles, requested string) (string, st } } if _, configured := profiles.Providers[profiles.Active]; !configured { - return "", "", fmt.Errorf("the session's provider is not configured; run /login") + return "", "", fmt.Errorf("the session's provider is not configured; run /accounts") } return profiles.Active, requested, nil } diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 6d67d6e67..6618de9f6 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -150,6 +150,9 @@ type ACPTextBlock struct { type Account struct { Detail string `json:"detail"` + // Email The sign-in's email when the provider reports one; null for keys, environment accounts, and sign-ins that carry no email. New sign-ins take it as their label until renamed. + Email *string `json:"email" nullable:"true"` + // Endpoint The base url a key account sends to; null for sign-in accounts. Endpoint *string `json:"endpoint" nullable:"true"` @@ -163,6 +166,12 @@ type Account struct { // LimitedUntil When a rate or usage limit recorded against this account ends; null when it has room. LimitedUntil *string `json:"limited_until" nullable:"true"` + // NeedsSignIn The saved sign-in can no longer be used (its renewal was refused, it was revoked, or the provider suspended it) until it is signed in again. Rotation skips it. Always false for keys. + NeedsSignIn bool `json:"needs_sign_in"` + + // Plan The subscription tier the provider reports for a sign-in, such as `Max`, `Pro` or `Plus`; null when unknown. + Plan *string `json:"plan" nullable:"true"` + // Provider Opaque identity. Never infer a resource type or route from its contents. Provider ID `json:"provider"` @@ -2519,7 +2528,7 @@ type ProgressPreview struct { type ProviderProfile struct { AccountID *ID `json:"account_id" nullable:"true"` - // AccountIDs Accounts this profile rotates between after a limit, by id. Null when it does not rotate. Exclusive with `account_id`; with neither, a profile uses one account (its saved key, the environment key, or the provider's selected or first account) and never switches. + // AccountIDs Accounts this profile uses, in order, by id. Null when it does not rotate. Exclusive with `account_id`; with neither, a profile uses one account (its saved key, the environment key, or the provider's selected or first account) and never switches. `rotation` says how the list is used. AccountIDs []ID `json:"account_ids" nullable:"true"` // API Bedrock API mode. Null or omission means messages; replay protocol is unchanged. @@ -2539,13 +2548,16 @@ type ProviderProfile struct { Model ID `json:"model"` Project *string `json:"project" nullable:"true"` Protocol string `json:"protocol"` + + // Rotation How `account_ids` is used. `failover` uses the first ready account and moves down the list after a limit. `spread` starts each new session (every agent is a session) on the next ready account in turn and keeps it there for the session's life, so its prompt cache stays warm; it moves only when that account is limited or needs sign-in, and stays on the account it moved to. `first` uses only the first and waits out its limit. Ignored without `account_ids`. + Rotation string `json:"rotation"` } // ProviderProfilePatch Partial existing profile; extension and model required when creating a new map entry. type ProviderProfilePatch struct { AccountID *ID `json:"account_id,omitempty" nullable:"true"` - // AccountIDs Accounts this profile rotates between after a limit, by id. Null when it does not rotate. Exclusive with `account_id`; with neither, a profile uses one account (its saved key, the environment key, or the provider's selected or first account) and never switches. + // AccountIDs Accounts this profile uses, in order, by id. Null when it does not rotate. Exclusive with `account_id`; with neither, a profile uses one account (its saved key, the environment key, or the provider's selected or first account) and never switches. `rotation` says how the list is used. AccountIDs []ID `json:"account_ids,omitempty" nullable:"true"` // API Bedrock API mode. Omission preserves an existing value; new and legacy profiles without a value use messages; converse selects streaming Converse. @@ -2565,6 +2577,9 @@ type ProviderProfilePatch struct { Model *ID `json:"model,omitempty"` Project *string `json:"project,omitempty" nullable:"true"` Protocol *string `json:"protocol,omitempty"` + + // Rotation How `account_ids` is used. `failover` uses the first ready account and moves down the list after a limit. `spread` starts each new session (every agent is a session) on the next ready account in turn and keeps it there for the session's life, so its prompt cache stays warm; it moves only when that account is limited or needs sign-in, and stays on the account it moved to. `first` uses only the first and waits out its limit. Ignored without `account_ids`. + Rotation *string `json:"rotation,omitempty"` } // ProviderRequestRecord defines model for ProviderRequestRecord. @@ -5521,7 +5536,7 @@ type ClientInterface interface { // DeleteAccount Remove an unreferenced provider account // - // Reject if a profile pins it by `account_id`, if it is the last account of a profile's `account_ids`, or if it comes from the environment (`account_external`). Otherwise it also leaves every `account_ids` list naming it. Does not interrupt captured credentials in an active request. Account IDs are never reused. Requires capability `provider_auth: 1`. + // Signs the account out. Reject only an account that comes from the environment (`account_external`). A profile pinned to it by `account_id` goes back to automatic selection, and it leaves every `account_ids` list naming it; a list it empties becomes null. Does not interrupt captured credentials in an active request. Account IDs are never reused. Requires capability `provider_auth: 1`. // // Corresponds with DELETE /auth/accounts/{account_id} (the `DeleteAccount` operationId). DeleteAccount(ctx context.Context, accountID ID, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -7192,7 +7207,7 @@ func (c *Client) GetAuth(ctx context.Context, reqEditors ...RequestEditorFn) (*h // DeleteAccount Remove an unreferenced provider account // -// Reject if a profile pins it by `account_id`, if it is the last account of a profile's `account_ids`, or if it comes from the environment (`account_external`). Otherwise it also leaves every `account_ids` list naming it. Does not interrupt captured credentials in an active request. Account IDs are never reused. Requires capability `provider_auth: 1`. +// Signs the account out. Reject only an account that comes from the environment (`account_external`). A profile pinned to it by `account_id` goes back to automatic selection, and it leaves every `account_ids` list naming it; a list it empties becomes null. Does not interrupt captured credentials in an active request. Account IDs are never reused. Requires capability `provider_auth: 1`. // // Corresponds with DELETE /auth/accounts/{account_id} (the `DeleteAccount` operationId). func (c *Client) DeleteAccount(ctx context.Context, accountID ID, reqEditors ...RequestEditorFn) (*http.Response, error) { diff --git a/cli/internal/daemon/protocol/digest.gen.go b/cli/internal/daemon/protocol/digest.gen.go index 508924520..4547dc869 100644 --- a/cli/internal/daemon/protocol/digest.gen.go +++ b/cli/internal/daemon/protocol/digest.gen.go @@ -5,4 +5,4 @@ package protocol // APIDigest identifies the wire contract these types were generated from. // The daemon reports its own in GET /server; a different value means this // client's decoders may reject what the daemon sends. -const APIDigest = "809b03d0ead404bba1e79ec4b88f1ae1250dc7ad97471bc755f06bb586561f58" +const APIDigest = "bb284504402366058bf4db589d0ac1996c8b9354b439ee8f0f4c393ebfb3a5d5" diff --git a/cli/internal/daemon/rotation.go b/cli/internal/daemon/rotation.go new file mode 100644 index 000000000..baffa155a --- /dev/null +++ b/cli/internal/daemon/rotation.go @@ -0,0 +1,117 @@ +package daemon + +import ( + "cmp" + "context" + "maps" + "slices" + + "albedo/cli/internal/config" + "albedo/cli/internal/daemon/protocol" +) + +// The rotation modes a service's accounts take. A profile stores one of +// them beside its account_ids. +const ( + RotationFailover = "failover" + RotationSpread = "spread" + RotationFirst = "first" +) + +// ServiceRotation is how a service's sign-in accounts are used, read from +// its profiles the way every client reads it: the lead profile is the +// default when it runs this extension, else the first by name with an +// account list, else the first by name. The order is the lead's list (ids +// that still exist) followed by the service's other accounts in the order +// given; the mode is the lead's rotation when it has a list. A lead with one +// account, pinned or automatic, never switches, which reads as first. +func ServiceRotation(extension string, profiles config.Profiles, accounts []string) (order []string, mode string) { + lead, ok := leadProfile(extension, profiles) + mode = RotationFailover + if ok { + for _, id := range lead.AccountIDs { + if slices.Contains(accounts, id) && !slices.Contains(order, id) { + order = append(order, id) + } + } + switch { + case len(lead.AccountIDs) > 0: + mode = cmp.Or(lead.Rotation, RotationFailover) + case len(accounts) > 1: + mode = RotationFirst + } + } + for _, id := range accounts { + if !slices.Contains(order, id) { + order = append(order, id) + } + } + return order, mode +} + +func leadProfile(extension string, profiles config.Profiles) (config.Settings, bool) { + if s, ok := profiles.Providers[profiles.Active]; ok && profileExtension(s) == extension { + return s, true + } + names := slices.Sorted(maps.Keys(profiles.Providers)) + var first *config.Settings + for _, name := range names { + s := profiles.Providers[name] + if profileExtension(s) != extension { + continue + } + if len(s.AccountIDs) > 0 { + return s, true + } + if first == nil { + first = &s + } + } + if first == nil { + return config.Settings{}, false + } + return *first, true +} + +func profileExtension(s config.Settings) string { return cmp.Or(s.Extension, "openai") } + +// RotationTargets are the profiles a service's rotation is written to: every +// profile of the extension except those pinned to one account, an override +// kept under advanced setups, and those holding a key of their own, which +// do not sign in. +func RotationTargets(extension string, profiles config.Profiles) []string { + var names []string + for _, name := range slices.Sorted(maps.Keys(profiles.Providers)) { + s := profiles.Providers[name] + if profileExtension(s) == extension && s.AccountID == nil && !s.HasKey { + names = append(names, name) + } + } + return names +} + +// RotationPatch is the providers settings patch that gives a service the +// order and mode: every target profile takes the list and the mode, and +// drops any pin. It is nil when no profile would change. +func RotationPatch(extension string, profiles config.Profiles, order []string, mode string) map[string]any { + targets := RotationTargets(extension, profiles) + if len(targets) == 0 { + return nil + } + patch := map[string]any{} + for _, name := range targets { + patch[name] = map[string]any{"account_ids": slices.Clone(order), "rotation": mode, "account_id": nil} + } + return map[string]any{"profiles": patch} +} + +// SaveServiceRotation writes a service's order and mode in one patch. It +// reports false when no profile runs the service, so nothing was written. +func SaveServiceRotation(ctx context.Context, conn *Connection, extension string, profiles config.Profiles, order []string, mode string) (bool, error) { + body := RotationPatch(extension, profiles, order, mode) + if body == nil { + return false, nil + } + var change protocol.ProviderSettingsChange + return true, patchSettingsGroup(ctx, conn, "providers", profiles.ETag, body, &change) +} diff --git a/cli/internal/daemon/rotation_test.go b/cli/internal/daemon/rotation_test.go new file mode 100644 index 000000000..cccd4326d --- /dev/null +++ b/cli/internal/daemon/rotation_test.go @@ -0,0 +1,64 @@ +// The service rotation mapping every client shares: one ordered list and +// mode per service, read from a lead profile and written to every profile +// of the extension that is not pinned. +package daemon + +import ( + "reflect" + "testing" + + "albedo/cli/internal/config" +) + +func TestServiceRotationReadsTheLeadProfile(t *testing.T) { + accounts := []string{"a", "b", "c"} + cases := []struct { + profiles config.Profiles + name string + mode string + order []string + }{ + {name: "no profile keeps auth order", profiles: config.Profiles{Providers: map[string]config.Settings{}}, + order: []string{"a", "b", "c"}, mode: RotationFailover}, + {name: "automatic lead with several accounts reads as first", profiles: config.Profiles{Providers: map[string]config.Settings{ + "claude": {Extension: "claude"}, + }}, order: []string{"a", "b", "c"}, mode: RotationFirst}, + {name: "default profile leads, gone ids are dropped, the rest follow", profiles: config.Profiles{Active: "work", Providers: map[string]config.Settings{ + "alpha": {Extension: "claude", AccountIDs: []string{"a"}, Rotation: "first"}, + "work": {Extension: "claude", AccountIDs: []string{"c", "gone", "a"}, Rotation: "spread"}, + }}, order: []string{"c", "a", "b"}, mode: RotationSpread}, + {name: "a default of another extension does not lead", profiles: config.Profiles{Active: "gpt", Providers: map[string]config.Settings{ + "gpt": {Extension: "codex", AccountIDs: []string{"x"}}, + "plain": {Extension: "claude"}, + "zeta": {Extension: "claude", AccountIDs: []string{"b", "a"}}, + }}, order: []string{"b", "a", "c"}, mode: RotationFailover}, + } + for _, c := range cases { + order, mode := ServiceRotation("claude", c.profiles, accounts) + if !reflect.DeepEqual(order, c.order) || mode != c.mode { + t.Errorf("%s: got %v %s, want %v %s", c.name, order, mode, c.order, c.mode) + } + } + if _, mode := ServiceRotation("claude", config.Profiles{Providers: map[string]config.Settings{"c": {Extension: "claude"}}}, []string{"a"}); mode != RotationFailover { + t.Errorf("one automatic account reads as %s", mode) + } +} + +func TestRotationPatchSkipsPinnedAndKeyedProfiles(t *testing.T) { + profiles := config.Profiles{Providers: map[string]config.Settings{ + "claude": {Extension: "claude"}, + "team": {Extension: "claude", AccountIDs: []string{"a"}}, + "pinned": {Extension: "claude", AccountID: new("a")}, + "keyed": {Extension: "claude", HasKey: true}, + "chatgpt": {Extension: "codex"}, + }} + got := RotationPatch("claude", profiles, []string{"b", "a"}, RotationSpread) + entry := map[string]any{"account_ids": []string{"b", "a"}, "rotation": "spread", "account_id": nil} + want := map[string]any{"profiles": map[string]any{"claude": entry, "team": entry}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("patch %v, want %v", got, want) + } + if RotationPatch("gemini", profiles, []string{"a"}, RotationFailover) != nil { + t.Fatal("a service no profile runs got a patch") + } +} diff --git a/cli/internal/daemon/settings.go b/cli/internal/daemon/settings.go index ca57f2012..5fc538722 100644 --- a/cli/internal/daemon/settings.go +++ b/cli/internal/daemon/settings.go @@ -56,7 +56,7 @@ func GetSettings(ctx context.Context, conn *Connection) (Settings, error) { } result := Settings{Profiles: config.Profiles{Active: value(wire.Providers.DefaultProfile), Providers: map[string]config.Settings{}, ETag: wire.GroupResources.Providers.ETag}, MCP: map[string]config.MCPServer{}, Credentials: Credentials{MCP: map[string]MCPSecretNames{}}, ETags: map[string]string{"providers": wire.GroupResources.Providers.ETag, "mcp": wire.GroupResources.MCP.ETag, "extensions": wire.GroupResources.Extensions.ETag, "extension_settings": wire.GroupResources.ExtensionSettings.ETag, "capabilities": wire.GroupResources.Capabilities.ETag, "models": wire.GroupResources.Models.ETag, "ui": wire.GroupResources.UI.ETag}, Extensions: wire.Extensions.Defaults} for name, profile := range wire.Providers.Profiles { - result.Profiles.Providers[name] = config.Settings{ProfileName: name, Extension: profile.Extension, API: value(profile.API), BaseURL: value(profile.Endpoint), Model: profile.Model, Protocol: profile.Protocol, HasKey: profile.HasKey, Effort: profile.Effort, ImageEdge: intPointer(profile.ImageEdge), AccountID: profile.AccountID, AccountIDs: idsToStrings(profile.AccountIDs), Project: profile.Project, Location: profile.Location} + result.Profiles.Providers[name] = config.Settings{ProfileName: name, Extension: profile.Extension, API: value(profile.API), BaseURL: value(profile.Endpoint), Model: profile.Model, Protocol: profile.Protocol, HasKey: profile.HasKey, Effort: profile.Effort, ImageEdge: intPointer(profile.ImageEdge), AccountID: profile.AccountID, AccountIDs: idsToStrings(profile.AccountIDs), Rotation: profile.Rotation, Project: profile.Project, Location: profile.Location} if profile.HasKey { result.Credentials.Providers = append(result.Credentials.Providers, name) } @@ -150,6 +150,9 @@ func saveProvider(ctx context.Context, conn *Connection, name string, profile co if profile.API != "" { profilePatch["api"] = profile.API } + if profile.Rotation != "" { + profilePatch["rotation"] = profile.Rotation + } if profile.APIKey != "" { profilePatch["api_key"] = profile.APIKey } diff --git a/cli/internal/daemon/settings_bedrock_test.go b/cli/internal/daemon/settings_bedrock_test.go index 10c0d5c2a..8461eced5 100644 --- a/cli/internal/daemon/settings_bedrock_test.go +++ b/cli/internal/daemon/settings_bedrock_test.go @@ -16,7 +16,7 @@ func TestBedrockAPISettingsRoundTrip(t *testing.T) { t.Run(stringOrDefault(api), func(t *testing.T) { profile := map[string]any{"extension": "bedrock", "api": api, "endpoint": nil, "protocol": "chat_completions", "model": "amazon.nova-pro-v1:0", "effort": nil, - "image_edge": nil, "account_id": nil, "account_ids": []string{"first", "second"}, "project": nil, "location": nil, "has_key": true} + "image_edge": nil, "account_id": nil, "account_ids": []string{"first", "second"}, "project": nil, "location": nil, "has_key": true, "rotation": "spread"} conn := controlledConnection(t, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if r.Method == http.MethodGet && r.URL.Path == "/settings" { @@ -52,7 +52,7 @@ func TestBedrockAPISettingsRoundTrip(t *testing.T) { t.Errorf("save changed API: %v", sent) } ids, ok := sent["account_ids"].([]any) - if !ok || len(ids) != 2 || ids[0] != "first" || ids[1] != "second" || sent["account_id"] != nil { + if !ok || len(ids) != 2 || ids[0] != "first" || ids[1] != "second" || sent["account_id"] != nil || sent["rotation"] != "spread" { t.Errorf("save changed explicit rotation: %v", sent) } if sent["protocol"] != "chat_completions" || sent["extension"] != "bedrock" { diff --git a/cli/internal/tui/accounts.go b/cli/internal/tui/accounts.go new file mode 100644 index 000000000..a50cd66d7 --- /dev/null +++ b/cli/internal/tui/accounts.go @@ -0,0 +1,978 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "cmp" + "context" + "fmt" + "maps" + "slices" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +// accountService is a sign-in service as /accounts names it: what it is +// called, the models it brings, and the subscriptions that sign in to it. +type accountService struct{ Extension, Label, Blurb, Plans string } + +// accountServices are the sign-in services /accounts lists first, in this +// order. Keep the names and model lists here so they are easy to update; +// other sign-in services keep the daemon's own label and detail. +var accountServices = []accountService{ + {Extension: "claude", Label: "Claude", Blurb: "Opus, Sonnet, Haiku", Plans: "Pro or Max"}, + {Extension: "codex", Label: "ChatGPT", Blurb: "Astra, Sol, Terra, Luna", Plans: "Plus or Pro"}, + {Extension: "antigravity", Label: "Gemini", Blurb: "Gemini 4 Carbon, Argon, Hydrogen", Plans: "Google account"}, +} + +// keyBlurb is what the API key group can reach. +const keyBlurb = "OpenRouter, Mistral, Bedrock…" + +// rotationModes are how a service's accounts take turns, in the order tab +// cycles them. +var rotationModes = []struct{ ID, Label, Detail string }{ + {daemon.RotationFailover, "one at a time", "Use #1; move down the list when it's limited."}, + {daemon.RotationSpread, "spread evenly", "Each new session or agent starts on the next account and stays there."}, + {daemon.RotationFirst, "only #1", "Never switch; wait when it's limited."}, +} + +func rotationMode(id string) (label, detail string) { + for _, mode := range rotationModes { + if mode.ID == id { + return mode.Label, mode.Detail + } + } + return rotationModes[0].Label, rotationModes[0].Detail +} + +// nextRotation is the mode after id in the cycle. +func nextRotation(id string) string { + i := slices.IndexFunc(rotationModes, func(mode struct{ ID, Label, Detail string }) bool { return mode.ID == id }) + return rotationModes[(i+1)%len(rotationModes)].ID +} + +// The sections and rows of /accounts that are not a service's own. +const ( + sectionKeys = "API keys" + sectionTools = "tool sign-ins" + sectionMore = "sign in to more" + sectionAdvanced = "advanced" + + rowAccount = "acct:" + rowAdd = "add:" + rowMore = "more:" + rowTool = "tool:" + rowKeys = "keys" + rowAdvanced = "advanced" + rowPending = "pending" +) + +// serviceGroup is one sign-in service with the accounts it holds, in the +// order its rotation uses them. +type serviceGroup struct { + Extension, Label, Blurb, Mode string + Accounts []daemon.Account + HasLogin bool +} + +// rotates reports a service whose accounts take turns, so they are numbered +// and tab and alt+↑↓ change how. +func (g serviceGroup) rotates() bool { return len(g.Accounts) > 1 } + +func modelAccount(a daemon.Account) bool { return a.Kind != "key" && a.Kind != "service" } + +// serviceName is a sign-in service's label and model list. +func (m LoginModel) serviceName(extension string) (label, blurb string) { + if i := slices.IndexFunc(accountServices, func(s accountService) bool { return s.Extension == extension }); i >= 0 { + return accountServices[i].Label, accountServices[i].Blurb + } + if login, ok := m.signInFor(extension); ok { + return cmp.Or(login.Label, extension), login.Detail + } + return extension, "" +} + +// serviceGroups lists every model sign-in service: those in accountServices +// first in its order, then the rest as the daemon lists them, then any +// provider holding accounts the daemon no longer offers a sign-in for. +func (m LoginModel) serviceGroups() []serviceGroup { + var extensions []string + for _, s := range accountServices { + if login, ok := m.signInFor(s.Extension); ok && login.Kind != "service" { + extensions = append(extensions, s.Extension) + } + } + for _, login := range m.SignIns { + if login.Kind != "service" && !slices.Contains(extensions, login.Provider) { + extensions = append(extensions, login.Provider) + } + } + for _, a := range m.Accounts { + if modelAccount(a) && !slices.Contains(extensions, a.Provider) { + extensions = append(extensions, a.Provider) + } + } + groups := make([]serviceGroup, 0, len(extensions)) + for _, extension := range extensions { + var ids []string + byID := map[string]daemon.Account{} + for _, a := range m.Accounts { + if a.Provider == extension && modelAccount(a) { + ids = append(ids, a.ID) + byID[a.ID] = a + } + } + order, mode := daemon.ServiceRotation(extension, m.Profiles, ids) + g := serviceGroup{Extension: extension, Mode: mode} + g.Label, g.Blurb = m.serviceName(extension) + _, g.HasLogin = m.signInFor(extension) + for _, id := range order { + g.Accounts = append(g.Accounts, byID[id]) + } + groups = append(groups, g) + } + return groups +} + +// groupOf is the service an account belongs to. +func (m LoginModel) groupOf(account daemon.Account) (serviceGroup, bool) { + for _, g := range m.serviceGroups() { + if g.Extension == account.Provider && modelAccount(account) { + return g, true + } + } + return serviceGroup{}, false +} + +// accountByID finds an account the daemon listed. +func (m LoginModel) accountByID(id string) (daemon.Account, bool) { + i := slices.IndexFunc(m.Accounts, func(a daemon.Account) bool { return a.ID == id }) + if i < 0 { + return daemon.Account{}, false + } + return m.Accounts[i], true +} + +// limitedUntil is when an account's limit ends, if it is limited now. +func limitedUntil(a daemon.Account) (time.Time, bool) { + until, err := time.Parse(time.RFC3339, a.LimitedUntil) + if err != nil || !until.After(time.Now()) { + return time.Time{}, false + } + return until, true +} + +func clock(t time.Time) string { return t.Local().Format("15:04") } + +// allLimited reports a service none of whose accounts can run now, at least +// one of them only until a limit ends, and when the first comes back. +func (g serviceGroup) allLimited() (time.Time, bool) { + var first time.Time + for _, a := range g.Accounts { + until, limited := limitedUntil(a) + switch { + case a.NeedsSignIn, !limited: + return time.Time{}, false + case first.IsZero() || until.Before(first): + first = until + } + } + return first, !first.IsZero() +} + +// keyName is what a key account reaches: the key provider whose endpoint +// it sends to, else the endpoint's host, else its extension. +func keyName(a daemon.Account) string { + if a.Endpoint != nil { + for _, p := range customProviders { + if p.DefaultURL != "" && p.DefaultURL == *a.Endpoint { + return p.Label + } + } + } + if p, ok := customFor(a.Provider); ok && p.Extension != "openai" { + return p.Label + } + return cmp.Or(a.Detail, a.Provider) +} + +// sameKeyTarget reports two key accounts that reach the same models. +func sameKeyTarget(a, b daemon.Account) bool { + return a.Provider == b.Provider && deref(a.Endpoint) == deref(b.Endpoint) +} + +// signOutConsequence says what keeps working, or stops, once the account +// is signed out. +func (m LoginModel) signOutConsequence(a daemon.Account) string { + switch a.Kind { + case "key": + name := keyName(a) + var rest []string + for _, other := range m.Accounts { + if other.ID != a.ID && other.Kind == "key" && sameKeyTarget(a, other) { + rest = append(rest, other.Label) + } + } + if len(rest) > 0 { + return fmt.Sprintf("%s keeps running on %s.", name, strings.Join(rest, ", ")) + } + return fmt.Sprintf("Models from %s stop until you add another %s key.", name, name) + case "service": + return "Tools that use it stop until you sign in again." + } + label, _ := m.serviceName(a.Provider) + var rest []string + if g, ok := m.groupOf(a); ok { + for _, other := range g.Accounts { + if other.ID != a.ID { + rest = append(rest, other.Label) + } + } + } + if len(rest) > 0 { + return fmt.Sprintf("%s keeps running on %s.", label, strings.Join(rest, ", ")) + } + return label + " models stop working until you sign in again. Sessions keep their history." +} + +// lastOfService reports that signing out leaves its service nothing to run. +func (m LoginModel) lastOfService(a daemon.Account) bool { + return !strings.Contains(m.signOutConsequence(a), "keeps running") +} + +// pendingIn reports the inline sign-in in flight for a provider, and which +// account it signs in again, if any. +func (m LoginModel) pendingIn(provider string) (accountID string, ok bool) { + if !m.signingInline() || m.Provider != provider { + return "", false + } + return m.reSignIn, true +} + +// signingInline reports a sign-in started from the accounts list, which +// stays on screen while it runs. +func (m LoginModel) signingInline() bool { + return m.inline && (m.Step == StepOAuth) +} + +// accountsEmpty reports the first run: nothing signed in, no key and no +// setup, so the screen offers the sign-ins up front instead of a list. +func (m LoginModel) accountsEmpty() bool { + if !m.loaded || len(m.Profiles.Providers) > 0 || m.signingInline() { + return false + } + return !slices.ContainsFunc(m.Accounts, func(a daemon.Account) bool { return a.Kind != "service" }) +} + +// accountColumns are the widths of an account row's label, plan and status +// in width cells after its lead. +func accountColumns(width int) (label, plan, status int) { + label, plan, status = 22, 11, 15 + if spare := width - (3 + label + 1 + plan + status + 3); spare < 0 { + label = max(8, label+spare) + } + return label, plan, status +} + +// buildChoosePicker lists what the screen shows: the accounts, or the +// advanced setups when they are open. +func (m *LoginModel) buildChoosePicker() { + if m.advanced { + m.buildAdvancedPicker() + return + } + m.buildAccountsPicker() +} + +// buildAccountsPicker lists the accounts one section per service, each +// closed by a row that adds another, then API keys, tool sign-ins, the +// services not yet signed in to, and the advanced setups. The cursor stays +// on its row across a rebuild. +func (m *LoginModel) buildAccountsPicker() { + keep := m.focus + m.focus = "" + if keep == "" { + if row, ok := m.ChoosePicker.highlighted(); ok { + keep = row.key + } + } + var rows []listEntry + titles := map[string]func(width int) string{} + pendingRow := func(section string) listEntry { + return listEntry{key: rowPending, section: section, name: "signing in…", draw: func(int, []int) string { + return DefaultStyles.Agent.Render("◌") + " " + DefaultStyles.Agent.Render("signing in… finish in your browser") + }, detail: m.pendingPane} + } + var more []listEntry + for _, g := range m.serviceGroups() { + reSign, pending := m.pendingIn(g.Extension) + if len(g.Accounts) == 0 && !pending { + if g.HasLogin { + more = append(more, m.moreRow(rowMore+g.Extension, g.Label, g.Blurb, m.servicePane(g))) + } + continue + } + section := g.Label + titles[section] = m.groupTitle(g) + for i, a := range g.Accounts { + if pending && reSign == a.ID { + rows = append(rows, pendingRow(section)) + continue + } + rows = append(rows, m.accountRow(a, section, g, i)) + } + switch { + case pending && reSign == "": + rows = append(rows, pendingRow(section)) + case g.HasLogin: + rows = append(rows, m.addRow(rowAdd+g.Extension, section, "add a "+g.Label+" account", m.servicePane(g))) + } + } + var keys []daemon.Account + for _, a := range m.Accounts { + if a.Kind == "key" { + keys = append(keys, a) + } + } + if len(keys) > 0 { + titles[sectionKeys] = func(width int) string { return accountsRule(sectionKeys, len(keys), "", width) } + for _, a := range keys { + rows = append(rows, m.accountRow(a, sectionKeys, serviceGroup{}, 0)) + } + rows = append(rows, m.addRow(rowKeys, sectionKeys, "add a key", m.keysPane())) + } else { + more = append(more, m.moreRow(rowKeys, "API key or endpoint", keyBlurb, m.keysPane())) + } + var tools []listEntry + for _, login := range m.SignIns { + if login.Kind != "service" { + continue + } + signedIn := false + for _, a := range m.Accounts { + if a.Provider == login.Provider && a.Kind == "service" { + signedIn = true + tools = append(tools, m.accountRow(a, sectionTools, serviceGroup{}, 0)) + } + } + if _, pending := m.pendingIn(login.Provider); pending { + tools = append(tools, pendingRow(sectionTools)) + } else if !signedIn { + tools = append(tools, m.addRow(rowTool+login.Provider, sectionTools, "sign in to "+login.Label, m.toolPane(login))) + } + } + if len(tools) > 0 { + count := 0 + for _, t := range tools { + if strings.HasPrefix(t.key, rowAccount) { + count++ + } + } + titles[sectionTools] = func(width int) string { return accountsRule("tool sign-ins", count, "", width) } + rows = append(rows, tools...) + } + if len(more) > 0 { + titles[sectionMore] = func(width int) string { return accountsRule(sectionMore, -1, "", width) } + rows = append(rows, more...) + } + titles[sectionAdvanced] = func(width int) string { return accountsRule(sectionAdvanced, -1, "", width) } + rows = append(rows, listEntry{key: rowAdvanced, section: sectionAdvanced, name: "setups", desc: "models, endpoints, protocols, pins", + search: []string{"profiles", "advanced"}, + draw: func(width int, hits []int) string { + lw, _, _ := accountColumns(width) + return DefaultStyles.Muted.Render("⋯") + " " + markedCell("setups", hits, lw, lipgloss.NewStyle()) + " " + + DefaultStyles.Faint.Render(ansi.Truncate("models, endpoints, protocols, pins", max(1, width-lw-4), "…")) + }, + detail: m.advancedPane}) + + if !slices.ContainsFunc(rows, func(r listEntry) bool { return r.key == keep }) { + keep = "" + if i := slices.IndexFunc(rows, func(r listEntry) bool { return strings.HasPrefix(r.key, rowAccount) }); i >= 0 { + keep = rows[i].key + } + } + if m.signingInline() { + keep = rowPending + } + if !m.loaded { + // Nothing is known until the daemon answers, not even what to add. + rows = nil + } + p := loginPick{listView: newListView("Search")} + p.Empty = "loading accounts…" + p.setSize(m.Width, m.Height) + p.sectionTitle = func(section string, width int) string { + if title, ok := titles[section]; ok { + return title(width) + } + return sectionRule(section, 0, width) + } + for _, r := range rows { + p.items = append(p.items, loginItem{ID: r.key, Label: r.name}) + } + p.setRows(rows) + if i := slices.IndexFunc(p.shown, func(s listShown) bool { return p.rows[s.row].key == keep }); i >= 0 { + p.Cursor = i + } + m.ChoosePicker = p +} + +// accountsRule heads a section: " ─ Claude 2 · one at a time ───". A +// negative count shows none. +func accountsRule(label string, count int, extra string, width int) string { + head := " " + label + " " + tail := "" + if count >= 0 { + tail = fmt.Sprintf("%d ", count) + } + used := 2 + ansi.StringWidth(head+tail) + ansi.StringWidth(extra) + if extra != "" { + used++ + } + out := DefaultStyles.Decor.Render(" ─") + DefaultStyles.Muted.Bold(true).Render(head) + DefaultStyles.Decor.Render(tail) + if extra != "" { + out += extra + " " + } + return out + DefaultStyles.Decor.Render(strings.Repeat("─", max(2, width-used))) +} + +// groupTitle is a service's rule: its name, how many accounts it has, and +// how they take turns, or when the first is back if every one is limited. +func (m LoginModel) groupTitle(g serviceGroup) func(width int) string { + extra := "" + if back, all := g.allLimited(); all { + extra = DefaultStyles.Faint.Render("· ") + DefaultStyles.Warning.Render("all limited · back "+clock(back)) + } else if g.rotates() { + label, _ := rotationMode(g.Mode) + extra = DefaultStyles.Faint.Render("· " + label) + } + return func(width int) string { return accountsRule(g.Label, len(g.Accounts), extra, width) } +} + +// accountState is an account's dot, its short status for the row, and its +// longer one for the pane, each in its colour. +func accountState(a daemon.Account) (dot, short, long string) { + if a.NeedsSignIn { + return DefaultStyles.Error.Render("✕"), DefaultStyles.Error.Render("sign in again"), DefaultStyles.Error.Render("needs sign-in") + } + if until, limited := limitedUntil(a); limited { + return DefaultStyles.Warning.Render("◐"), DefaultStyles.Warning.Render("back " + clock(until)), DefaultStyles.Warning.Render("limited until " + clock(until)) + } + if a.Source == "env" { + return DefaultStyles.Success.Render("●"), DefaultStyles.Faint.Render("environment"), DefaultStyles.Success.Render("ready") + } + return DefaultStyles.Success.Render("●"), DefaultStyles.Muted.Render("ready"), DefaultStyles.Success.Render("ready") +} + +// accountPlan is the small tag after an account's label: its plan, or for a +// key what it reaches. +func accountPlan(a daemon.Account) string { + if a.Kind == "key" { + return keyName(a) + } + return a.Plan +} + +// accountRow is one account: its state, label, plan, status, and its place +// in the rotation when the service has several. +func (m LoginModel) accountRow(a daemon.Account, section string, g serviceGroup, index int) listEntry { + place := "" + if g.rotates() { + place = fmt.Sprintf("#%d", index+1) + } + plan := accountPlan(a) + return listEntry{key: rowAccount + a.ID, section: section, name: a.Label, desc: plan, search: []string{a.Email}, + draw: func(width int, hits []int) string { + lw, pw, sw := accountColumns(width) + dot, short, _ := accountState(a) + status := short + strings.Repeat(" ", max(1, sw-ansi.StringWidth(short))) + return dot + " " + markedCell(a.Label, hits, lw, lipgloss.NewStyle()) + " " + + DefaultStyles.Muted.Render(svCell(plan, pw-1, false)) + " " + status + DefaultStyles.Faint.Render(place) + }, + detail: func(width int) []string { return m.accountPane(a, width) }} +} + +// addRow closes a section with what adds to it. +func (m LoginModel) addRow(key, section, label string, pane func(int) []string) listEntry { + return listEntry{key: key, section: section, name: label, draw: func(width int, hits []int) string { + return DefaultStyles.Muted.Render("+") + " " + markedCell(label, hits, max(1, width-3), DefaultStyles.Muted) + }, detail: pane} +} + +// moreRow is a service not signed in to yet, with what it brings. +func (m LoginModel) moreRow(key, label, blurb string, pane func(int) []string) listEntry { + return listEntry{key: key, section: sectionMore, name: label, desc: blurb, draw: func(width int, hits []int) string { + lw, _, _ := accountColumns(width) + line := DefaultStyles.Muted.Render("+") + " " + markedCell(label, hits, lw, lipgloss.NewStyle()) + if room := width - lw - 4; room > 3 && blurb != "" { + line += " " + DefaultStyles.Muted.Render(ansi.Truncate(blurb, room, "…")) + } + return line + }, detail: pane} +} + +// accountPane is what an account's detail says: its status, models and +// place, then what enter or ctrl+x does with it. +func (m LoginModel) accountPane(a daemon.Account, width int) []string { + service, blurb := m.serviceName(a.Provider) + switch a.Kind { + case "key": + service, blurb = "API keys", "from "+keyName(a) + case "service": + service, blurb = "tool sign-in", "" + } + subtitle := service + if plan := accountPlan(a); plan != "" { + subtitle += " · " + plan + } + lines := paneTitle(a.Label, subtitle, width) + _, _, long := accountState(a) + lines = append(lines, factRows("status", long, width)...) + if blurb != "" { + lines = append(lines, factRows("models", blurb, width)...) + } + g, grouped := m.groupOf(a) + if grouped && g.rotates() { + place := slices.IndexFunc(g.Accounts, func(o daemon.Account) bool { return o.ID == a.ID }) + 1 + mode, _ := rotationMode(g.Mode) + lines = append(lines, factRows("rotation", fmt.Sprintf("#%d of %d · %s", place, len(g.Accounts), mode), width)...) + } + if a.Email != "" && a.Email != a.Label { + lines = append(lines, factRows("email", a.Email, width)...) + } + if a.Source == "env" { + lines = append(lines, factRows("source", "the daemon's environment", width)...) + } + lines = append(lines, "") + back, all := g.allLimited() + switch { + case a.Source == "env": + lines = append(lines, paneNote("Read from the daemon's environment on every request; change or remove it there.", width)...) + case a.NeedsSignIn: + lines = append(lines, paneNote(service+" ended this sign-in. enter signs in again and keeps its place; rotation skips it until then.", width)...) + case grouped && all: + lines = append(lines, paneNote(fmt.Sprintf("Every %s account is limited. Sessions on %s wait until %s.", service, service, clock(back)), width)...) + if other := m.readyServiceBesides(a.Provider); other != "" { + // A sentence of its own, so the wrap never breaks after the slash. + lines = append(lines, paneNote("/model can switch them to "+other+".", width)...) + } + default: + lines = append(lines, paneNote("ctrl+x signs out this account. "+m.signOutConsequence(a), width)...) + } + return lines +} + +// readyServiceBesides names another service with an account that can run +// now, for sessions to move to. +func (m LoginModel) readyServiceBesides(extension string) string { + for _, g := range m.serviceGroups() { + if g.Extension == extension { + continue + } + for _, a := range g.Accounts { + if _, limited := limitedUntil(a); !limited && !a.NeedsSignIn { + return g.Label + } + } + } + return "" +} + +// servicePane is what adding an account to a service says. +func (m LoginModel) servicePane(g serviceGroup) func(int) []string { + return func(width int) []string { + title := "Sign in to " + g.Label + if len(g.Accounts) > 0 { + title = "Add a " + g.Label + " account" + } + lines := paneTitle(title, g.Blurb, width) + note := "enter opens " + g.Label + "'s sign-in page in your browser. Nothing else to answer." + if len(g.Accounts) > 0 { + note = fmt.Sprintf("enter opens %s's sign-in page in your browser. The new account joins the rotation as #%d.", g.Label, len(g.Accounts)+1) + } + return append(lines, paneNote(note, width)...) + } +} + +func (m LoginModel) keysPane() func(int) []string { + return func(width int) []string { + lines := paneTitle("API key or endpoint", keyBlurb, width) + return append(lines, paneNote("enter lists the key providers: OpenRouter, Mistral, Bedrock, Vertex, any OpenAI- or Anthropic-compatible endpoint.", width)...) + } +} + +func (m LoginModel) toolPane(login daemon.SignIn) func(int) []string { + return func(width int) []string { + lines := paneTitle(login.Label, login.Detail, width) + return append(lines, paneNote("A sign-in tools use, not models. enter signs in.", width)...) + } +} + +func (m LoginModel) advancedPane(width int) []string { + lines := paneTitle("Setups", "advanced", width) + return append(lines, paneNote("enter opens the named setups behind your accounts: which model each starts on, endpoints, protocols, keys, and accounts pinned to one setup.", width)...) +} + +// pendingPane is the sign-in in flight: the link to finish it on another +// machine, and where the account will go. +func (m LoginModel) pendingPane(width int) []string { + label, _ := m.serviceName(m.Provider) + lines := paneTitle("Signing in to "+label, "", width) + if m.SignInURL == "" { + lines = append(lines, DefaultStyles.Muted.Render(cmp.Or(m.Status, "starting sign-in…"))) + } else { + lead := "Open this page to sign in, or on another machine:" + if m.openBrowser != nil { + lead = "Your browser opened the sign-in page. If it didn't, or you're on another machine:" + } + lines = append(lines, paneNote(lead, width)...) + lines = append(lines, "") + lines = append(lines, linkRows(m.SignInURL, width)...) + } + if m.LoginInstructions != "" { + lines = append(lines, "") + lines = append(lines, paneNote(m.LoginInstructions, width)...) + } + lines = append(lines, "") + note := "then paste the code above." + g := serviceGroup{} + for _, group := range m.serviceGroups() { + if group.Extension == m.Provider { + g = group + } + } + switch { + case m.reSignIn != "": + note += " It keeps its place in the rotation." + case len(g.Accounts) > 0: + note += fmt.Sprintf(" It joins the rotation as #%d.", len(g.Accounts)+1) + } + return append(lines, paneNote(note, width)...) +} + +// accountsHints are the keys for the highlighted row of the accounts list. +func (m LoginModel) accountsHints(width int) []hint { + if m.signingInline() { + if m.signInOver() { + return []hint{{"enter", "try again"}, {"esc", "back"}} + } + return []hint{{"enter", "submit code"}, {"ctrl+o", "open browser again"}, {"esc", "cancel sign-in"}} + } + row, ok := m.ChoosePicker.highlighted() + if !ok { + return []hint{{"↑↓", "move"}, {"esc", "back"}} + } + id, isAccount := strings.CutPrefix(row.key, rowAccount) + if !isAccount { + verb := "sign in" + switch row.key { + case rowKeys: + verb = "choose" + case rowAdvanced: + verb = "open" + } + return []hint{{"↑↓", "move"}, {"enter", verb}, {"esc", "back"}} + } + a, _ := m.accountByID(id) + if a.Source == "env" { + return []hint{{"↑↓", "move"}, {"esc", "back"}} + } + if a.NeedsSignIn { + return []hint{{"enter", "sign in again"}, {"↑↓", "move"}, {"ctrl+x", "sign out"}, {"esc", "back"}} + } + hints := []hint{{"↑↓", "move"}} + if g, ok := m.groupOf(a); ok && g.rotates() { + hints = append(hints, hint{"tab", "rotation"}, hint{"alt+↑↓", "order"}) + } + if width >= 100 { + hints = append(hints, hint{"ctrl+r", "rename"}) + } + return append(hints, hint{"ctrl+x", "sign out"}, hint{"esc", "back"}) +} + +// accountsFooter is the list's keys with the status or error beside them, +// or the sign-out question. +func (m LoginModel) accountsFooter(width int) string { + if m.Step == StepRemove { + return m.signOutFooter(width) + } + if m.Step == StepSaving { + return statusRows(width, DefaultStyles.Faint.Render(cmp.Or(m.listBusy, "saving…"))) + } + if m.accountsEmpty() { + hints := []hint{{"↑↓", "move"}, {"enter", "sign in"}, {"esc", "later"}} + if m.Error != "" { + return footerLine(width, hints, DefaultStyles.Error.Render(m.Error), true) + } + return footerLine(width, hints, "", false) + } + hints := m.accountsHints(width) + if m.Error != "" { + return footerLine(width, hints, DefaultStyles.Error.Render(m.Error), true) + } + status := m.Status + if m.signingInline() { + status = "" + } + if status != "" { + return footerLine(width, hints, DefaultStyles.Faint.Render(status), true) + } + return footerLine(width, hints, "", false) +} + +// signOutFooter asks before signing out, saying what keeps running or +// stops: the question and its consequence on one row when they fit. +func (m LoginModel) signOutFooter(width int) string { + if m.Removing.Kind != "account" { + return m.confirm.footer(width, m.Error) + } + question := " Sign out " + m.Removing.Label + "? " + consequence := m.prompt + style := DefaultStyles.Muted + if a, ok := m.accountByID(m.Removing.ID); ok && m.lastOfService(a) { + style = DefaultStyles.Warning + } + var rows []string + if ansi.StringWidth(question+consequence) <= width-1 { + rows = append(rows, DefaultStyles.Bold.Render(question)+style.Render(consequence)) + } else { + rows = append(rows, DefaultStyles.Bold.Render(ansi.Truncate(question, width-1, "…"))) + for line := range strings.SplitSeq(ansi.Wrap(consequence, max(1, width-2), " "), "\n") { + rows = append(rows, " "+style.Render(line)) + } + } + verb := "sign out" + if m.Error != "" { + rows = append(rows, " "+DefaultStyles.Error.Render(ansi.Truncate(m.Error, max(1, width-1), "…"))) + verb = "retry" + } + return strings.Join(append(rows, " "+keyHints(hint{"enter", verb}, hint{"esc", "keep"})), "\n") +} + +// accountsKey handles the accounts list's own keys and reports whether it +// took the key; the rest move and filter the list. +func (m *LoginModel) accountsKey(msg tea.KeyPressMsg) (bool, tea.Cmd) { + key := msg.String() + row, ok := m.ChoosePicker.highlighted() + if !ok { + return false, nil + } + id, isAccount := strings.CutPrefix(row.key, rowAccount) + account, known := m.accountByID(id) + switch key { + case "tab", "alt+up", "alt+down", "ctrl+r", "ctrl+x", "ctrl+d": + default: + return false, nil + } + if !isAccount || !known { + return true, nil + } + if account.Source == "env" { + m.Error = "" + m.Status = "environment accounts are read from the daemon's environment; change them there" + return true, nil + } + switch key { + case "ctrl+r": + return true, m.askAccountRename(account) + case "ctrl+x", "ctrl+d": + return true, m.confirmRemoval(removal{Kind: "account", Provider: account.Provider, ID: account.ID, Label: account.Label}) + } + g, grouped := m.groupOf(account) + if !grouped || !g.rotates() { + return true, nil + } + order := make([]string, len(g.Accounts)) + for i, a := range g.Accounts { + order[i] = a.ID + } + mode := g.Mode + switch key { + case "tab": + mode = nextRotation(g.Mode) + case "alt+up", "alt+down": + at := slices.Index(order, account.ID) + to := at - 1 + if key == "alt+down" { + to = at + 1 + } + if to < 0 || to >= len(order) { + return true, nil + } + order[at], order[to] = order[to], order[at] + } + return true, m.saveRotation(g, order, mode) +} + +// saveRotation shows a service's new order and mode at once and writes it +// to every profile of the service, then re-reads what the daemon holds. +func (m *LoginModel) saveRotation(g serviceGroup, order []string, mode string) tea.Cmd { + before := m.Profiles + targets := daemon.RotationTargets(g.Extension, before) + if len(targets) == 0 { + m.Error = "" + m.Status = "nothing runs " + g.Label + " yet, so there is no order to keep; sign in again or add a setup under advanced" + return nil + } + providers := maps.Clone(before.Providers) + for _, name := range targets { + s := providers[name] + s.AccountIDs, s.Rotation, s.AccountID = slices.Clone(order), mode, nil + providers[name] = s + } + m.Profiles.Providers = providers + m.Error, m.Status = "", "" + label, detail := rotationMode(mode) + m.rotationNote = g.Label + ": " + label + ". " + detail + m.listBusy = "saving " + g.Label + "'s rotation…" + m.buildChoosePicker() + m.Step = StepSaving + conn, extension := m.Conn, g.Extension + return m.reloadCmd(func(ctx context.Context) error { + _, err := daemon.SaveServiceRotation(ctx, conn, extension, before, order, mode) + return err + }) +} + +// chooseAccountsRow runs enter on a row of the accounts list. +func (m *LoginModel) chooseAccountsRow(id string) tea.Cmd { + m.Error = "" + switch { + case id == rowAdvanced: + m.advanced = true + m.Status = "" + return m.backToChoose() + case id == rowKeys: + return m.chooseKeyProvider() + case strings.HasPrefix(id, rowAdd), strings.HasPrefix(id, rowMore), strings.HasPrefix(id, rowTool): + provider := id[strings.IndexByte(id, ':')+1:] + return m.signInInline(provider, "") + case strings.HasPrefix(id, rowAccount): + if a, ok := m.accountByID(strings.TrimPrefix(id, rowAccount)); ok && a.NeedsSignIn { + return m.signInInline(a.Provider, a.ID) + } + } + return nil +} + +// signInInline starts a sign-in that runs on the accounts list: the row +// waits in its section and the search line takes the code. accountID names +// the account it signs in again, or is empty for a new one. +func (m *LoginModel) signInInline(provider, accountID string) tea.Cmd { + login, ok := m.signInFor(provider) + if !ok { + label, _ := m.serviceName(provider) + m.Error = "the daemon does not offer a " + label + " sign-in right now" + return nil + } + m.inline, m.reSignIn = true, accountID + m.Status = "" + return m.startSignIn(login) +} + +// endInline leaves an inline sign-in for the list, keeping the account it +// was about highlighted. +func (m *LoginModel) endInline() tea.Cmd { + if m.reSignIn != "" { + m.focus = rowAccount + m.reSignIn + } else { + m.focus = rowAdd + m.Provider + } + m.inline, m.reSignIn = false, "" + return m.backToChoose() +} + +// signedIn returns to the list after an inline sign-in brought an account +// back, highlighting it and saying where it went, and re-reads the list so +// the setups the daemon updated show. +func (m *LoginModel) signedIn(account daemon.Account) tea.Cmd { + again := m.reSignIn != "" + m.inline, m.reSignIn = false, "" + m.focus = rowAccount + account.ID + m.Error = "" + label, _ := m.serviceName(account.Provider) + m.Status = "Signed in to " + label + " as " + account.Label + "." + if g, ok := m.groupOf(account); ok && g.rotates() { + place := slices.IndexFunc(g.Accounts, func(a daemon.Account) bool { return a.ID == account.ID }) + 1 + if again { + m.Status = fmt.Sprintf("Signed in again as %s; it keeps its place as #%d.", account.Label, place) + } else { + m.Status = fmt.Sprintf("Signed in as %s. It joins %s as #%d.", account.Label, label, place) + } + } + back := m.backToChoose() + gen := m.Generation + return tea.Batch(back, func() tea.Msg { return m.listSignIns(m.readCtx, gen) }) +} + +// chooseKeyProvider lists the providers an API key or endpoint can be set +// up for. +func (m *LoginModel) chooseKeyProvider() tea.Cmd { + items := make([]loginItem, 0, len(customProviders)) + for _, p := range customProviders { + items = append(items, loginItem{ID: p.ID, Label: p.Label, Detail: p.Detail, facts: p.facts(), note: "enter names the setup, then asks for its endpoint and key"}) + } + m.Step = StepAddKey + m.ChoosePicker = newLoginPick("API key or endpoint", items, "", m.Width, m.Height) + return m.ChoosePicker.Init() +} + +// firstRunRows are the first run's choices: the sign-in services the daemon +// offers, then everything else. +func (m LoginModel) firstRunRows() []accountService { + var rows []accountService + for _, s := range accountServices { + if _, ok := m.signInFor(s.Extension); ok { + rows = append(rows, s) + } + } + return append(rows, accountService{Extension: rowKeys, Label: "Other…", Blurb: "API keys, OpenRouter, Bedrock, any compatible endpoint"}) +} + +// firstRunKey moves through and picks from the first run's choices. +func (m *LoginModel) firstRunKey(msg tea.KeyPressMsg) tea.Cmd { + rows := m.firstRunRows() + switch msg.String() { + case "up", "ctrl+p": + m.firstCursor = max(0, m.firstCursor-1) + case "down", "ctrl+n": + m.firstCursor = min(len(rows)-1, m.firstCursor+1) + case "enter": + row := rows[min(m.firstCursor, len(rows)-1)] + if row.Extension == rowKeys { + return m.chooseKeyProvider() + } + return m.signInInline(row.Extension, "") + case "esc", "ctrl+c": + return func() tea.Msg { return LoginCancelMsg{} } + } + return nil +} + +// firstRunList is the first run in the list's place: a line on what works, +// the sign-ins, and a note on adding more. +func (m LoginModel) firstRunList(width, _ int) []string { + width = max(1, width-1) + lines := []string{"", " " + DefaultStyles.Bold.Render("Sign in to start. Your subscription works; no API key needed."), ""} + for i, row := range m.firstRunRows() { + detail := row.Blurb + if row.Plans != "" { + detail = row.Plans + " · " + row.Blurb + } + name := svCell(row.Label, 12, false) + if i == m.firstCursor { + line := selectBar() + " " + DefaultStyles.Prompt.Render("› ") + DefaultStyles.Bold.Render(name) + DefaultStyles.Muted.Render(ansi.Truncate(detail, max(1, width-17), "…")) + lines = append(lines, selectedLine(line, width)) + continue + } + lines = append(lines, " "+name+DefaultStyles.Muted.Render(ansi.Truncate(detail, max(1, width-17), "…"))) + } + lines = append(lines, "", "") + for _, l := range svWrap("Add more accounts later; albedo switches between them when one hits a limit.", max(1, width-4), 3) { + lines = append(lines, " "+DefaultStyles.Faint.Render(l)) + } + return inset(lines) +} diff --git a/cli/internal/tui/app_commands.go b/cli/internal/tui/app_commands.go index 5e31e306c..64139baa3 100644 --- a/cli/internal/tui/app_commands.go +++ b/cli/internal/tui/app_commands.go @@ -389,7 +389,7 @@ func (m *AppModel) handleCommandInvocation(msg tea.Msg) (tea.Cmd, bool) { return tea.Batch(commands...), true } switch msg.Name { - case "/login": + case "/login", "/accounts": return m.openLogin(msg.Args), true case "/model": if msg.Args != "" { diff --git a/cli/internal/tui/chat_input.go b/cli/internal/tui/chat_input.go index 28c461efc..dd28ce848 100644 --- a/cli/internal/tui/chat_input.go +++ b/cli/internal/tui/chat_input.go @@ -402,7 +402,7 @@ func (m *ChatModel) isRecognizedCommand(input string) bool { switch token { case "/a", "/agents", "/sessions", "/q", "/quit", "/exit", "/new", "/model", "/extensions", "/plugins", "/tree", "/fork", "/btw", "/quota", "/usage", "/context", "/t", "/thinking", "/v", "/verbose", - "/status", "/login", "/mouse", "/skills", "/instructions", "/mcp", "/cd", "/effort", "/compact", "/kernel", "/reload", + "/status", "/login", "/accounts", "/mouse", "/skills", "/instructions", "/mcp", "/cd", "/effort", "/compact", "/kernel", "/reload", "/work", "/paperclips", "/webhooks", "/discord", "/config", "/settings": return true } @@ -605,8 +605,10 @@ func (m *ChatModel) handleSubmittedCommand(input string, cmds *[]tea.Cmd) { switch { case strings.HasPrefix(trimmed, "/model "): emit(ChatExecuteCommandMsg{Name: "/model", Args: strings.TrimSpace(trimmed[7:])}) - case strings.HasPrefix(trimmed, "/login"): + case trimmed == "/login" || strings.HasPrefix(trimmed, "/login "): emit(ChatOpenLoginMsg{Name: strings.TrimSpace(strings.TrimPrefix(trimmed, "/login"))}) + case trimmed == "/accounts" || strings.HasPrefix(trimmed, "/accounts "): + emit(ChatOpenLoginMsg{Name: strings.TrimSpace(strings.TrimPrefix(trimmed, "/accounts"))}) default: for _, cmd := range m.CommandMenu.Catalog { if cmd.Name == trimmed && cmd.Page != nil && *cmd.Page { diff --git a/cli/internal/tui/commands.go b/cli/internal/tui/commands.go index dafc7a22f..7b6ad30bd 100644 --- a/cli/internal/tui/commands.go +++ b/cli/internal/tui/commands.go @@ -37,7 +37,8 @@ var AppCommands = []ChatCommand{ {Name: "/kernel", Description: "upgrade or restart the session kernel"}, {Name: "/model", Description: "choose a model"}, {Name: "/context", Description: "inspect prepared context"}, - {Name: "/login", Description: "add or select a model provider"}, + {Name: "/accounts", Description: "sign in to Claude, ChatGPT, Gemini or a key; rotation and sign-out"}, + {Name: "/login", Description: "same as /accounts"}, {Name: "/new", Description: "start a new coding session"}, {Name: "/sessions", Description: "switch to another session"}, {Name: "/agents", Description: "watch and message this session's agents (ctrl+o)"}, diff --git a/cli/internal/tui/list_view.go b/cli/internal/tui/list_view.go index 0328f4538..fa24e6167 100644 --- a/cli/internal/tui/list_view.go +++ b/cli/internal/tui/list_view.go @@ -45,9 +45,11 @@ type listView struct { // Empty is said when there are no rows at all. Empty string groupTitle func(group string, width int) string - input textinput.Model - Cursor int - height int + // sectionTitle draws a section's rule in place of sectionRule. + sectionTitle func(section string, width int) string + input textinput.Model + Cursor int + height int } // newFilter is a focused search field. @@ -273,7 +275,11 @@ func (l listView) list(width, height int) []string { if !newGroup && len(all) > 0 && height >= 10 { all = append(all, line{shown: -1}) } - all = append(all, line{text: sectionRule(r.section, run, width), shown: -1}) + rule := sectionRule(r.section, run, width) + if l.sectionTitle != nil { + rule = l.sectionTitle(r.section, width) + } + all = append(all, line{text: rule, shown: -1}) } if i == l.Cursor { selectedAt = len(all) diff --git a/cli/internal/tui/login.go b/cli/internal/tui/login.go index 4e7f8e103..985a8cd15 100644 --- a/cli/internal/tui/login.go +++ b/cli/internal/tui/login.go @@ -39,13 +39,18 @@ const ( StepRename StepCredential StepRotationPrompt + // StepAdvanced lists the named setups (profiles) behind the accounts, + // with today's edit, rename, pin and remove actions. + StepAdvanced + // StepAddKey lists the providers an API key or endpoint is set up for. + StepAddKey ) // signInPollInterval is how often the daemon is asked about a running sign-in. const signInPollInterval = 300 * time.Millisecond -// removal names something /login can delete: a provider in config.json or an -// account in the daemon's credential store. +// removal names something /accounts can delete: an account in the daemon's +// credential store (signing it out), or a setup under advanced. type removal struct { Kind string // "provider" | "account" Provider string @@ -56,7 +61,6 @@ type removal struct { type LoginModel struct { readCtx context.Context cancelReads context.CancelFunc - closed bool Conn *daemon.Connection openBrowser func(url string) Removing removal @@ -86,16 +90,32 @@ type LoginModel struct { ModelPicker loginPick confirm // terms warns before a sign-in in termsLogin starts. - terms *termsBox - termsLogin daemon.SignIn - Generation int - Width int - Height int - Step LoginStep + terms *termsBox + termsLogin daemon.SignIn + RenameAccountID string + // reSignIn is the account an inline sign-in signs in again. + reSignIn string + // focus is the row the next rebuild of the accounts list highlights. + focus string + // listBusy is what the accounts list says while a change it made is + // saved; rotationNote is what it says once that change is saved. + listBusy, rotationNote string + Generation int + Width int + Height int + Step LoginStep + firstCursor int // Editing changes the saved profile Name in place: it saves without // making Name the default and comes back to the list. - Editing bool - RenameAccountID string + Editing bool + // loaded is set once the daemon's accounts were read. + loaded bool + // advanced shows the setups list instead of the accounts. + advanced bool + // inline is a sign-in started from the accounts list, which stays on + // screen while it runs. + inline bool + closed bool } // NewLoginModel panics if conn is nil. A nil browser opener disables automatic @@ -135,29 +155,42 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { return m, nil } if msg.Loaded { + if !m.loaded && m.focus == "" { + // The rows before the first read are placeholders; the + // cursor starts on the first account instead. + m.ChoosePicker = loginPick{} + } m.SignIns = msg.Listed.Logins m.Accounts = msg.Listed.Accounts + m.loaded = true } if msg.Profiles != nil { m.Profiles = *msg.Profiles } if m.Step == StepSaving { - removed := m.Removing - m.Removing = removal{} + removed, note := m.Removing, m.rotationNote + m.Removing, m.rotationNote = removal{}, "" m.Error, m.Status = "", "" - if msg.Err != nil { - m.Error = m.refusalError(removed, msg.Err) + switch { + case msg.Err != nil: + m.Error = msg.Err.Error() + case removed.Kind == "account": + m.Status = "Signed out " + removed.Label + "." + case note != "": + m.Status = note } return m, m.backToChoose() } if msg.Err != nil && m.Error == "" { m.Error = msg.Err.Error() } - m.buildChoosePicker() + if m.Step == StepChoose || m.Step == StepAdvanced || m.signingInline() { + m.buildChoosePicker() + } if m.Hint != "" { return m, m.applyHint() } - if m.Step != StepChoose { + if m.Step != StepChoose && m.Step != StepAdvanced { return m, nil } return m, m.ChoosePicker.Init() @@ -174,6 +207,9 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { m.LoginETag = msg.ETag if msg.Err != nil { m.Error = operationError(msg.Err, "", "Sign-in may have started; check your accounts before starting another. Its outcome cannot be confirmed from this response.") + if m.inline { + m.buildChoosePicker() + } if msg.ID == "" { return m, nil } @@ -182,6 +218,9 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { m.LoginID = msg.ID m.SignInURL = msg.URL m.Status = "" + if m.inline { + m.buildChoosePicker() + } cmds := []tea.Cmd{textinput.Blink} if msg.URL != "" { @@ -210,7 +249,11 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { if msg.Err != nil { m.Error = msg.Err.Error() if api, ok := errors.AsType[*daemon.APIError](msg.Err); ok && (api.StatusCode == 404 || api.StatusCode == 410) { - return m, m.endSignIn() + end := m.endSignIn() + if m.inline { + return m, tea.Batch(end, m.endInline()) + } + return m, end } return m, signInPollTickCmd(msg.ID, m.Generation) } @@ -222,6 +265,9 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { browser = m.openBrowserCmd(msg.URL) } m.Status = msg.Message + if m.inline { + m.buildChoosePicker() + } switch msg.State { case "complete": m.LoginID = "" @@ -232,6 +278,13 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { m.Accounts = append(m.Accounts, account) } } + if m.inline { + if len(msg.Accounts) > 0 { + return m, m.signedIn(msg.Accounts[0]) + } + m.Status = "Signed in." + return m, m.endInline() + } if login, ok := m.signInFor(m.Provider); (ok && login.Kind == "service") || (len(msg.Accounts) > 0 && msg.Accounts[0].Kind == "service") { label := m.Provider if ok && login.Label != "" { @@ -247,7 +300,11 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { return m, m.credentialChosen() case "failed", "cancelled", "expired": m.LoginID = "" - m.Error = msg.Message + m.Error = cmp.Or(msg.Message, "the sign-in "+msg.State) + if m.inline { + m.Status = "" + return m, m.endInline() + } return m, nil default: return m, tea.Batch(browser, signInPollTickCmd(msg.ID, m.Generation)) @@ -298,6 +355,28 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { switch { case m.terms != nil: return m, m.termsKey(msg) + case m.Step == StepSaving && m.listBusy != "": + // The list waits for its change; only leaving is possible. + if key != "esc" && key != "ctrl+c" { + return m, nil + } + case m.Step == StepChoose && m.accountsEmpty(): + return m, m.firstRunKey(msg) + case m.Step == StepChoose: + if took, cmd := m.accountsKey(msg); took { + return m, cmd + } + case m.signingInline() && (key == "esc" || key == "ctrl+c"): + cancel := m.endSignIn() + m.Error, m.Status = "", "sign-in cancelled" + return m, tea.Batch(cancel, m.endInline()) + case m.signingInline() && key == "ctrl+o": + if m.SignInURL != "" { + return m, m.openBrowserCmd(m.SignInURL) + } + return m, nil + case m.signingInline() && (key == "up" || key == "down"): + return m, nil case m.Step == StepRotationPrompt: if key == "esc" || key == "ctrl+c" { return m, m.rotationAnswer(false) @@ -309,17 +388,13 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { return m, m.ChoosePicker.update(msg) case m.Step == StepRemove: return m, m.confirmKey(msg) - case m.Step == StepChoose && (key == "ctrl+d" || key == "ctrl+x"): + case m.Step == StepAdvanced && (key == "ctrl+d" || key == "ctrl+x"): if item, ok := m.ChoosePicker.Highlighted(); ok { if account, accountOK := m.accountAt(item.ID); accountOK { if account.Source == "env" { m.Status = "environment accounts are read-only and cannot be removed" return m, nil } - if refusal := m.removalRefusal(account); refusal != "" { - m.Error, m.Status = "", refusal - return m, nil - } } if target, ok := m.removalFor(item.ID); ok { return m, m.confirmRemoval(target) @@ -331,7 +406,7 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { return m, m.toggleCredentialTick() } return m, m.saveCredentialSelection() - case m.Step == StepChoose && (key == "ctrl+r" || key == "ctrl+e"): + case m.Step == StepAdvanced && (key == "ctrl+r" || key == "ctrl+e"): if item, ok := m.ChoosePicker.Highlighted(); ok { if account, accountOK := m.accountAt(item.ID); accountOK { if account.Source == "env" { @@ -358,7 +433,17 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { return m, m.backToChoose() } if key == "esc" || key == "ctrl+c" || key == "ctrl+d" { - pickerStep := m.Step == StepChoose || m.Step == StepAccountProfile || m.Step == StepCredential || m.Step == StepOAuthFlow || m.Step == StepProtocol || m.Step == StepModels || m.Step == StepOAuthModels + pickerStep := m.Step == StepChoose || m.Step == StepAdvanced || m.Step == StepAddKey || m.Step == StepAccountProfile || m.Step == StepCredential || m.Step == StepOAuthFlow || m.Step == StepProtocol || m.Step == StepModels || m.Step == StepOAuthModels + if key == "esc" && !pickerStep && m.Step != StepSaving { + // A question goes back to the list it started from. + cancel := m.endSignIn() + m.LoginValues, m.LoginFields = nil, nil + m.TextInput.SetValue("") + m.Generation = nextPageGeneration() + m.Error = "" + m.inline, m.reSignIn = false, "" + return m, tea.Batch(cancel, m.backToChoose()) + } if !pickerStep || key == "ctrl+d" { cancel := m.Close() m.LoginValues = nil @@ -391,6 +476,12 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { case StepCredential: return m, m.chooseCredentialRow(msg.ID) case StepChoose: + return m, m.chooseAccountsRow(msg.ID) + case StepAddKey: + if p, ok := customProviderByID(msg.ID); ok { + return m, m.startCustomProvider(p) + } + case StepAdvanced: if p, ok := customProviderByID(msg.ID); ok { return m, m.startCustomProvider(p) } @@ -432,7 +523,12 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { case PickerCancelMsg: switch m.Step { - case StepOAuthFlow, StepOAuthFields, StepAccountProfile, StepCredential: + case StepOAuthFlow, StepOAuthFields, StepAccountProfile, StepCredential, StepAddKey: + m.inline, m.reSignIn = false, "" + return m, m.backToChoose() + case StepAdvanced: + m.advanced = false + m.focus = rowAdvanced return m, m.backToChoose() case StepChoose, StepOAuthModels: return m, func() tea.Msg { return LoginCancelMsg{} } @@ -462,7 +558,7 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { } switch m.Step { - case StepChoose, StepAccountProfile, StepCredential, StepOAuthFlow, StepProtocol, StepModels, StepOAuthModels: + case StepChoose, StepAdvanced, StepAddKey, StepAccountProfile, StepCredential, StepOAuthFlow, StepProtocol, StepModels, StepOAuthModels: return m, m.pickUpdate(msg) } @@ -597,7 +693,7 @@ func (m LoginModel) Update(msg tea.Msg) (LoginModel, tea.Cmd) { } type keyAccountSavedMsg struct { - Gen int - Account daemon.Account Err error + Account daemon.Account + Gen int } diff --git a/cli/internal/tui/login_accounts.go b/cli/internal/tui/login_accounts.go index 2aa1f6369..5ec89aee9 100644 --- a/cli/internal/tui/login_accounts.go +++ b/cli/internal/tui/login_accounts.go @@ -6,7 +6,6 @@ import ( "cmp" "context" "encoding/json" - "errors" "fmt" "maps" "slices" @@ -49,19 +48,20 @@ func (m LoginModel) accountAt(id string) (daemon.Account, bool) { return m.Accounts[index], true } -// The rules the accounts picker groups its rows under. +// The rules the advanced setups list groups its rows under. const ( - sectionProviders = "providers" + sectionProviders = "setups" sectionAccounts = "accounts" - sectionNew = "new profile" + sectionNew = "new setup" sectionSignIn = "sign in" ) -// buildChoosePicker lists everything /login can do: the profiles new sessions -// can use, the accounts the daemon holds, the kinds of profile it can make, -// whether they sign in or take a key, and the service sign-ins tools use. The -// rules say which is which, so enter can mean one thing per section. -func (m *LoginModel) buildChoosePicker() { +// buildAdvancedPicker lists the setups behind the accounts: the profiles new +// sessions can use, the accounts the daemon holds (to pin one to a setup), +// the kinds of setup it can make, whether they sign in or take a key, and +// the service sign-ins tools use. The rules say which is which, so enter +// can mean one thing per section. +func (m *LoginModel) buildAdvancedPicker() { var items []loginItem for _, name := range slices.Sorted(maps.Keys(m.Profiles.Providers)) { settings := m.Profiles.Providers[name] @@ -119,7 +119,7 @@ func (m *LoginModel) buildChoosePicker() { ID: "signin:" + login.Provider, Label: login.Label, Detail: detail, section: sectionNew, lead: DefaultStyles.Muted.Render("+"), facts: append(signInFacts(login, accounts), loginFact{"auth", "one signed-in account, or a rotation of them"}), - note: "enter names a new profile, then picks the account it signs in with", + note: "enter names a new setup, then picks the account it signs in with", }) } for _, p := range customProviders { @@ -127,11 +127,15 @@ func (m *LoginModel) buildChoosePicker() { ID: p.ID, Label: p.Label, Detail: p.Detail, section: sectionNew, lead: DefaultStyles.Muted.Render("+"), facts: p.facts(), - note: "enter names a new profile, or updates the one you name", + note: "enter names a new setup, or updates the one you name", }) } items = append(items, services...) - m.ChoosePicker = newLoginPick("", items, "use:"+m.Profiles.Active, m.Width, m.Height) + initial := "use:" + m.Profiles.Active + if row, ok := m.ChoosePicker.highlighted(); ok && slices.ContainsFunc(items, func(item loginItem) bool { return item.ID == row.key }) { + initial = row.key + } + m.ChoosePicker = newLoginPick("", items, initial, m.Width, m.Height) } // profileDetail is a profile's one-line summary: what it runs and how it @@ -292,59 +296,21 @@ func (m LoginModel) removalFor(id string) (removal, bool) { return removal{}, false } -// removalRefusal says why the daemon would refuse to remove an account, or -// is empty when it would not: a profile pins it, or it is the last account a -// rotation has. -func (m LoginModel) removalRefusal(account daemon.Account) string { - if pinned := account.SelectedByProfiles; len(pinned) > 0 { - return fmt.Sprintf("%s is still used by %s; give %s another account first with ctrl+e on the profile", account.Label, strings.Join(pinned, ", "), itOrThem(pinned)) - } - var last []string - for _, name := range account.RotatedByProfiles { - if len(m.Profiles.Providers[name].AccountIDs) <= 1 { - last = append(last, name) - } - } - if len(last) > 0 { - return fmt.Sprintf("%s is the last account %s rotates; give %s another account first with ctrl+e on the profile", account.Label, strings.Join(last, ", "), itOrThem(last)) - } - return "" -} - -// refusalError is what a failed change says: for an account the daemon -// would not remove, which profiles hold it, read from the list re-read after. -func (m LoginModel) refusalError(removed removal, err error) string { - if api, ok := errors.AsType[*daemon.APIError](err); ok && api.Code == "account_in_use" && removed.Kind == "account" { - if i := slices.IndexFunc(m.Accounts, func(a daemon.Account) bool { return a.ID == removed.ID }); i >= 0 { - if refusal := m.removalRefusal(m.Accounts[i]); refusal != "" { - return refusal - } - } - } - return err.Error() -} - -// itOrThem is the pronoun for a list of profiles. -func itOrThem(names []string) string { - if len(names) == 1 { - return "it" - } - return "them" -} - +// confirmRemoval asks before signing an account out, saying what keeps +// running or stops, or before removing a setup under advanced. func (m *LoginModel) confirmRemoval(target removal) tea.Cmd { - detail := "This removes the provider and its saved key" + m.Removing = target + m.Step = StepRemove + m.Error = "" if target.Kind == "account" { - detail = "This removes its saved credential" - for _, a := range m.Accounts { - if a.ID == target.ID && len(a.RotatedByProfiles) > 0 { - detail += "; it leaves rotations " + strings.Join(a.RotatedByProfiles, ", ") - } + consequence := "" + if account, ok := m.accountByID(target.ID); ok { + consequence = m.signOutConsequence(account) } + m.confirm.ask("sign out", target.ID, "sign out", consequence) + return nil } - m.Removing = target - m.Step = StepRemove - m.confirm.ask("remove", target.ID, "remove", detail+". Remove "+target.Kind+" "+target.Label+"?") + m.confirm.ask("remove", target.ID, "remove", "This removes the setup and its saved key; accounts stay signed in. Remove setup "+target.Label+"?") return nil } @@ -447,8 +413,14 @@ func providerProtocol(provider string) string { return "responses" } +// backToChoose returns to the list the screen started from: the accounts, +// or the setups under advanced. func (m *LoginModel) backToChoose() tea.Cmd { m.Step = StepChoose + if m.advanced { + m.Step = StepAdvanced + } + m.listBusy = "" m.RenameAccountID = "" m.CredentialTicks = nil m.Editing = false @@ -500,6 +472,7 @@ func (m *LoginModel) termsKey(msg tea.KeyPressMsg) tea.Cmd { if proceed { return m.beginSignIn(login) } + m.inline, m.reSignIn = false, "" return nil } @@ -515,6 +488,15 @@ func (m *LoginModel) beginSignIn(login daemon.SignIn) tea.Cmd { m.LoginETag = "" m.SignInURL = "" m.Error = "" + if len(login.Flows) > 1 && m.inline { + // An inline sign-in asks nothing: the browser flow also takes a + // pasted code, so it serves another machine too. + m.LoginFlow = login.Flows[0] + if slices.Contains(login.Flows, "browser") { + m.LoginFlow = "browser" + } + return m.nextLoginField() + } if len(login.Flows) > 1 { m.Step = StepOAuthFlow items := make([]loginItem, 0, len(login.Flows)) @@ -570,6 +552,9 @@ func (m *LoginModel) beginLoginCmd() tea.Cmd { m.Status = "starting sign-in…" m.TextInput.Placeholder = "" m.promptInput("", false) + if m.inline { + m.buildChoosePicker() + } conn, provider, flow, gen, lifetime := m.Conn, m.Provider, m.LoginFlow, m.Generation, m.readCtx values := maps.Clone(m.LoginValues) m.LoginValues = nil @@ -692,6 +677,9 @@ func accountLimit(a daemon.Account) string { } func accountLead(a daemon.Account) string { + if a.NeedsSignIn { + return DefaultStyles.Error.Render("✕") + } if accountLimit(a) != "" { return DefaultStyles.Warning.Render("!") } @@ -699,5 +687,8 @@ func accountLead(a daemon.Account) string { } func accountTag(a daemon.Account) string { + if a.NeedsSignIn { + return DefaultStyles.Error.Render("needs sign-in") + } return DefaultStyles.Warning.Render(accountLimit(a)) } diff --git a/cli/internal/tui/login_pick.go b/cli/internal/tui/login_pick.go index e31a14f56..847e32983 100644 --- a/cli/internal/tui/login_pick.go +++ b/cli/internal/tui/login_pick.go @@ -101,7 +101,7 @@ func (m *LoginModel) pickerFor() *loginPick { // catalog still loading is a question until its models arrive. func (m LoginModel) listing() bool { switch m.Step { - case StepChoose, StepAccountProfile, StepCredential, StepOAuthFlow, StepProtocol: + case StepChoose, StepAdvanced, StepAddKey, StepAccountProfile, StepCredential, StepOAuthFlow, StepProtocol: return true case StepModels, StepOAuthModels: return m.Catalog != nil diff --git a/cli/internal/tui/login_profile.go b/cli/internal/tui/login_profile.go index ab0ee8429..96f117212 100644 --- a/cli/internal/tui/login_profile.go +++ b/cli/internal/tui/login_profile.go @@ -369,6 +369,11 @@ func (m LoginModel) acceptRename() (LoginModel, tea.Cmd) { if m.RenameAccountID != "" { id, label := m.RenameAccountID, to m.Step = StepSaving + m.focus = rowAccount + id + if !m.advanced { + m.listBusy = "renaming " + m.Name + "…" + m.buildChoosePicker() + } m.RenameAccountID = "" return m, m.reloadCmd(func(ctx context.Context) error { _, err := daemon.RenameAccount(ctx, m.Conn, id, label); return err }) } diff --git a/cli/internal/tui/login_provider.go b/cli/internal/tui/login_provider.go index d9db71ac2..2c7482fb6 100644 --- a/cli/internal/tui/login_provider.go +++ b/cli/internal/tui/login_provider.go @@ -332,9 +332,11 @@ func (m *LoginModel) applyHint() tea.Cmd { m.Draft = saved return m.useProfile(name, saved) } - if login, ok := m.signInFor(name); ok { - m.Draft = signInDraft(name) - return m.startSignIn(login) + if _, ok := m.signInFor(name); ok { + // Signing in runs on the accounts list, which the daemon joins + // the new account to; no setup question is asked. + m.Name = "" + return m.signInInline(name, "") } return m.askEndpoint() } diff --git a/cli/internal/tui/login_test.go b/cli/internal/tui/login_test.go index f97085f22..804fd85be 100644 --- a/cli/internal/tui/login_test.go +++ b/cli/internal/tui/login_test.go @@ -1,43 +1,78 @@ -// The /login list's state across a change the daemon refuses and a read that -// fails. A real daemon cannot fail one read on cue, so E2E never sees the -// screen drop rows it still holds when only the listing is missing. +// The /accounts list against a fake daemon: what sign-out and the rotation +// keys send, and the list's state across a change the daemon refuses and a +// read that fails. The real daemon cannot fail one read on cue, and the Go +// suite has no sign-in fixture to hold several model accounts, so E2E sees +// neither. package tui import ( "encoding/json" + "io" "net/http" + "reflect" + "slices" "strings" "testing" "albedo/cli/internal/daemon" "albedo/cli/internal/testwire" + "github.com/charmbracelet/x/ansi" + tea "charm.land/bubbletea/v2" ) -// pinnedKeyLogin is /login listing one key account the work profile pins. +// pinnedKeyLogin is the advanced list showing one key account the work +// profile pins. func pinnedKeyLogin(t *testing.T, conn *daemon.Connection) LoginModel { t.Helper() m := loginModel(120, 40) m.Conn = conn loginKeyAccounts(&m) - m.buildChoosePicker() + m.advanced = true + m.backToChoose() return m } -func TestLoginRefusedRemovalKeepsTheAccountListed(t *testing.T) { - endpoint := "https://api.openai.com/v1" +// accountsDaemon is a fake daemon for the fixture accounts: it answers +// reads with them, records each providers patch and deletion, and answers +// a deletion with status. Without listing, every read of /auth fails. +func accountsDaemon(t *testing.T, deleteStatus int, listing bool) (LoginModel, *[]map[string]any, *[]string) { + t.Helper() + var patches []map[string]any + var deleted []string conn := commandTestConnection(t, func(w http.ResponseWriter, r *http.Request) { switch { - case r.Method == http.MethodDelete && r.URL.Path == "/auth/accounts/key-1": + case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/auth/accounts/"): + if deleteStatus != http.StatusNoContent { + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(deleteStatus) + _, _ = w.Write([]byte(`{"code":"account_in_use","detail":"Provider account is referenced by a saved profile."}`)) + return + } + deleted = append(deleted, strings.TrimPrefix(r.URL.Path, "/auth/accounts/")) + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodPatch && r.URL.Path == "/settings": + data, _ := io.ReadAll(r.Body) + var body map[string]any + if err := json.Unmarshal(data, &body); err != nil { + t.Errorf("patch body is not JSON: %s", data) + } + patches = append(patches, body) w.Header().Set("Content-Type", "application/problem+json") w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{"code":"account_in_use","detail":"Provider account is referenced by a saved profile."}`)) + _, _ = w.Write([]byte(`{"code":"stale","detail":"refused by the test"}`)) + case r.URL.Path == "/auth" && !listing: + w.WriteHeader(http.StatusServiceUnavailable) case r.URL.Path == "/auth": - _ = json.NewEncoder(w).Encode(map[string]any{"providers": []any{}, "accounts": []any{map[string]any{ - "id": "key-1", "provider": "openai", "label": "team", "detail": "api.openai.com", "kind": "key", "source": "saved", - "endpoint": endpoint, "limited_until": nil, "selected_by_profiles": []string{"work"}, "rotated_by_profiles": []string{}, - }}}) + accounts := []any{} + for _, a := range accountsFixture() { + if !slices.Contains(deleted, a.ID) { + accounts = append(accounts, map[string]any{"id": a.ID, "provider": a.Provider, "label": a.Label, "detail": "", "kind": a.Kind, "source": a.Source, + "endpoint": nil, "limited_until": nil, "email": a.Email, "plan": a.Plan, "needs_sign_in": false, "selected_by_profiles": []string{}, "rotated_by_profiles": []string{}}) + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"providers": []any{}, "accounts": accounts}) case r.URL.Path == "/settings": _ = json.NewEncoder(w).Encode(testwire.Settings()) default: @@ -45,29 +80,127 @@ func TestLoginRefusedRemovalKeepsTheAccountListed(t *testing.T) { w.WriteHeader(http.StatusNotFound) } }) - m := pinnedKeyLogin(t, conn) - // The listing was read before a profile pinned the key, so the screen - // asks, and the daemon refuses. - focusLoginRow(&m, "account:1") + m := accountsModel(120, 40) + m.Conn = conn + m.Profiles.ETag = `"providers-1"` + return m, &patches, &deleted +} + +// plainView is what the screen shows, without its styling. +func plainView(m LoginModel) string { return ansi.Strip(m.View()) } + +// settleLogin runs cmd and feeds what it returns back to the screen. +func settleLogin(m LoginModel, cmd tea.Cmd) LoginModel { + for cmd != nil { + msg := cmd() + if batch, ok := msg.(tea.BatchMsg); ok { + for _, c := range batch { + m = settleLogin(m, c) + } + return m + } + if msg == nil { + return m + } + m, cmd = m.Update(msg) + } + return m +} + +func TestAccountsSignOutSaysWhatKeepsRunningAndAsksEvenWhenPinned(t *testing.T) { + m, _, deleted := accountsDaemon(t, http.StatusNoContent, true) + m.Accounts[1].SelectedByProfiles = []string{"work"} // pinned: asked anyway + m.buildChoosePicker() + focusLoginRow(&m, "acct:work") + m, _ = pressCtrl(m, 'x') + if m.Step != StepRemove || !strings.Contains(plainView(m), "Sign out work@studio.io? Claude keeps running on mayer@chernobog.") { + t.Fatalf("ctrl+x did not ask with the consequence: step %v\n%s", m.Step, plainView(m)) + } + m, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = settleLogin(m, cmd) + if !reflect.DeepEqual(*deleted, []string{"work"}) || m.Step != StepChoose || m.Status != "Signed out work@studio.io." { + t.Fatalf("enter did not sign out: deleted %v step %v status %q", *deleted, m.Step, m.Status) + } + + // The last account of a service says its models stop; esc keeps it. + m = accountsModel(120, 40) + focusLoginRow(&m, "acct:gpt") m, _ = pressCtrl(m, 'x') - if m.Step != StepRemove { - t.Fatalf("ctrl+x on an unpinned account did not ask: step %v", m.Step) + if !strings.Contains(plainView(m), "ChatGPT models stop working until you sign in again. Sessions keep their history.") { + t.Fatalf("the last account's question does not warn:\n%s", plainView(m)) } + if m, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}); m.Step != StepChoose || m.asking() { + t.Fatalf("esc did not keep the account: step %v", m.Step) + } +} + +func TestAccountsRefusedSignOutKeepsTheAccountListed(t *testing.T) { + m, _, _ := accountsDaemon(t, http.StatusConflict, true) + focusLoginRow(&m, "acct:work") + m, _ = pressCtrl(m, 'x') m.Status = "a line from before the change" m, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) if m.Step != StepSaving || cmd == nil { - t.Fatalf("enter did not remove: step %v", m.Step) + t.Fatalf("enter did not sign out: step %v", m.Step) } + // The re-read lists the account the daemon still holds. m, _ = m.Update(cmd()) + if m.Step != StepChoose || !strings.Contains(m.Error, "referenced by a saved profile") || m.Status != "" { + t.Fatalf("the refusal is not shown: step %v error %q status %q", m.Step, m.Error, m.Status) + } + if !strings.Contains(plainView(m), "work@studio.io") { + t.Fatalf("the refused account is not listed:\n%s", plainView(m)) + } +} - if m.Step != StepChoose || !strings.Contains(m.Error, "still used by work") { - t.Fatalf("the refusal is not shown: step %v error %q", m.Step, m.Error) +// Rotation is per service: tab and alt+↓ write one patch giving every +// unpinned profile of the service the same order and mode. +func TestAccountsRotationKeysWriteTheServiceOrder(t *testing.T) { + m, patches, _ := accountsDaemon(t, http.StatusNoContent, false) + m.Profiles.Providers["claude-team"] = m.Profiles.Providers["codex"] + team := m.Profiles.Providers["claude-team"] + team.Extension, team.AccountIDs = "claude", nil + m.Profiles.Providers["claude-team"] = team + m.buildChoosePicker() + focusLoginRow(&m, "acct:me") + + m, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyTab}) + if !strings.Contains(plainView(m), "Claude 2 · spread evenly") { + t.Fatalf("tab did not show the next mode at once:\n%s", plainView(m)) + } + m = settleLogin(m, cmd) + m, cmd = m.Update(tea.KeyPressMsg{Code: tea.KeyDown, Mod: tea.ModAlt}) + m = settleLogin(m, cmd) + + if len(*patches) != 2 { + t.Fatalf("want one patch per key, got %v", *patches) } - if len(m.Accounts) != 1 || m.Accounts[0].ID != "key-1" || !strings.Contains(m.View(), "team") { - t.Fatalf("the refused account is not listed: %+v\n%s", m.Accounts, m.View()) + tab := (*patches)[0]["profiles"].(map[string]any) + if len(tab) != 2 || !reflect.DeepEqual(tab["claude"], map[string]any{"account_ids": []any{"me", "work"}, "rotation": "spread", "account_id": nil}) || tab["claude-team"] == nil { + t.Fatalf("tab wrote %v", tab) } - if m.Status != "" { - t.Fatalf("the status from before the change stayed: %q", m.Status) + // The re-read failed, so the screen kept the mode it showed. + down := (*patches)[1]["profiles"].(map[string]any)["claude"] + if !reflect.DeepEqual(down, map[string]any{"account_ids": []any{"work", "me"}, "rotation": "spread", "account_id": nil}) { + t.Fatalf("alt+↓ wrote %v", down) + } + if !strings.Contains(m.Error, "refused by the test") { + t.Fatalf("the refused save is not reported: %q", m.Error) + } +} + +func TestAccountsInlineSignInAsksNothingAndEscGoesBack(t *testing.T) { + m := accountsModel(120, 40) + m, _ = m.Update(PickerSelectMsg{ID: "add:claude"}) + if m.Step != StepOAuth || m.LoginFlow != "browser" || !m.signingInline() { + t.Fatalf("adding a Claude account asked a question: step %v flow %q", m.Step, m.LoginFlow) + } + view := plainView(m) + if !strings.Contains(view, "code or callback URL") || !strings.Contains(view, "signing in… finish in your browser") || !strings.Contains(view, "esc cancel sign-in") { + t.Fatalf("the sign-in is not on the list:\n%s", view) + } + if m, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}); m.Step != StepChoose || m.inline || m.Status != "sign-in cancelled" { + t.Fatalf("esc did not cancel back to the list: step %v status %q", m.Step, m.Status) } } @@ -108,35 +241,3 @@ func TestLoginFailedReadKeepsTheRows(t *testing.T) { t.Fatalf("the failed read is not reported: %q", m.Error) } } - -func TestLoginPinnedAccountRemovalSaysWhichProfilesUseIt(t *testing.T) { - m := pinnedKeyLogin(t, &daemon.Connection{}) - m.Accounts[1].SelectedByProfiles = []string{"work", "home"} - m.buildChoosePicker() - focusLoginRow(&m, "account:1") - m, cmd := pressCtrl(m, 'x') - if m.Step != StepChoose || cmd != nil || m.asking() { - t.Fatalf("ctrl+x on a pinned account asked anyway: step %v", m.Step) - } - if !strings.Contains(m.Status, "work, home") || !strings.Contains(m.Status, "ctrl+e") { - t.Fatalf("the refusal does not name the profiles or the way out: %q", m.Status) - } - - // The last account of a rotation is refused the same way; one of two is - // not, and the confirm says which rotation it leaves. - m.Accounts[1].SelectedByProfiles = nil - m.Accounts[1].RotatedByProfiles = []string{"work"} - work := m.Profiles.Providers["work"] - work.AccountID, work.AccountIDs = nil, []string{"key-1"} - m.Profiles.Providers["work"] = work - m.buildChoosePicker() - focusLoginRow(&m, "account:1") - if m, _ = pressCtrl(m, 'd'); m.Step != StepChoose || !strings.Contains(m.Status, "last account work rotates") { - t.Fatalf("removing a rotation's last account was not refused: step %v status %q", m.Step, m.Status) - } - work.AccountIDs = []string{"key-1", "key-2"} - m.Profiles.Providers["work"] = work - if m, _ = pressCtrl(m, 'd'); m.Step != StepRemove { - t.Fatalf("one account of two in a rotation was refused: step %v status %q", m.Step, m.Status) - } -} diff --git a/cli/internal/tui/login_view.go b/cli/internal/tui/login_view.go index 3ddf93b65..9ef883bcd 100644 --- a/cli/internal/tui/login_view.go +++ b/cli/internal/tui/login_view.go @@ -48,7 +48,7 @@ func (m LoginModel) signInOver() bool { // fieldLabel is what the text input is asked for. func (m LoginModel) fieldLabel() string { if m.Step == StepOAuth { - return "callback URL or code" + return "code or callback URL" } label, _ := m.question() return label @@ -92,20 +92,45 @@ func (m LoginModel) View() string { func (m LoginModel) screen() string { width := cmp.Or(m.Width, 80) - title := brand("albedo") + " " + DefaultStyles.Muted.Render("/login") + title := brand("albedo") + " " + DefaultStyles.Muted.Render("/accounts") + if m.advanced { + title += DefaultStyles.Faint.Render(" › ") + DefaultStyles.Muted.Render("advanced") + } right := m.Name - if m.Step == StepChoose || (m.Step == StepRemove || m.Step == StepRotationPrompt) { + onList := m.Step == StepChoose || m.Step == StepAdvanced || m.Step == StepAddKey || m.Step == StepRemove || m.Step == StepRotationPrompt || m.signingInline() || (m.Step == StepSaving && m.listBusy != "") + if onList { right = homePath(config.HomeDir()) } + if m.Step == StepChoose && m.accountsEmpty() { + right = "no accounts yet" + } if right != "" { right = DefaultStyles.Faint.Render(right) } footer := m.footer(width) + if m.Step == StepChoose && m.accountsEmpty() { + return listFrame{title: title, right: right, list: m.firstRunList, footer: footer}.view(m.Width, m.Height) + } + if m.signingInline() { + f := m.accountsFrame(title, right, footer) + if !m.signInOver() { + f.filter = promptLead() + DefaultStyles.Muted.Render(m.fieldLabel()+" ") + m.TextInput.View() + } else { + f.filter = promptLead() + DefaultStyles.Faint.Render("the sign-in did not finish") + } + return f.view(m.Width, m.Height) + } + if m.Step == StepSaving && m.listBusy != "" { + return m.accountsFrame(title, right, footer).view(m.Width, m.Height) + } // A removal question keeps the list it asks about on screen, the way every // other confirm does. if m.listing() || (m.Step == StepRemove || m.Step == StepRotationPrompt) { + if !m.advanced && (m.Step == StepChoose || m.Step == StepRemove) { + return m.accountsFrame(title, right, footer).view(m.Width, m.Height) + } lv := m.pickerFor().listView - lv.Empty = "nothing to choose" + lv.Empty = cmp.Or(lv.Empty, "nothing to choose") return lv.frame(title, right, footer).view(m.Width, m.Height) } f := listFrame{ @@ -118,6 +143,14 @@ func (m LoginModel) screen() string { return f.view(m.Width, m.Height) } +// accountsFrame is the accounts list in the frame, with a pane wide enough +// for an account's facts on one row each. +func (m LoginModel) accountsFrame(title, right, footer string) listFrame { + f := m.ChoosePicker.frame(title, right, footer) + f.paneWidth = func(width int) int { return min(max(width*38/100, 36), 48) } + return f +} + // filterLine is the question's input line; a step that is only waiting on the // daemon takes no input and shows none. func (m LoginModel) filterLine() string { @@ -229,7 +262,7 @@ func (m LoginModel) hints() []hint { if verb := m.enterVerb(); verb != "" { hints = append(hints, hint{"enter", verb}) } - if item, ok := m.ChoosePicker.Highlighted(); ok && m.Step == StepChoose { + if item, ok := m.ChoosePicker.Highlighted(); ok && m.Step == StepAdvanced { if name, ok := m.highlightedProfile(); ok { if m.editable(name) { hints = append(hints, hint{"ctrl+e", "edit"}) @@ -242,7 +275,11 @@ func (m LoginModel) hints() []hint { hints = append(hints, hint{"ctrl+r", "rename"}) } if _, removable := m.removalFor(item.ID); removable && !external { - hints = append(hints, hint{"ctrl+x", "remove"}) + verb := "remove" + if isAccount { + verb = "sign out" + } + hints = append(hints, hint{"ctrl+x", verb}) } } return append(hints, hint{"esc", "back"}) @@ -353,6 +390,12 @@ func (m LoginModel) signInHint() string { // footer is the keys, with an error or the catalog's note beside them. func (m LoginModel) footer(width int) string { + if !m.advanced && (m.Step == StepChoose || m.signingInline() || (m.Step == StepSaving && m.listBusy != "") || (m.Step == StepRemove && m.Removing.Kind == "account")) { + return m.accountsFooter(width) + } + if m.Step == StepRemove && m.Removing.Kind == "account" { + return m.signOutFooter(width) + } if m.Step == StepRotationPrompt { return footerLine(width, []hint{{"↑↓", "choose"}, {"enter", "continue"}, {"esc", "no"}}, DefaultStyles.Warning.Render(m.confirm.prompt), true) } @@ -365,8 +408,8 @@ func (m LoginModel) footer(width int) string { status := "" if m.CatalogNote != "" && (m.Step == StepModels || m.Step == StepOAuthModels) { status = DefaultStyles.Faint.Render(m.CatalogNote) - } else if m.Status != "" && m.Step == StepChoose { + } else if m.Status != "" && (m.Step == StepChoose || m.Step == StepAdvanced) { status = DefaultStyles.Faint.Render(m.Status) } - return footerLine(width, m.hints(), status, m.Status != "" && m.Step == StepChoose) + return footerLine(width, m.hints(), status, m.Status != "" && (m.Step == StepChoose || m.Step == StepAdvanced)) } diff --git a/cli/internal/tui/session_viewer.go b/cli/internal/tui/session_viewer.go index 81474a0a2..6d0be6dda 100644 --- a/cli/internal/tui/session_viewer.go +++ b/cli/internal/tui/session_viewer.go @@ -127,7 +127,7 @@ func NewSessionViewer(workspace string) SessionViewer { func sessionViewerActions(workspace string) []PickerItem { return []PickerItem{ {ID: "new", Label: "New session", Detail: workspace}, - {ID: "login", Label: "Accounts", Detail: "add or select a provider"}, + {ID: "login", Label: "Accounts", Detail: "sign in, rotation, sign-out"}, {ID: "archive", Label: "Archive", Detail: "browse archived sessions"}, } } diff --git a/cli/internal/tui/session_viewer_view.go b/cli/internal/tui/session_viewer_view.go index b93958187..90e0a3884 100644 --- a/cli/internal/tui/session_viewer_view.go +++ b/cli/internal/tui/session_viewer_view.go @@ -357,7 +357,7 @@ func (m SessionViewer) row(item PickerItem, s daemon.Session, sec int, selected case "archive": glyph, title, hint, fg = "▤ ", "Archive", counted(len(m.archivedIDs), "session"), DefaultStyles.Muted case "login": - glyph, title, hint, fg = "◇ ", "Accounts", "providers", DefaultStyles.Muted + glyph, title, hint, fg = "◇ ", "Accounts", "sign-ins", DefaultStyles.Muted } titleWidth := min(ansi.StringWidth(title), cols.title) return fill(bar + st(fg).Render(glyph) + st(lipgloss.NewStyle()).Render(" ") + @@ -496,7 +496,7 @@ func (m SessionViewer) actionPreview(id string, inner, height int) []string { DefaultStyles.Faint.Render("enter ") + DefaultStyles.Muted.Render("browse")} default: lines = []string{"", "", DefaultStyles.Muted.Bold(true).Render("◇ Accounts"), "", - DefaultStyles.Muted.Render("add a provider, sign in, or pick"), DefaultStyles.Muted.Render("which one new sessions use."), "", + DefaultStyles.Muted.Render("sign in to Claude, ChatGPT, Gemini"), DefaultStyles.Muted.Render("or a key; rotation and sign-out."), "", DefaultStyles.Faint.Render("enter ") + DefaultStyles.Muted.Render("manage")} } for i, l := range lines { diff --git a/cli/internal/tui/shot_accounts_test.go b/cli/internal/tui/shot_accounts_test.go new file mode 100644 index 000000000..af07cd67e --- /dev/null +++ b/cli/internal/tui/shot_accounts_test.go @@ -0,0 +1,170 @@ +// The /accounts list in every state the design covers, for the shot +// gallery. A plain test run draws each state and writes nothing. +package tui + +import ( + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" + "time" + + tea "charm.land/bubbletea/v2" +) + +func init() { + registerShots("accounts", + shotState{"today", accountsShot(func(m *LoginModel) { + m.Accounts = []daemon.Account{{Provider: "claude", ID: "real", Label: "Claude Pro/Max", Plan: "Max", Kind: "model", Source: "saved"}} + m.Profiles.Providers = map[string]config.Settings{"claude": {Extension: "claude", Model: "claude-opus-4-5", Protocol: "chat_completions"}} + })}, + shotState{"rotating", accountsShot(nil)}, + shotState{"rotating-spread", accountsShot(nil, tea.KeyPressMsg{Code: tea.KeyTab})}, + shotState{"rotating-second", accountsShot(func(m *LoginModel) { focusLoginRow(m, "acct:work") })}, + shotState{"signing-in", accountsShot(func(m *LoginModel) { + m.Accounts = m.Accounts[:1:1] + m.Accounts = append(m.Accounts, accountsFixture()[2]) + startInline(m, "claude", "") + })}, + shotState{"signing-in-new-service", accountsShot(func(m *LoginModel) { startInline(m, "antigravity", "") })}, + shotState{"signing-in-code-typed", accountsShot(func(m *LoginModel) { startInline(m, "claude", "") }, typedKeys("4/0AbCdEf-code")...)}, + shotState{"signing-in-failed", accountsShot(func(m *LoginModel) { + startInline(m, "claude", "") + *m, _ = m.Update(signInStatusMsg{ID: "login-1", Gen: m.Generation, State: "failed", Message: "The sign-in was denied in the browser (access_denied)."}) + })}, + shotState{"signed-in", accountsShot(func(m *LoginModel) { + startInline(m, "claude", "") + added := daemon.Account{Provider: "claude", ID: "new", Label: "ana@valefar.dev", Plan: "Pro", Kind: "model", Source: "saved"} + *m, _ = m.Update(signInStatusMsg{ID: "login-1", Gen: m.Generation, State: "complete", Accounts: []daemon.Account{added}}) + })}, + shotState{"sign-out-confirm", accountsShot(func(m *LoginModel) { focusLoginRow(m, "acct:work") }, tea.KeyPressMsg{Code: 'x', Mod: tea.ModCtrl})}, + shotState{"sign-out-last", accountsShot(func(m *LoginModel) { focusLoginRow(m, "acct:gpt") }, tea.KeyPressMsg{Code: 'x', Mod: tea.ModCtrl})}, + shotState{"sign-out-failed", accountsShot(func(m *LoginModel) { + focusLoginRow(m, "acct:gpt") + *m, _ = pressCtrl(*m, 'x') + m.Error = "daemon connection unavailable" + })}, + shotState{"signing-out", accountsShot(func(m *LoginModel) { + focusLoginRow(m, "acct:work") + *m, _ = pressCtrl(*m, 'x') + m.Step, m.listBusy = StepSaving, "signing out work@studio.io…" + })}, + shotState{"all-limited", accountsShot(func(m *LoginModel) { + m.Accounts[0].LimitedUntil = soon(40 * time.Minute) + })}, + shotState{"needs-sign-in", accountsShot(func(m *LoginModel) { m.Accounts[0].NeedsSignIn = true })}, + shotState{"sign-in-again", accountsShot(func(m *LoginModel) { + m.Accounts[0].NeedsSignIn = true + startInline(m, "claude", "me") + })}, + shotState{"api-keys", accountsShot(func(m *LoginModel) { + or, ms := "https://openrouter.ai/api/v1", "https://api.mistral.ai/v1" + m.Accounts = append(m.Accounts[:1:1], m.Accounts[2], + daemon.Account{Provider: "openai", ID: "or", Label: "openrouter-main", Kind: "key", Source: "saved", Endpoint: &or}, + daemon.Account{Provider: "mistral", ID: "ms", Label: "mistral", Kind: "key", Source: "saved", Endpoint: &ms}, + daemon.Account{Provider: "openai", ID: "env:OPENAI_API_KEY", Label: "$OPENAI_API_KEY", Detail: "api.openai.com", Kind: "key", Source: "env"}, + ) + m.buildChoosePicker() + focusLoginRow(m, "acct:or") + })}, + shotState{"api-key-env", accountsShot(func(m *LoginModel) { + m.Accounts = append(m.Accounts, daemon.Account{Provider: "openai", ID: "env:OPENAI_API_KEY", Label: "$OPENAI_API_KEY", Detail: "api.openai.com", Kind: "key", Source: "env"}) + m.buildChoosePicker() + focusLoginRow(m, "acct:env:OPENAI_API_KEY") + })}, + shotState{"add-row", accountsShot(func(m *LoginModel) { focusLoginRow(m, "add:claude") })}, + shotState{"more-row", accountsShot(func(m *LoginModel) { focusLoginRow(m, "more:antigravity") })}, + shotState{"key-providers", accountsShot(nil, PickerSelectMsg{ID: rowKeys})}, + shotState{"advanced-row", accountsShot(func(m *LoginModel) { focusLoginRow(m, "advanced") })}, + shotState{"advanced-open", accountsShot(func(m *LoginModel) { *m, _ = m.Update(PickerSelectMsg{ID: rowAdvanced}) })}, + shotState{"tool-sign-ins", accountsShot(func(m *LoginModel) { + m.SignIns = append(m.SignIns, daemon.SignIn{Provider: "colab", Label: "Google Colab", Detail: "notebooks for tools", Kind: "service"}) + m.Accounts = append(m.Accounts, daemon.Account{Provider: "colab", ID: "colab-1", Label: "ana@valefar", Kind: "service", Source: "saved"}) + m.buildChoosePicker() + focusLoginRow(m, "acct:colab-1") + })}, + shotState{"filter", accountsShot(nil, typedKeys("studio")...)}, + shotState{"rotation-saved", accountsShot(func(m *LoginModel) { + m.Status = "Claude: spread evenly. Each new session or agent starts on the next account and stays there." + })}, + shotState{"error", accountsShot(func(m *LoginModel) { + m.Error = "daemon refused the change: the settings changed while this screen was open" + })}, + shotState{"first-run", accountsFirstRun(nil)}, + shotState{"first-run-other", accountsFirstRun(func(m *LoginModel) { m.firstCursor = 3 })}, + shotState{"first-run-error", accountsFirstRun(func(m *LoginModel) { m.Error = "daemon connection unavailable" })}, + shotState{"loading", func(width, height int) string { + m := NewLoginModel(&daemon.Connection{}, "", nil) + m.SetSize(width, height) + return m.View() + }}, + ) +} + +func soon(d time.Duration) string { return time.Now().Add(d).Format(time.RFC3339) } + +// accountsFixture is two Claude accounts, the second limited, and one +// ChatGPT account. +func accountsFixture() []daemon.Account { + return []daemon.Account{ + {Provider: "claude", ID: "me", Label: "mayer@chernobog", Email: "mayer@chernobog", Plan: "Max", Kind: "model", Source: "saved", RotatedByProfiles: []string{"claude"}}, + {Provider: "claude", ID: "work", Label: "work@studio.io", Email: "work@studio.io", Plan: "Pro", Kind: "model", Source: "saved", LimitedUntil: soon(2 * time.Hour), RotatedByProfiles: []string{"claude"}}, + {Provider: "codex", ID: "gpt", Label: "regent@hey.com", Plan: "Pro", Kind: "model", Source: "saved"}, + } +} + +// accountsSignIns are the sign-ins the daemon offers in the fixtures. +func accountsSignIns() []daemon.SignIn { + return []daemon.SignIn{ + {Provider: "claude", Label: "Claude", Detail: "console billing or your subscription", Flows: []string{"browser", "manual"}}, + {Provider: "codex", Label: "ChatGPT", Detail: "ChatGPT Plus or Pro", Flows: []string{"browser"}}, + {Provider: "antigravity", Label: "Antigravity", Detail: "Google account", Flows: []string{"browser"}}, + } +} + +// accountsModel is /accounts at a terminal size, listing the fixtures. +func accountsModel(width, height int) LoginModel { + m := NewLoginModel(&daemon.Connection{}, "", nil) + m.SetSize(width, height) + profiles := config.Profiles{Active: "claude", Providers: map[string]config.Settings{ + "claude": {Extension: "claude", Model: "claude-opus-4-5", Protocol: "chat_completions", AccountIDs: []string{"me", "work"}, Rotation: "failover"}, + "codex": {Extension: "codex", Model: "gpt-5-codex", Protocol: "responses"}, + }} + listed := daemon.SignIns{Logins: accountsSignIns(), Accounts: accountsFixture()} + m, _ = m.Update(signInsLoadedMsg{Gen: m.Generation, Loaded: true, Listed: listed, Profiles: &profiles}) + return m +} + +// startInline puts a sign-in in flight on the list, as if the daemon had +// answered with its link. +func startInline(m *LoginModel, provider, account string) { + m.openBrowser = func(string) {} + m.signInInline(provider, account) + *m, _ = m.Update(signInStartedMsg{Gen: m.Generation, ID: "login-1", ETag: `"l1"`, URL: "https://claude.ai/oauth/authorize?code=true&client_id=9d1c250a-e61b-44d9-88ed-5944d1962f5e&response_type=code&state=7f3c"}) +} + +// accountsShot draws /accounts after setup and keys. +func accountsShot(setup func(*LoginModel), keys ...tea.Msg) func(width, height int) string { + return func(width, height int) string { + m := accountsModel(width, height) + if setup != nil { + setup(&m) + m.buildChoosePicker() + } + for _, key := range keys { + m, _ = m.Update(key) + } + return m.View() + } +} + +// accountsFirstRun is /accounts with nothing signed in and no setup. +func accountsFirstRun(setup func(*LoginModel)) func(width, height int) string { + return func(width, height int) string { + m := NewLoginModel(&daemon.Connection{}, "", nil) + m.SetSize(width, height) + m, _ = m.Update(signInsLoadedMsg{Gen: m.Generation, Loaded: true, Listed: daemon.SignIns{Logins: accountsSignIns(), Accounts: []daemon.Account{}}, Profiles: &config.Profiles{Providers: map[string]config.Settings{}}}) + if setup != nil { + setup(&m) + } + return m.View() + } +} diff --git a/cli/internal/tui/shot_login_test.go b/cli/internal/tui/shot_login_test.go index 6bd2a13d2..a134073d5 100644 --- a/cli/internal/tui/shot_login_test.go +++ b/cli/internal/tui/shot_login_test.go @@ -1,5 +1,6 @@ -// The login steps in every state a person sees, for the shot gallery. A plain -// test run draws each state and writes nothing. +// The advanced setups steps of /accounts in every state a person sees, for +// the shot gallery. A plain test run draws each state and writes nothing. +// The accounts list itself is in shot_accounts_test.go. package tui import ( @@ -11,16 +12,13 @@ import ( ) func init() { - registerShots("login", + registerShots("advanced", shotState{"provider-list", loginShot(nil)}, shotState{"provider-filter", loginShot(nil, typedKeys("cla")...)}, shotState{"provider-no-match", loginShot(nil, typedKeys("zzz")...)}, shotState{"provider-remove-ask", loginShot(nil, tea.KeyPressMsg{Code: 'd', Mod: tea.ModCtrl})}, shotState{"provider-remove-stray-key", loginShot(nil, tea.KeyPressMsg{Code: 'd', Mod: tea.ModCtrl}, tea.KeyPressMsg{Code: 'x', Text: "x"})}, shotState{"provider-error", loginShot(func(m *LoginModel) { m.Error = "daemon refused the change" })}, - shotState{"first-run", loginEmpty(func(m *LoginModel) { m.SignIns = nil })}, - shotState{"first-run-sign-in-hint", loginEmpty(nil)}, - shotState{"load-failed", loginEmpty(func(m *LoginModel) { m.Error = "daemon connection unavailable" })}, shotState{"sign-in-flows", loginShot(func(m *LoginModel) { login, _ := m.signInFor("claude") m.startSignIn(login) @@ -245,20 +243,6 @@ func loginModel(width, height int) LoginModel { return m } -// loginEmpty is the first-run login: nothing saved, so it offers provider types. -func loginEmpty(setup func(*LoginModel)) func(width, height int) string { - return func(width, height int) string { - m := NewLoginModel(&daemon.Connection{}, "", nil) - m.SetSize(width, height) - m, _ = m.Update(signInsLoadedMsg{Gen: m.Generation, Loaded: true, Listed: daemon.SignIns{Logins: []daemon.SignIn{{Provider: "claude", Label: "Claude"}}}, Profiles: &config.Profiles{}}) - if setup != nil { - setup(&m) - } - m.buildChoosePicker() - return m.View() - } -} - // enterStep moves the screen to a step the way a real transition does, so its // input is sized for the question it now asks. func (m *LoginModel) enterStep(step LoginStep) { @@ -266,10 +250,12 @@ func (m *LoginModel) enterStep(step LoginStep) { m.SetSize(m.Width, m.Height) } -// loginShot draws the login screen after setup and keys. +// loginShot draws the advanced setups screen after setup and keys. func loginShot(setup func(*LoginModel), keys ...tea.Msg) func(width, height int) string { return func(width, height int) string { m := loginModel(width, height) + m.advanced = true + m.backToChoose() if setup != nil { setup(&m) } diff --git a/cli/internal/tui/terms.go b/cli/internal/tui/terms.go index 8fef1b887..9916b4567 100644 --- a/cli/internal/tui/terms.go +++ b/cli/internal/tui/terms.go @@ -23,7 +23,7 @@ type termsBox struct { } func signInTerms(terms daemon.Terms) *termsBox { - return &termsBox{terms: terms, title: "/login", back: "back", proceed: "sign in anyway"} + return &termsBox{terms: terms, title: "/accounts", back: "back", proceed: "sign in anyway"} } func messageTerms(terms daemon.Terms) *termsBox { diff --git a/cli/test/e2e/tui_login_test.go b/cli/test/e2e/tui_login_test.go index dd9588725..bce0324e4 100644 --- a/cli/test/e2e/tui_login_test.go +++ b/cli/test/e2e/tui_login_test.go @@ -12,7 +12,6 @@ import ( "path/filepath" "reflect" "slices" - "strconv" "strings" "testing" @@ -107,7 +106,7 @@ func TestTUILoginAddsAManualProviderThroughTheDaemon(t *testing.T) { t.Fatalf("saved config: %v", err) } got := profiles.Providers[name] - want := config.Settings{ProfileName: name, Extension: "openai", BaseURL: baseURL, Model: model, Protocol: "chat_completions", HasKey: true} + want := config.Settings{ProfileName: name, Extension: "openai", BaseURL: baseURL, Model: model, Protocol: "chat_completions", Rotation: "failover", HasKey: true} if got.AccountID == nil { t.Fatal("saved key was not pinned") } @@ -144,9 +143,12 @@ func TestTUILoginSavesCloudProviderProfiles(t *testing.T) { } start := func(id, name string) { t.Helper() - d.App.Chat.TextArea.SetValue("/login") + d.App.Chat.TextArea.SetValue("/accounts") d.Dispatch(d.Key(tea.KeyEnter)) expect(tui.StepChoose) + // "API key or endpoint" lists the key providers. + d.Dispatch(tui.PickerSelectMsg{ID: "keys"}) + expect(tui.StepAddKey) d.Dispatch(tui.PickerSelectMsg{ID: id}) expect(tui.StepName) d.App.Login.TextInput.SetValue(name) @@ -219,10 +221,10 @@ func TestTUILoginSavesCloudProviderProfiles(t *testing.T) { } } -// A profile can pin a key after /login read its list. The daemon then refuses -// the removal, and the account must stay on screen as the daemon still holds -// it; asked again, the screen names the profile instead of asking. -func TestTUILoginRefusedRemovalKeepsThePinnedAccount(t *testing.T) { +// Signing out never refuses: a key a setup pins after /accounts read its +// list still signs out, the question says what stops, and the daemon drops +// the pin so the setup goes back to automatic. +func TestTUIAccountsSignsOutAPinnedKey(t *testing.T) { name := "pins-the-key" providerRoute(t, echoReply) t.Setenv("ALBEDO_HOME", suite.home) @@ -231,58 +233,54 @@ func TestTUILoginRefusedRemovalKeepsThePinnedAccount(t *testing.T) { if err != nil { t.Fatalf("save the key account: %v", err) } + removed := false t.Cleanup(func() { + if removed { + return + } if removeErr := daemon.RemoveAccount(context.Background(), connection, account.ID); removeErr != nil { t.Errorf("remove the fixture account: %v", removeErr) } }) preserveLoginState(t, name) d := newTUIDriver(t) - d.App.Chat.TextArea.SetValue("/login") + d.App.Chat.TextArea.SetValue("/accounts") d.Dispatch(d.Key(tea.KeyEnter)) - row := slices.IndexFunc(d.App.Login.Accounts, func(a daemon.Account) bool { return a.ID == account.ID }) - if d.App.Login.Step != tui.StepChoose || row < 0 { - t.Fatalf("/login does not list the fixture account: step %v\n%s", d.App.Login.Step, d.View()) + if d.App.Login.Step != tui.StepChoose || !slices.ContainsFunc(d.App.Login.Accounts, func(a daemon.Account) bool { return a.ID == account.ID }) { + t.Fatalf("/accounts does not list the fixture account: step %v\n%s", d.App.Login.Step, d.View()) } - // focus moves the cursor onto the fixture account's row. - focus := func() { - t.Helper() - row := slices.IndexFunc(d.App.Login.Accounts, func(a daemon.Account) bool { return a.ID == account.ID }) - d.Type("refused fixture") - if item, ok := d.App.Login.ChoosePicker.Highlighted(); !ok || item.ID != "account:"+strconv.Itoa(row) { - t.Fatalf("filtering did not reach the fixture account\n%s", d.View()) - } + d.Type("refused fixture") + if item, ok := d.App.Login.ChoosePicker.Highlighted(); !ok || item.ID != "acct:"+account.ID { + t.Fatalf("filtering did not reach the fixture account\n%s", d.View()) } - focus() profiles, err := daemon.ProviderProfiles(t.Context(), connection) if err != nil { t.Fatal(err) } pinned := config.Settings{Extension: "openai", BaseURL: "https://refused.example/v1", Model: "fixture", Protocol: "chat_completions", AccountID: &account.ID} - if err := daemon.SaveProvider(t.Context(), connection, name, pinned, profiles.ETag); err != nil { + if err = daemon.SaveProvider(t.Context(), connection, name, pinned, profiles.ETag); err != nil { t.Fatalf("pin the account: %v", err) } - ctrlD := tea.KeyPressMsg{Code: 'd', Mod: tea.ModCtrl} - d.Dispatch(ctrlD) - if d.App.Login.Step != tui.StepRemove { - t.Fatalf("ctrl+d on the stale row did not ask: step %v\n%s", d.App.Login.Step, d.View()) + d.Dispatch(tea.KeyPressMsg{Code: 'x', Mod: tea.ModCtrl}) + view := d.View() + if d.App.Login.Step != tui.StepRemove || !strings.Contains(view, "Sign out refused fixture?") || !strings.Contains(view, "Models from refused.example stop until you add another refused.example key.") { + t.Fatalf("ctrl+x did not ask with the consequence: step %v\n%s", d.App.Login.Step, view) } d.Dispatch(d.Key(tea.KeyEnter)) - if login := d.App.Login; login.Step != tui.StepChoose || !strings.Contains(login.Error, "still used by "+name) { - t.Fatalf("the refusal is not shown: step %v error %q\n%s", login.Step, login.Error, d.View()) + removed = true + if login := d.App.Login; login.Step != tui.StepChoose || login.Error != "" || !strings.Contains(login.Status, "Signed out refused fixture") { + t.Fatalf("the sign-out did not finish: step %v error %q status %q\n%s", login.Step, login.Error, login.Status, d.View()) } - i := slices.IndexFunc(d.App.Login.Accounts, func(a daemon.Account) bool { return a.ID == account.ID }) - if i < 0 || !slices.Contains(d.App.Login.Accounts[i].SelectedByProfiles, name) { - t.Fatalf("the refused account is not listed as pinned by %s: %+v", name, d.App.Login.Accounts) + if slices.ContainsFunc(d.App.Login.Accounts, func(a daemon.Account) bool { return a.ID == account.ID }) { + t.Fatalf("the signed-out account is still listed: %+v", d.App.Login.Accounts) } - focus() - if !strings.Contains(d.View(), "refused fixture") { - t.Fatalf("the refused account's row is not drawn:\n%s", d.View()) + profiles, err = daemon.ProviderProfiles(t.Context(), connection) + if err != nil { + t.Fatal(err) } - d.Dispatch(ctrlD) - if login := d.App.Login; login.Step != tui.StepChoose || !strings.Contains(login.Status, name) { - t.Fatalf("ctrl+d on a pinned account did not say who pins it: step %v status %q", login.Step, login.Status) + if got := profiles.Providers[name]; got.AccountID != nil { + t.Fatalf("the setup still pins the signed-out account: %+v", got) } } @@ -319,6 +317,9 @@ func TestTUILoginOpenCodeGoSignInRowSavesAKeyAccount(t *testing.T) { d.App.Chat.TextArea.SetValue("/login") d.Dispatch(d.Key(tea.KeyEnter)) expect(tui.StepChoose) + // Naming a setup that signs in is under advanced. + d.Dispatch(tui.PickerSelectMsg{ID: "advanced"}) + expect(tui.StepAdvanced) d.Dispatch(tui.PickerSelectMsg{ID: "signin:opencode-go"}) expect(tui.StepProfileName) d.App.Login.TextInput.SetValue(name) @@ -407,12 +408,14 @@ func TestTUILoginSavesAnAnthropicAPIKeyProfile(t *testing.T) { } } - d.App.Chat.TextArea.SetValue("/login") + d.App.Chat.TextArea.SetValue("/accounts") d.Dispatch(d.Key(tea.KeyEnter)) expect(tui.StepChoose) if !slices.ContainsFunc(d.App.Login.SignIns, func(s daemon.SignIn) bool { return s.Provider == "claude" }) { t.Fatalf("the daemon offers no claude sign-in to route around: %+v", d.App.Login.SignIns) } + d.Dispatch(tui.PickerSelectMsg{ID: "keys"}) + expect(tui.StepAddKey) d.Dispatch(tui.PickerSelectMsg{ID: "add-anthropic"}) expect(tui.StepName) d.App.Login.TextInput.SetValue(name) @@ -433,7 +436,7 @@ func TestTUILoginSavesAnAnthropicAPIKeyProfile(t *testing.T) { if err != nil { t.Fatalf("saved config: %v", err) } - want := config.Settings{ProfileName: name, Extension: "claude", Model: model, Protocol: "chat_completions", HasKey: true} + want := config.Settings{ProfileName: name, Extension: "claude", Model: model, Protocol: "chat_completions", Rotation: "failover", HasKey: true} if got := profiles.Providers[name]; !reflect.DeepEqual(got, want) { t.Fatalf("config.json kept %+v, want %+v", got, want) } diff --git a/docs/openapi.yaml b/docs/openapi.yaml index d59c746d3..4ede971c3 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -4590,11 +4590,12 @@ paths: '409': $ref: '#/components/responses/Problem409' description: - "Reject if a profile pins it by `account_id`, if it is the last account - of a profile's `account_ids`, or if it comes from the environment - (`account_external`). Otherwise it also leaves every `account_ids` list - naming it. Does not interrupt captured credentials in an active request. - Account IDs are never reused. Requires capability `provider_auth: 1`." + 'Signs the account out. Reject only an account that comes from the + environment (`account_external`). A profile pinned to it by `account_id` + goes back to automatic selection, and it leaves every `account_ids` list + naming it; a list it empties becomes null. Does not interrupt captured + credentials in an active request. Account IDs are never reused. Requires + capability `provider_auth: 1`.' parameters: - name: account_id in: path @@ -8694,10 +8695,11 @@ components: - type: 'null' account_ids: description: - Accounts this profile rotates between after a limit, by id. Null - when it does not rotate. Exclusive with `account_id`; with neither, - a profile uses one account (its saved key, the environment key, or - the provider's selected or first account) and never switches. + Accounts this profile uses, in order, by id. Null when it does not + rotate. Exclusive with `account_id`; with neither, a profile uses + one account (its saved key, the environment key, or the provider's + selected or first account) and never switches. `rotation` says how + the list is used. anyOf: - type: array items: @@ -8705,6 +8707,18 @@ components: minItems: 1 maxItems: 50 - type: 'null' + rotation: + type: string + enum: [failover, spread, first] + default: failover + description: + How `account_ids` is used. `failover` uses the first ready account + and moves down the list after a limit. `spread` starts each new + session (every agent is a session) on the next ready account in turn + and keeps it there for the session's life, so its prompt cache stays + warm; it moves only when that account is limited or needs sign-in, + and stays on the account it moved to. `first` uses only the first + and waits out its limit. Ignored without `account_ids`. project: anyOf: - type: string @@ -8727,6 +8741,7 @@ components: image_edge, account_id, account_ids, + rotation, project, location, has_key, @@ -8776,10 +8791,11 @@ components: - type: 'null' account_ids: description: - Accounts this profile rotates between after a limit, by id. Null - when it does not rotate. Exclusive with `account_id`; with neither, - a profile uses one account (its saved key, the environment key, or - the provider's selected or first account) and never switches. + Accounts this profile uses, in order, by id. Null when it does not + rotate. Exclusive with `account_id`; with neither, a profile uses + one account (its saved key, the environment key, or the provider's + selected or first account) and never switches. `rotation` says how + the list is used. anyOf: - type: array items: @@ -8787,6 +8803,17 @@ components: minItems: 1 maxItems: 50 - type: 'null' + rotation: + type: string + enum: [failover, spread, first] + description: + How `account_ids` is used. `failover` uses the first ready account + and moves down the list after a limit. `spread` starts each new + session (every agent is a session) on the next ready account in turn + and keeps it there for the session's life, so its prompt cache stays + warm; it moves only when that account is limited or needs sign-in, + and stays on the account it moved to. `first` uses only the first + and waits out its limit. Ignored without `account_ids`. project: anyOf: - type: string @@ -15489,6 +15516,29 @@ components: - type: string format: date-time - type: 'null' + email: + description: + The sign-in's email when the provider reports one; null for keys, + environment accounts, and sign-ins that carry no email. New sign-ins + take it as their label until renamed. + anyOf: + - type: string + maxLength: 320 + - type: 'null' + plan: + description: + The subscription tier the provider reports for a sign-in, such as + `Max`, `Pro` or `Plus`; null when unknown. + anyOf: + - type: string + maxLength: 64 + - type: 'null' + needs_sign_in: + type: boolean + description: + The saved sign-in can no longer be used (its renewal was refused, it + was revoked, or the provider suspended it) until it is signed in + again. Rotation skips it. Always false for keys. selected_by_profiles: type: array description: Profiles pinned to this account by `account_id`. @@ -15511,6 +15561,9 @@ components: source, endpoint, limited_until, + email, + plan, + needs_sign_in, selected_by_profiles, rotated_by_profiles, ] diff --git a/packages/albedo_model/src/albedo_model.gleam b/packages/albedo_model/src/albedo_model.gleam index 60eae0209..ebff14cf6 100644 --- a/packages/albedo_model/src/albedo_model.gleam +++ b/packages/albedo_model/src/albedo_model.gleam @@ -760,6 +760,11 @@ pub type Event { /// The response's headers arrived with this status: the provider accepted /// the request, and a 2xx one is generating it. Responded(status: Int) + /// A response that is not 2xx arrived with these headers, before its body + /// becomes the `Refused` error. A provider that reads its limits from headers + /// (Claude's subscription rate limits) hears them here; everything else + /// ignores it. + RefusalHeaders(status: Int, headers: List(#(String, String))) /// What the provider has metered for the response so far, as its latest /// chunk reported it. Gemini routes report usage on intermediate chunks, /// so a call that fails midway still says what it cost. diff --git a/packages/albedo_model_stream/src/albedo_model_stream/http.gleam b/packages/albedo_model_stream/src/albedo_model_stream/http.gleam index 792010c79..671333ca3 100644 --- a/packages/albedo_model_stream/src/albedo_model_stream/http.gleam +++ b/packages/albedo_model_stream/src/albedo_model_stream/http.gleam @@ -115,7 +115,13 @@ pub fn exchange( http_error(connection, wait, exchange.refusal, status, final, [], 0) } case status >= 200 && status < 300 { - False -> failed() + False -> { + use _ <- result.try(notify( + [types.RefusalHeaders(status, headers)], + on_event, + )) + failed() + } True -> case wire.body(headers) { FailureBody -> failed() diff --git a/packages/albedo_sdk/src/albedo_sdk/accounts.gleam b/packages/albedo_sdk/src/albedo_sdk/accounts.gleam index 6bbc6e374..6615e90c0 100644 --- a/packages/albedo_sdk/src/albedo_sdk/accounts.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/accounts.gleam @@ -12,6 +12,7 @@ import gleam/erlang/atom.{type Atom} import gleam/int import gleam/list import gleam/option.{type Option, None, Some} +import gleam/order import gleam/result import gleam/string @@ -88,7 +89,7 @@ fn fingerprint(bytes: BitArray, hash: Int) -> Int { /// then the session's sticky or hashed choice. Accounts still inside a /// reported limit for `meter` go last, soonest reset first. `raw` exposes each /// account's JSON object. `identity` is called only for an account that can -/// match the session's sticky choice. +/// match the session's sticky choice. Accounts that need sign-in are left out. pub fn arrange( scope: String, values: List(account), @@ -97,40 +98,197 @@ pub fn arrange( raw: fn(account) -> Dynamic, meter: Option(String), ) -> List(account) { + arrange_by( + credential_store.Automatic, + scope, + values, + session, + identity, + raw, + meter, + ) +} + +/// `arrange` for a profile's rotation. `Automatic` keeps the selected and +/// hashed order above. A list rotation keeps the list's order: the session's +/// sticky account first while it is ready, then, for `Failover` and `First`, +/// the other ready accounts in list order, and for `Spread` the ready +/// accounts assigned to a session longest ago first, so each new session +/// starts on the next account. Limited accounts follow, soonest reset first. +pub fn arrange_by( + rotation: credential_store.Rotation, + scope: String, + values: List(account), + session: String, + identity: fn(account) -> String, + raw: fn(account) -> Dynamic, + meter: Option(String), +) -> List(account) { + let values = list.filter(values, fn(value) { !signed_out(raw(value)) }) case values { [] -> [] _ -> { let now = albedo_clock.system_ms() - let sticky = case - decode.run(get(sticky_key(scope, session)), decode.string) - { - Ok(pinned) if pinned != "" -> Some(pinned) - _ -> None + let sticky = sticky(scope, session) + case rotation { + credential_store.Automatic -> { + let entries = + list.map(values, fn(value) { + let fields = raw(value) + let until = until_of(fields, meter) + let id = case sticky { + Some(_) if until <= now -> identity(value) + _ -> "" + } + Entry(value, id, flag(fields, "selected"), until) + }) + order(entries, session, sticky, now) + } + _ -> listed(rotation, scope, values, sticky, identity, raw, meter, now) } - let entries = - list.map(values, fn(value) { - let fields = raw(value) - let until = until_of(fields, meter) - let id = case sticky { - Some(_) if until <= now -> identity(value) - _ -> "" - } - Entry(value, id, flag(fields, "selected"), until) - }) - order(entries, session, sticky, now) } } } -/// Stick the session to the account it was just given, in the calling -/// process. +fn listed( + rotation: credential_store.Rotation, + scope: String, + values: List(account), + sticky: Option(String), + identity: fn(account) -> String, + raw: fn(account) -> Dynamic, + meter: Option(String), + now: Int, +) -> List(account) { + let timed = + list.map(values, fn(value) { #(value, until_of(raw(value), meter)) }) + let #(limited, open) = list.partition(timed, fn(entry) { entry.1 > now }) + let open = list.map(open, fn(entry) { entry.0 }) + let #(hit, others) = case sticky { + None -> #([], open) + Some(pinned) -> + list.partition(open, fn(value) { identity(value) == pinned }) + } + let others = case rotation { + credential_store.Spread -> + others + |> list.index_map(fn(value, index) { + #(value, assigned(scope, identity(value)), index) + }) + |> list.sort(fn(first, second) { + case int.compare(first.1, second.1) { + order.Eq -> int.compare(first.2, second.2) + other -> other + } + }) + |> list.map(fn(entry) { entry.0 }) + _ -> others + } + let limited = + list.sort(limited, fn(first, second) { int.compare(first.1, second.1) }) + |> list.map(fn(entry) { entry.0 }) + list.flatten([hit, others, limited]) +} + +/// Whether a raw account is a sign-in that can no longer be used until it is +/// signed in again. +fn signed_out(value: Dynamic) -> Bool { + case decode.run(value, decode.dict(decode.string, decode.dynamic)) { + Ok(fields) -> credential_store.needs_sign_in(fields) + Error(_) -> False + } +} + +/// Stick the session to the account it was just given. The choice is kept +/// for the daemon's lifetime, scoped by provider store and session, so every +/// turn of the session reaches the same account and its prompt cache. A +/// change of account also records when the account was last assigned, which +/// `Spread` reads to start the next session on another account. pub fn remember(scope: String, session: String, identity: String) -> Nil { - put(sticky_key(scope, session), identity) - Nil + case sticky(scope, session) == Some(identity) { + True -> Nil + False -> { + registry.register(affinity(), #(scope, session), identity) + registry.register(assignments(), #(scope, identity), unique_integer()) + } + } } -fn sticky_key(scope: String, session: String) -> #(Atom, String, String) { - #(atom.create("albedo_accounts"), scope, session) +/// Drop every account a session was given, when the session is deleted or +/// closed for good. Without it the affinity table keeps one entry per +/// session and store for the daemon's lifetime. +pub fn forget_session(session: String) -> Nil { + case table_exists(affinity_table()) { + True -> { + let _ = + match_delete(affinity_table(), #( + #(atom.create("_"), session), + atom.create("_"), + )) + Nil + } + False -> Nil + } +} + +/// Drop the assignment stamps of an account that was signed out, by its +/// provider identity in any store. +pub fn forget_account(identity: String) -> Nil { + case table_exists(assigned_table()) { + True -> { + let _ = + match_delete(assigned_table(), #( + #(atom.create("_"), identity), + atom.create("_"), + )) + Nil + } + False -> Nil + } +} + +fn table_exists(table: Atom) -> Bool { + ets_whereis(table) != atom.to_dynamic(atom.create("undefined")) +} + +@external(erlang, "ets", "whereis") +fn ets_whereis(table: Atom) -> Dynamic + +@external(erlang, "ets", "match_delete") +fn match_delete(table: Atom, pattern: #(#(Atom, String), Atom)) -> Bool + +fn sticky(scope: String, session: String) -> Option(String) { + case registry.lookup(affinity(), #(scope, session)) { + Ok(identity) if identity != "" -> Some(identity) + _ -> None + } +} + +/// When an account was last given to a session, as an ordering stamp; 0 +/// when never. +fn assigned(scope: String, identity: String) -> Int { + registry.lookup(assignments(), #(scope, identity)) + |> result.unwrap(0) +} + +/// The table `albedo_account_affinity`, from store and session to the +/// account the session was given. +fn affinity() -> Registry(#(String, String), String) { + registry.new(affinity_table()) +} + +/// The table `albedo_account_assigned`, from store and account to when the +/// account was last given to a session. +fn assignments() -> Registry(#(String, String), Int) { + registry.new(assigned_table()) +} + +fn affinity_table() -> Atom { + atom.create("albedo_account_affinity") +} + +fn assigned_table() -> Atom { + atom.create("albedo_account_assigned") } /// Whether a raw account is inside any recorded limit at `now`. @@ -359,6 +517,15 @@ fn put(key: key, value: value) -> Dynamic @external(erlang, "gleam_stdlib", "identity") fn unsafe_coerce(value: Dynamic) -> a +/// A daemon-wide increasing integer, so two assignments in the same +/// millisecond still order. +fn unique_integer() -> Int { + unique_monotonic([atom.create("monotonic"), atom.create("positive")]) +} + +@external(erlang, "erlang", "unique_integer") +fn unique_monotonic(options: List(Atom)) -> Int + @external(erlang, "ets", "select_delete") fn select_delete( table: Atom, diff --git a/packages/albedo_sdk/src/albedo_sdk/auth_accounts.gleam b/packages/albedo_sdk/src/albedo_sdk/auth_accounts.gleam index b17268c70..4364147a8 100644 --- a/packages/albedo_sdk/src/albedo_sdk/auth_accounts.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/auth_accounts.gleam @@ -10,6 +10,7 @@ import albedo_bytes/scalars import albedo_clock import albedo_json import albedo_protect +import albedo_sdk/accounts as account_pools import albedo_sdk/credential_store.{type Object} import albedo_sdk/key_accounts import albedo_sdk/key_environment.{type KeyEnvironment} @@ -18,11 +19,13 @@ import albedo_sdk/profiles import albedo_sdk/rotation import albedo_sdk/settings_store import gleam/bit_array +import gleam/bool import gleam/crypto import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/erlang/atom +import gleam/int import gleam/json import gleam/list import gleam/option.{None, Some} @@ -73,12 +76,30 @@ pub fn signed_in( let saved = settings_store.object("accounts", creds) let values = credential_store.values(saved, store) let matches = fn(value: Object) { account(dyn(value)).id == raw_id } - let public_id = case list.find(values, matches) { + let previous = list.find(values, matches) + let public_id = case previous { Ok(previous) -> existing_id(previous) Error(_) -> token() } let described = account(credential) let assert Ok(credential) = credential_store.object(credential) + // A renamed account keeps its name; a new sign-in is named by its email, + // told apart from the other accounts of the provider on that email. + let label = case + previous |> result.try(dict.get(_, "label")), + described.email + { + Ok(label), _ -> Some(label) + Error(_), Some(email) -> + Some( + dyn(scalars.take(distinct_label(email, described, values, account), 256)), + ) + Error(_), None -> None + } + let credential = case label { + Some(label) -> dict.insert(credential, "label", label) + None -> credential + } let credential = credential |> dict.insert("_albedo_account_id", dyn(public_id)) @@ -110,6 +131,49 @@ pub fn signed_in( ) } +/// A new sign-in's label: its email, unless another account of the provider +/// already has that email (several accounts can share one), then the email +/// with the workspace name, else the plan, else `#N`, whichever no other +/// account is labelled with yet. Existing accounts are never renamed. +fn distinct_label( + email: String, + described: Account, + values: List(Object), + account: fn(Dynamic) -> Account, +) -> String { + let others = list.map(values, fn(value) { #(value, account(dyn(value))) }) + let shared = + list.filter(others, fn(other) { { other.1 }.email == Some(email) }) + let taken = + list.map(others, fn(other) { + case credential_store.text(other.0, "label") { + Ok(label) -> label + Error(_) -> { other.1 }.label + } + }) + case shared { + [] -> email + _ -> { + let suffixes = + list.flatten([ + option.to_result(described.workspace, Nil) + |> result.map(list.wrap) + |> result.unwrap([]), + option.to_result(described.plan, Nil) + |> result.map(list.wrap) + |> result.unwrap([]), + ["#" <> int.to_string(list.length(shared) + 1)], + ]) + suffixes + |> list.map(fn(suffix) { email <> " · " <> suffix }) + |> list.find(fn(label) { !list.contains(taken, label) }) + |> result.unwrap( + email <> " · #" <> int.to_string(list.length(values) + 1), + ) + } + } +} + /// The saved account's public ID. A hand edit can leave one that is not a /// string; signing in again replaces it with a fresh ID instead of failing. fn existing_id(value: Object) -> String { @@ -507,6 +571,15 @@ fn saved_projection( let assert Ok(meta_label) = dict.get(meta, "label") let label = dict.get(credential, "label") |> result.unwrap(meta_label) + let #(email, plan, refused) = case + list.find(logins, fn(login) { login.store == store }) + { + Ok(login) -> { + let described = login.account(dyn(credential)) + #(described.email, described.plan, described.needs_sign_in) + } + Error(_) -> #(None, None, False) + } Ok( meta |> dict.insert("id", id) @@ -514,6 +587,12 @@ fn saved_projection( |> dict.insert("source", dyn("saved")) |> dict.insert("endpoint", credential_store.null()) |> dict.insert("limited_until", limited_until(credential)) + |> dict.insert("email", reported(email, 320)) + |> dict.insert("plan", reported(plan, 64)) + |> dict.insert( + "needs_sign_in", + dyn(refused || credential_store.needs_sign_in(credential)), + ) |> dict.insert( "selected_by_profiles", dyn(selected_profiles(saved_profiles, id)), @@ -572,6 +651,14 @@ fn text_or(value: Object, name: String, default: String) -> String { credential_store.text(value, name) |> result.unwrap(default) } +/// A reported email or plan within the contract's length, else JSON null. +fn reported(value: option.Option(String), limit: Int) -> Dynamic { + case value { + Some(text) if text != "" -> dyn(scalars.take(text, limit)) + _ -> credential_store.null() + } +} + fn limited_until(credential: Object) -> Dynamic { case decode.run(field(credential, "limitedUntil"), decode.int) { Ok(until) if until > 0 -> dyn(albedo_clock.format_rfc3339(until)) @@ -652,6 +739,9 @@ fn key_descriptor( #("source", dict.get(credential, "source") |> result.unwrap(dyn("saved"))), #("endpoint", endpoint), #("limited_until", limited_until(credential)), + #("email", credential_store.null()), + #("plan", credential_store.null()), + #("needs_sign_in", dyn(False)), #("selected_by_profiles", dyn(selected_profiles(saved_profiles, id))), #("rotated_by_profiles", dyn(rotated_profiles(saved_profiles, id))), ]), @@ -689,8 +779,9 @@ fn host(endpoint: Dynamic) -> Dynamic { } } -/// Remove a saved account by public ID under the settings lock. -/// Return `#(HTTP status, code, message)` when it cannot be removed. +/// Remove a saved account by public ID under the settings lock, and take it +/// out of every profile (see `without_account`). Only an unknown or +/// environment account is refused, as `#(HTTP status, code, message)`. pub fn remove_account( home: String, logins: List(Login), @@ -713,35 +804,25 @@ pub fn remove_account( }), #(409, "account_external", "Environment accounts cannot be changed."), ) - use <- ensure( - list.all(selected, fn(account) { - field(account, "selected_by_profiles") == dyn([]) - }), - #( - 409, - "account_in_use", - "Provider account is referenced by a saved profile.", - ), - ) let config = settings_store.read(home, "config.json") let saved_profiles = dict.get(config, "providers") |> result.unwrap(dyn(empty())) let entries = profile_entries(saved_profiles) - use <- ensure( - entries - |> list.filter(fn(entry) { list.contains(rotation_ids(entry.1), dyn(id)) }) - |> list.all(fn(entry) { - let assert Ok(ids) = - decode.run( - dict.get(entry.1, "accountIds") |> result.unwrap(dyn([])), - decode.list(decode.dynamic), - ) - list.length(ids) > 1 - }), - #(409, "account_in_use", "Account is the last member of a rotation."), - ) let creds = settings_store.read(home, "creds.json") let stored = settings_store.object("accounts", creds) + // Rotation forgets when the account was last given to a session, by the + // identities selection knows it by: its public ID (keys) and its login's. + list.each(dict.keys(stored), fn(store) { + credential_store.values(stored, store) + |> list.filter(fn(value) { field(value, "_albedo_account_id") == dyn(id) }) + |> list.each(fn(value) { + account_pools.forget_account(id) + case list.find(logins, fn(login) { login.store == store }) { + Ok(login) -> account_pools.forget_account(login.account(dyn(value)).id) + Error(_) -> Nil + } + }) + }) let updated = list.fold(dict.keys(stored), stored, fn(saved, store) { credential_store.values(saved, store) @@ -751,19 +832,7 @@ pub fn remove_account( let next_profiles = list.map(entries, fn(entry) { let #(name, profile) = entry - case - decode.run(field(profile, "accountIds"), decode.list(decode.dynamic)) - { - Ok(ids) -> #( - name, - dyn(dict.insert( - profile, - "accountIds", - dyn(list.filter(ids, fn(value) { value != dyn(id) })), - )), - ) - Error(_) -> #(name, dyn(profile)) - } + #(name, dyn(without_account(profile, dyn(id)))) }) settings_store.commit_group( home, @@ -782,6 +851,152 @@ pub fn remove_account( Ok(Nil) } +/// The next `config.json` once a new model sign-in `id` for `extension`, +/// saved under `store` in `creds`, joins its service: +/// +/// - each profile of the extension with `accountIds` gains it at the end; +/// - each with neither a pin nor a list, nor a saved key, rotates through +/// every saved sign-in of the store, in file order, the new one last; +/// - a profile pinned by `accountId` is left alone; +/// - when no profile uses the extension, `first` (a model and protocol) +/// creates one named after it (`name`, `name-2`, ...) that rotates through +/// the new account, and it becomes the default when none is set. +/// +/// Pure: the caller commits the result with the credential. +pub fn joined( + config: Dynamic, + creds: Dynamic, + store: String, + extension: String, + id: String, + first: option.Option(#(String, String)), +) -> Dynamic { + let assert Ok(config) = credential_store.object(config) + let assert Ok(creds) = credential_store.object(creds) + // A legacy flat config is one profile without a name to join. + use <- bool.guard( + !dict.has_key(config, "providers") && dict.has_key(config, "model"), + dyn(config), + ) + let saved = dict.get(config, "providers") |> result.unwrap(dyn(empty())) + let entries = profile_entries(saved) + let keys = settings_store.object("providers", creds) + let signed_in_ids = + credential_store.values(settings_store.object("accounts", creds), store) + |> list.filter(fn(value) { field(value, "type") != dyn("key") }) + |> list.filter_map(fn(value) { + credential_store.text(value, "_albedo_account_id") + }) + let own = + list.filter(entries, fn(entry) { + text_or(entry.1, "extension", profiles.default_extension()) == extension + }) + let null = credential_store.null() + let next = case own, first { + [], Some(#(model, protocol)) -> { + let name = free_name(extension, entries, 1) + let profile = + dict.from_list([ + #("extension", dyn(extension)), + #("baseUrl", dyn("")), + #("model", dyn(model)), + #("protocol", dyn(protocol)), + #("accountIds", dyn([id])), + #("rotation", dyn("failover")), + ]) + let config = + dict.insert( + config, + "providers", + object([ + #(name, dyn(profile)), + ..list.map(entries, fn(entry) { #(entry.0, dyn(entry.1)) }) + ]), + ) + case field(config, "active") { + active if active == null -> dict.insert(config, "active", dyn(name)) + active -> + case decode.run(active, decode.string) { + Ok("") | Error(_) -> dict.insert(config, "active", dyn(name)) + Ok(_) -> config + } + } + } + [], None -> config + _, _ -> { + let updated = + list.map(entries, fn(entry) { + let #(name, profile) = entry + let joins = list.contains(own, entry) + let pinned = field(profile, "accountId") != null + let listed = + decode.run( + field(profile, "accountIds"), + decode.list(decode.dynamic), + ) + let next = case joins, pinned, listed { + False, _, _ | _, True, _ -> profile + True, False, Ok([_, ..] as ids) -> + case list.contains(ids, dyn(id)) { + True -> profile + False -> + dict.insert( + profile, + "accountIds", + dyn(list.append(ids, [dyn(id)])), + ) + } + True, False, _ -> + case dict.has_key(keys, name) || has_inline_key(profile) { + True -> profile + False -> dict.insert(profile, "accountIds", dyn(signed_in_ids)) + } + } + #(name, dyn(next)) + }) + dict.insert(config, "providers", object(updated)) + } + } + dyn(next) +} + +fn has_inline_key(profile: Object) -> Bool { + case credential_store.text(profile, "apiKey") { + Ok(key) -> key != "" + Error(_) -> False + } +} + +/// `base`, else `base-2`, `base-3`, ... the first no profile takes. +fn free_name(base: String, entries: List(#(String, Object)), n: Int) -> String { + let name = case n { + 1 -> base + _ -> base <> "-" <> int.to_string(n) + } + case list.any(entries, fn(entry) { entry.0 == name }) { + True -> free_name(base, entries, n + 1) + False -> name + } +} + +/// A profile once account `id` is signed out: a pin to it goes back to +/// automatic selection, and it leaves the rotation list, which becomes null +/// when it empties. +fn without_account(profile: Object, id: Dynamic) -> Object { + let profile = case field(profile, "accountId") == id { + True -> dict.delete(profile, "accountId") + False -> profile + } + case decode.run(field(profile, "accountIds"), decode.list(decode.dynamic)) { + Ok(ids) -> + case list.filter(ids, fn(value) { value != id }) { + [] -> dict.delete(profile, "accountIds") + kept -> dict.insert(profile, "accountIds", dyn(kept)) + } + Error(_) -> profile + } +} + // ---- helpers ---------------------------------------------------------------- /// Run `run` under the settings lock. A busy or unrecoverable store is the diff --git a/packages/albedo_sdk/src/albedo_sdk/credential_store.gleam b/packages/albedo_sdk/src/albedo_sdk/credential_store.gleam index e1c2e12d8..f28d0afeb 100644 --- a/packages/albedo_sdk/src/albedo_sdk/credential_store.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/credential_store.gleam @@ -222,6 +222,49 @@ pub fn profile(home: String, name: String) -> Result(Dynamic, String) { } } +/// How a profile uses its accounts. `Automatic` is a profile without an +/// `accountIds` list: a pin, or the provider's selected or first account. +/// The others are the list's saved `rotation`: `Failover` starts each new +/// session on the first ready account, `Spread` starts each new session on +/// the ready account assigned longest ago, and `First` uses only the first +/// account. A session keeps the account it was given until that account is +/// limited or needs sign-in. +pub type Rotation { + Automatic + Failover + Spread + First +} + +/// The saved `rotation` field: `failover` when absent, null or unknown. +pub fn rotation(value: Dynamic) -> Rotation { + case decode.run(value, decode.string) { + Ok("spread") -> Spread + Ok("first") -> First + _ -> Failover + } +} + +/// The saved and wire name of a list rotation. +pub fn rotation_name(rotation: Rotation) -> String { + case rotation { + Spread -> "spread" + First -> "first" + Failover | Automatic -> "failover" + } +} + +/// Whether a saved sign-in can no longer be used until it is signed in +/// again: its renewal was refused (`needsSignIn`) or the provider suspended +/// it (`suspended`). Signing in again replaces the record and clears both. +pub fn needs_sign_in(value: Object) -> Bool { + flag(value, "needsSignIn") + || case dict.get(value, "suspended") |> result.try(object) { + Ok(record) -> !dict.is_empty(record) + Error(_) -> False + } +} + /// A profile's explicit public account identity confines a transport to that /// account. No matching credential is an error rather than a silent /// fallback. Without a binding, the selected value wins, else the first. @@ -230,8 +273,18 @@ pub fn bound_values( profile: String, values: List(Object), ) -> Result(List(Object), String) { + binding(home, profile, values) |> result.map(fn(bound) { bound.0 }) +} + +/// `bound_values` with the profile's rotation. A `First` rotation binds only +/// the list's first account. +pub fn binding( + home: String, + profile: String, + values: List(Object), +) -> Result(#(List(Object), Rotation), String) { case profile { - "" -> Ok(values) + "" -> Ok(#(values, Automatic)) _ -> settings_store.lock( home, @@ -252,7 +305,7 @@ fn bind( config: Object, profile: String, values: List(Object), -) -> Result(List(Object), String) { +) -> Result(#(List(Object), Rotation), String) { let saved = case dict.get(config, "providers") { Ok(profiles) -> { let assert Ok(profiles) = object(profiles) @@ -267,46 +320,28 @@ fn bind( let account_id = field(saved, "accountId") let account_ids = field(saved, "accountIds") let id_list = decode.run(account_ids, decode.list(decode.dynamic)) + let listed = rotation(field(saved, "rotation")) case account_id == null, id_list, account_ids == null { - True, Ok([_, ..] as ids), _ -> { - let selected = - list.flat_map(ids, fn(id) { - list.filter(values, fn(value) { id_of(value) == id }) - }) - let missing = - list.filter(ids, fn(id) { - !list.any(selected, fn(value) { id_of(value) == id }) - }) - case selected, missing { - [], [id, ..] -> unavailable_account(id) - _, [] -> Ok(selected) - _, _ -> - case - list.all(missing, fn(id) { - case decode.run(id, decode.string) { - Ok("env:" <> _) -> True - _ -> False - } - }) - { - True -> Ok(selected) - False -> - Error("Profile's selected accounts are unavailable; run /login") - } + True, Ok([first, ..] as ids), _ -> { + let ids = case listed { + First -> [first] + _ -> ids } + use selected <- result.map(listed_values(ids, values, id_of)) + #(selected, listed) } True, _, True -> case list.find(values, flag(_, "selected")), values { - Ok(selected), _ -> Ok([selected]) - Error(_), [first, ..] -> Ok([first]) - Error(_), [] -> Ok([]) + Ok(selected), _ -> Ok(#([selected], Automatic)) + Error(_), [first, ..] -> Ok(#([first], Automatic)) + Error(_), [] -> Ok(#([], Automatic)) } False, _, True -> case decode.run(account_id, decode.string) { Ok(id) if id != "" -> case list.filter(values, fn(value) { id_of(value) == account_id }) { [] -> unavailable_account(account_id) - selected -> Ok(selected) + selected -> Ok(#(selected, Automatic)) } _ -> Error("Profile's selected account is invalid") } @@ -314,6 +349,40 @@ fn bind( } } +/// The values a list names, in its order. A missing account fails unless +/// every missing one is an environment account. +fn listed_values( + ids: List(Dynamic), + values: List(Object), + id_of: fn(Object) -> Dynamic, +) -> Result(List(Object), String) { + let selected = + list.flat_map(ids, fn(id) { + list.filter(values, fn(value) { id_of(value) == id }) + }) + let missing = + list.filter(ids, fn(id) { + !list.any(selected, fn(value) { id_of(value) == id }) + }) + case selected, missing { + [], [id, ..] -> unavailable_account(id) + _, [] -> Ok(selected) + _, _ -> + case + list.all(missing, fn(id) { + case decode.run(id, decode.string) { + Ok("env:" <> _) -> True + _ -> False + } + }) + { + True -> Ok(selected) + False -> + Error("Profile's selected accounts are unavailable; run /login") + } + } +} + fn unavailable_account(id: Dynamic) -> Result(a, String) { case decode.run(id, decode.string) { Ok("env:" <> variable) -> diff --git a/packages/albedo_sdk/src/albedo_sdk/credentials.gleam b/packages/albedo_sdk/src/albedo_sdk/credentials.gleam index ad5d7f12f..c4f34e8bb 100644 --- a/packages/albedo_sdk/src/albedo_sdk/credentials.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/credentials.gleam @@ -11,6 +11,7 @@ import albedo_sdk/key_accounts import albedo_sdk/key_environment.{type KeyEnvironment} import albedo_sdk/rotation import albedo_sdk/settings_store +import gleam/bit_array import gleam/dict import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode @@ -191,7 +192,7 @@ type NativeStored { /// An immutable credential snapshot, not a revocation lease. Keep it only for /// the operation consuming the credential; native storage remains authoritative. pub opaque type Stored(a) { - Stored(native: NativeStored, value: a) + Stored(native: NativeStored, value: a, rotation: credential_store.Rotation) } /// Read the decoded value captured in this snapshot, without rereading storage. @@ -310,30 +311,34 @@ fn snapshot( decoder: decode.Decoder(a), ) -> Result(Stored(a), String) { decode.run(stored_value(native), decoder) - |> result.map(fn(value) { Stored(native, value) }) + |> result.map(fn(value) { Stored(native, value, credential_store.Automatic) }) |> result.replace_error("Stored credential is invalid") } /// Filter these snapshots through the named profile's account bindings. -/// Return an error when binding cannot be resolved. This does not renew accounts. +/// Return an error when binding cannot be resolved. This does not renew +/// accounts. The snapshots carry the profile's rotation, which `order` keeps. pub fn bound( home: String, profile: String, values: List(Stored(a)), ) -> Result(List(Stored(a)), String) { - use bound <- result.map(credential_store.bound_values( + use #(bound, rotation) <- result.map(credential_store.binding( home, profile, list.map(values, fn(v) { native_value(v.native) }), )) list.filter_map(bound, fn(value) { list.find(values, fn(v) { native_value(v.native) == value }) + |> result.map(fn(v) { Stored(..v, rotation:) }) }) } -/// Order snapshots by selection, session affinity, and cooldown for `meter`. -/// `identity` supplies the provider's identity for each decoded value. This does -/// not remember a choice or renew a token; limited accounts remain at the end. +/// Order snapshots by selection, session affinity, and cooldown for `meter`, +/// following the rotation `bound` gave them. `identity` supplies the +/// provider's identity for each decoded value. This does not remember a +/// choice or renew a token; limited accounts remain at the end, and accounts +/// that need sign-in are left out. pub fn order( scope: String, values: List(Stored(a)), @@ -341,7 +346,12 @@ pub fn order( identity: fn(a) -> String, meter: Option(String), ) -> List(Stored(a)) { - accounts.arrange( + let rotation = case values { + [first, ..] -> first.rotation + [] -> credential_store.Automatic + } + accounts.arrange_by( + rotation, scope, values, session, @@ -351,8 +361,9 @@ pub fn order( ) } -/// Remember an identity for subsequent ordering in this calling process, -/// scoped by provider store and session. This does not edit saved selection. +/// Remember an identity for subsequent ordering, scoped by provider store +/// and session, for the daemon's lifetime: the session keeps this account +/// while it is ready. This does not edit saved selection. pub fn remember(scope: String, session: String, identity: String) -> Nil { accounts.remember(scope, session, identity) } @@ -444,6 +455,58 @@ pub fn expire(account: Stored(a)) -> Result(Nil, String) { stored_expire(account.native) } +/// Whether a token endpoint's answer to a refresh definitively refuses the +/// sign-in: a 401, or a 400 whose OAuth error is `invalid_grant` (RFC 6749 +/// section 5.2: the refresh token is invalid, expired or revoked). Other +/// failures may pass, so they never mark an account. +pub fn refused(status: Int, body: BitArray) -> Bool { + status == 401 + || status == 400 + && string.contains( + bit_array.to_string(body) |> result.unwrap(""), + "invalid_grant", + ) +} + +/// Record that the provider definitively refused this saved sign-in (its +/// refresh token was rejected or the sign-in revoked), so selection skips it +/// and `/auth` reports it as needing sign-in. Signing in again replaces the +/// record and clears the mark. Only the captured material is marked: a +/// credential replaced or removed since is left alone, which succeeds, as +/// do inline and environment snapshots. +pub fn refuse(account: Stored(a)) -> Result(Nil, String) { + case account.native { + SavedAccount(home, store, original) -> + settings_store.lock( + home, + fn() { + case credential_store.accounts(credential_store.path(home)) { + Error(_) -> Error(unreadable) + Ok(data) -> + case + credential_store.values(data, store) + |> list.filter(same_material(original, _)) + { + [current, ..] -> + replace_current( + home, + store, + current, + dict.insert(current, "needsSignIn", dyn(True)), + ) + // Signed in again or removed since: nothing left to mark. + [] -> Ok(Nil) + } + } + }, + fn(failure) { + Error(settings_store.reason(failure, busy: credential_busy)) + }, + ) + _ -> Ok(Nil) + } +} + // ---- snapshots -------------------------------------------------------------- fn stored_accounts( diff --git a/packages/albedo_sdk/src/albedo_sdk/google_oauth.gleam b/packages/albedo_sdk/src/albedo_sdk/google_oauth.gleam index 632aee85d..92690ded0 100644 --- a/packages/albedo_sdk/src/albedo_sdk/google_oauth.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/google_oauth.gleam @@ -76,35 +76,61 @@ pub fn renew( case fresh(previous) { True -> Ok(account) False -> - credentials.renew( - account, - decoder, - identity, - fn(value) { patch(tokens(value)) }, - fn(current) { - use _ <- result.try(validate(current)) - let current_tokens = tokens(current) - use _ <- result.try(valid_expiry(app, current_tokens)) - case fresh(current_tokens) { - True -> Ok(current) - False -> { - // A new refresh secret on a still-stale record is replacement, - // rather than the result of a successful concurrent refresh. - use _ <- result.try( - case current_tokens.refresh == previous.refresh { - True -> Ok(Nil) - False -> Error("credential changed during refresh") - }, - ) - use updated <- result.map(refresh(app, current_tokens)) - replace(current, updated) - } + case renewed(app, account, decoder, identity, tokens, replace, validate) { + Error(reason) -> { + // A refused refresh token cannot recover without a new sign-in. + let _ = case reason == refused(app) { + True -> credentials.refuse(account) + False -> Ok(Nil) } - }, - ) + Error(reason) + } + ready -> ready + } } } +/// What a refresh the token endpoint definitively refused returns. +fn refused(app: App) -> String { + app.name <> " sign-in was refused; run /login to sign in again" +} + +fn renewed( + app: App, + account: credentials.Stored(a), + decoder: decode.Decoder(a), + identity: fn(a) -> String, + tokens: fn(a) -> Tokens, + replace: fn(a, Tokens) -> a, + validate: fn(a) -> Result(Nil, String), +) -> Result(credentials.Stored(a), String) { + let previous = tokens(credentials.value(account)) + credentials.renew( + account, + decoder, + identity, + fn(value) { patch(tokens(value)) }, + fn(current) { + use _ <- result.try(validate(current)) + let current_tokens = tokens(current) + use _ <- result.try(valid_expiry(app, current_tokens)) + case fresh(current_tokens) { + True -> Ok(current) + False -> { + // A new refresh secret on a still-stale record is replacement, + // rather than the result of a successful concurrent refresh. + use _ <- result.try(case current_tokens.refresh == previous.refresh { + True -> Ok(Nil) + False -> Error("credential changed during refresh") + }) + use updated <- result.map(refresh(app, current_tokens)) + replace(current, updated) + } + } + }, + ) +} + fn valid_expiry(app: App, tokens: Tokens) -> Result(Nil, String) { case tokens.expires { Some(_) -> Ok(Nil) @@ -134,9 +160,16 @@ fn refresh(app: App, previous: Tokens) -> Result(Tokens, String) { use _ <- result.try(case status { 200 -> Ok(Nil) _ -> - Error( - app.name <> " token refresh failed (" <> int.to_string(status) <> ")", - ) + case credentials.refused(status, body) { + True -> Error(refused(app)) + False -> + Error( + app.name + <> " token refresh failed (" + <> int.to_string(status) + <> ")", + ) + } }) let response = { use access <- decode.field("access_token", decode.string) diff --git a/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam b/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam index 5d71174a0..11b9c50ac 100644 --- a/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam @@ -137,21 +137,22 @@ pub fn resolve(profile: Profile) -> Result(List(Account), String) { list.try_map(values, fn(value) { snapshot(profile, value) }) } -/// Resolve and order candidates for a session, then remember the first -/// account in this calling process. Return `None` when there are no candidates. +/// Resolve and order candidates for a session by the profile's rotation, +/// then remember the first account for the session. Return `None` when there are no candidates. /// Limited accounts remain candidates after available accounts. pub fn select( profile: Profile, session: String, ) -> Result(Option(Account), String) { - use values <- result.try(resolve_native( + use #(values, rotation) <- result.try(resolve_rotation( profile.home, profile.store, profile.name, profile.keys, )) case - accounts.arrange( + accounts.arrange_by( + rotation, profile.store, values, session, @@ -223,7 +224,7 @@ pub fn limited(account: Account) -> Bool { accounts.limited(native_raw(account.native), albedo_clock.system_ms()) } -/// Records provider-owned selection in the calling process, like select. +/// Records provider-owned selection for the session, like select. pub fn remember(account: Account, session: String) -> Nil { remember_native(account.profile.store, session, account.identity) } @@ -438,7 +439,7 @@ fn resolve_values( store: String, profile: String, keys: KeyEnvironment, -) -> Result(List(NativeAccount), String) { +) -> Result(#(List(NativeAccount), credential_store.Rotation), String) { settings_store.lock( home, fn() { @@ -470,26 +471,30 @@ fn resolve_values( case credential_store.text(saved, "apiKey") { Ok(key) if key != "" -> { let id = rotation.key_label(key) - Ok([ - dict.from_list([ - #("type", dyn("key")), - #("apiKey", dyn(key)), - #("endpoint", dyn(endpoint)), - #("label", dyn(profile)), - #("source", dyn("inline")), - #("_albedo_account_id", dyn(id)), - #("limitedUntil", dyn(accounts.noted(store, id))), - ]), - ]) + Ok(#( + [ + dict.from_list([ + #("type", dyn("key")), + #("apiKey", dyn(key)), + #("endpoint", dyn(endpoint)), + #("label", dyn(profile)), + #("source", dyn("inline")), + #("_albedo_account_id", dyn(id)), + #("limitedUntil", dyn(accounts.noted(store, id))), + ]), + ], + credential_store.Automatic, + )) } _ -> case credential_store.missing(saved, "accountId") && credential_store.missing(saved, "accountIds") { - True -> Ok(list.take(environment, 1)) + True -> + Ok(#(list.take(environment, 1), credential_store.Automatic)) False -> - credential_store.bound_values( + credential_store.binding( home, profile, list.append(saved_keys, environment), @@ -574,7 +579,24 @@ fn resolve_native( profile: String, keys: KeyEnvironment, ) -> Result(List(NativeAccount), String) { - resolve_values(home, store, profile, keys) |> result.try(validate_accounts) + resolve_rotation(home, store, profile, keys) + |> result.map(fn(resolved) { resolved.0 }) +} + +/// `resolve_native` with the profile's rotation. +fn resolve_rotation( + home: String, + store: String, + profile: String, + keys: KeyEnvironment, +) -> Result(#(List(NativeAccount), credential_store.Rotation), String) { + use #(values, rotation) <- result.try(resolve_values( + home, + store, + profile, + keys, + )) + validate_accounts(values) |> result.map(fn(values) { #(values, rotation) }) } /// Ordering reads identity, so validate every candidate before it runs. @@ -676,7 +698,7 @@ fn mark_selected( } Ok("inline") -> case resolve_values(home, store, profile, keys) { - Ok([current]) -> + Ok(#([current], _)) -> case credential_store.text(current, "source") == Ok("inline") && identity(current) == id @@ -723,7 +745,7 @@ fn summary( let id = native_identity(account) let now = albedo_clock.system_ms() let next = case resolve_values(home, store, profile, keys) { - Ok(values) -> + Ok(#(values, _)) -> list.filter(values, fn(value) { identity(value) != Ok(id) && !accounts.limited(native_raw(value), now) }) diff --git a/packages/albedo_sdk/src/albedo_sdk/oauth.gleam b/packages/albedo_sdk/src/albedo_sdk/oauth.gleam index dfa71fa59..560101f45 100644 --- a/packages/albedo_sdk/src/albedo_sdk/oauth.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/oauth.gleam @@ -287,8 +287,66 @@ pub type Grant { ) } +/// How a sign-in describes a stored credential. `id` names the account: equal +/// ids are the same account, and it must never be the email alone, since +/// several accounts can share one. `email`, `plan` and `workspace` are what +/// the provider reported, `None` when unknown; never guess them. +/// `needs_sign_in` is a provider-specific mark that the credential cannot be +/// used until it is signed in again, such as a suspension; the shared +/// `needsSignIn` mark is read by `auth_accounts` on its own. pub type Account { - Account(id: String, label: String, detail: String, selected: Bool) + Account( + id: String, + label: String, + detail: String, + selected: Bool, + email: Option(String), + plan: Option(String), + needs_sign_in: Bool, + /// The organization or workspace name the provider reports for the + /// account, which tells apart accounts sharing an email. + workspace: Option(String), + ) +} + +/// An account descriptor without an email, plan or sign-in mark. +pub fn account( + id id: String, + label label: String, + detail detail: String, + selected selected: Bool, +) -> Account { + Account( + id, + label, + detail, + selected, + option.None, + option.None, + False, + option.None, + ) +} + +/// A subscription tier as `/auth` shows it, its first letter in upper case: +/// `plus` reads `Plus`. `None` for empty text. +pub fn plan(tier: String) -> Option(String) { + case string.pop_grapheme(string.trim(tier)) { + Ok(#(first, rest)) -> option.Some(string.uppercase(first) <> rest) + Error(_) -> option.None + } +} + +/// A nonempty string field of a stored credential, `None` otherwise. +pub fn reported(credential: Dynamic, field: String) -> Option(String) { + case decode.run(credential, decode.at([field], decode.string)) { + Ok(value) -> + case string.trim(value) { + "" -> option.None + trimmed -> option.Some(trimmed) + } + Error(_) -> option.None + } } /// Whether the user selected a stored credential: `"selected": true`. diff --git a/packages/albedo_sdk/src/albedo_sdk/oauth_flows.gleam b/packages/albedo_sdk/src/albedo_sdk/oauth_flows.gleam index 4494367d9..3e7d33f77 100644 --- a/packages/albedo_sdk/src/albedo_sdk/oauth_flows.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/oauth_flows.gleam @@ -17,6 +17,7 @@ import albedo_json import albedo_oauth/listener import albedo_protect import albedo_sdk/auth_accounts +import albedo_sdk/credential_store import albedo_sdk/http_api import albedo_sdk/network import albedo_sdk/network_context @@ -94,7 +95,10 @@ pub fn start() -> Result(Service, actor.StartError) { /// Start sign-in `id` for `provider`, or return the one already started for /// the same intent. `login` is the provider's declaration, `None` when no /// extension names it. `keep` stores the credential when the login's resolver -/// supplies one. Returns whether it was created, and its JSON. +/// supplies one. `first_profile` names the model and protocol of the +/// profile a model sign-in creates when no profile uses its extension (see +/// `auth_accounts.joined`); the flow asks it outside the settings lock, and +/// only then. Returns whether it was created, and its JSON. pub fn start_identified( service: Service, home: String, @@ -103,8 +107,31 @@ pub fn start_identified( login: Option(Login), keep: Option(Keep), intent: String, + first_profile: FirstProfile, ) -> Result(#(Bool, String), Failure) { - call(service, Create(home, id, provider, login, keep, intent, _)) + call(service, Create( + home, + id, + provider, + login, + keep, + intent, + first_profile, + _, + )) +} + +/// The model and protocol a first profile of a sign-in's extension starts +/// with, `None` when there is none to offer. +pub type FirstProfile = + fn() -> Option(#(String, String)) + +/// How a completed sign-in joins its service's profiles: not at all (a +/// service sign-in, or one a resolver keeps), or as a model sign-in with the +/// first profile to create when no profile uses the extension. +type Join { + NoJoin + Joins(first: Option(#(String, String))) } /// Read sign-in `id` as JSON, describing its accounts through `logins`. @@ -149,6 +176,7 @@ pub opaque type Message { login: Option(Login), keep: Option(Keep), intent: String, + first_profile: FirstProfile, reply: Subject(Result(#(Bool, String), Failure)), ) Read( @@ -179,6 +207,7 @@ pub opaque type Message { credential: Dict(String, Dynamic), account: fn(Dynamic) -> Account, keep: Option(Keep), + join: Join, reply: Subject(Result(String, Failure)), ) /// A flow's terminal outcome. The flow waits for the reply, so a read @@ -276,10 +305,10 @@ fn call( fn handle(owner: Owner, message: Message) -> actor.Next(Owner, Message) { let flows = case message { - Create(home, id, provider, login, keep, intent, reply) -> { + Create(home, id, provider, login, keep, intent, first_profile, reply) -> { let #(answer, flows) = guard(owner.flows, fn() { - create(owner, home, id, provider, login, keep, intent) + create(owner, home, id, provider, login, keep, intent, first_profile) }) process.send(reply, answer) flows @@ -306,10 +335,19 @@ fn handle(owner: Owner, message: Message) -> actor.Next(Owner, Message) { process.send(reply, answer) flows } - Store(id, home, store, credential, account, keep, reply) -> { + Store(id, home, store, credential, account, keep, join, reply) -> { let #(answer, flows) = guard(owner.flows, fn() { - store_credential(owner, id, home, store, credential, account, keep) + store_credential( + owner, + id, + home, + store, + credential, + account, + keep, + join, + ) }) process.send(reply, answer) flows @@ -419,6 +457,7 @@ fn create( login: Option(Login), keep: Option(Keep), intent: String, + first_profile: FirstProfile, ) -> Result(#(#(Bool, String), Dict(String, Active)), Failure) { use admission <- result.try( locked(home, fn() { @@ -479,6 +518,14 @@ fn create( let owner_pid = process.self() let ready = process.new_subject() let save = fn(store, credential, account) { + let join = case login.kind, keep { + oauth.Model, None -> + Joins(case profile_uses(home, login.provider) { + True -> None + False -> first_profile() + }) + _, _ -> NoJoin + } store_with_owner( owner_pid, owner.direct, @@ -488,6 +535,7 @@ fn create( credential, account, keep, + join, ) } let pid = @@ -730,6 +778,7 @@ fn store_credential( credential: Dict(String, Dynamic), account: fn(Dynamic) -> Account, keep: Option(Keep), + join: Join, ) -> Result(#(String, Dict(String, Active)), Failure) { use active <- result.try(case dict.get(owner.flows, id) { Ok(active) if active.home == home -> Ok(active) @@ -754,6 +803,20 @@ fn store_credential( Some(keep) -> #(store, keep(creds, value)) None -> signed_in(creds, store, value, account, raw_id, flow.provider) } + // A new account joins its service's profiles in the same commit; a + // sign-in again keeps the account's id and place. + let config = case join, known_account(creds, store, public_id) { + Joins(first), False -> + Some(auth_accounts.joined( + settings_store.read_dynamic(home, "config.json"), + next_creds, + store, + flow.provider, + public_id, + first, + )) + _, _ -> None + } let next = finish( owner, @@ -773,6 +836,10 @@ fn store_credential( "oauth-logins.json", to_map(dict.insert(records, id, encode_record(next))), ), + ..case config { + Some(config) -> [#("config.json", config)] + None -> [] + } ]), ) Ok(next) @@ -946,10 +1013,14 @@ fn store_with_owner( credential: Dict(String, Dynamic), account: fn(Dynamic) -> Account, keep: Option(Keep), + join: Join, ) -> Result(String, String) { let monitor = process.monitor(owner) let reply = process.new_subject() - process.send(direct, Store(id, home, store, credential, account, keep, reply)) + process.send( + direct, + Store(id, home, store, credential, account, keep, join, reply), + ) let answer = process.new_selector() |> process.select_map(reply, fn(stored) { @@ -1457,6 +1528,47 @@ fn signed_in( auth_accounts.signed_in(creds, store, credential, account, raw_id, provider) } +/// Whether `creds` already holds the account with public ID `id` under +/// `store`. +fn known_account(creds: Dynamic, store: String, id: String) -> Bool { + case credential_store.object(creds) { + Ok(creds) -> + credential_store.values(settings_store.object("accounts", creds), store) + |> list.any(fn(value) { + credential_store.text(value, "_albedo_account_id") == Ok(id) + }) + Error(_) -> False + } +} + +/// Whether a saved profile uses `extension`, read without the settings lock: +/// the commit decides again under it. +fn profile_uses(home: String, extension: String) -> Bool { + case credential_store.config(home) { + Ok(config) -> + case + dict.get(config, "providers") |> result.try(credential_store.object) + { + Ok(profiles) -> + dict.values(profiles) + |> list.any(fn(profile) { + decode.run( + profile, + decode.optional_field( + "extension", + "openai", + decode.string, + decode.success, + ), + ) + == Ok(extension) + }) + Error(_) -> False + } + Error(_) -> False + } +} + fn account_projection(home: String, logins: List(Login)) -> List(Dynamic) { auth_accounts.saved_accounts(home, logins) } diff --git a/robot-docs/auth.md b/robot-docs/auth.md index 96e9b34a2..c1a7cb037 100644 --- a/robot-docs/auth.md +++ b/robot-docs/auth.md @@ -72,10 +72,20 @@ behavior. See [cache warming](cache-warming.md) for background eligibility, builds the account projection used by the auth API. It includes saved OAuth and key accounts and environment key accounts, together with profiles that select or rotate through them. The projection exposes account metadata, not the credential -value. Environment accounts cannot be renamed through `rename_account`. A -hand-edited key account without an ID, or without a label and a key that is a -string or a list of byte values, is left out of the projection rather than -failing it. A byte-list key keeps the label of its bytes. +value. Each sign-in also carries the `email` and `plan` its login's +`oauth.Account` descriptor reports, `null` when unknown, and `needs_sign_in`: +the shared `needsSignIn` mark, an Antigravity suspension, or a descriptor's own +`needs_sign_in`. Keys never carry them. Descriptors report only what the +provider said; never guess an email or plan. Environment accounts cannot be +renamed through `rename_account`. A hand-edited key account without an ID, or +without a label and a key that is a string or a list of byte values, is left out +of the projection rather than failing it. A byte-list key keeps the label of its +bytes. + +`remove_account` signs an account out and never refuses a saved one: a profile +pinned to it by `accountId` goes back to automatic selection, and it leaves +every `accountIds` list, which is removed when it empties. Only environment +accounts are refused (`account_external`). `put_key` checks the provider, UUIDv7 identity, endpoint, key, and label before saving a key account. The endpoint must be an HTTP or HTTPS URL with a host and @@ -100,7 +110,8 @@ transport. Selection preserves inline profile keys, explicit account membership, and environment discovery. The shared `select` operation does not acquire saved sibling accounts for an unbound profile; provider-owned selection can have a -different policy. Selection and affinity updates stay in the caller's process. +different policy. Session affinity is daemon-wide, as [rotation](#rotation) +describes. Environment discovery reads the variables that the profile's account IDs name. OpenCode Go and Mistral also name their own variables. Other key stores ask a @@ -173,9 +184,9 @@ their own credential types, identity rules, expiry policy, and HTTP protocol. Decoders use `lenient_text` for string fields that older stored credentials may hold as another type, and `/login` listings use `text` to read one string field from a raw credential. Both read a missing or non-string field as `""`. Account -reads and binding do not establish session affinity. Ordering and affinity stay -in the calling process. A separate read followed by binding is a snapshot, not a -transaction across both operations. +reads and binding do not establish session affinity; `remember` does. A separate +read followed by binding is a snapshot, not a transaction across both +operations. Login identity projections in [`claude/accounts`](../src/albedo/harness/extensions/claude/accounts.gleam), @@ -237,6 +248,63 @@ once, and `accounts.suspend` records a `suspended` object on the saved credential. Selection, discovery, quota reads, and limit advice skip suspended accounts; the failed request is not retried. A fresh `/login` of the account replaces the credential and clears the mark. Quota healing must not clear it. +`/auth` reports a suspended account as `needs_sign_in`. + +## Rotation + +A profile's `accountIds` lists the accounts it uses, in order, and its +`rotation` says how. `credential_store.binding` reads both under the settings +lock and returns the bound accounts with a `credential_store.Rotation`; +`credentials.bound` keeps it on the snapshots and `credentials.order` passes it +to `accounts.arrange_by`. Key pools read it through `key_accounts.select`. A +profile with a pin, or with neither a pin nor a list, is `Automatic`: its one +account, the provider's selected or first one, ordered as before. + +- `failover` (the default, also for an absent, null or unknown value): a new + session starts on the first ready account in list order. +- `spread`: a new session starts on the ready account that was given to a + session longest ago, so sessions and agents take turns. +- `first`: only the list's first account is bound. A limit is waited out or + fails, as for a pin. + +In every mode a session keeps the account it was given for the daemon's +lifetime, so its prompt cache stays warm. It leaves the account only when the +account is limited or needs sign-in, then stays on the account it moved to. +Requests never rebalance a session. `accounts.remember` records the session's +account in a daemon-wide ETS table scoped by store and session, and stamps when +each account was last given to a session, which `spread` orders by. Deleting a +session or closing an agent calls `accounts.forget_session`, so the affinity +table holds at most one entry per store for each session that is neither deleted +nor closed; an unloaded idle session keeps its account. Signing an account out +calls `accounts.forget_account` with its public id and its login identity, so +the stamp table holds at most one entry per saved account and store. Limited +accounts follow the ready ones, soonest reset first. The selected flag is not +read for a list. + +Every mode, `Automatic` included, leaves out an account that needs sign-in. +`credentials.refuse` sets `needsSignIn` on the captured saved credential, under +the settings lock, when the provider definitively refuses it: +`credentials.refused` is a 401 or a 400 `invalid_grant` from the token endpoint +on renewal (Claude, ChatGPT, and Google renewals through `google_oauth`), and a +ChatGPT 401 on a model request for a profile that names its accounts. Other +renewal failures never mark it. A credential replaced or removed since capture +is left alone. A fresh sign-in replaces the record, which clears the mark. + +A Claude sign-in's limit comes from two places. The [quota poller](quota.md)'s +`heal` marks the account until the latest reset of a window reported at 100 +percent, so new sessions pass over it before a request is refused; a report with +room never clears a mark. A 429 marks it from the response headers, which the +model stream's +[HTTP pump](../packages/albedo_model_stream/src/albedo_model_stream/http.gleam) +hands the wire as a `RefusalHeaders` event: `claude/accounts.limit_until` takes +the latest reset (epoch seconds) of the windows a `rejected` +`anthropic-ratelimit-unified-status` names +(`anthropic-ratelimit-unified-5h-status` / `-7d-status` with their `-reset`), +else `anthropic-ratelimit-unified-reset`, else `retry-after`, else one minute. +These header names come from Anthropic's rate-limit documentation, not from +captured responses. The request then moves to another ready account of the +profile, since the session would move there on its next turn and its prompt +cache is lost either way; a Claude 429 is never waited out. ## Sign-in @@ -292,6 +360,45 @@ progress text and waits its interval, unscaled, or until submitted input wakes it. The provider's `credential` builds the account from the whole token response, and each typed failure is worded in `oauth.gleam`. +A model sign-in that creates a new account joins its service in the same +settings group as the credential, through `auth_accounts.joined`. Each profile +of the extension with `accountIds` gains it at the end. Each with neither a pin, +a list, nor a saved key rotates through every saved sign-in of the store, in +file order. Pinned and keyed profiles are left alone. When no profile uses the +extension, the sign-in creates one named after it (`name`, `name-2`, ...) with +`rotation: failover`, and makes it the default when none is set. Its model is +the first one the extension's catalog lists, which is what clients pick, and its +protocol is the one the adapter takes. `http_auth` supplies that as +`start_identified`'s `first_profile`, and the flow asks it outside the settings +lock only when no profile uses the extension; with no listed model no profile is +created. + +A descriptor's `id` names the account, and signing in again replaces a saved +account only when the ids are equal: the credential is replaced and the account +keeps its public id, label, and place in every list. An account is a user in a +workspace or organization, never an email, since several accounts can share one: +a person can have a personal and a business ChatGPT workspace on one email, and +a workspace holds several people. + +- ChatGPT names it `@`: the token's `chatgpt_user_id` (else its + `sub`, else the stored account user id) and its `chatgpt_account_id`. +- Claude names it `:` from the account profile, + read at sign-in. A sign-in from before this was named by a token fingerprint; + its first request records `accountUuid` and `organizationUuid` on it + (`claude/accounts.record_subscription`), which its descriptor then names it + by, so a later sign-in to the same subscription replaces it in place. A legacy + sign-in that has not recorded them is never matched, and signing in again adds + a new account. +- Google (Antigravity, Colab) names it by its email, which a Google account owns + alone. + +A new account is labelled with its email. When another account of the provider +already has that email, the label adds the first of the workspace or +organization name the descriptor reports (`workspace`; Claude reports its +organization name, also shown as its detail), the plan, or `#N` that no account +is labelled with. Existing accounts are never renamed, and a renamed account +keeps its label when signed in again. + Mistral's [sign-in policy](../src/albedo/harness/extensions/mistral/sign_in.gleam) uses the custom `oauth.Device` callback rather than RFC 8628 `DeviceFlow`. It diff --git a/robot-docs/quota.md b/robot-docs/quota.md index 87af6848b..4a470a284 100644 --- a/robot-docs/quota.md +++ b/robot-docs/quota.md @@ -49,8 +49,9 @@ ID when a report has no limits. Every returned report then runs its source's `heal`. Antigravity's [`quota_source`](../src/albedo/harness/extensions/antigravity/accounts.gleam) heal updates account limit marks, including for reports with an error or no -limits. Empty reports prune expired marks and remove integer legacy global -marks. The +limits. Claude's heal marks a sign-in until the latest reset of a window at 100 +percent and never clears a mark; see [rotation](auth.md#rotation). Empty reports +prune expired marks and remove integer legacy global marks. The [account policy](../src/albedo/harness/extensions/antigravity/accounts.gleam) owns reconciliation; the native adapter retains matching, locking, storage layout, and unknown fields. An omitted meter keeps its live mark. The recorded diff --git a/robot-docs/settings.md b/robot-docs/settings.md index 5aca2c7db..9b5c1b956 100644 --- a/robot-docs/settings.md +++ b/robot-docs/settings.md @@ -54,11 +54,15 @@ every read of the group, so keep them cheap. Provider validation belongs to [SDK profile decoding](../packages/albedo_sdk/src/albedo_sdk/profiles.gleam). A -saved profile without an `extension` field belongs to -`profiles.default_extension()`, because profiles saved before the field existed -were OpenAI-compatible. Read a profile's extension with that default instead of -naming the extension again. Do not assume every provider setting is a secret or -that a presence indicator returns the credential value. +profile's `rotation` is saved as given (`failover`, `spread` or `first`; a patch +with any other value answers `400 invalid_request`, and `null` clears it). Every +read reports it, `failover` when it is absent or unknown; see +[rotation](auth.md#rotation) for what it does with `account_ids`. A saved +profile without an `extension` field belongs to `profiles.default_extension()`, +because profiles saved before the field existed were OpenAI-compatible. Read a +profile's extension with that default instead of naming the extension again. Do +not assume every provider setting is a secret or that a presence indicator +returns the credential value. ## Typed extension updates diff --git a/robot-docs/tui.md b/robot-docs/tui.md index 4afa1b877..f553f99d5 100644 --- a/robot-docs/tui.md +++ b/robot-docs/tui.md @@ -60,6 +60,36 @@ composer. The list keeps the highlight visible in short terminals. [Models](models.md#reasoning-defaults) owns the saved choice and provider resolution contract. +## Accounts + +[`/accounts`](../cli/internal/tui/accounts.go), with `/login` as an alias, lists +sign-in accounts grouped by service, then API keys, tool sign-ins, the services +not yet signed in to, and an advanced row. The service names and model lists +live in one table, `accountServices`; other sign-in services keep the daemon's +label and detail. Each service section ends with a row that adds an account, and +a service with two or more accounts numbers them and shows its rotation mode on +the section rule. With no accounts, no keys, and no setups, the screen shows the +first-run sign-in choices instead of the list. + +Enter signs in, or signs in again for an account that needs it. The sign-in runs +inline: the row waits in its section, the search line takes a code or callback +URL, and the pane shows the link. It asks no setup or model question, because +the daemon joins the new account to the service's profiles. Ctrl+O opens the +browser again and Escape cancels the sign-in. + +Tab cycles the service's rotation mode and Alt+Up or Alt+Down reorder its +accounts. Both write through +[`daemon.SaveServiceRotation`](../cli/internal/daemon/rotation.go), which owns +the client mapping from one service order and mode to the profiles of that +extension. Ctrl+R renames an account. Ctrl+X asks to sign out in the footer and +names what keeps running or stops. Environment accounts cannot be renamed or +signed out. + +The advanced row opens the setups list in +[`login_accounts.go`](../cli/internal/tui/login_accounts.go). It keeps profile +selection, editing, renaming, removal, account pins, and the setup forms. Do not +show profiles or setups in the main accounts list. + ## Moving a session `/cd` to another host's folder opens the diff --git a/robot-docs/web.md b/robot-docs/web.md index dca6ff44a..12d53362f 100644 --- a/robot-docs/web.md +++ b/robot-docs/web.md @@ -161,7 +161,7 @@ level carries its source annotation. Choosing that row returns to following the default. Unknown defaults stay unknown. Arrow keys move focus, Enter selects, and Escape closes without saving. Model details contain the profile-bypass action. Changes affect this session; profile defaults remain in Settings → -Providers. +Accounts, under Advanced. During session creation, selecting a model advances to the task. Its reasoning word opens the same menu. The model lists and composer prefer catalog display @@ -176,6 +176,36 @@ Its sections include [web search](web-search.md), [webhooks](webhooks.md), and [Discord](discord.md). Their services enforce the corresponding daemon-side rules. A client view is not an authorization boundary. +[`AccountsSettings.svelte`](../web/src/lib/settings/AccountsSettings.svelte) +shows provider accounts grouped by service: Claude, ChatGPT and Gemini first, +other sign-in services, then one API keys group. The service names and model +blurbs live in one table, `services` in +[`providers.ts`](../web/src/lib/settings/providers.ts). Profiles, setups, +endpoints and protocols stay reachable only under Advanced, which reuses the +per-provider +[`ProviderCard.svelte`](../web/src/lib/settings/ProviderCard.svelte) and +[`ConnectProvider.svelte`](../web/src/lib/settings/ConnectProvider.svelte). Do +not show profile or provider wording outside Advanced. + +Rotation is set per service, while the daemon stores it per profile. +[`accounts.ts`](../web/src/lib/settings/accounts.ts) owns the mapping. It reads +the order and mode from the service's lead profile (the default profile when it +is that service's, else the first that rotates, else the first). A write is one +settings patch that gives every following profile of the service the same +`account_ids`, `rotation` and a cleared `account_id`. Profiles pinned with +`account_id`, and profiles answering with a key saved on themselves, do not +follow. [`accounts.test.mjs`](../web/scripts/accounts.test.mjs) checks these +choices. Keep the mapping there rather than in the page. + +Sign-ins run inline as a row of their service's group through +[`SignInRow.svelte`](../web/src/lib/settings/SignInRow.svelte), which shares +[`SignInFlow`](../web/src/lib/settings/sign-in-flow.svelte.ts) with +`SignIn.svelte`. The page asks nothing else on a sign-in: when it completes, the +page reloads `/auth` and the providers group, because the daemon creates or +joins the service's profiles (see [authentication](auth.md)). Sign out never +asks the page to repair profiles first. Its confirmation states what happens +next. Tool sign-ins (`kind: service`) stay in their own small section. + The [HTTP API behavior guide](../docs/http-api-design.md) defines the browser client's ordering and recovery obligations. [OpenAPI](../docs/openapi.yaml) owns its wire shapes. diff --git a/src/albedo/daemon/api_digest.gleam b/src/albedo/daemon/api_digest.gleam index 6776c27ba..3091f08a0 100644 --- a/src/albedo/daemon/api_digest.gleam +++ b/src/albedo/daemon/api_digest.gleam @@ -2,4 +2,4 @@ //// GET /server reports it so a client built from another contract can tell. pub const digest = - "809b03d0ead404bba1e79ec4b88f1ae1250dc7ad97471bc755f06bb586561f58" + "bb284504402366058bf4db589d0ac1996c8b9354b439ee8f0f4c393ebfb3a5d5" diff --git a/src/albedo/daemon/events.gleam b/src/albedo/daemon/events.gleam index 8162dc935..f6db22961 100644 --- a/src/albedo/daemon/events.gleam +++ b/src/albedo/daemon/events.gleam @@ -171,6 +171,7 @@ pub fn stream_event( types.ArgumentsDelta(_, _, _) | types.Started(_) | types.Responded(_) + | types.RefusalHeaders(..) | types.Metered(..) | types.Served(..) | types.Billed(_) -> None diff --git a/src/albedo/daemon/http_auth.gleam b/src/albedo/daemon/http_auth.gleam index 8ee7f687b..4f4ddc5a4 100644 --- a/src/albedo/daemon/http_auth.gleam +++ b/src/albedo/daemon/http_auth.gleam @@ -303,6 +303,34 @@ pub fn auth( http_api.answer(outcome) } +/// The model and protocol of the profile a first model sign-in to +/// `provider` creates: the first model its catalog lists, as clients pick +/// when they create one, and the protocol its adapter takes. The sign-in asks +/// only when no profile uses the extension, outside the settings lock. +fn first_profile( + host: runtime.Runtime, + provider: String, +) -> oauth_flows.FirstProfile { + let installed = runtime.installed(host) + let keys = runtime.key_environment(host) + fn() { + case extension.provider_model_names(installed, provider, None, keys) { + [model, ..] -> Some(#(model, sign_in_protocol(provider))) + [] -> None + } + } +} + +/// The wire protocol a sign-in provider's adapter requires: ChatGPT's takes +/// the Responses API, every other sign-in chat completions. The clients' +/// sign-in tables hold the same rule. +fn sign_in_protocol(provider: String) -> String { + case provider { + "codex" -> "responses" + _ -> "chat_completions" + } +} + pub fn login( config: Config, registry: Subject(Message), @@ -352,6 +380,9 @@ pub fn login( Error(Nil) -> resolved_login(config, registry, provider) }, ) + use host <- result.try( + registry.host(registry) |> result.map_error(refusal.failure), + ) use created <- result.try( oauth_flows.start_identified( config.oauth, @@ -361,6 +392,7 @@ pub fn login( login, keep, intent, + first_profile(host, provider), ) |> result.map_error(http_api.native_failure), ) diff --git a/src/albedo/daemon/registry.gleam b/src/albedo/daemon/registry.gleam index 24ca3a334..5c633dfb5 100644 --- a/src/albedo/daemon/registry.gleam +++ b/src/albedo/daemon/registry.gleam @@ -5,6 +5,7 @@ import albedo/daemon/session_rows import albedo/harness/locations import albedo/harness/worktree import albedo_bytes/ids +import albedo_sdk/accounts as account_pools import albedo_sdk/family as families import albedo_sdk/input import albedo_sdk/letter as mail_value @@ -1568,6 +1569,8 @@ fn agent_op( case closed { Ok(_) -> { bus.closed(id) + // A closed agent never runs again: its accounts go back to the pool. + account_pools.forget_session(id) } Error(_) -> Nil } diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 77709057a..51e72000a 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2,6 +2,7 @@ import albedo/daemon/lifecycle import albedo/harness/locations +import albedo_sdk/accounts as account_pools import albedo_sdk/family as families import albedo_sdk/hosts import albedo_sdk/input @@ -3393,6 +3394,7 @@ fn handle( Ok(_) -> { active_output_store.revoke(state.home, state.info.id) cleanup_registrations(state.info.id) + account_pools.forget_session(state.info.id) wake_watchers(state) process.send(reply, Ok(Nil)) actor.stop() diff --git a/src/albedo/daemon/session_deletion.gleam b/src/albedo/daemon/session_deletion.gleam index a6a39262d..90efa98d1 100644 --- a/src/albedo/daemon/session_deletion.gleam +++ b/src/albedo/daemon/session_deletion.gleam @@ -12,6 +12,7 @@ import albedo/daemon/refusal.{type Refusal} import albedo/daemon/session import albedo/daemon/shell_commands import albedo/harness/runtime +import albedo_sdk/accounts as account_pools import albedo_sdk/store import gleam/dict.{type Dict} import gleam/dynamic/decode @@ -196,6 +197,7 @@ fn remove( runtime.cleaners(deletion.host), )) session.discard_state(deletion.home, id) + account_pools.forget_session(id) // A file left behind by a failure here is swept at the next start. let _ = shell_commands.remove_session(runtime.ledger(deletion.host), id) Ok(Nil) diff --git a/src/albedo/daemon/settings.gleam b/src/albedo/daemon/settings.gleam index 3bee4131f..4b7bb2a42 100644 --- a/src/albedo/daemon/settings.gleam +++ b/src/albedo/daemon/settings.gleam @@ -479,8 +479,8 @@ fn profile_change( use change <- result.try( fields_of(change, [ "extension", "api", "endpoint", "protocol", "model", "effort", - "image_edge", "account_id", "account_ids", "project", "location", - "api_key", + "image_edge", "account_id", "account_ids", "rotation", "project", + "location", "api_key", ]), ) use old <- result.try(object_or_invalid(get_or(profiles, name, empty()))) @@ -548,6 +548,18 @@ fn profile_change( ), ), ) + use _ <- result.try({ + let rotation = get_or(bound, "rotation", null()) + case is_null(rotation) || list.contains(rotations(), rotation) { + True -> Ok(Nil) + False -> + Error(#( + 400, + "invalid_request", + "rotation must be failover, spread or first", + )) + } + }) use _ <- result.try(nullable_text(get_or(bound, "project", null()), 256)) use _ <- result.try(nullable_text(get_or(bound, "location", null()), 256)) use _ <- result.try({ @@ -615,6 +627,11 @@ fn rename_profiles( }) } +/// The saved values of a profile's `rotation`. +fn rotations() -> List(Dynamic) { + list.map(["failover", "spread", "first"], dynamic.string) +} + /// Patch fields by their saved names. fn provider_fields() -> List(#(String, String)) { [ @@ -627,6 +644,7 @@ fn provider_fields() -> List(#(String, String)) { #("image_edge", "imageEdge"), #("account_id", "accountId"), #("account_ids", "accountIds"), + #("rotation", "rotation"), #("project", "project"), #("location", "location"), ] diff --git a/src/albedo/daemon/stream_trace.gleam b/src/albedo/daemon/stream_trace.gleam index e9c8cf374..10b305c8d 100644 --- a/src/albedo/daemon/stream_trace.gleam +++ b/src/albedo/daemon/stream_trace.gleam @@ -93,6 +93,7 @@ pub fn observe(trace: Trace, event: types.Event, now_ms: Int) -> Nil { | types.Metered(..) | types.Served(..) | types.Billed(_) -> process.send(notes, #(event, now_ms)) + types.RefusalHeaders(..) -> Nil types.Started(_) -> { process.send(notes, #(event, now_ms)) count(counters, started_ms, now_ms, None) @@ -154,8 +155,10 @@ fn note(reported: Reported, event: types.Event, at_ms: Int) -> Reported { trace_id: option.or(trace_id, reported.trace_id), ) types.Started(id) -> Reported(..reported, response_id: Some(id)) - types.ThinkingDelta(_) | types.TextDelta(..) | types.ArgumentsDelta(..) -> - reported + types.ThinkingDelta(_) + | types.TextDelta(..) + | types.ArgumentsDelta(..) + | types.RefusalHeaders(..) -> reported } } diff --git a/src/albedo/harness/extensions/antigravity/extension.gleam b/src/albedo/harness/extensions/antigravity/extension.gleam index 2f25dc407..5e901f935 100644 --- a/src/albedo/harness/extensions/antigravity/extension.gleam +++ b/src/albedo/harness/extensions/antigravity/extension.gleam @@ -578,7 +578,7 @@ fn exchange( /// How /login names a stored Google account, with any limit still running. fn account(credential: Dynamic) -> oauth.Account { case decode.run(credential, decode.dict(decode.dynamic, decode.dynamic)) { - Error(_) -> oauth.Account("", "invalid antigravity account", "", False) + Error(_) -> oauth.account("", "invalid antigravity account", "", False) Ok(_) -> { let label = case decode.run(credential, decode.at(["email"], decode.string)) @@ -587,10 +587,14 @@ fn account(credential: Dynamic) -> oauth.Account { Ok(email) -> email } oauth.Account( - accounts.login_identity(credential), - label, - limit_detail(credential, albedo_clock.system_ms()), - oauth.selected(credential), + ..oauth.account( + accounts.login_identity(credential), + label, + limit_detail(credential, albedo_clock.system_ms()), + oauth.selected(credential), + ), + email: oauth.reported(credential, "email"), + needs_sign_in: is_suspended(credential), ) } } @@ -600,13 +604,18 @@ fn account(credential: Dynamic) -> oauth.Account { /// limited, by meter name, or, for a credential without per-meter marks, its /// legacy `limitedUntil`. fn limit_detail(credential: Dynamic, now: Int) -> String { - let suspended = + case is_suspended(credential) { + True -> "suspended by Google" + False -> meter_detail(credential, now) + } +} + +/// Whether Google suspended the account: a nonempty `suspended` record. +fn is_suspended(credential: Dynamic) -> Bool { + let record = decode.at(["suspended"], decode.dict(decode.string, decode.dynamic)) |> decode.map(fn(record) { !dict.is_empty(record) }) - case decode.run(credential, suspended) { - Ok(True) -> "suspended by Google" - _ -> meter_detail(credential, now) - } + decode.run(credential, record) == Ok(True) } fn meter_detail(credential: Dynamic, now: Int) -> String { diff --git a/src/albedo/harness/extensions/claude/accounts.gleam b/src/albedo/harness/extensions/claude/accounts.gleam index 5cbc0a25a..a8aca176a 100644 --- a/src/albedo/harness/extensions/claude/accounts.gleam +++ b/src/albedo/harness/extensions/claude/accounts.gleam @@ -10,6 +10,7 @@ import albedo_sdk/credentials import albedo_sdk/http import albedo_sdk/usage_feed import gleam/bit_array +import gleam/bool import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/float @@ -27,6 +28,9 @@ pub type Account { expires: Option(Int), account_id: Option(String), email: Option(String), + /// The account UUID recorded from the account profile; `None` on an + /// older sign-in that `record_subscription` has not reached yet. + account_uuid: Option(String), ) } @@ -53,11 +57,17 @@ pub fn decoder() -> decode.Decoder(Account) { None, decode.map(decode.string, Some), ) + use account_uuid <- decode.optional_field( + "accountUuid", + None, + decode.one_of(decode.map(decode.string, Some), [decode.success(None)]), + ) case kind { - "oauth" -> decode.success(Account(access, refresh, expires, id, email)) + "oauth" -> + decode.success(Account(access, refresh, expires, id, email, account_uuid)) _ -> decode.failure( - Account("", "", None, None, None), + Account("", "", None, None, None, None), "Claude OAuth credential", ) } @@ -79,13 +89,67 @@ fn account_identity( } } -/// Presence stops fallback, including empty or malformed legacy identity fields. +/// The account a stored sign-in names when signing in again matches it. A +/// recorded subscription (`accountUuid` and `organizationUuid`) names it, +/// so an older sign-in whose `accountId` is a token fingerprint is still +/// replaced in place by a new sign-in to the same account. Otherwise +/// presence stops fallback, including empty or malformed legacy identity +/// fields. pub fn login_identity(credential: Dynamic) -> String { - account_identity( - present_text(credential, "accountId"), - present_text(credential, "email"), - credentials.text(credential, "refresh"), - ) + let recorded = + subscription_identity(Subscriber( + account: nonempty(credentials.text(credential, "accountUuid")), + organization: nonempty(credentials.text(credential, "organizationUuid")), + organization_name: None, + email: None, + plan: None, + )) + case recorded { + Some(identity) -> identity + None -> + account_identity( + present_text(credential, "accountId"), + present_text(credential, "email"), + credentials.text(credential, "refresh"), + ) + } +} + +/// Record the subscription an older sign-in belongs to, read from the +/// account profile its access token reaches, so a later sign-in to the same +/// account replaces it. Only fields absent from the record are written, and +/// its `accountId`, which selection names it by, is kept. +pub fn record_subscription(stored: credentials.Stored(Account)) -> Nil { + let raw = credentials.value(stored) + use <- bool.guard(option.is_some(raw.account_uuid) || raw.access == "", Nil) + let found = subscriber(raw.access) + case found.account { + None -> Nil + Some(_) -> { + let fields = + [ + #("accountUuid", found.account), + #("organizationUuid", found.organization), + #("organizationName", found.organization_name), + #("plan", found.plan), + ] + |> list.filter_map(fn(field) { + case field.1 { + Some(text) -> Ok(#(field.0, json.string(text))) + None -> Error(Nil) + } + }) + let _ = + credentials.renew( + stored, + decoder(), + identity, + fn(_) { json.object(fields) }, + Ok, + ) + Nil + } + } } fn present_text(credential: Dynamic, field: String) -> Option(String) { @@ -140,6 +204,18 @@ fn first( pub fn renew( stored: credentials.Stored(Account), +) -> Result(credentials.Stored(Account), String) { + case refresh_stored(stored) { + Error(reason) if reason == refused -> { + let _ = credentials.refuse(stored) + Error(reason) + } + other -> other + } +} + +fn refresh_stored( + stored: credentials.Stored(Account), ) -> Result(credentials.Stored(Account), String) { use _ <- result.try(valid_expiry(credentials.value(stored))) case @@ -176,6 +252,7 @@ pub fn renew( ..updated, account_id: Some(identity(current)), email: current.email, + account_uuid: current.account_uuid, ) } } @@ -191,6 +268,100 @@ fn valid_expiry(account: Account) -> Result(Nil, String) { } } +/// When a 429 from Claude's subscription API ends, in Unix milliseconds, +/// read from its response headers at `now_ms`. The header names follow +/// Anthropic's rate-limit documentation; no captured response was available +/// to check them against. A `rejected` unified status names the windows +/// that refused the request (`anthropic-ratelimit-unified-5h-status` and +/// `-7d-status`); the latest of their resets (`-5h-reset`, `-7d-reset`, +/// epoch seconds) is when the account has room again. Without per-window +/// statuses the overall `anthropic-ratelimit-unified-reset` is used. Then +/// `retry-after` (seconds), and else a minute. +pub fn limit_until(headers: List(#(String, String)), now_ms: Int) -> Int { + let header = fn(name) { + list.find_map(headers, fn(header) { + case string.lowercase(header.0) == name { + True -> Ok(string.trim(header.1)) + False -> Error(Nil) + } + }) + } + let epoch = fn(name) { + header(name) + |> result.try(int.parse) + |> result.map(fn(seconds) { seconds * 1000 }) + |> result.try(fn(at) { + case at > now_ms { + True -> Ok(at) + False -> Error(Nil) + } + }) + } + let rejected = fn(name) { header(name) == Ok("rejected") } + let unified = case rejected("anthropic-ratelimit-unified-status") { + False -> [] + True -> { + let windows = + [ + #("5h", rejected("anthropic-ratelimit-unified-5h-status")), + #("7d", rejected("anthropic-ratelimit-unified-7d-status")), + ] + |> list.filter_map(fn(window) { + case window.1 { + True -> + epoch("anthropic-ratelimit-unified-" <> window.0 <> "-reset") + False -> Error(Nil) + } + }) + case windows { + [] -> result.values([epoch("anthropic-ratelimit-unified-reset")]) + _ -> windows + } + } + } + case list.reduce(unified, int.max) { + Ok(until) -> until + Error(Nil) -> + case header("retry-after") |> result.try(int.parse) { + Ok(seconds) if seconds > 0 -> now_ms + seconds * 1000 + _ -> now_ms + default_limit_ms + } + } +} + +/// How long a 429 without a usable reset keeps a Claude account aside. +const default_limit_ms = 60_000 + +/// Record a limit on the saved account `stored` until `until`. +pub fn limit(stored: credentials.Stored(Account), until: Int) -> Nil { + let _ = credentials.mark(stored, until, None) + Nil +} + +/// Whether the profile has another ready account than `stored` for a +/// request to move to. +pub fn room( + home: String, + profile: String, + stored: credentials.Stored(Account), +) -> Bool { + let used = identity(credentials.value(stored)) + let now = albedo_clock.system_ms() + credentials.accounts(home, "anthropic", decoder()) + |> result.try(credentials.bound(home, profile, _)) + |> result.map(fn(bound) { + credentials.order("claude", bound, "", identity, None) + |> list.any(fn(value) { + let account = credentials.value(value) + identity(account) != used + && credentials.until(value, None) <= now + && account.access != "" + && account.refresh != "" + }) + }) + |> result.unwrap(False) +} + pub const client_id = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" pub fn exchange( @@ -225,23 +396,33 @@ fn post( ) { Ok(#(200, body)) -> token(body) - Ok(#(status, body)) -> - Error( - "Anthropic " - <> kind - <> " failed (" - <> int.to_string(status) - <> "): " - <> { - bit_array.to_string(body) - |> result.unwrap("") - |> scalars.take(2048) - }, - ) + Ok(#(status, body)) if kind == "refresh" -> + case credentials.refused(status, body) { + True -> Error(refused) + False -> Error(failure(kind, status, body)) + } + Ok(#(status, body)) -> Error(failure(kind, status, body)) Error(_) -> Error("Anthropic token request failed") } } +/// What a refresh the token endpoint definitively refused returns; `renew` +/// marks the account as needing sign-in on it. +const refused = "Claude sign-in was refused; run /login to sign in again" + +fn failure(kind: String, status: Int, body: BitArray) -> String { + "Anthropic " + <> kind + <> " failed (" + <> int.to_string(status) + <> "): " + <> { + bit_array.to_string(body) + |> result.unwrap("") + |> scalars.take(2048) + } +} + /// The provider accepts numeric expires_in and subtracts its five-minute margin. pub fn token(body: BitArray) -> Result(Account, String) { let decoder = { @@ -269,6 +450,7 @@ pub fn token(body: BitArray) -> Result(Account, String) { ), Some(credentials.fingerprint(refresh)), None, + None, )) _ -> Error("Anthropic token response is incomplete") } @@ -284,6 +466,36 @@ pub fn encode(account: Account) -> json.Json { ]) } +/// The quota poller's report heals the account's limit mark: a window at 100 +/// percent keeps the account aside until the latest such window resets, so +/// rotation passes over it before a request hits the limit. A report with +/// room never clears a mark; marks end on their own. +pub fn heal( + home: String, + account: String, + limits: List(usage_feed.Limit), +) -> Nil { + let now = albedo_clock.system_ms() + let spent = + list.filter_map(limits, fn(limit) { + case limit.used_percent, limit.resets_at { + Some(used), Some(reset) if used >=. 100.0 && reset > now -> Ok(reset) + _, _ -> Error(Nil) + } + }) + case list.reduce(spent, int.max) { + Error(Nil) -> Nil + Ok(until) -> + credentials.accounts(home, "anthropic", decoder()) + |> result.unwrap([]) + |> list.filter(fn(stored) { + identity(credentials.value(stored)) == account + && credentials.until(stored, None) < until + }) + |> list.each(limit(_, until)) + } +} + pub fn quota(home: String) -> List(#(String, json.Json)) { credentials.accounts(home, "anthropic", decoder()) |> result.unwrap([]) @@ -340,6 +552,111 @@ pub fn profile( } } +/// What the account profile says about a subscription. Each field is +/// `None` when the profile does not report it. +pub type Subscriber { + Subscriber( + account: Option(String), + organization: Option(String), + organization_name: Option(String), + email: Option(String), + plan: Option(String), + ) +} + +/// The account a subscription signs in to: the account UUID with its +/// organization's UUID, since one login can belong to several organizations, +/// each its own subscription. `None` without an account UUID. Never the +/// email: several accounts can share one. +pub fn subscription_identity(subscriber: Subscriber) -> Option(String) { + case subscriber.account, subscriber.organization { + Some(account), Some(organization) -> Some(account <> ":" <> organization) + Some(account), None -> Some(account) + None, _ -> None + } +} + +/// The subscription behind an access token, from the account profile. A +/// profile that cannot be read reports nothing; signing in does not depend +/// on it. +pub fn subscriber(access: String) -> Subscriber { + let unknown = Subscriber(None, None, None, None, None) + case + http.get( + "https://api.anthropic.com/api/oauth/profile", + [#("authorization", "Bearer " <> access), #("accept", "application/json")], + buffered.Timeouts(15_000, 10_000), + ) + { + Ok(#(200, body)) -> parse_subscriber(body) |> result.unwrap(unknown) + _ -> unknown + } +} + +/// The account profile's `account` and `organization` objects as a +/// `Subscriber`. +pub fn parse_subscriber(body: BitArray) -> Result(Subscriber, Nil) { + let text = fn(name) { + decode.optional_field( + name, + None, + decode.one_of(decode.map(decode.string, nonempty), [ + decode.success(None), + ]), + decode.success, + ) + } + let flag = fn(name) { + decode.optional_field( + name, + False, + decode.one_of(decode.bool, [decode.success(False)]), + decode.success, + ) + } + let account = { + use uuid <- decode.then(text("uuid")) + use email <- decode.then(text("email")) + use max <- decode.then(flag("has_claude_max")) + use pro <- decode.then(flag("has_claude_pro")) + decode.success( + #(uuid, email, case max, pro { + True, _ -> Some("Max") + False, True -> Some("Pro") + False, False -> None + }), + ) + } + let organization = { + use uuid <- decode.then(text("uuid")) + use name <- decode.then(text("name")) + decode.success(#(uuid, name)) + } + let decoder = { + use account <- decode.field("account", account) + use organization <- decode.optional_field( + "organization", + #(None, None), + decode.one_of(organization, [decode.success(#(None, None))]), + ) + decode.success(Subscriber( + account.0, + organization.0, + organization.1, + account.1, + account.2, + )) + } + json.parse_bits(body, decoder) |> result.replace_error(Nil) +} + +fn nonempty(text: String) -> Option(String) { + case string.trim(text) { + "" -> None + text -> Some(text) + } +} + fn device(uuid: String) -> String { "albedo:claude-device:" <> digest.hex(digest.sha256(<>)) } diff --git a/src/albedo/harness/extensions/claude/extension.gleam b/src/albedo/harness/extensions/claude/extension.gleam index 4c6f087c2..66d614fb4 100644 --- a/src/albedo/harness/extensions/claude/extension.gleam +++ b/src/albedo/harness/extensions/claude/extension.gleam @@ -8,6 +8,7 @@ import albedo/harness/extensions/claude/files import albedo/harness/extensions/claude/search as claude_search import albedo/harness/extensions/claude/wire import albedo/harness/extensions/models/catalogue as models +import albedo_clock import albedo_model as types import albedo_sdk/credentials import albedo_sdk/extension @@ -23,6 +24,7 @@ import gleam/bool import gleam/dict import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode +import gleam/erlang/process import gleam/list import gleam/option.{type Option, None, Some} import gleam/result @@ -47,10 +49,12 @@ pub fn extension() -> extension.Extension { )), extension.SearchPlugin(web_search.Provider("claude", "Claude", search)), extension.SettingsPlugin(settings.declaration(search_settings())), - extension.QuotaPlugin(usage_feed.accounts_source( - "anthropic", - accounts.quota, - )), + extension.QuotaPlugin( + usage_feed.Source( + ..usage_feed.accounts_source("anthropic", accounts.quota), + heal: accounts.heal, + ), + ), ], extension.no_initialise, tables: [], @@ -86,12 +90,37 @@ fn login() -> oauth.Login { fn(grant, code, _progress) { accounts.exchange(code, grant.state, grant.verifier, grant.redirect) |> result.map(fn(value) { + // The account and organization UUIDs name the subscription across + // sign-ins, so signing in again replaces it in place; without them + // the token names it. + let found = accounts.subscriber(value.access) + let reported = + [ + #("email", found.email), + #("plan", found.plan), + #("accountUuid", found.account), + #("organizationUuid", found.organization), + #("organizationName", found.organization_name), + ] + |> list.filter_map(fn(field) { + case field.1 { + Some(text) -> Ok(#(field.0, dynamic.string(text))) + None -> Error(Nil) + } + }) dict.from_list([ #("type", dynamic.string("oauth")), #("access", dynamic.string(value.access)), #("refresh", dynamic.string(value.refresh)), #("expires", dynamic.int(option.unwrap(value.expires, 0))), - #("accountId", dynamic.string(accounts.identity(value))), + #( + "accountId", + dynamic.string(option.unwrap( + accounts.subscription_identity(found), + accounts.identity(value), + )), + ), + ..reported ]) }) }, @@ -125,8 +154,18 @@ fn resolve( types.ChatCompletions, rotation.Pool( current: fn() { authenticate(context, Some(auth.auth)) }, - // Claude has no account hopping or backoff on 429. - mark: fn(_, _) { Some(rotation.Marked(types.Lasting, False)) }, + // `stream` records a sign-in's limit from the 429's headers. The + // request then moves to another ready account of the profile: the + // session would move there on its next turn anyway, its prompt cache + // is lost either way, and moving now saves sending the message again. + // A Claude 429 is never waited out. + mark: fn(connection, _) { + let room = case connection.stored { + Some(stored) -> accounts.room(context.home, context.profile, stored) + None -> False + } + Some(rotation.Marked(types.Lasting, room)) + }, same: fn(a, b) { a.auth == b.auth }, stream: fn(connection, request, on_event) { let auth = connection.auth @@ -153,16 +192,34 @@ fn resolve( endpoint, request, ) - wire.stream_for_mode( - context.home, - auth, - extension.within_listed_efforts( - request, - lookup(request.model, None), - ), - context.fast, - on_event, - ) + let refused = process.new_subject() + let outcome = + wire.stream_for_mode( + context.home, + auth, + extension.within_listed_efforts( + request, + lookup(request.model, None), + ), + context.fast, + fn(event) { + case event { + types.RefusalHeaders(429, headers) -> + process.send(refused, headers) + _ -> Nil + } + on_event(event) + }, + ) + case outcome, connection.stored { + Error(types.Refused(_, Some(429), _)), Some(stored) -> + process.receive(refused, 0) + |> result.unwrap([]) + |> accounts.limit_until(albedo_clock.system_ms()) + |> accounts.limit(stored, _) + _, _ -> Nil + } + outcome }, reject: fn(connection) { expire(connection) }, ), @@ -287,6 +344,9 @@ fn authenticate( _ -> accounts.profile(access, context.session) |> result.map(fn(profile) { + // An older sign-in learns its subscription once, so signing in + // to it again replaces it in place. + accounts.record_subscription(stored) wire.Subscription(access, profile.0, profile.1, profile.2) }) }) @@ -380,11 +440,21 @@ fn unlisted_info(id: String) -> Option(extension.ModelInfo) { /// Login shares the account identity rule with refresh and selection. fn account(credential: Dynamic) -> oauth.Account { case decode.run(credential, decode.dict(decode.dynamic, decode.dynamic)) { - Error(_) -> oauth.Account("", "invalid Claude account", "", False) + Error(_) -> oauth.account("", "invalid Claude account", "", False) Ok(_) -> { // A stored id that is not text has no name /login can show. let id = accounts.login_identity(credential) - oauth.Account(id, "Claude Pro/Max", "", oauth.selected(credential)) + oauth.Account( + ..oauth.account( + id, + "Claude Pro/Max", + credentials.text(credential, "organizationName"), + oauth.selected(credential), + ), + email: oauth.reported(credential, "email"), + plan: oauth.reported(credential, "plan"), + workspace: oauth.reported(credential, "organizationName"), + ) } } } diff --git a/src/albedo/harness/extensions/codex/accounts.gleam b/src/albedo/harness/extensions/codex/accounts.gleam index ee769644b..3e577f200 100644 --- a/src/albedo/harness/extensions/codex/accounts.gleam +++ b/src/albedo/harness/extensions/codex/accounts.gleam @@ -4,19 +4,16 @@ import albedo_bytes/scalars import albedo_clock import albedo_http/buffered import albedo_model as types -import albedo_sdk/credential_store import albedo_sdk/credentials import albedo_sdk/http import albedo_sdk/oauth import albedo_sdk/rotation -import albedo_sdk/settings_store import albedo_sdk/usage_feed import gleam/bit_array import gleam/bool import gleam/dict import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode -import gleam/erlang/atom import gleam/float import gleam/int import gleam/json @@ -75,19 +72,60 @@ fn first(values: List(String)) -> String { list.find(values, fn(value) { value != "" }) |> result.unwrap("") } +/// The account a credential signs in to: the user and the workspace +/// (`chatgpt_account_id`) together, since one person can sign in to several +/// workspaces on one email and one workspace holds several people. Never the +/// email. A record without either falls back to its token's fingerprint. pub fn identity(value: Account) -> String { - let #(id, user, _, _) = claims(value.access) - first([ - user, - value.user_id, - id, - value.account_id, - string.lowercase(value.email), - case value.refresh { - "" -> "" - refresh -> credentials.fingerprint(refresh) - }, - ]) + let #(workspace, member, _, _) = claims(value.access) + let workspace = first([workspace, value.account_id]) + let user = first([person(value.access), member, value.user_id]) + case workspace, user { + "", "" -> + case value.refresh { + "" -> "" + refresh -> credentials.fingerprint(refresh) + } + workspace, "" -> workspace + "", user -> user + workspace, user -> user <> "@" <> workspace + } +} + +/// The token's user: the auth claim's `chatgpt_user_id`, else its `sub`. +/// Empty for a token that is not a readable JWT. +pub fn person(token: String) -> String { + let decoder = { + use auth <- decode.optional_field( + "https://api.openai.com/auth", + "", + decode.optional_field( + "chatgpt_user_id", + "", + decode.one_of(decode.string, [decode.success("")]), + decode.success, + ), + ) + use subject <- decode.optional_field( + "sub", + "", + decode.one_of(decode.string, [decode.success("")]), + ) + decode.success(first([auth, subject])) + } + case string.split(token, ".") { + [_, payload, _] -> + case string.contains(payload, "+") || string.contains(payload, "/") { + True -> "" + False -> + bit_array.base64_url_decode(payload) + |> result.try(fn(bytes) { + json.parse_bits(bytes, decoder) |> result.replace_error(Nil) + }) + |> result.unwrap("") + } + _ -> "" + } } pub fn account_id(value: Account) -> String { @@ -219,6 +257,22 @@ fn choose( pub fn renew( stored: credentials.Stored(Account), +) -> Result(credentials.Stored(Account), String) { + case refresh_stored(stored) { + Error(reason) if reason == refused -> { + let _ = credentials.refuse(stored) + Error(reason) + } + other -> other + } +} + +/// What a refresh the token endpoint definitively refused returns; `renew` +/// marks the account as needing sign-in on it. +const refused = "ChatGPT sign-in was refused; run /login to sign in again" + +fn refresh_stored( + stored: credentials.Stored(Account), ) -> Result(credentials.Stored(Account), String) { case option.unwrap(credentials.value(stored).expires, 0) @@ -285,8 +339,12 @@ fn refresh(previous: Account) -> Result(Account, String) { ]) { Ok(#(200, body)) -> parse_refresh(body, previous) - Ok(#(status, _)) -> - Error("Codex token refresh failed (" <> int.to_string(status) <> ")") + Ok(#(status, body)) -> + case credentials.refused(status, body) { + True -> Error(refused) + False -> + Error("Codex token refresh failed (" <> int.to_string(status) <> ")") + } Error(_) -> Error("Codex token refresh failed") } } @@ -423,24 +481,38 @@ pub fn encode(value: Account) -> json.Json { } pub fn quota(home: String) -> List(#(String, json.Json)) { - credentials.accounts(home, "openai-codex", decoder()) - |> result.unwrap([]) - |> list.filter(fn(stored) { credentials.value(stored).access != "" }) - |> list.map(fn(stored) { - let ready = case valid(credentials.value(stored)) { - True -> renew(stored) |> result.unwrap(stored) - False -> stored - } - let value = credentials.value(ready) + let entries = + credentials.accounts(home, "openai-codex", decoder()) + |> result.unwrap([]) + |> list.filter(fn(stored) { credentials.value(stored).access != "" }) + |> list.map(fn(stored) { + let ready = case valid(credentials.value(stored)) { + True -> renew(stored) |> result.unwrap(stored) + False -> stored + } + let value = credentials.value(ready) + #( + first([ + email(value), + account_id(value), + case value.refresh { + "" -> "" + refresh -> credentials.fingerprint(refresh) + }, + ]), + value, + ) + }) + // Several accounts can share an email: those are labelled by their + // workspace too, so their readings stay apart. + list.map(entries, fn(entry) { + let #(label, value) = entry + let shared = list.count(entries, fn(other) { other.0 == label }) > 1 #( - first([ - email(value), - account_id(value), - case value.refresh { - "" -> "" - refresh -> credentials.fingerprint(refresh) - }, - ]), + case shared { + True -> label <> " · " <> account_id(value) + False -> label + }, usage_feed.oauth_credential( value.access, [#("accountId", value.account_id), #("email", value.email)], @@ -491,220 +563,14 @@ fn describe(value: Account) -> String { } } -/// Drops the account whose access token the server rejected, so the next -/// turn picks a sibling or asks for /login instead of replaying a revoked -/// token. Profiles that rotate through it stop naming it, in the same -/// journaled settings commit. Returns the removed account's email, or `""` -/// when none is recorded. -pub fn revoke( - home: String, - stored: credentials.Stored(Account), -) -> Result(String, String) { - let value = credentials.value(stored) - let public_id = credentials.public_id(stored) - with_credentials_lock(home, fn() { - remove_revoked(home, public_id, value.access, value.refresh) - }) -} - -/// Where creds.json keeps Codex accounts. -const store_key = "openai-codex" - -fn remove_revoked( - home: String, - public_id: String, - access: String, - refresh: String, -) -> Result(String, String) { - case stored_accounts(home) { - Error(True) -> Ok("") - Error(False) -> Error("stored Codex credentials are unreadable") - Ok(data) -> { - let #(rejected, kept) = - oauth_values(data, store_key) - |> list.partition(fn(value) { - field_is(value, "access", access) - && field_is(value, "refresh", refresh) - && { - public_id == "" || field_is(value, "_albedo_account_id", public_id) - } - }) - case rejected { - [] -> Ok("") - [removed, ..] -> { - let ids = - list.filter_map(rejected, fn(value) { - decode.run( - value, - decode.at(["_albedo_account_id"], decode.dynamic), - ) - }) - case remove_accounts(home, put_values(data, store_key, kept), ids) { - Ok(Nil) -> Ok(public_email(removed)) - Error(Nil) -> Error("could not remove revoked Codex credential") - } - } - } - } - } -} - -/// Whether a stored credential's field equals `expected`, a missing field -/// counting as `""`. -fn field_is(value: Dynamic, key: String, expected: String) -> Bool { - decode.run(value, field_or(key, dynamic.string(""), decode.dynamic)) - == Ok(dynamic.string(expected)) -} - -fn field_or( - key: String, - default: a, - decoder: decode.Decoder(a), -) -> decode.Decoder(a) { - use value <- decode.optional_field(key, default, decoder) - decode.success(value) -} - -/// The accounts section with `values` stored under `key`: none removes it, -/// one is stored bare, more as a list. -fn put_values( - data: dict.Dict(String, Dynamic), - key: String, - values: List(Dynamic), -) -> dict.Dict(String, Dynamic) { - case values { - [] -> dict.delete(data, key) - [one] -> dict.insert(data, key, one) - many -> dict.insert(data, key, dynamic.list(many)) - } -} - -fn remove_accounts( - home: String, - accounts: dict.Dict(String, Dynamic), - removed_ids: List(Dynamic), -) -> Result(Nil, Nil) { - let object = decode.dict(decode.string, decode.dynamic) - use config <- result.try(read_settings(home, "config.json")) - use creds <- result.try(read_settings(home, "creds.json")) - use profiles <- result.try( - decode.run(config, field_or("providers", dict.new(), object)) - |> result.replace_error(Nil), - ) - use updated <- result.try( - dict.to_list(profiles) - |> list.try_map(fn(entry) { - use profile <- result.map( - decode.run(entry.1, object) |> result.replace_error(Nil), - ) - #(entry.0, prune_rotation(profile, entry.1, removed_ids)) - }) - |> result.map(dict.from_list), - ) - use creds <- result.try( - decode.run(creds, object) |> result.replace_error(Nil), - ) - let documents = - dict.from_list([ - #( - "creds.json", - to_dynamic(dict.insert(creds, "accounts", to_dynamic(accounts))), - ), - ]) - use documents <- result.try(case updated == profiles { - True -> Ok(documents) - False -> { - use config <- result.map( - decode.run(config, object) |> result.replace_error(Nil), - ) - dict.insert( - documents, - "config.json", - to_dynamic(dict.insert(config, "providers", to_dynamic(updated))), - ) - } - }) - commit_settings(home, documents) -} - -/// A profile that rotates through removed accounts keeps the rest. When none -/// remain it pins the first account it named instead. -fn prune_rotation( - profile: dict.Dict(String, Dynamic), - raw: Dynamic, - removed_ids: List(Dynamic), -) -> Dynamic { - case dict.get(profile, "accountIds") { - Ok(ids) -> - case decode.run(ids, decode.list(decode.dynamic)) { - Ok([first, ..] as ids) -> - case list.filter(ids, fn(id) { !list.contains(removed_ids, id) }) { - [] -> - profile - |> dict.insert("accountId", first) - |> dict.delete("accountIds") - |> to_dynamic - kept -> - profile - |> dict.insert("accountIds", dynamic.list(kept)) - |> to_dynamic - } - _ -> raw - } - Error(Nil) -> raw - } -} - -fn to_dynamic(object: dict.Dict(String, Dynamic)) -> Dynamic { - object - |> dict.to_list - |> list.map(fn(entry) { #(dynamic.string(entry.0), entry.1) }) - |> dynamic.properties -} - -/// Runs `run` under the settings lock of the credential store's directory. -/// A busy lock answers an error. -fn with_credentials_lock( - home: String, - run: fn() -> Result(String, String), -) -> Result(String, String) { - settings_store.lock(credential_store.directory(home), run, fn(failure) { - Error(settings_store.reason(failure, busy: "credential store is busy")) - }) -} - -/// The accounts section of creds.json, or whether it is missing. -fn stored_accounts(home: String) -> Result(dict.Dict(String, Dynamic), Bool) { - credential_store.accounts(credential_store.path(home)) - |> result.map_error(fn(reason) { reason == atom.create("enoent") }) -} - -/// The OAuth credentials stored under `key`. -fn oauth_values( - data: dict.Dict(String, Dynamic), - key: String, -) -> List(Dynamic) { - credential_store.oauth(data, key) |> list.map(credential_store.to_dynamic) -} - -fn read_settings(home: String, name: String) -> Result(Dynamic, Nil) { - settings_store.guarded(fn() { - Ok(settings_store.read_dynamic(credential_store.directory(home), name)) - }) - |> result.replace_error(Nil) -} - -/// Commits the documents together through the settings recovery journal. -fn commit_settings( - home: String, - documents: dict.Dict(String, Dynamic), -) -> Result(Nil, Nil) { - settings_store.guarded(fn() { - let _ = - settings_store.commit_group(credential_store.directory(home), documents) - Ok(Nil) - }) - |> result.replace_error(Nil) +/// Marks the account whose access token the server rejected as needing +/// sign-in, so the next turn picks a sibling or asks for /login instead of +/// replaying a revoked token. The account keeps its place in every profile +/// and signing in again clears the mark. Returns the account's email, or +/// `""` when none is recorded. +pub fn revoke(stored: credentials.Stored(Account)) -> Result(String, String) { + use _ <- result.map(credentials.refuse(stored)) + email(credentials.value(stored)) } pub fn explicit(home: String, profile: String) -> Bool { diff --git a/src/albedo/harness/extensions/codex/extension.gleam b/src/albedo/harness/extensions/codex/extension.gleam index 9c7f5867f..17e3aaa8f 100644 --- a/src/albedo/harness/extensions/codex/extension.gleam +++ b/src/albedo/harness/extensions/codex/extension.gleam @@ -357,7 +357,7 @@ fn profile_pool_with_fast( reject: fn(client) { case accounts.explicit(home, profile) { True -> { - let _ = accounts.revoke(home, client.stored) + let _ = accounts.revoke(client.stored) Nil } False -> Nil @@ -482,8 +482,9 @@ fn limited( /// Explains a Codex failure that changes which account should be used. /// /// A 401 means the ChatGPT sign-in was revoked or expired server-side; -/// refreshing cannot recover it. The account is removed from creds.json and the -/// message ends in "run /login", which clients treat as a prompt to sign in again. +/// refreshing cannot recover it. The account is marked as needing sign-in and +/// the message ends in "run /login", which clients treat as a prompt to sign +/// in again. /// /// A limit 429 marks the account limited until its reset. By the time this /// explains one, the rotation has already tried every sibling with room. @@ -508,12 +509,14 @@ pub fn profile_failure( !accounts.explicit(home, profile), Some("ChatGPT sign-in was revoked; run /login"), ) - let message = case accounts.revoke(home, client.stored) { - Ok("") -> "ChatGPT sign-in was revoked and has been removed" + let message = case accounts.revoke(client.stored) { + Ok("") -> "ChatGPT sign-in was revoked and needs signing in again" Ok(email) -> - "ChatGPT sign-in for " <> email <> " was revoked and has been removed" + "ChatGPT sign-in for " + <> email + <> " was revoked and needs signing in again" Error(reason) -> - "ChatGPT sign-in was revoked but could not be removed (" + "ChatGPT sign-in was revoked but could not be marked (" <> reason <> ")" } @@ -560,12 +563,19 @@ fn login_account(credential: Dynamic) -> oauth.Account { plan -> name <> " · " <> plan } oauth.Account( - id: accounts.identity(account), - label:, - detail: oauth.limit_detail(credential, albedo_clock.system_ms()), - selected: oauth.selected(credential), + ..oauth.account( + id: accounts.identity(account), + label:, + detail: oauth.limit_detail(credential, albedo_clock.system_ms()), + selected: oauth.selected(credential), + ), + email: case accounts.email(account) { + "" -> None + email -> Some(email) + }, + plan: oauth.plan(accounts.plan(account)), ) } - _, _ -> oauth.Account("", "invalid chatgpt account", "", False) + _, _ -> oauth.account("", "invalid chatgpt account", "", False) } } diff --git a/src/albedo/harness/extensions/colab/extension.gleam b/src/albedo/harness/extensions/colab/extension.gleam index 2e46c3040..6cc6e0946 100644 --- a/src/albedo/harness/extensions/colab/extension.gleam +++ b/src/albedo/harness/extensions/colab/extension.gleam @@ -144,13 +144,16 @@ fn exchange( fn account(credential: Dynamic) -> oauth.Account { case decode.run(credential, decode.dict(decode.dynamic, decode.dynamic)) { - Error(_) -> oauth.Account("colab", "colab", "", False) + Error(_) -> oauth.account("colab", "colab", "", False) Ok(_) -> { let email = case credentials.text(credential, "email") { "" -> "google-colab account" email -> email } - oauth.Account(email, email, "", oauth.selected(credential)) + oauth.Account( + ..oauth.account(email, email, "", oauth.selected(credential)), + email: oauth.reported(credential, "email"), + ) } } } diff --git a/src/albedo/harness/extensions/github_copilot/extension.gleam b/src/albedo/harness/extensions/github_copilot/extension.gleam index e36848871..edf5d1d7a 100644 --- a/src/albedo/harness/extensions/github_copilot/extension.gleam +++ b/src/albedo/harness/extensions/github_copilot/extension.gleam @@ -210,7 +210,7 @@ fn account(credential: Dynamic) -> oauth.Account { |> result.unwrap("GitHub Copilot") kind_account(id, label, "github copilot · oauth", credential) } - _, "" -> oauth.Account("", "invalid GitHub Copilot account", "", False) + _, "" -> oauth.account("", "invalid GitHub Copilot account", "", False) _, key -> { let id = rotation.key_label(key) let label = case credentials.text(credential, "label") { @@ -230,7 +230,7 @@ fn kind_account( credential: Dynamic, ) -> oauth.Account { case oauth.selected(credential) { - True -> oauth.Account(id, label, kind <> " · selected", True) - False -> oauth.Account(id, label, kind, False) + True -> oauth.account(id, label, kind <> " · selected", True) + False -> oauth.account(id, label, kind, False) } } diff --git a/src/albedo/harness/extensions/mcp/oauth.gleam b/src/albedo/harness/extensions/mcp/oauth.gleam index 50d372a7b..c1ea6d34c 100644 --- a/src/albedo/harness/extensions/mcp/oauth.gleam +++ b/src/albedo/harness/extensions/mcp/oauth.gleam @@ -1085,7 +1085,7 @@ pub fn account(name: String, credential: Dynamic) -> oauth.Account { let label = decode.run(credential, decode.at(["label"], decode.string)) |> result.unwrap(name) - oauth.Account("mcp:" <> name, label, "MCP server " <> name, False) + oauth.account("mcp:" <> name, label, "MCP server " <> name, False) } /// Creds with this server's signed-in credential in place, keeping the diff --git a/src/albedo/harness/extensions/mistral/extension.gleam b/src/albedo/harness/extensions/mistral/extension.gleam index 191a0ef35..bae2d493a 100644 --- a/src/albedo/harness/extensions/mistral/extension.gleam +++ b/src/albedo/harness/extensions/mistral/extension.gleam @@ -197,14 +197,14 @@ fn list_models( /// How /login names a saved key: its label, else its masked key. fn account(credential: Dynamic) -> oauth.Account { case credentials.text(credential, "apiKey") { - "" -> oauth.Account("", "invalid Mistral account", "", False) + "" -> oauth.account("", "invalid Mistral account", "", False) key -> { let id = rotation.key_label(key) let label = case credentials.text(credential, "label") { "" -> id label -> label } - oauth.Account(id, label, "", oauth.selected(credential)) + oauth.account(id, label, "", oauth.selected(credential)) } } } diff --git a/src/albedo/harness/extensions/opencode_go/extension.gleam b/src/albedo/harness/extensions/opencode_go/extension.gleam index 2741b9349..ee1ea2527 100644 --- a/src/albedo/harness/extensions/opencode_go/extension.gleam +++ b/src/albedo/harness/extensions/opencode_go/extension.gleam @@ -235,13 +235,16 @@ fn with_detail(prefix: String, detail: String) -> String { /// Login uses the account policy while retaining incomplete legacy rows. fn account(credential: Dynamic) -> oauth.Account { case decode.run(credential, decode.dict(decode.dynamic, decode.dynamic)) { - Error(_) -> oauth.Account("", "invalid OpenCode Go account", "", False) + Error(_) -> oauth.account("", "invalid OpenCode Go account", "", False) Ok(_) -> oauth.Account( - id: accounts.login_identity(credential), - label: accounts.login_label(credential), - detail: oauth.limit_detail(credential, albedo_clock.system_ms()), - selected: oauth.selected(credential), + ..oauth.account( + id: accounts.login_identity(credential), + label: accounts.login_label(credential), + detail: oauth.limit_detail(credential, albedo_clock.system_ms()), + selected: oauth.selected(credential), + ), + email: oauth.reported(credential, "email"), ) } } diff --git a/src/albedo/harness/extensions/proxy/chat.gleam b/src/albedo/harness/extensions/proxy/chat.gleam index 8567dea00..f87790d56 100644 --- a/src/albedo/harness/extensions/proxy/chat.gleam +++ b/src/albedo/harness/extensions/proxy/chat.gleam @@ -740,6 +740,7 @@ pub fn delta(reply: Reply, event: types.Event) -> Option(Json) { types.ArgumentsDelta(..) | types.Started(_) | types.Responded(_) + | types.RefusalHeaders(..) | types.Metered(..) | types.Served(..) | types.Billed(_) -> None diff --git a/src/albedo/harness/settings/projection.gleam b/src/albedo/harness/settings/projection.gleam index c8fcdbf03..8f11bebe4 100644 --- a/src/albedo/harness/settings/projection.gleam +++ b/src/albedo/harness/settings/projection.gleam @@ -4,6 +4,7 @@ import albedo_clock import albedo_model as types import albedo_sdk/cache_ttl +import albedo_sdk/credential_store import albedo_sdk/profiles as configuration import albedo_sdk/settings/declared import albedo_sdk/settings_store @@ -28,6 +29,7 @@ type Profile { image_edge: Dynamic, account_id: Dynamic, account_ids: Dynamic, + rotation: Dynamic, project: Dynamic, location: Dynamic, has_key: Bool, @@ -247,12 +249,21 @@ fn profile( value(fields, "imageEdge", null()), value(fields, "accountId", null()), value(fields, "accountIds", null()), + rotation(value(fields, "rotation", null())), value(fields, "project", null()), value(fields, "location", null()), has_key || pinned_key(creds, saved), )) } +/// A saved rotation as the API names it: `failover` unless it is `spread` or +/// `first`. +fn rotation(saved: Dynamic) -> Dynamic { + dynamic.string( + credential_store.rotation_name(credential_store.rotation(saved)), + ) +} + fn pinned_key(creds: Dynamic, profile: configuration.SavedProfile) -> Bool { case profile.account_id { None -> False @@ -289,6 +300,7 @@ fn profile_value(profile: Profile) -> Dynamic { #("image_edge", profile.image_edge), #("account_id", profile.account_id), #("account_ids", profile.account_ids), + #("rotation", profile.rotation), #("project", profile.project), #("location", profile.location), #("has_key", dynamic.bool(profile.has_key)), diff --git a/test/e2e/account_rotation_test.py b/test/e2e/account_rotation_test.py index e9ad384a3..67c99a99a 100644 --- a/test/e2e/account_rotation_test.py +++ b/test/e2e/account_rotation_test.py @@ -140,13 +140,16 @@ class AccountRotationTest(unittest.TestCase): self.assertEqual( self.provider.requests[-1]["authorization"], "Bearer saved-secret" ) - self.problem( - app, f"/auth/accounts/{account_id}", method="DELETE", code="account_in_use" + self.assertEqual( + {key: account[key] for key in ("email", "plan", "needs_sign_in")}, + {"email": None, "plan": None, "needs_sign_in": False}, ) - self.patch_profile(app, account_id=None) + # Signing out a pinned account succeeds and unpins the profile. with app.api(f"/auth/accounts/{account_id}", method="DELETE") as response: self.assertEqual(response.status, 204) self.assertNotIn(account_id, [row["id"] for row in self.accounts(app)]) + profile = self.read(app, "/settings?group=providers")["profiles"][app.profile] + self.assertIsNone(profile["account_id"]) def test_legacy_key_patch_reuses_account_and_null_only_unpins(self): app = self.app_for() @@ -372,7 +375,7 @@ class AccountRotationTest(unittest.TestCase): self.assertEqual(rows[-1]["outcome"], "completed") self.assertEqual(rows[-1]["account_id"], "available") - def test_deleting_rotation_member_updates_profiles_but_cannot_empty_rotation(self): + def test_deleting_rotation_members_updates_profiles_and_empties_to_null(self): app = self.app_for() _, first = self.save_key(app, "first-secret") _, second = self.save_key(app, "second-secret") @@ -381,16 +384,71 @@ class AccountRotationTest(unittest.TestCase): self.assertEqual(response.status, 204) profile = self.read(app, "/settings?group=providers")["profiles"][app.profile] self.assertEqual(profile["account_ids"], [second["id"]]) - self.problem( - app, - f"/auth/accounts/{second['id']}", - method="DELETE", - code="account_in_use", - ) self.turn(app) self.assertEqual( self.provider.requests[-1]["authorization"], "Bearer second-secret" ) + # The last member signs out too: the list becomes null. + with app.api(f"/auth/accounts/{second['id']}", method="DELETE") as response: + self.assertEqual(response.status, 204) + profile = self.read(app, "/settings?group=providers")["profiles"][app.profile] + self.assertIsNone(profile["account_ids"]) + self.assertIsNone(profile["account_id"]) + + def test_rotation_is_validated_and_defaults_to_failover(self): + app = self.app_for() + profile = self.read(app, "/settings?group=providers")["profiles"][app.profile] + self.assertEqual(profile["rotation"], "failover") + route = "/settings?group=providers" + with app.api(route) as response: + response.read() + etag = response.headers["ETag"] + with self.assertRaises(urllib.error.HTTPError) as caught: + app.api( + route, + {"profiles": {app.profile: {"rotation": "sometimes"}}}, + method="PATCH", + headers={"If-Match": etag}, + ) + with caught.exception as response: + self.assertEqual(response.code, 400) + self.assertEqual( + self.patch_profile(app, rotation="spread")["rotation"], "spread" + ) + self.assertEqual(self.patch_profile(app, rotation=None)["rotation"], "failover") + + def test_spread_starts_each_session_on_the_next_key_and_keeps_it(self): + app = self.app_for() + _, first = self.save_key(app, "first-secret", label="first") + _, second = self.save_key(app, "second-secret", label="second") + self.patch_profile( + app, account_ids=[first["id"], second["id"]], rotation="spread" + ) + used = [] + sessions = [app.session(name=f"spread {index}") for index in range(3)] + for session in sessions + sessions[:1]: + self.turn(app, session) + used.append(self.provider.requests[-1]["authorization"]) + # Sessions take turns, and a session's later turns keep its key. + self.assertEqual(used[0], used[2]) + self.assertNotEqual(used[0], used[1]) + self.assertEqual(used[3], used[0]) + self.assertEqual(set(used), {"Bearer first-secret", "Bearer second-secret"}) + + def test_first_never_leaves_the_first_key(self): + app = self.app_for(lambda _request: quota_error()) + _, first = self.save_key(app, "first-secret", label="first") + _, second = self.save_key(app, "second-secret", label="second") + self.patch_profile( + app, account_ids=[first["id"], second["id"]], rotation="first" + ) + session = self.turn(app) + self.turn(app, session) + self.assertTrue(self.provider.requests) + self.assertEqual( + {r["authorization"] for r in self.provider.requests}, + {"Bearer first-secret"}, + ) def test_hand_edited_key_rows_leave_the_other_accounts_usable(self): app = self.app_for() diff --git a/test/e2e/fast_mode_test.py b/test/e2e/fast_mode_test.py index 1baa1d912..09c73d4a3 100644 --- a/test/e2e/fast_mode_test.py +++ b/test/e2e/fast_mode_test.py @@ -301,7 +301,7 @@ class CodexFastModeTests(unittest.TestCase): cleared["session"]["configuration_resource"]["value"]["cyber_access"] ) - def test_blue_initial_preview_matches_unpinned_account_at_creation(self): + def test_blue_initial_preview_matches_the_account_a_new_session_gets(self): import hashlib def prepare_dual(app): @@ -345,44 +345,45 @@ class CodexFastModeTests(unittest.TestCase): path.write_text(json.dumps(cache)) app = self.app_with_codex(prepare=prepare_dual) - - def account_slot(identity): - value = 0x811C9DC5 - for byte in identity.encode(): - value = ((value ^ byte) * 16777619) & 0xFFFFFFFF - return value % 2 - - first = operation_id() - second = first[:-1] + ("1" if ord(first[-1]) % 2 == 0 else "0") - self.assertNotEqual(account_slot(first), account_slot(second)) - blue_id, ordinary_id = ( - (first, second) if account_slot(first) == 0 else (second, first) - ) - for session_id, status in ( - (blue_id, "supported"), - (ordinary_id, "unsupported"), + # Failover starts each new session on its list's first ready account, + # so the list order decides which account a new session gets. + config = json.loads((app.home / "config.json").read_text()) + unpinned = config["providers"]["codex-unpinned"] + unpinned.pop("accountId", None) + for name, order in ( + ("codex-blue", ["one", "two"]), + ("codex-plain", ["two", "one"]), + ): + config["providers"][name] = {**unpinned, "accountIds": order} + (app.home / "config.json").write_text(json.dumps(config)) + for profile, status in ( + ("codex-blue", "supported"), + ("codex-plain", "unsupported"), ): with app.api( - f"/models?provider_profile=codex-unpinned&model=fixture-codex" - f"&session={session_id}&initial=true" + f"/models?provider_profile={profile}&model=fixture-codex" + f"&session={operation_id()}&initial=true" ) as response: [model] = json.load(response)["items"] self.assertEqual(model["cyber_access"]["status"], status) body = { "kind": "new", "workspace": str(app.workspace), - "provider_profile": "codex-unpinned", + "provider_profile": "codex-blue", "model": "fixture-codex", "cyber_access": "daybreak_blue", } with app.api( - f"/sessions/{blue_id}", body, method="PUT", headers={"If-None-Match": "*"} + f"/sessions/{operation_id()}", + body, + method="PUT", + headers={"If-None-Match": "*"}, ) as response: self.assertEqual(json.load(response)["cyber_access"], "daybreak_blue") with self.assertRaises(urllib.error.HTTPError) as refused: app.api( - f"/sessions/{ordinary_id}", - body, + f"/sessions/{operation_id()}", + {**body, "provider_profile": "codex-plain"}, method="PUT", headers={"If-None-Match": "*"}, ) @@ -393,7 +394,7 @@ class CodexFastModeTests(unittest.TestCase): ) with app.api( f"/sessions/{operation_id()}", - {**body, "cyber_access": None}, + {**body, "provider_profile": "codex-plain", "cyber_access": None}, method="PUT", headers={"If-None-Match": "*"}, ) as response: diff --git a/test/e2e/opencode_go_login_test.py b/test/e2e/opencode_go_login_test.py index a13b3b56f..1aabe353c 100644 --- a/test/e2e/opencode_go_login_test.py +++ b/test/e2e/opencode_go_login_test.py @@ -97,6 +97,22 @@ class OpencodeGoLoginTests(unittest.TestCase): self.assertEqual(account["email"], "ana@example.com", account) self.assertGreaterEqual(account["expires"], lookups_finished_ms + 3_540_000) + # The new sign-in is named by its email and joins the profile that + # used the service without naming an account. + with app.api("/auth") as response: + [listed] = [ + row + for row in json.load(response)["accounts"] + if row["provider"] == "opencode-go" + ] + self.assertEqual(listed["label"], "ana@example.com", listed) + self.assertEqual(listed["email"], "ana@example.com", listed) + self.assertFalse(listed["needs_sign_in"], listed) + with app.api("/settings?group=providers") as response: + profile = json.load(response)["profiles"]["go"] + self.assertEqual(profile["account_ids"], [listed["id"]], profile) + self.assertEqual(profile["rotation"], "failover", profile) + # The code request carried the console's own client identity and asked # for an organization scope; the polls named the device code. code_request = self.console.requests("/auth/device/code")[0]["body"] diff --git a/test/harness/albedo_mistral_sign_in_test_support.erl b/test/harness/albedo_mistral_sign_in_test_support.erl index a40be98c7..7204e99b8 100644 --- a/test/harness/albedo_mistral_sign_in_test_support.erl +++ b/test/harness/albedo_mistral_sign_in_test_support.erl @@ -150,7 +150,7 @@ cancellation() -> fun( _ ) -> - {account, <<"key">>, <<"key">>, <<>>, false} + {account, <<"key">>, <<"key">>, <<>>, false, none, none, false, none} end, none}, Id = albedo_oauth_test_support:identity(), @@ -163,7 +163,8 @@ cancellation() -> <<"mistral">>, {some, Login}, none, - <<"{}">> + <<"{}">>, + fun() -> none end ), Worker = receive diff --git a/test/harness/codex_test.gleam b/test/harness/codex_test.gleam index 47dbe5452..ac7bdaf8e 100644 --- a/test/harness/codex_test.gleam +++ b/test/harness/codex_test.gleam @@ -7,10 +7,15 @@ import albedo/harness/extensions/codex/wire as codex_wire import albedo_clock import albedo_model as types import albedo_openai +import albedo_sdk/auth_accounts +import albedo_sdk/credential_store import albedo_sdk/credentials as credential_sdk import albedo_sdk/extension +import albedo_sdk/oauth import albedo_sdk/rotation import gleam/bit_array +import gleam/dict +import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/erlang/process import gleam/int @@ -78,7 +83,7 @@ pub fn session_pin_survives_credential_reordering_test() -> Nil { cleanup(root) } -pub fn revoked_codex_account_is_removed_test() -> Nil { +pub fn revoked_codex_account_needs_sign_in_test() -> Nil { let #(root, _, home) = fixture() let _ = write(home, "creds.json", credentials) let #(revoked, client) = codex_client(home, "revoked-session") @@ -465,7 +470,7 @@ pub fn stale_codex_attempt_cannot_limit_or_revoke_replacement_test() -> Nil { ), ) |> should.be_error - let assert Ok(_) = accounts.revoke(home, attempted.stored) + let assert Ok(_) = accounts.revoke(attempted.stored) let #(_, current) = codex_client(home, session) current.client.connection.api_key |> should.equal("replacement-access") cleanup(root) @@ -487,7 +492,143 @@ pub fn codex_refresh_without_rotated_refresh_or_claims_keeps_identity_test() -> previous, ) updated.refresh |> should.equal("retained-refresh") - accounts.identity(updated) |> should.equal("retained-seat") + accounts.identity(updated) |> should.equal("retained-seat@retained-account") accounts.account_id(updated) |> should.equal("retained-account") accounts.email(updated) |> should.equal("stored@example.test") } + +/// A ChatGPT access token whose claims name this user, workspace, email and +/// plan, as the OpenAI auth server issues them. +fn chatgpt_token(user: String, workspace: String, plan: String) -> String { + let claims = + json.object([ + #("sub", json.string("auth0|" <> user)), + #( + "https://api.openai.com/auth", + json.object([ + #("chatgpt_user_id", json.string(user)), + #("chatgpt_account_id", json.string(workspace)), + #("chatgpt_plan_type", json.string(plan)), + ]), + ), + #( + "https://api.openai.com/profile", + json.object([#("email", json.string("you@example.com"))]), + ), + ]) + |> json.to_string + "e30." <> bit_array.base64_url_encode(<>, False) <> ".sig" +} + +fn codex_login() -> oauth.Login { + let assert Ok(login) = + list.find_map(codex.extension().plugins, fn(plugin) { + case plugin { + extension.LoginPlugin(login) -> Ok(login) + _ -> Error(Nil) + } + }) + login +} + +/// Sign `token` in over `creds` as the sign-in service does, returning the +/// public id and the next document. +fn sign_in_codex(creds: Dynamic, token: String) -> #(String, Dynamic) { + let login = codex_login() + let credential = + dynamic.properties([ + #(dynamic.string("type"), dynamic.string("oauth")), + #(dynamic.string("access"), dynamic.string(token)), + #(dynamic.string("refresh"), dynamic.string("refresh-" <> token)), + #(dynamic.string("expires"), dynamic.int(9_999_999_999_999)), + ]) + auth_accounts.signed_in( + creds, + login.store, + credential, + login.account, + login.account(credential).id, + "codex", + ) +} + +fn codex_labels(creds: Dynamic) -> List(#(String, String)) { + let assert Ok(creds) = credential_store.object(creds) + let assert Ok(accounts) = + dict.get(creds, "accounts") |> result.try(credential_store.object) + credential_store.values(accounts, "openai-codex") + |> list.map(fn(value) { + let assert Ok(id) = credential_store.text(value, "_albedo_account_id") + let assert Ok(label) = credential_store.text(value, "label") + #(id, label) + }) +} + +/// One person with a personal and a business workspace on one email has two +/// accounts; two people in one workspace have two accounts; the same person +/// and workspace signing in again replaces their account in place. +pub fn chatgpt_accounts_are_a_user_in_a_workspace_test() -> Nil { + let empty = dynamic.properties([]) + let #(personal, creds) = + sign_in_codex(empty, chatgpt_token("user-ana", "ws-personal", "plus")) + let #(business, creds) = + sign_in_codex(creds, chatgpt_token("user-ana", "ws-business", "team")) + let #(colleague, creds) = + sign_in_codex(creds, chatgpt_token("user-bo", "ws-business", "team")) + { personal != business && business != colleague } |> should.be_true + codex_labels(creds) + |> should.equal([ + #(personal, "you@example.com"), + #(business, "you@example.com · Team"), + #(colleague, "you@example.com · #3"), + ]) + // Ana signs in to the business workspace again: same id, label and place. + let #(again, creds) = + sign_in_codex(creds, chatgpt_token("user-ana", "ws-business", "team")) + again |> should.equal(business) + codex_labels(creds) + |> should.equal([ + #(personal, "you@example.com"), + #(business, "you@example.com · Team"), + #(colleague, "you@example.com · #3"), + ]) + // Every account of the service joins a profile that rotates through them. + let config = + dynamic.properties([ + #( + dynamic.string("providers"), + dynamic.properties([ + #( + dynamic.string("chatgpt"), + dynamic.properties([ + #(dynamic.string("extension"), dynamic.string("codex")), + #( + dynamic.string("accountIds"), + dynamic.list([ + dynamic.string(personal), + dynamic.string(business), + ]), + ), + ]), + ), + ]), + ), + ]) + let joined = + auth_accounts.joined( + config, + creds, + "openai-codex", + "codex", + colleague, + None, + ) + decode.run( + joined, + decode.at( + ["providers", "chatgpt", "accountIds"], + decode.list(decode.string), + ), + ) + |> should.equal(Ok([personal, business, colleague])) +} diff --git a/test/harness/google_oauth_test.gleam b/test/harness/google_oauth_test.gleam index 3d5b85ac7..dd5e3d898 100644 --- a/test/harness/google_oauth_test.gleam +++ b/test/harness/google_oauth_test.gleam @@ -73,11 +73,23 @@ pub fn a_rotated_refresh_token_replaces_the_old_one_test() -> Nil { string.contains(stored, "r1") |> should.be_false } -pub fn a_rejected_refresh_keeps_the_stored_account_test() -> Nil { +pub fn a_refused_refresh_keeps_the_account_and_marks_it_for_sign_in_test() -> Nil { let #(result, stored, _) = refresh(accounts([stale]), #(400, "{\"error\":\"invalid_grant\"}")) - result |> should.equal(Error("Google Colab token refresh failed (400)")) + result + |> should.equal(Error( + "Google Colab sign-in was refused; run /login to sign in again", + )) + string.contains(stored, "\"access\":\"old\"") |> should.be_true + string.contains(stored, "\"needsSignIn\":true") |> should.be_true +} + +pub fn a_failed_refresh_keeps_the_account_unmarked_test() -> Nil { + let #(result, stored, _) = + refresh(accounts([stale]), #(500, "{\"error\":\"backend\"}")) + result |> should.equal(Error("Google Colab token refresh failed (500)")) string.contains(stored, "\"access\":\"old\"") |> should.be_true + string.contains(stored, "needsSignIn") |> should.be_false } pub fn an_account_without_a_refresh_token_is_invalid_test() -> Nil { diff --git a/test/harness/oauth_test.gleam b/test/harness/oauth_test.gleam index 8401596df..45b720276 100644 --- a/test/harness/oauth_test.gleam +++ b/test/harness/oauth_test.gleam @@ -10,7 +10,7 @@ import gleam/dynamic/decode import gleam/erlang/process import gleam/json import gleam/list -import gleam/option.{None, Some} +import gleam/option.{type Option, None, Some} import gleam/result import gleam/string import gleam/uri @@ -53,7 +53,10 @@ fn fake(callback: oauth.Callback) -> oauth.Login { let selected = decode.run(credential, decode.at(["selected"], decode.bool)) |> result.unwrap(False) - oauth.Account(email, email, "fake account", selected) + oauth.Account( + ..oauth.account(email, email, "fake account", selected), + email: option.Some(email), + ) }, None, ) @@ -84,10 +87,141 @@ fn start( Some(login), None, "{\"provider\":\"fake\"}", + fn() { None }, ) #(id, flow) } +/// Sign in to the fake provider with `code` through a pasted redirect, the +/// first profile offered as `first`, and return the completed flow. +fn sign_in( + flows: oauth_flows.Service, + home: String, + code: String, + first: Option(#(String, String)), +) -> String { + let login = ephemeral() + let id = identity() + let assert Ok(#(True, flow)) = + oauth_flows.start_identified( + flows, + home, + id, + "fake", + Some(login), + None, + "{\"provider\":\"fake\"}", + fn() { first }, + ) + let assert Ok(state) = list.key_find(query(field(flow, "url")), "state") + let assert Ok(_) = + oauth_flows.input_identified( + flows, + home, + id, + etag.strong(flow), + "http://127.0.0.1:9/cb?code=" <> code <> "&state=" <> state, + [login], + ) + settle(flows, home, id, login, 100) +} + +fn config(home: String) -> dynamic.Dynamic { + let assert Ok(bytes) = read_file(home <> "/config.json") + let assert Ok(config) = json.parse_bits(bytes, decode.dynamic) + config +} + +fn profile_ids(home: String, name: String) -> Result(List(String), Nil) { + decode.run( + config(home), + decode.at(["providers", name, "accountIds"], decode.list(decode.string)), + ) + |> result.replace_error(Nil) +} + +fn account_ids(flow: String) -> List(String) { + let assert Ok(ids) = + json.parse( + flow, + decode.at(["accounts"], decode.list(decode.at(["id"], decode.string))), + ) + ids +} + +/// A first model sign-in creates its extension's profile under a free name +/// and makes it the default; later sign-ins join every rotating or automatic +/// profile of the extension, and leave pinned and keyed profiles alone. +pub fn a_model_sign_in_joins_its_service_profiles_test() -> Nil { + let #(root, _, home) = fixture() + let _ = + write_file( + home <> "/config.json", + "{\"providers\":{\"fake\":{\"extension\":\"openai\",\"model\":\"m\",\"protocol\":\"responses\"}}}", + ) + let flows = service() + let first = + sign_in(flows, home, "one", Some(#("fake-model", "chat_completions"))) + assert field(first, "state") == "complete" + let assert [one] = account_ids(first) + assert profile_ids(home, "fake-2") == Ok([one]) + assert decode.run(config(home), decode.at(["active"], decode.string)) + == Ok("fake-2") + assert decode.run( + config(home), + decode.at(["providers", "fake-2", "model"], decode.string), + ) + == Ok("fake-model") + // The new account is named by its email. + let assert Ok(snapshot) = + auth_accounts.auth_snapshot(home, [ephemeral()], key_environment.empty()) + let assert Ok([#(label, email, needs)]) = + json.parse( + snapshot, + decode.at( + ["accounts"], + decode.list({ + use label <- decode.field("label", decode.string) + use email <- decode.field("email", decode.optional(decode.string)) + use needs <- decode.field("needs_sign_in", decode.bool) + decode.success(#(label, email, needs)) + }), + ), + ) + assert #(label, email, needs) + == #("one@example.com", Some("one@example.com"), False) + // A pinned and a keyed profile of the same service, and an automatic one. + let _ = + write_file( + home <> "/config.json", + "{\"active\":\"fake-2\",\"providers\":{" + <> "\"fake-2\":{\"extension\":\"fake\",\"model\":\"m\",\"protocol\":\"chat_completions\",\"accountIds\":[\"" + <> one + <> "\"]}," + <> "\"pinned\":{\"extension\":\"fake\",\"model\":\"m\",\"protocol\":\"chat_completions\",\"accountId\":\"" + <> one + <> "\"}," + <> "\"keyed\":{\"extension\":\"fake\",\"model\":\"m\",\"protocol\":\"chat_completions\",\"apiKey\":\"k\"}," + <> "\"plain\":{\"extension\":\"fake\",\"model\":\"m\",\"protocol\":\"chat_completions\"}}}", + ) + let second = sign_in(flows, home, "two", None) + let assert [two] = account_ids(second) + assert profile_ids(home, "fake-2") == Ok([one, two]) + assert profile_ids(home, "plain") == Ok([one, two]) + assert profile_ids(home, "pinned") == Error(Nil) + assert profile_ids(home, "keyed") == Error(Nil) + assert decode.run( + config(home), + decode.at(["providers", "pinned", "accountId"], decode.string), + ) + == Ok(one) + // Signing in again to an account keeps its id and every list as it was. + let again = sign_in(flows, home, "two", None) + assert account_ids(again) == [two] + assert profile_ids(home, "fake-2") == Ok([one, two]) + cleanup(root) +} + fn field(flow: String, key: String) -> String { let assert Ok(value) = json.parse(flow, decode.field(key, decode.string, decode.success)) @@ -219,7 +353,7 @@ fn device_login() -> oauth.Login { let email = decode.run(credential, decode.at(["email"], decode.string)) |> result.unwrap("") - oauth.Account(email, email, "fake device account", False) + oauth.account(email, email, "fake device account", False) }, None, ) @@ -239,6 +373,7 @@ pub fn a_device_code_flow_publishes_instructions_and_completes_test() -> Nil { Some(login), None, "{\"provider\":\"fake-device\"}", + fn() { None }, ) assert field(flow, "url") == "https://auth.example/device?user_code=ABCD-1234" assert string.contains(field(flow, "instructions"), "ABCD-1234") @@ -361,5 +496,11 @@ fn release(taken: #(dynamic.Dynamic, Int)) -> Nil @external(erlang, "albedo_skills_test_support", "fixture") fn fixture() -> #(String, String, String) +@external(erlang, "file", "read_file") +fn read_file(path: String) -> Result(BitArray, dynamic.Dynamic) + +@external(erlang, "file", "write_file") +fn write_file(path: String, content: String) -> dynamic.Dynamic + @external(erlang, "albedo_skills_test_support", "cleanup") fn cleanup(root: String) -> Nil diff --git a/test/harness/rotation_test.gleam b/test/harness/rotation_test.gleam index 349a5d2cb..3dd0151cc 100644 --- a/test/harness/rotation_test.gleam +++ b/test/harness/rotation_test.gleam @@ -3,6 +3,8 @@ import albedo/harness/extensions/antigravity/accounts as antigravity_accounts import albedo/harness/extensions/antigravity/extension as antigravity +import albedo/harness/extensions/claude/accounts as claude_accounts +import albedo/harness/extensions/claude/extension as claude import albedo/harness/extensions/codex/extension as codex import albedo/harness/extensions/codex/wire as codex_wire import albedo/harness/extensions/openai/extension as openai @@ -16,16 +18,22 @@ import albedo_openai import albedo_openai/opencode as gateway import albedo_sdk/accounts import albedo_sdk/auth_accounts +import albedo_sdk/credential_store import albedo_sdk/credentials +import albedo_sdk/extension import albedo_sdk/key_accounts import albedo_sdk/key_environment +import albedo_sdk/oauth import albedo_sdk/rotation +import albedo_sdk/usage_feed import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode import gleam/erlang/process import gleam/int import gleam/list import gleam/option.{None, Some} +import gleam/result import gleam/string import gleeunit/should @@ -502,7 +510,7 @@ pub fn codex_plain_rejected_account_does_not_switch_on_this_or_later_turns_test( cleanup(root) } -pub fn codex_revocation_prunes_rotations_without_unbinding_last_members_test() -> Nil { +pub fn codex_revocation_marks_the_account_and_rotation_skips_it_test() -> Nil { let #(root, _, home) = fixture() let _ = write(home, "creds.json", codex_accounts) let _ = write(home, "config.json", codex_profiles) @@ -526,6 +534,8 @@ pub fn codex_revocation_prunes_rotations_without_unbinding_last_members_test() - ) |> should.equal(Error(refusal.openai(500, "sibling answered"))) drain(tried, []) |> should.equal(["codex-one", "codex-two"]) + // Pinned to, or rotating only through, the revoked account: it needs + // sign-in, so nothing is left to use. list.each(["pinned", "last"], fn(profile) { let unavailable = codex.profile_pool(home, "unavailable", profile, plain_stream) @@ -1022,6 +1032,349 @@ pub fn native_order_only_reads_identity_for_usable_sticky_accounts_test() -> Nil |> should.equal([limited]) } +fn listed( + rotation: credential_store.Rotation, + scope: String, + session: String, + values: List(Dict(String, Dynamic)), +) -> List(String) { + accounts.arrange_by(rotation, scope, values, session, name, raw, None) + |> list.map(name) +} + +fn name(account: Dict(String, Dynamic)) -> String { + let assert Ok(value) = dict.get(account, "name") + let assert Ok(name) = decode.run(value, decode.string) + name +} + +fn member(name: String) -> Dict(String, Dynamic) { + dict.from_list([#("name", dynamic.string(name))]) +} + +fn limited_member(name: String, until: Int) -> Dict(String, Dynamic) { + member(name) |> dict.insert("limitedUntil", dynamic.int(until)) +} + +/// Failover starts every new session on the first ready account, in list +/// order and whatever account is `selected`; a session stays where it was +/// given until that account is limited, then stays where it moved. +pub fn failover_starts_on_the_first_ready_account_and_keeps_the_session_test() -> Nil { + let scope = "failover-" <> int.to_string(unique()) + let later = albedo_clock.system_ms() + 1_000_000 + let one = member("one") + let two = member("two") |> dict.insert("selected", dynamic.bool(True)) + listed(credential_store.Failover, scope, "a", [one, two]) + |> should.equal(["one", "two"]) + listed(credential_store.Failover, scope, "b", [ + limited_member("one", later), + two, + ]) + |> should.equal(["two", "one"]) + remember(scope, "b", "two") + // One is ready again: a new session starts there, session b stays on two. + listed(credential_store.Failover, scope, "b", [one, two]) + |> should.equal(["two", "one"]) + listed(credential_store.Failover, scope, "c", [one, two]) + |> should.equal(["one", "two"]) +} + +/// Spread starts each new session on the ready account given out longest +/// ago, and never moves a session that still has its account. +pub fn spread_starts_each_new_session_on_the_next_account_test() -> Nil { + let scope = "spread-" <> int.to_string(unique()) + let pool = [member("one"), member("two"), member("three")] + let assign = fn(session) { + let assert [first, ..] = + listed(credential_store.Spread, scope, session, pool) + remember(scope, session, first) + first + } + list.map(["a", "b", "c", "d"], assign) + |> should.equal(["one", "two", "three", "one"]) + // A session keeps its account on every later turn. + assign("b") |> should.equal("two") + assign("e") |> should.equal("two") + // A limited account is passed over, and its session moves and stays. + let later = albedo_clock.system_ms() + 1_000_000 + let limited = [member("one"), limited_member("two", later), member("three")] + let assert ["three", "one", "two"] = + listed(credential_store.Spread, scope, "b", limited) + remember(scope, "b", "three") + listed(credential_store.Spread, scope, "b", pool) + |> list.first + |> should.equal(Ok("three")) +} + +/// A deleted or closed session gives its account back, and a signed-out +/// account loses its assignment stamp, so neither table outlives them. +pub fn forgetting_sessions_and_accounts_clears_their_entries_test() -> Nil { + let scope = "forget-" <> int.to_string(unique()) + let session = "session-" <> int.to_string(unique()) + let pool = [member("one"), member("two")] + remember(scope, session, "two") + listed(credential_store.Failover, scope, session, pool) + |> should.equal(["two", "one"]) + accounts.forget_session(session) + listed(credential_store.Failover, scope, session, pool) + |> should.equal(["one", "two"]) + // Two was given out last, so spread starts the next session on one; once + // one is signed out and back, it counts as never given. + remember(scope, "other-" <> session, "one") + listed(credential_store.Spread, scope, "new-" <> session, pool) + |> should.equal(["two", "one"]) + accounts.forget_account("one") + listed(credential_store.Spread, scope, "new-" <> session, pool) + |> should.equal(["one", "two"]) +} + +/// Every rotation leaves out an account that needs sign-in: a refused +/// renewal or an Antigravity suspension. +pub fn rotations_skip_accounts_that_need_sign_in_test() -> Nil { + let scope = "signed-out-" <> int.to_string(unique()) + let refused = + member("refused") |> dict.insert("needsSignIn", dynamic.bool(True)) + let suspended = + member("suspended") + |> dict.insert( + "suspended", + dynamic.properties([#(dynamic.string("reason"), dynamic.string("tos"))]), + ) + list.each( + [ + credential_store.Automatic, + credential_store.Failover, + credential_store.Spread, + credential_store.First, + ], + fn(rotation) { + listed(rotation, scope, "a", [refused, suspended, member("ready")]) + |> should.equal(["ready"]) + }, + ) +} + +// Header names follow Anthropic's rate-limit documentation, not captured +// responses. +pub fn claude_limit_reads_the_rejected_unified_windows_test() -> Nil { + let now = 1_000_000_000 + let at = fn(seconds) { int.to_string(now / 1000 + seconds) } + let five = #("anthropic-ratelimit-unified-5h-reset", at(3600)) + let seven = #("anthropic-ratelimit-unified-7d-reset", at(86_400)) + let rejected = #("anthropic-ratelimit-unified-status", "rejected") + claude_accounts.limit_until( + [ + rejected, + #("anthropic-ratelimit-unified-5h-status", "rejected"), + #("anthropic-ratelimit-unified-7d-status", "allowed"), + five, + seven, + ], + now, + ) + |> should.equal(now + 3_600_000) + claude_accounts.limit_until( + [ + #("Anthropic-Ratelimit-Unified-Status", "rejected"), + #("anthropic-ratelimit-unified-5h-status", "rejected"), + #("anthropic-ratelimit-unified-7d-status", "rejected"), + five, + seven, + ], + now, + ) + |> should.equal(now + 86_400_000) + claude_accounts.limit_until( + [rejected, #("anthropic-ratelimit-unified-reset", at(600))], + now, + ) + |> should.equal(now + 600_000) + // A reset already past is no reset; retry-after, then a minute, follow. + claude_accounts.limit_until( + [ + rejected, + #("anthropic-ratelimit-unified-reset", at(-5)), + #("retry-after", "30"), + ], + now, + ) + |> should.equal(now + 30_000) + claude_accounts.limit_until([], now) |> should.equal(now + 60_000) +} + +fn claude_login() -> oauth.Login { + let assert Ok(login) = + list.find_map(claude.extension().plugins, fn(plugin) { + case plugin { + extension.LoginPlugin(login) -> Ok(login) + _ -> Error(Nil) + } + }) + login +} + +/// A Claude sign-in as its exchange stores it, for a subscription. +fn claude_credential( + token: String, + subscriber: claude_accounts.Subscriber, +) -> Dynamic { + let field = fn(name, value) { + option.map(value, fn(text) { #(dynamic.string(name), dynamic.string(text)) }) + } + [ + Some(#(dynamic.string("type"), dynamic.string("oauth"))), + Some(#(dynamic.string("access"), dynamic.string("a-" <> token))), + Some(#(dynamic.string("refresh"), dynamic.string("r-" <> token))), + Some(#(dynamic.string("expires"), dynamic.int(9_999_999_999_999))), + field( + "accountId", + Some(option.unwrap( + claude_accounts.subscription_identity(subscriber), + "fp-" <> token, + )), + ), + field("email", subscriber.email), + field("plan", subscriber.plan), + field("accountUuid", subscriber.account), + field("organizationUuid", subscriber.organization), + field("organizationName", subscriber.organization_name), + ] + |> option.values + |> dynamic.properties +} + +fn claude_sign_in(creds: Dynamic, credential: Dynamic) -> #(String, Dynamic) { + let login = claude_login() + auth_accounts.signed_in( + creds, + login.store, + credential, + login.account, + login.account(credential).id, + "claude", + ) +} + +fn claude_labels(creds: Dynamic) -> List(#(String, String)) { + let assert Ok(creds) = credential_store.object(creds) + let assert Ok(saved) = + dict.get(creds, "accounts") |> result.try(credential_store.object) + credential_store.values(saved, "anthropic") + |> list.map(fn(value) { + let assert Ok(id) = credential_store.text(value, "_albedo_account_id") + let assert Ok(label) = credential_store.text(value, "label") + #(id, label) + }) +} + +/// One Claude login belongs to a personal and a team organization on one +/// email: two accounts, the second told apart by its organization. A legacy +/// sign-in named by its token is replaced in place once it has learnt its +/// subscription, keeping its id and label. +pub fn claude_accounts_are_an_account_in_an_organization_test() -> Nil { + let assert Ok(found) = + claude_accounts.parse_subscriber(<< + "{\"account\":{\"uuid\":\"acct\",\"email\":\"you@example.com\",\"has_claude_max\":true},\"organization\":{\"uuid\":\"org-team\",\"name\":\"Team Co\"}}":utf8, + >>) + found + |> should.equal(claude_accounts.Subscriber( + Some("acct"), + Some("org-team"), + Some("Team Co"), + Some("you@example.com"), + Some("Max"), + )) + let personal = + claude_accounts.Subscriber( + ..found, + organization: Some("org-me"), + organization_name: Some("Personal"), + ) + // A legacy row: named by its token, with its subscription recorded since. + let legacy = + claude_credential( + "old", + claude_accounts.Subscriber(..personal, account: None, organization: None), + ) + let assert Ok(legacy) = credential_store.object(legacy) + let legacy = + legacy + |> dict.insert("accountUuid", dynamic.string("acct")) + |> dict.insert("organizationUuid", dynamic.string("org-me")) + let #(old, creds) = + claude_sign_in(dynamic.properties([]), credential_store.to_dynamic(legacy)) + let #(team, creds) = claude_sign_in(creds, claude_credential("team", found)) + { old != team } |> should.be_true + claude_labels(creds) + |> should.equal([ + #(old, "you@example.com"), + #(team, "you@example.com · Team Co"), + ]) + // Signing in to the personal organization again replaces the legacy row. + let #(again, creds) = + claude_sign_in(creds, claude_credential("new", personal)) + again |> should.equal(old) + claude_labels(creds) + |> should.equal([ + #(old, "you@example.com"), + #(team, "you@example.com · Team Co"), + ]) +} + +/// A quota report with a spent window marks the Claude account until it +/// resets, so selection passes over it before a request is refused. +pub fn claude_quota_heal_marks_a_spent_account_test() -> Nil { + let #(root, _, home) = fixture() + let account = fn(id) { + "{\"type\":\"oauth\",\"access\":\"a-" + <> id + <> "\",\"refresh\":\"r-" + <> id + <> "\",\"expires\":9999999999999,\"accountId\":\"" + <> id + <> "\"}" + } + let _ = + write( + home, + "creds.json", + "{\"accounts\":{\"anthropic\":[" + <> account("c1") + <> "," + <> account("c2") + <> "]}}", + ) + let session = "heal-" <> int.to_string(unique()) + let picked = fn() { + let assert Ok(stored) = claude_accounts.select(home, session, "") + credentials.value(stored).account_id + } + let reset = albedo_clock.system_ms() + 3_600_000 + let limit = fn(used) { + usage_feed.Limit( + "five_hour", + "5h", + Some(used), + None, + None, + Some(reset), + None, + "ok", + ) + } + // Room left marks nothing. + claude_accounts.heal(home, "c1", [limit(40.0)]) + claude_accounts.heal(home, "c1", [limit(100.0)]) + // A new session starts on the account with room. + picked() |> should.equal(Some("c2")) + let assert Ok(values) = + credentials.accounts(home, "anthropic", claude_accounts.decoder()) + let assert [one, two] = values + credentials.until(one, None) |> should.equal(reset) + credentials.until(two, None) |> should.equal(0) + cleanup(root) +} + /// A pool over two tokens where a rejection makes `current` sign in afresh, /// recording every attempt. fn renewing_pool( diff --git a/web/scripts/accounts.test.mjs b/web/scripts/accounts.test.mjs new file mode 100644 index 000000000..b433745ef --- /dev/null +++ b/web/scripts/accounts.test.mjs @@ -0,0 +1,182 @@ +// How the accounts page reads a service's rotation off its profiles and +// writes it back (the accounts spec's mapping). A daemon E2E sees only the +// saved result; these check the choices: which profile leads, what order a +// list with stale ids shows, which profiles a write leaves alone. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { stripTypeScriptTypes } from 'node:module'; +import test from 'node:test'; + +const moduleURL = (code) => + `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`; +const typeless = async (path) => + stripTypeScriptTypes( + (await readFile(new URL(path, import.meta.url), 'utf8')).replace( + /^import type .*;\n/gm, + '', + ), + { mode: 'transform' }, + ); +const providersURL = moduleURL( + await typeless('../src/lib/settings/providers.ts'), +); +const accounts = await import( + moduleURL( + (await typeless('../src/lib/settings/accounts.ts')).replace( + /from ['"]\.\/providers['"]/, + `from ${JSON.stringify(providersURL)}`, + ), + ) +); + +const account = (id, extra = {}) => ({ + id, + provider: 'claude', + label: id, + detail: '', + kind: 'model', + source: 'saved', + endpoint: null, + limited_until: null, + email: null, + plan: null, + needs_sign_in: false, + selected_by_profiles: [], + rotated_by_profiles: [], + ...extra, +}); +const profile = (extra = {}) => ({ + extension: 'claude', + endpoint: null, + protocol: 'chat_completions', + model: 'm', + effort: null, + image_edge: null, + account_id: null, + account_ids: null, + rotation: 'failover', + project: null, + location: null, + has_key: false, + ...extra, +}); +const auth = [ + account('a'), + account('b'), + account('c'), + account('g', { provider: 'codex' }), + account('k', { kind: 'key', provider: 'openai' }), +]; + +test('the default profile leads, else the first that rotates', () => { + const settings = { + default_profile: 'zed', + profiles: { + alpha: profile(), + beta: profile({ account_ids: ['b'] }), + zed: profile({ account_ids: ['c'], rotation: 'spread' }), + gpt: profile({ extension: 'codex' }), + }, + }; + assert.equal(accounts.leadProfile('claude', settings), 'zed'); + assert.equal( + accounts.leadProfile('claude', { ...settings, default_profile: 'gpt' }), + 'beta', + ); + assert.equal(accounts.leadProfile('antigravity', settings), null); +}); + +test('order is the lead list (existing ids only), then the rest in auth order', () => { + const settings = { + default_profile: null, + profiles: { + claude: profile({ account_ids: ['c', 'gone', 'a'], rotation: 'spread' }), + }, + }; + const { order, mode } = accounts.serviceRotation('claude', settings, auth); + assert.deepEqual( + order.map((item) => item.id), + ['c', 'a', 'b'], + ); + assert.equal(mode, 'spread'); +}); + +test('an automatic lead with two accounts shows as Only #1', () => { + const settings = { default_profile: null, profiles: { claude: profile() } }; + assert.equal( + accounts.serviceRotation('claude', settings, auth).mode, + 'first', + ); + assert.equal( + accounts.serviceRotation('codex', settings, auth).mode, + 'failover', + ); +}); + +test('a write sets every following profile and leaves pins and own keys alone', () => { + const settings = { + default_profile: null, + profiles: { + auto: profile(), + list: profile({ account_ids: ['a'] }), + pinned: profile({ account_id: 'b' }), + keyed: profile({ has_key: true }), + gpt: profile({ extension: 'codex' }), + }, + }; + const change = { + account_ids: ['b', 'a'], + rotation: 'spread', + account_id: null, + }; + assert.deepEqual( + accounts.rotationPatch('claude', settings, ['b', 'a'], 'spread'), + { profiles: { auto: change, list: change } }, + ); + assert.deepEqual( + accounts.rotationPatch('antigravity', settings, ['x'], 'first'), + {}, + ); +}); + +test('moving clamps at the ends', () => { + assert.deepEqual(accounts.moved(['a', 'b', 'c'], 'c', -1), ['a', 'c', 'b']); + assert.deepEqual(accounts.moved(['a', 'b'], 'a', -1), ['a', 'b']); +}); + +test('status, and when every account is limited', () => { + const now = Date.parse('2026-11-17T10:00:00Z'); + const soon = account('s', { limited_until: '2026-11-17T11:00:00Z' }); + const later = account('l', { limited_until: '2026-11-17T12:00:00Z' }); + const past = account('p', { limited_until: '2026-11-17T09:00:00Z' }); + const expired = account('e', { needs_sign_in: true }); + assert.equal(accounts.status(past, now).kind, 'ready'); + assert.equal(accounts.status(expired, now).text, 'needs sign-in'); + assert.match(accounts.status(soon, now).text, /^limited until /); + assert.equal( + accounts.allLimited([later, soon, expired], now)?.toISOString(), + '2026-11-17T11:00:00.000Z', + ); + assert.equal(accounts.allLimited([later, past], now), null); + assert.equal(accounts.allLimited([expired], now), null); +}); + +test('sign-out says what happens next', () => { + assert.equal( + accounts.signOutConsequence(auth[0], auth), + 'Claude keeps running on b, c.', + ); + assert.equal( + accounts.signOutConsequence(auth[3], auth), + 'ChatGPT models stop working until you sign in again. Sessions keep their history.', + ); + const key = account('or', { + kind: 'key', + provider: 'openai', + endpoint: 'https://openrouter.ai/api/v1', + }); + assert.equal( + accounts.signOutConsequence(key, [key]), + 'Models from OpenRouter stop until you add another OpenRouter key.', + ); +}); diff --git a/web/src/App.svelte b/web/src/App.svelte index ff2be9b96..e536fae8e 100644 --- a/web/src/App.svelte +++ b/web/src/App.svelte @@ -1019,7 +1019,7 @@ {#if layout.phone} openSettings()} onusage={() => (usageSheetOpen = true)} onnew={() => (newOpen = true)} usageOpen={usageSheetOpen} diff --git a/web/src/lib/Settings.svelte b/web/src/lib/Settings.svelte index 43f322f1d..31afa5f87 100644 --- a/web/src/lib/Settings.svelte +++ b/web/src/lib/Settings.svelte @@ -1,6 +1,6 @@ + +{#snippet keyMark()}{/snippet} + +{#snippet dots()}{/snippet} + +{#snippet accountRow( + account: Account, + position: number, + order: string[], + mode: Rotation, +)} + {@const state = status(account, now)} + {@const login = account.kind === 'model' ? loginFor(account.provider) : null} + {@const rotating = order.length > 1} + {@const env = account.source === 'env'} +
  • + +
  • {/if} + {#if rotating && position < order.length - 1}
  • + +
  • {/if} +
  • + +
  • + {#if login}
  • + +
  • {/if} +
  • + +
  • + + {/if} + + {/if} + {#if confirming === account.id} +
    +

    + Sign out {account.label}? + {signOutConsequence(account, accounts)} +

    +
    + +
    +
    + {/if} + {#if adding?.again === account.id && login} + { + adding = null; + await reloadAuth(); + }} + oncancel={() => (adding = null)} + /> + {/if} + +{/snippet} + +
    +

    Pick a model anywhere; albedo picks the account.

    + {#if notice}{/if} + {#if problem}{/if} + + {#if !base || !auth}

    Loading accounts…

    + {:else if firstRun} +
    +

    Sign in to start

    +

    Your subscription works. No API key needed.

    +
    + {#each services.filter( (service) => loginFor(service.extension) ) as service (service.extension)} + + {/each} +
    + +
    + {:else} + {#each groups as extension (extension)} + {@const label = serviceLabel(extension)} + {@const rotation = serviceRotation(extension, base.value, accounts)} + {@const order = rotation.order.map((account) => account.id)} + {@const rotating = order.length > 1} + {@const settable = !!rotationPatch( + extension, + base.value, + order, + 'failover', + ).profiles} + {@const back = allLimited(rotation.order, now)} + {@const login = loginFor(extension)} + {@const elsewhere = groups.find( + (other) => other !== extension && ready(other), + )} +
    +
    + +
    +

    {label}

    + {#if blurb(extension)}

    {blurb(extension)}

    {/if} +
    + {#if rotating} +
    + {#each rotationModes as mode (mode.id)}{/each} +
    + {/if} +
    + {#if rotating}

    + {rotationModes.find((mode) => mode.id === rotation.mode)?.detail}. +

    {/if} + {#if back} + + {/if} +
      + {#each rotation.order as account, position (account.id)} + {@render accountRow(account, position, order, rotation.mode)} + {/each} +
    + {#if adding?.extension === extension && !adding.again && login} + { + adding = null; + await reloadAuth(); + }} + oncancel={() => (adding = null)} + /> + {:else if login} + + {/if} +
    + {/each} + + {#if showKeys} +
    +
    + {@render keyMark()} +
    +

    API keys

    +

    + OpenRouter, Mistral, Bedrock, any compatible URL +

    +
    +
    +
      + {#each keys as account (account.id)} + {@render accountRow(account, 0, [], 'failover')} + {/each} + {#each keyedSetups as name (name)} + {@const profile = profiles[name]} + + {/each} +
    + {#if connecting?.where === 'keys'} + (connecting = null)} + /> + {:else} + + {/if} +
    + {/if} + + {#if unconnected.length || !showKeys} +
    +

    Not connected

    +
    + {#each unconnected as extension (extension)}{/each} + {#if !showKeys}{/if} +
    +
    + {/if} + + {#if Object.keys(profiles).length} +
    + +

    + Any session can switch with /model. +

    +
    + {/if} + {/if} + + {#if base && auth && (toolAccounts.length || toolLogins.length)} +
    +

    Tool sign-ins

    +

    + Accounts extensions use for things other than answering, such as Colab + runtimes. +

    + {#each toolAccounts as account (account.id)} +
    + {account.label} + {account.detail}{#if account.source !== 'env'}{/if} +
    + {/each} + {#if serviceSignIn} + {@const provider = toolLogins.find((item) => item.id === serviceSignIn)} + {#if provider} { + serviceSignIn = null; + await reloadAuth(); + }} + oncancel={() => (serviceSignIn = null)} + />{/if} + {:else if toolLogins.length} +
    + {#each toolLogins as provider (provider.id)}{/each} +
    + {/if} +
    + {/if} + + {#if base && auth} +
    + Advanced endpoints, protocols, named setups +
    +

    + Each setup is a named way to reach a provider: its endpoint, protocol, + model and reasoning, and which accounts it uses. A setup pinned to one + account here keeps it whatever its service's rotation says. +

    + {#if connecting?.where === 'advanced'} + (connecting = null)} + /> + {/if} +
    + {#each cards as [extension, setups] (extension)} + toggle(extension, setups)} + {save} + {reloadAuth} + onproblem={(text) => (problem = text)} + onsetup={(account, endpoint) => { + connecting = { + where: 'advanced', + preset: { extension, account, endpoint }, + }; + }} + /> + {:else} +

    No setups yet.

    + {/each} +
    + {#if connecting?.where !== 'advanced'}
    + +
    {/if} +
    +
    + {/if} +
    + + diff --git a/web/src/lib/settings/ConnectProvider.svelte b/web/src/lib/settings/ConnectProvider.svelte index cbaf82dd5..648529073 100644 --- a/web/src/lib/settings/ConnectProvider.svelte +++ b/web/src/lib/settings/ConnectProvider.svelte @@ -28,6 +28,7 @@ reloadAuth, onclose, preset, + keysOnly = false, }: { providers: LoginProvider[]; settings: ProviderSettings; @@ -39,9 +40,13 @@ account: string; endpoint?: string | null; } | null; + /** Only keys and endpoints: the accounts page signs in on its own rows. */ + keysOnly?: boolean; } = $props(); - const options = $derived(connectOptions(providers)); + const options = $derived( + connectOptions(providers).filter((item) => !keysOnly || !item.login), + ); const flow = new ConnectFlow( () => settings, () => reloadAuth(), @@ -120,7 +125,9 @@

    {flow.step === 'choose' - ? 'Connect a provider' + ? keysOnly + ? 'Add an API key or endpoint' + : 'Connect a provider' : `Connect ${flow.option ? flow.option.label : ''}`}

    diff --git a/web/src/lib/settings/ProviderCard.svelte b/web/src/lib/settings/ProviderCard.svelte index 93bc2df4b..38d34d87e 100644 --- a/web/src/lib/settings/ProviderCard.svelte +++ b/web/src/lib/settings/ProviderCard.svelte @@ -99,7 +99,13 @@ const use = accountUse(p); if (use.kind === 'pin') return accountLabel(use.id); if (use.kind === 'rotate') - return `${use.ids.length} accounts, switching when one is limited`; + return `${use.ids.length} accounts, ${ + p.rotation === 'spread' + ? 'each new session on the next' + : p.rotation === 'first' + ? 'only the first' + : 'switching when one is limited' + }`; return automatic(p, accounts); } diff --git a/web/src/lib/settings/ProvidersSettings.svelte b/web/src/lib/settings/ProvidersSettings.svelte deleted file mode 100644 index 154fb81f4..000000000 --- a/web/src/lib/settings/ProvidersSettings.svelte +++ /dev/null @@ -1,418 +0,0 @@ - - -
    -

    - Who answers your sessions, which account each provider signs in with, and - the model new sessions start on. -

    - {#if notice}{/if} - {#if problem}{/if} - - {#if !base || !auth}

    Loading providers…

    - {:else} - {#if Object.keys(profiles).length} - - {/if} - - {#if connecting} - (connecting = null)} - /> - {/if} - -
    - {#each cards as [extension, setups] (extension)} - - provider.id === extension && provider.kind === 'model', - )} - {catalogs} - open={!!opened[extension]} - ontoggle={() => toggle(extension, setups)} - {save} - {reloadAuth} - onproblem={(text) => (problem = text)} - onsetup={(account, endpoint) => { - connecting = { preset: { extension, account, endpoint } }; - }} - /> - {:else} - {#if !connecting}
    -

    No provider is connected yet. Connect one to start sessions.

    -
    {/if} - {/each} -
    - - {#if !connecting}
    - -
    {/if} - - {#if services.length || serviceLogins.length} -
    -

    Other accounts

    -

    - Accounts extensions use for things other than answering, such as Colab - runtimes. -

    - {#each services as account (account.id)} -
    - {account.label} - {account.detail}{#if account.source !== 'env'}{/if} -
    - {/each} - {#if serviceSignIn} - {@const provider = serviceLogins.find( - (item) => item.id === serviceSignIn, - )} - {#if provider} { - serviceSignIn = null; - await reloadAuth(); - }} - oncancel={() => (serviceSignIn = null)} - />{/if} - {:else} -
    - {#each serviceLogins as provider (provider.id)}{/each} -
    - {/if} -
    - {/if} - {/if} -
    - - diff --git a/web/src/lib/settings/SignInRow.svelte b/web/src/lib/settings/SignInRow.svelte new file mode 100644 index 000000000..db05e89c3 --- /dev/null +++ b/web/src/lib/settings/SignInRow.svelte @@ -0,0 +1,273 @@ + + +{#if warning} + +{:else} +
    +
    + {#if signIn.problem}{:else}{/if} +
    + {#if signIn.problem} + Sign-in didn't finish + + {:else} + {title} +

    + {hint} + {#if signIn.url || (manual && signIn.id)}Different computer?{/if} + {#if signIn.url}{/if}{#if signIn.url && manual && signIn.id}{' · '}{/if}{#if manual && signIn.id}{/if} +

    + {/if} +
    +
    + {#if signIn.problem}{:else if signIn.url}Open page{/if} + +
    +
    + {#if pasting && !signIn.problem} +
    { + event.preventDefault(); + paste(); + }} + > + + +
    + {/if} +
    +{/if} + + diff --git a/web/src/lib/settings/accounts.ts b/web/src/lib/settings/accounts.ts new file mode 100644 index 000000000..01002217c --- /dev/null +++ b/web/src/lib/settings/accounts.ts @@ -0,0 +1,223 @@ +import type { Account, ProviderSettings, ProviderSettingsPatch } from '../api'; +import { providerLabel, services, type Profile } from './providers'; + +// The accounts page shows rotation per service (one ordered list and one +// mode), while the daemon keeps it per profile. These are the rules for +// reading a service's rotation off its profiles and writing it back to them +// (the accounts spec, "How clients map service rotation onto profiles"), +// kept pure so they can be checked without a daemon. + +export type Rotation = Profile['rotation']; + +export const rotationModes: { id: Rotation; label: string; detail: string }[] = + [ + { + id: 'failover', + label: 'One at a time', + detail: "Use #1; move down the list when it's limited", + }, + { + id: 'spread', + label: 'Spread evenly', + detail: + 'Each new session or agent starts on the next account and stays there', + }, + { + id: 'first', + label: 'Only #1', + detail: "Never switch; wait when it's limited", + }, + ]; + +/** What a sign-in service is called: the main three by the table, others by extension. */ +export const serviceLabel = (extension: string) => + services.find((service) => service.extension === extension)?.label ?? + providerLabel(extension); + +/** A service's sign-in accounts, in auth order. Keys and tool sign-ins are elsewhere. */ +export const signIns = (extension: string, accounts: Account[]) => + accounts.filter( + (account) => account.provider === extension && account.kind === 'model', + ); + +const ofExtension = (extension: string, settings: ProviderSettings) => + Object.keys(settings.profiles) + .filter((name) => settings.profiles[name].extension === extension) + .sort(); + +/** + * The profile a service's order and mode are read from: the default profile + * when it is this service's, else the first (by name) that rotates, else the + * first. + */ +export function leadProfile( + extension: string, + settings: ProviderSettings, +): string | null { + const names = ofExtension(extension, settings); + const preferred = settings.default_profile; + if (preferred && names.includes(preferred)) return preferred; + return ( + names.find((name) => settings.profiles[name].account_ids?.length) ?? + names[0] ?? + null + ); +} + +/** A service's accounts in the order it uses them, and how it rotates. */ +export function serviceRotation( + extension: string, + settings: ProviderSettings, + accounts: Account[], +): { order: Account[]; mode: Rotation } { + const own = signIns(extension, accounts); + const name = leadProfile(extension, settings); + const lead = name ? settings.profiles[name] : null; + const listed = lead?.account_ids?.length + ? lead.account_ids + : lead?.account_id + ? [lead.account_id] + : []; + const first = listed + .map((id) => own.find((account) => account.id === id)) + .filter((account): account is Account => !!account); + const order = [ + ...first, + ...own.filter((account) => !first.includes(account)), + ]; + // Without a list a profile uses one account and never switches: Only #1. + const mode: Rotation = lead?.account_ids?.length + ? lead.rotation + : own.length > 1 && lead + ? 'first' + : 'failover'; + return { order, mode }; +} + +/** + * Whether a profile follows its service's rotation. A pin (`account_id`) is + * an Advanced override, and a profile answering with the key saved on it is + * not using the service's sign-ins; both are left alone. + */ +export const follows = (profile: Profile) => + !profile.account_id && !(profile.has_key && !profile.account_ids?.length); + +/** One patch that gives every following profile of the service this order and mode. */ +export function rotationPatch( + extension: string, + settings: ProviderSettings, + order: string[], + mode: Rotation, +): ProviderSettingsPatch { + const profiles: NonNullable = {}; + for (const name of ofExtension(extension, settings)) + if (follows(settings.profiles[name])) + profiles[name] = order.length + ? { account_ids: order, rotation: mode, account_id: null } + : { account_ids: null, account_id: null }; + return Object.keys(profiles).length ? { profiles } : {}; +} + +/** `ids` with `id` moved `by` places, or unchanged when it cannot move. */ +export function moved(ids: string[], id: string, by: number): string[] { + const at = ids.indexOf(id), + to = at + by; + if (at < 0 || to < 0 || to >= ids.length) return ids; + const next = [...ids]; + next.splice(at, 1); + next.splice(to, 0, id); + return next; +} + +/** When an account's recorded limit ends, if it is still ahead. */ +export function limitEnds(account: Account, now: number): Date | null { + if (!account.limited_until) return null; + const until = new Date(account.limited_until); + return Number.isNaN(until.getTime()) || until.getTime() <= now ? null : until; +} + +/** A time of day, with the date only when it is not today. */ +export function clock(when: Date, now: number): string { + const today = when.toDateString() === new Date(now).toDateString(); + return when.toLocaleString( + [], + today + ? { hour: 'numeric', minute: '2-digit' } + : { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }, + ); +} + +export type Status = + | { kind: 'ready'; text: string } + | { kind: 'limited'; text: string; until: Date } + | { kind: 'sign-in'; text: string }; + +export function status(account: Account, now: number): Status { + if (account.needs_sign_in) return { kind: 'sign-in', text: 'needs sign-in' }; + const until = limitEnds(account, now); + if (until) + return { + kind: 'limited', + text: `limited until ${clock(until, now)}`, + until, + }; + return { kind: 'ready', text: 'ready' }; +} + +/** + * When none of a service's accounts can answer and at least one is waiting + * out a limit: when the first comes back. Null while one is ready. + */ +export function allLimited(accounts: Account[], now: number): Date | null { + if (!accounts.length) return null; + let first: Date | null = null; + for (const account of accounts) { + const state = status(account, now); + if (state.kind === 'ready') return null; + if (state.kind === 'limited' && (!first || state.until < first)) + first = state.until; + } + return first; +} + +const keyHosts: [RegExp, string][] = [ + [/openrouter\.ai$/, 'OpenRouter'], + [/ollama\.com$/, 'Ollama Cloud'], + [/aliyuncs\.com$/, 'Alibaba'], + [/(^|\.)openai\.com$/, 'OpenAI'], + [/(^|\.)anthropic\.com$/, 'Anthropic'], +]; + +/** What a key's models come from: its plan, its endpoint's service, or its provider. */ +export function keyName(account: Account): string { + if (account.plan) return account.plan; + if ( + account.endpoint && + (account.provider === 'openai' || account.provider === 'anthropic-api') + ) + try { + const host = new URL(account.endpoint).host; + return keyHosts.find(([pattern]) => pattern.test(host))?.[1] ?? host; + } catch { + /* not a URL: name the provider */ + } + return providerLabel(account.provider); +} + +/** What signing an account out does, in the confirmation's words. */ +export function signOutConsequence( + account: Account, + accounts: Account[], +): string { + if (account.kind === 'key') { + const name = keyName(account); + return `Models from ${name} stop until you add another ${name} key.`; + } + const service = serviceLabel(account.provider); + const rest = signIns(account.provider, accounts).filter( + (other) => other.id !== account.id, + ); + return rest.length + ? `${service} keeps running on ${rest.map((other) => other.label).join(', ')}.` + : `${service} models stop working until you sign in again. Sessions keep their history.`; +} diff --git a/web/src/lib/settings/providers.ts b/web/src/lib/settings/providers.ts index f71aa7a06..27929a94c 100644 --- a/web/src/lib/settings/providers.ts +++ b/web/src/lib/settings/providers.ts @@ -40,11 +40,27 @@ const labels: Record = { perplexity: 'Perplexity', bedrock: 'Amazon Bedrock', vertex: 'Google Vertex AI', + 'github-copilot': 'GitHub Copilot', }; export const providerLabel = (extension: string) => labels[extension] ?? extension; +/** + * The sign-in services the accounts page leads with, in this order: what a + * service is called and which models it brings. One table, so the wording is + * easy to change; it matches the TUI's (cli/internal/tui). + */ +export const services: { extension: string; label: string; blurb: string }[] = [ + { extension: 'claude', label: 'Claude', blurb: 'Opus, Sonnet, Haiku' }, + { extension: 'codex', label: 'ChatGPT', blurb: 'Astra, Sol, Terra, Luna' }, + { + extension: 'antigravity', + label: 'Gemini', + blurb: 'Gemini 4 Carbon, Argon, Hydrogen', + }, +]; + // Sign-ins name their protocol here; the daemon would refuse a wrong one. const signInProtocol: Record = { codex: 'responses', -- knotmirror 0.0.1