Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/architecture/sharing.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,22 @@ feature page). A client draws a conversation's saved state with one
`conversation.saved_status` call, and a user erasure takes the user's conversation rows,
saved ones included.

## Collection spend policy

`collection.budget_set` lets a collection's admin change its rolling 24-hour USD cap,
its separate named-user cap and its budget warning inbox. An omitted field keeps its
stored value; a zero cap inherits the server default, and an empty inbox disables
warnings. A warning inbox must belong to the same collection. Personal, missing and
retired collections cannot be configured through this operation.

The audited operation holds the directory-row claim from read through write and carries
every unrelated directory column forward. It changes no collection membership, tree,
visibility or login state. `namespace.register` continues to refuse collection names.
Budget status and admission guards read the same directory columns for collections as
for other namespaces; the operation changes no spend events or enforcement thresholds.
Both adjacent builds read the same stored fields, so the operation requires no schema
change. The Library's collection menu provides the same budget controls.

## Identity

A service in front of Loom (a chat app) signs a short-lived token for each request it
Expand Down
3 changes: 2 additions & 1 deletion docs/reference/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal
<!-- Generated by `python scripts/codegen/docs_reference.py`; edit the source, not this region. -->
<!-- prettier-ignore-start -->

375 operations in 43 groups. Every op is served at `POST /v1/<op>` and as the MCP tool `loom_<op>` (dots become underscores).
376 operations in 43 groups. Every op is served at `POST /v1/<op>` and as the MCP tool `loom_<op>` (dots become underscores).

Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row.

