Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 758609775f | |||
| 09efb089cf | |||
| c83ddf62a0 |
+58
-6
@@ -3934,21 +3934,73 @@ async function cmdServer(sub, flags) {
|
||||
} else {
|
||||
console.log(c.dim(" an admin already exists — add more with `agenthub users add`"));
|
||||
}
|
||||
const wasServer = auth.isServerMode();
|
||||
settingsEnv.writeSetting("AGENTHUB_MODE", "server");
|
||||
envNote("AGENTHUB_MODE");
|
||||
console.log(`${c.green("✔")} server mode on (${file})`);
|
||||
// One Linux user per account (S3) is the default on Linux: install it now
|
||||
// (one sudo), unless it is already in place or `--no-system` opts out.
|
||||
const linux = require(path.join(REPO_ROOT, "server", "lib", "linux-accounts.js"));
|
||||
const shared = flags["no-system"] === true || process.platform !== "linux";
|
||||
if (!shared) {
|
||||
if (linux.serverConf()) {
|
||||
console.log(c.dim(" one Linux user per account is already installed"));
|
||||
// The system unit serves; it reads the mode only when it starts.
|
||||
if (!wasServer) {
|
||||
const r = spawnSync("sudo", [
|
||||
"-n",
|
||||
"systemctl",
|
||||
"restart",
|
||||
"--no-block",
|
||||
"agenthub.service",
|
||||
]);
|
||||
console.log(
|
||||
r.status === 0
|
||||
? `${c.green("✔")} agenthub.service restarted`
|
||||
: c.yellow("! restart it: sudo systemctl restart agenthub")
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.log(" Installing one Linux user per account (asks for your sudo password)…");
|
||||
try {
|
||||
await installSystem({}, settingsEnv);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`${e.message}\n Server mode is on, but every pane still runs as this account.` +
|
||||
"\n Fix it and run `agenthub server install-system`, or keep one shared" +
|
||||
" account with `agenthub server setup --no-system`."
|
||||
);
|
||||
}
|
||||
}
|
||||
// The admin made above (and anyone made before) gets their Linux account.
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
await cmdUsers("provision", [], { all: true });
|
||||
}
|
||||
console.log(" Next:");
|
||||
console.log(
|
||||
" 1. Restart the dashboard: systemctl --user restart agenthub (or agenthub start)"
|
||||
shared
|
||||
? " 1. Restart the dashboard: systemctl --user restart agenthub (or agenthub start)"
|
||||
: " 1. Log out and back in once, so your shell joins the agenthub groups"
|
||||
);
|
||||
console.log(
|
||||
" 2. Serve it over HTTPS through a reverse proxy that keeps the Host header,\n" +
|
||||
" and run setup with --hostname <that name> — see docs/SERVER-MODE.md."
|
||||
);
|
||||
console.log(
|
||||
c.dim(" Members see only their own workspaces, but every pane still runs as this")
|
||||
);
|
||||
console.log(c.dim(" one Linux account — use it with people you trust (docs/SERVER-MODE.md)."));
|
||||
if (shared) {
|
||||
console.log(
|
||||
c.yellow(
|
||||
process.platform === "linux"
|
||||
? "! --no-system: every pane runs as this one Linux account"
|
||||
: "! one Linux user per account needs Linux: every pane runs as this one account"
|
||||
)
|
||||
);
|
||||
console.log(
|
||||
c.dim(" Members see only their own workspaces, but an agent in a pane can read")
|
||||
);
|
||||
console.log(
|
||||
c.dim(" every user's files — use it with people you trust (docs/SERVER-MODE.md).")
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
c.dim(" Workspaces made before now have no owner: agenthub users assign <id> <user>")
|
||||
);
|
||||
@@ -3989,7 +4041,7 @@ async function cmdServer(sub, flags) {
|
||||
}
|
||||
console.error(
|
||||
c.red(
|
||||
"✖ Usage: agenthub server setup [--hostname name] [--admin name] | install-system [--dry-run|--uninstall] | tools | off | status"
|
||||
"✖ Usage: agenthub server setup [--hostname name] [--admin name] [--no-system] | install-system [--dry-run|--uninstall] | tools | off | status"
|
||||
)
|
||||
);
|
||||
process.exitCode = 1;
|
||||
|
||||
@@ -18,7 +18,12 @@
|
||||
* or dropped from the desktop), streamed with progress, ≤ 500 MB a batch;
|
||||
* drag items onto a folder to move them (Ctrl: copy); download a file as
|
||||
* itself, anything else as one zip; a taken name asks Replace / Keep both /
|
||||
* Skip. Server side: `/api/lanes/:id/fs/*` (server/lib/file-explorer.js).
|
||||
* Skip. Deleting forever asks first when it empties the Trash or touches
|
||||
* another user's. An admin's Trash opens on one folder per user (with its
|
||||
* item count); each folder is THAT user's Trash, to restore from or purge
|
||||
* without waiting the 7 days.
|
||||
* Server side: `/api/lanes/:id/fs/*` and `/api/homes/:who/fs/*`
|
||||
* (server/lib/file-explorer.js).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -82,6 +87,7 @@ import {
|
||||
import type { Lane } from "../../lib/types";
|
||||
import { useDialog } from "../../hooks/useDialog";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { formatBytes } from "../../lib/format";
|
||||
import { copyText } from "../../lib/clipboard";
|
||||
import { ContextMenu, MenuItem, MenuSeparator, useContextMenu } from "../ContextMenu";
|
||||
@@ -250,6 +256,10 @@ export function FileBrowser({
|
||||
const [showHidden, setShowHidden] = useState(() => readPref(HIDDEN_KEY, "0") === "1");
|
||||
const [query, setQuery] = useState<string | null>(null);
|
||||
const [trash, setTrash] = useState<FsTrashItem[]>([]);
|
||||
// An admin's Trash opens on its root: one folder per user's Trash, counted
|
||||
// from `GET /api/homes/trash` (a Trash that could not be read: its error).
|
||||
const [trashRoot, setTrashRoot] = useState(false);
|
||||
const [trashErrors, setTrashErrors] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [renaming, setRenaming] = useState<{ path: string; value: string } | null>(null);
|
||||
const [creating, setCreating] = useState<{ kind: "dir" | "file"; value: string } | null>(null);
|
||||
@@ -330,7 +340,12 @@ export function FileBrowser({
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
if (view === "trash") setTrash((await api.files.trash(target)).items);
|
||||
if (view === "trash" && trashRoot) {
|
||||
const out = await api.files.allTrash();
|
||||
setTrash(out.items);
|
||||
// A user whose trash could not be read is said so on their folder.
|
||||
setTrashErrors(Object.fromEntries((out.errors ?? []).map((e) => [e.home, e.message])));
|
||||
} else if (view === "trash") setTrash((await api.files.trash(target)).items);
|
||||
else setListing(await api.files.list(target, path));
|
||||
} catch (e) {
|
||||
// A dashboard that does not know /fs yet (not restarted) answers 404.
|
||||
@@ -338,10 +353,11 @@ export function FileBrowser({
|
||||
(e as { status?: number }).status === 404 && !errCode(e) ? t("fx.unavailable") : errText(e)
|
||||
);
|
||||
if (view === "files" && errCode(e) === "ENOFILE" && path) setPathState("");
|
||||
if (view === "trash") setTrash([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [target, path, view, t]);
|
||||
}, [target, path, view, trashRoot, t]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
@@ -635,11 +651,70 @@ export function FileBrowser({
|
||||
|
||||
const homeName = (who: string) =>
|
||||
who === "me" ? t("fx.myHome") : (homes.find((h) => h.id === who)?.label ?? who);
|
||||
/** Delete forever — asked first when it is all of it or someone else's. */
|
||||
const purge = async (id: string) => {
|
||||
if (id === "all" || ro) {
|
||||
const item = trash.find((i) => i.id === id);
|
||||
const ok = await confirmDialog({
|
||||
title: id === "all" ? t("fx.emptyTrashTitle") : t("fx.purgeTitle"),
|
||||
message:
|
||||
id === "all"
|
||||
? t("fx.emptyTrashBody", { count: trash.length, where: trashLabel })
|
||||
: t("fx.purgeBody", { name: item?.path ?? id, where: trashLabel }),
|
||||
confirmLabel: id === "all" ? t("fx.emptyTrash") : t("fx.purge"),
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
const item = trash.find((i) => i.id === id);
|
||||
await run(() => api.files.purge(target, id, item?.store), t("fx.purged"));
|
||||
};
|
||||
const restoreItem = (id: string) => {
|
||||
const item = trash.find((i) => i.id === id);
|
||||
void run(() => api.files.restore(target, id, item?.store), t("fx.restored"));
|
||||
};
|
||||
/**
|
||||
* Open a Trash. Every user has ONE recycle bin — their home's, over every
|
||||
* place they deleted in — so `home` opens that user's ("me": the caller's);
|
||||
* null (no home to open) falls back to the trash of the place shown, and
|
||||
* "*" opens the root an admin starts on: one folder per user's Trash.
|
||||
*/
|
||||
const openTrash = (home: string | null) => {
|
||||
if (home === "*") {
|
||||
setTrashRoot(true);
|
||||
setView("trash");
|
||||
setSelected(new Set());
|
||||
return;
|
||||
}
|
||||
setTrashRoot(false);
|
||||
if (home && !(isHomePlace(target) && target.home === home)) {
|
||||
setTarget({ home });
|
||||
setPathState("");
|
||||
setHistory({ back: [], fwd: [] });
|
||||
onNavigate?.({ home }, "");
|
||||
}
|
||||
setView("trash");
|
||||
setSelected(new Set());
|
||||
};
|
||||
// Someone else's Trash can be opened: the Trash starts on its folders.
|
||||
const manyTrashes = homes.some((h) => h.id !== "me");
|
||||
const openTrashes = () =>
|
||||
openTrash(manyTrashes ? "*" : homes.some((h) => h.id === "me") ? "me" : null);
|
||||
const placeName = (p: FsPlace) => (isHomePlace(p) ? homeName(p.home) : laneName(laneOf(p)!));
|
||||
const laneName = (id: number) => {
|
||||
const l = lanes.find((x) => x.id === id);
|
||||
return l ? l.title || l.cwd.split("/").pop() || `#${id}` : `#${id}`;
|
||||
};
|
||||
// A home's Trash is its USER's recycle bin, named after them: another
|
||||
// user's shows THAT user's (an admin may restore from or purge it; the rest
|
||||
// of the home stays read-only). A workspace's (no home to open) is the
|
||||
// trash of whoever owns its folder.
|
||||
const trashLabel = trashRoot
|
||||
? t("fx.trash")
|
||||
: !isHomePlace(target)
|
||||
? t("fx.trashAt", { name: laneName(laneOf(target)!) })
|
||||
: target.home === "me"
|
||||
? t("fx.myTrash")
|
||||
: t("fx.trashOf", { name: homeName(target.home) });
|
||||
const crumbs = path ? path.split("/") : [];
|
||||
const menuItem = ctx.menu?.item ?? null;
|
||||
const menuTargets = menuItem ? (selected.has(menuItem.path) ? selectedEntries : [menuItem]) : [];
|
||||
@@ -748,17 +823,10 @@ export function FileBrowser({
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<div className="border-t border-border p-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setView("trash");
|
||||
setSelected(new Set());
|
||||
}}
|
||||
className={placeClass(view === "trash")}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
{t("fx.trash")}
|
||||
<div className="border-t border-border p-2" data-testid="fx-trashes">
|
||||
<button type="button" onClick={openTrashes} className={placeClass(view === "trash")}>
|
||||
<Trash2 className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">{t("fx.trash")}</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
@@ -774,8 +842,8 @@ export function FileBrowser({
|
||||
</HeadButton>
|
||||
<HeadButton
|
||||
label={t("fx.up")}
|
||||
disabled={view !== "files" || listing?.parent == null}
|
||||
onClick={goUp}
|
||||
disabled={view === "trash" ? trashRoot || !manyTrashes : listing?.parent == null}
|
||||
onClick={view === "trash" ? () => openTrash("*") : goUp}
|
||||
>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</HeadButton>
|
||||
@@ -805,9 +873,29 @@ export function FileBrowser({
|
||||
aria-label={t("fx.location")}
|
||||
className="flex min-w-0 flex-1 items-center overflow-x-auto rounded-md bg-surface-2 px-1 py-0.5"
|
||||
>
|
||||
{view === "trash" ? (
|
||||
{view === "trash" && manyTrashes ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openTrash("*")}
|
||||
className={`flex shrink-0 items-center gap-1.5 rounded px-2 py-1 text-sm hover:bg-surface-3 ${
|
||||
trashRoot ? "font-semibold" : "text-fg-secondary"
|
||||
}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" /> {t("fx.trash")}
|
||||
</button>
|
||||
{!trashRoot && (
|
||||
<span className="flex shrink-0 items-center">
|
||||
<ChevronRight className="h-3.5 w-3.5 text-fg-muted" />
|
||||
<span className="px-2 py-1 text-sm font-semibold">
|
||||
{isHomePlace(target) ? homeName(target.home) : trashLabel}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : view === "trash" ? (
|
||||
<span className="flex items-center gap-1.5 px-2 py-1 text-sm font-medium">
|
||||
<Trash2 className="h-4 w-4" /> {t("fx.trash")}
|
||||
<Trash2 className="h-4 w-4" /> {trashLabel}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
@@ -1169,12 +1257,23 @@ export function FileBrowser({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : trashRoot ? (
|
||||
<TrashFolders
|
||||
homes={homes}
|
||||
items={trash}
|
||||
errors={trashErrors}
|
||||
error={error}
|
||||
loading={loading}
|
||||
homeName={homeName}
|
||||
onOpen={openTrash}
|
||||
/>
|
||||
) : (
|
||||
<TrashView
|
||||
items={trash}
|
||||
error={error}
|
||||
laneName={laneName}
|
||||
onRestore={(id) => void run(() => api.files.restore(target, id), t("fx.restored"))}
|
||||
onPurge={(id) => void run(() => api.files.purge(target, id))}
|
||||
onRestore={restoreItem}
|
||||
onPurge={(id) => void purge(id)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1651,13 +1750,102 @@ function InlineName({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* An admin's Trash root: one folder per user's Trash (theirs first), each
|
||||
* with its item count — or why it could not be read. Opening one shows that
|
||||
* user's Trash, where its items are restored or deleted forever.
|
||||
*/
|
||||
function TrashFolders({
|
||||
homes,
|
||||
items,
|
||||
errors,
|
||||
error,
|
||||
loading,
|
||||
homeName,
|
||||
onOpen,
|
||||
}: {
|
||||
homes: FsHome[];
|
||||
/** Every Trash's items, merged, each tagged with its `home`. */
|
||||
items: FsTrashItem[];
|
||||
/** Per home id: why its Trash could not be read. */
|
||||
errors: Record<string, string>;
|
||||
error: string | null;
|
||||
loading: boolean;
|
||||
homeName: (id: string) => string;
|
||||
onOpen: (home: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation(["lanes"]);
|
||||
const counts = new Map<string, number>();
|
||||
for (const i of items) if (i.home) counts.set(i.home, (counts.get(i.home) ?? 0) + 1);
|
||||
const ordered = [...homes.filter((h) => h.id === "me"), ...homes.filter((h) => h.id !== "me")];
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col" data-testid="fx-trash-root">
|
||||
<div className="border-b border-border px-4 py-2 text-sm text-fg-secondary">
|
||||
{t("fx.trashFoldersHint")}
|
||||
</div>
|
||||
{error && (
|
||||
<div className="m-4 rounded-md border border-status-danger/40 bg-status-danger/10 px-3 py-2 text-sm text-status-danger">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid min-h-0 flex-1 auto-rows-min grid-cols-[repeat(auto-fill,minmax(8.5rem,1fr))] gap-2 overflow-y-auto p-4">
|
||||
{ordered.map((h) => {
|
||||
const n = counts.get(h.id) ?? 0;
|
||||
const failed = errors[h.id];
|
||||
const name = h.id === "me" ? t("fx.myTrash") : homeName(h.id);
|
||||
return (
|
||||
<button
|
||||
key={h.id}
|
||||
type="button"
|
||||
title={t("fx.trashOf", { name: h.id === "me" ? t("fx.myHome") : h.label })}
|
||||
onClick={() => onOpen(h.id)}
|
||||
className="flex flex-col items-center gap-1 rounded-lg px-2 py-3 text-center hover:bg-surface-2"
|
||||
data-testid="fx-trash-folder"
|
||||
>
|
||||
<span className="relative">
|
||||
<Folder
|
||||
className={`h-14 w-14 ${
|
||||
n ? "fill-accent/25 text-accent" : "fill-surface-3 text-fg-muted"
|
||||
}`}
|
||||
/>
|
||||
{h.id === "me" ? (
|
||||
<House className="absolute bottom-2 right-0 h-4 w-4 text-fg-secondary" />
|
||||
) : (
|
||||
<UserRound className="absolute bottom-2 right-0 h-4 w-4 text-fg-secondary" />
|
||||
)}
|
||||
</span>
|
||||
<span className="w-full truncate text-[13px] font-medium">{name}</span>
|
||||
<span
|
||||
className={`w-full truncate text-[11px] ${
|
||||
failed ? "text-status-danger" : "text-fg-muted"
|
||||
}`}
|
||||
title={failed}
|
||||
>
|
||||
{failed
|
||||
? failed
|
||||
: loading
|
||||
? "…"
|
||||
: n
|
||||
? t("fx.itemsCount", { count: n })
|
||||
: t("fx.trashFolderEmpty")}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TrashView({
|
||||
items,
|
||||
error,
|
||||
laneName,
|
||||
onRestore,
|
||||
onPurge,
|
||||
}: {
|
||||
items: FsTrashItem[];
|
||||
error: string | null;
|
||||
laneName: (id: number) => string;
|
||||
onRestore: (id: string) => void;
|
||||
onPurge: (id: string) => void;
|
||||
@@ -1665,6 +1853,11 @@ function TrashView({
|
||||
const { t } = useTranslation(["lanes"]);
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col" data-testid="fx-trash">
|
||||
{error && (
|
||||
<div className="m-4 rounded-md border border-status-danger/40 bg-status-danger/10 px-3 py-2 text-sm text-status-danger">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 border-b border-border px-4 py-2 text-sm text-fg-secondary">
|
||||
<span className="flex-1">{t("fx.trashHint")}</span>
|
||||
<button
|
||||
@@ -1732,7 +1925,7 @@ function TrashView({
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!items.length && (
|
||||
{!items.length && !error && (
|
||||
<div className="flex flex-col items-center gap-2 py-16 text-fg-muted">
|
||||
<Trash2 className="h-14 w-14 opacity-40" />
|
||||
<p className="text-sm">{t("fx.trashEmpty")}</p>
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
* opens sub-folders, makes a folder inline, deletes into the Trash without a
|
||||
* confirm, copies in one workspace and pastes into another (`fromLane`),
|
||||
* asks Replace / Keep both / Skip when an upload's name is taken, refuses a
|
||||
* batch over 500 MB before sending anything, and restores from the Trash.
|
||||
* batch over 500 MB before sending anything, restores from the user's own
|
||||
* Trash, opens an admin's Trash on one folder per user (counted, an unreadable
|
||||
* one saying why), opens each user's Trash from its folder (asking before a
|
||||
* purge there, sending the item's store) and
|
||||
* shows a Trash that could not be read as an error, never as empty.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
@@ -12,6 +16,9 @@ import userEvent from "@testing-library/user-event";
|
||||
import { FileExplorer } from "../FileExplorer";
|
||||
import { api, type FsListing } from "../../../lib/api";
|
||||
import { toast } from "../../../lib/toast";
|
||||
import { confirmDialog } from "../../../lib/confirm";
|
||||
|
||||
vi.mock("../../../lib/confirm", () => ({ confirmDialog: vi.fn(async () => false) }));
|
||||
|
||||
vi.mock("../../../lib/api", () => ({
|
||||
gitTarget: (lane: number, session?: string | null) => (session ? { lane, session } : lane),
|
||||
@@ -32,6 +39,7 @@ vi.mock("../../../lib/api", () => ({
|
||||
copy: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
trash: vi.fn(),
|
||||
allTrash: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
purge: vi.fn(),
|
||||
upload: vi.fn(),
|
||||
@@ -70,6 +78,7 @@ beforeEach(() => {
|
||||
} as never);
|
||||
vi.mocked(api.files.list).mockImplementation(async (_t, p = "") => (p === "src" ? src : root));
|
||||
vi.mocked(api.files.trash).mockResolvedValue({ items: [] });
|
||||
vi.mocked(api.files.allTrash).mockResolvedValue({ items: [], errors: [] });
|
||||
vi.mocked(api.files.homes).mockResolvedValue({
|
||||
homes: [
|
||||
{ id: "me", label: "An", readOnly: false },
|
||||
@@ -212,10 +221,93 @@ describe("FileExplorer", () => {
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
await user.click(screen.getByRole("button", { name: "Trash" }));
|
||||
await user.click(
|
||||
within(screen.getByTestId("fx-trashes")).getByRole("button", { name: "Trash" })
|
||||
);
|
||||
await user.click(await screen.findByRole("button", { name: /My Trash/ }));
|
||||
await waitFor(() => expect(api.files.trash).toHaveBeenLastCalledWith({ home: "me" }));
|
||||
const trashRow = await screen.findByTestId("fx-trash-row");
|
||||
await user.click(within(trashRow).getByRole("button", { name: /Restore/ }));
|
||||
await waitFor(() => expect(api.files.restore).toHaveBeenCalledWith(1, "abc12345"));
|
||||
await waitFor(() =>
|
||||
expect(api.files.restore).toHaveBeenCalledWith({ home: "me" }, "abc12345", undefined)
|
||||
);
|
||||
});
|
||||
|
||||
it("opens an admin's Trash on one folder per user, each opening that user's Trash", async () => {
|
||||
vi.mocked(api.files.allTrash).mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: "bob12345",
|
||||
name: "old",
|
||||
laneId: null,
|
||||
path: "old",
|
||||
isDir: true,
|
||||
deletedAt: "2026-10-15T08:00:00.000Z",
|
||||
store: "host",
|
||||
home: "bob",
|
||||
owner: "Bob",
|
||||
},
|
||||
],
|
||||
errors: [{ home: "me", owner: "An", message: "EMEMBERGONE" }],
|
||||
});
|
||||
vi.mocked(api.files.trash).mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: "bob12345",
|
||||
name: "old",
|
||||
laneId: null,
|
||||
path: "old",
|
||||
isDir: true,
|
||||
deletedAt: "2026-10-15T08:00:00.000Z",
|
||||
store: "host",
|
||||
},
|
||||
],
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
const trashes = screen.getByTestId("fx-trashes");
|
||||
expect(within(trashes).getAllByRole("button")).toHaveLength(1);
|
||||
await user.click(within(trashes).getByRole("button", { name: "Trash" }));
|
||||
const folders = await screen.findAllByTestId("fx-trash-folder");
|
||||
expect(folders.map((f) => f.textContent)).toEqual(["My TrashEMEMBERGONE", "Bob1 item(s)"]);
|
||||
expect(screen.queryByTestId("fx-trash-row")).toBeNull();
|
||||
await user.click(folders[1]!);
|
||||
await waitFor(() => expect(api.files.trash).toHaveBeenLastCalledWith({ home: "bob" }));
|
||||
expect(screen.getByRole("navigation", { name: "Location" }).textContent).toContain("Bob");
|
||||
const trashRow = await screen.findByTestId("fx-trash-row");
|
||||
await user.click(within(trashRow).getByRole("button", { name: /Delete forever/ }));
|
||||
await waitFor(() =>
|
||||
expect(confirmDialog).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: expect.stringContaining("Bob's Trash") })
|
||||
)
|
||||
);
|
||||
expect(api.files.purge).not.toHaveBeenCalled();
|
||||
vi.mocked(confirmDialog).mockResolvedValueOnce(true);
|
||||
await user.click(within(trashRow).getByRole("button", { name: /Delete forever/ }));
|
||||
await waitFor(() =>
|
||||
expect(api.files.purge).toHaveBeenCalledWith({ home: "bob" }, "bob12345", "host")
|
||||
);
|
||||
// Back to the folders through the path bar.
|
||||
await user.click(
|
||||
within(screen.getByRole("navigation", { name: "Location" })).getByRole("button", {
|
||||
name: "Trash",
|
||||
})
|
||||
);
|
||||
expect(await screen.findAllByTestId("fx-trash-folder")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("shows why a Trash could not be read instead of an empty one", async () => {
|
||||
vi.mocked(api.files.trash).mockRejectedValue(new Error("ENOENT: no such folder"));
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
await user.click(
|
||||
within(screen.getByTestId("fx-trashes")).getByRole("button", { name: "Trash" })
|
||||
);
|
||||
await user.click(await screen.findByRole("button", { name: /My Trash/ }));
|
||||
expect(await screen.findByText(/ENOENT: no such folder/)).toBeTruthy();
|
||||
expect(screen.queryByText("The Trash is empty.")).toBeNull();
|
||||
});
|
||||
|
||||
it("opens the user's home from the sidebar, and pastes from it into a workspace", async () => {
|
||||
@@ -242,7 +334,7 @@ describe("FileExplorer", () => {
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
await user.click(await screen.findByRole("button", { name: /Bob/ }));
|
||||
await user.click(await screen.findByRole("button", { name: "Bob" }));
|
||||
expect(await screen.findByTestId("fx-readonly")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "New" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Upload" })).toBeNull();
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
* @file GitIdentitySettings.tsx
|
||||
* @description Settings → Git → **Your git identity** (`/api/me/git`): the
|
||||
* commit author (name + email in the account's global git config — prefilled
|
||||
* from Settings → Account while unset, since a member's commits fail without
|
||||
* one), the SSH
|
||||
* from Settings → Account while unset, the email else `<username>@smartgift.vn`,
|
||||
* since a member's commits fail without one; a new SSH key is labelled with
|
||||
* that email), the SSH
|
||||
* keys a clone (Add workspace → Clone) and the pushes from that clone use —
|
||||
* an ED25519 and/or an RSA one (AWS CodeCommit takes only RSA) — make one, copy its public half to add to GitHub/GitLab, replace or delete
|
||||
* it, and whether git typed in the account's own terminal uses it too (a
|
||||
@@ -308,7 +309,7 @@ export function GitIdentitySettings() {
|
||||
const member = id.account === "member";
|
||||
const authorShown = author ?? {
|
||||
name: id.author.name ?? me?.displayName ?? me?.username ?? "",
|
||||
email: id.author.email ?? me?.email ?? "",
|
||||
email: id.author.email ?? me?.email ?? id.defaultEmail ?? "",
|
||||
};
|
||||
const authorUnset = !id.author.name || !id.author.email;
|
||||
const authorDirty =
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* @file MemberTmuxCard.tsx
|
||||
* @description The Users page's tmux card (one Linux user per account only,
|
||||
* `GET /api/users/tmux`): each member's own tmux server — the version it runs
|
||||
* beside the installed one, its sessions, whether an agent of theirs is
|
||||
* working — so an admin sees who still runs an old tmux after an upgrade.
|
||||
* An admin restarts one member's server, or every idle outdated one at once
|
||||
* (`POST /api/users/:id/tmux-restart`, `/api/users/tmux-restart-idle`), each
|
||||
* time with their own password again; a restart ends that member's panes,
|
||||
* and the next start runs the installed tmux. An analyst only reads.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { RefreshCw, RotateCcw, TerminalSquare } from "lucide-react";
|
||||
import { api, type MemberTmux, type MemberTmuxRow } from "../../lib/api";
|
||||
import { formatDateTime } from "../../lib/format";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { isSubmitEnter } from "../../lib/keys";
|
||||
import { useSpin } from "../../hooks/useSpin";
|
||||
import { ConfirmModal } from "../ConfirmModal";
|
||||
|
||||
function errorText(t: TFunction<"users">, e: unknown): string {
|
||||
const err = e as Error & { code?: string };
|
||||
return err.code && t(`tmux.errors.${err.code}`, { defaultValue: "" })
|
||||
? t(`tmux.errors.${err.code}`)
|
||||
: err.message;
|
||||
}
|
||||
|
||||
const BADGE = "badge ml-1.5 py-0 text-[10px]";
|
||||
const WARN = `${BADGE} bg-status-warning/10 text-status-warning border-status-warning/20`;
|
||||
const DANGER = `${BADGE} bg-status-danger/10 text-status-danger border-status-danger/20`;
|
||||
|
||||
export function MemberTmuxCard({ isAdmin }: { isAdmin: boolean }) {
|
||||
const { t } = useTranslation("users");
|
||||
const [data, setData] = useState<MemberTmux | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// A member row = restart that one; "idle" = every idle outdated member.
|
||||
const [restarting, setRestarting] = useState<MemberTmuxRow | "idle" | null>(null);
|
||||
|
||||
const load = useCallback(
|
||||
() =>
|
||||
api.users
|
||||
.tmux()
|
||||
.then((r) => {
|
||||
setData(r);
|
||||
setError(null);
|
||||
})
|
||||
.catch((e: Error) => setError(e.message)),
|
||||
[]
|
||||
);
|
||||
const [spinning, refresh] = useSpin(load);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
if (!data?.available) return null;
|
||||
const rows = data.users.filter((u) => u.running);
|
||||
const idleOutdated = rows.filter((u) => u.outdated && u.busy === 0);
|
||||
const th = "px-5 py-2.5 text-[11px] font-semibold text-fg-muted uppercase tracking-wider";
|
||||
|
||||
return (
|
||||
<section className="card" data-testid="member-tmux">
|
||||
<div className="flex flex-wrap items-center gap-2 px-5 py-4 border-b border-border">
|
||||
<TerminalSquare 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("tmux.title")}</h2>
|
||||
<p className="text-xs text-fg-muted">
|
||||
{t("tmux.description", { version: data.installed ?? "?" })}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={refresh}
|
||||
disabled={spinning}
|
||||
aria-busy={spinning}
|
||||
title={t("tmux.refresh")}
|
||||
aria-label={t("tmux.refresh")}
|
||||
className="btn-icon"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${spinning ? "animate-spin" : ""}`} />
|
||||
</button>
|
||||
{isAdmin && idleOutdated.length > 0 && (
|
||||
<button type="button" onClick={() => setRestarting("idle")} className="btn-primary">
|
||||
<RotateCcw className="w-4 h-4" />{" "}
|
||||
{t("tmux.restartIdle", { count: idleOutdated.length })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{!data.matched && (
|
||||
<p className="px-5 py-2.5 text-xs text-status-warning border-b border-border">
|
||||
{t("tmux.notMatched")}
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="px-5 py-3 text-xs text-status-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{rows.length === 0 ? (
|
||||
<p className="px-5 py-8 text-center text-sm text-fg-muted">{t("tmux.empty")}</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[560px]">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-left">
|
||||
<th className={th}>{t("tmux.user")}</th>
|
||||
<th className={th}>{t("tmux.version")}</th>
|
||||
<th className={`${th} text-right`}>{t("tmux.sessions")}</th>
|
||||
<th className={th}>{t("tmux.agents")}</th>
|
||||
{isAdmin && <th className={`${th} text-right`}>{t("actions")}</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border">
|
||||
{rows.map((u) => (
|
||||
<tr key={u.id}>
|
||||
<td className="px-5 py-2.5 text-sm text-fg-primary">{u.username}</td>
|
||||
<td className="px-5 py-2.5 text-sm text-fg-secondary">
|
||||
<span className="font-mono">{u.stuck ? "?" : (u.version ?? "?")}</span>
|
||||
{u.stuck && <span className={DANGER}>{t("tmux.stuck")}</span>}
|
||||
{u.outdated && <span className={WARN}>{t("tmux.outdated")}</span>}
|
||||
{u.startedAt && (
|
||||
<div className="text-[11px] text-fg-muted">
|
||||
{t("tmux.since", {
|
||||
at: formatDateTime(new Date(u.startedAt).toISOString()),
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-2.5 text-right text-sm tabular-nums text-fg-secondary">
|
||||
{u.sessions ?? "—"}
|
||||
</td>
|
||||
<td className="px-5 py-2.5 text-sm text-fg-secondary">
|
||||
{u.busy > 0 ? t("tmux.working", { count: u.busy }) : t("tmux.idle")}
|
||||
</td>
|
||||
{isAdmin && (
|
||||
<td className="px-5 py-2 text-right">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRestarting(u)}
|
||||
title={t("tmux.restart", { name: u.username })}
|
||||
aria-label={t("tmux.restart", { name: u.username })}
|
||||
className="btn-icon"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{restarting && (
|
||||
<RestartDialog
|
||||
target={restarting}
|
||||
idle={idleOutdated}
|
||||
onClose={() => setRestarting(null)}
|
||||
onDone={(msg) => {
|
||||
toast.success(msg);
|
||||
setRestarting(null);
|
||||
void load();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RestartDialog({
|
||||
target,
|
||||
idle,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
target: MemberTmuxRow | "idle";
|
||||
idle: MemberTmuxRow[];
|
||||
onClose: () => void;
|
||||
onDone: (message: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation("users");
|
||||
const [current, setCurrent] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const one = target === "idle" ? null : target;
|
||||
|
||||
const submit = async () => {
|
||||
if (!current || busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (one) {
|
||||
await api.users.tmuxRestart(one.id, current);
|
||||
onDone(t("tmux.done", { name: one.username }));
|
||||
} else {
|
||||
const r = await api.users.tmuxRestartIdle(current);
|
||||
// A server that would not stop needs root: say which, the rest went.
|
||||
if (r.failed.length) toast.error(r.failed.map((f) => f.message).join("\n"));
|
||||
onDone(t("tmux.doneIdle", { names: r.restarted.join(", ") || "—" }));
|
||||
}
|
||||
} catch (e) {
|
||||
setError(errorText(t, e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ConfirmModal
|
||||
open
|
||||
title={one ? t("tmux.restart", { name: one.username }) : t("tmux.restartIdleTitle")}
|
||||
message={
|
||||
one
|
||||
? t(one.busy > 0 ? "tmux.restartHintBusy" : "tmux.restartHint", {
|
||||
name: one.username,
|
||||
count: one.sessions ?? 0,
|
||||
})
|
||||
: t("tmux.restartIdleHint", { names: idle.map((u) => u.username).join(", ") })
|
||||
}
|
||||
confirmLabel={t("tmux.restartButton")}
|
||||
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="whitespace-pre-line 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* @file MemberTmuxCard.test.tsx
|
||||
* @description The Users page's members' tmux card: hidden without one Linux
|
||||
* user per account, lists each running member server with its version and a
|
||||
* badge when it is older than the installed tmux, warns until tmux-member is
|
||||
* installed, and an admin restarts one member — or every idle outdated one,
|
||||
* the working member left out — only with their own password typed; an
|
||||
* analyst sees no restart control.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import type { MemberTmux } from "../../../lib/api";
|
||||
|
||||
const users = vi.hoisted(() => ({
|
||||
tmux: vi.fn(),
|
||||
tmuxRestart: vi.fn(),
|
||||
tmuxRestartIdle: vi.fn(),
|
||||
}));
|
||||
vi.mock("../../../lib/api", async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>();
|
||||
return { ...actual, api: { users } };
|
||||
});
|
||||
vi.mock("../../../lib/toast", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
import { MemberTmuxCard } from "../MemberTmuxCard";
|
||||
|
||||
const DATA: MemberTmux = {
|
||||
available: true,
|
||||
installed: "3.8",
|
||||
matched: true,
|
||||
users: [
|
||||
{ id: 2, username: "mia", running: true, version: "3.6", sessions: 2, busy: 0, outdated: true },
|
||||
{ id: 3, username: "zed", running: true, version: "3.6", sessions: 1, busy: 1, outdated: true },
|
||||
{
|
||||
id: 4,
|
||||
username: "ann",
|
||||
running: true,
|
||||
version: "3.8",
|
||||
sessions: 3,
|
||||
busy: 0,
|
||||
outdated: false,
|
||||
},
|
||||
{ id: 5, username: "bob", running: false, busy: 0, outdated: false },
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
users.tmux.mockResolvedValue(DATA);
|
||||
});
|
||||
|
||||
describe("MemberTmuxCard", () => {
|
||||
it("renders nothing without one Linux user per account", async () => {
|
||||
users.tmux.mockResolvedValue({ available: false, users: [] });
|
||||
const { container } = render(<MemberTmuxCard isAdmin />);
|
||||
await waitFor(() => expect(users.tmux).toHaveBeenCalled());
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it("lists running servers and marks the ones older than the installed tmux", async () => {
|
||||
render(<MemberTmuxCard isAdmin={false} />);
|
||||
expect(await screen.findByText("mia")).toBeInTheDocument();
|
||||
expect(screen.queryByText("bob")).toBeNull();
|
||||
expect(screen.getAllByText("older than installed")).toHaveLength(2);
|
||||
expect(screen.getByText(/Installed: tmux 3\.8/)).toBeInTheDocument();
|
||||
// An analyst reads only.
|
||||
expect(screen.queryByRole("button", { name: /Restart/ })).toBeNull();
|
||||
});
|
||||
|
||||
it("warns until tmux-member is installed", async () => {
|
||||
users.tmux.mockResolvedValue({ ...DATA, matched: false });
|
||||
render(<MemberTmuxCard isAdmin />);
|
||||
expect(await screen.findByText(/install-system/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("restarts one member only with the admin's password", async () => {
|
||||
users.tmuxRestart.mockResolvedValue({});
|
||||
render(<MemberTmuxCard isAdmin />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Restart mia's tmux" }));
|
||||
expect(screen.getByText(/Every pane of mia closes \(2 sessions\)/)).toBeInTheDocument();
|
||||
const go = screen.getByRole("button", { name: "Restart" });
|
||||
expect(go).toBeDisabled();
|
||||
await userEvent.type(screen.getByLabelText("Your password"), "pw");
|
||||
await userEvent.click(go);
|
||||
await waitFor(() => expect(users.tmuxRestart).toHaveBeenCalledWith(2, "pw"));
|
||||
});
|
||||
|
||||
it("restarts every idle outdated member at once, the working one left out", async () => {
|
||||
users.tmuxRestartIdle.mockResolvedValue({ restarted: ["mia"], skipped: ["zed"], failed: [] });
|
||||
render(<MemberTmuxCard isAdmin />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Restart 1 idle member" }));
|
||||
expect(screen.getByText(/no agent working: mia\./)).toBeInTheDocument();
|
||||
await userEvent.type(screen.getByLabelText("Your password"), "pw");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Restart" }));
|
||||
await waitFor(() => expect(users.tmuxRestartIdle).toHaveBeenCalledWith("pw"));
|
||||
});
|
||||
});
|
||||
@@ -577,7 +577,7 @@
|
||||
"fx.cutDone": "Cut {{count}} item(s) — open a folder (or another workspace) and Paste.",
|
||||
"fx.pasted": "Pasted.",
|
||||
"fx.crossOnlyWorkspace": "These items can only be pasted where they came from (a session worktree, an extra folder, or between two homes).",
|
||||
"fx.needsUpgrade": "This needs the updated server helper — ask an admin to run `sudo agenthub server install-system` once.",
|
||||
"fx.needsUpgrade": "This needs the updated server helper — ask an admin to run `agenthub server install-system` once.",
|
||||
"fx.conflictTitle": "Already there",
|
||||
"fx.conflictBody": "This name is taken in the destination: {{names}}",
|
||||
"fx.conflictAll": "Do this for every remaining file",
|
||||
@@ -591,6 +591,16 @@
|
||||
"fx.purge": "Delete forever",
|
||||
"fx.restored": "Restored.",
|
||||
"fx.trashEmpty": "The Trash is empty.",
|
||||
"fx.trashOf": "{{name}}'s Trash",
|
||||
"fx.myTrash": "My Trash",
|
||||
"fx.trashAt": "Trash ({{name}})",
|
||||
"fx.trashFoldersHint": "Each folder is one user's Trash — open it to restore or delete forever.",
|
||||
"fx.trashFolderEmpty": "Empty",
|
||||
"fx.purged": "Deleted forever.",
|
||||
"fx.emptyTrashTitle": "Empty the Trash?",
|
||||
"fx.emptyTrashBody": "All {{count}} items in {{where}} will be deleted forever. This cannot be undone.",
|
||||
"fx.purgeTitle": "Delete forever?",
|
||||
"fx.purgeBody": "“{{name}}” in {{where}} will be deleted forever. This cannot be undone.",
|
||||
"changes.openExplorer": "Open File Explorer — manage, upload and download files",
|
||||
"changes.openInExplorer": "Open in File Explorer",
|
||||
"fx.places": "Workspaces",
|
||||
@@ -620,7 +630,7 @@
|
||||
"fx.noWorkspace": "There is no workspace yet. Add one first, then its files show here.",
|
||||
"fx.myHome": "Home",
|
||||
"fx.userHomes": "Users' homes",
|
||||
"fx.readOnlyHome": "Another user's home — view and download only",
|
||||
"fx.readOnlyHome": "Another user's home — view and download only; their Trash can be restored or emptied",
|
||||
"fx.readOnly": "Read-only",
|
||||
"fx.readOnlyHint": "This is another user's home: you can view, copy and download, not change it.",
|
||||
"fx.homeEmpty": "Nothing in your home yet — its hidden files (.bashrc, .claude…) are not shown here. Your workspaces are on the left.",
|
||||
|
||||
@@ -204,5 +204,35 @@
|
||||
"body": "This deletes {{name}} for good: their login, {{count}} workspace(s), and their Linux account with the whole home folder (/srv/agenthub/users/{{user}}) — every file and all source code in it. It cannot be undone. Session history and the audit log stay.",
|
||||
"confirm": "Delete for good",
|
||||
"needsPassword": "Enter your own password below first."
|
||||
},
|
||||
"tmux": {
|
||||
"title": "Members' tmux",
|
||||
"description": "Each member's own tmux server keeps the version it started with until its last pane closes. Installed: tmux {{version}}.",
|
||||
"refresh": "Refresh",
|
||||
"notMatched": "Run `agenthub server install-system` once: until then an older member server is asked with the installed tmux, which can leave it stuck at 100% CPU.",
|
||||
"empty": "No member has a tmux server running.",
|
||||
"user": "User",
|
||||
"version": "tmux",
|
||||
"sessions": "Sessions",
|
||||
"agents": "Agents",
|
||||
"stuck": "not answering",
|
||||
"outdated": "older than installed",
|
||||
"since": "since {{at}}",
|
||||
"working_one": "{{count}} working",
|
||||
"working_other": "{{count}} working",
|
||||
"idle": "idle",
|
||||
"restart": "Restart {{name}}'s tmux",
|
||||
"restartIdle_one": "Restart {{count}} idle member",
|
||||
"restartIdle_other": "Restart {{count}} idle members",
|
||||
"restartIdleTitle": "Restart idle members' tmux",
|
||||
"restartHint": "Every pane of {{name}} closes ({{count}} sessions). Their Claude sessions resume from the workspace, and the next start runs the installed tmux.",
|
||||
"restartHintBusy": "An agent of {{name}} is working right now and will be stopped. Every pane of theirs closes ({{count}} sessions); their Claude sessions resume from the workspace.",
|
||||
"restartIdleHint": "Restarts the tmux of every member on an older version with no agent working: {{names}}. Their panes close; their Claude sessions resume from the workspace.",
|
||||
"restartButton": "Restart",
|
||||
"done": "{{name}}'s tmux restarted",
|
||||
"doneIdle": "Restarted: {{names}}",
|
||||
"errors": {
|
||||
"ETMUXSTUCK": "The server did not stop. Run the `sudo kill -9` command shown, as root, on the server."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -577,7 +577,7 @@
|
||||
"fx.cutDone": "Đã cắt {{count}} mục — mở thư mục (hoặc workspace khác) rồi Dán.",
|
||||
"fx.pasted": "Đã dán.",
|
||||
"fx.crossOnlyWorkspace": "Các mục này chỉ dán được ở nơi chúng được lấy ra (worktree của session, thư mục phụ, hoặc giữa hai home).",
|
||||
"fx.needsUpgrade": "Cần cập nhật helper của server — nhờ admin chạy `sudo agenthub server install-system` một lần.",
|
||||
"fx.needsUpgrade": "Cần cập nhật helper của server — nhờ admin chạy `agenthub server install-system` một lần.",
|
||||
"fx.conflictTitle": "Đã có sẵn",
|
||||
"fx.conflictBody": "Tên này đã có ở nơi đến: {{names}}",
|
||||
"fx.conflictAll": "Áp dụng cho tất cả file còn lại",
|
||||
@@ -591,6 +591,16 @@
|
||||
"fx.purge": "Xoá vĩnh viễn",
|
||||
"fx.restored": "Đã khôi phục.",
|
||||
"fx.trashEmpty": "Thùng rác trống.",
|
||||
"fx.trashOf": "Thùng rác của {{name}}",
|
||||
"fx.myTrash": "Thùng rác của tôi",
|
||||
"fx.trashAt": "Thùng rác ({{name}})",
|
||||
"fx.trashFoldersHint": "Mỗi thư mục là Thùng rác của một user — mở ra để khôi phục hoặc xoá vĩnh viễn.",
|
||||
"fx.trashFolderEmpty": "Trống",
|
||||
"fx.purged": "Đã xoá vĩnh viễn.",
|
||||
"fx.emptyTrashTitle": "Dọn sạch Thùng rác?",
|
||||
"fx.emptyTrashBody": "Toàn bộ {{count}} mục trong {{where}} sẽ bị xoá vĩnh viễn, không khôi phục được.",
|
||||
"fx.purgeTitle": "Xoá vĩnh viễn?",
|
||||
"fx.purgeBody": "“{{name}}” trong {{where}} sẽ bị xoá vĩnh viễn, không khôi phục được.",
|
||||
"changes.openExplorer": "Mở Quản lý file — quản lý, tải lên và tải về file",
|
||||
"changes.openInExplorer": "Mở trong Quản lý file",
|
||||
"fx.places": "Workspace",
|
||||
@@ -620,7 +630,7 @@
|
||||
"fx.noWorkspace": "Chưa có workspace nào. Hãy thêm một workspace, file của nó sẽ hiện ở đây.",
|
||||
"fx.myHome": "Thư mục home",
|
||||
"fx.userHomes": "Home của các user",
|
||||
"fx.readOnlyHome": "Home của user khác — chỉ xem và tải về",
|
||||
"fx.readOnlyHome": "Home của user khác — chỉ xem và tải về; Thùng rác của họ thì khôi phục hoặc xoá được",
|
||||
"fx.readOnly": "Chỉ đọc",
|
||||
"fx.readOnlyHint": "Đây là home của user khác: bạn chỉ xem, sao chép và tải về được, không sửa được.",
|
||||
"fx.homeEmpty": "Home của bạn chưa có thư mục nào — các file ẩn (.bashrc, .claude…) không hiện ở đây. Các workspace nằm ở danh sách bên trái.",
|
||||
|
||||
@@ -204,5 +204,35 @@
|
||||
"body": "Thao tác này xoá vĩnh viễn {{name}}: tài khoản đăng nhập, {{count}} workspace, và tài khoản Linux cùng toàn bộ thư mục home (/srv/agenthub/users/{{user}}) — mọi file và source code trong đó. Không thể khôi phục. Lịch sử session và audit log vẫn được giữ.",
|
||||
"confirm": "Xoá vĩnh viễn",
|
||||
"needsPassword": "Hãy nhập mật khẩu của bạn ở ô bên dưới trước."
|
||||
},
|
||||
"tmux": {
|
||||
"title": "Tmux của member",
|
||||
"description": "Mỗi member có tmux server riêng, giữ phiên bản lúc nó khởi động cho đến khi pane cuối cùng đóng. Bản đã cài: tmux {{version}}.",
|
||||
"refresh": "Làm mới",
|
||||
"notMatched": "Chạy `agenthub server install-system` một lần: trước đó, server cũ của member được hỏi bằng tmux bản mới và có thể kẹt ở 100% CPU.",
|
||||
"empty": "Không member nào đang chạy tmux server.",
|
||||
"user": "Người dùng",
|
||||
"version": "tmux",
|
||||
"sessions": "Session",
|
||||
"agents": "Agent",
|
||||
"stuck": "không trả lời",
|
||||
"outdated": "cũ hơn bản cài",
|
||||
"since": "từ {{at}}",
|
||||
"working_one": "{{count}} đang chạy",
|
||||
"working_other": "{{count}} đang chạy",
|
||||
"idle": "rảnh",
|
||||
"restart": "Khởi động lại tmux của {{name}}",
|
||||
"restartIdle_one": "Khởi động lại {{count}} member đang rảnh",
|
||||
"restartIdle_other": "Khởi động lại {{count}} member đang rảnh",
|
||||
"restartIdleTitle": "Khởi động lại tmux của member đang rảnh",
|
||||
"restartHint": "Mọi pane của {{name}} sẽ đóng ({{count}} session). Phiên Claude của họ resume lại được từ workspace, và lần Start sau sẽ chạy tmux bản đã cài.",
|
||||
"restartHintBusy": "Agent của {{name}} đang chạy và sẽ bị dừng. Mọi pane của họ sẽ đóng ({{count}} session); phiên Claude resume lại được từ workspace.",
|
||||
"restartIdleHint": "Khởi động lại tmux của mọi member đang chạy bản cũ mà không có agent nào đang chạy: {{names}}. Pane của họ sẽ đóng; phiên Claude resume lại được từ workspace.",
|
||||
"restartButton": "Khởi động lại",
|
||||
"done": "Đã khởi động lại tmux của {{name}}",
|
||||
"doneIdle": "Đã khởi động lại: {{names}}",
|
||||
"errors": {
|
||||
"ETMUXSTUCK": "Server không dừng. Chạy lệnh `sudo kill -9` được nêu, bằng quyền root, trên máy server."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+61
-4
@@ -544,6 +544,31 @@ export type ServerUserUsage = AuthUser & {
|
||||
logins?: number;
|
||||
lastLoginAt?: string | null;
|
||||
};
|
||||
/** One member's own tmux server (`GET /api/users/tmux`). */
|
||||
export interface MemberTmuxRow {
|
||||
id: number;
|
||||
username: string;
|
||||
running: boolean;
|
||||
/** Did not answer (hung, or backed off). */
|
||||
stuck?: boolean;
|
||||
version?: string | null;
|
||||
pid?: number | null;
|
||||
startedAt?: number | null;
|
||||
sessions?: number | null;
|
||||
/** Workspaces of theirs with an agent working now. */
|
||||
busy: number;
|
||||
/** Runs an older tmux than the installed one. */
|
||||
outdated: boolean;
|
||||
}
|
||||
/** `GET /api/users/tmux`: `available` only with one Linux user per account. */
|
||||
export interface MemberTmux {
|
||||
available: boolean;
|
||||
installed?: string | null;
|
||||
/** Calls on an older server already use its own binary (tmux-member installed). */
|
||||
matched?: boolean;
|
||||
users: MemberTmuxRow[];
|
||||
}
|
||||
|
||||
/** One user's home folder on disk (`GET /api/users/storage`); null = not measured. */
|
||||
export type UserStorage = {
|
||||
bytes: number;
|
||||
@@ -817,6 +842,11 @@ export interface FsTrashItem {
|
||||
path: string;
|
||||
isDir: boolean;
|
||||
deletedAt: string;
|
||||
/** A home's recycle bin only: which of the user's trash folders holds it. */
|
||||
store?: "home" | "host";
|
||||
/** The merged view only (`allTrash`): the home it belongs to, and its user. */
|
||||
home?: string;
|
||||
owner?: string;
|
||||
}
|
||||
/** How a taken name is settled: ask (409 EEXISTS with `names`), skip, keep both, replace. */
|
||||
export type FsConflict = "fail" | "skip" | "keep" | "replace";
|
||||
@@ -915,6 +945,24 @@ export const api = {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ...body, currentPassword }),
|
||||
}),
|
||||
/** GET /api/users/tmux — each member's own tmux server beside the installed version (S3). */
|
||||
tmux: () => request<MemberTmux>("/users/tmux"),
|
||||
/** POST /api/users/:id/tmux-restart — end that member's tmux server (every pane of theirs). */
|
||||
tmuxRestart: (id: number, currentPassword: string) =>
|
||||
request<{ user: AuthUser }>(`/users/${id}/tmux-restart`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ currentPassword }),
|
||||
}),
|
||||
/** POST /api/users/tmux-restart-idle — restart every outdated member server with no agent working. */
|
||||
tmuxRestartIdle: (currentPassword: string) =>
|
||||
request<{
|
||||
restarted: string[];
|
||||
skipped: string[];
|
||||
failed: { username: string; message: string }[];
|
||||
}>("/users/tmux-restart-idle", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ currentPassword }),
|
||||
}),
|
||||
/** GET /api/users/:id — one account and the workspaces it owns (admin/analyst). */
|
||||
get: (id: number) => request<UserDetail>(`/users/${id}`),
|
||||
/** PATCH /api/users/:id — profile, role, state, password, workspaces and
|
||||
@@ -2595,15 +2643,22 @@ export const api = {
|
||||
body: JSON.stringify({ paths }),
|
||||
}),
|
||||
trash: (t: FsPlace) => request<{ items: FsTrashItem[]; keepDays?: number }>(fsUrl(t, "/trash")),
|
||||
restore: (t: FsPlace, id: string) =>
|
||||
/** Every Trash the caller may open, merged (an admin: every user's). */
|
||||
allTrash: () =>
|
||||
request<{
|
||||
items: FsTrashItem[];
|
||||
errors?: { home: string; owner: string; message: string }[];
|
||||
keepDays?: number;
|
||||
}>("/homes/trash"),
|
||||
restore: (t: FsPlace, id: string, store?: FsTrashItem["store"]) =>
|
||||
request<{ path: string; laneId: number | null }>(fsUrl(t, "/trash/restore"), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ id }),
|
||||
body: JSON.stringify(store ? { id, store } : { id }),
|
||||
}),
|
||||
purge: (t: FsPlace, id: string | "all") =>
|
||||
purge: (t: FsPlace, id: string | "all", store?: FsTrashItem["store"]) =>
|
||||
request<{ purged: number }>(fsUrl(t, "/trash/purge"), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ id }),
|
||||
body: JSON.stringify(store ? { id, store } : { id }),
|
||||
}),
|
||||
/** A zip of `paths` (files and folders), for a plain link/anchor download. */
|
||||
zipUrl: (t: FsPlace, paths: string[]) => {
|
||||
@@ -4219,6 +4274,8 @@ export interface GitIdentity {
|
||||
sshUsers?: { host: string; user: string }[];
|
||||
/** The account's commit author (`git config --global`); null fields = unset. */
|
||||
author: { name: string | null; email: string | null };
|
||||
/** The suggested email while none is set: `<username>@smartgift.vn`. */
|
||||
defaultEmail?: string | null;
|
||||
https: {
|
||||
protocol: "http" | "https";
|
||||
host: string;
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
* an admin — add a user, and ONE Edit per row (`UserEditDialog`: profile,
|
||||
* role, active/disabled, password, owned workspaces, sign out everywhere, sent
|
||||
* as one change), and the Claude/Codex account pool every user's sessions run
|
||||
* on (`AccountPoolCard`). Every change asks for the admin's OWN password again (the
|
||||
* on (`AccountPoolCard`), and (one Linux user per account) each member's own
|
||||
* tmux server beside the installed version, restartable by an admin
|
||||
* (`MemberTmuxCard`). Every change asks for the admin's OWN password again (the
|
||||
* server refuses without it); an analyst only reads. A row shows the display
|
||||
* name and email under the username when set.
|
||||
* Laid out like the other list pages: icon header, a row of totals
|
||||
@@ -48,6 +50,7 @@ import { ConfirmModal } from "../components/ConfirmModal";
|
||||
import { StatCard } from "../components/StatCard";
|
||||
import { ROLE_BADGE, UserEditDialog } from "../components/users/UserEditDialog";
|
||||
import { AccountPoolCard } from "../components/users/AccountPoolCard";
|
||||
import { MemberTmuxCard } from "../components/users/MemberTmuxCard";
|
||||
import { TableRowSkeleton } from "../components/Skeleton";
|
||||
|
||||
type Role = AuthUser["role"];
|
||||
@@ -296,6 +299,7 @@ export function Users() {
|
||||
</div>
|
||||
|
||||
<AccountPoolCard isAdmin={isAdmin} />
|
||||
<MemberTmuxCard isAdmin={isAdmin} />
|
||||
|
||||
<section className="card">
|
||||
<div className="flex items-center gap-2 px-5 py-4 border-b border-border">
|
||||
|
||||
@@ -40,6 +40,8 @@ const users = vi.hoisted(() => ({
|
||||
setPassword: vi.fn(),
|
||||
assignWorkspace: vi.fn(),
|
||||
get: vi.fn(),
|
||||
// No S3 here: the members' tmux card stays hidden.
|
||||
tmux: vi.fn(async () => ({ available: false, users: [] })),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/api", async (importOriginal) => {
|
||||
|
||||
@@ -7178,7 +7178,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
<span
|
||||
class="text-status-warning/90"
|
||||
>
|
||||
UI build v2.8.3 (rebuild client to match)
|
||||
UI build v2.8.5 (rebuild client to match)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
+30
-5
@@ -85,7 +85,7 @@ A dashboard shared by several people runs in **server mode** ([SERVER-MODE.md](S
|
||||
| `POST /api/auth/login` `{username, password}` | `{user}` + the cookie; `401 EBADLOGIN`, `429 ETOOMANY`, `404 ENOTSERVER` in local mode |
|
||||
| `POST /api/auth/logout` | `{ok: true}`, cookie cleared |
|
||||
|
||||
In server mode a **developer** sees only rows of the workspaces they own (`lanes.owner_id`): every list, count, chart and cost answer is limited to them, and a request naming another user's session, agent, workspace or run (in the path, query or body) answers `404 ENOTFOUND`. Admin and analyst see everything; `GET /api/users` lists every account (`displayName`, `email`, `createdAt`, `logins`, `lastLoginAt` included) with its workspaces, sessions and 7/30-day `{cost, tokens}`, `GET /api/users/storage[?refresh=1]` each user's home size (`{storage: {<id>: {bytes, files, partial, measuredAt} | null}, measuring}` — measured in the background, see [SERVER-MODE.md](SERVER-MODE.md)), and `GET /api/users/audit[?limit=]` the staff reads of developers' sessions and admins' account changes (`reader`/`owner` are usernames, `reader_display`/`owner_display` their display names or null) (all `403 EADMIN` for a developer). See [SERVER-MODE.md](SERVER-MODE.md#what-each-user-sees).
|
||||
In server mode a **developer** sees only rows of the workspaces they own (`lanes.owner_id`): every list, count, chart and cost answer is limited to them, and a request naming another user's session, agent, workspace or run (in the path, query or body) answers `404 ENOTFOUND`. Admin and analyst see everything; `GET /api/users` lists every account (`displayName`, `email`, `createdAt`, `logins`, `lastLoginAt` included) with its workspaces, sessions and 7/30-day `{cost, tokens}`, `GET /api/users/storage[?refresh=1]` each user's home size (`{storage: {<id>: {bytes, files, partial, measuredAt} | null}, measuring}` — measured in the background, see [SERVER-MODE.md](SERVER-MODE.md)), `GET /api/users/tmux` each member's own tmux server under one Linux user per account (`{available, installed, matched, users: [{id, username, running, stuck?, version, pid, startedAt, sessions, busy, outdated}]}`; an admin's `POST /api/users/:id/tmux-restart` and `POST /api/users/tmux-restart-idle` restart them with `currentPassword`, audited, `409 ETMUXSTUCK` for a server that will not stop), and `GET /api/users/audit[?limit=]` the staff reads of developers' sessions and admins' account changes (`reader`/`owner` are usernames, `reader_display`/`owner_display` their display names or null) (all `403 EADMIN` for a developer). See [SERVER-MODE.md](SERVER-MODE.md#what-each-user-sees).
|
||||
|
||||
An admin changes accounts with `POST /api/users` (`{username, password, role}` → `201 {user}`), `GET /api/users/:id` (`{user, workspaces: [{id, title, cwd}]}`, the account with `logins` and `lastLoginAt`, for the Edit form; admin or analyst), `GET /api/users/:id/avatar` (that account's picture for the sidebar's owner groups — admin or analyst, `nosniff` + `sandbox` CSP, `404 ENOAVATAR`; a workspace in `GET /api/lanes` carries `owner_avatar_at` to version its URL), `PATCH /api/users/:id` (any of `{displayName?, email?, role?, disabled?, password?, addWorkspaces?: [laneId], removeWorkspaces?: [laneId], signOut?: true}` — every field validated before any is written; `removeWorkspaces` leaves the workspace with no owner and answers `409 ENOTOWNED` for one the user does not own; an admin's own `password`/`signOut` keeps the login it came from), `POST /api/users/:id/password` (`{password}`; that user's logins end) `POST /api/users/:id/workspaces` (`{laneId}`; the workspace's owner becomes that user) and `DELETE /api/users/:id` (delete for good: the user's logins, panes, workspaces' records, prefs and — under S3 — their Linux account and whole home, removed FIRST so a refusal (`502 EPROVISION`) leaves every row; `409 ESELF` for yourself, `409 ELASTADMIN` for the last admin; session history and the audit log stay). Every one carries `currentPassword`, the admin's own password: `403 EREAUTH` when it is wrong or missing, `429 ETOOMANY` after 10 wrong tries in 15 minutes. `409 ESELF` for an admin's own role or disable, `409 EEXISTS` for a taken name, `400 EBADUSER`/`EBADPASSWORD`/`EBADROLE`/`EBADEMAIL`/`EBADFIELD`, `404 ENOUSER`/`ENOLANE`; a developer or analyst gets `403 EADMIN`, and local mode `403 ELOCALMODE`. No answer carries a password hash; each change is written to the audit log.
|
||||
|
||||
@@ -292,7 +292,7 @@ come `fromLane` another workspace the caller can see, of the same account
|
||||
(`403 EFOREIGN` otherwise). An upload is at most 500 MB (`413 ETOOBIG`, from
|
||||
`Content-Length` before a byte is stored), a zip at most 2 GB / 50,000 files.
|
||||
Under S3 a move/copy/delete needs the installed `write-as` to know
|
||||
`move`/`copy`: `409 EUPGRADE` until `sudo agenthub server install-system` is
|
||||
`move`/`copy`: `409 EUPGRADE` until `agenthub server install-system` is
|
||||
re-run.
|
||||
|
||||
#### File Explorer on a home
|
||||
@@ -311,7 +311,32 @@ the host account's home. Every dot entry at the TOP of a home (`.ssh`,
|
||||
refused for every read and write — also through a symlink, a download or a
|
||||
zip (`403 ESECRET`); dot files deeper down are ordinary. `:who` is `me`; an
|
||||
admin may also name another user — read-only (`403 EREADONLY` on every
|
||||
write), each read written to the audit log. A copy goes home ↔ workspace
|
||||
write), each read written to the audit log. The one exception is that user's
|
||||
**Trash**.
|
||||
|
||||
A home's Trash is its USER's one recycle bin, whatever place they deleted in:
|
||||
`GET …/trash` merges their home account's trash (a member's
|
||||
`~/.local/share/agenthub/trash/`) with their host trash
|
||||
(`<data dir>/trash/<user id>/`, what they deleted in a host-folder workspace)
|
||||
and tags each item `store: "home" | "host"`; `POST …/trash/restore` and
|
||||
`POST …/trash/purge` take `{id, store}` (`store` defaults to `home`;
|
||||
`{id: "all"}` empties every store). A host item whose workspace is gone
|
||||
answers `404 ENOFILE` (nowhere of that account to put it back). An admin may
|
||||
restore and purge in ANOTHER user's Trash too, each written to the audit log
|
||||
with the item id — so a member's deleted files can be restored or freed
|
||||
without waiting the 7 days. `GET /api/homes/trash` merges every Trash the
|
||||
caller may open into one list (`{items, errors, keepDays}`; an admin's is
|
||||
every user's, each other user's read audited): each item carries `home` (the
|
||||
`:who` its restore/purge goes to) and `owner`, and a user whose trash cannot
|
||||
be read is listed in `errors` rather than left out. The Files sidebar has ONE
|
||||
**Trash** entry: a user's opens their own Trash; an admin's opens on one
|
||||
folder per user (**My Trash** first, each counted from that merged list, an
|
||||
unreadable one showing its error), and opening a folder shows that user's
|
||||
Trash (path bar **Trash › user**, Up goes back to the folders). A trash that
|
||||
could not be read shows as an error rather than as empty, and deleting
|
||||
forever asks first.
|
||||
|
||||
A copy goes home ↔ workspace
|
||||
(`fromHome` on the workspace route, `fromLane` on the home one) when both are
|
||||
one Linux account; each side is checked under its own rule. A home is never a
|
||||
workspace. The **Files** page opens on `?home=me` by default.
|
||||
@@ -1042,7 +1067,7 @@ cannot collide on `index.lock`.
|
||||
#### Your git identity
|
||||
|
||||
```
|
||||
GET /api/me/git { account: "member"|"host", writable, ssh: { type, publicKey, fingerprint, terminal: "on"|"off"|"foreign" } | null (the first key), sshKeys: [{ type, publicKey, fingerprint }] (ed25519 first), sshTerminal, https: [{ protocol, host, username, hasToken }] }
|
||||
GET /api/me/git { account: "member"|"host", writable, ssh: { type, publicKey, fingerprint, terminal: "on"|"off"|"foreign" } | null (the first key), sshKeys: [{ type, publicKey, fingerprint }] (ed25519 first), sshTerminal, https: [{ protocol, host, username, hasToken }], author: { name, email }, defaultEmail }
|
||||
POST /api/me/git/ssh-key Make the SSH key of `type` — Body: { replace?, type?: "ed25519" | "rsa" } (409 EEXISTS when that TYPE exists, without replace; the other type is kept — an account may hold one of each, and every ssh git offers both) → 201, same shape
|
||||
DELETE /api/me/git/ssh-key Delete the key of `?type=ed25519|rsa`, or every key without it (404 ENOTFOUND, 400 EBADKEYTYPE) — also removes our terminal `core.sshCommand`
|
||||
PUT /api/me/git/ssh-terminal Use the key for git typed in the account's own terminal — Body: { on } — sets/unsets `core.sshCommand` in its `~/.gitconfig` (ours first, then `~/.ssh/id_*`); on by default when a member makes a key; 409 EFOREIGNSSH over one the user wrote, which is never touched
|
||||
@@ -1050,7 +1075,7 @@ PUT /api/me/git/ssh-user The SSH login name for one host — Body: { h
|
||||
DELETE /api/me/git/ssh-user/:host Drop that rule (404 ENOTFOUND); any other `insteadOf` the user wrote is never touched
|
||||
POST /api/me/git/https Save an https login — Body: { host, username, password }
|
||||
DELETE /api/me/git/https/:host Delete one (404 ENOTFOUND)
|
||||
PUT /api/me/git/author Commit author — Body: { name, email } (400 EBADAUTHOR) — `git config --global user.name/email` as the account
|
||||
PUT /api/me/git/author Commit author — Body: { name, email } (400 EBADAUTHOR) — `git config --global user.name/email` as the account. A new SSH key is labelled with that email, else `defaultEmail` (`<username>@smartgift.vn`; `AGENTHUB_EMAIL_DOMAIN` overrides the domain), also returned by GET /api/me/git as the email form's suggestion
|
||||
```
|
||||
|
||||
`GET` also answers `author: { name, email }` (null when unset). A member's
|
||||
|
||||
+1
-1
@@ -104,7 +104,7 @@ The CLI talks to the local dashboard server — **API-backed commands require it
|
||||
| `agenthub uninstall [--yes]` | **Uninstall AgentHub** (`scripts/uninstall.js`; Settings → System has the same button). Without `--yes` it only lists what is there and exits 1. With it, in order: closes every workspace terminal, removes the systemd/launchd unit, stops every dashboard server, the status-area icon and workspace stacks, takes AgentHub's own entries out of `~/.claude/settings.json` (hooks, statusline; backup `settings.json.agenthub-uninstall.bak`), Codex `hooks.json` and Antigravity `hooks.json`, deletes the AI Proxy `$CODEX_HOME/<name>.config.toml` files, runs `claude plugin uninstall` for `agenthub@*` and every plugin of the `agenthub` marketplace and removes that marketplace (never a shared one), then deletes `~/.local/bin/agenthub`, `~/.config/agenthub/`, `~/.claude/.agenthub.json`, `~/.claude/agenthub-{proxies,routers,git-credentials,accounts,profiles}`, `agenthub-lanes/.state` and `.locks`, the plugin's cached copies and the data directory (database included). **Kept:** the AI tools' own conversations (`~/.claude/projects`, `~/.codex/sessions`, …), workspace worktrees and branches, anything in your repositories, config backups. A data directory that is the home, `CLAUDE_HOME`, a checkout or not recognisably AgentHub's is refused. A failing step is logged and the rest still run; log: `$TMPDIR/agenthub-uninstall-<uid>.log`. Needs no running server. Run inside a dashboard terminal, it closes that terminal last. |
|
||||
| `agenthub tray` | Show AgentHub's **status-area icon** now, in the foreground (`scripts/tray.js`): Open AgentHub, Quit AgentHub (a submenu asks again, then runs `agenthub stop`), Start AgentHub after a quit (`agenthub start`), Hide this icon. A production server already keeps the icon up on its own unless Settings → System turned it off; this command does not change that setting. Exits at once when an icon is already running |
|
||||
| `agenthub repl` (aliases `shell`, `i`) | Open the **interactive shell** — see [Interactive REPL](#interactive-repl) |
|
||||
| `agenthub server setup [--hostname name] [--admin name]` | Turn **server mode** on (logins for a shared dashboard): writes `AGENTHUB_MODE=server` (and `DASHBOARD_ALLOWED_HOSTS`) to the settings file and creates the first admin, asking for its password. Works with the server down; restart it afterwards. See [SERVER-MODE.md](SERVER-MODE.md) |
|
||||
| `agenthub server setup [--hostname name] [--admin name] [--no-system]` | Turn **server mode** on (logins for a shared dashboard): writes `AGENTHUB_MODE=server` (and `DASHBOARD_ALLOWED_HOSTS`) to the settings file and creates the first admin, asking for its password. On Linux it then installs **one Linux user per account** by default — runs `install-system` (one sudo; skipped when `/etc/agenthub/server.conf` already exists) and `users provision --all`; if that fails, server mode stays on and the error says how to finish. `--no-system` (and any non-Linux machine) keeps every pane on the one host account, as before; then restart the dashboard yourself. See [SERVER-MODE.md](SERVER-MODE.md) |
|
||||
| `agenthub server install-system [--dry-run\|--uninstall]` | **One Linux user per account** (S3). Run as the account that runs the dashboard, never as root: it runs `scripts/server/install-system.sh` through one `sudo`. That script creates the groups, `/srv/agenthub/users`, `/opt/agenthub`, the sudoers file, the member hooks and `hidepid`, and installs the system unit `agenthub.service`. The command then points the unit at this install, writes `AGENTHUB_USERS_ROOT`, and moves the dashboard from the `systemd --user` unit to the system one (panes stay). `--dry-run` prints the sudo command; `--uninstall` goes back to the user unit. See [SERVER-MODE.md](SERVER-MODE.md#one-linux-user-per-account) |
|
||||
| `agenthub server tools` | One Linux user per account: publish this install's scripts and every installed AI tool under `/opt/agenthub` (`tools/bin/<command>`), where every account's pane runs them. The server also does this at start and after each install or update. Prints each tool's shared copy, or why it could not be shared |
|
||||
| `agenthub server off` / `agenthub server status` | Back to local mode (accounts kept) / show the mode and account count |
|
||||
|
||||
+54
-20
@@ -15,8 +15,9 @@ Local mode does not change at all. The login code stays dormant until
|
||||
> **What server mode separates, and what it does not.** In the dashboard and
|
||||
> its API, each developer sees only their own workspaces and the sessions,
|
||||
> prompts, events, tokens and cost under them (see [What each user sees](#what-each-user-sees)).
|
||||
> Until [one Linux user per account](#one-linux-user-per-account) is installed
|
||||
> (`agenthub server install-system`), every terminal pane runs as the one Linux
|
||||
> On Linux, `agenthub server setup` installs [one Linux user per account](#one-linux-user-per-account)
|
||||
> by default. Without it (`--no-system`, a machine that is not Linux, or an
|
||||
> install that failed), every terminal pane runs as the one Linux
|
||||
> account that runs the dashboard. An agent in a pane can then read every
|
||||
> user's folders, transcripts and the database straight from disk. Without it,
|
||||
> use server mode only with people you trust.
|
||||
@@ -27,12 +28,14 @@ On the machine that will host the dashboard, logged in as the account that
|
||||
runs it:
|
||||
|
||||
```bash
|
||||
# 1. Turn server mode on, allow the public name, and create the first admin
|
||||
# 1. Turn server mode on, allow the public name, create the first admin and,
|
||||
# on Linux, install one Linux user per account (one sudo; it moves the
|
||||
# dashboard to the system unit agenthub.service, which picks the mode up)
|
||||
agenthub server setup --hostname agenthub.example.com --admin boss
|
||||
# (asks for the admin's password twice; from a script: pipe it on stdin)
|
||||
|
||||
# 2. Restart the dashboard so it picks the mode up
|
||||
systemctl --user restart agenthub # or: agenthub start
|
||||
# 2. Log out and back in once, so your shell joins the agenthub groups
|
||||
# (with --no-system instead: systemctl --user restart agenthub)
|
||||
|
||||
# 3. Add the other people
|
||||
agenthub users add alice # developer
|
||||
@@ -42,7 +45,14 @@ agenthub users add carol --role analyst # reads everyone, works in their o
|
||||
`setup` writes `AGENTHUB_MODE=server` and `DASHBOARD_ALLOWED_HOSTS` into
|
||||
AgentHub's settings file (`~/.config/agenthub/settings.env`). The real
|
||||
environment and a checkout's `.env` still take priority over that file. Run
|
||||
setup again whenever you need to: it creates an admin only when none exists.
|
||||
setup again whenever you need to: it creates an admin only when none exists,
|
||||
runs `install-system` only while `/etc/agenthub/server.conf` is missing, and
|
||||
gives every user their Linux account (`users provision --all`, idempotent).
|
||||
The machine needs what [What a new machine needs](#what-a-new-machine-needs-before-install-system)
|
||||
lists first. If the install fails, server mode stays on with every pane on the
|
||||
host account, and the error says so: fix the cause and run
|
||||
`agenthub server install-system`, or choose that shared account on purpose
|
||||
with `agenthub server setup --no-system`.
|
||||
|
||||
## Put HTTPS in front of it
|
||||
|
||||
@@ -544,9 +554,9 @@ The pieces, and what each is for (the install steps are in the
|
||||
| `ah-<name>` | Made by `agenthub-provision`, not by the installer. One Linux user per AgentHub user, home `/srv/agenthub/users/<name>` (`0750`, group `agenthub`): the member owns it, the dashboard reads it, nobody else gets in. `.agenthub/{tmux,handoff}` (0700) is made by the member: their tmux socket, and the files the dashboard writes for their panes (as them) |
|
||||
| groups | `agenthub` (reads member homes: the host account), `agenthub-members` (every `ah-*` account), `agenthub-proc` (sees every process: the host account, `polkitd`) |
|
||||
| `agenthub.service` | A SYSTEM unit, `User=<host>`, with `SupplementaryGroups=agenthub agenthub-proc` and `AmbientCapabilities=CAP_DAC_READ_SEARCH`: the dashboard can read every member's tool files (Claude writes transcripts `0600`), but cannot write them. Every program it starts has the capability removed first (`setpriv`), so host panes, git and npm do not inherit it. It reads node and the plugin root from `<data dir>/runtime/agenthub.system.env`, a file the host owns, so a plugin update repoints it without root |
|
||||
| `/etc/sudoers.d/agenthub` | The host may run only `tmux`, `git`, `gh` (by the absolute paths recorded in `/etc/agenthub/server.conf`), `/opt/agenthub/libexec/write-as` and `/opt/agenthub/tools/bin/claude` (the [plugin baseline](#plugin-baseline-opt-in)) AS a member, plus, as root, only `/opt/agenthub/sbin/agenthub-provision` and `systemctl start/stop/restart/enable/disable agenthub.service`. Members are never in sudoers |
|
||||
| `/etc/sudoers.d/agenthub` | The host may run only `tmux`, `git`, `gh` (by the absolute paths recorded in `/etc/agenthub/server.conf`), `/opt/agenthub/libexec/tmux-member`, `/opt/agenthub/libexec/write-as` and `/opt/agenthub/tools/bin/claude` (the [plugin baseline](#plugin-baseline-opt-in)) AS a member, plus, as root, only `/opt/agenthub/sbin/agenthub-provision` and `systemctl start/stop/restart/enable/disable agenthub.service`. Members are never in sudoers |
|
||||
| `/etc/agenthub/server.conf` | Root's, `0644`: the host account and uid, the users root, the port, and the `tmux`/`git`/`gh` paths sudoers lists. Its presence turns S3 on |
|
||||
| `write-as`, `pane-launch` | `/opt/agenthub/libexec/`, root's. `write-as <path> [append\|replace\|private\|mkdir\|remove]` runs AS a member and does the one change, content on stdin. `pane-launch <file>` starts a member's pane from its launch file |
|
||||
| `write-as`, `pane-launch`, `tmux-member` | `/opt/agenthub/libexec/`, root's. `tmux-member -S <socket> …` runs a member's tmux call with their running server's own binary (else `TMUX_BIN`). `write-as <path> [append\|replace\|private\|mkdir\|remove]` runs AS a member and does the one change, content on stdin. `pane-launch <file>` starts a member's pane from its launch file |
|
||||
| `agenthub-provision` | The one root command besides `systemctl` on this unit: `create`, `disable` or `enable` `ah-<name>`. It refuses an account that exists outside `agenthub-members` and never deletes anything |
|
||||
| `/etc/claude-code/managed-settings.json` | Members' Claude Code hooks, through `/opt/agenthub/libexec/member-hook`, which does nothing for the host account (its plugin reports). A foreign file there is left alone |
|
||||
| `hidepid=invisible` | `/proc` (now and in `/etc/fstab`): an account sees only its own processes, so no member can read another's command line. A token passed with `tmux -e` is in one |
|
||||
@@ -682,9 +692,22 @@ a pane really is. Each case below is refused or bounded, with a test in
|
||||
running host server uses that server's own binary (`/proc/<pid>/exe`, found
|
||||
from its socket in `/proc`), so installing a newer tmux under a running
|
||||
server no longer mixes versions: a 3.8 client asking a 3.6 server kept it at
|
||||
100% CPU. A member's server is still asked with `TMUX_BIN` (the one path
|
||||
sudoers allows), so after a tmux upgrade restart each member's tmux server
|
||||
once it is idle (`sudo kill <pid>` of `tmux -S /srv/agenthub/users/<name>/.agenthub/tmux/sock`).
|
||||
100% CPU.
|
||||
- **A member's tmux across a tmux upgrade.** Every tmux call AS a member goes
|
||||
through `/opt/agenthub/libexec/tmux-member` (root's, in sudoers): it runs
|
||||
the call with the binary of the member's running server (`/proc/<pid>/exe`,
|
||||
found from their socket), else with `TMUX_BIN`, so a newer tmux never asks
|
||||
an older server. Until `agenthub server install-system` has installed
|
||||
it, calls use `TMUX_BIN` directly, as before. A member's server keeps its
|
||||
version until their last pane closes; the next start runs `TMUX_BIN`.
|
||||
- **Users → Members' tmux** (admin/analyst read, admin acts): each member's
|
||||
running server with its version beside the installed one (an *older than
|
||||
installed* badge), its sessions and whether an agent of theirs is working.
|
||||
**Restart** ends one member's server — every pane of theirs closes, their
|
||||
Claude sessions resume from the workspace — and **Restart N idle members**
|
||||
does it for every outdated member with no agent working; both take the
|
||||
admin's password again and are audited per member. A server that will not
|
||||
stop answers `409 ETMUXSTUCK` naming its pid: root has to `kill -9` it.
|
||||
- **A member's huge or sparse files.** Transcripts and journals are read line
|
||||
by line with a 64 MiB cap per line (a 512 MB line used to crash the server);
|
||||
a whole member file is read only up to a cap (1 MiB for a login or a
|
||||
@@ -746,15 +769,25 @@ itself, once.
|
||||
|
||||
### After an update that changes the member helpers
|
||||
|
||||
`write-as`, `pane-launch` and the sudoers file are copied to
|
||||
`write-as`, `pane-launch`, `tmux-member` and the sudoers file are copied to
|
||||
`/opt/agenthub/libexec` by `install-system` only — an update of AgentHub does
|
||||
not touch root-owned files. When a release changes them (v2.7.7: `write-as`
|
||||
learned `move`/`copy` for the File Explorer), re-run it once:
|
||||
learned `move`/`copy` for the File Explorer; v2.8.4 added `tmux-member`),
|
||||
re-run it once, as the host account and **without** `sudo` in front (it asks
|
||||
for the sudo password itself; as root it refuses, and `sudo agenthub …` fails
|
||||
with `command not found` because sudo's `secure_path` has no `~/.local/bin`):
|
||||
|
||||
```bash
|
||||
sudo agenthub server install-system
|
||||
agenthub server install-system
|
||||
```
|
||||
|
||||
A member server that a newer tmux already reached before `tmux-member` was
|
||||
installed can stay wedged: every call on that socket — `tmux-member`'s too —
|
||||
prints `server exited unexpectedly`. If Users → Members' tmux shows it with
|
||||
no panes, stop that one server (its pid is the `ah-<name>` process running
|
||||
`tmux -S <USERS_ROOT>/<name>/.agenthub/tmux/sock`) with `sudo kill -9 <pid>`;
|
||||
the next start runs a fresh server on `TMUX_BIN`. Never `tmux kill-server`.
|
||||
|
||||
Until then the File Explorer's move, copy and delete in a member's folder
|
||||
answer `409 EUPGRADE` (listing, upload, new folder/file and zip work).
|
||||
The same re-run installs `agenthub-provision delete`, behind the Users page's
|
||||
@@ -789,9 +822,10 @@ again under the same name gets a NEW, empty Linux account and home.
|
||||
4. AgentHub installed for the host account, as the plugin or a checkout
|
||||
(`npm run setup && npm run build`), and running once
|
||||
(`agenthub start`).
|
||||
5. Server mode on, with the first admin:
|
||||
`agenthub server setup --hostname agenthub.example.com --admin boss`
|
||||
(see [Set it up](#set-it-up)).
|
||||
5. Server mode itself is NOT a step before this: `agenthub server setup`
|
||||
(see [Set it up](#set-it-up)) turns it on and then runs `install-system`
|
||||
and `users provision --all` below itself. Run the Install steps by hand only
|
||||
after a `setup --no-system` or a failed install, or to repeat one.
|
||||
6. The AI tools members will use, installed for the host account (the AI
|
||||
Tools page or by hand).
|
||||
7. The HTTPS reverse proxy (see [Put HTTPS in front of it](#put-https-in-front-of-it)).
|
||||
@@ -821,7 +855,7 @@ again changes nothing that is already in place):
|
||||
host account's);
|
||||
3. writes `/etc/agenthub/server.conf` (`HOST_USER`, `HOST_UID`,
|
||||
`USERS_ROOT`, `PORT`, `TMUX_BIN`, `GIT_BIN`, `GH_BIN`);
|
||||
4. installs `agenthub-provision`, `write-as` and `pane-launch` from
|
||||
4. installs `agenthub-provision`, `write-as`, `pane-launch` and `tmux-member` from
|
||||
`scripts/server/`;
|
||||
5. copies node to `/opt/agenthub/tools/node/<version>` (linked from
|
||||
`tools/bin/node`) and this install's `scripts/` and `server/lib/` to
|
||||
@@ -846,8 +880,8 @@ again changes nothing that is already in place):
|
||||
|
||||
What a new machine still needs by hand after it:
|
||||
|
||||
1. `agenthub users provision --all`: users created before S3 was on (the
|
||||
admin from `server setup` is one) have no Linux account yet.
|
||||
1. `agenthub users provision --all`: users created before S3 was on have no
|
||||
Linux account yet (`server setup` already ran this for you).
|
||||
2. Log out and back in once, so your own shell joins `agenthub` and
|
||||
`agenthub-proc` (the unit gets them on its own).
|
||||
3. `chmod o-rwx ~` for the host account if the installer warned: the database
|
||||
|
||||
@@ -112,7 +112,7 @@ Branch: `server-s3`. Commits happen only when the user asks.
|
||||
- Verify: an e2e against a fake upstream (header swapped, streaming kept, a dead pane's token refused, another member's profile refused).
|
||||
|
||||
### P2. Host setup (sudo; on this machine with the agh-test users)
|
||||
- [x] `sudo agenthub server install-system` is idempotent, has `--uninstall`, and does the following:
|
||||
- [x] `agenthub server install-system` is idempotent, has `--uninstall`, and does the following:
|
||||
- creates groups `agenthub` and `agenthub-members`;
|
||||
- creates `/srv/agenthub/users` (0751) and `/opt/agenthub/{tools,app,libexec,sbin}`;
|
||||
- writes the sudoers file and checks it with `visudo -c`;
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.8.3",
|
||||
"version": "2.8.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "agenthub",
|
||||
"version": "2.8.3",
|
||||
"version": "2.8.5",
|
||||
"hasInstallScript": true,
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.8.3",
|
||||
"version": "2.8.5",
|
||||
"bin": {
|
||||
"agenthub": "bin/agenthub.js"
|
||||
},
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
# /opt/agenthub/libexec/member-hook Claude hook forwarder for members
|
||||
# /opt/agenthub/libexec/write-as writes in a member's home AS the member (sudo -u)
|
||||
# /opt/agenthub/libexec/pane-launch starts a member's pane from its launch file
|
||||
# /opt/agenthub/libexec/tmux-member a member's tmux, with their running server's own binary
|
||||
# /etc/sudoers.d/agenthub checked with visudo before it is installed
|
||||
# /etc/claude-code/managed-settings.json the member hooks (never over a foreign file)
|
||||
# /proc hidepid=invisible,gid=agenthub-proc (now and in /etc/fstab)
|
||||
@@ -105,6 +106,7 @@ chmod 0644 /etc/agenthub/server.conf
|
||||
install -m 0755 -o root -g root "$ROOT/scripts/server/agenthub-provision.sh" /opt/agenthub/sbin/agenthub-provision
|
||||
install -m 0755 -o root -g root "$ROOT/scripts/server/write-as.sh" /opt/agenthub/libexec/write-as
|
||||
install -m 0755 -o root -g root "$ROOT/scripts/server/pane-launch.sh" /opt/agenthub/libexec/pane-launch
|
||||
install -m 0755 -o root -g root "$ROOT/scripts/server/tmux-member.sh" /opt/agenthub/libexec/tmux-member
|
||||
|
||||
# ── node + the hook handler, for members (host-owned: the dashboard refreshes them) ──
|
||||
NODE_VER=$("$NODE" -p process.version)
|
||||
@@ -138,7 +140,7 @@ visudo -cf "$TMP_SUDOERS" >/dev/null 2>&1 && NOTTY="Defaults:$HOST !requiretty"
|
||||
{
|
||||
echo "# AgentHub server mode (install-system). Members are never in sudoers."
|
||||
[ -z "$NOTTY" ] || echo "$NOTTY"
|
||||
echo "$HOST ALL=(%agenthub-members) NOPASSWD:SETENV: $TMUX_BIN, $GIT_BIN${GH_BIN:+, $GH_BIN}, /opt/agenthub/libexec/write-as, /opt/agenthub/tools/bin/claude"
|
||||
echo "$HOST ALL=(%agenthub-members) NOPASSWD:SETENV: $TMUX_BIN, /opt/agenthub/libexec/tmux-member, $GIT_BIN${GH_BIN:+, $GH_BIN}, /opt/agenthub/libexec/write-as, /opt/agenthub/tools/bin/claude"
|
||||
echo "$HOST ALL=(root) NOPASSWD: /opt/agenthub/sbin/agenthub-provision"
|
||||
for a in start stop restart enable disable; do
|
||||
[ "$a" = start ] || [ "$a" = stop ] || [ "$a" = restart ] && extra=" --no-block" || extra=""
|
||||
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
# @file tmux-member.sh
|
||||
# @description Server mode, one Linux user per account (S3): installed as
|
||||
# /opt/agenthub/libexec/tmux-member, the one tmux the host may run AS a
|
||||
# member (sudoers). Called as `tmux-member -S <socket> <tmux args…>`, it runs
|
||||
# the args with the binary of the tmux server already listening on that
|
||||
# socket (`/proc/<pid>/exe`, which still runs after an upgrade replaced the
|
||||
# file), else with TMUX_BIN from /etc/agenthub/server.conf (no server yet:
|
||||
# this call starts one, on the installed version). A client must match its
|
||||
# server: a tmux 3.8 client asking a 3.6 server kept it at 100% CPU.
|
||||
#
|
||||
# It runs as the member and execs only a process THEY own (under hidepid they
|
||||
# see no other), so it can run nothing they could not run themselves.
|
||||
# @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
set -u
|
||||
bin=$(sed -n 's/^TMUX_BIN=//p' /etc/agenthub/server.conf 2>/dev/null | head -n 1)
|
||||
[[ "$bin" == /* ]] || { echo "tmux-member: no TMUX_BIN in /etc/agenthub/server.conf" >&2; exit 2; }
|
||||
if [ "${1:-}" = -S ] && [ -n "${2:-}" ]; then
|
||||
# /proc/net/unix: Num RefCount Protocol Flags Type St Inode Path; 00010000 = listening.
|
||||
inode=$(awk -v s="$2" '$4 == "00010000" && $8 == s { print $7; exit }' /proc/net/unix 2>/dev/null)
|
||||
if [ -n "$inode" ]; then
|
||||
for d in /proc/[0-9]*; do
|
||||
[ -O "$d" ] || continue
|
||||
read -r comm <"$d/comm" 2>/dev/null || continue
|
||||
[[ "$comm" == tmux* ]] || continue
|
||||
for fd in "$d"/fd/*; do
|
||||
if [ "$(readlink "$fd" 2>/dev/null)" = "socket:[$inode]" ] && [ -x "$d/exe" ]; then
|
||||
exec "$d/exe" "$@"
|
||||
fi
|
||||
done
|
||||
done
|
||||
fi
|
||||
fi
|
||||
exec "$bin" "$@"
|
||||
@@ -6,7 +6,7 @@
|
||||
* a systemd `--user` unit everywhere else (`systemd-service.js`, which reports
|
||||
* itself unavailable off Linux). Both export the same API — and so does the
|
||||
* third, `systemd-system-service.js`, chosen while the server-mode SYSTEM unit
|
||||
* `sudo agenthub server install-system` wrote exists (pure fs check).
|
||||
* `agenthub server install-system` wrote exists (pure fs check).
|
||||
* Require THIS module, never one of the three directly.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* @file systemd-system-service.js
|
||||
* @description Server mode with one Linux user per account (S3): the dashboard
|
||||
* runs as a SYSTEM unit, `/etc/systemd/system/agenthub.service`, written once
|
||||
* by `sudo agenthub server install-system` (scripts/server/install-system.sh).
|
||||
* by `agenthub server install-system` (scripts/server/install-system.sh).
|
||||
* The unit runs as the host account with group `agenthub` and
|
||||
* CAP_DAC_READ_SEARCH — the two things a `systemd --user` unit cannot give.
|
||||
*
|
||||
@@ -162,7 +162,7 @@ function installUserService(opts) {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Removing the system unit is root's: `sudo agenthub server install-system --uninstall`. */
|
||||
/** Removing the system unit is root's: `agenthub server install-system --uninstall`. */
|
||||
function uninstallUserService() {
|
||||
return "foreign";
|
||||
}
|
||||
|
||||
@@ -246,6 +246,8 @@ describe("/api/me/git", () => {
|
||||
const made = await request("POST", "/api/me/git/ssh-key", {});
|
||||
assert.equal(made.status, 201);
|
||||
assert.match(made.body.ssh.publicKey, /^ssh-ed25519 /);
|
||||
// No commit author yet: the key is labelled with the default email.
|
||||
assert.match(made.body.ssh.publicKey, /@smartgift\.vn$/);
|
||||
assert.match(made.body.ssh.fingerprint, /^SHA256:/);
|
||||
assert.ok(!JSON.stringify(made.body).includes("PRIVATE"));
|
||||
const key = path.join(ROOT, ".claude", "agenthub-ssh", "id_ed25519");
|
||||
@@ -311,6 +313,7 @@ describe("/api/me/git", () => {
|
||||
it("reads and sets the commit author, refusing a bad one", async () => {
|
||||
const r0 = await request("GET", "/api/me/git");
|
||||
assert.deepEqual(r0.body.author, { name: null, email: null });
|
||||
assert.equal(r0.body.defaultEmail, `${os.userInfo().username}@smartgift.vn`);
|
||||
const bad = await request("PUT", "/api/me/git/author", { name: "a\nb", email: "x@y" });
|
||||
assert.equal(bad.status, 400);
|
||||
assert.equal(bad.body.error.code, "EBADAUTHOR");
|
||||
@@ -318,6 +321,10 @@ describe("/api/me/git", () => {
|
||||
assert.equal(ok.status, 200);
|
||||
assert.deepEqual(ok.body.author, { name: "Vi", email: "vi@example.com" });
|
||||
assert.match(fs.readFileSync(path.join(ROOT, ".gitconfig"), "utf8"), /email = vi@example.com/);
|
||||
// A key made now is labelled with the author's email.
|
||||
const key = await request("POST", "/api/me/git/ssh-key", { replace: true });
|
||||
assert.match(key.body.ssh.publicKey, / vi@example\.com$/);
|
||||
await request("DELETE", "/api/me/git/ssh-key");
|
||||
});
|
||||
|
||||
it("saves an https login without ever returning the token", async () => {
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* (also through a symlink, a download or a zip) while a nested dotfile is
|
||||
* fine, delete/restore work with no workspace, a copy goes home ↔ workspace
|
||||
* under each side's own rule — and in server mode a developer never reaches
|
||||
* another user's home while an admin gets it read-only.
|
||||
* another user's home while an admin gets it read-only — except its Trash,
|
||||
* which the admin lists, restores from and purges as the member's own.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -204,3 +205,143 @@ describe("homes in server mode", () => {
|
||||
assert.ok(homes.listHomes({ user: ann }).some((x) => x.id === "bob" && x.readOnly));
|
||||
});
|
||||
});
|
||||
|
||||
describe("an admin manages a member's Trash", () => {
|
||||
const auth = require("../lib/auth");
|
||||
const USERS = path.join(ROOT, "users");
|
||||
let cara;
|
||||
let dan;
|
||||
const call = (method, p, cookie, body) =>
|
||||
fetch(`${base}${p}`, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json", cookie },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
}).then(async (r) => ({ status: r.status, body: await r.json().catch(() => null) }));
|
||||
const login = async (username, password) => {
|
||||
const r = await fetch(`${base}/api/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
return r.headers.get("set-cookie").split(";")[0];
|
||||
};
|
||||
before(async () => {
|
||||
fs.mkdirSync(path.join(USERS, "cara"), { recursive: true });
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
process.env.AGENTHUB_USERS_ROOT = USERS;
|
||||
await auth.createUser("cara", "cara-pass-1", "developer");
|
||||
await auth.createUser("dan", "dan-pass-1", "admin");
|
||||
cara = await login("cara", "cara-pass-1");
|
||||
dan = await login("dan", "dan-pass-1");
|
||||
});
|
||||
after(() => {
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
delete process.env.AGENTHUB_USERS_ROOT;
|
||||
});
|
||||
|
||||
it("lists, restores and purges the member's own trash — the rest stays read-only", async () => {
|
||||
const C = "/api/homes/me/fs";
|
||||
const D = "/api/homes/cara/fs";
|
||||
for (const n of ["old", "junk"]) {
|
||||
assert.equal((await call("POST", `${C}/mkdir`, cara, { path: n })).status, 201);
|
||||
}
|
||||
assert.equal((await call("POST", `${C}/delete`, cara, { paths: ["old", "junk"] })).status, 200);
|
||||
|
||||
// The admin sees CARA's trash, not their own.
|
||||
let items = (await call("GET", `${D}/trash`, dan)).body.items;
|
||||
assert.deepEqual(items.map((i) => i.name).sort(), ["junk", "old"]);
|
||||
assert.equal((await call("GET", "/api/homes/me/fs/trash", dan)).body?.items?.length ?? 0, 0);
|
||||
|
||||
// …and every user's in one list, each item tagged with its home and owner.
|
||||
const all = (await call("GET", "/api/homes/trash", dan)).body;
|
||||
assert.deepEqual(
|
||||
all.items.map((i) => [i.name, i.home, i.owner]).sort(),
|
||||
[
|
||||
["junk", "cara", "cara"],
|
||||
["old", "cara", "cara"],
|
||||
]
|
||||
);
|
||||
// A developer's merged view is only their own.
|
||||
assert.deepEqual(
|
||||
(await call("GET", "/api/homes/trash", cara)).body.items.map((i) => i.home),
|
||||
["me", "me"]
|
||||
);
|
||||
const old = items.find((i) => i.name === "old");
|
||||
const r = await call("POST", `${D}/trash/restore`, dan, { id: old.id });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.ok(fs.statSync(path.join(USERS, "cara", "old")).isDirectory());
|
||||
|
||||
assert.equal((await call("POST", `${D}/trash/purge`, dan, { id: "all" })).body.purged, 1);
|
||||
assert.equal((await call("GET", `${C}/trash`, cara)).body.items.length, 0);
|
||||
|
||||
// Everything else in another user's home is still refused.
|
||||
const w = await call("POST", `${D}/mkdir`, dan, { path: "nope" });
|
||||
assert.equal(w.status, 403);
|
||||
assert.equal(w.body.error.code, "EREADONLY");
|
||||
assert.equal((await call("POST", `${D}/delete`, dan, { paths: ["old"] })).status, 403);
|
||||
|
||||
// A developer still never reaches another user's trash.
|
||||
assert.equal((await call("GET", "/api/homes/dan/fs/trash", cara)).status, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("one recycle bin per user", () => {
|
||||
const fx = require("../lib/file-explorer");
|
||||
const runAs = require("../lib/run-as");
|
||||
const MEMBER = path.join(ROOT, "member-home");
|
||||
const put = (root, id, name, laneId) => {
|
||||
fs.mkdirSync(path.join(root, id, "item"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(root, id, "meta.json"),
|
||||
JSON.stringify({
|
||||
id,
|
||||
name,
|
||||
laneId,
|
||||
rel: name,
|
||||
isDir: true,
|
||||
deletedAt: new Date().toISOString(),
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
it("has one store when the home is the host's", async () => {
|
||||
const out = await fx.listUserTrash(HOME, "solo");
|
||||
assert.deepEqual(out.items, []);
|
||||
put(path.join(process.env.DASHBOARD_DATA_DIR, "trash", "solo"), "solo0001", "x", null);
|
||||
const items = (await fx.listUserTrash(HOME, "solo")).items;
|
||||
assert.deepEqual(
|
||||
items.map((i) => [i.name, i.store]),
|
||||
[["x", "home"]]
|
||||
);
|
||||
assert.equal(
|
||||
(await fx.purgeUserTrash(HOME, "solo", "host", "solo0001").catch((e) => e)).code,
|
||||
"EBADPATH"
|
||||
);
|
||||
});
|
||||
|
||||
it("merges a member's home trash with their host trash, each item tagged", async (t) => {
|
||||
fs.mkdirSync(MEMBER, { recursive: true });
|
||||
const acct = { name: "mem", home: MEMBER, uid: process.getuid() };
|
||||
const orig = runAs.accountForPath;
|
||||
t.after(() => {
|
||||
runAs.accountForPath = orig;
|
||||
});
|
||||
runAs.accountForPath = (p) => (String(p).startsWith(MEMBER) ? acct : null);
|
||||
put(path.join(MEMBER, ".local", "share", "agenthub", "trash"), "memhome01", "fromHome", null);
|
||||
put(path.join(process.env.DASHBOARD_DATA_DIR, "trash", "77"), "memhost01", "fromHostWs", 5);
|
||||
const items = (await fx.listUserTrash(MEMBER, "77")).items;
|
||||
assert.deepEqual(items.map((i) => [i.name, i.store]).sort(), [
|
||||
["fromHome", "home"],
|
||||
["fromHostWs", "host"],
|
||||
]);
|
||||
// A host item whose workspace is gone has nowhere to go back to.
|
||||
const r = await fx
|
||||
.restoreUserTrash(MEMBER, "77", "host", "memhost01", () => null)
|
||||
.catch((e) => e);
|
||||
assert.equal(r.code, "ENOFILE");
|
||||
assert.equal((await fx.purgeUserTrash(MEMBER, "77", "host", "memhost01")).purged, 1);
|
||||
assert.ok(
|
||||
!fs.existsSync(path.join(process.env.DASHBOARD_DATA_DIR, "trash", "77", "memhost01"))
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* @file Tests for each member's own tmux server on the Users page (S3,
|
||||
* server/lib/member-tmux.js + `/api/users/tmux*`): its version beside the
|
||||
* installed one, an admin's restart of one member (password again, audited,
|
||||
* ETMUXSTUCK when it will not stop) and of every idle outdated member — a
|
||||
* member whose agent is working is skipped. Member tmux calls are faked.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, before, after } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const path = require("node:path");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "member-tmux-"));
|
||||
const USERS = path.join(TMP, "users");
|
||||
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
|
||||
process.env.DASHBOARD_LIVENESS_PROBE = "0";
|
||||
|
||||
const { createApp, startServer } = require("../index");
|
||||
const { db } = require("../db");
|
||||
const auth = require("../lib/auth");
|
||||
const linux = require("../lib/linux-accounts");
|
||||
const tmux = require("../lib/tmux");
|
||||
|
||||
let server;
|
||||
let BASE;
|
||||
const ids = {};
|
||||
const BOSS_PASS = "admin-pass-1";
|
||||
|
||||
// Fake member tmux servers, by Linux login.
|
||||
const servers = {};
|
||||
function fakeMember(acct, args) {
|
||||
const s = servers[acct.login];
|
||||
if (!s || !s.alive) throw Object.assign(new Error("no server running"), { status: 1 });
|
||||
if (args[0] === "display-message") return `${s.version}\t${s.pid}\t1700000000\t${s.sessions}\n`;
|
||||
if (args[0] === "kill-server") {
|
||||
if (s.stuck) throw Object.assign(new Error("server exited unexpectedly"), { status: 1 });
|
||||
s.alive = false;
|
||||
return "";
|
||||
}
|
||||
if (args[0] === "list-sessions") return "";
|
||||
return "";
|
||||
}
|
||||
|
||||
async function call(method, p, { cookie, body } = {}) {
|
||||
const res = await fetch(BASE + p, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json", ...(cookie ? { cookie } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
return { status: res.status, body: await res.json().catch(() => null) };
|
||||
}
|
||||
|
||||
async function login(username, password) {
|
||||
const res = await fetch(BASE + "/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
return res.status === 200 ? res.headers.get("set-cookie").split(";")[0] : null;
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
process.env.AGENTHUB_USERS_ROOT = USERS;
|
||||
fs.mkdirSync(USERS, { recursive: true });
|
||||
server = await startServer(createApp(), 0);
|
||||
BASE = `http://127.0.0.1:${server.address().port}`;
|
||||
ids.boss = (await auth.createUser("boss", BOSS_PASS, "admin")).id;
|
||||
ids.mia = (await auth.createUser("mia", "member-pass-1", "developer")).id;
|
||||
ids.zed = (await auth.createUser("zed", "member-pass-1", "developer")).id;
|
||||
ids.ann = (await auth.createUser("ann", "member-pass-1", "developer")).id;
|
||||
ids.stu = (await auth.createUser("stu", "member-pass-1", "developer")).id;
|
||||
// zed's agent is working right now.
|
||||
db.prepare(
|
||||
"INSERT INTO lanes (cwd, tool, owner_id, status) VALUES (?, 'claude', ?, 'running')"
|
||||
).run(path.join(USERS, "zed", "p"), ids.zed);
|
||||
// S3 on: a server.conf whose TMUX_BIN answers 3.8, and tmux-member installed.
|
||||
const bin = path.join(TMP, "tmux");
|
||||
fs.writeFileSync(bin, "#!/bin/sh\necho 'tmux 3.8'\n", { mode: 0o755 });
|
||||
const wrapper = path.join(TMP, "tmux-member");
|
||||
fs.writeFileSync(wrapper, "#!/bin/sh\n", { mode: 0o755 });
|
||||
process.env.AGENTHUB_SERVER_CONF = path.join(TMP, "server.conf");
|
||||
fs.writeFileSync(
|
||||
process.env.AGENTHUB_SERVER_CONF,
|
||||
`HOST_USER=h\nHOST_UID=1\nUSERS_ROOT=${USERS}\nTMUX_BIN=${bin}\nGIT_BIN=/usr/bin/git\n`
|
||||
);
|
||||
linux.__setTmuxMember(wrapper);
|
||||
Object.assign(servers, {
|
||||
"ah-mia": { version: "3.6", pid: 11, sessions: 2, alive: true },
|
||||
"ah-zed": { version: "3.6", pid: 12, sessions: 1, alive: true },
|
||||
"ah-ann": { version: "3.8", pid: 13, sessions: 3, alive: true },
|
||||
"ah-stu": { version: "3.6", pid: 14, sessions: 1, alive: true, stuck: true },
|
||||
});
|
||||
tmux.__setAccountImpl(() => null, fakeMember);
|
||||
});
|
||||
|
||||
after(() => {
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
delete process.env.AGENTHUB_USERS_ROOT;
|
||||
delete process.env.AGENTHUB_SERVER_CONF;
|
||||
linux.__setTmuxMember("/opt/agenthub/libexec/tmux-member");
|
||||
linux.__resetConfCache();
|
||||
tmux.__reset();
|
||||
server?.close();
|
||||
fs.rmSync(TMP, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("member tmux servers on the Users page", () => {
|
||||
it("lists each member's version beside the installed one, and who is working", async () => {
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const r = await call("GET", "/api/users/tmux", { cookie: boss });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.available, true);
|
||||
assert.equal(r.body.installed, "3.8");
|
||||
assert.equal(r.body.matched, true);
|
||||
const by = Object.fromEntries(r.body.users.map((u) => [u.username, u]));
|
||||
assert.equal(by.mia.version, "3.6");
|
||||
assert.equal(by.mia.outdated, true);
|
||||
assert.equal(by.mia.sessions, 2);
|
||||
assert.equal(by.zed.busy, 1);
|
||||
assert.equal(by.ann.outdated, false);
|
||||
// boss (no server of theirs) is listed as not running.
|
||||
assert.equal(by.boss.running, false);
|
||||
});
|
||||
|
||||
it("is staff-only to read and an admin's to restart", async () => {
|
||||
const mia = await login("mia", "member-pass-1");
|
||||
assert.equal((await call("GET", "/api/users/tmux", { cookie: mia })).status, 403);
|
||||
const r = await call("POST", `/api/users/${ids.ann}/tmux-restart`, {
|
||||
cookie: mia,
|
||||
body: { currentPassword: "member-pass-1" },
|
||||
});
|
||||
assert.equal(r.status, 403);
|
||||
assert.equal(servers["ah-ann"].alive, true);
|
||||
});
|
||||
|
||||
it("restarts one member's server with the admin's password, audited", async () => {
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const wrong = await call("POST", `/api/users/${ids.ann}/tmux-restart`, {
|
||||
cookie: boss,
|
||||
body: { currentPassword: "nope" },
|
||||
});
|
||||
assert.equal(wrong.body.error.code, "EREAUTH");
|
||||
assert.equal(servers["ah-ann"].alive, true);
|
||||
const ok = await call("POST", `/api/users/${ids.ann}/tmux-restart`, {
|
||||
cookie: boss,
|
||||
body: { currentPassword: BOSS_PASS },
|
||||
});
|
||||
assert.equal(ok.status, 200);
|
||||
assert.equal(servers["ah-ann"].alive, false);
|
||||
const audit = db
|
||||
.prepare("SELECT path FROM audit_log WHERE owner_id = ? ORDER BY id DESC LIMIT 1")
|
||||
.get(ids.ann);
|
||||
assert.match(audit.path, /ann: tmux restarted \(was 3\.8, 3 session/);
|
||||
});
|
||||
|
||||
it("names the pid to kill as root when a server will not stop", async () => {
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const r = await call("POST", `/api/users/${ids.stu}/tmux-restart`, {
|
||||
cookie: boss,
|
||||
body: { currentPassword: BOSS_PASS },
|
||||
});
|
||||
assert.equal(r.status, 409);
|
||||
assert.equal(r.body.error.code, "ETMUXSTUCK");
|
||||
assert.match(r.body.error.message, /sudo kill -9 14/);
|
||||
});
|
||||
|
||||
it("restarts every idle outdated member, skipping one whose agent works", async () => {
|
||||
servers["ah-ann"] = { version: "3.8", pid: 13, sessions: 1, alive: true };
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const r = await call("POST", "/api/users/tmux-restart-idle", {
|
||||
cookie: boss,
|
||||
body: { currentPassword: BOSS_PASS },
|
||||
});
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(r.body.restarted, ["mia"]);
|
||||
assert.deepEqual(r.body.skipped, ["zed"]);
|
||||
assert.equal(r.body.failed[0].username, "stu");
|
||||
assert.equal(servers["ah-mia"].alive, false);
|
||||
assert.equal(servers["ah-zed"].alive, true);
|
||||
assert.equal(servers["ah-ann"].alive, true); // already on 3.8
|
||||
});
|
||||
});
|
||||
@@ -240,9 +240,20 @@ describe("run-as: a path under the users root belongs to that user", () => {
|
||||
process.env.AGENTHUB_SERVER_CONF,
|
||||
`HOST_USER=h\nHOST_UID=1\nUSERS_ROOT=${TMP}/users\nGIT_BIN=/usr/bin/git\nTMUX_BIN=/opt/x/tmux\n`
|
||||
);
|
||||
linux.__resetConfCache();
|
||||
linux.__setTmuxMember(path.join(TMP, "no-tmux-member"));
|
||||
assert.equal(runAs.sudoArgv(ACCT, "git", ["status"])[1][3], "/usr/bin/git");
|
||||
assert.equal(runAs.sudoArgv(ACCT, "tmux", [])[1][3], "/opt/x/tmux");
|
||||
// Once install-system put tmux-member there, a member's tmux goes through
|
||||
// it (their running server's own binary); the installed one is still known.
|
||||
const wrapper = path.join(TMP, "tmux-member");
|
||||
fs.writeFileSync(wrapper, "#!/bin/sh\n", { mode: 0o755 });
|
||||
linux.__setTmuxMember(wrapper);
|
||||
try {
|
||||
assert.equal(runAs.sudoArgv(ACCT, "tmux", [])[1][3], wrapper);
|
||||
assert.equal(linux.serverConf().tmuxInstalled, "/opt/x/tmux");
|
||||
} finally {
|
||||
linux.__setTmuxMember(path.join(TMP, "no-tmux-member"));
|
||||
}
|
||||
assert.equal(
|
||||
runAs.sudoArgv(ACCT, "/opt/agenthub/libexec/write-as", [])[1][3],
|
||||
"/opt/agenthub/libexec/write-as"
|
||||
|
||||
@@ -187,6 +187,7 @@ describe("Linux accounts", () => {
|
||||
hostUid: 4242,
|
||||
usersRoot: "/srv/agenthub/users",
|
||||
port: 4820,
|
||||
tmuxInstalled: null,
|
||||
bins: {},
|
||||
});
|
||||
assert.deepEqual(linux.accountFor("mia"), {
|
||||
@@ -199,7 +200,8 @@ describe("Linux accounts", () => {
|
||||
for (const bad of ["Mia", "1mia", "mi.a", "-x", "a".repeat(30), "root;id", "../x"]) {
|
||||
assert.throws(() => linux.provision("create", bad), { code: "EBADUSER" }, bad);
|
||||
}
|
||||
assert.throws(() => linux.provision("delete", "mia"), /unknown provision action/);
|
||||
// `delete` is an action now (Delete user); anything else is still refused.
|
||||
assert.throws(() => linux.provision("purge", "mia"), /unknown provision action/);
|
||||
assert.deepEqual(argvs, []);
|
||||
});
|
||||
|
||||
|
||||
@@ -1146,7 +1146,7 @@ async function installSkill(req, row, { replace = false } = {}) {
|
||||
);
|
||||
if (acct) {
|
||||
if (!runAs.writeAsCanMove()) {
|
||||
throw fail("EUPGRADE", "replacing needs the updated helper: run `sudo agenthub server install-system` once");
|
||||
throw fail("EUPGRADE", "replacing needs the updated helper: run `agenthub server install-system` once");
|
||||
}
|
||||
runAs.mkdirAs(acct, path.dirname(aside));
|
||||
await runAs.writeAsAsync(acct, target, ["move", aside]);
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
* @file The workspace File Explorer (`/api/lanes/:id/fs/*`): list a folder,
|
||||
* make a folder or an empty file, rename, move and copy (within a workspace
|
||||
* or into another of the same account), delete into a per-account TRASH that
|
||||
* can be restored (kept TRASH_DAYS), upload a file streamed from the request
|
||||
* can be restored (kept TRASH_DAYS) — and, for `/api/homes`, one recycle bin
|
||||
* per USER over every store their deletes went to — upload a file streamed from the request
|
||||
* into any (new) sub-folder, and download files or folders as one streamed zip.
|
||||
*
|
||||
* Every path is the read path's own (git-diff.js): `lanePath` (lexical, no
|
||||
@@ -17,7 +18,7 @@
|
||||
* Writes run as the folder's ACCOUNT (run-as.js): a member's through
|
||||
* `write-as` (sudo, as them — the host never writes in their home), the
|
||||
* host's directly. A move/copy/trash in a member's folder needs write-as's
|
||||
* `move`/`copy` (`EUPGRADE` until `sudo agenthub server install-system` has
|
||||
* `move`/`copy` (`EUPGRADE` until `agenthub server install-system` has
|
||||
* installed it). A copy or move never crosses accounts (`EFOREIGN`).
|
||||
*
|
||||
* A name that is taken is never silently replaced: `conflict` decides —
|
||||
@@ -140,7 +141,7 @@ function needMove(acct) {
|
||||
if (acct && !runAs.writeAsCanMove()) {
|
||||
throw bad(
|
||||
"EUPGRADE",
|
||||
"moving or copying in a member's folder needs the updated helper: run `sudo agenthub server install-system` once"
|
||||
"moving or copying in a member's folder needs the updated helper: run `agenthub server install-system` once"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -468,12 +469,17 @@ async function dropTrash(acct, idDir) {
|
||||
async function listTrash(dir, userKey) {
|
||||
const root = await laneRoot(dir);
|
||||
const acct = accountAt(root);
|
||||
const tr = trashRoot(acct, userKey);
|
||||
const items = await readStore(acct, trashRoot(acct, userKey));
|
||||
return { items, keepDays: TRASH_DAYS };
|
||||
}
|
||||
|
||||
/** The live items of one trash folder `tr` (of `acct`), expired ones dropped. */
|
||||
async function readStore(acct, tr, store) {
|
||||
let ids = [];
|
||||
try {
|
||||
ids = (await fs.promises.readdir(tr)).filter((n) => TRASH_ID_RE.test(n));
|
||||
} catch {
|
||||
return { items: [] };
|
||||
return [];
|
||||
}
|
||||
const cutoff = Date.now() - TRASH_DAYS * 86_400_000;
|
||||
const items = [];
|
||||
@@ -490,15 +496,20 @@ async function listTrash(dir, userKey) {
|
||||
path: meta.rel,
|
||||
isDir: !!meta.isDir,
|
||||
deletedAt: meta.deletedAt,
|
||||
...(store ? { store } : {}),
|
||||
});
|
||||
}
|
||||
items.sort((a, b) => b.deletedAt.localeCompare(a.deletedAt));
|
||||
return { items, keepDays: TRASH_DAYS };
|
||||
return items;
|
||||
}
|
||||
|
||||
function trashEntry(acct, userKey, id) {
|
||||
return entryAt(acct, trashRoot(acct, userKey), id);
|
||||
}
|
||||
|
||||
function entryAt(acct, tr, id) {
|
||||
if (!TRASH_ID_RE.test(String(id || ""))) throw bad("EBADPATH", "no such trash item");
|
||||
const idDir = path.join(trashRoot(acct, userKey), id);
|
||||
const idDir = path.join(tr, id);
|
||||
const meta = readMeta(acct, idDir);
|
||||
if (!meta) throw bad("ENOFILE", "no such trash item");
|
||||
return { idDir, meta };
|
||||
@@ -515,6 +526,11 @@ async function restore(dir, id, userKey, resolveLane) {
|
||||
const acct = accountAt(root);
|
||||
const { idDir, meta } = trashEntry(acct, userKey, id);
|
||||
const home = (meta.laneId != null && resolveLane(meta.laneId)) || dir;
|
||||
return putBack(acct, idDir, meta, home, dir);
|
||||
}
|
||||
|
||||
/** Move trash entry `idDir` back under folder `home` (`dir`: the fallback). */
|
||||
async function putBack(acct, idDir, meta, home, dir) {
|
||||
const parentRel = path.posix.dirname(String(meta.rel || meta.name));
|
||||
const relDir = parentRel === "." ? "" : parentRel;
|
||||
await ensureFolders(home, relDir);
|
||||
@@ -530,6 +546,77 @@ async function restore(dir, id, userKey, resolveLane) {
|
||||
return { path: relDir ? `${relDir}/${name}` : name, laneId: home === dir ? null : meta.laneId };
|
||||
}
|
||||
|
||||
// ── A user's recycle bin ───────────────────────────────────────────────────
|
||||
//
|
||||
// One Trash per USER, whatever place a delete happened in: the trash of their
|
||||
// home's account (a member's `~/.local/share/agenthub/trash/`, or the host's
|
||||
// `<data dir>/trash/<user id>/` when their home is the host's) plus — when
|
||||
// that is another folder — the host trash under their user id, where what
|
||||
// they deleted in a host-folder workspace went. Items carry `store`
|
||||
// ("home" | "host") so a restore or purge finds the right one.
|
||||
|
||||
/** The trash stores of the user `userKey` whose home is `homeDir`. */
|
||||
function userStores(homeDir, userKey) {
|
||||
const acct = accountAt(homeDir);
|
||||
const out = [{ store: "home", acct, root: trashRoot(acct, userKey) }];
|
||||
const host = trashRoot(null, userKey);
|
||||
if (acct || path.resolve(host) !== path.resolve(out[0].root)) {
|
||||
out.push({ store: "host", acct: null, root: host });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function pickStore(homeDir, userKey, store) {
|
||||
const s = userStores(homeDir, userKey).find((x) => x.store === (store || "home"));
|
||||
if (!s) throw bad("EBADPATH", "no such trash");
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Every item of the user's recycle bin, newest first. */
|
||||
async function listUserTrash(homeDir, userKey) {
|
||||
const items = [];
|
||||
for (const s of userStores(homeDir, userKey)) {
|
||||
items.push(...(await readStore(s.acct, s.root, s.store)));
|
||||
}
|
||||
items.sort((a, b) => b.deletedAt.localeCompare(a.deletedAt));
|
||||
return { items, keepDays: TRASH_DAYS };
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore item `id` of the user's `store`: into the workspace it came from
|
||||
* when `resolveLane` still gives one, else — for the home store — into the
|
||||
* home. A host-store item whose workspace is gone has nowhere of the same
|
||||
* account to go (`ENOFILE`).
|
||||
*/
|
||||
async function restoreUserTrash(homeDir, userKey, store, id, resolveLane) {
|
||||
const s = pickStore(homeDir, userKey, store);
|
||||
const { idDir, meta } = entryAt(s.acct, s.root, id);
|
||||
const fallback = s.store === "home" ? homeDir : null;
|
||||
const home = (meta.laneId != null && resolveLane(meta.laneId)) || fallback;
|
||||
if (!home) {
|
||||
throw bad("ENOFILE", "the workspace this came from is gone — there is nowhere to restore it");
|
||||
}
|
||||
return putBack(s.acct, idDir, meta, home, fallback);
|
||||
}
|
||||
|
||||
/** Delete item `id` of `store` forever, or `"all"` of every store. */
|
||||
async function purgeUserTrash(homeDir, userKey, store, id) {
|
||||
if (id === "all") {
|
||||
let n = 0;
|
||||
for (const s of userStores(homeDir, userKey)) {
|
||||
for (const it of await readStore(s.acct, s.root)) {
|
||||
await dropTrash(s.acct, path.join(s.root, it.id));
|
||||
n++;
|
||||
}
|
||||
}
|
||||
return { purged: n };
|
||||
}
|
||||
const s = pickStore(homeDir, userKey, store);
|
||||
const { idDir } = entryAt(s.acct, s.root, id);
|
||||
await dropTrash(s.acct, idDir);
|
||||
return { purged: 1 };
|
||||
}
|
||||
|
||||
async function purgeTrash(dir, userKey, id) {
|
||||
const root = await laneRoot(dir);
|
||||
const acct = accountAt(root);
|
||||
@@ -800,6 +887,9 @@ module.exports = {
|
||||
remove,
|
||||
trashOne,
|
||||
listTrash,
|
||||
listUserTrash,
|
||||
restoreUserTrash,
|
||||
purgeUserTrash,
|
||||
restore,
|
||||
purgeTrash,
|
||||
upload,
|
||||
|
||||
@@ -386,6 +386,15 @@ async function getAuthor(account) {
|
||||
return { name: await get("user.name"), email: await get("user.email") };
|
||||
}
|
||||
|
||||
/** The domain of a suggested email when the account has no author yet. */
|
||||
const DEFAULT_EMAIL_DOMAIN = process.env.AGENTHUB_EMAIL_DOMAIN || "smartgift.vn";
|
||||
|
||||
/** `<username>@<DEFAULT_EMAIL_DOMAIN>`, or null without a usable name. */
|
||||
function defaultEmail(username) {
|
||||
const local = String(username || "").replace(/[^\w.+-]/g, "");
|
||||
return local ? `${local}@${DEFAULT_EMAIL_DOMAIN}` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the account's commit author. Neither is a secret, so they may cross
|
||||
* sudo's argv; each is one line, a name up to 100 and an email up to 254
|
||||
@@ -798,6 +807,7 @@ module.exports = {
|
||||
defaultName,
|
||||
cloneRepo,
|
||||
getAuthor,
|
||||
defaultEmail,
|
||||
setAuthor,
|
||||
sshConfigFor,
|
||||
memberHttpsConfig,
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* workspaces in.
|
||||
*
|
||||
* S3 is ON when server mode is on AND `/etc/agenthub/server.conf` exists
|
||||
* (written by `sudo agenthub server install-system`, root-owned). Without it
|
||||
* (written by `agenthub server install-system`, root-owned). Without it
|
||||
* everything here is a no-op and server mode behaves as in S2.
|
||||
*
|
||||
* `provision` is the dashboard's only way to create, disable or enable a Linux
|
||||
@@ -46,6 +46,13 @@ function serverConf() {
|
||||
return confCache.value;
|
||||
}
|
||||
|
||||
let TMUX_MEMBER = "/opt/agenthub/libexec/tmux-member";
|
||||
/** Test seam: where tmux-member is looked for. */
|
||||
function __setTmuxMember(p) {
|
||||
TMUX_MEMBER = p;
|
||||
confCache = { at: 0, path: null, value: null };
|
||||
}
|
||||
|
||||
function readConf(file) {
|
||||
let text;
|
||||
try {
|
||||
@@ -56,16 +63,28 @@ function readConf(file) {
|
||||
const get = (k) => new RegExp(`^${k}=(.*)$`, "m").exec(text)?.[1]?.trim() || "";
|
||||
const usersRoot = get("USERS_ROOT");
|
||||
if (!path.isAbsolute(usersRoot)) return null;
|
||||
// A member's tmux runs through tmux-member once install-system put it there
|
||||
// (and in sudoers): it picks their RUNNING server's own binary, so a tmux
|
||||
// upgrade never mixes a new client with an old server. Before that, TMUX_BIN.
|
||||
let tmuxBin = get("TMUX_BIN");
|
||||
try {
|
||||
fs.accessSync(TMUX_MEMBER, fs.constants.X_OK);
|
||||
if (path.isAbsolute(tmuxBin)) tmuxBin = TMUX_MEMBER;
|
||||
} catch {
|
||||
/* not installed yet */
|
||||
}
|
||||
return {
|
||||
hostUser: get("HOST_USER"),
|
||||
hostUid: Number(get("HOST_UID")),
|
||||
usersRoot,
|
||||
port: Number(get("PORT")) || null,
|
||||
// The installed tmux (a new member server starts on it).
|
||||
tmuxInstalled: path.isAbsolute(get("TMUX_BIN")) ? get("TMUX_BIN") : null,
|
||||
// The absolute paths sudoers lists (sudo would resolve a bare name on its
|
||||
// own secure_path, which may not be them).
|
||||
bins: Object.fromEntries(
|
||||
[
|
||||
["tmux", get("TMUX_BIN")],
|
||||
["tmux", tmuxBin],
|
||||
["git", get("GIT_BIN")],
|
||||
["gh", get("GH_BIN")],
|
||||
].filter(([, v]) => path.isAbsolute(v))
|
||||
@@ -139,7 +158,7 @@ function provision(action, username) {
|
||||
// An installed helper older than this build (root's copy is refreshed
|
||||
// only by install-system) does not know the action yet.
|
||||
const hint = /unknown action/.test(why)
|
||||
? " — the server helper is older than this AgentHub: run `sudo agenthub server install-system` once"
|
||||
? " — the server helper is older than this AgentHub: run `agenthub server install-system` once"
|
||||
: "";
|
||||
throw Object.assign(new Error(`could not ${action} the Linux account: ${why}${hint}`), {
|
||||
code: "EPROVISION",
|
||||
@@ -154,6 +173,7 @@ function __resetConfCache() {
|
||||
|
||||
module.exports = {
|
||||
__resetConfCache,
|
||||
__setTmuxMember,
|
||||
confPath,
|
||||
LINUX_NAME_RE,
|
||||
serverConf,
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @file member-tmux.js
|
||||
* @description Server mode, one Linux user per account (S3): each member's
|
||||
* own tmux server as the Users page shows it — the version it runs next to
|
||||
* the installed one (`TMUX_BIN`), how many sessions it holds and whether an
|
||||
* agent of theirs is working — and an admin's restart of it. A tmux server
|
||||
* keeps the version it started with until its last session closes, so after
|
||||
* a tmux upgrade an old server lingers; `tmux-member` (install-system) keeps
|
||||
* every call on it matched to its own binary, and this is how an admin moves
|
||||
* a member onto the new version on purpose. A restart ends every pane of
|
||||
* theirs (their Claude sessions resume from the workspace).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
const { db } = require("../db");
|
||||
const linux = require("./linux-accounts");
|
||||
const tmux = require("./tmux");
|
||||
|
||||
const err = (code, message) => Object.assign(new Error(message), { code });
|
||||
|
||||
// The installed tmux's version (`3.8`), re-read at most once a minute.
|
||||
let installed = { at: 0, bin: null, version: null };
|
||||
function installedVersion() {
|
||||
const bin = linux.serverConf()?.tmuxInstalled || null;
|
||||
if (installed.bin === bin && Date.now() - installed.at < 60_000) return installed.version;
|
||||
let version = null;
|
||||
if (bin) {
|
||||
try {
|
||||
version =
|
||||
String(execFileSync(bin, ["-V"], { encoding: "utf8", timeout: 3000, stdio: "pipe" }))
|
||||
.trim()
|
||||
.replace(/^tmux\s+/, "") || null;
|
||||
} catch {
|
||||
/* missing or broken: unknown */
|
||||
}
|
||||
}
|
||||
installed = { at: Date.now(), bin, version };
|
||||
return version;
|
||||
}
|
||||
|
||||
/** How many of `userId`'s workspaces have an agent working right now. */
|
||||
function busyCount(userId) {
|
||||
return db
|
||||
.prepare("SELECT COUNT(*) AS n FROM lanes WHERE owner_id = ? AND status = 'running'")
|
||||
.get(userId).n;
|
||||
}
|
||||
|
||||
/** One user's row; null for an account with no Linux side. */
|
||||
function rowFor(user, installedV) {
|
||||
const acct = linux.accountFor(user.username);
|
||||
if (!acct) return null;
|
||||
const info = tmux.memberServerInfo(acct);
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
...info,
|
||||
busy: busyCount(user.id),
|
||||
outdated: !!(info.running && info.version && installedV && info.version !== installedV),
|
||||
};
|
||||
}
|
||||
|
||||
/** `{available, installed, matched, users: [...]}` for the Users page. */
|
||||
function overview(users) {
|
||||
if (!linux.s3Enabled()) return { available: false, users: [] };
|
||||
const conf = linux.serverConf();
|
||||
const v = installedVersion();
|
||||
return {
|
||||
available: true,
|
||||
installed: v,
|
||||
// Whether calls on an older server already use its own binary.
|
||||
matched: conf?.bins?.tmux !== conf?.tmuxInstalled,
|
||||
users: users.map((u) => rowFor(u, v)).filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Restart `user`'s tmux server. `{restarted: false}` when none ran; throws
|
||||
* ETMUXSTUCK (with the pid) when it would not stop — root has to kill it.
|
||||
*/
|
||||
function restart(user) {
|
||||
const acct = linux.accountFor(user.username);
|
||||
if (!acct) throw err("ENOS3", "this account has no Linux user (S3 is not installed)");
|
||||
const before = tmux.memberServerInfo(acct);
|
||||
if (!before.running) return { restarted: false, before };
|
||||
try {
|
||||
tmux.killMemberServer(acct);
|
||||
} catch {
|
||||
/* judged by what is left below */
|
||||
}
|
||||
const after = tmux.memberServerInfo(acct);
|
||||
if (after.running) {
|
||||
const pid = before.pid || after.pid;
|
||||
throw err(
|
||||
"ETMUXSTUCK",
|
||||
`${user.username}'s tmux server did not stop — run \`sudo kill -9 ${pid || "<pid>"}\` on the server`
|
||||
);
|
||||
}
|
||||
return { restarted: true, before };
|
||||
}
|
||||
|
||||
module.exports = { overview, restart, installedVersion };
|
||||
@@ -720,6 +720,53 @@ function killSession(name) {
|
||||
noteSession(name, accountOfQuiet(name), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* A member's tmux server as the Users page shows it: `{running: false}`, or
|
||||
* `{running: true, version, pid, startedAt, sessions}`, or `{stuck: true}`
|
||||
* when it did not answer (hung, or backed off). Asked with `tmux-member`, i.e.
|
||||
* with that server's own binary.
|
||||
*/
|
||||
function memberServerInfo(acct) {
|
||||
try {
|
||||
const out = String(
|
||||
memberCall(acct, [
|
||||
"display-message",
|
||||
"-p",
|
||||
"#{version}\t#{pid}\t#{start_time}\t#{server_sessions}",
|
||||
])
|
||||
).trim();
|
||||
const [version, pid, start, sessions] = out.split("\t");
|
||||
return {
|
||||
running: true,
|
||||
version: version || null,
|
||||
pid: /^\d+$/.test(pid) ? Number(pid) : null,
|
||||
startedAt: /^\d+$/.test(start) ? Number(start) * 1000 : null,
|
||||
sessions: /^\d+$/.test(sessions) ? Number(sessions) : null,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err.code === "ETMUXHUNG" || err.code === "ETIMEDOUT" || err.code === "ENOBUFS") {
|
||||
return { running: true, stuck: true };
|
||||
}
|
||||
// "no server running" / "error connecting": nothing to report.
|
||||
return { running: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop a member's tmux server — every pane of theirs ends (an admin's Users
|
||||
* page action, so the next start runs the installed tmux). Throws when the
|
||||
* server did not go: a stuck one may need root (`sudo kill <pid>`).
|
||||
*/
|
||||
function killMemberServer(acct) {
|
||||
unreachable.delete(acct.login); // asked deliberately, past any back-off
|
||||
try {
|
||||
memberCall(acct, ["kill-server"]);
|
||||
} finally {
|
||||
listGen++;
|
||||
listed.delete(acct.login);
|
||||
}
|
||||
}
|
||||
|
||||
/** Session names starting with `prefix`. Empty array if tmux has no server running at all. */
|
||||
function listSessions(prefix) {
|
||||
const names = [];
|
||||
@@ -867,6 +914,8 @@ module.exports = {
|
||||
upgradeAdvice,
|
||||
serverPid,
|
||||
memberAttach,
|
||||
memberServerInfo,
|
||||
killMemberServer,
|
||||
__setExecImpl,
|
||||
__setAccountImpl,
|
||||
__settle,
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
* - GET/PUT/DELETE /api/me/avatar (Auth) — the account's own picture
|
||||
* - GET/PATCH /api/users/{id} (Auth) — the Users page's Edit user form
|
||||
* - GET /api/users/{id}/avatar (Auth) — one account's picture (admin/analyst)
|
||||
* - GET /api/users/tmux, POST /api/users/{id}/tmux-restart, POST /api/users/tmux-restart-idle
|
||||
* (Auth) — each member's own tmux server and an admin's restart of it (S3)
|
||||
* Exports `{ tags, schemas, paths }`, combined into the spec by
|
||||
* server/openapi-extra.js. See docs/SERVER-MODE.md.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
@@ -409,6 +411,77 @@ const paths = {
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/users/tmux": {
|
||||
get: {
|
||||
tags: ["Auth"],
|
||||
operationId: "listMemberTmux",
|
||||
summary:
|
||||
"Each member's own tmux server (one Linux user per account): its version beside the installed one, sessions, agents working (admin/analyst)",
|
||||
responses: {
|
||||
200: {
|
||||
description:
|
||||
"{available, installed, matched, users: [{id, username, running, stuck?, version, pid, startedAt, sessions, busy, outdated}]} — available false without S3",
|
||||
},
|
||||
403: err("EADMIN — a developer"),
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/users/{id}/tmux-restart": {
|
||||
post: {
|
||||
tags: ["Auth"],
|
||||
operationId: "restartMemberTmux",
|
||||
summary:
|
||||
"End one member's tmux server — every pane of theirs closes; the next start runs the installed tmux (admin, own password again, audited)",
|
||||
parameters: [idParam],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
required: ["currentPassword"],
|
||||
properties: { currentPassword: { type: "string" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: { description: "{user}" },
|
||||
403: err("EREAUTH (own password wrong) / EADMIN / ELOCALMODE"),
|
||||
404: err("ENOUSER"),
|
||||
409: err(
|
||||
"ETMUXSTUCK — the server did not stop (the message names the pid for root) / ENOS3"
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/users/tmux-restart-idle": {
|
||||
post: {
|
||||
tags: ["Auth"],
|
||||
operationId: "restartIdleMemberTmux",
|
||||
summary:
|
||||
"Restart every member server older than the installed tmux while no agent of theirs works (admin, own password again, audited per member)",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
required: ["currentPassword"],
|
||||
properties: { currentPassword: { type: "string" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description:
|
||||
"{restarted: [username], skipped: [username — an agent working], failed: [{username, message}]}",
|
||||
},
|
||||
403: err("EREAUTH / EADMIN / ELOCALMODE"),
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/users/{id}/avatar": {
|
||||
get: {
|
||||
tags: ["Auth"],
|
||||
|
||||
@@ -6,13 +6,15 @@
|
||||
* git uses that key (`core.sshCommand`), the SSH login name per host
|
||||
* (`url.<…>.insteadOf` — AWS CodeCommit's SSH key ID), and the commit author (`user.name` /
|
||||
* `user.email` of the account's global git config — a member's commits fail
|
||||
* without one). The account is the signed-in user's
|
||||
* without one; a new SSH key is labelled with that email, else
|
||||
* `<username>@smartgift.vn`). The account is the signed-in user's
|
||||
* own Linux account under S3, else the host's, which only an admin (or local
|
||||
* mode) may change (`EHOSTIDENTITY`). Nothing here takes a path from the
|
||||
* request, and every write passes the same-origin guard.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const os = require("node:os");
|
||||
const express = require("express");
|
||||
|
||||
const identity = require("../lib/git-identity");
|
||||
@@ -39,7 +41,7 @@ function fail(res, e) {
|
||||
.json({ error: { code: e.code || "EINTERNAL", message: e.message } });
|
||||
}
|
||||
|
||||
async function view(account) {
|
||||
async function view(account, username) {
|
||||
const keys = identity.sshKeysInfo(account);
|
||||
const terminal = keys.length ? await identity.terminalSshState(account) : undefined;
|
||||
return {
|
||||
@@ -52,9 +54,14 @@ async function view(account) {
|
||||
sshUsers: await identity.listSshUsers(account),
|
||||
https: identity.listHttps(account),
|
||||
author: await identity.getAuthor(account),
|
||||
// What the author email form suggests while none is set.
|
||||
defaultEmail: identity.defaultEmail(username),
|
||||
};
|
||||
}
|
||||
|
||||
/** The signed-in user's name, or the OS user's in local mode. */
|
||||
const usernameOf = (req) => req.user?.username || os.userInfo().username;
|
||||
|
||||
/** The request's account; a write to the host's identity needs an admin. */
|
||||
function accountOf(req, { write = false } = {}) {
|
||||
const account = identity.accountForRequest(req);
|
||||
@@ -68,7 +75,7 @@ function accountOf(req, { write = false } = {}) {
|
||||
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
res.json(await view(accountOf(req)));
|
||||
res.json(await view(accountOf(req), usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -80,9 +87,11 @@ router.post("/ssh-key", sameOriginGuard, async (req, res) => {
|
||||
await identity.generateSshKey(account, {
|
||||
replace: req.body?.replace === true,
|
||||
type: req.body?.type === "rsa" ? "rsa" : "ed25519",
|
||||
comment: req.user?.username ? `${req.user.username}@agenthub` : "agenthub",
|
||||
// The key is labelled with the commit author's email, else the default one.
|
||||
comment:
|
||||
(await identity.getAuthor(account)).email || identity.defaultEmail(usernameOf(req)),
|
||||
});
|
||||
res.status(201).json(await view(account));
|
||||
res.status(201).json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -95,7 +104,7 @@ router.delete("/ssh-key", sameOriginGuard, async (req, res) => {
|
||||
if (!(await identity.removeSshKey(account, type))) {
|
||||
return res.status(404).json({ error: { code: "ENOTFOUND", message: "no SSH key" } });
|
||||
}
|
||||
res.json(await view(account));
|
||||
res.json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -112,7 +121,7 @@ router.put("/ssh-terminal", sameOriginGuard, async (req, res) => {
|
||||
return res.status(404).json({ error: { code: "ENOTFOUND", message: "no SSH key" } });
|
||||
}
|
||||
await identity.setTerminalSsh(account, req.body?.on === true);
|
||||
res.json(await view(account));
|
||||
res.json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -126,7 +135,7 @@ router.put("/ssh-user", sameOriginGuard, async (req, res) => {
|
||||
try {
|
||||
const account = accountOf(req, { write: true });
|
||||
await identity.setSshUser(account, req.body || {});
|
||||
res.json(await view(account));
|
||||
res.json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -138,7 +147,7 @@ router.delete("/ssh-user/:host", sameOriginGuard, async (req, res) => {
|
||||
if (!(await identity.removeSshUser(account, req.params.host))) {
|
||||
return res.status(404).json({ error: { code: "ENOTFOUND", message: "no such SSH user" } });
|
||||
}
|
||||
res.json(await view(account));
|
||||
res.json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -149,7 +158,7 @@ router.post("/https", sameOriginGuard, async (req, res) => {
|
||||
const account = accountOf(req, { write: true });
|
||||
const { host, username, password } = req.body || {};
|
||||
identity.saveHttps(account, { protocol: "https", host, username, password });
|
||||
res.json(await view(account));
|
||||
res.json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -161,7 +170,7 @@ router.delete("/https/:host", sameOriginGuard, async (req, res) => {
|
||||
if (!identity.removeHttps(account, "https", req.params.host)) {
|
||||
return res.status(404).json({ error: { code: "ENOTFOUND", message: "no such login" } });
|
||||
}
|
||||
res.json(await view(account));
|
||||
res.json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
@@ -172,7 +181,7 @@ router.put("/author", sameOriginGuard, async (req, res) => {
|
||||
try {
|
||||
const account = accountOf(req, { write: true });
|
||||
await identity.setAuthor(account, req.body || {});
|
||||
res.json(await view(account));
|
||||
res.json(await view(account, usernameOf(req)));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
|
||||
+69
-11
@@ -4,13 +4,18 @@
|
||||
* `inHome` so the dot entries at the top of a home stay out of reach).
|
||||
*
|
||||
* GET /api/homes the homes the caller may open
|
||||
* GET /api/homes/trash every Trash the caller may open, merged
|
||||
* GET /api/homes/:who/fs/list|trash|zip|download
|
||||
* POST /api/homes/:who/fs/mkdir|newfile|rename|move|copy|delete|upload|trash/restore|trash/purge
|
||||
*
|
||||
* `:who` is `me`, or — for an admin — another user's name: read-only
|
||||
* (`403 EREADONLY` on every write) and written to the audit log. Writes are
|
||||
* same-origin; a copy may come from a workspace (`fromLane`) the caller can
|
||||
* see, of the same Linux account.
|
||||
* (`403 EREADONLY` on every write) and written to the audit log. The one
|
||||
* exception is that user's TRASH: an admin lists, restores and purges it
|
||||
* (the recycle-bin management in /files), each write audited with the item
|
||||
* id. A home's Trash is its USER's whole recycle bin (`fx.listUserTrash`:
|
||||
* their home account's trash plus their host trash), each item tagged with
|
||||
* the `store` a restore/purge names. Writes are same-origin; a copy may come
|
||||
* from a workspace (`fromLane`) the caller can see, of the same Linux account.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -57,12 +62,12 @@ const paths = (body) =>
|
||||
* Resolve `:who`, refuse a write to someone else's home, audit an admin's
|
||||
* read of it, then run `fn(home)` inside the home rule.
|
||||
*/
|
||||
function handle(fn, { write = false } = {}) {
|
||||
function handle(fn, { write = false, trash = false } = {}) {
|
||||
return async (req, res) => {
|
||||
let home;
|
||||
try {
|
||||
home = homes.resolveHome(req, req.params.who);
|
||||
if (write && home.readOnly) {
|
||||
if (write && !trash && home.readOnly) {
|
||||
throw Object.assign(new Error("another user's home is read-only"), { code: "EREADONLY" });
|
||||
}
|
||||
if (home.readOnly && req.user) {
|
||||
@@ -70,7 +75,7 @@ function handle(fn, { write = false } = {}) {
|
||||
req.user.id,
|
||||
home.ownerId,
|
||||
req.method,
|
||||
`home ${req.params.who}: ${req.path} ${String(req.query.path ?? "")}`
|
||||
`home ${req.params.who}: ${req.path} ${String(req.query.path ?? req.body?.id ?? "")}`
|
||||
);
|
||||
}
|
||||
await fx.inHome(() => fn(req, res, home));
|
||||
@@ -81,11 +86,51 @@ function handle(fn, { write = false } = {}) {
|
||||
};
|
||||
}
|
||||
const trashFor = (req, home) => (rel) => fx.trashOne(home.dir, null, rel, userKey(req));
|
||||
/** Whose trash a home's Trash view shows: the home OWNER's (an admin looking
|
||||
* at another user's home manages THEIR recycle bin, not the admin's own). */
|
||||
const trashKey = (req, home) =>
|
||||
home.readOnly && home.ownerId != null ? String(home.ownerId) : userKey(req);
|
||||
|
||||
router.get("/", (req, res) => {
|
||||
res.json({ homes: homes.listHomes(req) });
|
||||
});
|
||||
|
||||
/**
|
||||
* Every recycle bin the caller may open in one list — an admin's is every
|
||||
* user's — each item tagged with its home (`home`, the `:who` a restore or
|
||||
* purge goes to) and that user's name (`owner`). A home whose trash cannot
|
||||
* be read is reported in `errors`, never silently left out. Each other
|
||||
* user's trash read is audited like opening their home.
|
||||
*/
|
||||
router.get("/trash", async (req, res) => {
|
||||
const items = [];
|
||||
const errors = [];
|
||||
let keepDays;
|
||||
for (const h of homes.listHomes(req)) {
|
||||
try {
|
||||
const home = homes.resolveHome(req, h.id);
|
||||
if (home.readOnly && req.user) {
|
||||
require("../lib/audit").recordHomeRead(
|
||||
req.user.id,
|
||||
home.ownerId,
|
||||
"GET",
|
||||
`home ${h.id}: /trash (all trashes)`
|
||||
);
|
||||
}
|
||||
const out = await fx.listUserTrash(home.dir, trashKey(req, home));
|
||||
keepDays = out.keepDays;
|
||||
for (const i of out.items) {
|
||||
if (i.laneId != null && !scope.canSeeLane(req, i.laneId)) continue;
|
||||
items.push({ ...i, home: h.id, owner: h.label });
|
||||
}
|
||||
} catch (err) {
|
||||
errors.push({ home: h.id, owner: h.label, message: err.message });
|
||||
}
|
||||
}
|
||||
items.sort((a, b) => b.deletedAt.localeCompare(a.deletedAt));
|
||||
res.json({ items, errors, keepDays });
|
||||
});
|
||||
|
||||
router.get(
|
||||
"/:who/fs/list",
|
||||
handle(async (req, res, home) => {
|
||||
@@ -136,13 +181,15 @@ router.get(
|
||||
router.get(
|
||||
"/:who/fs/trash",
|
||||
handle(async (req, res, home) => {
|
||||
const out = await fx.listTrash(home.dir, userKey(req));
|
||||
const out = await fx.listUserTrash(home.dir, trashKey(req, home));
|
||||
out.items = out.items.filter((i) => i.laneId == null || scope.canSeeLane(req, i.laneId));
|
||||
res.json(out);
|
||||
})
|
||||
);
|
||||
|
||||
const W = { write: true };
|
||||
// Restore/purge: writes, but allowed in another user's home for an admin.
|
||||
const TRASH_W = { write: true, trash: true };
|
||||
router.post(
|
||||
"/:who/fs/mkdir",
|
||||
sameOriginGuard,
|
||||
@@ -223,15 +270,26 @@ router.post(
|
||||
const l = lanesLib.getLane(Number(laneId));
|
||||
return l && scope.canSeeLane(req, l.id) ? l.cwd : null;
|
||||
};
|
||||
res.json(await fx.restore(home.dir, req.body?.id, userKey(req), resolveLane));
|
||||
}, W)
|
||||
res.json(
|
||||
await fx.restoreUserTrash(
|
||||
home.dir,
|
||||
trashKey(req, home),
|
||||
req.body?.store,
|
||||
req.body?.id,
|
||||
resolveLane
|
||||
)
|
||||
);
|
||||
}, TRASH_W)
|
||||
);
|
||||
router.post(
|
||||
"/:who/fs/trash/purge",
|
||||
sameOriginGuard,
|
||||
handle(
|
||||
async (req, res, home) => res.json(await fx.purgeTrash(home.dir, userKey(req), req.body?.id)),
|
||||
W
|
||||
async (req, res, home) =>
|
||||
res.json(
|
||||
await fx.purgeUserTrash(home.dir, trashKey(req, home), req.body?.store, req.body?.id)
|
||||
),
|
||||
TRASH_W
|
||||
)
|
||||
);
|
||||
router.post(
|
||||
|
||||
@@ -8,6 +8,12 @@
|
||||
* (server/lib/audit.js); `GET /storage` how much disk each user's home takes
|
||||
* (server/lib/user-storage.js — measured in a worker, `?refresh=1` re-measures).
|
||||
*
|
||||
* `GET /tmux` (S3) is each member's own tmux server — its version beside the
|
||||
* installed one, its sessions, whether an agent of theirs works — and an
|
||||
* admin restarts one (`POST /:id/tmux-restart`) or every idle outdated one
|
||||
* (`POST /tmux-restart-idle`), with their password again and audited
|
||||
* (server/lib/member-tmux.js); a restart ends that member's panes.
|
||||
*
|
||||
* `GET /:id` is one account with the workspaces it owns, for the Edit user form;
|
||||
* `GET /:id/avatar` its picture (server/lib/avatars.js), for the sidebar's
|
||||
* owner groups — staff only like the rest of `/users`.
|
||||
@@ -96,6 +102,11 @@ router.get("/audit", (req, res) => {
|
||||
res.json({ entries: listAudit(req.query.limit) });
|
||||
});
|
||||
|
||||
/** S3: each member's tmux server — its version beside the installed one (member-tmux.js). */
|
||||
router.get("/tmux", (_req, res) => {
|
||||
res.json(require("../lib/member-tmux").overview(listUsers()));
|
||||
});
|
||||
|
||||
const STATUS = {
|
||||
EBADUSER: 400,
|
||||
EBADEMAIL: 400,
|
||||
@@ -114,6 +125,9 @@ const STATUS = {
|
||||
ETOOMANY: 429,
|
||||
// S3: the Linux account could not be created/locked (the helper said why).
|
||||
EPROVISION: 502,
|
||||
ENOS3: 409,
|
||||
// A member's tmux server that would not stop: root has to kill it.
|
||||
ETMUXSTUCK: 409,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -290,6 +304,73 @@ router.delete(
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* Restart one member's tmux server (every pane of theirs ends, so the next
|
||||
* start runs the installed tmux) — the admin's password again, audited.
|
||||
*/
|
||||
router.post(
|
||||
"/:id/tmux-restart",
|
||||
accountChange(async (req) => {
|
||||
const u = target(req);
|
||||
const r = require("../lib/member-tmux").restart(u);
|
||||
return {
|
||||
user: auth.publicUser(u),
|
||||
action: r.restarted
|
||||
? `${u.username}: tmux restarted (was ${r.before.version || "?"}, ${r.before.sessions ?? "?"} session(s))`
|
||||
: `${u.username}: tmux restart — no server was running`,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* Restart the tmux server of every member running an older tmux than the
|
||||
* installed one while no agent of theirs works. One password, one audit
|
||||
* entry per member restarted.
|
||||
*/
|
||||
router.post("/tmux-restart-idle", async (req, res) => {
|
||||
try {
|
||||
if (!auth.isServerMode() || !req.user) {
|
||||
throw Object.assign(new Error("accounts are managed in server mode only"), {
|
||||
code: "ELOCALMODE",
|
||||
});
|
||||
}
|
||||
const body = req.body && typeof req.body === "object" ? req.body : {};
|
||||
await auth.confirmPassword(req.user, body.currentPassword);
|
||||
const mt = require("../lib/member-tmux");
|
||||
const all = db.prepare("SELECT * FROM users ORDER BY id").all();
|
||||
const rows = mt.overview(all.map(auth.publicUser)).users;
|
||||
const restarted = [];
|
||||
const skipped = [];
|
||||
const failed = [];
|
||||
for (const row of rows) {
|
||||
if (!row.outdated) continue;
|
||||
if (row.busy > 0) {
|
||||
skipped.push(row.username);
|
||||
continue;
|
||||
}
|
||||
const u = all.find((x) => x.id === row.id);
|
||||
try {
|
||||
const r = mt.restart(u);
|
||||
if (!r.restarted) continue;
|
||||
restarted.push(row.username);
|
||||
recordAccountChange(
|
||||
req.user.id,
|
||||
u.id,
|
||||
"POST",
|
||||
`${u.username}: tmux restarted (idle, was ${row.version})`
|
||||
);
|
||||
} catch (e) {
|
||||
failed.push({ username: row.username, message: e.message });
|
||||
}
|
||||
}
|
||||
res.json({ restarted, skipped, failed });
|
||||
} catch (err) {
|
||||
const status = STATUS[err.code];
|
||||
if (!status) return res.status(500).json({ error: { message: err.message } });
|
||||
res.status(status).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
});
|
||||
|
||||
router.post(
|
||||
"/:id/password",
|
||||
accountChange(async (req, body) => {
|
||||
|
||||
Reference in New Issue
Block a user