package thintest import ( "errors" "net/http" "net/url" "slices" "strings" "sync" "testing" "amadan.net/oficina/equipo/internal/equipo/chat" "amadan.net/oficina/equipo/internal/wire" ) // resumeMarker is a phrase of the note the Assistant gets once the // person has connected their Oficina apps (the instance's noteConnected). const resumeMarker = "has just connected their Oficina apps" // resumes are the person's Assistant turns the instance queued itself // after a connect: team_update turns whose note is noteConnected. func (o *oficinaRig) resumes() int { o.t.Helper() return o.rows("SELECT count(*) FROM chat_turns WHERE kind = ? AND lane = ? AND note LIKE ?", wire.TurnTeamUpdate, wire.LaneAssistant, "%"+resumeMarker+"%") } // asked raises the connect card from a person turn for words and ends // that turn the way a model does when it needs the apps: with a reply. func (o *oficinaRig) asked(words string) (turn string) { o.t.Helper() turn = o.begin(words) if res := o.tool("l-"+turn, wire.ToolLook, map[string]any{"query": "calendar"}); !strings.Contains(res.Text, "not connected") { o.t.Fatalf("look: %+v", res) } (&teamRig{o.opsRig}).reply(turn) return turn } // finish connects through Base and returns the finish's status, with // the state and code it used. func (o *oficinaRig) finish() (status, state, code string) { o.t.Helper() u, err := url.Parse(o.callback(o.base.Origin + "/ask")) if err != nil { o.t.Fatal(err) } state, code = u.Query().Get("oficina_state"), u.Query().Get("oficina_code") status, err = o.a.OficinaFinish(o.ctx, state, code) if err != nil { o.t.Fatalf("finish: %v", err) } return status, state, code } // laneMessages are the Assistant lane's messages as Base reads them, // oldest first. func (o *oficinaRig) laneMessages() []wire.Message { o.t.Helper() page, err := o.a.Messages(o.ctx, "", 100) if err != nil { o.t.Fatal(err) } items := slices.Clone(page.Items) slices.SortFunc(items, func(a, b wire.Message) int { return a.CreatedAt.Compare(b.CreatedAt) }) return items } // TestContractAssistantOficinaResumes (ruling 2026-11-19): once the // person connects, the Assistant carries on by itself. One team_update // turn is queued in their Assistant lane and dispatched, its note the // instance's, never words the person did not type; it may make the // write the person asked for; its reply is the only thing new in the // lane. A repeated finish, a connect with no card open, and the same // card settled again queue nothing more. func TestContractAssistantOficinaResumes(t *testing.T) { o := newOficinaRig(t) tr := &teamRig{o.opsRig} words := "Put lunch with Ana in my calendar on Friday." first := o.asked(words) before := o.laneMessages() status, state, code := o.finish() if status != "connected" { t.Fatalf("finish: %q", status) } u := tr.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate || u.TurnID == first || len(u.PersonText) != 0 || !strings.Contains(u.Text, resumeMarker) { t.Fatalf("resume frame: %+v", u) } if !slices.ContainsFunc(u.Tail, func(m wire.TailMessage) bool { return m.Role == wire.RolePerson && m.Text == words }) { t.Errorf("the request is not in the resume's tail: %+v", u.Tail) } if n := o.resumes(); n != 1 { t.Fatalf("%d resume turns", n) } // The resume answers the person's own request: the write they asked // for goes through. tr.in(u.TurnID, func() { if res := o.use("w1", "calendar_create_event", map[string]any{"title": "Lunch with Ana", "start_local": "2026-11-20T13:00"}); res.IsError || res.Code != "used" { t.Fatalf("write in the resume: %+v", res) } }) reply := "Lunch with Ana is in your calendar for Friday." if err := o.runner.Send(o.ctx, "r-resume", wire.FrameReply, wire.Reply{TurnID: u.TurnID, Attempt: 1, Text: reply}); err != nil { t.Fatal(err) } o.until("resume replied", func() bool { return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND state = ?", u.TurnID, wire.TurnReplied) == 1 }) after := o.laneMessages() if len(after) != len(before)+1 { t.Fatalf("lane before %+v, after %+v", before, after) } if last := after[len(after)-1]; last.Role != wire.RoleAssistant || last.Text != reply || last.TurnID != u.TurnID { t.Errorf("new in the lane: %+v", last) } if n := len(slices.DeleteFunc(after, func(m wire.Message) bool { return m.Role != wire.RolePerson })); n != 1 { t.Errorf("%d person messages in the lane", n) } // A repeated finish: the state is used up, nothing more is queued. if again, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || again != "expired" { t.Errorf("replayed finish: %q %v", again, err) } // Connecting again with no card open asks for nothing. if again, _, _ := o.finish(); again != "connected" { t.Errorf("second connect: %q", again) } // Two finishes that both found the card open settle it twice; the // card's key lets only the first queue a turn. card := o.connectCards()[0] if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET state = ? WHERE id = ?", wire.CardOpen, card.ID); err != nil { t.Fatal(err) } if err := o.inst.Store.Chat().SettleConnect(o.ctx, Owner, "oficina"); err != nil { t.Fatalf("settled again: %v", err) } if n := o.resumes(); n != 1 { t.Errorf("%d resume turns after replays", n) } if n := o.rows("SELECT count(*) FROM chat_turns WHERE lane = ? AND state IN (?, ?, ?)", wire.LaneAssistant, wire.TurnQueued, wire.TurnRunning, wire.TurnWaiting); n != 0 { t.Errorf("%d Assistant turns in flight after replays", n) } } // TestContractAssistantOficinaResumeWaits: a connect while the person's // Assistant turn still runs queues the resume behind it, as notes wait; // it is dispatched once that turn ends. func TestContractAssistantOficinaResumeWaits(t *testing.T) { o := newOficinaRig(t) tr := &teamRig{o.opsRig} first := o.begin("Put lunch with Ana in my calendar on Friday.") o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) if status, _, _ := o.finish(); status != "connected" { t.Fatalf("finish: %q", status) } if n := o.resumes(); n != 1 { t.Fatalf("%d resume turns", n) } if n := o.rows("SELECT count(*) FROM chat_turns WHERE kind = ? AND dispatched = ?", wire.TurnTeamUpdate, true); n != 0 { t.Fatalf("the resume went while the person's turn ran") } tr.reply(first) if u := tr.message(wire.LaneAssistant); u.Kind != wire.TurnTeamUpdate || !strings.Contains(u.Text, resumeMarker) { t.Fatalf("after the turn ended: %+v", u) } } // TestContractAssistantOficinaNoResumeUnlessConnected: a consent // refused, a finish connect could not complete and one that expired // queue nothing and leave the card open; the connect that works then // queues the one turn. func TestContractAssistantOficinaNoResumeUnlessConnected(t *testing.T) { o := newOficinaRig(t) ana := o.other("ana@example.com") ana.connect(o.base.Mint()) o.asked("Put lunch with Ana in my calendar on Friday.") o.fake.Deny = true if back := o.callback(o.base.Origin + "/ask"); back != o.base.Origin+"/ask?oficina=denied" { t.Fatalf("denied: %q", back) } o.fake.Down = true if status, _, _ := o.finish(); status != "unavailable" { t.Fatalf("connect down: %q", status) } o.fake.Down = false state, code := o.handBack(o.base.Origin + "/ask") var s *ErrStatus if _, err := ana.a.OficinaFinish(o.ctx, state, code); !errors.As(err, &s) || s.Status != http.StatusForbidden { t.Fatalf("another person's finish: %v", err) } if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "expired" { t.Fatalf("expired: %q %v", status, err) } if n := o.resumes(); n != 0 { t.Fatalf("%d resume turns without a connection", n) } if cards := o.connectCards(); len(cards) != 1 || cards[0].State != wire.CardOpen { t.Fatalf("cards: %+v", cards) } if status, _, _ := o.finish(); status != "connected" { t.Fatalf("finish: %q", status) } if n := o.resumes(); n != 1 { t.Errorf("%d resume turns once connected", n) } } // TestContractAssistantOficinaResumeRecovers: a finish whose settlement // fails after the connection is saved still says connected, and a // replay is expired; the person's next snapshot settles the card left // open and queues the one resume turn, and the one after adds nothing. func TestContractAssistantOficinaResumeRecovers(t *testing.T) { o := newOficinaRig(t) tr := &teamRig{o.opsRig} o.asked("Put lunch with Ana in my calendar on Friday.") db := o.inst.DB.Writer() if _, err := db.Exec("CREATE TRIGGER inject_settle BEFORE INSERT ON chat_connect_turns BEGIN SELECT RAISE(ABORT, 'injected'); END"); err != nil { t.Fatal(err) } status, state, code := o.finish() if status != "connected" { t.Fatalf("finish: %q", status) } if n := o.resumes(); n != 0 { t.Fatalf("%d resume turns through the injected failure", n) } if _, err := db.Exec("DROP TRIGGER inject_settle"); err != nil { t.Fatal(err) } if again, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || again != "expired" { t.Fatalf("replayed finish: %q %v", again, err) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND state = ?", wire.CardConnect, wire.CardOpen); n != 1 { t.Fatalf("%d open connect cards before the snapshot", n) } o.connectCards() // the person's next snapshot if n := o.resumes(); n != 1 { t.Fatalf("%d resume turns after the snapshot", n) } if cards := o.connectCards(); len(cards) != 1 || cards[0].State != wire.CardResolved { t.Errorf("cards: %+v", cards) } if u := tr.message(wire.LaneAssistant); u.Kind != wire.TurnTeamUpdate || !strings.Contains(u.Text, resumeMarker) { t.Fatalf("resume frame: %+v", u) } if n := o.resumes(); n != 1 { t.Errorf("%d resume turns after another snapshot", n) } } // TestContractAssistantOficinaResumeOnlyOficina: a connect card for // another provider settles with no turn queued, and a resume turn whose // card is not an Oficina one is granted no write. func TestContractAssistantOficinaResumeOnlyOficina(t *testing.T) { o := newOficinaRig(t) tr := &teamRig{o.opsRig} c := o.inst.Store.Chat() if open, err := c.RaiseConnect(o.ctx, Owner, chat.ConnectCard{Provider: "elsewhere", Question: "Connect", Link: wire.CardLink{Label: "Connect", URL: "https://elsewhere.example.com"}}); err != nil || !open { t.Fatalf("raise: %v %v", open, err) } if err := c.SettleConnect(o.ctx, Owner, "elsewhere"); err != nil { t.Fatal(err) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND name = ? AND state = ?", wire.CardConnect, "elsewhere", wire.CardResolved); n != 1 { t.Fatalf("another provider's card not settled: %d", n) } if n := o.rows("SELECT count(*) FROM chat_turns WHERE kind = ?", wire.TurnTeamUpdate); n != 0 { t.Fatalf("%d turns queued for another provider", n) } o.asked("Put lunch with Ana in my calendar on Friday.") if status, _, _ := o.finish(); status != "connected" { t.Fatalf("finish: %q", status) } u := tr.message(wire.LaneAssistant) if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET name = ? WHERE kind = ? AND name = ?", "elsewhere", wire.CardConnect, "oficina"); err != nil { t.Fatal(err) } tr.in(u.TurnID, func() { if res := o.use("w1", "calendar_create_event", map[string]any{"title": "Lunch with Ana", "start_local": "2026-11-20T13:00"}); !res.IsError || res.Code != "not_asked" { t.Fatalf("write for another provider's card: %+v", res) } }) } // TestContractAssistantOficinaResumeConcurrent: settlements racing on // the same open card queue one turn, one grant record and one dispatch. func TestContractAssistantOficinaResumeConcurrent(t *testing.T) { o := newOficinaRig(t) o.asked("Put lunch with Ana in my calendar on Friday.") c := o.inst.Store.Chat() const n = 8 start := make(chan struct{}) errs := make(chan error, n) var wg sync.WaitGroup for range n { wg.Add(1) go func() { defer wg.Done() <-start errs <- c.SettleConnect(o.ctx, Owner, "oficina") }() } close(start) wg.Wait() close(errs) for err := range errs { if err != nil { t.Errorf("settle: %v", err) } } if got := o.resumes(); got != 1 { t.Errorf("%d resume turns", got) } if got := o.rows("SELECT count(*) FROM chat_connect_turns"); got != 1 { t.Errorf("%d grant records", got) } if got := o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameMessage, "%"+resumeMarker+"%"); got != 1 { t.Errorf("%d resume dispatches", got) } } // TestContractAssistantOficinaResumeStaleEvidence: a lane read that // found the person connected and paused settles nothing on that stale // evidence. Meanwhile card A settles, the person disconnects and card B // is raised; once the read goes on, B stays open with no turn and no // grant, since no connection made after B was raised exists. func TestContractAssistantOficinaResumeStaleEvidence(t *testing.T) { o := newOficinaRig(t) o.asked("Put lunch with Ana in my calendar on Friday.") db := o.inst.DB.Writer() if _, err := db.Exec("CREATE TRIGGER inject_settle BEFORE INSERT ON chat_connect_turns BEGIN SELECT RAISE(ABORT, 'injected'); END"); err != nil { t.Fatal(err) } if status, _, _ := o.finish(); status != "connected" { t.Fatalf("finish: %q", status) } if _, err := db.Exec("DROP TRIGGER inject_settle"); err != nil { t.Fatal(err) } c := o.inst.Store.Chat() var once sync.Once o.inst.Store.SetOficinaCatchUpPause(func() { once.Do(func() { if err := c.SettleConnect(o.ctx, Owner, "oficina"); err != nil { t.Errorf("settle A: %v", err) } if status, _, page := o.browse(http.MethodPost, o.inst.URL+"/oficina/connect/disconnect"); status != http.StatusOK { t.Errorf("disconnect: %d %s", status, page) } if open, err := c.RaiseConnect(o.ctx, Owner, chat.ConnectCard{Provider: "oficina", Question: "Connect your Oficina apps", Link: wire.CardLink{Label: "Connect", URL: o.base.Origin + "/ask/oficina/connect"}}); err != nil || !open { t.Errorf("raise B: %v %v", open, err) } }) }) t.Cleanup(func() { o.inst.Store.SetOficinaCatchUpPause(nil) }) if _, err := o.a.Snapshot(o.ctx); err != nil { t.Fatal(err) } if n := o.resumes(); n != 1 { t.Errorf("%d resume turns, want only A's", n) } if n := o.rows("SELECT count(*) FROM chat_connect_turns"); n != 1 { t.Errorf("%d grant records, want only A's", n) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND state = ?", wire.CardConnect, wire.CardOpen); n != 1 { t.Errorf("%d open connect cards, want B", n) } } // TestContractAssistantOficinaResumeCardAfterConnection: a connect card // raised after the person's connection was last saved is no evidence of // a connect for it: a lane read leaves it open, with no turn. func TestContractAssistantOficinaResumeCardAfterConnection(t *testing.T) { o := newOficinaRig(t) o.asked("Put lunch with Ana in my calendar on Friday.") if status, _, _ := o.finish(); status != "connected" { t.Fatalf("finish: %q", status) } if open, err := o.inst.Store.Chat().RaiseConnect(o.ctx, Owner, chat.ConnectCard{Provider: "oficina", Question: "Connect your Oficina apps", Link: wire.CardLink{Label: "Connect", URL: o.base.Origin + "/ask/oficina/connect"}}); err != nil || !open { t.Fatalf("raise: %v %v", open, err) } if _, err := o.a.Snapshot(o.ctx); err != nil { t.Fatal(err) } if n := o.resumes(); n != 1 { t.Errorf("%d resume turns", n) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND state = ?", wire.CardConnect, wire.CardOpen); n != 1 { t.Errorf("%d open connect cards", n) } }