Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(cli): fail fast with actionable daemon startup errors

YYClaw7d04b1d9a3e1
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index abeee1fb69..ba7886db6d 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -236,6 +236,33 @@ func healthPortForProfile(profile string) int {
// --- daemon start ---
+// daemonExecutable resolves the binary to spawn as the background daemon
+// child. Tests override it: spawning the resolved executable there would fork
+// the test binary itself, which ignores the daemon args and re-runs the suite.
+var daemonExecutable = selfexec.Resolve
+
+// requireDaemonAuth fails fast when the user never ran `multica login`. The
+// daemon child performs the same check (resolveAuth) and dies immediately,
+// but the background parent can't see that exit — it would poll the health
+// port for the full 45s readiness window and then print a vague "check logs"
+// warning. Checking before spawning turns that silent stall into an
+// immediate, actionable error. Mirrors daemon.resolveAuth: the daemon only
+// authenticates via the stored config token, never MULTICA_TOKEN.
+func requireDaemonAuth(profile string) error {
+ cfg, err := cli.LoadCLIConfigForProfile(profile)
+ if err != nil {
+ return fmt.Errorf("load CLI config: %w", err)
+ }
+ if cfg.Token == "" {
+ loginHint := "multica login"
+ if profile != "" {
+ loginHint = fmt.Sprintf("multica login --profile %s", profile)
+ }
+ return fmt.Errorf("you are not logged in. Run '%s' first, then start the daemon", loginHint)
+ }
+ return nil
+}
+
func runDaemonStart(cmd *cobra.Command, _ []string) error {
foreground, _ := cmd.Flags().GetBool("foreground")
if foreground {
@@ -261,8 +288,12 @@ func runDaemonBackground(cmd *cobra.Command) error {
return fmt.Errorf("%s is already running (pid %v). Use 'daemon restart' to restart it", label, int(pid))
}
+ if err := requireDaemonAuth(profile); err != nil {
+ return err
+ }
+
// Resolve current executable so the foreground child reuses this binary.
- exePath, err := selfexec.Resolve()
+ exePath, err := daemonExecutable()
if err != nil {
return fmt.Errorf("resolve executable path: %w", err)
}
@@ -289,6 +320,18 @@ func runDaemonBackground(cmd *cobra.Command) error {
// user-facing hints below.
logPath := daemonLogPathForProfile(profile)
+ // Remember where both logs end now so an early-death report below can show
+ // only what THIS startup attempt wrote, not stale history. The err-log
+ // offset is taken after openBoundedErrLog, which may have rolled the file.
+ var logOffset int64
+ if info, statErr := os.Stat(logPath); statErr == nil {
+ logOffset = info.Size()
+ }
+ var errLogOffset int64
+ if info, statErr := os.Stat(errLogPath); statErr == nil {
+ errLogOffset = info.Size()
+ }
+
child := exec.Command(exePath, args...)
child.Stdout = logFile
child.Stderr = logFile
@@ -319,8 +362,15 @@ func runDaemonBackground(cmd *cobra.Command) error {
logFile.Close()
pid := child.Process.Pid
- // Detach: we don't Wait() on the child — it runs independently.
- child.Process.Release()
+ // Watch for early death instead of Release()ing right away: a child that
+ // fails preflight (unreachable server, token rejected with 401, ...) exits
+ // within seconds, and without this signal the readiness poll below would
+ // blindly run out its full window before printing a vague warning. The
+ // goroutine leaks Wait() for the (short) remainder of this process when
+ // the daemon starts fine — the child is never killed by it and keeps
+ // running independently, same as with Release().
+ waitCh := make(chan error, 1)
+ go func() { waitCh <- child.Wait() }()
// Write PID file.
pidPath := daemonPIDPathForProfile(profile)
@@ -339,7 +389,16 @@ func runDaemonBackground(cmd *cobra.Command) error {
started := false
lastStatus := ""
for time.Now().Before(deadline) {
- time.Sleep(500 * time.Millisecond)
+ select {
+ case waitErr := <-waitCh:
+ return daemonStartupFailureError(daemonStartupLogs{
+ logPath: logPath,
+ logOffset: logOffset,
+ errLogPath: errLogPath,
+ errLogOffset: errLogOffset,
+ }, waitErr, profile, resolveDaemonServerURL(cmd, profile))
+ case <-time.After(500 * time.Millisecond):
+ }
hctx, hcancel := context.WithTimeout(context.Background(), 2*time.Second)
health = checkDaemonHealthOnPort(hctx, healthPort)
hcancel()
@@ -367,6 +426,144 @@ func runDaemonBackground(cmd *cobra.Command) error {
return nil
}
+// resolveDaemonServerURL resolves the server URL the daemon will talk to,
+// in the same precedence order the foreground daemon uses: --server-url flag,
+// MULTICA_SERVER_URL env, then the stored CLI config for the profile.
+func resolveDaemonServerURL(cmd *cobra.Command, profile string) string {
+ serverURL := cli.FlagOrEnv(cmd, "server-url", "MULTICA_SERVER_URL", "")
+ if serverURL == "" {
+ if c, err := cli.LoadCLIConfigForProfile(profile); err == nil && c.ServerURL != "" {
+ serverURL = c.ServerURL
+ }
+ }
+ return serverURL
+}
+
+// daemonStartupLogs names the two sinks a failed startup attempt may have
+// written to: the child's structured slog output lands in the rotating
+// daemon.log, while raw stderr — Go panics and the final cobra "Error: ..."
+// line — lands in the crash sink (daemon.err.log). Both carry an offset
+// recorded before the spawn so the report covers only this attempt.
+type daemonStartupLogs struct {
+ logPath string
+ logOffset int64
+ errLogPath string
+ errLogOffset int64
+}
+
+// daemonStartupFailureError turns a daemon child that exited before ever
+// reporting ready into a friendly, actionable error. The two failure modes
+// users actually hit — stored token rejected by the server, server not
+// reachable — are recognized from what this startup attempt appended to the
+// structured log and the crash sink, and rendered as one reason line plus a
+// next step. Anything else falls back to a log excerpt with DBG/INF noise
+// dropped.
+func daemonStartupFailureError(logs daemonStartupLogs, waitErr error, profile, serverURL string) error {
+ lines := readLogTailSince(logs.logPath, logs.logOffset, 40)
+ crashLines := readLogTailSince(logs.errLogPath, logs.errLogOffset, 40)
+ joined := strings.Join(append(append([]string{}, lines...), crashLines...), "\n")
+
+ loginHint := "multica login"
+ if profile != "" {
+ loginHint += " --profile " + profile
+ }
+
+ switch {
+ case strings.Contains(joined, "auth token rejected") ||
+ strings.Contains(joined, "returned 401") ||
+ strings.Contains(joined, "not authenticated"):
+ return fmt.Errorf("daemon failed to start: the server rejected your login token (it may have expired or been revoked).\nRun '%s' to sign in again, then rerun 'multica daemon start'.\nFull log: %s", loginHint, logs.logPath)
+ case strings.Contains(joined, "connection refused") ||
+ strings.Contains(joined, "no such host") ||
+ strings.Contains(joined, "i/o timeout") ||
+ strings.Contains(joined, "network is unreachable"):
+ target := "the Multica server"
+ if serverURL != "" {
+ target += " at " + serverURL
+ }
+ return fmt.Errorf("daemon failed to start: cannot reach %s.\nMake sure the server is running and reachable, then rerun 'multica daemon start'.\nFull log: %s", target, logs.logPath)
+ }
+
+ var b strings.Builder
+ if exitErr := (&exec.ExitError{}); errors.As(waitErr, &exitErr) {
+ fmt.Fprintf(&b, "daemon exited during startup (%s).", exitErr)
+ } else {
+ b.WriteString("daemon exited during startup.")
+ }
+ excerpt := filterDaemonLogNoise(lines, 5)
+ // Crash output is already raw (panics, the final cobra error line) — no
+ // noise filter, just cap it like the structured excerpt.
+ if len(crashLines) > 5 {
+ crashLines = crashLines[len(crashLines)-5:]
+ }
+ excerpt = append(excerpt, crashLines...)
+ if len(excerpt) > 0 {
+ b.WriteString("\nLog output:")
+ for _, line := range excerpt {
+ fmt.Fprintf(&b, "\n %s", line)
+ }
+ }
+ fmt.Fprintf(&b, "\nFull log: %s", logs.logPath)
+ if len(crashLines) > 0 {
+ fmt.Fprintf(&b, "\nCrash output: %s", logs.errLogPath)
+ }
+ return errors.New(b.String())
+}
+
+// filterDaemonLogNoise drops DBG/INF log lines from an excerpt, keeping
+// WRN/ERR entries and plain (non-slog) lines such as the final error the
+// child printed before exiting, capped to the last max lines.
+func filterDaemonLogNoise(lines []string, max int) []string {
+ out := make([]string, 0, len(lines))
+ for _, line := range lines {
+ if strings.Contains(line, " DBG ") || strings.Contains(line, " INF ") {
+ continue
+ }
+ out = append(out, line)
+ }
+ if len(out) > max {
+ out = out[len(out)-max:]
+ }
+ return out
+}
+
+// readLogTailSince returns up to maxLines of the log content appended after
+// sinceOffset. Reads are capped at 64 KiB so a huge burst can't balloon the
+// error report; on any read problem it returns nil and the caller just points
+// at the log file instead.
+func readLogTailSince(logPath string, sinceOffset int64, maxLines int) []string {
+ f, err := os.Open(logPath)
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+
+ const readCap = 64 * 1024
+ if info, err := f.Stat(); err == nil && info.Size()-sinceOffset > readCap {
+ sinceOffset = info.Size() - readCap
+ }
+ if _, err := f.Seek(sinceOffset, io.SeekStart); err != nil {
+ return nil
+ }
+ data, err := io.ReadAll(io.LimitReader(f, readCap))
+ if err != nil || len(data) == 0 {
+ return nil
+ }
+
+ lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")
+ out := make([]string, 0, maxLines)
+ for _, line := range lines {
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
+ out = append(out, line)
+ }
+ if len(out) > maxLines {
+ out = out[len(out)-maxLines:]
+ }
+ return out
+}
+
// buildDaemonStartArgs constructs args for the background child process.
func buildDaemonStartArgs(cmd *cobra.Command) []string {
args := []string{"daemon", "start", "--foreground"}
@@ -452,12 +649,7 @@ func runDaemonForeground(cmd *cobra.Command) error {
logger = logger_pkg.NewWriterLoggerDefault("daemon", logRotator)
}
- serverURL := cli.FlagOrEnv(cmd, "server-url", "MULTICA_SERVER_URL", "")
- if serverURL == "" {
- if c, err := cli.LoadCLIConfigForProfile(profile); err == nil && c.ServerURL != "" {
- serverURL = c.ServerURL
- }
- }
+ serverURL := resolveDaemonServerURL(cmd, profile)
overrides := daemon.Overrides{
ServerURL: serverURL,
DaemonID: flagString(cmd, "daemon-id"),
@@ -590,15 +782,70 @@ func runDaemonForeground(cmd *cobra.Command) error {
// --- daemon restart ---
+// requireDaemonRestartPreflight validates, before a running daemon is
+// stopped, that its replacement could actually start. requireDaemonAuth's
+// empty-token check is not enough here: a stored token can be expired or
+// revoked, and the server can be unreachable — either passes the local check,
+// kills the working daemon in the stop phase, and then fails the replacement
+// child's preflight, leaving no daemon at all (#5165). So probe the server
+// the daemon will talk to with the stored token (same whoami call as
+// `multica auth status`) and refuse to touch the running daemon on failure.
+func requireDaemonRestartPreflight(cmd *cobra.Command, profile string) error {
+ if err := requireDaemonAuth(profile); err != nil {
+ return err
+ }
+ cfg, err := cli.LoadCLIConfigForProfile(profile)
+ if err != nil {
+ return fmt.Errorf("load CLI config: %w", err)
+ }
+
+ rawURL := resolveDaemonServerURL(cmd, profile)
+ if rawURL == "" {
+ rawURL = daemon.DefaultServerURL
+ }
+ baseURL, err := daemon.NormalizeServerBaseURL(rawURL)
+ if err != nil {
+ return fmt.Errorf("refusing to restart: invalid server URL %q: %w", rawURL, err)
+ }
+
+ loginHint := "multica login"
+ if profile != "" {
+ loginHint += " --profile " + profile
+ }
+
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+ if err := cli.NewAPIClient(baseURL, "", cfg.Token).GetJSON(ctx, "/api/me", nil); err != nil {
+ var httpErr *cli.HTTPError
+ if errors.As(err, &httpErr) {
+ if httpErr.StatusCode == http.StatusUnauthorized {
+ return fmt.Errorf("refusing to restart: the server rejected your login token (it may have expired or been revoked); the running daemon was left untouched.\nRun '%s' to sign in again, then rerun 'multica daemon restart'", loginHint)
+ }
+ return fmt.Errorf("refusing to restart: preflight check against %s failed (%w); the running daemon was left untouched", baseURL, err)
+ }
+ return fmt.Errorf("refusing to restart: cannot reach the Multica server at %s (%w); the running daemon was left untouched.\nMake sure the server is running and reachable, then rerun 'multica daemon restart'", baseURL, err)
+ }
+ return nil
+}
+
func runDaemonRestart(cmd *cobra.Command, args []string) error {
profile := resolveProfile(cmd)
healthPort := healthPortForProfile(profile)
- // Stop if running.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
health := checkDaemonHealthOnPort(ctx, healthPort)
if daemonAlive(health) {
+ // Validate the restart can succeed BEFORE the stop phase, not just
+ // inside the start phase: a missing/revoked token or an unreachable
+ // server would otherwise kill the running daemon and then fail to
+ // start a replacement, leaving no daemon at all. When nothing is
+ // running there is nothing to lose, so the cheaper start-path checks
+ // (empty-token guard + early child-exit detection) handle it without
+ // this extra server round-trip.
+ if err := requireDaemonRestartPreflight(cmd, profile); err != nil {
+ return err
+ }
pid, _ := health["pid"].(float64)
if pid > 0 {
fmt.Fprintf(os.Stderr, "Stopping daemon (pid %d)...\n", int(pid))
diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.go
index 53efbfa15a..136cfc4483 100644
--- a/server/cmd/multica/cmd_daemon_test.go
+++ b/server/cmd/multica/cmd_daemon_test.go
@@ -2,14 +2,21 @@ package main
import (
"bytes"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
"os"
+ "os/exec"
"path/filepath"
"strings"
"testing"
"time"
- "github.com/multica-ai/multica/server/internal/daemon"
"github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+ "github.com/multica-ai/multica/server/internal/daemon"
)
// TestDaemonAlive locks in the liveness predicate the lifecycle commands rely
@@ -112,6 +119,380 @@ func TestPrintDaemonStatusOmitsVersionWhenMissing(t *testing.T) {
}
}
+// TestRequireDaemonAuth pins the fail-fast contract for `daemon start`: a
+// user who never ran `multica login` must get an immediate, actionable error
+// from the parent process instead of a 45s health poll against a child that
+// already died with "not authenticated".
+func TestRequireDaemonAuth(t *testing.T) {
+ t.Run("not logged in", func(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ err := requireDaemonAuth("")
+ if err == nil || !strings.Contains(err.Error(), "multica login") {
+ t.Fatalf("requireDaemonAuth() = %v, want error mentioning 'multica login'", err)
+ }
+ })
+
+ t.Run("not logged in with profile", func(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ err := requireDaemonAuth("staging")
+ if err == nil || !strings.Contains(err.Error(), "multica login --profile staging") {
+ t.Fatalf("requireDaemonAuth(staging) = %v, want error mentioning profile login hint", err)
+ }
+ })
+
+ t.Run("authenticated", func(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ if err := cli.SaveCLIConfig(cli.CLIConfig{Token: "mul_test_token"}); err != nil {
+ t.Fatalf("SaveCLIConfig: %v", err)
+ }
+ if err := requireDaemonAuth(""); err != nil {
+ t.Fatalf("requireDaemonAuth() = %v, want nil", err)
+ }
+ })
+}
+
+// TestDaemonStartBackgroundUnauthenticatedFailsFast exercises the real
+// `daemon start` background path: without a stored token it must error out
+// before spawning the child (and long before the 45s readiness wait).
+func TestDaemonStartBackgroundUnauthenticatedFailsFast(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+
+ cmd := &cobra.Command{Use: "start"}
+ cmd.Flags().Bool("foreground", false, "")
+ cmd.Flags().String("profile", "", "")
+ // A named profile keeps the pre-spawn health probe off the default port,
+ // so a daemon running on the developer machine can't turn this into an
+ // "already running" error.
+ if err := cmd.Flags().Set("profile", "authtest-fail-fast"); err != nil {
+ t.Fatalf("set profile flag: %v", err)
+ }
+
+ start := time.Now()
+ err := runDaemonStart(cmd, nil)
+ elapsed := time.Since(start)
+
+ if err == nil || !strings.Contains(err.Error(), "multica login --profile authtest-fail-fast") {
+ t.Fatalf("runDaemonStart() = %v, want not-logged-in error with login hint", err)
+ }
+ if elapsed > 10*time.Second {
+ t.Fatalf("runDaemonStart took %s, want fail-fast before the readiness wait", elapsed)
+ }
+}
+
+// TestReadLogTailSince pins the log-excerpt helper used when the daemon child
+// dies during startup: only content appended after the recorded offset is
+// shown, capped to the last maxLines lines.
+func TestReadLogTailSince(t *testing.T) {
+ t.Parallel()
+
+ logPath := filepath.Join(t.TempDir(), "daemon.log")
+ if err := os.WriteFile(logPath, []byte("old line 1\nold line 2\n"), 0o644); err != nil {
+ t.Fatalf("write log: %v", err)
+ }
+ info, err := os.Stat(logPath)
+ if err != nil {
+ t.Fatalf("stat log: %v", err)
+ }
+ offset := info.Size()
+
+ f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND, 0o644)
+ if err != nil {
+ t.Fatalf("open log: %v", err)
+ }
+ for i := 1; i <= 5; i++ {
+ fmt.Fprintf(f, "new line %d\n", i)
+ }
+ f.Close()
+
+ lines := readLogTailSince(logPath, offset, 3)
+ want := []string{"new line 3", "new line 4", "new line 5"}
+ if len(lines) != len(want) {
+ t.Fatalf("readLogTailSince = %q, want %q", lines, want)
+ }
+ for i := range want {
+ if lines[i] != want[i] {
+ t.Fatalf("readLogTailSince[%d] = %q, want %q", i, lines[i], want[i])
+ }
+ }
+
+ if got := readLogTailSince(logPath, 1<<40, 3); len(got) != 0 {
+ t.Fatalf("readLogTailSince(past EOF) = %q, want empty", got)
+ }
+}
+
+// TestDaemonStartupFailureError pins the friendly classification of a daemon
+// child that died during startup: the two failure modes users actually hit
+// (token rejected, server unreachable) get a one-line reason plus an
+// actionable next step instead of a raw log dump; only unrecognized failures
+// fall back to a log excerpt, and even that excerpt drops DBG/INF noise.
+// Classification reads both sinks: structured slog lines land in daemon.log,
+// while the child's final cobra "Error: ..." line and panics land in the
+// crash sink (daemon.err.log).
+func TestDaemonStartupFailureError(t *testing.T) {
+ t.Parallel()
+
+ writeLog := func(t *testing.T, name, content string) string {
+ t.Helper()
+ logPath := filepath.Join(t.TempDir(), name)
+ if err := os.WriteFile(logPath, []byte(content), 0o644); err != nil {
+ t.Fatalf("write log: %v", err)
+ }
+ return logPath
+ }
+
+ t.Run("token rejected", func(t *testing.T) {
+ t.Parallel()
+ logPath := writeLog(t, "daemon.log", `18:29:58.416 INF authenticated component=daemon
+18:29:58.425 WRN auth token rejected by server — run 'multica login' to re-authenticate component=daemon error="POST /api/tokens/current/renew returned 401: {\"error\":\"invalid token\"}"
+list workspaces: GET /api/workspaces returned 401: {"error":"invalid token"}
+`)
+ err := daemonStartupFailureError(daemonStartupLogs{logPath: logPath}, nil, "", "http://localhost:8080")
+ msg := err.Error()
+ if !strings.Contains(msg, "rejected your login token") || !strings.Contains(msg, "multica login") {
+ t.Fatalf("error = %q, want token-rejected reason with login hint", msg)
+ }
+ if strings.Contains(msg, "component=daemon") {
+ t.Fatalf("error = %q, want no raw log lines for a classified failure", msg)
+ }
+ })
+
+ t.Run("token rejected with profile", func(t *testing.T) {
+ t.Parallel()
+ logPath := writeLog(t, "daemon.log", "WRN auth token rejected by server error=\"returned 401\"\n")
+ err := daemonStartupFailureError(daemonStartupLogs{logPath: logPath}, nil, "staging", "http://localhost:8080")
+ if !strings.Contains(err.Error(), "multica login --profile staging") {
+ t.Fatalf("error = %q, want profile-scoped login hint", err)
+ }
+ })
+
+ t.Run("server unreachable via crash sink", func(t *testing.T) {
+ t.Parallel()
+ // The detached child routes slog into daemon.log, but its final cobra
+ // error line goes to raw stderr — the crash sink. The "connection
+ // refused" reason may therefore exist ONLY there.
+ logPath := writeLog(t, "daemon.log", `18:40:46.588 DBG token renewal failed; will retry on next cycle component=daemon error="Post \"http://localhost:8080/api/tokens/current/renew\": dial tcp [::1]:8080: connect: connection refused"
+`)
+ errLogPath := writeLog(t, "daemon.err.log", `Error: list workspaces: Get "http://localhost:8080/api/workspaces": dial tcp [::1]:8080: connect: connection refused
+`)
+ err := daemonStartupFailureError(daemonStartupLogs{logPath: logPath, errLogPath: errLogPath}, nil, "", "http://localhost:8080")
+ msg := err.Error()
+ if !strings.Contains(msg, "cannot reach the Multica server at http://localhost:8080") {
+ t.Fatalf("error = %q, want server-unreachable reason with URL", msg)
+ }
+ if strings.Contains(msg, "dial tcp") || strings.Contains(msg, "component=daemon") {
+ t.Fatalf("error = %q, want no raw log lines for a classified failure", msg)
+ }
+ })
+
+ t.Run("unrecognized failure keeps filtered excerpt plus crash output", func(t *testing.T) {
+ t.Parallel()
+ logPath := writeLog(t, "daemon.log", `18:00:00.001 DBG some debug detail component=daemon
+18:00:00.002 INF starting daemon component=daemon
+18:00:00.003 ERR something exploded component=daemon
+`)
+ errLogPath := writeLog(t, "daemon.err.log", "open /nope: permission denied\n")
+ err := daemonStartupFailureError(daemonStartupLogs{logPath: logPath, errLogPath: errLogPath}, nil, "", "http://localhost:8080")
+ msg := err.Error()
+ if !strings.Contains(msg, "something exploded") || !strings.Contains(msg, "permission denied") {
+ t.Fatalf("error = %q, want WRN/ERR and crash lines kept", msg)
+ }
+ if strings.Contains(msg, "some debug detail") || strings.Contains(msg, "starting daemon") {
+ t.Fatalf("error = %q, want DBG/INF noise dropped", msg)
+ }
+ if !strings.Contains(msg, errLogPath) {
+ t.Fatalf("error = %q, want pointer to the crash sink", msg)
+ }
+ })
+
+ t.Run("empty logs", func(t *testing.T) {
+ t.Parallel()
+ logPath := writeLog(t, "daemon.log", "")
+ err := daemonStartupFailureError(daemonStartupLogs{logPath: logPath}, nil, "", "")
+ if !strings.Contains(err.Error(), "daemon exited during startup") || !strings.Contains(err.Error(), logPath) {
+ t.Fatalf("error = %q, want generic failure pointing at the log file", err)
+ }
+ })
+}
+
+// TestDaemonStartBackgroundReportsEarlyChildExit pins the fail-fast contract
+// for an authenticated `daemon start` whose child dies during preflight
+// (unreachable server, token rejected with 401, ...): the parent must notice
+// the exit and report failure immediately instead of polling the health port
+// for the full 45s readiness window and ending with a vague "check logs"
+// warning and exit code 0.
+//
+// The spawned child is stubbed to `false` via daemonExecutable so it dies
+// immediately with a non-zero status, the same shape as a failed preflight.
+func TestDaemonStartBackgroundReportsEarlyChildExit(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+
+ falseBin, err := exec.LookPath("false")
+ if err != nil {
+ t.Skipf("false binary unavailable: %v", err)
+ }
+ orig := daemonExecutable
+ daemonExecutable = func() (string, error) { return falseBin, nil }
+ t.Cleanup(func() { daemonExecutable = orig })
+
+ const profile = "child-exit-test"
+ if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{Token: "mul_fake"}, profile); err != nil {
+ t.Fatalf("SaveCLIConfigForProfile: %v", err)
+ }
+
+ cmd := &cobra.Command{Use: "start"}
+ cmd.Flags().Bool("foreground", false, "")
+ cmd.Flags().String("profile", "", "")
+ cmd.Flags().String("server-url", "", "")
+ if err := cmd.Flags().Set("profile", profile); err != nil {
+ t.Fatalf("set profile flag: %v", err)
+ }
+
+ start := time.Now()
+ err = runDaemonStart(cmd, nil)
+ elapsed := time.Since(start)
+
+ if err == nil || !strings.Contains(err.Error(), "daemon exited during startup") {
+ t.Fatalf("runDaemonStart() = %v, want startup failure error", err)
+ }
+ if elapsed > 15*time.Second {
+ t.Fatalf("runDaemonStart took %s, want early-exit detection well before the 45s readiness window", elapsed)
+ }
+}
+
+// TestDaemonRestartUnauthenticatedFailsBeforeStopping pins the ordering that
+// makes `daemon restart` safe when the user is not logged in: the auth check
+// must run BEFORE the stop phase. Otherwise restart kills the running daemon
+// and only then discovers it cannot start a replacement, leaving the user
+// with no daemon at all.
+func TestDaemonRestartUnauthenticatedFailsBeforeStopping(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+
+ const profile = "restart-authtest"
+
+ // Fake running daemon on the profile's health port. Any shutdown attempt
+ // means restart touched the daemon before checking auth.
+ stopped := fakeRunningDaemon(t, profile)
+
+ err := runDaemonRestart(newRestartTestCmd(t, profile), nil)
+ if err == nil || !strings.Contains(err.Error(), "multica login --profile restart-authtest") {
+ t.Fatalf("runDaemonRestart() = %v, want not-logged-in error with login hint", err)
+ }
+ select {
+ case <-stopped:
+ t.Fatal("restart asked the running daemon to shut down before the auth check")
+ default:
+ }
+}
+
+// fakeRunningDaemon serves a fake healthy daemon on the given profile's health
+// port and reports any /shutdown request on the returned channel. The PID in
+// /health is our own so a kill-fallback would be visible as a test crash too.
+func fakeRunningDaemon(t *testing.T, profile string) <-chan struct{} {
+ t.Helper()
+ ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", healthPortForProfile(profile)))
+ if err != nil {
+ t.Skipf("health port for profile %s unavailable: %v", profile, err)
+ }
+ stopped := make(chan struct{}, 1)
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/health":
+ _, _ = w.Write([]byte(fmt.Sprintf(`{"status":"running","pid":%d}`, os.Getpid())))
+ case "/shutdown":
+ select {
+ case stopped <- struct{}{}:
+ default:
+ }
+ }
+ })}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+ return stopped
+}
+
+func newRestartTestCmd(t *testing.T, profile string) *cobra.Command {
+ t.Helper()
+ cmd := &cobra.Command{Use: "restart"}
+ cmd.Flags().Bool("foreground", false, "")
+ cmd.Flags().String("profile", "", "")
+ cmd.Flags().String("server-url", "", "")
+ if err := cmd.Flags().Set("profile", profile); err != nil {
+ t.Fatalf("set profile flag: %v", err)
+ }
+ return cmd
+}
+
+// TestDaemonRestartRejectedTokenFailsBeforeStopping pins the restart safety
+// guarantee beyond the empty-token case: a stored token that the server
+// rejects with 401 (expired or revoked) must abort the restart BEFORE the
+// running daemon is stopped. Otherwise restart kills the working daemon and
+// the replacement child dies in preflight, leaving no daemon at all (#5165).
+func TestDaemonRestartRejectedTokenFailsBeforeStopping(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("MULTICA_SERVER_URL", "")
+
+ const profile = "restart-401test"
+
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusUnauthorized)
+ }))
+ defer api.Close()
+
+ if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{Token: "mul_revoked", ServerURL: api.URL}, profile); err != nil {
+ t.Fatalf("SaveCLIConfigForProfile: %v", err)
+ }
+
+ stopped := fakeRunningDaemon(t, profile)
+
+ err := runDaemonRestart(newRestartTestCmd(t, profile), nil)
+ if err == nil || !strings.Contains(err.Error(), "rejected your login token") {
+ t.Fatalf("runDaemonRestart() = %v, want token-rejected error", err)
+ }
+ if !strings.Contains(err.Error(), "multica login --profile restart-401test") {
+ t.Fatalf("runDaemonRestart() = %v, want profile login hint", err)
+ }
+ select {
+ case <-stopped:
+ t.Fatal("restart asked the running daemon to shut down despite a rejected token")
+ default:
+ }
+}
+
+// TestDaemonRestartUnreachableServerFailsBeforeStopping pins the other half of
+// the restart preflight: when the configured server cannot be reached at all,
+// restart must abort before stopping the running daemon, because the
+// replacement child would die in preflight against the same dead server.
+func TestDaemonRestartUnreachableServerFailsBeforeStopping(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("MULTICA_SERVER_URL", "")
+
+ const profile = "restart-unreachable-test"
+
+ // Grab a port that is guaranteed closed: listen, record, close.
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen: %v", err)
+ }
+ deadURL := "http://" + ln.Addr().String()
+ ln.Close()
+
+ if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{Token: "mul_fake", ServerURL: deadURL}, profile); err != nil {
+ t.Fatalf("SaveCLIConfigForProfile: %v", err)
+ }
+
+ stopped := fakeRunningDaemon(t, profile)
+
+ err = runDaemonRestart(newRestartTestCmd(t, profile), nil)
+ if err == nil || !strings.Contains(err.Error(), "cannot reach the Multica server") {
+ t.Fatalf("runDaemonRestart() = %v, want server-unreachable error", err)
+ }
+ select {
+ case <-stopped:
+ t.Fatal("restart asked the running daemon to shut down despite an unreachable server")
+ default:
+ }
+}
+
// TestPrintDaemonStatusAlignsValuesWithProfileLabel guards the alignment fix:
// before, a "Daemon [profile]" label was wider than the other keys, so the
// Daemon row's value started further right than every subsequent row. The