From 9f1d37277be2d81cc5795887a1591e18ba46501d Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:00:55 +0800 Subject: [PATCH] feat: make Run now an idempotent occurrence by command key (#544) --- changelog.d/544-run-now.added.md | 3 + docs/architecture.md | 18 ++++ src/app.ts | 24 +++++ src/db.ts | 70 ++++++++++++ src/jobs/service.ts | 91 +++++++++++++++- src/lib/routeClasses.ts | 3 + src/schedules/runNow.ts | 26 +++++ src/views/pages.ts | 9 +- test/scheduleOccurrences.test.ts | 2 +- test/scheduleRunNow.test.ts | 180 +++++++++++++++++++++++++++++++ 10 files changed, 423 insertions(+), 3 deletions(-) create mode 100644 changelog.d/544-run-now.added.md create mode 100644 src/schedules/runNow.ts create mode 100644 test/scheduleRunNow.test.ts diff --git a/changelog.d/544-run-now.added.md b/changelog.d/544-run-now.added.md new file mode 100644 index 00000000..2c6fcd54 --- /dev/null +++ b/changelog.d/544-run-now.added.md @@ -0,0 +1,3 @@ +A schedule's console now has a **Run now** button: one explicit run from the current +moment, identified by the key the page rendered, so a double click starts one run +and a new page starts a new one. It never moves the schedule's next run. diff --git a/docs/architecture.md b/docs/architecture.md index 6d22b719..8153c851 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2740,3 +2740,21 @@ and a path or key under a frozen family (`evaluator`, `evidence`, `ci`, `gate`, `auth`, `gateway`, `capability`) is refused before the store is asked to write. Recording `strategy_hash` and `strategy_version` on every job, the job-page diff, canary promotion with rollback, and the global bundle are later slices. + +## Run now is an occurrence, not a moved cursor (#544) + +A schedule names logical instants; the tick decides which of them run. "Run now" +is the one command that starts an instant a person asked for, and it keeps the +same record: an occurrence row, settled `dispatched` with the job it started or +`skipped` with the refusal. + +The occurrence's identity is the `command_key` the console form rendered, under +`UNIQUE(schedule_id, command_key)`. The same key returns the occurrence it +already wrote — a double click is one run — and a new key is a distinct +instance. The row is written before the job, so a crash between the two leaves a +row the next press reads instead of a second job, and a refused run still +settles the row so the replay answers the same refusal. + +The recurrence cursor (`last_occurrence_at`) is not touched: "run this now" must +not move when the schedule next fires. `schedule_occurrences.command_key` is +null on every row the tick wrote, which is why the unique index is partial. diff --git a/src/app.ts b/src/app.ts index 07951d61..c107ad75 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1692,6 +1692,9 @@ export async function buildApp(options: BuildOptions): Promise { viewer: viewOf(viewer), repo, state, + // #544 slice 8: the run-now form carries a key rendered once, so a double + // click is one command and a fresh page is a new one. + runNowKey: randomId('cmd'), form: { cron: row?.expression ?? '', every: row?.every_ms === null || row?.every_ms === undefined ? '' : intervalFieldText(row.every_ms), @@ -1705,6 +1708,7 @@ export async function buildApp(options: BuildOptions): Promise { dailyRuns: row?.daily_runs === null || row?.daily_runs === undefined ? '' : String(row.daily_runs), }, ...(queryText(request, 'saved') === undefined ? {} : { notice: t('排期已保存。', 'The schedule is saved.') }), + ...(queryText(request, 'ran') === undefined ? {} : { notice: t('已立即开始一次运行。', 'One run has started now.') }), ...(queryText(request, 'removed') === undefined ? {} : { notice: t('排期已删除,仓库回到旧的自动间隔。', 'The schedule was deleted; the repository is back on the legacy interval.') }), ...(refused === undefined ? {} : { error: refused }), })) @@ -1771,6 +1775,26 @@ export async function buildApp(options: BuildOptions): Promise { return reply.redirect(`${back}?saved=1`) }) + // #544 slice 8: Run now is one explicit occurrence. The key the page rendered + // makes a double click the same command; the recurrence cursor is untouched, + // so "run this now" never moves when the schedule next fires. + app.post('/repos/:id/schedule/run-now', async (request, reply) => { + const { repo } = ownedRepo(request, String((request.params as Record).id), true) + const back = `/repos/${repo.id}/schedule` + const t = translator(request.locale ?? 'zh') + if (repo.repo_role !== 'maintainer') { + return reply.redirect(`${back}?refused=${encodeURIComponent(t('只有 maintainer 可以立即运行排期。', 'Only a maintainer can run the schedule now.'))}`) + } + const result = await jobs.runScheduleNow(repo, form(request).command_key) + if (!result.ok) { + const message = result.code === 'schedule_missing' + ? t('这个仓库还没有排期。', 'This repository has no schedule yet.') + : (result.message ?? t('这次运行没有开始。', 'The run did not start.')) + return reply.redirect(`${back}?refused=${encodeURIComponent(message)}`) + } + return reply.redirect(`${back}?ran=${encodeURIComponent(result.jobId ?? '')}`) + }) + // Deleting the row hands the repository back to its legacy interval; it does // not stop the repository, so the audit says which schedule stopped owning it. app.post('/repos/:id/schedule/remove', async (request, reply) => { diff --git a/src/db.ts b/src/db.ts index 650358a9..3e9649d9 100644 --- a/src/db.ts +++ b/src/db.ts @@ -314,6 +314,12 @@ export interface ScheduleOccurrenceRow { lease_token: string | null /** Epoch milliseconds at which the lease lapses; null when nobody holds it. */ lease_expires_at: number | null + /** + * #544 slice 8: the command key a run-now press carried; null on an occurrence + * the tick decided. `UNIQUE(schedule_id, command_key)` is what makes the + * button idempotent. + */ + command_key: string | null } /** #544 slice 7: one durable notification send. */ @@ -2064,6 +2070,9 @@ CREATE TABLE IF NOT EXISTS schedule_occurrences ( attempts INTEGER NOT NULL DEFAULT 1, lease_token TEXT, lease_expires_at INTEGER, + -- #544 slice 8: a run-now occurrence is named by the command key the button + -- carried, not by a planned instant, so the same key cannot start twice. + command_key TEXT, UNIQUE(schedule_id, logical_time, timing_revision) ); CREATE INDEX IF NOT EXISTS schedule_occurrences_lease_idx ON schedule_occurrences(state, lease_expires_at); @@ -2460,6 +2469,7 @@ export class Store { ['attempts', 'INTEGER NOT NULL DEFAULT 1'], ['lease_token', 'TEXT'], ['lease_expires_at', 'INTEGER'], + ['command_key', 'TEXT'], ] for (const [name, type] of additions) { if (!columns.has(name)) this.run(`ALTER TABLE schedule_occurrences ADD COLUMN ${name} ${type}`) @@ -2469,6 +2479,9 @@ export class Store { migrateIndexes(): void { this.run('CREATE INDEX IF NOT EXISTS quota_ledger_repo_idx ON quota_ledger(repo_id, at DESC)') this.run('CREATE INDEX IF NOT EXISTS jobs_pr_state_idx ON jobs(pr_state, created_at DESC)') + // #544 slice 8: one occurrence per command key. Partial so the tick's rows + // (command_key NULL) are not collapsed into one another. + this.run('CREATE UNIQUE INDEX IF NOT EXISTS schedule_occurrences_command_idx ON schedule_occurrences(schedule_id, command_key) WHERE command_key IS NOT NULL') this.ensureOneActiveJobIndex() } @@ -5281,6 +5294,63 @@ export class Store { return { row, created: Number(result.changes) > 0 } } + // #544 slice 8: a run-now press is an occurrence too, but its identity is the + // command key the button carried rather than a planned instant. The unique + // index on `(schedule_id, command_key)` is what makes a replay a replay; the + // row is inserted `claimed` and settled by the service with the job it started, + // so a repeated press reads the outcome of the first instead of starting again. + scheduleOccurrenceByCommandKey(scheduleId: string, commandKey: string): ScheduleOccurrenceRow | undefined { + return this.get( + 'SELECT * FROM schedule_occurrences WHERE schedule_id = ? AND command_key = ?', + scheduleId, commandKey, + ) + } + + createRunNowOccurrence(input: { + id: string + scheduleId: string + repoId: string + logicalTime: number + timingRevision: number + commandKey: string + }): { row: ScheduleOccurrenceRow; created: boolean } { + // Two explicit commands in the same millisecond are two instances, so the + // logical time steps forward until the triple is free. The command key is + // checked first: a replay must never be mistaken for a collision. + for (let offset = 0; offset < 1_000; offset += 1) { + const result = this.db.prepare( + `INSERT INTO schedule_occurrences + (id, schedule_id, repo_id, logical_time, timing_revision, state, reason, missed, job_id, decided_at, dispatched_at, lag_ms, command_key) + VALUES (?, ?, ?, ?, ?, 'claimed', NULL, 0, NULL, ?, NULL, NULL, ?) + ON CONFLICT DO NOTHING`, + ).run(input.id, input.scheduleId, input.repoId, input.logicalTime + offset, input.timingRevision, nowIso(), input.commandKey) + if (Number(result.changes) > 0) { + const row = this.scheduleOccurrenceByCommandKey(input.scheduleId, input.commandKey) + if (row === undefined) throw new Error(`run-now occurrence ${input.commandKey} disappeared after insert`) + return { row, created: true } + } + const existing = this.scheduleOccurrenceByCommandKey(input.scheduleId, input.commandKey) + if (existing !== undefined) return { row: existing, created: false } + } + throw new Error(`run-now occurrence ${input.commandKey} could not take an instant`) + } + + settleRunNowOccurrence(input: { + id: string + state: 'dispatched' | 'skipped' + reason?: string | null + jobId?: string | null + dispatchedAt?: number | null + }): ScheduleOccurrenceRow | undefined { + this.run( + `UPDATE schedule_occurrences + SET state = ?, reason = ?, job_id = ?, dispatched_at = ?, lag_ms = 0 + WHERE id = ? AND command_key IS NOT NULL`, + input.state, input.reason ?? null, input.jobId ?? null, input.dispatchedAt ?? null, input.id, + ) + return this.get('SELECT * FROM schedule_occurrences WHERE id = ?', input.id) + } + // #544 slice 5: the instants one decision passed over are rows of their own, and // the cursor that leap-frogs past them moves in the same transaction. Otherwise // two workers deciding about the same window could both write a catch-up, and a diff --git a/src/jobs/service.ts b/src/jobs/service.ts index b88b4f5b..347a7005 100644 --- a/src/jobs/service.ts +++ b/src/jobs/service.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' import type { Config } from '../config.js' -import type { JobRow, RepoRow, SecurityFindingWrite, Store, UserRow } from '../db.js' +import type { JobRow, RepoRow, ScheduleOccurrenceRow, SecurityFindingWrite, Store, UserRow } from '../db.js' import type { Mailer, MailMessage } from '../email/mailer.js' import { QuotaNotifier } from '../gateway/notifier.js' import { quotaView } from '../gateway/quota.js' @@ -55,6 +55,7 @@ import { promoteDiscoveredIssue } from './discoveryPromotion.js' import { buildCarryOver, buildRunDigest, decideNextJob, failureStreak, lastDurationMs, MIN_DISCOVERY_INTERVAL_MINUTES, parseCarryOverLink, type CarryOverReader, type OutputKind } from './continuity.js' import { isTemporalStatus, summariseDelta, type TemporalDelta, type TemporalStatus } from '../lib/temporal.js' import { planTick, scheduleFromRow, type TickPlan } from '../schedules/tick.js' +import { parseRunNowKey } from '../schedules/runNow.js' import { utcDayEnd, utcDayStart } from '../schedules/budget.js' import type { ScheduleRow } from '../db.js' import { isImplementedWorkType, missingWorkTypeEvidence, resolveWorkType, workTypeForKind, workTypeMayAutoMerge } from '../lib/workTypes.js' @@ -3764,6 +3765,94 @@ export class Jobs { } } + // #544 slice 8: the console's Run now button. The press is a command whose + // identity is the key the form carried, so a replay answers the first press + // instead of starting a second run. Two rules make it safe: + // - the occurrence is written before the job, so a crash between the two + // starts nothing twice: the next press with the same key reads the row; + // - the recurrence high water mark (`last_occurrence_at`) is never touched, + // because a person asking for a run now does not move the schedule. + // The occurrence records the same state the tick's rows do (`dispatched` with + // the job, `skipped` with the refusal), so the console and the ledger read one + // vocabulary. A refusal still settles the row: the same key must keep + // answering the same thing. + async runScheduleNow(repo: RepoRow, rawKey: unknown): Promise<{ + ok: boolean + code?: string + message?: string + occurrence?: ScheduleOccurrenceRow + replayed?: boolean + jobId?: string | null + }> { + const schedule = this.store.scheduleForRepo(repo.id) + if (schedule === undefined) return { ok: false, code: 'schedule_missing', message: '这个仓库还没有排期。' } + const parsed = parseRunNowKey(rawKey) + if (!parsed.ok) return { ok: false, code: 'command_key_invalid', message: '这次运行的标识无效,请刷新页面后重试。' } + const existing = this.store.scheduleOccurrenceByCommandKey(schedule.id, parsed.key) + if (existing !== undefined) return this.runNowAnswer(existing, true) + const created = this.store.createRunNowOccurrence({ + id: randomId('occ'), + scheduleId: schedule.id, + repoId: repo.id, + logicalTime: Date.now(), + timingRevision: schedule.timing_revision, + commandKey: parsed.key, + }) + if (!created.created) return this.runNowAnswer(created.row, true) + const result = await this.enqueue(repo, 'manual', undefined, 'iterate', { ownerStarted: true }) + const dispatchedAt = Date.now() + if (!result.ok || result.job === undefined) { + const reason = result.code ?? 'dispatch-refused' + const settled = this.store.settleRunNowOccurrence({ id: created.row.id, state: 'skipped', reason, dispatchedAt }) + this.store.audit(repo.user_id, 'schedule.run_now', `${repo.id}: ${parsed.key} skipped ${reason}`) + return { + ok: false, + code: reason, + message: result.error ?? '这次运行没有开始。', + ...(settled === undefined ? {} : { occurrence: settled }), + replayed: false, + jobId: null, + } + } + const settled = this.store.settleRunNowOccurrence({ + id: created.row.id, + state: 'dispatched', + jobId: result.job.id, + dispatchedAt, + }) + this.store.audit(repo.user_id, 'schedule.run_now', `${repo.id}: ${parsed.key} -> ${result.job.id}`) + return { + ok: true, + ...(settled === undefined ? {} : { occurrence: settled }), + replayed: false, + jobId: result.job.id, + } + } + + // A replay and a fresh dispatch answer the same shape, read from the row the + // first press settled. `replayed` is the only difference, so the page can say + // "already started" without pretending it started again. + private runNowAnswer(row: ScheduleOccurrenceRow, replayed: boolean): { + ok: boolean + code?: string + message?: string + occurrence: ScheduleOccurrenceRow + replayed: boolean + jobId: string | null + } { + if (row.state === 'dispatched') { + return { ok: true, occurrence: row, replayed, jobId: row.job_id } + } + return { + ok: false, + code: row.reason ?? 'dispatch-refused', + message: '这次运行没有开始。', + occurrence: row, + replayed, + jobId: row.job_id, + } + } + async tick(): Promise { if (this.stopped || this.ticking) return this.ticking = true diff --git a/src/lib/routeClasses.ts b/src/lib/routeClasses.ts index 4fd48fbb..77578026 100644 --- a/src/lib/routeClasses.ts +++ b/src/lib/routeClasses.ts @@ -75,6 +75,9 @@ const EXPENSIVE_ROUTE_LIST = [ 'POST /repos/:id/models/apply', 'POST /repos/:id/schedule', 'POST /repos/:id/schedule/remove', + // #544 slice 8: run-now starts a job the moment the maintainer asks, so it is + // a start of real work like the schedule save beside it. + 'POST /repos/:id/schedule/run-now', 'POST /repos/:id/release', 'POST /repos/:id/releases/:releaseId/check', 'POST /repos/:id/gate/sessions', diff --git a/src/schedules/runNow.ts b/src/schedules/runNow.ts new file mode 100644 index 00000000..3bbc2d8d --- /dev/null +++ b/src/schedules/runNow.ts @@ -0,0 +1,26 @@ +// #544 slice 8: "Run now" is an explicit command, not a moved cursor. +// +// The card asks for one property: the same command key returns the same +// occurrence, and a new key is a distinct instance. The key is the identity the +// console form carries, so it has to be bounded and opaque before it reaches a +// unique index: an empty key would make every press the same press, and an +// unbounded one would let a client grow a row key by key. +export const RUN_NOW_KEY_MAX = 80 + +export type RunNowKeyReason = 'empty' | 'too-long' | 'invalid' + +export type RunNowKey = + | { ok: true; key: string } + | { ok: false; reason: RunNowKeyReason } + +// Letters, digits, `:`, `_` and `-` — the shape `randomId('cmd')` produces, and +// narrow enough that a key cannot carry a path or a sentence into the ledger. +const KEY_SHAPE = /^[A-Za-z0-9:_-]+$/ + +export function parseRunNowKey(raw: unknown): RunNowKey { + const value = typeof raw === 'string' ? raw.trim() : '' + if (value === '') return { ok: false, reason: 'empty' } + if (value.length > RUN_NOW_KEY_MAX) return { ok: false, reason: 'too-long' } + if (!KEY_SHAPE.test(value)) return { ok: false, reason: 'invalid' } + return { ok: true, key: value } +} diff --git a/src/views/pages.ts b/src/views/pages.ts index 29008c7e..922c520d 100644 --- a/src/views/pages.ts +++ b/src/views/pages.ts @@ -4635,10 +4635,11 @@ export function scheduleConsolePage(input: { repo: RepoRow state: ScheduleConsoleState form: { cron: string; every: string; timezone: string; startAt: string; endAt: string; misfire: string; grace: string; dailyRuns: string } + runNowKey: string notice?: string error?: string }): string { - const { config, locale, viewer, repo, state, form, notice, error } = input + const { config, locale, viewer, repo, state, form, runNowKey, notice, error } = input const t = translator(locale) const iso = (at: number | null): string => (at === null ? 'unknown' : new Date(at).toISOString()) const shown = (at: number | null): string => (at === null ? t('unknown', 'unknown') : humanTimeShort(new Date(at).toISOString())) @@ -4671,6 +4672,11 @@ export function scheduleConsolePage(input: { `).join('') const field = (name: string, label: string, value: string, placeholder: string): string => `` + // #544 slice 8: run-now is only offered when a schedule exists and can be read; + // a repository without one has no cadence to run out of turn. + const runNow = state.kind === 'none' || state.kind === 'unreadable' + ? '' + : `
${csrf(viewer)}${escapeHtml(t('从当前时刻开始一次,不改动下次运行。', 'One run from now; the next scheduled run does not move.'))}
` const kindNote = state.kind === 'none' ? `

${escapeHtml(t('这个仓库还没有排期;它仍按旧的自动间隔运行。保存一个排期后,由排期决定何时运行。', 'This repository has no schedule yet and still runs on the legacy interval. Once a schedule is saved, the schedule decides when it runs.'))}

` : state.kind === 'unreadable' @@ -4691,6 +4697,7 @@ export function scheduleConsolePage(input: {
${escapeHtml(t('宽限', 'Grace'))}
${escapeHtml(state.graceMs === null ? t('不限(默认)', 'unbounded (default)') : t(`${Math.round(state.graceMs / 60_000)} 分钟`, `${Math.round(state.graceMs / 60_000)} minutes`))}
${escapeHtml(t('每日运行上限', 'Daily run limit'))}
${escapeHtml(state.budget.dailyRuns === null ? t('不限(默认)', 'unbounded (default)') : t(`${state.budget.dailyRuns} 次`, `${state.budget.dailyRuns} runs`))} · ${escapeHtml(state.budget.runsToday === null ? t('今天已运行 unknown', 'today unknown') : t(`今天已运行 ${state.budget.runsToday} 次`, `${state.budget.runsToday} today`))}${state.budget.remaining === null ? '' : ` · ${escapeHtml(t(`今天还剩 ${state.budget.remaining} 次`, `${state.budget.remaining} left today`))}`}
+ ${runNow}

${escapeHtml(t('编辑排期', 'Edit the schedule'))}

${escapeHtml(t('排期是五字段 cron 或固定间隔,二选一;cron 需要 IANA 时区。开始/结束时间要带偏移。', 'A schedule is a five-field cron or a fixed interval, one of the two; cron needs an IANA zone. The start/end instants need an offset.'))}

diff --git a/test/scheduleOccurrences.test.ts b/test/scheduleOccurrences.test.ts index efd44062..df0d3451 100644 --- a/test/scheduleOccurrences.test.ts +++ b/test/scheduleOccurrences.test.ts @@ -69,7 +69,7 @@ test('the occurrence table is part of the schema at user_version 44', () => { assert.deepEqual(columns, [ 'id', 'schedule_id', 'repo_id', 'logical_time', 'timing_revision', 'state', 'reason', 'missed', 'job_id', 'decided_at', 'dispatched_at', 'lag_ms', - 'attempts', 'lease_token', 'lease_expires_at', + 'attempts', 'lease_token', 'lease_expires_at', 'command_key', ]) // The identity of a decision is the row's own uniqueness constraint, not a diff --git a/test/scheduleRunNow.test.ts b/test/scheduleRunNow.test.ts new file mode 100644 index 00000000..a1427898 --- /dev/null +++ b/test/scheduleRunNow.test.ts @@ -0,0 +1,180 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { buildApp } from '../src/app.js' +import { Store } from '../src/db.js' +import type { ScheduleOccurrenceRow } from '../src/db.js' +import { Jobs } from '../src/jobs/service.js' +import type { Runner, RunnerContext } from '../src/jobs/runner.js' +import { MemoryMailer, formBody, makeUser, sessionFor, testConfig } from './helpers.js' + +// #544 slice 8: "Run now" is an explicit command with its own identity. +// +// The card asks for one property: the same command key returns the same +// occurrence, a new key is a distinct instance, and neither moves the recurrence +// cursor. The occurrence is the record, so the assertions read rows rather than +// a counter — one occurrence per key, one job behind it, and a refusal that +// settles the row so the replay answers the same thing. + +interface Harness { + store: Store + jobs: Jobs + contexts: RunnerContext[] + userId: string + repoId: string +} + +function harness(name: string, role: 'maintainer' | 'developer' = 'maintainer'): Harness { + const config = testConfig() + const store = new Store(':memory:') + const contexts: RunnerContext[] = [] + const runner: Runner = { + name: 'capture', + async run(context) { + contexts.push(context) + return { status: 'running' } + }, + } + const jobs = new Jobs(store, config, runner, new MemoryMailer()) + const user = makeUser(store, { login: `${name}-user`, status: 'approved' }) + const repo = store.createRepo({ + id: `repo_${name}`, userId: user.id, owner: 'o', name, + defaultBranch: 'main', tokenEnc: 'x', permission: 'admin', + repoRole: role, goal: 'fix bugs', autoIterate: true, intervalMinutes: 1440, + }) + return { store, jobs, contexts, userId: user.id, repoId: repo.id } +} + +function saveSchedule(h: Harness, id = 'sch_run_now'): void { + h.store.saveSchedule({ id, repoId: h.repoId, kind: 'interval', everyMs: 24 * 60 * 60_000 }) + h.store.createWorkItem({ id: `work_${id}`, repoId: h.repoId, userId: h.userId, title: 'fix it', issueUrl: `https://github.com/o/${h.repoId}/issues/1`, state: 'triaged' }) +} + +function occurrences(h: Harness): ScheduleOccurrenceRow[] { + return h.store.listScheduleOccurrences(h.repoId, 50) +} + +test('the same command key returns the same occurrence and starts one job', async () => { + const h = harness('run-once') + try { + saveSchedule(h) + const repo = h.store.getRepo(h.repoId)! + const first = await h.jobs.runScheduleNow(repo, 'cmd-key-1') + assert.equal(first.ok, true) + assert.equal(first.replayed, false) + assert.equal(typeof first.jobId, 'string') + + const second = await h.jobs.runScheduleNow(repo, 'cmd-key-1') + assert.equal(second.ok, true) + assert.equal(second.replayed, true, 'the same key answers the first press') + assert.equal(second.occurrence?.id, first.occurrence?.id) + assert.equal(second.jobId, first.jobId) + + assert.equal(occurrences(h).length, 1, 'one key, one occurrence') + assert.equal(h.store.listJobsForRepo(h.repoId).length, 1, 'one key, one job') + assert.equal(occurrences(h)[0]?.state, 'dispatched') + assert.equal(occurrences(h)[0]?.command_key, 'cmd-key-1') + } finally { + h.store.close() + } +}) + +test('a new key is a distinct instance, and neither key moves the recurrence cursor', async () => { + const h = harness('run-distinct') + try { + saveSchedule(h) + const cursor = Date.parse('2026-01-01T00:00:00Z') + h.store.run('UPDATE schedules SET last_occurrence_at = ? WHERE repo_id = ?', cursor, h.repoId) + const repo = h.store.getRepo(h.repoId)! + + const first = await h.jobs.runScheduleNow(repo, 'cmd-key-a') + // The admission path still refuses a second run while the first is live, so + // the first job is finished before the second key is pressed. + const job = h.store.listJobsForRepo(h.repoId)[0]! + h.store.updateJob(job.id, { status: 'succeeded', finished_at: new Date().toISOString() }) + const second = await h.jobs.runScheduleNow(repo, 'cmd-key-b') + assert.equal(first.ok, true) + assert.equal(second.ok, true) + assert.notEqual(second.occurrence?.id, first.occurrence?.id) + assert.equal(occurrences(h).length, 2) + assert.equal(h.store.listJobsForRepo(h.repoId).length, 2) + assert.equal(h.store.scheduleForRepo(h.repoId)?.last_occurrence_at, cursor, 'run-now never moves the schedule') + } finally { + h.store.close() + } +}) + +test('a refused run still settles the row, so the replay answers the same refusal', async () => { + const h = harness('run-refused') + try { + saveSchedule(h) + h.store.updateRepo(h.repoId, { enabled: 0 }) + const repo = h.store.getRepo(h.repoId)! + const first = await h.jobs.runScheduleNow(repo, 'cmd-key-refused') + assert.equal(first.ok, false) + assert.equal(first.code, 'REPO_DISABLED') + assert.equal(occurrences(h).length, 1, 'the refusal is recorded, not dropped') + assert.equal(occurrences(h)[0]?.state, 'skipped') + assert.equal(occurrences(h)[0]?.reason, 'REPO_DISABLED') + assert.equal(h.store.listJobsForRepo(h.repoId).length, 0) + + const replay = await h.jobs.runScheduleNow(repo, 'cmd-key-refused') + assert.equal(replay.ok, false) + assert.equal(replay.replayed, true) + assert.equal(replay.code, 'REPO_DISABLED', 'the same key keeps answering the same thing') + assert.equal(occurrences(h).length, 1) + } finally { + h.store.close() + } +}) + +test('a repository without a schedule and a malformed key are refused before any row', async () => { + const h = harness('run-missing') + try { + const repo = h.store.getRepo(h.repoId)! + const missing = await h.jobs.runScheduleNow(repo, 'cmd-key-missing') + assert.equal(missing.ok, false) + assert.equal(missing.code, 'schedule_missing') + assert.equal(occurrences(h).length, 0) + + saveSchedule(h) + const empty = await h.jobs.runScheduleNow(repo, '') + assert.equal(empty.ok, false) + assert.equal(empty.code, 'command_key_invalid') + assert.equal(occurrences(h).length, 0, 'an invalid key writes nothing') + } finally { + h.store.close() + } +}) + +test('the console route starts one run per rendered key and says when it replayed', async () => { + const h = harness('run-route') + const config = testConfig() + const built = await buildApp({ config, store: h.store, mailer: new MemoryMailer(), runner: { name: 'capture', async run() { return { status: 'running' as const } } }, startScheduler: false }) + try { + saveSchedule(h) + const user = h.store.userById(h.userId)! + const session = sessionFor(built, user) + const repo = h.store.getRepo(h.repoId)! + const post = (key: string) => built.app.inject({ + method: 'POST', + url: `/repos/${repo.id}/schedule/run-now`, + headers: { cookie: session.cookie, 'content-type': 'application/x-www-form-urlencoded' }, + payload: formBody({ csrf: session.csrf, command_key: key }), + }) + + const page = await built.app.inject({ method: 'GET', url: `/repos/${repo.id}/schedule`, headers: { cookie: session.cookie } }) + assert.match(page.body, /name="command_key"/, 'the page carries the key the button submits') + + const first = await post('cmd-key-route') + assert.equal(first.statusCode, 302) + assert.equal(occurrences(h).length, 1) + assert.equal(h.store.listJobsForRepo(repo.id).length, 1) + + const replay = await post('cmd-key-route') + assert.equal(replay.statusCode, 302) + assert.equal(occurrences(h).length, 1, 'a double click is one command') + assert.equal(h.store.listJobsForRepo(repo.id).length, 1) + } finally { + await built.close() + } +})