Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5974 feat(daemon): let the daemon identify itself on /health (#6783)
Bohan Jiangef60815f5d5b
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex c68e9e461c..a013f38caf 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -283,6 +283,94 @@ func healthPortForProfile(profile string) int {return daemon.DefaultHealthPort + 1 + (h % 1000)}+// daemonProfileMismatchError reports that the daemon answering on a profile's+// health port is not that profile's daemon.+type daemonProfileMismatchError struct {+ Want string // profile the caller asked to act on+ Got string // profile the daemon on that port reports; unset when Unreadable+ Port int+ // Unreadable marks a daemon that answered the profile field with something+ // that is not a string. It claimed an identity we cannot read, so it must+ // not be credited as ours — see daemonIdentityMismatch.+ Unreadable bool+}++func (e *daemonProfileMismatchError) Error() string {+ if e.Unreadable {+ return fmt.Sprintf(+ "port %d is serving a daemon that reported an unreadable profile identity\n"++ "Refusing to act on it as %s: an identity that cannot be read cannot be confirmed to be yours.",+ e.Port, describeProfile(e.Want))+ }+ return fmt.Sprintf(+ "port %d is serving profile %s, not %s\n"++ "Both profile names hash to the same health port, so this command would have acted on the wrong daemon.\n"++ "Run it against %s directly, or rename one of the profiles.",+ e.Port, describeProfile(e.Got), describeProfile(e.Want), describeProfile(e.Got))+}++// statusNote is the one-line explanation `daemon status` prints under its+// verdict, where the command has not failed and there is no error to render.+func (e *daemonProfileMismatchError) statusNote() string {+ if e.Unreadable {+ return fmt.Sprintf("Note: port %d is serving a daemon whose profile identity could not be read.", e.Port)+ }+ return fmt.Sprintf("Note: port %d is serving %s, which hashes to the same port.",+ e.Port, describeProfile(e.Got))+}++// statusJSON is the additive `port_conflict` object for --output json.+func (e *daemonProfileMismatchError) statusJSON() map[string]any {+ if e.Unreadable {+ return map[string]any{"port": e.Port, "unreadable_identity": true}+ }+ return map[string]any{"port": e.Port, "profile": e.Got}+}++// describeProfile renders a profile name for humans, naming the default+// profile rather than printing an empty string.+func describeProfile(profile string) string {+ if profile == "" {+ return "the default profile"+ }+ return strconv.Quote(profile)+}++// daemonIdentityMismatch reports whether the daemon behind health belongs to a+// profile other than the one being acted on.+//+// The health port is a hash of the profile name into a 1000-port range, so+// distinct names collide — any rearrangement of the same characters lands on+// the same port. Without this check `--profile a daemon stop` reads the PID off+// whatever daemon answered and kills it, which for a collision is profile b's+// daemon and every runtime it hosts (#6694).+//+// A daemon that predates the profile field omits it entirely. That is the only+// case treated as "cannot prove identity, proceed anyway": refusing there would+// break lifecycle commands against a daemon that is merely older. Once the+// field is present it is enforced strictly — including the empty string, which+// is the default profile identifying itself, not a missing answer.+func daemonIdentityMismatch(health map[string]any, profile string, port int) error {+ raw, ok := health["profile"]+ if !ok {+ return nil+ }+ got, isString := raw.(string)+ if !isString {+ // Present but malformed (null, a number) is NOT the same as absent.+ // Dropping the type check would collapse such a value to "" and, for a+ // caller targeting the default profile, read as a match — handing the+ // lifecycle commands a daemon whose identity was never established.+ // Absence is a daemon too old to answer; this is a daemon answering+ // wrongly, so it fails closed.+ return &daemonProfileMismatchError{Want: profile, Port: port, Unreadable: true}+ }+ if got == profile {+ return nil+ }+ return &daemonProfileMismatchError{Want: profile, Got: got, Port: port}+}+// unknownProfileError reports an explicitly named --profile that has no// directory under ~/.multica/profiles. It carries the known profile names so// both the text and JSON renderings can list them without re-reading the disk.@@ -469,6 +557,13 @@ func runDaemonBackground(cmd *cobra.Command) error {defer cancel()health := checkDaemonHealthOnPort(ctx, healthPort)if daemonAlive(health) {+ // A live daemon on our port that belongs to someone else is a+ // collision, not an "already running" — starting would fail to bind+ // and "already running" would send the user looking for a daemon of+ // theirs that does not exist.+ if err := daemonIdentityMismatch(health, profile, healthPort); err != nil {+ return err+ }label := "daemon"if profile != "" {label = fmt.Sprintf("daemon [%s]", profile)@@ -1104,6 +1199,12 @@ func runDaemonRestart(cmd *cobra.Command, args []string) error {defer cancel()health := checkDaemonHealthOnPort(ctx, healthPort)if daemonAlive(health) {+ // Identity before preflight, and well before the stop phase: restart+ // kills whatever answered on this port, so a collision would take out+ // another profile's daemon and then start ours in its place.+ if err := daemonIdentityMismatch(health, profile, healthPort); err != nil {+ return err+ }// 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@@ -1164,6 +1265,11 @@ func runDaemonStop(cmd *cobra.Command, _ []string) error {fmt.Fprintf(os.Stderr, "%s is not running.\n", label)return nil}+ // The PID to kill comes from whatever answered on this port, so verify it+ // is ours before signalling it.+ if err := daemonIdentityMismatch(health, profile, healthPort); err != nil {+ return err+ }pid, ok := health["pid"].(float64)if !ok || pid == 0 {@@ -1258,7 +1364,29 @@ func runDaemonStatus(cmd *cobra.Command, _ []string) error {health := checkDaemonHealthOnPort(ctx, healthPort)+ // A daemon belonging to another profile answered on our port. Reporting it+ // as ours would be the same lie in a new place: this profile's daemon is+ // not running, and the port is simply occupied. Say exactly that, and keep+ // the top-level verdict "stopped" so scripts reading it stay correct.+ //+ // Only outside a daemon-managed task. There the port comes from the host+ // daemon's own injection rather than a profile hash, so no collision is+ // possible — and the task's profile is necessarily empty (--profile is+ // rejected) while the host may run a named one, which would make every+ // named-profile host look like a conflict and break the standing contract+ // that `daemon status` in a task reports on the daemon hosting it.+ var conflict *daemonProfileMismatchError+ if daemonAlive(health) && !inDaemonManagedExecutionContext() {+ errors.As(daemonIdentityMismatch(health, profile, healthPort), &conflict)+ }+if output == "json" {+ if conflict != nil {+ return cli.PrintJSON(os.Stdout, map[string]any{+ "status": "stopped",+ "port_conflict": conflict.statusJSON(),+ })+ }return cli.PrintJSON(os.Stdout, health)}@@ -1267,6 +1395,12 @@ func runDaemonStatus(cmd *cobra.Command, _ []string) error {label = fmt.Sprintf("Daemon [%s]", profile)}+ if conflict != nil {+ fmt.Fprintf(os.Stdout, "%s: stopped\n", label)+ fmt.Fprintln(os.Stdout, conflict.statusNote())+ return nil+ }+switch health["status"] {case "running":printDaemonStatusReport(os.Stdout, label, health)@@ -1304,6 +1438,16 @@ func daemonStatusHealthPort(cmd *cobra.Command) (int, error) {return port, nil}+// describeDaemonManager turns the daemon's launched_by tag into something a+// user can act on. Unknown values are passed through rather than dropped: a+// newer daemon naming a manager this CLI predates is still worth showing.+func describeDaemonManager(launchedBy string) string {+ if launchedBy == "desktop" {+ return "Multica Desktop app (start and stop it from the app)"+ }+ return launchedBy+}+// printDaemonStatusReport renders a key/value summary of the daemon health// response. The value column is aligned to the widest label so the dynamic// "Daemon [profile]" row stays in step with the static rows below it.@@ -1315,6 +1459,12 @@ func printDaemonStatusReport(w io.Writer, label string, health map[string]any) {if version, ok := health["cli_version"].(string); ok && version != "" {rows = append(rows, row{"Version", version})}+ // Answers "why is a daemon running that I never started?" — the reporter's+ // ask in #6694. Only rendered when the daemon names a manager, so a+ // standalone daemon and an older one that cannot say both stay unchanged.+ if managed, ok := health["launched_by"].(string); ok && managed != "" {+ rows = append(rows, row{"Managed by", describeDaemonManager(managed)})+ }// Only present while a confirmed on-disk version change is waiting for the// daemon to go idle, so it reads as an explanation rather than a status line.if reason, ok := health["reload_pending_reason"].(string); ok && reason != "" {diff --git a/server/cmd/multica/cmd_daemon_identity_test.go b/server/cmd/multica/cmd_daemon_identity_test.gonew file mode 100644index 0000000000..a7296e85c6--- /dev/null+++ b/server/cmd/multica/cmd_daemon_identity_test.go@@ -0,0 +1,441 @@+package main++import (+ "encoding/json"+ "errors"+ "fmt"+ "net"+ "net/http"+ "os"+ "os/exec"+ "strconv"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/spf13/cobra"+)++// blockingChildEnv marks a re-executed copy of this test binary as the+// stand-in daemon process rather than a normal test run.+const blockingChildEnv = "MULTICA_TEST_BLOCKING_CHILD"++// TestBlockingChildProcess is not a test. It is the entry point the child from+// startBlockingChild runs, and it returns immediately unless that child's env+// var is set, so an ordinary `go test` sees a no-op.+//+// Re-executing the test binary rather than spawning `sleep` keeps this working+// on Windows, which ships no sleep.exe for exec.Command to resolve. This file+// carries no platform build tag, so `go test ./cmd/multica` has to pass there+// even though CI currently only builds the package on Windows.+func TestBlockingChildProcess(t *testing.T) {+ if os.Getenv(blockingChildEnv) != "1" {+ return+ }+ // Bounded rather than blocking forever: if the parent ever fails to clean+ // up, the stray process still exits instead of outliving the test run.+ time.Sleep(60 * time.Second)+}++// startBlockingChild returns the PID of a live process this test owns, for+// cases where the code under test may signal the PID it is handed.+func startBlockingChild(t *testing.T) int {+ t.Helper()+ child := exec.Command(os.Args[0], "-test.run=^TestBlockingChildProcess$")+ child.Env = append(os.Environ(), blockingChildEnv+"=1")+ if err := child.Start(); err != nil {+ t.Fatalf("start stand-in daemon process: %v", err)+ }+ t.Cleanup(func() {+ _ = child.Process.Kill()+ _ = child.Wait()+ })+ return child.Process.Pid+}++// stubDaemon is a fake daemon on a real health port. It serves /shutdown as+// well as /health so `daemon stop` can complete through its graceful path:+// without that endpoint stop falls back to process.Kill() on whatever PID the+// health body advertises, which for a hardcoded PID means signalling an+// unrelated process on the developer's machine.+type stubDaemon struct {+ port int++ mu sync.Mutex+ stopped bool+ shutdowns int+}++func (s *stubDaemon) shutdownCount() int {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.shutdowns+}++// serveHealthAs stands up a stub daemon on the health port that `profile`+// hashes to, answering with the identity `reports` claims. A nil reports map+// means a pre-#6694 daemon: alive, but unable to say who it is.+//+// pid is what the stub advertises. Tests that reach the kill path must pass a+// process they own; the identity tests never get that far, so they leave it at+// the current process's PID, which is never signalled because they stop at the+// refusal.+func serveHealthAs(t *testing.T, profile string, reports map[string]any) *stubDaemon {+ t.Helper()+ return serveHealthAsPID(t, profile, reports, os.Getpid())+}++func serveHealthAsPID(t *testing.T, profile string, reports map[string]any, pid int) *stubDaemon {+ t.Helper()+ port := healthPortForProfile(profile)+ ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))+ if err != nil {+ t.Skipf("health port %d for profile %q is busy on this machine: %v", port, profile, err)+ }+ stub := &stubDaemon{port: port}++ body := map[string]any{"status": "running", "pid": pid, "uptime": "1h0m0s", "cli_version": "v0.4.23"}+ for k, v := range reports {+ body[k] = v+ }+ mux := http.NewServeMux()+ mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {+ stub.mu.Lock()+ stopped := stub.stopped+ stub.mu.Unlock()+ if stopped {+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "stopped"})+ return+ }+ _ = json.NewEncoder(w).Encode(body)+ })+ mux.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ w.WriteHeader(http.StatusMethodNotAllowed)+ return+ }+ stub.mu.Lock()+ stub.stopped = true+ stub.shutdowns+++ stub.mu.Unlock()+ w.WriteHeader(http.StatusOK)+ })+ srv := &http.Server{Handler: mux}+ go func() { _ = srv.Serve(ln) }()+ t.Cleanup(func() { _ = srv.Close() })+ return stub+}++func TestDaemonIdentityMismatch(t *testing.T) {+ cases := []struct {+ name string+ health map[string]any+ profile string+ wantErr bool+ }{+ {"same named profile", map[string]any{"profile": "dev"}, "dev", false},+ {"default profile identifying itself", map[string]any{"profile": ""}, "", false},+ {"different profile on our port", map[string]any{"profile": "dev-b"}, "dev-a", true},+ {"our port serving the default daemon", map[string]any{"profile": ""}, "dev", true},+ {"we asked for default, a named daemon answered", map[string]any{"profile": "dev"}, "", true},+ // A daemon that predates the field cannot prove anything; refusing+ // would break lifecycle commands against a merely older daemon.+ {"older daemon omits the field", map[string]any{"pid": 1.0}, "dev", false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ err := daemonIdentityMismatch(tc.health, tc.profile, 19589)+ var mismatch *daemonProfileMismatchError+ if got := errors.As(err, &mismatch); got != tc.wantErr {+ t.Fatalf("daemonIdentityMismatch = %v, wantErr = %v", err, tc.wantErr)+ }+ })+ }+}++func TestDaemonProfileMismatchErrorNamesBothSides(t *testing.T) {+ err := &daemonProfileMismatchError{Want: "desktop-localhost-18310", Got: "desktop-localhost-18130", Port: 19589}+ msg := err.Error()+ for _, want := range []string{"19589", "desktop-localhost-18130", "desktop-localhost-18310", "same health port"} {+ if !strings.Contains(msg, want) {+ t.Errorf("error %q should mention %q so the user can tell the two apart", msg, want)+ }+ }++ // The default profile has no name to print; "" would read as a bug.+ def := &daemonProfileMismatchError{Want: "dev", Got: "", Port: 19514}+ if !strings.Contains(def.Error(), "the default profile") {+ t.Errorf("error %q should name the default profile in words", def.Error())+ }+}++// The collision is only dangerous because these commands act on whatever+// answered: stop reads the PID off it and kills it, restart kills it and takes+// its port. Both must refuse before touching anything.+func TestDaemonLifecycleRefusesForeignDaemon(t *testing.T) {+ cases := []struct {+ name string+ run func(*cobra.Command) error+ }{+ {"stop", func(c *cobra.Command) error { return runDaemonStop(c, nil) }},+ {"restart", func(c *cobra.Command) error { return runDaemonRestart(c, nil) }},+ {"start", func(c *cobra.Command) error { return runDaemonBackground(c) }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "collide-ab", "collide-ba")+ // Same bytes, so the same hashed port: the shape of a real+ // collision without depending on a lucky pair of names.+ serveHealthAs(t, "collide-ab", map[string]any{"profile": "collide-ab"})++ cmd := daemonStatusCmdFor(t, "collide-ba", "")+ cmd.Flags().Bool("foreground", false, "")+ err := tc.run(cmd)++ var mismatch *daemonProfileMismatchError+ if !errors.As(err, &mismatch) {+ t.Fatalf("daemon %s = %v, want a refusal naming the port collision", tc.name, err)+ }+ if mismatch.Got != "collide-ab" || mismatch.Want != "collide-ba" {+ t.Fatalf("mismatch = %+v, want got=collide-ab want=collide-ba", mismatch)+ }+ })+ }+}++// A daemon too old to identify itself must keep working: stop runs to+// completion against it rather than refusing.+//+// The stub advertises a process this test owns and started, so even if stop+// ever fell through to its forced-kill branch the signal could only reach that+// child — never an unrelated process that happens to hold the same PID.+func TestDaemonStopAcceptsDaemonWithoutProfileField(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "legacy")++ stub := serveHealthAsPID(t, "legacy", nil, startBlockingChild(t))++ err := runDaemonStop(daemonStatusCmdFor(t, "legacy", ""), nil)+ if err != nil {+ t.Fatalf("runDaemonStop = %v, want nil: a daemon that predates the profile field must not be refused", err)+ }+ // Asserting the outcome, not just the absence of a refusal: stop must have+ // gone through the graceful endpoint, which is also what proves it never+ // reached the branch that signals a PID.+ if got := stub.shutdownCount(); got != 1 {+ t.Fatalf("shutdown requests = %d, want 1 — stop should have shut the daemon down gracefully", got)+ }+}++func TestDaemonStatusReportsPortConflictInsteadOfClaimingItsOwn(t *testing.T) {+ t.Run("table says stopped and names the occupant", func(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "collide-ab", "collide-ba")+ stub := serveHealthAs(t, "collide-ab", map[string]any{"profile": "collide-ab"})++ out, err := captureStdout(t, func() error {+ return runDaemonStatus(daemonStatusCmdFor(t, "collide-ba", ""), nil)+ })+ if err != nil {+ t.Fatalf("runDaemonStatus = %v, want nil", err)+ }+ if !strings.Contains(out, "stopped") {+ t.Errorf("stdout = %q, want collide-ba reported as stopped — its daemon is not running", out)+ }+ if strings.Contains(out, "running (pid 4242") {+ t.Errorf("stdout = %q, must not report another profile's daemon as this one's", out)+ }+ if !strings.Contains(out, "collide-ab") || !strings.Contains(out, fmt.Sprint(stub.port)) {+ t.Errorf("stdout = %q, should name the occupying profile and the shared port", out)+ }+ })++ t.Run("json keeps status stopped and adds the conflict", func(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "collide-ab", "collide-ba")+ serveHealthAs(t, "collide-ab", map[string]any{"profile": "collide-ab"})++ out, err := captureStdout(t, func() error {+ return runDaemonStatus(daemonStatusCmdFor(t, "collide-ba", "json"), nil)+ })+ if err != nil {+ t.Fatalf("runDaemonStatus = %v, want nil", err)+ }+ var payload struct {+ Status string `json:"status"`+ PortConflict struct {+ Port int `json:"port"`+ Profile string `json:"profile"`+ } `json:"port_conflict"`+ }+ if err := json.Unmarshal([]byte(out), &payload); err != nil {+ t.Fatalf("stdout is not valid JSON: %v\n%s", err, out)+ }+ // Existing `jq -r .status` callers must keep reading a truthful value.+ if payload.Status != "stopped" {+ t.Errorf("status = %q, want stopped", payload.Status)+ }+ if payload.PortConflict.Profile != "collide-ab" {+ t.Errorf("port_conflict.profile = %q, want collide-ab", payload.PortConflict.Profile)+ }+ })+}++func TestDaemonStatusShowsWhoManagesTheDaemon(t *testing.T) {+ t.Run("desktop-managed daemon says so", func(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "desk-managed-test")+ serveHealthAs(t, "desk-managed-test", map[string]any{+ "profile": "desk-managed-test", "launched_by": "desktop",+ })++ out, err := captureStdout(t, func() error {+ return runDaemonStatus(daemonStatusCmdFor(t, "desk-managed-test", ""), nil)+ })+ if err != nil {+ t.Fatalf("runDaemonStatus = %v, want nil", err)+ }+ if !strings.Contains(out, "Managed by") || !strings.Contains(out, "Desktop") {+ t.Errorf("stdout = %q, want it to say the Desktop app manages this daemon", out)+ }+ })++ t.Run("standalone daemon output is unchanged", func(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "standalone")+ serveHealthAs(t, "standalone", map[string]any{"profile": "standalone"})++ out, err := captureStdout(t, func() error {+ return runDaemonStatus(daemonStatusCmdFor(t, "standalone", ""), nil)+ })+ if err != nil {+ t.Fatalf("runDaemonStatus = %v, want nil", err)+ }+ if strings.Contains(out, "Managed by") {+ t.Errorf("stdout = %q, a standalone daemon must not grow a Managed by row", out)+ }+ })+}++// Inside a daemon-managed task the health port is injected by the host daemon+// rather than derived from a profile hash, so there is no collision to detect.+// The task's own profile is necessarily empty (--profile is rejected there),+// so verifying identity would compare that empty profile against a named-+// profile host and report a phantom conflict — breaking the standing contract+// that `daemon status` in a task reports on the daemon hosting it.+func TestDaemonStatusInTaskContextReportsNamedProfileHost(t *testing.T) {+ setup := func(t *testing.T) {+ t.Helper()+ clearDaemonTaskEnv(t)+ mkProfiles(t)+ stub := serveHealthAs(t, "host-named-profile", map[string]any{+ "profile": "host-named-profile", "launched_by": "desktop",+ })+ t.Setenv("MULTICA_TASK_ID", "task-test")+ t.Setenv("MULTICA_DAEMON_PORT", strconv.Itoa(stub.port))+ }++ t.Run("table reports the host as running", func(t *testing.T) {+ setup(t)+ out, err := captureStdout(t, func() error {+ return runDaemonStatus(daemonStatusCmdFor(t, "", ""), nil)+ })+ if err != nil {+ t.Fatalf("runDaemonStatus = %v, want nil", err)+ }+ if !strings.Contains(out, "running") {+ t.Fatalf("stdout = %q, want the hosting daemon reported as running", out)+ }+ if strings.Contains(out, "hashes to the same port") {+ t.Fatalf("stdout = %q, a named-profile host must not be reported as a port conflict", out)+ }+ })++ t.Run("json reports the host as running", func(t *testing.T) {+ setup(t)+ out, err := captureStdout(t, func() error {+ return runDaemonStatus(daemonStatusCmdFor(t, "", "json"), nil)+ })+ if err != nil {+ t.Fatalf("runDaemonStatus = %v, want nil", err)+ }+ var payload map[string]any+ if err := json.Unmarshal([]byte(out), &payload); err != nil {+ t.Fatalf("stdout is not valid JSON: %v\n%s", err, out)+ }+ if payload["status"] != "running" {+ t.Fatalf("status = %v, want running (host daemon)", payload["status"])+ }+ if _, ok := payload["port_conflict"]; ok {+ t.Fatalf("payload = %v, must not report a conflict against the injected host port", payload)+ }+ })+}++// A profile field that is present but not a string is a daemon answering+// wrongly, not an older daemon unable to answer. Collapsing it to "" would+// read as a match for the default profile and hand lifecycle commands a daemon+// whose identity was never established, so it fails closed.+func TestDaemonIdentityRejectsUnreadableProfileField(t *testing.T) {+ cases := []struct {+ name string+ raw any+ }{+ {"null", nil},+ {"number", 42.0},+ {"object", map[string]any{"name": "dev"}},+ {"bool", true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ // Target the default profile: that is where the dropped type check+ // used to turn an unreadable value into a silent match.+ err := daemonIdentityMismatch(map[string]any{"profile": tc.raw}, "", 19589)+ var mismatch *daemonProfileMismatchError+ if !errors.As(err, &mismatch) {+ t.Fatalf("daemonIdentityMismatch = %v, want a refusal", err)+ }+ if !mismatch.Unreadable {+ t.Fatalf("mismatch = %+v, want it flagged as an unreadable identity", mismatch)+ }+ if !strings.Contains(mismatch.Error(), "unreadable profile identity") {+ t.Errorf("error %q should say the identity could not be read", mismatch.Error())+ }+ })+ }+}++func TestDaemonRefusesDaemonWithUnreadableIdentity(t *testing.T) {+ t.Run("stop refuses", func(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "unreadable")+ serveHealthAs(t, "unreadable", map[string]any{"profile": nil})++ err := runDaemonStop(daemonStatusCmdFor(t, "unreadable", ""), nil)+ var mismatch *daemonProfileMismatchError+ if !errors.As(err, &mismatch) || !mismatch.Unreadable {+ t.Fatalf("runDaemonStop = %v, want a refusal on an unreadable identity", err)+ }+ })++ t.Run("status does not claim it", func(t *testing.T) {+ clearDaemonTaskEnv(t)+ mkProfiles(t, "unreadable")+ serveHealthAs(t, "unreadable", map[string]any{"profile": nil})++ out, err := captureStdout(t, func() error {+ return runDaemonStatus(daemonStatusCmdFor(t, "unreadable", ""), nil)+ })+ if err != nil {+ t.Fatalf("runDaemonStatus = %v, want nil", err)+ }+ if strings.Contains(out, "running (pid") {+ t.Fatalf("stdout = %q, must not report an unverified daemon as this profile's", out)+ }+ if !strings.Contains(out, "could not be read") {+ t.Fatalf("stdout = %q, should explain that the identity could not be read", out)+ }+ })+}diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex ca20bd3e94..f6b32c9110 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -25,12 +25,29 @@ type HealthResponse struct {// lifecycle CLI (`daemon start/stop`) acts on the host process namespace,// so a foreign-OS daemon can't be started/stopped by the app even though// /health is reachable. See #3916.- OS string `json:"os"`- Uptime string `json:"uptime"`+ OS string `json:"os"`+ Uptime string `json:"uptime"`+ // Profile names the CLI profile this daemon was started with, empty for+ // the default profile. Health ports are derived by hashing the profile+ // name into a 1000-port range, so two names can collide and a caller has+ // no other way to tell whose daemon answered: `--profile a daemon stop`+ // would happily kill profile b's daemon (#6694).+ //+ // Deliberately NOT omitempty. The empty string is a real answer — "I am+ // the default profile's daemon" — and must stay distinguishable from a+ // pre-#6694 daemon that cannot identify itself at all. Callers key off+ // the field's presence, so collapsing the two would make every default+ // daemon look unidentifiable.+ Profile string `json:"profile"`DaemonID string `json:"daemon_id"`DeviceName string `json:"device_name"`ServerURL string `json:"server_url"`CLIVersion string `json:"cli_version"`+ // LaunchedBy is "desktop" when the Electron app spawned this daemon, empty+ // for a standalone one. Already reported to the server on registration;+ // surfaced here so `daemon status` can say who manages the daemon instead+ // of leaving the user to guess why a daemon they never started is running.+ LaunchedBy string `json:"launched_by,omitempty"`// ActiveTaskCount remains the compatibility/safety count of every claimed// handleTask lifecycle. The additive counters split actual provider// execution from local-directory parking for throughput and diagnostics.@@ -117,6 +134,8 @@ func (d *Daemon) healthHandler(startedAt time.Time) http.HandlerFunc {PID: os.Getpid(),OS: runtime.GOOS,Uptime: time.Since(startedAt).Truncate(time.Second).String(),+ Profile: d.cfg.Profile,+ LaunchedBy: d.cfg.LaunchedBy,DaemonID: d.cfg.DaemonID,DeviceName: d.cfg.DeviceName,ServerURL: d.cfg.ServerBaseURL,diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex 30eb37ed73..4b93187f15 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -502,3 +502,64 @@ func assertActiveTaskCount(t *testing.T, h http.HandlerFunc, want int64) {t.Errorf("active_task_count: got %d, want %d", resp.ActiveTaskCount, want)}}++// The health port is a hash of the profile name, so distinct names collide and+// a caller cannot otherwise tell whose daemon answered. These pin the wire+// contract the CLI's collision check depends on (#6694).+func TestHealthHandlerReportsProfileIdentity(t *testing.T) {+ t.Parallel()++ rawHealth := func(t *testing.T, cfg Config) map[string]any {+ t.Helper()+ d := &Daemon{cfg: cfg, workspaces: map[string]*workspaceState{}, logger: slog.Default()}+ d.ready.Store(true)++ rec := httptest.NewRecorder()+ d.healthHandler(time.Now()).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", rec.Code)+ }+ var raw map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil {+ t.Fatalf("decode raw response: %v", err)+ }+ return raw+ }++ t.Run("named profile reports its name", func(t *testing.T) {+ t.Parallel()+ raw := rawHealth(t, Config{Profile: "desktop-api.multica.ai", LaunchedBy: "desktop"})+ if got, want := raw["profile"], "desktop-api.multica.ai"; got != want {+ t.Errorf("profile key: got %v, want %q", got, want)+ }+ if got, want := raw["launched_by"], "desktop"; got != want {+ t.Errorf("launched_by key: got %v, want %q", got, want)+ }+ })++ // The empty string is the default profile identifying itself. It has to+ // stay on the wire: a caller distinguishes "I am the default daemon" from+ // "I am too old to say" by whether the key is present at all, so omitempty+ // here would make every default daemon look unidentifiable.+ t.Run("default profile still emits the key", func(t *testing.T) {+ t.Parallel()+ raw := rawHealth(t, Config{Profile: ""})+ got, ok := raw["profile"]+ if !ok {+ t.Fatal("profile key missing for the default profile; it must be present and empty")+ }+ if got != "" {+ t.Errorf("profile key: got %v, want the empty string", got)+ }+ })++ // launched_by is display-only, so absence and empty mean the same thing+ // and omitempty keeps a standalone daemon's payload unchanged.+ t.Run("standalone daemon omits launched_by", func(t *testing.T) {+ t.Parallel()+ raw := rawHealth(t, Config{Profile: "dev"})+ if _, ok := raw["launched_by"]; ok {+ t.Errorf("launched_by should be omitted for a standalone daemon, got %v", raw["launched_by"])+ }+ })+}