Expand Down Expand Up @@ -245,6 +245,7 @@ Fields for every `collection` op: [operations/collection.md](operations/collecti

| Operation | Summary | Role | Kind | Listed under `all` | Audit |
| --- | --- | --- | --- | --- | --- |
| [`collection.budget_set`](operations/collection.md#collectionbudget_set) | Change only a collection's spend caps and warning destination. | admin | idempotent | no | yes |
| [`collection.create`](operations/collection.md#collectioncreate) | Create a collection: a namespace read and written only through grants. | viewer | idempotent | no | yes |
| [`collection.delete`](operations/collection.md#collectiondelete) | Delete a collection with what it holds: a purging erasure of the namespace (documents, chunks, originals, memory leave the disk), then it leaves the directory and the tree, and its name is never used… | admin | idempotent | no | yes |
| [`collection.list`](operations/collection.md#collectionlist) | List the collections the caller can read, by name. | viewer | read | no | |
Expand Down
22 changes: 22 additions & 0 deletions docs/reference/operations/collection.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,28 @@ Every op is `POST /v1/<op>` over HTTP and the MCP tool `loom_<op>`. The identity

<!-- prettier-ignore-start -->

## `collection.budget_set`

Change only a collection's spend caps and warning destination.

`POST /v1/collection.budget_set` · MCP `loom_collection_budget_set` · role `admin` · idempotent · audited · not listed under the MCP `all` toolset

| Input field | Type | Default | Meaning |
| --- | --- | --- | --- |
| `org` | `str` | required | The tenant (first element of the identity tuple). |
| `namespace` | `str` | required | The namespace the op reads or writes. |
| `daily_cost_cap_usd` | `float \| None` | `None` | Collection cap in USD per rolling 24 hours; 0 inherits the server default, omit keeps it. |
| `daily_user_cost_cap_usd` | `float \| None` | `None` | Named-user cap in USD per rolling 24 hours; 0 inherits the server default, omit keeps it. |
| `budget_alert_inbox` | `str \| None` | `None` | An existing task inbox owned by this collection; '' disables warnings, omit keeps it. |

| Output field | Type | Meaning |
| --- | --- | --- |
| `namespace` | `str` | The namespace the op reads or writes. |
| `changed` | `bool` | |
| `daily_cost_cap_usd` | `float` | |
| `daily_user_cost_cap_usd` | `float` | |
| `budget_alert_inbox` | `str` | |

## `collection.create`

Create a collection: a namespace read and written only through grants.
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/status.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets).
<!-- Generated by `python scripts/codegen/docs_reference.py`; edit the source, not this region. -->
<!-- prettier-ignore-start -->

375 operations, 261 of them experimental.
376 operations, 262 of them experimental.

| Group | Stable | Experimental |
| --- | --- | --- |
Expand All @@ -36,7 +36,7 @@ serves is in the [MCP reference](./mcp.md#toolsets).
| `blacklist` | 1 | [`blacklist.add`](operations/blacklist.md#blacklistadd), [`blacklist.remove`](operations/blacklist.md#blacklistremove), [`blacklist.sweep`](operations/blacklist.md#blacklistsweep) |
| `calibration` | 0 | [`calibration.get`](operations/calibration.md#calibrationget) |
| `code` | 28 | [`code.backport_gap`](operations/code.md#codebackport_gap), [`code.backport_gaps`](operations/code.md#codebackport_gaps), [`code.bisect_candidates`](operations/code.md#codebisect_candidates), [`code.blame_range`](operations/code.md#codeblame_range), [`code.callees`](operations/code.md#codecallees), [`code.conventions`](operations/code.md#codeconventions), [`code.coverage_claim`](operations/code.md#codecoverage_claim), [`code.examples`](operations/code.md#codeexamples), [`code.files`](operations/code.md#codefiles), [`code.first_build`](operations/code.md#codefirst_build), [`code.map`](operations/code.md#codemap), [`code.outline`](operations/code.md#codeoutline), [`code.path_guards`](operations/code.md#codepath_guards), [`code.pr_check`](operations/code.md#codepr_check), [`code.reindex`](operations/code.md#codereindex), [`code.repo.set_access`](operations/code.md#codereposet_access), [`code.repo.set_source`](operations/code.md#codereposet_source), [`code.review_brief`](operations/code.md#codereview_brief), [`code.setting_facts`](operations/code.md#codesetting_facts), [`code.symbol_history`](operations/code.md#codesymbol_history), [`code.test_gate`](operations/code.md#codetest_gate), [`code.test_home`](operations/code.md#codetest_home), [`code.tests_for`](operations/code.md#codetests_for), [`code.verify_citations`](operations/code.md#codeverify_citations) |
| `collection` | 0 | [`collection.create`](operations/collection.md#collectioncreate), [`collection.delete`](operations/collection.md#collectiondelete), [`collection.list`](operations/collection.md#collectionlist), [`collection.move`](operations/collection.md#collectionmove) |
| `collection` | 0 | [`collection.budget_set`](operations/collection.md#collectionbudget_set), [`collection.create`](operations/collection.md#collectioncreate), [`collection.delete`](operations/collection.md#collectiondelete), [`collection.list`](operations/collection.md#collectionlist), [`collection.move`](operations/collection.md#collectionmove) |
| `conflicts` | 2 | [`conflicts.allowlist_list`](operations/conflicts.md#conflictsallowlist_list), [`conflicts.allowlist_remove`](operations/conflicts.md#conflictsallowlist_remove), [`conflicts.propose_revision`](operations/conflicts.md#conflictspropose_revision) |
| `connection` | 0 | [`connection.disconnect`](operations/connection.md#connectiondisconnect), [`connection.list`](operations/connection.md#connectionlist) |
| `consolidations` | 0 | [`consolidations.list`](operations/consolidations.md#consolidationslist) |
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/api/collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@ import { COLLECTIONS_PAGE } from "../lib/collections";

// ===== Collections =====

export interface CollectionBudgetPolicy {
daily_cost_cap_usd: number;
daily_user_cost_cap_usd: number;
budget_alert_inbox: string;
}

/** Change only the explicitly supplied spend policy fields of an administered collection. */
export async function setCollectionBudget(
org: string,
namespace: string,
patch: Partial<CollectionBudgetPolicy>,
): Promise<CollectionBudgetPolicy & { namespace: string; changed: boolean }> {
return post("/v1/collection.budget_set", { ...patch, org, namespace });
}

/** Mirrors `server/identity/api/models_collections.py::_CollectionEntry`. */
export interface CollectionEntry {
namespace: string;
Expand Down
145 changes: 145 additions & 0 deletions frontend/src/flows/CollectionBudgetDialog.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl";
import * as api from "../api";
import userEvent from "@testing-library/user-event";
import { CollectionBudgetDialog } from "./CollectionBudgetDialog";
import { Picker, entry, read } from "../test/libraryCollections";
import { toast } from "../components/Toast";

vi.mock("../api", async (original) => ({
...(await original<typeof import("../api")>()),
getNamespace: vi.fn(),
setCollectionBudget: vi.fn(),
}));
vi.mock("../components/Toast", () => ({ toast: vi.fn(), toastError: vi.fn() }));

beforeEach(() => {
vi.mocked(api.getNamespace).mockResolvedValue({
namespace: "col-a",
daily_cost_cap_usd: 2,
daily_user_cost_cap_usd: 1,
budget_alert_inbox: "owned",
} as api.NamespaceInfo);
vi.mocked(api.setCollectionBudget).mockResolvedValue({
namespace: "col-a",
changed: true,
daily_cost_cap_usd: 2,
daily_user_cost_cap_usd: 0.5,
budget_alert_inbox: "",
});
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});

it("reads the collection policy and saves only changed budget fields to that collection", async () => {
const close = vi.fn();
render(<CollectionBudgetDialog org="o" collection={entry("col-a")} onClose={close} />);
const field = await screen.findByLabelText("Daily cap per user (USD)");
expect(api.getNamespace).toHaveBeenCalledWith(
{ org: "o", namespace: "col-a" },
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
fireEvent.change(field, { target: { value: "0.5" } });
fireEvent.change(screen.getByLabelText("Budget warning inbox"), { target: { value: "" } });
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save budget" })));
expect(api.setCollectionBudget).toHaveBeenCalledWith("o", "col-a", {
daily_user_cost_cap_usd: 0.5,
budget_alert_inbox: "",
});
expect(close).toHaveBeenCalledTimes(1);
});

it("keeps a failed save open and sends no write before its policy read succeeds", async () => {
vi.mocked(api.getNamespace).mockRejectedValueOnce(new TypeError("Failed to fetch"));
const close = vi.fn();
render(<CollectionBudgetDialog org="o" collection={entry("col-a")} onClose={close} />);
const error = await screen.findByRole("alert");
expect(error).toHaveTextContent(/connection|reach|network/i);
expect(error).not.toHaveTextContent(/saved|committed|re-check|check before/i);
expect(screen.getByRole("button", { name: "Save budget" })).toBeDisabled();
expect(api.setCollectionBudget).not.toHaveBeenCalled();
expect(close).not.toHaveBeenCalled();
});

it("retains the draft and the server refusal on a failed write", async () => {
vi.mocked(api.setCollectionBudget).mockRejectedValueOnce(new Error("Inbox belongs elsewhere"));
const close = vi.fn();
render(<CollectionBudgetDialog org="o" collection={entry("col-a")} onClose={close} />);
fireEvent.change(await screen.findByLabelText("Budget warning inbox"), { target: { value: "foreign" } });
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save budget" })));
await screen.findByRole("alert");
expect(screen.getByLabelText("Budget warning inbox")).toHaveValue("foreign");
expect(close).not.toHaveBeenCalled();
});

it("opens budget controls from the administered Library collection's actual menu", async () => {
const c = entry("col-a");
const view = render(<Picker org="o" namespace={null} current={c} collections={read([c])} onPick={vi.fn()} />);
await userEvent.click(screen.getByRole("button", { name: "Actions for col-a" }));
await userEvent.click(await screen.findByRole("menuitem", { name: "Budget…" }));
await waitFor(() => expect(screen.getByRole("dialog", { name: "Budget · col-a" })).toBeInTheDocument());
expect(await screen.findByLabelText("Daily cost cap (USD)")).toHaveValue(2);
const viewer = entry("col-a", { role: "viewer" });
view.rerender(<Picker org="o" namespace={null} current={viewer} collections={read([viewer])} onPick={vi.fn()} />);
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Budget · col-a" })).not.toBeInTheDocument());
});

it("an old save cannot close a later collection dialog or discard its draft", async () => {
let finish!: (value: Awaited<ReturnType<typeof api.setCollectionBudget>>) => void;
vi.mocked(api.setCollectionBudget).mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
}),
);
const a = entry("col-a"),
b = entry("col-b");
const places = read([a, b]);
const view = render(
<Picker org="o" namespace={null} current={a} place="col-a" collections={places} onPick={vi.fn()} />,
);
await userEvent.click(screen.getByRole("button", { name: "Actions for col-a" }));
await userEvent.click(await screen.findByRole("menuitem", { name: "Budget…" }));
fireEvent.change(await screen.findByLabelText("Daily cost cap (USD)"), { target: { value: "3" } });
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save budget" })));
expect(api.setCollectionBudget).toHaveBeenCalledWith("o", "col-a", { daily_cost_cap_usd: 3 });
view.rerender(<Picker org="o" namespace={null} current={b} place="col-b" collections={places} onPick={vi.fn()} />);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: "Actions for col-b" }));
await userEvent.click(await screen.findByRole("menuitem", { name: "Budget…" }));
const draft = await screen.findByLabelText("Daily cost cap (USD)");
fireEvent.change(draft, { target: { value: "7" } });
await act(async () =>
finish({
namespace: "col-a",
changed: true,
daily_cost_cap_usd: 3,
daily_user_cost_cap_usd: 1,
budget_alert_inbox: "owned",
}),
);
expect(screen.getByRole("dialog", { name: "Budget · col-b" })).toBeInTheDocument();
expect(screen.getByLabelText("Daily cost cap (USD)")).toHaveValue(7);
expect(toast).not.toHaveBeenCalled();
});

it.each(["viewer", "writer"] as const)(
"the unavailable Budget action remains keyboard reachable for a %s without reading or writing policy",
async (role) => {
const c = entry("col-a", { role });
render(<Picker org="o" namespace={null} current={c} collections={read([c])} onPick={vi.fn()} />);
const trigger = screen.getByRole("button", { name: "Actions for col-a" });
trigger.focus();
await userEvent.keyboard("{ArrowDown}");
const budget = await screen.findByRole("menuitem", { name: "Budget…" });
await waitFor(() => expect(budget).toHaveFocus());
expect(budget).toHaveAttribute("aria-disabled", "true");
expect(budget).toHaveAccessibleDescription("Needs admin on col-a. An admin of it can grant that.");
await userEvent.keyboard("{Enter} ");
await userEvent.click(budget);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(api.getNamespace).not.toHaveBeenCalled();
expect(api.setCollectionBudget).not.toHaveBeenCalled();
},
);
Loading
Loading