feat: React webui with flags support, build-ui pipeline

- packages/webui: Vite + React + Tailwind v4, single-file bundle
- Dark industrial theme, Space Grotesk + JetBrains Mono
- Config table with scope/flag badges, masked values, search/filter
- Admin panel for agent management
- scripts/build-ui.sh generates worker/src/ui.ts from webui build
- Worker serves UI at GET / before auth check
This commit is contained in:
团子 2026-04-21 04:01:35 +00:00
parent 117e334a07
commit 58494b8fca
24 changed files with 979 additions and 379 deletions

4
.gitignore vendored
View File

@ -1,2 +1,6 @@
node_modules/
dist/
.wrangler/ .wrangler/
.npmrc .npmrc
bun.lock
package-lock.json

24
packages/webui/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
packages/webui/README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

12
packages/webui/index.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Config Service</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,35 @@
{
"name": "webui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"lucide-react": "^1.8.0",
"react": "^19.2.5",
"react-dom": "^19.2.5"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@tailwindcss/vite": "^4.2.3",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"tailwindcss": "^4.2.3",
"terser": "^5.46.1",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.2",
"vite": "^8.0.9",
"vite-plugin-singlefile": "^2.3.3"
}
}

View File

@ -0,0 +1,34 @@
import { useState, useCallback } from "react";
import LoginPage from "./components/LoginPage";
import Dashboard from "./components/Dashboard";
import Toast from "./components/Toast";
import type { Toast as ToastType } from "./types";
export default function App() {
const [authed, setAuthed] = useState(!!localStorage.getItem("config-token"));
const [toasts, setToasts] = useState<ToastType[]>([]);
const addToast = useCallback((message: string, type: "success" | "error") => {
setToasts((prev) => [...prev, { id: Date.now() + Math.random(), message, type }]);
}, []);
const removeToast = useCallback((id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
const logout = () => {
localStorage.removeItem("config-token");
setAuthed(false);
};
return (
<>
<Toast toasts={toasts} remove={removeToast} />
{authed ? (
<Dashboard onLogout={logout} addToast={addToast} />
) : (
<LoginPage onLogin={() => setAuthed(true)} />
)}
</>
);
}

View File

@ -0,0 +1,90 @@
import { useState } from "react";
import type { ConfigEntry } from "../types";
interface Props {
editKey?: string;
editEntry?: ConfigEntry;
onSave: (key: string, value: string, scope: string, env: boolean, secret: boolean) => void;
onClose: () => void;
}
export default function AddEditModal({ editKey, editEntry, onSave, onClose }: Props) {
const [key, setKey] = useState(editKey || "");
const [value, setValue] = useState(editEntry?.value || "");
const [scope, setScope] = useState(editEntry?.scope || "personal");
const [excludeEnv, setExcludeEnv] = useState(editEntry ? !editEntry.env : false);
const [secret, setSecret] = useState(editEntry?.secret || false);
const isEdit = !!editKey;
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onSave(key, value, scope, !excludeEnv, secret);
};
return (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 backdrop-blur-sm" onClick={onClose}>
<form
onClick={(e) => e.stopPropagation()}
onSubmit={handleSubmit}
className="w-full max-w-lg bg-[#12141a] border border-[#1e2030] rounded-2xl p-6 shadow-2xl"
>
<h2 className="text-xl font-bold text-white mb-6" style={{ fontFamily: "var(--font-heading)" }}>
{isEdit ? "Edit Key" : "Add Key"}
</h2>
<label className="block text-sm text-[#64748b] mb-1 font-medium">Key</label>
<input
value={key}
onChange={(e) => setKey(e.target.value)}
disabled={isEdit}
className="w-full px-3 py-2 mb-4 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white disabled:opacity-50 focus:outline-none focus:border-[#3b82f6] transition-colors"
style={{ fontFamily: "var(--font-mono)" }}
placeholder="MY_CONFIG_KEY"
required
/>
<label className="block text-sm text-[#64748b] mb-1 font-medium">Value</label>
<textarea
value={value}
onChange={(e) => setValue(e.target.value)}
rows={4}
className="w-full px-3 py-2 mb-4 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white resize-none focus:outline-none focus:border-[#3b82f6] transition-colors"
style={{ fontFamily: "var(--font-mono)" }}
placeholder="value"
required
/>
<label className="block text-sm text-[#64748b] mb-1 font-medium">Scope</label>
<select
value={scope}
onChange={(e) => setScope(e.target.value as "personal" | "shared")}
className="w-full px-3 py-2 mb-4 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white focus:outline-none focus:border-[#3b82f6]"
>
<option value="personal">Personal</option>
<option value="shared">Shared</option>
</select>
<div className="flex flex-col gap-3 mb-6">
<label className="flex items-center gap-2 text-sm text-[#e2e8f0] cursor-pointer">
<input type="checkbox" checked={excludeEnv} onChange={(e) => setExcludeEnv(e.target.checked)} className="accent-[#eab308]" />
Exclude from env export
</label>
<label className="flex items-center gap-2 text-sm text-[#e2e8f0] cursor-pointer">
<input type="checkbox" checked={secret} onChange={(e) => setSecret(e.target.checked)} className="accent-[#ef4444]" />
Mark as secret
</label>
</div>
<div className="flex justify-end gap-3">
<button type="button" onClick={onClose} className="px-4 py-2 text-sm text-[#64748b] hover:text-white transition-colors">
Cancel
</button>
<button type="submit" className="px-5 py-2 bg-[#3b82f6] hover:bg-[#2563eb] text-white text-sm font-semibold rounded-lg transition-colors">
{isEdit ? "Update" : "Create"}
</button>
</div>
</form>
</div>
);
}

View File

@ -0,0 +1,114 @@
import { useEffect, useState } from "react";
import { useApi } from "../hooks/useApi";
import type { Agent } from "../types";
interface Props {
addToast: (msg: string, type: "success" | "error") => void;
}
export default function AdminPanel({ addToast }: Props) {
const api = useApi();
const [agents, setAgents] = useState<Agent[]>([]);
const [newAgentId, setNewAgentId] = useState("");
const [newRole, setNewRole] = useState("agent");
const [generatedToken, setGeneratedToken] = useState("");
const [loading, setLoading] = useState(true);
const loadAgents = async () => {
try {
const data = await api.getAgents();
setAgents(Array.isArray(data) ? data : data.agents || []);
} catch (e: any) {
addToast("Failed to load agents: " + e.message, "error");
} finally {
setLoading(false);
}
};
useEffect(() => { loadAgents(); }, []);
const handleCreateToken = async () => {
if (!newAgentId.trim()) return;
try {
const data = await api.createToken(newAgentId.trim(), newRole);
setGeneratedToken(data.token || JSON.stringify(data));
addToast("Token created", "success");
setNewAgentId("");
loadAgents();
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
const handleRevoke = async (tokenId: string) => {
try {
await api.revokeToken(tokenId);
addToast("Token revoked", "success");
loadAgents();
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
if (loading) return <div className="text-[#64748b] text-center py-8">Loading agents...</div>;
return (
<div className="space-y-6">
<div className="bg-[#12141a] border border-[#1e2030] rounded-xl p-6">
<h3 className="text-lg font-bold text-white mb-4" style={{ fontFamily: "var(--font-heading)" }}>Create Agent Token</h3>
<div className="flex gap-3 items-end flex-wrap">
<div>
<label className="block text-xs text-[#64748b] mb-1">Agent ID</label>
<input value={newAgentId} onChange={(e) => setNewAgentId(e.target.value)} placeholder="agent-name"
className="px-3 py-2 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white text-sm focus:outline-none focus:border-[#3b82f6]" style={{ fontFamily: "var(--font-mono)" }} />
</div>
<div>
<label className="block text-xs text-[#64748b] mb-1">Role</label>
<select value={newRole} onChange={(e) => setNewRole(e.target.value)}
className="px-3 py-2 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white text-sm focus:outline-none focus:border-[#3b82f6]">
<option value="agent">Agent</option>
<option value="admin">Admin</option>
</select>
</div>
<button onClick={handleCreateToken} className="px-4 py-2 bg-[#3b82f6] hover:bg-[#2563eb] text-white text-sm font-semibold rounded-lg transition-colors">
Generate Token
</button>
</div>
{generatedToken && (
<div className="mt-4 p-3 bg-[#0a0a0c] border border-green-500/30 rounded-lg">
<p className="text-xs text-green-400 mb-1">Generated token (copy now, shown once):</p>
<code className="text-sm text-white break-all" style={{ fontFamily: "var(--font-mono)" }}>{generatedToken}</code>
<button onClick={() => { navigator.clipboard.writeText(generatedToken); addToast("Copied", "success"); }}
className="ml-2 text-xs text-[#3b82f6] hover:underline">Copy</button>
</div>
)}
</div>
<div className="bg-[#12141a] border border-[#1e2030] rounded-xl p-6">
<h3 className="text-lg font-bold text-white mb-4" style={{ fontFamily: "var(--font-heading)" }}>Agents</h3>
{agents.length === 0 ? (
<p className="text-[#64748b] text-sm">No agents found</p>
) : (
<div className="space-y-3">
{agents.map((agent) => (
<div key={agent.id} className="flex items-center justify-between p-3 bg-[#0a0a0c] rounded-lg border border-[#1e2030]">
<div className="flex items-center gap-3">
<span className="text-white font-medium" style={{ fontFamily: "var(--font-mono)" }}>{agent.id}</span>
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
agent.role === "admin" ? "bg-purple-500/15 text-purple-400 border border-purple-500/30" : "bg-[#1e2030] text-[#64748b]"
}`}>{agent.role}</span>
</div>
{agent.tokens?.map((t) => (
<button key={t.id} onClick={() => handleRevoke(t.id)}
className="text-xs text-red-400 hover:text-red-300 hover:bg-red-500/10 px-2 py-1 rounded transition-colors">
Revoke {t.id.slice(0, 8)}...
</button>
))}
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,116 @@
import { useState } from "react";
import type { ConfigEntry } from "../types";
interface Props {
entries: [string, ConfigEntry][];
onEdit: (key: string, entry: ConfigEntry) => void;
onDelete: (key: string, scope: string) => void;
addToast: (msg: string, type: "success" | "error") => void;
}
export default function ConfigTable({ entries, onEdit, onDelete, addToast }: Props) {
const [revealed, setRevealed] = useState<Set<string>>(new Set());
const toggle = (key: string) => {
setRevealed((prev) => {
const next = new Set(prev);
next.has(key) ? next.delete(key) : next.add(key);
return next;
});
};
const copy = (value: string) => {
navigator.clipboard.writeText(value);
addToast("Copied to clipboard", "success");
};
const fmtTime = (iso: string) => {
try {
const d = new Date(iso);
return d.toLocaleDateString(undefined, { month: "short", day: "numeric" }) + " " + d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
} catch { return iso; }
};
if (entries.length === 0) {
return (
<div className="text-center py-16 text-[#64748b]">
<p className="text-lg mb-1">No configuration keys found</p>
<p className="text-sm">Add your first key to get started</p>
</div>
);
}
return (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-[#64748b] text-xs uppercase tracking-wider border-b border-[#1e2030]">
<th className="pb-3 pr-4 font-medium">Key</th>
<th className="pb-3 pr-4 font-medium">Value</th>
<th className="pb-3 pr-4 font-medium">Scope</th>
<th className="pb-3 pr-4 font-medium">Flags</th>
<th className="pb-3 pr-4 font-medium">Updated</th>
<th className="pb-3 font-medium text-right">Actions</th>
</tr>
</thead>
<tbody>
{entries.map(([key, entry]) => {
const show = revealed.has(key);
const displayVal = show ? entry.value : "•".repeat(Math.min(entry.value.length || 8, 24));
return (
<tr key={key} className="border-b border-[#1e2030]/50 hover:bg-[#1e2030]/30 transition-colors">
<td className="py-3 pr-4" style={{ fontFamily: "var(--font-mono)" }}>
<span className="text-white font-medium">{key}</span>
</td>
<td className="py-3 pr-4 max-w-[280px]">
<div className="flex items-center gap-2">
<span
className={`truncate ${show ? "text-white" : "text-[#64748b]"}`}
style={{ fontFamily: "var(--font-mono)", fontSize: "0.8rem" }}
>
{displayVal}
</span>
<button onClick={() => toggle(key)} className="text-[#64748b] hover:text-white shrink-0 transition-colors" title={show ? "Hide" : "Reveal"}>
{show ? "👁" : "👁‍🗨"}
</button>
<button onClick={() => copy(entry.value)} className="text-[#64748b] hover:text-[#3b82f6] shrink-0 transition-colors" title="Copy">
📋
</button>
</div>
</td>
<td className="py-3 pr-4">
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
entry.scope === "shared" ? "bg-blue-500/15 text-blue-400 border border-blue-500/30" : "bg-green-500/15 text-green-400 border border-green-500/30"
}`}>
{entry.scope}
</span>
</td>
<td className="py-3 pr-4">
<div className="flex gap-1.5">
{entry.secret && (
<span className="text-xs px-2 py-0.5 rounded-full bg-red-500/15 text-red-400 border border-red-500/30 font-medium">secret</span>
)}
{entry.env === false && (
<span className="text-xs px-2 py-0.5 rounded-full bg-yellow-500/15 text-yellow-400 border border-yellow-500/30 font-medium">no-env</span>
)}
</div>
</td>
<td className="py-3 pr-4 text-[#64748b] text-xs whitespace-nowrap">{fmtTime(entry.updated_at)}</td>
<td className="py-3 text-right">
<div className="flex justify-end gap-1">
<button onClick={() => onEdit(key, entry)} className="px-2 py-1 text-xs text-[#64748b] hover:text-white hover:bg-[#1e2030] rounded transition-colors">
Edit
</button>
<button onClick={() => onDelete(key, entry.scope)} className="px-2 py-1 text-xs text-[#64748b] hover:text-red-400 hover:bg-red-500/10 rounded transition-colors">
Delete
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

View File

@ -0,0 +1,161 @@
import { useCallback, useEffect, useState } from "react";
import { useApi } from "../hooks/useApi";
import type { ConfigEntry, ConfigResponse } from "../types";
import ConfigTable from "./ConfigTable";
import AddEditModal from "./AddEditModal";
import AdminPanel from "./AdminPanel";
interface Props {
onLogout: () => void;
addToast: (msg: string, type: "success" | "error") => void;
}
export default function Dashboard({ onLogout, addToast }: Props) {
const api = useApi();
const [data, setData] = useState<ConfigResponse | null>(null);
const [search, setSearch] = useState("");
const [scopeFilter, setScopeFilter] = useState<"all" | "personal" | "shared">("all");
const [modal, setModal] = useState<{ key?: string; entry?: ConfigEntry } | null>(null);
const [tab, setTab] = useState<"config" | "admin">("config");
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
try {
const d = await api.getConfig();
setData(d);
} catch (e: any) {
addToast("Failed to load: " + e.message, "error");
if (e.message.includes("401") || e.message.includes("403")) onLogout();
} finally {
setLoading(false);
}
}, []);
useEffect(() => { load(); }, [load]);
const entries = data ? Object.entries(data.secrets || {}) : [];
const filtered = entries.filter(([key, entry]) => {
if (search && !key.toLowerCase().includes(search.toLowerCase())) return false;
if (scopeFilter !== "all" && entry.scope !== scopeFilter) return false;
return true;
});
const handleSave = async (key: string, value: string, scope: string, env: boolean, secret: boolean) => {
try {
await api.putKey(key, scope, { value, env, secret });
addToast(`Key "${key}" saved`, "success");
setModal(null);
load();
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
const handleDelete = async (key: string, scope: string) => {
if (!confirm(`Delete "${key}"?`)) return;
try {
await api.deleteKey(key, scope);
addToast(`Key "${key}" deleted`, "success");
load();
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
const isAdmin = data?.role === "admin";
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-[#64748b]">Loading...</div>
</div>
);
}
return (
<div className="min-h-screen bg-[#0a0a0c]">
{/* Header */}
<header className="border-b border-[#1e2030] bg-[#12141a]/80 backdrop-blur-sm sticky top-0 z-30">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<h1 className="text-xl font-bold text-white" style={{ fontFamily: "var(--font-heading)" }}>Config Service</h1>
{isAdmin && (
<div className="flex bg-[#0a0a0c] rounded-lg p-0.5 border border-[#1e2030]">
<button onClick={() => setTab("config")} className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${tab === "config" ? "bg-[#3b82f6] text-white" : "text-[#64748b] hover:text-white"}`}>Config</button>
<button onClick={() => setTab("admin")} className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${tab === "admin" ? "bg-[#3b82f6] text-white" : "text-[#64748b] hover:text-white"}`}>Admin</button>
</div>
)}
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-[#64748b]" style={{ fontFamily: "var(--font-mono)" }}>{data?.agent_id}</span>
{isAdmin && <span className="text-xs px-2 py-0.5 rounded-full bg-purple-500/15 text-purple-400 border border-purple-500/30 font-medium">admin</span>}
<button onClick={onLogout} className="text-sm text-[#64748b] hover:text-white transition-colors">Logout</button>
</div>
</div>
</header>
<main className="max-w-7xl mx-auto px-6 py-6">
{tab === "config" ? (
<>
{/* Toolbar */}
<div className="flex items-center gap-3 mb-6 flex-wrap">
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search keys..."
className="flex-1 min-w-[200px] px-4 py-2.5 bg-[#12141a] border border-[#1e2030] rounded-lg text-white text-sm placeholder-[#334155] focus:outline-none focus:border-[#3b82f6] transition-colors"
/>
<select
value={scopeFilter}
onChange={(e) => setScopeFilter(e.target.value as any)}
className="px-3 py-2.5 bg-[#12141a] border border-[#1e2030] rounded-lg text-white text-sm focus:outline-none focus:border-[#3b82f6]"
>
<option value="all">All scopes</option>
<option value="personal">Personal</option>
<option value="shared">Shared</option>
</select>
<button onClick={() => setModal({})} className="px-4 py-2.5 bg-[#3b82f6] hover:bg-[#2563eb] text-white text-sm font-semibold rounded-lg transition-colors whitespace-nowrap">
+ Add Key
</button>
</div>
{/* Stats */}
<div className="grid grid-cols-3 gap-4 mb-6">
{[
{ label: "Total Keys", value: entries.length },
{ label: "Shared", value: entries.filter(([, e]) => e.scope === "shared").length },
{ label: "Secrets", value: entries.filter(([, e]) => e.secret).length },
].map((s) => (
<div key={s.label} className="bg-[#12141a] border border-[#1e2030] rounded-xl px-5 py-4">
<div className="text-2xl font-bold text-white" style={{ fontFamily: "var(--font-heading)" }}>{s.value}</div>
<div className="text-xs text-[#64748b] mt-1">{s.label}</div>
</div>
))}
</div>
{/* Table */}
<div className="bg-[#12141a] border border-[#1e2030] rounded-xl p-5">
<ConfigTable
entries={filtered}
onEdit={(key, entry) => setModal({ key, entry })}
onDelete={handleDelete}
addToast={addToast}
/>
</div>
</>
) : (
<AdminPanel addToast={addToast} />
)}
</main>
{modal && (
<AddEditModal
editKey={modal.key}
editEntry={modal.entry}
onSave={handleSave}
onClose={() => setModal(null)}
/>
)}
</div>
);
}

View File

@ -0,0 +1,54 @@
import { useState } from "react";
export default function LoginPage({ onLogin }: { onLogin: () => void }) {
const [token, setToken] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError("");
try {
const res = await fetch("/config", { headers: { Authorization: `Bearer ${token.trim()}` } });
if (!res.ok) throw new Error("Invalid token");
localStorage.setItem("config-token", token.trim());
onLogin();
} catch {
setError("Authentication failed. Check your token.");
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-[#0a0a0c]">
<form onSubmit={handleSubmit} className="w-full max-w-md p-8 bg-[#12141a] border border-[#1e2030] rounded-2xl">
<div className="mb-8 text-center">
<h1 className="text-3xl font-bold text-white mb-1" style={{ fontFamily: "var(--font-heading)" }}>
Config Service
</h1>
<p className="text-[#64748b] text-sm">Agent Configuration Management</p>
</div>
<label className="block text-sm text-[#64748b] mb-2 font-medium">API Token</label>
<input
type="password"
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder="Enter your bearer token"
className="w-full px-4 py-3 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white placeholder-[#334155] focus:outline-none focus:border-[#3b82f6] transition-colors"
style={{ fontFamily: "var(--font-mono)" }}
autoFocus
/>
{error && <p className="text-red-400 text-sm mt-2">{error}</p>}
<button
type="submit"
disabled={!token.trim() || loading}
className="w-full mt-6 py-3 bg-[#3b82f6] hover:bg-[#2563eb] disabled:opacity-40 text-white font-semibold rounded-lg transition-colors"
>
{loading ? "Authenticating..." : "Connect"}
</button>
</form>
</div>
);
}

View File

@ -0,0 +1,31 @@
import { useEffect, useState } from "react";
import type { Toast as ToastType } from "../types";
export default function Toast({ toasts, remove }: { toasts: ToastType[]; remove: (id: number) => void }) {
return (
<div className="fixed top-4 right-4 z-50 flex flex-col gap-2">
{toasts.map((t) => (
<ToastItem key={t.id} toast={t} remove={remove} />
))}
</div>
);
}
function ToastItem({ toast, remove }: { toast: ToastType; remove: (id: number) => void }) {
const [show, setShow] = useState(false);
useEffect(() => {
requestAnimationFrame(() => setShow(true));
const timer = setTimeout(() => { setShow(false); setTimeout(() => remove(toast.id), 300); }, 3000);
return () => clearTimeout(timer);
}, [toast.id, remove]);
return (
<div
className={`px-4 py-3 rounded-lg border text-sm font-medium transition-all duration-300 ${
show ? "opacity-100 translate-x-0" : "opacity-0 translate-x-4"
} ${toast.type === "error" ? "bg-red-500/10 border-red-500/30 text-red-400" : "bg-green-500/10 border-green-500/30 text-green-400"}`}
>
{toast.message}
</div>
);
}

View File

@ -0,0 +1,39 @@
import { useCallback } from "react";
const getToken = () => localStorage.getItem("config-token") || "";
export function useApi() {
const request = useCallback(async (path: string, options: RequestInit = {}) => {
const res = await fetch(path, {
...options,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getToken()}`,
...(options.headers || {}),
},
});
if (!res.ok) {
const text = await res.text();
throw new Error(text || `${res.status} ${res.statusText}`);
}
if (res.status === 204) return null;
return res.json();
}, []);
const getConfig = () => request("/config");
const getKey = (key: string) => request(`/config/${encodeURIComponent(key)}`);
const putKey = (key: string, scope: string, body: { value: string; env?: boolean; secret?: boolean }) =>
request(`/config/${encodeURIComponent(key)}?scope=${scope}`, { method: "PUT", body: JSON.stringify(body) });
const patchKey = (key: string, scope: string, body: { env?: boolean; secret?: boolean }) =>
request(`/config/${encodeURIComponent(key)}?scope=${scope}`, { method: "PATCH", body: JSON.stringify(body) });
const deleteKey = (key: string, scope: string) =>
request(`/config/${encodeURIComponent(key)}?scope=${scope}`, { method: "DELETE" });
const getAgents = () => request("/admin/agents");
const getAgent = (id: string) => request(`/admin/agent/${encodeURIComponent(id)}`);
const createToken = (agent_id: string, role?: string) =>
request("/admin/token", { method: "POST", body: JSON.stringify({ agent_id, role }) });
const revokeToken = (id: string) =>
request(`/admin/token/${encodeURIComponent(id)}`, { method: "DELETE" });
return { getConfig, getKey, putKey, patchKey, deleteKey, getAgents, getAgent, createToken, revokeToken };
}

View File

@ -0,0 +1,31 @@
@import "tailwindcss";
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Plus+Jakarta+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');
@theme {
--color-bg: #0a0a0c;
--color-surface: #12141a;
--color-border: #1e2030;
--color-accent: #3b82f6;
--color-accent-hover: #2563eb;
--color-text: #e2e8f0;
--color-text-dim: #64748b;
--color-badge-shared: #3b82f6;
--color-badge-personal: #22c55e;
--color-badge-secret: #ef4444;
--color-badge-noenv: #eab308;
--font-heading: 'Space Grotesk', sans-serif;
--font-body: 'Plus Jakarta Sans', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
}
body {
background-color: var(--color-bg);
color: var(--color-text);
font-family: var(--font-body);
margin: 0;
}
* {
scrollbar-width: thin;
scrollbar-color: #1e2030 transparent;
}

View File

@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
);

View File

@ -0,0 +1,25 @@
export interface ConfigEntry {
value: string;
scope: "personal" | "shared";
env: boolean;
secret: boolean;
updated_at: string;
}
export interface ConfigResponse {
agent_id: string;
role?: string;
secrets: Record<string, ConfigEntry>;
}
export interface Agent {
id: string;
role: string;
tokens?: { id: string; created_at: string }[];
}
export interface Toast {
id: number;
message: string;
type: "success" | "error";
}

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,12 @@
import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { viteSingleFile } from "vite-plugin-singlefile";
export default defineConfig({
plugins: [react(), tailwindcss(), viteSingleFile()],
build: {
target: "esnext",
minify: "terser",
},
});

View File

@ -292,6 +292,12 @@ export default {
// Health check // Health check
if (path === "/health") return json({ status: "ok" }); if (path === "/health") return json({ status: "ok" });
// Serve UI
if (path === "/" && method === "GET") {
const { renderUI } = await import("./ui.js");
return new Response(renderUI(), { headers: { "Content-Type": "text/html" } });
}
// Auth required for everything else // Auth required for everything else
const auth = await authenticate(request, env.CONFIG_KV); const auth = await authenticate(request, env.CONFIG_KV);
if (!auth) return err("unauthorized", 401); if (!auth) return err("unauthorized", 401);

File diff suppressed because one or more lines are too long

28
scripts/build-ui.sh Executable file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
export PATH="$HOME/.bun/bin:$PATH"
echo "Building webui..."
cd packages/webui
bun run build
HTML=$(cat dist/index.html)
echo "Generating ui.ts..."
cat > ../worker/src/ui.ts << 'TSEOF'
export function renderUI(): string {
return UI_HTML;
}
TSEOF
# Use node to safely embed the HTML as a JS string
node -e "
const fs = require('fs');
const html = fs.readFileSync('dist/index.html', 'utf8');
const src = 'export function renderUI(): string {\n return ' + JSON.stringify(html) + ';\n}\n';
fs.writeFileSync('../worker/src/ui.ts', src);
"
echo "Done. Generated packages/worker/src/ui.ts"