oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "errors"
5 "net/http"
6 "net/url"
7 "slices"
8 "strings"
9 "sync"
10 "testing"
11
12 "amadan.net/oficina/equipo/internal/equipo/chat"
13 "amadan.net/oficina/equipo/internal/wire"
14)
15
16// resumeMarker is a phrase of the note the Assistant gets once the
17// person has connected their Oficina apps (the instance's noteConnected).
18const resumeMarker = "has just connected their Oficina apps"
19
20// resumes are the person's Assistant turns the instance queued itself
21// after a connect: team_update turns whose note is noteConnected.
22func (o *oficinaRig) resumes() int {
23 o.t.Helper()
24 return o.rows("SELECT count(*) FROM chat_turns WHERE kind = ? AND lane = ? AND note LIKE ?", wire.TurnTeamUpdate, wire.LaneAssistant, "%"+resumeMarker+"%")
25}
26
27// asked raises the connect card from a person turn for words and ends
28// that turn the way a model does when it needs the apps: with a reply.
29func (o *oficinaRig) asked(words string) (turn string) {
30 o.t.Helper()
31 turn = o.begin(words)
32 if res := o.tool("l-"+turn, wire.ToolLook, map[string]any{"query": "calendar"}); !strings.Contains(res.Text, "not connected") {
33 o.t.Fatalf("look: %+v", res)
34 }
35 (&teamRig{o.opsRig}).reply(turn)
36 return turn
37}
38
39// finish connects through Base and returns the finish's status, with
40// the state and code it used.
41func (o *oficinaRig) finish() (status, state, code string) {
42 o.t.Helper()
43 u, err := url.Parse(o.callback(o.base.Origin + "/ask"))
44 if err != nil {
45 o.t.Fatal(err)
46 }
47 state, code = u.Query().Get("oficina_state"), u.Query().Get("oficina_code")
48 status, err = o.a.OficinaFinish(o.ctx, state, code)
49 if err != nil {
50 o.t.Fatalf("finish: %v", err)
51 }
52 return status, state, code
53}
54
55// laneMessages are the Assistant lane's messages as Base reads them,
56// oldest first.
57func (o *oficinaRig) laneMessages() []wire.Message {
58 o.t.Helper()
59 page, err := o.a.Messages(o.ctx, "", 100)
60 if err != nil {
61 o.t.Fatal(err)
62 }
63 items := slices.Clone(page.Items)
64 slices.SortFunc(items, func(a, b wire.Message) int { return a.CreatedAt.Compare(b.CreatedAt) })
65 return items
66}
67
68// TestContractAssistantOficinaResumes (ruling 2026-11-19): once the
69// person connects, the Assistant carries on by itself. One team_update
70// turn is queued in their Assistant lane and dispatched, its note the
71// instance's, never words the person did not type; it may make the
72// write the person asked for; its reply is the only thing new in the
73// lane. A repeated finish, a connect with no card open, and the same
74// card settled again queue nothing more.
75func TestContractAssistantOficinaResumes(t *testing.T) {
76 o := newOficinaRig(t)
77 tr := &teamRig{o.opsRig}
78 words := "Put lunch with Ana in my calendar on Friday."
79 first := o.asked(words)
80 before := o.laneMessages()
81
82 status, state, code := o.finish()
83 if status != "connected" {
84 t.Fatalf("finish: %q", status)
85 }
86 u := tr.message(wire.LaneAssistant)
87 if u.Kind != wire.TurnTeamUpdate || u.TurnID == first || len(u.PersonText) != 0 || !strings.Contains(u.Text, resumeMarker) {
88 t.Fatalf("resume frame: %+v", u)
89 }
90 if !slices.ContainsFunc(u.Tail, func(m wire.TailMessage) bool { return m.Role == wire.RolePerson && m.Text == words }) {
91 t.Errorf("the request is not in the resume's tail: %+v", u.Tail)
92 }
93 if n := o.resumes(); n != 1 {
94 t.Fatalf("%d resume turns", n)
95 }
96 // The resume answers the person's own request: the write they asked
97 // for goes through.
98 tr.in(u.TurnID, func() {
99 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" {
100 t.Fatalf("write in the resume: %+v", res)
101 }
102 })
103 reply := "Lunch with Ana is in your calendar for Friday."
104 if err := o.runner.Send(o.ctx, "r-resume", wire.FrameReply, wire.Reply{TurnID: u.TurnID, Attempt: 1, Text: reply}); err != nil {
105 t.Fatal(err)
106 }
107 o.until("resume replied", func() bool {
108 return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND state = ?", u.TurnID, wire.TurnReplied) == 1
109 })
110 after := o.laneMessages()
111 if len(after) != len(before)+1 {
112 t.Fatalf("lane before %+v, after %+v", before, after)
113 }
114 if last := after[len(after)-1]; last.Role != wire.RoleAssistant || last.Text != reply || last.TurnID != u.TurnID {
115 t.Errorf("new in the lane: %+v", last)
116 }
117 if n := len(slices.DeleteFunc(after, func(m wire.Message) bool { return m.Role != wire.RolePerson })); n != 1 {
118 t.Errorf("%d person messages in the lane", n)
119 }
120
121 // A repeated finish: the state is used up, nothing more is queued.
122 if again, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || again != "expired" {
123 t.Errorf("replayed finish: %q %v", again, err)
124 }
125 // Connecting again with no card open asks for nothing.
126 if again, _, _ := o.finish(); again != "connected" {
127 t.Errorf("second connect: %q", again)
128 }
129 // Two finishes that both found the card open settle it twice; the
130 // card's key lets only the first queue a turn.
131 card := o.connectCards()[0]
132 if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET state = ? WHERE id = ?", wire.CardOpen, card.ID); err != nil {
133 t.Fatal(err)
134 }
135 if err := o.inst.Store.Chat().SettleConnect(o.ctx, Owner, "oficina"); err != nil {
136 t.Fatalf("settled again: %v", err)
137 }
138 if n := o.resumes(); n != 1 {
139 t.Errorf("%d resume turns after replays", n)
140 }
141 if n := o.rows("SELECT count(*) FROM chat_turns WHERE lane = ? AND state IN (?, ?, ?)", wire.LaneAssistant, wire.TurnQueued, wire.TurnRunning, wire.TurnWaiting); n != 0 {
142 t.Errorf("%d Assistant turns in flight after replays", n)
143 }
144}
145
146// TestContractAssistantOficinaResumeWaits: a connect while the person's
147// Assistant turn still runs queues the resume behind it, as notes wait;
148// it is dispatched once that turn ends.
149func TestContractAssistantOficinaResumeWaits(t *testing.T) {
150 o := newOficinaRig(t)
151 tr := &teamRig{o.opsRig}
152 first := o.begin("Put lunch with Ana in my calendar on Friday.")
153 o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"})
154 if status, _, _ := o.finish(); status != "connected" {
155 t.Fatalf("finish: %q", status)
156 }
157 if n := o.resumes(); n != 1 {
158 t.Fatalf("%d resume turns", n)
159 }
160 if n := o.rows("SELECT count(*) FROM chat_turns WHERE kind = ? AND dispatched = ?", wire.TurnTeamUpdate, true); n != 0 {
161 t.Fatalf("the resume went while the person's turn ran")
162 }
163 tr.reply(first)
164 if u := tr.message(wire.LaneAssistant); u.Kind != wire.TurnTeamUpdate || !strings.Contains(u.Text, resumeMarker) {
165 t.Fatalf("after the turn ended: %+v", u)
166 }
167}
168
169// TestContractAssistantOficinaNoResumeUnlessConnected: a consent
170// refused, a finish connect could not complete and one that expired
171// queue nothing and leave the card open; the connect that works then
172// queues the one turn.
173func TestContractAssistantOficinaNoResumeUnlessConnected(t *testing.T) {
174 o := newOficinaRig(t)
175 ana := o.other("ana@example.com")
176 ana.connect(o.base.Mint())
177 o.asked("Put lunch with Ana in my calendar on Friday.")
178
179 o.fake.Deny = true
180 if back := o.callback(o.base.Origin + "/ask"); back != o.base.Origin+"/ask?oficina=denied" {
181 t.Fatalf("denied: %q", back)
182 }
183 o.fake.Down = true
184 if status, _, _ := o.finish(); status != "unavailable" {
185 t.Fatalf("connect down: %q", status)
186 }
187 o.fake.Down = false
188 state, code := o.handBack(o.base.Origin + "/ask")
189 var s *ErrStatus
190 if _, err := ana.a.OficinaFinish(o.ctx, state, code); !errors.As(err, &s) || s.Status != http.StatusForbidden {
191 t.Fatalf("another person's finish: %v", err)
192 }
193 if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "expired" {
194 t.Fatalf("expired: %q %v", status, err)
195 }
196 if n := o.resumes(); n != 0 {
197 t.Fatalf("%d resume turns without a connection", n)
198 }
199 if cards := o.connectCards(); len(cards) != 1 || cards[0].State != wire.CardOpen {
200 t.Fatalf("cards: %+v", cards)
201 }
202
203 if status, _, _ := o.finish(); status != "connected" {
204 t.Fatalf("finish: %q", status)
205 }
206 if n := o.resumes(); n != 1 {
207 t.Errorf("%d resume turns once connected", n)
208 }
209}
210
211// TestContractAssistantOficinaResumeRecovers: a finish whose settlement
212// fails after the connection is saved still says connected, and a
213// replay is expired; the person's next snapshot settles the card left
214// open and queues the one resume turn, and the one after adds nothing.
215func TestContractAssistantOficinaResumeRecovers(t *testing.T) {
216 o := newOficinaRig(t)
217 tr := &teamRig{o.opsRig}
218 o.asked("Put lunch with Ana in my calendar on Friday.")
219 db := o.inst.DB.Writer()
220 if _, err := db.Exec("CREATE TRIGGER inject_settle BEFORE INSERT ON chat_connect_turns BEGIN SELECT RAISE(ABORT, 'injected'); END"); err != nil {
221 t.Fatal(err)
222 }
223 status, state, code := o.finish()
224 if status != "connected" {
225 t.Fatalf("finish: %q", status)
226 }
227 if n := o.resumes(); n != 0 {
228 t.Fatalf("%d resume turns through the injected failure", n)
229 }
230 if _, err := db.Exec("DROP TRIGGER inject_settle"); err != nil {
231 t.Fatal(err)
232 }
233 if again, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || again != "expired" {
234 t.Fatalf("replayed finish: %q %v", again, err)
235 }
236 if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND state = ?", wire.CardConnect, wire.CardOpen); n != 1 {
237 t.Fatalf("%d open connect cards before the snapshot", n)
238 }
239 o.connectCards() // the person's next snapshot
240 if n := o.resumes(); n != 1 {
241 t.Fatalf("%d resume turns after the snapshot", n)
242 }
243 if cards := o.connectCards(); len(cards) != 1 || cards[0].State != wire.CardResolved {
244 t.Errorf("cards: %+v", cards)
245 }
246 if u := tr.message(wire.LaneAssistant); u.Kind != wire.TurnTeamUpdate || !strings.Contains(u.Text, resumeMarker) {
247 t.Fatalf("resume frame: %+v", u)
248 }
249 if n := o.resumes(); n != 1 {
250 t.Errorf("%d resume turns after another snapshot", n)
251 }
252}
253
254// TestContractAssistantOficinaResumeOnlyOficina: a connect card for
255// another provider settles with no turn queued, and a resume turn whose
256// card is not an Oficina one is granted no write.
257func TestContractAssistantOficinaResumeOnlyOficina(t *testing.T) {
258 o := newOficinaRig(t)
259 tr := &teamRig{o.opsRig}
260 c := o.inst.Store.Chat()
261 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 {
262 t.Fatalf("raise: %v %v", open, err)
263 }
264 if err := c.SettleConnect(o.ctx, Owner, "elsewhere"); err != nil {
265 t.Fatal(err)
266 }
267 if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND name = ? AND state = ?", wire.CardConnect, "elsewhere", wire.CardResolved); n != 1 {
268 t.Fatalf("another provider's card not settled: %d", n)
269 }
270 if n := o.rows("SELECT count(*) FROM chat_turns WHERE kind = ?", wire.TurnTeamUpdate); n != 0 {
271 t.Fatalf("%d turns queued for another provider", n)
272 }
273
274 o.asked("Put lunch with Ana in my calendar on Friday.")
275 if status, _, _ := o.finish(); status != "connected" {
276 t.Fatalf("finish: %q", status)
277 }
278 u := tr.message(wire.LaneAssistant)
279 if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET name = ? WHERE kind = ? AND name = ?", "elsewhere", wire.CardConnect, "oficina"); err != nil {
280 t.Fatal(err)
281 }
282 tr.in(u.TurnID, func() {
283 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" {
284 t.Fatalf("write for another provider's card: %+v", res)
285 }
286 })
287}
288
289// TestContractAssistantOficinaResumeConcurrent: settlements racing on
290// the same open card queue one turn, one grant record and one dispatch.
291func TestContractAssistantOficinaResumeConcurrent(t *testing.T) {
292 o := newOficinaRig(t)
293 o.asked("Put lunch with Ana in my calendar on Friday.")
294 c := o.inst.Store.Chat()
295 const n = 8
296 start := make(chan struct{})
297 errs := make(chan error, n)
298 var wg sync.WaitGroup
299 for range n {
300 wg.Add(1)
301 go func() {
302 defer wg.Done()
303 <-start
304 errs <- c.SettleConnect(o.ctx, Owner, "oficina")
305 }()
306 }
307 close(start)
308 wg.Wait()
309 close(errs)
310 for err := range errs {
311 if err != nil {
312 t.Errorf("settle: %v", err)
313 }
314 }
315 if got := o.resumes(); got != 1 {
316 t.Errorf("%d resume turns", got)
317 }
318 if got := o.rows("SELECT count(*) FROM chat_connect_turns"); got != 1 {
319 t.Errorf("%d grant records", got)
320 }
321 if got := o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameMessage, "%"+resumeMarker+"%"); got != 1 {
322 t.Errorf("%d resume dispatches", got)
323 }
324}
325
326// TestContractAssistantOficinaResumeStaleEvidence: a lane read that
327// found the person connected and paused settles nothing on that stale
328// evidence. Meanwhile card A settles, the person disconnects and card B
329// is raised; once the read goes on, B stays open with no turn and no
330// grant, since no connection made after B was raised exists.
331func TestContractAssistantOficinaResumeStaleEvidence(t *testing.T) {
332 o := newOficinaRig(t)
333 o.asked("Put lunch with Ana in my calendar on Friday.")
334 db := o.inst.DB.Writer()
335 if _, err := db.Exec("CREATE TRIGGER inject_settle BEFORE INSERT ON chat_connect_turns BEGIN SELECT RAISE(ABORT, 'injected'); END"); err != nil {
336 t.Fatal(err)
337 }
338 if status, _, _ := o.finish(); status != "connected" {
339 t.Fatalf("finish: %q", status)
340 }
341 if _, err := db.Exec("DROP TRIGGER inject_settle"); err != nil {
342 t.Fatal(err)
343 }
344 c := o.inst.Store.Chat()
345 var once sync.Once
346 o.inst.Store.SetOficinaCatchUpPause(func() {
347 once.Do(func() {
348 if err := c.SettleConnect(o.ctx, Owner, "oficina"); err != nil {
349 t.Errorf("settle A: %v", err)
350 }
351 if status, _, page := o.browse(http.MethodPost, o.inst.URL+"/oficina/connect/disconnect"); status != http.StatusOK {
352 t.Errorf("disconnect: %d %s", status, page)
353 }
354 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 {
355 t.Errorf("raise B: %v %v", open, err)
356 }
357 })
358 })
359 t.Cleanup(func() { o.inst.Store.SetOficinaCatchUpPause(nil) })
360 if _, err := o.a.Snapshot(o.ctx); err != nil {
361 t.Fatal(err)
362 }
363 if n := o.resumes(); n != 1 {
364 t.Errorf("%d resume turns, want only A's", n)
365 }
366 if n := o.rows("SELECT count(*) FROM chat_connect_turns"); n != 1 {
367 t.Errorf("%d grant records, want only A's", n)
368 }
369 if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND state = ?", wire.CardConnect, wire.CardOpen); n != 1 {
370 t.Errorf("%d open connect cards, want B", n)
371 }
372}
373
374// TestContractAssistantOficinaResumeCardAfterConnection: a connect card
375// raised after the person's connection was last saved is no evidence of
376// a connect for it: a lane read leaves it open, with no turn.
377func TestContractAssistantOficinaResumeCardAfterConnection(t *testing.T) {
378 o := newOficinaRig(t)
379 o.asked("Put lunch with Ana in my calendar on Friday.")
380 if status, _, _ := o.finish(); status != "connected" {
381 t.Fatalf("finish: %q", status)
382 }
383 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 {
384 t.Fatalf("raise: %v %v", open, err)
385 }
386 if _, err := o.a.Snapshot(o.ctx); err != nil {
387 t.Fatal(err)
388 }
389 if n := o.resumes(); n != 1 {
390 t.Errorf("%d resume turns", n)
391 }
392 if n := o.rows("SELECT count(*) FROM chat_cards WHERE kind = ? AND state = ?", wire.CardConnect, wire.CardOpen); n != 1 {
393 t.Errorf("%d open connect cards", n)
394 }
395}
396