Public: anyone can read this; the crew can change it.
An app's ordered change stream has a durable cursor: a client resumes from the last id it saw #15121
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15094-an-app-s-ordered-change-stream-has-a-dur → main 4 commits fork 2 threads · 2 unresolved
8 files
changed +281
−10
docs/features/events.md +4
| @@ -11,3 +11,7 @@ row: Events in the browser | ||
| 11 | 11 | The audience is the same as MCP `events` and `GET …/events`, because the page reads the same `eventsPage`: a webhook's URL and an app's variable names are the admins'. A public repository answers a guest with 200; a private one answers 404 to anyone who cannot read it. A row links to its page when the event has one (an issue, a push's commits) and is a plain row otherwise. |
| 12 | 12 | |
| 13 | 13 | The terminal's version is `v` on the About card (see the README). `enter` on a row opens the issue or pull the event names (a `pull.*` event opens the pull, any other the issue); the issue and pull screens check access themselves, and `esc` returns to the list at the same row. A push or a settings row names no number and opens nothing, and the key bar shows `enter open` only when the selected row can open something. `t` keeps only the kind of the row under the cursor and `t` again lifts it; `s` keeps only settings changes. |
| 14 | ||
| 15 | **Resuming.** `GET /api/v1/repos/:owner/:name/events?after=<id>` returns the events after that id, oldest first (`limit` as above, `kind` too), as `{ items, next_after }`; send `next_after` next time. The outbox is in SQLite under the data directory, so an id survives a restart. An id the repository no longer keeps (retention pruned it, or it is another repository's) answers `410` `{ error: "gone", oldest }`, `oldest` being the oldest id still kept: read the events afresh from there. `after` with `cursor` is 422. `eventsAfter` in `src/core/events_page.ts`; `test/events-resume.test.ts`. | |
| 16 | ||
| 17 | MCP `events` takes `after` too (`{ repo, after, kind?, limit? }`): the same `{ items, next_after }`, oldest first, or a `gone` refusal naming the oldest id kept; `after` with `cursor` is `invalid`. In the terminal, `u` on the Events screen reads what came since the newest row on screen (`eventsAfter`) and puts it above, or reads the list afresh when that row's id is gone. All three apply the viewer's audience: hidden events never appear, but `next_after` moves past them. |
src/core/events.ts +16 −1
| @@ -187,6 +187,8 @@ export interface ListEventsOptions { | ||
| 187 | 187 | afterId?: string; |
| 188 | 188 | /** @default 100 */ |
| 189 | 189 | limit?: number; |
| 190 | /** Read the oldest `limit` rows first, in `seq` order (a resume), not the newest. */ | |
| 191 | oldestFirst?: boolean; | |
| 190 | 192 | /** |
| 191 | 193 | * Of the newest `limit` events, keep only these kinds. The window is the |
| 192 | 194 | * same one an unfiltered read sees; the rows left out are never parsed, |
| @@ -293,6 +295,18 @@ export function headSeq(db: Database): number { | ||
| 293 | 295 | return db.query<{ s: number | null }, []>("SELECT MAX(seq) AS s FROM event").get()?.s ?? 0; |
| 294 | 296 | } |
| 295 | 297 | |
| 298 | /** The oldest event a repository still keeps (retention prunes the rest), or undefined. */ | |
| 299 | export function oldestEventId(db: Database, repoId: string): string | undefined { | |
| 300 | return db | |
| 301 | .query<{ id: string }, [string]>("SELECT id FROM event WHERE repo_id = ?1 ORDER BY seq ASC LIMIT 1") | |
| 302 | .get(repoId)?.id; | |
| 303 | } | |
| 304 | ||
| 305 | /** Whether this repository's outbox holds an event with this id. */ | |
| 306 | export function repoHasEvent(db: Database, repoId: string, eventId: string): boolean { | |
| 307 | return db.query<unknown, [string, string]>("SELECT 1 FROM event WHERE repo_id = ?1 AND id = ?2").get(repoId, eventId) !== null; | |
| 308 | } | |
| 309 | ||
| 296 | 310 | /** One event by id, or undefined. No access check: the caller owes one. */ |
| 297 | 311 | export function getEvent(db: Database, eventId: string): ForgeEvent | undefined { |
| 298 | 312 | const row = db |
| @@ -326,7 +340,8 @@ export function listEvents( | ||
| 326 | 340 | params.push(options.limit ?? 100); |
| 327 | 341 | const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""; |
| 328 | 342 | const limit = params.length; |
| 329 | let sql = `SELECT * FROM event ${where} ORDER BY event.seq DESC LIMIT ?${limit}`; | |
| 343 | const order = options.oldestFirst === true ? "ASC" : "DESC"; | |
| 344 | let sql = `SELECT * FROM event ${where} ORDER BY event.seq ${order} LIMIT ?${limit}`; | |
| 330 | 345 | if (options.kinds !== undefined) { |
| 331 | 346 | const marks = options.kinds.map((kind) => { |
| 332 | 347 | params.push(kind); |
src/core/events_page.ts +42 −1
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import type { Database } from "bun:sqlite"; |
| 2 | 2 | import { audienceFilter, eventForReader } from "./event_audience.ts"; |
| 3 | 3 | import { VIA_WORDS } from "./acting_via.ts"; |
| 4 | import { listEvents, type ForgeEvent } from "./events.ts"; | |
| 4 | import { listEvents, oldestEventId, repoHasEvent, type ForgeEvent } from "./events.ts"; | |
| 5 | 5 | import { getUsersByIds } from "./users.ts"; |
| 6 | 6 | |
| 7 | 7 | export const EVENTS_LIMIT_DEFAULT = 50; |
| @@ -73,3 +73,44 @@ export function eventsPage( | ||
| 73 | 73 | }; |
| 74 | 74 | return { items: page.map(toReader).map(said), next_cursor: next }; |
| 75 | 75 | } |
| 76 | ||
| 77 | /** | |
| 78 | * A resume: the events after `after`, oldest first, so a client that kept the | |
| 79 | * id of the last one it saw reads only what came since. The outbox is in | |
| 80 | * SQLite under the data directory, so an id outlives a restart. An id this | |
| 81 | * repository no longer keeps (pruned, or never its own) is `gone`, with the | |
| 82 | * oldest id still kept, so the client knows to read afresh. `next_after` is | |
| 83 | * the id to send next: the last row scanned, hidden ones included, so a | |
| 84 | * reader who sees few events still moves forward. | |
| 85 | */ | |
| 86 | export function eventsAfter( | |
| 87 | db: Database, | |
| 88 | repoId: string, | |
| 89 | viewer: Parameters<typeof audienceFilter>[1], | |
| 90 | limit: number, | |
| 91 | after: string, | |
| 92 | kind?: string, | |
| 93 | ): { gone: true; oldest: string | null } | { items: ForgeEvent[]; next_after: string } { | |
| 94 | if (!repoHasEvent(db, repoId, after)) return { gone: true, oldest: oldestEventId(db, repoId) ?? null }; | |
| 95 | const toReader = eventForReader(db, viewer); | |
| 96 | const found: ForgeEvent[] = []; | |
| 97 | let from = after; | |
| 98 | for (let n = 0; n < BATCHES && found.length < limit; n++) { | |
| 99 | const batch = listEvents(db, { | |
| 100 | repoId, | |
| 101 | limit: BATCH, | |
| 102 | afterId: from, | |
| 103 | oldestFirst: true, | |
| 104 | ...(kind === undefined ? {} : { kind }), | |
| 105 | }); | |
| 106 | if (batch.length === 0) break; | |
| 107 | const visible = audienceFilter(db, viewer, batch); | |
| 108 | for (const event of batch) { | |
| 109 | if (found.length >= limit) break; | |
| 110 | from = event.id; | |
| 111 | if (visible(event)) found.push(event); | |
| 112 | } | |
| 113 | if (batch.length < BATCH) break; | |
| 114 | } | |
| 115 | return { items: found.map(toReader), next_after: from }; | |
| 116 | } |
src/http/api.ts +12 −1
| @@ -149,7 +149,7 @@ import { | ||
| 149 | 149 | REQUEST_IN_MESSAGE, |
| 150 | 150 | } from "../actions/users.ts"; |
| 151 | 151 | import { OFFSET_LIMIT_MAX, offsetPage, offsetQuery } from "./offset_page.ts"; |
| 152 | import { EVENTS_LIMIT_MAX, eventsLimit, eventsPage, validEventsCursor, validEventsKind } from "../core/events_page.ts"; | |
| 152 | import { EVENTS_LIMIT_MAX, eventsAfter, eventsLimit, eventsPage, validEventsCursor, validEventsKind } from "../core/events_page.ts"; | |
| 153 | 153 | import { audienceFor } from "../core/audience.ts"; |
| 154 | 154 | import { repoFor, reposFor, writeAccess, type WriteAccess } from "../core/repo_fields.ts"; |
| 155 | 155 | import { creditFacts } from "../actions/credit_facts.ts"; |
| @@ -1908,6 +1908,17 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1908 | 1908 | const kind = q.get("kind"); |
| 1909 | 1909 | if (kind !== null && !validEventsKind(kind)) |
| 1910 | 1910 | return apiError("invalid_kind", 422, "kind is an event kind, like repo.settings_updated"); |
| 1911 | const after = q.get("after"); | |
| 1912 | if (after !== null) { | |
| 1913 | if (cursor !== null) return apiError("invalid_after", 422, "send after or cursor, not both"); | |
| 1914 | if (!validEventsCursor(after)) return apiError("invalid_after", 422, "after is the id of the last event you saw"); | |
| 1915 | const resumed = timePhase(ctx.request, "events", () => | |
| 1916 | eventsAfter(ctx.app.db, repo.id, ctx.auth.user, limit, after, kind ?? undefined), | |
| 1917 | ); | |
| 1918 | if ("gone" in resumed) | |
| 1919 | return json({ error: "gone", message: "that event is no longer kept here; read the events afresh", oldest: resumed.oldest }, 410); | |
| 1920 | return timePhase(ctx.request, "render", () => json(resumed)); | |
Resume is only on this route; MCP |
||
| 1921 | } | |
| 1911 | 1922 | const page = timePhase(ctx.request, "events", () => |
| 1912 | 1923 | eventsPage(ctx.app.db, repo.id, ctx.auth.user, limit, cursor ?? undefined, kind ?? undefined), |
| 1913 | 1924 | ); |
src/http/mcp/tools/events.ts +12 −2
| @@ -1,10 +1,10 @@ | ||
| 1 | import { EVENTS_LIMIT_MAX, eventsLimit, eventsPage, validEventsCursor, validEventsKind } from "../../../core/events_page.ts"; | |
| 1 | import { EVENTS_LIMIT_MAX, eventsAfter, eventsLimit, eventsPage, validEventsCursor, validEventsKind } from "../../../core/events_page.ts"; | |
| 2 | 2 | import { CURSOR_NOT_ISSUED } from "../../../actions/feed_words.ts"; |
| 3 | 3 | import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"; |
| 4 | 4 | |
| 5 | 5 | export const tool: Tool = { |
| 6 | 6 | name: "events", |
| 7 | doc: "`{ repo, kind?, limit?, cursor? }`: the repository's events (of one `kind`, e.g. `repo.settings_updated`, when given), newest first, as you may see them (a webhook's URL and an app's variable names are the admins'): `{ items, next_cursor }`, `limit` 1 to 200 (default 50), `cursor` from `next_cursor`", | |
| 7 | doc: "`{ repo, kind?, limit?, cursor?, after? }`: the repository's events (of one `kind`, e.g. `repo.settings_updated`, when given), newest first, as you may see them (a webhook's URL and an app's variable names are the admins'): `{ items, next_cursor }`, `limit` 1 to 200 (default 50), `cursor` from `next_cursor`; `after`, the id of the last event you saw, instead reads what came since, oldest first, as `{ items, next_after }` (send `next_after` next time), or `gone` with the `oldest` id kept when that id is no longer kept", | |
| 8 | 8 | description: "Repository events.", |
| 9 | 9 | inputSchema: { |
| 10 | 10 | type: "object", |
| @@ -13,6 +13,7 @@ export const tool: Tool = { | ||
| 13 | 13 | kind: { type: "string" }, |
| 14 | 14 | limit: { type: "integer" }, |
| 15 | 15 | cursor: { type: "string" }, |
| 16 | after: { type: "string" }, | |
| 16 | 17 | }, |
| 17 | 18 | required: ["repo"], |
| 18 | 19 | }, |
| @@ -28,6 +29,15 @@ export const tool: Tool = { | ||
| 28 | 29 | const kind = args["kind"]; |
| 29 | 30 | if (kind !== undefined && (typeof kind !== "string" || !validEventsKind(kind))) |
| 30 | 31 | return bad("invalid", "kind is an event kind, like repo.settings_updated"); |
| 32 | const after = args["after"]; | |
| 33 | if (after !== undefined) { | |
| 34 | if (given !== undefined) return bad("invalid", "send after or cursor, not both"); | |
| 35 | if (typeof after !== "string" || !validEventsCursor(after)) return bad("invalid", "after is the id of the last event you saw"); | |
| 36 | const resumed = eventsAfter(ctx.app.db, repo.id, user, limit, after, kind); | |
| 37 | return "gone" in resumed | |
| 38 | ? bad("gone", `that event is no longer kept here; read the events afresh (oldest kept: ${resumed.oldest ?? "none"})`) | |
| 39 | : good(resumed); | |
| 40 | } | |
| 31 | 41 | return good(eventsPage(ctx.app.db, repo.id, user, limit, given, kind)); |
| 32 | 42 | }, |
| 33 | 43 | }; |
src/tui/screens/events.ts +27 −3
| @@ -7,10 +7,12 @@ | ||
| 7 | 7 | * activity feed uses (`eventActor`, `eventVerb`). Fifty at a time; `n` reads |
| 8 | 8 | * the next page from the cursor the last one returned; `s` keeps only the |
| 9 | 9 | * settings changes (the same `kind` filter), each saying from what to what; |
| 10 | * `t` keeps only the kind of the row under the cursor, and again lifts it. | |
| 10 | * `t` keeps only the kind of the row under the cursor, and again lifts it; | |
| 11 | * `u` reads what came since the newest row on screen (`eventsAfter`, the | |
| 12 | * resume the API and MCP take as `after`) and puts it above. | |
| 11 | 13 | */ |
| 12 | 14 | |
| 13 | import { EVENTS_LIMIT_DEFAULT, eventsPage } from "../../core/events_page.ts"; | |
| 15 | import { EVENTS_LIMIT_MAX, EVENTS_LIMIT_DEFAULT, eventsAfter, eventsPage } from "../../core/events_page.ts"; | |
| 14 | 16 | import type { ForgeEvent } from "../../core/events.ts"; |
| 15 | 17 | import type { Repo } from "../../core/repos.ts"; |
| 16 | 18 | import { getUsersByIds } from "../../core/users.ts"; |
| @@ -75,6 +77,7 @@ export function eventsScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 75 | 77 | const state = new ListState(); |
| 76 | 78 | let count = 0; |
| 77 | 79 | const rows: ListRow[] = []; |
| 80 | const ids: string[] = []; | |
| 78 | 81 | const opens: ({ pull: boolean; number: number } | undefined)[] = []; |
| 79 | 82 | let next: string | null = null; |
| 80 | 83 | let kind: string | undefined; |
| @@ -85,6 +88,7 @@ export function eventsScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 85 | 88 | rows.length = 0; |
| 86 | 89 | kinds.length = 0; |
| 87 | 90 | opens.length = 0; |
| 91 | ids.length = 0; | |
| 88 | 92 | state.index = 0; |
| 89 | 93 | state.offset = 0; |
| 90 | 94 | read(); |
| @@ -95,9 +99,27 @@ export function eventsScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 95 | 99 | rows.push(...eventRows(f, page.items)); |
| 96 | 100 | kinds.push(...page.items.map((e) => e.kind)); |
| 97 | 101 | opens.push(...page.items.map(opensOf)); |
| 102 | ids.push(...page.items.map((e) => e.id)); | |
| 98 | 103 | next = page.next_cursor; |
| 99 | 104 | ctx.invalidate(); |
| 100 | 105 | }; |
| 106 | // `u`: the events since the newest one on screen, the resume the API and MCP | |
| 107 | // take as `after`. An id no longer kept reads the list afresh. | |
| 108 | const since = (): void => { | |
| 109 | const newest = ids[0]; | |
| 110 | if (newest === undefined) return narrow(kind); | |
| 111 | const got = eventsAfter(f.db, repo.id, f.user, EVENTS_LIMIT_MAX, newest, kind); | |
| 112 | if ("gone" in got) return narrow(kind); | |
| 113 | const fresh = [...got.items].reverse(); | |
| 114 | count += fresh.length; | |
| 115 | rows.unshift(...eventRows(f, fresh)); | |
| 116 | kinds.unshift(...fresh.map((e) => e.kind)); | |
| 117 | opens.unshift(...fresh.map(opensOf)); | |
| 118 | ids.unshift(...fresh.map((e) => e.id)); | |
| 119 | state.index = 0; | |
| 120 | state.offset = 0; | |
| 121 | ctx.invalidate(); | |
| 122 | }; | |
| 101 | 123 | read(); |
| 102 | 124 | return { |
| 103 | 125 | get title() { |
| @@ -108,6 +130,7 @@ export function eventsScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 108 | 130 | binding(["j", "k"], "move"), |
| 109 | 131 | ...(opens[state.index] === undefined ? [] : [binding(["enter"], "open")]), |
| 110 | 132 | ...(next === null ? [] : [binding(["n"], "next page")]), |
| 133 | binding(["u"], "new since"), | |
| 111 | 134 | binding(["s"], kind === SETTINGS_KIND ? "all events" : "settings only"), |
| 112 | 135 | binding(["t"], kind === undefined ? "this kind only" : "all events"), |
| 113 | 136 | binding(["esc", "q"], "back"), |
| @@ -127,7 +150,8 @@ export function eventsScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 127 | 150 | if (e.key === "esc" || e.key === "q") ctx.pop(); |
| 128 | 151 | else if (e.key === "n") { |
| 129 | 152 | if (next !== null) read(next); |
| 130 | } else if (e.key === "enter") { | |
| 153 | } else if (e.key === "u") since(); | |
| 154 | else if (e.key === "enter") { | |
| 131 | 155 | const target = opens[state.index]; |
| 132 | 156 | if (target !== undefined) { |
| 133 | 157 | const src = local(f, repo); |
test/events-resume.test.ts added +151
| @@ -0,0 +1,151 @@ | ||
| 1 | /** | |
| 2 | * A repository's change stream resumes from a cursor: `?after=<id>` returns | |
| 3 | * only later events, oldest first; an id the outbox does not keep is a plain | |
| 4 | * 410 naming the oldest id kept; the cursor survives a restart because the | |
| 5 | * outbox is a file under the data directory. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { listEvents } from "../src/core/events.ts"; | |
| 14 | import { eventsAfter } from "../src/core/events_page.ts"; | |
| 15 | import type { Ctx } from "../src/http/context.ts"; | |
| 16 | import { tool as eventsTool } from "../src/http/mcp/tools/events.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | ||
| 20 | type Page = { items: { id: string; payload: { n?: number } }[]; next_after: string }; | |
| 21 | ||
| 22 | describe("resuming a repository's events", () => { | |
| 23 | let dataDir: string; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | let alice: User; | |
| 27 | let repoId: string; | |
| 28 | ||
| 29 | const emit = (n: number, kind = "push") => | |
| 30 | app.bus.append({ kind, repoId, actorId: alice.id, payload: { n } }); | |
| 31 | const read = (query: string) => fetch(`${servers.url}/api/v1/repos/alice/stream/events?${query}`); | |
| 32 | ||
| 33 | beforeAll(async () => { | |
| 34 | dataDir = await mkdtemp(join(tmpdir(), "forge-resume-")); | |
| 35 | app = createApp({ dataDir, port: 0 }); | |
| 36 | servers = await serve(app); | |
| 37 | const made = await createUser(app.db, { | |
| 38 | origin: "seed", | |
| 39 | trusted: true, | |
| 40 | username: "alice", | |
| 41 | email: "[email protected]", | |
| 42 | password: "a-good-passphrase", | |
| 43 | adminIfFirst: true, | |
| 44 | }); | |
| 45 | if (!made.ok) throw new Error(made.error); | |
| 46 | alice = made.value; | |
| 47 | const repo = await createRepo(app, alice, { name: "stream", visibility: "public" }); | |
| 48 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 49 | repoId = repo.value.id; | |
| 50 | }, 30_000); | |
| 51 | ||
| 52 | afterAll(async () => { | |
| 53 | servers.stop?.(); | |
| 54 | app.close(); | |
| 55 | await rm(dataDir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | test("after returns only later events, oldest first, and next_after chains", async () => { | |
| 59 | for (let i = 0; i < 6; i++) emit(i); | |
| 60 | const all = listEvents(app.db, { repoId, oldestFirst: true, limit: 100 }); | |
| 61 | const mark = all[all.length - 7]!.id; // six events before the head | |
| 62 | const first = (await (await read(`after=${mark}&limit=4`)).json()) as Page; | |
| 63 | expect(first.items.map((e) => e.payload.n)).toEqual([0, 1, 2, 3]); | |
| 64 | const rest = (await (await read(`after=${first.next_after}&limit=4`)).json()) as Page; | |
| 65 | expect(rest.items.map((e) => e.payload.n)).toEqual([4, 5]); | |
| 66 | const done = (await (await read(`after=${rest.next_after}`)).json()) as Page; | |
| 67 | expect(done.items).toEqual([]); | |
| 68 | expect(done.next_after).toBe(rest.next_after); | |
| 69 | }); | |
| 70 | ||
| 71 | test("an unknown id is a 410 naming the oldest id kept", async () => { | |
| 72 | const oldest = listEvents(app.db, { repoId, oldestFirst: true, limit: 1 })[0]!.id; | |
| 73 | const res = await read("after=nosuchevent"); | |
| 74 | expect(res.status).toBe(410); | |
| 75 | const body = (await res.json()) as { error: string; oldest: string }; | |
| 76 | expect(body.error).toBe("gone"); | |
| 77 | expect(body.oldest).toBe(oldest); | |
| 78 | expect((await read("after=bad/id")).status).toBe(422); | |
| 79 | expect((await read(`after=${oldest}&cursor=${oldest}`)).status).toBe(422); | |
| 80 | }); | |
| 81 | ||
| 82 | test("a pruned id is gone, and the cursor survives a restart", async () => { | |
| 83 | const last = emit(99); | |
| 84 | const mark = last.id; | |
| 85 | servers.stop?.(); | |
| 86 | app.close(); | |
| 87 | app = createApp({ dataDir, port: 0 }); | |
| 88 | servers = await serve(app); | |
| 89 | emit(100); | |
| 90 | const resumed = (await (await read(`after=${mark}`)).json()) as Page; | |
| 91 | expect(resumed.items.map((e) => e.payload.n)).toEqual([100]); | |
| 92 | app.db.query("DELETE FROM event WHERE id = ?1").run(mark); | |
| 93 | expect((await read(`after=${mark}`)).status).toBe(410); | |
| 94 | }); | |
| 95 | ||
| 96 | test("a reader who cannot see an event never gets it, and next_after moves past it", async () => { | |
| 97 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 98 | if (!bob.ok) throw new Error(bob.error); | |
| 99 | const mark = emit(200); | |
| 100 | emit(201, "repo.settings_updated"); | |
| 101 | emit(202, "repo.settings_updated"); | |
| 102 | const guest = eventsAfter(app.db, repoId, undefined, 50, mark.id); | |
| 103 | const reader = eventsAfter(app.db, repoId, bob.value, 50, mark.id); | |
| 104 | const admin = eventsAfter(app.db, repoId, alice, 50, mark.id); | |
| 105 | const last = listEvents(app.db, { repoId, limit: 1 })[0]!.id; | |
| 106 | for (const seen of [guest, reader]) { | |
| 107 | if ("gone" in seen) throw new Error("gone"); | |
| 108 | expect(seen.items.map((e) => e.kind)).toEqual([]); | |
| 109 | expect(seen.next_after).toBe(last); | |
| 110 | } | |
| 111 | if ("gone" in admin) throw new Error("gone"); | |
| 112 | expect(admin.items.map((e) => e.kind)).toEqual(["repo.settings_updated", "repo.settings_updated"]); | |
| 113 | // A limit that stops inside the hidden run still advances only as far as it scanned. | |
| 114 | const short = eventsAfter(app.db, repoId, bob.value, 1, mark.id); | |
| 115 | if ("gone" in short) throw new Error("gone"); | |
| 116 | expect(short.items).toEqual([]); | |
| 117 | expect(short.next_after).toBe(last); | |
| 118 | }); | |
| 119 | ||
| 120 | test("kind narrows a resume, and a repository with no events has oldest null", async () => { | |
| 121 | const mark = emit(300); | |
| 122 | emit(301, "issue.opened"); | |
| 123 | emit(302, "push"); | |
| 124 | emit(303, "issue.opened"); | |
| 125 | const only = eventsAfter(app.db, repoId, alice, 50, mark.id, "issue.opened"); | |
| 126 | if ("gone" in only) throw new Error("gone"); | |
| 127 | expect(only.items.map((e) => e.payload["n"])).toEqual([301, 303]); | |
| 128 | const empty = await createRepo(app, alice, { name: "quiet", visibility: "public" }); | |
| 129 | if (!empty.ok) throw new Error(String(empty.error)); | |
| 130 | app.db.query("DELETE FROM event WHERE repo_id = ?1").run(empty.value.id); | |
| 131 | expect(eventsAfter(app.db, empty.value.id, alice, 50, "nosuchevent")).toEqual({ gone: true, oldest: null }); | |
| 132 | }); | |
| 133 | ||
| 134 | test("MCP events takes after: the same items, gone with the oldest, and not with cursor", async () => { | |
| 135 | const mark = emit(400); | |
| 136 | emit(401); | |
| 137 | const url = new URL("http://forge.test/mcp"); | |
| 138 | const ctx: Ctx = { app, request: new Request(url.href), url, params: {}, auth: { user: alice, scope: "ro", via: "token" }, theme: undefined }; | |
| 139 | const run = (args: Record<string, unknown>) => | |
| 140 | eventsTool.run(ctx, alice, { repo: "alice/stream", ...args }) as { ok: boolean; value?: any; error?: string; message?: string }; | |
| 141 | const got = run({ after: mark.id }); | |
| 142 | expect(got.ok).toBe(true); | |
| 143 | expect(got.value.items.map((e: { payload: { n: number } }) => e.payload.n)).toEqual([401]); | |
| 144 | const gone = run({ after: "nosuchevent" }); | |
| 145 | expect(gone.ok).toBe(false); | |
| 146 | expect(gone.error).toBe("gone"); | |
| 147 | expect(gone.message).toContain(listEvents(app.db, { repoId, oldestFirst: true, limit: 1 })[0]!.id); | |
| 148 | expect(run({ after: mark.id, cursor: mark.id }).error).toBe("invalid"); | |
| 149 | expect(run({ after: "bad/id" }).error).toBe("invalid"); | |
| 150 | }); | |
| 151 | }); |
test/tui-events.test.ts +17 −2
| @@ -65,7 +65,7 @@ afterAll(async () => { | ||
| 65 | 65 | }); |
| 66 | 66 | |
| 67 | 67 | /** Open the About card as `who`, press `v`, then the given keys; return the card's and the list's text. */ |
| 68 | async function open(who: User, keys: string[] = []): Promise<{ about: string; events: string }> { | |
| 68 | async function open(who: User, keys: (string | (() => void))[] = []): Promise<{ about: string; events: string }> { | |
| 69 | 69 | const { app, session } = createForgeApp( |
| 70 | 70 | forge, |
| 71 | 71 | { sshUsername: who.username, remoteAddress: "127.0.0.1", user: who }, |
| @@ -78,7 +78,13 @@ async function open(who: User, keys: string[] = []): Promise<{ about: string; ev | ||
| 78 | 78 | app.push(about); |
| 79 | 79 | await settleApp(app); |
| 80 | 80 | const card = app.screen.toText(); |
| 81 | for (const key of ["v", ...keys]) app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 81 | for (const key of ["v", ...keys]) { | |
| 82 | if (typeof key === "function") { | |
| 83 | key(); | |
| 84 | continue; | |
| 85 | } | |
| 86 | app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 87 | } | |
| 82 | 88 | await settleApp(app); |
| 83 | 89 | const events = app.screen.toText(); |
| 84 | 90 | app.stop(); |
| @@ -164,3 +170,12 @@ test("t keeps only the kind of the row under the cursor, and again lifts it", as | ||
| 164 | 170 | expect(lifted.events).toContain("alice pushed: b59"); |
| 165 | 171 | expect(lifted.events).not.toContain("Events · "); |
| 166 | 172 | }); |
| 173 | ||
| 174 | test("u reads what came since the newest row and puts it above", async () => { | |
| 175 | const add = () => forge.bus.append({ kind: "push", repoId: repo.id, actorId: alice.id, payload: { updates: [{ ref: "refs/heads/fresh" }] } }); | |
| 176 | const without = await open(alice, [add, "j"]); | |
| 177 | expect(without.events).not.toContain("pushed: fresh"); | |
| 178 | const resumed = await open(alice, [add, "u"]); | |
| 179 | expect(resumed.events).toContain("alice pushed: fresh"); | |
| 180 | expect(resumed.events.indexOf("pushed: fresh")).toBeLessThan(resumed.events.indexOf("pushed: b59")); | |
| 181 | }); |
new above
offline
Untested branch: hidden events are skipped here but still advance
from. Add a test for a reader who cannot see them.