package thintest import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "image" "image/color" "image/png" "os" "path/filepath" "slices" "sort" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/runner/designstep" "amadan.net/oficina/equipo/internal/runner/render" "amadan.net/oficina/equipo/internal/runner/renderpage" "amadan.net/oficina/equipo/internal/specialist" "amadan.net/oficina/equipo/internal/wire" ) // Design end to end (spec 2026-11-28-dynamic-specialists.md; slice 1 // plan task 20). The instance and its runner link are real; the // coordinator is this test's tool calls; the Design step's runner side is // the runner's own render_page Tool and Design tools (renderpage, // designstep) with a fake browser behind the real renderer health check, // so no Chromium runs. Render checks and render_file chunks go over the // runner link. const patrixRepo = "amadan.net/oficina/patrix" // overhaulWords is the person's request that leads to Design. const overhaulWords = "Patrix needs a design overhaul. Show me a couple of directions for the home page before anything is built." // rendererHealth is the runner's renderer check with its tree verified // and its fixture page rendered by fakes: fixture is the fixture's end. func rendererHealth(t *testing.T, fixture error) *render.Health { t.Helper() h := &render.Health{Config: render.LaunchConfig{Bwrap: "/usr/bin/bwrap", Binary: "/runner/equipo-runner", Tree: t.TempDir(), Pin: "pin"}, Scratch: t.TempDir(), Verify: func(string, string) error { return nil }, Fixture: func(context.Context, render.LaunchConfig, string) error { return fixture }} h.Ready(context.Background()) return h } // designHello is the primary's hello at protocol with Patrix on its list, // the owner's Claude subscription, and the renderer's reported health. func (r *toolRig) designHello(protocol int, h *render.Health) wire.Hello { hello := primaryAt(toolHello(r.runner.Welcome.Generation), protocol) hello.Repos = append(hello.Repos, patrixRepo) 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"}) hello.Capabilities.Tools = &wire.ToolHealth{Scanner: wire.ToolHealthy, Renderer: h.Report(context.Background())} return hello } // designOn says the design hello and adds Patrix as the team's project. func (r *toolRig) designOn(h *render.Health) { r.t.Helper() if err := r.runner.Send(r.ctx, "h-design", wire.FrameHello, r.designHello(wire.ProtocolCurrent, h)); err != nil { r.t.Fatal(err) } if refused := r.lease(r.runner, "h-design-ping", wire.LeaseCheck{}); refused != "" { r.t.Fatalf("ping refused %q", refused) } if res := r.call("d-add", wire.ToolAddProject, map[string]string{"repo": "oficina/patrix"}); res.IsError { r.t.Fatalf("add Patrix %+v", res) } } // redialAt reconnects the primary at protocol with h's renderer health. func (r *toolRig) redialAt(protocol int, h *render.Health) { r.t.Helper() f, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, r.designHello(protocol, h)) if err != nil { r.t.Fatal(err) } r.t.Cleanup(f.Close) r.runner, r.held = f, nil r.lease(f, "h-redial-ping", wire.LeaseCheck{}) } func designProposal() map[string]any { 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"} } // proposeDesign has the coordinator propose Design for Patrix, end its // turn, and returns the open card. func (r *toolRig) proposeDesign(key string) wire.Card { r.t.Helper() if res := r.call(key, wire.ToolProposeSpecialist, designProposal()); res.IsError || res.Code != "proposed" { r.t.Fatalf("propose %+v", res) } card := r.specialistCard(wire.CardOpen) 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 { r.t.Fatal(err) } prev := r.turn r.wait("replied", func(c *Conversation) bool { return c.Turns[prev].State == wire.TurnReplied }) return card } // continuation takes the specialist_added turn the Add queued. func (r *toolRig) continuation() *wire.MessageCommand { r.t.Helper() _, body := r.expect(wire.FrameMessage) m := body.(*wire.MessageCommand) r.wait("continuation running", func(c *Conversation) bool { return c.Turns[m.TurnID].State == wire.TurnRunning }) r.turn = m.TurnID return m } // designAdded taps Add on card and has the continuation record the // exploration and start it with Design; it returns the specialist and // the task. func (r *toolRig) designAdded(card wire.Card) (wire.Specialist, string) { r.t.Helper() if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAdd, card.Revision); err != nil { r.t.Fatal(err) } m := r.continuation() sp := card.Specialist if m.Kind != wire.TurnSpecialistAdded || len(m.PersonText) != 0 || !strings.Contains(m.Text, strconv.Quote(overhaulWords)) || !strings.Contains(m.Text, sp.ID) { r.t.Fatalf("continuation %+v", m) } 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})) if res := r.call("d-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Show two directions.", "specialist": sp.ID}); res.IsError { r.t.Fatalf("start %+v", res) } 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 { r.t.Fatal(err) } list, err := r.client.Specialists(r.ctx) if err != nil || len(list.Items) != 1 || list.Items[0].State != wire.SpecialistActive { r.t.Fatalf("specialists %+v %v", list, err) } return list.Items[0], id } // designHand is the runner side of one Design attempt: the fake model's // workspace, the runner's render_page Tool over a fake browser, and the // step's Design tools, whose render check is a lease over the link. type designHand struct { r *toolRig d *wire.DispatchCommand work, dir, scratch string page *renderpage.Tool at *designstep.Attempt usage renderpage.Usage checks, browserRuns int } func (r *toolRig) designHand(d *wire.DispatchCommand, h *render.Health) *designHand { root := r.t.TempDir() x := &designHand{r: r, d: d, work: filepath.Join(root, "work"), dir: filepath.Join(root, "render"), scratch: filepath.Join(root, "render-work")} x.page = &renderpage.Tool{Renderer: h, Config: h.Config, Render: x.browser} x.at = &designstep.Attempt{Dir: x.dir, Confirm: x.confirm, Render: func(ctx context.Context, raw json.RawMessage) (string, []renderpage.Capture, error) { return x.page.Call(ctx, x, raw) }} return x } func (x *designHand) confirm(context.Context) error { x.checks++ 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 != "" { return fmt.Errorf("%w: %s", designstep.ErrRenderRefused, why) } return nil } func (x *designHand) Dir() string { return x.dir } func (x *designHand) Scratch() string { return x.scratch } // Audit keeps nothing: the runner's state keeps the records (thin). func (x *designHand) Audit(context.Context, wire.RenderAudit) {} func (x *designHand) Accept(_ context.Context, captures int) (renderpage.Usage, error) { x.usage.Calls++ x.usage.Captures += captures return x.usage, nil } // Site exports the work tree's release/preview.json output; its digest // is over every exported file. func (x *designHand) Site(_ context.Context, tree, stage string) (string, error) { if tree != renderpage.TreeWork { return "", renderpage.Refuse(renderpage.CodeNoSite, "no base site") } var cfg struct{ Output string } raw, err := os.ReadFile(filepath.Join(x.work, "release", "preview.json")) if err != nil || json.Unmarshal(raw, &cfg) != nil { return "", renderpage.Refuse(renderpage.CodeNoSite, "no preview config") } sum, from := sha256.New(), filepath.Join(x.work, cfg.Output) var names []string err = filepath.WalkDir(from, func(p string, e os.DirEntry, err error) error { if err == nil && !e.IsDir() { names = append(names, p) } return err }) sort.Strings(names) for _, p := range names { rel, _ := filepath.Rel(from, p) b, _ := os.ReadFile(p) os.MkdirAll(filepath.Dir(filepath.Join(stage, rel)), 0o700) if err == nil { err = os.WriteFile(filepath.Join(stage, rel), b, 0o600) } fmt.Fprintf(sum, "%s\x00%d\x00%s", rel, len(b), b) } return hex.EncodeToString(sum.Sum(nil)), err } // browser stands in for Chromium: each page is its viewport's size in // a colour taken from the page's own file, so options differ. func (x *designHand) browser(_ context.Context, cfg render.LaunchConfig, out string, pages []render.Page) (*render.Report, error) { x.browserRuns++ rep := &render.Report{Schema: render.ReportSchema} for i, p := range pages { html, err := os.ReadFile(filepath.Join(cfg.Site, p.Path, "index.html")) if err != nil { return nil, err } w, h, _ := p.Viewport.Size() img, c := image.NewNRGBA(image.Rect(0, 0, w, h)), sha256.Sum256(html) for y := range h { for x := range w { img.Set(x, y, color.NRGBA{c[0], c[1], c[2], 0xff}) } } name := "page-" + itoa(i+1) + ".png" f, err := os.Create(filepath.Join(out, name)) if err != nil { return nil, err } err = errors.Join(png.Encode(f, img), f.Close()) if err != nil { return nil, err } 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"}) } return rep, nil } // mockups is the fake model writing its two options under // mockups// and release/preview.json naming them. func (x *designHand) mockups() { x.r.t.Helper() files := map[string]string{ "release/preview.json": `{"output": "mockups/` + x.d.TaskID + `"}`, "mockups/" + x.d.TaskID + "/calm/index.html": "

