Skip to content

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

Go

feat(environments): switch to desktop app windows from the issue sidebar (MUL-8985) (#10328)

Jiayuan Zhang30f2731c3d5f
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
index a29c2c8396..4a6f6b9ec2 100644
--- a/apps/desktop/src/main/daemon-manager.ts
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -59,6 +59,7 @@ import {
type AuthProbeResult,
} from "./daemon-auth-probe";
import { daemonSpawnEnv } from "./daemon-spawn-env";
+import { focusEnvironmentAt, type FocusEnvironmentResult } from "./environment-focus";
const POLL_INTERVAL_MS = 5_000;
const PREFS_PATH = join(homedir(), ".multica", "desktop_prefs.json");
@@ -229,6 +230,21 @@ async function fetchProfileHealth(
);
}
+/** Brings forward a desktop app this profile's daemon detected. */
+async function focusEnvironment(key: unknown): Promise<FocusEnvironmentResult> {
+ if (typeof key !== "string" || key === "" || key.length > 128) {
+ return { ok: false, reason: "failed", error: "invalid environment key" };
+ }
+ const active = await ensureActiveProfile();
+ if (!active) return { ok: false, reason: "unavailable" };
+ const health = await probeProfileHealth(active.name, async (port) => {
+ const payload = await fetchHealthAtPort(port);
+ return payload ? { ...payload, port } : null;
+ });
+ if (!health || health.status !== "running") return { ok: false, reason: "unavailable" };
+ return focusEnvironmentAt(health.port, key);
+}
+
/**
* Validates the daemon profile's token against the backend to find out whether
* a stuck start is an auth problem. Hits the same endpoint `multica auth status`
@@ -1486,6 +1502,7 @@ export function setupDaemonManager(
});
ipcMain.handle("daemon:get-status", () => fetchHealth());
ipcMain.handle("daemon:probe-runtimes", () => probeLocalRuntimes());
+ ipcMain.handle("daemon:focus-environment", (_e, key: unknown) => focusEnvironment(key));
// The host's OS name, available regardless of daemon state. The Runtimes
// page uses it as a fallback identity for "this machine" when no
// app-managed daemon is reporting a device name (e.g. the daemon runs
diff --git a/apps/desktop/src/main/environment-focus.test.ts b/apps/desktop/src/main/environment-focus.test.ts
new file mode 100644
index 0000000000..a9447609ea
--- /dev/null
+++ b/apps/desktop/src/main/environment-focus.test.ts
@@ -0,0 +1,48 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from "vitest";
+import { focusEnvironmentAt } from "./environment-focus";
+
+function respond(status: number, body: string, contentType = "application/json") {
+ return vi.fn(async () => new Response(body, { status, headers: { "Content-Type": contentType } }));
+}
+
+describe("focusEnvironmentAt", () => {
+ it("posts the key as JSON to the daemon's focus endpoint", async () => {
+ const fetchImpl = respond(200, `{"focused":true}`);
+ await expect(focusEnvironmentAt(19514, "detected:abc", fetchImpl)).resolves.toEqual({ ok: true });
+ const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toBe("http://127.0.0.1:19514/environments/focus");
+ expect(init.method).toBe("POST");
+ expect(init.headers).toEqual({ "Content-Type": "application/json" });
+ expect(JSON.parse(init.body as string)).toEqual({ key: "detected:abc" });
+ });
+
+ it("passes on why the daemon could not bring the app forward", async () => {
+ await expect(
+ focusEnvironmentAt(1, "k", respond(404, `{"reason":"gone","error":"the app is no longer running"}`)),
+ ).resolves.toEqual({ ok: false, reason: "gone", error: "the app is no longer running" });
+ await expect(focusEnvironmentAt(1, "k", respond(501, `{"reason":"unsupported"}`))).resolves.toEqual({
+ ok: false,
+ reason: "unsupported",
+ });
+ await expect(focusEnvironmentAt(1, "k", respond(403, `{"reason":"forbidden","error":"no"}`))).resolves.toEqual({
+ ok: false,
+ reason: "failed",
+ error: "no",
+ });
+ });
+
+ it("treats a daemon without the endpoint as unsupported", async () => {
+ await expect(focusEnvironmentAt(1, "k", respond(404, "404 page not found\n", "text/plain"))).resolves.toEqual({
+ ok: false,
+ reason: "unsupported",
+ });
+ });
+
+ it("reports an unreachable daemon as unavailable", async () => {
+ const fetchImpl = vi.fn(async () => {
+ throw new TypeError("fetch failed");
+ });
+ await expect(focusEnvironmentAt(1, "k", fetchImpl)).resolves.toEqual({ ok: false, reason: "unavailable" });
+ });
+});
diff --git a/apps/desktop/src/main/environment-focus.ts b/apps/desktop/src/main/environment-focus.ts
new file mode 100644
index 0000000000..72bf04209a
--- /dev/null
+++ b/apps/desktop/src/main/environment-focus.ts
@@ -0,0 +1,41 @@
+export type FocusEnvironmentResult =
+ | { ok: true }
+ | { ok: false; reason: "gone" | "unsupported" | "unavailable" | "failed"; error?: string };
+
+const FOCUS_TIMEOUT_MS = 15_000;
+const REASONS = new Set(["gone", "unsupported", "unavailable", "failed"]);
+
+/**
+ * Asks the daemon on `port` to bring the desktop app it detected under `key`
+ * forward. Node's fetch sends no Origin header, which is how the daemon tells
+ * this call apart from a web page's.
+ */
+export async function focusEnvironmentAt(
+ port: number,
+ key: string,
+ fetchImpl: typeof fetch = fetch,
+): Promise<FocusEnvironmentResult> {
+ let res: Response;
+ try {
+ res = await fetchImpl(`http://127.0.0.1:${port}/environments/focus`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ key }),
+ signal: AbortSignal.timeout(FOCUS_TIMEOUT_MS),
+ });
+ } catch {
+ return { ok: false, reason: "unavailable" };
+ }
+ if (res.ok) return { ok: true };
+ let body: { reason?: unknown; error?: unknown } | null = null;
+ try {
+ body = (await res.json()) as { reason?: unknown; error?: unknown };
+ } catch {
+ body = null;
+ }
+ // A daemon older than this endpoint answers its mux's plain-text 404.
+ if (!body || typeof body.reason !== "string") return { ok: false, reason: "unsupported" };
+ const error = typeof body.error === "string" ? body.error : undefined;
+ if (!REASONS.has(body.reason)) return { ok: false, reason: "failed", error };
+ return { ok: false, reason: body.reason as "gone" | "unsupported" | "unavailable" | "failed", error };
+}
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index b10b29e259..c518c926a1 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -165,6 +165,10 @@ type DaemonReauthResult =
| { ok: false; reason: "session_invalid" }
| { ok: false; reason: "transient"; message: string };
+type FocusEnvironmentResult =
+ | { ok: true }
+ | { ok: false; reason: "gone" | "unsupported" | "unavailable" | "failed"; error?: string };
+
interface DaemonAPI {
start: () => Promise<{ success: boolean; error?: string }>;
stop: () => Promise<{ success: boolean; error?: string }>;
@@ -172,6 +176,8 @@ interface DaemonAPI {
getStatus: () => Promise<DaemonStatus>;
probeRuntimes: () => Promise<LocalRuntimeProbe>;
getHostName: () => Promise<string>;
+ /** Brings forward a desktop app environment the local daemon detected. */
+ focusEnvironment: (key: string) => Promise<FocusEnvironmentResult>;
onStatusChange: (callback: (status: DaemonStatus) => void) => () => void;
setTargetApiUrl: (url: string) => Promise<void>;
syncToken: (token: string, userId: string) => Promise<void>;
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index e7aaf573a8..d5d95177fb 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -339,6 +339,10 @@ type DaemonReauthResult =
| { ok: false; reason: "session_invalid" }
| { ok: false; reason: "transient"; message: string };
+type FocusEnvironmentResult =
+ | { ok: true }
+ | { ok: false; reason: "gone" | "unsupported" | "unavailable" | "failed"; error?: string };
+
const daemonAPI = {
start: (): Promise<{ success: boolean; error?: string }> =>
ipcRenderer.invoke("daemon:start"),
@@ -352,6 +356,8 @@ const daemonAPI = {
ipcRenderer.invoke("daemon:probe-runtimes"),
getHostName: (): Promise<string> =>
ipcRenderer.invoke("daemon:get-host-name"),
+ focusEnvironment: (key: string): Promise<FocusEnvironmentResult> =>
+ ipcRenderer.invoke("daemon:focus-environment", key),
onStatusChange: (callback: (status: DaemonStatus) => void) => {
const handler = (_: unknown, status: DaemonStatus) => callback(status);
ipcRenderer.on("daemon:status", handler);
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 3314a27457..9a8be67734 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -296,7 +296,9 @@ describe("ApiClient issue environments response schema", () => {
task_id: "task-1",
runtime_id: "rt-1",
agent_id: "agent-1",
+ local_key: "config:web",
source: "config",
+ kind: "server",
name: "web",
label: "Web app",
url: "http://localhost:41000",
@@ -339,6 +341,34 @@ describe("ApiClient issue environments response schema", () => {
expect(result.environments[0]).toMatchObject({ state: "unreachable", source: "detected" });
});
+ it("keeps a desktop app's kind and the key its daemon knows it by", async () => {
+ stubEnvironments({
+ environments: [{ ...validEnvironment, kind: "app", local_key: "detected:app", url: "", port: null }],
+ });
+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");
+ expect(result.environments[0]).toMatchObject({ kind: "app", local_key: "detected:app" });
+ });
+
+ it("reads an older server's environment, with no kind or key, as a server", async () => {
+ const { kind: _kind, local_key: _key, ...older } = validEnvironment;
+ stubEnvironments({ environments: [older] });
+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");
+ expect(result.environments[0]).toMatchObject({ kind: "server", local_key: "", url: "http://localhost:41000" });
+ });
+
+ it("reads an unknown kind as a server and a malformed key as none", async () => {
+ stubEnvironments({
+ environments: [
+ { ...validEnvironment, kind: "tunnel", local_key: { key: "config:web" } },
+ { ...validEnvironment, id: "env-2", kind: "app", local_key: null },
+ ],
+ });
+ const result = await new ApiClient("https://api.example.test").listIssueEnvironments("issue-1");
+ expect(result.environments).toHaveLength(2);
+ expect(result.environments[0]).toMatchObject({ kind: "server", local_key: "" });
+ expect(result.environments[1]).toMatchObject({ kind: "app", local_key: "" });
+ });
+
it("falls back to an empty list when the body is not a list", async () => {
stubEnvironments({ environments: "nope" });
await expect(
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 5c79be68fb..e44d6891d1 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -468,14 +468,19 @@ export const EMPTY_ISSUE_PULL_REQUESTS_RESPONSE: IssuePullRequestsResponse = {
// 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.
+// unreachable, which offers no Open action. A kind this client does not know,
+// or none from an older server, reads as a server: the row then opens its URL
+// if it has one and offers nothing otherwise. A missing or malformed
+// local_key reads as empty, which leaves an app row without its switch action.
export const IssueEnvironmentSchema = z.object({
id: z.string(),
issue_id: z.string(),
task_id: z.string(),
runtime_id: z.string().nullable().optional().default(null),
agent_id: z.string().nullable().optional().default(null),
+ local_key: z.string().catch(""),
source: z.enum(["config", "detected"]).catch("detected"),
+ kind: z.enum(["server", "app"]).catch("server"),
name: z.string(),
label: z.string().optional().default(""),
url: z.string().optional().default(""),
diff --git a/packages/core/types/environment.ts b/packages/core/types/environment.ts
index e456445a54..f056e1bf54 100644
--- a/packages/core/types/environment.ts
+++ b/packages/core/types/environment.ts
@@ -3,6 +3,10 @@
* a task directory. */
export type IssueEnvironmentSource = "config" | "detected";
+/** A `server` opens at its URL; an `app` is a desktop app with no URL, whose
+ * window only Desktop on the machine running it can bring forward. */
+export type IssueEnvironmentKind = "server" | "app";
+
/** `unreachable` is derived by the server when the daemon that reported a
* live environment has gone quiet. */
export type IssueEnvironmentState = "starting" | "running" | "exited" | "stopped" | "unreachable";
@@ -13,7 +17,10 @@ export interface IssueEnvironment {
task_id: string;
runtime_id: string | null;
agent_id: string | null;
+ /** The reporting daemon's own name for the environment. */
+ local_key: string;
source: IssueEnvironmentSource;
+ kind: IssueEnvironmentKind;
name: string;
label: string;
url: string;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index ab7609fa79..1a22191c6f 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -238,6 +238,7 @@ export type {
export type {
IssueEnvironment,
IssueEnvironmentSource,
+ IssueEnvironmentKind,
IssueEnvironmentState,
IssueEnvironmentsResponse,
} from "./environment";
diff --git a/packages/views/issues/components/issue-environments-section.test.tsx b/packages/views/issues/components/issue-environments-section.test.tsx
index 7475757fed..464d474d8e 100644
--- a/packages/views/issues/components/issue-environments-section.test.tsx
+++ b/packages/views/issues/components/issue-environments-section.test.tsx
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, within } from "@testing-library/react";
+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";
@@ -35,6 +35,9 @@ vi.mock("../../platform/use-local-daemon-status", () => ({
}));
const copyText = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@multica/ui/lib/clipboard", () => ({ copyText }));
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({ toast: { error: toastError, success: vi.fn() } }));
+const focusEnvironment = vi.fn();
import { IssueEnvironmentsSection } from "./issue-environments-section";
@@ -68,7 +71,9 @@ function environment(overrides: Partial<IssueEnvironment>): IssueEnvironment {
task_id: "task-1",
runtime_id: "rt-1",
agent_id: "agent-1",
+ local_key: "config:abc",
source: "config",
+ kind: "server",
name: "web",
label: "Web app",
url: "http://localhost:41000",
@@ -100,6 +105,9 @@ describe("IssueEnvironmentsSection", () => {
mockRuntimes = [runtime({}), runtime({ id: "rt-2", daemon_id: "daemon-2", name: "Codex (build-02)", device_info: "build-02" })];
mockLocalDaemonId = null;
copyText.mockClear();
+ toastError.mockClear();
+ focusEnvironment.mockReset();
+ delete (window as { daemonAPI?: unknown }).daemonAPI;
});
it("renders nothing while the issue has no environments", async () => {
@@ -175,6 +183,104 @@ describe("IssueEnvironmentsSection", () => {
expect(within(ended).queryByRole("link")).not.toBeInTheDocument();
});
+ describe("desktop apps", () => {
+ const app = (overrides: Partial<IssueEnvironment> = {}) =>
+ environment({
+ id: "env-app",
+ local_key: "detected:app",
+ source: "detected",
+ kind: "app",
+ name: "Multica Canary multica-501",
+ label: "",
+ url: "",
+ port: null,
+ detail: "Remote debugging on localhost:9724",
+ expires_at: null,
+ ...overrides,
+ });
+ const onDesktop = () => {
+ mockLocalDaemonId = "daemon-1";
+ (window as { daemonAPI?: unknown }).daemonAPI = { focusEnvironment };
+ };
+
+ it("switches to the app's window on the machine whose daemon found it", async () => {
+ onDesktop();
+ focusEnvironment.mockResolvedValue({ ok: true });
+ mockEnvironments = [app()];
+ renderSection();
+
+ const row = await screen.findByTestId("environment-row");
+ expect(within(row).getByText("Multica Canary multica-501")).toBeVisible();
+ expect(within(row).queryByText(/localhost/)).not.toBeInTheDocument();
+ expect(within(row).queryByRole("link")).not.toBeInTheDocument();
+ expect(row).toHaveAttribute("title", expect.stringContaining("Remote debugging on localhost:9724"));
+
+ fireEvent.click(within(row).getByText("Multica Canary multica-501"));
+ fireEvent.click(within(row).getByRole("button", { name: "Switch to window" }));
+ await waitFor(() => expect(focusEnvironment).toHaveBeenCalledTimes(2));
+ expect(focusEnvironment).toHaveBeenCalledWith("detected:app");
+ expect(toastError).not.toHaveBeenCalled();
+ });
+
+ it("offers no switch for an app whose key did not arrive", async () => {
+ onDesktop();
+ mockEnvironments = [app({ local_key: "" })];
+ renderSection();
+
+ const row = await screen.findByTestId("environment-row");
+ expect(within(row).queryByRole("button")).not.toBeInTheDocument();
+ fireEvent.click(within(row).getByText("Multica Canary multica-501"));
+ expect(focusEnvironment).not.toHaveBeenCalled();
+ });
+
+ it("says so when the app has exited instead of opening anything", async () => {
+ onDesktop();
+ focusEnvironment.mockResolvedValue({ ok: false, reason: "gone" });
+ mockEnvironments = [app()];
+ renderSection();
+
+ fireEvent.click(await screen.findByRole("button", { name: "Switch to window" }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith("Multica Canary multica-501 is no longer running"));
+ });
+
+ it("cannot be switched to from another machine", async () => {
+ onDesktop();
+ mockEnvironments = [app({ runtime_id: "rt-2" })];
+ renderSection();
+
+ const row = await screen.findByTestId("environment-row");
+ expect(within(row).queryByRole("button")).not.toBeInTheDocument();
+ expect(row).toHaveAttribute("title", expect.stringContaining("Runs on build-02. Switch to its window from Multica Desktop on that machine."));
+ });
+
+ it("cannot be switched to on web", async () => {
+ mockEnvironments = [app(), app({ id: "env-app-2", runtime_id: "rt-gone", name: "Other App" })];
+ renderSection();
+
+ await screen.findByText("Multica Canary multica-501");
+ const rows = screen.getAllByTestId("environment-row");
+ for (const row of rows) {
+ expect(within(row).queryByRole("button")).not.toBeInTheDocument();
+ expect(within(row).queryByRole("link")).not.toBeInTheDocument();
+ }
+ const row = (name: string) => rows.find((r) => within(r).queryByText(name))!;
+ expect(row("Multica Canary multica-501")).toHaveAttribute("title", expect.stringContaining("Runs on studio.local. Switch to its window from Multica Desktop on that machine."));
+ expect(row("Other App")).toHaveAttribute("title", expect.stringContaining("Switch to its window from Multica Desktop on the machine running it."));
+ expect(focusEnvironment).not.toHaveBeenCalled();
+ });
+
+ it("cannot be switched to once it has ended", async () => {
+ onDesktop();
+ mockEnvironments = [environment({}), app({ state: "stopped", ended_at: new Date().toISOString() })];
+ renderSection();
+
+ fireEvent.click(await screen.findByRole("button", { name: /1 ended/ }));
+ const ended = screen.getAllByTestId("environment-row")[1]!;
+ expect(within(ended).getByText("Multica Canary multica-501")).toBeVisible();
+ expect(within(ended).queryByRole("button")).not.toBeInTheDocument();
+ });
+ });
+
it("offers no link for an environment whose daemon went quiet", async () => {
mockEnvironments = [environment({ state: "unreachable" })];
renderSection();
diff --git a/packages/views/issues/components/issue-environments-section.tsx b/packages/views/issues/components/issue-environments-section.tsx
index 37917894ea..9b7b1a0444 100644
--- a/packages/views/issues/components/issue-environments-section.tsx
+++ b/packages/views/issues/components/issue-environments-section.tsx
@@ -3,7 +3,7 @@
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
-import { ChevronRight, Copy, ExternalLink, Globe, Laptop, Server } from "@multica/ui/icons";
+import { AppWindow, ArrowUpRight, ChevronRight, Copy, ExternalLink, Globe, Laptop, Server } from "@multica/ui/icons";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { issueEnvironmentsOptions } from "@multica/core/issues/queries";
@@ -13,6 +13,7 @@ import { IconButton } from "@multica/ui/components/common/icon-button";
import { copyText } from "@multica/ui/lib/clipboard";
import { cn } from "@multica/ui/lib/utils";
import { useT, useTimeAgo } from "../../i18n";
+import { canFocusLocalEnvironments, focusLocalEnvironment } from "../../platform/environment-focus";
import { useLocalDaemonStatus } from "../../platform/use-local-daemon-status";
import { buildRuntimeMachines, type RuntimeMachine } from "../../runtimes/components/runtime-machines";
import { IssueSidebarSectionHeader } from "./issue-sidebar-section";
@@ -28,6 +29,7 @@ const STATE_TONE: Record<IssueEnvironmentState, string> = {
};
const isLive = (env: IssueEnvironment) => env.ended_at === null;
+const isApp = (env: IssueEnvironment) => env.kind === "app";
type MachineGroup = { key: string; machine: RuntimeMachine | null; envs: IssueEnvironment[] };
@@ -35,8 +37,9 @@ type MachineGroup = { key: string; machine: RuntimeMachine | null; envs: IssueEn
* "Environments" in the issue sidebar: the servers this issue's runs left
* running — declared in the repository's `.multica/environments.toml` or
* found listening in a run's directory — grouped by the machine they run on,
- * because a localhost URL only opens there. Renders nothing until a run
- * starts one.
+ * 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.
*/
export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
const { t } = useT("issues");
@@ -77,6 +80,16 @@ export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
? 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 groups = (list: IssueEnvironment[]) => {
const byMachine = new Map<string, MachineGroup>();
@@ -105,6 +118,7 @@ export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
key={env.id}
env={env}
localhostHint={localhostHint(group.machine)}
+ appHint={appHint(group.machine)}
/>
))}
</div>
@@ -147,28 +161,50 @@ export function IssueEnvironmentsSection({ issueId }: { issueId: string }) {
);
}
-function EnvironmentRow({ env, localhostHint }: { env: IssueEnvironment; localhostHint: string | null }) {
+function EnvironmentRow({
+ env,
+ localhostHint,
+ appHint,
+}: {
+ env: IssueEnvironment;
+ localhostHint: string | null;
+ /** Why this machine cannot switch to an app's window; null when it can. */
+ appHint: string | null;
+}) {
const { t } = useT("issues");
const timeAgo = useTimeAgo();
const live = isLive(env);
- const openable = live && env.url !== "" && env.state !== "unreachable";
- const Icon = env.url ? Globe : Server;
- const host = env.url ? displayHost(env.url) : null;
- const title = env.source === "config" ? env.label || env.name : host ?? env.name;
+ const app = isApp(env);
+ const openable = !app && live && 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 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 {
+ } else if (!app) {
parts.push(env.name);
}
const meta = environmentMeta(env, t, timeAgo);
const tooltip = [
env.source === "detected" ? t(($) => $.environments.detected_hint) : null,
env.detail || null,
- isLoopbackUrl(env.url) ? localhostHint : null,
+ app ? appHint : isLoopbackUrl(env.url) ? localhostHint : null,
].filter(Boolean).join("\n");
+ const focus = () => {
+ void focusLocalEnvironment(env.local_key).then((result) => {
+ if (result.ok) return;
+ if (result.reason === "gone") toast.error(t(($) => $.environments.focus_gone, { name: title }));
+ else if (result.reason === "unsupported") toast.error(t(($) => $.environments.focus_unsupported));
+ else if (result.reason === "unavailable") toast.error(t(($) => $.environments.focus_unavailable));
+ else toast.error(t(($) => $.environments.focus_failed, { name: title }));
+ });
+ };
+
const body = (
<>
<Icon className={cn("mt-px size-3.5 shrink-0", STATE_TONE[env.state] ?? "text-muted-foreground")} />
@@ -179,7 +215,7 @@ function EnvironmentRow({ env, localhostHint }: { env: IssueEnvironment; localho
className={cn(
"shrink-0 text-caption",
STATE_TONE[env.state] ?? "text-muted-foreground",
- openable && "group-hover/env:invisible group-has-[:focus-visible]/env:invisible [@media(pointer:coarse)]:invisible",
+ (openable || focusable) && "group-hover/env:invisible group-has-[:focus-visible]/env:invisible [@media(pointer:coarse)]:invisible",
)}
>
{t(($) => $.environments.state[env.state])}
@@ -200,9 +236,20 @@ function EnvironmentRow({ env, localhostHint }: { env: IssueEnvironment; localho
<a href={env.url} target="_blank" rel="noreferrer noopener" className="flex items-start gap-2 rounded-md px-2 py-2">
{body}
</a>
+ ) : focusable ? (
+ <button type="button" onClick={focus} className="flex w-full items-start gap-2 rounded-md px-2 py-2 text-left">
+ {body}
+ </button>
) : (
<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>
+ </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
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 6b4cfd4fc2..1a0b0bdc98 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1938,6 +1938,13 @@
"open": "Open",
"copy_url": "Copy URL",
"copied": "URL copied",
- "copy_failed": "Couldn't copy the URL"
+ "copy_failed": "Couldn't copy the URL",
+ "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}}"
}
}
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index a8fca9a39b..17671e9258 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -1938,6 +1938,13 @@
"open": "Abrir",
"copy_url": "Copiar URL",
"copied": "URL copiada",
- "copy_failed": "No se pudo copiar la URL"
+ "copy_failed": "No se pudo copiar la URL",
+ "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}}"
}
}
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index b59aaff8b8..f3a721bca0 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -1938,6 +1938,13 @@
"open": "Ouvrir",
"copy_url": "Copier l'URL",
"copied": "URL copiée",
- "copy_failed": "Impossible de copier l'URL"
+ "copy_failed": "Impossible de copier l'URL",
+ "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}}"
}
}
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index a57b0c612f..8ad881b66d 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -1862,6 +1862,13 @@
"open": "開く",
"copy_url": "URL をコピー",
"copied": "URL をコピーしました",
- "copy_failed": "URL をコピーできませんでした"
+ "copy_failed": "URL をコピーできませんでした",
+ "app_desktop_hint": "デスクトップアプリです。実行中のマシンの Multica Desktop からウィンドウに切り替えられます。",
+ "app_remote_hint": "{{machine}} で実行中です。そのマシンの Multica Desktop からウィンドウに切り替えられます。",
+ "focus": "ウィンドウに切り替え",
+ "focus_gone": "{{name}} はもう実行されていません",
+ "focus_unsupported": "このマシンのデーモンはまだアプリのウィンドウに切り替えられません。Multica を更新してもう一度お試しください。",
+ "focus_unavailable": "ローカルのデーモンが実行されていません",
+ "focus_failed": "{{name}} に切り替えられませんでした"
}
}
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 804bb7a395..3dc8f4340a 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -1862,6 +1862,13 @@
"open": "열기",
"copy_url": "URL 복사",
"copied": "URL을 복사했습니다",
- "copy_failed": "URL을 복사할 수 없습니다"
+ "copy_failed": "URL을 복사할 수 없습니다",
+ "app_desktop_hint": "데스크톱 앱입니다. 실행 중인 머신의 Multica Desktop에서 창으로 전환할 수 있습니다.",
+ "app_remote_hint": "{{machine}}에서 실행 중입니다. 해당 머신의 Multica Desktop에서 창으로 전환할 수 있습니다.",
+ "focus": "창으로 전환",
+ "focus_gone": "{{name}}이(가) 더 이상 실행되고 있지 않습니다",
+ "focus_unsupported": "이 머신의 데몬은 아직 앱 창으로 전환할 수 없습니다. Multica를 업데이트한 뒤 다시 시도하세요.",
+ "focus_unavailable": "로컬 데몬이 실행되고 있지 않습니다",
+ "focus_failed": "{{name}}(으)로 전환할 수 없습니다"
}
}
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index 69c9afbc61..525f1dc47e 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -2096,6 +2096,13 @@
"open": "Открыть",
"copy_url": "Копировать URL",
"copied": "URL скопирован",
- "copy_failed": "Не удалось скопировать URL"
+ "copy_failed": "Не удалось скопировать URL",
+ "app_desktop_hint": "Настольное приложение. Переключиться на его окно можно из Multica Desktop на машине, где оно запущено.",
+ "app_remote_hint": "Запущено на {{machine}}. Переключиться на его окно можно из Multica Desktop на этой машине.",
+ "focus": "Перейти к окну",
+ "focus_gone": "{{name}} больше не запущено",
+ "focus_unsupported": "Демон на этой машине пока не умеет переключаться на окна приложений. Обновите Multica и попробуйте снова.",
+ "focus_unavailable": "Локальный демон не запущен",
+ "focus_failed": "Не удалось переключиться на {{name}}"
}
}
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index b50165ded6..2689f47ee6 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -1862,6 +1862,13 @@
"open": "打开",
"copy_url": "复制地址",
"copied": "已复制地址",
- "copy_failed": "无法复制地址"
+ "copy_failed": "无法复制地址",
+ "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}}"
}
}
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index b4829af3b3..d503e70811 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -1862,6 +1862,13 @@
"open": "開啟",
"copy_url": "複製位址",
"copied": "已複製位址",
- "copy_failed": "無法複製位址"
+ "copy_failed": "無法複製位址",
+ "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}}"
}
}
diff --git a/packages/views/platform/environment-focus.ts b/packages/views/platform/environment-focus.ts
new file mode 100644
index 0000000000..af8c14d25f
--- /dev/null
+++ b/packages/views/platform/environment-focus.ts
@@ -0,0 +1,37 @@
+// Bringing a desktop app environment's window forward, through Desktop's
+// main process and the local daemon that detected the app. Web has no bridge.
+
+export type FocusEnvironmentResult =
+ | { ok: true }
+ | {
+ ok: false;
+ /** `gone`: the app exited. `unsupported`: the daemon cannot raise
+ * windows on its platform, or is too old to try. `unavailable`: no
+ * local daemon answered. */
+ reason: "gone" | "unsupported" | "unavailable" | "failed";
+ error?: string;
+ };
+
+interface DaemonFocusAPI {
+ focusEnvironment?: (key: string) => Promise<FocusEnvironmentResult>;
+}
+
+function readDaemonAPI(): DaemonFocusAPI | undefined {
+ if (typeof window === "undefined") return undefined;
+ return (window as unknown as { daemonAPI?: DaemonFocusAPI }).daemonAPI;
+}
+
+/** True in a Desktop build that can ask its daemon to raise a window. */
+export function canFocusLocalEnvironments(): boolean {
+ return typeof readDaemonAPI()?.focusEnvironment === "function";
+}
+
+export async function focusLocalEnvironment(key: string): Promise<FocusEnvironmentResult> {
+ const api = readDaemonAPI();
+ if (!api?.focusEnvironment) return { ok: false, reason: "unsupported" };
+ try {
+ return await api.focusEnvironment(key);
+ } catch (error) {
+ return { ok: false, reason: "failed", error: error instanceof Error ? error.message : String(error) };
+ }
+}
diff --git a/packages/views/platform/index.ts b/packages/views/platform/index.ts
index 1f7145f425..1ec740c495 100644
--- a/packages/views/platform/index.ts
+++ b/packages/views/platform/index.ts
@@ -27,6 +27,11 @@ export {
useLocalDaemonStatus,
type LocalDaemonStatus,
} from "./use-local-daemon-status";
+export {
+ canFocusLocalEnvironments,
+ focusLocalEnvironment,
+ type FocusEnvironmentResult,
+} from "./environment-focus";
export {
ScrollRestorationProvider,
useScrollRestorationAdapter,
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index fe4547f7f4..c576f5136b 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -681,6 +681,7 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas
type TaskEnvironmentReport struct {
Key string `json:"key"`
Source string `json:"source"`
+ Kind string `json:"kind,omitempty"`
Name string `json:"name"`
Label string `json:"label"`
URL string `json:"url"`
diff --git a/server/internal/daemon/environments.go b/server/internal/daemon/environments.go
index efbf081050..8bbdc724e7 100644
--- a/server/internal/daemon/environments.go
+++ b/server/internal/daemon/environments.go
@@ -5,7 +5,9 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"log/slog"
+ "mime"
"net/http"
"os"
"path/filepath"
@@ -145,6 +147,24 @@ func (s *environmentService) servesFrom(dir string) bool {
return false
}
+// focus brings forward the desktop app last detected under key.
+func (s *environmentService) focus(ctx context.Context, key string) error {
+ s.mu.Lock()
+ var target *localenv.Environment
+ for i := range s.detected {
+ if s.detected[i].Key == key && s.detected[i].Kind == localenv.KindApp {
+ env := s.detected[i]
+ target = &env
+ break
+ }
+ }
+ s.mu.Unlock()
+ if target == nil {
+ return localenv.ErrAppGone
+ }
+ return target.Focus(ctx)
+}
+
func (s *environmentService) nudge() {
if s == nil {
return
@@ -337,7 +357,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.State, env.URL, env.Label, env.Detail, expires}, "\x1f"))
+ parts = append(parts, strings.Join([]string{env.Key, env.Kind, env.State, env.URL, env.Label, env.Detail, expires}, "\x1f"))
}
sort.Strings(parts)
return strings.Join(parts, "\x1e")
@@ -347,7 +367,7 @@ func toEnvironmentReports(envs []localenv.Environment) []TaskEnvironmentReport {
out := make([]TaskEnvironmentReport, 0, len(envs))
for _, env := range envs {
out = append(out, TaskEnvironmentReport{
- Key: env.Key, Source: env.Source, Name: env.Name, Label: env.Label, URL: env.URL,
+ Key: env.Key, Source: env.Source, Kind: env.Kind, Name: env.Name, Label: env.Label, URL: env.URL,
Port: env.Port, State: env.State, Detail: env.Detail, StartedAt: env.StartedAt, ExpiresAt: env.ExpiresAt,
})
}
@@ -472,6 +492,60 @@ func (d *Daemon) environmentListHandler() http.HandlerFunc {
}
}
+type environmentFocusRequest struct {
+ Key string `json:"key"`
+}
+
+// environmentFocusHandler brings a detected desktop app's window forward.
+// Desktop calls it on behalf of whoever sits at this machine, so unlike its
+// siblings there is no task credential to check. A request can only raise a
+// window this daemon already found in a task directory. Browsers cannot send
+// it: a page's POST always carries an Origin header, and a JSON body needs a
+// CORS preflight this server never answers.
+func (d *Daemon) environmentFocusHandler() http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ mediaType, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if r.Header.Get("Origin") != "" || mediaType != "application/json" {
+ writeEnvironmentFocusError(w, http.StatusForbidden, "forbidden", "focus requests come from Desktop, as JSON, without an Origin")
+ return
+ }
+ if d.environments == nil {
+ writeEnvironmentFocusError(w, http.StatusServiceUnavailable, "unavailable", "environments are not available on this daemon")
+ return
+ }
+ var req environmentFocusRequest
+ if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil {
+ writeEnvironmentFocusError(w, http.StatusBadRequest, "invalid", "invalid request body: "+err.Error())
+ return
+ }
+ err := d.environments.focus(r.Context(), strings.TrimSpace(req.Key))
+ switch {
+ case err == nil:
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]bool{"focused": true})
+ case errors.Is(err, localenv.ErrAppGone):
+ writeEnvironmentFocusError(w, http.StatusNotFound, "gone", err.Error())
+ case errors.Is(err, localenv.ErrFocusUnsupported):
+ writeEnvironmentFocusError(w, http.StatusNotImplemented, "unsupported", err.Error())
+ default:
+ d.logger.Warn("environments: focus failed", "error", err)
+ writeEnvironmentFocusError(w, http.StatusInternalServerError, "failed", err.Error())
+ }
+ }
+}
+
+// The reason lets Desktop tell the user what happened; a daemon too old for
+// this endpoint answers the mux's plain-text 404 instead.
+func writeEnvironmentFocusError(w http.ResponseWriter, status int, reason, message string) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ json.NewEncoder(w).Encode(map[string]string{"reason": reason, "error": message})
+}
+
func writeEnvironmentResponse(w http.ResponseWriter, resp environmentResponse) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
diff --git a/server/internal/daemon/environments_test.go b/server/internal/daemon/environments_test.go
index 3ee2843fbc..6170aa4b7a 100644
--- a/server/internal/daemon/environments_test.go
+++ b/server/internal/daemon/environments_test.go
@@ -197,6 +197,47 @@ func doEnvironmentRequest(handler http.HandlerFunc, path, token, body string) *h
return rec
}
+func TestEnvironmentFocusRefusesBrowsersAndUnknownApps(t *testing.T) {
+ s, _ := newTestEnvironmentService(t)
+ s.detected = []localenv.Environment{detectedEnv("task-a", "detected:server")}
+ d := &Daemon{logger: s.logger, environments: s}
+ focus := func(body string, header map[string]string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, "/environments/focus", strings.NewReader(body))
+ for k, v := range header {
+ req.Header.Set(k, v)
+ }
+ rec := httptest.NewRecorder()
+ d.environmentFocusHandler()(rec, req)
+ return rec
+ }
+ jsonBody := map[string]string{"Content-Type": "application/json"}
+
+ if rec := focus(`{"key":"detected:server"}`, map[string]string{"Content-Type": "application/json", "Origin": "https://evil.example"}); rec.Code != http.StatusForbidden {
+ t.Fatalf("a request from a web page = %d, want 403", rec.Code)
+ }
+ if rec := focus(`{"key":"detected:server"}`, map[string]string{"Content-Type": "text/plain"}); rec.Code != http.StatusForbidden {
+ t.Fatalf("a request a browser could send without a preflight = %d, want 403", rec.Code)
+ }
+ for _, key := range []string{"detected:server", "detected:gone"} {
+ rec := focus(`{"key":"`+key+`"}`, jsonBody)
+ if rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), `"reason":"gone"`) {
+ t.Fatalf("focus %s = %d %s, want 404 gone: only a detected app can be brought forward", key, rec.Code, rec.Body)
+ }
+ }
+}
+
+func TestEnvironmentReportCarriesTheKind(t *testing.T) {
+ s, reporter := newTestEnvironmentService(t)
+ app := detectedEnv("task-a", "detected:app")
+ app.Kind, app.URL, app.Port = localenv.KindApp, "", 0
+ s.detected = []localenv.Environment{app}
+ s.report(context.Background(), time.Now())
+ calls := reporter.take()
+ if len(calls) != 1 || calls[0].envs[0].Kind != localenv.KindApp || calls[0].envs[0].URL != "" {
+ t.Fatalf("reported = %+v, want the app kind without a URL", calls)
+ }
+}
+
func TestEnvironmentHandlersRequireATaskCredential(t *testing.T) {
s, _ := newTestEnvironmentService(t)
d := &Daemon{logger: s.logger, environments: s}
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.go
index 2cb7d7df86..9122beb275 100644
--- a/server/internal/daemon/health.go
+++ b/server/internal/daemon/health.go
@@ -417,6 +417,7 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt tim
mux.HandleFunc("/environments/start", d.environmentStartHandler())
mux.HandleFunc("/environments/stop", d.environmentStopHandler())
mux.HandleFunc("/environments/list", d.environmentListHandler())
+ mux.HandleFunc("/environments/focus", d.environmentFocusHandler())
srv := &http.Server{Handler: mux}
diff --git a/server/internal/daemon/localenv/app.go b/server/internal/daemon/localenv/app.go
new file mode 100644
index 0000000000..aeb575b408
--- /dev/null
+++ b/server/internal/daemon/localenv/app.go
@@ -0,0 +1,88 @@
+package localenv
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "regexp"
+ "strconv"
+ "time"
+)
+
+const (
+ // KindServer is reached at its URL; KindApp is a desktop app, whose window
+ // only the machine running it can bring forward.
+ KindServer = "server"
+ KindApp = "app"
+)
+
+// ErrAppGone means the app an environment names is no longer running.
+var ErrAppGone = errors.New("the app is no longer running")
+
+// ErrFocusUnsupported is returned where the daemon cannot bring a window
+// forward.
+var ErrFocusUnsupported = errors.New("bringing an app forward is not supported on this platform yet")
+
+// Process is what detection learns about a listening process.
+type Process struct {
+ Args string
+ // App names the desktop app the process is and Bundle is where that app
+ // lives; both are empty for a process without windows of its own.
+ App string
+ Bundle string
+ // Unsettled marks a process that may yet turn out to be an app: its
+ // executable lives in an app bundle, but it has not shown itself as an
+ // app so far, as one that is still starting has not.
+ Unsettled bool
+}
+
+var remoteDebuggingPort = regexp.MustCompile(`--remote-debugging-port[= ]+(\d+)`)
+
+// debugs reports whether the process was told to serve the Chrome DevTools
+// Protocol on port: a debugger endpoint, not something to open.
+func (p Process) debugs(port int) bool {
+ for _, m := range remoteDebuggingPort.FindAllStringSubmatch(p.Args, -1) {
+ if n, err := strconv.Atoi(m[1]); err == nil && n == port {
+ return true
+ }
+ }
+ return false
+}
+
+// probeCDP reports whether port answers as a DevTools endpoint, for an app
+// that turned debugging on from its own code rather than its arguments.
+func probeCDP(ctx context.Context, port int) bool {
+ ctx, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/json/version", port), nil)
+ if err != nil {
+ return false
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return false
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return false
+ }
+ var version struct {
+ Protocol string `json:"Protocol-Version"`
+ WebSocket string `json:"webSocketDebuggerUrl"`
+ }
+ if json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&version) != nil {
+ return false
+ }
+ return version.Protocol != "" && version.WebSocket != ""
+}
+
+// Focus brings the desktop app the environment names to the front.
+func (e Environment) Focus(ctx context.Context) error {
+ if e.Kind != KindApp || e.pid <= 0 {
+ return ErrAppGone
+ }
+ return focusApp(ctx, e.pid, e.bundle)
+}
diff --git a/server/internal/daemon/localenv/app_darwin.go b/server/internal/daemon/localenv/app_darwin.go
new file mode 100644
index 0000000000..dd4d904155
--- /dev/null
+++ b/server/internal/daemon/localenv/app_darwin.go
@@ -0,0 +1,148 @@
+//go:build darwin
+
+package localenv
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os/exec"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// runningAppsScript reports, for each pid argument, the app it is when its
+// activation policy is regular: it has a Dock icon and windows of its own.
+// AppKit through the JXA bridge needs neither Accessibility nor Automation
+// permission.
+const runningAppsScript = `ObjC.import("AppKit");
+function run(argv) {
+ const out = {};
+ for (const arg of argv) {
+ const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(arg));
+ if (app.isNil() || app.activationPolicy !== $.NSApplicationActivationPolicyRegular) continue;
+ out[arg] = {
+ name: app.localizedName.isNil() ? "" : app.localizedName.js,
+ bundle: app.bundleURL.isNil() ? "" : app.bundleURL.path.js,
+ };
+ }
+ return JSON.stringify(out);
+}`
+
+// focusScript prepares the app with pid argv[0] to come forward, provided it
+// still is the app at bundle argv[1]: a pid reused since detection is someone
+// else's window.
+//
+// Since macOS 14 an activation request from a background process (the daemon)
+// is accepted and then ignored, and activation never restores minimized
+// windows. LaunchServices opening the bundle does both, the same as a Dock
+// click, but it names an app by bundle, so the script answers "open" only when
+// this process is the one running instance of its bundle. Otherwise it asks
+// AppKit by pid and answers "requested"; whether that took is only visible
+// from another process.
+const focusScript = `ObjC.import("AppKit");
+function run(argv) {
+ const pid = Number(argv[0]);
+ const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(pid);
+ if (app.isNil() || app.activationPolicy !== $.NSApplicationActivationPolicyRegular) return "gone";
+ const bundle = app.bundleURL.isNil() ? "" : app.bundleURL.path.js;
+ if (bundle !== argv[1]) return "gone";
+ app.unhide;
+ const twins = bundle === "" ? 0 : ObjC.unwrap($.NSWorkspace.sharedWorkspace.runningApplications)
+ .filter((other) => !other.bundleURL.isNil() && other.bundleURL.path.js === bundle).length;
+ if (twins === 1) return "open";
+ app.activateWithOptions($.NSApplicationActivateAllWindows);
+ return "requested";
+}`
+
+const frontmostScript = `ObjC.import("AppKit");
+$.NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier`
+
+func inspectProcesses(ctx context.Context, pids []int) map[int]Process {
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ list := make([]string, len(pids))
+ for i, pid := range pids {
+ list[i] = strconv.Itoa(pid)
+ }
+ out, err := matchOutput(exec.CommandContext(ctx, "ps", "-ww", "-o", "pid=,args=", "-p", strings.Join(list, ",")))
+ if err != nil {
+ return nil
+ }
+ procs := parsePsArgs(out)
+ var candidates []string
+ for pid, p := range procs {
+ // Only an executable inside an app bundle can be an app; asking AppKit
+ // about anything else would start osascript for nothing.
+ if strings.Contains(p.Args, ".app/Contents/MacOS/") {
+ candidates = append(candidates, strconv.Itoa(pid))
+ }
+ }
+ if len(candidates) == 0 {
+ return procs
+ }
+ // Until AppKit names a candidate as an app the answer is not final: it
+ // may still be starting, or osascript may have failed this once.
+ for _, c := range candidates {
+ pid, _ := strconv.Atoi(c)
+ p := procs[pid]
+ p.Unsettled = true
+ procs[pid] = p
+ }
+ raw, err := exec.CommandContext(ctx, "osascript", append([]string{"-l", "JavaScript", "-e", runningAppsScript}, candidates...)...).Output()
+ if err != nil {
+ return procs
+ }
+ var apps map[string]struct {
+ Name string `json:"name"`
+ Bundle string `json:"bundle"`
+ }
+ if json.Unmarshal(raw, &apps) != nil {
+ return procs
+ }
+ for key, app := range apps {
+ pid, _ := strconv.Atoi(key)
+ if p, ok := procs[pid]; ok && app.Name != "" {
+ p.App, p.Bundle, p.Unsettled = app.Name, app.Bundle, false
+ procs[pid] = p
+ }
+ }
+ return procs
+}
+
+func focusApp(ctx context.Context, pid int, bundle string) error {
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "osascript", "-l", "JavaScript", "-e", focusScript, strconv.Itoa(pid), bundle).Output()
+ if err != nil {
+ return fmt.Errorf("bring the app forward: %w", err)
+ }
+ switch strings.TrimSpace(string(out)) {
+ case "gone":
+ return ErrAppGone
+ case "open":
+ if err := exec.CommandContext(ctx, "/usr/bin/open", bundle).Run(); err != nil {
+ return fmt.Errorf("open the app's bundle: %w", err)
+ }
+ case "requested":
+ default:
+ return fmt.Errorf("bring the app forward: unexpected answer %q", out)
+ }
+ // macOS keeps the user's current app in front while they are using it, and
+ // says so to nobody; only the frontmost app, read afresh, tells.
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(400 * time.Millisecond):
+ }
+ front, err := exec.CommandContext(ctx, "osascript", "-l", "JavaScript", "-e", frontmostScript).Output()
+ if err != nil {
+ return fmt.Errorf("check the frontmost app: %w", err)
+ }
+ if strings.TrimSpace(string(front)) != strconv.Itoa(pid) {
+ return errors.New("macOS kept another app in front")
+ }
+ return nil
+}
diff --git a/server/internal/daemon/localenv/app_linux.go b/server/internal/daemon/localenv/app_linux.go
new file mode 100644
index 0000000000..0367f0c2b5
--- /dev/null
+++ b/server/internal/daemon/localenv/app_linux.go
@@ -0,0 +1,27 @@
+//go:build linux
+
+package localenv
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// inspectProcesses reads each process's arguments. Linux has no notion of an
+// app with a window of its own to ask about, so none is reported as one.
+func inspectProcesses(_ context.Context, pids []int) map[int]Process {
+ procs := make(map[int]Process, len(pids))
+ for _, pid := range pids {
+ cmdline, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "cmdline"))
+ if err != nil {
+ continue
+ }
+ procs[pid] = Process{Args: strings.TrimSpace(strings.ReplaceAll(string(cmdline), "\x00", " "))}
+ }
+ return procs
+}
+
+func focusApp(context.Context, int, string) error { return ErrFocusUnsupported }
diff --git a/server/internal/daemon/localenv/detect.go b/server/internal/daemon/localenv/detect.go
index 1de3ed82dc..3ca3e07472 100644
--- a/server/internal/daemon/localenv/detect.go
+++ b/server/internal/daemon/localenv/detect.go
@@ -6,6 +6,7 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
+ "sort"
"strconv"
"strings"
"sync"
@@ -26,12 +27,40 @@ type Listener struct {
type Detector struct {
// ignore holds command names that are never an environment: the agent
// CLIs themselves and the multica binary.
- ignore map[string]bool
- list func(ctx context.Context) ([]Listener, error)
- now func() time.Time
+ ignore map[string]bool
+ list func(ctx context.Context) ([]Listener, error)
+ inspect func(ctx context.Context, pids []int) map[int]Process
+ isCDP func(ctx context.Context, port int) bool
+ now func() time.Time
mu sync.Mutex
seen map[string]*sighting
+ // procs and cdp remember what a process is and which of its ports speak
+ // DevTools, so a settled answer is looked up once rather than every scan.
+ // An answer that can still change -- a process not yet showing as an app,
+ // a port not yet answering as DevTools -- is asked again, per the recheck
+ // kept for it.
+ procs map[int]Process
+ cdp map[[2]int]bool
+ procChecks map[int]*recheck
+ probeChecks map[[2]int]*recheck
+}
+
+// recheck paces repeated lookups of an answer that may still change: every
+// scan for the first few, when a starting app settles, then every tenth, so a
+// process that never becomes an app costs next to nothing.
+type recheck struct{ tries, wait int }
+
+func (r *recheck) due() bool {
+ if r.wait > 0 {
+ r.wait--
+ return false
+ }
+ r.tries++
+ if r.tries > 5 {
+ r.wait = 9
+ }
+ return true
}
type sighting struct {
@@ -46,20 +75,31 @@ func NewDetector(ignoreCommands []string) *Detector {
ignore[c] = true
}
}
- return &Detector{ignore: ignore, list: listListeners, now: time.Now, seen: make(map[string]*sighting)}
+ return &Detector{
+ ignore: ignore, list: listListeners, inspect: inspectProcesses, isCDP: probeCDP, now: time.Now,
+ seen: make(map[string]*sighting), procs: make(map[int]Process), cdp: make(map[[2]int]bool),
+ procChecks: make(map[int]*recheck), probeChecks: make(map[[2]int]*recheck),
+ }
}
// Detect lists the servers whose working directory belongs to a task.
// resolve maps a working directory to its task; owned reports process groups
// the manager already supervises. A server is reported from its second
// sighting on, so test servers that live for a moment never show up.
+//
+// A desktop app is reported once, as an app with no URL, however many ports
+// it listens on. A DevTools port is never reported as a URL: opening it shows
+// a debugger page, not the app.
func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, bool), owned func(pgid int) bool) ([]Environment, error) {
listeners, err := d.list(ctx)
if err != nil {
return nil, err
}
- now := d.now()
- found := make(map[string]Environment)
+ type candidate struct {
+ Listener
+ task Task
+ }
+ var candidates []candidate
for _, l := range listeners {
if l.Cwd == "" || d.ignore[strings.ToLower(l.Command)] {
continue
@@ -71,19 +111,57 @@ func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, b
if pgid := processGroup(l.PID); pgid > 0 && owned(pgid) {
continue
}
- key := detectedKey(task.RootDir, l.Port)
- if _, dup := found[key]; dup {
+ candidates = append(candidates, candidate{l, task})
+ }
+ pids := make([]int, 0, len(candidates))
+ for _, c := range candidates {
+ pids = append(pids, c.PID)
+ }
+ procs := d.processes(ctx, pids)
+
+ now := d.now()
+ found := make(map[string]Environment)
+ debugPorts := make(map[string][]int)
+ for _, c := range candidates {
+ proc := procs[c.PID]
+ // A process that may yet be an app is probed like one, so its debug
+ // port is not offered as a link while it starts.
+ debug := proc.debugs(c.Port) || ((proc.App != "" || proc.Unsettled) && d.speaksCDP(ctx, c.PID, c.Port))
+ if proc.App != "" {
+ key := detectedAppKey(c.task.RootDir, proc)
+ if _, dup := found[key]; !dup {
+ found[key] = Environment{
+ Key: key, TaskID: c.task.TaskID, IssueID: c.task.IssueID, Source: SourceDetected, Kind: KindApp,
+ Name: truncateName(proc.App), State: StateRunning, Dir: c.task.RootDir,
+ pid: c.PID, bundle: proc.Bundle,
+ }
+ }
+ if debug {
+ debugPorts[key] = append(debugPorts[key], c.Port)
+ }
+ }
+ if debug {
continue
}
- name := l.Command
- if r := []rune(name); len(r) > 64 {
- name = string(r[:64])
+ key := detectedKey(c.task.RootDir, c.Port)
+ if _, dup := found[key]; dup {
+ continue
}
found[key] = Environment{
- Key: key, TaskID: task.TaskID, IssueID: task.IssueID, Source: SourceDetected,
- Name: name, URL: fmt.Sprintf("http://localhost:%d", l.Port), Port: l.Port, State: StateRunning,
- Dir: task.RootDir,
+ 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,
+ }
+ }
+ for key, ports := range debugPorts {
+ sort.Ints(ports)
+ hosts := make([]string, len(ports))
+ for i, port := range ports {
+ hosts[i] = fmt.Sprintf("localhost:%d", port)
}
+ env := found[key]
+ env.Detail = "Remote debugging on " + strings.Join(hosts, ", ")
+ found[key] = env
}
d.mu.Lock()
@@ -110,6 +188,101 @@ func (d *Detector) Detect(ctx context.Context, resolve func(cwd string) (Task, b
return out, nil
}
+// processes returns what each pid is, asking about pids not seen in an
+// earlier scan and those whose answer may still change, and forgets pids that
+// stopped listening.
+func (d *Detector) processes(ctx context.Context, pids []int) map[int]Process {
+ d.mu.Lock()
+ var ask []int
+ live := make(map[int]bool, len(pids))
+ for _, pid := range pids {
+ if live[pid] {
+ continue
+ }
+ live[pid] = true
+ known, ok := d.procs[pid]
+ if !ok {
+ ask = append(ask, pid)
+ } else if known.Unsettled {
+ check := d.procChecks[pid]
+ if check == nil {
+ check = &recheck{tries: 1}
+ d.procChecks[pid] = check
+ }
+ if check.due() {
+ ask = append(ask, pid)
+ }
+ }
+ }
+ d.mu.Unlock()
+ var learned map[int]Process
+ if len(ask) > 0 {
+ learned = d.inspect(ctx, ask)
+ }
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ for pid, p := range learned {
+ d.procs[pid] = p
+ if !p.Unsettled {
+ delete(d.procChecks, pid)
+ }
+ }
+ for pid := range d.procs {
+ if !live[pid] {
+ delete(d.procs, pid)
+ delete(d.procChecks, pid)
+ }
+ }
+ for k := range d.cdp {
+ if !live[k[0]] {
+ delete(d.cdp, k)
+ }
+ }
+ for k := range d.probeChecks {
+ if !live[k[0]] {
+ delete(d.probeChecks, k)
+ }
+ }
+ out := make(map[int]Process, len(pids))
+ for _, pid := range pids {
+ out[pid] = d.procs[pid]
+ }
+ return out
+}
+
+// speaksCDP remembers a port that answered as DevTools. One that did not may
+// simply not be serving yet, so it is probed again rather than written off.
+func (d *Detector) speaksCDP(ctx context.Context, pid, port int) bool {
+ k := [2]int{pid, port}
+ d.mu.Lock()
+ if d.cdp[k] {
+ d.mu.Unlock()
+ return true
+ }
+ check := d.probeChecks[k]
+ if check == nil {
+ check = &recheck{}
+ d.probeChecks[k] = check
+ }
+ due := check.due()
+ d.mu.Unlock()
+ if !due || !d.isCDP(ctx, port) {
+ return false
+ }
+ d.mu.Lock()
+ d.cdp[k] = true
+ delete(d.probeChecks, k)
+ d.mu.Unlock()
+ return true
+}
+
+func truncateName(name string) string {
+ if r := []rune(name); len(r) > 64 {
+ return string(r[:64])
+ }
+ return name
+}
+
// detectedKey is stable across restarts of the same server, and carries no
// local path to the server.
func detectedKey(root string, port int) string {
@@ -117,6 +290,33 @@ func detectedKey(root string, port int) string {
return "detected:" + hex.EncodeToString(sum[:8])
}
+// detectedAppKey is stable across restarts of the same app, whatever ports
+// it listens on this time.
+func detectedAppKey(root string, p Process) string {
+ id := p.Bundle
+ if id == "" {
+ id = p.App
+ }
+ sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00app\x00%s", root, id)))
+ return "detected:" + hex.EncodeToString(sum[:8])
+}
+
+// parsePsArgs reads `ps -o pid=,args=` output into pid → process.
+func parsePsArgs(out string) map[int]Process {
+ procs := make(map[int]Process)
+ scanner := bufio.NewScanner(strings.NewReader(out))
+ scanner.Buffer(make([]byte, 64*1024), 1024*1024)
+ for scanner.Scan() {
+ pidField, args, _ := strings.Cut(strings.TrimSpace(scanner.Text()), " ")
+ pid, err := strconv.Atoi(pidField)
+ if err != nil || pid <= 0 {
+ continue
+ }
+ procs[pid] = Process{Args: strings.TrimSpace(args)}
+ }
+ return procs
+}
+
// parseLsofListeners reads `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` output.
func parseLsofListeners(out string) []Listener {
var listeners []Listener
diff --git a/server/internal/daemon/localenv/detect_darwin.go b/server/internal/daemon/localenv/detect_darwin.go
index b7a50d48df..139b68e8b6 100644
--- a/server/internal/daemon/localenv/detect_darwin.go
+++ b/server/internal/daemon/localenv/detect_darwin.go
@@ -43,9 +43,14 @@ func listListeners(ctx context.Context) ([]Listener, error) {
return listeners, nil
}
-// lsof exits 1 when it matches nothing, which is not an error here.
func lsof(ctx context.Context, args ...string) (string, error) {
- out, err := exec.CommandContext(ctx, "lsof", args...).Output()
+ return matchOutput(exec.CommandContext(ctx, "lsof", args...))
+}
+
+// matchOutput runs cmd for its output. lsof and ps exit 1 when they match
+// nothing, which is not an error here.
+func matchOutput(cmd *exec.Cmd) (string, error) {
+ out, err := cmd.Output()
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
return string(out), nil
diff --git a/server/internal/daemon/localenv/detect_other.go b/server/internal/daemon/localenv/detect_other.go
index b241d92c0d..6011e0e5a6 100644
--- a/server/internal/daemon/localenv/detect_other.go
+++ b/server/internal/daemon/localenv/detect_other.go
@@ -5,3 +5,7 @@ package localenv
import "context"
func listListeners(context.Context) ([]Listener, error) { return nil, nil }
+
+func inspectProcesses(context.Context, []int) map[int]Process { return nil }
+
+func focusApp(context.Context, int, string) error { return ErrFocusUnsupported }
diff --git a/server/internal/daemon/localenv/detect_system_test.go b/server/internal/daemon/localenv/detect_system_test.go
index 9816feb78b..07876b8dd9 100644
--- a/server/internal/daemon/localenv/detect_system_test.go
+++ b/server/internal/daemon/localenv/detect_system_test.go
@@ -51,3 +51,21 @@ func TestListListenersFindsAServerAndItsDirectory(t *testing.T) {
}
t.Fatalf("server pid %d on port %d was never listed", cmd.Process.Pid, port)
}
+
+func TestInspectProcessesReadsArgumentsOfAProcessWithoutWindows(t *testing.T) {
+ // The trailing `:` keeps the shell from exec'ing sleep in its place.
+ cmd := exec.Command("/bin/sh", "-c", "sleep 30; :", "sh", "--remote-debugging-port=9333")
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
+
+ procs := inspectProcesses(context.Background(), []int{cmd.Process.Pid})
+ p, ok := procs[cmd.Process.Pid]
+ if !ok || !p.debugs(9333) {
+ t.Fatalf("inspected = %+v, want the arguments the process was started with", procs)
+ }
+ if p.App != "" || p.Bundle != "" {
+ t.Fatalf("a test binary was reported as the app %q at %q", p.App, p.Bundle)
+ }
+}
diff --git a/server/internal/daemon/localenv/detect_test.go b/server/internal/daemon/localenv/detect_test.go
index a57827659b..00b874b15d 100644
--- a/server/internal/daemon/localenv/detect_test.go
+++ b/server/internal/daemon/localenv/detect_test.go
@@ -2,6 +2,10 @@ package localenv
import (
"context"
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
"strings"
"testing"
)
@@ -40,26 +44,19 @@ func TestDetectorReportsServersInTaskDirectories(t *testing.T) {
{PID: 2, Port: 9000, Command: "claude", Cwd: "/ws/task-a/workdir"},
{PID: 3, Port: 3000, Command: "node", Cwd: "/Users/me/own-project"},
}
- d := NewDetector([]string{"Claude"})
- d.list = func(context.Context) ([]Listener, error) { return listeners, nil }
- resolve := func(cwd string) (Task, bool) {
- if strings.HasPrefix(cwd, "/ws/task-a/") {
- return Task{TaskID: "task-a", IssueID: "issue-a", RootDir: "/ws/task-a"}, true
- }
- return Task{}, false
- }
- owned := func(int) bool { return false }
+ d := fakeDetector(&listeners, nil, nil)
+ d.ignore = NewDetector([]string{"Claude"}).ignore
- first, err := d.Detect(context.Background(), resolve, owned)
+ first, err := d.Detect(context.Background(), resolveTaskA, notOwned)
if err != nil || len(first) != 0 {
t.Fatalf("first scan = %+v, %v; want nothing until a server is seen twice", first, err)
}
- second, _ := d.Detect(context.Background(), resolve, owned)
+ second, _ := d.Detect(context.Background(), resolveTaskA, notOwned)
if len(second) != 1 {
t.Fatalf("second scan = %+v, want the one server in the task directory", second)
}
env := second[0]
- if env.Source != SourceDetected || env.TaskID != "task-a" || env.URL != "http://localhost:5173" || env.Name != "node" || env.State != StateRunning {
+ if env.Source != SourceDetected || env.Kind != KindServer || env.TaskID != "task-a" || env.URL != "http://localhost:5173" || env.Name != "node" || env.State != StateRunning {
t.Fatalf("detected = %+v", env)
}
if strings.Contains(env.Key, "/ws/") || env.Key != detectedKey("/ws/task-a", 5173) {
@@ -67,7 +64,254 @@ func TestDetectorReportsServersInTaskDirectories(t *testing.T) {
}
listeners = nil
- if gone, _ := d.Detect(context.Background(), resolve, owned); len(gone) != 0 {
+ if gone, _ := d.Detect(context.Background(), resolveTaskA, notOwned); len(gone) != 0 {
t.Fatalf("after the server stopped = %+v", gone)
}
}
+
+const electronBundle = "/ws/task-a/workdir/node_modules/electron/dist/Electron.app"
+
+func TestDetectorReportsADesktopAppInsteadOfItsDebugPort(t *testing.T) {
+ listeners := []Listener{
+ {PID: 10, Port: 9724, Command: "Electron", Cwd: "/ws/task-a/workdir/apps/desktop"},
+ {PID: 11, Port: 5173, Command: "node", Cwd: "/ws/task-a/workdir/apps/desktop"},
+ }
+ procs := map[int]Process{
+ 10: {Args: electronBundle + "/Contents/MacOS/Electron . --remote-debugging-port=9724", App: "Multica Canary multica-501", Bundle: electronBundle},
+ 11: {Args: "node node_modules/.bin/electron-vite dev"},
+ }
+ probed := 0
+ d := fakeDetector(&listeners, procs, func(int) bool { probed++; return false })
+
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ envs, _ := d.Detect(context.Background(), resolveTaskA, notOwned)
+ if len(envs) != 2 {
+ t.Fatalf("detected = %+v, want the app and the Vite server", envs)
+ }
+ app, vite := byKind(envs, KindApp), byKind(envs, KindServer)
+ if app.Name != "Multica Canary multica-501" || app.URL != "" || app.Port != 0 || app.Detail != "Remote debugging on localhost:9724" {
+ t.Fatalf("app = %+v, want the app's own name, no URL and the debug port as detail", app)
+ }
+ if app.pid != 10 || app.bundle != electronBundle {
+ t.Fatalf("app pid/bundle = %d/%q, want the listening process", app.pid, app.bundle)
+ }
+ if strings.Contains(app.Key, "/ws/") || app.Key != detectedAppKey("/ws/task-a", procs[10]) {
+ t.Fatalf("app key %q leaks the path or is unstable", app.Key)
+ }
+ if vite.URL != "http://localhost:5173" || vite.Name != "node" {
+ t.Fatalf("an ordinary server next to the app = %+v, want it unchanged", vite)
+ }
+ if probed != 0 {
+ t.Fatalf("probed %d ports; a debug port named in the arguments needs no probe", probed)
+ }
+
+ // The same app restarted on another debug port is still the same row.
+ listeners[0] = Listener{PID: 20, Port: 9800, Command: "Electron", Cwd: "/ws/task-a/workdir/apps/desktop"}
+ procs[20] = Process{Args: electronBundle + "/Contents/MacOS/Electron . --remote-debugging-port 9800", App: "Multica Canary multica-501", Bundle: electronBundle}
+ envs, _ = d.Detect(context.Background(), resolveTaskA, notOwned)
+ if restarted := byKind(envs, KindApp); restarted.Key != app.Key || restarted.pid != 20 || restarted.Detail != "Remote debugging on localhost:9800" {
+ t.Fatalf("restarted app = %+v, want the same key with the new process", restarted)
+ }
+}
+
+func TestDetectorFindsADebugPortTheAppOpenedItself(t *testing.T) {
+ listeners := []Listener{
+ {PID: 10, Port: 9222, Command: "Electron", Cwd: "/ws/task-a/workdir"},
+ {PID: 10, Port: 3000, Command: "Electron", Cwd: "/ws/task-a/workdir"},
+ }
+ procs := map[int]Process{10: {Args: electronBundle + "/Contents/MacOS/Electron .", App: "My App", Bundle: electronBundle}}
+ probes := map[int]int{}
+ d := fakeDetector(&listeners, procs, func(port int) bool { probes[port]++; return port == 9222 })
+
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ envs, _ := d.Detect(context.Background(), resolveTaskA, notOwned)
+ if len(envs) != 2 {
+ t.Fatalf("detected = %+v, want the app and the server it runs", envs)
+ }
+ if app := byKind(envs, KindApp); app.Name != "My App" || app.Detail != "Remote debugging on localhost:9222" {
+ t.Fatalf("app = %+v", app)
+ }
+ if server := byKind(envs, KindServer); server.URL != "http://localhost:3000" {
+ t.Fatalf("the app's own HTTP server = %+v, want it still opened in a browser", server)
+ }
+ if probes[9222] != 1 {
+ t.Fatalf("probes = %v, want a port that answered as DevTools probed once across scans", probes)
+ }
+}
+
+func TestDetectorNoticesAnAppThatWasStillStarting(t *testing.T) {
+ listeners := []Listener{{PID: 10, Port: 9724, Command: "Electron", Cwd: "/ws/task-a/workdir"}}
+ args := electronBundle + "/Contents/MacOS/Electron . --remote-debugging-port=9724"
+ procs := map[int]Process{10: {Args: args, Unsettled: true}}
+ d := fakeDetector(&listeners, procs, nil)
+
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ if envs, _ := d.Detect(context.Background(), resolveTaskA, notOwned); len(envs) != 0 {
+ t.Fatalf("before the app shows itself = %+v, want its debug port left out", envs)
+ }
+ procs[10] = Process{Args: args, App: "My App", Bundle: electronBundle}
+ var envs []Environment
+ for i := 0; i < 2; i++ {
+ envs, _ = d.Detect(context.Background(), resolveTaskA, notOwned)
+ }
+ if len(envs) != 1 || envs[0].Kind != KindApp || envs[0].Name != "My App" || envs[0].pid != 10 {
+ t.Fatalf("after the app showed itself = %+v, want the app row", envs)
+ }
+ if len(d.procChecks) != 0 {
+ t.Fatalf("procChecks = %v, want a settled process no longer rechecked", d.procChecks)
+ }
+}
+
+func TestDetectorNoticesADebugPortThatWasNotServingYet(t *testing.T) {
+ listeners := []Listener{{PID: 10, Port: 9222, Command: "Electron", Cwd: "/ws/task-a/workdir"}}
+ procs := map[int]Process{10: {Args: electronBundle + "/Contents/MacOS/Electron .", App: "My App", Bundle: electronBundle}}
+ ready, probes := false, 0
+ d := fakeDetector(&listeners, procs, func(int) bool { probes++; return ready })
+
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ envs, _ := d.Detect(context.Background(), resolveTaskA, notOwned)
+ if server := byKind(envs, KindServer); server.URL != "http://localhost:9222" {
+ t.Fatalf("while the port does not answer as DevTools = %+v, want it shown as a server", envs)
+ }
+ ready = true
+ envs, _ = d.Detect(context.Background(), resolveTaskA, notOwned)
+ if len(envs) != 1 || envs[0].Kind != KindApp || envs[0].Detail != "Remote debugging on localhost:9222" {
+ t.Fatalf("once it answers as DevTools = %+v, want only the app with the port as detail", envs)
+ }
+ settled := probes
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ if probes != settled {
+ t.Fatalf("probed %d more times after the port was recognized", probes-settled)
+ }
+}
+
+func TestDetectorSpacesOutRechecksThatNeverSettle(t *testing.T) {
+ listeners := []Listener{{PID: 10, Port: 3000, Command: "Electron", Cwd: "/ws/task-a/workdir"}}
+ procs := map[int]Process{10: {Args: electronBundle + "/Contents/MacOS/Electron .", Unsettled: true}}
+ inspected, probes := 0, 0
+ d := fakeDetector(&listeners, procs, func(int) bool { probes++; return false })
+ inner := d.inspect
+ d.inspect = func(ctx context.Context, pids []int) map[int]Process { inspected++; return inner(ctx, pids) }
+
+ for i := 0; i < 45; i++ {
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ }
+ // Five scans in a row, then every tenth.
+ if inspected != 9 || probes != 9 {
+ t.Fatalf("inspected %d times and probed %d times over 45 scans, want 9 each", inspected, probes)
+ }
+ listeners = nil
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ if len(d.procChecks) != 0 || len(d.probeChecks) != 0 {
+ t.Fatal("rechecks outlived the process")
+ }
+}
+
+func TestDetectorDropsTheDebugPortOfAProcessWithoutWindows(t *testing.T) {
+ listeners := []Listener{{PID: 10, Port: 9333, Command: "chrome", Cwd: "/ws/task-a/workdir"}}
+ procs := map[int]Process{10: {Args: "/opt/chrome/chrome --headless --remote-debugging-port=9333"}}
+ d := fakeDetector(&listeners, procs, func(int) bool { t.Fatal("a process that is not an app is never probed"); return false })
+
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ if envs, _ := d.Detect(context.Background(), resolveTaskA, notOwned); len(envs) != 0 {
+ t.Fatalf("detected = %+v, want a bare debug port left out", envs)
+ }
+}
+
+func TestDetectorInspectsEachProcessOnce(t *testing.T) {
+ listeners := []Listener{{PID: 10, Port: 5173, Command: "node", Cwd: "/ws/task-a/workdir"}}
+ inspected := map[int]int{}
+ d := fakeDetector(&listeners, map[int]Process{10: {Args: "node vite"}, 11: {Args: "node vite"}}, nil)
+ inner := d.inspect
+ d.inspect = func(ctx context.Context, pids []int) map[int]Process {
+ for _, pid := range pids {
+ inspected[pid]++
+ }
+ return inner(ctx, pids)
+ }
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ listeners[0].PID = 11
+ d.Detect(context.Background(), resolveTaskA, notOwned)
+ if inspected[10] != 1 || inspected[11] != 1 {
+ t.Fatalf("inspected = %v, want each pid once", inspected)
+ }
+ if _, kept := d.procs[10]; kept {
+ t.Fatal("a pid that stopped listening is still remembered")
+ }
+}
+
+func TestParsePsArgs(t *testing.T) {
+ out := " 4210 /Users/me/My App.app/Contents/MacOS/My App . --remote-debugging-port=9724\n 99 node vite\nbogus\n"
+ got := parsePsArgs(out)
+ if len(got) != 2 || got[4210].Args != "/Users/me/My App.app/Contents/MacOS/My App . --remote-debugging-port=9724" || got[99].Args != "node vite" {
+ t.Fatalf("parsePsArgs = %+v", got)
+ }
+ if !got[4210].debugs(9724) || got[4210].debugs(972) || got[99].debugs(9724) {
+ t.Fatal("debugs matched the wrong ports")
+ }
+}
+
+func TestProbeCDP(t *testing.T) {
+ cdp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/json/version" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Write([]byte(`{"Browser":"Chrome/152","Protocol-Version":"1.3","webSocketDebuggerUrl":"ws://127.0.0.1/devtools/browser/x"}`))
+ }))
+ defer cdp.Close()
+ web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(`<html>app</html>`))
+ }))
+ defer web.Close()
+ if !probeCDP(context.Background(), cdp.Listener.Addr().(*net.TCPAddr).Port) {
+ t.Fatal("a DevTools endpoint was not recognized")
+ }
+ if probeCDP(context.Background(), web.Listener.Addr().(*net.TCPAddr).Port) {
+ t.Fatal("an ordinary web server was taken for a DevTools endpoint")
+ }
+}
+
+func TestFocusNeedsADetectedApp(t *testing.T) {
+ if err := (Environment{Kind: KindServer, pid: 10}).Focus(context.Background()); !errors.Is(err, ErrAppGone) {
+ t.Fatalf("focusing a server = %v, want ErrAppGone", err)
+ }
+ if err := (Environment{Kind: KindApp}).Focus(context.Background()); !errors.Is(err, ErrAppGone) {
+ t.Fatalf("focusing an app without a process = %v, want ErrAppGone", err)
+ }
+}
+
+func fakeDetector(listeners *[]Listener, procs map[int]Process, isCDP func(port int) bool) *Detector {
+ d := NewDetector(nil)
+ d.list = func(context.Context) ([]Listener, error) { return *listeners, nil }
+ d.inspect = func(_ context.Context, pids []int) map[int]Process {
+ out := make(map[int]Process)
+ for _, pid := range pids {
+ if p, ok := procs[pid]; ok {
+ out[pid] = p
+ }
+ }
+ return out
+ }
+ d.isCDP = func(_ context.Context, port int) bool { return isCDP != nil && isCDP(port) }
+ return d
+}
+
+func resolveTaskA(cwd string) (Task, bool) {
+ if strings.HasPrefix(cwd, "/ws/task-a/") {
+ return Task{TaskID: "task-a", IssueID: "issue-a", RootDir: "/ws/task-a"}, true
+ }
+ return Task{}, false
+}
+
+func notOwned(int) bool { return false }
+
+func byKind(envs []Environment, kind string) Environment {
+ for _, env := range envs {
+ if env.Kind == kind {
+ return env
+ }
+ }
+ return Environment{}
+}
diff --git a/server/internal/daemon/localenv/manager.go b/server/internal/daemon/localenv/manager.go
index 5e216fd38e..0161da8bc1 100644
--- a/server/internal/daemon/localenv/manager.go
+++ b/server/internal/daemon/localenv/manager.go
@@ -69,6 +69,7 @@ type Environment struct {
TaskID string `json:"task_id"`
IssueID string `json:"issue_id"`
Source string `json:"source"`
+ Kind string `json:"kind,omitempty"`
Name string `json:"name"`
Label string `json:"label"`
URL string `json:"url"`
@@ -82,6 +83,10 @@ type Environment struct {
// 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 int
+ bundle string
}
// record is what survives a daemon restart, in <dir>/<id>/state.json.
@@ -529,7 +534,7 @@ func (m *Manager) viewLocked(e *entry) Environment {
rec := e.rec
view := Environment{
Key: "config:" + rec.ID, TaskID: rec.TaskID, IssueID: rec.IssueID,
- Source: SourceConfig, Name: rec.Name, Label: rec.Label, URL: rec.URL, Port: rec.Port,
+ 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,
LogPath: filepath.Join(m.dir, rec.ID, outputFile), Dir: rec.RepoRoot, pgid: rec.PID,
}
diff --git a/server/internal/handler/issue_environment.go b/server/internal/handler/issue_environment.go
index e463e66317..a7f4ae3ec6 100644
--- a/server/internal/handler/issue_environment.go
+++ b/server/internal/handler/issue_environment.go
@@ -29,10 +29,18 @@ var issueEnvironmentSources = map[string]bool{"config": true, "detected": true}
var issueEnvironmentStates = map[string]bool{"starting": true, "running": true, "exited": true, "stopped": true}
+// A server is reached at its URL; an app is a desktop window that only the
+// machine running it can bring forward.
+const (
+ issueEnvironmentKindServer = "server"
+ issueEnvironmentKindApp = "app"
+)
+
// 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"`
Name string `json:"name"`
Label string `json:"label"`
URL string `json:"url"`
@@ -53,7 +61,11 @@ type IssueEnvironmentResponse struct {
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"`
@@ -77,6 +89,11 @@ 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)
+ // 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 {
+ env.Kind = issueEnvironmentKindServer
+ }
switch {
case env.Key == "" || len(env.Key) > 128:
return "key must be 1-128 characters"
@@ -177,6 +194,7 @@ func (h *Handler) ReportTaskEnvironments(w http.ResponseWriter, r *http.Request)
AgentID: task.AgentID,
LocalKey: env.Key,
Source: env.Source,
+ Kind: env.Kind,
Name: env.Name,
Label: env.Label,
Url: env.URL,
@@ -196,7 +214,7 @@ func (h *Handler) ReportTaskEnvironments(w http.ResponseWriter, r *http.Request)
return
}
prev, wasOpen := open[env.Key]
- if !wasOpen || prev.State != env.State || prev.Url != env.URL || prev.Label != env.Label || prev.Detail != env.Detail {
+ if !wasOpen || prev.State != env.State || prev.Kind != env.Kind || prev.Url != env.URL || prev.Label != env.Label || prev.Detail != env.Detail {
changed = true
}
}
@@ -262,7 +280,9 @@ func issueEnvironmentToResponse(row db.IssueEnvironment, now time.Time) IssueEnv
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,
diff --git a/server/internal/handler/issue_environment_test.go b/server/internal/handler/issue_environment_test.go
index c9e50f583d..12e50f81a9 100644
--- a/server/internal/handler/issue_environment_test.go
+++ b/server/internal/handler/issue_environment_test.go
@@ -82,6 +82,23 @@ func TestReportTaskEnvironments_SnapshotLifecycle(t *testing.T) {
}
}
+func TestReportTaskEnvironments_Kinds(t *testing.T) {
+ issueID, taskID := issueEnvironmentFixture(t)
+ app := map[string]any{"key": "detected:app", "source": "detected", "kind": "app", "name": "Multica Canary", "state": "running", "detail": "DevTools on localhost:9724"}
+ future := map[string]any{"key": "detected:new", "source": "detected", "kind": "tunnel", "name": "future", "url": "http://localhost:4000", "port": 4000, "state": "running"}
+
+ reportEnvironments(t, taskID, webEnvironment("running"), app, future).Want(http.StatusOK)
+ envs := listEnvironments(t, issueID)
+ if got := envs["Multica Canary"]; got.Kind != "app" || got.LocalKey != "detected:app" || got.URL != "" || got.Port != nil {
+ t.Fatalf("app environment = %+v", got)
+ }
+ // A daemon older than kinds sends none; one newer may send a kind this
+ // server does not know. Both read back as a server.
+ if envs["web"].Kind != "server" || envs["future"].Kind != "server" {
+ t.Fatalf("kinds = web %q, future %q; want server for both", envs["web"].Kind, envs["future"].Kind)
+ }
+}
+
func TestReportTaskEnvironments_RestartReopensRow(t *testing.T) {
issueID, taskID := issueEnvironmentFixture(t)
reportEnvironments(t, taskID, webEnvironment("running")).Want(http.StatusOK)
diff --git a/server/migrations/637_issue_environment_kind.down.sql b/server/migrations/637_issue_environment_kind.down.sql
new file mode 100644
index 0000000000..362de58694
--- /dev/null
+++ b/server/migrations/637_issue_environment_kind.down.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_environment DROP COLUMN IF EXISTS kind;
diff --git a/server/migrations/637_issue_environment_kind.up.sql b/server/migrations/637_issue_environment_kind.up.sql
new file mode 100644
index 0000000000..f396ee3295
--- /dev/null
+++ b/server/migrations/637_issue_environment_kind.up.sql
@@ -0,0 +1,4 @@
+-- What an environment is: a server reached at its URL, or a desktop app whose
+-- window only the machine running it can bring forward. A constant default
+-- adds the column without rewriting the table.
+ALTER TABLE issue_environment ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'server';
diff --git a/server/pkg/db/generated/issue_environment.sql.go b/server/pkg/db/generated/issue_environment.sql.go
index 70f5210158..3adb552825 100644
--- a/server/pkg/db/generated/issue_environment.sql.go
+++ b/server/pkg/db/generated/issue_environment.sql.go
@@ -34,7 +34,7 @@ func (q *Queries) EndIssueEnvironmentsMissingFromSnapshot(ctx context.Context, a
}
const listIssueEnvironments = `-- name: ListIssueEnvironments :many
-SELECT id, workspace_id, issue_id, task_id, runtime_id, agent_id, local_key, source, name, label, url, port, state, detail, started_at, expires_at, last_seen_at, ended_at, created_at, updated_at FROM issue_environment
+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
WHERE issue_id = $1
AND workspace_id = $2
AND (ended_at IS NULL OR ended_at > $3::timestamptz)
@@ -79,6 +79,7 @@ func (q *Queries) ListIssueEnvironments(ctx context.Context, arg ListIssueEnviro
&i.EndedAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Kind,
); err != nil {
return nil, err
}
@@ -91,7 +92,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 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 FROM issue_environment
WHERE task_id = $1 AND ended_at IS NULL
`
@@ -125,6 +126,7 @@ func (q *Queries) ListOpenIssueEnvironmentsByTask(ctx context.Context, taskID pg
&i.EndedAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Kind,
); err != nil {
return nil, err
}
@@ -139,14 +141,15 @@ 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,
- name, label, url, port, state, detail, started_at, expires_at, ended_at
+ kind, name, label, url, port, state, detail, started_at, expires_at, ended_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7,
- $8, $9, $10, $11, $12, $13, $14, $15,
- CASE WHEN $12::text IN ('exited', 'stopped') THEN now() END
+ $8, $9, $10, $11, $12, $13, $14, $15, $16,
+ CASE WHEN $13::text IN ('exited', 'stopped') THEN now() END
)
ON CONFLICT (task_id, local_key) DO UPDATE SET
source = EXCLUDED.source,
+ kind = EXCLUDED.kind,
name = EXCLUDED.name,
label = EXCLUDED.label,
url = EXCLUDED.url,
@@ -160,7 +163,7 @@ 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
+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
`
type UpsertIssueEnvironmentParams struct {
@@ -171,6 +174,7 @@ type UpsertIssueEnvironmentParams struct {
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"`
@@ -192,6 +196,7 @@ func (q *Queries) UpsertIssueEnvironment(ctx context.Context, arg UpsertIssueEnv
arg.AgentID,
arg.LocalKey,
arg.Source,
+ arg.Kind,
arg.Name,
arg.Label,
arg.Url,
@@ -223,6 +228,7 @@ func (q *Queries) UpsertIssueEnvironment(ctx context.Context, arg UpsertIssueEnv
&i.EndedAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Kind,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 8699b49de5..9612f8efc3 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -989,6 +989,7 @@ type IssueEnvironment struct {
EndedAt pgtype.Timestamptz `json:"ended_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Kind string `json:"kind"`
}
type IssueLabel struct {
diff --git a/server/pkg/db/queries/issue_environment.sql b/server/pkg/db/queries/issue_environment.sql
index 278528c937..37942ea1dc 100644
--- a/server/pkg/db/queries/issue_environment.sql
+++ b/server/pkg/db/queries/issue_environment.sql
@@ -7,14 +7,15 @@ 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,
- name, label, url, port, state, detail, started_at, expires_at, ended_at
+ kind, name, label, url, port, state, detail, started_at, expires_at, ended_at
) VALUES (
@workspace_id, @issue_id, @task_id, @runtime_id, @agent_id, @local_key, @source,
- @name, @label, @url, @port, @state, @detail, @started_at, @expires_at,
+ @kind, @name, @label, @url, @port, @state, @detail, @started_at, @expires_at,
CASE WHEN @state::text IN ('exited', 'stopped') THEN now() END
)
ON CONFLICT (task_id, local_key) DO UPDATE SET
source = EXCLUDED.source,
+ kind = EXCLUDED.kind,
name = EXCLUDED.name,
label = EXCLUDED.label,
url = EXCLUDED.url,