From e2e86bf2d82d45516c098997cf9cd6201be5e972 Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Sun, 25 Oct 2026 02:08:39 +0300 Subject: [PATCH] tui: artifact open falls back to a free port and shows why albedo web did not start Signed-off-by: dawn <90008@klbr.net> --- cli/internal/tui/artifact.go | 38 +++++++++++++++++++++++-- cli/internal/tui/artifact_test.go | 46 +++++++++++++++++++++++++++++++ robot-docs/artifacts.md | 2 +- 3 files changed, 82 insertions(+), 4 deletions(-) diff --git a/cli/internal/tui/artifact.go b/cli/internal/tui/artifact.go index 087ba3fff..5e45ac908 100644 --- a/cli/internal/tui/artifact.go +++ b/cli/internal/tui/artifact.go @@ -89,11 +89,27 @@ func findOrStartWeb(ctx context.Context) (string, error) { if err != nil { return "", fmt.Errorf("cannot find albedo web: %w", err) } - log, err := os.OpenFile(filepath.Join(filepath.Dir(path), "web.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + return startWeb(ctx, executable, path) +} + +// startWeb starts albedo web on its usual port, so the link people know stays +// put. If that child dies at once (the port is taken) any free port will do: +// artifacts open on whatever server runs. +func startWeb(ctx context.Context, executable, path string) (string, error) { + base, err := launchWeb(ctx, executable, path) + if err == nil || ctx.Err() != nil { + return base, err + } + return launchWeb(ctx, executable, path, "--port", "0") +} + +func launchWeb(ctx context.Context, executable, path string, extra ...string) (string, error) { + logPath := filepath.Join(filepath.Dir(path), "web.log") + log, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) if err != nil { return "", fmt.Errorf("cannot start albedo web: %w", err) } - command := exec.Command(executable, "web", "--no-open") + command := exec.Command(executable, append([]string{"web", "--no-open"}, extra...)...) command.Stdout, command.Stderr, command.Env = log, log, os.Environ() command.SysProcAttr = &syscall.SysProcAttr{Setsid: true} if err := command.Start(); err != nil { @@ -101,13 +117,19 @@ func findOrStartWeb(ctx context.Context) (string, error) { return "", fmt.Errorf("cannot start albedo web: %w", err) } _ = log.Close() - go func() { _ = command.Wait() }() // reaped when it stops, not left as a zombie + exited := make(chan error, 1) + go func() { exited <- command.Wait() }() // also reaps it when it stops ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() for { select { case <-ctx.Done(): return "", errors.New("albedo web did not start within 8 seconds") + case err := <-exited: + if err != nil { + return "", webFailure(logPath, err) + } + exited = nil // it started its background server and left case <-ticker.C: if manifest, err := webui.ReadManifest(path); err == nil && webui.ManifestAlive(manifest) { return manifest.URL, nil @@ -115,3 +137,13 @@ func findOrStartWeb(ctx context.Context) (string, error) { } } } + +// webFailure is the last line the server logged, which says why it stopped. +func webFailure(logPath string, err error) error { + output, _ := os.ReadFile(logPath) + text := strings.TrimSpace(string(output)) + if text == "" { + text = err.Error() + } + return errors.New(text[strings.LastIndex(text, "\n")+1:]) +} diff --git a/cli/internal/tui/artifact_test.go b/cli/internal/tui/artifact_test.go index ff368e44e..cb6f6f733 100644 --- a/cli/internal/tui/artifact_test.go +++ b/cli/internal/tui/artifact_test.go @@ -3,6 +3,7 @@ package tui import ( "albedo/cli/internal/daemon" "albedo/cli/internal/webui" + "context" "encoding/json" "net/http" "net/http/httptest" @@ -10,6 +11,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func TestFindOrStartWebUsesLiveManifest(t *testing.T) { @@ -47,3 +49,47 @@ func TestClosedBurstKeepsTheNewestArtifactRow(t *testing.T) { t.Fatalf("a closed burst should offer the newest version once: %q", rendered) } } + +// fakeWeb stands in for the albedo binary: the script is what `albedo web +// --no-open` does, and a live manifest is what a started server leaves behind. +func fakeWeb(t *testing.T, script string) (executable, manifest string) { + t.Helper() + home := t.TempDir() + t.Setenv("ALBEDO_HOME", home) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) + t.Cleanup(server.Close) + data, _ := json.Marshal(webui.Manifest{PID: os.Getpid(), URL: server.URL}) + t.Setenv("FAKE_WEB_MANIFEST", string(data)) + executable = filepath.Join(t.TempDir(), "albedo") + if err := os.WriteFile(executable, []byte("#!/bin/sh\n"+script), 0o755); err != nil { + t.Fatal(err) + } + return executable, filepath.Join(home, "web.json") +} + +func TestStartWebFallsBackToAFreePortWhenTheDefaultIsTaken(t *testing.T) { + executable, manifest := fakeWeb(t, `case "$*" in +*"--port 0"*) printf '%s' "$FAKE_WEB_MANIFEST" > "$ALBEDO_HOME/web.json" ;; +*) echo "cannot listen on 0.0.0.0:4317: address already in use" >&2; exit 1 ;; +esac`) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + got, err := startWeb(ctx, executable, manifest) + if err != nil || !strings.HasPrefix(got, "http://127.0.0.1:") { + t.Fatalf("startWeb = %q, %v; want the server the --port 0 attempt started", got, err) + } +} + +func TestStartWebReportsWhyTheServerDidNotStart(t *testing.T) { + executable, manifest := fakeWeb(t, `echo "cannot listen on 0.0.0.0:4317: address already in use" >&2; exit 1`) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + started := time.Now() + _, err := startWeb(ctx, executable, manifest) + if err == nil || !strings.Contains(err.Error(), "address already in use") { + t.Fatalf("startWeb error = %v; want the child's own message", err) + } + if time.Since(started) > time.Second { + t.Fatalf("a dead child was waited on for %s", time.Since(started)) + } +} diff --git a/robot-docs/artifacts.md b/robot-docs/artifacts.md index 9e72f3348..3408f61db 100644 --- a/robot-docs/artifacts.md +++ b/robot-docs/artifacts.md @@ -106,4 +106,4 @@ The page and the window speak JSON-RPC 2.0 over `postMessage`, a subset of [MCP **Web.** A new artifact activity in a chat on the board opens a window beside that chat, tied to it like a review; only activities that arrive while the chat is open do this, never ones loaded from history. A window for an artifact that is already open moves to the new version in place. The view pans to it only when its chat is the selected window. A closed window stays closed; the chat's row says it changed and opens it. A window can be pinned to a version, and then it stays there. On a phone the artifact opens inside the chat, as a review does. A page icon in the chat's title bar (on the phone, above the composer; `ArtifactsButton.svelte`) counts the artifacts the session made and lists them, newest change first, to open one; the list is read when it opens and when the session's work stops. The palette finds artifacts by title; `open an artifact…` and `delete an artifact…` list the whole gallery. -**Terminal.** An `artifact` activity is the row `↗ open artifact albedo made for you: ` (`… albedo updated: <title> · v<n>` after the first version), under its burst whether the burst is open or not. A click opens the page in the browser: the TUI reads the artifact's key from `GET items/{id}`, finds `albedo web` through `web.json` (starting `albedo web --no-open` when it is not running) and opens the version the row names, `<url>/frame/{id}.{key}/{version}/`; the first version's row names none, so it opens `<url>/frame/{id}.{key}/latest/`, which reloads itself as the agent revises the page. +**Terminal.** An `artifact` activity is the row `↗ open artifact albedo made for you: <title>` (`… albedo updated: <title> · v<n>` after the first version), under its burst whether the burst is open or not. A click opens the page in the browser: the TUI reads the artifact's key from `GET items/{id}`, finds `albedo web` through `web.json` (starting `albedo web --no-open` when it is not running, on another port if its usual one is taken, and showing the server's own message if it still does not start) and opens the version the row names, `<url>/frame/{id}.{key}/{version}/`; the first version's row names none, so it opens `<url>/frame/{id}.{key}/latest/`, which reloads itself as the agent revises the page. -- knotmirror 0.0.1