Patrix

Calm: soft blue, larger type.

", "mockups/" + x.d.TaskID + "/bold/index.html": "

Patrix

Bold: black and yellow.

", } for name, body := range files { p := filepath.Join(x.work, name) if err := errors.Join(os.MkdirAll(filepath.Dir(p), 0o700), os.WriteFile(p, []byte(body), 0o600)); err != nil { x.r.t.Fatal(err) } } } // tool is the fake model calling one of the step's tools. func (x *designHand) tool(name, args string) (string, bool) { return x.at.Call(x.r.ctx, name, "", json.RawMessage(args)) } const renderBoth = `{"tree": "work", "pages": [{"path": "/calm/", "viewport": "desktop"}, {"path": "/calm/", "viewport": "phone"}, {"path": "/bold/", "viewport": "desktop"}]}` // uploads sends the named captures over the link as render_file chunks. func (x *designHand) uploads(key string) { x.r.t.Helper() files, err := designstep.Files(x.dir, x.d.TaskID, x.d.StepID, x.d.Attempt, x.at.Options()) if err != nil { x.r.t.Fatal(err) } for i, chunks := range files { for j, c := range chunks { x.r.ack(key+"-"+itoa(i)+"-"+itoa(j), wire.FrameRenderFile, c) } } } // ack sends one durable frame and waits for its ack, holding the rest. func (r *toolRig) ack(id, kind string, body any) { r.t.Helper() if err := r.runner.Send(r.ctx, id, kind, body); err != nil { r.t.Fatal(err) } for { f, b, err := r.runner.Next(r.ctx) if err != nil { r.t.Fatal(err) } if a, ok := b.(*wire.Ack); ok && a.ID == id { return } if f.Type != wire.FrameAck { r.held = append(r.held, heldFrame{f, b, r.runner.Received[len(r.runner.Received)-1]}) } } } // designStarted takes Design's dispatch, checks its binding, and has the // runner start it. func (r *toolRig) designStarted(sp wire.Specialist, id string) *wire.DispatchCommand { r.t.Helper() d := r.nextDispatch() design, _ := specialist.Lookup(specialist.ProfileDesign) 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 { r.t.Fatalf("Design's dispatch %+v", d) } if why := r.lease(r.runner, "ds-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); why != "" { r.t.Fatalf("start refused %q", why) } r.step("ds-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: baseX, Family: "claude", Account: "claude-a"}) return d } func (r *toolRig) makerOf(id string) string { r.t.Helper() var maker string if err := r.inst.DB.Writer().QueryRow("SELECT maker_specialist_id FROM chat_tasks WHERE id = ?", id).Scan(&maker); err != nil { r.t.Fatal(err) } return maker } // TestContractDesignFinishLine is slice 1's Design finish line: the // person asks for a Patrix design overhaul on a primary at 38 whose // renderer is ok and which holds their Claude subscription; the // coordinator proposes design-v1 for Patrix; the owner's Add queues the // continuation, which records an exploration and starts it with Design; // the dispatch carries the binding; the model renders through the // instance's render check, writes its options under mockups// and // submits; the captures go up as render_file chunks and the final // report keeps them; the task page and the direction card show them; // Build needs a note and, with one, makes the change task with Design // as its maker and the note quoted as the person's own words. func TestContractDesignFinishLine(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords) health := rendererHealth(t, nil) if got := health.Report(r.ctx); got != wire.ToolHealthy { t.Fatalf("renderer %q", got) } r.designOn(health) card := r.proposeDesign("d-propose") if card.Question != "Add Design to your team for Patrix?" || card.Specialist.Profile != specialist.ProfileDesign { t.Fatalf("card %+v %+v", card, card.Specialist) } sp, id := r.designAdded(card) if sp.Project != r.patrixID() || r.makerOf(id) != sp.ID || r.task(id).Kind != wire.KindExplore { t.Fatalf("maker %q", r.makerOf(id)) } d := r.designStarted(sp, id) x := r.designHand(d, health) x.mockups() if text, failed := x.tool(designstep.ToolRenderPage, renderBoth); failed || !strings.Contains(text, "/render/1-work-3.png") { t.Fatalf("render_page %v %s", failed, text) } if x.checks != 1 || x.browserRuns != 1 { t.Fatalf("%d render checks, %d browser runs", x.checks, x.browserRuns) } if text, failed := x.tool(designstep.ToolAskPerson, `{"question": "Blue or yellow?"}`); failed || text != designstep.AskText { t.Fatalf("ask_person %s", text) } 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 { t.Fatalf("submit %s", text) } x.uploads("ds-file") if r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ? AND complete = 1 AND kept = 0", d.StepID) != 3 { t.Fatal("the captures are not staged") } if why := r.lease(r.runner, "ds-push", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); why != "" { t.Fatalf("pre-push refused %q", why) } 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()}) // Kept, byte for byte, in the report's order. k := r.task(id) eng := stepsOf(k, wire.SpecialistEngineering)[0] 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 { t.Fatalf("kept %+v", eng.Design) } for _, o := range eng.Design.Options { for _, c := range o.Captures { want, err := os.ReadFile(filepath.Join(x.dir, c.CaptureID)) got, _ := r.fetch(r.client.Token, "/api/v1/tasks/"+id+"/files/"+c.ID, 200) if err != nil || string(got) != string(want) || c.Width < 1 { t.Fatalf("capture %+v: %d bytes, want %d", c, len(got), len(want)) } } } r.expect(wire.FrameWatchMerge) r.approved("ds", candX, true) dir := r.directionCard(id) if k := r.task(id); k.Direction == nil || len(k.Direction.Options) != 2 || !k.Direction.NoteNeeded { t.Fatalf("direction %+v", k.Direction) } calm := eng.Design.Options[0].Captures[0].ID page := r.get(r.inst.SessionFor(t, Owner), "/tasks/"+id, 200) conv := r.get(r.inst.SessionFor(t, Owner), "/conversation", 200) for _, want := range []string{"Option 1: Calm", "Option 2: Bold", `/tasks/` + id + `/files/` + calm} { if !strings.Contains(page, want) || !strings.Contains(conv, want) { t.Fatalf("the task page or the direction card lacks %q", want) } } if !strings.Contains(conv, "data-direction-build") { t.Fatal("the direction card's Build asks for no note") } // Build with two options needs the person's note. _, err := r.client.Answer(r.ctx, dir.ID, wire.ChoiceBuild, dir.Revision) var conflict wire.CardConflict if st, ok := err.(*ErrStatus); !ok || st.Status != 409 || json.Unmarshal(st.Body, &conflict) != nil || conflict.Code != wire.ConflictDirectionNote { t.Fatalf("Build without a note: %v", err) } note := "Build Calm, with Bold's yellow button." if _, err := r.client.AnswerNote(r.ctx, dir.ID, wire.ChoiceBuild, note, dir.Revision); err != nil { t.Fatal(err) } k = r.task(id) if k.BuiltAs == nil { t.Fatalf("built %+v", k) } built := r.task(k.BuiltAs.ID) 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 { t.Fatalf("the change task %q %q maker %q", built.Kind, built.Brief, r.makerOf(built.ID)) } if b := r.nextDispatch(); b.TaskID != built.ID || b.SpecialistID != sp.ID || b.Explore || !strings.Contains(b.Brief, wire.QuotedData(note)) { t.Fatalf("the change task's dispatch %+v", b) } } // patrixID is the Patrix project's id. func (r *toolRig) patrixID() string { r.t.Helper() list, err := r.client.Projects(r.ctx) if err != nil { r.t.Fatal(err) } for _, p := range list.Items { if p.Repo == patrixRepo { return p.ID } } r.t.Fatal("no Patrix project") return "" } // TestContractDesignRevokeMidStep: an owner revokes Design between two // renders. The runner gets cancel_step; the next render check is refused // over the link, so render_page stops for the attempt and the browser // never runs again; the pre-push check is refused; the captures it // uploads are never kept; and once the attempt reports its end, the // recovery card hands the task to Engineering, unbound. func TestContractDesignRevokeMidStep(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords) health := rendererHealth(t, nil) r.designOn(health) sp, id := r.designAdded(r.proposeDesign("d-propose")) d := r.designStarted(sp, id) x := r.designHand(d, health) x.mockups() if _, failed := x.tool(designstep.ToolRenderPage, renderBoth); failed { t.Fatal("the first render") } if _, err := r.client.RevokeSpecialist(r.ctx, sp.ID, sp.Revision); err != nil { t.Fatal(err) } if _, body := r.expect(wire.FrameCancelStep); body.(*wire.CancelStepCommand).StepID != d.StepID { t.Fatalf("cancel %+v", body) } for i := range 2 { if text, failed := x.tool(designstep.ToolRenderPage, renderBoth); !failed || text != designstep.RenderRefusedText { t.Fatalf("render %d after the revoke: %s", i+2, text) } } if x.checks != 2 || x.browserRuns != 1 { t.Fatalf("%d render checks, %d browser runs", x.checks, x.browserRuns) } if text, failed := x.tool(designstep.ToolSubmitCandidate, `{"options": [{"name": "Calm", "captures": ["1-work-1.png"]}]}`); failed { t.Fatalf("submit %s", text) } x.uploads("rv-file") if why := r.lease(r.runner, "rv-push", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); why == "" { t.Fatal("pushed after the revoke") } 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()}) // A chunk after the attempt ended is not staged either. files, _ := designstep.Files(x.dir, id, d.StepID, d.Attempt, x.at.Options()) r.ack("rv-late", wire.FrameRenderFile, files[0][0]) if n := r.rows("SELECT count(*) FROM chat_task_files WHERE step_id = ?", d.StepID); n != 0 { t.Fatalf("%d captures of a revoked attempt kept or staged", n) } if s := r.newest(id, wire.SpecialistEngineering); s.State != wire.StepCancelled || s.Design != nil { t.Fatalf("the attempt %+v", s) } var card wire.Card r.wait("recovery card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardMakerRemoved && k.TaskID == id && k.State == wire.CardOpen { card = k } } return card.ID != "" }) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceToEngineering, card.Revision); err != nil { t.Fatal(err) } if e := r.nextDispatch(); e.TaskID != id || e.SpecialistID != "" || e.Profile != "" || r.makerOf(id) != "" { t.Fatalf("handed to Engineering %+v", e) } } // TestContractDesignWaitsForItsRunner: Design never runs where it cannot. // A primary whose renderer failed its fixture page reports it, and the // started task's Design step waits for the renderer, unsent; reconnected // at protocol 37 with the renderer ok, it waits for the runner's update; // at 38 it is dispatched with its binding. The task page says why. func TestContractDesignWaitsForItsRunner(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords) broken := rendererHealth(t, errors.New("the fixture page did not render")) if got := broken.Report(r.ctx); got == wire.ToolHealthy { t.Fatalf("a failed fixture reported %q", got) } r.designOn(broken) sp, id := r.designAdded(r.proposeDesign("d-propose")) waits := func(reason, words string) { t.Helper() if err := r.inst.Store.Chat().Place(r.ctx); err != nil { t.Fatal(err) } s := r.newest(id, wire.SpecialistEngineering) if s.State != wire.StepQueued || s.Placement != wire.PlacementDesign || s.Reason != reason || s.RunnerID != "" || r.commands(wire.FrameDispatch) != 0 { t.Fatalf("waiting for %s: %+v", reason, s) } if page := r.get(r.inst.SessionFor(t, Owner), "/tasks/"+id, 200); !strings.Contains(page, words) { t.Fatalf("the task page lacks %q", words) } } waits("design_renderer", "Waiting for the runner’s page renderer.") ok := rendererHealth(t, nil) r.redialAt(wire.ProtocolMacEngineering, ok) waits("design_runner_old", "Waiting for the runner to be updated so it can run Design.") r.redialAt(wire.ProtocolCurrent, ok) if err := r.inst.Store.Chat().Place(r.ctx); err != nil { t.Fatal(err) } r.designStarted(sp, id) } // TestContractDesignAddNeedsAnOwner: only the card's owner adds Design. // Another person's tap finds nothing; the proposer made a member taps // Add and is refused. Nothing is granted, no continuation is queued and // no task is recorded. func TestContractDesignAddNeedsAnOwner(t *testing.T) { a := newToolRigAt(t, wire.ProtocolCurrent) a.designOn(rendererHealth(t, nil)) b := personToolRigAt(t, a, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) m := personToolRig(t, a, "member@example.com", equipo.RoleMember) card := b.proposeDesign("b-propose") for _, other := range []*toolRig{a, m} { if _, err := other.client.Answer(a.ctx, card.ID, wire.ChoiceAdd, card.Revision); Status(err) != 404 { t.Fatalf("another person's tap: %v", err) } } var revision int64 if err := a.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", "second@example.com").Scan(&revision); err != nil { t.Fatal(err) } if err := a.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, "second@example.com", equipo.RoleMember, true, revision); err != nil { t.Fatal(err) } if _, err := b.client.Answer(a.ctx, card.ID, wire.ChoiceAdd, card.Revision); Status(err) != 403 { t.Fatalf("a member added Design: %v", err) } 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 { t.Fatal("a member's tap granted, queued or recorded something") } } // TestContractDesignNotNowWindow: Not now grants nothing and queues no // continuation; the coordinator cannot propose Design for Patrix again // until 7 days have passed since the answer. func TestContractDesignNotNowWindow(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, overhaulWords) r.designOn(rendererHealth(t, nil)) card := r.proposeDesign("n-propose") if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceNotNow, card.Revision); err != nil { t.Fatal(err) } 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 { t.Fatal("Not now granted or queued something") } r.next("Patrix still needs that overhaul.") answered := func(ago time.Duration) { t.Helper() 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 { t.Fatal(err) } } answered(7*24*time.Hour - time.Minute) if res := r.call("n-again", wire.ToolProposeSpecialist, designProposal()); !res.IsError || res.Code != "declined_recently" { t.Fatalf("proposed again within 7 days %+v", res) } answered(7*24*time.Hour + time.Minute) if res := r.call("n-later", wire.ToolProposeSpecialist, designProposal()); res.IsError || res.Code != "proposed" { t.Fatalf("after 7 days %+v", res) } }