Let a bot and a workspace set their own envs

Envs had three scopes, general, workspace and computer. A bot had no
scope of its own, so the only way to give one worker a key was to set it
on a computer it happened to share.

The envs table gets a bot_id, and resolution now layers bot over
computer over workspace over general, so a bot's own key wins wherever it
runs. Every computer call site passes the run's bot_id, and grabRunEnvs
does the same for the {{env.KEY}} a custom tool or an MCP server's headers
read.

A bot's and a workspace's settings page can now edit their own envs, in
place, through the same save-env and delete-env routes: sending `scoped`
makes them answer with just that scope instead of the whole install's
overview. Super admins only, like the Environment page.
This commit is contained in:
2026-10-22 08:30:40 +01:00
parent 7a3d2df213
commit 96735de48f
38 changed files with 551 additions and 135 deletions
@@ -0,0 +1,155 @@
import { useState } from "react";
import Form from "@moduletrace/twui/form/Form";
import Input from "@moduletrace/twui/form/Input";
import Checkbox from "@moduletrace/twui/form/Checkbox";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Stack from "@moduletrace/twui/layout/Stack";
import type { EnvScope, EnvsMutationResult, KnownEnvStatus, PublicEnv } from "@/src/types";
import postEnvApi from "../../(functions)/post-env-api";
import SettingsStatus from "../settings-status";
type Props = {
scope: EnvScope;
/**
* Edits this env; adds one when not given.
*/
env?: PublicEnv;
/**
* Sets this app setting: its key, description and flags are fixed.
*/
known?: KnownEnvStatus;
onSaved: (data: EnvsMutationResult, msg: string) => void;
onCancel: () => void;
};
/**
* Adds or edits an env in one scope. A saved secret is never shown; typing
* a new value replaces it, leaving it empty keeps it.
*/
export default function EnvForm({ scope, env, known, onSaved, onCancel }: Props) {
const is_known = Boolean(known || env?.known);
const [key, setKey] = useState(env?.key || known?.key || "");
const [value, setValue] = useState(env && !env.secret ? env.value || "" : "");
const [description, setDescription] = useState(env?.description || "");
const [secret, setSecret] = useState(env?.secret ?? known?.secret ?? true);
const [expose, setExpose] = useState(env?.expose_to_computers ?? true);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
const id = `env-${env?.id || known?.key || "new"}`;
const keeps_secret = Boolean(env?.secret);
const submit = async () => {
if (loading) return;
if (!window.confirm(env?.id ? `Save ${env.key}?` : `Add ${key || "this env"}?`)) return;
setLoading(true);
setError(undefined);
const res = await postEnvApi({
path: "save-env",
body: {
env_id: env?.id,
key,
value: keeps_secret && !value ? undefined : value,
description: is_known ? undefined : description,
paradigm: scope.paradigm,
workspace_id: scope.paradigm == "workspace" ? scope.id : null,
computer_id: scope.paradigm == "computer" ? scope.id : null,
bot_id: scope.paradigm == "bot" ? scope.id : null,
scoped: scope.paradigm == "bot" || scope.paradigm == "workspace",
secret,
expose_to_computers: expose,
},
});
setLoading(false);
if (!res.success || !res.singleRes) {
setError(res.msg || "Couldn't save the env.");
return;
}
onSaved(res.singleRes, res.msg || "Saved.");
};
return (
<Form className="w-full gap-4! items-stretch py-4" onSubmit={submit}>
<Input
id={`${id}-key`}
title="Key"
label="Key"
showLabel
placeholder="GITHUB_TOKEN"
defaultValue={key}
disabled={Boolean(env) || is_known}
autoComplete="off"
onChange={(e) => setKey(e.target.value)}
/>
<Input
id={`${id}-value`}
title="Value"
label="Value"
showLabel
type={secret ? "password" : "text"}
autoComplete="off"
defaultValue={value}
placeholder={keeps_secret ? "Saved. Type a new value to replace it." : ""}
info="Encrypted before it's stored."
onChange={(e) => setValue(e.target.value)}
/>
{is_known ? null : (
<>
<Input
id={`${id}-description`}
title="Description"
label="Description"
showLabel
placeholder="A token for the company GitHub"
defaultValue={description}
info="Bots see the key and this description, never the value."
onChange={(e) => setDescription(e.target.value)}
/>
<Checkbox
title="Secret"
label="Secret: hidden once saved, and blanked out of everything bots read"
checked={secret}
changeHandler={setSecret}
/>
<Checkbox
title="Set on computers"
label="Set on computers, for bots' commands and code"
checked={expose}
changeHandler={setExpose}
/>
</>
)}
<Stack className="gap-3! items-stretch">
<SettingsStatus status={error ? { error: true, msg: error } : undefined} />
<Row className="gap-2! flex-nowrap justify-end">
<Button
title="Cancel"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={loading}
onClick={onCancel}
>
Cancel
</Button>
<Button
title={env ? "Save env" : "Add env"}
type="submit"
size="small"
loading={loading}
disabled={loading}
>
{env ? "Save env" : "Add env"}
</Button>
</Row>
</Stack>
</Form>
);
}
@@ -0,0 +1,49 @@
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import { Pencil, Plus, Trash2 } from "lucide-react";
type Props = {
name: string;
/**
* "set" for an app setting that isn't saved yet.
*/
mode: "edit" | "set";
busy?: boolean;
onEdit: () => void;
onRemove?: () => void;
};
/**
* Edit (or Set) and Remove for one env row.
*/
export default function EnvRowActions({ name, mode, busy, onEdit, onRemove }: Props) {
return (
<Row className="gap-1! flex-nowrap shrink-0">
<Button
title={mode == "set" ? `Set ${name}` : `Edit ${name}`}
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={onEdit}
>
{mode == "set" ? <Plus size={16} aria-hidden /> : <Pencil size={16} aria-hidden />}
</Button>
{onRemove ? (
<Button
title={`Remove ${name}`}
type="button"
variant="ghost"
color="gray"
size="small"
loading={busy}
disabled={busy}
onClick={onRemove}
>
<Trash2 size={16} aria-hidden />
</Button>
) : null}
</Row>
);
}
@@ -0,0 +1,100 @@
import { useState } from "react";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { EnvScope, EnvsMutationResult, KnownEnvStatus, PublicEnv } from "@/src/types";
import postEnvApi from "../../(functions)/post-env-api";
import EnvForm from "./env-form";
import EnvRowActions from "./env-row-actions";
type Props = {
scope: EnvScope;
/**
* The saved env, if any. An app setting may have none yet.
*/
env?: PublicEnv;
known?: KnownEnvStatus;
/**
* The bot or workspace's own list (its settings page) rather than the
* Environment page's overview.
*/
scoped?: boolean;
onChanged: (data: EnvsMutationResult, msg: string) => void;
onError: (msg: string) => void;
};
/**
* One env: its key, description and value (or "secret"), with Edit and
* Remove. Edit opens the form in place.
*/
export default function EnvRow({ scope, env, known, scoped, onChanged, onError }: Props) {
const [editing, setEditing] = useState(false);
const [busy, setBusy] = useState(false);
const key = env?.key || known?.key || "";
const remove = async () => {
if (!env || busy) return;
if (!window.confirm(`Remove ${key}? Computers drop it on their next run.`)) return;
setBusy(true);
const res = await postEnvApi({
path: "delete-env",
body: { env_id: env.id, scoped },
});
setBusy(false);
if (res.success && res.singleRes) onChanged(res.singleRes, res.msg || "Removed.");
else onError(res.msg || "Couldn't remove the env.");
};
if (editing) {
return (
<Stack className="w-full gap-0! items-stretch border-0 border-b border-solid border-hairline last:border-b-0">
<EnvForm
scope={scope}
env={env}
known={known}
onSaved={(data, msg) => {
setEditing(false);
onChanged(data, msg);
}}
onCancel={() => setEditing(false)}
/>
</Stack>
);
}
const status = env
? env.secret
? "Secret, saved"
: env.value || "Empty"
: known?.from_process
? "From the server's environment"
: "Not set";
const flags = env && !env.known && !env.expose_to_computers ? " · not on computers" : "";
return (
<Row className="w-full gap-3! flex-nowrap items-start justify-between py-3 border-0 border-b border-solid border-hairline last:border-b-0">
<Stack className="gap-0.5! min-w-0">
<Span className="text-sm font-bold leading-5 text-ink truncate">{key}</Span>
{env?.description || known?.description ? (
<Span className="text-[13px] leading-[18px] text-ink-secondary break-words">
{known?.description || env?.description}
</Span>
) : null}
<Span className="text-[13px] leading-[18px] text-ink-secondary break-all">
{status}
{flags}
</Span>
</Stack>
<EnvRowActions
name={key}
mode={env ? "edit" : "set"}
busy={busy}
onEdit={() => setEditing(true)}
onRemove={env ? remove : undefined}
/>
</Row>
);
}
@@ -0,0 +1,90 @@
import { useState } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import { Plus } from "lucide-react";
import type { EnvScope, EnvsMutationResult, PublicEnv } from "@/src/types";
import SettingsGroup from "../settings-group";
import SettingsList from "../settings-list";
import SettingsStatus from "../settings-status";
import EnvForm from "./env-form";
import EnvRow from "./env-row";
type Props = {
scope: EnvScope;
/**
* The scope's own envs (app settings left out).
*/
envs: PublicEnv[];
/**
* Set when the list is a bot's or workspace's own (its settings page)
* rather than the Environment page's overview.
*/
scoped?: boolean;
/**
* The heading, when it isn't plain "Envs".
*/
title?: string;
status?: {
error?: boolean;
success?: boolean;
msg?: string;
};
onChanged: (data: EnvsMutationResult, msg: string) => void;
onError: (msg: string) => void;
};
const Descriptions: Record<EnvScope["paradigm"], string> = {
general: "Set everywhere. A workspace, a bot or a computer can set the same key to override it.",
workspace: "For every bot working here. Beats general, loses to the bot's own.",
computer: "For this computer only. Beats a workspace, loses to the bot's own.",
bot: "For this bot only, everywhere it works. Beats the workspace, the computer and general.",
};
/**
* The envs bots and computers use, in one scope, with an add form.
*/
export default function EnvsGroup({ scope, envs, scoped, title, status, onChanged, onError }: Props) {
const [adding, setAdding] = useState(false);
return (
<SettingsGroup title={title || "Envs"} description={Descriptions[scope.paradigm]}>
<SettingsList is_empty={!envs.length} empty="Nothing set here yet.">
{envs.map((env) => (
<EnvRow
key={env.id}
scope={scope}
env={env}
scoped={scoped}
onChanged={onChanged}
onError={onError}
/>
))}
</SettingsList>
<SettingsStatus status={status} />
{adding ? (
<EnvForm
scope={scope}
onSaved={(data, msg) => {
setAdding(false);
onChanged(data, msg);
}}
onCancel={() => setAdding(false)}
/>
) : (
<Row className="gap-3! items-center justify-end">
<Button
title="Add an env"
type="button"
variant="outlined"
color="gray"
size="small"
onClick={() => setAdding(true)}
>
<Plus size={16} aria-hidden />
Add an env
</Button>
</Row>
)}
</SettingsGroup>
);
}
@@ -0,0 +1,42 @@
import { useState } from "react";
import type { EnvsMutationResult, ScopedEnvsPayload } from "@/src/types";
import EnvsGroup from "./envs-group";
type Props = {
/**
* A bot's own envs, or a workspace's. `null` when the viewer can't
* manage them, so the group isn't rendered at all.
*/
initial?: ScopedEnvsPayload | null;
};
/**
* The envs set on one bot or one workspace, on its settings page. Super
* admins only, like the Environment page.
*/
export default function ScopedEnvsGroup({ initial }: Props) {
const [data, setData] = useState<ScopedEnvsPayload | null>(initial || null);
const [status, setStatus] = useState<{
error?: boolean;
success?: boolean;
msg?: string;
}>();
if (!data?.can_manage) return null;
const changed = (result: EnvsMutationResult, msg: string) => {
if (result.scoped) setData(result.scoped);
setStatus({ success: true, msg });
};
return (
<EnvsGroup
scope={data.scope}
envs={data.envs}
scoped
status={status}
onChanged={changed}
onError={(msg) => setStatus({ error: true, msg })}
/>
);
}