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 after the welcome: its // seal key and connections, the whole inventory. func workerConnHello(key string, conns ...wire.HeldConnection) wire.Hello { h := macEngineerHello("Tito Studio", wire.EngineeringNoConnection, wire.ProtocolMacEngineering, false) h.SealKey, h.Connections, h.Inventory = key, append([]wire.HeldConnection{}, conns...), true 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") } }