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 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "image"
11 "image/color"
12 "image/png"
13 "os"
14 "path/filepath"
15 "slices"
16 "sort"
17 "strconv"
18 "strings"
19 "testing"
20 "time"
21
22 "amadan.net/oficina/equipo/internal/equipo"
23 "amadan.net/oficina/equipo/internal/runner/designstep"
24 "amadan.net/oficina/equipo/internal/runner/render"
25 "amadan.net/oficina/equipo/internal/runner/renderpage"
26 "amadan.net/oficina/equipo/internal/specialist"
27 "amadan.net/oficina/equipo/internal/wire"
28)
29
30// Design end to end (spec 2026-11-28-dynamic-specialists.md; slice 1
31// plan task 20). The instance and its runner link are real; the
32// coordinator is this test's tool calls; the Design step's runner side is
33// the runner's own render_page Tool and Design tools (renderpage,
34// designstep) with a fake browser behind the real renderer health check,
35// so no Chromium runs. Render checks and render_file chunks go over the
36// runner link.
37
38const patrixRepo = "amadan.net/oficina/patrix"
39
40// overhaulWords is the person's request that leads to Design.
41const overhaulWords = "Patrix needs a design overhaul. Show me a couple of directions for the home page before anything is built."
42
43// rendererHealth is the runner's renderer check with its tree verified
44// and its fixture page rendered by fakes: fixture is the fixture's end.
45func rendererHealth(t *testing.T, fixture error) *render.Health {
46 t.Helper()
47 h := &render.Health{Config: render.LaunchConfig{Bwrap: "/usr/bin/bwrap", Binary: "/runner/equipo-runner", Tree: t.TempDir(), Pin: "pin"}, Scratch: t.TempDir(),
48 Verify: func(string, string) error { return nil },
49 Fixture: func(context.Context, render.LaunchConfig, string) error { return fixture }}
50 h.Ready(context.Background())
51 return h
52}
53
54// designHello is the primary's hello at protocol with Patrix on its list,
55// the owner's Claude subscription, and the renderer's reported health.
56func (r *toolRig) designHello(protocol int, h *render.Health) wire.Hello {
57 hello := primaryAt(toolHello(r.runner.Welcome.Generation), protocol)
58 hello.Repos = append(hello.Repos, patrixRepo)
59 hello.Catalog = append(hello.Catalog, wire.RepoInfo{Repo: patrixRepo, DefaultBranch: "main", Summary: "Patrix is a parking app.", Names: []string{"patrix", "Patrix"}, Hints: []string{"web"}, HeadSHA: baseX, HeadSubject: "Start"})
60 hello.Capabilities.Tools = &wire.ToolHealth{Scanner: wire.ToolHealthy, Renderer: h.Report(context.Background())}
61 return hello
62}
63
64// designOn says the design hello and adds Patrix as the team's project.
65func (r *toolRig) designOn(h *render.Health) {
66 r.t.Helper()
67 if err := r.runner.Send(r.ctx, "h-design", wire.FrameHello, r.designHello(wire.ProtocolCurrent, h)); err != nil {
68 r.t.Fatal(err)
69 }
70 if refused := r.lease(r.runner, "h-design-ping", wire.LeaseCheck{}); refused != "" {
71 r.t.Fatalf("ping refused %q", refused)
72 }
73 if res := r.call("d-add", wire.ToolAddProject, map[string]string{"repo": "oficina/patrix"}); res.IsError {
74 r.t.Fatalf("add Patrix %+v", res)
75 }
76}
77
78// redialAt reconnects the primary at protocol with h's renderer health.
79func (r *toolRig) redialAt(protocol int, h *render.Health) {
80 r.t.Helper()
81 f, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, r.designHello(protocol, h))
82 if err != nil {
83 r.t.Fatal(err)
84 }
85 r.t.Cleanup(f.Close)
86 r.runner, r.held = f, nil
87 r.lease(f, "h-redial-ping", wire.LeaseCheck{})
88}
89
90func designProposal() map[string]any {
91 return map[string]any{"profile": specialist.ProfileDesign, "name": "Design", "brief": "Overhaul Patrix's look: calm colours, larger type.", "capabilities": []string{specialist.CapabilityBranchEdit, specialist.CapabilityPageRender}, "tools": []string{specialist.ToolRenderPage, specialist.ToolSubmitCandidate, specialist.ToolAskPerson}, "project": "patrix"}
92}
93
94// proposeDesign has the coordinator propose Design for Patrix, end its
95// turn, and returns the open card.
96func (r *toolRig) proposeDesign(key string) wire.Card {
97 r.t.Helper()
98 if res := r.call(key, wire.ToolProposeSpecialist, designProposal()); res.IsError || res.Code != "proposed" {
99 r.t.Fatalf("propose %+v", res)
100 }
101 card := r.specialistCard(wire.CardOpen)
102 if err := r.runner.Send(r.ctx, "r-reply-"+r.turn, wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Design would do this well. Add it?"}); err != nil {
103 r.t.Fatal(err)
104 }
105 prev := r.turn
106 r.wait("replied", func(c *Conversation) bool { return c.Turns[prev].State == wire.TurnReplied })
107 return card
108}
109
110// continuation takes the specialist_added turn the Add queued.
111func (r *toolRig) continuation() *wire.MessageCommand {
112 r.t.Helper()
113 _, body := r.expect(wire.FrameMessage)
114 m := body.(*wire.MessageCommand)
115 r.wait("continuation running", func(c *Conversation) bool { return c.Turns[m.TurnID].State == wire.TurnRunning })
116 r.turn = m.TurnID
117 return m
118}
119
120// designAdded taps Add on card and has the continuation record the
121// exploration and start it with Design; it returns the specialist and
122// the task.
123func (r *toolRig) designAdded(card wire.Card) (wire.Specialist, string) {
124 r.t.Helper()
125 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAdd, card.Revision); err != nil {
126 r.t.Fatal(err)
127 }
128 m := r.continuation()
129 sp := card.Specialist
130 if m.Kind != wire.TurnSpecialistAdded || len(m.PersonText) != 0 || !strings.Contains(m.Text, strconv.Quote(overhaulWords)) || !strings.Contains(m.Text, sp.ID) {
131 r.t.Fatalf("continuation %+v", m)
132 }
133 id := taskID(r.t, r.call("d-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/patrix", "title": "Patrix design overhaul", "brief": "Two directions for the home page.", "kind": wire.KindExplore}))
134 if res := r.call("d-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Show two directions.", "specialist": sp.ID}); res.IsError {
135 r.t.Fatalf("start %+v", res)
136 }
137 if err := r.runner.Send(r.ctx, "r-reply-"+m.TurnID, wire.FrameReply, wire.Reply{TurnID: m.TurnID, Attempt: 1, Text: "Design is on it."}); err != nil {
138 r.t.Fatal(err)
139 }
140 list, err := r.client.Specialists(r.ctx)
141 if err != nil || len(list.Items) != 1 || list.Items[0].State != wire.SpecialistActive {
142 r.t.Fatalf("specialists %+v %v", list, err)
143 }
144 return list.Items[0], id
145}
146
147// designHand is the runner side of one Design attempt: the fake model's
148// workspace, the runner's render_page Tool over a fake browser, and the
149// step's Design tools, whose render check is a lease over the link.
150type designHand struct {
151 r *toolRig
152 d *wire.DispatchCommand
153 work, dir, scratch string
154 page *renderpage.Tool
155 at *designstep.Attempt
156 usage renderpage.Usage
157 checks, browserRuns int
158}
159
160func (r *toolRig) designHand(d *wire.DispatchCommand, h *render.Health) *designHand {
161 root := r.t.TempDir()
162 x := &designHand{r: r, d: d, work: filepath.Join(root, "work"), dir: filepath.Join(root, "render"), scratch: filepath.Join(root, "render-work")}
163 x.page = &renderpage.Tool{Renderer: h, Config: h.Config, Render: x.browser}
164 x.at = &designstep.Attempt{Dir: x.dir, Confirm: x.confirm, Render: func(ctx context.Context, raw json.RawMessage) (string, []renderpage.Capture, error) {
165 return x.page.Call(ctx, x, raw)
166 }}
167 return x
168}
169
170func (x *designHand) confirm(context.Context) error {
171 x.checks++
172 if why := x.r.lease(x.r.runner, "ds-render-"+itoa(x.checks), wire.LeaseCheck{StepID: x.d.StepID, Attempt: x.d.Attempt, Purpose: wire.LeasePurposeRender}); why != "" {
173 return fmt.Errorf("%w: %s", designstep.ErrRenderRefused, why)
174 }
175 return nil
176}
177
178func (x *designHand) Dir() string { return x.dir }
179func (x *designHand) Scratch() string { return x.scratch }
180
181// Audit keeps nothing: the runner's state keeps the records (thin).
182func (x *designHand) Audit(context.Context, wire.RenderAudit) {}
183func (x *designHand) Accept(_ context.Context, captures int) (renderpage.Usage, error) {
184 x.usage.Calls++
185 x.usage.Captures += captures
186 return x.usage, nil
187}
188
189// Site exports the work tree's release/preview.json output; its digest
190// is over every exported file.
191func (x *designHand) Site(_ context.Context, tree, stage string) (string, error) {
192 if tree != renderpage.TreeWork {
193 return "", renderpage.Refuse(renderpage.CodeNoSite, "no base site")
194 }
195 var cfg struct{ Output string }
196 raw, err := os.ReadFile(filepath.Join(x.work, "release", "preview.json"))
197 if err != nil || json.Unmarshal(raw, &cfg) != nil {
198 return "", renderpage.Refuse(renderpage.CodeNoSite, "no preview config")
199 }
200 sum, from := sha256.New(), filepath.Join(x.work, cfg.Output)
201 var names []string
202 err = filepath.WalkDir(from, func(p string, e os.DirEntry, err error) error {
203 if err == nil && !e.IsDir() {
204 names = append(names, p)
205 }
206 return err
207 })
208 sort.Strings(names)
209 for _, p := range names {
210 rel, _ := filepath.Rel(from, p)
211 b, _ := os.ReadFile(p)
212 os.MkdirAll(filepath.Dir(filepath.Join(stage, rel)), 0o700)
213 if err == nil {
214 err = os.WriteFile(filepath.Join(stage, rel), b, 0o600)
215 }
216 fmt.Fprintf(sum, "%s\x00%d\x00%s", rel, len(b), b)
217 }
218 return hex.EncodeToString(sum.Sum(nil)), err
219}
220
221// browser stands in for Chromium: each page is its viewport's size in
222// a colour taken from the page's own file, so options differ.
223func (x *designHand) browser(_ context.Context, cfg render.LaunchConfig, out string, pages []render.Page) (*render.Report, error) {
224 x.browserRuns++
225 rep := &render.Report{Schema: render.ReportSchema}
226 for i, p := range pages {
227 html, err := os.ReadFile(filepath.Join(cfg.Site, p.Path, "index.html"))
228 if err != nil {
229 return nil, err
230 }
231 w, h, _ := p.Viewport.Size()
232 img, c := image.NewNRGBA(image.Rect(0, 0, w, h)), sha256.Sum256(html)
233 for y := range h {
234 for x := range w {
235 img.Set(x, y, color.NRGBA{c[0], c[1], c[2], 0xff})
236 }
237 }
238 name := "page-" + itoa(i+1) + ".png"
239 f, err := os.Create(filepath.Join(out, name))
240 if err != nil {
241 return nil, err
242 }
243 err = errors.Join(png.Encode(f, img), f.Close())
244 if err != nil {
245 return nil, err
246 }
247 rep.Pages = append(rep.Pages, render.PageReport{Path: p.Path, Viewport: p.Viewport, Width: w, Height: h, FullPage: p.FullPage, Capture: name, CaptureWidth: w, CaptureHeight: h, Title: "Patrix"})
248 }
249 return rep, nil
250}
251
252// mockups is the fake model writing its two options under
253// mockups/<task>/ and release/preview.json naming them.
254func (x *designHand) mockups() {
255 x.r.t.Helper()
256 files := map[string]string{
257 "release/preview.json": `{"output": "mockups/` + x.d.TaskID + `"}`,
258 "mockups/" + x.d.TaskID + "/calm/index.html": "<h1>Patrix</h1><p>Calm: soft blue, larger type.</p>",
259 "mockups/" + x.d.TaskID + "/bold/index.html": "<h1>Patrix</h1><p>Bold: black and yellow.</p>",
260 }
261 for name, body := range files {
262 p := filepath.Join(x.work, name)
263 if err := errors.Join(os.MkdirAll(filepath.Dir(p), 0o700), os.WriteFile(p, []byte(body), 0o600)); err != nil {
264 x.r.t.Fatal(err)
265 }
266 }
267}
268
269// tool is the fake model calling one of the step's tools.
270func (x *designHand) tool(name, args string) (string, bool) {
271 return x.at.Call(x.r.ctx, name, "", json.RawMessage(args))
272}
273
274const renderBoth = `{"tree": "work", "pages": [{"path": "/calm/", "viewport": "desktop"}, {"path": "/calm/", "viewport": "phone"}, {"path": "/bold/", "viewport": "desktop"}]}`
275
276// uploads sends the named captures over the link as render_file chunks.
277func (x *designHand) uploads(key string) {
278 x.r.t.Helper()
279 files, err := designstep.Files(x.dir, x.d.TaskID, x.d.StepID, x.d.Attempt, x.at.Options())
280 if err != nil {
281 x.r.t.Fatal(err)
282 }
283 for i, chunks := range files {
284 for j, c := range chunks {
285 x.r.ack(key+"-"+itoa(i)+"-"+itoa(j), wire.FrameRenderFile, c)
286 }
287 }
288}
289
290// ack sends one durable frame and waits for its ack, holding the rest.
291func (r *toolRig) ack(id, kind string, body any) {
292 r.t.Helper()
293 if err := r.runner.Send(r.ctx, id, kind, body); err != nil {
294 r.t.Fatal(err)
295 }
296 for {
297 f, b, err := r.runner.Next(r.ctx)
298 if err != nil {
299 r.t.Fatal(err)
300 }
301 if a, ok := b.(*wire.Ack); ok && a.ID == id {
302 return
303 }
304 if f.Type != wire.FrameAck {
305 r.held = append(r.held, heldFrame{f, b, r.runner.Received[len(r.runner.Received)-1]})
306 }
307 }
308}
309
310// designStarted takes Design's dispatch, checks its binding, and has the
311// runner start it.
312func (r *toolRig) designStarted(sp wire.Specialist, id string) *wire.DispatchCommand {
313 r.t.Helper()
314 d := r.nextDispatch()
315 design, _ := specialist.Lookup(specialist.ProfileDesign)
316 if d.TaskID != id || d.Specialist != wire.SpecialistEngineering || d.SpecialistID != sp.ID || d.SpecialistRevision != sp.Revision || d.SpecialistProject != r.patrixID() || d.Profile != specialist.ProfileDesign || !slices.Equal(d.Capabilities, design.Capabilities) || !d.Explore || d.SpecialistBrief != designProposal()["brief"] || !wire.ValidSpecialistBinding(d) || d.Repo != patrixRepo {
317 r.t.Fatalf("Design's dispatch %+v", d)
318 }
319 if why := r.lease(r.runner, "ds-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); why != "" {
320 r.t.Fatalf("start refused %q", why)
321 }
322 r.step("ds-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: baseX, Family: "claude", Account: "claude-a"})
323 return d
324}
325
326func (r *toolRig) makerOf(id string) string {
327 r.t.Helper()
328 var maker string
329 if err := r.inst.DB.Writer().QueryRow("SELECT maker_specialist_id FROM chat_tasks WHERE id = ?", id).Scan(&maker); err != nil {
330 r.t.Fatal(err)
331 }
332 return maker
333}
334
335// TestContractDesignFinishLine is slice 1's Design finish line: the
336// person asks for a Patrix design overhaul on a primary at 38 whose
337// renderer is ok and which holds their Claude subscription; the
338// coordinator proposes design-v1 for Patrix; the owner's Add queues the
339// continuation, which records an exploration and starts it with Design;
340// the dispatch carries the binding; the model renders through the
341// instance's render check, writes its options under mockups/<task>/ and
342// submits; the captures go up as render_file chunks and the final
343// report keeps them; the task page and the direction card show them;
344// Build needs a note and, with one, makes the change task with Design
345// as its maker and the note quoted as the person's own words.
346func TestContractDesignFinishLine(t *testing.T) {
347 r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords)
348 health := rendererHealth(t, nil)
349 if got := health.Report(r.ctx); got != wire.ToolHealthy {
350 t.Fatalf("renderer %q", got)
351 }
352 r.designOn(health)
353 card := r.proposeDesign("d-propose")
354 if card.Question != "Add Design to your team for Patrix?" || card.Specialist.Profile != specialist.ProfileDesign {
355 t.Fatalf("card %+v %+v", card, card.Specialist)
356 }
357 sp, id := r.designAdded(card)
358 if sp.Project != r.patrixID() || r.makerOf(id) != sp.ID || r.task(id).Kind != wire.KindExplore {
359 t.Fatalf("maker %q", r.makerOf(id))
360 }
361 d := r.designStarted(sp, id)
362
363 x := r.designHand(d, health)
364 x.mockups()
365 if text, failed := x.tool(designstep.ToolRenderPage, renderBoth); failed || !strings.Contains(text, "/render/1-work-3.png") {
366 t.Fatalf("render_page %v %s", failed, text)
367 }
368 if x.checks != 1 || x.browserRuns != 1 {
369 t.Fatalf("%d render checks, %d browser runs", x.checks, x.browserRuns)
370 }
371 if text, failed := x.tool(designstep.ToolAskPerson, `{"question": "Blue or yellow?"}`); failed || text != designstep.AskText {
372 t.Fatalf("ask_person %s", text)
373 }
374 if text, failed := x.tool(designstep.ToolSubmitCandidate, `{"options": [{"name": "Calm", "captures": ["1-work-1.png", "1-work-2.png"]}, {"name": "Bold", "captures": ["1-work-3.png"]}]}`); failed {
375 t.Fatalf("submit %s", text)
376 }
377 x.uploads("ds-file")
378 if r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ? AND complete = 1 AND kept = 0", d.StepID) != 3 {
379 t.Fatal("the captures are not staged")
380 }
381 if why := r.lease(r.runner, "ds-push", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); why != "" {
382 t.Fatalf("pre-push refused %q", why)
383 }
384 r.step("ds-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, BaseSHA: baseX, CandidateSHA: candX, Pushed: true, Termination: true, Family: "claude", Account: "claude-a", Summary: "Two directions.", Options: x.at.Options()})
385
386 // Kept, byte for byte, in the report's order.
387 k := r.task(id)
388 eng := stepsOf(k, wire.SpecialistEngineering)[0]
389 if eng.Design == nil || len(eng.Design.Options) != 2 || eng.Design.Options[0].Name != "Calm" || len(eng.Design.Options[0].Captures) != 2 || eng.Design.Options[1].Name != "Bold" || len(eng.Design.Options[1].Captures) != 1 {
390 t.Fatalf("kept %+v", eng.Design)
391 }
392 for _, o := range eng.Design.Options {
393 for _, c := range o.Captures {
394 want, err := os.ReadFile(filepath.Join(x.dir, c.CaptureID))
395 got, _ := r.fetch(r.client.Token, "/api/v1/tasks/"+id+"/files/"+c.ID, 200)
396 if err != nil || string(got) != string(want) || c.Width < 1 {
397 t.Fatalf("capture %+v: %d bytes, want %d", c, len(got), len(want))
398 }
399 }
400 }
401 r.expect(wire.FrameWatchMerge)
402 r.approved("ds", candX, true)
403 dir := r.directionCard(id)
404 if k := r.task(id); k.Direction == nil || len(k.Direction.Options) != 2 || !k.Direction.NoteNeeded {
405 t.Fatalf("direction %+v", k.Direction)
406 }
407 calm := eng.Design.Options[0].Captures[0].ID
408 page := r.get(r.inst.SessionFor(t, Owner), "/tasks/"+id, 200)
409 conv := r.get(r.inst.SessionFor(t, Owner), "/conversation", 200)
410 for _, want := range []string{"Option 1: Calm", "Option 2: Bold", `/tasks/` + id + `/files/` + calm} {
411 if !strings.Contains(page, want) || !strings.Contains(conv, want) {
412 t.Fatalf("the task page or the direction card lacks %q", want)
413 }
414 }
415 if !strings.Contains(conv, "data-direction-build") {
416 t.Fatal("the direction card's Build asks for no note")
417 }
418
419 // Build with two options needs the person's note.
420 _, err := r.client.Answer(r.ctx, dir.ID, wire.ChoiceBuild, dir.Revision)
421 var conflict wire.CardConflict
422 if st, ok := err.(*ErrStatus); !ok || st.Status != 409 || json.Unmarshal(st.Body, &conflict) != nil || conflict.Code != wire.ConflictDirectionNote {
423 t.Fatalf("Build without a note: %v", err)
424 }
425 note := "Build Calm, with Bold's yellow button."
426 if _, err := r.client.AnswerNote(r.ctx, dir.ID, wire.ChoiceBuild, note, dir.Revision); err != nil {
427 t.Fatal(err)
428 }
429 k = r.task(id)
430 if k.BuiltAs == nil {
431 t.Fatalf("built %+v", k)
432 }
433 built := r.task(k.BuiltAs.ID)
434 if built.Kind == wire.KindExplore || !strings.HasSuffix(built.Brief, "said which option to build in their own words: "+wire.QuotedData(note)) || r.makerOf(built.ID) != sp.ID {
435 t.Fatalf("the change task %q %q maker %q", built.Kind, built.Brief, r.makerOf(built.ID))
436 }
437 if b := r.nextDispatch(); b.TaskID != built.ID || b.SpecialistID != sp.ID || b.Explore || !strings.Contains(b.Brief, wire.QuotedData(note)) {
438 t.Fatalf("the change task's dispatch %+v", b)
439 }
440}
441
442// patrixID is the Patrix project's id.
443func (r *toolRig) patrixID() string {
444 r.t.Helper()
445 list, err := r.client.Projects(r.ctx)
446 if err != nil {
447 r.t.Fatal(err)
448 }
449 for _, p := range list.Items {
450 if p.Repo == patrixRepo {
451 return p.ID
452 }
453 }
454 r.t.Fatal("no Patrix project")
455 return ""
456}
457
458// TestContractDesignRevokeMidStep: an owner revokes Design between two
459// renders. The runner gets cancel_step; the next render check is refused
460// over the link, so render_page stops for the attempt and the browser
461// never runs again; the pre-push check is refused; the captures it
462// uploads are never kept; and once the attempt reports its end, the
463// recovery card hands the task to Engineering, unbound.
464func TestContractDesignRevokeMidStep(t *testing.T) {
465 r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords)
466 health := rendererHealth(t, nil)
467 r.designOn(health)
468 sp, id := r.designAdded(r.proposeDesign("d-propose"))
469 d := r.designStarted(sp, id)
470 x := r.designHand(d, health)
471 x.mockups()
472 if _, failed := x.tool(designstep.ToolRenderPage, renderBoth); failed {
473 t.Fatal("the first render")
474 }
475 if _, err := r.client.RevokeSpecialist(r.ctx, sp.ID, sp.Revision); err != nil {
476 t.Fatal(err)
477 }
478 if _, body := r.expect(wire.FrameCancelStep); body.(*wire.CancelStepCommand).StepID != d.StepID {
479 t.Fatalf("cancel %+v", body)
480 }
481 for i := range 2 {
482 if text, failed := x.tool(designstep.ToolRenderPage, renderBoth); !failed || text != designstep.RenderRefusedText {
483 t.Fatalf("render %d after the revoke: %s", i+2, text)
484 }
485 }
486 if x.checks != 2 || x.browserRuns != 1 {
487 t.Fatalf("%d render checks, %d browser runs", x.checks, x.browserRuns)
488 }
489 if text, failed := x.tool(designstep.ToolSubmitCandidate, `{"options": [{"name": "Calm", "captures": ["1-work-1.png"]}]}`); failed {
490 t.Fatalf("submit %s", text)
491 }
492 x.uploads("rv-file")
493 if why := r.lease(r.runner, "rv-push", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); why == "" {
494 t.Fatal("pushed after the revoke")
495 }
496 r.step("rv-end", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepCancelled, Reason: "cancelled", BaseSHA: baseX, Termination: true, Options: x.at.Options()})
497 // A chunk after the attempt ended is not staged either.
498 files, _ := designstep.Files(x.dir, id, d.StepID, d.Attempt, x.at.Options())
499 r.ack("rv-late", wire.FrameRenderFile, files[0][0])
500 if n := r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ?", d.StepID); n != 0 {
501 t.Fatalf("%d captures of a revoked attempt kept or staged", n)
502 }
503 if s := r.newest(id, wire.SpecialistEngineering); s.State != wire.StepCancelled || s.Design != nil {
504 t.Fatalf("the attempt %+v", s)
505 }
506 var card wire.Card
507 r.wait("recovery card", func(c *Conversation) bool {
508 for _, k := range c.Cards {
509 if k.Kind == wire.CardMakerRemoved && k.TaskID == id && k.State == wire.CardOpen {
510 card = k
511 }
512 }
513 return card.ID != ""
514 })
515 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceToEngineering, card.Revision); err != nil {
516 t.Fatal(err)
517 }
518 if e := r.nextDispatch(); e.TaskID != id || e.SpecialistID != "" || e.Profile != "" || r.makerOf(id) != "" {
519 t.Fatalf("handed to Engineering %+v", e)
520 }
521}
522
523// TestContractDesignWaitsForItsRunner: Design never runs where it cannot.
524// A primary whose renderer failed its fixture page reports it, and the
525// started task's Design step waits for the renderer, unsent; reconnected
526// at protocol 37 with the renderer ok, it waits for the runner's update;
527// at 38 it is dispatched with its binding. The task page says why.
528func TestContractDesignWaitsForItsRunner(t *testing.T) {
529 r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords)
530 broken := rendererHealth(t, errors.New("the fixture page did not render"))
531 if got := broken.Report(r.ctx); got == wire.ToolHealthy {
532 t.Fatalf("a failed fixture reported %q", got)
533 }
534 r.designOn(broken)
535 sp, id := r.designAdded(r.proposeDesign("d-propose"))
536 waits := func(reason, words string) {
537 t.Helper()
538 if err := r.inst.Store.Chat().Place(r.ctx); err != nil {
539 t.Fatal(err)
540 }
541 s := r.newest(id, wire.SpecialistEngineering)
542 if s.State != wire.StepQueued || s.Placement != wire.PlacementDesign || s.Reason != reason || s.RunnerID != "" || r.commands(wire.FrameDispatch) != 0 {
543 t.Fatalf("waiting for %s: %+v", reason, s)
544 }
545 if page := r.get(r.inst.SessionFor(t, Owner), "/tasks/"+id, 200); !strings.Contains(page, words) {
546 t.Fatalf("the task page lacks %q", words)
547 }
548 }
549 waits("design_renderer", "Waiting for the runner’s page renderer.")
550 ok := rendererHealth(t, nil)
551 r.redialAt(wire.ProtocolMacEngineering, ok)
552 waits("design_runner_old", "Waiting for the runner to be updated so it can run Design.")
553 r.redialAt(wire.ProtocolCurrent, ok)
554 if err := r.inst.Store.Chat().Place(r.ctx); err != nil {
555 t.Fatal(err)
556 }
557 r.designStarted(sp, id)
558}
559
560// TestContractDesignAddNeedsAnOwner: only the card's owner adds Design.
561// Another person's tap finds nothing; the proposer made a member taps
562// Add and is refused. Nothing is granted, no continuation is queued and
563// no task is recorded.
564func TestContractDesignAddNeedsAnOwner(t *testing.T) {
565 a := newToolRigAt(t, wire.ProtocolCurrent)
566 a.designOn(rendererHealth(t, nil))
567 b := personToolRigAt(t, a, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent)
568 m := personToolRig(t, a, "member@example.com", equipo.RoleMember)
569 card := b.proposeDesign("b-propose")
570 for _, other := range []*toolRig{a, m} {
571 if _, err := other.client.Answer(a.ctx, card.ID, wire.ChoiceAdd, card.Revision); Status(err) != 404 {
572 t.Fatalf("another person's tap: %v", err)
573 }
574 }
575 var revision int64
576 if err := a.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", "second@example.com").Scan(&revision); err != nil {
577 t.Fatal(err)
578 }
579 if err := a.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, "second@example.com", equipo.RoleMember, true, revision); err != nil {
580 t.Fatal(err)
581 }
582 if _, err := b.client.Answer(a.ctx, card.ID, wire.ChoiceAdd, card.Revision); Status(err) != 403 {
583 t.Fatalf("a member added Design: %v", err)
584 }
585 if a.rows("SELECT count(*) FROM chat_capability_grants") != 0 || a.rows("SELECT count(*) FROM chat_specialists WHERE state = ?", wire.SpecialistProposed) != 1 || a.rows("SELECT count(*) FROM chat_specialist_turns") != 0 || a.rows("SELECT count(*) FROM chat_tasks") != 0 {
586 t.Fatal("a member's tap granted, queued or recorded something")
587 }
588}
589
590// TestContractDesignNotNowWindow: Not now grants nothing and queues no
591// continuation; the coordinator cannot propose Design for Patrix again
592// until 7 days have passed since the answer.
593func TestContractDesignNotNowWindow(t *testing.T) {
594 r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords)
595 r.designOn(rendererHealth(t, nil))
596 card := r.proposeDesign("n-propose")
597 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceNotNow, card.Revision); err != nil {
598 t.Fatal(err)
599 }
600 if r.rows("SELECT count(*) FROM chat_capability_grants") != 0 || r.rows("SELECT count(*) FROM chat_specialist_turns") != 0 || r.rows("SELECT count(*) FROM chat_specialists WHERE state = ?", wire.SpecialistDeclined) != 1 {
601 t.Fatal("Not now granted or queued something")
602 }
603 r.next("Patrix still needs that overhaul.")
604 answered := func(ago time.Duration) {
605 t.Helper()
606 if _, err := r.inst.DB.Writer().Exec("UPDATE chat_specialists SET decided_at = ? WHERE id = ?", time.Now().UTC().Add(-ago), card.Specialist.ID); err != nil {
607 t.Fatal(err)
608 }
609 }
610 answered(7*24*time.Hour - time.Minute)
611 if res := r.call("n-again", wire.ToolProposeSpecialist, designProposal()); !res.IsError || res.Code != "declined_recently" {
612 t.Fatalf("proposed again within 7 days %+v", res)
613 }
614 answered(7*24*time.Hour + time.Minute)
615 if res := r.call("n-later", wire.ToolProposeSpecialist, designProposal()); res.IsError || res.Code != "proposed" {
616 t.Fatalf("after 7 days %+v", res)
617 }
618}
619