Skip to content

: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.

fix(tasks): show which environment variables a cloud environment holds (#89480)

Alessandro Pogliaghi7250899ee79a
diff --git a/products/desktop/packages/core/src/settings/environmentSetup.test.ts b/products/desktop/packages/core/src/settings/environmentSetup.test.ts
index 60d4c2eac584..c21d423dd92c 100644
--- a/products/desktop/packages/core/src/settings/environmentSetup.test.ts
+++ b/products/desktop/packages/core/src/settings/environmentSetup.test.ts
@@ -10,6 +10,7 @@ import {
planImageInput,
setupSteps,
setupStepsComplete,
+ splitPastedEnvVars,
stepError,
validateDomains,
withEnvironmentName,
@@ -180,6 +181,27 @@ describe("environmentSetup", () => {
]);
});
+ it("keeps a pasted .env usable by leaving out the keys the sandbox manages", () => {
+ const { entries, skipped } = splitPastedEnvVars(
+ [
+ "OPENAI_API_KEY=sk-example",
+ "GITHUB_TOKEN=ghp-example",
+ "GIT_AUTHOR_NAME=Jane",
+ "NODE_OPTIONS=--max-old-space-size=4096",
+ "DATABASE_URL=postgres://example.com/app",
+ ].join("\n"),
+ );
+ expect(entries).toEqual([
+ { key: "OPENAI_API_KEY", value: "sk-example" },
+ { key: "DATABASE_URL", value: "postgres://example.com/app" },
+ ]);
+ expect(skipped).toEqual([
+ "GITHUB_TOKEN",
+ "GIT_AUTHOR_NAME",
+ "NODE_OPTIONS",
+ ]);
+ });
+
it("rejects a malformed or repeated variable name", () => {
const rows = [
{ id: "a", key: "GOOD", value: "1" },
diff --git a/products/desktop/packages/core/src/settings/environmentSetup.ts b/products/desktop/packages/core/src/settings/environmentSetup.ts
index 2083433785d4..deeb2c43cd06 100644
--- a/products/desktop/packages/core/src/settings/environmentSetup.ts
+++ b/products/desktop/packages/core/src/settings/environmentSetup.ts
@@ -346,6 +346,19 @@ const BLOCKED_ENV_VAR_KEYS: ReadonlySet<string> = new Set([
"RUBYOPT",
]);
+/**
+ * Whether the sandbox manages this key itself. It strips these from a user's set
+ * before a session starts, and the API refuses a set that names one.
+ */
+export function isManagedEnvVarKey(key: string): boolean {
+ const trimmed = key.trim();
+ return (
+ RESERVED_ENV_VAR_KEYS.has(trimmed) ||
+ BLOCKED_ENV_VAR_KEYS.has(trimmed) ||
+ BLOCKED_ENV_VAR_PREFIXES.some((prefix) => trimmed.startsWith(prefix))
+ );
+}
+
/** Why one row cannot be sent, or null when it is fine. */
export function envVarError(
row: EnvVarRow,
@@ -399,6 +412,30 @@ export function parseEnvVarText(
return rows;
}
+export interface PastedEnvVars {
+ entries: { key: string; value: string }[];
+ /** Names the sandbox manages, which are left out rather than added. */
+ skipped: string[];
+}
+
+/**
+ * A pasted .env split into what the environment can hold and what it cannot. A
+ * real .env usually carries a few keys the sandbox manages, and adding them as
+ * rows blocks the whole paste over variables the sandbox would drop anyway.
+ */
+export function splitPastedEnvVars(text: string): PastedEnvVars {
+ const entries: { key: string; value: string }[] = [];
+ const skipped: string[] = [];
+ for (const entry of parseEnvVarText(text)) {
+ if (isManagedEnvVarKey(entry.key)) {
+ skipped.push(entry.key);
+ } else {
+ entries.push(entry);
+ }
+ }
+ return { entries, skipped };
+}
+
/** 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() !== "");
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 2aef13623269..b53c3f8c0a0d 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -425,6 +425,12 @@ export interface SandboxEnvironment {
include_default_domains: boolean;
repositories: string[];
has_environment_variables: boolean;
+ /**
+ * Names of the variables that are set. Values are write-only and never returned.
+ * Optional because desktop releases are not orchestrated with backend deploys, so a
+ * client can reach an API that predates this field.
+ */
+ environment_variable_keys?: string[];
private: boolean;
effective_domains: string[];
custom_image_id: string | null;
diff --git a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditForm.tsx b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditForm.tsx
index 84ff5ed513d0..86cfa23773dc 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditForm.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditForm.tsx
@@ -16,7 +16,8 @@ interface EnvironmentEditFormProps {
images: readonly SandboxCustomImage[];
/** The name shown in the heading, which a rename must not change mid-edit. */
environmentName: string;
- variablesAlreadySet: boolean;
+ /** Names of the variables already saved, whose values are never returned. */
+ savedVariableKeys: readonly string[];
saving: boolean;
deleting: boolean;
onCancel: () => void;
@@ -38,7 +39,7 @@ export function EnvironmentEditForm({
onChange,
images,
environmentName,
- variablesAlreadySet,
+ savedVariableKeys,
saving,
deleting,
onCancel,
@@ -86,7 +87,7 @@ export function EnvironmentEditForm({
<AccessStep
plan={plan}
onChange={onChange}
- variablesAlreadySet={variablesAlreadySet}
+ savedVariableKeys={savedVariableKeys}
/>
</Section>
{plan.customImages && (
diff --git a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditPage.tsx b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditPage.tsx
index 4f964795a489..3fce30a45f4c 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditPage.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/EnvironmentEditPage.tsx
@@ -104,7 +104,7 @@ function LoadedEditPage({
onChange={setPlan}
images={images}
environmentName={environment.name}
- variablesAlreadySet={environment.has_environment_variables}
+ savedVariableKeys={environment.environment_variable_keys ?? []}
saving={updateMutation.isPending}
deleting={deleteMutation.isPending}
onCancel={onDone}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/AccessStep.stories.tsx b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/AccessStep.stories.tsx
new file mode 100644
index 000000000000..118344a46ee8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/AccessStep.stories.tsx
@@ -0,0 +1,57 @@
+import {
+ type EnvironmentSetupPlan,
+ emptyEnvironmentSetupPlan,
+} from "@posthog/core/settings/environmentSetup";
+import { AccessStep } from "@posthog/ui/features/settings/sections/environments/setup/steps/AccessStep";
+import type { Meta, StoryObj } from "@storybook/react";
+import { useState } from "react";
+
+/** Stateful wrapper: the step is driven by its plan, so a story has to hold one. */
+function AccessStepStory({
+ initialPlan,
+ savedVariableKeys = [],
+}: {
+ initialPlan: EnvironmentSetupPlan;
+ savedVariableKeys?: string[];
+}) {
+ const [plan, setPlan] = useState(initialPlan);
+ return (
+ <div className="mx-auto max-w-[800px] p-6">
+ <AccessStep
+ plan={plan}
+ onChange={setPlan}
+ savedVariableKeys={savedVariableKeys}
+ />
+ </div>
+ );
+}
+
+const meta: Meta<typeof AccessStepStory> = {
+ title: "Environments/AccessStep",
+ component: AccessStepStory,
+ args: {
+ initialPlan: emptyEnvironmentSetupPlan({ repository: "posthog/posthog" }),
+ },
+};
+
+export default meta;
+
+export const NoVariablesYet: StoryObj<typeof AccessStepStory> = {};
+
+/** An environment that already holds variables, which is what editing one shows. */
+export const VariablesAlreadySaved: StoryObj<typeof AccessStepStory> = {
+ args: {
+ savedVariableKeys: ["ANTHROPIC_API_KEY", "DATABASE_URL", "OPENAI_API_KEY"],
+ },
+};
+
+/** Replacing a saved set, which the rows warn about before it happens. */
+export const ReplacingSavedVariables: StoryObj<typeof AccessStepStory> = {
+ args: {
+ initialPlan: {
+ ...emptyEnvironmentSetupPlan({ repository: "posthog/posthog" }),
+ envVars: [{ id: "a", key: "OPENAI_API_KEY", value: "sk-test" }],
+ },
+ savedVariableKeys: ["ANTHROPIC_API_KEY", "DATABASE_URL", "OPENAI_API_KEY"],
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/AccessStep.tsx b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/AccessStep.tsx
index 7dda33883e9e..6e04448a346d 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/AccessStep.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/AccessStep.tsx
@@ -9,15 +9,15 @@ import { useId } from "react";
interface AccessStepProps {
plan: EnvironmentSetupPlan;
onChange: (plan: EnvironmentSetupPlan) => void;
- /** True when the environment already holds variables that are not shown back. */
- variablesAlreadySet?: boolean;
+ /** Names of the variables the environment already holds; their values are not shown back. */
+ savedVariableKeys?: readonly string[];
}
/** What the sandbox may reach, and what it gets in its shell. */
export function AccessStep({
plan,
onChange,
- variablesAlreadySet = false,
+ savedVariableKeys = [],
}: AccessStepProps) {
const defaultsId = useId();
const domainsId = useId();
@@ -90,12 +90,13 @@ export function AccessStep({
Environment variables
</Label>
<Text className="max-w-[56ch] text-(--gray-10) text-[11.5px] leading-snug">
- {variablesAlreadySet
- ? "Variables are set. They are encrypted and never shown back, so adding any here replaces the whole set, and leaving this empty keeps them."
+ {savedVariableKeys.length > 0
+ ? "The variables below are saved. Values are encrypted and never shown back, so adding one here replaces the whole set, and leaving this alone keeps them."
: "The API keys or tokens the agent needs. They are encrypted, and never shown back once saved."}
</Text>
<EnvVarRows
rows={plan.envVars}
+ savedKeys={savedVariableKeys}
onChange={(envVars) => onChange({ ...plan, envVars })}
/>
</div>
diff --git a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/EnvVarRows.test.tsx b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/EnvVarRows.test.tsx
new file mode 100644
index 000000000000..d30ed7110063
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/EnvVarRows.test.tsx
@@ -0,0 +1,55 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+import { EnvVarRows } from "./EnvVarRows";
+
+describe("EnvVarRows", () => {
+ it("lists the variables already saved instead of reading as empty", () => {
+ render(
+ <EnvVarRows
+ rows={[]}
+ savedKeys={["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByText("ANTHROPIC_API_KEY")).toBeTruthy();
+ expect(screen.getByText("OPENAI_API_KEY")).toBeTruthy();
+ expect(screen.queryByText(/None yet/)).toBeNull();
+ });
+
+ it("says nothing is set only when nothing is", () => {
+ render(<EnvVarRows rows={[]} onChange={() => {}} />);
+ expect(screen.getByText(/None yet/)).toBeTruthy();
+ });
+
+ it("warns that entered rows replace the saved variables", () => {
+ render(
+ <EnvVarRows
+ rows={[{ id: "a", key: "OPENAI_API_KEY", value: "sk-test" }]}
+ savedKeys={["ANTHROPIC_API_KEY"]}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByText(/replaces the variables/)).toBeTruthy();
+ expect(screen.getByText(/ANTHROPIC_API_KEY/)).toBeTruthy();
+ });
+
+ it("adds a pasted .env without the keys the sandbox manages", async () => {
+ const onChange = vi.fn();
+ render(
+ <EnvVarRows
+ rows={[{ id: "a", key: "", value: "" }]}
+ onChange={onChange}
+ />,
+ );
+ await userEvent.click(screen.getByLabelText("Variable 1 name"));
+ await userEvent.paste(
+ "OPENAI_API_KEY=sk-example\nGITHUB_TOKEN=ghp-example",
+ );
+
+ expect(onChange).toHaveBeenCalledWith([
+ { id: expect.any(String), key: "OPENAI_API_KEY", value: "sk-example" },
+ ]);
+ expect(screen.getByText(/GITHUB_TOKEN/)).toBeTruthy();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/EnvVarRows.tsx b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/EnvVarRows.tsx
index 1bd89f664115..3cf70ad7aa7a 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/EnvVarRows.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/environments/setup/steps/EnvVarRows.tsx
@@ -2,13 +2,18 @@ import { Plus, X } from "@phosphor-icons/react";
import {
type EnvVarRow,
envVarError,
- parseEnvVarText,
+ splitPastedEnvVars,
} from "@posthog/core/settings/environmentSetup";
import { Button, Input, Text } from "@posthog/quill";
-import type { ClipboardEvent } from "react";
+import { type ClipboardEvent, type ReactNode, useState } from "react";
interface EnvVarRowsProps {
rows: readonly EnvVarRow[];
+ /**
+ * Names already saved on the environment. Values are never returned, so these
+ * are listed rather than edited, and entering a row replaces all of them.
+ */
+ savedKeys?: readonly string[];
onChange: (rows: EnvVarRow[]) => void;
}
@@ -17,7 +22,12 @@ interface EnvVarRowsProps {
* rows out, since that is how people carry these between machines, and the
* value column masks what it holds because most of them are secrets.
*/
-export function EnvVarRows({ rows, onChange }: EnvVarRowsProps) {
+export function EnvVarRows({
+ rows,
+ savedKeys = [],
+ onChange,
+}: EnvVarRowsProps) {
+ const [skippedOnPaste, setSkippedOnPaste] = useState<string[]>([]);
// Random ids, not row-count ones: a count repeats after delete-then-add,
// and a repeated id makes patch() edit two rows at once.
const nextId = () => crypto.randomUUID();
@@ -30,17 +40,25 @@ export function EnvVarRows({ rows, onChange }: EnvVarRowsProps) {
/**
* A paste that carries variables replaces the row it landed in, so pasting
- * into the first empty row does not leave a blank one behind.
+ * into the first empty row does not leave a blank one behind. Keys the
+ * sandbox manages are reported rather than added, because a row holding one
+ * blocks the save and the sandbox drops it from the set anyway.
*/
const handlePaste = (event: ClipboardEvent, row: EnvVarRow) => {
const text = event.clipboardData.getData("text");
- const parsed = parseEnvVarText(text);
- if (parsed.length === 0) return;
- if (parsed.length === 1 && !text.includes("\n") && row.key.trim() !== "") {
+ const { entries, skipped } = splitPastedEnvVars(text);
+ if (entries.length === 0 && skipped.length === 0) return;
+ if (
+ entries.length === 1 &&
+ skipped.length === 0 &&
+ !text.includes("\n") &&
+ row.key.trim() !== ""
+ ) {
return;
}
event.preventDefault();
- const added = parsed.map((entry) => ({
+ setSkippedOnPaste(skipped);
+ const added = entries.map((entry) => ({
id: nextId(),
...entry,
}));
@@ -51,8 +69,64 @@ export function EnvVarRows({ rows, onChange }: EnvVarRowsProps) {
]);
};
+ const skippedNotice = skippedOnPaste.length > 0 && (
+ <Text className="max-w-[64ch] text-(--gray-11) text-[11.5px] leading-snug">
+ Left out {skippedOnPaste.length}{" "}
+ {skippedOnPaste.length === 1 ? "variable" : "variables"} the sandbox
+ manages: {skippedOnPaste.join(", ")}. Everything else was added.
+ </Text>
+ );
+
+ /** Every branch ends with the paste notice, which outlives the rows it changed. */
+ const wrap = (body: ReactNode) => (
+ <div className="flex flex-col gap-2">
+ {body}
+ {skippedNotice}
+ </div>
+ );
+
+ // Saved names with no rows entered yet is the resting state of an environment
+ // that has variables. Listing them is the only way to tell it apart from one
+ // that has none, since the values never come back from the API.
+ if (rows.length === 0 && savedKeys.length > 0) {
+ return wrap(
+ <div
+ className="flex flex-col gap-2"
+ data-attr="environment-setup-saved-variables"
+ >
+ <ColumnHeadings />
+ {savedKeys.map((key) => (
+ <div key={key} className="flex max-w-[640px] items-center gap-2">
+ <Text className="flex-1 font-mono text-(--gray-12) text-[12px]">
+ {key}
+ </Text>
+ <Text className="flex-1 font-mono text-(--gray-10) text-[12px]">
+ ••••••••
+ </Text>
+ <span className="w-7 shrink-0" />
+ </div>
+ ))}
+ <div className="flex items-center gap-3">
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="environment-setup-add-variable"
+ onClick={addRow}
+ >
+ <Plus size={12} />
+ Add a variable
+ </Button>
+ <Text className="text-(--gray-10) text-[11.5px]">
+ Adding one replaces every variable listed here, so re-enter the ones
+ you want to keep.
+ </Text>
+ </div>
+ </div>,
+ );
+ }
+
if (rows.length === 0) {
- return (
+ return wrap(
<div className="flex flex-col items-start gap-2 rounded-(--radius-3) border border-(--gray-5) border-dashed px-3 py-3">
<Text className="text-(--gray-11) text-[11.5px]">
None yet. Add them one at a time, or paste a .env file into the first
@@ -67,17 +141,13 @@ export function EnvVarRows({ rows, onChange }: EnvVarRowsProps) {
<Plus size={12} />
Add a variable
</Button>
- </div>
+ </div>,
);
}
- return (
+ return wrap(
<div className="flex flex-col gap-2">
- <div className="flex max-w-[640px] items-center gap-2">
- <Text className="flex-1 text-(--gray-10) text-[11px]">Name</Text>
- <Text className="flex-1 text-(--gray-10) text-[11px]">Value</Text>
- <span className="w-7 shrink-0" />
- </div>
+ <ColumnHeadings />
{rows.map((row, index) => {
const error = envVarError(row, rows);
return (
@@ -136,6 +206,23 @@ export function EnvVarRows({ rows, onChange }: EnvVarRowsProps) {
Pasting a .env file fills out the rows.
</Text>
</div>
+ {savedKeys.length > 0 && (
+ <Text className="max-w-[64ch] text-(--amber-11) text-[11.5px] leading-snug">
+ Saving these replaces the variables already on this environment:{" "}
+ {savedKeys.join(", ")}. Remove every row to keep them instead.
+ </Text>
+ )}
+ </div>,
+ );
+}
+
+/** The name and value columns, above both the saved list and the editable rows. */
+function ColumnHeadings() {
+ return (
+ <div className="flex max-w-[640px] items-center gap-2">
+ <Text className="flex-1 text-(--gray-10) text-[11px]">Name</Text>
+ <Text className="flex-1 text-(--gray-10) text-[11px]">Value</Text>
+ <span className="w-7 shrink-0" />
</div>
);
}
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 2c02dea1ca3a..20df2dd86aa9 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -640,6 +640,10 @@ def _task_detail_to_dto(
def _sandbox_env_to_dto(env: SandboxEnvironment) -> contracts.SandboxEnvironmentDTO:
+ # The names are reported back so a caller can tell which variables are set; the values
+ # stay server-side. A value that failed to decrypt comes back as its ciphertext string
+ # rather than a dict, and that is not a variable set, so it reports as none.
+ env_vars = env.environment_variables if isinstance(env.environment_variables, dict) else {}
return contracts.SandboxEnvironmentDTO(
id=env.id,
team_id=env.team_id,
@@ -651,7 +655,8 @@ def _sandbox_env_to_dto(env: SandboxEnvironment) -> contracts.SandboxEnvironment
allowed_domains=list(env.allowed_domains or []),
repositories=list(env.repositories or []),
effective_domains=env.get_effective_domains(),
- has_environment_variables=bool(env.environment_variables),
+ has_environment_variables=bool(env_vars),
+ environment_variable_keys=sorted(env_vars),
created_by=_user_basic_info(env.created_by if env.created_by_id else None),
created_at=env.created_at,
updated_at=env.updated_at,
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index ddddbaf8efee..c9594d0a9b0b 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -731,6 +731,7 @@ class SandboxEnvironmentDTO:
repositories: list[str] = Field(default_factory=list)
effective_domains: list[str] = Field(default_factory=list)
has_environment_variables: bool = False
+ environment_variable_keys: list[str] = Field(default_factory=list)
created_by: TaskUserBasicInfo | None = None
created_at: datetime | None = None
updated_at: datetime | None = None
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index c28cb111b235..411cb44f4d99 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -3814,8 +3814,12 @@ class TaskRunSessionLogsQuerySerializer(serializers.Serializer):
)
+# One serializer for every read. The list used to carry a subset, and because the settings
+# page edits an environment straight off the list, each field missing there read as unset
+# rather than as unfetched: a saved variable set looked empty. Both also generated the same
+# OpenAPI component, so the narrower one is what downstream clients were typed against.
class SandboxEnvironmentSerializer(DataclassSerializer):
- """Detail/create/update response for a sandbox environment."""
+ """A sandbox environment, as returned by list, detail, create and update."""
created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
@@ -3829,6 +3833,7 @@ class SandboxEnvironmentSerializer(DataclassSerializer):
"include_default_domains",
"repositories",
"has_environment_variables",
+ "environment_variable_keys",
"private",
"internal",
"effective_domains",
@@ -3839,30 +3844,16 @@ class SandboxEnvironmentSerializer(DataclassSerializer):
"custom_image_name",
"custom_image_status",
]
-
-
-class SandboxEnvironmentListSerializer(DataclassSerializer):
- """List response for sandbox environments (subset of fields)."""
-
- created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
-
- class Meta:
- dataclass = SandboxEnvironmentDTO
- fields = [
- "id",
- "name",
- "network_access_level",
- "allowed_domains",
- "repositories",
- "private",
- "internal",
- "created_by",
- "created_at",
- "updated_at",
- "custom_image_id",
- "custom_image_name",
- "custom_image_status",
- ]
+ extra_kwargs = {
+ "has_environment_variables": {
+ "help_text": "Whether any environment variables are set on this environment."
+ },
+ "environment_variable_keys": {
+ "help_text": (
+ "Names of the environment variables that are set, sorted. Values are write-only and never returned."
+ )
+ },
+ }
class SandboxEnvironmentWriteSerializer(serializers.Serializer):
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 22ff43402635..5da07b1988da 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -108,7 +108,6 @@ from products.tasks.backend.presentation.serializers import (
SandboxCustomImageSerializer,
SandboxCustomImageUpdateSerializer,
SandboxCustomImageWriteSerializer,
- SandboxEnvironmentListSerializer,
SandboxEnvironmentSerializer,
SandboxEnvironmentWriteSerializer,
SlackThreadContextQuerySerializer,
@@ -3728,13 +3727,13 @@ class SandboxEnvironmentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
http_method_names = ["get", "post", "patch", "delete", "head", "options"]
lookup_value_regex = UUID_LOOKUP_REGEX
- @extend_schema(responses={200: SandboxEnvironmentListSerializer(many=True)})
+ @extend_schema(responses={200: SandboxEnvironmentSerializer(many=True)})
def list(self, request, **kwargs):
envs = tasks_facade.list_sandbox_environments(self.team_id, request.user.id)
page = self.paginate_queryset(envs)
if page is not None:
- return self.get_paginated_response(SandboxEnvironmentListSerializer(page, many=True).data)
- return Response(SandboxEnvironmentListSerializer(envs, many=True).data)
+ return self.get_paginated_response(SandboxEnvironmentSerializer(page, many=True).data)
+ return Response(SandboxEnvironmentSerializer(envs, many=True).data)
@extend_schema(responses={200: SandboxEnvironmentSerializer})
def retrieve(self, request, pk=None, **kwargs):
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index c205cf00fcb6..41138bb6aab4 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -11993,8 +11993,10 @@ class TestSandboxEnvironmentAPI(BaseTaskAPITest):
self.base_url,
{
"name": "Secret Env",
- "network_access_level": "full",
- "environment_variables": {"SECRET_KEY": "supersecret"},
+ "network_access_level": "custom",
+ "allowed_domains": ["example.com"],
+ "include_default_domains": True,
+ "environment_variables": {"SECRET_KEY": "supersecret", "API_TOKEN": "tok"},
},
format="json",
)
@@ -12002,14 +12004,20 @@ class TestSandboxEnvironmentAPI(BaseTaskAPITest):
data = response.json()
self.assertNotIn("environment_variables", data)
self.assertTrue(data["has_environment_variables"])
+ self.assertEqual(data["environment_variable_keys"], ["API_TOKEN", "SECRET_KEY"])
detail = self.client.get(self.detail_url(data["id"])).json()
self.assertNotIn("environment_variables", detail)
self.assertTrue(detail["has_environment_variables"])
+ self.assertEqual(detail["environment_variable_keys"], ["API_TOKEN", "SECRET_KEY"])
- list_data = self.client.get(self.base_url).json()
- for env in list_data["results"]:
- self.assertNotIn("environment_variables", env)
+ # The settings page edits an environment straight off the list, so a list row that
+ # omits these reads as an environment with nothing set however much was saved.
+ listed = next(env for env in self.client.get(self.base_url).json()["results"] if env["id"] == data["id"])
+ self.assertNotIn("environment_variables", listed)
+ self.assertTrue(listed["has_environment_variables"])
+ self.assertEqual(listed["environment_variable_keys"], ["API_TOKEN", "SECRET_KEY"])
+ self.assertTrue(listed["include_default_domains"])
def test_has_environment_variables_false_when_empty(self):
response = self.client.post(
@@ -12019,6 +12027,7 @@ class TestSandboxEnvironmentAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertFalse(response.json()["has_environment_variables"])
+ self.assertEqual(response.json()["environment_variable_keys"], [])
def test_custom_with_defaults_merges_without_duplicates(self):
response = self.client.post(
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index afc69718994f..2178e49d606b 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -849,16 +849,22 @@ export interface SandboxCustomImageBuildApi {
}
/**
- * List response for sandbox environments (subset of fields).
+ * A sandbox environment, as returned by list, detail, create and update.
*/
export interface SandboxEnvironmentDTOApi {
id: string
name: string
network_access_level: string
allowed_domains?: string[]
+ include_default_domains: boolean
repositories?: string[]
+ /** Whether any environment variables are set on this environment. */
+ has_environment_variables?: boolean
+ /** Names of the environment variables that are set, sorted. Values are write-only and never returned. */
+ environment_variable_keys?: string[]
private: boolean
internal: boolean
+ effective_domains?: string[]
created_by?: TaskUserBasicInfoApi | null
/** @nullable */
created_at?: string | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 92a89cf33eef..c90e9055e08c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54700,16 +54700,22 @@ export namespace Schemas {
}
/**
- * List response for sandbox environments (subset of fields).
+ * A sandbox environment, as returned by list, detail, create and update.
*/
export interface SandboxEnvironmentDTO {
id: string;
name: string;
network_access_level: string;
allowed_domains?: string[];
+ include_default_domains: boolean;
repositories?: string[];
+ /** Whether any environment variables are set on this environment. */
+ has_environment_variables?: boolean;
+ /** Names of the environment variables that are set, sorted. Values are write-only and never returned. */
+ environment_variable_keys?: string[];
private: boolean;
internal: boolean;
+ effective_domains?: string[];
created_by?: TaskUserBasicInfo | null;
/** @nullable */
created_at?: string | null;