Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7a88b74016 | |||
| 8ed5018a2f | |||
| aacd63b85b | |||
| 22de5009ff |
+6
-2
@@ -4232,7 +4232,7 @@ async function cmdCodexAccounts(sub, name, flags) {
|
||||
}
|
||||
pool.resetQuota();
|
||||
table(
|
||||
["codex account", "kind", "live", "$ 5h", "$ 7d", "quota", "state"],
|
||||
["codex account", "kind", "live", "$ 5h", "$ 7d", "tok 5h", "tok 7d", "quota", "state"],
|
||||
pool
|
||||
.poolStatus()
|
||||
.map((a) => [
|
||||
@@ -4241,6 +4241,8 @@ async function cmdCodexAccounts(sub, name, flags) {
|
||||
a.livePanes,
|
||||
a.spend5h.toFixed(2),
|
||||
a.spend7d.toFixed(2),
|
||||
a.tokens5h,
|
||||
a.tokens7d,
|
||||
a.quota
|
||||
? a.quota.windows.map((w) => `${w.label} ${Math.round(w.usedPercent)}%`).join(" ")
|
||||
: "–",
|
||||
@@ -4281,7 +4283,7 @@ async function cmdAccounts(sub, positional, flags = {}) {
|
||||
await pool.refreshQuotas({ force: true });
|
||||
const pct = (w) => (w?.utilization != null ? `${Math.round(w.utilization)}%` : "–");
|
||||
table(
|
||||
["account", "live", "$ 5h", "$ 7d", "quota 5h", "quota wk", "state"],
|
||||
["account", "live", "$ 5h", "$ 7d", "tok 5h", "tok 7d", "quota 5h", "quota wk", "state"],
|
||||
pool
|
||||
.poolStatus()
|
||||
.map((a) => [
|
||||
@@ -4289,6 +4291,8 @@ async function cmdAccounts(sub, positional, flags = {}) {
|
||||
a.livePanes,
|
||||
a.spend5h.toFixed(2),
|
||||
a.spend7d.toFixed(2),
|
||||
a.tokens5h,
|
||||
a.tokens7d,
|
||||
pct(a.quota?.fiveHour),
|
||||
pct(a.quota?.sevenDay),
|
||||
a.expired
|
||||
|
||||
+19
-2
@@ -64,6 +64,7 @@ import { GlobalTooltip } from "./components/Tooltip";
|
||||
import { Toaster } from "./components/Toaster";
|
||||
import { ConfirmHost } from "./components/ConfirmHost";
|
||||
import { RouteErrorBoundary, reloadOnce } from "./components/RouteErrorBoundary";
|
||||
import { usePermissions } from "./components/AuthGate";
|
||||
import { NotFound } from "./pages/NotFound";
|
||||
import { useWebSocket } from "./hooks/useWebSocket";
|
||||
import { useNotifications } from "./hooks/useNotifications";
|
||||
@@ -89,6 +90,7 @@ const SnapshotView = lazy(() =>
|
||||
);
|
||||
const FilesPage = lazy(() => import("./pages/FilesPage").then((m) => ({ default: m.FilesPage })));
|
||||
const Users = lazy(() => import("./pages/Users").then((m) => ({ default: m.Users })));
|
||||
const Artifacts = lazy(() => import("./pages/Artifacts").then((m) => ({ default: m.Artifacts })));
|
||||
|
||||
function PageFallback() {
|
||||
const { t } = useTranslation();
|
||||
@@ -108,6 +110,11 @@ function Page({ children }: { children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** A page only a shared server needs (the File Explorer): local mode goes home. */
|
||||
function ServerOnly({ children }: { children: ReactNode }) {
|
||||
return usePermissions().local ? <Navigate to="/" replace /> : <>{children}</>;
|
||||
}
|
||||
|
||||
/** Keyed by the id so moving to another session starts from fresh state. */
|
||||
function SessionDetailRoute() {
|
||||
const { id } = useParams();
|
||||
@@ -212,13 +219,23 @@ export default function App() {
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="files"
|
||||
path="artifacts"
|
||||
element={
|
||||
<Page>
|
||||
<FilesPage />
|
||||
<Artifacts />
|
||||
</Page>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="files"
|
||||
element={
|
||||
<ServerOnly>
|
||||
<Page>
|
||||
<FilesPage />
|
||||
</Page>
|
||||
</ServerOnly>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="users"
|
||||
element={
|
||||
|
||||
@@ -63,6 +63,10 @@ export function usePermissions() {
|
||||
const isAdmin = local || user?.role === "admin";
|
||||
return {
|
||||
isAdmin,
|
||||
// Local mode: one person on their own machine — what only serves a
|
||||
// shared server (File Explorer, uploads, AgentHub's own git logins) is
|
||||
// hidden; their desktop and their own git config already do it.
|
||||
local,
|
||||
seesAll: local || (!!user && user.role !== "developer"),
|
||||
// A developer only ever sees their own rows, so everything shown is theirs.
|
||||
canEditLane: (lane?: { owner_id?: number | null } | null) =>
|
||||
|
||||
@@ -149,15 +149,21 @@ export function usePrefersReducedMotion(): boolean {
|
||||
* changes via ResizeObserver) so a tall panel near a screen edge slides fully
|
||||
* into view instead of being cropped.
|
||||
*/
|
||||
/** `front`: above the mascot itself — the pet menu, which may overlap it. */
|
||||
/**
|
||||
* `front`: above the mascot itself — the pet menu, which may overlap it.
|
||||
* `beside`: at the mascot's side instead of above it — the chat window, on the
|
||||
* screen side away from the edge it docks to, its bottom level with the pet's.
|
||||
*/
|
||||
function SagiFlyout({
|
||||
anchor,
|
||||
children,
|
||||
front = false,
|
||||
beside = false,
|
||||
}: {
|
||||
anchor: Anchor;
|
||||
children: ReactNode;
|
||||
front?: boolean;
|
||||
beside?: boolean;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [style, setStyle] = useState<CSSProperties>({ visibility: "hidden" });
|
||||
@@ -170,6 +176,18 @@ function SagiFlyout({
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
|
||||
if (beside) {
|
||||
let left =
|
||||
anchor.side === "left"
|
||||
? anchor.left + anchor.size + FLYOUT_GAP
|
||||
: anchor.left - w - FLYOUT_GAP;
|
||||
left = Math.min(vw - w - VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, left));
|
||||
let top = anchor.top + anchor.size - h;
|
||||
top = Math.min(vh - h - VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, top));
|
||||
setStyle({ left, top, visibility: "visible" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Horizontal: hug the avatar's docked edge, then clamp on-screen.
|
||||
let left = anchor.side === "left" ? anchor.left : anchor.left + anchor.size - w;
|
||||
left = Math.min(vw - w - VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, left));
|
||||
@@ -182,7 +200,7 @@ function SagiFlyout({
|
||||
top = Math.min(vh - h - VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, top));
|
||||
|
||||
setStyle({ left, top, visibility: "visible" });
|
||||
}, [anchor.left, anchor.top, anchor.size, anchor.side, anchor.openUp]);
|
||||
}, [anchor.left, anchor.top, anchor.size, anchor.side, anchor.openUp, beside]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
place();
|
||||
@@ -431,37 +449,32 @@ function SagiBody() {
|
||||
onClearAlerts={brain.clearAlerts}
|
||||
onNavigate={onNavigate}
|
||||
onAsk={onAsk}
|
||||
onOpenChat={() => {
|
||||
setOpen(false);
|
||||
setChatOpen(true);
|
||||
}}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</SagiFlyout>
|
||||
)}
|
||||
|
||||
{/* Kept mounted while dragging (only hidden): unmounting would detach
|
||||
its terminal and lose a half-typed message. */}
|
||||
{/* Beside the pet, riding along with it mid-drag too (SagiFlyout follows
|
||||
it 1:1), and kept mounted: unmounting would detach its terminal and
|
||||
lose a half-typed message. */}
|
||||
{chatOpen && (
|
||||
<div style={place.dragging ? { display: "none" } : undefined}>
|
||||
<SagiFlyout anchor={anchor}>
|
||||
<PetChat
|
||||
name={name}
|
||||
initialPrompt={chatPrompt}
|
||||
onPromptTaken={() => setChatPrompt(null)}
|
||||
onBack={() => {
|
||||
setChatOpen(false);
|
||||
setOpen(true);
|
||||
}}
|
||||
onClose={() => setChatOpen(false)}
|
||||
onOpenWorkspace={(laneId, runId) => {
|
||||
navigate(`/workspace?lane=${laneId}&run=${encodeURIComponent(runId)}`);
|
||||
setChatOpen(false);
|
||||
}}
|
||||
onBusy={onBusy}
|
||||
/>
|
||||
</SagiFlyout>
|
||||
</div>
|
||||
<SagiFlyout anchor={anchor} beside>
|
||||
<PetChat
|
||||
name={name}
|
||||
initialPrompt={chatPrompt}
|
||||
onPromptTaken={() => setChatPrompt(null)}
|
||||
onBack={() => {
|
||||
setChatOpen(false);
|
||||
setOpen(true);
|
||||
}}
|
||||
onClose={() => setChatOpen(false)}
|
||||
onOpenWorkspace={(laneId, runId) => {
|
||||
navigate(`/workspace?lane=${laneId}&run=${encodeURIComponent(runId)}`);
|
||||
setChatOpen(false);
|
||||
}}
|
||||
onBusy={onBusy}
|
||||
/>
|
||||
</SagiFlyout>
|
||||
)}
|
||||
|
||||
{!place.dragging && menu && (
|
||||
|
||||
@@ -60,7 +60,6 @@ import {
|
||||
Radio,
|
||||
Heart,
|
||||
ChevronRight,
|
||||
MessageCircle,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -89,8 +88,6 @@ interface SagiPanelProps {
|
||||
onNavigate: (route: string) => void;
|
||||
/** Returns an answer to display, or null when the query was handed off. */
|
||||
onAsk: (query: string) => string | null;
|
||||
/** Opens the chat window (PetChat). */
|
||||
onOpenChat: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -108,7 +105,6 @@ export function SagiPanel({
|
||||
onClearAlerts,
|
||||
onNavigate,
|
||||
onAsk,
|
||||
onOpenChat,
|
||||
onClose,
|
||||
}: SagiPanelProps) {
|
||||
const { t } = useTranslation("settings");
|
||||
@@ -282,13 +278,6 @@ export function SagiPanel({
|
||||
|
||||
{/* quick actions */}
|
||||
<div className="mb-3 grid grid-cols-2 gap-1.5">
|
||||
<div className="col-span-2">
|
||||
<ActionButton
|
||||
icon={MessageCircle}
|
||||
label={t("sagi.panel.chat", { name })}
|
||||
onClick={onOpenChat}
|
||||
/>
|
||||
</div>
|
||||
<ActionButton
|
||||
icon={muted ? BellOff : Bell}
|
||||
label={muted ? t("sagi.panel.unmute") : t("sagi.panel.mute")}
|
||||
|
||||
@@ -144,10 +144,14 @@ describe("Sagi widget", () => {
|
||||
expect(screen.queryByRole("dialog", { name: /sagi companion/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the chat from the panel and goes back to it", () => {
|
||||
it("has no Chat button — Ask opens the chat — and Back returns to the panel", () => {
|
||||
localStorage.setItem("agenthub.defaultTool", "claude");
|
||||
renderSagi();
|
||||
fireEvent.click(screen.getByRole("button", { name: /open sagi companion/i }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /chat with sagi/i }));
|
||||
expect(screen.queryByRole("button", { name: /chat with sagi/i })).not.toBeInTheDocument();
|
||||
const input = screen.getByLabelText(/ask sagi/i);
|
||||
fireEvent.change(input, { target: { value: "write me a haiku" } });
|
||||
fireEvent.submit(input.closest("form")!);
|
||||
expect(screen.getByRole("dialog", { name: /chat with sagi/i })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Back" }));
|
||||
expect(screen.getByRole("dialog", { name: /sagi companion/i })).toBeInTheDocument();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @file Sidebar.tsx
|
||||
* @description The app's left sidebar: the brand, the navigation links and the workspace list, with Settings (on a workspace, that workspace's Settings tab — `lib/settingsLink.ts`) and the collapse/expand button pinned to its foot. It also owns the connection details modal (opened from the status bar), which carries the version and the update check — the sidebar itself has no footer, language or theme controls (those live in Settings → General / Appearance). The collapsed state is kept in localStorage; with none stored it starts collapsed below Tailwind's `lg`. Below `md` the Layout turns it into an off-canvas drawer (`drawer` prop): a modal dialog with the shared `useDialog` focus contract.
|
||||
* @description The app's left sidebar: the brand, the navigation links and the workspace list, with Settings (on a workspace, that workspace's Settings tab — `lib/settingsLink.ts`) and the collapse/expand button pinned to its foot — in server mode with the signed-in account above them (its avatar, name and role, linking to Settings → Account, and Log out). It also owns the connection details modal (opened from the status bar), which carries the version and the update check — the sidebar itself has no footer, language or theme controls (those live in Settings → General / Appearance). The collapsed state is kept in localStorage; with none stored it starts collapsed below Tailwind's `lg`. Below `md` the Layout turns it into an off-canvas drawer (`drawer` prop): a modal dialog with the shared `useDialog` focus contract.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
/* =============================================================================
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
LayoutDashboard,
|
||||
FolderOpen,
|
||||
HardDrive,
|
||||
Gem,
|
||||
BarChart3,
|
||||
Settings,
|
||||
Wifi,
|
||||
@@ -78,6 +79,7 @@ import type { LucideIcon } from "lucide-react";
|
||||
import { api } from "../lib/api";
|
||||
import { BRAND_LOGO, BRAND_MARK } from "../lib/brand";
|
||||
import { useAuth, usePermissions } from "./AuthGate";
|
||||
import { UserAvatar } from "./users/UserAvatar";
|
||||
import { eventBus } from "../lib/eventBus";
|
||||
import { WorkspaceTree } from "./WorkspaceTree";
|
||||
import type { UpdateStatusPayload, WSMessage } from "../lib/types";
|
||||
@@ -91,6 +93,8 @@ const NAV_KEYS = [
|
||||
{ to: "/sessions", icon: FolderOpen, key: "nav:sessions" },
|
||||
// The file manager (FilesPage): browse, upload and download workspace files.
|
||||
{ to: "/files", icon: HardDrive, key: "nav:files" },
|
||||
// What agents produced, and (server mode) the Hub others shared (Artifacts.tsx).
|
||||
{ to: "/artifacts", icon: Gem, key: "nav:artifacts" },
|
||||
] as const;
|
||||
|
||||
const STORAGE_KEY = "sidebar-collapsed";
|
||||
@@ -197,7 +201,8 @@ export function Sidebar({
|
||||
location.pathname.startsWith("/settings") ||
|
||||
new URLSearchParams(location.search).has("settings");
|
||||
// Checking for (and applying) an update acts on the host: an admin's.
|
||||
const canUpdate = usePermissions().isAdmin;
|
||||
const perms = usePermissions();
|
||||
const canUpdate = perms.isAdmin;
|
||||
const asideRef = useRef<HTMLElement>(null);
|
||||
const drawerOpen = Boolean(drawer?.open);
|
||||
useDialog(drawerOpen, asideRef, drawer?.onClose);
|
||||
@@ -472,7 +477,8 @@ export function Sidebar({
|
||||
<div className="flex-1 min-h-0 relative flex">
|
||||
<nav ref={navRef} className="flex-1 overflow-y-auto overflow-x-hidden px-2 py-2 space-y-px">
|
||||
{[
|
||||
...NAV_KEYS,
|
||||
// The file manager serves a shared server; locally it is the desktop's.
|
||||
...NAV_KEYS.filter((n) => !(perms.local && n.to === "/files")),
|
||||
// Server mode: the Users page, for an admin or analyst.
|
||||
...(auth.state.mode === "server" &&
|
||||
auth.state.user &&
|
||||
@@ -535,6 +541,59 @@ export function Sidebar({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Server mode: who is signed in — avatar, name and role, opening
|
||||
Settings → Account — and Log out. On the rail they stack. */}
|
||||
{auth.state.mode === "server" &&
|
||||
auth.state.user &&
|
||||
(() => {
|
||||
const user = auth.state.user;
|
||||
const name = user.displayName || user.username;
|
||||
const role = t(`users:roles.${user.role}`);
|
||||
const signedIn = t("common:auth.signedInAs", { name, role });
|
||||
return (
|
||||
<div
|
||||
data-testid="sidebar-account"
|
||||
className={`flex flex-shrink-0 gap-1 border-t border-border px-2 py-2 ${
|
||||
collapsed ? "flex-col items-center" : "items-center"
|
||||
}`}
|
||||
>
|
||||
<NavLink
|
||||
to={settingsHref("account", location)}
|
||||
title={signedIn}
|
||||
aria-label={signedIn}
|
||||
className={`flex min-w-0 items-center gap-2 rounded-md transition-colors hover:bg-surface-3 ${
|
||||
collapsed ? "justify-center p-1" : "flex-1 px-1.5 py-1"
|
||||
}`}
|
||||
>
|
||||
<UserAvatar
|
||||
name={name}
|
||||
avatarAt={user.avatarAt}
|
||||
className={collapsed ? "h-7 w-7 text-[11px]" : "h-8 w-8 text-xs"}
|
||||
/>
|
||||
{!collapsed && (
|
||||
<span className="min-w-0 leading-tight">
|
||||
<span className="block truncate text-sm font-medium text-fg-primary">
|
||||
{name}
|
||||
</span>
|
||||
<span className="block truncate text-[11px] text-fg-muted">{role}</span>
|
||||
</span>
|
||||
)}
|
||||
</NavLink>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void auth.logout()}
|
||||
title={`${signedIn} — ${t("common:auth.logout")}`}
|
||||
aria-label={t("common:auth.logout")}
|
||||
className={`inline-flex items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-3 hover:text-fg-primary ${
|
||||
collapsed ? "w-full py-2" : "h-8 w-8 flex-shrink-0"
|
||||
}`}
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Settings and the collapse toggle stick to the foot, out of the
|
||||
scrolling nav. On the rail they stack. */}
|
||||
<div
|
||||
@@ -550,22 +609,6 @@ export function Sidebar({
|
||||
<Settings className="w-4 h-4 flex-shrink-0" />
|
||||
{!collapsed && <span>{t("nav:settings")}</span>}
|
||||
</NavLink>
|
||||
{auth.state.mode === "server" && auth.state.user && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void auth.logout()}
|
||||
title={`${t("common:auth.signedInAs", {
|
||||
name: auth.state.user.displayName || auth.state.user.username,
|
||||
role: auth.state.user.role,
|
||||
})} — ${t("common:auth.logout")}`}
|
||||
aria-label={t("common:auth.logout")}
|
||||
className={`inline-flex items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-3 hover:text-fg-primary ${
|
||||
collapsed ? "py-2" : "h-8 w-8 flex-shrink-0"
|
||||
}`}
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
* Workspace page's own poll (`LIVE_RUNS_EVENT`). Owns its own Add-workspace and
|
||||
* destructive modals (lazy-loaded on first open) so the row menu works from any page. Which rows are
|
||||
* expanded lives in `projectTreePrefs.ts` (`expanded`). Server mode, admin or
|
||||
* analyst: EVERY workspace, grouped under its owner (`owner_display_name`,
|
||||
* else `owner_name`; yours
|
||||
* analyst: EVERY workspace, grouped under its owner (their avatar —
|
||||
* `owner_avatar_at`, `UserAvatar` — and `owner_display_name`, else `owner_name`; yours
|
||||
* first, no owner last, groups foldable — `collapsedOwners`); one this user
|
||||
* may not change (`canEditLane`) is read only — no menu, no new session, and a
|
||||
* session opens its analysis page (`/sessions/<id>`), never a pane.
|
||||
@@ -49,6 +49,7 @@ import { useProjectTreePrefs, writeProjectTreePrefs } from "../lib/projectTreePr
|
||||
import { LANE_DRAG_TYPE, WorkspaceRow, isLaneDrag, workspaceName } from "./lanes/WorkspaceRow";
|
||||
import { WorkspaceSessionList } from "./lanes/WorkspaceSessionList";
|
||||
import { WorkspaceRowMenu, type WorkspaceMenuAction } from "./lanes/WorkspaceRowMenu";
|
||||
import { UserAvatar } from "./users/UserAvatar";
|
||||
|
||||
// The sidebar is in the entry chunk; its two modals (and the run form the add
|
||||
// modal pulls in) load when first opened.
|
||||
@@ -366,12 +367,14 @@ export function WorkspaceTree() {
|
||||
) : (
|
||||
<ChevronDown className="h-3 w-3 shrink-0" />
|
||||
)}
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-surface-4 text-[9px] font-semibold uppercase text-fg-secondary"
|
||||
>
|
||||
{ownerShown(lane)[0] ?? "?"}
|
||||
</span>
|
||||
<UserAvatar
|
||||
name={ownerShown(lane) || "?"}
|
||||
userId={lane.owner_id ?? undefined}
|
||||
avatarAt={lane.owner_avatar_at}
|
||||
letters={1}
|
||||
className="h-4 w-4 text-[9px]"
|
||||
initialsClassName="bg-surface-4 text-fg-secondary"
|
||||
/>
|
||||
<span className="truncate">{ownerLabel}</span>
|
||||
<span className="ml-auto shrink-0 tabular-nums">
|
||||
{sorted.filter((l) => ownerKey(l) === owner).length}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* @file Sidebar.account.test.tsx
|
||||
* @description The sidebar's account row (server mode): the signed-in user's
|
||||
* avatar — or initials without one — name and role, linking to Settings →
|
||||
* Account, beside Sign out; local mode shows no row.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
|
||||
const auth = vi.hoisted(() => ({
|
||||
state: { mode: "local" } as Record<string, unknown>,
|
||||
logout: vi.fn(),
|
||||
updateUser: vi.fn(),
|
||||
}));
|
||||
vi.mock("../AuthGate", () => ({
|
||||
useAuth: () => auth,
|
||||
usePermissions: () => ({
|
||||
isAdmin: auth.state.mode !== "server",
|
||||
local: auth.state.mode !== "server",
|
||||
seesAll: true,
|
||||
canEditLane: () => true,
|
||||
}),
|
||||
}));
|
||||
|
||||
import { Sidebar } from "../Sidebar";
|
||||
|
||||
const renderSidebar = (collapsed = false) =>
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Sidebar
|
||||
wsConnected
|
||||
collapsed={collapsed}
|
||||
onToggle={() => {}}
|
||||
connectionOpen={false}
|
||||
onConnectionOpenChange={() => {}}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
describe("Sidebar account row", () => {
|
||||
it("shows the avatar, name and role, linking to Settings → Account", () => {
|
||||
auth.state = {
|
||||
mode: "server",
|
||||
user: { id: 2, username: "mia", role: "developer", displayName: "Mia Tran", avatarAt: "t1" },
|
||||
};
|
||||
renderSidebar();
|
||||
const row = screen.getByTestId("sidebar-account");
|
||||
expect(row.textContent).toContain("Mia Tran");
|
||||
expect(row.textContent).toContain("Developer");
|
||||
expect(within(row).getByTestId("user-avatar-img").getAttribute("src")).toBe(
|
||||
"/api/me/avatar?v=t1"
|
||||
);
|
||||
expect(within(row).getAllByRole("link")[0]?.getAttribute("href")).toBe("/settings/account");
|
||||
expect(within(row).getByRole("button", { name: "Sign out" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("falls back to initials, and keeps only the avatar on the rail", () => {
|
||||
auth.state = { mode: "server", user: { id: 3, username: "leo", role: "admin" } };
|
||||
renderSidebar(true);
|
||||
const row = screen.getByTestId("sidebar-account");
|
||||
expect(within(row).getByTestId("user-avatar-initials").textContent).toBe("le");
|
||||
expect(row.textContent).not.toContain("Admin");
|
||||
});
|
||||
|
||||
it("has no account row in local mode", () => {
|
||||
auth.state = { mode: "local" };
|
||||
renderSidebar();
|
||||
expect(screen.queryByTestId("sidebar-account")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -95,6 +95,8 @@ describe("Sidebar", () => {
|
||||
expect(hrefs).toContain("/sessions");
|
||||
expect(hrefs).toContain("/settings");
|
||||
expect(hrefs).not.toContain("/activity");
|
||||
// The file manager serves a shared server; a local dashboard has none.
|
||||
expect(hrefs).not.toContain("/files");
|
||||
});
|
||||
|
||||
describe("update status line, in the connection details modal", () => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* @file WorkspaceTree.owners.test.tsx
|
||||
* @description Server mode, the sidebar workspace list for an analyst: every
|
||||
* user's workspaces, grouped under their owner (yours first, no owner last),
|
||||
* user's workspaces, grouped under their owner (with their avatar, else an
|
||||
* initial; yours first, no owner last),
|
||||
* groups folding and remembered; another user's workspace is read only — no
|
||||
* menu, no new session, and a session opens its analysis page, never a pane.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
@@ -30,7 +31,11 @@ const lane = (id: number, owner: number | null, name: string | null, title: stri
|
||||
}) as unknown as Lane;
|
||||
|
||||
const lanes = [
|
||||
{ ...lane(1, 3, "bob", "Bob app"), owner_display_name: "Bob Nguyen" } as Lane,
|
||||
{
|
||||
...lane(1, 3, "bob", "Bob app"),
|
||||
owner_display_name: "Bob Nguyen",
|
||||
owner_avatar_at: "t1",
|
||||
} as Lane,
|
||||
lane(2, null, null, "Old"),
|
||||
lane(3, ME.id, "ana", "Mine"),
|
||||
lane(4, 1, "admin", "Admin site"),
|
||||
@@ -61,6 +66,11 @@ vi.mock("../../lib/api", async (importOriginal) => {
|
||||
})),
|
||||
},
|
||||
run: { list: vi.fn(async () => ({ items: [] })) },
|
||||
users: {
|
||||
avatarUrl: (id: number, at?: string | null) =>
|
||||
at ? `/api/users/${id}/avatar?v=${at}` : null,
|
||||
},
|
||||
me: { avatarUrl: () => null },
|
||||
aiTools: { list: vi.fn(async () => ({ tools: [], default: "claude" })), iconUrl: () => "" },
|
||||
},
|
||||
};
|
||||
@@ -118,6 +128,15 @@ describe("WorkspaceTree for an analyst", () => {
|
||||
await screen.findByTestId("workspace-row-1");
|
||||
expect(screen.getByTestId("workspace-owner-3")).toHaveTextContent("Bob Nguyen");
|
||||
expect(screen.getByTestId("workspace-owner-3")).not.toHaveTextContent("bob");
|
||||
// Bob set a picture: shown beside the name; Ana did not: her initial.
|
||||
expect(
|
||||
within(screen.getByTestId("workspace-owner-3"))
|
||||
.getByTestId("user-avatar-img")
|
||||
.getAttribute("src")
|
||||
).toBe("/api/users/3/avatar?v=t1");
|
||||
expect(
|
||||
within(screen.getByTestId("workspace-owner-2")).getByTestId("user-avatar-initials")
|
||||
).toHaveTextContent("a");
|
||||
expect(screen.getByTestId("workspace-owner-1")).toHaveTextContent("admin");
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,928 @@
|
||||
/**
|
||||
* @file ArtifactAddPanels.tsx
|
||||
* @description The Artifacts page's Add dialogs for a skill, a plugin and an
|
||||
* uploaded file (server/lib/artifacts.js):
|
||||
* - `SkillAddPanel` — three ways to make a skill: **Upload** (one Markdown
|
||||
* file that becomes SKILL.md, several files, a whole folder — picked or
|
||||
* dropped — or a .zip/.skill; an upload holding several skills makes one
|
||||
* artifact each), **Write** (name, description, instructions) and
|
||||
* **Existing** (a folder in the user's ~/.claude/skills or a workspace's
|
||||
* .claude/skills). The user names the skill; the name is previewed as the
|
||||
* folder and `/command` it installs as (`skillSlug`, the server's rule).
|
||||
* - `PluginAddPanel` — paste a marketplace link (a git https link, a forge
|
||||
* web link, `owner/repo` or a marketplace.json link), read its plugin list
|
||||
* and tick the ones to add; or type `name@marketplace` by hand, which is
|
||||
* also where a link the server cannot read (ssh, a private repo) ends up.
|
||||
* - `FileUploadPanel` — one file from the user's computer (≤ 25 MB).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState, type DragEvent } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FileText, FolderOpen, Package, Sparkles, Upload, X } from "lucide-react";
|
||||
import { api, type MarketplaceInfo } from "../../lib/api";
|
||||
import type { Lane } from "../../lib/types";
|
||||
import { toast } from "../../lib/toast";
|
||||
|
||||
const field = "w-full rounded border border-border bg-surface-1 px-2 py-1 text-sm text-fg-primary";
|
||||
const label = "block text-[11px] font-medium text-fg-secondary";
|
||||
const hint = "text-[11px] text-fg-muted";
|
||||
|
||||
/** The server's skill folder rule (server/lib/artifacts.js `skillSlug`). */
|
||||
export function skillSlug(text: string): string {
|
||||
return text
|
||||
.normalize("NFD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.replace(/đ/g, "d")
|
||||
.replace(/Đ/g, "D")
|
||||
.replace(/[^A-Za-z0-9._-]+/g, "-")
|
||||
.replace(/^[-._]+|-+$/g, "")
|
||||
.slice(0, 100);
|
||||
}
|
||||
|
||||
/** `field:` of a Markdown file's frontmatter, or "". */
|
||||
export function frontmatterField(text: string, name: string): string {
|
||||
const fm = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(text);
|
||||
if (!fm) return "";
|
||||
const m = new RegExp(`^${name}:\\s*(.*)$`, "m").exec(fm[1] ?? "");
|
||||
return (m?.[1] ?? "").trim().replace(/^(["'])(.*)\1$/, "$2");
|
||||
}
|
||||
|
||||
type Picked = { file: File; path: string };
|
||||
|
||||
/** A small file's text ("" on failure), only to prefill the name/description. */
|
||||
function readText(file: File): Promise<string> {
|
||||
if (file.size > 1024 * 1024) return Promise.resolve("");
|
||||
return new Promise((ok) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => ok(typeof r.result === "string" ? r.result : "");
|
||||
r.onerror = () => ok("");
|
||||
r.readAsText(file);
|
||||
});
|
||||
}
|
||||
|
||||
const JUNK = /(^|\/)(__MACOSX|\.DS_Store|Thumbs\.db|desktop\.ini|\.git|node_modules)(\/|$)/;
|
||||
const isSkillMd = (p: string) => /(^|\/)skill\.md$/i.test(p);
|
||||
const isArchive = (p: string) => /\.(zip|skill)$/i.test(p);
|
||||
const isText = (p: string) => /\.(md|markdown|txt)$/i.test(p);
|
||||
|
||||
/** Every file under what was dropped, folders walked (webkitGetAsEntry). */
|
||||
async function droppedFiles(e: DragEvent): Promise<Picked[]> {
|
||||
const items = Array.from(e.dataTransfer.items || []);
|
||||
const entries = items
|
||||
.map((i) => (i.webkitGetAsEntry ? i.webkitGetAsEntry() : null))
|
||||
.filter((x): x is FileSystemEntry => !!x);
|
||||
if (!entries.length) {
|
||||
return Array.from(e.dataTransfer.files).map((file) => ({ file, path: file.name }));
|
||||
}
|
||||
const out: Picked[] = [];
|
||||
const walk = async (entry: FileSystemEntry, prefix: string): Promise<void> => {
|
||||
if (entry.isFile) {
|
||||
const file = await new Promise<File>((ok, fail) =>
|
||||
(entry as FileSystemFileEntry).file(ok, fail)
|
||||
);
|
||||
out.push({ file, path: prefix + entry.name });
|
||||
return;
|
||||
}
|
||||
const reader = (entry as FileSystemDirectoryEntry).createReader();
|
||||
// readEntries answers in batches until an empty one.
|
||||
for (;;) {
|
||||
const batch = await new Promise<FileSystemEntry[]>((ok, fail) =>
|
||||
reader.readEntries(ok, fail)
|
||||
);
|
||||
if (!batch.length) break;
|
||||
for (const child of batch) await walk(child, `${prefix}${entry.name}/`);
|
||||
}
|
||||
};
|
||||
for (const entry of entries) await walk(entry, "");
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What an upload will make, guessed the way the server decides it. */
|
||||
function describeUpload(files: Picked[]): {
|
||||
kind: "none" | "single-md" | "archive" | "one" | "many" | "no-skill-md";
|
||||
count: number;
|
||||
folder: string;
|
||||
} {
|
||||
const real = files.filter((f) => !JUNK.test(f.path));
|
||||
if (!real.length) return { kind: "none", count: 0, folder: "" };
|
||||
if (real.length === 1 && isArchive(real[0]!.path))
|
||||
return { kind: "archive", count: 0, folder: "" };
|
||||
const roots = [
|
||||
...new Set(
|
||||
real.filter((f) => isSkillMd(f.path)).map((f) => f.path.split("/").slice(0, -1).join("/"))
|
||||
),
|
||||
].sort((a, b) => a.length - b.length);
|
||||
const under = (dir: string, p: string) => dir === "" || p === dir || p.startsWith(`${dir}/`);
|
||||
const top = roots.filter((r, i) => !roots.slice(0, i).some((o) => under(o, r)));
|
||||
if (!top.length) {
|
||||
return real.length === 1 && isText(real[0]!.path)
|
||||
? { kind: "single-md", count: 1, folder: "" }
|
||||
: { kind: "no-skill-md", count: 0, folder: "" };
|
||||
}
|
||||
if (top.length === 1) return { kind: "one", count: 1, folder: top[0]!.split("/").pop() ?? "" };
|
||||
return { kind: "many", count: top.length, folder: "" };
|
||||
}
|
||||
|
||||
function Tabs<T extends string>({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
value: T;
|
||||
options: { id: T; label: string }[];
|
||||
onChange: (v: T) => void;
|
||||
}) {
|
||||
return (
|
||||
<div role="tablist" className="flex rounded border border-border bg-surface-2 p-0.5">
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={value === o.id}
|
||||
onClick={() => onChange(o.id)}
|
||||
className={`flex-1 rounded px-2 py-1 text-xs ${
|
||||
value === o.id
|
||||
? "bg-accent-solid text-white"
|
||||
: "text-fg-secondary hover:bg-surface-3 hover:text-fg-primary"
|
||||
}`}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The name field with the folder/command it becomes. */
|
||||
function SkillNameField({
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
required,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
disabled?: boolean;
|
||||
required?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const slug = skillSlug(value);
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
<label className={label}>
|
||||
{t("skill.name")}
|
||||
{required ? " *" : ""}
|
||||
<input
|
||||
className={`${field} mt-0.5`}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
placeholder="release-notes"
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{value.trim() && (
|
||||
<p className={hint} data-testid="skill-slug">
|
||||
{slug ? t("skill.slugHint", { slug }) : t("skill.slugBad")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Skill ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function SkillAddPanel({
|
||||
lanes,
|
||||
onAdded,
|
||||
onClose,
|
||||
}: {
|
||||
lanes: Lane[];
|
||||
onAdded: () => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [mode, setMode] = useState<"upload" | "write" | "existing">("upload");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [nameTouched, setNameTouched] = useState(false);
|
||||
const [description, setDescription] = useState("");
|
||||
const [descTouched, setDescTouched] = useState(false);
|
||||
const [title, setTitle] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [files, setFiles] = useState<Picked[]>([]);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [laneId, setLaneId] = useState<number | null>(null);
|
||||
const [skills, setSkills] = useState<{ name: string; from: "user" | "workspace" }[] | null>(null);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const folderInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
// `webkitdirectory` is not in React's typings.
|
||||
useEffect(() => {
|
||||
folderInput.current?.setAttribute("webkitdirectory", "");
|
||||
}, [mode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode !== "existing") return;
|
||||
api.artifacts
|
||||
.skills(laneId ?? undefined)
|
||||
.then((r) => setSkills(r.items))
|
||||
.catch(() => setSkills([]));
|
||||
}, [mode, laneId]);
|
||||
|
||||
const shape = useMemo(() => describeUpload(files), [files]);
|
||||
|
||||
// Fill the name and description from what was picked, unless typed.
|
||||
useEffect(() => {
|
||||
if (!files.length) return;
|
||||
const md =
|
||||
files.find((f) => isSkillMd(f.path) && !JUNK.test(f.path)) ??
|
||||
(shape.kind === "single-md" ? files.find((f) => !JUNK.test(f.path)) : undefined);
|
||||
const stem = (p: string) => (p.split("/").pop() ?? "").replace(/\.[^.]+$/, "");
|
||||
let live = true;
|
||||
void (async () => {
|
||||
const text = md ? await readText(md.file) : "";
|
||||
if (!live) return;
|
||||
const fmName = frontmatterField(text, "name");
|
||||
const fmDesc = frontmatterField(text, "description");
|
||||
if (!nameTouched) {
|
||||
const guess =
|
||||
shape.kind === "single-md"
|
||||
? fmName || stem(md?.path ?? "")
|
||||
: shape.kind === "one"
|
||||
? fmName || shape.folder
|
||||
: shape.kind === "archive"
|
||||
? stem(files[0]!.path)
|
||||
: "";
|
||||
setName(guess);
|
||||
}
|
||||
if (!descTouched && fmDesc) setDescription(fmDesc);
|
||||
})();
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
// Refill only when the pick changes, never on a typed name.
|
||||
}, [files, shape]);
|
||||
|
||||
const pick = (list: FileList | null) => {
|
||||
if (!list?.length) return;
|
||||
setFiles(
|
||||
Array.from(list).map((file) => ({
|
||||
file,
|
||||
path: (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name,
|
||||
}))
|
||||
);
|
||||
};
|
||||
|
||||
const run = async (fn: () => Promise<number>) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const n = await fn();
|
||||
toast.success(n > 1 ? t("skill.addedMany", { count: n }) : t("added"));
|
||||
onAdded();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const many = shape.kind === "many";
|
||||
const total = files.reduce((n, f) => n + f.file.size, 0);
|
||||
const meta = (
|
||||
<>
|
||||
<label className={label}>
|
||||
{t("skill.description")}
|
||||
<textarea
|
||||
className={`${field} mt-0.5`}
|
||||
rows={2}
|
||||
value={description}
|
||||
disabled={many}
|
||||
placeholder={t("skill.descriptionHint")}
|
||||
onChange={(e) => {
|
||||
setDescTouched(true);
|
||||
setDescription(e.target.value);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className={label}>
|
||||
{t("form.title")}
|
||||
<input
|
||||
className={`${field} mt-0.5`}
|
||||
value={title}
|
||||
disabled={many}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Tabs
|
||||
value={mode}
|
||||
onChange={setMode}
|
||||
options={[
|
||||
{ id: "upload", label: t("skill.tab.upload") },
|
||||
{ id: "write", label: t("skill.tab.write") },
|
||||
{ id: "existing", label: t("skill.tab.existing") },
|
||||
]}
|
||||
/>
|
||||
|
||||
{mode === "upload" && (
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run(async () => {
|
||||
const r = await api.artifacts.uploadSkills(files, {
|
||||
name: many ? undefined : name.trim(),
|
||||
description: many ? undefined : description.trim(),
|
||||
title: many ? undefined : title.trim(),
|
||||
});
|
||||
return r.items.length;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div
|
||||
data-testid="skill-drop"
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragging(false);
|
||||
void droppedFiles(e).then((list) => list.length && setFiles(list));
|
||||
}}
|
||||
className={`rounded-lg border border-dashed p-4 text-center ${
|
||||
dragging ? "border-accent bg-accent/10" : "border-border"
|
||||
}`}
|
||||
>
|
||||
<Upload className="mx-auto mb-1 h-5 w-5 text-fg-muted" />
|
||||
<p className="text-xs text-fg-secondary">{t("skill.dropHint")}</p>
|
||||
<div className="mt-2 flex flex-wrap justify-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn-ghost text-xs"
|
||||
onClick={() => fileInput.current?.click()}
|
||||
>
|
||||
<FileText className="h-3.5 w-3.5" /> {t("skill.pickFiles")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-ghost text-xs"
|
||||
onClick={() => folderInput.current?.click()}
|
||||
>
|
||||
<FolderOpen className="h-3.5 w-3.5" /> {t("skill.pickFolder")}
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
multiple
|
||||
hidden
|
||||
data-testid="skill-files"
|
||||
onChange={(e) => {
|
||||
pick(e.target.files);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
ref={folderInput}
|
||||
type="file"
|
||||
multiple
|
||||
hidden
|
||||
data-testid="skill-folder"
|
||||
onChange={(e) => {
|
||||
pick(e.target.files);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{files.length > 0 && (
|
||||
<div className="rounded border border-border bg-surface-2 p-2">
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<p className="flex-1 text-xs text-fg-primary" data-testid="skill-shape">
|
||||
{t(`skill.shape.${shape.kind}`, { count: shape.count })}
|
||||
</p>
|
||||
<span className={hint}>
|
||||
{t("files", { count: files.length })} · {Math.ceil(total / 1024)} KB
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("skill.clear")}
|
||||
className="text-fg-muted hover:text-fg-primary"
|
||||
onClick={() => {
|
||||
setFiles([]);
|
||||
setNameTouched(false);
|
||||
setDescTouched(false);
|
||||
}}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<ul className="max-h-28 overflow-auto font-mono text-[11px] text-fg-secondary">
|
||||
{files.slice(0, 200).map((f) => (
|
||||
<li
|
||||
key={f.path}
|
||||
className={`truncate ${JUNK.test(f.path) ? "line-through opacity-50" : ""}`}
|
||||
>
|
||||
{f.path}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{many ? (
|
||||
<p className={hint}>{t("skill.manyHint")}</p>
|
||||
) : (
|
||||
<SkillNameField
|
||||
value={name}
|
||||
onChange={(v) => {
|
||||
setNameTouched(true);
|
||||
setName(v);
|
||||
}}
|
||||
required={shape.kind === "single-md"}
|
||||
/>
|
||||
)}
|
||||
{meta}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary text-sm"
|
||||
disabled={
|
||||
busy ||
|
||||
!files.length ||
|
||||
shape.kind === "no-skill-md" ||
|
||||
(shape.kind === "single-md" && !skillSlug(name))
|
||||
}
|
||||
>
|
||||
{busy ? t("skill.uploading") : t("form.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{mode === "write" && (
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run(async () => {
|
||||
await api.artifacts.writeSkill({
|
||||
name: name.trim(),
|
||||
description: description.trim(),
|
||||
content,
|
||||
title: title.trim() || undefined,
|
||||
});
|
||||
return 1;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SkillNameField value={name} onChange={setName} required />
|
||||
<label className={label}>
|
||||
{t("skill.description")} *
|
||||
<textarea
|
||||
className={`${field} mt-0.5`}
|
||||
rows={2}
|
||||
value={description}
|
||||
placeholder={t("skill.descriptionHint")}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className={label}>
|
||||
{t("skill.content")} *
|
||||
<textarea
|
||||
className={`${field} mt-0.5 font-mono text-xs`}
|
||||
rows={10}
|
||||
value={content}
|
||||
placeholder={t("skill.contentHint")}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className={label}>
|
||||
{t("form.title")}
|
||||
<input
|
||||
className={`${field} mt-0.5`}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary text-sm"
|
||||
disabled={
|
||||
busy ||
|
||||
!skillSlug(name) ||
|
||||
!content.trim() ||
|
||||
(!description.trim() && !frontmatterField(content, "description"))
|
||||
}
|
||||
>
|
||||
{t("form.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{mode === "existing" && (
|
||||
<div className="space-y-2">
|
||||
<select
|
||||
className={field}
|
||||
aria-label={t("form.workspace")}
|
||||
value={laneId ?? ""}
|
||||
onChange={(e) => setLaneId(e.target.value ? Number(e.target.value) : null)}
|
||||
>
|
||||
<option value="">{t("form.pickWorkspace")}</option>
|
||||
{lanes.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.title || l.cwd}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{skills && skills.length === 0 && <p className={hint}>{t("form.noSkills")}</p>}
|
||||
{skills && skills.length > 0 && (
|
||||
<ul className="max-h-72 space-y-0.5 overflow-auto">
|
||||
{skills.map((s) => (
|
||||
<li key={`${s.from}:${s.name}`} className="flex items-center gap-2 text-xs">
|
||||
<Sparkles className="h-3 w-3 shrink-0 text-fg-muted" />
|
||||
<span className="min-w-0 flex-1 truncate text-fg-secondary">{s.name}</span>
|
||||
<span className="text-fg-muted">
|
||||
{t(s.from === "user" ? "form.fromUser" : "form.fromWorkspace")}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-ghost text-xs"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
await api.artifacts.addSkill({
|
||||
name: s.name,
|
||||
...(s.from === "workspace" && laneId ? { laneId } : {}),
|
||||
title: title || undefined,
|
||||
description: description || undefined,
|
||||
});
|
||||
return 1;
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("form.save")}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<input
|
||||
className={field}
|
||||
placeholder={t("form.title")}
|
||||
aria-label={t("form.title")}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
className={field}
|
||||
rows={2}
|
||||
placeholder={t("form.description")}
|
||||
aria-label={t("form.description")}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Plugin ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MANUAL_CODES = new Set(["ENEEDLOGIN", "ESSHMARKET", "ENOTMARKET", "EMARKETFETCH"]);
|
||||
|
||||
export function PluginAddPanel({ onAdded, onClose }: { onAdded: () => void; onClose: () => void }) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [link, setLink] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [info, setInfo] = useState<MarketplaceInfo | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||
const [have, setHave] = useState<Set<string>>(new Set());
|
||||
const [manual, setManual] = useState(false);
|
||||
const [key, setKey] = useState("");
|
||||
const [market, setMarket] = useState("");
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
api.artifacts
|
||||
.list({ scope: "mine", kind: "plugin" })
|
||||
.then((r) => setHave(new Set(r.items.map((i) => i.source ?? ""))))
|
||||
.catch(() => setHave(new Set()));
|
||||
}, []);
|
||||
|
||||
const read = async () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
try {
|
||||
const r = await api.artifacts.inspectMarket(link.trim());
|
||||
setInfo(r);
|
||||
setPicked(
|
||||
new Set(
|
||||
r.plugins
|
||||
.filter((p) => !have.has(p.key))
|
||||
.slice(0, 1)
|
||||
.map((p) => p.key)
|
||||
)
|
||||
);
|
||||
setMarket(r.market);
|
||||
} catch (err) {
|
||||
const e = err as Error & { code?: string };
|
||||
setError(e.message);
|
||||
if (MANUAL_CODES.has(e.code ?? "")) {
|
||||
setManual(true);
|
||||
setMarket(link.trim());
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const addPicked = async () => {
|
||||
if (!info) return;
|
||||
setBusy(true);
|
||||
let n = 0;
|
||||
try {
|
||||
for (const p of info.plugins.filter((x) => picked.has(x.key))) {
|
||||
await api.artifacts.addPlugin({
|
||||
key: p.key,
|
||||
market: info.market,
|
||||
title: p.name,
|
||||
description: p.description,
|
||||
});
|
||||
n++;
|
||||
}
|
||||
toast.success(t("plugin.addedMany", { count: n }));
|
||||
onAdded();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
if (n) onAdded();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggle = (k: string) =>
|
||||
setPicked((s) => {
|
||||
const next = new Set(s);
|
||||
if (next.has(k)) next.delete(k);
|
||||
else next.add(k);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<form
|
||||
className="space-y-1"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (link.trim()) void read();
|
||||
}}
|
||||
>
|
||||
<label className={label}>
|
||||
{t("plugin.link")}
|
||||
<div className="mt-0.5 flex gap-2">
|
||||
<input
|
||||
className={field}
|
||||
value={link}
|
||||
autoFocus
|
||||
placeholder="https://git.example.com/org/claude-skills.git"
|
||||
onChange={(e) => setLink(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary shrink-0 text-sm"
|
||||
disabled={busy || !link.trim()}
|
||||
>
|
||||
{busy && !info ? t("plugin.reading") : t("plugin.read")}
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
<p className={hint}>{t("plugin.linkHint")}</p>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-status-danger/40 px-2 py-1 text-xs text-status-danger"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{info && (
|
||||
<div className="space-y-2" data-testid="market-plugins">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-fg-primary">
|
||||
<Package className="mr-1 inline h-4 w-4 text-fg-muted" />
|
||||
{info.name}
|
||||
</p>
|
||||
{info.description && <p className={hint}>{info.description}</p>}
|
||||
</div>
|
||||
{info.plugins.length === 0 ? (
|
||||
<p className={hint}>{t("plugin.none")}</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="flex items-center gap-2 text-xs text-fg-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={picked.size === info.plugins.length}
|
||||
onChange={(e) =>
|
||||
setPicked(new Set(e.target.checked ? info.plugins.map((p) => p.key) : []))
|
||||
}
|
||||
/>
|
||||
{t("plugin.all")}
|
||||
</label>
|
||||
<ul className="max-h-64 space-y-1 overflow-auto">
|
||||
{info.plugins.map((p) => (
|
||||
<li key={p.key}>
|
||||
<label className="flex cursor-pointer items-start gap-2 rounded px-1 py-1 hover:bg-surface-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={picked.has(p.key)}
|
||||
onChange={() => toggle(p.key)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="text-xs font-medium text-fg-primary">{p.name}</span>
|
||||
<span className="ml-1.5 font-mono text-[10px] text-fg-muted">{p.key}</span>
|
||||
{p.version && (
|
||||
<span className="ml-1.5 text-[10px] text-fg-muted">v{p.version}</span>
|
||||
)}
|
||||
{have.has(p.key) && (
|
||||
<span className="ml-1.5 rounded bg-surface-3 px-1 text-[10px] text-fg-secondary">
|
||||
{t("plugin.have")}
|
||||
</span>
|
||||
)}
|
||||
{p.description && (
|
||||
<span className="block text-[11px] text-fg-muted">{p.description}</span>
|
||||
)}
|
||||
</span>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
className="btn-primary text-sm"
|
||||
disabled={busy || picked.size === 0}
|
||||
onClick={() => void addPicked()}
|
||||
>
|
||||
{t("plugin.addPicked", { count: picked.size })}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-t border-border-light pt-2">
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-accent hover:underline"
|
||||
aria-expanded={manual}
|
||||
onClick={() => setManual((v) => !v)}
|
||||
>
|
||||
{t("plugin.manual")}
|
||||
</button>
|
||||
{manual && (
|
||||
<form
|
||||
className="mt-2 space-y-2"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.artifacts.addPlugin({
|
||||
key: key.trim(),
|
||||
market: market.trim(),
|
||||
title,
|
||||
description,
|
||||
});
|
||||
toast.success(t("added"));
|
||||
onAdded();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className={field}
|
||||
placeholder="my-plugin@my-marketplace"
|
||||
aria-label={t("form.pluginKey")}
|
||||
value={key}
|
||||
onChange={(e) => setKey(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
className={field}
|
||||
placeholder="owner/repo · https://… · git@host:org/repo.git"
|
||||
aria-label={t("form.market")}
|
||||
value={market}
|
||||
onChange={(e) => setMarket(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
className={field}
|
||||
placeholder={t("form.title")}
|
||||
aria-label={t("form.title")}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
className={field}
|
||||
rows={2}
|
||||
placeholder={t("form.description")}
|
||||
aria-label={t("form.description")}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary text-sm"
|
||||
disabled={busy || !key.trim() || !market.trim()}
|
||||
>
|
||||
{t("form.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── File upload ───────────────────────────────────────────────────────────
|
||||
|
||||
export function FileUploadPanel({ onAdded }: { onAdded: () => void }) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [title, setTitle] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const tooBig = !!file && file.size > 25 * 1024 * 1024;
|
||||
return (
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
if (!file) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.artifacts.uploadFile(file, { title: title.trim() || undefined });
|
||||
toast.success(t("added"));
|
||||
setFile(null);
|
||||
setTitle("");
|
||||
onAdded();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label className={label}>
|
||||
{t("file.fromComputer")}
|
||||
<input
|
||||
type="file"
|
||||
data-testid="file-upload"
|
||||
className="mt-0.5 block w-full text-xs text-fg-secondary"
|
||||
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</label>
|
||||
{tooBig && <p className="text-xs text-status-danger">{t("file.tooBig")}</p>}
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
className={field}
|
||||
placeholder={t("form.title")}
|
||||
aria-label={t("form.title")}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary shrink-0 text-sm"
|
||||
disabled={busy || !file || tooBig}
|
||||
>
|
||||
<Upload className="h-3.5 w-3.5" /> {t("file.upload")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,11 @@
|
||||
* subset of CommonMark + GFM that actually appears in Claude Code transcripts:
|
||||
* fenced code blocks, ATX headings, ordered/unordered lists, task lists, blockquotes,
|
||||
* horizontal rules, simple tables, inline code, bold, italic, strikethrough, links,
|
||||
* and auto-linked URLs. An absolute file path (bare or in inline code) opens
|
||||
* through `OpenFileContext` when the page provides one; `linkify` does the
|
||||
* same links for plain text. To make a reply easy to scan, bold is coloured
|
||||
* and auto-linked URLs. A file path — absolute, or relative with a folder and
|
||||
* an extension (`server/lib/x.js`), with or without a `:line` suffix, bare, in
|
||||
* inline code or as a markdown link's target — opens through `OpenFileContext`
|
||||
* when the page provides one (the page resolves a relative one against its own
|
||||
* folder); `linkify` does the same links for plain text. To make a reply easy to scan, bold is coloured
|
||||
* (accent), standalone numbers (87%, 3.5s, v2.7.1, dates) are tinted and
|
||||
* tabular, and a flag label ("Lưu ý:", "Warning:", "Lỗi:") takes the colour
|
||||
* of how serious it is.
|
||||
@@ -256,7 +258,19 @@ const LINK_CLASS =
|
||||
"text-violet-700 dark:text-violet-300 hover:text-violet-800 dark:hover:text-violet-200 underline underline-offset-2 decoration-violet-400/40 hover:decoration-violet-300/70 break-all";
|
||||
const URL_RE = /^https?:\/\/[^\s<>()]+[^\s<>().,!?;:'"]/;
|
||||
// Two segments at least, so "/" or "/s" stays text; a trailing full stop is prose.
|
||||
const PATH_RE = /^(?:\/[^\s/<>()'"`,;:]*[^\s/<>()'"`,;:.!?]){2,}/;
|
||||
// A `:12` or `:12:5` line suffix belongs to the link (Claude writes `path:line`).
|
||||
const PATH_RE = /^(?:\/[^\s/<>()'"`,;:]*[^\s/<>()'"`,;:.!?]){2,}(?::\d+(?::\d+)?)?/;
|
||||
// A relative path needs a folder AND an extension starting with a letter
|
||||
// (`docs/API.md`, `./a/b.ts:9`), so "and/or" and "3/4.5" stay text; a first segment with an inner dot is a host
|
||||
// (`github.com/x.js`), not a folder — a leading one (`.claude/…`) is a folder.
|
||||
const REL_PATH_RE =
|
||||
/^(?:\.{1,2}\/)*(?:\.?[\w@-][\w@-]*\/)(?:[\w.@-]+\/)*[\w.@-]*[\w@-]\.[A-Za-z][A-Za-z0-9]{0,9}(?::\d+(?::\d+)?)?(?![\p{L}\p{N}_/])/u;
|
||||
/** A path at the start of `text`, absolute or relative, or null. */
|
||||
const matchPath = (text: string) => PATH_RE.exec(text)?.[0] ?? REL_PATH_RE.exec(text)?.[0] ?? null;
|
||||
/** `a/b.ts:12:5` → `a/b.ts`: what is opened. */
|
||||
export const stripLine = (p: string) => p.replace(/(?::\d+){1,2}$/, "");
|
||||
// A markdown link target that is a page, not a file.
|
||||
const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
|
||||
// A link starts a word: "and/or" or "a/b/c" stays text.
|
||||
const atWordStart = (text: string, i: number) => i === 0 || /[\s([{"'`]/.test(text[i - 1]!);
|
||||
// A number worth spotting: 42, 1,234.5, 87%, $1.20, 3.5s, 12MB, v2.7.1, 2026-10-12, 12:30,
|
||||
@@ -284,6 +298,17 @@ function UrlLink({ url }: { url: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** A markdown link's file target as a path: `%20` decoded, `#L12` → `:12`. */
|
||||
function decodeHref(href: string): string {
|
||||
let p = href.replace(/^file:\/\//i, "").replace(/#L(\d+)(?:-L?\d+)?$/, ":$1").replace(/#.*$/, "");
|
||||
try {
|
||||
p = decodeURIComponent(p);
|
||||
} catch {
|
||||
/* a stray % stays as written */
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/** A path as a button that opens it, or as it was when nothing can. */
|
||||
function PathLink({ path, children }: { path: string; children: React.ReactNode }) {
|
||||
const open = React.useContext(OpenFileContext);
|
||||
@@ -292,7 +317,7 @@ function PathLink({ path, children }: { path: string; children: React.ReactNode
|
||||
<button
|
||||
type="button"
|
||||
title={path}
|
||||
onClick={() => open(path)}
|
||||
onClick={() => open(stripLine(path))}
|
||||
className={`${LINK_CLASS} text-left`}
|
||||
>
|
||||
{children}
|
||||
@@ -307,7 +332,7 @@ export function linkify(text: string): React.ReactNode[] {
|
||||
for (let i = 0; i < text.length;) {
|
||||
const rest = text.slice(i);
|
||||
const url = atWordStart(text, i) && URL_RE.exec(rest)?.[0];
|
||||
const path = !url && atWordStart(text, i) && PATH_RE.exec(rest)?.[0];
|
||||
const path = !url && atWordStart(text, i) && matchPath(rest);
|
||||
const hit = url || path;
|
||||
if (!hit) {
|
||||
buf += text[i++];
|
||||
@@ -359,7 +384,7 @@ function renderInline(text: string, baseKey = ""): React.ReactNode[] {
|
||||
</code>
|
||||
);
|
||||
push(
|
||||
PATH_RE.exec(codeM[1]!)?.[0] === codeM[1] ? (
|
||||
matchPath(codeM[1]!) === codeM[1] ? (
|
||||
<PathLink path={codeM[1]!}>{code}</PathLink>
|
||||
) : (
|
||||
code
|
||||
@@ -408,9 +433,23 @@ function renderInline(text: string, baseKey = ""): React.ReactNode[] {
|
||||
// Markdown link
|
||||
const linkM = rest.match(/^\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/);
|
||||
if (linkM) {
|
||||
const href = linkM[2]!;
|
||||
// `[x.ts](src/x.ts#L12)` names a file: open it like a bare path.
|
||||
if (
|
||||
/^file:\/\//i.test(href) ||
|
||||
(!SCHEME_RE.test(href) && !href.startsWith("#") && !href.startsWith("//"))
|
||||
) {
|
||||
push(
|
||||
<PathLink path={decodeHref(href)}>
|
||||
{renderInline(linkM[1]!, `${baseKey}-l${n}`)}
|
||||
</PathLink>
|
||||
);
|
||||
i += linkM[0].length;
|
||||
continue;
|
||||
}
|
||||
push(
|
||||
<a
|
||||
href={linkM[2]!}
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-violet-700 dark:text-violet-300 hover:text-violet-800 dark:hover:text-violet-200 underline underline-offset-2 decoration-violet-400/40 hover:decoration-violet-300/70"
|
||||
@@ -431,10 +470,10 @@ function renderInline(text: string, baseKey = ""): React.ReactNode[] {
|
||||
}
|
||||
|
||||
// An absolute path at a word start
|
||||
const pathM = atWordStart(text, i) ? PATH_RE.exec(rest) : null;
|
||||
const pathM = atWordStart(text, i) ? matchPath(rest) : null;
|
||||
if (pathM) {
|
||||
push(<PathLink path={pathM[0]}>{pathM[0]}</PathLink>);
|
||||
i += pathM[0].length;
|
||||
push(<PathLink path={pathM}>{pathM}</PathLink>);
|
||||
i += pathM.length;
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,52 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MarkdownContent } from "../MarkdownContent";
|
||||
import { vi } from "vitest";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { MarkdownContent, OpenFileContext } from "../MarkdownContent";
|
||||
import { resolveIn } from "../../../lib/resolvePath";
|
||||
|
||||
function withOpen(text: string) {
|
||||
const open = vi.fn();
|
||||
render(
|
||||
<OpenFileContext.Provider value={open}>
|
||||
<MarkdownContent text={text} />
|
||||
</OpenFileContext.Provider>
|
||||
);
|
||||
return open;
|
||||
}
|
||||
|
||||
describe("file links", () => {
|
||||
it("opens a relative path with its line suffix stripped", () => {
|
||||
const open = withOpen("See server/lib/x.js:42 for it.");
|
||||
fireEvent.click(screen.getByRole("button", { name: "server/lib/x.js:42" }));
|
||||
expect(open).toHaveBeenCalledWith("server/lib/x.js");
|
||||
});
|
||||
|
||||
it("opens an absolute path with a line suffix and one in inline code", () => {
|
||||
const open = withOpen("At /a/b/c.ts:9 and `docs/API.md`.");
|
||||
fireEvent.click(screen.getByRole("button", { name: "/a/b/c.ts:9" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "docs/API.md" }));
|
||||
expect(open.mock.calls).toEqual([["/a/b/c.ts"], ["docs/API.md"]]);
|
||||
});
|
||||
|
||||
it("opens a markdown link to a file instead of navigating", () => {
|
||||
const open = withOpen("[the panel](client/src/A%20B.tsx#L12) and [web](https://x.dev)");
|
||||
fireEvent.click(screen.getByRole("button", { name: "the panel" }));
|
||||
expect(open).toHaveBeenCalledWith("client/src/A B.tsx");
|
||||
expect(screen.getByRole("link", { name: "web" })).toHaveAttribute("href", "https://x.dev");
|
||||
});
|
||||
|
||||
it("leaves prose with slashes as text", () => {
|
||||
withOpen("and/or, 3/4.5, github.com/x.js, TCP/IP.");
|
||||
expect(screen.queryAllByRole("button")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("resolves a relative path against the pane's folder", () => {
|
||||
expect(resolveIn("/w/repo/", "./server/../docs/API.md")).toBe("/w/repo/docs/API.md");
|
||||
expect(resolveIn("/w/repo", "/etc/x.conf")).toBe("/etc/x.conf");
|
||||
});
|
||||
});
|
||||
|
||||
describe("<MarkdownContent />", () => {
|
||||
it("renders fenced code blocks with the language label", () => {
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
* manually-typed branch name; "Clone" runs `POST /api/lanes/clone` (an
|
||||
* https/ssh URL cloned into a folder of the user's, with their OWN SSH key or
|
||||
* HTTPS login — a 409 `ECREDENTIALS` opens a login row, `ESSHAUTH` points to
|
||||
* Settings → Git). The user also picks which CLI drives the lane
|
||||
* (Claude Code or Codex) — this choice is immutable after creation. Either
|
||||
* Settings → Git). There is no AI tool picker: the lane is created with the
|
||||
* default AI tool (Settings → AI Tools), and each new session picks its own
|
||||
* AI on the workspace home. Either
|
||||
* mode's path field can be filled by typing, by the CwdAutocomplete
|
||||
* suggestions, or by Browse (`PathPickButton`: the OS's own folder picker
|
||||
* opened by the server, the in-app `FolderBrowseModal` where it cannot be) —
|
||||
@@ -24,7 +25,7 @@
|
||||
|
||||
import { useCallback, useEffect, useId, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ChevronDown, X } from "lucide-react";
|
||||
import { X } from "lucide-react";
|
||||
import { useDialog } from "../../hooks/useDialog";
|
||||
import { CwdAutocomplete } from "../run/RunSetup";
|
||||
import { PathPickButton } from "../PathPickButton";
|
||||
@@ -32,7 +33,6 @@ import { api } from "../../lib/api";
|
||||
import type { CwdSuggestion } from "../../lib/api";
|
||||
import type { Lane, LaneWorktree } from "../../lib/types";
|
||||
import { useAiTools } from "../../hooks/useAiTools";
|
||||
import { AiToolIcon } from "../AiToolIcon";
|
||||
import { readDefaultTool } from "../../lib/sessionDefaults";
|
||||
|
||||
/** Polls the lane until the background `git worktree add` finishes (status
|
||||
@@ -135,27 +135,18 @@ export function AddLaneModal({
|
||||
const [branchMode, setBranchMode] = useState<"new" | "existing">("new");
|
||||
const [base, setBase] = useState("");
|
||||
const [branchesError, setBranchesError] = useState<string | null>(null);
|
||||
// null = the default AI tool (Settings → AI Tools), resolved at submit time.
|
||||
const [pickedTool, setPickedTool] = useState<string | null>(null);
|
||||
// No picker: a workspace's tool is only its DEFAULT — each new session
|
||||
// picks its own AI on the workspace home. This is the default AI tool
|
||||
// (Settings → AI Tools), the account's own pick first while it is
|
||||
// installed and on.
|
||||
const aiTools = useAiTools();
|
||||
// The account's own pick (first-run setup), while it is installed and on.
|
||||
const ownTool = readDefaultTool();
|
||||
const defaultTool =
|
||||
const tool =
|
||||
(ownTool && aiTools.tools.some((x) => x.id === ownTool && x.installed && x.enabled)
|
||||
? ownTool
|
||||
: null) ??
|
||||
aiTools.defaultId ??
|
||||
"claude";
|
||||
const tool = pickedTool ?? defaultTool;
|
||||
// Installed + enabled, the default first.
|
||||
const toolChoices = aiTools.tools
|
||||
.filter((x) => x.installed && x.enabled)
|
||||
.sort((a, b) => Number(b.id === defaultTool) - Number(a.id === defaultTool));
|
||||
const [toolListOpen, setToolListOpen] = useState(false);
|
||||
const pickTool = (id: string) => {
|
||||
setPickedTool(id === defaultTool ? null : id);
|
||||
setToolListOpen(false);
|
||||
};
|
||||
const noTools = aiTools.loaded && aiTools.defaultId === null;
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -177,7 +168,6 @@ export function AddLaneModal({
|
||||
setWorktrees([]);
|
||||
setBranchMode("new");
|
||||
setBase("");
|
||||
setPickedTool(null);
|
||||
setBranchesError(null);
|
||||
setError(null);
|
||||
setBusy(false);
|
||||
@@ -501,64 +491,14 @@ export function AddLaneModal({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
{noTools ? (
|
||||
<p className="rounded-md border border-status-warning/40 bg-status-warning/10 px-2 py-1.5 text-xs text-status-warning">
|
||||
{t("addLaneNoTools")}{" "}
|
||||
<a href="/settings/agents" className="underline">
|
||||
{t("addLaneNoToolsLink")}
|
||||
</a>
|
||||
</p>
|
||||
) : (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={toolListOpen}
|
||||
disabled={toolChoices.length < 2}
|
||||
onClick={() => setToolListOpen((o) => !o)}
|
||||
className="flex w-full items-center gap-2 rounded-md border border-border bg-surface-2 px-2.5 py-1.5 text-left text-sm text-fg-primary hover:bg-surface-3 disabled:cursor-default disabled:hover:bg-surface-2"
|
||||
>
|
||||
<AiToolIcon tool={{ id: tool, label: aiTools.label(tool) }} className="h-5 w-5" />
|
||||
<span className="min-w-0 flex-1 truncate">{aiTools.label(tool)}</span>
|
||||
{tool === defaultTool && (
|
||||
<span className="rounded-full bg-accent/15 px-2 py-0.5 text-[10px] font-medium text-accent">
|
||||
{t("addLaneToolDefaultBadge")}
|
||||
</span>
|
||||
)}
|
||||
{toolChoices.length > 1 && (
|
||||
<ChevronDown
|
||||
aria-hidden
|
||||
className={`h-4 w-4 text-fg-muted transition-transform ${toolListOpen ? "rotate-180" : ""}`}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
{toolListOpen && (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t("addLaneToolHint")}
|
||||
className="mt-1.5 grid grid-cols-2 gap-1.5 sm:grid-cols-3"
|
||||
>
|
||||
{toolChoices.map((x) => (
|
||||
<button
|
||||
key={x.id}
|
||||
type="button"
|
||||
aria-pressed={x.id === tool}
|
||||
onClick={() => pickTool(x.id)}
|
||||
className={`flex items-center gap-2 rounded-md border px-2 py-1.5 text-left text-xs transition-colors ${
|
||||
x.id === tool
|
||||
? "border-accent bg-accent/10 text-accent"
|
||||
: "border-border bg-surface-2 text-fg-secondary hover:bg-surface-3 hover:text-fg-primary"
|
||||
}`}
|
||||
>
|
||||
<AiToolIcon tool={x} className="h-5 w-5" />
|
||||
<span className="min-w-0 flex-1 truncate">{x.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{noTools && (
|
||||
<p className="rounded-md border border-status-warning/40 bg-status-warning/10 px-2 py-1.5 text-xs text-status-warning">
|
||||
{t("addLaneNoTools")}{" "}
|
||||
<a href="/settings/agents" className="underline">
|
||||
{t("addLaneNoToolsLink")}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-fg-secondary" htmlFor="add-lane-repo">
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* @file CloneSourcesForm — a workspace's "Or clone repositories" box, under
|
||||
* its Folders card: one URL per line, each cloned BESIDE the workspace folder
|
||||
* (`POST /api/lanes/:id/sources/clone`, the server picks the folder) and
|
||||
* added as an extra folder, one after another. A host that wants a login
|
||||
* (409 `ECREDENTIALS`) opens one login row; Retry re-runs only the failed
|
||||
* URLs with it, like Add workspace → Clone.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Check, Loader2, X } from "lucide-react";
|
||||
import { api, type LaneSourcesView } from "../../lib/api";
|
||||
|
||||
type Row = { url: string; state: "wait" | "busy" | "done" | "failed"; note?: string };
|
||||
type Login = { host: string; username: string; token: string; remember: boolean };
|
||||
|
||||
export function CloneSourcesForm({
|
||||
laneId,
|
||||
parent,
|
||||
onAdded,
|
||||
}: {
|
||||
laneId: number;
|
||||
/** Where the clones land: the workspace folder's parent, shown only. */
|
||||
parent: string;
|
||||
onAdded: (view: LaneSourcesView) => void;
|
||||
}) {
|
||||
const { t } = useTranslation("lanes");
|
||||
const [text, setText] = useState("");
|
||||
const [rows, setRows] = useState<Row[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [login, setLogin] = useState<Login | null>(null);
|
||||
|
||||
const urls = (s: string) => [
|
||||
...new Set(
|
||||
s
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean)
|
||||
),
|
||||
];
|
||||
|
||||
const cloneAll = async (list: string[]) => {
|
||||
if (busy || !list.length) return;
|
||||
setBusy(true);
|
||||
const next: Row[] = list.map((url) => ({ url, state: "wait" }));
|
||||
const show = () => setRows([...next]);
|
||||
show();
|
||||
let asked: Login | null = null;
|
||||
for (const row of next) {
|
||||
row.state = "busy";
|
||||
show();
|
||||
try {
|
||||
const view = await api.lanes.cloneFolder(laneId, {
|
||||
url: row.url,
|
||||
...(login?.username.trim() && login.token
|
||||
? {
|
||||
credentials: {
|
||||
username: login.username.trim(),
|
||||
password: login.token,
|
||||
remember: login.remember,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
row.state = "done";
|
||||
onAdded(view);
|
||||
} catch (err) {
|
||||
const e = err as { code?: string; auth?: { host?: string }; message?: string };
|
||||
const host = e.auth?.host || row.url;
|
||||
row.state = "failed";
|
||||
if (e.code === "ECREDENTIALS") {
|
||||
row.note = t(login?.token ? "clone.loginRejected" : "clone.loginNeeded", { host });
|
||||
asked ??= {
|
||||
host,
|
||||
username: login?.username ?? "",
|
||||
token: "",
|
||||
remember: login?.remember ?? true,
|
||||
};
|
||||
} else if (e.code === "ESSHAUTH") {
|
||||
row.note = t("clone.sshRefused", { host });
|
||||
} else {
|
||||
row.note = e.message || String(err);
|
||||
}
|
||||
}
|
||||
show();
|
||||
}
|
||||
if (asked) setLogin(asked);
|
||||
// What is left to do stays in the box; what was added leaves it.
|
||||
setText(
|
||||
next
|
||||
.filter((r) => r.state !== "done")
|
||||
.map((r) => r.url)
|
||||
.join("\n")
|
||||
);
|
||||
setBusy(false);
|
||||
};
|
||||
|
||||
const failed = rows.filter((r) => r.state === "failed").map((r) => r.url);
|
||||
|
||||
return (
|
||||
<div className="space-y-2 border-t border-border-light pt-2" data-testid="workspace-clone">
|
||||
<p className="text-[10px] uppercase tracking-wide text-fg-muted">{t("home.cloneFolders")}</p>
|
||||
<textarea
|
||||
data-testid="workspace-clone-input"
|
||||
aria-label={t("home.cloneFolders")}
|
||||
placeholder={t("home.clonePlaceholder")}
|
||||
rows={3}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
className="w-full rounded border border-border bg-surface-1 px-2 py-1 font-mono text-[11px] text-fg-primary"
|
||||
/>
|
||||
<p className="text-[11px] text-fg-muted">{t("home.cloneHint", { path: parent })}</p>
|
||||
{login && (
|
||||
<div className="space-y-1.5 rounded border border-border-light p-2">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
aria-label={t("clone.username")}
|
||||
placeholder={t("clone.username")}
|
||||
value={login.username}
|
||||
onChange={(e) => setLogin({ ...login, username: e.target.value })}
|
||||
className="min-w-0 flex-1 rounded border border-border bg-surface-1 px-2 py-1 text-[11px] text-fg-primary"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
aria-label={t("clone.token")}
|
||||
placeholder={t("clone.token")}
|
||||
value={login.token}
|
||||
onChange={(e) => setLogin({ ...login, token: e.target.value })}
|
||||
className="min-w-0 flex-1 rounded border border-border bg-surface-1 px-2 py-1 text-[11px] text-fg-primary"
|
||||
/>
|
||||
</div>
|
||||
<label className="flex items-center gap-1.5 text-[11px] text-fg-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={login.remember}
|
||||
onChange={(e) => setLogin({ ...login, remember: e.target.checked })}
|
||||
/>
|
||||
{t("clone.remember")}
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end gap-2">
|
||||
{failed.length > 0 && !busy && (
|
||||
<button type="button" onClick={() => void cloneAll(failed)} className="btn-ghost text-xs">
|
||||
{t("home.cloneRetry")}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
data-testid="workspace-clone-run"
|
||||
disabled={busy || !urls(text).length}
|
||||
onClick={() => void cloneAll(urls(text))}
|
||||
className="btn-ghost text-xs"
|
||||
>
|
||||
{busy ? t("clone.cloning") : t("home.cloneRun")}
|
||||
</button>
|
||||
</div>
|
||||
{rows.length > 0 && (
|
||||
<ul className="space-y-1" data-testid="workspace-clone-rows">
|
||||
{rows.map((r) => (
|
||||
<li key={r.url} className="text-[11px]">
|
||||
<span className="flex items-center gap-1.5">
|
||||
{r.state === "busy" ? (
|
||||
<Loader2 className="h-3 w-3 shrink-0 animate-spin text-fg-muted" />
|
||||
) : r.state === "done" ? (
|
||||
<Check
|
||||
className="h-3 w-3 shrink-0 text-status-success"
|
||||
aria-label={t("home.cloneDone")}
|
||||
/>
|
||||
) : r.state === "failed" ? (
|
||||
<X className="h-3 w-3 shrink-0 text-status-danger" />
|
||||
) : (
|
||||
<span className="h-3 w-3 shrink-0" />
|
||||
)}
|
||||
<span className="min-w-0 truncate font-mono text-fg-secondary" title={r.url}>
|
||||
{r.url}
|
||||
</span>
|
||||
</span>
|
||||
{r.note && <span className="ml-[18px] block text-status-danger">{r.note}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -270,9 +270,13 @@ export function FileBrowser({
|
||||
const folderInput = useRef<HTMLInputElement>(null);
|
||||
const ctx = useContextMenu<FsEntry | null>();
|
||||
|
||||
// A new caller target (another workspace's Files tab, the page's URL).
|
||||
// A new caller target (another workspace's Files tab, the page's URL) —
|
||||
// not the echo of our own `go()` through the page's URL, which would wipe
|
||||
// Back's history on every folder opened.
|
||||
useEffect(() => {
|
||||
setTarget(placeOf());
|
||||
const next = placeOf();
|
||||
if (samePlace(next, target) && initialPath === path) return;
|
||||
setTarget(next);
|
||||
setPathState(initialPath);
|
||||
setHistory({ back: [], fwd: [] });
|
||||
setSelected(new Set());
|
||||
@@ -1145,7 +1149,13 @@ export function FileBrowser({
|
||||
{listing && !entries.length && !creating && !error && (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-16 text-fg-muted">
|
||||
<Folder className="h-16 w-16 opacity-40" />
|
||||
<p className="text-sm">{query ? t("fx.noMatch") : t("fx.empty")}</p>
|
||||
<p className="max-w-md text-center text-sm">
|
||||
{query
|
||||
? t("fx.noMatch")
|
||||
: isHomePlace(target) && !path
|
||||
? t("fx.homeEmpty")
|
||||
: t("fx.empty")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{loading && !listing && <p className="p-6 text-sm text-fg-muted">{t("fx.loading")}</p>}
|
||||
|
||||
@@ -102,9 +102,9 @@ import {
|
||||
Sparkles,
|
||||
Trash2,
|
||||
UnfoldVertical,
|
||||
FolderOpen,
|
||||
} from "lucide-react";
|
||||
import { api, gitTarget } from "../../lib/api";
|
||||
import { usePermissions } from "../AuthGate";
|
||||
import { pasteToLane } from "../../lib/panePaste";
|
||||
import { confirmDialog, confirmDiscard as askDiscard } from "../../lib/confirm";
|
||||
import { copyText } from "../../lib/clipboard";
|
||||
@@ -810,8 +810,12 @@ export function LaneChangesPanel({
|
||||
wide = full,
|
||||
onDirtyChange,
|
||||
openRequest = null,
|
||||
filesChanged = 0,
|
||||
}: {
|
||||
laneId: number;
|
||||
/** Bumped when files changed outside this panel (the header's File
|
||||
* Explorer): the tree is read again, its open folders kept open. */
|
||||
filesChanged?: number;
|
||||
/** Open this file (relative to the panel's folder); a new `nonce` asks again. */
|
||||
openRequest?: { path: string; nonce: number } | null;
|
||||
/** The whole-file editor holds unsaved text (true) or not (false). */
|
||||
@@ -855,6 +859,9 @@ export function LaneChangesPanel({
|
||||
// history and the tree too, not just the diff `load` re-reads.
|
||||
const [reread, setReread] = useState(0);
|
||||
const [range, setRange] = useState<LaneChangeRange>("work");
|
||||
// Local mode: the files are already on this machine — no upload, download
|
||||
// or File Explorer (the desktop's file manager does all three).
|
||||
const { local } = usePermissions();
|
||||
const [mode, setMode] = useState<Mode>("overview");
|
||||
const [openFile, setOpenFile] = useState<string | null>(null);
|
||||
// An image opens as a picture, never as text or a binary diff.
|
||||
@@ -870,6 +877,16 @@ export function LaneChangesPanel({
|
||||
const [mdPreview, setMdPreview] = useState(false);
|
||||
useEffect(() => setMdPreview(false), [openFile]);
|
||||
const [data, setData] = useState<LaneChanges | null>(null);
|
||||
// A folder that is not a repo (an empty new workspace, a parent of clones)
|
||||
// has no changes, review or history — only its files, which Files reads
|
||||
// from the disk. Open there instead of on a page that only says "no git".
|
||||
// Both reads must say so: the facts alone also read "unavailable" on a
|
||||
// network error or an older server.
|
||||
const notRepo = git?.available === false && data?.available === false;
|
||||
useEffect(() => {
|
||||
if (notRepo && (mode === "overview" || mode === "review" || mode === "history"))
|
||||
setMode(full ? "overview" : "browse");
|
||||
}, [notRepo, mode, full]);
|
||||
const [commits, setCommits] = useState<LaneCommit[] | null>(null);
|
||||
// A folder's children, keyed by its path ("" is the root) — fetched once,
|
||||
// on first expand, and kept so re-collapsing doesn't re-fetch.
|
||||
@@ -1078,19 +1095,32 @@ export function LaneChangesPanel({
|
||||
}, [mode, laneId, query, reread, full, treeRootLoaded]);
|
||||
|
||||
// A folder's children are fetched lazily, the first time it is expanded.
|
||||
const readDir = (path: string) =>
|
||||
api.lanes
|
||||
.gitTree(target, path)
|
||||
.then(forLane(laneId, (r) => setTreeChildren((prev) => ({ ...prev, [path]: r.entries }))))
|
||||
.catch((err) => setError(err instanceof Error ? err.message : String(err)));
|
||||
const toggleDir = (path: string) => {
|
||||
const opening = !expandedDirs.has(path);
|
||||
setExpandedDirs((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (!next.delete(path)) next.add(path);
|
||||
return next;
|
||||
});
|
||||
if (path in treeChildren) return;
|
||||
void api.lanes
|
||||
.gitTree(target, path)
|
||||
.then(forLane(laneId, (r) => setTreeChildren((prev) => ({ ...prev, [path]: r.entries }))))
|
||||
.catch((err) => setError(err instanceof Error ? err.message : String(err)));
|
||||
// Every OPEN reads the folder again (the cached level shows meanwhile):
|
||||
// files land in it from outside the panel — an agent, the terminal, the
|
||||
// File Explorer — and a level cached while it was empty stayed empty.
|
||||
if (opening) void readDir(path);
|
||||
};
|
||||
|
||||
// Files changed outside the panel: read the root and every open folder again.
|
||||
useEffect(() => {
|
||||
if (!filesChanged) return;
|
||||
void readDir("");
|
||||
for (const p of expandedDirs) void readDir(p);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [filesChanged]);
|
||||
|
||||
const [treeBusy, setTreeBusy] = useState(false);
|
||||
|
||||
// "Expand all" is ONE read of the whole tree: a request per folder meant a
|
||||
@@ -1624,15 +1654,17 @@ export function LaneChangesPanel({
|
||||
<MenuItem onSelect={pick(treeCtx.close, () => showHistory(treeCtx.menu!.item.path))}>
|
||||
{t("changes.showHistory")}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
testId="lane-changes-menu-download"
|
||||
onSelect={pick(treeCtx.close, () => download(treeCtx.menu!.item.path))}
|
||||
>
|
||||
{t("changes.download")}
|
||||
</MenuItem>
|
||||
{!local && (
|
||||
<MenuItem
|
||||
testId="lane-changes-menu-download"
|
||||
onSelect={pick(treeCtx.close, () => download(treeCtx.menu!.item.path))}
|
||||
>
|
||||
{t("changes.download")}
|
||||
</MenuItem>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{treeCtx.menu.item.dir && (
|
||||
{!local && treeCtx.menu.item.dir && (
|
||||
<MenuItem
|
||||
testId="lane-changes-menu-upload"
|
||||
onSelect={pick(treeCtx.close, () => pickUpload(treeCtx.menu!.item.path))}
|
||||
@@ -1640,7 +1672,7 @@ export function LaneChangesPanel({
|
||||
{t("changes.uploadHere")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{treeCtx.menu.item.dir && (
|
||||
{!local && treeCtx.menu.item.dir && (
|
||||
<MenuItem
|
||||
testId="lane-changes-menu-explorer"
|
||||
onSelect={pick(treeCtx.close, () => setExplorer({ path: treeCtx.menu!.item.path }))}
|
||||
@@ -2134,9 +2166,9 @@ export function LaneChangesPanel({
|
||||
aria-label={t("changes.quickOpen")}
|
||||
className="w-full rounded border border-border bg-surface-1 px-2 py-1 font-mono text-[11px] text-fg-primary"
|
||||
/>
|
||||
<IconButton label={t("changes.openExplorer")} onClick={() => setExplorer({ path: "" })}>
|
||||
<FolderOpen className="h-3.5 w-3.5" />
|
||||
</IconButton>
|
||||
{/* The File Explorer's button lives in the panel header now (beside
|
||||
Full screen); this instance serves the tree's "Open in File
|
||||
Explorer". */}
|
||||
<FileExplorer
|
||||
open={!!explorer}
|
||||
laneId={laneId}
|
||||
@@ -2265,14 +2297,16 @@ export function LaneChangesPanel({
|
||||
<ChevronLeft className="h-3 w-3" />
|
||||
{t("changes.back")}
|
||||
</button>
|
||||
) : (
|
||||
) : notRepo && full ? null : (
|
||||
<div className="flex min-w-0 items-center rounded border border-border bg-surface-2 p-0.5">
|
||||
{/* Files is the whole repo's tree; at full width it is the
|
||||
sidebar already, so no button. */}
|
||||
{(full
|
||||
? (["overview", "review", "history"] as const)
|
||||
: (["overview", "browse", "review", "history"] as const)
|
||||
).map((m) => (
|
||||
{(notRepo
|
||||
? (["browse"] as const)
|
||||
: full
|
||||
? (["overview", "review", "history"] as const)
|
||||
: (["overview", "browse", "review", "history"] as const)
|
||||
).map((m: Mode) => (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
@@ -2627,7 +2661,9 @@ export function LaneChangesPanel({
|
||||
browsePane
|
||||
) : !data ? (
|
||||
<p className="text-[11px] text-fg-muted">{t("changes.loading")}</p>
|
||||
) : !data.available ? (
|
||||
) : !data.available && mode !== "file" ? (
|
||||
// A file still opens from Files: its whole-file read is the disk's,
|
||||
// not git's.
|
||||
<p className="text-[11px] text-fg-muted">
|
||||
{t(source ? "changes.unavailableFolder" : "changes.unavailable")}
|
||||
</p>
|
||||
@@ -2878,7 +2914,7 @@ export function LaneChangesPanel({
|
||||
{mdPreview ? t("changes.raw") : t("changes.preview")}
|
||||
</button>
|
||||
)}
|
||||
{range !== "commit" && openFile && (
|
||||
{!local && range !== "commit" && openFile && (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="lane-file-download"
|
||||
@@ -2970,7 +3006,9 @@ export function LaneChangesPanel({
|
||||
collapse={!whole}
|
||||
revertLabel={t("changes.revertBlock")}
|
||||
value={draft}
|
||||
original={baseText ?? draft}
|
||||
// Outside a repo there is no HEAD: the edits are
|
||||
// shown against the text as it was opened.
|
||||
original={(notRepo ? text?.lines.join("\n") : baseText) ?? draft}
|
||||
lang={langFor(openFile ?? "")}
|
||||
label={t("changes.editorLabel", { path: openFile })}
|
||||
onChange={setDraft}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* /api/lanes/:id/sources…`, see server/lib/lane-sources.js). Shown as the
|
||||
* workspace home's right column and, `compact`, folded at the bottom of the
|
||||
* session view's Changes panel. Folder suggestions are the repo's untracked
|
||||
* worktrees from `GET /api/projects`, filtered by Settings → Worktrees.
|
||||
* worktrees from `GET /api/projects`, filtered by Settings → Worktrees; the
|
||||
* same form clones related repos beside the workspace (`CloneSourcesForm`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -21,6 +22,7 @@ import { useProjectTreePrefs } from "../../lib/projectTreePrefs";
|
||||
import { MarkdownPreview } from "../MarkdownPreview";
|
||||
import { ContextMenu, MenuItem, MenuSeparator, useContextMenu } from "../ContextMenu";
|
||||
import { PathPickButton } from "../PathPickButton";
|
||||
import { CloneSourcesForm } from "./CloneSourcesForm";
|
||||
|
||||
function fmtBytes(n: number | null): string {
|
||||
if (!n) return "";
|
||||
@@ -436,6 +438,16 @@ function ContextBody({
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
{folderOpen && (
|
||||
<CloneSourcesForm
|
||||
laneId={lane.id}
|
||||
parent={lane.cwd.replace(/\/+$/, "").replace(/\/[^/]*$/, "") || "/"}
|
||||
onAdded={(next) => {
|
||||
setView(next);
|
||||
onSourcesChange?.(next);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
|
||||
@@ -670,46 +670,18 @@ describe("AddLaneModal — create/update readme", () => {
|
||||
describe("AddLaneModal — no proxy here", () => {
|
||||
it("asks for no AI Proxy: a new session picks its own", async () => {
|
||||
renderModal({});
|
||||
await screen.findByRole("button", { name: /Claude Code.*Default/ });
|
||||
await waitFor(() => expect(api.aiTools.list).toHaveBeenCalled());
|
||||
expect(screen.queryByRole("radio", { name: "AI Proxy" })).toBeNull();
|
||||
expect(api.aiProxies.list).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("AddLaneModal — tool selection", () => {
|
||||
it("sends the picked tool when adopting a repo", async () => {
|
||||
vi.mocked(api.lanes.ensure).mockResolvedValue({
|
||||
lane: laneFixture({ id: 23, kind: "adopted", status: "idle" }),
|
||||
created: true,
|
||||
});
|
||||
const onAdded = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
renderModal({ onAdded, onClose });
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Repo" }));
|
||||
const dirField = screen.getByLabelText("Directory");
|
||||
await focusField(user, dirField);
|
||||
await user.type(dirField, "/tmp/demo");
|
||||
// One button showing the default; it opens every installed + enabled tool.
|
||||
const picker = await screen.findByRole("button", { name: /Claude Code.*Default/ });
|
||||
expect(picker).toHaveAttribute("aria-expanded", "false");
|
||||
await user.click(picker);
|
||||
const list = screen.getByRole("group", { name: "Default AI tool" });
|
||||
expect(
|
||||
within(list)
|
||||
.getAllByRole("button")
|
||||
.map((b) => b.textContent)
|
||||
).toEqual(["Claude Code", "Codex", "Gemini"]);
|
||||
await user.click(within(list).getByRole("button", { name: "Codex" }));
|
||||
// The picked tool replaces the default on the button, and the list closes.
|
||||
expect(screen.getByRole("button", { name: "Codex", expanded: false })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Gemini" })).toBeNull();
|
||||
await user.click(screen.getByRole("button", { name: /add workspace|create/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(api.lanes.ensure).toHaveBeenCalledWith(expect.objectContaining({ tool: "codex" }))
|
||||
);
|
||||
it("offers no tool picker: a new session picks its own AI", async () => {
|
||||
renderModal({});
|
||||
await waitFor(() => expect(api.aiTools.list).toHaveBeenCalled());
|
||||
expect(screen.queryByRole("button", { name: /Claude Code/ })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Codex" })).toBeNull();
|
||||
});
|
||||
|
||||
it("says so, with a link to Settings, when no tool is installed and enabled", async () => {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* @file Tests for CloneSourcesForm: every URL in the box is cloned in turn as
|
||||
* an extra folder, a host that wants a login opens the login row, and Retry
|
||||
* re-runs only the failed URLs with that login.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import "../../../i18n";
|
||||
|
||||
vi.mock("../../../lib/api", () => ({
|
||||
api: { lanes: { cloneFolder: vi.fn() } },
|
||||
}));
|
||||
|
||||
import { api, type LaneSourcesView } from "../../../lib/api";
|
||||
import { CloneSourcesForm } from "../CloneSourcesForm";
|
||||
|
||||
const view = { sources: [] } as unknown as LaneSourcesView & { path: string };
|
||||
|
||||
describe("CloneSourcesForm", () => {
|
||||
beforeEach(() => vi.mocked(api.lanes.cloneFolder).mockReset());
|
||||
|
||||
it("clones each URL, asks for a login where needed, and retries only that one", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onAdded = vi.fn();
|
||||
vi.mocked(api.lanes.cloneFolder).mockImplementation(async (_id, body) => {
|
||||
if (body?.url.includes("private") && !body.credentials)
|
||||
throw Object.assign(new Error("login"), {
|
||||
code: "ECREDENTIALS",
|
||||
auth: { protocol: "https", host: "private.test" },
|
||||
});
|
||||
return view;
|
||||
});
|
||||
render(<CloneSourcesForm laneId={3} parent="/w" onAdded={onAdded} />);
|
||||
|
||||
await user.type(
|
||||
screen.getByTestId("workspace-clone-input"),
|
||||
"https://h/a.git\nhttps://private.test/b.git\nhttps://h/a.git"
|
||||
);
|
||||
await user.click(screen.getByTestId("workspace-clone-run"));
|
||||
|
||||
await waitFor(() => expect(api.lanes.cloneFolder).toHaveBeenCalledTimes(2));
|
||||
expect(onAdded).toHaveBeenCalledTimes(1);
|
||||
expect(await screen.findByText(/private\.test needs a login/)).toBeInTheDocument();
|
||||
// Only what is left stays in the box.
|
||||
expect(screen.getByTestId("workspace-clone-input")).toHaveValue("https://private.test/b.git");
|
||||
|
||||
await user.type(screen.getByLabelText("Username"), "dev");
|
||||
await user.type(screen.getByLabelText("Password or access token"), "tok");
|
||||
await user.click(screen.getByRole("button", { name: "Retry the failed ones" }));
|
||||
|
||||
await waitFor(() => expect(onAdded).toHaveBeenCalledTimes(2));
|
||||
expect(api.lanes.cloneFolder).toHaveBeenLastCalledWith(3, {
|
||||
url: "https://private.test/b.git",
|
||||
credentials: { username: "dev", password: "tok", remember: true },
|
||||
});
|
||||
expect(screen.getByTestId("workspace-clone-input")).toHaveValue("");
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,12 @@ import type { LaneChanges } from "../../../lib/types";
|
||||
|
||||
// The themed confirm needs its host (App); answer it here.
|
||||
// CodeMirror does not run in jsdom: the editor is a textarea over the same props.
|
||||
// Local mode unless a test says otherwise.
|
||||
const perms = vi.hoisted(() => ({ local: true }));
|
||||
vi.mock("../../AuthGate", async (importOriginal) => {
|
||||
const m = await importOriginal<typeof import("../../AuthGate")>();
|
||||
return { ...m, usePermissions: () => ({ ...m.usePermissions(), local: perms.local }) };
|
||||
});
|
||||
vi.mock("../DiffEditor", () => ({
|
||||
default: (p: {
|
||||
value: string;
|
||||
@@ -146,6 +152,7 @@ function discardOf(path: string) {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
perms.local = true;
|
||||
vi.mocked(api.lanes.git).mockReset().mockResolvedValue({ available: false });
|
||||
vi.mocked(api.lanes.changes).mockReset();
|
||||
vi.mocked(api.lanes.changes).mockResolvedValue(changes());
|
||||
@@ -310,16 +317,29 @@ describe("LaneChangesPanel", () => {
|
||||
await waitFor(() => expect(api.lanes.changes).toHaveBeenCalledWith(7, { range: "branch" }));
|
||||
});
|
||||
|
||||
it("says so, quietly, when the lane's directory is not a git repo", async () => {
|
||||
it("says so, quietly, beside the tree at full width, when the folder is not a repo", async () => {
|
||||
vi.mocked(api.lanes.changes).mockResolvedValue({
|
||||
available: false,
|
||||
range: "work",
|
||||
files: [],
|
||||
});
|
||||
render(<LaneChangesPanel laneId={7} full />);
|
||||
expect(
|
||||
await screen.findByText("This workspace's directory is not a readable git repository.")
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens on Files, its only tab, when the workspace folder is not a repo", async () => {
|
||||
vi.mocked(api.lanes.changes).mockResolvedValue({
|
||||
available: false,
|
||||
range: "work",
|
||||
files: [],
|
||||
});
|
||||
render(<LaneChangesPanel laneId={7} />);
|
||||
expect(
|
||||
await screen.findByText("This workspace's directory is not a readable git repository.")
|
||||
).toBeInTheDocument();
|
||||
expect(await screen.findByTestId("lane-changes-browse")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Files" })).toHaveAttribute("aria-pressed", "true");
|
||||
for (const name of ["Changes", "Review", "History"])
|
||||
expect(screen.queryByRole("button", { name })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adds an unversioned file to VCS, for that path alone, and ticks it", async () => {
|
||||
@@ -548,7 +568,38 @@ describe("LaneChangesPanel", () => {
|
||||
expect(screen.queryByTestId("lane-file-edit")).toBeNull();
|
||||
});
|
||||
|
||||
it("reads a folder again on every open, so files added since show (not a stale empty level)", async () => {
|
||||
let filled = false;
|
||||
vi.mocked(api.lanes.gitTree).mockImplementation(async (_t, path = "") => ({
|
||||
available: true,
|
||||
path,
|
||||
entries:
|
||||
path === "src"
|
||||
? filled
|
||||
? [{ name: "app.ts", path: "src/app.ts", dir: false }]
|
||||
: []
|
||||
: [{ name: "src", path: "src", dir: true }],
|
||||
truncated: false,
|
||||
}));
|
||||
const user = userEvent.setup();
|
||||
const { rerender } = render(<LaneChangesPanel laneId={7} full />);
|
||||
const sidebar = await screen.findByTestId("lane-changes-sidebar");
|
||||
await user.click(await within(sidebar).findByText("src"));
|
||||
await waitFor(() => expect(api.lanes.gitTree).toHaveBeenCalledWith(7, "src"));
|
||||
expect(within(sidebar).queryByText("app.ts")).toBeNull();
|
||||
// Source arrives from outside the panel (the File Explorer, a terminal).
|
||||
filled = true;
|
||||
await user.click(within(sidebar).getByText("src")); // close
|
||||
await user.click(within(sidebar).getByText("src")); // open again → read again
|
||||
expect(await within(sidebar).findByText("app.ts")).toBeInTheDocument();
|
||||
// And the header's File Explorer reports a change: open folders re-read.
|
||||
filled = false;
|
||||
rerender(<LaneChangesPanel laneId={7} full filesChanged={1} />);
|
||||
await waitFor(() => expect(within(sidebar).queryByText("app.ts")).toBeNull());
|
||||
});
|
||||
|
||||
it("uploads files into a folder from the tree menu, and downloads a file (issue #78)", async () => {
|
||||
perms.local = false;
|
||||
vi.mocked(api.lanes.gitTree).mockImplementation(async (_t, path = "") => ({
|
||||
available: true,
|
||||
path,
|
||||
@@ -586,6 +637,25 @@ describe("LaneChangesPanel", () => {
|
||||
picked.mockRestore();
|
||||
});
|
||||
|
||||
it("offers no upload, download or File Explorer in local mode", async () => {
|
||||
vi.mocked(api.lanes.gitTree).mockImplementation(async (_t, path = "") => ({
|
||||
available: true,
|
||||
path,
|
||||
entries:
|
||||
path === "out"
|
||||
? [{ name: "report.md", path: "out/report.md", dir: false }]
|
||||
: [{ name: "out", path: "out", dir: true }],
|
||||
truncated: false,
|
||||
}));
|
||||
const user = userEvent.setup();
|
||||
render(<LaneChangesPanel laneId={7} full />);
|
||||
const sidebar = await screen.findByTestId("lane-changes-sidebar");
|
||||
await user.pointer({ keys: "[MouseRight]", target: await within(sidebar).findByText("out") });
|
||||
expect(screen.getByTestId("lane-changes-tree-menu")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("lane-changes-menu-upload")).toBeNull();
|
||||
expect(screen.queryByTestId("lane-changes-menu-explorer")).toBeNull();
|
||||
});
|
||||
|
||||
it("at full width shows the tree as a sidebar and opens a file straight in the editor", async () => {
|
||||
vi.mocked(api.lanes.gitTree).mockResolvedValue({
|
||||
available: true,
|
||||
@@ -1728,6 +1798,24 @@ describe("LaneChangesPanel", () => {
|
||||
expect(screen.getByTestId("lane-file-view")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens a file from Files when the workspace folder is not a repo", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(api.lanes.changes).mockResolvedValue({
|
||||
available: false,
|
||||
range: "work",
|
||||
files: [],
|
||||
});
|
||||
render(<Tabbed laneId={7} />);
|
||||
await screen.findByTestId("lane-changes-browse");
|
||||
|
||||
await user.type(await screen.findByLabelText("Find a file by path…"), "main");
|
||||
await user.click(await screen.findByText("src/main.ts"));
|
||||
expect(await screen.findByTestId("lane-file-view")).toHaveTextContent("const whole = 1;");
|
||||
expect(
|
||||
screen.queryByText("This workspace's directory is not a readable git repository.")
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the overview rows mounted across re-renders (typing in the commit box)", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LaneChangesPanel laneId={7} />);
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
* `~/.claude` (a memory file, a plugin's skill) through `GET /api/cc-config/file`,
|
||||
* an attached image or text file through `GET /api/run/drop/:name`, an image
|
||||
* the session read anywhere else through `GET /api/sessions/:id/image`, and a
|
||||
* text file it read or wrote anywhere else through `GET /api/sessions/:id/file`.
|
||||
* text file it read, wrote or named (a generated report) anywhere else through
|
||||
* `GET /api/sessions/:id/file`.
|
||||
* Anything else (or a file those routes refuse) shows its path only. A Windows path's `\` counts as `/` throughout.
|
||||
* `SkillListModal` is the same dialog over the session's skills, each one's
|
||||
* SKILL.md found by name (`plugin:name` from the plugin list, else the user's
|
||||
|
||||
@@ -25,7 +25,10 @@
|
||||
* bar takes that pane out into a tab of its own there. Dropped on the MIDDLE
|
||||
* of another tab, a tab (or a pane header) joins that tab instead
|
||||
* (`joinGroup`: side by side, then under the right pane, then under the left
|
||||
* one, up to four panes). A right-click on a tab
|
||||
* one, up to four panes). A pane drag held over another tab for `SPRING_MS` shows that tab
|
||||
* (spring-loaded, as a file manager's folder), so the pane can be dropped on
|
||||
* any of its panes' edges; near either end of an overflowing bar a drag
|
||||
* scrolls it. A right-click on a tab
|
||||
* opens the same actions as a menu (`ContextMenu`). With tabs from every
|
||||
* workspace on, `tabs` spans every workspace (each run's `slot` a `paneKey`)
|
||||
* and `workspaceOf` names each tab's workspace before its own name. Settings
|
||||
@@ -57,7 +60,14 @@ import { isSubmitEnter } from "../../lib/keys";
|
||||
import { useAiTools } from "../../hooks/useAiTools";
|
||||
import { AiToolIcon } from "../AiToolIcon";
|
||||
import { freeSlot, startInFreeTab } from "../lanes/startSession";
|
||||
import { PANE_DRAG_TYPE, RunIcon, startPaneDrag, type GroupsUpdate } from "./PaneGrid";
|
||||
import {
|
||||
PANE_DRAG_TYPE,
|
||||
RunIcon,
|
||||
paneDragSlot,
|
||||
setDragChip,
|
||||
startPaneDrag,
|
||||
type GroupsUpdate,
|
||||
} from "./PaneGrid";
|
||||
import { insertionIndex } from "../../lib/laneOrderStorage";
|
||||
import {
|
||||
type PaneGroups,
|
||||
@@ -155,6 +165,11 @@ interface Tab {
|
||||
|
||||
const URGENCY: RunState[] = ["awaiting", "error", "running"];
|
||||
|
||||
/** How long a pane drag rests on a tab before that tab is shown. */
|
||||
export const SPRING_MS = 600;
|
||||
/** Within this many px of an overflowing bar's end, a drag scrolls it. */
|
||||
const EDGE_SCROLL_PX = 40;
|
||||
|
||||
/** The Settings tab's key among the tabs' (a group's key is its slots). */
|
||||
const SETTINGS_KEY = "settings";
|
||||
|
||||
@@ -256,8 +271,59 @@ export function ConsoleTabs({
|
||||
if (!tab || dragged.current.some((s) => tab.slots.includes(s))) return null;
|
||||
return tab.slots.length + Math.max(dragged.current.length, 1) <= MAX_PANES ? i : null;
|
||||
};
|
||||
// A pane drag resting on a tab (its drawn index) shows it after SPRING_MS.
|
||||
const spring = useRef<{ at: number; timer: ReturnType<typeof setTimeout> } | null>(null);
|
||||
const stopSpring = () => {
|
||||
if (spring.current) clearTimeout(spring.current.timer);
|
||||
spring.current = null;
|
||||
};
|
||||
useEffect(() => stopSpring, []);
|
||||
const hoveredIndexAt = (x: number) => {
|
||||
const els = [...(listRef.current?.querySelectorAll<HTMLElement>("[data-tab-index]") ?? [])];
|
||||
return els.findIndex((el) => {
|
||||
const b = el.getBoundingClientRect();
|
||||
return x >= b.left && x <= b.right;
|
||||
});
|
||||
};
|
||||
const springAt = (e: DragEvent) => {
|
||||
const slot = paneDragSlot();
|
||||
const i = hoveredIndexAt(e.clientX);
|
||||
const tab = tabs[i];
|
||||
// Only a pane drag, onto a tab not on screen that does not hold it.
|
||||
const target =
|
||||
slot !== null &&
|
||||
tab &&
|
||||
!settings?.active &&
|
||||
tab.index !== groups.active &&
|
||||
!tab.slots.includes(slot)
|
||||
? i
|
||||
: null;
|
||||
if ((spring.current?.at ?? null) === target) return;
|
||||
stopSpring();
|
||||
if (target === null || !tab) return;
|
||||
const index = tab.index;
|
||||
spring.current = {
|
||||
at: target,
|
||||
timer: setTimeout(() => {
|
||||
spring.current = null;
|
||||
if (paneDragSlot() === null) return;
|
||||
onGroupsChange((g) =>
|
||||
g.active === index || !g.groups[index] ? g : { ...g, active: index }
|
||||
);
|
||||
}, SPRING_MS),
|
||||
};
|
||||
};
|
||||
// An overflowing bar has no scrollbar: near either end, a drag scrolls it.
|
||||
const edgeScroll = (x: number) => {
|
||||
const list = listRef.current;
|
||||
if (!list || list.scrollWidth <= list.clientWidth) return;
|
||||
const b = list.getBoundingClientRect();
|
||||
if (x < b.left + EDGE_SCROLL_PX) list.scrollLeft -= 16;
|
||||
else if (x > b.right - EDGE_SCROLL_PX) list.scrollLeft += 16;
|
||||
};
|
||||
const endDrag = () => {
|
||||
dragged.current = [];
|
||||
stopSpring();
|
||||
setDropAt(null);
|
||||
setJoinAt(null);
|
||||
};
|
||||
@@ -266,6 +332,8 @@ export function ConsoleTabs({
|
||||
if (!isBarDrag(e)) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "move";
|
||||
edgeScroll(e.clientX);
|
||||
springAt(e);
|
||||
const join = joinIndexAt(e.clientX);
|
||||
const at = join === null ? dropIndexAt(e.clientX) : null;
|
||||
setJoinAt((d) => (d === join ? d : join));
|
||||
@@ -273,6 +341,7 @@ export function ConsoleTabs({
|
||||
},
|
||||
onDragLeave: (e: DragEvent) => {
|
||||
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
|
||||
stopSpring();
|
||||
setDropAt(null);
|
||||
setJoinAt(null);
|
||||
},
|
||||
@@ -504,10 +573,11 @@ export function ConsoleTabs({
|
||||
draggable
|
||||
onDragStart={(e) => {
|
||||
dragged.current = tab.slots;
|
||||
if (single) startPaneDrag(e, single.slot ?? 0);
|
||||
if (single) startPaneDrag(e, single.slot ?? 0, label(single));
|
||||
else {
|
||||
e.dataTransfer?.setData(TAB_DRAG_TYPE, String(tab.index));
|
||||
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
|
||||
setDragChip(e, tabLabel(tab));
|
||||
}
|
||||
}}
|
||||
onContextMenu={(e) => tabCtx.open(e, tab)}
|
||||
|
||||
@@ -65,6 +65,7 @@ import { addAttachments, dragAttachments } from "../../lib/promptAttach";
|
||||
import { readChatDraft, writeChatDraft } from "../../lib/chatDraft";
|
||||
import { ChatOutline, outlineAttachment, useSessionOutline, type OutlineList } from "./ChatOutline";
|
||||
import { FileListModal, FilePreview, SkillListModal, type PreviewScope } from "./ChatFilePreview";
|
||||
import { resolveIn } from "../../lib/resolvePath";
|
||||
import { Select } from "../Select";
|
||||
import { Divider, showTerminal } from "./PaneGrid";
|
||||
import {
|
||||
@@ -471,7 +472,9 @@ export const PaneChat = memo(function PaneChat({
|
||||
// (ConversationView is memoized).
|
||||
const openTerminal = useCallback(() => showTerminal(runId, sessionId), [runId, sessionId]);
|
||||
const openFile = useCallback(
|
||||
(path: string) => {
|
||||
(named: string) => {
|
||||
// A relative path in a reply (`server/lib/x.js`) is relative to this pane's folder.
|
||||
const path = resolveIn(cwd, named);
|
||||
// The workspace's Changes panel when the file is in its folder;
|
||||
// else this view's own preview.
|
||||
if (laneId !== null && openInChanges(laneId, cwd, path)) return;
|
||||
|
||||
@@ -14,7 +14,13 @@
|
||||
* one tab's panes; `onChange` applies through `updateActive`, so a session
|
||||
* dropped or swapped in from another tab leaves that tab. A header names the pane's session and
|
||||
* shows its state dot, as its tab does.
|
||||
* Tabs from `ConsoleTabs` drag in the same way (`startPaneDrag`). A
|
||||
* Tabs from `ConsoleTabs` drag in the same way (`startPaneDrag`). While a
|
||||
* drag is on, the pane it carries is dimmed, the browser's ghost is a small
|
||||
* chip with its name (`setDragChip`) instead of a whole header, and the drop
|
||||
* preview names what the drop will do (`dropAction`). The dragged pane's
|
||||
* header stays mounted even once the tab bar has switched tabs under the
|
||||
* drag (`ConsoleTabs` spring-loads a hovered tab) — removing the drag's
|
||||
* source node would lose its `dragend`. A
|
||||
* right-click on a header offers the swap, a split with a new terminal and
|
||||
* the close as one menu. Dividers resize by pointer or by arrow keys; a drag
|
||||
* moves only the line and commits the ratio on release, so the layout is
|
||||
@@ -69,11 +75,31 @@ export const PANE_DRAG_TYPE = "application/x-agenthub-pane";
|
||||
/** The slot being dragged: `dataTransfer` data cannot be read during dragover. */
|
||||
let dragSlot: number | null = null;
|
||||
|
||||
/** Starts dragging a pane or a tab (`slot`) onto the grid. */
|
||||
export function startPaneDrag(e: React.DragEvent, slot: number): void {
|
||||
/** The slot a pane drag carries, or null (no pane drag is on). */
|
||||
export const paneDragSlot = (): number | null => dragSlot;
|
||||
|
||||
/** The drag's ghost: a small chip naming what moves, not a snapshot of a
|
||||
* whole pane header or tab. Drawn off screen for the browser to copy. */
|
||||
export function setDragChip(e: React.DragEvent, label: string): void {
|
||||
const dt = e.dataTransfer;
|
||||
if (!label || typeof dt?.setDragImage !== "function") return;
|
||||
const chip = document.createElement("div");
|
||||
chip.textContent = label;
|
||||
chip.className =
|
||||
"fixed -top-96 left-0 max-w-[16rem] truncate rounded-md border border-accent/60 bg-surface-2 px-2.5 py-1 text-xs font-medium text-fg-primary shadow-lg";
|
||||
document.body.appendChild(chip);
|
||||
dt.setDragImage(chip, 12, 12);
|
||||
// The browser copies it during dragstart; it may go right after.
|
||||
window.setTimeout(() => chip.remove(), 0);
|
||||
}
|
||||
|
||||
/** Starts dragging a pane or a tab (`slot`) onto the grid; `label` names it
|
||||
* on the drag's chip. */
|
||||
export function startPaneDrag(e: React.DragEvent, slot: number, label?: string): void {
|
||||
dragSlot = slot;
|
||||
e.dataTransfer?.setData(PANE_DRAG_TYPE, String(slot));
|
||||
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
|
||||
if (label) setDragChip(e, label);
|
||||
}
|
||||
|
||||
/** A run's icon: a shell's terminal glyph, else its AI tool's mark. */
|
||||
@@ -140,6 +166,14 @@ export function dropPreview(l: PaneLayout, src: number, slot: number, zone: Zone
|
||||
return layoutRects(next.root).panes.find((p) => p.slot === src) ?? null;
|
||||
}
|
||||
|
||||
/** What a drop does, as an i18n key (`lanes` namespace): the center swaps a
|
||||
* pane already shown, or shows one from another tab in the target's place
|
||||
* (the target gets a tab of its own); an edge places it on that side. */
|
||||
export function dropAction(l: PaneLayout, src: number, zone: Zone): string {
|
||||
if (zone !== "center") return `panes.drop.${zone}`;
|
||||
return leaves(l.root).includes(src) ? "panes.drop.swap" : "panes.drop.replace";
|
||||
}
|
||||
|
||||
/** A small anchored menu: a trigger button and a list that closes on a pick,
|
||||
* an outside click or Escape. */
|
||||
function PaneMenu({
|
||||
@@ -398,6 +432,8 @@ export function PaneGrid({
|
||||
const { t } = useTranslation("lanes");
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
const [drop, setDrop] = useState<{ src: number; slot: number; zone: Zone } | null>(null);
|
||||
// The slot a pane drag carries (a header here, or a tab from the bar).
|
||||
const [dragging, setDragging] = useState<number | null>(null);
|
||||
const { panes, dividers } = layoutRects(layout.root);
|
||||
const shown = leaves(layout.root);
|
||||
const rectOf = new Map(panes.map((p) => [p.slot, p]));
|
||||
@@ -416,6 +452,7 @@ export function PaneGrid({
|
||||
const end = () => {
|
||||
dragSlot = null;
|
||||
setDrop(null);
|
||||
setDragging(null);
|
||||
};
|
||||
window.addEventListener("dragend", end);
|
||||
window.addEventListener("drop", end);
|
||||
@@ -479,6 +516,7 @@ export function PaneGrid({
|
||||
if (!isPaneDrag(e)) return;
|
||||
e.preventDefault();
|
||||
if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
|
||||
if (dragSlot !== dragging) setDragging(dragSlot);
|
||||
const z = zoneAt(e);
|
||||
const next = z && dragSlot !== null ? { src: dragSlot, ...z } : null;
|
||||
setDrop((d) =>
|
||||
@@ -495,6 +533,7 @@ export function PaneGrid({
|
||||
const z = zoneAt(e);
|
||||
dragSlot = null;
|
||||
setDrop(null);
|
||||
setDragging(null);
|
||||
if (!z || !Number.isInteger(src) || src === z.slot) return;
|
||||
onChange((l) => applyDrop(l, src, z.slot, z.zone));
|
||||
}}
|
||||
@@ -515,6 +554,7 @@ export function PaneGrid({
|
||||
const r = rectOf.get(slot);
|
||||
const run = runOf(slot);
|
||||
const focused = layout.focus === slot;
|
||||
const moving = dragging === slot;
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
@@ -522,17 +562,23 @@ export function PaneGrid({
|
||||
data-focused={r && focused ? "true" : undefined}
|
||||
// A menu opened in this pane stays inside it (`menuRoom`).
|
||||
data-menu-bounds
|
||||
className={r ? "absolute flex flex-col" : "hidden"}
|
||||
data-dragging={moving ? "true" : undefined}
|
||||
className={r ? `absolute flex flex-col${moving ? " opacity-40" : ""}` : "hidden"}
|
||||
style={r ? pct(r) : undefined}
|
||||
onPointerDownCapture={() => r && focus(slot)}
|
||||
// Tabbing into a pane focuses it as a click does.
|
||||
onFocusCapture={() => r && focus(slot)}
|
||||
>
|
||||
{multi && r && (
|
||||
{/* The dragged pane's header stays while the drag lasts, even
|
||||
hidden in another tab: it is the drag's source node. */}
|
||||
{((multi && r) || moving) && (
|
||||
<div
|
||||
data-testid={`pane-header-${slot}`}
|
||||
draggable
|
||||
onDragStart={(e) => startPaneDrag(e, slot)}
|
||||
onDragStart={(e) => {
|
||||
startPaneDrag(e, slot, run ? label(run) : t("panes.empty"));
|
||||
setDragging(slot);
|
||||
}}
|
||||
onContextMenu={(e) => paneCtx.open(e, slot)}
|
||||
title={t("panes.drag")}
|
||||
className={`relative flex h-8 shrink-0 cursor-grab items-center gap-1 border-b border-border bg-surface-1 pl-1.5 pr-1 text-xs ${
|
||||
@@ -667,12 +713,19 @@ export function PaneGrid({
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{preview && (
|
||||
{preview && drop && (
|
||||
<div
|
||||
data-testid="pane-drop-preview"
|
||||
className="pointer-events-none absolute z-20 rounded-md border-2 border-accent/60 bg-accent/15 transition-all duration-100"
|
||||
className="pointer-events-none absolute z-20 flex items-center justify-center rounded-md border-2 border-accent/60 bg-accent/15 transition-all duration-100"
|
||||
style={pct(preview)}
|
||||
/>
|
||||
>
|
||||
<span
|
||||
data-testid="pane-drop-label"
|
||||
className="max-w-[90%] truncate rounded-md bg-accent-solid px-2.5 py-1 text-xs font-medium text-white shadow-lg"
|
||||
>
|
||||
{t(dropAction(layout, drop.src, drop.zone))}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -69,6 +69,7 @@ import {
|
||||
addAttachments,
|
||||
droppedAttachments,
|
||||
droppedSkill,
|
||||
droppedText,
|
||||
SKILL_MIME,
|
||||
rememberUploads,
|
||||
} from "../../lib/promptAttach";
|
||||
@@ -412,7 +413,8 @@ export function PromptEditor({
|
||||
// else a `bare` editor's parent, the box every caller draws around it and
|
||||
// its toolbar — not only on the textarea: a panel row (`ATTACH_MIME`)
|
||||
// becomes an `@path` chip, a skill (`SKILL_MIME`) the prompt's leading
|
||||
// `/command`, a file is uploaded.
|
||||
// `/command`, a file is uploaded, a local `file://` list an `@path` chip
|
||||
// and any other text is inserted.
|
||||
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||
const dropRef = useRef<(e: DragEvent) => void>(() => {});
|
||||
dropRef.current = (e) => {
|
||||
@@ -425,6 +427,17 @@ export function PromptEditor({
|
||||
e.preventDefault();
|
||||
onChange(`/${skill} ${value.replace(/^\s+/, "")}`);
|
||||
} else if (attachImages(e.dataTransfer?.files)) e.preventDefault();
|
||||
else {
|
||||
// Only text (a file manager's or an editor's `file://` list, a
|
||||
// selection, a link): what the terminal beneath would paste.
|
||||
// On the textarea itself the browser inserts text at the drop point.
|
||||
const dropped = droppedText(e.dataTransfer);
|
||||
if (!dropped || ("text" in dropped && e.target === taRef.current)) return;
|
||||
e.preventDefault();
|
||||
if ("attachments" in dropped)
|
||||
onImagesChange((prev) => addAttachments(prev, dropped.attachments));
|
||||
else insert(dropped.text);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
const zone =
|
||||
@@ -433,7 +446,8 @@ export function PromptEditor({
|
||||
if (!zone) return;
|
||||
const over = (e: DragEvent) => {
|
||||
const types = e.dataTransfer?.types ?? [];
|
||||
if (![ATTACH_MIME, SKILL_MIME, "Files"].some((m) => types.includes(m))) return;
|
||||
const accepts = [ATTACH_MIME, SKILL_MIME, "Files", "text/uri-list", "text/plain"];
|
||||
if (!accepts.some((m) => types.includes(m))) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer!.dropEffect = "copy";
|
||||
};
|
||||
|
||||
@@ -406,6 +406,16 @@ export const TerminalView = memo(function TerminalView({
|
||||
}, 0);
|
||||
return false;
|
||||
}
|
||||
// Ctrl+Z: a terminal sends ^Z (SIGTSTP), which SUSPENDS claude or
|
||||
// codex — the pane drops to its shell and the session looks closed,
|
||||
// with nothing on screen saying `fg` brings it back. In a browser
|
||||
// Ctrl+Z means undo, so it sends Ctrl+_ — undo in Claude Code's prompt
|
||||
// and in bash/readline — and never suspends the program.
|
||||
if (ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey && key === "z") {
|
||||
ev.preventDefault();
|
||||
term.input("\x1f", true);
|
||||
return false;
|
||||
}
|
||||
if (ev.key === "Tab" && tabMovesRef.current) return false;
|
||||
if (ev.key === "Tab" && ev.shiftKey) ev.preventDefault();
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* @file ConsoleTabs.test.tsx
|
||||
* @description The tab bar's spring-loaded tabs: a pane drag resting on
|
||||
* another tab shows it after `SPRING_MS`, so the pane can be dropped on that
|
||||
* tab's panes; moving off before then, or resting on the tab already holding
|
||||
* the pane, shows nothing.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, createEvent, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import type { RunHandle } from "../../../lib/api";
|
||||
import type { Lane } from "../../../lib/types";
|
||||
import { pane, split, type PaneGroups } from "../../../lib/paneLayout";
|
||||
import { ConsoleTabs, SPRING_MS } from "../ConsoleTabs";
|
||||
import { PANE_DRAG_TYPE, paneDragSlot } from "../PaneGrid";
|
||||
|
||||
vi.mock("../../../lib/api", () => ({
|
||||
api: {
|
||||
aiTools: {
|
||||
list: vi.fn().mockResolvedValue({ default: "claude", tools: [] }),
|
||||
models: vi.fn().mockResolvedValue({ flag: true, models: [], defaultModel: null }),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const LANE = { id: 1, tool: "claude", cwd: "/w", title: "w" } as unknown as Lane;
|
||||
const run = (slot: number): RunHandle => ({
|
||||
id: slot ? `agenthub-lane-1-${slot}` : "agenthub-lane-1",
|
||||
laneId: 1,
|
||||
slot,
|
||||
status: "running",
|
||||
cwd: "/w",
|
||||
model: null,
|
||||
permissionMode: null,
|
||||
effort: null,
|
||||
resumeSessionId: null,
|
||||
sessionId: null,
|
||||
startedAt: null,
|
||||
promptPreview: null,
|
||||
tool: "shell",
|
||||
});
|
||||
// Tab 0: pane 0 alone (on screen); tab 1: panes 1 and 2.
|
||||
const GROUPS: PaneGroups = {
|
||||
groups: [
|
||||
{ root: pane(0), focus: 0 },
|
||||
{ root: split("row", pane(1), pane(2)), focus: 1 },
|
||||
],
|
||||
active: 0,
|
||||
};
|
||||
|
||||
function setup() {
|
||||
let groups = GROUPS;
|
||||
const onGroupsChange = vi.fn((fn: (g: PaneGroups) => PaneGroups) => {
|
||||
groups = fn(groups);
|
||||
});
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ConsoleTabs
|
||||
lane={LANE}
|
||||
tabs={[run(0), run(1), run(2)]}
|
||||
groups={GROUPS}
|
||||
onGroupsChange={onGroupsChange}
|
||||
onOpen={vi.fn()}
|
||||
onClosed={vi.fn()}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
// jsdom lays nothing out: tab i spans x 100i … 100i+100.
|
||||
for (const el of document.querySelectorAll<HTMLElement>("[data-tab-index]")) {
|
||||
const i = Number(el.dataset.tabIndex);
|
||||
el.getBoundingClientRect = () =>
|
||||
({
|
||||
left: i * 100,
|
||||
right: i * 100 + 100,
|
||||
width: 100,
|
||||
top: 0,
|
||||
bottom: 40,
|
||||
height: 40,
|
||||
}) as DOMRect;
|
||||
}
|
||||
return { onGroupsChange, groups: () => groups };
|
||||
}
|
||||
|
||||
const dataTransfer = () => ({
|
||||
types: [PANE_DRAG_TYPE],
|
||||
setData: vi.fn(),
|
||||
getData: () => "",
|
||||
effectAllowed: "",
|
||||
dropEffect: "",
|
||||
});
|
||||
|
||||
function drag(type: "dragStart" | "dragOver", el: Element, clientX = 0) {
|
||||
const ev = createEvent[type](el, { dataTransfer: dataTransfer() });
|
||||
Object.defineProperty(ev, "clientX", { value: clientX });
|
||||
fireEvent(el, ev);
|
||||
}
|
||||
|
||||
const tabEl = (key: string) => screen.getByTestId(`console-tab-${key}`).parentElement as Element;
|
||||
|
||||
describe("ConsoleTabs spring-loaded tabs", () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("a pane drag resting on another tab shows that tab", () => {
|
||||
const { onGroupsChange, groups } = setup();
|
||||
drag("dragStart", tabEl("0"));
|
||||
expect(paneDragSlot()).toBe(0);
|
||||
drag("dragOver", tabEl("1-2"), 150);
|
||||
act(() => void vi.advanceTimersByTime(SPRING_MS - 1));
|
||||
expect(onGroupsChange).not.toHaveBeenCalled();
|
||||
act(() => void vi.advanceTimersByTime(1));
|
||||
expect(groups().active).toBe(1);
|
||||
});
|
||||
|
||||
it("moving off the tab first, or resting on the pane's own tab, shows nothing", () => {
|
||||
const { onGroupsChange } = setup();
|
||||
drag("dragStart", tabEl("0"));
|
||||
drag("dragOver", tabEl("1-2"), 150);
|
||||
act(() => void vi.advanceTimersByTime(SPRING_MS / 2));
|
||||
drag("dragOver", tabEl("0"), 50);
|
||||
act(() => void vi.advanceTimersByTime(SPRING_MS * 2));
|
||||
expect(onGroupsChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -434,6 +434,45 @@ describe("PaneChat — the unsent prompt", () => {
|
||||
await waitFor(() => expect(localStorage.getItem("agenthub.chat.draft.s1")).toBeNull());
|
||||
});
|
||||
|
||||
// A drag from outside the dashboard (a file manager, VS Code, a selection)
|
||||
// carries only text: the terminal beneath pastes it, so the chat takes it too.
|
||||
const textDrop = (data: Record<string, string>) => {
|
||||
const drop = new Event("drop", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(drop, "dataTransfer", {
|
||||
value: { types: Object.keys(data), getData: (t: string) => data[t] ?? "", files: [] },
|
||||
});
|
||||
act(() => {
|
||||
screen.getByTestId("pane-chat").dispatchEvent(drop);
|
||||
});
|
||||
return drop;
|
||||
};
|
||||
|
||||
it("attaches the local files of a dropped file:// list", async () => {
|
||||
renderChat();
|
||||
const drop = textDrop({
|
||||
"text/uri-list": "file:///home/u/My%20Docs/spec.md\r\nfile:///home/u/b.ts",
|
||||
"text/plain": "/home/u/My Docs/spec.md",
|
||||
});
|
||||
expect(drop.defaultPrevented).toBe(true);
|
||||
expect(await screen.findByText("spec.md")).toBeInTheDocument();
|
||||
expect(screen.getByText("b.ts")).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByPlaceholderText("Write a message…"), {
|
||||
target: { value: "read" },
|
||||
});
|
||||
fireEvent.click(screen.getByTestId("pane-chat-send"));
|
||||
expect(submitToRun).toHaveBeenCalledWith(
|
||||
"agenthub-lane-1",
|
||||
'read @"/home/u/My Docs/spec.md" @/home/u/b.ts'
|
||||
);
|
||||
});
|
||||
|
||||
it("inserts dropped plain text into the prompt", () => {
|
||||
renderChat();
|
||||
const drop = textDrop({ "text/plain": "src/lib/x.ts" });
|
||||
expect(drop.defaultPrevented).toBe(true);
|
||||
expect(screen.getByPlaceholderText("Write a message…")).toHaveValue("src/lib/x.ts");
|
||||
});
|
||||
|
||||
// Issue #73: before the session starts the CLI may be asking in the terminal
|
||||
// (trust this folder? — "No, exit" preselected); an Enter sent from here
|
||||
// would answer it, so a send asks first.
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
* @file PaneGrid.test.ts
|
||||
* @description The pane drop preview: it draws where the dragged pane will
|
||||
* actually land (`dropPreview` over `applyDrop`), not half of the target's
|
||||
* current box, and nothing for a drop that changes nothing.
|
||||
* current box, and nothing for a drop that changes nothing; and the label
|
||||
* naming what a drop does (`dropAction`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { dropPreview } from "../PaneGrid";
|
||||
import { dropAction, dropPreview } from "../PaneGrid";
|
||||
import { pane, split, type PaneLayout } from "../../../lib/paneLayout";
|
||||
|
||||
const AB: PaneLayout = { root: split("row", pane(0), pane(1)), focus: 0 };
|
||||
@@ -34,3 +35,15 @@ describe("dropPreview", () => {
|
||||
expect(dropPreview(full, 5, 0, "left")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("dropAction", () => {
|
||||
it("an edge places the pane on that side", () => {
|
||||
expect(dropAction(AB, 0, "left")).toBe("panes.drop.left");
|
||||
expect(dropAction(AB, 2, "bottom")).toBe("panes.drop.bottom");
|
||||
});
|
||||
|
||||
it("the center swaps a shown pane, or shows one from another tab in its place", () => {
|
||||
expect(dropAction(AB, 0, "center")).toBe("panes.drop.swap");
|
||||
expect(dropAction(AB, 2, "center")).toBe("panes.drop.replace");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -520,9 +520,15 @@ describe("TerminalView", () => {
|
||||
"application/x-agenthub-attach": '{"path":"@src/a.ts","name":"a.ts"}',
|
||||
"text/plain": "src/a.ts",
|
||||
};
|
||||
const dataTransfer = { types: Object.keys(data), files: [], getData: (k: string) => data[k] ?? "" };
|
||||
const dataTransfer = {
|
||||
types: Object.keys(data),
|
||||
files: [],
|
||||
getData: (k: string) => data[k] ?? "",
|
||||
};
|
||||
fireEvent.dragEnter(screen.getByTestId("terminal-view"), { dataTransfer });
|
||||
expect(screen.getByTestId("terminal-drop")).toHaveTextContent("Drop to paste into the terminal");
|
||||
expect(screen.getByTestId("terminal-drop")).toHaveTextContent(
|
||||
"Drop to paste into the terminal"
|
||||
);
|
||||
fireEvent.drop(screen.getByTestId("terminal-view"), { dataTransfer });
|
||||
expect(pasteMock).toHaveBeenCalledWith("src/a.ts ");
|
||||
expect(screen.queryByTestId("terminal-drop")).toBeNull();
|
||||
@@ -582,6 +588,24 @@ describe("TerminalView", () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// ^Z suspended claude: the pane fell to its shell and the session looked
|
||||
// closed. Ctrl+Z is undo in a browser, so it sends Ctrl+_ instead.
|
||||
it("turns Ctrl+Z into undo (Ctrl+_) and never sends ^Z, which would suspend the session", () => {
|
||||
inputMock.mockClear();
|
||||
render(<TerminalView runId="r1" wsBaseUrl="ws://x" />);
|
||||
const handler = keyHandlerMock.mock.calls[0]![0]! as (e: KeyboardEvent) => boolean;
|
||||
const ev = new KeyboardEvent("keydown", { key: "z", ctrlKey: true, cancelable: true });
|
||||
expect(handler(ev)).toBe(false);
|
||||
expect(ev.defaultPrevented).toBe(true);
|
||||
expect(inputMock).toHaveBeenCalledWith("\x1f", true);
|
||||
expect(inputMock).not.toHaveBeenCalledWith("\x1a", expect.anything());
|
||||
// Other chords with Z are left to xterm (Ctrl+Shift+Z, plain z).
|
||||
expect(handler(new KeyboardEvent("keydown", { key: "Z", ctrlKey: true, shiftKey: true }))).toBe(
|
||||
true
|
||||
);
|
||||
expect(handler(new KeyboardEvent("keydown", { key: "z" }))).toBe(true);
|
||||
});
|
||||
|
||||
// Safari + macOS's own Vietnamese Telex: the first letter is an insertText,
|
||||
// every later key REPLACES the word — the event order captured on a Mac.
|
||||
it("forwards Safari Telex's word replacements as backspaces plus the new tail", () => {
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
* @file AccountSettings.tsx
|
||||
* @description Settings → Account (server mode, any signed-in role): the
|
||||
* account's own information (`GET /api/me/account` — username, role, member
|
||||
* since, workspaces, sessions, active sign-ins, last sign-in), its display name
|
||||
* since, workspaces, sessions, active sign-ins, last sign-in), its avatar
|
||||
* (`PUT`/`DELETE /api/me/avatar` — PNG, JPEG, GIF or WebP, at most 1 MB; the
|
||||
* sidebar shows it at once), its display name
|
||||
* and email (`PATCH /api/me/account`), a password change that asks for the
|
||||
* current one (`POST /api/me/password` — this browser stays signed in, every
|
||||
* other sign-in ends) and "Sign out other devices" (`POST
|
||||
@@ -11,9 +13,17 @@
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ChangeEvent,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LogOut, RefreshCw } from "lucide-react";
|
||||
import { Camera, LogOut, RefreshCw, Trash2 } from "lucide-react";
|
||||
import { api, type MyAccount } from "../../lib/api";
|
||||
import { formatDateTime } from "../../lib/format";
|
||||
import { toast } from "../../lib/toast";
|
||||
@@ -21,6 +31,7 @@ import { confirmDialog } from "../../lib/confirm";
|
||||
import { isSubmitEnter } from "../../lib/keys";
|
||||
import { useAuth } from "../AuthGate";
|
||||
import { ROLE_BADGE } from "../users/UserEditDialog";
|
||||
import { UserAvatar } from "../users/UserAvatar";
|
||||
import { SettingsSection } from "./SettingsRow";
|
||||
|
||||
type ServerAccount = Extract<MyAccount, { mode: "server" }>;
|
||||
@@ -42,8 +53,12 @@ export function AccountSettings() {
|
||||
(r: MyAccount) => {
|
||||
if (r.mode !== "server") return;
|
||||
setAccount(r);
|
||||
// The sidebar shows the display name: let it follow a save at once.
|
||||
updateUser({ displayName: r.user.displayName, email: r.user.email });
|
||||
// The sidebar shows the name and avatar: let them follow a save at once.
|
||||
updateUser({
|
||||
displayName: r.user.displayName,
|
||||
email: r.user.email,
|
||||
avatarAt: r.user.avatarAt ?? null,
|
||||
});
|
||||
},
|
||||
[updateUser]
|
||||
);
|
||||
@@ -72,7 +87,7 @@ export function AccountSettings() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<ProfileCard account={account} />
|
||||
<ProfileCard account={account} onSaved={apply} />
|
||||
<ProfileForm account={account} onSaved={apply} />
|
||||
<PasswordForm />
|
||||
<SignOutOthers logins={account.logins} onDone={load} />
|
||||
@@ -80,19 +95,84 @@ export function AccountSettings() {
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileCard({ account }: { account: ServerAccount }) {
|
||||
/** The largest avatar the server takes (server/lib/avatars.js). */
|
||||
const MAX_AVATAR_BYTES = 1024 * 1024;
|
||||
|
||||
function ProfileCard({
|
||||
account,
|
||||
onSaved,
|
||||
}: {
|
||||
account: ServerAccount;
|
||||
onSaved: (r: MyAccount) => void;
|
||||
}) {
|
||||
const { t } = useTranslation("settings");
|
||||
const { user } = account;
|
||||
const shown = user.displayName || user.username;
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const run = async (op: () => Promise<MyAccount>, done: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
onSaved(await op());
|
||||
toast.success(done);
|
||||
} catch (e) {
|
||||
toast.error(errText(t, e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const pick = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = ""; // the same file can be picked again
|
||||
if (!file) return;
|
||||
if (file.size > MAX_AVATAR_BYTES) {
|
||||
toast.error(t("account.avatar.tooBig"));
|
||||
return;
|
||||
}
|
||||
void run(() => api.me.setAvatar(file), t("account.avatar.saved"));
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="card p-5" data-testid="account-card">
|
||||
<div className="flex items-center gap-4">
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-full bg-accent/15 text-lg font-semibold uppercase text-accent"
|
||||
>
|
||||
{shown.slice(0, 2)}
|
||||
</span>
|
||||
<div className="flex flex-shrink-0 flex-col items-center gap-1.5">
|
||||
<UserAvatar name={shown} avatarAt={user.avatarAt} className="h-14 w-14 text-lg" />
|
||||
<div className="flex items-center gap-0.5">
|
||||
<button
|
||||
type="button"
|
||||
className="btn-ghost h-6 w-6 justify-center p-0"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={busy}
|
||||
title={t("account.avatar.change")}
|
||||
aria-label={t("account.avatar.change")}
|
||||
data-testid="account-avatar-change"
|
||||
>
|
||||
<Camera className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
{user.avatarAt && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn-ghost h-6 w-6 justify-center p-0"
|
||||
onClick={() => void run(() => api.me.removeAvatar(), t("account.avatar.removed"))}
|
||||
disabled={busy}
|
||||
title={t("account.avatar.remove")}
|
||||
aria-label={t("account.avatar.remove")}
|
||||
data-testid="account-avatar-remove"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/gif,image/webp"
|
||||
className="hidden"
|
||||
onChange={pick}
|
||||
data-testid="account-avatar-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h3 className="truncate text-base font-semibold text-fg-primary">{shown}</h3>
|
||||
<p className="truncate text-xs text-fg-muted">
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @file ArtifactsHubSettings — Settings → AI tools → Artifacts Hub: the
|
||||
* admin's server-wide switch that allows or blocks installing a shared skill
|
||||
* or plugin from the Hub into a user's own account (`GET/PUT
|
||||
* /api/artifacts/settings`). Renders nothing in local mode (there is no Hub)
|
||||
* or for anyone the server does not let manage it (`canManage`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { api, type ArtifactSettings } from "../../lib/api";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { SettingsSection, SettingsSwitchRow } from "./SettingsRow";
|
||||
|
||||
export function ArtifactsHubSettings() {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [settings, setSettings] = useState<ArtifactSettings | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.artifacts
|
||||
.settings()
|
||||
.then(setSettings)
|
||||
.catch(() => setSettings(null));
|
||||
}, []);
|
||||
|
||||
if (!settings?.serverMode || !settings.canManage) return null;
|
||||
return (
|
||||
<SettingsSection id="artifacts-hub" title={t("title")}>
|
||||
<SettingsSwitchRow
|
||||
label={t("installsSwitch")}
|
||||
description={t("installsSwitchHint")}
|
||||
checked={settings.installsEnabled}
|
||||
onChange={async (v) => {
|
||||
try {
|
||||
const r = await api.artifacts.setInstallsEnabled(v);
|
||||
setSettings({ ...settings, installsEnabled: r.installsEnabled });
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -64,6 +64,8 @@ export function GitIdentitySettings() {
|
||||
}
|
||||
};
|
||||
|
||||
// ed25519 suits GitHub/GitLab/Gitea; AWS IAM (CodeCommit) accepts only RSA.
|
||||
const [keyType, setKeyType] = useState<"ed25519" | "rsa">("ed25519");
|
||||
const generate = async () => {
|
||||
if (
|
||||
id?.ssh &&
|
||||
@@ -73,7 +75,10 @@ export function GitIdentitySettings() {
|
||||
}))
|
||||
)
|
||||
return;
|
||||
await run(() => api.gitIdentity.generateKey(Boolean(id?.ssh)), t("gitIdentity.keyMade"));
|
||||
await run(
|
||||
() => api.gitIdentity.generateKey(Boolean(id?.ssh), keyType),
|
||||
t("gitIdentity.keyMade")
|
||||
);
|
||||
};
|
||||
|
||||
const removeKey = async () => {
|
||||
@@ -203,6 +208,18 @@ export function GitIdentitySettings() {
|
||||
<h3 className="flex-1 text-xs font-semibold text-fg-primary">
|
||||
{t("gitIdentity.sshTitle")}
|
||||
</h3>
|
||||
{id.writable && (
|
||||
<select
|
||||
aria-label={t("gitIdentity.keyType")}
|
||||
value={keyType}
|
||||
disabled={busy}
|
||||
onChange={(e) => setKeyType(e.target.value === "rsa" ? "rsa" : "ed25519")}
|
||||
className="select !py-1 !text-xs"
|
||||
>
|
||||
<option value="ed25519">{t("gitIdentity.keyEd25519")}</option>
|
||||
<option value="rsa">{t("gitIdentity.keyRsa")}</option>
|
||||
</select>
|
||||
)}
|
||||
{id.writable && (
|
||||
<button type="button" className={BTN} disabled={busy} onClick={() => void generate()}>
|
||||
{id.ssh ? <RefreshCw className="h-3.5 w-3.5" /> : <Plus className="h-3.5 w-3.5" />}
|
||||
@@ -222,6 +239,7 @@ export function GitIdentitySettings() {
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[10px] text-fg-muted">
|
||||
{id.ssh.type === "rsa" ? "RSA 4096 · " : id.ssh.type ? "ED25519 · " : ""}
|
||||
{id.ssh.fingerprint}
|
||||
</span>
|
||||
<button
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* @file AccountSettings.test.tsx
|
||||
* @description Settings → Account: shows the account's own information, saves
|
||||
* only a changed display name/email, refuses a password change whose two new
|
||||
* passwords differ, sends the current + new password, and asks before signing
|
||||
* the other devices out.
|
||||
* passwords differ, sends the current + new password, asks before signing
|
||||
* the other devices out, and uploads/removes the avatar.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -16,6 +16,9 @@ const me = vi.hoisted(() => ({
|
||||
updateAccount: vi.fn(),
|
||||
changePassword: vi.fn(),
|
||||
signOutOthers: vi.fn(),
|
||||
setAvatar: vi.fn(),
|
||||
removeAvatar: vi.fn(),
|
||||
avatarUrl: (at?: string | null) => (at ? `/api/me/avatar?v=${at}` : null),
|
||||
}));
|
||||
vi.mock("../../../lib/api", async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>();
|
||||
@@ -44,7 +47,7 @@ const account = {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
for (const fn of Object.values(me)) fn.mockReset();
|
||||
for (const fn of Object.values(me)) if ("mockReset" in fn) fn.mockReset();
|
||||
me.account.mockResolvedValue(account);
|
||||
me.updateAccount.mockResolvedValue(account);
|
||||
me.changePassword.mockResolvedValue({ ok: true });
|
||||
@@ -53,6 +56,26 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("AccountSettings", () => {
|
||||
it("uploads a picked avatar and removes it again", async () => {
|
||||
const ue = userEvent.setup();
|
||||
const withAvatar = { ...account, user: { ...account.user, avatarAt: "2026-10-14T00:00:00Z" } };
|
||||
me.setAvatar.mockResolvedValue(withAvatar);
|
||||
me.removeAvatar.mockResolvedValue(account);
|
||||
render(<AccountSettings />);
|
||||
await screen.findByTestId("account-card");
|
||||
expect(screen.getByTestId("user-avatar-initials").textContent).toBe("Mi");
|
||||
expect(screen.queryByTestId("account-avatar-remove")).toBeNull();
|
||||
const file = new File([new Uint8Array([0x89, 0x50])], "me.png", { type: "image/png" });
|
||||
await ue.upload(screen.getByTestId("account-avatar-input"), file);
|
||||
await waitFor(() => expect(me.setAvatar).toHaveBeenCalledWith(file));
|
||||
expect((await screen.findByTestId("user-avatar-img")).getAttribute("src")).toBe(
|
||||
"/api/me/avatar?v=2026-10-14T00:00:00Z"
|
||||
);
|
||||
await ue.click(screen.getByTestId("account-avatar-remove"));
|
||||
await waitFor(() => expect(me.removeAvatar).toHaveBeenCalled());
|
||||
expect(await screen.findByTestId("user-avatar-initials")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows the account's own information", async () => {
|
||||
render(<AccountSettings />);
|
||||
const card = await screen.findByTestId("account-card");
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* @file Tests for ArtifactsHubSettings — the admin's Hub install switch in
|
||||
* Settings → AI tools: hidden in local mode and for a non-manager, and a
|
||||
* toggle saves through PUT /api/artifacts/settings.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import "../../../i18n";
|
||||
import { ArtifactsHubSettings } from "../ArtifactsHubSettings";
|
||||
import { api } from "../../../lib/api";
|
||||
|
||||
vi.mock("../../../lib/api", () => ({
|
||||
api: { artifacts: { settings: vi.fn(), setInstallsEnabled: vi.fn() } },
|
||||
}));
|
||||
|
||||
const settings = vi.mocked(api.artifacts.settings);
|
||||
const setInstalls = vi.mocked(api.artifacts.setInstallsEnabled);
|
||||
const base = { serverMode: true, canShare: true, installsEnabled: true, canManage: true };
|
||||
|
||||
describe("ArtifactsHubSettings", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("lets an admin turn Hub installs off", async () => {
|
||||
settings.mockResolvedValue(base);
|
||||
setInstalls.mockResolvedValue({ installsEnabled: false });
|
||||
render(<ArtifactsHubSettings />);
|
||||
const sw = await screen.findByRole("switch", { name: "Allow installing from the Hub" });
|
||||
fireEvent.click(sw);
|
||||
await waitFor(() => expect(setInstalls).toHaveBeenCalledWith(false));
|
||||
await waitFor(() => expect(sw).toHaveAttribute("aria-checked", "false"));
|
||||
});
|
||||
|
||||
it("renders nothing for a non-manager or in local mode", async () => {
|
||||
settings.mockResolvedValue({ ...base, canManage: false });
|
||||
const { container, unmount } = render(<ArtifactsHubSettings />);
|
||||
await waitFor(() => expect(settings).toHaveBeenCalled());
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
unmount();
|
||||
settings.mockResolvedValue({ ...base, serverMode: false });
|
||||
const r = render(<ArtifactsHubSettings />);
|
||||
await waitFor(() => expect(settings).toHaveBeenCalledTimes(2));
|
||||
expect(r.container).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
@@ -50,7 +50,7 @@ describe("GitIdentitySettings", () => {
|
||||
render(<GitIdentitySettings />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Generate SSH key" }));
|
||||
expect(confirmDialog).not.toHaveBeenCalled();
|
||||
expect(api.gitIdentity.generateKey).toHaveBeenCalledWith(false);
|
||||
expect(api.gitIdentity.generateKey).toHaveBeenCalledWith(false, "ed25519");
|
||||
expect(await screen.findByLabelText("Public key")).toHaveValue(KEY.publicKey);
|
||||
});
|
||||
|
||||
@@ -62,7 +62,7 @@ describe("GitIdentitySettings", () => {
|
||||
expect(copyText).toHaveBeenCalledWith(KEY.publicKey);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Replace key" }));
|
||||
expect(confirmDialog).toHaveBeenCalled();
|
||||
await waitFor(() => expect(api.gitIdentity.generateKey).toHaveBeenCalledWith(true));
|
||||
await waitFor(() => expect(api.gitIdentity.generateKey).toHaveBeenCalledWith(true, "ed25519"));
|
||||
});
|
||||
|
||||
it("lets a member save an https login of their own", async () => {
|
||||
@@ -85,6 +85,18 @@ describe("GitIdentitySettings", () => {
|
||||
expect(await screen.findByText("github.com")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("makes an RSA key when that type is picked (AWS CodeCommit takes only RSA)", async () => {
|
||||
vi.mocked(api.gitIdentity.get).mockResolvedValue(view());
|
||||
vi.mocked(api.gitIdentity.generateKey).mockResolvedValue(
|
||||
view({ ssh: { ...KEY, type: "rsa", publicKey: "ssh-rsa AAAAB3 an@agenthub" } })
|
||||
);
|
||||
render(<GitIdentitySettings />);
|
||||
await userEvent.selectOptions(await screen.findByLabelText("Key type"), "rsa");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Generate SSH key" }));
|
||||
expect(api.gitIdentity.generateKey).toHaveBeenCalledWith(false, "rsa");
|
||||
expect(await screen.findByText(/^RSA 4096 · /)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("warns while the commit author is unset and saves it", async () => {
|
||||
vi.mocked(api.gitIdentity.get).mockResolvedValue(view({ author: { name: null, email: null } }));
|
||||
vi.mocked(api.gitIdentity.saveAuthor).mockResolvedValue(view());
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* @file AccountPoolCard.tsx
|
||||
* @description The Users page's account pool card (`GET /api/accounts`): the
|
||||
* Claude and Codex accounts every user's new sessions are spread over, each
|
||||
* with its live panes, $ in the last 5 h / 7 d and quota — so nobody signs in
|
||||
* with its live panes, $ and tokens in the last 5 h / 7 d and quota — so nobody signs in
|
||||
* per user. An admin adds one — for Claude a login MOVED in from a saved
|
||||
* switch-user profile (`GET /api/accounts/profiles`), a pasted
|
||||
* `.credentials.json`, or a `claude setup-token` token; for Codex an OpenAI
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
type PoolProfile,
|
||||
type PoolTool,
|
||||
} from "../../lib/api";
|
||||
import { fmtCost, formatDateTime } from "../../lib/format";
|
||||
import { fmt, fmtCost, formatDateTime } from "../../lib/format";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { isSubmitEnter } from "../../lib/keys";
|
||||
import { useSpin } from "../../hooks/useSpin";
|
||||
@@ -40,6 +40,8 @@ type Row = {
|
||||
livePanes: number;
|
||||
spend5h: number;
|
||||
spend7d: number;
|
||||
tokens5h: number;
|
||||
tokens7d: number;
|
||||
quotaPercent: number | null;
|
||||
full: boolean;
|
||||
};
|
||||
@@ -175,9 +177,14 @@ export function AccountPoolCard({ isAdmin }: { isAdmin: boolean }) {
|
||||
{r.quotaPercent == null ? "—" : `${Math.round(r.quotaPercent)}%`}
|
||||
</td>
|
||||
<td className="px-5 py-2.5 text-right tabular-nums">
|
||||
<div className="text-sm text-fg-primary">{fmtCost(r.spend5h)}</div>
|
||||
<div className="text-sm text-fg-primary">
|
||||
{fmtCost(r.spend5h)}
|
||||
<span className="ml-1.5 text-[11px] text-fg-muted">
|
||||
{t("pool.tokens", { tokens: fmt(r.tokens5h) })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[11px] text-fg-muted">
|
||||
{t("pool.spend7d", { cost: fmtCost(r.spend7d) })}
|
||||
{t("pool.spend7d", { cost: fmtCost(r.spend7d), tokens: fmt(r.tokens7d) })}
|
||||
</div>
|
||||
</td>
|
||||
{isAdmin && (
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* @file UserAvatar.tsx
|
||||
* @description An account's round picture: the signed-in account's own
|
||||
* (`GET /api/me/avatar`) or, with `userId`, another's (`GET
|
||||
* /api/users/:id/avatar`, staff only), versioned by `avatarAt`; without one —
|
||||
* or when the image fails to load — the first letters of its name. Used by the
|
||||
* sidebar's account row, its workspace owner groups and Settings → Account.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { api } from "../../lib/api";
|
||||
|
||||
export function UserAvatar({
|
||||
name,
|
||||
avatarAt,
|
||||
userId,
|
||||
letters = 2,
|
||||
className = "h-7 w-7 text-[11px]",
|
||||
initialsClassName = "bg-accent/15 text-accent",
|
||||
}: {
|
||||
name: string;
|
||||
avatarAt?: string | null;
|
||||
/** Another account's (staff only); omitted = the signed-in account's own. */
|
||||
userId?: number;
|
||||
/** How many letters of the name stand in for a missing picture. */
|
||||
letters?: number;
|
||||
/** Size and font size: the parts that differ between call sites. */
|
||||
className?: string;
|
||||
/** The initials' colours. */
|
||||
initialsClassName?: string;
|
||||
}) {
|
||||
const url = userId != null ? api.users.avatarUrl(userId, avatarAt) : api.me.avatarUrl(avatarAt);
|
||||
// A broken image falls back to the initials, per URL.
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
const base = `flex flex-shrink-0 items-center justify-center overflow-hidden rounded-full ${className}`;
|
||||
if (url && failed !== url) {
|
||||
return (
|
||||
<img
|
||||
src={url}
|
||||
alt=""
|
||||
aria-hidden
|
||||
draggable={false}
|
||||
onError={() => setFailed(url)}
|
||||
className={`${base} object-cover`}
|
||||
data-testid="user-avatar-img"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className={`${base} ${initialsClassName} font-semibold uppercase`}
|
||||
data-testid="user-avatar-initials"
|
||||
>
|
||||
{name.slice(0, letters)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Copy, Eye, EyeOff, Plus, Sparkles, X } from "lucide-react";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { api, type AuthUser, type ServerUserUsage, type UserPatch } from "../../lib/api";
|
||||
import type { Lane } from "../../lib/types";
|
||||
import { fmtCost, formatDateTime } from "../../lib/format";
|
||||
@@ -131,6 +132,38 @@ export function UserEditDialog({
|
||||
}
|
||||
};
|
||||
|
||||
/** Delete the user for good — asked first, with what goes, in red. */
|
||||
const remove = async () => {
|
||||
if (self || busy) return;
|
||||
if (!current) {
|
||||
setError(t("delete.needsPassword"));
|
||||
return;
|
||||
}
|
||||
const name = user.displayName || user.username;
|
||||
const ok = await confirmDialog({
|
||||
title: t("delete.title", { name }),
|
||||
message: t("delete.body", { name, count: owned?.length ?? 0, user: user.username }),
|
||||
confirmLabel: t("delete.confirm"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.users.remove(user.id, current);
|
||||
onDone(t("done.deleted", { name }));
|
||||
} catch (e) {
|
||||
const err = e as Error & { code?: string };
|
||||
setError(
|
||||
err.code && t(`errors.${err.code}`, { defaultValue: "" })
|
||||
? t(`errors.${err.code}`)
|
||||
: err.message
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (isSubmitEnter(e)) {
|
||||
e.preventDefault();
|
||||
@@ -459,8 +492,21 @@ export function UserEditDialog({
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
{!self && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void remove()}
|
||||
disabled={busy}
|
||||
data-testid="user-delete"
|
||||
className="mr-auto rounded-md border border-status-danger/50 px-3 py-1.5 text-sm text-status-danger hover:bg-status-danger/10 disabled:opacity-50"
|
||||
>
|
||||
{t("delete.button")}
|
||||
</button>
|
||||
)}
|
||||
{!changed && (
|
||||
<span className="mr-auto text-xs text-fg-muted">{t("edit.noChanges")}</span>
|
||||
<span className={`text-xs text-fg-muted ${self ? "mr-auto" : ""}`}>
|
||||
{t("edit.noChanges")}
|
||||
</span>
|
||||
)}
|
||||
<button type="button" onClick={onClose} className="btn-ghost">
|
||||
{t("common:cancel")}
|
||||
|
||||
@@ -40,6 +40,8 @@ const POOL: AccountPool = {
|
||||
livePanes: 2,
|
||||
spend5h: 1.5,
|
||||
spend7d: 12,
|
||||
tokens5h: 250_000,
|
||||
tokens7d: 3_400_000,
|
||||
quotaPercent: 42,
|
||||
full: false,
|
||||
},
|
||||
@@ -52,6 +54,8 @@ const POOL: AccountPool = {
|
||||
livePanes: 0,
|
||||
spend5h: 0,
|
||||
spend7d: 0,
|
||||
tokens5h: 0,
|
||||
tokens7d: 0,
|
||||
quotaPercent: null,
|
||||
full: false,
|
||||
},
|
||||
@@ -82,6 +86,8 @@ describe("AccountPoolCard", () => {
|
||||
expect(await screen.findByText("team-1")).toBeInTheDocument();
|
||||
expect(screen.getByText("cx-1")).toBeInTheDocument();
|
||||
expect(screen.getByText("42%")).toBeInTheDocument();
|
||||
expect(screen.getByText("250.0K tokens")).toBeInTheDocument();
|
||||
expect(screen.getByText("$12.00 · 3.4M tokens in 7 days")).toBeInTheDocument();
|
||||
expect(screen.getByText("team1@example.com")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /add account/i })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /remove/i })).toBeNull();
|
||||
|
||||
@@ -13,7 +13,9 @@ import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import type { ServerUserUsage } from "../../../lib/api";
|
||||
|
||||
const users = vi.hoisted(() => ({ get: vi.fn(), update: vi.fn() }));
|
||||
const users = vi.hoisted(() => ({ get: vi.fn(), update: vi.fn(), remove: vi.fn() }));
|
||||
const confirmDialog = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../../../lib/confirm", () => ({ confirmDialog }));
|
||||
const lanes = vi.hoisted(() => ({ list: vi.fn() }));
|
||||
vi.mock("../../../lib/api", async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>();
|
||||
@@ -122,6 +124,45 @@ describe("UserEditDialog", () => {
|
||||
expect(save().hasAttribute("disabled")).toBe(false);
|
||||
});
|
||||
|
||||
it("deletes a user after the admin's password and a red confirm that says what goes", async () => {
|
||||
users.remove.mockReset().mockResolvedValue({ user: mia });
|
||||
confirmDialog.mockReset().mockResolvedValue(true);
|
||||
const ue = userEvent.setup();
|
||||
const { onDone } = open();
|
||||
await screen.findByText("api");
|
||||
// No password yet: asked for it, nothing sent.
|
||||
await ue.click(screen.getByRole("button", { name: "Delete user" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Enter your own password");
|
||||
expect(users.remove).not.toHaveBeenCalled();
|
||||
await ue.type(screen.getByLabelText("Your password"), "boss-pass");
|
||||
await ue.click(screen.getByRole("button", { name: "Delete user" }));
|
||||
expect(confirmDialog).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
destructive: true,
|
||||
message: expect.stringContaining("/srv/agenthub/users/mia"),
|
||||
})
|
||||
);
|
||||
await waitFor(() => expect(users.remove).toHaveBeenCalledWith(2, "boss-pass"));
|
||||
expect(onDone).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends nothing when the confirm is cancelled, and offers no delete for yourself", async () => {
|
||||
users.remove.mockReset();
|
||||
confirmDialog.mockReset().mockResolvedValue(false);
|
||||
const ue = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("api");
|
||||
await ue.type(screen.getByLabelText("Your password"), "boss-pass");
|
||||
await ue.click(screen.getByRole("button", { name: "Delete user" }));
|
||||
expect(users.remove).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("has no Delete button on your own account", async () => {
|
||||
open(mia, true);
|
||||
await screen.findByText("api");
|
||||
expect(screen.queryByRole("button", { name: "Delete user" })).toBeNull();
|
||||
});
|
||||
|
||||
it("generates a 16-character password", async () => {
|
||||
expect(generatePassword()).toHaveLength(16);
|
||||
const ue = userEvent.setup();
|
||||
|
||||
@@ -116,6 +116,7 @@ export const i18nReady = i18n
|
||||
"lanes",
|
||||
"users",
|
||||
"onboarding",
|
||||
"artifacts",
|
||||
],
|
||||
defaultNS: "common",
|
||||
interpolation: { escapeValue: false },
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"title": "Artifacts",
|
||||
"subtitle": "What your agents produced — claude.ai pages, files, skills and plugins — kept in one place.",
|
||||
"subtitleServer": "What your agents produced — claude.ai pages, files, skills and plugins. Share one and it appears in the Hub for everyone.",
|
||||
"tab.mine": "My library",
|
||||
"tab.hub": "Hub",
|
||||
"kind.all": "All",
|
||||
"kind.page": "Pages",
|
||||
"kind.file": "Files",
|
||||
"kind.skill": "Skills",
|
||||
"kind.plugin": "Plugins",
|
||||
"kindOne.page": "Page",
|
||||
"kindOne.file": "File",
|
||||
"kindOne.skill": "Skill",
|
||||
"kindOne.plugin": "Plugin",
|
||||
"search": "Search artifacts…",
|
||||
"add": "Add",
|
||||
"add.page": "claude.ai link",
|
||||
"add.file": "File from a workspace",
|
||||
"add.skill": "Skill",
|
||||
"add.plugin": "Plugin",
|
||||
"empty.mine": "Nothing here yet. Pages your sessions publish appear on their own; add files, skills and plugins with Add.",
|
||||
"empty.hub": "Nobody has shared anything yet.",
|
||||
"loading": "Loading…",
|
||||
"by": "by {{name}}",
|
||||
"shared": "Shared",
|
||||
"share": "Share",
|
||||
"unshare": "Unshare",
|
||||
"shareDone": "Shared to the Hub",
|
||||
"unshareDone": "Removed from the Hub",
|
||||
"open": "Open",
|
||||
"preview": "Preview",
|
||||
"download": "Download",
|
||||
"install": "Install",
|
||||
"installs": "{{count}} installs",
|
||||
"installed": "Installed to {{path}}",
|
||||
"installedPlugin": "Installed {{name}} — start a new session (or /reload-plugins) to use it",
|
||||
"rename": "Edit",
|
||||
"delete": "Delete",
|
||||
"deleteTitle": "Delete “{{title}}”?",
|
||||
"deleteBody": "It is removed from your library and the Hub. Anything already installed from it stays installed.",
|
||||
"deleteConfirm": "Delete",
|
||||
"installTitle": "Install “{{title}}”?",
|
||||
"installSkillBody": "These files are written to your own ~/.claude/skills/{{name}}/. A skill can carry scripts your agent will run — only install what you trust:",
|
||||
"installPluginBody": "Runs, as your account: claude plugin marketplace add {{market}} and claude plugin install {{name}} --scope user. Only install what you trust.",
|
||||
"installConfirm": "Install",
|
||||
"replaceTitle": "Replace your skill “{{name}}”?",
|
||||
"replaceBody": "You already have a skill with that name. Yours is moved to ~/.claude/agenthub-replaced-skills/, not deleted.",
|
||||
"replaceConfirm": "Replace",
|
||||
"installsOff": "Installs are off",
|
||||
"installsSwitch": "Allow installing from the Hub",
|
||||
"installsSwitchHint": "Off: nobody can install a shared skill or plugin into their account.",
|
||||
"form.url": "claude.ai link",
|
||||
"form.title": "Title (optional)",
|
||||
"form.description": "Description (optional)",
|
||||
"form.workspace": "Workspace",
|
||||
"form.pickWorkspace": "Pick a workspace…",
|
||||
"form.noCandidates": "No documents written by this workspace's sessions yet.",
|
||||
"form.pinned": "Pinned",
|
||||
"form.pin": "Pin",
|
||||
"form.missing": "gone",
|
||||
"form.skillFrom": "Skill",
|
||||
"form.fromUser": "mine",
|
||||
"form.fromWorkspace": "workspace",
|
||||
"form.noSkills": "No skills found in your ~/.claude/skills or this workspace's .claude/skills.",
|
||||
"form.pluginKey": "Plugin (name@marketplace)",
|
||||
"form.market": "Marketplace (owner/repo or git URL)",
|
||||
"form.save": "Add",
|
||||
"form.cancel": "Cancel",
|
||||
"added": "Added",
|
||||
"files": "{{count}} files",
|
||||
"close": "Close",
|
||||
"fromSession": "From a session",
|
||||
"form.saveEdit": "Save",
|
||||
"skill.tab.upload": "Upload files",
|
||||
"skill.tab.write": "Write new",
|
||||
"skill.tab.existing": "From my skills",
|
||||
"skill.name": "Skill name",
|
||||
"skill.slugHint": "Installs as ~/.claude/skills/{{slug}}/ and runs as /{{slug}}",
|
||||
"skill.slugBad": "Use letters, digits, '.', '_' or '-'",
|
||||
"skill.description": "Description — when Claude should use this skill",
|
||||
"skill.descriptionHint": "e.g. Use when writing release notes from the git log",
|
||||
"skill.content": "Instructions (the body of SKILL.md)",
|
||||
"skill.contentHint": "Write the steps Claude should follow. You can also paste a whole SKILL.md, frontmatter included.",
|
||||
"skill.dropHint": "Drop a SKILL.md, any Markdown file, a skill folder, several files or a .zip/.skill here",
|
||||
"skill.pickFiles": "Choose files",
|
||||
"skill.pickFolder": "Choose folder",
|
||||
"skill.clear": "Clear",
|
||||
"skill.uploading": "Uploading…",
|
||||
"skill.shape.none": "Nothing to upload",
|
||||
"skill.shape.single-md": "This Markdown file becomes the skill's SKILL.md",
|
||||
"skill.shape.archive": "An archive — it is unpacked; each folder with a SKILL.md becomes a skill",
|
||||
"skill.shape.one": "One skill folder",
|
||||
"skill.shape.many": "{{count}} skills — each is added on its own, named by its folder",
|
||||
"skill.shape.no-skill-md": "No SKILL.md here — add one, or upload a single Markdown file",
|
||||
"skill.manyHint": "Several skills: each keeps its own folder name and the description in its SKILL.md.",
|
||||
"skill.addedMany": "Added {{count}} skills",
|
||||
"plugin.link": "Marketplace link",
|
||||
"plugin.linkHint": "A git repository with .claude-plugin/marketplace.json (https link, the forge's web link, or owner/repo for GitHub), or a link to a marketplace.json.",
|
||||
"plugin.read": "Read plugins",
|
||||
"plugin.reading": "Reading…",
|
||||
"plugin.none": "This marketplace lists no plugins.",
|
||||
"plugin.all": "Select all",
|
||||
"plugin.have": "already added",
|
||||
"plugin.addPicked": "Add {{count}} plugin(s)",
|
||||
"plugin.addedMany": "Added {{count}} plugin(s)",
|
||||
"plugin.manual": "Type name@marketplace by hand (ssh link, private repository…)",
|
||||
"file.fromComputer": "From your computer (≤ 25 MB)",
|
||||
"file.upload": "Upload",
|
||||
"file.tooBig": "The file is larger than 25 MB.",
|
||||
"file.fromWorkspace": "Or pin a document a workspace's sessions wrote"
|
||||
}
|
||||
@@ -31,10 +31,8 @@
|
||||
"addLaneSetupTitle": "Setup",
|
||||
"addLaneTitleLabel": "Title",
|
||||
"addLaneTitlePlaceholder": "Optional",
|
||||
"addLaneToolDefaultBadge": "Default",
|
||||
"addLaneNoTools": "No AI tool is installed and enabled.",
|
||||
"addLaneNoToolsLink": "Open Settings → AI Tools",
|
||||
"addLaneToolHint": "Default AI tool",
|
||||
"addLaneWorktreeDetached": "(detached)",
|
||||
"addLaneWorktreesMore": "+{{count}} more",
|
||||
"addLaneWorktreesTitle": "Worktrees of this repo ({{count}})",
|
||||
@@ -417,6 +415,12 @@
|
||||
"home.addFolder": "Add folder",
|
||||
"home.folderPath": "Absolute folder path",
|
||||
"home.add": "Add",
|
||||
"home.cloneFolders": "Or clone repositories",
|
||||
"home.cloneHint": "One URL per line — each is cloned into {{path}} with your own git login (Settings → Git) and added here.",
|
||||
"home.clonePlaceholder": "https://host/owner/repo.git\ngit@host:owner/other.git",
|
||||
"home.cloneRun": "Clone",
|
||||
"home.cloneRetry": "Retry the failed ones",
|
||||
"home.cloneDone": "Added",
|
||||
"home.suggested": "Untracked worktrees",
|
||||
"home.remove": "Remove",
|
||||
"home.missing": "missing",
|
||||
@@ -432,7 +436,13 @@
|
||||
"tabs.settings": "Settings",
|
||||
"tabs.closeSettings": "Close Settings",
|
||||
"tabs.splitHint": "Ctrl/Cmd+click: open in a split · drag onto a pane to place it",
|
||||
"panes.drag": "Drag to move this pane — onto another pane's edge to split there, onto its middle to swap",
|
||||
"panes.drag": "Drag to move this pane — onto another pane's edge to split there, onto its middle to swap; hold it over another tab to open that tab",
|
||||
"panes.drop.left": "Place on the left",
|
||||
"panes.drop.right": "Place on the right",
|
||||
"panes.drop.top": "Place on top",
|
||||
"panes.drop.bottom": "Place below",
|
||||
"panes.drop.swap": "Swap places",
|
||||
"panes.drop.replace": "Show here — this pane moves to its own tab",
|
||||
"panes.pick": "Show another session in this pane",
|
||||
"panes.empty": "No session",
|
||||
"panes.split.right": "Split right",
|
||||
@@ -606,5 +616,6 @@
|
||||
"fx.userHomes": "Users' homes",
|
||||
"fx.readOnlyHome": "Another user's home — view and download only",
|
||||
"fx.readOnly": "Read-only",
|
||||
"fx.readOnlyHint": "This is another user's home: you can view, copy and download, not change it."
|
||||
"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."
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"activityFeed": "Activity Feed",
|
||||
"artifacts": "Artifacts",
|
||||
"agents": "Agents",
|
||||
"analytics": "Analytics",
|
||||
"avg": "avg",
|
||||
|
||||
@@ -57,8 +57,7 @@
|
||||
"attention": "Needs you",
|
||||
"attentionError": "errored",
|
||||
"attentionWaiting": "waiting on you",
|
||||
"attentionMore": "+{{count}} more in Sessions",
|
||||
"chat": "Chat with {{name}}"
|
||||
"attentionMore": "+{{count}} more in Sessions"
|
||||
},
|
||||
"bubbleDismiss": "Dismiss",
|
||||
"open": "Open {{name}} companion",
|
||||
@@ -911,11 +910,14 @@
|
||||
"removeKeyConfirm": "Delete this SSH key? Clones that use it can no longer fetch or push.",
|
||||
"publicKey": "Public key",
|
||||
"copy": "Copy public key",
|
||||
"addKeyHint": "Add this public key to your account on the git host (GitHub: Settings → SSH and GPG keys; GitLab: Preferences → SSH Keys). The private key never leaves the server.",
|
||||
"addKeyHint": "Add this public key to your account on the git host (GitHub: Settings → SSH and GPG keys; GitLab: Preferences → SSH Keys; AWS: IAM → Security credentials → SSH public keys — RSA only). Paste the whole line as one line. The private key never leaves the server.",
|
||||
"noKey": "No SSH key yet. Without one, an SSH clone uses the account's default ~/.ssh keys.",
|
||||
"httpsTitle": "HTTPS logins",
|
||||
"noLogins": "No HTTPS login saved. A clone asks for one when a host needs it.",
|
||||
"removeLoginConfirm": "Delete the login for {{host}}? Clones from that host will ask for a login again."
|
||||
"removeLoginConfirm": "Delete the login for {{host}}? Clones from that host will ask for a login again.",
|
||||
"keyType": "Key type",
|
||||
"keyEd25519": "ED25519 (GitHub, GitLab, Gitea)",
|
||||
"keyRsa": "RSA 4096 (AWS CodeCommit, older servers)"
|
||||
},
|
||||
"gitCreds": {
|
||||
"title": "Git credentials",
|
||||
@@ -1265,6 +1267,13 @@
|
||||
"appliesTo": "Applies to"
|
||||
},
|
||||
"account": {
|
||||
"avatar": {
|
||||
"change": "Change picture",
|
||||
"remove": "Remove picture",
|
||||
"saved": "Picture updated",
|
||||
"removed": "Picture removed",
|
||||
"tooBig": "The picture must be at most 1 MB"
|
||||
},
|
||||
"loadFailed": "Could not load your account: {{message}}",
|
||||
"memberSince": "Member since",
|
||||
"workspaces": "Workspaces",
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
"sessions": "Sessions",
|
||||
"last7d": "7 days",
|
||||
"last30d": "30 days",
|
||||
"storage": "Storage",
|
||||
"storageHint": "{{files}} files · measured {{at}}",
|
||||
"storagePartial": "at least — part of the folder could not be read in time",
|
||||
"storageNone": "No home folder of their own",
|
||||
"storageMeasuring": "Measuring…",
|
||||
"disabled": "disabled",
|
||||
"you": "you",
|
||||
"tokens": "{{n}} tokens",
|
||||
@@ -57,9 +62,12 @@
|
||||
"enabled": "{{name}} enabled",
|
||||
"password": "{{name}}'s password reset",
|
||||
"workspace": "Workspace given to {{name}}",
|
||||
"updated": "{{name}} updated"
|
||||
"updated": "{{name}} updated",
|
||||
"deleted": "{{name}} was deleted."
|
||||
},
|
||||
"errors": {
|
||||
"EBADIMAGE": "Only a PNG, JPEG, GIF or WebP picture",
|
||||
"ETOOBIG": "The picture must be at most 1 MB",
|
||||
"EREAUTH": "Your password is wrong.",
|
||||
"ETOOMANY": "Too many wrong passwords. Try again in 15 minutes.",
|
||||
"ESELF": "You cannot change your own role or disable yourself.",
|
||||
@@ -72,7 +80,8 @@
|
||||
"ENOTOWNED": "That workspace is not this user's any more.",
|
||||
"EOWNERFOLDER": "That workspace's folder belongs to another user's account.",
|
||||
"EBADROLE": "Unknown role.",
|
||||
"ELOCALMODE": "Accounts are managed in server mode only."
|
||||
"ELOCALMODE": "Accounts are managed in server mode only.",
|
||||
"ELASTADMIN": "The last admin cannot be deleted."
|
||||
},
|
||||
"readOnly": "Analysts can view accounts but not change them.",
|
||||
"auditTitle": "Audit log",
|
||||
@@ -126,7 +135,8 @@
|
||||
"livePanes": "Live",
|
||||
"quota": "Quota",
|
||||
"spend": "5 hours",
|
||||
"spend7d": "{{cost}} in 7 days",
|
||||
"spend7d": "{{cost}} · {{tokens}} tokens in 7 days",
|
||||
"tokens": "{{tokens}} tokens",
|
||||
"added": "added {{at}}",
|
||||
"expired": "expired",
|
||||
"full": "full",
|
||||
@@ -187,5 +197,12 @@
|
||||
"codex": "An OpenAI API key (sk-…), or the whole ~/.codex/auth.json after `codex login` with a ChatGPT account."
|
||||
},
|
||||
"refreshFailed": "refresh failed"
|
||||
},
|
||||
"delete": {
|
||||
"button": "Delete user",
|
||||
"title": "Delete {{name}}?",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"title": "Artifacts",
|
||||
"subtitle": "Những gì agent đã tạo ra — trang claude.ai, file, skill và plugin — gom một chỗ.",
|
||||
"subtitleServer": "Những gì agent đã tạo ra — trang claude.ai, file, skill và plugin. Chia sẻ một mục là nó hiện trong Hub cho mọi người.",
|
||||
"tab.mine": "Thư viện của tôi",
|
||||
"tab.hub": "Hub",
|
||||
"kind.all": "Tất cả",
|
||||
"kind.page": "Trang",
|
||||
"kind.file": "File",
|
||||
"kind.skill": "Skill",
|
||||
"kind.plugin": "Plugin",
|
||||
"kindOne.page": "Trang",
|
||||
"kindOne.file": "File",
|
||||
"kindOne.skill": "Skill",
|
||||
"kindOne.plugin": "Plugin",
|
||||
"search": "Tìm artifact…",
|
||||
"add": "Thêm",
|
||||
"add.page": "Link claude.ai",
|
||||
"add.file": "File từ workspace",
|
||||
"add.skill": "Skill",
|
||||
"add.plugin": "Plugin",
|
||||
"empty.mine": "Chưa có gì. Trang mà phiên publish sẽ tự xuất hiện; thêm file, skill và plugin bằng nút Thêm.",
|
||||
"empty.hub": "Chưa ai chia sẻ gì.",
|
||||
"loading": "Đang tải…",
|
||||
"by": "của {{name}}",
|
||||
"shared": "Đã chia sẻ",
|
||||
"share": "Chia sẻ",
|
||||
"unshare": "Bỏ chia sẻ",
|
||||
"shareDone": "Đã chia sẻ lên Hub",
|
||||
"unshareDone": "Đã gỡ khỏi Hub",
|
||||
"open": "Mở",
|
||||
"preview": "Xem",
|
||||
"download": "Tải về",
|
||||
"install": "Cài",
|
||||
"installs": "{{count}} lượt cài",
|
||||
"installed": "Đã cài vào {{path}}",
|
||||
"installedPlugin": "Đã cài {{name}} — mở phiên mới (hoặc /reload-plugins) để dùng",
|
||||
"rename": "Sửa",
|
||||
"delete": "Xoá",
|
||||
"deleteTitle": "Xoá “{{title}}”?",
|
||||
"deleteBody": "Mục này bị gỡ khỏi thư viện của bạn và Hub. Những bản người khác đã cài vẫn giữ nguyên.",
|
||||
"deleteConfirm": "Xoá",
|
||||
"installTitle": "Cài “{{title}}”?",
|
||||
"installSkillBody": "Các file này được ghi vào ~/.claude/skills/{{name}}/ của chính bạn. Skill có thể kèm script mà agent sẽ chạy — chỉ cài thứ bạn tin:",
|
||||
"installPluginBody": "Chạy dưới tài khoản của bạn: claude plugin marketplace add {{market}} và claude plugin install {{name}} --scope user. Chỉ cài thứ bạn tin.",
|
||||
"installConfirm": "Cài",
|
||||
"replaceTitle": "Thay skill “{{name}}” của bạn?",
|
||||
"replaceBody": "Bạn đã có skill trùng tên. Bản cũ được chuyển vào ~/.claude/agenthub-replaced-skills/, không bị xoá.",
|
||||
"replaceConfirm": "Thay",
|
||||
"installsOff": "Đang tắt cài đặt",
|
||||
"installsSwitch": "Cho phép cài từ Hub",
|
||||
"installsSwitchHint": "Tắt: không ai cài được skill hay plugin chia sẻ vào tài khoản của mình.",
|
||||
"form.url": "Link claude.ai",
|
||||
"form.title": "Tiêu đề (tuỳ chọn)",
|
||||
"form.description": "Mô tả (tuỳ chọn)",
|
||||
"form.workspace": "Workspace",
|
||||
"form.pickWorkspace": "Chọn workspace…",
|
||||
"form.noCandidates": "Các phiên của workspace này chưa ghi tài liệu nào.",
|
||||
"form.pinned": "Đã ghim",
|
||||
"form.pin": "Ghim",
|
||||
"form.missing": "đã mất",
|
||||
"form.skillFrom": "Skill",
|
||||
"form.fromUser": "của tôi",
|
||||
"form.fromWorkspace": "workspace",
|
||||
"form.noSkills": "Không thấy skill nào trong ~/.claude/skills của bạn hay .claude/skills của workspace này.",
|
||||
"form.pluginKey": "Plugin (tên@marketplace)",
|
||||
"form.market": "Marketplace (owner/repo hoặc git URL)",
|
||||
"form.save": "Thêm",
|
||||
"form.cancel": "Huỷ",
|
||||
"added": "Đã thêm",
|
||||
"files": "{{count}} file",
|
||||
"close": "Đóng",
|
||||
"fromSession": "Từ một phiên",
|
||||
"form.saveEdit": "Lưu",
|
||||
"skill.tab.upload": "Tải file lên",
|
||||
"skill.tab.write": "Viết mới",
|
||||
"skill.tab.existing": "Từ skill có sẵn",
|
||||
"skill.name": "Tên skill",
|
||||
"skill.slugHint": "Cài vào ~/.claude/skills/{{slug}}/ và gọi bằng /{{slug}}",
|
||||
"skill.slugBad": "Chỉ dùng chữ, số, '.', '_' hoặc '-'",
|
||||
"skill.description": "Mô tả — khi nào Claude nên dùng skill này",
|
||||
"skill.descriptionHint": "VD: Dùng khi viết release notes từ git log",
|
||||
"skill.content": "Hướng dẫn (nội dung SKILL.md)",
|
||||
"skill.contentHint": "Viết các bước Claude cần làm. Có thể dán nguyên một file SKILL.md, kể cả frontmatter.",
|
||||
"skill.dropHint": "Kéo thả vào đây: SKILL.md, một file Markdown bất kỳ, thư mục skill, nhiều file hoặc file .zip/.skill",
|
||||
"skill.pickFiles": "Chọn file",
|
||||
"skill.pickFolder": "Chọn thư mục",
|
||||
"skill.clear": "Bỏ chọn",
|
||||
"skill.uploading": "Đang tải lên…",
|
||||
"skill.shape.none": "Chưa có gì để tải lên",
|
||||
"skill.shape.single-md": "File Markdown này sẽ thành SKILL.md của skill",
|
||||
"skill.shape.archive": "File nén — sẽ được giải nén; mỗi thư mục có SKILL.md thành một skill",
|
||||
"skill.shape.one": "Một thư mục skill",
|
||||
"skill.shape.many": "{{count}} skill — mỗi skill được thêm riêng, đặt tên theo thư mục",
|
||||
"skill.shape.no-skill-md": "Không có SKILL.md — thêm một file SKILL.md, hoặc chỉ tải lên một file Markdown",
|
||||
"skill.manyHint": "Nhiều skill: mỗi skill giữ tên thư mục và mô tả trong SKILL.md của nó.",
|
||||
"skill.addedMany": "Đã thêm {{count}} skill",
|
||||
"plugin.link": "Link marketplace",
|
||||
"plugin.linkHint": "Repo git có .claude-plugin/marketplace.json (link https, link trang web của repo, hoặc owner/repo với GitHub), hoặc link tới file marketplace.json.",
|
||||
"plugin.read": "Đọc danh sách plugin",
|
||||
"plugin.reading": "Đang đọc…",
|
||||
"plugin.none": "Marketplace này không có plugin nào.",
|
||||
"plugin.all": "Chọn tất cả",
|
||||
"plugin.have": "đã thêm",
|
||||
"plugin.addPicked": "Thêm {{count}} plugin",
|
||||
"plugin.addedMany": "Đã thêm {{count}} plugin",
|
||||
"plugin.manual": "Nhập tay name@marketplace (link ssh, repo riêng tư…)",
|
||||
"file.fromComputer": "Từ máy tính (≤ 25 MB)",
|
||||
"file.upload": "Tải lên",
|
||||
"file.tooBig": "File lớn hơn 25 MB.",
|
||||
"file.fromWorkspace": "Hoặc ghim tài liệu do các phiên của workspace đã ghi"
|
||||
}
|
||||
@@ -31,10 +31,8 @@
|
||||
"addLaneSetupTitle": "Thiết lập",
|
||||
"addLaneTitleLabel": "Tiêu đề",
|
||||
"addLaneTitlePlaceholder": "Không bắt buộc",
|
||||
"addLaneToolDefaultBadge": "Mặc định",
|
||||
"addLaneNoTools": "Chưa có AI tool nào được cài và bật.",
|
||||
"addLaneNoToolsLink": "Mở Cài đặt → AI Tools",
|
||||
"addLaneToolHint": "AI tool mặc định",
|
||||
"addLaneWorktreeDetached": "(detached)",
|
||||
"addLaneWorktreesMore": "+{{count}} nữa",
|
||||
"addLaneWorktreesTitle": "Worktree của repo này ({{count}})",
|
||||
@@ -417,6 +415,12 @@
|
||||
"home.addFolder": "Thêm thư mục",
|
||||
"home.folderPath": "Đường dẫn tuyệt đối của thư mục",
|
||||
"home.add": "Thêm",
|
||||
"home.cloneFolders": "Hoặc clone repo",
|
||||
"home.cloneHint": "Mỗi dòng một URL — từng repo được clone vào {{path}} bằng login git của bạn (Cài đặt → Git) rồi thêm vào đây.",
|
||||
"home.clonePlaceholder": "https://host/owner/repo.git\ngit@host:owner/other.git",
|
||||
"home.cloneRun": "Clone",
|
||||
"home.cloneRetry": "Thử lại các repo lỗi",
|
||||
"home.cloneDone": "Đã thêm",
|
||||
"home.suggested": "Worktree chưa theo dõi",
|
||||
"home.remove": "Gỡ",
|
||||
"home.missing": "không còn",
|
||||
@@ -432,7 +436,13 @@
|
||||
"tabs.settings": "Cài đặt",
|
||||
"tabs.closeSettings": "Đóng Cài đặt",
|
||||
"tabs.splitHint": "Ctrl/Cmd+click: mở ở split · kéo thả vào một pane để đặt vị trí",
|
||||
"panes.drag": "Kéo để di chuyển pane — thả vào cạnh pane khác để tách ở đó, vào giữa để đổi chỗ",
|
||||
"panes.drag": "Kéo để di chuyển pane — thả vào cạnh pane khác để tách ở đó, vào giữa để đổi chỗ; giữ trên một tab khác để mở tab đó",
|
||||
"panes.drop.left": "Đặt bên trái",
|
||||
"panes.drop.right": "Đặt bên phải",
|
||||
"panes.drop.top": "Đặt phía trên",
|
||||
"panes.drop.bottom": "Đặt phía dưới",
|
||||
"panes.drop.swap": "Đổi chỗ",
|
||||
"panes.drop.replace": "Hiện ở đây — pane này sang tab riêng",
|
||||
"panes.pick": "Hiện session khác trong pane này",
|
||||
"panes.empty": "Không có session",
|
||||
"panes.split.right": "Tách sang phải",
|
||||
@@ -606,5 +616,6 @@
|
||||
"fx.userHomes": "Home của các user",
|
||||
"fx.readOnlyHome": "Home của user khác — chỉ xem và tải về",
|
||||
"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.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."
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"activityFeed": "Luồng hoạt động",
|
||||
"artifacts": "Artifacts",
|
||||
"agents": "Agent",
|
||||
"analytics": "Phân tích",
|
||||
"avg": "TB",
|
||||
|
||||
@@ -57,8 +57,7 @@
|
||||
"attention": "Cần bạn xem",
|
||||
"attentionError": "bị lỗi",
|
||||
"attentionWaiting": "đang chờ bạn",
|
||||
"attentionMore": "+{{count}} phiên khác trong Phiên",
|
||||
"chat": "Trò chuyện với {{name}}"
|
||||
"attentionMore": "+{{count}} phiên khác trong Phiên"
|
||||
},
|
||||
"bubbleDismiss": "Đóng",
|
||||
"open": "Mở trợ lý {{name}}",
|
||||
@@ -911,11 +910,14 @@
|
||||
"removeKeyConfirm": "Xoá SSH key này? Các bản clone dùng nó sẽ không fetch/push được nữa.",
|
||||
"publicKey": "Public key",
|
||||
"copy": "Copy public key",
|
||||
"addKeyHint": "Thêm public key này vào tài khoản trên git host (GitHub: Settings → SSH and GPG keys; GitLab: Preferences → SSH Keys). Private key không bao giờ rời khỏi server.",
|
||||
"addKeyHint": "Thêm public key này vào tài khoản trên git host (GitHub: Settings → SSH and GPG keys; GitLab: Preferences → SSH Keys; AWS: IAM → Security credentials → SSH public keys — chỉ nhận RSA). Dán nguyên dòng, trên một dòng. Private key không bao giờ rời khỏi server.",
|
||||
"noKey": "Chưa có SSH key. Khi chưa có, clone qua SSH dùng key mặc định trong ~/.ssh của tài khoản.",
|
||||
"httpsTitle": "Đăng nhập HTTPS",
|
||||
"noLogins": "Chưa lưu đăng nhập HTTPS nào. Khi clone, host nào cần sẽ hỏi.",
|
||||
"removeLoginConfirm": "Xoá đăng nhập của {{host}}? Clone từ host đó sẽ hỏi đăng nhập lại."
|
||||
"removeLoginConfirm": "Xoá đăng nhập của {{host}}? Clone từ host đó sẽ hỏi đăng nhập lại.",
|
||||
"keyType": "Loại key",
|
||||
"keyEd25519": "ED25519 (GitHub, GitLab, Gitea)",
|
||||
"keyRsa": "RSA 4096 (AWS CodeCommit, server cũ)"
|
||||
},
|
||||
"gitCreds": {
|
||||
"title": "Git credentials",
|
||||
@@ -1265,6 +1267,13 @@
|
||||
"appliesTo": "Áp dụng cho"
|
||||
},
|
||||
"account": {
|
||||
"avatar": {
|
||||
"change": "Đổi ảnh đại diện",
|
||||
"remove": "Xoá ảnh đại diện",
|
||||
"saved": "Đã cập nhật ảnh đại diện",
|
||||
"removed": "Đã xoá ảnh đại diện",
|
||||
"tooBig": "Ảnh tối đa 1 MB"
|
||||
},
|
||||
"loadFailed": "Không tải được tài khoản: {{message}}",
|
||||
"memberSince": "Tham gia từ",
|
||||
"workspaces": "Workspace",
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
"sessions": "Phiên",
|
||||
"last7d": "7 ngày",
|
||||
"last30d": "30 ngày",
|
||||
"storage": "Dung lượng",
|
||||
"storageHint": "{{files}} tệp · đo lúc {{at}}",
|
||||
"storagePartial": "ít nhất — một phần thư mục chưa đọc được kịp",
|
||||
"storageNone": "Không có thư mục home riêng",
|
||||
"storageMeasuring": "Đang đo…",
|
||||
"disabled": "đã khoá",
|
||||
"you": "bạn",
|
||||
"tokens": "{{n}} token",
|
||||
@@ -57,9 +62,12 @@
|
||||
"enabled": "Đã mở khoá {{name}}",
|
||||
"password": "Đã đặt lại mật khẩu cho {{name}}",
|
||||
"workspace": "Đã giao workspace cho {{name}}",
|
||||
"updated": "Đã cập nhật {{name}}"
|
||||
"updated": "Đã cập nhật {{name}}",
|
||||
"deleted": "Đã xoá {{name}}."
|
||||
},
|
||||
"errors": {
|
||||
"EBADIMAGE": "Chỉ nhận ảnh PNG, JPEG, GIF hoặc WebP",
|
||||
"ETOOBIG": "Ảnh tối đa 1 MB",
|
||||
"EREAUTH": "Mật khẩu của bạn không đúng.",
|
||||
"ETOOMANY": "Nhập sai mật khẩu quá nhiều lần. Thử lại sau 15 phút.",
|
||||
"ESELF": "Bạn không thể tự đổi vai trò hay tự khoá chính mình.",
|
||||
@@ -72,7 +80,8 @@
|
||||
"ENOTOWNED": "Workspace đó không còn thuộc người này.",
|
||||
"EOWNERFOLDER": "Thư mục của workspace đó thuộc tài khoản của người dùng khác.",
|
||||
"EBADROLE": "Vai trò không hợp lệ.",
|
||||
"ELOCALMODE": "Chỉ quản lý tài khoản được ở chế độ server."
|
||||
"ELOCALMODE": "Chỉ quản lý tài khoản được ở chế độ server.",
|
||||
"ELASTADMIN": "Không thể xoá admin cuối cùng."
|
||||
},
|
||||
"readOnly": "Analyst chỉ xem được tài khoản, không thay đổi được.",
|
||||
"auditTitle": "Nhật ký audit",
|
||||
@@ -126,7 +135,8 @@
|
||||
"livePanes": "Đang chạy",
|
||||
"quota": "Quota",
|
||||
"spend": "5 giờ",
|
||||
"spend7d": "{{cost}} trong 7 ngày",
|
||||
"spend7d": "{{cost}} · {{tokens}} tokens trong 7 ngày",
|
||||
"tokens": "{{tokens}} tokens",
|
||||
"added": "thêm lúc {{at}}",
|
||||
"expired": "hết hạn",
|
||||
"full": "đầy",
|
||||
@@ -187,5 +197,12 @@
|
||||
"codex": "OpenAI API key (sk-…), hoặc toàn bộ ~/.codex/auth.json sau khi `codex login` bằng tài khoản ChatGPT."
|
||||
},
|
||||
"refreshFailed": "làm mới lỗi"
|
||||
},
|
||||
"delete": {
|
||||
"button": "Xoá user",
|
||||
"title": "Xoá {{name}}?",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
|
||||
+242
-6
@@ -544,6 +544,14 @@ export type ServerUserUsage = AuthUser & {
|
||||
logins?: number;
|
||||
lastLoginAt?: string | null;
|
||||
};
|
||||
/** One user's home folder on disk (`GET /api/users/storage`); null = not measured. */
|
||||
export type UserStorage = {
|
||||
bytes: number;
|
||||
files: number;
|
||||
/** The walk timed out or met an unreadable folder: a lower bound. */
|
||||
partial: boolean;
|
||||
measuredAt: string;
|
||||
} | null;
|
||||
/** GET /api/users/:id — one account plus the workspaces it owns. */
|
||||
export type UserDetail = {
|
||||
user: AuthUser & { disabled: boolean; logins?: number; lastLoginAt?: string | null };
|
||||
@@ -585,6 +593,8 @@ export type PoolAccount = {
|
||||
livePanes: number;
|
||||
spend5h: number;
|
||||
spend7d: number;
|
||||
tokens5h: number;
|
||||
tokens7d: number;
|
||||
quotaPercent: number | null;
|
||||
full: boolean;
|
||||
};
|
||||
@@ -596,6 +606,8 @@ export type CodexPoolAccount = {
|
||||
livePanes: number;
|
||||
spend5h: number;
|
||||
spend7d: number;
|
||||
tokens5h: number;
|
||||
tokens7d: number;
|
||||
quotaPercent: number | null;
|
||||
full: boolean;
|
||||
};
|
||||
@@ -644,6 +656,8 @@ export type AuthUser = {
|
||||
/** Optional profile fields — absent from an older server's answers. */
|
||||
displayName?: string | null;
|
||||
email?: string | null;
|
||||
/** When the account's avatar was last set (null = none) — versions its URL. */
|
||||
avatarAt?: string | null;
|
||||
createdAt?: string;
|
||||
};
|
||||
export type AuthState = { mode: "local" } | { mode: "server"; user: AuthUser | null };
|
||||
@@ -679,6 +693,10 @@ async function send<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
...(token ? { "x-dashboard-token": token } : {}),
|
||||
...((options?.headers as Record<string, string>) || {}),
|
||||
};
|
||||
// A multipart upload: the browser writes Content-Type with its boundary.
|
||||
if (typeof FormData !== "undefined" && options?.body instanceof FormData) {
|
||||
delete headers["Content-Type"];
|
||||
}
|
||||
const res = await fetch(`${BASE}${path}`, { ...options, headers });
|
||||
if (!res.ok) {
|
||||
// Try to recover a structured error message from the JSON body; if the body
|
||||
@@ -857,14 +875,35 @@ export const api = {
|
||||
}),
|
||||
/** POST /api/me/sign-out-others — end every login of this account but this one. */
|
||||
signOutOthers: () => request<{ ended: number }>("/me/sign-out-others", { method: "POST" }),
|
||||
/** URL of this account's avatar, versioned by `avatarAt` (null = none). */
|
||||
avatarUrl: (avatarAt?: string | null) =>
|
||||
avatarAt ? `${BASE}/me/avatar?v=${encodeURIComponent(avatarAt)}` : null,
|
||||
/** PUT /api/me/avatar — one PNG, JPEG, GIF or WebP image, at most 1 MB. */
|
||||
setAvatar: (file: Blob) =>
|
||||
request<MyAccount>("/me/avatar", {
|
||||
method: "PUT",
|
||||
body: file,
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
}),
|
||||
/** DELETE /api/me/avatar — back to the initials. */
|
||||
removeAvatar: () => request<MyAccount>("/me/avatar", { method: "DELETE" }),
|
||||
},
|
||||
// ───────────────────────── Server mode staff views (routes/users.js) ─────────────────────────
|
||||
users: {
|
||||
/** URL of one account's avatar (admin/analyst), versioned by `avatarAt` (null = none). */
|
||||
avatarUrl: (id: number, avatarAt?: string | null) =>
|
||||
avatarAt ? `${BASE}/users/${id}/avatar?v=${encodeURIComponent(avatarAt)}` : null,
|
||||
/** GET /api/users — every account with its recent usage (admin/analyst). */
|
||||
list: () => request<{ users: ServerUserUsage[] }>("/users"),
|
||||
/** GET /api/users/audit — staff reads of members' sessions and admins'
|
||||
* account changes, newest first. */
|
||||
audit: () => request<{ entries: AuditEntry[] }>("/users/audit"),
|
||||
/** GET /api/users/storage — each user's home size, measured in the background
|
||||
* (`measuring` = more numbers are coming); `refresh` re-measures every home. */
|
||||
storage: (refresh = false) =>
|
||||
request<{ storage: Record<string, UserStorage>; measuring: boolean }>(
|
||||
`/users/storage${refresh ? "?refresh=1" : ""}`
|
||||
),
|
||||
// Account changes (admin only). Each carries the admin's OWN password
|
||||
// again (`currentPassword`): the server refuses without it (EREAUTH).
|
||||
/** POST /api/users — a new account. */
|
||||
@@ -885,6 +924,16 @@ export const api = {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ ...body, currentPassword }),
|
||||
}),
|
||||
/**
|
||||
* DELETE /api/users/:id — delete the user for good: logins, their
|
||||
* workspaces' records and (one Linux user per account) their Linux
|
||||
* account and whole home. Never yourself or the last admin.
|
||||
*/
|
||||
remove: (id: number, currentPassword: string) =>
|
||||
request<{ user: AuthUser }>(`/users/${id}`, {
|
||||
method: "DELETE",
|
||||
body: JSON.stringify({ currentPassword }),
|
||||
}),
|
||||
/** POST /api/users/:id/password — a new password; that user's logins end. */
|
||||
setPassword: (id: number, password: string, currentPassword: string) =>
|
||||
request<{ user: AuthUser }>(`/users/${id}/password`, {
|
||||
@@ -2545,8 +2594,7 @@ export const api = {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ paths }),
|
||||
}),
|
||||
trash: (t: FsPlace) =>
|
||||
request<{ items: FsTrashItem[]; keepDays?: number }>(fsUrl(t, "/trash")),
|
||||
trash: (t: FsPlace) => request<{ items: FsTrashItem[]; keepDays?: number }>(fsUrl(t, "/trash")),
|
||||
restore: (t: FsPlace, id: string) =>
|
||||
request<{ path: string; laneId: number | null }>(fsUrl(t, "/trash/restore"), {
|
||||
method: "POST",
|
||||
@@ -2613,11 +2661,14 @@ export const api = {
|
||||
/** The signed-in user's own git identity (`/api/me/git`, `server/routes/git-identity.js`). */
|
||||
gitIdentity: {
|
||||
get: () => request<GitIdentity>("/me/git"),
|
||||
/** Make the SSH key; `replace` swaps an existing one for a new pair. */
|
||||
generateKey: (replace = false) =>
|
||||
/**
|
||||
* Make the SSH key; `replace` swaps an existing one for a new pair.
|
||||
* `type`: ed25519 (default) or rsa (RSA 4096 — AWS CodeCommit takes only RSA).
|
||||
*/
|
||||
generateKey: (replace = false, type: "ed25519" | "rsa" = "ed25519") =>
|
||||
request<GitIdentity>("/me/git/ssh-key", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ replace }),
|
||||
body: JSON.stringify({ replace, type }),
|
||||
}),
|
||||
removeKey: () => request<GitIdentity>("/me/git/ssh-key", { method: "DELETE" }),
|
||||
saveHttps: (body: { host: string; username: string; password: string }) =>
|
||||
@@ -2646,6 +2697,115 @@ export const api = {
|
||||
),
|
||||
remove: (id: number) => request<{ ok: true }>(`/snapshots/${id}`, { method: "DELETE" }),
|
||||
},
|
||||
/** The Artifacts hub (`/api/artifacts`, `server/lib/artifacts.js`). */
|
||||
artifacts: {
|
||||
list: (params: { scope?: "mine" | "hub" | "all"; kind?: ArtifactKind; q?: string } = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.scope) qs.set("scope", params.scope);
|
||||
if (params.kind) qs.set("kind", params.kind);
|
||||
if (params.q) qs.set("q", params.q);
|
||||
const s = qs.toString();
|
||||
return request<{ items: Artifact[] }>(`/artifacts${s ? `?${s}` : ""}`);
|
||||
},
|
||||
settings: () => request<ArtifactSettings>("/artifacts/settings"),
|
||||
setInstallsEnabled: (installsEnabled: boolean) =>
|
||||
request<{ installsEnabled: boolean }>("/artifacts/settings", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ installsEnabled }),
|
||||
}),
|
||||
/** Documents a workspace's sessions wrote, to pin. */
|
||||
candidates: (laneId: number) =>
|
||||
request<{ items: ArtifactCandidate[] }>(`/artifacts/candidates?laneId=${laneId}`),
|
||||
/** Skill folders the caller may share (their own, and the workspace's). */
|
||||
skills: (laneId?: number) =>
|
||||
request<{ items: { name: string; from: "user" | "workspace" }[] }>(
|
||||
`/artifacts/skills${laneId ? `?laneId=${laneId}` : ""}`
|
||||
),
|
||||
addPage: (body: { url: string; title?: string; description?: string }) =>
|
||||
request<{ item: Artifact }>("/artifacts/page", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
pinFile: (body: { laneId: number; path: string; title?: string; sessionId?: string }) =>
|
||||
request<{ item: Artifact }>("/artifacts/file", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
addSkill: (body: { name: string; laneId?: number; title?: string; description?: string }) =>
|
||||
request<{ item: Artifact }>("/artifacts/skill", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
addPlugin: (body: { key: string; market: string; title?: string; description?: string }) =>
|
||||
request<{ item: Artifact }>("/artifacts/plugin", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
/** Read a marketplace (git link, owner/repo or marketplace.json link) and list its plugins. */
|
||||
inspectMarket: (market: string) =>
|
||||
request<MarketplaceInfo>("/artifacts/plugin/inspect", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ market }),
|
||||
}),
|
||||
/** A skill written in the dialog: SKILL.md gets `name`/`description` in its frontmatter. */
|
||||
writeSkill: (body: { name: string; description: string; content: string; title?: string }) =>
|
||||
request<{ item: Artifact; items: Artifact[] }>("/artifacts/skill/new", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
/** Skills from files: one Markdown file, a folder, several files, a .zip/.skill, or
|
||||
* several skills at once (one artifact each). `path` keeps a folder's layout. */
|
||||
uploadSkills: (
|
||||
files: { file: File; path: string }[],
|
||||
fields: { name?: string; title?: string; description?: string } = {}
|
||||
) => {
|
||||
const form = new FormData();
|
||||
for (const f of files) form.append("files", f.file, f.file.name);
|
||||
form.append("paths", JSON.stringify(files.map((f) => f.path)));
|
||||
for (const [k, v] of Object.entries(fields)) if (v) form.append(k, v);
|
||||
return request<{ items: Artifact[] }>("/artifacts/skill/upload", {
|
||||
method: "POST",
|
||||
body: form,
|
||||
});
|
||||
},
|
||||
/** One file from the user's computer, kept like a pinned one (≤ 25 MB). */
|
||||
uploadFile: (file: File, fields: { title?: string; description?: string } = {}) => {
|
||||
const form = new FormData();
|
||||
form.append("files", file, file.name);
|
||||
for (const [k, v] of Object.entries(fields)) if (v) form.append(k, v);
|
||||
return request<{ item: Artifact }>("/artifacts/file/upload", { method: "POST", body: form });
|
||||
},
|
||||
update: (
|
||||
id: number,
|
||||
body: {
|
||||
title?: string;
|
||||
description?: string;
|
||||
shared?: boolean;
|
||||
/** plugin only: `name@marketplace`. */
|
||||
source?: string;
|
||||
/** plugin only: the marketplace source. */
|
||||
market?: string;
|
||||
}
|
||||
) =>
|
||||
request<{ item: Artifact }>(`/artifacts/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
remove: (id: number) => request<{ ok: true }>(`/artifacts/${id}`, { method: "DELETE" }),
|
||||
install: (id: number, replace = false) =>
|
||||
request<{ installed: string; replaced?: boolean }>(`/artifacts/${id}/install`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ replace }),
|
||||
}),
|
||||
/** One of the snapshot's own files, served sandboxed. */
|
||||
rawUrl: (id: number, path?: string, download = false) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (path) qs.set("path", path);
|
||||
if (download) qs.set("download", "1");
|
||||
const s = qs.toString();
|
||||
return `${BASE}/artifacts/${id}/raw${s ? `?${s}` : ""}`;
|
||||
},
|
||||
},
|
||||
/** The mascot's custom pets (`/api/pets`, `server/lib/pets.js`). */
|
||||
pets: {
|
||||
list: () => request<PetList>("/pets"),
|
||||
@@ -3640,6 +3800,21 @@ export const api = {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ instructions }),
|
||||
}),
|
||||
/** POST /api/lanes/:id/sources/clone — clone a related repo BESIDE the
|
||||
* workspace folder and add it as an extra folder (409 ECREDENTIALS /
|
||||
* ESSHAUTH like {@link lanes.clone}). */
|
||||
cloneFolder: (
|
||||
id: number,
|
||||
body: {
|
||||
url: string;
|
||||
name?: string;
|
||||
credentials?: { username: string; password: string; remember?: boolean };
|
||||
}
|
||||
) =>
|
||||
request<LaneSourcesView & { path: string }>(`/lanes/${id}/sources/clone`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
/** POST /api/lanes/:id/sources/folder — an extra folder the agent may use. */
|
||||
addFolder: (id: number, path: string) =>
|
||||
request<LaneSourcesView>(`/lanes/${id}/sources/folder`, {
|
||||
@@ -3820,6 +3995,67 @@ function requestCodexBackupsHelper(params?: {
|
||||
export type CcArtifactType =
|
||||
"skills" | "agents" | "commands" | "output-styles" | "memory" | "auto-memory";
|
||||
|
||||
export type ArtifactKind = "page" | "file" | "skill" | "plugin";
|
||||
|
||||
/** One row of the Artifacts hub (`server/lib/artifacts.js` `view`). */
|
||||
export interface Artifact {
|
||||
id: number;
|
||||
kind: ArtifactKind;
|
||||
title: string;
|
||||
description: string;
|
||||
ownerId: number | null;
|
||||
owner: string | null;
|
||||
mine: boolean;
|
||||
canChange: boolean;
|
||||
laneId: number | null;
|
||||
sessionId: string | null;
|
||||
/** page: the file it was published from; file: its workspace path;
|
||||
* skill: its folder name; plugin: `name@marketplace`. */
|
||||
source: string | null;
|
||||
/** plugin: the marketplace source (owner/repo or a git URL). */
|
||||
market: string | null;
|
||||
/** page: the claude.ai link. */
|
||||
url: string | null;
|
||||
files: { path: string; size: number }[];
|
||||
size: number | null;
|
||||
shared: boolean;
|
||||
sharedAt: string | null;
|
||||
installs: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** POST /api/artifacts/plugin/inspect — a marketplace and the plugins it lists. */
|
||||
export interface MarketplaceInfo {
|
||||
/** The source as stored (owner/repo, a git URL or a marketplace.json link). */
|
||||
market: string;
|
||||
name: string;
|
||||
description: string;
|
||||
plugins: {
|
||||
name: string;
|
||||
/** `name@marketplace`, what `claude plugin install` takes. */
|
||||
key: string;
|
||||
description: string;
|
||||
version: string;
|
||||
category: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface ArtifactCandidate {
|
||||
path: string;
|
||||
sessionId: string;
|
||||
at: string;
|
||||
exists: boolean;
|
||||
pinned: boolean;
|
||||
}
|
||||
|
||||
export interface ArtifactSettings {
|
||||
serverMode: boolean;
|
||||
canShare: boolean;
|
||||
installsEnabled: boolean;
|
||||
canManage: boolean;
|
||||
}
|
||||
|
||||
/** Body for PUT /api/cc-config/file - create or overwrite one artifact. */
|
||||
export interface CcWriteArgs {
|
||||
// "auto-memory" targets a per-project memory file and requires `project`.
|
||||
@@ -3950,7 +4186,7 @@ export interface GitIdentity {
|
||||
account: "member" | "host";
|
||||
/** False for the host's identity seen by a non-admin. */
|
||||
writable: boolean;
|
||||
ssh: { publicKey: string; fingerprint: string } | null;
|
||||
ssh: { type?: "ed25519" | "rsa"; publicKey: string; fingerprint: string } | null;
|
||||
/** The account's commit author (`git config --global`); null fields = unset. */
|
||||
author: { name: string | null; email: string | null };
|
||||
https: {
|
||||
|
||||
@@ -64,6 +64,43 @@ export function droppedAttachments(dt: DataTransfer | null | undefined): Attachm
|
||||
}
|
||||
}
|
||||
|
||||
/** A drop that carries no file and none of ours, only text — a file manager
|
||||
* or an editor (VS Code) that hands over `file://` URIs, a selection, a
|
||||
* link: the local `file://` URIs as `@path` attachments, else the text to
|
||||
* insert, as a terminal pastes it. */
|
||||
export function droppedText(
|
||||
dt: DataTransfer | null | undefined
|
||||
): { attachments: Attachment[] } | { text: string } | null {
|
||||
try {
|
||||
const paths = (dt?.getData("text/uri-list") ?? "")
|
||||
.split(/\r?\n/)
|
||||
.filter((l) => l && !l.startsWith("#"))
|
||||
.map((l) => {
|
||||
try {
|
||||
const u = new URL(l.trim());
|
||||
return u.protocol === "file:" && (!u.host || u.host === "localhost")
|
||||
? decodeURIComponent(u.pathname)
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
if (paths.length && paths.every(Boolean)) {
|
||||
return {
|
||||
attachments: (paths as string[]).map((p) => ({
|
||||
// A space would end the mention: Claude Code reads `@"…"` whole.
|
||||
path: /\s/.test(p) ? `@"${p}"` : `@${p}`,
|
||||
name: p.replace(/\/$/, "").split("/").pop() || p,
|
||||
})),
|
||||
};
|
||||
}
|
||||
const text = dt?.getData("text/plain") ?? "";
|
||||
return text.trim() ? { text } : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const SKILL_MIME = "application/x-agenthub-skill";
|
||||
// A skill's name as Claude Code types it: `name` or `plugin:name`.
|
||||
const SKILL_RE = /^[\w.-]+(?::[\w.-]+)?$/;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* @file resolvePath.ts — resolves a path a chat reply names against the pane's
|
||||
* folder: an absolute one (POSIX, `~`-less, or `C:\…`) is kept, a relative one
|
||||
* (`server/lib/x.js`, `./a`, `../b`) is joined to `cwd` with `.`/`..` folded,
|
||||
* so the preview and the Changes panel see the same absolute path the agent meant.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
/** `path` as an absolute path; relative ones resolve against `cwd`. */
|
||||
export function resolveIn(cwd: string, path: string): string {
|
||||
if (/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(path) || !cwd) return path;
|
||||
const parts = cwd.replace(/[\\/]+$/, "").split(/[\\/]/);
|
||||
for (const seg of path.split(/[\\/]/)) {
|
||||
if (seg === "" || seg === ".") continue;
|
||||
if (seg === "..") {
|
||||
if (parts.length > 1) parts.pop();
|
||||
} else parts.push(seg);
|
||||
}
|
||||
return parts.join("/") || "/";
|
||||
}
|
||||
@@ -34,6 +34,8 @@ export const SETTINGS_INDEX: {
|
||||
to?: string;
|
||||
/** Server mode: a control only an admin sees, kept out of anyone else's search. */
|
||||
adminOnly?: boolean;
|
||||
/** Hidden in local mode (AgentHub's own git logins), so kept out of its search. */
|
||||
serverOnly?: boolean;
|
||||
}[] = [
|
||||
{
|
||||
section: "account",
|
||||
@@ -249,6 +251,15 @@ export const SETTINGS_INDEX: {
|
||||
descKey: "aiTools.description",
|
||||
keywords: ["install", "update", "default"],
|
||||
},
|
||||
{
|
||||
section: "agents",
|
||||
titleKey: "artifacts:installsSwitch",
|
||||
descKey: "artifacts:installsSwitchHint",
|
||||
keywords: ["artifacts", "hub", "skill", "plugin", "cài đặt"],
|
||||
to: "#artifacts-hub",
|
||||
adminOnly: true,
|
||||
serverOnly: true,
|
||||
},
|
||||
{ section: "agents/claude-code", titleKey: "hooks.title" },
|
||||
{ section: "agents/claude-code", titleKey: "claudeHome.title" },
|
||||
{ section: "agents/claude-code", titleKey: "ccConfig:tabs.skills", to: "?tab=skills" },
|
||||
@@ -330,10 +341,17 @@ export const SETTINGS_INDEX: {
|
||||
{ section: "agents/*", titleKey: "toolTab.defaultModel", keywords: ["model", "config"] },
|
||||
{ section: "ai-proxy", titleKey: "aiProxy.title", keywords: ["router", "endpoint", "key"] },
|
||||
{ section: "pricing", titleKey: "pricing.title", keywords: ["cost", "price", "tokens"] },
|
||||
{ section: "git", titleKey: "gitCreds.title", adminOnly: true, keywords: ["login", "token"] },
|
||||
{
|
||||
section: "git",
|
||||
titleKey: "gitCreds.title",
|
||||
adminOnly: true,
|
||||
serverOnly: true,
|
||||
keywords: ["login", "token"],
|
||||
},
|
||||
{
|
||||
section: "git",
|
||||
titleKey: "gitIdentity.title",
|
||||
serverOnly: true,
|
||||
keywords: ["ssh", "key", "clone", "https"],
|
||||
to: "#git-identity",
|
||||
},
|
||||
|
||||
@@ -1925,7 +1925,9 @@ export interface WSMessage {
|
||||
/** A lane's profile hook exited, with its status code. */
|
||||
| "lane_hook_result"
|
||||
/** A pane ended; refetch GET /api/run/interrupted (no payload). */
|
||||
| "runs_interrupted";
|
||||
| "runs_interrupted"
|
||||
/** An artifact was added, changed, shared or deleted; refetch the list. */
|
||||
| "artifact_changed";
|
||||
/** The message body, whose concrete shape is selected by `type` above. */
|
||||
data:
|
||||
| Session
|
||||
@@ -2671,6 +2673,8 @@ export interface Lane {
|
||||
owner_name?: string | null;
|
||||
/** The owner's display name (`users.display_name`); null when none is set. */
|
||||
owner_display_name?: string | null;
|
||||
/** When the owner's avatar was last set (`users.avatar_at`); null = none. */
|
||||
owner_avatar_at?: string | null;
|
||||
branch: string | null;
|
||||
kind: "managed" | "adopted";
|
||||
/** The CLI this lane's runs spawn. Immutable once the lane exists. */
|
||||
|
||||
@@ -0,0 +1,779 @@
|
||||
/**
|
||||
* @file Artifacts.tsx
|
||||
* @description `/artifacts` — the Artifacts hub (`/api/artifacts`,
|
||||
* server/lib/artifacts.js): claude.ai pages sessions published, pinned
|
||||
* workspace files (or one uploaded from the computer), skills (picked,
|
||||
* uploaded as a file/folder/zip, or written — `ArtifactAddPanels.tsx`) and
|
||||
* plugins (read from a marketplace link, or typed). **My library** lists the caller's
|
||||
* own; in server mode the **Hub** tab lists what every user shared, and a
|
||||
* shared skill or plugin is installed into the viewer's own account from
|
||||
* there (after a confirmation that lists what will be written or run). An
|
||||
* admin's switch in Settings → AI tools (`ArtifactsHubSettings`) turns Hub
|
||||
* installs off for everyone. Previews of a file are
|
||||
* the server's sandboxed `raw` route in a sandboxed iframe, so nothing a
|
||||
* shared HTML file carries runs on the dashboard's origin.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Download,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
FileText,
|
||||
Globe,
|
||||
Package,
|
||||
Pencil,
|
||||
Plus,
|
||||
Share2,
|
||||
Sparkles,
|
||||
Trash2,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
api,
|
||||
type Artifact,
|
||||
type ArtifactCandidate,
|
||||
type ArtifactKind,
|
||||
type ArtifactSettings,
|
||||
} from "../lib/api";
|
||||
import type { Lane } from "../lib/types";
|
||||
import { eventBus } from "../lib/eventBus";
|
||||
import { toast } from "../lib/toast";
|
||||
import { confirmDialog } from "../lib/confirm";
|
||||
import { useDialog } from "../hooks/useDialog";
|
||||
import {
|
||||
FileUploadPanel,
|
||||
PluginAddPanel,
|
||||
SkillAddPanel,
|
||||
} from "../components/artifacts/ArtifactAddPanels";
|
||||
|
||||
const KIND_ICON = { page: Globe, file: FileText, skill: Sparkles, plugin: Package } as const;
|
||||
const KINDS: ArtifactKind[] = ["page", "file", "skill", "plugin"];
|
||||
|
||||
function fmtBytes(n: number | null): string {
|
||||
if (!n) return "";
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
|
||||
return `${(n / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
const IMAGE = /\.(png|jpe?g|gif|webp|svg)$/i;
|
||||
|
||||
export function Artifacts() {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [settings, setSettings] = useState<ArtifactSettings | null>(null);
|
||||
const [tab, setTab] = useState<"mine" | "hub">("mine");
|
||||
const [kind, setKind] = useState<ArtifactKind | "">("");
|
||||
const [q, setQ] = useState("");
|
||||
const [items, setItems] = useState<Artifact[] | null>(null);
|
||||
const [adding, setAdding] = useState<ArtifactKind | null>(null);
|
||||
const [addMenu, setAddMenu] = useState(false);
|
||||
const [preview, setPreview] = useState<{ item: Artifact; path: string } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.artifacts
|
||||
.settings()
|
||||
.then(setSettings)
|
||||
.catch(() => setSettings(null));
|
||||
}, []);
|
||||
|
||||
const load = useCallback(() => {
|
||||
api.artifacts
|
||||
.list({ scope: tab, kind: kind || undefined, q: q.trim() || undefined })
|
||||
.then((r) => setItems(r.items))
|
||||
.catch((err) => {
|
||||
setItems([]);
|
||||
toast.error(err);
|
||||
});
|
||||
}, [tab, kind, q]);
|
||||
|
||||
useEffect(() => {
|
||||
const id = window.setTimeout(load, q ? 250 : 0);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [load, q]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
eventBus.subscribe((msg) => {
|
||||
if (msg.type === "artifact_changed") load();
|
||||
}),
|
||||
[load]
|
||||
);
|
||||
|
||||
const server = !!settings?.serverMode;
|
||||
|
||||
const share = async (a: Artifact) => {
|
||||
try {
|
||||
await api.artifacts.update(a.id, { shared: !a.shared });
|
||||
toast.success(t(a.shared ? "unshareDone" : "shareDone"));
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
const [renaming, setRenaming] = useState<Artifact | null>(null);
|
||||
|
||||
const remove = async (a: Artifact) => {
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t("deleteTitle", { title: a.title }),
|
||||
message: t("deleteBody"),
|
||||
confirmLabel: t("deleteConfirm"),
|
||||
}))
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await api.artifacts.remove(a.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
const install = async (a: Artifact) => {
|
||||
const message =
|
||||
a.kind === "skill"
|
||||
? `${t("installSkillBody", { name: a.source })} ${a.files.map((f) => f.path).join(", ")}`
|
||||
: t("installPluginBody", { market: a.market, name: a.source });
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t("installTitle", { title: a.title }),
|
||||
message,
|
||||
confirmLabel: t("installConfirm"),
|
||||
destructive: false,
|
||||
}))
|
||||
)
|
||||
return;
|
||||
const done = (r: { installed: string }) =>
|
||||
toast.success(
|
||||
a.kind === "skill"
|
||||
? t("installed", { path: r.installed })
|
||||
: t("installedPlugin", { name: r.installed })
|
||||
);
|
||||
try {
|
||||
done(await api.artifacts.install(a.id));
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string }).code;
|
||||
if (code !== "EEXISTS") return toast.error(err);
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t("replaceTitle", { name: a.source }),
|
||||
message: t("replaceBody"),
|
||||
confirmLabel: t("replaceConfirm"),
|
||||
}))
|
||||
)
|
||||
return;
|
||||
try {
|
||||
done(await api.artifacts.install(a.id, true));
|
||||
} catch (e) {
|
||||
toast.error(e);
|
||||
}
|
||||
}
|
||||
load();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-testid="artifacts-page">
|
||||
<header className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold text-fg-primary">{t("title")}</h1>
|
||||
<p className="text-sm text-fg-muted">{t(server ? "subtitleServer" : "subtitle")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
className="btn-primary flex items-center gap-1.5 text-sm"
|
||||
data-testid="artifacts-add"
|
||||
onClick={() => setAddMenu((v) => !v)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
{t("add")}
|
||||
</button>
|
||||
{addMenu && (
|
||||
<div className="absolute right-0 z-20 mt-1 w-56 rounded-lg border border-border bg-surface-1 p-1 shadow-xl">
|
||||
{KINDS.map((k) => {
|
||||
const Icon = KIND_ICON[k];
|
||||
return (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setAdding(k);
|
||||
setAddMenu(false);
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm text-fg-secondary hover:bg-surface-3 hover:text-fg-primary"
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
{t(`add.${k}`)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{server && (
|
||||
<div className="flex items-center rounded border border-border bg-surface-2 p-0.5">
|
||||
{(["mine", "hub"] as const).map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
aria-pressed={tab === v}
|
||||
onClick={() => setTab(v)}
|
||||
className={`rounded px-3 py-1 text-xs font-medium ${
|
||||
tab === v
|
||||
? "bg-accent-solid text-white"
|
||||
: "text-fg-secondary hover:bg-surface-3 hover:text-fg-primary"
|
||||
}`}
|
||||
>
|
||||
{t(`tab.${v}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center rounded border border-border bg-surface-2 p-0.5">
|
||||
{(["", ...KINDS] as const).map((k) => (
|
||||
<button
|
||||
key={k || "all"}
|
||||
type="button"
|
||||
aria-pressed={kind === k}
|
||||
onClick={() => setKind(k)}
|
||||
className={`rounded px-2.5 py-1 text-xs ${
|
||||
kind === k
|
||||
? "bg-surface-4 text-fg-primary"
|
||||
: "text-fg-secondary hover:bg-surface-3 hover:text-fg-primary"
|
||||
}`}
|
||||
>
|
||||
{t(k ? `kind.${k}` : "kind.all")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<input
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder={t("search")}
|
||||
aria-label={t("search")}
|
||||
className="ml-auto w-56 rounded border border-border bg-surface-1 px-2 py-1 text-sm text-fg-primary"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{items === null ? (
|
||||
<p className="text-sm text-fg-muted">{t("loading")}</p>
|
||||
) : items.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed border-border px-4 py-10 text-center text-sm text-fg-muted">
|
||||
{t(tab === "hub" ? "empty.hub" : "empty.mine")}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3" data-testid="artifacts-list">
|
||||
{items.map((a) => (
|
||||
<ArtifactCard
|
||||
key={a.id}
|
||||
item={a}
|
||||
server={server}
|
||||
canInstall={!!settings?.installsEnabled}
|
||||
onShare={() => void share(a)}
|
||||
onRename={() => setRenaming(a)}
|
||||
onDelete={() => void remove(a)}
|
||||
onInstall={() => void install(a)}
|
||||
onPreview={(path) => setPreview({ item: a, path })}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{adding && <AddDialog kind={adding} onClose={() => setAdding(null)} onAdded={load} />}
|
||||
{preview && <PreviewDialog {...preview} onClose={() => setPreview(null)} />}
|
||||
{renaming && (
|
||||
<RenameDialog
|
||||
item={renaming}
|
||||
onClose={() => setRenaming(null)}
|
||||
onSaved={() => {
|
||||
setRenaming(null);
|
||||
load();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ArtifactCard({
|
||||
item: a,
|
||||
server,
|
||||
canInstall,
|
||||
onShare,
|
||||
onRename,
|
||||
onDelete,
|
||||
onInstall,
|
||||
onPreview,
|
||||
}: {
|
||||
item: Artifact;
|
||||
server: boolean;
|
||||
canInstall: boolean;
|
||||
onShare: () => void;
|
||||
onRename: () => void;
|
||||
onDelete: () => void;
|
||||
onInstall: () => void;
|
||||
onPreview: (path: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const Icon = KIND_ICON[a.kind];
|
||||
const btn =
|
||||
"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-fg-secondary hover:bg-surface-3 hover:text-fg-primary";
|
||||
return (
|
||||
<li
|
||||
className="flex flex-col gap-2 rounded-lg border border-border bg-surface-1 p-3"
|
||||
data-testid={`artifact-${a.id}`}
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<Icon className="mt-0.5 h-4 w-4 shrink-0 text-fg-muted" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium text-fg-primary" title={a.title}>
|
||||
{a.title}
|
||||
</p>
|
||||
<p className="truncate text-[11px] text-fg-muted" title={a.source || a.url || ""}>
|
||||
{t(`kindOne.${a.kind}`)}
|
||||
{a.source ? ` · ${a.source}` : ""}
|
||||
{a.size ? ` · ${fmtBytes(a.size)}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
{a.shared && (
|
||||
<span className="shrink-0 rounded bg-surface-3 px-1.5 py-0.5 text-[10px] text-fg-secondary">
|
||||
{t("shared")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{a.description && <p className="line-clamp-2 text-xs text-fg-secondary">{a.description}</p>}
|
||||
<p className="text-[11px] text-fg-muted">
|
||||
{server && a.owner && !a.mine ? `${t("by", { name: a.owner })} · ` : ""}
|
||||
{new Date(a.createdAt).toLocaleString()}
|
||||
{a.installs > 0 ? ` · ${t("installs", { count: a.installs })}` : ""}
|
||||
</p>
|
||||
<div className="mt-auto flex flex-wrap items-center gap-1 border-t border-border-light pt-2">
|
||||
{a.kind === "page" && a.url && (
|
||||
<a href={a.url} target="_blank" rel="noopener noreferrer" className={btn}>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
{t("open")}
|
||||
</a>
|
||||
)}
|
||||
{(a.kind === "file" || a.kind === "skill") && a.files.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
className={btn}
|
||||
onClick={() => onPreview(a.kind === "skill" ? "SKILL.md" : (a.files[0]?.path ?? ""))}
|
||||
>
|
||||
<Eye className="h-3 w-3" />
|
||||
{t("preview")}
|
||||
</button>
|
||||
)}
|
||||
{a.kind === "file" && a.files.length > 0 && (
|
||||
<a href={api.artifacts.rawUrl(a.id, a.files[0]?.path, true)} className={btn}>
|
||||
<Download className="h-3 w-3" />
|
||||
{t("download")}
|
||||
</a>
|
||||
)}
|
||||
{(a.kind === "skill" || a.kind === "plugin") && (
|
||||
<button
|
||||
type="button"
|
||||
className={btn}
|
||||
disabled={!canInstall}
|
||||
title={canInstall ? undefined : t("installsOff")}
|
||||
onClick={onInstall}
|
||||
>
|
||||
<Download className="h-3 w-3" />
|
||||
{t("install")}
|
||||
</button>
|
||||
)}
|
||||
<span className="ml-auto flex items-center gap-1">
|
||||
{server && a.canChange && (
|
||||
<button type="button" className={btn} onClick={onShare}>
|
||||
<Share2 className="h-3 w-3" />
|
||||
{t(a.shared ? "unshare" : "share")}
|
||||
</button>
|
||||
)}
|
||||
{a.canChange && (
|
||||
<>
|
||||
<button type="button" className={btn} aria-label={t("rename")} onClick={onRename}>
|
||||
<Pencil className="h-3 w-3" />
|
||||
</button>
|
||||
<button type="button" className={btn} aria-label={t("delete")} onClick={onDelete}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function Modal({
|
||||
title,
|
||||
onClose,
|
||||
children,
|
||||
wide = false,
|
||||
}: {
|
||||
title: string;
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
wide?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const panel = useRef<HTMLDivElement>(null);
|
||||
useDialog(true, panel, onClose);
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-4"
|
||||
role="presentation"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
ref={panel}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={`flex max-h-[85vh] w-full ${wide ? "max-w-5xl" : "max-w-lg"} flex-col rounded-xl border border-border bg-surface-1 p-5 shadow-xl`}
|
||||
>
|
||||
<div className="mb-3 flex shrink-0 items-center justify-between gap-2">
|
||||
<h2 className="truncate text-sm font-semibold text-fg-primary">{title}</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("close")}
|
||||
onClick={onClose}
|
||||
className="text-fg-muted hover:text-fg-primary"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-auto">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RenameDialog({
|
||||
item,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
item: Artifact;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [title, setTitle] = useState(item.title);
|
||||
const [description, setDescription] = useState(item.description);
|
||||
const [source, setSource] = useState(item.source ?? "");
|
||||
const [market, setMarket] = useState(item.market ?? "");
|
||||
const plugin = item.kind === "plugin";
|
||||
const field =
|
||||
"w-full rounded border border-border bg-surface-1 px-2 py-1 text-sm text-fg-primary";
|
||||
return (
|
||||
<Modal title={t("rename")} onClose={onClose}>
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await api.artifacts.update(item.id, {
|
||||
title,
|
||||
description,
|
||||
...(plugin && source.trim() !== item.source ? { source: source.trim() } : {}),
|
||||
...(plugin && market.trim() !== item.market ? { market: market.trim() } : {}),
|
||||
});
|
||||
onSaved();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className={field}
|
||||
aria-label={t("form.title")}
|
||||
value={title}
|
||||
autoFocus
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
className={field}
|
||||
rows={3}
|
||||
aria-label={t("form.description")}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
{plugin && (
|
||||
<>
|
||||
<input
|
||||
className={field}
|
||||
aria-label={t("form.pluginKey")}
|
||||
placeholder="my-plugin@my-marketplace"
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
className={field}
|
||||
aria-label={t("form.market")}
|
||||
placeholder="owner/repo · https://…"
|
||||
value={market}
|
||||
onChange={(e) => setMarket(e.target.value)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-primary text-sm"
|
||||
disabled={!title.trim() || (plugin && (!source.trim() || !market.trim()))}
|
||||
>
|
||||
{t("form.saveEdit")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function PreviewDialog({
|
||||
item,
|
||||
path,
|
||||
onClose,
|
||||
}: {
|
||||
item: Artifact;
|
||||
path: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [current, setCurrent] = useState(path);
|
||||
const url = api.artifacts.rawUrl(item.id, current);
|
||||
return (
|
||||
<Modal title={item.title} onClose={onClose} wide>
|
||||
<div className="flex h-[70vh] gap-3">
|
||||
{item.files.length > 1 && (
|
||||
<ul className="w-56 shrink-0 space-y-0.5 overflow-auto">
|
||||
{item.files.map((f) => (
|
||||
<li key={f.path}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCurrent(f.path)}
|
||||
className={`w-full truncate rounded px-1.5 py-0.5 text-left font-mono text-[11px] ${
|
||||
f.path === current
|
||||
? "bg-surface-3 text-fg-primary"
|
||||
: "text-fg-secondary hover:bg-surface-2"
|
||||
}`}
|
||||
title={f.path}
|
||||
>
|
||||
{f.path}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="min-w-0 flex-1 rounded border border-border bg-white">
|
||||
{IMAGE.test(current) && !/\.svg$/i.test(current) ? (
|
||||
<img src={url} alt={current} className="h-full w-full object-contain" />
|
||||
) : (
|
||||
// No allow-* tokens: a shared page renders, nothing in it runs.
|
||||
<iframe
|
||||
title={current}
|
||||
src={url}
|
||||
sandbox=""
|
||||
className="h-full w-full"
|
||||
data-testid="artifact-preview"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function AddDialog({
|
||||
kind,
|
||||
onClose,
|
||||
onAdded,
|
||||
}: {
|
||||
kind: ArtifactKind;
|
||||
onClose: () => void;
|
||||
onAdded: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [url, setUrl] = useState("");
|
||||
const [lanes, setLanes] = useState<Lane[]>([]);
|
||||
const [laneId, setLaneId] = useState<number | null>(null);
|
||||
const [candidates, setCandidates] = useState<ArtifactCandidate[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (kind !== "file" && kind !== "skill") return;
|
||||
api.lanes
|
||||
.list()
|
||||
.then((r) => setLanes(r.lanes))
|
||||
.catch(() => setLanes([]));
|
||||
}, [kind]);
|
||||
|
||||
useEffect(() => {
|
||||
if (kind === "file") {
|
||||
setCandidates(null);
|
||||
if (laneId)
|
||||
api.artifacts
|
||||
.candidates(laneId)
|
||||
.then((r) => setCandidates(r.items))
|
||||
.catch((err) => {
|
||||
setCandidates([]);
|
||||
toast.error(err);
|
||||
});
|
||||
}
|
||||
}, [kind, laneId]);
|
||||
|
||||
const run = async (fn: () => Promise<unknown>, close = true) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
toast.success(t("added"));
|
||||
onAdded();
|
||||
if (close) onClose();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const field =
|
||||
"w-full rounded border border-border bg-surface-1 px-2 py-1 text-sm text-fg-primary";
|
||||
const meta = (
|
||||
<>
|
||||
<input
|
||||
className={field}
|
||||
placeholder={t("form.title")}
|
||||
aria-label={t("form.title")}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
className={field}
|
||||
rows={2}
|
||||
placeholder={t("form.description")}
|
||||
aria-label={t("form.description")}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
const workspacePicker = (
|
||||
<select
|
||||
className={field}
|
||||
aria-label={t("form.workspace")}
|
||||
value={laneId ?? ""}
|
||||
onChange={(e) => setLaneId(e.target.value ? Number(e.target.value) : null)}
|
||||
>
|
||||
<option value="">{t("form.pickWorkspace")}</option>
|
||||
{lanes.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.title || l.cwd}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
|
||||
return (
|
||||
<Modal title={t(`add.${kind}`)} onClose={onClose}>
|
||||
<div className="space-y-2" data-testid={`artifacts-add-${kind}`}>
|
||||
{kind === "page" && (
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run(() => api.artifacts.addPage({ url, title, description }));
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className={field}
|
||||
placeholder="https://claude.ai/…"
|
||||
aria-label={t("form.url")}
|
||||
value={url}
|
||||
autoFocus
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
/>
|
||||
{meta}
|
||||
<div className="flex justify-end">
|
||||
<button type="submit" className="btn-primary text-sm" disabled={busy || !url.trim()}>
|
||||
{t("form.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{kind === "file" && (
|
||||
<>
|
||||
<FileUploadPanel onAdded={onAdded} />
|
||||
<p className="border-t border-border-light pt-2 text-[11px] font-medium text-fg-secondary">
|
||||
{t("file.fromWorkspace")}
|
||||
</p>
|
||||
{workspacePicker}
|
||||
{laneId && candidates === null && (
|
||||
<p className="text-xs text-fg-muted">{t("loading")}</p>
|
||||
)}
|
||||
{candidates && candidates.length === 0 && (
|
||||
<p className="text-xs text-fg-muted">{t("form.noCandidates")}</p>
|
||||
)}
|
||||
{candidates && candidates.length > 0 && (
|
||||
<ul className="max-h-80 space-y-0.5 overflow-auto">
|
||||
{candidates.map((c) => (
|
||||
<li key={c.path} className="flex items-center gap-2 text-xs">
|
||||
<span
|
||||
className="min-w-0 flex-1 truncate font-mono text-fg-secondary"
|
||||
title={c.path}
|
||||
>
|
||||
{c.path}
|
||||
</span>
|
||||
{!c.exists ? (
|
||||
<span className="text-fg-muted">{t("form.missing")}</span>
|
||||
) : c.pinned ? (
|
||||
<span className="text-fg-muted">{t("form.pinned")}</span>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="btn-ghost text-xs"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
await api.artifacts.pinFile({
|
||||
laneId: laneId!,
|
||||
path: c.path,
|
||||
sessionId: c.sessionId,
|
||||
});
|
||||
setCandidates((list) =>
|
||||
(list ?? []).map((x) =>
|
||||
x.path === c.path ? { ...x, pinned: true } : x
|
||||
)
|
||||
);
|
||||
}, false)
|
||||
}
|
||||
>
|
||||
{t("form.pin")}
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{kind === "skill" && <SkillAddPanel lanes={lanes} onAdded={onAdded} onClose={onClose} />}
|
||||
|
||||
{kind === "plugin" && <PluginAddPanel onAdded={onAdded} onClose={onClose} />}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
* @description `/files` — the file manager (`FileBrowser`) as a page of its
|
||||
* own, reached from the sidebar's **Files** entry. The location is kept in the
|
||||
* URL (`?home=<me|user>&path=` or `?lane=<id>&path=`), so Back and a shared
|
||||
* link land in the same folder. With neither it opens the user's own HOME
|
||||
* (their Linux home under S3), or — where they have none — the last
|
||||
* workspace shown (`agenthub.workspace.selected`), else the first.
|
||||
* link land in the same folder. With neither it opens the workspace last
|
||||
* shown (`agenthub.workspace.selected`) — reached from a workspace, Files is
|
||||
* about THAT workspace — else the user's own HOME (their Linux home under S3),
|
||||
* else the first workspace.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -31,24 +32,31 @@ export function FilesPage() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const askedLane = Number(params.get("lane"));
|
||||
const askedHome = params.get("home");
|
||||
const [start, setStart] = useState<Start | null>(
|
||||
askedHome
|
||||
? { home: askedHome }
|
||||
: Number.isInteger(askedLane) && askedLane > 0
|
||||
? { lane: askedLane }
|
||||
: null
|
||||
);
|
||||
// The URL wins on every render: a place picked in the browser (another
|
||||
// user's home) lands in the URL, and a frozen start would send the next
|
||||
// folder opened there back to the first place.
|
||||
const asked: Start | null = askedHome
|
||||
? { home: askedHome }
|
||||
: Number.isInteger(askedLane) && askedLane > 0
|
||||
? { lane: askedLane }
|
||||
: null;
|
||||
const [fallback, setStart] = useState<Start | null>(null);
|
||||
const start = asked ?? fallback;
|
||||
const [none, setNone] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (start) return;
|
||||
void (async () => {
|
||||
const homes = await api.files.homes().catch(() => ({ homes: [] }));
|
||||
if (homes.homes.some((h) => h.id === "me")) return setStart({ home: "me" });
|
||||
// The workspace last shown first: Files reached from a workspace opens
|
||||
// THAT workspace (from PhuNT → AC_SHOP it opened your own home, empty
|
||||
// but for hidden files); the home is the fallback.
|
||||
const { lanes } = await api.lanes.list().catch(() => ({ lanes: [] }));
|
||||
const last = lastWorkspace();
|
||||
const pick = lanes.find((l) => l.id === last) ?? lanes[0];
|
||||
if (pick) setStart({ lane: pick.id });
|
||||
const shown = lanes.find((l) => l.id === last);
|
||||
if (shown) return setStart({ lane: shown.id });
|
||||
const homes = await api.files.homes().catch(() => ({ homes: [] }));
|
||||
if (homes.homes.some((h) => h.id === "me")) return setStart({ home: "me" });
|
||||
if (lanes[0]) setStart({ lane: lanes[0].id });
|
||||
else setNone(true);
|
||||
})();
|
||||
}, [start]);
|
||||
|
||||
@@ -67,6 +67,7 @@ import { SnapshotSettings } from "../components/settings/SnapshotSettings";
|
||||
import { ReportSettings } from "../components/settings/ReportSettings";
|
||||
import { AiToolsSettings } from "../components/settings/AiToolsSettings";
|
||||
import { AgentInstructionsSettings } from "../components/settings/AgentInstructionsSettings";
|
||||
import { ArtifactsHubSettings } from "../components/settings/ArtifactsHubSettings";
|
||||
import { PricingSettings } from "../components/settings/PricingSettings";
|
||||
import { WorktreeVisibilitySettings } from "../components/settings/WorktreeVisibilitySettings";
|
||||
import { useAiTools } from "../hooks/useAiTools";
|
||||
@@ -242,7 +243,7 @@ export function SettingsHub({ section }: { section?: string } = {}) {
|
||||
};
|
||||
}, [location.key, location.hash]);
|
||||
|
||||
const { isAdmin } = usePermissions();
|
||||
const { isAdmin, local } = usePermissions();
|
||||
const authState = useAuth().state;
|
||||
const signedIn = authState.mode === "server" && !!authState.user;
|
||||
const enabled = (id: string) => aiTools.byId(id)?.enabled !== false;
|
||||
@@ -292,6 +293,8 @@ export function SettingsHub({ section }: { section?: string } = {}) {
|
||||
<div className="space-y-6">
|
||||
<AgentInstructionsSettings />
|
||||
<AiToolsSettings settingsHref={toolHref} />
|
||||
{/* The Hub's install switch: server mode, an admin's (it hides itself). */}
|
||||
<ArtifactsHubSettings />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -394,15 +397,17 @@ export function SettingsHub({ section }: { section?: string } = {}) {
|
||||
...s("git"),
|
||||
render: () => (
|
||||
<div className="space-y-6">
|
||||
{/* Git logins are the host's own: an admin's. */}
|
||||
{isAdmin && (
|
||||
{/* Git logins are the host's own: an admin's. Not in local mode,
|
||||
nor the identity below: git uses this machine's own config,
|
||||
SSH keys and credential helper there. */}
|
||||
{isAdmin && !local && (
|
||||
<section id="git-credentials" className="scroll-mt-24">
|
||||
<h2 className="mb-2 text-sm font-semibold text-fg-primary">{t("gitCreds.title")}</h2>
|
||||
<GitCredentialsConfig />
|
||||
</section>
|
||||
)}
|
||||
{/* The user's own SSH key / HTTPS logins (S3: their own home). */}
|
||||
{(isAdmin || signedIn) && (
|
||||
{!local && (isAdmin || signedIn) && (
|
||||
<section id="git-identity" className="scroll-mt-24">
|
||||
<h2 className="mb-2 text-sm font-semibold text-fg-primary">
|
||||
{t("gitIdentity.title")}
|
||||
@@ -434,6 +439,7 @@ export function SettingsHub({ section }: { section?: string } = {}) {
|
||||
...SETTINGS_INDEX.filter(
|
||||
(e) =>
|
||||
(isAdmin || !e.adminOnly) &&
|
||||
(!local || !e.serverOnly) &&
|
||||
(e.section === sec.id ||
|
||||
(e.section === "agents/*" &&
|
||||
sec.id.startsWith("agents/") &&
|
||||
|
||||
+81
-10
@@ -2,8 +2,10 @@
|
||||
* @file Users.tsx
|
||||
* @description The Users page (`/users`, a sidebar item), server mode only and
|
||||
* only for an admin or analyst (docs/SERVER-MODE.md): every account with its
|
||||
* role, state, workspaces, sessions and the tokens/$ it used in the last 7 and
|
||||
* 30 days (`GET /api/users`), the audit log (`GET /api/users/audit`), and — for
|
||||
* role, state, workspaces, sessions, the tokens/$ it used in the last 7 and
|
||||
* 30 days (`GET /api/users`) and how much disk its home folder takes
|
||||
* (`GET /api/users/storage`, measured in the background — polled while the
|
||||
* server says `measuring`; Refresh re-measures), the audit log (`GET /api/users/audit`), and — for
|
||||
* 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
|
||||
@@ -30,8 +32,14 @@ import {
|
||||
UserPlus,
|
||||
Users as UsersIcon,
|
||||
} from "lucide-react";
|
||||
import { api, type AuditEntry, type AuthUser, type ServerUserUsage } from "../lib/api";
|
||||
import { fmt, fmtCost, formatDateTime } from "../lib/format";
|
||||
import {
|
||||
api,
|
||||
type AuditEntry,
|
||||
type AuthUser,
|
||||
type ServerUserUsage,
|
||||
type UserStorage,
|
||||
} from "../lib/api";
|
||||
import { fmt, fmtCost, formatBytes, formatDateTime } from "../lib/format";
|
||||
import { toast } from "../lib/toast";
|
||||
import { isSubmitEnter } from "../lib/keys";
|
||||
import { useSpin } from "../hooks/useSpin";
|
||||
@@ -56,10 +64,25 @@ export function Users() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [editing, setEditing] = useState<ServerUserUsage | null>(null);
|
||||
const [storage, setStorage] = useState<Record<string, UserStorage> | null>(null);
|
||||
const [measuring, setMeasuring] = useState(false);
|
||||
|
||||
const loadStorage = useCallback(
|
||||
(remeasure = false) =>
|
||||
api.users
|
||||
.storage(remeasure)
|
||||
.then((r) => {
|
||||
setStorage(r.storage);
|
||||
setMeasuring(r.measuring);
|
||||
})
|
||||
.catch(() => setMeasuring(false)),
|
||||
[]
|
||||
);
|
||||
|
||||
const load = useCallback(
|
||||
() =>
|
||||
(remeasure = false) =>
|
||||
Promise.all([
|
||||
loadStorage(remeasure),
|
||||
api.users
|
||||
.list()
|
||||
.then((r) => {
|
||||
@@ -72,14 +95,23 @@ export function Users() {
|
||||
.then((r) => setAudit(r.entries))
|
||||
.catch(() => setAudit([])),
|
||||
]),
|
||||
[]
|
||||
[loadStorage]
|
||||
);
|
||||
const [spinning, refresh] = useSpin(load);
|
||||
// The Refresh button also re-measures every home; a plain load reuses the
|
||||
// server's cached numbers.
|
||||
const [spinning, refresh] = useSpin(useCallback(() => load(true), [load]));
|
||||
|
||||
useEffect(() => {
|
||||
if (me && me.role !== "developer") void load();
|
||||
}, [me, load]);
|
||||
|
||||
// Homes are measured in the background: ask again until every number is in.
|
||||
useEffect(() => {
|
||||
if (!measuring) return;
|
||||
const id = setTimeout(() => void loadStorage(), 4000);
|
||||
return () => clearTimeout(id);
|
||||
}, [measuring, storage, loadStorage]);
|
||||
|
||||
// Local mode, or a developer: there is no Users page for them.
|
||||
if (!me || me.role === "developer") return <Navigate to="/" replace />;
|
||||
|
||||
@@ -168,7 +200,7 @@ export function Users() {
|
||||
)}
|
||||
|
||||
<div className="card overflow-x-auto">
|
||||
<table className="w-full min-w-[760px]" data-testid="users-table">
|
||||
<table className="w-full min-w-[860px]" data-testid="users-table">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-left">
|
||||
<th className={th}>{t("name")}</th>
|
||||
@@ -177,6 +209,7 @@ export function Users() {
|
||||
<th className={`${th} text-right`}>{t("sessions")}</th>
|
||||
<th className={`${th} text-right`}>{t("last7d")}</th>
|
||||
<th className={`${th} text-right`}>{t("last30d")}</th>
|
||||
<th className={`${th} text-right`}>{t("storage")}</th>
|
||||
{isAdmin && <th className={`${th} text-right`}>{t("actions")}</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -186,8 +219,8 @@ export function Users() {
|
||||
Array.from({ length: 4 }).map((_, i) => (
|
||||
<TableRowSkeleton
|
||||
key={i}
|
||||
columns={isAdmin ? 7 : 6}
|
||||
widths={["w-36", "w-20", "w-8", "w-8", "w-14", "w-14", "w-28"]}
|
||||
columns={isAdmin ? 8 : 7}
|
||||
widths={["w-36", "w-20", "w-8", "w-8", "w-14", "w-14", "w-14", "w-28"]}
|
||||
/>
|
||||
))}
|
||||
{users?.map((u) => {
|
||||
@@ -244,6 +277,10 @@ export function Users() {
|
||||
</td>
|
||||
<UsageCell usage={u.last7d} />
|
||||
<UsageCell usage={u.last30d} />
|
||||
<StorageCell
|
||||
storage={storage ? (storage[u.id] ?? null) : undefined}
|
||||
measuring={measuring}
|
||||
/>
|
||||
{isAdmin && (
|
||||
<td className="px-5 py-2 text-right whitespace-nowrap">
|
||||
<RowAction label={t("edit.button")} onClick={() => setEditing(u)}>
|
||||
@@ -341,6 +378,40 @@ function UsageCell({ usage }: { usage: { cost: number; tokens: number } }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A user's home folder size (`undefined` = not loaded yet). `null` while the
|
||||
* server is still measuring reads "Measuring…", otherwise "—" (no home of
|
||||
* their own).
|
||||
*/
|
||||
function StorageCell({ storage, measuring }: { storage?: UserStorage; measuring: boolean }) {
|
||||
const { t } = useTranslation("users");
|
||||
if (!storage) {
|
||||
const pending = storage === undefined || measuring;
|
||||
return (
|
||||
<td
|
||||
className="px-5 py-3 text-right text-sm tabular-nums text-fg-muted"
|
||||
title={pending ? undefined : t("storageNone")}
|
||||
>
|
||||
{pending ? t("storageMeasuring") : "—"}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<td
|
||||
className="px-5 py-3 text-right tabular-nums"
|
||||
title={storage.partial ? t("storagePartial") : undefined}
|
||||
>
|
||||
<div className="text-sm text-fg-primary">
|
||||
{storage.partial ? "≥ " : ""}
|
||||
{formatBytes(storage.bytes)}
|
||||
</div>
|
||||
<div className="text-[11px] text-fg-muted">
|
||||
{t("storageHint", { files: fmt(storage.files), at: formatDateTime(storage.measuredAt) })}
|
||||
</div>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
function RowAction({
|
||||
label,
|
||||
disabled,
|
||||
|
||||
@@ -64,12 +64,14 @@ import {
|
||||
PanelLeftClose,
|
||||
PanelRightClose,
|
||||
Maximize2,
|
||||
FolderOpen,
|
||||
Minimize2,
|
||||
ChartColumn,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
} from "lucide-react";
|
||||
import { api } from "../lib/api";
|
||||
import { usePermissions } from "../components/AuthGate";
|
||||
import type {
|
||||
CwdSuggestion,
|
||||
LaneSource,
|
||||
@@ -130,6 +132,7 @@ import PipelineMap from "../components/lanes/PipelineMap";
|
||||
import LaneCard, { since } from "../components/lanes/LaneCard";
|
||||
import { AddLaneModal } from "../components/lanes/AddLaneModal";
|
||||
import { LaneChangesPanel } from "../components/lanes/LaneChangesPanel";
|
||||
import { FileExplorer } from "../components/lanes/FileExplorer";
|
||||
import { WorkspaceContext } from "../components/lanes/WorkspaceContext";
|
||||
import { OPEN_IN_CHANGES_EVENT, type OpenInChanges } from "../lib/openInChanges";
|
||||
import { LaneGitRailCounts } from "../components/lanes/LaneGitHeader";
|
||||
@@ -659,6 +662,7 @@ function ConsoleArea({
|
||||
|
||||
export function Workspace() {
|
||||
const { t: tLanes } = useTranslation("lanes");
|
||||
const { local } = usePermissions();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
// Lane state: the list is the shared store the sidebar reads too; the
|
||||
@@ -773,6 +777,10 @@ export function Workspace() {
|
||||
// Whether the Changes panel is open. A viewer preference, so it lives in
|
||||
// localStorage and never reaches the server — same rule as the lane strip's
|
||||
// order (client/src/lib/laneOrderStorage.ts).
|
||||
// The File Explorer dialog, opened from the Changes panel header.
|
||||
const [explorerOpen, setExplorerOpen] = useState(false);
|
||||
// Bumped when the File Explorer changed files: the Files tree reads again.
|
||||
const [filesChanged, setFilesChanged] = useState(0);
|
||||
const [changesOpen, setChangesOpen] = useState(() => {
|
||||
try {
|
||||
return window.localStorage.getItem(CHANGES_OPEN_KEY) === "1";
|
||||
@@ -1511,6 +1519,35 @@ export function Workspace() {
|
||||
>
|
||||
<ChartColumn className="h-4 w-4" />
|
||||
</button>
|
||||
{/* The File Explorer, beside the window controls — on this
|
||||
workspace (the session's own worktree when it has one).
|
||||
Not in local mode: the desktop's file manager is there. */}
|
||||
{local ? (
|
||||
<span className="ml-auto" />
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="panel-file-explorer"
|
||||
disabled={!panelAt}
|
||||
onClick={() => setExplorerOpen(true)}
|
||||
aria-label={tLanes("changes.openExplorer")}
|
||||
title={tLanes("changes.openExplorer")}
|
||||
className="ml-auto flex h-6 w-6 items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-4 hover:text-fg-primary disabled:opacity-40"
|
||||
>
|
||||
<FolderOpen className="h-4 w-4" />
|
||||
</button>
|
||||
{panelAt && (
|
||||
<FileExplorer
|
||||
open={explorerOpen}
|
||||
laneId={panelAt.laneId}
|
||||
session={panelAt.session}
|
||||
onChanged={() => setFilesChanged((n) => n + 1)}
|
||||
onClose={() => setExplorerOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{/* A window's two controls: Full screen (Restore at full
|
||||
screen, to the last dragged width) and Collapse. */}
|
||||
<button
|
||||
@@ -1519,7 +1556,7 @@ export function Workspace() {
|
||||
onClick={() => setChangesSize(changesFull ? lastDraggedChanges() : "full")}
|
||||
aria-label={changesSizeLabel}
|
||||
title={changesSizeLabel}
|
||||
className="ml-auto flex h-6 w-6 items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-4 hover:text-fg-primary"
|
||||
className="flex h-6 w-6 items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-4 hover:text-fg-primary"
|
||||
>
|
||||
{changesFull ? (
|
||||
<Minimize2 className="h-4 w-4" />
|
||||
@@ -1568,6 +1605,7 @@ export function Workspace() {
|
||||
wide={changesRatio(changesSize) >= 0.45}
|
||||
onDirtyChange={dirtyFor(key)}
|
||||
openRequest={source ? null : changesRequest}
|
||||
filesChanged={source ? 0 : filesChanged}
|
||||
// A sibling worktree forks from the lane's SOURCE repo
|
||||
// when it has one (this lane is itself a worktree of
|
||||
// it); an adopted lane is its own repo.
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
/**
|
||||
* @file Tests for the `/artifacts` page: the library lists what the server
|
||||
* answers, the Hub tab and Share appear only in server mode, a skill is
|
||||
* installed only after a confirmation (and a taken name asks to replace),
|
||||
* and a file preview is a sandboxed iframe with no `allow-*` token. Adding:
|
||||
* a plugin is picked from the list its marketplace link answers (a link the
|
||||
* server cannot read opens the by-hand form), a skill is uploaded from one
|
||||
* Markdown file under the name the user types, or written in the dialog.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { Artifacts } from "../Artifacts";
|
||||
import { api, type Artifact } from "../../lib/api";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
|
||||
vi.mock("../../lib/confirm", () => ({ confirmDialog: vi.fn() }));
|
||||
vi.mock("../../lib/api", () => ({
|
||||
api: {
|
||||
lanes: { list: vi.fn() },
|
||||
artifacts: {
|
||||
settings: vi.fn(),
|
||||
list: vi.fn(),
|
||||
update: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
install: vi.fn(),
|
||||
setInstallsEnabled: vi.fn(),
|
||||
skills: vi.fn(),
|
||||
addSkill: vi.fn(),
|
||||
addPlugin: vi.fn(),
|
||||
inspectMarket: vi.fn(),
|
||||
uploadSkills: vi.fn(),
|
||||
writeSkill: vi.fn(),
|
||||
uploadFile: vi.fn(),
|
||||
candidates: vi.fn(),
|
||||
rawUrl: (id: number, path?: string) => `/api/artifacts/${id}/raw?path=${path ?? ""}`,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const item = (over: Partial<Artifact>): Artifact => ({
|
||||
id: 1,
|
||||
kind: "file",
|
||||
title: "report.html",
|
||||
description: "",
|
||||
ownerId: 1,
|
||||
owner: "vi",
|
||||
mine: true,
|
||||
canChange: true,
|
||||
laneId: 1,
|
||||
sessionId: null,
|
||||
source: "out/report.html",
|
||||
market: null,
|
||||
url: null,
|
||||
files: [{ path: "report.html", size: 10 }],
|
||||
size: 10,
|
||||
shared: false,
|
||||
sharedAt: null,
|
||||
installs: 0,
|
||||
createdAt: "2026-10-14T00:00:00Z",
|
||||
updatedAt: "2026-10-14T00:00:00Z",
|
||||
...over,
|
||||
});
|
||||
|
||||
const open = () =>
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Artifacts />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(api.artifacts.settings).mockResolvedValue({
|
||||
serverMode: false,
|
||||
canShare: false,
|
||||
installsEnabled: true,
|
||||
canManage: true,
|
||||
});
|
||||
vi.mocked(api.artifacts.list).mockResolvedValue({
|
||||
items: [
|
||||
item({}),
|
||||
item({ id: 2, kind: "skill", title: "deploy", source: "deploy", files: [{ path: "SKILL.md", size: 3 }] }),
|
||||
],
|
||||
});
|
||||
vi.mocked(confirmDialog).mockReset();
|
||||
vi.mocked(api.artifacts.install).mockReset();
|
||||
vi.mocked(api.lanes.list).mockResolvedValue({ lanes: [], counts: {} } as never);
|
||||
vi.mocked(api.artifacts.skills).mockResolvedValue({ items: [] });
|
||||
});
|
||||
|
||||
const addMenu = async (user: ReturnType<typeof userEvent.setup>, label: string) => {
|
||||
open();
|
||||
await screen.findByText("deploy");
|
||||
await user.click(screen.getByTestId("artifacts-add"));
|
||||
await user.click(screen.getByRole("button", { name: label }));
|
||||
};
|
||||
|
||||
describe("Adding", () => {
|
||||
it("adds the plugins picked from a marketplace link", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(api.artifacts.inspectMarket).mockResolvedValue({
|
||||
market: "https://git.x.vn/o/skills.git",
|
||||
name: "sg",
|
||||
description: "",
|
||||
plugins: [
|
||||
{ name: "sg-dev", key: "sg-dev@sg", description: "Dev", version: "", category: "" },
|
||||
{ name: "sg-common", key: "sg-common@sg", description: "", version: "", category: "" },
|
||||
],
|
||||
});
|
||||
vi.mocked(api.artifacts.addPlugin).mockResolvedValue({ item: item({ kind: "plugin" }) });
|
||||
await addMenu(user, "Plugin");
|
||||
await user.type(screen.getByLabelText("Marketplace link"), "https://git.x.vn/o/skills.git");
|
||||
await user.click(screen.getByRole("button", { name: "Read plugins" }));
|
||||
await screen.findByTestId("market-plugins");
|
||||
await user.click(screen.getByLabelText("Select all"));
|
||||
await user.click(screen.getByRole("button", { name: "Add 2 plugin(s)" }));
|
||||
await waitFor(() => expect(api.artifacts.addPlugin).toHaveBeenCalledTimes(2));
|
||||
expect(api.artifacts.addPlugin).toHaveBeenCalledWith({
|
||||
key: "sg-dev@sg",
|
||||
market: "https://git.x.vn/o/skills.git",
|
||||
title: "sg-dev",
|
||||
description: "Dev",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the by-hand form when the link cannot be read", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(api.artifacts.inspectMarket).mockRejectedValue(
|
||||
Object.assign(new Error("needs a login"), { code: "ENEEDLOGIN" })
|
||||
);
|
||||
await addMenu(user, "Plugin");
|
||||
await user.type(screen.getByLabelText("Marketplace link"), "https://git.x.vn/o/private.git");
|
||||
await user.click(screen.getByRole("button", { name: "Read plugins" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("needs a login");
|
||||
expect(screen.getByLabelText("Marketplace (owner/repo or git URL)")).toHaveValue(
|
||||
"https://git.x.vn/o/private.git"
|
||||
);
|
||||
});
|
||||
|
||||
it("uploads one Markdown file as a skill under the typed name", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(api.artifacts.uploadSkills).mockResolvedValue({ items: [item({ kind: "skill" })] });
|
||||
await addMenu(user, "Skill");
|
||||
const md = new File(["# Steps"], "notes.md", { type: "text/markdown" });
|
||||
await user.upload(screen.getByTestId("skill-files"), md);
|
||||
expect(await screen.findByTestId("skill-shape")).toHaveTextContent("becomes the skill's SKILL.md");
|
||||
const name = screen.getByLabelText(/Skill name/);
|
||||
await waitFor(() => expect(name).toHaveValue("notes"));
|
||||
await user.clear(name);
|
||||
await user.type(name, "Viết báo cáo");
|
||||
expect(screen.getByTestId("skill-slug")).toHaveTextContent("/Viet-bao-cao");
|
||||
await user.type(screen.getByLabelText(/Description/), "Use for reports");
|
||||
await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Add" }));
|
||||
await waitFor(() => expect(api.artifacts.uploadSkills).toHaveBeenCalled());
|
||||
const [files, fields] = vi.mocked(api.artifacts.uploadSkills).mock.calls[0]!;
|
||||
expect(files.map((f) => f.path)).toEqual(["notes.md"]);
|
||||
expect(fields).toMatchObject({ name: "Viết báo cáo", description: "Use for reports" });
|
||||
});
|
||||
|
||||
it("writes a new skill", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(api.artifacts.writeSkill).mockResolvedValue({ item: item({}), items: [] });
|
||||
await addMenu(user, "Skill");
|
||||
await user.click(screen.getByRole("tab", { name: "Write new" }));
|
||||
const add = within(screen.getByRole("dialog")).getByRole("button", { name: "Add" });
|
||||
await user.type(screen.getByLabelText(/Skill name/), "standup");
|
||||
await user.type(screen.getByLabelText(/Instructions/), "Summarise.");
|
||||
expect(add).toBeDisabled(); // no description yet
|
||||
await user.type(screen.getByLabelText(/Description/), "Daily standup");
|
||||
await user.click(add);
|
||||
await waitFor(() =>
|
||||
expect(api.artifacts.writeSkill).toHaveBeenCalledWith({
|
||||
name: "standup",
|
||||
description: "Daily standup",
|
||||
content: "Summarise.",
|
||||
title: undefined,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Artifacts", () => {
|
||||
it("lists the library, with no Hub or Share in local mode", async () => {
|
||||
open();
|
||||
expect(await screen.findByText("report.html")).toBeInTheDocument();
|
||||
expect(screen.getByText("deploy")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Hub" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /Share/ })).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the Hub and Share in server mode", async () => {
|
||||
vi.mocked(api.artifacts.settings).mockResolvedValue({
|
||||
serverMode: true,
|
||||
canShare: true,
|
||||
installsEnabled: true,
|
||||
canManage: false,
|
||||
});
|
||||
open();
|
||||
expect(await screen.findByRole("button", { name: "Hub" })).toBeInTheDocument();
|
||||
expect(screen.getAllByRole("button", { name: /^Share$/ }).length).toBe(2);
|
||||
});
|
||||
|
||||
it("installs a skill only after a confirmation, and asks before replacing", async () => {
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("deploy");
|
||||
vi.mocked(confirmDialog).mockResolvedValueOnce(false);
|
||||
await user.click(screen.getByRole("button", { name: "Install" }));
|
||||
expect(api.artifacts.install).not.toHaveBeenCalled();
|
||||
|
||||
vi.mocked(confirmDialog).mockResolvedValue(true);
|
||||
vi.mocked(api.artifacts.install)
|
||||
.mockRejectedValueOnce(Object.assign(new Error("taken"), { code: "EEXISTS" }))
|
||||
.mockResolvedValueOnce({ installed: "/h/.claude/skills/deploy", replaced: true });
|
||||
await user.click(screen.getByRole("button", { name: "Install" }));
|
||||
await waitFor(() => expect(api.artifacts.install).toHaveBeenLastCalledWith(2, true));
|
||||
const calls = vi.mocked(confirmDialog).mock.calls;
|
||||
expect(calls[calls.length - 1]?.[0].title).toMatch(/Replace/);
|
||||
});
|
||||
|
||||
it("previews a file in a sandboxed iframe that may run nothing", async () => {
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
await screen.findByText("report.html");
|
||||
await user.click(screen.getAllByRole("button", { name: "Preview" })[0]!);
|
||||
const frame = await screen.findByTestId("artifact-preview");
|
||||
expect(frame.getAttribute("sandbox")).toBe("");
|
||||
expect(frame.getAttribute("src")).toBe("/api/artifacts/1/raw?path=report.html");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* @file Tests for the `/files` page's starting place: the workspace last
|
||||
* shown wins (from PhuNT → AC_SHOP, Files opens AC_SHOP — not the viewer's
|
||||
* own home, empty but for hidden files), the home is the fallback, and an
|
||||
* explicit `?home=` / `?lane=` is obeyed — also when it changes after the
|
||||
* page opened (an admin opening another user's home, then a folder in it).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { act, render, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { FilesPage } from "../FilesPage";
|
||||
import { api } from "../../lib/api";
|
||||
|
||||
type Props = {
|
||||
laneId?: number | null;
|
||||
initialHome?: string | null;
|
||||
onNavigate?: (place: unknown, path: string) => void;
|
||||
};
|
||||
const seen: Array<{ laneId?: number | null; initialHome?: string | null }> = [];
|
||||
let nav: Props["onNavigate"];
|
||||
vi.mock("../../components/lanes/FileExplorer", () => ({
|
||||
FileBrowser: (p: Props) => {
|
||||
seen.push({ laneId: p.laneId, initialHome: p.initialHome });
|
||||
nav = p.onNavigate;
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
vi.mock("../../lib/api", () => ({
|
||||
isHomePlace: (p: unknown) => typeof p === "object" && p !== null && "home" in p,
|
||||
api: {
|
||||
lanes: { list: vi.fn() },
|
||||
files: { homes: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
const open = (url = "/files") =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={[url]}>
|
||||
<FilesPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
seen.length = 0;
|
||||
localStorage.clear();
|
||||
vi.mocked(api.lanes.list).mockResolvedValue({
|
||||
lanes: [
|
||||
{ id: 1, title: "AgentHub", cwd: "/a" },
|
||||
{ id: 2, title: "AC_SHOP", cwd: "/srv/agenthub/users/phunt/AC_SHOP" },
|
||||
],
|
||||
counts: {},
|
||||
} as never);
|
||||
vi.mocked(api.files.homes).mockResolvedValue({
|
||||
homes: [{ id: "me", label: "Vi", readOnly: false }],
|
||||
});
|
||||
});
|
||||
|
||||
describe("FilesPage", () => {
|
||||
it("opens the workspace last shown, not the viewer's own home", async () => {
|
||||
localStorage.setItem("agenthub.workspace.selected", "2");
|
||||
open();
|
||||
await waitFor(() => expect(seen[seen.length - 1]).toEqual({ laneId: 2, initialHome: null }));
|
||||
});
|
||||
|
||||
it("falls back to the home when no workspace was shown", async () => {
|
||||
open();
|
||||
await waitFor(() => expect(seen[seen.length - 1]).toEqual({ laneId: null, initialHome: "me" }));
|
||||
});
|
||||
|
||||
it("obeys an explicit ?home= or ?lane=", async () => {
|
||||
localStorage.setItem("agenthub.workspace.selected", "2");
|
||||
open("/files?home=me");
|
||||
await waitFor(() => expect(seen[seen.length - 1]).toEqual({ laneId: null, initialHome: "me" }));
|
||||
seen.length = 0;
|
||||
open("/files?lane=1");
|
||||
await waitFor(() => expect(seen[seen.length - 1]).toEqual({ laneId: 1, initialHome: null }));
|
||||
});
|
||||
|
||||
it("follows a place picked in the browser, so a folder opened there stays there", async () => {
|
||||
open("/files?home=me");
|
||||
await waitFor(() => expect(nav).toBeTruthy());
|
||||
act(() => nav!({ home: "phunt" }, ""));
|
||||
act(() => nav!({ home: "phunt" }, "AC_SHOP"));
|
||||
await waitFor(() =>
|
||||
expect(seen[seen.length - 1]).toEqual({ laneId: null, initialHome: "phunt" })
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,15 @@ import userEvent from "@testing-library/user-event";
|
||||
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
|
||||
import type { AiTool, AiToolsView } from "../../lib/api";
|
||||
|
||||
// Local mode unless a test says otherwise; still an admin either way.
|
||||
const perms = vi.hoisted(() => ({ local: true }));
|
||||
vi.mock("../../components/AuthGate", async (importOriginal) => {
|
||||
const m = await importOriginal<typeof import("../../components/AuthGate")>();
|
||||
return { ...m, usePermissions: () => ({ ...m.usePermissions(), local: perms.local }) };
|
||||
});
|
||||
vi.mock("../../components/settings/GitIdentitySettings", () => ({
|
||||
GitIdentitySettings: () => <div data-testid="git-identity" />,
|
||||
}));
|
||||
vi.mock("../Settings", () => ({
|
||||
Settings: ({ section }: { section: string }) => (
|
||||
<div data-testid={`settings-${section}`} data-settings-anchor={`${section}-row`} />
|
||||
@@ -52,6 +61,9 @@ vi.mock("../../components/settings/AiToolsSettings", () => ({
|
||||
vi.mock("../../components/settings/AgentInstructionsSettings", () => ({
|
||||
AgentInstructionsSettings: () => <div data-testid="agent-instructions" />,
|
||||
}));
|
||||
vi.mock("../../components/settings/ArtifactsHubSettings", () => ({
|
||||
ArtifactsHubSettings: () => null,
|
||||
}));
|
||||
vi.mock("../../components/settings/PricingSettings", () => ({
|
||||
PricingSettings: ({ vendor }: { vendor: string }) => <div data-testid={`pricing-${vendor}`} />,
|
||||
}));
|
||||
@@ -108,6 +120,7 @@ function renderAt(at: string) {
|
||||
const nav = () => screen.getByRole("navigation", { name: "Settings sections" });
|
||||
|
||||
beforeEach(() => {
|
||||
perms.local = true;
|
||||
__resetAiTools();
|
||||
view = {
|
||||
default: "claude",
|
||||
@@ -288,9 +301,19 @@ describe("SettingsHub", () => {
|
||||
});
|
||||
|
||||
it("shows git logins and worktree suggestions on one Git page", async () => {
|
||||
perms.local = false;
|
||||
renderAt("/settings/git");
|
||||
expect(await screen.findByRole("heading", { level: 1, name: "Git" })).toBeInTheDocument();
|
||||
expect(screen.getByTestId("git-credentials")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("git-identity")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("worktree-visibility")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps AgentHub's own git logins and identity off a local Git page", async () => {
|
||||
renderAt("/settings/git");
|
||||
expect(await screen.findByRole("heading", { level: 1, name: "Git" })).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("git-credentials")).toBeNull();
|
||||
expect(screen.queryByTestId("git-identity")).toBeNull();
|
||||
expect(screen.getByTestId("worktree-visibility")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import type { AuthState, ServerUserUsage } from "../../lib/api";
|
||||
@@ -34,6 +34,7 @@ const row = (id: number, username: string, role: ServerUserUsage["role"]): Serve
|
||||
const users = vi.hoisted(() => ({
|
||||
list: vi.fn(),
|
||||
audit: vi.fn(),
|
||||
storage: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
setPassword: vi.fn(),
|
||||
@@ -74,6 +75,7 @@ beforeEach(() => {
|
||||
users: [row(1, "boss", "admin"), row(2, "mia", "developer")],
|
||||
});
|
||||
users.audit.mockResolvedValue({ entries: [] });
|
||||
users.storage.mockResolvedValue({ storage: {}, measuring: false });
|
||||
users.get.mockImplementation(async (id: number) => ({
|
||||
user: { id, username: "x", role: "developer", disabled: false },
|
||||
workspaces: [],
|
||||
@@ -91,6 +93,28 @@ describe("Users page", () => {
|
||||
expect(users.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows each user's home size, and re-measures on Refresh", async () => {
|
||||
authState = { mode: "server", user: { id: 1, username: "boss", role: "admin" } };
|
||||
users.storage.mockResolvedValue({
|
||||
storage: {
|
||||
1: null,
|
||||
2: {
|
||||
bytes: 3 * 1024 ** 3,
|
||||
files: 1200,
|
||||
partial: false,
|
||||
measuredAt: "2026-10-14T09:00:00Z",
|
||||
},
|
||||
},
|
||||
measuring: false,
|
||||
});
|
||||
renderPage();
|
||||
expect(await screen.findByText("3.0 GB")).toBeTruthy();
|
||||
expect(screen.getByText("Storage")).toBeTruthy();
|
||||
expect(users.storage).toHaveBeenLastCalledWith(false);
|
||||
fireEvent.click(screen.getByRole("button", { name: /Refresh/ }));
|
||||
await waitFor(() => expect(users.storage).toHaveBeenLastCalledWith(true));
|
||||
});
|
||||
|
||||
it("shows an analyst the accounts with no controls", async () => {
|
||||
authState = { mode: "server", user: { id: 3, username: "ana", role: "analyst" } };
|
||||
renderPage();
|
||||
|
||||
@@ -56,6 +56,12 @@ const { HOME, LANE_A, LANE_B } = vi.hoisted(() => {
|
||||
|
||||
// The workspace's home (its own suite) fetches sources and memory; these
|
||||
// tests are about the session view it hides, so it is a stub here.
|
||||
// Local mode unless a test says otherwise.
|
||||
const perms = vi.hoisted(() => ({ local: true }));
|
||||
vi.mock("../../components/AuthGate", async (importOriginal) => {
|
||||
const m = await importOriginal<typeof import("../../components/AuthGate")>();
|
||||
return { ...m, usePermissions: () => ({ ...m.usePermissions(), local: perms.local }) };
|
||||
});
|
||||
vi.mock("../../components/lanes/WorkspaceHome", () => ({
|
||||
WorkspaceHome: () => <div data-testid="workspace-home" />,
|
||||
paneRunId: (id: number, slot: number) =>
|
||||
@@ -108,6 +114,12 @@ vi.mock("../../lib/api", async (importOriginal) => {
|
||||
features: { list: r({ features: [] }), show: r({ feature: null }) },
|
||||
proof: { list: r({ features: [] }), imageUrl: () => "" },
|
||||
},
|
||||
// The File Explorer opened from the panel header.
|
||||
files: {
|
||||
homes: r({ homes: [] }),
|
||||
list: r({ path: "", parent: null, entries: [], truncated: false }),
|
||||
trash: r({ items: [] }),
|
||||
},
|
||||
aiProxies: { list: r({ items: [] }) },
|
||||
sessions: { list: r({ sessions: [], total: 0, limit: 50, offset: 0 }) },
|
||||
},
|
||||
@@ -147,6 +159,7 @@ async function settle() {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
perms.local = true;
|
||||
i18n.changeLanguage("en");
|
||||
});
|
||||
|
||||
@@ -203,6 +216,22 @@ describe("Workspace — the Changes panel's width", () => {
|
||||
expect(card().className).toContain("w-[25%]");
|
||||
});
|
||||
|
||||
it("opens the File Explorer from the button beside Full screen", async () => {
|
||||
perms.local = false;
|
||||
await openPanel();
|
||||
const btn = screen.getByTestId("panel-file-explorer");
|
||||
// Right before the window controls, in the same header strip.
|
||||
expect(btn.nextElementSibling).toBe(screen.getByTestId("lane-changes-resize"));
|
||||
fireEvent.click(btn);
|
||||
expect(await screen.findByTestId("file-explorer")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("has no File Explorer button in local mode", async () => {
|
||||
await openPanel();
|
||||
expect(screen.queryByTestId("panel-file-explorer")).toBeNull();
|
||||
expect(screen.getByTestId("lane-changes-resize")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("remembers the width across a reload, and never asks the server", async () => {
|
||||
await openPanel();
|
||||
fireEvent.click(screen.getByTestId("lane-changes-resize"));
|
||||
|
||||
@@ -7178,7 +7178,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
<span
|
||||
class="text-status-warning/90"
|
||||
>
|
||||
UI build v2.7.7 (rebuild client to match)
|
||||
UI build v2.8.0 (rebuild client to match)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
+51
-11
@@ -85,11 +85,11 @@ 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}`, 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) (both `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)), 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), `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) and `POST /api/users/:id/workspaces` (`{laneId}`; the workspace's owner becomes that user). 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.
|
||||
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.
|
||||
|
||||
`GET /api/accounts[?force=1]` lists the Claude account pool ([SERVER-MODE.md](SERVER-MODE.md#claude-account-pool)): `{accounts: [{name, addedAt, expiresAt, expired, livePanes, spend5h, spend7d, quota: {fiveHour, sevenDay, checkedAt, error} | null, quotaPercent, full}], codex: [{name, kind: "apikey"|"chatgpt", addedAt, livePanes, spend5h, spend7d, quota: {windows: [{label, usedPercent, resetsAt}], asOf} | null, quotaPercent, full}], blockPercent}` — `codex` is the [Codex account pool](SERVER-MODE.md#codex-account-pool). It never includes a key or a token. `force=1` re-reads every quota first. Run rows (`/api/run/history`) carry `account`, the pool account their pane ran on (`null` = the machine's own login).
|
||||
`GET /api/accounts[?force=1]` lists the Claude account pool ([SERVER-MODE.md](SERVER-MODE.md#claude-account-pool)): `{accounts: [{name, addedAt, expiresAt, expired, livePanes, spend5h, spend7d, tokens5h, tokens7d, quota: {fiveHour, sevenDay, checkedAt, error} | null, quotaPercent, full}], codex: [{name, kind: "apikey"|"chatgpt", addedAt, livePanes, spend5h, spend7d, tokens5h, tokens7d, quota: {windows: [{label, usedPercent, resetsAt}], asOf} | null, quotaPercent, full}], blockPercent}` — `codex` is the [Codex account pool](SERVER-MODE.md#codex-account-pool). `spend*`/`tokens*` = the sessions the account's runs held, over the hours they held them (a Codex session counts whole once its run started in the window). It never includes a key or a token. `force=1` re-reads every quota first. Run rows (`/api/run/history`) carry `account`, the pool account their pane ran on (`null` = the machine's own login).
|
||||
|
||||
An admin (server mode) adds an account with `POST /api/accounts` `{tool: "claude"|"codex", name, currentPassword, …}` → `201 {account}`. For Claude the body carries one of: `profile` (a saved switch-user profile, MOVED in: the profile is deleted; the one the host's CLI is logged into moves in with its live login and the host's home becomes one more placement the server refreshes — `409 EACTIVE` only for a macOS Keychain login; `name` defaults to it), `credentials` (the text of a `.credentials.json`; Anthropic is asked whose account it is, `502 EUPSTREAM` when it cannot be reached), or `token` (a `claude setup-token` token). For Codex, `token` is an OpenAI API key or the text of an `auth.json`. `GET /api/accounts/profiles` lists the saved profiles `{profiles: [{name, label, email, subscriptionType, active}]}` (no token). Claude rows in `GET /api/accounts` carry `kind` (`token`|`login`), `email` and `refreshError`; a login's `expiresAt` is null and removes one with `DELETE /api/accounts/:name` `{tool, currentPassword}` → `{ok: true}`. No answer carries the token. `403 EREAUTH` wrong password (`429 ETOOMANY` after 10), `403 EADMIN` for a non-admin, `403 ELOCALMODE` in local mode, `400 EBADTOOL`/`EBADNAME`/`EBADTOKEN`, `409 EEXISTS`, `404 ENOACCOUNT`; each change is audited by account name.
|
||||
|
||||
@@ -102,10 +102,13 @@ An admin (server mode) adds an account with `POST /api/accounts` `{tool: "claude
|
||||
| `GET /api/me/instructions` | `{instructions, max, tools}` — `tools` lists the AI tool ids whose new panes receive them (`["claude","codex"]`; Cursor CLI and Antigravity have no per-session way to take them). The account's own agent instructions (Settings → AI tools → My agent instructions, `""` when none); `401 EAUTH` with no login |
|
||||
| `PUT /api/me/instructions` `{instructions: "<markdown>" \| null}` | replaced, the same shape back; blank or `null` clears; `400 EBADFIELD` not a string, `413 ETOOBIG` over 16 000 characters. Put BEFORE the workspace's own instructions in every new Claude/Codex pane of a workspace the account owns (local mode: every workspace) — see Workspace context below |
|
||||
| `POST /api/me/onboarded` | the first-run setup is done or skipped (kept from the first call) |
|
||||
| `GET /api/me/account` | Settings → Account. Server mode: `{mode: "server", user: {id, username, role, disabled, displayName, email, createdAt}, workspaces, sessions, logins, lastLoginAt}`; local mode `{mode: "local"}` |
|
||||
| `GET /api/me/account` | Settings → Account. Server mode: `{mode: "server", user: {id, username, role, disabled, displayName, email, avatarAt, createdAt}, workspaces, sessions, logins, lastLoginAt}`; local mode `{mode: "local"}` |
|
||||
| `PATCH /api/me/account` `{displayName?, email?}` | the account's own profile (`""`/`null` clears), the same shape back; `400 EBADFIELD` (display name over 100 characters or with control characters) / `EBADEMAIL` |
|
||||
| `POST /api/me/password` `{currentPassword, newPassword}` | `{ok: true}`; every other login of the account ends, this one stays. `403 EREAUTH` wrong current password (`429 ETOOMANY` after 10), `400 EBADPASSWORD` |
|
||||
| `POST /api/me/sign-out-others` | `{ended}` — every login of the account but this one ends |
|
||||
| `GET /api/me/avatar` | server mode: the account's own picture (`nosniff`, `sandbox` CSP; the client adds `?v=<avatarAt>`), `404 ENOAVATAR` when it has none |
|
||||
| `PUT /api/me/avatar` (raw image bytes) | the account's picture (PNG, JPEG, GIF or WebP by magic bytes — never SVG), stored as `<data dir>/avatars/u<id>.<ext>`; the `/api/me/account` shape back with `user.avatarAt` set. `400 EBADIMAGE`, `413 ETOOBIG` over 1 MB, `403 ELOCALMODE`. Login cookie only, audited |
|
||||
| `DELETE /api/me/avatar` | removes it (`avatarAt` back to `null`); deleting the user removes it too |
|
||||
|
||||
The keys are the browser's own localStorage names: `theme`, `agenthub.theme.dark`, `agenthub.theme.light`, `i18nextLng`, `agenthub.terminal.font`, `agenthub.terminal.fontSize`, `agenthub.ui.fontSize`, `agenthub.pet`, `agenthub.pet.size`, `agenthub.pet.names`, `agent-dashboard-sagi-enabled`, `agent-dashboard-sagi-muted`, `agent-monitor-notifications`, `agenthub.defaultTool`, `agenthub.permissionMode` (never `bypassPermissions` — bypass stays the per-session switch), `agenthub.tour`, and `agenthub.chatUi` (`"1"` = Claude/Codex sessions open as a chat; read and written on the server only, by `client/src/lib/chatUi.ts`). The request never names an account, and writes are same-origin. An account's save writes only their own row, and under S3 a `theme` of `dark` or `light` also becomes the `theme` in their own `~/.claude/settings.json`, written as them.
|
||||
|
||||
@@ -275,7 +278,7 @@ POST /api/lanes/:id/fs/upload?path=&conflict= raw body, streamed
|
||||
GET /api/lanes/:id/fs/zip?p=<path>&p=… application/zip, streamed
|
||||
```
|
||||
|
||||
The workspace **File Explorer** — the **Files** page in the sidebar (`/files?lane=<id>&path=<folder>`), laid out like GNOME Files (workspaces as places, Back/Forward, a path bar, icon grid or list, hidden files behind Ctrl+H), and the same manager in a dialog from a workspace's Files tab (the folder button; "Open in File Explorer" on a folder). `?session=` / `?source=` pick the same folder the
|
||||
The workspace **File Explorer** (server mode only — a local dashboard has no **Files** entry, `/files` redirects home, and its buttons are hidden; the routes still answer) — the **Files** page in the sidebar (`/files?lane=<id>&path=<folder>`), laid out like GNOME Files (workspaces as places, Back/Forward, a path bar, icon grid or list, hidden files behind Ctrl+H), and the same manager in a dialog from a workspace's Files tab (the folder button; "Open in File Explorer" on a folder). `?session=` / `?source=` pick the same folder the
|
||||
git reads do. Paths go through the read path's guards (`lanePath`, the parent
|
||||
`resolveInLane`-confined, the last segment kept as a name so a symlink is acted
|
||||
on as a link); nothing in `.git`, no secret file, never the workspace folder
|
||||
@@ -1040,7 +1043,7 @@ cannot collide on `index.lock`.
|
||||
|
||||
```
|
||||
GET /api/me/git { account: "member"|"host", writable, ssh: { publicKey, fingerprint } | null, https: [{ protocol, host, username, hasToken }] }
|
||||
POST /api/me/git/ssh-key Make the SSH key — Body: { replace? } (409 EEXISTS without replace) → 201, same shape
|
||||
POST /api/me/git/ssh-key Make the SSH key — Body: { replace?, type?: "ed25519" | "rsa" } (409 EEXISTS without replace) → 201, same shape
|
||||
DELETE /api/me/git/ssh-key Delete it (404 ENOTFOUND)
|
||||
POST /api/me/git/https Save an https login — Body: { host, username, password }
|
||||
DELETE /api/me/git/https/:host Delete one (404 ENOTFOUND)
|
||||
@@ -1058,8 +1061,7 @@ a prompt.
|
||||
The signed-in user's OWN SSH key and HTTPS logins, used by `POST
|
||||
/api/lanes/clone` (Settings → Git → **Your git identity**). With a Linux
|
||||
account of their own (S3) everything lives in their home under
|
||||
`~/.config/agenthub/` — `ssh/id_ed25519` (+`.pub`, an unencrypted ed25519
|
||||
key in OpenSSH format, made by the server) and `git-credentials` (git's
|
||||
`~/.config/agenthub/` — `ssh/id_ed25519` or `ssh/id_rsa` (+`.pub`, unencrypted, made by the server: ed25519 in OpenSSH format by default, or RSA 4096 as PKCS#1 PEM for hosts that take only RSA, such as AWS IAM/CodeCommit; one key per account, and `ssh.type` says which) and `git-credentials` (git's
|
||||
`credential-store` format) — written only AS the member (`write-as`, `0600`)
|
||||
and read through `readFileSafe`; no secret crosses sudo's argv or env.
|
||||
Otherwise the account is the host's: the key is
|
||||
@@ -1537,6 +1539,7 @@ POST /api/locks/:name/release
|
||||
GET /api/lanes/:id/sources
|
||||
PUT /api/lanes/:id/instructions {"instructions": "…" | null}
|
||||
POST /api/lanes/:id/sources/folder {"path": "/abs/dir"}
|
||||
POST /api/lanes/:id/sources/clone {"url": "https://host/o/r.git", "name"?: "r", "credentials"?: {username, password, remember?}}
|
||||
POST /api/lanes/:id/sources/file raw body, Content-Type: application/octet-stream, X-File-Name: <URI-encoded name>
|
||||
DELETE /api/lanes/:id/sources/:sourceId
|
||||
GET /api/lanes/:id/memory
|
||||
@@ -1559,6 +1562,7 @@ What a workspace's home page edits (`server/lib/lane-sources.js`, `server/routes
|
||||
|
||||
- **Instructions** — the `instructions` key is required (`400 EBADFIELD` without it), a string or `null`; blank clears; over 16 000 characters is `413 ETOOBIG`. The lane is re-broadcast (`lane_update`). The text is stored in `lanes.instructions` but is NOT part of the lane payload (`GET /api/lanes`, `lane_update`) — read it here.
|
||||
- **Folder** — must be absolute, exist and be a directory (`400 EBADPATH`), must not be or contain the OS home (`400 EBADHOME`), and must not be the workspace's own folder or one it already has (`400 EDUP`). Stored by real path. Removing it only drops the row.
|
||||
- **Clone** — clones a related repo BESIDE the workspace folder (into its parent; no path is taken from the request) and adds it as a Folder. The clone is `POST /api/lanes/clone`'s own: the same URL allowlist (`400 EBADURL`), one plain `name` (default: the repo's), `409 EEXISTS` for a taken name, run as the folder's account with that account's git identity, `409 ECREDENTIALS` (with `auth: {protocol, host}`) / `ESSHAUTH` / `ENOREPO`; a tool that takes no folders is `400 EUNSUPPORTED`. Answers the view plus `path`. Removing the folder later never deletes the clone. The workspace home's **Add folder** form takes several URLs, one per line, and clones them in turn.
|
||||
- **File** — up to 10 MB (`413 ETOOBIG`), not empty (`400 EEMPTY`). AgentHub stores it under `<data dir>/workspace-context/<lane id>/` with a name it derives from `X-File-Name` (directory parts and path characters dropped, `name (2).ext` on a clash), so a request never names a path. It is a COPY taken at upload: later edits to the original are not seen — remove and upload it again, or add its directory as a Folder (read live from disk). Removing it deletes that copy. At most 50 sources per workspace (`400 ETOOMANY`).
|
||||
- **Memory** — read-only: the folder's `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md`, and for a Claude workspace `<CLAUDE_HOME>/projects/<encoded cwd>/memory/*.md` — `{files: [{label, path, size, mtime, truncated, content}]}`, each at most 256 KB of content.
|
||||
- Every write is same-origin only (`403 EBADORIGIN`); an unknown workspace is `404 ENOLANE`, an unknown source `404 ENOSOURCE`.
|
||||
@@ -1780,7 +1784,7 @@ curl http://localhost:4820/api/sessions/sess_abc123/outline
|
||||
GET /api/sessions/:id/image?path=<absolute path>
|
||||
```
|
||||
|
||||
The bytes of an image the session's own `Read` tool read (a `PostToolUse` `Read` event of this session whose `tool_input.file_path` equals `path` exactly) — how a Chat pane's Files read preview shows a screenshot outside the workspace folder. Raster only (`png`, `jpg`/`jpeg`, `gif`, `webp`, else 400 `ENOTIMAGE`), at most 20 MB (`ETOOBIG`), served with a `sandbox` CSP, `nosniff` and `no-store`. 404 for an unknown session, a path the session never read, or a file that is gone; 403 `EUNSUPPORTED` for a session pushed from another machine (`push:<source>`), whose paths are not this host's to read, and in server mode without S3. With S3 a member's session (its folder under the users root) gets only a file inside that member's home that the member owns (else 404), a host session any file — a member's hook can only report sessions in its own home.
|
||||
The bytes of an image the session's own `Read` tool read (a `PostToolUse` `Read` event of this session whose `tool_input.file_path` equals `path` exactly) — how a Chat pane's Files read preview shows a screenshot outside the workspace folder — or one the session NAMED (see `/file` below: a chart its script drew). Raster only (`png`, `jpg`/`jpeg`, `gif`, `webp`, else 400 `ENOTIMAGE`), at most 20 MB (`ETOOBIG`), served with a `sandbox` CSP, `nosniff` and `no-store`. 404 for an unknown session, a path the session never read, or a file that is gone; 403 `EUNSUPPORTED` for a session pushed from another machine (`push:<source>`), whose paths are not this host's to read, and in server mode without S3. With S3 a member's session (its folder under the users root) gets only a file inside that member's home that the member owns (else 404), a host session any file — a member's hook can only report sessions in its own home.
|
||||
|
||||
```bash
|
||||
curl -o shot.png "http://localhost:4820/api/sessions/sess_abc123/image?path=/home/me/.cache/shot.png"
|
||||
@@ -1794,7 +1798,7 @@ curl -o shot.png "http://localhost:4820/api/sessions/sess_abc123/image?path=/hom
|
||||
GET /api/sessions/:id/file?path=<absolute path>
|
||||
```
|
||||
|
||||
`{ "text": "...", "truncated": false }` for a text file the session's own `Read`, `Write`, `Edit`, `MultiEdit` or `NotebookEdit` named (a `PostToolUse` event of this session whose `tool_input.file_path` or `notebook_path` equals `path` exactly) — how a Chat pane's Outputs/Files preview shows a file outside the workspace folder (a report written to `~/Documents`). At most the first 512 KB (`truncated: true` beyond). 400 `EBADPATH` for a relative path; 403 `ESECRET` for a credential by name (`isSecretConfigPath` — `.credentials.json`, `auth.json`, AgentHub's own stores and data dir — or a `settings.local.json`), judged on the path and on what it resolves to; 415 `EBINARY` for a file with a NUL byte in its first 8 KB; 404 for an unknown session, a path the session never touched, or a non-regular or missing file. 403 `EUNSUPPORTED` and the S3 member rules are the same as for `/image` above.
|
||||
`{ "text": "...", "truncated": false }` for a text file the session's own `Read`, `Write`, `Edit`, `MultiEdit` or `NotebookEdit` named (a `PostToolUse` event of this session whose `tool_input.file_path` or `notebook_path` equals `path` exactly) — how a Chat pane's Outputs/Files preview shows a file outside the workspace folder (a report written to `~/Documents`). A file the session only NAMED is served too (issue #76: a report its own script generated): `path` appears as a whole path — not as the prefix of a longer one — in one of its `PostToolUse` `Bash` events' `tool_input.command` or `tool_response.stdout`, or in a `Stop`/`SubagentStop` event's `last_assistant_message`, and the session's account could read it itself (`access(2)`, which ignores the S3 unit's `CAP_DAC_READ_SEARCH`; for a member's session the home/owner rule below decides). At most the first 512 KB (`truncated: true` beyond). 400 `EBADPATH` for a relative path; 403 `ESECRET` for a credential by name (`isSecretConfigPath` — `.credentials.json`, `auth.json`, AgentHub's own stores and data dir — or a `settings.local.json`), judged on the path and on what it resolves to; 415 `EBINARY` for a file with a NUL byte in its first 8 KB; 404 for an unknown session, a path the session never touched, or a non-regular or missing file. 403 `EUNSUPPORTED` and the S3 member rules are the same as for `/image` above.
|
||||
|
||||
```bash
|
||||
curl "http://localhost:4820/api/sessions/sess_abc123/file?path=/home/me/Documents/REPORT.md"
|
||||
@@ -2818,7 +2822,7 @@ DELETE /api/run/:id Kill (SIGTERM → SIGKILL after 5 s)
|
||||
|
||||
**PTY streaming:** Frames from the tmux pane are streamed to the client over `/ws-pty/:runId` as binary WebSocket frames (not JSON). The Workspace page's TerminalView component feeds these frames to xterm.js for live rendering. Simultaneously, `agenthub workspace shell` can attach the same session via a real local terminal, staying in sync with the browser view.
|
||||
|
||||
Every history row carries `lane_id` (the workspace whose run it belongs to) and `tool` (the CLI that was invoked: `"claude"` or `"codex"`). A run's `id` is its tmux pane name, which each Start in that pane reuses, so the run it replaces is kept as its own row with `id` = `<pane name>@<its started_at>` (status `abandoned` if it never recorded an end). A row still marked `running` is ended once its tmux session is gone — checked at server start and on the 10 s run-heal beat (`DASHBOARD_RUN_HEAL_MS`); a pane that survived a server restart stays `running`. It becomes `interrupted` when an agent session (not a Terminal tab, `session_id` known) died under the user — a reboot, a killed tmux, a crash; a Claude session the user ended (`SessionEnd` with reason `prompt_input_exit`/`logout`) and every row with no session become `abandoned`. Only Claude reports why it ended, so any other tool's vanished pane counts as interrupted. A pane the dashboard closed (Stop, close tab, Quit) is already `killed`. `GET /api/run/interrupted` lists the newest interrupted row of each session no newer run holds (`{id, session_id, lane_id, tool, cwd, model, permission_mode, effort, prompt_preview, started_at, ended_at, lane_title, lane_cwd, session_name}`), only the caller's own workspaces in server mode — the app-wide **Resume interrupted sessions?** dialog reads it; dismissing flips them to `abandoned`. The heal beat broadcasts `runs_interrupted` (no payload) whenever it ended a row, and every client refetches. `GET /api/run/history?laneId=<n>` returns only that workspace's runs. Spawned Claude processes fire the dashboard's hooks like any other CLI session, so they show up in `/api/sessions`, and the Dashboard's Analytics tab (Workflow sub-tab included) automatically. Codex runs do not emit these hooks; they are recorded only in run history and `dashboard_runs`.
|
||||
Every history row carries `lane_id` (the workspace whose run it belongs to) and `tool` (the CLI that was invoked: `"claude"` or `"codex"`). A run's `id` is its tmux pane name, which each Start in that pane reuses, so the run it replaces is kept as its own row with `id` = `<pane name>@<its started_at>` (status `abandoned` if it never recorded an end). A row still marked `running` is ended once its tmux session is gone — checked at server start and on the 10 s run-heal beat (`DASHBOARD_RUN_HEAL_MS`); a pane that survived a server restart stays `running`. It becomes `interrupted` when an agent session (not a Terminal tab, `session_id` known) died under the user — a reboot, a killed tmux, a crash; a Claude session the user ended (`SessionEnd` with reason `prompt_input_exit`/`logout`) and every row with no session become `abandoned`. A pane whose tmux server has run since before the pane started ended by itself (the user quit Codex, `exit`ed, closed it), so it is `abandoned` too — for Claude only when it sent any `SessionEnd` (none at all is a crash); a pane whose server is gone or restarted, or cannot be asked, died with it and stays `interrupted`. A pane the dashboard closed (Stop, close tab, Quit) is already `killed`. `GET /api/run/interrupted` lists the newest interrupted row of each session no newer run holds (`{id, session_id, lane_id, tool, cwd, model, permission_mode, effort, prompt_preview, started_at, ended_at, lane_title, lane_cwd, session_name}`), only the caller's own workspaces in server mode — the app-wide **Resume interrupted sessions?** dialog reads it; dismissing flips them to `abandoned`. The heal beat broadcasts `runs_interrupted` (no payload) whenever it ended a row, and every client refetches. `GET /api/run/history?laneId=<n>` returns only that workspace's runs. Spawned Claude processes fire the dashboard's hooks like any other CLI session, so they show up in `/api/sessions`, and the Dashboard's Analytics tab (Workflow sub-tab included) automatically. Codex runs do not emit these hooks; they are recorded only in run history and `dashboard_runs`.
|
||||
|
||||
---
|
||||
|
||||
@@ -2939,6 +2943,42 @@ DELETE /api/snapshots/:id { ok: true }
|
||||
|
||||
A snapshot freezes a session as it is at that moment into one immutable `session_snapshots` row (`server/routes/snapshots.js`): `payload` is `{ version: 1, captured_at, redacted: { file_paths }, session, agents, events, stats, cost }` — the session row, its agents (each with its own `cost`), every stored event oldest first (`events.data` exactly as stored), the `/api/sessions/:id/stats` body and the `/api/pricing/cost/:id` result priced at the session's start date. Its `token` is 24 random bytes in base64url (32 characters) and is the only way to read it; the page is `/snapshot/<token>`. With `redact.file_paths`, paths are replaced **before anything is stored**: every `cwd`, `transcript_path`, `agent_transcript_path`, `file_path`, `filePath`, `notebook_path` and `path` value (also inside `events.data` and `metadata` JSON) becomes `[redacted]`, and the session's cwd / the home directory inside any other string (a Bash command, a summary) become `<cwd>` / `~`. A row cannot be updated (a trigger aborts it), outlives its session, and survives **Clear Data** — it goes only through `DELETE` (Settings → **Snapshots**). Both writes are same-origin (`403 EBADORIGIN`); `400 INVALID_INPUT` without `session_id`, `404 NOT_FOUND` for an unknown session, token or id.
|
||||
|
||||
### Artifacts hub
|
||||
|
||||
```http
|
||||
GET /api/artifacts?scope=mine|hub&kind=page|file|skill|plugin&q= {items}
|
||||
GET /api/artifacts/settings {serverMode, canShare, installsEnabled, canManage}
|
||||
PUT /api/artifacts/settings {installsEnabled: boolean} — admin (any caller in local mode); the UI is Settings → AI tools → Artifacts Hub
|
||||
GET /api/artifacts/candidates?laneId= {items: [{path, sessionId, at, exists, pinned}]}
|
||||
GET /api/artifacts/skills?laneId= {items: [{name, from: "user"|"workspace"}]}
|
||||
POST /api/artifacts/page {url, title?, description?}
|
||||
POST /api/artifacts/file {laneId, path, title?, sessionId?}
|
||||
POST /api/artifacts/file/upload multipart: files (one), title?, description? → {item}
|
||||
POST /api/artifacts/skill {name, laneId?, title?, description?}
|
||||
POST /api/artifacts/skill/upload multipart: files, paths (JSON, each file's relative path), name?, title?, description? → {items}
|
||||
POST /api/artifacts/skill/new {name, description, content, title?} → {item, items}
|
||||
POST /api/artifacts/plugin/inspect {market} → {market, name, description, plugins: [{name, key, description, version, category}]}
|
||||
POST /api/artifacts/plugin {key: "name@marketplace", market: "owner/repo" | git URL | marketplace.json URL, title?, description?}
|
||||
GET /api/artifacts/:id {item}
|
||||
PATCH /api/artifacts/:id {title?, description?, shared?, source?, market?} (source/market: plugin only)
|
||||
DELETE /api/artifacts/:id
|
||||
GET /api/artifacts/:id/raw?path=&download=1 one snapshot file (sandbox CSP, nosniff)
|
||||
POST /api/artifacts/:id/install {replace?} → {installed, replaced?}
|
||||
```
|
||||
|
||||
What agents produced, per OWNER (`server/lib/artifacts.js`, plan: `docs/plans/artifacts/README.md`):
|
||||
|
||||
- **page** — a claude.ai link (`https://claude.ai/…` only, `400 EBADURL`), one row per owner and link. A session's `Artifact` tool publish is captured from its PostToolUse hook (the first `https://claude.ai/…artifact/…` in `tool_response`), owned by the session's workspace owner.
|
||||
- **file** — `candidates` are the documents (html, md, pdf, images, csv, office…) the workspace's sessions wrote with Write/Edit/MultiEdit/NotebookEdit, inside its folder. A pin is read under the download route's guards (`lanePath`, `resolveInLane`, `ESECRET`, ≤ 25 MB, `413 ETOOBIG`) and SNAPSHOTTED to `<data dir>/artifacts/<random>/`.
|
||||
- **skill** — the caller's own `~/.claude/skills/<name>` (their member home under S3; the host's for an admin or in local mode, else `409 ENOACCOUNT`) or a workspace's `.claude/skills/<name>`. Snapshotted whole: ≤ 300 files, ≤ 5 MB, a symlink anywhere is `ESYMLINK`, a secret-looking file name (`.env`, `*.pem`, `*token*`…) `403 ESECRET`.
|
||||
- **file upload** — one file from the user's computer (≤ 25 MB, `413 ETOOBIG`), snapshotted under its own base name (no folder kept).
|
||||
- **skill upload / new** — a skill made from files rather than picked: one Markdown/text file of any name becomes `SKILL.md`; several files or a picked/dropped folder (`paths` keeps the layout) need a `SKILL.md` (at the top or in one folder, which is stripped — `400 ENOSKILLMD` otherwise); a single `.zip`/`.skill` is unpacked (sizes checked from its directory first, a symlink entry `ESYMLINK`, `__MACOSX`/`.DS_Store`/`.git`/`node_modules` skipped); an upload holding several skill folders makes one artifact per skill, named by its folder, and stores NOTHING if any of them fails. The `name` the user typed (only for a single skill; else the frontmatter `name:`, the folder or the file name) is made a folder name (`skillSlug`: marks dropped, other characters → `-`; `400 EBADNAME` if nothing is left) and written into `SKILL.md`'s frontmatter as `name:`; a `description` given replaces the frontmatter's, and a skill with none anywhere is `400 ENODESCRIPTION`. Paths are relative with no `..` (`EBADPATH`); the same limits and `ESECRET` as a picked skill. `new` writes `SKILL.md` from `content` the same way.
|
||||
- **plugin** — only the spec and its marketplace source (`EBADPLUGIN`, `EBADMARKET`: `owner/repo`, a `validateRemoteUrl` URL, or an https link to a `marketplace.json`); no files. A GitHub web link becomes `owner/repo`, and a forge's `…/src/…`, `…/tree/…`, `…/blob/…` suffix or trailing slash is trimmed. The same `key` added again by its owner updates that row. **inspect** reads the marketplace's `.claude-plugin/marketplace.json` to list its plugins: a git link is cloned shallow, blob-less and without checkout into a temp dir that is removed after, with every credential helper switched off and no prompt (a repository that needs a login is `502 ENEEDLOGIN`; type the key by hand — installing then uses each user's own git login), https only (an ssh link is `400 ESSHMARKET`); a repo with only a `plugin.json` is `400 ENOTMARKET`; unreachable `502 EMARKETFETCH`. It reaches any https host a signed-in user names, like `publish` does — no login is ever sent with it.
|
||||
- **Visibility** — local mode: every row, no sharing (`400 ELOCALMODE`). Server mode: a developer sees their own rows and shared ones, admin/analyst every row; only the owner or an admin changes or deletes one (`403 EFORBIDDEN`). `shared` puts a row in every user's **Hub**.
|
||||
- **raw** — only a file the snapshot recorded (`404 ENOFILE` otherwise), never a request path; served with `Content-Security-Policy: …; sandbox` and `nosniff`, unknown types as an attachment.
|
||||
- **install** — a skill or plugin (`EBADKIND`), into the CALLER's own account: a skill is written to `~/.claude/skills/<name>/` (as the member through `write-as` under S3); a taken name is `409 EEXISTS` unless `replace: true`, which moves the old one to `~/.claude/agenthub-replaced-skills/<name>-<time>/`. A plugin runs `claude plugin marketplace add <market>` then `claude plugin install --scope user <key>` as the caller, never with `-y`. `403 EINSTALLSOFF` while an admin has turned installs off. Share, unshare, a shared row's delete and every install by someone else are written to `audit_log`.
|
||||
- Every write is same-origin. The `artifact_changed` broadcast (`{id, ownerId, shared}`) reaches everyone for a shared row, else its owner and staff.
|
||||
|
||||
### Query Explorer
|
||||
|
||||
The dashboard's Sessions page reads its **Agents** tab (`/sessions?view=agents`; the old `/query` page redirects there) from `entity=agents`; sessions and events have their own tabs over `GET /api/sessions` and `GET /api/events`. The route still answers all three entities for scripts and exports.
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ The CLI talks to the local dashboard server — **API-backed commands require it
|
||||
| `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 |
|
||||
| `agenthub accounts list\|add <name>\|remove <name>` | The **Claude account pool**: new Claude sessions spread over these accounts (each a `claude setup-token` token, typed hidden or read from stdin). `list` shows live panes, $ in the last 5 h / 7 d, and quota. With `--tool codex` the same for the **Codex account pool**: `add <name> --tool codex --api-key` (key typed hidden or on stdin) or `--from <dir>` (a `codex login` home or its `auth.json`). See [SERVER-MODE.md](SERVER-MODE.md#claude-account-pool) |
|
||||
| `agenthub accounts list\|add <name>\|remove <name>` | The **Claude account pool**: new Claude sessions spread over these accounts (each a `claude setup-token` token, typed hidden or read from stdin). `list` shows live panes, $ and tokens in the last 5 h / 7 d, and quota. With `--tool codex` the same for the **Codex account pool**: `add <name> --tool codex --api-key` (key typed hidden or on stdin) or `--from <dir>` (a `codex login` home or its `auth.json`). See [SERVER-MODE.md](SERVER-MODE.md#claude-account-pool) |
|
||||
| `agenthub users list\|add <name> [--role admin\|analyst\|member]\|passwd <name>\|role <name> <role>\|disable <name>\|enable <name>\|provision <name>\|--all\|assign <workspace id> <name>\|audit [--limit N]` | Server mode's accounts, written straight to the database. Once `install-system` ran, `add` first creates the Linux user `ah-<name>`; a name must then be lower case: a letter, then up to 28 letters, digits, `_` or `-`. `disable`/`enable` lock or unlock that Linux user too, and `provision` gives users made earlier their Linux user (idempotent); `assign` gives a workspace made before server mode an owner; `audit` lists admin/analyst reads of members' sessions. Inside a dashboard pane in server mode, every command acts as the workspace's owner through the pane's `AGENTHUB_PANE_TOKEN`. A password is typed hidden twice, or read from the first line of stdin |
|
||||
|
||||
### Interactive REPL
|
||||
|
||||
+10
-6
File diff suppressed because one or more lines are too long
+43
-7
@@ -115,7 +115,7 @@ their own workspaces (`useWorkLanes`); other users' work is read on Sessions,
|
||||
Analytics and Users, where Resume, Fork, Snapshot and "Open in workspace" are
|
||||
hidden for a session that is not theirs. The sidebar's workspace list shows an
|
||||
admin or analyst EVERY workspace, grouped under its owner (each lane carries
|
||||
`owner_name` and `owner_display_name`; the group shows the display name when
|
||||
`owner_name`, `owner_display_name` and `owner_avatar_at`; the group shows the owner's picture (`GET /api/users/:id/avatar`) and the display name when
|
||||
the owner set one, else the username; yours first, no owner last, each group folds): for an analyst
|
||||
another user's workspace there is read only — no menu, rename or new session,
|
||||
no live tabs, and a session opens its analysis page (`/sessions/<id>`). An analyst's alert feed
|
||||
@@ -144,6 +144,17 @@ Workspaces made before server mode, or by the host account, have none.
|
||||
- `GET /api/users` (admin/analyst) lists every account with its workspaces,
|
||||
sessions, and the tokens and $ it used in the last 7 and 30 days — the
|
||||
Users page in the sidebar shows it, with the audit log under it.
|
||||
- `GET /api/users/storage` (admin/analyst) is the page's **Storage** column:
|
||||
how much disk each user's home takes (their Linux home under S3, their
|
||||
folder under `AGENTHUB_USERS_ROOT` otherwise; an admin with none reads
|
||||
`null`). Homes are walked in a worker thread, one at a time, `du -x`-like
|
||||
(allocated blocks, `lstat` only, no symlink followed, a hard link once),
|
||||
and cached for 15 minutes; the answer comes back at once with
|
||||
`{storage: {<userId>: {bytes, files, partial, measuredAt} | null}, measuring}`
|
||||
and the page asks again while `measuring`. `?refresh=1` (the page's Refresh)
|
||||
re-measures. A walk over `AGENTHUB_STORAGE_TIMEOUT_MS` (default 120 s) or
|
||||
one meeting an unreadable folder is a lower bound, `partial: true` (shown
|
||||
as `≥`).
|
||||
|
||||
A developer also cannot open the host's own configuration, or any view across all
|
||||
users: Claude Code / Codex config (except the command and skill lists the
|
||||
@@ -283,8 +294,10 @@ workspace runs as the host account that every admin shares. The tick is never
|
||||
remembered, so the default is always the admin's own account.
|
||||
|
||||
Every signed-in user has **Settings → Account**: their username, role, member
|
||||
since, workspace and session counts and active logins; their own display name
|
||||
and email; **Change password** (the current password is required, the login
|
||||
since, workspace and session counts and active logins; their own picture
|
||||
(PNG, JPEG, GIF or WebP up to 1 MB, kept in `<data dir>/avatars/`; shown with
|
||||
their name and role at the foot of the sidebar, which opens this page); their
|
||||
own display name and email; **Change password** (the current password is required, the login
|
||||
it is changed from stays and every other one ends); and **Sign out other
|
||||
devices**. These are taken from the login cookie only — an agent in a pane,
|
||||
which acts as its workspace owner through its pane token, cannot change its
|
||||
@@ -316,7 +329,7 @@ stays empty (changing nothing) until you add an account.
|
||||
claude setup-token
|
||||
# Add it to the pool (the token is typed hidden, or piped on stdin)
|
||||
agenthub accounts add team-1
|
||||
agenthub accounts list # live panes, $ in the last 5 h / 7 d, quota, state
|
||||
agenthub accounts list # live panes, $ and tokens in the last 5 h / 7 d, quota, state
|
||||
agenthub accounts remove team-1
|
||||
```
|
||||
|
||||
@@ -345,7 +358,10 @@ Code reads it from no env var, so before a member's pane starts, AgentHub writes
|
||||
it as that member's `~/.claude/.credentials.json`, as the member (0600). It is
|
||||
never written into a host pane's home, never over a login the member made
|
||||
themselves, and never a second account into a home where a pane of theirs runs
|
||||
on one. Host panes therefore get only setup-token accounts. The refresh token of
|
||||
on one. Host panes therefore get only setup-token accounts — and the login the
|
||||
host itself was moved in from (the profile marked active), as long as the
|
||||
host's `~/.claude/.credentials.json` still holds that pair: the pane runs on it
|
||||
as it is and its usage is booked to that account. The refresh token of
|
||||
a login is single use, so the server is the one that refreshes it, before it
|
||||
expires (`claude-pool.refreshLogins`, checked every 60 s; `DASHBOARD_POOL_REFRESH_MS=0` turns it off). It then writes the new pair into every
|
||||
home it placed the login in, and Claude Code picks up tokens another process
|
||||
@@ -363,8 +379,13 @@ How a new session picks its account (`server/lib/claude-pool.js`):
|
||||
weekly window goes last. It is still used if every account is that full.
|
||||
2. Next, the account with the fewest live panes, so concurrent sessions spread out.
|
||||
3. Then the account with the least $ spent in the last 5 hours, then the last
|
||||
7 days. AgentHub sums this from the usage of the sessions it started on each
|
||||
account (`dashboard_runs.account`).
|
||||
7 days. AgentHub sums this from the usage of the sessions its runs held on
|
||||
each account (`dashboard_runs.account`), over the hours each run held them —
|
||||
a session resumed on another account counts there from then on — with
|
||||
sub-agent usage included and the same prices as the cost pages
|
||||
(`server/lib/pool-usage.js`). The table also shows the tokens behind it.
|
||||
Sessions started outside AgentHub on the same account are not counted; the
|
||||
quota column is Anthropic's own reading and does include them.
|
||||
|
||||
- The pane gets the token through tmux `-e CLAUDE_CODE_OAUTH_TOKEN=…`. That
|
||||
token outranks the machine's own `/login` for that process only.
|
||||
@@ -726,6 +747,21 @@ sudo agenthub server install-system
|
||||
|
||||
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
|
||||
**Delete user**: until then a delete answers `502 EPROVISION` ("unknown
|
||||
action: delete") and changes nothing.
|
||||
|
||||
### Deleting a user
|
||||
|
||||
Users page → Edit → **Delete user** (the admin's own password, then a red
|
||||
confirm). Order: the user's logins end and their workspaces' panes stop;
|
||||
under S3 `agenthub-provision delete <name>` locks `ah-<name>`, kills its
|
||||
processes, `userdel`s it and removes `<USERS_ROOT>/<name>` (a real
|
||||
directory exactly there — never a link — `rm -rf --one-file-system`); only
|
||||
then are the rows removed (the user, their workspaces' records, prefs, push
|
||||
subscriptions, personal AI Proxy profiles). Session history and the audit log
|
||||
stay. Never yourself (`ESELF`) or the last admin (`ELASTADMIN`). A user made
|
||||
again under the same name gets a NEW, empty Linux account and home.
|
||||
|
||||
### What a new machine needs before `install-system`
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# Artifacts hub — plan
|
||||
|
||||
_Drafted 2026-10-14. Status: all three phases built 2026-10-14 (the session view's own Artifacts tab is not built; the page has the per-workspace file picker)._
|
||||
|
||||
## Goal
|
||||
|
||||
One place to keep what agents PRODUCE, and (in server mode) to share it:
|
||||
|
||||
| Kind | What it is | Where it comes from |
|
||||
|---|---|---|
|
||||
| `page` | A claude.ai Artifact a session published (`claude.ai/…/artifact/…`) | the `Artifact` tool's PostToolUse hook, or a link pasted by hand |
|
||||
| `file` | A file an agent wrote (HTML, Markdown, PDF, image, CSV, Office…) | Write/Edit/NotebookEdit hook events, kept on the user's pin; or uploaded from the computer |
|
||||
| `skill` | A Claude Code skill folder (`SKILL.md` + files) | the user's own `~/.claude/skills/<name>` or a workspace's `.claude/skills/<name>`; or uploaded (a Markdown file, files, a folder, a .zip/.skill — several skills at once too) or written in the dialog, under a name the user chooses |
|
||||
| `plugin` | A plugin by marketplace source + name (no files) | picked from the list a marketplace link answers (`POST /api/artifacts/plugin/inspect`), or typed as `name@marketplace` |
|
||||
|
||||
- **Local mode:** one personal library, no sharing UI.
|
||||
- **Server mode:** every artifact is the OWNER's and private by default. The owner can **Share** it; a shared artifact appears in the **Hub** for every signed-in user. A shared skill or plugin can be **installed** into the viewer's own account.
|
||||
|
||||
## Rules (binding, same spirit as CLAUDE.md)
|
||||
|
||||
- **What is shared is a SNAPSHOT, never the owner's live file.** Sharing a `file`/`skill` copies it (size-capped, regular files only, no symlinks followed) into `<data dir>/artifacts/<id>/`, written once like `session_snapshots`. Viewers read only that copy, so no route ever reads another user's home for them. Re-sharing makes a new snapshot.
|
||||
- **Nothing shared runs on the dashboard's origin.** HTML/SVG previews are served under the `/git/raw` headers (`sandbox` CSP + `nosniff`) and shown in a sandboxed iframe; a `page` is only a link out, accepted only as `https://claude.ai/…`.
|
||||
- **Installing is the viewer's explicit click, into the viewer's own account only.** For a skill, the hub writes the snapshot's files into `~/.claude/skills/<name>/` of the VIEWER (S3: as their member, through `write-as`). It never overwrites an existing skill without `conflict: replace`, and the old one goes to the trash first. For a plugin, the hub runs `claude plugin marketplace add <source>` + `claude plugin install <name>@<market> --scope user` as the viewer (the `applyPluginBaseline` path). The marketplace source passes an allowlist (`owner/repo` or a `validateRemoteUrl` URL), and no argv comes from the request beyond those two validated values.
|
||||
- **Before installing, the dialog lists every file of the skill** (a skill may carry scripts that the viewer's agent will run). Every share, unshare and install is written to `audit_log`.
|
||||
- **Visibility follows ownership:** a developer sees their own artifacts plus shared ones; admin/analyst see per `scope.js`, like sessions. Unshare removes an artifact from the Hub but does not uninstall copies others already installed.
|
||||
|
||||
## Data
|
||||
|
||||
New table `artifacts` (`CREATE TABLE IF NOT EXISTS` in `server/db.js`):
|
||||
|
||||
`id, kind, title, description, owner_id, lane_id, session_id, source (path | url | market spec), url, snapshot (dir name | NULL), size, shared (0/1), shared_at, installs, created_at, updated_at`, plus an index on `(owner_id, kind)` and on `(shared, kind)`.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **Library (local + server, private).** Table, `server/lib/artifacts.js`, `/api/artifacts` (list/get/create/patch/delete). `page` rows are captured from the `Artifact` PostToolUse hook (URL taken from `tool_response` by an `https://claude.ai/…artifact/…` match). `file` candidates are listed per workspace from Write events with a document extension, and the user pins them. New **Artifacts** page (sidebar) plus an **Artifacts** tab in the session view's right panel. Scope wiring: `PATH_RULES`, `broadcastAudience`.
|
||||
2. **Hub (server mode).** Share/Unshare buttons, snapshot, `Hub` tab, sandboxed preview, download, `artifact_shared` broadcast.
|
||||
3. **Skills & plugins.** "Share a skill/plugin" picker, the install flow (S3 included), conflict handling, audit.
|
||||
|
||||
Each phase ships with its server and client tests and an update to `docs/API.md`.
|
||||
|
||||
## Open questions
|
||||
|
||||
- No `Artifact` tool call has happened on this machine yet, so the exact hook payload of a publish is unverified. Phase 1 matches the URL loosely and keeps "paste a link" as the fallback.
|
||||
- Should an admin be able to disable Hub installs for everyone (one switch in Settings)? Proposed: yes, on by default.
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.7.7",
|
||||
"version": "2.8.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "agenthub",
|
||||
"version": "2.7.7",
|
||||
"version": "2.8.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.7.7",
|
||||
"version": "2.8.0",
|
||||
"bin": {
|
||||
"agenthub": "bin/agenthub.js"
|
||||
},
|
||||
|
||||
@@ -7,11 +7,16 @@
|
||||
# agenthub-provision create <name> Linux user ah-<name>, home <USERS_ROOT>/<name>
|
||||
# agenthub-provision disable <name> lock the account and end its processes
|
||||
# agenthub-provision enable <name> unlock it
|
||||
# agenthub-provision delete <name> end its processes, remove the account
|
||||
# and its home <USERS_ROOT>/<name>
|
||||
#
|
||||
# Nothing but an action and a name comes from the caller; every path comes
|
||||
# from /etc/agenthub/server.conf (root's). It never deletes an account or a
|
||||
# home, never touches an account that is not an AgentHub member (one that
|
||||
# already exists outside group agenthub-members is refused), and never
|
||||
# from /etc/agenthub/server.conf (root's). It deletes only on `delete` (an
|
||||
# admin's step-up-confirmed "Delete user" on the Users page): only an AgentHub
|
||||
# member's account, and only the home at exactly <USERS_ROOT>/<name> — a real
|
||||
# directory, never a link, removed without following links or leaving its
|
||||
# filesystem. It never touches an account that is not an AgentHub member (one
|
||||
# that already exists outside group agenthub-members is refused), and never
|
||||
# grants a member sudo.
|
||||
# @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
set -euo pipefail
|
||||
@@ -20,7 +25,7 @@ cd / # runuser keeps the cwd: one every account may enter
|
||||
|
||||
die() { echo "agenthub-provision: $*" >&2; exit "${2:-1}"; }
|
||||
[ "$(id -u)" = 0 ] || die "must run as root (through sudo)"
|
||||
[ $# -eq 2 ] || die "usage: agenthub-provision create|disable|enable <name>" 2
|
||||
[ $# -eq 2 ] || die "usage: agenthub-provision create|disable|enable|delete <name>" 2
|
||||
|
||||
CONF=/etc/agenthub/server.conf
|
||||
[ -f "$CONF" ] || die "$CONF is missing — run agenthub server install-system first"
|
||||
@@ -84,5 +89,30 @@ case "$ACTION" in
|
||||
usermod --unlock "$LOGIN" >/dev/null 2>&1 || true
|
||||
echo "enabled $LOGIN"
|
||||
;;
|
||||
delete)
|
||||
if id "$LOGIN" >/dev/null 2>&1; then
|
||||
is_member || die "$LOGIN is not an AgentHub member — refusing to delete it" 4
|
||||
# Locked first, so nothing new starts while its processes are ended.
|
||||
usermod --lock --expiredate 1 "$LOGIN"
|
||||
for _ in 1 2 3; do
|
||||
pkill -KILL -u "$LOGIN" 2>/dev/null || true
|
||||
pgrep -u "$LOGIN" >/dev/null 2>&1 || break
|
||||
sleep 1
|
||||
done
|
||||
userdel "$LOGIN"
|
||||
# Its own user group, if userdel left it and nobody else is in it.
|
||||
if getent group "$LOGIN" >/dev/null 2>&1; then groupdel "$LOGIN" 2>/dev/null || true; fi
|
||||
fi
|
||||
if [ -e "$HOME_DIR" ] || [ -L "$HOME_DIR" ]; then
|
||||
# Exactly <USERS_ROOT>/<name>: a real directory sitting directly in the
|
||||
# (root-owned) users root — never a link a member planted elsewhere.
|
||||
[ -d "$HOME_DIR" ] && [ ! -L "$HOME_DIR" ] || die "$HOME_DIR is not a plain directory" 5
|
||||
ROOT_REAL=$(realpath -e "$USERS_ROOT")
|
||||
[ "$(realpath -e "$HOME_DIR")" = "$ROOT_REAL/$NAME" ] || die "$HOME_DIR resolves elsewhere" 5
|
||||
# rm never follows a link it removes; --one-file-system stays on this disk.
|
||||
rm -rf --one-file-system -- "$HOME_DIR"
|
||||
fi
|
||||
echo "deleted $LOGIN $HOME_DIR"
|
||||
;;
|
||||
*) die "unknown action: $ACTION" 2 ;;
|
||||
esac
|
||||
|
||||
@@ -3186,6 +3186,48 @@ describe("GET /api/sessions/:id/file", () => {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
assert.equal((await fetch(url(report))).status, 404);
|
||||
});
|
||||
|
||||
it("serves a file the session's Bash or reply named as a whole path (issue #76)", async () => {
|
||||
const sid = "named-file-" + Date.now();
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ah-named-file-"));
|
||||
const report = path.join(dir, "REPORT_ssh_ec2.md");
|
||||
const out = path.join(dir, "out.txt");
|
||||
const chart = path.join(dir, "chart.png");
|
||||
const stem = path.join(dir, "REPORT");
|
||||
const unread = path.join(dir, "locked.md");
|
||||
fs.writeFileSync(report, "# Audit");
|
||||
fs.writeFileSync(out, "generated");
|
||||
fs.writeFileSync(chart, "PNGBYTES");
|
||||
fs.writeFileSync(stem, "stem");
|
||||
fs.writeFileSync(unread, "locked");
|
||||
fs.chmodSync(unread, 0o000);
|
||||
await post("/api/hooks/event", { hook_type: "SessionStart", data: { session_id: sid } });
|
||||
await post("/api/hooks/event", {
|
||||
hook_type: "PostToolUse",
|
||||
data: {
|
||||
session_id: sid,
|
||||
tool_name: "Bash",
|
||||
tool_input: { command: `python gen.py -o ${out} && plot ${chart} ${unread}` },
|
||||
tool_response: { stdout: "done", stderr: "" },
|
||||
},
|
||||
});
|
||||
await post("/api/hooks/event", {
|
||||
hook_type: "Stop",
|
||||
data: { session_id: sid, last_assistant_message: `Báo cáo: \`${report}\`.` },
|
||||
});
|
||||
const url = (p) => `/api/sessions/${sid}/file?path=${encodeURIComponent(p)}`;
|
||||
|
||||
assert.deepEqual((await fetch(url(report))).body, { text: "# Audit", truncated: false });
|
||||
assert.deepEqual((await fetch(url(out))).body, { text: "generated", truncated: false });
|
||||
const img = await fetch(`/api/sessions/${sid}/image?path=${encodeURIComponent(chart)}`);
|
||||
assert.equal(img.status, 200);
|
||||
// Only a WHOLE path: `<dir>/REPORT` is a prefix of the named report, not named itself.
|
||||
assert.equal((await fetch(url(stem))).status, 404);
|
||||
// Named, but its account could not read it (root sees through the mode).
|
||||
if (process.getuid?.() !== 0) assert.equal((await fetch(url(unread))).status, 404);
|
||||
fs.chmodSync(unread, 0o600);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/sessions/:id/image", () => {
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* @file Tests for the Artifacts hub (server/lib/artifacts.js, routes/artifacts.js):
|
||||
* claude.ai pages (link allowlist, hook capture, one row per URL), workspace
|
||||
* file candidates and pins (a snapshot, served sandboxed), skills (snapshot,
|
||||
* symlink/secret refusal, install into the caller's Claude home with
|
||||
* replace moving the old one aside), plugins (marketplace allowlist, install
|
||||
* argv; a marketplace link read into its plugin list, the same plugin added
|
||||
* twice kept as one row, key/market edited), skills uploaded (one Markdown
|
||||
* file, a folder, a zip, several skills at once — name and frontmatter set,
|
||||
* junk skipped, nothing stored when one fails) or written in the dialog, a
|
||||
* file uploaded, sharing refused in local mode, visibility for a server-mode
|
||||
* developer, the admin's installs switch, and same-origin writes.
|
||||
* @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 fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const http = require("node:http");
|
||||
|
||||
const ROOT = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "artifacts-")));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(ROOT, "t.db");
|
||||
process.env.CLAUDE_HOME = path.join(ROOT, "claude");
|
||||
process.env.DASHBOARD_DATA_DIR = path.join(ROOT, "data");
|
||||
process.env.DASHBOARD_REMOTE_SYNC_MS = "0";
|
||||
process.env.DASHBOARD_LIVENESS_PROBE = "0";
|
||||
|
||||
const { createApp } = require("../index");
|
||||
const { db } = require("../db");
|
||||
const lanesLib = require("../lib/lanes");
|
||||
const artifacts = require("../lib/artifacts");
|
||||
|
||||
const ws = path.join(ROOT, "ws");
|
||||
let lane;
|
||||
let server;
|
||||
let base;
|
||||
|
||||
function request(method, p, body, headers = {}) {
|
||||
return fetch(`${base}${p}`, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json", ...headers },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
}).then(async (r) => ({
|
||||
status: r.status,
|
||||
headers: r.headers,
|
||||
text: await r.text(),
|
||||
})).then((r) => {
|
||||
let json = null;
|
||||
try {
|
||||
json = JSON.parse(r.text);
|
||||
} catch {
|
||||
/* not JSON */
|
||||
}
|
||||
return { ...r, body: json };
|
||||
});
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
fs.mkdirSync(path.join(ws, "out"), { recursive: true });
|
||||
fs.writeFileSync(path.join(ws, "out", "report.html"), "<h1>hi</h1><script>x()</script>");
|
||||
fs.writeFileSync(path.join(ws, "main.js"), "code");
|
||||
const skill = path.join(ws, ".claude", "skills", "deploy");
|
||||
fs.mkdirSync(path.join(skill, "scripts"), { recursive: true });
|
||||
fs.writeFileSync(path.join(skill, "SKILL.md"), "---\nname: deploy\ndescription: Ship it\n---\nDo it.\n");
|
||||
fs.writeFileSync(path.join(skill, "scripts", "run.sh"), "echo hi\n");
|
||||
fs.mkdirSync(process.env.CLAUDE_HOME, { recursive: true });
|
||||
lane = lanesLib.createLane({ cwd: ws, title: "ws" });
|
||||
db.prepare("INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('s1', 's1', 'active', ?, ?)").run(
|
||||
ws,
|
||||
lane.id
|
||||
);
|
||||
const ev = db.prepare(
|
||||
"INSERT INTO events (session_id, event_type, tool_name, data) VALUES ('s1', 'PostToolUse', ?, ?)"
|
||||
);
|
||||
ev.run("Write", JSON.stringify({ tool_input: { file_path: path.join(ws, "out", "report.html") } }));
|
||||
ev.run("Edit", JSON.stringify({ tool_input: { file_path: path.join(ws, "main.js") } }));
|
||||
ev.run("Write", JSON.stringify({ tool_input: { file_path: "/etc/passwd.md" } }));
|
||||
server = http.createServer(createApp());
|
||||
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
||||
base = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
after(async () => {
|
||||
await new Promise((r) => server.close(r));
|
||||
fs.rmSync(ROOT, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("pages", () => {
|
||||
it("accepts only a claude.ai link, and keeps one row per link", async () => {
|
||||
for (const url of ["http://claude.ai/x", "https://evil.example/claude.ai/", "javascript:x"]) {
|
||||
const r = await request("POST", "/api/artifacts/page", { url });
|
||||
assert.equal(r.status, 400, url);
|
||||
assert.equal(r.body.error.code, "EBADURL");
|
||||
}
|
||||
const url = "https://claude.ai/code/artifact/abc-123";
|
||||
const a = await request("POST", "/api/artifacts/page", { url, title: "One" });
|
||||
assert.equal(a.status, 201);
|
||||
const b = await request("POST", "/api/artifacts/page", { url, title: "Two" });
|
||||
assert.equal(b.body.item.id, a.body.item.id);
|
||||
assert.equal(b.body.item.title, "Two");
|
||||
});
|
||||
|
||||
it("captures a publish from the Artifact tool's hook, owned by the session's workspace", () => {
|
||||
const row = artifacts.captureFromHook("s1", {
|
||||
tool_input: { action: "publish", file_path: "/x/plan.html" },
|
||||
tool_response: "Published: https://claude.ai/artifact/zz9-Q\nWatching it.",
|
||||
});
|
||||
assert.equal(row.url, "https://claude.ai/artifact/zz9-Q");
|
||||
assert.equal(row.title, "plan.html");
|
||||
assert.equal(row.lane_id, lane.id);
|
||||
assert.equal(artifacts.captureFromHook("s1", { tool_input: { action: "read" } }), null);
|
||||
assert.equal(artifacts.captureFromHook("s1", { tool_response: "no link" }), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("files", () => {
|
||||
it("lists only documents a session wrote inside the workspace", async () => {
|
||||
const r = await request("GET", `/api/artifacts/candidates?laneId=${lane.id}`);
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(
|
||||
r.body.items.map((i) => i.path),
|
||||
["out/report.html"]
|
||||
);
|
||||
});
|
||||
|
||||
it("pins a snapshot and serves it sandboxed, never a path outside it", async () => {
|
||||
const r = await request("POST", "/api/artifacts/file", { laneId: lane.id, path: "out/report.html" });
|
||||
assert.equal(r.status, 201, r.text);
|
||||
const id = r.body.item.id;
|
||||
// The live file changes; the artifact does not.
|
||||
fs.writeFileSync(path.join(ws, "out", "report.html"), "changed");
|
||||
const raw = await request("GET", `/api/artifacts/${id}/raw`);
|
||||
assert.equal(raw.status, 200);
|
||||
assert.match(raw.text, /<h1>hi<\/h1>/);
|
||||
assert.match(raw.headers.get("content-security-policy"), /sandbox/);
|
||||
assert.equal(raw.headers.get("x-content-type-options"), "nosniff");
|
||||
const other = await request("GET", `/api/artifacts/${id}/raw?path=../../t.db`);
|
||||
assert.equal(other.status, 404);
|
||||
|
||||
const escape = await request("POST", "/api/artifacts/file", { laneId: lane.id, path: "../t.db" });
|
||||
assert.equal(escape.status, 400);
|
||||
|
||||
const del = await request("DELETE", `/api/artifacts/${id}`);
|
||||
assert.equal(del.status, 200);
|
||||
assert.equal((await request("GET", `/api/artifacts/${id}`)).status, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("skills", () => {
|
||||
it("snapshots a workspace skill and installs it into the caller's Claude home", async () => {
|
||||
const list = await request("GET", `/api/artifacts/skills?laneId=${lane.id}`);
|
||||
assert.deepEqual(list.body.items, [{ name: "deploy", from: "workspace" }]);
|
||||
const r = await request("POST", "/api/artifacts/skill", { laneId: lane.id, name: "deploy" });
|
||||
assert.equal(r.status, 201, r.text);
|
||||
assert.equal(r.body.item.description, "Ship it");
|
||||
assert.deepEqual(
|
||||
r.body.item.files.map((f) => f.path).sort(),
|
||||
["SKILL.md", "scripts/run.sh"]
|
||||
);
|
||||
const id = r.body.item.id;
|
||||
|
||||
const first = await request("POST", `/api/artifacts/${id}/install`, {});
|
||||
assert.equal(first.status, 200, first.text);
|
||||
const target = path.join(process.env.CLAUDE_HOME, "skills", "deploy");
|
||||
assert.equal(fs.readFileSync(path.join(target, "scripts", "run.sh"), "utf8"), "echo hi\n");
|
||||
|
||||
const again = await request("POST", `/api/artifacts/${id}/install`, {});
|
||||
assert.equal(again.status, 409);
|
||||
assert.equal(again.body.error.code, "EEXISTS");
|
||||
fs.writeFileSync(path.join(target, "mine.txt"), "keep me");
|
||||
const replaced = await request("POST", `/api/artifacts/${id}/install`, { replace: true });
|
||||
assert.equal(replaced.status, 200, replaced.text);
|
||||
assert.ok(!fs.existsSync(path.join(target, "mine.txt")));
|
||||
const aside = path.join(process.env.CLAUDE_HOME, "agenthub-replaced-skills");
|
||||
const [old] = fs.readdirSync(aside);
|
||||
assert.equal(fs.readFileSync(path.join(aside, old, "mine.txt"), "utf8"), "keep me");
|
||||
});
|
||||
|
||||
it("refuses a skill holding a symlink or a secret-looking file", async () => {
|
||||
const bad = path.join(ws, ".claude", "skills", "leaky");
|
||||
fs.mkdirSync(bad, { recursive: true });
|
||||
fs.writeFileSync(path.join(bad, "SKILL.md"), "x");
|
||||
fs.symlinkSync("/etc/passwd", path.join(bad, "link"));
|
||||
const r = await request("POST", "/api/artifacts/skill", { laneId: lane.id, name: "leaky" });
|
||||
assert.equal(r.body.error.code, "ESYMLINK");
|
||||
fs.unlinkSync(path.join(bad, "link"));
|
||||
fs.writeFileSync(path.join(bad, ".env"), "KEY=1");
|
||||
const s = await request("POST", "/api/artifacts/skill", { laneId: lane.id, name: "leaky" });
|
||||
assert.equal(s.body.error.code, "ESECRET");
|
||||
});
|
||||
|
||||
it("is not installed while an admin has turned installs off", async () => {
|
||||
const item = (await request("GET", "/api/artifacts?kind=skill")).body.items[0];
|
||||
const off = await request("PUT", "/api/artifacts/settings", { installsEnabled: false });
|
||||
assert.equal(off.body.installsEnabled, false);
|
||||
const r = await request("POST", `/api/artifacts/${item.id}/install`, { replace: true });
|
||||
assert.equal(r.status, 403);
|
||||
assert.equal(r.body.error.code, "EINSTALLSOFF");
|
||||
await request("PUT", "/api/artifacts/settings", { installsEnabled: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugins", () => {
|
||||
it("takes only name@marketplace from owner/repo or a remote URL, and installs without -y", async () => {
|
||||
const bad = await request("POST", "/api/artifacts/plugin", { key: "x@y", market: "/etc" });
|
||||
assert.equal(bad.body.error.code, "EBADMARKET");
|
||||
const dash = await request("POST", "/api/artifacts/plugin", { key: "-x@y", market: "o/r" });
|
||||
assert.equal(dash.body.error.code, "EBADPLUGIN");
|
||||
const r = await request("POST", "/api/artifacts/plugin", { key: "tool@market", market: "o/r" });
|
||||
assert.equal(r.status, 201, r.text);
|
||||
const calls = [];
|
||||
artifacts.__setExecImpl(async (cmd, args) => {
|
||||
calls.push([cmd, ...args]);
|
||||
return { stdout: "" };
|
||||
});
|
||||
const inst = await request("POST", `/api/artifacts/${r.body.item.id}/install`, {});
|
||||
assert.equal(inst.status, 200, inst.text);
|
||||
assert.deepEqual(calls, [
|
||||
["claude", "plugin", "marketplace", "add", "o/r"],
|
||||
["claude", "plugin", "install", "--scope", "user", "tool@market"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
function upload(p, files, fields = {}) {
|
||||
const form = new FormData();
|
||||
const paths = [];
|
||||
for (const [name, content] of files) {
|
||||
form.append("files", new Blob([content]), name.split("/").pop());
|
||||
paths.push(name);
|
||||
}
|
||||
form.append("paths", JSON.stringify(paths));
|
||||
for (const [k, v] of Object.entries(fields)) form.append(k, v);
|
||||
return fetch(`${base}${p}`, { method: "POST", body: form }).then(async (r) => ({
|
||||
status: r.status,
|
||||
body: await r.json(),
|
||||
}));
|
||||
}
|
||||
|
||||
const snapText = (item, file = "SKILL.md") =>
|
||||
fs.readFileSync(
|
||||
path.join(process.env.DASHBOARD_DATA_DIR, "artifacts", db.prepare("SELECT snapshot FROM artifacts WHERE id = ?").get(item.id).snapshot, file),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
describe("plugins from a marketplace link", () => {
|
||||
const MARKET = JSON.stringify({
|
||||
name: "sg",
|
||||
description: "Smartgift skills",
|
||||
plugins: [
|
||||
{ name: "sg-dev", source: "./plugins/dev", description: "Dev team" },
|
||||
{ name: "sg-common", source: "./plugins/common" },
|
||||
{ name: "-bad", source: "./x" },
|
||||
],
|
||||
});
|
||||
|
||||
it("normalizes what a user pastes into a marketplace source", () => {
|
||||
const n = artifacts.normalizeMarket;
|
||||
assert.equal(n("https://github.com/o/r"), "o/r");
|
||||
assert.equal(n("https://github.com/o/r.git/"), "o/r");
|
||||
assert.equal(
|
||||
n("https://git.example.vn/Org/skills/src/branch/main/"),
|
||||
"https://git.example.vn/Org/skills"
|
||||
);
|
||||
assert.equal(n("https://git.example.vn/Org/skills.git"), "https://git.example.vn/Org/skills.git");
|
||||
assert.throws(() => n("file:///etc"), { code: "EBADMARKET" });
|
||||
assert.throws(() => n("http://x/y.git"), { code: "EBADMARKET" });
|
||||
});
|
||||
|
||||
it("lists a marketplace's plugins and adds a picked one once", async () => {
|
||||
let asked = null;
|
||||
artifacts.__setInspectImpl(async (m) => {
|
||||
asked = m;
|
||||
return MARKET;
|
||||
});
|
||||
const r = await request("POST", "/api/artifacts/plugin/inspect", {
|
||||
market: "https://git.example.vn/Org/skills.git",
|
||||
});
|
||||
artifacts.__setInspectImpl(null);
|
||||
assert.equal(r.status, 200, r.text);
|
||||
assert.equal(asked, "https://git.example.vn/Org/skills.git");
|
||||
assert.equal(r.body.name, "sg");
|
||||
assert.deepEqual(r.body.plugins.map((p) => p.key), ["sg-dev@sg", "sg-common@sg"]);
|
||||
|
||||
const add = (title) =>
|
||||
request("POST", "/api/artifacts/plugin", { key: "sg-dev@sg", market: r.body.market, title });
|
||||
const a = await add("Dev");
|
||||
const b = await add("Dev team");
|
||||
assert.equal(a.status, 201, a.text);
|
||||
assert.equal(b.body.item.id, a.body.item.id);
|
||||
assert.equal(b.body.item.title, "Dev team");
|
||||
|
||||
const edit = await request("PATCH", `/api/artifacts/${a.body.item.id}`, {
|
||||
source: "sg-common@sg",
|
||||
market: "https://github.com/o/r",
|
||||
});
|
||||
assert.equal(edit.status, 200, edit.text);
|
||||
assert.equal(edit.body.item.source, "sg-common@sg");
|
||||
assert.equal(edit.body.item.market, "o/r");
|
||||
const bad = await request("PATCH", `/api/artifacts/${a.body.item.id}`, { source: "nope" });
|
||||
assert.equal(bad.body.error.code, "EBADPLUGIN");
|
||||
});
|
||||
|
||||
it("refuses a marketplace.json with no usable name", async () => {
|
||||
artifacts.__setInspectImpl(async () => "{}");
|
||||
const r = await request("POST", "/api/artifacts/plugin/inspect", { market: "o/r" });
|
||||
artifacts.__setInspectImpl(null);
|
||||
assert.equal(r.body.error.code, "EBADMARKET");
|
||||
});
|
||||
});
|
||||
|
||||
describe("skills from files or written", () => {
|
||||
it("makes one Markdown file the SKILL.md, named by the user, with a frontmatter", async () => {
|
||||
const r = await upload("/api/artifacts/skill/upload", [["Notes cho đội.md", "# Do this\nStep 1\n"]], {
|
||||
name: "Hướng dẫn deploy",
|
||||
description: "Use when deploying",
|
||||
});
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const [item] = r.body.items;
|
||||
assert.equal(item.source, "Huong-dan-deploy");
|
||||
assert.deepEqual(item.files.map((f) => f.path), ["SKILL.md"]);
|
||||
const text = snapText(item);
|
||||
assert.match(text, /^---\nname: Huong-dan-deploy\ndescription: Use when deploying\n---\n/);
|
||||
assert.match(text, /# Do this/);
|
||||
});
|
||||
|
||||
it("refuses a skill with no description anywhere", async () => {
|
||||
const r = await upload("/api/artifacts/skill/upload", [["x.md", "body"]], { name: "x" });
|
||||
assert.equal(r.body.error.code, "ENODESCRIPTION");
|
||||
});
|
||||
|
||||
it("takes a picked folder: the top folder is stripped, junk skipped, the name from the frontmatter", async () => {
|
||||
const r = await upload("/api/artifacts/skill/upload", [
|
||||
["my-skill/SKILL.md", "---\nname: release-notes\ndescription: Write notes\n---\nGo."],
|
||||
["my-skill/scripts/run.sh", "echo"],
|
||||
["my-skill/.DS_Store", "junk"],
|
||||
]);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const [item] = r.body.items;
|
||||
assert.equal(item.source, "release-notes");
|
||||
assert.equal(item.description, "Write notes");
|
||||
assert.deepEqual(item.files.map((f) => f.path).sort(), ["SKILL.md", "scripts/run.sh"]);
|
||||
});
|
||||
|
||||
it("unpacks a zip holding several skills into one artifact each", async () => {
|
||||
const AdmZip = require("adm-zip");
|
||||
const zip = new AdmZip();
|
||||
zip.addFile("pack/alpha/SKILL.md", Buffer.from("---\nname: alpha\ndescription: A\n---\n"));
|
||||
zip.addFile("pack/alpha/ref/more.md", Buffer.from("x"));
|
||||
zip.addFile("pack/beta/skill.md", Buffer.from("---\ndescription: B\n---\nb"));
|
||||
zip.addFile("__MACOSX/pack/._alpha", Buffer.from("junk"));
|
||||
const r = await upload("/api/artifacts/skill/upload", [["pack.zip", zip.toBuffer()]]);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
assert.deepEqual(r.body.items.map((i) => i.source).sort(), ["alpha", "beta"]);
|
||||
const beta = r.body.items.find((i) => i.source === "beta");
|
||||
assert.match(snapText(beta), /^---\nname: beta\ndescription: B\n---/);
|
||||
});
|
||||
|
||||
it("stores nothing when one skill of an upload is bad, and refuses a secret or a path out", async () => {
|
||||
const before = db.prepare("SELECT COUNT(*) AS n FROM artifacts WHERE kind = 'skill'").get().n;
|
||||
const r = await upload("/api/artifacts/skill/upload", [
|
||||
["a/SKILL.md", "---\ndescription: A\n---\n"],
|
||||
["b/SKILL.md", "no frontmatter"],
|
||||
]);
|
||||
assert.equal(r.body.error.code, "ENODESCRIPTION");
|
||||
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM artifacts WHERE kind = 'skill'").get().n, before);
|
||||
const secret = await upload(
|
||||
"/api/artifacts/skill/upload",
|
||||
[["s/SKILL.md", "---\ndescription: S\n---\n"], ["s/.env", "K=1"]]
|
||||
);
|
||||
assert.equal(secret.body.error.code, "ESECRET");
|
||||
const out = await upload("/api/artifacts/skill/upload", [["../SKILL.md", "x"]], { description: "d" });
|
||||
assert.equal(out.body.error.code, "EBADPATH");
|
||||
const none = await upload("/api/artifacts/skill/upload", [["a.png", "x"], ["b.png", "y"]]);
|
||||
assert.equal(none.body.error.code, "ENOSKILLMD");
|
||||
});
|
||||
|
||||
it("writes a skill from the dialog", async () => {
|
||||
const r = await request("POST", "/api/artifacts/skill/new", {
|
||||
name: "standup",
|
||||
description: "Use for the daily standup: summarise yesterday",
|
||||
content: "Summarise.",
|
||||
});
|
||||
assert.equal(r.status, 201, r.text);
|
||||
assert.match(snapText(r.body.item), /^---\nname: standup\ndescription: "Use for the daily standup: summarise yesterday"\n---\n\nSummarise\./);
|
||||
const bad = await request("POST", "/api/artifacts/skill/new", { name: "!!!", description: "d", content: "c" });
|
||||
assert.equal(bad.body.error.code, "EBADNAME");
|
||||
});
|
||||
|
||||
it("keeps an uploaded file as a snapshot, by its own base name", async () => {
|
||||
const r = await upload("/api/artifacts/file/upload", [["report.html", "<h1>x</h1>"]], { title: "Report" });
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
assert.equal(r.body.item.kind, "file");
|
||||
assert.equal(r.body.item.title, "Report");
|
||||
const raw = await request("GET", `/api/artifacts/${r.body.item.id}/raw`);
|
||||
assert.equal(raw.text, "<h1>x</h1>");
|
||||
assert.match(raw.headers.get("content-security-policy"), /sandbox/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sharing and visibility", () => {
|
||||
it("refuses to share in local mode", async () => {
|
||||
const item = (await request("GET", "/api/artifacts")).body.items[0];
|
||||
const r = await request("PATCH", `/api/artifacts/${item.id}`, { shared: true });
|
||||
assert.equal(r.status, 400);
|
||||
assert.equal(r.body.error.code, "ELOCALMODE");
|
||||
});
|
||||
|
||||
it("shows a server-mode developer their own rows and shared ones only", () => {
|
||||
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'a', 7, 'https://claude.ai/a')").run();
|
||||
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url, shared) VALUES ('page', 'b', 8, 'https://claude.ai/b', 1)").run();
|
||||
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'c', 8, 'https://claude.ai/c')").run();
|
||||
const dev = { method: "GET", user: { id: 7, role: "developer", username: "d" } };
|
||||
const titles = artifacts.list(dev).map((i) => i.title).sort();
|
||||
assert.deepEqual(titles, ["a", "b"]);
|
||||
assert.deepEqual(artifacts.list(dev, { scope: "hub" }).map((i) => i.title), ["b"]);
|
||||
const hidden = db.prepare("SELECT id FROM artifacts WHERE title = 'c'").get().id;
|
||||
assert.equal(artifacts.canSeeId(dev, hidden), false);
|
||||
const shared = db.prepare("SELECT id FROM artifacts WHERE title = 'b'").get().id;
|
||||
assert.throws(() => artifacts.update(dev, shared, { title: "x" }), { code: "EFORBIDDEN" });
|
||||
});
|
||||
|
||||
it("refuses a cross-origin write", async () => {
|
||||
const r = await request(
|
||||
"POST",
|
||||
"/api/artifacts/page",
|
||||
{ url: "https://claude.ai/artifact/q" },
|
||||
{ Origin: "https://evil.example" }
|
||||
);
|
||||
assert.equal(r.status, 403);
|
||||
});
|
||||
});
|
||||
@@ -120,6 +120,28 @@ describe("a pool login", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("is a host pane's account when it is the host's own login, and nothing is written", () => {
|
||||
const hostCreds = path.join(TMP, ".claude", ".credentials.json");
|
||||
fs.mkdirSync(path.dirname(hostCreds), { recursive: true });
|
||||
fs.writeFileSync(hostCreds, JSON.stringify({ claudeAiOauth: oauth("h") }));
|
||||
try {
|
||||
pool.addLoginAccount("mine", { oauth: oauth("h"), account: ACCOUNT, hostHolds: true });
|
||||
const spawn = pool.forSpawn(null);
|
||||
assert.equal(spawn.name, "mine", "the host pane's usage is booked to it");
|
||||
assert.deepEqual(spawn.env, {});
|
||||
spawn.place();
|
||||
assert.equal(
|
||||
JSON.parse(fs.readFileSync(hostCreds, "utf8")).claudeAiOauth.refreshToken,
|
||||
oauth("h").refreshToken
|
||||
);
|
||||
// The host logged in as someone else: no longer the pool's.
|
||||
fs.writeFileSync(hostCreds, JSON.stringify({ claudeAiOauth: oauth("other") }));
|
||||
assert.equal(pool.forSpawn(null), null);
|
||||
} finally {
|
||||
fs.rmSync(hostCreds, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("is never written over a member's own login", () => {
|
||||
pool.addLoginAccount("team", { oauth: oauth("a"), account: ACCOUNT });
|
||||
fs.mkdirSync(path.dirname(CREDS), { recursive: true });
|
||||
|
||||
@@ -27,21 +27,33 @@ const pty = require("../lib/pty-run");
|
||||
const TOKEN = (c) => `sk-ant-oat01-${c.repeat(40)}`;
|
||||
const realFetchUsage = ccUsage.fetchUsage;
|
||||
|
||||
function run(id, account, { status = "completed", session = null, started } = {}) {
|
||||
function run(id, account, { status = "completed", session = null, started, ended = null } = {}) {
|
||||
db.prepare(
|
||||
`INSERT INTO dashboard_runs (id, session_id, mode, cwd, status, started_at, account)
|
||||
VALUES (?, ?, 'interactive', '/tmp', ?, ?, ?)`
|
||||
).run(id, session, status, started || new Date().toISOString(), account);
|
||||
`INSERT INTO dashboard_runs (id, session_id, mode, cwd, status, started_at, ended_at, account)
|
||||
VALUES (?, ?, 'interactive', '/tmp', ?, ?, ?, ?)`
|
||||
).run(id, session, status, started || new Date().toISOString(), ended, account);
|
||||
}
|
||||
|
||||
function spend(session, tokens) {
|
||||
const MODEL = "claude-sonnet-4-5-20250929";
|
||||
const hoursAgo = (h) => new Date(Date.now() - h * 3600e3).toISOString();
|
||||
|
||||
/**
|
||||
* `tokens` output tokens of `session` spent `atHoursAgo` hours ago — the
|
||||
* hourly row plus the session total, as the hook writer keeps them both.
|
||||
* `{hourly: false}` = a total with no hourly row (a sub-agent's bucket).
|
||||
*/
|
||||
function spend(session, tokens, { atHoursAgo = 0, hourly = true, model = MODEL } = {}) {
|
||||
db.prepare(
|
||||
"INSERT OR IGNORE INTO sessions (id, name, status, cwd) VALUES (?, ?, 'completed', '/tmp')"
|
||||
).run(session, session);
|
||||
"INSERT OR IGNORE INTO sessions (id, name, status, cwd, started_at) VALUES (?, ?, 'completed', '/tmp', ?)"
|
||||
).run(session, session, hoursAgo(atHoursAgo));
|
||||
db.prepare(
|
||||
`INSERT INTO token_usage_hourly (session_id, hour, model, output_tokens)
|
||||
VALUES (?, ?, 'claude-sonnet-4-5-20250929', ?)`
|
||||
).run(session, new Date().toISOString().slice(0, 13), tokens);
|
||||
`INSERT INTO token_usage (session_id, model, output_tokens) VALUES (?, ?, ?)
|
||||
ON CONFLICT DO UPDATE SET output_tokens = output_tokens + excluded.output_tokens`
|
||||
).run(session, model, tokens);
|
||||
if (!hourly) return;
|
||||
db.prepare(
|
||||
`INSERT INTO token_usage_hourly (session_id, hour, model, output_tokens) VALUES (?, ?, ?, ?)`
|
||||
).run(session, hoursAgo(atHoursAgo).slice(0, 13), model, tokens);
|
||||
}
|
||||
|
||||
before(() => {
|
||||
@@ -62,6 +74,8 @@ describe("claude pool", () => {
|
||||
fs.rmSync(pool.poolDir(), { recursive: true, force: true });
|
||||
db.prepare("DELETE FROM dashboard_runs").run();
|
||||
db.prepare("DELETE FROM token_usage_hourly").run();
|
||||
db.prepare("DELETE FROM token_usage").run();
|
||||
db.prepare("DELETE FROM sessions").run();
|
||||
pool.__quotaCache.clear();
|
||||
});
|
||||
|
||||
@@ -109,6 +123,26 @@ describe("claude pool", () => {
|
||||
assert.equal(pool.pickAccount().name, "b");
|
||||
});
|
||||
|
||||
it("books a session to an account only for the hours its runs held it, sub-agents included", () => {
|
||||
for (const n of ["a", "b"]) pool.addAccount(n, TOKEN(n));
|
||||
// s1 ran on a 30 h ago, then was resumed on b 2 h ago.
|
||||
run("r-a", "a", { session: "s1", started: hoursAgo(30), ended: hoursAgo(29) });
|
||||
run("r-b", "b", { session: "s1", started: hoursAgo(2), status: "running" });
|
||||
spend("s1", 1000, { atHoursAgo: 30 });
|
||||
spend("s1", 3000, { atHoursAgo: 2 });
|
||||
// s2 (on a, now): its main agent and a Haiku sub-agent with no hourly row.
|
||||
run("r-a2", "a", { session: "s2" });
|
||||
spend("s2", 500);
|
||||
spend("s2", 200, { hourly: false, model: "claude-haiku-4-5-20251001" });
|
||||
const status = Object.fromEntries(pool.poolStatus().map((x) => [x.name, x]));
|
||||
assert.equal(status.a.tokens5h, 700, "s2, sub-agent included; s1 is b's now");
|
||||
assert.equal(status.a.tokens7d, 1700);
|
||||
assert.equal(status.b.tokens5h, 3000, "not the hours a held s1");
|
||||
assert.equal(status.b.tokens7d, 3000);
|
||||
assert.ok(status.a.spend7d > status.a.spend5h && status.a.spend5h > 0);
|
||||
assert.ok(status.b.spend5h > 0);
|
||||
});
|
||||
|
||||
it("puts an account whose quota is nearly used up last", async () => {
|
||||
for (const n of ["a", "b"]) pool.addAccount(n, TOKEN(n));
|
||||
ccUsage.fetchUsage = async (token) => ({
|
||||
|
||||
@@ -150,6 +150,36 @@ describe("dashboard-runs", () => {
|
||||
assert.deepEqual(offered(), []);
|
||||
});
|
||||
|
||||
it("does not offer a pane that ended by itself while its tmux server ran on", () => {
|
||||
const { db } = require("../db");
|
||||
db.prepare("INSERT INTO lanes (id, title, cwd) VALUES (21, 'w', '/j')").run();
|
||||
const session = db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd) VALUES (?, ?, 'active', '/j')"
|
||||
);
|
||||
for (const id of ["q-codex", "q-signal", "q-crash", "q-reboot"]) session.run(id, id);
|
||||
db.prepare(
|
||||
"INSERT INTO events (session_id, event_type, data) VALUES ('q-signal', 'SessionEnd', ?)"
|
||||
).run(JSON.stringify({ reason: "other" }));
|
||||
start("agenthub-lane-21", { laneId: 21, sessionId: "q-codex", tool: "codex" });
|
||||
start("agenthub-lane-21-1", { laneId: 21, sessionId: "q-signal" });
|
||||
start("agenthub-lane-21-2", { laneId: 21, sessionId: "q-crash" });
|
||||
start("agenthub-lane-21-3", { laneId: 21, sessionId: "q-reboot", tool: "codex" });
|
||||
|
||||
// The host's tmux has run since long before; lane 21-3's server is gone.
|
||||
const since = (id) => (id === "agenthub-lane-21-3" ? null : 0);
|
||||
runs.reconcileOrphans((id) => !id.startsWith("agenthub-lane-21"), since);
|
||||
const status = (id) => runs.getRun(id).status;
|
||||
assert.equal(status("agenthub-lane-21"), "abandoned", "Codex quit by the user");
|
||||
assert.equal(status("agenthub-lane-21-1"), "abandoned", "closed, tmux ran on");
|
||||
assert.equal(status("agenthub-lane-21-2"), "interrupted", "Claude never said it ended");
|
||||
assert.equal(status("agenthub-lane-21-3"), "interrupted", "died with its server");
|
||||
|
||||
// A server newer than the run restarted under it: interrupted too.
|
||||
start("agenthub-lane-21-4", { laneId: 21, sessionId: "q-codex", tool: "codex" });
|
||||
runs.reconcileOrphans((id) => !id.startsWith("agenthub-lane-21"), () => Date.now());
|
||||
assert.equal(status("agenthub-lane-21-4"), "interrupted");
|
||||
});
|
||||
|
||||
it("gives a hookless tool's session the lane of the run it started in", () => {
|
||||
const { db } = require("../db");
|
||||
start("agenthub-lane-7-1", {
|
||||
|
||||
@@ -192,6 +192,54 @@ describe("POST /api/lanes/clone", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/lanes/:id/sources/clone", () => {
|
||||
it("clones beside the workspace folder and adds it as an extra folder", async () => {
|
||||
const home = path.join(WORK, "app");
|
||||
fs.mkdirSync(home);
|
||||
const made = await request("POST", "/api/lanes/ensure", { cwd: home });
|
||||
assert.ok([200, 201].includes(made.status), JSON.stringify(made.body));
|
||||
const id = made.body.lane.id;
|
||||
|
||||
const r = await request("POST", `/api/lanes/${id}/sources/clone`, {
|
||||
url: "https://forge.test/o/r.git",
|
||||
name: "lib",
|
||||
// Ignored: the clone always lands beside the workspace folder.
|
||||
parent: path.join(ROOT, "elsewhere"),
|
||||
});
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const target = path.join(WORK, "lib");
|
||||
assert.equal(fs.realpathSync(r.body.path), fs.realpathSync(target));
|
||||
assert.equal(fs.readFileSync(path.join(target, "README.md"), "utf8"), "hi\n");
|
||||
const folders = r.body.sources.filter((s) => s.kind === "folder");
|
||||
assert.deepEqual(
|
||||
folders.map((f) => fs.realpathSync(f.path)),
|
||||
[fs.realpathSync(target)]
|
||||
);
|
||||
|
||||
const again = await request("POST", `/api/lanes/${id}/sources/clone`, {
|
||||
url: "https://forge.test/o/r.git",
|
||||
name: "lib",
|
||||
});
|
||||
assert.equal(again.status, 409);
|
||||
assert.equal(again.body.error.code, "EEXISTS");
|
||||
|
||||
const login = await request("POST", `/api/lanes/${id}/sources/clone`, {
|
||||
url: "https://private.test/o/r.git",
|
||||
name: "private-lib",
|
||||
});
|
||||
assert.equal(login.status, 409);
|
||||
assert.equal(login.body.error.code, "ECREDENTIALS");
|
||||
assert.equal(login.body.error.auth.host, "private.test");
|
||||
});
|
||||
|
||||
it("answers 404 for a workspace that does not exist", async () => {
|
||||
const r = await request("POST", "/api/lanes/99999/sources/clone", {
|
||||
url: "https://forge.test/o/r.git",
|
||||
});
|
||||
assert.equal(r.status, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("/api/me/git", () => {
|
||||
it("makes a key once, returns only its public half, and deletes it", async () => {
|
||||
await request("DELETE", "/api/me/git/ssh-key");
|
||||
@@ -219,6 +267,29 @@ describe("/api/me/git", () => {
|
||||
assert.equal(del.body.ssh, null);
|
||||
});
|
||||
|
||||
it("makes an RSA 4096 key for hosts that refuse ed25519 (AWS CodeCommit), one key at a time", async () => {
|
||||
await request("POST", "/api/me/git/ssh-key", {});
|
||||
const rsa = await request("POST", "/api/me/git/ssh-key", { replace: true, type: "rsa" });
|
||||
assert.equal(rsa.status, 201, JSON.stringify(rsa.body));
|
||||
assert.equal(rsa.body.ssh.type, "rsa");
|
||||
assert.match(rsa.body.ssh.publicKey, /^ssh-rsa AAAAB3NzaC1yc2E/);
|
||||
assert.ok(!JSON.stringify(rsa.body).includes("PRIVATE"));
|
||||
const dir = path.join(ROOT, ".claude", "agenthub-ssh");
|
||||
assert.equal(fs.statSync(path.join(dir, "id_rsa")).mode & 0o777, 0o600);
|
||||
assert.ok(!fs.existsSync(path.join(dir, "id_ed25519")), "the ed25519 key was replaced");
|
||||
const bits = execFileSync("ssh-keygen", ["-lf", path.join(dir, "id_rsa.pub")], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
assert.match(bits, /^4096 .*\(RSA\)/);
|
||||
assert.equal(
|
||||
(await request("POST", "/api/me/git/ssh-key", { replace: true, type: "dsa" })).status,
|
||||
201
|
||||
);
|
||||
// An unknown type falls back to the default (the route only passes rsa through).
|
||||
assert.equal((await request("GET", "/api/me/git")).body.ssh.type, "ed25519");
|
||||
await request("DELETE", "/api/me/git/ssh-key");
|
||||
});
|
||||
|
||||
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 });
|
||||
@@ -282,10 +353,10 @@ describe("git-identity, member account (S3, stubbed)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the key and the logins in the member's own home", () => {
|
||||
it("keeps the key and the logins in the member's own home", async () => {
|
||||
const account = identity.accountForDir(path.join(HOME, "proj"));
|
||||
assert.equal(account.kind, "member");
|
||||
identity.generateSshKey(account);
|
||||
await identity.generateSshKey(account);
|
||||
const key = path.join(HOME, ".config", "agenthub", "ssh", "id_ed25519");
|
||||
assert.equal(fs.statSync(key).mode & 0o777, 0o600);
|
||||
identity.saveHttps(account, { host: "gitlab.test", username: "an", password: "p@ss/1" });
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* @file me-avatar.test.js
|
||||
* @description Settings → Account's avatar (`/api/me/avatar`,
|
||||
* server/lib/avatars.js): an account sets, reads and removes its own picture;
|
||||
* only PNG/JPEG/GIF/WebP by magic bytes (an SVG is refused), at most 1 MB,
|
||||
* served with `nosniff` and a `sandbox` CSP; `avatarAt` reaches `/api/auth/me`;
|
||||
* another account never sees it through `/api/me`; staff read it at
|
||||
* `/api/users/:id/avatar` (a developer is refused) and a workspace carries
|
||||
* `owner_avatar_at` for the sidebar's owner groups.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { 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(), "me-avatar-"));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
|
||||
process.env.DASHBOARD_DATA_DIR = TMP;
|
||||
process.env.DASHBOARD_LIVENESS_PROBE = "0";
|
||||
|
||||
const { createApp, startServer } = require("../index");
|
||||
const auth = require("../lib/auth");
|
||||
|
||||
let server;
|
||||
let BASE;
|
||||
|
||||
const PNG = Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
Buffer.alloc(32, 1),
|
||||
]);
|
||||
const JPG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(32, 2)]);
|
||||
|
||||
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.headers.get("set-cookie").split(";")[0];
|
||||
}
|
||||
|
||||
const put = (cookie, body) =>
|
||||
fetch(BASE + "/api/me/avatar", {
|
||||
method: "PUT",
|
||||
headers: { cookie, "Content-Type": "application/octet-stream" },
|
||||
body,
|
||||
});
|
||||
|
||||
before(async () => {
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
server = await startServer(createApp(), 0);
|
||||
BASE = `http://127.0.0.1:${server.address().port}`;
|
||||
await auth.createUser("ava", "ava-pass-1", "developer");
|
||||
await auth.createUser("bob", "bob-pass-1", "developer");
|
||||
await auth.createUser("ann", "ann-pass-1", "analyst");
|
||||
});
|
||||
|
||||
after(() => {
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
server?.close();
|
||||
fs.rmSync(TMP, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("sets, serves, replaces and removes the account's own avatar", async () => {
|
||||
const ava = await login("ava", "ava-pass-1");
|
||||
const bob = await login("bob", "bob-pass-1");
|
||||
assert.equal((await fetch(BASE + "/api/me/avatar", { headers: { cookie: ava } })).status, 404);
|
||||
|
||||
const set = await put(ava, PNG);
|
||||
assert.equal(set.status, 200);
|
||||
const at = (await set.json()).user.avatarAt;
|
||||
assert.ok(at);
|
||||
const me = await (await fetch(BASE + "/api/auth/me", { headers: { cookie: ava } })).json();
|
||||
assert.equal(me.user.avatarAt, at);
|
||||
|
||||
const got = await fetch(BASE + "/api/me/avatar", { headers: { cookie: ava } });
|
||||
assert.equal(got.status, 200);
|
||||
assert.equal(got.headers.get("content-type"), "image/png");
|
||||
assert.equal(got.headers.get("x-content-type-options"), "nosniff");
|
||||
assert.match(got.headers.get("content-security-policy"), /sandbox/);
|
||||
assert.deepEqual(Buffer.from(await got.arrayBuffer()), PNG);
|
||||
// Another account sees only its own (none).
|
||||
assert.equal((await fetch(BASE + "/api/me/avatar", { headers: { cookie: bob } })).status, 404);
|
||||
|
||||
// A JPEG replaces the PNG — one file per account.
|
||||
assert.equal((await put(ava, JPG)).status, 200);
|
||||
const files = fs.readdirSync(path.join(TMP, "avatars"));
|
||||
assert.deepEqual(files, [files.find((f) => f.endsWith(".jpg"))]);
|
||||
|
||||
const del = await fetch(BASE + "/api/me/avatar", { method: "DELETE", headers: { cookie: ava } });
|
||||
assert.equal(del.status, 200);
|
||||
assert.equal((await del.json()).user.avatarAt, null);
|
||||
assert.equal(fs.readdirSync(path.join(TMP, "avatars")).length, 0);
|
||||
});
|
||||
|
||||
it("refuses an SVG, an empty body, a too-large image and no login", async () => {
|
||||
const ava = await login("ava", "ava-pass-1");
|
||||
const svg = await put(ava, Buffer.from("<svg xmlns='http://www.w3.org/2000/svg'/>"));
|
||||
assert.equal(svg.status, 400);
|
||||
assert.equal((await svg.json()).error.code, "EBADIMAGE");
|
||||
assert.equal((await put(ava, Buffer.alloc(0))).status, 400);
|
||||
const big = await put(ava, Buffer.concat([PNG, Buffer.alloc(1024 * 1024)]));
|
||||
assert.equal(big.status, 413);
|
||||
assert.equal((await big.json()).error.code, "ETOOBIG");
|
||||
assert.equal((await put("", PNG)).status, 401);
|
||||
});
|
||||
|
||||
it("staff read another account's avatar; workspaces carry owner_avatar_at", async () => {
|
||||
const ava = await login("ava", "ava-pass-1");
|
||||
const ann = await login("ann", "ann-pass-1");
|
||||
const bob = await login("bob", "bob-pass-1");
|
||||
const id = auth.findUser("ava").id;
|
||||
const { db } = require("../db");
|
||||
db.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES ('/w/ava', 'claude', ?)").run(id);
|
||||
assert.equal((await put(ava, PNG)).status, 200);
|
||||
const got = await fetch(`${BASE}/api/users/${id}/avatar`, { headers: { cookie: ann } });
|
||||
assert.equal(got.status, 200);
|
||||
assert.equal(got.headers.get("x-content-type-options"), "nosniff");
|
||||
assert.deepEqual(Buffer.from(await got.arrayBuffer()), PNG);
|
||||
assert.equal(
|
||||
(await fetch(`${BASE}/api/users/${id}/avatar`, { headers: { cookie: bob } })).status,
|
||||
403
|
||||
);
|
||||
const lanes = (await (await fetch(BASE + "/api/lanes", { headers: { cookie: ann } })).json())
|
||||
.lanes;
|
||||
assert.ok(lanes.find((l) => l.cwd === "/w/ava").owner_avatar_at);
|
||||
});
|
||||
|
||||
it("deleting the account deletes its avatar", async () => {
|
||||
const bob = await login("bob", "bob-pass-1");
|
||||
assert.equal((await put(bob, PNG)).status, 200);
|
||||
auth.deleteUser("bob");
|
||||
assert.ok(!fs.readdirSync(path.join(TMP, "avatars")).some((f) => f.startsWith("u2.")));
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* @file Tests for deleting a user (`DELETE /api/users/:id`, auth.deleteUser):
|
||||
* the admin's own password again, never yourself (ESELF) or the last admin
|
||||
* (ELASTADMIN); the user's logins end, their workspaces' records, prefs and
|
||||
* folder go, the audit log keeps the deed — and under S3 the root helper is
|
||||
* asked to `delete` the Linux account and home FIRST, so its refusal leaves
|
||||
* every row in place.
|
||||
* @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(), "server-mode-user-delete-"));
|
||||
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");
|
||||
|
||||
let server;
|
||||
let BASE;
|
||||
const ids = {};
|
||||
const BOSS_PASS = "admin-pass-1";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const lane = (cwd, owner) =>
|
||||
Number(
|
||||
db.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES (?, 'claude', ?)").run(cwd, owner)
|
||||
.lastInsertRowid
|
||||
);
|
||||
|
||||
before(async () => {
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
process.env.AGENTHUB_USERS_ROOT = USERS;
|
||||
fs.mkdirSync(path.join(USERS, "mia", "proj"), { recursive: true });
|
||||
fs.writeFileSync(path.join(USERS, "mia", "proj", "a.txt"), "x");
|
||||
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.miaLane = lane(path.join(USERS, "mia", "proj"), ids.mia);
|
||||
db.prepare("INSERT INTO user_prefs (user_key, prefs) VALUES (?, '{}')").run(`u${ids.mia}`);
|
||||
});
|
||||
|
||||
after(() => {
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
delete process.env.AGENTHUB_USERS_ROOT;
|
||||
delete process.env.AGENTHUB_SERVER_CONF;
|
||||
linux.__setRunImpl(null);
|
||||
linux.__resetConfCache();
|
||||
server?.close();
|
||||
fs.rmSync(TMP, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("Delete user (DELETE /api/users/:id)", () => {
|
||||
it("needs the admin's own password, and never deletes yourself", async () => {
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const wrong = await call("DELETE", `/api/users/${ids.mia}`, {
|
||||
cookie: boss,
|
||||
body: { currentPassword: "nope" },
|
||||
});
|
||||
assert.equal(wrong.status, 403);
|
||||
assert.equal(wrong.body.error.code, "EREAUTH");
|
||||
const self = await call("DELETE", `/api/users/${ids.boss}`, {
|
||||
cookie: boss,
|
||||
body: { currentPassword: BOSS_PASS },
|
||||
});
|
||||
assert.equal(self.status, 409);
|
||||
assert.equal(self.body.error.code, "ESELF");
|
||||
assert.ok(db.prepare("SELECT 1 FROM users WHERE id = ?").get(ids.mia));
|
||||
});
|
||||
|
||||
it("refuses a developer", async () => {
|
||||
const mia = await login("mia", "member-pass-1");
|
||||
const r = await call("DELETE", `/api/users/${ids.boss}`, {
|
||||
cookie: mia,
|
||||
body: { currentPassword: "member-pass-1" },
|
||||
});
|
||||
assert.equal(r.status, 403);
|
||||
});
|
||||
|
||||
it("deletes the user, their logins, workspaces' records, prefs and folder — audited", async () => {
|
||||
const miaCookie = await login("mia", "member-pass-1");
|
||||
const boss = await login("boss", BOSS_PASS);
|
||||
const r = await call("DELETE", `/api/users/${ids.mia}`, {
|
||||
cookie: boss,
|
||||
body: { currentPassword: BOSS_PASS },
|
||||
});
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(db.prepare("SELECT 1 FROM users WHERE id = ?").get(ids.mia), undefined);
|
||||
assert.equal(db.prepare("SELECT 1 FROM lanes WHERE id = ?").get(ids.miaLane), undefined);
|
||||
assert.equal(
|
||||
db.prepare("SELECT 1 FROM user_prefs WHERE user_key = ?").get(`u${ids.mia}`),
|
||||
undefined
|
||||
);
|
||||
assert.ok(!fs.existsSync(path.join(USERS, "mia")), "her folder is gone");
|
||||
// Her old login no longer works.
|
||||
assert.equal((await call("GET", "/api/me/account", { cookie: miaCookie })).status, 401);
|
||||
const audit = db
|
||||
.prepare("SELECT path FROM audit_log WHERE owner_id = ? ORDER BY id DESC")
|
||||
.get(ids.mia);
|
||||
assert.match(audit.path, /^delete mia/);
|
||||
// The same name can be made again, as a new account.
|
||||
const again = await auth.createUser("mia", "member-pass-3", "developer");
|
||||
assert.notEqual(again.id, ids.mia);
|
||||
});
|
||||
|
||||
it("never deletes the last admin", () => {
|
||||
assert.throws(() => auth.deleteUser("boss"), { code: "ELASTADMIN" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delete user under S3", () => {
|
||||
const CONF = path.join(TMP, "server.conf");
|
||||
let calls;
|
||||
before(() => {
|
||||
fs.writeFileSync(CONF, `HOST_USER=h\nHOST_UID=1000\nUSERS_ROOT=${USERS}\n`);
|
||||
process.env.AGENTHUB_SERVER_CONF = CONF;
|
||||
linux.__resetConfCache();
|
||||
});
|
||||
|
||||
it("asks the root helper to delete the account and home first", async () => {
|
||||
calls = [];
|
||||
linux.__setRunImpl((argv) => {
|
||||
calls.push(argv);
|
||||
return "ok";
|
||||
});
|
||||
const u = await auth.createUser("leo", "member-pass-2", "developer");
|
||||
calls = [];
|
||||
auth.deleteUser("leo");
|
||||
assert.deepEqual(calls, [["/opt/agenthub/sbin/agenthub-provision", "delete", "leo"]]);
|
||||
assert.equal(db.prepare("SELECT 1 FROM users WHERE id = ?").get(u.id), undefined);
|
||||
});
|
||||
|
||||
it("keeps every row when the helper refuses", async () => {
|
||||
linux.__setRunImpl(() => "ok");
|
||||
const u = await auth.createUser("zoe", "member-pass-4", "developer");
|
||||
const zl = lane(path.join(USERS, "zoe", "p"), u.id);
|
||||
linux.__setRunImpl(() => {
|
||||
throw Object.assign(new Error("x"), { stderr: "ah-zoe is not an AgentHub member" });
|
||||
});
|
||||
assert.throws(() => auth.deleteUser("zoe"), { code: "EPROVISION" });
|
||||
assert.ok(db.prepare("SELECT 1 FROM users WHERE id = ?").get(u.id));
|
||||
assert.ok(db.prepare("SELECT 1 FROM lanes WHERE id = ?").get(zl));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* @file user-storage.test.js
|
||||
* @description The Users page's Storage column (server/lib/user-storage.js,
|
||||
* `GET /api/users/storage`): the walk counts allocated blocks, a hard link
|
||||
* once and never follows a symlink; a server-mode user's folder under
|
||||
* AGENTHUB_USERS_ROOT is measured in the background and reported to staff,
|
||||
* a member is refused, and a user with no folder of their own reads null.
|
||||
* @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(), "user-storage-"));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
|
||||
process.env.DASHBOARD_LIVENESS_PROBE = "0";
|
||||
const USERS_ROOT = path.join(TMP, "users");
|
||||
fs.mkdirSync(USERS_ROOT);
|
||||
|
||||
const { createApp, startServer } = require("../index");
|
||||
const auth = require("../lib/auth");
|
||||
const { walk } = require("../lib/user-storage");
|
||||
|
||||
let server;
|
||||
let BASE;
|
||||
const ids = {};
|
||||
|
||||
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 }),
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
return res.headers.get("set-cookie").split(";")[0];
|
||||
}
|
||||
|
||||
async function storage(cookie, q = "") {
|
||||
const res = await fetch(`${BASE}/api/users/storage${q}`, { headers: { cookie } });
|
||||
return { status: res.status, body: await res.json().catch(() => null) };
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
process.env.AGENTHUB_USERS_ROOT = USERS_ROOT;
|
||||
server = await startServer(createApp(), 0);
|
||||
BASE = `http://127.0.0.1:${server.address().port}`;
|
||||
ids.boss = (await auth.createUser("boss", "admin-pass-1", "admin")).id;
|
||||
ids.mia = (await auth.createUser("mia", "member-pass-1", "developer")).id;
|
||||
const home = path.join(USERS_ROOT, "mia");
|
||||
fs.mkdirSync(path.join(home, "src"), { recursive: true });
|
||||
fs.writeFileSync(path.join(home, "src", "a.bin"), Buffer.alloc(64 * 1024, 1));
|
||||
});
|
||||
|
||||
after(() => {
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
delete process.env.AGENTHUB_USERS_ROOT;
|
||||
server?.close();
|
||||
fs.rmSync(TMP, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("walk", () => {
|
||||
it("counts blocks, a hard link once, and never follows a symlink", () => {
|
||||
const dir = fs.mkdtempSync(path.join(TMP, "walk-"));
|
||||
fs.writeFileSync(path.join(dir, "big"), Buffer.alloc(128 * 1024, 1));
|
||||
fs.linkSync(path.join(dir, "big"), path.join(dir, "big-link"));
|
||||
fs.symlinkSync("/usr", path.join(dir, "usr"));
|
||||
const r = walk(dir, Date.now() + 10_000);
|
||||
assert.equal(r.partial, false);
|
||||
assert.equal(r.files, 2); // big + the symlink itself; the hard link is skipped
|
||||
assert.ok(r.bytes >= 128 * 1024 && r.bytes < 1024 * 1024, `bytes ${r.bytes}`);
|
||||
});
|
||||
|
||||
it("stops at the deadline as a lower bound", () => {
|
||||
const r = walk(TMP, Date.now() - 1);
|
||||
assert.equal(r.partial, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/users/storage", () => {
|
||||
it("measures a user's folder in the background for staff", async () => {
|
||||
const admin = await login("boss", "admin-pass-1");
|
||||
let r = await storage(admin);
|
||||
assert.equal(r.status, 200);
|
||||
for (let i = 0; i < 50 && (r.body.measuring || !r.body.storage[ids.mia]); i++) {
|
||||
await new Promise((ok) => setTimeout(ok, 100));
|
||||
r = await storage(admin);
|
||||
}
|
||||
const mia = r.body.storage[ids.mia];
|
||||
assert.ok(mia, "mia's folder was measured");
|
||||
assert.ok(mia.bytes >= 64 * 1024);
|
||||
assert.equal(mia.files, 1);
|
||||
assert.equal(mia.partial, false);
|
||||
assert.ok(mia.measuredAt);
|
||||
// The admin has no folder under the users root: nothing to measure.
|
||||
assert.equal(r.body.storage[ids.boss], null);
|
||||
});
|
||||
|
||||
it("refuses a developer", async () => {
|
||||
const mia = await login("mia", "member-pass-1");
|
||||
const r = await storage(mia);
|
||||
assert.equal(r.status, 403);
|
||||
});
|
||||
});
|
||||
+35
-2
@@ -914,6 +914,37 @@ db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_lane_sources_lane ON lane_sources(lane_id);
|
||||
`);
|
||||
|
||||
// The Artifacts hub (server/lib/artifacts.js, docs/plans/artifacts/): what
|
||||
// agents produced — a claude.ai page, a file, a skill, a plugin — kept by its
|
||||
// OWNER and, in server mode, shared to every user when `shared` is set. A
|
||||
// file or skill is a snapshot under <data dir>/artifacts/<snapshot>/, never
|
||||
// the owner's live copy. Additive.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS artifacts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('page', 'file', 'skill', 'plugin')),
|
||||
title TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
owner_id INTEGER,
|
||||
lane_id INTEGER,
|
||||
session_id TEXT,
|
||||
source TEXT,
|
||||
market TEXT,
|
||||
url TEXT,
|
||||
snapshot TEXT,
|
||||
files TEXT,
|
||||
size INTEGER,
|
||||
shared INTEGER NOT NULL DEFAULT 0,
|
||||
shared_at TEXT,
|
||||
installs INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_artifacts_owner ON artifacts(owner_id, kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_artifacts_shared ON artifacts(shared, kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_artifacts_session ON artifacts(session_id);
|
||||
`);
|
||||
|
||||
// Seed lane_stage_events from the snapshots that predate it, so upgrading does
|
||||
// not read as "every pipeline has never run". Each lane's live `stages` blob
|
||||
// becomes one run; each archived feature becomes one more. That is all the
|
||||
@@ -1824,8 +1855,10 @@ try {
|
||||
}
|
||||
}
|
||||
// An account's own display name and email (the Users page's Edit user and
|
||||
// Settings → Account). Additive; after the rebuild above, which predates them.
|
||||
for (const col of ["display_name", "email"]) {
|
||||
// Settings → Account), and when its avatar was last set (server/lib/avatars.js
|
||||
// — the image is a file, the column only versions its URL). Additive; after
|
||||
// the rebuild above, which predates them.
|
||||
for (const col of ["display_name", "email", "avatar_at"]) {
|
||||
try {
|
||||
db.prepare(`SELECT ${col} FROM users LIMIT 1`).get();
|
||||
} catch {
|
||||
|
||||
+6
-4
@@ -210,6 +210,7 @@ function createApp() {
|
||||
app.use("/api/locks", locksRouter);
|
||||
app.use("/api/pets", petsRouter);
|
||||
app.use("/api/snapshots", snapshotsRouter);
|
||||
app.use("/api/artifacts", require("./routes/artifacts"));
|
||||
app.use("/api/alerts", alertsRouter);
|
||||
app.use("/api/budgets", budgetsRouter);
|
||||
app.use("/api/query", queryRouter);
|
||||
@@ -762,7 +763,7 @@ function startBackgroundServices() {
|
||||
if (Number.isFinite(HEAL_MS) && HEAL_MS > 0) {
|
||||
const { healAllRunIds } = require("./routes/lanes");
|
||||
const { reconcileOrphans } = require("./lib/dashboard-runs");
|
||||
const { liveSessions } = require("./lib/tmux");
|
||||
const { liveSessions, serverStartedAt } = require("./lib/tmux");
|
||||
const anyRun = require("./db").db.prepare(
|
||||
`SELECT EXISTS (SELECT 1 FROM lanes WHERE run_id IS NOT NULL)
|
||||
OR EXISTS (SELECT 1 FROM dashboard_runs WHERE status IN ('running', 'spawning')) AS any`
|
||||
@@ -782,7 +783,8 @@ function startBackgroundServices() {
|
||||
healAllRunIds(live);
|
||||
// A pane that quit (Ctrl+C, `exit`) ends its run record too; one that
|
||||
// died under its agent (killed tmux, crash) is offered for resume.
|
||||
if (reconcileOrphans((id) => live.has(id)) > 0) broadcast("runs_interrupted", {});
|
||||
if (reconcileOrphans((id) => live.has(id), serverStartedAt) > 0)
|
||||
broadcast("runs_interrupted", {});
|
||||
} catch (err) {
|
||||
console.warn("run heal failed:", err.message);
|
||||
}
|
||||
@@ -841,8 +843,8 @@ function startBackgroundServices() {
|
||||
// this process, owns it.
|
||||
try {
|
||||
const { reconcileOrphans } = require("./lib/dashboard-runs");
|
||||
const { hasSession } = require("./lib/tmux");
|
||||
const reconciled = reconcileOrphans(hasSession);
|
||||
const { hasSession, serverStartedAt } = require("./lib/tmux");
|
||||
const reconciled = reconcileOrphans(hasSession, serverStartedAt);
|
||||
if (reconciled > 0) {
|
||||
console.log(`[runs] reconciled ${reconciled} orphan run(s) → interrupted/abandoned`);
|
||||
}
|
||||
|
||||
@@ -494,6 +494,7 @@ async function testProxy(input = {}) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
proxiesDir,
|
||||
listProxies,
|
||||
getProxy,
|
||||
createProxy,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+74
-2
@@ -142,6 +142,8 @@ const publicUser = (u) =>
|
||||
disabled: Boolean(u.disabled),
|
||||
displayName: u.display_name ?? null,
|
||||
email: u.email ?? null,
|
||||
// When the avatar was last set (null = none): the client's cache-buster.
|
||||
avatarAt: u.avatar_at ?? null,
|
||||
createdAt: u.created_at ?? null,
|
||||
};
|
||||
|
||||
@@ -279,8 +281,8 @@ function stopHostPanes(userId) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Disable (ending every login) or re-enable a user. Users are never deleted:
|
||||
* S2 will hang owned rows off their id. */
|
||||
/** Disable (ending every login) or re-enable a user — the reversible way out;
|
||||
* `deleteUser` below is the one that removes an account for good. */
|
||||
function setDisabled(username, disabled) {
|
||||
const u = requireUser(username);
|
||||
const linux = require("./linux-accounts");
|
||||
@@ -298,6 +300,75 @@ function setDisabled(username, disabled) {
|
||||
if (disabled && hasAccount) linux.provision("disable", u.username);
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE a user — the Users page's "Delete user" (an admin, password
|
||||
* confirmed by the route). In order, so a failure leaves the account usable
|
||||
* rather than half gone: their logins end and the panes of their workspaces
|
||||
* stop; under S3 the Linux account `ah-<name>` and its whole home are removed
|
||||
* (`agenthub-provision delete`; EPROVISION stops here, with no row touched);
|
||||
* without S3 their own folder under AGENTHUB_USERS_ROOT goes. Then the rows:
|
||||
* their workspaces' records, prefs, push subscriptions, personal AI Proxy
|
||||
* profiles and the user. Session history and the audit log stay. Never the
|
||||
* last enabled admin (ELASTADMIN); the route refuses yourself (ESELF).
|
||||
* A user made again under the same name gets a NEW, empty Linux account.
|
||||
*/
|
||||
function deleteUser(username) {
|
||||
const u = requireUser(username);
|
||||
if (u.role === "admin") {
|
||||
const others = sql(
|
||||
"SELECT COUNT(*) AS n FROM users WHERE role = 'admin' AND disabled = 0 AND id != ?"
|
||||
).get(u.id).n;
|
||||
if (!others) throw err("ELASTADMIN", "the last admin cannot be deleted");
|
||||
}
|
||||
const lanes = sql("SELECT id, cwd FROM lanes WHERE owner_id = ?").all(u.id);
|
||||
sql("DELETE FROM auth_sessions WHERE user_id = ?").run(u.id);
|
||||
const pty = require("./pty-run");
|
||||
for (const lane of lanes) {
|
||||
for (let slot = 0; slot <= pty.MAX_PANE_SLOT; slot++) {
|
||||
try {
|
||||
pty.killRun(pty.runIdForLane(lane.id, slot));
|
||||
} catch {
|
||||
/* not running */
|
||||
}
|
||||
}
|
||||
}
|
||||
const linux = require("./linux-accounts");
|
||||
if (linux.s3Enabled()) {
|
||||
// Idempotent: a user with no Linux account (made before S3) or no home
|
||||
// still passes; anything the helper refuses stops the delete here.
|
||||
if (linux.LINUX_NAME_RE.test(u.username)) linux.provision("delete", u.username);
|
||||
} else {
|
||||
const path = require("node:path");
|
||||
const fs = require("node:fs");
|
||||
const root = (process.env.AGENTHUB_USERS_ROOT || "").trim();
|
||||
if (root && /^[a-z][a-z0-9_-]{0,63}$/i.test(u.username)) {
|
||||
const home = path.join(path.resolve(root), u.username);
|
||||
// Only a real folder directly in the users root — never a link.
|
||||
const st = fs.lstatSync(home, { throwIfNoEntry: false });
|
||||
if (st?.isDirectory()) fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
const lanesLib = require("./lanes");
|
||||
for (const lane of lanes) lanesLib.deleteLane(lane.id);
|
||||
sql("DELETE FROM user_prefs WHERE user_key = ?").run(`u${u.id}`);
|
||||
require("./avatars").removeAvatar(u.id);
|
||||
try {
|
||||
sql("DELETE FROM push_subscriptions WHERE user_id = ?").run(u.id);
|
||||
} catch {
|
||||
/* an older database without the column */
|
||||
}
|
||||
try {
|
||||
require("node:fs").rmSync(
|
||||
require("node:path").join(require("./ai-proxies").proxiesDir(), "users", String(u.id)),
|
||||
{ recursive: true, force: true }
|
||||
);
|
||||
} catch {
|
||||
/* no personal profiles */
|
||||
}
|
||||
sql("DELETE FROM users WHERE id = ?").run(u.id);
|
||||
return { id: u.id, username: u.username, workspaces: lanes.length };
|
||||
}
|
||||
|
||||
/** Give a workspace (a lane id) to a user — for the ones made before server
|
||||
* mode, which have no owner and so reach no member. */
|
||||
function assignWorkspace(laneId, username) {
|
||||
@@ -603,6 +674,7 @@ module.exports = {
|
||||
setPassword,
|
||||
setRole,
|
||||
setDisabled,
|
||||
deleteUser,
|
||||
assignWorkspace,
|
||||
unassignWorkspace,
|
||||
ownedWorkspaces,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* @file avatars.js
|
||||
* @description A server-mode account's own avatar (Settings → Account, shown
|
||||
* in the sidebar). One raster image per account, stored as
|
||||
* `<data dir>/avatars/u<id>.<png|jpg|gif|webp>` — a name made from the
|
||||
* account id and the type its magic bytes say, never from the request — and
|
||||
* `users.avatar_at` records when it was set, so the client can version the
|
||||
* URL. Raster only: an SVG served from the dashboard's origin runs script.
|
||||
* At most `MAX_AVATAR_BYTES`; the serving route adds `nosniff` and a
|
||||
* `sandbox` CSP like every other user-supplied file.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { getDataDir } = require("./claude-home");
|
||||
const { sniffImage } = require("./pets");
|
||||
|
||||
const MAX_AVATAR_BYTES = 1024 * 1024;
|
||||
const EXTS = ["png", "jpg", "gif", "webp"];
|
||||
const TYPES = { png: "image/png", jpg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
||||
|
||||
const fail = (code, message) => Object.assign(new Error(message), { code });
|
||||
|
||||
const avatarsDir = () => path.join(getDataDir(), "avatars");
|
||||
|
||||
function fileName(userId, ext) {
|
||||
const id = Number(userId);
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw fail("EBADFIELD", "bad account id");
|
||||
return path.join(avatarsDir(), `u${id}.${ext}`);
|
||||
}
|
||||
|
||||
const db = () => require("../db").db;
|
||||
|
||||
/** Deletes every stored avatar file of the account and clears `avatar_at`. */
|
||||
function removeAvatar(userId) {
|
||||
for (const ext of EXTS) fs.rmSync(fileName(userId, ext), { force: true });
|
||||
db().prepare("UPDATE users SET avatar_at = NULL WHERE id = ?").run(Number(userId));
|
||||
}
|
||||
|
||||
/** Stores `buf` as the account's avatar (EBADIMAGE / ETOOBIG); returns `avatar_at`. */
|
||||
function setAvatar(userId, buf) {
|
||||
if (!Buffer.isBuffer(buf) || buf.length === 0) throw fail("EBADIMAGE", "no image sent");
|
||||
if (buf.length > MAX_AVATAR_BYTES) throw fail("ETOOBIG", "the image is too large");
|
||||
const ext = sniffImage(buf);
|
||||
if (!ext) throw fail("EBADIMAGE", "only PNG, JPEG, GIF or WebP images");
|
||||
const target = fileName(userId, ext);
|
||||
fs.mkdirSync(avatarsDir(), { recursive: true, mode: 0o700 });
|
||||
// Written beside, then renamed: a reader never sees half an image.
|
||||
const tmp = `${target}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(tmp, buf, { mode: 0o600 });
|
||||
fs.renameSync(tmp, target);
|
||||
for (const other of EXTS) {
|
||||
if (other !== ext) fs.rmSync(fileName(userId, other), { force: true });
|
||||
}
|
||||
const at = new Date().toISOString();
|
||||
db().prepare("UPDATE users SET avatar_at = ? WHERE id = ?").run(at, Number(userId));
|
||||
return at;
|
||||
}
|
||||
|
||||
/** The account's avatar file and its type, or null when it has none. */
|
||||
function avatarFile(userId) {
|
||||
for (const ext of EXTS) {
|
||||
const file = fileName(userId, ext);
|
||||
const st = fs.lstatSync(file, { throwIfNoEntry: false });
|
||||
if (st?.isFile()) return { path: file, type: TYPES[ext] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = { MAX_AVATAR_BYTES, setAvatar, removeAvatar, avatarFile, avatarsDir };
|
||||
+18
-53
@@ -15,9 +15,9 @@
|
||||
* 1. an account whose last quota reading is ≥ `BLOCK_PERCENT` in either
|
||||
* window goes last (still used when every account is that full);
|
||||
* 2. fewest live panes (spreads concurrent sessions);
|
||||
* 3. least $ spent in the last 5 hours, then in the last 7 days — summed from
|
||||
* `token_usage_hourly` for the sessions its runs (`dashboard_runs.account`)
|
||||
* started.
|
||||
* 3. least $ spent in the last 5 hours, then in the last 7 days — the
|
||||
* sessions its runs (`dashboard_runs.account`) held, over the hours they
|
||||
* held them (pool-usage.js).
|
||||
* The quota is read with the account's own token in the background, at most
|
||||
* every `QUOTA_TTL_MS`; a token the usage endpoint refuses simply has no
|
||||
* reading, and ranking falls back to spend.
|
||||
@@ -375,47 +375,8 @@ function quotaPercent(name) {
|
||||
|
||||
// ── What AgentHub recorded per account ─────────────────────────────────────
|
||||
|
||||
const USAGE_COLS = [
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
"cache_read_tokens",
|
||||
"cache_write_tokens",
|
||||
"cache_write_1h_tokens",
|
||||
"web_search_requests",
|
||||
"web_fetch_requests",
|
||||
"code_execution_requests",
|
||||
"long_input_tokens",
|
||||
"long_output_tokens",
|
||||
"long_cache_read_tokens",
|
||||
"long_cache_write_tokens",
|
||||
"long_cache_write_1h_tokens",
|
||||
];
|
||||
|
||||
/**
|
||||
* $ spent on `account` since `sinceHour` (`YYYY-MM-DDTHH`, UTC): the hourly
|
||||
* usage of every session one of its runs started, from that run's start hour.
|
||||
* ponytail: a session later resumed on ANOTHER account keeps counting here
|
||||
* too; split by run end time if that ever skews a ranking.
|
||||
*/
|
||||
function spendSince(account, sinceHour) {
|
||||
const { db, stmts } = require("../db");
|
||||
const { calculateCost } = require("../routes/pricing");
|
||||
const rows = db
|
||||
.prepare(
|
||||
`WITH s AS (
|
||||
SELECT session_id, MIN(substr(started_at, 1, 13)) AS since
|
||||
FROM dashboard_runs
|
||||
WHERE tool = 'claude' AND account = ? AND session_id IS NOT NULL
|
||||
GROUP BY session_id)
|
||||
SELECT h.model, h.speed, h.inference_geo, h.service_tier,
|
||||
${USAGE_COLS.map((c) => `SUM(h.${c}) AS ${c}`).join(", ")}
|
||||
FROM s JOIN token_usage_hourly h
|
||||
ON h.session_id = s.session_id AND h.hour >= s.since AND h.hour >= ?
|
||||
GROUP BY h.model, h.speed, h.inference_geo, h.service_tier`
|
||||
)
|
||||
.all(account, sinceHour);
|
||||
return rows.length ? calculateCost(rows, stmts.listPricing.all()).total_cost : 0;
|
||||
}
|
||||
/** $ and tokens of the last 5 h / 7 d (pool-usage.js). */
|
||||
const usageOf = (account) => require("./pool-usage").accountUsage("claude", account);
|
||||
|
||||
function livePanes(account) {
|
||||
const { db } = require("../db");
|
||||
@@ -426,8 +387,6 @@ function livePanes(account) {
|
||||
.get(account).n;
|
||||
}
|
||||
|
||||
const hourAgo = (hours) => new Date(Date.now() - hours * 3600e3).toISOString().slice(0, 13);
|
||||
|
||||
/** Every account with what the balancer sees — never a token. */
|
||||
function poolStatus() {
|
||||
return allAccounts().map((a) => {
|
||||
@@ -442,8 +401,7 @@ function poolStatus() {
|
||||
expiresAt: expiresAt(a),
|
||||
expired: expired(a),
|
||||
livePanes: livePanes(a.name),
|
||||
spend5h: spendSince(a.name, hourAgo(5)),
|
||||
spend7d: spendSince(a.name, hourAgo(24 * 7)),
|
||||
...usageOf(a.name),
|
||||
quota: q
|
||||
? {
|
||||
fiveHour: q.fiveHour || null,
|
||||
@@ -481,8 +439,11 @@ function pick(member) {
|
||||
let usable = allAccounts().filter((a) => !expired(a));
|
||||
if (usable.length === 0) return null;
|
||||
if (!member) {
|
||||
// A host pane's home holds the host's own login.
|
||||
usable = usable.filter((a) => a.kind === "token");
|
||||
// A host pane's home holds the host's own login — a pool account only when
|
||||
// it was moved in from there (`hostHolds`) and is still the pair on disk:
|
||||
// the pane then runs on it as it is, and its usage is that account's.
|
||||
const disk = homeCreds(HOST_ACCT);
|
||||
usable = usable.filter((a) => a.kind === "token" || ownsHome(a, HOST, disk));
|
||||
} else {
|
||||
const disk = homeCreds(member);
|
||||
const placed = disk && usable.find((a) => ownsHome(a, member.name, disk));
|
||||
@@ -501,13 +462,14 @@ function pick(member) {
|
||||
const ranked = usable
|
||||
.map((a) => {
|
||||
const percent = quotaPercent(a.name);
|
||||
const u = usageOf(a.name);
|
||||
return {
|
||||
a,
|
||||
key: [
|
||||
percent != null && percent >= BLOCK_PERCENT ? 1 : 0,
|
||||
livePanes(a.name),
|
||||
spendSince(a.name, hourAgo(5)),
|
||||
spendSince(a.name, hourAgo(24 * 7)),
|
||||
u.spend5h,
|
||||
u.spend7d,
|
||||
],
|
||||
};
|
||||
})
|
||||
@@ -524,7 +486,8 @@ function pick(member) {
|
||||
* The account a new Claude pane should run on — `{name, kind, token?}` — or
|
||||
* null when the pool has nothing this pane may use. Synchronous (a spawn
|
||||
* cannot wait on the network): it ranks on the cached quota and starts a
|
||||
* background re-read. A `login` is only ever offered for a member.
|
||||
* background re-read. A `login` is offered for a member, and for a host pane
|
||||
* only when it is the host's own login (`hostHolds`), which stays as it is.
|
||||
*/
|
||||
function pickAccount(member = null) {
|
||||
const a = pick(member);
|
||||
@@ -545,6 +508,8 @@ function forSpawn(member = null) {
|
||||
if (a.kind === "token") {
|
||||
return { name: a.name, env: { CLAUDE_CODE_OAUTH_TOKEN: a.token }, place: () => {} };
|
||||
}
|
||||
// The host's own login is already in place; the server keeps it fresh.
|
||||
if (!member) return { name: a.name, env: {}, place: () => {} };
|
||||
return {
|
||||
name: a.name,
|
||||
env: {},
|
||||
|
||||
@@ -155,29 +155,12 @@ function livePanes(account) {
|
||||
}
|
||||
|
||||
/**
|
||||
* $ of the Codex sessions this account's runs started since `hours` ago.
|
||||
* $ and tokens of the last 5 h / 7 d (pool-usage.js).
|
||||
* ponytail: Codex usage has no hourly table, so a session counts whole once
|
||||
* its run started in the window; add hourly rows if that skews a ranking.
|
||||
*/
|
||||
function spendSince(account, hours) {
|
||||
const { db, stmts } = require("../db");
|
||||
const { calculateCost } = require("../routes/pricing");
|
||||
const since = new Date(Date.now() - hours * 3600e3).toISOString();
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT model, speed, inference_geo, service_tier,
|
||||
SUM(input_tokens) AS input_tokens, SUM(output_tokens) AS output_tokens,
|
||||
SUM(cache_read_tokens) AS cache_read_tokens,
|
||||
SUM(cache_write_tokens) AS cache_write_tokens
|
||||
FROM token_usage
|
||||
WHERE session_id IN (SELECT session_id FROM dashboard_runs
|
||||
WHERE tool = 'codex' AND account = ?
|
||||
AND session_id IS NOT NULL AND started_at >= ?)
|
||||
GROUP BY model, speed, inference_geo, service_tier`
|
||||
)
|
||||
.all(account, since);
|
||||
return rows.length ? calculateCost(rows, stmts.listPricing.all()).total_cost : 0;
|
||||
}
|
||||
const usageOf = (account) =>
|
||||
require("./pool-usage").accountUsage("codex", account, { wholeSession: true });
|
||||
|
||||
// ── Quota, from the account's own rollouts ─────────────────────────────────
|
||||
|
||||
@@ -262,8 +245,7 @@ function poolStatus() {
|
||||
kind: a.kind,
|
||||
addedAt: a.addedAt,
|
||||
livePanes: livePanes(a.name),
|
||||
spend5h: spendSince(a.name, 5),
|
||||
spend7d: spendSince(a.name, 24 * 7),
|
||||
...usageOf(a.name),
|
||||
quota: quotas().get(a.name) || null,
|
||||
quotaPercent: percent,
|
||||
full: percent != null && percent >= BLOCK_PERCENT,
|
||||
@@ -374,13 +356,14 @@ function pick(member) {
|
||||
const ranked = usable
|
||||
.map((a) => {
|
||||
const percent = quotaPercent(a.name);
|
||||
const u = usageOf(a.name);
|
||||
return {
|
||||
a,
|
||||
key: [
|
||||
percent != null && percent >= BLOCK_PERCENT ? 1 : 0,
|
||||
livePanes(a.name),
|
||||
spendSince(a.name, 5),
|
||||
spendSince(a.name, 24 * 7),
|
||||
u.spend5h,
|
||||
u.spend7d,
|
||||
],
|
||||
};
|
||||
})
|
||||
|
||||
@@ -288,6 +288,17 @@ const userExitStmt = db.prepare(`
|
||||
LIMIT 1
|
||||
`);
|
||||
|
||||
const anyEndStmt = db.prepare(`
|
||||
SELECT 1 FROM events WHERE session_id = ? AND event_type = 'SessionEnd' LIMIT 1
|
||||
`);
|
||||
// Whether the pane's tmux server was already up when the run started (and is
|
||||
// still): then the pane ended on its own, not with its server.
|
||||
function tmuxOutlived(row, serverStartedAt) {
|
||||
const since = serverStartedAt(row.id);
|
||||
const started = Date.parse(row.started_at || "");
|
||||
return Number.isFinite(since) && Number.isFinite(started) && since <= started;
|
||||
}
|
||||
|
||||
// A shell has no session, so its row only tracks the open tab: once closed it
|
||||
// is dropped — the sidebar keeps no list of closed Terminal tabs.
|
||||
const pruneShellsStmt = db.prepare(`
|
||||
@@ -303,12 +314,16 @@ const pruneShellsStmt = db.prepare(`
|
||||
* A pane AgentHub closed itself (Stop, close tab, Quit) is already `killed`.
|
||||
* Of the rest, an agent session the user did not exit is `interrupted` — a
|
||||
* reboot, a killed tmux, a crash — and offered for resume
|
||||
* (`listInterrupted`); everything else is `abandoned`. Only Claude reports
|
||||
* how it ended, so any other tool's vanished pane counts as interrupted.
|
||||
* (`listInterrupted`); everything else is `abandoned`. A pane whose tmux
|
||||
* server kept running since before it started (`serverStartedAt(id)`, epoch
|
||||
* ms or null) ended by itself — the user quit Codex, `exit`ed, closed it —
|
||||
* so it is not offered either: for Claude only when it said it ended (any
|
||||
* SessionEnd; none at all is a crash), for any other tool, which says
|
||||
* nothing, always. A server that cannot be asked counts as gone.
|
||||
*
|
||||
* Returns the number of rows updated.
|
||||
*/
|
||||
function reconcileOrphans(isAlive = () => false) {
|
||||
function reconcileOrphans(isAlive = () => false, serverStartedAt = () => null) {
|
||||
try {
|
||||
let changes = 0;
|
||||
const { unseenMemberFolder } = require("./linux-accounts");
|
||||
@@ -317,7 +332,11 @@ function reconcileOrphans(isAlive = () => false) {
|
||||
const interrupted =
|
||||
row.tool !== "shell" &&
|
||||
!!row.session_id &&
|
||||
!(row.tool === "claude" && userExitStmt.get(row.session_id));
|
||||
!(row.tool === "claude" && userExitStmt.get(row.session_id)) &&
|
||||
!(
|
||||
tmuxOutlived(row, serverStartedAt) &&
|
||||
(row.tool !== "claude" || anyEndStmt.get(row.session_id))
|
||||
);
|
||||
changes += endStmt.run({
|
||||
id: row.id,
|
||||
status: interrupted ? "interrupted" : "abandoned",
|
||||
|
||||
+89
-26
@@ -5,7 +5,7 @@
|
||||
*
|
||||
* Whose identity is decided by an ACCOUNT, never by the request:
|
||||
* - a member (S3, `run-as.js`): everything lives in their own home, under
|
||||
* `~/.config/agenthub/` — `ssh/id_ed25519` (+ `.pub`) and `git-credentials`
|
||||
* `~/.config/agenthub/` — `ssh/id_ed25519` or `ssh/id_rsa` (+ `.pub`) and `git-credentials`
|
||||
* (git's own `credential-store` format) — written only AS the member
|
||||
* (`write-as`, 0600 for the secrets), read only through `readFileSafe`.
|
||||
* Their git runs as them, so it reads these itself; no secret ever crosses
|
||||
@@ -61,18 +61,26 @@ function accountForRequest(req) {
|
||||
return { kind: "host", writable: !user || user.role === "admin" };
|
||||
}
|
||||
|
||||
/**
|
||||
* The key types offered: ed25519 (the default — GitHub, GitLab, Gitea…) and
|
||||
* RSA 4096 for hosts that refuse ed25519 (AWS IAM / CodeCommit takes only
|
||||
* `ssh-rsa`). One key per account at a time, in the file of its type.
|
||||
*/
|
||||
const KEY_FILES = { ed25519: "id_ed25519", rsa: "id_rsa" };
|
||||
const KEY_PREFIX = { ed25519: "ssh-ed25519", rsa: "ssh-rsa" };
|
||||
|
||||
function paths(account) {
|
||||
if (account.kind === "member") {
|
||||
const base = path.join(account.acct.home, ".config", "agenthub");
|
||||
return {
|
||||
base,
|
||||
sshDir: path.join(base, "ssh"),
|
||||
key: path.join(base, "ssh", "id_ed25519"),
|
||||
key: path.join(base, "ssh", KEY_FILES.ed25519),
|
||||
store: path.join(base, "git-credentials"),
|
||||
};
|
||||
}
|
||||
const sshDir = path.join(getClaudeHome(), "agenthub-ssh");
|
||||
return { base: sshDir, sshDir, key: path.join(sshDir, "id_ed25519"), store: null };
|
||||
return { base: sshDir, sshDir, key: path.join(sshDir, KEY_FILES.ed25519), store: null };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,6 +138,31 @@ const u32 = (n) => {
|
||||
};
|
||||
const sshString = (buf) => Buffer.concat([u32(buf.length), Buffer.from(buf)]);
|
||||
|
||||
/** An SSH mpint: big-endian, with a 0 byte in front when the top bit is set. */
|
||||
const mpint = (b) => sshString(b[0] & 0x80 ? Buffer.concat([Buffer.from([0]), b]) : b);
|
||||
|
||||
/**
|
||||
* A fresh RSA 4096 pair: the private key as PKCS#1 PEM (`BEGIN RSA PRIVATE
|
||||
* KEY`, which OpenSSH reads), the public one as an `ssh-rsa` line. Made off
|
||||
* the event loop — 4096-bit generation takes a second.
|
||||
*/
|
||||
async function makeRsaKeyPair(comment) {
|
||||
const pair = await require("node:util").promisify(crypto.generateKeyPair)("rsa", {
|
||||
modulusLength: 4096,
|
||||
publicExponent: 0x10001,
|
||||
});
|
||||
const jwk = pair.publicKey.export({ format: "jwk" });
|
||||
const blob = Buffer.concat([
|
||||
sshString(Buffer.from("ssh-rsa")),
|
||||
mpint(Buffer.from(jwk.e, "base64url")),
|
||||
mpint(Buffer.from(jwk.n, "base64url")),
|
||||
]);
|
||||
return {
|
||||
privateKey: pair.privateKey.export({ type: "pkcs1", format: "pem" }),
|
||||
publicKey: `ssh-rsa ${blob.toString("base64")} ${comment}\n`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A fresh ed25519 pair in OpenSSH's formats: `{privateKey, publicKey}` text,
|
||||
* unencrypted (`openssh-key-v1`, cipher none) — the dashboard has no terminal
|
||||
@@ -175,36 +208,65 @@ function fingerprint(publicKey) {
|
||||
return `SHA256:${crypto.createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`;
|
||||
}
|
||||
|
||||
/** `{publicKey, fingerprint}` of the account's key, or null — never the private half. */
|
||||
function sshKeyInfo(account) {
|
||||
const { key } = paths(account);
|
||||
const publicKey = readText(account, `${key}.pub`);
|
||||
if (!publicKey || !/^ssh-ed25519 [A-Za-z0-9+/=]+/.test(publicKey)) return null;
|
||||
// The private half is only looked at, never read into this process.
|
||||
if (!isOwnFile(account, key)) return null;
|
||||
return { publicKey: publicKey.trim(), fingerprint: fingerprint(publicKey) };
|
||||
/** `{type, file}` of the account's key (ed25519 first), or null. */
|
||||
function currentKey(account) {
|
||||
const { sshDir } = paths(account);
|
||||
for (const type of Object.keys(KEY_FILES)) {
|
||||
const file = path.join(sshDir, KEY_FILES[type]);
|
||||
const publicKey = readText(account, `${file}.pub`);
|
||||
if (!publicKey || !publicKey.startsWith(`${KEY_PREFIX[type]} `)) continue;
|
||||
// The private half is only looked at, never read into this process.
|
||||
if (!isOwnFile(account, file)) continue;
|
||||
return { type, file, publicKey: publicKey.trim() };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Make the account's key; an existing one is replaced only with `replace`. */
|
||||
function generateSshKey(account, { replace = false, comment } = {}) {
|
||||
/** The private key file a clone or fetch uses, or null. */
|
||||
const keyFile = (account) => currentKey(account)?.file ?? null;
|
||||
|
||||
/** `{type, publicKey, fingerprint}` of the account's key, or null — never the private half. */
|
||||
function sshKeyInfo(account) {
|
||||
const k = currentKey(account);
|
||||
return k ? { type: k.type, publicKey: k.publicKey, fingerprint: fingerprint(k.publicKey) } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the account's key (`type`: ed25519, the default, or rsa); an existing
|
||||
* one is replaced only with `replace` — and a key of the other type goes, so
|
||||
* there is one key per account.
|
||||
*/
|
||||
async function generateSshKey(account, { replace = false, comment, type = "ed25519" } = {}) {
|
||||
if (!KEY_FILES[type]) throw err("EBADKEYTYPE", "key type: ed25519 or rsa");
|
||||
if (sshKeyInfo(account) && !replace) {
|
||||
throw err("EEXISTS", "an SSH key already exists — replace it explicitly");
|
||||
}
|
||||
const label = String(comment || "agenthub")
|
||||
.replace(/[^\w.@+-]/g, "")
|
||||
.slice(0, 64);
|
||||
const { privateKey, publicKey } = makeKeyPair(label || "agenthub");
|
||||
const { key } = paths(account);
|
||||
writeText(account, key, privateKey, { secret: true });
|
||||
writeText(account, `${key}.pub`, publicKey, { secret: false });
|
||||
const label =
|
||||
String(comment || "agenthub")
|
||||
.replace(/[^\w.@+-]/g, "")
|
||||
.slice(0, 64) || "agenthub";
|
||||
const { privateKey, publicKey } =
|
||||
type === "rsa" ? await makeRsaKeyPair(label) : makeKeyPair(label);
|
||||
const { sshDir } = paths(account);
|
||||
const file = path.join(sshDir, KEY_FILES[type]);
|
||||
writeText(account, file, privateKey, { secret: true });
|
||||
writeText(account, `${file}.pub`, publicKey, { secret: false });
|
||||
for (const [other, name] of Object.entries(KEY_FILES)) {
|
||||
if (other === type) continue;
|
||||
const f = path.join(sshDir, name);
|
||||
if (isOwnFile(account, f) || readText(account, `${f}.pub`) != null) {
|
||||
removeFile(account, f);
|
||||
removeFile(account, `${f}.pub`);
|
||||
}
|
||||
}
|
||||
return sshKeyInfo(account);
|
||||
}
|
||||
|
||||
function removeSshKey(account) {
|
||||
const { key } = paths(account);
|
||||
if (!sshKeyInfo(account)) return false;
|
||||
removeFile(account, key);
|
||||
removeFile(account, `${key}.pub`);
|
||||
const k = currentKey(account);
|
||||
if (!k) return false;
|
||||
removeFile(account, k.file);
|
||||
removeFile(account, `${k.file}.pub`);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -354,7 +416,7 @@ async function sshConfigFor(dir) {
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const key = sshKeyInfo(account) ? paths(account).key : null;
|
||||
const key = keyFile(account);
|
||||
return [
|
||||
"-c",
|
||||
`core.sshCommand=ssh${key ? ` -i ${shq(key)}` : ""} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`,
|
||||
@@ -464,7 +526,7 @@ async function cloneRepo({ url, parent, name, once = null }) {
|
||||
|
||||
if (remote.scheme === "ssh") {
|
||||
if (once) throw err("EBADCRED", "a typed login is for https only — SSH uses your key");
|
||||
const key = sshKeyInfo(account) ? paths(account).key : null;
|
||||
const key = keyFile(account);
|
||||
const base = key ? `ssh -i ${shq(key)} -o IdentitiesOnly=yes` : "ssh";
|
||||
// BatchMode: no terminal to answer a prompt; accept-new: first contact
|
||||
// records the host key, a CHANGED one still fails.
|
||||
@@ -552,6 +614,7 @@ module.exports = {
|
||||
accountForDir,
|
||||
accountForRequest,
|
||||
makeKeyPair,
|
||||
makeRsaKeyPair,
|
||||
fingerprint,
|
||||
sshKeyInfo,
|
||||
generateSshKey,
|
||||
|
||||
+10
-5
@@ -736,12 +736,17 @@ function inferredDisplayStage(lane) {
|
||||
return lane.detected_stage;
|
||||
}
|
||||
|
||||
/** The owner's username and display name — the staff sidebar groups
|
||||
* workspaces by owner and shows the display name when one is set. */
|
||||
/** The owner's username, display name and avatar version — the staff
|
||||
* sidebar groups workspaces by owner and shows the display name and picture
|
||||
* (`GET /api/users/:id/avatar`) when one is set. */
|
||||
function ownerNames(id) {
|
||||
if (id == null) return { owner_name: null, owner_display_name: null };
|
||||
const u = db.prepare("SELECT username, display_name FROM users WHERE id = ?").get(id);
|
||||
return { owner_name: u?.username ?? null, owner_display_name: u?.display_name ?? null };
|
||||
if (id == null) return { owner_name: null, owner_display_name: null, owner_avatar_at: null };
|
||||
const u = db.prepare("SELECT username, display_name, avatar_at FROM users WHERE id = ?").get(id);
|
||||
return {
|
||||
owner_name: u?.username ?? null,
|
||||
owner_display_name: u?.display_name ?? null,
|
||||
owner_avatar_at: u?.avatar_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function lanePayload(lane, ageSec = null) {
|
||||
|
||||
@@ -23,7 +23,7 @@ const { execFileSync } = require("node:child_process");
|
||||
/** Lower case, a letter first, ≤ 29 so `ah-<name>` fits Linux's 32. */
|
||||
const LINUX_NAME_RE = /^[a-z][a-z0-9_-]{0,28}$/;
|
||||
const PROVISION = "/opt/agenthub/sbin/agenthub-provision";
|
||||
const ACTIONS = new Set(["create", "disable", "enable"]);
|
||||
const ACTIONS = new Set(["create", "disable", "enable", "delete"]);
|
||||
|
||||
const confPath = () => process.env.AGENTHUB_SERVER_CONF || "/etc/agenthub/server.conf";
|
||||
|
||||
@@ -121,7 +121,8 @@ function __setRunImpl(fn) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create / disable / enable the Linux account of `username`. A no-op outside
|
||||
* Create / disable / enable / delete (account AND home) the Linux account of
|
||||
* `username`. A no-op outside
|
||||
* S3 (returns null). Throws EPROVISION with the helper's own words on failure.
|
||||
*/
|
||||
function provision(action, username) {
|
||||
@@ -135,7 +136,12 @@ function provision(action, username) {
|
||||
.trim()
|
||||
.split("\n")
|
||||
.pop();
|
||||
throw Object.assign(new Error(`could not ${action} the Linux account: ${why}`), {
|
||||
// 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"
|
||||
: "";
|
||||
throw Object.assign(new Error(`could not ${action} the Linux account: ${why}${hint}`), {
|
||||
code: "EPROVISION",
|
||||
});
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user