Skip to content

The open-source app everyone uses to manage agents at work

Redesign environment variables editor (#8930)

Dottab5c914126e8c
diff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsx
index 79e7bd634e..50c812de30 100644
--- a/ui/src/components/AgentConfigForm.render.test.tsx
+++ b/ui/src/components/AgentConfigForm.render.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { createRoot, type Root } from "react-dom/client";
-import { act } from "react";
+import { flushSync } from "react-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Agent, Environment } from "@paperclipai/shared";
@@ -117,6 +117,14 @@ vi.mock("./MarkdownEditor", () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+async function act(callback: () => void | Promise<void>) {
+ let result: void | Promise<void> = undefined;
+ flushSync(() => {
+ result = callback();
+ });
+ await result;
+}
+
async function flushReact() {
await act(async () => {
for (let i = 0; i < 4; i += 1) {
@@ -169,6 +177,12 @@ function makeEnvironment(overrides: Partial<Environment>): Environment {
};
}
+function setInputValue(input: HTMLInputElement, value: string) {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ setter?.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+}
+
async function renderForm(
environments: Environment[],
agentOverrides: Partial<Agent> = {},
@@ -357,6 +371,51 @@ describe("AgentConfigForm environment selector", () => {
});
});
+ it("flushes pending environment variable edits before testing adapter config", async () => {
+ const result = await renderForm([
+ makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
+ ], {
+ adapterConfig: {
+ model: "gpt-5.4",
+ env: { API_TOKEN: { type: "plain", value: "old-token" } },
+ },
+ }, {
+ showAdapterTestEnvironmentButton: true,
+ });
+ roots.push(result.root);
+
+ const valueInput = result.container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]');
+ expect(valueInput).toBeTruthy();
+
+ await act(async () => {
+ setInputValue(valueInput!, "draft-token");
+ });
+ await flushReact();
+
+ const testButton = Array.from(result.container.querySelectorAll("button")).find(
+ (button) => button.textContent?.trim() === "Test",
+ );
+ expect(testButton).toBeTruthy();
+
+ await act(async () => {
+ testButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(mockAgentsApi.testEnvironment).toHaveBeenCalled();
+ for (const call of mockAgentsApi.testEnvironment.mock.calls) {
+ expect(call).toEqual([
+ "company-1",
+ "codex_local",
+ expect.objectContaining({
+ adapterConfig: expect.objectContaining({
+ env: { API_TOKEN: { type: "plain", value: "draft-token" } },
+ }),
+ }),
+ ]);
+ }
+ });
+
it("surfaces request failures instead of converting them into model test checks", async () => {
mockAgentsApi.testEnvironment.mockRejectedValueOnce(new Error("Network unavailable"));
diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx
index 7026078c21..cf9989dfe0 100644
--- a/ui/src/components/AgentConfigForm.tsx
+++ b/ui/src/components/AgentConfigForm.tsx
@@ -47,7 +47,10 @@ import { MarkdownEditor } from "./MarkdownEditor";
import { ChoosePathButton } from "./PathInstructionsModal";
import { OpenCodeLogoIcon } from "./OpenCodeLogoIcon";
import { ReportsToPicker } from "./ReportsToPicker";
-import { EnvVarEditor } from "./EnvVarEditor";
+import {
+ EnvironmentVariablesEditor,
+ type EnvironmentVariablesEditorHandle,
+} from "./environment-variables-editor";
import { shouldShowLegacyWorkingDirectoryField } from "../lib/legacy-agent-config";
import { listAdapterOptions, listVisibleAdapterTypes } from "../adapters/metadata";
import { getAdapterDisplay, getAdapterLabel } from "../adapters/adapter-display-registry";
@@ -208,6 +211,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
const hideInstructionsFile = props.hideInstructionsFile ?? false;
const { selectedCompanyId } = useCompany();
const queryClient = useQueryClient();
+ const environmentVariablesEditorRef = useRef<EnvironmentVariablesEditorHandle | null>(null);
// Sync disabled adapter types from server so dropdown filters them out
const disabledTypes = useDisabledAdaptersSync();
@@ -307,14 +311,29 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
}));
}
+ function flushEnvironmentDraft() {
+ return environmentVariablesEditorRef.current?.flushPendingDraft() ?? null;
+ }
+
/** Build accumulated patch and send to parent */
const handleCancel = useCallback(() => {
setOverlay({ ...emptyOverlay });
}, []);
const handleSave = useCallback(async () => {
- if (isCreate || !isDirty) return;
- await props.onSave(buildAgentUpdatePatch(props.agent, overlay));
+ if (isCreate) return;
+ const flushedEnv = flushEnvironmentDraft();
+ const nextOverlay = flushedEnv
+ ? {
+ ...overlay,
+ adapterConfig: {
+ ...overlay.adapterConfig,
+ env: flushedEnv,
+ },
+ }
+ : overlay;
+ if (!isOverlayDirty(nextOverlay)) return;
+ await props.onSave(buildAgentUpdatePatch(props.agent, nextOverlay));
}, [isCreate, isDirty, overlay, props]);
useEffect(() => {
@@ -531,7 +550,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
return next;
}
- function buildCheapAdapterConfigForTest(): Record<string, unknown> {
+ function buildCheapAdapterConfigForTest(adapterConfigPatch?: Record<string, unknown>): Record<string, unknown> {
const adapterDefaultConfig = asObject(adapterCheapDefault?.adapterConfig);
const createCheapModel = isCreate ? (val!.cheapModel ?? "").trim() : "";
const cheapAdapterConfig = isCreate
@@ -544,12 +563,12 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
...cheapProfileFromAgent.adapterConfig,
...asObject(cheapOverlay?.adapterConfig),
};
- return buildAdapterConfigForTest(cheapAdapterConfig);
+ return buildAdapterConfigForTest({ ...cheapAdapterConfig, ...adapterConfigPatch });
}
- function getCheapModelTestCase(): { model: string; adapterConfig: Record<string, unknown> } | null {
+ function getCheapModelTestCase(adapterConfigPatch?: Record<string, unknown>): { model: string; adapterConfig: Record<string, unknown> } | null {
if (!currentCheapEnabled) return null;
- const adapterConfig = buildCheapAdapterConfigForTest();
+ const adapterConfig = buildCheapAdapterConfigForTest(adapterConfigPatch);
const configModel = typeof adapterConfig.model === "string" ? adapterConfig.model.trim() : "";
const model = configModel || currentCheapModel.trim();
if (!model) return null;
@@ -616,8 +635,10 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
if (!selectedCompanyId) {
throw new Error("Select a company to test adapter environment");
}
+ const flushedEnv = flushEnvironmentDraft();
+ const adapterConfigPatch = flushedEnv ? { env: flushedEnv } : undefined;
const primaryModel = currentModelId.trim() || null;
- const cheapTestCase = getCheapModelTestCase();
+ const cheapTestCase = getCheapModelTestCase(adapterConfigPatch);
const environmentId = currentDefaultEnvironmentId || null;
const testResults: Array<{ label: string; model: string | null; result: AdapterEnvironmentTestResult }> = [
{
@@ -626,7 +647,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
result: await runEnvironmentTestCase(
"Primary model",
primaryModel,
- buildAdapterConfigForTest(),
+ buildAdapterConfigForTest(adapterConfigPatch),
environmentId,
),
},
@@ -1350,7 +1371,8 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
</Field>
<Field label="Environment variables" hint={help.envVars}>
- <EnvVarEditor
+ <EnvironmentVariablesEditor
+ ref={environmentVariablesEditorRef}
value={
isCreate
? ((val!.envBindings ?? EMPTY_ENV) as Record<string, EnvBinding>)
diff --git a/ui/src/components/EnvVarEditor.tsx b/ui/src/components/EnvVarEditor.tsx
deleted file mode 100644
index faabf9db09..0000000000
--- a/ui/src/components/EnvVarEditor.tsx
+++ /dev/null
@@ -1,425 +0,0 @@
-import { useEffect, useRef, useState } from "react";
-import type { CompanySecret, EnvBinding, SecretVersionSelector } from "@paperclipai/shared";
-import { AlertCircle, KeyRound, X } from "lucide-react";
-import { cn } from "../lib/utils";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-
-const inputClass =
- "w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";
-
-// shadcn Select trigger sized to line up with the mono inputs above.
-const selectTriggerClass =
- "h-[34px] min-h-[34px] rounded-md border-border bg-transparent px-2.5 text-sm font-mono shadow-none";
-
-/** Radix Select forbids empty-string item values; use a sentinel for "unset". */
-const SECRET_UNSET = "__unset__";
-
-/** Suggest an env-var-style KEY from a secret name (UPPER_SNAKE). */
-function envKeyFromSecretName(name: string): string {
- return name
- .trim()
- .toUpperCase()
- .replace(/[^A-Z0-9_]+/g, "_")
- .replace(/^_+|_+$/g, "")
- .slice(0, 64);
-}
-
-type Row = {
- key: string;
- source: "plain" | "secret";
- plainValue: string;
- secretId: string;
- version: SecretVersionSelector;
-};
-
-function emptyRow(): Row {
- return { key: "", source: "plain", plainValue: "", secretId: "", version: "latest" };
-}
-
-function toRows(rec: Record<string, EnvBinding> | null | undefined): Row[] {
- if (!rec || typeof rec !== "object") {
- return [emptyRow()];
- }
- const entries = Object.entries(rec).map(([key, binding]) => {
- if (typeof binding === "string") {
- return { key, source: "plain" as const, plainValue: binding, secretId: "", version: "latest" as const };
- }
- if (
- typeof binding === "object" &&
- binding !== null &&
- "type" in binding &&
- (binding as { type?: unknown }).type === "secret_ref"
- ) {
- const record = binding as { secretId?: unknown; version?: unknown };
- const version: SecretVersionSelector = typeof record.version === "number"
- ? record.version
- : "latest";
- return {
- key,
- source: "secret" as const,
- plainValue: "",
- secretId: typeof record.secretId === "string" ? record.secretId : "",
- version,
- };
- }
- if (
- typeof binding === "object" &&
- binding !== null &&
- "type" in binding &&
- (binding as { type?: unknown }).type === "plain"
- ) {
- const record = binding as { value?: unknown };
- return {
- key,
- source: "plain" as const,
- plainValue: typeof record.value === "string" ? record.value : "",
- secretId: "",
- version: "latest" as const,
- };
- }
- return { key, source: "plain" as const, plainValue: "", secretId: "", version: "latest" as const };
- });
- return [...entries, emptyRow()];
-}
-
-export function EnvVarEditor({
- value,
- secrets,
- onCreateSecret,
- onChange,
- recentlyUsedSecrets,
-}: {
- value: Record<string, EnvBinding>;
- secrets: CompanySecret[];
- onCreateSecret: (name: string, value: string) => Promise<CompanySecret>;
- onChange: (env: Record<string, EnvBinding> | undefined) => void;
- /**
- * Optional project-scoped secrets to surface as one-tap "quick bind" chips
- * below the editor (§3.4). Already-bound secrets are filtered out.
- */
- recentlyUsedSecrets?: CompanySecret[];
-}) {
- const [rows, setRows] = useState<Row[]>(() => toRows(value));
- const [sealError, setSealError] = useState<string | null>(null);
- const valueRef = useRef(value);
- const emittingRef = useRef(false);
-
- useEffect(() => {
- if (emittingRef.current) {
- emittingRef.current = false;
- valueRef.current = value;
- return;
- }
- if (value !== valueRef.current) {
- valueRef.current = value;
- setRows(toRows(value));
- }
- }, [value]);
-
- function emit(nextRows: Row[]) {
- const rec: Record<string, EnvBinding> = {};
- for (const row of nextRows) {
- const key = row.key.trim();
- if (!key) continue;
- if (row.source === "secret") {
- if (row.secretId) {
- rec[key] = { type: "secret_ref", secretId: row.secretId, version: row.version };
- } else {
- rec[key] = { type: "plain", value: row.plainValue };
- }
- } else {
- rec[key] = { type: "plain", value: row.plainValue };
- }
- }
- emittingRef.current = true;
- onChange(Object.keys(rec).length > 0 ? rec : undefined);
- }
-
- function updateRow(index: number, patch: Partial<Row>) {
- const withPatch: Row[] = rows.map((row, rowIndex) =>
- rowIndex === index ? { ...row, ...patch, version: patch.version ?? row.version } : row,
- );
- if (
- withPatch[withPatch.length - 1].key ||
- withPatch[withPatch.length - 1].plainValue ||
- withPatch[withPatch.length - 1].secretId
- ) {
- withPatch.push(emptyRow());
- }
- setRows(withPatch);
- emit(withPatch);
- }
-
- function removeRow(index: number) {
- const next = rows.filter((_, rowIndex) => rowIndex !== index);
- if (
- next.length === 0 ||
- next[next.length - 1].key ||
- next[next.length - 1].plainValue ||
- next[next.length - 1].secretId
- ) {
- next.push(emptyRow());
- }
- setRows(next);
- emit(next);
- }
-
- function bindRecentSecret(secret: CompanySecret) {
- // Fill the trailing empty row (or append one) with this secret bound.
- const next = rows.map((row) => ({ ...row }));
- const trailing = next[next.length - 1];
- let target: Row;
- if (trailing && !trailing.key && !trailing.plainValue && !trailing.secretId) {
- target = trailing;
- } else {
- target = emptyRow();
- next.push(target);
- }
- target.source = "secret";
- target.secretId = secret.id;
- target.version = "latest";
- if (!target.key) target.key = envKeyFromSecretName(secret.name);
- next.push(emptyRow());
- setRows(next);
- emit(next);
- }
-
- function defaultSecretName(key: string) {
- return key
- .trim()
- .toLowerCase()
- .replace(/[^a-z0-9_]+/g, "_")
- .replace(/^_+|_+$/g, "")
- .slice(0, 64);
- }
-
- async function sealRow(index: number) {
- const row = rows[index];
- if (!row) return;
- const key = row.key.trim();
- const plain = row.plainValue;
- if (!key || plain.length === 0) return;
-
- const suggested = defaultSecretName(key) || "secret";
- const name = window.prompt("Secret name", suggested)?.trim();
- if (!name) return;
-
- try {
- setSealError(null);
- const created = await onCreateSecret(name, plain);
- updateRow(index, { source: "secret", secretId: created.id });
- } catch (error) {
- setSealError(error instanceof Error ? error.message : "Failed to create secret");
- }
- }
-
- return (
- <div className="space-y-1.5">
- {rows.map((row, index) => {
- const isTrailing =
- index === rows.length - 1 &&
- !row.key &&
- !row.plainValue &&
- !row.secretId;
- return (
- <div key={index} className="flex items-center gap-1.5">
- <input
- className={cn(inputClass, "flex-[2]")}
- placeholder="KEY"
- value={row.key}
- onChange={(event) => updateRow(index, { key: event.target.value })}
- />
- <Select
- value={row.source}
- onValueChange={(next) =>
- updateRow(index, {
- source: next === "secret" ? "secret" : "plain",
- ...(next === "plain" ? { secretId: "" } : {}),
- })
- }
- >
- <SelectTrigger className={cn(selectTriggerClass, "flex-[1]")} aria-label="Binding mode">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="plain">Plain</SelectItem>
- <SelectItem value="secret">Secret</SelectItem>
- </SelectContent>
- </Select>
- {row.source === "secret" ? (
- <>
- <Select
- value={row.secretId || SECRET_UNSET}
- onValueChange={(next) =>
- updateRow(index, { secretId: next === SECRET_UNSET ? "" : next })
- }
- >
- <SelectTrigger
- aria-label="Secret"
- className={cn(
- selectTriggerClass,
- "flex-[3]",
- row.secretId &&
- !secrets.some((s) => s.id === row.secretId) &&
- "border-destructive text-destructive",
- )}
- >
- <SelectValue placeholder="Select secret..." />
- </SelectTrigger>
- <SelectContent>
- {row.secretId && !secrets.some((s) => s.id === row.secretId) ? (
- <SelectItem value={row.secretId}>
- Missing ({row.secretId.slice(0, 8)}…)
- </SelectItem>
- ) : null}
- {secrets.map((secret) => (
- <SelectItem key={secret.id} value={secret.id}>
- {secret.name}
- {secret.status !== "active" ? ` (${secret.status})` : ""}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Select
- value={row.version === "latest" ? "latest" : String(row.version)}
- onValueChange={(raw) =>
- updateRow(index, {
- version: raw === "latest" ? "latest" : Number.parseInt(raw, 10),
- })
- }
- disabled={!row.secretId}
- >
- <SelectTrigger className={cn(selectTriggerClass, "flex-[1]")} aria-label="Version">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="latest">latest</SelectItem>
- {(() => {
- const selected = secrets.find((s) => s.id === row.secretId);
- if (!selected) return null;
- return Array.from({ length: Math.max(0, selected.latestVersion) }, (_, idx) => {
- const version = selected.latestVersion - idx;
- if (version <= 0) return null;
- return (
- <SelectItem key={version} value={String(version)}>
- v{version}
- </SelectItem>
- );
- });
- })()}
- </SelectContent>
- </Select>
- <button
- type="button"
- className="inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0"
- onClick={() => sealRow(index)}
- disabled={!row.key.trim() || !row.plainValue}
- title="Create secret from current plain value"
- >
- New
- </button>
- </>
- ) : (
- <>
- <input
- className={cn(inputClass, "flex-[3]")}
- placeholder="value"
- value={row.plainValue}
- onChange={(event) => updateRow(index, { plainValue: event.target.value })}
- />
- <button
- type="button"
- className="inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0"
- onClick={() => sealRow(index)}
- disabled={!row.key.trim() || !row.plainValue}
- title="Store value as secret and replace with reference"
- >
- Seal
- </button>
- </>
- )}
- {!isTrailing ? (
- <button
- type="button"
- className="shrink-0 p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
- onClick={() => removeRow(index)}
- >
- <X className="h-3.5 w-3.5" />
- </button>
- ) : (
- <div className="w-[26px] shrink-0" />
- )}
- </div>
- );
- })}
- {(() => {
- const boundIds = new Set(
- rows.filter((row) => row.source === "secret" && row.secretId).map((row) => row.secretId),
- );
- const quick = (recentlyUsedSecrets ?? [])
- .filter((secret) => secret.status === "active" && !boundIds.has(secret.id))
- .slice(0, 8);
- if (quick.length === 0) return null;
- return (
- <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
- <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground/70">
- <KeyRound className="h-3 w-3" />
- Recently used:
- </span>
- {quick.map((secret) => (
- <button
- key={secret.id}
- type="button"
- onClick={() => bindRecentSecret(secret)}
- className="inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-[11px] text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
- title={`Bind ${secret.name}`}
- >
- + {secret.name}
- </button>
- ))}
- </div>
- );
- })()}
- {sealError && <p className="text-[11px] text-destructive">{sealError}</p>}
- {(() => {
- const issues: { key: string; reason: string }[] = [];
- for (const row of rows) {
- if (row.source !== "secret" || !row.secretId) continue;
- const secret = secrets.find((s) => s.id === row.secretId);
- if (!secret) {
- issues.push({ key: row.key.trim() || row.secretId, reason: "missing" });
- } else if (secret.status !== "active") {
- issues.push({ key: row.key.trim() || secret.name, reason: secret.status });
- }
- }
- if (!issues.length) return null;
- return (
- <p className="text-[11px] text-amber-700 dark:text-amber-400 inline-flex items-start gap-1">
- <AlertCircle className="h-3 w-3 mt-0.5 shrink-0" />
- <span>
- {issues.length} secret binding{issues.length === 1 ? "" : "s"} need attention:{" "}
- {issues.map((issue, idx) => (
- <span key={idx} className="font-mono">
- {issue.key}
- <span className="text-muted-foreground"> ({issue.reason})</span>
- {idx < issues.length - 1 ? ", " : ""}
- </span>
- ))}
- . Runs will fail until you remap or re-enable.
- </span>
- </p>
- );
- })()}
- <p className="text-[11px] text-muted-foreground/60">
- Set KEY to the env var name the process expects, for example GH_TOKEN. Choose Secret to resolve a stored
- value at run start. PAPERCLIP_* variables are injected automatically.
- </p>
- </div>
- );
-}
diff --git a/ui/src/components/ProjectProperties.tsx b/ui/src/components/ProjectProperties.tsx
index b2d159e7db..e1bb32ca4a 100644
--- a/ui/src/components/ProjectProperties.tsx
+++ b/ui/src/components/ProjectProperties.tsx
@@ -21,7 +21,7 @@ import { ChoosePathButton } from "./PathInstructionsModal";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { DraftInput } from "./agent-config-primitives";
import { InlineEditor } from "./InlineEditor";
-import { EnvVarEditor } from "./EnvVarEditor";
+import { EnvironmentVariablesEditor } from "./environment-variables-editor";
const PROJECT_STATUSES = [
{ value: "backlog", label: "Backlog" },
@@ -623,7 +623,7 @@ export function ProjectProperties({ project, onUpdate, onFieldUpdate, getFieldSa
valueClassName="space-y-2"
>
<div className="space-y-2">
- <EnvVarEditor
+ <EnvironmentVariablesEditor
value={project.env ?? {}}
secrets={availableSecrets}
onCreateSecret={async (name, value) => {
diff --git a/ui/src/components/SearchableSelect.tsx b/ui/src/components/SearchableSelect.tsx
index d4a29fdcd0..a827f5cbde 100644
--- a/ui/src/components/SearchableSelect.tsx
+++ b/ui/src/components/SearchableSelect.tsx
@@ -17,6 +17,7 @@ export interface SearchableSelectOption<TValue extends string = string> {
key: string;
value: TValue;
label: string;
+ title?: string;
searchText?: string;
disabled?: boolean;
}
@@ -37,7 +38,7 @@ export interface SearchableSelectProps<
> {
value: TValue | "";
groups: readonly SearchableSelectGroup<TValue, TOption>[];
- onValueChange: (value: TValue, option: TOption) => void;
+ onValueChange: (value: TValue, option: TOption) => void | boolean | { close?: boolean };
placeholder: string;
searchPlaceholder?: string;
emptyMessage?: string;
@@ -51,9 +52,24 @@ export interface SearchableSelectProps<
contentWidth?: "trigger" | "auto";
renderValue?: (option: TOption | null) => ReactNode;
renderOption?: (option: TOption, state: SearchableSelectRenderState) => ReactNode;
+ deriveGroups?: (
+ query: string,
+ groups: readonly SearchableSelectGroup<TValue, TOption>[],
+ ) => readonly SearchableSelectGroup<TValue, TOption>[];
filterOption?: (option: TOption, query: string) => boolean;
scoreOption?: (option: TOption, query: string) => number | null;
disablePortal?: boolean;
+ /**
+ * Optional pinned "creatable" item rendered at the bottom of the list,
+ * regardless of the query (used e.g. by the secret picker's
+ * `+ Create secret "<query>"…` affordance). `render` receives the live
+ * query so the label can echo it; `onSelect` fires with the query and the
+ * popover closes.
+ */
+ createItem?: {
+ render: (query: string) => ReactNode;
+ onSelect: (query: string) => void;
+ };
}
function defaultFilterOption(option: SearchableSelectOption, query: string) {
@@ -87,9 +103,11 @@ export function SearchableSelect<
contentWidth = "trigger",
renderValue,
renderOption,
+ deriveGroups,
filterOption = defaultFilterOption,
scoreOption,
disablePortal,
+ createItem,
}: SearchableSelectProps<TValue, TOption>) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
@@ -104,10 +122,15 @@ export function SearchableSelect<
return null;
}, [groups, value]);
+ const visibleGroups = useMemo(
+ () => (deriveGroups ? deriveGroups(query, groups) : groups),
+ [deriveGroups, groups, query],
+ );
+
const filteredGroups = useMemo(() => {
if (loading) return [];
const normalizedQuery = normalizeSearchText(query);
- return groups
+ return visibleGroups
.map((group) => {
const options = group.options
.map((option, index) => {
@@ -138,7 +161,7 @@ export function SearchableSelect<
};
})
.filter((group) => group.options.length > 0);
- }, [filterOption, groups, loading, query, scoreOption]);
+ }, [filterOption, loading, query, scoreOption, visibleGroups]);
const hasOptions = filteredGroups.some((group) => group.options.length > 0);
@@ -153,7 +176,10 @@ export function SearchableSelect<
function selectOption(option: TOption) {
if (option.disabled) return;
suppressNextTriggerFocusRef.current = true;
- onValueChange(option.value, option);
+ const result = onValueChange(option.value, option);
+ if (result === false || (typeof result === "object" && result?.close === false)) {
+ return;
+ }
closePopover();
}
@@ -192,7 +218,7 @@ export function SearchableSelect<
role="combobox"
className={cn("w-full justify-between overflow-hidden", className, triggerClassName)}
>
- <span className={cn("min-w-0 truncate", !selectedOption && "text-muted-foreground")}>
+ <span className={cn("min-w-0 flex-1 truncate text-left", !selectedOption && "text-muted-foreground")}>
{renderValue ? renderValue(selectedOption) : selectedOption?.label ?? placeholder}
</span>
<ChevronsUpDown className="ml-2 size-4 opacity-50" />
@@ -233,29 +259,54 @@ export function SearchableSelect<
>
{loading ? (
<div className="px-3 py-6 text-center text-sm text-muted-foreground">{loadingMessage}</div>
- ) : !hasOptions ? (
- <CommandEmpty>{emptyMessage}</CommandEmpty>
) : (
- filteredGroups.map((group) => (
- <CommandGroup key={group.id} heading={group.label}>
- {group.options.map((option) => {
- const selected = option.value === value;
- return (
- <CommandItem
- key={option.key}
- value={option.key}
- disabled={option.disabled}
- onSelect={() => selectOption(option)}
- >
- {renderOption
- ? renderOption(option, { selected })
- : <span className="min-w-0 truncate">{option.label}</span>}
- <Check className={cn("ml-auto size-4", selected ? "opacity-100" : "opacity-0")} />
- </CommandItem>
- );
- })}
- </CommandGroup>
- ))
+ <>
+ {!hasOptions && !createItem ? <CommandEmpty>{emptyMessage}</CommandEmpty> : null}
+ {!hasOptions && createItem ? (
+ <div className="px-3 py-3 text-center text-xs text-muted-foreground">{emptyMessage}</div>
+ ) : null}
+ {filteredGroups.map((group) => (
+ <CommandGroup key={group.id} heading={group.label}>
+ {group.options.map((option) => {
+ const selected = option.value === value;
+ return (
+ <CommandItem
+ key={option.key}
+ value={option.key}
+ disabled={option.disabled}
+ onSelect={() => selectOption(option)}
+ >
+ {renderOption
+ ? renderOption(option, { selected })
+ : <span className="min-w-0 truncate">{option.label}</span>}
+ <Check className={cn("ml-auto size-4", selected ? "opacity-100" : "opacity-0")} />
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ ))}
+ {createItem ? (
+ <CommandGroup className="border-t border-border">
+ <CommandItem
+ value="__searchable_select_create__"
+ onSelect={() => {
+ const q = query;
+ suppressNextTriggerFocusRef.current = true;
+ closePopover();
+ // Defer to the next macrotask so this popover fully
+ // closes (and Radix returns focus to the trigger)
+ // before the consumer opens its own popover. Firing
+ // synchronously lets the close's focus-return land as a
+ // `focusOutside` on the newly-opened popover, which
+ // Radix would immediately dismiss (see PAP-12476).
+ window.setTimeout(() => createItem.onSelect(q), 0);
+ }}
+ >
+ {createItem.render(query)}
+ </CommandItem>
+ </CommandGroup>
+ ) : null}
+ </>
)}
</CommandList>
</Command>
diff --git a/ui/src/components/StageSecretsPanel.tsx b/ui/src/components/StageSecretsPanel.tsx
index 9adf07d010..c34ee918db 100644
--- a/ui/src/components/StageSecretsPanel.tsx
+++ b/ui/src/components/StageSecretsPanel.tsx
@@ -2,7 +2,7 @@ import { KeyRound, Save } from "lucide-react";
import type { CompanySecret, RoutineEnvConfig } from "@paperclipai/shared";
import { Button } from "@/components/ui/button";
import { EmptyState } from "./EmptyState";
-import { EnvVarEditor } from "./EnvVarEditor";
+import { EnvironmentVariablesEditor } from "./environment-variables-editor";
import { AgentIcon } from "./AgentIconPicker";
export interface StageSecretsPanelProps {
@@ -28,8 +28,8 @@ export interface StageSecretsPanelProps {
* Stage Secrets tab body. Stage secrets are env bindings on the step's backing
* automation routine — the same company-secret backbone used by routines,
* agents, and projects. This panel is intentionally dense and reuses
- * `EnvVarEditor` for secret refs, inline secret creation, version selection,
- * and missing/disabled-secret warnings.
+ * `EnvironmentVariablesEditor` for secret refs, inline secret creation, version
+ * selection, and missing/disabled-secret warnings.
*/
export function StageSecretsPanel({
hasAutomation,
@@ -80,7 +80,7 @@ export function StageSecretsPanel({
{secretsLoading ? (
<p className="text-sm text-muted-foreground">Loading secrets…</p>
) : (
- <EnvVarEditor
+ <EnvironmentVariablesEditor
value={value}
secrets={secrets}
onCreateSecret={onCreateSecret}
diff --git a/ui/src/components/environment-variables-editor/ConvertToSecretPopover.tsx b/ui/src/components/environment-variables-editor/ConvertToSecretPopover.tsx
new file mode 100644
index 0000000000..4591d8143c
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/ConvertToSecretPopover.tsx
@@ -0,0 +1,4 @@
+// The "Store as secret" (convert) flow shares its form with the create flow;
+// both live in CreateSecretPopover.tsx. Re-exported here so the module keeps a
+// dedicated entry point for the convert popover (plan §4 file list).
+export { ConvertToSecretPopover } from "./CreateSecretPopover";
diff --git a/ui/src/components/environment-variables-editor/CreateSecretPopover.tsx b/ui/src/components/environment-variables-editor/CreateSecretPopover.tsx
new file mode 100644
index 0000000000..021362ee16
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/CreateSecretPopover.tsx
@@ -0,0 +1,156 @@
+import { useState } from "react";
+import { Eye, EyeOff, Loader2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { PopoverTitle, PopoverDescription } from "@/components/ui/popover";
+
+const SECRET_NAME_RE = /^[a-z][a-z0-9_]*$/;
+
+const fieldClass =
+ "w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/40";
+
+export interface SecretPopoverFormProps {
+ /** Popover heading / body copy differ between the two flows. */
+ mode: "create" | "store";
+ initialName: string;
+ /** The plaintext value being stored. Editable (create) or read-only (store). */
+ initialValue: string;
+ /** For a same-name uniqueness hint before the server round-trips. */
+ existingSecretNames?: readonly string[];
+ onCancel: () => void;
+ /** Resolves once the secret is created + the row is bound; rejects with a message. */
+ onSubmit: (name: string, value: string) => Promise<void>;
+}
+
+/**
+ * Shared anchored-popover form behind {@link CreateSecretPopover} and
+ * {@link ConvertToSecretPopover}. Replaces the old `window.prompt` seal flow
+ * (plan §6.5). Meant to be rendered inside a `<PopoverContent>`.
+ */
+export function SecretPopoverForm({
+ mode,
+ initialName,
+ initialValue,
+ existingSecretNames,
+ onCancel,
+ onSubmit,
+}: SecretPopoverFormProps) {
+ const [name, setName] = useState(initialName);
+ const [value, setValue] = useState(initialValue);
+ const [reveal, setReveal] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [touched, setTouched] = useState(false);
+
+ const trimmedName = name.trim();
+ const nameError = (() => {
+ if (!trimmedName) return touched ? "Name is required" : null;
+ if (!SECRET_NAME_RE.test(trimmedName)) return "Use lowercase letters, digits and _";
+ if (existingSecretNames?.some((existing) => existing.toLowerCase() === trimmedName)) {
+ return "A secret with this name already exists";
+ }
+ return null;
+ })();
+ const valueError = value.length === 0 ? (touched ? "Value is required" : null) : null;
+ const canSubmit = !submitting && trimmedName.length > 0 && value.length > 0 && !nameError;
+
+ async function handleSubmit() {
+ setTouched(true);
+ if (!canSubmit) return;
+ setSubmitting(true);
+ setError(null);
+ try {
+ await onSubmit(trimmedName, value);
+ } catch (submitError) {
+ setError(submitError instanceof Error ? submitError.message : "Failed to create secret");
+ setSubmitting(false);
+ }
+ }
+
+ const ctaLabel = mode === "create" ? "Create & bind" : "Store & bind";
+ const heading = mode === "create" ? "Create secret" : "Store value as secret";
+
+ return (
+ <div className="w-72 space-y-3">
+ <div className="space-y-1">
+ <PopoverTitle className="text-sm font-medium">{heading}</PopoverTitle>
+ {mode === "store" ? (
+ <PopoverDescription className="text-[11px] text-muted-foreground">
+ Moves the typed value into an encrypted company secret and binds{" "}
+ <span className="font-mono">{initialName || "this variable"}</span> to it.
+ </PopoverDescription>
+ ) : null}
+ </div>
+
+ <label className="block space-y-1">
+ <span className="text-[11px] font-medium text-muted-foreground">Name</span>
+ <input
+ className={cn(fieldClass, nameError && "border-destructive focus-visible:ring-destructive/40")}
+ value={name}
+ autoFocus
+ spellCheck={false}
+ placeholder="secret_name"
+ aria-label="Secret name"
+ aria-invalid={nameError ? true : undefined}
+ onChange={(event) => setName(event.target.value)}
+ onBlur={() => setTouched(true)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void handleSubmit();
+ }
+ }}
+ />
+ {nameError ? <span className="block text-[11px] text-destructive">{nameError}</span> : null}
+ </label>
+
+ <label className="block space-y-1">
+ <span className="text-[11px] font-medium text-muted-foreground">Value</span>
+ <div className="relative">
+ <input
+ className={cn(fieldClass, "pr-8", valueError && "border-destructive focus-visible:ring-destructive/40")}
+ type={reveal ? "text" : "password"}
+ value={value}
+ readOnly={mode === "store"}
+ spellCheck={false}
+ placeholder={mode === "create" ? "value" : undefined}
+ aria-label="Secret value"
+ aria-invalid={valueError ? true : undefined}
+ onChange={mode === "create" ? (event) => setValue(event.target.value) : undefined}
+ />
+ <button
+ type="button"
+ className="absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground"
+ aria-label={reveal ? "Hide value" : "Show value"}
+ onClick={() => setReveal((prev) => !prev)}
+ >
+ {reveal ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ {valueError ? <span className="block text-[11px] text-destructive">{valueError}</span> : null}
+ </label>
+
+ {error ? <p className="text-[11px] text-destructive">{error}</p> : null}
+
+ <div className="flex items-center justify-end gap-2 pt-0.5">
+ <Button type="button" variant="ghost" size="sm" onClick={onCancel} disabled={submitting}>
+ Cancel
+ </Button>
+ <Button type="button" size="sm" onClick={() => void handleSubmit()} disabled={!canSubmit}>
+ {submitting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}
+ {ctaLabel}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/** Create a brand-new secret from the fuzzy picker's creatable item (§6.4/§6.5). */
+export function CreateSecretPopover(props: Omit<SecretPopoverFormProps, "mode">) {
+ return <SecretPopoverForm mode="create" {...props} />;
+}
+
+/** Store a typed Text value as a secret and bind the row (replaces "Seal", §6.5). */
+export function ConvertToSecretPopover(props: Omit<SecretPopoverFormProps, "mode">) {
+ return <SecretPopoverForm mode="store" {...props} />;
+}
diff --git a/ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx b/ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
new file mode 100644
index 0000000000..8518ae86cf
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
@@ -0,0 +1,859 @@
+// @vitest-environment jsdom
+
+import { useState } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type { CompanySecret, EnvBinding } from "@paperclipai/shared";
+import { EnvironmentVariablesEditor } from "./index";
+import { SecretPicker } from "./SecretPicker";
+
+// Radix (DropdownMenu/Popover) relies on Pointer Capture APIs that jsdom omits.
+const OriginalPointerEvent = globalThis.PointerEvent;
+beforeAll(() => {
+ if (!globalThis.PointerEvent) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ globalThis.PointerEvent = MouseEvent as any;
+ }
+ Element.prototype.setPointerCapture ??= () => {};
+ Element.prototype.releasePointerCapture ??= () => {};
+ Element.prototype.hasPointerCapture ??= () => false;
+ if (!globalThis.ResizeObserver) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ globalThis.ResizeObserver = class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any;
+ }
+});
+afterAll(() => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ globalThis.PointerEvent = OriginalPointerEvent as any;
+});
+
+function makeSecret(id: string, overrides: Partial<CompanySecret> = {}): CompanySecret {
+ return {
+ id,
+ companyId: "co",
+ key: id,
+ name: id.toUpperCase(),
+ provider: "local_encrypted",
+ status: "active",
+ managedMode: "paperclip_managed",
+ externalRef: null,
+ providerConfigId: null,
+ providerMetadata: null,
+ latestVersion: 3,
+ description: null,
+ lastResolvedAt: null,
+ lastRotatedAt: null,
+ deletedAt: null,
+ createdByAgentId: null,
+ createdByUserId: null,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ ...overrides,
+ };
+}
+
+async function flush() {
+ for (let i = 0; i < 5; i += 1) {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ }
+ flushSync(() => {});
+}
+
+// Radix DropdownMenu opens/selects on the pointerdown→pointerup sequence, not a
+// bare click; drive both so jsdom exercises the real dismissal-layer path.
+function pointerClick(el: Element) {
+ el.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, button: 0 }));
+ el.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, cancelable: true, button: 0 }));
+ (el as HTMLElement).click();
+}
+
+// Deterministic settle for the nested DropdownMenu/combobox → Popover deferred-
+// open regression tests. Those flows open the anchored popover from inside a
+// closing menu via `window.setTimeout(…, 0)` (PAP-12476/12477/12478). Under real
+// timers, jsdom orders the menu's focus-return (a `focusin` that Radix reads as
+// `focusOutside` → dismiss) against that deferred open non-deterministically, so
+// the popover *sometimes* opens-then-instantly-closes — flaky. `vi.useFakeTimers`
+// makes that ordering deterministic (matching the real-browser path where the
+// focus-return settles before the macrotask), while still running the deferred
+// `setTimeout` — so a *synchronous* (unfixed) open would still be dismissed here.
+function settleFakeTimers() {
+ flushSync(() => {});
+ vi.runAllTimers();
+ flushSync(() => {});
+}
+
+describe("EnvironmentVariablesEditor", () => {
+ let container: HTMLDivElement;
+ let root: Root | null = null;
+
+ function render(node: React.ReactNode) {
+ root = createRoot(container);
+ flushSync(() => root!.render(node));
+ }
+
+ function rerender(node: React.ReactNode) {
+ flushSync(() => root!.render(node));
+ }
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(async () => {
+ // Restore real timers first (the PAP-12478 test swaps in fake timers and may
+ // exit without restoring if it throws) so unmount cleanup runs on real timers
+ // and gets drained below.
+ vi.useRealTimers();
+ if (document.activeElement instanceof HTMLElement) {
+ document.activeElement.blur();
+ }
+ flushSync(() => root?.unmount());
+ root = null;
+ container.remove();
+ // Drain any pending macrotasks (deferred popover-open timers, Radix's
+ // focus-restoration timers) so a timer scheduled by this test can't fire
+ // mid-way through the next one and dismiss its freshly-opened popover — that
+ // cross-test leak is what made the real-timer sibling regression tests flaky.
+ await flush();
+ for (const child of [...document.body.children]) {
+ child.remove();
+ }
+ document.body.style.pointerEvents = "";
+ vi.restoreAllMocks();
+ });
+
+ const secrets = [makeSecret("s1", { name: "GITHUB_TOKEN", latestVersion: 3 })];
+
+ function nameInputs() {
+ return [...container.querySelectorAll<HTMLInputElement>('input[aria-label="Variable name"]')];
+ }
+
+ function saveButton() {
+ return [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "Save")!;
+ }
+
+ it("renders header + a row per binding, no trailing ghost row", () => {
+ render(
+ <EnvironmentVariablesEditor
+ value={{
+ NODE_ENV: { type: "plain", value: "production" },
+ GH: { type: "secret_ref", secretId: "s1", version: 2 },
+ }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ expect(nameInputs()).toHaveLength(2);
+ expect(container.textContent).toContain("Name");
+ expect(container.textContent).toContain("Value");
+ // Version tag reflects the actual bound version (not a static "latest").
+ const versionTag = container.querySelector('button[aria-label="Version"]');
+ expect(versionTag?.textContent).toBe("v2");
+ });
+
+ it("keeps long secret names clear of the latest version control", () => {
+ const longSecret = makeSecret("long", {
+ name: "/paperclip-cloud/prod/provider/resend/api-key-with-a-very-long-name",
+ latestVersion: 4,
+ });
+
+ render(
+ <EnvironmentVariablesEditor
+ value={{
+ RESEND_API_KEY: { type: "secret_ref", secretId: "long", version: "latest" },
+ }}
+ secrets={[longSecret]}
+ onChange={() => {}}
+ onCreateSecret={async () => longSecret}
+ />,
+ );
+
+ const combobox = container.querySelector<HTMLElement>('[role="combobox"]')!;
+ const selectedLabel = combobox.querySelector<HTMLElement>("[title] span.truncate");
+ const versionTag = container.querySelector<HTMLButtonElement>('button[aria-label="Version"]')!;
+
+ expect(versionTag.textContent).toBe("latest");
+ expect(combobox.className).toContain("has-[>svg]:!pr-24");
+ expect(selectedLabel?.textContent).toBe(longSecret.name);
+ expect(selectedLabel?.className).toContain("flex-1");
+ });
+
+ it("shows the empty state with no bindings", () => {
+ render(<EnvironmentVariablesEditor value={{}} secrets={secrets} onChange={() => {}} onCreateSecret={async () => secrets[0]} />);
+ expect(container.textContent).toContain("No environment variables");
+ expect(nameInputs()).toHaveLength(0);
+ });
+
+ it("appends a row when + Add variable is clicked", async () => {
+ render(<EnvironmentVariablesEditor value={{}} secrets={secrets} onChange={() => {}} onCreateSecret={async () => secrets[0]} />);
+ const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
+ addButton.click();
+ await flush();
+ expect(nameInputs()).toHaveLength(1);
+ });
+
+ it("does not emit when + Add variable only creates an empty draft row", async () => {
+ const onChange = vi.fn();
+ render(<EnvironmentVariablesEditor value={{}} secrets={secrets} onChange={onChange} onCreateSecret={async () => secrets[0]} />);
+ const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
+ addButton.click();
+ await flush();
+ expect(nameInputs()).toHaveLength(1);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("saves plain bindings only when Save is clicked", async () => {
+ const onChange = vi.fn();
+ render(<EnvironmentVariablesEditor value={{ FOO: { type: "plain", value: "" } }} secrets={secrets} onChange={onChange} onCreateSecret={async () => secrets[0]} />);
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(valueInput, "bar");
+ valueInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(container.textContent).toContain("Unsaved changes");
+ saveButton().click();
+ await flush();
+ expect(onChange).toHaveBeenLastCalledWith({ FOO: { type: "plain", value: "bar" } });
+ });
+
+ it("flushes unsaved editor changes before an enclosing form submits", async () => {
+ const submittedValues: Array<Record<string, EnvBinding> | undefined> = [];
+
+ function FormHarness() {
+ const [value, setValue] = useState<Record<string, EnvBinding>>({
+ FOO: { type: "plain", value: "" },
+ });
+ return (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ submittedValues.push(value);
+ }}
+ >
+ <EnvironmentVariablesEditor
+ value={value}
+ secrets={secrets}
+ onChange={(next) => setValue(next ?? {})}
+ onCreateSecret={async () => secrets[0]}
+ />
+ <button type="submit">Outer save</button>
+ </form>
+ );
+ }
+
+ render(<FormHarness />);
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(valueInput, "bar");
+ valueInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+
+ const outerSave = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) =>
+ button.textContent?.includes("Outer save"),
+ )!;
+ outerSave.click();
+ await flush();
+
+ expect(submittedValues).toEqual([{ FOO: { type: "plain", value: "bar" } }]);
+ });
+
+ it("flushes unsaved editor changes before an external save button reads parent state", async () => {
+ const savedValues: Array<Record<string, EnvBinding>> = [];
+
+ function SaveButtonHarness() {
+ const [value, setValue] = useState<Record<string, EnvBinding>>({
+ FOO: { type: "plain", value: "" },
+ });
+ return (
+ <div>
+ <EnvironmentVariablesEditor
+ value={value}
+ secrets={secrets}
+ onChange={(next) => setValue(next ?? {})}
+ onCreateSecret={async () => secrets[0]}
+ />
+ <button type="button" onClick={() => savedValues.push(value)}>
+ Save settings
+ </button>
+ </div>
+ );
+ }
+
+ render(<SaveButtonHarness />);
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(valueInput, "bar");
+ valueInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+
+ const outerSave = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) =>
+ button.textContent?.includes("Save settings"),
+ )!;
+ outerSave.click();
+ await flush();
+
+ expect(savedValues).toEqual([{ FOO: { type: "plain", value: "bar" } }]);
+ });
+
+ it("makes unsaved fields and save controls prominent while editing", async () => {
+ render(<EnvironmentVariablesEditor value={{ FOO: { type: "plain", value: "" } }} secrets={secrets} onChange={() => {}} onCreateSecret={async () => secrets[0]} />);
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(valueInput, "bar");
+ valueInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+
+ const unsavedBar = [...container.querySelectorAll<HTMLElement>('[role="status"]')].find((node) =>
+ node.textContent?.includes("Unsaved changes"),
+ );
+ const valueCell = valueInput.closest<HTMLDivElement>(".relative.flex");
+ const save = saveButton();
+ const revert = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "Revert")!;
+
+ expect(unsavedBar?.className).toContain("bg-amber-500/10");
+ expect(valueCell?.className).toContain("border-amber-500/70");
+ expect(save.className).toContain("h-9");
+ expect(save.className).toContain("px-4");
+ expect(revert.className).toContain("h-9");
+ });
+
+ it("marks a newly typed variable name as unsaved before saving", async () => {
+ render(<EnvironmentVariablesEditor value={{}} secrets={secrets} onChange={() => {}} onCreateSecret={async () => secrets[0]} />);
+ const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
+ addButton.click();
+ await flush();
+
+ const nameInput = nameInputs()[0]!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(nameInput, "API_TOKEN");
+ nameInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+
+ expect(nameInput.className).toContain("border-amber-500/70");
+ expect(container.textContent).toContain("Unsaved changes");
+ });
+
+ it("does not emit or remount while typing a new variable before manual save", async () => {
+ const onChange = vi.fn();
+ const savedValue: Record<string, EnvBinding> = {
+ ZED: { type: "plain", value: "z" },
+ ALPHA: { type: "plain", value: "a" },
+ };
+ render(
+ <EnvironmentVariablesEditor
+ value={savedValue}
+ secrets={secrets}
+ onChange={onChange}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
+ addButton.click();
+ await flush();
+
+ const newNameInput = nameInputs().at(-1)!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(newNameInput, "ca");
+ newNameInput.dispatchEvent(new Event("input", { bubbles: true }));
+ newNameInput.focus();
+ await flush();
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(newNameInput);
+
+ rerender(
+ <EnvironmentVariablesEditor
+ value={savedValue}
+ secrets={secrets}
+ onChange={onChange}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ await flush();
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(newNameInput);
+ expect(nameInputs().at(-1)).toBe(newNameInput);
+
+ setter.call(newNameInput, "carol");
+ newNameInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+ expect(onChange).not.toHaveBeenCalled();
+
+ saveButton().click();
+ await flush();
+ expect(onChange).toHaveBeenLastCalledWith({
+ ZED: { type: "plain", value: "z" },
+ ALPHA: { type: "plain", value: "a" },
+ carol: { type: "plain", value: "" },
+ });
+ });
+
+ it("keeps the active row mounted when a manual save echo returns an equivalent value", async () => {
+ const onChange = vi.fn();
+ const emptyValue: Record<string, EnvBinding> = {};
+ const savedValue: Record<string, EnvBinding> = { API_TOKEN: { type: "plain", value: "secret-value" } };
+ render(
+ <EnvironmentVariablesEditor
+ value={emptyValue}
+ secrets={secrets}
+ onChange={onChange}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
+ addButton.click();
+ await flush();
+
+ const [nameInput] = nameInputs();
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(nameInput, "API_TOKEN");
+ nameInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ setter.call(valueInput, "secret-value");
+ valueInput.dispatchEvent(new Event("input", { bubbles: true }));
+ valueInput.focus();
+ await flush();
+ expect(document.activeElement).toBe(valueInput);
+ expect(onChange).not.toHaveBeenCalled();
+ saveButton().click();
+ await flush();
+ expect(onChange).toHaveBeenLastCalledWith(savedValue);
+
+ rerender(
+ <EnvironmentVariablesEditor
+ value={{ API_TOKEN: { type: "plain", value: "secret-value" } }}
+ secrets={secrets}
+ onChange={onChange}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ await flush();
+
+ expect(document.activeElement).toBe(valueInput);
+ expect(container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')).toBe(valueInput);
+ });
+
+ it("emits undefined when the last binding is removed", async () => {
+ const onChange = vi.fn();
+ render(<EnvironmentVariablesEditor value={{ FOO: { type: "plain", value: "x" } }} secrets={secrets} onChange={onChange} onCreateSecret={async () => secrets[0]} />);
+ const removeButton = container.querySelector<HTMLButtonElement>('button[aria-label^="Remove"]')!;
+ removeButton.click();
+ await flush();
+ expect(onChange).not.toHaveBeenCalled();
+ saveButton().click();
+ await flush();
+ expect(onChange).toHaveBeenLastCalledWith(undefined);
+ });
+
+ it("disables inputs in read-only mode", () => {
+ render(
+ <EnvironmentVariablesEditor
+ value={{ FOO: { type: "plain", value: "x" } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ disabled
+ />,
+ );
+ expect(container.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!.disabled).toBe(true);
+ expect(container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!.disabled).toBe(true);
+ });
+
+ it("renders name warnings as a row spanning the name and value columns", () => {
+ render(
+ <EnvironmentVariablesEditor
+ value={{ PAPERCLIP_PAGE_BASE_URL: { type: "plain", value: "https://pages.paperclip.ing" } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+
+ const nameInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!;
+ const warning = [...container.querySelectorAll<HTMLParagraphElement>("p")].find((node) =>
+ node.textContent?.includes("Reserved prefix"),
+ );
+
+ expect(warning, "reserved-prefix warning should render").toBeTruthy();
+ expect(nameInput.getAttribute("aria-describedby")).toBe(warning!.id);
+ expect(warning!.parentElement?.contains(nameInput), "warning should stay in the row grid").toBe(true);
+ expect(warning!.parentElement).not.toBe(nameInput.parentElement);
+ expect(warning!.className).toContain("col-span-2");
+ expect(warning!.className).toContain("@[40rem]/env:row-start-2");
+ });
+
+ it("bulk-imports a dotenv paste into an empty name field", async () => {
+ const onChange = vi.fn();
+ render(<EnvironmentVariablesEditor value={{}} secrets={secrets} onChange={onChange} onCreateSecret={async () => secrets[0]} />);
+ // Add an empty row to paste into.
+ const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
+ addButton.click();
+ await flush();
+ const nameInput = nameInputs()[0]!;
+ const clipboardData = { getData: () => "A=1\nB=2\nC=3" } as unknown as DataTransfer;
+ const pasteEvent = new Event("paste", { bubbles: true, cancelable: true }) as unknown as ClipboardEvent;
+ Object.defineProperty(pasteEvent, "clipboardData", { value: clipboardData });
+ nameInput.dispatchEvent(pasteEvent);
+ await flush();
+ expect(onChange).not.toHaveBeenCalled();
+ saveButton().click();
+ await flush();
+ expect(onChange).toHaveBeenLastCalledWith({
+ A: { type: "plain", value: "1" },
+ B: { type: "plain", value: "2" },
+ C: { type: "plain", value: "3" },
+ });
+ });
+
+ it("bulk-imports dotenv updates without mutating the committed row baseline", async () => {
+ render(
+ <EnvironmentVariablesEditor
+ value={{ A: { type: "plain", value: "old" } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const addButton = [...container.querySelectorAll("button")].find((button) =>
+ button.textContent?.includes("Add variable"),
+ )!;
+ addButton.click();
+ await flush();
+
+ const targetNameInput = nameInputs().at(-1)!;
+ const pasteEvent = new Event("paste", { bubbles: true, cancelable: true }) as unknown as ClipboardEvent;
+ Object.defineProperty(pasteEvent, "clipboardData", {
+ value: { getData: () => "A=new" } as unknown as DataTransfer,
+ });
+ targetNameInput.dispatchEvent(pasteEvent);
+ await flush();
+
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ const valueCell = valueInput.closest<HTMLDivElement>(".relative.flex");
+ expect(valueInput.value).toBe("new");
+ expect(valueCell?.className).toContain("border-amber-500/70");
+ });
+
+ it("auto-detects a sensitive value and offers a value-preserving Store-as-secret popover", async () => {
+ // A sensitive KEY (matches the shared regex) surfaces the ShieldAlert
+ // affordance and auto-masks the value input (§6.6).
+ render(
+ <EnvironmentVariablesEditor
+ value={{ STRIPE_API_KEY: { type: "plain", value: "supersecretvalue" } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ expect(valueInput.type).toBe("password"); // auto-masked
+ const storeButton = container.querySelector<HTMLButtonElement>('button[title^="This value looks sensitive"]');
+ expect(storeButton, "sensitive Store-as-secret affordance should render").toBeTruthy();
+ storeButton!.click();
+ await flush();
+ // The store popover carries the typed value forward (not discarded).
+ expect(document.body.textContent).toContain("Store value as secret");
+ const secretValueField = document.querySelector<HTMLInputElement>('input[aria-label="Secret value"]');
+ expect(secretValueField?.value).toBe("supersecretvalue");
+ });
+
+ it("opens the create-secret popover from the picker's + Create item (§6.4, PAP-12476)", async () => {
+ // Regression: selecting the picker's `+ Create secret` item closes the
+ // combobox popover and (in the same tick) opens the anchored create-secret
+ // popover. The two Radix popovers must not race — the create popover has to
+ // survive the combobox's focus-return instead of being dismissed instantly.
+ render(
+ <EnvironmentVariablesEditor
+ value={{ GH: { type: "secret_ref", secretId: "s1", version: 2 } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const combobox = container.querySelector<HTMLElement>('[role="combobox"]')!;
+ combobox.focus();
+ await flush();
+ const createItem = [...document.querySelectorAll<HTMLElement>("[cmdk-item]")].find((el) =>
+ el.textContent?.includes("Create"),
+ );
+ expect(createItem, "create item should be present in the open picker").toBeTruthy();
+ createItem!.click();
+ await flush();
+ // The create-secret popover is open (heading rendered) and stays open.
+ expect(document.body.textContent, "create-secret popover should open").toContain("Create secret");
+ expect(
+ document.querySelector('input[aria-label="Secret name"]'),
+ "create-secret name field should render",
+ ).toBeTruthy();
+ });
+
+ it("keeps the create-secret popover open when focus returns to a control inside the value cell (§6.4, PAP-12492)", async () => {
+ // Regression for the *fragile* part of the picker → create transition.
+ // The picker's combobox and the anchored create popover share the value
+ // cell as their anchor. When the picker tears down, Radix returns focus to
+ // the combobox trigger *inside* that anchor — and because the anchor sits
+ // outside the create popover's content, Radix reads that focus-return as a
+ // `focusOutside` and dismisses the just-opened create popover. The picker's
+ // close animation can delay that focus-return past the `setTimeout(0)` open
+ // defer, so a timing-based fix is not enough; the popover must survive an
+ // in-anchor focus-return whenever it lands. jsdom does not reproduce the
+ // animation-delayed focus-return on its own, so we drive it explicitly:
+ // open the create popover, then fire a late `focusin` on an in-anchor
+ // control and assert the popover is still open.
+ render(
+ <EnvironmentVariablesEditor
+ value={{ GH: { type: "secret_ref", secretId: "s1", version: 2 } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const combobox = container.querySelector<HTMLElement>('[role="combobox"]')!;
+ combobox.focus();
+ await flush();
+ const createItem = [...document.querySelectorAll<HTMLElement>("[cmdk-item]")].find((el) =>
+ el.textContent?.includes("Create"),
+ );
+ expect(createItem, "create item should be present in the open picker").toBeTruthy();
+ createItem!.click();
+ await flush();
+ expect(document.body.textContent, "create-secret popover should open").toContain("Create secret");
+
+ // Simulate the picker's animation-delayed focus-return landing on a control
+ // that lives inside the value cell (the source-switch trigger is a stable
+ // in-anchor target that doesn't reopen the picker). Moving focus fires a
+ // blur off the create popover's content (flipping Radix's "focus inside"
+ // flag) and then a focusin on the in-anchor control — exactly the sequence
+ // Radix reads as a `focusOutside`. Without the guard this dismisses the
+ // create popover; with it, the popover survives.
+ const sourceButton = container.querySelector<HTMLElement>('button[aria-label="Value source"]')!;
+ expect(sourceButton, "in-anchor Value source control should exist").toBeTruthy();
+ sourceButton.focus();
+ await flush();
+
+ expect(
+ document.body.textContent,
+ "create-secret popover must survive the in-anchor focus-return",
+ ).toContain("Create secret");
+ expect(
+ document.querySelector('input[aria-label="Secret name"]'),
+ "create-secret name field should still render",
+ ).toBeTruthy();
+ });
+
+ it("opens the store-as-secret popover from the ⋯ overflow menu (PAP-12477)", async () => {
+ // Regression: the ⋯ overflow → "Store as secret…" item is the same nested
+ // shape as the picker's + Create item — a DropdownMenu whose onSelect opens
+ // the row's anchored Popover. The menu closing returns focus to its trigger
+ // (which lives outside the Popover), which must not land as a focusOutside
+ // that dismisses the just-opened popover. A non-sensitive text row surfaces
+ // the ⋯ menu (the sensitive-value inline button is a separate path).
+ render(
+ <EnvironmentVariablesEditor
+ value={{ API_BASE_URL: { type: "plain", value: "https://example.com" } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ // The value is non-sensitive, so no inline Store-as-secret button — only ⋯.
+ expect(container.querySelector('button[title^="This value looks sensitive"]')).toBeNull();
+ const overflow = container.querySelector<HTMLButtonElement>('button[aria-label="More actions"]');
+ expect(overflow, "⋯ overflow menu should render for a non-sensitive text row").toBeTruthy();
+ pointerClick(overflow!);
+ await flush();
+ const storeItem = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((el) =>
+ el.textContent?.includes("Store as secret"),
+ );
+ expect(storeItem, "Store as secret… menu item should be present").toBeTruthy();
+ pointerClick(storeItem!);
+ await flush();
+ // The store popover is open (heading rendered) and stays open — it must not
+ // be dismissed by the menu's focus-return.
+ expect(document.body.textContent, "store-as-secret popover should open").toContain(
+ "Store value as secret",
+ );
+ expect(
+ document.querySelector('input[aria-label="Secret value"]'),
+ "store-as-secret value field should render",
+ ).toBeTruthy();
+ });
+
+ it("opens the store popover from the source dropdown Text→Secret (with a value) and keeps it open (PAP-12478)", () => {
+ // Regression: switching a *non-empty* Text row to "Secret reference" via the
+ // in-field Value source dropdown must open the anchored store-as-secret
+ // popover (§6.3) — value preserved, not discarded. This is the same nested
+ // DropdownMenu→Popover open-while-closing race as the ⋯ and picker paths
+ // (PAP-12476/12477): opening the popover synchronously inside the menu-item's
+ // onSelect lets the menu's focus-return dismiss it in the same tick. With a
+ // *synchronous* open this assertion fails; with the deferred open it passes.
+ vi.useFakeTimers();
+ render(
+ <EnvironmentVariablesEditor
+ value={{ NODE_ENV: { type: "plain", value: "production" } }}
+ secrets={secrets}
+ onChange={() => {}}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const sourceButton = container.querySelector<HTMLButtonElement>('button[aria-label="Value source"]');
+ expect(sourceButton, "Value source dropdown should render").toBeTruthy();
+ pointerClick(sourceButton!);
+ settleFakeTimers();
+ const secretItem = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((el) =>
+ el.textContent?.includes("Secret reference"),
+ );
+ expect(secretItem, "Secret reference menu item should be present").toBeTruthy();
+ pointerClick(secretItem!);
+ settleFakeTimers();
+ // The store popover is open (heading rendered) and stays open — it must not
+ // be dismissed by the menu's focus-return.
+ expect(document.body.textContent, "store-as-secret popover should open").toContain(
+ "Store value as secret",
+ );
+ // The current value is carried forward (masked), not discarded.
+ const secretValueField = document.querySelector<HTMLInputElement>('input[aria-label="Secret value"]');
+ expect(secretValueField, "store-as-secret value field should render").toBeTruthy();
+ expect(secretValueField!.value).toBe("production");
+ });
+
+ it("lets the user dismiss the sensitive-value hint, unmasking the value and keeping it plain (§6.6)", async () => {
+ const onChange = vi.fn();
+ render(
+ <EnvironmentVariablesEditor
+ value={{ STRIPE_API_KEY: { type: "plain", value: "supersecretvalue" } }}
+ secrets={secrets}
+ onChange={onChange}
+ onCreateSecret={async () => secrets[0]}
+ />,
+ );
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ expect(valueInput.type).toBe("password"); // auto-masked while the hint shows
+
+ const dismissButton = container.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Dismiss sensitive-value suggestion"]',
+ );
+ expect(dismissButton, "dismiss affordance should render alongside the hint").toBeTruthy();
+ dismissButton!.click();
+ await flush();
+
+ // Hint + its dismiss control are gone, and the value is no longer masked.
+ expect(
+ container.querySelector('button[title^="This value looks sensitive"]'),
+ "store-as-secret hint should be dismissed",
+ ).toBeNull();
+ expect(
+ container.querySelector('button[aria-label="Dismiss sensitive-value suggestion"]'),
+ ).toBeNull();
+ expect(
+ container.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!.type,
+ ).toBe("text");
+
+ // Dismissal is a local UI concern — the emitted plain value is unchanged.
+ const lastEmit = onChange.mock.calls.at(-1)?.[0];
+ if (lastEmit) {
+ expect(lastEmit).toEqual({ STRIPE_API_KEY: { type: "plain", value: "supersecretvalue" } });
+ }
+ });
+
+ it("lets slash-delimited secrets be browsed by folder and exposes full paths on hover", async () => {
+ const cloudProviderKey = "/paperclip-cloud/prod/provider/aws-access-key-id";
+ const cloudMigrationKey = "/paperclip-cloud/prod/migration/postgres-url";
+ const onSelect = vi.fn();
+ render(
+ <SecretPicker
+ secretId=""
+ secrets={[
+ makeSecret("provider-key", { name: cloudProviderKey, key: cloudProviderKey }),
+ makeSecret("migration-key", { name: cloudMigrationKey, key: cloudMigrationKey }),
+ makeSecret("plain-key", { name: "paperclip-page-aws-access-key-id", key: "paperclip-page-aws-access-key-id" }),
+ ]}
+ onSelect={onSelect}
+ onCreateNew={() => {}}
+ disablePortal
+ />,
+ );
+
+ const combobox = container.querySelector<HTMLElement>('[role="combobox"]')!;
+ combobox.focus();
+ await flush();
+
+ const itemByText = (text: string) =>
+ [...document.querySelectorAll<HTMLElement>("[cmdk-item]")].find((el) =>
+ el.textContent?.includes(text),
+ );
+ const rowTitle = (item: HTMLElement | undefined) => item?.querySelector<HTMLElement>("[title]")?.getAttribute("title");
+
+ expect(rowTitle(itemByText("paperclip-cloud"))).toBe("/paperclip-cloud");
+ expect(rowTitle(itemByText("paperclip-page-aws-access-key-id"))).toBe(
+ "paperclip-page-aws-access-key-id",
+ );
+
+ itemByText("paperclip-cloud")!.click();
+ await flush();
+ expect(rowTitle(itemByText("prod"))).toBe("/paperclip-cloud/prod");
+
+ itemByText("prod")!.click();
+ await flush();
+ expect(rowTitle(itemByText("provider"))).toBe("/paperclip-cloud/prod/provider");
+ expect(rowTitle(itemByText("migration"))).toBe("/paperclip-cloud/prod/migration");
+
+ itemByText("provider")!.click();
+ await flush();
+ const leaf = itemByText("aws-access-key-id");
+ expect(rowTitle(leaf)).toBe(cloudProviderKey);
+
+ leaf!.click();
+ await flush();
+ expect(onSelect).toHaveBeenCalledWith("provider-key");
+ });
+
+ it("keeps secret search global while browsing starts at slash folders", async () => {
+ const cloudMigrationKey = "/paperclip-cloud/prod/migration/postgres-url";
+ render(
+ <SecretPicker
+ secretId=""
+ secrets={[
+ makeSecret("provider-key", {
+ name: "/paperclip-cloud/prod/provider/aws-access-key-id",
+ key: "/paperclip-cloud/prod/provider/aws-access-key-id",
+ }),
+ makeSecret("migration-key", { name: cloudMigrationKey, key: cloudMigrationKey }),
+ ]}
+ onSelect={() => {}}
+ onCreateNew={() => {}}
+ disablePortal
+ />,
+ );
+
+ const combobox = container.querySelector<HTMLElement>('[role="combobox"]')!;
+ combobox.focus();
+ await flush();
+ expect(document.body.textContent).toContain("paperclip-cloud");
+ expect(document.body.textContent).not.toContain("postgres-url");
+
+ const search = document.querySelector<HTMLInputElement>('input[placeholder="Search secrets…"]')!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setter.call(search, "postgres");
+ search.dispatchEvent(new Event("input", { bubbles: true }));
+ await flush();
+
+ const match = [...document.querySelectorAll<HTMLElement>("[cmdk-item]")].find((el) =>
+ el.textContent?.includes(cloudMigrationKey),
+ );
+ expect(match?.querySelector<HTMLElement>("[title]")?.getAttribute("title")).toBe(cloudMigrationKey);
+ });
+});
diff --git a/ui/src/components/environment-variables-editor/Row.tsx b/ui/src/components/environment-variables-editor/Row.tsx
new file mode 100644
index 0000000000..8489c0d8ae
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/Row.tsx
@@ -0,0 +1,521 @@
+import { useEffect, useRef, useState } from "react";
+import {
+ ChevronDown,
+ KeyRound,
+ MoreHorizontal,
+ ShieldAlert,
+ Type as TypeIcon,
+ X,
+} from "lucide-react";
+import type { CompanySecret } from "@paperclipai/shared";
+import { cn } from "@/lib/utils";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { SecretPicker } from "./SecretPicker";
+import { CreateSecretPopover, ConvertToSecretPopover } from "./CreateSecretPopover";
+import { isSensitiveEnv } from "./sensitive";
+import {
+ computeRowHealth,
+ planSourceSwitch,
+ secretNameFromKey,
+ type EnvRow,
+ type NameIssue,
+} from "./model";
+
+const nameInputClass =
+ "w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/40";
+
+const valueTextInputClass =
+ "min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";
+
+type SecretPopoverState = { mode: "create" | "store"; name: string; value: string } | null;
+export interface EnvironmentVariableDirtyFields {
+ name: boolean;
+ value: boolean;
+}
+
+export interface EnvironmentVariableRowProps {
+ row: EnvRow;
+ isLast: boolean;
+ secrets: readonly CompanySecret[];
+ recentlyUsedSecrets?: readonly CompanySecret[];
+ disabled?: boolean;
+ nameIssue: NameIssue | null;
+ showNameIssue: boolean;
+ dirtyFields: EnvironmentVariableDirtyFields;
+ onPatch: (patch: Partial<EnvRow>) => void;
+ onRemove: () => void;
+ onNameBlur: () => void;
+ /** Handle a multi-line dotenv paste into the (empty) name field. Returns true if consumed. */
+ onNamePaste: (text: string) => boolean;
+ /** Enter pressed in the value of the last row — append a fresh row and focus it. */
+ onEnterInValueLast: () => void;
+ onCreateSecret: (name: string, value: string) => Promise<CompanySecret>;
+ onToast: (message: string) => void;
+ /** Parent-driven focus request for this row (append flow, source switch). */
+ focusRequest: "name" | "value" | null;
+ onFocusConsumed: () => void;
+}
+
+export function EnvironmentVariableRow({
+ row,
+ isLast,
+ secrets,
+ recentlyUsedSecrets,
+ disabled,
+ nameIssue,
+ showNameIssue,
+ dirtyFields,
+ onPatch,
+ onRemove,
+ onNameBlur,
+ onNamePaste,
+ onEnterInValueLast,
+ onCreateSecret,
+ onToast,
+ focusRequest,
+ onFocusConsumed,
+}: EnvironmentVariableRowProps) {
+ const nameInputRef = useRef<HTMLInputElement | null>(null);
+ const valueInputRef = useRef<HTMLInputElement | null>(null);
+ const valueCellRef = useRef<HTMLDivElement | null>(null);
+ const [secretPopover, setSecretPopover] = useState<SecretPopoverState>(null);
+ const [versionOpen, setVersionOpen] = useState(false);
+ const [undoPrev, setUndoPrev] = useState<EnvRow | null>(null);
+
+ const health = computeRowHealth(row, secrets);
+ const boundSecret = row.source === "secret" ? secrets.find((s) => s.id === row.secretId) ?? null : null;
+ const sensitive =
+ row.source === "text" && !row.sensitiveDismissed && isSensitiveEnv(row.name, row.textValue);
+
+ // Consume parent focus requests (append / source-switch flows).
+ useEffect(() => {
+ if (!focusRequest) return;
+ if (focusRequest === "name") {
+ nameInputRef.current?.focus();
+ } else if (row.source === "text") {
+ valueInputRef.current?.focus();
+ } else {
+ // Focusing the combobox trigger opens SearchableSelect (non-pointer focus).
+ valueCellRef.current?.querySelector<HTMLElement>("[role=combobox]")?.focus();
+ }
+ onFocusConsumed();
+ }, [focusRequest, onFocusConsumed, row.source]);
+
+ // Auto-expire the 5s "Undo" affordance after a Secret→Text switch (§6.3).
+ useEffect(() => {
+ if (!undoPrev) return;
+ const handle = window.setTimeout(() => setUndoPrev(null), 5000);
+ return () => window.clearTimeout(handle);
+ }, [undoPrev]);
+
+ function switchSource(next: "text" | "secret") {
+ const plan = planSourceSwitch(row, next);
+ switch (plan.kind) {
+ case "noop":
+ return;
+ case "open-store": {
+ // Defer to the next macrotask so the source DropdownMenu fully closes
+ // (and Radix returns focus to its trigger) before we open the anchored
+ // store-as-secret popover. Opening synchronously inside the menu-item's
+ // onSelect lets the menu's focus-return land as a `focusOutside` /
+ // `interactOutside` on the just-opened popover, which Radix would
+ // immediately dismiss — the same nested open-while-closing race as the
+ // ⋯ path and the picker's + Create item (PAP-12476/12477/12478).
+ const { name, value } = plan;
+ window.setTimeout(() => setSecretPopover({ mode: "store", name, value }), 0);
+ return;
+ }
+ case "to-secret":
+ onPatch({ source: "secret" });
+ // Auto-open the picker.
+ window.setTimeout(() => {
+ valueCellRef.current?.querySelector<HTMLElement>("[role=combobox]")?.focus();
+ }, 0);
+ return;
+ case "to-text":
+ if (plan.undoFrom) setUndoPrev(plan.undoFrom);
+ onPatch({ source: "text", secretId: "", version: "latest" });
+ window.setTimeout(() => valueInputRef.current?.focus(), 0);
+ return;
+ }
+ }
+
+ async function submitSecretPopover(name: string, value: string) {
+ const created = await onCreateSecret(name, value);
+ onPatch({ source: "secret", secretId: created.id, version: "latest", textValue: "" });
+ onToast(`Secret ${created.name} created`);
+ setSecretPopover(null);
+ }
+
+ function openStoreAsSecret() {
+ const name = secretNameFromKey(row.name) || "secret";
+ const { textValue } = row;
+ window.setTimeout(() => setSecretPopover({ mode: "store", name, value: textValue }), 0);
+ }
+
+ const sourceLabel = row.source === "text" ? "Text value" : "Secret reference";
+ const nameErrorId = `${row.id}-name-error`;
+ const healthId = `${row.id}-health`;
+ const isDirty = dirtyFields.name || dirtyFields.value;
+
+ const versions = boundSecret ? Math.max(0, boundSecret.latestVersion) : 0;
+ const versionTagLabel = row.version === "latest" ? "latest" : `v${row.version}`;
+ const versionPinned = row.version !== "latest";
+
+ return (
+ <div
+ className={cn(
+ "group/row grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1",
+ "@[40rem]/env:grid-cols-[minmax(160px,2fr)_minmax(240px,3fr)_32px] @[40rem]/env:items-center",
+ isDirty && "bg-amber-500/[0.06] ring-1 ring-amber-500/20",
+ )}
+ >
+ {/* Name cell — mobile col 1 / desktop col 1 */}
+ <div className="col-start-1 row-start-1 min-w-0 @[40rem]/env:row-start-1 @[40rem]/env:self-start">
+ <input
+ ref={nameInputRef}
+ className={cn(
+ nameInputClass,
+ dirtyFields.name && "border-amber-500/70 bg-amber-500/10 focus-visible:ring-amber-500/40",
+ showNameIssue && nameIssue?.level === "error" && "border-destructive focus-visible:ring-destructive/40",
+ showNameIssue && nameIssue?.level === "warn" && "border-amber-500 focus-visible:ring-amber-500/40",
+ )}
+ placeholder="KEY"
+ value={row.name}
+ spellCheck={false}
+ disabled={disabled}
+ aria-label="Variable name"
+ aria-invalid={showNameIssue && nameIssue?.level === "error" ? true : undefined}
+ aria-describedby={showNameIssue && nameIssue ? nameErrorId : undefined}
+ onChange={(event) => onPatch({ name: event.target.value })}
+ onBlur={onNameBlur}
+ onPaste={(event) => {
+ if (row.name) return;
+ const text = event.clipboardData.getData("text");
+ if (onNamePaste(text)) event.preventDefault();
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ if (row.source === "text") valueInputRef.current?.focus();
+ else valueCellRef.current?.querySelector<HTMLElement>("[role=combobox]")?.focus();
+ }
+ }}
+ />
+ </div>
+
+ {/* Value cell — mobile full-width line 2 / desktop col 2 */}
+ <div className="col-span-2 col-start-1 row-start-2 min-w-0 @[40rem]/env:col-span-1 @[40rem]/env:col-start-2 @[40rem]/env:row-start-1">
+ <Popover
+ open={secretPopover !== null}
+ onOpenChange={(open) => {
+ if (!open) setSecretPopover(null);
+ }}
+ >
+ <PopoverAnchor asChild>
+ <div
+ ref={valueCellRef}
+ className={cn(
+ "relative flex items-stretch overflow-hidden rounded-md border border-border bg-transparent focus-within:ring-2 focus-within:ring-ring/40",
+ dirtyFields.value && "border-amber-500/70 bg-amber-500/10 focus-within:ring-amber-500/40",
+ disabled && "opacity-60",
+ )}
+ >
+ {/* Source switch (inside the field) */}
+ <DropdownMenu>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DropdownMenuTrigger asChild disabled={disabled}>
+ <button
+ type="button"
+ aria-label="Value source"
+ className="flex shrink-0 items-center gap-0.5 border-r border-border px-2 text-muted-foreground hover:bg-accent/50 disabled:pointer-events-none"
+ >
+ {row.source === "text" ? (
+ <TypeIcon className="size-3.5" />
+ ) : (
+ <KeyRound className="size-3.5" />
+ )}
+ <ChevronDown className="size-3 opacity-60" />
+ </button>
+ </DropdownMenuTrigger>
+ </TooltipTrigger>
+ <TooltipContent side="top">{sourceLabel}</TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent align="start" className="w-56">
+ <DropdownMenuItem className="flex-col items-start gap-0.5" onSelect={() => switchSource("text")}>
+ <span className="text-sm">Text value</span>
+ <span className="text-[11px] text-muted-foreground">Store the value inline as plain text.</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem className="flex-col items-start gap-0.5" onSelect={() => switchSource("secret")}>
+ <span className="text-sm">Secret reference</span>
+ <span className="text-[11px] text-muted-foreground">Resolve a stored company secret at run start.</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ {row.source === "text" ? (
+ <>
+ <input
+ ref={valueInputRef}
+ className={valueTextInputClass}
+ placeholder="value"
+ value={row.textValue}
+ type={sensitive ? "password" : "text"}
+ spellCheck={false}
+ disabled={disabled}
+ aria-label="Variable value"
+ onChange={(event) => onPatch({ textValue: event.target.value })}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && isLast) {
+ event.preventDefault();
+ onEnterInValueLast();
+ }
+ }}
+ />
+ {sensitive ? (
+ <div className="flex shrink-0 items-stretch border-l border-border">
+ <button
+ type="button"
+ onClick={openStoreAsSecret}
+ disabled={disabled}
+ className="flex items-center gap-1 px-2 text-[11px] text-amber-700 hover:bg-amber-500/10 dark:text-amber-400"
+ title="This value looks sensitive — store it as a secret"
+ >
+ <ShieldAlert className="size-3.5" />
+ <span className="hidden @[30rem]/env:inline">Store as secret</span>
+ </button>
+ <button
+ type="button"
+ onClick={() => onPatch({ sensitiveDismissed: true })}
+ disabled={disabled}
+ aria-label="Dismiss sensitive-value suggestion"
+ title="Dismiss — keep this value as plain text"
+ className="flex items-center px-1.5 text-amber-700/60 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-400/60 dark:hover:text-amber-400"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ) : null}
+ </>
+ ) : (
+ <div className="relative min-w-0 flex-1">
+ <SecretPicker
+ secretId={row.secretId}
+ secrets={secrets}
+ recentlyUsedSecrets={recentlyUsedSecrets}
+ disabled={disabled}
+ onSelect={(id) => onPatch({ secretId: id, version: "latest" })}
+ onCreateNew={(query) =>
+ setSecretPopover({ mode: "create", name: secretNameFromKey(query) || query.trim(), value: "" })
+ }
+ triggerClassName={cn(
+ "rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",
+ boundSecret && boundSecret.status === "active" && "pr-24 has-[>svg]:!pr-24",
+ )}
+ />
+ {boundSecret && boundSecret.status === "active" ? (
+ <Popover open={versionOpen} onOpenChange={setVersionOpen}>
+ <PopoverAnchor asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setVersionOpen((prev) => !prev);
+ }}
+ aria-label="Version"
+ className={cn(
+ "absolute right-8 top-1/2 z-10 -translate-y-1/2 rounded px-1.5 py-0.5 text-[10px] font-medium",
+ versionPinned
+ ? "bg-amber-500/15 text-amber-700 dark:text-amber-400"
+ : "text-muted-foreground hover:bg-accent",
+ )}
+ >
+ {versionTagLabel}
+ </button>
+ </PopoverAnchor>
+ <PopoverContent align="end" className="w-44 p-1" role="radiogroup" aria-label="Secret version">
+ <button
+ type="button"
+ role="radio"
+ aria-checked={row.version === "latest"}
+ onClick={() => {
+ onPatch({ version: "latest" });
+ setVersionOpen(false);
+ }}
+ className={cn(
+ "flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",
+ row.version === "latest" && "font-medium",
+ )}
+ >
+ latest <span className="text-[11px] text-muted-foreground">(recommended)</span>
+ </button>
+ {Array.from({ length: versions }, (_, idx) => versions - idx)
+ .filter((v) => v > 0)
+ .map((v) => (
+ <button
+ key={v}
+ type="button"
+ role="radio"
+ aria-checked={row.version === v}
+ onClick={() => {
+ onPatch({ version: v });
+ setVersionOpen(false);
+ }}
+ className={cn(
+ "flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",
+ row.version === v && "font-medium text-amber-700 dark:text-amber-400",
+ )}
+ >
+ v{v}
+ </button>
+ ))}
+ </PopoverContent>
+ </Popover>
+ ) : null}
+ </div>
+ )}
+ </div>
+ </PopoverAnchor>
+ <PopoverContent
+ align="start"
+ className="w-auto p-3"
+ onInteractOutside={(event) => {
+ // Keep the create/store popover open when the dismissal
+ // originates from inside the value cell — i.e. the picker's
+ // combobox trigger or the source-switch dropdown trigger, both
+ // anchored here. Those controls close by returning focus to
+ // themselves; because the value cell is this popover's *anchor*
+ // (outside its content), Radix reads that focus-return as a
+ // `focusOutside` and would dismiss the just-opened popover.
+ //
+ // The picker's close animation can delay its focus-return past
+ // any single macrotask, so the `setTimeout(0)` open-defers
+ // (SearchableSelect / switchSource) cannot reliably win the race
+ // (PAP-12492). Guarding the interaction here makes the create /
+ // store popover survive that focus-return deterministically,
+ // independent of timing. Dismissals from anywhere *outside* the
+ // value cell (real outside clicks, Escape) are untouched.
+ const target = event.detail.originalEvent.target as Node | null;
+ if (target && valueCellRef.current?.contains(target)) {
+ event.preventDefault();
+ }
+ }}
+ >
+ {secretPopover?.mode === "store" ? (
+ <ConvertToSecretPopover
+ initialName={secretPopover.name}
+ initialValue={secretPopover.value}
+ existingSecretNames={secrets.map((s) => s.name)}
+ onCancel={() => setSecretPopover(null)}
+ onSubmit={submitSecretPopover}
+ />
+ ) : secretPopover?.mode === "create" ? (
+ <CreateSecretPopover
+ initialName={secretPopover.name}
+ initialValue={secretPopover.value}
+ existingSecretNames={secrets.map((s) => s.name)}
+ onCancel={() => setSecretPopover(null)}
+ onSubmit={submitSecretPopover}
+ />
+ ) : null}
+ </PopoverContent>
+ </Popover>
+
+ {/* Inline secret-health message */}
+ {health ? (
+ <p
+ id={healthId}
+ role="status"
+ className={cn(
+ "mt-0.5 text-[11px]",
+ health.level === "error" ? "text-destructive" : "text-amber-600 dark:text-amber-400",
+ )}
+ >
+ {health.message}
+ </p>
+ ) : null}
+
+ {/* 5s undo after Secret→Text */}
+ {undoPrev ? (
+ <p className="mt-0.5 inline-flex items-center gap-2 text-[11px] text-muted-foreground">
+ Reverted to text —{" "}
+ <button
+ type="button"
+ className="font-medium text-foreground underline underline-offset-2 hover:text-primary"
+ onClick={() => {
+ onPatch({ source: "secret", secretId: undoPrev.secretId, version: undoPrev.version, textValue: "" });
+ setUndoPrev(null);
+ }}
+ >
+ Undo
+ </button>
+ </p>
+ ) : null}
+ </div>
+
+ {showNameIssue && nameIssue ? (
+ <p
+ id={nameErrorId}
+ className={cn(
+ "col-span-2 col-start-1 row-start-3 min-w-0 text-[11px] @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",
+ nameIssue.level === "error" ? "text-destructive" : "text-amber-600 dark:text-amber-400",
+ )}
+ >
+ {nameIssue.message}
+ </p>
+ ) : null}
+
+ {/* Actions cell — mobile col 2 line 1 / desktop col 3 */}
+ <div className="col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center">
+ {row.source === "text" && !sensitive && (row.name.trim() || row.textValue) ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild disabled={disabled}>
+ <button
+ type="button"
+ aria-label="More actions"
+ className="rounded p-1 text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100"
+ >
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onSelect={() => {
+ // Defer to the next macrotask so this menu fully closes (and
+ // Radix returns focus to the ⋯ trigger, which sits outside the
+ // row's Popover) before we open the anchored store-as-secret
+ // popover. Opening synchronously lets the menu's focus-return
+ // land as a `focusOutside` on the just-opened popover, which
+ // Radix would immediately dismiss — the same nested open-while-
+ // closing race as the picker's + Create item (PAP-12476/12477).
+ window.setTimeout(openStoreAsSecret, 0);
+ }}
+ >
+ Store as secret…
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ <button
+ type="button"
+ onClick={onRemove}
+ disabled={disabled}
+ aria-label={`Remove ${row.name.trim() || "variable"}`}
+ className="rounded p-1 text-muted-foreground opacity-100 hover:bg-destructive/10 hover:text-destructive @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100"
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/components/environment-variables-editor/SecretPicker.tsx b/ui/src/components/environment-variables-editor/SecretPicker.tsx
new file mode 100644
index 0000000000..0458a10635
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/SecretPicker.tsx
@@ -0,0 +1,337 @@
+import { useCallback, useMemo, useState } from "react";
+import { CornerUpLeft, Folder, KeyRound, Plus } from "lucide-react";
+import type { CompanySecret, SecretStatus } from "@paperclipai/shared";
+import {
+ SearchableSelect,
+ type SearchableSelectGroup,
+ type SearchableSelectOption,
+} from "@/components/SearchableSelect";
+import { Badge } from "@/components/ui/badge";
+import { normalizeSearchText } from "@/lib/searchable-select";
+import { cn } from "@/lib/utils";
+
+interface SecretOption extends SearchableSelectOption {
+ kind?: "secret" | "folder" | "back";
+ secret?: CompanySecret;
+ missing?: boolean;
+ status?: SecretStatus;
+ folderPath?: string;
+ pathHint?: string;
+}
+
+const FOLDER_VALUE_PREFIX = "__secret_folder__:";
+
+function statusBadge(status: SecretStatus | undefined) {
+ if (!status || status === "active") return null;
+ return (
+ <Badge variant="outline" className="ml-auto text-[10px] font-normal text-muted-foreground">
+ {status}
+ </Badge>
+ );
+}
+
+function splitSecretPath(name: string) {
+ return name.split("/").filter((part) => part.length > 0);
+}
+
+function pathKey(parts: readonly string[]) {
+ return parts.join("/");
+}
+
+function pathLabel(parts: readonly string[]) {
+ return parts.length > 0 ? `/${parts.join("/")}` : "/";
+}
+
+function pathStartsWith(parts: readonly string[], prefix: readonly string[]) {
+ if (parts.length < prefix.length) return false;
+ return prefix.every((part, index) => parts[index] === part);
+}
+
+function folderValue(parts: readonly string[]) {
+ return `${FOLDER_VALUE_PREFIX}${pathKey(parts)}`;
+}
+
+function buildFolderGroup(
+ secrets: readonly CompanySecret[],
+ currentPath: readonly string[],
+ currentSecretId: string,
+): SearchableSelectGroup<string, SecretOption> {
+ const currentLength = currentPath.length;
+ const folders = new Map<string, SecretOption>();
+ const leafSecrets: SecretOption[] = [];
+
+ for (const secret of secrets) {
+ const parts = splitSecretPath(secret.name);
+ if (!pathStartsWith(parts, currentPath)) continue;
+
+ if (parts.length > currentLength + 1) {
+ const folderParts = parts.slice(0, currentLength + 1);
+ const key = pathKey(folderParts);
+ if (!folders.has(key)) {
+ const label = folderParts[folderParts.length - 1] ?? "/";
+ const fullPath = pathLabel(folderParts);
+ folders.set(key, {
+ key: `folder-${key || "root"}`,
+ value: folderValue(folderParts),
+ label,
+ title: fullPath,
+ searchText: fullPath,
+ kind: "folder",
+ folderPath: key,
+ pathHint: fullPath,
+ });
+ }
+ continue;
+ }
+
+ if (parts.length === currentLength + 1 || (currentLength === 0 && parts.length === 0)) {
+ const label = parts.at(-1) ?? secret.name;
+ leafSecrets.push({
+ key: `browse-${secret.id}`,
+ value: secret.id,
+ label,
+ title: secret.name,
+ searchText: `${secret.key} ${secret.name}`,
+ secret,
+ status: secret.status,
+ kind: "secret",
+ pathHint: secret.name,
+ disabled: secret.status !== "active" && secret.id !== currentSecretId,
+ });
+ }
+ }
+
+ const options: SecretOption[] = [];
+ if (currentPath.length > 0) {
+ const parentPath = currentPath.slice(0, -1);
+ options.push({
+ key: `folder-up-${pathKey(currentPath)}`,
+ value: folderValue(parentPath),
+ label: "Up one folder",
+ title: pathLabel(parentPath),
+ searchText: pathLabel(parentPath),
+ kind: "back",
+ folderPath: pathKey(parentPath),
+ pathHint: pathLabel(parentPath),
+ });
+ }
+ options.push(...folders.values(), ...leafSecrets);
+
+ return {
+ id: "browse-secrets",
+ label: currentPath.length > 0 ? pathLabel(currentPath) : "Browse secrets",
+ options,
+ };
+}
+
+export interface SecretPickerProps {
+ /** Currently-bound secret id, or "" when unbound. */
+ secretId: string;
+ secrets: readonly CompanySecret[];
+ recentlyUsedSecrets?: readonly CompanySecret[];
+ disabled?: boolean;
+ onSelect: (secretId: string) => void;
+ /** Open the create-secret popover, seeded with the current query. */
+ onCreateNew: (query: string) => void;
+ triggerClassName?: string;
+ /** SearchableSelect auto-opens on focus; suppress for programmatic control. */
+ disablePortal?: boolean;
+}
+
+/**
+ * Fuzzy secret combobox (plan §6.4). Reuses {@link SearchableSelect}, adds the
+ * Recently-used group, greys non-active secrets (non-selectable for new
+ * bindings), surfaces a missing-secret sentinel, and pins a `+ Create secret`
+ * creatable item.
+ */
+export function SecretPicker({
+ secretId,
+ secrets,
+ recentlyUsedSecrets,
+ disabled,
+ onSelect,
+ onCreateNew,
+ triggerClassName,
+ disablePortal,
+}: SecretPickerProps) {
+ const [currentPathKey, setCurrentPathKey] = useState("");
+ const boundSecret = useMemo(
+ () => secrets.find((secret) => secret.id === secretId) ?? null,
+ [secrets, secretId],
+ );
+ const boundMissing = Boolean(secretId) && !boundSecret;
+ const currentPath = useMemo(() => (currentPathKey ? currentPathKey.split("/") : []), [currentPathKey]);
+ const hasFolderPaths = useMemo(() => secrets.some((secret) => splitSecretPath(secret.name).length > 1), [secrets]);
+
+ const groups = useMemo<SearchableSelectGroup<string, SecretOption>[]>(() => {
+ const result: SearchableSelectGroup<string, SecretOption>[] = [];
+
+ // Missing (deleted) secret still needs a resolvable option so the trigger
+ // can render the destructive "Missing secret" chip.
+ if (boundMissing) {
+ result.push({
+ id: "current-missing",
+ label: "Current",
+ options: [
+ {
+ key: `missing-${secretId}`,
+ value: secretId,
+ label: `Missing secret (${secretId.slice(0, 8)}…)`,
+ title: `Missing secret (${secretId})`,
+ missing: true,
+ disabled: true,
+ },
+ ],
+ });
+ }
+
+ const recent = (recentlyUsedSecrets ?? []).filter(
+ (secret) => secret.status === "active" && secret.id !== secretId,
+ );
+ if (recent.length > 0) {
+ result.push({
+ id: "recently-used",
+ label: "Recently used",
+ options: recent.map((secret) => ({
+ key: `recent-${secret.id}`,
+ value: secret.id,
+ label: secret.name,
+ title: secret.name,
+ searchText: `${secret.key} ${secret.name}`,
+ secret,
+ status: secret.status,
+ kind: "secret",
+ })),
+ });
+ }
+
+ result.push({
+ id: "all-secrets",
+ label: recent.length > 0 ? "All secrets" : undefined,
+ options: secrets.map((secret) => ({
+ key: `all-${secret.id}`,
+ value: secret.id,
+ label: secret.name,
+ title: secret.name,
+ searchText: `${secret.key} ${secret.name}`,
+ secret,
+ status: secret.status,
+ kind: "secret",
+ // Non-active secrets are not selectable for new bindings, but the
+ // already-bound one stays selectable (it's the current value).
+ disabled: secret.status !== "active" && secret.id !== secretId,
+ })),
+ });
+
+ return result;
+ }, [boundMissing, recentlyUsedSecrets, secretId, secrets]);
+
+ const deriveGroups = useCallback(
+ (query: string, baseGroups: readonly SearchableSelectGroup<string, SecretOption>[]) => {
+ if (!hasFolderPaths) return baseGroups;
+ if (normalizeSearchText(query)) return baseGroups;
+
+ const browseGroup = buildFolderGroup(secrets, currentPath, secretId);
+ const stableGroups = baseGroups.filter((group) => group.id === "current-missing" || group.id === "recently-used");
+ return browseGroup.options.length > 0 ? [...stableGroups, browseGroup] : stableGroups;
+ },
+ [currentPath, hasFolderPaths, secretId, secrets],
+ );
+
+ return (
+ <SearchableSelect<string, SecretOption>
+ value={secretId || ""}
+ groups={groups}
+ onValueChange={(next, option) => {
+ if (option.folderPath !== undefined) {
+ setCurrentPathKey(option.folderPath);
+ return false;
+ }
+ setCurrentPathKey("");
+ onSelect(next);
+ }}
+ deriveGroups={deriveGroups}
+ disabled={disabled}
+ disablePortal={disablePortal}
+ placeholder="Select secret…"
+ searchPlaceholder="Search secrets…"
+ emptyMessage="No matching secrets"
+ triggerClassName={cn(
+ "h-[34px] min-h-[34px] font-mono text-sm",
+ boundMissing && "border-destructive text-destructive",
+ boundSecret && boundSecret.status !== "active" && "border-amber-500/60",
+ triggerClassName,
+ )}
+ renderValue={(option) => {
+ if (!option) {
+ return <span className="text-muted-foreground">Select secret…</span>;
+ }
+ if (option.missing) {
+ return (
+ <span className="flex w-full min-w-0 items-center gap-1.5 text-destructive">
+ <KeyRound className="size-3.5 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">{option.label}</span>
+ </span>
+ );
+ }
+ const nonActive = option.status && option.status !== "active";
+ return (
+ <span className="flex w-full min-w-0 items-center gap-1.5" title={option.title}>
+ <KeyRound className={cn("size-3.5 shrink-0", nonActive ? "text-amber-600" : "text-muted-foreground")} />
+ <span className="min-w-0 flex-1 truncate">{option.label}</span>
+ {nonActive ? <span className="text-amber-600">({option.status})</span> : null}
+ </span>
+ );
+ }}
+ renderOption={(option, { selected }) => {
+ if (option.kind === "folder" || option.kind === "back") {
+ const Icon = option.kind === "back" ? CornerUpLeft : Folder;
+ return (
+ <span className="flex min-w-0 flex-1 items-center gap-1.5" title={option.title ?? option.label}>
+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="flex min-w-0 flex-col">
+ <span className={cn("truncate text-sm", selected && "font-medium")}>{option.label}</span>
+ {option.pathHint ? (
+ <span className="truncate font-mono text-[11px] text-muted-foreground">{option.pathHint}</span>
+ ) : null}
+ </span>
+ </span>
+ );
+ }
+
+ return (
+ <span
+ className={cn("flex min-w-0 flex-1 items-center gap-1.5", option.disabled && "opacity-60")}
+ title={option.title ?? option.label}
+ >
+ <KeyRound className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="flex min-w-0 flex-col">
+ <span className={cn("min-w-0 truncate font-mono text-sm", selected && "font-medium")}>
+ {option.label}
+ </span>
+ {option.pathHint && option.pathHint !== option.label ? (
+ <span className="truncate font-mono text-[11px] text-muted-foreground">{option.pathHint}</span>
+ ) : null}
+ </span>
+ {statusBadge(option.status)}
+ </span>
+ );
+ }}
+ createItem={{
+ render: (query) => (
+ <span className="flex items-center gap-1.5 text-sm">
+ <Plus className="size-3.5 shrink-0" />
+ {query.trim() ? (
+ <span>
+ Create secret <span className="font-mono">&ldquo;{query.trim()}&rdquo;</span>…
+ </span>
+ ) : (
+ <span>Create new secret…</span>
+ )}
+ </span>
+ ),
+ onSelect: (query) => onCreateNew(query),
+ }}
+ />
+ );
+}
diff --git a/ui/src/components/environment-variables-editor/index.tsx b/ui/src/components/environment-variables-editor/index.tsx
new file mode 100644
index 0000000000..b29d7f4e82
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/index.tsx
@@ -0,0 +1,472 @@
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { flushSync } from "react-dom";
+import { AlertCircle, KeyRound, Plus, RotateCcw, Save } from "lucide-react";
+import type { CompanySecret, EnvBinding } from "@paperclipai/shared";
+import { cn } from "@/lib/utils";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { useOptionalToastActions } from "@/context/ToastContext";
+import { EnvironmentVariableRow } from "./Row";
+import { parseDotenv } from "./parse-dotenv";
+import {
+ computeDuplicateNames,
+ computeRowHealth,
+ emptyRow,
+ envKeyFromSecretName,
+ rowsFromValue,
+ validateName,
+ valueFromRows,
+ type EnvRow,
+} from "./model";
+import type { EnvironmentVariableDirtyFields } from "./Row";
+
+const DEFAULT_RESERVED_PREFIXES = ["PAPERCLIP_"];
+
+const DEFAULT_HINT =
+ "Set the KEY to the env var name the process expects, for example GH_TOKEN. Choose a secret to resolve a stored value at run start. PAPERCLIP_* variables are injected automatically.";
+
+function normalizedEnvKey(value: Record<string, EnvBinding> | null | undefined): string {
+ if (!value || typeof value !== "object") return "";
+ const entries = Object.entries(value)
+ .map(([name, binding]) => {
+ if (typeof binding === "string") {
+ return [name, { type: "plain", value: binding }] as const;
+ }
+ if (binding?.type === "secret_ref") {
+ return [
+ name,
+ {
+ type: "secret_ref",
+ secretId: typeof binding.secretId === "string" ? binding.secretId : "",
+ version: typeof binding.version === "number" ? binding.version : "latest",
+ },
+ ] as const;
+ }
+ if (binding?.type === "plain") {
+ return [
+ name,
+ { type: "plain", value: typeof binding.value === "string" ? binding.value : "" },
+ ] as const;
+ }
+ return [name, { type: "plain", value: "" }] as const;
+ })
+ .sort(([left], [right]) => left.localeCompare(right));
+ return JSON.stringify(entries);
+}
+
+function cloneRows(rows: readonly EnvRow[]): EnvRow[] {
+ return rows.map((row) => ({ ...row }));
+}
+
+function rowDirtyFields(row: EnvRow, committedRow: EnvRow | undefined): EnvironmentVariableDirtyFields {
+ if (!committedRow) {
+ return {
+ name: Boolean(row.name.trim()),
+ value:
+ row.source !== "text" ||
+ Boolean(row.textValue) ||
+ Boolean(row.secretId) ||
+ row.version !== "latest",
+ };
+ }
+
+ return {
+ name: row.name.trim() !== committedRow.name.trim(),
+ value:
+ row.source !== committedRow.source ||
+ row.textValue !== committedRow.textValue ||
+ row.secretId !== committedRow.secretId ||
+ row.version !== committedRow.version,
+ };
+}
+
+export interface EnvironmentVariablesEditorProps {
+ value: Record<string, EnvBinding>;
+ onChange: (next: Record<string, EnvBinding> | undefined) => void;
+ secrets: readonly CompanySecret[];
+ onCreateSecret: (name: string, value: string) => Promise<CompanySecret>;
+ /** Optional "Recently used" picker group + quick-bind chips. */
+ recentlyUsedSecrets?: readonly CompanySecret[];
+ /** Read-only rendering. */
+ disabled?: boolean;
+ /** Prefixes flagged as reserved/auto-provided. Default `["PAPERCLIP_"]`. */
+ reservedPrefixes?: readonly string[];
+ /** Context-specific hint line. `null` hides the default copy; omit for default. */
+ footerHint?: ReactNode | null;
+}
+
+export interface EnvironmentVariablesEditorHandle {
+ /**
+ * Promote the editor-local draft into the controlled value before an outer
+ * action reads parent state. Returns the promoted value when a draft existed.
+ */
+ flushPendingDraft: () => Record<string, EnvBinding> | null;
+}
+
+export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorHandle, EnvironmentVariablesEditorProps>(function EnvironmentVariablesEditor({
+ value,
+ onChange,
+ secrets,
+ onCreateSecret,
+ recentlyUsedSecrets,
+ disabled,
+ reservedPrefixes = DEFAULT_RESERVED_PREFIXES,
+ footerHint,
+}: EnvironmentVariablesEditorProps, ref) {
+ const toast = useOptionalToastActions();
+ const editorRootRef = useRef<HTMLDivElement | null>(null);
+ const [rows, setRows] = useState<EnvRow[]>(() => rowsFromValue(value));
+ const rowsRef = useRef(rows);
+ const [committedRows, setCommittedRows] = useState<EnvRow[]>(() => cloneRows(rows));
+ const initialValueKey = useMemo(() => normalizedEnvKey(value), []); // eslint-disable-line react-hooks/exhaustive-deps
+ const committedValueKeyRef = useRef(initialValueKey);
+ const lastPropValueKeyRef = useRef(initialValueKey);
+ const pendingSaveValueKeyRef = useRef<string | null>(null);
+ const [committedValueKey, setCommittedValueKey] = useState(initialValueKey);
+ // Seeded (already-committed) names are "touched" so a saved reserved/invalid
+ // var surfaces its message on load; freshly-typed rows wait for blur (§6.2).
+ const [touchedNames, setTouchedNames] = useState<ReadonlySet<string>>(
+ () => new Set(rowsFromValue(value).map((row) => row.name.trim()).filter(Boolean)),
+ );
+ const [pendingFocus, setPendingFocus] = useState<{ rowId: string; field: "name" | "value" } | null>(null);
+
+ useEffect(() => {
+ rowsRef.current = rows;
+ }, [rows]);
+
+ function markCommitted(nextValueKey: string, nextRows: readonly EnvRow[] = rowsRef.current) {
+ committedValueKeyRef.current = nextValueKey;
+ setCommittedValueKey(nextValueKey);
+ setCommittedRows(cloneRows(nextRows));
+ }
+
+ function touchCommittedNames(nextRows: EnvRow[]) {
+ setTouchedNames((prev) => {
+ const next = new Set(prev);
+ for (const row of nextRows) {
+ const name = row.name.trim();
+ if (name) next.add(name);
+ }
+ return next;
+ });
+ }
+
+ function adoptExternalValue(nextValue: Record<string, EnvBinding>): EnvRow[] {
+ const nextRows = rowsFromValue(nextValue);
+ setRows(nextRows);
+ touchCommittedNames(nextRows);
+ return nextRows;
+ }
+
+ // Controlled sync: clean external changes replace the editor rows, but dirty
+ // local drafts are never clobbered by refetches. A save echo only advances the
+ // committed baseline so the focused row keeps its local id.
+ useEffect(() => {
+ const incomingValueKey = normalizedEnvKey(value);
+ if (incomingValueKey === lastPropValueKeyRef.current) {
+ return;
+ }
+ lastPropValueKeyRef.current = incomingValueKey;
+
+ const draftValueKey = normalizedEnvKey(valueFromRows(rowsRef.current));
+ const draftIsDirty = draftValueKey !== committedValueKeyRef.current;
+ const matchesPendingSave = pendingSaveValueKeyRef.current === incomingValueKey;
+ if (matchesPendingSave) {
+ pendingSaveValueKeyRef.current = null;
+ }
+
+ if (!draftIsDirty) {
+ const nextRows = adoptExternalValue(value);
+ markCommitted(incomingValueKey, nextRows);
+ return;
+ }
+
+ if (matchesPendingSave || draftValueKey === incomingValueKey) {
+ touchCommittedNames(rowsRef.current);
+ markCommitted(incomingValueKey);
+ }
+ }, [value]);
+
+ const draftValue = useMemo(() => valueFromRows(rows), [rows]);
+ const draftValueKey = useMemo(() => normalizedEnvKey(draftValue), [draftValue]);
+ const hasUnsavedChanges = draftValueKey !== committedValueKey;
+
+ const flushPendingDraft = useCallback(() => {
+ if (disabled || !hasUnsavedChanges) return null;
+ pendingSaveValueKeyRef.current = draftValueKey;
+ flushSync(() => {
+ onChange(draftValue);
+ });
+ return draftValue ?? {};
+ }, [disabled, draftValue, draftValueKey, hasUnsavedChanges, onChange]);
+
+ useImperativeHandle(ref, () => ({ flushPendingDraft }), [flushPendingDraft]);
+
+ useEffect(() => {
+ const form = editorRootRef.current?.closest("form");
+ if (!form) return;
+
+ function handleSubmit() {
+ flushPendingDraft();
+ }
+
+ form.addEventListener("submit", handleSubmit, true);
+ return () => form.removeEventListener("submit", handleSubmit, true);
+ }, [flushPendingDraft]);
+
+ useEffect(() => {
+ const root = editorRootRef.current;
+ if (!root) return;
+ const currentRoot = root;
+
+ function handleDocumentClick(event: MouseEvent) {
+ const target = event.target;
+ if (!(target instanceof Element) || currentRoot.contains(target)) return;
+ const button = target.closest("button");
+ if (!button || button.disabled) return;
+ const label = `${button.getAttribute("aria-label") ?? ""} ${button.textContent ?? ""}`;
+ if (button.type === "submit" || /\b(save|create|update|test|import)\b/i.test(label)) {
+ flushPendingDraft();
+ }
+ }
+
+ document.addEventListener("click", handleDocumentClick, true);
+ return () => document.removeEventListener("click", handleDocumentClick, true);
+ }, [flushPendingDraft]);
+
+ function updateDraft(nextRows: EnvRow[]) {
+ setRows(nextRows);
+ }
+
+ function patchRow(id: string, patch: Partial<EnvRow>) {
+ updateDraft(rows.map((row) => (row.id === id ? { ...row, ...patch } : row)));
+ }
+
+ function removeRow(id: string) {
+ updateDraft(rows.filter((row) => row.id !== id));
+ }
+
+ function addRow() {
+ const row = emptyRow();
+ setRows([...rows, row]);
+ setPendingFocus({ rowId: row.id, field: "name" });
+ }
+
+ function markTouched(id: string) {
+ const rowName = rows.find((row) => row.id === id)?.name.trim();
+ if (!rowName) return;
+ setTouchedNames((prev) => {
+ if (prev.has(rowName)) return prev;
+ const next = new Set(prev);
+ next.add(rowName);
+ return next;
+ });
+ }
+
+ function bulkImport(text: string, targetRowId: string): boolean {
+ const pairs = parseDotenv(text);
+ if (pairs.length === 0) return false;
+ // Drop the empty row that received the paste, then upsert each pair.
+ const working = rows.filter((row) => row.id !== targetRowId).map((row) => ({ ...row }));
+ for (const { key, value: pairValue } of pairs) {
+ const existing = working.find((row) => row.name.trim() === key);
+ if (existing) {
+ existing.name = key;
+ existing.source = "text";
+ existing.textValue = pairValue;
+ existing.secretId = "";
+ existing.sensitiveDismissed = false;
+ } else {
+ working.push({ ...emptyRow(), name: key, textValue: pairValue });
+ }
+ }
+ updateDraft(working);
+ toast?.pushToast({ title: `Imported ${pairs.length} variable${pairs.length === 1 ? "" : "s"}`, tone: "success" });
+ return true;
+ }
+
+ function bindRecentSecret(secret: CompanySecret) {
+ const next = rows.map((row) => ({ ...row }));
+ const trailing = next[next.length - 1];
+ let target: EnvRow;
+ if (trailing && !trailing.name && !trailing.textValue && !trailing.secretId) {
+ target = trailing;
+ } else {
+ target = emptyRow();
+ next.push(target);
+ }
+ target.source = "secret";
+ target.secretId = secret.id;
+ target.version = "latest";
+ if (!target.name) target.name = envKeyFromSecretName(secret.name);
+ updateDraft(next);
+ }
+
+ function saveDraft() {
+ if (!hasUnsavedChanges) return;
+ pendingSaveValueKeyRef.current = draftValueKey;
+ onChange(draftValue);
+ }
+
+ function revertDraft() {
+ pendingSaveValueKeyRef.current = null;
+ lastPropValueKeyRef.current = normalizedEnvKey(value);
+ const nextRows = adoptExternalValue(value);
+ markCommitted(lastPropValueKeyRef.current, nextRows);
+ }
+
+ const duplicateNames = useMemo(() => computeDuplicateNames(rows), [rows]);
+
+ const attentionCount = useMemo(
+ () => rows.reduce((count, row) => (computeRowHealth(row, secrets) ? count + 1 : count), 0),
+ [rows, secrets],
+ );
+
+ const quickBind = useMemo(() => {
+ const boundIds = new Set(rows.filter((row) => row.source === "secret" && row.secretId).map((row) => row.secretId));
+ return (recentlyUsedSecrets ?? [])
+ .filter((secret) => secret.status === "active" && !boundIds.has(secret.id))
+ .slice(0, 8);
+ }, [recentlyUsedSecrets, rows]);
+
+ const hasRows = rows.length > 0;
+ const hint = footerHint === undefined ? DEFAULT_HINT : footerHint;
+ const committedRowsById = useMemo(
+ () => new Map(committedRows.map((row) => [row.id, row])),
+ [committedRows],
+ );
+
+ return (
+ <TooltipProvider>
+ <div ref={editorRootRef} className="@container/env space-y-2">
+ {attentionCount > 1 ? (
+ <p className="inline-flex items-center gap-1.5 text-[11px] font-medium text-amber-700 dark:text-amber-400">
+ <AlertCircle className="size-3.5" />
+ {attentionCount} bindings need attention
+ </p>
+ ) : null}
+
+ {hasRows ? (
+ <>
+ {/* Header (desktop only) */}
+ <div className="hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-[minmax(160px,2fr)_minmax(240px,3fr)_32px]">
+ <span className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Name</span>
+ <span className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Value</span>
+ <span />
+ </div>
+
+ {rows.map((row, index) => {
+ const issue = validateName(row.name, duplicateNames, reservedPrefixes);
+ const touched = touchedNames.has(row.name.trim());
+ return (
+ <EnvironmentVariableRow
+ key={row.id}
+ row={row}
+ isLast={index === rows.length - 1}
+ secrets={secrets}
+ recentlyUsedSecrets={recentlyUsedSecrets}
+ disabled={disabled}
+ nameIssue={issue}
+ showNameIssue={touched}
+ dirtyFields={rowDirtyFields(row, committedRowsById.get(row.id))}
+ onPatch={(patch) => patchRow(row.id, patch)}
+ onRemove={() => removeRow(row.id)}
+ onNameBlur={() => markTouched(row.id)}
+ onNamePaste={(text) => bulkImport(text, row.id)}
+ onEnterInValueLast={addRow}
+ onCreateSecret={onCreateSecret}
+ onToast={(message) => toast?.pushToast({ title: message, tone: "success" })}
+ focusRequest={pendingFocus?.rowId === row.id ? pendingFocus.field : null}
+ onFocusConsumed={() => setPendingFocus(null)}
+ />
+ );
+ })}
+ </>
+ ) : (
+ <p className="text-sm text-muted-foreground">No environment variables</p>
+ )}
+
+ {/* Footer bar */}
+ <div className="flex flex-wrap items-center justify-between gap-2 pt-1">
+ <button
+ type="button"
+ onClick={addRow}
+ disabled={disabled}
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
+ >
+ <Plus className="size-3.5" />
+ Add variable
+ </button>
+
+ {quickBind.length > 0 && !disabled ? (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground/70">
+ <KeyRound className="size-3" />
+ Recently used:
+ </span>
+ {quickBind.map((secret) => (
+ <button
+ key={secret.id}
+ type="button"
+ onClick={() => bindRecentSecret(secret)}
+ className="inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-[11px] text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
+ title={`Bind ${secret.name}`}
+ >
+ + {secret.name}
+ </button>
+ ))}
+ </div>
+ ) : null}
+
+ </div>
+
+ {hasUnsavedChanges && !disabled ? (
+ <div
+ role="status"
+ className="mt-3 flex w-full flex-col gap-3 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-3 text-amber-950 shadow-sm dark:bg-amber-500/15 dark:text-amber-100 @[34rem]/env:flex-row @[34rem]/env:items-center @[34rem]/env:justify-between"
+ >
+ <div className="flex min-w-0 items-center gap-2 text-sm font-medium">
+ <span className="size-2 rounded-full bg-amber-500 shadow-[0_0_0_3px_rgba(245,158,11,0.18)]" />
+ <span>Unsaved changes</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={revertDraft}
+ className="inline-flex h-9 items-center gap-1.5 rounded-md border border-amber-500/30 bg-background px-3 text-sm font-medium text-foreground transition-colors hover:bg-amber-500/10 dark:bg-background/80"
+ >
+ <RotateCcw className="size-4" />
+ Revert
+ </button>
+ <button
+ type="button"
+ onClick={saveDraft}
+ className="inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
+ >
+ <Save className="size-4" />
+ Save
+ </button>
+ </div>
+ </div>
+ ) : null}
+
+ {hint ? <p className="text-[11px] text-muted-foreground/70">{hint}</p> : null}
+ </div>
+ </TooltipProvider>
+ );
+});
+
+export type { EnvRow } from "./model";
+export { EnvironmentVariableRow } from "./Row";
+export { SecretPicker } from "./SecretPicker";
+export { CreateSecretPopover, ConvertToSecretPopover } from "./CreateSecretPopover";
+export { parseDotenv, looksLikeDotenv } from "./parse-dotenv";
+export { isSensitiveEnv } from "./sensitive";
diff --git a/ui/src/components/environment-variables-editor/model.test.ts b/ui/src/components/environment-variables-editor/model.test.ts
new file mode 100644
index 0000000000..2bb016afea
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/model.test.ts
@@ -0,0 +1,196 @@
+import { describe, expect, it } from "vitest";
+import type { CompanySecret } from "@paperclipai/shared";
+import {
+ computeDuplicateNames,
+ computeRowHealth,
+ emptyRow,
+ envKeyFromSecretName,
+ planSourceSwitch,
+ rowsFromValue,
+ secretNameFromKey,
+ validateName,
+ valueFromRows,
+ type EnvRow,
+} from "./model";
+
+function makeSecret(overrides: Partial<CompanySecret> & Pick<CompanySecret, "id">): CompanySecret {
+ return {
+ companyId: "co",
+ key: overrides.id,
+ name: overrides.id.toUpperCase(),
+ provider: "local_encrypted",
+ status: "active",
+ managedMode: "paperclip_managed",
+ externalRef: null,
+ providerConfigId: null,
+ providerMetadata: null,
+ latestVersion: 3,
+ description: null,
+ lastResolvedAt: null,
+ lastRotatedAt: null,
+ deletedAt: null,
+ createdByAgentId: null,
+ createdByUserId: null,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ ...overrides,
+ };
+}
+
+describe("rowsFromValue", () => {
+ it("returns no rows for empty/undefined input (no ghost row)", () => {
+ expect(rowsFromValue(undefined)).toEqual([]);
+ expect(rowsFromValue({})).toEqual([]);
+ });
+
+ it("maps legacy string, plain, and secret_ref bindings", () => {
+ const rows = rowsFromValue({
+ LEGACY: "raw",
+ PLAIN: { type: "plain", value: "v" },
+ REF: { type: "secret_ref", secretId: "s1", version: 2 },
+ REF_LATEST: { type: "secret_ref", secretId: "s2" },
+ });
+ expect(rows.map((r) => ({ name: r.name, source: r.source, textValue: r.textValue, secretId: r.secretId, version: r.version }))).toEqual([
+ { name: "LEGACY", source: "text", textValue: "raw", secretId: "", version: "latest" },
+ { name: "PLAIN", source: "text", textValue: "v", secretId: "", version: "latest" },
+ { name: "REF", source: "secret", textValue: "", secretId: "s1", version: 2 },
+ { name: "REF_LATEST", source: "secret", textValue: "", secretId: "s2", version: "latest" },
+ ]);
+ });
+});
+
+describe("valueFromRows (emit semantics)", () => {
+ function row(partial: Partial<EnvRow>): EnvRow {
+ return { ...emptyRow(), ...partial };
+ }
+
+ it("emits undefined when there are no complete rows", () => {
+ expect(valueFromRows([])).toBeUndefined();
+ expect(valueFromRows([row({ name: "" })])).toBeUndefined();
+ });
+
+ it("drops rows with empty (trimmed) names", () => {
+ expect(valueFromRows([row({ name: " ", textValue: "x" })])).toBeUndefined();
+ });
+
+ it("drops secret rows without a chosen secret (incomplete ref)", () => {
+ expect(valueFromRows([row({ name: "A", source: "secret", secretId: "" })])).toBeUndefined();
+ });
+
+ it("emits plain and secret_ref bindings", () => {
+ expect(
+ valueFromRows([
+ row({ name: "A", source: "text", textValue: "1" }),
+ row({ name: "B", source: "secret", secretId: "s1", version: 2 }),
+ ]),
+ ).toEqual({
+ A: { type: "plain", value: "1" },
+ B: { type: "secret_ref", secretId: "s1", version: 2 },
+ });
+ });
+
+ it("is last-writer-wins on duplicate names", () => {
+ expect(
+ valueFromRows([
+ row({ name: "A", textValue: "first" }),
+ row({ name: "A", textValue: "second" }),
+ ]),
+ ).toEqual({ A: { type: "plain", value: "second" } });
+ });
+});
+
+describe("validateName", () => {
+ const reserved = ["PAPERCLIP_"];
+
+ it("returns null for empty and valid names", () => {
+ expect(validateName("", new Set(), reserved)).toBeNull();
+ expect(validateName("GH_TOKEN", new Set(), reserved)).toBeNull();
+ expect(validateName("_private1", new Set(), reserved)).toBeNull();
+ });
+
+ it("flags invalid charset", () => {
+ expect(validateName("1BAD", new Set(), reserved)?.level).toBe("error");
+ expect(validateName("has-dash", new Set(), reserved)?.message).toMatch(/letters, digits/);
+ });
+
+ it("flags duplicates as errors", () => {
+ expect(validateName("DUP", new Set(["DUP"]), reserved)).toEqual({ level: "error", message: "Duplicate name" });
+ });
+
+ it("flags reserved prefixes as warnings", () => {
+ const issue = validateName("PAPERCLIP_HOME", new Set(), reserved);
+ expect(issue?.level).toBe("warn");
+ expect(issue?.message).toMatch(/Reserved prefix/);
+ });
+
+ it("charset error takes precedence over reserved prefix", () => {
+ expect(validateName("PAPERCLIP-X", new Set(), reserved)?.level).toBe("error");
+ });
+});
+
+describe("computeDuplicateNames", () => {
+ it("collects names appearing more than once", () => {
+ const rows = [
+ { ...emptyRow(), name: "A" },
+ { ...emptyRow(), name: "A" },
+ { ...emptyRow(), name: "B" },
+ { ...emptyRow(), name: "" },
+ ];
+ expect([...computeDuplicateNames(rows)]).toEqual(["A"]);
+ });
+});
+
+describe("computeRowHealth", () => {
+ const secrets = [makeSecret({ id: "active" }), makeSecret({ id: "disabled", status: "disabled" })];
+
+ it("returns null for healthy secret and text rows", () => {
+ expect(computeRowHealth({ ...emptyRow(), source: "text", name: "A", textValue: "x" }, secrets)).toBeNull();
+ expect(computeRowHealth({ ...emptyRow(), source: "secret", secretId: "active" }, secrets)).toBeNull();
+ });
+
+ it("flags a missing secret as an error", () => {
+ expect(computeRowHealth({ ...emptyRow(), source: "secret", secretId: "gone" }, secrets)?.kind).toBe("missing");
+ });
+
+ it("flags a disabled secret as a warning", () => {
+ expect(computeRowHealth({ ...emptyRow(), source: "secret", secretId: "disabled" }, secrets)?.kind).toBe("disabled");
+ });
+});
+
+describe("planSourceSwitch (§6.3)", () => {
+ it("is a noop when the source is unchanged", () => {
+ expect(planSourceSwitch({ ...emptyRow(), source: "text" }, "text")).toEqual({ kind: "noop" });
+ });
+
+ it("preserves a non-empty value on Text→Secret by opening the store popover", () => {
+ const plan = planSourceSwitch({ ...emptyRow(), name: "GH_TOKEN", source: "text", textValue: "abc" }, "secret");
+ expect(plan).toEqual({ kind: "open-store", name: "gh_token", value: "abc" });
+ });
+
+ it("switches straight to secret when the text value is empty", () => {
+ expect(planSourceSwitch({ ...emptyRow(), source: "text", textValue: " " }, "secret")).toEqual({ kind: "to-secret" });
+ });
+
+ it("offers undo on Secret→Text when a secret was bound", () => {
+ const row = { ...emptyRow(), source: "secret" as const, secretId: "s1", version: 2 as const };
+ const plan = planSourceSwitch(row, "text");
+ expect(plan.kind).toBe("to-text");
+ if (plan.kind === "to-text") expect(plan.undoFrom?.secretId).toBe("s1");
+ });
+
+ it("does not offer undo on Secret→Text when no secret was bound", () => {
+ const plan = planSourceSwitch({ ...emptyRow(), source: "secret" }, "text");
+ expect(plan).toEqual({ kind: "to-text", undoFrom: null });
+ });
+});
+
+describe("name suggestion helpers", () => {
+ it("secretNameFromKey lowercases to snake", () => {
+ expect(secretNameFromKey("GH_TOKEN")).toBe("gh_token");
+ expect(secretNameFromKey("Stripe-API-Key!")).toBe("stripe_api_key");
+ });
+
+ it("envKeyFromSecretName uppercases to snake", () => {
+ expect(envKeyFromSecretName("github token")).toBe("GITHUB_TOKEN");
+ });
+});
diff --git a/ui/src/components/environment-variables-editor/model.ts b/ui/src/components/environment-variables-editor/model.ts
new file mode 100644
index 0000000000..8a6c7eb60e
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/model.ts
@@ -0,0 +1,216 @@
+import type { CompanySecret, EnvBinding, SecretVersionSelector } from "@paperclipai/shared";
+
+export type RowSource = "text" | "secret";
+
+/** Local, per-row UI state. Only a subset is emitted upward (see {@link valueFromRows}). */
+export interface EnvRow {
+ /** Stable local id — used as React key and to target popovers/undo. */
+ id: string;
+ name: string;
+ source: RowSource;
+ textValue: string;
+ secretId: string;
+ version: SecretVersionSelector;
+ /** Session-local dismissal of the sensitive-value suggestion (§6.6). */
+ sensitiveDismissed?: boolean;
+}
+
+let rowCounter = 0;
+export function nextRowId(): string {
+ rowCounter += 1;
+ return `env-row-${rowCounter}`;
+}
+
+export function emptyRow(source: RowSource = "text"): EnvRow {
+ return { id: nextRowId(), name: "", source, textValue: "", secretId: "", version: "latest" };
+}
+
+function isSecretRef(binding: unknown): binding is { type: "secret_ref"; secretId?: unknown; version?: unknown } {
+ return (
+ typeof binding === "object" &&
+ binding !== null &&
+ "type" in binding &&
+ (binding as { type?: unknown }).type === "secret_ref"
+ );
+}
+
+function isPlainObj(binding: unknown): binding is { type: "plain"; value?: unknown } {
+ return (
+ typeof binding === "object" &&
+ binding !== null &&
+ "type" in binding &&
+ (binding as { type?: unknown }).type === "plain"
+ );
+}
+
+/** Build editor rows from the controlled value. No implicit trailing ghost row. */
+export function rowsFromValue(value: Record<string, EnvBinding> | null | undefined): EnvRow[] {
+ if (!value || typeof value !== "object") return [];
+ return Object.entries(value).map(([name, binding]) => {
+ if (typeof binding === "string") {
+ return { id: nextRowId(), name, source: "text" as const, textValue: binding, secretId: "", version: "latest" as const };
+ }
+ if (isSecretRef(binding)) {
+ const version: SecretVersionSelector = typeof binding.version === "number" ? binding.version : "latest";
+ return {
+ id: nextRowId(),
+ name,
+ source: "secret" as const,
+ textValue: "",
+ secretId: typeof binding.secretId === "string" ? binding.secretId : "",
+ version,
+ };
+ }
+ if (isPlainObj(binding)) {
+ return {
+ id: nextRowId(),
+ name,
+ source: "text" as const,
+ textValue: typeof binding.value === "string" ? binding.value : "",
+ secretId: "",
+ version: "latest" as const,
+ };
+ }
+ return { id: nextRowId(), name, source: "text" as const, textValue: "", secretId: "", version: "latest" as const };
+ });
+}
+
+/**
+ * Emit semantics (plan §4/§6.1): rows with empty (trimmed) names are dropped;
+ * secret rows without a chosen secret are incomplete and dropped; an empty
+ * result emits `undefined`. Duplicate names are last-writer-wins (unchanged).
+ */
+export function valueFromRows(rows: EnvRow[]): Record<string, EnvBinding> | undefined {
+ const record: Record<string, EnvBinding> = {};
+ for (const row of rows) {
+ const name = row.name.trim();
+ if (!name) continue;
+ if (row.source === "secret") {
+ if (!row.secretId) continue; // incomplete ref — not emitted
+ record[name] = { type: "secret_ref", secretId: row.secretId, version: row.version };
+ } else {
+ record[name] = { type: "plain", value: row.textValue };
+ }
+ }
+ return Object.keys(record).length > 0 ? record : undefined;
+}
+
+export const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+export type NameIssueLevel = "error" | "warn";
+export interface NameIssue {
+ level: NameIssueLevel;
+ message: string;
+}
+
+/**
+ * Validate a single row's name given the full set of names (for duplicate
+ * detection). Returns null when the name is empty (not yet an error) or valid.
+ */
+export function validateName(
+ name: string,
+ duplicateNames: ReadonlySet<string>,
+ reservedPrefixes: readonly string[],
+): NameIssue | null {
+ const trimmed = name.trim();
+ if (!trimmed) return null;
+ if (!ENV_NAME_RE.test(trimmed)) {
+ return { level: "error", message: "Invalid name — use letters, digits and _" };
+ }
+ if (duplicateNames.has(trimmed)) {
+ return { level: "error", message: "Duplicate name" };
+ }
+ for (const prefix of reservedPrefixes) {
+ if (prefix && trimmed.startsWith(prefix)) {
+ return { level: "warn", message: "Reserved prefix — provided automatically and may be overridden" };
+ }
+ }
+ return null;
+}
+
+/** Names that appear on more than one row (trimmed, non-empty). */
+export function computeDuplicateNames(rows: EnvRow[]): Set<string> {
+ const counts = new Map<string, number>();
+ for (const row of rows) {
+ const name = row.name.trim();
+ if (!name) continue;
+ counts.set(name, (counts.get(name) ?? 0) + 1);
+ }
+ const dupes = new Set<string>();
+ for (const [name, count] of counts) {
+ if (count > 1) dupes.add(name);
+ }
+ return dupes;
+}
+
+/**
+ * Pure decision for a source switch (§6.3), extracted so the value-preserving
+ * behaviour is unit-testable without driving the Radix menu.
+ */
+export type SourceSwitchPlan =
+ | { kind: "noop" }
+ /** Text → Secret with a non-empty value: never discard it — open Store-as-secret. */
+ | { kind: "open-store"; name: string; value: string }
+ /** Text → Secret with an empty value: switch and open the picker. */
+ | { kind: "to-secret" }
+ /** Secret → Text: clear the ref; offer undo when a secret was bound. */
+ | { kind: "to-text"; undoFrom: EnvRow | null };
+
+export function planSourceSwitch(row: EnvRow, next: RowSource): SourceSwitchPlan {
+ if (next === row.source) return { kind: "noop" };
+ if (next === "secret") {
+ if (row.textValue.trim()) {
+ return { kind: "open-store", name: secretNameFromKey(row.name) || "secret", value: row.textValue };
+ }
+ return { kind: "to-secret" };
+ }
+ return { kind: "to-text", undoFrom: row.secretId ? { ...row } : null };
+}
+
+export interface SecretHealth {
+ level: "error" | "warn";
+ message: string;
+ /** Short label for the summary line at the top of the editor. */
+ kind: "missing" | "disabled";
+}
+
+/** Per-row secret-binding health (plan §6.8). Null when healthy or not a bound ref. */
+export function computeRowHealth(row: EnvRow, secrets: readonly CompanySecret[]): SecretHealth | null {
+ if (row.source !== "secret" || !row.secretId) return null;
+ const secret = secrets.find((candidate) => candidate.id === row.secretId);
+ if (!secret) {
+ return {
+ level: "error",
+ kind: "missing",
+ message: "This secret no longer exists — runs will fail until you rebind.",
+ };
+ }
+ if (secret.status !== "active") {
+ return {
+ level: "warn",
+ kind: "disabled",
+ message: "Runs will fail until re-enabled or rebound.",
+ };
+ }
+ return null;
+}
+
+/** Suggest a `lower_snake` secret name from an env KEY (plan §6.5). */
+export function secretNameFromKey(key: string): string {
+ return key
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9_]+/g, "_")
+ .replace(/^_+|_+$/g, "")
+ .slice(0, 64);
+}
+
+/** Suggest an env KEY (UPPER_SNAKE) from a secret name (for quick-bind). */
+export function envKeyFromSecretName(name: string): string {
+ return name
+ .trim()
+ .toUpperCase()
+ .replace(/[^A-Z0-9_]+/g, "_")
+ .replace(/^_+|_+$/g, "")
+ .slice(0, 64);
+}
diff --git a/ui/src/components/environment-variables-editor/parse-dotenv.test.ts b/ui/src/components/environment-variables-editor/parse-dotenv.test.ts
new file mode 100644
index 0000000000..77619bdeaa
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/parse-dotenv.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+import { looksLikeDotenv, parseDotenv } from "./parse-dotenv";
+
+describe("parseDotenv", () => {
+ it("parses simple KEY=VALUE lines in order", () => {
+ expect(parseDotenv("FOO=bar\nBAZ=qux")).toEqual([
+ { key: "FOO", value: "bar" },
+ { key: "BAZ", value: "qux" },
+ ]);
+ });
+
+ it("ignores comments and blank lines", () => {
+ const text = "# a comment\n\nFOO=bar\n \n# another\nBAZ=qux\n";
+ expect(parseDotenv(text)).toEqual([
+ { key: "FOO", value: "bar" },
+ { key: "BAZ", value: "qux" },
+ ]);
+ });
+
+ it("tolerates a leading `export`", () => {
+ expect(parseDotenv("export TOKEN=abc123")).toEqual([{ key: "TOKEN", value: "abc123" }]);
+ });
+
+ it("strips a single layer of matching quotes", () => {
+ expect(parseDotenv('A="hello world"\nB=\'single\'')).toEqual([
+ { key: "A", value: "hello world" },
+ { key: "B", value: "single" },
+ ]);
+ });
+
+ it("keeps `=` characters inside the value", () => {
+ expect(parseDotenv("DB_URL=postgres://u:p@host/db?x=1")).toEqual([
+ { key: "DB_URL", value: "postgres://u:p@host/db?x=1" },
+ ]);
+ });
+
+ it("strips trailing inline comments on unquoted values", () => {
+ expect(parseDotenv("FOO=bar # trailing")).toEqual([{ key: "FOO", value: "bar" }]);
+ });
+
+ it("skips lines with invalid keys", () => {
+ expect(parseDotenv("1BAD=x\n-also-bad=y\nGOOD=z")).toEqual([{ key: "GOOD", value: "z" }]);
+ });
+
+ it("returns an empty array for text with no assignments", () => {
+ expect(parseDotenv("just some prose\nwith no equals")).toEqual([]);
+ });
+
+ it("allows empty values", () => {
+ expect(parseDotenv("EMPTY=")).toEqual([{ key: "EMPTY", value: "" }]);
+ });
+});
+
+describe("looksLikeDotenv", () => {
+ it("is true for a single KEY=VALUE", () => {
+ expect(looksLikeDotenv("FOO=bar")).toBe(true);
+ });
+
+ it("is false for a bare token with no equals", () => {
+ expect(looksLikeDotenv("ghp_1234567890abcdef")).toBe(false);
+ });
+
+ it("is false for prose that happens to contain an equals but no valid key", () => {
+ expect(looksLikeDotenv("1 = 1")).toBe(false);
+ });
+});
diff --git a/ui/src/components/environment-variables-editor/parse-dotenv.ts b/ui/src/components/environment-variables-editor/parse-dotenv.ts
new file mode 100644
index 0000000000..5db4d9665a
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/parse-dotenv.ts
@@ -0,0 +1,64 @@
+/**
+ * Minimal `.env`-style parser for bulk-pasting environment variables into the
+ * editor (plan §6.9). Deliberately forgiving: it ignores comments and blank
+ * lines, tolerates a leading `export `, strips one layer of matching quotes,
+ * and returns key/value pairs in source order. It is NOT a full dotenv
+ * implementation (no variable interpolation, no multi-line values).
+ */
+export interface ParsedEnvPair {
+ key: string;
+ value: string;
+}
+
+/** A KEY at the start of a line, optionally prefixed with `export `. */
+const LINE_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
+
+function stripInlineComment(value: string): string {
+ // Only strip a ` #comment` when the value is unquoted. Quoted values are
+ // handled by the caller before this runs, so here we only see bare values.
+ const hashIndex = value.indexOf(" #");
+ if (hashIndex >= 0) return value.slice(0, hashIndex);
+ return value;
+}
+
+function unquote(raw: string): string {
+ const trimmed = raw.trim();
+ if (trimmed.length >= 2) {
+ const first = trimmed[0];
+ const last = trimmed[trimmed.length - 1];
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
+ return trimmed.slice(1, -1);
+ }
+ }
+ return stripInlineComment(trimmed).trim();
+}
+
+/**
+ * Returns the parsed pairs, or an empty array when nothing looks like an env
+ * assignment. Callers can treat an empty result as "not a dotenv paste" and
+ * fall through to the browser's default paste handling.
+ */
+export function parseDotenv(text: string): ParsedEnvPair[] {
+ const pairs: ParsedEnvPair[] = [];
+ for (const rawLine of text.split(/\r?\n/)) {
+ const line = rawLine.trim();
+ if (!line || line.startsWith("#")) continue;
+ const match = LINE_RE.exec(line);
+ if (!match) continue;
+ const key = match[1];
+ const value = unquote(match[2]);
+ pairs.push({ key, value });
+ }
+ return pairs;
+}
+
+/**
+ * Heuristic: does a paste look like a `.env` block worth importing? We require
+ * either more than one parsed pair, or a single pair that spans a genuine
+ * `KEY=VALUE` (so a lone `FOO=bar` typed into an empty name still imports, but
+ * pasting a bare token like `ghp_xxx` does not hijack the field).
+ */
+export function looksLikeDotenv(text: string): boolean {
+ if (!text.includes("=")) return false;
+ return parseDotenv(text).length > 0;
+}
diff --git a/ui/src/components/environment-variables-editor/sensitive.test.ts b/ui/src/components/environment-variables-editor/sensitive.test.ts
new file mode 100644
index 0000000000..fdc5048d7b
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/sensitive.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from "vitest";
+import { isSensitiveEnv } from "./sensitive";
+
+describe("isSensitiveEnv", () => {
+ it("is false for an empty value regardless of name", () => {
+ expect(isSensitiveEnv("API_KEY", "")).toBe(false);
+ });
+
+ it("flags credential-shaped names (regex shared with the server migration)", () => {
+ expect(isSensitiveEnv("STRIPE_API_KEY", "x")).toBe(true);
+ expect(isSensitiveEnv("DB_PASSWORD", "x")).toBe(true);
+ expect(isSensitiveEnv("MY_SECRET", "x")).toBe(true);
+ expect(isSensitiveEnv("ACCESS_TOKEN", "x")).toBe(true);
+ expect(isSensitiveEnv("GH_AUTH_TOKEN", "x")).toBe(true);
+ });
+
+ it("does not flag benign names with short values", () => {
+ expect(isSensitiveEnv("NODE_ENV", "production")).toBe(false);
+ expect(isSensitiveEnv("PORT", "3000")).toBe(false);
+ // A bare `TOKEN` in the name is intentionally NOT matched by name alone
+ // (the server regex only matches access_token / auth_token).
+ expect(isSensitiveEnv("GH_TOKEN", "short")).toBe(false);
+ });
+
+ it("flags known credential value shapes even with benign names", () => {
+ expect(isSensitiveEnv("CONFIG", "sk-abcdefghijklmnopqrst")).toBe(true);
+ expect(isSensitiveEnv("CONFIG", "ghp_0123456789abcdef0123456789abcdef")).toBe(true);
+ expect(isSensitiveEnv("CONFIG", "xoxb-123456789012-abcdefghijkl")).toBe(true);
+ expect(isSensitiveEnv("CONFIG", "-----BEGIN RSA PRIVATE KEY-----")).toBe(true);
+ });
+
+ it("flags long high-entropy tokens", () => {
+ expect(isSensitiveEnv("CONFIG", "aB3xY7zQ9mN2pR5tK8wL1vC4")).toBe(true);
+ });
+
+ it("does not flag long lowercase-only prose/paths", () => {
+ expect(isSensitiveEnv("PATH", "/usr/local/bin/some/long/path/here")).toBe(false);
+ expect(isSensitiveEnv("GREETING", "hello there this is a message")).toBe(false);
+ });
+});
diff --git a/ui/src/components/environment-variables-editor/sensitive.ts b/ui/src/components/environment-variables-editor/sensitive.ts
new file mode 100644
index 0000000000..0c7d1cae5d
--- /dev/null
+++ b/ui/src/components/environment-variables-editor/sensitive.ts
@@ -0,0 +1,46 @@
+/**
+ * Sensitive-value detection (plan §6.6). Kept in sync with the server-side
+ * migration heuristic so the UI flags the same things the backend would.
+ * Source of the key regex: `scripts/migrate-inline-env-secrets.ts:5`.
+ */
+
+/** Env-var NAMES that conventionally hold credentials. */
+export const SENSITIVE_ENV_KEY_RE =
+ /(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i;
+
+/** Well-known credential value shapes (provider token prefixes, PEM headers). */
+const CREDENTIAL_VALUE_RES: RegExp[] = [
+ /^sk-[A-Za-z0-9-_]{16,}$/, // OpenAI / Stripe style
+ /^gh[pousr]_[A-Za-z0-9]{20,}$/, // GitHub PAT / OAuth / server / refresh
+ /^github_pat_[A-Za-z0-9_]{20,}$/, // GitHub fine-grained PAT
+ /^xox[baprs]-[A-Za-z0-9-]{10,}$/, // Slack tokens
+ /^AKIA[0-9A-Z]{16}$/, // AWS access key id
+ /^AIza[0-9A-Za-z\-_]{20,}$/, // Google API key
+ /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/, // PEM private key
+ /^eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/, // JWT
+];
+
+function looksHighEntropy(value: string): boolean {
+ // A long, unbroken, mixed token (base64/hex/opaque secret) with no spaces.
+ if (value.length < 24) return false;
+ if (/\s/.test(value)) return false;
+ if (!/^[A-Za-z0-9+/=_\-.]+$/.test(value)) return false;
+ const hasLower = /[a-z]/.test(value);
+ const hasUpper = /[A-Z]/.test(value);
+ const hasDigit = /[0-9]/.test(value);
+ // Require at least two character classes so plain lowercase words/paths
+ // (e.g. a long file path) don't trip the heuristic.
+ const classes = [hasLower, hasUpper, hasDigit].filter(Boolean).length;
+ return classes >= 2;
+}
+
+/**
+ * Returns true when a Text-source binding looks like it holds a secret and
+ * should be surfaced with the "Store as secret" suggestion.
+ */
+export function isSensitiveEnv(name: string, value: string): boolean {
+ if (!value) return false;
+ if (SENSITIVE_ENV_KEY_RE.test(name)) return true;
+ if (CREDENTIAL_VALUE_RES.some((re) => re.test(value))) return true;
+ return looksHighEntropy(value);
+}
diff --git a/ui/src/components/routine-sections/editable-sections.tsx b/ui/src/components/routine-sections/editable-sections.tsx
index f574a2cb50..2062f7e317 100644
--- a/ui/src/components/routine-sections/editable-sections.tsx
+++ b/ui/src/components/routine-sections/editable-sections.tsx
@@ -33,7 +33,7 @@ import { MarkdownEditor } from "../MarkdownEditor";
import { ScheduleEditor, getScheduleCronValidation } from "../ScheduleEditor";
import { RoutineVariablesEditor, RoutineVariablesHint } from "../RoutineVariablesEditor";
import { RoutineTriggerCard } from "../RoutineTriggerCard";
-import { EnvVarEditor } from "../EnvVarEditor";
+import { EnvironmentVariablesEditor } from "../environment-variables-editor";
import { createDefaultNewTrigger, useRoutineDetail } from "./context";
import type { EnvBinding, RoutineDetail as RoutineDetailType } from "@paperclipai/shared";
@@ -649,7 +649,7 @@ export function SecretsSection() {
</div>
) : null}
- <EnvVarEditor
+ <EnvironmentVariablesEditor
value={(editDraft.env ?? {}) as Record<string, EnvBinding>}
secrets={availableSecrets}
recentlyUsedSecrets={recentlyUsedSecrets}
diff --git a/ui/src/pages/CompanyEnvironments.test.tsx b/ui/src/pages/CompanyEnvironments.test.tsx
index 5585ab2e2f..de4f28833d 100644
--- a/ui/src/pages/CompanyEnvironments.test.tsx
+++ b/ui/src/pages/CompanyEnvironments.test.tsx
@@ -44,6 +44,8 @@ vi.mock("@/context/BreadcrumbContext", () => ({
vi.mock("@/context/ToastContext", () => ({
useToast: () => ({ pushToast: vi.fn() }),
+ useToastActions: () => ({ pushToast: vi.fn() }),
+ useOptionalToastActions: () => ({ pushToast: vi.fn() }),
}));
vi.mock("@/api/environments", () => ({
@@ -114,6 +116,12 @@ function click(element: Element | null | undefined) {
element?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
}
+function setInputValue(input: HTMLInputElement, value: string) {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ setter?.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+}
+
function getOpenDialog(): HTMLElement | null {
return document.body.querySelector("[role='dialog']");
}
@@ -376,6 +384,16 @@ describe("CompanyEnvironments — test provider button", () => {
Array.from(dialog?.querySelectorAll("input") ?? []).some((input) => (input as HTMLInputElement).value === "Alpha"),
).toBe(true);
+ await act(async () => click(findButton(dialog!, "Add variable")));
+ await flushReact();
+ const variableName = dialog!.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!;
+ const variableValue = dialog!.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
+ await act(async () => {
+ setInputValue(variableName, "API_TOKEN");
+ setInputValue(variableValue, "draft-token");
+ });
+ await flushReact();
+
await act(async () => {
findButton(document.body, "Save environment")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
@@ -383,7 +401,11 @@ describe("CompanyEnvironments — test provider button", () => {
expect(mockEnvironmentsApi.update).toHaveBeenCalledExactlyOnceWith(
"env-1",
- expect.objectContaining({ name: "Alpha", driver: "sandbox" }),
+ expect.objectContaining({
+ name: "Alpha",
+ driver: "sandbox",
+ envVars: { API_TOKEN: { type: "plain", value: "draft-token" } },
+ }),
);
expect(getOpenDialog()).toBeNull();
});
diff --git a/ui/src/pages/CompanyEnvironments.tsx b/ui/src/pages/CompanyEnvironments.tsx
index 757ab83b33..e8abcff00f 100644
--- a/ui/src/pages/CompanyEnvironments.tsx
+++ b/ui/src/pages/CompanyEnvironments.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, Play, RefreshCw, RotateCcw, Trash2, X } from "lucide-react";
import {
@@ -25,7 +25,10 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import { EnvVarEditor } from "@/components/EnvVarEditor";
+import {
+ EnvironmentVariablesEditor,
+ type EnvironmentVariablesEditorHandle,
+} from "@/components/environment-variables-editor";
import { JsonSchemaForm, getDefaultValues, validateJsonSchemaForm } from "@/components/JsonSchemaForm";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useCompany } from "@/context/CompanyContext";
@@ -592,6 +595,7 @@ export function CompanyEnvironments() {
const [environmentDialogOpen, setEnvironmentDialogOpen] = useState(false);
const [editingEnvironmentId, setEditingEnvironmentId] = useState<string | null>(null);
const [environmentForm, setEnvironmentForm] = useState<EnvironmentFormState>(createEmptyEnvironmentForm);
+ const environmentVariablesEditorRef = useRef<EnvironmentVariablesEditorHandle | null>(null);
const [probeResults, setProbeResults] = useState<Record<string, EnvironmentProbeResult | null>>({});
const [testingEnvironmentId, setTestingEnvironmentId] = useState<string | null>(null);
@@ -830,6 +834,11 @@ export function CompanyEnvironments() {
draftEnvironmentProbeMutation.reset();
}
+ function flushEnvironmentForm(): EnvironmentFormState {
+ const flushedEnvVars = environmentVariablesEditorRef.current?.flushPendingDraft();
+ return flushedEnvVars ? { ...environmentForm, envVars: flushedEnvVars } : environmentForm;
+ }
+
const discoveredPluginSandboxProviders = Object.entries(environmentCapabilities?.sandboxProviders ?? {})
.filter(([provider, capability]) => provider !== "fake" && capability.supportsRunExecution)
.map(([provider, capability]) => ({
@@ -1265,7 +1274,8 @@ export function CompanyEnvironments() {
label="Environment variables"
hint="Injected into runs that resolve through this environment. Use plain values or company secrets."
>
- <EnvVarEditor
+ <EnvironmentVariablesEditor
+ ref={environmentVariablesEditorRef}
value={environmentForm.envVars}
secrets={secrets ?? []}
onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}
@@ -1300,14 +1310,14 @@ export function CompanyEnvironments() {
{environmentForm.driver !== "local" ? (
<Button
variant="outline"
- onClick={() => draftEnvironmentProbeMutation.mutate(environmentForm)}
+ onClick={() => draftEnvironmentProbeMutation.mutate(flushEnvironmentForm())}
disabled={draftEnvironmentProbeMutation.isPending || !environmentFormValid}
>
{draftEnvironmentProbeMutation.isPending ? "Testing..." : "Test"}
</Button>
) : null}
<Button
- onClick={() => environmentMutation.mutate(environmentForm)}
+ onClick={() => environmentMutation.mutate(flushEnvironmentForm())}
disabled={environmentMutation.isPending || !environmentFormValid}
>
{environmentMutation.isPending
diff --git a/ui/src/pages/CompanySettings.test.tsx b/ui/src/pages/CompanySettings.test.tsx
index 74c43a0ca4..491c72602c 100644
--- a/ui/src/pages/CompanySettings.test.tsx
+++ b/ui/src/pages/CompanySettings.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { act } from "react";
+import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { AGENT_ADAPTER_TYPES, getEnvironmentCapabilities } from "@paperclipai/shared";
@@ -77,6 +77,8 @@ vi.mock("../context/ToastContext", () => ({
useToast: () => ({
pushToast: mockPushToast,
}),
+ useToastActions: () => ({ pushToast: mockPushToast }),
+ useOptionalToastActions: () => ({ pushToast: mockPushToast }),
}));
vi.mock("../context/CompanyContext", () => ({
@@ -105,6 +107,14 @@ class ResizeObserverStub {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).ResizeObserver = (globalThis as any).ResizeObserver ?? ResizeObserverStub;
+async function act(callback: () => void | Promise<void>) {
+ let result: void | Promise<void> = undefined;
+ flushSync(() => {
+ result = callback();
+ });
+ await result;
+}
+
async function flushReact() {
await act(async () => {
await Promise.resolve();
diff --git a/ui/src/pages/DesignGuide.tsx b/ui/src/pages/DesignGuide.tsx
index ea20407bb4..4e65b3df47 100644
--- a/ui/src/pages/DesignGuide.tsx
+++ b/ui/src/pages/DesignGuide.tsx
@@ -127,6 +127,8 @@ import { Identity } from "@/components/Identity";
import { IssueReferencePill } from "@/components/IssueReferencePill";
import { MembershipAction } from "@/components/MembershipAction";
import { IssueOutputSection } from "@/components/issue-output/IssueOutputSection";
+import { EnvironmentVariablesEditor } from "@/components/environment-variables-editor";
+import type { CompanySecret, EnvBinding } from "@paperclipai/shared";
import {
EnvInputsList,
ExternalSourcesList,
@@ -259,6 +261,78 @@ function TeamCardShowcase() {
);
}
+// Reusable environment-variables editor: one shared grid, in-field source
+// switch, fuzzy secret picker, sensitive-value detection, inline health.
+const DESIGN_GUIDE_SECRETS: CompanySecret[] = [
+ {
+ id: "dg-github",
+ companyId: "dg",
+ key: "github_token",
+ name: "GITHUB_TOKEN",
+ provider: "local_encrypted",
+ status: "active",
+ managedMode: "paperclip_managed",
+ externalRef: null,
+ providerConfigId: null,
+ providerMetadata: null,
+ latestVersion: 3,
+ description: null,
+ lastResolvedAt: null,
+ lastRotatedAt: null,
+ deletedAt: null,
+ createdByAgentId: null,
+ createdByUserId: null,
+ createdAt: new Date("2026-03-01T10:00:00.000Z"),
+ updatedAt: new Date("2026-03-01T10:00:00.000Z"),
+ },
+ {
+ id: "dg-db",
+ companyId: "dg",
+ key: "db_connection",
+ name: "DB_CONNECTION",
+ provider: "local_encrypted",
+ status: "active",
+ managedMode: "paperclip_managed",
+ externalRef: null,
+ providerConfigId: null,
+ providerMetadata: null,
+ latestVersion: 3,
+ description: null,
+ lastResolvedAt: null,
+ lastRotatedAt: null,
+ deletedAt: null,
+ createdByAgentId: null,
+ createdByUserId: null,
+ createdAt: new Date("2026-03-01T10:00:00.000Z"),
+ updatedAt: new Date("2026-03-01T10:00:00.000Z"),
+ },
+];
+
+function EnvironmentVariablesEditorShowcase() {
+ const [env, setEnv] = useState<Record<string, EnvBinding>>({
+ NODE_ENV: { type: "plain", value: "production" },
+ GH_TOKEN: { type: "secret_ref", secretId: "dg-github", version: "latest" },
+ DB_URL: { type: "secret_ref", secretId: "dg-db", version: 3 },
+ STRIPE_API_KEY: { type: "plain", value: "sk-live-51H8xL0aBcDeFgHiJkLmNoPq" },
+ });
+ return (
+ <div className="max-w-[640px] rounded-md border border-border p-4">
+ <EnvironmentVariablesEditor
+ value={env}
+ secrets={DESIGN_GUIDE_SECRETS}
+ onChange={(next) => setEnv(next ?? {})}
+ onCreateSecret={async (name) => ({
+ ...DESIGN_GUIDE_SECRETS[0]!,
+ id: `dg-${name}`,
+ key: name,
+ name: name.toUpperCase(),
+ latestVersion: 1,
+ })}
+ />
+ </div>
+ );
+}
+
/* ------------------------------------------------------------------ */
/* Color swatch */
/* ------------------------------------------------------------------ */
@@ -337,7 +411,7 @@ export function DesignGuide() {
{[
"StatusBadge", "StatusIcon", "PriorityIcon", "EntityRow", "EmptyState", "MetricCard",
"FilterBar", "InlineEditor", "PageSkeleton", "Identity", "CommentThread", "MarkdownEditor",
- "PropertiesPanel", "Sidebar", "CommandPalette",
+ "PropertiesPanel", "Sidebar", "CommandPalette", "EnvironmentVariablesEditor",
].map((name) => (
<Badge key={name} variant="ghost" className="font-mono text-[10px]">
{name}
@@ -1689,6 +1763,17 @@ export function DesignGuide() {
</p>
</SubSection>
</Section>
+
+ <Section title="Environment Variables Editor">
+ <p className="text-sm text-muted-foreground">
+ Reusable env-var editor (agents, projects, environments, routines). One shared grid, an
+ in-field Text/Secret source switch, a fuzzy secret picker with a pinned “Create secret”
+ item, automatic sensitive-value detection, and inline secret-health warnings. See the
+ Storybook <span className="font-mono">Product/Environment Variables Editor</span> stories
+ for all 10 states.
+ </p>
+ <EnvironmentVariablesEditorShowcase />
+ </Section>
</div>
);
}
diff --git a/ui/storybook/stories/environment-variables-editor.stories.tsx b/ui/storybook/stories/environment-variables-editor.stories.tsx
new file mode 100644
index 0000000000..62d35faf88
--- /dev/null
+++ b/ui/storybook/stories/environment-variables-editor.stories.tsx
@@ -0,0 +1,232 @@
+import { useState, type ReactNode } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import type { CompanySecret, EnvBinding, SecretStatus } from "@paperclipai/shared";
+import { EnvironmentVariablesEditor } from "@/components/environment-variables-editor";
+import { ToastProvider } from "@/context/ToastContext";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+
+function secret(
+ id: string,
+ name: string,
+ overrides: Partial<CompanySecret> = {},
+): CompanySecret {
+ return {
+ id,
+ companyId: "company-storybook",
+ key: name.toLowerCase(),
+ name,
+ provider: "local_encrypted",
+ status: "active" as SecretStatus,
+ managedMode: "paperclip_managed",
+ externalRef: null,
+ providerConfigId: null,
+ providerMetadata: null,
+ latestVersion: 3,
+ description: null,
+ lastResolvedAt: null,
+ lastRotatedAt: null,
+ deletedAt: null,
+ createdByAgentId: null,
+ createdByUserId: "user-board",
+ createdAt: new Date("2026-03-01T10:00:00.000Z"),
+ updatedAt: new Date("2026-04-01T10:00:00.000Z"),
+ ...overrides,
+ };
+}
+
+const SECRETS: CompanySecret[] = [
+ secret("s-github", "GITHUB_TOKEN", { latestVersion: 3 }),
+ secret("s-db", "DB_CONNECTION", { latestVersion: 3 }),
+ secret("s-openai", "OPENAI_API_KEY", { latestVersion: 2 }),
+ secret("s-resend-long", "/paperclip-cloud/prod/provider/resend/api-key-with-a-very-long-name", { latestVersion: 4 }),
+ secret("s-legacy", "LEGACY_DEPLOY_KEY", { status: "disabled", latestVersion: 2 }),
+ secret("s-archived", "OLD_STRIPE_KEY", { status: "archived", latestVersion: 4 }),
+];
+
+const RECENTLY_USED: CompanySecret[] = [SECRETS[2], secret("s-slack", "SLACK_WEBHOOK", { latestVersion: 1 })];
+
+function Surface({ title, hint, children }: { title: string; hint?: ReactNode; children: ReactNode }) {
+ return (
+ <ToastProvider>
+ <div className="p-6">
+ <Card className="w-full max-w-[720px]">
+ <CardHeader>
+ <CardTitle className="text-sm">{title}</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-2">
+ {hint ? <p className="text-xs text-muted-foreground">{hint}</p> : null}
+ {children}
+ </CardContent>
+ </Card>
+ </div>
+ </ToastProvider>
+ );
+}
+
+function Editor({
+ initial,
+ disabled,
+ recentlyUsed,
+}: {
+ initial: Record<string, EnvBinding>;
+ disabled?: boolean;
+ recentlyUsed?: CompanySecret[];
+}) {
+ const [env, setEnv] = useState<Record<string, EnvBinding>>(initial);
+ return (
+ <EnvironmentVariablesEditor
+ value={env}
+ secrets={SECRETS}
+ recentlyUsedSecrets={recentlyUsed ?? RECENTLY_USED}
+ disabled={disabled}
+ onChange={(next) => setEnv(next ?? {})}
+ onCreateSecret={async (name, value) =>
+ secret(`s-new-${name}`, name.toUpperCase(), { key: name, latestVersion: 1, description: `len=${value.length}` })
+ }
+ />
+ );
+}
+
+const meta: Meta = {
+ title: "Product/Environment Variables Editor",
+ parameters: { layout: "fullscreen", a11y: { test: "off" } },
+};
+export default meta;
+type Story = StoryObj;
+
+/** Frame 1 — default state with 4 mixed rows incl. pinned version + sensitive hint. */
+export const Default: Story = {
+ render: () => (
+ <Surface title="Default — mixed rows">
+ <Editor
+ initial={{
+ NODE_ENV: { type: "plain", value: "production" },
+ GH_TOKEN: { type: "secret_ref", secretId: "s-github", version: "latest" },
+ DB_URL: { type: "secret_ref", secretId: "s-db", version: 3 },
+ STRIPE_API_KEY: { type: "plain", value: "sk-live-51H8xL0aBcDeFgHiJkLmNoPq" },
+ }}
+ />
+ </Surface>
+ ),
+};
+
+/** Frame 2 — empty state. */
+export const Empty: Story = {
+ render: () => (
+ <Surface title="Empty — no variables">
+ <Editor initial={{}} />
+ </Surface>
+ ),
+};
+
+/** Frame 3 — secret picker open (interactive: click the secret trigger). */
+export const PickerOpen: Story = {
+ render: () => (
+ <Surface title="Secret picker" hint="Click the secret value trigger to open the fuzzy picker; type to filter, or pick the pinned “+ Create secret” item.">
+ <Editor initial={{ GH_TOKEN: { type: "secret_ref", secretId: "", version: "latest" } }} />
+ </Surface>
+ ),
+};
+
+/** Frame 4 — long bound secret name truncates before the latest badge. */
+export const LongSecretName: Story = {
+ render: () => (
+ <Surface title="Long secret name">
+ <Editor initial={{ RESEND_API_KEY: { type: "secret_ref", secretId: "s-resend-long", version: "latest" } }} />
+ </Surface>
+ ),
+};
+
+/** Frame 5 — create-secret popover (interactive: open picker → Create secret). */
+export const CreateSecret: Story = {
+ render: () => (
+ <Surface title="Create secret" hint="Open the secret picker and choose “+ Create secret …” to open the anchored create popover (name + masked value).">
+ <Editor initial={{ NEW_TOKEN: { type: "secret_ref", secretId: "", version: "latest" } }} />
+ </Surface>
+ ),
+};
+
+/** Frame 6 — store-as-secret popover (interactive: click the ShieldAlert on the sensitive row). */
+export const StoreAsSecret: Story = {
+ render: () => (
+ <Surface title="Store value as secret" hint="The sensitive-looking row shows a ShieldAlert “Store as secret” — click it to open the store popover (value preserved, masked). The adjacent “×” dismisses the hint and unmasks the value, keeping it as plain text.">
+ <Editor initial={{ AWS_SECRET_ACCESS_KEY: { type: "plain", value: "wJalrXUtnFEMI0K7MDENGbPxRfiCYEXAMPLEKEY" } }} />
+ </Surface>
+ ),
+};
+
+/** Frame 6 — version popover (interactive: click the amber version tag). */
+export const VersionPopover: Story = {
+ render: () => (
+ <Surface title="Version pinning" hint="The bound secret is pinned to v3 (amber tag). Click the tag to choose latest (recommended) or a specific version.">
+ <Editor initial={{ DB_URL: { type: "secret_ref", secretId: "s-db", version: 3 } }} />
+ </Surface>
+ ),
+};
+
+/** Frame 7 — validation trio + attention summary. */
+export const Validation: Story = {
+ render: () => (
+ <Surface title="Validation & health" hint="Invalid charset + reserved prefix warn on load; missing + disabled secret bindings drive the “2 bindings need attention” summary. Add a duplicate name to see the duplicate flag.">
+ <Editor
+ initial={{
+ "API-URL": { type: "plain", value: "https://api.example.com" },
+ PAPERCLIP_TOKEN: { type: "plain", value: "override" },
+ ABANDONED: { type: "secret_ref", secretId: "gone-1234", version: "latest" },
+ LEGACY: { type: "secret_ref", secretId: "s-legacy", version: "latest" },
+ }}
+ />
+ </Surface>
+ ),
+};
+
+/** Frame 8 — bulk-paste result (post-import state, last row flagged sensitive). */
+export const BulkPasteResult: Story = {
+ render: () => (
+ <Surface title="Bulk .env paste — result" hint="Pasting a multi-line KEY=VALUE block into an empty Name field imports one row per pair; sensitive-looking rows are auto-flagged.">
+ <Editor
+ initial={{
+ NODE_ENV: { type: "plain", value: "production" },
+ PORT: { type: "plain", value: "3000" },
+ LOG_LEVEL: { type: "plain", value: "info" },
+ STRIPE_API_KEY: { type: "plain", value: "sk-live-51H8xL0aBcDeFgHiJkLmNoPq" },
+ }}
+ />
+ </Surface>
+ ),
+};
+
+/** Frame 9 — 390px stacked layout (container-responsive). */
+export const MobileStacked: Story = {
+ render: () => (
+ <ToastProvider>
+ <div className="p-6">
+ <div className="w-[390px] rounded-lg border border-border p-4">
+ <Editor
+ initial={{
+ NODE_ENV: { type: "plain", value: "production" },
+ GH_TOKEN: { type: "secret_ref", secretId: "s-github", version: "latest" },
+ STRIPE_API_KEY: { type: "plain", value: "sk-live-51H8xL0aBcDeFgHiJkLmNoPq" },
+ }}
+ />
+ </div>
+ </div>
+ </ToastProvider>
+ ),
+};
+
+/** Frame 10 — disabled (read-only) state, health warnings still visible. */
+export const Disabled: Story = {
+ render: () => (
+ <Surface title="Disabled — read-only">
+ <Editor
+ disabled
+ initial={{
+ NODE_ENV: { type: "plain", value: "production" },
+ GH_TOKEN: { type: "secret_ref", secretId: "s-github", version: "latest" },
+ LEGACY: { type: "secret_ref", secretId: "s-legacy", version: "latest" },
+ }}
+ />
+ </Surface>
+ ),
+};
diff --git a/ui/storybook/stories/forms-editors.stories.tsx b/ui/storybook/stories/forms-editors.stories.tsx
index 8fa17c2071..fc5f1e983a 100644
--- a/ui/storybook/stories/forms-editors.stories.tsx
+++ b/ui/storybook/stories/forms-editors.stories.tsx
@@ -2,7 +2,7 @@ import { useMemo, useState, type ReactNode } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { Agent, CompanySecret, EnvBinding, Project, RoutineVariable } from "@paperclipai/shared";
import { Code2, FileText, ListPlus, RotateCcw, Table2 } from "lucide-react";
-import { EnvVarEditor } from "@/components/EnvVarEditor";
+import { EnvironmentVariablesEditor } from "@/components/environment-variables-editor";
import { ExecutionParticipantPicker } from "@/components/ExecutionParticipantPicker";
import { FoldCurtain } from "@/components/FoldCurtain";
import { InlineEditor } from "@/components/InlineEditor";
@@ -458,7 +458,7 @@ function InlineEditorGallery() {
);
}
-function EnvVarEditorGallery() {
+function EnvironmentVariablesEditorGallery() {
const [emptyEnv, setEmptyEnv] = useState<Record<string, EnvBinding>>({});
const [env, setEnv] = useState<Record<string, EnvBinding>>(filledEnv);
const createSecret = async (name: string): Promise<CompanySecret> => ({
@@ -469,16 +469,16 @@ function EnvVarEditorGallery() {
});
return (
- <Section eyebrow="EnvVarEditor" title="Runtime environment bindings">
+ <Section eyebrow="EnvironmentVariablesEditor" title="Runtime environment bindings">
<div className="grid gap-4 lg:grid-cols-3">
- <StatePanel label="Empty add row" detail="Trailing blank row is the add state.">
- <EnvVarEditor value={emptyEnv} secrets={storybookSecrets} onCreateSecret={createSecret} onChange={(next) => setEmptyEnv(next ?? {})} />
+ <StatePanel label="Empty add row" detail="Explicit + Add variable button; no trailing ghost row.">
+ <EnvironmentVariablesEditor value={emptyEnv} secrets={storybookSecrets} onCreateSecret={createSecret} onChange={(next) => setEmptyEnv(next ?? {})} />
</StatePanel>
- <StatePanel label="Plain and secret values" detail="Filled rows show edit, seal, secret select, and remove controls.">
- <EnvVarEditor value={env} secrets={storybookSecrets} onCreateSecret={createSecret} onChange={(next) => setEnv(next ?? {})} />
+ <StatePanel label="Plain and secret values" detail="Filled rows show text, secret picker, version tag, and remove controls.">
+ <EnvironmentVariablesEditor value={env} secrets={storybookSecrets} onCreateSecret={createSecret} onChange={(next) => setEnv(next ?? {})} />
</StatePanel>
<StatePanel label="Disabled shell" disabled>
- <EnvVarEditor value={filledEnv} secrets={storybookSecrets} onCreateSecret={createSecret} onChange={() => undefined} />
+ <EnvironmentVariablesEditor value={filledEnv} secrets={storybookSecrets} onCreateSecret={createSecret} onChange={() => undefined} disabled />
</StatePanel>
</div>
</Section>
@@ -655,7 +655,7 @@ function FormsEditorsShowcase() {
<MarkdownBodyGallery />
<JsonSchemaFormGallery />
<InlineEditorGallery />
- <EnvVarEditorGallery />
+ <EnvironmentVariablesEditorGallery />
<ScheduleEditorGallery />
<RoutineVariablesGallery />
<PickerGallery />
diff --git a/ui/storybook/stories/routine-secrets.stories.tsx b/ui/storybook/stories/routine-secrets.stories.tsx
index 612145cbad..e755659c6d 100644
--- a/ui/storybook/stories/routine-secrets.stories.tsx
+++ b/ui/storybook/stories/routine-secrets.stories.tsx
@@ -10,7 +10,7 @@ import type {
RoutineRevision,
RoutineRevisionSnapshotV1,
} from "@paperclipai/shared";
-import { EnvVarEditor } from "@/components/EnvVarEditor";
+import { EnvironmentVariablesEditor } from "@/components/environment-variables-editor";
import { RoutineHistoryTab } from "@/components/RoutineHistoryTab";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { useCompany } from "@/context/CompanyContext";
@@ -82,7 +82,7 @@ function SecretsTabSurface({
Routine secrets apply to every issue this routine creates. They override matching keys in
project and agent env. <span className="font-mono">PAPERCLIP_*</span> variables are reserved.
</p>
- <EnvVarEditor
+ <EnvironmentVariablesEditor
value={env}
secrets={storybookSecrets as CompanySecret[]}
onCreateSecret={async (name) => ({
diff --git a/ui/storybook/stories/secrets.stories.tsx b/ui/storybook/stories/secrets.stories.tsx
index 0b787829a9..f68448e4a9 100644
--- a/ui/storybook/stories/secrets.stories.tsx
+++ b/ui/storybook/stories/secrets.stories.tsx
@@ -5,7 +5,7 @@ import { AlertCircle, KeyRound } from "lucide-react";
import type { CompanySecret, EnvBinding } from "@paperclipai/shared";
import { Secrets } from "@/pages/Secrets";
import { SecretBindingPicker, type SecretBindingValue } from "@/components/SecretBindingPicker";
-import { EnvVarEditor } from "@/components/EnvVarEditor";
+import { EnvironmentVariablesEditor } from "@/components/environment-variables-editor";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useCompany } from "@/context/CompanyContext";
@@ -139,7 +139,7 @@ export const EnvEditorWithSecrets: Story = {
</CardTitle>
</CardHeader>
<CardContent>
- <EnvVarEditor
+ <EnvironmentVariablesEditor
value={env}
secrets={storybookSecrets as CompanySecret[]}
onCreateSecret={async (name, value) => ({