package thin import ( "bytes" "context" "log/slog" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" "github.com/coder/websocket" ) // fakeLookup is a lookup harness answering reply (or blocking until its // context ends when block), recording the prompt. type fakeLookup struct { reply string block bool prompt string closed bool } func (f *fakeLookup) Glance(ctx context.Context, prompt string) (string, error) { f.prompt = prompt if f.block { <-ctx.Done() return "", ctx.Err() } return f.reply, nil } func (f *fakeLookup) Warm(context.Context) error { return nil } func (f *fakeLookup) Up() bool { return true } func (f *fakeLookup) Close() { f.closed = true } // lookupEngine is an engine whose lookup harness is h, each in a new // directory under root; dirs are the directories made. func lookupEngine(t *testing.T, h *fakeLookup, logs *bytes.Buffer) (*Engine, *[]string) { t.Helper() root := t.TempDir() var dirs []string e := &Engine{Logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})), OpenLookup: func(person string, _ runner.AccountBinding) (Glancer, string, error) { dir, err := os.MkdirTemp(root, "lookup-") if err == nil { err = os.WriteFile(filepath.Join(dir, "session.jsonl"), []byte("a transcript"), 0o600) } dirs = append(dirs, dir) return h, dir, err }} return e, &dirs } func answerStep(text string) wire.LookupStep { return wire.LookupStep{Person: "paul@example.com", Lookup: "lk_1", Attempt: 1, Nonce: "n1", Stage: wire.LookupStageAnswer, Pack: wire.LookupPack{Question: "Weather in Dublin?", City: "Dublin", Date: "2026-11-28, Saturday"}, Results: []wire.SearchResult{{Title: "Met", URL: "https://www.met.ie/"}}, Pages: []wire.LookupPage{{URL: "https://www.met.ie/", Text: text}}} } // A lookup step has the glance's harness (no tools, never resumed) in a // directory of its own, gone when it returns; its result is its // stage's JSON, for its lookup, attempt and nonce. func TestLookupStepsIsolated(t *testing.T) { if lookupProfile.action != provider.GlanceAction || !lookupProfile.ephemeral || lookupProfile.set(true).permission == nil { t.Fatalf("profile %+v", lookupProfile) } h := &fakeLookup{reply: `{"answer": "Rain, 11°C.", "used": [0]}`} var logs bytes.Buffer e, dirs := lookupEngine(t, h, &logs) r := e.Lookup(context.Background(), answerStep("Rain at first.")) if r.Code != "" || r.Answer != "Rain, 11°C." || r.Lookup != "lk_1" || r.Nonce != "n1" || r.Attempt != 1 || r.Stage != wire.LookupStageAnswer { t.Fatalf("result %+v", r) } if len(*dirs) != 1 || !h.closed { t.Fatalf("dirs %v closed %v", *dirs, h.closed) } if _, err := os.Stat((*dirs)[0]); !os.IsNotExist(err) { t.Errorf("the step's directory is still there: %v", err) } if !strings.Contains(h.prompt, wire.LookupWebHeader) || !strings.HasPrefix(h.prompt, wire.LookupAnswerPrompt) { t.Errorf("prompt %.200q", h.prompt) } } // What a page says goes nowhere on the runner but the model: not its // log, not its directory, which is gone. func TestLookupStepEphemeralOnRunner(t *testing.T) { const sentinel = "SENTINEL-PAGE-TEXT-42" h := &fakeLookup{reply: `{"answer": "` + sentinel + `", "used": [0]}`} var logs bytes.Buffer e, dirs := lookupEngine(t, h, &logs) _ = e.Lookup(context.Background(), answerStep(sentinel)) if strings.Contains(logs.String(), sentinel) || !strings.Contains(logs.String(), "assistant lookup") { t.Errorf("logs %q", logs.String()) } if _, err := os.Stat((*dirs)[0]); !os.IsNotExist(err) { t.Error("the directory survived") } } func TestLookupStepTimeout(t *testing.T) { h := &fakeLookup{block: true} var logs bytes.Buffer e, _ := lookupEngine(t, h, &logs) e.LookupTimeout = 50 * time.Millisecond start := time.Now() if r := e.Lookup(context.Background(), answerStep("x")); r.Code != wire.CodeLookupFailed || time.Since(start) > 5*time.Second { t.Errorf("result %+v after %s", r, time.Since(start)) } if LookupTimeout != 20*time.Second { t.Errorf("the timeout is %s", LookupTimeout) } } func TestLookupStepBadJSON(t *testing.T) { for _, reply := range []string{"Rain, 11°C.", `{"answer": "x", "used": [0], "note": "y"}`, `{"answer": "x", "used": [5]}`} { h := &fakeLookup{reply: reply} var logs bytes.Buffer e, _ := lookupEngine(t, h, &logs) if r := e.Lookup(context.Background(), answerStep("x")); r.Code != wire.CodeLookupFailed || r.Answer != "" { t.Errorf("%q: %+v", reply, r) } } } // A result goes on the connection its step came on, or nowhere (Astra // phase 3 round 1, P2). func TestLookupResultStaysOnItsConnection(t *testing.T) { l := &Link{} l.init() first, second := &websocket.Conn{}, &websocket.Conn{} l.conn = first l.lookupResult(first, wire.LookupResult{Lookup: "a"}) l.conn = second l.lookupResult(first, wire.LookupResult{Lookup: "late"}) if got := l.takeLookups(second); len(got) != 0 { t.Errorf("sent on the next connection: %+v", got) } l.lookupResult(second, wire.LookupResult{Lookup: "b"}) if got := l.takeLookups(second); len(got) != 1 || got[0].Lookup != "b" { t.Errorf("got %+v", got) } }