Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: preserve environment variable raw editor values (#21044)

AmAzing-9b583f3b1ec9
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 4ae77d650bc..c90ae4ff416 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -607,11 +607,15 @@
"environments.form.filesDesc": "What this folder is called and what it holds for the agent.",
"environments.form.internetAccess": "Agent internet access",
"environments.form.internetAccessHint": "Setup always has network access. This controls the conversation itself.",
+ "environments.form.jsonSyntax": "Invalid JSON. Check double quotes, commas and braces, then save again.",
+ "environments.form.jsonValues": "Use a JSON object with a string value for every variable, such as {\"NODE_ENV\":\"production\"}.",
"environments.form.maintenance": "Maintenance command",
"environments.form.maintenanceHint": "Runs each time work resumes in a copy — refreshing a checkout, reapplying a migration. Not the setup command again: that one is expensive and is meant to run once.",
"environments.form.path": "Folder",
"environments.form.rawEditor": "Raw editor",
"environments.form.rawEditorHint": "One KEY=value per line, the way a .env file reads. Blank lines and # comments are ignored; saving replaces every variable.",
+ "environments.form.rawFormat": "Detected format: {{format}}",
+ "environments.form.rawFormatsHint": "Edit a JSON object with string values, or replace it with .env text (KEY=value per line). JSON decodes escapes; .env keeps backslashes literally. Saving replaces all variables.",
"environments.form.rawInvalid": "Line {{line}} is not KEY=value",
"environments.form.ref": "Branch or tag",
"environments.form.refDefault": "Repository default branch",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index b2eb2190028..09744a6f182 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -607,11 +607,15 @@
"environments.form.filesDesc": "这个文件夹叫什么、放了哪些给 agent 处理的文件。",
"environments.form.internetAccess": "对话联网",
"environments.form.internetAccessHint": "初始化命令始终可以联网,这里控制的是对话本身。",
+ "environments.form.jsonSyntax": "JSON 格式有误,请检查双引号、逗号和花括号后重新保存。",
+ "environments.form.jsonValues": "请使用每个变量值均为字符串的 JSON 对象,例如 {\"NODE_ENV\":\"production\"}。",
"environments.form.maintenance": "维护命令",
"environments.form.maintenanceHint": "每次回到这个副本继续工作时执行——更新代码、补一次迁移。它不是再跑一遍初始化命令:那个很贵,本来就只该跑一次。",
"environments.form.path": "目录",
"environments.form.rawEditor": "原始编辑器",
"environments.form.rawEditorHint": "每行一条 KEY=value,和 .env 文件一样。空行和 # 注释会被忽略;保存会替换全部变量。",
+ "environments.form.rawFormat": "当前识别格式:{{format}}",
+ "environments.form.rawFormatsHint": "编辑值为字符串的 JSON 对象,或替换为 .env 文本(每行 KEY=value)。JSON 会解析转义字符;.env 会保留原样的反斜杠。保存会替换全部变量。",
"environments.form.rawInvalid": "第 {{line}} 行不是 KEY=value 格式",
"environments.form.ref": "分支或标签",
"environments.form.refDefault": "仓库默认分支",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index e25f2dbba90..471e990ac72 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4220,6 +4220,13 @@ When I am ___, I need ___
'environments.form.rawEditor': 'Raw editor',
'environments.form.rawEditorHint':
'One KEY=value per line, the way a .env file reads. Blank lines and # comments are ignored; saving replaces every variable.',
+ 'environments.form.rawFormat': 'Detected format: {{format}}',
+ 'environments.form.rawFormatsHint':
+ 'Edit a JSON object with string values, or replace it with .env text (KEY=value per line). JSON decodes escapes; .env keeps backslashes literally. Saving replaces all variables.',
+ 'environments.form.jsonSyntax':
+ 'Invalid JSON. Check double quotes, commas and braces, then save again.',
+ 'environments.form.jsonValues':
+ 'Use a JSON object with a string value for every variable, such as {"NODE_ENV":"production"}.',
'environments.form.rawInvalid': 'Line {{line}} is not KEY=value',
'environments.form.removeEnv': 'Remove variable',
'environments.form.internetAccess': 'Agent internet access',
diff --git a/src/features/EnvironmentManager/EnvironmentVariables.test.ts b/src/features/EnvironmentManager/EnvironmentVariables.test.ts
index 70a72e107ab..b0188e4ef29 100644
--- a/src/features/EnvironmentManager/EnvironmentVariables.test.ts
+++ b/src/features/EnvironmentManager/EnvironmentVariables.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { formatDotenv, parseDotenv } from './EnvironmentVariables';
+import {
+ formatRawVariables,
+ getRawVariableFormat,
+ parseDotenv,
+ parseJsonVariables,
+ parseRawVariables,
+} from './EnvironmentVariables';
describe('parseDotenv', () => {
it('should read KEY=value lines and skip blanks and comments', () => {
@@ -28,12 +34,115 @@ describe('parseDotenv', () => {
expect(parseDotenv('1BAD=x')).toEqual({ line: 1 });
});
- it('should round-trip through formatDotenv', () => {
+ it('should round-trip through the JSON editor', () => {
const entries: [string, string][] = [
['PLAIN', 'value'],
['SPACED', 'two words'],
['HASH', 'a#b'],
];
- expect(parseDotenv(formatDotenv(entries))).toEqual({ entries });
+ expect(parseRawVariables(formatRawVariables(entries))).toEqual({ entries });
+ });
+
+ it.each([
+ 'say "hello" C:\\qa',
+ '"quoted"',
+ 'both \'single\' and "double" quotes',
+ 'line one\nline two\r\nlast',
+ 'tab\there',
+ ' padded ',
+ '\\n is literal',
+ 'control\u0000character',
+ ])('should preserve %j across repeated raw editor saves', (value) => {
+ const entries: [string, string][] = [['QA_VALUE', value]];
+ const first = parseRawVariables(formatRawVariables(entries));
+ expect(first).toEqual({ entries });
+ if ('entries' in first) {
+ expect(parseRawVariables(formatRawVariables(first.entries))).toEqual({ entries });
+ }
+ });
+
+ it('should preserve JSON-valid escapes in double-quoted dotenv imports', () => {
+ expect(
+ parseDotenv(String.raw`A="C:\test\new"
+B="\u0041"`),
+ ).toEqual({
+ entries: [
+ ['A', String.raw`C:\test\new`],
+ ['B', String.raw`\u0041`],
+ ],
+ });
+ });
+
+ it('should retain literal backslashes in single-quoted and unquoted imports', () => {
+ expect(
+ parseDotenv(String.raw`A='C:\test\new'
+B=C:\test\new
+C="C:\qa"`),
+ ).toEqual({
+ entries: [
+ ['A', String.raw`C:\test\new`],
+ ['B', String.raw`C:\test\new`],
+ ['C', String.raw`C:\qa`],
+ ],
+ });
+ });
+});
+
+describe('raw variable formats', () => {
+ it('should identify JSON and dotenv without changing dotenv escape semantics', () => {
+ expect(getRawVariableFormat(' {"A": "value"}')).toBe('json');
+ expect(getRawVariableFormat('A="value"')).toBe('dotenv');
+ expect(
+ parseRawVariables(String.raw`A="C:\test\new"
+B="\u0041"
+C="\b\f\r\t"`),
+ ).toEqual({
+ entries: [
+ ['A', String.raw`C:\test\new`],
+ ['B', String.raw`\u0041`],
+ ['C', String.raw`\b\f\r\t`],
+ ],
+ });
+ });
+
+ it('should decode edited JSON and preserve it after reopening and saving', () => {
+ const edited = String.raw`{"PATH":"C:\\test\\new", "TEXT":"say \"hello\"\nnext", "UNICODE":"\u0041"}`;
+ const result = parseRawVariables(edited);
+ expect(result).toEqual({
+ entries: [
+ ['PATH', String.raw`C:\test\new`],
+ ['TEXT', 'say "hello"\nnext'],
+ ['UNICODE', 'A'],
+ ],
+ });
+ if ('entries' in result) {
+ expect(parseRawVariables(formatRawVariables(result.entries))).toEqual(result);
+ }
+ });
+
+ it.each(['null', '[]', '1', 'true', '"text"', '{"A":1}', '{"A":null}', '{"A":[]}', '{"A":{}}'])(
+ 'should reject non-string JSON objects: %s',
+ (text) => {
+ expect(parseJsonVariables(text)).toEqual({ error: 'jsonValues' });
+ },
+ );
+
+ it('should reject incomplete JSON without interpreting it as dotenv', () => {
+ expect(parseRawVariables('{"A":"value"')).toEqual({ error: 'jsonSyntax' });
+ expect(parseRawVariables('["value"]')).toEqual({ error: 'jsonValues' });
+ });
+
+ it('should support empty values, empty objects and duplicate keys', () => {
+ expect(parseRawVariables('{"A":"old","A":""}')).toEqual({ entries: [['A', '']] });
+ expect(parseRawVariables('{}')).toEqual({ entries: [] });
+ expect(parseRawVariables('')).toEqual({ entries: [] });
+ });
+
+ it('should preserve property-like variable names without modifying prototypes', () => {
+ const entries: [string, string][] = [
+ ['__proto__', 'literal'],
+ ['constructor', 'value'],
+ ];
+ expect(parseRawVariables(formatRawVariables(entries))).toEqual({ entries });
});
});
diff --git a/src/features/EnvironmentManager/EnvironmentVariables.tsx b/src/features/EnvironmentManager/EnvironmentVariables.tsx
index c3248bbf4e2..5b35c6d23d2 100644
--- a/src/features/EnvironmentManager/EnvironmentVariables.tsx
+++ b/src/features/EnvironmentManager/EnvironmentVariables.tsx
@@ -1,5 +1,6 @@
'use client';
+import { isRecord } from '@lobechat/utils/object';
import {
ActionIcon,
Button,
@@ -62,8 +63,9 @@ type Entry = [string, string];
/**
* Parse `.env`-style text: one `KEY=value` per line, blank lines and `#`
* comments skipped, an optional `export ` prefix and a matching pair of quotes
- * around the value dropped. Later lines win over earlier ones with the same
- * key, as they would when a shell sources the file.
+ * around the value dropped. Quoted values keep literal backslashes; JSON
+ * escaping belongs to the separate JSON editor format. Later duplicate keys win,
+ * as they would when a shell sources the file.
*
* @returns the entries, or the 1-based number of the first line that is not a
* `KEY=value` pair
@@ -85,11 +87,33 @@ export const parseDotenv = (text: string): { entries: Entry[] } | { line: number
return { entries: [...entries.entries()] };
};
-/** The inverse, for the raw editor's starting text. */
-export const formatDotenv = (entries: Entry[]) =>
- entries
- .map(([key, value]) => `${key}=${/[\s#"']/.test(value) ? JSON.stringify(value) : value}`)
- .join('\n');
+/** JSON is unambiguous for editing escapes; .env imports retain literal semantics. */
+export const formatRawVariables = (entries: Entry[]) =>
+ JSON.stringify(Object.fromEntries(entries), null, 2);
+
+export const getRawVariableFormat = (text: string) =>
+ /^[{[]/.test(text.trimStart()) ? 'json' : 'dotenv';
+
+export const parseJsonVariables = (
+ text: string,
+): { entries: Entry[] } | { error: 'jsonSyntax' | 'jsonValues' } => {
+ let value: unknown;
+ try {
+ value = JSON.parse(text);
+ } catch {
+ return { error: 'jsonSyntax' };
+ }
+ if (!isRecord(value)) return { error: 'jsonValues' };
+ const entries: Entry[] = [];
+ for (const [key, entry] of Object.entries(value)) {
+ if (typeof entry !== 'string') return { error: 'jsonValues' };
+ entries.push([key, entry]);
+ }
+ return { entries };
+};
+
+export const parseRawVariables = (text: string) =>
+ getRawVariableFormat(text) === 'json' ? parseJsonVariables(text) : parseDotenv(text);
/**
* One variable, either as a row or open for editing. Key and value edit
@@ -227,12 +251,16 @@ const EnvironmentVariables = memo<EnvironmentVariablesProps>(({ entries, onSave
const openRaw = () => {
setAdding(null);
- setRaw(formatDotenv(entries));
+ setRaw(formatRawVariables(entries));
};
const saveRaw = () => {
if (raw === null) return;
- const parsed = parseDotenv(raw);
+ const parsed = parseRawVariables(raw);
+ if ('error' in parsed) {
+ toast.error(t(`environments.form.${parsed.error}`));
+ return;
+ }
if ('line' in parsed) {
toast.error(t('environments.form.rawInvalid', { line: parsed.line }));
return;
@@ -295,16 +323,22 @@ const EnvironmentVariables = memo<EnvironmentVariablesProps>(({ entries, onSave
{raw !== null ? (
<Flexbox gap={6}>
+ <Text fontSize={12} weight={500}>
+ {t('environments.form.rawFormat', {
+ format: getRawVariableFormat(raw) === 'json' ? 'JSON' : '.env',
+ })}
+ </Text>
<TextArea
autoFocus
+ aria-label={t('environments.form.rawEditor')}
classNames={{ input: styles.editor }}
- placeholder={'NODE_ENV=production\nAPI_URL=https://example.com'}
+ placeholder={'{\n "NODE_ENV": "production"\n}'}
rows={Math.min(16, Math.max(6, raw.split('\n').length + 1))}
value={raw}
onChange={(event) => setRaw(event.target.value)}
/>
<Text fontSize={12} type={'secondary'}>
- {t('environments.form.rawEditorHint')}
+ {t('environments.form.rawFormatsHint')}
</Text>
</Flexbox>
) : entries.length === 0 && !adding ? (