Skip to content

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

Go

MUL-8923: feat(environments): stop, restart, start and read logs from the issue sidebar (#10330)

Jiayuan Zhang079ec9f676ff
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 9a8be67734..d729eb3f9f 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -326,7 +326,16 @@ describe("ApiClient issue environments response schema", () => {
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]);
+ expect(result.environments).toEqual([{
+ ...validEnvironment,
+ repo: "",
+ excerpt: "",
+ controllable: false,
+ can_control: false,
+ pending_action: null,
+ last_action: null,
+ origin: null,
+ }]);
});
it("drops a malformed environment and keeps the rest", async () => {
@@ -373,7 +382,7 @@ describe("ApiClient issue environments response schema", () => {
stubEnvironments({ environments: "nope" });
await expect(
new ApiClient("https://api.example.test").listIssueEnvironments("issue-1"),
- ).resolves.toEqual({ environments: [] });
+ ).resolves.toEqual({ environments: [], configs: [], pending_starts: [], failed_starts: [] });
});
});
@@ -3474,3 +3483,51 @@ describe("ApiClient complete issue deliverables", () => {
expect(await client.listIssueDeliverables("issue")).toEqual([]);
});
});
+
+describe("ApiClient issue environments", () => {
+ const env = {
+ id: "env-1", issue_id: "issue-1", task_id: "task-1", source: "config", name: "web",
+ state: "running", started_at: "2026-11-10T00:00:00Z", last_seen_at: "2026-11-10T00:00:00Z",
+ };
+
+ function stub(body: unknown) {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(body), {
+ status: 200, headers: { "Content-Type": "application/json" },
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+ }
+
+ it("reads an older server's environments as read-only", async () => {
+ stub({ environments: [env] });
+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");
+ expect(result.configs).toEqual([]);
+ expect(result.pending_starts).toEqual([]);
+ expect(result.failed_starts).toEqual([]);
+ expect(result.environments[0]).toMatchObject({
+ repo: "", excerpt: "", controllable: false, can_control: false, pending_action: null, last_action: null, origin: null,
+ });
+ });
+
+ it("drops an action record it cannot read without losing the environment", async () => {
+ stub({
+ environments: [{ ...env, controllable: true, can_control: true, pending_action: { id: "cmd-1", action: "teleport", created_at: "x" } }],
+ configs: [{ runtime_id: "rt-1", task_id: "task-1", reported_at: "x", environments: [{ repo: "app", name: "web" }] }, { bad: true }],
+ pending_starts: [{ id: "cmd-2", action: "start", status: "queued", created_at: "x" }],
+ failed_starts: [{ id: "cmd-4", action: "start", status: "expired", task_id: "task-1", created_at: "x" }, { id: "cmd-5" }],
+ });
+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");
+ expect(result.environments[0]).toMatchObject({ controllable: true, can_control: true, pending_action: null });
+ expect(result.configs).toEqual([{ runtime_id: "rt-1", task_id: "task-1", reported_at: "x", can_control: false, environments: [{ repo: "app", name: "web", label: "", start: "" }] }]);
+ expect(result.pending_starts[0]).toMatchObject({ id: "cmd-2", status: "failed" });
+ expect(result.failed_starts).toEqual([expect.objectContaining({ id: "cmd-4", status: "expired", task_id: "task-1" })]);
+ });
+
+ it("posts a start with the run and environment it names", async () => {
+ const fetchMock = stub({ id: "cmd-3", action: "start", status: "pending", created_at: "x" });
+ const result = await new ApiClient("https://api.example.test").startIssueEnvironment("issue-1", { task_id: "task-1", repo: "app", name: "web" });
+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe("https://api.example.test/api/issues/issue-1/environments/start");
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({ task_id: "task-1", repo: "app", name: "web" });
+ expect(result).toMatchObject({ id: "cmd-3", status: "pending", output: null });
+ });
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 297decdfff..7f6abf40dc 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -187,6 +187,9 @@ import type {
PluginConfigRequest,
IssuePullRequestsResponse,
IssueEnvironmentsResponse,
+ IssueEnvironmentAction,
+ IssueEnvironmentCommand,
+ StartIssueEnvironmentRequest,
ListGitHubInstallationsResponse,
ListGitHubRepositoriesResponse,
GitHubConnectResponse,
@@ -495,6 +498,7 @@ import {
IssuePullRequestsResponseSchema,
EMPTY_ISSUE_ENVIRONMENTS_RESPONSE,
IssueEnvironmentsResponseSchema,
+ IssueEnvironmentCommandSchema,
ResourceLabelsResponseSchema,
EMPTY_LABEL,
EMPTY_LIST_LABELS_RESPONSE,
@@ -5282,6 +5286,42 @@ export class ApiClient {
);
}
+ /** Ask the environment's machine to stop it. Resolves once queued. */
+ async stopIssueEnvironment(issueId: string, environmentId: string): Promise<IssueEnvironmentCommand> {
+ return this.issueEnvironmentCommand(`/api/issues/${issueId}/environments/${environmentId}/stop`, "stop", { method: "POST" });
+ }
+
+ /** Ask the environment's machine to start it again from the same code. */
+ async restartIssueEnvironment(issueId: string, environmentId: string): Promise<IssueEnvironmentCommand> {
+ return this.issueEnvironmentCommand(`/api/issues/${issueId}/environments/${environmentId}/restart`, "restart", { method: "POST" });
+ }
+
+ /** Ask the environment's machine for the end of its log; poll the command for it. */
+ async readIssueEnvironmentLogs(issueId: string, environmentId: string): Promise<IssueEnvironmentCommand> {
+ return this.issueEnvironmentCommand(`/api/issues/${issueId}/environments/${environmentId}/logs`, "logs", { method: "POST" });
+ }
+
+ /** Start an environment the latest run on a machine declared. */
+ async startIssueEnvironment(issueId: string, body: StartIssueEnvironmentRequest): Promise<IssueEnvironmentCommand> {
+ return this.issueEnvironmentCommand(`/api/issues/${issueId}/environments/start`, "start", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ }
+
+ async getIssueEnvironmentCommand(issueId: string, commandId: string): Promise<IssueEnvironmentCommand> {
+ return this.issueEnvironmentCommand(`/api/issues/${issueId}/environment-commands/${commandId}`, "logs");
+ }
+
+ private async issueEnvironmentCommand(path: string, action: IssueEnvironmentAction, init?: RequestInit): Promise<IssueEnvironmentCommand> {
+ const raw = await this.fetch<unknown>(path, init);
+ const fallback: IssueEnvironmentCommand = {
+ id: "", action, status: "failed", error: "", environment_id: null, runtime_id: "", task_id: null, repo: "", name: "",
+ actor_type: "member", actor_id: null, created_at: new Date().toISOString(), completed_at: null, output: null,
+ };
+ return parseWithFallback(raw, IssueEnvironmentCommandSchema, fallback, { endpoint: `${init?.method ?? "GET"} ${path.replace(/[0-9a-f-]{36}/g, ":id")}` });
+ }
+
/** 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.ts
index e44d6891d1..b043ea930a 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -466,6 +466,30 @@ export const EMPTY_ISSUE_PULL_REQUESTS_RESPONSE: IssuePullRequestsResponse = {
auto_complete: null,
};
+// An action record from a newer server with an unknown action is dropped;
+// an unknown status reads as failed, which offers a retry.
+export const IssueEnvironmentActionSchema = z.object({
+ id: z.string(),
+ action: z.enum(["stop", "restart", "start", "logs"]),
+ status: z.enum(["pending", "succeeded", "failed", "expired"]).catch("failed"),
+ error: z.string().optional().default(""),
+ environment_id: z.string().nullable().optional().default(null),
+ runtime_id: z.string().optional().default(""),
+ task_id: z.string().nullable().optional().default(null),
+ repo: z.string().optional().default(""),
+ name: z.string().optional().default(""),
+ actor_type: z.string().optional().default("member"),
+ actor_id: z.string().nullable().optional().default(null),
+ created_at: z.string(),
+ completed_at: z.string().nullable().optional().default(null),
+}).loose();
+
+const OptionalIssueEnvironmentActionSchema = IssueEnvironmentActionSchema.nullable().optional().default(null).catch(null);
+
+export const IssueEnvironmentCommandSchema = IssueEnvironmentActionSchema.extend({
+ output: z.string().nullable().optional().default(null),
+}).loose();
+
// 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. A kind this client does not know,
@@ -481,32 +505,66 @@ export const IssueEnvironmentSchema = z.object({
local_key: z.string().catch(""),
source: z.enum(["config", "detected"]).catch("detected"),
kind: z.enum(["server", "app"]).catch("server"),
+ repo: z.string().optional().default(""),
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(""),
+ excerpt: 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),
+ // Older servers predate sidebar control: everything reads as read-only.
+ controllable: z.boolean().optional().default(false),
+ can_control: z.boolean().optional().default(false),
+ pending_action: OptionalIssueEnvironmentActionSchema,
+ last_action: OptionalIssueEnvironmentActionSchema,
+ origin: OptionalIssueEnvironmentActionSchema,
}).loose();
-export const IssueEnvironmentsResponseSchema = z.object({
- environments: z
+const DeclaredEnvironmentSchema = z.object({
+ repo: z.string(),
+ name: z.string(),
+ label: z.string().optional().default(""),
+ start: z.string().optional().default(""),
+}).loose();
+
+const IssueEnvironmentConfigSchema = z.object({
+ runtime_id: z.string(),
+ task_id: z.string(),
+ reported_at: z.string(),
+ can_control: z.boolean().optional().default(false),
+ environments: z.array(DeclaredEnvironmentSchema).default([]),
+}).loose();
+
+function lenientArray<T extends z.ZodType>(schema: T) {
+ return z
.array(z.unknown())
+ .optional()
.default([])
.transform((items) =>
items.flatMap((item) => {
- const parsed = IssueEnvironmentSchema.safeParse(item);
- return parsed.success ? [parsed.data] : [];
+ const parsed = schema.safeParse(item);
+ return parsed.success ? [parsed.data as z.infer<T>] : [];
}),
- ),
+ );
+}
+
+export const IssueEnvironmentsResponseSchema = z.object({
+ environments: lenientArray(IssueEnvironmentSchema),
+ configs: lenientArray(IssueEnvironmentConfigSchema),
+ pending_starts: lenientArray(IssueEnvironmentActionSchema),
+ failed_starts: lenientArray(IssueEnvironmentActionSchema),
}).loose();
export const EMPTY_ISSUE_ENVIRONMENTS_RESPONSE: IssueEnvironmentsResponse = {
environments: [],
+ configs: [],
+ pending_starts: [],
+ failed_starts: [],
};
// Label responses are consumed by settings tables and resource pickers. Keep
diff --git a/packages/core/issues/environments.ts b/packages/core/issues/environments.ts
new file mode 100644
index 0000000000..dff62eda81
--- /dev/null
+++ b/packages/core/issues/environments.ts
@@ -0,0 +1,44 @@
+import { queryOptions, useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { useWorkspaceId } from "../hooks";
+import type { IssueEnvironmentCommand, StartIssueEnvironmentRequest } from "../types";
+import { issueKeys } from "./queries";
+
+export const environmentCommandKeys = {
+ command: (issueId: string, commandId: string) =>
+ ["issues", "environment-commands", issueId, commandId] as const,
+};
+
+/** A command the machine has not answered yet; polled until it has. */
+export function issueEnvironmentCommandOptions(issueId: string, commandId: string | null) {
+ return queryOptions({
+ queryKey: environmentCommandKeys.command(issueId, commandId ?? ""),
+ queryFn: () => api.getIssueEnvironmentCommand(issueId, commandId!),
+ enabled: !!issueId && !!commandId,
+ refetchInterval: (query) => (query.state.data?.status === "pending" ? 1_000 : false),
+ staleTime: Infinity,
+ });
+}
+
+export type IssueEnvironmentControl =
+ | { action: "stop" | "restart"; environmentId: string }
+ | { action: "start"; body: StartIssueEnvironmentRequest };
+
+/** Stops, restarts or starts an environment; the list refetches to show it pending. */
+export function useControlIssueEnvironment(issueId: string) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (control: IssueEnvironmentControl): Promise<IssueEnvironmentCommand> => {
+ switch (control.action) {
+ case "stop":
+ return api.stopIssueEnvironment(issueId, control.environmentId);
+ case "restart":
+ return api.restartIssueEnvironment(issueId, control.environmentId);
+ case "start":
+ return api.startIssueEnvironment(issueId, control.body);
+ }
+ },
+ onSettled: () => qc.invalidateQueries({ queryKey: issueKeys.environments(wsId, issueId) }),
+ });
+}
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index d73c8f4caa..cadb399688 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -706,13 +706,21 @@ export function issueSubscribersOptions(issueId: string) {
}
// Reports arrive over realtime; the interval only re-derives "unreachable"
-// once a daemon goes quiet, which no event announces.
+// once a daemon goes quiet, and a command expiring when its machine never
+// answers, 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,
+ refetchInterval: (query) => {
+ const data = query.state.data;
+ const pending = !!data && (
+ data.pending_starts.length > 0 ||
+ data.environments.some((env) => env.pending_action?.status === "pending")
+ );
+ return pending ? 5_000 : 60_000;
+ },
});
}
diff --git a/packages/core/package.json b/packages/core/package.json
index f48a99179b..3e68004c4d 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -46,6 +46,7 @@
"./issues/canonical-id": "./issues/canonical-id.ts",
"./issues/queries": "./issues/queries.ts",
"./issues/wakeups": "./issues/wakeups.ts",
+ "./issues/environments": "./issues/environments.ts",
"./issues/mutations": "./issues/mutations.ts",
"./issues/timeline-sort": "./issues/timeline-sort.ts",
"./issues/comment-thread": "./issues/comment-thread.ts",
diff --git a/packages/core/types/environment.ts b/packages/core/types/environment.ts
index f056e1bf54..6ddb163be4 100644
--- a/packages/core/types/environment.ts
+++ b/packages/core/types/environment.ts
@@ -11,6 +11,35 @@ export type IssueEnvironmentKind = "server" | "app";
* live environment has gone quiet. */
export type IssueEnvironmentState = "starting" | "running" | "exited" | "stopped" | "unreachable";
+export type IssueEnvironmentAction = "stop" | "restart" | "start" | "logs";
+
+/** `pending` covers both queued and claimed; `expired` means the machine never
+ * answered in time. */
+export type IssueEnvironmentActionStatus = "pending" | "succeeded" | "failed" | "expired";
+
+/** A stop, restart, start or log read a member asked a machine to perform. */
+export interface IssueEnvironmentActionRecord {
+ id: string;
+ action: IssueEnvironmentAction;
+ status: IssueEnvironmentActionStatus;
+ error: string;
+ environment_id: string | null;
+ runtime_id: string;
+ /** The run a start was asked of. */
+ task_id: string | null;
+ repo: string;
+ name: string;
+ actor_type: string;
+ actor_id: string | null;
+ created_at: string;
+ completed_at: string | null;
+}
+
+export interface IssueEnvironmentCommand extends IssueEnvironmentActionRecord {
+ /** The log a `logs` command read, once it succeeded. */
+ output: string | null;
+}
+
export interface IssueEnvironment {
id: string;
issue_id: string;
@@ -21,18 +50,60 @@ export interface IssueEnvironment {
local_key: string;
source: IssueEnvironmentSource;
kind: IssueEnvironmentKind;
+ /** The checkout a declared environment runs from; empty for detected ones
+ * and from older daemons. */
+ repo: string;
name: string;
label: string;
url: string;
port: number | null;
state: IssueEnvironmentState;
detail: string;
+ /** The last lines a crashed environment printed, redacted by the server. */
+ excerpt: string;
started_at: string;
expires_at: string | null;
last_seen_at: string;
ended_at: string | null;
+ /** Reported by a daemon that carries out sidebar commands. */
+ controllable: boolean;
+ /** The caller may stop or restart it. */
+ can_control: boolean;
+ pending_action: IssueEnvironmentActionRecord | null;
+ last_action: IssueEnvironmentActionRecord | null;
+ /** The sidebar start or restart that created this environment. */
+ origin: IssueEnvironmentActionRecord | null;
+}
+
+/** One environment a repository declares, as the start menu offers it. */
+export interface DeclaredEnvironment {
+ repo: string;
+ name: string;
+ label: string;
+ start: string;
+}
+
+/** What the latest run on one machine declared. */
+export interface IssueEnvironmentConfig {
+ runtime_id: string;
+ task_id: string;
+ reported_at: string;
+ can_control: boolean;
+ environments: DeclaredEnvironment[];
}
export interface IssueEnvironmentsResponse {
environments: IssueEnvironment[];
+ configs: IssueEnvironmentConfig[];
+ /** Sidebar starts whose environment has not been reported yet. */
+ pending_starts: IssueEnvironmentActionRecord[];
+ /** Recent sidebar starts that failed or were never answered, and have not
+ * been tried again since. */
+ failed_starts: IssueEnvironmentActionRecord[];
+}
+
+export interface StartIssueEnvironmentRequest {
+ task_id: string;
+ repo: string;
+ name: string;
}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 1a22191c6f..28206b8043 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -236,11 +236,18 @@ export type {
GitHubConnectResponse,
} from "./github";
export type {
+ DeclaredEnvironment,
IssueEnvironment,
+ IssueEnvironmentAction,
+ IssueEnvironmentActionRecord,
+ IssueEnvironmentActionStatus,
+ IssueEnvironmentCommand,
+ IssueEnvironmentConfig,
IssueEnvironmentSource,
IssueEnvironmentKind,
IssueEnvironmentState,
IssueEnvironmentsResponse,
+ StartIssueEnvironmentRequest,
} from "./environment";
export type {
VCSProvider,
diff --git a/packages/views/issues/components/environment-log-dialog.tsx b/packages/views/issues/components/environment-log-dialog.tsx
new file mode 100644
index 0000000000..f3cbc23201
--- /dev/null
+++ b/packages/views/issues/components/environment-log-dialog.tsx
@@ -0,0 +1,258 @@
+"use client";
+
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { api } from "@multica/core/api";
+import { issueEnvironmentCommandOptions } from "@multica/core/issues/environments";
+import type { IssueEnvironment } from "@multica/core/types";
+import { ArrowDownToLine, Copy, RefreshCw, RotateCw, Search, Server, WrapText } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { Spinner } from "@multica/ui/components/ui/spinner";
+import { Toggle } from "@multica/ui/components/ui/toggle";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { cn } from "@multica/ui/lib/utils";
+import { useLocale, useT } from "../../i18n";
+import { classifyLogLines, environmentTitle, exitCode, isLive } from "./environment-model";
+
+const FOLLOW_INTERVAL = 5_000;
+
+const LEVEL_CLASS = {
+ error: "bg-destructive/10 text-destructive",
+ warn: "text-warning",
+} as const;
+
+interface LogSnapshot {
+ output: string;
+ readAt: string;
+}
+
+/**
+ * The end of a declared environment's log, read from its machine on demand:
+ * the machine answers a log command with at most 500 lines (256 KB), and the
+ * dialog keeps re-asking while the environment runs and "follow" is on. An
+ * offline machine cannot answer, so the dialog falls back to the lines the
+ * environment printed before it crashed, when there are any.
+ */
+export function EnvironmentLogDialog({
+ issueId,
+ env,
+ open,
+ onOpenChange,
+ machineTitle,
+ originLabel,
+ offline,
+ canRestart,
+ onRestart,
+}: {
+ issueId: string;
+ env: IssueEnvironment;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ machineTitle: string | null;
+ originLabel: string | null;
+ offline: boolean;
+ canRestart: boolean;
+ onRestart: () => void;
+}) {
+ const { t } = useT("issues");
+ const locale = useLocale();
+ const [commandId, setCommandId] = useState<string | null>(null);
+ const [snapshot, setSnapshot] = useState<LogSnapshot | null>(null);
+ const [failed, setFailed] = useState<string | null>(null);
+ const [filter, setFilter] = useState("");
+ const [wrap, setWrap] = useState(true);
+ const [follow, setFollow] = useState(true);
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const live = isLive(env);
+
+ const request = useMutation({
+ mutationFn: () => api.readIssueEnvironmentLogs(issueId, env.id),
+ onSuccess: (command) => {
+ setFailed(null);
+ setCommandId(command.id || null);
+ },
+ onError: (error) => setFailed(error instanceof Error ? error.message : String(error)),
+ });
+ const { data: command } = useQuery(issueEnvironmentCommandOptions(issueId, commandId));
+ const reading = request.isPending || command?.status === "pending";
+
+ useEffect(() => {
+ if (!command || command.id !== commandId) return;
+ if (command.status === "succeeded") {
+ setSnapshot({ output: command.output ?? "", readAt: command.completed_at ?? new Date().toISOString() });
+ setFailed(null);
+ } else if (command.status === "failed" || command.status === "expired") {
+ setFailed(command.error || t(($) => $.environments.log.no_response));
+ }
+ }, [command, commandId, t]);
+
+ const refresh = request.mutate;
+ useEffect(() => {
+ if (open && !offline) refresh();
+ }, [open, offline, refresh]);
+
+ useEffect(() => {
+ if (!open || offline || !live || !follow || reading || failed) return;
+ const timer = setTimeout(() => refresh(), FOLLOW_INTERVAL);
+ return () => clearTimeout(timer);
+ }, [open, offline, live, follow, reading, failed, refresh, snapshot]);
+
+ const lines = useMemo(() => {
+ const text = offline ? env.excerpt : snapshot?.output ?? "";
+ return text ? text.replace(/\n$/, "").split("\n") : [];
+ }, [offline, env.excerpt, snapshot]);
+ const levels = useMemo(() => classifyLogLines(lines), [lines]);
+ const visible = useMemo(() => {
+ const needle = filter.trim().toLowerCase();
+ return lines
+ .map((text, index) => ({ text, index, level: levels[index] ?? null }))
+ .filter((line) => !needle || line.text.toLowerCase().includes(needle));
+ }, [lines, levels, filter]);
+
+ useLayoutEffect(() => {
+ if (!follow || !bodyRef.current) return;
+ bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
+ }, [follow, visible]);
+
+ const timeOf = (iso: string, seconds: boolean) =>
+ new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", ...(seconds ? { second: "2-digit" } : {}), hour12: false }).format(new Date(iso));
+
+ const code = exitCode(env);
+ const meta = [
+ code !== null && code !== 0 ? t(($) => $.environments.exit_code, { code }) : null,
+ machineTitle,
+ originLabel,
+ ].filter(Boolean).join(" · ");
+
+ let divider: string | null = null;
+ if (env.ended_at && !filter) {
+ const at = timeOf(env.ended_at, true);
+ if (env.state === "stopped") divider = t(($) => $.environments.log.stopped_divider, { time: at });
+ else if (code !== null && code !== 0) divider = t(($) => $.environments.log.exit_divider_code, { time: at, code });
+ else divider = t(($) => $.environments.log.exit_divider, { time: at });
+ }
+
+ const copyLog = () => {
+ const text = visible.map((line) => line.text).join("\n");
+ void copyText(text).then((ok) => {
+ if (ok) toast.success(t(($) => $.environments.log.copied));
+ else toast.error(t(($) => $.environments.log.copy_failed));
+ });
+ };
+
+ let empty: string | null = null;
+ if (lines.length === 0) {
+ if (offline) empty = t(($) => $.environments.log.offline_empty);
+ else if (failed) empty = null;
+ else if (!snapshot) empty = t(($) => $.environments.log.loading);
+ else empty = t(($) => $.environments.log.empty);
+ } else if (visible.length === 0) {
+ empty = t(($) => $.environments.log.no_match);
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex h-[min(640px,calc(100dvh-4rem))] flex-col gap-0 overflow-hidden p-0 sm:max-w-[880px]">
+ <div className="border-b px-4 pt-4 pb-3 pr-12">
+ <DialogTitle className="flex min-w-0 items-center gap-2 text-body font-medium">
+ <Server className={cn("size-4 shrink-0", env.state === "exited" ? "text-destructive" : "text-muted-foreground")} />
+ <span className="truncate">{t(($) => $.environments.log.title, { name: environmentTitle(env) })}</span>
+ </DialogTitle>
+ <DialogDescription className="mt-1 flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">
+ <span className={cn("shrink-0", env.state === "exited" ? "text-destructive" : env.state === "running" ? "text-success" : undefined)}>
+ {t(($) => $.environments.state[env.state])}
+ </span>
+ {meta && <span aria-hidden="true">·</span>}
+ {meta && <span className="min-w-0 truncate">{meta}</span>}
+ </DialogDescription>
+ </div>
+
+ <div className="flex items-center gap-2 border-b px-4 py-2">
+ <div className="relative w-56">
+ <Search aria-hidden="true" className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ placeholder={t(($) => $.environments.log.filter)}
+ aria-label={t(($) => $.environments.log.filter)}
+ className="h-7 pl-7 text-caption"
+ />
+ </div>
+ <Toggle size="sm" pressed={wrap} onPressedChange={setWrap} aria-label={t(($) => $.environments.log.wrap)}>
+ <WrapText className="size-3.5" />
+ {t(($) => $.environments.log.wrap)}
+ </Toggle>
+ {live && !offline && (
+ <Toggle size="sm" pressed={follow} onPressedChange={setFollow} aria-label={t(($) => $.environments.log.follow)}>
+ <ArrowDownToLine className="size-3.5" />
+ {t(($) => $.environments.log.follow)}
+ </Toggle>
+ )}
+ <div className="flex-1" />
+ <Button variant="ghost" size="sm" onClick={copyLog} disabled={visible.length === 0}>
+ <Copy className="size-3.5" />
+ {t(($) => $.environments.log.copy)}
+ </Button>
+ </div>
+
+ {offline && (
+ <p className="border-b bg-muted/50 px-4 py-2 text-caption text-muted-foreground">
+ {env.excerpt ? t(($) => $.environments.log.offline_excerpt) : t(($) => $.environments.offline_hint)}
+ </p>
+ )}
+ {failed && !offline && (
+ <p role="alert" className="border-b bg-destructive/10 px-4 py-2 text-caption text-destructive">
+ {t(($) => $.environments.log.failed, { error: failed })}
+ </p>
+ )}
+
+ <div
+ ref={bodyRef}
+ data-testid="environment-log"
+ onWheel={(event) => {
+ if (event.deltaY < 0 && follow) setFollow(false);
+ }}
+ className="min-h-0 flex-1 overflow-auto py-2 font-mono text-caption leading-5"
+ >
+ {visible.map((line) => (
+ <div key={line.index} data-level={line.level ?? undefined} className={cn("flex px-4", line.level && LEVEL_CLASS[line.level])}>
+ <span aria-hidden="true" className="w-10 shrink-0 pr-3 text-right text-faint-foreground tabular-nums select-none">{line.index + 1}</span>
+ <span className={cn("min-w-0 flex-1", wrap ? "whitespace-pre-wrap break-all" : "whitespace-pre")}>{line.text || " "}</span>
+ </div>
+ ))}
+ {empty && <p className="px-4 py-6 text-center text-caption text-muted-foreground">{empty}</p>}
+ {divider && lines.length > 0 && (
+ <div className="mx-4 my-2 flex items-center gap-3 text-micro text-muted-foreground">
+ <span className="h-px flex-1 bg-border" />
+ <span>{divider}</span>
+ <span className="h-px flex-1 bg-border" />
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2 border-t px-4 py-3">
+ <p className="min-w-0 flex-1 truncate text-caption text-muted-foreground tabular-nums">
+ {snapshot && !offline
+ ? t(($) => $.environments.log.footer, { count: lines.length, time: timeOf(snapshot.readAt, false) })
+ : null}
+ </p>
+ {!offline && (
+ <Button variant="outline" size="sm" onClick={() => refresh()} disabled={reading}>
+ {reading ? <Spinner className="size-3.5" /> : <RefreshCw className="size-3.5" />}
+ {t(($) => $.environments.log.refresh)}
+ </Button>
+ )}
+ {canRestart && (
+ <Button size="sm" onClick={onRestart}>
+ <RotateCw className="size-3.5" />
+ {t(($) => $.environments.restart)}
+ </Button>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/issues/components/environment-model.ts b/packages/views/issues/components/environment-model.ts
new file mode 100644
index 0000000000..5220f8f0c9
--- /dev/null
+++ b/packages/views/issues/components/environment-model.ts
@@ -0,0 +1,124 @@
+import type { AgentTask, IssueEnvironment, IssueEnvironmentActionRecord } from "@multica/core/types";
+
+const DAY = 24 * 60 * 60_000;
+const RECENT_FAILURE = 10 * 60_000;
+
+/** Every localized "let the agent start it" instruction names this command,
+ * which is how the sidebar recognizes those runs whatever the reader's language. */
+export const ENVIRONMENT_START_MARKER = "multica env start";
+
+export const isLive = (env: IssueEnvironment) => env.ended_at === null;
+
+/** The exit code a daemon recorded as `exit status N`, if any. */
+export function exitCode(env: IssueEnvironment): number | null {
+ const match = /exit status (\d+)/.exec(env.detail);
+ return match ? Number(match[1]) : null;
+}
+
+/** A declared environment that crashed stays in the main list for a day, or
+ * until it is restarted or another one with its name starts on the machine. */
+/** Whether a reported environment is the one `repo` declares as `name` on a
+ * machine. Two repositories in one run may declare the same name; rows from
+ * daemons that predate reporting the repository match on the name alone. */
+export function isDeclaredAs(env: IssueEnvironment, runtimeId: string | null, repo: string, name: string): boolean {
+ return env.source === "config" && env.runtime_id === runtimeId && env.name === name && (env.repo === "" || env.repo === repo);
+}
+
+export function isPinnedCrash(env: IssueEnvironment, all: IssueEnvironment[], now: number): boolean {
+ if (env.source !== "config" || env.state !== "exited" || !env.ended_at) return false;
+ const code = exitCode(env);
+ if (code === 0 || (code === null && !env.excerpt)) return false;
+ const ended = new Date(env.ended_at).getTime();
+ if (now - ended > DAY) return false;
+ return !all.some((other) =>
+ other.id !== env.id &&
+ isDeclaredAs(other, env.runtime_id, env.repo, env.name) &&
+ new Date(other.started_at).getTime() >= ended,
+ );
+}
+
+/** The command the machine is still working on for this environment. */
+export function pendingAction(env: IssueEnvironment): IssueEnvironmentActionRecord | null {
+ return env.pending_action?.status === "pending" ? env.pending_action : null;
+}
+
+/** A stop or restart that failed or went unanswered in the last few minutes. */
+export function recentFailure(env: IssueEnvironment, now: number): ControlRecord | null {
+ const last = env.last_action;
+ if (!last || last.action === "logs" || (last.status !== "failed" && last.status !== "expired")) return null;
+ const at = new Date(last.completed_at ?? last.created_at).getTime();
+ return now - at <= RECENT_FAILURE ? { ...last, action: last.action } : null;
+}
+
+type ControlRecord = IssueEnvironmentActionRecord & { action: "stop" | "restart" | "start" };
+
+/** 1-based position of each run on the issue, oldest first. */
+export function runOrdinals(tasks: readonly AgentTask[]): Map<string, number> {
+ // Ids are time-ordered, which settles runs created in the same second.
+ const ordered = [...tasks].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id));
+ return new Map(ordered.map((task, index) => [task.id, index + 1]));
+}
+
+const ACTIVE_TASK_STATUSES = new Set<AgentTask["status"]>(["queued", "dispatched", "waiting_local_directory", "deferred", "running"]);
+
+export function isActiveTask(task: AgentTask): boolean {
+ return ACTIVE_TASK_STATUSES.has(task.status);
+}
+
+/** The agent run asked to start this issue's environment that is still under way. */
+export function preparingRun(tasks: readonly AgentTask[], requestedCommentIds: ReadonlySet<string>): AgentTask | null {
+ return tasks.find((task) =>
+ isActiveTask(task) && (
+ (task.trigger_comment_id !== undefined && requestedCommentIds.has(task.trigger_comment_id)) ||
+ (task.trigger_summary ?? "").includes(ENVIRONMENT_START_MARKER)
+ ),
+ ) ?? null;
+}
+
+export type LogLevel = "error" | "warn" | null;
+
+/** Colors a log the way a reader scans it: errors and the lines continuing
+ * them in red, warnings in yellow. */
+export function classifyLogLines(lines: readonly string[]): LogLevel[] {
+ const levels: LogLevel[] = [];
+ let previous: LogLevel = null;
+ for (const line of lines) {
+ let level: LogLevel = null;
+ if (/\b(ERROR|ERR|FATAL|PANIC)\b|^(panic|fatal error|error|Error)\b|\*\*\*.*\bError\b/.test(line)) {
+ level = "error";
+ } else if (/\b(WARN|WARNING)\b/.test(line)) {
+ level = "warn";
+ } else if (previous === "error" && /^\s+\S/.test(line)) {
+ level = "error";
+ }
+ levels.push(level);
+ previous = level;
+ }
+ return levels;
+}
+
+export 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;
+ }
+}
+
+export 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;
+ }
+}
+
+/** The environment's name as rows, menus and dialogs show it. */
+export function environmentTitle(env: IssueEnvironment): string {
+ const app = env.kind === "app";
+ const host = !app && env.url ? displayHost(env.url) : null;
+ return app || env.source === "config" ? env.label || env.name : host ?? env.name;
+}
diff --git a/packages/views/issues/components/environment-start-menu.tsx b/packages/views/issues/components/environment-start-menu.tsx
new file mode 100644
index 0000000000..11ba671a54
--- /dev/null
+++ b/packages/views/issues/components/environment-start-menu.tsx
@@ -0,0 +1,153 @@
+"use client";
+
+import { Fragment } from "react";
+import type { Agent, DeclaredEnvironment, IssueEnvironmentConfig } from "@multica/core/types";
+import { Bot, Plus, Server } from "@multica/ui/icons";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { useT } from "../../i18n";
+
+export type DeclaredState = "available" | "running" | "starting";
+
+export interface StartMenuMachine {
+ title: string;
+ offline: boolean;
+}
+
+const NOTE_CLASS = "px-2 py-1.5 text-caption text-muted-foreground";
+
+/**
+ * The section's "+": every environment the latest run on each machine
+ * declared, started from that run's code, and a way to have an agent prepare
+ * the code and start it when there is nothing to start directly.
+ */
+export function EnvironmentStartMenu({
+ configs,
+ machineFor,
+ runLabel,
+ declaredState,
+ onStart,
+ agent,
+ agentChoices,
+ preparing,
+ onAskAgent,
+}: {
+ configs: IssueEnvironmentConfig[];
+ machineFor: (runtimeId: string) => StartMenuMachine;
+ runLabel: (taskId: string) => string | null;
+ declaredState: (config: IssueEnvironmentConfig, declared: DeclaredEnvironment) => DeclaredState;
+ onStart: (config: IssueEnvironmentConfig, declared: DeclaredEnvironment) => void;
+ /** Who the start goes to; null lets the reader pick from `agentChoices`. */
+ agent: Agent | null;
+ agentChoices: Agent[];
+ preparing: boolean;
+ onAskAgent: (agent: Agent) => void;
+}) {
+ const { t } = useT("issues");
+ const declaring = configs.filter((config) => config.environments.length > 0);
+ const askLabel = agent
+ ? t(($) => $.environments.start_menu.ask_agent, { name: agent.name })
+ : t(($) => $.environments.start_menu.ask_any_agent);
+ const askSide = preparing ? t(($) => $.environments.start_menu.preparing) : t(($) => $.environments.start_menu.new_run);
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton variant="ghost" size="icon-xs" label={t(($) => $.environments.start_menu.trigger)}>
+ <Plus />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-80 max-w-(--available-width)">
+ {declaring.map((config, index) => {
+ const machine = machineFor(config.runtime_id);
+ const run = runLabel(config.task_id);
+ return (
+ <Fragment key={config.runtime_id}>
+ {index > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="flex min-w-0 items-center gap-1.5">
+ <span className="min-w-0 truncate">{run ? `${machine.title} · ${run}` : machine.title}</span>
+ {machine.offline && (
+ <span className="shrink-0 rounded-xs bg-warning/10 px-1 text-micro font-medium text-warning">{t(($) => $.environments.offline)}</span>
+ )}
+ </DropdownMenuLabel>
+ {config.environments.map((declared) => {
+ const state = declaredState(config, declared);
+ const disabled = state !== "available" || machine.offline || !config.can_control;
+ return (
+ <DropdownMenuItem
+ key={`${declared.repo}/${declared.name}`}
+ disabled={disabled}
+ onClick={() => onStart(config, declared)}
+ >
+ <Server className="text-muted-foreground" />
+ <span className="min-w-0 truncate">{declared.label || declared.name}</span>
+ <span className="ml-auto max-w-[50%] shrink-0 truncate pl-3 text-caption text-muted-foreground">
+ {state === "running"
+ ? t(($) => $.environments.state.running)
+ : state === "starting"
+ ? t(($) => $.environments.state.starting)
+ : <code className="font-mono">{declared.start}</code>}
+ </span>
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuGroup>
+ </Fragment>
+ );
+ })}
+ {declaring.length > 0 ? (
+ <p className={NOTE_CLASS}>
+ {declaring.some((config) => !config.can_control)
+ ? t(($) => $.environments.start_menu.no_permission)
+ : t(($) => $.environments.start_menu.note)}
+ </p>
+ ) : configs.length === 0 ? (
+ <p className={NOTE_CLASS}>{t(($) => $.environments.start_menu.nothing_to_start)}</p>
+ ) : null}
+ {(declaring.length > 0 || configs.length === 0) && <DropdownMenuSeparator />}
+ {agent ? (
+ <DropdownMenuItem disabled={preparing} onClick={() => onAskAgent(agent)}>
+ <Bot className="text-muted-foreground" />
+ <span className="min-w-0 truncate">{askLabel}</span>
+ <span className="ml-auto shrink-0 pl-3 text-caption text-muted-foreground">{askSide}</span>
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger disabled={preparing || agentChoices.length === 0}>
+ <Bot className="text-muted-foreground" />
+ <span className="min-w-0 truncate">{askLabel}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-56">
+ {agentChoices.map((choice) => (
+ <DropdownMenuItem key={choice.id} onClick={() => onAskAgent(choice)}>
+ <span className="min-w-0 truncate">{choice.name}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ {declaring.length === 0 && (
+ <p className={NOTE_CLASS}>
+ {agent
+ ? t(($) => $.environments.start_menu.ask_agent_hint, { name: agent.name })
+ : t(($) => $.environments.start_menu.ask_any_agent_hint)}
+ </p>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index b9d731bc10..a5e3f03635 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -463,6 +463,17 @@ function formatActivity(
return t(($) => $.activity.squad_leader_evaluated);
}
}
+ case "environment_controlled": {
+ const name = details.label || details.name || "?";
+ switch (details.action) {
+ case "stop":
+ return t(($) => $.activity.environment_stopped, { name });
+ case "restart":
+ return t(($) => $.activity.environment_restarted, { name });
+ default:
+ return t(($) => $.activity.environment_started, { name });
+ }
+ }
default:
return entry.action ?? "";
}
@@ -3242,8 +3253,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
/>
)}
- {/* Environments the issue's runs left running. Hidden until one starts. */}
- <IssueEnvironmentsSection issueId={id} />
+ {/* Environments the issue's runs left running, and the "+" that starts one. */}
+ <IssueEnvironmentsSection issueId={id} assigneeType={issue.assignee_type} assigneeId={issue.assignee_id} />
{/* Deliverables — the files this issue's comments delivered. Hidden
while there are none. */}
diff --git a/packages/views/issues/components/issue-environments-section.test.tsx b/packages/views/issues/components/issue-environments-section.test.tsx
index 464d474d8e..99b25566bc 100644
--- a/packages/views/issues/components/issue-environments-section.test.tsx
+++ b/packages/views/issues/components/issue-environments-section.test.tsx
@@ -2,21 +2,37 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, 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 type {
+ Agent,
+ AgentRuntime,
+ AgentTask,
+ IssueEnvironment,
+ IssueEnvironmentActionRecord,
+ IssueEnvironmentConfig,
+} 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 mockConfigs: IssueEnvironmentConfig[] = [];
+let mockPendingStarts: IssueEnvironmentActionRecord[] = [];
+let mockFailedStarts: IssueEnvironmentActionRecord[] = [];
let mockRuntimes: AgentRuntime[] = [];
+let mockTasks: AgentTask[] = [];
+let mockAgents: Agent[] = [];
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 }),
+ queryFn: async () => ({ environments: mockEnvironments, configs: mockConfigs, pending_starts: mockPendingStarts, failed_starts: mockFailedStarts }),
+ }),
+ issueTasksOptions: (issueId: string) => ({
+ queryKey: ["issues", "tasks", issueId],
+ queryFn: async () => mockTasks,
}),
}));
vi.mock("@multica/core/runtimes/queries", async (importOriginal) => ({
@@ -26,6 +42,19 @@ vi.mock("@multica/core/runtimes/queries", async (importOriginal) => ({
queryFn: async () => mockRuntimes,
}),
}));
+vi.mock("@multica/core/workspace/queries", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/workspace/queries")>()),
+ agentListOptions: (wsId: string) => ({
+ queryKey: ["workspaces", wsId, "agents"],
+ queryFn: async () => mockAgents,
+ }),
+}));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({
+ getActorName: (type: string, id: string) =>
+ type === "member" ? (id === "user-1" ? "Jiayuan" : "Unknown") : mockAgents.find((a) => a.id === id)?.name ?? "Unknown Agent",
+ }),
+}));
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" } }),
@@ -33,6 +62,20 @@ vi.mock("@multica/core/auth", () => ({
vi.mock("../../platform/use-local-daemon-status", () => ({
useLocalDaemonStatus: () => ({ daemonId: mockLocalDaemonId, deviceName: null, running: !!mockLocalDaemonId }),
}));
+const control = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/issues/environments", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/issues/environments")>()),
+ useControlIssueEnvironment: () => ({ mutate: control }),
+}));
+const createComment = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/issues/mutations", () => ({
+ useCreateComment: () => ({ mutate: createComment }),
+}));
+const apiMock = vi.hoisted(() => ({
+ readIssueEnvironmentLogs: vi.fn(),
+ getIssueEnvironmentCommand: vi.fn(),
+}));
+vi.mock("@multica/core/api", () => ({ api: apiMock }));
const copyText = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@multica/ui/lib/clipboard", () => ({ copyText }));
const toastError = vi.hoisted(() => vi.fn());
@@ -74,46 +117,107 @@ function environment(overrides: Partial<IssueEnvironment>): IssueEnvironment {
local_key: "config:abc",
source: "config",
kind: "server",
+ repo: "",
name: "web",
label: "Web app",
url: "http://localhost:41000",
port: 41000,
state: "running",
detail: "",
+ excerpt: "",
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,
+ controllable: true,
+ can_control: true,
+ pending_action: null,
+ last_action: null,
+ origin: null,
+ ...overrides,
+ };
+}
+
+function action(overrides: Partial<IssueEnvironmentActionRecord>): IssueEnvironmentActionRecord {
+ return {
+ id: "cmd-1",
+ action: "stop",
+ status: "pending",
+ error: "",
+ environment_id: "env-1",
+ runtime_id: "rt-1",
+ task_id: null,
+ repo: "app",
+ name: "web",
+ actor_type: "member",
+ actor_id: "user-1",
+ created_at: new Date().toISOString(),
+ completed_at: null,
...overrides,
};
}
-function renderSection() {
+function task(overrides: Partial<AgentTask>): AgentTask {
+ return {
+ id: "task-1",
+ agent_id: "agent-1",
+ runtime_id: "rt-1",
+ issue_id: "issue-1",
+ status: "completed",
+ priority: 0,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ result: null,
+ error: null,
+ created_at: new Date(Date.now() - 2 * HOUR).toISOString(),
+ ...overrides,
+ } as AgentTask;
+}
+
+const lambda = { id: "agent-1", name: "Lambda", archived_at: null } as Agent;
+
+function renderSection(props: { assigneeType?: "agent" | "member" | null; assigneeId?: string | null } = {}) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
<I18nProvider resources={TEST_RESOURCES} locale="en">
- <IssueEnvironmentsSection issueId="issue-1" />
+ <IssueEnvironmentsSection issueId="issue-1" {...props} />
</I18nProvider>
</QueryClientProvider>,
);
}
+async function openRowMenu(row: HTMLElement) {
+ fireEvent.click(within(row).getByRole("button", { name: "More actions" }));
+ return screen.findByRole("menu");
+}
+
describe("IssueEnvironmentsSection", () => {
beforeEach(() => {
mockEnvironments = [];
+ mockConfigs = [];
+ mockPendingStarts = [];
+ mockFailedStarts = [];
mockRuntimes = [runtime({}), runtime({ id: "rt-2", daemon_id: "daemon-2", name: "Codex (build-02)", device_info: "build-02" })];
+ mockTasks = [task({})];
+ mockAgents = [lambda];
mockLocalDaemonId = null;
copyText.mockClear();
toastError.mockClear();
focusEnvironment.mockReset();
delete (window as { daemonAPI?: unknown }).daemonAPI;
+ control.mockReset();
+ createComment.mockReset();
+ apiMock.readIssueEnvironmentLogs.mockReset();
+ apiMock.getIssueEnvironmentCommand.mockReset();
});
- it("renders nothing while the issue has no environments", async () => {
- const { container } = renderSection();
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(container).toBeEmptyDOMElement();
+ it("keeps the header and its start menu while the issue has no environments", async () => {
+ mockTasks = [];
+ renderSection();
+ expect(await screen.findByText("Environments")).toBeVisible();
+ expect(screen.queryByTestId("environment-row")).not.toBeInTheDocument();
});
it("groups live environments by machine and links the running ones", async () => {
@@ -158,7 +262,7 @@ describe("IssueEnvironmentsSection", () => {
expect(row("Docs")).not.toHaveAttribute("title");
});
- it("folds ended environments and shows why one exited", async () => {
+ it("keeps a crashed declared environment in view with its last lines", async () => {
mockEnvironments = [
environment({}),
environment({
@@ -167,20 +271,47 @@ describe("IssueEnvironmentsSection", () => {
label: "API",
state: "exited",
detail: "exit status 1",
+ excerpt: "ERROR failed to connect to database\ndial tcp [::1]:5432: connect: connection refused",
ended_at: new Date().toISOString(),
expires_at: null,
}),
];
renderSection();
+ const crashed = (await screen.findByText("API")).closest<HTMLElement>("[data-testid=environment-row]")!;
+ expect(within(crashed).getByText("Exited")).toBeVisible();
+ expect(within(crashed).getByText(/Exit code 1/)).toBeVisible();
+ expect(within(crashed).getByText("ERROR failed to connect to database")).toBeVisible();
+ expect(screen.queryByRole("button", { name: /ended/ })).not.toBeInTheDocument();
+
+ fireEvent.click(within(crashed).getByRole("button", { name: "Restart" }));
+ expect(control).toHaveBeenCalledWith({ action: "restart", environmentId: "env-3" }, expect.anything());
+ });
+
+ it("folds ended environments and says who stopped them", async () => {
+ mockEnvironments = [
+ environment({}),
+ environment({
+ id: "env-3",
+ name: "storybook",
+ label: "Storybook",
+ state: "stopped",
+ ended_at: new Date(Date.now() - 2 * HOUR).toISOString(),
+ expires_at: null,
+ last_action: action({ id: "cmd-9", environment_id: "env-3", status: "succeeded" }),
+ }),
+ ];
+ renderSection();
+
const fold = await screen.findByRole("button", { name: /1 ended/ });
- expect(screen.queryByText("API")).not.toBeInTheDocument();
+ expect(screen.queryByText("Storybook")).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]!;
+ const ended = screen.getByText("Storybook").closest<HTMLElement>("[data-testid=environment-row]")!;
+ expect(within(ended).getByText(/Stopped by Jiayuan/)).toBeVisible();
expect(within(ended).queryByRole("link")).not.toBeInTheDocument();
+
+ fireEvent.click(within(ended).getByRole("button", { name: "Restart" }));
+ expect(control).toHaveBeenCalledWith({ action: "restart", environmentId: "env-3" }, expect.anything());
});
describe("desktop apps", () => {
@@ -222,6 +353,21 @@ describe("IssueEnvironmentsSection", () => {
expect(toastError).not.toHaveBeenCalled();
});
+ it("keeps the controls of a desktop app the repository declares", async () => {
+ onDesktop();
+ focusEnvironment.mockResolvedValue({ ok: true });
+ mockEnvironments = [app({ id: "env-desktop", source: "config", local_key: "config:desktop", name: "desktop", label: "Desktop", repo: "app" })];
+ renderSection();
+
+ const row = await screen.findByTestId("environment-row");
+ fireEvent.click(within(row).getByRole("button", { name: "Switch to window" }));
+ await waitFor(() => expect(focusEnvironment).toHaveBeenCalledWith("config:desktop"));
+ const menu = await openRowMenu(row);
+ expect(within(menu).getByRole("menuitem", { name: /View logs/ })).not.toHaveAttribute("aria-disabled", "true");
+ fireEvent.click(within(menu).getByRole("menuitem", { name: /^Stop$/ }));
+ expect(control).toHaveBeenCalledWith({ action: "stop", environmentId: "env-desktop" }, expect.anything());
+ });
+
it("offers no switch for an app whose key did not arrive", async () => {
onDesktop();
mockEnvironments = [app({ local_key: "" })];
@@ -289,4 +435,226 @@ describe("IssueEnvironmentsSection", () => {
expect(within(row).queryByRole("link")).not.toBeInTheDocument();
expect(within(row).getByText(/Last seen/)).toBeVisible();
});
+
+ it("stops a declared environment from its menu and shows it pending", async () => {
+ mockEnvironments = [environment({})];
+ const { rerender } = renderSection();
+ const row = await screen.findByTestId("environment-row");
+ const menu = await openRowMenu(row);
+ expect(within(menu).getByText("Started by Lambda in the first run")).toBeInTheDocument();
+ fireEvent.click(within(menu).getByRole("menuitem", { name: "Stop" }));
+ expect(control).toHaveBeenCalledWith({ action: "stop", environmentId: "env-1" }, expect.anything());
+
+ mockEnvironments = [environment({ pending_action: action({}) })];
+ rerender(<></>);
+ renderSection();
+ const pending = await screen.findByText("Stopping");
+ const pendingRow = pending.closest<HTMLElement>("[data-testid=environment-row]")!;
+ expect(within(pendingRow).getByText("Waiting for the machine")).toBeVisible();
+ expect(within(pendingRow).queryByRole("link")).not.toBeInTheDocument();
+ });
+
+ it("says when the machine never answered", async () => {
+ mockEnvironments = [environment({ last_action: action({ status: "expired" }) })];
+ renderSection();
+ const row = await screen.findByTestId("environment-row");
+ expect(within(row).getByText("No response")).toBeVisible();
+ });
+
+ it("asks before stopping a detected service and offers no logs for it", async () => {
+ mockEnvironments = [
+ environment({ source: "detected", name: "vite", label: "", url: "http://localhost:5173", port: 5173, expires_at: null }),
+ ];
+ renderSection();
+ const menu = await openRowMenu(await screen.findByTestId("environment-row"));
+ expect(within(menu).getByText("Detected service · vite")).toBeInTheDocument();
+ expect(within(menu).getByRole("menuitem", { name: "View logs" })).toHaveAttribute("aria-disabled", "true");
+ fireEvent.click(within(menu).getByRole("menuitem", { name: "Stop…" }));
+
+ const dialog = await screen.findByRole("alertdialog");
+ expect(within(dialog).getByText("Stop localhost:5173?")).toBeVisible();
+ expect(control).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole("button", { name: "Stop" }));
+ expect(control).toHaveBeenCalledWith({ action: "stop", environmentId: "env-1" }, expect.anything());
+ });
+
+ it("disables every action while the machine is offline", async () => {
+ mockRuntimes = [runtime({ status: "offline" })];
+ mockEnvironments = [environment({ state: "unreachable" })];
+ renderSection();
+ await screen.findByText("Offline");
+ const menu = await openRowMenu(await screen.findByTestId("environment-row"));
+ expect(within(menu).getByText("Available once this machine is back online.")).toBeInTheDocument();
+ for (const name of ["View logs", "Restart", "Stop"]) {
+ expect(within(menu).getByRole("menuitem", { name })).toHaveAttribute("aria-disabled", "true");
+ }
+ });
+
+ it("leaves a member who cannot use the machine only the logs", async () => {
+ mockEnvironments = [environment({ can_control: false })];
+ renderSection();
+ const menu = await openRowMenu(await screen.findByTestId("environment-row"));
+ expect(within(menu).getByRole("menuitem", { name: "View logs" })).not.toHaveAttribute("aria-disabled");
+ expect(within(menu).queryByRole("menuitem", { name: "Restart" })).not.toBeInTheDocument();
+ expect(within(menu).queryByRole("menuitem", { name: "Stop" })).not.toBeInTheDocument();
+ expect(within(menu).getByText("Only members who can use this machine can stop or restart it.")).toBeInTheDocument();
+ });
+
+ it("reads the log from the machine and marks errors", async () => {
+ mockEnvironments = [environment({})];
+ apiMock.readIssueEnvironmentLogs.mockResolvedValue({ id: "log-1", status: "pending" });
+ apiMock.getIssueEnvironmentCommand.mockResolvedValue({
+ id: "log-1",
+ action: "logs",
+ status: "succeeded",
+ completed_at: new Date().toISOString(),
+ output: "> make server\nWARN database not ready\nERROR failed to connect\n err=\"dial tcp\"\ndone\n",
+ });
+ renderSection();
+ const menu = await openRowMenu(await screen.findByTestId("environment-row"));
+ fireEvent.click(within(menu).getByRole("menuitem", { name: "View logs" }));
+
+ const log = await screen.findByTestId("environment-log");
+ await waitFor(() => expect(within(log).getByText("ERROR failed to connect")).toBeInTheDocument());
+ expect(apiMock.readIssueEnvironmentLogs).toHaveBeenCalledWith("issue-1", "env-1");
+ const levelOf = (text: string) => within(log).getByText(text).closest("[data-level]")?.getAttribute("data-level") ?? null;
+ expect(levelOf("ERROR failed to connect")).toBe("error");
+ expect(levelOf("err=\"dial tcp\"", )).toBe("error");
+ expect(levelOf("WARN database not ready")).toBe("warn");
+ expect(levelOf("done")).toBeNull();
+ expect(screen.getByText(/Showing the last 5 lines/)).toBeInTheDocument();
+
+ fireEvent.change(screen.getByRole("textbox", { name: "Filter logs" }), { target: { value: "warn" } });
+ expect(within(log).queryByText("done")).not.toBeInTheDocument();
+ expect(within(log).getByText("WARN database not ready")).toBeInTheDocument();
+ });
+
+ it("starts a declared environment from the + menu", async () => {
+ mockConfigs = [{
+ runtime_id: "rt-1",
+ task_id: "task-1",
+ reported_at: new Date().toISOString(),
+ can_control: true,
+ environments: [
+ { repo: "app", name: "web", label: "Web app", start: "pnpm dev:web" },
+ { repo: "app", name: "api", label: "API", start: "make server" },
+ ],
+ }];
+ mockEnvironments = [environment({})];
+ renderSection();
+ await screen.findByTestId("environment-row");
+ fireEvent.click(screen.getByRole("button", { name: "Start an environment" }));
+ const menu = await screen.findByRole("menu");
+ expect(within(menu).getByText("studio.local · the first run")).toBeInTheDocument();
+ expect(within(menu).getByRole("menuitem", { name: /Web app/ })).toHaveAttribute("aria-disabled", "true");
+ expect(within(menu).getByText("make server")).toBeInTheDocument();
+ fireEvent.click(within(menu).getByRole("menuitem", { name: /API/ }));
+ expect(control).toHaveBeenCalledWith(
+ { action: "start", body: { task_id: "task-1", repo: "app", name: "api" } },
+ expect.anything(),
+ );
+ });
+
+ it("tells apart two repositories in one run that declare the same name", async () => {
+ mockConfigs = [{
+ runtime_id: "rt-1",
+ task_id: "task-1",
+ reported_at: new Date().toISOString(),
+ can_control: true,
+ environments: [
+ { repo: "app", name: "web", label: "App web", start: "pnpm dev:web" },
+ { repo: "docs", name: "web", label: "Docs web", start: "pnpm docs" },
+ ],
+ }];
+ mockEnvironments = [environment({ repo: "app", label: "App web" })];
+ mockPendingStarts = [];
+ renderSection();
+ await screen.findByTestId("environment-row");
+ fireEvent.click(screen.getByRole("button", { name: "Start an environment" }));
+ const menu = await screen.findByRole("menu");
+ expect(within(menu).getByRole("menuitem", { name: /App web/ })).toHaveAttribute("aria-disabled", "true");
+ const docs = within(menu).getByRole("menuitem", { name: /Docs web/ });
+ expect(docs).not.toHaveAttribute("aria-disabled", "true");
+ expect(within(docs).getByText("pnpm docs")).toBeInTheDocument();
+ fireEvent.click(docs);
+ expect(control).toHaveBeenCalledWith(
+ { action: "start", body: { task_id: "task-1", repo: "docs", name: "web" } },
+ expect.anything(),
+ );
+ });
+
+ it("keeps a start the machine accepted and then failed, with its reason and a retry", async () => {
+ mockConfigs = [{
+ runtime_id: "rt-1",
+ task_id: "task-2",
+ reported_at: new Date().toISOString(),
+ can_control: true,
+ environments: [{ repo: "app", name: "web", label: "Web app", start: "pnpm dev:web" }],
+ }];
+ mockFailedStarts = [action({
+ id: "cmd-9", action: "start", status: "failed", environment_id: null, task_id: "task-1",
+ error: "the run's checkout was cleaned up", completed_at: new Date().toISOString(),
+ })];
+ renderSection();
+ const row = await screen.findByTestId("environment-failed-start");
+ expect(within(row).getByText("Web app")).toBeVisible();
+ expect(within(row).getByText("Couldn't start")).toBeVisible();
+ expect(within(row).getByText(/the run's checkout was cleaned up/)).toBeVisible();
+ fireEvent.click(within(row).getByRole("button", { name: /Retry/ }));
+ expect(control).toHaveBeenCalledWith(
+ { action: "start", body: { task_id: "task-2", repo: "app", name: "web" } },
+ expect.anything(),
+ );
+ fireEvent.click(within(row).getByRole("button", { name: /Dismiss/ }));
+ await waitFor(() => expect(screen.queryByTestId("environment-failed-start")).not.toBeInTheDocument());
+ });
+
+ it("says when a start was never answered and lets it be retried", async () => {
+ mockFailedStarts = [action({ id: "cmd-10", action: "start", status: "expired", environment_id: null, task_id: "task-1" })];
+ renderSection();
+ const row = await screen.findByTestId("environment-failed-start");
+ expect(within(row).getByText("No response")).toBeVisible();
+ expect(within(row).getByText(/The machine didn't respond/)).toBeVisible();
+ fireEvent.click(within(row).getByRole("button", { name: /Retry/ }));
+ expect(control).toHaveBeenCalledWith(
+ { action: "start", body: { task_id: "task-1", repo: "app", name: "web" } },
+ expect.anything(),
+ );
+ });
+
+ it("drops a failed start once the environment came up another way", async () => {
+ mockFailedStarts = [action({
+ id: "cmd-11", action: "start", status: "failed", environment_id: null, task_id: "task-1",
+ created_at: new Date(Date.now() - 60_000).toISOString(),
+ })];
+ mockEnvironments = [environment({ repo: "app", started_at: new Date().toISOString() })];
+ renderSection();
+ await screen.findByTestId("environment-row");
+ expect(screen.queryByTestId("environment-failed-start")).not.toBeInTheDocument();
+ });
+
+ it("asks the agent to start it when nothing can be started directly", async () => {
+ mockTasks = [];
+ renderSection({ assigneeType: "agent", assigneeId: "agent-1" });
+ fireEvent.click(await screen.findByRole("button", { name: "Start an environment" }));
+ const menu = await screen.findByRole("menu");
+ expect(within(menu).getByText(/hasn't run yet/)).toBeInTheDocument();
+ fireEvent.click(within(menu).getByRole("menuitem", { name: /Ask Lambda to start it/ }));
+ expect(createComment).toHaveBeenCalledTimes(1);
+ const [{ content }] = createComment.mock.calls[0]!;
+ expect(content).toMatch(/^\[@Lambda\]\(mention:\/\/agent\/agent-1\) /);
+ expect(content).toContain("multica env start");
+ });
+
+ it("shows the agent preparing the environment while its run is under way", async () => {
+ mockTasks = [
+ task({}),
+ task({ id: "task-2", status: "running", created_at: new Date().toISOString(), trigger_summary: "@Lambda Start the environment: get this issue's code ready, then run multica env start" }),
+ ];
+ renderSection();
+ expect(await screen.findByText("Lambda is preparing the environment")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Start an environment" }));
+ const menu = await screen.findByRole("menu");
+ expect(within(menu).getByRole("menuitem", { name: /Ask Lambda to start it/ })).toHaveAttribute("aria-disabled", "true");
+ });
});
diff --git a/packages/views/issues/components/issue-environments-section.tsx b/packages/views/issues/components/issue-environments-section.tsx
index 9b7b1a0444..48261efe2a 100644
--- a/packages/views/issues/components/issue-environments-section.tsx
+++ b/packages/views/issues/components/issue-environments-section.tsx
@@ -1,55 +1,151 @@
"use client";
-import { useMemo, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
+import { useMemo, useState, type ReactNode } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
-import { AppWindow, ArrowUpRight, ChevronRight, Copy, ExternalLink, Globe, Laptop, Server } from "@multica/ui/icons";
+import {
+ AppWindow,
+ ArrowUpRight,
+ Bot,
+ ChevronRight,
+ Copy,
+ ExternalLink,
+ Globe,
+ Laptop,
+ MoreHorizontal,
+ RotateCw,
+ X,
+ ScrollText,
+ Server,
+ Square,
+ WifiOff,
+} from "@multica/ui/icons";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
-import { issueEnvironmentsOptions } from "@multica/core/issues/queries";
+import { useControlIssueEnvironment, type IssueEnvironmentControl } from "@multica/core/issues/environments";
+import { useCreateComment } from "@multica/core/issues/mutations";
+import { issueEnvironmentsOptions, issueKeys, issueTasksOptions } from "@multica/core/issues/queries";
import { runtimeListOptions } from "@multica/core/runtimes/queries";
-import type { IssueEnvironment, IssueEnvironmentState } from "@multica/core/types";
+import type {
+ Agent,
+ DeclaredEnvironment,
+ IssueAssigneeType,
+ IssueEnvironment,
+ IssueEnvironmentActionRecord,
+ IssueEnvironmentConfig,
+ IssueEnvironmentState,
+} from "@multica/core/types";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { agentListOptions } from "@multica/core/workspace/queries";
import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Spinner } from "@multica/ui/components/ui/spinner";
import { copyText } from "@multica/ui/lib/clipboard";
import { cn } from "@multica/ui/lib/utils";
+import { escapeMarkdownLabel } from "../../editor/utils/escape-markdown-label";
import { useT, useTimeAgo } from "../../i18n";
import { canFocusLocalEnvironments, focusLocalEnvironment } from "../../platform/environment-focus";
import { useLocalDaemonStatus } from "../../platform/use-local-daemon-status";
import { buildRuntimeMachines, type RuntimeMachine } from "../../runtimes/components/runtime-machines";
+import { EnvironmentLogDialog } from "./environment-log-dialog";
+import {
+ displayHost,
+ environmentTitle,
+ exitCode,
+ isDeclaredAs,
+ isLive,
+ isLoopbackUrl,
+ isPinnedCrash,
+ pendingAction,
+ preparingRun,
+ recentFailure,
+ runOrdinals,
+} from "./environment-model";
+import { EnvironmentStartMenu, type DeclaredState } from "./environment-start-menu";
import { IssueSidebarSectionHeader } from "./issue-sidebar-section";
type IssuesT = ReturnType<typeof useT<"issues">>["t"];
-const STATE_TONE: Record<IssueEnvironmentState, string> = {
+type RowState = IssueEnvironmentState | "stopping";
+
+const STATE_TONE: Record<RowState, string> = {
starting: "text-warning",
running: "text-success",
unreachable: "text-warning",
exited: "text-destructive",
stopped: "text-muted-foreground",
+ stopping: "text-muted-foreground",
};
-const isLive = (env: IssueEnvironment) => env.ended_at === null;
-const isApp = (env: IssueEnvironment) => env.kind === "app";
+// Comments this tab asked an agent to start the environment with, so the
+// "preparing" row shows before the run's summary is fetched.
+const requestedStartComments = new Map<string, Set<string>>();
-type MachineGroup = { key: string; machine: RuntimeMachine | null; envs: IssueEnvironment[] };
+type MachineGroup<T> = { key: string; machine: RuntimeMachine | null; offline: boolean; items: T[] };
+
+/** How a row can be acted on, given the machine and the caller. */
+interface RowAccess {
+ machineTitle: string | null;
+ offline: boolean;
+ localhostHint: string | null;
+ /** Why this machine cannot switch to an app's window; null when it can. */
+ appHint: string | null;
+ originLabel: string | null;
+}
/**
* "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,
+ * running — declared in the repository's environment config or found
+ * listening in a run's directory — grouped by the machine they run on,
* because a localhost URL only opens there. A desktop app has no URL; Desktop
* brings its window forward, but only through the daemon that found it.
- * Renders nothing until a run starts one.
+ * Members who may use a machine
+ * stop, restart and start its environments here; the machine carries the
+ * command out and the row shows it pending until it answers.
*/
-export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
+export function IssueEnvironmentsSection({
+ issueId,
+ assigneeType = null,
+ assigneeId = null,
+}: {
+ issueId: string;
+ assigneeType?: IssueAssigneeType | null;
+ assigneeId?: string | null;
+}) {
const { t } = useT("issues");
const wsId = useWorkspaceId();
+ const qc = useQueryClient();
const [open, setOpen] = useState(true);
const [showEnded, setShowEnded] = useState(false);
const { data } = useQuery(issueEnvironmentsOptions(wsId, issueId));
const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
+ const { data: tasks = [] } = useQuery(issueTasksOptions(issueId));
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { getActorName } = useActorName();
const local = useLocalDaemonStatus();
const currentUserId = useAuthStore((state) => state.user?.id ?? null);
+ const control = useControlIssueEnvironment(issueId);
+ const createComment = useCreateComment(issueId);
+ const [requested, setRequested] = useState<ReadonlySet<string>>(() => requestedStartComments.get(issueId) ?? new Set());
const machineByRuntime = useMemo(() => {
const machines = buildRuntimeMachines(runtimes, {
@@ -64,65 +160,230 @@ export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
}
return byRuntime;
}, [runtimes, local.daemonId, local.deviceName, currentUserId]);
+ const runtimeOnline = useMemo(() => new Map(runtimes.map((runtime) => [runtime.id, runtime.status === "online"])), [runtimes]);
+ const ordinals = useMemo(() => runOrdinals(tasks), [tasks]);
const envs = data?.environments ?? [];
- if (envs.length === 0) return null;
+ const configs = data?.configs ?? [];
+ const pendingStarts = data?.pending_starts ?? [];
+ const failedStarts = data?.failed_starts ?? [];
+ const [dismissedStarts, setDismissedStarts] = useState<ReadonlySet<string>>(() => new Set());
+ const now = Date.now();
+
+ // An unknown runtime is one this member cannot see; only a known one reads offline.
+ const isOffline = (runtimeId: string | null) => !!runtimeId && runtimeOnline.get(runtimeId) === false;
+ const machineOf = (runtimeId: string | null) => (runtimeId ? machineByRuntime.get(runtimeId) ?? null : null);
+ const machineTitle = (runtimeId: string | null) => machineOf(runtimeId)?.title ?? t(($) => $.environments.unknown_machine);
+ const runLabel = (taskId: string) => {
+ const ordinal = ordinals.get(taskId);
+ if (!ordinal) return null;
+ return ordinal === 1 ? t(($) => $.environments.run_first) : t(($) => $.environments.run_nth, { count: ordinal });
+ };
+ const actorName = (record: IssueEnvironmentActionRecord) =>
+ record.actor_id ? getActorName(record.actor_type, record.actor_id) : t(($) => $.environments.someone);
+
+ const originLabel = (env: IssueEnvironment): string | null => {
+ if (env.source === "detected") return t(($) => $.environments.detected_label, { name: env.name });
+ if (env.origin) {
+ const name = actorName(env.origin);
+ return env.origin.action === "restart"
+ ? t(($) => $.environments.restarted_by, { name })
+ : t(($) => $.environments.started_by, { name });
+ }
+ if (!env.agent_id) return null;
+ const agent = getActorName("agent", env.agent_id);
+ const run = runLabel(env.task_id);
+ return run
+ ? t(($) => $.environments.started_by_agent_in_run, { name: agent, run })
+ : t(($) => $.environments.started_by, { name: agent });
+ };
+
+ // Who "let the agent start it" goes to: the agent the issue is assigned to,
+ // else the last agent that ran on it; with neither, the reader picks.
+ const activeAgents = agents.filter((agent) => !agent.archived_at);
+ const agentById = (id: string | null | undefined) => (id ? activeAgents.find((agent) => agent.id === id) ?? null : null);
+ const latestAgentTask = [...tasks].sort((a, b) => b.created_at.localeCompare(a.created_at)).find((task) => agentById(task.agent_id));
+ const startAgent = (assigneeType === "agent" ? agentById(assigneeId) : null) ?? agentById(latestAgentTask?.agent_id);
+
+ const preparing = preparingRun(tasks, requested);
+ const preparingShown = preparing && !envs.some((env) => env.task_id === preparing.id && isLive(env));
+ const [justRequested, setJustRequested] = useState<string | null>(null);
+ const preparingAgentName = preparing
+ ? getActorName("agent", preparing.agent_id)
+ : justRequested;
+
+ const runControl = (action: IssueEnvironmentControl) => {
+ control.mutate(action, {
+ onError: (error) => {
+ toast.error(t(($) => $.environments.action_failed[action.action]), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ },
+ });
+ };
+
+ const askAgent = (agent: Agent) => {
+ const mention = `[@${escapeMarkdownLabel(agent.name)}](mention://agent/${agent.id})`;
+ setJustRequested(agent.name);
+ createComment.mutate(
+ { content: `${mention} ${t(($) => $.environments.start_menu.agent_instruction)}` },
+ {
+ onSuccess: (comment) => {
+ const ids = new Set(requestedStartComments.get(issueId) ?? []);
+ ids.add(comment.id);
+ requestedStartComments.set(issueId, ids);
+ setRequested(ids);
+ void qc.invalidateQueries({ queryKey: issueKeys.tasks(issueId) });
+ },
+ onError: (error) => {
+ toast.error(t(($) => $.environments.start_menu.ask_failed), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ },
+ onSettled: () => setJustRequested(null),
+ },
+ );
+ };
const live = envs.filter(isLive);
- const ended = envs.filter((env) => !isLive(env));
+ const pinned = envs.filter((env) => isPinnedCrash(env, envs, now));
+ const ended = envs.filter((env) => !isLive(env) && !pinned.includes(env));
+ // A start is settled once the environment it asked for has come up since,
+ // however it got there.
+ const startedSince = (start: IssueEnvironmentActionRecord) =>
+ live.some((env) => isDeclaredAs(env, start.runtime_id, start.repo, start.name) && env.started_at >= start.created_at);
+ const shownStarts = pendingStarts.filter((start) => !startedSince(start));
+ const shownFailures = failedStarts.filter((start) => !startedSince(start) && !dismissedStarts.has(start.id));
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);
- };
- // Only the daemon that detected an app knows its process, so a machine
- // that is merely named like this one does not count.
- const focusesHere = (machine: RuntimeMachine | null) =>
- canFocusLocalEnvironments() && knowsLocal && machine?.daemonId === local.daemonId;
- const appHint = (machine: RuntimeMachine | null) => {
- if (focusesHere(machine)) return null;
- return machine && !(knowsLocal && machine.isCurrent)
- ? t(($) => $.environments.app_remote_hint, { machine: machine.title })
- : t(($) => $.environments.app_desktop_hint);
+
+ const declaredState = (config: IssueEnvironmentConfig, declared: DeclaredEnvironment): DeclaredState => {
+ if (pendingStarts.some((start) =>
+ start.runtime_id === config.runtime_id && start.repo === declared.repo && start.name === declared.name,
+ )) return "starting";
+ const current = live.find((env) => isDeclaredAs(env, config.runtime_id, declared.repo, declared.name));
+ if (!current) return "available";
+ return current.state === "starting" || pendingAction(current)?.action === "restart" ? "starting" : "running";
};
- 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 groupBy = <T,>(items: T[], runtimeOf: (item: T) => string | null): MachineGroup<T>[] => {
+ const byMachine = new Map<string, MachineGroup<T>>();
+ for (const item of items) {
+ const runtimeId = runtimeOf(item);
+ const machine = machineOf(runtimeId);
const key = machine?.id ?? "unknown";
- const group = byMachine.get(key) ?? { key, machine, envs: [] };
- group.envs.push(env);
+ const group = byMachine.get(key) ?? { key, machine, offline: true, items: [] };
+ group.items.push(item);
+ group.offline = group.offline && isOffline(runtimeId);
byMachine.set(key, group);
}
- return [...byMachine.values()].sort((a, b) => Number(b.machine?.isCurrent ?? false) - Number(a.machine?.isCurrent ?? false));
+ return [...byMachine.values()].sort((a, b) =>
+ Number(a.offline) - Number(b.offline) ||
+ 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)}
- appHint={appHint(group.machine)}
- />
- ))}
- </div>
- ));
+ const access = (env: IssueEnvironment, group: MachineGroup<unknown>): RowAccess => {
+ const hint = knowsLocal && group.machine?.isCurrent
+ ? null
+ : group.machine
+ ? t(($) => $.environments.remote_hint, { machine: group.machine.title })
+ : t(($) => $.environments.localhost_hint);
+ // Only the daemon that detected an app knows its process, so a machine
+ // that is merely named like this one does not count.
+ const focusesHere = canFocusLocalEnvironments() && knowsLocal && group.machine?.daemonId === local.daemonId;
+ const appHint = focusesHere
+ ? null
+ : group.machine && !(knowsLocal && group.machine.isCurrent)
+ ? t(($) => $.environments.app_remote_hint, { machine: group.machine.title })
+ : t(($) => $.environments.app_desktop_hint);
+ return {
+ machineTitle: group.machine?.title ?? null,
+ offline: isOffline(env.runtime_id),
+ localhostHint: hint,
+ appHint,
+ originLabel: originLabel(env),
+ };
+ };
+
+ type MainItem = { kind: "env"; env: IssueEnvironment } | { kind: "start" | "failed"; start: IssueEnvironmentActionRecord };
+ const mainItems: MainItem[] = [
+ ...[...live, ...pinned].map((env) => ({ kind: "env" as const, env })),
+ ...shownStarts.map((start) => ({ kind: "start" as const, start })),
+ ...shownFailures.map((start) => ({ kind: "failed" as const, start })),
+ ];
+
+ const renderGroupHeader = (group: MachineGroup<unknown>) => (
+ <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}
+ {group.offline ? (
+ <span className="inline-flex shrink-0 items-center gap-0.5 rounded-xs bg-warning/10 px-1 text-micro font-medium text-warning">
+ <WifiOff className="size-2.5" />
+ {t(($) => $.environments.offline)}
+ </span>
+ ) : null}
+ </div>
+ );
+
+ const renderEnv = (env: IssueEnvironment, group: MachineGroup<unknown>) => (
+ <EnvironmentRow
+ key={env.id}
+ issueId={issueId}
+ env={env}
+ access={access(env, group)}
+ pinned={pinned.includes(env)}
+ actorName={actorName}
+ onControl={runControl}
+ />
+ );
+
+ const declaringConfig = (start: IssueEnvironmentActionRecord) => {
+ for (const config of configs) {
+ if (config.runtime_id !== start.runtime_id) continue;
+ const declared = config.environments.find((env) => env.repo === start.repo && env.name === start.name);
+ if (declared) return { config, declared };
+ }
+ return null;
+ };
+
+ const renderFailedStart = (start: IssueEnvironmentActionRecord) => {
+ const found = declaringConfig(start);
+ // Retry against the run that declares it now; the one first asked may
+ // have been cleaned up since.
+ const taskId = found?.config.task_id ?? start.task_id;
+ const canRetry = !!taskId && (found?.config.can_control ?? true) && !isOffline(start.runtime_id);
+ const expired = start.status === "expired";
+ return (
+ <FailedStartRow
+ key={start.id}
+ title={found?.declared.label || start.name}
+ state={expired ? t(($) => $.environments.no_response) : t(($) => $.environments.action_failed.start)}
+ meta={`${t(($) => $.environments.started_by, { name: actorName(start) })} · ${
+ expired ? t(($) => $.environments.log.no_response) : start.error || t(($) => $.environments.action_failed.start)
+ }`}
+ error={start.error}
+ canRetry={canRetry}
+ onRetry={() => taskId && runControl({ action: "start", body: { task_id: taskId, repo: start.repo, name: start.name } })}
+ onDismiss={() => setDismissedStarts((prev) => new Set(prev).add(start.id))}
+ />
+ );
+ };
+
+ const renderStart = (start: IssueEnvironmentActionRecord) => {
+ const declared = declaringConfig(start)?.declared;
+ return (
+ <StatusRow
+ key={start.id}
+ icon={<Server className="mt-px size-3.5 shrink-0 text-warning" />}
+ title={declared?.label || start.name}
+ state={<PendingState label={t(($) => $.environments.state.starting)} />}
+ meta={`${t(($) => $.environments.started_by, { name: actorName(start) })} · ${t(($) => $.environments.waiting_ready)}`}
+ />
+ );
+ };
return (
<div>
@@ -130,17 +391,47 @@ export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
title={t(($) => $.environments.section_title)}
open={open}
onOpenChange={setOpen}
- count={live.length}
+ count={live.length + pinned.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}
+ actions={
+ <EnvironmentStartMenu
+ configs={configs}
+ machineFor={(runtimeId) => ({ title: machineTitle(runtimeId), offline: isOffline(runtimeId) })}
+ runLabel={runLabel}
+ declaredState={declaredState}
+ onStart={(config, declared) =>
+ runControl({ action: "start", body: { task_id: config.task_id, repo: declared.repo, name: declared.name } })
+ }
+ agent={startAgent}
+ agentChoices={activeAgents}
+ preparing={!!preparing || justRequested !== null}
+ onAskAgent={askAgent}
+ />
+ }
/>
{open && (
<div className="px-2">
- {renderGroups(live)}
+ {(preparingShown || justRequested) && preparingAgentName && (
+ <StatusRow
+ icon={<Bot className="mt-px size-3.5 shrink-0 text-muted-foreground" />}
+ title={t(($) => $.environments.preparing_title, { name: preparingAgentName })}
+ state={<PendingState label={t(($) => $.environments.state.preparing)} />}
+ meta={t(($) => $.environments.preparing_hint)}
+ />
+ )}
+ {groupBy(mainItems, (item) => (item.kind === "env" ? item.env.runtime_id : item.start.runtime_id)).map((group) => (
+ <div key={group.key}>
+ {renderGroupHeader(group)}
+ {group.items.map((item) =>
+ item.kind === "env" ? renderEnv(item.env, group) : item.kind === "start" ? renderStart(item.start) : renderFailedStart(item.start),
+ )}
+ </div>
+ ))}
{ended.length > 0 && (
<>
<button
@@ -152,7 +443,12 @@ export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
{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)}
+ {showEnded && groupBy(ended, (env) => env.runtime_id).map((group) => (
+ <div key={group.key}>
+ {renderGroupHeader(group)}
+ {group.items.map((env) => renderEnv(env, group))}
+ </div>
+ ))}
</>
)}
</div>
@@ -161,38 +457,117 @@ export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
);
}
+function PendingState({ label }: { label: string }) {
+ return (
+ <span className="inline-flex shrink-0 items-center gap-1 text-caption text-muted-foreground">
+ <Spinner className="size-3" />
+ {label}
+ </span>
+ );
+}
+
+function StatusRow({ icon, title, state, meta }: { icon: ReactNode; title: string; state: ReactNode; meta: string }) {
+ return (
+ <div data-testid="environment-pending-row" className="flex items-start gap-2 rounded-md px-2 py-2">
+ {icon}
+ <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>
+ {state}
+ </p>
+ <p className="mt-1 truncate text-caption text-muted-foreground">{meta}</p>
+ </div>
+ </div>
+ );
+}
+
+function FailedStartRow({
+ title,
+ state,
+ meta,
+ error,
+ canRetry,
+ onRetry,
+ onDismiss,
+}: {
+ title: string;
+ state: string;
+ meta: string;
+ error: string;
+ canRetry: boolean;
+ onRetry: () => void;
+ onDismiss: () => void;
+}) {
+ const { t } = useT("issues");
+ return (
+ <div data-testid="environment-failed-start" className="group/env relative rounded-md px-2 py-2" title={error || undefined}>
+ <div className="flex items-start gap-2">
+ <Server className="mt-px size-3.5 shrink-0 text-destructive" />
+ <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="shrink-0 text-caption text-destructive">{state}</span>
+ </p>
+ <p className="mt-1 truncate text-caption text-muted-foreground">{meta}</p>
+ <div className="mt-2 flex items-center gap-1.5">
+ <Button variant="outline" size="xs" onClick={onRetry} disabled={!canRetry}>
+ <RotateCw />
+ {t(($) => $.environments.retry)}
+ </Button>
+ <Button variant="ghost" size="xs" onClick={onDismiss}>
+ <X />
+ {t(($) => $.environments.dismiss)}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
function EnvironmentRow({
+ issueId,
env,
- localhostHint,
- appHint,
+ access,
+ pinned,
+ actorName,
+ onControl,
}: {
+ issueId: string;
env: IssueEnvironment;
- localhostHint: string | null;
- /** Why this machine cannot switch to an app's window; null when it can. */
- appHint: string | null;
+ access: RowAccess;
+ pinned: boolean;
+ actorName: (record: IssueEnvironmentActionRecord) => string;
+ onControl: (control: IssueEnvironmentControl) => void;
}) {
const { t } = useT("issues");
const timeAgo = useTimeAgo();
+ const [logsOpen, setLogsOpen] = useState(false);
+ const [confirmStop, setConfirmStop] = useState(false);
const live = isLive(env);
- const app = isApp(env);
- const openable = !app && live && env.url !== "" && env.state !== "unreachable";
+ const pending = pendingAction(env);
+ const failure = pending ? null : recentFailure(env, Date.now());
+ const declared = env.source === "config";
+ const operable = env.controllable && env.can_control && !access.offline && !pending;
+ const canStop = live && operable;
+ const canRestart = declared && operable;
+ const canReadLogs = declared && env.controllable && !access.offline;
+
+ const app = env.kind === "app";
+ const rowState: RowState = pending?.action === "stop" ? "stopping" : pending ? "starting" : env.state;
+ const openable = !app && live && !pending && env.url !== "" && env.state !== "unreachable";
// Without the daemon's key for it there is nothing to ask the daemon for.
- const focusable = app && live && env.state === "running" && appHint === null && env.local_key !== "";
+ const focusable = app && live && env.state === "running" && access.appHint === null && env.local_key !== "";
const Icon = app ? AppWindow : env.url ? Globe : Server;
const host = !app && env.url ? displayHost(env.url) : null;
- const title = app || env.source === "config" ? env.label || env.name : host ?? env.name;
-
- const parts: string[] = [];
- if (env.source === "config") {
- if (host) parts.push(host);
- } else if (!app) {
- parts.push(env.name);
- }
- const meta = environmentMeta(env, t, timeAgo);
+ const title = environmentTitle(env);
+ const primary = declared ? host : app ? null : env.name;
+ const meta = environmentMeta(env, pending, t, timeAgo, actorName);
const tooltip = [
env.source === "detected" ? t(($) => $.environments.detected_hint) : null,
+ failure?.error || null,
env.detail || null,
- app ? appHint : isLoopbackUrl(env.url) ? localhostHint : null,
+ app ? access.appHint : isLoopbackUrl(env.url) ? access.localhostHint : null,
].filter(Boolean).join("\n");
const focus = () => {
@@ -205,31 +580,52 @@ function EnvironmentRow({
});
};
+ const restart = () => onControl({ action: "restart", environmentId: env.id });
+ const stop = () => onControl({ action: "stop", environmentId: env.id });
+
+ const showRestartIcon = !live && !pinned && canRestart;
+ // A detected app has no logs and is not stopped from here: it may be the
+ // reader's own app, and the daemon knows its process, not its listener. A
+ // declared one is supervised like any declared environment.
+ const hasMenu = (declared || !app) && (live || declared);
+ const hasActions = openable || focusable || hasMenu || showRestartIcon;
+
const body = (
<>
- <Icon className={cn("mt-px size-3.5 shrink-0", STATE_TONE[env.state] ?? "text-muted-foreground")} />
+ <Icon className={cn("mt-px size-3.5 shrink-0", STATE_TONE[rowState] ?? "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 || focusable) && "group-hover/env:invisible group-has-[:focus-visible]/env:invisible [@media(pointer:coarse)]:invisible",
+ STATE_TONE[rowState] ?? "text-muted-foreground",
+ hasActions && "group-hover/env:invisible group-has-[:focus-visible]/env:invisible [@media(pointer:coarse)]:invisible",
)}
>
- {t(($) => $.environments.state[env.state])}
+ {pending ? <PendingState label={t(($) => $.environments.state[rowState])} /> : t(($) => $.environments.state[rowState])}
</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>}
+ {primary && <span className="max-w-[60%] shrink-0 truncate">{primary}</span>}
+ {primary && meta && <span aria-hidden="true" className="text-faint-foreground">·</span>}
{meta && <span className="min-w-0 truncate">{meta}</span>}
+ {failure && (
+ <>
+ <span aria-hidden="true" className="text-faint-foreground">·</span>
+ <span className="shrink-0 text-warning">
+ {failure.status === "expired"
+ ? t(($) => $.environments.no_response)
+ : t(($) => $.environments.action_failed[failure.action])}
+ </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 ? (
@@ -243,49 +639,194 @@ function EnvironmentRow({
) : (
<div className="flex items-start gap-2 px-2 py-2">{body}</div>
)}
- {focusable && (
- <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.focus)} onClick={focus}>
- <ArrowUpRight />
- </IconButton>
+ {pinned && (
+ <div className="px-2 pb-2 pl-7.5">
+ {env.excerpt && (
+ <pre className="mb-2 overflow-hidden rounded-sm bg-destructive/10 px-2 py-1 font-mono text-micro leading-4 text-destructive">
+ {env.excerpt.split("\n").slice(-2).map((line, index) => (
+ <span key={index} className="block truncate">{line}</span>
+ ))}
+ </pre>
+ )}
+ <div className="flex items-center gap-1.5">
+ <Button variant="outline" size="xs" onClick={() => setLogsOpen(true)} disabled={!env.controllable}>
+ <ScrollText />
+ {t(($) => $.environments.view_logs)}
+ </Button>
+ <Button variant="outline" size="xs" onClick={restart} disabled={!canRestart}>
+ <RotateCw />
+ {t(($) => $.environments.restart)}
+ </Button>
+ </div>
</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>
+ {hasActions && (
+ <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 has-[[data-popup-open]]:opacity-100 [@media(pointer:coarse)]:opacity-100">
+ {openable && (
+ <>
+ <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>
+ </>
+ )}
+ {focusable && (
+ <IconButton variant="ghost" size="icon-xs" label={t(($) => $.environments.focus)} onClick={focus}>
+ <ArrowUpRight />
+ </IconButton>
+ )}
+ {showRestartIcon && (
+ <IconButton variant="ghost" size="icon-xs" label={t(($) => $.environments.restart)} onClick={restart}>
+ <RotateCw />
+ </IconButton>
+ )}
+ {hasMenu && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton variant="ghost" size="icon-xs" label={t(($) => $.environments.more_actions)}>
+ <MoreHorizontal />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-64">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="truncate">
+ {access.offline && access.machineTitle
+ ? t(($) => $.environments.machine_offline, { machine: access.machineTitle })
+ : access.originLabel ?? title}
+ </DropdownMenuLabel>
+ <DropdownMenuItem disabled={!canReadLogs} onClick={() => setLogsOpen(true)}>
+ <ScrollText />
+ {t(($) => $.environments.view_logs)}
+ </DropdownMenuItem>
+ {!declared && <MenuNote>{t(($) => $.environments.detected_no_logs)}</MenuNote>}
+ {declared && (env.can_control || access.offline || !env.controllable) && (
+ <DropdownMenuItem disabled={!canRestart} onClick={restart}>
+ <RotateCw />
+ {t(($) => $.environments.restart)}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuGroup>
+ {live && (env.can_control || access.offline || !env.controllable) && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={!canStop}
+ onClick={() => (declared ? stop() : setConfirmStop(true))}
+ >
+ <Square />
+ {declared ? t(($) => $.environments.stop) : t(($) => $.environments.stop_confirm_item)}
+ </DropdownMenuItem>
+ </>
+ )}
+ {access.offline ? (
+ <MenuNote>{t(($) => $.environments.offline_hint)}</MenuNote>
+ ) : !env.controllable ? (
+ <MenuNote>{t(($) => $.environments.outdated_hint)}</MenuNote>
+ ) : !env.can_control ? (
+ <>
+ <DropdownMenuSeparator />
+ <MenuNote>{t(($) => $.environments.no_permission_hint)}</MenuNote>
+ </>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</div>
)}
+ {logsOpen && (
+ <EnvironmentLogDialog
+ issueId={issueId}
+ env={env}
+ open={logsOpen}
+ onOpenChange={setLogsOpen}
+ machineTitle={access.machineTitle}
+ originLabel={access.originLabel}
+ offline={access.offline}
+ canRestart={canRestart}
+ onRestart={() => {
+ restart();
+ setLogsOpen(false);
+ }}
+ />
+ )}
+ <AlertDialog open={confirmStop} onOpenChange={setConfirmStop}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.environments.stop_confirm_title, { name: title })}</AlertDialogTitle>
+ <AlertDialogDescription>{t(($) => $.environments.stop_confirm_body, { process: env.name })}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.environments.cancel)}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ setConfirmStop(false);
+ stop();
+ }}
+ >
+ {t(($) => $.environments.stop)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
);
}
-function environmentMeta(env: IssueEnvironment, t: IssuesT, timeAgo: (iso: string) => string): string | null {
+function MenuNote({ children }: { children: ReactNode }) {
+ return <p className="px-2 py-1.5 text-caption text-muted-foreground">{children}</p>;
+}
+
+function environmentMeta(
+ env: IssueEnvironment,
+ pending: IssueEnvironmentActionRecord | null,
+ t: IssuesT,
+ timeAgo: (iso: string) => string,
+ actorName: (record: IssueEnvironmentActionRecord) => string,
+): string | null {
+ if (pending?.action === "stop") return t(($) => $.environments.waiting_machine);
+ if (pending?.action === "restart") {
+ return `${t(($) => $.environments.restarted_by, { name: actorName(pending) })} · ${t(($) => $.environments.waiting_ready)}`;
+ }
if (env.ended_at) {
- if (env.state === "exited" && env.detail) return env.detail;
+ const code = exitCode(env);
+ if (env.state === "exited" && code !== null && code !== 0) {
+ return `${t(($) => $.environments.exited_ago, { time: timeAgo(env.ended_at) })} · ${t(($) => $.environments.exit_code, { code })}`;
+ }
+ const last = env.last_action;
+ if (env.state === "stopped" && last?.action === "stop" && last.status === "succeeded") {
+ return `${t(($) => $.environments.stopped_by, { name: actorName(last) })} · ${timeAgo(env.ended_at)}`;
+ }
+ if (env.state === "stopped" && env.detail === "expired") return t(($) => $.environments.stopped_on_expiry);
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.state === "starting" && env.origin) {
+ const by = env.origin.action === "restart"
+ ? t(($) => $.environments.restarted_by, { name: actorName(env.origin) })
+ : t(($) => $.environments.started_by, { name: actorName(env.origin) });
+ return `${by} · ${t(($) => $.environments.waiting_ready)}`;
+ }
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 });
@@ -296,21 +837,3 @@ function environmentMeta(env: IssueEnvironment, t: IssuesT, timeAgo: (iso: strin
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.json
index 1a0b0bdc98..42f1b5ad3a 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -651,7 +651,10 @@
"wakeup_checkin_coalesced_one": "{{count}} silent check · latest: {{note}}",
"wakeup_checkin_coalesced_other": "{{count}} silent checks · latest: {{note}}",
"wakeup_chip_created_by": "{{name}}'s wakeup",
- "wakeup_chip_system": "System rule"
+ "wakeup_chip_system": "System rule",
+ "environment_stopped": "stopped the environment {{name}}",
+ "environment_restarted": "restarted the environment {{name}}",
+ "environment_started": "started the environment {{name}}"
},
"comment": {
"add_reaction": "Add reaction",
@@ -1919,7 +1922,9 @@
"running": "Running",
"exited": "Exited",
"stopped": "Stopped",
- "unreachable": "Not responding"
+ "unreachable": "Not responding",
+ "stopping": "Stopping",
+ "preparing": "Preparing"
},
"expires_in_minutes_one": "Expires in {{count}}m",
"expires_in_minutes_other": "Expires in {{count}}m",
@@ -1939,12 +1944,86 @@
"copy_url": "Copy URL",
"copied": "URL copied",
"copy_failed": "Couldn't copy the URL",
+ "offline": "Offline",
+ "machine_offline": "{{machine}} is offline",
+ "more_actions": "More actions",
+ "view_logs": "View logs",
+ "restart": "Restart",
+ "stop": "Stop",
+ "stop_confirm_item": "Stop…",
+ "run_first": "the first run",
+ "run_nth_one": "run {{count}}",
+ "run_nth_other": "run {{count}}",
+ "someone": "Someone",
+ "started_by": "Started by {{name}}",
+ "restarted_by": "Restarted by {{name}}",
+ "started_by_agent_in_run": "Started by {{name}} in {{run}}",
+ "stopped_by": "Stopped by {{name}}",
+ "stopped_on_expiry": "Stopped when it expired",
+ "exited_ago": "Exited {{time}}",
+ "exit_code": "Exit code {{code}}",
+ "detected_label": "Detected service · {{name}}",
+ "detected_no_logs": "This service wasn't started from the environment config, so it has no logs and can't be restarted.",
+ "offline_hint": "Available once this machine is back online.",
+ "outdated_hint": "Update Multica on this machine to manage it from here.",
+ "no_permission_hint": "Only members who can use this machine can stop or restart it.",
+ "waiting_machine": "Waiting for the machine",
+ "waiting_ready": "Waiting for it to be ready",
+ "no_response": "No response",
+ "action_failed": {
+ "stop": "Couldn't stop",
+ "restart": "Couldn't restart",
+ "start": "Couldn't start"
+ },
+ "stop_confirm_title": "Stop {{name}}?",
+ "stop_confirm_body": "This service ({{process}}) was detected, not started from the environment config. Once stopped it can't be restarted here; an agent has to start it again.",
+ "cancel": "Cancel",
+ "preparing_title": "{{name}} is preparing the environment",
+ "preparing_hint": "It will show up here once it starts",
+ "start_menu": {
+ "trigger": "Start an environment",
+ "note": "Starts from the project's environment config, using the code from the latest run on this machine.",
+ "no_permission": "Only members who can use a machine can start environments on it.",
+ "nothing_to_start": "This issue hasn't run yet, or the code from earlier runs has been cleaned up, so there's nothing to start directly.",
+ "ask_agent": "Ask {{name}} to start it",
+ "ask_any_agent": "Ask an agent to start it",
+ "new_run": "New run",
+ "preparing": "Preparing",
+ "ask_agent_hint": "{{name}} will get this issue's code ready, then start the environment. If the project has no environment config, it works out how to start it.",
+ "ask_any_agent_hint": "The agent will get this issue's code ready, then start the environment. If the project has no environment config, it works out how to start it.",
+ "ask_failed": "Couldn't ask the agent",
+ "agent_instruction": "Start the environment: get this issue's code ready, then run `multica env start` for the environments the project declares; if it declares none, work out how to start it yourself. Keep it running and reply with its address."
+ },
+ "log": {
+ "title": "{{name}} · Logs",
+ "filter": "Filter logs",
+ "wrap": "Wrap lines",
+ "follow": "Follow latest",
+ "copy": "Copy",
+ "copied": "Logs copied",
+ "copy_failed": "Couldn't copy the logs",
+ "refresh": "Refresh",
+ "footer_one": "Showing the last line · updated {{time}}",
+ "footer_other": "Showing the last {{count}} lines · updated {{time}}",
+ "loading": "Reading the logs…",
+ "empty": "No output yet",
+ "no_match": "No matching lines",
+ "no_response": "The machine didn't respond",
+ "failed": "Couldn't read the logs: {{error}}",
+ "offline_excerpt": "This machine is offline. These are the last lines it printed before exiting.",
+ "offline_empty": "Logs are available once this machine is back online.",
+ "exit_divider": "Exited at {{time}}",
+ "exit_divider_code": "Exited at {{time}} · exit code {{code}}",
+ "stopped_divider": "Stopped at {{time}}"
+ },
"app_desktop_hint": "A desktop app. Switch to its window from Multica Desktop on the machine running it.",
"app_remote_hint": "Runs on {{machine}}. Switch to its window from Multica Desktop on that machine.",
"focus": "Switch to window",
"focus_gone": "{{name}} is no longer running",
"focus_unsupported": "This machine's daemon can't switch to app windows yet. Update Multica and try again.",
"focus_unavailable": "The local daemon isn't running",
- "focus_failed": "Couldn't switch to {{name}}"
+ "focus_failed": "Couldn't switch to {{name}}",
+ "retry": "Retry",
+ "dismiss": "Dismiss"
}
}
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index 17671e9258..62db0be968 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -634,7 +634,10 @@
"wakeup_checkin_coalesced_other": "{{count}} comprobaciones silenciosas · última: {{note}}",
"wakeup_chip_created_by": "activación de {{name}}",
"wakeup_chip_system": "Regla del sistema",
- "wakeup_created_scheduled": "añadió una activación para {{agent}}: {{condition}}"
+ "wakeup_created_scheduled": "añadió una activación para {{agent}}: {{condition}}",
+ "environment_stopped": "detuvo el entorno {{name}}",
+ "environment_restarted": "reinició el entorno {{name}}",
+ "environment_started": "inició el entorno {{name}}"
},
"comment": {
"add_reaction": "Añadir reacción",
@@ -1919,7 +1922,9 @@
"running": "En ejecución",
"exited": "Terminado",
"stopped": "Detenido",
- "unreachable": "Sin respuesta"
+ "unreachable": "Sin respuesta",
+ "stopping": "Deteniendo",
+ "preparing": "Preparando"
},
"expires_in_minutes_one": "Caduca en {{count}} min",
"expires_in_minutes_other": "Caduca en {{count}} min",
@@ -1939,12 +1944,86 @@
"copy_url": "Copiar URL",
"copied": "URL copiada",
"copy_failed": "No se pudo copiar la URL",
+ "offline": "Sin conexión",
+ "machine_offline": "{{machine}} está sin conexión",
+ "more_actions": "Más acciones",
+ "view_logs": "Ver registros",
+ "restart": "Reiniciar",
+ "stop": "Detener",
+ "stop_confirm_item": "Detener…",
+ "run_first": "la primera ejecución",
+ "run_nth_one": "la ejecución {{count}}",
+ "run_nth_other": "la ejecución {{count}}",
+ "someone": "Alguien",
+ "started_by": "Iniciado por {{name}}",
+ "restarted_by": "Reiniciado por {{name}}",
+ "started_by_agent_in_run": "Iniciado por {{name}} en {{run}}",
+ "stopped_by": "Detenido por {{name}}",
+ "stopped_on_expiry": "Detenido al caducar",
+ "exited_ago": "Terminó {{time}}",
+ "exit_code": "Código de salida {{code}}",
+ "detected_label": "Servicio detectado · {{name}}",
+ "detected_no_logs": "Este servicio no se inició desde la configuración de entornos, así que no tiene registros ni se puede reiniciar.",
+ "offline_hint": "Disponible cuando este equipo vuelva a estar en línea.",
+ "outdated_hint": "Actualiza Multica en este equipo para gestionarlo desde aquí.",
+ "no_permission_hint": "Solo los miembros que pueden usar este equipo pueden detenerlo o reiniciarlo.",
+ "waiting_machine": "Esperando al equipo",
+ "waiting_ready": "Esperando a que esté listo",
+ "no_response": "Sin respuesta",
+ "action_failed": {
+ "stop": "No se pudo detener",
+ "restart": "No se pudo reiniciar",
+ "start": "No se pudo iniciar"
+ },
+ "stop_confirm_title": "¿Detener {{name}}?",
+ "stop_confirm_body": "Este servicio ({{process}}) se detectó automáticamente; no se inició desde la configuración de entornos. Una vez detenido, no se puede reiniciar aquí: un agente tendrá que volver a iniciarlo.",
+ "cancel": "Cancelar",
+ "preparing_title": "{{name}} está preparando el entorno",
+ "preparing_hint": "Aparecerá aquí cuando se inicie",
+ "start_menu": {
+ "trigger": "Iniciar un entorno",
+ "note": "Se inicia según la configuración de entornos del proyecto, con el código de la última ejecución en este equipo.",
+ "no_permission": "Solo los miembros que pueden usar un equipo pueden iniciar entornos en él.",
+ "nothing_to_start": "Esta tarea aún no se ha ejecutado, o el código de ejecuciones anteriores se ha limpiado, así que no hay nada que iniciar directamente.",
+ "ask_agent": "Pedir a {{name}} que lo inicie",
+ "ask_any_agent": "Pedir a un agente que lo inicie",
+ "new_run": "Nueva ejecución",
+ "preparing": "Preparando",
+ "ask_agent_hint": "{{name}} preparará el código de esta tarea y luego iniciará el entorno. Si el proyecto no tiene configuración de entornos, decidirá cómo iniciarlo.",
+ "ask_any_agent_hint": "El agente preparará el código de esta tarea y luego iniciará el entorno. Si el proyecto no tiene configuración de entornos, decidirá cómo iniciarlo.",
+ "ask_failed": "No se pudo pedir al agente",
+ "agent_instruction": "Inicia el entorno: prepara el código de esta tarea y ejecuta `multica env start` para los entornos que declara el proyecto; si no declara ninguno, decide tú cómo iniciarlo. Déjalo en marcha y responde con su dirección."
+ },
+ "log": {
+ "title": "{{name}} · Registros",
+ "filter": "Filtrar registros",
+ "wrap": "Ajustar líneas",
+ "follow": "Seguir lo último",
+ "copy": "Copiar",
+ "copied": "Registros copiados",
+ "copy_failed": "No se pudieron copiar los registros",
+ "refresh": "Actualizar",
+ "footer_one": "Mostrando la última línea · actualizado a las {{time}}",
+ "footer_other": "Mostrando las últimas {{count}} líneas · actualizado a las {{time}}",
+ "loading": "Leyendo los registros…",
+ "empty": "Todavía no hay salida",
+ "no_match": "Ninguna línea coincide",
+ "no_response": "El equipo no respondió",
+ "failed": "No se pudieron leer los registros: {{error}}",
+ "offline_excerpt": "Este equipo está sin conexión. Estas son las últimas líneas que imprimió antes de terminar.",
+ "offline_empty": "Los registros estarán disponibles cuando este equipo vuelva a estar en línea.",
+ "exit_divider": "Terminó a las {{time}}",
+ "exit_divider_code": "Terminó a las {{time}} · código de salida {{code}}",
+ "stopped_divider": "Detenido a las {{time}}"
+ },
"app_desktop_hint": "Una app de escritorio. Cambia a su ventana desde Multica Desktop en la máquina que la ejecuta.",
"app_remote_hint": "Se ejecuta en {{machine}}. Cambia a su ventana desde Multica Desktop en esa máquina.",
"focus": "Ir a la ventana",
"focus_gone": "{{name}} ya no se está ejecutando",
"focus_unsupported": "El daemon de esta máquina aún no puede cambiar a ventanas de apps. Actualiza Multica e inténtalo de nuevo.",
"focus_unavailable": "El daemon local no se está ejecutando",
- "focus_failed": "No se pudo cambiar a {{name}}"
+ "focus_failed": "No se pudo cambiar a {{name}}",
+ "retry": "Reintentar",
+ "dismiss": "Descartar"
}
}
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index f3a721bca0..cf1b559f92 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -651,7 +651,10 @@
"wakeup_checkin_coalesced_one": "{{count}} vérification silencieuse · dernière : {{note}}",
"wakeup_checkin_coalesced_other": "{{count}} vérifications silencieuses · dernière : {{note}}",
"wakeup_chip_created_by": "Réveil de {{name}}",
- "wakeup_chip_system": "Règle système"
+ "wakeup_chip_system": "Règle système",
+ "environment_stopped": "a arrêté l'environnement {{name}}",
+ "environment_restarted": "a redémarré l'environnement {{name}}",
+ "environment_started": "a démarré l'environnement {{name}}"
},
"comment": {
"add_reaction": "Ajouter une réaction",
@@ -1919,7 +1922,9 @@
"running": "En cours",
"exited": "Terminé",
"stopped": "Arrêté",
- "unreachable": "Sans réponse"
+ "unreachable": "Sans réponse",
+ "stopping": "Arrêt en cours",
+ "preparing": "Préparation"
},
"expires_in_minutes_one": "Expire dans {{count}} min",
"expires_in_minutes_other": "Expire dans {{count}} min",
@@ -1939,12 +1944,86 @@
"copy_url": "Copier l'URL",
"copied": "URL copiée",
"copy_failed": "Impossible de copier l'URL",
+ "offline": "Hors ligne",
+ "machine_offline": "{{machine}} est hors ligne",
+ "more_actions": "Plus d'actions",
+ "view_logs": "Voir les journaux",
+ "restart": "Redémarrer",
+ "stop": "Arrêter",
+ "stop_confirm_item": "Arrêter…",
+ "run_first": "la première exécution",
+ "run_nth_one": "l'exécution {{count}}",
+ "run_nth_other": "l'exécution {{count}}",
+ "someone": "Quelqu'un",
+ "started_by": "Démarré par {{name}}",
+ "restarted_by": "Redémarré par {{name}}",
+ "started_by_agent_in_run": "Démarré par {{name}} dans {{run}}",
+ "stopped_by": "Arrêté par {{name}}",
+ "stopped_on_expiry": "Arrêté à l'expiration",
+ "exited_ago": "Terminé {{time}}",
+ "exit_code": "Code de sortie {{code}}",
+ "detected_label": "Service détecté · {{name}}",
+ "detected_no_logs": "Ce service n'a pas été démarré depuis la configuration des environnements : il n'a pas de journaux et ne peut pas être redémarré.",
+ "offline_hint": "Disponible quand cet appareil sera de nouveau en ligne.",
+ "outdated_hint": "Mettez à jour Multica sur cet appareil pour le gérer d'ici.",
+ "no_permission_hint": "Seuls les membres qui peuvent utiliser cet appareil peuvent l'arrêter ou le redémarrer.",
+ "waiting_machine": "En attente de l'appareil",
+ "waiting_ready": "En attente qu'il soit prêt",
+ "no_response": "Aucune réponse",
+ "action_failed": {
+ "stop": "Impossible d'arrêter",
+ "restart": "Impossible de redémarrer",
+ "start": "Impossible de démarrer"
+ },
+ "stop_confirm_title": "Arrêter {{name}} ?",
+ "stop_confirm_body": "Ce service ({{process}}) a été détecté automatiquement ; il n'a pas été démarré depuis la configuration des environnements. Une fois arrêté, il ne peut pas être redémarré ici : un agent devra le relancer.",
+ "cancel": "Annuler",
+ "preparing_title": "{{name}} prépare l'environnement",
+ "preparing_hint": "Il apparaîtra ici une fois démarré",
+ "start_menu": {
+ "trigger": "Démarrer un environnement",
+ "note": "Démarre selon la configuration des environnements du projet, avec le code de la dernière exécution sur cet appareil.",
+ "no_permission": "Seuls les membres qui peuvent utiliser un appareil peuvent y démarrer des environnements.",
+ "nothing_to_start": "Cette tâche n'a pas encore été exécutée, ou le code des exécutions précédentes a été nettoyé : rien ne peut être démarré directement.",
+ "ask_agent": "Demander à {{name}} de le démarrer",
+ "ask_any_agent": "Demander à un agent de le démarrer",
+ "new_run": "Nouvelle exécution",
+ "preparing": "Préparation",
+ "ask_agent_hint": "{{name}} préparera le code de cette tâche, puis démarrera l'environnement. Si le projet n'a pas de configuration des environnements, il décidera comment le démarrer.",
+ "ask_any_agent_hint": "L'agent préparera le code de cette tâche, puis démarrera l'environnement. Si le projet n'a pas de configuration des environnements, il décidera comment le démarrer.",
+ "ask_failed": "Impossible de solliciter l'agent",
+ "agent_instruction": "Démarre l'environnement : prépare le code de cette tâche, puis lance `multica env start` pour les environnements déclarés par le projet ; s'il n'en déclare aucun, décide toi-même comment le démarrer. Laisse-le tourner et réponds avec son adresse."
+ },
+ "log": {
+ "title": "{{name}} · Journaux",
+ "filter": "Filtrer les journaux",
+ "wrap": "Retour à la ligne",
+ "follow": "Suivre la fin",
+ "copy": "Copier",
+ "copied": "Journaux copiés",
+ "copy_failed": "Impossible de copier les journaux",
+ "refresh": "Actualiser",
+ "footer_one": "Dernière ligne · mise à jour à {{time}}",
+ "footer_other": "Dernières {{count}} lignes · mis à jour à {{time}}",
+ "loading": "Lecture des journaux…",
+ "empty": "Aucune sortie pour l'instant",
+ "no_match": "Aucune ligne ne correspond",
+ "no_response": "L'appareil n'a pas répondu",
+ "failed": "Impossible de lire les journaux : {{error}}",
+ "offline_excerpt": "Cet appareil est hors ligne. Voici les dernières lignes affichées avant l'arrêt.",
+ "offline_empty": "Les journaux seront disponibles quand cet appareil sera de nouveau en ligne.",
+ "exit_divider": "Terminé à {{time}}",
+ "exit_divider_code": "Terminé à {{time}} · code de sortie {{code}}",
+ "stopped_divider": "Arrêté à {{time}}"
+ },
"app_desktop_hint": "Une app de bureau. Basculez vers sa fenêtre depuis Multica Desktop sur la machine qui l'exécute.",
"app_remote_hint": "S'exécute sur {{machine}}. Basculez vers sa fenêtre depuis Multica Desktop sur cette machine.",
"focus": "Afficher la fenêtre",
"focus_gone": "{{name}} ne s'exécute plus",
"focus_unsupported": "Le daemon de cette machine ne peut pas encore basculer vers les fenêtres d'apps. Mettez à jour Multica et réessayez.",
"focus_unavailable": "Le daemon local n'est pas en cours d'exécution",
- "focus_failed": "Impossible de basculer vers {{name}}"
+ "focus_failed": "Impossible de basculer vers {{name}}",
+ "retry": "Réessayer",
+ "dismiss": "Ignorer"
}
}
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 8ad881b66d..40fa966a16 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -635,7 +635,10 @@
"wakeup_checkin": "サイレントチェック:{{note}}",
"wakeup_checkin_coalesced_other": "サイレントチェック {{count}} 回 · 最新:{{note}}",
"wakeup_chip_created_by": "{{name}} が作成",
- "wakeup_chip_system": "システムルール"
+ "wakeup_chip_system": "システムルール",
+ "environment_stopped": "環境 {{name}} を停止しました",
+ "environment_restarted": "環境 {{name}} を再起動しました",
+ "environment_started": "環境 {{name}} を起動しました"
},
"comment": {
"add_reaction": "リアクションを追加",
@@ -1847,7 +1850,9 @@
"running": "実行中",
"exited": "終了",
"stopped": "停止",
- "unreachable": "応答なし"
+ "unreachable": "応答なし",
+ "stopping": "停止中",
+ "preparing": "準備中"
},
"expires_in_minutes_other": "{{count}}分後に期限切れ",
"expires_in_hours_other": "{{count}}時間後に期限切れ",
@@ -1863,12 +1868,84 @@
"copy_url": "URL をコピー",
"copied": "URL をコピーしました",
"copy_failed": "URL をコピーできませんでした",
+ "offline": "オフライン",
+ "machine_offline": "{{machine}} はオフラインです",
+ "more_actions": "その他の操作",
+ "view_logs": "ログを表示",
+ "restart": "再起動",
+ "stop": "停止",
+ "stop_confirm_item": "停止…",
+ "run_first": "初回の実行",
+ "run_nth_other": "{{count}} 回目の実行",
+ "someone": "誰か",
+ "started_by": "{{name}} が起動",
+ "restarted_by": "{{name}} が再起動",
+ "started_by_agent_in_run": "{{name}} が「{{run}}」で起動",
+ "stopped_by": "{{name}} が停止",
+ "stopped_on_expiry": "期限切れで自動停止",
+ "exited_ago": "{{time}}に終了",
+ "exit_code": "終了コード {{code}}",
+ "detected_label": "自動検出したサービス · {{name}}",
+ "detected_no_logs": "このサービスは環境設定から起動されていないため、ログを見ることも再起動することもできません。",
+ "offline_hint": "このマシンがオンラインに戻ると操作できます。",
+ "outdated_hint": "このマシンの Multica を更新すると、ここから操作できます。",
+ "no_permission_hint": "このマシンを使えるメンバーだけが停止・再起動できます。",
+ "waiting_machine": "マシンの応答を待っています",
+ "waiting_ready": "サービスの準備を待っています",
+ "no_response": "応答なし",
+ "action_failed": {
+ "stop": "停止できませんでした",
+ "restart": "再起動できませんでした",
+ "start": "起動できませんでした"
+ },
+ "stop_confirm_title": "{{name}} を停止しますか?",
+ "stop_confirm_body": "このサービス({{process}})は自動検出されたもので、環境設定から起動されたものではありません。停止するとここからは再起動できず、エージェントに起動し直してもらう必要があります。",
+ "cancel": "キャンセル",
+ "preparing_title": "{{name}} が環境を準備しています",
+ "preparing_hint": "起動するとここに表示されます",
+ "start_menu": {
+ "trigger": "環境を起動",
+ "note": "プロジェクトの環境設定に従い、このマシンでの最新の実行のコードで起動します。",
+ "no_permission": "マシンを使えるメンバーだけが、そのマシンで環境を起動できます。",
+ "nothing_to_start": "このタスクはまだ実行されていないか、以前の実行のコードが削除されているため、直接起動できる環境はありません。",
+ "ask_agent": "{{name}} に起動を依頼",
+ "ask_any_agent": "エージェントに起動を依頼",
+ "new_run": "新しい実行",
+ "preparing": "準備中",
+ "ask_agent_hint": "{{name}} がこのタスクのコードを用意してから環境を起動します。プロジェクトに環境設定がない場合は、起動方法を自分で判断します。",
+ "ask_any_agent_hint": "エージェントがこのタスクのコードを用意してから環境を起動します。プロジェクトに環境設定がない場合は、起動方法を自分で判断します。",
+ "ask_failed": "エージェントに依頼できませんでした",
+ "agent_instruction": "環境を起動してください:このタスクのコードを用意し、`multica env start` でプロジェクトに設定された環境を起動します。環境設定がない場合は、起動方法を自分で判断してください。サービスは動かしたままにして、アクセス先の URL を返信してください。"
+ },
+ "log": {
+ "title": "{{name}} · ログ",
+ "filter": "ログを絞り込む",
+ "wrap": "折り返し",
+ "follow": "最新を追う",
+ "copy": "コピー",
+ "copied": "ログをコピーしました",
+ "copy_failed": "ログをコピーできませんでした",
+ "refresh": "更新",
+ "footer_other": "直近 {{count}} 行を表示 · {{time}} に更新",
+ "loading": "ログを読み込んでいます…",
+ "empty": "まだ出力がありません",
+ "no_match": "一致する行はありません",
+ "no_response": "マシンが応答しませんでした",
+ "failed": "ログを読み込めませんでした:{{error}}",
+ "offline_excerpt": "このマシンはオフラインです。終了前に最後に出力された内容を表示しています。",
+ "offline_empty": "このマシンがオンラインに戻るとログを表示できます。",
+ "exit_divider": "{{time}} に終了",
+ "exit_divider_code": "{{time}} に終了 · 終了コード {{code}}",
+ "stopped_divider": "{{time}} に停止"
+ },
"app_desktop_hint": "デスクトップアプリです。実行中のマシンの Multica Desktop からウィンドウに切り替えられます。",
"app_remote_hint": "{{machine}} で実行中です。そのマシンの Multica Desktop からウィンドウに切り替えられます。",
"focus": "ウィンドウに切り替え",
"focus_gone": "{{name}} はもう実行されていません",
"focus_unsupported": "このマシンのデーモンはまだアプリのウィンドウに切り替えられません。Multica を更新してもう一度お試しください。",
"focus_unavailable": "ローカルのデーモンが実行されていません",
- "focus_failed": "{{name}} に切り替えられませんでした"
+ "focus_failed": "{{name}} に切り替えられませんでした",
+ "retry": "再試行",
+ "dismiss": "閉じる"
}
}
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 3dc8f4340a..26731a0ac8 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -635,7 +635,10 @@
"wakeup_checkin": "조용한 확인: {{note}}",
"wakeup_checkin_coalesced_other": "조용한 확인 {{count}}회 · 최근: {{note}}",
"wakeup_chip_created_by": "{{name}} 생성",
- "wakeup_chip_system": "시스템 규칙"
+ "wakeup_chip_system": "시스템 규칙",
+ "environment_stopped": "환경 {{name}}을(를) 중지했습니다",
+ "environment_restarted": "환경 {{name}}을(를) 재시작했습니다",
+ "environment_started": "환경 {{name}}을(를) 시작했습니다"
},
"comment": {
"add_reaction": "반응 추가",
@@ -1847,7 +1850,9 @@
"running": "실행 중",
"exited": "종료됨",
"stopped": "중지됨",
- "unreachable": "응답 없음"
+ "unreachable": "응답 없음",
+ "stopping": "중지 중",
+ "preparing": "준비 중"
},
"expires_in_minutes_other": "{{count}}분 후 만료",
"expires_in_hours_other": "{{count}}시간 후 만료",
@@ -1863,12 +1868,84 @@
"copy_url": "URL 복사",
"copied": "URL을 복사했습니다",
"copy_failed": "URL을 복사할 수 없습니다",
+ "offline": "오프라인",
+ "machine_offline": "{{machine}} 오프라인",
+ "more_actions": "추가 작업",
+ "view_logs": "로그 보기",
+ "restart": "재시작",
+ "stop": "중지",
+ "stop_confirm_item": "중지…",
+ "run_first": "첫 실행",
+ "run_nth_other": "{{count}}번째 실행",
+ "someone": "누군가",
+ "started_by": "{{name}} 님이 시작함",
+ "restarted_by": "{{name}} 님이 재시작함",
+ "started_by_agent_in_run": "{{name}} 님이 '{{run}}'에서 시작함",
+ "stopped_by": "{{name}} 님이 중지함",
+ "stopped_on_expiry": "만료되어 자동 중지됨",
+ "exited_ago": "{{time}} 종료됨",
+ "exit_code": "종료 코드 {{code}}",
+ "detected_label": "자동 감지된 서비스 · {{name}}",
+ "detected_no_logs": "이 서비스는 환경 설정으로 시작되지 않아 로그를 볼 수 없고 재시작할 수도 없습니다.",
+ "offline_hint": "이 기기가 다시 온라인이 되면 사용할 수 있습니다.",
+ "outdated_hint": "이 기기의 Multica를 업데이트하면 여기서 관리할 수 있습니다.",
+ "no_permission_hint": "이 기기를 사용할 수 있는 멤버만 중지하거나 재시작할 수 있습니다.",
+ "waiting_machine": "기기 응답 대기 중",
+ "waiting_ready": "서비스 준비 대기 중",
+ "no_response": "응답 없음",
+ "action_failed": {
+ "stop": "중지하지 못했습니다",
+ "restart": "재시작하지 못했습니다",
+ "start": "시작하지 못했습니다"
+ },
+ "stop_confirm_title": "{{name}}을(를) 중지할까요?",
+ "stop_confirm_body": "이 서비스({{process}})는 자동 감지된 것으로, 환경 설정으로 시작되지 않았습니다. 중지하면 여기서 재시작할 수 없으며 에이전트가 다시 시작해야 합니다.",
+ "cancel": "취소",
+ "preparing_title": "{{name}} 님이 환경을 준비하는 중",
+ "preparing_hint": "시작되면 여기에 표시됩니다",
+ "start_menu": {
+ "trigger": "환경 시작",
+ "note": "프로젝트의 환경 설정에 따라 이 기기의 최근 실행 코드로 시작합니다.",
+ "no_permission": "기기를 사용할 수 있는 멤버만 그 기기에서 환경을 시작할 수 있습니다.",
+ "nothing_to_start": "이 태스크는 아직 실행된 적이 없거나 이전 실행의 코드가 정리되어, 바로 시작할 수 있는 환경이 없습니다.",
+ "ask_agent": "{{name}}에게 시작 요청",
+ "ask_any_agent": "에이전트에게 시작 요청",
+ "new_run": "새 실행",
+ "preparing": "준비 중",
+ "ask_agent_hint": "{{name}}이(가) 이 태스크의 코드를 준비한 뒤 환경을 시작합니다. 프로젝트에 환경 설정이 없으면 시작 방법을 스스로 판단합니다.",
+ "ask_any_agent_hint": "에이전트가 이 태스크의 코드를 준비한 뒤 환경을 시작합니다. 프로젝트에 환경 설정이 없으면 시작 방법을 스스로 판단합니다.",
+ "ask_failed": "에이전트에게 요청하지 못했습니다",
+ "agent_instruction": "환경 시작: 이 태스크의 코드를 준비한 뒤 `multica env start`로 프로젝트에 설정된 환경을 시작하세요. 환경 설정이 없으면 시작 방법을 스스로 판단하세요. 서비스는 계속 실행해 두고 접속 주소를 답글로 알려 주세요."
+ },
+ "log": {
+ "title": "{{name}} · 로그",
+ "filter": "로그 필터",
+ "wrap": "자동 줄바꿈",
+ "follow": "최신 따라가기",
+ "copy": "복사",
+ "copied": "로그를 복사했습니다",
+ "copy_failed": "로그를 복사하지 못했습니다",
+ "refresh": "새로고침",
+ "footer_other": "최근 {{count}}줄 표시 · {{time}} 업데이트",
+ "loading": "로그를 읽는 중…",
+ "empty": "아직 출력이 없습니다",
+ "no_match": "일치하는 줄이 없습니다",
+ "no_response": "기기가 응답하지 않았습니다",
+ "failed": "로그를 읽지 못했습니다: {{error}}",
+ "offline_excerpt": "이 기기는 오프라인입니다. 종료 전에 마지막으로 출력한 내용입니다.",
+ "offline_empty": "이 기기가 다시 온라인이 되면 로그를 볼 수 있습니다.",
+ "exit_divider": "{{time}} 종료",
+ "exit_divider_code": "{{time}} 종료 · 종료 코드 {{code}}",
+ "stopped_divider": "{{time}} 중지"
+ },
"app_desktop_hint": "데스크톱 앱입니다. 실행 중인 머신의 Multica Desktop에서 창으로 전환할 수 있습니다.",
"app_remote_hint": "{{machine}}에서 실행 중입니다. 해당 머신의 Multica Desktop에서 창으로 전환할 수 있습니다.",
"focus": "창으로 전환",
"focus_gone": "{{name}}이(가) 더 이상 실행되고 있지 않습니다",
"focus_unsupported": "이 머신의 데몬은 아직 앱 창으로 전환할 수 없습니다. Multica를 업데이트한 뒤 다시 시도하세요.",
"focus_unavailable": "로컬 데몬이 실행되고 있지 않습니다",
- "focus_failed": "{{name}}(으)로 전환할 수 없습니다"
+ "focus_failed": "{{name}}(으)로 전환할 수 없습니다",
+ "retry": "다시 시도",
+ "dismiss": "닫기"
}
}
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index 525f1dc47e..f7e1302c0c 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -682,7 +682,10 @@
"wakeup_child_done_all_few": "Все {{count}} подзадачи завершены",
"wakeup_child_done_all_many": "Все {{count}} подзадач завершены",
"wakeup_checkin_coalesced_few": "{{count}} тихие проверки · последняя: {{note}}",
- "wakeup_checkin_coalesced_many": "{{count}} тихих проверок · последняя: {{note}}"
+ "wakeup_checkin_coalesced_many": "{{count}} тихих проверок · последняя: {{note}}",
+ "environment_stopped": "остановил(а) окружение {{name}}",
+ "environment_restarted": "перезапустил(а) окружение {{name}}",
+ "environment_started": "запустил(а) окружение {{name}}"
},
"comment": {
"add_reaction": "Добавить реакцию",
@@ -2069,7 +2072,9 @@
"running": "Работает",
"exited": "Завершилось",
"stopped": "Остановлено",
- "unreachable": "Не отвечает"
+ "unreachable": "Не отвечает",
+ "stopping": "Останавливается",
+ "preparing": "Подготовка"
},
"expires_in_minutes_one": "Истекает через {{count}} мин",
"expires_in_minutes_few": "Истекает через {{count}} мин",
@@ -2097,12 +2102,90 @@
"copy_url": "Копировать URL",
"copied": "URL скопирован",
"copy_failed": "Не удалось скопировать URL",
+ "offline": "Не в сети",
+ "machine_offline": "{{machine}} не в сети",
+ "more_actions": "Другие действия",
+ "view_logs": "Открыть журнал",
+ "restart": "Перезапустить",
+ "stop": "Остановить",
+ "stop_confirm_item": "Остановить…",
+ "run_first": "первом выполнении",
+ "run_nth_one": "выполнении {{count}}",
+ "run_nth_few": "выполнении {{count}}",
+ "run_nth_many": "выполнении {{count}}",
+ "run_nth_other": "выполнении {{count}}",
+ "someone": "Кто-то",
+ "started_by": "Запустил(а) {{name}}",
+ "restarted_by": "Перезапустил(а) {{name}}",
+ "started_by_agent_in_run": "Запустил(а) {{name}} при {{run}}",
+ "stopped_by": "Остановил(а) {{name}}",
+ "stopped_on_expiry": "Остановлено по истечении срока",
+ "exited_ago": "Завершилось {{time}}",
+ "exit_code": "Код выхода {{code}}",
+ "detected_label": "Обнаруженный сервис · {{name}}",
+ "detected_no_logs": "Этот сервис запущен не из конфигурации окружений, поэтому у него нет журнала и его нельзя перезапустить.",
+ "offline_hint": "Станет доступно, когда устройство снова будет в сети.",
+ "outdated_hint": "Обновите Multica на этом устройстве, чтобы управлять им отсюда.",
+ "no_permission_hint": "Останавливать и перезапускать могут только участники, которым доступно это устройство.",
+ "waiting_machine": "Ожидание ответа устройства",
+ "waiting_ready": "Ожидание готовности",
+ "no_response": "Нет ответа",
+ "action_failed": {
+ "stop": "Не удалось остановить",
+ "restart": "Не удалось перезапустить",
+ "start": "Не удалось запустить"
+ },
+ "stop_confirm_title": "Остановить {{name}}?",
+ "stop_confirm_body": "Этот сервис ({{process}}) обнаружен автоматически и запущен не из конфигурации окружений. После остановки его нельзя перезапустить отсюда — агенту придётся запустить его снова.",
+ "cancel": "Отмена",
+ "preparing_title": "{{name}} готовит окружение",
+ "preparing_hint": "Оно появится здесь после запуска",
+ "start_menu": {
+ "trigger": "Запустить окружение",
+ "note": "Запускается по конфигурации окружений проекта, с кодом последнего выполнения на этом устройстве.",
+ "no_permission": "Запускать окружения на устройстве могут только участники, которым оно доступно.",
+ "nothing_to_start": "Эта задача ещё не выполнялась или код прошлых выполнений уже удалён, поэтому запускать напрямую нечего.",
+ "ask_agent": "Попросить {{name}} запустить",
+ "ask_any_agent": "Попросить агента запустить",
+ "new_run": "Новое выполнение",
+ "preparing": "Подготовка",
+ "ask_agent_hint": "{{name}} подготовит код этой задачи и запустит окружение. Если в проекте нет конфигурации окружений, агент сам решит, как его запустить.",
+ "ask_any_agent_hint": "Агент подготовит код этой задачи и запустит окружение. Если в проекте нет конфигурации окружений, агент сам решит, как его запустить.",
+ "ask_failed": "Не удалось передать агенту",
+ "agent_instruction": "Запусти окружение: подготовь код этой задачи и выполни `multica env start` для окружений, объявленных в проекте; если их нет, сам реши, как его запустить. Оставь его работать и ответь с его адресом."
+ },
+ "log": {
+ "title": "{{name}} · Журнал",
+ "filter": "Фильтр журнала",
+ "wrap": "Перенос строк",
+ "follow": "Следить за концом",
+ "copy": "Копировать",
+ "copied": "Журнал скопирован",
+ "copy_failed": "Не удалось скопировать журнал",
+ "refresh": "Обновить",
+ "footer_one": "Последние строки: {{count}} · обновлено в {{time}}",
+ "footer_few": "Последние строки: {{count}} · обновлено в {{time}}",
+ "footer_many": "Последние строки: {{count}} · обновлено в {{time}}",
+ "footer_other": "Последние строки: {{count}} · обновлено в {{time}}",
+ "loading": "Чтение журнала…",
+ "empty": "Вывода пока нет",
+ "no_match": "Нет совпадающих строк",
+ "no_response": "Устройство не ответило",
+ "failed": "Не удалось прочитать журнал: {{error}}",
+ "offline_excerpt": "Устройство не в сети. Это последние строки, выведенные перед завершением.",
+ "offline_empty": "Журнал станет доступен, когда устройство снова будет в сети.",
+ "exit_divider": "Завершилось в {{time}}",
+ "exit_divider_code": "Завершилось в {{time}} · код выхода {{code}}",
+ "stopped_divider": "Остановлено в {{time}}"
+ },
"app_desktop_hint": "Настольное приложение. Переключиться на его окно можно из Multica Desktop на машине, где оно запущено.",
"app_remote_hint": "Запущено на {{machine}}. Переключиться на его окно можно из Multica Desktop на этой машине.",
"focus": "Перейти к окну",
"focus_gone": "{{name}} больше не запущено",
"focus_unsupported": "Демон на этой машине пока не умеет переключаться на окна приложений. Обновите Multica и попробуйте снова.",
"focus_unavailable": "Локальный демон не запущен",
- "focus_failed": "Не удалось переключиться на {{name}}"
+ "focus_failed": "Не удалось переключиться на {{name}}",
+ "retry": "Повторить",
+ "dismiss": "Скрыть"
}
}
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 2689f47ee6..7cb97706d7 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -635,7 +635,10 @@
"wakeup_checkin": "静默检查:{{note}}",
"wakeup_checkin_coalesced_other": "静默检查 {{count}} 次 · 最近一次:{{note}}",
"wakeup_chip_created_by": "{{name}} 创建",
- "wakeup_chip_system": "系统规则"
+ "wakeup_chip_system": "系统规则",
+ "environment_stopped": "停止了环境 {{name}}",
+ "environment_restarted": "重启了环境 {{name}}",
+ "environment_started": "启动了环境 {{name}}"
},
"comment": {
"add_reaction": "添加表情回应",
@@ -1847,7 +1850,9 @@
"running": "运行中",
"exited": "已退出",
"stopped": "已停止",
- "unreachable": "无响应"
+ "unreachable": "无响应",
+ "stopping": "停止中",
+ "preparing": "准备中"
},
"expires_in_minutes_other": "{{count}} 分钟后过期",
"expires_in_hours_other": "{{count}} 小时后过期",
@@ -1863,12 +1868,84 @@
"copy_url": "复制地址",
"copied": "已复制地址",
"copy_failed": "无法复制地址",
+ "offline": "离线",
+ "machine_offline": "{{machine}} 已离线",
+ "more_actions": "更多操作",
+ "view_logs": "查看日志",
+ "restart": "重启",
+ "stop": "停止",
+ "stop_confirm_item": "停止…",
+ "run_first": "首次运行",
+ "run_nth_other": "第 {{count}} 次运行",
+ "someone": "有人",
+ "started_by": "由 {{name}} 启动",
+ "restarted_by": "由 {{name}} 重启",
+ "started_by_agent_in_run": "由 {{name}} 在「{{run}}」中启动",
+ "stopped_by": "由 {{name}} 停止",
+ "stopped_on_expiry": "到期自动停止",
+ "exited_ago": "{{time}}退出",
+ "exit_code": "退出码 {{code}}",
+ "detected_label": "自动识别的服务 · {{name}}",
+ "detected_no_logs": "这个服务不是按环境配置启动的,所以看不到日志,也不能重启。",
+ "offline_hint": "这台机器重新上线后才能操作。",
+ "outdated_hint": "这台机器上的 Multica 更新后,才能在这里操作。",
+ "no_permission_hint": "只有能使用这台机器的成员可以停止或重启。",
+ "waiting_machine": "等待机器响应",
+ "waiting_ready": "等待服务就绪",
+ "no_response": "没有响应",
+ "action_failed": {
+ "stop": "停止失败",
+ "restart": "重启失败",
+ "start": "启动失败"
+ },
+ "stop_confirm_title": "停止 {{name}}?",
+ "stop_confirm_body": "这个服务({{process}})是自动识别的,不是按环境配置启动的。停止后不能在这里重启,需要让智能体重新启动它。",
+ "cancel": "取消",
+ "preparing_title": "{{name}} 正在准备环境",
+ "preparing_hint": "启动后会显示在这里",
+ "start_menu": {
+ "trigger": "启动环境",
+ "note": "按项目里的环境配置启动,使用这台机器上最近一次运行的代码。",
+ "no_permission": "只有能使用这台机器的成员可以在上面启动环境。",
+ "nothing_to_start": "这个任务还没运行过,或者之前运行的代码已被清理,没有可以直接启动的环境。",
+ "ask_agent": "让 {{name}} 启动",
+ "ask_any_agent": "让智能体启动",
+ "new_run": "新建运行",
+ "preparing": "准备中",
+ "ask_agent_hint": "{{name}} 会准备好这个任务的代码,再启动环境。项目里没有环境配置时,它会自己判断怎么启动。",
+ "ask_any_agent_hint": "智能体会准备好这个任务的代码,再启动环境。项目里没有环境配置时,它会自己判断怎么启动。",
+ "ask_failed": "没能交给智能体",
+ "agent_instruction": "启动环境:先准备好这个任务的代码,再用 `multica env start` 启动项目里配置的环境;项目里没有环境配置时,自己判断怎么启动。让服务保持运行,并回复访问地址。"
+ },
+ "log": {
+ "title": "{{name}} · 日志",
+ "filter": "筛选日志",
+ "wrap": "自动换行",
+ "follow": "跟随最新",
+ "copy": "复制",
+ "copied": "已复制日志",
+ "copy_failed": "无法复制日志",
+ "refresh": "刷新",
+ "footer_other": "显示最近 {{count}} 行 · {{time}} 更新",
+ "loading": "正在读取日志…",
+ "empty": "还没有输出",
+ "no_match": "没有匹配的行",
+ "no_response": "机器没有响应",
+ "failed": "没能读取日志:{{error}}",
+ "offline_excerpt": "这台机器已离线,下面是它退出前最后输出的内容。",
+ "offline_empty": "这台机器重新上线后才能查看日志。",
+ "exit_divider": "{{time}} 退出",
+ "exit_divider_code": "{{time}} 退出 · 退出码 {{code}}",
+ "stopped_divider": "{{time}} 停止"
+ },
"app_desktop_hint": "桌面 App。在运行它的那台机器上,用 Multica Desktop 切到它的窗口。",
"app_remote_hint": "运行在 {{machine}} 上。在那台机器上用 Multica Desktop 切到它的窗口。",
"focus": "切到窗口",
"focus_gone": "{{name}} 已经不在运行",
"focus_unsupported": "这台机器的 daemon 暂时不能切换 App 窗口。更新 Multica 后再试。",
"focus_unavailable": "本机 daemon 没有运行",
- "focus_failed": "无法切到 {{name}}"
+ "focus_failed": "无法切到 {{name}}",
+ "retry": "重试",
+ "dismiss": "忽略"
}
}
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index d503e70811..dade6a1699 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -635,7 +635,10 @@
"wakeup_checkin": "靜默檢查:{{note}}",
"wakeup_checkin_coalesced_other": "靜默檢查 {{count}} 次 · 最近一次:{{note}}",
"wakeup_chip_created_by": "{{name}} 建立",
- "wakeup_chip_system": "系統規則"
+ "wakeup_chip_system": "系統規則",
+ "environment_stopped": "停止了環境 {{name}}",
+ "environment_restarted": "重新啟動了環境 {{name}}",
+ "environment_started": "啟動了環境 {{name}}"
},
"comment": {
"add_reaction": "新增表情回應",
@@ -1847,7 +1850,9 @@
"running": "執行中",
"exited": "已退出",
"stopped": "已停止",
- "unreachable": "無回應"
+ "unreachable": "無回應",
+ "stopping": "停止中",
+ "preparing": "準備中"
},
"expires_in_minutes_other": "{{count}} 分鐘後到期",
"expires_in_hours_other": "{{count}} 小時後到期",
@@ -1863,12 +1868,84 @@
"copy_url": "複製位址",
"copied": "已複製位址",
"copy_failed": "無法複製位址",
+ "offline": "離線",
+ "machine_offline": "{{machine}} 已離線",
+ "more_actions": "更多操作",
+ "view_logs": "查看日誌",
+ "restart": "重新啟動",
+ "stop": "停止",
+ "stop_confirm_item": "停止…",
+ "run_first": "首次執行",
+ "run_nth_other": "第 {{count}} 次執行",
+ "someone": "有人",
+ "started_by": "由 {{name}} 啟動",
+ "restarted_by": "由 {{name}} 重新啟動",
+ "started_by_agent_in_run": "由 {{name}} 在「{{run}}」中啟動",
+ "stopped_by": "由 {{name}} 停止",
+ "stopped_on_expiry": "到期自動停止",
+ "exited_ago": "{{time}}退出",
+ "exit_code": "退出碼 {{code}}",
+ "detected_label": "自動識別的服務 · {{name}}",
+ "detected_no_logs": "這個服務不是按環境設定啟動的,所以看不到日誌,也不能重新啟動。",
+ "offline_hint": "這台機器重新上線後才能操作。",
+ "outdated_hint": "這台機器上的 Multica 更新後,才能在這裡操作。",
+ "no_permission_hint": "只有能使用這台機器的成員可以停止或重新啟動。",
+ "waiting_machine": "等待機器回應",
+ "waiting_ready": "等待服務就緒",
+ "no_response": "沒有回應",
+ "action_failed": {
+ "stop": "停止失敗",
+ "restart": "重新啟動失敗",
+ "start": "啟動失敗"
+ },
+ "stop_confirm_title": "停止 {{name}}?",
+ "stop_confirm_body": "這個服務({{process}})是自動識別的,不是按環境設定啟動的。停止後不能在這裡重新啟動,需要讓代理重新啟動它。",
+ "cancel": "取消",
+ "preparing_title": "{{name}} 正在準備環境",
+ "preparing_hint": "啟動後會顯示在這裡",
+ "start_menu": {
+ "trigger": "啟動環境",
+ "note": "按專案裡的環境設定啟動,使用這台機器上最近一次執行的程式碼。",
+ "no_permission": "只有能使用這台機器的成員可以在上面啟動環境。",
+ "nothing_to_start": "這個任務還沒執行過,或者之前執行的程式碼已被清理,沒有可以直接啟動的環境。",
+ "ask_agent": "讓 {{name}} 啟動",
+ "ask_any_agent": "讓代理啟動",
+ "new_run": "新建執行",
+ "preparing": "準備中",
+ "ask_agent_hint": "{{name}} 會準備好這個任務的程式碼,再啟動環境。專案裡沒有環境設定時,它會自己判斷怎麼啟動。",
+ "ask_any_agent_hint": "代理會準備好這個任務的程式碼,再啟動環境。專案裡沒有環境設定時,它會自己判斷怎麼啟動。",
+ "ask_failed": "沒能交給代理",
+ "agent_instruction": "啟動環境:先準備好這個任務的程式碼,再用 `multica env start` 啟動專案裡設定的環境;專案裡沒有環境設定時,自己判斷怎麼啟動。讓服務保持運行,並回覆存取網址。"
+ },
+ "log": {
+ "title": "{{name}} · 日誌",
+ "filter": "篩選日誌",
+ "wrap": "自動換行",
+ "follow": "跟隨最新",
+ "copy": "複製",
+ "copied": "已複製日誌",
+ "copy_failed": "無法複製日誌",
+ "refresh": "重新整理",
+ "footer_other": "顯示最近 {{count}} 行 · {{time}} 更新",
+ "loading": "正在讀取日誌…",
+ "empty": "還沒有輸出",
+ "no_match": "沒有符合的行",
+ "no_response": "機器沒有回應",
+ "failed": "沒能讀取日誌:{{error}}",
+ "offline_excerpt": "這台機器已離線,下面是它退出前最後輸出的內容。",
+ "offline_empty": "這台機器重新上線後才能查看日誌。",
+ "exit_divider": "{{time}} 退出",
+ "exit_divider_code": "{{time}} 退出 · 退出碼 {{code}}",
+ "stopped_divider": "{{time}} 停止"
+ },
"app_desktop_hint": "桌面 App。在執行它的那台機器上,用 Multica Desktop 切到它的視窗。",
"app_remote_hint": "在 {{machine}} 上執行。在那台機器上用 Multica Desktop 切到它的視窗。",
"focus": "切到視窗",
"focus_gone": "{{name}} 已不在執行",
"focus_unsupported": "這台機器的 daemon 暫時無法切換 App 視窗。更新 Multica 後再試。",
"focus_unavailable": "本機 daemon 沒有執行",
- "focus_failed": "無法切到 {{name}}"
+ "focus_failed": "無法切到 {{name}}",
+ "retry": "重試",
+ "dismiss": "忽略"
}
}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 91f2be8014..6c5a5345f5 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,10 @@ 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{
+ "642_issue_environment_config_issue_idx": "idx_issue_environment_config_issue",
+ "641_issue_environment_command_logs_idx": "idx_issue_environment_command_logs",
+ "640_issue_environment_command_issue_idx": "idx_issue_environment_command_issue",
+ "639_issue_environment_command_pending_idx": "idx_issue_environment_command_pending",
"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",
diff --git a/server/cmd/server/environment_log_sweeper.go b/server/cmd/server/environment_log_sweeper.go
new file mode 100644
index 0000000000..eccb0e390f
--- /dev/null
+++ b/server/cmd/server/environment_log_sweeper.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/handler"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const environmentLogSweepInterval = time.Minute
+
+// runEnvironmentLogSweeper deletes the environment log reads the sidebar no
+// longer needs, so program output does not stay in the database.
+func runEnvironmentLogSweeper(ctx context.Context, queries *db.Queries) {
+ ticker := time.NewTicker(environmentLogSweepInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ sweepCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ if n, err := handler.SweepEnvironmentLogCommands(sweepCtx, queries, time.Now()); err != nil {
+ slog.Warn("environment log sweep failed", "error", err)
+ } else if n > 0 {
+ slog.Debug("environment log sweep removed reads", "count", n)
+ }
+ cancel()
+ }
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 403c6ebf24..eb20754fb1 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -765,6 +765,7 @@ func main() {
// Source-context cleanup is object-store work, so it gets its own goroutine
// instead of a slot in the runtime sweep tick.
go runSourceContextSweeper(sweepCtx, taskSvc)
+ go runEnvironmentLogSweeper(sweepCtx, queries)
if h.ConnectedApps != nil {
go h.ConnectedApps.RunSweeper(sweepCtx)
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9706afc965..5f07e034ca 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1668,6 +1668,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/runtimes/{runtimeId}/models/{requestId}/result", h.ReportModelListResult)
r.Post("/runtimes/{runtimeId}/local-skills/{requestId}/result", h.ReportLocalSkillListResult)
r.Post("/runtimes/{runtimeId}/local-skills/import/{requestId}/result", h.ReportLocalSkillImportResult)
+ r.Post("/runtimes/{runtimeId}/environment-commands/claim", h.ClaimEnvironmentCommands)
+ r.Post("/runtimes/{runtimeId}/environment-commands/{commandId}/result", h.ReportEnvironmentCommandResult)
r.Get("/tasks/{taskId}/status", h.GetTaskStatus)
r.Post("/tasks/{taskId}/start", h.StartTask)
@@ -1679,6 +1681,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
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}/environment-configs", h.ReportTaskEnvironmentConfigs)
r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)
r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)
r.Post("/tasks/{taskId}/cancel-ack", h.AckTaskCancelled)
@@ -2182,6 +2185,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Put("/properties/{propertyId}", h.SetIssueProperty)
r.Delete("/properties/{propertyId}", h.DeleteIssueProperty)
r.Get("/environments", h.ListIssueEnvironments)
+ r.With(handler.RequireHumanActor).Post("/environments/start", h.StartIssueEnvironment)
+ r.With(handler.RequireHumanActor).Post("/environments/{environmentId}/stop", h.StopIssueEnvironment)
+ r.With(handler.RequireHumanActor).Post("/environments/{environmentId}/restart", h.RestartIssueEnvironment)
+ r.Post("/environments/{environmentId}/logs", h.ReadIssueEnvironmentLogs)
+ r.Get("/environment-commands/{commandId}", h.GetIssueEnvironmentCommand)
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.go
index c576f5136b..0664372fce 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -15,6 +15,7 @@ import (
"sync"
"time"
+ "github.com/multica-ai/multica/server/internal/daemon/localenv"
"github.com/multica-ai/multica/server/pkg/agent"
"github.com/multica-ai/multica/server/pkg/httptransport"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -682,6 +683,7 @@ type TaskEnvironmentReport struct {
Key string `json:"key"`
Source string `json:"source"`
Kind string `json:"kind,omitempty"`
+ Repo string `json:"repo,omitempty"`
Name string `json:"name"`
Label string `json:"label"`
URL string `json:"url"`
@@ -690,19 +692,68 @@ type TaskEnvironmentReport struct {
Detail string `json:"detail"`
StartedAt time.Time `json:"started_at"`
ExpiresAt *time.Time `json:"expires_at"`
+ Excerpt string `json:"excerpt,omitempty"`
}
// ReportTaskEnvironments replaces the task's environment snapshot; whatever
-// it leaves out the server records as stopped.
+// it leaves out the server records as stopped. controllable tells the server
+// this daemon carries out environment commands.
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,
+ "controllable": true,
}, nil)
}
+// ReportTaskEnvironmentConfigs records what a finished task's repositories
+// declare, which the sidebar offers to start.
+func (c *Client) ReportTaskEnvironmentConfigs(ctx context.Context, taskID string, envs []localenv.Declared) error {
+ if envs == nil {
+ envs = []localenv.Declared{}
+ }
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/environment-configs", taskID), map[string]any{
+ "environments": envs,
+ }, nil)
+}
+
+// EnvironmentCommand is a stop, restart, start or log read a member asked
+// for from the issue sidebar.
+type EnvironmentCommand struct {
+ ID string `json:"id"`
+ Action string `json:"action"`
+ WorkspaceID string `json:"workspace_id"`
+ IssueID string `json:"issue_id"`
+ TaskID string `json:"task_id"`
+ LocalKey string `json:"local_key"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+}
+
+// EnvironmentCommandResult is how a command went.
+type EnvironmentCommandResult struct {
+ OK bool `json:"ok"`
+ Error string `json:"error,omitempty"`
+ Output *string `json:"output,omitempty"`
+ EnvironmentKey string `json:"environment_key,omitempty"`
+}
+
+func (c *Client) ClaimEnvironmentCommands(ctx context.Context, runtimeID string) ([]EnvironmentCommand, error) {
+ var resp struct {
+ Commands []EnvironmentCommand `json:"commands"`
+ }
+ if err := c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/environment-commands/claim", runtimeID), map[string]any{}, &resp); err != nil {
+ return nil, err
+ }
+ return resp.Commands, nil
+}
+
+func (c *Client) ReportEnvironmentCommandResult(ctx context.Context, runtimeID, commandID string, result EnvironmentCommandResult) error {
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/environment-commands/%s/result", runtimeID, commandID), result, nil)
+}
+
func (c *Client) ReportTaskUsageSnapshot(ctx context.Context, taskID string, usage []TaskUsageEntry) error {
if len(usage) == 0 {
return nil
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 4e57332ab8..7ec1102ced 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -4649,6 +4649,14 @@ func (d *Daemon) handlePendingWorkHint(runtimeID, kind string) {
// Not one of ours (stale relay fanout, or the runtime was just pruned).
return
}
+ // Environment commands have their own claim, and are answered by a member
+ // waiting in the sidebar, so they skip the heartbeat and its rate limit.
+ if kind == protocol.PendingWorkKindEnvironmentCommand {
+ if ctx := d.recoveryContext(); ctx.Err() == nil {
+ d.environments.claimCommands(ctx, runtimeID)
+ }
+ return
+ }
d.pendingWorkMu.Lock()
if d.pendingWorkInflight == nil {
@@ -5995,6 +6003,9 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
if err := execenv.WriteGCMeta(result.EnvRoot, meta, taskLog); err != nil {
taskLog.Warn("write gc meta failed (non-fatal)", "error", err)
}
+ if meta.Kind == execenv.GCKindIssue && !meta.LocalDirectory {
+ d.environments.reportDeclared(ctx, task.ID, result.EnvRoot)
+ }
}
}
}
diff --git a/server/internal/daemon/environment_commands.go b/server/internal/daemon/environment_commands.go
new file mode 100644
index 0000000000..b4094af4a5
--- /dev/null
+++ b/server/internal/daemon/environment_commands.go
@@ -0,0 +1,243 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+ "github.com/multica-ai/multica/server/internal/daemon/localenv"
+)
+
+// Environment commands come from the issue sidebar: a member stops, restarts
+// or starts an environment, or reads its log. The server queues them and
+// sends a pending-work hint; the daemon claims them, carries them out and
+// reports each result.
+
+const (
+ environmentLogLines = 500
+ environmentLogBytes = 256 * 1024
+ environmentCommandTimeout = 90 * time.Second
+ environmentConfigsTimeout = 15 * time.Second
+)
+
+type environmentController interface {
+ ClaimEnvironmentCommands(ctx context.Context, runtimeID string) ([]EnvironmentCommand, error)
+ ReportEnvironmentCommandResult(ctx context.Context, runtimeID, commandID string, result EnvironmentCommandResult) error
+ ReportTaskEnvironmentConfigs(ctx context.Context, taskID string, envs []localenv.Declared) error
+}
+
+// claimCommands carries out the commands queued for a runtime. One claim runs
+// per runtime at a time; a hint that arrives meanwhile makes it claim again
+// when it is done.
+func (s *environmentService) claimCommands(ctx context.Context, runtimeID string) {
+ if s == nil {
+ return
+ }
+ ctl, ok := s.client.(environmentController)
+ if !ok {
+ return
+ }
+ s.mu.Lock()
+ if s.claiming[runtimeID] {
+ s.claimAgain[runtimeID] = true
+ s.mu.Unlock()
+ return
+ }
+ s.claiming[runtimeID] = true
+ s.mu.Unlock()
+ for {
+ cmds, err := ctl.ClaimEnvironmentCommands(ctx, runtimeID)
+ if err != nil && ctx.Err() == nil {
+ s.logger.Warn("environments: claim commands failed", "runtime_id", runtimeID, "error", err)
+ }
+ for _, cmd := range cmds {
+ go s.execute(ctx, ctl, runtimeID, cmd)
+ }
+ s.mu.Lock()
+ again := s.claimAgain[runtimeID]
+ delete(s.claimAgain, runtimeID)
+ if !again || ctx.Err() != nil {
+ delete(s.claiming, runtimeID)
+ s.mu.Unlock()
+ return
+ }
+ s.mu.Unlock()
+ }
+}
+
+func (s *environmentService) execute(ctx context.Context, ctl environmentController, runtimeID string, cmd EnvironmentCommand) {
+ runCtx, cancel := context.WithTimeout(ctx, environmentCommandTimeout)
+ result := s.carryOut(runCtx, cmd)
+ cancel()
+ if !result.OK {
+ s.logger.Info("environments: command failed", "action", cmd.Action, "command_id", cmd.ID, "error", result.Error)
+ }
+ reportCtx, cancelReport := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
+ defer cancelReport()
+ if err := ctl.ReportEnvironmentCommandResult(reportCtx, runtimeID, cmd.ID, result); err != nil {
+ s.logger.Warn("environments: report command result failed", "command_id", cmd.ID, "error", err)
+ }
+ if cmd.Action != "logs" {
+ s.nudge()
+ }
+}
+
+func (s *environmentService) carryOut(ctx context.Context, cmd EnvironmentCommand) EnvironmentCommandResult {
+ fail := func(err error) EnvironmentCommandResult {
+ return EnvironmentCommandResult{Error: err.Error()}
+ }
+ id, declared := localenv.IDFromKey(cmd.LocalKey)
+ if declared {
+ issueID, workspaceID, err := s.manager.RecordOwner(id)
+ if err != nil {
+ return fail(err)
+ }
+ if issueID != cmd.IssueID || workspaceID != cmd.WorkspaceID {
+ return fail(localenv.ErrUnknown)
+ }
+ }
+ switch cmd.Action {
+ case "stop":
+ if !declared {
+ return s.stopDetected(ctx, cmd)
+ }
+ if _, err := s.manager.StopID(id); err != nil {
+ return fail(err)
+ }
+ return EnvironmentCommandResult{OK: true}
+ case "restart":
+ if !declared {
+ return fail(errors.New("only environments the repository declares can be restarted"))
+ }
+ env, err := s.manager.Restart(id, s.resolve)
+ if err != nil {
+ return fail(err)
+ }
+ return EnvironmentCommandResult{OK: true, EnvironmentKey: env.Key}
+ case "start":
+ env, err := s.startDeclared(cmd)
+ if err != nil {
+ return fail(err)
+ }
+ return EnvironmentCommandResult{OK: true, EnvironmentKey: env.Key}
+ case "logs":
+ if !declared {
+ return fail(errors.New("only environments the repository declares have a log"))
+ }
+ out, err := s.manager.LogTail(id, environmentLogLines, environmentLogBytes)
+ if err != nil {
+ return fail(err)
+ }
+ return EnvironmentCommandResult{OK: true, Output: &out}
+ }
+ return fail(errors.New("this machine does not know the command " + cmd.Action))
+}
+
+// stopDetected stops a server detection found in the issue's directory. One
+// that is no longer detected has already stopped.
+func (s *environmentService) stopDetected(ctx context.Context, cmd EnvironmentCommand) EnvironmentCommandResult {
+ var target *localenv.Environment
+ s.mu.Lock()
+ for i := range s.detected {
+ if s.detected[i].Key == cmd.LocalKey && s.detected[i].IssueID == cmd.IssueID {
+ env := s.detected[i]
+ target = &env
+ break
+ }
+ }
+ s.mu.Unlock()
+ if target != nil {
+ if err := s.detector.Stop(ctx, *target); err != nil {
+ return EnvironmentCommandResult{Error: err.Error()}
+ }
+ }
+ // Detect now, so the report this triggers no longer lists it.
+ s.detect(ctx)
+ return EnvironmentCommandResult{OK: true}
+}
+
+// startDeclared starts an environment the task's repositories declare, in the
+// directory the task ran in, or the issue's latest one if that was reused.
+func (s *environmentService) startDeclared(cmd EnvironmentCommand) (localenv.Environment, error) {
+ task, ok := s.taskRoot(cmd.WorkspaceID, cmd.IssueID, cmd.TaskID)
+ if !ok {
+ return localenv.Environment{}, localenv.ErrGone
+ }
+ for _, d := range localenv.DiscoverDeclared(filepath.Join(task.RootDir, "workdir")) {
+ if d.Repo == cmd.Repo && d.Name == cmd.Name {
+ path := s.manager.LastPath(task.IssueID, task.WorkspaceID, d.Name)
+ return s.manager.Start(task, d.RepoRoot, d.Name, path)
+ }
+ }
+ return localenv.Environment{}, errors.New("the latest code on this machine no longer declares this environment")
+}
+
+// taskRoot finds the directory a task ran in: a running task's, else the one
+// whose .gc_meta.json names it, else the issue's most recent one.
+func (s *environmentService) taskRoot(workspaceID, issueID, taskID string) (localenv.Task, bool) {
+ s.mu.Lock()
+ for root, t := range s.tasks {
+ if t.TaskID == taskID && t.IssueID == issueID {
+ s.mu.Unlock()
+ t.RootDir = root
+ return t, true
+ }
+ }
+ s.mu.Unlock()
+
+ var best localenv.Task
+ var bestAt time.Time
+ for _, wsDir := range environmentSubdirs(s.workspacesRoot) {
+ for _, root := range environmentSubdirs(wsDir) {
+ meta, err := execenv.ReadGCMeta(root)
+ if err != nil || meta.Kind != execenv.GCKindIssue || meta.IssueID != issueID ||
+ meta.WorkspaceID != workspaceID || meta.LocalDirectory {
+ continue
+ }
+ task := localenv.Task{TaskID: meta.TaskID, IssueID: meta.IssueID, WorkspaceID: meta.WorkspaceID, RootDir: root}
+ if meta.TaskID == taskID {
+ return task, true
+ }
+ if best.RootDir == "" || meta.CompletedAt.After(bestAt) {
+ best, bestAt = task, meta.CompletedAt
+ }
+ }
+ }
+ return best, best.RootDir != ""
+}
+
+func environmentSubdirs(dir string) []string {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil
+ }
+ out := make([]string, 0, len(entries))
+ for _, e := range entries {
+ if e.IsDir() && !strings.HasPrefix(e.Name(), ".") {
+ out = append(out, filepath.Join(dir, e.Name()))
+ }
+ }
+ return out
+}
+
+// reportDeclared tells the server what a finished task's repositories
+// declare, so the sidebar can offer to start them from its directory.
+func (s *environmentService) reportDeclared(ctx context.Context, taskID, envRoot string) {
+ if s == nil || taskID == "" || envRoot == "" {
+ return
+ }
+ ctl, ok := s.client.(environmentController)
+ if !ok {
+ return
+ }
+ declared := localenv.DiscoverDeclared(filepath.Join(envRoot, "workdir"))
+ reportCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), environmentConfigsTimeout)
+ defer cancel()
+ if err := ctl.ReportTaskEnvironmentConfigs(reportCtx, taskID, declared); err != nil {
+ s.logger.Debug("environments: report declared environments failed", "task_id", taskID, "error", err)
+ }
+}
diff --git a/server/internal/daemon/environment_commands_unix_test.go b/server/internal/daemon/environment_commands_unix_test.go
new file mode 100644
index 0000000000..37e0e8856f
--- /dev/null
+++ b/server/internal/daemon/environment_commands_unix_test.go
@@ -0,0 +1,155 @@
+//go:build !windows
+
+package daemon
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "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 fakeEnvironmentController struct {
+ recordingEnvironmentReporter
+ mu sync.Mutex
+ queue []EnvironmentCommand
+ results map[string]EnvironmentCommandResult
+ declared map[string][]localenv.Declared
+}
+
+func (c *fakeEnvironmentController) ClaimEnvironmentCommands(context.Context, string) ([]EnvironmentCommand, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ cmds := c.queue
+ c.queue = nil
+ return cmds, nil
+}
+
+func (c *fakeEnvironmentController) ReportEnvironmentCommandResult(_ context.Context, _, commandID string, result EnvironmentCommandResult) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.results[commandID] = result
+ return nil
+}
+
+func (c *fakeEnvironmentController) ReportTaskEnvironmentConfigs(_ context.Context, taskID string, envs []localenv.Declared) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.declared[taskID] = envs
+ return nil
+}
+
+func (c *fakeEnvironmentController) run(t *testing.T, s *environmentService, cmd EnvironmentCommand) EnvironmentCommandResult {
+ t.Helper()
+ c.mu.Lock()
+ c.queue = append(c.queue, cmd)
+ c.mu.Unlock()
+ s.claimCommands(context.Background(), "runtime-1")
+ deadline := time.Now().Add(30 * time.Second)
+ for time.Now().Before(deadline) {
+ c.mu.Lock()
+ result, ok := c.results[cmd.ID]
+ c.mu.Unlock()
+ if ok {
+ return result
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ t.Fatalf("command %s was never answered", cmd.ID)
+ return EnvironmentCommandResult{}
+}
+
+func TestEnvironmentCommandsStartReadStopAndRestart(t *testing.T) {
+ ctl := &fakeEnvironmentController{results: map[string]EnvironmentCommandResult{}, declared: map[string][]localenv.Declared{}}
+ s := newEnvironmentService(Config{WorkspacesRoot: t.TempDir()}, ctl, nil, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ envRoot := filepath.Join(s.workspacesRoot, "acme-ws", "acme-1-task")
+ repo := filepath.Join(envRoot, "workdir", "app")
+ if err := os.MkdirAll(filepath.Join(repo, ".multica"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ config := "[environments.worker]\nlabel = \"Queue worker\"\nstart = \"echo worker up; exec sleep 60\"\nurl = \"\"\n"
+ if err := os.WriteFile(filepath.Join(repo, ".multica", "environments.toml"), []byte(config), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := execenv.WriteGCMeta(envRoot, execenv.GCMeta{Kind: execenv.GCKindIssue, IssueID: "issue-a", TaskID: "task-a", WorkspaceID: "ws"}, s.logger); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ for _, env := range s.manager.Snapshot() {
+ if id, ok := localenv.IDFromKey(env.Key); ok {
+ s.manager.StopID(id)
+ }
+ }
+ })
+
+ s.reportDeclared(context.Background(), "task-a", envRoot)
+ if got := ctl.declared["task-a"]; len(got) != 1 || got[0].Repo != "app" || got[0].Name != "worker" || got[0].Label != "Queue worker" {
+ t.Fatalf("declared = %+v", got)
+ }
+
+ started := ctl.run(t, s, EnvironmentCommand{ID: "c1", Action: "start", WorkspaceID: "ws", IssueID: "issue-a", TaskID: "task-a", Repo: "app", Name: "worker"})
+ if !started.OK || !strings.HasPrefix(started.EnvironmentKey, "config:") {
+ t.Fatalf("start = %+v", started)
+ }
+ key := started.EnvironmentKey
+
+ waitCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if env := s.manager.WaitReady(waitCtx, key); env.State != localenv.StateRunning {
+ t.Fatalf("started environment = %+v", env)
+ }
+
+ if other := ctl.run(t, s, EnvironmentCommand{ID: "c2", Action: "logs", WorkspaceID: "ws", IssueID: "issue-b", LocalKey: key}); other.OK {
+ t.Fatal("another issue read the environment's log")
+ }
+ var logs EnvironmentCommandResult
+ for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
+ delete(ctl.results, "c3")
+ logs = ctl.run(t, s, EnvironmentCommand{ID: "c3", Action: "logs", WorkspaceID: "ws", IssueID: "issue-a", LocalKey: key})
+ if logs.OK && logs.Output != nil && strings.Contains(*logs.Output, "worker up") {
+ break
+ }
+ }
+ if !logs.OK || logs.Output == nil || !strings.Contains(*logs.Output, "worker up") {
+ t.Fatalf("logs = %+v", logs)
+ }
+
+ restarted := ctl.run(t, s, EnvironmentCommand{ID: "c4", Action: "restart", WorkspaceID: "ws", IssueID: "issue-a", LocalKey: key})
+ if !restarted.OK || restarted.EnvironmentKey == key {
+ t.Fatalf("restart = %+v", restarted)
+ }
+ var old localenv.Environment
+ for _, env := range s.manager.Snapshot() {
+ if env.Key == key {
+ old = env
+ }
+ }
+ if old.State != localenv.StateStopped {
+ t.Fatalf("the restarted environment's old run = %+v, want stopped", old)
+ }
+
+ newID, _ := localenv.IDFromKey(restarted.EnvironmentKey)
+ if stopped := ctl.run(t, s, EnvironmentCommand{ID: "c5", Action: "stop", WorkspaceID: "ws", IssueID: "issue-a", LocalKey: restarted.EnvironmentKey}); !stopped.OK {
+ t.Fatalf("stop = %+v", stopped)
+ }
+ for _, env := range s.manager.Snapshot() {
+ if strings.HasSuffix(env.Key, newID) && env.State != localenv.StateStopped {
+ t.Fatalf("stopped environment = %+v", env)
+ }
+ }
+
+ if gone := ctl.run(t, s, EnvironmentCommand{ID: "c6", Action: "start", WorkspaceID: "ws", IssueID: "issue-z", TaskID: "task-z", Repo: "app", Name: "worker"}); gone.OK {
+ t.Fatal("started an environment for an issue with no directory on this machine")
+ }
+ if unknown := ctl.run(t, s, EnvironmentCommand{ID: "c7", Action: "reboot", WorkspaceID: "ws", IssueID: "issue-a"}); unknown.OK {
+ t.Fatal("an unknown command succeeded")
+ }
+}
diff --git a/server/internal/daemon/environments.go b/server/internal/daemon/environments.go
index 7518dee67b..802a0bd115 100644
--- a/server/internal/daemon/environments.go
+++ b/server/internal/daemon/environments.go
@@ -57,6 +57,10 @@ type environmentService struct {
sticky map[string]string
// reported is owned by the report loop: task ID → the last snapshot sent.
reported map[string]reportedSnapshot
+ // claiming marks runtimes with a command claim in flight; claimAgain
+ // asks that claim to run once more for a hint that arrived meanwhile.
+ claiming map[string]bool
+ claimAgain map[string]bool
}
type reportedSnapshot struct {
@@ -84,6 +88,8 @@ func newEnvironmentService(cfg Config, client environmentReporter, ignoreCommand
tasks: make(map[string]localenv.Task),
sticky: make(map[string]string),
reported: make(map[string]reportedSnapshot),
+ claiming: make(map[string]bool),
+ claimAgain: make(map[string]bool),
}
}
@@ -376,7 +382,7 @@ func environmentFingerprint(envs []localenv.Environment) string {
if env.ExpiresAt != nil {
expires = env.ExpiresAt.UTC().Format(time.RFC3339)
}
- parts = append(parts, strings.Join([]string{env.Key, env.Kind, env.State, env.URL, env.Label, env.Detail, expires}, "\x1f"))
+ parts = append(parts, strings.Join([]string{env.Key, env.Kind, env.Repo, env.State, env.URL, env.Label, env.Detail, expires, env.Excerpt}, "\x1f"))
}
sort.Strings(parts)
return strings.Join(parts, "\x1e")
@@ -386,8 +392,9 @@ 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, Kind: env.Kind, Name: env.Name, Label: env.Label, URL: env.URL,
+ Key: env.Key, Source: env.Source, Kind: env.Kind, Repo: env.Repo, Name: env.Name, Label: env.Label, URL: env.URL,
Port: env.Port, State: env.State, Detail: env.Detail, StartedAt: env.StartedAt, ExpiresAt: env.ExpiresAt,
+ Excerpt: env.Excerpt,
})
}
return out
diff --git a/server/internal/daemon/environments_unix_test.go b/server/internal/daemon/environments_unix_test.go
index 94b758f8fc..d6df772367 100644
--- a/server/internal/daemon/environments_unix_test.go
+++ b/server/internal/daemon/environments_unix_test.go
@@ -72,7 +72,9 @@ func TestEnvironmentHandlersStartListAndStop(t *testing.T) {
}
}
-func TestEnvironmentReportKeepsACrashedEnvironmentsOutputLocal(t *testing.T) {
+// The full output stays in the local log; only a short excerpt of a crash is
+// reported, which the server redacts before storing.
+func TestEnvironmentReportSendsOnlyACrashExcerpt(t *testing.T) {
const secret = "fake-password-for-tests"
s, reporter := newTestEnvironmentService(t)
root := t.TempDir()
@@ -101,8 +103,9 @@ func TestEnvironmentReportKeepsACrashedEnvironmentsOutputLocal(t *testing.T) {
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 got := calls[0].envs[0]; got.State != localenv.StateExited || got.Detail != "exit status 3" ||
+ !strings.HasPrefix(got.Excerpt, "cannot reach postgres://") {
+ t.Fatalf("reported %+v, want exited with its exit status and last output line", 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/localenv/control.go b/server/internal/daemon/localenv/control.go
new file mode 100644
index 0000000000..1f2645999d
--- /dev/null
+++ b/server/internal/daemon/localenv/control.go
@@ -0,0 +1,283 @@
+package localenv
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sort"
+ "strings"
+)
+
+// The sidebar controls an environment by the id in its key, possibly after
+// the manager has forgotten it: the record stays on disk next to its log.
+
+var idRE = regexp.MustCompile(`^[0-9a-f]{16}$`)
+
+const (
+ excerptLines = 2
+ excerptLineMax = 240
+ excerptReadSize = 16 * 1024
+)
+
+// IDFromKey returns the record id in a config environment's key.
+func IDFromKey(key string) (string, bool) {
+ id, ok := strings.CutPrefix(key, "config:")
+ return id, ok && idRE.MatchString(id)
+}
+
+// lookup finds a record in memory, else on disk. The entry is nil for a
+// record the manager no longer keeps.
+func (m *Manager) lookup(id string) (record, *entry, error) {
+ if !idRE.MatchString(id) {
+ return record{}, nil, ErrUnknown
+ }
+ m.mu.Lock()
+ e := m.envs[id]
+ if e != nil {
+ rec := e.rec
+ m.mu.Unlock()
+ return rec, e, nil
+ }
+ m.mu.Unlock()
+ data, err := os.ReadFile(filepath.Join(m.dir, id, stateFile))
+ if err != nil {
+ return record{}, nil, ErrUnknown
+ }
+ var rec record
+ if err := json.Unmarshal(data, &rec); err != nil || rec.ID != id {
+ return record{}, nil, ErrUnknown
+ }
+ return rec, nil, nil
+}
+
+// RecordOwner reports the issue and workspace an environment belongs to.
+func (m *Manager) RecordOwner(id string) (issueID, workspaceID string, err error) {
+ rec, _, err := m.lookup(id)
+ return rec.IssueID, rec.WorkspaceID, err
+}
+
+// StopID stops a live environment by id. Stopping one that already ended is
+// not an error.
+func (m *Manager) StopID(id string) (Environment, error) {
+ rec, e, err := m.lookup(id)
+ if err != nil {
+ return Environment{}, err
+ }
+ if e == nil {
+ return Environment{Key: "config:" + rec.ID, Name: rec.Name, State: rec.State}, nil
+ }
+ m.stop(e, "")
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.viewLocked(e), nil
+}
+
+// Restart stops the environment if it is still live and starts it again from
+// the same repository, with the same name and PATH. resolve maps the
+// repository to the task that now owns its directory; the restarted
+// environment is reported under that task.
+func (m *Manager) Restart(id string, resolve func(dir string) (Task, bool)) (Environment, error) {
+ rec, e, err := m.lookup(id)
+ if err != nil {
+ return Environment{}, err
+ }
+ if e != nil {
+ m.stop(e, "")
+ }
+ if _, err := os.Stat(filepath.Join(rec.RepoRoot, filepath.FromSlash(ConfigPath))); err != nil {
+ return Environment{}, ErrGone
+ }
+ task, ok := resolve(rec.RepoRoot)
+ if !ok {
+ task = Task{TaskID: rec.TaskID, IssueID: rec.IssueID, WorkspaceID: rec.WorkspaceID, RootDir: rec.RepoRoot}
+ }
+ if task.IssueID != rec.IssueID || task.WorkspaceID != rec.WorkspaceID {
+ return Environment{}, errors.New("the environment's directory now belongs to another issue")
+ }
+ return m.Start(task, rec.RepoRoot, rec.Name, rec.Path)
+}
+
+// LastPath returns the PATH the most recent environment with this name on
+// the issue was started with, so a start from the sidebar finds the same
+// tools as one an agent ran.
+func (m *Manager) LastPath(issueID, workspaceID, name string) string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var best *record
+ for _, e := range m.envs {
+ rec := e.rec
+ if rec.IssueID != issueID || rec.WorkspaceID != workspaceID || rec.Path == "" {
+ continue
+ }
+ if best == nil || (rec.Name == name && best.Name != name) ||
+ ((rec.Name == name) == (best.Name == name) && rec.StartedAt.After(best.StartedAt)) {
+ best = &rec
+ }
+ }
+ if best == nil {
+ return ""
+ }
+ return best.Path
+}
+
+// LogTail returns the end of an environment's output: at most maxLines lines
+// and maxBytes bytes, starting on a line boundary.
+func (m *Manager) LogTail(id string, maxLines, maxBytes int) (string, error) {
+ if _, _, err := m.lookup(id); err != nil {
+ return "", err
+ }
+ data, err := readTail(filepath.Join(m.dir, id, outputFile), int64(maxBytes))
+ if errors.Is(err, os.ErrNotExist) {
+ return "", nil
+ }
+ if err != nil {
+ return "", fmt.Errorf("read environment log: %w", err)
+ }
+ return string(lastLines(data, maxLines)), nil
+}
+
+func readTail(path string, max int64) ([]byte, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ info, err := f.Stat()
+ if err != nil {
+ return nil, err
+ }
+ offset := int64(0)
+ if info.Size() > max {
+ offset = info.Size() - max
+ }
+ if _, err := f.Seek(offset, io.SeekStart); err != nil {
+ return nil, err
+ }
+ data, err := io.ReadAll(io.LimitReader(f, max))
+ if err != nil {
+ return nil, err
+ }
+ if offset > 0 {
+ // Drop the partial first line.
+ if i := bytes.IndexByte(data, '\n'); i >= 0 {
+ data = data[i+1:]
+ }
+ }
+ return data, nil
+}
+
+func lastLines(data []byte, n int) []byte {
+ data = bytes.TrimRight(data, "\n")
+ count := 0
+ for i := len(data) - 1; i >= 0; i-- {
+ if data[i] == '\n' {
+ count++
+ if count == n {
+ return data[i+1:]
+ }
+ }
+ }
+ return data
+}
+
+// logExcerpt returns the last non-empty lines of a log, each shortened.
+func logExcerpt(path string) string {
+ data, err := readTail(path, excerptReadSize)
+ if err != nil {
+ return ""
+ }
+ var lines []string
+ for _, line := range strings.Split(string(data), "\n") {
+ line = strings.TrimSpace(stripANSI(line))
+ if line == "" {
+ continue
+ }
+ if r := []rune(line); len(r) > excerptLineMax {
+ line = string(r[:excerptLineMax]) + "…"
+ }
+ lines = append(lines, line)
+ }
+ if len(lines) > excerptLines {
+ lines = lines[len(lines)-excerptLines:]
+ }
+ return strings.Join(lines, "\n")
+}
+
+var ansiRE = regexp.MustCompile(`\x1b\[[0-9;?]*[ -/]*[@-~]`)
+
+func stripANSI(s string) string { return ansiRE.ReplaceAllString(s, "") }
+
+// Declared is one environment a repository declares, as the sidebar offers it.
+type Declared struct {
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+ Label string `json:"label"`
+ Start string `json:"start"`
+ // RepoRoot is local; it is never reported.
+ RepoRoot string `json:"-"`
+}
+
+// DiscoverDeclared finds the environments declared by the repositories in a
+// task's working directory: the directory itself and up to two levels below
+// it, where checkouts live.
+func DiscoverDeclared(workDir string) []Declared {
+ var out []Declared
+ seen := make(map[string]bool)
+ visit := func(dir string) {
+ data, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(ConfigPath)))
+ if err != nil {
+ return
+ }
+ cfg, err := ParseConfig(data)
+ if err != nil {
+ return
+ }
+ repo := filepath.Base(dir)
+ for _, name := range cfg.Names() {
+ if seen[repo+"\x00"+name] {
+ continue
+ }
+ seen[repo+"\x00"+name] = true
+ def := cfg.Environments[name]
+ out = append(out, Declared{Repo: repo, Name: name, Label: def.Label, Start: def.Start, RepoRoot: dir})
+ }
+ }
+ visit(workDir)
+ for _, child := range subdirs(workDir) {
+ visit(child)
+ for _, grandchild := range subdirs(child) {
+ visit(grandchild)
+ }
+ }
+ sort.SliceStable(out, func(i, j int) bool {
+ if out[i].Repo != out[j].Repo {
+ return out[i].Repo < out[j].Repo
+ }
+ return out[i].Name < out[j].Name
+ })
+ return out
+}
+
+func subdirs(dir string) []string {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil
+ }
+ var out []string
+ for _, e := range entries {
+ name := e.Name()
+ if !e.IsDir() || strings.HasPrefix(name, ".") || name == "node_modules" {
+ continue
+ }
+ out = append(out, filepath.Join(dir, name))
+ if len(out) == 50 {
+ break
+ }
+ }
+ return out
+}
diff --git a/server/internal/daemon/localenv/control_test.go b/server/internal/daemon/localenv/control_test.go
new file mode 100644
index 0000000000..53fbcee1b2
--- /dev/null
+++ b/server/internal/daemon/localenv/control_test.go
@@ -0,0 +1,247 @@
+//go:build !windows
+
+package localenv
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestIDFromKeyRejectsAnythingButARecordID(t *testing.T) {
+ if id, ok := IDFromKey("config:0123456789abcdef"); !ok || id != "0123456789abcdef" {
+ t.Fatalf("IDFromKey(valid) = %q, %v", id, ok)
+ }
+ for _, key := range []string{"detected:0123456789abcdef", "config:../state", "config:", "config:0123456789ABCDEF"} {
+ if _, ok := IDFromKey(key); ok {
+ t.Fatalf("IDFromKey(%q) accepted", key)
+ }
+ }
+}
+
+func TestManagerKeepsACrashExcerpt(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 || !strings.HasPrefix(env.Excerpt, "boom: cannot reach") {
+ t.Fatalf("crashed environment = %+v, want its last output line as the excerpt", env)
+ }
+}
+
+func TestManagerControlsAnEnvironmentByID(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)
+ id, _ := IDFromKey(env.Key)
+
+ if issueID, workspaceID, err := m.RecordOwner(id); err != nil || issueID != task.IssueID || workspaceID != task.WorkspaceID {
+ t.Fatalf("Owner = %q, %q, %v", issueID, workspaceID, err)
+ }
+ out, err := m.LogTail(id, 10, 4096)
+ if err != nil || !strings.Contains(out, "serving web") {
+ t.Fatalf("LogTail = %q, %v", out, err)
+ }
+
+ restarted, err := m.Restart(id, func(string) (Task, bool) { return task, true })
+ if err != nil {
+ t.Fatalf("Restart: %v", err)
+ }
+ if restarted.Key == env.Key {
+ t.Fatal("a restart starts a new environment")
+ }
+ restarted = waitReady(t, m, restarted.Key)
+ if restarted.State != StateRunning || restarted.Name != "web" {
+ t.Fatalf("restarted environment = %+v", restarted)
+ }
+ if groupAlive(env.pgid) {
+ t.Fatal("the restarted environment's old process group is still alive")
+ }
+
+ newID, _ := IDFromKey(restarted.Key)
+ stopped, err := m.StopID(newID)
+ if err != nil || stopped.State != StateStopped {
+ t.Fatalf("StopID = %+v, %v", stopped, err)
+ }
+ if _, err := m.StopID(newID); err != nil {
+ t.Fatalf("stopping an ended environment again = %v, want no error", err)
+ }
+}
+
+func TestManagerRestartsAndReadsAForgottenEnvironment(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)
+ id, _ := IDFromKey(env.Key)
+ if _, err := m.StopID(id); err != nil {
+ t.Fatalf("StopID: %v", err)
+ }
+ later := time.Now().Add(endedRetention + time.Minute)
+ m.now = func() time.Time { return later }
+ m.Tick()
+ for _, e := range m.Snapshot() {
+ if e.Key == env.Key {
+ t.Fatal("an ended environment past retention is still in the snapshot")
+ }
+ }
+
+ if out, err := m.LogTail(id, 10, 4096); err != nil || !strings.Contains(out, "serving web") {
+ t.Fatalf("LogTail after the record left memory = %q, %v", out, err)
+ }
+ m.now = time.Now
+ restarted, err := m.Restart(id, func(string) (Task, bool) { return task, true })
+ if err != nil {
+ t.Fatalf("Restart after the record left memory: %v", err)
+ }
+ if restarted = waitReady(t, m, restarted.Key); restarted.State != StateRunning {
+ t.Fatalf("restarted environment = %+v", restarted)
+ }
+}
+
+func TestManagerRestartRefusesAnotherIssuesDirectory(t *testing.T) {
+ m, task := newTestManager(t)
+ env, err := m.Start(task, task.RootDir, "broken", "")
+ if err != nil {
+ t.Fatalf("Start: %v", err)
+ }
+ waitReady(t, m, env.Key)
+ id, _ := IDFromKey(env.Key)
+ other := task
+ other.IssueID = "issue-2"
+ if _, err := m.Restart(id, func(string) (Task, bool) { return other, true }); err == nil {
+ t.Fatal("Restart started an environment under another issue")
+ }
+}
+
+func TestManagerRestartReportsCleanedUpCode(t *testing.T) {
+ m, task := newTestManager(t)
+ env, err := m.Start(task, task.RootDir, "broken", "")
+ if err != nil {
+ t.Fatalf("Start: %v", err)
+ }
+ waitReady(t, m, env.Key)
+ id, _ := IDFromKey(env.Key)
+ if err := os.RemoveAll(filepath.Join(task.RootDir, ".multica")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := m.Restart(id, func(string) (Task, bool) { return task, true }); err != ErrGone {
+ t.Fatalf("Restart = %v, want ErrGone", err)
+ }
+}
+
+func TestManagerUnknownIDs(t *testing.T) {
+ m, _ := newTestManager(t)
+ if _, err := m.LogTail("0123456789abcdef", 10, 100); err != ErrUnknown {
+ t.Fatalf("LogTail(unknown) = %v, want ErrUnknown", err)
+ }
+ if _, err := m.LogTail("../../etc", 10, 100); err != ErrUnknown {
+ t.Fatalf("LogTail(path) = %v, want ErrUnknown", err)
+ }
+}
+
+func TestLastLinesAndTailBoundaries(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "output.log")
+ var b strings.Builder
+ for i := 1; i <= 100; i++ {
+ fmt.Fprintf(&b, "line %03d\n", i)
+ }
+ if err := os.WriteFile(path, []byte(b.String()), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ data, err := readTail(path, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := string(lastLines(data, 500)); got != "line 098\nline 099\nline 100" {
+ t.Fatalf("byte-capped tail = %q, want whole lines only", got)
+ }
+ data, _ = readTail(path, 1<<20)
+ if got := string(lastLines(data, 2)); got != "line 099\nline 100" {
+ t.Fatalf("line-capped tail = %q", got)
+ }
+}
+
+func TestDiscoverDeclaredFindsCheckoutsInTheWorkdir(t *testing.T) {
+ workdir := t.TempDir()
+ writeConfig(t, filepath.Join(workdir, "app"), `
+[environments.web]
+label = "Web app"
+start = "make web"
+
+[environments.api]
+start = "make server"
+`)
+ writeConfig(t, filepath.Join(workdir, "node_modules", "pkg"), `
+[environments.ignored]
+start = "true"
+`)
+ got := DiscoverDeclared(workdir)
+ if len(got) != 2 || got[0].Name != "api" || got[1].Name != "web" || got[0].Repo != "app" ||
+ got[1].Label != "Web app" || got[0].Start != "make server" || got[0].RepoRoot != filepath.Join(workdir, "app") {
+ t.Fatalf("DiscoverDeclared = %+v", got)
+ }
+ if DiscoverDeclared(filepath.Join(workdir, "missing")) != nil {
+ t.Fatal("a missing workdir declares nothing")
+ }
+}
+
+func TestDetectorStopsOnlyTheListeningProcess(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()
+ cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcess$")
+ cmd.Env = append(os.Environ(), "LOCALENV_HELPER=serve", fmt.Sprintf("MULTICA_PORT=%d", port))
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan struct{})
+ go func() { cmd.Wait(); close(done) }()
+ t.Cleanup(func() { cmd.Process.Kill(); <-done })
+
+ listening := true
+ d := NewDetector(nil)
+ d.list = func(context.Context) ([]Listener, error) {
+ if !listening {
+ return nil, nil
+ }
+ select {
+ case <-done:
+ listening = false
+ return nil, nil
+ default:
+ return []Listener{{PID: cmd.Process.Pid, Port: port}}, nil
+ }
+ }
+ env := Environment{Source: SourceDetected, Name: "helper", Port: port, pid: cmd.Process.Pid}
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ if err := d.Stop(ctx, env); err != nil {
+ t.Fatalf("Stop: %v", err)
+ }
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the listening process is still running")
+ }
+
+ if err := d.Stop(ctx, Environment{Source: SourceDetected, Port: port, pid: os.Getpid()}); err != ErrUnknown {
+ t.Fatalf("Stop(self) = %v, want ErrUnknown", err)
+ }
+}
diff --git a/server/internal/daemon/localenv/detect.go b/server/internal/daemon/localenv/detect.go
index 197fb98207..b95b37adec 100644
--- a/server/internal/daemon/localenv/detect.go
+++ b/server/internal/daemon/localenv/detect.go
@@ -5,11 +5,14 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
+ "errors"
"fmt"
+ "os"
"sort"
"strconv"
"strings"
"sync"
+ "syscall"
"time"
)
@@ -163,7 +166,7 @@ func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, b
found[key] = Environment{
Key: key, TaskID: c.task.TaskID, IssueID: c.task.IssueID, Source: SourceDetected, Kind: KindServer,
Name: truncateName(c.Command), URL: fmt.Sprintf("http://localhost:%d", c.Port), Port: c.Port, State: StateRunning,
- Dir: c.task.RootDir,
+ Dir: c.task.RootDir, pid: c.PID,
}
}
for key, ports := range debugPorts {
@@ -296,6 +299,57 @@ func truncateName(name string) string {
return name
}
+// Stop ends a detected server and waits for its port to be released. It
+// signals the listening process only, never its process group: a server an
+// agent started in the background shares the agent's group.
+func (d *Detector) Stop(ctx context.Context, env Environment) error {
+ if !supported {
+ return ErrUnsupported
+ }
+ if env.Source != SourceDetected || env.pid <= 0 || env.pid == os.Getpid() {
+ return ErrUnknown
+ }
+ listening := func() bool {
+ listeners, err := d.list(ctx)
+ if err != nil {
+ return true
+ }
+ for _, l := range listeners {
+ if l.PID == env.pid && l.Port == env.Port {
+ return true
+ }
+ }
+ return false
+ }
+ // The process may have exited, and its pid been reused, since detection.
+ if !listening() {
+ return nil
+ }
+ for _, step := range []struct {
+ sig syscall.Signal
+ wait time.Duration
+ }{{syscall.SIGTERM, stopGrace}, {syscall.SIGKILL, 2 * time.Second}} {
+ if err := signalProcess(env.pid, step.sig); err != nil {
+ if errors.Is(err, syscall.ESRCH) {
+ return nil
+ }
+ return fmt.Errorf("stop %s: %w", env.Name, err)
+ }
+ deadline := time.Now().Add(step.wait)
+ for time.Now().Before(deadline) {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(500 * time.Millisecond):
+ }
+ if !listening() {
+ return nil
+ }
+ }
+ }
+ return fmt.Errorf("%s is still listening on port %d", env.Name, env.Port)
+}
+
// detectedKey is stable across restarts of the same server, and carries no
// local path to the server.
func detectedKey(root string, port int) string {
diff --git a/server/internal/daemon/localenv/detect_system_test.go b/server/internal/daemon/localenv/detect_system_test.go
index 07876b8dd9..2140b9f858 100644
--- a/server/internal/daemon/localenv/detect_system_test.go
+++ b/server/internal/daemon/localenv/detect_system_test.go
@@ -60,8 +60,19 @@ func TestInspectProcessesReadsArgumentsOfAProcessWithoutWindows(t *testing.T) {
}
t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
- procs := inspectProcesses(context.Background(), []int{cmd.Process.Pid})
- p, ok := procs[cmd.Process.Pid]
+ // Start can return while the kernel is still finishing the exec, before
+ // /proc/<pid>/cmdline holds the new arguments.
+ var procs map[int]Process
+ var p Process
+ var ok bool
+ for deadline := time.Now().Add(5 * time.Second); ; {
+ procs = inspectProcesses(context.Background(), []int{cmd.Process.Pid})
+ p, ok = procs[cmd.Process.Pid]
+ if (ok && p.debugs(9333)) || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
if !ok || !p.debugs(9333) {
t.Fatalf("inspected = %+v, want the arguments the process was started with", procs)
}
diff --git a/server/internal/daemon/localenv/manager.go b/server/internal/daemon/localenv/manager.go
index acdee86cd2..57451ced30 100644
--- a/server/internal/daemon/localenv/manager.go
+++ b/server/internal/daemon/localenv/manager.go
@@ -40,7 +40,8 @@ const (
outputFile = "output.log"
// An ended environment stays in the snapshot long enough to be reported
- // as ended, then only its log is kept.
+ // as ended. Its record stays on disk with its log, so it can still be
+ // restarted or read from the sidebar.
endedRetention = time.Hour
logRetention = 7 * 24 * time.Hour
readyTimeout = 10 * time.Minute
@@ -54,6 +55,13 @@ var ErrUnsupported = errors.New("local environments are not supported on this pl
// ErrNotFound means no live environment of that name belongs to the task.
var ErrNotFound = errors.New("no running environment with that name")
+// ErrUnknown means this daemon has no record of the environment, or no
+// longer keeps it.
+var ErrUnknown = errors.New("this machine no longer has a record of the environment")
+
+// ErrGone means the code an environment ran from has been cleaned up.
+var ErrGone = errors.New("the code this environment ran from has been cleaned up")
+
// 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 {
@@ -65,11 +73,14 @@ type Task struct {
// 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"`
- Kind string `json:"kind,omitempty"`
+ Key string `json:"key"`
+ TaskID string `json:"task_id"`
+ IssueID string `json:"issue_id"`
+ Source string `json:"source"`
+ Kind string `json:"kind,omitempty"`
+ // Repo names the checkout a declared environment runs from, as
+ // DiscoverDeclared does, so two repositories can declare the same name.
+ Repo string `json:"repo,omitempty"`
Name string `json:"name"`
Label string `json:"label"`
URL string `json:"url"`
@@ -79,12 +90,15 @@ type Environment struct {
StartedAt time.Time `json:"started_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
LogPath string `json:"log_path,omitempty"`
+ // Excerpt is the last lines a crashed environment printed, so the
+ // sidebar can say why it crashed; the server redacts it before storing.
+ Excerpt string `json:"excerpt,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
- // pid and bundle name a detected app's process for Focus; like Dir they
- // never leave this machine.
+ // pid names a detected environment's process, for Stop and Focus; bundle
+ // names a detected app for Focus. Like Dir they never leave this machine.
pid int
bundle string
}
@@ -106,6 +120,7 @@ type record struct {
Path string `json:"path"`
State string `json:"state"`
Detail string `json:"detail"`
+ Excerpt string `json:"excerpt,omitempty"`
StartedAt time.Time `json:"started_at"`
ExpiresAt time.Time `json:"expires_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
@@ -173,6 +188,9 @@ func (m *Manager) Load() error {
if err := json.Unmarshal(data, &rec); err != nil || rec.ID != d.Name() {
continue
}
+ if rec.EndedAt != nil && m.now().Sub(*rec.EndedAt) > endedRetention {
+ continue
+ }
m.envs[rec.ID] = &entry{rec: rec}
}
// Every record is loaded before any is ended, so a dead environment's
@@ -353,7 +371,6 @@ func (m *Manager) Tick() {
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
@@ -529,6 +546,9 @@ func (m *Manager) endLocked(e *entry, state, detail string) {
e.rec.State = state
e.rec.Detail = detail
e.rec.EndedAt = &now
+ if state == StateExited {
+ e.rec.Excerpt = logExcerpt(filepath.Join(m.dir, e.rec.ID, outputFile))
+ }
m.persistLocked(e)
if heir := m.heirLocked(e); heir != nil {
heir.rec.Adopted = append(heir.rec.Adopted, e.rec.PID)
@@ -573,8 +593,8 @@ func (m *Manager) viewLocked(e *entry) Environment {
rec := e.rec
view := Environment{
Key: "config:" + rec.ID, TaskID: rec.TaskID, IssueID: rec.IssueID,
- Source: SourceConfig, Kind: KindServer, Name: rec.Name, Label: rec.Label, URL: rec.URL, Port: rec.Port,
- State: rec.State, Detail: rec.Detail, StartedAt: rec.StartedAt,
+ Source: SourceConfig, Kind: KindServer, Repo: filepath.Base(rec.RepoRoot), Name: rec.Name, Label: rec.Label, URL: rec.URL, Port: rec.Port,
+ State: rec.State, Detail: rec.Detail, Excerpt: rec.Excerpt, StartedAt: rec.StartedAt,
LogPath: filepath.Join(m.dir, rec.ID, outputFile), Dir: rec.RepoRoot, pgid: rec.PID,
}
if e.live() {
diff --git a/server/internal/daemon/localenv/manager_test.go b/server/internal/daemon/localenv/manager_test.go
index 78ea9edda8..e01f1c97bf 100644
--- a/server/internal/daemon/localenv/manager_test.go
+++ b/server/internal/daemon/localenv/manager_test.go
@@ -97,6 +97,11 @@ func TestManagerStartsSupervisesAndStops(t *testing.T) {
if env.State != StateRunning || env.Label != "Web app" || env.URL != fmt.Sprintf("http://localhost:%d", env.Port) {
t.Fatalf("started environment = %+v", env)
}
+ // The repository is named as DiscoverDeclared names it, so the sidebar
+ // can match the two.
+ if want := filepath.Base(task.RootDir); env.Repo != want {
+ t.Fatalf("Repo = %q, want %q", env.Repo, want)
+ }
if env.ExpiresAt == nil || env.ExpiresAt.Sub(env.StartedAt) != DefaultTTL {
t.Fatalf("ExpiresAt = %v, want start + %s", env.ExpiresAt, DefaultTTL)
}
diff --git a/server/internal/daemon/localenv/proc_unix.go b/server/internal/daemon/localenv/proc_unix.go
index 22e8b8cbda..4ca64bb24e 100644
--- a/server/internal/daemon/localenv/proc_unix.go
+++ b/server/internal/daemon/localenv/proc_unix.go
@@ -42,6 +42,13 @@ func groupAlive(pgid int) bool {
return err == nil || errors.Is(err, syscall.EPERM)
}
+func signalProcess(pid int, sig syscall.Signal) error {
+ if pid <= 0 {
+ return errors.New("invalid process")
+ }
+ return syscall.Kill(pid, sig)
+}
+
func processGroup(pid int) int {
pgid, err := syscall.Getpgid(pid)
if err != nil {
diff --git a/server/internal/daemon/localenv/proc_windows.go b/server/internal/daemon/localenv/proc_windows.go
index 92d9a628d7..ccc78ffa47 100644
--- a/server/internal/daemon/localenv/proc_windows.go
+++ b/server/internal/daemon/localenv/proc_windows.go
@@ -15,6 +15,8 @@ func setProcessGroup(*exec.Cmd) {}
func signalGroup(int, syscall.Signal) error { return ErrUnsupported }
+func signalProcess(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.go
index a7f4ae3ec6..96273c0021 100644
--- a/server/internal/handler/issue_environment.go
+++ b/server/internal/handler/issue_environment.go
@@ -14,6 +14,7 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
+ "github.com/multica-ai/multica/server/pkg/redact"
)
const (
@@ -21,8 +22,9 @@ const (
// 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
+ issueEnvironmentHistoryWindow = 7 * 24 * time.Hour
maxIssueEnvironmentsPerSnapshot = 50
+ maxIssueEnvironmentExcerpt = 600
)
var issueEnvironmentSources = map[string]bool{"config": true, "detected": true}
@@ -38,9 +40,11 @@ const (
// IssueEnvironmentReport is one environment in a daemon's per-task snapshot.
type IssueEnvironmentReport struct {
- Key string `json:"key"`
- Source string `json:"source"`
- Kind string `json:"kind"`
+ Key string `json:"key"`
+ Source string `json:"source"`
+ Kind string `json:"kind"`
+ // Repo is the checkout directory a declared environment runs from.
+ Repo string `json:"repo,omitempty"`
Name string `json:"name"`
Label string `json:"label"`
URL string `json:"url"`
@@ -49,37 +53,59 @@ type IssueEnvironmentReport struct {
Detail string `json:"detail"`
StartedAt time.Time `json:"started_at"`
ExpiresAt *time.Time `json:"expires_at"`
+ // Excerpt is the last lines a crashed environment printed.
+ Excerpt string `json:"excerpt,omitempty"`
}
type ReportTaskEnvironmentsRequest struct {
Environments []IssueEnvironmentReport `json:"environments"`
+ // Controllable is set by daemons that claim environment commands.
+ Controllable bool `json:"controllable,omitempty"`
}
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"`
+ ID string `json:"id"`
+ IssueID string `json:"issue_id"`
+ TaskID string `json:"task_id"`
+ RuntimeID *string `json:"runtime_id"`
+ AgentID *string `json:"agent_id"`
// LocalKey is how the daemon that reported the environment names it, so
// Desktop on that machine can ask the daemon to act on it.
- LocalKey string `json:"local_key"`
- Source string `json:"source"`
- Kind string `json:"kind"`
- 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"`
+ LocalKey string `json:"local_key"`
+ Source string `json:"source"`
+ Kind string `json:"kind"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+ Label string `json:"label"`
+ URL string `json:"url"`
+ Port *int32 `json:"port"`
+ State string `json:"state"`
+ Detail string `json:"detail"`
+ Excerpt string `json:"excerpt"`
+ StartedAt string `json:"started_at"`
+ ExpiresAt *string `json:"expires_at"`
+ LastSeenAt string `json:"last_seen_at"`
+ EndedAt *string `json:"ended_at"`
+ Controllable bool `json:"controllable"`
+ // CanControl says whether the caller may stop or restart it.
+ CanControl bool `json:"can_control"`
+ // PendingAction is a stop or restart the machine has not finished yet.
+ PendingAction *IssueEnvironmentActionResponse `json:"pending_action"`
+ // LastAction is the most recent finished stop or restart of this row.
+ LastAction *IssueEnvironmentActionResponse `json:"last_action"`
+ // Origin is the sidebar start or restart that created this row.
+ Origin *IssueEnvironmentActionResponse `json:"origin"`
}
type IssueEnvironmentsResponse struct {
Environments []IssueEnvironmentResponse `json:"environments"`
+ // Configs lists, per machine, what the latest run's repositories declare.
+ Configs []IssueEnvironmentConfigResponse `json:"configs"`
+ // PendingStarts are sidebar starts whose environment has not appeared yet.
+ PendingStarts []IssueEnvironmentActionResponse `json:"pending_starts"`
+ // FailedStarts are recent sidebar starts that failed or were never
+ // answered, and have not been started again since.
+ FailedStarts []IssueEnvironmentActionResponse `json:"failed_starts"`
}
// validateIssueEnvironmentReport normalizes one reported environment and
@@ -89,6 +115,10 @@ func validateIssueEnvironmentReport(env *IssueEnvironmentReport, now time.Time)
env.Name = strings.TrimSpace(env.Name)
env.Label = strings.TrimSpace(env.Label)
env.URL = strings.TrimSpace(env.URL)
+ env.Repo = strings.TrimSpace(env.Repo)
+ if env.Source != "config" {
+ env.Repo = ""
+ }
// A daemon older than kinds sends none, and one newer than this server may
// send a kind it does not know; both are shown as a server.
if env.Kind != issueEnvironmentKindApp {
@@ -105,6 +135,8 @@ func validateIssueEnvironmentReport(env *IssueEnvironmentReport, now time.Time)
return "name must be 1-64 characters"
case utf8.RuneCountInString(env.Label) > 120:
return "label must be at most 120 characters"
+ case len(env.Repo) > maxDeclaredEnvironmentRepoLen:
+ return "repo too long"
case env.Port < 0 || env.Port > 65535:
return "port out of range"
}
@@ -117,6 +149,13 @@ func validateIssueEnvironmentReport(env *IssueEnvironmentReport, now time.Time)
if utf8.RuneCountInString(env.Detail) > 500 {
env.Detail = string([]rune(env.Detail)[:500])
}
+ env.Excerpt = redact.Text(strings.TrimSpace(env.Excerpt))
+ if utf8.RuneCountInString(env.Excerpt) > maxIssueEnvironmentExcerpt {
+ env.Excerpt = string([]rune(env.Excerpt)[:maxIssueEnvironmentExcerpt])
+ }
+ if env.State != "exited" {
+ env.Excerpt = ""
+ }
if env.StartedAt.IsZero() {
env.StartedAt = now
}
@@ -187,20 +226,23 @@ func (h *Handler) ReportTaskEnvironments(w http.ResponseWriter, r *http.Request)
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,
- Kind: env.Kind,
- Name: env.Name,
- Label: env.Label,
- Url: env.URL,
- State: env.State,
- Detail: env.Detail,
- StartedAt: pgtype.Timestamptz{Time: env.StartedAt, Valid: true},
+ WorkspaceID: wsUUID,
+ IssueID: task.IssueID,
+ TaskID: task.ID,
+ RuntimeID: task.RuntimeID,
+ AgentID: task.AgentID,
+ LocalKey: env.Key,
+ Source: env.Source,
+ Kind: env.Kind,
+ Repo: env.Repo,
+ Name: env.Name,
+ Label: env.Label,
+ Url: env.URL,
+ State: env.State,
+ Detail: env.Detail,
+ Excerpt: env.Excerpt,
+ Controllable: req.Controllable,
+ StartedAt: pgtype.Timestamptz{Time: env.StartedAt, Valid: true},
}
if env.Port > 0 {
params.Port = pgtype.Int4{Int32: int32(env.Port), Valid: true}
@@ -214,7 +256,8 @@ func (h *Handler) ReportTaskEnvironments(w http.ResponseWriter, r *http.Request)
return
}
prev, wasOpen := open[env.Key]
- if !wasOpen || prev.State != env.State || prev.Kind != env.Kind || prev.Url != env.URL || prev.Label != env.Label || prev.Detail != env.Detail {
+ if !wasOpen || prev.State != env.State || prev.Kind != env.Kind || prev.Repo != env.Repo || prev.Url != env.URL || prev.Label != env.Label || prev.Detail != env.Detail ||
+ prev.Excerpt != env.Excerpt || prev.Controllable != req.Controllable {
changed = true
}
}
@@ -262,11 +305,106 @@ func (h *Handler) ListIssueEnvironments(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusInternalServerError, "failed to list environments")
return
}
+ controls, err := h.Queries.ListIssueEnvironmentControls(r.Context(), db.ListIssueEnvironmentControlsParams{
+ IssueID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ CreatedAfter: pgtype.Timestamptz{Time: now.Add(-issueEnvironmentHistoryWindow), Valid: true},
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list environments")
+ return
+ }
+ configs, err := h.Queries.ListLatestIssueEnvironmentConfigs(r.Context(), db.ListLatestIssueEnvironmentConfigsParams{
+ IssueID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list environments")
+ return
+ }
+ canControl := h.environmentControlChecker(r, issue)
+
+ // controls is newest first, so the first match per key wins.
+ pending := make(map[string]*IssueEnvironmentActionResponse)
+ last := make(map[string]*IssueEnvironmentActionResponse)
+ origin := make(map[string]*IssueEnvironmentActionResponse)
+ pendingStarts := []IssueEnvironmentActionResponse{}
+ failedStarts := []IssueEnvironmentActionResponse{}
+ // Only the newest start of each declared environment says how it went.
+ seenStart := make(map[string]bool)
+ for _, c := range controls {
+ action := issueEnvironmentActionToResponse(c, now)
+ envID := uuidToString(c.EnvironmentID)
+ if c.ResultKey != "" && action.Status == "succeeded" {
+ if _, ok := origin[c.ResultKey]; !ok {
+ origin[c.ResultKey] = &action
+ }
+ }
+ switch {
+ case c.Action == "start":
+ startKey := uuidToString(c.RuntimeID) + "\x00" + c.Repo + "\x00" + c.Name
+ if seenStart[startKey] {
+ break
+ }
+ seenStart[startKey] = true
+ switch action.Status {
+ case "pending":
+ pendingStarts = append(pendingStarts, action)
+ case "failed", "expired":
+ if now.Sub(startEndedAt(c)) < environmentStartFailureWindow {
+ failedStarts = append(failedStarts, action)
+ }
+ }
+ case !c.EnvironmentID.Valid:
+ case action.Status == "pending":
+ if _, ok := pending[envID]; !ok {
+ pending[envID] = &action
+ }
+ default:
+ if _, ok := last[envID]; !ok {
+ last[envID] = &action
+ }
+ }
+ }
+
out := make([]IssueEnvironmentResponse, 0, len(rows))
for _, row := range rows {
- out = append(out, issueEnvironmentToResponse(row, now))
+ resp := issueEnvironmentToResponse(row, now)
+ resp.CanControl = row.Controllable && canControl(row.RuntimeID)
+ resp.PendingAction = pending[resp.ID]
+ resp.LastAction = last[resp.ID]
+ resp.Origin = origin[row.LocalKey]
+ out = append(out, resp)
+ }
+ configOut := make([]IssueEnvironmentConfigResponse, 0, len(configs))
+ for _, cfg := range configs {
+ var envs []DeclaredEnvironment
+ if err := json.Unmarshal(cfg.Environments, &envs); err != nil {
+ continue
+ }
+ configOut = append(configOut, IssueEnvironmentConfigResponse{
+ RuntimeID: uuidToString(cfg.RuntimeID),
+ TaskID: uuidToString(cfg.TaskID),
+ ReportedAt: timestampToString(cfg.ReportedAt),
+ CanControl: canControl(cfg.RuntimeID),
+ Environments: envs,
+ })
+ }
+ writeJSON(w, http.StatusOK, IssueEnvironmentsResponse{
+ Environments: out, Configs: configOut, PendingStarts: pendingStarts, FailedStarts: failedStarts,
+ })
+}
+
+// startEndedAt is when a start stopped being pending: its answer, or for one
+// never answered, the end of its pending window.
+func startEndedAt(c db.ListIssueEnvironmentControlsRow) time.Time {
+ if c.CompletedAt.Valid {
+ return c.CompletedAt.Time
+ }
+ if c.ClaimedAt.Valid {
+ return c.ClaimedAt.Time.Add(environmentCommandClaimedWindow)
}
- writeJSON(w, http.StatusOK, IssueEnvironmentsResponse{Environments: out})
+ return c.CreatedAt.Time.Add(environmentCommandPendingWindow)
}
func issueEnvironmentToResponse(row db.IssueEnvironment, now time.Time) IssueEnvironmentResponse {
@@ -275,23 +413,26 @@ func issueEnvironmentToResponse(row db.IssueEnvironment, now time.Time) IssueEnv
state = "unreachable"
}
resp := IssueEnvironmentResponse{
- ID: uuidToString(row.ID),
- IssueID: uuidToString(row.IssueID),
- TaskID: uuidToString(row.TaskID),
- RuntimeID: uuidToPtr(row.RuntimeID),
- AgentID: uuidToPtr(row.AgentID),
- LocalKey: row.LocalKey,
- Source: row.Source,
- Kind: row.Kind,
- 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),
+ ID: uuidToString(row.ID),
+ IssueID: uuidToString(row.IssueID),
+ TaskID: uuidToString(row.TaskID),
+ RuntimeID: uuidToPtr(row.RuntimeID),
+ AgentID: uuidToPtr(row.AgentID),
+ LocalKey: row.LocalKey,
+ Source: row.Source,
+ Kind: row.Kind,
+ Repo: row.Repo,
+ Name: row.Name,
+ Label: row.Label,
+ URL: row.Url,
+ State: state,
+ Detail: row.Detail,
+ Excerpt: row.Excerpt,
+ StartedAt: timestampToString(row.StartedAt),
+ ExpiresAt: timestampToPtr(row.ExpiresAt),
+ LastSeenAt: timestampToString(row.LastSeenAt),
+ EndedAt: timestampToPtr(row.EndedAt),
+ Controllable: row.Controllable,
}
if row.Port.Valid {
port := row.Port.Int32
diff --git a/server/internal/handler/issue_environment_control.go b/server/internal/handler/issue_environment_control.go
new file mode 100644
index 0000000000..f487e64861
--- /dev/null
+++ b/server/internal/handler/issue_environment_control.go
@@ -0,0 +1,628 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "regexp"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/logger"
+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+ "github.com/multica-ai/multica/server/pkg/redact"
+)
+
+// Environment commands let a member stop, restart, start or read the log of
+// an issue's environment from the sidebar. The server cannot reach a daemon
+// directly, so a command is a row the daemon claims after a pending-work hint
+// and answers with a result. Every replica sees the same rows, and control
+// rows are kept as the record of who did what.
+const (
+ // A command the daemon has not claimed in this window is reported to the
+ // member as unanswered and is never carried out afterwards.
+ environmentCommandPendingWindow = 30 * time.Second
+ // A claimed command covers a stop's grace period plus a start; past this
+ // the machine went away mid-command.
+ environmentCommandClaimedWindow = 2 * time.Minute
+ // Log reads carry output, so they are deleted soon after.
+ environmentLogCommandRetention = 10 * time.Minute
+ // A sidebar start that failed or was never answered stays in the list
+ // this long, so the member sees why and can retry it.
+ environmentStartFailureWindow = 10 * time.Minute
+
+ maxEnvironmentLogBytes = 256 * 1024
+ maxEnvironmentCommandError = 500
+ maxDeclaredEnvironments = 50
+ maxDeclaredEnvironmentStart = 500
+ maxDeclaredEnvironmentRepoLen = 200
+)
+
+var declaredEnvironmentNameRE = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,39}$`)
+
+// DeclaredEnvironment is one environment a repository declares.
+type DeclaredEnvironment struct {
+ // Repo is the repository's directory name inside the task's checkout.
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+ Label string `json:"label"`
+ // Start is the command, shown so a member knows what will run.
+ Start string `json:"start"`
+}
+
+type IssueEnvironmentConfigResponse struct {
+ RuntimeID string `json:"runtime_id"`
+ TaskID string `json:"task_id"`
+ ReportedAt string `json:"reported_at"`
+ CanControl bool `json:"can_control"`
+ Environments []DeclaredEnvironment `json:"environments"`
+}
+
+type IssueEnvironmentActionResponse struct {
+ ID string `json:"id"`
+ Action string `json:"action"`
+ // Status is pending, succeeded, failed or expired (never answered).
+ Status string `json:"status"`
+ Error string `json:"error"`
+ EnvironmentID *string `json:"environment_id"`
+ RuntimeID string `json:"runtime_id"`
+ TaskID *string `json:"task_id"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+ ActorType string `json:"actor_type"`
+ ActorID *string `json:"actor_id"`
+ CreatedAt string `json:"created_at"`
+ CompletedAt *string `json:"completed_at"`
+}
+
+type IssueEnvironmentCommandResponse struct {
+ IssueEnvironmentActionResponse
+ // Output is the log a logs command read.
+ Output *string `json:"output"`
+}
+
+type StartIssueEnvironmentRequest struct {
+ TaskID string `json:"task_id"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+}
+
+func environmentCommandStatus(status string, createdAt, claimedAt pgtype.Timestamptz, now time.Time) string {
+ switch status {
+ case "pending":
+ if now.Sub(createdAt.Time) > environmentCommandPendingWindow {
+ return "expired"
+ }
+ return "pending"
+ case "claimed":
+ if claimedAt.Valid && now.Sub(claimedAt.Time) > environmentCommandClaimedWindow {
+ return "expired"
+ }
+ return "pending"
+ }
+ return status
+}
+
+func issueEnvironmentActionToResponse(c db.ListIssueEnvironmentControlsRow, now time.Time) IssueEnvironmentActionResponse {
+ return IssueEnvironmentActionResponse{
+ ID: uuidToString(c.ID),
+ Action: c.Action,
+ Status: environmentCommandStatus(c.Status, c.CreatedAt, c.ClaimedAt, now),
+ Error: c.Error,
+ EnvironmentID: uuidToPtr(c.EnvironmentID),
+ RuntimeID: uuidToString(c.RuntimeID),
+ TaskID: uuidToPtr(c.TaskID),
+ Repo: c.Repo,
+ Name: c.Name,
+ ActorType: c.ActorType,
+ ActorID: uuidToPtr(c.ActorID),
+ CreatedAt: timestampToString(c.CreatedAt),
+ CompletedAt: timestampToPtr(c.CompletedAt),
+ }
+}
+
+func issueEnvironmentCommandToResponse(c db.IssueEnvironmentCommand, now time.Time) IssueEnvironmentCommandResponse {
+ resp := IssueEnvironmentCommandResponse{IssueEnvironmentActionResponse: issueEnvironmentActionToResponse(db.ListIssueEnvironmentControlsRow{
+ ID: c.ID, WorkspaceID: c.WorkspaceID, IssueID: c.IssueID, RuntimeID: c.RuntimeID,
+ EnvironmentID: c.EnvironmentID, TaskID: c.TaskID, Action: c.Action, LocalKey: c.LocalKey,
+ Repo: c.Repo, Name: c.Name, ActorType: c.ActorType, ActorID: c.ActorID, Status: c.Status,
+ Error: c.Error, ResultKey: c.ResultKey, CreatedAt: c.CreatedAt, ClaimedAt: c.ClaimedAt,
+ CompletedAt: c.CompletedAt,
+ }, now)}
+ if c.Action == "logs" && c.Status == "succeeded" && c.Output.Valid {
+ output := c.Output.String
+ resp.Output = &output
+ }
+ return resp
+}
+
+// environmentControlChecker reports, per runtime, whether the caller may stop,
+// restart or start environments on it: a human member who may use the
+// machine. Private machines stay their owner's, as for running agents on them.
+func (h *Handler) environmentControlChecker(r *http.Request, issue db.Issue) func(pgtype.UUID) bool {
+ if isMachineCredentialActor(r) {
+ return func(pgtype.UUID) bool { return false }
+ }
+ member, err := h.getWorkspaceMember(r.Context(), requestUserID(r), uuidToString(issue.WorkspaceID))
+ if err != nil {
+ return func(pgtype.UUID) bool { return false }
+ }
+ memo := make(map[string]bool)
+ return func(runtimeID pgtype.UUID) bool {
+ if !runtimeID.Valid {
+ return false
+ }
+ key := uuidToString(runtimeID)
+ if allowed, ok := memo[key]; ok {
+ return allowed
+ }
+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceIssue, runtimeID)
+ allowed := err == nil && rt.WorkspaceID == issue.WorkspaceID && canUseRuntimeForAgent(member, rt)
+ memo[key] = allowed
+ return allowed
+ }
+}
+
+// environmentRuntime loads the machine a command targets and checks it can
+// take one now. control adds the permission to act on the machine; reading a
+// log only needs the issue.
+func (h *Handler) environmentRuntime(w http.ResponseWriter, r *http.Request, issue db.Issue, runtimeID pgtype.UUID, control bool) (db.AgentRuntime, bool) {
+ if !runtimeID.Valid {
+ writeError(w, http.StatusConflict, "the machine this environment ran on is no longer registered")
+ return db.AgentRuntime{}, false
+ }
+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceIssue, runtimeID)
+ if err != nil || rt.WorkspaceID != issue.WorkspaceID {
+ writeError(w, http.StatusConflict, "the machine this environment ran on is no longer registered")
+ return db.AgentRuntime{}, false
+ }
+ if control {
+ member, ok := h.requireWorkspaceMember(w, r, uuidToString(issue.WorkspaceID), "issue not found")
+ if !ok {
+ return db.AgentRuntime{}, false
+ }
+ if !canUseRuntimeForAgent(member, rt) {
+ writeError(w, http.StatusForbidden, "you cannot use this machine")
+ return db.AgentRuntime{}, false
+ }
+ }
+ if rt.Status != "online" {
+ writeError(w, http.StatusConflict, "the machine is offline")
+ return db.AgentRuntime{}, false
+ }
+ return rt, true
+}
+
+func (h *Handler) StopIssueEnvironment(w http.ResponseWriter, r *http.Request) {
+ h.commandIssueEnvironment(w, r, "stop")
+}
+
+func (h *Handler) RestartIssueEnvironment(w http.ResponseWriter, r *http.Request) {
+ h.commandIssueEnvironment(w, r, "restart")
+}
+
+func (h *Handler) ReadIssueEnvironmentLogs(w http.ResponseWriter, r *http.Request) {
+ h.commandIssueEnvironment(w, r, "logs")
+}
+
+func (h *Handler) commandIssueEnvironment(w http.ResponseWriter, r *http.Request, action string) {
+ control := action != "logs"
+ if control && isMachineCredentialActor(r) {
+ writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")
+ return
+ }
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ envID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "environmentId"), "environment_id")
+ if !ok {
+ return
+ }
+ env, err := h.Queries.GetIssueEnvironment(r.Context(), db.GetIssueEnvironmentParams{
+ ID: envID, IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "environment not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load environment")
+ return
+ }
+ switch {
+ case action == "stop" && env.EndedAt.Valid:
+ writeError(w, http.StatusConflict, "the environment is not running")
+ return
+ case env.Kind == issueEnvironmentKindApp && env.Source != "config":
+ writeError(w, http.StatusConflict, "only desktop apps the repository declares can be controlled from the sidebar")
+ return
+ case action != "stop" && env.Source != "config":
+ writeError(w, http.StatusConflict, "only environments the repository declares can be restarted or have a log")
+ return
+ case !env.Controllable:
+ writeError(w, http.StatusConflict, "update Multica on this machine to control its environments from the sidebar")
+ return
+ }
+ rt, ok := h.environmentRuntime(w, r, issue, env.RuntimeID, control)
+ if !ok {
+ return
+ }
+ now := time.Now()
+ if control {
+ open, err := h.Queries.HasOpenIssueEnvironmentControl(r.Context(), db.HasOpenIssueEnvironmentControlParams{
+ IssueID: issue.ID,
+ EnvironmentID: env.ID,
+ PendingAfter: pgtype.Timestamptz{Time: now.Add(-environmentCommandPendingWindow), Valid: true},
+ ClaimedAfter: pgtype.Timestamptz{Time: now.Add(-environmentCommandClaimedWindow), Valid: true},
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to queue the command")
+ return
+ }
+ if open {
+ writeError(w, http.StatusConflict, "the environment is already being stopped or restarted")
+ return
+ }
+ }
+ h.queueEnvironmentCommand(w, r, issue, rt, db.CreateIssueEnvironmentCommandParams{
+ EnvironmentID: env.ID,
+ TaskID: env.TaskID,
+ Action: action,
+ LocalKey: env.LocalKey,
+ Name: env.Name,
+ })
+}
+
+// StartIssueEnvironment starts an environment the latest run on a machine
+// declared, in that run's directory.
+func (h *Handler) StartIssueEnvironment(w http.ResponseWriter, r *http.Request) {
+ if isMachineCredentialActor(r) {
+ writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")
+ return
+ }
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ var req StartIssueEnvironmentRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ taskID, ok := parseUUIDOrBadRequest(w, req.TaskID, "task_id")
+ if !ok {
+ return
+ }
+ cfg, err := h.Queries.GetIssueEnvironmentConfig(r.Context(), db.GetIssueEnvironmentConfigParams{
+ TaskID: taskID, IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "no declared environments for this run")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load declared environments")
+ return
+ }
+ var declared []DeclaredEnvironment
+ _ = json.Unmarshal(cfg.Environments, &declared)
+ found := false
+ for _, d := range declared {
+ if d.Repo == req.Repo && d.Name == req.Name {
+ found = true
+ break
+ }
+ }
+ if !found {
+ writeError(w, http.StatusNotFound, "the run does not declare this environment")
+ return
+ }
+ rt, ok := h.environmentRuntime(w, r, issue, cfg.RuntimeID, true)
+ if !ok {
+ return
+ }
+ h.queueEnvironmentCommand(w, r, issue, rt, db.CreateIssueEnvironmentCommandParams{
+ TaskID: cfg.TaskID,
+ Action: "start",
+ Repo: req.Repo,
+ Name: req.Name,
+ })
+}
+
+func (h *Handler) queueEnvironmentCommand(w http.ResponseWriter, r *http.Request, issue db.Issue, rt db.AgentRuntime, params db.CreateIssueEnvironmentCommandParams) {
+ params.WorkspaceID = issue.WorkspaceID
+ params.IssueID = issue.ID
+ params.RuntimeID = rt.ID
+ params.ActorType = "member"
+ params.ActorID = optionalActorUUID(requestUserID(r))
+ cmd, err := h.Queries.CreateIssueEnvironmentCommand(r.Context(), params)
+ if err != nil {
+ slog.Warn("queue environment command failed", append(logger.RequestAttrs(r), "error", err, "action", params.Action)...)
+ writeError(w, http.StatusInternalServerError, "failed to queue the command")
+ return
+ }
+ h.requestDaemonPendingWork(uuidToString(rt.ID), protocol.PendingWorkKindEnvironmentCommand)
+ if params.Action != "logs" {
+ h.publishEnvironmentChanged(uuidToString(issue.WorkspaceID), issue.ID)
+ }
+ writeJSON(w, http.StatusAccepted, issueEnvironmentCommandToResponse(cmd, time.Now()))
+}
+
+// GetIssueEnvironmentCommand reports how a command went; a log read carries
+// its output.
+func (h *Handler) GetIssueEnvironmentCommand(w http.ResponseWriter, r *http.Request) {
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ cmdID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "commandId"), "command_id")
+ if !ok {
+ return
+ }
+ cmd, err := h.Queries.GetIssueEnvironmentCommand(r.Context(), db.GetIssueEnvironmentCommandParams{
+ ID: cmdID, IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "command not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load command")
+ return
+ }
+ writeJSON(w, http.StatusOK, issueEnvironmentCommandToResponse(cmd, time.Now()))
+}
+
+func (h *Handler) publishEnvironmentChanged(workspaceID string, issueID pgtype.UUID) {
+ h.publish(protocol.EventEnvironmentChanged, workspaceID, "system", "", map[string]string{
+ "issue_id": uuidToString(issueID),
+ })
+}
+
+// Daemon side.
+
+type DaemonEnvironmentCommand struct {
+ ID string `json:"id"`
+ Action string `json:"action"`
+ WorkspaceID string `json:"workspace_id"`
+ IssueID string `json:"issue_id"`
+ TaskID string `json:"task_id"`
+ LocalKey string `json:"local_key"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+}
+
+type ClaimEnvironmentCommandsResponse struct {
+ Commands []DaemonEnvironmentCommand `json:"commands"`
+}
+
+type EnvironmentCommandResultRequest struct {
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+ // Output is the log a logs command read.
+ Output *string `json:"output"`
+ // EnvironmentKey names the environment a start or restart produced.
+ EnvironmentKey string `json:"environment_key"`
+}
+
+type ReportTaskEnvironmentConfigsRequest struct {
+ Environments []DeclaredEnvironment `json:"environments"`
+}
+
+// ClaimEnvironmentCommands hands a daemon the commands queued for one of its
+// runtimes.
+func (h *Handler) ClaimEnvironmentCommands(w http.ResponseWriter, r *http.Request) {
+ rt, ok := h.requireDaemonRuntimeAccess(w, r, chi.URLParam(r, "runtimeId"))
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ClaimIssueEnvironmentCommands(r.Context(), db.ClaimIssueEnvironmentCommandsParams{
+ RuntimeID: rt.ID,
+ PendingAfter: pgtype.Timestamptz{Time: time.Now().Add(-environmentCommandPendingWindow), Valid: true},
+ })
+ if err != nil {
+ slog.Warn("claim environment commands failed", "runtime_id", uuidToString(rt.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to claim environment commands")
+ return
+ }
+ out := make([]DaemonEnvironmentCommand, 0, len(rows))
+ for _, c := range rows {
+ out = append(out, DaemonEnvironmentCommand{
+ ID: uuidToString(c.ID),
+ Action: c.Action,
+ WorkspaceID: uuidToString(c.WorkspaceID),
+ IssueID: uuidToString(c.IssueID),
+ TaskID: uuidToString(c.TaskID),
+ LocalKey: c.LocalKey,
+ Repo: c.Repo,
+ Name: c.Name,
+ })
+ }
+ writeJSON(w, http.StatusOK, ClaimEnvironmentCommandsResponse{Commands: out})
+}
+
+// ReportEnvironmentCommandResult records how a claimed command went.
+func (h *Handler) ReportEnvironmentCommandResult(w http.ResponseWriter, r *http.Request) {
+ rt, ok := h.requireDaemonRuntimeAccess(w, r, chi.URLParam(r, "runtimeId"))
+ if !ok {
+ return
+ }
+ cmdID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "commandId"), "command_id")
+ if !ok {
+ return
+ }
+ var req EnvironmentCommandResultRequest
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxEnvironmentLogBytes+64*1024)).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ params := db.CompleteIssueEnvironmentCommandParams{
+ ID: cmdID,
+ RuntimeID: rt.ID,
+ Status: "succeeded",
+ ResultKey: strings.TrimSpace(req.EnvironmentKey),
+ }
+ if len(params.ResultKey) > 128 {
+ params.ResultKey = ""
+ }
+ if !req.OK {
+ params.Status = "failed"
+ params.Error = truncateRunes(redact.Text(strings.TrimSpace(req.Error)), maxEnvironmentCommandError)
+ if params.Error == "" {
+ params.Error = "the machine could not carry out the command"
+ }
+ }
+ if req.OK && req.Output != nil {
+ output := redact.Text(strings.ToValidUTF8(*req.Output, "\uFFFD"))
+ if len(output) > maxEnvironmentLogBytes {
+ output = strings.ToValidUTF8(output[len(output)-maxEnvironmentLogBytes:], "")
+ }
+ params.Output = pgtype.Text{String: output, Valid: true}
+ }
+ cmd, err := h.Queries.CompleteIssueEnvironmentCommand(r.Context(), params)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "command not found")
+ return
+ }
+ slog.Warn("complete environment command failed", "command_id", uuidToString(cmdID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to record the result")
+ return
+ }
+ // A log read is collected by the member polling its command.
+ if cmd.Action != "logs" {
+ if cmd.Status == "succeeded" {
+ h.recordEnvironmentActivity(r.Context(), cmd)
+ }
+ h.publishEnvironmentChanged(uuidToString(cmd.WorkspaceID), cmd.IssueID)
+ }
+ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+}
+
+func (h *Handler) recordEnvironmentActivity(ctx context.Context, cmd db.IssueEnvironmentCommand) {
+ details := map[string]string{"action": cmd.Action, "name": cmd.Name}
+ if cmd.EnvironmentID.Valid {
+ if env, err := h.Queries.GetIssueEnvironment(ctx, db.GetIssueEnvironmentParams{
+ ID: cmd.EnvironmentID, IssueID: cmd.IssueID, WorkspaceID: cmd.WorkspaceID,
+ }); err == nil {
+ details["label"] = env.Label
+ details["url"] = env.Url
+ }
+ }
+ raw, _ := json.Marshal(details)
+ actorID := uuidToString(cmd.ActorID)
+ activity, err := h.Queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: cmd.WorkspaceID,
+ IssueID: cmd.IssueID,
+ ActorType: strToText(cmd.ActorType),
+ ActorID: cmd.ActorID,
+ Action: "environment_controlled",
+ Details: raw,
+ })
+ if err != nil {
+ slog.Warn("record environment activity failed", "command_id", uuidToString(cmd.ID), "error", err)
+ return
+ }
+ h.publish(protocol.EventActivityCreated, uuidToString(cmd.WorkspaceID), cmd.ActorType, actorID, map[string]any{
+ "issue_id": uuidToString(cmd.IssueID),
+ "entry": map[string]any{
+ "type": "activity",
+ "id": uuidToString(activity.ID),
+ "actor_type": cmd.ActorType,
+ "actor_id": actorID,
+ "action": activity.Action,
+ "details": json.RawMessage(raw),
+ "created_at": timestampToString(activity.CreatedAt),
+ },
+ })
+}
+
+// ReportTaskEnvironmentConfigs records the environments a finished task's
+// repositories declare. The latest report per machine is what the sidebar
+// offers to start, so an empty list clears what an earlier run declared.
+func (h *Handler) ReportTaskEnvironmentConfigs(w http.ResponseWriter, r *http.Request) {
+ task, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, chi.URLParam(r, "taskId"))
+ if !ok {
+ return
+ }
+ var req ReportTaskEnvironmentConfigsRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if len(req.Environments) > maxDeclaredEnvironments {
+ writeError(w, http.StatusBadRequest, "too many environments")
+ return
+ }
+ seen := make(map[string]bool, len(req.Environments))
+ envs := make([]DeclaredEnvironment, 0, len(req.Environments))
+ for _, env := range req.Environments {
+ env.Repo = strings.TrimSpace(env.Repo)
+ env.Name = strings.TrimSpace(env.Name)
+ env.Label = truncateRunes(strings.TrimSpace(env.Label), 120)
+ env.Start = truncateRunes(strings.TrimSpace(env.Start), maxDeclaredEnvironmentStart)
+ if !declaredEnvironmentNameRE.MatchString(env.Name) {
+ writeError(w, http.StatusBadRequest, "invalid environment name "+env.Name)
+ return
+ }
+ if env.Repo == "" || len(env.Repo) > maxDeclaredEnvironmentRepoLen || strings.ContainsAny(env.Repo, `/\`) {
+ writeError(w, http.StatusBadRequest, "invalid repository name")
+ return
+ }
+ key := env.Repo + "\x00" + env.Name
+ if seen[key] {
+ continue
+ }
+ seen[key] = true
+ envs = append(envs, env)
+ }
+ if !task.IssueID.Valid || !task.RuntimeID.Valid {
+ writeJSON(w, http.StatusOK, map[string]int{"accepted": 0})
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace_id")
+ if !ok {
+ return
+ }
+ raw, _ := json.Marshal(envs)
+ if err := h.Queries.UpsertIssueEnvironmentConfig(r.Context(), db.UpsertIssueEnvironmentConfigParams{
+ TaskID: task.ID,
+ WorkspaceID: wsUUID,
+ IssueID: task.IssueID,
+ RuntimeID: task.RuntimeID,
+ Environments: raw,
+ }); err != nil {
+ slog.Warn("record declared environments failed", "task_id", uuidToString(task.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to record declared environments")
+ return
+ }
+ h.publishEnvironmentChanged(workspaceID, task.IssueID)
+ writeJSON(w, http.StatusOK, map[string]int{"accepted": len(envs)})
+}
+
+// SweepEnvironmentLogCommands deletes log reads whose output is no longer
+// needed.
+func SweepEnvironmentLogCommands(ctx context.Context, queries *db.Queries, now time.Time) (int64, error) {
+ return queries.DeleteIssueEnvironmentLogCommandsBefore(ctx, pgtype.Timestamptz{
+ Time: now.Add(-environmentLogCommandRetention), Valid: true,
+ })
+}
+
+func truncateRunes(s string, max int) string {
+ if utf8.RuneCountInString(s) <= max {
+ return s
+ }
+ return string([]rune(s)[:max])
+}
diff --git a/server/internal/handler/issue_environment_control_test.go b/server/internal/handler/issue_environment_control_test.go
new file mode 100644
index 0000000000..c8e34b575e
--- /dev/null
+++ b/server/internal/handler/issue_environment_control_test.go
@@ -0,0 +1,471 @@
+package handler
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+type environmentControlFixture struct {
+ issueID, taskID, runtimeID string
+}
+
+func newEnvironmentControlFixture(t *testing.T, runtimeCols ...testutil.Cols) environmentControlFixture {
+ t.Helper()
+ suffix := fmt.Sprint(time.Now().UnixNano())
+ runtimeID := dbfx.Runtime(t, "environment-control runtime "+suffix, runtimeCols...)
+ agentID := dbfx.Agent(t, "environment-control agent "+suffix, runtimeID)
+ issueID := dbfx.Issue(t, "environment-control 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)
+ dbfx.Cleanup(t, `DELETE FROM issue_environment_command WHERE issue_id = $1`, issueID)
+ dbfx.Cleanup(t, `DELETE FROM issue_environment_config WHERE issue_id = $1`, issueID)
+ dbfx.Cleanup(t, `DELETE FROM activity_log WHERE issue_id = $1`, issueID)
+ return environmentControlFixture{issueID: issueID, taskID: taskID, runtimeID: runtimeID}
+}
+
+func (f environmentControlFixture) report(t *testing.T, controllable bool, envs ...map[string]any) {
+ t.Helper()
+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+f.taskID+"/environments",
+ map[string]any{"environments": envs, "controllable": controllable}), "taskId", f.taskID)
+ testutil.Call(t, testHandler.ReportTaskEnvironments, req).Want(http.StatusOK)
+}
+
+func (f environmentControlFixture) list(t *testing.T, userID string) IssueEnvironmentsResponse {
+ t.Helper()
+ var out IssueEnvironmentsResponse
+ testutil.Call(t, testHandler.ListIssueEnvironments,
+ withURLParam(newRequestAs(userID, http.MethodGet, "/api/issues/"+f.issueID+"/environments", nil), "id", f.issueID)).
+ Want(http.StatusOK).JSON(&out)
+ return out
+}
+
+func (f environmentControlFixture) env(t *testing.T, name string) IssueEnvironmentResponse {
+ t.Helper()
+ for _, env := range f.list(t, testUserID).Environments {
+ if env.Name == name {
+ return env
+ }
+ }
+ t.Fatalf("no environment %q", name)
+ return IssueEnvironmentResponse{}
+}
+
+func (f environmentControlFixture) command(t *testing.T, req *http.Request, action, envID string) *testutil.Response {
+ t.Helper()
+ req = withURLParams(req, "id", f.issueID, "environmentId", envID)
+ switch action {
+ case "stop":
+ return testutil.Call(t, testHandler.StopIssueEnvironment, req)
+ case "restart":
+ return testutil.Call(t, testHandler.RestartIssueEnvironment, req)
+ default:
+ return testutil.Call(t, testHandler.ReadIssueEnvironmentLogs, req)
+ }
+}
+
+func (f environmentControlFixture) commandAs(t *testing.T, userID, action, envID string) *testutil.Response {
+ t.Helper()
+ return f.command(t, newRequestAs(userID, http.MethodPost, "/api/issues/"+f.issueID+"/environments/"+envID+"/"+action, nil), action, envID)
+}
+
+func (f environmentControlFixture) claim(t *testing.T) []DaemonEnvironmentCommand {
+ t.Helper()
+ var out ClaimEnvironmentCommandsResponse
+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+f.runtimeID+"/environment-commands/claim", nil), "runtimeId", f.runtimeID)
+ testutil.Call(t, testHandler.ClaimEnvironmentCommands, req).Want(http.StatusOK).JSON(&out)
+ return out.Commands
+}
+
+func (f environmentControlFixture) result(t *testing.T, commandID string, body EnvironmentCommandResultRequest) *testutil.Response {
+ t.Helper()
+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+f.runtimeID+"/environment-commands/"+commandID+"/result", body),
+ "runtimeId", f.runtimeID, "commandId", commandID)
+ return testutil.Call(t, testHandler.ReportEnvironmentCommandResult, req)
+}
+
+func (f environmentControlFixture) getCommand(t *testing.T, commandID string) IssueEnvironmentCommandResponse {
+ t.Helper()
+ var out IssueEnvironmentCommandResponse
+ req := withURLParams(newRequest(http.MethodGet, "/api/issues/"+f.issueID+"/environment-commands/"+commandID, nil),
+ "id", f.issueID, "commandId", commandID)
+ testutil.Call(t, testHandler.GetIssueEnvironmentCommand, req).Want(http.StatusOK).JSON(&out)
+ return out
+}
+
+func detectedEnvironment() map[string]any {
+ return map[string]any{"key": "detected:abc", "source": "detected", "name": "vite", "url": "http://localhost:5173", "port": 5173, "state": "running"}
+}
+
+func TestEnvironmentStop_RoundTripsThroughTheDaemon(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("running"))
+ web := f.env(t, "web")
+ if !web.Controllable || !web.CanControl || web.PendingAction != nil {
+ t.Fatalf("reported environment = %+v, want controllable by its machine's owner", web)
+ }
+
+ var queued IssueEnvironmentCommandResponse
+ f.commandAs(t, testUserID, "stop", web.ID).Want(http.StatusAccepted).JSON(&queued)
+ if queued.Action != "stop" || queued.Status != "pending" {
+ t.Fatalf("queued command = %+v", queued)
+ }
+ if pending := f.env(t, "web").PendingAction; pending == nil || pending.ID != queued.ID {
+ t.Fatalf("pending action = %+v, want the queued stop", pending)
+ }
+ f.commandAs(t, testUserID, "stop", web.ID).Want(http.StatusConflict)
+
+ cmds := f.claim(t)
+ if len(cmds) != 1 || cmds[0].ID != queued.ID || cmds[0].LocalKey != "config:web" || cmds[0].IssueID != f.issueID {
+ t.Fatalf("claimed = %+v", cmds)
+ }
+ if again := f.claim(t); len(again) != 0 {
+ t.Fatalf("a claimed command was handed out twice: %+v", again)
+ }
+ f.result(t, queued.ID, EnvironmentCommandResultRequest{OK: true}).Want(http.StatusOK)
+ f.result(t, queued.ID, EnvironmentCommandResultRequest{OK: true}).Want(http.StatusNotFound)
+
+ web = f.env(t, "web")
+ if web.PendingAction != nil || web.LastAction == nil || web.LastAction.Status != "succeeded" ||
+ web.LastAction.ActorID == nil || *web.LastAction.ActorID != testUserID {
+ t.Fatalf("after the stop = %+v / %+v", web.PendingAction, web.LastAction)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM activity_log WHERE issue_id = $1 AND action = 'environment_controlled' AND details->>'action' = 'stop'`, f.issueID); n != 1 {
+ t.Fatalf("stop activities = %d, want 1", n)
+ }
+}
+
+func TestEnvironmentRestart_LinksTheNewEnvironment(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("exited"))
+ web := f.env(t, "web")
+
+ var queued IssueEnvironmentCommandResponse
+ f.commandAs(t, testUserID, "restart", web.ID).Want(http.StatusAccepted).JSON(&queued)
+ f.claim(t)
+ f.result(t, queued.ID, EnvironmentCommandResultRequest{OK: true, EnvironmentKey: "config:web2"}).Want(http.StatusOK)
+
+ restarted := webEnvironment("starting")
+ restarted["key"] = "config:web2"
+ restarted["name"] = "web2"
+ f.report(t, true, restarted)
+ if origin := f.env(t, "web2").Origin; origin == nil || origin.Action != "restart" || origin.ActorID == nil || *origin.ActorID != testUserID {
+ t.Fatalf("restarted environment origin = %+v", origin)
+ }
+}
+
+func TestEnvironmentFailedCommandReportsItsError(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("exited"))
+ web := f.env(t, "web")
+ var queued IssueEnvironmentCommandResponse
+ f.commandAs(t, testUserID, "restart", web.ID).Want(http.StatusAccepted).JSON(&queued)
+ f.claim(t)
+ f.result(t, queued.ID, EnvironmentCommandResultRequest{Error: "the code this environment ran from has been cleaned up"}).Want(http.StatusOK)
+ got := f.getCommand(t, queued.ID)
+ if got.Status != "failed" || !strings.Contains(got.Error, "cleaned up") {
+ t.Fatalf("failed command = %+v", got)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM activity_log WHERE issue_id = $1 AND action = 'environment_controlled'`, f.issueID); n != 0 {
+ t.Fatalf("a failed restart recorded %d activities", n)
+ }
+}
+
+func TestEnvironmentLogs_AreReadOnDemandAndRedacted(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("running"))
+ web := f.env(t, "web")
+
+ var queued IssueEnvironmentCommandResponse
+ f.commandAs(t, testUserID, "logs", web.ID).Want(http.StatusAccepted).JSON(&queued)
+ if queued.Output != nil {
+ t.Fatal("a pending log read has no output")
+ }
+ f.claim(t)
+ output := "listening\nERROR cannot reach postgres://app:[email protected]/app\n"
+ f.result(t, queued.ID, EnvironmentCommandResultRequest{OK: true, Output: &output}).Want(http.StatusOK)
+
+ got := f.getCommand(t, queued.ID)
+ if got.Status != "succeeded" || got.Output == nil {
+ t.Fatalf("log read = %+v", got)
+ }
+ if strings.Contains(*got.Output, "hunter2") || !strings.Contains(*got.Output, "ERROR cannot reach [REDACTED") {
+ t.Fatalf("log output = %q, want the connection string redacted", *got.Output)
+ }
+ if f.env(t, "web").LastAction != nil {
+ t.Fatal("a log read is not an action on the environment")
+ }
+
+ dbfx.Exec(t, `UPDATE issue_environment_command SET created_at = now() - interval '11 minutes' WHERE id = $1`, queued.ID)
+ if _, err := SweepEnvironmentLogCommands(t.Context(), testHandler.Queries, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM issue_environment_command WHERE id = $1`, queued.ID); n != 0 {
+ t.Fatal("an old log read was kept")
+ }
+}
+
+func TestEnvironmentCrashExcerptIsRedacted(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ crashed := webEnvironment("exited")
+ crashed["excerpt"] = "panic: dial postgres://app:[email protected]/app\nexit"
+ f.report(t, true, crashed)
+ web := f.env(t, "web")
+ if strings.Contains(web.Excerpt, "hunter2") || !strings.HasPrefix(web.Excerpt, "panic: dial [REDACTED") {
+ t.Fatalf("excerpt = %q", web.Excerpt)
+ }
+
+ running := webEnvironment("running")
+ running["excerpt"] = "only kept for a crash"
+ f.report(t, true, running)
+ if got := f.env(t, "web").Excerpt; got != "" {
+ t.Fatalf("running environment excerpt = %q", got)
+ }
+}
+
+func TestEnvironmentCommandsAreRefusedWhereTheyCannotWork(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("exited"), detectedEnvironment())
+ web, vite := f.env(t, "web"), f.env(t, "vite")
+
+ f.commandAs(t, testUserID, "stop", web.ID).Want(http.StatusConflict)
+ f.commandAs(t, testUserID, "restart", vite.ID).Want(http.StatusConflict)
+ f.commandAs(t, testUserID, "logs", vite.ID).Want(http.StatusConflict)
+ f.commandAs(t, testUserID, "stop", vite.ID).Want(http.StatusAccepted)
+
+ f.report(t, true, webEnvironment("exited"), detectedEnvironment(),
+ map[string]any{"key": "detected:app", "source": "detected", "kind": "app", "name": "Multica Canary", "state": "running"},
+ map[string]any{"key": "config:desktop", "source": "config", "kind": "app", "name": "desktop", "state": "running"})
+ f.commandAs(t, testUserID, "stop", f.env(t, "Multica Canary").ID).Want(http.StatusConflict)
+ // A desktop app the repository declares is supervised like any declared environment.
+ f.commandAs(t, testUserID, "stop", f.env(t, "desktop").ID).Want(http.StatusAccepted)
+
+ dbfx.Exec(t, `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, f.runtimeID)
+ f.commandAs(t, testUserID, "restart", web.ID).Want(http.StatusConflict)
+ f.commandAs(t, testUserID, "logs", web.ID).Want(http.StatusConflict)
+}
+
+func TestEnvironmentFromAnOlderDaemonIsReadOnly(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, false, webEnvironment("running"))
+ web := f.env(t, "web")
+ if web.Controllable || web.CanControl {
+ t.Fatalf("environment from an older daemon = %+v", web)
+ }
+ f.commandAs(t, testUserID, "stop", web.ID).Want(http.StatusConflict)
+ f.commandAs(t, testUserID, "logs", web.ID).Want(http.StatusConflict)
+}
+
+func TestEnvironmentControlPermissions(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("running"))
+ web := f.env(t, "web")
+
+ t.Run("a member who cannot use the private machine", func(t *testing.T) {
+ member := plainMember(t, "env-control-member")
+ if got := f.list(t, member).Environments[0]; got.CanControl {
+ t.Fatal("a member who cannot use the machine is offered control")
+ }
+ f.commandAs(t, member, "stop", web.ID).Want(http.StatusForbidden)
+ f.commandAs(t, member, "restart", web.ID).Want(http.StatusForbidden)
+ // Reading the log only needs the issue.
+ f.commandAs(t, member, "logs", web.ID).Want(http.StatusAccepted)
+ })
+
+ // Membership for every issue route is enforced by RequireWorkspaceMember;
+ // acting on a machine checks it again.
+ t.Run("someone outside the workspace", func(t *testing.T) {
+ outsider := dbfx.User(t, "env-control-outsider", fmt.Sprintf("env-control-outsider-%[email protected]", time.Now().UnixNano()))
+ f.commandAs(t, outsider, "stop", web.ID).Want(http.StatusNotFound)
+ })
+
+ t.Run("an agent's task token", func(t *testing.T) {
+ req := newRequest(http.MethodPost, "/api/issues/"+f.issueID+"/environments/"+web.ID+"/stop", nil)
+ req.Header.Set("X-Actor-Source", "task_token")
+ f.command(t, req, "stop", web.ID).Want(http.StatusForbidden)
+ })
+
+ t.Run("an environment of another issue", func(t *testing.T) {
+ other := newEnvironmentControlFixture(t)
+ req := withURLParams(newRequest(http.MethodPost, "/", nil), "id", other.issueID, "environmentId", web.ID)
+ testutil.Call(t, testHandler.StopIssueEnvironment, req).Want(http.StatusNotFound)
+ })
+
+ t.Run("a public machine", func(t *testing.T) {
+ shared := newEnvironmentControlFixture(t, testutil.Cols{"visibility": "public"})
+ shared.report(t, true, webEnvironment("running"))
+ member := plainMember(t, "env-control-public")
+ if !shared.list(t, member).Environments[0].CanControl {
+ t.Fatal("a member is not offered control of a public machine")
+ }
+ shared.commandAs(t, member, "stop", shared.env(t, "web").ID).Want(http.StatusAccepted)
+ })
+}
+
+func TestEnvironmentCommandsStayWithTheirDaemon(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("running"))
+ var queued IssueEnvironmentCommandResponse
+ f.commandAs(t, testUserID, "stop", f.env(t, "web").ID).Want(http.StatusAccepted).JSON(&queued)
+
+ foreign := withURLParam(newDaemonTokenRequest(http.MethodPost, "/", nil, testWorkspaceID, "attacker-daemon"), "runtimeId", f.runtimeID)
+ testutil.Call(t, testHandler.ClaimEnvironmentCommands, foreign).Want(http.StatusNotFound)
+
+ other := newEnvironmentControlFixture(t)
+ if cmds := other.claim(t); len(cmds) != 0 {
+ t.Fatalf("another runtime claimed %+v", cmds)
+ }
+ f.claim(t)
+ // Another runtime cannot answer for this one.
+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/", EnvironmentCommandResultRequest{OK: true}),
+ "runtimeId", other.runtimeID, "commandId", queued.ID)
+ testutil.Call(t, testHandler.ReportEnvironmentCommandResult, req).Want(http.StatusNotFound)
+}
+
+func TestEnvironmentUnansweredCommandsExpire(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ f.report(t, true, webEnvironment("running"))
+ web := f.env(t, "web")
+ var queued IssueEnvironmentCommandResponse
+ f.commandAs(t, testUserID, "stop", web.ID).Want(http.StatusAccepted).JSON(&queued)
+ dbfx.Exec(t, `UPDATE issue_environment_command SET created_at = now() - interval '1 minute' WHERE id = $1`, queued.ID)
+
+ if got := f.getCommand(t, queued.ID); got.Status != "expired" {
+ t.Fatalf("unanswered command status = %q, want expired", got.Status)
+ }
+ if cmds := f.claim(t); len(cmds) != 0 {
+ t.Fatalf("an expired command was carried out late: %+v", cmds)
+ }
+ got := f.env(t, "web")
+ if got.PendingAction != nil || got.LastAction == nil || got.LastAction.Status != "expired" {
+ t.Fatalf("after the command expired = %+v / %+v", got.PendingAction, got.LastAction)
+ }
+ // It no longer blocks another try.
+ f.commandAs(t, testUserID, "stop", web.ID).Want(http.StatusAccepted)
+}
+
+func TestEnvironmentStartFromDeclaredConfig(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ reportConfigs := func(envs ...DeclaredEnvironment) *testutil.Response {
+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+f.taskID+"/environment-configs",
+ ReportTaskEnvironmentConfigsRequest{Environments: envs}), "taskId", f.taskID)
+ return testutil.Call(t, testHandler.ReportTaskEnvironmentConfigs, req)
+ }
+ reportConfigs(DeclaredEnvironment{Repo: "multica", Name: "BAD NAME", Start: "x"}).Want(http.StatusBadRequest)
+ reportConfigs(DeclaredEnvironment{Repo: "../etc", Name: "web", Start: "x"}).Want(http.StatusBadRequest)
+ reportConfigs(
+ DeclaredEnvironment{Repo: "multica", Name: "web", Label: "Web app", Start: "make dev-web"},
+ DeclaredEnvironment{Repo: "multica", Name: "api", Label: "API", Start: "make server"},
+ ).Want(http.StatusOK)
+
+ list := f.list(t, testUserID)
+ if len(list.Configs) != 1 || list.Configs[0].TaskID != f.taskID || !list.Configs[0].CanControl || len(list.Configs[0].Environments) != 2 {
+ t.Fatalf("configs = %+v", list.Configs)
+ }
+
+ start := func(userID string, body StartIssueEnvironmentRequest) *testutil.Response {
+ req := withURLParam(newRequestAs(userID, http.MethodPost, "/api/issues/"+f.issueID+"/environments/start", body), "id", f.issueID)
+ return testutil.Call(t, testHandler.StartIssueEnvironment, req)
+ }
+ start(testUserID, StartIssueEnvironmentRequest{TaskID: f.taskID, Repo: "multica", Name: "worker"}).Want(http.StatusNotFound)
+ start(plainMember(t, "env-start-member"), StartIssueEnvironmentRequest{TaskID: f.taskID, Repo: "multica", Name: "web"}).Want(http.StatusForbidden)
+
+ var queued IssueEnvironmentCommandResponse
+ start(testUserID, StartIssueEnvironmentRequest{TaskID: f.taskID, Repo: "multica", Name: "web"}).Want(http.StatusAccepted).JSON(&queued)
+ if pending := f.list(t, testUserID).PendingStarts; len(pending) != 1 || pending[0].Name != "web" || pending[0].RuntimeID != f.runtimeID {
+ t.Fatalf("pending starts = %+v", pending)
+ }
+ cmds := f.claim(t)
+ if len(cmds) != 1 || cmds[0].Action != "start" || cmds[0].TaskID != f.taskID || cmds[0].Repo != "multica" || cmds[0].Name != "web" {
+ t.Fatalf("claimed start = %+v", cmds)
+ }
+
+ // A later run that declares nothing clears the offer.
+ reportConfigs().Want(http.StatusOK)
+ if list := f.list(t, testUserID); len(list.Configs) != 1 || len(list.Configs[0].Environments) != 0 {
+ t.Fatalf("configs after an empty report = %+v", list.Configs)
+ }
+}
+
+func TestEnvironmentStartFailuresStayVisibleUntilRetried(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+f.taskID+"/environment-configs",
+ ReportTaskEnvironmentConfigsRequest{Environments: []DeclaredEnvironment{
+ {Repo: "multica", Name: "web", Start: "make dev-web"},
+ {Repo: "multica", Name: "api", Start: "make server"},
+ }}), "taskId", f.taskID)
+ testutil.Call(t, testHandler.ReportTaskEnvironmentConfigs, req).Want(http.StatusOK)
+ start := func(name string) IssueEnvironmentCommandResponse {
+ var queued IssueEnvironmentCommandResponse
+ req := withURLParam(newRequestAs(testUserID, http.MethodPost, "/api/issues/"+f.issueID+"/environments/start",
+ StartIssueEnvironmentRequest{TaskID: f.taskID, Repo: "multica", Name: name}), "id", f.issueID)
+ testutil.Call(t, testHandler.StartIssueEnvironment, req).Want(http.StatusAccepted).JSON(&queued)
+ return queued
+ }
+
+ t.Run("failed after the machine accepted it", func(t *testing.T) {
+ queued := start("web")
+ f.claim(t)
+ f.result(t, queued.ID, EnvironmentCommandResultRequest{Error: "the run's checkout was cleaned up"}).Want(http.StatusOK)
+
+ list := f.list(t, testUserID)
+ if len(list.PendingStarts) != 0 || len(list.FailedStarts) != 1 {
+ t.Fatalf("pending = %+v, failed = %+v", list.PendingStarts, list.FailedStarts)
+ }
+ failed := list.FailedStarts[0]
+ if failed.ID != queued.ID || failed.Status != "failed" || failed.Error != "the run's checkout was cleaned up" ||
+ failed.TaskID == nil || *failed.TaskID != f.taskID {
+ t.Fatalf("failed start = %+v", failed)
+ }
+
+ // Retrying replaces the failure with the new attempt.
+ start("web")
+ list = f.list(t, testUserID)
+ if len(list.PendingStarts) != 1 || len(list.FailedStarts) != 0 {
+ t.Fatalf("after retry: pending = %+v, failed = %+v", list.PendingStarts, list.FailedStarts)
+ }
+ f.claim(t)
+ })
+
+ t.Run("never answered", func(t *testing.T) {
+ queued := start("api")
+ dbfx.Exec(t, `UPDATE issue_environment_command SET created_at = now() - interval '1 minute' WHERE id = $1`, queued.ID)
+ list := f.list(t, testUserID)
+ var found *IssueEnvironmentActionResponse
+ for i := range list.FailedStarts {
+ if list.FailedStarts[i].ID == queued.ID {
+ found = &list.FailedStarts[i]
+ }
+ }
+ if found == nil || found.Status != "expired" {
+ t.Fatalf("failed starts = %+v, want the unanswered start as expired", list.FailedStarts)
+ }
+
+ // An old failure is no longer news.
+ dbfx.Exec(t, `UPDATE issue_environment_command SET created_at = now() - interval '20 minutes' WHERE id = $1`, queued.ID)
+ for _, s := range f.list(t, testUserID).FailedStarts {
+ if s.ID == queued.ID {
+ t.Fatalf("a start that expired 20 minutes ago is still listed: %+v", s)
+ }
+ }
+ })
+}
+
+func TestEnvironmentReportsKeepTheirRepository(t *testing.T) {
+ f := newEnvironmentControlFixture(t)
+ web := webEnvironment("running")
+ web["repo"] = "multica"
+ detected := detectedEnvironment()
+ detected["repo"] = "multica"
+ f.report(t, true, web, detected)
+ if got := f.env(t, "web").Repo; got != "multica" {
+ t.Fatalf("declared environment repo = %q", got)
+ }
+ if got := f.env(t, "vite").Repo; got != "" {
+ t.Fatalf("detected environment repo = %q, want none", got)
+ }
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 9426b25eb9..e6439f1247 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -155,6 +155,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"app_action_request": workspaceDelete,
"app_tool_call": workspaceDelete,
"issue_environment": workspaceDelete,
+ "issue_environment_command": workspaceDelete,
+ "issue_environment_config": workspaceDelete,
"workspace_app_setting": workspaceDelete,
"app_tool_class_override": workspaceDelete,
"workspace": workspaceDelete,
diff --git a/server/migrations/638_issue_environment_control.down.sql b/server/migrations/638_issue_environment_control.down.sql
new file mode 100644
index 0000000000..e13c23044e
--- /dev/null
+++ b/server/migrations/638_issue_environment_control.down.sql
@@ -0,0 +1,6 @@
+DROP TABLE IF EXISTS issue_environment_config;
+DROP TABLE IF EXISTS issue_environment_command;
+ALTER TABLE issue_environment
+ DROP COLUMN IF EXISTS controllable,
+ DROP COLUMN IF EXISTS excerpt,
+ DROP COLUMN IF EXISTS repo;
diff --git a/server/migrations/638_issue_environment_control.up.sql b/server/migrations/638_issue_environment_control.up.sql
new file mode 100644
index 0000000000..a6b5997a43
--- /dev/null
+++ b/server/migrations/638_issue_environment_control.up.sql
@@ -0,0 +1,49 @@
+-- Controlling an issue's local environments from the sidebar (MUL-8923).
+--
+-- repo is the checkout directory a declared environment runs from, which
+-- tells apart two repositories in one run that declare the same name.
+-- excerpt holds the last redacted lines a crashed environment printed, so the
+-- sidebar can say why it crashed while its machine is offline. controllable
+-- marks rows reported by a daemon that accepts the commands below; rows from
+-- older daemons stay read-only.
+ALTER TABLE issue_environment
+ ADD COLUMN IF NOT EXISTS repo TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS excerpt TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS controllable BOOLEAN NOT NULL DEFAULT false;
+
+-- A stop, restart, start or log read a member asked a daemon to perform. The
+-- daemon claims pending rows for its runtime and reports the outcome; control
+-- rows double as the record of who did what. Log rows carry the output they
+-- read and are deleted shortly after.
+CREATE TABLE IF NOT EXISTS issue_environment_command (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ issue_id UUID NOT NULL,
+ runtime_id UUID NOT NULL,
+ environment_id UUID,
+ task_id UUID,
+ action TEXT NOT NULL CHECK (action IN ('stop', 'restart', 'start', 'logs')),
+ local_key TEXT NOT NULL DEFAULT '',
+ repo TEXT NOT NULL DEFAULT '',
+ name TEXT NOT NULL DEFAULT '',
+ actor_type TEXT NOT NULL,
+ actor_id UUID,
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'claimed', 'succeeded', 'failed')),
+ error TEXT NOT NULL DEFAULT '',
+ output TEXT,
+ result_key TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ claimed_at TIMESTAMPTZ,
+ completed_at TIMESTAMPTZ
+);
+
+-- The environments a task's repositories declare, as the daemon found them
+-- when the task finished, so the sidebar can offer to start them.
+CREATE TABLE IF NOT EXISTS issue_environment_config (
+ task_id UUID PRIMARY KEY,
+ workspace_id UUID NOT NULL,
+ issue_id UUID NOT NULL,
+ runtime_id UUID NOT NULL,
+ environments JSONB NOT NULL DEFAULT '[]',
+ reported_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/639_issue_environment_command_pending_idx.down.sql b/server/migrations/639_issue_environment_command_pending_idx.down.sql
new file mode 100644
index 0000000000..bba3405cc0
--- /dev/null
+++ b/server/migrations/639_issue_environment_command_pending_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_environment_command_pending;
diff --git a/server/migrations/639_issue_environment_command_pending_idx.up.sql b/server/migrations/639_issue_environment_command_pending_idx.up.sql
new file mode 100644
index 0000000000..1fe82edb18
--- /dev/null
+++ b/server/migrations/639_issue_environment_command_pending_idx.up.sql
@@ -0,0 +1,4 @@
+-- A daemon's claim of the commands queued for one of its runtimes.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_environment_command_pending
+ ON issue_environment_command (runtime_id, created_at)
+ WHERE status = 'pending';
diff --git a/server/migrations/640_issue_environment_command_issue_idx.down.sql b/server/migrations/640_issue_environment_command_issue_idx.down.sql
new file mode 100644
index 0000000000..2d68431779
--- /dev/null
+++ b/server/migrations/640_issue_environment_command_issue_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_environment_command_issue;
diff --git a/server/migrations/640_issue_environment_command_issue_idx.up.sql b/server/migrations/640_issue_environment_command_issue_idx.up.sql
new file mode 100644
index 0000000000..9a32796be9
--- /dev/null
+++ b/server/migrations/640_issue_environment_command_issue_idx.up.sql
@@ -0,0 +1,3 @@
+-- The issue sidebar's pending and most recent actions per environment.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_environment_command_issue
+ ON issue_environment_command (issue_id, created_at);
diff --git a/server/migrations/641_issue_environment_command_logs_idx.down.sql b/server/migrations/641_issue_environment_command_logs_idx.down.sql
new file mode 100644
index 0000000000..b8fc53c11e
--- /dev/null
+++ b/server/migrations/641_issue_environment_command_logs_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_environment_command_logs;
diff --git a/server/migrations/641_issue_environment_command_logs_idx.up.sql b/server/migrations/641_issue_environment_command_logs_idx.up.sql
new file mode 100644
index 0000000000..42981f6392
--- /dev/null
+++ b/server/migrations/641_issue_environment_command_logs_idx.up.sql
@@ -0,0 +1,4 @@
+-- The sweep that deletes log reads once their output is no longer needed.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_environment_command_logs
+ ON issue_environment_command (created_at)
+ WHERE action = 'logs';
diff --git a/server/migrations/642_issue_environment_config_issue_idx.down.sql b/server/migrations/642_issue_environment_config_issue_idx.down.sql
new file mode 100644
index 0000000000..b96bba1814
--- /dev/null
+++ b/server/migrations/642_issue_environment_config_issue_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_environment_config_issue;
diff --git a/server/migrations/642_issue_environment_config_issue_idx.up.sql b/server/migrations/642_issue_environment_config_issue_idx.up.sql
new file mode 100644
index 0000000000..14f484c14c
--- /dev/null
+++ b/server/migrations/642_issue_environment_config_issue_idx.up.sql
@@ -0,0 +1,3 @@
+-- The latest declared environments per machine for an issue.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_environment_config_issue
+ ON issue_environment_config (issue_id, reported_at);
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index e6a5a6cec2..60a86b9424 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -514,6 +514,12 @@ cleared_unread AS (
),
cleared_environments AS (
DELETE FROM issue_environment WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_environment_commands AS (
+ DELETE FROM issue_environment_command WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_environment_configs AS (
+ DELETE FROM issue_environment_config 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.go
index 3adb552825..ffb4b20a0f 100644
--- a/server/pkg/db/generated/issue_environment.sql.go
+++ b/server/pkg/db/generated/issue_environment.sql.go
@@ -11,6 +11,199 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const claimIssueEnvironmentCommands = `-- name: ClaimIssueEnvironmentCommands :many
+UPDATE issue_environment_command
+SET status = 'claimed', claimed_at = now()
+WHERE id IN (
+ SELECT c.id FROM issue_environment_command c
+ WHERE c.runtime_id = $1
+ AND c.status = 'pending'
+ AND c.created_at > $2::timestamptz
+ ORDER BY c.created_at
+ LIMIT 20
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING id, workspace_id, issue_id, runtime_id, environment_id, task_id, action, local_key, repo, name, actor_type, actor_id, status, error, output, result_key, created_at, claimed_at, completed_at
+`
+
+type ClaimIssueEnvironmentCommandsParams struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ PendingAfter pgtype.Timestamptz `json:"pending_after"`
+}
+
+// Commands older than the pending window were already reported to the member
+// as unanswered, so they are never carried out late.
+func (q *Queries) ClaimIssueEnvironmentCommands(ctx context.Context, arg ClaimIssueEnvironmentCommandsParams) ([]IssueEnvironmentCommand, error) {
+ rows, err := q.db.Query(ctx, claimIssueEnvironmentCommands, arg.RuntimeID, arg.PendingAfter)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueEnvironmentCommand{}
+ for rows.Next() {
+ var i IssueEnvironmentCommand
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.RuntimeID,
+ &i.EnvironmentID,
+ &i.TaskID,
+ &i.Action,
+ &i.LocalKey,
+ &i.Repo,
+ &i.Name,
+ &i.ActorType,
+ &i.ActorID,
+ &i.Status,
+ &i.Error,
+ &i.Output,
+ &i.ResultKey,
+ &i.CreatedAt,
+ &i.ClaimedAt,
+ &i.CompletedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const completeIssueEnvironmentCommand = `-- name: CompleteIssueEnvironmentCommand :one
+UPDATE issue_environment_command
+SET status = $1,
+ error = $2,
+ output = $3,
+ result_key = $4,
+ completed_at = now()
+WHERE id = $5 AND runtime_id = $6 AND status = 'claimed'
+RETURNING id, workspace_id, issue_id, runtime_id, environment_id, task_id, action, local_key, repo, name, actor_type, actor_id, status, error, output, result_key, created_at, claimed_at, completed_at
+`
+
+type CompleteIssueEnvironmentCommandParams struct {
+ Status string `json:"status"`
+ Error string `json:"error"`
+ Output pgtype.Text `json:"output"`
+ ResultKey string `json:"result_key"`
+ ID pgtype.UUID `json:"id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+}
+
+func (q *Queries) CompleteIssueEnvironmentCommand(ctx context.Context, arg CompleteIssueEnvironmentCommandParams) (IssueEnvironmentCommand, error) {
+ row := q.db.QueryRow(ctx, completeIssueEnvironmentCommand,
+ arg.Status,
+ arg.Error,
+ arg.Output,
+ arg.ResultKey,
+ arg.ID,
+ arg.RuntimeID,
+ )
+ var i IssueEnvironmentCommand
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.RuntimeID,
+ &i.EnvironmentID,
+ &i.TaskID,
+ &i.Action,
+ &i.LocalKey,
+ &i.Repo,
+ &i.Name,
+ &i.ActorType,
+ &i.ActorID,
+ &i.Status,
+ &i.Error,
+ &i.Output,
+ &i.ResultKey,
+ &i.CreatedAt,
+ &i.ClaimedAt,
+ &i.CompletedAt,
+ )
+ return i, err
+}
+
+const createIssueEnvironmentCommand = `-- name: CreateIssueEnvironmentCommand :one
+INSERT INTO issue_environment_command (
+ workspace_id, issue_id, runtime_id, environment_id, task_id, action,
+ local_key, repo, name, actor_type, actor_id
+) VALUES (
+ $1, $2, $3, $4, $5, $6,
+ $7, $8, $9, $10, $11
+)
+RETURNING id, workspace_id, issue_id, runtime_id, environment_id, task_id, action, local_key, repo, name, actor_type, actor_id, status, error, output, result_key, created_at, claimed_at, completed_at
+`
+
+type CreateIssueEnvironmentCommandParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ EnvironmentID pgtype.UUID `json:"environment_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Action string `json:"action"`
+ LocalKey string `json:"local_key"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+}
+
+func (q *Queries) CreateIssueEnvironmentCommand(ctx context.Context, arg CreateIssueEnvironmentCommandParams) (IssueEnvironmentCommand, error) {
+ row := q.db.QueryRow(ctx, createIssueEnvironmentCommand,
+ arg.WorkspaceID,
+ arg.IssueID,
+ arg.RuntimeID,
+ arg.EnvironmentID,
+ arg.TaskID,
+ arg.Action,
+ arg.LocalKey,
+ arg.Repo,
+ arg.Name,
+ arg.ActorType,
+ arg.ActorID,
+ )
+ var i IssueEnvironmentCommand
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.RuntimeID,
+ &i.EnvironmentID,
+ &i.TaskID,
+ &i.Action,
+ &i.LocalKey,
+ &i.Repo,
+ &i.Name,
+ &i.ActorType,
+ &i.ActorID,
+ &i.Status,
+ &i.Error,
+ &i.Output,
+ &i.ResultKey,
+ &i.CreatedAt,
+ &i.ClaimedAt,
+ &i.CompletedAt,
+ )
+ return i, err
+}
+
+const deleteIssueEnvironmentLogCommandsBefore = `-- name: DeleteIssueEnvironmentLogCommandsBefore :execrows
+DELETE FROM issue_environment_command
+WHERE action = 'logs' AND created_at < $1::timestamptz
+`
+
+func (q *Queries) DeleteIssueEnvironmentLogCommandsBefore(ctx context.Context, createdBefore pgtype.Timestamptz) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteIssueEnvironmentLogCommandsBefore, createdBefore)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const endIssueEnvironmentsMissingFromSnapshot = `-- name: EndIssueEnvironmentsMissingFromSnapshot :exec
UPDATE issue_environment
SET ended_at = now(),
@@ -33,8 +226,227 @@ func (q *Queries) EndIssueEnvironmentsMissingFromSnapshot(ctx context.Context, a
return err
}
+const getIssueEnvironment = `-- name: GetIssueEnvironment :one
+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, kind, repo, excerpt, controllable FROM issue_environment
+WHERE id = $1 AND issue_id = $2 AND workspace_id = $3
+`
+
+type GetIssueEnvironmentParams struct {
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetIssueEnvironment(ctx context.Context, arg GetIssueEnvironmentParams) (IssueEnvironment, error) {
+ row := q.db.QueryRow(ctx, getIssueEnvironment, arg.ID, arg.IssueID, arg.WorkspaceID)
+ 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,
+ &i.Kind,
+ &i.Repo,
+ &i.Excerpt,
+ &i.Controllable,
+ )
+ return i, err
+}
+
+const getIssueEnvironmentCommand = `-- name: GetIssueEnvironmentCommand :one
+SELECT id, workspace_id, issue_id, runtime_id, environment_id, task_id, action, local_key, repo, name, actor_type, actor_id, status, error, output, result_key, created_at, claimed_at, completed_at FROM issue_environment_command
+WHERE id = $1 AND issue_id = $2 AND workspace_id = $3
+`
+
+type GetIssueEnvironmentCommandParams struct {
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetIssueEnvironmentCommand(ctx context.Context, arg GetIssueEnvironmentCommandParams) (IssueEnvironmentCommand, error) {
+ row := q.db.QueryRow(ctx, getIssueEnvironmentCommand, arg.ID, arg.IssueID, arg.WorkspaceID)
+ var i IssueEnvironmentCommand
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.RuntimeID,
+ &i.EnvironmentID,
+ &i.TaskID,
+ &i.Action,
+ &i.LocalKey,
+ &i.Repo,
+ &i.Name,
+ &i.ActorType,
+ &i.ActorID,
+ &i.Status,
+ &i.Error,
+ &i.Output,
+ &i.ResultKey,
+ &i.CreatedAt,
+ &i.ClaimedAt,
+ &i.CompletedAt,
+ )
+ return i, err
+}
+
+const getIssueEnvironmentConfig = `-- name: GetIssueEnvironmentConfig :one
+SELECT task_id, workspace_id, issue_id, runtime_id, environments, reported_at FROM issue_environment_config
+WHERE task_id = $1 AND issue_id = $2 AND workspace_id = $3
+`
+
+type GetIssueEnvironmentConfigParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetIssueEnvironmentConfig(ctx context.Context, arg GetIssueEnvironmentConfigParams) (IssueEnvironmentConfig, error) {
+ row := q.db.QueryRow(ctx, getIssueEnvironmentConfig, arg.TaskID, arg.IssueID, arg.WorkspaceID)
+ var i IssueEnvironmentConfig
+ err := row.Scan(
+ &i.TaskID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.RuntimeID,
+ &i.Environments,
+ &i.ReportedAt,
+ )
+ return i, err
+}
+
+const hasOpenIssueEnvironmentControl = `-- name: HasOpenIssueEnvironmentControl :one
+SELECT EXISTS (
+ SELECT 1 FROM issue_environment_command
+ WHERE issue_id = $1
+ AND environment_id = $2
+ AND action IN ('stop', 'restart')
+ AND (
+ (status = 'pending' AND created_at > $3::timestamptz)
+ OR (status = 'claimed' AND claimed_at > $4::timestamptz)
+ )
+)
+`
+
+type HasOpenIssueEnvironmentControlParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ EnvironmentID pgtype.UUID `json:"environment_id"`
+ PendingAfter pgtype.Timestamptz `json:"pending_after"`
+ ClaimedAfter pgtype.Timestamptz `json:"claimed_after"`
+}
+
+// A stop or restart still waiting on the daemon for the same environment.
+func (q *Queries) HasOpenIssueEnvironmentControl(ctx context.Context, arg HasOpenIssueEnvironmentControlParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasOpenIssueEnvironmentControl,
+ arg.IssueID,
+ arg.EnvironmentID,
+ arg.PendingAfter,
+ arg.ClaimedAfter,
+ )
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
+const listIssueEnvironmentControls = `-- name: ListIssueEnvironmentControls :many
+SELECT id, workspace_id, issue_id, runtime_id, environment_id, task_id, action,
+ local_key, repo, name, actor_type, actor_id, status, error, result_key,
+ created_at, claimed_at, completed_at
+FROM issue_environment_command
+WHERE issue_id = $1
+ AND workspace_id = $2
+ AND action <> 'logs'
+ AND created_at > $3::timestamptz
+ORDER BY created_at DESC
+LIMIT 100
+`
+
+type ListIssueEnvironmentControlsParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CreatedAfter pgtype.Timestamptz `json:"created_after"`
+}
+
+type ListIssueEnvironmentControlsRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ EnvironmentID pgtype.UUID `json:"environment_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Action string `json:"action"`
+ LocalKey string `json:"local_key"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Status string `json:"status"`
+ Error string `json:"error"`
+ ResultKey string `json:"result_key"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ClaimedAt pgtype.Timestamptz `json:"claimed_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+}
+
+// Recent stops, restarts and starts, without log reads.
+func (q *Queries) ListIssueEnvironmentControls(ctx context.Context, arg ListIssueEnvironmentControlsParams) ([]ListIssueEnvironmentControlsRow, error) {
+ rows, err := q.db.Query(ctx, listIssueEnvironmentControls, arg.IssueID, arg.WorkspaceID, arg.CreatedAfter)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListIssueEnvironmentControlsRow{}
+ for rows.Next() {
+ var i ListIssueEnvironmentControlsRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.RuntimeID,
+ &i.EnvironmentID,
+ &i.TaskID,
+ &i.Action,
+ &i.LocalKey,
+ &i.Repo,
+ &i.Name,
+ &i.ActorType,
+ &i.ActorID,
+ &i.Status,
+ &i.Error,
+ &i.ResultKey,
+ &i.CreatedAt,
+ &i.ClaimedAt,
+ &i.CompletedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
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, kind FROM issue_environment
+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, kind, repo, excerpt, controllable FROM issue_environment
WHERE issue_id = $1
AND workspace_id = $2
AND (ended_at IS NULL OR ended_at > $3::timestamptz)
@@ -80,6 +492,49 @@ func (q *Queries) ListIssueEnvironments(ctx context.Context, arg ListIssueEnviro
&i.CreatedAt,
&i.UpdatedAt,
&i.Kind,
+ &i.Repo,
+ &i.Excerpt,
+ &i.Controllable,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listLatestIssueEnvironmentConfigs = `-- name: ListLatestIssueEnvironmentConfigs :many
+SELECT DISTINCT ON (runtime_id) task_id, workspace_id, issue_id, runtime_id, environments, reported_at
+FROM issue_environment_config
+WHERE issue_id = $1 AND workspace_id = $2
+ORDER BY runtime_id, reported_at DESC
+`
+
+type ListLatestIssueEnvironmentConfigsParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// The most recent task on each machine that declared environments.
+func (q *Queries) ListLatestIssueEnvironmentConfigs(ctx context.Context, arg ListLatestIssueEnvironmentConfigsParams) ([]IssueEnvironmentConfig, error) {
+ rows, err := q.db.Query(ctx, listLatestIssueEnvironmentConfigs, arg.IssueID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueEnvironmentConfig{}
+ for rows.Next() {
+ var i IssueEnvironmentConfig
+ if err := rows.Scan(
+ &i.TaskID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.RuntimeID,
+ &i.Environments,
+ &i.ReportedAt,
); err != nil {
return nil, err
}
@@ -92,7 +547,7 @@ func (q *Queries) ListIssueEnvironments(ctx context.Context, arg ListIssueEnviro
}
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, kind FROM issue_environment
+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, kind, repo, excerpt, controllable FROM issue_environment
WHERE task_id = $1 AND ended_at IS NULL
`
@@ -127,6 +582,9 @@ func (q *Queries) ListOpenIssueEnvironmentsByTask(ctx context.Context, taskID pg
&i.CreatedAt,
&i.UpdatedAt,
&i.Kind,
+ &i.Repo,
+ &i.Excerpt,
+ &i.Controllable,
); err != nil {
return nil, err
}
@@ -141,21 +599,26 @@ func (q *Queries) ListOpenIssueEnvironmentsByTask(ctx context.Context, taskID pg
const upsertIssueEnvironment = `-- name: UpsertIssueEnvironment :one
INSERT INTO issue_environment (
workspace_id, issue_id, task_id, runtime_id, agent_id, local_key, source,
- kind, name, label, url, port, state, detail, started_at, expires_at, ended_at
+ kind, repo, name, label, url, port, state, detail, started_at, expires_at, ended_at,
+ excerpt, controllable
) VALUES (
$1, $2, $3, $4, $5, $6, $7,
- $8, $9, $10, $11, $12, $13, $14, $15, $16,
- CASE WHEN $13::text IN ('exited', 'stopped') THEN now() END
+ $8, $9, $10, $11, $12, $13, $14, $15, $16, $17,
+ CASE WHEN $14::text IN ('exited', 'stopped') THEN now() END,
+ $18, $19
)
ON CONFLICT (task_id, local_key) DO UPDATE SET
source = EXCLUDED.source,
kind = EXCLUDED.kind,
+ repo = EXCLUDED.repo,
name = EXCLUDED.name,
label = EXCLUDED.label,
url = EXCLUDED.url,
port = EXCLUDED.port,
state = EXCLUDED.state,
detail = EXCLUDED.detail,
+ excerpt = EXCLUDED.excerpt,
+ controllable = EXCLUDED.controllable,
started_at = EXCLUDED.started_at,
expires_at = EXCLUDED.expires_at,
last_seen_at = now(),
@@ -163,26 +626,29 @@ ON CONFLICT (task_id, local_key) DO UPDATE SET
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, kind
+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, kind, repo, excerpt, controllable
`
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"`
- Kind string `json:"kind"`
- 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"`
+ 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"`
+ Kind string `json:"kind"`
+ Repo string `json:"repo"`
+ 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"`
+ Excerpt string `json:"excerpt"`
+ Controllable bool `json:"controllable"`
}
// A reported environment that has exited or stopped keeps its first ended_at,
@@ -197,6 +663,7 @@ func (q *Queries) UpsertIssueEnvironment(ctx context.Context, arg UpsertIssueEnv
arg.LocalKey,
arg.Source,
arg.Kind,
+ arg.Repo,
arg.Name,
arg.Label,
arg.Url,
@@ -205,6 +672,8 @@ func (q *Queries) UpsertIssueEnvironment(ctx context.Context, arg UpsertIssueEnv
arg.Detail,
arg.StartedAt,
arg.ExpiresAt,
+ arg.Excerpt,
+ arg.Controllable,
)
var i IssueEnvironment
err := row.Scan(
@@ -229,6 +698,37 @@ func (q *Queries) UpsertIssueEnvironment(ctx context.Context, arg UpsertIssueEnv
&i.CreatedAt,
&i.UpdatedAt,
&i.Kind,
+ &i.Repo,
+ &i.Excerpt,
+ &i.Controllable,
)
return i, err
}
+
+const upsertIssueEnvironmentConfig = `-- name: UpsertIssueEnvironmentConfig :exec
+INSERT INTO issue_environment_config (task_id, workspace_id, issue_id, runtime_id, environments)
+VALUES ($1, $2, $3, $4, $5)
+ON CONFLICT (task_id) DO UPDATE SET
+ runtime_id = EXCLUDED.runtime_id,
+ environments = EXCLUDED.environments,
+ reported_at = now()
+`
+
+type UpsertIssueEnvironmentConfigParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Environments []byte `json:"environments"`
+}
+
+func (q *Queries) UpsertIssueEnvironmentConfig(ctx context.Context, arg UpsertIssueEnvironmentConfigParams) error {
+ _, err := q.db.Exec(ctx, upsertIssueEnvironmentConfig,
+ arg.TaskID,
+ arg.WorkspaceID,
+ arg.IssueID,
+ arg.RuntimeID,
+ arg.Environments,
+ )
+ return err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 9612f8efc3..12b0242c99 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -969,27 +969,61 @@ type IssueDependency struct {
}
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"`
- Kind string `json:"kind"`
+ 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"`
+ Kind string `json:"kind"`
+ Repo string `json:"repo"`
+ Excerpt string `json:"excerpt"`
+ Controllable bool `json:"controllable"`
+}
+
+type IssueEnvironmentCommand struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ EnvironmentID pgtype.UUID `json:"environment_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Action string `json:"action"`
+ LocalKey string `json:"local_key"`
+ Repo string `json:"repo"`
+ Name string `json:"name"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Status string `json:"status"`
+ Error string `json:"error"`
+ Output pgtype.Text `json:"output"`
+ ResultKey string `json:"result_key"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ClaimedAt pgtype.Timestamptz `json:"claimed_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+}
+
+type IssueEnvironmentConfig struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Environments []byte `json:"environments"`
+ ReportedAt pgtype.Timestamptz `json:"reported_at"`
}
type IssueLabel struct {
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 2b474886d0..2cc7e7a9c0 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -501,6 +501,12 @@ deleted_app_tool_calls AS (
deleted_issue_environments AS (
DELETE FROM issue_environment WHERE workspace_id = $1
),
+deleted_issue_environment_commands AS (
+ DELETE FROM issue_environment_command WHERE workspace_id = $1
+),
+deleted_issue_environment_configs AS (
+ DELETE FROM issue_environment_config 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.sql
index 2a2c980e86..fa1ab1b483 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -509,6 +509,12 @@ cleared_unread AS (
),
cleared_environments AS (
DELETE FROM issue_environment WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_environment_commands AS (
+ DELETE FROM issue_environment_command WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_environment_configs AS (
+ DELETE FROM issue_environment_config 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.sql
index 37942ea1dc..751547bb76 100644
--- a/server/pkg/db/queries/issue_environment.sql
+++ b/server/pkg/db/queries/issue_environment.sql
@@ -7,21 +7,26 @@ WHERE task_id = $1 AND ended_at IS NULL;
-- 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,
- kind, name, label, url, port, state, detail, started_at, expires_at, ended_at
+ kind, repo, name, label, url, port, state, detail, started_at, expires_at, ended_at,
+ excerpt, controllable
) VALUES (
@workspace_id, @issue_id, @task_id, @runtime_id, @agent_id, @local_key, @source,
- @kind, @name, @label, @url, @port, @state, @detail, @started_at, @expires_at,
- CASE WHEN @state::text IN ('exited', 'stopped') THEN now() END
+ @kind, @repo, @name, @label, @url, @port, @state, @detail, @started_at, @expires_at,
+ CASE WHEN @state::text IN ('exited', 'stopped') THEN now() END,
+ @excerpt, @controllable
)
ON CONFLICT (task_id, local_key) DO UPDATE SET
source = EXCLUDED.source,
kind = EXCLUDED.kind,
+ repo = EXCLUDED.repo,
name = EXCLUDED.name,
label = EXCLUDED.label,
url = EXCLUDED.url,
port = EXCLUDED.port,
state = EXCLUDED.state,
detail = EXCLUDED.detail,
+ excerpt = EXCLUDED.excerpt,
+ controllable = EXCLUDED.controllable,
started_at = EXCLUDED.started_at,
expires_at = EXCLUDED.expires_at,
last_seen_at = now(),
@@ -50,3 +55,96 @@ WHERE issue_id = @issue_id
AND (ended_at IS NULL OR ended_at > @ended_after::timestamptz)
ORDER BY created_at DESC
LIMIT 50;
+
+-- name: GetIssueEnvironment :one
+SELECT * FROM issue_environment
+WHERE id = @id AND issue_id = @issue_id AND workspace_id = @workspace_id;
+
+-- name: CreateIssueEnvironmentCommand :one
+INSERT INTO issue_environment_command (
+ workspace_id, issue_id, runtime_id, environment_id, task_id, action,
+ local_key, repo, name, actor_type, actor_id
+) VALUES (
+ @workspace_id, @issue_id, @runtime_id, @environment_id, @task_id, @action,
+ @local_key, @repo, @name, @actor_type, @actor_id
+)
+RETURNING *;
+
+-- name: HasOpenIssueEnvironmentControl :one
+-- A stop or restart still waiting on the daemon for the same environment.
+SELECT EXISTS (
+ SELECT 1 FROM issue_environment_command
+ WHERE issue_id = @issue_id
+ AND environment_id = @environment_id
+ AND action IN ('stop', 'restart')
+ AND (
+ (status = 'pending' AND created_at > @pending_after::timestamptz)
+ OR (status = 'claimed' AND claimed_at > @claimed_after::timestamptz)
+ )
+);
+
+-- name: ClaimIssueEnvironmentCommands :many
+-- Commands older than the pending window were already reported to the member
+-- as unanswered, so they are never carried out late.
+UPDATE issue_environment_command
+SET status = 'claimed', claimed_at = now()
+WHERE id IN (
+ SELECT c.id FROM issue_environment_command c
+ WHERE c.runtime_id = @runtime_id
+ AND c.status = 'pending'
+ AND c.created_at > @pending_after::timestamptz
+ ORDER BY c.created_at
+ LIMIT 20
+ FOR UPDATE SKIP LOCKED
+)
+RETURNING *;
+
+-- name: CompleteIssueEnvironmentCommand :one
+UPDATE issue_environment_command
+SET status = @status,
+ error = @error,
+ output = sqlc.narg('output'),
+ result_key = @result_key,
+ completed_at = now()
+WHERE id = @id AND runtime_id = @runtime_id AND status = 'claimed'
+RETURNING *;
+
+-- name: GetIssueEnvironmentCommand :one
+SELECT * FROM issue_environment_command
+WHERE id = @id AND issue_id = @issue_id AND workspace_id = @workspace_id;
+
+-- name: ListIssueEnvironmentControls :many
+-- Recent stops, restarts and starts, without log reads.
+SELECT id, workspace_id, issue_id, runtime_id, environment_id, task_id, action,
+ local_key, repo, name, actor_type, actor_id, status, error, result_key,
+ created_at, claimed_at, completed_at
+FROM issue_environment_command
+WHERE issue_id = @issue_id
+ AND workspace_id = @workspace_id
+ AND action <> 'logs'
+ AND created_at > @created_after::timestamptz
+ORDER BY created_at DESC
+LIMIT 100;
+
+-- name: DeleteIssueEnvironmentLogCommandsBefore :execrows
+DELETE FROM issue_environment_command
+WHERE action = 'logs' AND created_at < @created_before::timestamptz;
+
+-- name: UpsertIssueEnvironmentConfig :exec
+INSERT INTO issue_environment_config (task_id, workspace_id, issue_id, runtime_id, environments)
+VALUES (@task_id, @workspace_id, @issue_id, @runtime_id, @environments)
+ON CONFLICT (task_id) DO UPDATE SET
+ runtime_id = EXCLUDED.runtime_id,
+ environments = EXCLUDED.environments,
+ reported_at = now();
+
+-- name: ListLatestIssueEnvironmentConfigs :many
+-- The most recent task on each machine that declared environments.
+SELECT DISTINCT ON (runtime_id) *
+FROM issue_environment_config
+WHERE issue_id = @issue_id AND workspace_id = @workspace_id
+ORDER BY runtime_id, reported_at DESC;
+
+-- name: GetIssueEnvironmentConfig :one
+SELECT * FROM issue_environment_config
+WHERE task_id = @task_id AND issue_id = @issue_id AND workspace_id = @workspace_id;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 50a21a4e3b..e57a626a39 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -511,6 +511,12 @@ deleted_app_tool_calls AS (
deleted_issue_environments AS (
DELETE FROM issue_environment WHERE workspace_id = $1
),
+deleted_issue_environment_commands AS (
+ DELETE FROM issue_environment_command WHERE workspace_id = $1
+),
+deleted_issue_environment_configs AS (
+ DELETE FROM issue_environment_config WHERE workspace_id = $1
+),
deleted_workspace_app_settings AS (
DELETE FROM workspace_app_setting WHERE workspace_id = $1
),
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index f895d52efa..f90584fe7c 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -186,6 +186,10 @@ const (
PendingWorkKindModelList = "model_list"
PendingWorkKindLocalSkills = "local_skills"
PendingWorkKindLocalSkillImport = "local_skill_import"
+ // PendingWorkKindEnvironmentCommand asks a daemon that supports it to claim
+ // its queued environment commands instead of heartbeating. Older daemons
+ // heartbeat as for any kind, which claims nothing.
+ PendingWorkKindEnvironmentCommand = "environment_command"
)
// PendingWorkPayload is sent from server to daemon as a wakeup hint when a