From 50845430e37d3c2f89a89aab73e314991a15997b Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 11 Sep 2026 20:10:59 +1000 Subject: [PATCH] test(ui): smoke the archie-ui process against live dependencies The in-process suite proved the composition; nothing proved the process. This builds the real binary, points it at a State Store and a Gateway on loopback gRPC through an operator-shaped config.toml, and drives it over HTTP: the token exchange and its 401s, the embedded SPA, a chat stream relayed frame by frame, an operator task action crossing to the Gateway and refused without the CSRF header, unauthenticated capture intake, the ratified degradations, readiness dropping when a dependency dies while liveness holds, and a clean SIGTERM. It found one regression, fixed here at the producer. Task rows lost their forge links in the extracted process: taskURLs read config.Holder, which is nil once the dashboard stops sharing the daemon's process, so every click-through to the issue and the PR silently disappeared. The forge is now resolved once per request from whichever source that process owns, the daemon's configuration or the daemon's published projection. A multi-identity deployment keeps no links rather than gaining wrong ones: the projection carries the default identity alone, so it now says so and the renderer withholds. --- cmd/archie-ui/main_test.go | 686 +++++++++++++++++++++++++++++++ docs/prds/ui-service-boundary.md | 17 +- internal/webui/api_config.go | 13 +- internal/webui/api_tasks.go | 49 ++- internal/webui/api_tasks_test.go | 58 ++- 5 files changed, 808 insertions(+), 15 deletions(-) create mode 100644 cmd/archie-ui/main_test.go diff --git a/cmd/archie-ui/main_test.go b/cmd/archie-ui/main_test.go new file mode 100644 index 000000000..3c1ad6a09 --- /dev/null +++ b/cmd/archie-ui/main_test.go @@ -0,0 +1,686 @@ +// Package main's smoke test runs the real archie-ui binary against a State +// Store and a Gateway reached over loopback gRPC, and drives it through HTTP +// the way an operator's browser does. +// +// The in-process suite (internal/app/archieui) proves the composition; this +// proves the process: flags and configuration file, listener bind, dashboard +// token, SPA assets, streamed chat, an operator task action crossing to the +// Gateway, the degradations the PRD ratified, dependency loss while running, +// and a clean SIGTERM. See docs/prds/ui-service-boundary.md, migration +// sequence step 6. + +package main + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "syscall" + "testing" + "time" + + "google.golang.org/grpc" + + "github.com/samcharles93/archie-core/internal/domain/health" + "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/taskstate" + "github.com/samcharles93/archie-core/internal/webui" +) + +const dashboardToken = "smoke-token" + +// fakeGateway stands in for the archie-gateway process. The dashboard only +// needs the Gateway to answer, stream, and accept an operator action, so the +// rest satisfy messaging.ChatContract without pretending to do more. +type fakeGateway struct { + mu sync.Mutex + actions []string +} + +func (f *fakeGateway) Snapshot(context.Context) (messaging.ChatSnapshot, error) { + return messaging.ChatSnapshot{ + Sessions: []messaging.SessionContext{{ + SessionID: "s1", + Source: messaging.SessionSource{Platform: "web", ChannelID: "dash"}, + }}, + Models: []string{"test/model"}, + ActiveModel: "test/model", + ActivePersonas: map[string]string{}, + CancellationAvailable: true, + }, nil +} + +func (f *fakeGateway) GetSession(context.Context, string) (messaging.SessionContext, bool, error) { + return messaging.SessionContext{}, false, nil +} + +func (f *fakeGateway) RecentMessages(context.Context, string, int) ([]messaging.Message, error) { + return nil, nil +} + +func (f *fakeGateway) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) { + return nil, nil +} + +func (f *fakeGateway) Route(context.Context, messaging.Inbound) (messaging.ChatReply, error) { + return messaging.ChatReply{Text: "routed", SessionID: "s1"}, nil +} + +// Stream emits the contract's documented order: started, a delta, then done. +func (f *fakeGateway) Stream(ctx context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) { + events := make(chan messaging.ChatEvent, 3) + go func() { + defer close(events) + for _, event := range []messaging.ChatEvent{ + {Kind: "started", SessionID: "s1"}, + {Kind: "delta", Text: "hello " + in.Message.Text, SessionID: "s1"}, + {Kind: "done", SessionID: "s1"}, + } { + select { + case events <- event: + case <-ctx.Done(): + return + } + } + }() + return events, nil +} + +func (f *fakeGateway) Cancel(context.Context, string) (messaging.ChatCancellation, error) { + return messaging.ChatCancellation{Cancelled: true}, nil +} + +func (f *fakeGateway) SetPersona(context.Context, string, string) (bool, error) { return false, nil } + +func (f *fakeGateway) ApplyTaskAction(context.Context, string, int64, taskstate.Action) (messaging.TaskActionResult, error) { + return messaging.TaskActionResult{}, nil +} + +func (f *fakeGateway) ApplyOperatorTaskAction(_ context.Context, id int64, action taskstate.Action) (messaging.TaskActionResult, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.actions = append(f.actions, fmt.Sprintf("%d:%s", id, action)) + return messaging.TaskActionResult{TaskID: id, Action: string(action)}, nil +} + +func (f *fakeGateway) applied() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.actions...) +} + +// repoRoot walks up from this test's source directory to the module root, so +// the build works regardless of the harness working directory. +func repoRoot(t *testing.T) string { + t.Helper() + _, file, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("cannot determine test source path") + } + dir := filepath.Dir(file) + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + parent := filepath.Dir(dir) + if parent == dir { + t.Fatal("go.mod not found above test source") + } + dir = parent + } +} + +func buildUIBinary(t *testing.T, dir string) string { + t.Helper() + bin := filepath.Join(dir, "archie-ui") + cmd := exec.CommandContext(t.Context(), "go", "build", "-o", bin, "./cmd/archie-ui") + cmd.Dir = repoRoot(t) + cmd.Env = os.Environ() + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("go build archie-ui: %v\n%s", err, out) + } + return bin +} + +// syncBuffer is a concurrency-safe sink for the subprocess's stderr: the +// os/exec goroutine writes while the test reads it to recover the bound +// address and to report it on failure. +type syncBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuffer) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +// serveGRPC runs register against a fresh loopback listener, returning the +// dial target and a stop func so a test can take the dependency away. +func serveGRPC(t *testing.T, register func(grpc.ServiceRegistrar)) (target string, stop func()) { + t.Helper() + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := grpc.NewServer() + register(server) + go func() { _ = server.Serve(listener) }() + t.Cleanup(server.Stop) + return listener.Addr().String(), server.Stop +} + +// writeUIConfig writes the config.toml an operator would keep: the service +// endpoints the UI dials live in it, so the process is started without +// -gateway-target or -state-target and has to read them itself. The rest is +// what configuration validation requires of any archie config file. +func writeUIConfig(t *testing.T, dir, stateTarget, gatewayTarget string) string { + t.Helper() + path := filepath.Join(dir, "config.toml") + content := fmt.Sprintf(`bot_user = "archie-bot" +db_path = %q +[forge] +type = "github" +host = "https://github.example.com" +token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" } +[[repos]] +owner = "acme" +name = "widget" +[services.state] +target = %q +[services.gateway] +target = %q +`, filepath.Join(dir, "archie.db"), stateTarget, gatewayTarget) + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatalf("write ui config: %v", err) + } + return path +} + +// uiProcess is a running archie-ui, plus the address it actually bound. +type uiProcess struct { + cmd *exec.Cmd + addr string + log *syncBuffer +} + +func startUIProcess(t *testing.T, bin, cfg string) *uiProcess { + t.Helper() + // The process outlives t.Context() deliberately: that context is + // cancelled just before cleanups run, which would SIGKILL archie-ui out + // from under the graceful-shutdown check in stop. Cancelling this one is + // registered first, so it runs last and only backstops a process that + // ignored SIGTERM. + ctx, cancel := context.WithCancel(context.WithoutCancel(t.Context())) + t.Cleanup(cancel) + cmd := exec.CommandContext(ctx, bin, + "-config", cfg, + "-listen", "127.0.0.1:0", + "-token", dashboardToken, + ) + cmd.Env = append(os.Environ(), "ARCHIE_GITHUB_TOKEN=test-token") + var log syncBuffer + cmd.Stderr = &log + cmd.Stdout = &log + if err := cmd.Start(); err != nil { + t.Fatalf("start archie-ui: %v", err) + } + p := &uiProcess{cmd: cmd, log: &log} + t.Cleanup(func() { p.stop(t) }) + + // -listen 127.0.0.1:0 means the kernel picks the port, so the bound + // address comes back out of the process's own startup log. + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) && p.addr == "" { + if cmd.ProcessState != nil { + t.Fatalf("archie-ui exited early:\n%s", log.String()) + } + p.parseAddr() + if p.addr == "" { + time.Sleep(25 * time.Millisecond) + } + } + if p.addr == "" { + t.Fatalf("did not recover the bound address from the log:\n%s", log.String()) + } + waitHealthy(t, p) + return p +} + +func (p *uiProcess) parseAddr() { + scanner := bufio.NewScanner(strings.NewReader(p.log.String())) + for scanner.Scan() { + var record map[string]any + if err := json.Unmarshal(scanner.Bytes(), &record); err != nil { + continue + } + if msg, _ := record["msg"].(string); msg != "archie-ui running" { + continue + } + if addr, ok := record["addr"].(string); ok && addr != "" { + p.addr = addr + return + } + } +} + +func waitHealthy(t *testing.T, p *uiProcess) { + t.Helper() + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) { + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://"+p.addr+"/healthz", nil) + if err != nil { + t.Fatalf("build liveness request: %v", err) + } + if resp, err := http.DefaultClient.Do(req); err == nil { + _ = resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return + } + } + time.Sleep(25 * time.Millisecond) + } + t.Fatalf("/healthz never answered:\n%s", p.log.String()) +} + +// stop ends the process the way a service manager does and reports a +// non-graceful exit, which is how a shutdown-ordering regression surfaces. +func (p *uiProcess) stop(t *testing.T) { + t.Helper() + if p.cmd.Process == nil || p.cmd.ProcessState != nil { + return + } + if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil { + t.Errorf("SIGTERM archie-ui: %v", err) + return + } + done := make(chan error, 1) + go func() { done <- p.cmd.Wait() }() + select { + case err := <-done: + if err != nil { + t.Errorf("archie-ui exited %v after SIGTERM, want a clean shutdown:\n%s", err, p.log.String()) + } + case <-time.After(20 * time.Second): + _ = p.cmd.Process.Kill() + t.Errorf("archie-ui did not exit within 20s of SIGTERM:\n%s", p.log.String()) + } +} + +// reply is one dashboard response, already read and closed. The assertions +// want the status and the bytes rather than a live body, and handing back a +// closed value keeps the close where the read is. +type reply struct { + status int + header http.Header + body []byte +} + +func (r reply) cookies() []*http.Cookie { + return (&http.Response{Header: r.header}).Cookies() +} + +// dashboard is a browser-shaped client for the running process. +type dashboard struct { + t *testing.T + base string + client *http.Client +} + +// noRedirect returns a dashboard that reports a redirect rather than +// following it, so an exchange can be inspected instead of chased. Following +// it here would land on the clean URL without the cookie jar a browser has. +func (d dashboard) noRedirect() dashboard { + d.client = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }} + return d +} + +func (d dashboard) do(req *http.Request) reply { + d.t.Helper() + client := d.client + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + d.t.Fatalf("%s %s: %v", req.Method, req.URL.Path, err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + d.t.Fatalf("read %s: %v", req.URL.Path, err) + } + return reply{status: resp.StatusCode, header: resp.Header, body: body} +} + +func (d dashboard) request(method, path, body string, authorized bool) *http.Request { + d.t.Helper() + var reader io.Reader = http.NoBody + if body != "" { + reader = strings.NewReader(body) + } + req, err := http.NewRequestWithContext(d.t.Context(), method, d.base+path, reader) + if err != nil { + d.t.Fatalf("build %s %s: %v", method, path, err) + } + if authorized { + req.Header.Set("Authorization", "Bearer "+dashboardToken) + } + if body != "" { + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Archie-CSRF", "1") + } + return req +} + +func (d dashboard) get(path string) reply { + d.t.Helper() + return d.do(d.request(http.MethodGet, path, "", true)) +} + +// seedStore fills a real task database and publishes the configuration +// projection, so everything the dashboard renders arrives over the wire from +// a store this process never opens. +func seedStore(t *testing.T, dir string) *store.Store { + t.Helper() + st, err := store.Open(t.Context(), filepath.Join(dir, "tasks.sqlite")) + if err != nil { + t.Fatalf("open store: %v", err) + } + t.Cleanup(func() { _ = st.Close() }) + + if _, err := st.EnqueueIssue(t.Context(), "acme", "widget", 7, "smoke task", "body", "", ""); err != nil { + t.Fatalf("seed task: %v", err) + } + tasks, err := st.Tasks(t.Context(), 10) + if err != nil || len(tasks) != 1 { + t.Fatalf("seeded tasks = %d (%v), want 1", len(tasks), err) + } + seeded := tasks[0] + seeded.PRNumber = 34 + if err := st.Update(t.Context(), &seeded); err != nil { + t.Fatalf("record PR number: %v", err) + } + + published, err := json.Marshal(webui.ConfigView{ + Identity: webui.IdentityView{ + BotUser: "archie-bot", + ForgeType: "github", + ForgeHost: "https://github.example.com", + }, + }) + if err != nil { + t.Fatal(err) + } + if err := st.PutConfigSnapshot(t.Context(), store.ConfigSnapshot{ + Schema: webui.ConfigViewSchema, Document: published, + }); err != nil { + t.Fatalf("publish config snapshot: %v", err) + } + return st +} + +func TestUIProcessServesTheDashboardAgainstLiveDependencies(t *testing.T) { + dir := t.TempDir() + st := seedStore(t, dir) + gateway := &fakeGateway{} + + stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) { + staterpc.RegisterServer(r, staterpc.Deps{ + Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, + Log: slog.New(slog.DiscardHandler), + }) + }) + gatewayTarget, _ := serveGRPC(t, func(r grpc.ServiceRegistrar) { + gatewayrpc.RegisterServer(r, gateway) + }) + + ui := startUIProcess(t, buildUIBinary(t, dir), writeUIConfig(t, dir, stateTarget, gatewayTarget)) + d := dashboard{t: t, base: "http://" + ui.addr} + + t.Run("liveness stays unauthenticated", func(t *testing.T) { + for _, path := range []string{"/healthz", "/health"} { + if got := d.do(d.request(http.MethodGet, path, "", false)); got.status != http.StatusOK { + t.Errorf("GET %s = %d without a token, want 200: probes must not need the dashboard token", path, got.status) + } + } + }) + + t.Run("an unauthenticated API request is refused", func(t *testing.T) { + if got := d.do(d.request(http.MethodGet, "/api/tasks", "", false)); got.status != http.StatusUnauthorized { + t.Errorf("GET /api/tasks = %d without a token, want 401", got.status) + } + wrong := d.request(http.MethodGet, "/api/tasks", "", false) + wrong.Header.Set("Authorization", "Bearer not-the-token") + if got := d.do(wrong); got.status != http.StatusUnauthorized { + t.Errorf("GET /api/tasks = %d with a wrong token, want 401", got.status) + } + }) + + t.Run("the token in the URL is exchanged for a cookie", func(t *testing.T) { + got := d.noRedirect().do(d.request(http.MethodGet, "/?t="+dashboardToken, "", false)) + if got.status != http.StatusSeeOther { + t.Fatalf("GET /?t= = %d, want 303 onto the clean URL", got.status) + } + var carried bool + for _, cookie := range got.cookies() { + if cookie.Value == dashboardToken && cookie.HttpOnly { + carried = true + } + } + if !carried { + t.Errorf("no HttpOnly cookie carried the token; it would stay in browser history (%v)", got.cookies()) + } + }) + + t.Run("task rows carry forge links from the published projection", func(t *testing.T) { + got := d.get("/api/tasks") + if got.status != http.StatusOK { + t.Fatalf("GET /api/tasks = %d (%s), want 200", got.status, got.body) + } + var rows []struct { + ID int64 `json:"id"` + RepoURL string `json:"repo_url"` + IssueURL string `json:"issue_url"` + PRURL string `json:"pr_url"` + } + if err := json.Unmarshal(got.body, &rows); err != nil { + t.Fatalf("decode task rows: %v (%s)", err, got.body) + } + if len(rows) != 1 { + t.Fatalf("task rows = %d, want the 1 seeded behind the State Store (%s)", len(rows), got.body) + } + const repoURL = "https://github.example.com/acme/widget" + if rows[0].RepoURL != repoURL || rows[0].IssueURL != repoURL+"/issues/7" || rows[0].PRURL != repoURL+"/pull/34" { + t.Errorf("forge links = %q, %q, %q; want them built from the daemon's published projection, since this process holds no configuration of its own", + rows[0].RepoURL, rows[0].IssueURL, rows[0].PRURL) + } + }) + + t.Run("the SPA and its assets are served", func(t *testing.T) { + index := d.get("/") + if index.status != http.StatusOK || !bytes.Contains(bytes.ToLower(index.body), []byte(" 0, + Models: cfg.Models, + Providers: providersView(cfg.Providers), Budgets: BudgetsView{ MaxSteps: cfg.Budgets.MaxSteps, WallClock: cfg.Budgets.WallClock.Std().String(), diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index ae0ce0f30..f22c83a2c 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -54,9 +54,10 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } + forge := s.resolveForge(r.Context()) views := make([]taskView, len(tasks)) for i := range tasks { - repoURL, issueURL, prURL := s.taskURLs(tasks[i]) + repoURL, issueURL, prURL := taskURLs(tasks[i], forge(tasks[i])) views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL} } writeJSON(w, views) @@ -70,21 +71,51 @@ type taskView struct { PRURL string `json:"pr_url,omitempty"` } -func (s *Server) taskURLs(task task.Task) (repoURL, issueURL, prURL string) { - if s.Cfg == nil { +// forgeCoordinates locate a repository on its forge: the base URL, and the +// forge type that decides the pull-request path segment. +type forgeCoordinates struct { + host string + forgeType string +} + +// resolveForge reads the forge layout once for a request and returns each +// task's coordinates from it. +// +// The daemon holds the configuration and resolves per task, so a deployment +// with several identities links each task to its own forge. The UI process +// holds none and reads the projection the daemon published instead, which +// carries the default identity alone -- so where that is not the whole +// picture it withholds the links rather than pointing them at the wrong +// forge. Publishing per-identity forges is what a multi-identity dashboard +// needs, and it is a projection change, not a rendering one. +func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates { + if s.Cfg != nil { + cfg := s.Cfg.Get() + return func(t task.Task) forgeCoordinates { + forge := forgeConfigForTask(cfg, t) + return forgeCoordinates{host: forge.Host, forgeType: forge.Type} + } + } + unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} } + view, ok, err := s.configSource()(ctx) + if err != nil || !ok || view.MultiIdentity { + return unlinked + } + published := forgeCoordinates{host: view.Identity.ForgeHost, forgeType: view.Identity.ForgeType} + return func(task.Task) forgeCoordinates { return published } +} + +func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL string) { + if forge.host == "" || task.Owner == "" || task.Repo == "" { return "", "", "" } - forgeCfg := forgeConfigForTask(s.Cfg.Get(), task) - if forgeCfg.Host == "" || task.Owner == "" || task.Repo == "" { - return "", "", "" - } - repoURL = strings.TrimRight(forgeCfg.Host, "/") + "/" + url.PathEscape(task.Owner) + "/" + url.PathEscape(task.Repo) + repoURL = strings.TrimRight(forge.host, "/") + "/" + url.PathEscape(task.Owner) + "/" + url.PathEscape(task.Repo) if task.IsForgeBacked() && task.IssueNumber > 0 { issueURL = repoURL + "/issues/" + strconv.Itoa(task.IssueNumber) } if task.PRNumber > 0 { segment := "pull" - if forgeCfg.Type == "gitea" { + if forge.forgeType == "gitea" { segment = "pulls" } prURL = repoURL + "/" + segment + "/" + strconv.Itoa(task.PRNumber) diff --git a/internal/webui/api_tasks_test.go b/internal/webui/api_tasks_test.go index ee2945f24..bf3f849a1 100644 --- a/internal/webui/api_tasks_test.go +++ b/internal/webui/api_tasks_test.go @@ -7,7 +7,9 @@ package webui import ( "bytes" + "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -30,19 +32,71 @@ func TestTaskURLsUseOwningForgeRoutes(t *testing.T) { })} task := workflow.Task{Owner: "acme", Repo: "widget", IssueNumber: 12, PRNumber: 34, Identity: "gitea"} - repoURL, issueURL, prURL := srv.taskURLs(task) + forge := srv.resolveForge(t.Context()) + repoURL, issueURL, prURL := taskURLs(task, forge(task)) if repoURL != "https://gitea.example/acme/widget" || issueURL != repoURL+"/issues/12" || prURL != repoURL+"/pulls/34" { t.Fatalf("URLs = %q, %q, %q; want canonical Gitea routes", repoURL, issueURL, prURL) } task.Identity = "" task.Owner, task.Repo = "other", "repo" - _, _, prURL = srv.taskURLs(task) + _, _, prURL = taskURLs(task, forge(task)) if prURL != "https://github.example/other/repo/pull/34" { t.Fatalf("GitHub PR URL = %q", prURL) } } +// A process with no configuration of its own still has to render the links, +// or the extracted dashboard loses every click-through to the issue and the +// pull request it opened. The daemon's published projection is where they +// come from once the holder is gone. +func TestTaskURLsFallBackToThePublishedProjection(t *testing.T) { + tests := []struct { + name string + view ConfigView + ok bool + err error + wantPR string + wantURL string + }{ + { + name: "published projection", + view: ConfigView{Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"}}, + ok: true, + wantURL: "https://github.example/acme/widget", + wantPR: "https://github.example/acme/widget/pull/34", + }, + { + name: "multi-identity publishes only the default forge, so links are withheld", + view: ConfigView{ + Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"}, + MultiIdentity: true, + }, + ok: true, + }, + { + name: "no snapshot published yet", + }, + { + name: "snapshot read failed", + err: errors.New("state store down"), + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := &Server{ConfigSource: func(context.Context) (ConfigView, bool, error) { + return tc.view, tc.ok, tc.err + }} + task := workflow.Task{Owner: "acme", Repo: "widget", IssueNumber: 12, PRNumber: 34} + forge := srv.resolveForge(t.Context()) + repoURL, _, prURL := taskURLs(task, forge(task)) + if repoURL != tc.wantURL || prURL != tc.wantPR { + t.Fatalf("repo/PR URLs = %q, %q; want %q, %q", repoURL, prURL, tc.wantURL, tc.wantPR) + } + }) + } +} + // Approve requeues from the task's own recorded state rather than anything // the caller supplies, so a stale dashboard cannot approve a task twice. func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) {