Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| decf176b4b | |||
| dea74b777e | |||
| 18e574a765 | |||
| 879a6bb02d | |||
| 1a365a45bd | |||
| 54001585e2 | |||
| 0bf552b793 | |||
| 87ba935c6e | |||
| 045e46e111 | |||
| e7573f13d9 | |||
| 9d28807f2c |
@@ -72,6 +72,10 @@ export function usePermissions() {
|
||||
// A developer only ever sees their own rows, so everything shown is theirs.
|
||||
canEditLane: (lane?: { owner_id?: number | null } | null) =>
|
||||
isAdmin || user?.role === "developer" || (!!user && lane?.owner_id === user.id),
|
||||
// Owner-only actions on a workspace (rename, reset, remove, share): its
|
||||
// owner or an admin. A workspace shared with this user is not theirs.
|
||||
ownsLane: (lane?: { owner_id?: number | null } | null) =>
|
||||
isAdmin || (!!user && lane?.owner_id === user.id),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,9 @@ import { UserAvatar } from "./users/UserAvatar";
|
||||
const AddLaneModal = lazy(() =>
|
||||
import("./lanes/AddLaneModal").then((m) => ({ default: m.AddLaneModal }))
|
||||
);
|
||||
const WorkspaceShareModal = lazy(() =>
|
||||
import("./lanes/WorkspaceShareModal").then((m) => ({ default: m.WorkspaceShareModal }))
|
||||
);
|
||||
const DestructiveLaneModal = lazy(() =>
|
||||
import("./lanes/DestructiveLaneModal").then((m) => ({ default: m.DestructiveLaneModal }))
|
||||
);
|
||||
@@ -116,7 +119,9 @@ export function WorkspaceTree() {
|
||||
const selected = selectedFrom(location.pathname, location.search);
|
||||
const { lanes, refresh: refreshLanes } = useLanes();
|
||||
const { state: auth } = useAuth();
|
||||
const { seesAll, canEditLane } = usePermissions();
|
||||
const { seesAll, canEditLane, ownsLane } = usePermissions();
|
||||
// Sharing a workspace with other users (server mode): the open dialog's lane.
|
||||
const [sharing, setSharing] = useState<Lane | null>(null);
|
||||
const meId = auth.mode === "server" ? (auth.user?.id ?? null) : null;
|
||||
// Server mode staff see every user's workspaces, so the list says whose.
|
||||
const grouped = auth.mode === "server" && seesAll;
|
||||
@@ -375,6 +380,7 @@ export function WorkspaceTree() {
|
||||
|
||||
const onMenuAction = (lane: Lane, action: WorkspaceMenuAction) => {
|
||||
if (action === "rename") setRenamingId(lane.id);
|
||||
else if (action === "share") setSharing(lane);
|
||||
else if (action === "new-here") openAdd(lane.source_repo || lane.cwd);
|
||||
else if (action === "reset" || action === "remove") setDestructive({ lane, action });
|
||||
};
|
||||
@@ -559,7 +565,8 @@ export function WorkspaceTree() {
|
||||
onNewSession={() => select(lane.id)}
|
||||
onReorder={nudge}
|
||||
onMenu={(x, y) => setMenu({ lane, x, y })}
|
||||
onRenameStart={() => setRenamingId(lane.id)}
|
||||
// A workspace shared with this user keeps its owner's name.
|
||||
onRenameStart={() => ownsLane(lane) && setRenamingId(lane.id)}
|
||||
onRenameEnd={(title) => void rename(lane, title)}
|
||||
/>
|
||||
)}
|
||||
@@ -688,6 +695,7 @@ export function WorkspaceTree() {
|
||||
</ContextMenu>
|
||||
)}
|
||||
<Suspense fallback={null}>
|
||||
{sharing && <WorkspaceShareModal lane={sharing} onClose={() => setSharing(null)} />}
|
||||
{destructive && (
|
||||
<DestructiveLaneModal
|
||||
lane={destructive.lane}
|
||||
|
||||
@@ -31,6 +31,7 @@ export function SessionMenu({
|
||||
onArchive,
|
||||
onUnarchive,
|
||||
onPin,
|
||||
onShare,
|
||||
}: MenuPoint & {
|
||||
laneId: number;
|
||||
session: Session | null;
|
||||
@@ -42,6 +43,8 @@ export function SessionMenu({
|
||||
onUnarchive?: () => void;
|
||||
/** Pin or unpin (by `session.pinned_at`), where the list offers it. */
|
||||
onPin?: () => void;
|
||||
/** Share this session on its own (server mode, the workspace's owner). */
|
||||
onShare?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("lanes");
|
||||
const navigate = useNavigate();
|
||||
@@ -81,6 +84,11 @@ export function SessionMenu({
|
||||
{t(session.pinned_at ? "sessionMenu.unpin" : "sessionMenu.pin")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{onShare && session && (
|
||||
<MenuItem testId="session-menu-share" onSelect={pick(onShare)}>
|
||||
{t("sessionMenu.share")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{session && (
|
||||
<>
|
||||
<MenuItem onSelect={pick(() => navigate(`/sessions/${session.id}`))}>
|
||||
|
||||
@@ -57,6 +57,8 @@ import { AiToolIcon } from "../AiToolIcon";
|
||||
import { ProxyPicker, proxyArg, useAiProxies, useSessionProxy } from "../run/ProxyPicker";
|
||||
import { Select } from "../Select";
|
||||
import { WorkspaceRowMenu, type WorkspaceMenuAction } from "./WorkspaceRowMenu";
|
||||
import { WorkspaceShareModal } from "./WorkspaceShareModal";
|
||||
import { usePermissions } from "../AuthGate";
|
||||
import { workspaceName } from "./WorkspaceRow";
|
||||
import { SessionMenu } from "./SessionMenu";
|
||||
import { menuPoint, useContextMenu } from "../ContextMenu";
|
||||
@@ -118,6 +120,7 @@ function HomeBody({
|
||||
const { t } = useTranslation("lanes");
|
||||
const navigate = useNavigate();
|
||||
const aiTools = useAiTools();
|
||||
const { ownsLane } = usePermissions();
|
||||
// The NEW session's AI tool — its own choice, the workspace's by default.
|
||||
const [tool, setTool] = useState(lane.tool);
|
||||
const entry = aiTools.byId(tool);
|
||||
@@ -195,6 +198,7 @@ function HomeBody({
|
||||
const [nameDraft, setNameDraft] = useState("");
|
||||
const [menuAt, setMenuAt] = useState<{ x: number; y: number } | null>(null);
|
||||
const [title, setTitle] = useState<string | null>(null);
|
||||
const [sharing, setSharing] = useState(false);
|
||||
const recentCtx = useContextMenu<Session>();
|
||||
|
||||
// A new pane, a pane gone, a session id learned — all move these lane fields.
|
||||
@@ -270,10 +274,17 @@ function HomeBody({
|
||||
};
|
||||
|
||||
const text = promptWithImages(prompt, images, claude);
|
||||
// A workspace shared with this user: a session they start runs on their
|
||||
// own account and is billed to them (the server answers ENOCOLLABACCOUNT
|
||||
// when they have none).
|
||||
const collab = !ownsLane(lane);
|
||||
// Only a session of it is shared with them (phase 3): no new session here —
|
||||
// they open that session and send it messages (the server answers ESESSIONSHARE).
|
||||
const sessionOnly = lane.access === "session";
|
||||
const start = async () => {
|
||||
// Enter reaches here past the disabled button: the same guards again.
|
||||
// A ref, not only the state: two Enters in one tick both read `starting` false.
|
||||
if (startingRef.current || uploading || !text) return;
|
||||
if (sessionOnly || startingRef.current || uploading || !text) return;
|
||||
startingRef.current = true;
|
||||
setStarting(true);
|
||||
setError(null);
|
||||
@@ -529,7 +540,7 @@ function HomeBody({
|
||||
type="button"
|
||||
data-testid="workspace-home-start"
|
||||
onClick={() => void start()}
|
||||
disabled={starting || uploading || !text}
|
||||
disabled={sessionOnly || starting || uploading || !text}
|
||||
aria-label={t("home.start")}
|
||||
title={t("home.start")}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-accent-solid text-white transition-opacity hover:opacity-90 disabled:opacity-40"
|
||||
@@ -539,6 +550,11 @@ function HomeBody({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{collab && (
|
||||
<p data-testid="workspace-home-collab" className="mt-2 text-xs text-fg-muted">
|
||||
{t(sessionOnly ? "shared.sessionOnly" : "shared.ownAccount")}
|
||||
</p>
|
||||
)}
|
||||
{/* The session's quieter choices, under the box like Claude Desktop's. */}
|
||||
<div
|
||||
data-testid="workspace-home-options"
|
||||
@@ -787,9 +803,16 @@ function HomeBody({
|
||||
x={menuAt.x}
|
||||
y={menuAt.y}
|
||||
onClose={() => setMenuAt(null)}
|
||||
onAction={(a) => (a === "rename" ? setTitle(lane.title || "") : onMenuAction(a))}
|
||||
onAction={(a) =>
|
||||
a === "rename"
|
||||
? setTitle(lane.title || "")
|
||||
: a === "share"
|
||||
? setSharing(true)
|
||||
: onMenuAction(a)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{sharing && <WorkspaceShareModal lane={lane} onClose={() => setSharing(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
* @file WorkspaceRowMenu — the sidebar workspace row's context menu, opened at
|
||||
* the pointer (right-click) or under the row's `⋯` button. Every item is an
|
||||
* existing call: Rename (the row's inline field), New workspace here (the
|
||||
* Add modal prefilled), Copy path, and Reset/Remove through `DestructiveLaneModal` — Reset only on a
|
||||
* Add modal prefilled), Copy path, Share (server mode: `WorkspaceShareModal`),
|
||||
* and Reset/Remove through `DestructiveLaneModal` — Reset only on a
|
||||
* managed lane — plus Move to group (the sidebar's own groups,
|
||||
* `lib/workspaceGroups.ts`: one of them, a new one, or out of its group). The
|
||||
* server's guards are the real ones; the menu only hides
|
||||
* what the lane's kind or tool makes meaningless. The shell (position,
|
||||
* what the lane's kind or tool makes meaningless, and the owner-only items
|
||||
* (Rename, Share, Reset, Remove) on a workspace shared with this user. The shell (position,
|
||||
* Escape / outside-click close) is `ContextMenu`.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
@@ -17,8 +19,9 @@ import { Check } from "lucide-react";
|
||||
import { ContextMenu, MenuItem, MenuSeparator } from "../ContextMenu";
|
||||
import type { WorkspaceGroup } from "../../lib/workspaceGroups";
|
||||
import { copyText } from "../../lib/clipboard";
|
||||
import { usePermissions } from "../AuthGate";
|
||||
|
||||
export type WorkspaceMenuAction = "rename" | "new-here" | "reset" | "remove";
|
||||
export type WorkspaceMenuAction = "rename" | "new-here" | "share" | "reset" | "remove";
|
||||
|
||||
export function WorkspaceRowMenu({
|
||||
lane,
|
||||
@@ -43,9 +46,11 @@ export function WorkspaceRowMenu({
|
||||
onGroup?: (target: string | null | "new") => void;
|
||||
}) {
|
||||
const { t } = useTranslation("lanes");
|
||||
const { local, ownsLane } = usePermissions();
|
||||
const owner = ownsLane(lane);
|
||||
return (
|
||||
<ContextMenu x={x} y={y} onClose={onClose} testId={`workspace-row-menu-${lane.id}`}>
|
||||
<MenuItem onSelect={() => onAction("rename")}>{t("menu.rename")}</MenuItem>
|
||||
{owner && <MenuItem onSelect={() => onAction("rename")}>{t("menu.rename")}</MenuItem>}
|
||||
<MenuItem onSelect={() => onAction("new-here")}>{t("menu.newHere")}</MenuItem>
|
||||
<MenuItem
|
||||
onSelect={() => {
|
||||
@@ -55,6 +60,11 @@ export function WorkspaceRowMenu({
|
||||
>
|
||||
{t("menu.copyPath")}
|
||||
</MenuItem>
|
||||
{owner && !local && (
|
||||
<MenuItem testId="workspace-menu-share" onSelect={() => onAction("share")}>
|
||||
{t("menu.share")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{onGroup && (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
@@ -84,15 +94,19 @@ export function WorkspaceRowMenu({
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
{lane.kind === "managed" && (
|
||||
<MenuItem danger onSelect={() => onAction("reset")}>
|
||||
{t("menu.reset")}
|
||||
</MenuItem>
|
||||
{owner && (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
{lane.kind === "managed" && (
|
||||
<MenuItem danger onSelect={() => onAction("reset")}>
|
||||
{t("menu.reset")}
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuItem danger onSelect={() => onAction("remove")}>
|
||||
{t("menu.remove")}
|
||||
</MenuItem>
|
||||
</>
|
||||
)}
|
||||
<MenuItem danger onSelect={() => onAction("remove")}>
|
||||
{t("menu.remove")}
|
||||
</MenuItem>
|
||||
</ContextMenu>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { lazy, Suspense, useEffect, useState, type ReactNode } from "react";
|
||||
import { endRuns } from "../../lib/stopSession";
|
||||
import { isSubmitEnter } from "../../lib/keys";
|
||||
import { Archive, GitBranch, Pin, PinOff, SquareTerminal } from "lucide-react";
|
||||
@@ -46,6 +46,11 @@ import { useAiTools } from "../../hooks/useAiTools";
|
||||
import { useThrottledValue } from "../../hooks/useThrottledValue";
|
||||
import { useContextMenu } from "../ContextMenu";
|
||||
import { SessionMenu } from "./SessionMenu";
|
||||
import { usePermissions } from "../AuthGate";
|
||||
|
||||
const WorkspaceShareModal = lazy(() =>
|
||||
import("./WorkspaceShareModal").then((m) => ({ default: m.WorkspaceShareModal }))
|
||||
);
|
||||
|
||||
export const SESSION_LIMIT = 6;
|
||||
|
||||
@@ -256,6 +261,9 @@ export function WorkspaceSessionList({
|
||||
const [busy, setBusy] = useState(false);
|
||||
const ctx = useContextMenu<RunHandle>();
|
||||
const sessionCtx = useContextMenu<Session>();
|
||||
// Share one session (server mode, the workspace's owner or an admin).
|
||||
const { local, ownsLane } = usePermissions();
|
||||
const [sharing, setSharing] = useState<Session | null>(null);
|
||||
// Rows shown; See all raises it to the whole list.
|
||||
const [limit, setLimit] = useState(SESSION_LIMIT);
|
||||
|
||||
@@ -637,8 +645,18 @@ export function WorkspaceSessionList({
|
||||
onPin={() =>
|
||||
void patch(sessionCtx.menu!.item, { pinned: !sessionCtx.menu!.item.pinned_at })
|
||||
}
|
||||
onShare={!local && ownsLane(lane) ? () => setSharing(sessionCtx.menu!.item) : undefined}
|
||||
/>
|
||||
)}
|
||||
{sharing && (
|
||||
<Suspense fallback={null}>
|
||||
<WorkspaceShareModal
|
||||
lane={lane}
|
||||
session={{ id: sharing.id, name: sharing.name }}
|
||||
onClose={() => setSharing(null)}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* @file WorkspaceShareModal — share a workspace, or one of its sessions
|
||||
* (`session`), with other users (server mode, docs/plans/workspace-sharing/
|
||||
* phases 1 and 3). Ticks people from `GET /api/artifacts/people` (names only)
|
||||
* and saves the whole list through `PUT /api/lanes/:id/shares` or
|
||||
* `PUT /api/lanes/:id/sessions/:sid/shares`. It says plainly what sharing means on this
|
||||
* server: the people it is shared with work as the owner's account and can
|
||||
* read everything in the owner's home. Only the owner or an admin opens it —
|
||||
* the server refuses anyone else (`ENOTOWNER`).
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ShieldAlert, X } from "lucide-react";
|
||||
import { api } from "../../lib/api";
|
||||
import type { Lane } from "../../lib/types";
|
||||
import { toast } from "../../lib/toast";
|
||||
import { confirmDialog } from "../../lib/confirm";
|
||||
import { useDialog } from "../../hooks/useDialog";
|
||||
import { Checkbox } from "../Checkbox";
|
||||
|
||||
type Person = { id: number; username: string; name: string; disabled?: boolean };
|
||||
|
||||
export function WorkspaceShareModal({
|
||||
lane,
|
||||
session,
|
||||
onClose,
|
||||
}: {
|
||||
lane: Lane;
|
||||
/** Share this one session instead of the whole workspace. */
|
||||
session?: { id: string; name?: string | null };
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("lanes");
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
useDialog(true, panelRef, onClose);
|
||||
const [people, setPeople] = useState<Person[] | null>(null);
|
||||
const [initial, setInitial] = useState<Set<number>>(new Set());
|
||||
const [picked, setPicked] = useState<Set<number>>(new Set());
|
||||
const [query, setQuery] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const sid = session?.id;
|
||||
Promise.all([
|
||||
api.artifacts.people(),
|
||||
sid ? api.lanes.sessionShares(lane.id, sid) : api.lanes.shares(lane.id),
|
||||
])
|
||||
.then(([p, s]) => {
|
||||
if (!alive) return;
|
||||
// Never the owner: a workspace is not shared with them. Someone it is
|
||||
// already shared with but who was disabled since is not in `people`:
|
||||
// listed anyway, so they can be taken off.
|
||||
const known = new Set(p.people.map((x) => x.id));
|
||||
setPeople([
|
||||
...p.people.filter((x) => x.id !== lane.owner_id),
|
||||
...s.shares.filter((x) => !known.has(x.id)).map((x) => ({ ...x, disabled: true })),
|
||||
]);
|
||||
const ids = new Set(s.shares.map((x) => x.id));
|
||||
setInitial(ids);
|
||||
setPicked(new Set(ids));
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!alive) return;
|
||||
toast.error(err);
|
||||
setPeople([]);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [lane.id, lane.owner_id, session?.id]);
|
||||
|
||||
const shown = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return (people ?? []).filter(
|
||||
(p) => !q || p.name.toLowerCase().includes(q) || p.username.toLowerCase().includes(q)
|
||||
);
|
||||
}, [people, query]);
|
||||
const added = [...picked].filter((id) => !initial.has(id));
|
||||
const changed = added.length > 0 || [...initial].some((id) => !picked.has(id));
|
||||
const name = session ? session.name || session.id : lane.title || lane.cwd;
|
||||
|
||||
const save = async () => {
|
||||
if (added.length > 0) {
|
||||
const names = (people ?? []).filter((p) => added.includes(p.id)).map((p) => p.name);
|
||||
const ok = await confirmDialog({
|
||||
title: t("share.confirmTitle", { name }),
|
||||
message: t("share.confirmBody", { people: names.join(", ") }),
|
||||
confirmLabel: t("share.confirm"),
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = session
|
||||
? await api.lanes.setSessionShares(lane.id, session.id, [...picked])
|
||||
: await api.lanes.setShares(lane.id, [...picked]);
|
||||
toast.success(
|
||||
r.shares.length ? t("share.saved", { count: r.shares.length }) : t("share.savedNone")
|
||||
);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggle = (id: number, on: boolean) =>
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (on) next.add(id);
|
||||
else next.delete(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-surface-0/70 p-4"
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
ref={panelRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="workspace-share-title"
|
||||
data-testid="workspace-share-modal"
|
||||
className="flex max-h-[85vh] w-full max-w-md flex-col overflow-hidden rounded-xl border border-border bg-surface-1 shadow-xl"
|
||||
>
|
||||
<div className="flex items-start gap-3 border-b border-border px-5 py-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 id="workspace-share-title" className="text-base font-semibold text-fg-primary">
|
||||
{t(session ? "share.sessionTitle" : "share.title")}
|
||||
</h2>
|
||||
<p className="mt-0.5 truncate text-xs text-fg-muted" title={lane.cwd}>
|
||||
{name}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t("share.close")}
|
||||
className="rounded p-1 text-fg-muted hover:bg-surface-3 hover:text-fg-primary"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-5 py-4">
|
||||
<p className="text-xs text-fg-secondary">
|
||||
{t(session ? "share.sessionWhat" : "share.what")}
|
||||
</p>
|
||||
<div
|
||||
data-testid="workspace-share-warning"
|
||||
className="flex gap-2 rounded-lg border border-status-warning/30 bg-status-warning/10 px-3 py-2 text-xs text-status-warning"
|
||||
>
|
||||
<ShieldAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
<span>{t("share.warning")}</span>
|
||||
</div>
|
||||
{people === null ? (
|
||||
<p className="text-xs text-fg-muted">{t("share.loading")}</p>
|
||||
) : people.length === 0 ? (
|
||||
<p className="text-xs text-fg-muted">{t("share.nobody")}</p>
|
||||
) : (
|
||||
<>
|
||||
{people.length > 8 && (
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t("share.search")}
|
||||
aria-label={t("share.search")}
|
||||
className="input w-full text-sm"
|
||||
/>
|
||||
)}
|
||||
<ul className="space-y-1" data-testid="workspace-share-people">
|
||||
{shown.map((p) => (
|
||||
<li key={p.id}>
|
||||
<Checkbox
|
||||
checked={picked.has(p.id)}
|
||||
onChange={(v) => toggle(p.id, v)}
|
||||
disabled={busy}
|
||||
label={
|
||||
<span>
|
||||
{p.name}
|
||||
{p.name !== p.username && (
|
||||
<span className="ml-1.5 text-fg-muted">@{p.username}</span>
|
||||
)}
|
||||
{p.disabled && (
|
||||
<span className="ml-1.5 text-fg-muted">{t("share.disabled")}</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
|
||||
<button type="button" className="btn-ghost text-sm" onClick={onClose} disabled={busy}>
|
||||
{t("share.cancel")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-primary text-sm"
|
||||
data-testid="workspace-share-save"
|
||||
onClick={() => void save()}
|
||||
disabled={busy || !changed || people === null}
|
||||
>
|
||||
{busy ? t("share.saving") : t("share.save")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* @file Tests for workspace sharing in the client: WorkspaceShareModal starts
|
||||
* on the current list, never offers the owner, warns what sharing means, asks
|
||||
* once before adding someone and saves the WHOLE list; WorkspaceRowMenu offers
|
||||
* Share (server mode) and the other owner-only items only to the workspace's
|
||||
* owner or an admin; given a session, it lists and saves THAT session's
|
||||
* shares instead.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, act, fireEvent } from "@testing-library/react";
|
||||
import "../../../i18n";
|
||||
import i18n from "../../../i18n";
|
||||
import { settleConfirm } from "../../../lib/confirm";
|
||||
import { WorkspaceShareModal } from "../WorkspaceShareModal";
|
||||
import { WorkspaceRowMenu } from "../WorkspaceRowMenu";
|
||||
import type { Lane } from "../../../lib/types";
|
||||
|
||||
const perms = vi.hoisted(() => ({ local: false, me: 1, admin: false }));
|
||||
vi.mock("../../AuthGate", () => ({
|
||||
usePermissions: () => ({
|
||||
local: perms.local,
|
||||
isAdmin: perms.admin,
|
||||
ownsLane: (l?: { owner_id?: number | null } | null) =>
|
||||
perms.local || perms.admin || l?.owner_id === perms.me,
|
||||
}),
|
||||
}));
|
||||
|
||||
const m = vi.hoisted(() => ({
|
||||
people: vi.fn(),
|
||||
shares: vi.fn(),
|
||||
setShares: vi.fn(),
|
||||
sessionShares: vi.fn(),
|
||||
setSessionShares: vi.fn(),
|
||||
}));
|
||||
vi.mock("../../../lib/api", () => ({
|
||||
api: {
|
||||
artifacts: { people: m.people },
|
||||
lanes: {
|
||||
shares: m.shares,
|
||||
setShares: m.setShares,
|
||||
sessionShares: m.sessionShares,
|
||||
setSessionShares: m.setSessionShares,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const lane = {
|
||||
id: 7,
|
||||
title: "Shop",
|
||||
cwd: "/home/alice/shop",
|
||||
owner_id: 1,
|
||||
kind: "adopted",
|
||||
} as Lane;
|
||||
|
||||
async function settle() {
|
||||
await act(async () => {
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
i18n.changeLanguage("en");
|
||||
perms.local = false;
|
||||
perms.me = 1;
|
||||
perms.admin = false;
|
||||
m.people.mockResolvedValue({
|
||||
people: [
|
||||
{ id: 1, username: "alice", name: "Alice" },
|
||||
{ id: 2, username: "bob", name: "Bob" },
|
||||
{ id: 3, username: "carol", name: "Carol" },
|
||||
],
|
||||
});
|
||||
m.shares.mockResolvedValue({
|
||||
shares: [{ id: 2, username: "bob", name: "Bob", sharedAt: "2026-11-06T00:00:00Z" }],
|
||||
canManage: true,
|
||||
});
|
||||
m.setShares.mockImplementation(async (_id: number, ids: number[]) => ({
|
||||
shares: ids.map((id) => ({ id, username: `u${id}`, name: `U${id}`, sharedAt: "" })),
|
||||
}));
|
||||
});
|
||||
|
||||
describe("WorkspaceShareModal", () => {
|
||||
it("starts on the current list, never offers the owner and says what sharing means", async () => {
|
||||
render(<WorkspaceShareModal lane={lane} onClose={() => {}} />);
|
||||
await settle();
|
||||
const list = screen.getByTestId("workspace-share-people");
|
||||
expect(list).not.toHaveTextContent("Alice");
|
||||
expect(screen.getByRole("checkbox", { name: /Bob/ })).toHaveAttribute("aria-checked", "true");
|
||||
expect(screen.getByRole("checkbox", { name: /Carol/ })).toHaveAttribute(
|
||||
"aria-checked",
|
||||
"false"
|
||||
);
|
||||
expect(screen.getByTestId("workspace-share-warning")).toHaveTextContent(/your home folder/i);
|
||||
// Nothing changed yet: nothing to save.
|
||||
expect(screen.getByTestId("workspace-share-save")).toBeDisabled();
|
||||
});
|
||||
|
||||
it("asks once before adding someone, then saves the whole list", async () => {
|
||||
const onClose = vi.fn();
|
||||
render(<WorkspaceShareModal lane={lane} onClose={onClose} />);
|
||||
await settle();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: /Carol/ }));
|
||||
fireEvent.click(screen.getByTestId("workspace-share-save"));
|
||||
await settle();
|
||||
expect(m.setShares).not.toHaveBeenCalled();
|
||||
await act(async () => settleConfirm(true));
|
||||
await settle();
|
||||
expect(m.setShares).toHaveBeenCalledWith(7, [2, 3]);
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lists a collaborator disabled since, so they can be taken off", async () => {
|
||||
m.shares.mockResolvedValue({
|
||||
shares: [
|
||||
{ id: 2, username: "bob", name: "Bob", sharedAt: "" },
|
||||
{ id: 9, username: "dan", name: "Dan", sharedAt: "", disabled: true },
|
||||
],
|
||||
canManage: true,
|
||||
});
|
||||
render(<WorkspaceShareModal lane={lane} onClose={() => {}} />);
|
||||
await settle();
|
||||
const dan = screen.getByRole("checkbox", { name: /Dan/ });
|
||||
expect(dan).toHaveAttribute("aria-checked", "true");
|
||||
expect(dan).toHaveTextContent("(disabled)");
|
||||
fireEvent.click(dan);
|
||||
fireEvent.click(screen.getByTestId("workspace-share-save"));
|
||||
await settle();
|
||||
expect(m.setShares).toHaveBeenCalledWith(7, [2]);
|
||||
});
|
||||
|
||||
it("takes someone off without asking", async () => {
|
||||
render(<WorkspaceShareModal lane={lane} onClose={() => {}} />);
|
||||
await settle();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: /Bob/ }));
|
||||
fireEvent.click(screen.getByTestId("workspace-share-save"));
|
||||
await settle();
|
||||
expect(m.setShares).toHaveBeenCalledWith(7, []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkspaceRowMenu on a shared workspace", () => {
|
||||
const open = () =>
|
||||
render(<WorkspaceRowMenu lane={lane} x={0} y={0} onClose={() => {}} onAction={() => {}} />);
|
||||
|
||||
it("offers its owner Share, Rename and Delete", () => {
|
||||
open();
|
||||
expect(screen.getByTestId("workspace-menu-share")).toBeInTheDocument();
|
||||
expect(screen.getByText("Rename")).toBeInTheDocument();
|
||||
expect(screen.getByText("Delete workspace…")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers a user it is shared with none of the owner-only items", () => {
|
||||
perms.me = 2;
|
||||
open();
|
||||
expect(screen.queryByTestId("workspace-menu-share")).toBeNull();
|
||||
expect(screen.queryByText("Rename")).toBeNull();
|
||||
expect(screen.queryByText("Delete workspace…")).toBeNull();
|
||||
expect(screen.getByText("Copy path")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("has no Share in local mode", () => {
|
||||
perms.local = true;
|
||||
open();
|
||||
expect(screen.queryByTestId("workspace-menu-share")).toBeNull();
|
||||
expect(screen.getByText("Rename")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkspaceShareModal for one session", () => {
|
||||
it("reads and saves that session's own list, never the workspace's", async () => {
|
||||
m.shares.mockClear();
|
||||
m.setShares.mockClear();
|
||||
m.sessionShares.mockResolvedValue({ shares: [], canManage: true });
|
||||
m.setSessionShares.mockResolvedValue({
|
||||
shares: [{ id: 3, username: "carol", name: "Carol", sharedAt: "" }],
|
||||
});
|
||||
render(
|
||||
<WorkspaceShareModal
|
||||
lane={lane}
|
||||
session={{ id: "s-1", name: "Fix cart" }}
|
||||
onClose={() => {}}
|
||||
/>
|
||||
);
|
||||
await settle();
|
||||
expect(m.sessionShares).toHaveBeenCalledWith(7, "s-1");
|
||||
expect(m.shares).not.toHaveBeenCalled();
|
||||
expect(screen.getByText("Share session")).toBeTruthy();
|
||||
expect(screen.getByText("Fix cart")).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: /Carol/ }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
await settle();
|
||||
await act(async () => settleConfirm(true));
|
||||
await settle();
|
||||
expect(m.setSessionShares).toHaveBeenCalledWith(7, "s-1", [3]);
|
||||
expect(m.setShares).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -85,6 +85,8 @@ import {
|
||||
slotOfKey,
|
||||
} from "../../lib/paneLayout";
|
||||
import { ContextMenu, MenuItem, MenuSeparator, useContextMenu } from "../ContextMenu";
|
||||
import { useAuth } from "../AuthGate";
|
||||
import { usePanePresence } from "../../hooks/usePanePresence";
|
||||
|
||||
type AiToolsState = ReturnType<typeof useAiTools>;
|
||||
|
||||
@@ -234,6 +236,19 @@ export function ConsoleTabs({
|
||||
const tabRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const tabCtx = useContextMenu<Tab>();
|
||||
// Server mode: who else has these panes open, and whose money a pane is.
|
||||
const presence = usePanePresence(lane.id);
|
||||
const { state: auth } = useAuth();
|
||||
const meId = auth.mode === "server" ? auth.user?.id : undefined;
|
||||
const othersIn = (tab: Tab) => {
|
||||
const seen = new Map<number, { id: number; name: string }>();
|
||||
for (const r of tab.runs) {
|
||||
for (const u of presence[r.id] ?? []) if (u.id !== meId) seen.set(u.id, u);
|
||||
}
|
||||
return [...seen.values()];
|
||||
};
|
||||
const billedTo = (tab: Tab) =>
|
||||
[...new Set(tab.runs.map((r) => r.startedBy?.name).filter(Boolean))] as string[];
|
||||
|
||||
// A group whose runs the list has not caught up with yet is not drawn.
|
||||
const tabs = useMemo<Tab[]>(
|
||||
@@ -532,6 +547,7 @@ export function ConsoleTabs({
|
||||
{tabs.map((tab, i) => {
|
||||
const active = !settings?.active && tab.index === groups.active;
|
||||
const single = tab.runs.length === 1 ? tab.focus : null;
|
||||
const others = othersIn(tab);
|
||||
const state = tabState(tab);
|
||||
if (single && renaming === single.id) {
|
||||
return (
|
||||
@@ -606,7 +622,7 @@ export function ConsoleTabs({
|
||||
// Ctrl/Cmd+click brings a one-pane tab into the tab on screen.
|
||||
onClick={(e) => onOpen(tab.focus.id, !!single && (e.ctrlKey || e.metaKey))}
|
||||
onDoubleClick={() => single && startRename(single)}
|
||||
title={
|
||||
title={[
|
||||
single
|
||||
? [
|
||||
toolLabel(single),
|
||||
@@ -617,8 +633,14 @@ export function ConsoleTabs({
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n")
|
||||
: tab.runs.map((r) => `${toolLabel(r)} — ${label(r)}`).join("\n")
|
||||
}
|
||||
: tab.runs.map((r) => `${toolLabel(r)} — ${label(r)}`).join("\n"),
|
||||
...billedTo(tab).map((name) => t("tabs.billedTo", { name })),
|
||||
others.length
|
||||
? t("tabs.here", { names: others.map((u) => u.name).join(", ") })
|
||||
: null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n")}
|
||||
className="flex h-full min-w-0 items-center gap-2 pl-3 pr-1.5 text-sm"
|
||||
>
|
||||
<span className="flex shrink-0 items-center gap-1">
|
||||
@@ -627,6 +649,23 @@ export function ConsoleTabs({
|
||||
))}
|
||||
</span>
|
||||
<span className="truncate">{tabLabel(tab)}</span>
|
||||
{others.length > 0 && (
|
||||
<span
|
||||
data-testid={`console-tab-people-${tab.key}`}
|
||||
className="flex shrink-0 -space-x-1"
|
||||
aria-label={t("tabs.here", { names: others.map((u) => u.name).join(", ") })}
|
||||
>
|
||||
{others.slice(0, 3).map(({ id, name }) => (
|
||||
<span
|
||||
key={id}
|
||||
aria-hidden
|
||||
className="flex h-4 w-4 items-center justify-center rounded-full border border-surface-1 bg-accent-solid text-[9px] font-semibold uppercase text-white"
|
||||
>
|
||||
{name.slice(0, 1)}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
{state && <RunDot state={state} />}
|
||||
</button>
|
||||
{tab.runs.some(canSleep) && (
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* @file ConsoleTabs.presence.test.tsx
|
||||
* @description Workspace sharing phase 4 on the tab bar: a tab shows who ELSE
|
||||
* has its panes open (never the viewer), and its tooltip says whose money a
|
||||
* pane a collaborator opened is.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import "../../../i18n";
|
||||
import type { RunHandle } from "../../../lib/api";
|
||||
import type { Lane } from "../../../lib/types";
|
||||
import { pane, type PaneGroups } from "../../../lib/paneLayout";
|
||||
import { ConsoleTabs } from "../ConsoleTabs";
|
||||
|
||||
vi.mock("../../../lib/api", () => ({
|
||||
api: {
|
||||
aiTools: {
|
||||
list: vi.fn().mockResolvedValue({ default: "claude", tools: [] }),
|
||||
models: vi.fn().mockResolvedValue({ flag: true, models: [], defaultModel: null }),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("../../AuthGate", () => ({
|
||||
useAuth: () => ({ state: { mode: "server", user: { id: 1, username: "alice" } } }),
|
||||
usePermissions: () => ({ local: false, isAdmin: false }),
|
||||
}));
|
||||
vi.mock("../../../hooks/usePanePresence", () => ({
|
||||
usePanePresence: () => ({
|
||||
"agenthub-lane-1": [
|
||||
{ id: 1, name: "Alice" },
|
||||
{ id: 2, name: "Bob" },
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
const LANE = { id: 1, tool: "claude", cwd: "/w", title: "w" } as unknown as Lane;
|
||||
const RUN: RunHandle = {
|
||||
id: "agenthub-lane-1",
|
||||
laneId: 1,
|
||||
slot: 0,
|
||||
status: "running",
|
||||
cwd: "/w",
|
||||
model: null,
|
||||
permissionMode: null,
|
||||
effort: null,
|
||||
resumeSessionId: null,
|
||||
sessionId: null,
|
||||
startedAt: null,
|
||||
promptPreview: null,
|
||||
startedBy: { id: 2, name: "Bob" },
|
||||
tool: "claude",
|
||||
};
|
||||
const GROUPS: PaneGroups = { groups: [{ root: pane(0), focus: 0 }], active: 0 };
|
||||
|
||||
describe("ConsoleTabs presence", () => {
|
||||
it("shows who else is in a pane, and whose money it is", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ConsoleTabs
|
||||
lane={LANE}
|
||||
tabs={[RUN]}
|
||||
groups={GROUPS}
|
||||
onGroupsChange={vi.fn()}
|
||||
onOpen={vi.fn()}
|
||||
onClosed={vi.fn()}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
const people = screen.getAllByTestId(/^console-tab-people-/)[0]!;
|
||||
expect(people.textContent).toBe("B");
|
||||
expect(people.getAttribute("aria-label")).toBe("Also here: Bob");
|
||||
const tab = screen.getAllByRole("tab")[0]!;
|
||||
expect(tab.getAttribute("title")).toContain("Billed to Bob");
|
||||
expect(tab.getAttribute("title")).not.toContain("Alice");
|
||||
});
|
||||
});
|
||||
@@ -53,12 +53,16 @@ function load(): Promise<void> {
|
||||
}
|
||||
|
||||
function onMessage(msg: WSMessage) {
|
||||
// A workspace shared with this user, or taken back: re-read the list.
|
||||
if (msg.type === "lane_access") return void load();
|
||||
if (msg.type !== "lane_update") return;
|
||||
const payload = msg.data as { lane?: Lane; removed?: number };
|
||||
const lane = payload.lane;
|
||||
if (payload.removed !== undefined || !lane || !lanes) return void load();
|
||||
const i = lanes.findIndex((l) => l.id === lane.id);
|
||||
if (i === -1) return void load();
|
||||
// A broadcast carries no viewer's `access`: a lane seen through a shared
|
||||
// session re-reads it (its access may have changed too).
|
||||
if (i === -1 || lanes[i]?.access) return void load();
|
||||
const next = [...lanes];
|
||||
next[i] = lane;
|
||||
publish(next);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @file usePanePresence.ts
|
||||
* @description Who has each of a workspace's panes open (server mode, workspace
|
||||
* sharing phase 4): `GET /api/lanes/:id/presence` once, then every
|
||||
* `pane_presence` frame for that workspace, and a re-read on a WebSocket
|
||||
* reconnect (frames missed while away are never replayed). Local mode has
|
||||
* one user and reads nothing. Returns `{runId: [{id, name}]}`.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { api } from "../lib/api";
|
||||
import { eventBus } from "../lib/eventBus";
|
||||
import { usePermissions } from "../components/AuthGate";
|
||||
|
||||
export type PanePeople = Record<string, { id: number; name: string }[]>;
|
||||
|
||||
export function usePanePresence(laneId: number | null | undefined): PanePeople {
|
||||
const { local } = usePermissions();
|
||||
const [panes, setPanes] = useState<PanePeople>({});
|
||||
useEffect(() => {
|
||||
setPanes({});
|
||||
if (local || laneId == null) return;
|
||||
let alive = true;
|
||||
const load = () =>
|
||||
Promise.resolve()
|
||||
.then(() => api.lanes.presence(laneId))
|
||||
.then((r) => alive && setPanes(r.panes))
|
||||
.catch(() => {
|
||||
/* presence is a nicety: no list, no chips */
|
||||
});
|
||||
void load();
|
||||
const offMsg = eventBus.subscribe((msg) => {
|
||||
if (msg.type !== "pane_presence") return;
|
||||
const d = msg.data as { laneId?: number; runId?: string; users?: PanePeople[string] };
|
||||
if (d.laneId !== laneId || !d.runId) return;
|
||||
setPanes((prev) => {
|
||||
const next = { ...prev };
|
||||
if (d.users?.length) next[d.runId!] = d.users;
|
||||
else delete next[d.runId!];
|
||||
return next;
|
||||
});
|
||||
});
|
||||
const offConn = eventBus.onConnection((up) => {
|
||||
if (up) void load();
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
offMsg();
|
||||
offConn();
|
||||
};
|
||||
}, [laneId, local]);
|
||||
return panes;
|
||||
}
|
||||
@@ -386,6 +386,32 @@
|
||||
"menu.copyPath": "Copy path",
|
||||
"menu.reset": "Reset worktree…",
|
||||
"menu.remove": "Delete workspace…",
|
||||
"menu.share": "Share…",
|
||||
"share.title": "Share workspace",
|
||||
"share.what": "People you share it with see this workspace and its sessions, join its open terminals, type into them and commit — like you. Only you rename, reset, delete or share it. A session they start runs on their own account and is billed to them.",
|
||||
"share.warning": "They work as YOUR account on this server: they can read everything in your home folder (your other workspaces, SSH keys and AI logins) and their commits carry your name. Share only with people you would hand your keyboard to.",
|
||||
"share.loading": "Loading…",
|
||||
"share.nobody": "There is no one else to share with.",
|
||||
"share.search": "Search people",
|
||||
"share.cancel": "Cancel",
|
||||
"share.close": "Close",
|
||||
"share.save": "Save",
|
||||
"share.saving": "Saving…",
|
||||
"share.confirmTitle": "Share \"{{name}}\"?",
|
||||
"share.confirmBody": "{{people}} will work in it as your account and can read everything in your home folder.",
|
||||
"share.confirm": "Share",
|
||||
"share.saved_one": "Shared with {{count}} person",
|
||||
"share.saved_other": "Shared with {{count}} people",
|
||||
"share.disabled": "(disabled)",
|
||||
"share.savedNone": "No longer shared with anyone",
|
||||
"shared.ownAccount": "This workspace is shared with you: a session you start here runs on your own account — a pool account or an AI Proxy of yours — and is billed to you.",
|
||||
"share.sessionTitle": "Share session",
|
||||
"share.sessionWhat": "People you share it with see this session and the workspace's changes, join its open tab, type into it, send it messages (on their own account, billed to them) and commit — nothing else of the workspace. Only you share it. On this server they work as YOUR account inside its terminal, so they can still reach the rest of your home from there.",
|
||||
"sessionMenu.share": "Share…",
|
||||
"shared.sessionOnly": "Only a session of this workspace is shared with you: open it from the list to work in it.",
|
||||
"tabs.billedTo": "Billed to {{name}}",
|
||||
"tabs.here": "Also here: {{names}}",
|
||||
"shared.badge": "Shared with you",
|
||||
"panel.changes": "Changes",
|
||||
"panel.analyst": "Analyst",
|
||||
"panel.preview": "Preview",
|
||||
|
||||
@@ -386,6 +386,32 @@
|
||||
"menu.copyPath": "Sao chép đường dẫn",
|
||||
"menu.reset": "Đặt lại worktree…",
|
||||
"menu.remove": "Xóa workspace…",
|
||||
"menu.share": "Chia sẻ…",
|
||||
"share.title": "Chia sẻ workspace",
|
||||
"share.what": "Người được chia sẻ thấy workspace này và các session của nó, vào được terminal đang mở, gõ và commit — như bạn. Chỉ bạn được đổi tên, đặt lại, xoá hay chia sẻ nó. Session họ mở chạy bằng tài khoản của chính họ và tính tiền cho họ.",
|
||||
"share.warning": "Họ làm việc bằng TÀI KHOẢN CỦA BẠN trên server này: đọc được mọi thứ trong thư mục home của bạn (các workspace khác, SSH key, đăng nhập AI) và commit của họ mang tên bạn. Chỉ chia sẻ với người bạn tin như đưa bàn phím cho họ.",
|
||||
"share.loading": "Đang tải…",
|
||||
"share.nobody": "Không còn ai khác để chia sẻ.",
|
||||
"share.search": "Tìm người",
|
||||
"share.cancel": "Huỷ",
|
||||
"share.close": "Đóng",
|
||||
"share.save": "Lưu",
|
||||
"share.saving": "Đang lưu…",
|
||||
"share.confirmTitle": "Chia sẻ \"{{name}}\"?",
|
||||
"share.confirmBody": "{{people}} sẽ làm việc trong đó bằng tài khoản của bạn và đọc được mọi thứ trong thư mục home của bạn.",
|
||||
"share.confirm": "Chia sẻ",
|
||||
"share.saved_one": "Đã chia sẻ với {{count}} người",
|
||||
"share.saved_other": "Đã chia sẻ với {{count}} người",
|
||||
"share.disabled": "(đã vô hiệu hoá)",
|
||||
"share.savedNone": "Không còn chia sẻ với ai",
|
||||
"shared.ownAccount": "Workspace này được chia sẻ với bạn: session bạn mở ở đây chạy bằng tài khoản của chính bạn — tài khoản pool hoặc AI Proxy của bạn — và tính tiền cho bạn.",
|
||||
"share.sessionTitle": "Chia sẻ session",
|
||||
"share.sessionWhat": "Người được chia sẻ thấy session này và các thay đổi của workspace, vào tab đang mở, gõ, gửi tin nhắn cho nó (bằng tài khoản của họ, tính tiền cho họ) và commit — không gì khác của workspace. Chỉ bạn chia sẻ được. Trên server này họ làm việc bằng TÀI KHOẢN CỦA BẠN trong terminal của nó, nên từ đó họ vẫn với tới được phần còn lại trong home của bạn.",
|
||||
"sessionMenu.share": "Chia sẻ…",
|
||||
"shared.sessionOnly": "Chỉ một session của workspace này được chia sẻ với bạn: mở nó từ danh sách để làm việc.",
|
||||
"tabs.billedTo": "Tính tiền cho {{name}}",
|
||||
"tabs.here": "Cũng đang mở: {{names}}",
|
||||
"shared.badge": "Được chia sẻ với bạn",
|
||||
"panel.changes": "Thay đổi",
|
||||
"panel.analyst": "Analyst",
|
||||
"panel.preview": "Xem trang",
|
||||
|
||||
@@ -940,6 +940,15 @@ export type PoolProfile = {
|
||||
subscriptionType: string | null;
|
||||
active: boolean;
|
||||
};
|
||||
/** A user a workspace is shared with (`/api/lanes/:id/shares`) — names only. */
|
||||
export type LaneShare = {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
sharedAt: string;
|
||||
/** Disabled since it was shared: kept on the list, granting nothing. */
|
||||
disabled?: boolean;
|
||||
};
|
||||
/** A login profile of a tool other than Claude (`/api/tool-profiles`) — never a token. */
|
||||
export type ToolProfileIdentity = {
|
||||
/** codex: `chatgpt` | `apikey`; omp: `credentials`. */
|
||||
@@ -5095,6 +5104,31 @@ export const api = {
|
||||
}),
|
||||
/** DELETE /api/lanes/:id/sources/:sourceId — a folder stays on disk; an
|
||||
* uploaded file's AgentHub copy is deleted. */
|
||||
/** GET /api/lanes/:id/shares — the users a workspace is shared with (server mode). */
|
||||
shares: (id: number) =>
|
||||
request<{ shares: LaneShare[]; canManage: boolean }>(`/workspaces/${id}/shares`),
|
||||
/** PUT /api/lanes/:id/shares — the WHOLE list (owner or admin; `ENOTOWNER` else). */
|
||||
setShares: (id: number, userIds: number[]) =>
|
||||
request<{ shares: LaneShare[] }>(`/workspaces/${id}/shares`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ userIds }),
|
||||
}),
|
||||
/** GET /api/lanes/:id/presence — who has which pane open (server mode). */
|
||||
presence: (id: number) =>
|
||||
request<{ panes: Record<string, { id: number; name: string }[]> }>(
|
||||
`/workspaces/${id}/presence`
|
||||
),
|
||||
/** GET /api/lanes/:id/sessions/:sid/shares — the users one session is shared with. */
|
||||
sessionShares: (id: number, sid: string) =>
|
||||
request<{ shares: LaneShare[]; canManage: boolean }>(
|
||||
`/workspaces/${id}/sessions/${encodeURIComponent(sid)}/shares`
|
||||
),
|
||||
/** PUT /api/lanes/:id/sessions/:sid/shares — the WHOLE list (owner or admin). */
|
||||
setSessionShares: (id: number, sid: string, userIds: number[]) =>
|
||||
request<{ shares: LaneShare[] }>(
|
||||
`/workspaces/${id}/sessions/${encodeURIComponent(sid)}/shares`,
|
||||
{ method: "PUT", body: JSON.stringify({ userIds }) }
|
||||
),
|
||||
removeSource: (id: number, sourceId: number) =>
|
||||
request<LaneSourcesView>(`/workspaces/${id}/sources/${sourceId}`, { method: "DELETE" }),
|
||||
/** GET /api/lanes/:id/memory — CLAUDE.md/AGENTS.md and Claude's auto memory, read-only. */
|
||||
@@ -6496,6 +6530,9 @@ export interface RunHandle {
|
||||
startedAt: string | null;
|
||||
/** Initial prompt preview (first 500 chars), null when not provided. */
|
||||
promptPreview: string | null;
|
||||
/** Server mode: a user the workspace is shared with opened it — they pay
|
||||
* for it. Null/absent = the workspace's owner. */
|
||||
startedBy?: { id: number; name: string } | null;
|
||||
tool: LaneTool;
|
||||
}
|
||||
|
||||
|
||||
@@ -1942,6 +1942,10 @@ export interface WSMessage {
|
||||
| "remote_source.status"
|
||||
| "remote_data.updated"
|
||||
| "lane_update"
|
||||
/** A workspace was shared with / taken back from the users named (`userIds`). */
|
||||
| "lane_access"
|
||||
/** Who has a pane open changed: `{laneId, runId, users}` (pane-presence.js). */
|
||||
| "pane_presence"
|
||||
/** One output line from a lane's profile hook, while it runs. */
|
||||
| "lane_hook_output"
|
||||
/** A lane's stack finished coming up (or failed to), with fresh facts. */
|
||||
@@ -2706,6 +2710,8 @@ export interface Lane {
|
||||
owner_display_name?: string | null;
|
||||
/** When the owner's avatar was last set (`users.avatar_at`); null = none. */
|
||||
owner_avatar_at?: string | null;
|
||||
/** Server mode: `"session"` when only sessions of it are shared with this viewer. */
|
||||
access?: "session";
|
||||
branch: string | null;
|
||||
kind: "managed" | "adopted";
|
||||
/** The CLI this lane's runs spawn. Immutable once the lane exists. */
|
||||
|
||||
@@ -7316,7 +7316,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
<span
|
||||
class="text-status-warning/90"
|
||||
>
|
||||
UI build v2.8.77 (rebuild client to match)
|
||||
UI build v2.8.78 (rebuild client to match)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
+52
@@ -2098,6 +2098,58 @@ POST /api/locks/:name/release
|
||||
- **409** `{ "error": { "code": "ENOTHOLDER", "message": "...", "currentHolder": "lane1" } }` — `holder` doesn't match the current owner; a release never trusts its caller, same rule every other destructive path in this project follows.
|
||||
- **404** `{ "error": { "code": "ENOLOCK", "message": "no such lock: build" } }` — nothing by that name is held.
|
||||
|
||||
#### Sharing a workspace (server mode)
|
||||
|
||||
```http
|
||||
GET /api/lanes/:id/shares → { shares: [{id, username, name, sharedAt}], canManage }
|
||||
PUT /api/lanes/:id/shares {"userIds": [2, 5]} → { shares }
|
||||
```
|
||||
|
||||
The users a workspace is shared with (`lane_shares`, names only). `PUT` takes the
|
||||
WHOLE list — at most 200 enabled users, never the owner (`400 EBADUSER`) — from the
|
||||
owner or an admin only (`403 ENOTOWNER`), same-origin, each change audited. Local
|
||||
mode: `GET` answers an empty list, `PUT` `400 ELOCALMODE`. A user it is shared with
|
||||
sees and works in it like its owner, but `PATCH {title}`, `reset`/`remove`/`purge`,
|
||||
`DELETE` and `PUT …/shares` answer them `403 ENOTOWNER`. A session they start or
|
||||
resume (`POST /api/lanes/:id/start`, `POST /api/run`) runs on THEIR OWN account —
|
||||
a pool setup-token (Claude) or API key (Codex, Cursor) they may use, or an AI
|
||||
Proxy of theirs — else `409 ENOCOLLABACCOUNT`; resuming a non-Claude session the other side pays
|
||||
for, or a collaborator's `resumeLast`, is `409 ECOLLABRESUME`; their spend quota (`429 EQUOTA`)
|
||||
decides, not the owner's. Every pane they open (a Terminal tab too) records them
|
||||
in `dashboard_runs.started_by`: its pane token acts as them, and an AI pane's
|
||||
session hours are billed to them (`session_payers`; a Terminal tab's stay the
|
||||
owner's). A user disabled since stays on the
|
||||
list (`disabled: true`) and may be kept or removed; only a new one must be enabled. Users taken off
|
||||
get the WebSocket message `lane_access` `{laneId, userIds}` (sent to them only). See
|
||||
`docs/SERVER-MODE.md` → Sharing a workspace. A collaborator's pane token
|
||||
answers only that workspace's reads, the workspace list (filtered to it), its
|
||||
stage / up / down / hook / feature / mcp-sync writes and `/api/health`
|
||||
(`403 EPANESCOPE` — never a start or resume).
|
||||
|
||||
```http
|
||||
GET /api/lanes/:id/presence → { panes: { "<run id>": [{id, name}] } }
|
||||
```
|
||||
|
||||
Who has which pane open (server mode; local mode `{panes: {}}`), in memory;
|
||||
changes come as the WebSocket message `pane_presence` `{laneId, runId, users}`
|
||||
to the workspace's owner and full collaborators. A run handle
|
||||
(`GET /api/run`) carries `startedBy: {id, name}` when a collaborator opened
|
||||
it — they pay for it. The first keystroke of a terminal attach into a shared
|
||||
workspace's pane by anyone but its owner is audited (`type into <run id>`).
|
||||
|
||||
```http
|
||||
GET /api/lanes/:id/sessions/:sid/shares → { shares, canManage }
|
||||
PUT /api/lanes/:id/sessions/:sid/shares {"userIds": [3]} → { shares }
|
||||
```
|
||||
|
||||
One session shared on its own (`session_shares`), same rules as the workspace
|
||||
list (owner or admin, enabled users, audited `share session <id>`, `404
|
||||
ENOSESSION` for a session of another workspace). The user gets the workspace
|
||||
in `GET /api/lanes` with `access: "session"`, only that session in its session
|
||||
lists, the pane holding it, a resume of it (`start {resumeSessionId}` — no
|
||||
fork, no new session, no shell), and the workspace's git/Files reads and git
|
||||
writes; any other call on the workspace answers `403 ESESSIONSHARE`.
|
||||
|
||||
#### Workspace context: instructions, folders, context files, memory
|
||||
|
||||
```http
|
||||
|
||||
+113
-1
@@ -152,7 +152,8 @@ Workspaces made before server mode, or by the host account, have none.
|
||||
- A session belongs to the workspace that owns it: `sessions.lane_id`, or the
|
||||
workspace whose pane holds it. Its agents, events, tokens, cost, alerts,
|
||||
snapshots and workflow runs belong to that session.
|
||||
- A **developer** sees only rows of their own workspaces, everywhere: lists,
|
||||
- A **developer** sees only rows of their own workspaces (and of workspaces
|
||||
shared with them — see [Sharing a workspace](#sharing-a-workspace)), everywhere: lists,
|
||||
counts, charts, cost, the Sessions/Events/Agents tables, exports, live
|
||||
WebSocket updates and terminals. A request naming someone else's row (in the
|
||||
path, the query or the body) gets `404 ENOTFOUND`, the same answer as a row
|
||||
@@ -235,6 +236,117 @@ hides them for developers. The command and skill lists show a developer only the
|
||||
own workspaces' project items: `?cwd=` outside one of them answers
|
||||
`403 EFOLDER`, and with no `cwd` they list no project items at all.
|
||||
|
||||
### Sharing a workspace
|
||||
|
||||
A workspace's owner (or an admin) shares it with other users from its `⋯`
|
||||
menu → **Share…** (`WorkspaceShareModal`, `GET/PUT /api/lanes/:id/shares`,
|
||||
table `lane_shares`). There is one level: **collaborate**. A user it is shared
|
||||
with sees the workspace, its sessions, Changes, history and Files like its
|
||||
owner, joins its open terminals, types into them, commits and pushes, edits its
|
||||
instructions and context — every row and live update, through the same
|
||||
`scope.js` predicates (`canSeeLane`, `sessionWhere`, `laneWhere`,
|
||||
`broadcastAudience`'s `viewers`). Only the owner or an admin renames, resets,
|
||||
removes, deletes or shares it (`403 ENOTOWNER`).
|
||||
|
||||
**Whoever starts or resumes a session pays for it.** A session a collaborator
|
||||
starts or resumes runs on THEIR OWN account and never on the owner's login
|
||||
(`spawnRun` `startedBy`): a pool **setup-token** (Claude) or **API key**
|
||||
(Codex, Cursor) their pool group, pin or choice allows (`forCollaborator` —
|
||||
never a pool *login*, which would be written into the owner's home), or an AI
|
||||
Proxy profile of theirs (resolved as them; the gateway relays it). With none,
|
||||
the start is refused (`409 ENOCOLLABACCOUNT`); omp and every other tool, which
|
||||
can only run on the folder account's own login, are refused too. Their own
|
||||
spend quota decides (`EQUOTA`), their pane's hooks read their own flag
|
||||
(`quota-u<id>.json` in the owner's handoff dir under S3, `u<id>.json` on the
|
||||
host), and a quota sweep ends or blocks only the panes THEY pay for
|
||||
(`runPayer`). Money is per hour (`session_payers`, `server/lib/session-payers.js`):
|
||||
a session nobody else ran has no row and is billed exactly as before; a session
|
||||
a collaborator started is theirs from its first hour; a resume changes hands
|
||||
from the NEXT hour (the hour it happens in stays with the previous payer), in
|
||||
either direction. Only a Claude session books its spend by the hour, so only
|
||||
it can change hands: a Codex/Cursor/other session is billed whole at its start
|
||||
hour, and resuming one the other side pays for is refused (`409
|
||||
ECOLLABRESUME`), as is a collaborator's `resumeLast` (it names no session).
|
||||
A Claude session's sub-agent usage is likewise booked at the session's start
|
||||
hour, so after a hand-over it stays with the first payer — an accepted
|
||||
rounding. A Terminal tab stays the owner's money: a `claude` typed there runs
|
||||
on the folder account's own login. The Users page, spend quotas, Today (`/api/pricing/cost?mine=1`)
|
||||
and a developer's budgets all count by payer; the workspace owner's agent
|
||||
instructions still go into every pane of the workspace. `MAX_AI_SESSIONS` counts
|
||||
per Linux account, so a collaborator's sessions count against the owner's
|
||||
account limit.
|
||||
|
||||
**Under S3 a collaborator works as the OWNER's Linux account** — the folder
|
||||
decides the account. They can read everything in the owner's home (the owner's
|
||||
other workspaces, SSH keys, AI logins, the pane tokens of the owner's panes)
|
||||
and their commits carry the owner's git identity; only AgentHub's `audit_log`
|
||||
records who did what. The Share dialog says so. Share only with people you
|
||||
would hand your keyboard to. Two consequences follow and are accepted, not
|
||||
bugs: a collaborator can read the pane token of a pane the OWNER started (and
|
||||
so act as the owner through the CLI from it), and `ENOCOLLABACCOUNT` is a
|
||||
dashboard rule, not a barrier — in a terminal they can run `claude` as the
|
||||
owner's account on the owner's login, and either side can edit the other's
|
||||
quota flag file in that home (the flag is fail-open anyway; the start check is
|
||||
server-side). A collaborator's personal Codex proxy writes no key into the
|
||||
owner's home, only its endpoint. Every pane the collaborator opens records them
|
||||
as its starter (`dashboard_runs.started_by`), so its own pane token acts as
|
||||
THEM, and only while the workspace is still shared with them
|
||||
(`userFromPaneToken`).
|
||||
|
||||
A user already on the list who was disabled since stays listed (marked
|
||||
disabled, granting nothing) and can be taken off; only a NEW addition must be
|
||||
enabled. Every share and unshare is audited (`share workspace <id>` /
|
||||
`unshare workspace <id>`). Taking it back sends the users taken off
|
||||
`lane_access` (their list re-reads) and closes their open terminals on it at
|
||||
the next attach re-check. Deleting the workspace, or the user, drops the rows;
|
||||
giving the workspace to a user it was shared with drops theirs.
|
||||
|
||||
**A collaborator's pane token acts as them inside that workspace only.** The
|
||||
owner's account can read it (it sits in the owner's home), so it answers only
|
||||
reads of `/api/lanes/<that id>/…` (and `/api/workspaces/<id>/…`), the
|
||||
workspace list (which then holds that workspace only), `/api/health`, and its
|
||||
`stage`, `up`, `down`, `hook/<name>`, `features/activate` and `mcp/sync`
|
||||
writes (`paneLane`, `403 EPANESCOPE` for everything else) — never a start,
|
||||
resume or any other call that could bill them. The CLI's workspace commands
|
||||
work from their pane; the MCP server and the statusline's spend line do not.
|
||||
A pane the owner or an admin opens still acts as the owner.
|
||||
|
||||
**Who is here, and who pays.** A pane's tab shows the other people who have
|
||||
it open (`pane_presence`, `GET /api/lanes/:id/presence`, in memory — never
|
||||
the viewer themself), and its tooltip says "Billed to <name>" for a pane a
|
||||
collaborator opened (`startedBy` on the run). The first keystroke of each
|
||||
terminal attach into a SHARED workspace's pane (whole or one session of it)
|
||||
by anyone but its owner is written to the audit log as `type into <run id>` —
|
||||
who typed where, never what (mouse, focus and the terminal's own answers to
|
||||
tmux do not count); the Chat composer types through the same attach, so its
|
||||
prompts are covered too. A terminal that stops answering pings (a sleeping
|
||||
laptop) is ended at the next re-check, and its presence with it.
|
||||
|
||||
#### Sharing one session
|
||||
|
||||
The owner (or an admin) can also share ONE session: right-click it in the
|
||||
sidebar → **Share…** (`GET/PUT /api/lanes/:id/sessions/:sid/shares`, table
|
||||
`session_shares`, audited as `share session <id>`). The user sees the
|
||||
workspace in their list (`access: "session"`) with only that session in it,
|
||||
attaches to the pane holding it, sends it messages (a resume, on their own
|
||||
account and billed to them, as above) and uses the workspace's Changes, git
|
||||
and Files reads and git writes. Everything else of the workspace — another
|
||||
session, a new session, a fork, a Terminal tab, `/api/run`, its instructions,
|
||||
context and settings — answers `403 ESESSIONSHARE` (`sessionShareAllows` in
|
||||
`scope.js`, checked in `scopeGuard`). Their run lists show only runs that held
|
||||
that session, and a pane switching to another session closes their terminal
|
||||
at the next attach re-check. Taking it back, deleting the workspace or the
|
||||
user drops the rows. A resume names a free slot (`slot: "auto"`, never pane
|
||||
0) and a session of THAT workspace; the session's name and archive state stay
|
||||
the owner's (`PATCH /api/sessions/<id>` is `ESESSIONSHARE`), and the
|
||||
workspace's extra folders (`?source=`), its files list for Artifacts and its
|
||||
stage history stay out of reach. **These limits hold for the dashboard's API
|
||||
only.** Under S3 the pane runs as the owner's Linux account: inside it the
|
||||
user can `/resume` any session of the folder, run shell commands and read the
|
||||
owner's home — a session share hands over as much as a workspace share
|
||||
there. The Share dialog says so; share only with people you would hand your
|
||||
keyboard to.
|
||||
|
||||
### AI Proxy profiles
|
||||
|
||||
Each user may keep **personal** AI Proxy profiles beside the **shared** ones:
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
# Workspace & session sharing — plan
|
||||
|
||||
Status: **phases 1–4 built 2026-11-06** (workspace sharing; collaborators run on their own account, billed per payer by hour — `session_payers`; one session can be shared — `session_shares`; pane presence + typing audit; R1 decided as option **(a)** — accept and warn hard).
|
||||
An independent review of phase 1 found and got fixed: a collaborator's Terminal
|
||||
tab acted as the owner through its pane token (now `dashboard_runs.started_by`),
|
||||
`POST /api/run {shell:true}` bypassed `ECOLLABSTART`, a disabled collaborator
|
||||
locked the share list, and the home's prompt box let a collaborator type into a
|
||||
Start that always failed. Accepted under (a): the owner's own panes' tokens are
|
||||
readable by a collaborator, and `ECOLLABSTART` is advisory under S3.
|
||||
|
||||
Server mode only. In local mode there are no users, so there is nothing to share
|
||||
and every piece below is a no-op (`isServerMode()`).
|
||||
|
||||
## What the user asked for
|
||||
|
||||
Members of the same AgentHub install work together on one workspace or one
|
||||
session. Decisions taken with the repo owner (2026-11-06):
|
||||
|
||||
| Question | Decision |
|
||||
| --- | --- |
|
||||
| What may a person it is shared with do? | **Always collaborate** — the same as the owner inside that workspace/session: type into panes, send prompts, start sessions, commit, push. No view-only level. |
|
||||
| Unit of sharing | **Both** — a whole workspace (every session, present and future) or a single session. |
|
||||
| Who pays for a session a collaborator starts? | **The person who opens it** — its tokens, cost and spend quota are theirs, not the workspace owner's. |
|
||||
| Whose AI subscription does a collaborator's run use? | **Their own, or none**: only a pool account of kind `token` that the collaborator may use (passed by env). With a `login`-kind pool or no pool the run is **refused** (`ENOCOLLABACCOUNT`) — a collaborator never spends the owner's subscription. |
|
||||
| Spend quota | **Only the payer's** (the person who started or resumed the run). The owner's quota is not involved. |
|
||||
| A collaborator resumes someone else's session | **The resumer pays from then on** — billing is per RUN, not per session (below). |
|
||||
| Session-only share and git | **Allowed** — commit/push in that session's tree, like everything else. |
|
||||
| Sharing with an analyst | **Allowed** — a shared workspace counts as their own for writes. |
|
||||
|
||||
## The one fact everything else follows from (S3)
|
||||
|
||||
Under S3 a pane runs as the Linux account of its **folder**
|
||||
(`accountForPath`, `server/lib/run-as.js`), and only the folder's account may
|
||||
own a workspace there (`assertOwnerFits`, `EOWNERFOLDER`). Sharing does **not**
|
||||
change that: a collaborator's work in Alice's workspace runs as `ah-alice`.
|
||||
|
||||
What that means, and the UI must say it once, plainly, in the Share dialog:
|
||||
|
||||
- **Git identity, SSH key, HTTPS store, commit signing are the owner's.** A
|
||||
collaborator's commit is authored by the owner (`git config --global` of the
|
||||
owner's account). AgentHub's `audit_log` records who clicked; git does not.
|
||||
- **Files written are the owner's.** Everything a collaborator's session
|
||||
creates belongs to `ah-alice`.
|
||||
- **The owner's `~/.claude` applies** — their skills, memory, MCP servers,
|
||||
settings — to the collaborator's sessions too.
|
||||
- **The owner's account can read the collaborator's pane token** (it is in a
|
||||
launch file in the owner's home, like every pane secret). So the collaborator's
|
||||
token must be scoped to the shared workspace only (below), never their whole
|
||||
account.
|
||||
|
||||
There is no way around these without moving the folder to a shared account —
|
||||
out of scope. Sharing is therefore something you do with people you would
|
||||
also hand your keyboard to; the dialog says so.
|
||||
|
||||
## Data model (migration-safe, `server/db.js`)
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS lane_shares (
|
||||
lane_id INTEGER NOT NULL REFERENCES lanes(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
granted_by INTEGER NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
PRIMARY KEY (lane_id, user_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS session_shares (
|
||||
session_id TEXT NOT NULL,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
granted_by INTEGER NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
PRIMARY KEY (session_id, user_id)
|
||||
);
|
||||
-- who started a dashboard run (a collaborator's run is billed to them)
|
||||
ALTER TABLE dashboard_runs ADD COLUMN started_by INTEGER; -- guarded like every ALTER in db.js
|
||||
```
|
||||
|
||||
No `role`/`level` column: there is one level (collaborate). Adding view-only
|
||||
later is one column.
|
||||
|
||||
## Who may do what
|
||||
|
||||
| Action | Owner | Workspace collaborator | Session collaborator | Admin |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| See the workspace, its sessions, Changes, history | ✓ | ✓ | that session + the workspace's Changes panel | ✓ |
|
||||
| Attach to / type into a live pane | ✓ | ✓ every pane | that session's pane | ✓ |
|
||||
| Send a message to an ended session (resume) | ✓ | ✓ | that session | ✓ |
|
||||
| Start a NEW session | ✓ | ✓ (billed to them) | ✗ | ✓ |
|
||||
| Git writes (commit, push, shelve, rewrite…) | ✓ | ✓ | ✓ (the session's tree) | ✓ |
|
||||
| Workspace instructions, context files, extra folders | ✓ | ✓ | ✗ | ✓ |
|
||||
| Rename / Remove / Reset the workspace | ✓ | ✗ | ✗ | ✓ |
|
||||
| Share / unshare | ✓ | ✗ | ✗ | ✓ |
|
||||
| `agenthub stage`, lane runtime `up/down/hook` | ✓ | ✓ | ✗ | ✓ |
|
||||
|
||||
Owner-only actions get an `assertLaneOwner(req, laneId)` (owner or admin);
|
||||
everything else becomes "owner **or** collaborator".
|
||||
|
||||
## Server changes
|
||||
|
||||
1. **`server/lib/scope.js`** — the one place that decides visibility:
|
||||
- `laneWhere` / `canSeeLane`: `owner_id = ? OR id IN (SELECT lane_id FROM lane_shares WHERE user_id = ?)`.
|
||||
- `ownedSessionWhere`: add `OR col IN (SELECT session_id FROM session_shares WHERE user_id = ?)` and sessions of shared lanes (through the same lane predicate).
|
||||
- `PATH_RULES` / `namedIds` need no new rule (they call `canSeeLane`/`canSeeSession`); a new route under a new prefix (`/api/shares`) gets its own rule.
|
||||
- Keep `memberId` as is: an analyst still reads everything and writes only what they own **or collaborate on**.
|
||||
2. **Session ownership & billing ("whoever opens it pays")**
|
||||
- `spawnRun` takes `startedBy = req.user.id`; writes `dashboard_runs.started_by`.
|
||||
- `bindRunSession` (`server/routes/hooks.js`) stamps `sessions.owner_id = started_by` when it differs from the lane owner. `sessions.owner_id` already exists (remote clients) and `scope.js`, `session-account.js`, `users.js` honour it.
|
||||
- `server/routes/users.js` ownership CTE: `sessions.owner_id` must WIN over the lane owner (today it is a UNION — a session could count twice). Same in `user-quota.js` spend (`hourlyTokenRows` + `calculateCost`, never a second formula).
|
||||
- Spend quota: `assertSpawnAllowed(startedBy)` instead of the lane owner, and `hook-handler.js`'s `UserPromptSubmit` check reads the flag of the RUN's payer (the quota file is per Linux account today → per account + payer user id, passed to the pane as `AGENTHUB_PAYER_ID`).
|
||||
- **Billing is per run, not per session.** A session can be paid by several
|
||||
people over time: whoever starts or resumes a run pays for everything that
|
||||
run does, including what anyone types into its live pane (keystrokes cannot
|
||||
be attributed; the run's starter can). New table
|
||||
`session_payers(session_id, user_id, from_at)` — one row per run start whose
|
||||
payer differs from the previous one. `hourlyTokenRows` books a session's
|
||||
tokens per UTC hour already; each hour goes to the payer whose `from_at` is
|
||||
the latest ≤ that hour (a run started mid-hour takes the hour from the next
|
||||
one on — documented rounding, never a second cost formula). With no row the
|
||||
session's owner pays, as today. `sessions.owner_id` keeps meaning "who
|
||||
opened it" (visibility); `session_payers` only moves money.
|
||||
3. **AI login of a collaborator's run — their own or refused.**
|
||||
- The collaborator's pool pick (`pickAccount(startedBy)`, their group, pin
|
||||
and own choice) must be of kind `token`: it goes in as
|
||||
`CLAUDE_CODE_OAUTH_TOKEN` through tmux `-e` / the launch file, overriding
|
||||
the owner's home login for that pane only.
|
||||
- A `login`-kind pick, or no pool account for them: `spawnRun` refuses with
|
||||
`409 ENOCOLLABACCOUNT` before anything starts, for a new session AND for a
|
||||
resume. The home's Start button says why. The owner's login is never used
|
||||
for a collaborator's run.
|
||||
- Codex / other tools: same rule with their own env-only kinds (Codex API key
|
||||
`AGENTHUB_POOL_KEY`, Cursor `CURSOR_API_KEY`); a ChatGPT login (written into
|
||||
the home as `auth.json`) is refused like a Claude `login`.
|
||||
4. **Pane token.** A collaborator's session gets a pane token of the
|
||||
collaborator, **scoped to that lane**: `dashboard_runs.pane_token_hash` plus a
|
||||
`scope_lane_id`, and `userFromPaneToken` refuses anything outside that lane.
|
||||
`peerIsPaneAccount` keeps checking the folder's account (`ah-alice`) — the
|
||||
token is accepted from that uid because the pane runs as it.
|
||||
5. **Live co-working.** tmux already allows several attaches with a shared
|
||||
size (`pty-attach.js`). Add:
|
||||
- presence: who is attached to which pane (in-memory, broadcast to the lane's audience);
|
||||
- an audit line per attach-with-input and per prompt sent from the chat composer (`audit_log`, actor = the real user). Keystrokes are not logged.
|
||||
6. **WebSocket** — `broadcastAudience` (`server/websocket.js`): every lane- or
|
||||
session-scoped message also reaches the lane's/session's collaborators. A new
|
||||
type `shares_changed` (owner + affected user).
|
||||
7. **Routes** (`server/routes/shares.js`, same-origin, audited, server mode only):
|
||||
- `GET /api/lanes/:id/shares`, `PUT /api/lanes/:id/shares {userIds}` (owner/admin)
|
||||
- `GET /api/sessions/:id/shares`, `PUT /api/sessions/:id/shares {userIds}` (owner/admin)
|
||||
- `GET /api/me/shared` — what is shared with me
|
||||
- only enabled users; never the owner themself; a disabled user's shares stay but grant nothing.
|
||||
8. **Revoke.** Removing a share closes that user's live attaches on the lane
|
||||
(their websocket attach ends), revokes their pane tokens' lane scope, and
|
||||
leaves their running sessions running (they run as the owner; the owner can
|
||||
stop them). Deleting a lane cascades its shares.
|
||||
|
||||
## Client changes
|
||||
|
||||
- **Share dialog** from the workspace's `⋯` menu and the session's right-click
|
||||
menu: user picker (enabled users, not me), the current list with Remove, and
|
||||
the S3 warning above. `confirmDialog` on Share, `toast` on the result.
|
||||
- **Sidebar**: a "Shared with me" group (workspaces shared with me, and loose
|
||||
shared sessions under their workspace name, marked). A share icon on rows I
|
||||
shared.
|
||||
- **Presence**: small avatars on a pane's tab of who else is attached.
|
||||
- **Recents / session list**: the opener's avatar on a session a collaborator
|
||||
started; the cost column is the opener's.
|
||||
- Owner-only controls hidden for collaborators (the server refuses anyway —
|
||||
`ENOTOWNER`, 403).
|
||||
|
||||
## Docs to update when built
|
||||
|
||||
`docs/SERVER-MODE.md` (new § Sharing + scope table), `docs/LANES.md`,
|
||||
`docs/API.md`, `CLAUDE.md` (the scope.js rule and the S3 rule gain "or a
|
||||
collaborator"), `README.md` feature list.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **S1 — Workspace sharing, visibility + live panes.** Tables, scope.js,
|
||||
broadcastAudience, Share dialog, sidebar group, attach/type, git writes.
|
||||
Collaborators can join live panes but cannot start sessions yet.
|
||||
2. **S2 — Collaborator runs on their own account, billed per run.**
|
||||
`started_by`, `sessions.owner_id` stamping, `session_payers`, users.js /
|
||||
quota precedence (and the double count fixed), pane token scope, pool
|
||||
`token` env, `ENOCOLLABACCOUNT`.
|
||||
3. **S3 — Session-only sharing.** `session_shares`, its scope rules and UI.
|
||||
4. **S4 — Presence + audit of prompts.**
|
||||
|
||||
Each phase ships on its own; tests per phase: `scope.test.js` (every predicate
|
||||
with and without a share), `server-mode-review-fixes.test.js` style 404s for a
|
||||
non-collaborator, users/quota attribution, websocket audience, and the client
|
||||
dialog/sidebar tests.
|
||||
|
||||
## Self-review against the code (2026-11-06)
|
||||
|
||||
Checked every claim above against `server/lib/scope.js`, `auth.js`
|
||||
(`userFromPaneToken`), `hook-auth.js` (`peerIsPaneAccount`), `pty-run.js`
|
||||
(`spawnRun`), `user-quota.js`, `lane-sources.js` (`launchExtras`),
|
||||
`websocket.js` (pty attach) and `routes/users.js`.
|
||||
|
||||
**R1 — CRITICAL: sharing a workspace hands out a shell as the owner's whole
|
||||
account, not just that workspace.** A collaborator who types into a pane (or
|
||||
whose prompt makes Claude run Bash) runs as `ah-alice`, whose home holds ALL of
|
||||
Alice's workspaces, `~/.ssh` keys, `~/.config/agenthub/` HTTPS store, Claude and
|
||||
Codex logins (`.credentials.json`, `auth.json`) and the env of her live panes.
|
||||
So Bob can read Alice's other projects, copy her SSH key and her Claude
|
||||
subscription token, and — via `$AGENTHUB_PANE_TOKEN` in any of her panes — call
|
||||
the CLI/MCP **as Alice** (`userFromPaneToken` returns the lane owner, and is
|
||||
accepted from Alice's uid, which Bob's typing runs as). This also defeats
|
||||
decision 1 ("never the owner's subscription"): Bob can simply use her login.
|
||||
The section "The one fact everything else follows from" understated this.
|
||||
Options:
|
||||
- **(a) Accept it, warn hard.** Share = "give this person your account". Simple,
|
||||
honest, no isolation.
|
||||
- **(b) Team workspaces in their own Linux account.** A shared workspace lives
|
||||
under a dedicated account (`ah-team-<id>`, provisioned by `agenthub-provision`
|
||||
like a member, its own home, git identity, logins = the pool's `token` kinds
|
||||
only). Every member of the team works there; nobody's personal home is
|
||||
exposed. Real isolation; more work (provisioning, git identity per team,
|
||||
`assertOwnerFits` learns team folders, moving an existing workspace = clone).
|
||||
- **(c) Chat-only collaborators.** No terminal for collaborators — but Claude's
|
||||
own Bash tool still runs as Alice, so this isolates nothing. Not proposed.
|
||||
|
||||
**R2 — Typing into the owner's live pane spends the owner's subscription.**
|
||||
Unavoidable while the pane runs on her login; contradicts the spirit of
|
||||
decision 1. Under (b) it disappears (team panes use pool `token` accounts).
|
||||
|
||||
**R3 — Pane tokens.** `userFromPaneToken` maps a token to the LANE OWNER. Needs
|
||||
`dashboard_runs.started_by` → the token's user. And every pane token of a shared
|
||||
lane (the owner's too, see R1) must be limited to that lane, or one leaked token
|
||||
is a whole account.
|
||||
|
||||
**R4 — Session-only sharing does not fit the current checks.** `canSeeRun` and
|
||||
every `/api/lanes/:id/...` route decide by LANE (`canSeeLane`). Granting a
|
||||
session collaborator `canSeeLane` would show them the whole workspace. Needs a
|
||||
run/session-level predicate and an allowlist of lane routes usable with
|
||||
`?session=<shared id>` only. Recommend: drop session-only sharing from the first
|
||||
release, or limit it to that session's pane + chat (no Changes panel).
|
||||
|
||||
**R5 — Per-account limits are shared.** `MAX_AI_SESSIONS` (default 4) and
|
||||
`member-guard.js` count per Linux account, so collaborators' sessions eat the
|
||||
owner's 4 (no issue under (b): the team account has its own limit).
|
||||
|
||||
**R6 — Spend-quota flag is one file per account** (`quota.json` in the member's
|
||||
handoff dir, `flagEnv`). Payer-based quota needs one file per payer
|
||||
(`quota-u<id>.json`) and `AGENTHUB_QUOTA_FILE` pointing at the payer's.
|
||||
|
||||
**R7 — `launchExtras` puts the lane OWNER's personal instructions** first in
|
||||
every pane; a collaborator's session should get the starter's.
|
||||
|
||||
**R8 — AI Proxy.** `resolveProxy(tool, proxy, laneOwner)` resolves by owner: a
|
||||
collaborator could spend the owner's proxy key. Resolve by the starter — and a
|
||||
collaborator's OWN proxy profile is a valid "own account" besides a `token` pool
|
||||
account (decision 1 should allow it).
|
||||
|
||||
**R9 — Other `owner_id = ?` call sites** to extend or keep owner-only, checked
|
||||
one by one: `scope.js` (`laneWhere`, `canSeeLane`, `visibleLaneIds`,
|
||||
`insideOwnWorkspace`), `auth.js` (demote/disable ends a user's host panes —
|
||||
must also end runs they `started_by` elsewhere), `pool-usage.js`,
|
||||
`member-tmux.js`, `me.js` counts, `users.js`.
|
||||
|
||||
**R10 — Simplification found:** the pty attach socket already re-checks its user
|
||||
periodically ("still owning the pane's workspace", `websocket.js`), so revoking
|
||||
a share closes live attaches by just changing the predicate — no new kill path.
|
||||
|
||||
## Answered questions (2026-11-06)
|
||||
|
||||
1. A collaborator's run uses **their own `token`-kind pool account, or is
|
||||
refused** (`ENOCOLLABACCOUNT`) — never the owner's subscription.
|
||||
2. Spend quota: **only the payer's**.
|
||||
3. Resume by someone else: **the resumer pays from then on** (per-run billing,
|
||||
`session_payers`).
|
||||
4. Session-only share: **commit/push allowed**.
|
||||
5. Analysts: **sharing gives write** in that workspace.
|
||||
|
||||
## Still to settle while building
|
||||
|
||||
- The per-hour rounding of `session_payers` (a run started at 10:40 by Bob in a
|
||||
session Alice paid at 10:05): the hour goes to the earlier payer and Bob pays
|
||||
from 11:00, or token rows get a finer key. Phase 2 measures how often it
|
||||
matters before adding a finer key.
|
||||
- Typing into a live pane started by someone else costs the run's starter. The
|
||||
pane's header shows "billed to <name>" so nobody is surprised.
|
||||
+1143
-48
File diff suppressed because one or more lines are too long
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.8.77",
|
||||
"version": "2.8.78",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "agenthub",
|
||||
"version": "2.8.77",
|
||||
"version": "2.8.78",
|
||||
"hasInstallScript": true,
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.8.77",
|
||||
"version": "2.8.78",
|
||||
"bin": {
|
||||
"agenthub": "bin/agenthub.js"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* @file collab-runs.test.js
|
||||
* @description A session started by a user a workspace is shared with
|
||||
* (sharing phase 2, pty-run.js spawnRun `startedBy`): it runs on a pool
|
||||
* setup-token of THEIR OWN through tmux `-e` (never the owner's pick, never a
|
||||
* login), is refused with `ENOCOLLABACCOUNT` when they have none, records
|
||||
* `started_by`, makes them the payer of the new session from its first hour
|
||||
* (session-payers.js), points its hooks at their own quota flag and is
|
||||
* refused while they are over their quota. The owner's own start is unchanged.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, before, after, beforeEach } = 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(), "collab-runs-test-"));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
|
||||
process.env.CLAUDE_HOME = path.join(TMP, "claude");
|
||||
|
||||
const { db } = require("../db");
|
||||
const ccUsage = require("../lib/cc-usage");
|
||||
const pool = require("../lib/claude-pool");
|
||||
const tmux = require("../lib/tmux");
|
||||
const pty = require("../lib/pty-run");
|
||||
|
||||
const TOKEN = (c) => `sk-ant-oat01-${c.repeat(40)}`;
|
||||
const realFetchUsage = ccUsage.fetchUsage;
|
||||
const realFetchOwner = ccUsage.fetchOwner;
|
||||
let argv = null;
|
||||
let alice;
|
||||
let bob;
|
||||
let lane;
|
||||
|
||||
const envOf = (name) => {
|
||||
const hit = (argv || []).find((x) => String(x).startsWith(`${name}=`));
|
||||
return hit ? String(hit).slice(name.length + 1) : undefined;
|
||||
};
|
||||
|
||||
before(() => {
|
||||
ccUsage.fetchUsage = async () => {
|
||||
throw Object.assign(new Error("offline"), { code: "EUNAUTHORIZED" });
|
||||
};
|
||||
ccUsage.fetchOwner = async () => null;
|
||||
tmux.__setExecImpl((args) => {
|
||||
if (args[0] === "has-session") throw Object.assign(new Error("gone"), { status: 1 });
|
||||
if (args[0] === "new-session") argv = args;
|
||||
return "";
|
||||
});
|
||||
const user = (name) =>
|
||||
Number(
|
||||
db
|
||||
.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'x', 'developer')")
|
||||
.run(name).lastInsertRowid
|
||||
);
|
||||
alice = user("alice");
|
||||
bob = user("bob");
|
||||
lane = Number(
|
||||
db.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES (?, 'claude', ?)").run(TMP, alice)
|
||||
.lastInsertRowid
|
||||
);
|
||||
db.prepare("INSERT INTO lane_shares (lane_id, user_id) VALUES (?, ?)").run(lane, bob);
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
});
|
||||
|
||||
after(() => {
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
ccUsage.fetchUsage = realFetchUsage;
|
||||
ccUsage.fetchOwner = realFetchOwner;
|
||||
tmux.__setExecImpl(null);
|
||||
fs.rmSync(TMP, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fs.rmSync(pool.poolDir(), { recursive: true, force: true });
|
||||
db.prepare("DELETE FROM dashboard_runs").run();
|
||||
db.prepare("DELETE FROM session_payers").run();
|
||||
db.prepare("DELETE FROM account_pins").run();
|
||||
db.prepare("DELETE FROM user_quotas").run();
|
||||
pool.__quotaCache.clear();
|
||||
argv = null;
|
||||
});
|
||||
|
||||
describe("a collaborator's own session", () => {
|
||||
it("is refused without an account of their own, never run on the owner's", () => {
|
||||
assert.throws(() => pty.spawnRun({ laneId: lane, cwd: TMP, tool: "claude", startedBy: bob }), {
|
||||
code: "ENOCOLLABACCOUNT",
|
||||
});
|
||||
assert.equal(argv, null, "no pane was started");
|
||||
// The owner's own start is as before.
|
||||
pty.spawnRun({ laneId: lane, cwd: TMP, tool: "claude" });
|
||||
const row = db.prepare("SELECT started_by FROM dashboard_runs").get();
|
||||
assert.equal(row.started_by, null);
|
||||
});
|
||||
|
||||
it("runs on their own pool token, records them and makes them its payer", () => {
|
||||
pool.addAccount("theirs", TOKEN("b"));
|
||||
pty.spawnRun({ laneId: lane, cwd: TMP, tool: "claude", startedBy: bob, slot: 1 });
|
||||
assert.equal(envOf("CLAUDE_CODE_OAUTH_TOKEN"), TOKEN("b"));
|
||||
assert.ok(argv.indexOf(`CLAUDE_CODE_OAUTH_TOKEN=${TOKEN("b")}`) < argv.indexOf("--"));
|
||||
// Their own quota flag, never the owner's.
|
||||
assert.match(envOf("AGENTHUB_QUOTA_FILE"), new RegExp(`u${bob}\\.json$`));
|
||||
const run = db
|
||||
.prepare("SELECT session_id, started_by, account FROM dashboard_runs WHERE id = ?")
|
||||
.get(`agenthub-lane-${lane}-1`);
|
||||
assert.equal(run.started_by, bob);
|
||||
assert.equal(run.account, "theirs");
|
||||
assert.deepEqual(
|
||||
db.prepare("SELECT session_id, from_hour, user_id FROM session_payers").all(),
|
||||
[{ session_id: run.session_id, from_hour: "0000", user_id: bob }]
|
||||
);
|
||||
});
|
||||
|
||||
it("starts nothing while they are over their own quota — and the owner still starts", () => {
|
||||
pool.addAccount("theirs", TOKEN("b"));
|
||||
const MODEL = "claude-sonnet-4-5-20250929";
|
||||
const hour = new Date().toISOString().slice(0, 13);
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd, lane_id, updated_at) VALUES ('sBob', 'b', 'active', ?, ?, ?)"
|
||||
).run(TMP, lane, new Date().toISOString());
|
||||
db.prepare(
|
||||
"INSERT INTO token_usage (session_id, model, output_tokens) VALUES ('sBob', ?, 10000000)"
|
||||
).run(MODEL);
|
||||
db.prepare(
|
||||
"INSERT INTO token_usage_hourly (session_id, hour, model, output_tokens) VALUES ('sBob', ?, ?, 10000000)"
|
||||
).run(hour, MODEL);
|
||||
db.prepare("INSERT INTO session_payers VALUES ('sBob', '0000', ?)").run(bob);
|
||||
const q = require("../lib/user-quota");
|
||||
for (const id of [alice, bob]) {
|
||||
q.setUserQuota(id, { mode: "custom", limit_usd: 1, period: "5h", tz_offset: 0 });
|
||||
}
|
||||
assert.throws(() => pty.spawnRun({ laneId: lane, cwd: TMP, tool: "claude", startedBy: bob }), {
|
||||
code: "EQUOTA",
|
||||
});
|
||||
// Those hours are bob's money, not alice's.
|
||||
pty.spawnRun({ laneId: lane, cwd: TMP, tool: "claude", slot: 2 });
|
||||
assert.ok(argv, "the owner's pane started");
|
||||
});
|
||||
|
||||
it("never resumes a non-Claude session across payers, nor the latest one for a collaborator", () => {
|
||||
pool.addAccount("theirs", TOKEN("b"));
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd, lane_id, tool) VALUES ('sCodexAAA', 'a', 'completed', ?, ?, 'codex')"
|
||||
).run(TMP, lane);
|
||||
assert.throws(
|
||||
() =>
|
||||
pty.spawnRun({
|
||||
laneId: lane,
|
||||
cwd: TMP,
|
||||
tool: "codex",
|
||||
resumeSessionId: "sCodexAAA",
|
||||
startedBy: bob,
|
||||
}),
|
||||
{ code: "ECOLLABRESUME" }
|
||||
);
|
||||
// Nor the owner a session the collaborator pays for.
|
||||
db.prepare("INSERT INTO session_payers VALUES ('sCodexBBB', '0000', ?)").run(bob);
|
||||
assert.throws(
|
||||
() => pty.spawnRun({ laneId: lane, cwd: TMP, tool: "codex", resumeSessionId: "sCodexBBB" }),
|
||||
{ code: "ECOLLABRESUME" }
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
pty.spawnRun({ laneId: lane, cwd: TMP, tool: "claude", resumeLast: true, startedBy: bob }),
|
||||
{ code: "ECOLLABRESUME" }
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a Terminal tab's session the owner's money", () => {
|
||||
const payers = require("../lib/session-payers");
|
||||
db.prepare(
|
||||
`INSERT INTO dashboard_runs (id, session_id, mode, cwd, status, lane_id, tool, started_by)
|
||||
VALUES ('agenthub-lane-shell', 'sShell', 'interactive', ?, 'running', ?, 'shell', ?)`
|
||||
).run(TMP, lane, bob);
|
||||
payers.noteRun("agenthub-lane-shell");
|
||||
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM session_payers").get().n, 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,527 @@
|
||||
/**
|
||||
* @file lane-shares.test.js
|
||||
* @description Sharing a workspace with other users (server mode,
|
||||
* docs/plans/workspace-sharing/ phase 1): only the owner or an admin manages
|
||||
* the list (`GET/PUT /api/lanes/:id/shares`, audited, enabled users only, never
|
||||
* the owner); the user it is shared with sees the workspace and its sessions
|
||||
* but may not rename, reset, remove or delete it (`ENOTOWNER`); an AI session
|
||||
* they start needs an account of their own (`ENOCOLLABACCOUNT`) and each hour
|
||||
* of a session is billed to whoever ran it then (users page, quotas, Today); a
|
||||
* Terminal tab they open acts as THEM through its pane token, never as the
|
||||
* owner; a collaborator disabled since does not block the list; a user it is
|
||||
* not shared with still gets 404; taking it back ends their access at once.
|
||||
* @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("path");
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
|
||||
const TEST_DB = path.join(os.tmpdir(), `lane-shares-${Date.now()}-${process.pid}.db`);
|
||||
process.env.DASHBOARD_DB_PATH = TEST_DB;
|
||||
process.env.DASHBOARD_LIVENESS_PROBE = "0";
|
||||
|
||||
const { createApp, startServer } = require("../index");
|
||||
const { db } = require("../db");
|
||||
const auth = require("../lib/auth");
|
||||
|
||||
let server;
|
||||
let BASE;
|
||||
const cookies = {};
|
||||
const users = {};
|
||||
let laneA;
|
||||
|
||||
async function call(method, p, { as, body } = {}) {
|
||||
const res = await fetch(BASE + p, {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: BASE,
|
||||
...(as ? { cookie: cookies[as] } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
return { status: res.status, body: await res.json().catch(() => null) };
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
server = await startServer(createApp(), 0);
|
||||
BASE = `http://127.0.0.1:${server.address().port}`;
|
||||
users.alice = await auth.createUser("alice", "alice-pass-1", "developer");
|
||||
users.bob = await auth.createUser("bob", "bob-pass-1", "developer");
|
||||
users.carol = await auth.createUser("carol", "carol-pass-1", "developer");
|
||||
users.boss = await auth.createUser("boss", "admin-pass-1", "admin");
|
||||
laneA = Number(
|
||||
db
|
||||
.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES ('/w/alice', 'claude', ?)")
|
||||
.run(users.alice.id).lastInsertRowid
|
||||
);
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('sA', 'alice one', 'active', '/w/alice', ?)"
|
||||
).run(laneA);
|
||||
process.env.AGENTHUB_MODE = "server";
|
||||
for (const [name, pass] of [
|
||||
["alice", "alice-pass-1"],
|
||||
["bob", "bob-pass-1"],
|
||||
["carol", "carol-pass-1"],
|
||||
["boss", "admin-pass-1"],
|
||||
]) {
|
||||
const r = await fetch(BASE + "/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: name, password: pass }),
|
||||
});
|
||||
assert.equal(r.status, 200);
|
||||
cookies[name] = r.headers.get("set-cookie").split(";")[0];
|
||||
}
|
||||
});
|
||||
|
||||
after(() => {
|
||||
delete process.env.AGENTHUB_MODE;
|
||||
server?.close();
|
||||
for (const f of [TEST_DB, `${TEST_DB}-wal`, `${TEST_DB}-shm`, `${TEST_DB}-migrate.lock`]) {
|
||||
fs.rmSync(f, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const laneIds = async (as) => (await call("GET", "/api/lanes", { as })).body.lanes.map((l) => l.id);
|
||||
|
||||
describe("sharing a workspace", () => {
|
||||
it("is managed only by its owner (or an admin), for enabled users other than the owner", async () => {
|
||||
assert.equal((await call("GET", `/api/lanes/${laneA}/shares`, { as: "bob" })).status, 404);
|
||||
const put = (as, userIds) =>
|
||||
call("PUT", `/api/lanes/${laneA}/shares`, { as, body: { userIds } });
|
||||
assert.equal((await put("bob", [users.bob.id])).status, 404);
|
||||
assert.equal((await put("alice", [users.alice.id])).body.error.code, "EBADUSER");
|
||||
assert.equal((await put("alice", [9999])).body.error.code, "EBADUSER");
|
||||
assert.equal((await put("alice", "bob")).body.error.code, "EBADUSER");
|
||||
|
||||
const r = await put("alice", [users.bob.id]);
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(
|
||||
r.body.shares.map((u) => u.username),
|
||||
["bob"]
|
||||
);
|
||||
const audit = db
|
||||
.prepare("SELECT user_id, owner_id, path FROM audit_log WHERE path LIKE 'share workspace%'")
|
||||
.all();
|
||||
assert.deepEqual(audit, [
|
||||
{ user_id: users.alice.id, owner_id: users.bob.id, path: `share workspace ${laneA}` },
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows the workspace and its sessions to the user it is shared with — and nobody else", async () => {
|
||||
assert.ok((await laneIds("bob")).includes(laneA));
|
||||
assert.equal((await call("GET", "/api/sessions/sA", { as: "bob" })).status, 200);
|
||||
const shares = await call("GET", `/api/lanes/${laneA}/shares`, { as: "bob" });
|
||||
assert.equal(shares.status, 200);
|
||||
assert.equal(shares.body.canManage, false);
|
||||
assert.ok(!(await laneIds("carol")).includes(laneA));
|
||||
assert.equal((await call("GET", "/api/sessions/sA", { as: "carol" })).status, 404);
|
||||
});
|
||||
|
||||
it("keeps rename, remove, delete and sharing the owner's", async () => {
|
||||
const code = (r) => r.body?.error?.code;
|
||||
assert.equal(
|
||||
code(await call("PATCH", `/api/lanes/${laneA}`, { as: "bob", body: { title: "mine" } })),
|
||||
"ENOTOWNER"
|
||||
);
|
||||
assert.equal(
|
||||
code(
|
||||
await call("POST", `/api/lanes/${laneA}/remove`, { as: "bob", body: { confirm: true } })
|
||||
),
|
||||
"ENOTOWNER"
|
||||
);
|
||||
assert.equal(code(await call("DELETE", `/api/lanes/${laneA}`, { as: "bob" })), "ENOTOWNER");
|
||||
assert.equal(
|
||||
code(
|
||||
await call("PUT", `/api/lanes/${laneA}/shares`, {
|
||||
as: "bob",
|
||||
body: { userIds: [users.bob.id, users.carol.id] },
|
||||
})
|
||||
),
|
||||
"ENOTOWNER"
|
||||
);
|
||||
// Notes are not owner-only: a collaborator writes them like the owner.
|
||||
const notes = await call("PATCH", `/api/lanes/${laneA}`, { as: "bob", body: { notes: "hi" } });
|
||||
assert.equal(notes.status, 200);
|
||||
// The owner and an admin still rename it.
|
||||
assert.equal(
|
||||
(await call("PATCH", `/api/lanes/${laneA}`, { as: "alice", body: { title: "A" } })).status,
|
||||
200
|
||||
);
|
||||
assert.equal(
|
||||
(await call("PATCH", `/api/lanes/${laneA}`, { as: "boss", body: { title: "B" } })).status,
|
||||
200
|
||||
);
|
||||
});
|
||||
|
||||
it("starts a collaborator's AI session only on an account of their own", async () => {
|
||||
// No pool account and no AI Proxy of theirs: refused, never the owner's login.
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lane-shares-cwd-"));
|
||||
db.prepare("UPDATE lanes SET cwd = ? WHERE id = ?").run(dir, laneA);
|
||||
let r;
|
||||
let run;
|
||||
try {
|
||||
r = await call("POST", `/api/lanes/${laneA}/start`, {
|
||||
as: "bob",
|
||||
body: { slot: "auto", prompt: "hi" },
|
||||
});
|
||||
run = await call("POST", "/api/run", {
|
||||
as: "bob",
|
||||
body: { laneId: laneA, initialPrompt: "hi" },
|
||||
});
|
||||
} finally {
|
||||
db.prepare("UPDATE lanes SET cwd = '/w/alice' WHERE id = ?").run(laneA);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
assert.equal(r.status, 409, JSON.stringify(r.body));
|
||||
assert.equal(r.body.error.code, "ENOCOLLABACCOUNT");
|
||||
assert.equal(run.status, 409, JSON.stringify(run.body));
|
||||
assert.equal(run.body.error.code, "ENOCOLLABACCOUNT");
|
||||
});
|
||||
|
||||
it("bills each hour of a session to whoever ran it then", async () => {
|
||||
const payers = require("../lib/session-payers");
|
||||
const MODEL = "claude-sonnet-4-5-20250929";
|
||||
const hour = (h) => new Date(Date.now() - h * 3600e3).toISOString().slice(0, 13);
|
||||
const spend = (sid, h, tokens) => {
|
||||
db.prepare(
|
||||
`INSERT INTO token_usage (session_id, model, output_tokens) VALUES (?, ?, ?)
|
||||
ON CONFLICT DO UPDATE SET output_tokens = output_tokens + excluded.output_tokens`
|
||||
).run(sid, MODEL, tokens);
|
||||
db.prepare(
|
||||
"INSERT INTO token_usage_hourly (session_id, hour, model, output_tokens) VALUES (?, ?, ?, ?)"
|
||||
).run(sid, hour(h), MODEL, tokens);
|
||||
};
|
||||
const started = new Date(Date.now() - 3 * 3600e3).toISOString();
|
||||
db.prepare(
|
||||
`INSERT INTO sessions (id, name, status, cwd, lane_id, started_at, updated_at)
|
||||
VALUES ('sPaid', 'paid', 'active', '/w/alice', ?, ?, ?)`
|
||||
).run(laneA, started, new Date().toISOString());
|
||||
spend("sPaid", 2, 1_000_000); // alice's hours
|
||||
// Bob resumes it now: his from the next hour on.
|
||||
const runIns = (id, by) =>
|
||||
db
|
||||
.prepare(
|
||||
`INSERT OR REPLACE INTO dashboard_runs (id, session_id, mode, cwd, status, lane_id, tool, started_by, started_at)
|
||||
VALUES (?, 'sPaid', 'interactive', '/w/alice', 'completed', ?, 'claude', ?, ?)`
|
||||
)
|
||||
.run(id, laneA, by, new Date().toISOString());
|
||||
runIns("agenthub-lane-x-bob", users.bob.id);
|
||||
const now = Date.now();
|
||||
payers.noteRun("agenthub-lane-x-bob", now);
|
||||
assert.deepEqual(
|
||||
db
|
||||
.prepare(
|
||||
"SELECT from_hour, user_id FROM session_payers WHERE session_id = 'sPaid' ORDER BY from_hour"
|
||||
)
|
||||
.all(),
|
||||
[
|
||||
{ from_hour: "0000", user_id: users.alice.id },
|
||||
{ from_hour: new Date(now + 3600e3).toISOString().slice(0, 13), user_id: users.bob.id },
|
||||
]
|
||||
);
|
||||
// Noting the same payer again changes nothing.
|
||||
payers.noteRun("agenthub-lane-x-bob", now);
|
||||
assert.equal(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM session_payers WHERE session_id = 'sPaid'").get().n,
|
||||
2
|
||||
);
|
||||
// Book bob's hour as the next one (a test cannot wait an hour).
|
||||
db.prepare(
|
||||
"INSERT INTO token_usage_hourly (session_id, hour, model, output_tokens) VALUES ('sPaid', ?, ?, 2000000)"
|
||||
).run(new Date(now + 3600e3).toISOString().slice(0, 13), MODEL);
|
||||
db.prepare(
|
||||
"UPDATE token_usage SET output_tokens = output_tokens + 2000000 WHERE session_id = 'sPaid'"
|
||||
).run();
|
||||
|
||||
const resolve = payers.payerResolver();
|
||||
assert.equal(resolve({ session_id: "sPaid", date: hour(2) }), users.alice.id);
|
||||
assert.equal(
|
||||
resolve({ session_id: "sPaid", date: new Date(now + 3600e3).toISOString().slice(0, 13) }),
|
||||
users.bob.id
|
||||
);
|
||||
|
||||
// The users page: each sees only the hours they paid (2:1 tokens).
|
||||
const details = async (u) =>
|
||||
(await call("GET", `/api/users/${u.id}/details`, { as: "boss" })).body.usage.last7d;
|
||||
const a = await details(users.alice);
|
||||
const b = await details(users.bob);
|
||||
assert.ok(a.cost > 0 && b.cost > 0, JSON.stringify({ a, b }));
|
||||
assert.ok(Math.abs(b.cost / a.cost - 2) < 0.01, JSON.stringify({ a, b }));
|
||||
const list = (await call("GET", "/api/users", { as: "boss" })).body.users;
|
||||
const last7 = (name) => list.find((u) => u.username === name).last7d.cost;
|
||||
assert.ok(Math.abs(last7("bob") / last7("alice") - 2) < 0.01, JSON.stringify(list));
|
||||
|
||||
// Spend quotas count the same hours.
|
||||
const q = require("../lib/user-quota");
|
||||
q.setUserQuota(users.bob.id, { mode: "custom", limit_usd: 1000, period: "day", tz_offset: 0 });
|
||||
q.setUserQuota(users.alice.id, {
|
||||
mode: "custom",
|
||||
limit_usd: 1000,
|
||||
period: "day",
|
||||
tz_offset: 0,
|
||||
});
|
||||
const st = q.statusAll({ now: now + 3600e3 + 60e3, userIds: [users.alice.id, users.bob.id] });
|
||||
assert.ok(Math.abs(st.get(users.bob.id).spend - b.cost) < 0.01, JSON.stringify([...st]));
|
||||
q.setUserQuota(users.bob.id, { mode: "default" });
|
||||
q.setUserQuota(users.alice.id, { mode: "default" });
|
||||
|
||||
// Today (`mine=1`) is each one's own money, never the other's hours.
|
||||
const mine = async (as) =>
|
||||
(await call("GET", "/api/pricing/cost?mine=1", { as })).body.total_cost;
|
||||
assert.ok(Math.abs((await mine("bob")) - b.cost) < 0.01);
|
||||
assert.ok(Math.abs((await mine("alice")) - a.cost) < 0.01);
|
||||
db.prepare("DELETE FROM dashboard_runs WHERE id = 'agenthub-lane-x-bob'").run();
|
||||
});
|
||||
|
||||
it("makes a pane token act as the user who opened that pane, never the owner", () => {
|
||||
const tmux = require("../lib/tmux");
|
||||
const real = tmux.hasSession;
|
||||
tmux.hasSession = () => true;
|
||||
try {
|
||||
const tokenFor = (runId, startedBy) => {
|
||||
const cred = auth.newPaneToken();
|
||||
db.prepare(
|
||||
`INSERT OR REPLACE INTO dashboard_runs (id, mode, cwd, status, lane_id, tool, pane_token_hash, started_by)
|
||||
VALUES (?, 'interactive', '/w/alice', 'running', ?, 'shell', ?, ?)`
|
||||
).run(runId, laneA, cred.hash, startedBy);
|
||||
return cred.token;
|
||||
};
|
||||
const asUser = (token) =>
|
||||
auth.userFromPaneToken({
|
||||
headers: { "x-agenthub-pane-token": token },
|
||||
socket: { remoteAddress: "127.0.0.1" },
|
||||
});
|
||||
assert.equal(asUser(tokenFor(`agenthub-lane-${laneA}-1`, null))?.username, "alice");
|
||||
const bobs = tokenFor(`agenthub-lane-${laneA}-2`, users.bob.id);
|
||||
assert.equal(asUser(bobs)?.username, "bob");
|
||||
// …inside this workspace only: the owner's account can read that token.
|
||||
assert.equal(asUser(bobs)?.paneLane, laneA);
|
||||
const guard = (p, method = "GET") => {
|
||||
let out = null;
|
||||
auth.authGuard(
|
||||
{
|
||||
path: p,
|
||||
method,
|
||||
headers: { "x-agenthub-pane-token": bobs },
|
||||
socket: { remoteAddress: "127.0.0.1" },
|
||||
},
|
||||
{
|
||||
status: (code) => ({ json: (body) => (out = { code, body }) }),
|
||||
},
|
||||
() => (out = "next")
|
||||
);
|
||||
return out;
|
||||
};
|
||||
assert.equal(guard(`/lanes/${laneA}`), "next");
|
||||
assert.equal(guard(`/workspaces/${laneA}/git`), "next");
|
||||
assert.equal(guard("/sessions").body.error.code, "EPANESCOPE");
|
||||
assert.equal(guard(`/lanes/${laneA + 1000}`).body.error.code, "EPANESCOPE");
|
||||
assert.equal(guard("/me").body.error.code, "EPANESCOPE");
|
||||
// The CLI finds its workspace in the list (which answers that one only)…
|
||||
assert.equal(guard("/workspaces"), "next");
|
||||
// …and never starts or bills a session with it.
|
||||
assert.equal(guard(`/lanes/${laneA}/start`, "POST").body.error.code, "EPANESCOPE");
|
||||
assert.equal(guard(`/lanes/${laneA}/reset`, "POST").body.error.code, "EPANESCOPE");
|
||||
assert.equal(guard("/run", "POST").body.error.code, "EPANESCOPE");
|
||||
// No longer shared with him: his pane's token is nobody.
|
||||
db.prepare("DELETE FROM lane_shares WHERE lane_id = ? AND user_id = ?").run(
|
||||
laneA,
|
||||
users.bob.id
|
||||
);
|
||||
assert.equal(asUser(bobs), null);
|
||||
db.prepare("INSERT INTO lane_shares (lane_id, user_id) VALUES (?, ?)").run(
|
||||
laneA,
|
||||
users.bob.id
|
||||
);
|
||||
} finally {
|
||||
tmux.hasSession = real;
|
||||
db.prepare("DELETE FROM dashboard_runs WHERE lane_id = ?").run(laneA);
|
||||
}
|
||||
});
|
||||
|
||||
it("is not blocked by a collaborator disabled since", async () => {
|
||||
const put = (userIds) =>
|
||||
call("PUT", `/api/lanes/${laneA}/shares`, { as: "alice", body: { userIds } });
|
||||
assert.equal((await put([users.bob.id, users.carol.id])).status, 200);
|
||||
db.prepare("UPDATE users SET disabled = 1 WHERE id = ?").run(users.carol.id);
|
||||
try {
|
||||
const listed = await call("GET", `/api/lanes/${laneA}/shares`, { as: "alice" });
|
||||
assert.equal(listed.body.shares.find((u) => u.id === users.carol.id)?.disabled, true);
|
||||
// Kept on the list while another change is saved, then taken off.
|
||||
assert.equal((await put([users.bob.id, users.carol.id])).status, 200);
|
||||
const r = await put([users.bob.id]);
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(
|
||||
r.body.shares.map((u) => u.username),
|
||||
["bob"]
|
||||
);
|
||||
// But never newly added while disabled.
|
||||
assert.equal((await put([users.bob.id, users.carol.id])).body.error.code, "EBADUSER");
|
||||
} finally {
|
||||
db.prepare("UPDATE users SET disabled = 0 WHERE id = ?").run(users.carol.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("ends their access as soon as it is taken back, and says so in the audit log", async () => {
|
||||
const r = await call("PUT", `/api/lanes/${laneA}/shares`, {
|
||||
as: "alice",
|
||||
body: { userIds: [] },
|
||||
});
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(r.body.shares, []);
|
||||
assert.ok(!(await laneIds("bob")).includes(laneA));
|
||||
assert.equal((await call("GET", "/api/sessions/sA", { as: "bob" })).status, 404);
|
||||
assert.equal(
|
||||
db
|
||||
.prepare("SELECT COUNT(*) AS n FROM audit_log WHERE path = ? AND owner_id = ?")
|
||||
.get(`unshare workspace ${laneA}`, users.bob.id).n,
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
it("goes with the workspace when it is deleted", async () => {
|
||||
await call("PUT", `/api/lanes/${laneA}/shares`, {
|
||||
as: "alice",
|
||||
body: { userIds: [users.carol.id] },
|
||||
});
|
||||
assert.equal(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM lane_shares WHERE lane_id = ?").get(laneA).n,
|
||||
1
|
||||
);
|
||||
assert.equal((await call("DELETE", `/api/lanes/${laneA}`, { as: "alice" })).status, 200);
|
||||
assert.equal(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM lane_shares WHERE lane_id = ?").get(laneA).n,
|
||||
0
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sharing one session", () => {
|
||||
let laneS;
|
||||
before(() => {
|
||||
laneS = Number(
|
||||
db
|
||||
.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES ('/w/alice2', 'claude', ?)")
|
||||
.run(users.alice.id).lastInsertRowid
|
||||
);
|
||||
for (const id of ["s1-shared", "s2-private"]) {
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES (?, ?, 'completed', '/w/alice2', ?)"
|
||||
).run(id, id, laneS);
|
||||
}
|
||||
});
|
||||
const put = (as, userIds, sid = "s1-shared") =>
|
||||
call("PUT", `/api/lanes/${laneS}/sessions/${sid}/shares`, { as, body: { userIds } });
|
||||
|
||||
it("is managed by the workspace's owner only, for a session of that workspace", async () => {
|
||||
assert.equal((await put("carol", [users.carol.id])).status, 404);
|
||||
assert.equal((await put("alice", [users.carol.id], "sA")).status, 404, "not this workspace's");
|
||||
const r = await put("alice", [users.carol.id]);
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(
|
||||
r.body.shares.map((u) => u.username),
|
||||
["carol"]
|
||||
);
|
||||
assert.equal(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM audit_log WHERE path = 'share session s1-shared'").get()
|
||||
.n,
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
it("shows that session and its workspace — no other session of it", async () => {
|
||||
const lanes = (await call("GET", "/api/lanes", { as: "carol" })).body.lanes;
|
||||
const mine = lanes.find((l) => l.id === laneS);
|
||||
assert.equal(mine?.access, "session");
|
||||
const list = await call("GET", `/api/sessions?lane=${laneS}`, { as: "carol" });
|
||||
assert.deepEqual(
|
||||
list.body.sessions.map((s) => s.id),
|
||||
["s1-shared"]
|
||||
);
|
||||
assert.equal((await call("GET", "/api/sessions/s1-shared", { as: "carol" })).status, 200);
|
||||
assert.equal((await call("GET", "/api/sessions/s2-private", { as: "carol" })).status, 404);
|
||||
});
|
||||
|
||||
it("allows that session's pane, Changes and a resume of it — nothing else of the workspace", async () => {
|
||||
const scope = require("../lib/scope");
|
||||
const req = { user: { id: users.carol.id, role: "developer" }, method: "POST" };
|
||||
const run = (id, sid) =>
|
||||
db
|
||||
.prepare(
|
||||
`INSERT OR REPLACE INTO dashboard_runs (id, session_id, mode, cwd, status, lane_id, tool)
|
||||
VALUES (?, ?, 'interactive', '/w/alice2', 'running', ?, 'claude')`
|
||||
)
|
||||
.run(id, sid, laneS);
|
||||
run(`agenthub-lane-${laneS}-1`, "s1-shared");
|
||||
run(`agenthub-lane-${laneS}-2`, "s2-private");
|
||||
assert.equal(scope.canSeeRun(req, `agenthub-lane-${laneS}-1`), true);
|
||||
assert.equal(scope.canSeeRun(req, `agenthub-lane-${laneS}-2`), false);
|
||||
assert.equal(scope.canSeeRun(req, `agenthub-lane-${laneS}`), false, "no run there");
|
||||
|
||||
const refused = async (method, p, body) => {
|
||||
const r = await call(method, p, { as: "carol", body });
|
||||
assert.equal(r.status, 403, `${method} ${p} → ${r.status}`);
|
||||
assert.equal(r.body.error.code, "ESESSIONSHARE");
|
||||
};
|
||||
await refused("PATCH", `/api/lanes/${laneS}`, { title: "x" });
|
||||
await refused("GET", `/api/lanes/${laneS}/sources`);
|
||||
await refused("PUT", `/api/lanes/${laneS}/instructions`, { instructions: "x" });
|
||||
await refused("POST", `/api/lanes/${laneS}/start`, { slot: "auto", prompt: "new" });
|
||||
await refused("POST", `/api/lanes/${laneS}/start`, { shell: true });
|
||||
await refused("POST", `/api/lanes/${laneS}/start`, {
|
||||
resumeSessionId: "s1-shared",
|
||||
forkSession: true,
|
||||
});
|
||||
await refused("POST", "/api/run", { laneId: laneS, initialPrompt: "hi" });
|
||||
await refused("POST", `/api/lanes/${laneS}/start`, { resumeSessionId: "s1-shared", slot: 0 });
|
||||
await refused("POST", `/api/lanes/${laneS}/start`, { resumeSessionId: "s1-shared" });
|
||||
await refused("GET", `/api/lanes/${laneS}/git/tree?source=1`);
|
||||
await refused("GET", `/api/artifacts/candidates?laneId=${laneS}`);
|
||||
await refused("PATCH", "/api/sessions/s1-shared", { name: "mine now" });
|
||||
// A shared session resumed only in its own workspace.
|
||||
const laneT = Number(
|
||||
db
|
||||
.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES ('/w/alice3', 'claude', ?)")
|
||||
.run(users.alice.id).lastInsertRowid
|
||||
);
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('sT-other', 't', 'completed', '/w/alice3', ?)"
|
||||
).run(laneT);
|
||||
db.prepare("INSERT INTO session_shares (session_id, user_id) VALUES ('sT-other', ?)").run(
|
||||
users.carol.id
|
||||
);
|
||||
await refused("POST", `/api/lanes/${laneT}/start`, {
|
||||
resumeSessionId: "s1-shared",
|
||||
slot: "auto",
|
||||
});
|
||||
db.prepare("DELETE FROM session_shares WHERE session_id = 'sT-other'").run();
|
||||
// Another session of it is not even there.
|
||||
const other = await call("POST", `/api/lanes/${laneS}/start`, {
|
||||
as: "carol",
|
||||
body: { resumeSessionId: "s2-private" },
|
||||
});
|
||||
assert.equal(other.status, 404);
|
||||
// A resume of the shared one gets past the scope (and then needs their own account).
|
||||
const resume = await call("POST", `/api/lanes/${laneS}/start`, {
|
||||
as: "carol",
|
||||
body: { resumeSessionId: "s1-shared", prompt: "hi", slot: "auto" },
|
||||
});
|
||||
assert.ok(![403, 404].includes(resume.status), JSON.stringify(resume.body));
|
||||
// Reads of the workspace's git and its own row pass.
|
||||
assert.equal((await call("GET", `/api/lanes/${laneS}`, { as: "carol" })).status, 200);
|
||||
const git = await call("GET", `/api/lanes/${laneS}/git`, { as: "carol" });
|
||||
assert.notEqual(git.status, 403);
|
||||
db.prepare("DELETE FROM dashboard_runs WHERE lane_id = ?").run(laneS);
|
||||
});
|
||||
|
||||
it("ends their access when it is taken back", async () => {
|
||||
assert.equal((await put("alice", [])).status, 200);
|
||||
assert.ok(!(await laneIds("carol")).includes(laneS));
|
||||
assert.equal((await call("GET", "/api/sessions/s1-shared", { as: "carol" })).status, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* @file pane-presence.test.js
|
||||
* @description Who has which pane open (server/lib/pane-presence.js, sharing
|
||||
* phase 4): a user counted once however many attaches they hold, gone with
|
||||
* their last one, listed per workspace; the first keystroke into a SHARED
|
||||
* workspace's pane is audited (who and where, never what) and an unshared
|
||||
* one's is not; `pane_presence` reaches the workspace's owner and the users
|
||||
* it is shared with, nobody else.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, before, after, beforeEach } = 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(), "pane-presence-test-"));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
|
||||
|
||||
const { db } = require("../db");
|
||||
const presence = require("../lib/pane-presence");
|
||||
const scope = require("../lib/scope");
|
||||
|
||||
let alice;
|
||||
let bob;
|
||||
let carol;
|
||||
let lane;
|
||||
let lonely;
|
||||
|
||||
before(() => {
|
||||
const user = (name) =>
|
||||
Number(
|
||||
db
|
||||
.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'x', 'developer')")
|
||||
.run(name).lastInsertRowid
|
||||
);
|
||||
alice = user("alice");
|
||||
bob = user("bob");
|
||||
carol = user("carol");
|
||||
const mk = () =>
|
||||
Number(
|
||||
db
|
||||
.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES (?, 'claude', ?)")
|
||||
.run(`/w/${Math.random()}`, alice).lastInsertRowid
|
||||
);
|
||||
lane = mk();
|
||||
lonely = mk();
|
||||
db.prepare("INSERT INTO lane_shares (lane_id, user_id) VALUES (?, ?)").run(lane, bob);
|
||||
});
|
||||
|
||||
after(() => fs.rmSync(TMP, { recursive: true, force: true }));
|
||||
beforeEach(() => presence.__reset());
|
||||
|
||||
describe("pane presence", () => {
|
||||
it("counts a user once per pane, until their last attach closes", () => {
|
||||
const run = `agenthub-lane-${lane}-1`;
|
||||
presence.join(run, { id: bob, username: "bob", displayName: "Bob B" });
|
||||
presence.join(run, { id: bob, username: "bob" });
|
||||
presence.join(run, { id: alice, username: "alice" });
|
||||
assert.deepEqual(presence.forLane(lane)[run], [
|
||||
{ id: bob, name: "Bob B" },
|
||||
{ id: alice, name: "alice" },
|
||||
]);
|
||||
presence.leave(run, { id: bob });
|
||||
assert.equal(presence.forLane(lane)[run].length, 2, "one of bob's attaches is still open");
|
||||
presence.leave(run, { id: bob });
|
||||
presence.leave(run, { id: alice });
|
||||
assert.deepEqual(presence.forLane(lane), {});
|
||||
presence.join("not-a-run", { id: bob });
|
||||
assert.deepEqual(presence.users("not-a-run"), []);
|
||||
});
|
||||
|
||||
it("audits the first keystroke only in a shared workspace", () => {
|
||||
const count = () =>
|
||||
db.prepare("SELECT COUNT(*) AS n FROM audit_log WHERE path LIKE 'type into %'").get().n;
|
||||
presence.auditInput(`agenthub-lane-${lonely}`, { id: alice });
|
||||
assert.equal(count(), 0);
|
||||
presence.auditInput(`agenthub-lane-${lane}-2`, { id: bob });
|
||||
const row = db
|
||||
.prepare(
|
||||
"SELECT user_id, owner_id, method, path FROM audit_log WHERE path LIKE 'type into %'"
|
||||
)
|
||||
.get();
|
||||
assert.deepEqual(row, {
|
||||
user_id: bob,
|
||||
owner_id: alice,
|
||||
method: "PTY",
|
||||
path: `type into agenthub-lane-${lane}-2`,
|
||||
});
|
||||
});
|
||||
|
||||
it("is news for the workspace's owner and collaborators only", () => {
|
||||
const aud = scope.broadcastAudience("pane_presence", { laneId: lane, runId: "x", users: [] });
|
||||
const dev = (id) => ({ id, role: "developer" });
|
||||
assert.equal(scope.audienceIncludes(aud, dev(alice)), true);
|
||||
assert.equal(scope.audienceIncludes(aud, dev(bob)), true);
|
||||
assert.equal(scope.audienceIncludes(aud, dev(carol)), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("what counts as typing", () => {
|
||||
const { isTyping } = require("../lib/pty-attach");
|
||||
it("ignores mouse, focus and the terminal answering tmux", () => {
|
||||
for (const s of [
|
||||
"\x1b[<0;10;5M",
|
||||
"\x1b[I",
|
||||
"\x1b[>0;276;0c",
|
||||
"\x1b[?1;2c",
|
||||
"\x1b[12;40R",
|
||||
"\x1b[0n",
|
||||
"\x1b[?2004;1$y",
|
||||
"\x1b]11;rgb:1e1e/1e1e/1e1e\x1b\\",
|
||||
"\x1b]10;rgb:ffff/ffff/ffff\x07",
|
||||
"\x1bP>|xterm.js(6.0.0)\x1b\\",
|
||||
]) {
|
||||
assert.equal(isTyping(s), false, JSON.stringify(s));
|
||||
}
|
||||
assert.equal(isTyping("ls\r"), true);
|
||||
assert.equal(isTyping("\x1b[A"), true, "an arrow key is typing");
|
||||
});
|
||||
|
||||
it("never audits the owner's own typing", () => {
|
||||
const before = db.prepare("SELECT COUNT(*) AS n FROM audit_log").get().n;
|
||||
presence.auditInput(`agenthub-lane-${lane}`, { id: alice });
|
||||
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM audit_log").get().n, before);
|
||||
});
|
||||
});
|
||||
@@ -308,3 +308,62 @@ describe("scopeGuard against the router's own leniency", () => {
|
||||
assert.equal(run({ user: m1, path: "/lanes/pipeline-stats" }), 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a workspace shared with another user (lane_shares)", () => {
|
||||
// Lane 2 (user 2's, session s2) shared with user 1; taken back afterwards so
|
||||
// the suites above keep their own picture.
|
||||
before(() => {
|
||||
db.prepare("INSERT INTO lane_shares (lane_id, user_id, granted_by) VALUES (2, 1, 2)").run();
|
||||
});
|
||||
after(() => db.prepare("DELETE FROM lane_shares").run());
|
||||
|
||||
it("lets the user it is shared with see it, its sessions and its runs", () => {
|
||||
assert.equal(scope.canSeeLane(member(1), 2), true);
|
||||
assert.equal(scope.canSeeSession(member(1), "s2"), true);
|
||||
assert.equal(scope.canSeeRun({ ...member(1), method: "POST" }, "agenthub-lane-2-1"), true);
|
||||
assert.deepEqual(visibleSessions(member(1)), ["s-unstamped", "s1", "s2"]);
|
||||
assert.deepEqual(scope.visibleLaneIds(member(1)).sort(), [1, 2]);
|
||||
const w = scope.laneWhere(member(1));
|
||||
assert.deepEqual(
|
||||
db.prepare(`SELECT id FROM lanes WHERE ${w.where} ORDER BY id`).all(...w.params).map((r) => r.id),
|
||||
[1, 2]
|
||||
);
|
||||
// Nobody else gained anything.
|
||||
assert.equal(scope.canSeeLane(member(3), 2), false);
|
||||
assert.deepEqual(visibleSessions(member(3)), []);
|
||||
});
|
||||
|
||||
it("keeps it out of the user's OWN money (budgets, Today)", () => {
|
||||
const own = (w) =>
|
||||
db.prepare(`SELECT id FROM sessions WHERE ${w.where} ORDER BY id`).all(...w.params).map((r) => r.id);
|
||||
assert.deepEqual(own(scope.ownedOnlySessionWhere(member(1))), ["s-unstamped", "s1"]);
|
||||
assert.deepEqual(own(scope.ownSessionWhere(member(1))), ["s-unstamped", "s1"]);
|
||||
});
|
||||
|
||||
it("leaves owner-only actions to the owner and admins", () => {
|
||||
assert.equal(scope.isLaneOwner(member(1), 2), false);
|
||||
assert.equal(scope.isLaneOwner(member(2), 2), true);
|
||||
assert.equal(scope.isLaneOwner(admin, 2), true);
|
||||
assert.equal(scope.isLaneOwner(local, 2), true);
|
||||
assert.equal(scope.isLaneOwner({ user: { id: 1, role: "analyst" } }, 2), false);
|
||||
});
|
||||
|
||||
it("sends its news to the user it is shared with, without making it theirs", () => {
|
||||
const a = scope.broadcastAudience("lane_update", { lane: { id: 2 } });
|
||||
assert.equal(scope.audienceIncludes(a, member(1).user), true);
|
||||
assert.equal(a.owners.has(1), false);
|
||||
const s = scope.broadcastAudience("session_updated", { id: "s2" });
|
||||
assert.equal(scope.audienceIncludes(s, member(1).user), true);
|
||||
assert.equal(s.owners.has(1), false);
|
||||
assert.equal(scope.audienceIncludes(s, member(3).user), false);
|
||||
// Taken back: only the users named hear about it.
|
||||
assert.deepEqual([...scope.exactAudience("lane_access", { laneId: 2, userIds: [1] })], [1]);
|
||||
});
|
||||
|
||||
it("stops at once when it is taken back", () => {
|
||||
db.prepare("DELETE FROM lane_shares WHERE lane_id = 2 AND user_id = 1").run();
|
||||
assert.equal(scope.canSeeLane(member(1), 2), false);
|
||||
assert.equal(scope.canSeeRun({ ...member(1), method: "POST" }, "agenthub-lane-2-1"), false);
|
||||
assert.deepEqual(visibleSessions(member(1)), ["s-unstamped", "s1"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -998,6 +998,51 @@ db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_artifact_shares_user ON artifact_shares(user_id);
|
||||
`);
|
||||
|
||||
// A workspace shared with another user (docs/plans/workspace-sharing/, phase 1):
|
||||
// they see it and work in it like its owner, except owner-only actions
|
||||
// (rename, reset, remove, sharing). No foreign keys, like artifact_shares — a
|
||||
// table rebuild of lanes/users must not cascade them away; deleteLane and
|
||||
// deleteUser remove the rows themselves.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS lane_shares (
|
||||
lane_id INTEGER NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
granted_by INTEGER,
|
||||
shared_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
PRIMARY KEY (lane_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_lane_shares_user ON lane_shares(user_id);
|
||||
`);
|
||||
|
||||
// A single session shared with another user (sharing phase 3): they see that
|
||||
// session and its workspace's Changes, join its pane and resume it — nothing
|
||||
// else of the workspace. No foreign keys, like lane_shares.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS session_shares (
|
||||
session_id TEXT NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
granted_by INTEGER,
|
||||
shared_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
PRIMARY KEY (session_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_session_shares_user ON session_shares(user_id);
|
||||
`);
|
||||
|
||||
// Who pays for a session from which UTC hour on (sharing phase 2,
|
||||
// server/lib/session-payers.js): written only once someone other than the
|
||||
// workspace's owner runs it — a session with no row is its owner's. `from_hour`
|
||||
// is `YYYY-MM-DDTHH`, or `0000` for the whole session. Kept when a user goes:
|
||||
// it is money history.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS session_payers (
|
||||
session_id TEXT NOT NULL,
|
||||
from_hour TEXT NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
PRIMARY KEY (session_id, from_hour)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_session_payers_user ON session_payers(user_id);
|
||||
`);
|
||||
|
||||
// One row per install of an artifact (server/lib/artifacts.js `install`):
|
||||
// who, when, and the folders it was written to — `artifacts.installs` only
|
||||
// counts. Installs before this table existed stay counted, not listed.
|
||||
@@ -1857,6 +1902,15 @@ try {
|
||||
db.prepare("ALTER TABLE dashboard_runs ADD COLUMN pane_token_hash TEXT").run();
|
||||
}
|
||||
|
||||
// Who started a run, when it is not the workspace's owner (a user the
|
||||
// workspace is shared with opening a Terminal tab): its pane token acts as
|
||||
// THEM, never as the owner (server/lib/auth.js `userFromPaneToken`). NULL = the owner.
|
||||
try {
|
||||
db.prepare("SELECT started_by FROM dashboard_runs LIMIT 1").get();
|
||||
} catch {
|
||||
db.prepare("ALTER TABLE dashboard_runs ADD COLUMN started_by INTEGER").run();
|
||||
}
|
||||
|
||||
// A realtime chat run's bridge secret (`AGENTHUB_CHAT_TOKEN`), SHA-256: only the
|
||||
// pane's own bridge may stream that run's events (server/routes/chat.js).
|
||||
// Never listed.
|
||||
|
||||
+79
-8
@@ -258,9 +258,36 @@ function validateProfile(body) {
|
||||
|
||||
// Latin look-alikes from other scripts, so "Vĩ" in Cyrillic still collides.
|
||||
const CONFUSABLE = {
|
||||
а: "a", в: "b", е: "e", к: "k", м: "m", н: "h", о: "o", р: "p", с: "c", т: "t",
|
||||
у: "y", х: "x", і: "i", ј: "j", ԁ: "d", ѕ: "s", ӏ: "l", α: "a", β: "b", ε: "e",
|
||||
η: "n", ι: "i", κ: "k", ν: "v", ο: "o", ρ: "p", τ: "t", υ: "u", χ: "x", "ı": "i",
|
||||
а: "a",
|
||||
в: "b",
|
||||
е: "e",
|
||||
к: "k",
|
||||
м: "m",
|
||||
н: "h",
|
||||
о: "o",
|
||||
р: "p",
|
||||
с: "c",
|
||||
т: "t",
|
||||
у: "y",
|
||||
х: "x",
|
||||
і: "i",
|
||||
ј: "j",
|
||||
ԁ: "d",
|
||||
ѕ: "s",
|
||||
ӏ: "l",
|
||||
α: "a",
|
||||
β: "b",
|
||||
ε: "e",
|
||||
η: "n",
|
||||
ι: "i",
|
||||
κ: "k",
|
||||
ν: "v",
|
||||
ο: "o",
|
||||
ρ: "p",
|
||||
τ: "t",
|
||||
υ: "u",
|
||||
χ: "x",
|
||||
ı: "i",
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -517,6 +544,9 @@ function deleteUser(username) {
|
||||
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}`);
|
||||
// Workspaces other users shared with them (lane_shares has no foreign key).
|
||||
sql("DELETE FROM lane_shares WHERE user_id = ?").run(u.id);
|
||||
sql("DELETE FROM session_shares WHERE user_id = ?").run(u.id);
|
||||
require("./avatars").removeAvatar(u.id);
|
||||
try {
|
||||
sql("DELETE FROM push_subscriptions WHERE user_id = ?").run(u.id);
|
||||
@@ -545,6 +575,11 @@ function assignWorkspace(laneId, username) {
|
||||
if (lane) require("./run-as").assertOwnerFits(lane.cwd, u.id);
|
||||
const r = sql("UPDATE lanes SET owner_id = ? WHERE id = ?").run(u.id, Number(laneId));
|
||||
if (r.changes === 0) throw err("ENOLANE", `no workspace ${laneId}`);
|
||||
// Its new owner no longer needs it shared with them.
|
||||
sql("DELETE FROM lane_shares WHERE lane_id = ? AND user_id = ?").run(Number(laneId), u.id);
|
||||
sql(
|
||||
"DELETE FROM session_shares WHERE user_id = ? AND session_id IN (SELECT id FROM sessions WHERE lane_id = ?)"
|
||||
).run(u.id, Number(laneId));
|
||||
}
|
||||
|
||||
/** Take a workspace back from the user who owns it: it is left with no owner
|
||||
@@ -725,25 +760,58 @@ function newPaneToken() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace owner a request from inside a live pane acts as: its
|
||||
* The user a request from inside a live pane acts as: its
|
||||
* `x-agenthub-pane-token` names a run that is still running in tmux, on a
|
||||
* workspace someone owns, and the request came straight from this machine.
|
||||
* That user is the workspace owner — or, for a pane a user the workspace is
|
||||
* shared with started (`dashboard_runs.started_by`), THAT user, and only while
|
||||
* it is still shared with them: their Terminal tab never acts as the owner.
|
||||
*/
|
||||
function userFromPaneToken(req) {
|
||||
const t = req.headers[PANE_HEADER];
|
||||
if (typeof t !== "string" || !t.startsWith("ahpane_") || t.length > 200) return null;
|
||||
if (!isLocalRequest(req)) return null;
|
||||
const row = sql(
|
||||
`SELECT r.id, r.lane_id, l.owner_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
|
||||
`SELECT r.id, r.lane_id, r.session_id, r.started_by, l.owner_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
|
||||
WHERE r.pane_token_hash = ? AND r.status IN ('running', 'spawning') AND instr(r.id, '@') = 0`
|
||||
).get(sha256(t));
|
||||
if (!row || row.owner_id == null) return null;
|
||||
// S3: only from the account that pane runs as (any local uid could post it).
|
||||
if (!require("./hook-auth").peerIsPaneAccount(req, row.lane_id)) return null;
|
||||
if (!require("./tmux").hasSession(row.id)) return null;
|
||||
return (
|
||||
publicUser(sql("SELECT * FROM users WHERE id = ? AND disabled = 0").get(row.owner_id)) || null
|
||||
);
|
||||
const uid = row.started_by ?? row.owner_id;
|
||||
const user = sql("SELECT * FROM users WHERE id = ? AND disabled = 0").get(uid);
|
||||
if (!user) return null;
|
||||
if (
|
||||
uid !== row.owner_id &&
|
||||
user.role !== "admin" &&
|
||||
!require("./scope").sharedWith(row.lane_id, uid) &&
|
||||
!require("./scope").sessionSharedWith(row.session_id, uid)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const pub = publicUser(user);
|
||||
if (!pub) return null;
|
||||
// A collaborator's pane runs as the OWNER's Linux account, which can read
|
||||
// its token: it acts as the collaborator inside this workspace only
|
||||
// (`paneLane`, authGuard), never across their account.
|
||||
return uid !== row.owner_id ? { ...pub, paneLane: row.lane_id } : pub;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a collaborator's pane token may call — the CLI's workspace commands,
|
||||
* nothing that starts or bills a session (the owner's account can read the
|
||||
* token): reads of its own workspace (and the workspace list, which answers
|
||||
* that one only), health, and its stage / stack / hook / feature writes.
|
||||
*/
|
||||
function paneLaneAllows(method, lp, laneId) {
|
||||
const read = method === "GET" || method === "HEAD";
|
||||
if (lp === "/health") return true;
|
||||
if (read && /^\/(?:lanes|workspaces)\/?$/i.test(lp)) return true;
|
||||
const m = /^\/(?:lanes|workspaces)\/(\d+)(\/.*)?$/i.exec(lp);
|
||||
if (!m || Number(m[1]) !== laneId) return false;
|
||||
if (read) return true;
|
||||
return /^\/(stage|up|down|hook\/[^/]+|features\/activate|mcp\/sync)$/i.test(m[2] || "");
|
||||
}
|
||||
|
||||
// ── Gates ───────────────────────────────────────────────────────────────────
|
||||
@@ -799,6 +867,9 @@ function authGuard(req, res, next) {
|
||||
const cookieUser = userFromRequest(req);
|
||||
const user = cookieUser || userFromPaneToken(req);
|
||||
if (!user) return deny(res, 401, "EAUTH", "log in first");
|
||||
if (!cookieUser && user.paneLane != null && !paneLaneAllows(req.method, lp, user.paneLane)) {
|
||||
return deny(res, 403, "EPANESCOPE", "this pane's token acts only inside its own workspace");
|
||||
}
|
||||
req.user = user;
|
||||
// A password an admin gave: the login may only read its own account and
|
||||
// pick its own password until it has.
|
||||
|
||||
+22
-8
@@ -12,7 +12,7 @@
|
||||
*/
|
||||
|
||||
const { stmts } = require("../db");
|
||||
const { memberId, sessionWhere } = require("./scope");
|
||||
const { memberId, ownedOnlySessionWhere } = require("./scope");
|
||||
const { calculateCost, dailyTokenRows, costWhere } = require("../routes/pricing");
|
||||
|
||||
const PERIODS = ["day", "week", "month"];
|
||||
@@ -71,15 +71,29 @@ function budgetSpend(cfg, { now = Date.now(), back = 0, rules, req } = {}) {
|
||||
// A session that spent in the period was touched in it, so older ones are
|
||||
// skipped before their hours are read.
|
||||
const extra = [{ clause: "s.updated_at >= ?", params: [b.startUtc] }];
|
||||
if (memberId(req) != null) {
|
||||
const own = sessionWhere(req, "s.id", "s.lane_id");
|
||||
extra.push({ clause: own.where, params: own.params });
|
||||
}
|
||||
const scope = cfg.tool ? { where: "tool = ?", params: [cfg.tool] } : null;
|
||||
let paid = [];
|
||||
if (memberId(req) != null) {
|
||||
// Their OWN money: their workspaces' sessions, by the hours they paid
|
||||
// where a collaborator ran one — and the hours they paid for in
|
||||
// workspaces shared with them (server/lib/session-payers.js).
|
||||
const own = ownedOnlySessionWhere(req, "s.id", "s.lane_id");
|
||||
const payers = require("./session-payers");
|
||||
extra.push({ clause: `(${own.where}) AND s.id NOT IN (${payers.SPLIT})`, params: own.params });
|
||||
const split = costWhere({
|
||||
scope,
|
||||
lane: cfg.lane,
|
||||
extra: [
|
||||
{ clause: "s.updated_at >= ?", params: [b.startUtc] },
|
||||
{ clause: `s.id IN (${payers.SPLIT})`, params: [] },
|
||||
],
|
||||
});
|
||||
paid = payers.paidDailyRows(req.user.id, split.whereClause, split.params, `${-tz} minutes`);
|
||||
}
|
||||
const where = costWhere({ scope, lane: cfg.lane, extra });
|
||||
const rows = dailyTokenRows(`${-tz} minutes`, where.whereClause, where.params).filter(
|
||||
(r) => r.date >= b.start && r.date <= b.end
|
||||
);
|
||||
const rows = dailyTokenRows(`${-tz} minutes`, where.whereClause, where.params)
|
||||
.concat(paid)
|
||||
.filter((r) => r.date >= b.start && r.date <= b.end);
|
||||
const spend = calculateCost(rows, rules || stmts.listPricing.all()).total_cost;
|
||||
// The pace so far, carried to the period's end; at least an hour of pace so
|
||||
// the first minutes of a period do not project a fortune.
|
||||
|
||||
@@ -627,6 +627,22 @@ function forSpawn(member = null, ownerId = null) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a pane a user runs in a workspace SHARED with them needs (sharing
|
||||
* phase 2): a setup-token of THEIR OWN — their group's, their pin or choice,
|
||||
* else the balancer's pick — by env, or null. Never a login: one would be
|
||||
* written into the owner's home (`place()`), and the owner's own login there
|
||||
* is the owner's money.
|
||||
*/
|
||||
function forCollaborator(userId) {
|
||||
const allowed = require("./pool-groups").allowed(userId, "claude");
|
||||
const usable = allAccounts().filter((a) => a.kind === "token" && !expired(a) && allowed(a.name));
|
||||
if (usable.length === 0) return null;
|
||||
const pin = require("./account-pins").preferredFor(userId, "claude");
|
||||
const a = (pin && usable.find((x) => x.name === pin)) || rankAccounts(usable);
|
||||
return { name: a.name, env: { CLAUDE_CODE_OAUTH_TOKEN: a.token }, place: () => {} };
|
||||
}
|
||||
|
||||
/** Is `name` an account in the pool (any state)? */
|
||||
const hasAccount = (name) => NAME_RE.test(String(name)) && Boolean(readAccount(String(name)));
|
||||
|
||||
@@ -640,6 +656,7 @@ module.exports = {
|
||||
poolStatus,
|
||||
pickAccount,
|
||||
forSpawn,
|
||||
forCollaborator,
|
||||
forRemote,
|
||||
switchHome,
|
||||
refreshQuotas,
|
||||
|
||||
@@ -478,7 +478,28 @@ function pickAccount(member = null, ownerId = null) {
|
||||
* (a member's launch file); `place()` runs just before the pane starts.
|
||||
*/
|
||||
function forSpawn(member = null, ownerId = null) {
|
||||
const a = pick(member, ownerId);
|
||||
return spawnOf(pick(member, ownerId), member);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a pane a user runs in a workspace SHARED with them needs (sharing
|
||||
* phase 2): an API key of THEIR OWN by env, or null — never a ChatGPT login,
|
||||
* which would be written into the owner's CODEX_HOME.
|
||||
*/
|
||||
function forCollaborator(userId) {
|
||||
const allowed = require("./pool-groups").allowed(userId, "codex");
|
||||
const usable = allAccounts().filter((a) => a.kind === "apikey" && allowed(a.name));
|
||||
if (usable.length === 0) return null;
|
||||
const pin = require("./account-pins").preferredFor(userId, "codex");
|
||||
const a =
|
||||
(pin && usable.find((x) => x.name === pin)) ||
|
||||
usable
|
||||
.map((x) => ({ x, n: livePanes(x.name) }))
|
||||
.sort((p, q) => p.n - q.n || p.x.name.localeCompare(q.x.name))[0].x;
|
||||
return spawnOf(a, null);
|
||||
}
|
||||
|
||||
function spawnOf(a, member) {
|
||||
if (!a) return null;
|
||||
if (a.kind === "apikey") {
|
||||
const provider = `{name="OpenAI (AgentHub pool)",base_url="https://api.openai.com/v1",env_key="${KEY_ENV}",wire_api="responses"}`;
|
||||
@@ -522,6 +543,7 @@ module.exports = {
|
||||
poolStatus,
|
||||
pickAccount,
|
||||
forSpawn,
|
||||
forCollaborator,
|
||||
syncBack,
|
||||
poolDir,
|
||||
__read: readAccount,
|
||||
|
||||
@@ -34,11 +34,11 @@ const insertStmt = db.prepare(`
|
||||
INSERT OR REPLACE INTO dashboard_runs (
|
||||
id, session_id, mode, cwd, model, permission_mode, effort,
|
||||
resume_session_id, prompt_preview, status, exit_code, started_at, ended_at,
|
||||
lane_id, tool, worktree, proxy, account, pane_token_hash
|
||||
lane_id, tool, worktree, proxy, account, pane_token_hash, started_by
|
||||
) VALUES (
|
||||
@id, @session_id, @mode, @cwd, @model, @permission_mode, @effort,
|
||||
@resume_session_id, @prompt_preview, @status, @exit_code, @started_at, @ended_at,
|
||||
@lane_id, @tool, @worktree, @proxy, @account, @pane_token_hash
|
||||
@lane_id, @tool, @worktree, @proxy, @account, @pane_token_hash, @started_by
|
||||
)
|
||||
`);
|
||||
|
||||
@@ -53,7 +53,7 @@ const updateStmt = db.prepare(`
|
||||
|
||||
const RUN_COLUMNS = `id, session_id, mode, cwd, model, permission_mode, effort,
|
||||
resume_session_id, prompt_preview, status, exit_code,
|
||||
started_at, ended_at, lane_id, tool, worktree, proxy, account`;
|
||||
started_at, ended_at, lane_id, tool, worktree, proxy, account, started_by`;
|
||||
|
||||
const listStmt = db.prepare(`
|
||||
SELECT ${RUN_COLUMNS}
|
||||
@@ -128,7 +128,11 @@ function recordRun(handle) {
|
||||
proxy: handle.proxy || null,
|
||||
account: handle.account || null,
|
||||
pane_token_hash: handle.paneTokenHash || null,
|
||||
started_by: Number.isInteger(handle.startedBy) ? handle.startedBy : null,
|
||||
});
|
||||
// Who pays for the session it holds (session-payers.js) — a no-op for
|
||||
// the owner's own run of a session nobody else ran.
|
||||
if (handle.sessionId) require("./session-payers").noteRun(handle.id);
|
||||
} catch (err) {
|
||||
// Best-effort by design (a live run must never fail because sqlite did),
|
||||
// but not silent: a swallowed insert leaves the runs modal showing rows with
|
||||
@@ -151,6 +155,7 @@ function patchRun({ id, sessionId, status, exitCode, endedAt }) {
|
||||
exit_code: typeof exitCode === "number" ? exitCode : null,
|
||||
ended_at: endedAt ? new Date(endedAt).toISOString() : null,
|
||||
});
|
||||
if (sessionId) require("./session-payers").noteRun(id);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@@ -250,7 +255,15 @@ const claimRunStmt = db.prepare(`
|
||||
*/
|
||||
function claimToolSessions(sessionId = null) {
|
||||
try {
|
||||
if (sessionId) claimRunStmt.run({ id: sessionId });
|
||||
if (sessionId && claimRunStmt.run({ id: sessionId }).changes) {
|
||||
// The run just claimed it: the newest holding it.
|
||||
const r = db
|
||||
.prepare(
|
||||
"SELECT id FROM dashboard_runs WHERE session_id = ? ORDER BY started_at DESC LIMIT 1"
|
||||
)
|
||||
.get(sessionId);
|
||||
if (r) require("./session-payers").noteRun(r.id);
|
||||
}
|
||||
return claimToolStmt.run({ id: sessionId }).changes;
|
||||
} catch {
|
||||
return 0;
|
||||
|
||||
@@ -331,6 +331,13 @@ function setProvisioningFacts(id, facts = {}) {
|
||||
|
||||
function deleteLane(id) {
|
||||
const gone = db.prepare("DELETE FROM lanes WHERE id = ?").run(id).changes > 0;
|
||||
// Who it was shared with goes with it (lane_shares has no foreign key).
|
||||
if (gone) {
|
||||
db.prepare("DELETE FROM lane_shares WHERE lane_id = ?").run(id);
|
||||
db.prepare(
|
||||
"DELETE FROM session_shares WHERE session_id IN (SELECT id FROM sessions WHERE lane_id = ?)"
|
||||
).run(id);
|
||||
}
|
||||
// Its `lane_sources` rows cascade; AgentHub's own copies of its uploaded
|
||||
// context files go with them. A folder source is the user's and stays.
|
||||
// Lazy: lane-sources.js reads the db directly and must not load at import.
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* @file pane-presence.js
|
||||
* @description Who has which pane open right now (server mode, workspace
|
||||
* sharing phase 4): every terminal attach (`/ws-pty/:runId`, websocket.js)
|
||||
* adds its logged-in user to its pane, and its close takes them off. In
|
||||
* memory only — a restart drops every attach anyway. A change is broadcast as
|
||||
* `pane_presence` `{laneId, runId, users}` to the workspace's owner and the
|
||||
* users it is shared with; `GET /api/lanes/:id/presence` gives the current
|
||||
* state. The first keystroke of an attach into a SHARED workspace's pane by
|
||||
* anyone but its owner is written to `audit_log` (`type into <run id>`) — who
|
||||
* typed, never what.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
/** runId → Map(userId → {id, name, n}) — `n` attaches of that user. */
|
||||
const panes = new Map();
|
||||
|
||||
const laneOf = (runId) => {
|
||||
const m = /^agenthub-lane-(\d+)(?:-\d+)?$/.exec(String(runId || ""));
|
||||
return m ? Number(m[1]) : null;
|
||||
};
|
||||
|
||||
const nameOf = (user) => user.displayName || user.display_name || user.username;
|
||||
|
||||
function users(runId) {
|
||||
return [...(panes.get(runId)?.values() || [])].map(({ id, name }) => ({ id, name }));
|
||||
}
|
||||
|
||||
function announce(runId) {
|
||||
try {
|
||||
require("../websocket").broadcast("pane_presence", {
|
||||
laneId: laneOf(runId),
|
||||
runId,
|
||||
users: users(runId),
|
||||
});
|
||||
} catch {
|
||||
/* no websocket server (tests) */
|
||||
}
|
||||
}
|
||||
|
||||
/** `user` opened pane `runId`. */
|
||||
function join(runId, user) {
|
||||
if (!user || laneOf(runId) == null) return;
|
||||
if (!panes.has(runId)) panes.set(runId, new Map());
|
||||
const here = panes.get(runId);
|
||||
const me = here.get(user.id);
|
||||
if (me) {
|
||||
me.n += 1;
|
||||
return;
|
||||
}
|
||||
here.set(user.id, { id: user.id, name: nameOf(user), n: 1 });
|
||||
announce(runId);
|
||||
}
|
||||
|
||||
/** `user` closed one attach of pane `runId`. */
|
||||
function leave(runId, user) {
|
||||
const here = user && panes.get(runId);
|
||||
const me = here?.get(user.id);
|
||||
if (!me) return;
|
||||
me.n -= 1;
|
||||
if (me.n > 0) return;
|
||||
here.delete(user.id);
|
||||
if (!here.size) panes.delete(runId);
|
||||
announce(runId);
|
||||
}
|
||||
|
||||
/** `{runId: [{id, name}]}` for workspace `laneId`'s panes. */
|
||||
function forLane(laneId) {
|
||||
const out = {};
|
||||
for (const runId of panes.keys()) {
|
||||
if (laneOf(runId) === Number(laneId)) out[runId] = users(runId);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether workspace `laneId` is shared with anyone, whole or a session of it. */
|
||||
function isShared(laneId) {
|
||||
const { db } = require("../db");
|
||||
return Boolean(
|
||||
db
|
||||
.prepare(
|
||||
`SELECT 1 FROM lane_shares WHERE lane_id = ?
|
||||
UNION ALL SELECT 1 FROM session_shares
|
||||
WHERE session_id IN (SELECT id FROM sessions WHERE lane_id = ?) LIMIT 1`
|
||||
)
|
||||
.get(laneId, laneId)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The first keystroke of an attach: in a shared workspace, write who typed
|
||||
* into which pane (`audit_log`, owner = the workspace's owner). Best effort.
|
||||
*/
|
||||
function auditInput(runId, user) {
|
||||
const laneId = laneOf(runId);
|
||||
if (!user || laneId == null) return;
|
||||
try {
|
||||
if (!isShared(laneId)) return;
|
||||
const { db } = require("../db");
|
||||
const owner = db.prepare("SELECT owner_id FROM lanes WHERE id = ?").get(laneId)?.owner_id;
|
||||
if (owner === user.id) return; // the owner in their own workspace
|
||||
require("./audit").recordAccountChange(user.id, owner ?? null, "PTY", `type into ${runId}`);
|
||||
} catch (err) {
|
||||
console.warn("[presence] could not audit:", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
const __reset = () => panes.clear();
|
||||
|
||||
module.exports = { join, leave, forLane, auditInput, users, __reset };
|
||||
@@ -82,6 +82,17 @@ const PASTE_HOLD_MS = 700;
|
||||
// keystroke first leaves copy-mode (`tmux.leaveCopyMode`), then is written.
|
||||
const NOT_TYPING_RE = /\x1b\[<\d+;\d+;\d+[Mm]|\x1b\[M[\s\S]{3}|\x1b\[[IO]/g;
|
||||
|
||||
// What the browser's terminal sends back on its own when tmux asks it
|
||||
// something on attach (device attributes, cursor/status reports, mode
|
||||
// reports, colour queries): no one typed it.
|
||||
const TERMINAL_REPLY_RE =
|
||||
/\x1b\[[?>=]?[\d;]*[cRn]|\x1b\[\?[\d;]*\$y|\x1bP[\s\S]*?\x1b\\|\x1b\][\s\S]*?(?:\x07|\x1b\\)/g;
|
||||
|
||||
/** Whether `text` from a browser is someone typing (not a mouse, focus or terminal reply). */
|
||||
function isTyping(text) {
|
||||
return text.replace(NOT_TYPING_RE, "").replace(TERMINAL_REPLY_RE, "") !== "";
|
||||
}
|
||||
|
||||
// runId -> { driver, viewers: Set<{ ws, pty, cols, rows }>, scrolled }
|
||||
// (`scrolled`: a mouse report reached the pane since the last keystroke — per
|
||||
// pane, since one browser may scroll and another type)
|
||||
@@ -333,4 +344,11 @@ __setSpawnImpl((...args) => require("@lydell/node-pty").spawn(...args));
|
||||
|
||||
const __resetGroups = () => groups.clear();
|
||||
|
||||
module.exports = { attach, attachBinary, validateRunId, __setSpawnImpl, __resetGroups };
|
||||
module.exports = {
|
||||
attach,
|
||||
attachBinary,
|
||||
validateRunId,
|
||||
isTyping,
|
||||
__setSpawnImpl,
|
||||
__resetGroups,
|
||||
};
|
||||
|
||||
+76
-10
@@ -419,6 +419,7 @@ function spawnRun(args) {
|
||||
bypass,
|
||||
initialPrompt,
|
||||
proxy,
|
||||
startedBy,
|
||||
} = args || {};
|
||||
if (typeof laneId !== "number" || !Number.isInteger(laneId)) {
|
||||
throw makeErr("EBADLANE", "laneId must be an integer");
|
||||
@@ -497,10 +498,16 @@ function spawnRun(args) {
|
||||
// their .mcp.json) or a member in someone else's.
|
||||
if (lane) require("./run-as").assertOwnerFits(lane.cwd, laneOwner); // EOWNERFOLDER
|
||||
assertCwdAccount(laneId, cwd); // ECWDACCOUNT
|
||||
// Server mode: an owner over their spend quota starts nothing new (user-quota.js).
|
||||
require("./user-quota").assertSpawnAllowed(laneOwner); // EQUOTA
|
||||
// Who pays (sharing phase 2): a user the workspace is shared with runs on
|
||||
// their OWN account — a pool token or API key, or an AI Proxy of theirs —
|
||||
// under their own quota, never on the owner's login (session-payers.js).
|
||||
const payer =
|
||||
lane && Number.isInteger(startedBy) && startedBy !== laneOwner ? startedBy : laneOwner;
|
||||
const collab = payer !== laneOwner;
|
||||
// Server mode: a payer over their spend quota starts nothing new (user-quota.js).
|
||||
require("./user-quota").assertSpawnAllowed(payer); // EQUOTA
|
||||
assertSessionRoom(laneId); // ESESSIONLIMIT
|
||||
const proxyProfile = resolveProxy(tool, proxy, laneOwner); // EBADPROXY, EUNSUPPORTED
|
||||
const proxyProfile = resolveProxy(tool, proxy, payer); // EBADPROXY, EUNSUPPORTED
|
||||
// A Claude session on the vendor's own API runs on the least-loaded pool
|
||||
// account, if the admin added any (claude-pool.js) — or the one the
|
||||
// workspace owner is pinned to (account-pins.js); an AI Proxy brings its
|
||||
@@ -509,21 +516,56 @@ function spawnRun(args) {
|
||||
// a setup-token goes in as CLAUDE_CODE_OAUTH_TOKEN.
|
||||
const poolAccount =
|
||||
entry.launcher === "claude" && !proxyProfile
|
||||
? require("./claude-pool").forSpawn(require("./run-as").accountForLane(laneId), laneOwner)
|
||||
? collab
|
||||
? require("./claude-pool").forCollaborator(payer)
|
||||
: require("./claude-pool").forSpawn(require("./run-as").accountForLane(laneId), laneOwner)
|
||||
: null;
|
||||
// Codex likewise, from its own pool (codex-pool.js): an API key through
|
||||
// `-e`, or a ChatGPT login written into the member's CODEX_HOME by place().
|
||||
const codexPool =
|
||||
entry.launcher === "codex" && !proxyProfile
|
||||
? require("./codex-pool").forSpawn(require("./run-as").accountForLane(laneId), laneOwner)
|
||||
? collab
|
||||
? require("./codex-pool").forCollaborator(payer)
|
||||
: require("./codex-pool").forSpawn(require("./run-as").accountForLane(laneId), laneOwner)
|
||||
: null;
|
||||
// Cursor's pool is API keys only (cursor-pool.js): CURSOR_API_KEY through `-e`.
|
||||
const cursorPool = tool === "cursor" ? require("./cursor-pool").forSpawn(laneOwner) : null;
|
||||
const cursorPool = tool === "cursor" ? require("./cursor-pool").forSpawn(payer) : null;
|
||||
// Only a Claude session books its spend by the hour, so only it can change
|
||||
// hands mid-way (session-payers.js): any other tool's whole session is
|
||||
// billed at its start hour, and a resume across payers would bill the wrong
|
||||
// one. `resumeLast` names no session, so its payer could not be known.
|
||||
if (collab && resumeLast === true) {
|
||||
throw makeErr(
|
||||
"ECOLLABRESUME",
|
||||
"in a workspace shared with you, resume a session by picking it — not the latest one"
|
||||
);
|
||||
}
|
||||
if (
|
||||
resumeSessionId &&
|
||||
laneOwner != null &&
|
||||
entry.launcher !== "claude" &&
|
||||
require("./session-payers").currentPayer(resumeSessionId, laneOwner) !== payer
|
||||
) {
|
||||
throw makeErr(
|
||||
"ECOLLABRESUME",
|
||||
`${tool} books a session's spend at its start, so only the user who pays for it may resume it — start a new session instead`
|
||||
);
|
||||
}
|
||||
// Any other tool, or no account of their own, would run on the owner's
|
||||
// login in the owner's home: refused.
|
||||
if (collab && !proxyProfile && !poolAccount && !codexPool && !cursorPool) {
|
||||
throw makeErr(
|
||||
"ENOCOLLABACCOUNT",
|
||||
"this workspace is shared with you, so a session you start must run on your own account — " +
|
||||
"a pool account an admin gave you, or an AI Proxy of yours — and you have none for " +
|
||||
`${tool}. The owner's own login is never used for you.`
|
||||
);
|
||||
}
|
||||
const paneCred = require("./auth").newPaneToken();
|
||||
// A member's omp on the host's shared omp login (omp-share.js): its
|
||||
// models.yml points at the loopback gateway, with a key already listed there.
|
||||
const ompShare =
|
||||
tool === "omp"
|
||||
tool === "omp" && !collab
|
||||
? require("./omp-share").forSpawn(
|
||||
require("./run-as").accountForLane(laneId),
|
||||
runIdForLane(laneId, slot)
|
||||
@@ -651,6 +693,7 @@ function spawnRun(args) {
|
||||
proxy: proxyProfile ? proxyProfile.name : null,
|
||||
account: (poolAccount || codexPool || cursorPool)?.name ?? null,
|
||||
paneTokenHash: paneCred ? paneCred.hash : null,
|
||||
startedBy: collab ? payer : null,
|
||||
prompt: initialPrompt || "",
|
||||
status: "running",
|
||||
startedAt,
|
||||
@@ -734,9 +777,9 @@ function spawnRun(args) {
|
||||
for (const k of Object.keys(env)) delete env[k];
|
||||
Object.assign(env, own);
|
||||
}
|
||||
// Server mode: where this pane's hooks look for its owner's quota flag
|
||||
// Server mode: where this pane's hooks look for its payer's quota flag
|
||||
// (user-quota.js) — a refused prompt is decided by the hook, locally.
|
||||
Object.assign(env, require("./user-quota").flagEnv(laneOwner, member));
|
||||
Object.assign(env, require("./user-quota").flagEnv(payer, member, laneOwner));
|
||||
|
||||
// `after-start` tools take no prompt on their command line: paste it once
|
||||
// the CLI has had `delayMs` to draw its input box. ponytail: fixed delay,
|
||||
@@ -759,6 +802,9 @@ function spawnRun(args) {
|
||||
const prepareHome = () => {
|
||||
codexPool?.place();
|
||||
poolAccount?.place();
|
||||
// A collaborator's flag sits in the owner's handoff dir: write its state
|
||||
// now, so one left from an earlier share never says the wrong thing.
|
||||
if (collab) require("./user-quota").writeCollabFlag(payer, member);
|
||||
ompShare?.place();
|
||||
if (member && entry.launcher === "claude" && (poolAccount || proxyProfile)) {
|
||||
require("./run-as").markClaudeOnboarded(member);
|
||||
@@ -808,7 +854,9 @@ function spawnRun(args) {
|
||||
* `shell` so the tab can say what it is. The caller has already made sure the
|
||||
* slot holds no live session.
|
||||
*/
|
||||
function spawnShell({ laneId, slot = 0, cwd }) {
|
||||
/** `startedBy`: the user opening it when that is not the workspace's owner (a
|
||||
* workspace shared with them) — its pane token then acts as them. */
|
||||
function spawnShell({ laneId, slot = 0, cwd, startedBy = null }) {
|
||||
if (!Number.isInteger(laneId)) throw makeErr("EBADLANE", "laneId must be an integer");
|
||||
if (!Number.isInteger(slot) || slot < 0 || slot > MAX_PANE_SLOT) {
|
||||
throw makeErr("EBADSLOT", `slot must be an integer 0–${MAX_PANE_SLOT}`);
|
||||
@@ -844,6 +892,8 @@ function spawnShell({ laneId, slot = 0, cwd }) {
|
||||
worktree: false,
|
||||
proxy: null,
|
||||
paneTokenHash: paneCred ? paneCred.hash : null,
|
||||
startedBy:
|
||||
lane && Number.isInteger(startedBy) && startedBy !== lane.owner_id ? startedBy : null,
|
||||
prompt: "",
|
||||
status: "running",
|
||||
startedAt: Date.now(),
|
||||
@@ -884,9 +934,25 @@ function publicRun(id, live = tmux.hasSession(id)) {
|
||||
worktree: !!row?.worktree,
|
||||
startedAt: row?.started_at || null,
|
||||
promptPreview: row?.prompt_preview || null,
|
||||
// Server mode: a pane a user the workspace is shared with opened — whose
|
||||
// money it is (session-payers.js). Null = the workspace's owner.
|
||||
startedBy: row?.started_by != null ? starterOf(row.started_by) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function starterOf(userId) {
|
||||
try {
|
||||
const u = require("../db")
|
||||
.db.prepare(
|
||||
"SELECT id, COALESCE(NULLIF(display_name, ''), username) AS name FROM users WHERE id = ?"
|
||||
)
|
||||
.get(userId);
|
||||
return u ? { id: u.id, name: u.name } : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getRun(id) {
|
||||
if (laneIdFromRunId(id) === null) return null;
|
||||
return publicRun(id);
|
||||
|
||||
+235
-26
@@ -3,7 +3,10 @@
|
||||
* @description Server mode's row ownership (phase S2, docs/SERVER-MODE.md) —
|
||||
* the ONE place that decides which rows a request may see.
|
||||
*
|
||||
* A workspace (`lanes.owner_id`) belongs to the user who created it. A session
|
||||
* A workspace (`lanes.owner_id`) belongs to the user who created it, and may be
|
||||
* SHARED with other users (`lane_shares`): they see it and work in it like its
|
||||
* owner — visibility here — while owner-only actions check `isLaneOwner`, and
|
||||
* personal figures (Today, budgets) stay on owned rows only. A session
|
||||
* belongs to its workspace: `sessions.lane_id`, or a `dashboard_runs` row of
|
||||
* that workspace holding it (a session not stamped yet). A session no workspace owns
|
||||
* belongs to the user of the Linux account it ran as (`sessions.account`,
|
||||
@@ -41,7 +44,16 @@ const ownerFor = (req) => (req?.user ? req.user.id : null);
|
||||
* unrestricted. `col` is the session id expression, `laneCol` its lane id.
|
||||
*/
|
||||
function sessionWhere(req, col = "id", laneCol = "lane_id") {
|
||||
return ownedSessionWhere(memberId(req), col, laneCol);
|
||||
return ownedSessionWhere(memberId(req), col, laneCol, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* `sessionWhere` without shared workspaces: what this request's user OWNS —
|
||||
* for their own money (budgets), never another user's spend in a workspace
|
||||
* shared with them. "1" when unrestricted, like `sessionWhere`.
|
||||
*/
|
||||
function ownedOnlySessionWhere(req, col = "id", laneCol = "lane_id") {
|
||||
return ownedSessionWhere(memberId(req), col, laneCol, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,15 +65,32 @@ function ownSessionWhere(req, col = "id", laneCol = "lane_id") {
|
||||
return ownedSessionWhere(req?.user ? req.user.id : null, col, laneCol);
|
||||
}
|
||||
|
||||
function ownedSessionWhere(uid, col, laneCol) {
|
||||
// The workspaces a user owns or that are shared with them (2 params: uid, uid).
|
||||
const MY_LANES =
|
||||
"SELECT id FROM lanes WHERE owner_id = ? UNION SELECT lane_id FROM lane_shares WHERE user_id = ?";
|
||||
// The sessions shared with a user one by one (1 param: uid), and the
|
||||
// workspaces holding them (sharing phase 3: seen, but only that session).
|
||||
const MY_SESSIONS = "SELECT session_id FROM session_shares WHERE user_id = ?";
|
||||
const SESSION_LANES = `SELECT lane_id FROM sessions WHERE lane_id IS NOT NULL AND id IN (${MY_SESSIONS})`;
|
||||
// Every workspace a user may open (3 params: uid ×3).
|
||||
const SEEN_LANES = `${MY_LANES} UNION ${SESSION_LANES}`;
|
||||
|
||||
function ownedSessionWhere(uid, col, laneCol, shared = false) {
|
||||
if (uid == null) return { where: "1", params: [] };
|
||||
const lanes = shared ? MY_LANES : "SELECT id FROM lanes WHERE owner_id = ?";
|
||||
const lp = shared ? [uid, uid] : [uid];
|
||||
return {
|
||||
where: `(${laneCol} IN (SELECT id FROM lanes WHERE owner_id = ?)
|
||||
OR ${col} IN (SELECT r.session_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
|
||||
WHERE l.owner_id = ? AND r.session_id IS NOT NULL)
|
||||
where: `(${laneCol} IN (${lanes})
|
||||
OR ${col} IN (SELECT r.session_id FROM dashboard_runs r
|
||||
WHERE r.lane_id IN (${lanes}) AND r.session_id IS NOT NULL)
|
||||
OR ${col} IN (SELECT id FROM sessions WHERE owner_id = ?)
|
||||
OR ${col} IN (SELECT session_id FROM (${ACCOUNT_OWNED}) WHERE uid = ?))`,
|
||||
params: [uid, uid, uid, uid],
|
||||
OR ${col} IN (SELECT session_id FROM (${ACCOUNT_OWNED}) WHERE uid = ?)${
|
||||
shared
|
||||
? `
|
||||
OR ${col} IN (${MY_SESSIONS})`
|
||||
: ""
|
||||
})`,
|
||||
params: [...lp, ...lp, uid, uid, ...(shared ? [uid] : [])],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -77,7 +106,56 @@ function bySessionWhere(req, col = "session_id") {
|
||||
function laneWhere(req, col = "id") {
|
||||
const uid = memberId(req);
|
||||
if (uid == null) return { where: "1", params: [] };
|
||||
return { where: `${col} IN (SELECT id FROM lanes WHERE owner_id = ?)`, params: [uid] };
|
||||
return { where: `${col} IN (${SEEN_LANES})`, params: [uid, uid, uid] };
|
||||
}
|
||||
|
||||
/** Whether session `sessionId` is shared with `userId` on its own (phase 3). */
|
||||
function sessionSharedWith(sessionId, userId) {
|
||||
if (!sessionId || userId == null) return false;
|
||||
return Boolean(
|
||||
sql("SELECT 1 FROM session_shares WHERE session_id = ? AND user_id = ?").get(
|
||||
String(sessionId),
|
||||
userId
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of workspace `laneId` this request may use: `all` (local mode, an
|
||||
* admin or analyst read, its owner, a user it is shared with), `session`
|
||||
* (only sessions shared with them one by one), or null.
|
||||
*/
|
||||
function laneAccess(req, laneId) {
|
||||
const uid = memberId(req);
|
||||
if (uid == null) return "all";
|
||||
const v = typeof laneId === "number" ? laneId : String(laneId);
|
||||
const row = sql("SELECT id, owner_id FROM lanes WHERE id = ?").get(v);
|
||||
if (!row) return null;
|
||||
if (row.owner_id === uid || sharedWith(row.id, uid)) return "all";
|
||||
const one = sql(
|
||||
`SELECT 1 FROM sessions WHERE lane_id = ? AND id IN (${MY_SESSIONS}) LIMIT 1`
|
||||
).get(row.id, uid);
|
||||
return one ? "session" : null;
|
||||
}
|
||||
|
||||
/** Whether `userId` is one of the users workspace `laneId` is shared with. */
|
||||
function sharedWith(laneId, userId) {
|
||||
if (laneId == null || userId == null) return false;
|
||||
return Boolean(
|
||||
sql("SELECT 1 FROM lane_shares WHERE lane_id = ? AND user_id = ?").get(Number(laneId), userId)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner-only actions on a workspace (rename, reset, remove, sharing): its
|
||||
* owner or an admin; always true in local mode. A user it is shared with may
|
||||
* do everything else, which `canSeeLane` decides.
|
||||
*/
|
||||
function isLaneOwner(req, laneId) {
|
||||
const u = req?.user;
|
||||
if (!u || u.role === "admin") return true;
|
||||
const row = sql("SELECT owner_id FROM lanes WHERE id = ?").get(Number(laneId));
|
||||
return Boolean(row) && row.owner_id === u.id;
|
||||
}
|
||||
|
||||
function canSeeLane(req, laneId) {
|
||||
@@ -86,9 +164,7 @@ function canSeeLane(req, laneId) {
|
||||
// Bound as given, like getLane binds a route param: SQLite's integer
|
||||
// affinity reads '9002.0' or ' 9002' as 9002 for both, so the row checked
|
||||
// here is the row the route would load.
|
||||
const v = typeof laneId === "number" ? laneId : String(laneId);
|
||||
const row = sql("SELECT owner_id FROM lanes WHERE id = ?").get(v);
|
||||
return Boolean(row) && row.owner_id === uid;
|
||||
return laneAccess(req, laneId) != null;
|
||||
}
|
||||
|
||||
function canSeeSession(req, sessionId) {
|
||||
@@ -109,7 +185,13 @@ function canSeeAgent(req, agentId) {
|
||||
function canSeeRun(req, runId) {
|
||||
if (memberId(req) == null) return true;
|
||||
const m = /^agenthub-lane-(\d+)(?:-\d+)?(?:@.*)?$/.exec(String(runId || ""));
|
||||
if (m) return canSeeLane(req, m[1]);
|
||||
if (m) {
|
||||
const access = laneAccess(req, m[1]);
|
||||
if (access !== "session") return access != null;
|
||||
// A session shared on its own: only the pane holding that session.
|
||||
const row = sql("SELECT session_id FROM dashboard_runs WHERE id = ?").get(String(runId));
|
||||
return Boolean(row?.session_id) && sessionSharedWith(row.session_id, memberId(req));
|
||||
}
|
||||
const row = sql("SELECT lane_id FROM dashboard_runs WHERE id = ?").get(String(runId));
|
||||
return Boolean(row && row.lane_id != null) && canSeeLane(req, row.lane_id);
|
||||
}
|
||||
@@ -118,9 +200,9 @@ function canSeeRun(req, runId) {
|
||||
function visibleLaneIds(req) {
|
||||
const uid = memberId(req);
|
||||
if (uid == null) return null;
|
||||
return sql("SELECT id FROM lanes WHERE owner_id = ?")
|
||||
.all(uid)
|
||||
.map((r) => r.id);
|
||||
return sql(SEEN_LANES)
|
||||
.all(uid, uid, uid)
|
||||
.map((r) => r.lane_id ?? r.id);
|
||||
}
|
||||
|
||||
/** A row of `table` (`id` = `rowId`) whose `session_id` this request may see. */
|
||||
@@ -133,8 +215,11 @@ function canSeeRowSession(req, table, rowId, idCol = "id") {
|
||||
/** A `dashboard_runs` row (`/api/run/history/:id`) of one of this request's workspaces. */
|
||||
function canSeeRunRow(req, id) {
|
||||
if (memberId(req) == null) return true;
|
||||
const row = sql("SELECT lane_id FROM dashboard_runs WHERE id = ?").get(String(id));
|
||||
return Boolean(row && row.lane_id != null) && canSeeLane(req, row.lane_id);
|
||||
const row = sql("SELECT lane_id, session_id FROM dashboard_runs WHERE id = ?").get(String(id));
|
||||
if (!row || row.lane_id == null) return false;
|
||||
const access = laneAccess(req, row.lane_id);
|
||||
if (access !== "session") return access != null;
|
||||
return Boolean(row.session_id) && sessionSharedWith(row.session_id, memberId(req));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -235,6 +320,28 @@ function scopeGuard(req, res, next) {
|
||||
if (bad) return notFound();
|
||||
if (lanes.some((id) => !/^\d+$/.test(id) || !canSeeLane(req, Number(id)))) return notFound();
|
||||
if (sessions.some((id) => !canSeeSession(req, id))) return notFound();
|
||||
// A workspace seen only through a session shared on its own (phase 3):
|
||||
// that session, its pane and the workspace's Changes — nothing else of it.
|
||||
const write = req.method !== "GET" && req.method !== "HEAD";
|
||||
const pm = /^\/(?:lanes|workspaces)\/(\d+)(\/.*)?$/i.exec(p);
|
||||
if (
|
||||
pm &&
|
||||
laneAccess(req, Number(pm[1])) === "session" &&
|
||||
!sessionShareAllows(req, pm[2] || "", Number(pm[1]))
|
||||
) {
|
||||
return sessionOnly(res);
|
||||
}
|
||||
const viaSession = lanes.some((id) => laneAccess(req, Number(id)) === "session");
|
||||
// Workspace-wide reads by `?laneId=`: files and skills of every session, stage history.
|
||||
if (
|
||||
viaSession &&
|
||||
(write || /^\/(artifacts|lanes\/pipeline-stats|workspaces\/pipeline-stats)(\/|$)/i.test(p))
|
||||
) {
|
||||
return sessionOnly(res);
|
||||
}
|
||||
// The shared session itself: open it, never rename or archive it.
|
||||
const sm = /^\/sessions\/([^/]+)/i.exec(p);
|
||||
if (write && sm && sessionOnlyVia(req, sm[1])) return sessionOnly(res);
|
||||
// S3: a WRITE to a workspace re-checks that its owner may still own that
|
||||
// folder, by the LIVE role — an admin demoted since keeps owning their
|
||||
// host-folder workspaces, and `/up`, `/hook`, a commit (git hooks) or a
|
||||
@@ -255,6 +362,55 @@ function scopeGuard(req, res, next) {
|
||||
return next();
|
||||
}
|
||||
|
||||
/** Whether this request sees session `sid` only because it is shared with them on its own. */
|
||||
function sessionOnlyVia(req, sid) {
|
||||
const uid = memberId(req);
|
||||
if (uid == null || !sessionSharedWith(sid, uid)) return false;
|
||||
const row = sql("SELECT lane_id FROM sessions WHERE id = ?").get(String(sid));
|
||||
return !row?.lane_id || laneAccess(req, row.lane_id) === "session";
|
||||
}
|
||||
|
||||
const sessionOnly = (res) =>
|
||||
res.status(403).json({
|
||||
error: {
|
||||
code: "ESESSIONSHARE",
|
||||
message: "only a session of this workspace is shared with you: open that session",
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* What a user with only a session of workspace (rest = the path after
|
||||
* `/lanes/<id>`) may call there: reads of the workspace, its git, files and
|
||||
* share list (not its instructions or context); git writes; and a `start` that
|
||||
* resumes a session shared with them — no new session, fork or terminal.
|
||||
*/
|
||||
function sessionShareAllows(req, rest, laneId) {
|
||||
const r = rest.toLowerCase();
|
||||
// A workspace's extra folders are its own, not the session's.
|
||||
if (req.query?.source !== undefined) return false;
|
||||
if (req.method === "GET" || req.method === "HEAD") {
|
||||
return r === "" || r === "/" || /^\/(git|fs|shares)(\/|$)/.test(r);
|
||||
}
|
||||
if (/^\/git\//.test(r)) return true;
|
||||
if (r === "/start") {
|
||||
const b = req.body && typeof req.body === "object" ? req.body : {};
|
||||
return (
|
||||
typeof b.resumeSessionId === "string" &&
|
||||
b.forkSession !== true &&
|
||||
b.shell !== true &&
|
||||
b.resume !== true &&
|
||||
// A free slot the server picks (no slot means pane 0, the workspace's
|
||||
// own run — another user's live agent there would answer ERUNLIVE).
|
||||
b.slot === "auto" &&
|
||||
sessionSharedWith(b.resumeSessionId, memberId(req)) &&
|
||||
Boolean(
|
||||
sql("SELECT 1 FROM sessions WHERE id = ? AND lane_id = ?").get(b.resumeSessionId, laneId)
|
||||
)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether a workspace's owner may still own its folder (S3, live role). */
|
||||
function ownerStillFits(laneId) {
|
||||
const lane = sql("SELECT cwd, owner_id FROM lanes WHERE id = ?").get(laneId);
|
||||
@@ -292,6 +448,42 @@ function laneOwners(laneId) {
|
||||
return new Set(row && row.owner_id != null ? [row.owner_id] : []);
|
||||
}
|
||||
|
||||
/**
|
||||
* The users a workspace is shared with — they get its news, but it is not
|
||||
* "theirs". `sessions`: also those with only a session of it (its row
|
||||
* changes, never its stack's output).
|
||||
*/
|
||||
function laneViewers(laneId, { sessions = false } = {}) {
|
||||
if (laneId == null) return new Set();
|
||||
return new Set(
|
||||
sql(
|
||||
`SELECT user_id FROM lane_shares WHERE lane_id = ?${
|
||||
sessions
|
||||
? ` UNION SELECT user_id FROM session_shares
|
||||
WHERE session_id IN (SELECT id FROM sessions WHERE lane_id = ?)`
|
||||
: ""
|
||||
}`
|
||||
)
|
||||
.all(...(sessions ? [Number(laneId), Number(laneId)] : [Number(laneId)]))
|
||||
.map((r) => r.user_id)
|
||||
);
|
||||
}
|
||||
|
||||
/** The users the workspace holding a session is shared with. */
|
||||
function sessionViewers(sessionId) {
|
||||
if (!sessionId) return new Set();
|
||||
return new Set(
|
||||
sql(
|
||||
`SELECT user_id FROM lane_shares WHERE lane_id IN (
|
||||
SELECT lane_id FROM sessions WHERE id = ? AND lane_id IS NOT NULL
|
||||
UNION SELECT lane_id FROM dashboard_runs WHERE session_id = ? AND lane_id IS NOT NULL)
|
||||
UNION SELECT user_id FROM session_shares WHERE session_id = ?`
|
||||
)
|
||||
.all(String(sessionId), String(sessionId), String(sessionId))
|
||||
.map((r) => r.user_id)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Who a broadcast may reach: `null` = every client, `{owners: Set<userId>}` =
|
||||
* admin/analyst plus those members, `{staffOnly: true}` = admin/analyst only.
|
||||
@@ -303,25 +495,31 @@ function broadcastAudience(type, data) {
|
||||
switch (type) {
|
||||
case "session_created":
|
||||
case "session_updated":
|
||||
return { owners: sessionOwners(d.id) };
|
||||
return { owners: sessionOwners(d.id), viewers: sessionViewers(d.id) };
|
||||
case "agent_created":
|
||||
case "agent_updated":
|
||||
case "new_event":
|
||||
case "workflow_upserted":
|
||||
case "transcript_changed":
|
||||
return { owners: sessionOwners(d.session_id) };
|
||||
return { owners: sessionOwners(d.session_id), viewers: sessionViewers(d.session_id) };
|
||||
case "alert_triggered":
|
||||
case "alert_updated":
|
||||
if (d.acked_all) return null;
|
||||
return d.session_id ? { owners: sessionOwners(d.session_id) } : STAFF;
|
||||
return d.session_id
|
||||
? { owners: sessionOwners(d.session_id), viewers: sessionViewers(d.session_id) }
|
||||
: STAFF;
|
||||
case "lane_update":
|
||||
// A removal names an id that no longer resolves; it reveals nothing.
|
||||
if (d.removed != null && !d.lane) return null;
|
||||
return { owners: laneOwners(d.lane?.id) };
|
||||
return {
|
||||
owners: laneOwners(d.lane?.id),
|
||||
viewers: laneViewers(d.lane?.id, { sessions: true }),
|
||||
};
|
||||
case "pane_presence":
|
||||
case "lane_hook_output":
|
||||
case "lane_hook_result":
|
||||
case "lane_runtime":
|
||||
return { owners: laneOwners(d.laneId) };
|
||||
return { owners: laneOwners(d.laneId), viewers: laneViewers(d.laneId) };
|
||||
// A shared artifact is everyone's news; a private one, its owner's and
|
||||
// the people it is shared with by name.
|
||||
case "artifact_changed":
|
||||
@@ -359,6 +557,8 @@ function broadcastAudience(type, data) {
|
||||
function exactAudience(type, data) {
|
||||
const d = data && typeof data === "object" ? data : {};
|
||||
if (type === "cc_config_changed" && d.ownerId != null) return new Set([d.ownerId]);
|
||||
// A workspace no longer shared with these users: only they re-read their list.
|
||||
if (type === "lane_access" && Array.isArray(d.userIds)) return new Set(d.userIds);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -366,7 +566,10 @@ function exactAudience(type, data) {
|
||||
function audienceIncludes(audience, user) {
|
||||
if (!user || user.role !== "developer") return true;
|
||||
if (audience === null || audience.strip) return true;
|
||||
return Boolean(audience.owners && audience.owners.has(user.id));
|
||||
return Boolean(
|
||||
(audience.owners && audience.owners.has(user.id)) ||
|
||||
(audience.viewers && audience.viewers.has(user.id))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -437,8 +640,8 @@ function insideOwnWorkspace(req, dir) {
|
||||
const u = req?.user;
|
||||
if (!u || u.role === "admin") return true;
|
||||
return insideLanes(
|
||||
sql("SELECT id FROM lanes WHERE owner_id = ?")
|
||||
.all(u.id)
|
||||
sql(MY_LANES)
|
||||
.all(u.id, u.id)
|
||||
.map((r) => r.id),
|
||||
dir
|
||||
);
|
||||
@@ -488,12 +691,18 @@ module.exports = {
|
||||
PATH_RULES,
|
||||
canSeeRowSession,
|
||||
canSeeRunRow,
|
||||
laneAccess,
|
||||
sessionSharedWith,
|
||||
folderAllowed,
|
||||
ownFolder,
|
||||
memberId,
|
||||
ownerFor,
|
||||
sessionWhere,
|
||||
ownSessionWhere,
|
||||
ownedOnlySessionWhere,
|
||||
isLaneOwner,
|
||||
sharedWith,
|
||||
laneViewers,
|
||||
bySessionWhere,
|
||||
laneWhere,
|
||||
canSeeLane,
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* @file session-payers.js
|
||||
* @description Who pays for a session, hour by hour (server mode, workspace
|
||||
* sharing phase 2 — docs/plans/workspace-sharing/). A session is its
|
||||
* workspace OWNER's money until someone else runs it: a user the workspace is
|
||||
* shared with starts or resumes it (`dashboard_runs.started_by`), and from
|
||||
* then on it is theirs — until the owner (or another collaborator) runs it
|
||||
* again. Recorded in `session_payers` (session, from UTC hour, user); a
|
||||
* session with no row is billed exactly as before.
|
||||
*
|
||||
* Hours are the booking unit (`hourlyTokenRows`), so a switch takes effect
|
||||
* from the NEXT hour: the hour a resume happens in stays with the previous
|
||||
* payer, while a session the run itself started is the starter's from its
|
||||
* first hour (`0000`). The rest of a session's total that no hour holds is
|
||||
* booked at its start hour, like every other report.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const db = () => require("../db").db;
|
||||
|
||||
const WHOLE = "0000";
|
||||
const HOUR_MS = 3_600_000;
|
||||
const hourOf = (ms) => new Date(ms).toISOString().slice(0, 13);
|
||||
/** How far before its run a session may have started and still be the run's own (clock skew). */
|
||||
const NEW_SESSION_SLACK_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Note the payer of run `runId`'s session — its starter, else the workspace
|
||||
* owner — once the run knows its session. Best effort: a run never fails
|
||||
* because this did.
|
||||
*/
|
||||
function noteRun(runId, now = Date.now()) {
|
||||
try {
|
||||
const run = db()
|
||||
.prepare(
|
||||
`SELECT r.session_id, r.started_by, r.started_at, r.tool, l.owner_id
|
||||
FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id WHERE r.id = ?`
|
||||
)
|
||||
.get(runId);
|
||||
// A Terminal tab is no account of its starter's: a `claude` typed there
|
||||
// runs on the folder account's own login, so it stays the owner's money.
|
||||
if (!run?.session_id || run.owner_id == null || run.tool === "shell") return;
|
||||
const payer = run.started_by ?? run.owner_id;
|
||||
const put = db().prepare(
|
||||
"INSERT OR REPLACE INTO session_payers (session_id, from_hour, user_id) VALUES (?, ?, ?)"
|
||||
);
|
||||
db().transaction(() => {
|
||||
const rows = timeline(run.session_id);
|
||||
const current = rows.length ? rows[rows.length - 1].user_id : run.owner_id;
|
||||
if (current === payer) return;
|
||||
// The run's own new session (started with it, or not seen yet) is the
|
||||
// starter's whole; a resumed one changes hands from the hour after the
|
||||
// run started (a hook may tell us late).
|
||||
const s = db().prepare("SELECT started_at FROM sessions WHERE id = ?").get(run.session_id);
|
||||
const startedMs = Date.parse(run.started_at);
|
||||
const fresh = !s || Date.parse(s.started_at) >= startedMs - NEW_SESSION_SLACK_MS;
|
||||
const from =
|
||||
fresh && !rows.length
|
||||
? WHOLE
|
||||
: hourOf((Number.isFinite(startedMs) ? Math.min(startedMs, now) : now) + HOUR_MS);
|
||||
// The first change of hands: the owner's part becomes a row too, so the
|
||||
// timeline alone answers for every hour.
|
||||
if (!rows.length && from !== WHOLE) put.run(run.session_id, WHOLE, run.owner_id);
|
||||
put.run(run.session_id, from, payer);
|
||||
})();
|
||||
} catch (err) {
|
||||
console.warn(`[session-payers] run ${runId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Who pays for `sessionId` now: its timeline's last payer, else `ownerId`. */
|
||||
function currentPayer(sessionId, ownerId) {
|
||||
const rows = timeline(sessionId);
|
||||
return rows.length ? rows[rows.length - 1].user_id : ownerId;
|
||||
}
|
||||
|
||||
function timeline(sessionId) {
|
||||
return db()
|
||||
.prepare(
|
||||
"SELECT from_hour, user_id FROM session_payers WHERE session_id = ? ORDER BY from_hour"
|
||||
)
|
||||
.all(sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every split session's timeline: `{has(sessionId), payer(sessionId, hour)}`.
|
||||
* `hour` is an hourly row's `date` (`YYYY-MM-DDTHH`).
|
||||
*/
|
||||
function index() {
|
||||
const map = new Map();
|
||||
for (const r of db()
|
||||
.prepare("SELECT session_id, from_hour, user_id FROM session_payers ORDER BY from_hour")
|
||||
.all()) {
|
||||
if (!map.has(r.session_id)) map.set(r.session_id, []);
|
||||
map.get(r.session_id).push(r);
|
||||
}
|
||||
return {
|
||||
has: (sid) => map.has(sid),
|
||||
payer(sid, hour) {
|
||||
const rows = map.get(sid);
|
||||
if (!rows) return null;
|
||||
let uid = rows[0].user_id;
|
||||
for (const r of rows) {
|
||||
if (r.from_hour <= hour) uid = r.user_id;
|
||||
else break;
|
||||
}
|
||||
return uid;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** SQL: the split sessions (`s.id IN (…)` / `NOT IN`). */
|
||||
const SPLIT = "SELECT session_id FROM session_payers";
|
||||
|
||||
/**
|
||||
* Daily-shaped token rows (`date` = local date for `tzModifier`, as
|
||||
* `dailyTokenRows`) of the hours `uid` pays for in split sessions matching
|
||||
* `whereClause` — which must already narrow to `s.id IN (SPLIT)`.
|
||||
*/
|
||||
function paidDailyRows(uid, whereClause, params, tzModifier = "+0 minutes") {
|
||||
const { hourlyTokenRows } = require("../routes/pricing");
|
||||
const shift = Number.parseInt(String(tzModifier), 10) || 0;
|
||||
const idx = index();
|
||||
const out = [];
|
||||
for (const r of hourlyTokenRows(whereClause, params)) {
|
||||
if (idx.payer(r.session_id, r.date) !== uid) continue;
|
||||
const { session_id: _sid, ...row } = r;
|
||||
row.date = new Date(Date.parse(`${r.date}:00:00Z`) + shift * 60_000).toISOString().slice(0, 10);
|
||||
out.push(row);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Map(session id → first-wins owner) of `OWNED_SESSIONS`, with each hour's payer laid over it. */
|
||||
function payerResolver() {
|
||||
const { OWNED_SESSIONS } = require("../routes/users");
|
||||
const owner = new Map();
|
||||
for (const r of db().prepare(OWNED_SESSIONS).all()) {
|
||||
if (!owner.has(r.session_id)) owner.set(r.session_id, r.uid);
|
||||
}
|
||||
const idx = index();
|
||||
/** The user an hourly row's money is (null: nobody's). */
|
||||
return (row) =>
|
||||
idx.has(row.session_id)
|
||||
? idx.payer(row.session_id, row.date)
|
||||
: (owner.get(row.session_id) ?? null);
|
||||
}
|
||||
|
||||
module.exports = { noteRun, currentPayer, index, paidDailyRows, payerResolver, SPLIT, WHOLE };
|
||||
+106
-27
@@ -8,8 +8,10 @@
|
||||
* browser's getTimezoneOffset() when they saved it) or `5h` (a sliding
|
||||
* window: the current UTC hour and the four before it — spend booked in hour
|
||||
* H counts until H + 5 h). Spend is the users page's own booking
|
||||
* (`hourlyTokenRows` over the sessions a user OWNS through a workspace,
|
||||
* priced by `calculateCost`), never a second formula.
|
||||
* (`hourlyTokenRows` over the sessions a user OWNS through a workspace, each
|
||||
* hour counted for its payer — session-payers.js — priced by `calculateCost`),
|
||||
* never a second formula. A pane a collaborator opened in a workspace shared
|
||||
* with them is THEIR quota's: its start, its flag and the sweep go by payer.
|
||||
*
|
||||
* A user over their quota cannot chat on until it resets:
|
||||
* - `assertSpawnAllowed` refuses every new pane (`EQUOTA`, 429) — start,
|
||||
@@ -203,10 +205,9 @@ function statusAll({ now = Date.now(), userIds = null } = {}) {
|
||||
const { OWNED_SESSIONS } = require("../routes/users");
|
||||
const rules = require("../db").stmts.listPricing.all();
|
||||
const oldest = quotas.reduce((a, q) => (q.win.since < a ? q.win.since : a), quotas[0].win.since);
|
||||
const owner = new Map();
|
||||
for (const r of db().prepare(OWNED_SESSIONS).all()) {
|
||||
if (!owner.has(r.session_id)) owner.set(r.session_id, r.uid);
|
||||
}
|
||||
// Each hour's money is its payer's: the owner's, or a collaborator's who
|
||||
// ran the session then (session-payers.js).
|
||||
const payerOf = require("./session-payers").payerResolver();
|
||||
// A session that spent in the window was touched in it.
|
||||
const rows = hourlyTokenRows(
|
||||
`WHERE COALESCE(NULLIF(s.updated_at, ''), s.started_at) >= ? AND s.id IN (SELECT session_id FROM (${OWNED_SESSIONS}))`,
|
||||
@@ -214,7 +215,7 @@ function statusAll({ now = Date.now(), userIds = null } = {}) {
|
||||
);
|
||||
const byUser = new Map();
|
||||
for (const r of rows) {
|
||||
const uid = owner.get(r.session_id);
|
||||
const uid = payerOf(r);
|
||||
if (uid == null) continue;
|
||||
if (!byUser.has(uid)) byUser.set(uid, []);
|
||||
byUser.get(uid).push(r);
|
||||
@@ -275,7 +276,7 @@ function message(s, now = Date.now()) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Throws EQUOTA when the workspace owner is over their quota. No-op in local mode. */
|
||||
/** Throws EQUOTA when the payer (the workspace owner, or a collaborator) is over their quota. No-op in local mode. */
|
||||
function assertSpawnAllowed(ownerId) {
|
||||
if (!isServerMode() || ownerId == null) return;
|
||||
const s = statusFor(ownerId);
|
||||
@@ -288,14 +289,65 @@ const FLAG = "quota.json";
|
||||
const hostDir = () => path.join(require("./claude-home").getDataDir(), "user-quota");
|
||||
const hostFlag = (userId) => path.join(hostDir(), `u${userId}.json`);
|
||||
|
||||
/** A collaborator's flag in the workspace owner's handoff dir (sharing phase 2). */
|
||||
const collabFlag = (userId) => `quota-u${userId}.json`;
|
||||
|
||||
/**
|
||||
* The env a pane of `ownerId` gets: where its hooks look for the flag —
|
||||
* the member's handoff dir (S3: the pane runs as them) or the host's data dir.
|
||||
* The env a pane paid for by `payerId` gets: where its hooks look for the
|
||||
* flag — the pane account's handoff dir (S3: the pane runs as the workspace
|
||||
* owner's account; a collaborator's own file there) or the host's data dir.
|
||||
*/
|
||||
function flagEnv(ownerId, member) {
|
||||
if (!isServerMode() || ownerId == null) return {};
|
||||
const file = member ? path.join(require("./run-as").handoffDir(member), FLAG) : hostFlag(ownerId);
|
||||
return { AGENTHUB_QUOTA_FILE: file };
|
||||
function flagEnv(payerId, member, ownerId = payerId) {
|
||||
if (!isServerMode() || payerId == null) return {};
|
||||
if (!member) return { AGENTHUB_QUOTA_FILE: hostFlag(payerId) };
|
||||
const name = payerId === ownerId ? FLAG : collabFlag(payerId);
|
||||
return { AGENTHUB_QUOTA_FILE: path.join(require("./run-as").handoffDir(member), name) };
|
||||
}
|
||||
|
||||
function flagText(s, now) {
|
||||
const body = s?.exceeded
|
||||
? { blocked: true, until: s.resetsAt, message: message(s, now) }
|
||||
: { blocked: false };
|
||||
return `${JSON.stringify(body)}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write collaborator `userId`'s flag in pane account `member`'s handoff dir —
|
||||
* at spawn, so a file left from an earlier share never says the wrong thing.
|
||||
* (The host's per-user flag is the sweep's.) Best effort.
|
||||
*/
|
||||
function writeCollabFlag(userId, member, now = Date.now()) {
|
||||
if (!isServerMode() || !member) return;
|
||||
try {
|
||||
require("./run-as").handoffWrite(
|
||||
member,
|
||||
collabFlag(userId),
|
||||
flagText(statusFor(userId, { now }), now)
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn(`user quota: collaborator flag u${userId} not written:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The pane accounts of the workspaces shared with `userId` (not their own). */
|
||||
function sharedAccounts(userId) {
|
||||
const runAs = require("./run-as");
|
||||
const out = new Map();
|
||||
for (const { cwd } of db()
|
||||
.prepare(
|
||||
`SELECT l.cwd FROM lane_shares ls JOIN lanes l ON l.id = ls.lane_id WHERE ls.user_id = ?
|
||||
UNION SELECT l.cwd FROM session_shares ss JOIN sessions s ON s.id = ss.session_id
|
||||
JOIN lanes l ON l.id = s.lane_id WHERE ss.user_id = ?`
|
||||
)
|
||||
.all(userId, userId)) {
|
||||
try {
|
||||
const acct = runAs.accountForPath(cwd);
|
||||
if (acct) out.set(acct.name, acct);
|
||||
} catch {
|
||||
/* EMEMBERGONE: no pane runs there */
|
||||
}
|
||||
}
|
||||
return [...out.values()];
|
||||
}
|
||||
|
||||
function writeHostFlag(userId, text) {
|
||||
@@ -308,10 +360,7 @@ function writeHostFlag(userId, text) {
|
||||
|
||||
/** Write a user's flag everywhere their panes may read it. Best effort per place. */
|
||||
function writeFlags(user, s, now) {
|
||||
const body = s?.exceeded
|
||||
? { blocked: true, until: s.resetsAt, message: message(s, now) }
|
||||
: { blocked: false };
|
||||
const text = `${JSON.stringify(body)}\n`;
|
||||
const text = flagText(s, now);
|
||||
try {
|
||||
writeHostFlag(user.id, text);
|
||||
} catch (err) {
|
||||
@@ -323,11 +372,30 @@ function writeFlags(user, s, now) {
|
||||
} catch {
|
||||
acct = null;
|
||||
}
|
||||
if (!acct) return;
|
||||
if (acct) {
|
||||
try {
|
||||
require("./run-as").handoffWrite(acct, FLAG, text);
|
||||
} catch (err) {
|
||||
console.warn(`user quota: ${user.username}'s flag not written:`, err.message);
|
||||
}
|
||||
}
|
||||
// Their panes in workspaces shared with them run as the owner's account.
|
||||
let shared = [];
|
||||
try {
|
||||
require("./run-as").handoffWrite(acct, FLAG, text);
|
||||
} catch (err) {
|
||||
console.warn(`user quota: ${user.username}'s flag not written:`, err.message);
|
||||
shared = sharedAccounts(user.id);
|
||||
} catch {
|
||||
shared = [];
|
||||
}
|
||||
for (const other of shared) {
|
||||
if (acct && other.name === acct.name) continue;
|
||||
try {
|
||||
require("./run-as").handoffWrite(other, collabFlag(user.id), text);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`user quota: ${user.username}'s flag at ${other.name} not written:`,
|
||||
err.message
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,15 +406,25 @@ let blocked = new Set();
|
||||
/** user id → the flag text last written, so an unchanged state writes nothing. */
|
||||
const written = new Map();
|
||||
|
||||
function laneOwner(laneId) {
|
||||
/** Who pays for run `runId`: its starter when someone shared the workspace with them, else its owner. */
|
||||
function runPayer(runId) {
|
||||
const r = db()
|
||||
.prepare(
|
||||
`SELECT COALESCE(r.started_by, l.owner_id) AS uid
|
||||
FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id WHERE r.id = ?`
|
||||
)
|
||||
.get(runId);
|
||||
if (r) return r.uid ?? null;
|
||||
const laneId = require("./pty-run").laneIdFromRunId(runId);
|
||||
if (laneId == null) return null;
|
||||
return db().prepare("SELECT owner_id FROM lanes WHERE id = ?").get(laneId)?.owner_id ?? null;
|
||||
}
|
||||
|
||||
/** Is run `runId`'s workspace owner over quota (by the last sweep)? omp-share asks. */
|
||||
/** Is run `runId`'s payer over quota (by the last sweep)? omp-share asks. */
|
||||
function isRunBlocked(runId) {
|
||||
if (!blocked.size) return false;
|
||||
const laneId = require("./pty-run").laneIdFromRunId(runId);
|
||||
return laneId != null && blocked.has(laneOwner(laneId));
|
||||
const uid = runPayer(runId);
|
||||
return uid != null && blocked.has(uid);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -384,7 +462,7 @@ function endUnstoppable(userIds) {
|
||||
const runAs = require("./run-as");
|
||||
const ended = [];
|
||||
for (const run of runs.listRuns()) {
|
||||
if (run.status !== "running" || !userIds.has(laneOwner(run.laneId))) continue;
|
||||
if (run.status !== "running" || !userIds.has(runPayer(run.id))) continue;
|
||||
if (hookCanStop(run, runAs.accountForLane(run.laneId))) continue;
|
||||
try {
|
||||
if (runs.killRun(run.id)) ended.push(run.id);
|
||||
@@ -460,6 +538,7 @@ module.exports = {
|
||||
message,
|
||||
assertSpawnAllowed,
|
||||
flagEnv,
|
||||
writeCollabFlag,
|
||||
isRunBlocked,
|
||||
hookCanStop,
|
||||
sweep,
|
||||
|
||||
@@ -701,6 +701,97 @@ const paths = {
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/lanes/{id}/shares": {
|
||||
get: {
|
||||
tags: ["Lanes"],
|
||||
summary: "The users a workspace is shared with",
|
||||
description:
|
||||
"Server mode (local mode: `{shares: [], canManage: false}`). `{shares:[{id, username, name, sharedAt}], canManage}` — names only; `canManage` is whether this caller (the owner or an admin) may change the list. A user it is shared with may read it too.",
|
||||
operationId: "getLaneShares",
|
||||
parameters: [idParam],
|
||||
responses: { 200: { description: "`{shares, canManage}`.", ...json(obj) }, 404: notFound },
|
||||
},
|
||||
put: {
|
||||
tags: ["Lanes"],
|
||||
summary: "Set the users a workspace is shared with",
|
||||
description:
|
||||
"`{userIds:[…]}` is the WHOLE list (≤ 200 enabled users, never the owner). The owner or an admin only (`403 ENOTOWNER`); same-origin; each user added or taken off is written to the audit log. A user it is shared with sees it and works in it like its owner — under S3 as the owner's Linux account — except rename, reset, remove, delete and sharing (`ENOTOWNER`), and a session they start runs on their own account (else `409 ENOCOLLABACCOUNT`) and is billed to them. Users taken off get `lane_access` and lose access at once.",
|
||||
operationId: "setLaneShares",
|
||||
parameters: [idParam],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
required: ["userIds"],
|
||||
properties: { userIds: { type: "array", items: { type: "integer" } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: { description: "`{shares}`.", ...json(obj) },
|
||||
400: { description: "EBADUSER or ELOCALMODE." },
|
||||
403: { description: "ENOTOWNER." },
|
||||
404: notFound,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/lanes/{id}/presence": {
|
||||
get: {
|
||||
tags: ["Lanes"],
|
||||
summary: "Who has which of a workspace's panes open",
|
||||
description:
|
||||
"Server mode (local mode: `{panes: {}}`). `{panes: {<run id>: [{id, name}]}}` — the users with a terminal attached to each pane, from memory; changes arrive as the WebSocket message `pane_presence` `{laneId, runId, users}` (the workspace's owner and the users it is shared with).",
|
||||
operationId: "getLanePresence",
|
||||
parameters: [idParam],
|
||||
responses: { 200: { description: "`{panes}`.", ...json(obj) }, 404: notFound },
|
||||
},
|
||||
},
|
||||
"/api/lanes/{id}/sessions/{sid}/shares": {
|
||||
get: {
|
||||
tags: ["Lanes"],
|
||||
summary: "The users one session of a workspace is shared with",
|
||||
description:
|
||||
"Server mode (local mode: `{shares: [], canManage: false}`). `{shares:[{id, username, name, sharedAt}], canManage}` for session `sid` of this workspace (`404 ENOSESSION` otherwise).",
|
||||
operationId: "getSessionShares",
|
||||
parameters: [
|
||||
idParam,
|
||||
{ name: "sid", in: "path", required: true, schema: { type: "string" } },
|
||||
],
|
||||
responses: { 200: { description: "`{shares, canManage}`.", ...json(obj) }, 404: notFound },
|
||||
},
|
||||
put: {
|
||||
tags: ["Lanes"],
|
||||
summary: "Set the users one session of a workspace is shared with",
|
||||
description:
|
||||
"`{userIds:[…]}` is the WHOLE list (≤ 200 enabled users, never the workspace's owner). The owner or an admin only (`403 ENOTOWNER`); same-origin; audited as `share session <id>` / `unshare session <id>`. A user it is shared with sees that session and its workspace (`access: \"session\"` in the workspace list), joins the pane holding it, resumes it on their own account and uses the workspace's git — every other call on the workspace answers them `403 ESESSIONSHARE`.",
|
||||
operationId: "setSessionShares",
|
||||
parameters: [
|
||||
idParam,
|
||||
{ name: "sid", in: "path", required: true, schema: { type: "string" } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
required: ["userIds"],
|
||||
properties: { userIds: { type: "array", items: { type: "integer" } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: { description: "`{shares}`.", ...json(obj) },
|
||||
400: { description: "EBADUSER or ELOCALMODE." },
|
||||
403: { description: "ENOTOWNER." },
|
||||
404: notFound,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/lanes/{id}/memory": {
|
||||
get: {
|
||||
tags: ["Lanes"],
|
||||
|
||||
+213
-6
@@ -229,11 +229,23 @@ function broadcastLane(id) {
|
||||
router.get("/", (req, res) => {
|
||||
// Server mode: a member lists (and counts) only their own workspaces.
|
||||
const visible = scope.visibleLaneIds(req);
|
||||
const rows = lanesLib.listLanes().filter((l) => visible === null || visible.includes(l.id));
|
||||
// A collaborator's pane token: its own workspace only (auth.js paneLaneAllows).
|
||||
const paneLane = req.user?.paneLane ?? null;
|
||||
const rows = lanesLib
|
||||
.listLanes()
|
||||
.filter(
|
||||
(l) => (visible === null || visible.includes(l.id)) && (paneLane == null || l.id === paneLane)
|
||||
);
|
||||
// ONE list-sessions answers every lane's run, instead of a synchronous
|
||||
// has-session per lane (null when tmux could not be asked: per-lane then).
|
||||
const live = rows.some((l) => l.run_id) ? tmux.liveSessions() : null;
|
||||
const lanes = rows.map((l) => payload(l, live));
|
||||
// `access: "session"`: only sessions of it are shared with this user (phase 3).
|
||||
const lanes = rows.map((l) => {
|
||||
const p = payload(l, live);
|
||||
return visible !== null && scope.laneAccess(req, l.id) === "session"
|
||||
? { ...p, access: "session" }
|
||||
: p;
|
||||
});
|
||||
res.json({
|
||||
lanes,
|
||||
counts: {
|
||||
@@ -426,6 +438,13 @@ router.get("/branches", async (req, res) => {
|
||||
/** The lane fields a server-mode member may PATCH (the UI sends title and pipeline). */
|
||||
const MEMBER_PATCHABLE = new Set(["title", "pipeline", "notes", "links", "branch"]);
|
||||
|
||||
/** A shared workspace's owner-only action (rename, reset, remove, sharing). */
|
||||
function notOwner(res) {
|
||||
return res.status(403).json({
|
||||
error: { code: "ENOTOWNER", message: "only the workspace's owner (or an admin) may do this" },
|
||||
});
|
||||
}
|
||||
|
||||
/** Server mode: the folder is, holds or lies in another user's workspace. */
|
||||
function refuseOwned(res) {
|
||||
return res.status(409).json({
|
||||
@@ -1356,6 +1375,8 @@ router.patch("/:id", sameOriginGuard, (req, res) => {
|
||||
// that tie a workspace to a pane or a session (`run_id` pointed at another
|
||||
// user's pane would let stop/reset kill it).
|
||||
const body = req.body && typeof req.body === "object" ? req.body : {};
|
||||
// A workspace's name is its owner's: a user it is shared with renames nothing.
|
||||
if ("title" in body && !scope.isLaneOwner(req, req.params.id)) return notOwner(res);
|
||||
if (scope.memberId(req) != null) {
|
||||
const off = Object.keys(body).filter((k) => !MEMBER_PATCHABLE.has(k));
|
||||
if (off.length) {
|
||||
@@ -1386,6 +1407,168 @@ router.patch("/:id", sameOriginGuard, (req, res) => {
|
||||
res.json({ lane: payload(lane) });
|
||||
});
|
||||
|
||||
// ── Sharing a workspace with other users (server mode) ─────────────────────
|
||||
// docs/plans/workspace-sharing/: a user it is shared with sees it and works in
|
||||
// it like its owner — under S3 AS the owner's Linux account — except the
|
||||
// owner-only actions (`scope.isLaneOwner`). Names only, never a password.
|
||||
|
||||
const MAX_SHARES = 200;
|
||||
|
||||
/** The users a workspace (`lane_shares`) or one session (`session_shares`) is shared with. */
|
||||
function sharesOf(table, keyCol, key) {
|
||||
return require("../db")
|
||||
.db.prepare(
|
||||
`SELECT u.id, u.username, COALESCE(NULLIF(u.display_name, ''), u.username) AS name,
|
||||
s.shared_at AS sharedAt, u.disabled
|
||||
FROM ${table} s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.${keyCol} = ? ORDER BY name COLLATE NOCASE`
|
||||
)
|
||||
.all(key)
|
||||
.map((u) => ({ ...u, disabled: Boolean(u.disabled) }));
|
||||
}
|
||||
const laneShares = (laneId) => sharesOf("lane_shares", "lane_id", Number(laneId));
|
||||
const sessionShares = (sessionId) => sharesOf("session_shares", "session_id", String(sessionId));
|
||||
|
||||
/**
|
||||
* Replace the WHOLE share list of a workspace or a session with `req.body.userIds`:
|
||||
* server mode, the workspace's owner or an admin, enabled users only (one
|
||||
* already listed may stay though disabled since), never the owner; every
|
||||
* change audited as `<verb> <what> <id>`. Answers the new list, or sends the
|
||||
* error and answers null.
|
||||
*/
|
||||
function replaceShares(req, res, { lane, table, keyCol, key, what }) {
|
||||
const auth = require("../lib/auth");
|
||||
if (!auth.isServerMode()) {
|
||||
res.status(400).json({ error: { code: "ELOCALMODE", message: "sharing needs server mode" } });
|
||||
return null;
|
||||
}
|
||||
if (!scope.isLaneOwner(req, lane.id)) {
|
||||
notOwner(res);
|
||||
return null;
|
||||
}
|
||||
const raw = req.body?.userIds;
|
||||
if (
|
||||
!Array.isArray(raw) ||
|
||||
raw.length > MAX_SHARES ||
|
||||
!raw.every((x) => Number.isInteger(x) && x > 0)
|
||||
) {
|
||||
res
|
||||
.status(400)
|
||||
.json({ error: { code: "EBADUSER", message: "userIds must be a list of user ids" } });
|
||||
return null;
|
||||
}
|
||||
const { db } = require("../db");
|
||||
const wanted = [...new Set(raw)];
|
||||
const before = new Set(sharesOf(table, keyCol, key).map((u) => u.id));
|
||||
const user = db.prepare("SELECT id, disabled FROM users WHERE id = ?");
|
||||
for (const id of wanted) {
|
||||
const u = user.get(id);
|
||||
// A user already on the list may since have been disabled: keeping them
|
||||
// must not block every other change (it grants nothing while disabled).
|
||||
if (!u || (u.disabled && !before.has(id))) {
|
||||
res.status(400).json({ error: { code: "EBADUSER", message: `no enabled user ${id}` } });
|
||||
return null;
|
||||
}
|
||||
if (id === lane.owner_id) {
|
||||
res
|
||||
.status(400)
|
||||
.json({ error: { code: "EBADUSER", message: `a ${what} is not shared with its owner` } });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const added = wanted.filter((id) => !before.has(id));
|
||||
const removed = [...before].filter((id) => !wanted.includes(id));
|
||||
const actor = req.user?.id ?? null;
|
||||
db.transaction(() => {
|
||||
const del = db.prepare(`DELETE FROM ${table} WHERE ${keyCol} = ? AND user_id = ?`);
|
||||
const ins = db.prepare(
|
||||
`INSERT OR IGNORE INTO ${table} (${keyCol}, user_id, granted_by) VALUES (?, ?, ?)`
|
||||
);
|
||||
for (const id of removed) del.run(key, id);
|
||||
for (const id of added) ins.run(key, id, actor);
|
||||
})();
|
||||
const audit = require("../lib/audit");
|
||||
for (const id of added) audit.recordAccountChange(actor, id, "PUT", `share ${what} ${key}`);
|
||||
for (const id of removed) audit.recordAccountChange(actor, id, "PUT", `unshare ${what} ${key}`);
|
||||
// The owner and everyone it is shared with now re-read it; the users taken
|
||||
// off re-read their list, and their open terminals on it close at the next
|
||||
// attach re-check (websocket.js).
|
||||
broadcastLane(lane.id);
|
||||
if (removed.length) broadcast("lane_access", { laneId: lane.id, userIds: removed });
|
||||
return sharesOf(table, keyCol, key);
|
||||
}
|
||||
|
||||
router.get("/:id/shares", (req, res) => {
|
||||
const lane = lanesLib.getLane(req.params.id);
|
||||
if (!lane)
|
||||
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
|
||||
if (!require("../lib/auth").isServerMode()) return res.json({ shares: [], canManage: false });
|
||||
res.json({ shares: laneShares(lane.id), canManage: scope.isLaneOwner(req, lane.id) });
|
||||
});
|
||||
|
||||
/** `{userIds}` — the WHOLE list of users the workspace is shared with. */
|
||||
router.put("/:id/shares", sameOriginGuard, (req, res) => {
|
||||
const lane = lanesLib.getLane(req.params.id);
|
||||
if (!lane)
|
||||
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
|
||||
const shares = replaceShares(req, res, {
|
||||
lane,
|
||||
table: "lane_shares",
|
||||
keyCol: "lane_id",
|
||||
key: lane.id,
|
||||
what: "workspace",
|
||||
});
|
||||
if (shares) res.json({ shares });
|
||||
});
|
||||
|
||||
// Who has which of this workspace's panes open (pane-presence.js): server
|
||||
// mode's `{panes: {runId: [{id, name}]}}`; changes come as `pane_presence`.
|
||||
router.get("/:id/presence", (req, res) => {
|
||||
const lane = lanesLib.getLane(req.params.id);
|
||||
if (!lane)
|
||||
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
|
||||
if (!require("../lib/auth").isServerMode()) return res.json({ panes: {} });
|
||||
res.json({ panes: require("../lib/pane-presence").forLane(lane.id) });
|
||||
});
|
||||
|
||||
/** A session of this workspace (`sessions.lane_id`), or null after sending 404. */
|
||||
function laneSession(req, res, lane) {
|
||||
const row = require("../db")
|
||||
.db.prepare("SELECT id FROM sessions WHERE id = ? AND lane_id = ?")
|
||||
.get(String(req.params.sid), lane.id);
|
||||
if (!row) res.status(404).json({ error: { code: "ENOSESSION", message: "session not found" } });
|
||||
return row;
|
||||
}
|
||||
|
||||
// One session shared on its own (sharing phase 3): the users see that session
|
||||
// and its workspace's Changes, join its pane and resume it (on their own
|
||||
// account) — nothing else of the workspace (scope.js sessionShareAllows).
|
||||
router.get("/:id/sessions/:sid/shares", (req, res) => {
|
||||
const lane = lanesLib.getLane(req.params.id);
|
||||
if (!lane)
|
||||
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
|
||||
const row = laneSession(req, res, lane);
|
||||
if (!row) return;
|
||||
if (!require("../lib/auth").isServerMode()) return res.json({ shares: [], canManage: false });
|
||||
res.json({ shares: sessionShares(row.id), canManage: scope.isLaneOwner(req, lane.id) });
|
||||
});
|
||||
|
||||
router.put("/:id/sessions/:sid/shares", sameOriginGuard, (req, res) => {
|
||||
const lane = lanesLib.getLane(req.params.id);
|
||||
if (!lane)
|
||||
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
|
||||
const row = laneSession(req, res, lane);
|
||||
if (!row) return;
|
||||
const shares = replaceShares(req, res, {
|
||||
lane,
|
||||
table: "session_shares",
|
||||
keyCol: "session_id",
|
||||
key: row.id,
|
||||
what: "session",
|
||||
});
|
||||
if (shares) res.json({ shares });
|
||||
});
|
||||
|
||||
router.post("/:id/stage", sameOriginGuard, (req, res) => {
|
||||
const current = lanesLib.getLane(req.params.id);
|
||||
if (!current) {
|
||||
@@ -3240,6 +3423,11 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
if (!lane)
|
||||
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
|
||||
const body = req.body || {};
|
||||
// A workspace shared with this user: they may not destroy it. A session
|
||||
// they start or resume runs on their own account and is billed to them
|
||||
// (pty-run.js spawnRun `startedBy`, server/lib/session-payers.js).
|
||||
const startedBy = scope.isLaneOwner(req, lane.id) ? null : (req.user?.id ?? null);
|
||||
if (startedBy != null && DESTRUCTIVE_ACTIONS.has(action)) return notOwner(res);
|
||||
|
||||
if (DESTRUCTIVE_ACTIONS.has(action)) {
|
||||
if (body.confirm !== true) {
|
||||
@@ -3382,7 +3570,14 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
if (picked === null) return { allBusy: true };
|
||||
slot = picked;
|
||||
if (isLive(current.id, slot)) return { conflict: true };
|
||||
startedRunId = runs.spawnShell({ laneId: current.id, slot, cwd: current.cwd }).id;
|
||||
startedRunId = runs.spawnShell({
|
||||
laneId: current.id,
|
||||
slot,
|
||||
cwd: current.cwd,
|
||||
// A user it is shared with: their pane token acts as them
|
||||
// (the owner's or an admin's acts as the owner, as before).
|
||||
startedBy,
|
||||
}).id;
|
||||
return {};
|
||||
});
|
||||
if (shellOutcome.missing) {
|
||||
@@ -3447,7 +3642,7 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
const wantProxy =
|
||||
(body.proxy ?? body.router) !== undefined
|
||||
? (body.proxy ?? body.router)
|
||||
: resumeProxy(resumeId, lane.owner_id ?? null);
|
||||
: resumeProxy(resumeId, startedBy ?? lane.owner_id ?? null);
|
||||
if (wantProxy === require("../lib/ai-proxies").COMPANY_NAME) {
|
||||
try {
|
||||
await require("../lib/remote-client").ping();
|
||||
@@ -3506,7 +3701,7 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
? (body.proxy ?? body.router)
|
||||
: resumeProxy(
|
||||
body.resumeSessionId || (body.resume ? current.session_id : null),
|
||||
current.owner_id ?? null
|
||||
startedBy ?? current.owner_id ?? null
|
||||
),
|
||||
model: body.model,
|
||||
permissionMode: body.permissionMode,
|
||||
@@ -3517,6 +3712,7 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
bypass: body.bypass === true,
|
||||
resumeSessionId: body.resumeSessionId || (body.resume ? current.session_id : undefined),
|
||||
forkSession: body.forkSession === true,
|
||||
startedBy,
|
||||
});
|
||||
startedRunId = handle.id;
|
||||
// An extra pane's session is not the lane's run: `run_id` stays the
|
||||
@@ -3587,7 +3783,14 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
// ESESSIONLIMIT (S3): the member already runs the most AI sessions allowed.
|
||||
const status = /^(EBAD|EUNSUPPORTED$|ENOHUB$)/.test(err.code || "")
|
||||
? 400
|
||||
: ["ENOTSHARED", "EMEMBERGONE", "EOWNERFOLDER", "ECWDACCOUNT"].includes(err.code)
|
||||
: [
|
||||
"ENOTSHARED",
|
||||
"EMEMBERGONE",
|
||||
"EOWNERFOLDER",
|
||||
"ECWDACCOUNT",
|
||||
"ENOCOLLABACCOUNT",
|
||||
"ECOLLABRESUME",
|
||||
].includes(err.code)
|
||||
? 409
|
||||
: err.code === "EQUOTA" || err.code === "ESESSIONLIMIT"
|
||||
? 429
|
||||
@@ -3603,6 +3806,9 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
});
|
||||
|
||||
router.delete("/:id", sameOriginGuard, (req, res) => {
|
||||
if (lanesLib.getLane(req.params.id) && !scope.isLaneOwner(req, req.params.id)) {
|
||||
return notOwner(res);
|
||||
}
|
||||
const ok = lanesLib.deleteLane(req.params.id);
|
||||
if (!ok)
|
||||
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
|
||||
@@ -3613,4 +3819,5 @@ router.delete("/:id", sameOriginGuard, (req, res) => {
|
||||
module.exports = router;
|
||||
module.exports.broadcastLane = broadcastLane;
|
||||
module.exports.healAllRunIds = healAllRunIds;
|
||||
module.exports.notOwner = notOwner;
|
||||
module.exports.broadcastForeignLaneChanges = broadcastForeignLaneChanges;
|
||||
|
||||
@@ -579,11 +579,25 @@ function costScope(req, res) {
|
||||
// `mine=1`: the caller's own sessions even for an admin/analyst, who would
|
||||
// otherwise get every user's sum (the status bar's Today is a personal figure).
|
||||
const extra = [];
|
||||
let payer = null;
|
||||
if (req.query.mine === "1") {
|
||||
const own = require("../lib/scope").ownSessionWhere(req, "s.id", "s.lane_id");
|
||||
if (own.where !== "1") extra.push({ clause: own.where, params: own.params });
|
||||
if (own.where !== "1") {
|
||||
// Money is per payer: a session a collaborator ran (in either
|
||||
// direction) counts by the hours each paid (server/lib/session-payers.js).
|
||||
const { SPLIT } = require("../lib/session-payers");
|
||||
extra.push({ clause: `(${own.where}) AND s.id NOT IN (${SPLIT})`, params: own.params });
|
||||
payer = {
|
||||
uid: req.user.id,
|
||||
...costWhere({
|
||||
scope: parseScope(req),
|
||||
lane,
|
||||
extra: [{ clause: `s.id IN (${SPLIT})`, params: [] }],
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
return costWhere({ scope: parseScope(req), lane, extra });
|
||||
return { ...costWhere({ scope: parseScope(req), lane, extra }), payer };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -610,11 +624,22 @@ function costByTool(dailyTokens, rules) {
|
||||
* the spend pace keep their own windows. Also used by scheduled reports.
|
||||
*/
|
||||
function computeCost(
|
||||
{ whereClause = "", params = [] } = {},
|
||||
{ whereClause = "", params = [], payer = null } = {},
|
||||
range = null,
|
||||
tzModifier = "+0 minutes"
|
||||
) {
|
||||
const dailyTokens = dailyTokenRows(tzModifier, whereClause, params);
|
||||
// `payer` (`?mine=1` in server mode): plus the hours of split sessions this
|
||||
// user paid for, the scope itself having left those sessions out.
|
||||
const dailyTokens = dailyTokenRows(tzModifier, whereClause, params).concat(
|
||||
payer
|
||||
? require("../lib/session-payers").paidDailyRows(
|
||||
payer.uid,
|
||||
payer.whereClause,
|
||||
payer.params,
|
||||
tzModifier
|
||||
)
|
||||
: []
|
||||
);
|
||||
const inside = range ? dailyTokens.filter((r) => inRange(range, r.date)) : dailyTokens;
|
||||
const rules = stmts.listPricing.all();
|
||||
// Price the date-split rows so each day's usage bills at the rate effective on
|
||||
|
||||
+27
-5
@@ -89,7 +89,13 @@ router.get("/", (req, res) => {
|
||||
// Server mode: a member sees only the panes of their own workspaces.
|
||||
const visible = scope.visibleLaneIds(req);
|
||||
const items = runs.listRuns();
|
||||
res.json({ items: visible === null ? items : items.filter((r) => visible.includes(r.laneId)) });
|
||||
// A workspace one of whose sessions is shared with them: that session's pane only.
|
||||
res.json({
|
||||
items:
|
||||
visible === null
|
||||
? items
|
||||
: items.filter((r) => visible.includes(r.laneId) && scope.canSeeRun(req, r.id)),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -400,8 +406,11 @@ router.get("/history", (req, res) => {
|
||||
.sort((a, b) => String(b.started_at).localeCompare(String(a.started_at)))
|
||||
.slice(0, Math.max(1, Math.min(500, Math.floor(opts.limit) || 50)));
|
||||
const liveIds = new Set(runs.listRuns().map((h) => h.id));
|
||||
// A session shared on its own: only the runs that held it.
|
||||
const shown =
|
||||
scope.memberId(req) == null ? items : items.filter((it) => scope.canSeeRunRow(req, it.id));
|
||||
res.json({
|
||||
items: items.map((it) => ({ ...it, isLive: liveIds.has(it.id) })),
|
||||
items: shown.map((it) => ({ ...it, isLive: liveIds.has(it.id) })),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -618,6 +627,10 @@ router.post("/", async (req, res) => {
|
||||
if (!Number.isInteger(laneId)) {
|
||||
return res.status(400).json({ error: { code: "EBADLANE", message: "laneId is required" } });
|
||||
}
|
||||
// A workspace shared with this user: the session runs on their own account
|
||||
// and is billed to them (pty-run.js spawnRun `startedBy`).
|
||||
const startedBy =
|
||||
lanesLib.getLane(laneId) && !scope.isLaneOwner(req, laneId) ? (req.user?.id ?? null) : null;
|
||||
let cwd;
|
||||
try {
|
||||
// A member's run with no cwd starts in its workspace, not the server's folder.
|
||||
@@ -635,7 +648,7 @@ router.post("/", async (req, res) => {
|
||||
? (body.proxy ?? body.router)
|
||||
: resumeProxy(
|
||||
typeof body.resumeSessionId === "string" ? body.resumeSessionId : null,
|
||||
lanesLib.getLane(laneId)?.owner_id ?? null
|
||||
startedBy ?? lanesLib.getLane(laneId)?.owner_id ?? null
|
||||
);
|
||||
if (wantProxy === require("../lib/ai-proxies").COMPANY_NAME) {
|
||||
try {
|
||||
@@ -660,7 +673,7 @@ router.post("/", async (req, res) => {
|
||||
? (body.proxy ?? body.router)
|
||||
: resumeProxy(
|
||||
typeof body.resumeSessionId === "string" ? body.resumeSessionId : null,
|
||||
lane?.owner_id ?? null
|
||||
startedBy ?? lane?.owner_id ?? null
|
||||
),
|
||||
model: typeof body.model === "string" && body.model ? body.model : null,
|
||||
permissionMode:
|
||||
@@ -680,12 +693,21 @@ router.post("/", async (req, res) => {
|
||||
? body.resumeSessionId
|
||||
: null,
|
||||
initialPrompt: typeof body.initialPrompt === "string" ? body.initialPrompt : "",
|
||||
startedBy,
|
||||
});
|
||||
return res.status(201).json(handle);
|
||||
} catch (err) {
|
||||
// A busy pane is a conflict with live state, not a malformed request.
|
||||
if (
|
||||
["ERUNLIVE", "ENOTSHARED", "EMEMBERGONE", "EOWNERFOLDER", "ECWDACCOUNT"].includes(err.code)
|
||||
[
|
||||
"ERUNLIVE",
|
||||
"ENOTSHARED",
|
||||
"EMEMBERGONE",
|
||||
"EOWNERFOLDER",
|
||||
"ECWDACCOUNT",
|
||||
"ENOCOLLABACCOUNT",
|
||||
"ECOLLABRESUME",
|
||||
].includes(err.code)
|
||||
) {
|
||||
return res.status(409).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
|
||||
+13
-9
@@ -81,10 +81,9 @@ const OWNED_SESSIONS = `
|
||||
function usageSince(windows, rules) {
|
||||
const { calculateCost, hourlyTokenRows } = require("./pricing");
|
||||
const oldest = windows.reduce((a, b) => (b < a ? b : a));
|
||||
const owner = new Map();
|
||||
for (const r of db.prepare(OWNED_SESSIONS).all()) {
|
||||
if (!owner.has(r.session_id)) owner.set(r.session_id, r.uid);
|
||||
}
|
||||
// Each hour is its payer's: the owner's, or a collaborator's who ran the
|
||||
// session then (server/lib/session-payers.js).
|
||||
const payerOf = require("../lib/session-payers").payerResolver();
|
||||
// A session that spent in the window was touched in it (budgets.js does the same).
|
||||
const rows = hourlyTokenRows(
|
||||
`WHERE COALESCE(NULLIF(s.updated_at, ''), s.started_at) >= ? AND s.id IN (SELECT session_id FROM (${OWNED_SESSIONS}))`,
|
||||
@@ -93,7 +92,7 @@ function usageSince(windows, rules) {
|
||||
return windows.map((since) => {
|
||||
const byUser = new Map();
|
||||
for (const r of rows) {
|
||||
const uid = owner.get(r.session_id);
|
||||
const uid = payerOf(r);
|
||||
if (uid == null || r.date < since) continue;
|
||||
if (!byUser.has(uid)) byUser.set(uid, []);
|
||||
byUser.get(uid).push(r);
|
||||
@@ -362,6 +361,10 @@ router.get("/:id/details", async (req, res) => {
|
||||
const rules = stmts.listPricing.all();
|
||||
const uid = u.id;
|
||||
const owned = `SELECT session_id FROM (${OWNED_SESSIONS}) WHERE uid = ?`;
|
||||
// Spend is per payer: a session someone else ran (or this user ran in a
|
||||
// workspace shared with them) counts only for the hours each paid.
|
||||
const payers = require("../lib/session-payers").index();
|
||||
const paid = (r) => !payers.has(r.session_id) || payers.payer(r.session_id, r.date) === uid;
|
||||
const off = parseInt(req.query.tz_offset, 10);
|
||||
const offMin = Number.isFinite(off) && Math.abs(off) <= 840 ? off : 0;
|
||||
// A UTC hour (`YYYY-MM-DDTHH`) → the viewer's local date.
|
||||
@@ -370,9 +373,10 @@ router.get("/:id/details", async (req, res) => {
|
||||
|
||||
const since30 = hourAgo(30);
|
||||
const rows = hourlyTokenRows(
|
||||
`WHERE COALESCE(NULLIF(s.updated_at, ''), s.started_at) >= ? AND s.id IN (${owned})`,
|
||||
[since30, uid]
|
||||
).filter((r) => r.date >= since30);
|
||||
`WHERE COALESCE(NULLIF(s.updated_at, ''), s.started_at) >= ?
|
||||
AND (s.id IN (${owned}) OR s.id IN (SELECT session_id FROM session_payers WHERE user_id = ?))`,
|
||||
[since30, uid, uid]
|
||||
).filter((r) => r.date >= since30 && paid(r));
|
||||
const today = todayHour(offMin);
|
||||
const since7 = hourAgo(7);
|
||||
|
||||
@@ -408,7 +412,7 @@ router.get("/:id/details", async (req, res) => {
|
||||
r.model, r.account, r.proxy, r.session_id AS sessionId, r.started_at AS startedAt,
|
||||
r.status
|
||||
FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
|
||||
WHERE l.owner_id = ? AND r.status IN ('running', 'spawning')
|
||||
WHERE COALESCE(r.started_by, l.owner_id) = ? AND r.status IN ('running', 'spawning')
|
||||
ORDER BY r.started_at DESC`
|
||||
)
|
||||
.all(uid);
|
||||
|
||||
+35
-1
@@ -159,6 +159,33 @@ function initPtyWebSocket(server) {
|
||||
if (cookie !== undefined) {
|
||||
ws.cookie = cookie;
|
||||
ws.runId = runId;
|
||||
// A browser that vanished without a close (a sleeping laptop) answers
|
||||
// no ping: the beat below ends it, and its presence with it.
|
||||
ws.isAlive = true;
|
||||
ws.on("pong", () => {
|
||||
ws.isAlive = true;
|
||||
});
|
||||
}
|
||||
// Server mode: who has this pane open (pane-presence.js), and the first
|
||||
// keystroke of a collaborator-era attach written to the audit log.
|
||||
if (cookie !== undefined) {
|
||||
const presence = require("./lib/pane-presence");
|
||||
const user = userFromRequest({ headers: { cookie } });
|
||||
if (user) {
|
||||
presence.join(runId, user);
|
||||
ws.on("close", () => presence.leave(runId, user));
|
||||
let typed = false;
|
||||
ws.on("message", (data, isBinary) => {
|
||||
if (typed) return;
|
||||
const binary = typeof isBinary === "boolean" ? isBinary : false;
|
||||
const text = data.toString("utf8");
|
||||
if (!binary && text.startsWith('{"type"')) return; // a control frame
|
||||
// A mouse report, a focus change or the terminal answering tmux.
|
||||
if (!require("./lib/pty-attach").isTyping(text)) return;
|
||||
typed = true;
|
||||
presence.auditInput(runId, user);
|
||||
});
|
||||
}
|
||||
}
|
||||
try {
|
||||
attach(ws, runId, size || { cols: 80, rows: 24 });
|
||||
@@ -221,13 +248,20 @@ function initPtyWebSocket(server) {
|
||||
ptyWss.clients.forEach((ws) => {
|
||||
if (ws.cookie === undefined) return;
|
||||
const user = userFromRequest({ headers: { cookie: ws.cookie } });
|
||||
if (!user || !canSeeRun({ user, method: "POST" }, ws.runId)) {
|
||||
if (!user || !canSeeRun({ user, method: "POST" }, ws.runId) || ws.isAlive === false) {
|
||||
try {
|
||||
ws.close(1008, "log in again");
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
ws.terminate();
|
||||
return;
|
||||
}
|
||||
ws.isAlive = false;
|
||||
try {
|
||||
ws.ping();
|
||||
} catch {
|
||||
/* closing */
|
||||
}
|
||||
});
|
||||
}, PTY_RECHECK_MS);
|
||||
|
||||
Reference in New Issue
Block a user