Skip to content

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

Go

feat(environments): declare web and desktop environments, and list their servers once (MUL-8996) (#10338)

Jiayuan Zhang293b760de4e6
diff --git a/.github/ci-paths.json b/.github/ci-paths.json
index 8540c5e303..2fa6a63558 100644
--- a/.github/ci-paths.json
+++ b/.github/ci-paths.json
@@ -85,6 +85,9 @@
"scripts/worktree-db.test.sh",
"scripts/dev-env.sh",
"scripts/dev-env.test.sh",
+ "scripts/agent-environment.sh",
+ "scripts/agent-environment.test.sh",
+ ".multica/environments.toml",
"scripts/perf-compare.mjs",
"scripts/perf-compare.test.sh",
"scripts/selfhost-wait.sh",
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d984a4a654..8f32847b22 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -917,6 +917,9 @@ jobs:
- name: Test development environment registry
run: bash scripts/dev-env.test.sh
+ - name: Test agent environment lifecycle
+ run: bash scripts/agent-environment.test.sh
+
- name: Test UI performance comparison runner
run: bash scripts/perf-compare.test.sh
diff --git a/.gitignore b/.gitignore
index 5cc0cef2bc..a6d3c9c14b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -54,7 +54,8 @@ apps/web/test-results/
# context (agent workspace)
.context
.agent_context/
-.multica/
+.multica/*
+!.multica/environments.toml
# local settings
.claude/
diff --git a/.multica/environments.toml b/.multica/environments.toml
new file mode 100644
index 0000000000..6b8a69eb8d
--- /dev/null
+++ b/.multica/environments.toml
@@ -0,0 +1,25 @@
+# Environments an agent can start for an issue with `multica env start <name>`.
+# The daemon supervises them, lists them in the issue sidebar and stops them at
+# their TTL. Format: CLI_AND_DAEMON.md → Local Environments.
+#
+# Both are this checkout's `make up` environment (scripts/dev-env.sh), which
+# keeps owning the ports, database and CLI profile, and they share one API and
+# database. scripts/agent-environment.sh connects it to the daemon; stopping
+# the last of the two runs `make destroy`.
+
+# API + web app. $MULTICA_PORT redirects to the web app's own port.
+[environments.web]
+label = "Web app"
+start = "bash scripts/agent-environment.sh start web"
+stop = "bash scripts/agent-environment.sh stop web"
+ttl = "24h"
+
+# API + Electron Desktop, signed in. It has no URL: Desktop's issue sidebar
+# brings its window forward instead. $MULTICA_PORT answers once the app is up.
+[environments.desktop]
+label = "Desktop app"
+start = "bash scripts/agent-environment.sh start desktop"
+stop = "bash scripts/agent-environment.sh stop desktop"
+url = ""
+ready = "http://localhost:$MULTICA_PORT"
+ttl = "24h"
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index c7c6340833..ba53cb9d3a 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -346,6 +346,8 @@ multica env list
multica env stop web
```
+A declared environment's own servers are not listed a second time as detected ones. That includes servers its `start` command detaches into process groups of their own, as long as they stay in the session `start` runs in. When two environments from the same checkout share a server, such as one API, and the one that started it ends, the server passes to the other while it runs. When such an environment has no URL and one of its processes is a desktop app, the sidebar shows the environment as that app, and Desktop on the same machine can bring its window forward.
+
These commands use the running task's credential, so they work only inside a run. Environments belong to the issue, which means a later run on the same issue can list and stop what an earlier one started. Neither detected nor declared environments are supported on Windows yet.
### Configuration
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 8457b21a40..353bf9cd63 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -624,6 +624,33 @@ Two constraints are enforced rather than documented:
Desktop exactly that way, so an agent can run `make up C=api,web,daemon` and
test a real agent run. `make destroy` stops the daemon and removes its profile.
+### An environment that outlives the agent's run
+
+When a reviewer should open the app after the run ends, an agent inside a
+Multica task starts an environment this repository declares in
+`.multica/environments.toml`:
+
+```bash
+multica env start web # make up C=api,web
+multica env start desktop # make up C=desktop ARGS=--cdp
+multica env stop web
+```
+
+The daemon lists each one in the issue sidebar and stops it after 24 hours.
+
+- `web` has the URL `http://localhost:$MULTICA_PORT`, which redirects to the web
+ app on the port `make up` allocated.
+- `desktop` has no URL. The sidebar shows it as an app, and Desktop on the same
+ machine brings its window forward.
+
+Both are this checkout's `make up` environment, so they share one API and
+database, and `make status` and `make env-exec` work as usual. Stopping one
+leaves the other running; stopping the last one, or the last one's app going
+away, runs `make destroy`. A component started with a plain `make up` counts
+as in use too, and an environment that existed before `multica env start` is
+left in place, with its own owner and TTL. See
+[Local Environments](CLI_AND_DAEMON.md#local-environments) for the file format.
+
### Web with realistic content
Every `make up`, whatever components it starts, signs `dev@localhost` in,
diff --git a/scripts/agent-environment.sh b/scripts/agent-environment.sh
new file mode 100755
index 0000000000..0703484ac6
--- /dev/null
+++ b/scripts/agent-environment.sh
@@ -0,0 +1,217 @@
+#!/usr/bin/env bash
+# Runs this checkout's `make up` environment as a daemon-supervised environment
+# declared in .multica/environments.toml.
+#
+# agent-environment.sh start web|desktop
+# agent-environment.sh stop web|desktop
+#
+# The two models differ in two ways, and this script is the adapter:
+#
+# 1. The daemon hands out $MULTICA_PORT and reports http://localhost:$MULTICA_PORT.
+# dev-env.sh allocates its own ports, and the web app's origin, API URL and
+# CORS settings are built from them. So the web app keeps its dev-env port,
+# and $MULTICA_PORT answers with a redirect to it. Desktop has no URL;
+# $MULTICA_PORT only answers once `up` has finished, which is what the
+# environment's ready check waits for.
+# 2. The daemon treats an environment as alive while the start command's
+# process group is. dev-env.sh detaches every component into its own group
+# and returns. So `start` stays in the foreground after `up`, and exits once
+# the component is gone, which is what lets the sidebar report it as exited.
+# It cleans up on its way out, because once it has exited the daemon
+# neither runs `stop` nor expires the environment.
+#
+# web and desktop share one dev-env environment: the same API, database and
+# profile. Each running `start` holds a claim on it. Stopping a component, or
+# its `start` exiting, gives up the claim; whoever gives up the last one
+# destroys the environment. Claims are read and changed under one lock per
+# checkout, so two stops at once still leave exactly one of them to destroy.
+#
+# Someone may use the same environment through a plain `make up`, with no
+# claim. So a component that is running counts as in use whether or not it is
+# claimed, and an environment that existed before the first claim was made is
+# never destroyed, and keeps its owner and TTL: it belongs to whoever made it.
+set -euo pipefail
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+DEV_ENV="$REPO_ROOT/scripts/dev-env.sh"
+STATE_DIR="$REPO_ROOT/.multica/agent-environments"
+LOCK_DIR="$STATE_DIR/lock.d"
+BORROWED="$STATE_DIR/borrowed"
+
+# One hour longer than the ttl in environments.toml: the daemon's stop runs
+# first, and dev-env's own expiry only collects what a dead daemon left behind.
+DEV_ENV_TTL_HOURS=25
+
+usage() {
+ echo "Usage: agent-environment.sh start|stop web|desktop" >&2
+ exit 2
+}
+
+other_component() {
+ case "$1" in
+ web) printf 'desktop' ;;
+ desktop) printf 'web' ;;
+ *) usage ;;
+ esac
+}
+
+# An atomic mkdir, as in dev-env.sh: flock is not on a stock macOS. A lock
+# whose holder is gone is taken over, so a killed stop cannot wedge the next.
+acquire_lock() {
+ local holder waited=0
+ mkdir -p "$STATE_DIR"
+ while ! mkdir "$LOCK_DIR" 2>/dev/null; do
+ holder="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
+ if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null; then
+ rm -rf "$LOCK_DIR"
+ continue
+ fi
+ waited=$((waited + 1))
+ [ "$waited" -lt 3000 ] || { echo "Timed out waiting for $LOCK_DIR." >&2; exit 1; }
+ sleep 0.1
+ done
+ printf '%s\n' "$$" > "$LOCK_DIR/pid"
+}
+
+release_lock() { rm -rf "$LOCK_DIR"; }
+
+claim_file() { printf '%s/%s.claim' "$STATE_DIR" "$1"; }
+
+# The pid of the `start` holding a claim on the component, if it still runs.
+# A claim left by a `start` that was killed outright is not one.
+claim_holder() {
+ local pid
+ pid="$(cat "$(claim_file "$1")" 2>/dev/null || true)"
+ [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null && printf '%s' "$pid"
+ return 0
+}
+
+# Stops the component, and the whole environment when nothing else claims it.
+# The caller holds the lock and has given up the component's claim.
+release_component() {
+ local component="$1" other
+ other="$(other_component "$component")"
+ if ! bash "$DEV_ENV" status --json >/dev/null 2>&1; then
+ echo "No environment registered for $REPO_ROOT; nothing to stop."
+ return 0
+ fi
+ bash "$DEV_ENV" down --components "$component"
+ if [ -n "$(claim_holder "$other")" ]; then
+ echo "$other still uses the API and database; kept them."
+ elif [ "$(component_state "$other")" != stopped ]; then
+ echo "$other is running outside 'multica env'; kept the API and database."
+ elif [ -f "$BORROWED" ]; then
+ echo "The environment existed before 'multica env start'; kept it."
+ else
+ bash "$DEV_ENV" destroy --yes
+ fi
+}
+
+# The component's state in `dev-env.sh status --json`: running, stopped, ...
+component_state() {
+ node -e '
+ const status = JSON.parse(process.argv[1]);
+ process.stdout.write(String(status.components?.[process.argv[2]]?.state ?? "stopped"));
+ ' "$(bash "$DEV_ENV" status --json)" "$1"
+}
+
+# Runs when `start` exits for any reason: the component went away, `up`
+# failed, or the daemon signalled it after running `stop`. Only a claim this
+# process still holds is given up; one `stop` already took is left alone.
+finish_start() {
+ local component="$1" status="$2"
+ trap - EXIT
+ acquire_lock
+ if [ "$(claim_holder "$component")" = "$$" ]; then
+ rm -f "$(claim_file "$component")"
+ release_component "$component" || true
+ fi
+ release_lock
+ exit "$status"
+}
+
+cmd_start() {
+ local component="$1" status
+ other_component "$component" >/dev/null
+ : "${MULTICA_PORT:?MULTICA_PORT is not set; start this through 'multica env start <name>'.}"
+
+ # Electron listens on nothing by itself. The DevTools port is what lets the
+ # daemon find the app among this environment's processes and offer its
+ # window in the sidebar, and it is what scripts/desktop-cdp.mjs attaches to.
+ local flags=()
+ [ "$component" != desktop ] || flags+=(--cdp)
+
+ acquire_lock
+ if [ -z "$(claim_holder web)$(claim_holder desktop)" ]; then
+ rm -f "$BORROWED"
+ ! bash "$DEV_ENV" status --json >/dev/null 2>&1 || touch "$BORROWED"
+ fi
+ printf '%s\n' "$$" > "$(claim_file "$component")"
+ release_lock
+ trap "finish_start $component \$?" EXIT
+ [ -f "$BORROWED" ] || flags+=(--ttl "$DEV_ENV_TTL_HOURS")
+
+ bash "$DEV_ENV" up --components "api,$component" ${flags[@]+"${flags[@]}"}
+ status="$(bash "$DEV_ENV" status --json)"
+
+ node -e '
+ const http = require("node:http");
+ const net = require("node:net");
+
+ const status = JSON.parse(process.argv[1]);
+ const component = process.argv[2];
+ const port = Number(process.env.MULTICA_PORT);
+ // The port whose listener is the component: Next for web, the renderer
+ // dev server for desktop, which goes away when the app is quit.
+ const watched = component === "web" ? status.frontend_port : status.desktop_renderer_port;
+ const target = `http://localhost:${status.frontend_port}`;
+ const home = `/${status.workspace_slug}/issues`;
+
+ const answer = (req, res) => {
+ if (component === "web") {
+ res.writeHead(302, { Location: target + (req.url === "/" ? home : req.url) });
+ res.end();
+ } else {
+ res.writeHead(200, { "Content-Type": "text/plain" });
+ res.end("The Desktop app of this environment is running.\n");
+ }
+ };
+ http.createServer(answer).listen(port, "127.0.0.1");
+ // Best effort: a machine without IPv6 loopback still has the listener above.
+ http.createServer(answer).on("error", () => {}).listen(port, "::1");
+ console.log(component === "web"
+ ? `http://localhost:${port} redirects to ${target}${home}`
+ : `desktop is up; watching its renderer on :${watched}`);
+
+ let misses = 0;
+ setInterval(() => {
+ const socket = net.connect({ port: watched, host: "localhost" });
+ socket.setTimeout(3000);
+ socket.once("connect", () => { misses = 0; socket.destroy(); });
+ const miss = () => {
+ socket.destroy();
+ if (++misses < 3) return;
+ console.error(`${component} on :${watched} is gone; exiting.`);
+ process.exit(1);
+ };
+ socket.once("error", miss);
+ socket.once("timeout", miss);
+ }, 5000);
+ ' "$status" "$component"
+}
+
+cmd_stop() {
+ local component="$1"
+ other_component "$component" >/dev/null
+ acquire_lock
+ trap release_lock EXIT
+ rm -f "$(claim_file "$component")"
+ release_component "$component"
+}
+
+[ $# -eq 2 ] || usage
+case "$1" in
+ start) cmd_start "$2" ;;
+ stop) cmd_stop "$2" ;;
+ *) usage ;;
+esac
diff --git a/scripts/agent-environment.test.sh b/scripts/agent-environment.test.sh
new file mode 100644
index 0000000000..f5ed17360e
--- /dev/null
+++ b/scripts/agent-environment.test.sh
@@ -0,0 +1,195 @@
+#!/usr/bin/env bash
+# Lifecycle of scripts/agent-environment.sh against a stub dev-env.sh: who
+# stops a component, who destroys the shared environment, and that exactly one
+# of them does whatever order or timing the stops come in.
+set -euo pipefail
+
+root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+tmp_dir="$(mktemp -d)"
+pids=()
+cleanup() {
+ local pid
+ for pid in ${pids[@]+"${pids[@]}"}; do kill "$pid" 2>/dev/null || true; done
+ wait 2>/dev/null || true
+ rm -rf "$tmp_dir"
+}
+trap cleanup EXIT
+
+fail() {
+ echo "FAIL: $*" >&2
+ [ ! -f "$repo/calls.log" ] || sed 's/^/ calls: /' "$repo/calls.log" >&2
+ exit 1
+}
+
+free_port() {
+ node -e 'const s = require("node:net").createServer().listen(0, "127.0.0.1", () => { console.log(s.address().port); s.close(); });'
+}
+
+# A fresh fake checkout: the real script next to a dev-env.sh that records
+# each verb, keeps "registered" as the environment's existence and
+# "<component>.running" as each component's state.
+new_repo() {
+ repo="$tmp_dir/repo-$1"
+ mkdir -p "$repo/scripts"
+ cp "$root_dir/scripts/agent-environment.sh" "$repo/scripts/"
+ component_port="$(free_port)"
+ cat > "$repo/scripts/dev-env.sh" <<EOF
+#!/usr/bin/env bash
+set -eu
+cd "$repo"
+state() { [ -f "\$1.running" ] && echo running || echo stopped; }
+case "\$1" in
+ up)
+ echo "\$*" >> calls.log; touch registered
+ case "\$3" in *web*) touch web.running ;; *desktop*) touch desktop.running ;; esac ;;
+ status)
+ [ -f registered ] || exit 1
+ printf '{"frontend_port":%s,"desktop_renderer_port":%s,"workspace_slug":"dev","components":{"web":{"state":"%s"},"desktop":{"state":"%s"}}}\n' \
+ "$component_port" "$component_port" "\$(state web)" "\$(state desktop)" ;;
+ down) sleep 0.3; echo "down \$3" >> calls.log; rm -f "\$3.running" ;;
+ destroy) sleep 0.3; echo destroy >> calls.log; rm -f registered web.running desktop.running ;;
+esac
+EOF
+ : > "$repo/calls.log"
+}
+
+count() { grep -cx "$1" "$repo/calls.log" || true; }
+
+# A process that stands in for a running start: its pid is what a claim names.
+live_claim() {
+ mkdir -p "$repo/.multica/agent-environments"
+ sleep 300 &
+ pids+=("$!")
+ printf '%s\n' "$!" > "$repo/.multica/agent-environments/$1.claim"
+}
+
+# Kills and reaps a background job, so bash does not report it as terminated.
+stop_job() {
+ kill "$1" 2>/dev/null || true
+ wait "$1" 2>/dev/null || true
+}
+
+serve_component() {
+ node -e 'require("node:http").createServer((_, res) => res.end("ok")).listen(Number(process.argv[1]), "127.0.0.1")' "$component_port" &
+ component_pid=$!
+ pids+=("$component_pid")
+}
+
+start_in_background() {
+ MULTICA_PORT="$(free_port)" bash "$repo/scripts/agent-environment.sh" start "$1" > "$repo/start.log" 2>&1 &
+ start_pid=$!
+ pids+=("$start_pid")
+ local i
+ for i in $(seq 1 100); do
+ grep -q "redirects to\|watching its renderer" "$repo/start.log" 2>/dev/null && return 0
+ sleep 0.1
+ done
+ fail "start $1 never came up: $(cat "$repo/start.log")"
+}
+
+wait_for_exit() {
+ local i
+ for i in $(seq 1 300); do
+ kill -0 "$1" 2>/dev/null || { wait "$1" 2>/dev/null || true; return 0; }
+ sleep 0.1
+ done
+ fail "process $1 did not exit"
+}
+
+# 1. The component going away is cleaned up by start itself: the daemon
+# neither runs stop nor expires an environment whose start has exited.
+new_repo exit-last
+serve_component
+start_in_background web
+stop_job "$component_pid"
+wait_for_exit "$start_pid"
+[ "$(count "down web")" = 1 ] && [ "$(count destroy)" = 1 ] || fail "a component that exited was not cleaned up"
+[ ! -f "$repo/registered" ] || fail "the environment outlived its last component"
+
+# 2. ...but what the other component still uses is kept.
+new_repo exit-shared
+live_claim web
+serve_component
+start_in_background desktop
+stop_job "$component_pid"
+wait_for_exit "$start_pid"
+[ "$(count "down desktop")" = 1 ] && [ "$(count destroy)" = 0 ] || fail "an exiting component destroyed what web still uses"
+
+# 3. Two stops at once: both components stop, exactly one destroys.
+new_repo concurrent
+touch "$repo/registered"
+live_claim web
+live_claim desktop
+bash "$repo/scripts/agent-environment.sh" stop web > /dev/null &
+first=$!
+bash "$repo/scripts/agent-environment.sh" stop desktop > /dev/null &
+second=$!
+wait "$first" || fail "stop web failed"
+wait "$second" || fail "stop desktop failed"
+[ "$(count "down web")" = 1 ] && [ "$(count "down desktop")" = 1 ] || fail "concurrent stops did not stop both components"
+[ "$(count destroy)" = 1 ] || fail "concurrent stops destroyed $(count destroy) times, want once"
+
+# 4. The daemon signals start after running stop. start's own cleanup then
+# finds nothing left to do.
+new_repo signalled
+serve_component
+start_in_background web
+bash "$repo/scripts/agent-environment.sh" stop web > /dev/null
+stop_job "$start_pid"
+[ "$(count "down web")" = 1 ] && [ "$(count destroy)" = 1 ] || fail "stop followed by the daemon's signal cleaned up more than once"
+
+# 5. A claim whose start was killed outright does not keep the environment.
+new_repo stale
+touch "$repo/registered"
+mkdir -p "$repo/.multica/agent-environments"
+sleep 0 & dead=$!
+wait "$dead"
+printf '%s\n' "$dead" > "$repo/.multica/agent-environments/desktop.claim"
+bash "$repo/scripts/agent-environment.sh" stop web > /dev/null
+[ "$(count destroy)" = 1 ] || fail "a stale claim kept the environment alive"
+
+# 6. A component started with a plain `make up` has no claim, but is in use:
+# stopping or losing the managed one next to it keeps what it uses. Both
+# orders, through both ways a managed component ends.
+for pair in "desktop web" "web desktop"; do
+ set -- $pair
+ unmanaged=$1 managed=$2
+
+ new_repo "unmanaged-$unmanaged-exit"
+ touch "$repo/registered" "$repo/$unmanaged.running"
+ serve_component
+ start_in_background "$managed"
+ stop_job "$component_pid"
+ wait_for_exit "$start_pid"
+ [ "$(count "down $managed")" = 1 ] && [ "$(count destroy)" = 0 ] \
+ || fail "$managed exiting destroyed the environment $unmanaged runs in"
+
+ new_repo "unmanaged-$unmanaged-stop"
+ touch "$repo/registered" "$repo/$unmanaged.running"
+ serve_component
+ start_in_background "$managed"
+ bash "$repo/scripts/agent-environment.sh" stop "$managed" > /dev/null
+ stop_job "$start_pid"
+ [ "$(count "down $managed")" = 1 ] && [ "$(count destroy)" = 0 ] \
+ || fail "stopping $managed destroyed the environment $unmanaged runs in"
+done
+
+# 7. An environment that existed before the first claim is someone else's:
+# start keeps its owner and TTL, and the last stop leaves it in place.
+new_repo borrowed
+touch "$repo/registered"
+serve_component
+start_in_background web
+grep -q -- "--ttl" "$repo/calls.log" && fail "start gave an existing environment a TTL"
+bash "$repo/scripts/agent-environment.sh" stop web > /dev/null
+stop_job "$start_pid"
+[ "$(count "down web")" = 1 ] && [ "$(count destroy)" = 0 ] || fail "the last stop destroyed an environment it did not create"
+
+# 8. ...while one start created fresh still gets the TTL.
+new_repo fresh
+serve_component
+start_in_background web
+grep -q -- "--ttl 25" "$repo/calls.log" || fail "start did not give a new environment its TTL"
+stop_job "$start_pid"
+
+echo "✓ agent-environment.sh lifecycle verified"
diff --git a/server/internal/daemon/environments.go b/server/internal/daemon/environments.go
index 8bbdc724e7..7518dee67b 100644
--- a/server/internal/daemon/environments.go
+++ b/server/internal/daemon/environments.go
@@ -147,7 +147,9 @@ func (s *environmentService) servesFrom(dir string) bool {
return false
}
-// focus brings forward the desktop app last detected under key.
+// focus brings forward the desktop app last detected under key: an app found
+// on its own, or the app of a declared environment, under that environment's
+// key.
func (s *environmentService) focus(ctx context.Context, key string) error {
s.mu.Lock()
var target *localenv.Environment
@@ -203,7 +205,7 @@ func (s *environmentService) run(ctx context.Context) {
}
func (s *environmentService) detect(ctx context.Context) {
- found, err := s.detector.Detect(ctx, s.resolve, s.manager.Owns)
+ found, err := s.detector.Detect(ctx, s.resolve, s.manager.Owner)
if err != nil {
s.logger.Debug("environments: detection failed", "error", err)
return
@@ -247,14 +249,31 @@ func (s *environmentService) resolve(cwd string) (localenv.Task, bool) {
// is not empty, and once more as empty after its last environment is gone.
func (s *environmentService) report(ctx context.Context, now time.Time) {
groups := make(map[string][]localenv.Environment)
- for _, env := range s.manager.Snapshot() {
- if env.IssueID != "" {
- groups[env.TaskID] = append(groups[env.TaskID], env)
+ declared := s.manager.Snapshot()
+ s.mu.Lock()
+ // A desktop app found among a declared environment's processes is not a
+ // row of its own: the environment is shown as that app when it has no URL
+ // to open instead.
+ apps := make(map[string]bool)
+ for _, env := range s.detected {
+ if env.Source == localenv.SourceConfig {
+ apps[env.Key] = true
}
}
- s.mu.Lock()
+ for _, env := range declared {
+ if env.IssueID == "" {
+ continue
+ }
+ if env.URL == "" && env.State == localenv.StateRunning && apps[env.Key] {
+ env.Kind = localenv.KindApp
+ }
+ groups[env.TaskID] = append(groups[env.TaskID], env)
+ }
live := make(map[string]bool, len(s.detected))
for _, env := range s.detected {
+ if env.Source == localenv.SourceConfig {
+ continue
+ }
live[env.Key] = true
if owner, ok := s.sticky[env.Key]; ok {
env.TaskID = owner
diff --git a/server/internal/daemon/environments_unix_test.go b/server/internal/daemon/environments_unix_test.go
index c3d77e823a..94b758f8fc 100644
--- a/server/internal/daemon/environments_unix_test.go
+++ b/server/internal/daemon/environments_unix_test.go
@@ -108,3 +108,47 @@ func TestEnvironmentReportKeepsACrashedEnvironmentsOutputLocal(t *testing.T) {
t.Fatalf("local log = %q, want the command's output kept there", log)
}
}
+
+func TestEnvironmentReportShowsADeclaredEnvironmentAsItsApp(t *testing.T) {
+ s, reporter := newTestEnvironmentService(t)
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".multica"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ config := "[environments.desktop]\nlabel = \"Desktop app\"\nstart = \"exec sleep 60\"\nurl = \"\"\n"
+ if err := os.WriteFile(filepath.Join(root, ".multica", "environments.toml"), []byte(config), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ task := localenv.Task{TaskID: "task-a", IssueID: "issue-a", WorkspaceID: "ws", RootDir: root}
+ env, err := s.manager.Start(task, root, "desktop", os.Getenv("PATH"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { s.manager.Stop(task, "desktop") })
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if env = s.manager.WaitReady(ctx, env.Key); env.State != localenv.StateRunning {
+ t.Fatalf("environment = %+v, want running", env)
+ }
+
+ s.report(context.Background(), time.Now())
+ calls := reporter.take()
+ if len(calls) != 1 || len(calls[0].envs) != 1 || calls[0].envs[0].Kind != localenv.KindServer {
+ t.Fatalf("before its app is found = %+v, want the environment alone, as a server", calls)
+ }
+
+ // What detection returns once it finds an app among the environment's
+ // processes: the app, under the environment's key.
+ s.detected = []localenv.Environment{{
+ Key: env.Key, TaskID: "task-a", IssueID: "issue-a", Source: localenv.SourceConfig, Kind: localenv.KindApp,
+ Name: "Multica Canary", State: localenv.StateRunning,
+ }}
+ s.report(context.Background(), time.Now())
+ calls = reporter.take()
+ if len(calls) != 1 || len(calls[0].envs) != 1 {
+ t.Fatalf("reports = %+v, want one row: the app is the environment, not a second entry", calls)
+ }
+ if got := calls[0].envs[0]; got.Key != env.Key || got.Kind != localenv.KindApp || got.Source != localenv.SourceConfig || got.Label != "Desktop app" {
+ t.Fatalf("reported %+v, want the declared environment as an app", got)
+ }
+}
diff --git a/server/internal/daemon/localenv/config_test.go b/server/internal/daemon/localenv/config_test.go
index 088bbe08be..ba9e9d5410 100644
--- a/server/internal/daemon/localenv/config_test.go
+++ b/server/internal/daemon/localenv/config_test.go
@@ -97,3 +97,23 @@ func TestFindConfigWalksUpToTheBoundary(t *testing.T) {
t.Fatal("FindConfig accepted a directory outside the task")
}
}
+
+// The repository's own environments file is what agents working on Multica
+// start, so a typo in it should fail here rather than in an agent's run.
+func TestRepositoryConfigParses(t *testing.T) {
+ data, err := os.ReadFile(filepath.Join("..", "..", "..", "..", filepath.FromSlash(ConfigPath)))
+ if err != nil {
+ t.Fatalf("read %s: %v", ConfigPath, err)
+ }
+ cfg, err := ParseConfig(data)
+ if err != nil {
+ t.Fatalf("ParseConfig: %v", err)
+ }
+ if got := strings.Join(cfg.Names(), ","); got != "desktop,web" {
+ t.Fatalf("declared = %s, want desktop and web", got)
+ }
+ // Desktop has nothing to open, but still waits for its app to be up.
+ if desktop := cfg.Environments["desktop"]; desktop.URL != "" || desktop.Ready == "" {
+ t.Fatalf("desktop = %+v, want no URL and a ready check", desktop)
+ }
+}
diff --git a/server/internal/daemon/localenv/detect.go b/server/internal/daemon/localenv/detect.go
index 3ca3e07472..197fb98207 100644
--- a/server/internal/daemon/localenv/detect.go
+++ b/server/internal/daemon/localenv/detect.go
@@ -83,21 +83,27 @@ func NewDetector(ignoreCommands []string) *Detector {
}
// Detect lists the servers whose working directory belongs to a task.
-// resolve maps a working directory to its task; owned reports process groups
-// the manager already supervises. A server is reported from its second
-// sighting on, so test servers that live for a moment never show up.
+// resolve maps a working directory to its task; owner names the declared
+// environment a process belongs to, if any. A server is reported from its
+// second sighting on, so test servers that live for a moment never show up.
//
// A desktop app is reported once, as an app with no URL, however many ports
// it listens on. A DevTools port is never reported as a URL: opening it shows
// a debugger page, not the app.
-func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, bool), owned func(pgid int) bool) ([]Environment, error) {
+//
+// The servers of a declared environment are already listed under it and are
+// left out. A desktop app among them is returned under the environment's own
+// key, with the config source, so the caller can show that environment as the
+// app and bring its window forward.
+func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, bool), owner func(pid int) string) ([]Environment, error) {
listeners, err := d.list(ctx)
if err != nil {
return nil, err
}
type candidate struct {
Listener
- task Task
+ task Task
+ owner string
}
var candidates []candidate
for _, l := range listeners {
@@ -108,10 +114,7 @@ func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, b
if !ok {
continue
}
- if pgid := processGroup(l.PID); pgid > 0 && owned(pgid) {
- continue
- }
- candidates = append(candidates, candidate{l, task})
+ candidates = append(candidates, candidate{l, task, owner(l.PID)})
}
pids := make([]int, 0, len(candidates))
for _, c := range candidates {
@@ -124,6 +127,16 @@ func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, b
debugPorts := make(map[string][]int)
for _, c := range candidates {
proc := procs[c.PID]
+ if c.owner != "" {
+ if _, dup := found[c.owner]; proc.App != "" && !dup {
+ found[c.owner] = Environment{
+ Key: c.owner, TaskID: c.task.TaskID, IssueID: c.task.IssueID, Source: SourceConfig, Kind: KindApp,
+ Name: truncateName(proc.App), State: StateRunning, Dir: c.task.RootDir,
+ pid: c.PID, bundle: proc.Bundle,
+ }
+ }
+ continue
+ }
// A process that may yet be an app is probed like one, so its debug
// port is not offered as a link while it starts.
debug := proc.debugs(c.Port) || ((proc.App != "" || proc.Unsettled) && d.speaksCDP(ctx, c.PID, c.Port))
diff --git a/server/internal/daemon/localenv/detect_test.go b/server/internal/daemon/localenv/detect_test.go
index 00b874b15d..a01b94e4b1 100644
--- a/server/internal/daemon/localenv/detect_test.go
+++ b/server/internal/daemon/localenv/detect_test.go
@@ -69,6 +69,38 @@ func TestDetectorReportsServersInTaskDirectories(t *testing.T) {
}
}
+func TestDetectorLeavesOutADeclaredEnvironmentsServersAndKeepsItsApp(t *testing.T) {
+ listeners := []Listener{
+ {PID: 10, Port: 9724, Command: "Electron", Cwd: "/ws/task-a/workdir/apps/desktop"},
+ {PID: 11, Port: 5173, Command: "node", Cwd: "/ws/task-a/workdir/apps/desktop"},
+ {PID: 12, Port: 8080, Command: "server", Cwd: "/ws/task-a/workdir/server"},
+ {PID: 13, Port: 6006, Command: "node", Cwd: "/ws/task-a/workdir"},
+ }
+ procs := map[int]Process{
+ 10: {Args: electronBundle + "/Contents/MacOS/Electron . --remote-debugging-port=9724", App: "Multica Canary", Bundle: electronBundle},
+ }
+ owner := func(pid int) string {
+ if pid == 13 {
+ return ""
+ }
+ return "config:abc"
+ }
+ d := fakeDetector(&listeners, procs, nil)
+
+ d.Detect(context.Background(), resolveTaskA, owner)
+ envs, _ := d.Detect(context.Background(), resolveTaskA, owner)
+ if len(envs) != 2 {
+ t.Fatalf("detected = %+v, want the environment's app and the one server nobody declared", envs)
+ }
+ app, other := byKind(envs, KindApp), byKind(envs, KindServer)
+ if app.Key != "config:abc" || app.Source != SourceConfig || app.pid != 10 || app.bundle != electronBundle {
+ t.Fatalf("app = %+v, want it under the environment's key with the config source", app)
+ }
+ if other.Source != SourceDetected || other.Port != 6006 {
+ t.Fatalf("other = %+v, want the server on 6006 as detected", other)
+ }
+}
+
const electronBundle = "/ws/task-a/workdir/node_modules/electron/dist/Electron.app"
func TestDetectorReportsADesktopAppInsteadOfItsDebugPort(t *testing.T) {
@@ -305,7 +337,7 @@ func resolveTaskA(cwd string) (Task, bool) {
return Task{}, false
}
-func notOwned(int) bool { return false }
+func notOwned(int) string { return "" }
func byKind(envs []Environment, kind string) Environment {
for _, env := range envs {
diff --git a/server/internal/daemon/localenv/manager.go b/server/internal/daemon/localenv/manager.go
index 0161da8bc1..acdee86cd2 100644
--- a/server/internal/daemon/localenv/manager.go
+++ b/server/internal/daemon/localenv/manager.go
@@ -109,6 +109,10 @@ type record struct {
StartedAt time.Time `json:"started_at"`
ExpiresAt time.Time `json:"expires_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
+ // Adopted lists the sessions of environments of the same checkout that
+ // ended while this one ran. What is left of them, such as an API both
+ // used, is still in use and still declared.
+ Adopted []int `json:"adopted,omitempty"`
}
type entry struct {
@@ -169,12 +173,17 @@ func (m *Manager) Load() error {
if err := json.Unmarshal(data, &rec); err != nil || rec.ID != d.Name() {
continue
}
- e := &entry{rec: rec}
- if e.live() && !groupAlive(rec.PID) {
+ m.envs[rec.ID] = &entry{rec: rec}
+ }
+ // Every record is loaded before any is ended, so a dead environment's
+ // sessions can pass to a live one of the same checkout.
+ for _, e := range m.envs {
+ if e.live() && !groupAlive(e.rec.PID) {
m.endLocked(e, StateExited, "stopped while the daemon was not running")
}
- m.envs[rec.ID] = e
- if e.live() && rec.State == StateStarting {
+ }
+ for _, e := range m.envs {
+ if e.live() && e.rec.State == StateStarting {
go m.probe(e)
}
}
@@ -360,17 +369,26 @@ func (m *Manager) Tick() {
}
}
-// Owns reports whether pgid is the process group of a live environment this
-// manager started, so detection does not list it a second time.
-func (m *Manager) Owns(pgid int) bool {
+// Owner returns the key of the live environment that pid belongs to, or ""
+// when it belongs to none, so detection does not list an environment's own
+// servers a second time. A process belongs to an environment through its
+// process group or, once a script has detached it into a group of its own,
+// through its session.
+func (m *Manager) Owner(pid int) string {
+ pgid, sid := processGroup(pid), processSession(pid)
m.mu.Lock()
defer m.mu.Unlock()
for _, e := range m.envs {
- if e.live() && e.rec.PID == pgid {
- return true
+ if !e.live() {
+ continue
+ }
+ for _, leader := range append([]int{e.rec.PID}, e.rec.Adopted...) {
+ if leader > 0 && (leader == pgid || leader == sid) {
+ return "config:" + e.rec.ID
+ }
}
}
- return false
+ return ""
}
func (e *entry) leaderGone() bool {
@@ -512,6 +530,27 @@ func (m *Manager) endLocked(e *entry, state, detail string) {
e.rec.Detail = detail
e.rec.EndedAt = &now
m.persistLocked(e)
+ if heir := m.heirLocked(e); heir != nil {
+ heir.rec.Adopted = append(heir.rec.Adopted, e.rec.PID)
+ heir.rec.Adopted = append(heir.rec.Adopted, e.rec.Adopted...)
+ m.persistLocked(heir)
+ }
+}
+
+// heirLocked picks the live environment that takes over an ended one's
+// sessions: the earliest started from the same checkout, for the same owner.
+func (m *Manager) heirLocked(ended *entry) *entry {
+ owner := Task{TaskID: ended.rec.TaskID, IssueID: ended.rec.IssueID, WorkspaceID: ended.rec.WorkspaceID}
+ var heir *entry
+ for _, e := range m.envs {
+ if e == ended || !e.live() || e.rec.RepoRoot != ended.rec.RepoRoot || !sameOwner(e.rec, owner) {
+ continue
+ }
+ if heir == nil || e.rec.StartedAt.Before(heir.rec.StartedAt) {
+ heir = e
+ }
+ }
+ return heir
}
func (m *Manager) persistLocked(e *entry) {
diff --git a/server/internal/daemon/localenv/manager_test.go b/server/internal/daemon/localenv/manager_test.go
index 80867efb31..78ea9edda8 100644
--- a/server/internal/daemon/localenv/manager_test.go
+++ b/server/internal/daemon/localenv/manager_test.go
@@ -11,9 +11,12 @@ import (
"net/http"
"net/http/httptest"
"os"
+ "os/exec"
"path/filepath"
+ "strconv"
"strings"
"sync/atomic"
+ "syscall"
"testing"
"time"
)
@@ -30,6 +33,18 @@ func TestHelperProcess(t *testing.T) {
}
fmt.Println("serving", os.Getenv("MULTICA_ENVIRONMENT"))
http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "ok") }))
+ case "detach":
+ // What `make up` does: start the server in a process group of its
+ // own, then stay around for as long as the environment should live.
+ server := exec.Command(os.Args[0], "-test.run=^TestHelperProcess$")
+ server.Env = append(os.Environ(), "LOCALENV_HELPER=serve")
+ server.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ if err := server.Start(); err != nil {
+ fmt.Println("detach:", err)
+ os.Exit(2)
+ }
+ os.WriteFile(os.Getenv("LOCALENV_PID_FILE"), []byte(strconv.Itoa(server.Process.Pid)), 0o600)
+ server.Wait()
case "crash":
fmt.Println("boom: cannot reach postgres://demo:" + crashSecret + "@db.invalid/app")
os.Exit(3)
@@ -197,8 +212,8 @@ func TestManagerAdoptsEnvironmentsAfterRestart(t *testing.T) {
if len(adopted) != 1 || adopted[0].Key != env.Key || adopted[0].State != StateRunning {
t.Fatalf("adopted = %+v, want the running environment", adopted)
}
- if !restarted.Owns(env.pgid) {
- t.Fatal("restarted manager does not own the adopted process group")
+ if got := restarted.Owner(env.pgid); got != env.Key {
+ t.Fatalf("restarted manager names %q as the owner of the adopted process, want %q", got, env.Key)
}
if _, err := restarted.Stop(task, "web"); err != nil {
t.Fatalf("Stop after restart: %v", err)
@@ -264,3 +279,115 @@ func TestManagerAllocatesDistinctPortBlocks(t *testing.T) {
t.Fatalf("state was not persisted: %v", err)
}
}
+
+func TestManagerOwnsAServerDetachedIntoItsOwnProcessGroup(t *testing.T) {
+ root := t.TempDir()
+ pidFile := filepath.Join(t.TempDir(), "server.pid")
+ writeConfig(t, root, fmt.Sprintf(`
+[environments.web]
+start = "LOCALENV_PID_FILE='%s' %s"
+`, pidFile, helperCommand("detach")))
+ m := NewManager(t.TempDir(), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ task := Task{TaskID: "task-1", IssueID: "issue-1", WorkspaceID: "ws-1", RootDir: root}
+ env, err := m.Start(task, root, "web", os.Getenv("PATH"))
+ if err != nil {
+ t.Fatalf("Start: %v", err)
+ }
+ if ready := waitReady(t, m, env.Key); ready.State != StateRunning {
+ t.Fatalf("environment = %+v, want running", ready)
+ }
+ data, err := os.ReadFile(pidFile)
+ if err != nil {
+ t.Fatalf("read the detached server's pid: %v", err)
+ }
+ server, _ := strconv.Atoi(string(data))
+ t.Cleanup(func() {
+ m.Stop(task, "web")
+ syscall.Kill(server, syscall.SIGKILL)
+ })
+
+ if processGroup(server) == env.pgid {
+ t.Fatal("the server shares the start command's process group; the test proves nothing")
+ }
+ if got := m.Owner(server); got != env.Key {
+ t.Fatalf("Owner(detached server) = %q, want %q", got, env.Key)
+ }
+ if got := m.Owner(os.Getpid()); got != "" {
+ t.Fatalf("Owner(this test) = %q, want none", got)
+ }
+ if _, err := m.Stop(task, "web"); err != nil {
+ t.Fatalf("Stop: %v", err)
+ }
+ if got := m.Owner(server); got != "" {
+ t.Fatalf("Owner after stop = %q, want none: a stopped environment owns nothing", got)
+ }
+}
+
+func TestManagerPassesASharedServerToTheEnvironmentStillUsingIt(t *testing.T) {
+ for _, first := range []string{"api", "web"} {
+ t.Run("stop "+first+" first", func(t *testing.T) {
+ root := t.TempDir()
+ pidFile := filepath.Join(t.TempDir(), "server.pid")
+ // api detaches a server the way `make up` detaches the API that
+ // both environments of a checkout use.
+ writeConfig(t, root, fmt.Sprintf(`
+[environments.api]
+start = "LOCALENV_PID_FILE='%s' %s"
+
+[environments.web]
+start = "%s"
+`, pidFile, helperCommand("detach"), helperCommand("serve")))
+ dir := t.TempDir()
+ m := NewManager(dir, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ task := Task{TaskID: "task-1", IssueID: "issue-1", WorkspaceID: "ws-1", RootDir: root}
+ keys := map[string]string{}
+ for _, name := range []string{"api", "web"} {
+ env, err := m.Start(task, root, name, os.Getenv("PATH"))
+ if err != nil {
+ t.Fatalf("Start %s: %v", name, err)
+ }
+ if ready := waitReady(t, m, env.Key); ready.State != StateRunning {
+ t.Fatalf("%s = %+v, want running", name, ready)
+ }
+ keys[name] = env.Key
+ }
+ data, err := os.ReadFile(pidFile)
+ if err != nil {
+ t.Fatalf("read the detached server's pid: %v", err)
+ }
+ server, _ := strconv.Atoi(string(data))
+ t.Cleanup(func() {
+ m.Stop(task, "api")
+ m.Stop(task, "web")
+ syscall.Kill(server, syscall.SIGKILL)
+ })
+
+ second := map[string]string{"api": "web", "web": "api"}[first]
+ if _, err := m.Stop(task, first); err != nil {
+ t.Fatalf("Stop %s: %v", first, err)
+ }
+ if !groupAlive(processGroup(server)) {
+ t.Fatal("the shared server stopped with the first environment; the test proves nothing")
+ }
+ if got := m.Owner(server); got != keys[second] {
+ t.Fatalf("Owner(shared server) after stopping %s = %q, want %s, which still runs", first, got, second)
+ }
+
+ // The ownership survives a daemon restart.
+ restarted := NewManager(dir, m.logger)
+ if err := restarted.Load(); err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+ if got := restarted.Owner(server); got != keys[second] {
+ t.Fatalf("after a restart Owner(shared server) = %q, want %s", got, keys[second])
+ }
+
+ if _, err := m.Stop(task, second); err != nil {
+ t.Fatalf("Stop %s: %v", second, err)
+ }
+ if got := m.Owner(server); got != "" {
+ t.Fatalf("Owner after both stopped = %q, want none", got)
+ }
+ })
+ }
+}
diff --git a/server/internal/daemon/localenv/proc_unix.go b/server/internal/daemon/localenv/proc_unix.go
index ccd2bee7e3..22e8b8cbda 100644
--- a/server/internal/daemon/localenv/proc_unix.go
+++ b/server/internal/daemon/localenv/proc_unix.go
@@ -6,6 +6,8 @@ import (
"errors"
"os/exec"
"syscall"
+
+ "golang.org/x/sys/unix"
)
const supported = true
@@ -14,10 +16,13 @@ func shellCommand(script string) *exec.Cmd {
return exec.Command("/bin/sh", "-c", script)
}
-// setProcessGroup makes the command lead its own process group, so stopping
-// the environment reaches every server it spawned and nothing else.
+// setProcessGroup makes the command lead its own session, and with it its own
+// process group. The group is what stopping signals, so it reaches every
+// server the command spawned and nothing else. The session is what a server
+// keeps when a script moves it into a process group of its own to detach it,
+// so detection still knows whose it is.
func setProcessGroup(cmd *exec.Cmd) {
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
}
func signalGroup(pgid int, sig syscall.Signal) error {
@@ -44,3 +49,11 @@ func processGroup(pid int) int {
}
return pgid
}
+
+func processSession(pid int) int {
+ sid, err := unix.Getsid(pid)
+ if err != nil {
+ return 0
+ }
+ return sid
+}
diff --git a/server/internal/daemon/localenv/proc_windows.go b/server/internal/daemon/localenv/proc_windows.go
index 1aa4737ed3..92d9a628d7 100644
--- a/server/internal/daemon/localenv/proc_windows.go
+++ b/server/internal/daemon/localenv/proc_windows.go
@@ -18,3 +18,5 @@ func signalGroup(int, syscall.Signal) error { return ErrUnsupported }
func groupAlive(int) bool { return false }
func processGroup(int) int { return 0 }
+
+func processSession(int) int { return 0 }