Public: anyone can read this; the crew can change it.

An app gets an ordered change stream: rooms, presence and durable order, with no dependency #16751

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/10839-an-app-gets-an-ordered-change-stream-roo → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/10839-an-app-gets-an-ordered-change-stream-roo was merged into main as 3f72871.

Review

Sign in to review this change.
25 files changed +632 −6
docs/features/sync.md added +18
@@ -0,0 +1,18 @@
1 ---
2 topic: Your apps
3 row: Ordered change stream (sync)
4 ---
5 # Ordered change stream (sync)
6
7 An app declares `"sync": true` at the top level of `forge.json` and gets a per-app ordered change stream from the forge, with no dependency. A change is any JSON value (at most 8 KB) appended to a **room**; the forge numbers it, gap-free within the app, so every client reads the same order.
8
9 - Read: `GET /api/v1/repos/:owner/:name/changes/:room?since=N` answers `{ changes: [{ seq, room, data, at }], next, here }`, oldest first, at most 500 (`limit` narrows). Send `next` as `since` after a reconnect to catch up from where you stopped.
10 - Append: `POST` the same path with `{ "data": <json> }` answers `201 { seq }`. Needs an `rw` token or a session.
11 - Presence: each read marks the reader present; `here` lists the usernames that touched the room in the last 30 seconds (in memory, not kept).
12 - MCP: the `changes` tool, `{ repo, room, since?, data? }`: with `data` it appends, without it reads. It is not in the short default list; `find_tool` reaches it.
13
14 Whoever may enter the app (`canEnterApp`) may read and append. An app that has not declared `sync` answers `404 not_synced`; a room name is letters, digits, `_`, `.`, `-` (64); an append over the rate (100 a second per app) is refused `429` (`retry-after: 1`); a body or value over the size is `413`/`422`; a read-only token is `403`. Rows live in `<data>/changes/<app>.sqlite` (bun:sqlite) on the forge, so they survive a restart. Code: `src/apps/changes.ts`, `src/apps/room_presence.ts`, `src/actions/app_changes.ts`; test `test/app-changes.test.ts`.
15
16 In the terminal: the palette's "Change stream" opens the `lobby` room (`src/tui/screens/app_changes.ts`); `o` picks another room, `a` appends a JSON value, `r` reads again. It goes through the same `readChanges`/`appendChange` as the API, so what is written there is what API readers see.
17
18 Not yet: a push channel (clients poll `since`), retention, and per-room permissions.
scripts/unreached-allow.json −1
@@ -1,5 +1,4 @@
11 [
2 "src/apps/changes.ts",
32 "src/apps/room.ts",
43 "src/spawn/pod.ts"
54 ]
scripts/unused-exports-allow.json −1
@@ -1,6 +1,5 @@
11 [
22 "src/apps/check-memory.ts usePodMemoryFile",
3 "src/apps/changes.ts openChanges",
43 "src/apps/room.ts openRooms",
54 "src/looks/archive.ts useLookStore",
65 "src/looks/archive.ts useLookStore",
src/actions/app_changes.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * An app's ordered change stream, for a person or an agent (#10839): the one

Stale: there is no apps action changes; the door is the MCP changes tool.

3 * door behind `GET`/`POST /api/v1/repos/:owner/:name/changes/:room`, the MCP
4 * `changes` tool and the terminal screen. The app declares `sync: true` in
5 * forge.json; whoever may enter the app may read and append. The store is
6 * `apps/changes.ts`, kept under the forge's data directory.
7 */
8
9 import { isRoom, openChanges, type Changes } from "../apps/changes.ts";
10 import { parseManifest } from "../apps/manifest.ts";
11 import { openRoomPresence, type RoomPresence } from "../apps/room_presence.ts";
12 import type { App } from "../app.ts";
13 import { readFileAt } from "../apps/checkout.ts";
14 import { getAppByRepo } from "../core/apps.ts";
15 import { canEnterApp, type Repo } from "../core/repos.ts";
16 import type { User } from "../core/users.ts";
17 import { resolveOid } from "../git/merge.ts";
18 import { repoDir } from "../git/repos.ts";
19
20 export type ChangesRefusal = "not_found" | "forbidden" | "not_synced";
21
22 export interface ChangesRead {
23 readonly changes: readonly { seq: number; room: string; data: unknown; at: number }[];
24 /** Pass this as `since` next time. */
25 readonly next: number;
26 readonly here: readonly string[];
27 }
28
29 export type ChangesResult<T> = { ok: true; value: T } | { ok: false; error: ChangesRefusal | { invalid: string } };
30
31 const stores = new WeakMap<App, Changes>();
32 const presence: RoomPresence = openRoomPresence();
33
34 function store(app: App): Changes {
35 let s = stores.get(app);
36 if (!s) stores.set(app, (s = openChanges(app.config.dataDir)));
37 return s;
38 }
39
40 async function declared(app: App, repo: Repo): Promise<boolean> {
41 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
42 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
43 if (tip === undefined) return false;
44 const [forgeJson, packageJson] = await Promise.all([readFileAt(dir, tip, "forge.json"), readFileAt(dir, tip, "package.json")]);
45 const manifest = parseManifest(forgeJson, packageJson);
46 return manifest.ok && manifest.value.sync === true;
47 }
48
49 async function gate(app: App, repo: Repo, user: User | undefined): Promise<ChangesResult<string>> {
50 const record = getAppByRepo(app.db, repo.id);
51 if (record === undefined) return { ok: false, error: "not_found" };
52 if (!canEnterApp(app.db, repo, record, user)) return { ok: false, error: user ? "forbidden" : "not_found" };
53 if (!(await declared(app, repo))) return { ok: false, error: "not_synced" };
54 return { ok: true, value: record.slug };
55 }
56
57 const view = (rows: readonly { seq: number; room: string; json: string; at: number }[], since: number) => ({
58 changes: rows.map((r) => ({ seq: r.seq, room: r.room, data: JSON.parse(r.json) as unknown, at: r.at })),
59 next: rows.length > 0 ? rows[rows.length - 1]!.seq : since,
60 });
61
62 /** Changes after `since` in a room; the reader is marked present. */
63 export async function readChanges(
64 app: App,
65 repo: Repo,
66 user: User | undefined,
67 room: string,
68 since: number,
69 limit?: number,
70 ): Promise<ChangesResult<ChangesRead>> {
71 const g = await gate(app, repo, user);
72 if (!g.ok) return g;
73 if (!isRoom(room)) return { ok: false, error: { invalid: "bad room" } };
74 const here = presence.touch(g.value, room, user?.username ?? "guest");
75 const rows = store(app).since(g.value, room, since, limit);
76 return { ok: true, value: { ...view(rows, since), here } };
77 }
78
79 /** Append one JSON value to a room; answers its sequence number. */
80 export async function appendChange(
81 app: App,
82 repo: Repo,
83 user: User | undefined,
84 room: string,
85 json: string,
86 ): Promise<ChangesResult<{ seq: number }>> {
87 const g = await gate(app, repo, user);
88 if (!g.ok) return g;
89 const out = store(app).append(g.value, room, json);
90 return out.ok ? { ok: true, value: { seq: out.seq } } : { ok: false, error: { invalid: out.why } };
91 }
src/apps/changes.ts +3
@@ -31,6 +31,9 @@ export const LIMIT_MAX = 500;
3131 const APP = /^[0-9a-z][0-9a-z_-]{0,62}$/i;
3232 const ROOM = /^[0-9a-z][0-9a-z_.-]{0,63}$/i;
3333
34 /** Whether `room` is a name a client may use. */
35 export const isRoom = (room: unknown): room is string => typeof room === "string" && ROOM.test(room);
36
3437 export interface Changes {
3538 append(app: string, room: string, json: string): Appended;
3639 since(app: string, room: string, seq: number, limit?: number): Change[];
src/apps/manifest.ts +8
@@ -90,6 +90,11 @@ export interface AppManifest {
9090 * out of the app's HTML pages. Unset is on.
9191 */
9292 readonly toolbar?: boolean | undefined;
93 /**
94 * `sync` (top level of `forge.json`): `true` gives the app the forge's ordered change stream
95 * (rooms, presence, catch-up from an offset; docs/features/sync.md). Unset is off.
96 */
97 readonly sync?: true | undefined;
9398 /**
9499 * `env` (top level of `forge.json`): the secret names the app reads from its environment
95100 * (`core/app_secrets.ts`).
@@ -224,6 +229,8 @@ export function parseManifest(
224229 const toolbar = parsed.value["toolbar"];
225230 if (toolbar !== undefined && typeof toolbar !== "boolean")
226231 return invalid("forge.json: toolbar must be true or false");
232 const sync = parsed.value["sync"];
233 if (sync !== undefined && typeof sync !== "boolean") return invalid("forge.json: sync must be true or false");
227234 const adapter = parseAdapter(parsed.value["adapter"]);
228235 if (!adapter.ok) return invalid(adapter.error);
229236 const toolchain = parseToolchain(parsed.value["toolchain"]);
@@ -280,6 +287,7 @@ export function parseManifest(
280287 egress: egress.value,
281288 limits: limits.value,
282289 toolbar: toolbar ?? true,
290 ...(sync === true ? { sync: true as const } : {}),
283291 ...(needs.value.length === 0 ? {} : { env: needs.value }),
284292 ...(adapter.value === undefined ? {} : { adapter: adapter.value }),
285293 ...(toolchain.value === undefined ? {} : { toolchain: toolchain.value }),
src/apps/room_presence.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Who is in a room (#10839): a name is "here" for `TTL_MS` after it last
3 * touched the room, so a client that goes quiet drops out by itself. In
4 * memory only: presence is a fact about now, not something to keep.
5 */
6
7 export const PRESENCE_TTL_MS = 30_000;
8 /** Names kept per room, so one room cannot grow without bound. */
9 export const PRESENCE_MAX = 200;
10
11 export interface RoomPresence {
12 /** Mark `who` as here in the room and return everyone here, sorted. */
13 touch(app: string, room: string, who: string): string[];
14 }
15
16 export function openRoomPresence(now: () => number = Date.now): RoomPresence {
17 const rooms = new Map<string, Map<string, number>>();
18 return {
19 touch(app, room, who) {
20 const key = `${app.toLowerCase()}\n${room.toLowerCase()}`;
21 const t = now();
22 const seen = rooms.get(key) ?? new Map<string, number>();
23 for (const [name, at] of seen) if (t - at >= PRESENCE_TTL_MS) seen.delete(name);
24 if (seen.has(who) || seen.size < PRESENCE_MAX) seen.set(who, t);
25 if (seen.size === 0) rooms.delete(key);
26 else rooms.set(key, seen);
27 return [...seen.keys()].sort();
28 },
29 };
30 }
src/contract/openapi/routes/getApiV1ReposOwnerNameChangesRoom.ts added +17
@@ -0,0 +1,17 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `${REPO}/changes/{room}`,
6 summary: "Read an app's change stream after an offset",
7 detail: "Read a room of the app's ordered change stream after `since` (403 you may not enter the app, 422 a bad room); answers { changes, next, here }; the app declares sync in forge.json",
8 auth: true,
9 role: "member",
10 refusals: {
11 not_found: "no such repository, or it is not an app",
12 not_synced: "the app does not declare sync in forge.json",
13 forbidden: "you may not enter this app",
14 invalid: "the room name is not valid",
15 },
16 refuses: [401, 404],
17 };
src/contract/openapi/routes/index.ts +2
@@ -155,6 +155,7 @@ export { route as getApiV1ReposOwnerNameBuilds } from "./getApiV1ReposOwnerNameB
155155 export { route as getApiV1ReposOwnerNameBuildsLabelCart } from "./getApiV1ReposOwnerNameBuildsLabelCart.ts";
156156 export { route as getApiV1ReposOwnerNameBuildsLabelShots } from "./getApiV1ReposOwnerNameBuildsLabelShots.ts";
157157 export { route as getApiV1ReposOwnerNameBuildsLabelShotsLooks } from "./getApiV1ReposOwnerNameBuildsLabelShotsLooks.ts";
158 export { route as getApiV1ReposOwnerNameChangesRoom } from "./getApiV1ReposOwnerNameChangesRoom.ts";
158159 export { route as getApiV1ReposOwnerNameChapters } from "./getApiV1ReposOwnerNameChapters.ts";
159160 export { route as getApiV1ReposOwnerNameCommits } from "./getApiV1ReposOwnerNameCommits.ts";
160161 export { route as getApiV1ReposOwnerNameCommitsOid } from "./getApiV1ReposOwnerNameCommitsOid.ts";
@@ -381,6 +382,7 @@ export { route as postApiV1ReposOwnerNameBuildsLabelShots } from "./postApiV1Rep
381382 export { route as postApiV1ReposOwnerNameBuildsLabelShotsFile } from "./postApiV1ReposOwnerNameBuildsLabelShotsFile.ts";
382383 export { route as postApiV1ReposOwnerNameBuildsLabelShotsLooks } from "./postApiV1ReposOwnerNameBuildsLabelShotsLooks.ts";
383384 export { route as postApiV1ReposOwnerNameBuildsPreview } from "./postApiV1ReposOwnerNameBuildsPreview.ts";
385 export { route as postApiV1ReposOwnerNameChangesRoom } from "./postApiV1ReposOwnerNameChangesRoom.ts";
384386 export { route as postApiV1ReposOwnerNameChapters } from "./postApiV1ReposOwnerNameChapters.ts";
385387 export { route as postApiV1ReposOwnerNameChaptersChapterVerb } from "./postApiV1ReposOwnerNameChaptersChapterVerb.ts";
386388 export { route as postApiV1ReposOwnerNameChecksRecheck } from "./postApiV1ReposOwnerNameChecksRecheck.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameChangesRoom.ts added +18
@@ -0,0 +1,18 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/changes/{room}`,
6 summary: "Append to an app's change stream",
7 detail: "Append { data } (any JSON, at most 8 KB) to a room of the app's ordered change stream (rw scope); answers 201 { seq }; 403 a read-only token, 413 a body over the cap, 422 an invalid room or data, 429 over 100 appends a second",
8 auth: true,
9 role: "member",
10 refusals: {
11 not_found: "no such repository, or it is not an app",
12 not_synced: "the app does not declare sync in forge.json",
13 forbidden: "you may not enter this app, or a read-only token",
14 rate_limited: "more than 100 appends a second to this app (429, retry-after 1)",
15 invalid: "the room or the data is not valid, or too large",
16 },
outdated

refuses omits 403 and 422 (and 413 for an oversize body) that this route answers; list them. The same on the GET route.

17 refuses: [401, 403, 404],
18 };
src/contract/tags.ts +1
@@ -14,6 +14,7 @@ const ALIAS: Readonly<Record<string, string>> = {
1414 schedules: "apps",
1515 jobs: "apps",
1616 "app-templates": "apps",
17 changes: "apps",
1718 display: "builds",
1819 following: "forks",
1920 upstream: "forks",
src/http/api.ts +2
@@ -368,6 +368,7 @@ import { buildCartRoutes } from "./api/build_cart.ts";
368368 import { iterationRoutes } from "./api/iterations.ts";
369369 import { deepsecRoutes } from "./api/deepsec.ts";
370370 import { appNoteRoutes } from "./api/app_notes.ts";
371 import { appChangesRoutes } from "./api/app_changes.ts";
371372 import { reportRoutes } from "./api/reports.ts";
372373 import { offerHandler, offerStatusHandler } from "./offer_routes.ts";
373374 import { outsiderStatusJson } from "./offer_routes.ts";
@@ -2273,6 +2274,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
22732274 router.add("GET", "/api/v1/status/:token", outsiderStatusJson);
22742275 startRoutes(router);
22752276 appNoteRoutes(router);
2277 appChangesRoutes(router);
22762278 rollbackRoutes(router);
22772279 takeBackRoutes(router);
22782280 conversationConfirmRoutes(router);
src/http/api/app_changes.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * An app's ordered change stream over the API (#10839):
3 * `GET /api/v1/repos/:owner/:name/changes/:room?since=N` reads what came after
4 * sequence N, oldest first, with who is in the room, and
5 * `POST` appends the JSON body's `data`. The rules live in `actions/app_changes.ts`.
6 */
7
8 import { appendChange, readChanges, type ChangesRefusal } from "../../actions/app_changes.ts";
9 import { loadRepo } from "../api.ts";
10 import type { Ctx, Handler } from "../context.ts";
11 import { apiError, body, json, notFound, requireScope } from "../respond.ts";
12 import type { Router } from "../router.ts";
13
14 export function refusal(error: ChangesRefusal | { invalid: string }): Response {
15 if (error === "not_found") return notFound();
16 if (error === "forbidden") return apiError("forbidden", 403, "you may not enter this app");
17 if (error === "not_synced") return apiError("not_synced", 404, 'this app does not declare `"sync": true` in forge.json');
18 if (error.invalid === "too many changes")
19 return json({ error: "rate_limited", message: "too many changes in a second" }, 429, { "retry-after": "1" });
20 return apiError("invalid", 422, error.invalid);
21 }
22
23 const whole = (v: string | null): number => (v !== null && /^\d{1,15}$/.test(v) ? Number(v) : 0);
24
25 export function appChangesRoutes(router: Router<Handler>): void {
26 const room = (ctx: Ctx) => ctx.params.room ?? "";
27 router.add("GET", "/api/v1/repos/:owner/:name/changes/:room", async (ctx) => {
28 const denied = requireScope(ctx, "ro");
29 if (denied) return denied;
30 const repo = loadRepo(ctx);
31 if (!repo) return notFound();
32 const url = new URL(ctx.request.url);
33 const limit = url.searchParams.get("limit");
34 const out = await readChanges(ctx.app, repo, ctx.auth.user, room(ctx), whole(url.searchParams.get("since")), limit === null ? undefined : whole(limit));
35 return out.ok ? json(out.value, 200, { "cache-control": "no-store" }) : refusal(out.error);
36 });
37 router.add("POST", "/api/v1/repos/:owner/:name/changes/:room", async (ctx) => {
38 const denied = requireScope(ctx, "rw");
39 if (denied) return denied;
40 const repo = loadRepo(ctx);
41 if (!repo) return notFound();
42 const input = await body(ctx.request);
43 if (!("data" in input)) return apiError("invalid", 422, "`data` is the JSON value to append");
44 const out = await appendChange(ctx.app, repo, ctx.auth.user, room(ctx), JSON.stringify(input["data"]));
45 return out.ok ? json(out.value, 201) : refusal(out.error);
46 });
47 }
src/http/mcp/tools/changes.ts added +39
@@ -0,0 +1,39 @@
1 import { appendChange, readChanges } from "../../../actions/app_changes.ts";
2 import { bad, good, isAnswer, REPO_ARG, repoArg, type Tool } from "../shared.ts";
3
4 export const tool: Tool = {
5 name: "changes",
6 doc: "`{ repo, room, since?, data? }` as `GET`/`POST …/changes/:room` (forge.json `sync`): `data` (JSON) appends: `{ seq }`; else reads `{ changes, next, here }` after `since`",
7 description: "An app's ordered change stream: read a room after an offset, or append to it.",
8 inputSchema: {
9 type: "object",
10 properties: {
11 repo: REPO_ARG,
12 room: { type: "string" },
13 since: { type: "integer", minimum: 0 },
14 data: {},
15 },
16 required: ["repo", "room"],
17 },
18 writes: true,
19 heldNotWhen: (args) => args["data"] === undefined,
20 readsWithout: "data",
21 async run(ctx, user, args) {
22 const repo = repoArg(ctx, user, args);
23 if (isAnswer(repo)) return repo;
24 const room = args["room"];
25 if (typeof room !== "string") return bad("invalid", "`room` is text");
26 const since = args["since"] ?? 0;
27 if (typeof since !== "number" || !Number.isInteger(since) || since < 0) return bad("invalid", "`since` is a whole number from 0");
28 const out =
29 args["data"] === undefined
30 ? await readChanges(ctx.app, repo, user, room, since)
31 : await appendChange(ctx.app, repo, user, room, JSON.stringify(args["data"]));
32 if (out.ok) return good(out.value);
33 if (typeof out.error === "object" && out.error.invalid === "too many changes") return bad("rate_limited", "too many changes in a second; try again shortly");
34 if (typeof out.error === "object") return bad("invalid", out.error.invalid);
35 if (out.error === "forbidden") return bad("forbidden", "you may not enter this app");
36 if (out.error === "not_synced") return bad("not_found", 'this app does not declare "sync": true in forge.json');
37 return bad("not_found", "no such app or repository (owner/name)");
38 },
39 };
src/http/mcp/tools/index.ts +1
@@ -43,6 +43,7 @@ export { tool as branches } from "./branches.ts";
4343 export { tool as bring } from "./bring.ts";
4444 export { tool as builds } from "./builds.ts";
4545 export { tool as capacity } from "./capacity.ts";
46 export { tool as changes } from "./changes.ts";
4647 export { tool as claim_link } from "./claim_link.ts";
4748 export { tool as close } from "./close.ts";
4849 export { tool as cloud_account } from "./cloud_account.ts";
src/tui/screens/app_changes.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * An app's ordered change stream in the terminal (#10839): the latest
3 * changes in a room (`lobby` first; the room every app starts with),
4 * who is present, `r` to read again, `a` to append a JSON value and `o` to
5 * choose another room, through `readChanges` and `appendChange`: the same
6 * gate and the same words as the API route and the MCP `changes` tool.
7 */
8
9 import { appendChange, readChanges, type ChangesRead } from "../../actions/app_changes.ts";
10 import { isRoom } from "../../apps/changes.ts";
11 import { getAppByRepo } from "../../core/apps.ts";
12 import type { Repo } from "../../core/repos.ts";
13 import type { Ctx, Screen } from "../app/app.ts";
14 import { binding } from "../app/keys.ts";
15 import type { Command } from "../app/palette.ts";
16 import type { Session } from "../session.ts";
17 import { style } from "../term/style.ts";
18 import { fill, len, split } from "../ui/layout.ts";
19 import { ListState, drawList, promptScreen, runAsync, type ListRow } from "./common.ts";
20
21 /** The palette's "Change stream", for a repository that is an app. */
22 export function changesCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
23 if (repo === undefined || f.user === undefined) return [];
24 if (getAppByRepo(f.app.db, repo.id) === undefined) return [];
25 return [
26 {
27 id: "app-changes",
28 title: `${repo.ownerName}/${repo.name} — Change stream`,
29 hint: "r read again",
30 run: () => ctx.push(changesScreen(f, ctx, repo, "lobby")),
31 },
32 ];
33 }
34
35 const WORDS: Record<string, string> = {
36 not_found: "No such app.",
37 forbidden: "You may not enter this app.",
38 not_synced: 'This app has not declared "sync": true in forge.json.',
39 };
40
41 const wordsOf = (error: string | { invalid: string }): string =>
42 typeof error === "string" ? (WORDS[error] ?? error) : error.invalid;
43
44 export function changesScreen(f: Session, ctx: Ctx, repo: Repo, firstRoom: string): Screen {
45 let room = firstRoom;
46 const state = new ListState();
47 let got: ChangesRead | undefined;
48 let note = "Reading…";
49 const load = (): void => {
50 runAsync(ctx, async () => {
51 const done = await readChanges(f.app, repo, f.user, room, 0, 100);
52 if (done.ok) {
53 got = done.value;
54 note = `${got.changes.length} in ${room}; here: ${got.here.join(", ") || "no one"}.`;
55 } else {
outdated

The screen only reads. Add an append key (prompt for JSON, call appendChange) and a way to pick a room, so the terminal does what the API does.

56 got = undefined;
57 note = wordsOf(done.error);
58 }
59 state.clamp(got?.changes.length ?? 0);
60 ctx.invalidate();
61 });
62 };
63 load();
64 const screen: Screen = {
65 get title() {
66 return `Change stream · ${room}`;
67 },
68 get keys() {
69 return [
70 binding(["a"], "append"),
71 binding(["o"], "other room"),
72 binding(["r"], "read again"),
73 binding(["j", "k"], "move cursor"),
74 ];
75 },
76 render(area, s) {
77 const c = ctx.theme.c;
78 const [head, list] = split(area, "v", [len(1), fill(1)]);
79 s.text(head!.x, head!.y, note, style(c.mutedFg, c.bg), head!.x + head!.w);
80 const rows: ListRow[] = (got?.changes ?? []).map((r) => ({ title: `#${r.seq}`, meta: JSON.stringify(r.data) }));
81 drawList(s, list!, c, state, rows);
82 },
83 key(e) {
84 if (state.key(e, got?.changes.length ?? 0)) return true;
85 if (e.ctrl || e.alt) return false;
86 if (e.key === "r") {
87 load();
88 return true;
89 }
90 if (e.key === "o") {
91 ctx.push(
92 promptScreen(ctx, screen, {
93 title: "Room",
94 label: "Room name",
95 value: room,
96 onSubmit: (raw) => {
97 const next = raw.trim();
98 if (!isRoom(next)) return "a room is letters, digits, - _ and ., up to 64";
99 room = next;
100 state.clamp(0);
101 note = "Reading…";
102 load();
103 return undefined;
104 },
105 }),
106 );
107 return true;
108 }
109 if (e.key === "a") {
110 ctx.push(
111 promptScreen(ctx, screen, {
112 title: `Append to ${room}`,
113 label: "JSON value",
114 placeholder: '{"hello":"world"}',
115 onSubmit: (raw) => {
116 let value: unknown;
117 try {
118 value = JSON.parse(raw);
119 } catch {
120 return "not JSON";
121 }
122 return (async () => {
123 const done = await appendChange(f.app, repo, f.user, room, JSON.stringify(value));
124 note = done.ok ? `Appended #${done.value.seq} to ${room}.` : wordsOf(done.error);
125 if (done.ok) load();
126 else ctx.invalidate();
127 })();
128 },
129 }),
130 );
131 return true;
132 }
133 return false;
134 },
135 };
136 return screen;
137 }
src/tui/screens/workspace.ts +2
@@ -209,6 +209,7 @@ import { labelsCommands } from "./labels.ts";
209209 import { appEnvCommands } from "./appenv.ts";
210210 import { appSecretCommands } from "./appsecrets.ts";
211211 import { appFlagCommands } from "./appflags.ts";
212 import { changesCommands } from "./app_changes.ts";
212213 import { appBackupCommands } from "./appbackup.ts";
213214 import { variantsCommands } from "./variants.ts";
214215 import { autonomyCommands } from "./autonomy.ts";
@@ -2445,6 +2446,7 @@ export function workspaceScreen(
24452446 ...appEnvCommands(f, ctx, repo),
24462447 ...appSecretCommands(f, ctx, repo),
24472448 ...appFlagCommands(f, ctx, repo),
2449 ...changesCommands(f, ctx, repo),
24482450 ...appBackupCommands(f, ctx, repo),
24492451 ...variantsCommands(f, ctx, repo),
24502452 ...autonomyCommands(f, ctx, repo),
test/app-changes.test.ts added +208
@@ -0,0 +1,208 @@
1 /**
2 * An app's ordered change stream (#10839): `sync: true` in forge.json opens
3 * `GET`/`POST /api/v1/repos/:owner/:name/changes/:room` and the MCP `changes`
4 * tool. Two clients see the same order, a reconnect catches up from an
5 * offset, presence lists who is in the room, and a refusal is plain.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { newApp } from "../src/actions/apps.ts";
14 import { commitToBranch } from "../src/actions/repos.ts";
15 import { readFileAt } from "../src/apps/checkout.ts";
16 import { parseManifest } from "../src/apps/manifest.ts";
17 import { getRepo } from "../src/core/repos.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { resolveOid } from "../src/git/merge.ts";
21 import { repoDir } from "../src/git/repos.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { createForgeApp } from "../src/tui/forge.ts";
24 import { changesScreen } from "../src/tui/screens/app_changes.ts";
25 import { headlessTerminal } from "../src/tui/term/terminal.ts";
26 import { settleApp } from "./helpers/tui.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28 import { seedAdmin } from "./helpers/admin.ts";
29
30 quietLogs();
31
32 test("forge.json `sync` is true, absent, or refused", () => {
33 const m = (extra: string) => parseManifest(`{"app":{"run":"bun x.ts"}${extra}}`, undefined);
34 expect(m(',"sync":true')).toMatchObject({ ok: true, value: { sync: true } });
35 expect((m("") as any).value.sync).toBeUndefined();
36 expect((m(',"sync":false') as any).value.sync).toBeUndefined();
37 expect(m(',"sync":"yes"').ok).toBe(false);
38 });
39
40 describe("the change stream over the API and MCP", () => {
41 let dataDir: string;
42 let app: App;
43 let servers: Servers;
44 const tok: Record<string, string> = {};
45 const users: Record<string, User> = {};
46 const P = (room: string, repo = "alice/live") => `${servers.url}/api/v1/repos/${repo}/changes/${room}`;
47 const get = (who: string, room: string, q = "", repo?: string) =>
48 fetch(P(room, repo) + q, { headers: { authorization: `Bearer ${tok[who]}` } });
49 const post = (who: string, room: string, data: unknown, repo?: string) =>
50 fetch(P(room, repo), {
51 method: "POST",
52 headers: { authorization: `Bearer ${tok[who]}`, "content-type": "application/json" },
53 body: JSON.stringify({ data }),
54 });
55 const rpc = async (who: string, args: unknown) => {
56 const res = await fetch(`${servers.url}/mcp`, {
57 method: "POST",
58 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tok[who]}` },
59 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "changes", arguments: args } }),
60 });
61 const body: any = await res.json();
62 if (!body.result) throw new Error(JSON.stringify(body));
63 return { error: body.result.isError === true, text: String(body.result.content[0].text) };
64 };
65
66 beforeAll(async () => {
67 dataDir = await mkdtemp(join(process.env.TMPDIR ?? tmpdir(), "forge-app-changes-"));
68 app = createApp({ dataDir, port: 0 });
69 servers = await serve(app);
70 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
71 if (!a.ok) throw new Error(a.error);
72 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
73 if (!b.ok) throw new Error(b.error);
74 users.alice = a.value;
75 users.bob = b.value;
76 tok.alice = createToken(app.db, a.value.id, "rw", "rw").token;
77 tok.aliceRo = createToken(app.db, a.value.id, "ro", "ro").token;
78 tok.bob = createToken(app.db, b.value.id, "rw", "rw").token;
79 const live = await newApp(app, a.value, { name: "live", visibility: "public" });
80 const quiet = await newApp(app, a.value, { name: "quiet", visibility: "public" });
81 const hidden = await newApp(app, a.value, { name: "hidden", visibility: "private" });
82 if (!live.ok || !quiet.ok || !hidden.ok) throw new Error("no app");
83 for (const made of [live, hidden]) {
84 const dir = repoDir(app.reposRoot, "alice", made.value.repo.name);
85 const tip = (await resolveOid(dir, `refs/heads/${made.value.repo.defaultBranch}`))!;
86 const forgeJson = JSON.parse((await readFileAt(dir, tip, "forge.json")) ?? "{}");
87 const done = await commitToBranch(app, a.value, made.value.repo, {
88 message: "Declare sync",
89 files: [{ path: "forge.json", content: JSON.stringify({ ...forgeJson, sync: true }) }],
90 });
91 if (!done.ok) throw new Error(String(done.error));
92 }
93 }, 120_000);
94
95 afterAll(async () => {
96 servers.stop();
97 app.close();
98 await rm(dataDir, { recursive: true, force: true });
99 });
100
101 test("two clients read the same order, and a reconnect catches up from an offset", async () => {
102 expect((await (await post("alice", "lobby", { n: 1 })).json())).toEqual({ seq: 1 });
103 expect((await (await post("bob", "lobby", { n: 2 })).json())).toEqual({ seq: 2 });
104 await post("alice", "other", "x");
105 await post("bob", "lobby", { n: 3 });
106 const a: any = await (await get("alice", "lobby")).json();
107 const b: any = await (await get("bob", "lobby")).json();
108 expect(a.changes.map((c: any) => c.data.n)).toEqual([1, 2, 3]);
109 expect(a.changes.map((c: any) => c.seq)).toEqual(b.changes.map((c: any) => c.seq));
110 expect(a.next).toBe(4);
111 await post("alice", "lobby", { n: 4 });
112 const more: any = await (await get("bob", "lobby", `?since=${a.next}`)).json();
113 expect(more.changes.map((c: any) => c.data.n)).toEqual([4]);
114 expect((await (await get("bob", "lobby", `?since=${more.next}`)).json() as any).changes).toEqual([]);
115 });
116
117 test("presence lists who touched the room", async () => {
118 const seen: any = await (await get("bob", "hall")).json();
119 expect(seen.here).toEqual(["bob"]);
120 await get("alice", "hall");
121 expect(((await (await get("bob", "hall")).json()) as any).here).toEqual(["alice", "bob"]);
122 expect(((await (await get("bob", "empty-room")).json()) as any).here).toEqual(["bob"]);
123 });
124
125 test("MCP changes appends and reads through the same stream", async () => {
126 const sent = await rpc("bob", { repo: "alice/live", room: "mcp", data: { hi: true } });
127 expect(JSON.parse(sent.text)).toEqual({ seq: expect.any(Number) });
128 const read = JSON.parse((await rpc("alice", { repo: "alice/live", room: "mcp" })).text);
129 expect(read.changes.map((c: any) => c.data)).toEqual([{ hi: true }]);
130 expect((await rpc("alice", { repo: "alice/live", room: "mcp", since: -1 })).error).toBe(true);
131 expect((await rpc("alice", { repo: "alice/quiet", room: "mcp" })).error).toBe(true);
132 });
133
134 test("MCP changes refuses an append from a read-only token and appends nothing", async () => {
135 const refused = await rpc("aliceRo", { repo: "alice/live", room: "ro-room", data: { x: 1 } });
136 expect(refused.error).toBe(true);
137 expect(((await (await get("alice", "ro-room")).json()) as any).changes).toEqual([]);
138 });
139
140 /** Drive the terminal screen as `user` (undefined: a guest); `keys` are fed in turn. */
141 async function screenAs(user: User | undefined, repoName: string, room: string, keys: string[]): Promise<string> {
142 const terminal = headlessTerminal(120, 40);
143 const { app: tui, session } = createForgeApp(
144 app,
145 { sshUsername: user?.username ?? "guest", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", ...(user ? { user } : {}) },
146 { terminal, exitHooks: false },
147 );
148 tui.start();
149 const repo = getRepo(app.db, "alice", repoName)!;
150 tui.ctx.push(changesScreen(session, tui.ctx, repo, room));
151 await settleApp(tui);
152 for (const k of keys) {
153 terminal.feed(k);
154 await settleApp(tui);
155 }
156 const text = tui.screen.toText();
157 tui.stop?.();
158 return text;
159 }
160
161 test("the terminal screen: a guest or a stranger sees nothing, an entered user reads and appends", async () => {
162 expect(await screenAs(undefined, "hidden", "lobby", [])).toContain("No such app.");
163 const stranger = await screenAs(users.bob!, "hidden", "lobby", []);
164 expect(stranger).toContain("You may not enter this app.");
165 expect(stranger).not.toContain("#1");
166 await post("alice", "desk", { seeded: true }, "alice/hidden");
167 const read = await screenAs(users.alice!, "hidden", "desk", []);
168 expect(read).toContain("1 in desk");
169 expect(read).toContain("seeded");
170 // `a` opens the prompt, the JSON is typed, enter submits; the change is in the API read.
171 const after = await screenAs(users.alice!, "hidden", "desk", ["a", ...'{"from":"tty"}'.split(""), "\r"]);
172 expect(after).toContain("2 in desk");
173 const api: any = await (await get("alice", "desk", "", "alice/hidden")).json();
174 expect(api.changes.map((c: any) => c.data)).toEqual([{ seeded: true }, { from: "tty" }]);
175 // Not JSON stays in the prompt and appends nothing; `o` moves to another room.
176 await screenAs(users.alice!, "hidden", "desk", ["a", "n", "o", "\r"]);
177 expect(((await (await get("alice", "desk", "", "alice/hidden")).json()) as any).changes.length).toBe(2);
178 const moved = await screenAs(users.alice!, "hidden", "desk", ["o", ..."desk".split("").map(() => "\x7f"), ..."other".split(""), "\r"]);
179 expect(moved).toContain("in other");
180 });
181
182 test("refusals: undeclared app, bad room, bad payload, read-only token, unknown app", async () => {
183 const quiet = await get("alice", "r", "", "alice/quiet");
184 expect(quiet.status).toBe(404);
185 expect(((await quiet.json()) as any).error).toBe("not_synced");
186 expect((await get("alice", "bad room!")).status).toBe(422);
187 expect((await post("alice", "../x", 1)).status).not.toBe(201);
188 const big = await post("alice", "big", "x".repeat(9000));
189 expect(big.status).toBe(422);
190 expect((await post("aliceRo", "lobby", 1)).status).toBe(403);
191 expect((await get("alice", "lobby", "", "alice/nope")).status).toBe(404);
192 const noData = await fetch(P("lobby"), { method: "POST", headers: { authorization: `Bearer ${tok.alice}`, "content-type": "application/json" }, body: "{}" });
193 expect(noData.status).toBe(422);
194 expect(((await (await get("alice", "lobby")).json()) as any).changes.length).toBe(4);
195 });
196 });
197
198 test("a name leaves the room when it goes quiet", async () => {
199 const { openRoomPresence, PRESENCE_TTL_MS } = await import("../src/apps/room_presence.ts");
200 let t = 0;
201 const p = openRoomPresence(() => t);
202 expect(p.touch("a", "r", "x")).toEqual(["x"]);
203 t += PRESENCE_TTL_MS - 1;
204 expect(p.touch("a", "r", "y")).toEqual(["x", "y"]);
205 t += 2;
206 expect(p.touch("a", "r", "y")).toEqual(["y"]);
207 expect(p.touch("a", "other", "z")).toEqual(["z"]);
208 });
test/conversation-confirm.test.ts +1 −1
@@ -124,7 +124,7 @@ describe("the one list of what asks first", () => {
124124 // `writes: true` tool is on neither list until someone decides.
125125 const NOT_ASKED = new Set([
126126 "access", "account_requests", "app_flags", "apps", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide", "atlas",
127 "asks", "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "valves", "cloud_accounts", "close", "confirm_wait",
127 "asks", "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "changes", "valves", "cloud_accounts", "close", "confirm_wait",
128128 "crew", "decisions_by", "desk", "detach", "economics", "edit", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner",
129129 "follow_mode", "forge", "fork", "front_page", "hold", "issue_teams", "keep_plan", "knobs", "labels", "lift", "limb", "maintenance", "make_it_yours", "map", "merge", "new_app",
130130 "next_up", "week", "notify", "open_pull", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports",
test/llms-budget.test.ts +2 −1
@@ -59,7 +59,8 @@ const get = async (token?: string): Promise<string> =>
5959 * add about 40 to 330 bytes to it. Only an agent with an admin token reads this text, and few do,
6060 * so the cost of the room is small. Raised to 98,500 for cut_wave (admin 98,345), then to 98,700
6161 * for the allocation tool (#8718; admin 98,516), then to 99,200 for the app_flags tool (#1830;
62 * admin 98,939). Raised to 100,700 for the profile tool's `gift` action (admin 99,756).
62 * admin 98,939). Raised to 100,700 for the profile tool's `gift` action (admin 99,756; 100,036 with the changes
63 * tool of #10839).
6364 */
6465 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 100_700 } as const;
6566
test/mcp-forge-protocol.test.ts +1
@@ -277,6 +277,7 @@ describe("the forge over MCP: protocol", () => {
277277 "atlas",
278278 "access",
279279 "capacity",
280 "changes",
280281 "scorecard",
281282 "flags",
282283 "flow",
test/open-routes-floor.test.ts +1 −1
@@ -41,7 +41,7 @@ const FILL: Readonly<Record<string, string>> = {
4141 ref: "main", branch: "main", oid: "0".repeat(40), sha: "0".repeat(40), commit: "0".repeat(40),
4242 // Not seeded: each still has to answer its not-found with the floor.
4343 team: "core", env: "prod", file: "README.md", label: "v1", chapter: "1", kind: "desktop", machine: "web",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x", room: "lobby",
4545 };
4646
4747 /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */
test/pages-budget.test.ts +1 −1
@@ -70,7 +70,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
7070 };
7171
7272 /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */
73 const MAX_UNFIXTURED = 159; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830)
73 const MAX_UNFIXTURED = 160; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830) // +1: /api/v1/repos/:owner/:name/changes/:room, a change stream of an app that declares sync, which the fixture does not (#10839)
7474
7575 /** Streams and live fragments: no page. */
7676 const NOT_PAGES = new Set([
test/security-floor-routes.test.ts +1
@@ -71,6 +71,7 @@ const SHOT = "needs a pin with a picture kept by refs/shots; the seed pins nothi
7171 const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers its headers)";
7272 const UNSEEDED: Record<string, string> = {
7373 "/:owner/-/teams/:team": ORG,
74 "/api/v1/repos/:owner/:name/changes/:room": "an app's change stream needs forge.json sync:true on its default branch, which the seed does not declare (test/app-changes.test.ts covers it)",
7475 "/api/v1/repos/:owner/:name/drop/:file": "a file name in an app's private drop; the seed drops none",
7576 "/api/v1/runner/jobs/:id/git/info/refs": "a job a runner holds, read with that job's own token; the seed offers none (test/checks-runner-placement.test.ts covers it)",
7677 "/claim/start/:token": "needs a one-time start claim token, which the seed does not mint (test/start.test.ts covers it)",
test/worker-database-opens.test.ts +1
@@ -56,6 +56,7 @@ const ONE_JOB: Record<string, string> = {
5656 * that no Worker calls these.
5757 */
5858 const REACHED: Record<string, { opens: number; why: string }> = {
59 "src/apps/changes.ts": { opens: 1, why: "an app's change stream keeps one handle per app database, opened on its first read or append, on the serving thread behind a request; no Worker calls it" },
5960 "src/apps/data.ts": { opens: 1, why: "quiesceSqlite folds each app database's log before a copy: called by the serving thread's clone and backup paths, in reach of Workers only through the page layer's imports" },
6061 "src/apps/dump_import.ts": { opens: 3, why: "a person's import of a dump, on the serving thread behind a request; no Worker calls it" },
6162 "src/apps/dump_undo.ts": { opens: 1, why: "an undo folds the live store's log before it is set aside, on the serving thread behind an admin's request; no Worker calls it" },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs