From 8bf938b2662176c4cf8e6b75593089461cc1baef Mon Sep 17 00:00:00 2001 From: "Fredrik Liljegren (Claude Code Opus 5.5)" Date: Tue, 10 Nov 2026 13:35:55 +0100 Subject: [PATCH 1/7] fix: a pull-request session follows the pull request's head The Sessions page moves a row's session to the current head (findings carry over), a review page opened on an old head moves on by itself and offers Update when the head moves while open, the attendant is always handed the current head, and posting to an outdated head asks first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Bwp5QefjsjMFeq6CK6cT6w --- README.md | 14 +- packages/api/src/github.ts | 10 + packages/api/src/info.ts | 19 ++ packages/api/src/requests.ts | 1 + packages/api/tests/requests.test.ts | 8 + packages/server/src/app.ts | 5 +- packages/server/src/github.ts | 4 + packages/server/src/service.ts | 142 +++++++++++- packages/server/src/ui-api.ts | 29 ++- packages/server/tests/helpers.ts | 4 +- packages/server/tests/mcp.test.ts | 6 +- packages/server/tests/posting.test.ts | 49 ++++- packages/server/tests/routine.test.ts | 37 +++- packages/server/tests/service.test.ts | 114 +++++++++- packages/ui/src/components/diff/diff-page.tsx | 4 + .../src/components/layout/github-dialog.tsx | 156 +++++++++---- .../src/components/layout/moved-on-banner.tsx | 32 +++ packages/ui/src/components/layout/toolbar.tsx | 4 +- packages/ui/src/hooks/use-follow-head.ts | 43 ++++ packages/ui/src/hooks/use-info.ts | 11 +- packages/ui/src/lib/api.ts | 30 ++- packages/ui/src/lib/session-head.ts | 79 +++++++ packages/ui/tests/follow-head.test.tsx | 205 ++++++++++++++++++ 23 files changed, 919 insertions(+), 87 deletions(-) create mode 100644 packages/ui/src/components/layout/moved-on-banner.tsx create mode 100644 packages/ui/src/hooks/use-follow-head.ts create mode 100644 packages/ui/src/lib/session-head.ts create mode 100644 packages/ui/tests/follow-head.test.tsx diff --git a/README.md b/README.md index 77c92d96..a4ed5a61 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,15 @@ 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 links the session at the current head, a review page opened on an older one moves + there, and one left open 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 +232,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..b9a5a5da 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -797,8 +797,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/service.ts b/packages/server/src/service.ts index 2af2f1d1..6da2dbc5 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); } } @@ -84,6 +86,22 @@ 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; + +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 +181,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 +251,123 @@ export class ReviewService { return cached; } + /** + * Each row with the user's session at the pull request's current head. Only a pull request updated + * since its session was made can have moved, 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 rows: ReviewRequestRow[] = requests.map(request => ({ + ...request, + session: sessions.get(prKey(request.owner, request.repo, request.number)) ?? null, + })); + const updated = rows.filter(row => row.session && Date.parse(row.updatedAt) > Date.parse(row.session.createdAt)); + await eachLimited(updated, ADVANCE_CONCURRENCY, async row => { + try { + const session = await this.reviews.getSession(userId, row.session!.id); + const advanced = session && await this.advanceSession(session, { fresh: false }); + if (advanced && advanced.id !== session.id) { + row.session = { id: advanced.id, headSha: advanced.headSha, createdAt: advanced.createdAt }; + } + } catch (err) { + console.warn(`Bringing ${row.owner}/${row.repo}#${row.number} to its current head failed: ${err instanceof Error ? err.message : String(err)}`); + } + }); + return rows; + } + + /** 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 the 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. + */ + async advanceSession(session: ReviewSessionRecord, { fresh = true }: { fresh?: boolean } = {}): Promise { + if (session.prNumber === null) { + return session; + } + const head = await this.knownPullHead(session, fresh); + if (head && (head.closed || head.headSha === session.headSha)) { + return session; + } + const newest = await this.newestPrSession(session); + if (newest && (head ? newest.headSha === head.headSha : newest.id !== session.id && newest.createdAt > session.createdAt)) { + return (await this.reviews.getSession(session.userId, newest.id)) ?? session; + } + if (!head) { + return session; + } + return (await this.createSession(session.userId, { repo: `${session.owner}/${session.repo}`, pr: session.prNumber })).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; + } + const head = await this.knownPullHead(session, false); + 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 { @@ -600,11 +733,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..b1648c09 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); + 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/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..402cc1fb 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'); @@ -388,3 +390,111 @@ 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('brings the review requests’ sessions to the current head, 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 lookups = pullLookups(); + expect((await service.reviewRequests(dave))?.requests[0].session?.id).toBe(session.id); + 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 rows = (await service.reviewRequests(dave, { now }))!.requests; + expect(rows[0].session?.headSha).toBe(fixture.head2); + expect(rows[0].session?.id).not.toBe(session.id); + const afterMove = pullLookups(); + expect(afterMove).toBeGreaterThan(lookups); + expect((await service.reviewRequests(dave, { now }))!.requests[0].session?.id).toBe(rows[0].session?.id); + expect(pullLookups()).toBe(afterMove); + } finally { + moveTo(fixture.head1); + github.reviewRequests['bob-token'] = []; + } + }); + + it('keeps a row’s session when bringing it forward fails', 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(service, 'createSession').mockRejectedValueOnce(new Error('mirror 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(warn).toHaveBeenCalledWith(expect.stringContaining('mirror 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..f1fedf7b 100644 --- a/packages/ui/src/components/diff/diff-page.tsx +++ b/packages/ui/src/components/diff/diff-page.tsx @@ -12,6 +12,7 @@ import { 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); 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; @@ -289,45 +323,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..30c5f9f3 --- /dev/null +++ b/packages/ui/src/hooks/use-follow-head.ts @@ -0,0 +1,43 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { toast } from 'sonner'; +import type { MovedOn } from '../lib/api'; +import { advanceAndGo } from '../lib/session-head'; + +/** + * A page opened on an outdated session moves to the current one before the reader starts. Once the + * reader is in it, the page never switches by itself: a head that moves meanwhile is offered as an + * update instead. + */ +export function useFollowHead(sessionId: string | null, movedOn: MovedOn | null | undefined) { + const checked = useRef(false); + const [updating, setUpdating] = useState(false); + + const update = useCallback(async () => { + if (!sessionId) { + return; + } + setUpdating(true); + try { + if (!(await advanceAndGo(sessionId))) { + setUpdating(false); + } + } catch (err) { + setUpdating(false); + toast.error('Could not update to the pull request’s current head', { + description: err instanceof Error ? err.message : undefined, + }); + } + }, [sessionId]); + + useEffect(() => { + if (checked.current || !sessionId) { + return; + } + checked.current = true; + if (movedOn) { + void update(); + } + }, [sessionId, movedOn, update]); + + return { movedOn: movedOn ?? null, updating, 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..2623ebb5 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,31 @@ 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}`); +} + +export function advanceSession(): Promise { + return apiFetch('/api/advance', { method: 'POST' }); } export function pullCommentsFromGitHub(sessionId: string): Promise { @@ -163,7 +185,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..a1046856 --- /dev/null +++ b/packages/ui/src/lib/session-head.ts @@ -0,0 +1,79 @@ +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. + */ +export async function advanceAndGo(currentSessionId: string, beforeLeaving?: (sessionId: string) => void): Promise { + 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/tests/follow-head.test.tsx b/packages/ui/tests/follow-head.test.tsx new file mode 100644 index 00000000..f81e53d9 --- /dev/null +++ b/packages/ui/tests/follow-head.test.tsx @@ -0,0 +1,205 @@ +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { 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(); + 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 }: { movedOn: MovedOn | null }) { + const head = useFollowHead('old', movedOn); + return head.movedOn + ? + : current; +} + +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])).toEqual([['POST', '/api/advance']]); + }); + + 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(); + }); +}); + +const details: GitHubDetails = { + prNumber: 7, + prTitle: 'Change line ten', + prUrl: 'https://github.com/o/r/pull/7', + prCreatedAt: '2026-08-21T10:00:00.000Z', + headSha: OLD, + commentCount: 0, + viewerDidAuthor: false, + prAuthor: 'octocat', + prBody: '', + reviews: [], +}; + +const threads = [ + makeThread({ id: 't1', comments: [makeComment({ id: 'c1', body: 'P2: one' })] }), + makeThread({ id: 't2', comments: [makeComment({ id: 'c2', body: 'P2: two' })] }), +]; + +function renderDialog(sessionId: string) { + return render( + , + ); +} + +const movedOn = () => Response.json( + { error: 'The pull request has moved on', code: 'moved_on', headSha: NEW, sessionHeadSha: OLD }, + { status: 409 }, +); + +const posted = () => Response.json({ + submitted: 2, submittedThreadIds: ['t1', 't2'], commentIds: [], skipped: 0, failed: 0, errors: [], reviewUrl: 'u', commitSha: OLD, +}); + +describe('posting after the pull request moved on', () => { + it('asks first, and posts to the reviewed commit when told to', async () => { + let refuse = true; + const calls = stubServer({ '/api/github/create-review': () => (refuse ? movedOn() : posted()) }); + const user = userEvent.setup(); + renderDialog('old'); + + await user.click(screen.getByRole('button', { name: /^submit 2/i })); + const confirm = await screen.findByTestId('moved-on-confirm'); + expect(confirm.textContent).toContain(NEW.slice(0, 7)); + expect(screen.getByRole('button', { name: `Update to ${NEW.slice(0, 7)}` })).toBeTruthy(); + expect((calls[0].body as { allowOutdated?: boolean }).allowOutdated).toBeUndefined(); + + refuse = false; + await user.click(screen.getByRole('button', { name: `Post to ${OLD.slice(0, 7)} anyway` })); + await waitFor(() => expect(calls).toHaveLength(2)); + expect(calls[1].body).toMatchObject({ event: 'COMMENT', allowOutdated: true }); + }); + + it('updates to the new head, and the draft comes along', async () => { + const calls = stubServer({ + '/api/github/create-review': movedOn, + '/api/advance': () => Response.json({ sessionId: 'new', headSha: NEW }), + }); + const replace = stubNavigation(); + const user = userEvent.setup(); + renderDialog('old'); + + await user.click(screen.getAllByRole('checkbox')[0]); + await user.type(screen.getByRole('textbox'), 'Looks right'); + await user.click(screen.getByRole('button', { name: /^request changes$/i })); + await user.click(screen.getByRole('button', { name: /^submit 1/i })); + await user.click(await screen.findByRole('button', { name: `Update to ${NEW.slice(0, 7)}` })); + await waitFor(() => expect(replace).toHaveBeenCalledWith('/s/new/')); + expect(calls.map(call => call.url)).toEqual(['/api/github/create-review', '/api/advance']); + + cleanup(); + renderDialog('new'); + expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('Looks right'); + expect(screen.getByRole('button', { name: /^request changes$/i }).getAttribute('aria-pressed')).toBe('true'); + expect(screen.getByRole('button', { name: /^submit 1/i })).toBeTruthy(); + + cleanup(); + renderDialog('new'); + expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(''); + }); +}); + +function RequestHarness() { + const { data } = useQuery(repoInfoOptions()); + const request = useRequestReview(); + return data ? : null; +} + +describe('asking for a review after the pull request moved on', () => { + it('goes to the session the review was asked for on', async () => { + const run = { state: 'queued', queuedAt: null, startedAt: null, doneAt: null, note: '' }; + stubServer({ + '/api/info': () => Response.json({ sessionId: 'old', review: { ...run, state: 'none' } }), + '/api/review-request': () => Response.json({ ...run, sessionId: 'new' }), + }); + const replace = stubNavigation(); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + , + ); + + await userEvent.setup().click(await screen.findByRole('button', { name: 'Ask' })); + await waitFor(() => expect(replace).toHaveBeenCalledWith('/s/new/')); + expect(client.getQueryData(repoInfoOptions().queryKey)?.review?.state).toBe('none'); + client.clear(); + }); +}); From 48e2fcb2a4996315c61992800361e17ca5af7b53 Mon Sep 17 00:00:00 2001 From: "Fredrik Liljegren (Claude Code Opus 5.5)" Date: Tue, 10 Nov 2026 13:37:07 +0100 Subject: [PATCH 2/7] fix: a page whose session an agent is still reviewing offers the new head instead of leaving Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Bwp5QefjsjMFeq6CK6cT6w --- packages/ui/src/components/diff/diff-page.tsx | 2 +- packages/ui/src/hooks/use-follow-head.ts | 9 +++++---- packages/ui/tests/follow-head.test.tsx | 14 ++++++++++++-- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/ui/src/components/diff/diff-page.tsx b/packages/ui/src/components/diff/diff-page.tsx index f1fedf7b..ba1ba054 100644 --- a/packages/ui/src/components/diff/diff-page.tsx +++ b/packages/ui/src/components/diff/diff-page.tsx @@ -92,7 +92,7 @@ export function DiffPage() { const agentCalled = !agentListening && !!liveStatus?.calledAt; const agentReachable = agentListening || !!liveStatus?.routine; const requestReview = useRequestReview(); - const head = useFollowHead(sessionId, info?.movedOn); + const head = useFollowHead(sessionId, info?.movedOn, info?.review?.state === 'reviewing'); const commentCountsByFile = useMemo(() => buildThreadCountsByFile(threads), [threads]); diff --git a/packages/ui/src/hooks/use-follow-head.ts b/packages/ui/src/hooks/use-follow-head.ts index 30c5f9f3..4d9a3b3d 100644 --- a/packages/ui/src/hooks/use-follow-head.ts +++ b/packages/ui/src/hooks/use-follow-head.ts @@ -6,9 +6,10 @@ import { advanceAndGo } from '../lib/session-head'; /** * A page opened on an outdated session moves to the current one before the reader starts. Once the * reader is in it, the page never switches by itself: a head that moves meanwhile is offered as an - * update instead. + * update instead. Neither does it while an agent is still reviewing this session, whose findings + * would land where the reader no longer looks. */ -export function useFollowHead(sessionId: string | null, movedOn: MovedOn | null | undefined) { +export function useFollowHead(sessionId: string | null, movedOn: MovedOn | null | undefined, reviewing = false) { const checked = useRef(false); const [updating, setUpdating] = useState(false); @@ -34,10 +35,10 @@ export function useFollowHead(sessionId: string | null, movedOn: MovedOn | null return; } checked.current = true; - if (movedOn) { + if (movedOn && !reviewing) { void update(); } - }, [sessionId, movedOn, update]); + }, [sessionId, movedOn, reviewing, update]); return { movedOn: movedOn ?? null, updating, update }; } diff --git a/packages/ui/tests/follow-head.test.tsx b/packages/ui/tests/follow-head.test.tsx index f81e53d9..daee0c79 100644 --- a/packages/ui/tests/follow-head.test.tsx +++ b/packages/ui/tests/follow-head.test.tsx @@ -51,8 +51,8 @@ describe('the address of the same view in another session', () => { }); }); -function Harness({ movedOn }: { movedOn: MovedOn | null }) { - const head = useFollowHead('old', movedOn); +function Harness({ movedOn, reviewing }: { movedOn: MovedOn | null; reviewing?: boolean }) { + const head = useFollowHead('old', movedOn, reviewing); return head.movedOn ? : current; @@ -68,6 +68,16 @@ describe('a review page behind its pull request', () => { expect(calls.map(call => [call.method, call.url])).toEqual([['POST', '/api/advance']]); }); + 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(); From 9e8fcba8f98b034377373b5aa9ce028ad5af6496 Mon Sep 17 00:00:00 2001 From: "Fredrik Liljegren (Claude Code Opus 5.5)" Date: Tue, 10 Nov 2026 13:50:19 +0100 Subject: [PATCH 3/7] fix: the Sessions page only points at the current head, and an open tab follows it when nothing would be lost Advancing onto an existing session carries the source's open findings over too, and posting anyway needs something to post. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Bwp5QefjsjMFeq6CK6cT6w --- README.md | 5 +- packages/server/src/app.ts | 4 +- packages/server/src/reviews.ts | 16 ++- packages/server/src/service.ts | 85 +++++++++---- packages/server/tests/http.test.ts | 24 +++- packages/server/tests/service.test.ts | 94 +++++++++++++-- .../src/components/layout/github-dialog.tsx | 5 +- packages/ui/src/hooks/use-follow-head.ts | 49 ++++++-- packages/ui/src/lib/sign-in.ts | 7 +- packages/ui/src/queries/info.ts | 2 + packages/ui/tests/follow-head.test.tsx | 113 +++++++++++++++++- 11 files changed, 344 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index a4ed5a61..f441df73 100644 --- a/README.md +++ b/README.md @@ -34,8 +34,9 @@ The first tool call opens the browser to sign in and allow the connection. Then: - **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. A pull request session follows its head: the - Sessions page links the session at the current head, a review page opened on an older one moves - there, and one left open offers the update. + 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 diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index b9a5a5da..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 ? `
` : ''}` : `
diff --git a/packages/server/src/reviews.ts b/packages/server/src/reviews.ts index 43503afa..bc0fa39a 100644 --- a/packages/server/src/reviews.ts +++ b/packages/server/src/reviews.ts @@ -350,6 +350,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 +374,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 +393,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 6da2dbc5..a2d5f252 100644 --- a/packages/server/src/service.ts +++ b/packages/server/src/service.ts @@ -57,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 { @@ -252,25 +254,33 @@ export class ReviewService { } /** - * Each row with the user's session at the pull request's current head. Only a pull request updated - * since its session was made can have moved, so the others cost no GitHub request. + * Each row with the user's newest session, or their session at the pull request's current head where + * they have one. Nothing is made or moved here: a session left behind is brought forward when it is + * opened or handed to an agent. Only a pull request updated since its session was made can have moved, + * so the others cost no GitHub request. */ private async withSessions(userId: string, requests: ReviewRequest[]): Promise { const sessions = await this.reviews.latestPrSessions(userId, requests); const rows: ReviewRequestRow[] = requests.map(request => ({ ...request, session: sessions.get(prKey(request.owner, request.repo, request.number)) ?? null, + movedTo: null, })); const updated = rows.filter(row => row.session && Date.parse(row.updatedAt) > Date.parse(row.session.createdAt)); await eachLimited(updated, ADVANCE_CONCURRENCY, async row => { try { - const session = await this.reviews.getSession(userId, row.session!.id); - const advanced = session && await this.advanceSession(session, { fresh: false }); - if (advanced && advanced.id !== session.id) { - row.session = { id: advanced.id, headSha: advanced.headSha, createdAt: advanced.createdAt }; + 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 = 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(`Bringing ${row.owner}/${row.repo}#${row.number} to its current head failed: ${err instanceof Error ? err.message : String(err)}`); + console.warn(`Looking up ${row.owner}/${row.repo}#${row.number}'s current head failed: ${err instanceof Error ? err.message : String(err)}`); } }); return rows; @@ -320,26 +330,40 @@ export class ReviewService { } /** - * The user's session at the pull request's current head, made if need be, with the 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. + * 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. */ - async advanceSession(session: ReviewSessionRecord, { fresh = true }: { fresh?: boolean } = {}): Promise { + async advanceSession(session: ReviewSessionRecord): Promise { if (session.prNumber === null) { return session; } - const head = await this.knownPullHead(session, fresh); + const head = await this.knownPullHead(session, true); if (head && (head.closed || head.headSha === session.headSha)) { return session; } - const newest = await this.newestPrSession(session); - if (newest && (head ? newest.headSha === head.headSha : newest.id !== session.id && newest.createdAt > session.createdAt)) { - return (await this.reviews.getSession(session.userId, newest.id)) ?? 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 (!head) { - return session; + if (existing) { + await this.carryOpenWork(existing, [session]); + return existing; + } + const created = await this.createSession(session.userId, { repo: `${session.owner}/${session.repo}`, pr: session.prNumber }); + if (!created.created) { + await this.carryOpenWork(created.session, [session]); } - return (await this.createSession(session.userId, { repo: `${session.owner}/${session.repo}`, pr: session.prNumber })).session; + 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. */ @@ -449,20 +473,29 @@ export class ReviewService { /** * 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; } @@ -474,7 +507,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) { @@ -498,7 +531,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 { 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/service.test.ts b/packages/server/tests/service.test.ts index 402cc1fb..6cd22eb8 100644 --- a/packages/server/tests/service.test.ts +++ b/packages/server/tests/service.test.ts @@ -448,27 +448,83 @@ describe('following a pull request’s head', () => { } }); - it('brings the review requests’ sessions to the current head, asking GitHub only about updated pull requests, once a minute', async () => { + 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('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(); - expect((await service.reviewRequests(dave))?.requests[0].session?.id).toBe(session.id); + 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 rows = (await service.reviewRequests(dave, { now }))!.requests; - expect(rows[0].session?.headSha).toBe(fixture.head2); - expect(rows[0].session?.id).not.toBe(session.id); + 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].session?.id).toBe(rows[0].session?.id); + expect((await service.reviewRequests(dave, { now }))!.requests[0].movedTo).toBe(fixture.head2); expect(pullLookups()).toBe(afterMove); } finally { moveTo(fixture.head1); @@ -476,7 +532,26 @@ describe('following a pull request’s head', () => { } }); - it('keeps a row’s session when bringing it forward fails', async () => { + 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('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; @@ -484,12 +559,13 @@ describe('following a pull request’s head', () => { { 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(service, 'createSession').mockRejectedValueOnce(new Error('mirror unavailable')); + 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(warn).toHaveBeenCalledWith(expect.stringContaining('mirror unavailable')); + expect(rows[0].movedTo).toBeNull(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('database unavailable')); } finally { failing.mockRestore(); warn.mockRestore(); diff --git a/packages/ui/src/components/layout/github-dialog.tsx b/packages/ui/src/components/layout/github-dialog.tsx index d5f69eb3..36cbd701 100644 --- a/packages/ui/src/components/layout/github-dialog.tsx +++ b/packages/ui/src/components/layout/github-dialog.tsx @@ -213,6 +213,9 @@ export function GitHubDialog(props: GitHubDialogProps) { return (
e.stopPropagation()} > @@ -340,7 +343,7 @@ export function GitHubDialog(props: GitHubDialogProps) {