package thintest import ( "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // Task 11, fix round 1 (Astra round 1): a worker's reconnect never lets // the credential hold lapse (#1), a sync that reports a connection holds // in its own transaction (#2), nothing of a worker's connections moves // below 37 in either direction (#3), and usage keeps its legacy form // below 37 (#4). // heldNow is the instance's hold on runner, read from the store as it // is now. func (r *runnersRig) heldNow(runner string) bool { r.t.Helper() held, err := r.inst.Store.Chat().MacCredentialHeld(r.ctx, runner) if err != nil { r.t.Fatal(err) } return held } // inventoryHello is a worker's hello after the welcome, which says its // connections and hold in full: change sets the hold's fields. func inventoryHello(key string, change func(*wire.Capabilities), conns ...wire.HeldConnection) wire.Hello { h := workerConnHello(key, conns...) h.Inventory = true if change != nil { caps := *h.Capabilities change(&caps) h.Capabilities = &caps } return h } // handshakeHello is what a real worker says before the welcome: no // connections, no seal key, no hold and none of the protocol 37 // capability fields (WithoutMacEngineering), though it offers 37. func handshakeHello() wire.Hello { h := workerConnHello("") wire.WithoutMacEngineering(&h) return h } // syncNow sends a sync and waits until the instance has applied it. A // sync is not durable, so nothing acks it; the instance applies one // connection's frames in order, so the answer to a lease sent after it // means the sync is in the store. func (p *peer) syncNow(s wire.Sync) { p.t.Helper() p.send(wire.FrameSync, s) p.lease("", 0) } // workerSync is a worker's sync after the welcome, saying conns. func workerSync(conns ...wire.HeldConnection) wire.Sync { return wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}, Connections: append([]wire.HeldConnection{}, conns...)} } // TestContractWorkerReconnectKeepsHold (#1): the real reconnect sequence // (the hello before the welcome, the sync, the full hello after it) // never releases the hold nor signs a connection out: with a token on // disk, and with only a Keychain item left. Only a full report saying // nothing is left releases it; a later hello that does not say it is // full never does. func TestContractWorkerReconnectKeepsHold(t *testing.T) { claude1 := wire.HeldConnection{LocalID: "claude-1", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, Label: "w@example.com", State: wire.ConnHealthy} holds := func(c *wire.Capabilities) { c.ModelHold = true } residue := func(c *wire.Capabilities) { c.ModelHold, c.HoldingItems = true, []string{"Claude Code-credentials-1a2b3c4d"} } t.Run("a token on disk", func(t *testing.T) { r := newMacRig(t) key := sealKeys(t).PublicString() w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) wid := w.fr.Welcome.RunnerID w.heartbeat(inventoryHello(key, holds, claude1)) if c, ok := r.connRow(wid, "claude-1"); !ok || c.State != wire.ConnHealthy || !r.heldNow(wid) { t.Fatalf("setup: %+v %v held=%v", c, ok, r.heldNow(wid)) } stillThere := func(when string) { t.Helper() if c, _ := r.connRow(wid, "claude-1"); c.State != wire.ConnHealthy || !r.heldNow(wid) { t.Fatalf("%s: row %s, held=%v", when, c.State, r.heldNow(wid)) } } // A hello before the welcome is never the inventory, whatever it // says. claims := handshakeHello() claims.Inventory = true w = r.redialMac(w, claims) w.lease("", 0) stillThere("a hello before the welcome claiming to be the inventory") w = r.redialMac(w, handshakeHello()) w.lease("", 0) stillThere("the hello before the welcome") w.syncNow(workerSync(claude1)) stillThere("the sync") w.heartbeat(inventoryHello(key, holds, claude1)) stillThere("the full hello") // A hello that does not say it is full says nothing is gone. partial := workerConnHello(key) partial.Inventory = false w.heartbeat(partial) stillThere("a hello without its inventory") // Nor does a marked hello with no capability report, or one the // instance refuses: nothing in it can be judged (fix round 2). bare := workerConnHello(key) bare.Capabilities = nil w.heartbeat(bare) stillThere("a marked hello with no capability report") invalid := workerConnHello(key) caps := *invalid.Capabilities caps.Tags = append([]string{"not-a-tag"}, caps.Tags...) invalid.Capabilities = &caps if wire.ValidCapabilities(caps) == nil { t.Fatal("the report meant to be refused is valid") } w.heartbeat(invalid) stillThere("a marked hello with a refused capability report") w.heartbeat(inventoryHello(key, nil)) if c, _ := r.connRow(wid, "claude-1"); c.State != wire.ConnSignedOut || r.heldNow(wid) { t.Fatalf("a full report of nothing: row %s, held=%v", c.State, r.heldNow(wid)) } }) t.Run("only a Keychain item", func(t *testing.T) { r := newMacRig(t) key := sealKeys(t).PublicString() w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) wid := w.fr.Welcome.RunnerID w.heartbeat(inventoryHello(key, nil)) a, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, RunnerID: wid}) if err != nil { t.Fatal(err) } w.expect(wire.FrameConnect) w.send(wire.FrameConnection, wire.ConnectionReport{Connection: a.ID, Person: Owner, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: "provider_refused"}) w.heartbeat(inventoryHello(key, residue)) if !r.heldNow(wid) { t.Fatal("setup: not held with an item left") } w = r.redialMac(w, handshakeHello()) w.lease("", 0) if !r.heldNow(wid) { t.Fatal("the hello before the welcome released the hold") } w.syncNow(workerSync()) if !r.heldNow(wid) { t.Fatal("an empty sync released the hold") } w.heartbeat(inventoryHello(key, residue)) if !r.heldNow(wid) { t.Fatal("the full hello naming the item released the hold") } w.heartbeat(inventoryHello(key, nil)) if r.heldNow(wid) { t.Fatal("still held once the Mac said in full that nothing is left") } }) } // TestContractWorkerSyncHolds (#2): a worker's sync that reports a // connection records it and holds the Mac in the same transaction; an // empty sync neither releases the hold nor signs the connection out. func TestContractWorkerSyncHolds(t *testing.T) { r := newMacRig(t) key := sealKeys(t).PublicString() w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) wid := w.fr.Welcome.RunnerID w.heartbeat(inventoryHello(key, nil)) if r.heldNow(wid) { t.Fatal("held with nothing there") } w.syncNow(workerSync(wire.HeldConnection{LocalID: "claude-2", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnHealthy})) if c, ok := r.connRow(wid, "claude-2"); !ok || c.State != wire.ConnHealthy || !r.heldNow(wid) { t.Fatalf("after the sync: %+v %v held=%v", c, ok, r.heldNow(wid)) } w.syncNow(workerSync()) if c, _ := r.connRow(wid, "claude-2"); c.State != wire.ConnHealthy || !r.heldNow(wid) { t.Fatalf("an empty sync: row %s, held=%v", c.State, r.heldNow(wid)) } } // TestContractWorkerConnectionCommandsBelow37 (#3): a Mac that comes // back below 37 is delivered none of the connection commands queued for // it, and what it replays of its connections (a report, a check's usage) // changes nothing; back at 37 the queued command goes. func TestContractWorkerConnectionCommandsBelow37(t *testing.T) { r := newMacRig(t) key := sealKeys(t).PublicString() w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) wid := w.fr.Welcome.RunnerID w.heartbeat(inventoryHello(key, nil)) a, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken, RunnerID: wid}) if err != nil { t.Fatal(err) } old := r.redialMac(w, macEngineerHello("Tito Studio", wire.EngineeringNoConnection, wire.ProtocolChangeDiffs, false)) if old.fr.Welcome.Protocol != wire.ProtocolChangeDiffs { t.Fatalf("welcome %+v", old.fr.Welcome) } old.lease("", 0) time.Sleep(300 * time.Millisecond) old.lease("", 0) for _, h := range old.held { switch h.f.Type { case wire.FrameConnect, wire.FrameSecret, wire.FrameCancelConnect, wire.FrameDisconnect, wire.FrameCheck, wire.FramePreference: t.Fatalf("delivered below 37: %s", h.raw) } } if r.unacked(wid, wire.FrameConnect) != 1 { t.Fatal("the queued connect did not wait") } // What it replays from before changes nothing. old.send(wire.FrameConnection, wire.ConnectionReport{Connection: a.ID, Person: Owner, LocalID: "claude-1", Provider: wire.ProviderClaude, State: wire.ConnHealthy, Label: "w@example.com"}) if c, err := r.client.Connection(r.ctx, a.ID); err != nil || c.State != wire.ConnConnecting || c.LocalID != "" { t.Fatalf("a report below 37 applied: %+v %v", c, err) } old.send(wire.FrameUsage, wire.UsageReport{CheckID: "chk_old", Rows: []wire.Usage{{Provider: wire.ProviderClaude, Connection: "claude-1", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true}}}) if n := r.count("SELECT count(*) FROM chat_usage WHERE step_id = 'chk_old'"); n != 0 { t.Fatalf("%d usage rows from a worker below 37", n) } // Back at 37: the queued connect goes. back := r.redialMac(old, inventoryHello(key, nil)) if _, body := back.expect(wire.FrameConnect); body.(*wire.ConnectCommand).Connection != a.ID { t.Fatalf("connect %+v", body) } } // TestContractUsageBelow37 (#4): below 37 a usage row keeps the legacy // form (no runner) and a worker's connection usage is refused; at 37 the // row names the runner that reported it. func TestContractUsageBelow37(t *testing.T) { report := func(id string) wire.UsageReport { return wire.UsageReport{CheckID: id, Rows: []wire.Usage{{Provider: wire.ProviderClaude, Connection: "claude-1", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: i64(10), OutputTokens: i64(5)}}} } runnerOf := func(r *runnersRig, check string) (string, int) { t.Helper() var n int var runner *string if err := r.inst.DB.Writer().QueryRow("SELECT count(*), max(runner_id) FROM chat_usage WHERE step_id = ?", check).Scan(&n, &runner); err != nil { t.Fatal(err) } if runner == nil { return "", n } return *runner, n } t.Run("36", func(t *testing.T) { r := newMacRigAt(t, 36) w := r.newMacEngineerAt("Tito Studio", wire.EngineeringNoConnection, 36, false) r.primary.send(wire.FrameUsage, report("chk_p36")) if got, n := runnerOf(r, "chk_p36"); n != 1 || got != "" { t.Fatalf("the primary's row at 36: %d rows, runner %s", n, got) } w.send(wire.FrameUsage, report("chk_w36")) if _, n := runnerOf(r, "chk_w36"); n != 0 { t.Fatalf("%d rows of a worker's connection usage at 36", n) } }) t.Run("37", func(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) r.primary.send(wire.FrameUsage, report("chk_p37")) if got, n := runnerOf(r, "chk_p37"); n != 1 || got != r.primary.fr.Welcome.RunnerID { t.Fatalf("the primary's row at 37: %d rows, runner %s", n, got) } w.send(wire.FrameUsage, report("chk_w37")) if got, n := runnerOf(r, "chk_w37"); n != 1 || got != w.fr.Welcome.RunnerID { t.Fatalf("the worker's row at 37: %d rows, runner %s", n, got) } }) }