Mac slice F task 11: worker connections, lifecycle routed by runner
A Mac worker opens Conns over its own accounts root, seals to its own key, and says its connections and seal key in hello only at 37. It keeps only Claude token connections (pasted or its darwin sign-in) and refuses other kinds with mac_claude_only. Refresh is the darwin auth status; readProfilesAtStart calls Gate() on a Mac. The instance routes start, secret, cancel, sign out, check and the preference by the row's runner, and a sign-out names that runner. A worker's hello records only its own connections, from 37; below it the hello is stripped before it is stored. Usage rows carry their runner. D1 bookkeeping: the instance holds a Mac as having a model credential (runners.credential_held_at, amended into 0120) from connecting until its hello says no files, Keychain items or unproven launches are left; the worker derives the same hold from durable state. The Connections page groups rows by machine, main runner first, and offers "Add Claude to <Mac>"; Needs you mac_connection links there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
34 files changed,
+1,779
−92
.rastrillo/budgets.txt+5 −5docs/api/equipo-v1.openapi.json+12 −0docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json+10 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+2 −0internal/equipo/chat/connections.go+103 −33internal/equipo/chat/metered.go+10 −1internal/equipo/chat/placement.go+1 −1internal/equipo/chat/placement_abandon.go+1 −1internal/equipo/chat/questions.go+2 −2internal/equipo/chat/research.go+1 −1internal/equipo/chat/runner.go+22 −2internal/equipo/chat/tasks.go+1 −1internal/equipo/chat/worker_connections.go+195 −0internal/equipo/chat_connections.go+27 −7internal/equipo/connections_machines_test.go+157 −0internal/equipo/connections_view.go+78 −8internal/equipo/copy.go+9 −7internal/equipo/migrations/0120_mac_engineering.sql+6 −0internal/equipo/migrations/schema.sql+2 −0internal/equipo/setup/runner_models.go+3 −0internal/equipo/templates/models.html+15 −10internal/equipo/templates/work_parts.html+1 −1internal/equipo/work_views.go+7 −0internal/runner/thin/connector.go+18 −4internal/runner/thin/mac.go+1 −1internal/runner/thin/profile.go+4 −0internal/runner/thin/run.go+34 −3internal/runner/thin/worker_conns.go+145 −0internal/runner/thin/worker_conns_test.go+484 −0internal/thintest/worker_connections_contract_test.go+370 −0internal/wire/connections.go+11 −0internal/wire/mac_engineering.go+6 −3internal/wire/mac_engineering_test.go+23 −0internal/wire/runners.go+13 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index d6b0558f..adff68b7 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 24018 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe and proof codes, Mac credential copy; measured 24018. |
| -size internal/wire 8609 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe and proof codes, credential_unproven; measured 8609. |
| +size internal/equipo 24117 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe and proof codes, Mac credential copy, Mac connections; measured 24117. |
| +size internal/wire 8635 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe and proof codes, credential_unproven, model hold; measured 8635. |
| size internal/equipotest - 12683 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures and Rastrillo asset contract; measured 0/12683 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| 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; |
| -size internal/runner/thin 31482 28115 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials; measured 31482/28115. |
| +size internal/runner/thin 31676 28599 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns; measured 31676/28599. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally. |
| 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). |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| -size internal/equipo/chat 38860 12096 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places, waiting cards, Mac waits, Mac Engineering; measured 38860/12096. |
| +size internal/equipo/chat 39154 12096 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places, waiting cards, Mac waits, Mac Engineering, Mac conns; measured 39154/12096. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
| @@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally). |
| size internal/headless - 11977 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files end to end; the restart wait; the live site waits for a place; a card answer settles at the bottom; measured 11977 test lines. |
| -size internal/thintest - 38966 Protocol 31 contracts, 35 diffs, stuck tasks, no-access merges, held retries, unfinished work, free rounds, previews, Assistant files, places, Mac waits, Mac Engineering; measured 38966. |
| +size internal/thintest - 39336 Protocol 31 contracts, 35 diffs, stuck tasks, no-access merges, held retries, unfinished work, free rounds, previews, Assistant files, places, Mac waits, Mac Engineering, Mac conns; measured 39336. |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
| perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage. |
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json| index ac00d28b..b58146eb 100644 |
| --- a/docs/api/equipo-v1.openapi.json |
| +++ b/docs/api/equipo-v1.openapi.json |
| @@ -19156,6 +19156,18 @@ |
| }, |
| "engineering": { |
| "$ref": "#/components/schemas/EngineeringStatus" |
| + }, |
| + "unproven": { |
| + "type": "string" |
| + }, |
| + "model_hold": { |
| + "type": "boolean" |
| + }, |
| + "holding_items": { |
| + "type": "array", |
| + "items": { |
| + "type": "string" |
| + } |
| } |
| }, |
| "required": [ |
diff --git a/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json| index 3e69aa3c..2335a711 100644 |
| --- a/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json |
| +++ b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json |
| @@ -103,5 +103,15 @@ |
| "key": "runner.unproven.credential_unproven", |
| "where": "Machines page, a Mac's card: its Claude connections are closed because it could not prove that an earlier sign-in, token check or auth status ended (wire.UnprovenCredential); a restart of the Mac clears it", |
| "draft": "This Mac could not prove that an earlier Claude sign-in or check ended, so it keeps its Claude connections closed. Restart the Mac to clear it." |
| + }, |
| + { |
| + "key": "chat.connections.add_to", |
| + "where": "Connections page, the button under a Mac's group that adds Claude to that Mac; also the Needs you link on a task waiting for Claude on that Mac (waiting_mac_connection, no connection or signed out); %s is the Mac's name", |
| + "draft": "Add Claude to %s" |
| + }, |
| + { |
| + "key": "chat.connections.reason.mac_claude_only", |
| + "where": "Connections page, the note an ended attempt leaves when a Mac refused a kind of connection it does not take (Codex, an API key, an endpoint): only Claude runs on a Mac in slice F", |
| + "draft": "Only Claude can be added to a Mac for now." |
| } |
| ] |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 04e2e06e..8ed68e75 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -7026,6 +7026,8 @@ records remain unchanged. |
| | `runner.mac.home_open_folder` | Other people on this Mac can reach a folder where %[1]s keeps Claude, so Equipo won't keep Claude there. The runner's log names the folder and what to change. | Copy specialist | COPY REVIEW PENDING | |
| | `runner.mac.keychain_item` | This Mac's Keychain has an item named %[1]s, so Equipo won't keep Claude there. Remove it in Keychain Access as %[2]s, then try again. | Copy specialist | COPY REVIEW PENDING | |
| | `runner.unproven.credential_unproven` | This Mac could not prove that an earlier Claude sign-in or check ended, so it keeps its Claude connections closed. Restart the Mac to clear it. | Copy specialist | COPY REVIEW PENDING | |
| +| `chat.connections.add_to` | Add Claude to %s | Copy specialist | COPY REVIEW PENDING | |
| +| `chat.connections.reason.mac_claude_only` | Only Claude can be added to a Mac for now. | Copy specialist | COPY REVIEW PENDING | |
| ## Task 21 |
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index 0168240e..f2af1f7b 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -88,8 +88,12 @@ func (connectionRecord) TableName() string { return "chat_connections" } |
| // usageRecord is one turn's, step attempt's or answer's token use, as the |
| // runner reported it from the harness (spec §6, recorded from day one). |
| type usageRecord struct { |
| - ID int64 `gorm:"primaryKey"` |
| - Person string `gorm:"index:chat_usage_person,priority:1"` |
| + ID int64 `gorm:"primaryKey"` |
| + Person string `gorm:"index:chat_usage_person,priority:1"` |
| + // RunnerID is the runner that reported the row: a connection is its |
| + // runner and local id (local ids repeat across runners). Rows before |
| + // slice F name none: the main runner's. |
| + RunnerID string |
| Connection string `gorm:"uniqueIndex:chat_usage_key,priority:4"` |
| Provider string |
| Model string `gorm:"uniqueIndex:chat_usage_key,priority:5"` |
| @@ -285,19 +289,22 @@ func (t *txn) connections(person string) ([]connectionRecord, error) { |
| // person: only the runner's own person's. |
| func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error { |
| person, runner := l.Runner.Person, l.Runner.RunnerID |
| - // The preference goes again with every hello: a runner with a fresh |
| - // state learns it, one that has it ignores the same revision. |
| + rows, err := t.connections(person) |
| + if err != nil { |
| + return err |
| + } |
| + // The preference goes again with every hello, to the runner that |
| + // said it: a runner with a fresh state learns it, one that has it |
| + // ignores the same revision. A worker hears it only while it holds |
| + // one of the person's connections. |
| + mine := l.Role != wire.RoleWorker || len(held) > 0 || slices.ContainsFunc(rows, func(r connectionRecord) bool { return r.RunnerID == runner && r.State != wire.ConnSignedOut }) |
| if value, _, revision, err := t.settingRevision(preferenceKey(person)); err != nil { |
| return err |
| - } else if revision > 0 { |
| - if err := t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: value, Revision: revision}); err != nil { |
| + } else if revision > 0 && mine { |
| + if err := t.commandTo(runner, person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: value, Revision: revision}); err != nil { |
| return err |
| } |
| } |
| - rows, err := t.connections(person) |
| - if err != nil { |
| - return err |
| - } |
| byLocal := map[string]int{} |
| for i, r := range rows { |
| if r.RunnerID == runner && r.LocalID != "" { |
| @@ -481,7 +488,7 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error { |
| // Connect again: the same account, signed out before, is this one |
| // now; its old record goes. |
| if r.Label != "" { |
| - if err := t.forgetSignedOut(r.Person, r.Provider, r.Label, r.ID); err != nil { |
| + if err := t.forgetSignedOut(r.Person, r.RunnerID, r.Provider, r.Label, r.ID); err != nil { |
| return err |
| } |
| } |
| @@ -510,10 +517,11 @@ func signingIn(r connectionRecord) bool { |
| } |
| // forgetSignedOut removes the person's signed-out records of one account |
| -// (provider and label), except keep, each with its last event. |
| -func (t *txn) forgetSignedOut(person, provider, label, keep string) error { |
| +// (provider and label) on one runner, except keep, each with its last |
| +// event. The same account on another machine is another connection. |
| +func (t *txn) forgetSignedOut(person, runner, provider, label, keep string) error { |
| var rows []connectionRecord |
| - if err := t.db.Where("person = ? AND provider = ? AND label = ? AND state = ? AND id <> ?", person, provider, label, wire.ConnSignedOut, keep).Find(&rows).Error; err != nil { |
| + if err := t.db.Where("person = ? AND runner_id = ? AND provider = ? AND label = ? AND state = ? AND id <> ?", person, runner, provider, label, wire.ConnSignedOut, keep).Find(&rows).Error; err != nil { |
| return err |
| } |
| for i := range rows { |
| @@ -662,7 +670,16 @@ func (t *txn) setPreference(person string, in wire.Preferences) (out wire.Prefer |
| if err := t.event("", person, wire.EventPreference, "preference", person, revision, "", "", 0, out); err != nil { |
| return out, err |
| } |
| - return out, t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision, Until: in.Until}) |
| + runners, err := t.preferenceRunners(person) |
| + if err != nil { |
| + return out, err |
| + } |
| + for _, runner := range runners { |
| + if err := t.commandTo(runner, person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision, Until: in.Until}); err != nil { |
| + return out, err |
| + } |
| + } |
| + return out, nil |
| } |
| // Connections lists the person's own connections, every runner. |
| @@ -753,9 +770,25 @@ func (s *Store) StartConnection(ctx context.Context, person string, in wire.Conn |
| if err != nil { |
| return err |
| } |
| - if runner.ID == "" || in.RunnerID != "" && in.RunnerID != runner.ID { |
| + if runner.ID == "" { |
| return ErrNotFound |
| } |
| + onMac := in.RunnerID != "" && in.RunnerID != runner.ID |
| + if onMac { |
| + // Claude on one of the person's Macs (slice F): a pasted token |
| + // or the Mac's own sign-in, sealed to that Mac's key. |
| + m, found, err := t.connectionMachine(person, in.RunnerID) |
| + if err != nil { |
| + return err |
| + } |
| + if !found { |
| + return ErrNotFound |
| + } |
| + if !TakesClaude(m) || in.Provider != wire.ProviderClaude { |
| + return ErrInvalid |
| + } |
| + runner = wire.Runner{ID: m.ID, Online: m.Online, SealKey: m.SealKey} |
| + } |
| rows, err := t.connections(person) |
| if err != nil { |
| return err |
| @@ -781,8 +814,18 @@ func (s *Store) StartConnection(ctx context.Context, person string, in wire.Conn |
| if err := t.saveConnection(&r, true); err != nil { |
| return err |
| } |
| + if onMac { |
| + // The Mac holds a model credential from now (D1) until it says |
| + // everything of one is gone. |
| + if err := t.holdCredential(r.RunnerID); err != nil { |
| + return err |
| + } |
| + } |
| + if err := t.audit(person, "connection.start", r.ID+"@"+r.RunnerID); err != nil { |
| + return err |
| + } |
| out = connectionView(r) |
| - return t.command(person, wire.FrameConnect, wire.ConnectCommand{Connection: r.ID, Person: person, Provider: r.Provider, Kind: r.Kind, SameMachine: in.SameMachine}) |
| + return t.commandTo(r.RunnerID, person, wire.FrameConnect, wire.ConnectCommand{Connection: r.ID, Person: person, Provider: r.Provider, Kind: r.Kind, SameMachine: in.SameMachine}) |
| }) |
| return out, err |
| } |
| @@ -811,7 +854,14 @@ func (s *Store) CancelConnection(ctx context.Context, person, id string) (out wi |
| return err |
| } |
| out = connectionView(r) |
| - return t.command(person, wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: r.ID, Person: person}) |
| + runner, err := t.connectionRunner(r) |
| + if err != nil { |
| + return err |
| + } |
| + if err := t.audit(person, "connection.cancel", r.ID+"@"+runner); err != nil { |
| + return err |
| + } |
| + return t.commandTo(runner, person, wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: r.ID, Person: person}) |
| }) |
| return out, err |
| } |
| @@ -855,7 +905,16 @@ func (s *Store) SignOut(ctx context.Context, person, id string) (out wire.Connec |
| if r.State == wire.ConnSignedOut || r.LocalID == "" { |
| return nil |
| } |
| - return t.command(person, wire.FrameDisconnect, wire.DisconnectCommand{Connection: r.ID, Person: person, LocalID: r.LocalID}) |
| + // To the runner that holds it, naming it: local ids repeat across |
| + // runners. |
| + runner, err := t.connectionRunner(r) |
| + if err != nil { |
| + return err |
| + } |
| + if err := t.audit(person, "connection.sign_out", r.ID+"@"+runner); err != nil { |
| + return err |
| + } |
| + return t.commandTo(runner, person, wire.FrameDisconnect, wire.DisconnectCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, RunnerID: runner}) |
| }) |
| if err == nil && out.State == wire.ConnConnecting { |
| return s.CancelConnection(ctx, person, id) |
| @@ -988,13 +1047,14 @@ var usageOutcomes = map[string]bool{wire.OutcomeReplied: true, wire.OutcomeFaile |
| // recordUsage keeps one row per attempt and model, keyed so a resent |
| // frame changes nothing. turn is a coordinator turn, step a step or a |
| // question; round the step's fix round. |
| -func (t *txn) recordUsage(protocol int, person, role, task, step, turn string, round int, rows []wire.Usage) error { |
| +func (t *txn) recordUsage(l Lease, person, role, task, step, turn string, round int, rows []wire.Usage) error { |
| + protocol := l.Protocol |
| settle := map[int64]bool{} |
| for _, u := range rows { |
| if !usageOutcomes[u.Outcome] || u.Attempt < 1 || len(u.Model) > 200 || len(u.Connection) > 200 || u.Turns != nil && *u.Turns < 0 || u.CostMicros != nil && *u.CostMicros < 0 || u.CostReportedMicros != nil && *u.CostReportedMicros < 0 || len(u.Currency) > 8 || len(u.PriceVersion) > 64 || len(u.Family) > 64 || len(u.Tier) > 16 || len(u.TierVersion) > 64 { |
| return ErrInvalid |
| } |
| - r := usageRecord{Person: person, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: u.Attempt, Outcome: u.Outcome, Complete: u.Complete, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, Round: round, Turns: u.Turns, Overcount: protocol < wire.ProtocolSpend && u.Provider == "claude" && (role == "coordinator" || role == "ask"), CostMicros: u.CostMicros, Currency: u.Currency, PriceVersion: u.PriceVersion, CostReportedMicros: u.CostReportedMicros, Family: u.Family, Tier: u.Tier, TierVersion: u.TierVersion, ModelMismatch: u.ModelMismatch, RecordedAt: t.now()} |
| + r := usageRecord{Person: person, RunnerID: l.Runner.RunnerID, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: u.Attempt, Outcome: u.Outcome, Complete: u.Complete, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, Round: round, Turns: u.Turns, Overcount: protocol < wire.ProtocolSpend && u.Provider == "claude" && (role == "coordinator" || role == "ask"), CostMicros: u.CostMicros, Currency: u.Currency, PriceVersion: u.PriceVersion, CostReportedMicros: u.CostReportedMicros, Family: u.Family, Tier: u.Tier, TierVersion: u.TierVersion, ModelMismatch: u.ModelMismatch, RecordedAt: t.now()} |
| if err := t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&r).Error; err != nil { |
| return err |
| } |
| @@ -1031,7 +1091,7 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| if _, err := t.ownTurn(l, v.TurnID); err != nil { |
| return err |
| } |
| - return t.recordUsage(l.Protocol, person, "coordinator", "", "", v.TurnID, 0, v.Rows) |
| + return t.recordUsage(l, person, "coordinator", "", "", v.TurnID, 0, v.Rows) |
| case v.StepID != "" && v.TurnID == "" && v.QuestionID == "": |
| var s stepRecord |
| if err := t.db.Where("id = ? AND person = ?", v.StepID, person).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| @@ -1039,7 +1099,7 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| } else if err != nil { |
| return err |
| } |
| - return t.recordUsage(l.Protocol, person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Rows) |
| + return t.recordUsage(l, person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Rows) |
| case v.QuestionID != "" && v.TurnID == "" && v.StepID == "": |
| q, err := t.ownQuestion(l, v.QuestionID) |
| if err != nil { |
| @@ -1049,21 +1109,21 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| if err != nil { |
| return err |
| } |
| - return t.recordUsage(l.Protocol, person, "ask", q.TaskID, q.ID, "", round, v.Rows) |
| + return t.recordUsage(l, person, "ask", q.TaskID, q.ID, "", round, v.Rows) |
| case v.ProbeID != "" && v.CheckID == "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "": |
| // A metered connection's probe: one billable token on its model, |
| // charged like any other attempt (connectors spec §2.2). |
| if len(v.ProbeID) > 200 { |
| return ErrInvalid |
| } |
| - return t.recordUsage(l.Protocol, person, wire.UsageProbe, "", v.ProbeID, "", 0, v.Rows) |
| + return t.recordUsage(l, person, wire.UsageProbe, "", v.ProbeID, "", 0, v.Rows) |
| case v.CheckID != "" && v.ProbeID == "" && 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(l.Protocol, person, "check", "", v.CheckID, "", 0, v.Rows) |
| + return t.recordUsage(l, person, "check", "", v.CheckID, "", 0, v.Rows) |
| } |
| return ErrInvalid |
| } |
| @@ -1176,20 +1236,26 @@ func figure(p *int64) int64 { |
| } |
| // UsageToday sums the person's recorded tokens (input and output) per |
| -// connection since midnight UTC, without rows that overcount. |
| +// connection (by UsageKey) since midnight UTC, without rows that |
| +// overcount. |
| func (s *Store) UsageToday(ctx context.Context, person string) (map[string]int64, error) { |
| out := map[string]int64{} |
| err := s.read(ctx, func(tx *gorm.DB) error { |
| var rows []struct { |
| + Runner string |
| Connection string |
| N int64 |
| } |
| + primary, err := s.authority.PrimaryRunner(tx, person) |
| + if err != nil { |
| + return err |
| + } |
| day := s.now().UTC().Truncate(24 * time.Hour) |
| - if err := tx.Raw("SELECT connection, sum(coalesce(input_tokens,0) + coalesce(output_tokens,0)) AS n FROM chat_usage WHERE person = ? AND recorded_at >= ? AND NOT coalesce(overcount, 0) GROUP BY connection", person, day).Scan(&rows).Error; err != nil { |
| + if err := tx.Raw("SELECT coalesce(runner_id, '') AS runner, connection, sum(coalesce(input_tokens,0) + coalesce(output_tokens,0)) AS n FROM chat_usage WHERE person = ? AND recorded_at >= ? AND NOT coalesce(overcount, 0) GROUP BY coalesce(runner_id, ''), connection", person, day).Scan(&rows).Error; err != nil { |
| return err |
| } |
| for _, r := range rows { |
| - out[r.Connection] = r.N |
| + out[UsageKey(primary, r.Runner, r.Connection)] += r.N |
| } |
| return nil |
| }) |
| @@ -1261,7 +1327,7 @@ func (s *Store) SetStatedEmail(ctx context.Context, person, id, email string) er |
| // RowFacts are what the Connections page knows beside the runner's |
| // report: the email the person stated for each connection (by its id), |
| -// and the connections (by local id) a turn was answered on a while ago, |
| +// and the connections (by UsageKey) a turn was answered on a while ago, |
| // whose provider had its chance to report usage by now. |
| type RowFacts struct { |
| Stated map[string]string |
| @@ -1285,12 +1351,16 @@ func (s *Store) ConnectionRowFacts(ctx context.Context, person string, grace tim |
| for _, r := range stated { |
| out.Stated[r.ID] = r.StatedEmail |
| } |
| - var served []string |
| - if err := tx.Raw("SELECT DISTINCT connection FROM chat_usage WHERE person = ? AND role NOT IN ('check', 'probe') AND outcome = ? AND recorded_at < ?", person, wire.OutcomeReplied, servedBefore).Scan(&served).Error; err != nil { |
| + var served []struct{ Runner, Connection string } |
| + primary, err := s.authority.PrimaryRunner(tx, person) |
| + if err != nil { |
| + return err |
| + } |
| + if err := tx.Raw("SELECT DISTINCT coalesce(runner_id, '') AS runner, connection FROM chat_usage WHERE person = ? AND role NOT IN ('check', 'probe') AND outcome = ? AND recorded_at < ?", person, wire.OutcomeReplied, servedBefore).Scan(&served).Error; err != nil { |
| return err |
| } |
| for _, c := range served { |
| - out.Served[c] = true |
| + out.Served[UsageKey(primary, c.Runner, c.Connection)] = true |
| } |
| return nil |
| }) |
diff --git a/internal/equipo/chat/metered.go b/internal/equipo/chat/metered.go| index 18ccb3be..a1e36d5a 100644 |
| --- a/internal/equipo/chat/metered.go |
| +++ b/internal/equipo/chat/metered.go |
| @@ -66,7 +66,16 @@ func (s *Store) startAPIKey(ctx context.Context, person string, in wire.Connect) |
| if err != nil { |
| return err |
| } |
| - if runner.ID == "" || in.RunnerID != "" && in.RunnerID != runner.ID { |
| + if runner.ID == "" { |
| + return ErrNotFound |
| + } |
| + if in.RunnerID != "" && in.RunnerID != runner.ID { |
| + // An API key stays on the main runner (Mac runners spec §8.5). |
| + if _, found, err := t.connectionMachine(person, in.RunnerID); err != nil { |
| + return err |
| + } else if found { |
| + return ErrInvalid |
| + } |
| return ErrNotFound |
| } |
| rows, err := t.connections(person) |
diff --git a/internal/equipo/chat/placement.go b/internal/equipo/chat/placement.go| index d1d91b04..19c731af 100644 |
| --- a/internal/equipo/chat/placement.go |
| +++ b/internal/equipo/chat/placement.go |
| @@ -152,7 +152,7 @@ func (t *txn) moveReport(l Lease, k *taskRecord, s *stepRecord, v *wire.StepRepo |
| if advanced || v.Attempt != s.Attempt || !wire.StepTerminal(v.State) { |
| return nil |
| } |
| - if err := t.recordUsage(l.Protocol, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| + if err := t.recordUsage(l, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| return err |
| } |
| if !v.Termination { |
diff --git a/internal/equipo/chat/placement_abandon.go b/internal/equipo/chat/placement_abandon.go| index 8ea80e2c..66e3c744 100644 |
| --- a/internal/equipo/chat/placement_abandon.go |
| +++ b/internal/equipo/chat/placement_abandon.go |
| @@ -31,7 +31,7 @@ func (t *txn) abandonedReport(l Lease, k *taskRecord, s *stepRecord, v *wire.Ste |
| if advanced || s.Terminated { |
| return nil |
| } |
| - if err := t.recordUsage(l.Protocol, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| + if err := t.recordUsage(l, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| return err |
| } |
| if v.Pushed { |
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go| index 4e89a4c3..c503c321 100644 |
| --- a/internal/equipo/chat/questions.go |
| +++ b/internal/equipo/chat/questions.go |
| @@ -456,7 +456,7 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error { |
| if err != nil { |
| return err |
| } |
| - if err := t.recordUsage(l.Protocol, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| + if err := t.recordUsage(l, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| return err |
| } |
| if v.Timing != nil { |
| @@ -470,7 +470,7 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error { |
| if err != nil { |
| return err |
| } |
| - if err := t.recordUsage(l.Protocol, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| + if err := t.recordUsage(l, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| return err |
| } |
| default: |
diff --git a/internal/equipo/chat/research.go b/internal/equipo/chat/research.go| index 77556872..747d26c8 100644 |
| --- a/internal/equipo/chat/research.go |
| +++ b/internal/equipo/chat/research.go |
| @@ -652,7 +652,7 @@ func (t *txn) researchReport(l Lease, k *taskRecord, s *stepRecord, v *wire.Step |
| } |
| } else { |
| if wire.StepTerminal(v.State) { |
| - if err := t.recordUsage(l.Protocol, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| + if err := t.recordUsage(l, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| return err |
| } |
| } |
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go| index c29090fc..f264f1a9 100644 |
| --- a/internal/equipo/chat/runner.go |
| +++ b/internal/equipo/chat/runner.go |
| @@ -43,6 +43,11 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string, |
| return rerr |
| } |
| lease.Role = role |
| + if role == wire.RoleWorker && wire.WithoutWorkerConnections(&hello, lease.Protocol) { |
| + // A worker below 37 holds no connection and publishes no seal |
| + // key: what it says of either is not kept. |
| + raw, _ = json.Marshal(cleanHello(hello)) |
| + } |
| if hello.Capabilities != nil && hello.Capabilities.Tainted { |
| if err := t.markTainted(p.RunnerID); err != nil { |
| return err |
| @@ -105,6 +110,8 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string, |
| if err := t.helloConnections(lease, hello.Connections); err != nil { |
| return err |
| } |
| + } else if err := t.workerHello(lease, hello); err != nil { |
| + return err |
| } |
| if err := t.runnerEvent(p.Person, r); err != nil { |
| return err |
| @@ -188,6 +195,9 @@ func (s *Store) Confirm(ctx context.Context, l Lease) error { |
| // Heartbeat records a repeated hello. |
| func (s *Store) Heartbeat(ctx context.Context, l Lease, hello wire.Hello) error { |
| + if l.Role == wire.RoleWorker { |
| + wire.WithoutWorkerConnections(&hello, l.Protocol) |
| + } |
| raw, _ := json.Marshal(cleanHello(hello)) |
| return s.tx(ctx, func(t *txn) error { |
| r, err := t.current(l) |
| @@ -233,6 +243,8 @@ func (s *Store) Heartbeat(ctx context.Context, l Lease, hello wire.Hello) error |
| return err |
| } |
| } |
| + } else if err := t.workerHello(l, hello); err != nil { |
| + return err |
| } |
| if !online { |
| if err := t.runnerEvent(l.Runner.Person, r); err != nil { |
| @@ -530,7 +542,7 @@ func (t *txn) reply(l Lease, v *wire.Reply) error { |
| for _, u := range v.Usage { |
| r.Connection = u.Connection |
| } |
| - if err := t.recordUsage(l.Protocol, r.Person, "coordinator", "", "", r.ID, 0, v.Usage); err != nil { |
| + if err := t.recordUsage(l, r.Person, "coordinator", "", "", r.ID, 0, v.Usage); err != nil { |
| return err |
| } |
| // A move-in or explore turn with nothing to say posts nothing. |
| @@ -624,9 +636,17 @@ func (t *txn) sync(l Lease, v *wire.Sync) error { |
| // Only the person's primary runner holds their turns and questions; |
| // another of their runners must not fail the primary's work. |
| primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person) |
| - if err != nil || primary != l.Runner.RunnerID { |
| + if err != nil { |
| return err |
| } |
| + if primary != l.Runner.RunnerID { |
| + // A worker's own connections (37): the sync carries them as a |
| + // hello does; nothing else of the primary's is its to settle. |
| + if l.Role == wire.RoleWorker && l.Protocol >= wire.ProtocolMacEngineering { |
| + return t.helloConnections(l, v.Connections) |
| + } |
| + return nil |
| + } |
| if err := t.helloConnections(l, v.Connections); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index 7fe0e112..37c3a9a9 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -1546,7 +1546,7 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| raw, _ := json.Marshal(v.Copy) |
| s.CopyResult = string(raw) |
| } |
| - if err := t.recordUsage(l.Protocol, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| + if err := t.recordUsage(l, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| return err |
| } |
| } |
diff --git a/internal/equipo/chat/worker_connections.go b/internal/equipo/chat/worker_connections.go| new file mode 100644 |
| index 00000000..e6ecac4e |
| --- /dev/null |
| +++ b/internal/equipo/chat/worker_connections.go |
| @@ -0,0 +1,195 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "slices" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// A Mac worker's own Claude connections (Mac runners spec §8.5; slice F |
| +// task 11). A connection row names its runner, and every operation on it |
| +// goes there: start, the sealed secret, cancel, sign out, check, and the |
| +// preference to each runner holding one. Local ids repeat across |
| +// runners, so a row is matched by (runner, local id), never by the local |
| +// id alone. A worker's hello records that worker's connections only, and |
| +// only from protocol 37 (wire.WithoutWorkerConnections). |
| +// |
| +// The credential hold (D1, spec §8.3 (4)): from the moment a connection |
| +// on a Mac starts connecting, the instance holds that Mac as having a |
| +// model credential (runners.credential_held_at), and lets go only once |
| +// the Mac's own hello says nothing of one is left: no connection, no |
| +// files, no Keychain item, no launch it could not prove ended, and |
| +// nothing the Mac has not been told yet. Task 15 reads it (the D1 |
| +// predicate) through macCredentialHeld. |
| + |
| +// ConnectionMachine is one of the person's runners as the Connections |
| +// page groups connections by: its id, name, role and platform (OS), the |
| +// protocol it speaks, whether it is online, being removed or tainted, |
| +// and the seal key it published. |
| +type ConnectionMachine struct { |
| + ID, Label, Role, Platform string |
| + Protocol int |
| + Online, Removing, Tainted bool |
| + SealKey string |
| +} |
| + |
| +// TakesClaude: Claude can be added to m. Only a Mac worker that speaks |
| +// ProtocolMacEngineering and published a seal key, and is neither being |
| +// removed nor tainted (D2: a tainted runner takes no model connection). |
| +// The main runner adds its own as it always has. |
| +func TakesClaude(m ConnectionMachine) bool { |
| + return m.Role == wire.RoleWorker && m.Platform == "darwin" && m.Protocol >= wire.ProtocolMacEngineering && m.SealKey != "" && !m.Removing && !m.Tainted |
| +} |
| + |
| +// machineOf is r as a ConnectionMachine. |
| +func machineOf(r runnerInfo) ConnectionMachine { |
| + m := ConnectionMachine{ID: r.ID, Label: r.Label, Role: r.Role, Protocol: r.Protocol, Online: r.Online, Removing: r.Removing, Tainted: r.Tainted, SealKey: r.Hello.SealKey} |
| + if r.Hello.Platform != nil { |
| + m.Platform = r.Hello.Platform.OS |
| + } |
| + return m |
| +} |
| + |
| +// UsageKey is how UsageToday and RowFacts name a connection's usage: its |
| +// local id on the main runner (and for rows that predate the runner's |
| +// id), its runner and local id on any other. |
| +func UsageKey(primary, runner, local string) string { |
| + if runner == "" || runner == primary { |
| + return local |
| + } |
| + return runner + "/" + local |
| +} |
| + |
| +// ConnectionMachines are the person's runners, the main runner first. |
| +func (s *Store) ConnectionMachines(ctx context.Context, person string) (out []ConnectionMachine, err error) { |
| + err = s.read(ctx, func(tx *gorm.DB) error { |
| + if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| + return err |
| + } |
| + t := &txn{s: s, db: tx} |
| + primary, err := s.authority.PrimaryRunner(tx, person) |
| + if err != nil { |
| + return err |
| + } |
| + rs, err := t.runners(person) |
| + if err != nil { |
| + return err |
| + } |
| + for _, r := range rs { |
| + out = append(out, machineOf(r)) |
| + } |
| + slices.SortStableFunc(out, func(a, b ConnectionMachine) int { |
| + switch { |
| + case a.ID == primary && b.ID != primary: |
| + return -1 |
| + case b.ID == primary && a.ID != primary: |
| + return 1 |
| + } |
| + return 0 |
| + }) |
| + return nil |
| + }) |
| + return out, err |
| +} |
| + |
| +// connectionMachine is the person's runner id as a ConnectionMachine |
| +// (found false when it is none of theirs). |
| +func (t *txn) connectionMachine(person, id string) (ConnectionMachine, bool, error) { |
| + rs, err := t.runners(person) |
| + if err != nil { |
| + return ConnectionMachine{}, false, err |
| + } |
| + for _, r := range rs { |
| + if r.ID == id { |
| + return machineOf(r), true, nil |
| + } |
| + } |
| + return ConnectionMachine{}, false, nil |
| +} |
| + |
| +// connectionRunner is where a row's commands go: its runner, or the |
| +// main runner for a row that names none. |
| +func (t *txn) connectionRunner(r connectionRecord) (string, error) { |
| + if r.RunnerID != "" { |
| + return r.RunnerID, nil |
| + } |
| + return t.s.authority.PrimaryRunner(t.db, r.Person) |
| +} |
| + |
| +// MacCredentialHeld reports whether the instance holds a runner as |
| +// having a model credential. A lookup error is an error, never "no". |
| +func (s *Store) MacCredentialHeld(ctx context.Context, runner string) (held bool, err error) { |
| + err = s.read(ctx, func(tx *gorm.DB) error { |
| + held, err = (&txn{s: s, db: tx}).macCredentialHeld(runner) |
| + return err |
| + }) |
| + return held, err |
| +} |
| + |
| +// macCredentialHeld is the instance's credential hold on runner (task |
| +// 15's unsandboxedAllowed reads it in its transaction). |
| +func (t *txn) macCredentialHeld(runner string) (bool, error) { |
| + var n int64 |
| + err := t.db.Raw(`SELECT count(*) FROM runners WHERE id = ? AND credential_held_at IS NOT NULL`, runner).Scan(&n).Error |
| + return n > 0, err |
| +} |
| + |
| +// holdCredential sets the hold on runner, from now, if it is not set. |
| +func (t *txn) holdCredential(runner string) error { |
| + return t.db.Exec(`UPDATE runners SET credential_held_at = ? WHERE id = ? AND credential_held_at IS NULL`, t.now(), runner).Error |
| +} |
| + |
| +// helloHold applies a worker's hello (protocol 37) to its credential |
| +// hold: held while the hello says anything of a credential may be there, |
| +// says nothing it can be judged by (no valid capability report), or the |
| +// instance has an attempt connecting there or a connect or secret frame |
| +// the Mac has not taken; released only when none of that is so. |
| +func (t *txn) helloHold(l Lease, h wire.Hello) error { |
| + runner := l.Runner.RunnerID |
| + c := cleanHello(h).Capabilities |
| + held := c == nil || c.ModelHold || len(c.HoldingItems) > 0 || c.Unproven == wire.UnprovenCredential || len(h.Connections) > 0 |
| + if !held { |
| + var connecting, untaken int64 |
| + if err := t.db.Model(&connectionRecord{}).Where("runner_id = ? AND state = ?", runner, wire.ConnConnecting).Count(&connecting).Error; err != nil { |
| + return err |
| + } |
| + if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind IN ? AND acked_at IS NULL", runner, []string{wire.FrameConnect, wire.FrameSecret}).Count(&untaken).Error; err != nil { |
| + return err |
| + } |
| + held = connecting+untaken > 0 |
| + } |
| + if held { |
| + return t.holdCredential(runner) |
| + } |
| + return t.db.Exec(`UPDATE runners SET credential_held_at = NULL WHERE id = ?`, runner).Error |
| +} |
| + |
| +// workerHello records what a worker's hello says of its connections: |
| +// below ProtocolMacEngineering nothing (its hello was read without them); |
| +// from it, that worker's connections and its credential hold. |
| +func (t *txn) workerHello(l Lease, h wire.Hello) error { |
| + if l.Role != wire.RoleWorker || l.Protocol < wire.ProtocolMacEngineering { |
| + return nil |
| + } |
| + if err := t.helloConnections(l, h.Connections); err != nil { |
| + return err |
| + } |
| + return t.helloHold(l, h) |
| +} |
| + |
| +// preferenceRunners are the runners a preference goes to: the main |
| +// runner, and every other runner holding one of the person's |
| +// connections (not signed out). |
| +func (t *txn) preferenceRunners(person string) ([]string, error) { |
| + primary, err := t.s.authority.PrimaryRunner(t.db, person) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var others []string |
| + if err := t.db.Model(&connectionRecord{}).Where("person = ? AND runner_id <> ? AND runner_id <> '' AND state <> ?", person, primary, wire.ConnSignedOut).Distinct("runner_id").Order("runner_id").Pluck("runner_id", &others).Error; err != nil { |
| + return nil, err |
| + } |
| + return append([]string{primary}, others...), nil |
| +} |
diff --git a/internal/equipo/chat_connections.go b/internal/equipo/chat_connections.go| index 370c074b..5fd2f848 100644 |
| --- a/internal/equipo/chat_connections.go |
| +++ b/internal/equipo/chat_connections.go |
| @@ -36,8 +36,9 @@ type modelLine struct { |
| // code the card seals (wire.PromptAuthorize). |
| SignIn bool |
| // A token or sign-in card seals to RunnerID's SealKey ("" when the |
| - // runner has none to give) for Endpoint. |
| - RunnerID, SealKey, Endpoint string |
| + // runner has none to give) for Endpoint. Machine is RunnerID when it |
| + // is not the main runner: switching the way of connecting stays there. |
| + RunnerID, SealKey, Endpoint, Machine string |
| // Phrases are the loading line's rotating words while the runner has |
| // not yet shown the provider's sign-in. |
| Phrases string |
| @@ -67,6 +68,9 @@ type modelsView struct { |
| // Metered are the API-key providers the chooser offers, each with |
| // its confirmation and budget form (connectors spec S1). |
| Metered []meteredAdd |
| + // Machines are the rows grouped by machine, the main runner first |
| + // (slice F task 11). |
| + Machines []connMachine |
| } |
| // loadingLine is the card an Add shows at once, before the server has |
| @@ -265,6 +269,11 @@ func (a *application) connectionsPageFor(w http.ResponseWriter, r *http.Request, |
| a.failure(w, r, chatError(err)) |
| return |
| } |
| + machines, err := a.store.Chat().ConnectionMachines(ctx, address) |
| + if err != nil { |
| + a.failure(w, r, chatError(err)) |
| + return |
| + } |
| v := connectionsPage(snap, today, prefer, runner, facts.Stated, time.Now().In(a.store.Chat().Zone(address))) |
| v.Adding = adding |
| v.Metered = meteredAdds(r.URL.Query().Get("refused")) |
| @@ -272,6 +281,7 @@ func (a *application) connectionsPageFor(w http.ResponseWriter, r *http.Request, |
| v.Rows[i].New = !adding && v.Rows[i].ID == r.URL.Query().Get("added") |
| } |
| rowFacts(&v, snap, facts) |
| + groupByMachine(&v, machines, snap.Runner.ID) |
| data.Models, data.ConnectionsStream = v, true |
| render(w, "models", data) |
| } |
| @@ -289,18 +299,28 @@ func (a *application) connectionsStart(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| a.chatActionTo(w, r, "/conversation/settings/connections/add", func(ctx context.Context, address string) error { |
| - provider, kind := r.PostFormValue("provider"), wire.KindSubscription |
| + provider, kind, machine := r.PostFormValue("provider"), wire.KindSubscription, r.PostFormValue("runner_id") |
| if r.PostFormValue("kind") == wire.KindToken { |
| kind = wire.KindToken |
| } |
| - // The card open gives way to the other way of connecting: the |
| - // sign-in by a link, or a token. |
| + // The card open on the same machine gives way to the other way of |
| + // connecting: the sign-in by a link, or a token. |
| conns, err := a.store.Chat().Connections(ctx, address) |
| if err != nil { |
| return err |
| } |
| + snap, err := a.store.Chat().Snapshot(ctx, address) |
| + if err != nil { |
| + return err |
| + } |
| + there := func(c wire.Connection) bool { |
| + if machine == "" || machine == snap.Runner.ID { |
| + return onPrimary(c, snap.Runner.ID) |
| + } |
| + return c.RunnerID == machine |
| + } |
| for _, c := range conns { |
| - if c.State == wire.ConnConnecting && c.Provider == provider && c.Kind != kind { |
| + if c.State == wire.ConnConnecting && c.Provider == provider && c.Kind != kind && there(c) { |
| // Switching is not giving up: the ended card goes unsaid. |
| if _, err := a.store.Chat().CancelConnection(ctx, address, c.ID); err != nil { |
| return err |
| @@ -310,7 +330,7 @@ func (a *application) connectionsStart(w http.ResponseWriter, r *http.Request) { |
| } |
| } |
| } |
| - _, err = a.store.Chat().StartConnection(ctx, address, wire.Connect{Provider: provider, Kind: kind}) |
| + _, err = a.store.Chat().StartConnection(ctx, address, wire.Connect{Provider: provider, Kind: kind, RunnerID: machine}) |
| if errors.Is(err, chat.ErrRunnerOffline) { |
| return nil |
| } |
diff --git a/internal/equipo/connections_machines_test.go b/internal/equipo/connections_machines_test.go| new file mode 100644 |
| index 00000000..b56fb632 |
| --- /dev/null |
| +++ b/internal/equipo/connections_machines_test.go |
| @@ -0,0 +1,157 @@ |
| +package equipo |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// connectionsHTML is the Connections page's content for v. |
| +func connectionsHTML(t *testing.T, v modelsView) string { |
| + t.Helper() |
| + var buf bytes.Buffer |
| + if err := pages["models"].ExecuteTemplate(&buf, "content", pageData{Models: v, Address: "me@example.com"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return buf.String() |
| +} |
| + |
| +// TestConnectionsPageGroupsByMachine (Mac runners slice F, task 11): |
| +// the Connections page groups the person's connections by machine, the |
| +// main runner first, each under its name. A Mac worker that can take |
| +// Claude (protocol 37, a seal key, not removing, not tainted) offers |
| +// "Add Claude to <Mac>", which starts on that Mac; a worker below 37, a |
| +// tainted one and the main runner offer none. A worker's connection with |
| +// the same local id as one on the main runner keeps its own usage and is |
| +// never the coordinator's. |
| +func TestConnectionsPageGroupsByMachine(t *testing.T) { |
| + key := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) |
| + snap := screenshotSnapshot() |
| + snap.Connections = append(snap.Connections, wire.Connection{ID: "c-mac", RunnerID: "w-studio", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, Label: "studio@tito.io", State: wire.ConnHealthy}) |
| + // The coordinator answered last on the main runner's claude-1; a card |
| + // connecting on the Mac seals to the Mac's own key. |
| + snap.Turns = append(snap.Turns, wire.Turn{ID: "t3", State: wire.TurnReplied, Connection: "claude-1", UpdatedAt: screenshotNow.Add(-time.Minute)}) |
| + macKey := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{9}, 32)) |
| + snap.Runner.SealKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{8}, 32)) |
| + snap.Runners = []wire.Runner{snap.Runner, {ID: "w-studio", Role: wire.RoleWorker, SealKey: macKey}} |
| + snap.Connections = append(snap.Connections, wire.Connection{ID: "c-mac-2", RunnerID: "w-studio", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"}}) |
| + machines := []chat.ConnectionMachine{ |
| + {ID: "w-old", Label: "Old Mac", Role: wire.RoleWorker, Platform: "darwin", Protocol: wire.ProtocolChangeDiffs, Online: true, SealKey: key}, |
| + {ID: "r1", Label: "docs-t1", Role: wire.RolePrimary, Platform: "linux", Protocol: wire.ProtocolMacEngineering, Online: true, SealKey: key}, |
| + {ID: "w-studio", Label: "Tito Studio", Role: wire.RoleWorker, Platform: "darwin", Protocol: wire.ProtocolMacEngineering, Online: true, SealKey: key}, |
| + {ID: "w-taint", Label: "Shared Mac", Role: wire.RoleWorker, Platform: "darwin", Protocol: wire.ProtocolMacEngineering, Online: true, SealKey: key, Tainted: true}, |
| + {ID: "w-new", Label: "Paul's Mac mini", Role: wire.RoleWorker, Platform: "darwin", Protocol: wire.ProtocolMacEngineering, Online: true, SealKey: key}, |
| + } |
| + today := map[string]int64{chat.UsageKey("r1", "", "claude-1"): 840, chat.UsageKey("r1", "w-studio", "claude-1"): 12_400} |
| + v := connectionsPage(snap, today, wire.Preferences{}, "docs-t1", nil, screenshotNow) |
| + groupByMachine(&v, machines, snap.Runner.ID) |
| + var names []string |
| + for _, m := range v.Machines { |
| + names = append(names, m.Name) |
| + } |
| + if strings.Join(names, "|") != "docs-t1|Tito Studio|Paul's Mac mini" { |
| + t.Fatalf("groups %v", names) |
| + } |
| + main, studio, mini := v.Machines[0], v.Machines[1], v.Machines[2] |
| + if !main.Primary || len(main.Rows) != 3 || main.AddClaude != "" { |
| + t.Fatalf("the main runner's group %+v", main) |
| + } |
| + if len(studio.Rows) != 1 || studio.Rows[0].ID != "c-mac" || studio.AddClaude != "Add Claude to Tito Studio" || studio.ID != "w-studio" { |
| + t.Fatalf("the Mac's group %+v", studio) |
| + } |
| + if len(mini.Rows) != 0 || mini.AddClaude != "Add Claude to Paul's Mac mini" { |
| + t.Fatalf("a Mac with nothing yet %+v", mini) |
| + } |
| + if rowOf(t, v, "c-claude").Usage != "840" || rowOf(t, v, "c-mac").Usage != "12k" { |
| + t.Fatalf("usage: main %q, Mac %q", rowOf(t, v, "c-claude").Usage, rowOf(t, v, "c-mac").Usage) |
| + } |
| + if len(v.Attempts) != 1 || v.Attempts[0].SealKey != macKey || v.Attempts[0].Machine != "w-studio" { |
| + t.Fatalf("the Mac's card %+v", v.Attempts) |
| + } |
| + if !slices.ContainsFunc(rowOf(t, v, "c-claude").Roles, func(r connRole) bool { return r.Name == copyText("conversation.coordinator") }) { |
| + t.Fatalf("the main runner's claude-1 is not the coordinator's: %+v", rowOf(t, v, "c-claude").Roles) |
| + } |
| + for _, r := range rowOf(t, v, "c-mac").Roles { |
| + if r.Name == copyText("conversation.coordinator") { |
| + t.Fatal("a Mac's connection shown as the coordinator's") |
| + } |
| + } |
| + |
| + html := connectionsHTML(t, v) |
| + group := func(id string) string { |
| + t.Helper() |
| + m := regexp.MustCompile(`(?s)<section equipo-conn-group data-machine="` + id + `".*?</section>`).FindString(html) |
| + if m == "" { |
| + t.Fatalf("no group %s:\n%s", id, html) |
| + } |
| + return m |
| + } |
| + if !strings.Contains(group("r1"), "<h2>docs-t1 ") || strings.Contains(group("r1"), "runner_id") { |
| + t.Fatalf("the main runner's group:\n%s", group("r1")) |
| + } |
| + studioHTML := group("w-studio") |
| + for _, want := range []string{"<h2>Tito Studio ", `data-connection="c-mac"`, `<input type="hidden" name="runner_id" value="w-studio">`, `<input type="hidden" name="provider" value="claude">`, ">Add Claude to Tito Studio<", `id="machine-w-studio"`} { |
| + if !strings.Contains(studioHTML, want) { |
| + t.Fatalf("the Mac's group lacks %q:\n%s", want, studioHTML) |
| + } |
| + } |
| + if strings.Index(html, `data-machine="r1"`) > strings.Index(html, `data-machine="w-studio"`) { |
| + t.Fatal("the main runner is not first") |
| + } |
| + for _, id := range []string{"w-old", "w-taint"} { |
| + if strings.Contains(html, `value="`+id+`"`) || strings.Contains(html, `data-machine="`+id+`"`) { |
| + t.Fatalf("%s offers Claude:\n%s", id, html) |
| + } |
| + } |
| + |
| + // One machine, as before: no machine heading. |
| + plain := connectionsPage(screenshotSnapshot(), nil, wire.Preferences{}, "docs-t1", nil, screenshotNow) |
| + groupByMachine(&plain, machines[1:2], "r1") |
| + if strings.Contains(connectionsHTML(t, plain), "data-machine=") { |
| + t.Fatal("a page with only the main runner grouped by machine") |
| + } |
| +} |
| + |
| +// TestTakesClaude: the one rule for offering Claude on a machine. |
| +func TestTakesClaude(t *testing.T) { |
| + key := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) |
| + ok := chat.ConnectionMachine{ID: "w", Role: wire.RoleWorker, Platform: "darwin", Protocol: wire.ProtocolMacEngineering, Online: true, SealKey: key} |
| + if !chat.TakesClaude(ok) { |
| + t.Fatal("a Mac at 37 does not take Claude") |
| + } |
| + for name, change := range map[string]func(*chat.ConnectionMachine){ |
| + "below 37": func(m *chat.ConnectionMachine) { m.Protocol = wire.ProtocolChangeDiffs }, |
| + "no key": func(m *chat.ConnectionMachine) { m.SealKey = "" }, |
| + "tainted": func(m *chat.ConnectionMachine) { m.Tainted = true }, |
| + "removing": func(m *chat.ConnectionMachine) { m.Removing = true }, |
| + "the main": func(m *chat.ConnectionMachine) { m.Role = wire.RolePrimary }, |
| + "not a Mac": func(m *chat.ConnectionMachine) { m.Platform = "linux" }, |
| + } { |
| + m := ok |
| + change(&m) |
| + if chat.TakesClaude(m) { |
| + t.Fatalf("%s takes Claude", name) |
| + } |
| + } |
| +} |
| + |
| +// TestMacConnectionNeedsLinksToAdd: Needs you for a Mac waiting for a |
| +// Claude connection links straight to adding Claude to that Mac. |
| +func TestMacConnectionNeedsLinksToAdd(t *testing.T) { |
| + task := wire.Task{ID: "t1", NeedsYou: wire.NeedsMacConnection, Steps: []wire.Step{{ID: "s1", Specialist: wire.SpecialistEngineering, RunnerID: "w-studio", RunnerLabel: "Tito Studio", Placement: wire.PlacementMacConnection, EngineeringStatus: &wire.EngineeringStatus{State: wire.EngineeringNoConnection}}}} |
| + d := decisionOf(task, taskLine{}) |
| + if d.AddClaude != "/conversation/settings/connections#machine-w-studio" || d.AddClaudeLabel != "Add Claude to Tito Studio" { |
| + t.Fatalf("decision %+v", d) |
| + } |
| + task.Steps[0].EngineeringStatus = &wire.EngineeringStatus{State: wire.EngineeringHomeOpen} |
| + if d := decisionOf(task, taskLine{}); d.AddClaude != "" { |
| + t.Fatalf("a Mac whose home is open offered Claude: %+v", d) |
| + } |
| +} |
diff --git a/internal/equipo/connections_view.go b/internal/equipo/connections_view.go| index 8a680d3f..814b5c25 100644 |
| --- a/internal/equipo/connections_view.go |
| +++ b/internal/equipo/connections_view.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "cmp" |
| "fmt" |
| "slices" |
| "strings" |
| @@ -18,6 +19,60 @@ import ( |
| // otherwise), and Add a connection with its chooser and the connecting |
| // card. |
| +// connMachine is one machine's connections on the Connections page |
| +// (Mac runners slice F, task 11): its name, its rows, and on a Mac that |
| +// can take Claude the "Add Claude to <Mac>" its button says. |
| +type connMachine struct { |
| + ID, Name string |
| + Primary bool |
| + Rows []connRow |
| + AddClaude string |
| +} |
| + |
| +// groupByMachine groups v's rows by the machine each is on, the main |
| +// runner (primary) first, then each other machine in enrolment order |
| +// that holds a row or can take Claude (chat.TakesClaude). A row on a |
| +// machine no longer listed stays with the main runner's. |
| +func groupByMachine(v *modelsView, machines []chat.ConnectionMachine, primary string) { |
| + listed := map[string]bool{} |
| + for _, m := range machines { |
| + listed[m.ID] = true |
| + } |
| + main := connMachine{ID: primary, Name: v.Runner, Primary: true} |
| + byRunner := map[string][]connRow{} |
| + for _, r := range v.Rows { |
| + if r.Machine == "" || !listed[r.Machine] { |
| + main.Rows = append(main.Rows, r) |
| + } else { |
| + byRunner[r.Machine] = append(byRunner[r.Machine], r) |
| + } |
| + } |
| + v.Machines = []connMachine{main} |
| + for _, m := range machines { |
| + if m.ID == primary { |
| + continue |
| + } |
| + g := connMachine{ID: m.ID, Name: cmp.Or(m.Label, m.ID), Rows: byRunner[m.ID]} |
| + if chat.TakesClaude(m) { |
| + g.AddClaude = fmt.Sprintf(copyText("chat.connections.add_to"), g.Name) |
| + } |
| + if len(g.Rows) > 0 || g.AddClaude != "" { |
| + v.Machines = append(v.Machines, g) |
| + } |
| + } |
| +} |
| + |
| +// onPrimary: c is on the main runner (a row before slice F names no |
| +// runner, and is). |
| +func onPrimary(c wire.Connection, primary string) bool { |
| + return c.RunnerID == "" || c.RunnerID == primary |
| +} |
| + |
| +// connKey is c's key for usage and live roles (chat.UsageKey). |
| +func connKey(c wire.Connection, primary string) string { |
| + return chat.UsageKey(primary, c.RunnerID, c.LocalID) |
| +} |
| + |
| // connRow is one connection the person holds (or held). |
| type connRow struct { |
| // Label is the account the provider named (the success card's); |
| @@ -40,6 +95,9 @@ type connRow struct { |
| Usage, UsageTail string |
| // PreferRevision is the preference's, for Make preferred. |
| PreferRevision int64 |
| + // Machine is the runner a row is on when that is not the main |
| + // runner: its recovery starts there. |
| + Machine string |
| // Needs is the one recovery action a row that needs the person shows |
| // (Sign in again, Connect again). |
| Needs string |
| @@ -130,6 +188,7 @@ type connOption struct { |
| func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Preferences, runner string, stated map[string]string, now time.Time) modelsView { |
| v := modelsView{Offline: !snap.Runner.Online, Runner: runner, Cursor: snap.Cursor} |
| v.Prefer = preferControl(prefer) |
| + primary := snap.Runner.ID |
| live := liveRoles(snap) |
| coord := coordinatorOn(snap) |
| var held []wire.Connection |
| @@ -141,9 +200,15 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| line.Endpoint = kp.Endpoint |
| line.Title, line.Sub = fmt.Sprintf(copyText("chat.connections.metered.title"), kp.Name), fmt.Sprintf(copyText("chat.connections.metered.key_sub"), kp.Name) |
| } |
| + // The card seals to the key of the machine it is on. |
| if c.RunnerID == snap.Runner.ID { |
| line.SealKey = snap.Runner.SealKey |
| } |
| + for _, r := range snap.Runners { |
| + if r.ID == c.RunnerID && r.ID != primary { |
| + line.SealKey, line.Machine = r.SealKey, r.ID |
| + } |
| + } |
| line.SignIn = c.Prompt != nil && c.Prompt.Kind == wire.PromptAuthorize && c.Kind != wire.KindToken |
| if line.SignIn { |
| line.Endpoint = wire.EndpointClaudeCode |
| @@ -179,7 +244,8 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| names := namesOf(held, labels) |
| // A metered connection never runs the coordinator (spec §0 decision |
| // 8): the answering line and the roles leave it out. |
| - answerable := slices.DeleteFunc(slices.Clone(held), func(c wire.Connection) bool { return c.Kind == wire.KindAPIKey }) |
| + // Nor does one on another machine than the main runner. |
| + answerable := slices.DeleteFunc(slices.Clone(held), func(c wire.Connection) bool { return c.Kind == wire.KindAPIKey || !onPrimary(c, primary) }) |
| if coord == "" { |
| // Nothing answered yet: the first that can, the preferred first. |
| for _, c := range answerable { |
| @@ -190,7 +256,11 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| } |
| work := workOn(snap, answerable, coord) |
| for _, c := range held { |
| - row := connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), Label: c.Label, Tag: chat.LabelOf(labels, c), Plan: planLabel(c.Plan), Kind: c.Kind, State: c.State, Usage: tokensText(today[c.LocalID]), PreferRevision: prefer.Revision} |
| + key := connKey(c, primary) |
| + row := connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), Label: c.Label, Tag: chat.LabelOf(labels, c), Plan: planLabel(c.Plan), Kind: c.Kind, State: c.State, Usage: tokensText(today[key]), PreferRevision: prefer.Revision} |
| + if !onPrimary(c, primary) { |
| + row.Machine = c.RunnerID |
| + } |
| _, row.UsageTail, _ = strings.Cut(copyText("chat.connections.usage_today"), "%s") |
| if c.State == wire.ConnError { |
| row.State = wire.ConnSignInAgain |
| @@ -238,11 +308,11 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| row.RolesNote = fmt.Sprintf(copyText("chat.connections.roles.resting_moved"), strings.Join(to, copyText("chat.connections.and"))) |
| } |
| default: |
| - if c.LocalID == coord { |
| - row.Roles = append(row.Roles, connRole{Name: copyText("conversation.coordinator"), Live: live[c.LocalID+"/coordinator"]}) |
| + if c.LocalID == coord && onPrimary(c, primary) { |
| + row.Roles = append(row.Roles, connRole{Name: copyText("conversation.coordinator"), Live: live[key+"/coordinator"]}) |
| } |
| for _, r := range []string{wire.SpecialistEngineering, wire.SpecialistReview} { |
| - if live[c.LocalID+"/"+r] { |
| + if live[key+"/"+r] { |
| row.Roles = append(row.Roles, connRole{Name: copyText("work.specialist." + r), Live: true}) |
| } |
| } |
| @@ -289,7 +359,7 @@ func rowFacts(v *modelsView, snap wire.Snapshot, f chat.RowFacts) { |
| if row.State != wire.ConnHealthy || len(row.Meters) > 0 { |
| continue |
| } |
| - if c.Kind == wire.KindToken && f.Served[c.LocalID] && (c.Headroom == nil || len(c.Headroom.Windows) == 0) { |
| + if c.Kind == wire.KindToken && f.Served[connKey(c, snap.Runner.ID)] && (c.Headroom == nil || len(c.Headroom.Windows) == 0) { |
| row.UsageNote = copyText("chat.connections.usage_unreported") |
| } else { |
| row.UsageNote = fmt.Sprintf(copyText("chat.connections.usage_pending"), row.Name) |
| @@ -340,7 +410,7 @@ func liveRoles(snap wire.Snapshot) map[string]bool { |
| for _, k := range snap.Tasks { |
| for _, s := range k.Steps { |
| if s.State == wire.StepRunning && s.Account != "" { |
| - out[s.Account+"/"+s.Specialist] = true |
| + out[chat.UsageKey(snap.Runner.ID, s.RunnerID, s.Account)+"/"+s.Specialist] = true |
| } |
| } |
| } |
| @@ -358,7 +428,7 @@ func coordinatorOn(snap wire.Snapshot) string { |
| } |
| } |
| for _, c := range snap.Connections { |
| - if c.LocalID == on && c.State == wire.ConnHealthy { |
| + if c.LocalID == on && c.State == wire.ConnHealthy && onPrimary(c, snap.Runner.ID) { |
| return on |
| } |
| } |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 85ad2505..01ff2776 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -2108,13 +2108,15 @@ var pageCopy = map[string]string{ |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "runner.verdict.skipped": "Not run", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "runner.verdict.unavailable": "Unavailable", |
| - "runner.unproven.record_incomplete": "Equipo could not prove that an earlier step on this Mac stopped completely, so that step stays unfinished.", // COPY REVIEW PENDING |
| - "runner.probe_detail.turn_busy": "The Mac was busy with other work, so this was not checked.", // COPY REVIEW PENDING |
| - "runner.mac.home_open": "Other people on this Mac can open %[1]s's home folder, so Equipo won't keep Claude there. Run chmod 700 ~ as %[1]s, then try again.", // COPY REVIEW PENDING |
| - "runner.mac.home_open_folder": "Other people on this Mac can reach a folder where %[1]s keeps Claude, so Equipo won't keep Claude there. The runner's log names the folder and what to change.", // COPY REVIEW PENDING |
| - "runner.unproven.credential_unproven": "This Mac could not prove that an earlier Claude sign-in or check ended, so it keeps its Claude connections closed. Restart the Mac to clear it.", // COPY REVIEW PENDING |
| - "runner.mac.keychain_item": "This Mac's Keychain has an item named %[1]s, so Equipo won't keep Claude there. Remove it in Keychain Access as %[2]s, then try again.", // COPY REVIEW PENDING |
| + "runner.verdict.unavailable": "Unavailable", |
| + "runner.unproven.record_incomplete": "Equipo could not prove that an earlier step on this Mac stopped completely, so that step stays unfinished.", // COPY REVIEW PENDING |
| + "runner.probe_detail.turn_busy": "The Mac was busy with other work, so this was not checked.", // COPY REVIEW PENDING |
| + "runner.mac.home_open": "Other people on this Mac can open %[1]s's home folder, so Equipo won't keep Claude there. Run chmod 700 ~ as %[1]s, then try again.", // COPY REVIEW PENDING |
| + "runner.mac.home_open_folder": "Other people on this Mac can reach a folder where %[1]s keeps Claude, so Equipo won't keep Claude there. The runner's log names the folder and what to change.", // COPY REVIEW PENDING |
| + "runner.unproven.credential_unproven": "This Mac could not prove that an earlier Claude sign-in or check ended, so it keeps its Claude connections closed. Restart the Mac to clear it.", // COPY REVIEW PENDING |
| + "runner.mac.keychain_item": "This Mac's Keychain has an item named %[1]s, so Equipo won't keep Claude there. Remove it in Keychain Access as %[2]s, then try again.", // COPY REVIEW PENDING |
| + "chat.connections.add_to": "Add Claude to %s", // COPY REVIEW PENDING |
| + "chat.connections.reason.mac_claude_only": "Only Claude can be added to a Mac for now.", // COPY REVIEW PENDING |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "runner.origin": "Equipo address:", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/migrations/0120_mac_engineering.sql b/internal/equipo/migrations/0120_mac_engineering.sql| index d09d75df..eebfe5b4 100644 |
| --- a/internal/equipo/migrations/0120_mac_engineering.sql |
| +++ b/internal/equipo/migrations/0120_mac_engineering.sql |
| @@ -17,3 +17,9 @@ ALTER TABLE chat_questions ADD COLUMN candidate_sha text; |
| -- The Mac tags a task's Engineering was first found to need (JSON list), |
| -- written once at placement and never cleared. |
| ALTER TABLE chat_tasks ADD COLUMN mac_needs text; |
| +-- A Mac worker held as having a model credential (D1): set when a |
| +-- connection there starts connecting, cleared only once the Mac says |
| +-- nothing of one is left. |
| +ALTER TABLE runners ADD COLUMN credential_held_at datetime; |
| +-- The runner a usage row came from: local ids repeat across runners. |
| +ALTER TABLE chat_usage ADD COLUMN runner_id text; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 7fa79b50..0cc99a16 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -855,3 +855,5 @@ ALTER TABLE chat_questions ADD COLUMN runner_id text; |
| ALTER TABLE chat_questions ADD COLUMN base_sha text; |
| ALTER TABLE chat_questions ADD COLUMN candidate_sha text; |
| ALTER TABLE chat_tasks ADD COLUMN mac_needs text; |
| +ALTER TABLE runners ADD COLUMN credential_held_at datetime; |
| +ALTER TABLE chat_usage ADD COLUMN runner_id text; |
diff --git a/internal/equipo/setup/runner_models.go b/internal/equipo/setup/runner_models.go| index a75a73dc..5c51e55d 100644 |
| --- a/internal/equipo/setup/runner_models.go |
| +++ b/internal/equipo/setup/runner_models.go |
| @@ -24,6 +24,9 @@ type Runner struct { |
| // RemovingAt: removal asked for while work it may have started was |
| // still running; it is revoked once that work's end is proven. |
| RemovingAt *time.Time |
| + // CredentialHeldAt: since when the instance holds this Mac worker as |
| + // having a model credential (slice F, D1); nil when it holds none. |
| + CredentialHeldAt *time.Time |
| } |
| // RunnerReport is a runner's own report, for the Connections view. |
diff --git a/internal/equipo/templates/models.html b/internal/equipo/templates/models.html| index 1f8805da..ab3e0805 100644 |
| --- a/internal/equipo/templates/models.html |
| +++ b/internal/equipo/templates/models.html |
| @@ -4,8 +4,8 @@ |
| {{define "conn-star"}}<span equipo-sparkle data-conn-star aria-hidden="true"><svg viewBox="0 0 16 16" focusable="false"><path d="M8 0C8.6 4.6 11.4 7.4 16 8 11.4 8.6 8.6 11.4 8 16 7.4 11.4 4.6 8.6 0 8 4.6 7.4 7.4 4.6 8 0Z"/><circle cx="8" cy="8" r="1.7"/></svg><i data-sat="1"></i><i data-sat="2"></i><i data-sat="3"></i></span>{{end}} |
| {{define "conn-copy"}}<button type="button" rst-btn data-copy="{{.}}" data-copied="{{copy "chat.connections.copied"}}">{{copy "chat.connections.copy"}}</button>{{end}} |
| {{define "conn-copy-link"}}<button type="button" rst-btn data-copy="{{.}}" data-copy-link data-copied="{{copy "chat.connections.copied"}}">{{copy "chat.connections.copy_link"}}</button>{{end}} |
| -{{define "conn-sign-in-instead"}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="subscription"><button equipo-link type="submit" data-sign-in-instead>{{copy "chat.connections.sign_in_instead"}}</button></form>{{end}} |
| -{{define "conn-paste-instead"}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="token"><button equipo-link type="submit" data-paste-instead>{{copy "chat.connections.paste_token_instead"}}</button></form>{{end}} |
| +{{define "conn-sign-in-instead"}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude">{{with .}}<input type="hidden" name="runner_id" value="{{.}}">{{end}}<input type="hidden" name="kind" value="subscription"><button equipo-link type="submit" data-sign-in-instead>{{copy "chat.connections.sign_in_instead"}}</button></form>{{end}} |
| +{{define "conn-paste-instead"}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude">{{with .}}<input type="hidden" name="runner_id" value="{{.}}">{{end}}<input type="hidden" name="kind" value="token"><button equipo-link type="submit" data-paste-instead>{{copy "chat.connections.paste_token_instead"}}</button></form>{{end}} |
| {{define "conn-waiting"}}<p equipo-conn-waiting aria-live="polite">{{template "conn-star"}}<span data-words>{{.}}</span></p>{{end}} |
| {{define "conn-cancel"}}<form method="post" action="/conversation/connections/{{.}}/cancel" equipo-inline-form><button rst-btn data-quiet type="submit" data-connection-cancel>{{copy "chat.connections.cancel"}}</button></form>{{end}} |
| {{define "conn-attempt"}}<div equipo-conn-card data-connection="{{.ID}}" data-connecting data-provider="{{.Provider}}"{{if eq .Kind "token"}} data-kind="token" data-runner="{{.RunnerID}}" data-endpoint="{{.Endpoint}}"{{with .SealKey}} data-seal-key="{{.}}"{{end}}{{else if eq .Kind "api_key"}} data-kind="api_key" data-runner="{{.RunnerID}}" data-endpoint="{{.Endpoint}}"{{with .SealKey}} data-seal-key="{{.}}"{{end}}{{else if .SignIn}} data-kind="sign_in" data-runner="{{.RunnerID}}" data-endpoint="{{.Endpoint}}" data-attempt="{{.Prompt.Attempt}}"{{with .SealKey}} data-seal-key="{{.}}"{{end}}{{end}}> |
| @@ -17,7 +17,7 @@ |
| <li><div><form method="post" action="/conversation/connections/{{.ID}}/email" equipo-conn-token data-code-form autocomplete="off"><input type="hidden" name="from" value="add"><label for="code-{{.ID}}">{{copy "chat.connections.code_paste"}}</label>{{if .Prompt.WrongCode}}<span equipo-conn-small data-code-wrong data-tone="bad" role="status">{{copy "chat.connections.code_wrong"}}</span>{{end}}<span equipo-conn-token-row><input rst-input id="code-{{.ID}}" type="password" data-code-field autocomplete="off" autocapitalize="off" spellcheck="false" required></span><span equipo-conn-small data-token-note role="status" hidden data-bad="{{copy "chat.connections.code_bad"}}" data-failed="{{copy "chat.connections.code_failed"}}" data-no-key="{{copy "chat.connections.code_no_key"}}"></span><span equipo-conn-small data-token-trust>{{copy "chat.connections.token_sealed"}}</span><span equipo-conn-signin-email><label for="signin-email-{{.ID}}">{{copy "chat.connections.email_ask"}}</label><input rst-input id="signin-email-{{.ID}}" type="email" name="email" maxlength="254" autocapitalize="off" spellcheck="false" data-email-field><span equipo-conn-small>{{copy "chat.connections.email_hint"}}</span><span equipo-conn-small data-email-note role="status" hidden data-bad="{{copy "chat.connections.email_bad"}}" data-tone="bad"></span></span><span><button rst-btn="primary" type="submit" data-code-connect>{{copy "chat.connections.token_connect"}}</button></span></form></div></li> |
| </ol> |
| <div data-token-waiting hidden>{{template "conn-waiting" (copy "chat.connections.waiting_code")}}</div> |
| -<div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-paste-instead"}}</span>{{template "conn-cancel" .ID}}</div> |
| +<div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-paste-instead" .Machine}}</span>{{template "conn-cancel" .ID}}</div> |
| {{else}}{{template "conn-waiting" (copy "chat.connections.waiting_code")}} |
| <p equipo-conn-small>{{copy "chat.connections.token_sealed"}}</p> |
| <div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div> |
| @@ -40,7 +40,7 @@ |
| <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> |
| -<div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-sign-in-instead"}}</span>{{template "conn-cancel" .ID}}</div> |
| +<div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-sign-in-instead" .Machine}}</span>{{template "conn-cancel" .ID}}</div> |
| {{else}}<div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div> |
| {{end}}</div>{{end}} |
| {{define "conn-api-key"}}{{if and .Prompt (eq .Prompt.Kind "api_key")}}<ol equipo-conn-steps data-key-steps> |
| @@ -84,11 +84,11 @@ |
| <p equipo-conn-facts><span equipo-conn-state data-connection-state data-s="{{.State}}"{{with .WordsAt}} title="{{.}}"{{end}}>{{.Words}}</span>{{with .Expires}}<span equipo-conn-expires data-token-expires>{{.}}</span>{{end}}{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"{{with .At}} title="{{.}}"{{end}}><span equipo-conn-bar><i data-w="{{.Used}}"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}{{with .Age}}<span equipo-conn-usage-note data-reading-age>{{.}}</span>{{end}}{{with .UsageNote}}<span equipo-conn-usage-note data-usage-note>{{.}}</span>{{end}}</p> |
| {{if .Metered}}{{template "conn-metered-row" .}}{{end}} |
| {{if .AskEmail}}<details equipo-conn-email data-account-email="{{.ID}}"{{if .AskOpen}} open{{end}}><summary>{{if .Stated}}{{copy "chat.connections.email_change"}}{{else}}{{copy "chat.connections.email_add"}}{{end}}</summary><form method="post" action="/conversation/connections/{{.ID}}/email" equipo-conn-token data-email-form autocomplete="off"><label for="email-{{.ID}}">{{copy "chat.connections.email_ask"}}</label><span equipo-conn-token-row><input rst-input id="email-{{.ID}}" type="email" name="email" maxlength="254" value="{{.Stated}}" autocapitalize="off" spellcheck="false" data-email-field><button rst-btn type="submit" data-email-save>{{copy "form.save"}}</button></span><span equipo-conn-small>{{copy "chat.connections.email_hint"}}</span><span equipo-conn-small data-email-note role="status" hidden data-bad="{{copy "chat.connections.email_bad"}}" data-tone="bad"></span></form></details>{{end}} |
| -{{if .Renew}}<div equipo-conn-renew data-token-renew>{{copy "chat.connections.token_renew"}} <form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}"><button equipo-link type="submit" data-renew>{{copy "chat.connections.sign_in_again_action"}}</button></form></div>{{end}} |
| +{{if .Renew}}<div equipo-conn-renew data-token-renew>{{copy "chat.connections.token_renew"}} <form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}">{{with .Machine}}<input type="hidden" name="runner_id" value="{{.}}">{{end}}<button equipo-link type="submit" data-renew>{{copy "chat.connections.sign_in_again_action"}}</button></form></div>{{end}} |
| {{if .Roles}}<p equipo-conn-roles><span equipo-conn-roles-label>{{copy "chat.connections.serving"}}</span>{{range .Roles}}<span equipo-conn-chip{{if .Live}} data-live{{end}}>{{if .Live}}{{template "conn-star"}}{{end}}{{.Name}}</span>{{end}}</p>{{else}}{{with .RolesNote}}<p equipo-conn-roles><span equipo-conn-roles-note>{{.}}</span></p>{{end}}{{end}} |
| </div> |
| <div equipo-conn-side> |
| -<div equipo-conn-actions>{{if .Needs}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}"><button rst-btn type="submit" data-recover="{{.Provider}}">{{.Needs}}</button></form>{{end}}{{if or .MakePreferred .SignOut .Forget .CheckAgain}}<span equipo-conn-quiet>{{template "conn-quiet" .}}</span><details equipo-conn-more><summary aria-label="{{copy "chat.connections.more"}}">{{icon "more-horizontal"}}</summary><div>{{template "conn-quiet" .}}</div></details>{{end}}</div> |
| +<div equipo-conn-actions>{{if .Needs}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}">{{with .Machine}}<input type="hidden" name="runner_id" value="{{.}}">{{end}}<button rst-btn type="submit" data-recover="{{.Provider}}">{{.Needs}}</button></form>{{end}}{{if or .MakePreferred .SignOut .Forget .CheckAgain}}<span equipo-conn-quiet>{{template "conn-quiet" .}}</span><details equipo-conn-more><summary aria-label="{{copy "chat.connections.more"}}">{{icon "more-horizontal"}}</summary><div>{{template "conn-quiet" .}}</div></details>{{end}}</div> |
| <p equipo-conn-usage>{{if eq .State "signed_out"}}{{printf (copy "chat.connections.tokens_before") .Usage}}{{else}}<b>{{.Usage}}</b>{{.UsageTail}}{{end}}</p> |
| </div> |
| </article>{{end}} |
| @@ -105,14 +105,19 @@ |
| {{if .Models.Adding}}{{range .Models.Ended}}{{template "conn-note" (dict "Row" . "Add" $.Models.Adding)}}{{end}} |
| <div equipo-conn-add-area data-attempts>{{range .Models.Attempts}}{{template "conn-attempt" .}}{{else}}{{template "conn-chooser" .Models}}{{end}}</div> |
| <div hidden>{{range .Models.Rows}}<i data-held-connection="{{.ID}}" data-state="{{.State}}" data-account="{{.Label}}"></i>{{end}}</div> |
| -{{else if .Models.Rows}}{{with .Models.Answering}}<section equipo-conn-answering{{with .Tone}} data-tone="{{.}}"{{end}} aria-label="{{copy "chat.connections.title"}}" data-answering>{{if .Tone}}<span equipo-conn-lead-icon aria-hidden="true">{{icon "alert-triangle"}}</span>{{else}}{{template "conn-star"}}{{end}}<p equipo-conn-lead{{with .LeadAt}} title="{{.}}"{{end}}>{{.LeadStart}}<b>{{.LeadName}}</b>{{.LeadEnd}}</p><p equipo-conn-sub>{{.Sub}}{{if .SeeConversation}} <a href="/conversation">{{copy "chat.connections.answering.see"}}</a>{{end}}</p> |
| +{{else if or .Models.Rows (gt (len .Models.Machines) 1)}}{{if .Models.Rows}}{{with .Models.Answering}}<section equipo-conn-answering{{with .Tone}} data-tone="{{.}}"{{end}} aria-label="{{copy "chat.connections.title"}}" data-answering>{{if .Tone}}<span equipo-conn-lead-icon aria-hidden="true">{{icon "alert-triangle"}}</span>{{else}}{{template "conn-star"}}{{end}}<p equipo-conn-lead{{with .LeadAt}} title="{{.}}"{{end}}>{{.LeadStart}}<b>{{.LeadName}}</b>{{.LeadEnd}}</p><p equipo-conn-sub>{{.Sub}}{{if .SeeConversation}} <a href="/conversation">{{copy "chat.connections.answering.see"}}</a>{{end}}</p> |
| {{if not .Tone}}{{with $.Models.Prefer}}<div equipo-conn-prefer><span>{{copy "chat.connections.prefer"}}</span><span equipo-seg role="group" aria-label="{{copy "chat.connections.prefer"}}">{{range .Options}}<form method="post" action="/conversation/connections/prefer" equipo-inline-form><input type="hidden" name="provider" value="{{.Value}}"><input type="hidden" name="revision" value="{{$.Models.Prefer.Revision}}"><button type="submit" aria-pressed="{{.On}}" data-prefer="{{.Value}}">{{.Label}}</button></form>{{end}}</span><span equipo-conn-hint>{{.Hint}}</span></div>{{end}}{{end}} |
| -</section>{{end}} |
| -<section equipo-conn-group><h2>{{copy "chat.connections.group"}} <span equipo-conn-n>{{len .Models.Rows}}</span><span equipo-conn-hint>{{copy "chat.connections.usage_resets"}}</span></h2> |
| +</section>{{end}}{{end}} |
| +{{if gt (len .Models.Machines) 1}}{{range $i, $m := .Models.Machines}}<section equipo-conn-group data-machine="{{$m.ID}}" id="machine-{{$m.ID}}"><h2>{{$m.Name}} <span equipo-conn-n>{{len $m.Rows}}</span>{{if eq $i 0}}<span equipo-conn-hint>{{copy "chat.connections.usage_resets"}}</span>{{end}}</h2> |
| +<div equipo-conn-list{{if $m.Primary}} data-connection-list{{end}} aria-live="polite">{{range $m.Rows}}{{template "conn-row" .}}{{end}}</div> |
| +{{if $m.Primary}}{{range $.Models.Ended}}{{template "conn-note" (dict "Row" . "Add" $.Models.Adding)}}{{end}} |
| +<div equipo-conn-add-foot>{{template "conn-add-link" false}}<span>{{copy "chat.connections.add_hint"}}</span></div>{{end}} |
| +{{with $m.AddClaude}}<div equipo-conn-add-foot><form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="subscription"><input type="hidden" name="runner_id" value="{{$m.ID}}"><button rst-btn type="submit" data-add-claude="{{$m.ID}}">{{icon "plug"}}{{.}}</button></form></div>{{end}} |
| +</section>{{end}}{{else}}<section equipo-conn-group><h2>{{copy "chat.connections.group"}} <span equipo-conn-n>{{len .Models.Rows}}</span><span equipo-conn-hint>{{copy "chat.connections.usage_resets"}}</span></h2> |
| <div equipo-conn-list data-connection-list aria-live="polite">{{range .Models.Rows}}{{template "conn-row" .}}{{end}}</div> |
| {{range .Models.Ended}}{{template "conn-note" (dict "Row" . "Add" $.Models.Adding)}}{{end}} |
| <div equipo-conn-add-foot>{{template "conn-add-link" false}}<span>{{copy "chat.connections.add_hint"}}</span></div> |
| -</section> |
| +</section>{{end}} |
| {{else}}<section equipo-conn-empty data-empty-state="chat.connections.empty"><p equipo-conn-pair>{{template "conn-mark" "claude"}}{{template "conn-mark" "codex"}}</p> |
| <h2>{{copy "chat.connections.empty_title"}}</h2> |
| <p>{{copy "chat.connections.empty_body"}}</p> |
diff --git a/internal/equipo/templates/work_parts.html b/internal/equipo/templates/work_parts.html| index 4e1be335..feb29522 100644 |
| --- a/internal/equipo/templates/work_parts.html |
| +++ b/internal/equipo/templates/work_parts.html |
| @@ -37,7 +37,7 @@ |
| {{if $.Head}}{{template "mono" $t.Mono}}<div equipo-d-title><a href="/tasks/{{$t.ID}}">{{$t.Title}}</a><div equipo-quiet>{{template "placement-chip" $t}} · {{template "source" $t}}</div></div>{{end}} |
| <p equipo-d-why>{{.Why}}</p> |
| {{with .Ask}}<p equipo-d-ask>{{.}}</p>{{end}}{{if .Link}}<p equipo-quiet data-direction-line>{{with .LinkText}}{{.}} {{end}}<a equipo-link href="{{.Link}}" rel="noopener noreferrer" target="_blank" data-direction-link>{{.LinkLabel}}</a>{{with .AltLink}} <a equipo-link href="{{.}}" rel="noopener noreferrer" target="_blank" data-direction-branch>{{$t.Decision.AltLabel}}</a>{{end}}</p>{{end}}{{with .Said}}<p equipo-quiet data-triage-said>{{.}}</p>{{end}}{{with .Failed}}<p equipo-quiet data-triage-failed>{{.}}</p>{{end}}{{with .Recommend}}<p equipo-quiet data-triage-recommend>{{.}}</p>{{end}} |
| -<div equipo-d-actions>{{if .CopyContinue}}<form method="post" action="/conversation/tasks/{{$t.ID}}/continue-without-copy"><input type="hidden" name="from" value="{{$.From}}"><button equipo-btn data-primary type="submit" data-copy-continue>{{copy "copy.continue"}}</button></form>{{end}}{{with .Card}}<form method="post" action="/conversation/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="task" value="{{$t.ID}}">{{if $.Task.Decision.Note}}<textarea rst-input name="note" maxlength="1000" rows="2" aria-label="{{copy "chat.card.direction_note"}}" placeholder="{{copy "chat.card.direction_note"}}" data-direction-note></textarea>{{end}}{{range $.Task.Decision.Choices}}<button equipo-btn{{if .Primary}} data-primary{{end}} type="submit" name="choice" value="{{.Value}}" data-merge-choice="{{.Value}}">{{.Label}}</button>{{end}}</form>{{end}}{{if .Fold}}<form method="post" action="/tasks/{{$t.ID}}/duplicate"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="of" value="{{$t.Dup.ID}}"><button equipo-btn data-primary type="submit" data-task-duplicate>{{copy "work.decide.fold"}}</button></form>{{end}}{{if .Recover}}<form method="post" action="/conversation/tasks/{{$t.ID}}/recover"><input type="hidden" name="from" value="{{$.From}}"><button equipo-btn data-primary type="submit" data-task-recover>{{copy "work.recover"}}</button></form>{{end}}{{with .Unsandboxed}}<details equipo-mach-confirm data-unsandboxed><summary equipo-btn>{{copy "work.decide.unsandboxed"}}</summary><div><p>{{.Warning}}</p><form method="post" action="/conversation/tasks/{{$t.ID}}/unsandboxed"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="step" value="{{.Step}}"><input type="hidden" name="attempt" value="{{.Attempt}}"><button equipo-btn data-danger type="submit" data-task-unsandboxed>{{copy "work.decide.unsandboxed_confirm"}}</button></form></div></details>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{$t.ID}}/retry"><input type="hidden" name="from" value="{{$.From}}"><button {{if .Fold}}equipo-link{{else}}equipo-btn data-primary{{end}} type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Round}}<form method="post" action="/conversation/tasks/{{$t.ID}}/round"><input type="hidden" name="from" value="{{$.From}}"><button equipo-btn data-primary type="submit" data-task-round>{{copy "work.decide.round"}}</button></form>{{end}}{{if .Talk}}<a equipo-btn href="/conversation?about={{$t.ID}}" data-ask-coordinator>{{copy "work.decide.ask_coordinator"}}</a>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{$t.ID}}/cancel"><input type="hidden" name="from" value="{{$.From}}"><button equipo-link type="submit" data-task-cancel>{{copy "work.decide.cancel"}}</button></form>{{end}}{{with .Hint}}<span equipo-quiet>{{.}}</span>{{end}}<span equipo-d-quiet>{{if .Mac}}<a equipo-link href="/conversation/settings/machines/add" data-set-up-mac>{{copy "work.decide.mac_set_up"}}</a>{{end}}<a equipo-link href="/conversation?about={{$t.ID}}" data-ask-about>{{copy "work.ask_about"}}</a></span></div> |
| +<div equipo-d-actions>{{if .CopyContinue}}<form method="post" action="/conversation/tasks/{{$t.ID}}/continue-without-copy"><input type="hidden" name="from" value="{{$.From}}"><button equipo-btn data-primary type="submit" data-copy-continue>{{copy "copy.continue"}}</button></form>{{end}}{{with .Card}}<form method="post" action="/conversation/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="task" value="{{$t.ID}}">{{if $.Task.Decision.Note}}<textarea rst-input name="note" maxlength="1000" rows="2" aria-label="{{copy "chat.card.direction_note"}}" placeholder="{{copy "chat.card.direction_note"}}" data-direction-note></textarea>{{end}}{{range $.Task.Decision.Choices}}<button equipo-btn{{if .Primary}} data-primary{{end}} type="submit" name="choice" value="{{.Value}}" data-merge-choice="{{.Value}}">{{.Label}}</button>{{end}}</form>{{end}}{{if .Fold}}<form method="post" action="/tasks/{{$t.ID}}/duplicate"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="of" value="{{$t.Dup.ID}}"><button equipo-btn data-primary type="submit" data-task-duplicate>{{copy "work.decide.fold"}}</button></form>{{end}}{{if .Recover}}<form method="post" action="/conversation/tasks/{{$t.ID}}/recover"><input type="hidden" name="from" value="{{$.From}}"><button equipo-btn data-primary type="submit" data-task-recover>{{copy "work.recover"}}</button></form>{{end}}{{with .Unsandboxed}}<details equipo-mach-confirm data-unsandboxed><summary equipo-btn>{{copy "work.decide.unsandboxed"}}</summary><div><p>{{.Warning}}</p><form method="post" action="/conversation/tasks/{{$t.ID}}/unsandboxed"><input type="hidden" name="from" value="{{$.From}}"><input type="hidden" name="step" value="{{.Step}}"><input type="hidden" name="attempt" value="{{.Attempt}}"><button equipo-btn data-danger type="submit" data-task-unsandboxed>{{copy "work.decide.unsandboxed_confirm"}}</button></form></div></details>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{$t.ID}}/retry"><input type="hidden" name="from" value="{{$.From}}"><button {{if .Fold}}equipo-link{{else}}equipo-btn data-primary{{end}} type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Round}}<form method="post" action="/conversation/tasks/{{$t.ID}}/round"><input type="hidden" name="from" value="{{$.From}}"><button equipo-btn data-primary type="submit" data-task-round>{{copy "work.decide.round"}}</button></form>{{end}}{{if .Talk}}<a equipo-btn href="/conversation?about={{$t.ID}}" data-ask-coordinator>{{copy "work.decide.ask_coordinator"}}</a>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{$t.ID}}/cancel"><input type="hidden" name="from" value="{{$.From}}"><button equipo-link type="submit" data-task-cancel>{{copy "work.decide.cancel"}}</button></form>{{end}}{{with .Hint}}<span equipo-quiet>{{.}}</span>{{end}}<span equipo-d-quiet>{{if .AddClaude}}<a equipo-link href="{{.AddClaude}}" data-add-claude>{{.AddClaudeLabel}}</a>{{end}}{{if .Mac}}<a equipo-link href="/conversation/settings/machines/add" data-set-up-mac>{{copy "work.decide.mac_set_up"}}</a>{{end}}<a equipo-link href="/conversation?about={{$t.ID}}" data-ask-about>{{copy "work.ask_about"}}</a></span></div> |
| </div>{{end}}{{end}} |
| {{define "star-toggle"}}{{$p := .P}}<form method="post" action="/projects/{{$p.ID}}/star" equipo-star-form><input type="hidden" name="starred" value="{{if $p.Star.On}}0{{else}}1{{end}}"><input type="hidden" name="from" value="{{.From}}"><button type="submit" equipo-star{{if $p.Star.On}} aria-pressed="true"{{if $p.Star.Auto}} data-auto{{end}}{{else}} aria-pressed="false"{{end}} aria-label="{{$p.Star.Label}}" title="{{$p.Star.Who}}" data-star-toggle>{{icon "star"}}</button></form>{{end}} |
| {{define "project-facts"}}{{with .StackLine}}<span>{{if $.PhoneStack}}{{icon "phone"}}{{else}}{{icon "code"}}{{end}}{{.}}</span>{{end}}{{with .Repos}}<span data-repos>{{icon "git"}}{{if eq (len .) 1}}{{copy "work.project.one_repo"}}{{else}}{{printf (copy "work.project.repos") (len .)}}{{end}}</span>{{end}}{{with .ChecksLine}}<span data-tone="{{if $.Checks.Here}}positive{{else}}warning{{end}}" data-checks-fact>{{if $.Checks.Here}}{{icon "check-circle"}}{{else}}{{icon "help-circle"}}{{end}}{{.}}</span>{{end}}{{end}} |
diff --git a/internal/equipo/work_views.go b/internal/equipo/work_views.go| index 8bd13165..d5ce8eac 100644 |
| --- a/internal/equipo/work_views.go |
| +++ b/internal/equipo/work_views.go |
| @@ -159,6 +159,9 @@ type decisionView struct { |
| Recover bool |
| // Mac: checks wait for a Mac; the card links setting one up. |
| Mac bool |
| + // AddClaude links adding Claude to the Mac Engineering waits for |
| + // (AddClaudeLabel says so). |
| + AddClaude, AddClaudeLabel string |
| // Unsandboxed offers the creator Run outside the sandbox, behind a |
| // confirm with its warning, for checks waiting for a Mac's sandbox. |
| Unsandboxed *unsandboxedOffer |
| @@ -823,6 +826,10 @@ func decisionOf(t wire.Task, v taskLine) *decisionView { |
| state = s.EngineeringStatus.State |
| } |
| key = "work.decide.mac_connection_why." + state |
| + if (state == wire.EngineeringNoConnection || state == wire.EngineeringSignedOut) && s.RunnerID != "" { |
| + // What it needs is Claude on that Mac: straight there. |
| + d.AddClaude, d.AddClaudeLabel = "/conversation/settings/connections#machine-"+s.RunnerID, fmt.Sprintf(copyText("chat.connections.add_to"), s.RunnerLabel) |
| + } |
| } |
| d.Why, d.Ask, d.Cancel = fmt.Sprintf(copyText(key), s.RunnerLabel), fmt.Sprintf(copyText("work.decide.mac_wait_ask"), s.RunnerLabel), v.Cancel |
| } |
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go| index 31fbe8b0..3475a11e 100644 |
| --- a/internal/runner/thin/connector.go |
| +++ b/internal/runner/thin/connector.go |
| @@ -249,7 +249,7 @@ func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.Connect |
| // its secret, however soon it follows, finds the attempt ready (the |
| // attempt ends if this fails). |
| _, apiKey := wire.APIKeyProviders[cmd.Provider] |
| - if (cmd.Kind == wire.KindToken && cmd.Provider == wire.ProviderClaude || cmd.Kind == wire.KindAPIKey && apiKey) && slices.Contains(c.Owners, cmd.Person) { |
| + if (cmd.Kind == wire.KindToken && cmd.Provider == wire.ProviderClaude || cmd.Kind == wire.KindAPIKey && apiKey) && slices.Contains(c.Owners, cmd.Person) && (c.Mac == nil || macTakes(cmd)) { |
| if _, herr := c.tokenHome(ctx, cmd.Connection); herr != nil { |
| c.log("connect home", herr) |
| } |
| @@ -349,13 +349,16 @@ func (c *Connector) Check(ctx context.Context, frameID string, cmd wire.CheckCom |
| return nil |
| } |
| -// Disconnect signs a connection out (DELETE /connections/{id}). |
| +// Disconnect signs a connection out (DELETE /connections/{id}). A |
| +// command that names another runner (protocol 37: local ids repeat |
| +// across runners) is consumed and removes nothing here. |
| func (c *Connector) Disconnect(ctx context.Context, frameID string, cmd wire.DisconnectCommand) error { |
| fresh := false |
| + other := cmd.RunnerID != "" && cmd.RunnerID != c.RunnerID |
| k := cleanup{connection: cmd.Connection, person: cmd.Person, local: cmd.LocalID, report: true} |
| err := c.State.tx(ctx, func(t *sql.Tx) error { |
| var err error |
| - if fresh, err = seen(t, frameID); err != nil || !fresh { |
| + if fresh, err = seen(t, frameID); err != nil || !fresh || other { |
| return err |
| } |
| return owe(t, k) |
| @@ -363,6 +366,10 @@ func (c *Connector) Disconnect(ctx context.Context, frameID string, cmd wire.Dis |
| if err != nil || !fresh { |
| return err |
| } |
| + if other { |
| + c.log("disconnect", errors.New("a sign-out addressed to another runner; nothing removed")) |
| + return nil |
| + } |
| c.background(func() { c.settle(k) }) |
| return nil |
| } |
| @@ -403,7 +410,9 @@ func (c *Connector) remove(k cleanup) bool { |
| } |
| } |
| _, apiKey := wire.APIKeyProviders[k.provider] |
| - if k.home != "" && exists(k.home) && !apiKey { |
| + // A Mac never runs a CLI it has not pinned (spec §8.2): its token's |
| + // sign-out is the home's deletion. |
| + if k.home != "" && exists(k.home) && !apiKey && c.Mac == nil { |
| if lock, err := os.Open(k.home); err == nil { |
| if unix.Flock(int(lock.Fd()), unix.LOCK_EX) == nil { |
| if err := c.logout(ctx, k.provider, k.home); err != nil { |
| @@ -497,6 +506,11 @@ func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire |
| r.State, r.Reason = wire.ConnError, reason |
| c.finish(cmd.Connection, r) |
| } |
| + if c.Mac != nil && !macTakes(cmd) { |
| + // A Mac takes Claude alone; nothing of the attempt was made. |
| + fail(wire.ReasonMacClaudeOnly) |
| + return |
| + } |
| if cmd.Kind == wire.KindAPIKey && slices.Contains(c.Owners, cmd.Person) { |
| c.runAPIKey(ctx, cmd, base) |
| return |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index 6d4b4462..b5909b66 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -888,7 +888,7 @@ func serveMac(ctx context.Context, c runner.Config, o Options, h *macHost) error |
| o.Logger.Warn("srt is not installed: checks run outside the sandbox and say so") |
| } |
| up := &macUpdater{origin: c.Origin, version: o.Version, binary: c.Executable, fetch: fetchLimited} |
| - return runWorker(ctx, c, o, hostPlatform(), workerSetup{probe: h.caps, gate: h.checks, find: h.find, ready: h.probes.wait, |
| + return runWorker(ctx, c, o, hostPlatform(), workerSetup{probe: h.caps, gate: h.checks, find: h.find, ready: h.probes.wait, creds: h.creds, |
| started: func(ctx context.Context, refresh func()) { |
| h.taint.changed = refresh |
| h.probes.start(ctx, refresh) |
diff --git a/internal/runner/thin/profile.go b/internal/runner/thin/profile.go| index c3f04a18..454bbc25 100644 |
| --- a/internal/runner/thin/profile.go |
| +++ b/internal/runner/thin/profile.go |
| @@ -312,6 +312,10 @@ func (o ClaudeOptions) readProfilesAtStart(ctx context.Context, conns *Conns, na |
| if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || tokenLabel(b.AccountID) != "" || conns.ValidatedAt(b.ID).IsZero() { |
| continue |
| } |
| + if o.Mac != nil && o.Mac.Gate() != nil { |
| + // A Mac uses a token only while its guards pass (maccreds.go). |
| + return |
| + } |
| token, err := provider.ReadToken(b.ProviderHome) |
| if err != nil { |
| if o.Logger != nil { |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index c412719f..366db7fd 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -716,6 +716,9 @@ type workerSetup struct { |
| // capability report; welcomed sees each welcome. |
| started func(ctx context.Context, refresh func()) |
| welcomed func(wire.Welcome, *Worker, context.CancelCauseFunc) |
| + // creds is a Mac's credential operations (maccreds.go): with them the |
| + // worker holds Claude connections of its own (nil: none). |
| + creds *macCreds |
| } |
| // workerRecord is the process record Verify settles: an attempt that |
| @@ -755,15 +758,43 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| defer cancel(nil) |
| caps := &Capabilities{Probe: w.probe, Logger: o.Logger} |
| link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true, Role: enrolledRole(c, creds.Bearer.Role)} |
| + // A Mac's own Claude connections (slice F task 11): said in hello |
| + // only once the welcome says 37. |
| + var own *workerConns |
| + if w.creds != nil { |
| + own = openWorkerConns(c, o, state, creds.Bearer, w.creds, link.Notify, link.HelloSoon) |
| + } |
| link.Hello = func() wire.Hello { |
| report := caps.Get(ctx) |
| - return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: w.gate.Sandbox(), Capabilities: &report} |
| + h := wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: w.gate.Sandbox(), Capabilities: &report} |
| + if own != nil { |
| + spoken, _ := link.Spoken() |
| + own.hello(spoken, &h) |
| + } |
| + return h |
| } |
| engineer := &Engineer{O: o.Claude, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, Owners: coordinatorPersons(c)(), MaxStep: o.MaxStep, Host: c.MachineLabel} |
| engineer.O.Runner, engineer.O.State, engineer.O.Logger = c, state, o.Logger |
| + if own != nil { |
| + engineer.O = own.claude |
| + } |
| worker := &Worker{State: state, Engine: engineer, Gate: w.gate, MaxStep: o.MaxStep, StepRoot: filepath.Join(c.ScratchRoot, "worker-steps"), Find: w.find, Ready: w.ready} |
| - if w.welcomed != nil { |
| - link.Welcomed = func(welcome wire.Welcome) { w.welcomed(welcome, worker, cancel) } |
| + link.Welcomed = func(welcome wire.Welcome) { |
| + if w.welcomed != nil { |
| + w.welcomed(welcome, worker, cancel) |
| + } |
| + if own != nil { |
| + // The first hello said no connections: the next says them. |
| + link.HelloSoon() |
| + } |
| + } |
| + if own != nil { |
| + if err := own.start(ctx); err != nil { |
| + return err |
| + } |
| + link.Connector = own.connector |
| + go own.claude.readProfilesAtStart(ctx, own.conns, link.HelloSoon) |
| + go own.conns.Loop(ctx) |
| } |
| if w.started != nil { |
| w.started(ctx, func() { caps.Stale(); link.HelloSoon() }) |
diff --git a/internal/runner/thin/worker_conns.go b/internal/runner/thin/worker_conns.go| new file mode 100644 |
| index 00000000..4c74b818 |
| --- /dev/null |
| +++ b/internal/runner/thin/worker_conns.go |
| @@ -0,0 +1,145 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// A Mac worker's own Claude connections (Mac runners spec §8.5; slice F |
| +// task 11). The worker opens Conns over its own accounts root (the one |
| +// its home guard checks), seals to its own enrolment key, and says its |
| +// connections and seal key in hello only once the welcome says 37. Only |
| +// Claude token connections live on a Mac, pasted or made by its own |
| +// sign-in (maccreds.go); every store and use passes the Mac's guards. |
| +// |
| +// The credential hold (D1): from the moment an attempt starts until its |
| +// files are gone and the Keychain is clean, the Mac counts as holding a |
| +// model credential. Every source of it is on disk (the attempt rows, the |
| +// bindings, the accounts root, the Keychain records), so it holds across |
| +// a restart; one that cannot be read holds. |
| + |
| +// workerConns is a Mac worker's own Claude connections. |
| +type workerConns struct { |
| + conns *Conns |
| + connector *Connector |
| + // claude is the worker's Claude options: the Mac's check, auth |
| + // status and guards. |
| + claude ClaudeOptions |
| + sealKey string |
| + mac *macCreds |
| +} |
| + |
| +// openWorkerConns opens a Mac worker's connections over state, for the |
| +// runner bearer names, with m its credential operations. notify sends |
| +// what is queued; changed asks for a hello soon. |
| +func openWorkerConns(c runner.Config, o Options, state *State, bearer runnerproto.RunnerCredential, m *macCreds, notify, changed func()) *workerConns { |
| + w := &workerConns{mac: m, claude: o.Claude} |
| + if p := w.claude.Profile; p != nil && p.Version == "" { |
| + named := *p |
| + named.Version = o.Version |
| + w.claude.Profile = &named |
| + } |
| + // On a Mac the CLI's auth status is the darwin one, token by |
| + // descriptor, in its turn and behind the guards: never Linux's, which |
| + // puts the token in an environment outside any turn. |
| + w.claude.Runner, w.claude.State, w.claude.Logger, w.claude.Mac, w.claude.Refresh = c, state, o.Logger, m, m.authStatus |
| + conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: m.authStatus, LockWait: w.claude.LockWait, Changed: changed} |
| + conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { |
| + res, err := w.claude.CheckToken(ctx, b) |
| + if res.Seen != nil && !errors.Is(err, provider.ErrLoginRequired) { |
| + if res.Seen.Limited { |
| + conns.Limit(b.ID, *res.Seen) |
| + } else { |
| + conns.Observe(b.ID, *res.Seen, "") |
| + } |
| + } |
| + if rerr := state.ReportCheck(context.Background(), res.Rows); rerr != nil && o.Logger != nil { |
| + o.Logger.Warn("token check usage", "err", sanitize(rerr)) |
| + } |
| + if changed != nil { |
| + changed() |
| + } |
| + return err |
| + } |
| + w.conns = conns |
| + w.connector = &Connector{Runner: c, State: state, Conns: conns, Root: m.paths.AccountsRoot, Owners: withPerson(coordinatorPersons(c)(), bearer.Person), Notify: notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: bearer.RunnerID, Mac: m} |
| + if key, err := runner.ReadMachineKey(c.StateDir); err == nil { |
| + if keys, err := sealbox.FromEd25519(key); err == nil { |
| + w.connector.Seal, w.sealKey = &keys, keys.PublicString() |
| + } |
| + clear(key) |
| + } else if o.Logger != nil { |
| + o.Logger.Warn("no seal key: Claude cannot be added to this Mac", "err", sanitize(err)) |
| + } |
| + return w |
| +} |
| + |
| +// start recovers what a previous process left (connector.go's Start: |
| +// attempts, owed sign-outs, the Keychain watches). |
| +func (w *workerConns) start(ctx context.Context) error { return w.connector.Start(ctx) } |
| + |
| +// hello puts the worker's connections, seal key and credential hold in |
| +// h, only at ProtocolMacEngineering: below it (and before any welcome, |
| +// spoken 0) a worker says none. |
| +func (w *workerConns) hello(spoken int, h *wire.Hello) { |
| + if spoken < wire.ProtocolMacEngineering { |
| + return |
| + } |
| + h.Connections, h.SealKey = w.conns.Held(), w.sealKey |
| + if h.Capabilities == nil { |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + c := *h.Capabilities |
| + c.ModelHold = w.held(ctx) |
| + if items := w.mac.keychain.Residue(); len(items) > 0 { |
| + c.ModelHold, c.HoldingItems = true, items[:min(len(items), wire.MaxHoldingItems)] |
| + } |
| + h.Capabilities = &c |
| +} |
| + |
| +// held is the worker's credential hold now. |
| +func (w *workerConns) held(ctx context.Context) bool { return w.connector.credentialHeld(ctx) } |
| + |
| +// credentialHeld: this runner holds, or may hold, a model credential: an |
| +// attempt running or a sign-out owed, a binding, anything in the |
| +// accounts root, or (on a Mac) a Keychain record (an item left, or a |
| +// launch not yet proven ended). A source that cannot be read holds. |
| +func (c *Connector) credentialHeld(ctx context.Context) bool { |
| + var n int |
| + if err := c.State.db.QueryRowContext(ctx, "SELECT (SELECT count(*) FROM connect_attempts WHERE state='running') + (SELECT count(*) FROM connect_cleanups)").Scan(&n); err != nil || n > 0 { |
| + return true |
| + } |
| + if bs, err := runner.LoadBindings(c.Runner.AccountBindingsPath); err != nil || len(bs) > 0 { |
| + return true |
| + } |
| + if entries, err := os.ReadDir(c.Root); err != nil && !errors.Is(err, fs.ErrNotExist) || len(entries) > 0 { |
| + return true |
| + } |
| + if c.Mac != nil { |
| + if c.Mac.Held() { |
| + return true |
| + } |
| + if left, err := c.Mac.keychain.Unproven(); err != nil || len(left) > 0 { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// macTakes: a Mac keeps only Claude, by a pasted token or its own |
| +// sign-in (Mac runners spec §8.5: Codex is slice G, metered and endpoint |
| +// connections stay on the primary). |
| +func macTakes(cmd wire.ConnectCommand) bool { |
| + return cmd.Provider == wire.ProviderClaude && (cmd.Kind == wire.KindToken || cmd.Kind == wire.KindSubscription || cmd.Kind == "") |
| +} |
diff --git a/internal/runner/thin/worker_conns_test.go b/internal/runner/thin/worker_conns_test.go| new file mode 100644 |
| index 00000000..c0549508 |
| --- /dev/null |
| +++ b/internal/runner/thin/worker_conns_test.go |
| @@ -0,0 +1,484 @@ |
| +//go:build testbuild |
| + |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "log/slog" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/fakeclaude" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +// A Mac worker's own Claude connections (Mac runners slice F, task 11): |
| +// the worker opens Conns over its own accounts root, says its |
| +// connections and seal key in hello once the welcome says 37, takes the |
| +// instance's connect, cancel, sign-out and preference commands, keeps |
| +// only Claude token connections (pasted, or made by its own sign-in), and |
| +// holds the Mac as having a model credential for as long as anything of |
| +// one may be there. |
| + |
| +// machineKey writes the runner's enrolment key into its state, as |
| +// enrolment does, and makes the rig seal to it. |
| +func (r *darwinRig) machineKey() { |
| + r.t.Helper() |
| + _, key, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(base64.RawURLEncoding.EncodeToString(key)) |
| + if err := os.WriteFile(filepath.Join(r.cfg.StateDir, "machine-key.json"), raw, 0o600); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + if r.keys, err = sealbox.FromEd25519(key); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +// workerOptions are a worker's options in these tests. |
| +func (r *darwinRig) workerOptions(protocol int) Options { |
| + return Options{Version: "v-test", Logger: slog.New(slog.NewTextHandler(&r.logs, nil)), Claude: ClaudeOptions{LockWait: 5 * time.Second}, ConnectLimit: time.Hour, Protocol: protocol} |
| +} |
| + |
| +// worker is the Mac worker's own connections over the rig, as runWorker |
| +// opens them, started. |
| +func (r *darwinRig) worker() *workerConns { |
| + r.t.Helper() |
| + r.machineKey() |
| + w := openWorkerConns(r.cfg, r.workerOptions(0), r.state, runnerproto.RunnerCredential{RunnerID: tokenRunner, Person: connPerson}, r.m, nil, nil) |
| + w.connector.spawn = func(f func()) { f() } |
| + if err := w.start(r.ctx); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return w |
| +} |
| + |
| +// workerInstance is an instance's runner stream for one worker |
| +// connection at a time: it welcomes at a protocol, acks every durable |
| +// frame the worker sends, and hands the frames over in order. |
| +type workerInstance struct { |
| + t *testing.T |
| + origin string |
| + conns chan *websocket.Conn |
| + ws *websocket.Conn |
| + frames chan workerFrame |
| + seq int |
| +} |
| + |
| +type workerFrame struct { |
| + f wire.Frame |
| + body any |
| +} |
| + |
| +func newWorkerInstance(t *testing.T) *workerInstance { |
| + t.Helper() |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + i := &workerInstance{t: t, origin: "http://" + l.Addr().String(), conns: make(chan *websocket.Conn, 4), frames: make(chan workerFrame, 256)} |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + ws, err := websocket.Accept(w, r, nil) |
| + if err != nil { |
| + return |
| + } |
| + ws.SetReadLimit(wire.MaxFrameBytes) |
| + i.conns <- ws |
| + <-r.Context().Done() |
| + })} |
| + go srv.Serve(l) |
| + t.Cleanup(func() { srv.Close() }) |
| + return i |
| +} |
| + |
| +// welcome takes the worker's connection, its first hello, and welcomes |
| +// it at protocol; it returns that first hello. |
| +func (i *workerInstance) welcome(protocol int) wire.Hello { |
| + i.t.Helper() |
| + select { |
| + case i.ws = <-i.conns: |
| + case <-time.After(20 * time.Second): |
| + i.t.Fatal("the worker never connected") |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + _, raw, err := i.ws.Read(ctx) |
| + f, body, perr := wire.ParseFrame(raw) |
| + if err != nil || perr != nil || f.Type != wire.FrameHello { |
| + i.t.Fatalf("no hello: %v %v %s", err, perr, raw) |
| + } |
| + i.send(wire.FrameWelcome, wire.Welcome{Generation: 1, RunnerID: tokenRunner, Protocol: protocol, Role: wire.RoleWorker}) |
| + go func(ws *websocket.Conn) { |
| + for { |
| + _, raw, err := ws.Read(context.Background()) |
| + if err != nil { |
| + return |
| + } |
| + f, body, err := wire.ParseFrame(raw) |
| + if err != nil { |
| + continue |
| + } |
| + if f.Durable() { |
| + ack, _ := wire.NewFrame("i-ack-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| + out, _ := json.Marshal(ack) |
| + _ = ws.Write(context.Background(), websocket.MessageText, out) |
| + } |
| + i.frames <- workerFrame{f, body} |
| + } |
| + }(i.ws) |
| + return *body.(*wire.Hello) |
| +} |
| + |
| +// send writes one frame to the worker. |
| +func (i *workerInstance) send(kind string, body any) { |
| + i.t.Helper() |
| + i.seq++ |
| + f, err := wire.NewFrame("i-"+kind+"-"+itoa(int64(i.seq)), kind, body) |
| + if err != nil { |
| + i.t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(f) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + if err := i.ws.Write(ctx, websocket.MessageText, raw); err != nil { |
| + i.t.Fatal(err) |
| + } |
| +} |
| + |
| +// next is the first frame of kind for which ok says yes. |
| +func (i *workerInstance) next(kind string, ok func(any) bool) any { |
| + i.t.Helper() |
| + deadline := time.After(45 * time.Second) |
| + for { |
| + select { |
| + case w := <-i.frames: |
| + if w.f.Type == kind && (ok == nil || ok(w.body)) { |
| + return w.body |
| + } |
| + case <-deadline: |
| + i.t.Fatalf("no %s", kind) |
| + } |
| + } |
| +} |
| + |
| +// runWorker runs the Mac worker over the rig (its credential operations, |
| +// the fake gate and capabilities) against inst, offering protocol (0: |
| +// the current one); stop ends it. |
| +func (r *darwinRig) runWorker(inst *workerInstance, protocol int) (stop func()) { |
| + r.t.Helper() |
| + c := r.cfg |
| + c.Origin, c.WorkspaceRoot, c.MachineLabel = inst.origin, filepath.Join(r.dir, "work"), "Tito Studio" |
| + ctx, cancel := context.WithCancel(r.ctx) |
| + done := make(chan error, 1) |
| + go func() { |
| + done <- runWorker(ctx, c, r.workerOptions(protocol), wire.Platform{OS: "darwin", Arch: "arm64"}, workerSetup{probe: fake.capabilities, gate: fake.gate("", ""), creds: r.m}) |
| + }() |
| + return func() { |
| + r.t.Helper() |
| + cancel() |
| + select { |
| + case err := <-done: |
| + if err != nil { |
| + r.t.Fatalf("worker ended: %v", err) |
| + } |
| + case <-time.After(30 * time.Second): |
| + r.t.Fatal("the worker did not stop") |
| + } |
| + } |
| +} |
| + |
| +// workerCredential is the worker's enrolment credential in its state. |
| +func (r *darwinRig) workerCredential() { |
| + r.t.Helper() |
| + raw, _ := json.Marshal(runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "bearer-worker-test", Role: wire.RoleWorker, RunnerID: tokenRunner, Person: connPerson}}) |
| + if err := os.WriteFile(filepath.Join(r.cfg.StateDir, "credentials.json"), raw, 0o600); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestWorkerHelloConnections: at 37 a worker takes a connect and its |
| +// sealed token through its link, and its hello (and sync) carry the |
| +// connection and its seal key; the same worker welcomed at 35 says none |
| +// and no seal key. The first hello, sent before any welcome, says none |
| +// either way. |
| +func TestWorkerHelloConnections(t *testing.T) { |
| + r := newDarwinRig(t) |
| + r.machineKey() |
| + r.workerCredential() |
| + key := r.keys.PublicString() |
| + |
| + inst := newWorkerInstance(t) |
| + stop := r.runWorker(inst, 0) |
| + first := inst.welcome(wire.ProtocolMacEngineering) |
| + if len(first.Connections) != 0 || first.SealKey != "" { |
| + t.Fatalf("the first hello, before the welcome: %+v %q", first.Connections, first.SealKey) |
| + } |
| + inst.next(wire.FrameHello, func(b any) bool { return b.(*wire.Hello).SealKey == key }) |
| + inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| + inst.next(wire.FrameConnection, func(b any) bool { |
| + v := b.(*wire.ConnectionReport) |
| + return v.Connection == "cn_w1" && v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptToken |
| + }) |
| + token := fakeclaude.Token("w@example.com") |
| + inst.send(wire.FrameSecret, r.sealed("cn_w1", token, nil)) |
| + end := inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).State != wire.ConnConnecting }).(*wire.ConnectionReport) |
| + if end.State != wire.ConnHealthy || end.LocalID == "" { |
| + t.Fatalf("the worker's connection: %+v\n%s", end, r.logs.String()) |
| + } |
| + h := inst.next(wire.FrameHello, func(b any) bool { return len(b.(*wire.Hello).Connections) == 1 }).(*wire.Hello) |
| + if c := h.Connections[0]; c.LocalID != end.LocalID || c.Kind != wire.KindToken || c.Person != connPerson || h.SealKey != key { |
| + t.Fatalf("hello at 37: %+v %q", h.Connections, h.SealKey) |
| + } |
| + if h.Capabilities == nil || !h.Capabilities.ModelHold { |
| + t.Fatalf("a worker holding a token said it holds none: %+v", h.Capabilities) |
| + } |
| + // The person's preference, addressed to this runner, is kept here. |
| + inst.send(wire.FramePreference, wire.PreferenceCommand{Person: connPerson, Provider: wire.ProviderClaude, Revision: 3}) |
| + r.waitFor(func() bool { |
| + var raw string |
| + _ = r.state.db.QueryRow("SELECT value FROM meta WHERE key=?", "prefer:"+connPerson).Scan(&raw) |
| + return raw != "" |
| + }, "the preference kept") |
| + // A cancel ends an attempt on this runner. |
| + inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w2", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| + inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).Connection == "cn_w2" }) |
| + inst.send(wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: "cn_w2", Person: connPerson}) |
| + inst.next(wire.FrameConnection, func(b any) bool { |
| + v := b.(*wire.ConnectionReport) |
| + return v.Connection == "cn_w2" && v.State == wire.ConnError && v.Reason == "cancelled" |
| + }) |
| + // A sign-out addressed to this runner signs its connection out. |
| + inst.send(wire.FrameDisconnect, wire.DisconnectCommand{Connection: "cn_w1", Person: connPerson, LocalID: end.LocalID, RunnerID: tokenRunner}) |
| + inst.next(wire.FrameConnection, func(b any) bool { |
| + v := b.(*wire.ConnectionReport) |
| + return v.Connection == "cn_w1" && v.State == wire.ConnSignedOut |
| + }) |
| + inst.next(wire.FrameHello, func(b any) bool { return len(b.(*wire.Hello).Connections) == 0 }) |
| + // Another for the 35 run: held, so its absence below 37 means something. |
| + inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w3", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| + inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).Connection == "cn_w3" }) |
| + inst.send(wire.FrameSecret, r.sealed("cn_w3", fakeclaude.Token("w3@example.com"), nil)) |
| + inst.next(wire.FrameConnection, func(b any) bool { |
| + v := b.(*wire.ConnectionReport) |
| + return v.Connection == "cn_w3" && v.State == wire.ConnHealthy |
| + }) |
| + stop() |
| + |
| + again := newWorkerInstance(t) |
| + stop = r.runWorker(again, 0) |
| + first = again.welcome(wire.ProtocolChangeDiffs) |
| + sync := again.next(wire.FrameSync, nil).(*wire.Sync) |
| + h = again.next(wire.FrameHello, nil).(*wire.Hello) |
| + if len(first.Connections) != 0 || len(sync.Connections) != 0 || len(h.Connections) != 0 || h.SealKey != "" || first.SealKey != "" { |
| + t.Fatalf("at 35: first %+v, sync %+v, hello %+v %q", first.Connections, sync.Connections, h.Connections, h.SealKey) |
| + } |
| + if h.Capabilities != nil && (h.Capabilities.ModelHold || len(h.Capabilities.HoldingItems) > 0) { |
| + t.Fatalf("the hold said below 37: %+v", h.Capabilities) |
| + } |
| + stop() |
| +} |
| + |
| +// TestWorkerTokenConnectionStored: a pasted token on a worker rests in a |
| +// 0600 file in a 0700 home inside a 0700 accounts root; with the home |
| +// guard failing nothing is stored. |
| +func TestWorkerTokenConnectionStored(t *testing.T) { |
| + r := newDarwinRig(t) |
| + w := r.worker() |
| + token := fakeclaude.Token("a@example.com") |
| + home, end := r.paste(w.connector, "c1", token) |
| + if end.State != wire.ConnHealthy { |
| + t.Fatalf("not connected: %+v\n%s", end, r.logs.String()) |
| + } |
| + for path, want := range map[string]os.FileMode{r.root: 0o700, home: 0o700, filepath.Join(home, provider.TokenFile): 0o600} { |
| + info, err := os.Lstat(path) |
| + if err != nil || info.Mode().Perm() != want { |
| + t.Fatalf("%s: %v %v, want %v", path, err, info.Mode().Perm(), want) |
| + } |
| + } |
| + if b, ok := w.conns.Binding(filepath.Base(home)); !ok || b.Kind != wire.KindToken || b.PersonID != connPerson { |
| + t.Fatalf("binding %+v %v", b, ok) |
| + } |
| + r.onlyIn(token, home) |
| + // The home guard fails: refused, nothing written. |
| + if err := os.Chmod(r.dir, 0o750); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.Chmod(r.dir, 0o700) }) |
| + home2, end := r.paste(w.connector, "c2", fakeclaude.Token("b@example.com")) |
| + if end.State != wire.ConnError || end.Reason != "provider_refused" || r.seals("c2") != 0 || exists(filepath.Join(home2, provider.TokenFile)) || exists(filepath.Join(home2, provider.TokenStaging)) { |
| + t.Fatalf("stored with the home guard failing: %+v seals=%d", end, r.seals("c2")) |
| + } |
| +} |
| + |
| +// TestWorkerRefusesOtherConnectionKinds: a worker keeps only Claude |
| +// token connections. Codex, an API key and an endpoint are refused, each |
| +// with the stated reason and nothing made in the accounts root; Claude's |
| +// sign-in and a pasted token both start. |
| +func TestWorkerRefusesOtherConnectionKinds(t *testing.T) { |
| + r := newDarwinRig(t) |
| + w := r.worker() |
| + budget := &wire.Budget{Day: 5_000_000, Month: 50_000_000, Currency: "USD", Revision: 1} |
| + for i, cmd := range []wire.ConnectCommand{ |
| + {Provider: wire.ProviderCodex, Kind: wire.KindSubscription}, |
| + {Provider: wire.ProviderCodex, Kind: wire.KindToken}, |
| + {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: budget}, |
| + {Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, Billing: wire.BillingSubscription, Budget: budget}, |
| + {Provider: "local", Kind: "endpoint"}, |
| + } { |
| + cmd.Connection, cmd.Person = "x"+itoa(int64(i)), connPerson |
| + if err := w.connector.Accept(r.ctx, "f-"+cmd.Connection, cmd); err != nil { |
| + t.Fatal(err) |
| + } |
| + if end := r.ended(cmd.Connection); end.State != wire.ConnError || end.Reason != wire.ReasonMacClaudeOnly { |
| + t.Fatalf("%s %s: %+v", cmd.Provider, cmd.Kind, end) |
| + } |
| + if entries, _ := os.ReadDir(r.root); len(entries) != 0 { |
| + t.Fatalf("%s %s left %d entries in the accounts root", cmd.Provider, cmd.Kind, len(entries)) |
| + } |
| + } |
| + if !wire.ConnectReasons[wire.ReasonMacClaudeOnly] { |
| + t.Fatal("the reason is not one an instance accepts") |
| + } |
| + r.connect(w.connector, "t1") |
| + link, _ := r.signIn(w.connector, "s1") |
| + if link == "" { |
| + t.Fatal("no sign-in") |
| + } |
| +} |
| + |
| +// TestWorkerCredentialHoldDurable: the worker holds the Mac as having a |
| +// model credential from the moment an attempt starts, through a refused |
| +// sign-in that left a Keychain item, and across a restart, until the |
| +// connection's files are gone and the Keychain is clean; the hello says |
| +// so, with the item's service. |
| +func TestWorkerCredentialHoldDurable(t *testing.T) { |
| + r := newDarwinRig(t) |
| + w := r.worker() |
| + if w.held(r.ctx) { |
| + t.Fatal("held with nothing there") |
| + } |
| + r.kc.set(true) // deletes fail: the item the sign-in leaves stays |
| + link, home := r.signIn(w.connector, "s1") |
| + if !w.held(r.ctx) { |
| + t.Fatal("not held while connecting") |
| + } |
| + item := r.own(r.signInDir()) |
| + r.kc.add(item) |
| + r.codeIn(w.connector, "s1", link, "a@example.com") |
| + if end := r.ended("s1"); end.Reason != "provider_refused" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if exists(home) { |
| + t.Fatal("the refused attempt's home stayed") |
| + } |
| + if entries, _ := os.ReadDir(r.root); len(entries) != 0 || !w.held(r.ctx) { |
| + t.Fatalf("files gone, item left: held=%v", w.held(r.ctx)) |
| + } |
| + h := wire.Hello{Capabilities: &wire.Capabilities{}} |
| + w.hello(wire.ProtocolMacEngineering, &h) |
| + if !h.Capabilities.ModelHold || !slices.Equal(h.Capabilities.HoldingItems, []string{item.Service}) || wire.ValidCapabilities(*h.Capabilities) != nil { |
| + t.Fatalf("hello %+v", h.Capabilities) |
| + } |
| + |
| + // A restart: the same state, held still. |
| + again := darwinRigAt(t, r.dir) |
| + again.kc = r.kc |
| + again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete |
| + again.kc.r = again |
| + w2 := openWorkerConns(again.cfg, again.workerOptions(0), again.state, runnerproto.RunnerCredential{RunnerID: tokenRunner, Person: connPerson}, again.m, nil, nil) |
| + if !w2.held(again.ctx) { |
| + t.Fatal("the hold did not survive the restart") |
| + } |
| + // The item goes (deletes work again); the restart's settling clears it. |
| + r.kc.set(false) |
| + w2.connector.spawn = func(f func()) { f() } |
| + if err := w2.start(again.ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w2.held(again.ctx) || r.kc.has(item) { |
| + t.Fatalf("still held once the files and the item are gone: %v", again.m.keychain.Residue()) |
| + } |
| + h = wire.Hello{Capabilities: &wire.Capabilities{}} |
| + w2.hello(wire.ProtocolMacEngineering, &h) |
| + if h.Capabilities.ModelHold || len(h.Capabilities.HoldingItems) != 0 { |
| + t.Fatalf("hello %+v", h.Capabilities) |
| + } |
| + // An attempt running, or a sign-out owed, holds by itself, before |
| + // anything of it is on disk. |
| + for _, q := range []string{ |
| + "INSERT INTO connect_attempts(id, person, provider, state, created_at) VALUES('x1', 'p', 'claude', 'running', '2026-11-29T00:00:00Z')", |
| + "INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) VALUES('x2', 'p', 'claude-8', 1, '2026-11-29T00:00:00Z')", |
| + } { |
| + if _, err := again.state.db.Exec(q); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !w2.held(again.ctx) { |
| + t.Fatalf("not held by %s", q) |
| + } |
| + if _, err := again.state.db.Exec("DELETE FROM connect_attempts WHERE id='x1'; DELETE FROM connect_cleanups WHERE connection='x2'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if w2.held(again.ctx) { |
| + t.Fatal("held once they were gone") |
| + } |
| + // A file in the accounts root holds by itself. |
| + if err := os.Mkdir(filepath.Join(again.root, "claude-9"), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !w2.held(again.ctx) { |
| + t.Fatal("a home in the accounts root does not hold") |
| + } |
| +} |
| + |
| +// TestWorkerSignOutOnlyItsOwn: a disconnect addressed to another runner |
| +// removes nothing here, even for a local id this runner holds. |
| +func TestWorkerSignOutOnlyItsOwn(t *testing.T) { |
| + r := newDarwinRig(t) |
| + w := r.worker() |
| + home, end := r.paste(w.connector, "c1", fakeclaude.Token("a@example.com")) |
| + if end.State != wire.ConnHealthy { |
| + t.Fatalf("not connected: %+v", end) |
| + } |
| + local := filepath.Base(home) |
| + if err := w.connector.Disconnect(r.ctx, "f-out-1", wire.DisconnectCommand{Connection: "c1", Person: connPerson, LocalID: local, RunnerID: "run_primary"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := w.conns.Binding(local); !ok || !exists(home) { |
| + t.Fatal("another runner's sign-out removed this runner's connection") |
| + } |
| + if err := w.connector.Disconnect(r.ctx, "f-out-2", wire.DisconnectCommand{Connection: "c1", Person: connPerson, LocalID: local, RunnerID: tokenRunner}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := w.conns.Binding(local); ok || exists(home) { |
| + t.Fatal("its own sign-out left the connection") |
| + } |
| +} |
| + |
| +// TestWorkerProfileAtStartGated: on a Mac the start's profile reads use |
| +// a token only while the Mac's guards pass: a tainted Mac reads none; an |
| +// untainted one reads as Linux does. |
| +func TestWorkerProfileAtStartGated(t *testing.T) { |
| + r := newProfileRig(t) |
| + m := &macCreds{taint: loadTaint(filepath.Join(r.dir, "state", "tainted"))} |
| + m.taint.Set() |
| + r.o.Mac = m |
| + if named := r.start(); named != 0 || r.fake.count() != 0 { |
| + t.Fatalf("a tainted Mac read %d profiles", r.fake.count()) |
| + } |
| +} |
diff --git a/internal/thintest/worker_connections_contract_test.go b/internal/thintest/worker_connections_contract_test.go| new file mode 100644 |
| index 00000000..c84f9670 |
| --- /dev/null |
| +++ b/internal/thintest/worker_connections_contract_test.go |
| @@ -0,0 +1,370 @@ |
| +package thintest |
| + |
| +import ( |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/sealbox" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// A Mac worker's own Claude connections (Mac runners slice F, task 11): |
| +// every connection operation goes to the runner its row names, never to |
| +// the primary; the hello of whichever runner sent it records that |
| +// runner's connections only; and the instance holds a Mac as having a |
| +// model credential from the moment a connection there starts connecting |
| +// until the Mac says its files, its Keychain items and any unproven |
| +// launch are all gone. |
| + |
| +// workerConnHello is a Mac worker's hello at 37 with its seal key and |
| +// connections. |
| +func workerConnHello(key string, conns ...wire.HeldConnection) wire.Hello { |
| + h := macEngineerHello("Tito Studio", wire.EngineeringNoConnection, wire.ProtocolMacEngineering, false) |
| + h.SealKey, h.Connections = key, append([]wire.HeldConnection{}, conns...) |
| + return h |
| +} |
| + |
| +// connRow is the person's connection on runner with local id. |
| +func (r *runnersRig) connRow(runner, local string) (wire.Connection, bool) { |
| + r.t.Helper() |
| + list, err := r.client.Connections(r.ctx) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + for _, c := range list.Items { |
| + if c.RunnerID == runner && c.LocalID == local { |
| + return c, true |
| + } |
| + } |
| + return wire.Connection{}, false |
| +} |
| + |
| +// redialMac connects p's Mac again (an instance restart dropped it), |
| +// saying h at once. |
| +func (r *runnersRig) redialMac(p *peer, h wire.Hello) *peer { |
| + r.t.Helper() |
| + c, ok := r.creds[p.fr] |
| + if !ok { |
| + r.t.Fatal("unknown peer") |
| + } |
| + h.Generation = p.fr.Welcome.Generation |
| + fr, err := DialRunnerHello(r.ctx, r.inst.URL, c[0], h) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + r.t.Cleanup(fr.Close) |
| + r.creds[fr] = c |
| + return &peer{t: r.t, r: r.toolRig, fr: fr} |
| +} |
| + |
| +// TestContractWorkerConnectionLifecycle: start, the sealed token, cancel, |
| +// sign out, check and the preference for a connection on a worker go to |
| +// that worker and never reach the primary; a worker and the primary may |
| +// hold the same local id without either's hello touching the other's |
| +// row; a box sealed for one runner is refused for the other's attempt; |
| +// a worker below 37, or the kinds a Mac does not take, get no connection. |
| +func TestContractWorkerConnectionLifecycle(t *testing.T) { |
| + r := newMacRig(t) |
| + keys := sealKeys(t) |
| + w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) |
| + wid, pid := w.fr.Welcome.RunnerID, r.primary.fr.Welcome.RunnerID |
| + w.heartbeat(workerConnHello(keys.PublicString())) |
| + waitFor(t, "the worker's seal key published", func() bool { |
| + list, err := r.client.Runners(r.ctx) |
| + if err != nil { |
| + return false |
| + } |
| + for _, it := range list.Items { |
| + if it.ID == wid { |
| + return it.SealKey == keys.PublicString() |
| + } |
| + } |
| + return false |
| + }) |
| + if _, err := r.client.SetPreferences(r.ctx, wire.Preferences{Provider: wire.ProviderClaude}); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The primary holds claude-1 of its own. |
| + ph := primaryHello(0) |
| + ph.Protocol = wire.ProtocolMacEngineering |
| + ph.Catalog[0].NeedsMacOS = true |
| + ph.Connections = []wire.HeldConnection{{LocalID: "claude-1", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, Label: "p@example.com", State: wire.ConnHealthy}} |
| + r.primary.heartbeat(ph) |
| + if c, ok := r.connRow(pid, "claude-1"); !ok || c.State != wire.ConnHealthy { |
| + t.Fatalf("the primary's connection: %+v %v", c, ok) |
| + } |
| + connects, secrets, cancels, disconnects, checks := r.mailbox(pid, wire.FrameConnect), r.mailbox(pid, wire.FrameSecret), r.mailbox(pid, wire.FrameCancelConnect), r.mailbox(pid, wire.FrameDisconnect), r.mailbox(pid, wire.FrameCheck) |
| + |
| + // Start on the worker. |
| + a, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken, RunnerID: wid}) |
| + if err != nil || a.RunnerID != wid || a.State != wire.ConnConnecting { |
| + t.Fatalf("connect on the worker: %+v %v", a, err) |
| + } |
| + if _, body := w.expect(wire.FrameConnect); body.(*wire.ConnectCommand).Connection != a.ID { |
| + t.Fatalf("connect frame %+v", body) |
| + } |
| + // A box sealed for the primary is refused for the worker's attempt. |
| + seal := func(runner string) wire.Sealed { |
| + t.Helper() |
| + s, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: "sk-ant-oat01-worker", RunnerID: runner, ConnectionID: a.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| + } |
| + if _, err := r.client.Secret(r.ctx, a.ID, seal(pid)); Status(err) != 422 { |
| + t.Fatalf("a box for the primary taken for the worker's attempt: %v", err) |
| + } |
| + if _, err := r.client.Secret(r.ctx, a.ID, seal(wid)); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.expect(wire.FrameSecret) |
| + // The worker's connection is claude-1 too. |
| + w.send(wire.FrameConnection, wire.ConnectionReport{Connection: a.ID, Person: Owner, LocalID: "claude-1", Provider: wire.ProviderClaude, State: wire.ConnHealthy, Label: "w@example.com"}) |
| + held := wire.HeldConnection{LocalID: "claude-1", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, Label: "w@example.com", State: wire.ConnHealthy} |
| + prefs := r.mailbox(pid, wire.FramePreference) |
| + wprefs := r.mailbox(wid, wire.FramePreference) |
| + w.heartbeat(workerConnHello(keys.PublicString(), held)) |
| + if c, ok := r.connRow(wid, "claude-1"); !ok || c.ID != a.ID || c.State != wire.ConnHealthy || c.Label != "w@example.com" { |
| + t.Fatalf("the worker's connection: %+v %v", c, ok) |
| + } |
| + if c, _ := r.connRow(pid, "claude-1"); c.State != wire.ConnHealthy || c.Label != "p@example.com" { |
| + t.Fatalf("the worker's hello changed the primary's row: %+v", c) |
| + } |
| + // The worker's hello says the preference again to the worker alone. |
| + if r.mailbox(pid, wire.FramePreference) != prefs || r.mailbox(wid, wire.FramePreference) <= wprefs { |
| + t.Fatalf("preference: primary %d (was %d), worker %d (was %d)", r.mailbox(pid, wire.FramePreference), prefs, r.mailbox(wid, wire.FramePreference), wprefs) |
| + } |
| + // Nor does the primary's hello touch the worker's claude-1. |
| + r.primary.heartbeat(ph) |
| + if c, _ := r.connRow(wid, "claude-1"); c.State != wire.ConnHealthy || c.Label != "w@example.com" { |
| + t.Fatalf("the primary's hello changed the worker's row: %+v", c) |
| + } |
| + // A new preference reaches the worker holding a connection, and the primary. |
| + wprefs, prefs = r.mailbox(wid, wire.FramePreference), r.mailbox(pid, wire.FramePreference) |
| + now, err := r.client.Preferences(r.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.client.SetPreferences(r.ctx, wire.Preferences{Provider: wire.ProviderCodex, Revision: now.Revision}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.mailbox(wid, wire.FramePreference) != wprefs+1 || r.mailbox(pid, wire.FramePreference) != prefs+1 { |
| + t.Fatal("a new preference did not reach each runner holding a connection once") |
| + } |
| + |
| + // Check again goes to the worker. |
| + if err := r.client.CheckConnection(r.ctx, a.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, body := w.expect(wire.FrameCheck); body.(*wire.CheckCommand).LocalID != "claude-1" { |
| + t.Fatalf("check frame %+v", body) |
| + } |
| + // Sign out goes to the worker, naming it. |
| + if _, err := r.client.SignOut(r.ctx, a.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, body := w.expect(wire.FrameDisconnect) |
| + if d := body.(*wire.DisconnectCommand); d.LocalID != "claude-1" || d.RunnerID != wid || d.Connection != a.ID { |
| + t.Fatalf("disconnect frame %+v", d) |
| + } |
| + // The worker no longer holds it: its row is signed out, the primary's |
| + // claude-1 stays as it was. |
| + w.heartbeat(workerConnHello(keys.PublicString())) |
| + if c, _ := r.connRow(wid, "claude-1"); c.State != wire.ConnSignedOut { |
| + t.Fatalf("the worker's row: %+v", c) |
| + } |
| + if c, _ := r.connRow(pid, "claude-1"); c.State != wire.ConnHealthy || c.Label != "p@example.com" { |
| + t.Fatalf("the worker's hello signed out the primary's row: %+v", c) |
| + } |
| + // Cancel goes to the worker. |
| + b, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, RunnerID: wid}) |
| + if err != nil || b.RunnerID != wid { |
| + t.Fatalf("sign-in on the worker: %+v %v", b, err) |
| + } |
| + w.expect(wire.FrameConnect) |
| + if _, err := r.client.CancelConnection(r.ctx, b.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, body := w.expect(wire.FrameCancelConnect); body.(*wire.CancelConnectCommand).Connection != b.ID { |
| + t.Fatalf("cancel frame %+v", body) |
| + } |
| + // None of it reached the primary. |
| + if r.mailbox(pid, wire.FrameConnect) != connects || r.mailbox(pid, wire.FrameSecret) != secrets || r.mailbox(pid, wire.FrameCancelConnect) != cancels || r.mailbox(pid, wire.FrameDisconnect) != disconnects || r.mailbox(pid, wire.FrameCheck) != checks { |
| + t.Fatal("a worker's connection command reached the primary") |
| + } |
| + // The primary's own sign-out still goes to the primary. |
| + pc, _ := r.connRow(pid, "claude-1") |
| + if _, err := r.client.SignOut(r.ctx, pc.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, body := r.primary.expect(wire.FrameDisconnect); body.(*wire.DisconnectCommand).RunnerID != pid { |
| + t.Fatalf("the primary's disconnect %+v", body) |
| + } |
| + if r.mailbox(wid, wire.FrameDisconnect) != 1 { |
| + t.Fatal("the primary's sign-out reached the worker") |
| + } |
| + |
| + // What a Mac does not take, and a worker below 37. |
| + for _, in := range []wire.Connect{{Provider: wire.ProviderCodex, RunnerID: wid}, {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, RunnerID: wid, LimitConfirmed: true, Budget: &wire.Budget{Day: 1_000_000, Month: 10_000_000}}} { |
| + if _, err := r.client.Connect(r.ctx, in); Status(err) != 422 { |
| + t.Fatalf("%s %s on a Mac: %v", in.Provider, in.Kind, err) |
| + } |
| + } |
| + oh := macEngineerHello("Old Mac", wire.EngineeringNoConnection, wire.ProtocolChangeDiffs, false) |
| + oh.SealKey, oh.Connections = sealKeys(t).PublicString(), []wire.HeldConnection{{LocalID: "claude-7", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnHealthy}} |
| + ofr, err := DialRunnerHello(r.ctx, r.inst.URL, r.inst.EnrolRunner(t).Token, oh) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(ofr.Close) |
| + old := &peer{t: t, r: r.toolRig, fr: ofr} |
| + oid := old.fr.Welcome.RunnerID |
| + nothingBelow37 := func(when string) { |
| + t.Helper() |
| + if _, ok := r.connRow(oid, "claude-7"); ok { |
| + t.Fatalf("%s: a worker below 37 recorded a connection", when) |
| + } |
| + list, err := r.client.Runners(r.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, it := range list.Items { |
| + if it.ID == oid && it.SealKey != "" { |
| + t.Fatalf("%s: a worker below 37 published a seal key", when) |
| + } |
| + } |
| + } |
| + old.lease("", 0) |
| + nothingBelow37("its first hello") |
| + old.heartbeat(oh) |
| + nothingBelow37("a later hello") |
| + if _, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken, RunnerID: oid}); err == nil { |
| + t.Fatal("a connection started on a worker below 37") |
| + } |
| + if r.mailbox(oid, wire.FrameConnect) != 0 { |
| + t.Fatal("a connect reached a worker below 37") |
| + } |
| +} |
| + |
| +// TestContractCredentialHeldFromConnecting: the instance holds a Mac as |
| +// having a model credential from the moment a connection there starts |
| +// connecting: before the Mac has the frame, through a refused connect |
| +// whose Keychain item stays, across an instance restart, while an |
| +// earlier launch is unproven, and until the Mac says its files and its |
| +// Keychain items are gone. |
| +func TestContractCredentialHeldFromConnecting(t *testing.T) { |
| + r := newMacRig(t) |
| + keys := sealKeys(t) |
| + w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) |
| + wid := w.fr.Welcome.RunnerID |
| + isHeld := func() bool { |
| + t.Helper() |
| + // The store as it is now: an instance restart opens another. |
| + held, err := r.inst.Store.Chat().MacCredentialHeld(r.ctx, wid) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return held |
| + } |
| + hello := workerConnHello(keys.PublicString()) |
| + w.heartbeat(hello) |
| + if isHeld() { |
| + t.Fatal("held before anything started") |
| + } |
| + a, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, RunnerID: wid}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !isHeld() { |
| + t.Fatal("not held from the moment it started connecting") |
| + } |
| + // The Mac has not taken the frame yet, and says it holds nothing. |
| + w.heartbeat(hello) |
| + if !isHeld() { |
| + t.Fatal("not held from connecting") |
| + } |
| + w.expect(wire.FrameConnect) |
| + // The Mac has it now, and its hello does not say so yet: the attempt |
| + // connecting there holds. |
| + w.heartbeat(hello) |
| + if !isHeld() { |
| + t.Fatal("released while an attempt there is connecting") |
| + } |
| + // The sign-in is refused, and its Keychain item stays. |
| + w.send(wire.FrameConnection, wire.ConnectionReport{Connection: a.ID, Person: Owner, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: "provider_refused"}) |
| + residue := workerConnHello(keys.PublicString()) |
| + caps := *residue.Capabilities |
| + caps.ModelHold, caps.HoldingItems = true, []string{"Claude Code-credentials-1a2b3c4d"} |
| + residue.Capabilities = &caps |
| + w.heartbeat(residue) |
| + if !isHeld() { |
| + t.Fatal("released with a Keychain item left") |
| + } |
| + // An instance restart: still held. |
| + r.inst.Restart(t) |
| + w = r.redialMac(w, residue) |
| + w.heartbeat(residue) |
| + if !isHeld() { |
| + t.Fatal("the hold did not survive the restart") |
| + } |
| + // Each word of the Mac's alone holds: its hold, or an item it names. |
| + for _, change := range []func(*wire.Capabilities){ |
| + func(c *wire.Capabilities) { c.ModelHold = true }, |
| + func(c *wire.Capabilities) { c.HoldingItems = []string{"Claude Code-credentials-1a2b3c4d"} }, |
| + } { |
| + one := workerConnHello(keys.PublicString()) |
| + caps := *one.Capabilities |
| + change(&caps) |
| + one.Capabilities = &caps |
| + w.heartbeat(one) |
| + if !isHeld() { |
| + t.Fatalf("released while the Mac says %+v", caps) |
| + } |
| + } |
| + // The item is gone but an earlier launch is unproven: held. |
| + unproven := workerConnHello(keys.PublicString()) |
| + caps = *unproven.Capabilities |
| + caps.Unproven = wire.UnprovenCredential |
| + unproven.Capabilities = &caps |
| + w.heartbeat(unproven) |
| + if !isHeld() { |
| + t.Fatal("released while a launch is unproven") |
| + } |
| + // A hello with no capability report proves nothing. |
| + bare := workerConnHello(keys.PublicString()) |
| + bare.Capabilities = nil |
| + w.heartbeat(bare) |
| + if !isHeld() { |
| + t.Fatal("released by a hello that reported nothing") |
| + } |
| + // Everything gone: released. |
| + w.heartbeat(hello) |
| + if isHeld() { |
| + t.Fatal("still held once the Mac said everything is gone") |
| + } |
| + // A connect the Mac has not taken holds by itself: started and |
| + // cancelled at once. |
| + b, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, RunnerID: wid}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.client.CancelConnection(r.ctx, b.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.heartbeat(hello) |
| + if !isHeld() { |
| + t.Fatal("released with a connect the Mac has not taken") |
| + } |
| + w.expect(wire.FrameConnect) |
| + w.expect(wire.FrameCancelConnect) |
| + w.heartbeat(hello) |
| + if isHeld() { |
| + t.Fatal("still held once the Mac took the connect and its cancel") |
| + } |
| + // A connection the Mac reports holds it again, even unasked. |
| + w.heartbeat(workerConnHello(keys.PublicString(), wire.HeldConnection{LocalID: "claude-1", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnHealthy})) |
| + if !isHeld() { |
| + t.Fatal("a held connection does not hold") |
| + } |
| +} |
diff --git a/internal/wire/connections.go b/internal/wire/connections.go| index 6a3bda93..35d4c009 100644 |
| --- a/internal/wire/connections.go |
| +++ b/internal/wire/connections.go |
| @@ -63,8 +63,15 @@ var ConnectReasons = map[string]bool{ |
| // model Equipo can price (ProtocolMetered). |
| "key_refused": true, |
| "no_priced_model": true, |
| + // A Mac worker keeps only Claude token connections (slice F, |
| + // ProtocolMacEngineering): any other kind is refused with this. |
| + ReasonMacClaudeOnly: true, |
| } |
| +// ReasonMacClaudeOnly ends an attempt a Mac worker does not take: only |
| +// Claude, by a pasted token or its own sign-in, runs on a Mac. |
| +const ReasonMacClaudeOnly = "mac_claude_only" |
| + |
| // EventConnection fires on every state or headroom change of one of the |
| // person's connections; Data is the Connection. |
| const EventConnection = "connection" |
| @@ -242,6 +249,10 @@ type DisconnectCommand struct { |
| Connection string `json:"connection"` |
| Person string `json:"person"` |
| LocalID string `json:"local_id"` |
| + // RunnerID (ProtocolMacEngineering) is the runner whose connection it |
| + // is: a runner signs out only its own (local ids repeat across |
| + // runners). Dropped below 37. |
| + RunnerID string `json:"runner_id,omitempty"` |
| } |
| // ConnectCommand asks the runner to connect a new account for Person. |
diff --git a/internal/wire/mac_engineering.go b/internal/wire/mac_engineering.go| index 39251bf5..5492a2fa 100644 |
| --- a/internal/wire/mac_engineering.go |
| +++ b/internal/wire/mac_engineering.go |
| @@ -253,7 +253,8 @@ const ( |
| NeedsMacUpdate = "mac_update" |
| ) |
| -// WithoutMacEngineering drops a hello's Engineering status, Unproven and F probes |
| +// WithoutMacEngineering drops a hello's Engineering status, Unproven, the |
| +// credential hold and F probes |
| // (in new values; the caller's are untouched). The runner's first hello |
| // on a connection goes out before the welcome names the protocol, and an |
| // older instance's ValidCapabilities refuses an F probe; the runner sends |
| @@ -264,11 +265,11 @@ func WithoutMacEngineering(h *Hello) bool { |
| return false |
| } |
| isF := func(p Probe) bool { _, ok := engineeringProbeSuccess[p.ID]; return ok } |
| - if c.Engineering == nil && c.Unproven == "" && !slices.ContainsFunc(c.Probes, isF) { |
| + if c.Engineering == nil && c.Unproven == "" && !c.ModelHold && c.HoldingItems == nil && !slices.ContainsFunc(c.Probes, isF) { |
| return false |
| } |
| out := *c |
| - out.Engineering, out.Unproven = nil, "" |
| + out.Engineering, out.Unproven, out.ModelHold, out.HoldingItems = nil, "", false, nil |
| if slices.ContainsFunc(c.Probes, isF) { |
| out.Probes = slices.DeleteFunc(slices.Clone(c.Probes), isF) |
| } |
| @@ -325,6 +326,8 @@ func downgradeMacEngineering(body any, protocol int) (bool, error) { |
| v.ChangeFiles, v.DiffCollection, v.OutcomePhase = nil, "", "" |
| case *AskCommand: |
| v.EngAttempt, v.EngAccount, v.EngSession = 0, "", "" |
| + case *DisconnectCommand: |
| + v.RunnerID = "" |
| default: |
| return false, nil |
| } |
diff --git a/internal/wire/mac_engineering_test.go b/internal/wire/mac_engineering_test.go| index 0337cd03..af8c2563 100644 |
| --- a/internal/wire/mac_engineering_test.go |
| +++ b/internal/wire/mac_engineering_test.go |
| @@ -260,6 +260,11 @@ func TestEncodeDropsEmptyMacEngineeringKeysBelow37(t *testing.T) { |
| {"send_pack", with("frames/send_pack.json", []string{"transfer"}, map[string]any{"kind": "", "old_base_sha": ""}), []string{"kind", "old_base_sha"}}, |
| {"hello", with("frames/hello-mac-probes.json", []string{"capabilities"}, map[string]any{"engineering": nil}), []string{"engineering"}}, |
| {"change_diff", emptyDiff, []string{"publication"}}, |
| + // Slice F task 11: the credential hold, and the runner a sign-out |
| + // names, set or empty. |
| + {"hello hold", with("frames/hello-mac-probes.json", []string{"capabilities"}, map[string]any{"model_hold": true, "holding_items": []string{"Claude Code-credentials"}}), []string{"model_hold", "holding_items"}}, |
| + {"disconnect", with("frames/disconnect.json", nil, map[string]any{"runner_id": ""}), []string{"runner_id"}}, |
| + {"disconnect named", with("frames/disconnect.json", nil, map[string]any{"runner_id": "run_1"}), []string{"runner_id"}}, |
| } { |
| for _, p := range []int{35, 36} { |
| got, err := wire.Encode(c.frame, p) |
| @@ -558,3 +563,21 @@ func TestPrepareBaseAndBaseReport(t *testing.T) { |
| } |
| func typeName(v any) string { return fmt.Sprintf("%T", v) } |
| + |
| +// The Mac's credential hold names at most MaxHoldingItems Keychain items, |
| +// each within the capability string rules. |
| +func TestHoldingItemsBounded(t *testing.T) { |
| + items := make([]string, wire.MaxHoldingItems) |
| + for i := range items { |
| + items[i] = "Claude Code-credentials-" + strings.Repeat("a", i+1) |
| + } |
| + if err := wire.ValidCapabilities(wire.Capabilities{ModelHold: true, HoldingItems: items}); err != nil { |
| + t.Fatalf("%d items: %v", len(items), err) |
| + } |
| + if wire.ValidCapabilities(wire.Capabilities{ModelHold: true, HoldingItems: append(items, "one more")}) == nil { |
| + t.Fatal("more than MaxHoldingItems taken") |
| + } |
| + if wire.ValidCapabilities(wire.Capabilities{HoldingItems: []string{"a/b"}}) == nil { |
| + t.Fatal("a path taken as an item") |
| + } |
| +} |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index a096eb12..327c3bb3 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -279,7 +279,9 @@ var Tags = []string{TagLinux, TagMacOS, TagXcode, TagIOSSimulator, TagClaude, Ta |
| const ( |
| MaxSimulators = 40 |
| MaxCapabilityString = 300 |
| - MaxCapabilityBytes = 8 << 10 |
| + // MaxHoldingItems bounds Capabilities.HoldingItems. |
| + MaxHoldingItems = 8 |
| + MaxCapabilityBytes = 8 << 10 |
| ) |
| // Platform is a runner's operating system and architecture, as Go names |
| @@ -331,6 +333,13 @@ type Capabilities struct { |
| // Unproven (ProtocolMacEngineering) is a code for an attempt whose |
| // end this runner can never prove (UnprovenRecordIncomplete). |
| Unproven string `json:"unproven,omitempty"` |
| + // ModelHold (ProtocolMacEngineering): a Mac worker holds, or may |
| + // hold, a model credential: an attempt connecting, a connection's |
| + // files, a Keychain item a launch left, or a launch not yet proven |
| + // ended (spec §8.3 (4), D1). HoldingItems names the Keychain items |
| + // (their services) that hold it, at most MaxHoldingItems. |
| + ModelHold bool `json:"model_hold,omitempty"` |
| + HoldingItems []string `json:"holding_items,omitempty"` |
| } |
| // UnprovenRecordIncomplete: an attempt's turn record was not complete |
| @@ -449,6 +458,9 @@ func ValidCapabilities(c Capabilities) error { |
| if e := c.Engineering; e != nil && !validEngineeringStatus(*e) { |
| return ErrCapabilities |
| } |
| + if len(c.HoldingItems) > MaxHoldingItems { |
| + return ErrCapabilities |
| + } |
| if err := checkStrings(reflect.ValueOf(c)); err != nil { |
| return err |
| } |