diff --git a/README.md b/README.md index 77c92d96..f441df73 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,16 @@ The first tool call opens the browser to sign in and allow the connection. Then: installed on the agent's side. In Claude Code it is `/mcp__diffity__review`. - **Sessions.** `create_session` takes a pull request, two commits, or a base commit and a patch (for work that is not pushed). Its result carries the page's URL. A new session on a pull request - that moved on carries the open findings over. + that moved on carries the open findings over. A pull request session follows its head: the + Sessions page shows the current head, a review page opened on an older session moves there, and + one left open follows while its tab is hidden and nothing typed would be lost, and otherwise offers + the update. - **Findings** are inline comments with a severity prefix (`P1`/`P2`/`P3` unless the repository says otherwise); tours give the diff a reading order. - **Posting.** From the page the user posts the findings to the pull request as one review, and - pulls GitHub's review threads in. Posting is only for pull request sessions, and refused once the - pull request has moved past the session's head. GitHub is reached as the user: through the GitHub + pulls GitHub's review threads in. Posting is only for pull request sessions. Once the pull request + has moved past the session's head the page asks whether to update to the new head or post to the + reviewed commit anyway; an agent's `post_review` is refused. GitHub is reached as the user: through the GitHub App they connect on **Settings**, or a token pasted there when no App is configured. An agent posts as the App instead (see Automated reviews). @@ -229,8 +233,9 @@ The deploy runs one instance (pending OAuth consents are held in memory), sets - OAuth client secrets, codes, access and refresh tokens, automation tokens and the web session cookie are stored as sha256 hashes; GitHub tokens (pasted, or the App's access and refresh tokens) are encrypted with `DIFFITY_SECRET_KEY`. -- Posting is only for pull request sessions, and refused once the pull request has moved past the - session's head: the user asks for a new session, which the open findings carry over to. +- Posting is only for pull request sessions. Once the pull request has moved past the session's + head, a review goes to the reviewed commit only when the user asks for that; otherwise the session + at the current head, which the open findings carry over to, is where to post from. ## License diff --git a/packages/api/src/github.ts b/packages/api/src/github.ts index b09ffad4..5baaadc4 100644 --- a/packages/api/src/github.ts +++ b/packages/api/src/github.ts @@ -48,6 +48,16 @@ export interface ReviewSubmission { event: ReviewEvent; body: string; comments: PrComment[]; + /** Posts against the session's head even though the pull request has moved on since. */ + allowOutdated?: boolean; +} + +/** The body of the 409 a review gets when the pull request has moved on since the session's head. */ +export interface MovedOnRefusal { + error: string; + code: 'moved_on'; + headSha: string; + sessionHeadSha: string; } export interface ReviewResult { diff --git a/packages/api/src/info.ts b/packages/api/src/info.ts index baeb27da..3c7b0483 100644 --- a/packages/api/src/info.ts +++ b/packages/api/src/info.ts @@ -24,6 +24,25 @@ export interface RepoInfoResponse { sessionId: string; review?: ReviewRun | null; github: GitHubRemote | null; + /** The pull request has a newer head than this session shows. */ + movedOn?: MovedOn | null; +} + +export interface MovedOn { + headSha: string; + /** The user's session at that head, when there is one already. */ + sessionId: string | null; +} + +/** What `POST /api/advance` answers: the session at the pull request's current head, which may be this one. */ +export interface AdvanceResponse { + sessionId: string; + headSha: string; +} + +/** What `POST /api/review-request` answers; the review was asked for on `sessionId`, the session at the pull request's current head. */ +export interface ReviewRequestResponse extends ReviewRun { + sessionId: string; } /** diff --git a/packages/api/src/requests.ts b/packages/api/src/requests.ts index 0ed87357..45e4f97e 100644 --- a/packages/api/src/requests.ts +++ b/packages/api/src/requests.ts @@ -130,6 +130,7 @@ export function parseReviewSubmission(body: unknown): ParseResult { }); }); + it('carries allowOutdated, and refuses one that is not a boolean', () => { + expect(parseReviewSubmission({ event: 'APPROVE', allowOutdated: true })).toEqual({ + ok: true, + value: { event: 'APPROVE', body: '', comments: [], allowOutdated: true }, + }); + expect(errorOf(parseReviewSubmission({ event: 'APPROVE', allowOutdated: 'yes' }))).toContain('allowOutdated'); + }); + it('rejects an unknown verdict instead of coercing it', () => { expect(errorOf(parseReviewSubmission({ event: 'SHIP_IT' }))) .toBe('event must be one of: COMMENT, APPROVE, REQUEST_CHANGES'); diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index 8be1ef63..588e0cff 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -671,7 +671,9 @@ export function createApp(deps: AppDeps): express.Express { const rows = found.rows.map(request => { const slug = `${request.owner}/${request.repo}`; const action = request.session - ? `open · ${escapeHtml(request.session.headSha.slice(0, 7))}${reachable + ? `open · ${escapeHtml((request.movedTo ?? request.session.headSha).slice(0, 7))}${reachable ? `
` : ''}` : `
@@ -797,8 +799,9 @@ export function createApp(deps: AppDeps): express.Express { sendPage(res, 404, 'Not found', '

No such session

Your sessions

', user); return; } - await live.queueReview(user.id, session.id); - await routine.fire(user.id, session, 'review'); + const current = await service.sessionToReview(session); + await live.queueReview(user.id, current.id); + await routine.fire(user.id, current, 'review'); res.redirect(303, '/'); }); diff --git a/packages/server/src/github.ts b/packages/server/src/github.ts index 1a7d4c73..5b4686a2 100644 --- a/packages/server/src/github.ts +++ b/packages/server/src/github.ts @@ -30,6 +30,8 @@ export interface PullInfo { headSha: string; headRef: string; baseRef: string; + /** Closed or merged. */ + closed: boolean; } export interface ReviewComment { @@ -273,6 +275,7 @@ export class GitHubApi { html_url: string; created_at: string; body: string | null; + state?: string; user: { login: string } | null; base: { sha: string; ref: string }; head: { sha: string; ref: string }; @@ -287,6 +290,7 @@ export class GitHubApi { headSha: json.head.sha, headRef: json.head.ref, baseRef: json.base.ref, + closed: json.state === 'closed', }; } diff --git a/packages/server/src/reviews.ts b/packages/server/src/reviews.ts index 43503afa..1e78576e 100644 --- a/packages/server/src/reviews.ts +++ b/packages/server/src/reviews.ts @@ -328,9 +328,11 @@ export class Reviews { } /** The newest session of each of these pull requests that has one, keyed by `prKey`. */ + /** With `openWork`, only sessions still holding open threads count. */ async latestPrSessions( userId: string, pulls: { owner: string; repo: string; number: number }[], + { openWork = false }: { openWork?: boolean } = {}, ): Promise> { const found = new Map(); if (pulls.length === 0) { @@ -341,6 +343,7 @@ export class Reviews { FROM sessions s JOIN repos r ON r.id = s.repo_id WHERE s.user_id = $1 AND s.pr_number IS NOT NULL AND lower(r.owner) || '/' || lower(r.name) || '#' || s.pr_number = ANY($2::text[]) + ${openWork ? "AND EXISTS (SELECT 1 FROM threads t WHERE t.session_id = s.id AND t.status = 'open')" : ''} ORDER BY lower(r.owner), lower(r.name), s.pr_number, s.created_at DESC, s.seq DESC`, [userId, pulls.map(pull => prKey(pull.owner, pull.repo, pull.number))], ); @@ -350,6 +353,16 @@ export class Reviews { return found; } + /** The user's newest session of the pull request at this head. */ + async prSessionAt(userId: string, pull: { owner: string; repo: string; number: number }, headSha: string): Promise { + const row = await this.db.one( + `${SESSION_SELECT} WHERE s.user_id = $1 AND lower(r.owner) = lower($2) AND lower(r.name) = lower($3) AND s.pr_number = $4 AND s.head_sha = $5 + ORDER BY s.created_at DESC, s.seq DESC LIMIT 1`, + [userId, pull.owner, pull.repo, pull.number, headSha], + ); + return row ? rowToSession(row) : null; + } + /** Earlier sessions of the same pull request, newest first — where carried work comes from. */ async priorPrSessions(userId: string, repoId: number, prNumber: number, excludeId: string): Promise { const rows = await this.db.query( @@ -364,9 +377,9 @@ export class Reviews { * Moves rather than copies, so ids stay stable. Resolved and dismissed threads stay with the * commit where they were dealt with. */ - async moveOpenWork(userId: string, fromSessionIds: string[], toSessionId: string): Promise { + async moveOpenWork(userId: string, fromSessionIds: string[], toSessionId: string): Promise { if (fromSessionIds.length === 0) { - return 0; + return []; } return this.db.transaction(async tx => { const moved = await tx.query<{ id: string }>( @@ -383,7 +396,7 @@ export class Reviews { userId, fromSessionIds, ]); - return moved.length; + return moved.map(row => row.id); }); } diff --git a/packages/server/src/service.ts b/packages/server/src/service.ts index 2af2f1d1..019a0f43 100644 --- a/packages/server/src/service.ts +++ b/packages/server/src/service.ts @@ -4,6 +4,7 @@ import { type CommentThread, type DiffResponse, type GitHubDetails, + type MovedOn, type PullCommentsResult, type ReviewResult, type ReviewSubmission, @@ -29,7 +30,8 @@ import { /** A failure worth telling the caller about in words, with the HTTP status it amounts to. */ export class ServiceError extends Error { - constructor(message: string, readonly status = 400) { + /** `details` go out beside the message, for a caller that acts on the failure rather than showing it. */ + constructor(message: string, readonly status = 400, readonly details?: Record) { super(message); } } @@ -55,8 +57,10 @@ export interface Standards { } export interface ReviewRequestRow extends ReviewRequest { - /** The user's newest session on this pull request. */ + /** The user's newest session on this pull request, or their session at its current head. */ session: { id: string; headSha: string; createdAt: string } | null; + /** The pull request's current head where the session is behind it; opening the session brings it there. */ + movedTo: string | null; } export interface ReviewRequests { @@ -84,6 +88,24 @@ const CACHE_ENTRIES = 256; const REVIEW_REQUESTS_TTL_MS = 60_000; /** GitHub's search allows 30 requests a minute, and a refused one reads as an empty list. */ const FRESH_MIN_AGE_MS = 10_000; +const PULL_HEAD_TTL_MS = 60_000; +const ADVANCE_CONCURRENCY = 4; +const MOVED_ON_WAIT_MS = 2_000; +const HEAD_LOOKUP_BUDGET_MS = 3_000; + +interface PullHead { + headSha: string; + closed: boolean; +} + +async function eachLimited(items: T[], limit: number, work: (item: T) => Promise): Promise { + let next = 0; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => { + while (next < items.length) { + await work(items[next++]); + } + })); +} export function filterReviewRequests(requests: ReviewRequest[], settings: UserSettings): ReviewRequest[] { const skip = settings.skipTitles.map(pattern => pattern.trim().toLowerCase()).filter(Boolean); @@ -163,6 +185,7 @@ export class ReviewService { /** One GitHub mutation per user at a time, so a second submit sees the first one's comments. */ private readonly githubLock = keyedSerializer(); private readonly reviewRequestCache = new Map }>(); + private readonly pullHeads = new Map }>(); constructor( readonly reviews: Reviews, @@ -232,9 +255,159 @@ export class ReviewService { return cached; } + /** + * Each row with the user's session that still holds open findings, else their newest one, else their + * session at the pull request's current head. Nothing is made or moved here: a session left behind is + * brought forward, findings and all, when it is opened or handed to an agent. Only a pull request + * updated since its session was made, or one whose findings sit on an older session, can be behind, + * so the others cost no GitHub request. + */ private async withSessions(userId: string, requests: ReviewRequest[]): Promise { - const sessions = await this.reviews.latestPrSessions(userId, requests); - return requests.map(request => ({ ...request, session: sessions.get(prKey(request.owner, request.repo, request.number)) ?? null })); + const [newest, withWork] = await Promise.all([ + this.reviews.latestPrSessions(userId, requests), + this.reviews.latestPrSessions(userId, requests, { openWork: true }), + ]); + const rows = requests.map(request => { + const key = prKey(request.owner, request.repo, request.number); + const working = withWork.get(key) ?? null; + const latest = newest.get(key) ?? null; + return { + row: { ...request, session: working ?? latest, movedTo: null } as ReviewRequestRow, + olderWork: !!working && working.id !== latest?.id, + }; + }); + const behind = rows.filter(({ row, olderWork }) => row.session && (olderWork || Date.parse(row.updatedAt) > Date.parse(row.session.createdAt))); + // A slow GitHub must not hold the page: what has not answered in time shows next refresh, from the cache. + const lookups = eachLimited(behind, ADVANCE_CONCURRENCY, async ({ row, olderWork }) => { + try { + const head = await this.pullHead(userId, row.owner, row.repo, row.number, false); + if (!head || head.closed || head.headSha === row.session!.headSha) { + return; + } + const current = olderWork ? null : await this.reviews.prSessionAt(userId, row, head.headSha); + if (current) { + row.session = { id: current.id, headSha: current.headSha, createdAt: current.createdAt }; + } else { + row.movedTo = head.headSha; + } + } catch (err) { + console.warn(`Looking up ${row.owner}/${row.repo}#${row.number}'s current head failed: ${err instanceof Error ? err.message : String(err)}`); + } + }); + await Promise.race([lookups, new Promise(resolve => setTimeout(resolve, HEAD_LOOKUP_BUDGET_MS).unref())]); + return rows.map(({ row }) => ({ ...row })); + } + + /** The pull request's head as GitHub has it, asked at most once a minute per user and pull request unless `fresh`. */ + private pullHead(userId: string, owner: string, repo: string, prNumber: number, fresh: boolean): Promise { + const now = Date.now(); + for (const [key, entry] of this.pullHeads) { + if (now - entry.at > PULL_HEAD_TTL_MS) { + this.pullHeads.delete(key); + } + } + const key = `${userId}\0${prKey(owner, repo, prNumber)}`; + const cached = this.pullHeads.get(key); + if (cached && !fresh) { + return cached.head; + } + const entry = { + at: now, + head: (async () => { + const pull = await this.github.getPull(await this.access.tokenFor(userId), owner, repo, prNumber); + return pull && { headSha: pull.headSha, closed: pull.closed }; + })(), + }; + this.pullHeads.set(key, entry); + entry.head.catch(() => { + if (this.pullHeads.get(key) === entry) { + this.pullHeads.delete(key); + } + }); + return entry.head; + } + + /** Null when GitHub could not say. */ + private async knownPullHead(session: ReviewSessionRecord, fresh: boolean): Promise { + try { + return await this.pullHead(session.userId, session.owner, session.repo, session.prNumber!, fresh); + } catch { + return null; + } + } + + private async newestPrSession(session: ReviewSessionRecord): Promise<{ id: string; headSha: string; createdAt: string } | null> { + const pull = { owner: session.owner, repo: session.repo, number: session.prNumber! }; + return (await this.reviews.latestPrSessions(session.userId, [pull])).get(prKey(pull.owner, pull.repo, pull.number)) ?? null; + } + + /** + * The user's session at the pull request's current head, made if need be, with this session's open + * findings carried over to it. A session of no pull request, or of a closed one, is its own current + * session. Where GitHub cannot say what the head is, a newer session of the pull request stands in for it. + * Without `carry` only the destination is made, so a page that may yet stay keeps its findings. + */ + async advanceSession(session: ReviewSessionRecord, { carry = true }: { carry?: boolean } = {}): Promise { + if (session.prNumber === null) { + return session; + } + const head = await this.knownPullHead(session, true); + if (head && (head.closed || head.headSha === session.headSha)) { + return session; + } + const pull = { owner: session.owner, repo: session.repo, number: session.prNumber }; + let existing: ReviewSessionRecord | null = null; + if (head) { + existing = await this.reviews.prSessionAt(session.userId, pull, head.headSha); + } else { + const newest = await this.newestPrSession(session); + if (newest && newest.id !== session.id && newest.createdAt > session.createdAt) { + existing = await this.reviews.getSession(session.userId, newest.id); + } + if (!existing) { + return session; + } + } + if (existing) { + if (carry) { + await this.carryForward(existing); + } + return existing; + } + const created = await this.createSession(session.userId, { repo: `${session.owner}/${session.repo}`, pr: session.prNumber }, { carry }); + return created.session; + } + + /** For handing a session to an agent: one that cannot be advanced is reviewed where it is rather than not at all. */ + async sessionToReview(session: ReviewSessionRecord): Promise { + try { + return await this.advanceSession(session); + } catch (err) { + console.warn(`Bringing session ${session.id} to its pull request's current head failed: ${err instanceof Error ? err.message : String(err)}`); + return session; + } + } + + /** What `advanceSession` would move to, found without making anything; null while the session is current. */ + async movedOn(session: ReviewSessionRecord): Promise { + if (session.prNumber === null) { + return null; + } + // The page waits on this, so a slow GitHub answers on a later poll from the cache instead. + const head = await Promise.race([ + this.knownPullHead(session, false), + new Promise(resolve => setTimeout(resolve, MOVED_ON_WAIT_MS, null).unref()), + ]); + if (head && (head.closed || head.headSha === session.headSha)) { + return null; + } + const newest = await this.newestPrSession(session); + if (head) { + return { headSha: head.headSha, sessionId: newest?.headSha === head.headSha ? newest.id : null }; + } + return newest && newest.id !== session.id && newest.createdAt > session.createdAt + ? { headSha: newest.headSha, sessionId: newest.id } + : null; } async requireSession(userId: string, idOrPrefix: string): Promise { @@ -245,7 +418,7 @@ export class ReviewService { return session; } - async createSession(userId: string, input: CreateSessionInput): Promise { + async createSession(userId: string, input: CreateSessionInput, { carry = true }: { carry?: boolean } = {}): Promise { const slug = parseRepoSlug(input.repo); const mode = sessionMode(input); const token = await this.access.tokenFor(userId); @@ -310,26 +483,35 @@ export class ReviewService { baseSha, headSha, }); - const carried = created && prNumber !== null ? await this.carryForward(session) : 0; + const carried = carry && prNumber !== null ? await this.carryForward(session) : 0; return { session, created, carried, files: await this.changedFiles(session) }; } /** * A pull request that moved on gets a new session, and anything still open has to come along: - * acting on the findings is what moves the head. Lines follow their code where it can be found. + * acting on the findings is what moves the head. */ private async carryForward(session: ReviewSessionRecord): Promise { const priors = await this.reviews.priorPrSessions(session.userId, session.repoId, session.prNumber!, session.id); - if (priors.length === 0) { + return this.carryOpenWork(session, priors); + } + + /** + * Moves the sources' open findings to `session`. The moved threads' lines follow their code where it + * can be found; threads that were on `session` already stay where they are. + */ + private async carryOpenWork(session: ReviewSessionRecord, sources: ReviewSessionRecord[]): Promise { + const others = sources.filter(source => source.id !== session.id); + if (others.length === 0) { return 0; } - const moved = await this.reviews.moveOpenWork(session.userId, priors.map(prior => prior.id), session.id); - if (moved === 0) { + const movedIds = new Set(await this.reviews.moveOpenWork(session.userId, others.map(source => source.id), session.id)); + if (movedIds.size === 0) { return 0; } const token = await this.access.tokenFor(session.userId); const moves = new Map(); - for (const head of new Set(priors.map(prior => prior.headSha))) { + for (const head of new Set(others.map(source => source.headSha))) { if (head === session.headSha) { continue; } @@ -341,7 +523,7 @@ export class ReviewService { // A head the mirror no longer has cannot say what was renamed; the paths stay as they are. } } - const threads = await this.reviews.threadsForSession(session.userId, session.id, 'open'); + const threads = (await this.reviews.threadsForSession(session.userId, session.id, 'open')).filter(thread => movedIds.has(thread.id)); for (const thread of threads) { const path = followRename(thread.filePath, moves); if (path !== thread.filePath) { @@ -365,7 +547,7 @@ export class ReviewService { await this.reviews.updateThreadLines(session.userId, thread.id, range.startLine, range.endLine); } } - return moved; + return movedIds.size; } private async fromMirror(session: ReviewSessionRecord, read: () => Promise): Promise { @@ -600,11 +782,12 @@ export class ReviewService { if (!pull) { throw new ServiceError(`${owner}/${repo} has no pull request #${prNumber}`, 404); } - if (pull.headSha !== session.headSha) { + if (pull.headSha !== session.headSha && !submission.allowOutdated) { throw new ServiceError( `The pull request has moved on to ${pull.headSha.slice(0, 7)} since this session (${session.headSha.slice(0, 7)}). ` - + 'Ask your agent for a new session on the pull request; open findings carry over to it.', + + `Call create_session { repo: "${owner}/${repo}", pr: ${prNumber} } for a session at the current head; open findings carry over to it.`, 409, + { code: 'moved_on', headSha: pull.headSha, sessionHeadSha: session.headSha }, ); } const [patch, existing, viewerLogin] = await Promise.all([ diff --git a/packages/server/src/ui-api.ts b/packages/server/src/ui-api.ts index 2d83441d..8bc73b69 100644 --- a/packages/server/src/ui-api.ts +++ b/packages/server/src/ui-api.ts @@ -11,10 +11,11 @@ import { THREAD_STATUSES, type CommentAuthor, type FileContentResponse, + type AdvanceResponse, type LiveStatusResponse, type ParseResult, type RepoInfoResponse, - type ReviewRun, + type ReviewRequestResponse, } from '@diffity/api'; import type { ReviewSessionRecord } from './reviews.js'; import { describeSession, ServiceError, type ReviewService } from './service.js'; @@ -35,8 +36,8 @@ interface Scoped { session: ReviewSessionRecord; } -function fail(res: Response, status: number, message: string): void { - res.status(status).json({ error: message }); +function fail(res: Response, status: number, message: string, details?: Record): void { + res.status(status).json({ ...details, error: message }); } function parsed(res: Response, result: ParseResult): T | null { @@ -78,7 +79,12 @@ export function uiApiRouter(deps: UiApiDeps): Router { } } catch (err) { if (!res.headersSent) { - fail(res, err instanceof ServiceError ? err.status : 500, err instanceof Error ? err.message : String(err)); + fail( + res, + err instanceof ServiceError ? err.status : 500, + err instanceof Error ? err.message : String(err), + err instanceof ServiceError ? err.details : undefined, + ); } } }; @@ -118,7 +124,7 @@ export function uiApiRouter(deps: UiApiDeps): Router { return comment; }; - router.get('/info', handle(({ session }, _req, res) => { + router.get('/info', handle(async ({ session }, _req, res) => { res.json({ name: `${session.owner}/${session.repo}`, branch: session.prMeta?.headRef ?? session.headSha.slice(0, 7), @@ -127,9 +133,15 @@ export function uiApiRouter(deps: UiApiDeps): Router { sessionId: session.id, review: session.review, github: session.prNumber !== null ? { owner: session.owner, repo: session.repo } : null, + movedOn: await service.movedOn(session), } satisfies RepoInfoResponse); })); + router.post('/advance', handle(async ({ session }, req, res) => { + const advanced = await service.advanceSession(session, { carry: req.body?.prepare !== true }); + res.json({ sessionId: advanced.id, headSha: advanced.headSha } satisfies AdvanceResponse); + })); + router.get('/diff', handle(async ({ session }, req, res) => { res.json(await service.parsedDiff(session, { ignoreWhitespace: req.query.whitespace === 'hide' })); })); @@ -260,9 +272,10 @@ export function uiApiRouter(deps: UiApiDeps): Router { })); router.post('/review-request', handle(async ({ user, session }, _req, res) => { - await live.queueReview(user.id, session.id); - await routine.fire(user.id, session, 'review'); - res.json((await reviews.getSession(user.id, session.id))!.review satisfies ReviewRun); + const current = await service.sessionToReview(session); + await live.queueReview(user.id, current.id); + await routine.fire(user.id, current, 'review'); + res.json({ ...(await reviews.getSession(user.id, current.id))!.review, sessionId: current.id } satisfies ReviewRequestResponse); })); router.get('/github/details', handle(async ({ session }, _req, res) => { diff --git a/packages/server/tests/helpers.ts b/packages/server/tests/helpers.ts index e180a684..51a0f615 100644 --- a/packages/server/tests/helpers.ts +++ b/packages/server/tests/helpers.ts @@ -132,7 +132,7 @@ export interface FakeRepo { private: boolean; /** Tokens that may read it; a public repository is readable with none. */ tokens: string[]; - pulls: Record; + pulls: Record; } export interface FakeComment { @@ -425,7 +425,7 @@ export async function startFakeGitHub(repos: FakeRepo[]): Promise { html_url: `https://github.com/${repo.owner}/${repo.name}/pull/${number}`, created_at: '2026-09-01T10:00:00Z', body: 'What the change is for', - state: 'open', + state: pull.closed ? 'closed' : 'open', user: { login: pull.author ?? 'octocat' }, base: { sha: pull.baseSha, ref: 'main' }, head: { sha: pull.headSha, ref: 'feature' }, diff --git a/packages/server/tests/http.test.ts b/packages/server/tests/http.test.ts index 51614c30..5afac91c 100644 --- a/packages/server/tests/http.test.ts +++ b/packages/server/tests/http.test.ts @@ -31,6 +31,7 @@ let session: ReviewSessionRecord; let prSession: ReviewSessionRecord; let bobSession: ReviewSessionRecord; let pr2Head: string; +let pulls: Record; async function api( path: string, @@ -77,10 +78,10 @@ beforeAll(async () => { name: 'widgets', private: false, tokens: [], - pulls: { + pulls: (pulls = { 1: { title: 'Change line ten', baseSha: fixture.mainTip, headSha: fixture.head1 }, 2: { title: 'Rename a file', baseSha: fixture.mainTip, headSha: pr2Head }, - }, + }), }, ]); dataDir = tempDir('http'); @@ -263,6 +264,25 @@ describe('pull requests awaiting review', () => { } }); + it('shows the head a session is behind on and links that session, making nothing', async () => { + const dora = (await server.users.findOrCreate('dora@example.com')).id; + const doraCookie = await login(server.base, 'dora@example.com'); + const behind = (await server.service.createSession(dora, { repo: 'acme/widgets', pr: 2 })).session; + github.reviewRequests['dora-token'] = [ + { owner: 'acme', repo: 'widgets', number: 2, title: 'Rename a file', author: 'carol', updatedAt: '2999-01-01T00:00:00Z' }, + ]; + await server.users.setGitHubToken(dora, 'dora-token'); + pulls[2].headSha = fixture.head2; + try { + const page = (await api('/', { cookie: doraCookie })).body as string; + expect(page).toContain(`open · ${fixture.head2.slice(0, 7)}`); + expect((await server.service.reviews.listSessions(dora)).map(listed => listed.id)).toEqual([behind.id]); + } finally { + pulls[2].headSha = pr2Head; + await server.users.setGitHubToken(dora, null); + } + }); + it('offers to hand a pull request to the agent when a routine is configured, with nobody listening', async () => { github.reviewRequests['alice-token-routine'] = [ { owner: 'acme', repo: 'widgets', number: 1, title: 'Change line ten', author: 'octocat', updatedAt: '2026-10-03T09:15:00Z' }, diff --git a/packages/server/tests/mcp.test.ts b/packages/server/tests/mcp.test.ts index 0b0b5130..d9e63a44 100644 --- a/packages/server/tests/mcp.test.ts +++ b/packages/server/tests/mcp.test.ts @@ -533,11 +533,13 @@ describe('post_review', () => { } }); - it('refuses once the pull request has moved past the session', async () => { + it('refuses once the pull request has moved past the session, naming the call that gets the current head', async () => { const { session } = await ok<{ session: string }>(routine, 'create_session', { repo: 'acme/widgets', pr: 1 }); pulls[1].headSha = fixture.head2; try { - expect(await failed(routine, 'post_review', { session, event: 'REQUEST_CHANGES', body: 'Changes, please' })).toContain('moved on'); + const refusal = await failed(routine, 'post_review', { session, event: 'REQUEST_CHANGES', body: 'Changes, please' }); + expect(refusal).toContain('moved on'); + expect(refusal).toContain('create_session { repo: "acme/widgets", pr: 1 }'); } finally { pulls[1].headSha = fixture.head1; } diff --git a/packages/server/tests/posting.test.ts b/packages/server/tests/posting.test.ts index 67d74e1c..c672f4c7 100644 --- a/packages/server/tests/posting.test.ts +++ b/packages/server/tests/posting.test.ts @@ -1,5 +1,5 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; -import type { GitHubDetails, PullCommentsResult, ReviewResult } from '@diffity/api'; +import type { GitHubDetails, PullCommentsResult, RepoInfoResponse, ReviewResult } from '@diffity/api'; import type { ReviewSessionRecord } from '../src/reviews.js'; import { login, @@ -132,11 +132,22 @@ describe('posting a review', () => { expect(refused.status).toBe(403); expect(refused.body.error).toContain('Connect GitHub first'); + }); + + it('refuses a moved head with what it moved to, and posts against the reviewed commit when asked to anyway', async () => { repoPulls[1].headSha = fixture.head2; try { + const before = github.postedReviews.length; const moved = await post(prSession.id, '/github/create-review', { event: 'APPROVE' }); expect(moved.status).toBe(409); - expect(moved.body.error).toContain('new session'); + expect(moved.body).toMatchObject({ code: 'moved_on', headSha: fixture.head2, sessionHeadSha: fixture.head1 }); + expect(moved.body.error).toContain('create_session { repo: "acme/widgets", pr: 1 }'); + expect(github.postedReviews.length).toBe(before); + + const anyway = await post(prSession.id, '/github/create-review', { event: 'APPROVE', allowOutdated: true }); + expect(anyway.status).toBe(200); + expect(anyway.body).toMatchObject({ commitSha: fixture.head1 }); + expect(github.postedReviews.at(-1)).toMatchObject({ commit_id: fixture.head1, event: 'APPROVE' }); } finally { repoPulls[1].headSha = fixture.head1; } @@ -185,3 +196,37 @@ describe('GitHub details', () => { expect(details.reviews.map(r => [r.author, r.state])).toEqual([['carol', 'APPROVED']]); }); }); + +describe('a pull request that moved on', () => { + const info = async (sessionId: string, cookie = aliceCookie) => + (await fetch(`${server.base}/s/${sessionId}/api/info`, { headers: { cookie } })).json() as Promise; + + it('is current until the head moves, then advances to a session at the new head that the old one points to', async () => { + expect((await info(prSession.id)).movedOn).toBeNull(); + const same = await post(prSession.id, '/advance', {}); + expect(same.body).toEqual({ sessionId: prSession.id, headSha: fixture.head1 }); + + repoPulls[1].headSha = fixture.head2; + fixture.pushPull(fixture.head2); + try { + expect((await post(prSession.id, '/advance', {}, bobCookie)).status).toBe(404); + const advanced = await post(prSession.id, '/advance', {}); + expect(advanced.status).toBe(200); + expect(advanced.body.headSha).toBe(fixture.head2); + expect(advanced.body.sessionId).not.toBe(prSession.id); + + expect((await info(prSession.id)).movedOn).toEqual({ headSha: fixture.head2, sessionId: advanced.body.sessionId }); + expect((await info(advanced.body.sessionId)).movedOn).toBeNull(); + expect((await post(prSession.id, '/advance', {})).body.sessionId).toBe(advanced.body.sessionId); + } finally { + repoPulls[1].headSha = fixture.head1; + fixture.pushPull(fixture.head1); + } + }); + + it('never moves a session of no pull request', async () => { + const commits = (await server.service.createSession(aliceId, { repo: 'acme/widgets', base: fixture.mainTip, head: fixture.head2 })).session; + expect((await post(commits.id, '/advance', {})).body).toEqual({ sessionId: commits.id, headSha: fixture.head2 }); + expect((await info(commits.id)).movedOn).toBeNull(); + }); +}); diff --git a/packages/server/tests/routine.test.ts b/packages/server/tests/routine.test.ts index 0f6fd920..2f005658 100644 --- a/packages/server/tests/routine.test.ts +++ b/packages/server/tests/routine.test.ts @@ -30,6 +30,7 @@ let aliceId: string; let bobId: string; let fired: Fired[]; let answer: number; +let pulls: Record; const routineFetch = (async (input: string | URL | Request, init?: RequestInit) => { fired.push({ url: String(input), headers: new Headers(init?.headers), text: (JSON.parse(String(init?.body)) as { text: string }).text }); @@ -70,15 +71,8 @@ const fields = (text: string): Record => { beforeAll(async () => { fixture = makeFixture(); - github = await startFakeGitHub([ - { - owner: 'acme', - name: 'widgets', - private: false, - tokens: [], - pulls: { 1: { title: 'Change line ten', baseSha: fixture.mainTip, headSha: fixture.head1 } }, - }, - ]); + pulls = { 1: { title: 'Change line ten', baseSha: fixture.mainTip, headSha: fixture.head1 } }; + github = await startFakeGitHub([{ owner: 'acme', name: 'widgets', private: false, tokens: [], pulls }]); dataDir = tempDir('routine'); server = await startTestServer(dataDir, github.url, { remoteUrl: fixture.remoteUrl, uiDir: fakeUiDir(dataDir), routineFetch }); aliceCookie = await login(server.base, 'alice@example.com'); @@ -191,6 +185,31 @@ describe('calling the routine', () => { expect(await firedAt(session.id)).toBeNull(); }); + it('hands the agent the session at the pull request’s current head, from the Sessions page and from the review page', async () => { + const old = (await server.service.createSession(aliceId, { repo: 'acme/widgets', pr: 1 })).session; + const bobs = (await server.service.createSession(bobId, { repo: 'acme/widgets', pr: 1 })).session; + pulls[1].headSha = fixture.head2; + fixture.pushPull(fixture.head2); + try { + const fromList = await fetch(`${server.base}/sessions/${old.id}/review-request`, { method: 'POST', redirect: 'manual', headers: sameSite(aliceCookie) }); + expect(fromList.status).toBe(303); + expect(fired).toHaveLength(1); + const payload = fields(fired[0].text); + expect(payload).toMatchObject({ pr: '1', head: fixture.head2, kind: 'review' }); + expect(payload.session).not.toBe(old.id); + + const fromPage = await fetch(`${server.base}/s/${bobs.id}/api/review-request`, { method: 'POST', headers: sameSite(bobCookie) }); + const answered = await fromPage.json() as { sessionId: string; state: string }; + expect(answered.sessionId).not.toBe(bobs.id); + expect(answered.state).toBe('queued'); + expect((await server.service.reviews.getSession(bobId, answered.sessionId))?.headSha).toBe(fixture.head2); + expect((await server.service.reviews.getSession(bobId, bobs.id))?.review.state).toBe('none'); + } finally { + pulls[1].headSha = fixture.head1; + fixture.pushPull(fixture.head1); + } + }); + it('fires nothing for a user without a routine', async () => { const created = await createAndReview(bobCookie); expect(created.status).toBe(303); diff --git a/packages/server/tests/service.test.ts b/packages/server/tests/service.test.ts index 7bec2457..d543a950 100644 --- a/packages/server/tests/service.test.ts +++ b/packages/server/tests/service.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import type { Db } from '../src/db.js'; import { Mirrors } from '../src/git.js'; import { GitHubApi, StoredTokenAccess, type ReviewRequest } from '../src/github.js'; @@ -25,16 +25,18 @@ let service: ReviewService; let alice: string; let bob: string; let mallory: string; +let pulls: Record; beforeAll(async () => { fixture = makeFixture(); + pulls = { 1: { title: 'Change line ten', baseSha: fixture.mainTip, headSha: fixture.head1 } }; github = await startFakeGitHub([ { owner: 'Acme', name: 'widgets', private: true, tokens: ['alice-token', 'bob-token'], - pulls: { 1: { title: 'Change line ten', baseSha: fixture.mainTip, headSha: fixture.head1 } }, + pulls, }, ]); dataDir = tempDir('service'); @@ -331,8 +333,7 @@ describe('review requests', () => { { owner: 'acme', repo: 'widgets', number: 2, title: 'Bump lodash', author: 'dependabot', updatedAt: '2026-10-02T09:00:00Z' }, { owner: 'acme', repo: 'widgets', number: 3, title: 'Sketch', author: 'octocat', draft: true, updatedAt: '2026-10-01T09:00:00Z' }, ]; - await service.createSession(bob, { repo: 'acme/widgets', pr: 1 }); - const newest = (await reviews.listSessions(bob)).find(s => s.prNumber === 1)!; + const newest = (await service.createSession(bob, { repo: 'acme/widgets', pr: 1 })).session; const now = Date.now(); const searches = github.searches.length; @@ -388,3 +389,257 @@ describe('review requests', () => { expect(alices).toContain(found?.requests[0].session?.id); }); }); + +describe('following a pull request’s head', () => { + let erin: string; + const pullLookups = () => github.requests.filter(request => request.toLowerCase() === 'get /repos/acme/widgets/pulls/1').length; + const moveTo = (sha: string) => { + pulls[1].headSha = sha; + fixture.pushPull(sha); + }; + + beforeAll(async () => { + erin = (await users.findOrCreate('erin@example.com')).id; + await users.setGitHubToken(erin, 'bob-token'); + }); + + it('keeps a session at the current head, and a session of no pull request', async () => { + const session = (await service.createSession(erin, { repo: 'acme/widgets', pr: 1 })).session; + expect(await service.advanceSession(session)).toEqual(session); + expect(await service.movedOn(session)).toBeNull(); + const commits = (await service.createSession(erin, { repo: 'acme/widgets', base: fixture.mainTip, head: fixture.head2 })).session; + const lookups = pullLookups(); + expect(await service.advanceSession(commits)).toBe(commits); + expect(await service.movedOn(commits)).toBeNull(); + expect(pullLookups()).toBe(lookups); + }); + + it('moves to a session at the new head with the open findings, made once', async () => { + const session = (await service.createSession(erin, { repo: 'acme/widgets', pr: 1 })).session; + const open = await reviews.createThread({ + userId: erin, sessionId: session.id, filePath: 'src.ts', side: 'new', startLine: 10, endLine: 10, + body: 'Why this change?', author: { name: 'Agent', type: 'agent' }, anchorContent: 'line 10 changed by the feature', + }); + moveTo(fixture.head2); + try { + const advanced = await service.advanceSession(session); + expect(advanced.id).not.toBe(session.id); + expect(advanced.headSha).toBe(fixture.head2); + expect((await reviews.threadsForSession(erin, advanced.id)).map(t => [t.id, t.startLine])).toEqual([[open.id, 13]]); + expect(await service.movedOn(session)).toEqual({ headSha: fixture.head2, sessionId: advanced.id }); + expect((await service.advanceSession(session)).id).toBe(advanced.id); + expect(await service.movedOn(advanced)).toBeNull(); + } finally { + moveTo(fixture.head1); + } + }); + + it('leaves a closed pull request where it is', async () => { + const session = (await service.createSession(erin, { repo: 'acme/widgets', pr: 1 })).session; + pulls[1].closed = true; + pulls[1].headSha = fixture.head2; + try { + expect(await service.advanceSession(session)).toBe(session); + expect(await service.movedOn(session)).toBeNull(); + } finally { + pulls[1].closed = false; + pulls[1].headSha = fixture.head1; + } + }); + + it('advances onto a session that already exists at the head, carrying only the findings left behind', async () => { + const gina = (await users.findOrCreate('gina@example.com')).id; + await users.setGitHubToken(gina, 'bob-token'); + const old = (await service.createSession(gina, { repo: 'acme/widgets', pr: 1 })).session; + const finding = (body: string, sessionId: string) => reviews.createThread({ + userId: gina, sessionId, filePath: 'src.ts', side: 'new', startLine: 10, endLine: 10, + body, author: { name: 'Agent', type: 'agent' }, anchorContent: 'line 10 changed by the feature', + }); + moveTo(fixture.head2); + try { + const current = (await service.createSession(gina, { repo: 'acme/widgets', pr: 1 })).session; + const own = await finding('Left on the new head', current.id); + const later = await finding('Written in a tab still on the old head', old.id); + + const advanced = await service.advanceSession(old); + expect(advanced.id).toBe(current.id); + const lines = new Map((await reviews.threadsForSession(gina, current.id)).map(t => [t.id, t.startLine])); + expect(lines.get(later.id)).toBe(13); + expect(lines.get(own.id)).toBe(10); + expect(await reviews.threadsForSession(gina, old.id, 'open')).toEqual([]); + } finally { + moveTo(fixture.head1); + } + }); + + it('only makes the head’s session when asked not to carry, leaving the findings where they are', async () => { + const jan = (await users.findOrCreate('jan@example.com')).id; + await users.setGitHubToken(jan, 'bob-token'); + const old = (await service.createSession(jan, { repo: 'acme/widgets', pr: 1 })).session; + const kept = await reviews.createThread({ + userId: jan, sessionId: old.id, filePath: 'src.ts', side: 'new', startLine: 10, endLine: 10, + body: 'Still being replied to', author: { name: 'Agent', type: 'agent' }, anchorContent: 'line 10 changed by the feature', + }); + moveTo(fixture.head2); + try { + const prepared = await service.advanceSession(old, { carry: false }); + expect(prepared.id).not.toBe(old.id); + expect(await reviews.threadsForSession(jan, prepared.id)).toEqual([]); + expect((await reviews.threadsForSession(jan, old.id, 'open')).map(t => t.id)).toEqual([kept.id]); + + expect((await service.advanceSession(old)).id).toBe(prepared.id); + expect((await reviews.threadsForSession(jan, prepared.id)).map(t => [t.id, t.startLine])).toEqual([[kept.id, 13]]); + } finally { + moveTo(fixture.head1); + } + }); + + it('links the session holding the findings while a prepared one at the head has none, and gathers them when the head’s session is asked for', async () => { + const kim = (await users.findOrCreate('kim@example.com')).id; + await users.setGitHubToken(kim, 'bob-token'); + const old = (await service.createSession(kim, { repo: 'acme/widgets', pr: 1 })).session; + const kept = await reviews.createThread({ + userId: kim, sessionId: old.id, filePath: 'src.ts', side: 'new', startLine: 10, endLine: 10, + body: 'Not carried yet', author: { name: 'Agent', type: 'agent' }, anchorContent: 'line 10 changed by the feature', + }); + moveTo(fixture.head2); + github.reviewRequests['bob-token'] = [ + { owner: 'acme', repo: 'widgets', number: 1, title: 'Change line ten', author: 'octocat', updatedAt: '2000-01-01T00:00:00Z' }, + ]; + try { + const prepared = await service.advanceSession(old, { carry: false }); + const row = (await service.reviewRequests(kim, { now: Date.now() + 720_000 }))!.requests[0]; + expect(row.session?.id).toBe(old.id); + expect(row.movedTo).toBe(fixture.head2); + + const again = await service.createSession(kim, { repo: 'acme/widgets', pr: 1 }); + expect(again.session.id).toBe(prepared.id); + expect(again.carried).toBe(1); + expect((await reviews.threadsForSession(kim, prepared.id)).map(t => t.id)).toEqual([kept.id]); + } finally { + github.reviewRequests['bob-token'] = []; + moveTo(fixture.head1); + } + }); + + it('carries the findings left behind when making the head’s session finds it already there', async () => { + const hal = (await users.findOrCreate('hal@example.com')).id; + await users.setGitHubToken(hal, 'bob-token'); + const first = (await service.createSession(hal, { repo: 'acme/widgets', pr: 1 })).session; + moveTo(fixture.head2); + try { + const second = (await service.createSession(hal, { repo: 'acme/widgets', pr: 1 })).session; + const later = await reviews.createThread({ + userId: hal, sessionId: second.id, filePath: 'src.ts', side: 'new', startLine: 13, endLine: 13, + body: 'On the second head', author: { name: 'Agent', type: 'agent' }, anchorContent: 'line 10 changed by the feature', + }); + moveTo(fixture.head1); + const lookup = vi.spyOn(reviews, 'prSessionAt').mockResolvedValueOnce(null); + const back = await service.advanceSession(second); + lookup.mockRestore(); + expect(back.id).toBe(first.id); + expect((await reviews.threadsForSession(hal, first.id)).map(t => [t.id, t.startLine])).toEqual([[later.id, 10]]); + } finally { + moveTo(fixture.head1); + } + }); + + it('shows the review requests’ current head without making or moving anything, asking GitHub only about updated pull requests, once a minute', async () => { + const dave = (await users.findOrCreate('dave@example.com')).id; + await users.setGitHubToken(dave, 'bob-token'); + const request = { owner: 'acme', repo: 'widgets', number: 1, title: 'Change line ten', author: 'octocat', updatedAt: '2026-10-03T09:00:00Z' }; + github.reviewRequests['bob-token'] = [request]; + const session = (await service.createSession(dave, { repo: 'acme/widgets', pr: 1 })).session; + const open = await reviews.createThread({ + userId: dave, sessionId: session.id, filePath: 'src.ts', side: 'new', startLine: 10, endLine: 10, + body: 'Still open', author: { name: 'Agent', type: 'agent' }, + }); + + const lookups = pullLookups(); + const unchanged = (await service.reviewRequests(dave))!.requests[0]; + expect(unchanged.session?.id).toBe(session.id); + expect(unchanged.movedTo).toBeNull(); + expect(pullLookups()).toBe(lookups); + + github.reviewRequests['bob-token'] = [{ ...request, updatedAt: '2999-01-01T00:00:00Z' }]; + moveTo(fixture.head2); + try { + const now = Date.now() + 120_000; + const sessionsBefore = (await reviews.listSessions(dave)).length; + const row = (await service.reviewRequests(dave, { now }))!.requests[0]; + expect(row.session?.id).toBe(session.id); + expect(row.movedTo).toBe(fixture.head2); + expect((await reviews.listSessions(dave)).length).toBe(sessionsBefore); + expect((await reviews.getThread(dave, open.id))?.sessionId).toBe(session.id); + const afterMove = pullLookups(); + expect(afterMove).toBeGreaterThan(lookups); + expect((await service.reviewRequests(dave, { now }))!.requests[0].movedTo).toBe(fixture.head2); + expect(pullLookups()).toBe(afterMove); + } finally { + moveTo(fixture.head1); + github.reviewRequests['bob-token'] = []; + } + }); + + it('links the session at the current head where the user already has one', async () => { + const ivy = (await users.findOrCreate('ivy@example.com')).id; + await users.setGitHubToken(ivy, 'bob-token'); + const atHead1 = (await service.createSession(ivy, { repo: 'acme/widgets', pr: 1 })).session; + moveTo(fixture.head2); + await service.createSession(ivy, { repo: 'acme/widgets', pr: 1 }); + moveTo(fixture.head1); + github.reviewRequests['bob-token'] = [ + { owner: 'acme', repo: 'widgets', number: 1, title: 'Change line ten', author: 'octocat', updatedAt: '2999-01-01T00:00:00Z' }, + ]; + try { + const row = (await service.reviewRequests(ivy, { now: Date.now() + 360_000 }))!.requests[0]; + expect(row.session).toMatchObject({ id: atHead1.id, headSha: fixture.head1 }); + expect(row.movedTo).toBeNull(); + } finally { + github.reviewRequests['bob-token'] = []; + } + }); + + it('shows the rows without waiting long on a slow head lookup', async () => { + const lena = (await users.findOrCreate('lena@example.com')).id; + await users.setGitHubToken(lena, 'bob-token'); + const session = (await service.createSession(lena, { repo: 'acme/widgets', pr: 1 })).session; + github.reviewRequests['bob-token'] = [ + { owner: 'acme', repo: 'widgets', number: 1, title: 'Change line ten', author: 'octocat', updatedAt: '2999-01-01T00:00:00Z' }, + ]; + const stuck = vi.spyOn(GitHubApi.prototype, 'getPull').mockReturnValue(new Promise(() => {})); + try { + const started = Date.now(); + const rows = (await service.reviewRequests(lena, { now: Date.now() + 840_000 }))!.requests; + expect(Date.now() - started).toBeLessThan(5_000); + expect(rows[0].session?.id).toBe(session.id); + expect(rows[0].movedTo).toBeNull(); + } finally { + stuck.mockRestore(); + github.reviewRequests['bob-token'] = []; + } + }, 10_000); + + it('keeps a row as it is when its head cannot be looked up', async () => { + const frank = (await users.findOrCreate('frank@example.com')).id; + await users.setGitHubToken(frank, 'bob-token'); + const session = (await service.createSession(frank, { repo: 'acme/widgets', pr: 1 })).session; + github.reviewRequests['bob-token'] = [ + { owner: 'acme', repo: 'widgets', number: 1, title: 'Change line ten', author: 'octocat', updatedAt: '2999-01-01T00:00:00Z' }, + ]; + pulls[1].headSha = fixture.head2; + const failing = vi.spyOn(reviews, 'prSessionAt').mockRejectedValueOnce(new Error('database unavailable')); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const rows = (await service.reviewRequests(frank, { now: Date.now() + 240_000 }))!.requests; + expect(rows[0].session?.id).toBe(session.id); + expect(rows[0].movedTo).toBeNull(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('database unavailable')); + } finally { + failing.mockRestore(); + warn.mockRestore(); + pulls[1].headSha = fixture.head1; + github.reviewRequests['bob-token'] = []; + } + }); +}); diff --git a/packages/ui/src/components/diff/diff-page.tsx b/packages/ui/src/components/diff/diff-page.tsx index 5d15c97e..b8be4316 100644 --- a/packages/ui/src/components/diff/diff-page.tsx +++ b/packages/ui/src/components/diff/diff-page.tsx @@ -8,10 +8,11 @@ import { useWrapLines } from '../../hooks/use-wrap-lines'; import { useKeyboard } from '../../hooks/use-keyboard'; import { useReviewThreads } from '../../hooks/use-review-threads'; import { useTours } from '../../hooks/use-tours'; -import { useHeld, useReviewArrival } from '../../hooks/use-review-arrival'; +import { isReviewPending, useHeld, useReviewArrival } from '../../hooks/use-review-arrival'; import { useHideWhitespace } from '../../hooks/use-hide-whitespace'; import { useAnswerAlerts } from '../../hooks/use-answer-alerts'; import { useTabBadge } from '../../hooks/use-tab-badge'; +import { useFollowHead } from '../../hooks/use-follow-head'; import { isThreadOnScreen, type AnswerAlert } from '../../lib/answer-alerts'; import { pickActiveTour, orderPathsByTour, stopsByPath } from '../../lib/tour-order'; import { TOUR_NOT_STARTED, clampTourStep } from '../../lib/tour-navigation'; @@ -24,6 +25,7 @@ import { DiffView, type DiffViewHandle } from './diff-view'; import { Sidebar } from '../layout/sidebar'; import { ShortcutModal } from '../layout/shortcut-modal'; import { ReviewBanner } from '../layout/review-banner'; +import { MovedOnBanner } from '../layout/moved-on-banner'; import { PullRequestPanel } from '../layout/pull-request-panel'; import { AnswerBubble } from '../layout/answer-bubble'; import { CheckCircleIcon } from '../icons/check-circle-icon'; @@ -90,6 +92,7 @@ export function DiffPage() { const agentCalled = !agentListening && !!liveStatus?.calledAt; const agentReachable = agentListening || !!liveStatus?.routine; const requestReview = useRequestReview(); + const head = useFollowHead(sessionId, info?.movedOn, isReviewPending(info?.review?.state)); const commentCountsByFile = useMemo(() => buildThreadCountsByFile(threads), [threads]); @@ -512,6 +515,7 @@ export function DiffPage() { onGitHubPulled={() => queryClient.invalidateQueries({ queryKey: ['threads'] })} /> + {head.movedOn && } {info?.review && ( ('COMMENT'); + const [draft] = useState(() => (sessionId ? takeReviewDraft(sessionId) : null)); + const [event, setEvent] = useState(draft?.event ?? 'COMMENT'); const submittable = useMemo(() => threads.filter(isSubmittable), [threads]); - const [selected, setSelected] = useState>(new Set()); - const [summary, setSummary] = useState(''); - const [summaryEdited, setSummaryEdited] = useState(false); + const [selected, setSelected] = useState>(() => new Set(draft?.deselected.map(id => `-${id}`))); + const [summary, setSummary] = useState(draft?.summary ?? ''); + const [summaryEdited, setSummaryEdited] = useState(draft?.summary != null); + /** The pull request's head, when posting found it had moved on since this session's. */ + const [movedTo, setMovedTo] = useState(null); + const [updating, setUpdating] = useState(false); // Everything open is selected by default, including threads arriving from the agent while // the dialog is open; deselecting is the deliberate act. @@ -120,7 +126,7 @@ export function GitHubDialog(props: GitHubDialogProps) { setSelected(new Set(submittable.map(thread => thread.id))); }; - const handleSubmit = async () => { + const handleSubmit = async (allowOutdated = false) => { if (!canSubmit) { return; } @@ -130,6 +136,7 @@ export function GitHubDialog(props: GitHubDialogProps) { event, body: summary, comments: chosen.map(threadToPayload), + ...(allowOutdated ? { allowOutdated } : {}), }); if (result.failed > 0) { @@ -138,7 +145,7 @@ export function GitHubDialog(props: GitHubDialogProps) { }); } else { const skipped = result.skipped > 0 ? ` (${result.skipped} already on the PR)` : ''; - const moved = movedOnNote({ commitSha: result.commitSha, headSha: details.headSha }); + const moved = movedOnNote({ commitSha: result.commitSha, headSha: movedTo ?? details.headSha }); toast.success( `Submitted ${result.submitted} comment${result.submitted !== 1 ? 's' : ''} as one review${skipped}`, moved ? { description: moved } : undefined, @@ -147,6 +154,10 @@ export function GitHubDialog(props: GitHubDialogProps) { onClose(); } } catch (err) { + if (err instanceof MovedOnError) { + setMovedTo(err.headSha); + return; + } toast.error('Failed to submit review', { description: err instanceof Error ? err.message : 'Unknown error', }); @@ -155,6 +166,29 @@ export function GitHubDialog(props: GitHubDialogProps) { } }; + const handleUpdate = async () => { + if (!sessionId) { + return; + } + setUpdating(true); + try { + const left = await advanceAndGo(sessionId, next => saveReviewDraft(next, { + summary: summaryEdited ? summary : null, + event, + deselected: submittable.filter(thread => !selected.has(thread.id)).map(thread => thread.id), + })); + if (!left) { + setUpdating(false); + setMovedTo(null); + } + } catch (err) { + setUpdating(false); + toast.error('Could not update to the pull request’s current head', { + description: err instanceof Error ? err.message : 'Unknown error', + }); + } + }; + const handlePull = async () => { if (!sessionId || commentCount === 0) { return; @@ -179,6 +213,9 @@ export function GitHubDialog(props: GitHubDialogProps) { return (
e.stopPropagation()} > @@ -289,45 +326,79 @@ export function GitHubDialog(props: GitHubDialogProps) {
)} -
-
- {(Object.keys(EVENT_LABELS) as ReviewEvent[]).map(value => { - const blocked = value !== 'COMMENT' && details.viewerDidAuthor; - return ( - - ); - })} -
- -
+
+ The pull request has moved on to {movedTo.slice(0, 7)} since{' '} + {details.headSha.slice(0, 7)}, the commit you reviewed. Update to see the new code; open + findings and this draft come along. Or post to the reviewed commit, where GitHub marks lines changed + since as outdated. +
+
+ + +
+
+ ) : ( +
+
+ {(Object.keys(EVENT_LABELS) as ReviewEvent[]).map(value => { + const blocked = value !== 'COMMENT' && details.viewerDidAuthor; + return ( + + ); + })} +
+ +
+ )}
diff --git a/packages/ui/src/components/layout/moved-on-banner.tsx b/packages/ui/src/components/layout/moved-on-banner.tsx new file mode 100644 index 00000000..44af7ebf --- /dev/null +++ b/packages/ui/src/components/layout/moved-on-banner.tsx @@ -0,0 +1,32 @@ +import { Spinner } from '../icons/spinner'; + +interface MovedOnBannerProps { + headSha: string; + updating: boolean; + onUpdate: () => void; +} + +export function MovedOnBanner({ headSha, updating, onUpdate }: MovedOnBannerProps) { + const short = headSha.slice(0, 7); + return ( +
+ {updating && } + + The pull request has moved on to {short} + + {!updating && ( + + )} +
+ ); +} diff --git a/packages/ui/src/components/layout/toolbar.tsx b/packages/ui/src/components/layout/toolbar.tsx index 5ab00b74..3243f101 100644 --- a/packages/ui/src/components/layout/toolbar.tsx +++ b/packages/ui/src/components/layout/toolbar.tsx @@ -12,6 +12,7 @@ import { GitHubIcon } from '../icons/github-icon'; import type { GitHubDetails } from '../../lib/api'; import { DiffStats } from '../diff/diff-stats'; import { GitHubDialog } from './github-dialog'; +import { hasReviewDraft } from '../../lib/session-head'; import { CommentToolbarActions } from '../comments/comment-toolbar-actions'; import { OptionsMenu, menuItemClass } from './options-menu'; import { GENERAL_THREAD_FILE_PATH } from '../comments/types'; @@ -137,7 +138,8 @@ export function Toolbar(props: ToolbarProps) { sessionId, onGitHubPulled, } = props; - const [showGitHub, setShowGitHub] = useState(false); + // A review being posted when the reader moved to the pull request's current head picks up where it was. + const [showGitHub, setShowGitHub] = useState(() => !!sessionId && hasReviewDraft(sessionId)); const formatForCopy = useCallback(() => { return formatThreadsForCopy(threads, diff); diff --git a/packages/ui/src/hooks/use-follow-head.ts b/packages/ui/src/hooks/use-follow-head.ts new file mode 100644 index 00000000..7c47aed9 --- /dev/null +++ b/packages/ui/src/hooks/use-follow-head.ts @@ -0,0 +1,77 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { toast } from 'sonner'; +import type { MovedOn } from '../lib/api'; +import { advanceAndGo } from '../lib/session-head'; +import { readPageState, safeToLeave } from '../lib/sign-in'; + +function postDialogOpen(doc: Document = document): boolean { + return doc.querySelector('[data-post-dialog]') !== null; +} + +/** + * A page opened on an outdated session moves to the current one before the reader starts. Later it + * follows the head only while nobody is looking at it — the tab hidden, or just shown again — and + * only when nothing would be lost: no draft, no field being edited, no save under way, no post + * dialog open. Otherwise, and always while the reader is on the page, a head that moves is offered + * as an update instead. It never moves while a review of this session is queued or under way, + * whose findings would land where the reader no longer looks. + */ +export function useFollowHead(sessionId: string | null, movedOn: MovedOn | null | undefined, reviewing = false) { + const checked = useRef(false); + // Read when the server answers, which can be after a review was asked for meanwhile. + const reviewingNow = useRef(reviewing); + reviewingNow.current = reviewing; + const inFlight = useRef(false); + const [updating, setUpdating] = useState(false); + + const update = useCallback(async (mayLeave?: () => boolean) => { + if (!sessionId || inFlight.current) { + return; + } + inFlight.current = true; + setUpdating(true); + try { + if (!(await advanceAndGo(sessionId, undefined, mayLeave))) { + inFlight.current = false; + setUpdating(false); + } + } catch (err) { + inFlight.current = false; + setUpdating(false); + toast.error('Could not update to the pull request’s current head', { + description: err instanceof Error ? err.message : undefined, + }); + } + }, [sessionId]); + + const followIfUnattended = useCallback(() => { + const unattended = () => !reviewingNow.current && safeToLeave(readPageState()) && !postDialogOpen(); + if (!movedOn || !unattended()) { + return; + } + void update(unattended); + }, [movedOn, update]); + + useEffect(() => { + if (!sessionId) { + return; + } + if (!checked.current) { + checked.current = true; + if (movedOn && !reviewing) { + void update(() => !reviewingNow.current && safeToLeave(readPageState())); + } + return; + } + if (document.visibilityState === 'hidden') { + followIfUnattended(); + } + }, [sessionId, movedOn, reviewing, update, followIfUnattended]); + + useEffect(() => { + document.addEventListener('visibilitychange', followIfUnattended); + return () => document.removeEventListener('visibilitychange', followIfUnattended); + }, [followIfUnattended]); + + return { movedOn: movedOn ?? null, updating, update: () => update() }; +} diff --git a/packages/ui/src/hooks/use-info.ts b/packages/ui/src/hooks/use-info.ts index 445848cf..8c107b4d 100644 --- a/packages/ui/src/hooks/use-info.ts +++ b/packages/ui/src/hooks/use-info.ts @@ -1,6 +1,7 @@ import { useMutation, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'; import { repoInfoOptions } from '../queries/info'; import { requestReview } from '../lib/api'; +import { goToSession } from '../lib/session-head'; export function useInfo() { const { data, error } = useSuspenseQuery(repoInfoOptions()); @@ -16,8 +17,14 @@ export function useRequestReview() { const queryClient = useQueryClient(); return useMutation({ mutationFn: requestReview, - onSuccess: review => { - queryClient.setQueryData(repoInfoOptions().queryKey, info => (info ? { ...info, review } : info)); + onSuccess: ({ sessionId, ...review }) => { + const info = queryClient.getQueryData(repoInfoOptions().queryKey); + // The review was asked for on the pull request's current head, which is another session. + if (sessionId && info && sessionId !== info.sessionId) { + goToSession(sessionId); + return; + } + queryClient.setQueryData(repoInfoOptions().queryKey, current => (current ? { ...current, review } : current)); }, }); } diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts index cee92083..e5b8cbf4 100644 --- a/packages/ui/src/lib/api.ts +++ b/packages/ui/src/lib/api.ts @@ -1,4 +1,5 @@ import type { + AdvanceResponse, Comment, CommentAuthor, CommentThread, @@ -7,11 +8,12 @@ import type { FileContentResponse, GitHubDetails, LiveStatusResponse, + MovedOnRefusal, PullCommentsResult, RepoInfoResponse, ReplyRequest, + ReviewRequestResponse, ReviewResult, - ReviewRun, ReviewSubmission, ThreadStatus, Tour, @@ -21,6 +23,7 @@ import { apiRequest } from './request'; export type { GitHubDetails, + MovedOn, PrComment, ReviewEvent, ReviewRun, @@ -143,12 +146,32 @@ export async function fetchGitHubDetails(): Promise { return res.json(); } -export function createReviewOnGitHub(review: ReviewSubmission): Promise { - return apiFetch('/api/github/create-review', { +/** The pull request has moved on since the session's head, and the review was not posted. */ +export class MovedOnError extends Error { + constructor(readonly headSha: string, readonly sessionHeadSha: string, message: string) { + super(message); + } +} + +export async function createReviewOnGitHub(review: ReviewSubmission): Promise { + const res = await apiRequest(apiPath('/api/github/create-review'), { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(review), }); + if (res.ok) { + return res.json(); + } + const json = (await res.json().catch(() => null)) as Partial | null; + if (res.status === 409 && json?.code === 'moved_on' && json.headSha && json.sessionHeadSha) { + throw new MovedOnError(json.headSha, json.sessionHeadSha, json.error ?? 'The pull request has moved on'); + } + throw new Error(json?.error || `HTTP ${res.status}`); +} + +/** With `prepare` the session at the current head is made, but nothing is moved to it yet. */ +export function advanceSession(prepare = false): Promise { + return apiFetch('/api/advance', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify({ prepare }) }); } export function pullCommentsFromGitHub(sessionId: string): Promise { @@ -163,7 +186,7 @@ export function fetchLiveStatus(): Promise { return apiFetch('/api/live/status'); } -export function requestReview(): Promise { +export function requestReview(): Promise { return apiFetch('/api/review-request', { method: 'POST' }); } diff --git a/packages/ui/src/lib/session-head.ts b/packages/ui/src/lib/session-head.ts new file mode 100644 index 00000000..6d099c70 --- /dev/null +++ b/packages/ui/src/lib/session-head.ts @@ -0,0 +1,91 @@ +import { advanceSession, type ReviewEvent } from './api'; +import { appBase } from './base'; + +/** The same view of another session: the page is served under `/s/`, and the rest of the URL carries over. */ +export function sessionHref( + sessionId: string, + location: { pathname: string; search: string; hash: string }, + base = appBase(), +): string { + const rest = base && location.pathname.startsWith(base) ? location.pathname.slice(base.length) : location.pathname; + return `/s/${encodeURIComponent(sessionId)}${rest || '/'}${location.search}${location.hash}`; +} + +/** Replaced in tests, where the page cannot leave. */ +export const navigation = { + replace: (href: string) => window.location.replace(href), +}; + +export function goToSession(sessionId: string): void { + navigation.replace(sessionHref(sessionId, window.location)); +} + +/** + * Moves the page to the session at the pull request's current head. False when this session is + * already it, so the page stays. With `mayLeave` the destination is made first and asked again + * once it is ready, and the findings move only when the page is still free to go; making a new + * session can take long enough for the reader to have started something here. + */ +export async function advanceAndGo( + currentSessionId: string, + beforeLeaving?: (sessionId: string) => void, + mayLeave?: () => boolean, +): Promise { + if (mayLeave) { + const prepared = await advanceSession(true); + if (prepared.sessionId === currentSessionId || !mayLeave()) { + return false; + } + } + const { sessionId } = await advanceSession(); + if (sessionId === currentSessionId) { + return false; + } + beforeLeaving?.(sessionId); + goToSession(sessionId); + return true; +} + +/** What the reader had written in the post dialog, kept across the move to a newer session. */ +export interface ReviewDraft { + summary: string | null; + event: ReviewEvent; + deselected: string[]; +} + +const DRAFT_KEY = 'diffity:review-draft:'; + +export function saveReviewDraft(sessionId: string, draft: ReviewDraft): void { + try { + sessionStorage.setItem(DRAFT_KEY + sessionId, JSON.stringify(draft)); + } catch { + // Without storage the draft is lost; the findings themselves carry over on the server. + } +} + +export function hasReviewDraft(sessionId: string): boolean { + try { + return sessionStorage.getItem(DRAFT_KEY + sessionId) !== null; + } catch { + return false; + } +} + +/** Read once: a draft restored into the dialog is the dialog's from then on. */ +export function takeReviewDraft(sessionId: string): ReviewDraft | null { + try { + const raw = sessionStorage.getItem(DRAFT_KEY + sessionId); + sessionStorage.removeItem(DRAFT_KEY + sessionId); + if (!raw) { + return null; + } + const draft = JSON.parse(raw) as Partial; + return { + summary: typeof draft.summary === 'string' ? draft.summary : null, + event: draft.event === 'APPROVE' || draft.event === 'REQUEST_CHANGES' ? draft.event : 'COMMENT', + deselected: Array.isArray(draft.deselected) ? draft.deselected.filter((id): id is string => typeof id === 'string') : [], + }; + } catch { + return null; + } +} diff --git a/packages/ui/src/lib/sign-in.ts b/packages/ui/src/lib/sign-in.ts index 4002bebf..5a6ceb43 100644 --- a/packages/ui/src/lib/sign-in.ts +++ b/packages/ui/src/lib/sign-in.ts @@ -43,8 +43,13 @@ export interface PageState { unsavedWrite: boolean; } +/** Nothing the reader is in the middle of would be lost by leaving the page. */ +export function safeToLeave(state: PageState): boolean { + return !state.unsavedWrite && !state.hasDraft && !state.editing; +} + export function shouldAutoReload(state: PageState, alreadyReloaded: boolean): boolean { - return !alreadyReloaded && !state.unsavedWrite && state.visible && !state.hasDraft && !state.editing; + return !alreadyReloaded && state.visible && safeToLeave(state); } const TEXT_INPUT_TYPES = new Set(['', 'text', 'search', 'email', 'url', 'tel', 'password', 'number']); diff --git a/packages/ui/src/queries/info.ts b/packages/ui/src/queries/info.ts index 63eaf357..b6dff62d 100644 --- a/packages/ui/src/queries/info.ts +++ b/packages/ui/src/queries/info.ts @@ -8,5 +8,7 @@ export function repoInfoOptions() { queryFn: () => fetchRepoInfo(), // Quick while a review is arriving; otherwise slow enough to notice one that an agent starts later. refetchInterval: query => (isReviewPending(query.state.data?.review?.state) ? 3000 : 30_000), + // A hidden page still hears that the pull request moved on, so it can follow before the reader is back. + refetchIntervalInBackground: true, }); } diff --git a/packages/ui/tests/follow-head.test.tsx b/packages/ui/tests/follow-head.test.tsx new file mode 100644 index 00000000..e7630b5d --- /dev/null +++ b/packages/ui/tests/follow-head.test.tsx @@ -0,0 +1,365 @@ +import type { ReactNode } from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { act, render, cleanup, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'; +import { useFollowHead } from '../src/hooks/use-follow-head'; +import { useRequestReview } from '../src/hooks/use-info'; +import { repoInfoOptions } from '../src/queries/info'; +import { MovedOnBanner } from '../src/components/layout/moved-on-banner'; +import { GitHubDialog } from '../src/components/layout/github-dialog'; +import { navigation, sessionHref } from '../src/lib/session-head'; +import type { GitHubDetails, MovedOn } from '../src/lib/api'; +import { makeComment, makeThread } from './helpers/wire'; + +const OLD = 'a'.repeat(40); +const NEW = 'b'.repeat(40); + +interface Call { + url: string; + method: string; + body: unknown; +} + +function stubServer(answers: Record Response>): Call[] { + const calls: Call[] = []; + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ url, method: init?.method ?? 'GET', body }); + const path = Object.keys(answers).find(key => url.endsWith(key)); + return path ? answers[path](body) : Response.json({ error: 'Not found' }, { status: 404 }); + }); + return calls; +} + +function stubNavigation() { + return vi.spyOn(navigation, 'replace').mockImplementation(() => {}); +} + +afterEach(() => { + cleanup(); + setVisibility('visible', false); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + sessionStorage.clear(); +}); + +describe('the address of the same view in another session', () => { + it('swaps the session and keeps the rest', () => { + const location = { pathname: '/s/old/', search: '?view=unified', hash: '#src.ts' }; + expect(sessionHref('new', location, '/s/old')).toBe('/s/new/?view=unified#src.ts'); + expect(sessionHref('new', { pathname: '/s/old', search: '', hash: '' }, '/s/old')).toBe('/s/new/'); + }); +}); + +function Harness({ movedOn, reviewing, children }: { movedOn: MovedOn | null; reviewing?: boolean; children?: ReactNode }) { + const head = useFollowHead('old', movedOn, reviewing); + return ( + <> + {children} + {head.movedOn + ? + : current} + + ); +} + +let visibility: DocumentVisibilityState = 'visible'; + +function setVisibility(state: DocumentVisibilityState, announce = true) { + visibility = state; + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility }); + if (announce) { + act(() => { + document.dispatchEvent(new Event('visibilitychange')); + }); + } +} + +const moved: MovedOn = { headSha: NEW, sessionId: 'new' }; + +describe('a review page behind its pull request', () => { + it('moves to the current head on load, without asking', async () => { + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const replace = stubNavigation(); + render(); + + await waitFor(() => expect(replace).toHaveBeenCalledWith('/s/new/')); + expect(calls.map(call => [call.method, call.url, call.body])).toEqual([ + ['POST', '/api/advance', { prepare: true }], + ['POST', '/api/advance', { prepare: false }], + ]); + }); + + it('stays and offers the update while an agent is still reviewing this session', async () => { + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const replace = stubNavigation(); + render(); + + expect(await screen.findByTestId('moved-on-banner')).toBeTruthy(); + expect(calls).toHaveLength(0); + expect(replace).not.toHaveBeenCalled(); + }); + + it('offers an update when the head moves while the page is open, and moves only when asked', async () => { + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const replace = stubNavigation(); + const { rerender } = render(); + expect(screen.getByText('current')).toBeTruthy(); + + rerender(); + const banner = await screen.findByTestId('moved-on-banner'); + expect(banner.textContent).toContain(`moved on to ${NEW.slice(0, 7)}`); + expect(calls).toHaveLength(0); + expect(replace).not.toHaveBeenCalled(); + + await userEvent.setup().click(screen.getByRole('button', { name: 'Update' })); + await waitFor(() => expect(replace).toHaveBeenCalledWith('/s/new/')); + expect(calls.map(call => call.url)).toEqual(['/api/advance']); + }); + + it('stays when the server finds the session current after all', async () => { + stubServer({ '/api/advance': () => Response.json({ sessionId: 'old', headSha: OLD }) }); + const replace = stubNavigation(); + render(); + + await waitFor(() => expect(screen.getByRole('button', { name: 'Update' })).toBeTruthy()); + expect(replace).not.toHaveBeenCalled(); + }); +}); + +describe('a review page nobody is looking at', () => { + it('follows a head that moves while the tab is hidden', async () => { + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const replace = stubNavigation(); + const { rerender } = render(); + setVisibility('hidden', false); + + rerender(); + await waitFor(() => expect(replace).toHaveBeenCalledWith('/s/new/')); + expect(calls.map(call => call.body)).toEqual([{ prepare: true }, { prepare: false }]); + }); + + it('follows when the reader leaves the tab, or comes back to it, with the update still on offer', async () => { + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const replace = stubNavigation(); + const { rerender } = render(); + rerender(); + expect(await screen.findByTestId('moved-on-banner')).toBeTruthy(); + expect(calls).toHaveLength(0); + + setVisibility('hidden'); + await waitFor(() => expect(replace).toHaveBeenCalledWith('/s/new/')); + expect(calls).toHaveLength(2); + }); + + it('stays when the reader starts writing while the new head is being fetched', async () => { + let answer!: () => void; + const answered = new Promise(resolve => { answer = resolve; }); + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const fetchNow = globalThis.fetch; + vi.stubGlobal('fetch', async (...args: Parameters) => { + await answered; + return fetchNow(...args); + }); + const replace = stubNavigation(); + const { rerender } = render(); + setVisibility('hidden', false); + rerender(); + + screen.getByRole('textbox', { name: 'Reply' }).focus(); + answer(); + await waitFor(() => expect(calls).toHaveLength(1)); + await new Promise(resolve => setTimeout(resolve, 20)); + expect(calls.map(call => call.body)).toEqual([{ prepare: true }]); + expect(replace).not.toHaveBeenCalled(); + expect(screen.getByTestId('moved-on-banner')).toBeTruthy(); + }); + + it('stays when a review is asked for while the new head is being fetched', async () => { + let answer!: () => void; + const answered = new Promise(resolve => { answer = resolve; }); + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const fetchNow = globalThis.fetch; + vi.stubGlobal('fetch', async (...args: Parameters) => { + await answered; + return fetchNow(...args); + }); + const replace = stubNavigation(); + const { rerender } = render(); + setVisibility('hidden', false); + rerender(); + + rerender(); + answer(); + await waitFor(() => expect(calls).toHaveLength(1)); + await new Promise(resolve => setTimeout(resolve, 20)); + expect(replace).not.toHaveBeenCalled(); + }); + + it('stays while the reader is on the page', async () => { + const calls = stubServer({ '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }) }); + const replace = stubNavigation(); + const { rerender } = render(); + rerender(); + expect(await screen.findByTestId('moved-on-banner')).toBeTruthy(); + rerender(); + await new Promise(resolve => setTimeout(resolve, 20)); + expect(calls).toHaveLength(0); + expect(replace).not.toHaveBeenCalled(); + }); + + const blockers: [string, () => ReactNode, () => void][] = [ + ['a draft in a field', () =>