Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6002: feat(agents): support pasting environment files (#6730)
Yuri Gui7746cef56bbc
diff --git a/packages/views/agents/components/tabs/env-file.test.ts b/packages/views/agents/components/tabs/env-file.test.tsnew file mode 100644index 0000000000..7092a504c1--- /dev/null+++ b/packages/views/agents/components/tabs/env-file.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from "vitest";++import { isEnvFilePaste, parseEnvFile } from "./env-file";++describe("parseEnvFile", () => {+ it("parses dotenv-style assignments while preserving literal values", () => {+ expect(+ parseEnvFile(String.raw`+# Agent credentials+export API_KEY="secret value"+EMPTY=+URL=https://example.com/path?first=one&second=two+HASH='value # kept'+PLAIN=value # ignored comment+WIN_DIR=C:\Users\me\.ssh+PASSWORD=p$ss${"`"}word+JSON={"a":1}+QUOTED='say "hello" with $HOME and C:\path'+`),+ ).toEqual([+ { key: "API_KEY", value: "secret value" },+ { key: "EMPTY", value: "" },+ {+ key: "URL",+ value: "https://example.com/path?first=one&second=two",+ },+ { key: "HASH", value: "value # kept" },+ { key: "PLAIN", value: "value" },+ { key: "WIN_DIR", value: String.raw`C:\Users\me\.ssh` },+ { key: "PASSWORD", value: "p$ss`word" },+ { key: "JSON", value: '{"a":1}' },+ { key: "QUOTED", value: String.raw`say "hello" with $HOME and C:\path` },+ ]);+ });++ it("supports Windows line endings", () => {+ expect(parseEnvFile("FIRST=one\r\nSECOND=two\r\n")).toEqual([+ { key: "FIRST", value: "one" },+ { key: "SECOND", value: "two" },+ ]);+ });++ it("rejects partial files instead of silently dropping unsupported lines", () => {+ expect(parseEnvFile("FIRST=one\necho hello\nSECOND=two")).toBeNull();+ expect(parseEnvFile('BROKEN="unterminated')).toBeNull();+ expect(parseEnvFile('TOKEN="abc"#suffix')).toBeNull();+ expect(parseEnvFile("FIRST=one\nFIRST=two")).toBeNull();+ });++ it("does not treat ordinary key text as an environment file", () => {+ expect(parseEnvFile("API_KEY")).toBeNull();+ expect(isEnvFilePaste("API_KEY")).toBe(false);+ expect(isEnvFilePaste("API_KEY\n")).toBe(false);+ expect(isEnvFilePaste("# database settings\n")).toBe(false);+ expect(isEnvFilePaste("API_KEY=value")).toBe(true);+ expect(isEnvFilePaste("FIRST=one\nSECOND=two")).toBe(true);+ });+});diff --git a/packages/views/agents/components/tabs/env-file.ts b/packages/views/agents/components/tabs/env-file.tsnew file mode 100644index 0000000000..c7e11d2ff4--- /dev/null+++ b/packages/views/agents/components/tabs/env-file.ts@@ -0,0 +1,92 @@+export interface EnvAssignment {+ key: string;+ value: string;+}++const ASSIGNMENT_PATTERN =+ /^(?:export[\t ]+)?([A-Za-z_][A-Za-z0-9_]*)[\t ]*=(.*)$/;+const ASSIGNMENT_PREFIX_PATTERN =+ /^(?:export[\t ]+)?[A-Za-z_][A-Za-z0-9_]*[\t ]*=/;++function parseQuotedValue(rawValue: string): string | null {+ const quote = rawValue[0];+ if (quote !== '"' && quote !== "'") return null;++ for (let index = 1; index < rawValue.length; index += 1) {+ if (rawValue[index] === quote) {+ const remainder = rawValue.slice(index + 1);+ if (remainder.trim() === "" || /^[\t ]+#/.test(remainder)) {+ return rawValue.slice(1, index);+ }+ }+ }++ return null;+}++function parseUnquotedValue(+ rawValue: string,+ hadLeadingWhitespace: boolean,+): string {+ for (let index = 0; index < rawValue.length; index += 1) {+ const character = rawValue[index];++ if (+ character === "#" &&+ ((index === 0 && hadLeadingWhitespace) ||+ /\s/.test(rawValue[index - 1] ?? ""))+ ) {+ return rawValue.slice(0, index).trimEnd();+ }+ }++ return rawValue.trimEnd();+}++function parseValue(rawValue: string): string | null {+ const hadLeadingWhitespace = /^[\t ]/.test(rawValue);+ const value = rawValue.trimStart();+ if (value.startsWith('"') || value.startsWith("'")) {+ return parseQuotedValue(value);+ }++ return parseUnquotedValue(value, hadLeadingWhitespace);+}++export function isEnvFilePaste(text: string): boolean {+ const trimmedText = text.trim();+ if (!trimmedText) return false;++ const meaningfulLines = trimmedText+ .replace(/\r\n?/g, "\n")+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line !== "" && !line.startsWith("#"));++ 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 {+ const assignments: EnvAssignment[] = [];+ const keys = new Set<string>();++ for (const line of text.replace(/\r\n?/g, "\n").split("\n")) {+ const trimmedLine = line.trim();+ if (trimmedLine === "" || trimmedLine.startsWith("#")) continue;++ const match = ASSIGNMENT_PATTERN.exec(trimmedLine);+ if (!match) return null;++ const value = parseValue(match[2] ?? "");+ if (value === null) return null;++ const key = match[1] ?? "";+ if (keys.has(key)) return null;++ keys.add(key);+ assignments.push({ key, value });+ }++ return assignments.length > 0 ? assignments : null;+}diff --git a/packages/views/agents/components/tabs/env-tab.test.tsx b/packages/views/agents/components/tabs/env-tab.test.tsxnew file mode 100644index 0000000000..4e4d2c3fe9--- /dev/null+++ b/packages/views/agents/components/tabs/env-tab.test.tsx@@ -0,0 +1,177 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import type { Agent } from "@multica/core/types";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../../locales/en/common.json";+import enAgents from "../../../locales/en/agents.json";++const getAgentEnv = vi.hoisted(() => vi.fn());+const updateAgentEnv = vi.hoisted(() => vi.fn());+const toastError = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", () => ({+ api: { getAgentEnv, updateAgentEnv },+}));++vi.mock("sonner", () => ({+ toast: { error: toastError, success: vi.fn() },+}));++import { EnvTab } from "./env-tab";++const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };++const agent: Agent = {+ id: "agent-1",+ workspace_id: "ws-1",+ runtime_id: "runtime-1",+ name: "Agent",+ description: "",+ instructions: "",+ avatar_url: null,+ runtime_mode: "local",+ runtime_config: {},+ custom_args: [],+ visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],+ status: "idle",+ max_concurrent_tasks: 1,+ model: "",+ owner_id: "user-1",+ skills: [],+ created_at: "2026-08-08T00:00:00Z",+ updated_at: "2026-08-08T00:00:00Z",+ archived_at: null,+ archived_by: null,+};++function renderTab() {+ return render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <EnvTab agent={agent} />+ </I18nProvider>,+ );+}++describe("EnvTab", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getAgentEnv.mockResolvedValue({ custom_env: {} });+ updateAgentEnv.mockResolvedValue({ custom_env: {} });+ });++ it("turns pasted environment-file assignments into separate rows", async () => {+ const user = userEvent.setup();+ renderTab();++ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));+ expect(+ screen.getByText(/paste KEY=value lines into a key field/i),+ ).toBeInTheDocument();+ const keyInput = screen.getByPlaceholderText("KEY");+ keyInput.focus();+ fireEvent.paste(keyInput, {+ clipboardData: {+ getData: () =>+ 'API_KEY="secret value"\nexport BASE_URL=https://example.com/api',+ },+ });++ expect(+ screen+ .getAllByPlaceholderText("KEY")+ .map((input) => (input as HTMLInputElement).value),+ ).toEqual(["API_KEY", "BASE_URL"]);+ expect(+ screen+ .getAllByPlaceholderText("value")+ .map((input) => (input as HTMLInputElement).value),+ ).toEqual(["secret value", "https://example.com/api"]);+ expect(+ screen+ .getAllByPlaceholderText("value")+ .every((input) => (input as HTMLInputElement).type === "password"),+ ).toBe(true);+ expect(screen.getAllByPlaceholderText("KEY")[0]).toHaveFocus();+ });++ it("leaves a bare key with a trailing newline to native paste handling", async () => {+ const user = userEvent.setup();+ renderTab();++ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));+ const keyInput = screen.getByPlaceholderText("KEY");+ const pasteAllowed = fireEvent.paste(keyInput, {+ clipboardData: { getData: () => "API_KEY\n" },+ });++ expect(pasteAllowed).toBe(true);+ expect(toastError).not.toHaveBeenCalled();+ });++ it("leaves a comment-only paste to native handling without an error", async () => {+ const user = userEvent.setup();+ renderTab();++ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));+ const pasteAllowed = fireEvent.paste(screen.getByPlaceholderText("KEY"), {+ clipboardData: { getData: () => "# database settings\n" },+ });++ expect(pasteAllowed).toBe(true);+ expect(toastError).not.toHaveBeenCalled();+ });++ it("preserves special environment keys in the save payload", async () => {+ const user = userEvent.setup();+ renderTab();++ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));+ fireEvent.paste(screen.getByPlaceholderText("KEY"), {+ clipboardData: { getData: () => "__proto__=secret" },+ });+ await user.click(screen.getByRole("button", { name: /^save$/i }));++ const payload = updateAgentEnv.mock.calls[0]?.[1] as {+ custom_env: Record<string, string>;+ };+ expect(Object.hasOwn(payload.custom_env, "__proto__")).toBe(true);+ expect(payload.custom_env.__proto__).toBe("secret");+ });++ it("rejects malformed environment-file pastes without changing the row", async () => {+ const user = userEvent.setup();+ renderTab();++ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));+ const keyInput = screen.getByPlaceholderText("KEY");+ const pasteAllowed = fireEvent.paste(keyInput, {+ clipboardData: { getData: () => "FIRST=one\necho unsafe" },+ });++ expect(pasteAllowed).toBe(false);+ expect(keyInput).toHaveValue("");+ expect(toastError).toHaveBeenCalledWith(+ "Couldn't parse pasted environment variables",+ );+ });++ it("rejects duplicate keys during paste", async () => {+ const user = userEvent.setup();+ renderTab();++ await user.click(screen.getByRole("button", { name: /reveal & edit/i }));+ const pasteAllowed = fireEvent.paste(screen.getByPlaceholderText("KEY"), {+ clipboardData: { getData: () => "API_KEY=first\nAPI_KEY=second" },+ });++ expect(pasteAllowed).toBe(false);+ expect(toastError).toHaveBeenCalledWith(+ "Duplicate environment variable keys",+ );+ });+});diff --git a/packages/views/agents/components/tabs/env-tab.tsx b/packages/views/agents/components/tabs/env-tab.tsxindex 951feafdc1..1f97e15432 100644--- a/packages/views/agents/components/tabs/env-tab.tsx+++ b/packages/views/agents/components/tabs/env-tab.tsx@@ -1,21 +1,15 @@"use client";import { useCallback, useEffect, useState } from "react";-import {- Eye,- EyeOff,- Loader2,- Lock,- Plus,- Save,- Trash2,-} from "lucide-react";+import type { ClipboardEvent } from "react";+import { Eye, EyeOff, Loader2, Lock, Plus, Save, Trash2 } 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 { toast } from "sonner";import { useT } from "../../../i18n";+import { isEnvFilePaste, parseEnvFile } from "./env-file";// Env values never reach this component until the user clicks// "Reveal & edit" — the agent resource feed no longer carries@@ -33,16 +27,20 @@ interface EnvEntry {}function envMapToEntries(env: Record<string, string>): EnvEntry[] {- return Object.entries(env).map(([key, value]) => ({+ const entries = Object.entries(env).map(([key, value]) => ({id: nextEnvId++,key,value,visible: false,}));++ return entries.length > 0+ ? entries+ : [{ id: nextEnvId++, key: "", value: "", visible: true }];}function entriesToEnvMap(entries: EnvEntry[]): Record<string, string> {- const map: Record<string, string> = {};+ const map = Object.create(null) as Record<string, string>;for (const entry of entries) {const key = entry.key.trim();if (key) {@@ -115,7 +113,12 @@ export function EnvTab({};const removeEnvEntry = (index: number) => {- setRevealed((prev) => (prev ?? []).filter((_, i) => i !== index));+ setRevealed((prev) => {+ const entries = (prev ?? []).filter((_, i) => i !== index);+ return entries.length > 0+ ? entries+ : [{ id: nextEnvId++, key: "", value: "", visible: true }];+ });};const updateEnvEntry = (@@ -130,6 +133,55 @@ export function EnvTab({);};+ const handleEnvPaste = (+ index: number,+ event: ClipboardEvent<HTMLInputElement>,+ ) => {+ const text = event.clipboardData.getData("text/plain");+ const assignments = parseEnvFile(text);+ 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;+ toast.error(+ t(($) =>+ hasDuplicateKeys+ ? $.tab_body.env.duplicate_keys_toast+ : $.tab_body.env.paste_invalid_toast,+ ),+ );+ }+ return;+ }++ event.preventDefault();+ setRevealed((prev) => {+ const currentEntries = prev ?? [];+ const currentEntry = currentEntries[index];+ const pastedEntries = assignments.map(({ key, value }, pasteIndex) => ({+ id: pasteIndex === 0 && currentEntry ? currentEntry.id : nextEnvId++,+ key,+ value,+ visible: false,+ }));++ return [+ ...currentEntries.slice(0, index),+ ...pastedEntries,+ ...currentEntries.slice(index + 1),+ ];+ });+ };+const toggleEnvVisibility = (index: number) => {setRevealed((prev) =>(prev ?? []).map((entry, i) =>@@ -214,17 +266,20 @@ export function EnvTab({return (<div className="space-y-4"><div className="flex items-start justify-between gap-3">- <p className="text-caption text-muted-foreground">- {t(($) => $.tab_body.env.intro_prefix)}- <code className="rounded bg-muted px-1 py-0.5 font-mono text-micro">- {"ANTHROPIC_API_KEY"}- </code>- {t(($) => $.tab_body.env.intro_separator)}- <code className="rounded bg-muted px-1 py-0.5 font-mono text-micro">- {"ANTHROPIC_BASE_URL"}- </code>- {t(($) => $.tab_body.env.intro_suffix)}- </p>+ <div className="space-y-1 text-caption text-muted-foreground">+ <p>+ {t(($) => $.tab_body.env.intro_prefix)}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-micro">+ {"ANTHROPIC_API_KEY"}+ </code>+ {t(($) => $.tab_body.env.intro_separator)}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-micro">+ {"ANTHROPIC_BASE_URL"}+ </code>+ {t(($) => $.tab_body.env.intro_suffix)}+ </p>+ <p>{t(($) => $.tab_body.env.paste_hint)}</p>+ </div><Buttontype="button"variant="outline"@@ -244,6 +299,7 @@ export function EnvTab({<Inputvalue={entry.key}onChange={(e) => updateEnvEntry(index, "key", e.target.value)}+ onPaste={(event) => handleEnvPaste(index, event)}placeholder={t(($) => $.tab_body.env.key_placeholder)}className="w-[40%] font-mono text-caption"/>@@ -261,7 +317,11 @@ export function EnvTab({type="button"onClick={() => toggleEnvVisibility(index)}className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"- aria-label={entry.visible ? t(($) => $.tab_body.env.hide_value_aria) : t(($) => $.tab_body.env.show_value_aria)}+ aria-label={+ entry.visible+ ? t(($) => $.tab_body.env.hide_value_aria)+ : t(($) => $.tab_body.env.show_value_aria)+ }>{entry.visible ? (<EyeOff className="h-3.5 w-3.5" />@@ -290,7 +350,9 @@ export function EnvTab({<div className="flex items-center justify-end gap-3">{dirty && (- <span className="text-caption text-muted-foreground">{t(($) => $.tab_body.common.unsaved_changes)}</span>+ <span className="text-caption text-muted-foreground">+ {t(($) => $.tab_body.common.unsaved_changes)}+ </span>)}<Button onClick={handleSave} disabled={!dirty || saving} size="sm">{saving ? (diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex bf6125aee0..e9a2a439c6 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -463,6 +463,8 @@"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.",+ "paste_invalid_toast": "Couldn't parse pasted environment variables","key_placeholder": "KEY","value_placeholder": "value","show_value_aria": "Show value",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 673341d9df..cf18f8e2f2 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -346,6 +346,8 @@"intro_prefix": "エージェントプロセスの起動時に注入されます(例: ","intro_separator": ", ","intro_suffix": ")。",+ "paste_hint": "KEY=value 形式の行をキー欄に貼り付けると、複数の環境変数を追加できます。",+ "paste_invalid_toast": "貼り付けた環境変数を解析できませんでした","key_placeholder": "KEY","value_placeholder": "value","show_value_aria": "値を表示",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex bfbdc83abe..865e58bacd 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -354,6 +354,8 @@"intro_prefix": "에이전트 프로세스가 시작될 때 주입됩니다(예: ","intro_separator": ", ","intro_suffix": ").",+ "paste_hint": "키 필드에 KEY=value 형식의 줄을 붙여넣으면 여러 환경 변수를 추가할 수 있습니다.",+ "paste_invalid_toast": "붙여넣은 환경 변수를 파싱할 수 없습니다","key_placeholder": "KEY","value_placeholder": "value","show_value_aria": "값 표시",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 370c34aa7c..112f175e47 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -453,6 +453,8 @@"intro_prefix": "在智能体进程启动时注入(例如 ","intro_separator": "、","intro_suffix": ")。",+ "paste_hint": "将 KEY=value 格式的内容粘贴到 key 输入框,即可添加多个环境变量。",+ "paste_invalid_toast": "无法解析粘贴的环境变量","key_placeholder": "KEY","value_placeholder": "值","show_value_aria": "显示值",