package designstep
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"amadan.net/oficina/equipo/internal/runner/renderpage"
"amadan.net/oficina/equipo/internal/wire"
)
var digest = strings.Repeat("d", 64)
// rig is an Attempt whose render_page writes the captures it is told to
// into its directory, and records what asked what, in order.
type rig struct {
a *Attempt
dir string
events []string
confirm error
next [][]string
saved [][]wire.DesignOption
}
func newRig(t *testing.T) *rig {
t.Helper()
r := &rig{dir: filepath.Join(t.TempDir(), "render")}
if err := os.Mkdir(r.dir, 0o700); err != nil {
t.Fatal(err)
}
r.a = &Attempt{Dir: r.dir}
r.a.Confirm = func(context.Context) error {
r.events = append(r.events, "confirm")
return r.confirm
}
r.a.Render = func(_ context.Context, raw json.RawMessage) (string, []renderpage.Capture, error) {
r.events = append(r.events, "render")
var files []string
if len(r.next) > 0 {
files, r.next = r.next[0], r.next[1:]
}
var caps []renderpage.Capture
for _, f := range files {
if err := os.WriteFile(filepath.Join(r.dir, f), []byte("png of "+f), 0o600); err != nil {
return "", nil, err
}
caps = append(caps, renderpage.Capture{File: f, Tree: "work", Digest: digest, Bytes: int64(len("png of " + f))})
}
return "rendered " + strings.Join(files, ","), caps, nil
}
r.a.Record = func(_ context.Context, opts []wire.DesignOption) error {
r.saved = append(r.saved, opts)
return nil
}
return r
}
func (r *rig) call(name, args string) (string, bool) {
return r.a.Call(context.Background(), name, "u", json.RawMessage(args))
}
const page = `{"tree": "work", "pages": [{"path": "/", "viewport": "phone"}]}`
// TestRenderAsksTheLeaseFirst: every render_page call asks the instance
// first (wire.LeasePurposeRender), before its input is even read.
func TestRenderAsksTheLeaseFirst(t *testing.T) {
r := newRig(t)
r.next = [][]string{{"1-work-1.png"}}
if text, isError := r.call(ToolRenderPage, page); isError || text != "rendered 1-work-1.png" {
t.Fatalf("%q %v", text, isError)
}
r.call(ToolRenderPage, `not json`)
if strings.Join(r.events, " ") != "confirm render confirm render" {
t.Fatalf("events %v", r.events)
}
r.a.Confirm = nil
if text, isError := r.call(ToolRenderPage, page); !isError || text != RenderUnconfirmedText {
t.Fatalf("no lease check: %q %v", text, isError)
}
}
// TestRefusedRenderLeaseStopsRendering: once the instance refuses a
// render, render_page renders nothing more in the step, never asks
// again, and says why in fixed text; a check that could not be made
// stops it too, saying so.
func TestRefusedRenderLeaseStopsRendering(t *testing.T) {
for name, tc := range map[string]struct {
err error
text string
}{
"refused": {errors.Join(ErrRenderRefused, errors.New("withdrawn")), RenderRefusedText},
"unconfirmed": {errors.New("no connection"), RenderUnconfirmedText},
} {
t.Run(name, func(t *testing.T) {
r := newRig(t)
r.next = [][]string{{"1-work-1.png"}, {"2-work-1.png"}}
r.call(ToolRenderPage, page)
r.confirm = tc.err
for i := range 3 {
text, isError := r.call(ToolRenderPage, page)
if !isError || text != tc.text {
t.Fatalf("call %d: %q %v", i+2, text, isError)
}
}
if strings.Join(r.events, " ") != "confirm render confirm" {
t.Fatalf("events %v", r.events)
}
r.confirm = nil
if text, _ := r.call(ToolRenderPage, page); text != tc.text {
t.Fatalf("rendering came back: %q", text)
}
// What it rendered before the refusal can still be named.
if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet", "captures": ["1-work-1.png"]}]}`); isError {
t.Fatal(text)
}
})
}
if !strings.Contains(RenderRefusedText, "refused") || !strings.Contains(RenderUnconfirmedText, "could not confirm") {
t.Fatal("the texts do not say why")
}
}
// TestCancelledRenderLeaseIsNotAStop: a check cut short by the step
// ending is no refusal.
func TestCancelledRenderLeaseIsNotAStop(t *testing.T) {
r := newRig(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
r.a.Confirm = func(ctx context.Context) error { return ctx.Err() }
if text, isError := r.a.Call(ctx, ToolRenderPage, "u", json.RawMessage(page)); !isError || text == RenderRefusedText || text == RenderUnconfirmedText {
t.Fatalf("%q %v", text, isError)
}
r.a.Confirm = func(context.Context) error { return nil }
r.next = [][]string{{"1-work-1.png"}}
if text, isError := r.call(ToolRenderPage, page); isError {
t.Fatalf("stopped after a cancelled check: %q", text)
}
}
// TestSubmitCandidateRecordsOptions: submit_candidate records the
// options' names and, for each capture it names, the SHA-256 and tree
// digest of the file render_page wrote in this attempt; a later call
// replaces them.
func TestSubmitCandidateRecordsOptions(t *testing.T) {
r := newRig(t)
r.next = [][]string{{"1-work-1.png", "1-work-2.png"}}
r.call(ToolRenderPage, page)
text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet editorial", "captures": ["1-work-1.png"]}, {"name": "Market stall", "captures": ["1-work-2.png"]}]}`)
if isError || !strings.HasPrefix(text, "Recorded 2 options with 2 captures.") {
t.Fatalf("%q %v", text, isError)
}
sum := sha256.Sum256([]byte("png of 1-work-1.png"))
want := wire.DesignCapture{ID: "1-work-1.png", SHA256: hex.EncodeToString(sum[:]), TreeDigest: digest}
got := r.a.Options()
if len(got) != 2 || got[0].Name != "Quiet editorial" || len(got[0].Captures) != 1 || got[0].Captures[0] != want || got[1].Name != "Market stall" {
t.Fatalf("options %+v", got)
}
if len(r.saved) != 1 || len(r.saved[0]) != 2 {
t.Fatalf("recorded %+v", r.saved)
}
if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet editorial", "captures": []}]}`); isError {
t.Fatal(text)
}
if got := r.a.Options(); len(got) != 1 || len(got[0].Captures) != 0 {
t.Fatalf("not replaced: %+v", got)
}
r.a.Record = func(context.Context, []wire.DesignOption) error { return errors.New("disk") }
if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Again", "captures": ["1-work-1.png"]}]}`); !isError || text != submitUnrecordedText {
t.Fatalf("unrecorded: %q %v", text, isError)
}
if got := r.a.Options(); len(got) != 1 || got[0].Name != "Quiet editorial" {
t.Fatalf("an unrecorded call changed them: %+v", got)
}
}
// TestSubmitCandidateRefusals: only captures render_page made in this
// attempt, named once; the wire's bounds; strict input. A refusal
// records nothing.
func TestSubmitCandidateRefusals(t *testing.T) {
r := newRig(t)
var many []string
for i := 1; i <= 13; i++ {
many = append(many, "1-work-"+itoa(i)+".png")
}
r.next = [][]string{many}
r.call(ToolRenderPage, `{"tree": "work", "pages": []}`)
// A file in the render directory that no reply of this attempt gave
// (another attempt's, or planted).
if err := os.WriteFile(filepath.Join(r.dir, "9-work-1.png"), []byte("other"), 0o600); err != nil {
t.Fatal(err)
}
quoted := func(ids ...string) string {
raw, _ := json.Marshal(ids)
return string(raw)
}
for name, args := range map[string]string{
// These two must be refused for what they are, whatever else.
"not this attempt's: is not a capture": `{"options": [{"name": "A", "captures": ["9-work-1.png"]}]}`,
"never made: is not a capture": `{"options": [{"name": "A", "captures": ["2-work-1.png"]}]}`,
"not this attempt's": `{"options": [{"name": "A", "captures": ["9-work-1.png"]}]}`,
"never made": `{"options": [{"name": "A", "captures": ["2-work-1.png"]}]}`,
"not a capture id": `{"options": [{"name": "A", "captures": ["../state.db"]}]}`,
"twice": `{"options": [{"name": "A", "captures": ["1-work-1.png"]}, {"name": "B", "captures": ["1-work-1.png"]}]}`,
"13 captures": `{"options": [{"name": "A", "captures": ` + quoted(many...) + `}]}`,
"5 options": `{"options": [{"name": "A", "captures": []}, {"name": "B", "captures": []}, {"name": "C", "captures": []}, {"name": "D", "captures": []}, {"name": "E", "captures": []}]}`,
"a name twice": `{"options": [{"name": "A", "captures": []}, {"name": "a", "captures": []}]}`,
"a bad name": `{"options": [{"name": "A", "captures": []}]}`,
"unknown field": `{"options": [], "summary": "x"}`,
"unknown option part": `{"options": [{"name": "A", "captures": [], "url": "x"}]}`,
"no options": `{}`,
"trailing": `{"options": []} {}`,
"not an object": `[]`,
} {
text, isError := r.call(ToolSubmitCandidate, args)
if !isError || !strings.HasPrefix(text, "submit_candidate refused:") {
t.Errorf("%s: %q %v", name, text, isError)
}
if _, why, ok := strings.Cut(name, ": "); ok && !strings.Contains(text, why) {
t.Errorf("%s: %q", name, text)
}
}
if len(r.saved) != 0 || r.a.Options() != nil {
t.Fatalf("a refusal recorded %+v", r.saved)
}
if text, isError := r.call(ToolSubmitCandidate, `{"options": []}`); isError {
t.Fatalf("no options at all: %q", text)
}
}
// TestAskPersonSaysNobodyCanAnswer: ask_person's reply is fixed.
func TestAskPersonSaysNobodyCanAnswer(t *testing.T) {
r := newRig(t)
if text, isError := r.call(ToolAskPerson, `{"question": "which?"}`); isError || text != AskText || !strings.HasPrefix(text, "Nobody can answer") {
t.Fatalf("%q %v", text, isError)
}
if _, isError := r.call("submit_render", `{}`); !isError {
t.Fatal("another tool answered")
}
if len(r.events) != 0 {
t.Fatalf("events %v", r.events)
}
}
// TestFilesAreTheNamedCapturesOfTheAttempt: the upload is exactly the
// named captures, read from the attempt's own render directory, each
// as valid render_file chunks bound to the task, step and attempt that
// reassemble to the file; a capture that is not the file recorded, or
// not a regular file there, refuses the upload.
func TestFilesAreTheNamedCapturesOfTheAttempt(t *testing.T) {
r := newRig(t)
big := make([]byte, 300<<10)
for i := range big {
big[i] = byte(i * 7)
}
r.next = [][]string{{"1-work-1.png", "1-work-2.png"}}
r.call(ToolRenderPage, page)
if err := os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), big, 0o600); err != nil {
t.Fatal(err)
}
// The capture as render_page left it is the big one (rewritten
// before it was recorded would be a lie: record it again).
r.a.captures = nil
r.a.keep([]renderpage.Capture{{File: "1-work-1.png", Digest: digest}, {File: "1-work-2.png", Digest: digest}})
if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet", "captures": ["1-work-1.png"]}]}`); isError {
t.Fatal(text)
}
os.WriteFile(filepath.Join(r.dir, "3-work-1.png"), []byte("planted"), 0o600)
files, err := Files(r.dir, "tk1", "st1", 2, r.a.Options())
if err != nil {
t.Fatal(err)
}
if len(files) != 1 {
t.Fatalf("%d files uploaded", len(files))
}
var whole []byte
for i, f := range files[0] {
if !wire.ValidRenderFile(f) || f.TaskID != "tk1" || f.StepID != "st1" || f.Attempt != 2 || f.CaptureID != "1-work-1.png" || f.Index != i || f.Total != 3 || f.Size != int64(len(big)) {
t.Fatalf("chunk %d: %+v", i, f)
}
part, _ := base64.StdEncoding.DecodeString(f.Data)
whole = append(whole, part...)
}
if string(whole) != string(big) || files[0][0].SHA256 != r.a.Options()[0].Captures[0].SHA256 {
t.Fatal("the chunks are not the capture")
}
if files, err := Files(r.dir, "tk1", "st1", 2, nil); err != nil || len(files) != 0 {
t.Fatalf("no options: %v %v", files, err)
}
opts := r.a.Options()
for name, change := range map[string]func(){
"changed": func() { os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), []byte("other bytes"), 0o600) },
"gone": func() { os.Remove(filepath.Join(r.dir, "1-work-1.png")) },
"a link": func() {
// To a file of the same bytes: only the link itself is wrong.
os.WriteFile(filepath.Join(r.dir, "5-work-1.png"), big, 0o600)
os.Remove(filepath.Join(r.dir, "1-work-1.png"))
os.Symlink("5-work-1.png", filepath.Join(r.dir, "1-work-1.png"))
},
"too large": func() {
os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), make([]byte, wire.MaxCaptureBytes+1), 0o600)
},
} {
os.Remove(filepath.Join(r.dir, "1-work-1.png"))
os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), big, 0o600)
if _, err := Files(r.dir, "tk1", "st1", 2, opts); err != nil {
t.Fatalf("%s: restored: %v", name, err)
}
change()
if _, err := Files(r.dir, "tk1", "st1", 2, opts); err == nil {
t.Errorf("%s: uploaded", name)
}
}
os.Remove(filepath.Join(r.dir, "1-work-1.png"))
os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), big, 0o600)
bad := clone(opts)
bad[0].Name = "Quiet"
if _, err := Files(r.dir, "tk1", "st1", 2, bad); err == nil {
t.Fatal("options the wire refuses uploaded")
}
}
func itoa(i int) string {
raw, _ := json.Marshal(i)
return string(raw)
}