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
5 changes: 5 additions & 0 deletions .changeset/schedule-by-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vercel/board': patch
---

`vb schedules <schedule id>` asks the board for that schedule alone (`schedules({ id })`, `GET /schedules?id=`) instead of listing every schedule to find it. On Vercel's board that is one read of the schedule (`GET /schedules/:id`), its channel, and its creator, where it paged the whole list and read every schedule's channel. An API without that route still gets the list, once per process, and only the schedule shown has its channel read.
1 change: 1 addition & 0 deletions packages/board/docs/01-board/07-schedules.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ const reminder = await team.schedule({ re: '812' }, { text: '@ada friendly ping:
const digest = await team.schedule('standup', { text: "what's everyone on today?", every: '1d', at: new Date('2026-10-09T12:00:00Z') })

await team.schedules({ re: '812' }) // pending, oldest first; { all: true } for the rest
await team.schedules({ id: reminder.id, all: true }) // that one alone, whatever its state
await team.cancelSchedule(reminder.id) // { schedule, canceled }
```

Expand Down
2 changes: 1 addition & 1 deletion packages/board/docs/04-reference/03-http.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ a refused write it can read answers 403. `GET /me` returns the caller's
| POST | `/attachments` | Upload one file. Answers 201 `{ attachment: { id, name, type, size } }`. See [Attachments](#attachments) |
| GET | `/attachments/:id` | The file |
| POST | `/schedules` | Schedule a message. Answers 201 `{ schedule, mentions? }`. See [Schedules](#schedules) |
| GET | `/schedules` | `{ schedules }`. Query: `re`, `channel`, `by`, `all` |
| GET | `/schedules` | `{ schedules }`. Query: `id` (one schedule's own), `re`, `channel`, `by`, `all` |
| POST | `/schedules/:id/cancel` | Cancel one, by the ID the board gave it (`s12` on `local()`, which also takes `12`). Its creator (as a profile, only what that profile scheduled), or `manage` in its channel. Answers `{ schedule, canceled }` |
| POST | `/tasks` | `{ channel, text, labels?, noSync?, attachments?, id?, needs?, for?, claim?, lease? }` starts a thread as a task, or `{ re, needs?, for?, claim?, lease? }` makes the thread `re` roots one. Answers 201 `{ task, claim? }`, where `task` is its root. See [Tasks](#tasks) |
| POST | `/tasks/batch` | `{ channel, tasks, id? }`: starts a thread for each of 1 to 100 tasks, in one write. A task is `{ key?, text, labels?, noSync?, attachments?, needs?, for? }`. Answers 201 `{ tasks }`, their roots in order |
Expand Down
2 changes: 2 additions & 0 deletions packages/board/src/api/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,8 @@ export const ScheduleBody = z
})

export const SchedulesQuery = z.object({
/** A schedule's own ID: that schedule alone, when the rest of the query lets it in. */
id: id.optional(),
/** Any message in a thread: the schedules that reply in it. */
re: id.optional(),
channel: z.string().optional(),
Expand Down
3 changes: 2 additions & 1 deletion packages/board/src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1923,7 +1923,8 @@ async function run(command: string | undefined, args: string[]): Promise<number>
case 'schedules': {
// A schedule's own ID (s12) shows that schedule, whatever became of it: sent, canceled, or still pending.
if (args[0] !== undefined && isScheduleId(args[0])) {
const one = (await client().schedules({ all: true })).find((schedule) => schedule.id.toLowerCase() === args[0]!.toLowerCase())
// A board from before `id` lists them all, so the CLI still finds it among what comes back.
const one = (await client().schedules({ id: args[0], all: true })).find((schedule) => schedule.id.toLowerCase() === args[0]!.toLowerCase())
if (!one)
throw new Failed({
class: 'not_found',
Expand Down
4 changes: 4 additions & 0 deletions packages/board/src/conformance/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,10 @@ const CHECKS: Check[] = [
check(listed.some((s) => s.id === schedule.id), `the schedules should include ${schedule.id}`)
const { schedule: canceled } = await ctx.board.cancelSchedule(schedule.id)
same(canceled.state, 'canceled', 'the canceled schedule')
// Its own ID is that schedule alone, a finished one with `all`.
same((await ctx.board.schedules({ id: schedule.id })).length, 0, "the pending schedules by the canceled one's id")
const byId = await ctx.board.schedules({ id: schedule.id, all: true })
check(byId.length === 1 && byId[0]!.id === schedule.id && byId[0]!.state === 'canceled', `the schedules by its id, with all, should be it alone, canceled, got ${show(byId.map((s) => [s.id, s.state]))}`)
Comment on lines +1013 to +1015

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a fresh board, the schedules conformance check passes even when the backend completely ignores id, because the canceled schedule is the only schedule present.

Fix on Vercel

},
},
{
Expand Down
16 changes: 12 additions & 4 deletions packages/board/src/server/a2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,15 @@ const afterAt = (value: string | undefined): number | undefined => (value === un
* `s`, and `ss12` from an older CLI that adds one to what this board hands out, name it too.
*/
function scheduleAt(value: string): number {
const bare = value.replace(/^s{1,2}/, '')
const index = indexOf(bare)
if (index === null || index === 0) throw notFound(`schedule not found: s${bare}`, 'schedule_not_found')
const index = scheduleIndex(value)
if (index === null) throw notFound(`schedule not found: s${value.replace(/^s{1,2}/, '')}`, 'schedule_not_found')
return index
}
/** What `scheduleAt` reads, null for a value that names no schedule. */
function scheduleIndex(value: string): number | null {
const index = indexOf(value.replace(/^s{1,2}/, ''))
return index === null || index === 0 ? null : index
}

/** A signal that never aborts, for what the board does by itself. */
const NEVER = new AbortController().signal
Expand Down Expand Up @@ -623,7 +627,11 @@ function build(options: A2Options, binding: BoardBinding) {
const visible = (schedule: Schedule) => principal.access.readable(schedule.channel) || createdBy(schedule, { principal, actor })
// `me` is the caller, as it is on Vercel's board.
const by = query.by === 'me' ? actor.id : query.by
return { schedules: (await schedules.list({ ...query, ...(by !== undefined ? { by } : {}), ...(root !== undefined ? { root } : {}) }, visible)).map((schedule) => blindSchedule(schedule, principal.access, actor.id)) }
const { id, ...rest } = query
// `S12` names `s12`, as the CLI has always matched it.
const at = id === undefined ? undefined : scheduleIndex(id.toLowerCase())
if (at === null) return { schedules: [] }
return { schedules: (await schedules.list({ ...rest, ...(by !== undefined ? { by } : {}), ...(root !== undefined ? { root } : {}), ...(at !== undefined ? { at } : {}) }, visible)).map((schedule) => blindSchedule(schedule, principal.access, actor.id)) }
},
async cancelSchedule(caller, { id }) {
const identity = await identityOf(caller)
Expand Down
30 changes: 29 additions & 1 deletion packages/board/src/server/backend-vercel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ const SANDBOX_ROUTES: readonly SandboxRoute[] = [
{ method: 'GET', path: '/attachments/:id' },
{ method: 'POST', path: '/attachments/:id/complete' },
{ method: 'GET', path: '/schedules' },
{ method: 'GET', path: '/schedules/:id' },
{ method: 'POST', path: '/schedules' },
{ method: 'POST', path: '/schedules/:id/cancel' },
{ method: 'GET', path: '/sync/linked' },
Expand Down Expand Up @@ -1257,6 +1258,27 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm
return [root, ...(range.limit === undefined ? replies : range.after === undefined ? replies.slice(-range.limit) : replies.slice(0, range.limit))]
}

/** Whether the API reads one schedule by its ID (`GET /schedules/:id`): until it answers that it has no such route, it's asked. */
let schedulesById = true
/**
* The schedule with `id`, whatever its state, or null for one the API doesn't have or won't show the caller (404
* `schedule_not_found`). Undefined when the API can't say, and the schedule is found in the list, as before: one
* from before the route answers 404 for the route itself (`not_found`), and it's never asked again; any other
* 400 or 403 lists them this once. The API's IDs are lowercase, and the CLI has always matched one in any case.
*/
async function scheduleById(who: Who, id: string, signal?: AbortSignal): Promise<ApiSchedule | null | undefined> {
if (!schedulesById) return undefined
try {
const path = await onBoard(who, `/schedules/${encodeURIComponent(id.toLowerCase())}`)
return (await api<{ schedule: ApiSchedule }>(who, 'GET', path, signal ? { signal } : {})).schedule
} catch (error) {
if (error instanceof HttpError && error.code === 'schedule_not_found') return null
if (error instanceof HttpError && error.status === 404) schedulesById = false
else if (!(error instanceof HttpError && (error.status === 400 || error.status === 403))) throw error
return undefined
}
}

/** Who reacted with each emoji. The API counts them on the message and lists them apart. */
async function reactors(who: Who, message: ApiMessage): Promise<Record<string, string[]>> {
if (!message.reactions || Object.keys(message.reactions).length === 0) return {}
Expand Down Expand Up @@ -3524,6 +3546,11 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm
},
async schedules(caller, query, signal) {
const who = whoOf(caller)
// A schedule named by its ID alone is read by it, not found in the list.
if (query.id !== undefined && query.re === undefined && query.channel === undefined && query.by === undefined) {
const one = await scheduleById(who, query.id, signal)
if (one !== undefined) return { schedules: one && (query.all || one.state === 'pending') ? [await scheduleView(who, one)] : [] }
}
const filter: Record<string, string | undefined> = { state: query.all ? undefined : 'pending' }
if (query.re !== undefined) {
const found = await messageIn(who, query.re, signal).catch((error: unknown) => {
Expand Down Expand Up @@ -3551,7 +3578,8 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm
return found
})
if (!listed) return { schedules: [] }
const views = await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule)))
const id = query.id?.toLowerCase()
const views = await Promise.all(listed.filter((schedule) => (id === undefined || schedule.id === id) && created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule)))
return { schedules: views }
},
async cancelSchedule(caller, { id }, signal) {
Expand Down
5 changes: 3 additions & 2 deletions packages/board/src/server/schedules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,15 +376,16 @@ export function createSchedules(options: { store?: A2Store | undefined; schedule
}
}

/** `visible`: which schedules the caller may see. */
async function list(query: SchedulesQueryOutput & { root?: number }, visible: (schedule: Schedule) => boolean = () => true) {
/** `visible`: which schedules the caller may see. `at`: the one at that index alone. */
async function list(query: Omit<SchedulesQueryOutput, 'id'> & { root?: number; at?: number }, visible: (schedule: Schedule) => boolean = () => true) {
if (!writes) throw new Error('schedules used before the board bound them')
const [{ state }, { state: actors }] = await Promise.all([
session.state(schedulesReducer),
writes.session.state(actorsReducer),
])
return Object.values(state.byId)
.filter(visible)
.filter((s) => (query.at === undefined ? true : s.id === query.at))
.filter((s) => (query.all ? true : s.next !== null))
.filter((s) => (query.root === undefined ? true : s.re === query.root))
.filter((s) => (query.channel === undefined ? true : s.channel === query.channel))
Expand Down
33 changes: 33 additions & 0 deletions packages/board/test/backend-vercel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2244,6 +2244,39 @@ describe('vercel()', () => {
expect(api.requests.filter(listing)).toHaveLength(2)
})

it('reads one schedule by its ID, whatever its state, in one request and not the list', async () => {
const api = fakeMessageboard()
const pong = handleOn(api, 'project:prj_pong:production')
for (let n = 0; n < 9; n++) await pong.schedule('ops', { text: `ops ${n}`, in: '1h' })
const done = await pong.schedule('ops', { text: 'once', in: '1m' })
api.send(done.id)
api.requests.length = 0
expect((await pong.schedules({ id: done.id, all: true })).map((s) => [s.id, s.state, s.channel])).toEqual([[done.id, 'done', 'ops']])
expect(api.requests.filter((request) => request.startsWith('GET /boards/brd_test/schedules'))).toEqual([`GET /boards/brd_test/schedules/${done.id}`])
// Without `all`, a finished one is left out, as the list leaves it out; and the API's IDs are lowercase, as the CLI has always matched them.
expect(await pong.schedules({ id: done.id })).toEqual([])
expect((await pong.schedules({ id: done.id.toUpperCase(), all: true })).map((s) => s.id)).toEqual([done.id])
expect(await pong.schedules({ id: 'sch_missing', all: true })).toEqual([])
// One in a channel the caller can't read is as missing.
const secret = await pong.schedule('secret', { text: 'hidden', in: '1h' })
const fixer = pong.as('fixer', { can: { ops: ['read'] } })
expect((await fixer.schedules({ id: done.id, all: true })).map((s) => s.id)).toEqual([done.id])
expect(await fixer.schedules({ id: secret.id, all: true })).toEqual([])
})

it('finds one schedule in the list on an API from before it read one by its ID, and asks for it by ID no more', async () => {
const api = fakeMessageboard({ scheduleById: false })
const pong = handleOn(api, 'project:prj_pong:production')
const made: string[] = []
for (let n = 0; n < 3; n++) made.push((await pong.schedule('ops', { text: `ops ${n}`, in: '1h' })).id)
api.requests.length = 0
expect((await pong.schedules({ id: made[1]!, all: true })).map((s) => s.text)).toEqual(['ops 1'])
expect((await pong.schedules({ id: made[2]! })).map((s) => s.text)).toEqual(['ops 2'])
expect(await pong.schedules({ id: 'sch_missing', all: true })).toEqual([])
const byId = api.requests.filter((request) => /^GET \/boards\/brd_test\/schedules\/./.test(request))
expect(byId).toEqual([`GET /boards/brd_test/schedules/${made[1]}`])
})

it('cancels a schedule once, as the API answers it, and shows who did', async () => {
const api = fakeMessageboard()
const pong = handleOn(api, 'project:prj_pong:production')
Expand Down
35 changes: 35 additions & 0 deletions packages/board/test/cli-embedded.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,41 @@ describe('the embedded CLI', () => {
}
})

it("shows one schedule on Vercel's board by its ID with a read of it, where an API without that read pages the list", async () => {
const home = await isolated()
const cwd = process.cwd()
process.chdir(home)
vi.stubEnv('VERCEL_AUTH_TOKEN', 'user:u_jb')
const fetching = vi.spyOn(globalThis, 'fetch')
try {
const reads: Record<string, string[]> = {}
for (const scheduleById of [true, false]) {
const api = fakeMessageboard({ slug: 'acme', scheduleById })
const ada = board({ backend: vercel({ team: 'team_test', api: 'http://localhost', fetch: as(api, 'user:u_ada') }) })
// Everyone's schedules, a channel each, as a swarm's agents make them: the fake API pages them two at a time.
const made: string[] = []
for (let n = 0; n < 12; n++) made.push((await ada.schedule(`agent-${n}`, { text: `check ${n}`, in: '1h' })).id)
fetching.mockImplementation((input, init) => api.fetch(input, init))
api.requests.length = 0
const shown = await capture(() => createApp({ appName: 'vercel board' }).run(['schedules', made[10]!, '--scope', 'acme']))
expect(shown).toMatchObject({ code: 0, stderr: '', stdout: expect.stringMatching(new RegExp(`^${made[10]} new thread in agent-10 · once · next in`)) })
// Each request but finding the board, its ID left out where it names a schedule or a channel.
reads[String(scheduleById)] = api.requests.filter((request) => request !== 'GET /boards').map((request) => request.replace(/\/(sch|chn)_[^/]+$/, '/$1_…'))
api.requests.length = 0
const missing = await capture(() => createApp({ appName: 'vercel board' }).run(['schedules', 'sch_missing', '--scope', 'acme']))
expect(missing).toMatchObject({ code: 1, stderr: expect.stringMatching(/^error: Couldn't find schedule sch_missing\./) })
}
// The schedule, its channel's name, and who made it.
expect(reads.true).toEqual(['GET /boards/brd_test/schedules/sch_…', 'GET /boards/brd_test/channels/chn_…', 'GET /boards/brd_test/actors'])
// An API without the read says it has no such route: every page of the list, and only the one schedule shown.
expect(reads.false).toEqual(['GET /boards/brd_test/schedules/sch_…', ...Array(6).fill('GET /boards/brd_test/schedules'), 'GET /boards/brd_test/channels/chn_…', 'GET /boards/brd_test/actors'])
} finally {
fetching.mockRestore()
process.chdir(cwd)
await rm(home, { recursive: true, force: true })
}
})

it("names where another project's import came from by that project, and its own by its key", async () => {
const home = await isolated()
const api = fakeMessageboard({ slug: 'acme', projects: { prj_www: 'www' } })
Expand Down
1 change: 1 addition & 0 deletions packages/board/test/cli-schedules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ describe('cli schedules', () => {
expect((await vb(['schedules', '--all'], as)).stdout).toMatch(/· done · 1 sent · by u_julian[\s\S]*· canceled · by u_julian/)
// Its own ID shows the one schedule, canceled as it is: how to see that a cancel went through.
expect(await vb(['schedules', id], as)).toMatchObject({ code: 0, stdout: expect.stringMatching(new RegExp(`^${id} #${root} · every 30m[^\\n]* · canceled · by u_julian\\n`)) })
expect((await vb(['schedules', id.toUpperCase()], as)).stdout).toMatch(new RegExp(`^${id} #${root} · every 30m`))
expect(await vb(['schedules', 's99999'], as)).toMatchObject({ code: 1, stderr: expect.stringMatching(/^error: Couldn't find schedule s99999\.\n/) })
// Vercel's board names a schedule sch_…: that is one too, and no message's ID (a number, or msg_…) is.
expect(['s12', 'S12', 'sch_01HZX3'].every(isScheduleId)).toBe(true)
Expand Down
10 changes: 10 additions & 0 deletions packages/board/test/messageboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ type Shared = {
projectIdHandles: boolean
unscopedSync: boolean
tasks: boolean
scheduleById: boolean
/** A schema the team has, by its ID: a built-in, or one it registered. */
schemaOf: (id: string) => Record<string, unknown> | undefined
}
Expand Down Expand Up @@ -1788,6 +1789,12 @@ function fakeBoard(shared: Shared, boardId: string) {
for (; at < bound && kept.length < 2; at++) if (matches(listed[at]!)) kept.push(listed[at]!)
return { schedules: kept.map(showSchedule), cursor: at < listed.length ? String(at) : null }
}
// One by its ID, whatever its state: one in a channel the caller can't read is as missing as one that isn't there.
if ((found = /^\/schedules\/([^/]+)$/.exec(rest)) && method === 'GET' && shared.scheduleById) {
const target = schedules.get(decodeURIComponent(found[1]!))
if (!target || !may(actor, 'read', target.channelId)) throw new Refused(404, 'schedule_not_found')
return { schedule: showSchedule(target) }
}
if ((found = /^\/schedules\/([^/]+)\/cancel$/.exec(rest)) && method === 'POST') {
const target = schedules.get(decodeURIComponent(found[1]!))
if (!target) throw new Refused(404, 'schedule_not_found')
Expand Down Expand Up @@ -2661,6 +2668,8 @@ export function fakeMessageboard(
unscopedSync?: boolean
/** `false`: an API that serves no task routes, as Vercel's did before its threads carried tasks. Each is its 404, as any route it doesn't have is. */
tasks?: boolean
/** `false`: an API from before it read one schedule by its ID (`GET /schedules/:id`), which is its 404 there, as any route it doesn't have is. */
scheduleById?: boolean
/** True for a team whose plan holds only its own board, as Hobby's does: making another is 400 `too_many_boards`. */
oneBoard?: boolean
} = {},
Expand Down Expand Up @@ -2705,6 +2714,7 @@ export function fakeMessageboard(
projectIdHandles: options.projectIdHandles ?? false,
unscopedSync: options.unscopedSync ?? false,
tasks: options.tasks ?? true,
scheduleById: options.scheduleById ?? true,
schemaOf: (id) => (BUILT_IN_SCHEMAS.find((row) => row.id === id) ?? schemas.kept.get(id))?.schema,
}

Expand Down
Loading