Skip to content

Commit c826356

Browse files
shizhiguclaude
andauthored
feat(settings): add user env vars UI + shell injection (anomalyco#1548)
* feat(settings): add user env vars UI + shell injection Add a Settings → Environment pane for user-level environment variables persisted to ~/.config/openwork/env.json (0o600), plus shell and orchestrator injection so the values reach every child process OpenWork spawns (OpenCode, OpenWork server, opencode-router). Fixes the Linux GUI silent-auth-failure case where shell env isn't inherited. Scope is the OSS / self-hosted path; Den's cloud LLM Providers push continues to own the org-signed-in case. Closes anomalyco#1436. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(settings): whitelist 'environment' tab in parseSettingsPath parseSettingsPath had a hardcoded switch listing every known tab. The new 'environment' case wasn't in it, so /settings/environment fell through to default: and redirected to /settings/general. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(env-vars): reframe copy around service credentials, not plumbing The initial copy described env vars in defensive terms ("so the app can read them without a terminal launch"), which hides the actual value: a single place to drop credentials for every external service skills and MCPs call into (ElevenLabs, Gemini image APIs, GitHub, LangSmith, cloud projects, corporate proxies, etc.). - Reframe settings.tab_description_environment to lead with user intent. - Reframe the panel description to mention MCPs + plugin subprocesses explicitly, since those are the biggest consumers. - Empty-state example keys broadened from just ANTHROPIC_API_KEY to a cross-section that reflects actual workspace usage. - PRD "Why" section rewritten on the same axis, with explicit non-overlap callouts vs. OpenCode provider auth and Den's cloud LLM Providers push. Copy updates applied to en, zh, ja; other locales fall back to en. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(env-vars): tighten auth, harden UI, expand tests Server: - Routes switch from `host` to `host-token` auth. Owner-scoped remote bearer tokens are now also rejected — env vars are strictly desktop-host-only. - env-file loader + reserved-keys policy tightened in line with Rust / Electron / orchestrator loaders. Tests: - env-routes.e2e.test.ts gains owner-bearer rejection + CORS PUT preflight tests. - 23 pass total across env-file + env-routes; full server suite 106/0. UI: - environment-view.tsx: ConfirmModal instead of window.confirm, request-race guard on refresh, Escape-to-close editor, aria labels, cleaner empty / loading state for remote workspaces. Copy: - en / zh / ja strings pruned to reflect service-credentials framing; PRD updated to match. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(env-vars): polish apply flow and evidence * Harden env var prompt context * chore(env-vars): add locale fallbacks * fix env store corruption handling * block env apply while tasks run * fix sidecar signing path list * fix env apply state and store races --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 6487285 commit c826356

39 files changed

Lines changed: 2848 additions & 58 deletions
230 KB
Loading
8.41 MB
Binary file not shown.
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
# Environment variables UI
2+
3+
Closes #1436.
4+
5+
## Why
6+
7+
Agentic workflows pull in secrets from every direction — LLM provider keys,
8+
ElevenLabs for TTS, Gemini / Nano Banana for images, GitHub tokens for repo
9+
automation, cloud project IDs, corporate proxies and CA certs. Skills and
10+
MCPs in a workspace assume those values exist in the process environment.
11+
12+
Today the only way to get them there is to edit shell rc files and launch
13+
OpenWork from a terminal, which:
14+
15+
- **Breaks entirely on Linux GUI launches** (`.bashrc` isn't sourced) — the
16+
concrete user report in #1436.
17+
- **Is invisible friction for non-technical teammates** (the "Susan" persona
18+
called out in `AGENTS.md`).
19+
- Has no masking, no audit trail, no reserved-keys guardrail.
20+
21+
This PR adds a first-class **Settings → Environment** pane. Credentials go
22+
in once, and every child OpenWork spawns — OpenCode, the OpenWork server,
23+
opencode-router, and any MCP or plugin those three launch — inherits them
24+
via OS process environment.
25+
26+
Boundaries vs. adjacent features:
27+
28+
- Not a replacement for OpenCode's native `provider auth` flow, which owns
29+
credentials for LLM providers OpenCode directly supports (stored in
30+
`auth.json`). Users should keep using that for model keys where possible.
31+
- Not a replacement for Den's cloud `LLM Providers` push, which owns
32+
org-wide distribution for signed-in users. On remote workspaces, the pane
33+
shows a read-only hint and does not fetch or display local env values.
34+
- This fills the OSS / local-machine path for every other service skills
35+
and MCPs call into — ElevenLabs, Gemini image APIs, GitHub, Notion,
36+
LangSmith / OTEL exporters, proxy + CA-cert config, and so on.
37+
38+
## Storage
39+
40+
Deterministic path, identical across every loader:
41+
42+
| OS | Path |
43+
| --- | --- |
44+
| Linux / macOS | `~/.config/openwork/env.json` |
45+
| Windows | `%APPDATA%\openwork\env.json` |
46+
47+
Override via `OPENWORK_ENV_STORE` (mirrors `OPENWORK_TOKEN_STORE`). The file
48+
is written with `0o600` perms on POSIX.
49+
50+
Shape:
51+
52+
```json
53+
{
54+
"schemaVersion": 1,
55+
"updatedAt": 1714000000000,
56+
"variables": [
57+
{ "key": "ANTHROPIC_API_KEY", "value": "sk-ant-...", "updatedAt": 1714000000000 }
58+
]
59+
}
60+
```
61+
62+
## Server
63+
64+
`EnvService` at `apps/server/src/env-file.ts` — mirrors the `TokenService`
65+
pattern. Four desktop-host-token routes on the OpenWork server, so remote
66+
owner/collaborator/viewer clients and OpenCode tools are structurally unable to
67+
reach them:
68+
69+
- `GET /env` → `{ items: [{ key, value, updatedAt }] }` (values raw; the UI masks presentationally)
70+
- `GET /env/keys` → `{ keys: [...] }` (names only, used for agent context)
71+
- `PUT /env` → single entry `{ key, value }` or batch `{ entries: [...] }`
72+
- `DELETE /env/:key`
73+
74+
## Shell spawn injection
75+
76+
Same file, four loaders that agree byte-for-byte on path + reserved-keys policy:
77+
78+
| Host | File | Integration point |
79+
| --- | --- | --- |
80+
| Tauri (Rust) | `apps/desktop/src-tauri/src/env_file.rs` | merged into 4 spawn sites alongside `bun_env_overrides()` |
81+
| Electron (Node) | inline in `apps/desktop/electron/runtime.mjs` | single `buildChildEnv()` helper |
82+
| Orchestrator (TS) | inline in `apps/orchestrator/src/cli.ts` | single `buildSpawnEnv()` helper |
83+
| Server injection helper | `EnvService.readForInjection()` | reserved by consumers that want to reuse the TS reader |
84+
85+
Merge order on every host: **user env first, process env / caller env wins.**
86+
This matches the Linux-GUI case (no shell env → user env fills in) and never
87+
lets the user shadow wiring the shell has already set.
88+
89+
Reserved-keys policy: **any key starting with `OPENWORK_` or `OPENCODE_`** is
90+
refused at write time and stripped at read time. Defends against a
91+
hand-edited `env.json` that tries to shadow auth credentials.
92+
93+
## UI
94+
95+
`apps/app/src/react-app/domains/settings/pages/environment-view.tsx` —
96+
self-contained React pane registered as a **global** settings tab (user-level
97+
data, not workspace-scoped). Drops into the existing settings shell with one
98+
line in each of `types.ts`, `settings-page.tsx`, `settings-route.tsx`.
99+
100+
- Table with masked values (`ab••••yz`), reveal/hide toggle per row, add/edit
101+
modal, delete-with-confirm.
102+
- Client-side key validation mirrors the server (`^[A-Za-z_][A-Za-z0-9_]*$`)
103+
+ reserved-prefix check.
104+
- Writes are saved immediately and then marked as pending. The user can click
105+
**Apply changes** to restart the local agents so the new environment is
106+
active without a full app relaunch.
107+
- Remote workspaces show a read-only hint and do not list local env values.
108+
109+
## Reload semantics
110+
111+
Env vars are fixed in a process's environment at spawn time, so saving the
112+
file alone cannot update an already-running OpenCode/server/router child. The
113+
pane makes that explicit: after a successful write it shows a pending state and
114+
an **Apply changes** action. Applying restarts the local OpenWork runtime with
115+
the sidecar orchestrator path, preserves the local workspace list and remote
116+
access setting, reconnects the client, then clears the pending state.
117+
118+
Until pending changes are applied, the app does not inject newly saved key names
119+
into agent system context. That avoids the agent claiming a key is configured
120+
before the running processes can actually read it.
121+
122+
The same restart boundary is used for delete: removed key names stop appearing
123+
after **Apply changes**.
124+
125+
## Agent context
126+
127+
The app never sends secret values to the model. When there are no pending
128+
environment changes, it calls `GET /env/keys` and sends only configured key
129+
names as per-message system context:
130+
131+
```text
132+
OpenWork environment variables configured:
133+
- EXAMPLE_API_KEY
134+
135+
Only names are shown; values are secret. Use these names when relevant.
136+
```
137+
138+
This is not written into `AGENTS.md`; OpenCode combines it with its normal
139+
instruction sources for that prompt.
140+
141+
## i18n
142+
143+
All strings live under the `settings.environment.*` and
144+
`settings.tab_*_environment` namespaces. Full translations in `en.ts`,
145+
`zh.ts`, `ja.ts`. Other locales (`vi`, `pt-BR`, `th`, `fr`, `ca`, `es`) fall
146+
back to English via the existing `t()` runtime (`i18n/index.ts:109-113`), so
147+
nothing ships as raw keys.
148+
149+
## Tests
150+
151+
| Layer | File | What |
152+
| --- | --- | --- |
153+
| Server unit | `apps/server/src/env-file.test.ts` | 12 tests — path resolution, validation, reserved keys, perms, round-trip, tampered-file defense |
154+
| Server HTTP e2e | `apps/server/src/env-routes.e2e.test.ts` | 12 tests — auth 401, owner-bearer rejection, CORS PUT preflight, PUT/GET round-trip, key-name-only route, batch PUT, invalid key 400, reserved key 400, DELETE missing/found, restart persistence |
155+
| Tauri Rust unit | `apps/desktop/src-tauri/src/env_file.rs` | 4 tests — missing file, malformed JSON, well-formed load, reserved-key strip |
156+
157+
Bun picks up `*.e2e.test.ts` automatically — no CI wiring change.
158+
159+
## Verification ran in latest review
160+
161+
```
162+
pnpm --filter openwork-server test # 107 pass, 0 fail
163+
bun test ./src/env-file.test.ts ./src/env-routes.e2e.test.ts # 24 pass, 0 fail
164+
pnpm --filter openwork-server typecheck # clean
165+
pnpm --filter openwork-server build:bin # ok
166+
pnpm --filter openwork-orchestrator typecheck # clean
167+
pnpm --filter @openwork/app typecheck # clean
168+
pnpm build:ui # ok (production Vite; large chunk warning unchanged)
169+
node --check apps/desktop/electron/runtime.mjs # ok
170+
node --check apps/desktop/scripts/prepare-sidecar.mjs # ok
171+
node --check apps/desktop/scripts/tauri-before-dev.mjs # ok
172+
PATH="$HOME/.cargo/bin:$PATH" cargo test env_file # 4 pass, 0 fail
173+
git diff --check # clean
174+
```
175+
176+
## Evidence
177+
178+
- Screenshot: `apps/app/pr/environment-variables-dark.png`
179+
- Demo recording: `apps/app/pr/environment-variables-demo.mp4`
180+
181+
## Non-goals (follow-ups)
182+
183+
- OS keychain storage (`PRINCIPLES.md` line 29). JSON + `0o600` matches the
184+
existing `tokens.ts` precedent and keeps the Rust reader trivial (no
185+
keychain FFI). A follow-up PR can migrate values into the keychain while
186+
leaving the JSON file as a manifest of key names + timestamps.
187+
- Per-workspace scoping. The issue asks for user-level; workspace overrides
188+
are a separate feature.
189+
- Cloud push for MCP keys — owned by the Den / LLM Providers team.
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
const PENDING_CHANGES_KEY = "openwork.settings.environment.pendingChanges";
2+
3+
type PendingChangesState = {
4+
pending: boolean;
5+
runtimeKey?: string;
6+
};
7+
8+
function getStorage(kind: "localStorage" | "sessionStorage"): Storage | null {
9+
if (typeof window === "undefined") return null;
10+
try {
11+
return window[kind] ?? null;
12+
} catch {
13+
return null;
14+
}
15+
}
16+
17+
function parsePendingChangesState(raw: string | null): PendingChangesState {
18+
if (!raw) return { pending: false };
19+
if (raw === "1") return { pending: true };
20+
try {
21+
const parsed = JSON.parse(raw) as { pending?: unknown; runtimeKey?: unknown };
22+
return {
23+
pending: parsed.pending === true,
24+
runtimeKey: typeof parsed.runtimeKey === "string" && parsed.runtimeKey.trim()
25+
? parsed.runtimeKey.trim()
26+
: undefined,
27+
};
28+
} catch {
29+
return { pending: false };
30+
}
31+
}
32+
33+
export function buildOpenworkEnvRuntimeKey(input: {
34+
baseUrl?: string | null;
35+
pid?: number | null;
36+
port?: number | null;
37+
}): string | undefined {
38+
const baseUrl = (input.baseUrl?.trim() ?? "").replace(/\/+$/, "");
39+
const pid = typeof input.pid === "number" && Number.isFinite(input.pid) && input.pid > 0
40+
? `pid:${input.pid}`
41+
: "";
42+
const port = !pid && typeof input.port === "number" && Number.isFinite(input.port) && input.port > 0
43+
? `port:${input.port}`
44+
: "";
45+
const runtime = pid || port;
46+
if (!baseUrl && !runtime) return undefined;
47+
return `${baseUrl || "openwork"}::${runtime || "runtime"}`;
48+
}
49+
50+
export function readOpenworkEnvPendingChanges(runtimeKey?: string | null): boolean {
51+
const localStorage = getStorage("localStorage");
52+
const sessionStorage = getStorage("sessionStorage");
53+
const state = parsePendingChangesState(localStorage?.getItem(PENDING_CHANGES_KEY) ?? null);
54+
const legacySessionState = parsePendingChangesState(
55+
sessionStorage?.getItem(PENDING_CHANGES_KEY) ?? null,
56+
);
57+
const pending = state.pending ? state : legacySessionState;
58+
if (!pending.pending) return false;
59+
60+
const currentRuntimeKey = runtimeKey?.trim() || undefined;
61+
if (currentRuntimeKey && pending.runtimeKey && pending.runtimeKey !== currentRuntimeKey) {
62+
writeOpenworkEnvPendingChanges(false);
63+
return false;
64+
}
65+
66+
return true;
67+
}
68+
69+
export function writeOpenworkEnvPendingChanges(value: boolean, runtimeKey?: string | null): void {
70+
const localStorage = getStorage("localStorage");
71+
const sessionStorage = getStorage("sessionStorage");
72+
try {
73+
if (value) {
74+
const payload = {
75+
pending: true,
76+
changedAt: Date.now(),
77+
...(runtimeKey?.trim() ? { runtimeKey: runtimeKey.trim() } : {}),
78+
};
79+
localStorage?.setItem(PENDING_CHANGES_KEY, JSON.stringify(payload));
80+
sessionStorage?.removeItem(PENDING_CHANGES_KEY);
81+
} else {
82+
localStorage?.removeItem(PENDING_CHANGES_KEY);
83+
sessionStorage?.removeItem(PENDING_CHANGES_KEY);
84+
}
85+
} catch {
86+
// ignore persistence failures
87+
}
88+
}

0 commit comments

Comments
 (0)