Skip to content

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

Go

MUL-6002: feat(agents): add bulk edit mode for agent environment variables (#6818)

Bohan Jiang51c1b144b423
diff --git a/packages/views/agents/components/tabs/env-file.test.ts b/packages/views/agents/components/tabs/env-file.test.ts
index 7092a504c1..bbefccadb6 100644
--- a/packages/views/agents/components/tabs/env-file.test.ts
+++ b/packages/views/agents/components/tabs/env-file.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
-import { isEnvFilePaste, parseEnvFile } from "./env-file";
+import type { EnvAssignment } from "./env-file";
+import {
+ formatEnvFile,
+ isEnvFilePaste,
+ parseEnvFile,
+ parseEnvFileResult,
+} from "./env-file";
describe("parseEnvFile", () => {
it("parses dotenv-style assignments while preserving literal values", () => {
@@ -56,3 +62,157 @@ QUOTED='say "hello" with $HOME and C:\path'
expect(isEnvFilePaste("FIRST=one\nSECOND=two")).toBe(true);
});
});
+
+describe("parseEnvFileResult", () => {
+ it("reports the physical line of the first malformed line", () => {
+ expect(parseEnvFileResult("# comment\n\nFIRST=one\necho hello")).toEqual({
+ ok: false,
+ error: { kind: "malformed", line: 4 },
+ });
+ expect(parseEnvFileResult('BROKEN="unterminated')).toEqual({
+ ok: false,
+ error: { kind: "malformed", line: 1 },
+ });
+ });
+
+ it("reports which key was duplicated and where", () => {
+ expect(parseEnvFileResult("FIRST=one\nSECOND=two\nFIRST=three")).toEqual({
+ ok: false,
+ error: { kind: "duplicate", line: 3, key: "FIRST" },
+ });
+ });
+
+ it("treats an assignment-free input as an empty success", () => {
+ expect(parseEnvFileResult("")).toEqual({ ok: true, assignments: [] });
+ expect(parseEnvFileResult("# only a comment\n")).toEqual({
+ ok: true,
+ assignments: [],
+ });
+ // parseEnvFile keeps the stricter "this is not an env file" contract the
+ // paste path depends on.
+ expect(parseEnvFile("# only a comment\n")).toBeNull();
+ });
+});
+
+describe("formatEnvFile", () => {
+ // The invariant that matters: anything the API accepts and this serializer
+ // agrees to render must read back byte-identical. Reasoning about "which
+ // characters are dangerous" is what previously truncated `foo" #bar`.
+ const ROUND_TRIP_VALUES = [
+ ["plain", "value"],
+ ["empty", ""],
+ ["windows path", String.raw`C:\Users\me\.ssh`],
+ ["dollar and backtick", "p$ss`word"],
+ ["json", '{"a":1}'],
+ ["padded", " spaced "],
+ ["inline hash", "value # kept"],
+ ["leading hash", "#not-a-comment"],
+ ["wrapped in quotes", '"quoted"'],
+ ["apostrophe", "it's"],
+ ["double quote then hash", 'foo" #bar'],
+ ["single quote then hash", "foo' #bar"],
+ ["both quote styles", `a"b'c`],
+ ["only whitespace", " "],
+ ["equals signs", "a=b=c"],
+ ["trailing backslash", "C:\\path\\"],
+ ] as const;
+
+ it.each(ROUND_TRIP_VALUES)("round-trips %s", (_label, value) => {
+ const assignments = [{ key: "K", value }];
+ const formatted = formatEnvFile(assignments);
+ expect(formatted.ok).toBe(true);
+ if (!formatted.ok) return;
+ expect(parseEnvFileResult(formatted.text)).toEqual({
+ ok: true,
+ assignments,
+ });
+ });
+
+ it("round-trips a whole file at once", () => {
+ const assignments = ROUND_TRIP_VALUES.map(([label, value], index) => ({
+ key: `K${index}_${label.replace(/[^a-z]/gi, "")}`,
+ value,
+ }));
+ const formatted = formatEnvFile(assignments);
+ expect(formatted.ok).toBe(true);
+ if (!formatted.ok) return;
+ expect(parseEnvFileResult(formatted.text)).toEqual({
+ ok: true,
+ assignments,
+ });
+ });
+
+ it("refuses values it cannot represent instead of mangling them", () => {
+ // A real newline: the parser splits on those before it ever sees a value,
+ // so there is no encoding. The server does accept these (PEM keys).
+ expect(formatEnvFile([{ key: "PEM", value: "line1\nline2" }])).toEqual({
+ ok: false,
+ reason: "unrepresentable",
+ key: "PEM",
+ });
+ // Closes early under both quote styles.
+ expect(formatEnvFile([{ key: "TRICKY", value: `a" #b' #c` }])).toEqual({
+ ok: false,
+ reason: "unrepresentable",
+ key: "TRICKY",
+ });
+ });
+
+ it("refuses keys the parser could not read back", () => {
+ expect(formatEnvFile([{ key: "foo-bar", value: "x" }])).toEqual({
+ ok: false,
+ reason: "unrepresentable",
+ key: "foo-bar",
+ });
+ });
+
+ it("refuses duplicate keys, which no text could round-trip", () => {
+ expect(
+ formatEnvFile([
+ { key: "A", value: "1" },
+ { key: "B", value: "2" },
+ { key: "A", value: "3" },
+ ]),
+ ).toEqual({ ok: false, reason: "duplicate", key: "A" });
+ });
+
+ it("guarantees that success means the whole text round-trips", () => {
+ // The contract in one assertion: whatever formatEnvFile agrees to render
+ // must parse back to exactly what went in — including the inputs it is
+ // allowed to reject, which must reject rather than render something lossy.
+ const inputs: EnvAssignment[][] = [
+ [{ key: "A", value: "1" }],
+ [{ key: "PEM", value: "line1\nline2" }],
+ [{ key: "TRICKY", value: `a" #b' #c` }],
+ [{ key: "QUOTED", value: 'foo" #bar' }],
+ [{ key: "foo-bar", value: "x" }],
+ [
+ { key: "A", value: "1" },
+ { key: "A", value: "2" },
+ ],
+ ROUND_TRIP_VALUES.map(([label, value], index) => ({
+ key: `R${index}_${label.replace(/[^a-z]/gi, "")}`,
+ value,
+ })),
+ ];
+
+ for (const assignments of inputs) {
+ const formatted = formatEnvFile(assignments);
+ if (!formatted.ok) continue;
+ expect(parseEnvFileResult(formatted.text)).toEqual({
+ ok: true,
+ assignments,
+ });
+ }
+ });
+
+ it("leaves values bare unless quoting is required", () => {
+ expect(
+ formatEnvFile([
+ { key: "A", value: "plain" },
+ { key: "B", value: "" },
+ { key: "C", value: " padded" },
+ ]),
+ ).toEqual({ ok: true, text: 'A=plain\nB=\nC=" padded"' });
+ });
+});
diff --git a/packages/views/agents/components/tabs/env-file.ts b/packages/views/agents/components/tabs/env-file.ts
index c7e11d2ff4..0f55b7f24e 100644
--- a/packages/views/agents/components/tabs/env-file.ts
+++ b/packages/views/agents/components/tabs/env-file.ts
@@ -3,6 +3,20 @@ export interface EnvAssignment {
value: string;
}
+/**
+ * Why the line number matters: a paste or a bulk edit can carry dozens of
+ * lines, and "couldn't parse" without a location leaves the user guessing.
+ * `line` is 1-based and counts every physical line, including the blanks and
+ * comments the parser skips, so it matches what the editor shows.
+ */
+export type EnvParseError =
+ | { kind: "malformed"; line: number }
+ | { kind: "duplicate"; line: number; key: string };
+
+export type EnvParseResult =
+ | { ok: true; assignments: EnvAssignment[] }
+ | { ok: false; error: EnvParseError };
+
const ASSIGNMENT_PATTERN =
/^(?:export[\t ]+)?([A-Za-z_][A-Za-z0-9_]*)[\t ]*=(.*)$/;
const ASSIGNMENT_PREFIX_PATTERN =
@@ -66,27 +80,106 @@ export function isEnvFilePaste(text: string): boolean {
return meaningfulLines.some((line) => ASSIGNMENT_PREFIX_PATTERN.test(line));
}
-/** Parse a pasted dotenv-style file without evaluating or rewriting values. */
-export function parseEnvFile(text: string): EnvAssignment[] | null {
+/**
+ * Parse a dotenv-style file without evaluating or rewriting values, reporting
+ * where the first bad line is. An input with no assignments at all is a
+ * success with an empty list — that is how bulk editing expresses "clear
+ * everything". Callers that need "this isn't an env file" should use
+ * `parseEnvFile`.
+ */
+export function parseEnvFileResult(text: string): EnvParseResult {
const assignments: EnvAssignment[] = [];
const keys = new Set<string>();
+ const lines = text.replace(/\r\n?/g, "\n").split("\n");
- for (const line of text.replace(/\r\n?/g, "\n").split("\n")) {
+ for (const [index, line] of lines.entries()) {
const trimmedLine = line.trim();
if (trimmedLine === "" || trimmedLine.startsWith("#")) continue;
+ const lineNumber = index + 1;
const match = ASSIGNMENT_PATTERN.exec(trimmedLine);
- if (!match) return null;
+ if (!match) {
+ return { ok: false, error: { kind: "malformed", line: lineNumber } };
+ }
const value = parseValue(match[2] ?? "");
- if (value === null) return null;
+ if (value === null) {
+ return { ok: false, error: { kind: "malformed", line: lineNumber } };
+ }
const key = match[1] ?? "";
- if (keys.has(key)) return null;
+ if (keys.has(key)) {
+ return { ok: false, error: { kind: "duplicate", line: lineNumber, key } };
+ }
keys.add(key);
assignments.push({ key, value });
}
- return assignments.length > 0 ? assignments : null;
+ return { ok: true, assignments };
+}
+
+/** Parse a pasted dotenv-style file without evaluating or rewriting values. */
+export function parseEnvFile(text: string): EnvAssignment[] | null {
+ const result = parseEnvFileResult(text);
+ if (!result.ok || result.assignments.length === 0) return null;
+ return result.assignments;
+}
+
+export type EnvFormatResult =
+ | { ok: true; text: string }
+ | { ok: false; reason: "unrepresentable" | "duplicate"; key: string };
+
+const KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+/**
+ * Pick an encoding by round-tripping each candidate through the very parser
+ * that will read it back, instead of reasoning about which characters are
+ * dangerous — that reasoning is what previously turned `foo" #bar` into `foo`.
+ *
+ * Some values have no representation at all: an embedded newline (the parser
+ * splits on those first) or a value that closes early under both quote styles,
+ * such as `a" #b' #c`. The server accepts those, so they must be reported
+ * rather than mangled into something that merely looks editable.
+ */
+function encodeValue(key: string, value: string): string | null {
+ if (/[\r\n]/.test(value)) return null;
+
+ for (const candidate of [value, `"${value}"`, `'${value}'`]) {
+ const result = parseEnvFileResult(`${key}=${candidate}`);
+ if (result.ok && result.assignments[0]?.value === value) return candidate;
+ }
+
+ return null;
+}
+
+/**
+ * Serialize entries back into text `parseEnvFileResult` reads identically, or
+ * name the first entry that cannot be represented so the caller can refuse to
+ * enter bulk editing without touching any data.
+ *
+ * Success means the whole text round-trips, which is why duplicate keys are a
+ * refusal rather than a formatting detail: two entries sharing a key can only
+ * ever read back as one, so no text could satisfy the contract.
+ */
+export function formatEnvFile(assignments: EnvAssignment[]): EnvFormatResult {
+ const lines: string[] = [];
+ const keys = new Set<string>();
+
+ for (const { key, value } of assignments) {
+ if (!KEY_PATTERN.test(key)) {
+ return { ok: false, reason: "unrepresentable", key };
+ }
+ if (keys.has(key)) return { ok: false, reason: "duplicate", key };
+
+ const encoded = encodeValue(key, value);
+ if (encoded === null) {
+ return { ok: false, reason: "unrepresentable", key };
+ }
+
+ keys.add(key);
+ lines.push(`${key}=${encoded}`);
+ }
+
+ return { ok: true, text: lines.join("\n") };
}
diff --git a/packages/views/agents/components/tabs/env-tab.test.tsx b/packages/views/agents/components/tabs/env-tab.test.tsx
index 4e4d2c3fe9..9d29ac3524 100644
--- a/packages/views/agents/components/tabs/env-tab.test.tsx
+++ b/packages/views/agents/components/tabs/env-tab.test.tsx
@@ -69,8 +69,10 @@ describe("EnvTab", () => {
renderTab();
await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ // Bulk editing is the advertised entry point; pasting into a field stays
+ // as an undocumented shortcut for people who reach for it.
expect(
- screen.getByText(/paste KEY=value lines into a key field/i),
+ screen.getByRole("button", { name: /bulk edit/i }),
).toBeInTheDocument();
const keyInput = screen.getByPlaceholderText("KEY");
keyInput.focus();
@@ -156,7 +158,7 @@ describe("EnvTab", () => {
expect(pasteAllowed).toBe(false);
expect(keyInput).toHaveValue("");
expect(toastError).toHaveBeenCalledWith(
- "Couldn't parse pasted environment variables",
+ "Line 2 isn't a KEY=value assignment",
);
});
@@ -171,7 +173,256 @@ describe("EnvTab", () => {
expect(pasteAllowed).toBe(false);
expect(toastError).toHaveBeenCalledWith(
- "Duplicate environment variable keys",
+ 'Duplicate key "API_KEY" on line 2',
);
});
});
+
+describe("EnvTab bulk editing", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAgentEnv.mockResolvedValue({
+ custom_env: { API_KEY: "secret value", BASE_URL: "https://example.com" },
+ });
+ updateAgentEnv.mockResolvedValue({ custom_env: {} });
+ });
+
+ async function revealAndBulkEdit() {
+ const user = userEvent.setup();
+ renderTab();
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ await user.click(screen.getByRole("button", { name: /bulk edit/i }));
+ return user;
+ }
+
+ it("seeds the textarea with the current variables", async () => {
+ await revealAndBulkEdit();
+
+ expect(screen.getByRole("textbox", { name: /bulk edit/i })).toHaveValue(
+ "API_KEY=secret value\nBASE_URL=https://example.com",
+ );
+ // The row editor is what the textarea replaces, not something beside it.
+ expect(screen.queryAllByPlaceholderText("KEY")).toHaveLength(0);
+ expect(
+ screen.getByText(/values are shown in plain text/i),
+ ).toBeInTheDocument();
+ });
+
+ it("saves what the textarea holds", async () => {
+ const user = await revealAndBulkEdit();
+
+ const textarea = screen.getByRole("textbox", { name: /bulk edit/i });
+ await user.clear(textarea);
+ await user.type(textarea, "WIN_DIR=C:\\Users\\me{Enter}PG=p$ssw0rd");
+ await user.click(screen.getByRole("button", { name: /^save$/i }));
+
+ expect(updateAgentEnv.mock.calls[0]?.[1]).toEqual({
+ custom_env: { WIN_DIR: String.raw`C:\Users\me`, PG: "p$ssw0rd" },
+ });
+ });
+
+ it("blocks saving while the text does not parse and names the line", async () => {
+ const user = await revealAndBulkEdit();
+
+ const textarea = screen.getByRole("textbox", { name: /bulk edit/i });
+ await user.clear(textarea);
+ await user.type(textarea, "FIRST=one{Enter}echo unsafe");
+
+ expect(
+ screen.getByText("Line 2 isn't a KEY=value assignment"),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /^save$/i })).toBeDisabled();
+ // Leaving via the toggle would silently discard the text, so it waits too.
+ expect(screen.getByRole("button", { name: /edit as rows/i })).toBeDisabled();
+
+ // Fixing the line releases both.
+ await user.clear(textarea);
+ await user.type(textarea, "FIRST=one");
+ expect(screen.getByRole("button", { name: /^save$/i })).toBeEnabled();
+ expect(screen.getByRole("button", { name: /edit as rows/i })).toBeEnabled();
+ });
+
+ it("names the duplicated key and its line", async () => {
+ const user = await revealAndBulkEdit();
+
+ const textarea = screen.getByRole("textbox", { name: /bulk edit/i });
+ await user.clear(textarea);
+ await user.type(textarea, "A=1{Enter}A=2");
+
+ expect(
+ screen.getByText('Duplicate key "A" on line 2'),
+ ).toBeInTheDocument();
+ });
+
+ it("carries edits back into the row editor, still masked", async () => {
+ const user = await revealAndBulkEdit();
+
+ const textarea = screen.getByRole("textbox", { name: /bulk edit/i });
+ await user.clear(textarea);
+ await user.type(textarea, "ONLY_KEY=only value");
+ await user.click(screen.getByRole("button", { name: /edit as rows/i }));
+
+ expect(
+ screen.getAllByPlaceholderText("KEY").map((i) => (i as HTMLInputElement).value),
+ ).toEqual(["ONLY_KEY"]);
+ expect(
+ screen.getAllByPlaceholderText("value").map((i) => (i as HTMLInputElement).type),
+ ).toEqual(["password"]);
+ });
+});
+
+describe("EnvTab value-field paste", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAgentEnv.mockResolvedValue({ custom_env: {} });
+ updateAgentEnv.mockResolvedValue({ custom_env: {} });
+ });
+
+ it("leaves the value field alone — a pasted value is a value", async () => {
+ const user = userEvent.setup();
+ renderTab();
+
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ await user.type(screen.getByPlaceholderText("KEY"), "CONFIG");
+
+ // `foo=bar` looks like an assignment but was pasted as a value. Hijacking
+ // it would save { foo: "bar" } instead of { CONFIG: "foo=bar" }.
+ const valueInput = screen.getByPlaceholderText("value");
+ const nativeAllowed = fireEvent.paste(valueInput, {
+ clipboardData: { getData: () => "foo=bar" },
+ });
+
+ expect(nativeAllowed).toBe(true);
+ expect(toastError).not.toHaveBeenCalled();
+ expect(
+ screen.getAllByPlaceholderText("KEY").map((i) => (i as HTMLInputElement).value),
+ ).toEqual(["CONFIG"]);
+ });
+
+ it("does not intercept a whole file pasted into the value field either", async () => {
+ const user = userEvent.setup();
+ renderTab();
+
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ const nativeAllowed = fireEvent.paste(screen.getByPlaceholderText("value"), {
+ clipboardData: { getData: () => "FIRST=one\nSECOND=two" },
+ });
+
+ expect(nativeAllowed).toBe(true);
+ expect(screen.getAllByPlaceholderText("KEY")).toHaveLength(1);
+ });
+
+ it("reports the offending line when a paste cannot be parsed", async () => {
+ const user = userEvent.setup();
+ renderTab();
+
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ fireEvent.paste(screen.getByPlaceholderText("KEY"), {
+ clipboardData: { getData: () => "FIRST=one\necho unsafe" },
+ });
+
+ expect(toastError).toHaveBeenCalledWith(
+ "Line 2 isn't a KEY=value assignment",
+ );
+ });
+});
+
+describe("EnvTab unsaved-work reporting", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAgentEnv.mockResolvedValue({ custom_env: { API_KEY: "secret" } });
+ updateAgentEnv.mockResolvedValue({ custom_env: {} });
+ });
+
+ it("reports bulk text that does not parse as unsaved work", async () => {
+ const onDirtyChange = vi.fn();
+ const user = userEvent.setup();
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <EnvTab agent={agent} onDirtyChange={onDirtyChange} />
+ </I18nProvider>,
+ );
+
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ await user.click(screen.getByRole("button", { name: /bulk edit/i }));
+ onDirtyChange.mockClear();
+
+ const textarea = screen.getByRole("textbox", { name: /bulk edit/i });
+ await user.clear(textarea);
+ await user.type(textarea, "not-an-assignment");
+
+ // Without this the parent's discard guard sees a clean tab and lets a tab
+ // switch drop the text with no prompt.
+ expect(onDirtyChange).toHaveBeenLastCalledWith(true);
+ expect(screen.getByText(/unsaved changes/i)).toBeInTheDocument();
+
+ // Clearing the error settles back to genuinely clean.
+ await user.clear(textarea);
+ await user.type(textarea, "API_KEY=secret");
+ expect(onDirtyChange).toHaveBeenLastCalledWith(false);
+ });
+});
+
+describe("EnvTab values that bulk text cannot represent", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ updateAgentEnv.mockResolvedValue({ custom_env: {} });
+ });
+
+ it("refuses to enter bulk mode rather than serialize lossily", async () => {
+ getAgentEnv.mockResolvedValue({
+ custom_env: { PEM: "line1\nline2", SAFE: "ok" },
+ });
+ const user = userEvent.setup();
+ renderTab();
+
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ await user.click(screen.getByRole("button", { name: /bulk edit/i }));
+
+ expect(toastError).toHaveBeenCalledWith(
+ '"PEM" can\'t be shown as text — edit it as a row',
+ );
+ // Still in the row editor, data untouched.
+ expect(
+ screen.queryByRole("textbox", { name: /bulk edit/i }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getAllByPlaceholderText("KEY").map((i) => (i as HTMLInputElement).value),
+ ).toEqual(["PEM", "SAFE"]);
+ });
+
+ it("refuses bulk mode when two rows share a key", async () => {
+ getAgentEnv.mockResolvedValue({ custom_env: { A: "1" } });
+ const user = userEvent.setup();
+ renderTab();
+
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ await user.click(screen.getByRole("button", { name: /^add$/i }));
+ await user.type(screen.getAllByPlaceholderText("KEY")[1]!, "A");
+ await user.click(screen.getByRole("button", { name: /bulk edit/i }));
+
+ // No text could round-trip two entries sharing a key, so entering bulk
+ // mode would show a duplicate error the user could not trace to a row.
+ expect(toastError).toHaveBeenCalledWith("Duplicate environment variable keys");
+ expect(
+ screen.queryByRole("textbox", { name: /bulk edit/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps a quote-then-hash value intact through a bulk round trip", async () => {
+ getAgentEnv.mockResolvedValue({ custom_env: { TRICKY: 'foo" #bar' } });
+ const user = userEvent.setup();
+ renderTab();
+
+ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));
+ await user.click(screen.getByRole("button", { name: /bulk edit/i }));
+ await user.click(screen.getByRole("button", { name: /edit as rows/i }));
+ await user.click(screen.getByRole("button", { name: /^add$/i }));
+ await user.type(screen.getAllByPlaceholderText("KEY")[1]!, "NEW");
+ await user.click(screen.getByRole("button", { name: /^save$/i }));
+
+ expect(updateAgentEnv.mock.calls[0]?.[1]).toEqual({
+ custom_env: { TRICKY: 'foo" #bar', NEW: "" },
+ });
+ });
+});
diff --git a/packages/views/agents/components/tabs/env-tab.tsx b/packages/views/agents/components/tabs/env-tab.tsx
index 1f97e15432..de5512c1c0 100644
--- a/packages/views/agents/components/tabs/env-tab.tsx
+++ b/packages/views/agents/components/tabs/env-tab.tsx
@@ -2,14 +2,31 @@
import { useCallback, useEffect, useState } from "react";
import type { ClipboardEvent } from "react";
-import { Eye, EyeOff, Loader2, Lock, Plus, Save, Trash2 } from "lucide-react";
+import {
+ Eye,
+ EyeOff,
+ List,
+ Loader2,
+ Lock,
+ Plus,
+ Save,
+ Trash2,
+ WrapText,
+} from "lucide-react";
import { api } from "@multica/core/api";
import type { Agent } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
import { Input } from "@multica/ui/components/ui/input";
+import { Textarea } from "@multica/ui/components/ui/textarea";
import { toast } from "sonner";
import { useT } from "../../../i18n";
-import { isEnvFilePaste, parseEnvFile } from "./env-file";
+import type { EnvParseError } from "./env-file";
+import {
+ formatEnvFile,
+ isEnvFilePaste,
+ parseEnvFile,
+ parseEnvFileResult,
+} from "./env-file";
// Env values never reach this component until the user clicks
// "Reveal & edit" — the agent resource feed no longer carries
@@ -39,6 +56,16 @@ function envMapToEntries(env: Record<string, string>): EnvEntry[] {
: [{ id: nextEnvId++, key: "", value: "", visible: true }];
}
+// Bulk mode round-trips through the same parser the paste path uses, so the
+// two entry points can never disagree about what a line means.
+function entriesToBulkText(entries: EnvEntry[]) {
+ return formatEnvFile(
+ entries
+ .filter((entry) => entry.key.trim() !== "")
+ .map((entry) => ({ key: entry.key.trim(), value: entry.value })),
+ );
+}
+
function entriesToEnvMap(entries: EnvEntry[]): Record<string, string> {
const map = Object.create(null) as Record<string, string>;
for (const entry of entries) {
@@ -76,6 +103,16 @@ export function EnvTab({
const [revealing, setRevealing] = useState(false);
const [saving, setSaving] = useState(false);
+ // Bulk mode is a second editor over the same `revealed` state rather than a
+ // staging buffer: every keystroke that parses is written straight through,
+ // so dirty tracking and Save behave identically in both modes. A keystroke
+ // that does not parse leaves `revealed` on its last good value and raises
+ // `bulkError`, which disables Save so the user can never ship the stale
+ // state that is no longer on screen.
+ const [bulkEditing, setBulkEditing] = useState(false);
+ const [bulkText, setBulkText] = useState("");
+ const [bulkError, setBulkError] = useState<EnvParseError | null>(null);
+
const keyCount = agent.custom_env_key_count ?? 0;
const currentEnvMap = revealed ? entriesToEnvMap(revealed) : originalMap;
@@ -83,9 +120,14 @@ export function EnvTab({
revealed !== null &&
JSON.stringify(currentEnvMap) !== JSON.stringify(originalMap);
+ // Bulk text that does not parse never reaches `revealed`, so `dirty` alone
+ // would report a clean tab while the textarea still holds the user's work —
+ // and the parent's discard guard would let a tab switch drop it silently.
+ const hasUnsavedWork = dirty || (bulkEditing && bulkError !== null);
+
useEffect(() => {
- onDirtyChange?.(dirty);
- }, [dirty, onDirtyChange]);
+ onDirtyChange?.(hasUnsavedWork);
+ }, [hasUnsavedWork, onDirtyChange]);
const handleReveal = useCallback(async () => {
setRevealing(true);
@@ -133,6 +175,14 @@ export function EnvTab({
);
};
+ const describeParseError = (error: EnvParseError) =>
+ error.kind === "duplicate"
+ ? t(($) => $.tab_body.env.parse_error_duplicate, {
+ line: error.line,
+ key: error.key,
+ })
+ : t(($) => $.tab_body.env.parse_error_malformed, { line: error.line });
+
const handleEnvPaste = (
index: number,
event: ClipboardEvent<HTMLInputElement>,
@@ -142,22 +192,11 @@ export function EnvTab({
if (!assignments) {
if (isEnvFilePaste(text)) {
event.preventDefault();
- const assignmentKeys = text
- .replace(/\r\n?/g, "\n")
- .split("\n")
- .map(
- (line) =>
- /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line)?.[1],
- )
- .filter((key): key is string => key !== undefined);
- const hasDuplicateKeys =
- new Set(assignmentKeys).size < assignmentKeys.length;
+ const result = parseEnvFileResult(text);
toast.error(
- t(($) =>
- hasDuplicateKeys
- ? $.tab_body.env.duplicate_keys_toast
- : $.tab_body.env.paste_invalid_toast,
- ),
+ result.ok
+ ? t(($) => $.tab_body.env.paste_invalid_toast)
+ : describeParseError(result.error),
);
}
return;
@@ -182,6 +221,53 @@ export function EnvTab({
});
};
+ const enterBulkEditing = () => {
+ const formatted = entriesToBulkText(revealed ?? []);
+ if (!formatted.ok) {
+ // Refuse rather than hand back text that cannot be read again — the
+ // user would edit an unrelated line and silently truncate this one.
+ toast.error(
+ formatted.reason === "duplicate"
+ ? t(($) => $.tab_body.env.duplicate_keys_toast)
+ : t(($) => $.tab_body.env.bulk_unsupported_toast, {
+ key: formatted.key,
+ }),
+ );
+ return;
+ }
+
+ setBulkText(formatted.text);
+ setBulkError(null);
+ setBulkEditing(true);
+ };
+
+ const leaveBulkEditing = () => {
+ setBulkEditing(false);
+ setBulkError(null);
+ };
+
+ const handleBulkTextChange = (text: string) => {
+ setBulkText(text);
+
+ const result = parseEnvFileResult(text);
+ if (!result.ok) {
+ setBulkError(result.error);
+ return;
+ }
+
+ setBulkError(null);
+ setRevealed(
+ result.assignments.length > 0
+ ? result.assignments.map(({ key, value }) => ({
+ id: nextEnvId++,
+ key,
+ value,
+ visible: false,
+ }))
+ : [{ id: nextEnvId++, key: "", value: "", visible: true }],
+ );
+ };
+
const toggleEnvVisibility = (index: number) => {
setRevealed((prev) =>
(prev ?? []).map((entry, i) =>
@@ -205,8 +291,21 @@ export function EnvTab({
custom_env: currentEnvMap,
});
const env = resp.custom_env ?? {};
+ const savedEntries = envMapToEntries(env);
setOriginalMap(env);
- setRevealed(envMapToEntries(env));
+ setRevealed(savedEntries);
+ // Keep the textarea in step with what the server accepted rather than
+ // dropping the user out of bulk mode on every save. If the server hands
+ // back something bulk text cannot express, fall back to rows — the data
+ // is already saved, so the only wrong move would be showing lossy text.
+ if (bulkEditing) {
+ const formatted = entriesToBulkText(savedEntries);
+ if (formatted.ok) {
+ setBulkText(formatted.text);
+ } else {
+ leaveBulkEditing();
+ }
+ }
toast.success(t(($) => $.tab_body.env.saved_toast));
onSaved?.();
} catch (err) {
@@ -278,21 +377,60 @@ export function EnvTab({
</code>
{t(($) => $.tab_body.env.intro_suffix)}
</p>
- <p>{t(($) => $.tab_body.env.paste_hint)}</p>
</div>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={addEnvEntry}
- className="shrink-0"
- >
- <Plus className="h-3 w-3" />
- {t(($) => $.tab_body.common.add)}
- </Button>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={bulkEditing ? leaveBulkEditing : enterBulkEditing}
+ disabled={bulkEditing && bulkError !== null}
+ >
+ {bulkEditing ? (
+ <List className="h-3 w-3" />
+ ) : (
+ <WrapText className="h-3 w-3" />
+ )}
+ {bulkEditing
+ ? t(($) => $.tab_body.env.row_edit_action)
+ : t(($) => $.tab_body.env.bulk_edit_action)}
+ </Button>
+ {!bulkEditing && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={addEnvEntry}
+ >
+ <Plus className="h-3 w-3" />
+ {t(($) => $.tab_body.common.add)}
+ </Button>
+ )}
+ </div>
</div>
- {revealed.length > 0 ? (
+ {bulkEditing ? (
+ <div className="space-y-2">
+ <Textarea
+ value={bulkText}
+ onChange={(e) => handleBulkTextChange(e.target.value)}
+ placeholder={t(($) => $.tab_body.env.bulk_placeholder)}
+ aria-label={t(($) => $.tab_body.env.bulk_edit_action)}
+ aria-invalid={bulkError !== null}
+ spellCheck={false}
+ className="min-h-48 font-mono text-caption"
+ />
+ {bulkError ? (
+ <p className="text-caption text-destructive">
+ {describeParseError(bulkError)}
+ </p>
+ ) : (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.tab_body.env.bulk_plaintext_notice)}
+ </p>
+ )}
+ </div>
+ ) : revealed.length > 0 ? (
<div className="space-y-2">
{revealed.map((entry, index) => (
<div key={entry.id} className="flex items-center gap-2">
@@ -310,6 +448,9 @@ export function EnvTab({
onChange={(e) =>
updateEnvEntry(index, "value", e.target.value)
}
+ // Deliberately no paste interception here: a value is
+ // arbitrary text, and `foo=bar` pasted as a value is a value,
+ // not an assignment. Bulk edit is the entry point for files.
placeholder={t(($) => $.tab_body.env.value_placeholder)}
className="pr-8 font-mono text-caption"
/>
@@ -349,12 +490,16 @@ export function EnvTab({
)}
<div className="flex items-center justify-end gap-3">
- {dirty && (
+ {hasUnsavedWork && (
<span className="text-caption text-muted-foreground">
{t(($) => $.tab_body.common.unsaved_changes)}
</span>
)}
- <Button onClick={handleSave} disabled={!dirty || saving} size="sm">
+ <Button
+ onClick={handleSave}
+ disabled={!dirty || saving || bulkError !== null}
+ size="sm"
+ >
{saving ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index e9a2a439c6..fe6b2ad718 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -463,7 +463,13 @@
"intro_prefix": "Injected into the agent process at launch (e.g. ",
"intro_separator": ", ",
"intro_suffix": ").",
- "paste_hint": "Paste KEY=value lines into a key field to add multiple variables.",
+ "bulk_edit_action": "Bulk edit",
+ "row_edit_action": "Edit as rows",
+ "bulk_placeholder": "API_KEY=value\nBASE_URL=https://example.com",
+ "bulk_plaintext_notice": "Values are shown in plain text while bulk editing.",
+ "bulk_unsupported_toast": "\"{{key}}\" can't be shown as text — edit it as a row",
+ "parse_error_malformed": "Line {{line}} isn't a KEY=value assignment",
+ "parse_error_duplicate": "Duplicate key \"{{key}}\" on line {{line}}",
"paste_invalid_toast": "Couldn't parse pasted environment variables",
"key_placeholder": "KEY",
"value_placeholder": "value",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index cf18f8e2f2..1c8a971144 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -346,7 +346,13 @@
"intro_prefix": "エージェントプロセスの起動時に注入されます(例: ",
"intro_separator": ", ",
"intro_suffix": ")。",
- "paste_hint": "KEY=value 形式の行をキー欄に貼り付けると、複数の環境変数を追加できます。",
+ "bulk_edit_action": "一括編集",
+ "row_edit_action": "個別編集",
+ "bulk_placeholder": "API_KEY=値\nBASE_URL=https://example.com",
+ "bulk_plaintext_notice": "一括編集中は値が平文で表示されます。",
+ "bulk_unsupported_toast": "\"{{key}}\" の値はテキストで表現できません。個別編集で変更してください",
+ "parse_error_malformed": "{{line}} 行目が KEY=value 形式ではありません",
+ "parse_error_duplicate": "{{line}} 行目のキー \"{{key}}\" が重複しています",
"paste_invalid_toast": "貼り付けた環境変数を解析できませんでした",
"key_placeholder": "KEY",
"value_placeholder": "value",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 865e58bacd..c83ffb79cd 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -354,7 +354,13 @@
"intro_prefix": "에이전트 프로세스가 시작될 때 주입됩니다(예: ",
"intro_separator": ", ",
"intro_suffix": ").",
- "paste_hint": "키 필드에 KEY=value 형식의 줄을 붙여넣으면 여러 환경 변수를 추가할 수 있습니다.",
+ "bulk_edit_action": "일괄 편집",
+ "row_edit_action": "개별 편집",
+ "bulk_placeholder": "API_KEY=값\nBASE_URL=https://example.com",
+ "bulk_plaintext_notice": "일괄 편집 중에는 값이 평문으로 표시됩니다.",
+ "bulk_unsupported_toast": "\"{{key}}\" 값은 텍스트로 표현할 수 없습니다. 개별 편집에서 수정하세요",
+ "parse_error_malformed": "{{line}}번째 줄이 KEY=value 형식이 아닙니다",
+ "parse_error_duplicate": "{{line}}번째 줄의 키 \"{{key}}\"가 중복됩니다",
"paste_invalid_toast": "붙여넣은 환경 변수를 파싱할 수 없습니다",
"key_placeholder": "KEY",
"value_placeholder": "value",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 112f175e47..425c8924d6 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -453,7 +453,13 @@
"intro_prefix": "在智能体进程启动时注入(例如 ",
"intro_separator": "、",
"intro_suffix": ")。",
- "paste_hint": "将 KEY=value 格式的内容粘贴到 key 输入框,即可添加多个环境变量。",
+ "bulk_edit_action": "批量编辑",
+ "row_edit_action": "逐条编辑",
+ "bulk_placeholder": "API_KEY=值\nBASE_URL=https://example.com",
+ "bulk_plaintext_notice": "批量编辑时,值以明文显示。",
+ "bulk_unsupported_toast": "\"{{key}}\" 的值无法用文本表示,请用逐条编辑修改",
+ "parse_error_malformed": "第 {{line}} 行不是 KEY=value 格式",
+ "parse_error_duplicate": "第 {{line}} 行的 key \"{{key}}\" 重复",
"paste_invalid_toast": "无法解析粘贴的环境变量",
"key_placeholder": "KEY",
"value_placeholder": "值",