package headless import ( "context" "crypto/rand" "encoding/json" "fmt" "os" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/stagingtest" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // session is one client: a snapshot, a conversation folded from events, // and an open stream. type session struct { env *Env ctx context.Context conv *thintest.Conversation stream *thintest.Stream // followed closes when the stream's last event has been applied. followed chan struct{} } func open(t *testing.T, env *Env) *session { t.Helper() limit := 10 * time.Minute if env.Live { // Live review and checks run for many minutes. limit = 50 * time.Minute } ctx, cancel := context.WithTimeout(context.Background(), limit) t.Cleanup(cancel) snap, err := env.Client.Snapshot(ctx) if err != nil { t.Fatal(err) } s := &session{env: env, ctx: ctx, conv: thintest.NewConversation(snap)} s.follow(t) return s } // follow opens the stream at the conversation's cursor, retrying while an // instance restarts. func (s *session) follow(t *testing.T) { t.Helper() deadline := time.Now().Add(90 * time.Second) for { stream, err := s.env.Client.Open(s.ctx, s.conv.Cursor) if err == nil { s.stream = stream t.Cleanup(stream.Close) followed := make(chan struct{}) s.followed = followed go func() { defer close(followed) s.conv.Follow(stream) }() return } if thintest.Status(err) == 410 || time.Now().After(deadline) { t.Fatalf("open stream: %v", err) } time.Sleep(500 * time.Millisecond) } } // close ends the stream once every event it brought has been applied: // the conversation's cursor holds still after it. func (s *session) close() { if s.stream != nil { s.stream.Close() <-s.stream.Done <-s.followed s.stream = nil } } func key() string { return "h-" + strings.ToLower(rand.Text()) } func (s *session) send(t *testing.T, text string) wire.Sent { t.Helper() if s.env.RunID != "" { text += "\nSuite run: " + s.env.RunID } s.env.Turn(t) sent, err := s.env.Client.Send(s.ctx, text, key()) if err != nil { t.Fatalf("send: %v", err) } return sent } func (s *session) wait(t *testing.T, what string, timeout time.Duration, cond func(*thintest.Conversation) bool) { t.Helper() if !s.conv.Wait(timeout, cond) { var state string s.conv.Locked(func(c *thintest.Conversation) { raw, _ := json.Marshal(c.Turns) state = string(raw) }) t.Fatalf("timed out waiting for %s; turns %s", what, state) } } func (s *session) waitTurn(t *testing.T, id string, states ...string) wire.Turn { t.Helper() var out wire.Turn s.wait(t, "turn "+id+" "+strings.Join(states, "|"), 4*time.Minute, func(c *thintest.Conversation) bool { out = c.Turns[id] for _, st := range states { if out.State == st { return true } } return false }) return out } func (s *session) reply(t *testing.T, turn string) wire.Message { t.Helper() var out wire.Message s.conv.Locked(func(c *thintest.Conversation) { for _, m := range c.Replies() { if m.TurnID == turn { if out.ID != "" { t.Fatalf("two replies for turn %s", turn) } out = m } } }) if out.ID == "" { t.Fatalf("no reply for turn %s", turn) } return out } // firstToken sends text and returns the time to the first streamed delta. func (s *session) firstToken(t *testing.T, text string) (time.Duration, wire.Sent) { t.Helper() start := time.Now() sent := s.send(t, text) commit := time.Since(start) var first time.Time s.wait(t, "first delta", 3*time.Minute, func(c *thintest.Conversation) bool { first = c.FirstDelta[sent.Turn.ID] return !first.IsZero() || wire.Terminal(c.Turns[sent.Turn.ID].State) }) if first.IsZero() { t.Fatalf("turn ended without a delta: %+v", s.conv.Turns[sent.Turn.ID]) } s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) clock := turnClock{Commit: commit, FirstDelta: first.Sub(start), Message: time.Since(start)} s.conv.Locked(func(c *thintest.Conversation) { if at, ok := c.FirstActivity[sent.Turn.ID]; ok { clock.FirstActivity = at.Sub(start) } }) if turn, err := s.env.Client.Turn(s.ctx, sent.Turn.ID); err == nil { clock.Timing = turn.Timing } TurnClocks[t.Name()+"/"+strconv.Itoa(len(TurnClocks))+"/"+sent.Turn.ID] = clock return first.Sub(start), sent } // Timings collects first-token measurements for the report; Witness // what each Engineering scenario saw. var ( Timings = map[string]time.Duration{} Witness = map[string]any{} ) func report(t *testing.T) { path := os.Getenv("EQUIPO_HEADLESS_REPORT") if path == "" { return } out := map[string]any{} for k, v := range Timings { out[k] = v.Round(time.Millisecond).String() } for k, v := range TurnClocks { out[k] = v } for k, v := range Witness { out["witness/"+k] = v } raw, _ := json.MarshalIndent(out, "", " ") if err := os.WriteFile(path, raw, 0600); err != nil { t.Log(err) } } // Scenario 1: a signed-in device says hello and sees the first streamed // text quickly. Cold (no coordinator process: fresh or resumed session) // and warm (process already up) are measured separately. func scenarioFirstToken(t *testing.T, env *Env) { env.RestartRunner(t) s := open(t, env) // The edge can drop a stream (a 502 on staging); follow like a client. s.keep() me, err := env.Client.Me(s.ctx) if err != nil || me.Address == "" { t.Fatalf("me: %+v %v", me, err) } s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) cold, first := s.firstToken(t, "hello") warm, second := s.firstToken(t, "Thanks. Reply with one short sentence.") env.RestartRunner(t) resumed, third := s.firstToken(t, "Still there? One short sentence.") Timings[t.Name()+"/cold"], Timings[t.Name()+"/warm"], Timings[t.Name()+"/cold_resume"] = cold, warm, resumed t.Logf("first token: cold %v, warm %v, cold resume %v", cold, warm, resumed) for _, sent := range []wire.Sent{first, second, third} { if r := s.reply(t, sent.Turn.ID); r.Text == "" { t.Fatalf("empty reply for %s", sent.Turn.ID) } } if !env.Live { if r := s.reply(t, second.Turn.ID).Text; !strings.Contains(r, "process turn 2.") { t.Fatalf("second turn did not reuse the warm process: %q", r) } if r := s.reply(t, third.Turn.ID).Text; !strings.Contains(r, "Turn 3, resumed session, process turn 1.") { t.Fatalf("restarted runner did not resume the session: %q", r) } } for _, sample := range []struct { name string first, limit time.Duration cold bool }{ {"warm", warm, 5 * time.Second, false}, {"cold", cold, env.ResumeThreshold, true}, {"cold_resume", resumed, env.ResumeThreshold, true}, } { samples, err := stagingtest.Latency(sample.first, sample.limit, func() time.Duration { if sample.cold { env.RestartRunner(t) } elapsed, _ := s.firstToken(t, "Reply with one short sentence.") return elapsed }) for i, elapsed := range samples { Timings[fmt.Sprintf("%s/%s/sample_%d", t.Name(), sample.name, i+1)] = elapsed } t.Logf("%s first-token samples: %v (limit %v)", sample.name, samples, sample.limit) if err != nil { t.Error(err) } } } // Scenario 3: with the runner offline the message waits as queued; when // the runner reconnects it is answered exactly once. func scenarioRunnerOffline(t *testing.T, env *Env) { s := open(t, env) // The edge can drop a stream (a 502 on staging); follow like a client. s.keep() env.StopRunner(t) s.wait(t, "runner offline", 90*time.Second, func(c *thintest.Conversation) bool { return !c.Runner.Online }) sent := s.send(t, "Are you there? One short sentence.") time.Sleep(time.Second) if st := s.conv.Turns[sent.Turn.ID].State; st != wire.TurnQueued { t.Fatalf("offline turn is %s, want queued", st) } env.StartRunner(t) s.wait(t, "runner online", 60*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) s.reply(t, sent.Turn.ID) page, err := env.Client.Messages(s.ctx, "", 200) if err != nil { t.Fatal(err) } count := 0 for _, m := range page.Items { if m.TurnID == sent.Turn.ID && m.Role == wire.RoleCoordinator { count++ } } if count != 1 { t.Fatalf("%d replies stored for one turn", count) } } // Scenario 6: two quick messages while the coordinator is busy reach it // as one frame and produce one reply. func scenarioQuickMessages(t *testing.T, env *Env) { s := open(t, env) // The edge can drop a stream (a 502 on staging); follow like a client. s.keep() busy := s.send(t, env.Slow) s.waitTurn(t, busy.Turn.ID, wire.TurnRunning, wire.TurnReplied) a := s.send(t, "One more thing:") b, err := env.Client.Send(s.ctx, "what is two plus two? Reply with the number only.", key()) if err != nil { t.Fatal(err) } if b.Turn.ID != a.Turn.ID || len(b.Turn.MessageIDs) != 2 { t.Fatalf("quick messages split: %s %s %v", a.Turn.ID, b.Turn.ID, b.Turn.MessageIDs) } s.waitTurn(t, busy.Turn.ID, wire.TurnReplied) s.waitTurn(t, a.Turn.ID, wire.TurnReplied) r := s.reply(t, a.Turn.ID) if !env.Live && !strings.Contains(r.Text, "You sent 2 messages") { t.Fatalf("coordinator did not get both messages in one frame: %q", r.Text) } if env.Live && !strings.Contains(r.Text, "4") { t.Fatalf("joined reply %q", r.Text) } } // Scenario 7: a dropped stream resumes from its cursor with nothing lost // or repeated; an expired cursor gets 410 and recovers from a snapshot. func scenarioStreamResume(t *testing.T, env *Env) { s := open(t, env) s.wait(t, "runner online", 60*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) s.close() cursor := s.conv.Cursor sent := s.send(t, "Reply with the word resumed.") deadline := time.Now().Add(3 * time.Minute) for { turn, err := env.Client.Turn(s.ctx, sent.Turn.ID) if err == nil && wire.Terminal(turn.State) { break } if time.Now().After(deadline) { t.Fatalf("turn did not end: %+v %v", turn, err) } time.Sleep(300 * time.Millisecond) } before := s.conv.Applied s.follow(t) s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) s.reply(t, sent.Turn.ID) if s.conv.Applied == before { t.Fatal("no events replayed from the cursor") } // The same events again from the old cursor change nothing. Only the // replay counts, up to where the conversation stood: the live stream // closes first, and nothing after that point is a repeat. The // conversation goes on after a reply (on staging a runner's hello // stores a connection's fresh headroom at any moment), and an event // newer than the conversation's cursor is news, not a replay. s.close() top := s.conv.Cursor applied := s.conv.Applied // The whole replay is bounded, opening it again included. rctx, cancel := context.WithTimeout(s.ctx, 30*time.Second) defer cancel() again, err := env.Client.Open(rctx, cursor) if err != nil { t.Fatal(err) } if env.duringReplay != nil { env.duringReplay(t, s) } last := cursor replay: for { select { case e, ok := <-again.Events: if !ok { // The edge can drop a stream (a 502 on staging): resume the // replay from what it brought, as a client would. again.Close() for again, err = env.Client.Open(rctx, last); err != nil; again, err = env.Client.Open(rctx, last) { if thintest.Status(err) == 410 || rctx.Err() != nil { t.Fatalf("reopen the replay at %d: %v", last, err) } time.Sleep(500 * time.Millisecond) } continue } if e.Cursor > top { t.Fatalf("the replay passed cursor %d without it (at %d)", top, e.Cursor) } s.conv.Apply(e) last = max(last, e.Cursor) if e.Cursor == top { break replay } case <-rctx.Done(): t.Fatalf("the replay did not reach cursor %d (at %d)", top, last) } } again.Close() if s.conv.Applied != applied { t.Fatal("replayed events applied twice") } stale := s.conv.Cursor + 1_000_000_000 if env.AgeEvents(t) { stale = cursor } if _, err = env.Client.Open(s.ctx, stale); thintest.Status(err) != 410 { t.Fatalf("stale cursor: %v", err) } snap, err := env.Client.Snapshot(s.ctx) if err != nil { t.Fatal(err) } s.close() s.conv.Reset(snap) s.follow(t) found := false for _, m := range snap.Messages { found = found || m.TurnID == sent.Turn.ID && m.Role == wire.RoleCoordinator } if !found { t.Fatal("snapshot lost the reply") } } // Scenario 8: the instance restarts during a turn. The turn finishes or // fails visibly; nothing the person sent or was sent is lost. func scenarioInstanceRestart(t *testing.T, env *Env) { s := open(t, env) s.wait(t, "runner online", 60*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) sent := s.send(t, env.Slow) s.waitTurn(t, sent.Turn.ID, wire.TurnRunning, wire.TurnReplied) s.close() s.restartInstance(t) // Reopen from the cursor, and again if anything still cuts the stream. s.keep() turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied, wire.TurnFailed) if turn.State == wire.TurnFailed && turn.Reason == "" { t.Fatal("failed without a reason") } snap, err := env.Client.Snapshot(s.ctx) if err != nil { t.Fatal(err) } ids := map[string]bool{} for _, m := range snap.Messages { ids[m.ID] = true } if !ids[sent.Message.ID] || turn.State == wire.TurnReplied && !ids[turn.ReplyID] { t.Fatalf("restart lost messages: %+v", turn) } // The conversation carries on (fake CLI only, to save live turns). if !env.Live { next := s.send(t, "And now? One short sentence.") s.waitTurn(t, next.Turn.ID, wire.TurnReplied) } } // restartInstance restarts the instance and returns only once the old // process has stopped and a new one serves. The platform's restart command // returns before the box cycles the instance (2-35 s later on staging), so // a probe stream opened first marks the old process: draining closes every // stream. A draining process still answers briefly, but its new streams end // at once, so the new process is the one that holds a stream open. func (s *session) restartInstance(t *testing.T) { t.Helper() const stops, serves, hold = 2 * time.Minute, 90 * time.Second, 2 * time.Second var cursor int64 s.conv.Locked(func(c *thintest.Conversation) { cursor = c.Cursor }) probe, err := s.env.Client.Open(s.ctx, cursor) if err != nil { t.Fatalf("instance restart: open the probe stream: %v", err) } defer probe.Close() // A full event buffer would stall the reader before it sees the end. drain := func(st *thintest.Stream) { go func() { for range st.Events { } }() } drain(probe) issued := time.Now() s.env.RestartInst(t) select { case <-probe.Done: case <-time.After(stops): t.Fatalf("instance restart: the old instance still serves %v after the restart command returned", stops) } stopped := time.Now() deadline := stopped.Add(serves) for { ctx, cancel := context.WithTimeout(s.ctx, 30*time.Second) stream, err := s.env.Client.Open(ctx, cursor) held := false if err == nil { drain(stream) select { case <-stream.Done: case <-time.After(hold): held = true } stream.Close() } cancel() if held { break } if time.Now().After(deadline) { t.Fatalf("instance restart: no new instance holds a stream %v after the old one stopped (last error %v)", serves, err) } time.Sleep(500 * time.Millisecond) } t.Logf("instance restart: old instance stopped %v after the command, new one serving %v later", stopped.Sub(issued).Round(100*time.Millisecond), time.Since(stopped).Round(100*time.Millisecond)) } // Coordinator cancel: the attempt's process is stopped, the draft // discarded, the turn ends cancelled, and the next message is answered. func scenarioCancel(t *testing.T, env *Env) { s := open(t, env) // The edge can drop a stream (a 502 on staging); follow like a client. s.keep() sent := s.send(t, env.Slow) s.waitTurn(t, sent.Turn.ID, wire.TurnRunning) s.wait(t, "draft", time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[sent.Turn.ID] != "" }) if _, err := env.Client.Cancel(s.ctx, sent.Turn.ID); err != nil { t.Fatal(err) } s.waitTurn(t, sent.Turn.ID, wire.TurnCancelled) if s.conv.Drafts[sent.Turn.ID] != "" { t.Fatal("draft kept after cancel") } if !env.Live { next := s.send(t, "Never mind. One short sentence.") s.waitTurn(t, next.Turn.ID, wire.TurnReplied) } } // Crash recovery: the runner process is killed (SIGKILL) mid-turn; on // restart it takes a new attempt from its durable state and the turn is // answered once. func scenarioRunnerCrash(t *testing.T, env *Env) { s := open(t, env) // The edge can drop a stream (a 502 on staging); follow like a client. s.keep() sent := s.send(t, env.Slow) s.waitTurn(t, sent.Turn.ID, wire.TurnRunning) s.wait(t, "streaming", 2*time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[sent.Turn.ID] != "" }) env.KillRunner(t) env.StartRunner(t) turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) if turn.Attempt != 2 { t.Fatalf("recovered turn attempt %d, want 2", turn.Attempt) } s.reply(t, sent.Turn.ID) } var scenarios = []struct { name string run func(*testing.T, *Env) }{ // Moving in first: on staging a fresh runner moves in at once, and // these settle it before the other scenarios talk to it. {"2b_move_in", scenarioMoveIn}, {"2b_first_message", scenarioFirstMessage}, {"2b_access", scenarioAccessChange}, {"2b_desk_failure", scenarioDeskFailure}, {"2b_notebook", scenarioNotebook}, {"1_first_token", scenarioFirstToken}, {"3_runner_offline", scenarioRunnerOffline}, {"6_quick_messages", scenarioQuickMessages}, {"7_stream_resume", scenarioStreamResume}, {"8_instance_restart", scenarioInstanceRestart}, {"cancel", scenarioCancel}, {"runner_crash", scenarioRunnerCrash}, {"2_project", scenarioProject}, {"2_find", scenarioFindAndRead}, {"2_new_work", scenarioNewWork}, {"2_question", scenarioQuestion}, {"2_project_home", scenarioProjectHome}, {"3_engineering", scenarioEngineering}, {"3_step_cancel", scenarioStepCancel}, {"3_step_contained", scenarioStepContained}, {"3_step_refused", scenarioStepRefused}, {"4_step_crash", scenarioStepCrash}, {"3_grant", scenarioGrant}, {"3_empty_repo", scenarioEmptyRepo}, {"3_empty_engineering", scenarioEmptyEngineering}, {"3_empty_merge", scenarioEmptyMerge}, {"3_empty_merge_rebuilt", scenarioEmptyMergeRebuilt}, {"3_empty_fix_round", scenarioEmptyFixRound}, {"4_review", scenarioReview}, {"4_checks_honest", scenarioChecksHonest}, {"4_witness", scenarioReviewWitness}, {"4b_ask", scenarioAsk}, {"4b_witness", scenarioAskWitness}, {"4c_checks_card", scenarioChecksCard}, {"4c_rebase", scenarioRebase}, {"4c_duplicate", scenarioDuplicate}, {"4c_witness", scenarioMergeWitness}, {"conn1_witness", scenarioConnWitness}, {"assistant_attachments", scenarioAssistantAttachments}, } // TestHeadless runs every scenario against a fresh local instance and // runner with the fake CLI in real bubblewrap. func TestHeadless(t *testing.T) { for _, sc := range scenarios { t.Run(sc.name, func(t *testing.T) { env, _, r := localEnv(t) r.subprocess = sc.name == "runner_crash" || sc.name == "4_step_crash" // Moving in is on for its own scenarios; those that reset the // desk start the runner themselves. r.opts.NoMoveIn = !strings.HasPrefix(sc.name, "2b_") if sc.name == "2b_first_message" { r.opts.Claude.MoveInNote = "\nmovein-pause:700" } if sc.name != "2b_desk_failure" { r.start(t) } sc.run(t, env) }) } report(t) } // TestHeadlessStreamResumeWhileLive is scenario 7 while something new // reaches the conversation as it reads the replay: on staging a runner's // hello stores a connection's fresh headroom at any moment after a reply. // Only the replay must change nothing; what is new still applies. func TestHeadlessStreamResumeWhileLive(t *testing.T) { env, _, r := localEnv(t) r.opts.NoMoveIn = true r.start(t) var added string var live *session env.duringReplay = func(t *testing.T, s *session) { c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } added, live = c.ID, s } scenarioStreamResume(t, env) // What was new during the replay reaches the conversation all the same. live.wait(t, "the connection added during the replay", 30*time.Second, func(c *thintest.Conversation) bool { _, ok := c.Connections[added] return ok }) } // TestStaging runs the same scenarios against staging with the real CLI. // The gate script sets the origin, the device bearer and the controls. func TestStaging(t *testing.T) { env := stagingEnv(t) only := os.Getenv("EQUIPO_STAGING_SCENARIOS") for _, sc := range scenarios { if only != "" && !strings.Contains(","+only+",", ","+sc.name+",") { continue } if !t.Run(sc.name, func(t *testing.T) { before := *env.turns defer func() { used := *env.turns - before t.Logf("model turns used: %d (total %d)", used, *env.turns) Witness[t.Name()+"/turns"] = used }() sc.run(t, env) }) { break } } t.Logf("model turns used: %d", *env.turns) report(t) fmt.Fprintf(os.Stderr, "staging turns %d\n", *env.turns) }