Token review round 1: real check, saved-binding recovery, expiry
Health check (Important). The pinned CLI's auth status says signed in for any token, so a token connection is now checked with one minimal real turn through the contained launch (tokencheck.go), bounded at 90 s, its usage reported in a usage frame with a new check_id (role check on the instance). Connect saves the binding, then checks; a refusal or an unfinished check undoes it. The hourly pass uses the same check, and a sign_in_again stays until a check succeeds. The fake's status now says logged in for any token; only a turn rejects a bad one. A rejected paste ends error/provider_refused: the instance refuses a sign_in_again attempt report, which closed the runner link. Recovery (Important). A restart that finds its own binding (same home and id) carries on from it instead of calling it already_connected. With a cancel recorded, the end and the owed sign-out are written in one transaction (connect_cleanups), so the home and token go even after a stop. New crash stages "bound" and "owed" in the tests. Expiry (Minor). Neither the token nor the CLI (env tokens carry expiresAt null) gives the date, so the expiry is an estimate: expires_estimated on hello and the API, "Expires about <date>", and the renewal line six weeks ahead (TokenRenewal 42 days). Trust wording (Minor). Beside the field: sealed in your browser to your runner's key, trusting the Equipo page that seals; the server only passes on a sealed copy it cannot open. The thin size exemption rises to 15000 (measured 14948).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 files changed,
+769
−102
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+2 −1internal/equipo/chat/connections.go+21 −11internal/equipo/connections_view.go+9 −3internal/equipo/copy.go+2 −1internal/equipo/migrations/0057_thin_token_expiry_estimate.sql+1 −0internal/equipo/migrations/schema.sql+1 −1internal/equipo/static/equipo.css+1 −1internal/equipo/templates/models.html+1 −2internal/fakeclaude/fake.go+16 −9internal/headless/browser_token_test.go+14 −7internal/headless/token_test.go+85 −2internal/runner/thin/connector.go+3 −1internal/runner/thin/conns.go+29 −4internal/runner/thin/run.go+9 −0internal/runner/thin/token.go+112 −30internal/runner/thin/token_test.go+254 −10internal/runner/thin/tokencheck.go+158 −0internal/thintest/token_contract_test.go+24 −3internal/wire/connections.go+14 −7internal/wire/frames.go+9 −5internal/wire/runners.go+1 −1internal/wire/wiretest/testdata/api/connection-connecting-codex.json+1 −1internal/wire/wiretest/testdata/api/connections.json+1 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 12eca6f3..76e7f0d2 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -36,7 +36,7 @@ perf GET /releases/* skip Verified runner release file downloads, not browser GE |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions. |
| time internal/tryequipo 30s Release starter-set controller K3 records CI runs of 10.8s and 13.1s; 30s retains the guide integration checks with headroom on the shared runner. |
| -size internal/runner/thin 14900 - Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| +size internal/runner/thin 15000 - Claude token review round 1 adds the token check (tokencheck.go: one minimal turn through the contained launch, because the CLI's status cannot tell a good token from a bad one, about 150 lines) and the saved-binding recovery with its durable undo in token.go; measured 14948. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| time internal/thintest 180s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts, and Astra round 1 eight transition contracts (about 15s; the package measured 126s locally under load). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing a waiting test two seconds after it starts. About 6s alone; loaded CI measured 12.5s. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index c5f07e37..3703e184 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -5318,12 +5318,13 @@ records remain unchanged. |
| | `chat.connections.token_approve` | Approve in the browser. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_paste` | Paste the token here. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_connect` | Connect | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| -| `chat.connections.token_sealed` | It's sealed to your runner; Equipo's server never sees it. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `chat.connections.token_sealed` | Sealed in your browser to your runner's key. This trusts the Equipo page that does the sealing. Equipo's server only passes on a sealed copy it cannot open. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_bad` | That is not a Claude token. Paste the line that starts sk-ant-oat. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_failed` | That did not go through. Paste the token again. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_no_key` | Your runner needs an update before it can take a token. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.waiting_token` | Your runner is checking the token… | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_expires` | Token expires %s | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `chat.connections.token_expires_about` | Expires about %s | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_renew` | It expires soon. | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_new` | Paste a new token | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.connections.token_rejected` | This token was rejected. Run claude setup-token again. | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index 36178583..1b62185d 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -45,8 +45,10 @@ type connectionRecord struct { |
| Revision int64 |
| CreatedAt time.Time |
| UpdatedAt time.Time |
| - // ExpiresAt is when a pasted token expires, as the runner reports it. |
| - ExpiresAt *time.Time |
| + // ExpiresAt is when a pasted token expires, as the runner reports it; |
| + // ExpiresEstimated says the date is an estimate. |
| + ExpiresAt *time.Time |
| + ExpiresEstimated bool |
| } |
| func (connectionRecord) TableName() string { return "chat_connections" } |
| @@ -61,7 +63,8 @@ type usageRecord struct { |
| Model string `gorm:"uniqueIndex:chat_usage_key,priority:5"` |
| Role string |
| TaskID string |
| - // StepID is a step's, or a question's; TurnID a coordinator turn's. |
| + // StepID is a step's, a question's or a health check's; TurnID a |
| + // coordinator turn's. |
| StepID string `gorm:"uniqueIndex:chat_usage_key,priority:2"` |
| TurnID string `gorm:"uniqueIndex:chat_usage_key,priority:1"` |
| Attempt int64 `gorm:"uniqueIndex:chat_usage_key,priority:3"` |
| @@ -79,7 +82,7 @@ type usageRecord struct { |
| func (usageRecord) TableName() string { return "chat_usage" } |
| func connectionView(r connectionRecord) wire.Connection { |
| - v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, ExpiresAt: r.ExpiresAt} |
| + v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, ExpiresAt: r.ExpiresAt, ExpiresEstimated: r.ExpiresEstimated} |
| if r.Headroom != "" { |
| v.Headroom = &wire.Headroom{} |
| if json.Unmarshal([]byte(r.Headroom), v.Headroom) != nil { |
| @@ -115,7 +118,7 @@ func (t *txn) saveConnection(r *connectionRecord, fresh bool) error { |
| r.CreatedAt = r.UpdatedAt |
| err = t.db.Create(r).Error |
| } else { |
| - err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at", "expires_at").Updates(r).Error |
| + err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at", "expires_at", "expires_estimated").Updates(r).Error |
| } |
| if err != nil { |
| return err |
| @@ -170,21 +173,21 @@ func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error { |
| }) { |
| continue |
| } |
| - r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom, ExpiresAt: h.ExpiresAt} |
| + r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom, ExpiresAt: h.ExpiresAt, ExpiresEstimated: h.ExpiresEstimated} |
| if err := t.saveConnection(&r, true); err != nil { |
| return err |
| } |
| continue |
| } |
| r := rows[i] |
| - changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != "" || !sameTime(r.ExpiresAt, h.ExpiresAt) |
| + changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != "" || !sameTime(r.ExpiresAt, h.ExpiresAt) || r.ExpiresEstimated != h.ExpiresEstimated |
| if !changed && r.Headroom == headroom { |
| continue |
| } |
| if !changed && t.now().Sub(r.UpdatedAt) < headroomEvery { |
| continue |
| } |
| - r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt, r.ExpiresAt = h.State, h.Label, h.Plan, headroom, "", "", h.ExpiresAt |
| + r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt, r.ExpiresAt, r.ExpiresEstimated = h.State, h.Label, h.Plan, headroom, "", "", h.ExpiresAt, h.ExpiresEstimated |
| if err := t.saveConnection(&r, false); err != nil { |
| return err |
| } |
| @@ -243,10 +246,10 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error { |
| r.Prompt = "" |
| } |
| if v.State == wire.ConnHealthy && r.Kind == wire.KindToken && r.ExpiresAt == nil { |
| - // A setup token lasts a year from when it was pasted; the runner's |
| - // hello says exactly when. |
| + // An estimate until the runner's hello says what it knows: a |
| + // setup token lasts about a year from when it was made. |
| at := t.now().Add(wire.TokenLifetime) |
| - r.ExpiresAt = &at |
| + r.ExpiresAt, r.ExpiresEstimated = &at, true |
| } |
| if v.LocalID != "" && v.State != wire.ConnError { |
| // The hello may have recorded the new connection first. |
| @@ -636,6 +639,13 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| return err |
| } |
| return t.recordUsage(person, "ask", q.TaskID, q.ID, "", v.Rows) |
| + case v.CheckID != "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "": |
| + // A token connection's health check: a real request on the |
| + // person's own connection, keyed by the check so each counts. |
| + if len(v.CheckID) > 200 { |
| + return ErrInvalid |
| + } |
| + return t.recordUsage(person, "check", "", v.CheckID, "", v.Rows) |
| } |
| return ErrInvalid |
| } |
diff --git a/internal/equipo/connections_view.go b/internal/equipo/connections_view.go| index 790fb7a3..52da75ac 100644 |
| --- a/internal/equipo/connections_view.go |
| +++ b/internal/equipo/connections_view.go |
| @@ -174,8 +174,9 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| return v |
| } |
| -// tokenFacts says when a pasted token expires, asks for a new one within |
| -// TokenRenewal of then, and says a rejected one was rejected. |
| +// tokenFacts says when a pasted token expires (about when, for an |
| +// estimate), asks for a new one within TokenRenewal of then, and says a |
| +// rejected one was rejected. |
| func tokenFacts(row *connRow, c wire.Connection, now time.Time) { |
| if row.State == wire.ConnSignInAgain { |
| row.Words = copyText("chat.connections.token_rejected") |
| @@ -184,7 +185,12 @@ func tokenFacts(row *connRow, c wire.Connection, now time.Time) { |
| if c.ExpiresAt == nil || row.State == wire.ConnSignedOut { |
| return |
| } |
| - row.Expires = fmt.Sprintf(copyText("chat.connections.token_expires"), c.ExpiresAt.UTC().Format("2 Jan 2006")) |
| + words := "chat.connections.token_expires" |
| + if c.ExpiresEstimated { |
| + // Neither the token nor the CLI says when: the date is a guess. |
| + words = "chat.connections.token_expires_about" |
| + } |
| + row.Expires = fmt.Sprintf(copyText(words), c.ExpiresAt.UTC().Format("2 Jan 2006")) |
| row.Renew = c.ExpiresAt.Sub(now) < wire.TokenRenewal |
| } |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 880ba7b6..a1c06017 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -806,12 +806,13 @@ var pageCopy = map[string]string{ |
| "chat.connections.token_approve": "Approve in the browser.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_paste": "Paste the token here.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_connect": "Connect", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "chat.connections.token_sealed": "It's sealed to your runner; Equipo's server never sees it.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.token_sealed": "Sealed in your browser to your runner's key. This trusts the Equipo page that does the sealing. Equipo's server only passes on a sealed copy it cannot open.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_bad": "That is not a Claude token. Paste the line that starts sk-ant-oat.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_failed": "That did not go through. Paste the token again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_no_key": "Your runner needs an update before it can take a token.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.waiting_token": "Your runner is checking the token…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_expires": "Token expires %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.connections.token_expires_about": "Expires about %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_renew": "It expires soon.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_new": "Paste a new token", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.token_rejected": "This token was rejected. Run claude setup-token again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/migrations/0057_thin_token_expiry_estimate.sql b/internal/equipo/migrations/0057_thin_token_expiry_estimate.sql| new file mode 100644 |
| index 00000000..3b582675 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0057_thin_token_expiry_estimate.sql |
| @@ -0,0 +1 @@ |
| +ALTER TABLE chat_connections ADD COLUMN expires_estimated numeric; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 9590f2a8..909141b8 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -607,7 +607,7 @@ CREATE TABLE chat_task_distinct (a text, b text, created_at datetime, PRIMARY KE |
| CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime); |
| CREATE INDEX chat_question_task ON chat_questions(task_id); |
| CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key); |
| -CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime, expires_at datetime); |
| +CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime, expires_at datetime, expires_estimated numeric); |
| CREATE INDEX chat_connection_person ON chat_connections(person); |
| CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime); |
| CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at); |
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css| index 53683c1b..0b71562d 100644 |
| --- a/internal/equipo/static/equipo.css |
| +++ b/internal/equipo/static/equipo.css |
| @@ -870,7 +870,7 @@ a[equipo-source]:hover { color: var(--rst-text); text-decoration: underline; tex |
| [equipo-conn-token] label { color: var(--rst-text); } |
| [equipo-conn-token-row] { display: flex; flex-wrap: wrap; gap: var(--rst-sp-2); } |
| [equipo-conn-token-row] input { flex: 1 1 14rem; min-inline-size: 0; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; } |
| -[equipo-conn-token] [data-token-note] { margin: 0; } |
| +[equipo-conn-token] [data-token-note], [equipo-conn-token] [data-token-trust] { margin: 0; } |
| [equipo-conn-token] [data-token-note][data-tone="bad"] { color: var(--rst-tone-negative-fg); } |
| [equipo-conn-expires] { font-size: var(--rst-fs-xs); color: var(--rst-text-muted); white-space: nowrap; } |
| [equipo-conn-renew] { font-size: var(--rst-fs-xs); color: var(--rst-tone-warning-fg); } |
diff --git a/internal/equipo/templates/models.html b/internal/equipo/templates/models.html| index 84a95fb5..e7e3edb7 100644 |
| --- a/internal/equipo/templates/models.html |
| +++ b/internal/equipo/templates/models.html |
| @@ -32,10 +32,9 @@ |
| {{else if eq .Prompt.Kind "token"}}<ol equipo-conn-steps data-token-steps> |
| <li><div><p>{{copy "chat.connections.token_run"}}</p><div equipo-conn-code-row><code equipo-conn-code data-command>{{.Prompt.Code}}</code>{{template "conn-copy" .Prompt.Code}}</div></div></li> |
| <li><div><p>{{copy "chat.connections.token_approve"}}</p></div></li> |
| -<li><div><form equipo-conn-token data-token-form autocomplete="off"><label for="token-{{.ID}}">{{copy "chat.connections.token_paste"}}</label><span equipo-conn-token-row><input rst-input id="token-{{.ID}}" type="password" data-token-field autocomplete="off" autocapitalize="off" spellcheck="false" required><button rst-btn="primary" type="submit" data-token-connect>{{copy "chat.connections.token_connect"}}</button></span><span equipo-conn-small data-token-note role="status" hidden data-bad="{{copy "chat.connections.token_bad"}}" data-failed="{{copy "chat.connections.token_failed"}}" data-no-key="{{copy "chat.connections.token_no_key"}}"></span></form></div></li> |
| +<li><div><form equipo-conn-token data-token-form autocomplete="off"><label for="token-{{.ID}}">{{copy "chat.connections.token_paste"}}</label><span equipo-conn-token-row><input rst-input id="token-{{.ID}}" type="password" data-token-field autocomplete="off" autocapitalize="off" spellcheck="false" required><button rst-btn="primary" type="submit" data-token-connect>{{copy "chat.connections.token_connect"}}</button></span><span equipo-conn-small data-token-trust>{{copy "chat.connections.token_sealed"}}</span><span equipo-conn-small data-token-note role="status" hidden data-bad="{{copy "chat.connections.token_bad"}}" data-failed="{{copy "chat.connections.token_failed"}}" data-no-key="{{copy "chat.connections.token_no_key"}}"></span></form></div></li> |
| </ol> |
| <div data-token-waiting hidden>{{template "conn-waiting" (copy "chat.connections.waiting_token")}}</div> |
| -<p equipo-conn-small>{{copy "chat.connections.token_sealed"}}</p> |
| <div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-sign-in-instead"}}</span>{{template "conn-cancel" .ID}}</div> |
| {{else if eq .Prompt.Kind "terminal"}}<ol equipo-conn-steps data-finish-on> |
| <li><div><p><strong>{{printf (copy "chat.connections.open_terminal") .Runner}}</strong></p></div></li> |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index c261e38f..89251d72 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -66,12 +66,13 @@ |
| // Native tools in system/init are those of --tools. |
| // |
| // Setup tokens: with CLAUDE_CODE_OAUTH_TOKEN in its environment the fake |
| -// is signed in by that token, as the CLI is: `auth status` reports it |
| -// (with the email Token encoded, when it has one) and writes no login |
| -// file; a turn on a token that is not one of Token's is refused as an |
| -// authentication failure, and so is a turn in a home with neither a |
| -// token nor a login file. A token anywhere in argv exits 3 at once. A |
| -// reply on a token ends "(signed in by token)". |
| +// is signed in by that token, as the pinned CLI is: `auth status` says |
| +// logged in for any token at all, never asking the server (with the |
| +// email Token encoded, when it has one), and writes no login file; only |
| +// a turn finds a bad token out: a turn on a token that is not one of |
| +// Token's is refused as an authentication failure, and so is a turn in |
| +// a home with neither a token nor a login file. A token anywhere in |
| +// argv exits 3 at once. A reply on a token ends "(signed in by token)". |
| package fakeclaude |
| import ( |
| @@ -142,11 +143,11 @@ func home() string { |
| // authStatus reports the identity in the home and refreshes the login the |
| // way the CLI does: a new credential file, atomically replaced. |
| func authStatus(stdout io.Writer) int { |
| - if tok, set := os.LookupEnv(tokenEnv); set { |
| + if tok, set := os.LookupEnv(tokenEnv); set && tok != "" { |
| + // Any token is logged in: status never checks it. |
| email, ok := tokenEmail(tok) |
| if !ok { |
| - fmt.Fprintln(stdout, `{"loggedIn":false,"authMethod":"none","apiProvider":"firstParty"}`) |
| - return 1 |
| + email = "" |
| } |
| status := map[string]any{"loggedIn": true, "authMethod": "oauth_token", "apiProvider": "firstParty"} |
| if email != "" { |
| @@ -1025,6 +1026,12 @@ func Token(email string) string { |
| return "sk-ant-oat01-fake-" + hex.EncodeToString([]byte(email)) + "-ok" |
| } |
| +// Accepts reports whether a turn on tok would run: whether Token made it. |
| +func Accepts(tok string) bool { |
| + _, ok := tokenEmail(tok) |
| + return ok |
| +} |
| + |
| // tokenEmail reads a token Token made. |
| func tokenEmail(tok string) (string, bool) { |
| mid, ok := strings.CutPrefix(tok, "sk-ant-oat01-fake-") |
diff --git a/internal/headless/browser_token_test.go b/internal/headless/browser_token_test.go| index c3bd9cf0..1450b8c7 100644 |
| --- a/internal/headless/browser_token_test.go |
| +++ b/internal/headless/browser_token_test.go |
| @@ -25,6 +25,10 @@ import ( |
| // canaryToken is an obviously fake setup token. |
| const canaryToken = "sk-ant-oat01-CANARY-not-a-real-token-CANARY" |
| +// sealedWords stand beside the token field: what is trusted, and what |
| +// the server can and cannot do with the token. |
| +const sealedWords = "Sealed in your browser to your runner's key. This trusts the Equipo page that does the sealing. Equipo's server only passes on a sealed copy it cannot open." |
| + |
| // tokenDay is where this feature's screenshots go. |
| const tokenDay = "2026-11-10" |
| @@ -154,7 +158,7 @@ func TestBrowserConnectionsToken(t *testing.T) { |
| t.Fatalf("connect frame %+v", cmd) |
| } |
| // The card: the Codex card's three steps. |
| - p.check(`(()=>{const card=document.querySelector('[data-connecting][data-kind="token"]');const steps=card.querySelectorAll('[data-token-steps] > li');const field=card.querySelector('[data-token-field]');return card.querySelector('h3').textContent==='Connect Claude' && steps.length===3 && steps[0].textContent.includes('On any computer with Claude Code, run') && steps[0].querySelector('[data-command]').textContent==='claude setup-token' && steps[0].querySelector('[data-copy]').dataset.copy==='claude setup-token' && steps[1].textContent.includes('Approve in the browser.') && steps[2].textContent.includes('Paste the token here.') && field.type==='password' && !field.name && !!card.querySelector('[data-token-connect]') && card.textContent.includes("It's sealed to your runner; Equipo's server never sees it.") && !!card.dataset.sealKey && card.querySelector('[data-token-steps]').checkVisibility() && document.documentElement.scrollWidth<=innerWidth+1})()`, "the token card is not the three steps with a password field") |
| + p.check(`(()=>{const card=document.querySelector('[data-connecting][data-kind="token"]');const steps=card.querySelectorAll('[data-token-steps] > li');const field=card.querySelector('[data-token-field]');return card.querySelector('h3').textContent==='Connect Claude' && steps.length===3 && steps[0].textContent.includes('On any computer with Claude Code, run') && steps[0].querySelector('[data-command]').textContent==='claude setup-token' && steps[0].querySelector('[data-copy]').dataset.copy==='claude setup-token' && steps[1].textContent.includes('Approve in the browser.') && steps[2].textContent.includes('Paste the token here.') && field.type==='password' && !field.name && !!card.querySelector('[data-token-connect]') && field.form.querySelector('[data-token-trust]')?.textContent===`+jsonString(sealedWords)+` && field.form.querySelector('[data-token-trust]').checkVisibility() && !card.textContent.includes('never sees') && !!card.dataset.sealKey && card.querySelector('[data-token-steps]').checkVisibility() && document.documentElement.scrollWidth<=innerWidth+1})()`, "the token card is not the three steps with a password field") |
| shot("token-card") |
| // A bad format is refused here, quietly, with no request. |
| @@ -182,21 +186,24 @@ func TestBrowserConnectionsToken(t *testing.T) { |
| // The runner's healthy report: the flourish, then the row with |
| // the account and the token's expiry. |
| p.check(`(()=>{window.__success=false;new MutationObserver(()=>{if(document.querySelector('[data-success]'))window.__success=true}).observe(document.body,{childList:true,subtree:true});return true})()`, "observer") |
| + // Neither the token nor the CLI says when it expires: the date |
| + // is an estimate, and the row says about. |
| expires := time.Now().UTC().Add(wire.TokenLifetime) |
| runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: cmd.Connection, Person: thintest.Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: second}) |
| - runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnHealthy, ExpiresAt: &expires}) |
| - want := "Token expires " + expires.Format("2 Jan 2006") |
| + runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnHealthy, ExpiresAt: &expires, ExpiresEstimated: true}) |
| + want := "Expires about " + expires.Format("2 Jan 2006") |
| p.run(waitLong(`window.__success && !document.querySelector('[data-success]') && [...document.querySelectorAll('[equipo-conn-row][data-provider="claude"]')].some(e=>!e.hidden && e.textContent.includes('` + second + `') && e.querySelector('[data-token-expires]')?.textContent==='` + want + `') && !document.querySelector('[data-token-renew]')`)) |
| shot("token-connected") |
| - // Within a month of expiry: a quiet line asks for a new one. |
| - soon := time.Now().UTC().Add(10 * 24 * time.Hour) |
| - runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnHealthy, ExpiresAt: &soon}) |
| + // Within six weeks of the estimated expiry: a quiet line asks |
| + // for a new one. |
| + soon := time.Now().UTC().Add(40 * 24 * time.Hour) |
| + runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnHealthy, ExpiresAt: &soon, ExpiresEstimated: true}) |
| p.run(waitLong(`!!document.querySelector('[data-token-renew]') && document.querySelector('[data-token-renew]').textContent.includes('It expires soon.') && document.querySelector('[data-token-renew] [data-renew]').textContent==='Paste a new token'`)) |
| shot("token-renew") |
| // Rejected: sign in again, said for a token. |
| - runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnSignInAgain, ExpiresAt: &soon}) |
| + runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnSignInAgain, ExpiresAt: &soon, ExpiresEstimated: true}) |
| p.run(waitLong(`(()=>{const row=document.querySelector('[equipo-conn-row][data-provider="claude"][data-state="sign_in_again"]');return !!row && row.querySelector('[data-connection-state]').textContent==='This token was rejected. Run claude setup-token again.' && row.querySelector('[data-recover]').textContent==='Sign in again'})()`)) |
| shot("token-rejected") |
| // Sign in again is a new token attempt. |
diff --git a/internal/headless/token_test.go b/internal/headless/token_test.go| index ee4642b3..297d59e8 100644 |
| --- a/internal/headless/token_test.go |
| +++ b/internal/headless/token_test.go |
| @@ -171,9 +171,16 @@ func TestHeadlessTokenPasteEndToEnd(t *testing.T) { |
| got = cv.Connections[c.ID] |
| return got.State == wire.ConnHealthy |
| }) |
| - if got.ExpiresAt == nil || time.Until(*got.ExpiresAt) < 360*24*time.Hour || got.LocalID == "" { |
| + if got.ExpiresAt == nil || !got.ExpiresEstimated || time.Until(*got.ExpiresAt) < 360*24*time.Hour || got.LocalID == "" { |
| t.Fatalf("healthy token connection %+v", got) |
| } |
| + // Healthy only after a real request through the contained launch; |
| + // its usage is the person's, recorded like any other. |
| + until(t, "the check's usage", func() bool { |
| + var n int |
| + err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND connection = ? AND outcome = ? AND person = ?", got.LocalID, wire.OutcomeReplied, thintest.Owner).Scan(&n) |
| + return err == nil && n == 1 |
| + }) |
| // The same box again is refused by the instance or answered with |
| // nothing by the runner: the connection stays as it is. |
| _, _ = env.Client.Secret(s.ctx, c.ID, sealed) |
| @@ -196,7 +203,7 @@ func TestHeadlessTokenPasteEndToEnd(t *testing.T) { |
| if strings.Contains(inst.Logs(), token) { |
| t.Fatal("the token is in the instance's logs") |
| } |
| - if page := inst.Get(t, "/conversation/connections"); strings.Contains(page, token) || !strings.Contains(page, "Token expires") { |
| + if page := inst.Get(t, "/conversation/connections"); strings.Contains(page, token) || !strings.Contains(page, "Expires about") { |
| t.Fatal("the token is on the page, or its expiry is not") |
| } |
| list, _ := env.Client.Connections(s.ctx) |
| @@ -213,3 +220,79 @@ func TestHeadlessTokenPasteEndToEnd(t *testing.T) { |
| t.Fatalf("the token's home stayed: %v", err) |
| } |
| } |
| + |
| +// A bad token pasted end to end. The CLI's status says signed in for any |
| +// token, so only the check's real request, through the contained launch, |
| +// finds it out: "This token was rejected", never healthy, the home and |
| +// the binding gone, and the refused request's usage recorded. The link |
| +// stays up: the instance takes every frame the runner sent. |
| +func TestHeadlessTokenRejected(t *testing.T) { |
| + env, inst, r := localEnv(t) |
| + _, key, _ := ed25519.GenerateKey(rand.Reader) |
| + if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.only(t) |
| + homes := func() string { |
| + entries, _ := os.ReadDir(filepath.Join(r.root, "accounts")) |
| + var names []string |
| + for _, e := range entries { |
| + names = append(names, e.Name()) |
| + } |
| + return strings.Join(names, ",") |
| + } |
| + before := homes() |
| + r.start(t) |
| + s := open(t, env) |
| + s.keep() |
| + c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.wait(t, "token card", time.Minute, func(cv *thintest.Conversation) bool { |
| + v := cv.Connections[c.ID] |
| + return v.Prompt != nil && v.Prompt.Kind == wire.PromptToken |
| + }) |
| + snap, err := env.Client.Snapshot(s.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: "sk-ant-oat01-revoked-by-the-provider", RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(wire.SealedTTL).UTC().Truncate(time.Second)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + var end wire.Connection |
| + s.wait(t, "the attempt's end", time.Minute, func(cv *thintest.Conversation) bool { |
| + end = cv.Connections[c.ID] |
| + return end.State != wire.ConnConnecting |
| + }) |
| + if end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" { |
| + t.Fatalf("a bad token ended %+v", end) |
| + } |
| + if page := inst.Get(t, "/conversation/connections"); !strings.Contains(page, "This token was rejected. Run claude setup-token again.") { |
| + t.Fatal("the row does not say the token was rejected") |
| + } |
| + until(t, "the home and binding gone", func() bool { |
| + return homes() == before && len(r.bindings(t)) == 0 |
| + }) |
| + until(t, "the refused check's usage", func() bool { |
| + var n int |
| + err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND outcome = ?", wire.OutcomeFailed).Scan(&n) |
| + return err == nil && n == 1 |
| + }) |
| +} |
| + |
| +// until polls cond (it reads files and rows, which send no events). |
| +func until(t *testing.T, what string, cond func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(time.Minute) |
| + for !cond() { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("timed out waiting for %s", what) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| +} |
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go| index 85d69890..262d4c3c 100644 |
| --- a/internal/runner/thin/connector.go |
| +++ b/internal/runner/thin/connector.go |
| @@ -60,7 +60,9 @@ type Connector struct { |
| // it to stop the process between a frame and its cleanup). |
| spawn func(func()) |
| // fault, in tests, stops a secret's delivery at a boundary ("staged", |
| - // "transaction", "committed") as if the process stopped there. |
| + // "transaction", "committed"), a token attempt after its binding is |
| + // saved ("bound") or after a sign-out it owes is recorded ("owed"), |
| + // as if the process stopped there. |
| fault func(stage string) error |
| mu sync.Mutex |
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go| index 493b2857..b422ed5d 100644 |
| --- a/internal/runner/thin/conns.go |
| +++ b/internal/runner/thin/conns.go |
| @@ -45,6 +45,9 @@ type Conns struct { |
| // Refresh runs the official CLI in a source home under its lock. |
| Refresh func(context.Context, provider.Binding) (provider.Identity, error) |
| LockWait time.Duration |
| + // Verify checks a token connection with a real request (CheckToken); |
| + // without it nothing can prove a token, so its state never improves. |
| + Verify func(context.Context, runner.AccountBinding) error |
| // Changed is called when a connection may have become usable or its |
| // standing changed (a hello is due; held turns look again). |
| Changed func() |
| @@ -360,7 +363,10 @@ func (c *Conns) Held() []wire.HeldConnection { |
| if kind == wire.KindToken { |
| held.Label = tokenLabel(b.AccountID) |
| if at, ok := expiries[b.ID]; ok { |
| - held.ExpiresAt = &at |
| + // Paste time plus a year: neither the token nor the |
| + // pinned CLI (which holds an environment token with no |
| + // expiry) says when it really ends. |
| + held.ExpiresAt, held.ExpiresEstimated = &at, true |
| } |
| } |
| out = append(out, held) |
| @@ -406,7 +412,9 @@ func (c *Conns) expiries() map[string]time.Time { |
| // Loop refreshes each Claude and Codex home on start and hourly under its |
| // lock, with the same CLI-native refresh the runs use: a refresh that |
| // fails marks the connection sign_in_again (the provider revoked it) or |
| -// error; one that succeeds clears both. |
| +// error; one that succeeds clears both. A token connection is checked |
| +// with a real request instead (Verify), and only an answer clears its |
| +// sign_in_again. |
| func (c *Conns) Loop(ctx context.Context) { |
| // The first check waits a little so it does not contend with a first |
| // turn (a turn checks a connection it would choose itself). |
| @@ -440,6 +448,10 @@ func (c *Conns) Check(ctx context.Context) { |
| // checkOne refreshes one connection with its CLI under the source lock. |
| func (c *Conns) checkOne(ctx context.Context, b runner.AccountBinding) { |
| + if b.Kind == wire.KindToken { |
| + c.checkToken(ctx, b) |
| + return |
| + } |
| direct, err := c.Runner.DirectBinding(b) |
| if err == nil { |
| var lease *provider.AccountLease |
| @@ -454,7 +466,20 @@ func (c *Conns) checkOne(ctx context.Context, b runner.AccountBinding) { |
| c.checked(b.ID, err) |
| } |
| -// checked records one refresh's outcome. |
| +// checkToken checks a token connection (a busy home proves nothing). |
| +func (c *Conns) checkToken(ctx context.Context, b runner.AccountBinding) { |
| + if c.Verify == nil { |
| + return |
| + } |
| + err := c.Verify(ctx, b) |
| + if ctx.Err() != nil || errors.Is(err, provider.ErrAccountBusy) { |
| + return |
| + } |
| + c.checked(b.ID, err) |
| +} |
| + |
| +// checked records one refresh's outcome. A refused credential stays so |
| +// until a check succeeds; any other failure proves nothing about it. |
| func (c *Conns) checked(id string, err error) { |
| c.mu.Lock() |
| cs := c.live[id] |
| @@ -468,7 +493,7 @@ func (c *Conns) checked(id string, err error) { |
| cs.State = wire.ConnHealthy |
| case errors.Is(err, provider.ErrLoginRequired): |
| cs.State = wire.ConnSignInAgain |
| - case err != nil && !errors.Is(err, provider.ErrAccountBusy): |
| + case err != nil && !errors.Is(err, provider.ErrAccountBusy) && cs.State != wire.ConnSignInAgain: |
| cs.State = wire.ConnError |
| } |
| if cs.State != was { |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 0dc026a5..31902e09 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -168,6 +168,15 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| tools := &bridge{State: state, Link: link, Forge: fg, Clones: clones, Index: index, Logger: o.Logger, SessionRoot: o.Claude.SessionRoot, Activity: link.Activity} |
| o.Claude.Tools, o.Claude.Catalog = tools.Call, index.Catalog |
| conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: o.Claude.Refresh, LockWait: o.Claude.LockWait} |
| + // A token check is a real request; its usage counts like any other. |
| + conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { |
| + rows, err := o.Claude.CheckToken(ctx, b) |
| + if rerr := state.ReportCheck(context.Background(), rows); rerr != nil && o.Logger != nil { |
| + o.Logger.Warn("token check usage", "err", sanitize(rerr)) |
| + } |
| + link.Notify() |
| + return err |
| + } |
| engine := &Engine{State: state, Conns: conns, Logger: o.Logger, Emit: link.Delta, Act: link.Activity, Notify: link.Notify, Authorize: link.Confirm, Open: func(person string, b runner.AccountBinding) (Coordinator, error) { |
| if b.Provider == "codex" { |
| return OpenCodex(o.Claude, o.Codex, person, b) |
diff --git a/internal/runner/thin/token.go b/internal/runner/thin/token.go| index e7f1968b..6654e10b 100644 |
| --- a/internal/runner/thin/token.go |
| +++ b/internal/runner/thin/token.go |
| @@ -11,6 +11,7 @@ import ( |
| "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| @@ -171,55 +172,136 @@ func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base |
| return |
| } |
| defer lock.Close() |
| + // A binding this attempt saved before a stop (its home and id, the |
| + // person's): a restart carries on from it, never calling it a second |
| + // connection of the same account. |
| + saved, bound := c.savedToken(cmd.Person, id, home) |
| if a.cancelled || ctx.Err() != nil { |
| - failed(home, reasonOf(firstErr(ctx.Err(), context.Canceled))) |
| - return |
| - } |
| - // The probe: the unmodified CLI's `auth status --json` in the home, |
| - // the token in its environment. |
| - options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} |
| - observed, err := provider.RefreshLogin(ctx, provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true}, options) |
| - if ctx.Err() != nil { |
| - failed(home, reasonOf(ctx.Err())) |
| - return |
| - } |
| - if err != nil { |
| - // The token does not sign the CLI in: "This token was rejected. |
| - // Run claude setup-token again." |
| - c.log("connect token probe", err) |
| - r := base |
| - r.State = wire.ConnSignInAgain |
| - end(home, r) |
| + reason := reasonOf(firstErr(ctx.Err(), context.Canceled)) |
| + if bound { |
| + c.undoToken(cmd, id, lock, reason) |
| + } else { |
| + failed(home, reason) |
| + } |
| return |
| } |
| - for _, b := range c.mine(cmd.Person) { |
| - if b.Provider == wire.ProviderClaude && b.AccountID == observed.AccountID { |
| - failed(home, "already_connected") |
| + if !bound { |
| + // `auth status --json`, the token in the CLI's environment: the |
| + // email, if it names one. It proves nothing about the token. |
| + options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} |
| + observed, err := provider.RefreshLogin(ctx, provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true}, options) |
| + if ctx.Err() != nil { |
| + failed(home, reasonOf(ctx.Err())) |
| return |
| } |
| - } |
| - if c.Conns != nil { |
| - c.Conns.Forget(id) |
| - if err = c.Conns.setExpiry(id, time.Now().Add(wire.TokenLifetime)); err != nil { |
| - c.log("connect token", err) |
| + if err != nil { |
| + c.log("connect token probe", err) |
| + failed(home, "provider_refused") |
| + return |
| + } |
| + for _, b := range c.mine(cmd.Person) { |
| + if b.Provider == wire.ProviderClaude && b.AccountID == observed.AccountID { |
| + failed(home, "already_connected") |
| + return |
| + } |
| + } |
| + if c.Conns != nil { |
| + c.Conns.Forget(id) |
| + if err = c.Conns.setExpiry(id, time.Now().Add(wire.TokenLifetime)); err != nil { |
| + c.log("connect token", err) |
| + failed(home, "provider_refused") |
| + return |
| + } |
| + } |
| + if err = saveToken(ctx, c.Runner.AccountBindingsPath, cmd.Person, id, home, observed); err != nil { |
| + c.log("connect token binding", err) |
| + failed(home, "provider_refused") |
| + return |
| + } |
| + if c.stop("bound") != nil { |
| + return |
| + } |
| + if saved, bound = c.savedToken(cmd.Person, id, home); !bound { |
| failed(home, "provider_refused") |
| return |
| } |
| } |
| - if err = saveToken(ctx, c.Runner.AccountBindingsPath, cmd.Person, id, home, observed); err != nil { |
| - c.log("connect token binding", err) |
| - failed(home, "provider_refused") |
| + // The real check (it takes the home's lock, as every launch does). |
| + // Only an answer makes the connection. A refusal, or a check that |
| + // cannot finish, ends the attempt provider_refused (the app's "This |
| + // token was rejected"; an attempt never ends sign_in_again). |
| + _ = unix.Flock(int(lock.Fd()), unix.LOCK_UN) |
| + if err = c.verifyToken(ctx, saved); err != nil { |
| + c.log("connect token check", err) |
| + reason := "provider_refused" |
| + if ctx.Err() != nil { |
| + reason = reasonOf(ctx.Err()) |
| + } |
| + c.undoToken(cmd, id, lock, reason) |
| return |
| } |
| if c.Conns != nil { |
| + c.Conns.checked(id, nil) |
| c.Conns.changed() |
| } |
| r := base |
| - r.State, r.LocalID, r.Label = wire.ConnHealthy, id, tokenLabel(observed.AccountID) |
| + r.State, r.LocalID, r.Label = wire.ConnHealthy, id, tokenLabel(saved.AccountID) |
| c.finish(cmd.Connection, r) |
| c.standOrGo(cmd, id, lock) |
| } |
| +// savedToken is the binding a token attempt saved for its home. |
| +func (c *Connector) savedToken(person, id, home string) (runner.AccountBinding, bool) { |
| + for _, b := range c.mine(person) { |
| + if b.ID == id && b.ProviderHome == home && b.Kind == wire.KindToken { |
| + return b, true |
| + } |
| + } |
| + return runner.AccountBinding{}, false |
| +} |
| + |
| +// verifyToken is a saved token's check (Conns.Verify), skipped when this |
| +// attempt passed it before a stop. |
| +func (c *Connector) verifyToken(ctx context.Context, b runner.AccountBinding) error { |
| + if c.Conns == nil || c.Conns.Verify == nil { |
| + return provider.ErrLoginUnavailable |
| + } |
| + if c.Conns.load(ctx) == nil { |
| + c.Conns.mu.Lock() |
| + cs := c.Conns.live[b.ID] |
| + c.Conns.mu.Unlock() |
| + if cs.State == wire.ConnHealthy { |
| + return nil |
| + } |
| + } |
| + return c.Conns.Verify(ctx, b) |
| +} |
| + |
| +// undoToken ends an attempt whose saved token must not stand: its end |
| +// and the sign-out it owes go in one transaction, so even after a stop |
| +// the home and the token are deleted; then the sign-out runs. |
| +func (c *Connector) undoToken(cmd wire.ConnectCommand, id string, lock *os.File, reason string) { |
| + lock.Close() |
| + k := cleanup{connection: cmd.Connection, person: cmd.Person, local: id} |
| + r := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason} |
| + err := c.State.tx(context.Background(), func(t *sql.Tx) error { |
| + if _, err := t.Exec("UPDATE connect_attempts SET state='done', local_id=? WHERE id=?", id, cmd.Connection); err != nil { |
| + return err |
| + } |
| + if err := c.State.enqueue(t, wire.FrameConnection, "", r); err != nil { |
| + return err |
| + } |
| + return owe(t, k) |
| + }) |
| + c.log("connect token", err) |
| + if c.Notify != nil { |
| + c.Notify() |
| + } |
| + if err == nil && c.stop("owed") == nil { |
| + c.settle(k) |
| + } |
| +} |
| + |
| // tokenLabel is what a token connection is called: the account's email |
| // when the CLI reported one, else nothing (the app names it). |
| func tokenLabel(account string) string { |
diff --git a/internal/runner/thin/token_test.go b/internal/runner/thin/token_test.go| index e84107ae..f959b44c 100644 |
| --- a/internal/runner/thin/token_test.go |
| +++ b/internal/runner/thin/token_test.go |
| @@ -12,6 +12,7 @@ import ( |
| "path/filepath" |
| "strings" |
| "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| @@ -59,12 +60,16 @@ type tokenRig struct { |
| logs lockedBuffer |
| errs []error |
| ctx context.Context |
| + // checks counts the real-request checks (verify); refuse makes the |
| + // next ones fail for another reason than the token. |
| + checks atomic.Int64 |
| + refuse atomic.Pointer[error] |
| } |
| func newTokenRig(t *testing.T) *tokenRig { |
| dir := t.TempDir() |
| r := &tokenRig{t: t, dir: dir, root: filepath.Join(dir, "accounts")} |
| - for _, d := range []string{r.root, filepath.Join(dir, "config"), filepath.Join(dir, "state"), filepath.Join(dir, "bin")} { |
| + for _, d := range []string{r.root, filepath.Join(dir, "config"), filepath.Join(dir, "state"), filepath.Join(dir, "bin"), filepath.Join(dir, "scratch")} { |
| if err := os.MkdirAll(d, 0700); err != nil { |
| t.Fatal(err) |
| } |
| @@ -82,8 +87,8 @@ func newTokenRig(t *testing.T) *tokenRig { |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { r.state.Close() }) |
| - r.cfg = runner.Config{AccountBindingsPath: filepath.Join(dir, "config", "bindings.json"), ClaudePath: claudePath, CodexPath: "/bin/true"} |
| - r.conns = &Conns{Runner: r.cfg, State: r.state} |
| + r.cfg = runner.Config{AccountBindingsPath: filepath.Join(dir, "config", "bindings.json"), ClaudePath: claudePath, CodexPath: "/bin/true", ScratchRoot: filepath.Join(dir, "scratch")} |
| + r.conns = &Conns{Runner: r.cfg, State: r.state, Verify: r.verify} |
| _, key, _ := ed25519.GenerateKey(rand.Reader) |
| if r.keys, err = sealbox.FromEd25519(key); err != nil { |
| t.Fatal(err) |
| @@ -94,6 +99,25 @@ func newTokenRig(t *testing.T) *tokenRig { |
| return r |
| } |
| +// verify is the token check as the provider answers a real request: the |
| +// fake CLI's turn runs only on a token fakeclaude.Token made. (The |
| +// contained launch itself is TestHeadlessTokenRejected's.) |
| +func (r *tokenRig) verify(ctx context.Context, b runner.AccountBinding) error { |
| + r.checks.Add(1) |
| + if err := r.refuse.Load(); err != nil { |
| + return *err |
| + } |
| + raw, err := provider.ReadToken(b.ProviderHome) |
| + if err != nil { |
| + return err |
| + } |
| + defer clear(raw) |
| + if !fakeclaude.Accepts(string(raw)) { |
| + return provider.ErrLoginRequired |
| + } |
| + return nil |
| +} |
| + |
| // connector starts a connector, as a runner process does. |
| func (r *tokenRig) connector() *Connector { |
| keys := r.keys |
| @@ -237,7 +261,7 @@ func (r *tokenRig) healthy(id, home, token, email string) { |
| } |
| for _, h := range r.conns.Held() { |
| if h.LocalID == local { |
| - if h.Kind != wire.KindToken || h.Label != email || h.ExpiresAt == nil || time.Until(*h.ExpiresAt) < wire.TokenLifetime-time.Hour { |
| + if h.Kind != wire.KindToken || h.Label != email || h.ExpiresAt == nil || !h.ExpiresEstimated || time.Until(*h.ExpiresAt) < wire.TokenLifetime-time.Hour { |
| r.t.Fatalf("held %+v", h) |
| } |
| return |
| @@ -259,7 +283,7 @@ func TestTokenConnect(t *testing.T) { |
| r.healthy("cn_t1", home, token, "t@example.com") |
| // The expiry stays the same across a restart. |
| before := r.conns.Held()[0].ExpiresAt |
| - r.conns = &Conns{Runner: r.cfg, State: r.state} |
| + r.conns = &Conns{Runner: r.cfg, State: r.state, Verify: r.verify} |
| r.connector() |
| if after := r.conns.Held()[0].ExpiresAt; after == nil || !after.Equal(*before) { |
| t.Fatalf("expiry moved: %v %v", before, after) |
| @@ -279,23 +303,243 @@ func TestTokenConnectWithoutEmail(t *testing.T) { |
| } |
| } |
| -// A token the CLI does not accept: sign in again, nothing kept. |
| +// A token the provider does not accept: the CLI's status says signed in |
| +// (it says so for any token), so only the real request finds it out. |
| +// The attempt ends provider_refused (the app's "This token was |
| +// rejected"), nothing kept, never healthy. |
| func TestTokenRejected(t *testing.T) { |
| r := newTokenRig(t) |
| c := r.connector() |
| home := r.connect(c, "cn_t3") |
| r.deliver(c, "f-secret", r.sealed("cn_t3", "sk-ant-oat01-revoked", nil)) |
| - if end := r.ended("cn_t3"); end.State != wire.ConnSignInAgain || end.LocalID != "" { |
| + if end := r.ended("cn_t3"); end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" { |
| t.Fatalf("end %+v", end) |
| } |
| - if _, err := os.Stat(home); !os.IsNotExist(err) { |
| - t.Fatal("the rejected token's home stayed") |
| + if r.checks.Load() != 1 { |
| + t.Fatalf("%d checks", r.checks.Load()) |
| } |
| - if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 { |
| + for _, v := range r.reports("cn_t3") { |
| + if v.State == wire.ConnHealthy { |
| + t.Fatal("a rejected token was healthy") |
| + } |
| + } |
| + // The sign-out recorded with the end deletes the home. |
| + r.waitFor(func() bool { |
| + _, err := os.Lstat(home) |
| + var owed int |
| + _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed) |
| + return os.IsNotExist(err) && owed == 0 |
| + }, "the rejected token's home deleted") |
| + if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 || len(r.conns.Held()) != 0 { |
| t.Fatal("a rejected token was bound") |
| } |
| } |
| +// A check that cannot finish (no reply, no refusal) proves nothing: the |
| +// attempt ends in error and nothing is kept. |
| +func TestTokenCheckUnfinished(t *testing.T) { |
| + r := newTokenRig(t) |
| + stopped := errCheckFailed |
| + r.refuse.Store(&stopped) |
| + c := r.connector() |
| + home := r.connect(c, "cn_t4") |
| + r.deliver(c, "f-secret", r.sealed("cn_t4", fakeclaude.Token("u@example.com"), nil)) |
| + if end := r.ended("cn_t4"); end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + // The sign-out recorded with the end deletes the home. |
| + r.waitFor(func() bool { |
| + _, err := os.Lstat(home) |
| + return os.IsNotExist(err) |
| + }, "the unchecked token's home deleted") |
| + if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 { |
| + t.Fatal("an unchecked token stayed bound") |
| + } |
| +} |
| + |
| +// The hourly pass never clears a real rejection. A turn's refusal marks |
| +// a token connection sign_in_again; the CLI's status, which says signed |
| +// in for any token, is not asked; a check that fails for another reason |
| +// keeps the rejection too; only a check the provider answers clears it. |
| +func TestTokenRejectionSurvivesHourlyCheck(t *testing.T) { |
| + r := newTokenRig(t) |
| + c := r.connector() |
| + home := r.connect(c, "cn_h1") |
| + r.deliver(c, "f-secret", r.sealed("cn_h1", fakeclaude.Token(""), nil)) |
| + r.ended("cn_h1") |
| + local := filepath.Base(home) |
| + state := func() string { |
| + for _, h := range r.conns.Held() { |
| + if h.LocalID == local { |
| + return h.State |
| + } |
| + } |
| + return "gone" |
| + } |
| + if state() != wire.ConnHealthy { |
| + t.Fatalf("state %s", state()) |
| + } |
| + // The provider revokes the token (a token naming no account, so the |
| + // CLI's status names the same identity before and after): a turn is |
| + // refused. |
| + if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte("sk-ant-oat01-revoked-later"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.conns.SignInAgain(local) |
| + // The hourly pass, with the CLI's own status as the refresh: it says |
| + // signed in, and must not be what decides. |
| + paths := provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath} |
| + r.conns.Refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| + return provider.RefreshLogin(ctx, b, paths) |
| + } |
| + before := r.checks.Load() |
| + r.conns.Check(r.ctx) |
| + if state() != wire.ConnSignInAgain || r.checks.Load() != before+1 { |
| + t.Fatalf("after the hourly pass: %s, %d checks", state(), r.checks.Load()-before) |
| + } |
| + busy := errors.New("the check did not finish") |
| + r.refuse.Store(&busy) |
| + r.conns.Check(r.ctx) |
| + if state() != wire.ConnSignInAgain { |
| + t.Fatalf("an unfinished check changed the rejection: %s", state()) |
| + } |
| + // No checker at all: nothing can prove the token. |
| + verify := r.conns.Verify |
| + r.conns.Verify = nil |
| + r.conns.Check(r.ctx) |
| + if state() != wire.ConnSignInAgain { |
| + t.Fatalf("without a check: %s", state()) |
| + } |
| + // The provider answers again: the check clears it. |
| + r.conns.Verify = verify |
| + r.refuse.Store(nil) |
| + if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(fakeclaude.Token("")), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.conns.Check(r.ctx) |
| + if state() != wire.ConnHealthy { |
| + t.Fatalf("after an answered check: %s", state()) |
| + } |
| +} |
| + |
| +// A stop after the binding is saved and before the attempt is marked |
| +// done. The restarted runner finds its own binding (same home, same |
| +// attempt): it is not a second connection of the same account. Without |
| +// a cancel the attempt finishes healthy, once; with a cancel recorded, |
| +// the sign-out it owes is recorded durably and the home and its token |
| +// are deleted. |
| +func TestTokenRecoversSavedBinding(t *testing.T) { |
| + for _, cancelled := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "kept", true: "cancelled"}[cancelled], func(t *testing.T) { |
| + r := newTokenRig(t) |
| + first := r.connector() |
| + stopped := make(chan struct{}) |
| + first.fault = func(at string) error { |
| + if at == "bound" { |
| + close(stopped) |
| + return errStopped |
| + } |
| + return nil |
| + } |
| + id := "cn_b_" + map[bool]string{false: "kept", true: "cancelled"}[cancelled] |
| + home := r.connect(first, id) |
| + token := fakeclaude.Token("b@example.com") |
| + if !r.deliver(first, "f-secret", r.sealed(id, token, nil)) { |
| + t.Fatal(r.errs) |
| + } |
| + select { |
| + case <-stopped: |
| + case <-time.After(20 * time.Second): |
| + t.Fatal("never reached the saved binding") |
| + } |
| + local := filepath.Base(home) |
| + r.waitFor(func() bool { |
| + var state string |
| + _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id=?", id).Scan(&state) |
| + _, ok := r.binding(local) |
| + return ok && state == "running" |
| + }, "the stop between the binding and the attempt's end") |
| + if cancelled { |
| + if err := first.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: id, Person: connPerson}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + r.connector() |
| + for _, v := range r.reports(id) { |
| + if v.Reason == "already_connected" { |
| + t.Fatalf("its own binding called a second connection: %+v", v) |
| + } |
| + } |
| + if !cancelled { |
| + r.healthy(id, home, token, "b@example.com") |
| + return |
| + } |
| + if end := r.ended(id); end.State != wire.ConnError || end.Reason != "cancelled" || end.LocalID != "" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + r.waitFor(func() bool { |
| + _, err := os.Lstat(home) |
| + var owed int |
| + _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed) |
| + return os.IsNotExist(err) && owed == 0 |
| + }, "the cancelled token's home deleted and nothing owed") |
| + if _, ok := r.binding(local); ok || len(r.conns.Held()) != 0 { |
| + t.Fatal("the cancelled token stayed bound") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A stop after the cancelled attempt's end and sign-out are recorded, |
| +// before the sign-out ran: the next start does it from the record. |
| +func TestTokenCancelledCleanupIsDurable(t *testing.T) { |
| + r := newTokenRig(t) |
| + first := r.connector() |
| + stopped := make(chan struct{}) |
| + first.fault = func(at string) error { |
| + if at == "bound" { |
| + close(stopped) |
| + return errStopped |
| + } |
| + return nil |
| + } |
| + home := r.connect(first, "cn_d1") |
| + r.deliver(first, "f-secret", r.sealed("cn_d1", fakeclaude.Token("d@example.com"), nil)) |
| + <-stopped |
| + r.waitFor(func() bool { _, ok := r.binding(filepath.Base(home)); return ok }, "the binding") |
| + if err := first.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_d1", Person: connPerson}); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The second process records the end and the sign-out it owes, and |
| + // stops before the sign-out runs. |
| + second := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &r.keys, RunnerID: tokenRunner, Limit: time.Hour} |
| + second.spawn = func(func()) {} |
| + owed := make(chan struct{}) |
| + second.fault = func(at string) error { |
| + if at == "owed" { |
| + close(owed) |
| + return errStopped |
| + } |
| + return nil |
| + } |
| + if err := second.Start(r.ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + <-owed |
| + var n int |
| + _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups WHERE connection='cn_d1'").Scan(&n) |
| + if _, err := os.Lstat(home); err != nil || n != 1 { |
| + t.Fatalf("after the stop: home %v, %d owed", err, n) |
| + } |
| + r.connector() |
| + r.waitFor(func() bool { |
| + _, err := os.Lstat(home) |
| + var n int |
| + _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&n) |
| + return os.IsNotExist(err) && n == 0 |
| + }, "the home deleted from the record") |
| +} |
| + |
| // Crash at each delivery boundary: the process stops after the staging |
| // file is synced, inside the seen_seals transaction, or after the commit |
| // and before the ack. The restarted runner recovers and the instance's |
diff --git a/internal/runner/thin/tokencheck.go b/internal/runner/thin/tokencheck.go| new file mode 100644 |
| index 00000000..68e01741 |
| --- /dev/null |
| +++ b/internal/runner/thin/tokencheck.go |
| @@ -0,0 +1,158 @@ |
| +package thin |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// A token connection's check. The pinned CLI's `auth status` says signed |
| +// in for any token in its environment without asking the server, so only |
| +// a real request tells a good token from a bad one: one minimal turn (a |
| +// one-word reply) through the contained launch every turn uses, bounded |
| +// by tokenCheckLimit, its usage reported like any other. |
| +const ( |
| + tokenCheckLimit = 90 * time.Second |
| + tokenCheckPrompt = "Reply with the single word OK." |
| +) |
| + |
| +// errCheckFailed: no reply and no refusal (a stop, a timeout, a broken |
| +// stream). It proves nothing about the token. |
| +var errCheckFailed = errors.New("the token check did not finish") |
| + |
| +// CheckToken runs one check. nil: the provider answered (a quota refusal |
| +// answers too: the token is good, the account busy). ErrLoginRequired: |
| +// the provider refused the token. Rows are its usage, whatever the end. |
| +func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding) ([]wire.Usage, error) { |
| + o.defaults() |
| + if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || o.Manager == nil { |
| + return nil, provider.ErrPolicy |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, tokenCheckLimit) |
| + defer cancel() |
| + direct, err := o.Runner.DirectBinding(b) |
| + if err != nil { |
| + return nil, err |
| + } |
| + lease, err := provider.OpenRuntimeCopy(ctx, direct, o.Refresh, o.LockWait) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer lease.Close() |
| + binding := lease.Binding() |
| + scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer os.RemoveAll(scratch) |
| + // An empty workspace: the check reads nothing, and calls no tool. |
| + work, err := os.MkdirTemp(o.SessionRoot, "check-") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer os.RemoveAll(work) |
| + tool, err := openToolSocket(context.Background(), o.Runner.StateDir, func(context.Context, string, string, json.RawMessage) (string, bool) { return toolNoTurn, true }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer tool.Close() |
| + sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} |
| + in, err := runner.CertificationInputs(ctx, o.Runner, sel, binding, work, "converse", scratch) |
| + if err != nil { |
| + return nil, err |
| + } |
| + session := uuid() |
| + in.Argv = append(in.Argv, "--session-id", session) |
| + policy, err := provider.BuildPolicy(binding, in) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if claude.ExecutableDigest(policy) != o.Digest { |
| + return nil, provider.ErrVersion |
| + } |
| + if err = lease.CheckCopy(ctx); err != nil { |
| + return nil, err |
| + } |
| + launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "check/" + uuid(), Workspace: work, Selection: sel, Binding: binding, Policy: policy} |
| + pctx, kill := context.WithCancel(context.Background()) |
| + defer kill() |
| + proc, err := o.Manager.StartRecorded(pctx, launch, in.Argv, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + // The namespace is killed at the limit (which ends the reads below) |
| + // and at the end; its exit is observed and its record released before |
| + // the copy goes. |
| + exited := make(chan struct{}) |
| + go func() { defer close(exited); _, _ = proc.Wait(context.Background()) }() |
| + stop := context.AfterFunc(ctx, kill) |
| + defer func() { |
| + stop() |
| + kill() |
| + select { |
| + case <-exited: |
| + case <-time.After(30 * time.Second): |
| + } |
| + (&coordBase{o: o}).forget(proc.ID()) |
| + }() |
| + go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() |
| + raw, err := claude.UserContent(session, tokenCheckPrompt, nil) |
| + if err == nil { |
| + _, err = proc.Stdin().Write(raw) |
| + } |
| + if err != nil { |
| + return nil, firstErr(ctx.Err(), errCheckFailed) |
| + } |
| + scan := bufio.NewScanner(proc.Stdout()) |
| + scan.Buffer(make([]byte, 0, 64<<10), claude.MaxFrameBytes) |
| + signal := "" |
| + for scan.Scan() { |
| + events, err := claude.Decode(scan.Bytes()) |
| + if len(scan.Bytes()) > 0 && err != nil { |
| + break |
| + } |
| + for _, ev := range events { |
| + if sig := connect.ClaudeSignal(ev.Payload); sig != "" { |
| + signal = sig |
| + } |
| + if ev.Kind != "turn.completed" && ev.Kind != "turn.failed" { |
| + continue |
| + } |
| + res, ok := claude.ParseResult(ev.Payload) |
| + outcome := wire.OutcomeReplied |
| + if !ok || res.Failed { |
| + outcome = wire.OutcomeFailed |
| + } |
| + rows := usageRows(connect.ClaudeRows(ev.Payload), b, 1, outcome) |
| + switch { |
| + case signal == connect.FailAuth: |
| + return rows, provider.ErrLoginRequired |
| + case outcome == wire.OutcomeReplied, signal == connect.FailQuota: |
| + return rows, nil |
| + } |
| + return rows, errCheckFailed |
| + } |
| + } |
| + return nil, firstErr(ctx.Err(), errCheckFailed) |
| +} |
| + |
| +// ReportCheck queues a check's usage for the instance (durable). |
| +func (s *State) ReportCheck(ctx context.Context, rows []wire.Usage) error { |
| + if len(rows) == 0 { |
| + return nil |
| + } |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + return s.enqueue(t, wire.FrameUsage, "", wire.UsageReport{CheckID: "chk_" + uuid(), Rows: rows}) |
| + }) |
| +} |
diff --git a/internal/thintest/token_contract_test.go b/internal/thintest/token_contract_test.go| index c779d4ef..02397498 100644 |
| --- a/internal/thintest/token_contract_test.go |
| +++ b/internal/thintest/token_contract_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "io" |
| "net/http" |
| "os" |
| + "strconv" |
| "strings" |
| "sync" |
| "testing" |
| @@ -205,17 +206,37 @@ func TestContractTokenConnection(t *testing.T) { |
| if err = runner.Send(r.ctx, "r-healthy", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: Owner}); err != nil { |
| t.Fatal(err) |
| } |
| - hello.Connections = []wire.HeldConnection{{LocalID: "claude-1", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: Owner, State: wire.ConnHealthy, ExpiresAt: &tokenExpires}} |
| + // The expiry is an estimate: neither the token nor the CLI says it. |
| + hello.Connections = []wire.HeldConnection{{LocalID: "claude-1", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: Owner, State: wire.ConnHealthy, ExpiresAt: &tokenExpires, ExpiresEstimated: true}} |
| if err = runner.Send(r.ctx, "h2", wire.FrameHello, hello); err != nil { |
| t.Fatal(err) |
| } |
| r.wait("healthy with the token's expiry", func(c *Conversation) bool { |
| v := c.Connections[attempt.ID] |
| - return v.State == wire.ConnHealthy && v.ExpiresAt != nil && v.ExpiresAt.Equal(tokenExpires) |
| + return v.State == wire.ConnHealthy && v.ExpiresAt != nil && v.ExpiresAt.Equal(tokenExpires) && v.ExpiresEstimated |
| }) |
| - if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.ExpiresAt == nil || !got.ExpiresAt.Equal(tokenExpires) || got.Kind != wire.KindToken { |
| + if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.ExpiresAt == nil || !got.ExpiresAt.Equal(tokenExpires) || !got.ExpiresEstimated || got.Kind != wire.KindToken { |
| t.Fatalf("connection %+v %v", got, err) |
| } |
| + if page := r.inst.Get(t, "/conversation/connections"); !strings.Contains(page, "Expires about "+tokenExpires.Format("2 Jan 2006")) { |
| + t.Fatal("the row does not say the expiry is an estimate") |
| + } |
| + |
| + // The health check's real request: its usage is recorded like any |
| + // other, once per check, as the person's on that connection. |
| + for i, check := range []string{"chk_1", "chk_2", "chk_2"} { |
| + in := int64(900 + i) |
| + usage := wire.UsageReport{CheckID: check, Rows: []wire.Usage{{Provider: "claude", Connection: "claude-1", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in}}} |
| + if err = runner.Send(r.ctx, "r-check-"+strconv.Itoa(i), wire.FrameUsage, usage); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + waitFor(t, "the checks' usage", func() bool { |
| + var n, sum int64 |
| + var role, person string |
| + err := r.inst.DB.Writer().QueryRow("SELECT count(*), coalesce(sum(input_tokens),0), coalesce(max(role),''), coalesce(max(person),'') FROM chat_usage WHERE connection = 'claude-1' AND step_id LIKE 'chk_%'").Scan(&n, &sum, &role, &person) |
| + return err == nil && n == 2 && sum == 900+901 && role == "check" && person == Owner |
| + }) |
| // The sweep: everything the instance serves, logs or keeps on disk. |
| var sinks []string |
diff --git a/internal/wire/connections.go b/internal/wire/connections.go| index 27ff6593..ac9825d0 100644 |
| --- a/internal/wire/connections.go |
| +++ b/internal/wire/connections.go |
| @@ -97,8 +97,10 @@ type Connection struct { |
| CreatedAt time.Time `json:"created_at"` |
| UpdatedAt time.Time `json:"updated_at"` |
| // ExpiresAt is when the connection's own credential expires (a pasted |
| - // setup token), null when it renews itself. |
| - ExpiresAt *time.Time `json:"expires_at"` |
| + // setup token), null when it renews itself. ExpiresEstimated: the |
| + // date is an estimate (neither the token nor the CLI says it). |
| + ExpiresAt *time.Time `json:"expires_at"` |
| + ExpiresEstimated bool `json:"expires_estimated"` |
| } |
| // ConnectionList is GET /api/v1/connections: the person's own, every runner. |
| @@ -210,8 +212,10 @@ type HeldConnection struct { |
| State string `json:"state"` |
| Plan string `json:"plan"` |
| Headroom *Headroom `json:"headroom"` |
| - // ExpiresAt is when a pasted credential expires (absent otherwise). |
| - ExpiresAt *time.Time `json:"expires_at,omitempty"` |
| + // ExpiresAt is when a pasted credential expires (absent otherwise); |
| + // ExpiresEstimated says the date is an estimate. |
| + ExpiresAt *time.Time `json:"expires_at,omitempty"` |
| + ExpiresEstimated bool `json:"expires_estimated,omitempty"` |
| } |
| // Switched is the quiet line under a reply (or on a step) that moved to |
| @@ -243,10 +247,13 @@ const ( |
| SealedTTL = 10 * time.Minute |
| // MaxSealedBytes caps a box (base64 included). |
| MaxSealedBytes = 4096 |
| - // TokenLifetime is how long a setup token lasts from when it is pasted |
| - // (the CLI's one year); TokenRenewal is when the row asks for a new one. |
| + // TokenLifetime estimates how long a setup token lasts from when it |
| + // is pasted: the CLI says a year when it makes one, but neither the |
| + // token nor the CLI reveals the date and the token may be older. So |
| + // the expiry is marked an estimate, and TokenRenewal, when the row |
| + // asks for a new one, is six weeks ahead. |
| TokenLifetime = 365 * 24 * time.Hour |
| - TokenRenewal = 30 * 24 * time.Hour |
| + TokenRenewal = 42 * 24 * time.Hour |
| ) |
| // Sealed is a secret sealed to one runner (spec §2.4): Box is |
diff --git a/internal/wire/frames.go b/internal/wire/frames.go| index df3573e6..f6153817 100644 |
| --- a/internal/wire/frames.go |
| +++ b/internal/wire/frames.go |
| @@ -415,15 +415,19 @@ const ( |
| // FrameUsage (runner to instance, durable) carries the usage rows of |
| // attempts that produced no reply (failed, cancelled, refused before a |
| -// failover). Exactly one of TurnID, StepID or QuestionID is set. |
| +// failover), and of a token connection's health check. Exactly one of |
| +// TurnID, StepID, QuestionID or CheckID is set. |
| const FrameUsage = "usage" |
| // UsageReport is a usage frame. |
| type UsageReport struct { |
| - TurnID string `json:"turn_id"` |
| - StepID string `json:"step_id"` |
| - QuestionID string `json:"question_id"` |
| - Rows []Usage `json:"rows"` |
| + TurnID string `json:"turn_id"` |
| + StepID string `json:"step_id"` |
| + QuestionID string `json:"question_id"` |
| + // CheckID names one health check of a token connection: a minimal |
| + // real request whose usage counts like any other (absent otherwise). |
| + CheckID string `json:"check_id,omitempty"` |
| + Rows []Usage `json:"rows"` |
| } |
| // Reply is the committed coordinator answer for a turn. |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index 4bfe9c44..f3fcea12 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -375,7 +375,7 @@ func downgrade(body any) bool { |
| case *Hello: |
| v.Protocol, v.Platform, v.Label, v.Sandbox, v.Capabilities, v.SealKey = 0, nil, "", "", nil, "" |
| for i := range v.Connections { |
| - v.Connections[i].ExpiresAt = nil |
| + v.Connections[i].ExpiresAt, v.Connections[i].ExpiresEstimated = nil, false |
| } |
| for i := range v.Catalog { |
| v.Catalog[i].NeedsMacOS, v.Catalog[i].Simulator = false, false |
diff --git a/internal/wire/wiretest/testdata/api/connection-connecting-codex.json b/internal/wire/wiretest/testdata/api/connection-connecting-codex.json| index 9c0241ef..97aa64de 100644 |
| --- a/internal/wire/wiretest/testdata/api/connection-connecting-codex.json |
| +++ b/internal/wire/wiretest/testdata/api/connection-connecting-codex.json |
| @@ -1 +1 @@ |
| -{"id":"cn_0002","revision":2,"runner_id":"rn_0001","local_id":"","provider":"codex","kind":"subscription","label":"","state":"connecting","reason":"","plan":"","headroom":null,"prompt":{"kind":"device_code","url":"https://auth.openai.com/codex/device","code":"ABCD-1234"},"created_at":"2026-11-08T10:00:00Z","updated_at":"2026-11-08T10:00:01Z","expires_at":null} |
| +{"id":"cn_0002","revision":2,"runner_id":"rn_0001","local_id":"","provider":"codex","kind":"subscription","label":"","state":"connecting","reason":"","plan":"","headroom":null,"prompt":{"kind":"device_code","url":"https://auth.openai.com/codex/device","code":"ABCD-1234"},"created_at":"2026-11-08T10:00:00Z","updated_at":"2026-11-08T10:00:01Z","expires_at":null,"expires_estimated":false} |
diff --git a/internal/wire/wiretest/testdata/api/connections.json b/internal/wire/wiretest/testdata/api/connections.json| index 90bad38c..c8c5472d 100644 |
| --- a/internal/wire/wiretest/testdata/api/connections.json |
| +++ b/internal/wire/wiretest/testdata/api/connections.json |
| @@ -1 +1 @@ |
| -{"items":[{"id":"cn_0001","revision":4,"runner_id":"rn_0001","local_id":"claude-a","provider":"claude","kind":"subscription","label":"owner@example.com","state":"limited","reason":"","plan":"","headroom":{"utilization":1,"resets_at":"2026-11-10T10:00:00Z","windows":[{"name":"seven_day","used_percent":100,"minutes":10080,"resets_at":"2026-11-10T10:00:00Z"}]},"prompt":null,"created_at":"2026-11-06T09:00:00Z","updated_at":"2026-11-08T09:59:00Z","expires_at":null},{"id":"cn_0002","revision":3,"runner_id":"rn_0001","local_id":"codex-1","provider":"codex","kind":"subscription","label":"owner@example.com","state":"healthy","reason":"","plan":"pro","headroom":{"utilization":0.12,"resets_at":null,"windows":[{"name":"primary","used_percent":12,"minutes":300,"resets_at":"2026-11-08T14:00:00Z"}]},"prompt":null,"created_at":"2026-11-08T10:00:00Z","updated_at":"2026-11-08T10:00:01Z","expires_at":null}]} |
| +{"items":[{"id":"cn_0001","revision":4,"runner_id":"rn_0001","local_id":"claude-a","provider":"claude","kind":"subscription","label":"owner@example.com","state":"limited","reason":"","plan":"","headroom":{"utilization":1,"resets_at":"2026-11-10T10:00:00Z","windows":[{"name":"seven_day","used_percent":100,"minutes":10080,"resets_at":"2026-11-10T10:00:00Z"}]},"prompt":null,"created_at":"2026-11-06T09:00:00Z","updated_at":"2026-11-08T09:59:00Z","expires_at":null,"expires_estimated":false},{"id":"cn_0002","revision":3,"runner_id":"rn_0001","local_id":"codex-1","provider":"codex","kind":"subscription","label":"owner@example.com","state":"healthy","reason":"","plan":"pro","headroom":{"utilization":0.12,"resets_at":null,"windows":[{"name":"primary","used_percent":12,"minutes":300,"resets_at":"2026-11-08T14:00:00Z"}]},"prompt":null,"created_at":"2026-11-08T10:00:00Z","updated_at":"2026-11-08T10:00:01Z","expires_at":null,"expires_estimated":false}]} |