Files
AgentHub/client/src/components/users/AccountPoolCard.tsx
T
nntrivi2001 c042adc51b ui(pool): pick an account's users from its own Edit
Each account row in the Account pool card has a pencil: tick the users
whose sessions run on it (one moves off any other account, unticking sends
one back to the balancer). PUT /api/accounts/:name/users saves the set in one
transaction, audits each change and switches a Claude login into each added
user's home at once. The card-level switch button and pinned list are gone.
2026-10-19 10:45:54 +07:00

675 lines
23 KiB
TypeScript

/**
* @file AccountPoolCard.tsx
* @description The Users page's account pool card (`GET /api/accounts`): the
* Claude and Codex accounts every user's new sessions are spread over, each
* with its live panes, $ and tokens in the last 5 h / 7 d and quota — so nobody signs in
* per user. An admin adds one — for Claude a login MOVED in from a saved
* switch-user profile (`GET /api/accounts/profiles`), a pasted
* `.credentials.json`, or a `claude setup-token` token; for Codex an OpenAI
* API key or a pasted `auth.json` — or removes one, each time with their own
* password again; an analyst only reads. The secret only goes IN: the server
* never sends it back. An account's Edit (pencil) picks the users who run on
* it (`PUT /api/accounts/:name/users`): their sessions skip the balancer, and
* a Claude login goes into their home at once — no restart.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { useCallback, useEffect, useState, type KeyboardEvent, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { KeyRound, Pencil, Plus, RefreshCw, Trash2 } from "lucide-react";
import {
api,
type AccountPin,
type AccountPool,
type PoolAccountInput,
type PoolProfile,
type PoolTool,
type ServerUserUsage,
} from "../../lib/api";
import { fmt, fmtCost, formatDateTime } from "../../lib/format";
import { toast } from "../../lib/toast";
import { isSubmitEnter } from "../../lib/keys";
import { useSpin } from "../../hooks/useSpin";
import { ConfirmModal } from "../ConfirmModal";
import { Checkbox } from "../Checkbox";
type Row = {
tool: PoolTool;
name: string;
kind: string;
email: string | null;
refreshError: string | null;
addedAt: string;
expired: boolean;
livePanes: number;
spend5h: number;
spend7d: number;
tokens5h: number;
tokens7d: number;
quotaPercent: number | null;
full: boolean;
};
function rowsOf(pool: AccountPool): Row[] {
return [
...pool.accounts.map((a) => ({ ...a, tool: "claude" as const })),
...pool.codex.map((a) => ({
...a,
tool: "codex" as const,
expired: false,
email: null,
refreshError: null,
})),
];
}
const pinsOf = (pool: AccountPool, tool: PoolTool): AccountPin[] => pool.pins?.[tool] ?? [];
function errorText(t: TFunction<"users">, e: unknown): string {
const err = e as Error & { code?: string };
return err.code && t(`pool.errors.${err.code}`, { defaultValue: "" })
? t(`pool.errors.${err.code}`)
: err.message;
}
export function AccountPoolCard({ isAdmin }: { isAdmin: boolean }) {
const { t } = useTranslation("users");
const [pool, setPool] = useState<AccountPool | null>(null);
const [error, setError] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const [removing, setRemoving] = useState<Row | null>(null);
const [editing, setEditing] = useState<Row | null>(null);
const load = useCallback(
(force = false) =>
api.accountPool
.list(force)
.then((r) => {
setPool(r);
setError(null);
})
.catch((e: Error) => setError(e.message)),
[]
);
const [spinning, refresh] = useSpin(() => load(true));
useEffect(() => {
void load();
}, [load]);
const rows = pool ? rowsOf(pool) : [];
const th = "px-5 py-2.5 text-[11px] font-semibold text-fg-muted uppercase tracking-wider";
return (
<section className="card" data-testid="account-pool">
<div className="flex flex-wrap items-center gap-2 px-5 py-4 border-b border-border">
<KeyRound className="w-4 h-4 text-fg-muted" />
<div className="flex-1 min-w-0">
<h2 className="text-sm font-semibold text-fg-primary">{t("pool.title")}</h2>
<p className="text-xs text-fg-muted">{t("pool.description")}</p>
</div>
<button
type="button"
onClick={refresh}
disabled={spinning}
aria-busy={spinning}
title={t("pool.refresh")}
aria-label={t("pool.refresh")}
className="btn-icon"
>
<RefreshCw className={`w-4 h-4 ${spinning ? "animate-spin" : ""}`} />
</button>
{isAdmin && (
<button type="button" onClick={() => setAdding(true)} className="btn-primary">
<Plus className="w-4 h-4" /> {t("pool.add")}
</button>
)}
</div>
{error && (
<p role="alert" className="px-5 py-3 text-xs text-status-danger">
{error}
</p>
)}
{pool && rows.length === 0 && (
<p className="px-5 py-8 text-center text-sm text-fg-muted">{t("pool.empty")}</p>
)}
{rows.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full min-w-[640px]">
<thead>
<tr className="border-b border-border text-left">
<th className={th}>{t("pool.account")}</th>
<th className={th}>{t("pool.tool")}</th>
<th className={`${th} text-right`}>{t("pool.livePanes")}</th>
<th className={`${th} text-right`}>{t("pool.quota")}</th>
<th className={`${th} text-right`}>{t("pool.spend")}</th>
{isAdmin && <th className={`${th} text-right`}>{t("actions")}</th>}
</tr>
</thead>
<tbody className="divide-y divide-border">
{rows.map((r) => (
<tr key={`${r.tool}:${r.name}`} className={r.expired ? "opacity-60" : ""}>
<td className="px-5 py-2.5">
<div className="text-sm font-medium text-fg-primary">{r.name}</div>
{r.email && <div className="text-[11px] text-fg-secondary">{r.email}</div>}
<div className="text-[11px] text-fg-muted">
{t("pool.added", { at: formatDateTime(r.addedAt) })}
</div>
{pool && pinsOf(pool, r.tool).some((p) => p.account === r.name) && (
<div className="text-[11px] text-fg-secondary">
{t("pool.pinned", {
users: pinsOf(pool, r.tool)
.filter((p) => p.account === r.name)
.map((p) => p.username)
.join(", "),
})}
</div>
)}
</td>
<td className="px-5 py-2.5 text-sm text-fg-secondary">
{t(`pool.kind.${r.kind}`)}
{r.expired && (
<span className="badge ml-1.5 py-0 text-[10px] bg-status-danger/10 text-status-danger border-status-danger/20">
{t("pool.expired")}
</span>
)}
{r.refreshError && !r.expired && (
<span
className="badge ml-1.5 py-0 text-[10px] bg-status-warning/10 text-status-warning border-status-warning/20"
title={r.refreshError}
>
{t("pool.refreshFailed")}
</span>
)}
{r.full && (
<span className="badge ml-1.5 py-0 text-[10px] bg-status-warning/10 text-status-warning border-status-warning/20">
{t("pool.full")}
</span>
)}
</td>
<td className="px-5 py-2.5 text-right text-sm tabular-nums text-fg-secondary">
{r.livePanes}
</td>
<td className="px-5 py-2.5 text-right text-sm tabular-nums text-fg-secondary">
{r.quotaPercent == null ? "—" : `${Math.round(r.quotaPercent)}%`}
</td>
<td className="px-5 py-2.5 text-right tabular-nums">
<div className="text-sm text-fg-primary">
{fmtCost(r.spend5h)}
<span className="ml-1.5 text-[11px] text-fg-muted">
{t("pool.tokens", { tokens: fmt(r.tokens5h) })}
</span>
</div>
<div className="text-[11px] text-fg-muted">
{t("pool.spend7d", { cost: fmtCost(r.spend7d), tokens: fmt(r.tokens7d) })}
</div>
</td>
{isAdmin && (
<td className="px-5 py-2 text-right whitespace-nowrap">
<button
type="button"
onClick={() => setEditing(r)}
title={t("pool.edit", { name: r.name })}
aria-label={t("pool.edit", { name: r.name })}
className="btn-icon"
>
<Pencil className="h-4 w-4" />
</button>
<button
type="button"
onClick={() => setRemoving(r)}
title={t("pool.remove", { name: r.name })}
aria-label={t("pool.remove", { name: r.name })}
className="btn-icon"
>
<Trash2 className="h-4 w-4" />
</button>
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
)}
{adding && (
<AddAccountDialog
onClose={() => setAdding(false)}
onDone={(name) => {
toast.success(t("pool.done.added", { name }));
setAdding(false);
void load();
}}
/>
)}
{removing && (
<RemoveAccountDialog
row={removing}
onClose={() => setRemoving(null)}
onDone={() => {
toast.success(t("pool.done.removed", { name: removing.name }));
setRemoving(null);
void load();
}}
/>
)}
{editing && pool && (
<EditAccountDialog
pool={pool}
row={editing}
onClose={() => setEditing(null)}
onDone={(r) => {
const left = r.added.filter(
(u) => u.switched === "own-login" || u.switched === "expired"
);
toast.success(t("pool.editDone", { name: editing.name }));
for (const u of left) {
toast.info(
t(`pool.pinDone.${u.switched}`, { user: u.username, account: editing.name })
);
}
setEditing(null);
void load();
}}
/>
)}
</section>
);
}
/**
* One account's Edit: tick the users whose sessions run on it. A user already
* on another account of the tool moves here when ticked; unticking one sends
* them back to the least-used account. Saved in one request, password again.
*/
function EditAccountDialog({
pool,
row,
onClose,
onDone,
}: {
pool: AccountPool;
row: Row;
onClose: () => void;
onDone: (r: Awaited<ReturnType<typeof api.accountPool.setUsers>>) => void;
}) {
const { t } = useTranslation("users");
const pins = pinsOf(pool, row.tool);
const initial = pins.filter((p) => p.account === row.name).map((p) => p.userId);
const [users, setUsers] = useState<ServerUserUsage[] | null>(null);
const [chosen, setChosen] = useState<Set<number>>(() => new Set(initial));
const [current, setCurrent] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
api.users
.list()
.then((r) => setUsers(r.users))
.catch(() => setUsers([]));
}, []);
const changed = chosen.size !== initial.length || initial.some((id) => !chosen.has(id));
const ready = changed && current.length > 0;
const toggle = (id: number, on: boolean) =>
setChosen((prev) => {
const next = new Set(prev);
if (on) next.add(id);
else next.delete(id);
return next;
});
const submit = async () => {
if (!ready || busy) return;
setBusy(true);
setError(null);
try {
onDone(await api.accountPool.setUsers(row.tool, row.name, [...chosen], current));
} catch (e) {
setError(errorText(t, e));
} finally {
setBusy(false);
}
};
return (
<ConfirmModal
open
title={t("pool.edit", { name: row.name })}
message={t("pool.editHint")}
confirmLabel={t("pool.save")}
cancelLabel={t("common:cancel")}
destructive={false}
busy={busy}
disabled={!ready}
onConfirm={() => void submit()}
onCancel={onClose}
>
<div
className="mt-3 space-y-3"
onKeyDown={(e) => {
if ((e.target as HTMLElement).tagName === "INPUT" && isSubmitEnter(e)) {
e.preventDefault();
void submit();
}
}}
>
<div>
<span className="text-xs font-medium text-fg-secondary">{t("pool.users")}</span>
<div className="mt-1 max-h-56 overflow-y-auto rounded-md border border-border divide-y divide-border">
{users === null && (
<p className="px-3 py-2 text-xs text-fg-muted">{t("pool.loadingUsers")}</p>
)}
{users?.length === 0 && (
<p className="px-3 py-2 text-xs text-fg-muted">{t("pool.noUsers")}</p>
)}
{users?.map((u) => {
const elsewhere = pins.find((p) => p.userId === u.id && p.account !== row.name);
return (
<div key={u.id} className="px-3 py-2">
<Checkbox
checked={chosen.has(u.id)}
onChange={(on) => toggle(u.id, on)}
label={
<span>
{u.username}
{u.disabled && (
<span className="ml-1 text-fg-muted">({t("disabled")})</span>
)}
{elsewhere && (
<span className="ml-1.5 text-[11px] text-fg-muted">
{t("pool.onAccount", { account: elsewhere.account })}
</span>
)}
</span>
}
labelClassName="text-sm text-fg-primary"
/>
</div>
);
})}
</div>
</div>
<Field label={t("yourPassword")} hint={t("yourPasswordHint")}>
<input
type="password"
className="input w-full text-sm"
value={current}
onChange={(e) => setCurrent(e.target.value)}
autoComplete="current-password"
aria-label={t("yourPassword")}
/>
</Field>
{error && (
<p role="alert" className="text-xs text-status-danger">
{error}
</p>
)}
</div>
</ConfirmModal>
);
}
type ClaudeSource = "profile" | "credentials" | "token";
function AddAccountDialog({
onClose,
onDone,
}: {
onClose: () => void;
onDone: (name: string) => void;
}) {
const { t } = useTranslation("users");
const [tool, setTool] = useState<PoolTool>("claude");
const [source, setSource] = useState<ClaudeSource>("profile");
const [profiles, setProfiles] = useState<PoolProfile[] | null>(null);
const [profile, setProfile] = useState("");
const [name, setName] = useState("");
const [secret, setSecret] = useState("");
const [current, setCurrent] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
api.accountPool
.profiles()
.then((r) => setProfiles(r.profiles))
.catch(() => setProfiles([]));
}, []);
const fromProfile = tool === "claude" && source === "profile";
// A profile already names itself: its name is the default.
const ready =
current.length > 0 &&
(fromProfile ? profile.length > 0 : name.trim().length > 0 && secret.trim().length > 0);
const submit = async () => {
if (!ready || busy) return;
setBusy(true);
setError(null);
const body: PoolAccountInput =
tool === "codex"
? { tool, name: name.trim(), token: secret.trim() }
: source === "profile"
? { tool, name: name.trim() || profile, profile }
: source === "credentials"
? { tool, name: name.trim(), credentials: secret.trim() }
: { tool, name: name.trim(), token: secret.trim() };
try {
const r = await api.accountPool.add(body, current);
onDone(r.account.name);
} catch (e) {
setError(errorText(t, e));
} finally {
setBusy(false);
}
};
const onKeyDown = (e: KeyboardEvent) => {
// The secret box is a textarea for pasted JSON: Enter there is a newline.
if ((e.target as HTMLElement).tagName !== "TEXTAREA" && isSubmitEnter(e)) {
e.preventDefault();
void submit();
}
};
const secretKind = tool === "codex" ? "codex" : source;
return (
<ConfirmModal
open
title={t("pool.add")}
confirmLabel={t("pool.add")}
cancelLabel={t("common:cancel")}
destructive={false}
busy={busy}
disabled={!ready}
onConfirm={() => void submit()}
onCancel={onClose}
>
<div className="mt-3 space-y-3" onKeyDown={onKeyDown}>
<Field label={t("pool.tool")}>
<select
className="input w-full text-sm"
value={tool}
onChange={(e) => setTool(e.target.value as PoolTool)}
aria-label={t("pool.tool")}
>
<option value="claude">Claude Code</option>
<option value="codex">Codex</option>
</select>
</Field>
{tool === "claude" && (
<Field label={t("pool.source")} hint={t(`pool.sourceHint.${source}`)}>
<select
className="input w-full text-sm"
value={source}
onChange={(e) => setSource(e.target.value as ClaudeSource)}
aria-label={t("pool.source")}
>
{(["profile", "credentials", "token"] as const).map((s) => (
<option key={s} value={s}>
{t(`pool.sources.${s}`)}
</option>
))}
</select>
</Field>
)}
{fromProfile && (
<Field label={t("pool.profile")} hint={t("pool.profileHint")}>
<select
className="input w-full text-sm"
value={profile}
onChange={(e) => setProfile(e.target.value)}
aria-label={t("pool.profile")}
>
<option value="">
{profiles === null
? t("pool.loadingProfiles")
: profiles.length === 0
? t("pool.noProfiles")
: t("pool.chooseProfile")}
</option>
{profiles?.map((p) => (
<option key={p.name} value={p.name}>
{p.label}
{p.email ? ` — ${p.email}` : ""}
{p.active ? ` (${t("pool.activeHere")})` : ""}
</option>
))}
</select>
</Field>
)}
<Field
label={t("pool.name")}
hint={fromProfile ? t("pool.nameFromProfile") : t("pool.nameHint")}
>
<input
className="input w-full text-sm"
value={name}
onChange={(e) => setName(e.target.value)}
autoComplete="off"
aria-label={t("pool.name")}
/>
</Field>
{!fromProfile && (
<Field label={t(`pool.secret.${secretKind}`)} hint={t(`pool.secretHint.${secretKind}`)}>
{secretKind === "token" ? (
<input
type="password"
className="input w-full font-mono text-sm"
value={secret}
onChange={(e) => setSecret(e.target.value)}
autoComplete="off"
aria-label={t(`pool.secret.${secretKind}`)}
/>
) : (
<textarea
className="input w-full h-24 font-mono text-xs"
value={secret}
onChange={(e) => setSecret(e.target.value)}
autoComplete="off"
spellCheck={false}
aria-label={t(`pool.secret.${secretKind}`)}
/>
)}
</Field>
)}
<Field label={t("yourPassword")} hint={t("yourPasswordHint")}>
<input
type="password"
className="input w-full text-sm"
value={current}
onChange={(e) => setCurrent(e.target.value)}
autoComplete="current-password"
aria-label={t("yourPassword")}
/>
</Field>
{error && (
<p role="alert" className="text-xs text-status-danger">
{error}
</p>
)}
</div>
</ConfirmModal>
);
}
function RemoveAccountDialog({
row,
onClose,
onDone,
}: {
row: Row;
onClose: () => void;
onDone: () => void;
}) {
const { t } = useTranslation("users");
const [current, setCurrent] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = async () => {
if (!current || busy) return;
setBusy(true);
setError(null);
try {
await api.accountPool.remove(row.tool, row.name, current);
onDone();
} catch (e) {
setError(errorText(t, e));
} finally {
setBusy(false);
}
};
return (
<ConfirmModal
open
title={t("pool.remove", { name: row.name })}
message={t("pool.removeHint")}
confirmLabel={t("pool.removeButton")}
cancelLabel={t("common:cancel")}
busy={busy}
disabled={!current}
onConfirm={() => void submit()}
onCancel={onClose}
>
<div
className="mt-3 space-y-3"
onKeyDown={(e) => {
if (isSubmitEnter(e)) {
e.preventDefault();
void submit();
}
}}
>
<Field label={t("yourPassword")} hint={t("yourPasswordHint")}>
<input
type="password"
className="input w-full text-sm"
value={current}
onChange={(e) => setCurrent(e.target.value)}
autoComplete="current-password"
aria-label={t("yourPassword")}
/>
</Field>
{error && (
<p role="alert" className="text-xs text-status-danger">
{error}
</p>
)}
</div>
</ConfirmModal>
);
}
function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
return (
<label className="block">
<span className="text-xs font-medium text-fg-secondary">{label}</span>
<div className="mt-1">{children}</div>
{hint && <span className="mt-0.5 block text-[11px] text-fg-muted">{hint}</span>}
</label>
);
}