Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8912: feat(environments): show the environments an issue started in its sidebar (#10265)
Jiayuan Zhang1ca17b606914
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 5799b6e23d..c7c6340833 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -320,6 +320,34 @@ does not clear those blocks or establish that earlier background processes exite4. Heartbeats are sent periodically (default: 15s) so the server knows the daemon is alive5. On shutdown, all runtimes are deregistered+### Local Environments++The issue sidebar's **Environments** section lists the servers an issue's runs left running, grouped by the machine they run on. A localhost URL opens only on that machine. The daemon reports environments in two ways:++- **Detected.** On macOS and Linux, any process listening on a TCP port whose working directory is inside a run's directory shows up. It has to be seen on two scans in a row, about 30 seconds apart, so short-lived test servers stay out. The agent CLIs themselves are ignored, and so are servers in a project's own local directory, which the user started.+- **Declared.** A repository can describe its environments in `.multica/environments.toml`. An agent starts one with `multica env start <name>`. The daemon then supervises it: the environment keeps running after the run ends and stops at its TTL. If it is still running when the daemon restarts, the new daemon process picks it back up.++```toml+[environments.web]+label = "Web app"+start = "pnpm dev --port $MULTICA_PORT"+# url defaults to http://localhost:$MULTICA_PORT; set url = "" when there is none+# ready = "http://localhost:$MULTICA_PORT/health" # defaults to url+# stop = "docker compose down" # runs before the process group is signalled+ttl = "24h" # 1m to 7d, default 24h+```++Each environment gets ten ports, `MULTICA_PORT` through `MULTICA_PORT+9`. Parallel runs therefore never collide. `start` runs with `/bin/sh -c` from the directory that holds `.multica/`, with the caller's `PATH`. The daemon's `MULTICA_*` credentials are not passed to it. Output goes to a log under `<workspaces root>/.environments/v1/`, and `multica env start` prints its path. The log stays on the machine. Output can contain secrets such as a connection string, so for an environment that crashed the sidebar shows only its exit status, while `multica env start` prints the log's last lines locally.++```bash+multica env start web # waits until the ready URL answers below 500, then prints the URL+multica env start web --wait=false+multica env list+multica env stop web+```++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.+### ConfigurationDaemon behavior is configured via flags or environment variables:diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 5371db5cf5..5a22a73cf6 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -289,6 +289,64 @@ describe("ApiClient pull-request response schema", () => {});});+describe("ApiClient issue environments response schema", () => {+ const validEnvironment = {+ id: "env-1",+ issue_id: "issue-1",+ task_id: "task-1",+ runtime_id: "rt-1",+ agent_id: "agent-1",+ source: "config",+ name: "web",+ label: "Web app",+ url: "http://localhost:41000",+ port: 41000,+ state: "running",+ detail: "",+ started_at: "2026-11-10T09:00:00Z",+ expires_at: "2026-11-11T09:00:00Z",+ last_seen_at: "2026-11-10T09:05:00Z",+ ended_at: null,+ };++ function stubEnvironments(body: unknown) {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );+ }++ it("parses a valid environment list", async () => {+ stubEnvironments({ environments: [validEnvironment] });+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");+ expect(result.environments).toEqual([validEnvironment]);+ });++ it("drops a malformed environment and keeps the rest", async () => {+ stubEnvironments({ environments: [{ ...validEnvironment, id: 7 }, { ...validEnvironment, id: "env-2" }] });+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");+ expect(result.environments.map((env) => env.id)).toEqual(["env-2"]);+ });++ it("reads an unknown state from a newer server as unreachable", async () => {+ stubEnvironments({ environments: [{ ...validEnvironment, state: "hibernating", source: "remote" }] });+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");+ expect(result.environments[0]).toMatchObject({ state: "unreachable", source: "detected" });+ });++ it("falls back to an empty list when the body is not a list", async () => {+ stubEnvironments({ environments: "nope" });+ await expect(+ new ApiClient("https://api.example.test").listIssueEnvironments("issue-1"),+ ).resolves.toEqual({ environments: [] });+ });+});+describe("ApiClient Plugin preview response schema", () => {it("degrades a malformed preview so a blank scope list is never shown as approval", async () => {vi.stubGlobal(diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 6b112c516e..ed68e35289 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -186,6 +186,7 @@ import type {PluginInstallRequest,PluginConfigRequest,IssuePullRequestsResponse,+ IssueEnvironmentsResponse,ListGitHubInstallationsResponse,ListGitHubRepositoriesResponse,GitHubConnectResponse,@@ -491,6 +492,8 @@ import {EMPTY_ISSUE_PROPERTIES_RESPONSE,EMPTY_ISSUE_PULL_REQUESTS_RESPONSE,IssuePullRequestsResponseSchema,+ EMPTY_ISSUE_ENVIRONMENTS_RESPONSE,+ IssueEnvironmentsResponseSchema,ResourceLabelsResponseSchema,EMPTY_LABEL,EMPTY_LIST_LABELS_RESPONSE,@@ -5251,6 +5254,17 @@ export class ApiClient {);}+ /** Environments the issue's runs started, live ones plus recently ended. */+ async listIssueEnvironments(issueId: string): Promise<IssueEnvironmentsResponse> {+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/environments`);+ return parseWithFallback(+ raw,+ IssueEnvironmentsResponseSchema,+ EMPTY_ISSUE_ENVIRONMENTS_RESPONSE,+ { endpoint: "GET /api/issues/:id/environments" },+ );+ }+/** Link a PR the workspace already mirrors, by pasted URL or by id (undo). */async linkIssuePullRequest(issueId: string,diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 2ac6937ca5..5f4c41b55c 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -58,6 +58,7 @@ import type {GroupedIssuesResponse,GitHubConnectResponse,IssuePullRequestsResponse,+ IssueEnvironmentsResponse,InboxItem,InboxWorkspaceUnread,IssueUnread,@@ -465,6 +466,44 @@ export const EMPTY_ISSUE_PULL_REQUESTS_RESPONSE: IssuePullRequestsResponse = {auto_complete: null,};+// One malformed environment drops out of the list instead of taking the+// whole section with it; an unknown state from a newer server reads as+// unreachable, which offers no Open action.+export const IssueEnvironmentSchema = z.object({+ id: z.string(),+ issue_id: z.string(),+ task_id: z.string(),+ runtime_id: z.string().nullable().optional().default(null),+ agent_id: z.string().nullable().optional().default(null),+ source: z.enum(["config", "detected"]).catch("detected"),+ name: z.string(),+ label: z.string().optional().default(""),+ url: z.string().optional().default(""),+ port: z.number().nullable().optional().default(null),+ state: z.enum(["starting", "running", "exited", "stopped", "unreachable"]).catch("unreachable"),+ detail: z.string().optional().default(""),+ started_at: z.string(),+ expires_at: z.string().nullable().optional().default(null),+ last_seen_at: z.string(),+ ended_at: z.string().nullable().optional().default(null),+}).loose();++export const IssueEnvironmentsResponseSchema = z.object({+ environments: z+ .array(z.unknown())+ .default([])+ .transform((items) =>+ items.flatMap((item) => {+ const parsed = IssueEnvironmentSchema.safeParse(item);+ return parsed.success ? [parsed.data] : [];+ }),+ ),+}).loose();++export const EMPTY_ISSUE_ENVIRONMENTS_RESPONSE: IssueEnvironmentsResponse = {+ environments: [],+};+// Label responses are consumed by settings tables and resource pickers. Keep// the resource type lenient so newer server scopes do not break older clients,// while defaulting fields that predate scoped label catalogs.diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex 3aa367a566..4bd12a40c7 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -159,6 +159,11 @@ export const issueKeys = {[...issueKeys.childrenByParentsAll(wsId), parentIds] as const,childProgress: (wsId: string) =>[...issueKeys.all(wsId), "child-progress"] as const,+ /** Prefix for every per-issue environments query in a workspace. */+ environmentsAll: (wsId: string) =>+ [...issueKeys.all(wsId), "environments"] as const,+ environments: (wsId: string, issueId: string) =>+ [...issueKeys.environmentsAll(wsId), issueId] as const,/** Prefix-match keys for invalidating the per-issue caches below across* all issues. These keys carry no wsId, so `issueKeys.all(wsId)` does NOT* cover them — WS reconnect recovery must invalidate these `*All`@@ -701,6 +706,17 @@ export function issueSubscribersOptions(issueId: string) {});}+// Reports arrive over realtime; the interval only re-derives "unreachable"+// once a daemon goes quiet, which no event announces.+export function issueEnvironmentsOptions(wsId: string, issueId: string) {+ return queryOptions({+ queryKey: issueKeys.environments(wsId, issueId),+ queryFn: () => api.listIssueEnvironments(issueId),+ enabled: !!wsId && !!issueId,+ refetchInterval: 60_000,+ });+}+export function issueUsageOptions(issueId: string) {return queryOptions({queryKey: issueKeys.usage(issueId),diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 687f02a7a9..f988878025 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -1002,6 +1002,10 @@ export function useRealtimeSync(// PR queries — the open issue detail page will refetch its own list.qc.invalidateQueries({ queryKey: ["github", "pull-requests"] });},+ environment: () => {+ const wsId = getCurrentWsId();+ if (wsId) qc.invalidateQueries({ queryKey: issueKeys.environmentsAll(wsId) });+ },// Powers the agent presence cache: any task lifecycle change// (dispatch / completed / failed / cancelled) refreshes the// workspace-wide agent-task-snapshot query so per-agent presencediff --git a/packages/core/types/environment.ts b/packages/core/types/environment.tsnew file mode 100644index 0000000000..e456445a54--- /dev/null+++ b/packages/core/types/environment.ts@@ -0,0 +1,31 @@+/** Where an environment came from: declared in `.multica/environments.toml`+ * and started by the daemon, or a server the daemon found listening inside+ * a task directory. */+export type IssueEnvironmentSource = "config" | "detected";++/** `unreachable` is derived by the server when the daemon that reported a+ * live environment has gone quiet. */+export type IssueEnvironmentState = "starting" | "running" | "exited" | "stopped" | "unreachable";++export interface IssueEnvironment {+ id: string;+ issue_id: string;+ task_id: string;+ runtime_id: string | null;+ agent_id: string | null;+ source: IssueEnvironmentSource;+ name: string;+ label: string;+ url: string;+ port: number | null;+ state: IssueEnvironmentState;+ detail: string;+ started_at: string;+ expires_at: string | null;+ last_seen_at: string;+ ended_at: string | null;+}++export interface IssueEnvironmentsResponse {+ environments: IssueEnvironment[];+}diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex a46fac5b4c..1dcdea400b 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -98,7 +98,8 @@ export type WSEventType =| "github_installation:deleted"| "pull_request:linked"| "pull_request:updated"- | "pull_request:unlinked";+ | "pull_request:unlinked"+ | "environment:changed";export interface WSMessage<T = unknown> {type: WSEventType;@@ -714,6 +715,7 @@ export interface WSEventPayloadMap {"pull_request:linked": unknown;"pull_request:updated": unknown;"pull_request:unlinked": unknown;+ "environment:changed": { issue_id: string };}/**diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex a6c6f04521..ab7609fa79 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -235,6 +235,12 @@ export type {ListGitHubRepositoriesResponse,GitHubConnectResponse,} from "./github";+export type {+ IssueEnvironment,+ IssueEnvironmentSource,+ IssueEnvironmentState,+ IssueEnvironmentsResponse,+} from "./environment";export type {VCSProvider,VCSConnection,diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 012f4572d4..4bacd6fe07 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -122,6 +122,7 @@ import { WakeupsSection } from "./wakeups-section";import { QuickActionsSection } from "./quick-actions-section";import { PluginPanelSection } from "../../plugins";import { PullRequestsSection } from "./pull-requests-section";+import { IssueEnvironmentsSection } from "./issue-environments-section";import { useGitHubSettings } from "@multica/core/github";import { DeliverablesSection } from "./deliverables/deliverables-section";import { IssueAppsSection } from "./issue-apps-section";@@ -3193,6 +3194,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr/>)}+ {/* Environments the issue's runs left running. Hidden until one starts. */}+ <IssueEnvironmentsSection issueId={id} />+{/* Deliverables — the files this issue's comments delivered. Hiddenwhile there are none. */}<DeliverablesSectiondiff --git a/packages/views/issues/components/issue-environments-section.test.tsx b/packages/views/issues/components/issue-environments-section.test.tsxnew file mode 100644index 0000000000..7475757fed--- /dev/null+++ b/packages/views/issues/components/issue-environments-section.test.tsx@@ -0,0 +1,186 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import type { AgentRuntime, IssueEnvironment } from "@multica/core/types";+import enCommon from "../../locales/en/common.json";+import enIssues from "../../locales/en/issues.json";++const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };++let mockEnvironments: IssueEnvironment[] = [];+let mockRuntimes: AgentRuntime[] = [];+let mockLocalDaemonId: string | null = null;++vi.mock("@multica/core/issues/queries", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/issues/queries")>()),+ issueEnvironmentsOptions: (wsId: string, issueId: string) => ({+ queryKey: ["issues", wsId, "environments", issueId],+ queryFn: async () => ({ environments: mockEnvironments }),+ }),+}));+vi.mock("@multica/core/runtimes/queries", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/runtimes/queries")>()),+ runtimeListOptions: (wsId: string) => ({+ queryKey: ["runtimes", wsId, "list"],+ queryFn: async () => mockRuntimes,+ }),+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (select: (state: { user: { id: string } }) => unknown) => select({ user: { id: "user-1" } }),+}));+vi.mock("../../platform/use-local-daemon-status", () => ({+ useLocalDaemonStatus: () => ({ daemonId: mockLocalDaemonId, deviceName: null, running: !!mockLocalDaemonId }),+}));+const copyText = vi.hoisted(() => vi.fn(async () => true));+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText }));++import { IssueEnvironmentsSection } from "./issue-environments-section";++const HOUR = 3_600_000;++function runtime(overrides: Partial<AgentRuntime>): AgentRuntime {+ return {+ id: "rt-1",+ workspace_id: "ws-1",+ daemon_id: "daemon-1",+ name: "Claude (studio.local)",+ runtime_mode: "local",+ provider: "claude",+ launch_header: "",+ status: "online",+ device_info: "studio.local · claude 1.0.0",+ metadata: {},+ owner_id: "user-1",+ visibility: "private",+ last_seen_at: new Date().toISOString(),+ created_at: "2026-11-10T00:00:00Z",+ updated_at: "2026-11-10T00:00:00Z",+ ...overrides,+ };+}++function environment(overrides: Partial<IssueEnvironment>): IssueEnvironment {+ return {+ id: "env-1",+ issue_id: "issue-1",+ task_id: "task-1",+ runtime_id: "rt-1",+ agent_id: "agent-1",+ source: "config",+ name: "web",+ label: "Web app",+ url: "http://localhost:41000",+ port: 41000,+ state: "running",+ detail: "",+ started_at: new Date(Date.now() - HOUR).toISOString(),+ expires_at: new Date(Date.now() + 23 * HOUR).toISOString(),+ last_seen_at: new Date().toISOString(),+ ended_at: null,+ ...overrides,+ };+}++function renderSection() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={qc}>+ <I18nProvider resources={TEST_RESOURCES} locale="en">+ <IssueEnvironmentsSection issueId="issue-1" />+ </I18nProvider>+ </QueryClientProvider>,+ );+}++describe("IssueEnvironmentsSection", () => {+ beforeEach(() => {+ mockEnvironments = [];+ mockRuntimes = [runtime({}), runtime({ id: "rt-2", daemon_id: "daemon-2", name: "Codex (build-02)", device_info: "build-02" })];+ mockLocalDaemonId = null;+ copyText.mockClear();+ });++ it("renders nothing while the issue has no environments", async () => {+ const { container } = renderSection();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(container).toBeEmptyDOMElement();+ });++ it("groups live environments by machine and links the running ones", async () => {+ mockLocalDaemonId = "daemon-1";+ mockEnvironments = [+ environment({}),+ environment({ id: "env-2", runtime_id: "rt-2", source: "detected", name: "node", label: "", url: "http://localhost:5173", port: 5173, expires_at: null }),+ ];+ renderSection();++ expect(await screen.findByText("Web app")).toBeVisible();+ expect(screen.getByText("2 running")).toBeVisible();+ expect(screen.getByText("This machine")).toBeVisible();+ expect(screen.getByText("studio.local")).toBeVisible();+ expect(screen.getByText("build-02")).toBeVisible();++ const [local, remote] = screen.getAllByTestId("environment-row");+ expect(within(local!).getByText("localhost:41000")).toBeVisible();+ expect(within(local!).getByText("Expires in 23h")).toBeVisible();+ expect(within(local!).getAllByRole("link")[0]).toHaveAttribute("href", "http://localhost:41000");+ expect(within(remote!).getByText("localhost:5173")).toBeVisible();+ expect(remote).toHaveAttribute("title", expect.stringContaining("Runs on build-02"));+ expect(local).not.toHaveAttribute("title");++ fireEvent.click(within(local!).getByRole("button", { name: "Copy URL" }));+ expect(copyText).toHaveBeenCalledWith("http://localhost:41000");+ });++ it("tells a viewer who may be on another machine where each localhost URL opens", async () => {+ mockEnvironments = [+ environment({ runtime_id: "rt-2" }),+ environment({ id: "env-2", runtime_id: "rt-gone", name: "api", label: "API", url: "http://127.0.0.1:41010", port: 41010 }),+ environment({ id: "env-3", runtime_id: "rt-2", name: "docs", label: "Docs", url: "https://docs.example.com", port: 0 }),+ ];+ renderSection();++ await screen.findByText("Web app");+ const rows = screen.getAllByTestId("environment-row");+ const row = (label: string) => rows.find((r) => within(r).queryByText(label))!;+ expect(row("Web app")).toHaveAttribute("title", "Runs on build-02. A localhost URL opens only on that machine.");+ expect(row("API")).toHaveAttribute("title", "A localhost URL opens only on the machine running it.");+ expect(row("Docs")).not.toHaveAttribute("title");+ });++ it("folds ended environments and shows why one exited", async () => {+ mockEnvironments = [+ environment({}),+ environment({+ id: "env-3",+ name: "api",+ label: "API",+ state: "exited",+ detail: "exit status 1",+ ended_at: new Date().toISOString(),+ expires_at: null,+ }),+ ];+ renderSection();++ const fold = await screen.findByRole("button", { name: /1 ended/ });+ expect(screen.queryByText("API")).not.toBeInTheDocument();+ fireEvent.click(fold);+ expect(screen.getByText("API")).toBeVisible();+ expect(screen.getByText("Exited")).toBeVisible();+ expect(screen.getByText("exit status 1")).toBeVisible();+ const ended = screen.getAllByTestId("environment-row")[1]!;+ expect(within(ended).queryByRole("link")).not.toBeInTheDocument();+ });++ it("offers no link for an environment whose daemon went quiet", async () => {+ mockEnvironments = [environment({ state: "unreachable" })];+ renderSection();+ const row = await screen.findByTestId("environment-row");+ expect(within(row).getByText("Not responding")).toBeVisible();+ expect(within(row).queryByRole("link")).not.toBeInTheDocument();+ expect(within(row).getByText(/Last seen/)).toBeVisible();+ });+});diff --git a/packages/views/issues/components/issue-environments-section.tsx b/packages/views/issues/components/issue-environments-section.tsxnew file mode 100644index 0000000000..37917894ea--- /dev/null+++ b/packages/views/issues/components/issue-environments-section.tsx@@ -0,0 +1,269 @@+"use client";++import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { ChevronRight, Copy, ExternalLink, Globe, Laptop, Server } from "@multica/ui/icons";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceId } from "@multica/core/hooks";+import { issueEnvironmentsOptions } from "@multica/core/issues/queries";+import { runtimeListOptions } from "@multica/core/runtimes/queries";+import type { IssueEnvironment, IssueEnvironmentState } from "@multica/core/types";+import { IconButton } from "@multica/ui/components/common/icon-button";+import { copyText } from "@multica/ui/lib/clipboard";+import { cn } from "@multica/ui/lib/utils";+import { useT, useTimeAgo } from "../../i18n";+import { useLocalDaemonStatus } from "../../platform/use-local-daemon-status";+import { buildRuntimeMachines, type RuntimeMachine } from "../../runtimes/components/runtime-machines";+import { IssueSidebarSectionHeader } from "./issue-sidebar-section";++type IssuesT = ReturnType<typeof useT<"issues">>["t"];++const STATE_TONE: Record<IssueEnvironmentState, string> = {+ starting: "text-warning",+ running: "text-success",+ unreachable: "text-warning",+ exited: "text-destructive",+ stopped: "text-muted-foreground",+};++const isLive = (env: IssueEnvironment) => env.ended_at === null;++type MachineGroup = { key: string; machine: RuntimeMachine | null; envs: IssueEnvironment[] };++/**+ * "Environments" in the issue sidebar: the servers this issue's runs left+ * running — declared in the repository's `.multica/environments.toml` or+ * found listening in a run's directory — grouped by the machine they run on,+ * because a localhost URL only opens there. Renders nothing until a run+ * starts one.+ */+export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const [open, setOpen] = useState(true);+ const [showEnded, setShowEnded] = useState(false);+ const { data } = useQuery(issueEnvironmentsOptions(wsId, issueId));+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));+ const local = useLocalDaemonStatus();+ const currentUserId = useAuthStore((state) => state.user?.id ?? null);++ const machineByRuntime = useMemo(() => {+ const machines = buildRuntimeMachines(runtimes, {+ now: Date.now(),+ localDaemonId: local.daemonId,+ localMachineName: local.deviceName,+ currentUserId,+ });+ const byRuntime = new Map<string, RuntimeMachine>();+ for (const machine of machines) {+ for (const runtime of machine.runtimes) byRuntime.set(runtime.id, machine);+ }+ return byRuntime;+ }, [runtimes, local.daemonId, local.deviceName, currentUserId]);++ const envs = data?.environments ?? [];+ if (envs.length === 0) return null;++ const live = envs.filter(isLive);+ const ended = envs.filter((env) => !isLive(env));+ const running = live.filter((env) => env.state === "running").length;+ // Only Desktop knows which machine it is on. Anywhere else, every+ // localhost URL may belong to another machine, so every row says whose it is.+ const knowsLocal = !!local.daemonId;+ const localhostHint = (machine: RuntimeMachine | null) => {+ if (knowsLocal && machine?.isCurrent) return null;+ return machine+ ? t(($) => $.environments.remote_hint, { machine: machine.title })+ : t(($) => $.environments.localhost_hint);+ };++ const groups = (list: IssueEnvironment[]) => {+ const byMachine = new Map<string, MachineGroup>();+ for (const env of list) {+ const machine = env.runtime_id ? machineByRuntime.get(env.runtime_id) ?? null : null;+ const key = machine?.id ?? "unknown";+ const group = byMachine.get(key) ?? { key, machine, envs: [] };+ group.envs.push(env);+ byMachine.set(key, group);+ }+ return [...byMachine.values()].sort((a, b) => Number(b.machine?.isCurrent ?? false) - Number(a.machine?.isCurrent ?? false));+ };++ const renderGroups = (list: IssueEnvironment[]) =>+ groups(list).map((group) => (+ <div key={group.key}>+ <div className="flex min-h-7 items-center gap-1.5 px-2 text-micro text-muted-foreground">+ <Laptop className="size-3 shrink-0" />+ <span className="min-w-0 truncate">{group.machine?.title ?? t(($) => $.environments.unknown_machine)}</span>+ {group.machine?.isCurrent ? (+ <span className="shrink-0 rounded-xs bg-muted px-1 text-micro font-medium">{t(($) => $.environments.this_machine)}</span>+ ) : null}+ </div>+ {group.envs.map((env) => (+ <EnvironmentRow+ key={env.id}+ env={env}+ localhostHint={localhostHint(group.machine)}+ />+ ))}+ </div>+ ));++ return (+ <div>+ <IssueSidebarSectionHeader+ title={t(($) => $.environments.section_title)}+ open={open}+ onOpenChange={setOpen}+ count={live.length}+ status={running > 0 ? (+ <span className="inline-flex shrink-0 items-center gap-1 text-caption text-success tabular-nums">+ <span aria-hidden="true" className="size-1.5 rounded-full bg-success" />+ {t(($) => $.environments.running_count, { count: running })}+ </span>+ ) : undefined}+ />+ {open && (+ <div className="px-2">+ {renderGroups(live)}+ {ended.length > 0 && (+ <>+ <button+ type="button"+ aria-expanded={showEnded}+ onClick={() => setShowEnded((v) => !v)}+ className="flex w-full items-center gap-1 rounded-md px-2 py-1 text-left text-micro text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"+ >+ {t(($) => $.environments.ended_count, { count: ended.length })}+ <ChevronRight aria-hidden="true" className={cn("size-3 text-faint-foreground transition-transform motion-reduce:transition-none", showEnded && "rotate-90")} />+ </button>+ {showEnded && renderGroups(ended)}+ </>+ )}+ </div>+ )}+ </div>+ );+}++function EnvironmentRow({ env, localhostHint }: { env: IssueEnvironment; localhostHint: string | null }) {+ const { t } = useT("issues");+ const timeAgo = useTimeAgo();+ const live = isLive(env);+ const openable = live && env.url !== "" && env.state !== "unreachable";+ const Icon = env.url ? Globe : Server;+ const host = env.url ? displayHost(env.url) : null;+ const title = env.source === "config" ? env.label || env.name : host ?? env.name;++ const parts: string[] = [];+ if (env.source === "config") {+ if (host) parts.push(host);+ } else {+ parts.push(env.name);+ }+ const meta = environmentMeta(env, t, timeAgo);+ const tooltip = [+ env.source === "detected" ? t(($) => $.environments.detected_hint) : null,+ env.detail || null,+ isLoopbackUrl(env.url) ? localhostHint : null,+ ].filter(Boolean).join("\n");++ const body = (+ <>+ <Icon className={cn("mt-px size-3.5 shrink-0", STATE_TONE[env.state] ?? "text-muted-foreground")} />+ <div className="min-w-0 flex-1">+ <p className="flex min-w-0 items-center gap-2">+ <span className="min-w-0 flex-1 truncate text-label font-medium">{title}</span>+ <span+ className={cn(+ "shrink-0 text-caption",+ STATE_TONE[env.state] ?? "text-muted-foreground",+ openable && "group-hover/env:invisible group-has-[:focus-visible]/env:invisible [@media(pointer:coarse)]:invisible",+ )}+ >+ {t(($) => $.environments.state[env.state])}+ </span>+ </p>+ <p className="mt-1 flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap text-caption text-muted-foreground tabular-nums">+ {parts.length > 0 && <span className="max-w-[70%] shrink-0 truncate">{parts.join(" · ")}</span>}+ {parts.length > 0 && meta && <span aria-hidden="true" className="text-faint-foreground">·</span>}+ {meta && <span className="min-w-0 truncate">{meta}</span>}+ </p>+ </div>+ </>+ );++ return (+ <div data-testid="environment-row" className="group/env relative rounded-md transition-colors hover:bg-accent/50" title={tooltip || undefined}>+ {openable ? (+ <a href={env.url} target="_blank" rel="noreferrer noopener" className="flex items-start gap-2 rounded-md px-2 py-2">+ {body}+ </a>+ ) : (+ <div className="flex items-start gap-2 px-2 py-2">{body}</div>+ )}+ {openable && (+ <div className="absolute top-1 right-1 flex items-center gap-0.5 opacity-0 group-hover/env:opacity-100 group-has-[:focus-visible]/env:opacity-100 [@media(pointer:coarse)]:opacity-100">+ <IconButton+ variant="ghost"+ size="icon-xs"+ label={t(($) => $.environments.open)}+ nativeButton={false}+ render={<a href={env.url} target="_blank" rel="noreferrer noopener" />}+ >+ <ExternalLink />+ </IconButton>+ <IconButton+ variant="ghost"+ size="icon-xs"+ label={t(($) => $.environments.copy_url)}+ onClick={() => {+ void copyText(env.url).then((ok) => {+ if (ok) toast.success(t(($) => $.environments.copied));+ else toast.error(t(($) => $.environments.copy_failed));+ });+ }}+ >+ <Copy />+ </IconButton>+ </div>+ )}+ </div>+ );+}++function environmentMeta(env: IssueEnvironment, t: IssuesT, timeAgo: (iso: string) => string): string | null {+ if (env.ended_at) {+ if (env.state === "exited" && env.detail) return env.detail;+ return t(($) => $.environments.ended_ago, { time: timeAgo(env.ended_at) });+ }+ if (env.state === "unreachable") return t(($) => $.environments.last_seen, { time: timeAgo(env.last_seen_at) });+ if (env.expires_at) {+ const minutes = Math.max(1, Math.round((new Date(env.expires_at).getTime() - Date.now()) / 60_000));+ if (minutes < 60) return t(($) => $.environments.expires_in_minutes, { count: minutes });+ const hours = Math.round(minutes / 60);+ if (hours < 48) return t(($) => $.environments.expires_in_hours, { count: hours });+ return t(($) => $.environments.expires_in_days, { count: Math.round(hours / 24) });+ }+ return t(($) => $.environments.started_ago, { time: timeAgo(env.started_at) });+}++function isLoopbackUrl(url: string): boolean {+ try {+ const host = new URL(url).hostname;+ return host === "localhost" || host.endsWith(".localhost") || host === "[::1]" || host === "0.0.0.0" || host.startsWith("127.");+ } catch {+ return false;+ }+}++function displayHost(url: string): string | null {+ try {+ const parsed = new URL(url);+ const path = parsed.pathname === "/" ? "" : parsed.pathname;+ return `${parsed.host}${path}`;+ } catch {+ return null;+ }+}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 570fd9996e..de04357864 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -1908,5 +1908,37 @@"rejected": "Declined","rate_limited": "Rate limited"}+ },+ "environments": {+ "section_title": "Environments",+ "running_count_one": "{{count}} running",+ "running_count_other": "{{count}} running",+ "this_machine": "This machine",+ "unknown_machine": "Unknown machine",+ "state": {+ "starting": "Starting",+ "running": "Running",+ "exited": "Exited",+ "stopped": "Stopped",+ "unreachable": "Not responding"+ },+ "expires_in_minutes_one": "Expires in {{count}}m",+ "expires_in_minutes_other": "Expires in {{count}}m",+ "expires_in_hours_one": "Expires in {{count}}h",+ "expires_in_hours_other": "Expires in {{count}}h",+ "expires_in_days_one": "Expires in {{count}}d",+ "expires_in_days_other": "Expires in {{count}}d",+ "started_ago": "Started {{time}}",+ "ended_ago": "Ended {{time}}",+ "last_seen": "Last seen {{time}}",+ "ended_count_one": "{{count}} ended",+ "ended_count_other": "{{count}} ended",+ "detected_hint": "Found listening in the directory of one of this issue's runs",+ "remote_hint": "Runs on {{machine}}. A localhost URL opens only on that machine.",+ "localhost_hint": "A localhost URL opens only on the machine running it.",+ "open": "Open",+ "copy_url": "Copy URL",+ "copied": "URL copied",+ "copy_failed": "Couldn't copy the URL"}}diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex 13d02aba7a..0be015db6b 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -1908,5 +1908,37 @@"rejected": "Rechazada","rate_limited": "Límite de llamadas alcanzado"}+ },+ "environments": {+ "section_title": "Entornos",+ "running_count_one": "{{count}} en ejecución",+ "running_count_other": "{{count}} en ejecución",+ "this_machine": "Este equipo",+ "unknown_machine": "Equipo desconocido",+ "state": {+ "starting": "Iniciando",+ "running": "En ejecución",+ "exited": "Terminado",+ "stopped": "Detenido",+ "unreachable": "Sin respuesta"+ },+ "expires_in_minutes_one": "Caduca en {{count}} min",+ "expires_in_minutes_other": "Caduca en {{count}} min",+ "expires_in_hours_one": "Caduca en {{count}} h",+ "expires_in_hours_other": "Caduca en {{count}} h",+ "expires_in_days_one": "Caduca en {{count}} d",+ "expires_in_days_other": "Caduca en {{count}} d",+ "started_ago": "Iniciado {{time}}",+ "ended_ago": "Finalizado {{time}}",+ "last_seen": "Última respuesta {{time}}",+ "ended_count_one": "{{count}} finalizado",+ "ended_count_other": "{{count}} finalizados",+ "detected_hint": "Servidor encontrado en el directorio de una ejecución de esta tarea",+ "remote_hint": "Se ejecuta en {{machine}}. Una URL localhost solo se abre en ese equipo.",+ "localhost_hint": "Una URL localhost solo se abre en el equipo que la ejecuta.",+ "open": "Abrir",+ "copy_url": "Copiar URL",+ "copied": "URL copiada",+ "copy_failed": "No se pudo copiar la URL"}}diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 2512c0c6dd..f19f45a94c 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -1908,5 +1908,37 @@"rejected": "Refusé","rate_limited": "Limite atteinte"}+ },+ "environments": {+ "section_title": "Environnements",+ "running_count_one": "{{count}} en cours",+ "running_count_other": "{{count}} en cours",+ "this_machine": "Cet appareil",+ "unknown_machine": "Appareil inconnu",+ "state": {+ "starting": "Démarrage",+ "running": "En cours",+ "exited": "Terminé",+ "stopped": "Arrêté",+ "unreachable": "Sans réponse"+ },+ "expires_in_minutes_one": "Expire dans {{count}} min",+ "expires_in_minutes_other": "Expire dans {{count}} min",+ "expires_in_hours_one": "Expire dans {{count}} h",+ "expires_in_hours_other": "Expire dans {{count}} h",+ "expires_in_days_one": "Expire dans {{count}} j",+ "expires_in_days_other": "Expire dans {{count}} j",+ "started_ago": "Démarré {{time}}",+ "ended_ago": "Terminé {{time}}",+ "last_seen": "Dernière réponse {{time}}",+ "ended_count_one": "{{count}} terminé",+ "ended_count_other": "{{count}} terminés",+ "detected_hint": "Serveur trouvé dans le répertoire d'une exécution de cette tâche",+ "remote_hint": "S'exécute sur {{machine}}. Une URL localhost ne s'ouvre que sur cet appareil.",+ "localhost_hint": "Une URL localhost ne s'ouvre que sur l'appareil qui l'exécute.",+ "open": "Ouvrir",+ "copy_url": "Copier l'URL",+ "copied": "URL copiée",+ "copy_failed": "Impossible de copier l'URL"}}diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex fbbc594180..9399ee5195 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -1838,5 +1838,32 @@"rejected": "却下","rate_limited": "レート制限"}+ },+ "environments": {+ "section_title": "環境",+ "running_count_other": "{{count}} 件実行中",+ "this_machine": "このマシン",+ "unknown_machine": "不明なマシン",+ "state": {+ "starting": "起動中",+ "running": "実行中",+ "exited": "終了",+ "stopped": "停止",+ "unreachable": "応答なし"+ },+ "expires_in_minutes_other": "{{count}}分後に期限切れ",+ "expires_in_hours_other": "{{count}}時間後に期限切れ",+ "expires_in_days_other": "{{count}}日後に期限切れ",+ "started_ago": "起動: {{time}}",+ "ended_ago": "終了: {{time}}",+ "last_seen": "最終応答: {{time}}",+ "ended_count_other": "終了済み {{count}} 件",+ "detected_hint": "このタスクの実行ディレクトリで待ち受けていたサーバー",+ "remote_hint": "{{machine}} で実行中です。localhost の URL はそのマシンでのみ開けます。",+ "localhost_hint": "localhost の URL は、それを実行しているマシンでのみ開けます。",+ "open": "開く",+ "copy_url": "URL をコピー",+ "copied": "URL をコピーしました",+ "copy_failed": "URL をコピーできませんでした"}}diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 6a6d92f0fb..f670120449 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -1838,5 +1838,32 @@"rejected": "거절됨","rate_limited": "속도 제한"}+ },+ "environments": {+ "section_title": "환경",+ "running_count_other": "{{count}}개 실행 중",+ "this_machine": "이 기기",+ "unknown_machine": "알 수 없는 기기",+ "state": {+ "starting": "시작 중",+ "running": "실행 중",+ "exited": "종료됨",+ "stopped": "중지됨",+ "unreachable": "응답 없음"+ },+ "expires_in_minutes_other": "{{count}}분 후 만료",+ "expires_in_hours_other": "{{count}}시간 후 만료",+ "expires_in_days_other": "{{count}}일 후 만료",+ "started_ago": "시작: {{time}}",+ "ended_ago": "종료: {{time}}",+ "last_seen": "마지막 응답: {{time}}",+ "ended_count_other": "종료됨 {{count}}개",+ "detected_hint": "이 태스크의 실행 디렉터리에서 발견된 서버",+ "remote_hint": "{{machine}}에서 실행 중입니다. localhost URL은 해당 기기에서만 열 수 있습니다.",+ "localhost_hint": "localhost URL은 이를 실행 중인 기기에서만 열 수 있습니다.",+ "open": "열기",+ "copy_url": "URL 복사",+ "copied": "URL을 복사했습니다",+ "copy_failed": "URL을 복사할 수 없습니다"}}diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 61bce2515f..6d40bfdc14 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -2054,5 +2054,47 @@"rejected": "Отклонено","rate_limited": "Лимит вызовов достигнут"}+ },+ "environments": {+ "section_title": "Окружения",+ "running_count_one": "{{count}} работает",+ "running_count_few": "{{count}} работают",+ "running_count_many": "{{count}} работают",+ "running_count_other": "{{count}} работают",+ "this_machine": "Это устройство",+ "unknown_machine": "Неизвестное устройство",+ "state": {+ "starting": "Запускается",+ "running": "Работает",+ "exited": "Завершилось",+ "stopped": "Остановлено",+ "unreachable": "Не отвечает"+ },+ "expires_in_minutes_one": "Истекает через {{count}} мин",+ "expires_in_minutes_few": "Истекает через {{count}} мин",+ "expires_in_minutes_many": "Истекает через {{count}} мин",+ "expires_in_minutes_other": "Истекает через {{count}} мин",+ "expires_in_hours_one": "Истекает через {{count}} ч",+ "expires_in_hours_few": "Истекает через {{count}} ч",+ "expires_in_hours_many": "Истекает через {{count}} ч",+ "expires_in_hours_other": "Истекает через {{count}} ч",+ "expires_in_days_one": "Истекает через {{count}} д",+ "expires_in_days_few": "Истекает через {{count}} д",+ "expires_in_days_many": "Истекает через {{count}} д",+ "expires_in_days_other": "Истекает через {{count}} д",+ "started_ago": "Запущено {{time}}",+ "ended_ago": "Завершено {{time}}",+ "last_seen": "Последний ответ {{time}}",+ "ended_count_one": "{{count}} завершено",+ "ended_count_few": "{{count}} завершено",+ "ended_count_many": "{{count}} завершено",+ "ended_count_other": "{{count}} завершено",+ "detected_hint": "Сервер, найденный в каталоге одного из выполнений этой задачи",+ "remote_hint": "Работает на {{machine}}. Адрес localhost открывается только на этом устройстве.",+ "localhost_hint": "Адрес localhost открывается только на устройстве, где он запущен.",+ "open": "Открыть",+ "copy_url": "Копировать URL",+ "copied": "URL скопирован",+ "copy_failed": "Не удалось скопировать URL"}}diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 3e75927f2a..2b13e9f3fd 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -1838,5 +1838,32 @@"rejected": "已拒绝","rate_limited": "已限流"}+ },+ "environments": {+ "section_title": "环境",+ "running_count_other": "{{count}} 个运行中",+ "this_machine": "本机",+ "unknown_machine": "未知设备",+ "state": {+ "starting": "启动中",+ "running": "运行中",+ "exited": "已退出",+ "stopped": "已停止",+ "unreachable": "无响应"+ },+ "expires_in_minutes_other": "{{count}} 分钟后过期",+ "expires_in_hours_other": "{{count}} 小时后过期",+ "expires_in_days_other": "{{count}} 天后过期",+ "started_ago": "{{time}}启动",+ "ended_ago": "{{time}}结束",+ "last_seen": "{{time}}最后响应",+ "ended_count_other": "{{count}} 个已结束",+ "detected_hint": "在这个任务某次运行的目录中发现的服务",+ "remote_hint": "运行在 {{machine}} 上,localhost 地址只能在那台机器上打开。",+ "localhost_hint": "localhost 地址只能在运行它的那台机器上打开。",+ "open": "打开",+ "copy_url": "复制地址",+ "copied": "已复制地址",+ "copy_failed": "无法复制地址"}}diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex b829ee47c3..298186776d 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -1838,5 +1838,32 @@"rejected": "已拒絕","rate_limited": "已限流"}+ },+ "environments": {+ "section_title": "環境",+ "running_count_other": "{{count}} 個執行中",+ "this_machine": "本機",+ "unknown_machine": "未知裝置",+ "state": {+ "starting": "啟動中",+ "running": "執行中",+ "exited": "已退出",+ "stopped": "已停止",+ "unreachable": "無回應"+ },+ "expires_in_minutes_other": "{{count}} 分鐘後到期",+ "expires_in_hours_other": "{{count}} 小時後到期",+ "expires_in_days_other": "{{count}} 天後到期",+ "started_ago": "{{time}}啟動",+ "ended_ago": "{{time}}結束",+ "last_seen": "{{time}}最後回應",+ "ended_count_other": "{{count}} 個已結束",+ "detected_hint": "在這個任務某次執行的目錄中發現的服務",+ "remote_hint": "執行於 {{machine}},localhost 位址只能在那台機器上開啟。",+ "localhost_hint": "localhost 位址只能在執行它的那台機器上開啟。",+ "open": "開啟",+ "copy_url": "複製位址",+ "copied": "已複製位址",+ "copy_failed": "無法複製位址"}}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 14710c9254..91f2be8014 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,8 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "635_issue_environment_issue_idx": "idx_issue_environment_issue",+ "634_issue_environment_task_key_idx": "uq_issue_environment_task_key","632_project_member_user_idx": "idx_project_member_workspace_user","628_app_action_request_chat_idx": "idx_app_action_request_chat","627_app_tool_call_issue_idx": "idx_app_tool_call_issue",diff --git a/server/cmd/multica/cmd_environment.go b/server/cmd/multica/cmd_environment.gonew file mode 100644index 0000000000..69051c89e1--- /dev/null+++ b/server/cmd/multica/cmd_environment.go@@ -0,0 +1,259 @@+package main++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "strings"+ "time"++ "github.com/multica-ai/multica/server/internal/cli"+ "github.com/spf13/cobra"+)++var environmentCmd = &cobra.Command{+ Use: "environment",+ Aliases: []string{"env"},+ Short: "Start and stop the environments a repository declares",+ Long: "Runs the environments declared in the repository's .multica/environments.toml under the daemon, " ++ "so they keep running after the task ends and show in the issue sidebar.\n\n" ++ "Each environment gets a port block of its own: MULTICA_PORT through MULTICA_PORT+9. " ++ "Its output goes to a log file the daemon keeps, and it is stopped when its TTL runs out.\n\n" ++ "Example .multica/environments.toml:\n\n" ++ " [environments.web]\n" ++ " label = \"Web app\"\n" ++ " start = \"pnpm dev --port $MULTICA_PORT\"\n" ++ " # url defaults to http://localhost:$MULTICA_PORT; url = \"\" for none\n" ++ " # ready = \"http://localhost:$MULTICA_PORT/health\"\n" ++ " # stop = \"docker compose down\"\n" ++ " ttl = \"24h\"\n\n" ++ "These commands run inside a daemon task; they use the task's credential.",+}++var environmentStartCmd = &cobra.Command{+ Use: "start <name>",+ Short: "Start a declared environment, or return it if it is already running",+ Long: "Starts the named environment from the .multica/environments.toml found in the current directory or a parent. " ++ "Starting one that is already running on this issue returns it unchanged. " ++ "By default the command waits until the environment answers at its ready URL with a status below 500 and prints its URL.",+ Args: exactArgs(1),+ RunE: runEnvironmentStart,+}++var environmentStopCmd = &cobra.Command{+ Use: "stop <name>",+ Short: "Stop a running environment",+ Long: "Runs the environment's stop command, if it declares one, then stops whatever is left of its processes.",+ Args: exactArgs(1),+ RunE: runEnvironmentStop,+}++var environmentListCmd = &cobra.Command{+ Use: "list",+ Short: "List this issue's environments on this machine",+ Args: cobra.NoArgs,+ RunE: runEnvironmentList,+}++func init() {+ environmentStartCmd.Flags().Bool("wait", true, "wait until the environment is ready (or exits) before returning")+ environmentStartCmd.Flags().String("output", "table", "Output format: table or json")+ environmentStopCmd.Flags().String("output", "table", "Output format: table or json")+ environmentListCmd.Flags().String("output", "table", "Output format: table or json")++ environmentCmd.AddCommand(environmentStartCmd)+ environmentCmd.AddCommand(environmentStopCmd)+ environmentCmd.AddCommand(environmentListCmd)+}++// daemonEnvironment mirrors localenv.Environment as the daemon serves it.+type daemonEnvironment struct {+ Key string `json:"key"`+ Name string `json:"name"`+ Label string `json:"label"`+ URL string `json:"url"`+ Port int `json:"port"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt time.Time `json:"started_at"`+ ExpiresAt *time.Time `json:"expires_at"`+ LogPath string `json:"log_path"`+}++type daemonEnvironmentResponse struct {+ Environment *daemonEnvironment `json:"environment"`+ Environments []daemonEnvironment `json:"environments"`+}++func runEnvironmentStart(cmd *cobra.Command, args []string) error {+ wait, _ := cmd.Flags().GetBool("wait")+ dir, err := os.Getwd()+ if err != nil {+ return fmt.Errorf("get working directory: %w", err)+ }+ var resp daemonEnvironmentResponse+ err = callDaemonEnvironment(cmd.Context(), "/environments/start", map[string]any{+ "name": args[0],+ "dir": dir,+ "path": os.Getenv("PATH"),+ "wait": wait,+ }, &resp, 11*time.Minute)+ if err != nil {+ return err+ }+ if resp.Environment == nil {+ return fmt.Errorf("daemon returned no environment")+ }+ env := *resp.Environment+ if output, _ := cmd.Flags().GetString("output"); output == "json" {+ if err := cli.PrintJSON(os.Stdout, env); err != nil {+ return err+ }+ } else if env.URL != "" {+ fmt.Fprintln(os.Stdout, env.URL)+ }+ switch env.State {+ case "exited", "stopped":+ if tail := logTail(env.LogPath, 20); tail != "" {+ fmt.Fprintf(os.Stderr, "Last lines of %s:\n%s\n", env.LogPath, tail)+ }+ reason := env.State+ if env.Detail != "" {+ reason += " (" + env.Detail + ")"+ }+ return fmt.Errorf("environment %s %s; log: %s", env.Name, reason, env.LogPath)+ case "starting":+ if wait {+ fmt.Fprintf(os.Stderr, "Environment %s is still starting: %s (log: %s)\n", env.Name, env.Detail, env.LogPath)+ return nil+ }+ }+ fmt.Fprintln(os.Stderr, environmentStartSummary(env))+ return nil+}++// logTail returns the last n lines of the environment's log, read locally:+// the daemon never sends its output anywhere.+func logTail(path string, n int) string {+ if path == "" {+ return ""+ }+ f, err := os.Open(path)+ if err != nil {+ return ""+ }+ defer f.Close()+ const maxTail = 16 << 10+ if info, err := f.Stat(); err == nil && info.Size() > maxTail {+ if _, err := f.Seek(-maxTail, io.SeekEnd); err != nil {+ return ""+ }+ }+ data, err := io.ReadAll(f)+ if err != nil {+ return ""+ }+ lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")+ if len(lines) > n {+ lines = lines[len(lines)-n:]+ }+ return strings.Join(lines, "\n")+}++func environmentStartSummary(env daemonEnvironment) string {+ var b strings.Builder+ fmt.Fprintf(&b, "Environment %s is %s", env.Name, env.State)+ if env.URL != "" {+ fmt.Fprintf(&b, " at %s", env.URL)+ }+ fmt.Fprintf(&b, " (ports %d-%d). Log: %s.", env.Port, env.Port+9, env.LogPath)+ if env.ExpiresAt != nil {+ fmt.Fprintf(&b, " It stops at %s", env.ExpiresAt.Local().Format(time.RFC3339))+ }+ fmt.Fprintf(&b, "; stop it sooner with `multica env stop %s`.", env.Name)+ return b.String()+}++func runEnvironmentStop(cmd *cobra.Command, args []string) error {+ var resp daemonEnvironmentResponse+ if err := callDaemonEnvironment(cmd.Context(), "/environments/stop", map[string]any{"name": args[0]}, &resp, 2*time.Minute); err != nil {+ return err+ }+ if output, _ := cmd.Flags().GetString("output"); output == "json" && resp.Environment != nil {+ return cli.PrintJSON(os.Stdout, *resp.Environment)+ }+ fmt.Fprintf(os.Stdout, "Stopped %s.\n", args[0])+ return nil+}++func runEnvironmentList(cmd *cobra.Command, _ []string) error {+ var resp daemonEnvironmentResponse+ if err := callDaemonEnvironment(cmd.Context(), "/environments/list", map[string]any{}, &resp, 30*time.Second); err != nil {+ return err+ }+ if resp.Environments == nil {+ resp.Environments = []daemonEnvironment{}+ }+ if output, _ := cmd.Flags().GetString("output"); output == "json" {+ return cli.PrintJSON(os.Stdout, resp.Environments)+ }+ if len(resp.Environments) == 0 {+ fmt.Fprintln(os.Stderr, "No environments.")+ return nil+ }+ rows := make([][]string, 0, len(resp.Environments))+ for _, env := range resp.Environments {+ rows = append(rows, []string{env.Name, env.State, env.URL, env.LogPath})+ }+ cli.PrintTable(os.Stdout, []string{"NAME", "STATE", "URL", "LOG"}, rows)+ return nil+}++func callDaemonEnvironment(parent context.Context, path string, body, out any, timeout time.Duration) error {+ daemonPort := os.Getenv("MULTICA_DAEMON_PORT")+ if daemonPort == "" {+ return fmt.Errorf("MULTICA_DAEMON_PORT not set (this command is intended to be run by an agent inside a daemon task)")+ }+ taskToken := os.Getenv("MULTICA_TOKEN")+ if taskToken == "" {+ return fmt.Errorf("MULTICA_TOKEN not set (environment commands require the active task credential)")+ }+ data, err := json.Marshal(body)+ if err != nil {+ return fmt.Errorf("encode request: %w", err)+ }+ if parent == nil {+ parent = context.Background()+ }+ ctx, cancel := context.WithTimeout(parent, timeout)+ defer cancel()+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%s%s", daemonPort, path), bytes.NewReader(data))+ if err != nil {+ return fmt.Errorf("create daemon request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+taskToken)+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ return fmt.Errorf("connect to daemon: %w", err)+ }+ defer resp.Body.Close()+ respBody, err := io.ReadAll(resp.Body)+ if err != nil {+ return fmt.Errorf("read daemon response: %w", err)+ }+ if resp.StatusCode == http.StatusNotFound && strings.HasPrefix(string(respBody), "404 page not found") {+ return fmt.Errorf("this daemon does not support environments yet; update it with `multica update`")+ }+ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("%s", strings.TrimSpace(string(respBody)))+ }+ if err := json.Unmarshal(respBody, out); err != nil {+ return fmt.Errorf("parse daemon response: %w", err)+ }+ return nil+}diff --git a/server/cmd/multica/cmd_environment_test.go b/server/cmd/multica/cmd_environment_test.gonew file mode 100644index 0000000000..75ef9ace12--- /dev/null+++ b/server/cmd/multica/cmd_environment_test.go@@ -0,0 +1,114 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++func newEnvironmentTestCmd(flags map[string]string) *cobra.Command {+ cmd := &cobra.Command{Use: "env-test"}+ cmd.Flags().Bool("wait", true, "")+ cmd.Flags().String("output", "table", "")+ for k, v := range flags {+ _ = cmd.Flags().Set(k, v)+ }+ return cmd+}++func fakeEnvironmentDaemon(t *testing.T, handler http.HandlerFunc) {+ t.Helper()+ srv := httptest.NewServer(handler)+ t.Cleanup(srv.Close)+ u, _ := url.Parse(srv.URL)+ t.Setenv("MULTICA_DAEMON_PORT", u.Port())+ t.Setenv("MULTICA_TOKEN", "mat_task")+}++func TestEnvironmentStartSendsTheTaskContextAndPrintsTheURL(t *testing.T) {+ var got map[string]any+ fakeEnvironmentDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/environments/start" || r.Header.Get("Authorization") != "Bearer mat_task" {+ t.Errorf("request = %s %s", r.URL.Path, r.Header.Get("Authorization"))+ }+ json.NewDecoder(r.Body).Decode(&got)+ json.NewEncoder(w).Encode(map[string]any{"environment": map[string]any{+ "name": "web", "url": "http://localhost:41000", "port": 41000, "state": "running", "log_path": "/tmp/web.log",+ }})+ })+ t.Setenv("PATH", "/opt/node/bin:/usr/bin")+ wd, _ := os.Getwd()++ out, err := captureStdout(t, func() error { return runEnvironmentStart(newEnvironmentTestCmd(nil), []string{"web"}) })+ if err != nil {+ t.Fatalf("start: %v", err)+ }+ if strings.TrimSpace(out) != "http://localhost:41000" {+ t.Fatalf("stdout = %q, want the URL alone", out)+ }+ if got["name"] != "web" || got["dir"] != wd || got["path"] != "/opt/node/bin:/usr/bin" || got["wait"] != true {+ t.Fatalf("request body = %v", got)+ }+}++func TestEnvironmentStartFailsWhenTheEnvironmentExited(t *testing.T) {+ fakeEnvironmentDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ json.NewEncoder(w).Encode(map[string]any{"environment": map[string]any{+ "name": "web", "state": "exited", "detail": "exit status 1", "log_path": "/tmp/web.log",+ }})+ })+ _, err := captureStdout(t, func() error { return runEnvironmentStart(newEnvironmentTestCmd(nil), []string{"web"}) })+ if err == nil || !strings.Contains(err.Error(), "exited (exit status 1)") || !strings.Contains(err.Error(), "/tmp/web.log") {+ t.Fatalf("err = %v, want the exit status and log path", err)+ }+}++func TestEnvironmentLogTailReadsTheLastLines(t *testing.T) {+ path := filepath.Join(t.TempDir(), "output.log")+ var lines []string+ for i := 1; i <= 30; i++ {+ lines = append(lines, fmt.Sprintf("line %d", i))+ }+ if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if got, want := logTail(path, 3), "line 28\nline 29\nline 30"; got != want {+ t.Fatalf("logTail = %q, want %q", got, want)+ }+ if got := logTail(filepath.Join(t.TempDir(), "missing.log"), 3); got != "" {+ t.Fatalf("logTail of a missing log = %q, want empty", got)+ }+}++func TestEnvironmentCommandsExplainAnOldDaemonAndDaemonErrors(t *testing.T) {+ fakeEnvironmentDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/environments/stop" {+ http.Error(w, `no running environment named "web" on this issue`, http.StatusNotFound)+ return+ }+ http.NotFound(w, r)+ })+ err := runEnvironmentList(newEnvironmentTestCmd(nil), nil)+ if err == nil || !strings.Contains(err.Error(), "multica update") {+ t.Fatalf("list against an old daemon = %v", err)+ }+ err = runEnvironmentStop(newEnvironmentTestCmd(nil), []string{"web"})+ if err == nil || err.Error() != `no running environment named "web" on this issue` {+ t.Fatalf("stop = %v, want the daemon's message", err)+ }+}++func TestEnvironmentCommandsNeedATask(t *testing.T) {+ t.Setenv("MULTICA_DAEMON_PORT", "")+ if err := runEnvironmentList(newEnvironmentTestCmd(nil), nil); err == nil || !strings.Contains(err.Error(), "inside a daemon task") {+ t.Fatalf("err = %v", err)+ }+}diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex d8c46a8a9d..bd81a9fd04 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -88,6 +88,7 @@ func init() {rootCmd.AddCommand(autopilotCmd)rootCmd.AddCommand(workspaceCmd)rootCmd.AddCommand(repoCmd)+ rootCmd.AddCommand(environmentCmd)rootCmd.AddCommand(skillCmd)rootCmd.AddCommand(squadCmd)rootCmd.AddCommand(chatCmd)diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 36cb356aa7..dd12d66017 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1673,6 +1673,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/tasks/{taskId}/complete", h.CompleteTask)r.Post("/tasks/{taskId}/fail", h.FailTask)r.Post("/tasks/{taskId}/usage", h.ReportTaskUsage)+ r.Post("/tasks/{taskId}/environments", h.ReportTaskEnvironments)r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)r.Post("/tasks/{taskId}/cancel-ack", h.AckTaskCancelled)@@ -2174,6 +2175,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/metadata/{key}", h.DeleteIssueMetadataKey)r.Put("/properties/{propertyId}", h.SetIssueProperty)r.Delete("/properties/{propertyId}", h.DeleteIssueProperty)+ r.Get("/environments", h.ListIssueEnvironments)r.Get("/pull-requests", h.ListPullRequestsForIssue)r.Post("/pull-requests", h.LinkIssuePullRequest)r.Delete("/pull-requests/{prId}", h.UnlinkIssuePullRequest)diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 70881082f8..fe4547f7f4 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -677,6 +677,31 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas// (task_id, provider, model), so snapshots cannot accumulate; the flag is what// keeps the server's additive metrics counter and per-run log on the terminal// report, where they would otherwise bill each flush against the last.+// TaskEnvironmentReport is one entry of a task's environment snapshot.+type TaskEnvironmentReport struct {+ Key string `json:"key"`+ Source string `json:"source"`+ Name string `json:"name"`+ Label string `json:"label"`+ URL string `json:"url"`+ Port int `json:"port"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt time.Time `json:"started_at"`+ ExpiresAt *time.Time `json:"expires_at"`+}++// ReportTaskEnvironments replaces the task's environment snapshot; whatever+// it leaves out the server records as stopped.+func (c *Client) ReportTaskEnvironments(ctx context.Context, taskID string, envs []TaskEnvironmentReport) error {+ if envs == nil {+ envs = []TaskEnvironmentReport{}+ }+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/environments", taskID), map[string]any{+ "environments": envs,+ }, nil)+}+func (c *Client) ReportTaskUsageSnapshot(ctx context.Context, taskID string, usage []TaskUsageEntry) error {if len(usage) == 0 {return nildiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 88e11690fc..4e57332ab8 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -29,6 +29,7 @@ import ("github.com/multica-ai/multica/server/internal/cli""github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/internal/daemon/localenv""github.com/multica-ai/multica/server/internal/daemon/repocache""github.com/multica-ai/multica/server/internal/selfexec""github.com/multica-ai/multica/server/internal/util"@@ -711,6 +712,11 @@ type Daemon struct {repoCheckoutTasksMu sync.RWMutexrepoCheckoutTasks map[string]activeRepoCheckoutTask+ // environments supervises what tasks start with `multica env start` and+ // reports it, with the servers detected in task directories, to each+ // task's issue. Nil when the daemon has no workspaces root.+ environments *environmentService+// localPathLocks serialises agent tasks whose project resource is a// local_directory pinned to this daemon. Two tasks targeting the same// on-disk path run sequentially; the second blocks on the lock and is@@ -811,6 +817,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {reconcile: newReconcileBroadcaster(),workspaceChanges: newWorkspaceChangeSignal(),wsRPC: newWSRPCClient(wsRPCResponseGrace),+ environments: newEnvironmentService(cfg, client, environmentIgnoreCommands(cfg.Agents), logger),}d.activeEnvRootsCond = sync.NewCond(&d.activeEnvRootsMu)d.activeStoresCond = sync.NewCond(&d.activeStoresMu)@@ -2179,6 +2186,7 @@ func (d *Daemon) run(ctx context.Context, healthLn net.Listener) error {go d.gcLoop(ctx)go d.autoUpdateLoop(ctx)go d.tokenRenewalLoop(ctx)+ go d.environments.run(ctx)// Preflight succeeded and the background loops are up: the daemon has// registered its runtimes and can now claim and run tasks. Flip /health@@ -9067,11 +9075,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot id.registerActiveRepoCheckoutTask(agentToken, activeRepoCheckoutTask{WorkspaceID: task.WorkspaceID,TaskID: task.ID,+ IssueID: task.IssueID,AgentID: task.AgentID,AgentName: task.Agent.Name,WorkDir: env.WorkDir,})defer d.clearActiveRepoCheckoutTask(agentToken)+ defer d.environments.trackTask(env.RootDir, localenv.Task{+ TaskID: task.ID, IssueID: task.IssueID, WorkspaceID: task.WorkspaceID,+ })()taskLog.Debug("invoking backend","provider", provider,diff --git a/server/internal/daemon/environments.go b/server/internal/daemon/environments.gonew file mode 100644index 0000000000..efbf081050--- /dev/null+++ b/server/internal/daemon/environments.go@@ -0,0 +1,478 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/internal/daemon/localenv"+)++const (+ environmentTickInterval = 15 * time.Second+ // Detection shells out to lsof on macOS, so it runs at half the tick rate.+ environmentDetectEvery = 2+ // A live snapshot is re-sent at least this often so the server can tell a+ // daemon that went away from one that has nothing new to say.+ environmentHeartbeat = time.Minute+ environmentReportedFile = "reported.json"+ environmentStartTimeout = 10 * time.Minute+)++type environmentReporter interface {+ ReportTaskEnvironments(ctx context.Context, taskID string, envs []TaskEnvironmentReport) error+}++// environmentService supervises the environments tasks start with+// `multica env start`, detects servers agents started on their own, and+// reports both to the issue each task belongs to.+type environmentService struct {+ manager *localenv.Manager+ detector *localenv.Detector+ client environmentReporter+ logger *slog.Logger+ workspacesRoot string+ stateDir string+ wake chan struct{}++ mu sync.Mutex+ // tasks maps the env root of each running task to its identity, so a+ // server started inside it is attributed before .gc_meta.json exists.+ tasks map[string]localenv.Task+ detected []localenv.Environment+ // sticky keeps a detected server on the task that first reported it when+ // a later task reuses the same directory.+ sticky map[string]string+ // reported is owned by the report loop: task ID → the last snapshot sent.+ reported map[string]reportedSnapshot+}++type reportedSnapshot struct {+ fingerprint string+ sentAt time.Time+}++func newEnvironmentService(cfg Config, client environmentReporter, ignoreCommands []string, logger *slog.Logger) *environmentService {+ if strings.TrimSpace(cfg.WorkspacesRoot) == "" {+ return nil+ }+ root := cfg.WorkspacesRoot+ if resolved, err := filepath.EvalSymlinks(root); err == nil {+ root = resolved+ }+ stateDir := filepath.Join(cfg.WorkspacesRoot, ".environments", "v1")+ return &environmentService{+ manager: localenv.NewManager(stateDir, logger),+ detector: localenv.NewDetector(ignoreCommands),+ client: client,+ logger: logger,+ workspacesRoot: root,+ stateDir: stateDir,+ wake: make(chan struct{}, 1),+ tasks: make(map[string]localenv.Task),+ sticky: make(map[string]string),+ reported: make(map[string]reportedSnapshot),+ }+}++// environmentIgnoreCommands names the processes detection never reports:+// the agent CLIs, whose own helper servers are not the task's environment.+func environmentIgnoreCommands(agents map[string]AgentEntry) []string {+ out := make([]string, 0, len(agents)*2)+ for name, entry := range agents {+ out = append(out, name)+ if entry.Path != "" {+ out = append(out, strings.TrimSuffix(filepath.Base(entry.Path), filepath.Ext(entry.Path)))+ }+ if entry.Command != "" {+ out = append(out, filepath.Base(entry.Command))+ }+ }+ return out+}++func (s *environmentService) trackTask(envRoot string, task localenv.Task) func() {+ if s == nil || envRoot == "" {+ return func() {}+ }+ if resolved, err := filepath.EvalSymlinks(envRoot); err == nil {+ envRoot = resolved+ }+ task.RootDir = envRoot+ s.mu.Lock()+ s.tasks[envRoot] = task+ s.mu.Unlock()+ return func() {+ s.mu.Lock()+ if s.tasks[envRoot].TaskID == task.TaskID {+ delete(s.tasks, envRoot)+ }+ s.mu.Unlock()+ }+}++// servesFrom reports whether a live environment runs from inside dir, so GC+// leaves the directory alone until it stops.+func (s *environmentService) servesFrom(dir string) bool {+ if s == nil {+ return false+ }+ if resolved, err := filepath.EvalSymlinks(dir); err == nil {+ dir = resolved+ }+ for _, env := range s.manager.Snapshot() {+ if (env.State == localenv.StateStarting || env.State == localenv.StateRunning) && pathWithin(env.Dir, dir) {+ return true+ }+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, env := range s.detected {+ if pathWithin(env.Dir, dir) {+ return true+ }+ }+ return false+}++func (s *environmentService) nudge() {+ if s == nil {+ return+ }+ select {+ case s.wake <- struct{}{}:+ default:+ }+}++func (s *environmentService) run(ctx context.Context) {+ if s == nil {+ return+ }+ if err := s.manager.Load(); err != nil {+ s.logger.Warn("environments: load state failed", "error", err)+ }+ s.loadReported()+ ticker := time.NewTicker(environmentTickInterval)+ defer ticker.Stop()+ for tick := 0; ; tick++ {+ s.manager.Tick()+ if tick%environmentDetectEvery == 0 {+ s.detect(ctx)+ }+ s.report(ctx, time.Now())+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ case <-s.wake:+ // A start or stop just happened; report it without detecting again.+ tick--+ }+ }+}++func (s *environmentService) detect(ctx context.Context) {+ found, err := s.detector.Detect(ctx, s.resolve, s.manager.Owns)+ if err != nil {+ s.logger.Debug("environments: detection failed", "error", err)+ return+ }+ s.mu.Lock()+ s.detected = found+ s.mu.Unlock()+}++// resolve attributes a working directory to the issue task whose env root+// contains it: a running task from the registry, else a finished one from+// its .gc_meta.json.+func (s *environmentService) resolve(cwd string) (localenv.Task, bool) {+ cwd = filepath.Clean(cwd)+ s.mu.Lock()+ for root, task := range s.tasks {+ if pathWithin(cwd, root) {+ s.mu.Unlock()+ return task, task.IssueID != ""+ }+ }+ s.mu.Unlock()++ rel, err := filepath.Rel(s.workspacesRoot, cwd)+ if err != nil || !filepath.IsLocal(rel) {+ return localenv.Task{}, false+ }+ parts := strings.Split(rel, string(filepath.Separator))+ if len(parts) < 2 || strings.HasPrefix(parts[0], ".") {+ return localenv.Task{}, false+ }+ envRoot := filepath.Join(s.workspacesRoot, parts[0], parts[1])+ meta, err := execenv.ReadGCMeta(envRoot)+ if err != nil || meta.Kind != execenv.GCKindIssue || meta.IssueID == "" || meta.TaskID == "" {+ return localenv.Task{}, false+ }+ return localenv.Task{TaskID: meta.TaskID, IssueID: meta.IssueID, WorkspaceID: meta.WorkspaceID, RootDir: envRoot}, true+}++// report sends each task's snapshot when it changed, as a heartbeat while it+// 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)+ }+ }+ s.mu.Lock()+ live := make(map[string]bool, len(s.detected))+ for _, env := range s.detected {+ live[env.Key] = true+ if owner, ok := s.sticky[env.Key]; ok {+ env.TaskID = owner+ } else {+ s.sticky[env.Key] = env.TaskID+ }+ groups[env.TaskID] = append(groups[env.TaskID], env)+ }+ for key := range s.sticky {+ if !live[key] {+ delete(s.sticky, key)+ }+ }+ s.mu.Unlock()+ for taskID := range s.reported {+ if _, ok := groups[taskID]; !ok {+ groups[taskID] = nil+ }+ }++ taskIDs := make([]string, 0, len(groups))+ for taskID := range groups {+ taskIDs = append(taskIDs, taskID)+ }+ sort.Strings(taskIDs)+ changed := false+ for _, taskID := range taskIDs {+ envs := groups[taskID]+ fingerprint := environmentFingerprint(envs)+ prev, had := s.reported[taskID]+ if !had && len(envs) == 0 {+ continue+ }+ if had && prev.fingerprint == fingerprint && (len(envs) == 0 || now.Sub(prev.sentAt) < environmentHeartbeat) {+ continue+ }+ err := s.client.ReportTaskEnvironments(ctx, taskID, toEnvironmentReports(envs))+ var reqErr *requestError+ switch {+ case err == nil:+ case errors.As(err, &reqErr) && (reqErr.StatusCode == http.StatusNotFound || reqErr.StatusCode == http.StatusForbidden):+ // The task is gone or belongs to a workspace this daemon left;+ // nothing will ever accept its snapshot.+ s.logger.Debug("environments: snapshot refused", "task_id", taskID, "status", reqErr.StatusCode)+ envs = nil+ default:+ if ctx.Err() == nil {+ s.logger.Warn("environments: report failed", "task_id", taskID, "error", err)+ }+ continue+ }+ if len(envs) == 0 {+ delete(s.reported, taskID)+ } else {+ s.reported[taskID] = reportedSnapshot{fingerprint: fingerprint, sentAt: now}+ }+ changed = changed || had != (len(envs) > 0)+ }+ if changed {+ s.saveReported()+ }+}++// The reported task set survives a restart, so the environments a stopped+// daemon reported are closed out instead of turning unreachable forever.+func (s *environmentService) loadReported() {+ data, err := os.ReadFile(filepath.Join(s.stateDir, environmentReportedFile))+ if err != nil {+ return+ }+ var taskIDs []string+ if json.Unmarshal(data, &taskIDs) != nil {+ return+ }+ for _, id := range taskIDs {+ s.reported[id] = reportedSnapshot{fingerprint: "restarted"}+ }+}++func (s *environmentService) saveReported() {+ taskIDs := make([]string, 0, len(s.reported))+ for id := range s.reported {+ taskIDs = append(taskIDs, id)+ }+ sort.Strings(taskIDs)+ data, _ := json.Marshal(taskIDs)+ if err := os.MkdirAll(s.stateDir, 0o700); err != nil {+ return+ }+ path := filepath.Join(s.stateDir, environmentReportedFile)+ if err := os.WriteFile(path+".tmp", data, 0o600); err == nil {+ os.Rename(path+".tmp", path)+ }+}++func environmentFingerprint(envs []localenv.Environment) string {+ parts := make([]string, 0, len(envs))+ for _, env := range envs {+ expires := ""+ if env.ExpiresAt != nil {+ expires = env.ExpiresAt.UTC().Format(time.RFC3339)+ }+ parts = append(parts, strings.Join([]string{env.Key, env.State, env.URL, env.Label, env.Detail, expires}, "\x1f"))+ }+ sort.Strings(parts)+ return strings.Join(parts, "\x1e")+}++func toEnvironmentReports(envs []localenv.Environment) []TaskEnvironmentReport {+ out := make([]TaskEnvironmentReport, 0, len(envs))+ for _, env := range envs {+ out = append(out, TaskEnvironmentReport{+ Key: env.Key, Source: env.Source, Name: env.Name, Label: env.Label, URL: env.URL,+ Port: env.Port, State: env.State, Detail: env.Detail, StartedAt: env.StartedAt, ExpiresAt: env.ExpiresAt,+ })+ }+ return out+}++func pathWithin(path, root string) bool {+ if path == "" || root == "" {+ return false+ }+ rel, err := filepath.Rel(root, path)+ return err == nil && (rel == "." || filepath.IsLocal(rel))+}++// Local HTTP API used by `multica environment`. Identity comes from the+// task-scoped bearer token, exactly as for /repo/checkout.++type environmentStartRequest struct {+ Name string `json:"name"`+ Dir string `json:"dir"`+ Path string `json:"path"`+ Wait bool `json:"wait"`+}++type environmentStopRequest struct {+ Name string `json:"name"`+}++type environmentResponse struct {+ Environment *localenv.Environment `json:"environment,omitempty"`+ Environments []localenv.Environment `json:"environments,omitempty"`+}++func (d *Daemon) environmentTask(w http.ResponseWriter, r *http.Request) (localenv.Task, bool) {+ if r.Method != http.MethodPost {+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)+ return localenv.Task{}, false+ }+ if d.environments == nil {+ http.Error(w, "environments are not available on this daemon", http.StatusServiceUnavailable)+ return localenv.Task{}, false+ }+ active, result := d.activeRepoCheckoutTask(r)+ if result != repoCheckoutAuthOK {+ http.Error(w, "environment commands need the credential of a task running in this daemon; "++ "run them from inside the task, while it is running", http.StatusUnauthorized)+ return localenv.Task{}, false+ }+ return localenv.Task{TaskID: active.TaskID, IssueID: active.IssueID, WorkspaceID: active.WorkspaceID, RootDir: active.WorkDir}, true+}++func (d *Daemon) environmentStartHandler() http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ task, ok := d.environmentTask(w, r)+ if !ok {+ return+ }+ var req environmentStartRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)+ return+ }+ if req.Dir == "" {+ req.Dir = task.RootDir+ }+ env, err := d.environments.manager.Start(task, req.Dir, strings.TrimSpace(req.Name), req.Path)+ if err != nil {+ status := http.StatusBadRequest+ if errors.Is(err, localenv.ErrUnsupported) {+ status = http.StatusNotImplemented+ }+ http.Error(w, err.Error(), status)+ return+ }+ d.environments.nudge()+ if req.Wait {+ ctx, cancel := context.WithTimeout(r.Context(), environmentStartTimeout)+ env = d.environments.manager.WaitReady(ctx, env.Key)+ cancel()+ d.environments.nudge()+ }+ writeEnvironmentResponse(w, environmentResponse{Environment: &env})+ }+}++func (d *Daemon) environmentStopHandler() http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ task, ok := d.environmentTask(w, r)+ if !ok {+ return+ }+ var req environmentStopRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)+ return+ }+ env, err := d.environments.manager.Stop(task, strings.TrimSpace(req.Name))+ if errors.Is(err, localenv.ErrNotFound) {+ http.Error(w, fmt.Sprintf("no running environment named %q on this issue", req.Name), http.StatusNotFound)+ return+ }+ if err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }+ d.environments.nudge()+ writeEnvironmentResponse(w, environmentResponse{Environment: &env})+ }+}++func (d *Daemon) environmentListHandler() http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ task, ok := d.environmentTask(w, r)+ if !ok {+ return+ }+ envs := d.environments.manager.List(task)+ if envs == nil {+ envs = []localenv.Environment{}+ }+ writeEnvironmentResponse(w, environmentResponse{Environments: envs})+ }+}++func writeEnvironmentResponse(w http.ResponseWriter, resp environmentResponse) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(resp)+}diff --git a/server/internal/daemon/environments_test.go b/server/internal/daemon/environments_test.gonew file mode 100644index 0000000000..3ee2843fbc--- /dev/null+++ b/server/internal/daemon/environments_test.go@@ -0,0 +1,217 @@+package daemon++import (+ "context"+ "errors"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/internal/daemon/localenv"+)++type recordingEnvironmentReporter struct {+ mu sync.Mutex+ calls []environmentReportCall+ err error+}++type environmentReportCall struct {+ taskID string+ envs []TaskEnvironmentReport+}++func (r *recordingEnvironmentReporter) ReportTaskEnvironments(_ context.Context, taskID string, envs []TaskEnvironmentReport) error {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.calls = append(r.calls, environmentReportCall{taskID: taskID, envs: envs})+ return r.err+}++func (r *recordingEnvironmentReporter) take() []environmentReportCall {+ r.mu.Lock()+ defer r.mu.Unlock()+ calls := r.calls+ r.calls = nil+ return calls+}++func newTestEnvironmentService(t *testing.T) (*environmentService, *recordingEnvironmentReporter) {+ t.Helper()+ reporter := &recordingEnvironmentReporter{}+ s := newEnvironmentService(Config{WorkspacesRoot: t.TempDir()}, reporter, nil, slog.New(slog.NewTextHandler(io.Discard, nil)))+ return s, reporter+}++func detectedEnv(taskID, key string) localenv.Environment {+ return localenv.Environment{+ Key: key, TaskID: taskID, IssueID: "issue-" + taskID, Source: localenv.SourceDetected,+ Name: "node", URL: "http://localhost:5173", Port: 5173, State: localenv.StateRunning,+ StartedAt: time.Date(2026, 11, 10, 9, 0, 0, 0, time.UTC),+ }+}++func TestEnvironmentReportSendsChangesHeartbeatsAndAFinalEmptySnapshot(t *testing.T) {+ s, reporter := newTestEnvironmentService(t)+ ctx := context.Background()+ now := time.Now()++ s.report(ctx, now)+ if calls := reporter.take(); len(calls) != 0 {+ t.Fatalf("reported %d snapshots with nothing running", len(calls))+ }++ s.detected = []localenv.Environment{detectedEnv("task-a", "detected:aaa")}+ s.report(ctx, now)+ calls := reporter.take()+ if len(calls) != 1 || calls[0].taskID != "task-a" || len(calls[0].envs) != 1 || calls[0].envs[0].URL != "http://localhost:5173" {+ t.Fatalf("first snapshot = %+v", calls)+ }++ s.report(ctx, now.Add(20*time.Second))+ if calls := reporter.take(); len(calls) != 0 {+ t.Fatalf("an unchanged snapshot was re-sent before the heartbeat: %+v", calls)+ }+ s.report(ctx, now.Add(environmentHeartbeat+time.Second))+ if calls := reporter.take(); len(calls) != 1 {+ t.Fatalf("heartbeat sent %d snapshots, want 1", len(calls))+ }++ s.detected = nil+ s.report(ctx, now.Add(2*environmentHeartbeat))+ calls = reporter.take()+ if len(calls) != 1 || calls[0].taskID != "task-a" || len(calls[0].envs) != 0 {+ t.Fatalf("after the server stopped = %+v, want one empty snapshot", calls)+ }+ s.report(ctx, now.Add(3*environmentHeartbeat))+ if calls := reporter.take(); len(calls) != 0 {+ t.Fatalf("an empty snapshot was sent again: %+v", calls)+ }+}++func TestEnvironmentReportRetriesFailuresAndDropsRefusedTasks(t *testing.T) {+ s, reporter := newTestEnvironmentService(t)+ ctx := context.Background()+ now := time.Now()+ s.detected = []localenv.Environment{detectedEnv("task-a", "detected:aaa")}++ reporter.err = errors.New("connection refused")+ s.report(ctx, now)+ reporter.err = nil+ s.report(ctx, now.Add(time.Second))+ if calls := reporter.take(); len(calls) != 2 {+ t.Fatalf("a failed snapshot was not retried: %d calls", len(calls))+ }++ s.detected = []localenv.Environment{detectedEnv("task-b", "detected:bbb")}+ reporter.err = &requestError{StatusCode: http.StatusNotFound}+ s.report(ctx, now.Add(2*time.Second))+ reporter.take()+ if _, ok := s.reported["task-b"]; ok {+ t.Fatal("a task the server refused is still tracked")+ }+}++func TestEnvironmentReportKeepsADetectedServerOnItsFirstTask(t *testing.T) {+ s, reporter := newTestEnvironmentService(t)+ ctx := context.Background()+ now := time.Now()+ s.detected = []localenv.Environment{detectedEnv("task-a", "detected:aaa")}+ s.report(ctx, now)+ reporter.take()++ // A later task reuses the directory; the same server is still task-a's.+ s.detected = []localenv.Environment{detectedEnv("task-b", "detected:aaa")}+ s.report(ctx, now.Add(time.Second))+ if calls := reporter.take(); len(calls) != 0 {+ t.Fatalf("the server moved tasks: %+v", calls)+ }+}++func TestEnvironmentServiceClosesOutTasksReportedBeforeARestart(t *testing.T) {+ s, reporter := newTestEnvironmentService(t)+ s.detected = []localenv.Environment{detectedEnv("task-a", "detected:aaa")}+ s.report(context.Background(), time.Now())+ reporter.take()++ restarted := newEnvironmentService(Config{WorkspacesRoot: filepath.Dir(filepath.Dir(s.stateDir))}, reporter, nil, s.logger)+ restarted.loadReported()+ restarted.report(context.Background(), time.Now())+ calls := reporter.take()+ if len(calls) != 1 || calls[0].taskID != "task-a" || len(calls[0].envs) != 0 {+ t.Fatalf("after restart = %+v, want an empty snapshot closing task-a", calls)+ }+}++func TestEnvironmentResolveAttributesRunningAndFinishedTasks(t *testing.T) {+ s, _ := newTestEnvironmentService(t)+ running := filepath.Join(s.workspacesRoot, "ws-1", "task-running")+ finished := filepath.Join(s.workspacesRoot, "ws-1", "task-finished")+ for _, dir := range []string{filepath.Join(running, "workdir", "app"), filepath.Join(finished, "workdir")} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ }+ untrack := s.trackTask(running, localenv.Task{TaskID: "t-run", IssueID: "i-run", WorkspaceID: "ws-1"})+ if err := execenv.WriteGCMeta(finished, execenv.GCMeta{Kind: execenv.GCKindIssue, IssueID: "i-done", TaskID: "t-done", WorkspaceID: "ws-1"}, s.logger); err != nil {+ t.Fatal(err)+ }++ if task, ok := s.resolve(filepath.Join(running, "workdir", "app")); !ok || task.TaskID != "t-run" || task.RootDir != running {+ t.Fatalf("running task resolved to %+v, %v", task, ok)+ }+ if task, ok := s.resolve(filepath.Join(finished, "workdir")); !ok || task.TaskID != "t-done" || task.IssueID != "i-done" {+ t.Fatalf("finished task resolved to %+v, %v", task, ok)+ }+ for _, dir := range []string{"/Users/me/own-project", filepath.Join(s.workspacesRoot, ".repos", "x"), s.workspacesRoot} {+ if _, ok := s.resolve(dir); ok {+ t.Fatalf("%s was attributed to a task", dir)+ }+ }+ untrack()+ if _, ok := s.resolve(filepath.Join(running, "workdir")); ok {+ t.Fatal("an untracked task without metadata still resolves")+ }++ s.detected = []localenv.Environment{{Key: "detected:x", Dir: finished, State: localenv.StateRunning}}+ if !s.servesFrom(finished) || s.servesFrom(running) {+ t.Fatal("servesFrom does not follow the detected server's directory")+ }+}++func doEnvironmentRequest(handler http.HandlerFunc, path, token, body string) *httptest.ResponseRecorder {+ req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ rec := httptest.NewRecorder()+ handler(rec, req)+ return rec+}++func TestEnvironmentHandlersRequireATaskCredential(t *testing.T) {+ s, _ := newTestEnvironmentService(t)+ d := &Daemon{logger: s.logger, environments: s}+ for path, handler := range map[string]http.HandlerFunc{+ "/environments/start": d.environmentStartHandler(),+ "/environments/stop": d.environmentStopHandler(),+ "/environments/list": d.environmentListHandler(),+ } {+ rec := doEnvironmentRequest(handler, path, "", `{}`)+ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("%s without a credential = %d", path, rec.Code)+ }+ rec = doEnvironmentRequest(handler, path, "mat_unknown", `{}`)+ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("%s with an unknown credential = %d", path, rec.Code)+ }+ }+}diff --git a/server/internal/daemon/environments_unix_test.go b/server/internal/daemon/environments_unix_test.gonew file mode 100644index 0000000000..c3d77e823a--- /dev/null+++ b/server/internal/daemon/environments_unix_test.go@@ -0,0 +1,110 @@+//go:build !windows++package daemon++import (+ "context"+ "encoding/json"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/localenv"+)++func TestEnvironmentHandlersStartListAndStop(t *testing.T) {+ s, _ := newTestEnvironmentService(t)+ d := &Daemon{logger: s.logger, environments: s}+ workDir := t.TempDir()+ if err := os.MkdirAll(filepath.Join(workDir, "repo", ".multica"), 0o755); err != nil {+ t.Fatal(err)+ }+ config := "[environments.worker]\nlabel = \"Queue worker\"\nstart = \"exec sleep 60\"\nurl = \"\"\n"+ if err := os.WriteFile(filepath.Join(workDir, "repo", ".multica", "environments.toml"), []byte(config), 0o644); err != nil {+ t.Fatal(err)+ }+ d.registerActiveRepoCheckoutTask("mat_env_a", activeRepoCheckoutTask{WorkspaceID: "ws", TaskID: "task-a", IssueID: "issue-a", WorkDir: workDir})+ d.registerActiveRepoCheckoutTask("mat_env_b", activeRepoCheckoutTask{WorkspaceID: "ws", TaskID: "task-b", IssueID: "issue-b", WorkDir: workDir})++ rec := doEnvironmentRequest(d.environmentStartHandler(), "/environments/start", "mat_env_a",+ `{"name":"worker","dir":"`+filepath.Join(workDir, "repo")+`","wait":true}`)+ if rec.Code != http.StatusOK {+ t.Fatalf("start = %d %s", rec.Code, rec.Body.String())+ }+ var started environmentResponse+ json.NewDecoder(rec.Body).Decode(&started)+ if started.Environment == nil || started.Environment.State != localenv.StateRunning || started.Environment.Label != "Queue worker" {+ t.Fatalf("started = %+v", started.Environment)+ }+ t.Cleanup(func() {+ s.manager.Stop(localenv.Task{TaskID: "task-a", IssueID: "issue-a", WorkspaceID: "ws"}, "worker")+ })++ rec = doEnvironmentRequest(d.environmentListHandler(), "/environments/list", "mat_env_b", `{}`)+ var other environmentResponse+ json.NewDecoder(rec.Body).Decode(&other)+ if len(other.Environments) != 0 {+ t.Fatalf("another issue lists %+v", other.Environments)+ }+ rec = doEnvironmentRequest(d.environmentStopHandler(), "/environments/stop", "mat_env_b", `{"name":"worker"}`)+ if rec.Code != http.StatusNotFound {+ t.Fatalf("another issue stopping the environment = %d", rec.Code)+ }++ rec = doEnvironmentRequest(d.environmentStartHandler(), "/environments/start", "mat_env_a",+ `{"name":"web","dir":"`+filepath.Join(workDir, "repo")+`"}`)+ if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "declared: worker") {+ t.Fatalf("start of an undeclared environment = %d %s", rec.Code, rec.Body.String())+ }+ rec = doEnvironmentRequest(d.environmentStartHandler(), "/environments/start", "mat_env_a", `{"name":"worker"}`)+ if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "run from inside the repository") {+ t.Fatalf("start above the repository = %d %s", rec.Code, rec.Body.String())+ }++ rec = doEnvironmentRequest(d.environmentStopHandler(), "/environments/stop", "mat_env_a", `{"name":"worker"}`)+ var stopped environmentResponse+ json.NewDecoder(rec.Body).Decode(&stopped)+ if rec.Code != http.StatusOK || stopped.Environment == nil || stopped.Environment.State != localenv.StateStopped {+ t.Fatalf("stop = %d %+v", rec.Code, stopped.Environment)+ }+}++func TestEnvironmentReportKeepsACrashedEnvironmentsOutputLocal(t *testing.T) {+ const secret = "fake-password-for-tests"+ s, reporter := newTestEnvironmentService(t)+ root := t.TempDir()+ if err := os.MkdirAll(filepath.Join(root, ".multica"), 0o755); err != nil {+ t.Fatal(err)+ }+ config := "[environments.api]\nstart = \"echo 'cannot reach postgres://demo:" + secret + "@db.invalid/app'; exit 3\"\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, "api", os.Getenv("PATH"))+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ deadline := time.Now().Add(10 * time.Second)+ for env.State != localenv.StateExited && time.Now().Before(deadline) {+ env = s.manager.WaitReady(ctx, env.Key)+ time.Sleep(20 * time.Millisecond)+ }++ s.report(context.Background(), time.Now())+ calls := reporter.take()+ if len(calls) != 1 || len(calls[0].envs) != 1 {+ t.Fatalf("reports = %+v, want one snapshot with the crashed environment", calls)+ }+ if got := calls[0].envs[0]; got.State != localenv.StateExited || got.Detail != "exit status 3" {+ t.Fatalf("reported %+v, want exited with only its exit status", got)+ }+ if log, _ := os.ReadFile(env.LogPath); !strings.Contains(string(log), secret) {+ t.Fatalf("local log = %q, want the command's output kept there", log)+ }+}diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 2170fcac33..5929040fd8 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -69,7 +69,7 @@ func writeBackgroundTaskSafetySlim(b *strings.Builder) {b.WriteString("## Background Task Safety\n\n")b.WriteString("Multica marks the task terminal the moment your top-level turn exits — any run-owned work still active is orphaned, its result lost, and the final comment you meant to post never sends. There is no background-completion wakeup, whatever a tool response promises; an issue wakeup (`multica issue wakeup create`) is different — the platform stores it and starts a new run later. Never background-and-yield: collect required results inside foreground tool calls that block to completion, run unobservable work synchronously, and never end a turn \"standing by\" for something to finish — that message becomes your final output.\n\n")b.WriteString("External systems triggered by your completed actions — CI, GitHub Actions after a successful push — are not run-owned: do not wait for them, and do not run `gh pr checks --watch`, `gh run watch`, or sleep/retry polls. A repo's merge gate (\"CI must be green before merge\") is NOT your delivery acceptance criteria. Deliver what you have — \"Local tests pass; CI running: <PR link>\" is a complete hand-off. The one exception: when the trigger comment or the issue's acceptance criteria explicitly ask for the CI result, collect it as ONE foreground blocking call (`gh pr checks <pr> --watch`) inside this same turn.\n\n")- b.WriteString("A user explicitly asking for a local service to stay available after the turn is a persistent service handoff, not background-and-yield — allowed only when the running service itself is the requested deliverable. Detach its lifecycle from this run first (durable logs, a recorded cleanup handle such as PID/profile), verify readiness, and reply with the URL, logs, and stop instructions. Without a supervisor, describe survival as best-effort, not guaranteed.\n\n")+ b.WriteString("A user explicitly asking for a local service to stay available after the turn is a persistent service handoff, not background-and-yield — allowed only when the running service itself is the requested deliverable. Detach its lifecycle from this run first (durable logs, a recorded cleanup handle such as PID/profile), verify readiness, and reply with the URL, logs, and stop instructions. Without a supervisor, describe survival as best-effort, not guaranteed. When the repository declares the service in `.multica/environments.toml`, start it with `multica env start <name>` instead: the daemon supervises it, keeps its log, stops it at its TTL, and shows it in the issue sidebar.\n\n")b.WriteString("Never terminate `multica` or `multica.exe` by executable name: a long-lived matching process may be the workspace daemon. Cancel only the exact child PID you started, and before terminating it compare that PID with `multica daemon status --output json`; never kill it if it is the reported daemon PID.\n\n")}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex c7f0a80a65..0b0e8d1045 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -212,7 +212,7 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)continue}taskDir := filepath.Join(wsDir, entry.Name())- if d.isActiveEnvRoot(taskDir) {+ if d.isActiveEnvRoot(taskDir) || d.environments.servesFrom(taskDir) {stats.skipped++continue}@@ -422,8 +422,8 @@ func (d *Daemon) taskDirGCDecision(ctx context.Context, taskDir string) (gcActio// still-running task can reuse the prior workdir of an already-done issue// whose updated_at is older than the TTL (a task re-claim doesn't advance// updated_at), so the regular TTL check alone wouldn't notice the resumed- // activity.- if d.isActiveEnvRoot(taskDir) {+ // activity. A directory a running environment serves from is in use too.+ if d.isActiveEnvRoot(taskDir) || d.environments.servesFrom(taskDir) {return gcActionSkip, nil}diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 5ef71ab191..2cb7d7df86 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -126,6 +126,7 @@ type repoCheckoutRequest struct {type activeRepoCheckoutTask struct {WorkspaceID stringTaskID string+ IssueID stringAgentID stringAgentName stringWorkDir string@@ -413,6 +414,9 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt timmux.HandleFunc("/health", d.healthHandler(startedAt))mux.HandleFunc("/shutdown", d.shutdownHandler())mux.HandleFunc("/repo/checkout", d.repoCheckoutHandler())+ mux.HandleFunc("/environments/start", d.environmentStartHandler())+ mux.HandleFunc("/environments/stop", d.environmentStopHandler())+ mux.HandleFunc("/environments/list", d.environmentListHandler())srv := &http.Server{Handler: mux}diff --git a/server/internal/daemon/localenv/config.go b/server/internal/daemon/localenv/config.gonew file mode 100644index 0000000000..c4d544eb0d--- /dev/null+++ b/server/internal/daemon/localenv/config.go@@ -0,0 +1,183 @@+// Package localenv runs and finds the local environments (dev servers) an+// agent starts for a task, so the daemon can report them on the issue.+//+// An environment is either declared by the repository in+// .multica/environments.toml and supervised by the daemon ("config"), or a+// listening process the daemon finds running inside a task's directory+// ("detected").+package localenv++import (+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "regexp"+ "sort"+ "strings"+ "time"++ "github.com/pelletier/go-toml/v2"+)++// ConfigPath is where a repository declares its environments, relative to+// the repository root.+const ConfigPath = ".multica/environments.toml"++const (+ DefaultTTL = 24 * time.Hour+ MaxTTL = 7 * 24 * time.Hour+ minTTL = time.Minute+)++var nameRE = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,39}$`)++// Definition is one [environments.<name>] table.+type Definition struct {+ Name string+ Label string+ // Start is run by `sh -c` from the repository root.+ Start string+ // URL is where a reader opens the environment. Empty means it has none+ // (a worker, say).+ URL string+ // Ready is polled until it answers; it defaults to URL.+ Ready string+ // Stop, when set, is run instead of signalling the start command's process+ // group. The group is still signalled afterwards if anything is left.+ Stop string+ TTL time.Duration+}++type configFile struct {+ Environments map[string]struct {+ Label string `toml:"label"`+ Start string `toml:"start"`+ URL *string `toml:"url"`+ Ready string `toml:"ready"`+ Stop string `toml:"stop"`+ TTL string `toml:"ttl"`+ } `toml:"environments"`+}++// Config is a repository's parsed environments file.+type Config struct {+ // RepoRoot is the directory holding .multica/; commands run from here.+ RepoRoot string+ Environments map[string]Definition+}++// Names lists the declared environments in a stable order.+func (c Config) Names() []string {+ names := make([]string, 0, len(c.Environments))+ for name := range c.Environments {+ names = append(names, name)+ }+ sort.Strings(names)+ return names+}++// ErrNoConfig means no environments file was found between the start+// directory and the boundary.+var ErrNoConfig = errors.New("no " + ConfigPath + " found")++// FindConfig walks up from dir, stopping at boundary, and loads the first+// environments file it meets. dir must be inside boundary.+func FindConfig(dir, boundary string) (Config, error) {+ dir = filepath.Clean(dir)+ boundary = filepath.Clean(boundary)+ if !within(dir, boundary) {+ return Config{}, fmt.Errorf("%s is outside the task directory", dir)+ }+ start := dir+ notFound := fmt.Errorf("%w in %s or its parent directories; run from inside the repository", ErrNoConfig, start)+ for {+ path := filepath.Join(dir, filepath.FromSlash(ConfigPath))+ data, err := os.ReadFile(path)+ if err == nil {+ cfg, err := ParseConfig(data)+ if err != nil {+ return Config{}, fmt.Errorf("%s: %w", path, err)+ }+ cfg.RepoRoot = dir+ return cfg, nil+ }+ if !errors.Is(err, os.ErrNotExist) {+ return Config{}, err+ }+ if dir == boundary {+ return Config{}, notFound+ }+ parent := filepath.Dir(dir)+ if parent == dir {+ return Config{}, notFound+ }+ dir = parent+ }+}++// ParseConfig parses and validates an environments file.+func ParseConfig(data []byte) (Config, error) {+ var file configFile+ if err := toml.Unmarshal(data, &file); err != nil {+ return Config{}, err+ }+ cfg := Config{Environments: make(map[string]Definition, len(file.Environments))}+ for name, raw := range file.Environments {+ if !nameRE.MatchString(name) {+ return Config{}, fmt.Errorf("environment name %q must be lowercase letters, digits, - or _ (at most 40)", name)+ }+ def := Definition{+ Name: name,+ Label: strings.TrimSpace(raw.Label),+ Start: strings.TrimSpace(raw.Start),+ URL: "http://localhost:$MULTICA_PORT",+ Ready: strings.TrimSpace(raw.Ready),+ Stop: strings.TrimSpace(raw.Stop),+ TTL: DefaultTTL,+ }+ if def.Start == "" {+ return Config{}, fmt.Errorf("environment %q has no start command", name)+ }+ if raw.URL != nil {+ def.URL = strings.TrimSpace(*raw.URL)+ }+ if def.Ready == "" {+ def.Ready = def.URL+ }+ if ttl := strings.TrimSpace(raw.TTL); ttl != "" {+ d, err := time.ParseDuration(ttl)+ if err != nil {+ return Config{}, fmt.Errorf("environment %q ttl: %w", name, err)+ }+ if d < minTTL || d > MaxTTL {+ return Config{}, fmt.Errorf("environment %q ttl must be between %s and %s", name, minTTL, MaxTTL)+ }+ def.TTL = d+ }+ cfg.Environments[name] = def+ }+ if len(cfg.Environments) == 0 {+ return Config{}, errors.New("declares no environments")+ }+ return cfg, nil+}++// expandPort substitutes $MULTICA_PORT / ${MULTICA_PORT} in a URL. Commands+// are not expanded here: the shell sees MULTICA_PORT in their environment.+func expandPort(s string, port int) string {+ return os.Expand(s, func(key string) string {+ if key == "MULTICA_PORT" {+ return fmt.Sprint(port)+ }+ return "$" + key+ })+}++func within(path, root string) bool {+ rel, err := filepath.Rel(root, path)+ if err != nil {+ return false+ }+ return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))+}diff --git a/server/internal/daemon/localenv/config_test.go b/server/internal/daemon/localenv/config_test.gonew file mode 100644index 0000000000..088bbe08be--- /dev/null+++ b/server/internal/daemon/localenv/config_test.go@@ -0,0 +1,99 @@+package localenv++import (+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestParseConfigDefaults(t *testing.T) {+ cfg, err := ParseConfig([]byte(`+[environments.web]+label = "Web app"+start = "pnpm dev --port $MULTICA_PORT"++[environments.worker]+start = "pnpm worker"+url = ""+ttl = "2h"+`))+ if err != nil {+ t.Fatalf("ParseConfig: %v", err)+ }+ web := cfg.Environments["web"]+ if web.URL != "http://localhost:$MULTICA_PORT" || web.Ready != web.URL || web.TTL != DefaultTTL || web.Label != "Web app" {+ t.Fatalf("web = %+v", web)+ }+ worker := cfg.Environments["worker"]+ if worker.URL != "" || worker.Ready != "" || worker.TTL != 2*time.Hour {+ t.Fatalf("worker = %+v, want no URL and a 2h TTL", worker)+ }+ if got := strings.Join(cfg.Names(), ","); got != "web,worker" {+ t.Fatalf("Names = %s", got)+ }+ if got := expandPort(web.URL, 41000); got != "http://localhost:41000" {+ t.Fatalf("expandPort = %s", got)+ }+}++func TestParseConfigRejects(t *testing.T) {+ cases := map[string]string{+ "no environments": ``,+ "bad name": "[environments.Web]\nstart = \"x\"",+ "no start": "[environments.web]\nlabel = \"x\"",+ "ttl too long": "[environments.web]\nstart = \"x\"\nttl = \"720h\"",+ "ttl unparsable": "[environments.web]\nstart = \"x\"\nttl = \"soon\"",+ }+ for name, body := range cases {+ t.Run(name, func(t *testing.T) {+ if _, err := ParseConfig([]byte(body)); err == nil {+ t.Fatal("ParseConfig accepted an invalid file")+ }+ })+ }+}++func writeConfig(t *testing.T, repo, body string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Join(repo, ".multica"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(repo, filepath.FromSlash(ConfigPath)), []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+}++func TestFindConfigWalksUpToTheBoundary(t *testing.T) {+ root := t.TempDir()+ repo := filepath.Join(root, "workdir", "app")+ sub := filepath.Join(repo, "packages", "web")+ if err := os.MkdirAll(sub, 0o755); err != nil {+ t.Fatal(err)+ }+ writeConfig(t, repo, "[environments.web]\nstart = \"x\"")++ cfg, err := FindConfig(sub, root)+ if err != nil {+ t.Fatalf("FindConfig: %v", err)+ }+ if cfg.RepoRoot != repo {+ t.Fatalf("RepoRoot = %s, want %s", cfg.RepoRoot, repo)+ }++ // A config above the task directory belongs to someone else.+ outside := t.TempDir()+ task := filepath.Join(outside, "task")+ if err := os.MkdirAll(task, 0o755); err != nil {+ t.Fatal(err)+ }+ writeConfig(t, outside, "[environments.web]\nstart = \"x\"")+ if _, err := FindConfig(task, task); !errors.Is(err, ErrNoConfig) {+ t.Fatalf("FindConfig past the boundary = %v, want ErrNoConfig", err)+ }+ if _, err := FindConfig(outside, task); err == nil {+ t.Fatal("FindConfig accepted a directory outside the task")+ }+}diff --git a/server/internal/daemon/localenv/detect.go b/server/internal/daemon/localenv/detect.gonew file mode 100644index 0000000000..1de3ed82dc--- /dev/null+++ b/server/internal/daemon/localenv/detect.go@@ -0,0 +1,208 @@+package localenv++import (+ "bufio"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "fmt"+ "strconv"+ "strings"+ "sync"+ "time"+)++// Listener is a process listening on a TCP port.+type Listener struct {+ PID int+ Port int+ Command string+ Cwd string+}++// Detector finds servers running inside task directories that nobody+// declared, so a repository with no environments file still shows what its+// agent started.+type Detector struct {+ // ignore holds command names that are never an environment: the agent+ // CLIs themselves and the multica binary.+ ignore map[string]bool+ list func(ctx context.Context) ([]Listener, error)+ now func() time.Time++ mu sync.Mutex+ seen map[string]*sighting+}++type sighting struct {+ first time.Time+ scans int+}++func NewDetector(ignoreCommands []string) *Detector {+ ignore := map[string]bool{"multica": true}+ for _, c := range ignoreCommands {+ if c = strings.ToLower(strings.TrimSpace(c)); c != "" {+ ignore[c] = true+ }+ }+ return &Detector{ignore: ignore, list: listListeners, now: time.Now, seen: make(map[string]*sighting)}+}++// 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.+func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, bool), owned func(pgid int) bool) ([]Environment, error) {+ listeners, err := d.list(ctx)+ if err != nil {+ return nil, err+ }+ now := d.now()+ found := make(map[string]Environment)+ for _, l := range listeners {+ if l.Cwd == "" || d.ignore[strings.ToLower(l.Command)] {+ continue+ }+ task, ok := resolve(l.Cwd)+ if !ok {+ continue+ }+ if pgid := processGroup(l.PID); pgid > 0 && owned(pgid) {+ continue+ }+ key := detectedKey(task.RootDir, l.Port)+ if _, dup := found[key]; dup {+ continue+ }+ name := l.Command+ if r := []rune(name); len(r) > 64 {+ name = string(r[:64])+ }+ found[key] = Environment{+ Key: key, TaskID: task.TaskID, IssueID: task.IssueID, Source: SourceDetected,+ Name: name, URL: fmt.Sprintf("http://localhost:%d", l.Port), Port: l.Port, State: StateRunning,+ Dir: task.RootDir,+ }+ }++ d.mu.Lock()+ defer d.mu.Unlock()+ out := make([]Environment, 0, len(found))+ for key, env := range found {+ s := d.seen[key]+ if s == nil {+ s = &sighting{first: now}+ d.seen[key] = s+ }+ s.scans+++ if s.scans >= 2 {+ env.StartedAt = s.first+ out = append(out, env)+ }+ }+ for key := range d.seen {+ if _, ok := found[key]; !ok {+ delete(d.seen, key)+ }+ }+ sortEnvironments(out)+ return out, nil+}++// detectedKey is stable across restarts of the same server, and carries no+// local path to the server.+func detectedKey(root string, port int) string {+ sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%d", root, port)))+ return "detected:" + hex.EncodeToString(sum[:8])+}++// parseLsofListeners reads `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` output.+func parseLsofListeners(out string) []Listener {+ var listeners []Listener+ pid, command := 0, ""+ seen := make(map[[2]int]bool)+ scanner := bufio.NewScanner(strings.NewReader(out))+ for scanner.Scan() {+ line := scanner.Text()+ if line == "" {+ continue+ }+ switch line[0] {+ case 'p':+ pid, _ = strconv.Atoi(line[1:])+ command = ""+ case 'c':+ command = line[1:]+ case 'n':+ port := portFromAddress(line[1:])+ if pid > 0 && port > 0 && !seen[[2]int{pid, port}] {+ seen[[2]int{pid, port}] = true+ listeners = append(listeners, Listener{PID: pid, Port: port, Command: command})+ }+ }+ }+ return listeners+}++// parseLsofCwd reads `lsof -a -d cwd -Fpn -p ...` output into pid → cwd.+func parseLsofCwd(out string) map[int]string {+ cwds := make(map[int]string)+ pid := 0+ scanner := bufio.NewScanner(strings.NewReader(out))+ for scanner.Scan() {+ line := scanner.Text()+ if line == "" {+ continue+ }+ switch line[0] {+ case 'p':+ pid, _ = strconv.Atoi(line[1:])+ case 'n':+ if pid > 0 {+ cwds[pid] = line[1:]+ }+ }+ }+ return cwds+}++func portFromAddress(addr string) int {+ addr = strings.TrimSpace(addr)+ if i := strings.Index(addr, "->"); i >= 0 {+ addr = addr[:i]+ }+ i := strings.LastIndex(addr, ":")+ if i < 0 {+ return 0+ }+ port, err := strconv.Atoi(addr[i+1:])+ if err != nil || port <= 0 || port > 65535 {+ return 0+ }+ return port+}++// parseProcNetTCP reads /proc/net/tcp{,6} into socket inode → listening port.+func parseProcNetTCP(out string, into map[string]int) {+ scanner := bufio.NewScanner(strings.NewReader(out))+ for scanner.Scan() {+ fields := strings.Fields(scanner.Text())+ // sl local_address rem_address st tx:rx tr:when retrnsmt uid timeout inode+ if len(fields) < 10 || fields[3] != "0A" {+ continue+ }+ local := fields[1]+ i := strings.LastIndex(local, ":")+ if i < 0 {+ continue+ }+ port, err := strconv.ParseInt(local[i+1:], 16, 32)+ if err != nil || port <= 0 {+ continue+ }+ if fields[9] != "0" {+ into[fields[9]] = int(port)+ }+ }+}diff --git a/server/internal/daemon/localenv/detect_darwin.go b/server/internal/daemon/localenv/detect_darwin.gonew file mode 100644index 0000000000..b7a50d48df--- /dev/null+++ b/server/internal/daemon/localenv/detect_darwin.go@@ -0,0 +1,54 @@+//go:build darwin++package localenv++import (+ "context"+ "errors"+ "os/exec"+ "strconv"+ "strings"+ "time"+)++func listListeners(ctx context.Context) ([]Listener, error) {+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ // +c 0 keeps full command names; lsof truncates them to nine characters+ // otherwise.+ out, err := lsof(ctx, "-nP", "+c", "0", "-iTCP", "-sTCP:LISTEN", "-Fpcn")+ if err != nil {+ return nil, err+ }+ listeners := parseLsofListeners(out)+ if len(listeners) == 0 {+ return nil, nil+ }+ pids := make([]string, 0, len(listeners))+ seen := make(map[int]bool)+ for _, l := range listeners {+ if !seen[l.PID] {+ seen[l.PID] = true+ pids = append(pids, strconv.Itoa(l.PID))+ }+ }+ out, err = lsof(ctx, "-a", "-d", "cwd", "-Fpn", "-p", strings.Join(pids, ","))+ if err != nil {+ return nil, err+ }+ cwds := parseLsofCwd(out)+ for i := range listeners {+ listeners[i].Cwd = cwds[listeners[i].PID]+ }+ return listeners, nil+}++// lsof exits 1 when it matches nothing, which is not an error here.+func lsof(ctx context.Context, args ...string) (string, error) {+ out, err := exec.CommandContext(ctx, "lsof", args...).Output()+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {+ return string(out), nil+ }+ return string(out), err+}diff --git a/server/internal/daemon/localenv/detect_linux.go b/server/internal/daemon/localenv/detect_linux.gonew file mode 100644index 0000000000..7775ec2844--- /dev/null+++ b/server/internal/daemon/localenv/detect_linux.go@@ -0,0 +1,61 @@+//go:build linux++package localenv++import (+ "context"+ "os"+ "path/filepath"+ "strconv"+ "strings"+)++func listListeners(ctx context.Context) ([]Listener, error) {+ inodes := make(map[string]int)+ for _, f := range []string{"/proc/net/tcp", "/proc/net/tcp6"} {+ if data, err := os.ReadFile(f); err == nil {+ parseProcNetTCP(string(data), inodes)+ }+ }+ if len(inodes) == 0 {+ return nil, nil+ }+ procs, err := os.ReadDir("/proc")+ if err != nil {+ return nil, err+ }+ var listeners []Listener+ for _, p := range procs {+ if ctx.Err() != nil {+ return nil, ctx.Err()+ }+ pid, err := strconv.Atoi(p.Name())+ if err != nil {+ continue+ }+ base := filepath.Join("/proc", p.Name())+ fds, err := os.ReadDir(filepath.Join(base, "fd"))+ if err != nil {+ continue+ }+ ports := make(map[int]bool)+ for _, fd := range fds {+ link, err := os.Readlink(filepath.Join(base, "fd", fd.Name()))+ if err != nil || !strings.HasPrefix(link, "socket:[") {+ continue+ }+ if port, ok := inodes[strings.TrimSuffix(strings.TrimPrefix(link, "socket:["), "]")]; ok {+ ports[port] = true+ }+ }+ if len(ports) == 0 {+ continue+ }+ cwd, _ := os.Readlink(filepath.Join(base, "cwd"))+ comm, _ := os.ReadFile(filepath.Join(base, "comm"))+ for port := range ports {+ listeners = append(listeners, Listener{PID: pid, Port: port, Command: strings.TrimSpace(string(comm)), Cwd: cwd})+ }+ }+ return listeners, nil+}diff --git a/server/internal/daemon/localenv/detect_other.go b/server/internal/daemon/localenv/detect_other.gonew file mode 100644index 0000000000..b241d92c0d--- /dev/null+++ b/server/internal/daemon/localenv/detect_other.go@@ -0,0 +1,7 @@+//go:build !darwin && !linux++package localenv++import "context"++func listListeners(context.Context) ([]Listener, error) { return nil, nil }diff --git a/server/internal/daemon/localenv/detect_system_test.go b/server/internal/daemon/localenv/detect_system_test.gonew file mode 100644index 0000000000..9816feb78b--- /dev/null+++ b/server/internal/daemon/localenv/detect_system_test.go@@ -0,0 +1,53 @@+//go:build darwin || linux++package localenv++import (+ "context"+ "fmt"+ "net"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"+)++func TestListListenersFindsAServerAndItsDirectory(t *testing.T) {+ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ port := ln.Addr().(*net.TCPAddr).Port+ ln.Close()++ dir, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcess$")+ cmd.Dir = dir+ cmd.Env = append(os.Environ(), "LOCALENV_HELPER=serve", fmt.Sprintf("MULTICA_PORT=%d", port))+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })++ deadline := time.Now().Add(15 * time.Second)+ for time.Now().Before(deadline) {+ listeners, err := listListeners(context.Background())+ if err != nil {+ t.Fatalf("listListeners: %v", err)+ }+ for _, l := range listeners {+ if l.PID == cmd.Process.Pid && l.Port == port {+ if l.Cwd != dir || l.Command == "" {+ t.Fatalf("listener = %+v, want cwd %s and a command name", l, dir)+ }+ return+ }+ }+ time.Sleep(200 * time.Millisecond)+ }+ t.Fatalf("server pid %d on port %d was never listed", cmd.Process.Pid, port)+}diff --git a/server/internal/daemon/localenv/detect_test.go b/server/internal/daemon/localenv/detect_test.gonew file mode 100644index 0000000000..a57827659b--- /dev/null+++ b/server/internal/daemon/localenv/detect_test.go@@ -0,0 +1,73 @@+package localenv++import (+ "context"+ "strings"+ "testing"+)++func TestParseLsofListeners(t *testing.T) {+ out := "p4210\ncnode\nf23\nn*:5173\nf24\nn[::1]:5173\np4300\ncpostgres\nf5\nn127.0.0.1:5432\np99\ncweird\nf1\nnlocalhost:http\n"+ got := parseLsofListeners(out)+ if len(got) != 2 {+ t.Fatalf("listeners = %+v, want node:5173 once and postgres:5432", got)+ }+ if got[0] != (Listener{PID: 4210, Port: 5173, Command: "node"}) || got[1] != (Listener{PID: 4300, Port: 5432, Command: "postgres"}) {+ t.Fatalf("listeners = %+v", got)+ }+ cwds := parseLsofCwd("p4210\nfcwd\nn/Users/me/multica_workspaces/ws/abc/workdir/app\np4300\nfcwd\nn/\n")+ if cwds[4210] != "/Users/me/multica_workspaces/ws/abc/workdir/app" || cwds[4300] != "/" {+ t.Fatalf("cwds = %v", cwds)+ }+}++func TestParseProcNetTCP(t *testing.T) {+ out := ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode+ 0: 00000000:1435 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 31337 1 0000000000000000 100 0 0 10 0+ 1: 0100007F:A028 0100007F:1435 01 00000000:00000000 00:00000000 00000000 1000 0 31338 1 0000000000000000 20 4 30 10 -1+`+ inodes := map[string]int{}+ parseProcNetTCP(out, inodes)+ if len(inodes) != 1 || inodes["31337"] != 5173 {+ t.Fatalf("inodes = %v, want only the listening socket on 5173", inodes)+ }+}++func TestDetectorReportsServersInTaskDirectories(t *testing.T) {+ listeners := []Listener{+ {PID: 1, Port: 5173, Command: "node", Cwd: "/ws/task-a/workdir/app"},+ {PID: 1, Port: 5173, Command: "node", Cwd: "/ws/task-a/workdir/app"},+ {PID: 2, Port: 9000, Command: "claude", Cwd: "/ws/task-a/workdir"},+ {PID: 3, Port: 3000, Command: "node", Cwd: "/Users/me/own-project"},+ }+ d := NewDetector([]string{"Claude"})+ d.list = func(context.Context) ([]Listener, error) { return listeners, nil }+ resolve := func(cwd string) (Task, bool) {+ if strings.HasPrefix(cwd, "/ws/task-a/") {+ return Task{TaskID: "task-a", IssueID: "issue-a", RootDir: "/ws/task-a"}, true+ }+ return Task{}, false+ }+ owned := func(int) bool { return false }++ first, err := d.Detect(context.Background(), resolve, owned)+ if err != nil || len(first) != 0 {+ t.Fatalf("first scan = %+v, %v; want nothing until a server is seen twice", first, err)+ }+ second, _ := d.Detect(context.Background(), resolve, owned)+ if len(second) != 1 {+ t.Fatalf("second scan = %+v, want the one server in the task directory", second)+ }+ env := second[0]+ if env.Source != SourceDetected || env.TaskID != "task-a" || env.URL != "http://localhost:5173" || env.Name != "node" || env.State != StateRunning {+ t.Fatalf("detected = %+v", env)+ }+ if strings.Contains(env.Key, "/ws/") || env.Key != detectedKey("/ws/task-a", 5173) {+ t.Fatalf("key %q leaks the path or is unstable", env.Key)+ }++ listeners = nil+ if gone, _ := d.Detect(context.Background(), resolve, owned); len(gone) != 0 {+ t.Fatalf("after the server stopped = %+v", gone)+ }+}diff --git a/server/internal/daemon/localenv/manager.go b/server/internal/daemon/localenv/manager.gonew file mode 100644index 0000000000..5e216fd38e--- /dev/null+++ b/server/internal/daemon/localenv/manager.go@@ -0,0 +1,674 @@+package localenv++import (+ "context"+ "crypto/rand"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "syscall"+ "time"+)++const (+ StateStarting = "starting"+ StateRunning = "running"+ StateExited = "exited"+ StateStopped = "stopped"++ SourceConfig = "config"+ SourceDetected = "detected"++ // Each environment gets ten consecutive ports, MULTICA_PORT through+ // MULTICA_PORT+9, so a web app and its API can run side by side and+ // parallel tasks never collide.+ portBlock = 10+ portLow = 41000+ portHigh = 48990+ stateFile = "state.json"+ outputFile = "output.log"++ // An ended environment stays in the snapshot long enough to be reported+ // as ended, then only its log is kept.+ endedRetention = time.Hour+ logRetention = 7 * 24 * time.Hour+ readyTimeout = 10 * time.Minute+ stopGrace = 10 * time.Second+ stopCmdTimeout = time.Minute+)++// ErrUnsupported is returned on platforms without process groups.+var ErrUnsupported = errors.New("local environments are not supported on this platform yet")++// ErrNotFound means no live environment of that name belongs to the task.+var ErrNotFound = errors.New("no running environment with that name")++// Task identifies who asks for an environment. RootDir is the task's own+// directory; an environment can only be started from inside it.+type Task struct {+ TaskID string+ IssueID string+ WorkspaceID string+ RootDir string+}++// Environment is one environment as the daemon reports and the CLI prints it.+type Environment struct {+ Key string `json:"key"`+ TaskID string `json:"task_id"`+ IssueID string `json:"issue_id"`+ Source string `json:"source"`+ Name string `json:"name"`+ Label string `json:"label"`+ URL string `json:"url"`+ Port int `json:"port"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt time.Time `json:"started_at"`+ ExpiresAt *time.Time `json:"expires_at,omitempty"`+ LogPath string `json:"log_path,omitempty"`+ // Dir is the directory the environment runs from, kept local so GC can+ // leave it in place; it is never reported.+ Dir string `json:"-"`+ pgid int+}++// record is what survives a daemon restart, in <dir>/<id>/state.json.+type record struct {+ ID string `json:"id"`+ TaskID string `json:"task_id"`+ IssueID string `json:"issue_id"`+ WorkspaceID string `json:"workspace_id"`+ Name string `json:"name"`+ Label string `json:"label"`+ RepoRoot string `json:"repo_root"`+ URL string `json:"url"`+ Ready string `json:"ready"`+ Stop string `json:"stop"`+ Port int `json:"port"`+ PID int `json:"pid"`+ Path string `json:"path"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt time.Time `json:"started_at"`+ ExpiresAt time.Time `json:"expires_at"`+ EndedAt *time.Time `json:"ended_at,omitempty"`+}++type entry struct {+ rec record+ stopping bool+ // leaderDone is closed once the start command's own process has exited.+ // It is nil for an environment adopted after a daemon restart, whose+ // liveness is checked on its process group instead.+ leaderDone chan struct{}+}++func (e *entry) live() bool { return e.rec.EndedAt == nil }++// Manager owns the environments this daemon started.+type Manager struct {+ dir string+ logger *slog.Logger+ now func() time.Time+ client *http.Client++ mu sync.Mutex+ envs map[string]*entry+ lastLogSwep time.Time+}++func NewManager(dir string, logger *slog.Logger) *Manager {+ return &Manager{+ dir: dir,+ logger: logger,+ now: time.Now,+ client: &http.Client{Timeout: 2 * time.Second},+ envs: make(map[string]*entry),+ }+}++// Load adopts the environments a previous daemon process left running. They+// keep running across a daemon restart; the ones whose process group is gone+// are recorded as exited.+func (m *Manager) Load() error {+ dirs, err := os.ReadDir(m.dir)+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ if err != nil {+ return err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ for _, d := range dirs {+ if !d.IsDir() {+ continue+ }+ data, err := os.ReadFile(filepath.Join(m.dir, d.Name(), stateFile))+ if err != nil {+ continue+ }+ var rec record+ if err := json.Unmarshal(data, &rec); err != nil || rec.ID != d.Name() {+ continue+ }+ e := &entry{rec: rec}+ if e.live() && !groupAlive(rec.PID) {+ m.endLocked(e, StateExited, "stopped while the daemon was not running")+ }+ m.envs[rec.ID] = e+ if e.live() && rec.State == StateStarting {+ go m.probe(e)+ }+ }+ return nil+}++// Start starts the named environment from the repository config found at or+// above dir. Starting one that is already running returns it unchanged.+func (m *Manager) Start(task Task, dir, name, pathEnv string) (Environment, error) {+ if !supported {+ return Environment{}, ErrUnsupported+ }+ root, err := filepath.EvalSymlinks(task.RootDir)+ if err != nil {+ return Environment{}, fmt.Errorf("resolve task directory: %w", err)+ }+ dir, err = filepath.EvalSymlinks(dir)+ if err != nil {+ return Environment{}, fmt.Errorf("resolve directory: %w", err)+ }+ cfg, err := FindConfig(dir, root)+ if err != nil {+ return Environment{}, err+ }+ def, ok := cfg.Environments[name]+ if !ok {+ return Environment{}, fmt.Errorf("%s declares no %q environment (declared: %s)",+ ConfigPath, name, strings.Join(cfg.Names(), ", "))+ }++ m.mu.Lock()+ defer m.mu.Unlock()+ for _, e := range m.envs {+ if e.live() && !e.stopping && sameOwner(e.rec, task) && e.rec.Name == name && e.rec.RepoRoot == cfg.RepoRoot {+ return m.viewLocked(e), nil+ }+ }+ port, err := m.allocatePortLocked()+ if err != nil {+ return Environment{}, err+ }+ id, err := randomID()+ if err != nil {+ return Environment{}, err+ }+ envDir := filepath.Join(m.dir, id)+ if err := os.MkdirAll(envDir, 0o700); err != nil {+ return Environment{}, fmt.Errorf("create environment directory: %w", err)+ }+ logFile, err := os.OpenFile(filepath.Join(envDir, outputFile), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)+ if err != nil {+ return Environment{}, fmt.Errorf("open environment log: %w", err)+ }+ now := m.now()+ rec := record{+ ID: id, TaskID: task.TaskID, IssueID: task.IssueID, WorkspaceID: task.WorkspaceID,+ Name: name, Label: def.Label, RepoRoot: cfg.RepoRoot,+ URL: expandPort(def.URL, port), Ready: expandPort(def.Ready, port), Stop: def.Stop,+ Port: port, Path: pathEnv, State: StateStarting,+ StartedAt: now, ExpiresAt: now.Add(def.TTL),+ }+ cmd := shellCommand(def.Start)+ cmd.Dir = cfg.RepoRoot+ cmd.Env = childEnv(pathEnv, port, name)+ cmd.Stdout = logFile+ cmd.Stderr = logFile+ setProcessGroup(cmd)+ if err := cmd.Start(); err != nil {+ logFile.Close()+ os.RemoveAll(envDir)+ return Environment{}, fmt.Errorf("start %q: %w", name, err)+ }+ rec.PID = cmd.Process.Pid+ e := &entry{rec: rec, leaderDone: make(chan struct{})}+ m.envs[id] = e+ m.persistLocked(e)+ m.logger.Info("environment started", "name", name, "id", id, "port", port, "task_id", task.TaskID)++ go m.wait(e, cmd, logFile)+ go m.probe(e)+ return m.viewLocked(e), nil+}++// WaitReady blocks until the environment stops starting or ctx ends, and+// returns its latest view.+func (m *Manager) WaitReady(ctx context.Context, key string) Environment {+ ticker := time.NewTicker(250 * time.Millisecond)+ defer ticker.Stop()+ for {+ m.mu.Lock()+ var view Environment+ for _, e := range m.envs {+ if "config:"+e.rec.ID == key {+ view = m.viewLocked(e)+ }+ }+ m.mu.Unlock()+ if view.State != StateStarting {+ return view+ }+ select {+ case <-ctx.Done():+ return view+ case <-ticker.C:+ }+ }+}++// Stop stops the task's live environment with this name.+func (m *Manager) Stop(task Task, name string) (Environment, error) {+ m.mu.Lock()+ var target *entry+ for _, e := range m.envs {+ if e.live() && sameOwner(e.rec, task) && e.rec.Name == name {+ target = e+ break+ }+ }+ m.mu.Unlock()+ if target == nil {+ return Environment{}, ErrNotFound+ }+ m.stop(target, "")+ m.mu.Lock()+ defer m.mu.Unlock()+ return m.viewLocked(target), nil+}++// List returns the task's environments, including recently ended ones.+func (m *Manager) List(task Task) []Environment {+ m.mu.Lock()+ defer m.mu.Unlock()+ var out []Environment+ for _, e := range m.envs {+ if sameOwner(e.rec, task) {+ out = append(out, m.viewLocked(e))+ }+ }+ sortEnvironments(out)+ return out+}++// Snapshot returns every environment the manager still reports.+func (m *Manager) Snapshot() []Environment {+ m.mu.Lock()+ defer m.mu.Unlock()+ out := make([]Environment, 0, len(m.envs))+ for _, e := range m.envs {+ out = append(out, m.viewLocked(e))+ }+ sortEnvironments(out)+ return out+}++// Tick expires environments past their TTL, notices adopted ones that died,+// and forgets ended ones once they have been reported.+func (m *Manager) Tick() {+ now := m.now()+ var expired []*entry+ m.mu.Lock()+ for id, e := range m.envs {+ switch {+ case e.live() && !e.stopping && now.After(e.rec.ExpiresAt):+ e.stopping = true+ expired = append(expired, e)+ case e.live() && e.leaderGone() && !groupAlive(e.rec.PID):+ m.endLocked(e, StateExited, "")+ case !e.live() && now.Sub(*e.rec.EndedAt) > endedRetention:+ delete(m.envs, id)+ os.Remove(filepath.Join(m.dir, id, stateFile))+ }+ }+ sweepLogs := now.Sub(m.lastLogSwep) > time.Hour+ if sweepLogs {+ m.lastLogSwep = now+ }+ m.mu.Unlock()+ for _, e := range expired {+ go m.stop(e, "expired")+ }+ if sweepLogs {+ m.sweepLogs(now)+ }+}++// 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 {+ m.mu.Lock()+ defer m.mu.Unlock()+ for _, e := range m.envs {+ if e.live() && e.rec.PID == pgid {+ return true+ }+ }+ return false+}++func (e *entry) leaderGone() bool {+ if e.leaderDone == nil {+ return true+ }+ select {+ case <-e.leaderDone:+ return true+ default:+ return false+ }+}++func (m *Manager) wait(e *entry, cmd *exec.Cmd, logFile *os.File) {+ err := cmd.Wait()+ logFile.Close()+ m.mu.Lock()+ defer m.mu.Unlock()+ close(e.leaderDone)+ // A start command that hands its servers off to children and returns+ // leaves them in its process group; the environment lives as long as the+ // group does, which Tick checks.+ if e.live() && !e.stopping && groupAlive(e.rec.PID) {+ return+ }+ if e.live() {+ state, detail := StateExited, exitDetail(err)+ if e.stopping {+ state, detail = StateStopped, e.rec.Detail+ }+ m.endLocked(e, state, detail)+ }+}++// probe marks the environment running once its ready URL answers with a+// status below 500. A 404 still counts, since a server with no route at "/"+// is up; a 5xx is a server still warming up or failing its health check. An+// environment with no URL is running as soon as it starts.+func (m *Manager) probe(e *entry) {+ m.mu.Lock()+ ready := e.rec.Ready+ m.mu.Unlock()+ if ready == "" {+ m.setRunning(e)+ return+ }+ detail := "not answering at " + ready+ deadline := m.now().Add(readyTimeout)+ for m.now().Before(deadline) {+ m.mu.Lock()+ live := e.live() && !e.stopping+ m.mu.Unlock()+ if !live {+ return+ }+ if resp, err := m.client.Get(ready); err == nil {+ io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))+ resp.Body.Close()+ if resp.StatusCode < http.StatusInternalServerError {+ m.setRunning(e)+ return+ }+ detail = fmt.Sprintf("%s answered %d", ready, resp.StatusCode)+ }+ time.Sleep(time.Second)+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ if e.live() && e.rec.State == StateStarting {+ e.rec.Detail = detail+ m.persistLocked(e)+ }+}++func (m *Manager) setRunning(e *entry) {+ m.mu.Lock()+ defer m.mu.Unlock()+ if e.live() && e.rec.State == StateStarting {+ e.rec.State = StateRunning+ e.rec.Detail = ""+ m.persistLocked(e)+ }+}++// stop runs the environment's stop command, then signals whatever is left+// of its process group.+func (m *Manager) stop(e *entry, detail string) {+ m.mu.Lock()+ if !e.live() {+ m.mu.Unlock()+ return+ }+ e.stopping = true+ if detail != "" {+ e.rec.Detail = detail+ }+ rec := e.rec+ m.mu.Unlock()++ if rec.Stop != "" {+ ctx, cancel := context.WithTimeout(context.Background(), stopCmdTimeout)+ cmd := shellCommand(rec.Stop)+ cmd.Dir = rec.RepoRoot+ cmd.Env = childEnv(rec.Path, rec.Port, rec.Name)+ setProcessGroup(cmd)+ if out, err := runWithContext(ctx, cmd); err != nil {+ m.logger.Warn("environment stop command failed", "name", rec.Name, "id", rec.ID, "error", err, "output", strings.TrimSpace(string(out)))+ }+ cancel()+ }+ if groupAlive(rec.PID) {+ _ = signalGroup(rec.PID, syscall.SIGTERM)+ deadline := time.Now().Add(stopGrace)+ for groupAlive(rec.PID) && time.Now().Before(deadline) {+ time.Sleep(200 * time.Millisecond)+ }+ if groupAlive(rec.PID) {+ _ = signalGroup(rec.PID, syscall.SIGKILL)+ }+ }+ if e.leaderDone != nil {+ select {+ case <-e.leaderDone:+ case <-time.After(2 * time.Second):+ }+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ if e.live() {+ m.endLocked(e, StateStopped, e.rec.Detail)+ }+ m.logger.Info("environment stopped", "name", rec.Name, "id", rec.ID)+}++func (m *Manager) endLocked(e *entry, state, detail string) {+ now := m.now()+ e.rec.State = state+ e.rec.Detail = detail+ e.rec.EndedAt = &now+ m.persistLocked(e)+}++func (m *Manager) persistLocked(e *entry) {+ data, err := json.MarshalIndent(e.rec, "", " ")+ if err != nil {+ return+ }+ path := filepath.Join(m.dir, e.rec.ID, stateFile)+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ m.logger.Warn("persist environment state failed", "id", e.rec.ID, "error", err)+ return+ }+ if err := os.Rename(tmp, path); err != nil {+ m.logger.Warn("persist environment state failed", "id", e.rec.ID, "error", err)+ }+}++func (m *Manager) viewLocked(e *entry) Environment {+ rec := e.rec+ view := Environment{+ Key: "config:" + rec.ID, TaskID: rec.TaskID, IssueID: rec.IssueID,+ Source: SourceConfig, Name: rec.Name, Label: rec.Label, URL: rec.URL, Port: rec.Port,+ State: rec.State, Detail: rec.Detail, StartedAt: rec.StartedAt,+ LogPath: filepath.Join(m.dir, rec.ID, outputFile), Dir: rec.RepoRoot, pgid: rec.PID,+ }+ if e.live() {+ expires := rec.ExpiresAt+ view.ExpiresAt = &expires+ }+ return view+}++func (m *Manager) allocatePortLocked() (int, error) {+ taken := make(map[int]bool)+ for _, e := range m.envs {+ if e.live() {+ taken[e.rec.Port] = true+ }+ }+ for base := portLow; base <= portHigh; base += portBlock {+ if taken[base] {+ continue+ }+ free := true+ for p := base; p < base+portBlock && free; p++ {+ free = portFree(p)+ }+ if free {+ return base, nil+ }+ }+ return 0, errors.New("no free port block for the environment")+}++func (m *Manager) sweepLogs(now time.Time) {+ dirs, err := os.ReadDir(m.dir)+ if err != nil {+ return+ }+ m.mu.Lock()+ known := make(map[string]bool, len(m.envs))+ for id := range m.envs {+ known[id] = true+ }+ m.mu.Unlock()+ for _, d := range dirs {+ if !d.IsDir() || known[d.Name()] {+ continue+ }+ info, err := os.Stat(filepath.Join(m.dir, d.Name(), outputFile))+ if err == nil && now.Sub(info.ModTime()) < logRetention {+ continue+ }+ os.RemoveAll(filepath.Join(m.dir, d.Name()))+ }+}++// sameOwner scopes an environment to its issue, so a later task on the same+// issue can see and stop what an earlier one started. A task with no issue+// owns only its own.+func sameOwner(rec record, task Task) bool {+ if task.IssueID != "" {+ return rec.IssueID == task.IssueID && rec.WorkspaceID == task.WorkspaceID+ }+ return rec.TaskID == task.TaskID+}++func portFree(port int) bool {+ for _, host := range []string{"127.0.0.1", "", "::1"} {+ ln, err := net.Listen("tcp", net.JoinHostPort(host, fmt.Sprint(port)))+ if err != nil {+ if errors.Is(err, syscall.EADDRINUSE) {+ return false+ }+ continue+ }+ ln.Close()+ }+ return true+}++// childEnv is the daemon's environment without the Multica identity a task+// carries, plus the caller's PATH so the repository's toolchain resolves.+func childEnv(pathEnv string, port int, name string) []string {+ env := make([]string, 0, len(os.Environ())+3)+ for _, kv := range os.Environ() {+ key, _, _ := strings.Cut(kv, "=")+ if strings.HasPrefix(key, "MULTICA_") || (pathEnv != "" && key == "PATH") {+ continue+ }+ env = append(env, kv)+ }+ if pathEnv != "" {+ env = append(env, "PATH="+pathEnv)+ }+ return append(env, fmt.Sprintf("MULTICA_PORT=%d", port), "MULTICA_ENVIRONMENT="+name)+}++// exitDetail says how the start command ended and nothing it printed: the+// detail is reported to the server, and output can carry secrets such as a+// connection string. The output stays in the local log.+func exitDetail(err error) string {+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ return exitErr.Error()+ }+ return ""+}++func runWithContext(ctx context.Context, cmd *exec.Cmd) ([]byte, error) {+ var out strings.Builder+ cmd.Stdout = &out+ cmd.Stderr = &out+ if err := cmd.Start(); err != nil {+ return nil, err+ }+ done := make(chan error, 1)+ go func() { done <- cmd.Wait() }()+ select {+ case err := <-done:+ return []byte(out.String()), err+ case <-ctx.Done():+ _ = signalGroup(cmd.Process.Pid, syscall.SIGKILL)+ <-done+ return []byte(out.String()), ctx.Err()+ }+}++func randomID() (string, error) {+ b := make([]byte, 8)+ if _, err := rand.Read(b); err != nil {+ return "", err+ }+ return hex.EncodeToString(b), nil+}++func sortEnvironments(envs []Environment) {+ sort.Slice(envs, func(i, j int) bool {+ if !envs[i].StartedAt.Equal(envs[j].StartedAt) {+ return envs[i].StartedAt.Before(envs[j].StartedAt)+ }+ return envs[i].Key < envs[j].Key+ })+}diff --git a/server/internal/daemon/localenv/manager_test.go b/server/internal/daemon/localenv/manager_test.gonew file mode 100644index 0000000000..80867efb31--- /dev/null+++ b/server/internal/daemon/localenv/manager_test.go@@ -0,0 +1,266 @@+//go:build !windows++package localenv++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// TestHelperProcess is the environment under test: the test binary re-run as+// a server on MULTICA_PORT, or as a command that fails on start.+func TestHelperProcess(t *testing.T) {+ switch os.Getenv("LOCALENV_HELPER") {+ case "serve":+ ln, err := net.Listen("tcp", "127.0.0.1:"+os.Getenv("MULTICA_PORT"))+ if err != nil {+ fmt.Println("listen:", err)+ os.Exit(2)+ }+ fmt.Println("serving", os.Getenv("MULTICA_ENVIRONMENT"))+ http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "ok") }))+ case "crash":+ fmt.Println("boom: cannot reach postgres://demo:" + crashSecret + "@db.invalid/app")+ os.Exit(3)+ }+}++const crashSecret = "fake-password-for-tests"++func helperCommand(mode string) string {+ return fmt.Sprintf("LOCALENV_HELPER=%s exec '%s' -test.run='^TestHelperProcess$'", mode, os.Args[0])+}++func newTestManager(t *testing.T) (*Manager, Task) {+ t.Helper()+ root := t.TempDir()+ writeConfig(t, root, fmt.Sprintf(`+[environments.web]+label = "Web app"+start = "%s"++[environments.broken]+start = "%s"+`, helperCommand("serve"), helperCommand("crash")))+ m := NewManager(t.TempDir(), slog.New(slog.NewTextHandler(io.Discard, nil)))+ task := Task{TaskID: "task-1", IssueID: "issue-1", WorkspaceID: "ws-1", RootDir: root}+ t.Cleanup(func() {+ for _, env := range m.Snapshot() {+ if env.State == StateStarting || env.State == StateRunning {+ m.Stop(task, env.Name)+ }+ }+ })+ return m, task+}++func waitReady(t *testing.T, m *Manager, key string) Environment {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ return m.WaitReady(ctx, key)+}++func TestManagerStartsSupervisesAndStops(t *testing.T) {+ m, task := newTestManager(t)+ env, err := m.Start(task, task.RootDir, "web", os.Getenv("PATH"))+ if err != nil {+ t.Fatalf("Start: %v", err)+ }+ env = waitReady(t, m, env.Key)+ if env.State != StateRunning || env.Label != "Web app" || env.URL != fmt.Sprintf("http://localhost:%d", env.Port) {+ t.Fatalf("started environment = %+v", env)+ }+ if env.ExpiresAt == nil || env.ExpiresAt.Sub(env.StartedAt) != DefaultTTL {+ t.Fatalf("ExpiresAt = %v, want start + %s", env.ExpiresAt, DefaultTTL)+ }+ resp, err := http.Get(env.URL)+ if err != nil {+ t.Fatalf("environment is not serving: %v", err)+ }+ resp.Body.Close()++ again, err := m.Start(task, task.RootDir, "web", "")+ if err != nil || again.Key != env.Key {+ t.Fatalf("second Start = %+v, %v; want the running environment back", again, err)+ }++ stopped, err := m.Stop(task, "web")+ if err != nil || stopped.State != StateStopped {+ t.Fatalf("Stop = %+v, %v", stopped, err)+ }+ if groupAlive(env.pgid) {+ t.Fatal("process group still alive after Stop")+ }+ if _, err := m.Stop(task, "web"); err != ErrNotFound {+ t.Fatalf("second Stop = %v, want ErrNotFound", err)+ }+}++func TestManagerReportsACrash(t *testing.T) {+ m, task := newTestManager(t)+ env, err := m.Start(task, task.RootDir, "broken", "")+ if err != nil {+ t.Fatalf("Start: %v", err)+ }+ env = waitReady(t, m, env.Key)+ if env.State != StateExited || env.Detail != "exit status 3" {+ t.Fatalf("crashed environment = %+v, want exited with only its exit status", env)+ }+ if env.ExpiresAt != nil {+ t.Fatalf("an ended environment has no expiry, got %v", env.ExpiresAt)+ }+ log, err := os.ReadFile(env.LogPath)+ if err != nil || !strings.Contains(string(log), crashSecret) {+ t.Fatalf("local log = %q, %v; want the command's output kept there", log, err)+ }+}++func TestManagerWaitsForAHealthyReadyCheck(t *testing.T) {+ var healthy atomic.Bool+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ if !healthy.Load() {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }+ io.WriteString(w, "ok")+ }))+ defer srv.Close()+ root := t.TempDir()+ writeConfig(t, root, fmt.Sprintf("[environments.web]\nstart = \"exec sleep 60\"\nurl = %q\n", srv.URL))+ 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)+ }+ t.Cleanup(func() { m.Stop(task, "web") })++ ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)+ got := m.WaitReady(ctx, env.Key)+ cancel()+ if got.State != StateStarting {+ t.Fatalf("state while the ready check answers 503 = %q, want starting", got.State)+ }+ healthy.Store(true)+ if got = waitReady(t, m, env.Key); got.State != StateRunning {+ t.Fatalf("state once the ready check answers 200 = %q, want running", got.State)+ }+}++func TestManagerStopsAnExpiredEnvironment(t *testing.T) {+ m, task := newTestManager(t)+ env, err := m.Start(task, task.RootDir, "web", "")+ if err != nil {+ t.Fatalf("Start: %v", err)+ }+ waitReady(t, m, env.Key)+ m.now = func() time.Time { return time.Now().Add(DefaultTTL + time.Minute) }+ m.Tick()+ deadline := time.Now().Add(15 * time.Second)+ for time.Now().Before(deadline) {+ if got := m.List(task)[0]; got.State == StateStopped {+ if got.Detail != "expired" {+ t.Fatalf("expired environment detail = %q", got.Detail)+ }+ return+ }+ time.Sleep(100 * time.Millisecond)+ }+ t.Fatalf("environment past its TTL is still %+v", m.List(task)[0])+}++func TestManagerAdoptsEnvironmentsAfterRestart(t *testing.T) {+ m, task := newTestManager(t)+ env, err := m.Start(task, task.RootDir, "web", "")+ if err != nil {+ t.Fatalf("Start: %v", err)+ }+ waitReady(t, m, env.Key)++ restarted := NewManager(m.dir, m.logger)+ if err := restarted.Load(); err != nil {+ t.Fatalf("Load: %v", err)+ }+ adopted := restarted.List(task)+ 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 _, err := restarted.Stop(task, "web"); err != nil {+ t.Fatalf("Stop after restart: %v", err)+ }+ if groupAlive(env.pgid) {+ t.Fatal("adopted environment still alive after Stop")+ }+}++func TestManagerScopesEnvironmentsToTheIssue(t *testing.T) {+ m, task := newTestManager(t)+ env, err := m.Start(task, task.RootDir, "web", "")+ if err != nil {+ t.Fatalf("Start: %v", err)+ }+ waitReady(t, m, env.Key)++ laterTask := task+ laterTask.TaskID = "task-2"+ if got := m.List(laterTask); len(got) != 1 {+ t.Fatalf("a later task on the same issue sees %d environments, want 1", len(got))+ }+ otherIssue := Task{TaskID: "task-3", IssueID: "issue-2", WorkspaceID: "ws-1", RootDir: task.RootDir}+ if got := m.List(otherIssue); len(got) != 0 {+ t.Fatalf("another issue sees %d environments", len(got))+ }+ if _, err := m.Stop(otherIssue, "web"); err != ErrNotFound {+ t.Fatalf("another issue stopped the environment: %v", err)+ }+}++func TestManagerRefusesDirectoriesOutsideTheTask(t *testing.T) {+ m, task := newTestManager(t)+ outside := t.TempDir()+ writeConfig(t, outside, fmt.Sprintf("[environments.web]\nstart = \"%s\"", helperCommand("serve")))+ if _, err := m.Start(task, outside, "web", ""); err == nil {+ t.Fatal("Start accepted a directory outside the task")+ }+ if _, err := m.Start(task, task.RootDir, "missing", ""); err == nil || !strings.Contains(err.Error(), "declared: broken, web") {+ t.Fatalf("Start of an undeclared environment = %v", err)+ }+ if len(m.Snapshot()) != 0 {+ t.Fatal("refused starts left environments behind")+ }+}++func TestManagerAllocatesDistinctPortBlocks(t *testing.T) {+ m, task := newTestManager(t)+ first, err := m.Start(task, task.RootDir, "web", "")+ if err != nil {+ t.Fatalf("Start: %v", err)+ }+ other := Task{TaskID: "task-9", IssueID: "issue-9", WorkspaceID: "ws-1", RootDir: task.RootDir}+ second, err := m.Start(other, task.RootDir, "web", "")+ if err != nil {+ t.Fatalf("Start: %v", err)+ }+ t.Cleanup(func() { m.Stop(other, "web") })+ if first.Port == second.Port || first.Port%portBlock != 0 || second.Port%portBlock != 0 {+ t.Fatalf("ports = %d and %d, want distinct block starts", first.Port, second.Port)+ }+ if _, err := os.Stat(filepath.Join(m.dir, strings.TrimPrefix(first.Key, "config:"), stateFile)); err != nil {+ t.Fatalf("state was not persisted: %v", err)+ }+}diff --git a/server/internal/daemon/localenv/proc_unix.go b/server/internal/daemon/localenv/proc_unix.gonew file mode 100644index 0000000000..ccd2bee7e3--- /dev/null+++ b/server/internal/daemon/localenv/proc_unix.go@@ -0,0 +1,46 @@+//go:build !windows++package localenv++import (+ "errors"+ "os/exec"+ "syscall"+)++const supported = true++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.+func setProcessGroup(cmd *exec.Cmd) {+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+}++func signalGroup(pgid int, sig syscall.Signal) error {+ if pgid <= 0 {+ return errors.New("invalid process group")+ }+ return syscall.Kill(-pgid, sig)+}++// groupAlive reports whether any process is left in the group. A group id is+// not reused while one of its members exists, so a live group is still ours.+func groupAlive(pgid int) bool {+ if pgid <= 0 {+ return false+ }+ err := syscall.Kill(-pgid, 0)+ return err == nil || errors.Is(err, syscall.EPERM)+}++func processGroup(pid int) int {+ pgid, err := syscall.Getpgid(pid)+ if err != nil {+ return 0+ }+ return pgid+}diff --git a/server/internal/daemon/localenv/proc_windows.go b/server/internal/daemon/localenv/proc_windows.gonew file mode 100644index 0000000000..1aa4737ed3--- /dev/null+++ b/server/internal/daemon/localenv/proc_windows.go@@ -0,0 +1,20 @@+//go:build windows++package localenv++import (+ "os/exec"+ "syscall"+)++const supported = false++func shellCommand(script string) *exec.Cmd { return exec.Command("cmd", "/C", script) }++func setProcessGroup(*exec.Cmd) {}++func signalGroup(int, syscall.Signal) error { return ErrUnsupported }++func groupAlive(int) bool { return false }++func processGroup(int) int { return 0 }diff --git a/server/internal/handler/issue_environment.go b/server/internal/handler/issue_environment.gonew file mode 100644index 0000000000..e463e66317--- /dev/null+++ b/server/internal/handler/issue_environment.go@@ -0,0 +1,281 @@+package handler++import (+ "encoding/json"+ "log/slog"+ "net/http"+ "net/url"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++const (+ // The daemon re-reports a live environment at least once a minute, so one+ // that has not been seen for a few minutes is on a machine that went away.+ issueEnvironmentUnreachableAfter = 3 * time.Minute+ // Ended environments stay listed this long so the sidebar can show what ran.+ issueEnvironmentHistoryWindow = 7 * 24 * time.Hour+ maxIssueEnvironmentsPerSnapshot = 50+)++var issueEnvironmentSources = map[string]bool{"config": true, "detected": true}++var issueEnvironmentStates = map[string]bool{"starting": true, "running": true, "exited": true, "stopped": true}++// IssueEnvironmentReport is one environment in a daemon's per-task snapshot.+type IssueEnvironmentReport struct {+ Key string `json:"key"`+ Source string `json:"source"`+ Name string `json:"name"`+ Label string `json:"label"`+ URL string `json:"url"`+ Port int `json:"port"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt time.Time `json:"started_at"`+ ExpiresAt *time.Time `json:"expires_at"`+}++type ReportTaskEnvironmentsRequest struct {+ Environments []IssueEnvironmentReport `json:"environments"`+}++type IssueEnvironmentResponse struct {+ ID string `json:"id"`+ IssueID string `json:"issue_id"`+ TaskID string `json:"task_id"`+ RuntimeID *string `json:"runtime_id"`+ AgentID *string `json:"agent_id"`+ Source string `json:"source"`+ Name string `json:"name"`+ Label string `json:"label"`+ URL string `json:"url"`+ Port *int32 `json:"port"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt string `json:"started_at"`+ ExpiresAt *string `json:"expires_at"`+ LastSeenAt string `json:"last_seen_at"`+ EndedAt *string `json:"ended_at"`+}++type IssueEnvironmentsResponse struct {+ Environments []IssueEnvironmentResponse `json:"environments"`+}++// validateIssueEnvironmentReport normalizes one reported environment and+// returns a reason when it cannot be stored.+func validateIssueEnvironmentReport(env *IssueEnvironmentReport, now time.Time) string {+ env.Key = strings.TrimSpace(env.Key)+ env.Name = strings.TrimSpace(env.Name)+ env.Label = strings.TrimSpace(env.Label)+ env.URL = strings.TrimSpace(env.URL)+ switch {+ case env.Key == "" || len(env.Key) > 128:+ return "key must be 1-128 characters"+ case !issueEnvironmentSources[env.Source]:+ return "unknown source"+ case !issueEnvironmentStates[env.State]:+ return "unknown state"+ case env.Name == "" || utf8.RuneCountInString(env.Name) > 64:+ return "name must be 1-64 characters"+ case utf8.RuneCountInString(env.Label) > 120:+ return "label must be at most 120 characters"+ case env.Port < 0 || env.Port > 65535:+ return "port out of range"+ }+ if env.URL != "" {+ u, err := url.Parse(env.URL)+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || len(env.URL) > 2048 {+ return "url must be an http(s) URL"+ }+ }+ if utf8.RuneCountInString(env.Detail) > 500 {+ env.Detail = string([]rune(env.Detail)[:500])+ }+ if env.StartedAt.IsZero() {+ env.StartedAt = now+ }+ return ""+}++// ReportTaskEnvironments replaces the daemon's view of one task's environments.+// The snapshot is complete: an environment the task reported before and omits+// now has ended.+func (h *Handler) ReportTaskEnvironments(w http.ResponseWriter, r *http.Request) {+ task, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, chi.URLParam(r, "taskId"))+ if !ok {+ return+ }+ var req ReportTaskEnvironmentsRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if len(req.Environments) > maxIssueEnvironmentsPerSnapshot {+ writeError(w, http.StatusBadRequest, "too many environments")+ return+ }+ now := time.Now()+ seen := make(map[string]bool, len(req.Environments))+ for i := range req.Environments {+ if reason := validateIssueEnvironmentReport(&req.Environments[i], now); reason != "" {+ writeError(w, http.StatusBadRequest, "environment "+req.Environments[i].Key+": "+reason)+ return+ }+ if seen[req.Environments[i].Key] {+ writeError(w, http.StatusBadRequest, "duplicate environment key "+req.Environments[i].Key)+ return+ }+ seen[req.Environments[i].Key] = true+ }+ // Environments are an issue-sidebar surface; other task kinds have nowhere+ // to show them.+ if !task.IssueID.Valid {+ writeJSON(w, http.StatusOK, map[string]int{"accepted": 0})+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace_id")+ if !ok {+ return+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to report environments")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ before, err := qtx.ListOpenIssueEnvironmentsByTask(r.Context(), task.ID)+ if err != nil {+ slog.Warn("list task environments failed", "task_id", uuidToString(task.ID), "error", err)+ writeError(w, http.StatusInternalServerError, "failed to report environments")+ return+ }+ changed := false+ open := make(map[string]db.IssueEnvironment, len(before))+ for _, row := range before {+ open[row.LocalKey] = row+ }+ keep := make([]string, 0, len(req.Environments))+ for _, env := range req.Environments {+ keep = append(keep, env.Key)+ params := db.UpsertIssueEnvironmentParams{+ WorkspaceID: wsUUID,+ IssueID: task.IssueID,+ TaskID: task.ID,+ RuntimeID: task.RuntimeID,+ AgentID: task.AgentID,+ LocalKey: env.Key,+ Source: env.Source,+ Name: env.Name,+ Label: env.Label,+ Url: env.URL,+ State: env.State,+ Detail: env.Detail,+ StartedAt: pgtype.Timestamptz{Time: env.StartedAt, Valid: true},+ }+ if env.Port > 0 {+ params.Port = pgtype.Int4{Int32: int32(env.Port), Valid: true}+ }+ if env.ExpiresAt != nil {+ params.ExpiresAt = pgtype.Timestamptz{Time: *env.ExpiresAt, Valid: true}+ }+ if _, err := qtx.UpsertIssueEnvironment(r.Context(), params); err != nil {+ slog.Warn("upsert task environment failed", "task_id", uuidToString(task.ID), "key", env.Key, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to report environments")+ return+ }+ prev, wasOpen := open[env.Key]+ if !wasOpen || prev.State != env.State || prev.Url != env.URL || prev.Label != env.Label || prev.Detail != env.Detail {+ changed = true+ }+ }+ for key := range open {+ if !seen[key] {+ changed = true+ }+ }+ if err := qtx.EndIssueEnvironmentsMissingFromSnapshot(r.Context(), db.EndIssueEnvironmentsMissingFromSnapshotParams{+ TaskID: task.ID,+ KeepKeys: keep,+ }); err != nil {+ slog.Warn("end task environments failed", "task_id", uuidToString(task.ID), "error", err)+ writeError(w, http.StatusInternalServerError, "failed to report environments")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to report environments")+ return+ }+ // A heartbeat that only refreshes last_seen_at changes nothing a reader+ // sees, so it stays off the realtime channel.+ if changed {+ h.publish(protocol.EventEnvironmentChanged, workspaceID, "system", "", map[string]string{+ "issue_id": uuidToString(task.IssueID),+ })+ }+ writeJSON(w, http.StatusOK, map[string]int{"accepted": len(req.Environments)})+}++// ListIssueEnvironments returns the issue's live environments and those that+// ended recently.+func (h *Handler) ListIssueEnvironments(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ now := time.Now()+ rows, err := h.Queries.ListIssueEnvironments(r.Context(), db.ListIssueEnvironmentsParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ EndedAfter: pgtype.Timestamptz{Time: now.Add(-issueEnvironmentHistoryWindow), Valid: true},+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list environments")+ return+ }+ out := make([]IssueEnvironmentResponse, 0, len(rows))+ for _, row := range rows {+ out = append(out, issueEnvironmentToResponse(row, now))+ }+ writeJSON(w, http.StatusOK, IssueEnvironmentsResponse{Environments: out})+}++func issueEnvironmentToResponse(row db.IssueEnvironment, now time.Time) IssueEnvironmentResponse {+ state := row.State+ if !row.EndedAt.Valid && row.LastSeenAt.Valid && now.Sub(row.LastSeenAt.Time) > issueEnvironmentUnreachableAfter {+ state = "unreachable"+ }+ resp := IssueEnvironmentResponse{+ ID: uuidToString(row.ID),+ IssueID: uuidToString(row.IssueID),+ TaskID: uuidToString(row.TaskID),+ RuntimeID: uuidToPtr(row.RuntimeID),+ AgentID: uuidToPtr(row.AgentID),+ Source: row.Source,+ Name: row.Name,+ Label: row.Label,+ URL: row.Url,+ State: state,+ Detail: row.Detail,+ StartedAt: timestampToString(row.StartedAt),+ ExpiresAt: timestampToPtr(row.ExpiresAt),+ LastSeenAt: timestampToString(row.LastSeenAt),+ EndedAt: timestampToPtr(row.EndedAt),+ }+ if row.Port.Valid {+ port := row.Port.Int32+ resp.Port = &port+ }+ return resp+}diff --git a/server/internal/handler/issue_environment_test.go b/server/internal/handler/issue_environment_test.gonew file mode 100644index 0000000000..c9e50f583d--- /dev/null+++ b/server/internal/handler/issue_environment_test.go@@ -0,0 +1,153 @@+package handler++import (+ "net/http"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func issueEnvironmentFixture(t *testing.T) (issueID, taskID string) {+ t.Helper()+ runtimeID := dbfx.Runtime(t, "issue-environment runtime")+ agentID := dbfx.Agent(t, "issue-environment agent", runtimeID)+ issueID = dbfx.Issue(t, "issue-environment issue")+ taskID = dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": runtimeID, "status": "running"})+ dbfx.Cleanup(t, `DELETE FROM issue_environment WHERE task_id = $1`, taskID)+ return issueID, taskID+}++func reportEnvironments(t *testing.T, taskID string, envs ...map[string]any) *testutil.Response {+ t.Helper()+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/environments",+ map[string]any{"environments": envs}), "taskId", taskID)+ return testutil.Call(t, testHandler.ReportTaskEnvironments, req)+}++func listEnvironments(t *testing.T, issueID string) map[string]IssueEnvironmentResponse {+ t.Helper()+ var out IssueEnvironmentsResponse+ testutil.Call(t, testHandler.ListIssueEnvironments,+ withURLParam(newRequest(http.MethodGet, "/api/issues/"+issueID+"/environments", nil), "id", issueID)).+ Want(http.StatusOK).JSON(&out)+ byKey := make(map[string]IssueEnvironmentResponse, len(out.Environments))+ for _, env := range out.Environments {+ byKey[env.Name] = env+ }+ return byKey+}++func webEnvironment(state string) map[string]any {+ return map[string]any{+ "key": "config:web", "source": "config", "name": "web", "label": "Web app",+ "url": "http://localhost:41000", "port": 41000, "state": state,+ "started_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339),+ "expires_at": time.Now().Add(24 * time.Hour).UTC().Format(time.RFC3339),+ }+}++func TestReportTaskEnvironments_SnapshotLifecycle(t *testing.T) {+ issueID, taskID := issueEnvironmentFixture(t)+ vite := map[string]any{"key": "detected:abc", "source": "detected", "name": "node", "url": "http://localhost:5173", "port": 5173, "state": "running"}++ reportEnvironments(t, taskID, webEnvironment("running"), vite).Want(http.StatusOK)+ envs := listEnvironments(t, issueID)+ if len(envs) != 2 || envs["web"].State != "running" || envs["node"].State != "running" {+ t.Fatalf("after first snapshot = %+v", envs)+ }+ if envs["web"].Label != "Web app" || envs["web"].URL != "http://localhost:41000" || envs["web"].Port == nil || *envs["web"].Port != 41000 {+ t.Fatalf("web environment = %+v", envs["web"])+ }+ if envs["web"].ExpiresAt == nil || envs["web"].EndedAt != nil {+ t.Fatalf("web environment times = %+v", envs["web"])+ }++ // The detected server is gone from the next snapshot: it has stopped.+ reportEnvironments(t, taskID, webEnvironment("running")).Want(http.StatusOK)+ envs = listEnvironments(t, issueID)+ if envs["node"].State != "stopped" || envs["node"].EndedAt == nil {+ t.Fatalf("omitted environment = %+v, want stopped and ended", envs["node"])+ }+ if envs["web"].State != "running" || envs["web"].EndedAt != nil {+ t.Fatalf("still-reported environment = %+v", envs["web"])+ }++ // A crashed environment keeps saying so after the daemon drops it.+ reportEnvironments(t, taskID, webEnvironment("exited")).Want(http.StatusOK)+ reportEnvironments(t, taskID).Want(http.StatusOK)+ envs = listEnvironments(t, issueID)+ if envs["web"].State != "exited" || envs["web"].EndedAt == nil {+ t.Fatalf("exited environment = %+v, want exited and ended", envs["web"])+ }+}++func TestReportTaskEnvironments_RestartReopensRow(t *testing.T) {+ issueID, taskID := issueEnvironmentFixture(t)+ reportEnvironments(t, taskID, webEnvironment("running")).Want(http.StatusOK)+ reportEnvironments(t, taskID).Want(http.StatusOK)+ reportEnvironments(t, taskID, webEnvironment("running")).Want(http.StatusOK)++ envs := listEnvironments(t, issueID)+ if len(envs) != 1 || envs["web"].State != "running" || envs["web"].EndedAt != nil {+ t.Fatalf("restarted environment = %+v, want one live row", envs)+ }+}++func TestListIssueEnvironments_UnreachableWhenNotSeen(t *testing.T) {+ issueID, taskID := issueEnvironmentFixture(t)+ reportEnvironments(t, taskID, webEnvironment("running")).Want(http.StatusOK)+ dbfx.Exec(t, `UPDATE issue_environment SET last_seen_at = now() - interval '10 minutes' WHERE task_id = $1`, taskID)++ if got := listEnvironments(t, issueID)["web"].State; got != "unreachable" {+ t.Fatalf("state of an environment not seen for 10 minutes = %q, want unreachable", got)+ }+}++func TestReportTaskEnvironments_RejectsInvalidSnapshot(t *testing.T) {+ _, taskID := issueEnvironmentFixture(t)+ cases := map[string]map[string]any{+ "script url": {"key": "a", "source": "config", "name": "web", "url": "javascript:alert(1)", "state": "running"},+ "unknown source": {"key": "a", "source": "cloud", "name": "web", "state": "running"},+ "unknown state": {"key": "a", "source": "config", "name": "web", "state": "healthy"},+ "empty name": {"key": "a", "source": "config", "name": " ", "state": "running"},+ "bad port": {"key": "a", "source": "config", "name": "web", "port": 70000, "state": "running"},+ }+ for name, env := range cases {+ t.Run(name, func(t *testing.T) {+ reportEnvironments(t, taskID, env).Want(http.StatusBadRequest)+ })+ }+ t.Run("duplicate key", func(t *testing.T) {+ reportEnvironments(t, taskID, webEnvironment("running"), webEnvironment("running")).Want(http.StatusBadRequest)+ })+ if n := dbfx.Count(t, `SELECT count(*) FROM issue_environment WHERE task_id = $1`, taskID); n != 0 {+ t.Fatalf("rejected snapshots stored %d rows", n)+ }+}++func TestReportTaskEnvironments_OtherWorkspaceDaemonCannotReport(t *testing.T) {+ issueID, taskID := issueEnvironmentFixture(t)+ req := withURLParam(newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/environments",+ map[string]any{"environments": []any{webEnvironment("running")}},+ "00000000-0000-0000-0000-000000000000", "attacker-daemon"), "taskId", taskID)+ testutil.Call(t, testHandler.ReportTaskEnvironments, req).Want(http.StatusNotFound)++ if envs := listEnvironments(t, issueID); len(envs) != 0 {+ t.Fatalf("environments after a foreign daemon's report = %+v", envs)+ }+}++func TestReportTaskEnvironments_TaskWithoutIssueIsIgnored(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "issue-environment chat runtime")+ agentID := dbfx.Agent(t, "issue-environment chat agent", runtimeID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running"})+ dbfx.Cleanup(t, `DELETE FROM issue_environment WHERE task_id = $1`, taskID)++ // A task with no issue may not resolve to a workspace at all; either way it+ // must not store anything.+ reportEnvironments(t, taskID, webEnvironment("running")).WantOneOf(http.StatusOK, http.StatusNotFound)+ if n := dbfx.Count(t, `SELECT count(*) FROM issue_environment WHERE task_id = $1`, taskID); n != 0 {+ t.Fatalf("issue-less task stored %d environments", n)+ }+}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex e16f493dd9..3079f8ac22 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -153,6 +153,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"app_action_rule": workspaceDelete,"app_action_request": workspaceDelete,"app_tool_call": workspaceDelete,+ "issue_environment": workspaceDelete,"workspace_app_setting": workspaceDelete,"app_tool_class_override": workspaceDelete,"workspace": workspaceDelete,diff --git a/server/migrations/633_issue_environment.down.sql b/server/migrations/633_issue_environment.down.sqlnew file mode 100644index 0000000000..a63358790b--- /dev/null+++ b/server/migrations/633_issue_environment.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS issue_environment;diff --git a/server/migrations/633_issue_environment.up.sql b/server/migrations/633_issue_environment.up.sqlnew file mode 100644index 0000000000..9a50c4e1cd--- /dev/null+++ b/server/migrations/633_issue_environment.up.sql@@ -0,0 +1,26 @@+-- Local environments (dev servers) a daemon started or detected for one of an+-- issue's tasks. The daemon reports a full snapshot per task; an environment it+-- stops reporting is ended rather than deleted, so the issue sidebar can show+-- what ran recently.+CREATE TABLE IF NOT EXISTS issue_environment (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ issue_id UUID NOT NULL,+ task_id UUID NOT NULL,+ runtime_id UUID,+ agent_id UUID,+ local_key TEXT NOT NULL,+ source TEXT NOT NULL CHECK (source IN ('config', 'detected')),+ name TEXT NOT NULL,+ label TEXT NOT NULL DEFAULT '',+ url TEXT NOT NULL DEFAULT '',+ port INTEGER,+ state TEXT NOT NULL CHECK (state IN ('starting', 'running', 'exited', 'stopped')),+ detail TEXT NOT NULL DEFAULT '',+ started_at TIMESTAMPTZ NOT NULL,+ expires_at TIMESTAMPTZ,+ last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ ended_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/634_issue_environment_task_key_idx.down.sql b/server/migrations/634_issue_environment_task_key_idx.down.sqlnew file mode 100644index 0000000000..f1faee3264--- /dev/null+++ b/server/migrations/634_issue_environment_task_key_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_issue_environment_task_key;diff --git a/server/migrations/634_issue_environment_task_key_idx.up.sql b/server/migrations/634_issue_environment_task_key_idx.up.sqlnew file mode 100644index 0000000000..49244247c0--- /dev/null+++ b/server/migrations/634_issue_environment_task_key_idx.up.sql@@ -0,0 +1,3 @@+-- One row per environment per task: the daemon's snapshot upserts on it.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_issue_environment_task_key+ ON issue_environment (task_id, local_key);diff --git a/server/migrations/635_issue_environment_issue_idx.down.sql b/server/migrations/635_issue_environment_issue_idx.down.sqlnew file mode 100644index 0000000000..0bd8f1852e--- /dev/null+++ b/server/migrations/635_issue_environment_issue_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_environment_issue;diff --git a/server/migrations/635_issue_environment_issue_idx.up.sql b/server/migrations/635_issue_environment_issue_idx.up.sqlnew file mode 100644index 0000000000..bb7b71112f--- /dev/null+++ b/server/migrations/635_issue_environment_issue_idx.up.sql@@ -0,0 +1,3 @@+-- The issue sidebar's environment list.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_environment_issue+ ON issue_environment (issue_id, created_at);diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 033de863e2..e6a5a6cec2 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -511,6 +511,9 @@ cleared_pr_exclusions AS (),cleared_unread AS (DELETE FROM issue_unread WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_environments AS (+ DELETE FROM issue_environment WHERE issue_id IN (SELECT target.id FROM target))DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target)`diff --git a/server/pkg/db/generated/issue_environment.sql.go b/server/pkg/db/generated/issue_environment.sql.gonew file mode 100644index 0000000000..70f5210158--- /dev/null+++ b/server/pkg/db/generated/issue_environment.sql.go@@ -0,0 +1,228 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: issue_environment.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const endIssueEnvironmentsMissingFromSnapshot = `-- name: EndIssueEnvironmentsMissingFromSnapshot :exec+UPDATE issue_environment+SET ended_at = now(),+ state = CASE WHEN state = 'exited' THEN 'exited' ELSE 'stopped' END,+ updated_at = now()+WHERE task_id = $1+ AND ended_at IS NULL+ AND NOT (local_key = ANY($2::text[]))+`++type EndIssueEnvironmentsMissingFromSnapshotParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ KeepKeys []string `json:"keep_keys"`+}++// Environments the daemon no longer reports for the task have stopped. An+// exited one keeps its state so the sidebar can still say it crashed.+func (q *Queries) EndIssueEnvironmentsMissingFromSnapshot(ctx context.Context, arg EndIssueEnvironmentsMissingFromSnapshotParams) error {+ _, err := q.db.Exec(ctx, endIssueEnvironmentsMissingFromSnapshot, arg.TaskID, arg.KeepKeys)+ return err+}++const listIssueEnvironments = `-- name: ListIssueEnvironments :many+SELECT id, workspace_id, issue_id, task_id, runtime_id, agent_id, local_key, source, name, label, url, port, state, detail, started_at, expires_at, last_seen_at, ended_at, created_at, updated_at FROM issue_environment+WHERE issue_id = $1+ AND workspace_id = $2+ AND (ended_at IS NULL OR ended_at > $3::timestamptz)+ORDER BY created_at DESC+LIMIT 50+`++type ListIssueEnvironmentsParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ EndedAfter pgtype.Timestamptz `json:"ended_after"`+}++// Live environments plus those that ended within the history window.+func (q *Queries) ListIssueEnvironments(ctx context.Context, arg ListIssueEnvironmentsParams) ([]IssueEnvironment, error) {+ rows, err := q.db.Query(ctx, listIssueEnvironments, arg.IssueID, arg.WorkspaceID, arg.EndedAfter)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueEnvironment{}+ for rows.Next() {+ var i IssueEnvironment+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.TaskID,+ &i.RuntimeID,+ &i.AgentID,+ &i.LocalKey,+ &i.Source,+ &i.Name,+ &i.Label,+ &i.Url,+ &i.Port,+ &i.State,+ &i.Detail,+ &i.StartedAt,+ &i.ExpiresAt,+ &i.LastSeenAt,+ &i.EndedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listOpenIssueEnvironmentsByTask = `-- name: ListOpenIssueEnvironmentsByTask :many+SELECT id, workspace_id, issue_id, task_id, runtime_id, agent_id, local_key, source, name, label, url, port, state, detail, started_at, expires_at, last_seen_at, ended_at, created_at, updated_at FROM issue_environment+WHERE task_id = $1 AND ended_at IS NULL+`++func (q *Queries) ListOpenIssueEnvironmentsByTask(ctx context.Context, taskID pgtype.UUID) ([]IssueEnvironment, error) {+ rows, err := q.db.Query(ctx, listOpenIssueEnvironmentsByTask, taskID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueEnvironment{}+ for rows.Next() {+ var i IssueEnvironment+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.TaskID,+ &i.RuntimeID,+ &i.AgentID,+ &i.LocalKey,+ &i.Source,+ &i.Name,+ &i.Label,+ &i.Url,+ &i.Port,+ &i.State,+ &i.Detail,+ &i.StartedAt,+ &i.ExpiresAt,+ &i.LastSeenAt,+ &i.EndedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const upsertIssueEnvironment = `-- name: UpsertIssueEnvironment :one+INSERT INTO issue_environment (+ workspace_id, issue_id, task_id, runtime_id, agent_id, local_key, source,+ name, label, url, port, state, detail, started_at, expires_at, ended_at+) VALUES (+ $1, $2, $3, $4, $5, $6, $7,+ $8, $9, $10, $11, $12, $13, $14, $15,+ CASE WHEN $12::text IN ('exited', 'stopped') THEN now() END+)+ON CONFLICT (task_id, local_key) DO UPDATE SET+ source = EXCLUDED.source,+ name = EXCLUDED.name,+ label = EXCLUDED.label,+ url = EXCLUDED.url,+ port = EXCLUDED.port,+ state = EXCLUDED.state,+ detail = EXCLUDED.detail,+ started_at = EXCLUDED.started_at,+ expires_at = EXCLUDED.expires_at,+ last_seen_at = now(),+ ended_at = CASE+ WHEN EXCLUDED.state IN ('exited', 'stopped') THEN COALESCE(issue_environment.ended_at, now())+ END,+ updated_at = now()+RETURNING id, workspace_id, issue_id, task_id, runtime_id, agent_id, local_key, source, name, label, url, port, state, detail, started_at, expires_at, last_seen_at, ended_at, created_at, updated_at+`++type UpsertIssueEnvironmentParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ TaskID pgtype.UUID `json:"task_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ LocalKey string `json:"local_key"`+ Source string `json:"source"`+ Name string `json:"name"`+ Label string `json:"label"`+ Url string `json:"url"`+ Port pgtype.Int4 `json:"port"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt pgtype.Timestamptz `json:"started_at"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+}++// A reported environment that has exited or stopped keeps its first ended_at,+// so re-reporting the same snapshot does not move it.+func (q *Queries) UpsertIssueEnvironment(ctx context.Context, arg UpsertIssueEnvironmentParams) (IssueEnvironment, error) {+ row := q.db.QueryRow(ctx, upsertIssueEnvironment,+ arg.WorkspaceID,+ arg.IssueID,+ arg.TaskID,+ arg.RuntimeID,+ arg.AgentID,+ arg.LocalKey,+ arg.Source,+ arg.Name,+ arg.Label,+ arg.Url,+ arg.Port,+ arg.State,+ arg.Detail,+ arg.StartedAt,+ arg.ExpiresAt,+ )+ var i IssueEnvironment+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.TaskID,+ &i.RuntimeID,+ &i.AgentID,+ &i.LocalKey,+ &i.Source,+ &i.Name,+ &i.Label,+ &i.Url,+ &i.Port,+ &i.State,+ &i.Detail,+ &i.StartedAt,+ &i.ExpiresAt,+ &i.LastSeenAt,+ &i.EndedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex af17032070..24e0576c65 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -968,6 +968,29 @@ type IssueDependency struct {Type string `json:"type"`}+type IssueEnvironment struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ TaskID pgtype.UUID `json:"task_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ LocalKey string `json:"local_key"`+ Source string `json:"source"`+ Name string `json:"name"`+ Label string `json:"label"`+ Url string `json:"url"`+ Port pgtype.Int4 `json:"port"`+ State string `json:"state"`+ Detail string `json:"detail"`+ StartedAt pgtype.Timestamptz `json:"started_at"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`+ EndedAt pgtype.Timestamptz `json:"ended_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type IssueLabel struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 077fa877ff..2b474886d0 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -498,6 +498,9 @@ deleted_app_action_requests AS (deleted_app_tool_calls AS (DELETE FROM app_tool_call WHERE workspace_id = $1),+deleted_issue_environments AS (+ DELETE FROM issue_environment WHERE workspace_id = $1+),deleted_workspace_app_settings AS (DELETE FROM workspace_app_setting WHERE workspace_id = $1),diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 5079417272..2a2c980e86 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -506,6 +506,9 @@ cleared_pr_exclusions AS (),cleared_unread AS (DELETE FROM issue_unread WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_environments AS (+ DELETE FROM issue_environment WHERE issue_id IN (SELECT target.id FROM target))DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);diff --git a/server/pkg/db/queries/issue_environment.sql b/server/pkg/db/queries/issue_environment.sqlnew file mode 100644index 0000000000..278528c937--- /dev/null+++ b/server/pkg/db/queries/issue_environment.sql@@ -0,0 +1,51 @@+-- name: ListOpenIssueEnvironmentsByTask :many+SELECT * FROM issue_environment+WHERE task_id = $1 AND ended_at IS NULL;++-- name: UpsertIssueEnvironment :one+-- A reported environment that has exited or stopped keeps its first ended_at,+-- so re-reporting the same snapshot does not move it.+INSERT INTO issue_environment (+ workspace_id, issue_id, task_id, runtime_id, agent_id, local_key, source,+ name, label, url, port, state, detail, started_at, expires_at, ended_at+) VALUES (+ @workspace_id, @issue_id, @task_id, @runtime_id, @agent_id, @local_key, @source,+ @name, @label, @url, @port, @state, @detail, @started_at, @expires_at,+ CASE WHEN @state::text IN ('exited', 'stopped') THEN now() END+)+ON CONFLICT (task_id, local_key) DO UPDATE SET+ source = EXCLUDED.source,+ name = EXCLUDED.name,+ label = EXCLUDED.label,+ url = EXCLUDED.url,+ port = EXCLUDED.port,+ state = EXCLUDED.state,+ detail = EXCLUDED.detail,+ started_at = EXCLUDED.started_at,+ expires_at = EXCLUDED.expires_at,+ last_seen_at = now(),+ ended_at = CASE+ WHEN EXCLUDED.state IN ('exited', 'stopped') THEN COALESCE(issue_environment.ended_at, now())+ END,+ updated_at = now()+RETURNING *;++-- name: EndIssueEnvironmentsMissingFromSnapshot :exec+-- Environments the daemon no longer reports for the task have stopped. An+-- exited one keeps its state so the sidebar can still say it crashed.+UPDATE issue_environment+SET ended_at = now(),+ state = CASE WHEN state = 'exited' THEN 'exited' ELSE 'stopped' END,+ updated_at = now()+WHERE task_id = @task_id+ AND ended_at IS NULL+ AND NOT (local_key = ANY(@keep_keys::text[]));++-- name: ListIssueEnvironments :many+-- Live environments plus those that ended within the history window.+SELECT * FROM issue_environment+WHERE issue_id = @issue_id+ AND workspace_id = @workspace_id+ AND (ended_at IS NULL OR ended_at > @ended_after::timestamptz)+ORDER BY created_at DESC+LIMIT 50;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 3ecd9afea4..50a21a4e3b 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -508,6 +508,9 @@ deleted_app_action_requests AS (deleted_app_tool_calls AS (DELETE FROM app_tool_call WHERE workspace_id = $1),+deleted_issue_environments AS (+ DELETE FROM issue_environment WHERE workspace_id = $1+),deleted_workspace_app_settings AS (DELETE FROM workspace_app_setting WHERE workspace_id = $1),diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 1a1d9d62d4..bde3e6fc39 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -197,6 +197,10 @@ const (EventPullRequestUpdated = "pull_request:updated"EventPullRequestUnlinked = "pull_request:unlinked"+ // An issue's local environments changed: one started, stopped, changed+ // state, or its daemon stopped reporting it.+ EventEnvironmentChanged = "environment:changed"+// VCS integration events (Forgejo / Gitea / GitLab)EventVCSConnectionCreated = "vcs_connection:created"EventVCSConnectionDeleted = "vcs_connection:deleted"