Skip to content

An open-source, faster Devin alternative

TypeScript

web: Secrets page for the computer's organization secrets (work 095 step 3)

Igor Zalutski via Computerbf386b234478
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 4007d135..bd1c7901 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -30,6 +30,9 @@ const SandboxWebhooks = lazy(() => import('./pages/SandboxWebhooks'))
const DeferredAction = lazy(() => import('./pages/DeferredAction'))
const ManagedAgentsHome = lazy(() => import('./managed-agents/Home'))
const ManagedComputer = lazy(() => import('./managed-agents/Computer'))
+const ManagedComputerSecrets = lazy(
+ () => import('./managed-agents/ComputerSecrets'),
+)
const ManagedAgentDetail = lazy(() => import('./managed-agents/Detail'))
const ManagedProjectDetail = lazy(() => import('./managed-agents/Project'))
const ManagedSessionDetail = lazy(() => import('./managed-agents/Session'))
@@ -96,6 +99,10 @@ export default function App() {
}
/>
<Route path="computer" element={<ManagedComputer />} />
+ <Route
+ path="computer/secrets"
+ element={<ManagedComputerSecrets />}
+ />
{managedAgentsExperimentEnabled ? (
<Route path="automations" element={<ManagedAgentsHome list />} />
) : null}
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 0398371d..c69b5d90 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -134,11 +134,14 @@ function errorDetails(body: unknown): Record<string, unknown> | undefined {
// The authenticated request with error normalization, returning the raw
// Response for callers that need headers (a memory document's ETag) as well
// as the body. `apiFetch` is the JSON-and-schema layer over it.
+// `base` is `/api` for the public API's routes a dashboard session may also
+// call, such as the computer's secrets (work 095).
export async function apiFetchResponse(
path: string,
options: RequestInit = {},
+ base: '/api' | typeof API_BASE = API_BASE,
): Promise<Response> {
- const res = await fetch(`${API_BASE}${path}`, {
+ const res = await fetch(`${base}${path}`, {
...options,
credentials: 'include',
headers: {
@@ -169,6 +172,7 @@ export async function apiFetch<T>(
path: string,
options: RequestInit = {},
schema?: z.ZodType<T>,
+ base: '/api' | typeof API_BASE = API_BASE,
): Promise<T> {
// Opt-in, dev-only preview mode: serve canned data with no backend/auth so
// the dashboard can be rendered locally (VITE_PREVIEW=1 npm run dev). Require
@@ -179,7 +183,7 @@ export async function apiFetch<T>(
return validate(schema, await mockFetch<unknown>(path, options), path)
}
- const res = await apiFetchResponse(path, options)
+ const res = await apiFetchResponse(path, options, base)
if (res.status === 204) {
return undefined as T
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index 03cf548c..398dbeae 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -1677,6 +1677,51 @@ function previewComputerSessions() {
let previewProjectServiceAttachments: Array<Record<string, unknown>> = []
+// The computer's organization secrets (work 095); `?secrets=none` shows the
+// empty page.
+const previewSecretActor = (name: string) => ({ member: `usr_${name}`, name })
+function previewOrgSecrets() {
+ if (new URLSearchParams(window.location.search).get('secrets') === 'none')
+ return { secrets: [] }
+ const at = (hours: number) =>
+ new Date(Date.now() - hours * 3_600_000).toISOString()
+ const row = (
+ name: string,
+ by: string,
+ updated: number,
+ used: number | null,
+ extra: Record<string, unknown> = {},
+ ) => ({
+ name,
+ layer: 'organization',
+ kind: 'secret',
+ file: false,
+ createdAt: at(updated + 240),
+ createdBy: previewSecretActor(by),
+ updatedAt: at(updated),
+ updatedBy: previewSecretActor(by),
+ lastUsedAt: used === null ? null : at(used),
+ overriddenIn: { threads: 0, people: 0 },
+ ...extra,
+ })
+ return {
+ secrets: [
+ row('EXECUTOR_API_KEY', 'Ayush', 26, 2, {
+ overriddenIn: { threads: 1, people: 0 },
+ }),
+ row('GITHUB_TOKEN', 'Igor', 240, 0.1, {
+ overriddenIn: { threads: 0, people: 2 },
+ }),
+ row('GCP_SERVICE_ACCOUNT', 'Mohamed', 400, 30, { file: true }),
+ row('LINEAR_API_KEY', 'Utpal', 480, 24),
+ row('OPENAI_BASE_URL', 'Mohamed', 72, null, {
+ kind: 'variable',
+ value: 'https://gateway.example.com/v1',
+ }),
+ ],
+ }
+}
+
// Ordered most-specific first. Matched against the path (without /api/dashboard).
const ROUTES: Array<[RegExp, Handler]> = [
[/^\/me$/, () => me],
@@ -1686,6 +1731,28 @@ const ROUTES: Array<[RegExp, Handler]> = [
],
[/^\/managed-agents\/agents$/, () => ({ agents: managedAgentItems })],
[/^\/managed-agents\/computer$/, previewComputer],
+ [
+ /^\/managed-agents\/computer\/secrets\/[^/]+\/events$/,
+ () => ({
+ events: [
+ {
+ at: new Date(Date.now() - 26 * 3_600_000).toISOString(),
+ action: 'replace',
+ kind: 'secret',
+ actor: previewSecretActor('Ayush'),
+ via: 'dashboard',
+ },
+ {
+ at: new Date(Date.now() - 266 * 3_600_000).toISOString(),
+ action: 'set',
+ kind: 'secret',
+ actor: { slackUserId: 'U0PREVIEW' },
+ via: 'slack',
+ },
+ ],
+ }),
+ ],
+ [/^\/managed-agents\/computer\/secrets$/, previewOrgSecrets],
[
/^\/managed-agents\/computer\/sessions$/,
() => ({ sessions: previewComputerSessions() }),
diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.ts
index 74b856d2..1a3b4895 100644
--- a/web/src/components/app-shell-nav.ts
+++ b/web/src/components/app-shell-nav.ts
@@ -8,6 +8,7 @@ import {
Computer,
Database,
FolderKanban,
+ KeyRound,
KeySquare,
Layers,
MessagesSquare,
@@ -134,7 +135,10 @@ export function managedAgentsNav(options: {
groups.push({
items: [
...(options.computerEnabled
- ? [{ to: '/computer', label: 'Computer', icon: Computer }]
+ ? [
+ { to: '/computer', label: 'Computer', icon: Computer, end: true },
+ { to: '/computer/secrets', label: 'Secrets', icon: KeyRound },
+ ]
: []),
{ to: '/automations', label: 'Automations', icon: FolderKanban },
],
diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.ts
index f93cdb43..120c90d9 100644
--- a/web/src/components/app-shell.test.ts
+++ b/web/src/components/app-shell.test.ts
@@ -14,14 +14,15 @@ describe('managed agents navigation', () => {
computerEnabled: true,
})
expect(nav.map((group) => group.items.map((item) => item.label))).toEqual([
- ['Computer', 'Automations'],
+ ['Computer', 'Secrets', 'Automations'],
['Connections'],
])
expect(nav[0]?.items[0]).toMatchObject({
to: '/computer',
label: 'Computer',
})
- expect(nav[0]?.items[1]).toMatchObject({ to: '/automations' })
+ expect(nav[0]?.items[1]).toMatchObject({ to: '/computer/secrets' })
+ expect(nav[0]?.items[2]).toMatchObject({ to: '/automations' })
expect(nav[1]?.items[0]).toMatchObject({
to: '/managed-agents/connections',
label: 'Connections',
@@ -34,7 +35,7 @@ describe('managed agents navigation', () => {
managedAgentsNav({ ...defaults, computerEnabled: true }).map((group) =>
group.items.map((item) => item.label),
),
- ).toEqual([['Computer', 'Automations'], ['Connections']])
+ ).toEqual([['Computer', 'Secrets', 'Automations'], ['Connections']])
})
it('hides the computer from organizations without it (rollout flag)', () => {
diff --git a/web/src/managed-agents/ComputerSecrets.test.tsx b/web/src/managed-agents/ComputerSecrets.test.tsx
new file mode 100644
index 00000000..8298ad03
--- /dev/null
+++ b/web/src/managed-agents/ComputerSecrets.test.tsx
@@ -0,0 +1,211 @@
+// @vitest-environment happy-dom
+
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ApiError } from '@/api/errors'
+
+const secretsApi = vi.hoisted(() => ({
+ getOrgSecrets: vi.fn(),
+ getSecretEvents: vi.fn(),
+ putOrgSecret: vi.fn(),
+ deleteOrgSecret: vi.fn(),
+}))
+vi.mock('./computer-secrets-api', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./computer-secrets-api')>()),
+ ...secretsApi,
+}))
+
+const { ComputerSecrets } = await import('./ComputerSecrets')
+
+const row = {
+ name: 'EXECUTOR_API_KEY',
+ layer: 'organization' as const,
+ kind: 'secret' as const,
+ file: false,
+ createdAt: '2026-10-30T10:00:00.000Z',
+ createdBy: { member: 'usr_1', name: 'Ayush' },
+ updatedAt: '2026-10-30T10:00:00.000Z',
+ updatedBy: { member: 'usr_1', name: 'Ayush' },
+ lastUsedAt: null,
+ overriddenIn: { threads: 1, people: 0 },
+}
+
+let container: HTMLDivElement
+let root: Root
+
+beforeEach(() => {
+ ;(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true
+ container = document.createElement('div')
+ document.body.appendChild(container)
+ root = createRoot(container)
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ container.remove()
+ document.body.innerHTML = ''
+ vi.clearAllMocks()
+})
+
+async function render() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ act(() => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <ComputerSecrets />
+ </QueryClientProvider>,
+ )
+ })
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+}
+
+// The last match: a dialog's button comes after the page's of the same name.
+function button(label: string) {
+ const found = [...document.querySelectorAll('button')]
+ .reverse()
+ .find(
+ (el) =>
+ el.textContent?.trim() === label ||
+ el.getAttribute('aria-label') === label,
+ )
+ if (!found) throw new Error(`no button ${label}`)
+ return found
+}
+
+function type(input: HTMLInputElement, value: string) {
+ Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ 'value',
+ )?.set?.call(input, value)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+}
+
+async function flush() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+}
+
+describe('computer secrets page', () => {
+ it('lists organization secrets with who set them and where they are overridden', async () => {
+ secretsApi.getOrgSecrets.mockResolvedValue([row])
+ await render()
+ expect(container.textContent).toContain('EXECUTOR_API_KEY')
+ expect(container.textContent).toContain('Ayush')
+ expect(container.textContent).toContain('Not yet')
+ expect(container.textContent).toContain(
+ 'Overridden in 1 thread by a copy set in Slack',
+ )
+ })
+
+ it('offers to add the first secret when there are none', async () => {
+ secretsApi.getOrgSecrets.mockResolvedValue([])
+ await render()
+ expect(container.textContent).toContain('No secrets yet')
+ expect(button('Add secret')).toBeTruthy()
+ })
+
+ it('adds a secret and shows a refused name next to the field', async () => {
+ secretsApi.getOrgSecrets.mockResolvedValue([])
+ secretsApi.putOrgSecret.mockRejectedValueOnce(
+ new ApiError(
+ "Can't use this name: PATH is reserved.",
+ 400,
+ 'invalid_name',
+ ),
+ )
+ await render()
+ act(() => button('Add secret').click())
+ const name = document.getElementById('secret-name') as HTMLInputElement
+ const value = document.getElementById('secret-value') as HTMLInputElement
+ act(() => {
+ type(name, 'path')
+ type(value, 'x')
+ })
+ expect(value.type).toBe('password')
+ act(() => button('Add secret').click())
+ await flush()
+ expect(secretsApi.putOrgSecret.mock.calls[0]?.[0]).toEqual({
+ name: 'PATH',
+ value: 'x',
+ file: false,
+ variable: false,
+ })
+ expect(document.getElementById('secret-name-error')?.textContent).toBe(
+ "Can't use this name: PATH is reserved.",
+ )
+ })
+
+ it('replaces without showing or prefilling the old value', async () => {
+ secretsApi.getOrgSecrets.mockResolvedValue([row])
+ secretsApi.putOrgSecret.mockResolvedValue(row)
+ await render()
+ act(() => button('Replace').click())
+ expect(document.getElementById('secret-name')).toBeNull()
+ const value = document.getElementById('secret-value') as HTMLInputElement
+ expect(value.value).toBe('')
+ act(() => type(value, 'new'))
+ act(() => button('Replace').click())
+ await flush()
+ expect(secretsApi.putOrgSecret.mock.calls[0]?.[0]).toEqual({
+ name: 'EXECUTOR_API_KEY',
+ value: 'new',
+ file: false,
+ variable: false,
+ })
+ })
+
+ it('deletes after a confirm that names the organization layer', async () => {
+ secretsApi.getOrgSecrets.mockResolvedValue([row])
+ secretsApi.deleteOrgSecret.mockResolvedValue(undefined)
+ await render()
+ act(() => button('Delete').click())
+ expect(document.body.textContent).toContain(
+ 'Delete EXECUTOR_API_KEY for the organization?',
+ )
+ const confirm = [
+ ...document.querySelectorAll('[role="alertdialog"] button'),
+ ].find((el) => el.textContent?.trim() === 'Delete') as HTMLButtonElement
+ act(() => confirm.click())
+ await flush()
+ expect(secretsApi.deleteOrgSecret.mock.calls[0]?.[0]).toBe(
+ 'EXECUTOR_API_KEY',
+ )
+ })
+
+ it('shows the history of a name', async () => {
+ secretsApi.getOrgSecrets.mockResolvedValue([row])
+ secretsApi.getSecretEvents.mockResolvedValue([
+ {
+ at: '2026-10-30T10:00:00.000Z',
+ action: 'replace',
+ kind: 'secret',
+ actor: { member: 'usr_1', name: 'Ayush' },
+ via: 'dashboard',
+ },
+ {
+ at: '2026-10-29T10:00:00.000Z',
+ action: 'set',
+ kind: 'secret',
+ actor: { slackUserId: 'U1' },
+ via: 'slack',
+ },
+ ])
+ await render()
+ act(() => button('History of EXECUTOR_API_KEY').click())
+ await flush()
+ expect(secretsApi.getSecretEvents).toHaveBeenCalledWith('EXECUTOR_API_KEY')
+ expect(document.body.textContent).toContain(
+ 'Replaced by Ayush in the dashboard',
+ )
+ expect(document.body.textContent).toContain('Set in Slack')
+ })
+})
diff --git a/web/src/managed-agents/ComputerSecrets.tsx b/web/src/managed-agents/ComputerSecrets.tsx
new file mode 100644
index 00000000..e0567136
--- /dev/null
+++ b/web/src/managed-agents/ComputerSecrets.tsx
@@ -0,0 +1,554 @@
+import { type FormEvent, useContext, useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { Navigate } from 'react-router-dom'
+import { History, KeyRound, Loader2, Plus, TriangleAlert } from 'lucide-react'
+import { ApiError } from '@/api/errors'
+import { ConfirmDialog } from '@/components/confirm-dialog'
+import { EmptyState } from '@/components/empty-state'
+import { PageHeader } from '@/components/page-header'
+import { Panel } from '@/components/panel'
+import { Badge } from '@/components/ui/badge'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table'
+import { AuthContext } from '@/hooks/useAuth'
+import { notifyError, notifySuccess } from '@/lib/errors'
+import { relativeTime } from './computer-state'
+import {
+ SECRET_NAME,
+ deleteOrgSecret,
+ getOrgSecrets,
+ getSecretEvents,
+ orgSecretsQueryKey,
+ putOrgSecret,
+ secretEventsQueryKey,
+ type OrgSecret,
+ type SecretActor,
+ type SecretEvent,
+} from './computer-secrets-api'
+
+// The computer's organization secrets (serverless-agents-ws work 095, v1):
+// the Organization view of the plan's mockup. Personal and thread secrets stay
+// in Slack for now; a row only counts where one of those wins over it.
+
+export default function ComputerSecretsPage() {
+ const auth = useContext(AuthContext)
+ if (auth?.user && !auth.user.computerEnabled)
+ return <Navigate to="/" replace />
+ return <ComputerSecrets />
+}
+
+type Editing = { mode: 'add' } | { mode: 'replace'; secret: OrgSecret }
+
+export function ComputerSecrets() {
+ const secrets = useQuery({
+ queryKey: orgSecretsQueryKey,
+ queryFn: getOrgSecrets,
+ })
+ const [editing, setEditing] = useState<Editing | null>(null)
+ const [deleting, setDeleting] = useState<OrgSecret | null>(null)
+ const [historyOf, setHistoryOf] = useState<string | null>(null)
+
+ const add = (
+ <Button onClick={() => setEditing({ mode: 'add' })}>
+ <Plus className="size-4" aria-hidden />
+ Add secret
+ </Button>
+ )
+
+ return (
+ <div>
+ <PageHeader
+ title="Secrets"
+ description="Every session on your computer gets these as environment variables. Anyone in your organization can set them; values can't be read back."
+ actions={secrets.data?.length ? add : null}
+ />
+ <Panel>
+ {secrets.isLoading ? (
+ <div
+ role="status"
+ aria-label="Loading"
+ className="flex min-h-40 items-center justify-center"
+ >
+ <Loader2 className="text-muted-foreground size-5 animate-spin" />
+ </div>
+ ) : secrets.isError ? (
+ <EmptyState
+ icon={KeyRound}
+ title="Secrets are temporarily unavailable"
+ description={secrets.error.message}
+ action={
+ <Button variant="outline" onClick={() => void secrets.refetch()}>
+ Try again
+ </Button>
+ }
+ />
+ ) : !secrets.data?.length ? (
+ <EmptyState
+ icon={KeyRound}
+ title="No secrets yet"
+ description="Add an API key or token once, and every session can use it."
+ action={add}
+ />
+ ) : (
+ <SecretsTable
+ secrets={secrets.data}
+ onReplace={(secret) => setEditing({ mode: 'replace', secret })}
+ onDelete={setDeleting}
+ onHistory={setHistoryOf}
+ />
+ )}
+ </Panel>
+ <p className="text-muted-foreground mt-3 text-xs">
+ Sessions can read these values, so anyone who can talk to your computer
+ can use them. Slack sessions get them today; API and dashboard sessions
+ will soon.
+ </p>
+
+ {editing ? (
+ <SecretDialog editing={editing} onClose={() => setEditing(null)} />
+ ) : null}
+ <DeleteSecretDialog secret={deleting} onClose={() => setDeleting(null)} />
+ <HistoryDialog name={historyOf} onClose={() => setHistoryOf(null)} />
+ </div>
+ )
+}
+
+function SecretsTable({
+ secrets,
+ onReplace,
+ onDelete,
+ onHistory,
+}: {
+ secrets: OrgSecret[]
+ onReplace: (secret: OrgSecret) => void
+ onDelete: (secret: OrgSecret) => void
+ onHistory: (name: string) => void
+}) {
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-4">Name</TableHead>
+ <TableHead>Updated</TableHead>
+ <TableHead>Last used</TableHead>
+ <TableHead className="pr-4 text-right">
+ <span className="sr-only">Actions</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {secrets.map((secret) => (
+ <TableRow key={secret.name}>
+ <TableCell className="py-3 pl-4 align-top">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-mono text-sm font-medium">
+ {secret.name}
+ </span>
+ {secret.kind === 'variable' ? (
+ <Badge variant="secondary">Variable</Badge>
+ ) : null}
+ {secret.file ? <Badge variant="secondary">File</Badge> : null}
+ </div>
+ {secret.kind === 'variable' && secret.value ? (
+ <p className="text-muted-foreground mt-1 max-w-md truncate font-mono text-xs">
+ {secret.value}
+ </p>
+ ) : null}
+ <Overridden in={secret.overriddenIn} />
+ </TableCell>
+ <TableCell className="py-3 align-top text-sm">
+ {secret.updatedAt ? relativeTime(secret.updatedAt) : '—'}
+ <p className="text-muted-foreground text-xs">
+ {actorLabel(secret.updatedBy)}
+ </p>
+ </TableCell>
+ <TableCell className="text-muted-foreground py-3 align-top text-sm">
+ {secret.lastUsedAt ? relativeTime(secret.lastUsedAt) : 'Not yet'}
+ </TableCell>
+ <TableCell className="py-2 pr-4 text-right align-top">
+ <div className="flex justify-end gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label={`History of ${secret.name}`}
+ onClick={() => onHistory(secret.name)}
+ >
+ <History className="size-4" aria-hidden />
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onReplace(secret)}
+ >
+ Replace
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-destructive"
+ onClick={() => onDelete(secret)}
+ >
+ Delete
+ </Button>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )
+}
+
+/**
+ * A thread's or a person's copy of the name, set in Slack, wins over this one
+ * where it applies: the stale copy that silently beat the org value is the
+ * bug that started work 095.
+ */
+function Overridden({ in: counts }: { in: OrgSecret['overriddenIn'] }) {
+ const parts = [
+ counts.threads
+ ? `${counts.threads} ${counts.threads === 1 ? 'thread' : 'threads'}`
+ : null,
+ counts.people
+ ? `for ${counts.people} ${counts.people === 1 ? 'person' : 'people'}`
+ : null,
+ ].filter(Boolean)
+ if (!parts.length) return null
+ const where = counts.threads
+ ? `in ${parts.join(' and ')}`
+ : (parts[0] as string)
+ return (
+ <p className="mt-1 flex items-center gap-1 text-xs text-amber-700 dark:text-amber-400">
+ <TriangleAlert className="size-3 shrink-0" aria-hidden />
+ Overridden {where} by a copy set in Slack
+ </p>
+ )
+}
+
+function actorLabel(actor: SecretActor | null): string {
+ if (!actor) return ''
+ if ('member' in actor) return actor.name ?? 'A member'
+ if ('slackUserId' in actor) return 'From Slack'
+ return 'OpenComputer'
+}
+
+function SecretDialog({
+ editing,
+ onClose,
+}: {
+ editing: Editing
+ onClose: () => void
+}) {
+ const queryClient = useQueryClient()
+ const replacing = editing.mode === 'replace' ? editing.secret : null
+ const [name, setName] = useState(replacing?.name ?? '')
+ const [value, setValue] = useState('')
+ const [variable, setVariable] = useState(replacing?.kind === 'variable')
+ const [file, setFile] = useState(replacing?.file ?? false)
+ const [nameError, setNameError] = useState<string | null>(null)
+
+ const save = useMutation({
+ mutationFn: putOrgSecret,
+ onSuccess: async (secret) => {
+ await queryClient.invalidateQueries({ queryKey: orgSecretsQueryKey })
+ notifySuccess(
+ `${secret.name} ${replacing ? 'replaced' : 'saved'}.`,
+ 'Running sessions get it right away.',
+ )
+ onClose()
+ },
+ onError: (error) => {
+ if (error instanceof ApiError && error.type === 'invalid_name') {
+ setNameError(error.message)
+ return
+ }
+ notifyError("Couldn't save it.", error)
+ },
+ })
+
+ function submit(event: FormEvent) {
+ event.preventDefault()
+ const trimmed = name.trim()
+ if (!SECRET_NAME.test(trimmed)) {
+ setNameError(
+ 'Use letters, digits and _, not starting with a digit (at most 64).',
+ )
+ return
+ }
+ if (!value) return
+ save.mutate({ name: trimmed, value, file: !variable && file, variable })
+ }
+
+ const what = variable ? 'variable' : 'secret'
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !save.isPending) onClose()
+ }}
+ >
+ <DialogContent className="sm:max-w-lg">
+ <form onSubmit={submit} className="space-y-4">
+ <DialogHeader>
+ <DialogTitle>
+ {replacing ? `Replace ${replacing.name}` : 'Add a secret'}
+ </DialogTitle>
+ <DialogDescription>
+ {replacing
+ ? `The new value replaces the old one for every session. The old value can't be shown.`
+ : 'Every session on your computer gets it as an environment variable.'}
+ </DialogDescription>
+ </DialogHeader>
+
+ {replacing ? null : (
+ <div className="space-y-2">
+ <Label htmlFor="secret-name">Name</Label>
+ <Input
+ id="secret-name"
+ value={name}
+ onChange={(event) => {
+ setName(event.target.value.toUpperCase())
+ setNameError(null)
+ }}
+ placeholder="EXECUTOR_API_KEY"
+ autoComplete="off"
+ spellCheck={false}
+ className="font-mono"
+ aria-invalid={nameError ? true : undefined}
+ aria-describedby={nameError ? 'secret-name-error' : undefined}
+ />
+ {nameError ? (
+ <p id="secret-name-error" className="text-destructive text-xs">
+ {nameError}
+ </p>
+ ) : null}
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Label htmlFor="secret-value">Value</Label>
+ {file && !variable ? (
+ <textarea
+ id="secret-value"
+ value={value}
+ onChange={(event) => setValue(event.target.value)}
+ rows={6}
+ autoComplete="off"
+ spellCheck={false}
+ className="border-input bg-background w-full rounded-md border px-2.5 py-2 font-mono text-xs outline-none"
+ />
+ ) : (
+ <Input
+ id="secret-value"
+ type={variable ? 'text' : 'password'}
+ value={value}
+ onChange={(event) => setValue(event.target.value)}
+ autoComplete="off"
+ spellCheck={false}
+ className="font-mono"
+ />
+ )}
+ </div>
+
+ {replacing ? null : (
+ <fieldset className="space-y-2">
+ <legend className="text-sm font-medium">Kind</legend>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="radio"
+ name="secret-kind"
+ checked={!variable}
+ onChange={() => setVariable(false)}
+ className="mt-1"
+ />
+ <span>
+ Secret
+ <span className="text-muted-foreground block text-xs">
+ Write-only, and hidden from session output.
+ </span>
+ </span>
+ </label>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="radio"
+ name="secret-kind"
+ checked={variable}
+ onChange={() => setVariable(true)}
+ className="mt-1"
+ />
+ <span>
+ Variable
+ <span className="text-muted-foreground block text-xs">
+ Not sensitive, and shown here, like a region or a base URL.
+ </span>
+ </span>
+ </label>
+ </fieldset>
+ )}
+
+ {variable || replacing ? null : (
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="checkbox"
+ checked={file}
+ onChange={(event) => setFile(event.target.checked)}
+ className="mt-1"
+ />
+ <span>
+ Save as a file
+ <span className="text-muted-foreground block text-xs">
+ For a key file or kubeconfig: the variable holds the
+ file&apos;s path.
+ </span>
+ </span>
+ </label>
+ )}
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={save.isPending}
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={!value || save.isPending}>
+ {save.isPending ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null}
+ {replacing ? 'Replace' : `Add ${what}`}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function DeleteSecretDialog({
+ secret,
+ onClose,
+}: {
+ secret: OrgSecret | null
+ onClose: () => void
+}) {
+ const queryClient = useQueryClient()
+ const remove = useMutation({
+ mutationFn: deleteOrgSecret,
+ onSuccess: async (_, name) => {
+ await queryClient.invalidateQueries({ queryKey: orgSecretsQueryKey })
+ notifySuccess(`${name} deleted.`)
+ onClose()
+ },
+ onError: (error) => notifyError("Couldn't delete it.", error),
+ })
+ return (
+ <ConfirmDialog
+ open={secret !== null}
+ onOpenChange={(open) => !open && onClose()}
+ title={`Delete ${secret?.name ?? ''} for the organization?`}
+ description="Running sessions lose it right away. Copies set in Slack for a thread or a person stay."
+ confirmLabel="Delete"
+ destructive
+ pending={remove.isPending}
+ onConfirm={() => secret && remove.mutate(secret.name)}
+ />
+ )
+}
+
+const ACTIONS: Record<string, string> = {
+ set: 'Set',
+ replace: 'Replaced',
+ delete: 'Deleted',
+ expire: 'Expired',
+}
+
+const SURFACES: Record<string, string> = {
+ slack: 'in Slack',
+ dashboard: 'in the dashboard',
+ api: 'with an API key',
+ opc: 'from the CLI',
+}
+
+function HistoryDialog({
+ name,
+ onClose,
+}: {
+ name: string | null
+ onClose: () => void
+}) {
+ const events = useQuery({
+ queryKey: secretEventsQueryKey(name ?? ''),
+ queryFn: () => getSecretEvents(name!),
+ enabled: name !== null,
+ })
+ return (
+ <Dialog open={name !== null} onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="font-mono">{name}</DialogTitle>
+ <DialogDescription>
+ Who changed it, and where. Values are never recorded.
+ </DialogDescription>
+ </DialogHeader>
+ {events.isLoading ? (
+ <div className="flex min-h-24 items-center justify-center">
+ <Loader2 className="text-muted-foreground size-5 animate-spin" />
+ </div>
+ ) : events.isError ? (
+ <p className="text-muted-foreground text-sm">
+ Couldn&apos;t load the history. {events.error.message}
+ </p>
+ ) : !events.data?.length ? (
+ <p className="text-muted-foreground text-sm">
+ No changes recorded yet. History starts with this release.
+ </p>
+ ) : (
+ <ol className="max-h-[24rem] divide-y overflow-y-auto rounded-md border">
+ {events.data.map((event, index) => (
+ <HistoryRow key={`${event.at}-${index}`} event={event} />
+ ))}
+ </ol>
+ )}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function HistoryRow({ event }: { event: SecretEvent }) {
+ const who = actorLabel(event.actor)
+ return (
+ <li className="flex items-baseline justify-between gap-4 px-3 py-2 text-sm">
+ <span>
+ {ACTIONS[event.action] ?? event.action}
+ {who && event.actor && !('slackUserId' in event.actor)
+ ? ` by ${who}`
+ : ''}{' '}
+ <span className="text-muted-foreground">
+ {SURFACES[event.via] ?? ''}
+ </span>
+ </span>
+ <span className="text-muted-foreground shrink-0 text-xs">
+ {event.at ? relativeTime(event.at) : ''}
+ </span>
+ </li>
+ )
+}
diff --git a/web/src/managed-agents/computer-secrets-api.ts b/web/src/managed-agents/computer-secrets-api.ts
new file mode 100644
index 00000000..3aa5acce
--- /dev/null
+++ b/web/src/managed-agents/computer-secrets-api.ts
@@ -0,0 +1,100 @@
+import { z } from 'zod'
+import { apiFetch } from '@/api/client'
+
+// The computer's organization secrets (serverless-agents-ws work 095, v1):
+// the public Computer API's routes (docs/api/http/secrets.mdx), which a
+// dashboard session may call as it is. Values go in and never come back;
+// only a variable's value is listed.
+
+const actorSchema = z.union([
+ z.object({ member: z.string(), name: z.string().nullable() }),
+ z.object({ slackUserId: z.string() }),
+ z.object({ system: z.literal(true) }),
+])
+
+export const orgSecretSchema = z.object({
+ name: z.string(),
+ layer: z.literal('organization'),
+ kind: z.enum(['secret', 'variable']),
+ file: z.boolean(),
+ /** Variables only; null when it could not be opened. */
+ value: z.string().nullable().optional(),
+ createdAt: z.string().nullable(),
+ createdBy: actorSchema.nullable(),
+ updatedAt: z.string().nullable(),
+ updatedBy: actorSchema.nullable(),
+ /** Null until a session gets it after it was last set. */
+ lastUsedAt: z.string().nullable(),
+ /** Narrower copies of the name that win where they apply (counts only). */
+ overriddenIn: z.object({ threads: z.number(), people: z.number() }),
+})
+
+export const secretEventSchema = z.object({
+ at: z.string().nullable(),
+ action: z.string(),
+ kind: z.enum(['secret', 'variable']),
+ actor: actorSchema.nullable(),
+ via: z.string(),
+})
+
+export type SecretActor = z.infer<typeof actorSchema>
+export type OrgSecret = z.infer<typeof orgSecretSchema>
+export type SecretEvent = z.infer<typeof secretEventSchema>
+
+export const orgSecretsQueryKey = ['managed-computer', 'secrets'] as const
+export const secretEventsQueryKey = (name: string) =>
+ ['managed-computer', 'secrets', name, 'events'] as const
+
+const PREFIX = '/managed-agents/computer'
+
+export async function getOrgSecrets() {
+ return (
+ await apiFetch(
+ `${PREFIX}/secrets`,
+ undefined,
+ z.object({ secrets: z.array(orgSecretSchema) }),
+ '/api',
+ )
+ ).secrets
+}
+
+export async function getSecretEvents(name: string) {
+ return (
+ await apiFetch(
+ `${PREFIX}/secrets/${encodeURIComponent(name)}/events`,
+ undefined,
+ z.object({ events: z.array(secretEventSchema) }),
+ '/api',
+ )
+ ).events
+}
+
+/** Sets or replaces an organization secret or variable. */
+export async function putOrgSecret(input: {
+ name: string
+ value: string
+ file: boolean
+ variable: boolean
+}) {
+ const { name, ...body } = input
+ return (
+ await apiFetch(
+ `${PREFIX}/organization/secrets/${encodeURIComponent(name)}`,
+ { method: 'PUT', body: JSON.stringify(body) },
+ z.object({ secret: orgSecretSchema }),
+ '/api',
+ )
+ ).secret
+}
+
+export async function deleteOrgSecret(name: string) {
+ await apiFetch(
+ `${PREFIX}/organization/secrets/${encodeURIComponent(name)}`,
+ { method: 'DELETE' },
+ undefined,
+ '/api',
+ )
+}
+
+/** The name the server checks too; this only catches typos early. */
+export const SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/