Compare commits

...
2 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 bc9739509c Release v0.15.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
tbenandClaude Opus 5.5 4d6c330954 Have worker bots work in their own home on computers
A worker now works in /home/cb-<bot>/workspace/users/<user> (cwd, HOME
and ~), with its bot-wide folder at /home/cb-<bot>/workspace and, in a
workspace, the shared folder at /home/cb-<bot>/workspace/workspaces/<id>.
Only /home/cb-<bot>/workspace is kept: the agent makes it a link to the
bot's folder on the mounted workspace (bots/<bot>), and workspaces/<id>
in it a link to the workspace's shared folder, checking both on every
request and putting back one that's gone. Nothing on disk moves, so
existing work opens at the new paths.

Paths are checked on their real place (computerWorkspacePath), so the
real spelling still works, and shown to a worker its own way
(computerRunPath). Computer folder refs take either spelling. The
coordinator keeps working in the computer's workspace.

Computer image 1.3.0; the layout bump recreates every computer once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
19 changed files with 422 additions and 114 deletions
+1 -1
View File
@@ -141,7 +141,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
- **Settings per computer** (super admin, its settings page): resources, and its browser (`browser_settings`, `ComputerBrowserSettingsSchema`: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, lightweight (for small hosts: `--disable-gpu`, so the GPU process loads no Mesa and WebGL is off, reduced motion, no smooth scrolling or component downloads, Xvnc at `LightweightFrameRate` fps), extra Chrome and Playwright MCP flags), passed as env (`computerBrowserEnv`); saving either recreates the container. Chrome reads only one `--disable-features=`/`--enable-features=`, so `browserArgs` merges the agent's with the extra flags' (`mergeFeatureFlags`). Flags that would open DevTools or MCP around the token are refused (`ComputerBlockedBrowserArgs`/`ComputerBlockedMcpArgs`) and dropped again by the agent (`computer/agent/blocked-args.ts`; keep both alike). **Rebuild** (`api/admin/computers/rebuild-computer`) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
- **Folders:** a run works only in `bots/<bot>/users/<user>` (cwd, `HOME`), `bots/<bot>` and `workspaces/<workspace>` (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`), and Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
- **Installs:** workers install pip/npm packages into `~/.local` of their folder themselves; anything needing root goes through `request_install` (worker task runs the user follows) -> `install_requests` -> a coordinator task on that computer in the super admin's coordinator conversation (`createInstallRequest`, fenced `installRequestBlock`, `InstallRequestNote`, `answer_install_request`); when that job ends however it ends (`settleInstallRequest`, from the job helpers) the answer lands in the worker's session as a crew message (`from_install_request_id`, `isCrewMessage`) and wakes it. Stop also ends a worker's leftover processes on its computers (`endWorkerProcesses`).
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
+8 -2
View File
@@ -55,7 +55,13 @@ commands. Every worker bot works as its own account, `cb-<bot id>` (uid and
gid `100000 + id`, no sudo), made by the agent the first time the app acts
for it (`run_as`). Its folder `bots/<id>` is its own (`2770`), and a
workspace's folder `workspaces/<id>` (root's) belongs to the group `cw-<id>`
its bots join. `gem`, and so Chrome, can't open either: the app passes a
its bots join. A worker works through its home: `/home/cb-<id>/workspace`
is a link to `bots/<id>` (the only part of its home that's kept, since the
home itself lives in the container), its users' folders are `users/<user>`
in it, and in a workspace `workspaces/<workspace id>` in it is a link to
that workspace's folder. The agent checks both links on every request for
the worker and puts back one that's gone (whatever sits in its place is
moved aside). `gem`, and so Chrome, can't open either: the app passes a
worker's uploads, downloads and files saved by name through a folder of the
call's own, copied by the worker's account (`sudo -u`), and a worker can't
open `file:` URLs. Its env files live in its own home.
@@ -116,7 +122,7 @@ tag; the release workflow builds a tag once (a dispatch with
bun run build:computer # builds AppData.ComputerImage for this machine
docker run -d --name cobble-computer-dev --shm-size 2g \
--security-opt seccomp=unconfined --cap-add NET_ADMIN -p 8170:8080 \
ghcr.io/moduletrace/cobble-computer:1.2.0
ghcr.io/moduletrace/cobble-computer:1.3.0
```
A computer run by hand like that has no token, so anyone who reaches its port
+78 -9
View File
@@ -1,8 +1,9 @@
import { execFile } from "node:child_process";
import { chmod, chown, mkdir, stat } from "node:fs/promises";
import { chmod, chown, lstat, mkdir, readlink, rename, stat, symlink, unlink } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { AgentConfig } from "./config";
import commandArgv from "./command-argv";
import log from "./log";
import type { RunUser } from "./run-user-for";
@@ -20,19 +21,28 @@ let queue: Promise<unknown> = Promise.resolve();
* Makes a worker's account and, in a workspace, its group (idempotent,
* one at a time), and hands it its folders: its home (private), the bot's
* folder (its own) and the workspace's (its group's). Neither gem nor any
* other worker can read them; the coordinator, as gem, uses sudo.
* other worker can read them; the coordinator, as gem, uses sudo. Then,
* on every call, makes sure of the links the worker works through
* (`keepLinks`): only the bot's folder is kept, so a write through a link
* that's gone would land somewhere a recreate wipes.
*/
export default function ensureRunUser({ run_user }: { run_user: RunUser }) {
export default async function ensureRunUser({ run_user }: { run_user: RunUser }) {
const key = `${run_user.uid}:${run_user.workspace?.gid || 0}`;
if (ready.has(key)) return Promise.resolve();
if (!ready.has(key)) {
await serially(async () => {
if (ready.has(key)) return;
const next = queue.then(async () => {
if (ready.has(key)) return;
await setUp({ run_user });
ready.add(key);
});
}
await setUp({ run_user });
ready.add(key);
});
if (!(await linksInPlace({ run_user }))) await serially(() => keepLinks({ run_user }));
}
function serially(work: () => Promise<void>) {
const next = queue.then(work);
queue = next.catch(() => {});
@@ -71,6 +81,65 @@ async function setUp({ run_user }: { run_user: RunUser }) {
* bots share it through the group.
*/
if (workspace) await shareFolder({ dir: workspace.dir, uid: 0, gid: workspace.gid });
await keepLinks({ run_user });
}
/**
* Whether the worker's links lead where they should: `workspace` in its
* home to the bot's folder, and in a workspace, `workspaces/<id>` in the
* bot's folder to the workspace's shared one. Only reads.
*/
async function linksInPlace({ run_user }: { run_user: RunUser }) {
if (!(await isLinkTo({ link: run_user.kept_dir, target: run_user.bot_dir }))) return false;
return !run_user.workspace || isLinkTo({ link: run_user.workspace.link, target: run_user.workspace.dir });
}
async function isLinkTo({ link, target }: { link: string; target: string }) {
const info = await lstat(link).catch(() => null);
return !!info?.isSymbolicLink() && (await readlink(link).catch(() => "")) == target;
}
/**
* Puts the worker's links back where they're missing or lead elsewhere.
* Whatever else sits in a link's place is moved aside, never deleted.
* The home's link is made as root (the home is a real folder in root's
* /home, so nothing in its path is the worker's to swap); the shared
* folder's, inside the bot's folder (the worker's own), by the worker's
* account, so a link it left there can't send root anywhere.
*/
async function keepLinks({ run_user }: { run_user: RunUser }) {
const { kept_dir, bot_dir, workspace } = run_user;
if (!(await isLinkTo({ link: kept_dir, target: bot_dir }))) {
const info = await lstat(kept_dir).catch(() => null);
if (info?.isSymbolicLink()) await unlink(kept_dir);
else if (info) await rename(kept_dir, `${kept_dir}.before-${Date.now()}`);
await symlink(bot_dir, kept_dir);
}
if (workspace && !(await isLinkTo({ link: workspace.link, target: workspace.dir }))) {
const link = quoted({ text: workspace.link });
const target = quoted({ text: workspace.dir });
const argv = commandArgv({
command: [
`umask 007`,
`mkdir -p "$(dirname ${link})"`,
`if [ -L ${link} ]; then ln -sfn ${target} ${link}; elif [ -e ${link} ]; then mv ${link} ${link}.before-$(date +%s) && ln -s ${target} ${link}; else ln -s ${target} ${link}; fi`,
].join(" && "),
as: { uid: run_user.uid, gid: run_user.gid },
});
await run(argv.file, argv.args, { cwd: "/", timeout: 30_000 });
}
}
function quoted({ text }: { text: string }) {
return `'${text.replaceAll("'", `'\\''`)}'`;
}
/**
+2
View File
@@ -8,6 +8,7 @@ describe("runUserFor", () => {
uid: 100_007,
gid: 100_007,
home: "/home/cb-7",
kept_dir: "/home/cb-7/workspace",
bot_dir: "/home/gem/workspace/bots/7",
workspace: null,
});
@@ -18,6 +19,7 @@ describe("runUserFor", () => {
name: "cw-12",
gid: 10_000_012,
dir: "/home/gem/workspace/workspaces/12",
link: "/home/gem/workspace/bots/3/workspaces/12",
});
});
+16 -5
View File
@@ -9,21 +9,28 @@ export type RunUser = {
* Its home, in the container (the env files live there).
*/
home: string;
/**
* `workspace` in its home: a link to `bot_dir`, the only part of its
* home that's kept. The app names every worker path through it.
*/
kept_dir: string;
/**
* The bot's folder in the workspace, owned by the account.
*/
bot_dir: string;
/**
* The workspace the run is in: its shared folder belongs to this group,
* which the account joins.
* which the account joins, and `link` (`workspaces/<id>` in the bot's
* folder) leads to it.
*/
workspace: { name: string; gid: number; dir: string } | null;
workspace: { name: string; gid: number; dir: string; link: string } | null;
};
/**
* The account a worker bot's commands run as on this computer
* (`cb-<bot id>`, no sudo) and, in a workspace, the group its bots share
* (`cw-<id>`). Throws for an id that isn't a whole number in range.
* (`cw-<id>`). Keep alike the app's `computerWorkerAccount` and
* `computerRunDirs`. Throws for an id that isn't a whole number in range.
*/
export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown; workspace_id?: unknown }): RunUser {
const bot = runId({ value: bot_id });
@@ -38,18 +45,22 @@ export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown;
const id = AgentConfig.WorkerIdBase + bot;
const name = `cb-${bot}`;
const home = `/home/${name}`;
const bot_dir = path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot));
return {
name,
uid: id,
gid: id,
home: `/home/${name}`,
bot_dir: path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot)),
home,
kept_dir: path.posix.join(home, "workspace"),
bot_dir,
workspace: workspace
? {
name: `cw-${workspace}`,
gid: AgentConfig.WorkspaceGroupBase + workspace,
dir: path.posix.join(AgentConfig.WorkspaceDir, "workspaces", String(workspace)),
link: path.posix.join(bot_dir, "workspaces", String(workspace)),
}
: null,
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.14.2",
"version": "0.15.0",
"module": "index.ts",
"type": "module",
"private": true,
+6 -3
View File
@@ -110,7 +110,7 @@ export const AppData = {
* `computer/` (the release workflow builds that tag), and bump
* `ComputerWorkspaceLayout` too when existing computers must move to it.
*/
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.2.0",
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.3.0",
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
/**
* Only a computer's workspace (`ComputerWorkspaceDir` in its
@@ -174,9 +174,12 @@ export const AppData = {
* (`migrateComputerLayout`), keeping its workspace and browser profile.
* `cobble-computer` moved every computer off the AIO sandbox;
* `cobble-computer-accounts` gave worker bots their own accounts (the
* container gets `NET_ADMIN` to keep them off its services).
* container gets `NET_ADMIN` to keep them off its services);
* `cobble-computer-homes` has workers work in their own home
* (`/home/cb-<bot>/workspace`, a link the agent keeps to their folder),
* which an older agent would make a folder that isn't kept.
*/
ComputerWorkspaceLayout: "cobble-computer-accounts",
ComputerWorkspaceLayout: "cobble-computer-homes",
ComputerUserUid: 1000,
ComputerUserGid: 1000,
/**
+6 -3
View File
@@ -53,9 +53,10 @@ describe("harness prompts", () => {
dirs: computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 }),
});
expect(note).toContain("[folder:computer:8:bots/3/users/7/seo/coderank/raw]");
expect(note).toContain("/home/gem/workspace/bots/3/users/7");
expect(note).toContain("/home/gem/workspace/workspaces/2");
expect(note).toContain("[folder:computer:8:home/cb-3/workspace/users/7/seo/coderank/raw]");
expect(note).toContain("starts in /home/cb-3/workspace/users/7 (also ~ and $HOME)");
expect(note).toContain("/home/cb-3/workspace/workspaces/2: shared");
expect(note).toContain("only /home/cb-3/workspace and the browser's logins survive it (the rest of your account's home, /home/cb-3, doesn't)");
expect(note).toContain("request_install");
expect(note).not.toContain("sudo apt-get");
});
@@ -67,6 +68,8 @@ describe("harness prompts", () => {
});
expect(note).toContain("sudo apt-get");
expect(note).toContain("/home/gem/workspace/bots/1/users/7");
expect(note).toContain("only /home/gem/workspace and the browser's logins survive it. ");
expect(note).not.toContain("request_install");
});
+7 -4
View File
@@ -1,7 +1,8 @@
import { AppData } from "@/src/data/app-data";
import botRef from "@/src/utils/bot-ref";
import folderRef from "@/src/utils/folder-ref";
import { computerWorkspaceRelative, type ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import computerWorkerAccount from "@/src/utils/computer-worker-account";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
/**
* Prompts the helper harnesses send. The text model gets their output in
@@ -109,14 +110,16 @@ export const ComputerFilesNote = ({
can_import?: boolean;
}) => `# Files on the computer
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~), and a path outside your folders is refused.
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~ and $HOME), and a path outside your folders is refused.
- ${dirs.cwd}: this user's work. Everything for them goes here.
- ${dirs.bot_dir}: only what is the same for every user you work for (other users' folders in it are not yours).${
dirs.shared_dir ? `\n- ${dirs.shared_dir}: shared with every bot in this workspace.` : ""
}
- The browser downloads to its own folder: move what you download into your folder straight away.
- A computer can be restarted or rebuilt at any time, and only ${AppData.ComputerWorkspaceDir} and the browser's logins survive it. ${
- A computer can be restarted or rebuilt at any time, and only ${dirs.run_as ? dirs.bot_dir : AppData.ComputerWorkspaceDir} and the browser's logins survive it${
dirs.run_as ? ` (the rest of your account's home, ${computerWorkerAccount({ bot_id: dirs.run_as.bot_id }).home}, doesn't)` : ""
}. ${
dirs.run_as
? `You work as your own account, without sudo, and the browser can't open your folders' files (file: URLs): to look at a page you made, serve its folder on localhost (python3 -m http.server --bind 127.0.0.1, in the background) and open that. Python and Node packages you install yourself (pip install --user, npm install -g) go to ~/.local in this user's folder, so they stay. A system package (apt) needs the coordinator: in a task, ask with request_install, then end your run saying you're waiting for it; you're woken with the answer. System packages may be gone after a rebuild: check for one first (command -v) and ask again when it's missing.`
: `Programs you install (sudo apt-get install -y, pip, npm -g) may be gone afterwards: check for one first (command -v) and install it again when it's missing.`
@@ -124,7 +127,7 @@ You work only in your own folders on the computer, never elsewhere in it: every
What you make there (downloads, screenshots, a crawl, raw evidence, logs) is kept with the computer, not in your files, and it is not searchable.
- The user can open any of it: name a folder on the computer as a folder ref, its path from the computer's workspace (${AppData.ComputerWorkspaceDir}), e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${computerWorkspaceRelative({ absolute: dirs.cwd })}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
- The user can open any of it: name a folder on the computer as a folder ref with its full path as you see it, e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${dirs.cwd}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
${
can_import
? `- import_file copies a file or a folder off the computer into your own files, in one go, and the copy is searchable straight away. Import the finished work (the report, the spreadsheet, the final document), attach it when it is what they asked for, and name it with its [file:ID] ref.\n- The raw evidence can stay on the computer: import it only when the user needs it kept, or when the computer may be rebuilt.\n`
@@ -1,23 +1,40 @@
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
import shellQuote from "@/src/utils/shell-quote";
/**
* The shell that puts a command in the run's folder on the computer:
* creates its folders (the user's in the bot's, and the workspace's shared
* one), moves into the user's and makes it `HOME`, so `~` and every
* relative path land there. A worker (its own account, no sudo) also
* gets `umask 007`, so its files stay its workspace group's and nobody
* else's, and installs into that home that work without root
* (`pip install --user`, `npm install -g` into `~/.local`, on `PATH`).
* Ends with `; `, ready to prefix a command.
* creates the user's folder in the bot's, moves into it and makes it
* `HOME`, so `~` and every relative path land there. The coordinator also
* creates the workspace's shared folder. A worker's shared folder is a
* link in its own (`workspaces/<id>`, made by the computer's agent) to the
* real one; when it's gone the link is put back, never a folder made in
* its place, which would keep the workspace's work from its other bots. A
* worker (its own account, no sudo) also gets `umask 007`, so its files
* stay its workspace group's and nobody else's, and installs into that
* home that work without root (`pip install --user`, `npm install -g` into
* `~/.local`, on `PATH`). Ends with `; `, ready to prefix a command.
*/
export default function computerDirsShell({ dirs }: { dirs: ComputerRunDirs }) {
const cwd = shellQuote({ text: dirs.cwd });
const folders = [dirs.cwd, ...(dirs.shared_dir ? [dirs.shared_dir] : [])]
.map((dir) => shellQuote({ text: dir }))
.join(" ");
if (!dirs.run_as) return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd}; `;
if (!dirs.run_as) {
const folders = [dirs.cwd, ...(dirs.shared_dir ? [dirs.shared_dir] : [])]
.map((dir) => shellQuote({ text: dir }))
.join(" ");
return `umask 007 && mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd}; `;
}
const shared = dirs.shared_dir ? sharedLinkShell({ link: dirs.shared_dir }) : "";
return `umask 007 && ${shared}mkdir -p ${cwd} && cd ${cwd} && export HOME=${cwd} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
}
function sharedLinkShell({ link }: { link: string }) {
const quoted = shellQuote({ text: link });
const parent = shellQuote({ text: link.replace(/\/[^/]+$/, "") });
const target = shellQuote({ text: computerWorkspacePath({ absolute: link }) });
return `{ [ -e ${quoted} ] || [ -L ${quoted} ] || { mkdir -p ${parent} && ln -s ${target} ${quoted}; }; } && `;
}
+27 -16
View File
@@ -95,9 +95,8 @@ export default function importFileTool({
* Workspace-relative from here on, which is what a folder ref
* names.
*/
const source = computerWorkspaceRelative({
absolute: resolveComputerPath({ path: args.path, dirs }),
});
const shown = resolveComputerPath({ path: args.path, dirs });
const source = computerWorkspaceRelative({ absolute: shown });
if (!source) return `Give a file or folder inside your folder, e.g. "seo/coderank/raw".`;
@@ -110,13 +109,14 @@ export default function importFileTool({
const kind = await sourceKind({ computer: target, source, run_as: dirs.run_as, signal });
if (kind == "missing") {
return `Nothing at ${onComputer({ source })} on this computer. Check it with search_computers or the computer's own tools before importing.`;
return `Nothing at ${shown} on this computer. Check it with search_computers or the computer's own tools before importing.`;
}
if (kind == "folder") {
return importFolder({
computer: target,
source,
shown,
name: (args.name || source.split("/").pop() || "import").trim(),
scope: own,
bot_id,
@@ -130,6 +130,7 @@ export default function importFileTool({
return importOneFile({
computer: target,
source,
shown,
name: (args.name || source.split("/").pop() || "import").trim(),
scope: own,
bot_id,
@@ -146,7 +147,14 @@ export default function importFileTool({
type ImportTarget = {
computer: ComputerApi;
/**
* Relative to the computer's workspace, where it really is.
*/
source: string;
/**
* Its path as the run sees it, for what the bot is told.
*/
shown: string;
name: string;
scope: StorageScope;
bot_id: number | string;
@@ -180,7 +188,7 @@ async function importOneFile({
signal,
});
if (!download.ok) return importFailure({ reason: download.reason, size: download.size, path: target.source });
if (!download.ok) return importFailure({ reason: download.reason, size: download.size, shown: target.shown });
const previous = await grabBotFileRow({
scope: target.scope.scope,
@@ -206,11 +214,11 @@ async function importOneFile({
return [
previous?.id
? `You already had ${saved.path} (same ref, no second copy): its bytes are now this file, ${formatSize({ bytes: download.size })} byte for byte.`
: `Copied ${onComputer({ source: target.source })} into your files as ${saved.path} [file:${saved.id}], ${formatSize({ bytes: download.size })} byte for byte.`,
: `Copied ${target.shown} into your files as ${saved.path} [file:${saved.id}], ${formatSize({ bytes: download.size })} byte for byte.`,
`The original is still on the computer, in ${folderRef({
volume: "computer",
owner_id: target.computer_id,
path: sourceFolder({ path: target.source }),
path: sourceFolder({ path: target.shown }),
})}`,
"Name the copy with its [file:ID] ref when you tell the user about it.",
].join("\n");
@@ -239,22 +247,22 @@ async function importFolder({
return importFailure({
reason: archive.reason,
size: archive.size,
path: target.source,
shown: target.shown,
});
}
const saved = await unpackArchive({ archive: archive.bytes, folder: name.replace(/\/+$/, ""), scope, bot_id, user_id });
if (!saved.length) return `The folder ${onComputer({ source: target.source })} is empty, so nothing was imported.`;
if (!saved.length) return `The folder ${target.shown} is empty, so nothing was imported.`;
return [
`Copied ${saved.length} file(s) from ${onComputer({ source: target.source })} into your files under ${name}/:`,
`Copied ${saved.length} file(s) from ${target.shown} into your files under ${name}/:`,
...saved.slice(0, 20).map((file) => `- ${file.path} [file:${file.id}]`),
saved.length > 20 ? `(and ${saved.length - 20} more)` : "",
`The originals are still on the computer, in ${folderRef({
volume: "computer",
owner_id: computer_id,
path: target.source,
path: target.shown,
})}`,
"Name the copies that matter with their [file:ID] refs.",
]
@@ -306,23 +314,26 @@ async function sourceKind({
function importFailure({
reason,
size,
path: source,
shown,
}: {
reason: "missing" | "too_big" | "cut_short";
size: number;
path: string;
/**
* The path as the run sees it.
*/
shown: string;
}) {
const limit = formatSize({ bytes: AppData.BotFileImportMaxBytes });
if (reason == "missing") {
return `Nothing at ${onComputer({ source })} on this computer. Check it with search_computers or the computer's own tools before importing.`;
return `Nothing at ${shown} on this computer. Check it with search_computers or the computer's own tools before importing.`;
}
if (reason == "too_big") {
return `${onComputer({ source })} is ${formatSize({ bytes: size })}, over the ${limit} limit, so nothing was copied. Zip it on the computer first, or import the files that matter on their own.`;
return `${shown} is ${formatSize({ bytes: size })}, over the ${limit} limit, so nothing was copied. Zip it on the computer first, or import the files that matter on their own.`;
}
return `The copy of ${onComputer({ source })} came back with ${formatSize({ bytes: size })} of its bytes, so it was thrown away rather than saved. Try again; if it keeps happening, the file is changing while it is read.`;
return `The copy of ${shown} came back with ${formatSize({ bytes: size })} of its bytes, so it was thrown away rather than saved. Try again; if it keeps happening, the file is changing while it is read.`;
}
/**
@@ -12,16 +12,18 @@ const echoTool = (name: string): HarnessTool => ({
});
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
const cwd = "/home/gem/workspace/bots/3/users/7";
const cwd = "/home/cb-3/workspace/users/7";
const shared = "/home/cb-3/workspace/workspaces/2";
const signal = new AbortController().signal;
const call = async (name: string, args: Record<string, unknown>) =>
JSON.parse((await withComputerDirs({ tool: echoTool(name), dirs }).run({ args, signal })) as string);
describe("withComputerDirs", () => {
test("uploads resolve paths and refuse outside ones", async () => {
expect((await call("browser_file_upload", { paths: ["a.pdf", "/home/gem/workspace/workspaces/2/b.png"] })).paths).toEqual([
expect((await call("browser_file_upload", { paths: ["a.pdf", `${shared}/b.png`, "/home/gem/workspace/workspaces/2/c.png"] })).paths).toEqual([
`${cwd}/a.pdf`,
"/home/gem/workspace/workspaces/2/b.png",
`${shared}/b.png`,
`${shared}/c.png`,
]);
await expect(call("browser_file_upload", { paths: ["/home/gem/.bashrc"] })).rejects.toThrow();
await expect(call("browser_file_upload", { paths: ["../../../4/x"] })).rejects.toThrow();
@@ -50,9 +52,7 @@ describe("withComputerDirs", () => {
test("a file saved by name lands in the run's folders", async () => {
expect((await call("browser_take_screenshot", { filename: "shot.png" })).filename).toBe(`${cwd}/shot.png`);
expect((await call("browser_snapshot", { filename: "/home/gem/workspace/workspaces/2/page.md" })).filename).toBe(
"/home/gem/workspace/workspaces/2/page.md",
);
expect((await call("browser_snapshot", { filename: `${shared}/page.md` })).filename).toBe(`${shared}/page.md`);
await expect(call("browser_console_messages", { filename: "/home/gem/workspace/bots/4/log.txt" })).rejects.toThrow();
});
@@ -63,9 +63,15 @@ describe("withComputerDirs", () => {
});
describe("computerDirsShell", () => {
test("a worker's: its umask, the folders, moved in, installs into its home", () => {
test("a worker's: its umask, the shared link put back, its folder, moved in, installs into its home", () => {
expect(computerDirsShell({ dirs })).toBe(
`umask 007 && mkdir -p '${cwd}' '/home/gem/workspace/workspaces/2' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
`umask 007 && { [ -e '${shared}' ] || [ -L '${shared}' ] || { mkdir -p '/home/cb-3/workspace/workspaces' && ln -s '/home/gem/workspace/workspaces/2' '${shared}'; }; } && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
);
});
test("a worker outside a workspace: no shared link", () => {
expect(computerDirsShell({ dirs: computerRunDirs({ bot_id: 3, user_id: 7 }) })).toBe(
`umask 007 && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
);
});
+46 -17
View File
@@ -2,25 +2,30 @@ import { describe, expect, test } from "bun:test";
import computerRunDirs, { computerWorkspaceRelative, resolveComputerPath } from "./computer-work-dirs";
const W = "/home/gem/workspace";
const H = "/home/cb-3/workspace";
describe("computerRunDirs", () => {
test("a worker gets its own folder, the user's inside it", () => {
test("a worker works in its kept folder at home, the user's inside it", () => {
const dirs = computerRunDirs({ bot_id: 3, user_id: 7 });
expect(dirs.cwd).toBe(`${W}/bots/3/users/7`);
expect(dirs.roots).toEqual([`${W}/bots/3`]);
expect(dirs.cwd).toBe(`${H}/users/7`);
expect(dirs.bot_dir).toBe(H);
expect(dirs.roots).toEqual([H]);
expect(dirs.shared_dir).toBeNull();
});
test("in a workspace the shared folder joins", () => {
test("in a workspace the shared folder joins, inside its own", () => {
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
expect(dirs.roots).toEqual([`${W}/bots/3`, `${W}/workspaces/2`]);
expect(dirs.shared_dir).toBe(`${H}/workspaces/2`);
expect(dirs.roots).toEqual([H, `${H}/workspaces/2`]);
});
test("the coordinator reaches the whole workspace", () => {
const dirs = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1 });
test("the coordinator works in the computer's workspace and reaches all of it", () => {
const dirs = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1, workspace_id: 2 });
expect(dirs.cwd).toBe(`${W}/bots/1/users/1`);
expect(dirs.shared_dir).toBe(`${W}/workspaces/2`);
expect(dirs.roots).toEqual([W]);
});
@@ -35,27 +40,41 @@ describe("resolveComputerPath", () => {
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
test("relative paths and ~ land in the user's folder", () => {
expect(resolveComputerPath({ path: "seo/raw", dirs })).toBe(`${W}/bots/3/users/7/seo/raw`);
expect(resolveComputerPath({ path: "~/a.txt", dirs })).toBe(`${W}/bots/3/users/7/a.txt`);
expect(resolveComputerPath({ path: "~", dirs })).toBe(`${W}/bots/3/users/7`);
expect(resolveComputerPath({ path: "", dirs })).toBe(`${W}/bots/3/users/7`);
expect(resolveComputerPath({ path: "seo/raw", dirs })).toBe(`${H}/users/7/seo/raw`);
expect(resolveComputerPath({ path: "~/a.txt", dirs })).toBe(`${H}/users/7/a.txt`);
expect(resolveComputerPath({ path: "~", dirs })).toBe(`${H}/users/7`);
expect(resolveComputerPath({ path: "", dirs })).toBe(`${H}/users/7`);
});
test("absolute paths inside the roots pass", () => {
expect(resolveComputerPath({ path: `${W}/bots/3/notes.md`, dirs })).toBe(`${W}/bots/3/notes.md`);
expect(resolveComputerPath({ path: `${W}/workspaces/2/x/`, dirs })).toBe(`${W}/workspaces/2/x`);
expect(resolveComputerPath({ path: `${H}/notes.md`, dirs })).toBe(`${H}/notes.md`);
expect(resolveComputerPath({ path: `${H}/workspaces/2/x/`, dirs })).toBe(`${H}/workspaces/2/x`);
expect(resolveComputerPath({ path: "workspaces/2", dirs: computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 }) })).toBe(
`${H}/users/7/workspaces/2`,
);
});
test("the real paths they link to pass too, given back as the bot sees them", () => {
expect(resolveComputerPath({ path: `${W}/bots/3/users/7/a`, dirs })).toBe(`${H}/users/7/a`);
expect(resolveComputerPath({ path: `${W}/workspaces/2/x`, dirs })).toBe(`${H}/workspaces/2/x`);
});
test("anything outside is refused", () => {
for (const path of [
"/home/gem/x.txt",
"/home/cb-3/.cobble/env",
"/home/cb-3",
"/etc/passwd",
"../../../4/a",
"../8/secret",
"../../..",
`${W}/bots/4`,
"/home/cb-4/workspace",
`${H}/users/8/a`,
`${W}/bots/3/users/8/a`,
`${W}/bots/30`,
`${W}/workspaces/5`,
`${H}/workspaces/5`,
"~/../../../../x",
"a\0b",
]) {
@@ -63,19 +82,29 @@ describe("resolveComputerPath", () => {
}
});
test("the bot-wide folder and its users folder itself pass", () => {
expect(resolveComputerPath({ path: "..", dirs })).toBe(`${W}/bots/3/users`);
expect(resolveComputerPath({ path: "../..", dirs })).toBe(`${W}/bots/3`);
test("outside a workspace no workspace folder is the run's", () => {
const alone = computerRunDirs({ bot_id: 3, user_id: 7 });
expect(() => resolveComputerPath({ path: `${H}/workspaces/2`, dirs: alone })).toThrow();
});
test("the coordinator reaches any bot's folder", () => {
test("the bot-wide folder and its users folder itself pass", () => {
expect(resolveComputerPath({ path: "..", dirs })).toBe(`${H}/users`);
expect(resolveComputerPath({ path: "../..", dirs })).toBe(H);
});
test("the coordinator reaches any bot's folder, by either spelling", () => {
const coordinator = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1 });
expect(resolveComputerPath({ path: `${W}/bots/3/report.md`, dirs: coordinator })).toBe(`${W}/bots/3/report.md`);
expect(resolveComputerPath({ path: `${H}/report.md`, dirs: coordinator })).toBe(`${W}/bots/3/report.md`);
expect(() => resolveComputerPath({ path: "/home/gem/.config", dirs: coordinator })).toThrow();
expect(() => resolveComputerPath({ path: "/home/cb-3/.cobble", dirs: coordinator })).toThrow();
});
test("workspace-relative names", () => {
expect(computerWorkspaceRelative({ absolute: `${W}/bots/3/users/7/seo` })).toBe("bots/3/users/7/seo");
expect(computerWorkspaceRelative({ absolute: `${H}/users/7/seo` })).toBe("bots/3/users/7/seo");
expect(computerWorkspaceRelative({ absolute: `${H}/workspaces/2/x` })).toBe("workspaces/2/x");
});
});
+70 -29
View File
@@ -1,11 +1,17 @@
import path from "node:path";
import { AppData } from "@/src/data/app-data";
import AppError from "@/src/utils/app-error";
import computerWorkerAccount from "@/src/utils/computer-worker-account";
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
/**
* Where one run may work on a computer, every path absolute inside the
* computer's workspace (`AppData.ComputerWorkspaceDir`, the only directory
* mounted from the data volume).
* Where one run may work on a computer, every path absolute and as the run
* sees it. Only the computer's workspace (`AppData.ComputerWorkspaceDir`)
* is mounted from the data volume. A worker sees its folders through its
* own home: `/home/cb-<bot>/workspace` is a link to `bots/<bot>` in the
* workspace, and `workspaces/<id>` in it a link to the workspace's shared
* folder (`computerWorkspacePath` turns either spelling into the real
* one). The coordinator works in the workspace itself.
*/
export type ComputerRunDirs = {
/**
@@ -13,16 +19,18 @@ export type ComputerRunDirs = {
*/
workspace: string;
/**
* Where the run starts and where a relative path lands: the user's
* folder in the bot's (`bots/<bot>/users/<user>`).
* Where the run starts, its `HOME`, and where a relative path lands:
* the user's folder in the bot's (`users/<user>`).
*/
cwd: string;
/**
* The bot's own folder (`bots/<bot>`).
* The bot's own folder: a worker's `/home/cb-<bot>/workspace`, the
* coordinator's `bots/<bot>` in the workspace.
*/
bot_dir: string;
/**
* The workspace's shared folder (`workspaces/<id>`), in a workspace.
* The workspace's shared folder, in a workspace: a worker's
* `workspaces/<id>` inside its own, the coordinator's in the workspace.
*/
shared_dir: string | null;
/**
@@ -62,9 +70,11 @@ type Params = {
/**
* The folders a run works in on a computer: the user's own inside the
* bot's (`bots/<bot>/users/<user>`, where it starts), the bot's own
* (`bots/<bot>`, for work that is the same for every user) and, in a
* workspace, the folder its bots share (`workspaces/<id>`).
* bot's (`users/<user>`, where it starts), the bot's own (for work that is
* the same for every user) and, in a workspace, the folder its bots share.
* A worker's are under `/home/cb-<bot>/workspace` (its account's home
* stays in the container, only that folder is kept); the coordinator's
* are in the computer's workspace (`bots/<bot>`, `workspaces/<id>`).
*/
export default function computerRunDirs({
bot_id,
@@ -73,10 +83,14 @@ export default function computerRunDirs({
workspace_id,
}: Params): ComputerRunDirs {
const workspace = AppData.ComputerWorkspaceDir;
const bot_dir = path.posix.join(workspace, "bots", String(Number(bot_id)));
const is_coordinator = bot_kind == "coordinator";
const in_workspace = Number(workspace_id) > 0;
const bot_dir = is_coordinator
? path.posix.join(workspace, "bots", String(Number(bot_id)))
: computerWorkerAccount({ bot_id }).workspace;
const cwd = path.posix.join(bot_dir, "users", String(Number(user_id)));
const shared_dir = Number(workspace_id) > 0
? path.posix.join(workspace, "workspaces", String(Number(workspace_id)))
const shared_dir = in_workspace
? path.posix.join(is_coordinator ? workspace : bot_dir, "workspaces", String(Number(workspace_id)))
: null;
return {
@@ -84,13 +98,11 @@ export default function computerRunDirs({
cwd,
bot_dir,
shared_dir,
roots: bot_kind == "coordinator"
? [workspace]
: [bot_dir, ...(shared_dir ? [shared_dir] : [])],
roots: is_coordinator ? [workspace] : [bot_dir, ...(shared_dir ? [shared_dir] : [])],
user_id: Number(user_id),
run_as: bot_kind == "coordinator"
run_as: is_coordinator
? null
: { bot_id: Number(bot_id), workspace_id: Number(workspace_id) > 0 ? Number(workspace_id) : null },
: { bot_id: Number(bot_id), workspace_id: in_workspace ? Number(workspace_id) : null },
};
}
@@ -105,8 +117,11 @@ export function isInsideDir({ parent, child }: { parent: string; child: string }
* Turns a path a bot gave a computer tool into the absolute one it means,
* only when it is one of the run's: a relative path (or `~`, which the
* run's shells read as its folder) lands in `cwd`, an absolute one must be
* inside `roots`, and another user's folder in a bot's is refused. Throws
* an `AppError` the bot gets back as the tool's error.
* inside `roots`, and another user's folder in a bot's is refused. Checked
* on the real path (`computerWorkspacePath`), so a worker may also give
* one under the computer's workspace (what `pwd -P` or a script's own cwd
* prints), and returned as the run sees it (`computerRunPath`). Throws an
* `AppError` the bot gets back as the tool's error.
*/
export function resolveComputerPath({
path: requested,
@@ -130,22 +145,47 @@ export function resolveComputerPath({
: path.posix.join(dirs.cwd, raw || "."),
).replace(/(.)\/+$/, "$1");
if (!isComputerPathAllowed({ absolute, dirs })) {
const real = computerWorkspacePath({ absolute });
if (!isComputerPathAllowed({ real, dirs })) {
throw new AppError(
`${absolute} is outside your folders on this computer. Work in ${dirs.cwd} (this user's), ${dirs.roots.join(" or ")} for work every user shares.`,
);
}
return absolute;
return computerRunPath({ real, dirs });
}
/**
* Whether an absolute, normalized path is one the run may touch.
* A real path on the computer (`computerWorkspacePath`) as the run sees
* it: for a worker, its folder and the workspace's shared one through its
* own home (`/home/cb-<bot>/workspace/...`).
*/
function isComputerPathAllowed({ absolute, dirs }: { absolute: string; dirs: ComputerRunDirs }) {
if (!dirs.roots.some((root) => isInsideDir({ parent: root, child: absolute }))) return false;
export function computerRunPath({ real, dirs }: { real: string; dirs: ComputerRunDirs }) {
if (!dirs.run_as) return real;
const relative = path.posix.relative(dirs.workspace, absolute).split("/");
for (const dir of [dirs.shared_dir, dirs.bot_dir]) {
if (!dir) continue;
const dir_real = computerWorkspacePath({ absolute: dir });
if (isInsideDir({ parent: dir_real, child: real })) {
return `${dir}${real.slice(dir_real.length)}`;
}
}
return real;
}
/**
* Whether a real, normalized path is one the run may touch.
*/
function isComputerPathAllowed({ real, dirs }: { real: string; dirs: ComputerRunDirs }) {
const roots = dirs.roots.map((root) => computerWorkspacePath({ absolute: root }));
if (!roots.some((root) => isInsideDir({ parent: root, child: real }))) return false;
const relative = path.posix.relative(dirs.workspace, real).split("/");
/**
* `bots/<bot>/users/<user>/...`: only the run's own user.
@@ -158,9 +198,10 @@ function isComputerPathAllowed({ absolute, dirs }: { absolute: string; dirs: Com
}
/**
* A path inside the computer's workspace as a folder ref or the files
* browser names it: relative to the workspace root, no leading slash.
* A path inside the computer's workspace as the files browser names it:
* relative to the workspace root, no leading slash. A worker's
* `/home/cb-<bot>/workspace/...` is read as the real path it links to.
*/
export function computerWorkspaceRelative({ absolute }: { absolute: string }) {
return path.posix.relative(AppData.ComputerWorkspaceDir, absolute);
return path.posix.relative(AppData.ComputerWorkspaceDir, computerWorkspacePath({ absolute }));
}
+5 -2
View File
@@ -1,10 +1,13 @@
/**
* A worker bot's own account on a computer, as the computer's agent makes
* it (`computer/agent/run-user-for.ts`; keep both alike): `cb-<bot id>`,
* without sudo, its home inside the container (the env files live there).
* without sudo. Its home stays inside the container (the env files live
* there); only `workspace` in it is kept, a link the agent makes to the
* bot's folder on the computer's mounted workspace (`bots/<bot id>`).
*/
export default function computerWorkerAccount({ bot_id }: { bot_id: number | string }) {
const name = `cb-${Number(bot_id)}`;
const home = `/home/${name}`;
return { name, home: `/home/${name}` };
return { name, home, workspace: `${home}/workspace` };
}
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test";
import computerWorkspacePath from "./computer-workspace-path";
const W = "/home/gem/workspace";
describe("computerWorkspacePath", () => {
test("a worker's kept folder is the bot's folder in the workspace", () => {
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace" })).toBe(`${W}/bots/3`);
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/users/7/a/" })).toBe(`${W}/bots/3/users/7/a`);
});
test("a workspace folder inside it is the shared one", () => {
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/workspaces/2/x" })).toBe(`${W}/workspaces/2/x`);
expect(computerWorkspacePath({ absolute: `${W}/bots/3/workspaces/2` })).toBe(`${W}/workspaces/2`);
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/workspaces" })).toBe(`${W}/bots/3/workspaces`);
});
test("the rest of a worker's home and other paths stay as they are", () => {
expect(computerWorkspacePath({ absolute: "/home/cb-3/.cobble/env" })).toBe("/home/cb-3/.cobble/env");
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace2" })).toBe("/home/cb-3/workspace2");
expect(computerWorkspacePath({ absolute: `${W}/bots/3/users/7` })).toBe(`${W}/bots/3/users/7`);
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/../../gem/x" })).toBe("/home/gem/x");
});
});
+42
View File
@@ -0,0 +1,42 @@
import { AppData } from "@/src/data/app-data";
/**
* The real place of an absolute path on a computer, inside its mounted
* workspace (`AppData.ComputerWorkspaceDir`). A worker sees its folders
* through its home: `/home/cb-<bot>/workspace` is a link to `bots/<bot>`,
* and `workspaces/<id>` inside that a link to the workspace's shared
* `workspaces/<id>`, so both spellings (and the shared folder reached
* through the bot's link) come out as the one real path. Anything else is
* returned normalized, as it is.
*/
export default function computerWorkspacePath({ absolute }: { absolute: string }) {
const workspace = AppData.ComputerWorkspaceDir;
const normal = normalizeAbsolute({ absolute });
const home = normal.match(/^\/home\/cb-(\d+)\/workspace(\/.*)?$/);
const real = home ? `${workspace}/bots/${Number(home[1])}${home[2] || ""}` : normal;
const shared = real.match(new RegExp(`^${escapeRegExp(workspace)}/bots/\\d+/workspaces/(\\d+)(/.*)?$`));
return shared ? `${workspace}/workspaces/${Number(shared[1])}${shared[2] || ""}` : real;
}
/**
* `path.posix.normalize` for an absolute path, without `node:path` (folder
* refs read this in the browser): `.` and `..` resolved, slashes merged,
* no trailing one.
*/
function normalizeAbsolute({ absolute }: { absolute: string }) {
const segments: string[] = [];
for (const segment of absolute.split("/")) {
if (!segment || segment == ".") continue;
if (segment == "..") segments.pop();
else segments.push(segment);
}
return `/${segments.join("/")}`;
}
function escapeRegExp(text: string) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
+19
View File
@@ -105,3 +105,22 @@ describe("linkComputerRefs", () => {
expect(parseFolderRefHref({ href: linked.match(/\((#file-[^)]+)\)/)?.[1] })).toBeNull();
});
});
describe("computer folder refs written as the bot sees them", () => {
test("a worker's kept folder and the computer's workspace open their real place", () => {
const open = (path: string) => parseFolderRefHref({ href: folderRefHref({ volume: "computer", owner_id: 3, path }) })?.path;
expect(open("/home/cb-7/workspace/users/1/seo")).toBe("bots/7/users/1/seo");
expect(open("home/cb-7/workspace/workspaces/2/brief")).toBe("workspaces/2/brief");
expect(open("/home/gem/workspace/bots/7/notes")).toBe("bots/7/notes");
expect(open("/home/gem/workspace")).toBe("");
expect(open("bots/7/users/1")).toBe("bots/7/users/1");
expect(open("seo/raw")).toBe("seo/raw");
});
test("other volumes keep the path as written", () => {
expect(parseFolderRefHref({ href: folderRefHref({ volume: "bot", owner_id: 3, path: "home/cb-7/workspace" }) })?.path).toBe(
"home/cb-7/workspace",
);
});
});
+21 -2
View File
@@ -9,6 +9,8 @@
* (`fileRef`), which is what downloads. There is no guessing from the
* name's extension: the ref says which one it is.
*/
import { AppData } from "@/src/data/app-data";
import computerWorkspacePath from "./computer-workspace-path";
import {
isStorageVolume,
parseStorageSpec,
@@ -38,6 +40,23 @@ function cleanPath({ path }: { path?: string | null }) {
return (path || "").trim().replace(/^\/+|\/+$/g, "");
}
/**
* A path in a folder ref, as the files browser names it. On a computer a
* bot may write the folder as it sees it there (`/home/cb-3/workspace/...`,
* `/home/gem/workspace/...`): that becomes its real place in the
* computer's workspace (`computerWorkspacePath`), relative to it.
*/
function refPath({ volume, path }: { volume: string; path: string }) {
if (volume != "computers") return path;
const workspace = AppData.ComputerWorkspaceDir;
const real = computerWorkspacePath({ absolute: `/${path}` });
if (real == workspace) return "";
return real.startsWith(`${workspace}/`) ? real.slice(workspace.length + 1) : path;
}
/**
* How a bot names a folder in a message. The path is written as it is; the
* chat encodes it into the link.
@@ -91,7 +110,7 @@ export function parseFolderRefHref({
return {
spec: { volume, owner_id: Math.trunc(owner_id) },
path: rest.join(":").replace(/^\/+|\/+$/g, ""),
path: refPath({ volume, path: rest.join(":").replace(/^\/+|\/+$/g, "") }),
};
}
@@ -114,5 +133,5 @@ export function folderRefUrl({ volume, owner_id, path }: RefParams) {
if (!spec) return StorageBrowserPath;
return storageSpecHref({ spec, path });
return storageSpecHref({ spec, path: refPath({ volume: known, path: cleanPath({ path }) }) });
}