:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): environment setup plan logic and image catalog (#87673)
Shy Alter9b607d1eb71d
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex aee069f78598..96f526b7ab32 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -800,6 +800,23 @@ function readDetail(error: ApiRequestError): string {return body?.detail ?? error.message;}+/**+ * DRF validation failures carry the messages per field, `{ field: [msg] }`,+ * with no top-level `detail`. Flatten them so the server's own wording reaches+ * the toast instead of a bare status text.+ */+function readFieldErrors(error: ApiRequestError): string {+ if (typeof error.body !== "object" || error.body === null) {+ return error.message;+ }+ const record = error.body as Record<string, unknown>;+ if (typeof record.detail === "string") return record.detail;+ const parts = Object.values(record).flatMap((messages) =>+ Array.isArray(messages) ? messages.map(String) : [],+ );+ return parts.length > 0 ? parts.join(" ") : error.message;+}+export interface TaskArtifactUploadRequest {name: string;type: "output" | "user_attachment" | "skill_bundle";@@ -5943,20 +5960,22 @@ export class PostHogAPIClient {const url = new URL(`${this.api.baseUrl}/api/projects/${teamId}/sandbox_environments/`,);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path: `/api/projects/${teamId}/sandbox_environments/`,- overrides: {- body: JSON.stringify(input),- },- });- if (!response.ok) {+ try {+ const response = await this.api.fetcher.fetch({+ method: "post",+ url,+ path: `/api/projects/${teamId}/sandbox_environments/`,+ overrides: {+ body: JSON.stringify(input),+ },+ });+ return (await response.json()) as SandboxEnvironment;+ } catch (error) {+ if (!(error instanceof ApiRequestError)) throw error;throw new Error(- `Failed to create sandbox environment: ${response.statusText}`,+ `Failed to create sandbox environment: ${readFieldErrors(error)}`,);}- return (await response.json()) as SandboxEnvironment;}async updateSandboxEnvironment(@@ -5967,20 +5986,22 @@ export class PostHogAPIClient {const url = new URL(`${this.api.baseUrl}/api/projects/${teamId}/sandbox_environments/${id}/`,);- const response = await this.api.fetcher.fetch({- method: "patch",- url,- path: `/api/projects/${teamId}/sandbox_environments/${id}/`,- overrides: {- body: JSON.stringify(input),- },- });- if (!response.ok) {+ try {+ const response = await this.api.fetcher.fetch({+ method: "patch",+ url,+ path: `/api/projects/${teamId}/sandbox_environments/${id}/`,+ overrides: {+ body: JSON.stringify(input),+ },+ });+ return (await response.json()) as SandboxEnvironment;+ } catch (error) {+ if (!(error instanceof ApiRequestError)) throw error;throw new Error(- `Failed to update sandbox environment: ${response.statusText}`,+ `Failed to update sandbox environment: ${readFieldErrors(error)}`,);}- return (await response.json()) as SandboxEnvironment;}async deleteSandboxEnvironment(id: string): Promise<void> {diff --git a/products/desktop/packages/core/src/settings/environmentSetup.test.ts b/products/desktop/packages/core/src/settings/environmentSetup.test.tsnew file mode 100644index 000000000000..2482c5e30895--- /dev/null+++ b/products/desktop/packages/core/src/settings/environmentSetup.test.ts@@ -0,0 +1,229 @@+import { describe, expect, it } from "vitest";+import {+ type EnvironmentSetupPlan,+ emptyEnvironmentSetupPlan,+ envVarError,+ isPlanDirty,+ isValidDomain,+ parseEnvVarText,+ planEnvironmentInput,+ planImageInput,+ setupSteps,+ setupStepsComplete,+ stepError,+ validateDomains,+ withEnvironmentName,+ withRepositories,+} from "./environmentSetup";++describe("environmentSetup", () => {+ const plan = (patch: Partial<EnvironmentSetupPlan> = {}) => ({+ ...emptyEnvironmentSetupPlan({ repository: "posthog/posthog" }),+ ...patch,+ });++ it("seeds both names from the repository", () => {+ const seeded = emptyEnvironmentSetupPlan({ repository: "posthog/posthog" });+ expect(seeded.environmentName).toBe("posthog cloud runs");+ expect(seeded.imageName).toBe("posthog toolchain");+ });++ it("keeps a typed environment name when the repositories change", () => {+ const typed = withEnvironmentName(plan(), "Internal APIs");+ const moved = withRepositories(typed, ["posthog/hogql"]);+ expect(moved.environmentName).toBe("Internal APIs");+ expect(moved.imageName).toBe("hogql toolchain");+ });++ it("keeps the first repository as the one the image is built for", () => {+ const two = withRepositories(plan(), ["posthog/posthog", "posthog/hogql"]);+ expect(two.repositories).toEqual(["posthog/posthog", "posthog/hogql"]);+ expect(two.imageName).toBe("posthog toolchain");+ });++ it("shows access only for a new environment, and image steps only when building", () => {+ expect(setupSteps(plan()).map((step) => step.key)).toEqual([+ "environment",+ "access",+ "image",+ "review",+ ]);+ expect(+ setupSteps(plan({ target: "existing", baseImage: "new" })).map(+ (step) => step.key,+ ),+ ).toEqual(["environment", "image", "tools", "setup", "review"]);+ });++ it("names what is unresolved on each step", () => {+ expect(stepError(plan({ environmentName: " " }), "environment")).toBe(+ "Give the environment a name.",+ );+ expect(stepError(plan({ target: "existing" }), "environment")).toBe(+ "Pick the environment to add to.",+ );+ expect(stepError(plan({ baseImage: "existing" }), "image")).toBe(+ "Pick an image.",+ );+ expect(+ stepError(+ plan({+ networkAccessLevel: "custom",+ allowedDomainsText: "http://nope",+ }),+ "access",+ ),+ ).toBe("Invalid domain: http://nope");+ });++ it("holds a custom access level that allows nothing", () => {+ expect(stepError(plan({ networkAccessLevel: "custom" }), "access")).toBe(+ "Add a domain, or pick another access level.",+ );+ });++ it("holds review until every visible step resolves", () => {+ expect(stepError(plan({ baseImage: "new", imageName: "" }), "review")).toBe(+ "Give the image a name.",+ );+ expect(setupStepsComplete(plan())).toEqual([true, true, true, true]);+ });++ it("carries the repositories and image onto the environment payload", () => {+ const input = planEnvironmentInput(+ withRepositories(plan(), ["posthog/posthog", "posthog/hogql"]),+ "image-1",+ );+ expect(input).toMatchObject({+ name: "posthog cloud runs",+ repositories: ["posthog/posthog", "posthog/hogql"],+ custom_image_id: "image-1",+ allowed_domains: [],+ include_default_domains: false,+ });+ expect(input.environment_variables).toBeUndefined();+ });++ it("keeps the allowlist only when the access level uses one", () => {+ const custom = planEnvironmentInput(+ plan({+ networkAccessLevel: "custom",+ allowedDomainsText: "github.com\n*.example.com",+ }),+ null,+ );+ expect(custom.allowed_domains).toEqual(["github.com", "*.example.com"]);+ expect(custom.include_default_domains).toBe(true);+ });++ it("sends only the rows that carry a variable", () => {+ const input = planEnvironmentInput(+ plan({+ envVars: [+ { id: "a", key: "OPENAI_API_KEY", value: "sk-test" },+ { id: "b", key: " ", value: "" },+ ],+ }),+ null,+ );+ expect(input.environment_variables).toEqual({ OPENAI_API_KEY: "sk-test" });+ });++ it("carries the repository and privacy onto the image payload", () => {+ const input = planImageInput(plan({ imageName: " CI toolchain " }));+ expect(input.name).toBe("CI toolchain");+ expect(input.repository).toBe("posthog/posthog");+ expect(input.private).toBe(true);+ expect(input.description).toContain("posthog/posthog");++ const bare = planImageInput(+ plan({ repositories: [], private: false, imageName: "Bare" }),+ );+ expect(bare).not.toHaveProperty("repository");+ expect(bare).not.toHaveProperty("private");+ });++ it("marks a plan dirty only when a field actually changed", () => {+ const saved = plan({+ envVars: [{ id: "a", key: "TOKEN", value: "abc" }],+ setupLines: [{ id: "s", value: "pnpm install" }],+ });+ expect(isPlanDirty({ ...saved }, saved)).toBe(false);+ expect(+ isPlanDirty({ ...saved, repositories: ["posthog/hogql"] }, saved),+ ).toBe(true);+ expect(+ isPlanDirty(+ { ...saved, envVars: [{ id: "a", key: "TOKEN", value: "xyz" }] },+ saved,+ ),+ ).toBe(true);+ });++ it("reads pasted variables in the formats people carry them in", () => {+ expect(+ parseEnvVarText(+ [+ "# a comment",+ "export TOKEN=abc",+ 'QUOTED="with spaces"',+ "EMPTY=",+ "not a variable",+ "URL=https://example.com/path?a=b",+ ].join("\n"),+ ),+ ).toEqual([+ { key: "TOKEN", value: "abc" },+ { key: "QUOTED", value: "with spaces" },+ { key: "EMPTY", value: "" },+ { key: "URL", value: "https://example.com/path?a=b" },+ ]);+ });++ it("rejects a malformed or repeated variable name", () => {+ const rows = [+ { id: "a", key: "GOOD", value: "1" },+ { id: "b", key: "2BAD", value: "1" },+ { id: "c", key: "GOOD", value: "2" },+ { id: "d", key: "", value: "orphan" },+ ];+ expect(envVarError(rows[0], rows)).toBe("GOOD is set twice.");+ expect(envVarError(rows[1], rows)).toContain("Letters, digits");+ expect(envVarError(rows[3], rows)).toBe("Name this variable.");+ });++ it.each(["GITHUB_TOKEN", "GH_TOKEN", "POSTHOG_PERSONAL_API_KEY"])(+ "rejects the reserved key %s before submit",+ (key) => {+ const rows = [{ id: "a", key, value: "x" }];+ expect(envVarError(rows[0], rows)).toContain("reserved by PostHog");+ },+ );++ it.each([+ "NODE_OPTIONS",+ "BASH_ENV",+ "LD_PRELOAD",+ "DYLD_PRINT_LIBRARIES",+ "GIT_DIR",+ ])("rejects the blocked key %s before submit", (key) => {+ const rows = [{ id: "a", key, value: "x" }];+ expect(envVarError(rows[0], rows)).toContain("not allowed");+ });+});++describe("validateDomains", () => {+ it.each([+ ["github.com", true],+ ["*.example.com", true],+ ["https://github.com", false],+ ])("isValidDomain(%s) -> %s", (domain, expected) => {+ expect(isValidDomain(domain)).toBe(expected);+ });++ it("collects valid domains, skips blank lines, and reports invalid ones", () => {+ const result = validateDomains("github.com\n\n*.example.com\nnot a domain");+ expect(result.domains).toEqual(["github.com", "*.example.com"]);+ expect(result.errors).toEqual(["Invalid domain: not a domain"]);+ });+});diff --git a/products/desktop/packages/core/src/settings/environmentSetup.ts b/products/desktop/packages/core/src/settings/environmentSetup.tsnew file mode 100644index 000000000000..f36bfaf3823f--- /dev/null+++ b/products/desktop/packages/core/src/settings/environmentSetup.ts@@ -0,0 +1,574 @@+import type {+ NetworkAccessLevel,+ SandboxEnvironment,+ SandboxEnvironmentInput,+} from "@posthog/shared/domain-types";+import {+ DEFAULT_TOOL_IDS,+ IMAGE_PRESET_TOOLS,+ type ImagePresetTool,+ imagePresetBrief,+ imagePresetName,+} from "./imagePreset";+import {+ type ImageSpecInput,+ imageSpecError,+ setupCommandError,+} from "./imageSpec";++const DOMAIN_RE =+ /^(\*\.)?[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/;++export function isValidDomain(domain: string): boolean {+ return DOMAIN_RE.test(domain);+}++export function validateDomains(text: string): {+ domains: string[];+ errors: string[];+} {+ const domains: string[] = [];+ const errors: string[] = [];+ for (const line of text.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ if (isValidDomain(trimmed)) {+ domains.push(trimmed);+ } else {+ errors.push(`Invalid domain: ${trimmed}`);+ }+ }+ return { domains, errors };+}++/** Whether the flow creates an environment or adds to one that exists. */+export type SetupTarget = "new" | "existing";++/**+ * What the flow produces. An image scope creates only an image: it is reused by+ * any environment, so making one must not create an environment as a side+ * effect.+ */+export type SetupScope = "environment" | "image";++/** Where sessions in the environment start from. */+export type BaseImageChoice = "default" | "existing" | "new";++/**+ * A setup command with a stable id. Removing a line must not re-key the rest,+ * or the input being typed in loses focus.+ */+export interface SetupLine {+ id: string;+ value: string;+}++/** One environment variable, with a stable id so a row can be removed. */+export interface EnvVarRow {+ id: string;+ key: string;+ value: string;+}++export interface EnvironmentSetupPlan {+ scope: SetupScope;+ target: SetupTarget;+ /** The environment being added to, when the target is an existing one. */+ environmentId: string | null;+ environmentName: string;+ /** Set once the name is typed into, so the repository stops seeding it. */+ environmentNameEdited: boolean;+ /** Every repository this environment applies to; the first seeds the image. */+ repositories: readonly string[];+ private: boolean;+ networkAccessLevel: NetworkAccessLevel;+ allowedDomainsText: string;+ includeDefaultDomains: boolean;+ envVars: readonly EnvVarRow[];+ /**+ * False when custom images are unavailable (flag off or billing-disabled):+ * the image step disappears and the payload never carries an image id, so+ * the flow cannot walk someone into a build that fails at the end.+ */+ customImages: boolean;+ baseImage: BaseImageChoice;+ /** The image being reused, when the base image is an existing one. */+ existingImageId: string | null;+ imageName: string;+ imageNameEdited: boolean;+ excludedToolIds: readonly string[];+ setupLines: readonly SetupLine[];+}++export interface EmptyPlanOptions {+ repository?: string | null;+ scope?: SetupScope;+ /** False when custom images are unavailable to this account. */+ customImages?: boolean;+}++/**+ * The target always starts as a new environment: an existing one is a choice+ * the first step offers, and defaulting to it would open the flow on a+ * question with no answer yet.+ */+export function emptyEnvironmentSetupPlan({+ repository = null,+ scope = "environment",+ customImages = true,+}: EmptyPlanOptions = {}): EnvironmentSetupPlan {+ return {+ scope,+ target: "new",+ environmentId: null,+ environmentName: repository === null ? "" : environmentNameFor(repository),+ environmentNameEdited: false,+ repositories: repository === null ? [] : [repository],+ private: true,+ networkAccessLevel: "full",+ allowedDomainsText: "",+ includeDefaultDomains: true,+ envVars: [],+ customImages,+ baseImage: customImages && scope === "image" ? "new" : "default",+ existingImageId: null,+ imageName: repository === null ? "" : imagePresetName(repository),+ imageNameEdited: false,+ excludedToolIds: IMAGE_PRESET_TOOLS.filter(+ (tool) => !DEFAULT_TOOL_IDS.includes(tool.id),+ ).map((tool) => tool.id),+ setupLines: [],+ };+}++/**+ * The repository the image is built for. An environment can apply to several,+ * and setup commands run in one checkout, so the first is the one they use.+ */+export function primaryRepository(plan: EnvironmentSetupPlan): string | null {+ return plan.repositories[0] ?? null;+}++/**+ * An existing environment as a plan, so editing one uses the same fields the+ * setup flow does. Variable values are never returned by the API, so the rows+ * start empty and entering any replaces the whole set.+ */+export function planFromEnvironment(+ environment: SandboxEnvironment,+ { customImages = true }: { customImages?: boolean } = {},+): EnvironmentSetupPlan {+ return {+ scope: "environment",+ target: "existing",+ environmentId: environment.id,+ environmentName: environment.name,+ environmentNameEdited: true,+ repositories: environment.repositories,+ private: environment.private,+ networkAccessLevel: environment.network_access_level,+ allowedDomainsText: environment.allowed_domains.join("\n"),+ includeDefaultDomains: environment.include_default_domains,+ envVars: [],+ customImages,+ baseImage: environment.custom_image_id === null ? "default" : "existing",+ existingImageId: environment.custom_image_id,+ imageName: "",+ imageNameEdited: false,+ excludedToolIds: [],+ setupLines: [],+ };+}++/** The environment name suggested for a repository, e.g. `posthog cloud runs`. */+export function environmentNameFor(repository: string): string {+ const repoName = repository.split("/").pop() ?? repository;+ return `${repoName} cloud runs`;+}++/**+ * Both names follow the first repository until they are typed into, so the+ * common path needs no typing and a chosen name is never overwritten.+ */+export function withRepositories(+ plan: EnvironmentSetupPlan,+ repositories: readonly string[],+): EnvironmentSetupPlan {+ const primary = repositories[0] ?? null;+ if (primary === null) return { ...plan, repositories };+ return {+ ...plan,+ repositories,+ environmentName: plan.environmentNameEdited+ ? plan.environmentName+ : environmentNameFor(primary),+ imageName: plan.imageNameEdited ? plan.imageName : imagePresetName(primary),+ };+}++export function withEnvironmentName(+ plan: EnvironmentSetupPlan,+ environmentName: string,+): EnvironmentSetupPlan {+ return { ...plan, environmentName, environmentNameEdited: true };+}++export function withImageName(+ plan: EnvironmentSetupPlan,+ imageName: string,+): EnvironmentSetupPlan {+ return { ...plan, imageName, imageNameEdited: true };+}++export function withToolToggled(+ plan: EnvironmentSetupPlan,+ toolId: string,+): EnvironmentSetupPlan {+ return {+ ...plan,+ excludedToolIds: plan.excludedToolIds.includes(toolId)+ ? plan.excludedToolIds.filter((id) => id !== toolId)+ : [...plan.excludedToolIds, toolId],+ };+}++export function planTools(plan: EnvironmentSetupPlan): ImagePresetTool[] {+ return IMAGE_PRESET_TOOLS.filter(+ (tool) => !plan.excludedToolIds.includes(tool.id),+ );+}++export function planSetupCommands(plan: EnvironmentSetupPlan): string[] {+ return plan.setupLines+ .map((line) => line.value)+ .filter((command) => command.trim() !== "");+}++export function planSpecInput(plan: EnvironmentSetupPlan): ImageSpecInput {+ return {+ tools: planTools(plan),+ setupCommands: planSetupCommands(plan),+ repository: primaryRepository(plan),+ };+}++/** True when the flow will author and build a new image. */+export function buildsImage(plan: EnvironmentSetupPlan): boolean {+ return plan.baseImage === "new";+}++export type SetupStepKey =+ | "environment"+ | "access"+ | "image"+ | "tools"+ | "setup"+ | "review";++const STEP_LABELS: Record<SetupStepKey, string> = {+ environment: "Environment",+ access: "Access",+ image: "Image",+ tools: "Tools",+ setup: "Setup",+ review: "Review",+};++export interface SetupStep {+ key: SetupStepKey;+ label: string;+}++/**+ * The steps this plan actually has. An existing environment keeps its own+ * access settings, and setup commands only exist for an image being built, so+ * neither step is shown as a dead end.+ */+export function setupSteps(plan: EnvironmentSetupPlan): SetupStep[] {+ if (plan.scope === "image") {+ return (["image", "tools", "setup", "review"] as SetupStepKey[]).map(+ (key) => ({ key, label: STEP_LABELS[key] }),+ );+ }+ const keys: SetupStepKey[] = ["environment"];+ if (plan.target === "new") keys.push("access");+ if (plan.customImages) keys.push("image");+ if (buildsImage(plan)) keys.push("tools", "setup");+ keys.push("review");+ return keys.map((key) => ({+ key,+ label: key === "image" ? "Base image" : STEP_LABELS[key],+ }));+}++const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;++/**+ * Keys the environment API refuses, mirrored from RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS+ * in products/tasks/backend/constants.py. The server stays the last word; this copy+ * lets the row show its error before submit.+ */+const RESERVED_ENV_VAR_KEYS: ReadonlySet<string> = new Set([+ "POSTHOG_PERSONAL_API_KEY",+ "POSTHOG_WIZARD_API_KEY",+ "POSTHOG_API_URL",+ "POSTHOG_PROJECT_ID",+ "JWT_PUBLIC_KEY",+ "GITHUB_TOKEN",+ "GH_TOKEN",+ "LLM_GATEWAY_URL",+ "AI_GATEWAY_URL",+ "AI_GATEWAY_PRODUCTS",+ "AI_GATEWAY_TOKEN",+ "POSTHOG_RESUME_RUN_ID",+ "POSTHOG_AGENT_OTEL_LOGS_URL",+ "POSTHOG_AGENT_OTEL_LOGS_TOKEN",+ "POSTHOG_AGENT_OTEL_TRACES_URL",+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",+ "DISABLE_TELEMETRY",+ "DISABLE_ERROR_REPORTING",+ "POSTHOG_CONTEXT_LAYER_PATH",+ "POSTHOG_CONTEXT_LAYER_COMMITS_PATH",+]);++/** BLOCKED_SANDBOX_ENVIRONMENT_VARIABLE_PREFIXES in the same file; same mirror rule. */+const BLOCKED_ENV_VAR_PREFIXES = ["LD_", "DYLD_", "GIT_"] as const;++/** BLOCKED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS in the same file; same mirror rule. */+const BLOCKED_ENV_VAR_KEYS: ReadonlySet<string> = new Set([+ "NODE_OPTIONS",+ "NODE_REPL_EXTERNAL_MODULE",+ "BASH_ENV",+ "PROMPT_COMMAND",+ "PYTHONSTARTUP",+ "PERL5OPT",+ "RUBYOPT",+]);++/** Why one row cannot be sent, or null when it is fine. */+export function envVarError(+ row: EnvVarRow,+ rows: readonly EnvVarRow[],+): string | null {+ const key = row.key.trim();+ if (key === "") return row.value.trim() === "" ? null : "Name this variable.";+ if (!ENV_KEY_RE.test(key)) {+ return "Letters, digits and underscores only, and not starting with a digit.";+ }+ if (RESERVED_ENV_VAR_KEYS.has(key)) {+ return `${key} is reserved by PostHog and cannot be set.`;+ }+ if (+ BLOCKED_ENV_VAR_KEYS.has(key) ||+ BLOCKED_ENV_VAR_PREFIXES.some((prefix) => key.startsWith(prefix))+ ) {+ return `${key} can change how sandbox processes execute code, so it is not allowed.`;+ }+ const duplicate = rows.some(+ (other) => other.id !== row.id && other.key.trim() === key,+ );+ return duplicate ? `${key} is set twice.` : null;+}++/**+ * Splits pasted text into rows. A pasted .env file, a shell export block or a+ * single KEY=value all land the same way, since that is how people carry these+ * between machines.+ */+export function parseEnvVarText(+ text: string,+): { key: string; value: string }[] {+ const rows: { key: string; value: string }[] = [];+ for (const line of text.split(/\r?\n/)) {+ const trimmed = line.trim().replace(/^export\s+/, "");+ if (trimmed === "" || trimmed.startsWith("#")) continue;+ const separator = trimmed.indexOf("=");+ if (separator <= 0) continue;+ const key = trimmed.slice(0, separator).trim();+ let value = trimmed.slice(separator + 1).trim();+ if (+ value.length >= 2 &&+ ((value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'")))+ ) {+ value = value.slice(1, -1);+ }+ rows.push({ key, value });+ }+ return rows;+}++/** The rows that carry a variable, ignoring blank ones left behind. */+export function filledEnvVars(plan: EnvironmentSetupPlan): EnvVarRow[] {+ return plan.envVars.filter((row) => row.key.trim() !== "");+}++/** Why a step is unresolved, or null when it is done. */+export function stepError(+ plan: EnvironmentSetupPlan,+ key: SetupStepKey,+): string | null {+ switch (key) {+ case "environment":+ if (plan.target === "existing") {+ return plan.environmentId === null+ ? "Pick the environment to add to."+ : null;+ }+ return plan.environmentName.trim() === ""+ ? "Give the environment a name."+ : null;++ case "access": {+ if (plan.networkAccessLevel === "custom") {+ const domains = validateDomains(plan.allowedDomainsText);+ if (domains.errors[0]) return domains.errors[0];+ if (domains.domains.length === 0) {+ return "Add a domain, or pick another access level.";+ }+ }+ for (const row of plan.envVars) {+ const error = envVarError(row, plan.envVars);+ if (error) return error;+ }+ return null;+ }++ case "image":+ if (plan.scope === "image") {+ return plan.imageName.trim() === "" ? "Give the image a name." : null;+ }+ if (plan.baseImage === "existing") {+ return plan.existingImageId === null ? "Pick an image." : null;+ }+ if (plan.baseImage === "new" && plan.imageName.trim() === "") {+ return "Give the image a name.";+ }+ return null;++ case "tools":+ return imageSpecError(planSpecInput(plan));++ case "setup": {+ for (const command of planSetupCommands(plan)) {+ const error = setupCommandError(command);+ if (error) return error;+ }+ return null;+ }++ case "review": {+ for (const step of setupSteps(plan)) {+ if (step.key === "review") continue;+ const error = stepError(plan, step.key);+ if (error) return error;+ }+ return null;+ }+ }+}++/** Per-step completeness, in the order `setupSteps` returns. */+export function setupStepsComplete(plan: EnvironmentSetupPlan): boolean[] {+ return setupSteps(plan).map((step) => stepError(plan, step.key) === null);+}++/**+ * The environment payload this plan creates. The repositories are carried so+ * the environment records what it is for, which is also how the cost checklist+ * sees that an image is in use.+ */+export function planEnvironmentInput(+ plan: EnvironmentSetupPlan,+ customImageId: string | null,+): SandboxEnvironmentInput {+ const isCustom = plan.networkAccessLevel === "custom";+ const envVars = filledEnvVars(plan);+ return {+ name: plan.environmentName.trim(),+ network_access_level: plan.networkAccessLevel,+ allowed_domains: isCustom+ ? validateDomains(plan.allowedDomainsText).domains+ : [],+ include_default_domains: isCustom ? plan.includeDefaultDomains : false,+ private: plan.private,+ repositories: [...plan.repositories],+ // Accounts without custom images must not send the key at all: the API+ // rejects it when the feature is billing-disabled.+ ...(plan.customImages ? { custom_image_id: customImageId } : {}),+ ...(envVars.length > 0+ ? {+ environment_variables: Object.fromEntries(+ envVars.map((row) => [row.key.trim(), row.value]),+ ),+ }+ : {}),+ };+}++export interface ImageCreateInput {+ name: string;+ description: string;+ repository?: string;+ private?: boolean;+}++/** The creation payload for the image this plan builds. */+export function planImageInput(plan: EnvironmentSetupPlan): ImageCreateInput {+ const repository = primaryRepository(plan);+ return {+ name: plan.imageName.trim(),+ description: imagePresetBrief(+ repository,+ planTools(plan),+ planSetupCommands(plan),+ ),+ ...(repository ? { repository } : {}),+ ...(plan.private ? { private: true } : {}),+ };+}++function sameArray<T>(+ a: readonly T[],+ b: readonly T[],+ same: (x: T, y: T) => boolean = (x, y) => x === y,+): boolean {+ return (+ a.length === b.length && a.every((item, index) => same(item, b[index]))+ );+}++/** Whether the plan differs from the saved one, compared field by field. */+export function isPlanDirty(+ plan: EnvironmentSetupPlan,+ saved: EnvironmentSetupPlan,+): boolean {+ return !(+ plan.scope === saved.scope &&+ plan.target === saved.target &&+ plan.environmentId === saved.environmentId &&+ plan.environmentName === saved.environmentName &&+ plan.environmentNameEdited === saved.environmentNameEdited &&+ sameArray(plan.repositories, saved.repositories) &&+ plan.private === saved.private &&+ plan.networkAccessLevel === saved.networkAccessLevel &&+ plan.allowedDomainsText === saved.allowedDomainsText &&+ plan.includeDefaultDomains === saved.includeDefaultDomains &&+ sameArray(+ plan.envVars,+ saved.envVars,+ (x, y) => x.id === y.id && x.key === y.key && x.value === y.value,+ ) &&+ plan.customImages === saved.customImages &&+ plan.baseImage === saved.baseImage &&+ plan.existingImageId === saved.existingImageId &&+ plan.imageName === saved.imageName &&+ plan.imageNameEdited === saved.imageNameEdited &&+ sameArray(plan.excludedToolIds, saved.excludedToolIds) &&+ sameArray(+ plan.setupLines,+ saved.setupLines,+ (x, y) => x.id === y.id && x.value === y.value,+ )+ );+}diff --git a/products/desktop/packages/core/src/settings/imagePreset.test.ts b/products/desktop/packages/core/src/settings/imagePreset.test.tsnew file mode 100644index 000000000000..b4c2379a5779--- /dev/null+++ b/products/desktop/packages/core/src/settings/imagePreset.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { IMAGE_PRESET_TOOLS, imagePresetBrief } from "./imagePreset";++describe("imagePresetBrief", () => {+ it("carries each pinned version, so the builder installs the vetted release", () => {+ const brief = imagePresetBrief("PostHog/posthog", IMAGE_PRESET_TOOLS, []);+ const pinned = IMAGE_PRESET_TOOLS.filter((tool) => tool.version);+ expect(pinned.length).toBeGreaterThan(0);+ for (const tool of pinned) {+ expect(brief).toContain(`${tool.command}@${tool.version}`);+ }+ });++ it("leaves unpinned tools without a version marker", () => {+ const brief = imagePresetBrief("PostHog/posthog", IMAGE_PRESET_TOOLS, []);+ expect(brief).not.toContain("@undefined");+ const unpinned = IMAGE_PRESET_TOOLS.filter((tool) => !tool.version);+ expect(unpinned.length).toBeGreaterThan(0);+ for (const tool of unpinned) {+ expect(brief).toContain(`- ${tool.command} (${tool.name}):`);+ }+ });+});diff --git a/products/desktop/packages/core/src/settings/imagePreset.ts b/products/desktop/packages/core/src/settings/imagePreset.tsnew file mode 100644index 000000000000..30ef80777775--- /dev/null+++ b/products/desktop/packages/core/src/settings/imagePreset.ts@@ -0,0 +1,593 @@+/**+ * The starting toolset for a cost-management custom sandbox image, and the+ * brief that seeds the builder session.+ *+ * Every entry is a tool an agent commonly reaches for, chosen because it either+ * returns less text than the default it replaces or removes a per-run install.+ * Each reason states what the tool does. None of them claims a savings figure.+ *+ * `aptPackages` is how the tool gets onto the image. A tool apt carries (plus+ * at most a symlink) can be written straight into a spec and built. The rest+ * need a multi-step install that has to be verified inside the image, which is+ * what the builder session is for.+ */++/** How the list is grouped, so a long catalog stays scannable. */+export type ImageToolCategory =+ | "search"+ | "data"+ | "web"+ | "code"+ | "shell"+ | "media"+ | "platform";++export const IMAGE_TOOL_CATEGORIES: {+ id: ImageToolCategory;+ label: string;+}[] = [+ { id: "search", label: "Search and navigation" },+ { id: "data", label: "Structured data" },+ { id: "web", label: "Reading web pages and documents" },+ { id: "code", label: "Reading and changing code" },+ { id: "shell", label: "Shell and network" },+ { id: "media", label: "Screenshots and video" },+ { id: "platform", label: "Repository platform" },+];++export interface ImagePresetTool {+ id: string;+ category: ImageToolCategory;+ /** The command as typed, so the list reads like the shell it lands in. */+ command: string;+ name: string;+ /** One line, present tense, on what having it changes. */+ reason: string;+ /** Where the tool is documented, so a name can be checked before it is picked. */+ url: string;+ /** Rough installed size, so a long list's cost on the image stays visible. */+ sizeMb: number;+ /** Debian packages that install it, when apt carries it. */+ aptPackages?: string[];+ /** Single-line commands run after the packages, e.g. a symlink. */+ runCommands?: string[];+ /** mise registry name, when it differs from this tool's id. */+ miseTool?: string;+ /**+ * Exact version to install, for anything not carried by apt. Unpinned means+ * a rebuild can pull different code than the build before it, so the version+ * is part of the catalog rather than resolved at build time.+ */+ version?: string;+}++/** How the tool gets onto the image. */+export type ToolInstallMethod = "apt" | "script" | "mise";++/**+ * apt when Debian carries it, the tool's own commands when it brings them, and+ * mise for the rest. Order matters: a tool that ships an install script is not+ * in mise's registry, and asking mise for it fails the whole build.+ */+export function toolInstallMethod(tool: ImagePresetTool): ToolInstallMethod {+ if ((tool.aptPackages?.length ?? 0) > 0) return "apt";+ if ((tool.runCommands?.length ?? 0) > 0) return "script";+ return "mise";+}++/**+ * The tools an image starts with: the four an agent reaches for on nearly every+ * run. Everything else in the catalog is opt-in, so a new image stays small+ * unless someone asks for more.+ */+export const DEFAULT_TOOL_IDS: readonly string[] = [+ "ripgrep",+ "fd",+ "jq",+ "tree",+];++/** A tool the wizard can write into a spec without a builder session. */+export function isDirectlyInstallable(tool: ImagePresetTool): boolean {+ return (tool.aptPackages?.length ?? 0) > 0;+}++/** The image size the picked tools add, for the footer's running total. */+export function toolsSizeMb(tools: readonly ImagePresetTool[]): number {+ return tools.reduce((total, tool) => total + tool.sizeMb, 0);+}++export const IMAGE_PRESET_TOOLS: readonly ImagePresetTool[] = [+ {+ id: "ripgrep",+ category: "search",+ command: "rg",+ name: "ripgrep",+ url: "https://github.com/BurntSushi/ripgrep",+ sizeMb: 5,+ reason: "Faster search, and it respects gitignore",+ aptPackages: ["ripgrep"],+ },+ {+ id: "fd",+ category: "search",+ command: "fd",+ name: "fd",+ url: "https://github.com/sharkdp/fd",+ sizeMb: 3,+ reason: "Finds files by name without a find expression",+ aptPackages: ["fd-find"],+ runCommands: ["ln -sf $(command -v fdfind) /usr/local/bin/fd"],+ },+ {+ id: "jq",+ category: "data",+ command: "jq",+ name: "jq",+ url: "https://jqlang.github.io/jq/",+ sizeMb: 1,+ reason: "Reads one field out of a JSON response",+ aptPackages: ["jq"],+ },+ {+ id: "tree",+ category: "search",+ command: "tree",+ name: "tree",+ url: "https://gitlab.com/OldManProgrammer/unix-tree",+ sizeMb: 1,+ reason: "Shows a directory's shape in one call",+ aptPackages: ["tree"],+ },+ {+ id: "w3m",+ category: "web",+ command: "w3m",+ name: "w3m",+ url: "https://github.com/tats/w3m",+ sizeMb: 4,+ reason: "Renders a saved HTML page as text, so markup stays out of context",+ aptPackages: ["w3m"],+ },+ {+ id: "pandoc",+ category: "web",+ command: "pandoc",+ name: "Pandoc",+ url: "https://pandoc.org",+ sizeMb: 130,+ reason: "Converts HTML, docx and rst to Markdown in one call",+ aptPackages: ["pandoc"],+ },+ {+ id: "pdftotext",+ category: "web",+ command: "pdftotext",+ name: "Poppler utils",+ url: "https://poppler.freedesktop.org",+ sizeMb: 2,+ reason: "Reads a PDF as text, which the agent otherwise cannot open",+ aptPackages: ["poppler-utils"],+ },+ {+ id: "shellcheck",+ category: "code",+ command: "shellcheck",+ name: "ShellCheck",+ url: "https://www.shellcheck.net",+ sizeMb: 20,+ reason: "Finds shell bugs without running the script",+ aptPackages: ["shellcheck"],+ },+ {+ id: "ctags",+ category: "code",+ command: "ctags",+ name: "Universal Ctags",+ url: "https://github.com/universal-ctags/ctags",+ sizeMb: 4,+ reason: "Finds where a symbol is defined without reading the file",+ aptPackages: ["universal-ctags"],+ runCommands: ["ln -sf $(command -v ctags-universal) /usr/local/bin/ctags"],+ },+ {+ id: "yamllint",+ category: "code",+ command: "yamllint",+ name: "yamllint",+ url: "https://github.com/adrienverge/yamllint",+ sizeMb: 3,+ reason: "Names the line a broken manifest breaks on",+ aptPackages: ["yamllint"],+ },+ {+ id: "actionlint",+ version: "1.7.12",+ category: "code",+ command: "actionlint",+ name: "actionlint",+ url: "https://github.com/rhysd/actionlint",+ sizeMb: 6,+ reason: "Catches a broken workflow before a push waits on red CI",+ },+ {+ id: "ast-grep",+ version: "0.45.1",+ category: "code",+ command: "ast-grep",+ name: "ast-grep",+ url: "https://ast-grep.github.io",+ sizeMb: 12,+ reason: "Matches code by syntax instead of by text",+ },+ {+ id: "yq",+ version: "4.53.6",+ category: "data",+ command: "yq",+ name: "yq",+ url: "https://github.com/mikefarah/yq",+ sizeMb: 12,+ reason: "The same as jq, for YAML config and workflows",+ },+ {+ id: "sd",+ category: "code",+ command: "sd",+ name: "sd",+ url: "https://github.com/chmln/sd",+ sizeMb: 3,+ reason: "Replaces text across files without a sed expression",+ aptPackages: ["sd"],+ },+ {+ id: "miller",+ category: "data",+ command: "mlr",+ name: "Miller",+ url: "https://miller.readthedocs.io",+ sizeMb: 12,+ reason: "Queries CSV and TSV without loading it into a script",+ aptPackages: ["miller"],+ },+ {+ id: "sqlite3",+ category: "data",+ command: "sqlite3",+ name: "SQLite",+ url: "https://www.sqlite.org",+ sizeMb: 2,+ reason: "Queries the .db files a repository ships, in one call",+ aptPackages: ["sqlite3"],+ },+ {+ id: "duckdb",+ version: "1.5.5",+ category: "data",+ command: "duckdb",+ name: "DuckDB",+ url: "https://duckdb.org",+ sizeMb: 40,+ reason: "Runs SQL over a CSV, JSON or Parquet file with no import step",+ },+ {+ id: "xmllint",+ category: "data",+ command: "xmllint",+ name: "libxml2 utils",+ url: "https://gitlab.gnome.org/GNOME/libxml2",+ sizeMb: 1,+ reason: "Pulls one XPath match out of XML, and checks it parses",+ aptPackages: ["libxml2-utils"],+ },+ {+ id: "gron",+ category: "data",+ command: "gron",+ name: "gron",+ url: "https://github.com/tomnomnom/gron",+ sizeMb: 4,+ reason: "Flattens JSON into lines, so a field can be grepped",+ aptPackages: ["gron"],+ },+ {+ id: "difftastic",+ version: "0.70.0",+ category: "code",+ command: "difft",+ name: "difftastic",+ url: "https://difftastic.wilfred.me.uk",+ sizeMb: 10,+ reason: "Diffs by syntax, so a reformat is not a wall of changes",+ },+ {+ id: "moreutils",+ category: "shell",+ command: "sponge",+ name: "moreutils",+ url: "https://joeyh.name/code/moreutils/",+ sizeMb: 1,+ reason:+ "Writes a file it just read without truncating it, plus chronic, ts and parallel",+ aptPackages: ["moreutils"],+ },+ {+ id: "bsdtar",+ category: "shell",+ command: "bsdtar",+ name: "libarchive tools",+ url: "https://www.libarchive.org",+ sizeMb: 4,+ reason: "Unpacks tar, zip, 7z and iso without picking an extractor",+ aptPackages: ["libarchive-tools", "unzip", "zstd"],+ },+ {+ id: "dig",+ category: "shell",+ command: "dig",+ name: "BIND DNS utils",+ url: "https://www.isc.org/bind/",+ sizeMb: 2,+ reason: "Separates a blocked host from a wrong one in one call",+ aptPackages: ["bind9-dnsutils"],+ },+ {+ id: "xh",+ version: "0.26.2",+ category: "shell",+ command: "xh",+ name: "xh",+ url: "https://github.com/ducaale/xh",+ sizeMb: 6,+ reason: "Calls a JSON API and prints the body without the header block",+ },+ // Tools for looking at what the agent built. A browser install belongs in+ // the setup step instead: it has to match the repository's own Playwright+ // version and warm its browser cache, which only a checkout can do.+ {+ id: "playwright",+ category: "media",+ command: "playwright",+ name: "Playwright with Chromium",+ url: "https://playwright.dev/docs/browsers",+ sizeMb: 450,+ reason: "Drives a browser to screenshot and record what the agent built",+ runCommands: [+ "npm install -g [email protected] && playwright install --with-deps chromium",+ ],+ },+ {+ id: "ffmpeg",+ category: "media",+ command: "ffmpeg",+ name: "FFmpeg",+ url: "https://ffmpeg.org/documentation.html",+ sizeMb: 240,+ reason: "Trims and converts the video a browser test recorded",+ aptPackages: ["ffmpeg"],+ },+ {+ id: "imagemagick",+ category: "media",+ command: "convert",+ name: "ImageMagick",+ url: "https://imagemagick.org/script/command-line-tools.php",+ sizeMb: 60,+ reason: "Crops and compares screenshots without writing a script",+ aptPackages: ["imagemagick"],+ },+ // Repository tools that do not depend on which host the repo lives on.+ {+ id: "gh",+ category: "platform",+ version: "2.97.0",+ command: "gh",+ name: "GitHub CLI",+ url: "https://cli.github.com",+ sizeMb: 40,+ reason: "Reads issues, pull requests and CI logs without scraping",+ },+ {+ id: "git-lfs",+ category: "platform",+ command: "git-lfs",+ name: "Git LFS",+ url: "https://git-lfs.com",+ sizeMb: 12,+ reason: "Checks out real files instead of pointer stubs",+ aptPackages: ["git-lfs"],+ },+ {+ id: "gitleaks",+ category: "platform",+ command: "gitleaks",+ name: "Gitleaks",+ url: "https://github.com/gitleaks/gitleaks",+ sizeMb: 12,+ reason: "Scans a diff for secrets offline, before anything is pushed",+ aptPackages: ["gitleaks"],+ },+ {+ id: "git-absorb",+ category: "platform",+ command: "git-absorb",+ name: "git-absorb",+ url: "https://github.com/tummychow/git-absorb",+ sizeMb: 3,+ reason: "Folds fixups into the commits they belong to, without a rebase",+ aptPackages: ["git-absorb"],+ runCommands: [+ "ln -sf /usr/lib/git-core/git-absorb /usr/local/bin/git-absorb",+ ],+ },+];++/** A short, human name for the image, derived from the repo it serves. */+export function imagePresetName(repository: string): string {+ const repoName = repository.split("/").pop() ?? repository;+ return `${repoName} toolchain`;+}++/**+ * The brief handed to the builder session. The builder authors and verifies the+ * spec, so this states the goal, the tools and the setup commands rather than+ * shell lines, and asks it to report anything it could not install instead of+ * silently dropping it.+ */+export function imagePresetBrief(+ repository: string | null,+ tools: readonly ImagePresetTool[],+ setupCommands: readonly string[],+): string {+ const toolLines = tools+ .map((tool) => {+ const invocation = tool.version+ ? `${tool.command}@${tool.version}`+ : tool.command;+ return `- ${invocation} (${tool.name}): ${tool.reason}`;+ })+ .join("\n");+ const target = repository ?? "our cloud runs";+ const sections = [+ `Build a sandbox image for ${target} that cloud runs can start from without a setup step.`,+ `Put these command line tools on PATH:\n\n${toolLines}`,+ ];+ if (repository) {+ const commands = setupCommands.filter((command) => command.trim() !== "");+ sections.push(+ commands.length > 0+ ? `Run these in a checkout of ${repository} so a run starts with dependencies warm:\n\n${commands.map((command) => `- ${command}`).join("\n")}`+ : `Read ${repository} to find how its dependencies are installed (lockfiles, package managers, language runtimes, browsers or system libraries the tests need) and warm them at the versions the repo pins.`,+ );+ }+ sections.push(+ "Keep the image lean: no editors, shells or interactive tools, since nobody types in it. Pin versions where the tool has a stable release channel. When something cannot be installed, leave it out and say so in your summary rather than substituting an alternative.",+ );+ return sections.join("\n\n");+}++/**+ * Setup commands worth offering, since they are the ones that pay off most and+ * the easiest to get subtly wrong. They run in a checkout at build time, so a+ * browser or dependency install lands at the version the repository pins and+ * its cache is baked in.+ */+export type SetupCommandGroup = "dependencies" | "toolchains" | "project";++export const SETUP_COMMAND_GROUPS: readonly {+ id: SetupCommandGroup;+ label: string;+}[] = [+ { id: "dependencies", label: "Dependencies" },+ { id: "toolchains", label: "Toolchains" },+ { id: "project", label: "Project setup" },+];++export interface SetupCommandSuggestion {+ id: string;+ group: SetupCommandGroup;+ label: string;+ command: string;+ /** One line on what it buys, or what it costs. */+ note: string;+}++/**+ * Commands worth offering, one per ecosystem: the install a repository runs+ * before anything else, in the form that reads the lockfile instead of+ * resolving fresh. Tools the image can install belong in the tools step, so+ * nothing here installs a binary the catalog already carries.+ */+export const SETUP_COMMAND_SUGGESTIONS: readonly SetupCommandSuggestion[] = [+ {+ id: "pnpm",+ group: "dependencies",+ label: "Node (pnpm)",+ command: "corepack enable && pnpm install --frozen-lockfile",+ note: "Warms the pnpm store at the version packageManager pins, so a session install is a linking pass.",+ },+ {+ id: "npm",+ group: "dependencies",+ label: "Node (npm)",+ command: "npm ci --prefer-offline --no-audit",+ note: "Installs from package-lock.json only, so the build fails rather than drifting off the lockfile.",+ },+ {+ id: "uv",+ group: "dependencies",+ label: "Python (uv)",+ command: "uv sync --frozen",+ note: "Warms the uv cache from uv.lock. uv is already on the base image.",+ },+ {+ id: "poetry",+ group: "dependencies",+ label: "Python (poetry)",+ command: "poetry install --no-interaction --no-root",+ note: "For repositories on poetry.lock. Skips installing the project itself, which the checkout already has.",+ },+ {+ id: "go",+ group: "dependencies",+ label: "Go modules",+ command: "go mod download",+ note: "Fills the module cache from go.sum, which is most of a cold Go build.",+ },+ {+ id: "cargo",+ group: "dependencies",+ label: "Rust crates",+ command: "cargo fetch --locked",+ note: "Downloads every crate in Cargo.lock without building, so nothing is resolved at session start.",+ },+ {+ id: "bundler",+ group: "dependencies",+ label: "Ruby gems",+ command: "bundle install --jobs 4",+ note: "Installs the gems in Gemfile.lock, including native extensions that are slow to compile.",+ },+ {+ id: "gradle",+ group: "dependencies",+ label: "Gradle",+ command: "./gradlew --no-daemon dependencies",+ note: "Resolves and caches the dependency graph. No daemon, since the build here is one shot.",+ },+ {+ id: "maven",+ group: "dependencies",+ label: "Maven",+ command: "mvn -B -q dependency:go-offline",+ note: "Pulls everything the build needs into the local repository, so a session can build offline.",+ },+ {+ id: "composer",+ group: "dependencies",+ label: "PHP packages",+ command: "composer install --no-interaction --prefer-dist",+ note: "Installs from composer.lock and prefers prebuilt archives over cloning each package.",+ },+ {+ id: "dotnet",+ group: "dependencies",+ label: "NuGet packages",+ command: "dotnet restore",+ note: "Restores packages for every project in the solution.",+ },+ {+ id: "mise-repo",+ group: "toolchains",+ label: "Toolchains the repo pins",+ command: "mise install -y",+ note: "Installs the versions declared in .mise.toml or .tool-versions, so nothing is guessed.",+ },+ {+ id: "pre-commit",+ group: "project",+ label: "Pre-commit hooks",+ command: "pre-commit install --install-hooks",+ note: "Builds each hook's environment now, so the first commit in a session is not a five-minute wait.",+ },+];diff --git a/products/desktop/packages/core/src/settings/imageSpec.test.ts b/products/desktop/packages/core/src/settings/imageSpec.test.tsnew file mode 100644index 000000000000..8d261b7e4a1c--- /dev/null+++ b/products/desktop/packages/core/src/settings/imageSpec.test.ts@@ -0,0 +1,220 @@+import { IMAGE_TOOLS_ENV_KEY } from "@posthog/shared/constants";+import { describe, expect, it } from "vitest";+import {+ IMAGE_PRESET_TOOLS,+ type ImagePresetTool,+ SETUP_COMMAND_SUGGESTIONS,+ toolInstallMethod,+} from "./imagePreset";+import {+ buildImageSpec,+ imageSpecError,+ imageSpecToYaml,+ setupCommandError,+} from "./imageSpec";++const aptTools = IMAGE_PRESET_TOOLS.filter(+ (tool) => (tool.aptPackages?.length ?? 0) > 0,+);+const builderTool = IMAGE_PRESET_TOOLS.find(+ (tool) => (tool.aptPackages?.length ?? 0) === 0,+) as ImagePresetTool;++describe("setupCommandError", () => {+ it.each([+ ["pnpm install --frozen-lockfile", null],+ ["", "Enter a command or remove the line."],+ ["a\nb", "One line per command. Chain steps with &&."],+ ] as const)("%j", (command, expected) => {+ expect(setupCommandError(command)).toBe(expected);+ });++ it("rejects a command past the length cap", () => {+ expect(setupCommandError("x".repeat(5000))).toMatch(/4096 characters/);+ });+});++describe("imageSpecError", () => {+ it("passes for tools plus commands with a repository", () => {+ expect(+ imageSpecError({+ tools: aptTools,+ setupCommands: ["pnpm install"],+ repository: "posthog/posthog",+ }),+ ).toBeNull();+ });++ it("requires something to install", () => {+ expect(+ imageSpecError({ tools: [], setupCommands: [], repository: null }),+ ).toMatch(/at least one tool/);+ });++ it("requires a repository for setup commands, since they run in a checkout", () => {+ expect(+ imageSpecError({+ tools: aptTools,+ setupCommands: ["pnpm install"],+ repository: null,+ }),+ ).toMatch(/pick a repository/);+ });++ it("surfaces a bad command", () => {+ expect(+ imageSpecError({+ tools: aptTools,+ setupCommands: ["cd foo\nmake"],+ repository: "posthog/posthog",+ }),+ ).toMatch(/One line per command/);+ });+});++describe("buildImageSpec", () => {+ it("collects packages and commands, dropping duplicates", () => {+ const spec = buildImageSpec({+ tools: [...aptTools, ...aptTools],+ setupCommands: [" pnpm install ", ""],+ repository: "posthog/posthog",+ });+ expect(spec.apt_packages).toEqual(+ aptTools.flatMap((tool) => tool.aptPackages ?? []),+ );+ expect(spec.run_commands).toEqual([+ ...new Set(aptTools.flatMap((tool) => tool.runCommands ?? [])),+ ]);+ expect(spec.repo_setup_commands).toEqual(["pnpm install"]);+ });++ it("drops setup commands without a repository to run them in", () => {+ const spec = buildImageSpec({+ tools: aptTools,+ setupCommands: ["pnpm install"],+ repository: null,+ });+ expect(spec.repo_setup_commands).toEqual([]);+ });++ it("installs a non-apt tool with mise, and links it onto PATH", () => {+ const spec = buildImageSpec({+ tools: [builderTool],+ setupCommands: [],+ repository: null,+ });+ expect(spec.apt_packages).toEqual([]);+ expect(spec.run_commands[0]).toContain("sha256sum -c -");+ expect(spec.run_commands[0]).toMatch(+ /releases\/download\/v[\d.]+\/mise-v[\d.]+-linux-"\$MISE_ARCH"\.tar\.gz/,+ );+ expect(spec.run_commands[0]).toContain("x86_64) MISE_ARCH=x64");+ expect(spec.run_commands[0]).toContain("aarch64|arm64) MISE_ARCH=arm64");+ expect(spec.run_commands[1]).toContain("mise use -g -y");+ expect(spec.run_commands[1]).toContain(+ `/usr/local/bin/${builderTool.command}`,+ );+ });++ it("bootstraps mise once, however many tools need it", () => {+ const miseTools = IMAGE_PRESET_TOOLS.filter(+ (tool) => (tool.aptPackages?.length ?? 0) === 0,+ ).slice(0, 3);+ const spec = buildImageSpec({+ tools: miseTools,+ setupCommands: [],+ repository: null,+ });+ const bootstraps = spec.run_commands.filter((command) =>+ command.includes("install -m 0755 /tmp/mise/bin/mise"),+ );+ expect(bootstraps).toHaveLength(1);+ expect(spec.run_commands).toHaveLength(1 + miseTools.length);+ });++ it("leaves mise out entirely when apt carries everything", () => {+ const spec = buildImageSpec({+ tools: aptTools,+ setupCommands: [],+ repository: null,+ });+ expect(spec.run_commands.some((command) => command.includes("mise"))).toBe(+ false,+ );+ });+});++describe("tool pinning", () => {+ it("pins a version for every tool apt does not carry", () => {+ const unpinned = IMAGE_PRESET_TOOLS.filter(+ (tool) => toolInstallMethod(tool) === "mise",+ ).filter((tool) => !tool.version);+ expect(unpinned.map((tool) => tool.id)).toEqual([]);+ });++ it("never emits an unpinned mise install", () => {+ const spec = buildImageSpec({+ tools: IMAGE_PRESET_TOOLS,+ setupCommands: [],+ repository: null,+ });+ const unpinned = spec.run_commands.filter((command) =>+ command.includes("@latest"),+ );+ expect(unpinned).toEqual([]);+ });++ it("offers no setup command that resolves a version at build time", () => {+ // A rebuild re-runs these commands, so a `latest` toolchain lands a+ // different runtime without any repository change.+ const unpinned = SETUP_COMMAND_SUGGESTIONS.filter((suggestion) =>+ suggestion.command.includes("@latest"),+ );+ expect(unpinned.map((suggestion) => suggestion.id)).toEqual([]);+ });+});++describe("buildImageSpec env", () => {+ it("publishes the tools it installed, so the agent is told about them", () => {+ const spec = buildImageSpec({+ tools: aptTools,+ setupCommands: [],+ repository: null,+ });+ expect(spec.env[IMAGE_TOOLS_ENV_KEY]?.split(" ")).toEqual(+ aptTools.map((tool) => tool.command),+ );+ expect(imageSpecToYaml(spec)).toContain(` ${IMAGE_TOOLS_ENV_KEY}: '`);+ });+});++describe("imageSpecToYaml", () => {+ it("writes only the lists that have entries, with quoted values", () => {+ expect(+ imageSpecToYaml({+ apt_packages: ["ripgrep"],+ run_commands: [],+ repo_setup_commands: ["pnpm install --frozen-lockfile"],+ env: {},+ }),+ ).toBe(+ [+ "apt_packages:",+ " - 'ripgrep'",+ "repo_setup_commands:",+ " - 'pnpm install --frozen-lockfile'",+ ].join("\n"),+ );+ });++ it("escapes a quote so the YAML stays parseable", () => {+ expect(+ imageSpecToYaml({+ apt_packages: [],+ run_commands: ["echo 'hi'"],+ repo_setup_commands: [],+ env: {},+ }),+ ).toBe(["run_commands:", " - 'echo ''hi'''"].join("\n"));+ });+});diff --git a/products/desktop/packages/core/src/settings/imageSpec.ts b/products/desktop/packages/core/src/settings/imageSpec.tsnew file mode 100644index 000000000000..57fdd901b590--- /dev/null+++ b/products/desktop/packages/core/src/settings/imageSpec.ts@@ -0,0 +1,202 @@+import { IMAGE_TOOLS_ENV_KEY } from "@posthog/shared/constants";+import { type ImagePresetTool, toolInstallMethod } from "./imagePreset";++/**+ * Builds the declarative sandbox image spec the backend scans and builds.+ *+ * The rules here mirror the server's schema, so the wizard cannot produce a+ * spec the scanner rejects: commands are single-line (each becomes one+ * Dockerfile RUN, so chain with &&), apt package names are lowercase and free+ * of shell characters, repo setup commands need a repository to run in, and+ * every list is capped.+ */++const MAX_APT_PACKAGES = 128;+const MAX_RUN_COMMANDS = 64;+export const MAX_COMMAND_LENGTH = 4096;++const APT_PACKAGE_PATTERN = /^[a-z0-9][a-z0-9+.-]*$/;++export interface ImageSpec {+ apt_packages: string[];+ run_commands: string[];+ repo_setup_commands: string[];+ /** Baked into the image, so every session on it starts with these set. */+ env: Record<string, string>;+}++export interface ImageSpecInput {+ tools: readonly ImagePresetTool[];+ setupCommands: readonly string[];+ /** `org/repo`, or null when the image is not tied to one. */+ repository: string | null;+}++/** Why a single setup command cannot be built, or null when it is fine. */+export function setupCommandError(command: string): string | null {+ const trimmed = command.trim();+ if (trimmed === "") return "Enter a command or remove the line.";+ if (/[\r\n]/.test(command)) {+ return "One line per command. Chain steps with &&.";+ }+ if (trimmed.length > MAX_COMMAND_LENGTH) {+ return `Commands are limited to ${MAX_COMMAND_LENGTH} characters.`;+ }+ return null;+}++/** Why the spec cannot be built, or null when it is ready. */+export function imageSpecError({+ tools,+ setupCommands,+ repository,+}: ImageSpecInput): string | null {+ if (tools.length === 0 && setupCommands.length === 0) {+ return "Pick at least one tool, or add a setup command.";+ }+ const commands = setupCommands.filter((command) => command.trim() !== "");+ if (commands.length > 0 && !repository) {+ return "Setup commands run in a repository checkout, so pick a repository first.";+ }+ for (const command of commands) {+ const error = setupCommandError(command);+ if (error) return error;+ }+ if (aptPackagesFor(tools).length > MAX_APT_PACKAGES) {+ return `Images are limited to ${MAX_APT_PACKAGES} packages.`;+ }+ if (commands.length + toolCommands(tools).length > MAX_RUN_COMMANDS) {+ return `Images are limited to ${MAX_RUN_COMMANDS} commands.`;+ }+ return null;+}++function aptPackagesFor(tools: readonly ImagePresetTool[]): string[] {+ return tools+ .flatMap((tool) => tool.aptPackages ?? [])+ .filter((name) => APT_PACKAGE_PATTERN.test(name));+}++function runCommandsFor(tools: readonly ImagePresetTool[]): string[] {+ return tools.flatMap((tool) => tool.runCommands ?? []);+}++/**+ * The mise release the bootstrap installs. Pinned to a tag with its published+ * sha256, because the image scanner rejects an unpinned download-and-execute+ * step, and a moving installer would change what a rebuild produces.+ */+const MISE_VERSION = "v2026.8.10";+/** Published sha256 per architecture, from the release's SHASUMS256.txt. */+const MISE_SHA256 = {+ x64: "e013fe11a0a9055fe78d2546baa85eba90a56e6445c431021b4fe328e6910fe2",+ arm64: "5fd8a9ffb312b47e29f642d377ad4fa9093962b47061ef5c15665086904e1046",+} as const;++/**+ * Puts mise on PATH. The archive holds `mise/bin/mise`, so a wrong layout+ * fails the build loudly rather than leaving a half-installed image.+ */+function miseBootstrapCommand(): string {+ const base = `https://github.com/jdx/mise/releases/download/${MISE_VERSION}/mise-${MISE_VERSION}-linux`;+ const resolveArch = [+ 'case "$(uname -m)" in',+ `x86_64) MISE_ARCH=x64; MISE_SUM=${MISE_SHA256.x64};;`,+ `aarch64|arm64) MISE_ARCH=arm64; MISE_SUM=${MISE_SHA256.arm64};;`,+ '*) echo "mise: unsupported architecture $(uname -m)" >&2; exit 1;;',+ "esac",+ ].join(" ");+ return [+ resolveArch,+ `curl -fsSL -o /tmp/mise.tar.gz ${base}-"$MISE_ARCH".tar.gz`,+ 'echo "$MISE_SUM /tmp/mise.tar.gz" | sha256sum -c -',+ "tar -xzf /tmp/mise.tar.gz -C /tmp",+ "install -m 0755 /tmp/mise/bin/mise /usr/local/bin/mise",+ "rm -rf /tmp/mise /tmp/mise.tar.gz",+ ].join(" && ");+}++/**+ * Installs one tool with mise and links it onto PATH. mise keeps binaries+ * behind shims that a non-interactive shell never activates, so without the+ * link the tool is installed and invisible.+ */+function miseInstallCommand(tool: ImagePresetTool): string {+ const registryName = tool.miseTool ?? tool.id;+ const version = tool.version ?? "latest";+ return [+ `mise use -g -y ${registryName}@${version}`,+ `ln -sf "$(mise which ${tool.command})" /usr/local/bin/${tool.command}`,+ ].join(" && ");+}++/**+ * Every command the tools need, in build order: mise itself first, then the+ * tools it carries, then the packages' own follow-up commands.+ */+function toolCommands(tools: readonly ImagePresetTool[]): string[] {+ const miseTools = tools.filter((tool) => toolInstallMethod(tool) === "mise");+ return [+ ...(miseTools.length > 0 ? [miseBootstrapCommand()] : []),+ ...miseTools.map(miseInstallCommand),+ ...runCommandsFor(tools),+ ];+}++/**+ * The spec for the chosen tools and setup commands. Callers must check+ * `imageSpecError` first; this assumes a valid input.+ */+export function buildImageSpec({+ tools,+ setupCommands,+ repository,+}: ImageSpecInput): ImageSpec {+ const commands = tools.map((tool) => tool.command);+ return {+ apt_packages: [...new Set(aptPackagesFor(tools))],+ run_commands: [...new Set(toolCommands(tools))],+ repo_setup_commands: repository+ ? setupCommands.map((command) => command.trim()).filter(Boolean)+ : [],+ env:+ commands.length > 0+ ? { [IMAGE_TOOLS_ENV_KEY]: [...new Set(commands)].join(" ") }+ : {},+ };+}++/**+ * The spec as the YAML the build endpoint takes. Hand-written rather than via a+ * YAML library: the shape is three string lists, and every value is already+ * validated, so quoting each entry is enough.+ */+export function imageSpecToYaml(spec: ImageSpec): string {+ const lines: string[] = [];+ const block = (+ key: "apt_packages" | "run_commands" | "repo_setup_commands",+ ) => {+ const values = spec[key];+ if (values.length === 0) return;+ lines.push(`${key}:`);+ for (const value of values) {+ lines.push(` - ${quote(value)}`);+ }+ };+ block("apt_packages");+ block("run_commands");+ block("repo_setup_commands");+ const env = Object.entries(spec.env);+ if (env.length > 0) {+ lines.push("env:");+ for (const [key, value] of env) {+ lines.push(` ${key}: ${quote(value)}`);+ }+ }+ return lines.join("\n");+}++/** Single-quoted YAML scalar, which needs only quote doubling. */+function quote(value: string): string {+ return `'${value.replace(/'/g, "''")}'`;+}diff --git a/products/desktop/packages/shared/src/constants.ts b/products/desktop/packages/shared/src/constants.tsindex f34e86c35d9f..177de9baa950 100644--- a/products/desktop/packages/shared/src/constants.ts+++ b/products/desktop/packages/shared/src/constants.ts@@ -9,6 +9,13 @@ export const SELF_DRIVING_SETUP_TASK_FLAG =export const BRANCH_PREFIX = "posthog/";export const POSTHOG_CODE_INTERNAL_CHILD_ENV = "POSTHOG_CODE_INTERNAL_CHILD";+/**+ * Names the tools a custom sandbox image carries. The image spec builder+ * writes it into the image's env; the agent reads it at session start, since+ * nothing else tells it what was installed.+ */+export const IMAGE_TOOLS_ENV_KEY = "POSTHOG_IMAGE_TOOLS";+// Mirrors --color-background (dark) in packages/ui globals.css, for surfaces// that cannot read CSS variables: the Electron window and the boot error screen.export const DARK_APP_BACKGROUND_COLOR = "#131316";