Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(team-board): items on room threads (store, states, routes) behind a switch
milind-soni05384419c480
diff --git a/docs/team-board.md b/docs/team-board.mdnew file mode 100644index 0000000000..2ddcabbfd9--- /dev/null+++ b/docs/team-board.md@@ -0,0 +1,74 @@+# Team Board++A work layer over a Team Cloud's rooms. A room thread can carry one **board item**: a title, a state, what it waits+for, labels, and which bot may take it. Rooms and threads stay what they are; the item only says where the work in that+thread stands. Nothing new is shown to anyone: a person sees an item exactly when they can see its room thread.++It is off unless an Owner or Admin turns on **Board** in Settings → Features (`features.teamBoard` in `config.json`).+The switch exists only on a Team Cloud; anywhere else, and while it is off, the routes below answer 404.++This release has the items, their states, the routes and the live frame. Bots taking items, the bot tools, the Board+page and repeating items come later.++## The item++`BoardItem` in `shared/board.ts`, one per room thread, keyed by its `threadId`:++| Field | |+|---|---|+| `title` | One line, at most 120 characters. |+| `state` | See below. |+| `needs` | Thread ids of other items in the same room that must be `done` first; at most 10, never a loop. |+| `labels` | At most 12; key of at most 32 of `a-z 0-9 _ -`, value of at most 80 characters. |+| `forBotId` | Only this member bot of the room may take it; otherwise any of them. |+| `holder` | The bot working on it, and since when (while `working` or `needs_person`). |+| `attempts` | Times a bot took it since it was made or reopened. |+| `question` | What its bot asked a person (while `needs_person`). |+| `result` | What came of it, at most 2,000 characters. |+| `createdBy` | The person or bot who made it. |++A room holds at most 200 items that are not settled.++## States++`waiting` → `ready` → `working` → `done` | `failed` | `cancelled`, with `needs_person` beside `working`.++- A new item is `waiting` while any need is not `done`, else `ready`. A waiting item becomes ready by itself when its+ last need is done; a failed or cancelled need readies nothing.+- `ready` → `working`: the server gives it to a bot (later releases).+- `working` → `done`, `failed`, `needs_person` (the bot asked someone) or back to `ready` (released, or the turn ended+ without settling it). `needs_person` → `working` when the person replies, `ready` when a person releases it, or+ `cancelled`.+- A person may cancel any open item, mark any open item done, release one waiting on a person, and reopen a settled+ one (its tries start again from 0, and it waits again if a need is not done). A bot may cancel an open item it made.+- An item that is removed, or whose thread or room is deleted, stops being needed: what waited only on it is ready.++Every other move is refused with 409 `board_bad_move`. The rules are `server/board/state.ts`.++## Routes++For every member and admin who is signed in (`server/routes/board.ts`). Writing needs what writing in the room needs:+chat access to each of its bots.++- `GET /api/board[?groupId=]` → `{ items }`, the ones the caller can see, oldest first.+- `POST /api/board/items` `{ groupId, title, text?, needs?, labels?, forBotId?, threadId? }` → 201 `{ item }`. Without+ `threadId` it opens a new thread in the room, without making it the room's current one, whose first line is `text`+ (or the title), written as the caller's; no bot answers it. With `threadId`, that thread of the room becomes the item.+- `PATCH /api/board/items/:threadId` `{ move?: "cancel" | "reopen" | "release" | "done", title?, labels?, needs?,+ forBotId?, result? }` → `{ item }`. `labels` replaces them all; `needs` changes only before a bot takes the item;+ `forBotId: null` lets any member bot take it.+- `DELETE /api/board/items/:threadId` removes the item; its thread and everything said there stay.++Errors carry a `code`: `board_bad_input` (400), `board_not_found` (404, also for an item the caller cannot see),+`board_bad_move`, `board_exists`, `board_cycle`, `board_full` (409).++## Live frame++`{ kind: "board.item", groupId, threadId, item }` on every change (`item: null` when it is removed), sent only to people+who can see that room thread.++## Storage++`board.json` in the data folder, written whole and readable only by its owner: `{ version: 1, items, repeats }`. A new+file, so older versions simply do not read it. A file that does not parse is an empty board, and an item that does not+parse is left out.diff --git a/packages/phone-protocol/src/board.ts b/packages/phone-protocol/src/board.tsnew file mode 100644index 0000000000..bdd03c987f--- /dev/null+++ b/packages/phone-protocol/src/board.ts@@ -0,0 +1,115 @@+// The Team Board (docs/team-board.md): work items on a Team Cloud's room threads, one item per thread, keyed by that+// thread. A person sees an item exactly when they can see its room thread.++/** Where an item is. `waiting`: some item it needs is not done yet. `ready`: a bot may take it. `working`: a bot holds it+ * and runs a turn on it. `needs_person`: its bot asked a person and waits for the reply. The last three are settled. */+export type BoardItemState = "waiting" | "ready" | "working" | "needs_person" | "done" | "failed" | "cancelled";++export const BOARD_OPEN_STATES: readonly BoardItemState[] = ["waiting", "ready", "working", "needs_person"];+export const BOARD_SETTLED_STATES: readonly BoardItemState[] = ["done", "failed", "cancelled"];++export interface BoardItemHolder {+ botId: string;+ /** When the bot took it, or last went back to it after a person's reply; epoch ms. */+ since: number;+}++export interface BoardItemQuestion {+ text: string;+ askedAt: number;+ /** The person key of whoever was asked; absent when anyone who sees the room may answer. */+ person?: string;+}++export interface BoardItemCreator {+ kind: "person" | "bot";+ /** A person key or a bot id. */+ id: string;+ name: string;+}++export interface BoardItem {+ /** The room thread the work happens in; the item's id. */+ threadId: string;+ groupId: string;+ title: string;+ state: BoardItemState;+ /** Thread ids of items in the same room that must be `done` before this one is ready. */+ needs: string[];+ labels: Record<string, string>;+ /** Only this bot may take it; otherwise any member bot of the room. */+ forBotId?: string;+ /** Set while `working` or `needs_person`. */+ holder?: BoardItemHolder;+ /** Times a bot took it since it was made or last reopened. */+ attempts: number;+ question?: BoardItemQuestion;+ /** What came of it, set when it is settled. */+ result?: string;+ createdBy: BoardItemCreator;+ createdAt: number;+ updatedAt: number;+}++export const BOARD_LIMITS = {+ titleMax: 120,+ /** The first line of a new item's thread. */+ textMax: 20_000,+ needsMax: 10,+ labelsMax: 12,+ labelKeyMax: 32,+ labelValueMax: 80,+ resultMax: 2_000,+ questionMax: 2_000,+ /** Items not yet settled in one room. */+ openPerRoom: 200,+ /** Items one bot call may add. */+ itemsPerCall: 15,+} as const;++/** A label key: lowercase letters, digits, `_` and `-`. */+export const BOARD_LABEL_KEY = /^[a-z0-9_-]{1,32}$/;++/** What a person may do to an item: `cancel` an open one, `reopen` a settled one, `release` one waiting on a person back+ * to ready, or mark it `done` themselves. */+export type BoardPersonMove = "cancel" | "reopen" | "release" | "done";++/** POST /api/board/items. Without `threadId` a new room thread is opened whose first line is `text`, the caller's;+ * with it, that existing thread of the room becomes the item. */+export interface BoardItemCreateBody {+ groupId: string;+ title: string;+ text?: string;+ needs?: string[];+ labels?: Record<string, string>;+ forBotId?: string;+ threadId?: string;+}++/** PATCH /api/board/items/:threadId. `labels` replaces the whole map; `forBotId: null` lets any member bot take it. */+export interface BoardItemPatchBody {+ move?: BoardPersonMove;+ title?: string;+ labels?: Record<string, string>;+ needs?: string[];+ forBotId?: string | null;+ result?: string;+}++/** GET /api/board (`?groupId=` for one room): the items the caller can see, oldest first. */+export interface BoardListResponse {+ items: BoardItem[];+}++export interface BoardItemResponse {+ item: BoardItem;+}++/** An item was made or changed (`item`), or removed (`item: null`; its thread stays). Sent only to people who can see+ * the room thread. */+export interface BoardItemFrame {+ kind: "board.item";+ groupId: string;+ threadId: string;+ item: BoardItem | null;+}diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex 44d4465638..3f46f1eeef 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -1,7 +1,7 @@/** The client-visible wire model for tasks, bots, messages and rooms. A field* here is one the server emits in every response and SSE frame that carries* the shape. */-import type { PresenceFrame } from "./team-presence.ts"; import type { HandoffCardFields } from "./sign-in-request.ts";+import type { PresenceFrame } from "./team-presence.ts"; import type { BoardItemFrame } from "./board.ts"; import type { HandoffCardFields } from "./sign-in-request.ts";import type { DataBroadcast } from "./data-surface.ts";import type { ApprovalMode } from "./approval-mode.ts";import type { ToolScope } from "./tool-scope.ts"; import type { ToolGroup } from "./tool-groups.ts";@@ -995,6 +995,6 @@ export type ServerFrame =/** A job is waiting for the phone whose registry key this is; it polls now. */| { kind: "device.job"; phone: string; id: string }/** Who is here on a Team Cloud (shared/team-presence.ts). */- | PresenceFrame+ | PresenceFrame | /** A Team Board item was made, changed or removed (board.ts). */ BoardItemFrame/** The config status object spread flat into the frame. */| ({ kind: "config" } & Record<string, unknown>);diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex b18263a8fe..d15ea03232 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -90,6 +90,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-asker-owns.e2e.test.ts","server/cloud-team-away.e2e.test.ts","server/cloud-team-bitwarden.e2e.test.ts",+ "server/cloud-team-board.e2e.test.ts","server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-check-backs.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex f03d388d63..2d12905090 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -230,6 +230,7 @@ describe("CI outputs", () => {"server/cloud-team-asker-owns.e2e.test.ts","server/cloud-team-away.e2e.test.ts","server/cloud-team-bitwarden.e2e.test.ts",+ "server/cloud-team-board.e2e.test.ts","server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-check-backs.e2e.test.ts",diff --git a/server/board/host.test.ts b/server/board/host.test.tsnew file mode 100644index 0000000000..aff408c2de--- /dev/null+++ b/server/board/host.test.ts@@ -0,0 +1,194 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { BOARD_LIMITS } from "../../shared/board.ts";+import { createBoard, type BoardChange, type NewBoardItem } from "./host.ts";+import { BOARD_FILE } from "./store.ts";++const T0 = 1_700_000_000_000;+const MIRA = { kind: "person" as const, id: "p_mira", name: "Mira" };+const PERSON = { kind: "person" as const, person: "p_mira" };+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function harness(dir = mkdtempSync(join(tmpdir(), "omb-board-host-"))) {+ if (!dirs.includes(dir)) dirs.push(dir);+ const h = {+ dir,+ clock: T0,+ rooms: new Map<string, { bots: string[]; threads: Set<string> }>([+ ["g1", { bots: ["scout", "payroll"], threads: new Set(["t1", "t2", "t3", "t4"]) }],+ ["g2", { bots: ["notes"], threads: new Set(["u1"]) }],+ ]),+ changes: [] as BoardChange[],+ opened: 0,+ };+ const board = createBoard({+ dataDir: dir,+ now: () => h.clock,+ alive: (groupId, threadId) => h.rooms.get(groupId)?.threads.has(threadId) ?? false,+ roomBots: (groupId) => h.rooms.get(groupId)?.bots ?? null,+ log: () => {},+ });+ board.onChange((change) => h.changes.push(change));+ const open = (groupId: string) => (title: string) => {+ const threadId = `new${++h.opened}`;+ h.rooms.get(groupId)!.threads.add(threadId);+ expect(title).toBeTruthy();+ return threadId;+ };+ const add = (over: Partial<NewBoardItem> = {}) => board.create({ groupId: "g1", title: "Item", createdBy: MIRA, ...over }, open(over.groupId ?? "g1"));+ return { h, board, add };+}++describe("the board", () => {+ it("makes an item on a new thread, saves it, and tells listeners", () => {+ const { h, add } = harness();+ const item = add({ title: "Write the brief", labels: { area: "billing" }, forBotId: "scout" });+ expect(item).toMatchObject({ threadId: "new1", groupId: "g1", title: "Write the brief", state: "ready", needs: [], labels: { area: "billing" }, forBotId: "scout", attempts: 0, createdBy: MIRA, createdAt: T0 });+ expect(h.changes).toEqual([{ groupId: "g1", threadId: "new1", item }]);+ expect(JSON.parse(readFileSync(join(h.dir, BOARD_FILE), "utf8")).items).toEqual([item]);+ expect(createBoard({ dataDir: h.dir, alive: () => true, roomBots: () => [] }).get("new1")).toEqual(item);+ });++ it("makes an item of a thread the room has, once", () => {+ const { board, add } = harness();+ expect(add({ threadId: "t1" }).threadId).toBe("t1");+ expect(() => add({ threadId: "t1" })).toThrow(expect.objectContaining({ status: 409, code: "board_exists" }));+ expect(() => add({ threadId: "u1" })).toThrow(expect.objectContaining({ status: 404 }));+ expect(() => add({ groupId: "nope" })).toThrow(expect.objectContaining({ status: 404 }));+ expect(() => board.create({ groupId: "g1", title: "x", createdBy: MIRA })).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ });++ it("checks everything before it opens a thread", () => {+ const { h, add } = harness();+ for (const bad of [{ title: "" }, { labels: { Bad: "x" } }, { forBotId: "notes" }, { needs: ["missing"] }]) {+ expect(() => add(bad), JSON.stringify(bad)).toThrow(expect.objectContaining({ status: 400 }));+ }+ expect(h.opened).toBe(0);+ });++ it("refuses the 201st open item in a room but not a settled one's place", () => {+ const { board, add } = harness();+ for (let i = 0; i < BOARD_LIMITS.openPerRoom; i += 1) add();+ expect(() => add()).toThrow(expect.objectContaining({ status: 409, code: "board_full" }));+ expect(add({ groupId: "g2" }).groupId).toBe("g2");+ board.move(board.list({ groupId: "g1" })[0]!.threadId, { move: "cancel" }, PERSON);+ expect(add().state).toBe("ready");+ });++ it("readies a waiting item when its last need is done, and says so", () => {+ const { h, board, add } = harness();+ const a = add({ title: "A" });+ const b = add({ title: "B" });+ const c = add({ title: "C", needs: [a.threadId, b.threadId] });+ expect(c.state).toBe("waiting");+ board.move(a.threadId, { move: "done" }, PERSON);+ expect(board.get(c.threadId)!.state).toBe("waiting");+ h.changes.length = 0;+ h.clock += 10;+ board.move(b.threadId, { move: "done", result: "Done by hand" }, PERSON);+ expect(board.get(c.threadId)).toMatchObject({ state: "ready", updatedAt: T0 + 10 });+ expect(h.changes.map((change) => [change.threadId, change.item?.state])).toEqual([[b.threadId, "done"], [c.threadId, "ready"]]);+ });++ it("a failed or cancelled need leaves its dependent waiting", () => {+ const { board, add } = harness();+ const a = add({ title: "A" });+ const c = add({ title: "C", needs: [a.threadId] });+ board.move(a.threadId, { move: "take", botId: "scout" }, { kind: "dispatcher" });+ board.move(a.threadId, { move: "failed", result: "No access" }, { kind: "bot", botId: "scout" });+ expect(board.get(c.threadId)!.state).toBe("waiting");+ board.move(c.threadId, { move: "cancel" }, PERSON);+ board.move(c.threadId, { move: "reopen" }, PERSON);+ expect(board.get(c.threadId)!.state).toBe("waiting");+ });++ it("changes fields: title, labels, the bot, needs before a bot takes it, a settled item's result", () => {+ const { board, add } = harness();+ const a = add({ title: "A" });+ const b = add({ title: "B" });+ const patched = board.patch(b.threadId, { title: "B2", labels: { area: "ops" }, forBotId: "payroll", needs: [a.threadId] }, PERSON);+ expect(patched).toMatchObject({ title: "B2", labels: { area: "ops" }, forBotId: "payroll", needs: [a.threadId], state: "waiting" });+ expect(board.patch(b.threadId, { forBotId: null, needs: [] }, PERSON)).toMatchObject({ state: "ready", needs: [] });+ expect(board.get(b.threadId)!.forBotId).toBeUndefined();+ expect(() => board.patch(a.threadId, { needs: [b.threadId] }, PERSON)).not.toThrow();+ expect(() => board.patch(b.threadId, { needs: [a.threadId] }, PERSON)).toThrow(expect.objectContaining({ code: "board_cycle" }));+ board.move(b.threadId, { move: "take", botId: "scout" }, { kind: "dispatcher" });+ expect(() => board.patch(b.threadId, { needs: [] }, PERSON)).toThrow(expect.objectContaining({ code: "board_bad_move" }));+ expect(() => board.patch(b.threadId, { result: "x" }, PERSON)).toThrow(expect.objectContaining({ code: "board_bad_move" }));+ board.move(b.threadId, { move: "done" }, PERSON);+ expect(board.patch(b.threadId, { result: "Sent on Friday" }, PERSON).result).toBe("Sent on Friday");+ expect(() => board.move("missing", { move: "cancel" }, PERSON)).toThrow(expect.objectContaining({ status: 404 }));+ });++ it("a refused change saves nothing and says nothing", () => {+ const { h, board, add } = harness();+ const a = add();+ h.changes.length = 0;+ const before = readFileSync(join(h.dir, BOARD_FILE), "utf8");+ expect(() => board.patch(a.threadId, { title: "Fine", labels: { BAD: "x" } }, PERSON)).toThrow();+ expect(() => board.move(a.threadId, { move: "reopen" }, PERSON)).toThrow();+ expect(readFileSync(join(h.dir, BOARD_FILE), "utf8")).toBe(before);+ expect(h.changes).toEqual([]);+ });++ it("removing an item leaves its thread and frees what needed it", () => {+ const { h, board, add } = harness();+ const a = add({ title: "A" });+ const c = add({ title: "C", needs: [a.threadId] });+ h.changes.length = 0;+ expect(board.remove(a.threadId)!.threadId).toBe(a.threadId);+ expect(board.get(c.threadId)).toMatchObject({ needs: [], state: "ready" });+ expect(h.changes.map((change) => [change.threadId, change.item?.state ?? null])).toEqual([[c.threadId, "ready"], [a.threadId, null]]);+ expect(h.rooms.get("g1")!.threads.has(a.threadId)).toBe(true);+ expect(board.remove(a.threadId)).toBeNull();+ });++ it("drops the items of a deleted thread or room when it next reads the board", () => {+ const { h, board, add } = harness();+ const a = add({ title: "A" });+ const c = add({ title: "C", needs: [a.threadId] });+ const other = add({ groupId: "g2", title: "Elsewhere" });+ h.rooms.get("g1")!.threads.delete(a.threadId);+ h.changes.length = 0;+ expect(board.list().map((item) => item.threadId)).toEqual([c.threadId, other.threadId]);+ expect(board.get(c.threadId)).toMatchObject({ state: "ready", needs: [] });+ expect(h.changes).toContainEqual({ groupId: "g1", threadId: a.threadId, item: null });+ h.rooms.delete("g2");+ expect(board.list().map((item) => item.threadId)).toEqual([c.threadId]);+ expect(JSON.parse(readFileSync(join(h.dir, BOARD_FILE), "utf8")).items.map((item: { threadId: string }) => item.threadId)).toEqual([c.threadId]);+ });++ it("lists oldest first, by room and state", () => {+ const { h, board, add } = harness();+ const a = add({ title: "A" });+ h.clock += 1;+ const b = add({ title: "B", groupId: "g2" });+ h.clock += 1;+ const c = add({ title: "C", needs: [a.threadId] });+ expect(board.list().map((item) => item.title)).toEqual(["A", "B", "C"]);+ expect(board.list({ groupId: "g1" }).map((item) => item.threadId)).toEqual([a.threadId, c.threadId]);+ expect(board.list({ state: "waiting" }).map((item) => item.threadId)).toEqual([c.threadId]);+ expect(b.groupId).toBe("g2");+ });++ it("starts empty from a corrupt file and writes a good one on the next change", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-board-host-"));+ writeFileSync(join(dir, BOARD_FILE), "{oops");+ const { board, add } = harness(dir);+ expect(board.list()).toEqual([]);+ add();+ expect(JSON.parse(readFileSync(join(dir, BOARD_FILE), "utf8")).items).toHaveLength(1);+ });++ it("hands out copies: changing one changes nothing on the board", () => {+ const { board, add } = harness();+ const a = add({ labels: { area: "ops" } });+ a.labels.area = "changed";+ board.get(a.threadId)!.needs.push("x");+ expect(board.get(a.threadId)).toMatchObject({ labels: { area: "ops" }, needs: [] });+ });+});diff --git a/server/board/host.ts b/server/board/host.tsnew file mode 100644index 0000000000..d659a9cfb3--- /dev/null+++ b/server/board/host.ts@@ -0,0 +1,195 @@+// The Team Board's items, kept in `board.json`: made, moved, changed and removed here, each change saved before it is+// told to `onChange` listeners. An item whose room or thread is gone is dropped the next time the board is read.+import { join } from "node:path";++import type { BoardItem, BoardItemCreator, BoardItemState } from "../../shared/board.ts";+import { BOARD_LIMITS } from "../../shared/board.ts";+import {+ applyMove, boardLabels, boardNeeds, boardResult, boardTitle, BoardError, isOpen, promote, startState, withoutItems,+ type BoardActor, type BoardMove,+} from "./state.ts";+import { BOARD_FILE, readBoardFile, writeBoardFile, type BoardFile } from "./store.ts";++export interface BoardDeps {+ dataDir: string;+ file?: string;+ now?: () => number;+ /** False once the room or its thread is gone. */+ alive(groupId: string, threadId: string): boolean;+ /** The bots in the room, or null for no such room. */+ roomBots(groupId: string): readonly string[] | null;+ log?(text: string): void;+}++export interface NewBoardItem {+ groupId: string;+ title: unknown;+ needs?: unknown;+ labels?: unknown;+ forBotId?: unknown;+ createdBy: BoardItemCreator;+ /** An existing room thread to make the item of; without it `openThread` makes one. */+ threadId?: string;+}++export interface BoardPatch {+ move?: BoardMove;+ title?: unknown;+ labels?: unknown;+ needs?: unknown;+ forBotId?: unknown;+ result?: unknown;+}++export interface BoardChange {+ groupId: string;+ threadId: string;+ item: BoardItem | null;+}++export interface BoardFilter {+ groupId?: string;+ state?: BoardItemState;+}++export function createBoard(deps: BoardDeps) {+ const file = deps.file ?? join(deps.dataDir, BOARD_FILE);+ const now = deps.now ?? Date.now;+ const log = deps.log ?? ((text: string) => console.error(text));+ let board: BoardFile | null = null;+ const listeners = new Set<(change: BoardChange) => void>();++ const loaded = (): BoardFile => (board ??= readBoardFile(file));+ const copy = (item: BoardItem): BoardItem => ({ ...item, needs: [...item.needs], labels: { ...item.labels } });++ /** Saves the board `next` makes of the current items, then tells listeners each item that changed. */+ function commit(next: (items: readonly BoardItem[]) => BoardItem[]): void {+ const current = loaded();+ const items = next(current.items);+ writeBoardFile(file, { items, repeats: current.repeats });+ board = { items, repeats: current.repeats };+ const before = new Map(current.items.map((item) => [item.threadId, item]));+ const changes: BoardChange[] = [];+ for (const item of items) {+ if (before.get(item.threadId) !== item) changes.push({ groupId: item.groupId, threadId: item.threadId, item: copy(item) });+ before.delete(item.threadId);+ }+ for (const gone of before.values()) changes.push({ groupId: gone.groupId, threadId: gone.threadId, item: null });+ for (const change of changes) {+ for (const listener of listeners) {+ try { listener(change); } catch (error) { log(`board: a listener failed: ${String(error)}`); }+ }+ }+ }++ /** The items whose room thread is still here; the others are dropped from the file. */+ function live(): readonly BoardItem[] {+ const items = loaded().items;+ const gone = new Set(items.filter((item) => !deps.alive(item.groupId, item.threadId)).map((item) => item.threadId));+ if (gone.size) {+ try { commit((current) => withoutItems(current, gone, now())); } catch (error) { log(`board: could not drop items of gone threads: ${String(error)}`); }+ }+ return loaded().items.filter((item) => !gone.has(item.threadId));+ }++ function found(threadId: string): BoardItem {+ const item = live().find((candidate) => candidate.threadId === threadId);+ if (!item) throw new BoardError(404, "board_not_found", "No board item on that thread.");+ return item;+ }++ function botFor(groupId: string, raw: unknown): string | undefined {+ if (raw === undefined) return undefined;+ if (typeof raw !== "string" || !raw) throw new BoardError(400, "board_bad_input", "forBotId must be a bot id.");+ if (!deps.roomBots(groupId)?.includes(raw)) throw new BoardError(400, "board_bad_input", "That bot is not in this room.");+ return raw;+ }++ /** One move, then the fields of `change`, as one change; items it readies change with it. */+ function patch(threadId: string, change: BoardPatch, actor: BoardActor): BoardItem {+ const items = live();+ let item = found(threadId);+ const at = now();+ if (change.move) item = applyMove(item, change.move, actor, items, at);+ if (change.title !== undefined) item = { ...item, title: boardTitle(change.title) };+ if (change.labels !== undefined) item = { ...item, labels: boardLabels(change.labels) };+ if (change.forBotId !== undefined) {+ const { forBotId: _forBotId, ...rest } = item;+ const bot = change.forBotId === null ? undefined : botFor(item.groupId, change.forBotId);+ item = { ...rest, ...(bot ? { forBotId: bot } : {}) };+ }+ if (change.needs !== undefined) {+ if (item.state !== "waiting" && item.state !== "ready") throw new BoardError(409, "board_bad_move", "Change what an item needs only before a bot takes it.");+ const needs = boardNeeds(change.needs, items, item);+ item = { ...item, needs, state: startState({ needs }, items) };+ }+ if (change.result !== undefined) {+ if (isOpen(item.state)) throw new BoardError(409, "board_bad_move", "An item gets a result when it is done, failed or cancelled.");+ const { result: _result, ...rest } = item;+ const result = boardResult(change.result);+ item = { ...rest, ...(result ? { result } : {}) };+ }+ const changed = { ...item, updatedAt: at };+ commit((current) => promote(current.map((other) => other.threadId === threadId ? changed : other), at));+ return copy(loaded().items.find((other) => other.threadId === threadId) ?? changed);+ }++ return {+ /** Items oldest first. */+ list(filter: BoardFilter = {}): BoardItem[] {+ return live().filter((item) => (!filter.groupId || item.groupId === filter.groupId) && (!filter.state || item.state === filter.state))+ .sort((a, b) => a.createdAt - b.createdAt).map(copy);+ },++ get(threadId: string): BoardItem | null {+ const item = live().find((candidate) => candidate.threadId === threadId);+ return item ? copy(item) : null;+ },++ /** Checks everything first, then opens the thread (when `input.threadId` is absent), then saves the item. */+ create(input: NewBoardItem, openThread?: (title: string) => string): BoardItem {+ const items = live();+ if (!deps.roomBots(input.groupId)) throw new BoardError(404, "board_not_found", "No such room.");+ if (input.threadId && !deps.alive(input.groupId, input.threadId)) throw new BoardError(404, "board_not_found", "No such thread in that room.");+ if (input.threadId && items.some((item) => item.threadId === input.threadId)) throw new BoardError(409, "board_exists", "That thread is already a board item.");+ if (items.filter((item) => item.groupId === input.groupId && isOpen(item.state)).length >= BOARD_LIMITS.openPerRoom) {+ throw new BoardError(409, "board_full", `This room already has ${BOARD_LIMITS.openPerRoom} open items, the most it may. Finish or cancel some first.`);+ }+ const title = boardTitle(input.title);+ const labels = boardLabels(input.labels);+ const forBotId = botFor(input.groupId, input.forBotId);+ const needs = boardNeeds(input.needs, items, { threadId: input.threadId ?? "", groupId: input.groupId });+ if (!input.threadId && !openThread) throw new BoardError(400, "board_bad_input", "Name the thread the item is on.");+ const threadId = input.threadId ?? openThread!(title);+ const at = now();+ const item: BoardItem = {+ threadId, groupId: input.groupId, title, state: startState({ needs }, items), needs, labels,+ ...(forBotId ? { forBotId } : {}), attempts: 0, createdBy: { ...input.createdBy }, createdAt: at, updatedAt: at,+ };+ commit((current) => [...current, item]);+ return copy(item);+ },++ patch,++ move(threadId: string, move: BoardMove, actor: BoardActor): BoardItem {+ return patch(threadId, { move }, actor);+ },++ /** Removes the item only: its thread stays. Items that needed it no longer do. */+ remove(threadId: string): BoardItem | null {+ const item = live().find((candidate) => candidate.threadId === threadId);+ if (!item) return null;+ commit((current) => withoutItems(current, new Set([threadId]), now()));+ return copy(item);+ },++ /** Every saved change, one item at a time; `item: null` when it was removed. Returns the unsubscribe. */+ onChange(listener: (change: BoardChange) => void): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+ },+ };+}++export type Board = ReturnType<typeof createBoard>;diff --git a/server/board/state.test.ts b/server/board/state.test.tsnew file mode 100644index 0000000000..0d13076679--- /dev/null+++ b/server/board/state.test.ts@@ -0,0 +1,195 @@+import { describe, expect, it } from "vitest";++import { BOARD_LIMITS, type BoardItem, type BoardItemState } from "../../shared/board.ts";+import {+ applyMove, boardLabels, boardNeeds, boardResult, boardTitle, BoardError, closesCycle, promote, startState, withoutItems,+ type BoardActor, type BoardMove,+} from "./state.ts";++const T = 1_700_000_000_000;+const PERSON: BoardActor = { kind: "person", person: "p_mira" };+const DISPATCHER: BoardActor = { kind: "dispatcher" };+const HOLDER: BoardActor = { kind: "bot", botId: "scout" };+const OTHER_BOT: BoardActor = { kind: "bot", botId: "payroll" };+const STATES: BoardItemState[] = ["waiting", "ready", "working", "needs_person", "done", "failed", "cancelled"];++function item(over: Partial<BoardItem> = {}): BoardItem {+ return {+ threadId: "t1", groupId: "g1", title: "Write the brief", state: "ready", needs: [], labels: {}, attempts: 0,+ createdBy: { kind: "person", id: "p_mira", name: "Mira" }, createdAt: T, updatedAt: T, ...over,+ };+}+const inState = (state: BoardItemState): BoardItem => item({+ state, ...(state === "working" || state === "needs_person" ? { holder: { botId: "scout", since: T } } : {}),+ ...(state === "needs_person" ? { question: { text: "Which client?", askedAt: T } } : {}),+});++const MOVES: Record<BoardMove["move"], BoardMove> = {+ take: { move: "take", botId: "scout" }, done: { move: "done", result: "Shipped" }, failed: { move: "failed", result: "No access" },+ ask: { move: "ask", question: "Which client?" }, resume: { move: "resume" }, release: { move: "release" },+ cancel: { move: "cancel" }, reopen: { move: "reopen" },+};++/** Every move each actor may make, by state: anything not listed is refused. */+const ALLOWED: Record<string, Array<[BoardItemState, BoardMove["move"], BoardActor]>> = {+ dispatcher: [+ ["ready", "take", DISPATCHER], ["working", "done", DISPATCHER], ["working", "failed", DISPATCHER], ["working", "release", DISPATCHER],+ ["needs_person", "resume", DISPATCHER], ["needs_person", "release", DISPATCHER],+ ],+ holder: [["working", "done", HOLDER], ["working", "failed", HOLDER], ["working", "ask", HOLDER], ["working", "release", HOLDER]],+ person: [+ ["waiting", "done", PERSON], ["ready", "done", PERSON], ["working", "done", PERSON], ["needs_person", "done", PERSON],+ ["needs_person", "release", PERSON],+ ["waiting", "cancel", PERSON], ["ready", "cancel", PERSON], ["working", "cancel", PERSON], ["needs_person", "cancel", PERSON],+ ["done", "reopen", PERSON], ["failed", "reopen", PERSON], ["cancelled", "reopen", PERSON],+ ],+};++describe("moves", () => {+ const actors: Array<[string, BoardActor]> = [["dispatcher", DISPATCHER], ["holder", HOLDER], ["person", PERSON], ["other bot", OTHER_BOT]];+ for (const [name, actor] of actors) {+ for (const state of STATES) {+ for (const move of Object.keys(MOVES) as Array<BoardMove["move"]>) {+ const ok = (ALLOWED[name] ?? []).some(([s, m]) => s === state && m === move);+ it(`${name} ${ok ? "may" : "may not"} ${move} a ${state} item`, () => {+ const run = () => applyMove(inState(state), MOVES[move], actor, [], T + 1);+ if (ok) expect(run().updatedAt).toBe(T + 1);+ else expect(run).toThrow(expect.objectContaining({ status: 409, code: "board_bad_move" }));+ });+ }+ }+ }++ it("a bot cancels only an open item it made", () => {+ const made = item({ createdBy: { kind: "bot", id: "payroll", name: "Payroll" } });+ expect(applyMove(made, { move: "cancel", result: "Not needed" }, OTHER_BOT, [], T + 1)).toMatchObject({ state: "cancelled", result: "Not needed" });+ expect(() => applyMove(made, { move: "cancel" }, HOLDER, [], T + 1)).toThrow(BoardError);+ expect(() => applyMove({ ...made, state: "done" }, { move: "cancel" }, OTHER_BOT, [], T + 1)).toThrow(BoardError);+ });++ it("take sets the holder and counts the attempt; done clears the holder and keeps the result", () => {+ const taken = applyMove(item({ attempts: 1 }), { move: "take", botId: "scout" }, DISPATCHER, [], T + 5);+ expect(taken).toMatchObject({ state: "working", holder: { botId: "scout", since: T + 5 }, attempts: 2 });+ const done = applyMove(taken, { move: "done", result: "Shipped" }, HOLDER, [], T + 9);+ expect(done).toMatchObject({ state: "done", result: "Shipped", attempts: 2 });+ expect(done.holder).toBeUndefined();+ });++ it("ask keeps the holder and the question; resume goes back to the same bot", () => {+ const working = inState("working");+ const asked = applyMove(working, { move: "ask", question: " Which client? ", person: "p_mira" }, HOLDER, [], T + 3);+ expect(asked).toMatchObject({ state: "needs_person", holder: { botId: "scout" }, question: { text: "Which client?", askedAt: T + 3, person: "p_mira" } });+ const resumed = applyMove(asked, { move: "resume" }, DISPATCHER, [], T + 7);+ expect(resumed).toMatchObject({ state: "working", holder: { botId: "scout", since: T + 7 } });+ expect(resumed.question).toBeUndefined();+ expect(() => applyMove(working, { move: "ask", question: " " }, HOLDER, [], T)).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ expect(() => applyMove(working, { move: "ask", question: "x".repeat(BOARD_LIMITS.questionMax + 1) }, HOLDER, [], T)).toThrow(BoardError);+ });++ it("release frees the item for any bot", () => {+ const released = applyMove(inState("needs_person"), { move: "release" }, PERSON, [], T + 1);+ expect(released.state).toBe("ready");+ expect(released.holder).toBeUndefined();+ expect(released.question).toBeUndefined();+ });++ it("reopen resets the tries and the result, and waits again when a need is not done", () => {+ const failed = item({ state: "failed", attempts: 3, result: "Stopped after 3 tries" });+ const reopened = applyMove(failed, { move: "reopen" }, PERSON, [failed], T + 1);+ expect(reopened).toMatchObject({ state: "ready", attempts: 0 });+ expect(reopened.result).toBeUndefined();+ const need = item({ threadId: "t0", state: "working" });+ const dependent = item({ state: "cancelled", needs: ["t0"] });+ expect(applyMove(dependent, { move: "reopen" }, PERSON, [need, dependent], T + 1).state).toBe("waiting");+ });++ it("refuses a result over the limit", () => {+ expect(() => applyMove(inState("working"), { move: "done", result: "x".repeat(BOARD_LIMITS.resultMax + 1) }, HOLDER, [], T)).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ });+});++describe("needs", () => {+ const board = (states: Record<string, BoardItemState>, needs: Record<string, string[]> = {}) =>+ Object.entries(states).map(([threadId, state]) => item({ threadId, state, needs: needs[threadId] ?? [] }));++ it("a new item waits while any need is not done", () => {+ const items = board({ a: "done", b: "working" });+ expect(startState({ needs: ["a"] }, items)).toBe("ready");+ expect(startState({ needs: ["a", "b"] }, items)).toBe("waiting");+ expect(startState({ needs: [] }, items)).toBe("ready");+ });++ it("a waiting item is ready only when every need is done", () => {+ const items = board({ a: "done", b: "working", c: "waiting" }, { c: ["a", "b"] });+ expect(promote(items, T + 1).find((one) => one.threadId === "c")!.state).toBe("waiting");+ const both = board({ a: "done", b: "done", c: "waiting" }, { c: ["a", "b"] });+ const promoted = promote(both, T + 1).find((one) => one.threadId === "c")!;+ expect(promoted).toMatchObject({ state: "ready", updatedAt: T + 1 });+ });++ it("a failed or cancelled need readies nothing", () => {+ for (const state of ["failed", "cancelled"] as const) {+ const items = board({ a: state, c: "waiting" }, { c: ["a"] });+ expect(promote(items, T + 1).find((one) => one.threadId === "c")!.state).toBe("waiting");+ }+ });++ it("promote leaves every other item as it was", () => {+ const items = board({ a: "done", b: "ready", c: "waiting" }, { c: ["a"] });+ const after = promote(items, T + 1);+ expect(after[0]).toBe(items[0]);+ expect(after[1]).toBe(items[1]);+ });++ it("refuses a cycle, a need on itself, one in another room, an unknown one, and more than ten", () => {+ const items = board({ a: "ready", b: "waiting", c: "waiting" }, { b: ["a"], c: ["b"] });+ expect(closesCycle(items, "a", ["c"])).toBe(true);+ expect(() => boardNeeds(["c"], items, { threadId: "a", groupId: "g1" })).toThrow(expect.objectContaining({ status: 409, code: "board_cycle" }));+ expect(() => boardNeeds(["a"], items, { threadId: "a", groupId: "g1" })).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ expect(() => boardNeeds(["zz"], items, { threadId: "n", groupId: "g1" })).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ expect(() => boardNeeds(["a"], [...items, item({ threadId: "x", groupId: "g2" })], { threadId: "x2", groupId: "g2" })).toThrow(BoardError);+ expect(() => boardNeeds([{}], items, { threadId: "n", groupId: "g1" })).toThrow(BoardError);+ const many = Array.from({ length: BOARD_LIMITS.needsMax + 1 }, (_, i) => item({ threadId: `m${i}` }));+ expect(() => boardNeeds(many.map((one) => one.threadId), many, { threadId: "n", groupId: "g1" })).toThrow(BoardError);+ expect(boardNeeds(many.slice(0, BOARD_LIMITS.needsMax).map((one) => one.threadId), many, { threadId: "n", groupId: "g1" })).toHaveLength(BOARD_LIMITS.needsMax);+ expect(boardNeeds(["a", "a", "b"], items, { threadId: "n", groupId: "g1" })).toEqual(["a", "b"]);+ });++ it("an item that leaves the board stops being needed, and what that readies is ready", () => {+ const items = board({ a: "working", b: "done", c: "waiting" }, { c: ["a", "b"] });+ const after = withoutItems(items, new Set(["a"]), T + 2);+ expect(after.map((one) => one.threadId)).toEqual(["b", "c"]);+ expect(after.find((one) => one.threadId === "c")).toMatchObject({ needs: ["b"], state: "ready" });+ });+});++describe("fields", () => {+ it("titles: one line, at most 120 characters, not empty", () => {+ expect(boardTitle(" Write\nthe brief ")).toBe("Write the brief");+ expect(boardTitle("x".repeat(BOARD_LIMITS.titleMax))).toHaveLength(BOARD_LIMITS.titleMax);+ for (const bad of ["", " ", 3, undefined, "x".repeat(BOARD_LIMITS.titleMax + 1)]) {+ expect(() => boardTitle(bad), String(bad)).toThrow(expect.objectContaining({ status: 400, code: "board_bad_input" }));+ }+ });++ it("labels: at most 12, keys of lowercase letters, digits, _ and -, values of at most 80 characters", () => {+ expect(boardLabels({ area: " billing ", "due-by_2": "Friday" })).toEqual({ area: "billing", "due-by_2": "Friday" });+ expect(boardLabels(undefined)).toEqual({});+ const twelve = Object.fromEntries(Array.from({ length: BOARD_LIMITS.labelsMax }, (_, i) => [`k${i}`, "v"]));+ expect(Object.keys(boardLabels(twelve))).toHaveLength(BOARD_LIMITS.labelsMax);+ for (const bad of [+ { ...twelve, k99: "v" }, { Area: "x" }, { "a b": "x" }, { ["k".repeat(BOARD_LIMITS.labelKeyMax + 1)]: "x" }, { "": "x" },+ { area: "x".repeat(BOARD_LIMITS.labelValueMax + 1) }, { area: 3 }, ["area"], "area", null,+ ]) {+ expect(() => boardLabels(bad), JSON.stringify(bad)).toThrow(expect.objectContaining({ code: "board_bad_input" }));+ }+ expect(boardLabels({ ["k".repeat(BOARD_LIMITS.labelKeyMax)]: "x".repeat(BOARD_LIMITS.labelValueMax) })).toBeTruthy();+ });++ it("results: text of at most 2,000 characters; blank is none", () => {+ expect(boardResult(undefined)).toBeUndefined();+ expect(boardResult(" ")).toBeUndefined();+ expect(boardResult("x".repeat(BOARD_LIMITS.resultMax))).toHaveLength(BOARD_LIMITS.resultMax);+ expect(() => boardResult(5)).toThrow(BoardError);+ });+});diff --git a/server/board/state.ts b/server/board/state.tsnew file mode 100644index 0000000000..0811df20fc--- /dev/null+++ b/server/board/state.ts@@ -0,0 +1,175 @@+// The Team Board's rules, with no storage: which moves an item may make and who may make them, what a valid item is,+// and which waiting items become ready. Every function returns new items and never changes the ones it is given.+import {+ BOARD_LABEL_KEY, BOARD_LIMITS, BOARD_OPEN_STATES, type BoardItem, type BoardItemState,+} from "../../shared/board.ts";++export type BoardErrorCode = "board_bad_input" | "board_bad_move" | "board_not_found" | "board_full" | "board_exists" | "board_cycle";++export class BoardError extends Error {+ readonly status: number;+ readonly code: BoardErrorCode;+ constructor(status: number, code: BoardErrorCode, message: string) {+ super(message);+ this.status = status;+ this.code = code;+ }+}++const badInput = (message: string) => new BoardError(400, "board_bad_input", message);+const badMove = (message: string) => new BoardError(409, "board_bad_move", message);++/** Who asks for a move. `dispatcher`: the server itself, giving work to bots and taking it back when a turn ends. */+export type BoardActor = { kind: "person"; person: string } | { kind: "bot"; botId: string } | { kind: "dispatcher" };++export type BoardMove =+ | { move: "take"; botId: string }+ | { move: "done"; result?: string }+ | { move: "failed"; result?: string }+ | { move: "ask"; question: string; person?: string }+ | { move: "resume" }+ | { move: "release" }+ | { move: "cancel"; result?: string }+ | { move: "reopen" };++export const isOpen = (state: BoardItemState): boolean => BOARD_OPEN_STATES.includes(state);++const oneLine = (value: string) => value.replace(/\s+/g, " ").trim();++export function boardTitle(raw: unknown): string {+ if (typeof raw !== "string" || !oneLine(raw)) throw badInput("Give the item a title.");+ const title = oneLine(raw);+ if (title.length > BOARD_LIMITS.titleMax) throw badInput(`A title is at most ${BOARD_LIMITS.titleMax} characters.`);+ return title;+}++export function boardLabels(raw: unknown): Record<string, string> {+ if (raw === undefined) return {};+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw badInput("labels must be an object of short texts.");+ const entries = Object.entries(raw as Record<string, unknown>);+ if (entries.length > BOARD_LIMITS.labelsMax) throw badInput(`An item has at most ${BOARD_LIMITS.labelsMax} labels.`);+ const labels: Record<string, string> = {};+ for (const [key, value] of entries) {+ if (!BOARD_LABEL_KEY.test(key)) throw badInput(`The label "${key.slice(0, 40)}" needs a key of at most ${BOARD_LIMITS.labelKeyMax} lowercase letters, digits, _ or -.`);+ if (typeof value !== "string") throw badInput(`The label "${key}" needs a text value.`);+ const text = oneLine(value);+ if (text.length > BOARD_LIMITS.labelValueMax) throw badInput(`The label "${key}" is at most ${BOARD_LIMITS.labelValueMax} characters.`);+ labels[key] = text;+ }+ return labels;+}++export function boardResult(raw: unknown): string | undefined {+ if (raw === undefined) return undefined;+ if (typeof raw !== "string") throw badInput("result must be text.");+ if (raw.length > BOARD_LIMITS.resultMax) throw badInput(`A result is at most ${BOARD_LIMITS.resultMax} characters.`);+ return raw.trim() || undefined;+}++/** Whether `threadId` needing `needs` closes a loop: some need, through its own needs, already needs `threadId`. */+export function closesCycle(items: readonly BoardItem[], threadId: string, needs: readonly string[]): boolean {+ const byId = new Map(items.map((item) => [item.threadId, item]));+ const seen = new Set<string>();+ const stack = [...needs];+ while (stack.length) {+ const id = stack.pop()!;+ if (id === threadId) return true;+ if (seen.has(id)) continue;+ seen.add(id);+ stack.push(...(byId.get(id)?.needs ?? []));+ }+ return false;+}++/** The needs of `threadId`, checked against the board: other items of the same room, at most ten, with no loop. */+export function boardNeeds(raw: unknown, items: readonly BoardItem[], self: { threadId: string; groupId: string }): string[] {+ if (raw === undefined) return [];+ if (!Array.isArray(raw) || raw.some((id) => typeof id !== "string")) throw badInput("needs must be a list of item thread ids.");+ const needs = [...new Set(raw as string[])];+ if (needs.length > BOARD_LIMITS.needsMax) throw badInput(`An item needs at most ${BOARD_LIMITS.needsMax} others.`);+ for (const id of needs) {+ if (id === self.threadId) throw badInput("An item cannot need itself.");+ const need = items.find((item) => item.threadId === id);+ if (!need || need.groupId !== self.groupId) throw badInput("Each need must be an item in the same room.");+ }+ if (closesCycle(items, self.threadId, needs)) throw new BoardError(409, "board_cycle", "Those needs would make items wait for each other forever.");+ return needs;+}++export function needsMet(item: Pick<BoardItem, "needs">, items: readonly BoardItem[]): boolean {+ return item.needs.every((id) => items.find((other) => other.threadId === id)?.state === "done");+}++/** Where a new item, or one whose needs changed while not yet taken, starts. */+export const startState = (item: Pick<BoardItem, "needs">, items: readonly BoardItem[]): "waiting" | "ready" =>+ needsMet(item, items) ? "ready" : "waiting";++const holds = (item: BoardItem, actor: BoardActor) => actor.kind === "bot" && item.holder?.botId === actor.botId;+const madeIt = (item: BoardItem, actor: BoardActor) => actor.kind === "bot" && item.createdBy.kind === "bot" && item.createdBy.id === actor.botId;++/** Who may make each move, from which states. */+function allowed(item: BoardItem, move: BoardMove["move"], actor: BoardActor): boolean {+ const { state } = item;+ const person = actor.kind === "person";+ const dispatcher = actor.kind === "dispatcher";+ switch (move) {+ case "take": return dispatcher && state === "ready";+ case "done": return state === "working" ? person || dispatcher || holds(item, actor) : person && isOpen(state);+ case "failed": return state === "working" && (dispatcher || holds(item, actor));+ case "ask": return state === "working" && holds(item, actor);+ case "resume": return state === "needs_person" && dispatcher;+ case "release": return state === "working" ? dispatcher || holds(item, actor) : state === "needs_person" && (person || dispatcher);+ case "cancel": return isOpen(state) && (person || madeIt(item, actor));+ case "reopen": return !isOpen(state) && person;+ }+}++const settle = (item: BoardItem, state: BoardItemState, result: string | undefined, now: number): BoardItem => {+ const { holder: _holder, question: _question, ...rest } = item;+ return { ...rest, state, ...(result !== undefined ? { result } : {}), updatedAt: now };+};++/** The item after `move`, or a 409 `board_bad_move` when this actor may not make it from where the item is. */+export function applyMove(item: BoardItem, move: BoardMove, actor: BoardActor, items: readonly BoardItem[], now: number): BoardItem {+ if (!allowed(item, move.move, actor)) throw badMove(`This item is ${item.state.replace("_", " ")}: it cannot be moved to ${move.move} now.`);+ switch (move.move) {+ case "take": {+ const { question: _question, result: _result, ...rest } = item;+ return { ...rest, state: "working", holder: { botId: move.botId, since: now }, attempts: item.attempts + 1, updatedAt: now };+ }+ case "done":+ case "failed":+ case "cancel":+ return settle(item, move.move === "cancel" ? "cancelled" : move.move, boardResult(move.result), now);+ case "ask": {+ const text = typeof move.question === "string" ? move.question.trim() : "";+ if (!text) throw badInput("Say what you want to ask.");+ if (text.length > BOARD_LIMITS.questionMax) throw badInput(`A question is at most ${BOARD_LIMITS.questionMax} characters.`);+ return { ...item, state: "needs_person", question: { text, askedAt: now, ...(move.person ? { person: move.person } : {}) }, updatedAt: now };+ }+ case "resume": {+ const { question: _question, ...rest } = item;+ return { ...rest, state: "working", holder: { botId: item.holder!.botId, since: now }, updatedAt: now };+ }+ case "release": {+ const { holder: _holder, question: _question, ...rest } = item;+ return { ...rest, state: "ready", updatedAt: now };+ }+ case "reopen": {+ const { holder: _holder, question: _question, result: _result, ...rest } = item;+ return { ...rest, state: startState(item, items), attempts: 0, updatedAt: now };+ }+ }+}++/** Waiting items whose every need is now done, made ready. A failed or cancelled need readies nothing. */+export function promote(items: readonly BoardItem[], now: number): BoardItem[] {+ return items.map((item) => item.state === "waiting" && needsMet(item, items) ? { ...item, state: "ready" as const, updatedAt: now } : item);+}++/** The board without the items in `gone`, each other item's needs of them dropped, and what that readies made ready. */+export function withoutItems(items: readonly BoardItem[], gone: ReadonlySet<string>, now: number): BoardItem[] {+ const kept = items.filter((item) => !gone.has(item.threadId)).map((item) => item.needs.some((id) => gone.has(id))+ ? { ...item, needs: item.needs.filter((id) => !gone.has(id)), updatedAt: now } : item);+ return promote(kept, now);+}diff --git a/server/board/store.test.ts b/server/board/store.test.tsnew file mode 100644index 0000000000..2c040a9129--- /dev/null+++ b/server/board/store.test.ts@@ -0,0 +1,57 @@+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import type { BoardItem } from "../../shared/board.ts";+import { BOARD_FILE, readBoardFile, writeBoardFile } from "./store.ts";++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+const fileIn = () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-board-store-"));+ dirs.push(dir);+ return join(dir, "data", BOARD_FILE);+};++const ITEM: BoardItem = {+ threadId: "t1", groupId: "g1", title: "Write the brief", state: "needs_person", needs: ["t0"], labels: { area: "billing" },+ forBotId: "scout", holder: { botId: "scout", since: 5 }, attempts: 1, question: { text: "Which client?", askedAt: 6, person: "p_mira" },+ createdBy: { kind: "person", id: "p_mira", name: "Mira" }, createdAt: 1, updatedAt: 6,+};++describe("board.json", () => {+ it("round-trips items and keeps repeats it does not know", () => {+ const file = fileIn();+ writeBoardFile(file, { items: [ITEM], repeats: [{ every: "day" }] });+ expect(readBoardFile(file)).toEqual({ items: [ITEM], repeats: [{ every: "day" }] });+ expect(JSON.parse(readFileSync(file, "utf8"))).toMatchObject({ version: 1 });+ });++ it("is written whole, readable only by its owner, with no temporary file left beside it", () => {+ const file = fileIn();+ writeBoardFile(file, { items: [ITEM], repeats: [] });+ writeBoardFile(file, { items: [], repeats: [] });+ expect(readBoardFile(file).items).toEqual([]);+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(readdirSync(join(file, ".."))).toEqual([BOARD_FILE]);+ });++ it("reads a missing, corrupt or foreign file as an empty board", () => {+ const file = fileIn();+ expect(readBoardFile(file)).toEqual({ items: [], repeats: [] });+ writeBoardFile(file, { items: [], repeats: [] });+ for (const text of ["{not json", "[]", JSON.stringify({ version: 2, items: [ITEM] }), JSON.stringify({ version: 1 })]) {+ writeFileSync(file, text);+ expect(readBoardFile(file), text).toEqual({ items: [], repeats: [] });+ }+ });++ it("leaves out an item that does not parse and keeps the rest, with fields a newer version added", () => {+ const file = fileIn();+ writeBoardFile(file, { items: [ITEM], repeats: [] });+ const newer = { ...ITEM, threadId: "t2", lane: "fast" };+ writeFileSync(file, JSON.stringify({ version: 1, items: [ITEM, { ...ITEM, state: "stuck" }, { threadId: "t3" }, newer], repeats: [] }));+ expect(readBoardFile(file).items).toEqual([ITEM, newer]);+ });+});diff --git a/server/board/store.ts b/server/board/store.tsnew file mode 100644index 0000000000..6e6d29088a--- /dev/null+++ b/server/board/store.ts@@ -0,0 +1,52 @@+// `board.json` in the data folder: the Team Board's items. A file that is missing or unreadable is an empty board, and an+// item that does not parse is left out, so one bad record never hides the rest.+import { mkdirSync, readFileSync } from "node:fs";+import { dirname } from "node:path";+import { z } from "zod";++import { BOARD_LIMITS, type BoardItem } from "../../shared/board.ts";+import { writeFileAtomic } from "../atomic.ts";++export const BOARD_FILE = "board.json";++const id = z.string().min(1).max(200);+const itemSchema = z.looseObject({+ threadId: id, groupId: id,+ title: z.string().min(1).max(BOARD_LIMITS.titleMax),+ state: z.enum(["waiting", "ready", "working", "needs_person", "done", "failed", "cancelled"]),+ needs: z.array(id).max(BOARD_LIMITS.needsMax),+ labels: z.record(z.string(), z.string()),+ forBotId: id.optional(),+ holder: z.object({ botId: id, since: z.number() }).optional(),+ attempts: z.number().int().min(0),+ question: z.object({ text: z.string(), askedAt: z.number(), person: z.string().optional() }).optional(),+ result: z.string().optional(),+ createdBy: z.object({ kind: z.enum(["person", "bot"]), id: z.string(), name: z.string() }),+ createdAt: z.number(), updatedAt: z.number(),+});+const fileSchema = z.object({ version: z.literal(1), items: z.array(z.unknown()), repeats: z.array(z.unknown()).optional() });++export interface BoardFile {+ items: BoardItem[];+ /** Repeating items, kept as read until a version that knows them. */+ repeats: unknown[];+}++export function readBoardFile(file: string): BoardFile {+ try {+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (!parsed.success) return { items: [], repeats: [] };+ const items = parsed.data.items.flatMap((candidate) => {+ const item = itemSchema.safeParse(candidate);+ return item.success ? [item.data as BoardItem] : [];+ });+ return { items, repeats: parsed.data.repeats ?? [] };+ } catch {+ return { items: [], repeats: [] };+ }+}++export function writeBoardFile(file: string, board: BoardFile): void {+ mkdirSync(dirname(file), { recursive: true });+ writeFileAtomic(file, JSON.stringify({ version: 1, items: board.items, repeats: board.repeats }, null, 2), { mode: 0o600 });+}diff --git a/server/board/wiring.ts b/server/board/wiring.tsnew file mode 100644index 0000000000..48b9d721a3--- /dev/null+++ b/server/board/wiring.ts@@ -0,0 +1,60 @@+// The Team Board as the server runs it: the items, their routes, and a `board.item` frame for every change.+import type { ResolvedSender } from "../../shared/wire.ts";+import type { BoardItemFrame } from "../../shared/board.ts";+import type { VisibleSet } from "../bot-visibility.ts";+import type { RequestAuth } from "../request-auth.ts";+import { createBoardRoutes, type BoardPerson } from "../routes/board.ts";+import type { Store } from "../store.ts";+import { createBoard } from "./host.ts";++export interface TeamBoardDeps {+ dataDir: string;+ /** A Team Cloud. */+ team: boolean;+ /** `features.teamBoard`, read on every request. */+ enabled(): boolean;+ store: Pick<Store, "group" | "groupTaskByThread" | "createGroupTask" | "appendMessage" | "bot">;+ visible(auth: RequestAuth): VisibleSet;+ person(auth: RequestAuth): BoardPerson | null;+ sender(auth: RequestAuth): ResolvedSender | undefined;+ /** Notes who opened a thread, as a person's own new thread does. */+ opened(auth: RequestAuth, threadId: string): void;+ roomRefusal(groupId: string): string | null;+ broadcast(payload: Record<string, unknown>): void;+}++export function createTeamBoard(deps: TeamBoardDeps) {+ const { store } = deps;+ const board = createBoard({+ dataDir: deps.dataDir,+ alive: (groupId, threadId) => Boolean(store.groupTaskByThread(groupId, threadId)),+ roomBots: (groupId) => {+ const room = store.group(groupId);+ return room && !room.dm ? room.memberIds : null;+ },+ });+ board.onChange((change) => deps.broadcast({ kind: "board.item", ...change } satisfies BoardItemFrame));+ const routes = createBoardRoutes({+ board,+ on: () => deps.team && deps.enabled(),+ person: deps.person,+ visible: deps.visible,+ room: (groupId) => {+ const room = store.group(groupId);+ return room ? { dm: room.dm === true, memberIds: room.memberIds } : null;+ },+ botName: (botId) => store.bot(botId)?.name,+ roomRefusal: deps.roomRefusal,+ openThread: (auth, groupId, title, text) => {+ const task = store.createGroupTask(groupId, title, false);+ if (!task) throw new Error(`could not open a thread in room ${groupId}`);+ deps.opened(auth, task.threadId);+ const sender = deps.sender(auth);+ store.appendMessage(task.threadId, { role: "user", kind: "text", text, ...(sender ? { sender } : {}) });+ return task.threadId;+ },+ });+ return { board, routes };+}++export type TeamBoard = ReturnType<typeof createTeamBoard>;diff --git a/server/bot-visibility.test.ts b/server/bot-visibility.test.tsindex e850d9655e..4c68d27752 100644--- a/server/bot-visibility.test.ts+++ b/server/bot-visibility.test.ts@@ -241,6 +241,19 @@ describe("live frames for a member", () => {.toEqual({ kind: "bot", bot: { id: "corp" } });});+ it("sends a board item only to someone who sees both its room and its thread", () => {+ const ctx = context(new VisibleSet(bots, groups, BOB));+ const shown = { kind: "board.item", groupId: "room-pub", threadId: "t-room-pub", item: null };+ expect(frameForMember(shown, ctx, seen())).toBe(shown);+ for (const frame of [+ { kind: "board.item", groupId: "room-mixed", threadId: "t-room-mixed-2", item: { title: "Payroll run" } },+ { kind: "board.item", groupId: "room-pub", threadId: "t-hr", item: null },+ { kind: "board.item", groupId: "room-mixed", threadId: "t-room-pub", item: null },+ { kind: "board.item", threadId: "t-room-pub", item: null },+ { kind: "board.item", groupId: "room-pub", item: null },+ ]) expect(frameForMember(frame, ctx, seen()), JSON.stringify(frame)).toBeUndefined();+ });+it("withdraws a bot once when it becomes hidden, and sends it whole when it appears", () => {const state = seen();const before = new VisibleSet(bots, groups, BOB);diff --git a/server/bot-visibility.ts b/server/bot-visibility.tsindex e952e7f3df..a260c6a098 100644--- a/server/bot-visibility.ts+++ b/server/bot-visibility.ts@@ -619,6 +619,8 @@ export function frameForMember(payload: Record<string, unknown>, ctx: FrameConteconst { help: _help, ...rest } = payload;return { ...rest, helpReason: null };}+ case "board.item":+ return visible.group(str(payload.groupId)) && visible.thread(str(payload.threadId)) ? payload : undefined;case "config":case "routine.deleted":case "webhook.deleted":diff --git a/server/cloud-team-board.e2e.test.ts b/server/cloud-team-board.e2e.test.tsnew file mode 100644index 0000000000..96eb2084bc--- /dev/null+++ b/server/cloud-team-board.e2e.test.ts@@ -0,0 +1,198 @@+// The Team Board on a real Team Cloud: Olive (the Owner) and three Members. Desk is in the Launch room everyone sees;+// Payroll is shared with Mira to chat and Cara to view, so its Pay desk room is Mira's and Cara's to see and Ben's not at+// all. The board answers 404 until Olive switches it on; a member's item opens a room thread with their line and starts+// no turn; nobody who cannot see the room hears of its items; needs ready what waits on them; and a personal Cloud has+// no board. The engine is the synthetic Claude CLI.+import { randomBytes } from "node:crypto";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import type { BoardItem, BoardItemFrame } from "../shared/board.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++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 CARA = { email: "[email protected]", role: "member" as const };++type Room = { id: string; threadId: string };+type Line = { role: string; text?: string; sender?: { name: string } };++let fx: CloudSendFixture, team: CloudTeamFixture;+let olive = "", mira = "", ben = "", cara = "";+let launch: Room, payDesk: Room;++const messages = async (token: string, threadId: string) => (await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as Line[];+const idle = async () => ((await team.as(olive, "GET", "/api/bots")).body.bots as Array<{ busy?: boolean; activity?: string }>)+ .every((bot) => !bot.busy && bot.activity !== "working");+const board = async (token: string, query = "") => {+ const listed = await team.as(token, "GET", `/api/board${query}`);+ expect(listed.status, JSON.stringify(listed.body)).toBe(200);+ return listed.body.items as BoardItem[];+};+const add = async (token: string, body: Record<string, unknown>) => {+ const made = await team.as(token, "POST", "/api/board/items", body);+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ return made.body.item as BoardItem;+};+const patch = (token: string, threadId: string, body: Record<string, unknown>) => team.as(token, "PATCH", `/api/board/items/${threadId}`, body);++async function until(done: () => Promise<boolean> | boolean, timeoutMs = 20_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+}++/** One person's live stream: every board frame it was sent. */+async function listen(token: string) {+ const controller = new AbortController();+ const stream = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${token}`, accept: "text/event-stream" }, signal: controller.signal });+ expect(stream.status).toBe(200);+ const reader = stream.body!.getReader();+ const decoder = new TextDecoder();+ let text = "";+ const done = (async () => { for (;;) { const { value, done } = await reader.read(); if (done) return; text += decoder.decode(value, { stream: true }); } })().catch(() => {});+ await until(() => text.includes("\"hello\""));+ const frames = () => [...text.matchAll(/^data: (.*)$/gm)].map((match) => JSON.parse(match[1]!) as { kind: string })+ .filter((frame): frame is BoardItemFrame => frame.kind === "board.item");+ return { frames, close: async () => { controller.abort(); await done; } };+}++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-board-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-board", name: "Acme" } });+ team = fx.team!;+ olive = (await team.pair(OLIVE)).token!;+ mira = (await team.pair(MIRA)).token!;+ ben = (await team.pair(BEN)).token!;+ cara = (await team.pair(CARA)).token!;+ const bot = async (name: string) => {+ const made = await team.as(olive, "POST", "/api/bots", { name, visibility: "everyone" });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ return made.body.bot as { id: string };+ };+ const desk = await bot("Desk");+ const payroll = await bot("Payroll");+ const shared = await team.as(olive, "PUT", `/api/bots/${payroll.id}/access`, { everyone: "none", people: { [MIRA.email]: "chat", [CARA.email]: "view" } });+ expect(shared.status, JSON.stringify(shared.body)).toBe(200);+ const room = async (name: string, memberIds: string[]) => {+ const made = await team.as(olive, "POST", "/api/groups", { name, memberIds, setup: { bulletin: "", defaultResponder: { kind: "everyone" } } });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ return made.body.group as Room;+ };+ launch = await room("Launch", [desk.id]);+ payDesk = await room("Pay desk", [payroll.id]);+}, hostTimeout(180_000));++afterAll(async () => {+ await fx?.close();+});++it("has no board until it is switched on, and the switch shows only here", async () => {+ expect((await team.as(mira, "GET", "/api/board")).status).toBe(404);+ expect((await team.as(mira, "POST", "/api/board/items", { groupId: launch.id, title: "Early" })).status).toBe(404);+ expect((await team.as(olive, "GET", "/api/config")).body.features.teamBoard).toBe(false);+ const on = await team.as(olive, "PATCH", "/api/config", { features: { teamBoard: true } });+ expect(on.status, JSON.stringify(on.body)).toBe(200);+ expect(on.body.features.teamBoard).toBe(true);+ expect((await team.as(mira, "GET", "/api/config")).body.features?.teamBoard).toBe(true);+ expect(await board(mira)).toEqual([]);+ expect((await fx.onCloud("GET", "/api/config")).body.features?.teamBoard).toBeUndefined();+}, hostTimeout(60_000));++it("a member's item opens a room thread with their line and starts no turn", async () => {+ const item = await add(mira, { groupId: launch.id, title: "Draft the launch post", text: "Please draft the launch post for Friday.", labels: { area: "marketing" } });+ expect(item).toMatchObject({ groupId: launch.id, title: "Draft the launch post", state: "ready", labels: { area: "marketing" }, attempts: 0, createdBy: { kind: "person" } });+ expect(item.threadId).not.toBe(launch.threadId);+ const lines = await messages(mira, item.threadId);+ expect(lines).toHaveLength(1);+ expect(lines[0]).toMatchObject({ role: "user", text: "Please draft the launch post for Friday." });+ expect(lines[0]!.sender?.name).toBeTruthy();+ const rooms = (await team.as(mira, "GET", "/api/bots?messages=0")).body.groups as Array<Room & { tasks?: Array<{ threadId: string; title: string }> }>;+ const room = rooms.find((one) => one.id === launch.id)!;+ expect(room.threadId, "the room's current thread stays where it was").toBe(launch.threadId);+ expect(room.tasks?.find((task) => task.threadId === item.threadId)?.title).toBe("Draft the launch post");+ await new Promise((resolve) => setTimeout(resolve, 1_500));+ expect(await idle()).toBe(true);+ expect(await messages(mira, item.threadId)).toHaveLength(1);+ expect((await board(ben)).map((one) => one.threadId)).toEqual([item.threadId]);+}, hostTimeout(60_000));++it("someone who cannot see a room gets 404 and hears nothing of its items; a viewer may not write there", async () => {+ const miraStream = await listen(mira);+ const benStream = await listen(ben);+ try {+ expect((await team.as(ben, "POST", "/api/board/items", { groupId: payDesk.id, title: "Peek" })).status).toBe(404);+ const hidden = await add(mira, { groupId: payDesk.id, title: "Run November payroll" });+ await until(() => miraStream.frames().some((frame) => frame.threadId === hidden.threadId));+ const control = await add(mira, { groupId: launch.id, title: "Book the venue" });+ await until(() => benStream.frames().some((frame) => frame.threadId === control.threadId));+ expect(benStream.frames().filter((frame) => frame.groupId === payDesk.id || frame.threadId === hidden.threadId)).toEqual([]);+ expect((await board(ben)).map((one) => one.threadId)).not.toContain(hidden.threadId);+ expect((await board(ben, `?groupId=${payDesk.id}`))).toEqual([]);+ expect((await patch(ben, hidden.threadId, { move: "cancel" })).status).toBe(404);+ expect((await team.as(ben, "DELETE", `/api/board/items/${hidden.threadId}`)).status).toBe(404);+ expect((await team.as(ben, "POST", "/api/board/items", { groupId: payDesk.id, title: "Mine now", threadId: hidden.threadId })).status).toBe(404);+ expect((await board(cara, `?groupId=${payDesk.id}`)).map((one) => one.threadId)).toEqual([hidden.threadId]);+ const viewer = await team.as(cara, "POST", "/api/board/items", { groupId: payDesk.id, title: "Cara's" });+ expect(viewer.status, JSON.stringify(viewer.body)).toBe(403);+ expect((await patch(cara, hidden.threadId, { move: "cancel" })).status).toBe(403);+ expect((await board(olive)).map((one) => one.threadId)).toContain(hidden.threadId);+ } finally {+ await miraStream.close();+ await benStream.close();+ }+}, hostTimeout(60_000));++it("an item that needs another waits, and is ready once that one is done", async () => {+ const research = await add(mira, { groupId: launch.id, title: "Research venues" });+ const pick = await add(ben, { groupId: launch.id, title: "Pick a venue", needs: [research.threadId] });+ expect(pick.state).toBe("waiting");+ const loop = await patch(mira, research.threadId, { needs: [pick.threadId] });+ expect(loop.status).toBe(409);+ expect(loop.body.code).toBe("board_cycle");+ const done = await patch(mira, research.threadId, { move: "done", result: "Three venues shortlisted." });+ expect(done.status, JSON.stringify(done.body)).toBe(200);+ expect(done.body.item).toMatchObject({ state: "done", result: "Three venues shortlisted." });+ expect((await board(ben)).find((one) => one.threadId === pick.threadId)?.state).toBe("ready");+}, hostTimeout(60_000));++it("cancel, reopen, a refused move, and an existing thread made an item", async () => {+ const item = await add(ben, { groupId: launch.id, title: "Order banners" });+ const cancelled = await patch(ben, item.threadId, { move: "cancel", result: "Not this time." });+ expect(cancelled.body.item).toMatchObject({ state: "cancelled", result: "Not this time." });+ expect((await patch(ben, item.threadId, { move: "release" })).body.code).toBe("board_bad_move");+ const reopened = await patch(mira, item.threadId, { move: "reopen", title: "Order two banners" });+ expect(reopened.body.item).toMatchObject({ state: "ready", attempts: 0, title: "Order two banners" });+ expect(reopened.body.item.result).toBeUndefined();+ expect((await patch(mira, item.threadId, { move: "launch" })).status).toBe(400);+ const again = await team.as(mira, "POST", "/api/board/items", { groupId: launch.id, title: "Twice", threadId: item.threadId });+ expect([again.status, again.body.code]).toEqual([409, "board_exists"]);+ const madeOf = await add(mira, { groupId: launch.id, title: "The room's own thread", threadId: launch.threadId });+ expect(madeOf.threadId).toBe(launch.threadId);+ expect((await team.as(mira, "POST", "/api/board/items", { groupId: payDesk.id, title: "Wrong room", threadId: item.threadId })).status).toBe(404);+}, hostTimeout(60_000));++it("DELETE removes the item and leaves its thread", async () => {+ const item = await add(mira, { groupId: launch.id, title: "Throwaway", text: "Keep this line." });+ const removed = await team.as(mira, "DELETE", `/api/board/items/${item.threadId}`);+ expect(removed.status, JSON.stringify(removed.body)).toBe(200);+ expect((await board(mira)).map((one) => one.threadId)).not.toContain(item.threadId);+ expect((await messages(mira, item.threadId)).map((line) => line.text)).toEqual(["Keep this line."]);+ expect((await team.as(mira, "DELETE", `/api/board/items/${item.threadId}`)).status).toBe(404);+}, hostTimeout(60_000));++it("keeps the board across a restart and starts nothing on it", async () => {+ const before = await board(olive);+ await team.relaunch();+ expect(await board(olive)).toEqual(before);+ await new Promise((resolve) => setTimeout(resolve, 1_500));+ expect(await idle()).toBe(true);+ const first = before.find((one) => one.title === "Draft the launch post")!;+ expect(await messages(olive, first.threadId)).toHaveLength(1);+}, hostTimeout(120_000));++it("a personal Cloud has no board", async () => {+ expect((await fx.onCloud("GET", "/api/board")).status).toBe(404);+ expect((await fx.onCloud("POST", "/api/board/items", { groupId: "x", title: "x" })).status).toBe(404);+}, hostTimeout(60_000));diff --git a/server/config.ts b/server/config.tsindex 7d3696224a..991c8c24ee 100644--- a/server/config.ts+++ b/server/config.ts@@ -226,7 +226,7 @@ const featureConfigSchema = z.object({/** Room jobs to several members run side by side, each in a thread of its own. On unless false. */parallelRoomJobs: z.boolean().optional(),acpPlanLines: z.boolean().optional(), // An ACP agent's plan as activity lines. Off unless true.-}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional(), skillBurger: z.boolean().optional(), threadTabs: z.boolean().optional(), roomFeed: z.boolean().optional() }); // skillBurger: Skill Burgers in chat, the side menu and the bot panel, and the tools that run them, on unless false; threadTabs: a bot's threads as tabs above its chat, off unless true; roomFeed: a room's threads as one feed with the open thread beside it, off unless true; cloudComputerAutoReplace: set a dead or silent cloud computer aside (kept seven days with its files) and give its bot a new one by itself, on unless false (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)+}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional(), skillBurger: z.boolean().optional(), threadTabs: z.boolean().optional(), roomFeed: z.boolean().optional(), teamBoard: z.boolean().optional() }); // skillBurger: Skill Burgers in chat, the side menu and the bot panel, and the tools that run them, on unless false; threadTabs: a bot's threads as tabs above its chat, off unless true; roomFeed: a room's threads as one feed with the open thread beside it, off unless true; teamBoard: the Team Board on a Team Cloud (docs/team-board.md), off unless true; cloudComputerAutoReplace: set a dead or silent cloud computer aside (kept seven days with its files) and give its bot a new one by itself, on unless false (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)const onboardingConfigSchema = z.object({completedAt: z.string().trim().max(40).optional(),version: z.number().int().min(0).max(1000).optional(),@@ -467,7 +467,7 @@ export interface AppConfig extends HelperConfig {context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };memory?: { captureQuietMs?: number; tidyHour?: number };localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };- features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean; phonePush?: boolean; skillBurger?: boolean; threadTabs?: boolean; roomFeed?: boolean };+ features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean; phonePush?: boolean; skillBurger?: boolean; threadTabs?: boolean; roomFeed?: boolean; teamBoard?: boolean };onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };browserProfiles?: BrowserProfile[];browserEngine?: BrowserEngineConfig;diff --git a/server/index.ts b/server/index.tsindex 486f9b0a77..c0cc5e72dd 100644--- a/server/index.ts+++ b/server/index.ts@@ -598,7 +598,7 @@ import { createTrustAnswers } from "./host/trust-answers.ts";import { createInternalThreadRoutes } from "./routes/internal-threads.ts";import { createBrowserEvidenceRoutes } from "./routes/browser-evidence.ts";import { createSignInCardRoutes } from "./routes/sign-in-cards.ts";-import { createInternalChiefTeamRoutes } from "./routes/internal-chief-team.ts"; import { createInternalModelRoutes } from "./routes/internal-models.ts"; import { createOwnThreads } from "./host/own-threads.ts"; import { createEngineHints } from "./host/engine-hints.ts"; import { burstDefaultModel, burstProposalRefusal, createBurstHost } from "./host/burst-host.ts"; import { expandBurstTurnText } from "./burst/command.ts"; import { createBurstProposalRoutes, createBurstRoutes } from "./routes/burst.ts"; import { createCheckBacks } from "./host/check-backs.ts"; import { writeCheckBackLine } from "./host/check-back-host.ts"; import { checkBackRefusal, createCheckBackRoutes, createCheckBackToolRoutes } from "./routes/check-backs.ts"; import { createHandoffStatus } from "./host/handoff-status.ts";+import { createInternalChiefTeamRoutes } from "./routes/internal-chief-team.ts"; import { createInternalModelRoutes } from "./routes/internal-models.ts"; import { createOwnThreads } from "./host/own-threads.ts"; import { createEngineHints } from "./host/engine-hints.ts"; import { burstDefaultModel, burstProposalRefusal, createBurstHost } from "./host/burst-host.ts"; import { expandBurstTurnText } from "./burst/command.ts"; import { createBurstProposalRoutes, createBurstRoutes } from "./routes/burst.ts"; import { createCheckBacks } from "./host/check-backs.ts"; import { createTeamBoard } from "./board/wiring.ts"; import { writeCheckBackLine } from "./host/check-back-host.ts"; import { checkBackRefusal, createCheckBackRoutes, createCheckBackToolRoutes } from "./routes/check-backs.ts"; import { createHandoffStatus } from "./host/handoff-status.ts";import { createRoomHoldRoutes } from "./routes/room-holds.ts";import { checkedGroupResponder, createGroupRoutes } from "./routes/groups.ts";import { createChannelRoutes } from "./routes/channels.ts";@@ -11378,7 +11378,7 @@ function claimPhoneSecretBotDeletion(botId: string): (() => void) | null {}const secretCards = createSecretCards({ store, cfg, botLogins, vaultStore: logins, vaultReader: vaultReaders.turn, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), threadLanguage, email: { connect: (request, reading) => emailService.connect(request, reading), refusal: () => emailService.status().reason, connected: (address) => { const one = emailService.store.get(address); return Boolean(one && !one.problem); }, sendingProblem: (address) => emailService.sendingProblem(address), account: (address) => emailService.status().accounts.find((one) => one.address.toLowerCase() === address.toLowerCase()), checkOutgoing: (address, fields) => emailService.checkOutgoing(address, fields), profileAddress: () => cfg.profile?.email?.trim() || undefined }, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });-ROUTES.push(createCheckBackRoutes({ checkBacks, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, messageId) => cardAnswerRefusal(auth, threadId, messageId, "deny") })); ROUTES.push(createBurstRoutes({ owner: (id) => burst.owner(id), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, id) => cardAnswerRefusal(auth, threadId, id, "allow"), view: (id) => burst.view(id), run: (id) => burst.run(id), cancel: (id) => burst.cancel(id), retry: (id) => burst.retryFailed(id), edit: (id, plan) => burst.edit(id, plan) })); ROUTES.push(createSecretCardRoutes({ cards: secretCards, phoneSecretSubmissions, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), answerContext: (auth, botId, threadId) => ({ personalCloud: Boolean(CLOUD_PERSONAL), shared: sharedMembership(), owner: (CLOUD_TEAM ? teamOwners.routing.askedPerson(botId, threadId) : null) ?? threadStarters.get(threadId) ?? null, person: auth.kind === "session" ? personKey(auth.session) : null }) }));+const teamBoard = createTeamBoard({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), enabled: () => cfg.features?.teamBoard === true, store, visible: (auth) => visibleTo(viewerFor(auth)), person: (auth) => auth.kind === "session" && auth.session.email ? { person: personKey(auth.session), name: messageSender(auth)?.name ?? "" } : null, sender: messageSender, opened: (auth, threadId) => { if (auth.kind === "session") threadStarters.set(threadId, actorKey(auth)); }, roomRefusal: (groupId) => phoneSecretSubmissions.hasGroup(groupId) ? "This room is securely saving a credential. Try again when it finishes." : null, broadcast }); ROUTES.push(teamBoard.routes); ROUTES.push(createCheckBackRoutes({ checkBacks, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, messageId) => cardAnswerRefusal(auth, threadId, messageId, "deny") })); ROUTES.push(createBurstRoutes({ owner: (id) => burst.owner(id), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), refusal: (auth, threadId, id) => cardAnswerRefusal(auth, threadId, id, "allow"), view: (id) => burst.view(id), run: (id) => burst.run(id), cancel: (id) => burst.cancel(id), retry: (id) => burst.retryFailed(id), edit: (id, plan) => burst.edit(id, plan) })); ROUTES.push(createSecretCardRoutes({ cards: secretCards, phoneSecretSubmissions, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), answerContext: (auth, botId, threadId) => ({ personalCloud: Boolean(CLOUD_PERSONAL), shared: sharedMembership(), owner: (CLOUD_TEAM ? teamOwners.routing.askedPerson(botId, threadId) : null) ?? threadStarters.get(threadId) ?? null, person: auth.kind === "session" ? personKey(auth.session) : null }) }));// By design OpenMausBot never receives a website password: the person signs in where the bot works, and the bot uses that session.@@ -11626,7 +11626,7 @@ function configStatus() {autoRecall: autoRecallEnabled(cfg),roomMemoryCapture: roomMemoryCaptureEnabled(cfg),parallelRoomJobs: parallelRoomJobsEnabled(cfg),- savedSteps: savedStepsEnabled(cfg), savedStepsHere: savedSteps.here(), skillBurger: skillBurgerEnabled(cfg), threadTabs: cfg.features?.threadTabs === true, roomFeed: cfg.features?.roomFeed === true,+ savedSteps: savedStepsEnabled(cfg), savedStepsHere: savedSteps.here(), skillBurger: skillBurgerEnabled(cfg), threadTabs: cfg.features?.threadTabs === true, roomFeed: cfg.features?.roomFeed === true, teamBoard: CLOUD_TEAM ? cfg.features?.teamBoard === true : undefined,usbPhoneTakeover: HAS_USB_PORT ? usbPhoneTakeoverEnabled(cfg) : undefined,},onboarding: {diff --git a/server/request-auth.ts b/server/request-auth.tsindex 69691a652c..76d0610b4b 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -508,6 +508,11 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["GET"], path: /^\/api\/team-files(?:\/file)?$/ },{ methods: ["PUT"], path: /^\/api\/team-files\/file$/ },{ methods: ["POST"], path: /^\/api\/team-files\/(?:folder|rename|delete)$/ },+ // a Team Cloud's board: the handler shows and changes an item only for someone who sees its room thread and may write in+ // the room (routes/board.ts); off a Team Cloud, or with the board off, they answer 404+ { methods: ["GET"], path: /^\/api\/board$/ },+ { methods: ["POST"], path: /^\/api\/board\/items$/ },+ { methods: ["PATCH", "DELETE"], path: /^\/api\/board\/items\/[\w-]+$/ },// 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/board.ts b/server/routes/board.tsnew file mode 100644index 0000000000..2ce968b04d--- /dev/null+++ b/server/routes/board.ts@@ -0,0 +1,129 @@+// The Team Board's routes, for every member and admin of a Team Cloud with the board switched on (docs/team-board.md).+// Anywhere else none of them exists: they answer 404 like any unknown path.+// GET /api/board[?groupId=] the items the caller can see, oldest first+// POST /api/board/items a new item, on a new room thread or on one the room has+// PATCH /api/board/items/:threadId a move (cancel, reopen, release, done) and changed fields+// DELETE /api/board/items/:threadId the item only; its thread stays+// Security: an item is shown, changed or removed only for someone who can see its room thread, and anything that writes+// needs what writing in the room needs (chat on every bot of it); an item they cannot see answers as a missing one.+import { atLeast } from "../../shared/bot-access.ts";+import { BOARD_LIMITS, type BoardPersonMove } from "../../shared/board.ts";+import type { VisibleSet } from "../bot-visibility.ts";+import type { Board } from "../board/host.ts";+import { BoardError, type BoardMove } from "../board/state.ts";+import { refusalFor } from "../host/bot-access-gate.ts";+import { messageTextRefusal } from "../message-text.ts";+import type { RequestAuth } from "../request-auth.ts";+import { PASS, type RouteContext, type RouteHandler } from "./table.ts";++export const BOARD_PATH = "/api/board";+const ITEM = /^\/api\/board\/items\/([\w-]+)$/;++export interface BoardPerson {+ /** The person key. */+ person: string;+ name: string;+}++export interface BoardRouteDeps {+ board: Board;+ /** A Team Cloud with `features.teamBoard` on. */+ on(): boolean;+ /** The signed-in person; null for a session that is no one. */+ person(auth: RequestAuth): BoardPerson | null;+ visible(auth: RequestAuth): Pick<VisibleSet, "member" | "group" | "thread" | "level">;+ room(groupId: string): { dm: boolean; memberIds: readonly string[] } | null;+ botName(botId: string): string | undefined;+ /** Why the room takes no new thread now, or null. */+ roomRefusal(groupId: string): string | null;+ /** Opens a room thread without making it the room's current one and writes `text` as the person's first line in it,+ * starting no turn. Returns the new thread's id. */+ openThread(auth: RequestAuth, groupId: string, title: string, text: string): string;+}++const MOVES: Record<BoardPersonMove, (result: string | undefined) => BoardMove> = {+ cancel: (result) => ({ move: "cancel", result }),+ reopen: () => ({ move: "reopen" }),+ release: () => ({ move: "release" }),+ done: (result) => ({ move: "done", result }),+};++const record = (body: unknown): Record<string, unknown> | null => body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : null;++export function createBoardRoutes(deps: BoardRouteDeps): RouteHandler {+ /** Why this person may not write in the room: a bot of it they may only view. */+ const writeRefusal = (visible: ReturnType<BoardRouteDeps["visible"]>, memberIds: readonly string[]): string | null => {+ if (!visible.member) return null;+ for (const botId of memberIds) {+ const level = visible.level(botId);+ if (level !== "none" && !atLeast(level, "chat")) return refusalFor(deps.botName(botId) ?? "this bot", "chat").error;+ }+ return null;+ };++ return async (ctx: RouteContext) => {+ const { req, res, url, path, method, auth, json, readBody } = ctx;+ if (path !== BOARD_PATH && !path.startsWith(`${BOARD_PATH}/`)) return PASS;+ if (!deps.on()) return PASS;+ const person = deps.person(auth);+ if (!person) { req.resume(); return json(res, 403, { error: "Sign in to the team to use its board.", code: "forbidden" }); }+ const visible = deps.visible(auth);+ const seen = (groupId: string, threadId: string) => visible.group(groupId) && visible.thread(threadId);+ try {+ if (path === BOARD_PATH && method === "GET") {+ const groupId = url.searchParams.get("groupId") || undefined;+ return json(res, 200, { items: deps.board.list({ groupId }).filter((item) => seen(item.groupId, item.threadId)) });+ }+ if (path === `${BOARD_PATH}/items` && method === "POST") {+ const body = record(await readBody(req));+ if (!body) return json(res, 400, { error: "Send a JSON object.", code: "board_bad_input" });+ const groupId = typeof body.groupId === "string" ? body.groupId : "";+ const room = groupId ? deps.room(groupId) : null;+ if (!room || room.dm || !visible.group(groupId)) return json(res, 404, { error: "No such room.", code: "board_not_found" });+ const threadId = body.threadId === undefined ? undefined : typeof body.threadId === "string" ? body.threadId : "";+ if (threadId !== undefined && !visible.thread(threadId)) return json(res, 404, { error: "No such thread in that room.", code: "board_not_found" });+ const refused = writeRefusal(visible, room.memberIds) ?? (threadId ? null : deps.roomRefusal(groupId));+ if (refused) return json(res, 403, { error: refused, code: "forbidden" });+ const text = body.text;+ const textProblem = messageTextRefusal(text);+ if (textProblem || (typeof text === "string" && text.length > BOARD_LIMITS.textMax)) {+ return json(res, 400, { error: textProblem ?? `The first line is at most ${BOARD_LIMITS.textMax} characters.`, code: "board_bad_input" });+ }+ const item = deps.board.create({+ groupId, title: body.title, needs: body.needs, labels: body.labels, forBotId: body.forBotId, threadId,+ createdBy: { kind: "person", id: person.person, name: person.name },+ }, (title) => deps.openThread(auth, groupId, title, typeof text === "string" && text.trim() ? text.trim() : title));+ return json(res, 201, { item });+ }+ const m = ITEM.exec(path);+ if (!m || (method !== "PATCH" && method !== "DELETE")) { req.resume(); return json(res, 404, { error: "not found" }); }+ const current = deps.board.get(m[1]!);+ if (!current || !seen(current.groupId, current.threadId)) { req.resume(); return json(res, 404, { error: "No board item on that thread.", code: "board_not_found" }); }+ const refused = writeRefusal(visible, deps.room(current.groupId)?.memberIds ?? []);+ if (refused) { req.resume(); return json(res, 403, { error: refused, code: "forbidden" }); }+ if (method === "DELETE") {+ req.resume();+ deps.board.remove(current.threadId);+ return json(res, 200, { ok: true });+ }+ const body = record(await readBody(req));+ if (!body) return json(res, 400, { error: "Send a JSON object.", code: "board_bad_input" });+ const move = body.move;+ if (move !== undefined && !(typeof move === "string" && Object.hasOwn(MOVES, move))) {+ return json(res, 400, { error: "move is one of cancel, reopen, release or done.", code: "board_bad_input" });+ }+ if (body.result !== undefined && typeof body.result !== "string") return json(res, 400, { error: "result must be text.", code: "board_bad_input" });+ const result = body.result as string | undefined;+ const moving = move ? MOVES[move as BoardPersonMove](result) : undefined;+ const item = deps.board.patch(current.threadId, {+ ...(moving ? { move: moving } : {}),+ title: body.title, labels: body.labels, needs: body.needs, forBotId: body.forBotId,+ ...(moving && "result" in moving ? {} : { result: body.result }),+ }, { kind: "person", person: person.person });+ return json(res, 200, { item });+ } catch (error) {+ if (error instanceof BoardError) return json(res, error.status, { error: error.message, code: error.code });+ throw error;+ }+ };+}diff --git a/shared/board.ts b/shared/board.tsnew file mode 100644index 0000000000..fa3bbcd033--- /dev/null+++ b/shared/board.ts@@ -0,0 +1 @@+export * from "../packages/phone-protocol/src/board.ts";diff --git a/src/components/settings/SettingsWindow.test.ts b/src/components/settings/SettingsWindow.test.tsindex 1ac9afffc3..b333c301fb 100644--- a/src/components/settings/SettingsWindow.test.ts+++ b/src/components/settings/SettingsWindow.test.ts@@ -302,6 +302,12 @@ describe("Settings → Features", () => {expect(api).toHaveBeenCalledWith("/api/config", { method: "PATCH", body: JSON.stringify({ features: { skillBurger: false } }) });});+ it("shows the Board switch only where the server reports it (a Team Cloud)", () => {+ fixture.config = { cloudHome: true, team: { name: "Acme" }, features: { skillBurger: true, threadTabs: false, teamBoard: false } };+ expect(render("features")).toContain("Board");+ expect(featureSwitches()).toEqual({ skillBurger: true, threadTabs: false, teamBoard: false });+ });+it("shows no switch its server doesn't know, and isn't offered to a team's member", () => {fixture.config = {};render("features");diff --git a/src/components/settings/pages/FeaturesPage.tsx b/src/components/settings/pages/FeaturesPage.tsxindex c9dc805fb1..490e4d57c2 100644--- a/src/components/settings/pages/FeaturesPage.tsx+++ b/src/components/settings/pages/FeaturesPage.tsx@@ -10,9 +10,10 @@ const COPY: Record<Feature, { title: LocaleKey; line: LocaleKey }> = {skillBurger: { title: "settings.features.skillBurger", line: "settings.features.skillBurgerLine" },threadTabs: { title: "settings.features.threadTabs", line: "settings.features.threadTabsLine" },roomFeed: { title: "settings.features.roomFeed", line: "settings.features.roomFeedLine" },+ teamBoard: { title: "settings.features.teamBoard", line: "settings.features.teamBoardLine" },};-/** One switch kept in this place's config.json; shown once its server says it knows the switch. */+/** One switch kept in this place's config.json; shown once its server says it knows the switch (the board: only a Team Cloud's). */function FeatureRow({ name }: { name: Feature }) {const on = useFeature(name);const known = useStoreSelector((state) => typeof state.config?.features?.[name] === "boolean");@@ -49,6 +50,7 @@ export function FeaturesPage() {<FeatureRow name="skillBurger" /><FeatureRow name="threadTabs" /><FeatureRow name="roomFeed" />+ <FeatureRow name="teamBoard" /></SettingsRows></SettingsGroup>);diff --git a/src/lib/feature-flags.ts b/src/lib/feature-flags.tsindex ac30e161cf..1b9d55caa0 100644--- a/src/lib/feature-flags.ts+++ b/src/lib/feature-flags.ts@@ -1,7 +1,7 @@import { t } from "./i18n";export interface FeatureFlagConfig {- features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean; usbPhoneTakeover?: boolean; skillBurger?: boolean; threadTabs?: boolean; roomFeed?: boolean };+ features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean; usbPhoneTakeover?: boolean; skillBurger?: boolean; threadTabs?: boolean; roomFeed?: boolean; teamBoard?: boolean };browserEngine?: { kind: "engine" | "unavailable"; reason?: string; installable?: boolean; installing?: boolean; installError?: string };}@@ -109,3 +109,7 @@ export function threadTabsEnabled(config: FeatureFlagConfig | null | undefined):export function roomFeedEnabled(config: FeatureFlagConfig | null | undefined): boolean {return config?.features?.roomFeed === true;}++export function teamBoardEnabled(config: FeatureFlagConfig | null | undefined): boolean {+ return config?.features?.teamBoard === true;+}diff --git a/src/lib/use-feature.ts b/src/lib/use-feature.tsindex 6d2cb494a2..f1121311ee 100644--- a/src/lib/use-feature.ts+++ b/src/lib/use-feature.ts@@ -1,14 +1,15 @@-import { roomFeedEnabled, skillBurgerEnabled, threadTabsEnabled } from "@/lib/feature-flags";+import { roomFeedEnabled, skillBurgerEnabled, teamBoardEnabled, threadTabsEnabled } from "@/lib/feature-flags";import type { ConfigStatus } from "@/state/store";import { useStoreSelector } from "@/state/store-select";/** Switches on Settings → Features, kept in the place's config.json (`features.<name>`), so its server reads them too. */-export type Feature = "skillBurger" | "threadTabs" | "roomFeed";+export type Feature = "skillBurger" | "threadTabs" | "roomFeed" | "teamBoard";const FEATURES: Record<Feature, (config: ConfigStatus | null | undefined) => boolean> = {skillBurger: skillBurgerEnabled,threadTabs: threadTabsEnabled,roomFeed: roomFeedEnabled,+ teamBoard: teamBoardEnabled,};/** Whether a switch on Settings → Features is on. */diff --git a/src/locales/de.json b/src/locales/de.jsonindex cf26339c16..f3b502db44 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -4390,6 +4390,8 @@"room.thread.panel": "Thread","room.thread.close": "Thread schließen","room.thread.resize": "Thread-Breite ändern",+ "settings.features.teamBoard": "Board",+ "settings.features.teamBoardLine": "Verfolge Arbeit in Gruppenchats als Einträge mit Status, Labels und dem, worauf jeder wartet","settings.features.error": "Das konnte nicht gespeichert werden. Prüfe deine Verbindung und versuche es erneut.","skillBurger.pill.cooking": "Wird gekocht… {count}","skillBurger.pill.add": "Hinzufügen",diff --git a/src/locales/en.json b/src/locales/en.jsonindex f0ae80479c..f7f0625b81 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -12010,6 +12010,8 @@"room.thread.panel": "Thread","room.thread.close": "Close thread","room.thread.resize": "Resize thread",+ "settings.features.teamBoard": "Board",+ "settings.features.teamBoardLine": "Track work in group chats as items with a state, labels and what each one waits for","settings.features.error": "Couldn't save that. Check your connection and try again.","skillBurger.pill.cooking": "Cooking… {count}","skillBurger.pill.add": "Add",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 641873c87d..1f5fa11945 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -12010,6 +12010,8 @@"room.thread.panel": "Conversa","room.thread.close": "Fechar conversa","room.thread.resize": "Redimensionar conversa",+ "settings.features.teamBoard": "Quadro",+ "settings.features.teamBoardLine": "Acompanhe o trabalho nos chats em grupo como itens com status, rótulos e o que cada um espera","settings.features.error": "Não foi possível salvar. Verifique sua conexão e tente de novo.","skillBurger.pill.cooking": "Cozinhando… {count}","skillBurger.pill.add": "Adicionar",diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex 4fcc9c524f..6eb8366fd6 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -169,7 +169,7 @@ export interface ConfigStatus {/** What a paired phone calls this computer; "" uses the default. */computerName?: string;/** Opt-in flags. Absent means off. */- features?: { skillAuthoring: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean; usbPhoneTakeover?: boolean; skillBurger?: boolean; threadTabs?: boolean; roomFeed?: boolean };+ features?: { skillAuthoring: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; savedSteps?: boolean; savedStepsHere?: boolean; usbPhoneTakeover?: boolean; skillBurger?: boolean; threadTabs?: boolean; roomFeed?: boolean; teamBoard?: boolean };/** First-run progress: whether the welcome tour was finished and which* one-time hints were dismissed. Server-owned so it follows the workspace. */onboarding?: OnboardingStatus;