Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team files: one shared folder for the team and its bots (#6346)
Milind Soni8c3269b0d1da
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 26f2b5db5b..010e16c936 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -546,6 +546,29 @@ On a My Cloud and on a desktop there is one person: every audience is the team'severy browser keeps its old name and Chrome its old launcher, every engine keeps the server's HOME, and nothing herechanges what those do.+## Team files++One shared folder per Team Cloud, `team-files/` in its data folder, for everyone on the team and every bot (details in+[team-files.md](team-files.md); `server/host/team-files.ts`, `server/host/team-files-host.ts`,+`server/routes/team-files.ts`). Its audience is `team`: every turn reads it, from a private chat too. People use it from+**Team files** in the Tools menu: upload (100 MB a file, 5 GB in all), folders, download, rename, delete (an admin+anything, a member what they uploaded) and a preview of text and pictures.++- **In the bot box** it is at `/team-files` in every turn's box (`BoxAudience.teamFiles`), read-only, and each turn's+ prompt says where and whether it may write. A bot an admin marked **Can edit team files** (`teamFilesEdit`, a bot+ setting only an admin changes) has it read-write in every chat, members' private chats included: a record written+ from Mira's private chat with Payroll lands in the team's folder, and its line says *"Changed by Mira with Payroll"*.+ This is the one place a private chat writes into the team's audience, by an admin's choice; the conversation itself+ never goes there. The audience rule otherwise holds: the bot's own folder stays read-only in that chat (above).+- **The template library** (`templates/`, `server/team-templates.ts`) is one folder of it: everyone reads it, only an+ admin changes it from the page, and it is read-only in every box. It counts toward the 5 GB.+- **Who changed what** is kept in `team-files-activity.json`: the page's changes as they happen, a bot's after each turn+ that could write (the folder's sizes and times compared before and after), with the person the turn worked for (whoever+ asked, else the person whose private chat it is).+- **Backups and exports** carry `team-files/` and its activity, as the team's; a link a bot left in the folder is skipped,+ never followed. **A member who leaves** takes nothing of it: what they uploaded or had a bot write stays the team's.+- **Off a Team Cloud** there is no folder, no menu entry, no prompt line, and the routes answer 404.+## RoutinesA routine lives where it was made or where it reports (`server/routine-home.ts`). One for a member's own MausBot, or that@@ -1065,6 +1088,10 @@ opens the team's page on the Cloud site (`/cloud/team/<id>`), not a chat. Nothin- **Someone invited who never opened the team.** The machine first learns of a member at their first pairing, so untilthen they are in no People list, and nothing says they joined (`team.people`): the Admin sends no roster and no"joined" of its own.+- **Team files without a box, and the cap for bots.** Without the bot box nothing keeps Team files read-only for a bot:+ any bot's shell can write it, and its changes are still recorded. The 5 GB cap holds for the page at every upload, but+ for a bot only when its turn starts (the folder is then read-only for every bot until someone removes files), so one+ turn can write past it.- **The team's folder without a box, and outside a conversation.** Without the bot box a shell in any chat writes thebot's own folder and reads every conversation folder, as it reads engine homes (next). A bot's MCP server the serverstarts outside any conversation (a configured server's probe or its app connections) keeps the bot's own folderdiff --git a/docs/team-files.md b/docs/team-files.mdnew file mode 100644index 0000000000..dae1abf7bb--- /dev/null+++ b/docs/team-files.md@@ -0,0 +1,59 @@+# Team files++One shared folder per Team Cloud, for every teammate and every bot: payroll records, client lists, templates, brand+assets. It is the team's (audience `team`, [team-cloud.md](team-cloud.md#team-files)): everyone on the team reads it,+whichever chat they are in.++## For people++**Team files** in the Tools menu (and the sidebar's tools) opens it, only on a Team Cloud. The page lists one folder at+a time with breadcrumbs back up, and for each file its size and its last change: *"Uploaded by Ben · 5 min ago"*,+*"Changed by Mira with Payroll · 2 hr ago"* (Payroll changed it in a turn Mira asked for). Under the title it shows the+space used of 5 GB.++- **Upload** with the button or by dropping files on the list: at most 100 MB a file, 5 GB in all. An upload that does not+ fit is refused and says why; a file with the same name is replaced only by whoever uploaded it, or an admin.+- **New folder**, **Download**, **Rename** and **Delete**. An Owner or Admin renames and deletes anything; a member what+ they uploaded (and a folder of theirs only when everything in it is theirs too).+- **`templates/`** is the team's template library (`server/team-templates.ts`, added from Share): everyone sees it,+ only an Owner or Admin uploads, renames or deletes anything in it there.+- **Preview** of text, Markdown, CSV and JSON (up to 1 MB) and of PNG, JPEG, GIF and WebP pictures; anything else downloads.++The desktop app and the browser show the same page. The routes (`/api/team-files/*`, below) are a member's, so the phone app+may list and download from them; it has no page of its own.++## For bots++Every turn of every bot on a Team Cloud has the folder at **`/team-files`** in its bot box, read-only, and its system+prompt says so in one line (*"Team files, the folder everyone at Acme shares: /team-files. It is read-only for you."*).+An admin turns on **Can edit team files** in the bot's settings (Access) to let it add and change files there from any+chat, members' private chats included: that is how a record from a private chat lands where the team keeps it. Nothing of+a conversation goes there by itself; the bot writes only what it is asked to.++`/team-files/templates`, the template library, is read-only in every box, for a bot that may edit too: the library is+its admins', and every import reads a template again through the package gate. When the folder is full the box has it+read-only for every bot, and the line says so. A process an engine keeps between+turns (Claude Code's, an ACP engine's) is started again when a bot's access changes, so turning the switch off takes effect+at its next turn.++## Who changed what++`team-files-activity.json` beside the folder records each change with its time, path, action, the person and the bot:+uploads, new folders, renames and deletes from the page as they happen, and a bot's writes after each turn that could+write (a bot that may edit, or any bot where no box keeps the folder read-only), found by comparing each file's size and+time before and after. A folder of more than 20,000 entries is not compared, so its changes go unrecorded. A change the+page or another turn made meanwhile is never put on the turn.++## Routes++| Route | What |+|---|---|+| `GET /api/team-files?path=<folder>` | the folder's entries with their last change, the space used and the caps |+| `GET /api/team-files/file?path=<file>` | the file; `&download=1` as an attachment |+| `PUT /api/team-files/file?path=<folder>&name=<name>` | an upload, the body as is |+| `POST /api/team-files/folder` `{path}` | a new folder |+| `POST /api/team-files/rename` `{from, to}` | |+| `POST /api/team-files/delete` `{path}` | |++Off a Team Cloud they answer 404. Every path is relative to the folder, with no `..` part, and nothing in the folder is+reached through a link (a bot could leave one there).diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex d8c48a56a9..f041a84e53 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -332,7 +332,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {/** Whether this bot may use the X research tools (x_search and its* actions), which spend the workspace's treg balance.* Absent/false = off: the person turns it on per bot. */- xResearch?: boolean;+ xResearch?: boolean; /** Team Cloud: an admin let it change the team's shared files from any chat. Absent: it reads them only. */ teamFilesEdit?: boolean;/** Whether this bot uses native memory. Absent/true = enabled. */memoryEnabled?: boolean;/** Built-in tool groups turned off for this bot (shared/tool-groups.ts). Absent or empty: all on. */diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 98b070beb4..14dee46739 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -92,6 +92,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-connections.e2e.test.ts","server/cloud-team-conversation-share.e2e.test.ts","server/cloud-team-engine-homes.e2e.test.ts",+ "server/cloud-team-files.e2e.test.ts","server/cloud-team-gateway-mcp.e2e.test.ts","server/cloud-team-inbox.e2e.test.ts","server/cloud-team-included-hosting.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 869c83baba..618082a782 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -232,6 +232,7 @@ describe("CI outputs", () => {"server/cloud-team-connections.e2e.test.ts","server/cloud-team-conversation-share.e2e.test.ts","server/cloud-team-engine-homes.e2e.test.ts",+ "server/cloud-team-files.e2e.test.ts","server/cloud-team-gateway-mcp.e2e.test.ts","server/cloud-team-inbox.e2e.test.ts","server/cloud-team-included-hosting.e2e.test.ts",diff --git a/server/bot-box/box.ts b/server/bot-box/box.tsindex 20ec4039a3..eb77c27308 100644--- a/server/bot-box/box.ts+++ b/server/bot-box/box.ts@@ -90,8 +90,9 @@ export class BoxRunner {private conversation(request: BoxRequest): { botId: string | null; threadId: string | null; folder: boolean } {const ids = request.cwd ? taskWorkspaceIds(request.cwd, this.options.setup.dataDir) : null;if (ids) return { ...ids, folder: true };+ if (!request.cwd && request.conversationBot) return { botId: request.conversationBot, threadId: request.threadId ?? null, folder: false };const inWorkspaces = request.cwd ? relative(join(this.options.setup.dataDir, "workspaces"), resolve(request.cwd)).split(sep)[0] : undefined;- const botId = request.botId ?? (inWorkspaces && /^[A-Za-z0-9_-]{1,128}$/.test(inWorkspaces) ? inWorkspaces : null);+ const botId = request.botId ?? (inWorkspaces && /^[A-Za-z0-9_-]{1,128}$/.test(inWorkspaces) ? inWorkspaces : null) ?? request.conversationBot ?? null;return { botId, threadId: request.threadId ?? null, folder: false };}@@ -274,7 +275,7 @@ export class BotBox {broker: { port: BOX_BROKER_PORT, mintForProcess: this.credentials.mintForProcess, revoke: this.credentials.revoke },});this.runner.scopeAudiences(this.audiences);- distrustHomePrograms(options.home, [options.dataDir], ["workspaces", "task-workspaces", "engine-homes"].map((name) => join(options.dataDir, name)));+ distrustHomePrograms(options.home, [options.dataDir], ["workspaces", "task-workspaces", "engine-homes", "team-files"].map((name) => join(options.dataDir, name)));resetPathCache();log(`bot box: on (bubblewrap, ${this.detection.tools.socat ? "socat" : "node"} bridges, credential broker, seccomp ${this.seccompFile ? "on" : "unsupported here"})`);return this.detection;@@ -327,9 +328,15 @@ export class BotBox {/** What a process the bot's conversations share is boxed with, as a key: the conversations its box puts back on a* Team Cloud, so a conversation made after it started gets a process whose box has its folder. Null elsewhere. */- sharedThreadsKey(request: Pick<BoxRequest, "cwd" | "threadId">): string | null {- const threads = this.runner?.audienceFor({ command: "", args: [], env: {}, ...request, botThreads: true })?.threads;- return threads ? JSON.stringify([threads.rw, threads.ro]) : null;+ sharedThreadsKey(request: Pick<BoxRequest, "cwd" | "threadId" | "conversationBot">): string | null {+ const audience = this.runner?.audienceFor({ command: "", args: [], env: {}, ...request, botThreads: true });+ return audience?.threads ? JSON.stringify([audience.threads.rw, audience.threads.ro, audience.teamFiles?.write ?? null]) : null;+ }++ /** What the audience rule gives one box now, as a key: what a process kept between turns is started again on. */+ audienceKey(request: Pick<BoxRequest, "cwd" | "threadId" | "conversationBot">): string | null {+ const audience = this.runner?.audienceFor({ command: "", args: [], env: {}, ...request });+ return audience ? JSON.stringify([audience.teamReadOnly, audience.teamFiles?.write ?? null]) : null;}/** More read-write folders for one conversation's boxes (a memory layer); nothing without a runner. */diff --git a/server/bot-box/plan.test.ts b/server/bot-box/plan.test.tsindex 2e2e401bd9..cb2aee7b19 100644--- a/server/bot-box/plan.test.ts+++ b/server/bot-box/plan.test.ts@@ -322,6 +322,20 @@ linuxBox("the box plan", () => {expect(visibleInBox(ask({ teamReadOnly: true }, { cwd: "/data/projects/site", botId: "bot-a" }), join(team, "MEMORY.md"))).toBe("ro");});+ it("every turn has the team's shared folder at /team-files: read-only, or read-write for a bot that may edit it", () => {+ const source = join(dataDir, "team-files");+ const read = ask({ teamReadOnly: true, teamFiles: { source, write: false } });+ expect(visibleInBox(read, "/team-files/payroll/nov.csv")).toBe("ro");+ expect(visibleInBox(read, join(source, "payroll", "nov.csv")), "only at its own path, never where the server keeps it").toBe("none");+ const edit = ask({ teamReadOnly: true, teamFiles: { source, write: true } });+ expect(visibleInBox(edit, "/team-files/payroll/nov.csv")).toBe("rw");+ expect(edit.writable).toContain("/team-files");+ expect(writesTeamThings(edit), "editing team files is not writing the bot's own folder").toEqual(["ro", "ro", "ro", "ro"]);+ expect(bwrapArgs(edit).join(" ")).toContain(`--bind-try ${source} /team-files`);+ expect(visibleInBox(edit, "/team-files/templates/reporter/bot.yaml"), "the team's template library stays the admins'").toBe("ro");+ expect(visibleInBox(ask({ teamReadOnly: false }), "/team-files/x")).toBe("none");+ });+it("a process the bot's conversations share has only the conversations its audience may read", () => {const threads = (rw: string[], ro: string[]) => planBox(setup(), { command: "opencode", args: ["acp"], cwd, env: { HOME: home }, botThreads: true, audience: { teamReadOnly: ro.length > 0, threads: { rw, ro } } });const mira = threads(["thread-1", "thread-3"], ["thread-team"]);diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.tsindex 2095ab1794..66f8390945 100644--- a/server/bot-box/plan.ts+++ b/server/bot-box/plan.ts@@ -88,6 +88,8 @@ export interface BoxRequest {relay?: string;/** The conversation this spawn runs for, when the caller knows it (a Team Cloud's engine homes do). */threadId?: string;+ /** The bot whose turn that is, for the audience rule only (BoxAudience); unlike `botId` it puts back nothing. */+ conversationBot?: string;/** On a Team Cloud: what the conversation's audience gives the box of the bot's team things (BoxAudience). */audience?: BoxAudience;}@@ -102,8 +104,16 @@ export interface BoxAudience {/** With `botThreads`: the bot's conversations the shared process may see, in place of all of them. Its own audience's* read-write, the team's read-only; another person's never. */threads?: { rw: readonly string[]; ro: readonly string[] };+ /** The Team Cloud's shared folder (team-files/), at TEAM_FILES_IN_BOX in every box of a turn: read-only, or read-write+ * for a bot an admin marked "Can edit team files" while the folder has room (server/host/team-files.ts). */+ teamFiles?: { source: string; write: boolean };}+/** Where every bot's box has its Team Cloud's shared folder. */+export const TEAM_FILES_IN_BOX = "/team-files";+/** Its template library, read-only in every box. */+export const TEAM_FILES_LIBRARY = "templates";+/** What stays read-only in a bot's own folder that is a non-team turn's working folder. */export const TEAM_FOLDER_KEPT = ["MEMORY.md", "memory", "skills"] as const;@@ -299,6 +309,15 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {mounts.push({ kind: "ro", source: full, target: full, optional: true });}+ // The team's shared folder, at one path in every box: its own line, as nothing else is bound there.+ const teamFiles = request.audience?.teamFiles;+ if (teamFiles) {+ mounts.push({ kind: teamFiles.write ? "bind" : "ro", source: resolve(teamFiles.source), target: TEAM_FILES_IN_BOX, optional: true });+ if (teamFiles.write && !writable.includes(TEAM_FILES_IN_BOX)) writable.push(TEAM_FILES_IN_BOX);+ // The team's template library (server/team-templates.ts) is its admins', so it stays read-only for a bot that may edit.+ if (teamFiles.write) mounts.push({ kind: "ro", source: join(resolve(teamFiles.source), TEAM_FILES_LIBRARY), target: join(TEAM_FILES_IN_BOX, TEAM_FILES_LIBRARY), optional: true });+ }+const options = ["--unshare-user", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup-try", "--die-with-parent", "--hostname", BOX_HOSTNAME];if (!mutate.has("share-pid")) options.push("--unshare-pid");if (setup.seccompFd !== undefined && !mutate.has("no-seccomp")) options.push("--seccomp", String(setup.seccompFd));diff --git a/server/cloud-team-files.e2e.test.ts b/server/cloud-team-files.e2e.test.tsnew file mode 100644index 0000000000..cb1112ff87--- /dev/null+++ b/server/cloud-team-files.e2e.test.ts@@ -0,0 +1,185 @@+// Team files on a real Team Cloud: Olive (the Owner), Mira and Ben (Members), a Payroll bot an admin lets edit the shared+// folder and a Notes bot that only reads it. Mira uploads; Payroll writes a record from Mira's private chat and the page+// names them both; members delete only what they uploaded and an admin anything; the export carries the folder; Mira+// leaving takes none of it; a personal Cloud has no such routes. The bot box runs only where an unprivileged bubblewrap+// does (not macOS, not CI's Ubuntu 24.04): there the read-only folder is checked here too, elsewhere in+// server/host/team-box-scope.test.ts and server/bot-box/plan.test.ts.+import { randomBytes } from "node:crypto";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import type { TeamFilesListing } from "../shared/team-files.ts";+import { detectBox } from "./bot-box/detect.ts";+import { hostTimeout } from "./testing/host-timeout.ts";+import { stagedWorkspaceData, stageWorkspaceBackup } from "./workspace-backup.ts";++const posix = process.platform !== "win32";+const boxed = posix && detectBox({ env: { ...process.env, OMB_CLOUD_ROLE: "team" } }).box === "bwrap";+const TOKEN = `ops_fake-team-files-${randomBytes(8).toString("hex")}`;+const PASSWORD = "correct horse battery staple";+const OLIVE = { email: "[email protected]", role: "owner" as const };+const MIRA = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const SHELL = `import { readFileSync as readToolCalls } from "node:fs";+process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";+process.env.FAKE_CLAUDE_SHELL_LOG = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/shell.jsonl";+process.env.FAKE_CLAUDE_RUN_BASH = "1";+process.env.FAKE_CLAUDE_EXIT_AFTER_TURN = "1";+try { process.env.FAKE_CLAUDE_TOOL_CALLS = readToolCalls(process.env.FAKE_CLAUDE_FIXTURE_DIR + "/tool-calls.json", "utf8"); } catch {}`;++let fx: CloudSendFixture, team: CloudTeamFixture;+let olive = "", mira = "", ben = "";+let payroll: { id: string; name: string }, notes: { id: string; name: string };+let dataDir = "", folder = "";++const messages = async (token: string, threadId: string) => (await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as Array<{ role: string }>;+const idle = async (token: string) => ((await team.as(token, "GET", "/api/bots")).body.bots as Array<{ activity?: string; busy?: boolean }>)+ .every((entry) => entry.activity !== "working" && !entry.busy);+const shellOutput = (command: string) => existsSync(join(team.home, "shell.jsonl"))+ ? readFileSync(join(team.home, "shell.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line) as { command: string; output: string }).filter((entry) => entry.command === command).at(-1)?.output ?? "" : "";+async function turn(token: string, botId: string, threadId: string, command: string): Promise<{ systemPrompt: string; output: string }> {+ rmSync(join(team.home, "dump.json"), { force: true });+ writeFileSync(join(team.home, "tool-calls.json"), JSON.stringify([{ name: "Bash", input: { command } }]));+ try {+ const before = (await messages(token, threadId)).length;+ const sent = await team.as(token, "POST", `/api/bots/${botId}/messages`, { text: "Do it.", threadId });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await expect.poll(async () => await idle(token) && (await messages(token, threadId)).length >= before + 2 && existsSync(join(team.home, "dump.json")),+ { timeout: 60_000, interval: 100 }).toBe(true);+ } finally {+ rmSync(join(team.home, "tool-calls.json"), { force: true });+ }+ return { systemPrompt: (JSON.parse(readFileSync(join(team.home, "dump.json"), "utf8")) as { systemPrompt?: string }).systemPrompt ?? "", output: shellOutput(command) };+}+const newThread = async (token: string, botId: string) => {+ const created = await team.as(token, "POST", `/api/bots/${botId}/tasks`, { title: "Chat" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ return created.body.task.threadId as string;+};+const list = async (token: string, path = "") => {+ const answer = await team.as(token, "GET", `/api/team-files?path=${encodeURIComponent(path)}`);+ expect(answer.status, JSON.stringify(answer.body)).toBe(200);+ return answer.body as TeamFilesListing;+};+const upload = (token: string, path: string, name: string, text: string) =>+ team.as(token, "PUT", `/api/team-files/file?path=${encodeURIComponent(path)}&name=${encodeURIComponent(name)}`, new TextEncoder().encode(text), { "content-type": "application/octet-stream" });++beforeAll(async () => {+ if (!posix) return;+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, team: { id: "team-acme-files", name: "Acme", engine: SHELL }, cloudEngine: SHELL });+ team = fx.team!;+ dataDir = join(team.home, ".openmausbot");+ olive = (await team.pair(OLIVE)).token!;+ mira = (await team.pair(MIRA)).token!;+ ben = (await team.pair(BEN)).token!;+ for (const name of ["Payroll", "Notes"]) {+ const created = await team.as(olive, "POST", "/api/bots", { name, visibility: "everyone" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ if (name === "Payroll") payroll = created.body.bot; else notes = created.body.bot;+ }+ folder = boxed ? "/team-files" : join(dataDir, "team-files");+}, hostTimeout(180_000));++afterAll(async () => {+ await fx?.close();+});++it.runIf(posix)("a member uploads and makes folders, and every teammate sees who did", async () => {+ expect((await team.as(mira, "POST", "/api/team-files/folder", { path: "payroll" })).status).toBe(201);+ const uploaded = await upload(mira, "", "handbook.md", "# Handbook\nBe kind.\n");+ expect(uploaded.status, JSON.stringify(uploaded.body)).toBe(201);+ const seen = await list(ben);+ expect(seen.entries.map((entry) => [entry.name, entry.kind])).toEqual([["payroll", "folder"], ["handbook.md", "file"]]);+ const handbook = seen.entries.find((entry) => entry.name === "handbook.md")!;+ expect(handbook).toMatchObject({ size: 20, canDelete: false, mine: false, last: { action: "uploaded" } });+ expect(handbook.last?.person).toMatch(/mira/i);+ expect(seen.used).toBe(20);+ expect(seen.cap).toBe(5 * 1024 ** 3);+ const read = await fetch(`${team.base}/api/team-files/file?path=handbook.md`, { headers: { ...fx.edge, authorization: `Bearer ${ben}` } });+ expect([read.status, read.headers.get("content-type"), await read.text()]).toEqual([200, "text/plain; charset=utf-8", "# Handbook\nBe kind.\n"]);+ expect((await team.as(ben, "GET", "/api/team-files?path=..%2F")).status).toBe(400);+ expect((await upload(ben, "../workspaces", "x.md", "no")).status).toBe(400);+}, hostTimeout(60_000));++it.runIf(posix)("only an admin lets a bot edit team files", async () => {+ const refused = await team.as(mira, "PATCH", `/api/bots/${payroll.id}`, { teamFilesEdit: true });+ expect(refused.status).toBe(403);+ const allowed = await team.as(olive, "PATCH", `/api/bots/${payroll.id}`, { teamFilesEdit: true });+ expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);+ const bots = (await team.as(mira, "GET", "/api/bots")).body.bots as Array<{ id: string; teamFilesEdit?: boolean }>;+ expect(bots.find((bot) => bot.id === payroll.id)?.teamFilesEdit).toBe(true);+ expect(bots.find((bot) => bot.id === notes.id)?.teamFilesEdit).toBeFalsy();+}, hostTimeout(60_000));++it.runIf(posix)("Payroll writes a record from Mira's private chat, and the page names Mira and Payroll", async () => {+ const thread = await newThread(mira, payroll.id);+ const command = `printf 'name,net\\nMira,4200\\n' > "${folder}/payroll/nov.csv" && echo WROTE`;+ const { systemPrompt, output } = await turn(mira, payroll.id, thread, command);+ expect(systemPrompt).toContain(`Team files, the folder everyone at Acme shares: ${folder}. You can add and change files there`);+ expect(output).toContain("WROTE");+ const listed = await list(ben, "payroll");+ const record = listed.entries.find((entry) => entry.name === "nov.csv")!;+ expect(record).toMatchObject({ kind: "file", canDelete: false, last: { action: "added", bot: "Payroll" } });+ expect(record.last?.person).toMatch(/mira/i);+ // The conversation itself never goes there.+ expect((await list(olive, "")).entries.map((entry) => entry.name).sort()).toEqual(["handbook.md", "payroll"]);+}, hostTimeout(120_000));++it.runIf(posix)("a bot nobody let edit is told the folder is read-only for it", async () => {+ const thread = await newThread(mira, notes.id);+ const command = `cat "${folder}/handbook.md" && (echo x >> "${folder}/handbook.md") 2>&1 && echo WROTE || echo REFUSED`;+ const { systemPrompt, output } = await turn(mira, notes.id, thread, command);+ expect(systemPrompt).toContain(`shares: ${folder}. It is read-only for you.`);+ expect(output).toContain("Be kind.");+ if (boxed) {+ expect(output).toContain("REFUSED");+ expect(readFileSync(join(dataDir, "team-files", "handbook.md"), "utf8")).toBe("# Handbook\nBe kind.\n");+ }+}, hostTimeout(120_000));++it.runIf(posix)("a member deletes only what they uploaded; an admin deletes anything", async () => {+ expect((await team.as(ben, "POST", "/api/team-files/delete", { path: "handbook.md" }))).toMatchObject({ status: 403, body: { code: "forbidden" } });+ expect((await team.as(ben, "POST", "/api/team-files/delete", { path: "payroll/nov.csv" })).status).toBe(403);+ expect((await team.as(ben, "POST", "/api/team-files/rename", { from: "handbook.md", to: "mine.md" })).status).toBe(403);+ expect((await upload(ben, "", "ben.txt", "Ben's")).status).toBe(201);+ expect((await team.as(ben, "POST", "/api/team-files/delete", { path: "ben.txt" })).status).toBe(200);+ expect((await list(olive)).entries.find((entry) => entry.name === "handbook.md")?.canDelete).toBe(true);+ expect((await upload(mira, "", "old.md", "old")).status).toBe(201);+ expect((await team.as(olive, "POST", "/api/team-files/delete", { path: "old.md" })).status).toBe(200);+ expect((await list(mira)).entries.map((entry) => entry.name)).toEqual(["payroll", "handbook.md"]);+}, hostTimeout(60_000));++it.runIf(posix)("the Owner's export carries the team's files and who changed them", async () => {+ const made = await team.as(olive, "POST", "/api/workspace-backup/export", { password: PASSWORD });+ expect(made.status, JSON.stringify(made.body)).toBe(200);+ const download = await fetch(`${team.base}/api/workspace-backup/download/${made.body.id}`, { headers: { ...fx.edge, authorization: `Bearer ${olive}` } });+ expect(download.status).toBe(200);+ const unpack = mkdtempSync(join(tmpdir(), "omb-team-files-export-"));+ try {+ const archive = join(unpack, "export.ombbackup");+ writeFileSync(archive, Buffer.from(await download.arrayBuffer()));+ const staged = await stageWorkspaceBackup(unpack, archive, { password: PASSWORD, currentAppVersion: made.body.summary.appVersion });+ const { data } = stagedWorkspaceData(unpack, staged.id);+ expect(readFileSync(join(data, "team-files", "payroll", "nov.csv"), "utf8")).toContain("Mira,4200");+ expect(readFileSync(join(data, "team-files", "handbook.md"), "utf8")).toContain("Be kind.");+ expect(readFileSync(join(data, "team-files-activity.json"), "utf8")).toContain("payroll/nov.csv");+ } finally {+ rmSync(unpack, { recursive: true, force: true });+ }+}, hostTimeout(180_000));++it.runIf(posix)("Mira leaving takes nothing of team files: what she wrote stays the team's", async () => {+ const left = await team.signed("POST", "/api/cloud/team/member-left", { email: MIRA.email });+ expect(left.status, JSON.stringify(left.body)).toBe(200);+ const listed = await list(olive);+ expect(listed.entries.map((entry) => entry.name)).toEqual(["payroll", "handbook.md"]);+ expect((await list(olive, "payroll")).entries.map((entry) => entry.name)).toEqual(["nov.csv"]);+}, hostTimeout(60_000));++it.runIf(posix)("a personal Cloud has no team files at all", async () => {+ expect((await fx.onCloud("GET", "/api/team-files")).status).toBe(404);+ expect((await fx.onCloud("POST", "/api/team-files/folder", { path: "x" })).status).toBe(404);+ expect(existsSync(join(team.home, "..", "cloud", ".openmausbot", "team-files"))).toBe(false);+}, hostTimeout(60_000));diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex ba995722ab..8d5926765a 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -19,7 +19,7 @@ import { DeviceAuthController, deviceAuthInstanceSurface, type DeviceSignIn } frimport { AcpBrowserAuth, acpBrowserAuthInstanceSurface, type AcpBrowserSignInSpec } from "./browser-auth.ts";import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";import type { PromptSplitReceipt } from "../prompt-split.ts";-import { describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";+import { boxAudienceKey, describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";import { runAcpOneShot } from "./background-text.ts";import { acpCapabilities } from "./capabilities.ts";import { acpNativeLogMessage } from "./tool-log.ts";@@ -1025,7 +1025,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>? createHash("sha256").update(support.toolScopeCacheKey({ config: turnConfig, env, cwd })).digest("hex") : null;const processContract = [launch.command, launch.args ?? [], spawnArgs,support.sessionScopedApproval ? null : turnConfig.fullAuto === true, envFingerprint,- support.spawnFingerprint?.(spawnEnv, turnConfig) ?? null, launch.ro ?? []];+ support.spawnFingerprint?.(spawnEnv, turnConfig) ?? null, launch.ro ?? [], boxAudienceKey(cwd)];const contractKey = JSON.stringify([...processContract, cwd, turn.toolScope ?? null, inheritedScopeFingerprint]);const launchModel = support.sessionModelEnv && cliTurn.model && /^[\w.:/-]{1,200}$/u.test(cliTurn.model)&& catalog.accountModels?.has(cliTurn.model) ? cliTurn.model : undefined;diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex e40267fa95..a6a01cf007 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -10,7 +10,7 @@ import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";import { writeFileAtomicIfChanged } from "../atomic.ts";import { augmentedPath, findCliCandidates } from "../env-path.ts"; import { BASH_MAX_TIMEOUT_MS } from "../system-prompt.ts";-import { brokerSocketPath, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../engine-stop.ts";+import { boxAudienceKey, brokerSocketPath, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../engine-stop.ts";import { cliToLaunch, cliVersionProbe } from "../cli-version-probe.ts";import { claudeAuthStatus } from "./claude-auth-status.ts";import { projectMcpServers } from "./claude-project-mcp.ts";@@ -1194,7 +1194,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {model: injected.model ?? null,base: env.ANTHROPIC_BASE_URL ?? null,configDir: env.CLAUDE_CONFIG_DIR ?? null,- hooks: Boolean(hooks),+ hooks: Boolean(hooks), box: boxAudienceKey(cwd),toolSearch, mcpOutputTokens: env.MAX_MCP_OUTPUT_TOKENS ?? null,botSettings: createHash("sha256").update(JSON.stringify(botSettings)).digest("hex"),// Rotating an account's key/helper must not reuse the old process.diff --git a/server/engine-homes/engine-homes.ts b/server/engine-homes/engine-homes.tsindex 62acc7d347..954793f7fd 100644--- a/server/engine-homes/engine-homes.ts+++ b/server/engine-homes/engine-homes.ts@@ -26,6 +26,7 @@ export class EngineHomes {#setup: (EngineHomesSetup & { serverHome: string }) | null = null;#migration: MigrationResult | null = null;readonly #thread = new AsyncLocalStorage<string>();+ readonly #bot = new AsyncLocalStorage<string | undefined>();start(setup: EngineHomesSetup): void {this.#setup = { ...setup, serverHome: setup.serverHome ?? homedir() };@@ -40,9 +41,9 @@ export class EngineHomes {return this.#setup !== null;}- /** Runs `start` with what it spawns counted as this conversation's. */- within<T>(threadId: string, start: () => T): T {- return this.#setup ? this.#thread.run(threadId, start) : start();+ /** Runs `start` with what it spawns counted as this conversation's (and its bot's, when the caller names it). */+ within<T>(threadId: string, start: () => T, botId?: string): T {+ return this.#setup ? this.#thread.run(threadId, () => this.#bot.run(botId, start)) : start();}/** The conversation the caller runs in, on a Team Cloud; undefined elsewhere. */@@ -50,6 +51,11 @@ export class EngineHomes {return this.#setup ? this.#thread.getStore() : undefined;}+ /** The bot whose turn the caller runs in, on a Team Cloud, when its adapter was told. */+ bot(): string | undefined {+ return this.#setup ? this.#bot.getStore() : undefined;+ }+/** The audience key of the conversation the caller runs in, so engines never share a process across audiences. */scope(): string | null {const threadId = this.#setup ? this.#thread.getStore() : undefined;@@ -107,7 +113,7 @@ export function withEngineHomes(instance: ProviderInstance, homes: EngineHomes =const warm = adapter.cacheKeepWarm;(instance as { adapter: ProviderInstance["adapter"] }).adapter = {...adapter,- sendTurn: (input) => homes.within(input.threadId, () => adapter.sendTurn(input)),+ sendTurn: (input) => homes.within(input.threadId, () => adapter.sendTurn(input), input.botId),...(warm ? { cacheKeepWarm: {...warm,ping: (threadId, options) => homes.within(threadId, () => warm.ping(threadId, options)),diff --git a/server/host/cloud-team-host.ts b/server/host/cloud-team-host.tsindex 20dac8222f..27ecdd55d8 100644--- a/server/host/cloud-team-host.ts+++ b/server/host/cloud-team-host.ts@@ -11,7 +11,7 @@ import { ensureWorkspace, loadMemory, workspaceDir } from "../workspace.ts";import type { EngineHomes } from "../engine-homes/engine-homes.ts";import { storeThreads, type StoreBotThreads } from "../engine-homes/migrate.ts";import type { ConversationShares } from "./conversation-shares.ts";-import { createTeamBoxScope, type TeamBoxBots } from "./team-box-scope.ts";+import { createTeamBoxScope, type TeamBoxBots, type TeamBoxScopeDeps } from "./team-box-scope.ts";import type { BoxAudienceScope } from "../bot-box/box.ts";export interface CloudTeamHostDeps {@@ -31,6 +31,8 @@ export interface CloudTeamHostDeps {engineHomes?: Pick<EngineHomes, "start">;/** Given the audience rule on a team, for every box (server/host/team-box-scope.ts). */box?: { scopeAudiences(scope: BoxAudienceScope | null): void };+ /** The team's shared folder in each bot's boxes (server/host/team-files-host.ts). */+ teamFiles?: TeamBoxScopeDeps["teamFiles"];}export interface TeamSessionInfo { id: string; name: string; role: TeamRole }@@ -55,7 +57,7 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {return person && !deps.shares?.isShareKey(person) ? person : null;};if (team) deps.engineHomes?.start({ dataDir: deps.dataDir, audienceOf, threads: () => storeThreads(deps.store.bots ?? []) });- if (team) deps.box?.scopeAudiences(createTeamBoxScope({ audienceOf, bots: () => deps.store.bots ?? [] }));+ if (team) deps.box?.scopeAudiences(createTeamBoxScope({ audienceOf, bots: () => deps.store.bots ?? [], ...(deps.teamFiles ? { teamFiles: deps.teamFiles } : {}) }));/** The layer a turn in this conversation writes into: the bot's own folder off a team or for the team's conversations,* a sibling folder for a room's or a member's. The folder exists before the turn starts, so the box can bind it. */const layer = (botId: string, threadId: string): string => {@@ -217,6 +219,11 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {sessionInfo(session: { teamRole?: TeamRole }): TeamSessionInfo | null {return team && session.teamRole ? { id: team.id, name: team.name, role: session.teamRole } : null;},+ /** The person whose own conversation this is on a team; null for the team's, a room's, one shared with one person,+ * and anywhere off a team. */+ ownerOf(threadId: string): string | null {+ return team ? ownPerson(audienceOf(threadId)) : null;+ },/** The person a conversation is private to on a team (theirs alone, audience.ts); null for the team's, a room's and* anywhere off a team. Security invariant: a conversation shared with one person answers its share key, which no* session holds, so whatever follows this alone (a routine's home, an ask's person) reaches nobody rather than eitherdiff --git a/server/host/team-box-scope.test.ts b/server/host/team-box-scope.test.tsindex 6ad78c7822..bdb2fd6389 100644--- a/server/host/team-box-scope.test.ts+++ b/server/host/team-box-scope.test.ts@@ -11,7 +11,7 @@ import { botBox, type WrappedSpawn } from "../bot-box/box.ts";import { visibleInBox, type BoxRequest } from "../bot-box/plan.ts";import { DATA_DIR } from "../config.ts";import { engineHomes } from "../engine-homes/engine-homes.ts";-import { boxedSpawn, sharedBoxScope } from "../procs.ts";+import { boxAudienceKey, boxedSpawn, sharedBoxScope } from "../procs.ts";import { removeTempDir } from "../testing/cleanup.ts";import { ensureTaskWorkspace } from "../workspace.ts";import { createCloudTeamHost } from "./cloud-team-host.ts";@@ -43,6 +43,13 @@ describe("the Team Cloud's box scope", () => {.toEqual({ rw: ["mira-1", "mira-2", "mira-new"], ro: ["main", "team-1"] });expect(botConversations(bots, "bot-gone")).toEqual([]);});++ it("gives every turn the team's shared folder as the host says, whatever its audience", () => {+ const withFiles = createTeamBoxScope({ audienceOf: (threadId) => team(undefined).audienceOf(threadId), bots: () => bots,+ teamFiles: (botId) => ({ source: "/data/team-files", write: botId === BOT }) });+ expect(withFiles({ threadId: "mira-1", botId: BOT, sharedProcess: false })).toEqual({ teamReadOnly: true, teamFiles: { source: "/data/team-files", write: true } });+ expect(withFiles({ threadId: "main", botId: "bot-other", sharedProcess: false })).toEqual({ teamReadOnly: false, teamFiles: { source: "/data/team-files", write: false } });+ });});// The box's gates listen on unix sockets, which Windows refuses at a file path; the box runs only on a Linux Cloud home.@@ -129,6 +136,19 @@ describe.skipIf(process.platform === "win32")("a Team Cloud turn's box, through}});+ it("a process kept between turns starts again when the bot may no longer edit team files", () => {+ let edit = true;+ createCloudTeamHost({ team: { id: "team-acme", name: "Acme" } as never, dataDir: DATA_DIR, store, starters, markers: new Set(["nobody"]), engineHomes, box: botBox,+ teamFiles: () => ({ source: at("team-files"), write: edit }) });+ const key = () => engineHomes.within("mira-1", () => boxAudienceKey(folder("mira-1")), BOT);+ const before = key();+ expect(visibleInBox(planIn("mira-1", folder("mira-1")), "/team-files/payroll.csv")).toBe("rw");+ edit = false;+ expect(key(), "Claude Code's and the ACP engines' process keys carry it").not.toBe(before);+ expect(visibleInBox(planIn("mira-1", folder("mira-1")), "/team-files/payroll.csv")).toBe("ro");+ expect(engineHomes.within("mira-1", () => sharedBoxScope(folder("mira-1")), BOT)).toContain("#");+ });+it("off a team the box is as it was: every turn writes the bot's own folder", () => {team(botBox, false);botBox.scopeAudiences(null);diff --git a/server/host/team-box-scope.ts b/server/host/team-box-scope.tsindex 007b33f78a..9c6fa0e926 100644--- a/server/host/team-box-scope.ts+++ b/server/host/team-box-scope.ts@@ -12,6 +12,8 @@ export type TeamBoxBots = ReadonlyArray<{ id: string; threadId?: string; tasks?:export interface TeamBoxScopeDeps {audienceOf(threadId: string): Audience;bots(): TeamBoxBots;+ /** The team's shared folder as this bot's boxes get it (server/host/team-files-host.ts), whatever the audience. */+ teamFiles?(botId: string | null): BoxAudience["teamFiles"] | null;}/** Every conversation the store has for this bot; one it no longer has (deleted) is never put back. */@@ -24,7 +26,8 @@ export function botConversations(bots: TeamBoxBots, botId: string): string[] {export function createTeamBoxScope(deps: TeamBoxScopeDeps): BoxAudienceScope {return ({ threadId, botId, sharedProcess }): BoxAudience => {const turn = deps.audienceOf(threadId);- const audience: BoxAudience = { teamReadOnly: turn !== TEAM_AUDIENCE };+ const files = deps.teamFiles?.(botId) ?? null;+ const audience: BoxAudience = { teamReadOnly: turn !== TEAM_AUDIENCE, ...(files ? { teamFiles: files } : {}) };if (!sharedProcess || !botId) return audience;const rw: string[] = [], ro: string[] = [];for (const other of botConversations(deps.bots(), botId)) {diff --git a/server/host/team-files-host.test.ts b/server/host/team-files-host.test.tsnew file mode 100644index 0000000000..753fa4f66e--- /dev/null+++ b/server/host/team-files-host.test.ts@@ -0,0 +1,51 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { createTeamFilesHost } from "./team-files-host.ts";++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+function host(options: { team?: boolean; boxOn?: boolean; edit?: boolean } = {}) {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-team-files-host-"));+ dirs.push(dataDir);+ const bots = [{ id: "payroll", teamFilesEdit: options.edit ?? false }, { id: "notes" }];+ return { dataDir, host: createTeamFilesHost({ team: options.team === false ? null : { name: "Acme" }, dataDir, bots: () => bots, boxOn: () => options.boxOn ?? true, askerOf: (threadId) => (threadId === "t-mira" ? "p_mira" : null) }) };+}++describe("Team files on a Team Cloud at run time", () => {+ it("is nothing off a Team Cloud: no folder, no box mount, no line", () => {+ const { host: off } = host({ team: false });+ expect(off.files).toBeNull();+ expect(off.boxFolder("payroll")).toBeNull();+ expect(off.promptLine("payroll")).toBe("");+ });++ it("mounts the folder read-write only for a bot an admin let edit it, and tells each bot which", () => {+ const { host: on, dataDir } = host({ edit: true });+ expect(on.boxFolder("payroll")).toEqual({ source: join(dataDir, "team-files"), write: true });+ expect(on.boxFolder("notes")).toEqual({ source: join(dataDir, "team-files"), write: false });+ expect(on.boxFolder(null)?.write).toBe(false);+ expect(on.promptLine("payroll")).toBe("\n\nTeam files, the folder everyone at Acme shares: /team-files. You can add and change files there; everyone on the team sees them.");+ expect(on.promptLine("notes")).toBe("\n\nTeam files, the folder everyone at Acme shares: /team-files. It is read-only for you.");+ // Without a box the folder is where the server keeps it.+ const { host: unboxed, dataDir: where } = host({ boxOn: false });+ expect(unboxed.promptLine("notes")).toContain(`shares: ${join(where, "team-files")}. It is read-only for you.`);+ });++ it("records a turn's changes for a bot that may edit, and for any bot where no box keeps the folder read-only", () => {+ const { host: on, dataDir } = host({ edit: true });+ on.beginTurn("payroll", "t-mira");+ writeFileSync(join(dataDir, "team-files", "nov.csv"), "x");+ on.onEvent({ type: "turn.completed", threadId: "t-mira" });+ expect(on.files!.activity()).toMatchObject([{ path: "nov.csv", action: "added", bot: "payroll", person: "p_mira" }]);+ on.beginTurn("notes", "t-other");+ expect(on.files!.openTurns(), "a read-only bot in a box changes nothing").toBe(0);+ const { host: unboxed, dataDir: plain } = host({ boxOn: false });+ unboxed.beginTurn("notes", "t-other");+ writeFileSync(join(plain, "team-files", "x.md"), "y");+ unboxed.onEvent({ type: "session.exited", threadId: "t-other" });+ expect(unboxed.files!.activity()).toMatchObject([{ path: "x.md", action: "added", bot: "notes" }]);+ });+});diff --git a/server/host/team-files-host.ts b/server/host/team-files-host.tsnew file mode 100644index 0000000000..a91a30ae2f--- /dev/null+++ b/server/host/team-files-host.ts@@ -0,0 +1,60 @@+// Team files on a Team Cloud at run time (server/host/team-files.ts is the folder itself): what each bot's box gets of+// the folder, the one line a bot's prompt says about it, and the before-and-after of every turn that could write it, so+// the page says "Changed by Mira with Payroll". Off a Team Cloud there is no folder, no line and no route.+import { mkdirSync } from "node:fs";+import { join } from "node:path";++import { TEAM_FILES_IN_BOX } from "../bot-box/plan.ts";+import { createTeamFiles, TEAM_FILES_TEMPLATES, type TeamFiles } from "./team-files.ts";++export interface TeamFilesHostDeps {+ team: { name: string } | null;+ dataDir: string;+ bots(): ReadonlyArray<{ id: string; teamFilesEdit?: boolean }>;+ /** Whether turns run in the bot box here: only there is the folder at /team-files and read-only for a bot. */+ boxOn(): boolean;+ /** The person a turn works for: whoever asked (their line), else the person the conversation is theirs alone. */+ askerOf(threadId: string): string | null;+}++export function createTeamFilesHost(deps: TeamFilesHostDeps) {+ const files: TeamFiles | null = deps.team ? createTeamFiles({ dataDir: deps.dataDir }) : null;+ if (files) files.ensure();+ const canEdit = (botId: string | null) => botId !== null && deps.bots().some((bot) => bot.id === botId && bot.teamFilesEdit === true);++ return {+ files,+ /** What a bot's boxes get of the folder: read-write for a bot that may edit it while it has room, else read-only. */+ boxFolder(botId: string | null): { source: string; write: boolean } | null {+ if (!files) return null;+ const source = files.ensure();+ // Made first, so the read-only bind over it has something to cover in a box that may write the rest.+ try { mkdirSync(join(source, TEAM_FILES_TEMPLATES), { recursive: true, mode: 0o700 }); } catch {}+ return { source, write: canEdit(botId) && !files.full() };+ },+ /** One line for every bot's turn on a Team Cloud: where the folder is, and whether this bot may change it. */+ promptLine(botId: string): string {+ if (!files || !deps.team) return "";+ const where = deps.boxOn() ? TEAM_FILES_IN_BOX : files.root();+ const mode = !canEdit(botId) ? "It is read-only for you."+ : files.full() ? `It is full (${Math.round(files.cap / 1024 ** 3)} GB), so it is read-only until someone removes files.`+ : "You can add and change files there; everyone on the team sees them.";+ return `\n\nTeam files, the folder everyone at ${deps.team.name} shares: ${where}. ${mode}`;+ },+ /** Before a bot's turn: the folder as it is, when the turn could change it (a bot that may edit, or any bot where no+ * box keeps it read-only). */+ beginTurn(botId: string, threadId: string): void {+ if (!files) return;+ files.endTurn(threadId);+ if (!canEdit(botId) && deps.boxOn()) return;+ const person = deps.askerOf(threadId);+ files.beginTurn(threadId, { bot: botId, ...(person ? { person } : {}) });+ },+ /** After it (turn.completed, or the engine gone): what it changed, as the bot's for that person. */+ onEvent(event: { type: string; threadId: string }): void {+ if (files && (event.type === "turn.completed" || event.type === "session.exited")) files.endTurn(event.threadId);+ },+ };+}++export type TeamFilesHost = ReturnType<typeof createTeamFilesHost>;diff --git a/server/host/team-files.test.ts b/server/host/team-files.test.tsnew file mode 100644index 0000000000..fc10e6fdb4--- /dev/null+++ b/server/host/team-files.test.ts@@ -0,0 +1,163 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Readable } from "node:stream";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { compareSnapshots, createTeamFiles, teamFileName, teamFilePath, TEAM_FILES_ACTIVITY, TEAM_FILES_DIR, TeamFilesError, type TeamFiles } from "./team-files.ts";++const MIRA = { person: "p_mira", admin: false }, BEN = { person: "p_ben", admin: false }, ADA = { person: "p_ada", admin: true };+let dataDir = "", files: TeamFiles, clock = 1_000;+const body = (text: string) => Readable.from([Buffer.from(text)]);+const refused = async (work: () => unknown): Promise<{ status: number; code: string }> => {+ try { await work(); } catch (error) { if (error instanceof TeamFilesError) return { status: error.status, code: error.code }; throw error; }+ throw new Error("not refused");+};++beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), "omb-team-files-"));+ clock = 1_000;+ files = createTeamFiles({ dataDir, now: () => clock, cap: 64, uploadMax: 32 });+});+afterEach(() => rmSync(dataDir, { recursive: true, force: true }));++describe("paths", () => {+ it("takes relative paths and names, and refuses every way out of the folder", () => {+ expect(teamFilePath("")).toBe("");+ expect(teamFilePath("/payroll//nov.csv/")).toBe("payroll/nov.csv");+ expect(teamFilePath("Clients/Acme Ltd/brief.md")).toBe("Clients/Acme Ltd/brief.md");+ for (const bad of ["..", "a/../b", "./a", "a\\b", "a\u0000b", "a\nb", " ", "x".repeat(256), 3, null, `a/${"b/".repeat(600)}`]) {+ expect(teamFilePath(bad), String(bad)).toBeNull();+ }+ expect(teamFileName("nov.csv")).toBe("nov.csv");+ expect(teamFileName("a/b")).toBeNull();+ expect(teamFileName("")).toBeNull();+ });++ it("never follows a link a bot left in the folder", async () => {+ const outside = join(dataDir, "config.json");+ writeFileSync(outside, "secret");+ mkdirSync(join(dataDir, TEAM_FILES_DIR), { recursive: true });+ symlinkSync(outside, join(dataDir, TEAM_FILES_DIR, "config.json"));+ symlinkSync(dataDir, join(dataDir, TEAM_FILES_DIR, "data"));+ expect(await refused(() => files.open("config.json"))).toEqual({ status: 400, code: "link" });+ expect(await refused(() => files.list("data", ADA))).toEqual({ status: 400, code: "link" });+ expect(await refused(() => files.upload("data", "x.txt", body("x"), 1, ADA))).toEqual({ status: 400, code: "link" });+ expect(files.list("", ADA).entries.map((entry) => entry.name)).toEqual([]);+ });+});++describe("the folder", () => {+ it("uploads, lists with who uploaded, opens, renames and deletes", async () => {+ files.folder("payroll", MIRA);+ clock = 2_000;+ const entry = await files.upload("payroll", "nov.csv", body("a,b\n1,2\n"), 8, MIRA);+ expect(entry).toMatchObject({ path: "payroll/nov.csv", kind: "file", size: 8, owner: "p_mira", last: { action: "uploaded", person: "p_mira", at: 2_000 } });+ expect(files.list("", BEN).entries).toMatchObject([{ name: "payroll", kind: "folder", owner: "p_mira", last: { path: "payroll/nov.csv", action: "uploaded" } }]);+ const opened = files.open("payroll/nov.csv");+ expect(opened.size).toBe(8);+ expect(await new Promise<string>((resolve) => { let text = ""; files.stream(opened.fd).on("data", (chunk) => { text += chunk; }).on("end", () => resolve(text)); })).toBe("a,b\n1,2\n");+ files.rename("payroll/nov.csv", "payroll/november.csv", MIRA);+ expect(files.list("payroll", MIRA).entries).toMatchObject([{ name: "november.csv", owner: "p_mira", last: { action: "renamed", from: "payroll/nov.csv" } }]);+ files.remove("payroll/november.csv", MIRA);+ expect(files.list("payroll", MIRA).entries).toEqual([]);+ expect(JSON.parse(readFileSync(join(dataDir, TEAM_FILES_ACTIVITY), "utf8")).changes.map((change: { action: string }) => change.action))+ .toEqual(["folder", "uploaded", "renamed", "deleted"]);+ });++ it("lets a member delete, rename and replace only what they uploaded; an admin anything", async () => {+ await files.upload("", "brief.md", body("hi"), 2, MIRA);+ expect(await refused(() => files.remove("brief.md", BEN))).toEqual({ status: 403, code: "forbidden" });+ expect(await refused(() => files.rename("brief.md", "x.md", BEN))).toEqual({ status: 403, code: "forbidden" });+ expect(await refused(() => files.upload("", "brief.md", body("no"), 2, BEN))).toEqual({ status: 409, code: "exists" });+ await files.upload("", "brief.md", body("v2"), 2, MIRA);+ files.folder("shared", MIRA);+ await files.upload("shared", "ben.txt", body("b"), 1, BEN);+ expect(await refused(() => files.remove("shared", MIRA)), "her folder holds Ben's file").toEqual({ status: 403, code: "forbidden" });+ files.remove("shared", ADA);+ files.remove("brief.md", ADA);+ expect(files.list("", ADA).entries).toEqual([]);+ });++ it("refuses an upload over the per-file limit or past the cap, and keeps nothing of it", async () => {+ expect(await refused(() => files.upload("", "big.bin", body("x".repeat(40)), 40, MIRA))).toEqual({ status: 413, code: "too_large" });+ expect(await refused(() => files.upload("", "big.bin", body("x".repeat(40)), null, MIRA)), "a body longer than it said").toEqual({ status: 413, code: "too_large" });+ await files.upload("", "a.bin", body("x".repeat(30)), 30, MIRA);+ await files.upload("", "b.bin", body("x".repeat(30)), 30, MIRA);+ files.reload();+ expect(await refused(() => files.upload("", "c.bin", body("x".repeat(10)), 10, MIRA))).toEqual({ status: 507, code: "full" });+ expect(files.full()).toBe(false);+ expect(files.list("", MIRA).entries.map((entry) => entry.name)).toEqual(["a.bin", "b.bin"]);+ expect(files.used()).toBe(60);+ });++ it("refuses names that are taken, and a folder into itself", async () => {+ files.folder("a", ADA);+ expect(await refused(() => files.folder("a", ADA))).toEqual({ status: 409, code: "exists" });+ expect(await refused(() => files.rename("a", "a/b", ADA))).toEqual({ status: 400, code: "bad_path" });+ expect(await refused(() => files.upload("missing", "x.txt", body("x"), 1, ADA))).toEqual({ status: 404, code: "not_found" });+ expect(await refused(() => files.open("a"))).toEqual({ status: 400, code: "not_file" });+ });+});++describe("the team's template library", () => {+ it("is the admins' to change; members see it; it counts toward the space used", async () => {+ files.ensure();+ mkdirSync(join(dataDir, TEAM_FILES_DIR, "templates", "reporter"), { recursive: true });+ writeFileSync(join(dataDir, TEAM_FILES_DIR, "templates", "reporter", "bot.yaml"), "name: Reporter\n");+ expect(files.list("templates", MIRA).entries.map((entry) => entry.name)).toEqual(["reporter"]);+ expect(files.mayRemove("templates/reporter", MIRA)).toBe(false);+ expect(files.mayRemove("templates/reporter", ADA)).toBe(true);+ expect(await refused(() => files.upload("templates", "x.yaml", body("x"), 1, MIRA))).toEqual({ status: 403, code: "forbidden" });+ expect(await refused(() => files.folder("templates/mine", MIRA))).toEqual({ status: 403, code: "forbidden" });+ expect(await refused(() => files.remove("templates/reporter", MIRA))).toEqual({ status: 403, code: "forbidden" });+ await files.upload("", "a.md", body("a"), 1, MIRA);+ expect(await refused(() => files.rename("a.md", "templates/a.md", MIRA))).toEqual({ status: 403, code: "forbidden" });+ files.reload();+ expect(files.used()).toBe(1 + "name: Reporter\n".length);+ expect([...files.snapshot()!.keys()], "never a turn's change").toEqual(["a.md"]);+ files.remove("templates/reporter", ADA);+ });+});++describe("a turn's changes", () => {+ const root = () => join(dataDir, TEAM_FILES_DIR);++ it("records what a bot added, changed and deleted, as the bot's for the person it worked for", async () => {+ await files.upload("", "old.csv", body("1"), 1, MIRA);+ writeFileSync(join(root(), "edit.md"), "v1");+ expect(files.beginTurn("t-mira", { bot: "payroll", person: "p_mira" })).toBe(true);+ clock = 5_000;+ writeFileSync(join(root(), "new.csv"), "x");+ writeFileSync(join(root(), "edit.md"), "v2 longer");+ rmSync(join(root(), "old.csv"));+ expect(files.endTurn("t-mira")).toEqual({ added: ["new.csv"], changed: ["edit.md"], deleted: ["old.csv"] });+ expect(files.activity().slice(-3)).toEqual([+ { at: 5_000, path: "new.csv", action: "added", bot: "payroll", person: "p_mira" },+ { at: 5_000, path: "edit.md", action: "changed", bot: "payroll", person: "p_mira" },+ { at: 5_000, path: "old.csv", action: "deleted", bot: "payroll", person: "p_mira" },+ ]);+ expect(files.list("", BEN).entries.find((entry) => entry.name === "new.csv")?.last).toMatchObject({ bot: "payroll", person: "p_mira" });+ expect(files.endTurn("t-mira"), "once").toBeNull();+ });++ it("never claims what the page or another turn changed meanwhile", async () => {+ files.beginTurn("t-mira", { bot: "payroll", person: "p_mira" });+ files.beginTurn("t-ben", { bot: "notes", person: "p_ben" });+ await files.upload("", "uploaded.pdf", body("pdf"), 3, ADA);+ writeFileSync(join(root(), "ben.md"), "b");+ expect(files.endTurn("t-ben")).toEqual({ added: ["ben.md"], changed: [], deleted: [] });+ writeFileSync(join(root(), "mira.md"), "m");+ expect(files.endTurn("t-mira")).toEqual({ added: ["mira.md"], changed: [], deleted: [] });+ expect(files.list("", ADA).entries.find((entry) => entry.name === "uploaded.pdf")?.last).toMatchObject({ action: "uploaded", person: "p_ada" });+ });++ it("compares by size and modification time only", () => {+ files.ensure();+ writeFileSync(join(root(), "a.txt"), "aa");+ const before = files.snapshot()!;+ utimesSync(join(root(), "a.txt"), new Date(5_000_000), new Date(5_000_000));+ expect(compareSnapshots(before, files.snapshot()!)).toEqual({ added: [], changed: ["a.txt"], deleted: [] });+ expect(compareSnapshots(new Map([["x", "1:1"]]), new Map())).toEqual({ added: [], changed: [], deleted: ["x"] });+ });+});diff --git a/server/host/team-files.ts b/server/host/team-files.tsnew file mode 100644index 0000000000..e27bc53dcb--- /dev/null+++ b/server/host/team-files.ts@@ -0,0 +1,440 @@+// Team files: one shared folder per Team Cloud (`team-files/` in the data folder, audience `team`) that every teammate+// and every bot can use: payroll records, client lists, templates, brand assets. People reach it through the Team files+// page (server/routes/team-files.ts); bots through the bot box, where it is at /team-files, read-only unless an admin+// marked the bot "Can edit team files" (server/host/team-box-scope.ts). What changed, and who changed it, is kept in+// `team-files-activity.json`: the page's uploads and deletes as they happen, a bot's writes after each turn that could+// write (a cheap size and time comparison of the folder before and after). Nothing here exists off a Team Cloud.+import { closeSync, constants, createReadStream, createWriteStream, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, type Stats } from "node:fs";+import { randomBytes } from "node:crypto";+import { dirname, join, relative, isAbsolute } from "node:path";+import type { Readable } from "node:stream";+import { Transform } from "node:stream";+import { pipeline } from "node:stream/promises";++import { writeFileAtomic } from "../atomic.ts";++export const TEAM_FILES_DIR = "team-files";+/** The team's library of templates, one folder of Team files (server/team-templates.ts): its admins' to change. */+export const TEAM_FILES_TEMPLATES = "templates";+export const TEAM_FILES_ACTIVITY = "team-files-activity.json";+/** Where every bot's box has the folder. */+export const TEAM_FILES_IN_BOX = "/team-files";+export const TEAM_FILES_CAP_BYTES = 5 * 1024 ** 3;+export const TEAM_FILES_UPLOAD_MAX_BYTES = 100 * 1024 ** 2;+/** A folder with more entries than this is not compared around a turn: its changes go unrecorded rather than slow it. */+export const TEAM_FILES_SNAPSHOT_MAX = 20_000;+const ACTIVITY_MAX = 5_000;+const USAGE_TTL_MS = 10_000;+/** Uploads arrive here first, outside the folder a bot can write (and out of backups, which leave tmp/ out). */+const STAGING = join("tmp", "team-files-uploads");++import type { TeamFileAction } from "../../shared/team-files.ts";+export type { TeamFileAction };++/** One change: who (a person, a bot working for a person, or a bot alone), what and when. */+export interface TeamFileChange {+ at: number;+ path: string;+ action: TeamFileAction;+ /** The person who did it, or the one whose turn the bot was working on. */+ person?: string;+ bot?: string;+ /** A rename's old path. */+ from?: string;+}++interface ActivityFile {+ changes: TeamFileChange[];+ /** Who uploaded each file or made each folder through the page: they (and the admins) may delete it. */+ owners: Record<string, string>;+}++export interface TeamFileEntry {+ name: string;+ path: string;+ kind: "file" | "folder";+ size: number;+ modifiedAt: number;+ /** The last change recorded for it, if any. */+ last?: TeamFileChange;+ owner?: string;+}++export interface TeamFilesActor { person: string; admin: boolean }++export class TeamFilesError extends Error {+ readonly status: number;+ readonly code: string;+ constructor(status: number, code: string, message: string) {+ super(message);+ this.status = status;+ this.code = code;+ }+}++const SEGMENT_MAX = 255, PATH_MAX = 1024;+// Control characters and the separators of other systems never name a team file.+// eslint-disable-next-line no-control-regex+const BAD_CHARS = /[\u0000-\u001f\u007f\\]/;++/** A path in the folder as the routes take it: relative, "/"-separated, no `.` or `..` part, no control characters. "" is+ * the folder itself; null is refused. Leading, trailing and doubled slashes are dropped. */+export function teamFilePath(input: unknown): string | null {+ if (typeof input !== "string" || input.length > PATH_MAX || BAD_CHARS.test(input)) return null;+ const parts = input.split("/").filter((part) => part !== "");+ if (parts.some((part) => part === "." || part === ".." || part.length > SEGMENT_MAX || part.trim() === "")) return null;+ return parts.join("/");+}++/** One name inside a folder (an upload's, a new folder's). */+export function teamFileName(input: unknown): string | null {+ const path = teamFilePath(input);+ return path && !path.includes("/") ? path : null;+}++/** The folder's files by path, as size and modification time: what a turn's before and after are compared by. */+export type TeamFilesSnapshot = Map<string, string>;++export interface TeamFilesChanges { added: string[]; changed: string[]; deleted: string[] }++export function compareSnapshots(before: TeamFilesSnapshot, after: TeamFilesSnapshot): TeamFilesChanges {+ const added: string[] = [], changed: string[] = [], deleted: string[] = [];+ for (const [path, mark] of after) {+ const was = before.get(path);+ if (was === undefined) added.push(path);+ else if (was !== mark) changed.push(path);+ }+ for (const path of before.keys()) if (!after.has(path)) deleted.push(path);+ return { added: added.sort(), changed: changed.sort(), deleted: deleted.sort() };+}++const inside = (path: string, folder: string) => path === folder || path.startsWith(`${folder}/`);++export interface TeamFilesOptions {+ dataDir: string;+ now?: () => number;+ cap?: number;+ uploadMax?: number;+}++export function createTeamFiles(options: TeamFilesOptions) {+ const root = join(options.dataDir, TEAM_FILES_DIR);+ const activityPath = join(options.dataDir, TEAM_FILES_ACTIVITY);+ const now = options.now ?? Date.now;+ const cap = options.cap ?? TEAM_FILES_CAP_BYTES;+ const uploadMax = options.uploadMax ?? TEAM_FILES_UPLOAD_MAX_BYTES;+ let usage: { bytes: number; at: number } | null = null;+ let activity: ActivityFile | null = null;++ const ensure = (): string => {+ mkdirSync(root, { recursive: true, mode: 0o700 });+ return root;+ };++ /** The full path of `rel`, refusing a link anywhere on the way (a bot with edit could plant one) and a non-folder parent. */+ const resolve = (rel: string, want: "file" | "folder" | "any" | "absent" | "maybe"): { full: string; stat: Stats | null } => {+ ensure();+ const parts = rel ? rel.split("/") : [];+ let full = root;+ let stat: Stats | null = lstatSync(root);+ for (let i = 0; i < parts.length; i++) {+ if (!stat?.isDirectory()) throw new TeamFilesError(404, "not_found", "That folder doesn't exist.");+ full = join(full, parts[i]!);+ try { stat = lstatSync(full); } catch { stat = null; }+ if (stat?.isSymbolicLink()) throw new TeamFilesError(400, "link", "Team files never follow links.");+ if (!stat && i < parts.length - 1) throw new TeamFilesError(404, "not_found", "That folder doesn't exist.");+ }+ if (want === "absent" && stat) throw new TeamFilesError(409, "exists", "Something with that name is already there.");+ if ((want === "file" || want === "folder" || want === "any") && !stat) throw new TeamFilesError(404, "not_found", "That file doesn't exist any more.");+ if (want === "file" && !stat!.isFile()) throw new TeamFilesError(400, "not_file", "That is a folder, not a file.");+ if (want === "folder" && !stat!.isDirectory()) throw new TeamFilesError(400, "not_folder", "That is a file, not a folder.");+ return { full, stat };+ };++ /** The real place of `full` (and of its folder) is inside the folder: nothing on the way was swapped for a link. */+ const within = (full: string): boolean => {+ try {+ const rel = relative(realpathSync(root), realpathSync(full));+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));+ } catch {+ return false;+ }+ };+ const settledParent = (full: string) => {+ if (!within(dirname(full))) throw new TeamFilesError(400, "link", "Team files never follow links.");+ };++ /** Turns that could write the folder, by key, with the folder as it was when each started. */+ const open = new Map<string, { before: TeamFilesSnapshot; by: { bot: string; person?: string } }>();+ /** A change someone else made (the page, another turn) is never claimed by a turn still open. */+ const settle = (paths: readonly string[]) => {+ if (!open.size || !paths.length) return;+ for (const path of paths) {+ let mark: string | null = null;+ try { const stat = lstatSync(join(root, path)); if (stat.isFile()) mark = `${stat.size}:${Math.round(stat.mtimeMs)}`; } catch {}+ for (const turn of open.values()) {+ for (const known of turn.before.keys()) if (known !== path && inside(known, path) && mark === null) turn.before.delete(known);+ if (mark === null) turn.before.delete(path); else turn.before.set(path, mark);+ }+ }+ };++ /** Every regular file under the folder, by path; null when there are more than `max` (too large to compare cheaply). */+ const walk = (max = Number.POSITIVE_INFINITY, countAll = true): { files: Map<string, Stats>; bytes: number } | null => {+ ensure();+ const files = new Map<string, Stats>();+ let bytes = 0, seen = 0;+ const stack: string[] = [""];+ while (stack.length) {+ const rel = stack.pop()!;+ let names: string[];+ try { names = readdirSync(rel ? join(root, rel) : root); } catch { continue; }+ for (const name of names) {+ if (++seen > max) return null;+ const path = rel ? `${rel}/${name}` : name;+ if (!countAll && path === TEAM_FILES_TEMPLATES) continue;+ let stat: Stats;+ try { stat = lstatSync(join(root, path)); } catch { continue; }+ if (stat.isDirectory()) stack.push(path);+ else if (stat.isFile()) { files.set(path, stat); bytes += stat.size; }+ }+ }+ return { files, bytes };+ };++ /** The folder's files as they are now, or null when it is too large to compare. */+ const snapshot = (): TeamFilesSnapshot | null => {+ // The template library is no turn's to change (read-only in every box) and keeps its own record of who added what.+ const walked = walk(TEAM_FILES_SNAPSHOT_MAX, false);+ if (!walked) return null;+ return new Map([...walked.files].map(([path, stat]) => [path, `${stat.size}:${Math.round(stat.mtimeMs)}`]));+ };++ const used = (): number => {+ if (usage && now() - usage.at < USAGE_TTL_MS) return usage.bytes;+ usage = { bytes: walk()?.bytes ?? 0, at: now() };+ return usage.bytes;+ };+ const changedSize = () => { usage = null; };++ const readActivity = (): ActivityFile => {+ if (activity) return activity;+ try {+ const parsed = JSON.parse(readFileSync(activityPath, "utf8")) as Partial<ActivityFile>;+ activity = { changes: Array.isArray(parsed.changes) ? parsed.changes.filter((change) => change && typeof change.path === "string") : [], owners: parsed.owners && typeof parsed.owners === "object" ? parsed.owners : {} };+ } catch {+ activity = { changes: [], owners: {} };+ }+ return activity;+ };+ const saveActivity = () => {+ const file = readActivity();+ if (file.changes.length > ACTIVITY_MAX) file.changes.splice(0, file.changes.length - ACTIVITY_MAX);+ writeFileAtomic(activityPath, `${JSON.stringify(file)}\n`, { mode: 0o600 });+ };+ const record = (changes: TeamFileChange[]) => {+ if (!changes.length) return;+ readActivity().changes.push(...changes);+ saveActivity();+ };+ /** The last recorded change of each path: a file's own, a folder's latest of anything in it. */+ const lastChanges = (): Map<string, TeamFileChange> => {+ const last = new Map<string, TeamFileChange>();+ for (const change of readActivity().changes) last.set(change.path, change);+ return last;+ };++ /** The template library is the admins': members see it, only an admin changes anything in it. */+ const librarys = (rel: string) => inside(rel, TEAM_FILES_TEMPLATES);+ const mayAdd = (folder: string, actor: TeamFilesActor) => {+ if (!actor.admin && librarys(folder)) throw new TeamFilesError(403, "forbidden", "The team's templates are the admins' to change.");+ };+ const mayRemove = (rel: string, actor: TeamFilesActor): boolean => {+ if (actor.admin) return true;+ if (librarys(rel)) return false;+ const owners = readActivity().owners;+ return owners[rel] === actor.person;+ };++ return {+ root: () => root,+ ensure,+ cap,+ uploadMax,+ used,+ /** Full: a bot's box has the folder read-only, and the page refuses uploads, until someone removes files. */+ full: () => used() >= cap,++ list(rel: string, actor: TeamFilesActor): { entries: TeamFileEntry[] } {+ const { full } = resolve(rel, "folder");+ const last = lastChanges();+ const owners = readActivity().owners;+ const entries: TeamFileEntry[] = [];+ for (const name of readdirSync(full)) {+ const path = rel ? `${rel}/${name}` : name;+ let stat: Stats;+ try { stat = lstatSync(join(full, name)); } catch { continue; }+ if (!stat.isFile() && !stat.isDirectory()) continue;+ const kind = stat.isDirectory() ? "folder" as const : "file" as const;+ let latest = last.get(path);+ if (kind === "folder") for (const [changed, change] of last) if (changed.startsWith(`${path}/`) && (!latest || change.at > latest.at)) latest = change;+ entries.push({ name, path, kind, size: kind === "file" ? stat.size : 0, modifiedAt: Math.round(stat.mtimeMs), ...(latest ? { last: latest } : {}), ...(owners[path] ? { owner: owners[path] } : {}) });+ }+ void actor;+ entries.sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "folder" ? -1 : 1));+ return { entries };+ },++ mayRemove,++ /** A file to read, by path, opened without following a link and checked to be the one inside the folder. The caller+ * streams it (`stream`) and so closes the descriptor. */+ open(rel: string): { fd: number; size: number; name: string } {+ const { full } = resolve(rel, "file");+ const fd = openSync(full, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const stat = fstatSync(fd);+ if (!stat.isFile() || !within(full)) throw new TeamFilesError(400, "link", "Team files never follow links.");+ return { fd, size: stat.size, name: rel.split("/").at(-1)! };+ } catch (error) {+ closeSync(fd);+ throw error;+ }+ },++ stream(fd: number): Readable { return createReadStream("", { fd }); },++ /** One file into `folder` from a request body; replaces a file of the same name only for its uploader or an admin. */+ async upload(folder: string, name: string, body: Readable, declared: number | null, actor: TeamFilesActor): Promise<TeamFileEntry> {+ resolve(folder, "folder");+ const path = folder ? `${folder}/${name}` : name;+ mayAdd(path, actor);+ const target = resolve(path, "maybe");+ if (target.stat?.isDirectory()) throw new TeamFilesError(409, "exists", "A folder with that name is already there.");+ if (target.stat && !mayRemove(path, actor)) throw new TeamFilesError(409, "exists", "A file with that name is already there, and it isn't yours to replace.");+ if (declared !== null && declared > uploadMax) throw new TeamFilesError(413, "too_large", `A file may be at most ${Math.round(uploadMax / 1024 ** 2)} MB.`);+ const room = cap - used() + (target.stat?.size ?? 0);+ if (room <= 0 || (declared !== null && declared > room)) throw new TeamFilesError(507, "full", `Team files are full (${Math.round(cap / 1024 ** 3)} GB). Remove files to make room.`);+ const staging = join(options.dataDir, STAGING);+ mkdirSync(staging, { recursive: true, mode: 0o700 });+ const temp = join(staging, `${randomBytes(8).toString("hex")}.part`);+ let taken = 0;+ const limit = Math.min(uploadMax, room);+ const capped = new Transform({ transform(chunk: Buffer, _encoding, done) { taken += chunk.length; done(taken > limit ? new TeamFilesError(taken > uploadMax ? 413 : 507, "too_large", "") : null, chunk); } });+ try {+ await pipeline(body, capped, createWriteStream(temp, { mode: 0o600 }));+ } catch (error) {+ rmSync(temp, { force: true });+ if (taken > uploadMax) throw new TeamFilesError(413, "too_large", `A file may be at most ${Math.round(uploadMax / 1024 ** 2)} MB.`);+ if (taken > limit) throw new TeamFilesError(507, "full", `Team files are full (${Math.round(cap / 1024 ** 3)} GB). Remove files to make room.`);+ throw error instanceof TeamFilesError ? error : new TeamFilesError(400, "incomplete", "The file did not arrive whole.");+ }+ // Checked again just before it lands: the folder may have changed while the file arrived.+ const again = resolve(path, "maybe");+ if (again.stat?.isDirectory()) { rmSync(temp, { force: true }); throw new TeamFilesError(409, "exists", "A folder with that name is already there."); }+ try { settledParent(again.full); } catch (error) { rmSync(temp, { force: true }); throw error; }+ renameSync(temp, again.full);+ changedSize();+ const file = readActivity();+ file.owners[path] = actor.person;+ record([{ at: now(), path, action: "uploaded", person: actor.person }]);+ settle([path]);+ const stat = statSync(again.full);+ return { name, path, kind: "file", size: stat.size, modifiedAt: Math.round(stat.mtimeMs), owner: actor.person, last: file.changes.at(-1)! };+ },++ folder(rel: string, actor: TeamFilesActor): void {+ if (!rel) throw new TeamFilesError(400, "bad_path", "Name the new folder.");+ mayAdd(rel, actor);+ const { full } = resolve(rel, "absent");+ settledParent(full);+ mkdirSync(full, { mode: 0o700 });+ readActivity().owners[rel] = actor.person;+ record([{ at: now(), path: rel, action: "folder", person: actor.person }]);+ },++ rename(from: string, to: string, actor: TeamFilesActor): void {+ if (!from || !to) throw new TeamFilesError(400, "bad_path", "Name the file and its new name.");+ if (inside(to, from)) throw new TeamFilesError(400, "bad_path", "A folder can't go inside itself.");+ const source = resolve(from, "any");+ if (!mayRemove(from, actor)) throw new TeamFilesError(403, "forbidden", "Only an admin, or whoever uploaded it, can rename this.");+ mayAdd(to, actor);+ if (dirname(to) !== "." && dirname(to) !== "") resolve(dirname(to), "folder");+ const target = resolve(to, "absent");+ settledParent(source.full);+ settledParent(target.full);+ const moved = source.stat!.isDirectory() ? [...(walk()?.files.keys() ?? [])].filter((path) => inside(path, from)) : [from];+ renameSync(source.full, target.full);+ settle([...moved, ...moved.map((path) => `${to}${path.slice(from.length)}`)]);+ const owners = readActivity().owners;+ for (const path of Object.keys(owners)) {+ if (inside(path, from)) { owners[`${to}${path.slice(from.length)}`] = owners[path]!; delete owners[path]; }+ }+ record([{ at: now(), path: to, from, action: "renamed", person: actor.person }]);+ },++ remove(rel: string, actor: TeamFilesActor): void {+ if (!rel) throw new TeamFilesError(400, "bad_path", "Name what to delete.");+ const { full, stat } = resolve(rel, "any");+ if (!mayRemove(rel, actor)) throw new TeamFilesError(403, "forbidden", "Only an admin, or whoever uploaded it, can delete this.");+ const owners = readActivity().owners;+ if (stat!.isDirectory() && !actor.admin) {+ // A member's own folder goes only when everything in it is theirs too.+ const others = [...(walk()?.files.keys() ?? [])].filter((path) => inside(path, rel) && owners[path] !== actor.person);+ if (others.length) throw new TeamFilesError(403, "forbidden", "That folder has other people's files in it: only an admin can delete it.");+ }+ settledParent(full);+ const gone = stat!.isDirectory() ? [...(walk()?.files.keys() ?? [])].filter((path) => inside(path, rel)) : [rel];+ rmSync(full, { recursive: true, force: true });+ settle(gone);+ changedSize();+ for (const path of Object.keys(owners)) if (inside(path, rel)) delete owners[path];+ record([{ at: now(), path: rel, action: "deleted", person: actor.person }]);+ },++ snapshot,++ /** A turn that could write starts: the folder as it is now, to compare with when it ends. False when the folder is+ * too large to compare. */+ beginTurn(key: string, by: { bot: string; person?: string }): boolean {+ const before = snapshot();+ if (before) open.set(key, { before, by }); else open.delete(key);+ return before !== null;+ },++ /** The turn ended: what it changed, recorded as the bot's for the person it worked for. */+ endTurn(key: string): TeamFilesChanges | null {+ const turn = open.get(key);+ open.delete(key);+ if (!turn) return null;+ const { before, by } = turn;+ const after = snapshot();+ if (!after) return null;+ const changes = compareSnapshots(before, after);+ const at = now();+ const who = { bot: by.bot, ...(by.person ? { person: by.person } : {}) };+ const rows: TeamFileChange[] = [+ ...changes.added.map((path) => ({ at, path, action: "added" as const, ...who })),+ ...changes.changed.map((path) => ({ at, path, action: "changed" as const, ...who })),+ ...changes.deleted.map((path) => ({ at, path, action: "deleted" as const, ...who })),+ ];+ if (rows.length) {+ const owners = readActivity().owners;+ for (const path of changes.deleted) delete owners[path];+ changedSize();+ record(rows);+ settle(rows.map((row) => row.path));+ }+ return changes;+ },++ activity(): readonly TeamFileChange[] { return readActivity().changes; },+ /** For tests and a restore: forget what was read, so the file on disk is read again. */+ reload(): void { activity = null; usage = null; },+ exists: () => existsSync(root),+ /** Turns still open, for tests. */+ openTurns: () => open.size,+ };+}++export type TeamFiles = ReturnType<typeof createTeamFiles>;diff --git a/server/host/team-member-left.ts b/server/host/team-member-left.tsindex 04be809850..30fcd51ff7 100644--- a/server/host/team-member-left.ts+++ b/server/host/team-member-left.ts@@ -9,6 +9,8 @@// restores nothing, and one admin activity row says who left, in counts. The Admin tells this machine with a signed// request (`POST /api/cloud/team/member-left`, cloud-signed.ts).//+// Team files (team-files/, host/team-files.ts) are the team's: what they uploaded, or had a bot write there, stays.+//// Each conversation keeps its starter (thread-starters.json, a hash): what other records still name it (a decision's// row, a usage trace) stays someone else's, so no admin ever reads it there either.import { existsSync, readdirSync, rmSync } from "node:fs";diff --git a/server/index.ts b/server/index.tsindex d0fa5c8057..b684a1bf05 100644--- a/server/index.ts+++ b/server/index.ts@@ -278,7 +278,7 @@ import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachmeimport { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment } from "./host/delete-leftovers.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft, memoryLayerRecords } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createWokeNotifier } from "./cloud-woke.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";-import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createPersonNames } from "./host/person-names.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";+import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { createTeamFilesHost } from "./host/team-files-host.ts"; import { createTeamFilesRoutes } from "./routes/team-files.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createPersonNames } from "./host/person-names.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";import { createCloudMoveRoutes } from "./cloud-move-http.ts";import { RESTART_EXIT_CODE } from "./restart.ts"; import { installCrashGuard, SERVER_ERROR_CAUSE } from "./crash-guard.ts"; import { markRequestArrival } from "./perf/loop-stalls.ts"; import { createThreadMaps, keepThreadEntry } from "./host/thread-maps.ts"; import { botLimitRefusal } from "./bot-limit.ts";import { applyIncludedXMessage, holdIncludedServices, hostingCredential, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { applyPhoneLinkMessage, phoneLinkPart } from "./phone-link.ts"; import { createResearchAvailability } from "./research.ts";@@ -950,8 +950,8 @@ const CLOUD_OWNER_KEY = CLOUD_PERSONAL ? `p_${createHash("sha256").update(`cloud/** Settled at boot once routines load (settleCloudHome); only `proven` feeds lending and memory. */let cloudEarlierOwners: Pick<CloudOwnership, "adopted" | "proven"> = { adopted: new Set(), proven: new Set() };/** Until it is settled, a Cloud home counts as shared. */-let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHost = createCloudTeamHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, store: { groupByThread: (threadId) => store.groupByThread(threadId), get bots() { return store.bots; } }, engineHomes, box: botBox, starters: threadStarters, shares: conversationShares, markers: new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]), language: appLanguage,- serverProfile: { read: () => cfg.profile, clear: () => { adminActorScope.exit(() => saveConfig({ profile: { name: "", email: "", aboutMe: "", avatarUrl: "" } })); Object.assign(cfg, loadConfig()); } } }); const vaultReaders = createVaultReaders({ team: CLOUD_TEAM !== null, audienceOf: (threadId) => teamHost.audienceOf(threadId), personOf: actorKey });+let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHost = createCloudTeamHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, store: { groupByThread: (threadId) => store.groupByThread(threadId), get bots() { return store.bots; } }, engineHomes, box: botBox, teamFiles: (botId) => teamFilesHost.boxFolder(botId), starters: threadStarters, shares: conversationShares, markers: new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]), language: appLanguage,+ serverProfile: { read: () => cfg.profile, clear: () => { adminActorScope.exit(() => saveConfig({ profile: { name: "", email: "", aboutMe: "", avatarUrl: "" } })); Object.assign(cfg, loadConfig()); } } }); const teamFilesHost = createTeamFilesHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, bots: () => store.bots, boxOn: () => botBox.enabled(), askerOf: (threadId) => runOwners.asker(threadId)?.person ?? teamHost.ownerOf(threadId) }); const vaultReaders = createVaultReaders({ team: CLOUD_TEAM !== null, audienceOf: (threadId) => teamHost.audienceOf(threadId), personOf: actorKey });const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters }); const mausbotOwnChat = createMausBotOwnChat({ bots: () => store.bots, starters: threadStarters, personKey: (email) => personKey({ id: "", email }), moveNotes: (from, to, person) => moveMemoryLayer(from, to, personLanguages.forLine(person)) });const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR, (person) => { botOrders?.forgetPerson(person); forgetNotificationReader(person); }) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast, shared: (threadId) => teamHost.privateTo(threadId) === null || conversationShares.readers(threadId) !== null, wireBot: (botId) => { const bot = store.bot(botId); return bot ? wireBot(bot) : null; } });const botOrders = CLOUD_TEAM ? createPersonBotOrder(DATA_DIR) : null; const teamRoutines = createTeamRoutines({ team: Boolean(CLOUD_TEAM), privateTo: teamHost.privateTo, task: (botId, threadId) => store.taskByThread(botId, threadId), routines: () => routines, authors: cloudRoutineAuthors, withWriter: withRoutineWriter, ownBot: (botId) => { const person = store.bot(botId)?.defaultBot?.person; return person ? personKey({ id: "", email: person }) : null; }, tasks: (botId) => store.tasks(botId), threadRefusal: cloudThreadRefusal, openChat: (botId, title, person) => { const threadId = store.createTask(botId, title, false)?.threadId; if (threadId) threadStarters.set(threadId, person); return threadId; } });@@ -7079,7 +7079,7 @@ const repeats = createUnattendedTurns({bus.subscribe((event: RuntimeEvent) => { if (!shouldIgnoreProviderEvent(event)) repeats.onEvent(event); });const personFirst = createPersonFirst({ firstMs: Number(process.env.OMB_PERSON_FIRST_MS) || undefined, waiting: (threadId) => watchdog.waiting(threadId) || activeRoutineRunForThread(threadId) !== null,stop: async (threadId, line) => { const bot = store.botByThread(threadId); if (!bot) return; store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: line, ok: true } }); turnStops.stopping(threadId, liveTurnByThread.get(threadId), line); await interruptDirectThread(bot.id, threadId, line); } });-bus.subscribe((event: RuntimeEvent) => { if (!shouldIgnoreProviderEvent(event)) personFirst.onEvent(event); }); const runOwners = createRunOwners({ shared: (threadId) => CLOUD_TEAM !== null && audienceMember(teamHost.audienceOf(threadId)) === null, directRequest: (threadId) => directRequestOwners.get(threadId), roomRequestMessageId: (threadId) => [...(groupTurnOperations.get(store.groupByThread(threadId)?.id ?? "") ?? [])].find((operation) => operation.threadId === threadId && !operation.cancelled && operation.requestMessageId)?.requestMessageId, isRoom: (threadId) => Boolean(store.groupByThread(threadId)), messages: (threadId) => store.messagesFor(threadId), personName: (person) => teamHost.personName(person), language: threadLanguage }), runActor = (auth: RequestAuth) => runActorOf(auth, actorKey);+bus.subscribe((event: RuntimeEvent) => { if (!shouldIgnoreProviderEvent(event)) { personFirst.onEvent(event); teamFilesHost.onEvent(event); } }); const runOwners = createRunOwners({ shared: (threadId) => CLOUD_TEAM !== null && audienceMember(teamHost.audienceOf(threadId)) === null, directRequest: (threadId) => directRequestOwners.get(threadId), roomRequestMessageId: (threadId) => [...(groupTurnOperations.get(store.groupByThread(threadId)?.id ?? "") ?? [])].find((operation) => operation.threadId === threadId && !operation.cancelled && operation.requestMessageId)?.requestMessageId, isRoom: (threadId) => Boolean(store.groupByThread(threadId)), messages: (threadId) => store.messagesFor(threadId), personName: (person) => teamHost.personName(person), language: threadLanguage }), runActor = (auth: RequestAuth) => runActorOf(auth, actorKey);// A first reply that never comes gets one notice with a way out (server/first-reply-rescue.ts), on listeners of their own.const firstReplyRescue = createFirstReplyRescue({ store, botForThread, speaker: (threadId) => groupSpeakers.get(threadId), runningEngine: (threadId) => runningTurnEngines.get(threadId)?.instanceId,engineName: (instanceId) => engineName(instanceId), quiet: (threadId) => isInternalTurn(threadId) || activeRoutineRunForThread(threadId) !== null,@@ -7890,7 +7890,7 @@ async function beginTurn(if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) throw new DirectTurnSetupCancelled("turn stopped while its tools were prepared"); const worksInWorkspace = supportsWorkspaceFiles(instance.driverKind);if (worksInWorkspace) {ensureWorkspace(bot.id, appLanguage());- if (bot.memoryEnabled !== false) beginMemoryTurn(teamHost.layer(bot.id, threadId), threadId); botBox.lend(bot.id, threadId, teamHost.layerDirs(bot.id, threadId));+ if (bot.memoryEnabled !== false) beginMemoryTurn(teamHost.layer(bot.id, threadId), threadId); botBox.lend(bot.id, threadId, teamHost.layerDirs(bot.id, threadId)); teamFilesHost.beginTurn(bot.id, threadId);}const privateWorkspace = worksInWorkspace ? ensureTaskWorkspaceWithSkills(bot.id, threadId, skillsHost.turnImports(bot, threadId, instance)) : undefined;const skillInstructions = renderSkillInstructions(selectedSkills, {@@ -8335,7 +8335,7 @@ async function beginTurn(cwd: liveBot?.cwd ?? bot.cwd,connectedApps: setupConnectedApps(bot, instance.adapter.capabilities.composioMcp === true, Boolean(integrations.composio)),}) },- { id: "files", label: "File locations", text: worksInWorkspace ? workspaceLocationsPrompt(bot.id, cwd, liveBot?.cwd ?? bot.cwd, { attachFile: Boolean(integrations.agents) && !CLOUD_HOME && !HOSTED_WORKSPACE }) : "" },+ { id: "files", label: "File locations", text: worksInWorkspace ? workspaceLocationsPrompt(bot.id, cwd, liveBot?.cwd ?? bot.cwd, { attachFile: Boolean(integrations.agents) && !CLOUD_HOME && !HOSTED_WORKSPACE }) + teamFilesHost.promptLine(bot.id) : "" },{ id: "shell", label: "Long-running commands", text: worksInWorkspace ? longCommandsPrompt(computerPromptKind) : "" },{ id: "computer", label: "Computer", text: computerPrompt(computerPromptKind) },{ id: "team-computer", label: "Team computer", text: teamComputerPrompt(teamComputer) },@@ -9473,7 +9473,7 @@ const webhookIngressStatus = () => ({baseUrl: webhookIngress?.baseUrl ?? `http://127.0.0.1:${WEBHOOK_PORT}`,...(webhookIngressError ? { error: webhookIngressError } : {}),});-ROUTES.push(createWebhookRoutes({ webhooks, ingress: webhookIngressStatus, visible: (auth) => visibleTo(viewerFor(auth)) }), botApi.routes);+ROUTES.push(createTeamFilesRoutes({ files: teamFilesHost.files, actor: (auth) => auth.kind === "session" && auth.session.email ? { person: personKey(auth.session), admin: auth.scopes.includes("admin") } : null, personName: (person) => teamHost.personName(person), botName: (botId) => store.bot(botId)?.name })); ROUTES.push(createWebhookRoutes({ webhooks, ingress: webhookIngressStatus, visible: (auth) => visibleTo(viewerFor(auth)) }), botApi.routes);const RUNTIME_KEEP_MS = 30 * 24 * 60 * 60_000;let runtimePrunedAt = 0;@@ -10086,7 +10086,7 @@ async function runClaimedGroupMemberTurn(const cwd = workspace && cloudGuestOpened(threadId)? ensureTaskWorkspaceWithSkills(bot.id, threadId, skillsHost.turnImports(bot, threadId, instance)): groupTurnCwd(workspace, () => store.pinGroupCwd(readyGroup.id, threadId));- assertRoomFolder(cwd); if (workspace && bot.memoryEnabled !== false) beginMemoryTurn(teamHost.layer(bot.id, threadId), threadId); if (workspace) botBox.lend(bot.id, threadId, teamHost.layerDirs(bot.id, threadId));+ assertRoomFolder(cwd); if (workspace && bot.memoryEnabled !== false) beginMemoryTurn(teamHost.layer(bot.id, threadId), threadId); if (workspace) { botBox.lend(bot.id, threadId, teamHost.layerDirs(bot.id, threadId)); teamFilesHost.beginTurn(bot.id, threadId); }{const drift = checkSoulDrift(bot.id, bot.soul ?? "", bot.soulHash ?? "");if (drift.drift !== Boolean(bot.soulDrift)) store.patchBot(bot.id, { soulDrift: drift.drift });@@ -10114,7 +10114,7 @@ async function runClaimedGroupMemberTurn(applyAgentsBridge(threadId, integrations, cfg, bot, turnEngine(instance, providerConfigs(), registry.lastSnapshot(instance.instanceId), cwd));const roomSystem = buildSystemPrompt(system, store.bot(bot.id)?.soul ?? bot.soul ?? "", [{ id: "user-profile", label: "About the user", text: userProfileSystemPrompt(teamHost.profileFor(threadId, cfg.profile)) }, { id: "people", label: "People", text: teamMessages.prompt(bot.id, threadId, Boolean(integrations.agents)) },- { id: "files", label: "File locations", text: workspace ? workspaceLocationsPrompt(bot.id, cwd, readyBot.cwd, { attachFile: Boolean(integrations.agents) && !CLOUD_HOME && !HOSTED_WORKSPACE }) : "" },+ { id: "files", label: "File locations", text: workspace ? workspaceLocationsPrompt(bot.id, cwd, readyBot.cwd, { attachFile: Boolean(integrations.agents) && !CLOUD_HOME && !HOSTED_WORKSPACE }) + teamFilesHost.promptLine(bot.id) : "" },{ id: "shell", label: "Long-running commands", text: workspace ? longCommandsPrompt(roomComputerPromptKind) : "" },{ id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) + teamConnections.prompt(threadId, internalGeneration, integrations) },{ id: "computer", label: "Computer", text: computerPrompt(roomComputerPromptKind) },diff --git a/server/procs.ts b/server/procs.tsindex 0885713a87..324463746d 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -265,8 +265,16 @@ export function boxedSpawn(resolved: ResolvedSpawn, opts: CliSpawnOptions, ownerif (opts.box === false || (owner !== "bot" && !opts.box)) return null;const request = typeof opts.box === "object" ? opts.box : {};const home = homed ? { home: homed.home, shared: homed.shared } : {};- const threadId = engineHomes.thread();- return botBox.wrap({ command: resolved.command, args: resolved.args, cwd: typeof opts.cwd === "string" ? opts.cwd : undefined, env: opts.env ?? process.env, ...(threadId ? { threadId } : {}), ...request, ...home });+ const threadId = engineHomes.thread(), conversationBot = engineHomes.bot();+ return botBox.wrap({ command: resolved.command, args: resolved.args, cwd: typeof opts.cwd === "string" ? opts.cwd : undefined, env: opts.env ?? process.env, ...(threadId ? { threadId } : {}), ...(conversationBot ? { conversationBot } : {}), ...request, ...home });+}++/** What the audience rule gives a box in `cwd` now, as a key (null off a team or with the box off): a process kept+ * between turns is started again when it changes, such as a bot's "Can edit team files". */+export function boxAudienceKey(cwd: string): string | null {+ if (!botBox.enabled()) return null;+ const threadId = engineHomes.thread(), conversationBot = engineHomes.bot();+ return botBox.audienceKey({ cwd, ...(threadId ? { threadId } : {}), ...(conversationBot ? { conversationBot } : {}) });}/** What a process several conversations share must be boxed with to serve `cwd` (null with the box off): all of the bot's@@ -276,8 +284,8 @@ export function sharedBoxScope(cwd: string): string | null {if (!botBox.enabled()) return null;const parent = dirname(resolve(cwd));if (basename(dirname(parent)) !== "task-workspaces") return resolve(cwd);- const threadId = engineHomes.thread();- const threads = botBox.sharedThreadsKey({ cwd, ...(threadId ? { threadId } : {}) });+ const threadId = engineHomes.thread(), conversationBot = engineHomes.bot();+ const threads = botBox.sharedThreadsKey({ cwd, ...(threadId ? { threadId } : {}), ...(conversationBot ? { conversationBot } : {}) });return threads ? `${parent}#${createHash("sha256").update(threads).digest("hex").slice(0, 16)}` : parent;}diff --git a/server/request-auth.ts b/server/request-auth.tsindex 742395973e..b976462311 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -493,6 +493,11 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg// what the viewer's own bots put online, from conversations they can read; the handler deletes only what is theirs{ methods: ["GET"], path: /^\/api\/published-apps(?:\/framing)?$/ },{ methods: ["POST"], path: /^\/api\/published-apps\/delete$/ },+ // a Team Cloud's shared folder: every member reads and adds; the handler lets a member delete or rename only what they+ // uploaded (routes/team-files.ts); off a Team Cloud they answer 404+ { methods: ["GET"], path: /^\/api\/team-files(?:\/file)?$/ },+ { methods: ["PUT"], path: /^\/api\/team-files\/file$/ },+ { methods: ["POST"], path: /^\/api\/team-files\/(?:folder|rename|delete)$/ },// Slack for Clouds: the Admin calls these with the member's own session, and the handler answers each as that member// alone, on a personal Cloud its owner alone (routes/team-slack.ts); off a Cloud they answer 404{ methods: ["GET"], path: /^\/api\/slack\/team\/bots$/ },diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex db91dadff4..b36ecaffe8 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -307,6 +307,11 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {if (typeof body.xResearch !== "boolean") return json(res, 400, { error: "xResearch must be true or false" });patch.xResearch = body.xResearch;}+ // Lets the bot write the Team Cloud's shared folder from every chat, members' private ones too: an admin decision.+ if (body.teamFilesEdit !== undefined) {+ if (typeof body.teamFilesEdit !== "boolean") return json(res, 400, { error: "teamFilesEdit must be true or false" });+ patch.teamFilesEdit = body.teamFilesEdit || undefined;+ }if (body.toolsOff !== undefined) {const toolsOff = body.toolsOff === null ? [] : parseToolsOff(body.toolsOff);if (!toolsOff) return json(res, 400, { error: `toolsOff must be a list of ${TOOL_GROUPS.join(", ")}` });diff --git a/server/routes/team-files.ts b/server/routes/team-files.tsnew file mode 100644index 0000000000..b74d68002e--- /dev/null+++ b/server/routes/team-files.ts@@ -0,0 +1,126 @@+// Team files' routes, for every member and admin of a Team Cloud (server/host/team-files.ts). Off a Team Cloud none of+// them exists: they answer 404 like any unknown path.+// GET /api/team-files?path=<folder> the folder's entries, who changed each last, the space used and the caps+// GET /api/team-files/file?path=<file> the file (?download=1 always as an attachment)+// PUT /api/team-files/file?path=<folder>&name= an upload, the request body as is (at most 100 MB)+// POST /api/team-files/folder {path} a new folder+// POST /api/team-files/rename {from, to}+// POST /api/team-files/delete {path} an admin anything; a member what they uploaded+// Security: every path goes through teamFilePath (no `..`, no control characters) and the folder never follows a link;+// a file is served as an attachment unless it is text or a common picture, and text is never served as HTML.+import { pipeline } from "node:stream/promises";++import type { RequestAuth } from "../request-auth.ts";+import type { TeamFileView } from "../../shared/team-files.ts";+import { teamFileName, teamFilePath, TeamFilesError, type TeamFileEntry, type TeamFiles, type TeamFilesActor } from "../host/team-files.ts";+import { PASS, type RouteContext, type RouteHandler } from "./table.ts";++export const TEAM_FILES_PATH = "/api/team-files";++export interface TeamFilesRouteDeps {+ files: TeamFiles | null;+ /** The signed-in person and whether they are the team's Owner or an Admin; null for a session that is no one. */+ actor(auth: RequestAuth): TeamFilesActor | null;+ personName(person: string): string | undefined;+ botName(botId: string): string | undefined;+}++const PREVIEW_TYPES: Record<string, string> = {+ txt: "text/plain; charset=utf-8", md: "text/plain; charset=utf-8", markdown: "text/plain; charset=utf-8", csv: "text/plain; charset=utf-8",+ tsv: "text/plain; charset=utf-8", json: "text/plain; charset=utf-8", log: "text/plain; charset=utf-8",+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp",+};++/** How a file is served: a preview type for text and common pictures, else bytes to download. */+export function teamFileType(name: string): { type: string; preview: boolean } {+ const ext = name.includes(".") ? name.split(".").at(-1)!.toLowerCase() : "";+ const type = PREVIEW_TYPES[ext];+ return type ? { type, preview: true } : { type: "application/octet-stream", preview: false };+}++function disposition(kind: "inline" | "attachment", name: string): string {+ const ascii = name.replace(/[^\x20-\x7e]|["\\]/g, "_");+ return `${kind}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;+}++export function createTeamFilesRoutes(deps: TeamFilesRouteDeps): RouteHandler {+ const view = (files: TeamFiles, entry: TeamFileEntry, actor: TeamFilesActor): TeamFileView => {+ const { last, owner, ...rest } = entry;+ const named = last && {+ at: last.at, action: last.action,+ ...(last.person ? { person: deps.personName(last.person) ?? "" } : {}),+ ...(last.bot ? { bot: deps.botName(last.bot) ?? "" } : {}),+ ...(last.from ? { from: last.from } : {}),+ };+ return { ...rest, ...(named ? { last: named } : {}), canDelete: files.mayRemove(entry.path, actor), mine: owner === actor.person };+ };++ return async (ctx: RouteContext) => {+ const { req, res, url, path, method, auth, json, readBody } = ctx;+ if (path !== TEAM_FILES_PATH && !path.startsWith(`${TEAM_FILES_PATH}/`)) return PASS;+ const files = deps.files;+ if (!files) return PASS;+ const actor = deps.actor(auth);+ if (!actor) { req.resume(); return json(res, 403, { error: "Sign in to the team to use its files.", code: "forbidden" }); }+ try {+ if (path === TEAM_FILES_PATH && method === "GET") {+ const folder = teamFilePath(url.searchParams.get("path") ?? "");+ if (folder === null) return json(res, 400, { error: "That isn't a path in team files.", code: "bad_path" });+ const listed = files.list(folder, actor);+ return json(res, 200, {+ path: folder, entries: listed.entries.map((entry) => view(files, entry, actor)),+ used: files.used(), cap: files.cap, uploadMax: files.uploadMax, admin: actor.admin,+ });+ }+ if (path === `${TEAM_FILES_PATH}/file` && method === "GET") {+ const file = teamFilePath(url.searchParams.get("path") ?? "");+ if (!file) return json(res, 400, { error: "That isn't a file in team files.", code: "bad_path" });+ const opened = files.open(file);+ const served = teamFileType(opened.name);+ const download = url.searchParams.get("download") === "1" || !served.preview;+ res.writeHead(200, {+ "content-type": download ? "application/octet-stream" : served.type, "content-length": String(opened.size),+ "content-disposition": disposition(download ? "attachment" : "inline", opened.name),+ "x-content-type-options": "nosniff", "content-security-policy": "sandbox; default-src 'none'", "cache-control": "private, no-store",+ });+ await pipeline(files.stream(opened.fd), res).catch(() => {});+ return;+ }+ if (path === `${TEAM_FILES_PATH}/file` && method === "PUT") {+ const folder = teamFilePath(url.searchParams.get("path") ?? "");+ const name = teamFileName(url.searchParams.get("name") ?? "");+ if (folder === null || !name) { req.resume(); return json(res, 400, { error: "Name the file and the folder it goes in.", code: "bad_path" }); }+ const length = req.headers["content-length"];+ const declared = length === undefined ? null : Number(length);+ if (declared !== null && (!Number.isFinite(declared) || declared < 0)) { req.resume(); return json(res, 400, { error: "That upload has no usable length.", code: "bad_length" }); }+ const entry = await files.upload(folder, name, req, declared, actor);+ return json(res, 201, { entry: view(files, entry, actor), used: files.used() });+ }+ if (method !== "POST") { req.resume(); return json(res, 405, { error: "method not allowed" }); }+ const body = await readBody(req) as Record<string, unknown> | null;+ if (!body || typeof body !== "object") return json(res, 400, { error: "send a JSON object", code: "bad_path" });+ if (path === `${TEAM_FILES_PATH}/folder`) {+ const folder = teamFilePath(body.path);+ if (!folder) return json(res, 400, { error: "Name the new folder.", code: "bad_path" });+ files.folder(folder, actor);+ return json(res, 201, { ok: true });+ }+ if (path === `${TEAM_FILES_PATH}/rename`) {+ const from = teamFilePath(body.from), to = teamFilePath(body.to);+ if (!from || !to) return json(res, 400, { error: "Name the file and its new name.", code: "bad_path" });+ files.rename(from, to, actor);+ return json(res, 200, { ok: true });+ }+ if (path === `${TEAM_FILES_PATH}/delete`) {+ const target = teamFilePath(body.path);+ if (!target) return json(res, 400, { error: "Name what to delete.", code: "bad_path" });+ files.remove(target, actor);+ return json(res, 200, { ok: true, used: files.used() });+ }+ return json(res, 404, { error: "not found" });+ } catch (error) {+ if (error instanceof TeamFilesError) { if (!req.readableEnded) req.resume(); return json(res, error.status, { error: error.message, code: error.code }); }+ throw error;+ }+ };+}diff --git a/server/team-move-in.test.ts b/server/team-move-in.test.tsindex f9227eb74e..3b6d56634a 100644--- a/server/team-move-in.test.ts+++ b/server/team-move-in.test.ts@@ -128,7 +128,7 @@ describe("what a move-in may write", () => {const ADMINS_SET = {approvalMode: "full", autoApprove: true, alwaysAllow: ["Bash(*)"], chiefOfStaff: true, managedSections: ["Ops"], computer: "local", cwd: "/",cloudBackend: "vps", composio: true, browser: true, browserProfile: "guest", mcpServers: ["github"],- toolScope: { allow: ["native:*"] }, connectorTools: {}, connectorScopes: {}, outbound: {}, xResearch: true, phoneApps: [], section: "Finance",+ toolScope: { allow: ["native:*"] }, connectorTools: {}, connectorScopes: {}, outbound: {}, xResearch: true, teamFilesEdit: true, phoneApps: [], section: "Finance",visibility: { audience: "members" }, recordBrowserSteps: true, cacheKeepWarm: true,};diff --git a/server/team-templates.ts b/server/team-templates.tsindex 5e9375711c..0a3c6c6ee6 100644--- a/server/team-templates.ts+++ b/server/team-templates.ts@@ -12,10 +12,10 @@ import type { TeamTemplate, TemplateScope } from "../shared/share-card.ts";import type { ShareFolderFiles } from "../shared/share-folder.ts";import { renameWithRetry, writeFileAtomic } from "./atomic.ts";import { readFolderFromDisk, ShareError, writeFolder } from "./share.ts";+import { TEAM_FILES_DIR, TEAM_FILES_TEMPLATES } from "./host/team-files.ts";-/** The team's shared files. Its templates are one folder of it. */-export const TEAM_FILES_FOLDER = "team-files";-export const teamTemplatesFolder = (dataDir: string): string => join(dataDir, TEAM_FILES_FOLDER, "templates");+/** The team's shared files (server/host/team-files.ts). Its templates are one folder of it. */+export const teamTemplatesFolder = (dataDir: string): string => join(dataDir, TEAM_FILES_DIR, TEAM_FILES_TEMPLATES);export const TEAM_TEMPLATE_SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/;const MAX_TEMPLATES = 500;diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex 2884a41d92..f519c62a42 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -359,6 +359,12 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: CrskippedDependencies++;continue;}+ // A link a bot made in a conversation's folder, or in Team files (which a bot may be let to write), is never+ // followed or carried, and never stops the backup.+ if (stat.isSymbolicLink() && path.startsWith("team-files/")) {+ skippedWorkLinks++;+ continue;+ }if (stat.isSymbolicLink() && path.startsWith("task-workspaces/")) {if (managedTaskSkillLink(source, path, [root, resolve(dataDir)])) skippedLinks++; else skippedWorkLinks++;continue;diff --git a/shared/team-files.ts b/shared/team-files.tsnew file mode 100644index 0000000000..4dcc68d586--- /dev/null+++ b/shared/team-files.ts@@ -0,0 +1,30 @@+// What the Team files routes answer (server/routes/team-files.ts) and the page reads (src/components/team-files).+export type TeamFileAction = "uploaded" | "added" | "changed" | "deleted" | "renamed" | "folder";++/** The last change of a file or of anything in a folder, by name: the person who did it, or for whom the bot did it. */+export interface TeamFileChangeView { at: number; action: TeamFileAction; person?: string; bot?: string; from?: string }++export interface TeamFileView {+ name: string;+ /** Relative to the team's folder, "/"-separated. */+ path: string;+ kind: "file" | "folder";+ size: number;+ modifiedAt: number;+ last?: TeamFileChangeView;+ /** The viewer may delete or rename it: an admin anything, a member what they uploaded. */+ canDelete: boolean;+ mine: boolean;+}++export interface TeamFilesListing {+ path: string;+ entries: TeamFileView[];+ used: number;+ cap: number;+ uploadMax: number;+ admin: boolean;+}++/** Why a request was refused, as the routes' `code`. */+export type TeamFilesRefusal = "bad_path" | "not_found" | "exists" | "forbidden" | "too_large" | "full" | "link" | "not_file" | "not_folder" | "incomplete" | "bad_length";diff --git a/src/App.tsx b/src/App.tsxindex 65581f1c1c..56d36d3769 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -24,7 +24,7 @@ import { SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQueimport { preloadConnectedApps } from "@/lib/connected-apps";import {ActivityPanel, BotSettingsDialog, CloudAddDialog, ComputerPanel, FilesView, InspectorPanel, KeyboardShortcutsModal, LocalVmWorkspace,- PluginsPanel, preloadScreens, PublishedAppsPage, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamMapPage, TriggersPage,+ PluginsPanel, preloadScreens, PublishedAppsPage, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamFilesPage, TeamMapPage, TriggersPage,} from "@/components/lazy-screens";import { useAdvancedMode } from "@/lib/interface-mode";import { useRoomPanelShown } from "@/lib/room-panel";@@ -381,6 +381,8 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {<WebPanelPage />) : state.activeView === "published-apps" ? (<PublishedAppsPage />+ ) : state.activeView === "team-files" && state.config?.team ? (+ <TeamFilesPage />) : state.activeView === "routines" ? (<TriggersPage onBack={closeCalendar} onOpenRoom={openCalendarRoom} />) : !remoteClient && localVmWorkspaceBotId ? (diff --git a/src/components/SidebarFooterNav.tsx b/src/components/SidebarFooterNav.tsxindex 6b285d9c95..3dc6e37ee3 100644--- a/src/components/SidebarFooterNav.tsx+++ b/src/components/SidebarFooterNav.tsx@@ -1,4 +1,4 @@-import { AppWindow, FolderOpen, Globe, Puzzle, Rocket, UsersRound, Zap } from "lucide-react";+import { AppWindow, FolderOpen, FolderTree, Globe, Puzzle, Rocket, UsersRound, Zap } from "lucide-react";import { useMemo, type ReactNode } from "react";import { useAppTriggers } from "@/lib/app-triggers";@@ -181,6 +181,16 @@ export function SidebarFooterNav({icon={(active) => <Rocket size={iconSize} className={tone(active)} />}onClick={() => dispatch({ type: "showPublishedApps" })}/>+ {state.config?.team && (+ <NavRow+ id="team-files"+ label={t("sidebar.nav.teamFiles")}+ iconsOnly={iconsOnly || toolbar}+ active={state.activeView === "team-files"}+ icon={(active) => <FolderTree size={iconSize} className={tone(active)} />}+ onClick={() => dispatch({ type: "showTeamFiles" })}+ />+ )}{advanced && webPanels.map((panel) => (<NavRowkey={panel.id}diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsxindex cc25fd9e0d..61d247cf49 100644--- a/src/components/SidebarProfileMenu.tsx+++ b/src/components/SidebarProfileMenu.tsx@@ -17,6 +17,7 @@ import {LogOut,MessageSquare,Sparkles,+ FolderTree,RefreshCw,Rocket,Settings as SettingsIcon,@@ -307,7 +308,7 @@ export function phoneDevicesItem(state: PhonePlaceState, place: string, onSelect};}-export function toolMenuItems({ activeView, automationsNeedYou, onAutomations, onTeamMap, onFiles, onPublishedApps, archived }: {+export function toolMenuItems({ activeView, automationsNeedYou, onAutomations, onTeamMap, onFiles, onPublishedApps, onTeamFiles, archived }: {activeView: string;automationsNeedYou: boolean;onAutomations: () => void;@@ -315,6 +316,8 @@ export function toolMenuItems({ activeView, automationsNeedYou, onAutomations, o/** set once My Cloud's files are ready to open */onFiles?: () => void;onPublishedApps?: () => void;+ /** set only on a Team Cloud: its shared folder */+ onTeamFiles?: () => void;archived?: ArchivedBots;}): SidebarMenuItem[] {return [@@ -322,6 +325,7 @@ export function toolMenuItems({ activeView, automationsNeedYou, onAutomations, o{ key: "team-map", label: t("sidebar.nav.teamMap"), icon: <UsersRound size={16} />, active: activeView === "team-map", onSelect: onTeamMap },...(onFiles ? [{ key: "files", label: t("sidebar.nav.files"), icon: <FolderOpen size={16} />, active: activeView === "files", onSelect: onFiles }] : []),...(onPublishedApps ? [{ key: "published-apps", label: t("sidebar.nav.publishedApps"), icon: <Rocket size={16} />, active: activeView === "published-apps", onSelect: onPublishedApps }] : []),+ ...(onTeamFiles ? [{ key: "team-files", label: t("sidebar.nav.teamFiles"), icon: <FolderTree size={16} />, active: activeView === "team-files", onSelect: onTeamFiles }] : []),...(archived?.count ? [{ key: "archived", label: t("sidebar.archived.title"), icon: <Archive size={16} />, value: String(archived.count), onSelect: archived.open }] : []),];}@@ -592,6 +596,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = faonTeamMap: () => dispatch({ type: "showTeamMap" }),onFiles: filesReady ? () => dispatch({ type: "showFiles" }) : undefined,onPublishedApps: () => dispatch({ type: "showPublishedApps" }),+ onTeamFiles: state.config?.team ? () => dispatch({ type: "showTeamFiles" }) : undefined,archived: account?.archived,}),} } : {}),diff --git a/src/components/bot-settings/AccessSection.tsx b/src/components/bot-settings/AccessSection.tsxindex 01e4482f93..fb0a9404bf 100644--- a/src/components/bot-settings/AccessSection.tsx+++ b/src/components/bot-settings/AccessSection.tsx@@ -24,6 +24,7 @@ import { BotApiCard } from "./BotApiCard";import { ToolBudgetLine } from "./ToolBudgetLine";import { useCloudPlan } from "../ProIntroduction";import { xResearchAction } from "@/lib/cloud-plan";+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { useBotApps } from "./useBotApps";import {classifyConnectorTool,@@ -508,6 +509,28 @@ function ResearchCard({ bot, patch }: { bot: Bot; patch: (patch: { xResearch: bo);}+/** On a Team Cloud: whether this bot may add and change the team's shared files, from any chat (an admin's to set). */+function TeamFilesCard({ bot, patch }: { bot: Bot; patch: (patch: { teamFilesEdit: boolean }) => void }) {+ const admin = useOwnerOrAdmin();+ const on = bot.teamFilesEdit === true;+ return (+ <div className="flex items-center justify-between gap-4 rounded-xl bg-card p-4" data-testid="access-team-files">+ <div>+ <div className="text-[15px] font-medium text-ink">{t("botAccess.teamFiles.title")}</div>+ <div className="mt-0.5 text-[13px] text-ink-secondary">{t(on ? "botAccess.teamFiles.on" : "botAccess.teamFiles.off")}</div>+ {!admin && <div className="mt-0.5 text-[12px] text-ink-secondary">{t("botAccess.teamFiles.adminsOnly")}</div>}+ </div>+ <Switch+ checked={on}+ aria-label={t("botAccess.teamFiles.title")}+ disabled={!admin}+ onClick={() => patch({ teamFilesEdit: !on })}+ className="disabled:cursor-not-allowed"+ />+ </div>+ );+}+function RecordStepsRow({ on, browserOn, myChrome, onChange }: { on: boolean; browserOn: boolean; myChrome: boolean; onChange: (on: boolean) => void }) {return (<div className="mt-3 flex items-center justify-between gap-4 border-t border-hairline/40 pt-3">@@ -665,7 +688,7 @@ function DraftWorksOn({ bot, patch, seat }: { bot: Bot; patch: ReturnType<typeof</>;}-export type AccessPart = "worksOn" | "folder" | "apps" | "phone" | "xResearch" | "mcp" | "tools" | "browser" | "webhooks" | "always";+export type AccessPart = "worksOn" | "folder" | "apps" | "phone" | "xResearch" | "teamFiles" | "mcp" | "tools" | "browser" | "webhooks" | "always";export function AccessSection({bot,@@ -836,6 +859,8 @@ export function AccessSection({{!draft && shows("xResearch") && <ResearchCard bot={bot} patch={patch} />}+ {!draft && shows("teamFiles") && state.config?.team && <TeamFilesCard bot={bot} patch={patch} />}+{!draft && shows("webhooks") && <BotApiCard bot={bot} />}{!draft && shows("webhooks") && <div className="rounded-xl bg-card p-4">diff --git a/src/components/bot-settings/useBotSettingsDerived.ts b/src/components/bot-settings/useBotSettingsDerived.tsindex d7d19ad90d..62a92392d5 100644--- a/src/components/bot-settings/useBotSettingsDerived.ts+++ b/src/components/bot-settings/useBotSettingsDerived.ts@@ -34,6 +34,7 @@ export type BotPatch = Partial<| "replyStyle"| "memoryEnabled"| "xResearch"+ | "teamFilesEdit"| "toolsOff"| "voice"| "chiefOfStaff"diff --git a/src/components/lazy-screens.test.ts b/src/components/lazy-screens.test.tsindex 195588521d..f1419a62b0 100644--- a/src/components/lazy-screens.test.ts+++ b/src/components/lazy-screens.test.ts@@ -155,7 +155,7 @@ describe("preloadScreens", () => {it("a page on this machine fetches nothing ahead: each screen loads when it opens", () => {vi.useFakeTimers();const preloads = stubPreloads();- expect(preloads.length).toBe(22);+ expect(preloads.length).toBe(23);for (const host of ["127.0.0.1", "localhost", "[::1]"]) preloadScreens(host);vi.runAllTimers();for (const preload of preloads) expect(preload).not.toHaveBeenCalled();@@ -200,7 +200,7 @@ describe("preloadScreens", () => {preloadScreens("cloud.example");for (const preload of preloads) expect(preload).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(60_000);- const rarelyOpened = [screens.CloudAddDialog, screens.GrokMoveDialog, screens.PhoneAppDialog, screens.ShareDepartmentDialog, screens.ImportDialog, screens.TeamLibraryPanel];+ const rarelyOpened = [screens.CloudAddDialog, screens.GrokMoveDialog, screens.PhoneAppDialog, screens.ShareDepartmentDialog, screens.ImportDialog, screens.TeamLibraryPanel, screens.TeamFilesPage];const stubbed = Object.values(screens).filter((value): value is ReturnType<typeof lazyScreen> => typeof value === "function" && "preload" in value);for (const screen of stubbed) expect(screen.preload).toHaveBeenCalledTimes(rarelyOpened.includes(screen as never) ? 0 : 1);expect(preloads.length).toBe(stubbed.length);@@ -263,7 +263,7 @@ describe("launch bundle", () => {const deferred = ["ActivityPanel", "BotSettingsDialog", "CloudAddDialog", "ComputerPanel", "InspectorPanel", "KeyboardShortcutsModal","LocalVmWorkspace", "NewBotDialog", "PhoneAppDialog", "PhoneSetupFlow", "PluginsPanel", "published-apps/PublishedAppsPage", "RemoteAgentSettingsPanel", "remote-desktop-panel", "RoutineCalendarPage",- "RoutinesPage", "SettingsModal", "ShareDepartmentDialog", "ImportDialog", "TeamLibraryPanel", "TeamMapPage", "TriggersPage", "WebhookTrigger", "room-panel/RoomPanel",+ "RoutinesPage", "SettingsModal", "ShareDepartmentDialog", "ImportDialog", "TeamLibraryPanel", "TeamMapPage", "team-files/TeamFilesPage", "TriggersPage", "WebhookTrigger", "room-panel/RoomPanel",].map((name) => `components/${name}.tsx`);expect(deferred.filter((file) => reached.has(file))).toEqual([]);expect(reached.has("lib/template-details.ts"), "the team library brings the YAML parser in").toBe(false);diff --git a/src/components/lazy-screens.tsx b/src/components/lazy-screens.tsxindex f38f0056ea..f8b04dc220 100644--- a/src/components/lazy-screens.tsx+++ b/src/components/lazy-screens.tsx@@ -89,6 +89,8 @@ export const ShareDepartmentDialog = lazyScreen("ShareDepartmentDialog", async (export const ImportDialog = lazyScreen("ImportDialog", async () => (await import("./ImportDialog")).ImportDialog);export const GrokMoveDialog = lazyScreen("GrokMoveDialog", async () => (await import("./GrokMoveDialog")).GrokMoveDialog);export const TeamLibraryPanel = lazyScreen("TeamLibraryPanel", async () => (await import("./TeamLibraryPanel")).TeamLibraryPanel);+// Only a Team Cloud has it, so no page fetches it ahead.+export const TeamFilesPage = lazyScreen("TeamFilesPage", async () => (await import("./team-files/TeamFilesPage")).TeamFilesPage);// Most opened first: a Cloud page fetches these in this order.const SCREENS = [diff --git a/src/components/team-files/TeamFilesPage.test.ts b/src/components/team-files/TeamFilesPage.test.tsnew file mode 100644index 0000000000..2176793357--- /dev/null+++ b/src/components/team-files/TeamFilesPage.test.ts@@ -0,0 +1,143 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { TeamFilesListing } from "../../../shared/team-files";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const fixture = vi.hoisted(() => ({ state: { config: { team: { id: "team-acme", name: "Acme" } } }, dispatch: vi.fn(), api: vi.fn() }));+class FakeApiError extends Error {+ status: number; body?: Record<string, unknown>;+ constructor(message: string, status: number, body?: Record<string, unknown>) { super(message); this.status = status; this.body = body; }+}+vi.mock("@/state/store", () => ({ useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) }));+vi.mock("@/state/api", () => ({ api: fixture.api, ApiError: FakeApiError }));++const { TeamFilesPage, changedLine, formatSize, refusalText } = await import("./TeamFilesPage");++const NOW = Date.parse("2026-11-17T12:00:00Z");+const GB = 1024 ** 3;+const listings: Record<string, TeamFilesListing> = {+ "": {+ path: "", used: 1.5 * GB, cap: 5 * GB, uploadMax: 100 * 1024 ** 2, admin: false, entries: [+ { name: "payroll", path: "payroll", kind: "folder", size: 0, modifiedAt: NOW, canDelete: false, mine: false, last: { at: NOW - 2 * 3_600_000, action: "added", person: "Mira", bot: "Payroll" } },+ { name: "handbook.md", path: "handbook.md", kind: "file", size: 2048, modifiedAt: NOW, canDelete: true, mine: true, last: { at: NOW - 60_000 * 5, action: "uploaded", person: "Ben" } },+ { name: "logo.png", path: "logo.png", kind: "file", size: 10, modifiedAt: NOW, canDelete: false, mine: false },+ ],+ },+ payroll: {+ path: "payroll", used: 1.5 * GB, cap: 5 * GB, uploadMax: 100 * 1024 ** 2, admin: false, entries: [+ { name: "nov.csv", path: "payroll/nov.csv", kind: "file", size: 20, modifiedAt: NOW, canDelete: false, mine: false, last: { at: NOW - 2 * 3_600_000, action: "added", person: "Mira", bot: "Payroll" } },+ ],+ },+};++let root: Root, host: HTMLElement;+const calls: Array<{ path: string; method: string; body?: string }> = [];+const fetches: Array<{ url: string; method: string }> = [];+let putAnswer: () => Response;++beforeEach(() => {+ vi.useFakeTimers({ now: NOW, toFake: ["Date"] });+ calls.length = 0;+ fetches.length = 0;+ putAnswer = () => new Response("{}", { status: 201 });+ fixture.api.mockReset();+ fixture.api.mockImplementation(async (path: string, init?: { method?: string; body?: string }) => {+ calls.push({ path, method: init?.method ?? "GET", ...(init?.body ? { body: init.body } : {}) });+ const listed = /^\/api\/team-files\?path=(.*)$/.exec(path);+ if (listed) return listings[decodeURIComponent(listed[1]!)];+ return { ok: true };+ });+ vi.stubGlobal("fetch", vi.fn(async (url: string, init?: { method?: string }) => {+ fetches.push({ url, method: init?.method ?? "GET" });+ return init?.method === "PUT" ? putAnswer() : new Response("name,net\nMira,4200\n", { status: 200 });+ }));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++const render = async () => { await act(async () => root.render(createElement(TeamFilesPage))); await act(async () => {}); };+const button = (label: string) => [...host.querySelectorAll("button")].find((one) => one.getAttribute("aria-label") === label || one.textContent === label)!;++describe("the Team files page", () => {+ it("lists the folder with who changed each file, the space used, and actions by what the viewer may do", async () => {+ await render();+ expect(host.querySelector("[data-team-files]")?.getAttribute("data-team-files")).toBe("3");+ expect(host.textContent).toContain("1.5 GB of 5 GB used");+ const rows = [...host.querySelectorAll("[data-team-file]")];+ expect(rows.map((row) => row.getAttribute("data-team-file"))).toEqual(["payroll", "handbook.md", "logo.png"]);+ expect(rows[0]!.textContent).toContain("Changed by Mira with Payroll · 2 hr ago");+ expect(rows[1]!.textContent).toContain("2 KB · Uploaded by Ben · 5 min ago");+ expect(rows[1]!.querySelector("[aria-label='Delete']")).not.toBeNull();+ expect(rows[2]!.querySelector("[aria-label='Delete']"), "not theirs").toBeNull();+ expect(rows[1]!.querySelector("a[download]")?.getAttribute("href")).toBe("/api/team-files/file?path=handbook.md&download=1");+ });++ it("opens a folder with breadcrumbs back, and previews text", async () => {+ await render();+ await act(async () => button("Open payroll").click());+ await act(async () => {});+ expect(calls.at(-1)?.path).toBe("/api/team-files?path=payroll");+ expect(host.querySelector("nav [aria-current='page']")?.textContent).toBe("payroll");+ await act(async () => button("Open nov.csv").click());+ expect(host.querySelector("[data-team-file-preview]")?.textContent).toBe("name,net\nMira,4200\n");+ await act(async () => [...host.querySelectorAll("nav button")][0]!.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ await act(async () => {});+ expect(calls.at(-1)?.path).toBe("/api/team-files?path=");+ });++ it("uploads what is dropped into the open folder, and says why one was refused", async () => {+ await render();+ const file = new File(["hello"], "notes.txt");+ const drop = new Event("drop", { bubbles: true }) as Event & { dataTransfer: { files: File[] } };+ Object.defineProperty(drop, "dataTransfer", { value: { files: [file] } });+ await act(async () => host.querySelector("[data-team-files]")!.dispatchEvent(drop));+ await act(async () => {});+ expect(fetches.find((one) => one.method === "PUT")?.url).toBe("/api/team-files/file?path=&name=notes.txt");+ putAnswer = () => new Response(JSON.stringify({ error: "full", code: "full" }), { status: 507 });+ const picker = host.querySelector<HTMLInputElement>("[data-testid='team-files-picker']")!;+ Object.defineProperty(picker, "files", { value: [new File(["x"], "big.bin")], configurable: true });+ await act(async () => picker.dispatchEvent(new Event("change", { bubbles: true })));+ await act(async () => {});+ expect(host.querySelector("[role='alert']")?.textContent).toBe("Team files are full (5 GB). Remove files to make room.");+ });++ it("makes a folder and deletes after asking", async () => {+ await render();+ await act(async () => button("New folder").click());+ const input = host.querySelector<HTMLInputElement>("form input")!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "Clients");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => host.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));+ expect(calls.find((call) => call.path === "/api/team-files/folder")).toEqual({ path: "/api/team-files/folder", method: "POST", body: JSON.stringify({ path: "Clients" }) });+ vi.stubGlobal("confirm", () => true);+ await act(async () => host.querySelector<HTMLElement>("[data-team-file='handbook.md'] [aria-label='Delete']")!.click());+ expect(calls.find((call) => call.path === "/api/team-files/delete")?.body).toBe(JSON.stringify({ path: "handbook.md" }));+ });+});++describe("its words", () => {+ it("names who changed a file, and what a refusal means", () => {+ expect(changedLine({ last: { at: NOW - 3_600_000, action: "changed", bot: "Payroll" } }, NOW)).toBe("Changed by Payroll · 1 hr ago");+ expect(changedLine({ last: { at: NOW, action: "folder", person: "Ada" } }, NOW)).toBe("Made by Ada · just now");+ expect(changedLine({}, NOW)).toBeNull();+ expect(formatSize(512)).toBe("512 B");+ expect(formatSize(100 * 1024 ** 2)).toBe("100 MB");+ const limits = { uploadMax: 100 * 1024 ** 2, cap: 5 * GB };+ expect(refusalText(new FakeApiError("x", 413, { code: "too_large" }), limits)).toBe("A file may be at most 100 MB.");+ expect(refusalText(new FakeApiError("x", 403, { code: "forbidden" }), limits)).toBe("Only an admin, or whoever uploaded it, can do that.");+ expect(refusalText(new Error("offline"), limits)).toBe("That didn't work. Try again.");+ });+});diff --git a/src/components/team-files/TeamFilesPage.tsx b/src/components/team-files/TeamFilesPage.tsxnew file mode 100644index 0000000000..13beb3ffe3--- /dev/null+++ b/src/components/team-files/TeamFilesPage.tsx@@ -0,0 +1,244 @@+import { useCallback, useEffect, useRef, useState, type DragEvent } from "react";+import { Download, FileText, Folder, FolderPlus, Image as ImageIcon, Pencil, Trash2, Upload, X } from "lucide-react";++import type { TeamFileView, TeamFilesListing, TeamFilesRefusal } from "../../../shared/team-files";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { relativeTime } from "@/lib/memory";+import type { LocaleKey } from "@/locales";+import { api, ApiError } from "@/state/api";+import { useStore } from "@/state/store";+import { TOOL_PAGE_TITLE, ToolPage, ToolPageActions, ToolPageHeader } from "../ToolPageShell";++// Team files: the Team Cloud's one shared folder (server/routes/team-files.ts), for every teammate and bot. A folder list+// with breadcrumbs, upload by button or drop, new folder, download, rename, delete (an admin anything, a member what they+// uploaded), a preview of text and pictures, who changed each file last, and the space used.++const BASE = "/api/team-files";+const PREVIEW_MAX_BYTES = 1024 * 1024;+const TEXT = new Set(["txt", "md", "markdown", "csv", "tsv", "json", "log"]);+const PICTURE = new Set(["png", "jpg", "jpeg", "gif", "webp"]);+const REFUSALS: Partial<Record<TeamFilesRefusal, LocaleKey>> = {+ exists: "teamFiles.error.exists", forbidden: "teamFiles.error.forbidden", not_found: "teamFiles.error.notFound",+ bad_path: "teamFiles.error.badName", link: "teamFiles.error.badName",+};++const extension = (name: string) => (name.includes(".") ? name.split(".").at(-1)!.toLowerCase() : "");+export const previewKind = (name: string): "text" | "picture" | null => (TEXT.has(extension(name)) ? "text" : PICTURE.has(extension(name)) ? "picture" : null);+export const fileUrl = (path: string, download = false) => `${BASE}/file?path=${encodeURIComponent(path)}${download ? "&download=1" : ""}`;+const join = (folder: string, name: string) => (folder ? `${folder}/${name}` : name);++export function formatSize(bytes: number): string {+ const units = ["B", "KB", "MB", "GB"];+ let value = bytes, unit = 0;+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; }+ return `${unit === 0 ? value : value < 10 ? Number(value.toFixed(1)) : Math.round(value)} ${units[unit]}`;+}++/** "Changed by Mira with Payroll · 2 hr ago", from the last recorded change. */+export function changedLine(entry: Pick<TeamFileView, "last">, now = Date.now()): string | null {+ const last = entry.last;+ if (!last) return null;+ const person = last.person || t("teamFiles.someone"), when = relativeTime(last.at, now);+ if (last.action === "uploaded") return t("teamFiles.uploaded", { person, when });+ if (last.action === "folder") return t("teamFiles.made", { person, when });+ if (last.bot) return last.person ? t("teamFiles.changedWith", { person, bot: last.bot, when }) : t("teamFiles.changedBy", { person: last.bot, when });+ return t("teamFiles.changedBy", { person, when });+}++/** The words for a refusal the routes answered with, in the person's language. */+export function refusalText(error: unknown, limits: { uploadMax: number; cap: number }): string {+ const body = error instanceof ApiError ? error.body : (error as { body?: Record<string, unknown> } | null)?.body;+ const code = typeof body?.code === "string" ? body.code as TeamFilesRefusal : null;+ if (code === "too_large") return t("teamFiles.error.tooLarge", { mb: Math.round(limits.uploadMax / 1024 ** 2) });+ if (code === "full") return t("teamFiles.error.full", { gb: Math.round(limits.cap / 1024 ** 3) });+ return t((code && REFUSALS[code]) || "teamFiles.error.failed");+}++/** One file up, the bytes as the request body. */+async function uploadFile(folder: string, file: File): Promise<void> {+ const res = await fetch(`${BASE}/file?path=${encodeURIComponent(folder)}&name=${encodeURIComponent(file.name)}`, {+ method: "PUT", body: file, headers: { "content-type": "application/octet-stream" },+ });+ if (!res.ok) throw new ApiError(`${res.status}`, res.status, await res.json().catch(() => ({})));+}++type Editing = { kind: "folder" } | { kind: "rename"; entry: TeamFileView } | null;+type Preview = { entry: TeamFileView; text?: string; tooLarge?: boolean } | null;++export function TeamFilesPage() {+ const { state, dispatch } = useStore();+ const [folder, setFolder] = useState("");+ const [listing, setListing] = useState<TeamFilesListing | null>(null);+ const [failed, setFailed] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ const [uploading, setUploading] = useState<string | null>(null);+ const [dragging, setDragging] = useState(false);+ const [editing, setEditing] = useState<Editing>(null);+ const [name, setName] = useState("");+ const [preview, setPreview] = useState<Preview>(null);+ const back = useRef<HTMLButtonElement>(null);+ const picker = useRef<HTMLInputElement>(null);+ const loading = useRef<AbortController | null>(null);+ const limits = { uploadMax: listing?.uploadMax ?? 100 * 1024 ** 2, cap: listing?.cap ?? 5 * 1024 ** 3 };++ const load = useCallback(async (path: string) => {+ loading.current?.abort();+ const controller = new AbortController();+ loading.current = controller;+ try {+ const answer = await api<TeamFilesListing>(`${BASE}?path=${encodeURIComponent(path)}`, { signal: controller.signal });+ if (controller.signal.aborted) return;+ setListing(answer);+ setFailed(false);+ } catch (error) {+ if (controller.signal.aborted) return;+ // A folder someone removed meanwhile: back to the top.+ if (path && error instanceof ApiError && error.status === 404) { setFolder(""); return; }+ setFailed(true);+ }+ }, []);+ useEffect(() => { void load(folder); }, [folder, load]);+ useEffect(() => () => loading.current?.abort(), []);+ useEffect(() => { back.current?.focus({ preventScroll: true }); }, []);++ const act = async (work: () => Promise<unknown>) => {+ setProblem(null);+ try { await work(); } catch (error) { setProblem(refusalText(error, limits)); }+ await load(folder);+ };+ const upload = (files: readonly File[]) => act(async () => {+ try {+ for (const file of files) {+ setUploading(file.name);+ await uploadFile(folder, file);+ }+ } finally {+ setUploading(null);+ }+ });+ const submitName = () => {+ const wanted = name.trim();+ if (!wanted || !editing) return;+ const current = editing;+ setEditing(null);+ void act(() => current.kind === "folder"+ ? api(`${BASE}/folder`, { method: "POST", body: JSON.stringify({ path: join(folder, wanted) }) })+ : api(`${BASE}/rename`, { method: "POST", body: JSON.stringify({ from: current.entry.path, to: join(folder, wanted) }) }));+ };+ const remove = (entry: TeamFileView) => {+ if (!window.confirm(t("teamFiles.deleteConfirm", { name: entry.name }))) return;+ void act(() => api(`${BASE}/delete`, { method: "POST", body: JSON.stringify({ path: entry.path }) }));+ };+ const open = async (entry: TeamFileView) => {+ if (entry.kind === "folder") { setPreview(null); setFolder(entry.path); return; }+ const kind = previewKind(entry.name);+ if (kind !== "text") { setPreview({ entry }); return; }+ if (entry.size > PREVIEW_MAX_BYTES) { setPreview({ entry, tooLarge: true }); return; }+ try {+ const res = await fetch(fileUrl(entry.path));+ setPreview({ entry, text: res.ok ? await res.text() : "" });+ } catch {+ setPreview({ entry, text: "" });+ }+ };+ const drop = (event: DragEvent) => {+ event.preventDefault();+ setDragging(false);+ const files = [...(event.dataTransfer?.files ?? [])];+ if (files.length) void upload(files);+ };+ const crumbs = folder ? folder.split("/") : [];+ const team = state.config?.team?.name ?? "";++ return (+ <ToolPage label={t("teamFiles.title")}>+ <ToolPageHeader backLabel={t("automations.back")} onBack={() => dispatch({ type: "showChat" })} backRef={back}>+ <h1 className={TOOL_PAGE_TITLE}>{t("teamFiles.title")}</h1>+ <ToolPageActions>+ <button type="button" className="ui-button" onClick={() => { setName(""); setEditing({ kind: "folder" }); }}><FolderPlus size={15} />{t("teamFiles.newFolder")}</button>+ <button type="button" className="ui-button ui-button-primary" disabled={uploading !== null} onClick={() => picker.current?.click()}><Upload size={15} />{t("teamFiles.upload")}</button>+ <input ref={picker} type="file" multiple hidden data-testid="team-files-picker" onChange={(event) => { const files = [...(event.target.files ?? [])]; event.target.value = ""; if (files.length) void upload(files); }} />+ </ToolPageActions>+ </ToolPageHeader>+ <div+ className={cn("relative min-h-0 flex-1 overflow-y-auto", dragging && "bg-accent/5")}+ data-team-files={listing ? listing.entries.length : "loading"}+ onDragOver={(event) => { event.preventDefault(); setDragging(true); }}+ onDragLeave={() => setDragging(false)}+ onDrop={drop}+ >+ <div className="mx-auto w-full max-w-4xl p-4 sm:p-6">+ {team && <p className="mb-3 text-[13px] text-ink-secondary">{t("teamFiles.intro", { team })}</p>}+ <nav aria-label={t("teamFiles.title")} className="mb-3 flex flex-wrap items-center gap-1 text-[14px]">+ <button type="button" className="rounded px-1 text-ink-secondary hover:text-ink" onClick={() => { setPreview(null); setFolder(""); }}>{t("teamFiles.title")}</button>+ {crumbs.map((part, index) => (+ <span key={index} className="flex items-center gap-1">+ <span className="text-ink-secondary">/</span>+ <button type="button" aria-current={index === crumbs.length - 1 ? "page" : undefined} className="rounded px-1 text-ink hover:underline"+ onClick={() => { setPreview(null); setFolder(crumbs.slice(0, index + 1).join("/")); }}>{part}</button>+ </span>+ ))}+ </nav>+ {listing && <p data-team-files-used={`${listing.used}/${listing.cap}`} className="mb-3 text-[12px] text-ink-secondary">{t("teamFiles.used", { used: formatSize(listing.used), cap: formatSize(listing.cap) })}</p>}+ {uploading && <p role="status" className="mb-2 text-[13px] text-ink-secondary">{t("teamFiles.uploading", { name: uploading })}</p>}+ {problem && <p role="alert" className="mb-2 text-[13px] text-danger">{problem}</p>}+ {editing && (+ <form className="mb-3 flex items-center gap-2" onSubmit={(event) => { event.preventDefault(); submitName(); }}>+ <input autoFocus aria-label={t(editing.kind === "folder" ? "teamFiles.folderName" : "teamFiles.newName")} className="min-w-0 flex-1 rounded-lg bg-inset px-3 py-2 text-[13px] text-ink outline-none focus:ring-1 focus:ring-accent" value={name} onChange={(event) => setName(event.target.value)} />+ <button type="submit" className="ui-button ui-button-primary">{t(editing.kind === "folder" ? "teamFiles.create" : "teamFiles.save")}</button>+ <button type="button" className="ui-button" onClick={() => setEditing(null)}>{t("common.cancel")}</button>+ </form>+ )}+ {dragging && <p className="mb-2 text-center text-[13px] text-accent-text">{t("teamFiles.drop")}</p>}+ {failed && !listing ? (+ <section role="alert" className="px-6 py-16 text-center">+ <p className="text-[14px] text-ink-secondary">{t("teamFiles.loadFailed")}</p>+ <button type="button" className="ui-button mt-4" onClick={() => void load(folder)}>{t("common.tryAgain")}</button>+ </section>+ ) : listing && listing.entries.length === 0 ? (+ <section aria-label={t("teamFiles.empty.title")} className="rounded-xl border border-dashed border-hairline px-6 py-12 text-center">+ <div className="mx-auto mb-3 flex size-11 items-center justify-center rounded-2xl bg-accent/10 text-accent"><Folder size={20} /></div>+ <h2 className="text-[16px] font-semibold text-ink">{t("teamFiles.empty.title")}</h2>+ <p className="mx-auto mt-1 max-w-sm text-[13px] leading-relaxed text-ink-secondary">{t("teamFiles.empty.body")}</p>+ </section>+ ) : listing ? (+ <ul aria-label={t("teamFiles.title")} className="divide-y divide-hairline/40 overflow-hidden rounded-xl border border-hairline/40 bg-card">+ {listing.entries.map((entry) => {+ const line = changedLine(entry);+ const Icon = entry.kind === "folder" ? Folder : previewKind(entry.name) === "picture" ? ImageIcon : FileText;+ return (+ <li key={entry.path} data-team-file={entry.path} className="flex items-center gap-3 px-3 py-2.5">+ <Icon size={18} className="shrink-0 text-ink-secondary" aria-hidden />+ <button type="button" className="min-w-0 flex-1 text-left" aria-label={t("teamFiles.open", { name: entry.name })} onClick={() => void open(entry)}>+ <span className="block truncate text-[14px] text-ink">{entry.name}</span>+ <span className="block truncate text-[12px] text-ink-secondary">{[entry.kind === "file" ? formatSize(entry.size) : "", line].filter(Boolean).join(" · ")}</span>+ </button>+ {entry.kind === "file" && <a className="ui-icon-button" href={fileUrl(entry.path, true)} download={entry.name} aria-label={t("teamFiles.download")} title={t("teamFiles.download")}><Download size={15} /></a>}+ {entry.canDelete && <button type="button" className="ui-icon-button" aria-label={t("teamFiles.rename")} title={t("teamFiles.rename")} onClick={() => { setName(entry.name); setEditing({ kind: "rename", entry }); }}><Pencil size={15} /></button>}+ {entry.canDelete && <button type="button" className="ui-icon-button" aria-label={t("teamFiles.delete")} title={t("teamFiles.delete")} onClick={() => remove(entry)}><Trash2 size={15} /></button>}+ </li>+ );+ })}+ </ul>+ ) : null}+ {preview && (+ <section aria-label={preview.entry.name} className="mt-4 rounded-xl border border-hairline/40 bg-card">+ <header className="flex items-center gap-2 border-b border-hairline/40 px-3 py-2">+ <span className="min-w-0 flex-1 truncate text-[14px] font-medium text-ink">{preview.entry.name}</span>+ <a className="ui-icon-button" href={fileUrl(preview.entry.path, true)} download={preview.entry.name} aria-label={t("teamFiles.download")}><Download size={15} /></a>+ <button type="button" className="ui-icon-button" aria-label={t("teamFiles.closePreview")} onClick={() => setPreview(null)}><X size={15} /></button>+ </header>+ <div className="max-h-[60vh] overflow-auto p-3">+ {previewKind(preview.entry.name) === "picture" ? <img src={fileUrl(preview.entry.path)} alt={preview.entry.name} className="mx-auto max-h-[56vh] max-w-full" />+ : preview.tooLarge ? <p className="text-[13px] text-ink-secondary">{t("teamFiles.previewTooLarge")}</p>+ : preview.text !== undefined ? <pre data-team-file-preview="" className="whitespace-pre-wrap break-words text-[13px] text-ink">{preview.text}</pre>+ : <p className="text-[13px] text-ink-secondary">{t("teamFiles.noPreview")}</p>}+ </div>+ </section>+ )}+ </div>+ </div>+ </ToolPage>+ );+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex 474ad685b1..d7a194da6a 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -3911,6 +3911,7 @@"sidebar.update.restartAction": "Neu starten","sidebar.update.retryAction": "Erneut versuchen","sidebar.nav.publishedApps": "Veröffentlichte Apps",+ "sidebar.nav.teamFiles": "Teamdateien","settings.advancedMode.subtitle": "Zeigt auf diesem Gerät jede technische Einstellung: Nutzung und Tokens, den Inspektor und andere Werkzeuge für Bastler. Schalte ihn für eine einfachere App aus. Gelöscht wird so oder so nichts.","settings.analytics.link": "Alles ansehen, was gesendet wird","settings.analytics.subtitle": "Anonyme Produktereignisse und einmal am Tag eine Zählung dessen, was eingerichtet ist: welche Anbieter einen Schlüssel haben (nie der Schlüssel) und wie viele Bots, Räume, Routinen und Computer. Nie Gespräche, Prompts, Dateiinhalte, Namen oder Adressen. Deine E-Mail wird nur angehängt, wenn du sie bei der Einrichtung geteilt hast oder im Cloud-Pro-Fenster, bei MausBot Cloud angemeldet, Upgrade, Verwalten oder Pläne vergleichen wählst (die E-Mail deines Cloud-Kontos).",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 8eedb385af..34681a0523 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7094,6 +7094,46 @@"webPanels.page.pageGone": "This page can't be shown right now","webPanels.page.refusedBody": "{site} doesn't allow other apps to show it. Open it in your browser instead.","sidebar.nav.publishedApps": "Published apps",+ "sidebar.nav.teamFiles": "Team files",+ "teamFiles.title": "Team files",+ "teamFiles.intro": "One folder for everyone on {team} and its bots: records, client lists, templates, brand assets.",+ "teamFiles.upload": "Upload",+ "teamFiles.newFolder": "New folder",+ "teamFiles.folderName": "Folder name",+ "teamFiles.create": "Create",+ "teamFiles.download": "Download",+ "teamFiles.rename": "Rename",+ "teamFiles.newName": "New name",+ "teamFiles.save": "Save",+ "teamFiles.delete": "Delete",+ "teamFiles.deleteConfirm": "Delete {name}? This can't be undone.",+ "teamFiles.actions": "More for {name}",+ "teamFiles.open": "Open {name}",+ "teamFiles.closePreview": "Close preview",+ "teamFiles.noPreview": "No preview for this kind of file. Download it to open it.",+ "teamFiles.previewTooLarge": "Too large to preview here. Download it to open it.",+ "teamFiles.empty.title": "Nothing here yet",+ "teamFiles.empty.body": "Drop files here or upload them. Everyone on the team and every bot can read them.",+ "teamFiles.drop": "Drop to upload here",+ "teamFiles.used": "{used} of {cap} used",+ "teamFiles.loadFailed": "Team files couldn't be loaded.",+ "teamFiles.uploading": "Uploading {name}…",+ "teamFiles.uploaded": "Uploaded by {person} · {when}",+ "teamFiles.made": "Made by {person} · {when}",+ "teamFiles.changedWith": "Changed by {person} with {bot} · {when}",+ "teamFiles.changedBy": "Changed by {person} · {when}",+ "teamFiles.someone": "someone",+ "teamFiles.error.tooLarge": "A file may be at most {mb} MB.",+ "teamFiles.error.full": "Team files are full ({gb} GB). Remove files to make room.",+ "teamFiles.error.exists": "Something with that name is already there.",+ "teamFiles.error.forbidden": "Only an admin, or whoever uploaded it, can do that.",+ "teamFiles.error.notFound": "That isn't there any more.",+ "teamFiles.error.badName": "That name can't be used.",+ "teamFiles.error.failed": "That didn't work. Try again.",+ "botAccess.teamFiles.title": "Can edit team files",+ "botAccess.teamFiles.on": "Adds and changes files in Team files from any chat, private chats too.",+ "botAccess.teamFiles.off": "Reads Team files but can't change them.",+ "botAccess.teamFiles.adminsOnly": "Only an admin can change this.","publishedApps.title": "Published apps","publishedApps.empty.title": "Nothing published yet","publishedApps.empty.body": "Sites and apps your bots put online show up here. Ask a bot to build a site or app and publish it.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex 2bc84006c6..5b237bf8e1 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -6317,6 +6317,7 @@"sidebar.update.restartAction": "Reiniciar","sidebar.update.retryAction": "Reintentar","sidebar.nav.publishedApps": "Apps publicadas",+ "sidebar.nav.teamFiles": "Archivos del equipo","settings.followUp.subtitle": "Meterlo añade tu mensaje a lo que el bot hace ahora; ponerlo en cola lo ejecuta cuando termina el turno. {key} hace lo otro para un solo mensaje, y la flecha junto a Enviar también puede reiniciar el turno. Solo en este dispositivo.","settings.openAtLogin.subtitle": "Abre {app} cuando inicias sesión en este ordenador, para que tus bots y rutinas estén listos sin abrirlo tú.","settings.simple.advancedMode": "Muestra todos los controles, incluidas herramientas para creadores. No se borra nada en ningún caso.",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 6f78654fac..723eb7437e 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3708,6 +3708,7 @@"sidebar.update.restartAction": "Redémarrer","sidebar.update.retryAction": "Réessayer","sidebar.nav.publishedApps": "Apps publiées",+ "sidebar.nav.teamFiles": "Fichiers de l'équipe","settings.advancedMode.subtitle": "Affiche chaque réglage technique sur cet appareil : usage et tokens, l'inspecteur et d'autres outils pour bâtisseurs. Désactivez-le pour une app plus simple. Rien n'est supprimé dans un cas comme dans l'autre.","settings.analytics.link": "Voir tout ce qui est envoyé","settings.analytics.subtitle": "Des événements produit anonymes et, une fois par jour, un décompte de ce qui est configuré : quels fournisseurs ont une clé (jamais la clé) et combien de bots, salons, routines et ordinateurs. Jamais de conversations, prompts, contenus de fichiers, noms ou adresses. Votre email n'est joint que si vous l'avez partagé pendant la configuration, ou si vous choisissez de passer à un forfait, de le gérer ou de comparer les forfaits dans la fenêtre Cloud Pro en étant connecté à MausBot Cloud (l'email de votre compte Cloud).",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex e14db2b7f7..ddb24a7bd5 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -3562,6 +3562,7 @@"sidebar.update.restartAction": "रीस्टार्ट करें","sidebar.update.retryAction": "फिर से कोशिश करें","sidebar.nav.publishedApps": "प्रकाशित ऐप्स",+ "sidebar.nav.teamFiles": "टीम फ़ाइलें","settings.advancedMode.subtitle": "इस डिवाइस पर हर तकनीकी नियंत्रण दिखाएँ: उपयोग और टोकन, इंस्पेक्टर और बिल्डर्स के लिए दूसरे टूल। आसान ऐप के लिए इसे बंद करें। दोनों ही तरह कुछ भी मिटता नहीं।","settings.analytics.link": "वह सब देखें जो यह भेजता है","settings.analytics.subtitle": "अनाम उत्पाद इवेंट और दिन में एक बार इस बात की गिनती कि क्या सेट अप है: किन प्रदाताओं के पास कुंजी है (कुंजी कभी नहीं) और कितने बॉट, रूम, रूटीन और कंप्यूटर। बातचीत, प्रॉम्प्ट, फ़ाइलों की सामग्री, नाम या पते कभी नहीं। आपका ईमेल तभी जुड़ता है जब आपने सेटअप के दौरान उसे साझा किया हो, या MausBot Cloud में साइन इन रहते हुए Cloud Pro पॉपअप पर अपग्रेड, प्रबंधन या प्लान की तुलना चुनी हो (आपके Cloud खाते का ईमेल)।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 44c992df81..95122883d0 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -6892,6 +6892,7 @@"sidebar.update.restartAction": "Riavvia","sidebar.update.retryAction": "Riprova","sidebar.nav.publishedApps": "App pubblicate",+ "sidebar.nav.teamFiles": "File del team","settings.followUp.subtitle": "Inserirlo aggiunge il tuo messaggio a ciò che il bot sta facendo; metterlo in coda lo esegue alla fine del turno. {key} fa l'altra cosa per un solo messaggio, e la freccia accanto a Invia può anche riavviare il turno. Solo su questo dispositivo.","settings.openAtLogin.subtitle": "Apre {app} quando accedi a questo computer, così bot e routine sono pronti senza aprirlo tu.","settings.simple.advancedMode": "Mostra ogni controllo, compresi gli strumenti per chi costruisce. Non si cancella nulla in nessun caso.",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 9743408d2e..bdd48f57ac 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -7886,6 +7886,7 @@"settings.theme.lightOrDark": "ライトまたはダーク","settings.userBubbles.simpleTitle": "自分のメッセージにボットの色を使う","sidebar.nav.publishedApps": "公開したアプリ",+ "sidebar.nav.teamFiles": "チームのファイル","settings.simple.themes.browse": "テーマを見る","phone.pair.rowTitle": "お使いのスマホ","phone.pair.rowLine": "App Store または Google Play からスマホに {app} をインストールし、ここでペアリングします。",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex f8cdd2515c..81018bfa10 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7569,6 +7569,7 @@"settings.userBubbles.simpleTitle": "내 메시지에 봇 색상 사용","sidebar.account.moving": "내 클라우드로 이동 중…","sidebar.nav.publishedApps": "게시한 앱",+ "sidebar.nav.teamFiles": "팀 파일","settings.followUp.subtitle": "끼워 넣으면 봇이 지금 하는 일에 메시지를 더하고, 대기열에 넣으면 턴이 끝난 뒤 실행합니다. {key}는 메시지 하나에 대해 다른 방식을 쓰며, 보내기 옆 화살표로 턴을 다시 시작할 수도 있습니다. 이 기기에서만.","settings.simple.followUp": "{key}는 메시지 하나에 대해 다른 방식을 씁니다.","settings.simple.themes.browse": "테마 둘러보기",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 890dbc48b2..28ddce43b5 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -7025,6 +7025,7 @@"sidebar.update.restartAction": "Uruchom ponownie","sidebar.update.retryAction": "Ponów","sidebar.nav.publishedApps": "Opublikowane aplikacje",+ "sidebar.nav.teamFiles": "Pliki zespołu","defaultBot.show.subtitle": "Twój pomocnik do wszystkiego w aplikacji. Ukryty dalej pracuje, a wyszukiwanie wciąż go znajduje.","settings.followUp.subtitle": "Włączenie dodaje wiadomość do tego, co bot teraz robi; kolejka uruchamia ją po końcu tury. {key} robi to drugie dla pojedynczej wiadomości, a strzałka obok Wyślij może też zacząć turę od nowa. Tylko na tym urządzeniu.","settings.openAtLogin.subtitle": "Otwiera {app} po zalogowaniu się do tego komputera, aby boty i rutyny były gotowe bez ręcznego otwierania.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 1c8e1c7cbd..04d3ee20ab 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6745,6 +6745,46 @@"webPanels.page.pageGone": "Esta página não pode ser mostrada agora","webPanels.page.refusedBody": "O site {site} não permite que outros apps mostrem seu conteúdo. Abra-o no navegador.","sidebar.nav.publishedApps": "Apps publicados",+ "sidebar.nav.teamFiles": "Arquivos da equipe",+ "teamFiles.title": "Arquivos da equipe",+ "teamFiles.intro": "Uma pasta para todos em {team} e seus bots: registros, listas de clientes, modelos, materiais da marca.",+ "teamFiles.upload": "Enviar",+ "teamFiles.newFolder": "Nova pasta",+ "teamFiles.folderName": "Nome da pasta",+ "teamFiles.create": "Criar",+ "teamFiles.download": "Baixar",+ "teamFiles.rename": "Renomear",+ "teamFiles.newName": "Novo nome",+ "teamFiles.save": "Salvar",+ "teamFiles.delete": "Excluir",+ "teamFiles.deleteConfirm": "Excluir {name}? Isso não pode ser desfeito.",+ "teamFiles.actions": "Mais opções para {name}",+ "teamFiles.open": "Abrir {name}",+ "teamFiles.closePreview": "Fechar visualização",+ "teamFiles.noPreview": "Não há visualização para este tipo de arquivo. Baixe-o para abrir.",+ "teamFiles.previewTooLarge": "Grande demais para visualizar aqui. Baixe-o para abrir.",+ "teamFiles.empty.title": "Nada aqui ainda",+ "teamFiles.empty.body": "Solte arquivos aqui ou envie-os. Todos na equipe e todos os bots podem lê-los.",+ "teamFiles.drop": "Solte para enviar aqui",+ "teamFiles.used": "{used} de {cap} usados",+ "teamFiles.loadFailed": "Não foi possível carregar os arquivos da equipe.",+ "teamFiles.uploading": "Enviando {name}…",+ "teamFiles.uploaded": "Enviado por {person} · {when}",+ "teamFiles.made": "Criada por {person} · {when}",+ "teamFiles.changedWith": "Alterado por {person} com {bot} · {when}",+ "teamFiles.changedBy": "Alterado por {person} · {when}",+ "teamFiles.someone": "alguém",+ "teamFiles.error.tooLarge": "Um arquivo pode ter no máximo {mb} MB.",+ "teamFiles.error.full": "Os arquivos da equipe estão cheios ({gb} GB). Remova arquivos para liberar espaço.",+ "teamFiles.error.exists": "Já existe algo com esse nome.",+ "teamFiles.error.forbidden": "Só um admin, ou quem enviou, pode fazer isso.",+ "teamFiles.error.notFound": "Isso não está mais aqui.",+ "teamFiles.error.badName": "Esse nome não pode ser usado.",+ "teamFiles.error.failed": "Não funcionou. Tente de novo.",+ "botAccess.teamFiles.title": "Pode editar os arquivos da equipe",+ "botAccess.teamFiles.on": "Adiciona e altera arquivos em Arquivos da equipe a partir de qualquer conversa, inclusive as privadas.",+ "botAccess.teamFiles.off": "Lê os Arquivos da equipe, mas não pode alterá-los.",+ "botAccess.teamFiles.adminsOnly": "Só um admin pode mudar isso.","publishedApps.title": "Apps publicados","publishedApps.empty.title": "Nada publicado ainda","publishedApps.empty.body": "Os sites e apps que seus bots colocam no ar aparecem aqui. Peça a um bot para criar um site ou app e publicá-lo.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex a9ff1c91ce..af25ab6fa5 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -7080,6 +7080,7 @@"sidebar.update.restartAction": "Перезапустить","sidebar.update.retryAction": "Повторить","sidebar.nav.publishedApps": "Опубликованные приложения",+ "sidebar.nav.teamFiles": "Файлы команды","settings.followUp.subtitle": "Добавление вносит сообщение в то, что бот делает сейчас; очередь запускает его после окончания хода. {key} делает другое для одного сообщения, а стрелка рядом с «Отправить» может также перезапустить ход. Только на этом устройстве.","settings.openAtLogin.subtitle": "Открывает {app} при входе в этот компьютер, чтобы боты и рутины были готовы без ручного запуска.","settings.simple.advancedMode": "Показывает все настройки, включая инструменты для разработчиков. Ничего не удаляется в любом случае.",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 827c40b2e3..5e2733c0d9 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -5815,6 +5815,7 @@"sidebar.update.restartAction": "Yeniden başlat","sidebar.update.retryAction": "Tekrar dene","sidebar.nav.publishedApps": "Yayınlanan uygulamalar",+ "sidebar.nav.teamFiles": "Ekip dosyaları","settings.analytics.link": "Gönderdiği her şeyi gör","settings.analytics.subtitle": "Anonim ürün olayları ve günde bir kez neyin kurulu olduğunun sayımı: hangi sağlayıcıların anahtarı var (asla anahtarın kendisi) ve kaç bot, oda, rutin ve bilgisayar. Asla konuşmalar, istemler, dosya içerikleri, adlar veya adresler. E-postan yalnızca kurulumda paylaştıysan ya da MausBot Cloud'a giriş yapmışken Cloud Pro penceresinde yükseltme, yönetme veya plan karşılaştırmayı seçersen eklenir (Cloud hesabının e-postası).","settings.followUp.subtitle": "Ekleme mesajını botun şu an yaptığına katar; sıraya alma tur bitince çalıştırır. {key} tek bir mesaj için diğerini yapar, Gönder'in yanındaki ok da turu yeniden başlatabilir. Yalnızca bu cihazda.",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 7009669e87..5113d5cda2 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -3986,6 +3986,7 @@"sidebar.update.restartAction": "Перезапустити","sidebar.update.retryAction": "Повторити","sidebar.nav.publishedApps": "Опубліковані застосунки",+ "sidebar.nav.teamFiles": "Файли команди","settings.advancedMode.subtitle": "Показувати на цьому пристрої всі технічні налаштування: використання й токени, інспектор та інші інструменти для розробників. Вимкніть для простішого застосунку. Нічого не видаляється в жодному разі.","settings.analytics.link": "Переглянути все, що надсилається","settings.analytics.subtitle": "Анонімні події продукту та раз на день підрахунок того, що налаштовано: які провайдери мають ключ (ніколи сам ключ) і скільки ботів, кімнат, рутин і комп’ютерів. Ніколи розмови, запити, вміст файлів, імена чи адреси. Ваша пошта додається, лише якщо ви поділилися нею під час налаштування або вибрали оновлення, керування чи порівняння планів у вікні Cloud Pro, увійшовши в MausBot Cloud (пошта вашого акаунта Cloud).",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 91e686dad6..d5dc226b45 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -5815,6 +5815,7 @@"sidebar.update.restartAction": "Khởi động lại","sidebar.update.retryAction": "Thử lại","sidebar.nav.publishedApps": "Ứng dụng đã xuất bản",+ "sidebar.nav.teamFiles": "Tệp của nhóm","settings.analytics.link": "Xem mọi thứ được gửi đi","settings.analytics.subtitle": "Sự kiện sản phẩm ẩn danh và mỗi ngày một lần đếm những gì đã thiết lập: nhà cung cấp nào có khóa (không bao giờ là khóa) và bao nhiêu bot, phòng, quy trình và máy tính. Không bao giờ gửi cuộc trò chuyện, lời nhắc, nội dung tệp, tên hay địa chỉ. Email của bạn chỉ được đính kèm nếu bạn đã chia sẻ khi thiết lập, hoặc khi bạn chọn nâng cấp, quản lý hay so sánh gói trên cửa sổ Cloud Pro lúc đã đăng nhập MausBot Cloud (email tài khoản Cloud của bạn).","settings.followUp.subtitle": "Đưa vào sẽ thêm tin nhắn vào việc bot đang làm; xếp hàng sẽ chạy khi lượt kết thúc. {key} làm cách còn lại cho một tin nhắn, và mũi tên cạnh Gửi cũng có thể bắt đầu lại lượt. Chỉ trên thiết bị này.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex ec5b260e4e..1e1f0f1a8f 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -10077,6 +10077,7 @@"settings.font.line": "在這台裝置上取代主題字型。","settings.profile.awayEmails": "我不在時寄電子郵件給我","sidebar.nav.publishedApps": "已發佈的 App",+ "sidebar.nav.teamFiles": "團隊檔案","phone.pair.rowTitle": "你的手機","phone.pair.rowLine": "從 App Store 或 Google Play 在手機上安裝 {app},然後在這裡配對。","phone.otherPlace.line": "與 {place} 配對的手機",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 24e2bba039..c3b8b527e2 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -9900,6 +9900,7 @@"accounts.browserOpen": "重新打开浏览器","accounts.signInAgain": "重新登录","sidebar.nav.publishedApps": "已发布的应用",+ "sidebar.nav.teamFiles": "团队文件","settings.simple.themes.browse": "浏览主题","phone.pair.rowTitle": "你的手机","phone.pair.rowLine": "从 App Store 或 Google Play 在手机上安装 {app},然后在这里配对。",diff --git a/src/state/bot-patch-queue.ts b/src/state/bot-patch-queue.tsindex 0185f138d2..9253c65443 100644--- a/src/state/bot-patch-queue.ts+++ b/src/state/bot-patch-queue.ts@@ -30,6 +30,7 @@ export type BotUpdatePatch = Partial<| "voiceNotes"| "voiceNoteEveryReply"| "xResearch"+ | "teamFilesEdit"| "toolsOff"| "pinned"| "hidden"diff --git a/src/state/store.tsx b/src/state/store.tsxindex bb081ec647..95070973ef 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -309,7 +309,7 @@ export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" |speakReplies?: boolean;replyStyle?: import("../../shared/wire").WireBot["replyStyle"];voice?: string; liveVoice?: string; // liveVoice: the bot's own Live call voice; "" or absent: the app's- voiceNotes?: boolean; xResearch?: boolean; toolsOff?: import("../../shared/tool-groups").ToolGroup[]; voiceNoteEveryReply?: boolean | null; // null or absent: follows the Voice setting+ voiceNotes?: boolean; xResearch?: boolean; teamFilesEdit?: boolean; toolsOff?: import("../../shared/tool-groups").ToolGroup[]; voiceNoteEveryReply?: boolean | null; // null or absent: follows the Voice settingmemoryEnabled?: boolean;pinned?: boolean;hidden?: boolean;@@ -507,7 +507,7 @@ export interface AppState {liveCallVersion: number;liveCallLookupSeq: number;selectedId: string;- activeView: "chat" | "team-map" | "routines" | "files" | "web-panel" | "published-apps";+ activeView: "chat" | "team-map" | "routines" | "files" | "web-panel" | "published-apps" | "team-files";/** Folders a finished move left on this computer, for Files to offer sharing. */filesSuggest: string[] | null; webPanelId?: string;routines: Routine[];@@ -590,7 +590,7 @@ export type Action =| { type: "botsOrdered"; botIds: string[] } | { type: "groupsOrdered"; groupIds: string[] }| { type: "sectionDeleted"; section: string; sections: string[] }| { type: "showRoutines"; section?: "schedule" | "logs"; view?: "calendar" | "list"; botId?: string; routineId?: string; runStatus?: RoutineRunStatusFilter }- | { type: "showTeamMap" } | { type: "showPublishedApps" } | { type: "showWebPanel"; id: string }+ | { type: "showTeamMap" } | { type: "showPublishedApps" } | { type: "showTeamFiles" } | { type: "showWebPanel"; id: string }| { type: "showFiles"; suggest?: string[] }| { type: "showChat" }| { type: "routinesHydrated"; routines: Routine[]; runs: RoutineRun[]; since?: number }@@ -943,10 +943,10 @@ export function reducer(state: AppState, action: Action): AppState {case "forkPanelMessage": case "forkPanelActive": case "closeForkPanel":return reduceForkPanel(state, action);case "showTeamMap":- case "showFiles": case "showWebPanel": case "showPublishedApps":+ case "showFiles": case "showWebPanel": case "showPublishedApps": case "showTeamFiles":return {...state,- activeView: action.type === "showFiles" ? "files" : action.type === "showWebPanel" ? "web-panel" : action.type === "showPublishedApps" ? "published-apps" : "team-map",+ activeView: action.type === "showFiles" ? "files" : action.type === "showWebPanel" ? "web-panel" : action.type === "showPublishedApps" ? "published-apps" : action.type === "showTeamFiles" ? "team-files" : "team-map",filesSuggest: action.type === "showFiles" && action.suggest?.length ? action.suggest : null, webPanelId: action.type === "showWebPanel" ? action.id : state.webPanelId,settingsOpen: false, computerOpen: false, inspectorOpen: false, activityOpen: false, appSettingsOpen: false, pluginsOpen: false,};@@ -2194,7 +2194,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {};const wrapped: React.Dispatch<Action> = (action) => {- store.flushFrames(); if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps"].includes(action.type)) selectionRevision.current++;+ store.flushFrames(); if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps", "showTeamFiles"].includes(action.type)) selectionRevision.current++;// Pin before any await or optimistic state change.action = pinBotThreadAction(action, stateRef.current.bots);if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };