TypeScript
feat(web): pull request files can be marked as viewed (#7721)
Yordis Prieto03950089ffa5
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.tsindex 2cb8c61a161..06fe4c9597d 100644--- a/apps/mobile/src/features/review/reviewModel.ts+++ b/apps/mobile/src/features/review/reviewModel.ts@@ -1,6 +1,7 @@import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";+import { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";import * as Arr from "effect/Array";import { pipe } from "effect/Function";import * as Order from "effect/Order";@@ -372,8 +373,8 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender}function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {- const path = file.name || file.prevName || "";- const previousPath = file.prevName || null;+ const path = unquoteGitPatchPath(file.name || file.prevName || "");+ const previousPath = file.prevName ? unquoteGitPatchPath(file.prevName) : null;const additions = file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0);const deletions = file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0);const cacheKey = file.cacheKey ?? `${previousPath ?? "none"}:${path}:${file.type}`;diff --git a/apps/server/package.json b/apps/server/package.jsonindex e1aef0cd76f..cf0dc919e1b 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -28,6 +28,7 @@"@effect/platform-node-shared": "catalog:","@ff-labs/fff-node": "0.9.4","@opencode-ai/sdk": "^1.3.15",+ "diff": "8.0.3","effect": "catalog:","msgpackr-extract": "3.0.4","node-pty": "^1.1.0",diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 36371713a7a..b9ae42f77e7 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -76,6 +76,7 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsThreadComments]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,+ [WS_METHODS.pullRequestsFilesViewed]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsRunAction]: AuthOrchestrationOperateScope,[WS_METHODS.pullRequestsUpdate]: AuthOrchestrationOperateScope,[WS_METHODS.pullRequestsComment]: AuthOrchestrationOperateScope,@@ -84,6 +85,7 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.pullRequestsReplyToThread]: AuthOrchestrationOperateScope,[WS_METHODS.pullRequestsSetThreadResolution]: AuthOrchestrationOperateScope,[WS_METHODS.pullRequestsSetReaction]: AuthOrchestrationOperateScope,+ [WS_METHODS.pullRequestsSetFilesViewed]: AuthOrchestrationOperateScope,// Read scope like the reads it un-caches: refreshing is part of reading, and a read-only// client pressing refresh must not be told it may not look again.[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,diff --git a/apps/server/src/persistence/Errors.ts b/apps/server/src/persistence/Errors.tsindex 2715bf65a7b..4625b368d8f 100644--- a/apps/server/src/persistence/Errors.ts+++ b/apps/server/src/persistence/Errors.ts@@ -167,5 +167,6 @@ export type OrchestrationCommandReceiptRepositoryError =export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError;export type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError;export type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError;+export type PullRequestFilesViewedRepositoryError = PersistenceSqlError | PersistenceDecodeError;export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError;diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex ad015534ea0..18aae09febf 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -64,6 +64,7 @@ import Migration0049 from "./Migrations/049_ProjectionThreadsActiveOrderKey.ts";import Migration0050 from "./Migrations/050_ProjectionThreadPullRequests.ts";import Migration0051 from "./Migrations/051_ProjectionThreadMessageContext.ts";import Migration0052 from "./Migrations/052_ProjectionThreadTitleState.ts";+import Migration0053 from "./Migrations/053_PullRequestFilesViewed.ts";/*** Migration loader with all migrations defined inline.@@ -128,6 +129,7 @@ const migrationEntries = [[50, "ProjectionThreadPullRequests", Migration0050],[51, "ProjectionThreadMessageContext", Migration0051],[52, "ProjectionThreadTitleState", Migration0052],+ [53, "PullRequestFilesViewed", Migration0053],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/053_PullRequestFilesViewed.ts b/apps/server/src/persistence/Migrations/053_PullRequestFilesViewed.tsnew file mode 100644index 00000000000..5e7f67c0b18--- /dev/null+++ b/apps/server/src/persistence/Migrations/053_PullRequestFilesViewed.ts@@ -0,0 +1,25 @@+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/unstable/sql/SqlClient";++export default Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ // One row per file a reader has cleared on a host that keeps no record of its own. `revision`+ // is what the file was when it was cleared, so a push that changes it is reported as changed+ // rather than silently left ticked, and it is nullable for the reason `PullRequestFileViewedMark`+ // gives. Unticking deletes the row: absent is the resting state, and a table of "not viewed"+ // rows would grow with every diff anybody scrolled past.+ yield* sql`+ CREATE TABLE IF NOT EXISTS pull_request_files_viewed (+ provider TEXT NOT NULL,+ host TEXT NOT NULL,+ repository TEXT NOT NULL,+ number INTEGER NOT NULL,+ viewer TEXT NOT NULL,+ path TEXT NOT NULL,+ revision TEXT,+ viewed_at TEXT NOT NULL,+ PRIMARY KEY (provider, host, repository, number, viewer, path)+ ) WITHOUT ROWID+ `;+});diff --git a/apps/server/src/persistence/PullRequestFilesViewed.ts b/apps/server/src/persistence/PullRequestFilesViewed.tsnew file mode 100644index 00000000000..9904e244018--- /dev/null+++ b/apps/server/src/persistence/PullRequestFilesViewed.ts@@ -0,0 +1,184 @@+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Schema from "effect/Schema";+import * as SqlClient from "effect/unstable/sql/SqlClient";+import * as SqlSchema from "effect/unstable/sql/SqlSchema";++import { SourceControlProviderKind } from "@t3tools/contracts";++import {+ PersistenceDecodeError,+ PersistenceSqlError,+ type PullRequestFilesViewedRepositoryError,+} from "./Errors.ts";++/**+ * Which change request, on which host, for which reader. The host is part of it because the same+ * `group/project` exists on gitlab.com and on a self-managed instance, and the reader because+ * signing in as somebody else must not inherit their ticks. A host that will not say who the+ * reader is leaves it empty, which is one reader rather than none.+ */+export const PullRequestFilesViewedScope = Schema.Struct({+ provider: SourceControlProviderKind,+ host: Schema.String,+ repository: Schema.String,+ number: Schema.Int,+ viewer: Schema.String,+});+export type PullRequestFilesViewedScope = typeof PullRequestFilesViewedScope.Type;++/** A file this reader cleared, and what it was when they cleared it. */+export const PullRequestFileViewedMark = Schema.Struct({+ path: Schema.String,+ /**+ * The host's own name for that version of the file, opaque here. Empty where the host said it+ * had none to give, which is an answer rather than a gap: a file with no version at the head is+ * one the change request deletes. Null where the host could not say at all, which is no baseline+ * rather than an empty one, and such a mark stays cleared until a press replaces it.+ *+ * This null is the only one this environment invents; the other two are in+ * `docs/internals/pull-request-file-revisions.md`.+ */+ revision: Schema.NullOr(Schema.String),+});+export type PullRequestFileViewedMark = typeof PullRequestFileViewedMark.Type;++export interface SetPullRequestFilesViewedInput extends PullRequestFilesViewedScope {+ readonly files: ReadonlyArray<PullRequestFileViewedMark & { readonly viewed: boolean }>;+ /** When the presses landed, as an ISO instant. */+ readonly viewedAt: string;+}++/**+ * How many marks one read of this store carries. Every one of them is a path held in a set and a+ * map for as long as the caller holds the read, so an unbounded read of a change request with+ * thousands of marks in it is paid for again per scope the caller is holding. Matched to what the+ * GitHub reader walks in one go, past what anyone reviews in a sitting.+ */+export const MAX_FILES_VIEWED_ROWS = 500;++/** The marks for one scope, and whether the store had more of them than it carried. */+export interface PullRequestFilesViewedPage {+ readonly files: ReadonlyArray<PullRequestFileViewedMark>;+ readonly truncated: boolean;+}++/**+ * The marks this environment keeps for hosts that keep none of their own.+ *+ * Only cleared files are rows. Unticking deletes rather than writing a "not viewed" row, so the+ * table holds what a reader has done and not what they have merely scrolled past.+ */+export class PullRequestFilesViewedRepository extends Context.Service<+ PullRequestFilesViewedRepository,+ {+ readonly list: (+ input: PullRequestFilesViewedScope,+ ) => Effect.Effect<PullRequestFilesViewedPage, PullRequestFilesViewedRepositoryError>;+ readonly set: (+ input: SetPullRequestFilesViewedInput,+ ) => Effect.Effect<void, PullRequestFilesViewedRepositoryError>;+ }+>()("t3/persistence/PullRequestFilesViewed/PullRequestFilesViewedRepository") {}++function toSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {+ return (cause: unknown): PullRequestFilesViewedRepositoryError =>+ Schema.isSchemaError(cause)+ ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)+ : new PersistenceSqlError({ operation: sqlOperation, cause });+}++const make = Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ const listRows = SqlSchema.findAll({+ Request: PullRequestFilesViewedScope,+ Result: PullRequestFileViewedMark,+ execute: ({ provider, host, repository, number, viewer }) =>+ sql`+ SELECT+ path AS "path",+ revision AS "revision"+ FROM pull_request_files_viewed+ WHERE provider = ${provider}+ AND host = ${host}+ AND repository = ${repository}+ AND number = ${number}+ AND viewer = ${viewer}+ ORDER BY path+ LIMIT ${MAX_FILES_VIEWED_ROWS + 1}+ `,+ });++ return PullRequestFilesViewedRepository.of({+ // Ordered by path and read one row past the ceiling, so the same marks come back on every+ // read rather than a window that shuffles, and having more than were carried is known rather+ // than guessed at from a full page.+ list: (input) =>+ listRows(input).pipe(+ Effect.map((rows) => ({+ files: rows.slice(0, MAX_FILES_VIEWED_ROWS),+ truncated: rows.length > MAX_FILES_VIEWED_ROWS,+ })),+ Effect.mapError(toSqlOrDecodeError("listPullRequestFilesViewed", "PullRequestFileViewed")),+ ),++ // One statement per file rather than one for the batch: the batch is what a reader ticked in+ // the last few hundred milliseconds, so it is a handful of rows on a local database, and a+ // mixed batch of clears and un-clears has no single statement anyway.+ set: (input) =>+ // One transaction for the batch. A press is a handful of files, and a failure part way+ // through would otherwise leave some of them cleared and the rest not, which the reader+ // sees on the next read as marks they never made.+ sql+ .withTransaction(+ Effect.forEach(+ input.files,+ (file) =>+ file.viewed+ ? sql`+ INSERT INTO pull_request_files_viewed (+ provider,+ host,+ repository,+ number,+ viewer,+ path,+ revision,+ viewed_at+ )+ VALUES (+ ${input.provider},+ ${input.host},+ ${input.repository},+ ${input.number},+ ${input.viewer},+ ${file.path},+ ${file.revision},+ ${input.viewedAt}+ )+ ON CONFLICT (provider, host, repository, number, viewer, path)+ DO UPDATE SET revision = excluded.revision, viewed_at = excluded.viewed_at+ `+ : sql`+ DELETE FROM pull_request_files_viewed+ WHERE provider = ${input.provider}+ AND host = ${input.host}+ AND repository = ${input.repository}+ AND number = ${input.number}+ AND viewer = ${input.viewer}+ AND path = ${file.path}+ `,+ { discard: true },+ ),+ )+ .pipe(+ Effect.mapError(+ (cause) => new PersistenceSqlError({ operation: "setPullRequestFilesViewed", cause }),+ ),+ ),+ });+});++export const layer = Layer.effect(PullRequestFilesViewedRepository, make);diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.tsindex d893924b3f2..6e378c43b1b 100644--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.ts+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.ts@@ -29,6 +29,45 @@ function output(stdout: string) {};}+/** What VcsProcess allows a read that asked for no ceiling of its own. */+const VCS_DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;++/**+ * The runner as it really behaves: it cuts stdout at the ceiling its caller asked for, and cuts+ * it at the process default when the caller asked for none. A read whose response is larger than+ * its ceiling gets JSON that stops mid-string, which is the whole cost of an unset ceiling.+ */+function outputWithin(maxOutputBytes: number | undefined, response: string) {+ const ceiling = maxOutputBytes ?? VCS_DEFAULT_MAX_OUTPUT_BYTES;+ return ceiling >= Buffer.byteLength(response)+ ? output(response)+ : { ...output(response.slice(0, ceiling)), stdoutTruncated: true };+}++/** A fixture's own shape, spelled the way `az` would answer with it. */+const json = (value: Record<string, unknown>) => JSON.stringify(value);++const pullRequestRow = {+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+};++const oneIteration = {+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+};+function pullRequestRows(count: number,firstNumber: number,@@ -56,6 +95,92 @@ function argsOfCall(index: number): ReadonlyArray<string> {return call[0].args;}+/** The output ceiling the nth az invocation asked for, if it asked for one at all. */+function maxOutputBytesOfCall(index: number) {+ const call = mockedExecute.mock.calls[index];+ assert.isDefined(call);+ return call[0].maxOutputBytes;+}++/** A page of change entries the size Azure really answers with, url and object ids and all. */+function changeEntries(count: number): ReadonlyArray<Record<string, unknown>> {+ const commit = "c".repeat(40);+ return Array.from({ length: count }, (_, index) => {+ const path = `/apps/server/src/generated/module-${index}/persisted-projection-${index}.ts`;+ return {+ changeType: "edit",+ item: {+ path,+ objectId: "a".repeat(40),+ originalObjectId: "b".repeat(40),+ commitId: commit,+ gitObjectType: "blob",+ url: `https://dev.azure.com/acme/platform/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/items${path}?versionType=Commit&version=${commit}`,+ },+ };+ });+}++/** An Azure identity, which rides along with every comment and every push Azure answers with. */+function identity(name: string) {+ const id = "6f9c9b7f-0000-0000-0000-000000000000";+ return {+ displayName: name,+ id,+ uniqueName: `${name.toLowerCase().replace(/ /g, ".")}@acme.com`,+ descriptor: `aad.${"z".repeat(52)}`,+ imageUrl: `https://dev.azure.com/acme/_api/_common/identityImage?id=${id}`,+ url: `https://spsprodweu1.vssps.visualstudio.com/A${id}/_apis/Identities/${id}`,+ _links: {+ avatar: {+ href: `https://dev.azure.com/acme/_apis/GraphProfile/MemberAvatars/aad.${"z".repeat(52)}`,+ },+ },+ };+}++/** A review's threads the shape Azure answers with, system threads and identities and all. */+function threadRows(count: number): ReadonlyArray<Record<string, unknown>> {+ return Array.from({ length: count }, (_, index) => ({+ id: index + 1,+ publishedDate: "2026-07-02T00:00:00Z",+ lastUpdatedDate: "2026-07-02T00:00:00Z",+ status: "active",+ threadContext: { filePath: `/apps/server/src/generated/module-${index}.ts` },+ identities: { 1: identity("Reviewer One") },+ isDeleted: false,+ comments: [+ {+ id: 1,+ parentCommentId: 0,+ author: identity("Reviewer One"),+ content: `Comment ${index}: ${"this needs another look. ".repeat(20)}`,+ publishedDate: "2026-07-02T00:00:00Z",+ lastUpdatedDate: "2026-07-02T00:00:00Z",+ commentType: "text",+ usersLiked: [],+ },+ ],+ }));+}++/** A review's iterations the shape Azure answers with, one per push. */+function iterationRows(count: number): ReadonlyArray<Record<string, unknown>> {+ return Array.from({ length: count }, (_, index) => ({+ id: index + 1,+ description: `Pushed ${index} commits`,+ author: identity("Author One"),+ createdDate: "2026-07-02T00:00:00Z",+ updatedDate: "2026-07-02T00:00:00Z",+ sourceRefCommit: { commitId: `${index}`.padStart(40, "a") },+ targetRefCommit: { commitId: "b".repeat(40) },+ commonRefCommit: { commitId: "c".repeat(40) },+ hasMultipleCommits: true,+ reason: "push",+ push: { pushId: index + 1, date: "2026-07-02T00:00:00Z", pushedBy: identity("Author One") },+ }));+}+afterEach(() => {mockedExecute.mockReset();});@@ -107,20 +232,9 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {const response = JSON.stringify(rows);expect(Buffer.byteLength(response)).toBeGreaterThan(1_000_000);- mockedExecute.mockImplementationOnce((input) => {- const maxOutputBytes =- "maxOutputBytes" in input && typeof input.maxOutputBytes === "number"- ? input.maxOutputBytes- : 1_000_000;- return Effect.succeed(- maxOutputBytes >= Buffer.byteLength(response)- ? output(response)- : {- ...output(response.slice(0, maxOutputBytes)),- stdoutTruncated: true,- },- );- });+ mockedExecute.mockImplementationOnce((input) =>+ Effect.succeed(outputWithin(input.maxOutputBytes, response)),+ );const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;const batch = yield* cli.listPullRequests({@@ -516,6 +630,590 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {}),);+ it.effect("names the head's blob as what a cleared file was cleared at", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ {+ id: 2,+ sourceRefCommit: { commitId: "c".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ changeEntries: [+ { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },+ { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },+ ],+ }),+ ),+ ),+ );+ const provider = yield* AzureDevOpsPullRequestProvider.make;++ // Kept here rather than on Azure: its own record of what a reader has read is behind an+ // undocumented endpoint, so the marks belong to this environment and need a revision of+ // their own to tell a re-push from a file still as it was read.+ assert.strictEqual(provider.capabilities.viewedFiles, "environment");+ assert.isDefined(provider.getFileRevisions);+ const answer = yield* provider.getFileRevisions({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ paths: ["README.md"],+ });++ // The latest push, since an iteration's changes are reported against the merge base rather+ // than against the push before it.+ expect(argsOfCall(2)).toContain("iterationId=2");+ // Only what was asked for. DEMO.md changed too, and nobody has marked it.+ expect([...answer.revisions]).toEqual([["README.md", "8f80"]]);+ }),+ );++ it.effect("reads where a pull request lives once, however often it is asked about", () =>+ Effect.gen(function* () {+ // A pull request cannot move repositories, and the marks would otherwise pay for a whole+ // pull request read every time they checked whether a file had been pushed to.+ const pullRequest = Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+ }),+ ),+ );+ const iterations = () =>+ Effect.succeed(+ output(+ JSON.stringify({+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+ }),+ ),+ );+ const changes = () =>+ Effect.succeed(+ output(+ JSON.stringify({+ changeEntries: [+ { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },+ ],+ }),+ ),+ );+ mockedExecute+ .mockReturnValueOnce(pullRequest)+ .mockReturnValueOnce(iterations())+ .mockReturnValueOnce(changes())+ .mockReturnValueOnce(iterations())+ .mockReturnValueOnce(changes());+ const provider = yield* AzureDevOpsPullRequestProvider.make;+ const read = provider.getFileRevisions;+ assert.isDefined(read);+ const ask = () =>+ read({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ paths: ["README.md"],+ });++ yield* ask();+ const again = yield* ask();++ assert.strictEqual(mockedExecute.mock.calls.length, 5);+ // The second read goes straight to the pushes, and still answers with the head's blob.+ expect(argsOfCall(3)).toContain("pullRequestIterations");+ expect([...again.revisions]).toEqual([["README.md", "8f80"]]);+ }),+ );++ it.effect(+ "answers for a marked file the pull request no longer changes as the empty version",+ () =>+ Effect.gen(function* () {+ // Which is what was stored for it when it was ticked with nothing on the head, so a file+ // the pull request deletes is cleared once and stays cleared.+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(Effect.succeed(output('{"changeEntries":[]}')));+ const provider = yield* AzureDevOpsPullRequestProvider.make;+ assert.isDefined(provider.getFileRevisions);++ const answer = yield* provider.getFileRevisions({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ paths: ["GONE.md"],+ });++ expect([...answer.revisions]).toEqual([["GONE.md", ""]]);+ }),+ );++ it.effect("says nothing about the files past the end of a change it gave up following", () =>+ Effect.gen(function* () {+ // Every page is an `az` process of its own, so a change past the ceiling stops being+ // followed. A path nobody looked at must not be answered for as deleted.+ const entries = (from: number, count: number) =>+ Array.from({ length: count }, (_, index) => ({+ changeType: "edit",+ item: { path: `/src/f${from + index}.ts`, objectId: `blob-${from + index}` },+ }));+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(output(json({ changeEntries: entries(0, 5_000), nextSkip: 5_000 }))),+ )+ .mockReturnValueOnce(+ Effect.succeed(output(json({ changeEntries: entries(5_000, 5_000), nextSkip: 10_000 }))),+ );+ const provider = yield* AzureDevOpsPullRequestProvider.make;+ assert.isDefined(provider.getFileRevisions);++ const answer = yield* provider.getFileRevisions({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ paths: ["src/f1.ts", "src/f5001.ts", "src/past-the-cut.ts"],+ });++ // The second page picks up where the first said it ended.+ expect(argsOfCall(3)).toContain("$skip=5000");+ expect([...answer.revisions]).toEqual([+ ["src/f1.ts", "blob-1"],+ ["src/f5001.ts", "blob-5001"],+ ]);+ }),+ );++ it.effect("stops following pages by what Azure counts, not by what survives decoding", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+ }),+ ),+ ),+ )+ // Nothing a review can show, so every page decodes to nothing at all and a ceiling counted+ // in files would never be reached however long the walk went on.+ .mockImplementation((command) => {+ const skip = command.args.find((arg) => arg.startsWith("$skip="));+ const from = Number(skip?.slice("$skip=".length) ?? 0);+ return Effect.succeed(+ output(+ json({+ changeEntries: [{ changeType: "add", item: { path: "/src", isFolder: true } }],+ nextSkip: from + 2_000,+ }),+ ),+ );+ });+ const provider = yield* AzureDevOpsPullRequestProvider.make;+ assert.isDefined(provider.getFileRevisions);++ const answer = yield* provider.getFileRevisions({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ paths: ["src/page.ts"],+ });++ // The pull request, its pushes, and five pages: the walk gives up on Azure's own offset+ // rather than spending an `az` process a page for as long as Azure keeps paging.+ assert.strictEqual(mockedExecute.mock.calls.length, 7);+ // And it read part of a change, so it says nothing about the file it never saw.+ assert.strictEqual(answer.revisions.size, 0);+ }),+ );++ it.effect("leaves one file the host would not hand over listed without its hunks", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))+ .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ changeEntries: [+ { changeType: "add", item: { path: "/huge.bin", objectId: "8f80" } },+ { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.fail(+ new AzureDevOpsCli.AzureDevOpsCommandFailedError({+ operation: "execute",+ command: "az",+ cwd: "/w",+ argumentCount: 1,+ cause: "the blob is past what the route will carry",+ }),+ ),+ )+ .mockReturnValueOnce(Effect.succeed(output(json({ content: "hello\n" }))));+ const provider = yield* AzureDevOpsPullRequestProvider.make;++ const slice = yield* provider.getDiff({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ });++ assert.isTrue(slice.truncated);+ expect(slice.patch).toContain("diff --git a/huge.bin b/huge.bin");+ // And the file behind it still renders, which is the point of giving up on one file.+ expect(slice.patch).toContain("+hello");+ }),+ );++ it.effect("fails the whole read when it is the connection that would not answer", () =>+ Effect.gen(function* () {+ // A rate limit is not this file's problem, and answering with a change full of files listed+ // without their hunks would read as a change nobody can see rather than as a host to wait+ // for.+ mockedExecute+ .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))+ .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ changeEntries: [+ { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.fail(+ new AzureDevOpsCli.AzureDevOpsCliRateLimitError({+ operation: "execute",+ command: "az",+ cwd: "/w",+ argumentCount: 1,+ cause: "429",+ }),+ ),+ );+ const provider = yield* AzureDevOpsPullRequestProvider.make;++ const error = yield* Effect.flip(+ provider.getDiff({ cwd: "/w", repository: "web", host: "dev.azure.com", number: 42 }),+ );++ assert.strictEqual(error.reason, "rate-limited");+ }),+ );++ it.effect("takes Azure's own word on a file it will not spell out", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ changeEntries: [+ { changeType: "add", item: { path: "/logo.png", objectId: "8f80" } },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(json({ content: "iVBORw0KGgo=", contentMetadata: { isBinary: true } })),+ ),+ );+ const provider = yield* AzureDevOpsPullRequestProvider.make;++ const slice = yield* provider.getDiff({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ });++ // Azure leaves the metadata out unless it is asked for, and without it every file reads as+ // text however it was stored.+ expect(argsOfCall(3)).toContain("includeContentMetadata=true");+ expect(slice.patch).toContain("Binary files a/logo.png and b/logo.png differ");+ assert.isTrue(slice.truncated);+ }),+ );++ it.effect("stops following pages when one of them does not move the cursor on", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ pullRequestId: 42,+ title: "Add the page",+ status: "active",+ sourceRefName: "refs/heads/feat/page",+ targetRefName: "refs/heads/main",+ creationDate: "2026-07-01T00:00:00Z",+ url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",+ repository: { name: "web", project: { name: "platform" } },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "a".repeat(40) },+ commonRefCommit: { commitId: "b".repeat(40) },+ },+ ],+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ changeEntries: [{ changeType: "edit", item: { path: "/a.ts", objectId: "8f80" } }],+ nextSkip: 2_000,+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ json({+ changeEntries: [{ changeType: "edit", item: { path: "/b.ts", objectId: "0ca4" } }],+ nextSkip: 2_000,+ }),+ ),+ ),+ );+ const provider = yield* AzureDevOpsPullRequestProvider.make;+ assert.isDefined(provider.getFileRevisions);++ const answer = yield* provider.getFileRevisions({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ paths: ["a.ts", "b.ts", "unlisted.ts"],+ });++ // Four reads and no more: a page pointing at where it already is would be read forever.+ assert.strictEqual(mockedExecute.mock.calls.length, 4);+ // And what was read is not the whole change, so the file nobody listed is left unanswered+ // rather than reported as gone from the change request.+ expect([...answer.revisions]).toEqual([+ ["a.ts", "8f80"],+ ["b.ts", "0ca4"],+ ]);+ }),+ );++ it.effect("asks Azure nothing when no file has been ticked off", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValue(Effect.succeed(output('{"changeEntries":[]}')));+ const provider = yield* AzureDevOpsPullRequestProvider.make;+ assert.isDefined(provider.getFileRevisions);++ const answer = yield* provider.getFileRevisions({+ cwd: "/w",+ repository: "web",+ host: "dev.azure.com",+ number: 42,+ paths: [],+ });++ expect(answer.revisions.size).toBe(0);+ // Nothing was marked, so Azure was not asked at all.+ assert.strictEqual(mockedExecute.mock.calls.length, 0);+ }),+ );+it.effect("reads the conversation through the REST API, pinned to a version", () =>Effect.gen(function* () {mockedExecute.mockReturnValueOnce(@@ -539,14 +1237,134 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {const comments = yield* cli.listThreads({cwd: "/w",- threadsUrl: "https://dev.azure.com/acme/platform/_apis/git/r/web/pullRequests/42/threads",+ location: { project: "platform", repository: "web" },+ number: 42,});assert.strictEqual(comments.length, 1);- expect(argsOfCall(0)).toContain("rest");- expect(argsOfCall(0)).toContain(- "https://dev.azure.com/acme/platform/_apis/git/r/web/pullRequests/42/threads?api-version=7.1",+ // `az devops invoke` rather than `az rest`: it signs in the way the azure-devops extension+ // does, and `az rest` mints its own token against whichever tenant `az` defaults to.+ expect(argsOfCall(0)).toContain("invoke");+ expect(argsOfCall(0)).toContain("pullRequestThreads");+ expect(argsOfCall(0)).toContain("project=platform");+ expect(argsOfCall(0)).toContain("repositoryId=web");+ expect(argsOfCall(0)).toContain("pullRequestId=42");+ // A review's threads grow with how long it ran, and this route does not page, so the read+ // asks for more than the process default rather than taking whatever it is given.+ expect(maxOutputBytesOfCall(0)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);+ }),+ );++ it.effect("reads a long review's threads, which are past the default output limit", () =>+ Effect.gen(function* () {+ const response = json({ value: threadRows(800) });+ // Azure opens a thread per vote and per ref update beside the ones people wrote, and every+ // comment carries a full identity, so a review argued over for weeks outgrows the default.+ expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);+ mockedExecute.mockImplementationOnce((input) =>+ Effect.succeed(outputWithin(input.maxOutputBytes, response)),);+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;++ const comments = yield* cli.listThreads({+ cwd: "/w",+ location: { project: "platform", repository: "web" },+ number: 42,+ });++ assert.strictEqual(comments.length, 800);+ }),+ );++ it.effect("reads a long review's iterations, which are past the default output limit", () =>+ Effect.gen(function* () {+ const response = json({ value: iterationRows(1_200) });+ // This route does not page, so the whole history arrives at once. Cut at the default it is+ // JSON stopping mid-string, and every diff and file revision read on this host fails with+ // it, since each of them starts by asking which iteration is the latest.+ expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);+ mockedExecute.mockImplementationOnce((input) =>+ Effect.succeed(outputWithin(input.maxOutputBytes, response)),+ );+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;++ const iterations = yield* cli.listIterations({+ cwd: "/w",+ location: { project: "platform", repository: "web" },+ number: 42,+ });++ assert.strictEqual(iterations.length, 1_200);+ assert.strictEqual(iterations.at(-1)?.id, 1_200);+ }),+ );++ it.effect("reads a full page of change entries, which is past the default output limit", () =>+ Effect.gen(function* () {+ const response = json({ changeEntries: changeEntries(2_000) });+ // Azure's own maximum for this route, and every entry carries a path, a url and three+ // object ids, so an ordinary page of a large change already outgrows the default.+ expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);+ mockedExecute.mockImplementationOnce((input) =>+ Effect.succeed(outputWithin(input.maxOutputBytes, response)),+ );+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;++ const page = yield* cli.listIterationChanges({+ cwd: "/w",+ location: { project: "platform", repository: "web" },+ number: 42,+ iterationId: 1,+ });++ // Cut at the default this would arrive as JSON stopping mid-string, and a perfectly+ // ordinary page would be reported as a host answering with nonsense.+ assert.strictEqual(page.changes.length, 2_000);+ assert.isFalse(page.truncated);+ }),+ );++ it.effect("reads a file whose JSON envelope is past the default output limit", () =>+ Effect.gen(function* () {+ // Under a megabyte as bytes on the host, so this is a file the other hosts hand over.+ const file = "const value = 1;\n".repeat(57_000);+ const response = json({ content: file });+ expect(Buffer.byteLength(file)).toBeLessThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);+ // And past it once Azure wraps it, because there is no route here that serves the bytes.+ expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);+ mockedExecute.mockImplementationOnce((input) =>+ Effect.succeed(outputWithin(input.maxOutputBytes, response)),+ );+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;++ const item = yield* cli.readItemContent({+ cwd: "/w",+ location: { project: "platform", repository: "web" },+ path: "src/generated/schema.ts",+ commit: "a".repeat(40),+ });++ assert.strictEqual(item.contents, file);+ assert.isFalse(item.isBinary);+ }),+ );++ it.effect("asks for a file by Azure's own spelling of its path", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(json({ content: "const a = 1;" }))));+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;++ // The path carried around here has had Azure's leading slash taken off so it matches the+ // patch and the viewed mark. The items route is documented in Azure's spelling, so it goes+ // back on the way out rather than being sent as the shorter name.+ yield* cli.readItemContent({+ cwd: "/w",+ location: { project: "platform", repository: "web" },+ path: "src/app.ts",+ commit: "a".repeat(40),+ });++ expect(argsOfCall(0)).toContain("path=/src/app.ts");}),);diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.tsindex 91a39e8de3e..5f5453a9b3b 100644--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.ts+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.ts@@ -13,11 +13,18 @@ import type {import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";import {+ decodeItemContentJson,+ decodeIterationChangesJson,+ decodeIterationsJson,decodePullRequestJson,decodePullRequestListJson,decodeThreadsJson,decodeViewerJson,+ type AzureDevOpsChangeEntry,+ type AzureDevOpsItemContent,+ type AzureDevOpsIteration,type AzureDevOpsPullRequest,+ type AzureDevOpsRepositoryLocation,} from "./azureDevOpsPullRequestJson.ts";import type { ProviderListCursor } from "./PullRequestProvider.ts";@@ -112,6 +119,44 @@ export type AzureDevOpsPullRequestCliError =/** The version every REST call below is pinned to, so a new default cannot reshape a response. */const REST_API_VERSION = "7.1";const PULL_REQUEST_LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;+/**+ * A full page of change entries is two thousand files, each carrying its path, its url and+ * several object ids, which is past the megabyte a read is given by default. Output cut at that+ * ceiling arrives here as JSON that will not parse, so a change large enough to be paged would+ * report itself as a host returning nonsense rather than as the ordinary page it is.+ */+const CHANGE_ENTRIES_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;+/**+ * Four times the megabyte of file the other hosts hand over, because Azure has no route that+ * serves the bytes themselves: the file arrives inside a JSON envelope, escaped if it is text and+ * base64 if it is not, and both are larger than the file they carry.+ */+const ITEM_CONTENT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;+/**+ * What a review's own history is given. Neither route pages, so each answers with the whole of it+ * at once and grows with how long the review ran rather than with how large the change is. Cut at+ * the default, both arrive as JSON that stops mid-string, and a long review would report its host+ * as answering with nonsense.+ */+const REVIEW_HISTORY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;++/** Azure's own ceiling for one page of an iteration's changes. */+const CHANGE_ENTRIES_PER_PAGE = 2000;++/**+ * Where following the pages stops, counted in the entries Azure was asked to skip rather than in+ * the files that survived decoding: a page can be entirely folders and other entries a review has+ * nothing to show for, and bounding on what was kept would follow such a change forever. Every+ * page is an `az` process of its own, so the read gives up and reports itself incomplete rather+ * than presenting five pages as the whole change.+ */+const MAX_CHANGE_ENTRIES = 10_000;++/** What an iteration changed, and whether following its pages reached the end of it. */+export interface AzureDevOpsIterationChanges {+ readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;+ readonly truncated: boolean;+}export class AzureDevOpsPullRequestCli extends Context.Service<AzureDevOpsPullRequestCli,@@ -150,9 +195,42 @@ export class AzureDevOpsPullRequestCli extends Context.Service</** Threads are not reachable through `az repos pr`, so they come from the REST API. */readonly listThreads: (input: {readonly cwd: string;- readonly threadsUrl: string;+ readonly location: AzureDevOpsRepositoryLocation;+ readonly number: number;}) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>;+ /**+ * The pushes a pull request has had, oldest first. Azure hangs the changed files off an+ * iteration rather than off the pull request, so reading a diff starts here.+ */+ readonly listIterations: (input: {+ readonly cwd: string;+ readonly location: AzureDevOpsRepositoryLocation;+ readonly number: number;+ }) => Effect.Effect<ReadonlyArray<AzureDevOpsIteration>, AzureDevOpsPullRequestCliError>;++ /**+ * What one iteration changed, against the merge base rather than against the previous push,+ * which is the whole of the pull request rather than the latest slice of it.+ */+ readonly listIterationChanges: (input: {+ readonly cwd: string;+ readonly location: AzureDevOpsRepositoryLocation;+ readonly number: number;+ readonly iterationId: number;+ }) => Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError>;++ /**+ * One file's text at one commit. Azure has no diff route that carries content, so both sides+ * of every changed file are read this way and the patch is made from them here.+ */+ readonly readItemContent: (input: {+ readonly cwd: string;+ readonly location: AzureDevOpsRepositoryLocation;+ readonly path: string;+ readonly commit: string;+ }) => Effect.Effect<AzureDevOpsItemContent, AzureDevOpsPullRequestCliError>;+readonly runPullRequestAction: (input: {readonly cwd: string;readonly number: number;@@ -281,6 +359,77 @@ export const make = Effect.gen(function* () {...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),});+ /**+ * A REST route reached through `az devops invoke`, which addresses it by area, resource and+ * route parameters rather than by URL. Used in place of `az rest` because it signs in the way+ * the azure-devops extension does: `az rest` mints its own token against the tenant `az`+ * defaults to, and an organisation in any other tenant answers that with a sign-in page, which+ * arrives here as unreadable output rather than as a failure.+ */+ const invoke = <A>(input: {+ readonly cwd: string;+ readonly operation: string;+ readonly resource: string;+ readonly routeParameters: ReadonlyArray<string>;+ readonly queryParameters?: ReadonlyArray<string>;+ readonly maxOutputBytes?: number;+ readonly decode: (raw: string) => Result.Result<A, unknown>;+ }): Effect.Effect<A, AzureDevOpsPullRequestCliError> =>+ executeJson({+ cwd: input.cwd,+ ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),+ args: [+ "devops",+ "invoke",+ ...detectArgs,+ "--area",+ "git",+ "--resource",+ input.resource,+ "--api-version",+ REST_API_VERSION,+ "--route-parameters",+ ...input.routeParameters,+ ...(input.queryParameters === undefined+ ? []+ : ["--query-parameters", ...input.queryParameters]),+ ],+ }).pipe(+ Effect.flatMap((result) => {+ const decoded = input.decode(result.stdout.trim());+ return Result.isSuccess(decoded)+ ? Effect.succeed(decoded.success)+ : Effect.fail(+ new AzureDevOpsPullRequestReadError({+ command: "az",+ cwd: input.cwd,+ operation: input.operation,+ cause: decoded.failure,+ }),+ );+ }),+ );++ /**+ * Azure names its own items with a leading slash, which the repository paths carried around+ * here have had taken off so they match the patch and the viewed mark. Put it back on the way+ * out, because the items route is documented in Azure's own spelling.+ */+ const toItemPath = (path: string) => (path.startsWith("/") ? path : `/${path}`);++ const repositoryRoute = (location: AzureDevOpsRepositoryLocation): ReadonlyArray<string> => [+ `project=${location.project}`,+ `repositoryId=${location.repository}`,+ ];++ const pullRequestRoute = (input: {+ readonly location: AzureDevOpsRepositoryLocation;+ readonly number: number;+ }): ReadonlyArray<string> => [+ ...repositoryRoute(input.location),+ `pullRequestId=${input.number}`,+ ];+/*** Azure pages by raw offset. Keep reading when malformed rows leave the decoded page short, and* retain the raw count so the next public cursor skips every row this walk consumed.@@ -448,30 +597,80 @@ export const make = Effect.gen(function* () {),listThreads: (input) =>- executeJson({+ invoke({cwd: input.cwd,- args: [- "rest",- "--method",- "get",- "--url",- `${input.threadsUrl}?api-version=${REST_API_VERSION}`,+ operation: "listThreads",+ resource: "pullRequestThreads",+ routeParameters: pullRequestRoute(input),+ maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,+ decode: decodeThreadsJson,+ }),++ listIterations: (input) =>+ invoke({+ cwd: input.cwd,+ operation: "listIterations",+ resource: "pullRequestIterations",+ routeParameters: pullRequestRoute(input),+ maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,+ decode: decodeIterationsJson,+ }),++ listIterationChanges: (input) => {+ const page = (skip: number) =>+ invoke({+ cwd: input.cwd,+ operation: "listIterationChanges",+ resource: "pullRequestIterationChanges",+ routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],+ // Azure pages this route at 1000 entries by default; this is its own maximum per page,+ // and it names where the next page starts rather than answering with the whole change.+ queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],+ maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,+ decode: decodeIterationChangesJson,+ });+ const from = (+ skip: number,+ collected: ReadonlyArray<AzureDevOpsChangeEntry>,+ ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>+ page(skip).pipe(+ Effect.flatMap((answer) => {+ const changes = [...collected, ...answer.changes];+ // The last page names no page after it, and only that is the end of the change.+ if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });+ // A page pointing at where the read already is would be followed forever, and one+ // past the ceiling is a change nobody will read to the end of. Both stop the read+ // and both say so, rather than presenting part of a change as the whole of it.+ return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES+ ? Effect.succeed({ changes, truncated: true })+ : from(answer.nextSkip, changes);+ }),+ );+ return from(0, []);+ },++ readItemContent: (input) =>+ invoke({+ cwd: input.cwd,+ operation: "readItemContent",+ resource: "items",+ routeParameters: repositoryRoute(input.location),+ queryParameters: [+ `path=${toItemPath(input.path)}`,+ "versionDescriptor.versionType=commit",+ `versionDescriptor.version=${input.commit}`,+ "includeContent=true",+ // Azure leaves `contentMetadata` out unless this is asked for, and with it goes its own+ // word on whether the file is binary, which is the only reliable one, since a binary+ // file arrives encoded rather than as the bytes it is on the host.+ "includeContentMetadata=true",+ // Without this Azure answers with the file's own bytes rather than with a JSON+ // envelope, and `az devops invoke` refuses anything it cannot parse as JSON.+ "$format=json",],- }).pipe(- Effect.flatMap((result) => {- const decoded = decodeThreadsJson(result.stdout.trim());- return Result.isSuccess(decoded)- ? Effect.succeed(decoded.success)- : Effect.fail(- new AzureDevOpsPullRequestReadError({- command: "az",- cwd: input.cwd,- operation: "listThreads",- cause: decoded.failure,- }),- );- }),- ),+ maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES,+ decode: decodeItemContentJson,+ }),setPullRequestReviewers: (input) =>input.reviewers.some((reviewer) => !isReviewerName(reviewer))diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.test.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.test.tsnew file mode 100644index 00000000000..1b96984cf76--- /dev/null+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.test.ts@@ -0,0 +1,420 @@+import { describe, expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";+import {+ LOCATION_CACHE_CAPACITY,+ make,+ MAX_DIFF_SPAWNS,+} from "./AzureDevOpsPullRequestProvider.ts";+import {+ byteLength,+ MAX_DIFF_SLICE_BYTES,+ MAX_DIFF_SLICE_FILES,+ MAX_FILE_DIFF_EDITS,+ parseAzureDevOpsDiffCursor,+} from "./azureDevOpsDiff.ts";+import type { AzureDevOpsChangeEntry } from "./azureDevOpsPullRequestJson.ts";++const ITERATION = { id: 3, headCommit: "head", mergeBaseCommit: "base" };++const PULL_REQUEST = {+ number: 7,+ title: "Pull request 7",+ url: "https://dev.azure.com/acme/web/_git/web/pullrequest/7",+ author: null,+ headBranch: "feat/page",+ baseBranch: "main",+ state: "open" as const,+ isDraft: false,+ mergeability: "mergeable" as const,+ createdAt: "2026-07-01T00:00:00Z",+ updatedAt: "2026-07-02T00:00:00Z",+ closedAt: null,+ body: "",+ reviewRequestLogins: [],+ reviewers: [],+ location: { project: "acme", repository: "web" },+ autoMergeEnabled: false,+};++function change(+ path: string,+ changeKind: AzureDevOpsChangeEntry["changeKind"] = "change",+): AzureDevOpsChangeEntry {+ return { path, oldPath: path, changeKind, objectId: "8f80", originalObjectId: "0ca4" };+}++/**+ * A file whose two sides share no line, so its patch is `lines` removals and `lines` additions of+ * `width` characters each: the diff work and the patch bytes one file costs are both dialled from+ * here, and they are what a slice is bounded by. Each line carries its own number and a prefix+ * as well, so `width` is a floor on how long a line is rather than its byte count.+ */+function side(prefix: string, lines: number, width: number): string {+ const pad = "z".repeat(width);+ return `${Array.from({ length: lines }, (_, line) => `${prefix} ${line} ${pad}`).join("\n")}\n`;+}++const readSlice = (input: {+ readonly paths: ReadonlyArray<string>;+ readonly lines: number;+ readonly width: number;+ /** Paths the host refuses, which is one file's problem rather than the read's. */+ readonly refused?: ReadonlyArray<string>;+ /** Paths the change creates, so the host has nothing to hand back for their old side. */+ readonly created?: ReadonlyArray<string>;+ readonly cursor?: string;+}) =>+ Effect.gen(function* () {+ const reads: string[] = [];+ const refused = new Set(input.refused ?? []);+ const created = new Set(input.created ?? []);+ let inFlight = 0;+ let peakInFlight = 0;++ const provider = yield* make.pipe(+ Effect.provide(+ Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({+ getPullRequest: () => Effect.succeed(PULL_REQUEST),+ listIterations: () => Effect.succeed([ITERATION]),+ listIterationChanges: () =>+ Effect.succeed({+ changes: input.paths.map((path) =>+ change(path, created.has(path) ? "new" : "change"),+ ),+ truncated: false,+ }),+ readItemContent: (item) =>+ Effect.gen(function* () {+ reads.push(item.path);+ inFlight += 1;+ peakInFlight = Math.max(peakInFlight, inFlight);+ // Every read suspends before it answers, as a subprocess would, so what runs at+ // once is the scheduler's answer rather than an artefact of resolving inline. The+ // later a file is listed the sooner it answers, to leave the assembled patch+ // nothing but the change list to take its order from.+ const answersAfter = input.paths.length - input.paths.indexOf(item.path);+ for (let turn = 0; turn < answersAfter; turn += 1) yield* Effect.yieldNow;+ inFlight -= 1;+ if (refused.has(item.path)) {+ return yield* new AzureDevOpsPullRequestCli.AzureDevOpsPullRequestReadError({+ command: "az",+ cwd: "/w",+ operation: "readItemContent",+ cause: "refused",+ });+ }+ const isOldSide = item.commit !== ITERATION.headCommit;+ if (isOldSide && created.has(item.path)) return { contents: "", isBinary: false };+ return {+ contents: side(isOldSide ? "old" : "new", input.lines, input.width),+ isBinary: false,+ };+ }),+ }),+ ),+ );++ const slice = yield* provider.getDiff({+ cwd: "/w",+ repository: "acme/web",+ host: "dev.azure.com",+ number: 7,+ ...(input.cursor === undefined ? {} : { cursor: input.cursor }),+ });+ return { slice, reads, peakInFlight };+ });++/** Which files the patch carries a section for, in the order it carries them. */+function patchedPaths(patch: string): ReadonlyArray<string> {+ return [...patch.matchAll(/^diff --git a\/(?<path>\S+) b\//gmu)].map(+ (match) => match.groups?.path ?? "",+ );+}++describe("getChangeRequestSummary", () => {+ it.effect("costs the one pull request read, not the iterations changedFiles needs", () =>+ Effect.gen(function* () {+ let pullRequestReads = 0;++ const provider = yield* make.pipe(+ Effect.provide(+ // listIterations and listIterationChanges are left unimplemented here, so a summary+ // that reached for either would die with UnimplementedError instead of this passing.+ Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({+ getPullRequest: () => {+ pullRequestReads += 1;+ return Effect.succeed(PULL_REQUEST);+ },+ }),+ ),+ );++ const readSummary = provider.getChangeRequestSummary;+ if (readSummary === undefined) return yield* Effect.die("summary read was not implemented");+ const summary = yield* readSummary({+ cwd: "/w",+ repository: "acme/web",+ host: "dev.azure.com",+ number: 7,+ });++ expect(pullRequestReads).toBe(1);+ expect(summary.title).toBe(PULL_REQUEST.title);+ expect(summary.changedFiles).toBeUndefined();+ }),+ );+});++describe("getChangeRequest", () => {+ it.effect("still reports the file count the detail panel needs", () =>+ Effect.gen(function* () {+ const provider = yield* make.pipe(+ Effect.provide(+ Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({+ getPullRequest: () => Effect.succeed(PULL_REQUEST),+ listIterations: () => Effect.succeed([ITERATION]),+ listIterationChanges: () =>+ Effect.succeed({ changes: [change("a.ts"), change("b.ts")], truncated: false }),+ }),+ ),+ );++ const detail = yield* provider.getChangeRequest({+ cwd: "/w",+ repository: "acme/web",+ host: "dev.azure.com",+ number: 7,+ });++ expect(detail.changedFiles).toBe(2);+ }),+ );+});++describe("getDiff reads", () => {+ it.effect("holds every reader together to one request's worth of processes", () =>+ Effect.gen(function* () {+ // The fan-out inside a read bounds one Code tab. Two people opening two Azure reviews at+ // once are two reads, so without a ceiling above them both they are twice a request's+ // processes, each paying a Python interpreter's start-up on the same machine.+ const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"];+ let inFlight = 0;+ let peakInFlight = 0;++ const provider = yield* make.pipe(+ Effect.provide(+ Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({+ getPullRequest: () => Effect.succeed(PULL_REQUEST),+ listIterations: () => Effect.succeed([ITERATION]),+ listIterationChanges: () =>+ Effect.succeed({ changes: paths.map((path) => change(path)), truncated: false }),+ readItemContent: () =>+ Effect.gen(function* () {+ inFlight += 1;+ peakInFlight = Math.max(peakInFlight, inFlight);+ // Suspends before answering, as a subprocess would, so what is out at once is the+ // scheduler's answer rather than an artefact of resolving inline.+ yield* Effect.yieldNow;+ yield* Effect.yieldNow;+ inFlight -= 1;+ return { contents: side("new", 2, 4), isBinary: false };+ }),+ }),+ ),+ );++ const readDiff = (number: number) =>+ provider.getDiff({ cwd: "/w", repository: "acme/web", host: "dev.azure.com", number });++ yield* Effect.all([readDiff(7), readDiff(8)], { concurrency: 2 });++ expect(peakInFlight).toBeLessThanOrEqual(MAX_DIFF_SPAWNS);+ }),+ );++ it.effect("leaves a run of files it could not diff at all for the next slice", () =>+ Effect.gen(function* () {+ // A binary, oversize, purely renamed or unreadable entry is a header apiece, a couple of+ // hundred bytes with no edits in it, so a change made of them spends neither budget: the+ // byte one would take well over a thousand of them, and the edit one never fills at all.+ // A listing holds up to ten thousand entries and each still costs its two reads, which is+ // what a file count is here to bound.+ const paths = Array.from({ length: MAX_DIFF_SLICE_FILES + 20 }, (_, at) => `gen/a${at}.bin`);+ const read = yield* readSlice({ paths, lines: 2, width: 4, refused: paths });++ expect(patchedPaths(read.slice.patch)).toHaveLength(MAX_DIFF_SLICE_FILES);+ // Well inside the byte budget, so the file count is what stopped it rather than either of+ // the budgets that were already there.+ expect(byteLength(read.slice.patch)).toBeLessThan(MAX_DIFF_SLICE_BYTES);+ expect(parseAzureDevOpsDiffCursor(read.slice.nextCursor)?.fileIndex).toBe(+ MAX_DIFF_SLICE_FILES,+ );+ }),+ );++ it.effect("asks for both sides of several files at once rather than one side at a time", () =>+ Effect.gen(function* () {+ // Each file is two `az` invocations, each paying a Python interpreter's start-up, so a+ // slice read one side after another is most of what the Code tab waits for.+ const read = yield* readSlice({+ paths: ["a.ts", "b.ts", "c.ts", "d.ts"],+ lines: 2,+ width: 4,+ });++ expect(read.peakInFlight).toBeGreaterThan(2);+ }),+ );++ it.effect("holds the number of files it reads at once down", () =>+ Effect.gen(function* () {+ // The host throttles, and `az` is a process on the same machine the reader runs agents on,+ // so a long change is read in batches rather than all at once.+ const paths = Array.from({ length: 24 }, (_, file) => `file-${file}.ts`);+ const read = yield* readSlice({ paths, lines: 2, width: 4 });++ expect(read.reads).toHaveLength(paths.length * 2);+ expect(read.peakInFlight).toBeLessThanOrEqual(8);+ }),+ );++ it.effect("keeps the patch in the order the change was listed, whoever answered first", () =>+ Effect.gen(function* () {+ const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts"];+ const read = yield* readSlice({ paths, lines: 2, width: 4 });++ expect(patchedPaths(read.slice.patch)).toEqual(paths);+ expect(read.slice.nextCursor).toBeNull();+ }),+ );++ it.effect("leaves a file the host refused listed without its hunks, in its place", () =>+ Effect.gen(function* () {+ const paths = ["a.ts", "b.ts", "c.ts"];+ const read = yield* readSlice({ paths, lines: 2, width: 4, refused: ["b.ts"] });++ expect(patchedPaths(read.slice.patch)).toEqual(paths);+ expect(read.slice.truncated).toBe(true);+ // Its section ends at its header, and the files around it still carry their hunks.+ expect(read.slice.patch).toContain("+++ b/b.ts\ndiff --git a/c.ts");+ expect(read.slice.patch.match(/^@@ /gmu)).toHaveLength(2);+ }),+ );+});++describe("what one diff slice spends", () => {+ it.effect("stops on the byte ceiling without carrying what it read past it", () =>+ Effect.gen(function* () {+ // Two of these fill the slice, and the batch they were read in reached two files further.+ // Those two belong to the next slice: carrying them would put the request past a ceiling+ // that is there to bound what one answer weighs.+ const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"];+ const read = yield* readSlice({ paths, lines: 100, width: 900 });++ expect(read.slice.patch.length).toBeGreaterThan(MAX_DIFF_SLICE_BYTES);+ expect(patchedPaths(read.slice.patch)).toEqual(["a.ts", "b.ts"]);+ expect(read.slice.nextCursor).toBe(`${ITERATION.id}:2`);+ expect(new Set(read.reads)).toEqual(new Set(["a.ts", "b.ts", "c.ts", "d.ts"]));+ }),+ );++ it.effect("narrows what it reads at once as the slice fills", () =>+ Effect.gen(function* () {+ // Four files fit inside the budget and the fifth is past half of what is left of it, so+ // reading four more would throw most of them away and read them again next slice. Every+ // file is two `az` invocations, so the batch is judged against what the files before it+ // weighed rather than left at its full width to the last file.+ const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts", "g.ts", "h.ts"];+ const read = yield* readSlice({ paths, lines: 50, width: 450 });++ expect(read.slice.nextCursor).not.toBeNull();+ expect(new Set(read.reads)).toEqual(new Set(patchedPaths(read.slice.patch)));+ }),+ );++ it.effect("stops once the diff work one request may do is spent", () =>+ Effect.gen(function* () {+ // Short lines are cheap on the wire and dear to diff, so the byte ceiling alone would let+ // one request hold the thread through a dozen of them. Each of these is half of what one+ // file is allowed, and the slice ends while there is still room for another.+ const paths = Array.from({ length: 12 }, (_, file) => `file-${file}.ts`);+ const read = yield* readSlice({ paths, lines: MAX_FILE_DIFF_EDITS / 4, width: 1 });++ expect(read.slice.patch.length).toBeLessThan(MAX_DIFF_SLICE_BYTES);+ expect(patchedPaths(read.slice.patch)).toEqual(paths.slice(0, 5));+ expect(read.slice.nextCursor).toBe(`${ITERATION.id}:5`);+ }),+ );++ it.effect("carries a whole new file and stops the slice on what it weighed", () =>+ Effect.gen(function* () {+ // A creation has no edit distance to search out, so no edit bound applies to it and its+ // section is the whole file. What keeps a run of them from filling one answer is the bytes+ // they weighed, which the slice has to be charged for.+ const paths = ["new.ts", "b.ts", "c.ts", "d.ts"];+ const read = yield* readSlice({ paths, lines: 8_000, width: 30, created: ["new.ts"] });++ expect(patchedPaths(read.slice.patch)).toEqual(["new.ts"]);+ expect(read.slice.patch).toContain("--- /dev/null");+ expect(read.slice.patch).toContain("@@ -0,0 +1,8000 @@");+ expect(read.slice.patch.length).toBeGreaterThan(MAX_DIFF_SLICE_BYTES);+ expect(read.slice.nextCursor).toBe(`${ITERATION.id}:1`);+ }),+ );++ it.effect("carries on from where the last slice stopped", () =>+ Effect.gen(function* () {+ const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"];+ const read = yield* readSlice({+ paths,+ lines: 100,+ width: 900,+ cursor: `${ITERATION.id}:2`,+ });++ expect(patchedPaths(read.slice.patch)).toEqual(["c.ts", "d.ts"]);+ expect(read.slice.nextCursor).toBe(`${ITERATION.id}:4`);+ }),+ );+ it.effect("keeps the pull request being read, not the one looked up first", () =>+ Effect.gen(function* () {+ // Where a pull request lives is read from the pull request itself, so an evicted entry+ // costs a whole pull request read before any file can be asked for. Ordered by insertion+ // alone a hit does not renew its entry, so the review being worked through is the first+ // thing dropped once a listing has walked a cache's worth of cold pull requests.+ const HOT = 7;+ const readsOf = new Map<number, number>();++ const provider = yield* make.pipe(+ Effect.provide(+ Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({+ getPullRequest: (input) =>+ Effect.sync(() => {+ readsOf.set(input.number, (readsOf.get(input.number) ?? 0) + 1);+ return { ...PULL_REQUEST, number: input.number };+ }),+ listIterations: () => Effect.succeed([ITERATION]),+ listIterationChanges: () =>+ Effect.succeed({ changes: [change("a.ts")], truncated: false }),+ readItemContent: () => Effect.succeed({ contents: side("new", 2, 4), isBinary: false }),+ }),+ ),+ );++ const readDiff = (number: number) =>+ provider.getDiff({ cwd: "/w", repository: "acme/web", host: "dev.azure.com", number });++ yield* readDiff(HOT);+ // A cache's worth of cold pull requests, with the open one read in between each of them.+ for (let filled = 0; filled < LOCATION_CACHE_CAPACITY; filled += 1) {+ yield* readDiff(HOT + 1 + filled);+ yield* readDiff(HOT);+ }++ expect(readsOf.get(HOT)).toBe(1);+ }),+ );+});diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.tsindex ae586ee0a61..b194e500473 100644--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts@@ -1,21 +1,62 @@import * as Effect from "effect/Effect";+import * as Semaphore from "effect/Semaphore";import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";+import {+ azureDevOpsFilePatch,+ azureDevOpsUnreadableFilePatch,+ formatAzureDevOpsDiffCursor,+ parseAzureDevOpsDiffCursor,+ MAX_DIFF_SLICE_BYTES,+ MAX_DIFF_SLICE_EDITS,+ MAX_DIFF_SLICE_FILES,+ byteLength,+ MAX_FILE_DIFF_EDITS,+ type AzureDevOpsFileTexts,+} from "./azureDevOpsDiff.ts";import {PullRequestProviderError,type PullRequestProviderFailure,type ProviderChangeRequest,type ProviderChangeRequestActivity,type ProviderChangeRequestDetail,+ type ProviderChangeRequestSummary,+ type ProviderDiffSlice,type PullRequestProviderApi,} from "./PullRequestProvider.ts";-import type { AzureDevOpsPullRequest } from "./azureDevOpsPullRequestJson.ts";+import type { AzureDevOpsIterationChanges } from "./AzureDevOpsPullRequestCli.ts";+import type {+ AzureDevOpsChangeEntry,+ AzureDevOpsItemContent,+ AzureDevOpsIteration,+ AzureDevOpsPullRequest,+ AzureDevOpsRepositoryLocation,+} from "./azureDevOpsPullRequestJson.ts";++/**+ * How many of a slice's files are read at once. Every file is two `az` invocations, each paying a+ * Python interpreter's start-up, so reading them one after another is most of what the Code tab+ * waits for. Four files means eight processes at once: the fan-out the GitHub CLI reads its+ * per-file stats with here, and low enough not to swamp the host's throttling or the machine.+ */+const DIFF_FILE_CONCURRENCY = 4;++/**+ * How many `az` processes this build will have out at once, counted across every reader rather+ * than per request. The fan-out above bounds one Code tab, so two people opening two Azure reviews+ * had sixteen Python interpreters starting at once and nothing above them. Held at what one+ * request at full width spends, so a second reader waits behind the first instead of adding to it.+ */+export const MAX_DIFF_SPAWNS = 2 * DIFF_FILE_CONCURRENCY;++/** How many pull requests' repository locations one provider remembers at once. */+export const LOCATION_CACHE_CAPACITY = 128;const CAPABILITIES: PullRequestCapabilities = {- // `az repos pr` has no diff command, and the REST route reports changed files without their- // contents, so there is no patch to show. The Code tab is hidden rather than empty.- diff: false,+ // Azure serves no patch of its own, so the one the Code tab reads is built here out of the+ // files an iteration changed and both sides of each of them.+ diff: true,// Reading a conversation is a plain REST read, but posting one is not something this can// claim without having run it, so the composer stays hidden.comment: false,@@ -33,7 +74,8 @@ const CAPABILITIES: PullRequestCapabilities = {// `az repos pr list` filters by status, creator, reviewer and branch, and by no text at all.search: false,reactions: false,- // With no patch to show there are no lines to write against, so nothing here is offered.+ // The patch has lines to write against, but writing a remark at all is what Azure is not+ // offered for here, so nothing in a review is either.review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },// `az repos pr reviewer add` and `remove` name identities, and nothing anywhere in `az repos`// lists the ones this repository could name — that lives behind the identity and graph APIs, a@@ -44,6 +86,11 @@ const CAPABILITIES: PullRequestCapabilities = {// Rewriting a remark is false for the same reason posting one is: this cannot put a remark on// Azure DevOps at all, so there is nothing here it could rewrite either.edit: { changeRequest: true, comment: false },+ // Azure does keep a viewed record of its own, but only behind the undocumented contribution+ // endpoint its web UI talks to, keyed on an iteration so a push would drop every mark anyway.+ // So they are kept here instead, and the client says whose they are rather than implying the+ // Azure DevOps page will show them.+ viewedFiles: "environment",};/**@@ -85,8 +132,8 @@ function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeReqstate: pullRequest.state,isDraft: pullRequest.isDraft,mergeability: pullRequest.mergeability,- // Azure reports no line counts on a pull request, and with no patch to read there is- // nothing to count them from either.+ // Azure counts a pull request's files but never its lines, and counting them here would mean+ // reading every file on both sides of every row of a listing.additions: 0,deletions: 0,createdAt: pullRequest.createdAt,@@ -101,6 +148,11 @@ function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeReqexport const make = Effect.gen(function* () {const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;+ // Made once with the provider, which the registry builds once, so this is the whole build's+ // allowance rather than one request's.+ const diffSpawns = yield* Semaphore.make(MAX_DIFF_SPAWNS);+ const readItemContent = (input: Parameters<typeof cli.readItemContent>[0]) =>+ diffSpawns.withPermits(1)(cli.readItemContent(input));const fail =(operation: string) => (error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError) =>@@ -123,6 +175,123 @@ export const make = Effect.gen(function* () {}),);+ /** A pull request Azure could not place has no diff to read, which reads as an empty one. */+ const EMPTY_DIFF_SLICE: ProviderDiffSlice = { patch: "", truncated: false, nextCursor: null };++ /**+ * Where a pull request's repository lives, which is the route every other read of it needs and+ * the one thing only the pull request itself states. A pull request cannot move between+ * repositories, so it is remembered rather than re-read: the marks alone would otherwise pay for+ * a whole pull request read every time they checked whether a file had been pushed to. Least+ * recently used, so a listing walking cold pull requests cannot evict the one being read.+ */+ const locations = new Map<string, AzureDevOpsRepositoryLocation>();++ const locationOf = (input: { readonly cwd: string; readonly number: number }) => {+ const key = `${input.cwd} ${input.number}`;+ const held = locations.get(key);+ if (held !== undefined) {+ locations.delete(key);+ locations.set(key, held);+ return Effect.succeed(held);+ }+ return cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(+ Effect.map((pullRequest) => {+ const location = pullRequest.location;+ if (location === null) return null;+ if (locations.size >= LOCATION_CACHE_CAPACITY) {+ const oldest = locations.keys().next().value;+ if (oldest !== undefined) locations.delete(oldest);+ }+ locations.set(key, location);+ return location;+ }),+ );+ };++ /**+ * Everything a diff read needs before it can ask for a file: where the repository lives, and+ * which pushes the pull request has had. A client names neither, and the iterations are read+ * afresh every time because the newest one is what a push adds.+ */+ const diffScope = (input: { readonly cwd: string; readonly number: number }) =>+ Effect.gen(function* () {+ const location = yield* locationOf(input);+ if (location === null) return null;+ const iterations = yield* cli.listIterations({+ cwd: input.cwd,+ location,+ number: input.number,+ });+ return { location, iterations };+ });++ const EMPTY_ITEM: AzureDevOpsItemContent = { contents: "", isBinary: false };++ /**+ * Both sides of one changed file, read at once because neither answer depends on the other and+ * `az` pays a Python interpreter's start-up for each. Only the sides a change actually has are+ * asked for: Azure answers for a file that is not at a commit with a failure rather than with+ * nothing.+ */+ const readTexts = (input: {+ readonly cwd: string;+ readonly location: AzureDevOpsRepositoryLocation;+ readonly iteration: AzureDevOpsIteration;+ readonly change: Pick<AzureDevOpsChangeEntry, "changeKind" | "path" | "oldPath">;+ }) =>+ Effect.all(+ [+ input.change.changeKind === "new"+ ? Effect.succeed(EMPTY_ITEM)+ : readItemContent({+ cwd: input.cwd,+ location: input.location,+ path: input.change.oldPath,+ commit: input.iteration.mergeBaseCommit,+ }),+ input.change.changeKind === "deleted"+ ? Effect.succeed(EMPTY_ITEM)+ : readItemContent({+ cwd: input.cwd,+ location: input.location,+ path: input.change.path,+ commit: input.iteration.headCommit,+ }),+ ],+ { concurrency: 2 },+ ).pipe(+ Effect.map(([oldItem, newItem]): AzureDevOpsFileTexts => ({+ oldContents: oldItem.contents,+ newContents: newItem.contents,+ // Azure hands a file it calls binary over in an encoding of its own, so its own word on+ // that is taken rather than looked for in bytes it may never have sent verbatim.+ binary: oldItem.isBinary || newItem.isBinary,+ })),+ );++ /**+ * What the whole pull request changed, taken from its latest push. An iteration's changes are+ * reported against the merge base rather than against the push before it, so the newest one is+ * the whole of the change rather than the last slice of it.+ */+ const listLatestChanges = (input: {+ readonly cwd: string;+ readonly location: AzureDevOpsRepositoryLocation;+ readonly number: number;+ readonly iterations: ReadonlyArray<AzureDevOpsIteration>;+ }) => {+ const latest = input.iterations.at(-1);+ return latest === undefined+ ? Effect.succeed({ changes: [], truncated: false } as AzureDevOpsIterationChanges)+ : cli.listIterationChanges({+ cwd: input.cwd,+ location: input.location,+ number: input.number,+ iterationId: latest.id,+ });+ };+const provider: PullRequestProviderApi = {kind: "azure-devops",capabilities: CAPABILITIES,@@ -156,13 +325,52 @@ export const make = Effect.gen(function* () {})),),- getChangeRequest: (input) =>+ // The polled path a linked thread's row stays live on: one `az` read, no iterations or+ // changes behind it, since the file count that would cost is not shown here.+ getChangeRequestSummary: (input) =>cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(- Effect.mapError(fail("getChangeRequest")),- Effect.map((pullRequest): ProviderChangeRequestDetail => ({+ Effect.mapError(fail("getChangeRequestSummary")),+ Effect.map((pullRequest): ProviderChangeRequestSummary => ({+ number: pullRequest.number,+ title: pullRequest.title,+ url: pullRequest.url,+ author: pullRequest.author,+ headBranch: pullRequest.headBranch,+ baseBranch: pullRequest.baseBranch,+ state: pullRequest.state,+ isDraft: pullRequest.isDraft,+ mergeability: pullRequest.mergeability,+ closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,+ mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,+ updatedAt: pullRequest.updatedAt,+ })),+ ),++ getChangeRequest: (input) =>+ Effect.gen(function* () {+ const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });+ const location = pullRequest.location;+ // The file count is two reads past the pull request itself, and it is the only thing+ // riding on them, so a failure leaves it unknown rather than losing the whole detail.+ const changedFiles =+ location === null+ ? 0+ : yield* cli.listIterations({ cwd: input.cwd, location, number: input.number }).pipe(+ Effect.flatMap((iterations) =>+ listLatestChanges({+ cwd: input.cwd,+ location,+ number: input.number,+ iterations,+ }),+ ),+ Effect.map((listed) => listed.changes.length),+ Effect.orElseSucceed(() => 0),+ );+ const detail: ProviderChangeRequestDetail = {...toChangeRequest(pullRequest),body: pullRequest.body,- changedFiles: 0,+ changedFiles,mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,reviewers: pullRequest.reviewers,@@ -173,19 +381,26 @@ export const make = Effect.gen(function* () {...(pullRequest.autoMergeMethod === undefined? {}: { autoMergeMethod: pullRequest.autoMergeMethod }),- })),- ),+ };+ return detail;+ }).pipe(Effect.mapError(fail("getChangeRequest"))),getChangeRequestActivity: (input) =>cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(Effect.mapError(fail("getChangeRequestActivity")),Effect.flatMap((pullRequest) =>- (pullRequest.threadsUrl === null+ (pullRequest.location === null? Effect.succeed({ comments: [], truncated: true })- : cli.listThreads({ cwd: input.cwd, threadsUrl: pullRequest.threadsUrl }).pipe(- Effect.map((comments) => ({ comments, truncated: false })),- Effect.orElseSucceed(() => ({ comments: [], truncated: true })),- )+ : cli+ .listThreads({+ cwd: input.cwd,+ location: pullRequest.location,+ number: input.number,+ })+ .pipe(+ Effect.map((comments) => ({ comments, truncated: false })),+ Effect.orElseSucceed(() => ({ comments: [], truncated: true })),+ )).pipe(Effect.map((conversation): ProviderChangeRequestActivity => ({comments: conversation.comments,@@ -202,16 +417,170 @@ export const make = Effect.gen(function* () {// reach, so the answer is the same constant the detail carries.getViewerPermissions: () => Effect.succeed(AZURE_DEVOPS_VIEWER_PERMISSIONS),- // Never called: `capabilities.diff` is false, and the service refuses a diff without it.- getDiff: () =>- Effect.fail(- new PullRequestProviderError({- provider: "azure-devops",- operation: "getDiff",- reason: "failed",- detail: "Azure DevOps cannot produce a patch for a pull request.",- }),- ),+ // `input.commit` is deliberately dropped: Azure states no commit list on a pull request, so+ // the Code tab has nothing to scope itself to and always asks for the whole change.+ getDiff: (input) =>+ Effect.gen(function* () {+ const scope = yield* diffScope(input);+ if (scope === null) return EMPTY_DIFF_SLICE;+ const cursor = parseAzureDevOpsDiffCursor(input.cursor);+ // Reading on stays with the push the first slice was taken against. A push landing+ // mid-read would otherwise renumber the files and hand the reader one twice, or none.+ const iteration =+ cursor === null+ ? scope.iterations.at(-1)+ : scope.iterations.find((candidate) => candidate.id === cursor.iterationId);+ if (iteration === undefined) return EMPTY_DIFF_SLICE;+ const listed = yield* cli.listIterationChanges({+ cwd: input.cwd,+ location: scope.location,+ number: input.number,+ iterationId: iteration.id,+ });+ const changes = listed.changes;++ const sections: string[] = [];+ let truncated = listed.truncated;+ let bytes = 0;+ let edits = 0;+ let index = cursor?.fileIndex ?? 0;+ let full = false;+ // How many files to read at once. Every file costs a request a side, and everything read+ // past the point the slice fills is thrown away and read again by the next slice, so the+ // batch narrows as the budgets do: what is left of each, over what a file has spent of it+ // on average so far, which is the only estimate there is before a file is read. At least+ // one, so a file heavier than the whole budget still moves the cursor.+ const batchWidth = () => {+ if (sections.length === 0) return DIFF_FILE_CONCURRENCY;+ const admits = (left: number, spent: number) =>+ Math.ceil(left / Math.max(1, spent / sections.length));+ return Math.max(+ 1,+ Math.min(+ DIFF_FILE_CONCURRENCY,+ // The file budget needs no estimate: a file spends exactly one of it.+ MAX_DIFF_SLICE_FILES - sections.length,+ admits(MAX_DIFF_SLICE_BYTES - bytes, bytes),+ admits(MAX_DIFF_SLICE_EDITS - MAX_FILE_DIFF_EDITS - edits, edits),+ ),+ );+ };+ while (!full && index < changes.length) {+ const batch = changes.slice(index, index + batchWidth());+ const read = yield* Effect.forEach(+ batch,+ (change) =>+ // A pair Azure refuses is one file rather than the whole slice: an oversize blob or+ // a path `az` will not carry through leaves that file listed without its hunks, and+ // everything around it still renders.+ readTexts({ cwd: input.cwd, location: scope.location, iteration, change }).pipe(+ // Only what is this one file's problem. A signed-out CLI, a rate limit or no `az`+ // at all is the read failing rather than the file, and belongs to the caller,+ // which pauses the host rather than showing every file as unreadable.+ Effect.catchTags({+ AzureDevOpsPullRequestNotFoundError: () => Effect.succeed(null),+ AzureDevOpsCommandFailedError: () => Effect.succeed(null),+ AzureDevOpsPullRequestReadError: () => Effect.succeed(null),+ }),+ Effect.map((texts) => ({ change, texts })),+ ),+ { concurrency: DIFF_FILE_CONCURRENCY },+ );+ for (const { change, texts } of read) {+ // The diff is synchronous and the reads no longer stand between one file and the next+ // to let anything else on the server run, so the thread is handed back here.+ yield* Effect.yieldNow;+ const file =+ texts === null+ ? azureDevOpsUnreadableFilePatch(change)+ : azureDevOpsFilePatch({ change, texts });+ sections.push(file.section);+ bytes += byteLength(file.section);+ edits += file.edits;+ truncated = truncated || file.truncated;+ index += 1;+ // A file whose diff was given up on spent the whole of what one file is allowed and+ // has only a header to show for it, and a file the diff never ran on at all weighs+ // almost nothing in either budget and still costs its two reads. So the file count+ // bounds the request alongside the bytes.+ // Checked after the file is added rather than before it, so every slice carries at+ // least one: a section heavier than the whole budget would otherwise never be added,+ // and the read would answer the same slice forever without moving the cursor.+ if (+ bytes >= MAX_DIFF_SLICE_BYTES ||+ edits + MAX_FILE_DIFF_EDITS > MAX_DIFF_SLICE_EDITS ||+ sections.length >= MAX_DIFF_SLICE_FILES ||+ file.abandoned+ ) {+ full = true;+ break;+ }+ }+ }++ const slice: ProviderDiffSlice = {+ patch: sections.join(""),+ truncated,+ nextCursor:+ index >= changes.length+ ? null+ : formatAzureDevOpsDiffCursor({ iterationId: iteration.id, fileIndex: index }),+ };+ return slice;+ }).pipe(Effect.mapError(fail("getDiff"))),++ // The patch is built from whole files, so opening the lines around a hunk is the same two+ // reads over again rather than a wider request. Read against the latest iteration: nothing in+ // the request says which push the reader is looking at, and expansion is stale after a+ // mid-review push on every host here anyway.+ getDiffFileContents: (input) =>+ Effect.gen(function* () {+ const scope = yield* diffScope(input);+ const iteration = scope?.iterations.at(-1);+ if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };+ return yield* readTexts({+ cwd: input.cwd,+ location: scope.location,+ iteration,+ change: {+ changeKind: input.changeType,+ path: input.newPath,+ oldPath: input.oldPath,+ },+ });+ }).pipe(Effect.mapError(fail("getDiffFileContents"))),++ /**+ * What the head has of each marked file, which is the blob Azure already names on the change+ * it reports. One read covers every path, since the latest iteration lists the whole change.+ *+ * A path the change does not carry is at the empty revision, which is where a file the pull+ * request deletes sits. When the change was too long to follow to its end, those paths are+ * left out instead: reporting them as deleted would clear a file nobody has read.+ */+ getFileRevisions: (input) =>+ Effect.gen(function* () {+ const revisions = new Map<string, string>();+ if (input.paths.length === 0) return { revisions };+ const scope = yield* diffScope(input);+ if (scope === null) return { revisions };+ const listed = yield* listLatestChanges({+ ...scope,+ cwd: input.cwd,+ number: input.number,+ });+ const marked = new Set(input.paths);+ for (const change of listed.changes) {+ if (!marked.has(change.path) || change.objectId === null) continue;+ revisions.set(change.path, change.objectId);+ }+ if (!listed.truncated) {+ for (const path of input.paths) {+ if (!revisions.has(path)) revisions.set(path, "");+ }+ }+ return { revisions };+ }).pipe(Effect.mapError(fail("getFileRevisions"))),runAction: (input) =>clidiff --git a/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts b/apps/server/src/pullRequest/BitbucketPullRequestApi.test.tsindex 8945ecc5e1e..49cdaa90f7d 100644--- a/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts+++ b/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts@@ -1,6 +1,8 @@import { afterEach, assert, expect, it, vi } from "@effect/vitest";+import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as TestClock from "effect/testing/TestClock";import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";@@ -362,6 +364,159 @@ layer("BitbucketPullRequestApi.layer", (it) => {}),);+ it.effect("reads every file version the patch states, not only the paths asked about", () =>+ Effect.gen(function* () {+ mockedRequest.mockReturnValueOnce(+ Effect.succeed(+ response(+ [+ "diff --git a/a.ts b/a.ts",+ "index 1111111..2222222 100644",+ "--- a/a.ts",+ "+++ b/a.ts",+ "@@ -1 +1 @@",+ "-a",+ "+b",+ "diff --git a/b.ts b/b.ts",+ "index 3333333..4444444 100644",+ "--- a/b.ts",+ "+++ b/b.ts",+ "@@ -1 +1 @@",+ "-c",+ "+d",+ "",+ ].join("\n"),+ ),+ ),+ );+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;++ const revisions = yield* api.getFileRevisions({+ repository: "acme/web",+ number: 71,+ paths: ["a.ts", "missing.ts"],+ });++ // `b.ts` was not asked about and is reported anyway: parsing the patch for `a.ts` read it+ // too, and the caller holding it is what stops the next tick paying for the patch again.+ // `missing.ts` was asked about and the whole patch was read without finding it, which is+ // what a file this pull request deletes looks like, so it is answered as the empty version.+ assert.deepStrictEqual(+ [...revisions.revisions],+ [+ ["a.ts", "2222222"],+ ["b.ts", "4444444"],+ ["missing.ts", ""],+ ],+ );+ assert.strictEqual(revisions.complete, true);+ expect(callAt(0)).toMatchObject({ url: "/repositories/acme/web/pullrequests/71/diff" });+ }),+ );++ it.effect("says nothing about the files past the end of a patch it could not read whole", () =>+ Effect.gen(function* () {+ // Bitbucket's patch is read up to a byte ceiling, and a file past the cut was not looked at.+ // Answering for it as deleted would clear a mark on it once and for good.+ mockedRequest.mockReturnValueOnce(+ Effect.succeed({+ body: "diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n",+ truncated: true,+ }),+ );+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;++ const revisions = yield* api.getFileRevisions({+ repository: "acme/web",+ number: 72,+ paths: ["a.ts", "past-the-cut.ts"],+ });++ assert.deepStrictEqual([...revisions.revisions], [["a.ts", "2222222"]]);+ // `past-the-cut.ts` gets no empty version, and nothing here may be held as the whole story.+ assert.strictEqual(revisions.complete, false);+ }),+ );++ it.effect("reads the patch once for a run of ticks, not once a tick", () =>+ Effect.gen(function* () {+ mockedRequest.mockReturnValue(+ Effect.succeed(+ response(+ [+ "diff --git a/a.ts b/a.ts",+ "index 1111111..2222222 100644",+ "@@ -1 +1 @@",+ "diff --git a/b.ts b/b.ts",+ "index 3333333..4444444 100644",+ "@@ -1 +1 @@",+ "",+ ].join("\n"),+ ),+ ),+ );+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;++ const first = yield* api.getFileRevisions({+ repository: "acme/web",+ number: 74,+ paths: ["a.ts"],+ });+ // A path nobody has asked about before, which is what every tick after the first names.+ const second = yield* api.getFileRevisions({+ repository: "acme/web",+ number: 74,+ paths: ["b.ts"],+ });++ const both = [+ ["a.ts", "2222222"],+ ["b.ts", "4444444"],+ ];+ assert.deepStrictEqual([...first.revisions], both);+ assert.deepStrictEqual([...second.revisions], both);+ assert.strictEqual(mockedRequest.mock.calls.length, 1);+ }),+ );++ it.effect("reads the patch afresh once the one it held has aged out", () =>+ Effect.gen(function* () {+ mockedRequest.mockReturnValue(+ Effect.succeed(+ response("diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n"),+ ),+ );+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;+ const read = () =>+ api.getFileRevisions({ repository: "acme/web", number: 75, paths: ["a.ts"] });++ yield* read();+ yield* read();+ assert.strictEqual(mockedRequest.mock.calls.length, 1);++ // Well inside the window the caller holds versions for: a refresh drops what it holds so+ // that the read after it reaches Bitbucket, and this must not answer that read instead.+ yield* TestClock.adjust(Duration.seconds(30));+ yield* read();+ assert.strictEqual(mockedRequest.mock.calls.length, 2);+ }),+ );++ it.effect("asks Bitbucket nothing when no file has been ticked off", () =>+ Effect.gen(function* () {+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;++ const revisions = yield* api.getFileRevisions({+ repository: "acme/web",+ number: 73,+ paths: [],+ });++ assert.strictEqual(revisions.revisions.size, 0);+ assert.strictEqual(mockedRequest.mock.calls.length, 0);+ }),+ );+it.effect("aggregates every diffstat page", () =>Effect.gen(function* () {const next = "https://api.bitbucket.org/2.0/diffstat?page=2";diff --git a/apps/server/src/pullRequest/BitbucketPullRequestApi.ts b/apps/server/src/pullRequest/BitbucketPullRequestApi.tsindex 632f0d9a550..c7d017071fc 100644--- a/apps/server/src/pullRequest/BitbucketPullRequestApi.ts+++ b/apps/server/src/pullRequest/BitbucketPullRequestApi.ts@@ -1,5 +1,8 @@+import * as Cache from "effect/Cache";import * as Context from "effect/Context";+import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";+import * as Exit from "effect/Exit";import * as Layer from "effect/Layer";import * as Result from "effect/Result";import * as Schema from "effect/Schema";@@ -19,6 +22,7 @@ import type {} from "@t3tools/contracts";import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";+import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";import {buildReviewThreads,decodeCommentsJson,@@ -135,7 +139,13 @@ const CONVERSATION_PAGE_SIZE = 50;const CONVERSATION_PAGES = 10;/** The same ceiling the gh and glab diff reads use. */const DIFF_MAX_BYTES = 8 * 1024 * 1024;-+/**+ * Deliberately far shorter than the window the caller holds versions for: a refresh drops what the+ * caller holds precisely so the next read reaches Bitbucket, and this must not be what answers it+ * instead.+ */+const REVISION_PATCH_TTL = Duration.seconds(5);+const REVISION_PATCH_CAPACITY = 16;export interface BitbucketPullRequestBatch {readonly items: ReadonlyArray<BitbucketPullRequest>;readonly truncated: boolean;@@ -182,6 +192,25 @@ export class BitbucketPullRequestApi extends Context.Service<readonly number: number;}) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;+ /**+ * What the pull request's head has of each of these paths, as opaque ids, read off the pull+ * request's own patch, the only place Bitbucket states a file's version. A path the patch does+ * not carry is answered as the empty revision, and left out altogether when the patch was cut+ * short at the byte ceiling and so cannot be spoken for.+ *+ * Answers with every file the patch carries rather than only the paths asked about, since+ * reading one file's version here means parsing all of them. `complete` is false for a patch+ * cut short, which cannot speak for what came after the cut.+ */+ readonly getFileRevisions: (input: {+ readonly repository: string;+ readonly number: number;+ readonly paths: ReadonlyArray<string>;+ }) => Effect.Effect<+ { readonly revisions: ReadonlyMap<string, string>; readonly complete: boolean },+ BitbucketPullRequestApiError+ >;+readonly getMergeability: (input: {readonly repository: string;readonly number: number;@@ -525,6 +554,58 @@ export const make = Effect.gen(function* () {}),);+ const pullRequestDiff = (input: {+ readonly repository: string;+ readonly number: number;+ readonly commit?: string | undefined;+ }): Effect.Effect<+ { readonly patch: string; readonly truncated: boolean },+ BitbucketPullRequestApiError+ > =>+ input.commit !== undefined && !isCommitSha(input.commit)+ ? Effect.fail(new BitbucketDiffCommitError())+ : withRepository(input.repository, (path) =>+ // Already a unified patch, so it needs no decoding at all, only a bound, which a+ // diff of any size would otherwise ignore. A commit's own patch sits beside the pull+ // request's at `/diff/{sha}` and reads the same way.+ bitbucket+ .request({+ method: "GET",+ url:+ input.commit === undefined+ ? `${path}/pullrequests/${input.number}/diff`+ : `${path}/diff/${input.commit}`,+ maxBytes: DIFF_MAX_BYTES,+ })+ .pipe(+ Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),+ ),+ );++ /**+ * What the version reads that come one tick at a time want out of the pull request's whole+ * patch, shared between them. The parsed answer rather than the patch, which at this capacity+ * would hold sixteen bodies of up to the byte ceiling each resident, and saves walking a patch+ * of a hundred thousand lines again on every tick.+ */+ const revisionPatches = yield* Cache.makeWith(+ (key: string) => {+ const [repository, number] = JSON.parse(key) as [string, number];+ return pullRequestDiff({ repository, number }).pipe(+ Effect.map((diff) => ({+ revisions: parseDiffFileRevisions(diff.patch),+ truncated: diff.truncated,+ })),+ );+ },+ {+ capacity: REVISION_PATCH_CAPACITY,+ // A failure is not held: the tick after it should reach Bitbucket rather than be handed the+ // same error for as long as a good patch would have lasted.+ timeToLive: (exit) => (Exit.isSuccess(exit) ? REVISION_PATCH_TTL : Duration.zero),+ },+ );+return BitbucketPullRequestApi.of({getViewer: () =>bitbucket.request({ method: "GET", url: "/user" }).pipe(@@ -596,25 +677,23 @@ export const make = Effect.gen(function* () {}),).pipe(Effect.catchIf(isRepositoryPermissionRemovedError, () => Effect.succeed(true))),- getPullRequestDiff: (input) =>- input.commit !== undefined && !isCommitSha(input.commit)- ? Effect.fail(new BitbucketDiffCommitError())- : withRepository(input.repository, (path) =>- // Already a unified patch, so it needs no decoding at all — only a bound, which a- // diff of any size would otherwise ignore. A commit's own patch sits beside the pull- // request's at `/diff/{sha}` and reads the same way.- bitbucket- .request({- method: "GET",- url:- input.commit === undefined- ? `${path}/pullrequests/${input.number}/diff`- : `${path}/diff/${input.commit}`,- maxBytes: DIFF_MAX_BYTES,- })- .pipe(- Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),- ),+ getPullRequestDiff: pullRequestDiff,++ getFileRevisions: (input) =>+ input.paths.length === 0+ ? Effect.succeed({ revisions: new Map(), complete: false })+ : Cache.get(revisionPatches, JSON.stringify([input.repository, input.number])).pipe(+ Effect.map((diff) => {+ const revisions = new Map(diff.revisions);+ // A patch cut short at the byte ceiling says nothing about the files past the cut,+ // so those paths are left out rather than reported as removed.+ if (!diff.truncated) {+ for (const path of input.paths) {+ if (!revisions.has(path)) revisions.set(path, "");+ }+ }+ return { revisions, complete: !diff.truncated };+ }),),getDiffStat: (input) =>diff --git a/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts b/apps/server/src/pullRequest/BitbucketPullRequestProvider.tsindex 3b5b93d11c4..b9fe9d669f4 100644--- a/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts+++ b/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts@@ -31,6 +31,11 @@ const CAPABILITIES: PullRequestCapabilities = {},reviewers: { request: true, listCandidates: true },edit: { changeRequest: true, comment: true },+ // Bitbucket Cloud states nothing about what a reviewer has already read: no endpoint carries a+ // viewed file, and the per-pull-request properties it does offer are one value shared by+ // everyone rather than one per reader. So the marks are kept here, and the client says whose+ // they are rather than implying bitbucket.org will show them.+ viewedFiles: "environment",};/**@@ -234,6 +239,15 @@ export const make = Effect.gen(function* () {Effect.map((diff) => ({ ...diff, nextCursor: null })),),+ getFileRevisions: (input) =>+ api+ .getFileRevisions({+ repository: input.repository,+ number: input.number,+ paths: input.paths,+ })+ .pipe(Effect.mapError(fail("getFileRevisions"))),+// Users only: Bitbucket requests a review of an account, and has no group that stands in for// one on a pull request.listReviewerCandidates: (input) =>diff --git a/apps/server/src/pullRequest/ForgejoPullRequestProvider.ts b/apps/server/src/pullRequest/ForgejoPullRequestProvider.tsindex 526be38f7df..fddedbf6059 100644--- a/apps/server/src/pullRequest/ForgejoPullRequestProvider.ts+++ b/apps/server/src/pullRequest/ForgejoPullRequestProvider.ts@@ -4,6 +4,7 @@ import * as Result from "effect/Result";import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";import { decodeJsonResult } from "@t3tools/shared/schemaJson";import { ForgejoCli, type ForgejoApiInput } from "../sourceControl/ForgejoCli.ts";+import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";import {PullRequestProviderError,type ProviderChangeRequestDetail,@@ -34,6 +35,7 @@ import {const CAPABILITIES: PullRequestCapabilities = {diff: true,+ viewedFiles: "environment",comment: true,actions: ["merge", "close", "reopen", "update-branch"],mergeMethods: ["merge", "squash", "rebase"],@@ -347,6 +349,17 @@ export const make = Effect.gen(function* () {};},),+ getFileRevisions: Effect.fn("ForgejoPullRequestProvider.getFileRevisions")(function* (input) {+ const result = yield* request({ ...input, path: `${pullPath(input)}.diff` });+ if (result.stdoutTruncated) {+ return yield* failure("getFileRevisions", "Forgejo diff exceeded the output limit.");+ }+ const revisions = new Map(parseDiffFileRevisions(result.stdout));+ for (const path of input.paths) {+ if (!revisions.has(path)) revisions.set(path, "");+ }+ return { revisions, complete: true };+ }),getDiff: (input) =>request({...input,diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.test.tsindex 2f90c5b7955..23c14da3b48 100644--- a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts@@ -2838,11 +2838,12 @@ layer("GitHubPullRequestCli.layer", (it) => {mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;+ // Its own pull request: a node id looked up once is remembered for the life of the service.yield* cli.setReaction({cwd: "/w",repository: "acme/web",host: "github.com",- number: 7,+ number: 21,content: "rocket",reacted: true,});@@ -2851,7 +2852,7 @@ layer("GitHubPullRequestCli.layer", (it) => {const lookup = callAt(0).args;expect(lookup).toContain("owner=acme");expect(lookup).toContain("name=web");- expect(lookup).toContain("number=7");+ expect(lookup).toContain("number=21");// @effect-diagnostics-next-line preferSchemaOverJson:offconst request = JSON.parse(callAt(1).stdin ?? "") as {query: string;@@ -2912,7 +2913,7 @@ layer("GitHubPullRequestCli.layer", (it) => {cwd: "/w",repository: "acme/web",host: "github.com",- number: 7,+ number: 22,...fields,});@@ -2920,21 +2921,21 @@ layer("GitHubPullRequestCli.layer", (it) => {yield* rewrite({ body: "A better description." });yield* rewrite({ title: "Both", body: "at once." });- // Each rewrite looks the pull request's node id up first, then mutates.+ // One node id lookup for the pull request, then a mutation per rewrite.const variablesAt = (index: number) =>(JSON.parse(callAt(index).stdin ?? "") as { variables: Record<string, string> }).variables;expect(variablesAt(1)).toEqual({ pullRequestId: "PR_kwDOA", title: "A better title" });- expect(variablesAt(3)).toEqual({+ expect(variablesAt(2)).toEqual({pullRequestId: "PR_kwDOA",body: "A better description.",});- expect(variablesAt(5)).toEqual({+ expect(variablesAt(3)).toEqual({pullRequestId: "PR_kwDOA",title: "Both",body: "at once.",});// The reader's own words, so they travel the way every other body does.- expect(callAt(5).args.join(" ")).not.toContain("at once.");+ expect(callAt(3).args.join(" ")).not.toContain("at once.");}),);@@ -3655,4 +3656,252 @@ layer("GitHubPullRequestCli.layer", (it) => {expect(callAt(1).args).toContain("repos/acme/web/issues/7/labels/area%2Fweb");}),);++ it.effect("reads every page of viewed files, and says so when there are too many", () =>+ Effect.gen(function* () {+ const page = (index: number, hasNextPage: boolean) =>+ Effect.succeed(+ output(+ JSON.stringify({+ data: {+ repository: {+ pullRequest: {+ files: {+ pageInfo: { hasNextPage, endCursor: `cursor-${index}` },+ nodes: [+ { path: `src/file${index}.ts`, viewerViewedState: "VIEWED" },+ { path: `src/other${index}.ts`, viewerViewedState: "UNVIEWED" },+ ],+ },+ },+ },+ },+ }),+ ),+ );+ mockedExecute+ .mockReturnValueOnce(page(0, true))+ .mockReturnValueOnce(page(1, true))+ .mockReturnValueOnce(page(2, false));+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ const viewed = yield* cli.getPullRequestFilesViewed({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ });++ assert.strictEqual(mockedExecute.mock.calls.length, 3);+ // The first page asks from the start; each one after it carries the cursor before it.+ assert.isFalse(callAt(0).args.some((arg) => arg.startsWith("after=")));+ expect(callAt(1).args).toContain("after=cursor-0");+ expect(callAt(2).args).toContain("after=cursor-1");+ assert.isFalse(viewed.truncated);+ expect(viewed.files.map((file) => [file.path, file.state])).toEqual([+ ["src/file0.ts", "viewed"],+ ["src/other0.ts", "unviewed"],+ ["src/file1.ts", "viewed"],+ ["src/other1.ts", "unviewed"],+ ["src/file2.ts", "viewed"],+ ["src/other2.ts", "unviewed"],+ ]);+ }),+ );++ it.effect("stops paging viewed files rather than following a change without end", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValue(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ data: {+ repository: {+ pullRequest: {+ files: {+ pageInfo: { hasNextPage: true, endCursor: "cursor" },+ nodes: [{ path: "src/file.ts", viewerViewedState: "VIEWED" }],+ },+ },+ },+ },+ }),+ ),+ ),+ );+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ const viewed = yield* cli.getPullRequestFilesViewed({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ });++ assert.strictEqual(mockedExecute.mock.calls.length, 5);+ assert.isTrue(viewed.truncated);+ assert.strictEqual(viewed.files.length, 5);+ }),+ );++ it.effect("clears and restores a burst of files in one request", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ output(JSON.stringify({ data: { repository: { pullRequest: { id: "PR_1" } } } })),+ ),+ )+ .mockReturnValueOnce(Effect.succeed(output("{}")));+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ yield* cli.setPullRequestFilesViewed({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 23,+ files: [+ { path: "src/a.ts", viewed: true },+ { path: "src/b.ts", viewed: false },+ ],+ });++ // One request to learn the pull request's node id, one for every press together.+ assert.strictEqual(mockedExecute.mock.calls.length, 2);+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ const sent = JSON.parse(callAt(1).stdin ?? "") as {+ query: string;+ variables: Record<string, string>;+ };+ expect(sent.query).toContain("f0: markFileAsViewed");+ expect(sent.query).toContain("f1: unmarkFileAsViewed");+ expect(sent.variables).toEqual({+ pullRequestId: "PR_1",+ path0: "src/a.ts",+ path1: "src/b.ts",+ });+ }),+ );++ it.effect("asks the host nothing when nothing was pressed", () =>+ Effect.gen(function* () {+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ yield* cli.setPullRequestFilesViewed({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ files: [],+ });++ assert.strictEqual(mockedExecute.mock.calls.length, 0);+ }),+ );++ it.effect("looks a pull request's node id up once, however often it is written to", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ output(JSON.stringify({ data: { repository: { pullRequest: { id: "PR_24" } } } })),+ ),+ )+ .mockReturnValue(Effect.succeed(output("{}")));+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;+ const pullRequest = { cwd: "/w", repository: "acme/web", host: "github.com", number: 24 };++ yield* cli.setPullRequestFilesViewed({+ ...pullRequest,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ yield* cli.setPullRequestFilesViewed({+ ...pullRequest,+ files: [{ path: "src/b.ts", viewed: true }],+ });+ yield* cli.updatePullRequest({ ...pullRequest, title: "Ticked through" });++ // One lookup, then a mutation per write, every one of them addressed by the id it answered.+ assert.strictEqual(mockedExecute.mock.calls.length, 4);+ expect(callAt(0).args).toContain("number=24");+ const idSentAt = (index: number) =>+ (JSON.parse(callAt(index).stdin ?? "") as { variables: { pullRequestId: string } })+ .variables.pullRequestId;+ expect([idSentAt(1), idSentAt(2), idSentAt(3)]).toEqual(["PR_24", "PR_24", "PR_24"]);+ }),+ );++ it.effect("does not remember a node id lookup that failed", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(Effect.succeed(output('{"message":"not found"}')))+ .mockReturnValueOnce(+ Effect.succeed(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ output(JSON.stringify({ data: { repository: { pullRequest: { id: "PR_25" } } } })),+ ),+ )+ .mockReturnValueOnce(Effect.succeed(output("{}")));+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;+ const write = () =>+ cli.setPullRequestFilesViewed({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 25,+ files: [{ path: "src/a.ts", viewed: true }],+ });++ const error = yield* Effect.flip(write());+ assert.strictEqual(error._tag, "GitHubPullRequestReadError");++ yield* write();++ assert.strictEqual(mockedExecute.mock.calls.length, 3);+ const idSentAt = (index: number) =>+ (JSON.parse(callAt(index).stdin ?? "") as { variables: { pullRequestId: string } })+ .variables.pullRequestId;+ expect(idSentAt(2)).toEqual("PR_25");+ }),+ );+ it.effect("keeps the pull request being ticked through, not the one looked up first", () =>+ Effect.gen(function* () {+ // Ordered by insertion alone, a hit does not renew its entry, so the review the reader is+ // working down is the first thing evicted once a listing has walked a cache's worth of cold+ // pull requests, and every press after that pays a round trip again.+ // This block shares one cache, so these numbers are its own and it runs last.+ const HOT = 9_000;+ const lookupsOf = new Map<number, number>();+ mockedExecute.mockImplementation((input) => {+ const asked = input.args.find((arg) => arg.startsWith("number="));+ if (asked === undefined) return Effect.succeed(output("{}"));+ const number = Number(asked.slice("number=".length));+ lookupsOf.set(number, (lookupsOf.get(number) ?? 0) + 1);+ return Effect.succeed(+ output(encodeJson({ data: { repository: { pullRequest: { id: `PR_${number}` } } } })),+ );+ });+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;+ const tick = (number: number) =>+ cli.setPullRequestFilesViewed({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number,+ files: [{ path: "src/a.ts", viewed: true }],+ });++ yield* tick(HOT);+ // A cache's worth of cold pull requests, with the open one pressed in between each of them.+ for (let filled = 0; filled < GitHubPullRequestCli.NODE_ID_CACHE_CAPACITY; filled += 1) {+ yield* tick(HOT + 1 + filled);+ yield* tick(HOT);+ }++ assert.strictEqual(lookupsOf.get(HOT), 1);+ }),+ );});diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.tsindex 4bb86401d8e..d68d77c38f6 100644--- a/apps/server/src/pullRequest/GitHubPullRequestCli.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.ts@@ -15,6 +15,7 @@ import {type PullRequestAction,type PullRequestStackHead,type PullRequestActor,+ type PullRequestFileViewed,type PullRequestInvolvement,type PullRequestListFilters,type PullRequestListState,@@ -39,10 +40,12 @@ import {ADD_REACTION_GRAPHQL_MUTATION,buildReviewSubmissionJson,buildReviewerRequestJson,+ buildSetFilesViewedGraphQlMutation,decodeActorAvatarsJson,decodePullRequestActivityJson,decodePullRequestDetailJson,decodePullRequestFilesJson,+ decodePullRequestFilesViewedJson,decodePullRequestHeadsJson,decodePullRequestListJson,decodePullRequestNodeIdJson,@@ -69,6 +72,7 @@ import {decodeBaseComparisonJson,PULL_REQUEST_DETAIL_JSON_FIELDS,PULL_REQUEST_LIST_JSON_FIELDS,+ PULL_REQUEST_FILES_VIEWED_GRAPHQL_QUERY,PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,REMOVE_REACTION_GRAPHQL_MUTATION,@@ -371,6 +375,19 @@ const PULL_REQUEST_FALLBACK_MAX_ROWS = 1_000;/** What the files API serves at most in one response, which is what one slice is made of. */const DIFF_FILES_PAGE_SIZE = 100;+/**+ * How many hundred-file pages of viewed state one read will walk. A point of the hourly GraphQL+ * budget per page, against a change request nobody reviews in one sitting past the first few+ * hundred files: beyond this the read stops and says it was cut short.+ */+const FILES_VIEWED_MAX_PAGES = 5;++/**+ * How many pull requests' node ids are remembered at once. A long-lived server sees far more of+ * them than a reader ever has open, and least recently used rather than first in: a listing+ * walking cold pull requests must not evict the review being ticked through.+ */+export const NODE_ID_CACHE_CAPACITY = 128;/*** Pages of review threads to follow before the conversation is reported as truncated. GitHub@@ -416,6 +433,12 @@ export interface GitHubPullRequestDiffSlice {readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;}+export interface GitHubPullRequestFilesViewed {+ readonly files: ReadonlyArray<PullRequestFileViewed>;+ /** GitHub had more files than the page budget below would read. */+ readonly truncated: boolean;+}+export class GitHubPullRequestCli extends Context.Service<GitHubPullRequestCli,{@@ -569,6 +592,29 @@ export class GitHubPullRequestCli extends Context.Service<GitHubPullRequestCliError>;+ /**+ * Which files of the pull request the signed-in account has cleared, and which of those have+ * been pushed to since. Read apart from the patch because GitHub only reports it over GraphQL.+ */+ readonly getPullRequestFilesViewed: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly number: number;+ }) => Effect.Effect<GitHubPullRequestFilesViewed, GitHubPullRequestCliError>;++ /**+ * Clears files, or puts them back, as one request. GitHub takes a single path per mutation,+ * so a burst is batched with aliases into one document rather than one subprocess per press.+ */+ readonly setPullRequestFilesViewed: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly number: number;+ readonly files: ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>;+ }) => Effect.Effect<void, GitHubPullRequestCliError>;+readonly listReviewThreadComments: (input: {readonly cwd: string;readonly repository: string;@@ -1123,15 +1169,30 @@ export const make = Effect.gen(function* () {/*** The pull request's own node id, which is what a mutation against the pull request itself is* addressed by: a reaction on its description, or a rewrite of its words.+ *+ * A pull request keeps its node id for life, so it is remembered rather than re-read: a reader+ * ticking files viewed would otherwise pay a GraphQL round trip per press.*/+ const nodeIds = new Map<string, string>();+const pullRequestNodeId = (input: {readonly cwd: string;readonly repository: string;readonly host: string;readonly number: number;readonly operation: string;- }) => {+ }): Effect.Effect<string, GitHubPullRequestCliError> => {const { owner, name } = parseRepositorySelector(input.repository);+ const key = `${input.host} ${owner}/${name} ${input.number}`;+ const held = nodeIds.get(key);+ if (held !== undefined) {+ // Put back at the end on every hit, so what falls out is the pull request nobody has looked+ // at rather than the one being ticked through: a run of cold reads would otherwise evict the+ // open review and make it pay a round trip per press.+ nodeIds.delete(key);+ nodeIds.set(key, held);+ return Effect.succeed(held);+ }return graphqlRead({cwd: input.cwd,host: input.host,@@ -1144,7 +1205,17 @@ export const make = Effect.gen(function* () {],query: PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,decode: decodePullRequestNodeIdJson,- });+ }).pipe(+ Effect.tap((nodeId) =>+ Effect.sync(() => {+ if (nodeIds.size >= NODE_ID_CACHE_CAPACITY) {+ const oldest = nodeIds.keys().next().value;+ if (oldest !== undefined) nodeIds.delete(oldest);+ }+ nodeIds.set(key, nodeId);+ }),+ ),+ );};/**@@ -2482,6 +2553,56 @@ export const make = Effect.gen(function* () {variables: { threadId: input.threadId, body: input.body },}),+ getPullRequestFilesViewed: (input) => {+ const { owner, name } = parseRepositorySelector(input.repository);+ const read = (+ after: string | null,+ collected: ReadonlyArray<PullRequestFileViewed>,+ pagesLeft: number,+ ): Effect.Effect<GitHubPullRequestFilesViewed, GitHubPullRequestCliError> =>+ graphqlRead({+ cwd: input.cwd,+ host: input.host,+ operation: "getPullRequestFilesViewed",+ variables: [+ ["-f", `owner=${owner}`],+ ["-f", `name=${name}`],+ ["-F", `number=${input.number}`],+ ...(after === null+ ? []+ : ([["-f", `after=${after}`]] as ReadonlyArray<readonly [string, string]>)),+ ],+ query: PULL_REQUEST_FILES_VIEWED_GRAPHQL_QUERY,+ decode: decodePullRequestFilesViewedJson,+ }).pipe(+ Effect.flatMap((page) => {+ const files = [...collected, ...page.files];+ if (page.nextCursor === null) {+ return Effect.succeed({ files, truncated: false });+ }+ return pagesLeft <= 1+ ? Effect.succeed({ files, truncated: true })+ : read(page.nextCursor, files, pagesLeft - 1);+ }),+ );+ return read(null, [], FILES_VIEWED_MAX_PAGES);+ },++ setPullRequestFilesViewed: (input) => {+ const mutation = buildSetFilesViewedGraphQlMutation(input.files);+ if (mutation === null) return Effect.void;+ return pullRequestNodeId({ ...input, operation: "setPullRequestFilesViewed" }).pipe(+ Effect.flatMap((pullRequestId) =>+ graphql({+ cwd: input.cwd,+ host: input.host,+ query: mutation.query,+ variables: { pullRequestId, ...mutation.variables },+ }),+ ),+ );+ },+setReviewThreadResolution: (input) =>graphql({cwd: input.cwd,diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.tsindex 8a6190a43b4..e73e666f76c 100644--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.ts@@ -40,6 +40,7 @@ const CAPABILITIES: PullRequestCapabilities = {updateMethods: ["merge", "rebase"],search: true,reactions: true,+ viewedFiles: "host",review: {inlineComment: true,reply: true,@@ -576,6 +577,12 @@ export const make = Effect.gen(function* () {getDiffFileContents: (input) =>cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),+ getFilesViewed: (input) =>+ cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),++ setFilesViewed: (input) =>+ cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),+listReviewerCandidates: (input) =>cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),diff --git a/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts b/apps/server/src/pullRequest/GitLabPullRequestCli.test.tsindex 014d91a0274..daa85ee9eb8 100644--- a/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts+++ b/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts@@ -1402,4 +1402,171 @@ layer("GitLabPullRequestCli.layer", (it) => {expect(callAt(0).stdin).toBe('{"body":"true"}');}),);+ it.effect("reads blob ids for the marked paths at the merge request's head", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ iid: 7,+ title: "t",+ web_url: "https://gitlab.com/acme/web/-/merge_requests/7",+ source_branch: "feat",+ target_branch: "main",+ created_at: "2026-07-01T00:00:00Z",+ updated_at: "2026-07-01T00:00:00Z",+ diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },+ }),+ ),+ ),+ );+ mockedExecute.mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ data: {+ project: { repository: { blobs: { nodes: [{ path: "src/a.ts", oid: "aaa" }] } } },+ },+ }),+ ),+ ),+ );+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const revisions = yield* cli.getFileRevisions({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ paths: ["src/a.ts", "src/gone.ts"],+ });++ // Every path was looked for at the head, so one the head does not have is one the merge+ // request removed: said as the empty version, which a mark on it was stamped with too.+ expect([...revisions]).toEqual([+ ["src/a.ts", "aaa"],+ ["src/gone.ts", ""],+ ]);+ // The head the reader is looking at, not whatever the source branch has moved on to.+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ const body: unknown = JSON.parse(callAt(1).stdin ?? "{}");+ expect(body).toMatchObject({+ variables: { fullPath: "acme/web", ref: "head", paths: ["src/a.ts", "src/gone.ts"] },+ });+ }),+ );++ it.effect("leaves the paths out when GitLab did not answer the blobs query", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ iid: 7,+ title: "t",+ web_url: "https://gitlab.com/acme/web/-/merge_requests/7",+ source_branch: "feat",+ target_branch: "main",+ created_at: "2026-07-01T00:00:00Z",+ updated_at: "2026-07-01T00:00:00Z",+ diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },+ }),+ ),+ ),+ );+ // What GitLab says of a project the token cannot see. It is not the head having none of+ // these files, and reading it that way would report every file the reader has cleared as+ // changed on nothing worse than a permission.+ mockedExecute.mockReturnValueOnce(+ Effect.succeed(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ output(JSON.stringify({ data: { project: null } })),+ ),+ );+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const revisions = yield* cli.getFileRevisions({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ paths: ["src/a.ts", "src/b.ts"],+ });++ expect([...revisions]).toEqual([]);+ }),+ );++ it.effect("asks GitLab nothing when no file is marked", () =>+ Effect.gen(function* () {+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const revisions = yield* cli.getFileRevisions({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ paths: [],+ });++ expect([...revisions]).toEqual([]);+ expect(mockedExecute).not.toHaveBeenCalled();+ }),+ );++ it.effect("splits the paths across requests, because GitLab charges the query by how many", () =>+ Effect.gen(function* () {+ const paths = Array.from({ length: 150 }, (_, index) => `src/${index}.ts`);+ mockedExecute.mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ iid: 7,+ title: "t",+ web_url: "https://gitlab.com/acme/web/-/merge_requests/7",+ source_branch: "feat",+ target_branch: "main",+ created_at: "2026-07-01T00:00:00Z",+ updated_at: "2026-07-01T00:00:00Z",+ diff_refs: { base_sha: "base", head_sha: "head", start_sha: "start" },+ }),+ ),+ ),+ );+ mockedExecute.mockImplementation((request) => {+ const body = JSON.parse(request.stdin ?? "{}") as {+ readonly variables: { readonly paths: ReadonlyArray<string> };+ };+ return Effect.succeed(+ output(+ JSON.stringify({+ data: {+ project: {+ repository: {+ blobs: {+ nodes: body.variables.paths.map((path) => ({ path, oid: `oid-${path}` })),+ },+ },+ },+ },+ }),+ ),+ );+ });+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const revisions = yield* cli.getFileRevisions({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ paths,+ });++ assert.strictEqual(revisions.size, 150);+ assert.strictEqual(revisions.get("src/149.ts"), "oid-src/149.ts");+ // The diff refs, then two batches: a hundred paths and the fifty left over.+ assert.strictEqual(mockedExecute.mock.calls.length, 3);+ }),+ );});diff --git a/apps/server/src/pullRequest/GitLabPullRequestCli.ts b/apps/server/src/pullRequest/GitLabPullRequestCli.tsindex 60bf2c55742..5a07bb1ae37 100644--- a/apps/server/src/pullRequest/GitLabPullRequestCli.ts+++ b/apps/server/src/pullRequest/GitLabPullRequestCli.ts@@ -35,8 +35,10 @@ import {decodeOwnAwardIdJson,decodeProjectMergeCapabilitiesJson,decodeProjectUsersJson,+ decodeRepositoryBlobsJson,decodeViewerJson,gitLabAwardName,+ REPOSITORY_BLOBS_GRAPHQL_QUERY,type GitLabDiffRefs,type GitLabMergeRequestDetail,type GitLabMergeRequestListItem,@@ -283,6 +285,21 @@ export class GitLabPullRequestCli extends Context.Service<readonly repository: string;}) => Effect.Effect<PullRequestMergeCapabilities, GitLabPullRequestCliError>;+ /**+ * What the merge request's head has of each of these paths, as blob ids.+ *+ * The head sha comes from the merge request's own diff refs, so the answer is the version a+ * reader is looking at rather than whatever the source branch has moved on to. A path the+ * head does not have is answered as the empty revision, since the batch it was asked in was+ * looked at; a batch GitLab did not answer for is left out instead.+ */+ readonly getFileRevisions: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly number: number;+ readonly paths: ReadonlyArray<string>;+ }) => Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError>;+/*** Who this merge request may be sent to, and who it has already been sent to. Two reads at* once, because GitLab keeps the people with access on the project and the reviewers on the@@ -1031,6 +1048,88 @@ export const make = Effect.gen(function* () {}),);+ /**+ * GitLab charges the blobs query by how many paths it is handed, and its connection hands back+ * one page. A hundred at a time keeps each request inside both.+ */+ const BLOB_PATHS_PER_REQUEST = 100;++ const blobsAt = (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly ref: string;+ readonly paths: ReadonlyArray<string>;+ }): Effect.Effect<ReadonlyMap<string, string> | null, GitLabPullRequestCliError> =>+ api({+ cwd: input.cwd,+ path: "graphql",+ method: "POST",+ stdin: JSON.stringify({+ query: REPOSITORY_BLOBS_GRAPHQL_QUERY,+ variables: { fullPath: input.repository, ref: input.ref, paths: input.paths },+ }),+ }).pipe(+ Effect.flatMap(+ (result): Effect.Effect<ReadonlyMap<string, string> | null, GitLabPullRequestCliError> => {+ const decoded = decodeRepositoryBlobsJson(result.stdout.trim());+ return Result.isSuccess(decoded)+ ? Effect.succeed(decoded.success)+ : Effect.fail(+ new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: "getFileRevisions",+ cause: decoded.failure,+ }),+ );+ },+ ),+ );++ const fileRevisions = (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly number: number;+ readonly paths: ReadonlyArray<string>;+ }): Effect.Effect<ReadonlyMap<string, string>, GitLabPullRequestCliError> =>+ input.paths.length === 0+ ? Effect.succeed(new Map())+ : getDiffRefs(input).pipe(+ Effect.flatMap((refs) => {+ const batches: Array<ReadonlyArray<string>> = [];+ for (let at = 0; at < input.paths.length; at += BLOB_PATHS_PER_REQUEST) {+ batches.push(input.paths.slice(at, at + BLOB_PATHS_PER_REQUEST));+ }+ return Effect.forEach(+ batches,+ (paths) =>+ blobsAt({ ...input, ref: refs.headSha, paths }).pipe(+ Effect.map((page) => ({ paths, page })),+ ),+ { concurrency: 2 },+ ).pipe(+ Effect.map((pages) => {+ const revisions = new Map<string, string>();+ for (const { paths, page } of pages) {+ // A batch GitLab did not answer says nothing about its paths, so they are left+ // out and the caller reads them as versions it could not learn, which leaves+ // the marks on them alone. Filling them in as removed would report every file+ // a reader has cleared as changed over a project the token cannot see.+ if (page === null) continue;+ for (const [path, oid] of page) revisions.set(path, oid);+ // Within a batch that was answered, every path was looked for at the head, so+ // one that is not there is one the merge request removed. Said as the empty+ // revision, which is an answer the caller can compare against and keep.+ for (const path of paths) {+ if (!revisions.has(path)) revisions.set(path, "");+ }+ }+ return revisions as ReadonlyMap<string, string>;+ }),+ );+ }),+ );+const viewerUsername = (input: { readonly cwd: string }) =>api({ cwd: input.cwd, path: "user" }).pipe(Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {@@ -1066,6 +1165,8 @@ export const make = Effect.gen(function* () {listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),+ getFileRevisions: fileRevisions,+setReaction: (input) =>Effect.gen(function* () {const subject = awardSubjectPath(input);diff --git a/apps/server/src/pullRequest/GitLabPullRequestProvider.ts b/apps/server/src/pullRequest/GitLabPullRequestProvider.tsindex 46fce288427..c1482d601bd 100644--- a/apps/server/src/pullRequest/GitLabPullRequestProvider.ts+++ b/apps/server/src/pullRequest/GitLabPullRequestProvider.ts@@ -35,6 +35,11 @@ const CAPABILITIES: PullRequestCapabilities = {updateMethods: ["rebase"],search: true,reactions: true,+ // GitLab keeps a reader's viewed files in one browser's local storage, where nothing outside+ // that browser can read or write them. So the marks made here are this environment's own: they+ // follow the reader between the clients connected to it, but they are not the ones gitlab.com+ // shows, and the surface says so rather than implying a review can be carried on from there.+ viewedFiles: "environment",review: {inlineComment: true,reply: true,@@ -218,6 +223,15 @@ export const make = Effect.gen(function* () {getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),+ // What each marked file is at the head, which is what tells a mark that still stands from one+ // the branch has moved past. GitLab's own local-storage marks are keyed on the blob id too,+ // so this stales at the same moment its web UI would.+ getFileRevisions: (input) =>+ cli.getFileRevisions(input).pipe(+ Effect.mapError(fail("getFileRevisions")),+ Effect.map((revisions) => ({ revisions })),+ ),+// Users only: GitLab requests a review of a person, and the groups that can stand in for one// appear in approval rules rather than in a merge request's reviewers.listReviewerCandidates: (input) =>diff --git a/apps/server/src/pullRequest/PullRequestProvider.ts b/apps/server/src/pullRequest/PullRequestProvider.tsindex 405eb6ae9e6..eb09f81417c 100644--- a/apps/server/src/pullRequest/PullRequestProvider.ts+++ b/apps/server/src/pullRequest/PullRequestProvider.ts@@ -10,6 +10,7 @@ import type {PullRequestChecksState,PullRequestCheck,PullRequestComment,+ PullRequestFileViewed,PullRequestCommit,PullRequestInvolvement,PullRequestLabel,@@ -258,6 +259,32 @@ export interface ProviderDiffFileContents {readonly newContents: string;}+export interface ProviderFilesViewed {+ readonly files: ReadonlyArray<PullRequestFileViewed>;+ /** The host has more files than were read, so the ones missing here are not "unviewed". */+ readonly truncated: boolean;+}++/**+ * What version each of the asked-for files is at, on the change request's head. Opaque strings,+ * compared only against one another, where the empty string is the answer for a file the change+ * request deletes rather than a gap. A path is absent only where the read could not say, so a+ * provider converts its host's own absences on the way here.+ *+ * The whole path a version travels, and the three senses of null along it, are in+ * `docs/internals/pull-request-file-revisions.md`.+ */+export interface ProviderFileRevisions {+ readonly revisions: ReadonlyMap<string, string>;+ /**+ * Whether these are every file the change request carries rather than only the paths asked+ * about. A host with no per-file version reads the whole change to answer for one file, and+ * saying so is what keeps the next tick, naming a path nothing asked about before, from making+ * it read the whole change again. False for a read cut short, which cannot speak past the cut.+ */+ readonly complete?: boolean;+}+export interface ProviderRepositoryRef {readonly cwd: string;/** Provider-native repository identity, e.g. `owner/repo` or `group/subgroup/project`. */@@ -448,6 +475,40 @@ export interface PullRequestProviderApi {},) => Effect.Effect<ProviderDiffFileContents, PullRequestProviderError>;+ /**+ * Which files the reader has already cleared. Only called when `capabilities.viewedFiles` is+ * `"host"`, and read apart from the patch: this moves with every press rather than every push.+ */+ readonly getFilesViewed?: (+ input: ProviderRepositoryRef & { readonly number: number },+ ) => Effect.Effect<ProviderFilesViewed, PullRequestProviderError>;++ /**+ * Clears files, or puts them back. Only called when `capabilities.viewedFiles` is `"host"`.+ * A host with no bulk form is still owed one round trip for the batch rather than one per file,+ * since the point of gathering presses is that the host is asked once.+ */+ readonly setFilesViewed?: (+ input: ProviderRepositoryRef & {+ readonly number: number;+ readonly files: ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>;+ },+ ) => Effect.Effect<void, PullRequestProviderError>;++ /**+ * What version the head has of each of these files. Required of a host whose+ * `capabilities.viewedFiles` is `"environment"`, and unused by one that keeps the marks itself:+ * the marks live here, but only the host can say whether what a reader cleared last week is+ * still what is in front of them. Asked for the marked paths alone, so the cost follows how+ * much of the change request has been read rather than how large it is.+ */+ readonly getFileRevisions?: (+ input: ProviderRepositoryRef & {+ readonly number: number;+ readonly paths: ReadonlyArray<string>;+ },+ ) => Effect.Effect<ProviderFileRevisions, PullRequestProviderError>;+readonly runAction: (input: ProviderRepositoryRef & {readonly number: number;diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 51ce3aa5507..4000d383642 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -1,4 +1,5 @@import * as NodeServices from "@effect/platform-node/NodeServices";+import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";import * as KeyValueStore from "effect/unstable/persistence/KeyValueStore";import { assert, it } from "@effect/vitest";import * as Deferred from "effect/Deferred";@@ -18,8 +19,12 @@ import type {import { PullRequestOperationError } from "@t3tools/contracts";import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";+import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";+import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";+import { ForgejoCli } from "../sourceControl/ForgejoCli.ts";+import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";import {PullRequestProviderError,type ProviderChangeRequest,@@ -28,6 +33,10 @@ import {import { PullRequestProviderRegistry, fromProviders } from "./PullRequestProviderRegistry.ts";import * as PullRequestService from "./PullRequestService.ts";import * as PullRequestReadCache from "./PullRequestReadCache.ts";+import {+ FILE_REVISIONS_CACHE_CAPACITY,+ MAX_FILE_REVISION_PATHS,+} from "./pullRequestViewedFiles.ts";function project(input: {readonly id: string;@@ -184,8 +193,10 @@ function makeService(input: {readonly providers: ReadonlyArray<PullRequestProviderApi>;readonly resolveHandle?: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"]["resolveHandle"];}) {- return PullRequestService.make.pipe(- Effect.provide(+ // Built into the test's own scope rather than provided call by call: the marks store owns a+ // database, and `Effect.provide` would close it the moment the service was handed back.+ return Effect.flatMap(+ Layer.build(Layer.mergeAll(Layer.succeed(PullRequestProviderRegistry, fromProviders(input.providers)),Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({@@ -202,12 +213,16 @@ function makeService(input: {Effect.succeed(Option.fromNullishOr(input.projects.find((p) => p.id === projectId))),}),SourceControlRateLimit.layer,+ // The real store over a database of its own, so the environment-kept marks are exercised+ // through the SQL that holds them rather than through a stand-in that agrees with itself.+ PullRequestFilesViewed.layer.pipe(Layer.provide(SqlitePersistenceMemory)),Layer.effect(PullRequestReadCache.PullRequestReadCache, PullRequestReadCache.make).pipe(Layer.provide(KeyValueStore.layerMemory),Layer.provide(NodeServices.layer),),),),+ (context) => Effect.provideContext(PullRequestService.make, context),);}@@ -4002,7 +4017,7 @@ it.effect("shares linked summaries and reuses them for display without asking thit.effect("keeps routed reads separate when the GitHub account changes", () =>Effect.gen(function* () {- for (const operation of ["summary", "detail", "diff"] as const) {+ for (const operation of ["summary", "detail", "diff", "filesViewed"] as const) {let failing = false;let calls = 0;const read = () =>@@ -4018,6 +4033,14 @@ it.effect("keeps routed reads separate when the GitHub account changes", () =>],providers: [fakeProvider("github", {+ capabilities: { ...fakeProvider("github").capabilities, viewedFiles: "host" },+ getFilesViewed: () =>+ read().pipe(+ Effect.as({+ files: [{ path: "private.ts", state: "viewed" as const }],+ truncated: false,+ }),+ ),getChangeRequestSummary: read,getChangeRequest: read,getDiff: () =>@@ -4048,7 +4071,7 @@ it.effect("keeps routed reads separate when the GitHub account changes", () =>it.effect("isolates routed caches for two credentials belonging to the same account", () =>Effect.gen(function* () {- for (const operation of ["summary", "detail", "diff"] as const) {+ for (const operation of ["summary", "detail", "diff", "filesViewed"] as const) {let credential = "broad";let calls = 0;const read = () =>@@ -4064,6 +4087,14 @@ it.effect("isolates routed caches for two credentials belonging to the same acco],providers: [fakeProvider("github", {+ capabilities: { ...fakeProvider("github").capabilities, viewedFiles: "host" },+ getFilesViewed: () =>+ read().pipe(+ Effect.as({+ files: [{ path: "private.ts", state: "viewed" as const }],+ truncated: false,+ }),+ ),withVerifiedCredential: (_, use) =>Effect.suspend(() =>use({@@ -5089,6 +5120,1393 @@ it.effect("names the signed-in account in the detail, and says nothing where the}),);+it.effect("keeps the diff cached across a file being ticked off", () =>+ Effect.gen(function* () {+ let diffReads = 0;+ let viewedReads = 0;+ let state: "viewed" | "dismissed" = "viewed";+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),+ ],+ providers: [+ fakeProvider("github", {+ capabilities: {+ diff: true,+ comment: true,+ actions: ["merge"],+ mergeMethods: ["merge"],+ search: true,+ reactions: true,+ viewedFiles: "host",+ review: FULL_REVIEW,+ reviewers: FULL_REVIEWERS,+ },+ getDiff: () => {+ diffReads += 1;+ return Effect.succeed({ patch: "@@", truncated: false, nextCursor: null });+ },+ getFilesViewed: () => {+ viewedReads += 1;+ return Effect.succeed({+ files: [{ path: "src/a.ts", state }],+ truncated: false,+ });+ },+ setFilesViewed: () => Effect.void,+ }),+ ],+ });+ const reference = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 };++ yield* service.diff(reference);+ yield* service.filesViewed(reference);+ yield* service.setFilesViewed({ ...reference, files: [{ path: "src/a.ts", viewed: false }] });+ yield* service.diff(reference);+ yield* service.filesViewed(reference);++ // The press forgets only the reader's own ticks: a diff of any size survives it.+ assert.strictEqual(diffReads, 1);+ assert.strictEqual(viewedReads, 2);++ state = "dismissed";+ yield* service.invalidate({ reference, filesViewedOnly: true });+ yield* service.diff(reference);+ assert.deepStrictEqual((yield* service.filesViewed(reference)).files, [+ { path: "src/a.ts", state: "dismissed" },+ ]);+ assert.strictEqual(diffReads, 1);+ assert.strictEqual(viewedReads, 3);+ }),+);++const environmentViewedProvider = (+ revisions: Map<string, string>,+ asked: Array<ReadonlyArray<string>>,+ unreadable: ReadonlySet<string> = new Set(),+) =>+ fakeProvider("gitlab", {+ capabilities: {+ diff: true,+ comment: true,+ actions: ["merge"],+ mergeMethods: ["merge"],+ search: true,+ reactions: true,+ viewedFiles: "environment",+ review: FULL_REVIEW,+ reviewers: FULL_REVIEWERS,+ },+ getFilesViewed: () => Effect.die("the host keeps no marks of its own"),+ setFilesViewed: () => Effect.die("the host keeps no marks of its own"),+ // A merge confirms itself against the host before it says the change request landed.+ getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-07-02T00:00:00Z")),+ getFileRevisions: (input) => {+ asked.push(input.paths);+ return Effect.succeed({+ // A path the host looked at and did not find is at the empty version, which is what a+ // file the change request deletes is at. One it could not look at is left out entirely.+ revisions: new Map(+ input.paths.flatMap((path) =>+ unreadable.has(path) ? [] : [[path, revisions.get(path) ?? ""] as const],+ ),+ ),+ });+ },+ });++const environmentViewedService = (+ revisions: Map<string, string>,+ asked: Array<ReadonlyArray<string>>,+ unreadable: ReadonlySet<string> = new Set(),+) =>+ makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [environmentViewedProvider(revisions, asked, unreadable)],+ });++const GITLAB_REFERENCE = {+ projectId: "p1" as ProjectId,+ repository: "group/project",+ number: 1,+};++it.effect("tracks Forgejo viewed files through its diff and refuses truncated baselines", () =>+ Effect.gen(function* () {+ let alpha = "b485fe5";+ let truncated = false;+ let diffReads = 0;+ const provider = yield* ForgejoPullRequestProvider.make.pipe(+ Effect.provide(+ Layer.mock(ForgejoCli)({+ api: (input) => {+ assert.strictEqual(input.host, "forge.example:3000");+ const viewer = input.path === "user";+ if (!viewer) {+ assert.strictEqual(input.repository, "reviewer/project");+ assert.strictEqual(input.path, "repos/reviewer/project/pulls/1.diff");+ diffReads++;+ }+ return Effect.succeed({+ exitCode: ChildProcessSpawner.ExitCode(0),+ stdout: viewer+ ? JSON.stringify({ login: "reviewer" })+ : truncated+ ? `diff --git a/alpha.ts b/alpha.ts\nindex eb2d7c5..${alpha} 100644\n`+ : [+ "diff --git a/alpha.ts b/alpha.ts",+ `index eb2d7c5..${alpha} 100644`,+ "diff --git a/beta.ts b/beta.ts",+ "index b39e8b3..5851425 100644",+ 'diff --git "a/caf\\303\\251 notes.txt" "b/caf\\303\\251 notes.txt"',+ "index ffd99ce..6dd9855 100644",+ "diff --git a/deleted.txt b/deleted.txt",+ "deleted file mode 100644",+ "index 233f5c6..0000000",+ "diff --git a/old.txt b/renamed.txt",+ "similarity index 100%",+ "rename from old.txt",+ "rename to renamed.txt",+ "",+ ].join("\n"),+ stderr: "",+ stdoutTruncated: !viewer && truncated,+ stderrTruncated: false,+ });+ },+ }),+ ),+ );+ const service = yield* makeService({+ projects: [+ project({+ id: "forgejo",+ title: "on forgejo",+ workspaceRoot: "/forgejo",+ repository: "reviewer/project",+ provider: "forgejo",+ host: "forge.example:3000",+ remoteUrl: "http://forge.example:3000/reviewer/project.git",+ }),+ ],+ providers: [provider],+ });+ const reference = {+ projectId: "forgejo" as ProjectId,+ repository: "reviewer/project",+ host: "forge.example:3000",+ number: 1,+ };+ const paths = ["alpha.ts", "beta.ts", "café notes.txt", "deleted.txt", "renamed.txt"];+ yield* service.setFilesViewed({+ ...reference,+ files: paths.map((path) => ({ path, viewed: true })),+ });+ assert.deepStrictEqual(+ new Map((yield* service.filesViewed(reference)).files.map((file) => [file.path, file.state])),+ new Map(paths.map((path) => [path, "viewed"])),+ );+ assert.strictEqual(diffReads, 1);++ alpha = "aabbccd";+ yield* service.invalidate({ reference });+ assert.deepStrictEqual(+ new Map((yield* service.filesViewed(reference)).files.map((file) => [file.path, file.state])),+ new Map(paths.map((path) => [path, path === "alpha.ts" ? "dismissed" : "viewed"])),+ );+ yield* service.setFilesViewed({+ ...reference,+ files: [{ path: "beta.ts", viewed: false }],+ });+ assert.isFalse(+ (yield* service.filesViewed(reference)).files.some((file) => file.path === "beta.ts"),+ );++ truncated = true;+ yield* service.invalidate({ reference });+ yield* service.setFilesViewed({+ ...reference,+ files: [{ path: "beta.ts", viewed: true }],+ });+ truncated = false;+ yield* service.invalidate({ reference });+ // A partial response must not stamp an empty revision and then dismiss the mark on recovery.+ assert.deepStrictEqual(+ (yield* service.filesViewed(reference)).files.find((file) => file.path === "beta.ts"),+ { path: "beta.ts", state: "viewed" },+ );+ }),+);++it.effect("keeps hosted Forgejo marks with their repository instead of the serving checkout", () =>+ Effect.gen(function* () {+ const projects = [+ project({+ id: "p1",+ title: "first repository",+ workspaceRoot: "/first",+ repository: "reviewer/first",+ provider: "forgejo",+ host: "forge.example",+ remoteUrl: "https://forge.example:3000/reviewer/first.git",+ }),+ ];+ const service = yield* makeService({+ projects,+ providers: [+ { ...environmentViewedProvider(new Map([["same.ts", "blob"]]), []), kind: "forgejo" },+ ],+ resolveHandle: ({ context }) =>+ Effect.succeed({+ context: {+ ...context!,+ provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://forge.example:3000" },+ },+ provider: undefined as never,+ }),+ });+ const first = {+ projectId: "p1" as ProjectId,+ host: "forge.example:3000",+ repository: "reviewer/first",+ number: 1,+ };+ const second = { ...first, repository: "reviewer/second" };+ const files = [{ path: "same.ts", viewed: true }];+ yield* service.setFilesViewed({ ...first, files });+ assert.deepStrictEqual((yield* service.filesViewed(second)).files, []);+ yield* service.setFilesViewed({ ...second, files });+ yield* service.setFilesViewed({ ...first, files: [{ path: "same.ts", viewed: false }] });+ assert.deepStrictEqual((yield* service.filesViewed(second)).files, [+ { path: "same.ts", state: "viewed" },+ ]);++ projects.push(+ project({+ id: "p2",+ title: "second repository",+ workspaceRoot: "/second",+ repository: "reviewer/second",+ provider: "forgejo",+ host: "forge.example",+ remoteUrl: "https://forge.example:3000/reviewer/second.git",+ }),+ );+ assert.deepStrictEqual(+ (yield* service.filesViewed({ ...second, projectId: "p2" as ProjectId })).files,+ [{ path: "same.ts", state: "viewed" }],+ );+ projects.push(+ project({+ id: "ssh",+ title: "second repository over SSH",+ workspaceRoot: "/ssh",+ repository: "reviewer/second",+ provider: "forgejo",+ host: "ssh.forge.example",+ remoteUrl: "[email protected]:reviewer/second.git",+ }),+ );+ assert.deepStrictEqual(+ (yield* service.filesViewed({ ...second, projectId: "ssh" as ProjectId })).files,+ [{ path: "same.ts", state: "viewed" }],+ );+ }),+);++it.effect("keeps viewed files itself for a host that keeps none of its own", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const service = yield* environmentViewedService(+ new Map([+ ["src/a.ts", "blob-a"],+ ["src/b.ts", "blob-b"],+ ]),+ asked,+ );++ // Nothing marked is nothing to ask the host about.+ const empty = yield* service.filesViewed(GITLAB_REFERENCE);+ assert.deepStrictEqual(empty, { files: [], truncated: false });+ assert.deepStrictEqual(asked, []);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [+ { path: "src/a.ts", viewed: true },+ { path: "src/b.ts", viewed: true },+ ],+ });+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(+ [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)),+ [+ { path: "src/a.ts", state: "viewed" },+ { path: "src/b.ts", state: "viewed" },+ ],+ );+ assert.strictEqual(marked.truncated, false);+ // The marked paths alone, so the cost follows how much has been read rather than PR size,+ // and the read after the press is answered from what the press already heard.+ assert.deepStrictEqual(+ asked.map((paths) => [...paths].toSorted()),+ [["src/a.ts", "src/b.ts"]],+ );+ }),+);++it.effect("holds what a whole-change answer carried, so the next tick reads nothing", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const head = new Map([+ ["src/a.ts", "blob-a"],+ ["src/b.ts", "blob-b"],+ ]);+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ {+ ...environmentViewedProvider(head, []),+ // A host with no per-file version reads the whole change to answer for one file, which+ // is what Bitbucket's patch is, and says as much.+ getFileRevisions: (input) => {+ asked.push(input.paths);+ return Effect.succeed({ revisions: head, complete: true });+ },+ },+ ],+ });++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ // A path nothing has asked about before, which is what every tick after the first names. Its+ // version came back with the first answer, so there is nothing left to read it for.+ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/b.ts", viewed: true }],+ });++ assert.deepStrictEqual(asked, [["src/a.ts"]]);+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);+ assert.deepStrictEqual(+ [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)),+ [+ { path: "src/a.ts", state: "viewed" },+ { path: "src/b.ts", state: "viewed" },+ ],+ );++ // Still only as fresh as the read it came from: past that window the press reads again rather+ // than stamping a mark with a version the head may have moved off.+ yield* TestClock.adjust("2 minutes");+ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/b.ts", viewed: true }],+ });+ assert.deepStrictEqual(asked, [["src/a.ts"], ["src/b.ts"]]);+ }),+);++it.effect("reads the marks without asking the host what the head has every time", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const service = yield* environmentViewedService(new Map([["src/a.ts", "blob-a"]]), asked);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ // Past the marks' own cache, so this read reaches the point where the host would be asked.+ yield* TestClock.adjust("20 seconds");+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(marked.files, [{ path: "src/a.ts", state: "viewed" }]);+ assert.deepStrictEqual(asked, [["src/a.ts"]]);+ }),+);++it.effect("answers the marks from what it last heard while it asks the host again", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const revisions = new Map([["src/a.ts", "blob-a"]]);+ const service = yield* environmentViewedService(revisions, asked);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ revisions.set("src/a.ts", "blob-a-again");+ yield* TestClock.adjust("90 seconds");+ const held = yield* service.filesViewed(GITLAB_REFERENCE);++ // The push is not in this answer, because waiting for the host is the thing being avoided.+ assert.deepStrictEqual(held.files, [{ path: "src/a.ts", state: "viewed" }]);+ assert.strictEqual(asked.length, 2);++ yield* TestClock.adjust("20 seconds");+ const caught = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(caught.files, [{ path: "src/a.ts", state: "dismissed" }]);+ // The refresh behind the previous answer is the one that heard about the push.+ assert.strictEqual(asked.length, 2);+ }),+);++it.effect("asks the host about a file it has not been asked about before", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const service = yield* environmentViewedService(+ new Map([+ ["src/a.ts", "blob-a"],+ ["src/b.ts", "blob-b"],+ ]),+ asked,+ );++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ yield* TestClock.adjust("20 seconds");+ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/b.ts", viewed: true }],+ });+ yield* TestClock.adjust("20 seconds");+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(+ [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)),+ [+ { path: "src/a.ts", state: "viewed" },+ { path: "src/b.ts", state: "viewed" },+ ],+ );+ // The second press paid for its own file; the read that follows was already covered.+ assert.deepStrictEqual(asked, [["src/a.ts"], ["src/b.ts"]]);+ }),+);++it.effect("does not let a press about one file keep another file's version alive", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const revisions = new Map([+ ["src/a.ts", "blob-a"],+ ["src/b.ts", "blob-b"],+ ]);+ const service = yield* environmentViewedService(revisions, asked);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ yield* TestClock.adjust("40 seconds");+ // This press asks about its own file and carries the other one forward untouched. Counting+ // the whole scope as heard from would put the first file's version back inside the window it+ // had almost aged out of, and a reader working down a long diff renews it press after press.+ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/b.ts", viewed: true }],+ });+ assert.deepStrictEqual(asked, [["src/a.ts"], ["src/b.ts"]]);++ revisions.set("src/a.ts", "blob-a-again");+ yield* TestClock.adjust("30 seconds");+ yield* service.filesViewed(GITLAB_REFERENCE);+ assert.strictEqual(asked.length, 3);++ yield* TestClock.adjust("20 seconds");+ const caught = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(+ [...caught.files].toSorted((left, right) => left.path.localeCompare(right.path)),+ [+ { path: "src/a.ts", state: "dismissed" },+ { path: "src/b.ts", state: "viewed" },+ ],+ );+ }),+);++it.effect("reports a file pushed to since it was cleared as changed", () =>+ Effect.gen(function* () {+ const revisions = new Map([+ ["src/a.ts", "blob-a"],+ ["src/b.ts", "blob-b"],+ ]);+ const service = yield* environmentViewedService(revisions, []);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [+ { path: "src/a.ts", viewed: true },+ { path: "src/b.ts", viewed: true },+ ],+ });+ revisions.set("src/a.ts", "blob-a-again");+ // A push is not something the marks can hear about, so the reader asks to be re-answered.+ yield* service.invalidate({ reference: GITLAB_REFERENCE });+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(+ [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)),+ [+ { path: "src/a.ts", state: "dismissed" },+ { path: "src/b.ts", state: "viewed" },+ ],+ );+ }),+);++it.effect("clears a mark again when the file is put back", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const service = yield* environmentViewedService(new Map([["src/a.ts", "blob-a"]]), asked);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: false }],+ });+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(marked.files, []);+ // Unticking asks the host nothing: the row is going away whatever the head has.+ assert.deepStrictEqual(asked, [["src/a.ts"]]);+ }),+);++it.effect("keeps a deleted file cleared, which the head has no version of at all", () =>+ Effect.gen(function* () {+ const service = yield* environmentViewedService(new Map(), []);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/gone.ts", viewed: true }],+ });+ yield* service.invalidate({ reference: GITLAB_REFERENCE });+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(marked.files, [{ path: "src/gone.ts", state: "viewed" }]);+ }),+);++it.effect("leaves a mark alone when the host could not say what the head has of it", () =>+ Effect.gen(function* () {+ // A host answers for as much of a long change as it can read in one go. Reading the rest as+ // deleted would clear every file past the cut over a version nobody ever looked at.+ const revisions = new Map([+ ["src/a.ts", "blob-a"],+ ["src/past-the-cut.ts", "blob-b"],+ ]);+ const service = yield* environmentViewedService(+ revisions,+ [],+ new Set(["src/past-the-cut.ts"]),+ );++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [+ { path: "src/a.ts", viewed: true },+ { path: "src/past-the-cut.ts", viewed: true },+ ],+ });+ revisions.set("src/a.ts", "blob-a-again");+ yield* service.invalidate({ reference: GITLAB_REFERENCE });+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(+ [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)),+ [+ { path: "src/a.ts", state: "dismissed" },+ { path: "src/past-the-cut.ts", state: "viewed" },+ ],+ );+ }),+);++it.effect("keeps a file cleared that the press could not learn a version for", () =>+ Effect.gen(function* () {+ // The press is the only moment a mark is given something to be measured against, and a host+ // reading as much of a long change as it can manage does not always reach the file being+ // ticked. Storing the empty version there reads as the head having nothing of the file, so the+ // first read that does reach it reports the reader's own press back to them as work to do.+ const revisions = new Map([["src/past-the-cut.ts", "blob-b"]]);+ const unreadable = new Set(["src/past-the-cut.ts"]);+ const service = yield* environmentViewedService(revisions, [], unreadable);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/past-the-cut.ts", viewed: true }],+ });+ unreadable.delete("src/past-the-cut.ts");+ yield* service.invalidate({ reference: GITLAB_REFERENCE });++ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/past-the-cut.ts", state: "viewed" },+ ]);+ }),+);++it.effect("keeps the version it last heard when a later read of the head stops short", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const revisions = new Map([["src/a.ts", "blob-a"]]);+ const unreadable = new Set<string>();+ const service = yield* environmentViewedService(revisions, asked, unreadable);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ revisions.set("src/a.ts", "blob-a-again");+ yield* service.invalidate({ reference: GITLAB_REFERENCE });+ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/a.ts", state: "dismissed" },+ ]);++ // The read behind the next answer has to stop before this file. Forgetting the version it was+ // last seen at would put the badge the reader has already been shown back to cleared, over an+ // answer that said nothing about the file either way.+ unreadable.add("src/a.ts");+ yield* TestClock.adjust("90 seconds");+ yield* service.filesViewed(GITLAB_REFERENCE);+ yield* TestClock.adjust("20 seconds");++ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/a.ts", state: "dismissed" },+ ]);+ }),+);++it.effect("re-asks what the head has of a marked file after a whole-workspace refresh", () =>+ Effect.gen(function* () {+ const revisions = new Map([["src/a.ts", "blob-a"]]);+ const service = yield* environmentViewedService(revisions, []);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ // A push nobody told this environment about. No single reference has moved, so the held+ // answer goes only because the refresh is the reader asking for all of it to be read again.+ revisions.set("src/a.ts", "blob-a-again");+ yield* service.invalidate({});++ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/a.ts", state: "dismissed" },+ ]);+ }),+);++it.effect("forgets what the head had of a marked file once a mutation moves the head", () =>+ Effect.gen(function* () {+ const revisions = new Map([["src/a.ts", "blob-a"]]);+ const service = yield* environmentViewedService(revisions, []);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ // Merging moves the head under the mark, and nobody asks for the refresh: the mutation is+ // the thing that knows, so it drops what it was holding rather than waiting to be told.+ revisions.set("src/a.ts", "blob-a-again");+ yield* service.runAction({ ...GITLAB_REFERENCE, action: "merge" });++ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/a.ts", state: "dismissed" },+ ]);+ }),+);++it.effect("still reports its own marks when the host will not say what the head has", () =>+ Effect.gen(function* () {+ let answering = true;+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ fakeProvider("gitlab", {+ capabilities: {+ diff: true,+ comment: true,+ actions: ["merge"],+ mergeMethods: ["merge"],+ search: true,+ reactions: true,+ viewedFiles: "environment",+ review: FULL_REVIEW,+ reviewers: FULL_REVIEWERS,+ },+ getFilesViewed: () => Effect.die("the host keeps no marks of its own"),+ setFilesViewed: () => Effect.die("the host keeps no marks of its own"),+ getFileRevisions: (input) =>+ answering+ ? Effect.succeed({+ revisions: new Map(input.paths.map((path) => [path, "blob-a"] as const)),+ })+ : Effect.fail(requestFailed),+ }),+ ],+ });++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ answering = false;+ yield* service.invalidate({ reference: GITLAB_REFERENCE });++ // The rows are this environment's own. A rate limit or a signed-out CLI costs them the+ // staleness they would have carried, not the reader's whole record of what they have read.+ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/a.ts", state: "viewed" },+ ]);+ }),+);++it.effect("finishes two presses on one file in the order they were made", () =>+ Effect.gen(function* () {+ // A tick asks the host what it has of the file before it stores anything, and an untick asks+ // nothing at all, so the second press would otherwise land first and be overwritten by the+ // first one finishing behind it.+ const held = yield* Deferred.make<void>();+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ fakeProvider("gitlab", {+ capabilities: {+ diff: true,+ comment: true,+ actions: ["merge"],+ mergeMethods: ["merge"],+ search: true,+ reactions: true,+ viewedFiles: "environment",+ review: FULL_REVIEW,+ reviewers: FULL_REVIEWERS,+ },+ getFilesViewed: () => Effect.die("the host keeps no marks of its own"),+ setFilesViewed: () => Effect.die("the host keeps no marks of its own"),+ getFileRevisions: (input) =>+ Deferred.await(held).pipe(+ Effect.as({ revisions: new Map(input.paths.map((path) => [path, "blob-a"])) }),+ ),+ }),+ ],+ });++ const tick = service+ .setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ })+ .pipe(Effect.runFork);+ // Far enough for the tick to be waiting on the host rather than still on its way there.+ yield* TestClock.adjust("1 second");+ const untick = service+ .setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: false }],+ })+ .pipe(Effect.runFork);+ yield* TestClock.adjust("1 second");+ yield* Deferred.succeed(held, undefined);+ yield* Fiber.join(tick);+ yield* Fiber.join(untick);++ // The untick came second and stands: the file is open again.+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);+ assert.deepStrictEqual(marked.files, []);+ }),+);++/** Azure, whose selector is a bare repository name, backed by this environment's own marks. */+const azureViewedService = (projects: ReadonlyArray<OrchestrationProjectShell>) =>+ makeService({+ projects,+ providers: [+ fakeProvider("azure-devops", {+ capabilities: {+ diff: true,+ comment: true,+ actions: ["merge"],+ mergeMethods: ["merge"],+ search: true,+ reactions: true,+ viewedFiles: "environment",+ review: FULL_REVIEW,+ reviewers: FULL_REVIEWERS,+ },+ getFilesViewed: () => Effect.die("the host keeps no marks of this environment's own"),+ setFilesViewed: () => Effect.die("the host keeps no marks of this environment's own"),+ getFileRevisions: (input) =>+ Effect.succeed({ revisions: new Map(input.paths.map((path) => [path, "blob-a"])) }),+ }),+ ],+ });++const AZURE_PAIR = [+ project({+ id: "p1",+ title: "platform web",+ workspaceRoot: "/a",+ repository: "acme/platform/_git/web",+ provider: "azure-devops",+ host: "dev.azure.com",+ }),+ project({+ id: "p2",+ title: "other web",+ workspaceRoot: "/b",+ repository: "acme/other/_git/web",+ provider: "azure-devops",+ host: "dev.azure.com",+ }),+];++const AZURE_PLATFORM = { projectId: "p1" as ProjectId, repository: "web", number: 1 };+const AZURE_OTHER = { projectId: "p2" as ProjectId, repository: "web", number: 1 };++it.effect("keeps the marks of two Azure repositories of the same name apart", () =>+ Effect.gen(function* () {+ // Azure addresses a repository by its bare name, which is unique inside one of its projects+ // and not across an organisation. Two `web` repositories would otherwise share one row.+ const service = yield* azureViewedService(AZURE_PAIR);++ yield* service.setFilesViewed({+ ...AZURE_PLATFORM,+ files: [{ path: "src/a.ts", viewed: true }],+ });++ assert.deepStrictEqual((yield* service.filesViewed(AZURE_PLATFORM)).files, [+ { path: "src/a.ts", state: "viewed" },+ ]);+ assert.deepStrictEqual((yield* service.filesViewed(AZURE_OTHER)).files, []);+ }),+);++it.effect("keeps environment marks apart from another change request's", () =>+ Effect.gen(function* () {+ const service = yield* environmentViewedService(new Map([["src/a.ts", "blob-a"]]), []);++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ const other = yield* service.filesViewed({ ...GITLAB_REFERENCE, number: 2 });++ assert.deepStrictEqual(other.files, []);+ }),+);++it.effect("bounds the paths one change request's held revisions carry", () =>+ Effect.gen(function* () {+ // The cache's count bounds how many change requests are held, not what any one of them holds:+ // a reader ticking a wide change request renews the same entry on every press and adds a path+ // to it each time. A press carries at most half the cap, so going one past it takes three.+ const asked: Array<ReadonlyArray<string>> = [];+ const service = yield* environmentViewedService(new Map(), asked);+ const batch = (prefix: string, count: number) =>+ Array.from({ length: count }, (_, index) => ({+ path: `${prefix}/${String(index).padStart(4, "0")}.ts`,+ viewed: true,+ }));+ const press = (prefix: string, count: number) =>+ service.setFilesViewed({ ...GITLAB_REFERENCE, files: batch(prefix, count) });++ yield* press("a", MAX_FILE_REVISION_PATHS / 2);+ yield* press("b", MAX_FILE_REVISION_PATHS / 2);+ yield* press("c", 1);+ const pressed = asked.length;++ // The marks a read carries come first by path, so this one covers the earliest batch, which+ // is where the paths asked about longest ago are. Held short of them the entry no longer+ // answers the read, and the host is asked rather than the reader being told a version that+ // nothing holds any more.+ yield* service.filesViewed(GITLAB_REFERENCE);++ assert.strictEqual(asked.length, pressed + 1);+ assert.ok(asked.at(-1)?.includes("a/0000.ts"));+ }),+);++it.effect("keeps the marked paths when a whole-change answer is wider than the cap", () =>+ Effect.gen(function* () {+ // A host with no per-file version answers with the whole change, which on a wide review+ // carries more paths than one entry holds. What the trim reaches has to be the paths the+ // answer threw in rather than the ones the reader ticked: a mark stored with no baseline+ // reports viewed however far the head moves off it.+ const head = new Map<string, string>(+ Array.from(+ { length: MAX_FILE_REVISION_PATHS + 178 },+ (_, index) =>+ [`src/f${String(index).padStart(4, "0")}.ts`, `blob-${String(index)}`] as const,+ ),+ );+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ {+ ...environmentViewedProvider(head, []),+ getFileRevisions: () => Effect.succeed({ revisions: head, complete: true }),+ },+ ],+ });+ const ticked = ["src/f0000.ts", "src/f0500.ts"];++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: ticked.map((path) => ({ path, viewed: true })),+ });+ for (const path of ticked) head.set(path, "blob-moved");+ // Past the stale window, so the read is answered by the host rather than from what the press+ // heard.+ yield* TestClock.adjust("11 minutes");+ const marked = yield* service.filesViewed(GITLAB_REFERENCE);++ assert.deepStrictEqual(+ [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)),+ [+ { path: "src/f0000.ts", state: "dismissed" },+ { path: "src/f0500.ts", state: "dismissed" },+ ],+ );+ }),+);++it.effect("keeps the change request being ticked through, not the one pressed first", () =>+ Effect.gen(function* () {+ // Ordered by insertion alone a hit does not renew its entry, so the review a reader is+ // working down is the first thing dropped once a cache's worth of other change requests have+ // been pressed, and the next press on it pays a host read for a version already held.+ const asked: Array<ReadonlyArray<string>> = [];+ const service = yield* environmentViewedService(new Map([["src/a.ts", "blob-a"]]), asked);+ const press = (number: number) =>+ service.setFilesViewed({+ ...GITLAB_REFERENCE,+ number,+ files: [{ path: "src/a.ts", viewed: true }],+ });++ yield* press(1);+ // A cache's worth of other change requests, with the open one pressed in between each.+ for (let filled = 0; filled < FILE_REVISIONS_CACHE_CAPACITY; filled += 1) {+ yield* press(2 + filled);+ yield* press(1);+ }++ assert.strictEqual(asked.length, 1 + FILE_REVISIONS_CACHE_CAPACITY);+ }),+);++/** The environment-backed fixture with its own answer to who the reader is. */+const environmentViewedServiceWithViewer = (+ revisions: Map<string, string>,+ getViewer: PullRequestProviderApi["getViewer"],+) =>+ makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [{ ...environmentViewedProvider(revisions, []), getViewer }],+ });++it.effect("keeps one reader's marks on a host that names nobody", () =>+ Effect.gen(function* () {+ const service = yield* environmentViewedServiceWithViewer(+ new Map([["src/a.ts", "blob-a"]]),+ () => Effect.succeed(""),+ );++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });++ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/a.ts", state: "viewed" },+ ]);+ }),+);++it.effect("puts a listing and a press for one host on a single viewer lookup", () =>+ Effect.gen(function* () {+ let viewerLookups = 0;+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ {+ ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []),+ getViewer: () =>+ Effect.gen(function* () {+ viewerLookups += 1;+ // Suspends before answering, as a subprocess would, so both callers are in flight+ // at once rather than the second finding the first has already answered.+ yield* Effect.yieldNow;+ return "bilal";+ }),+ },+ ],+ });++ // What a cold page load does: read the listing and the reader's own marks at the same time.+ // Nothing about which of them asked is in the lookup's key, so they wait on one CLI between+ // them rather than starting one each.+ yield* Effect.all([service.list({ state: "open" }), service.filesViewed(GITLAB_REFERENCE)], {+ concurrency: 2,+ });++ assert.strictEqual(viewerLookups, 1);+ }),+);++it.effect("carries a bounded number of its own marks and says it held more", () =>+ Effect.gen(function* () {+ const asked: Array<ReadonlyArray<string>> = [];+ const paths = Array.from(+ { length: PullRequestFilesViewed.MAX_FILES_VIEWED_ROWS + 40 },+ (_, at) => `src/f${String(at).padStart(4, "0")}.ts`,+ );+ const service = yield* environmentViewedService(+ new Map(paths.map((path) => [path, "blob"] as const)),+ asked,+ );++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: paths.map((path) => ({ path, viewed: true })),+ });+ const read = yield* service.filesViewed(GITLAB_REFERENCE);++ // Every mark read is a path held in a set and a map for as long as the caller holds the read,+ // per scope it is holding, so the rows are bounded rather than however many a reader has ever+ // ticked. The reader is told the count is short rather than shown a quietly clipped list.+ assert.lengthOf(read.files, PullRequestFilesViewed.MAX_FILES_VIEWED_ROWS);+ assert.strictEqual(read.truncated, true);+ }),+);++it.effect("records a press while the host is backing off", () =>+ Effect.gen(function* () {+ let viewerLookups = 0;+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ {+ ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []),+ getViewer: () =>+ Effect.sync(() => {+ viewerLookups += 1;+ return "bilal";+ }),+ // Backing off for the hour, so the pause outlives the ten minutes who is signed in is+ // held for and the second press has to ask again while it is on.+ getFileRevisions: () =>+ Effect.fail(+ new PullRequestProviderError({+ provider: "gitlab",+ operation: "getFileRevisions",+ reason: "rate-limited",+ detail: "API rate limit exceeded.",+ retryAt: 60 * 60 * 1_000,+ }),+ ),+ },+ ],+ });++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ yield* TestClock.adjust("11 minutes");+ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/b.ts", viewed: true }],+ });++ // Nothing about a host holding its reads off says the reader did not press these, and these+ // rows are this environment's own. They keep no baseline, because none was read, so they hold+ // until they are pressed again rather than reporting a staleness nobody looked up.+ assert.deepStrictEqual(+ [...(yield* service.filesViewed(GITLAB_REFERENCE)).files].toSorted((left, right) =>+ left.path.localeCompare(right.path),+ ),+ [+ { path: "src/a.ts", state: "viewed" },+ { path: "src/b.ts", state: "viewed" },+ ],+ );+ assert.strictEqual(viewerLookups, 2);+ }),+);++it.effect("asks who is reading through a pause only for the press that is waiting on it", () =>+ Effect.gen(function* () {+ let viewerLookups = 0;+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ {+ ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []),+ getViewer: () =>+ Effect.sync(() => {+ viewerLookups += 1;+ return "bilal";+ }),+ listChangeRequests: () =>+ Effect.succeed({ items: [], truncated: false, continues: true }),+ // Backing off for the hour, so the pause outlives the ten minutes who is signed in is+ // held for.+ getFileRevisions: () =>+ Effect.fail(+ new PullRequestProviderError({+ provider: "gitlab",+ operation: "getFileRevisions",+ reason: "rate-limited",+ detail: "API rate limit exceeded.",+ retryAt: 60 * 60 * 1_000,+ }),+ ),+ },+ ],+ });++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ assert.strictEqual(viewerLookups, 1);+ yield* TestClock.adjust("11 minutes");++ // A listing is not the reader waiting on this lookup, and a failed one is held nowhere, so+ // letting it through would spawn the host's CLI on every refresh for as long as the pause+ // lasts and re-extend it each time.+ const listed = yield* Effect.flip(service.list({ state: "open", involvement: "all" }));+ assert.strictEqual(listed._tag, "PullRequestOperationError");+ assert.strictEqual(viewerLookups, 1);++ // The press is bounded by what the reader does, and its rows are keyed by who they are, so+ // it is asked rather than refused.+ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/b.ts", viewed: true }],+ });+ assert.strictEqual(viewerLookups, 2);+ }),+);++it.effect("does not ask a paused host who is reading again after the ask failed", () =>+ Effect.gen(function* () {+ let viewerLookups = 0;+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ {+ ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []),+ getViewer: () =>+ Effect.suspend(() => {+ viewerLookups += 1;+ return Effect.fail(+ new PullRequestProviderError({+ provider: "gitlab",+ operation: "getViewer",+ reason: "failed",+ detail: "glab exited with status 1",+ }),+ );+ }),+ listChangeRequests: () =>+ Effect.succeed({ items: [], truncated: false, continues: true }),+ runAction: () =>+ Effect.fail(+ new PullRequestProviderError({+ provider: "gitlab",+ operation: "runAction",+ reason: "rate-limited",+ detail: "API rate limit exceeded.",+ retryAt: 60 * 60 * 1_000,+ }),+ ),+ },+ ],+ });++ yield* Effect.flip(service.filesViewed(GITLAB_REFERENCE));+ assert.strictEqual(viewerLookups, 1);+ yield* Effect.flip(service.runAction({ ...GITLAB_REFERENCE, action: "merge" }));++ // A failed lookup is held nowhere, so a background read let through the pause would spawn the+ // host's CLI on every refresh for as long as the pause lasted, and re-extend it each time.+ yield* Effect.flip(service.list({ state: "open", involvement: "all" }));+ yield* TestClock.adjust("11 minutes");+ yield* Effect.flip(service.list({ state: "open", involvement: "all" }));+ assert.strictEqual(viewerLookups, 1);+ }),+);++it.effect("refuses the marks when the host could not be asked who is reading", () =>+ Effect.gen(function* () {+ let answering = true;+ const service = yield* environmentViewedServiceWithViewer(+ new Map([["src/a.ts", "blob-a"]]),+ () =>+ answering+ ? Effect.succeed("bilal")+ : Effect.fail(+ new PullRequestProviderError({+ provider: "gitlab",+ operation: "getViewer",+ reason: "failed",+ detail: "glab exited with status 1",+ }),+ ),+ );++ yield* service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/a.ts", viewed: true }],+ });+ // Who is signed in is held for ten minutes, so the lookup has to come round again before a+ // failing CLI can reach the read at all.+ answering = false;+ yield* TestClock.adjust("11 minutes");++ // Answering these from the unnamed reader's rows would show the reader none of their own+ // ticks, and file the next press where the recovered CLI will never look for it again.+ const read = yield* Effect.flip(service.filesViewed(GITLAB_REFERENCE));+ const write = yield* Effect.flip(+ service.setFilesViewed({+ ...GITLAB_REFERENCE,+ files: [{ path: "src/b.ts", viewed: true }],+ }),+ );+ assert.strictEqual(read._tag, "PullRequestOperationError");+ assert.strictEqual(write._tag, "PullRequestOperationError");++ answering = true;+ assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [+ { path: "src/a.ts", state: "viewed" },+ ]);+ }),+);++it.effect("refuses to track viewed files on a host that does not", () =>+ Effect.gen(function* () {+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: "gitlab",+ }),+ ],+ providers: [+ fakeProvider("gitlab", {+ getFilesViewed: () => Effect.die("must not be called"),+ setFilesViewed: () => Effect.die("must not be called"),+ }),+ ],+ });+ const reference = { projectId: "p1" as ProjectId, repository: "group/project", number: 1 };++ const read = yield* Effect.flip(service.filesViewed(reference));+ const write = yield* Effect.flip(+ service.setFilesViewed({ ...reference, files: [{ path: "a.ts", viewed: true }] }),+ );++ assert.strictEqual(read._tag, "PullRequestOperationError");+ assert.strictEqual(write._tag, "PullRequestOperationError");+ }),+);+it.effect("keeps Azure continuation cursors separate for repositories with the same name", () =>Effect.gen(function* () {const seen: string[] = [];diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex 7cb33a4b3da..f1369c21d41 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -3,6 +3,7 @@ import {isSshRemoteUrl,sourceControlRepositorySelector,} from "@t3tools/shared/sourceControl";+import { normalizeGitRemoteUrl } from "@t3tools/shared/git";import * as Cache from "effect/Cache";import * as Clock from "effect/Clock";import * as Context from "effect/Context";@@ -35,6 +36,7 @@ import {type PullRequestDiffFileContentsResult,type PullRequestDiffStat,type PullRequestDiffInput,+ type PullRequestFilesViewedResult,type PullRequestDiffResult,type PullRequestInvalidateInput,type PullRequestListEntry,@@ -55,6 +57,7 @@ import {type PullRequestReviewerRequestInput,type PullRequestLabelCandidateList,type PullRequestLabelChangeInput,+ type PullRequestSetFilesViewedInput,type PullRequestSubmitReviewInput,PullRequestStack,PullRequestSummary,@@ -70,6 +73,7 @@ import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceimport { AllowGitHubReserve } from "../sourceControl/GitHubCli.ts";import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";+import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";import {@@ -80,6 +84,7 @@ import {} from "./PullRequestProvider.ts";import * as PullRequestReadCache from "./PullRequestReadCache.ts";import { PullRequestProviderRegistry } from "./PullRequestProviderRegistry.ts";+import * as ViewedFiles from "./pullRequestViewedFiles.ts";export interface PullRequestMergeEvent extends PullRequestRef {readonly mergedAt: string;@@ -128,6 +133,12 @@ const DIFF_CACHE_TTL = Duration.seconds(60);const COMMIT_DIFF_CACHE_TTL = Duration.minutes(10);/** Sized like the client's own stale time; a row's counts move only when somebody pushes. */const LIST_STATS_CACHE_TTL = Duration.seconds(60);+/**+ * Short, and with no stale window behind it: this is the reader's own bookkeeping, and the+ * press that changes it is the same press the page is already showing optimistically. Held at+ * all only so opening a change request on two devices costs one read.+ */+const FILES_VIEWED_CACHE_TTL = Duration.seconds(15);/** A diff can stay interactive while its next cached value is fetched off the critical path. */const DIFF_STALE_WINDOW = Duration.minutes(10);/** How long one host's signed-in login is believed without asking its CLI again. */@@ -139,6 +150,7 @@ const LIST_CACHE_CAPACITY = 64;const LIST_STATS_CACHE_CAPACITY = 32;const DETAIL_CACHE_CAPACITY = 128;const DIFF_CACHE_CAPACITY = 128;+const FILES_VIEWED_CACHE_CAPACITY = 128;const VIEWER_CACHE_CAPACITY = 32;export type PullRequestError = PullRequestUnavailableError | PullRequestOperationError;@@ -202,6 +214,12 @@ export class PullRequestService extends Context.Service<readonly diffFileContents: (input: PullRequestDiffFileContentsInput,) => Effect.Effect<PullRequestDiffFileContentsResult, PullRequestError>;+ readonly filesViewed: (+ input: PullRequestRef,+ ) => Effect.Effect<PullRequestFilesViewedResult, PullRequestError>;+ readonly setFilesViewed: (+ input: PullRequestSetFilesViewedInput,+ ) => Effect.Effect<void, PullRequestError>;readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;@@ -281,13 +299,18 @@ const REVIEWER_REQUEST_REFUSAL = "You need write access on this repository to asconst LABEL_CHANGE_REFUSAL = "You need triage access on this repository to change its labels.";/** A project this page can read: its remote is on a host with an implementation. */-interface SupportedProject {+export interface SupportedProject {readonly cursorKey: string;readonly project: OrchestrationProjectShell;readonly api: PullRequestProviderApi;readonly repository: string;/** The host the repository lives on, which is the account boundary rather than the kind. */readonly host: string;+ /**+ * The identity's canonical key, which is what this environment's own records are keyed by.+ * Unique where `repository` is not: Azure's is a bare name that repeats across an organisation.+ */+ readonly remote: string;}/**@@ -448,6 +471,7 @@ function withRateLimitBackoff(api: PullRequestProviderApi,host: string,limits: SourceControlRateLimit.SourceControlRateLimit["Service"],+ options?: { readonly viewerAllowsPause: boolean },): PullRequestProviderApi {const key = { provider: api.kind, host };const protect = <A>(@@ -499,7 +523,13 @@ function withRateLimitBackoff(const wrapped = {kind: api.kind,capabilities: api.capabilities,- getViewer: wrap("getViewer", api.getViewer),+ // Refused during a pause like any other read, except for the caller that asks for the+ // bypass: a lookup that failed is not held, so letting every background read through would+ // spawn this host's CLI on each of them and re-extend the pause it was already in.+ getViewer:+ options?.viewerAllowsPause === true+ ? interactive("getViewer", api.getViewer)+ : wrap("getViewer", api.getViewer),...(api.getRoutingIdentity === undefined ? {} : { getRoutingIdentity: api.getRoutingIdentity }),...(api.withVerifiedCredential === undefined? {}@@ -535,6 +565,15 @@ function withRateLimitBackoff(...(api.getDiffFileContents === undefined? {}: { getDiffFileContents: wrap("getDiffFileContents", api.getDiffFileContents) }),+ ...(api.getFilesViewed === undefined+ ? {}+ : { getFilesViewed: wrap("getFilesViewed", api.getFilesViewed) }),+ ...(api.setFilesViewed === undefined+ ? {}+ : { setFilesViewed: interactive("setFilesViewed", api.setFilesViewed) }),+ ...(api.getFileRevisions === undefined+ ? {}+ : { getFileRevisions: wrap("getFileRevisions", api.getFileRevisions) }),runAction: interactive("runAction", api.runAction),...(api.updateChangeRequest === undefined? {}@@ -568,6 +607,7 @@ export const make = Effect.gen(function* () {const projections = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;const rateLimits = yield* SourceControlRateLimit.SourceControlRateLimit;+ const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository;const readCache = yield* PullRequestReadCache.PullRequestReadCache;const refineUnknownProjectKinds = (@@ -727,6 +767,10 @@ export const make = Effect.gen(function* () {api: withRateLimitBackoff(api, host, rateLimits),repository,host,+ remote:+ kind === "azure-devops"+ ? identity.canonicalKey+ : normalizeGitRemoteUrl(`https://${host}/${repository}`),});}return { supported, unimplemented, viewerRoots };@@ -793,7 +837,14 @@ export const make = Effect.gen(function* () {);}return Effect.succeed(- route.api.kind === "azure-devops" ? route : { ...route, repository },+ route.api.kind === "azure-devops" ||+ route.repository.toLowerCase() === repository.toLowerCase()+ ? route+ : {+ ...route,+ repository,+ remote: normalizeGitRemoteUrl(`https://${host}/${repository}`),+ },);}),);@@ -890,7 +941,10 @@ export const make = Effect.gen(function* () {if (registered === null) {return Effect.die(new Error(`Missing pull request provider: ${kind}`));}- const api = withRateLimitBackoff(registered, host, rateLimits);+ // Let through a pause: a press the reader is waiting on has to be answered, and the+ // callers that are not that press are held back at the gate below instead, before they+ // reach this lookup at all.+ const api = withRateLimitBackoff(registered, host, rateLimits, { viewerAllowsPause: true });return Effect.firstSuccessOf(roots.map((cwd) => api.getViewer({ cwd, host }))).pipe(Effect.map((viewer) => ({host,@@ -923,6 +977,7 @@ export const make = Effect.gen(function* () {const resolveViewers = (projects: ReadonlyArray<SupportedProject>,viewerRoots: WorkspaceProjects["viewerRoots"],+ options?: { readonly allowPaused: boolean },) =>Effect.forEach([...new Set(projects.map(({ host }) => host))],@@ -938,8 +993,33 @@ export const make = Effect.gen(function* () {// unreadable worktree would otherwise report the whole host as signed out.const roots =viewerRoots.get(host) ?? forHost.map(({ project }) => project.workspaceRoot);+ // Nothing about the caller is in the key. A listing and a press for the same host and+ // roots are the same lookup, and putting them on separate flights would spawn two of+ // this host's CLIs on a cold page load, which is the coalescing this exists for.const key = JSON.stringify([host, api.kind, [...new Set(roots)].sort()]);- return Cache.get(viewerFlights, key);+ if (options?.allowPaused === true) return Cache.get(viewerFlights, key);+ // The pause is checked here rather than inside the lookup, so that it holds back the+ // callers nobody is waiting on without splitting the flight they share with a press.+ // A failed lookup is held nowhere, so letting a background read through would spawn+ // this host's CLI on every refresh for as long as the pause lasted, and re-extend it.+ return rateLimits.check({ provider: api.kind, host }).pipe(+ Effect.flatMap(() => Cache.get(viewerFlights, key)),+ Effect.catch((error) =>+ Effect.succeed<ResolvedViewer>({+ host,+ kind: api.kind,+ viewer: null,+ error: new PullRequestProviderError({+ provider: api.kind,+ operation: "getViewer",+ reason: "rate-limited",+ detail: error.detail,+ retryAt: error.retryAt,+ cause: error,+ }),+ }),+ ),+ );}),{ concurrency: REPOSITORY_CONCURRENCY },);@@ -1697,6 +1777,43 @@ export const make = Effect.gen(function* () {}),);+ const context = yield* Effect.context<never>();+ /** Runs a refresh as its own fiber, for the reads that answer from a held value first. */+ const runFork = Effect.runForkWith(context);++ /**+ * Who the host says the reader is, for the paths whose rows are keyed by it. A lookup that+ * failed is refused rather than answered as the unnamed reader: a momentarily signed-out CLI+ * would otherwise hide every tick this reader has made and file the next press under rows that+ * are orphaned once it recovers. The reader is waiting on every one of these paths, so the+ * lookup is let through a host's backoff rather than turning a pause into a refusal, and only+ * here, where the bypass is bounded by what the reader does.+ */+ const requiredViewerOf = (+ project: SupportedProject,+ operation: string,+ ): Effect.Effect<string | null, PullRequestError> =>+ resolveViewers([project], new Map(), { allowPaused: true }).pipe(+ Effect.flatMap(([resolved]) => {+ const error = resolved?.error ?? null;+ return error === null+ ? Effect.succeed(resolved?.viewer ?? null)+ : Effect.fail(toPullRequestError(operation)(error));+ }),+ );++ const setFilesViewed: PullRequestService["Service"]["setFilesViewed"] = (input) =>+ canonicalRef(input).pipe(+ Effect.flatMap((ref) =>+ viewedFiles.setFilesViewed(input).pipe(+ // Deliberately not `invalidatedByMutation`: ticking a file off says nothing about the+ // change request, and dropping a 300-file diff on every checkbox is the whole cost of+ // the feature. Only this reader's own bookkeeping is forgotten.+ Effect.tap(() => Effect.sync(() => bumpFilesViewedEpoch(ref))),+ ),+ ),+ );+const runAction = (input: PullRequestActionInput): Effect.Effect<string, PullRequestError> =>requireProject(input).pipe(Effect.flatMap((project): Effect.Effect<string, PullRequestError> => {@@ -2334,8 +2451,6 @@ export const make = Effect.gen(function* () {return { stats: stats.flat() };});- const context = yield* Effect.context<never>();- const runFork = Effect.runForkWith(context);const revalidate = <A, E>(read: Effect.Effect<A, E>) =>Effect.context<never>().pipe(Effect.flatMap((caller) =>@@ -2494,14 +2609,34 @@ export const make = Effect.gen(function* () {if (oldest !== undefined) recentStats.delete(oldest);}};- const bumpRefEpoch = (ref: PullRequestRef) => {+ const bumpEpoch = (epochs: Map<string, number>, ref: PullRequestRef) => {const scope = refScope(ref);- if (!refEpochs.has(scope) && refEpochs.size >= REF_EPOCH_CAPACITY) {- const oldest = refEpochs.keys().next().value;- if (oldest !== undefined) refEpochs.delete(oldest);+ if (!epochs.has(scope) && epochs.size >= REF_EPOCH_CAPACITY) {+ const oldest = epochs.keys().next().value;+ if (oldest !== undefined) epochs.delete(oldest);}- refEpochs.set(scope, ++epochCounter);+ epochs.set(scope, ++epochCounter);};+ const bumpRefEpoch = (ref: PullRequestRef) => bumpEpoch(refEpochs, ref);+ // Its own scope, so a press forgets the reader's ticks and nothing else. The read's key+ // carries both epochs, which is what makes an ordinary refresh re-ask for these too.+ const filesViewedEpochs = new Map<string, number>();+ const filesViewedEpoch = (ref: PullRequestRef) => filesViewedEpochs.get(refScope(ref)) ?? 0;+ const bumpFilesViewedEpoch = (ref: PullRequestRef) => bumpEpoch(filesViewedEpochs, ref);++ /** Bumped by a whole-workspace refresh, the one drop no single reference's epoch covers. */+ let everyFileRevisionEpoch = 0;+ // Built after the epochs because it reads two of them: taken as an argument any higher,+ // `refEpoch` would be read while its `const` was still in its dead zone and this would throw.+ const viewedFiles = ViewedFiles.make({+ filesViewedStore,+ requireProject,+ requiredViewerOf,+ toPullRequestError,+ runFork,+ refEpoch,+ fileRevisionsEpoch: () => everyFileRevisionEpoch,+ });/** The positional filter slot of a cache key, back as the record `listUncached` takes. */const filtersOfKey = (@@ -2785,6 +2920,25 @@ export const make = Effect.gen(function* () {return staleDiff(key, Cache.get(diffCache, key));};+ const filesViewedCache = yield* Cache.makeWith(+ (key: string) => {+ const [referenceKey] = JSON.parse(key) as [string, number];+ return viewedFiles.filesViewed(refOfCacheKey(referenceKey));+ },+ {+ capacity: FILES_VIEWED_CACHE_CAPACITY,+ timeToLive: (exit) => (Exit.isSuccess(exit) ? FILES_VIEWED_CACHE_TTL : Duration.zero),+ },+ );+ // Canonicalised before it is keyed: both epochs are bumped against the remote's own spelling,+ // so a reference keyed as the client spelled it would never see a refresh or a press.+ const filesViewed: PullRequestService["Service"]["filesViewed"] = (input) =>+ canonicalRef(input).pipe(+ Effect.flatMap((ref) =>+ Cache.get(filesViewedCache, JSON.stringify([refCacheKey(ref), filesViewedEpoch(ref)])),+ ),+ );+const listStatsCache = yield* Cache.makeWith((key: string) => {const [, refs] = JSON.parse(key) as [number, ReadonlyArray<[string, string, number, number]>];@@ -2846,6 +3000,14 @@ export const make = Effect.gen(function* () {"PullRequestService.invalidate",)(function* (input, options) {const reference = input.reference;+ if (input.filesViewedOnly === true) {+ return yield* reference === undefined+ ? Cache.invalidateAll(filesViewedCache)+ : canonicalRef(reference).pipe(+ Effect.flatMap((ref) => Effect.sync(() => bumpFilesViewedEpoch(ref))),+ Effect.ignore,+ );+ }if (reference !== undefined) {yield* canonicalRef(reference).pipe(Effect.flatMap((ref) =>@@ -2857,6 +3019,7 @@ export const make = Effect.gen(function* () {);} else {listingsEpoch = ++epochCounter;+ everyFileRevisionEpoch = ++epochCounter;viewersByHost.clear();yield* Cache.invalidateAll(viewerFlights);}@@ -2971,6 +3134,8 @@ export const make = Effect.gen(function* () {threadComments,diff: credentialCached(diff),diffFileContents,+ filesViewed: credentialCached(filesViewed),+ setFilesViewed,runAction: runActionAndInvalidate,update: invalidatedByMutation(update),comment: invalidatedByMutation(comment),diff --git a/apps/server/src/pullRequest/azureDevOpsDiff.test.ts b/apps/server/src/pullRequest/azureDevOpsDiff.test.tsnew file mode 100644index 00000000000..30d57575519--- /dev/null+++ b/apps/server/src/pullRequest/azureDevOpsDiff.test.ts@@ -0,0 +1,459 @@+import { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";+import { describe, expect, it } from "vite-plus/test";++import {+ azureDevOpsFilePatch,+ azureDevOpsUnreadableFilePatch,+ byteLength,+ formatAzureDevOpsDiffCursor,+ MAX_FILE_DIFF_EDITS,+ parseAzureDevOpsDiffCursor,+} from "./azureDevOpsDiff.ts";+import type { AzureDevOpsChangeEntry } from "./azureDevOpsPullRequestJson.ts";++function change(overrides: Partial<AzureDevOpsChangeEntry> = {}): AzureDevOpsChangeEntry {+ return {+ path: "README.md",+ oldPath: "README.md",+ changeKind: "change",+ objectId: "8f80",+ originalObjectId: "0ca4",+ ...overrides,+ };+}++function texts(oldContents: string, newContents: string, binary = false) {+ return { oldContents, newContents, binary };+}++describe("azureDevOpsFilePatch", () => {+ it("writes a changed file as the unified patch every diff viewer already reads", () => {+ const patch = azureDevOpsFilePatch({+ change: change(),+ texts: texts("one\ntwo\nthree\n", "one\ntwo again\nthree\n"),+ });++ expect(patch.truncated).toBe(false);+ expect(patch.section).toBe(+ [+ "diff --git a/README.md b/README.md",+ "--- a/README.md",+ "+++ b/README.md",+ "@@ -1,3 +1,3 @@",+ " one",+ "-two",+ "+two again",+ " three",+ "",+ ].join("\n"),+ );+ });++ it("names the side a new file does not have as /dev/null", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "DEMO.md", oldPath: "DEMO.md", changeKind: "new" }),+ texts: texts("", "hello\n"),+ });++ expect(patch.section).toContain("new file mode 100644");+ expect(patch.section).toContain("--- /dev/null");+ expect(patch.section).toContain("+++ b/DEMO.md");+ // Git points the range a new file does not have at line zero, not at line one.+ expect(patch.section).toContain("@@ -0,0 +1 @@");+ expect(patch.section).toContain("+hello");+ });++ it("names the side a deleted file no longer has as /dev/null", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "OLD.md", oldPath: "OLD.md", changeKind: "deleted" }),+ texts: texts("gone\n", ""),+ });++ expect(patch.section).toContain("deleted file mode 100644");+ expect(patch.section).toContain("--- a/OLD.md");+ expect(patch.section).toContain("+++ /dev/null");+ expect(patch.section).toContain("@@ -1 +0,0 @@");+ expect(patch.section).toContain("-gone");+ });++ it("keeps the carriage returns of a file with Windows line endings", () => {+ // They are part of the line rather than around it, so a patch that dropped them would ask+ // the reader to look at a change that is not the one on the host.+ const patch = azureDevOpsFilePatch({+ change: change(),+ texts: texts("one\r\ntwo\r\n", "one\r\ntwo again\r\n"),+ });++ expect(patch.section).toContain("-two\r");+ expect(patch.section).toContain("+two again\r");+ });++ it("keeps a file that only moved, which has no hunks to give", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "docs/new.md", oldPath: "docs/old.md", changeKind: "rename-pure" }),+ texts: texts("same\n", "same\n"),+ });++ expect(patch.truncated).toBe(false);+ expect(patch.section).toBe(+ [+ "diff --git a/docs/old.md b/docs/new.md",+ "rename from docs/old.md",+ "rename to docs/new.md",+ "--- a/docs/old.md",+ "+++ b/docs/new.md",+ "",+ ].join("\n"),+ );+ });++ it("reports a binary file as changed rather than spelling it out", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "logo.png", oldPath: "logo.png" }),+ texts: texts("PNG\u0000old", "PNG\u0000new"),+ });++ expect(patch.truncated).toBe(true);+ expect(patch.section).toContain("Binary files a/logo.png and b/logo.png differ");+ });++ it("shows an overlong file as changed without its hunks", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "bundle.js", oldPath: "bundle.js" }),+ texts: texts("a\n".repeat(400_000), "b\n".repeat(400_000)),+ });++ expect(patch.truncated).toBe(true);+ expect(patch.section).toBe(+ ["diff --git a/bundle.js b/bundle.js", "--- a/bundle.js", "+++ b/bundle.js", ""].join("\n"),+ );+ });++ it("takes the host's word that a file is binary, whatever its bytes look like", () => {+ // Azure hands such a file over base64-encoded, so nothing in the text it sent gives it away.+ const patch = azureDevOpsFilePatch({+ change: change({ path: "logo.png", oldPath: "logo.png" }),+ texts: texts("b2xk", "bmV3", true),+ });++ expect(patch.truncated).toBe(true);+ expect(patch.section).toContain("Binary files a/logo.png and b/logo.png differ");+ });++ it("counts an overlong file in bytes rather than in characters", () => {+ // Three bytes each, so a ceiling counted in code units would let three times the size through.+ const patch = azureDevOpsFilePatch({+ change: change({ path: "notes.md", oldPath: "notes.md" }),+ texts: texts("\u4e00".repeat(200_000), "\u4e8c".repeat(200_000)),+ });++ expect(patch.truncated).toBe(true);+ expect(patch.section).toBe(+ ["diff --git a/notes.md b/notes.md", "--- a/notes.md", "+++ b/notes.md", ""].join("\n"),+ );+ });++ const lineRange = (count: number, prefix: string) =>+ Array.from({ length: count }, (_, line) => `${prefix} ${line}`).join("\n");++ it("lists a file too far apart to diff without its hunks", () => {+ // Sharing no line at all costs one edit per line on each side, so this pair is twice the+ // ceiling apart. Left to itself the search costs about the square of that and would hold the+ // whole server, every websocket client with it, while it worked out a patch nobody reads.+ // Writing both sides out instead would read as a genuine rewrite: the ceiling is a distance+ // rather than a proportion, so a long file reaches it having changed in one corner, and that+ // corner would be buried in a wall of red and green.+ const lines = (prefix: string) =>+ Array.from({ length: MAX_FILE_DIFF_EDITS }, (_, line) => `${prefix} ${line}`).join("\n");+ const patch = azureDevOpsFilePatch({+ change: change({ path: "generated.ts", oldPath: "generated.ts" }),+ texts: texts(`${lines("old")}\n`, `${lines("new")}\n`),+ });++ expect(patch.truncated).toBe(true);+ // And it says the search was given up on, because the reader of a run of files is meant to+ // stop rather than spend that work again on each of the ones behind it.+ expect(patch.abandoned).toBe(true);+ expect(patch.section).toBe(+ [+ "diff --git a/generated.ts b/generated.ts",+ "--- a/generated.ts",+ "+++ b/generated.ts",+ "",+ ].join("\n"),+ );+ });++ it("writes out a wholly new file however many lines it has", () => {+ // Nothing on the old side means there was no edit distance to search out, so this is the+ // minimal patch and not a stand-in for one. Fifteen thousand lines of thirty bytes is the+ // shape this used to lose: inside the byte ceiling that gates every file, and well past every+ // bound a two-sided file answers to, none of which is protecting against anything here.+ const contents = `${Array.from({ length: 15_000 }, () => "x".repeat(29)).join("\n")}\n`;+ const patch = azureDevOpsFilePatch({+ change: change({ path: "DEMO.md", oldPath: "DEMO.md", changeKind: "new" }),+ texts: texts("", contents),+ });++ expect(byteLength(contents)).toBeLessThan(512 * 1024);+ expect(patch.truncated).toBe(false);+ expect(patch.abandoned).toBe(false);+ expect(patch.edits).toBe(15_000);+ expect(patch.section).toContain("@@ -0,0 +1,15000 @@");+ // Only the `+++` of the header on top of the file's own lines, so nothing was dropped out of+ // the middle.+ expect(patch.section.match(/^\+/gmu)).toHaveLength(15_001);+ });++ it("keeps a wholly new file too heavy to write out listed without its hunks", () => {+ // Every line carries a marker, so a side of very short lines answers with up to twice its own+ // bytes: these 200,000 one-character lines fit the ceiling each side is read under and weigh+ // about 600KB written out, more than twice what a whole slice may carry. There is no smaller+ // true patch for a creation to fall back to, so it is listed without its hunks, the same as a+ // side too big to read at all, rather than sent at a size the slice budget exists to prevent.+ const contents = `${Array.from({ length: 200_000 }, () => "x").join("\n")}\n`;+ const patch = azureDevOpsFilePatch({+ change: change({ path: "bundle.min.js", oldPath: "bundle.min.js", changeKind: "new" }),+ texts: texts("", contents),+ });++ expect(byteLength(contents)).toBeLessThan(512 * 1024);+ expect(patch.truncated).toBe(true);+ expect(patch.abandoned).toBe(false);+ // It still cost the walk over its lines, which is what the slice is charged for.+ expect(patch.edits).toBe(200_000);+ expect(patch.section).toBe(+ [+ "diff --git a/bundle.min.js b/bundle.min.js",+ "new file mode 100644",+ "--- /dev/null",+ "+++ b/bundle.min.js",+ "",+ ].join("\n"),+ );+ });++ it("writes out a wholly deleted file however many lines it had", () => {+ const contents = `${lineRange(20_000, "line")}\n`;+ const patch = azureDevOpsFilePatch({+ change: change({ path: "OLD.md", oldPath: "OLD.md", changeKind: "deleted" }),+ texts: texts(contents, ""),+ });++ expect(patch.truncated).toBe(false);+ expect(patch.abandoned).toBe(false);+ expect(patch.edits).toBe(20_000);+ expect(patch.section).toContain("@@ -1,20000 +0,0 @@");+ expect(patch.section.match(/^-line /gmu)).toHaveLength(20_000);+ expect(patch.section.match(/^-/gmu)).toHaveLength(20_001);+ });++ it("gives an empty new file no hunk to read", () => {+ // A file with nothing on either side has no lines to claim were replaced, and git writes it+ // as a header alone.+ const patch = azureDevOpsFilePatch({+ change: change({ path: "EMPTY.md", oldPath: "EMPTY.md", changeKind: "new" }),+ texts: texts("", ""),+ });++ expect(patch.edits).toBe(0);+ expect(patch.section).not.toContain("@@");+ });++ it("marks a wholly new file whose last line has no newline after it", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "NOTES.md", oldPath: "NOTES.md", changeKind: "new" }),+ texts: texts("", "one\ntwo"),+ });++ expect(patch.section).toBe(+ [+ "diff --git a/NOTES.md b/NOTES.md",+ "new file mode 100644",+ "--- /dev/null",+ "+++ b/NOTES.md",+ "@@ -0,0 +1,2 @@",+ "+one",+ "+two",+ "\\ No newline at end of file",+ "",+ ].join("\n"),+ );+ });++ it("keeps a file it did diff out of the giving up", () => {+ const patch = azureDevOpsFilePatch({+ change: change(),+ texts: texts("one\ntwo\n", "one\ntwo again\n"),+ });++ expect(patch.abandoned).toBe(false);+ });++ it("counts what the diff worked out, which is what the file cost to diff", () => {+ // The caller spends a budget of these across a slice, so they have to be the edits the search+ // actually made: one line replaced is a removal and an addition, and the three lines of+ // context around them cost nothing.+ const patch = azureDevOpsFilePatch({+ change: change(),+ texts: texts("one\ntwo\nthree\nfour\n", "one\ntwo again\nthree\nfour\n"),+ });++ expect(patch.edits).toBe(2);+ });++ it("counts nothing for a file it never diffed", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "logo.png", oldPath: "logo.png" }),+ texts: texts("PNG\u0000old", "PNG\u0000new"),+ });++ expect(patch.edits).toBe(0);+ });++ it("lists a file whose hunks outweigh its sides without them", () => {+ // A handful of very long lines is a few edits and nowhere near the edit ceiling, and the+ // patch carries both sides in full with three lines of context around each hunk, so the+ // section comes out heavier than either side was. What one file weighs is what a slice's+ // budget is spent in, so the edit ceiling alone does not bound this.+ const line = `${"a".repeat(400 * 1024)}\n`;+ const patch = azureDevOpsFilePatch({+ change: change({ path: "min.js", oldPath: "min.js" }),+ texts: texts(line, `${"b".repeat(400 * 1024)}\n`),+ });++ expect(patch.edits).toBeLessThan(MAX_FILE_DIFF_EDITS);+ expect(patch.truncated).toBe(true);+ expect(patch.section).toBe(+ ["diff --git a/min.js b/min.js", "--- a/min.js", "+++ b/min.js", ""].join("\n"),+ );+ expect(byteLength(patch.section)).toBeLessThan(byteLength(line));+ });++ it("marks a file that does not end in a newline, as git does", () => {+ const patch = azureDevOpsFilePatch({+ change: change(),+ texts: texts("one\n", "two"),+ });++ expect(patch.section).toContain("\\ No newline at end of file");+ });+});++describe("azureDevOpsUnreadableFilePatch", () => {+ it("keeps a file the host would not hand over, listed without its hunks", () => {+ const patch = azureDevOpsUnreadableFilePatch(change({ path: "huge.bin", oldPath: "huge.bin" }));++ expect(patch.truncated).toBe(true);+ expect(patch.section).toBe(+ ["diff --git a/huge.bin b/huge.bin", "--- a/huge.bin", "+++ b/huge.bin", ""].join("\n"),+ );+ });+});++describe("a file Azure names something a patch header cannot carry plainly", () => {+ it("writes each side as git's quoted form, the side letter inside the quotes", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "notes\treadme.md", oldPath: "notes\treadme.md" }),+ texts: texts("one\n", "two\n"),+ });++ expect(patch.section).toBe(+ [+ 'diff --git "a/notes\\treadme.md" "b/notes\\treadme.md"',+ '--- "a/notes\\treadme.md"',+ '+++ "b/notes\\treadme.md"',+ "@@ -1 +1 @@",+ "-one",+ "+two",+ "",+ ].join("\n"),+ );+ });++ it("keeps a name holding a newline on the one header line it belongs to", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "line\nfile.txt", oldPath: "line\nfile.txt" }),+ texts: texts("one\n", "two\n"),+ });++ // Written as itself the name would start a line of its own, and a reader would take what+ // followed for a header the patch never had.+ expect(patch.section.split("\n").slice(0, 3)).toEqual([+ 'diff --git "a/line\\nfile.txt" "b/line\\nfile.txt"',+ '--- "a/line\\nfile.txt"',+ '+++ "b/line\\nfile.txt"',+ ]);+ });++ it("quotes the names a rename states, which carry no side letter", () => {+ const patch = azureDevOpsFilePatch({+ change: change({+ path: "docs/new\tname.md",+ oldPath: "docs/old\tname.md",+ changeKind: "rename-pure",+ }),+ texts: texts("same\n", "same\n"),+ });++ expect(patch.section).toBe(+ [+ 'diff --git "a/docs/old\\tname.md" "b/docs/new\\tname.md"',+ 'rename from "docs/old\\tname.md"',+ 'rename to "docs/new\\tname.md"',+ '--- "a/docs/old\\tname.md"',+ '+++ "b/docs/new\\tname.md"',+ "",+ ].join("\n"),+ );+ });++ it("quotes the sides of the one line a binary file gets", () => {+ const patch = azureDevOpsFilePatch({+ change: change({ path: "logo\tmark.png", oldPath: "logo\tmark.png" }),+ texts: texts("PNG\u0000old", "PNG\u0000new"),+ });++ expect(patch.section).toContain(+ 'Binary files "a/logo\\tmark.png" and "b/logo\\tmark.png" differ',+ );+ });++ it("hands a reader of the header back the name Azure gave", () => {+ const path = 'every\t\n"kind"\\of.md';+ const patch = azureDevOpsFilePatch({+ change: change({ path, oldPath: path }),+ texts: texts("one\n", "two\n"),+ });+ const [header, oldLine, newLine] = patch.section.split("\n");++ expect(header).not.toContain("\t");+ expect(unquoteGitPatchPath(oldLine?.slice(4) ?? "")).toBe(`a/${path}`);+ expect(unquoteGitPatchPath(newLine?.slice(4) ?? "")).toBe(`b/${path}`);+ });+});++describe("a diff cursor", () => {+ it("carries the push it was taken against back to the next slice", () => {+ const cursor = formatAzureDevOpsDiffCursor({ iterationId: 3, fileIndex: 12 });++ expect(parseAzureDevOpsDiffCursor(cursor)).toEqual({ iterationId: 3, fileIndex: 12 });+ });++ it("reads anything it did not write as no position at all", () => {+ // Which starts the read from the top rather than failing it: a cursor is the client's to+ // hand back, and nothing downstream is worth refusing a whole diff over.+ for (const raw of [undefined, null, "", "abc", "1", "0:4", "1:-2", "1:2:3"]) {+ expect(parseAzureDevOpsDiffCursor(raw)).toBeNull();+ }+ });++ it("refuses a half it did not write rather than reading it as the first file", () => {+ // `Number` is wider than the cursor: an empty, padded or hex half would otherwise pass as a+ // position, and the read would resume against an iteration the client never saw instead of+ // starting again from the latest one.+ for (const raw of ["1:", ":4", "1: ", " 1:4", "1:0x2", "0x1:2", "1e2:0", "1:4.0"]) {+ expect(parseAzureDevOpsDiffCursor(raw)).toBeNull();+ }+ });+});diff --git a/apps/server/src/pullRequest/azureDevOpsDiff.ts b/apps/server/src/pullRequest/azureDevOpsDiff.tsnew file mode 100644index 00000000000..aa5323c32fa--- /dev/null+++ b/apps/server/src/pullRequest/azureDevOpsDiff.ts@@ -0,0 +1,273 @@+import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";+import { structuredPatch } from "diff";++import type { AzureDevOpsChangeEntry } from "./azureDevOpsPullRequestJson.ts";++/**+ * How far a diff read got, and which push it was reading. Azure hangs a pull request's changed+ * files off an iteration, so a push landing mid-read would renumber the list under a cursor that+ * did not also pin the iteration.+ */+export interface AzureDevOpsDiffCursor {+ readonly iterationId: number;+ readonly fileIndex: number;+}++const CURSOR_SEPARATOR = ":";++/**+ * Restricts each half to plain decimal, so `Number` cannot read a foreign cursor's `0x3` as+ * three.+ */+const CURSOR_COMPONENT = /^\d+$/;++export function formatAzureDevOpsDiffCursor(cursor: AzureDevOpsDiffCursor): string {+ return `${cursor.iterationId}${CURSOR_SEPARATOR}${cursor.fileIndex}`;+}++/** Null for anything this did not write, which starts the read from the top rather than failing. */+export function parseAzureDevOpsDiffCursor(+ raw: string | null | undefined,+): AzureDevOpsDiffCursor | null {+ if (raw === null || raw === undefined) return null;+ const [iteration, file, ...rest] = raw.split(CURSOR_SEPARATOR);+ if (rest.length > 0) return null;+ if (iteration === undefined || file === undefined) return null;+ if (!CURSOR_COMPONENT.test(iteration) || !CURSOR_COMPONENT.test(file)) return null;+ const iterationId = Number(iteration);+ const fileIndex = Number(file);+ if (!Number.isSafeInteger(iterationId) || iterationId <= 0) return null;+ if (!Number.isSafeInteger(fileIndex) || fileIndex < 0) return null;+ return { iterationId, fileIndex };+}++/** The two texts of one changed file, empty on whichever side the change does not have. */+export interface AzureDevOpsFileTexts {+ readonly oldContents: string;+ readonly newContents: string;+ /** Azure's own flag for a file it hands back base64-encoded instead of as text. */+ readonly binary: boolean;+}++export interface AzureDevOpsFilePatch {+ readonly section: string;+ /** The file changed but its hunks are not in the section, so the patch has a hole in it. */+ readonly truncated: boolean;+ /**+ * The diff was given up on partway, having spent the whole edit budget, so a caller reading a+ * run of files stops here rather than paying that again for each one behind it.+ */+ readonly abandoned: boolean;+ /**+ * Lines added or removed, which is the edit distance the diff had to search out, and what a+ * slice's budget is spent in: a file of short lines is cheap on the wire and dear to diff.+ */+ readonly edits: number;+}++/**+ * Beyond this a file is shown as changed without its hunks. Azure hands back whole files rather+ * than a patch, so an oversize file is paid for twice over before anything can be diffed.+ */+const MAX_FILE_BYTES = 512 * 1024;++/** Git's own default, and what the hunks from this repo's other hosts are already cut to. */+const PATCH_CONTEXT_LINES = 3;++/**+ * How far apart one file's two sides may be before it is listed without its hunks. The line diff+ * costs about the square of the edit distance, so an unbounded pair sharing almost nothing could+ * hold the whole server. Bounded in edits rather than milliseconds so a change slices the same+ * way on every machine.+ */+export const MAX_FILE_DIFF_EDITS = 2_000;++/**+ * A backstop for a machine slower than the edit ceiling was tuned for. The ceiling rather than+ * this is what decides a patch's shape: a timeout that fires would slice the same change one way+ * here and another on a busier host.+ */+const MAX_FILE_DIFF_MILLIS = 2_000;++/** How much diff work one slice does before the rest is left for the next request. */+export const MAX_DIFF_SLICE_EDITS = 6_000;++/** How much patch one slice carries before the rest is left for the next request. */+export const MAX_DIFF_SLICE_BYTES = 256 * 1024;++/**+ * How many files one slice carries however little each one weighs. A binary, oversize, or+ * unreadable entry is just a header, so neither budget above stops a run of thousands of them.+ */+export const MAX_DIFF_SLICE_FILES = 300;++/** Git's own note for a side whose last line has no newline after it. */+const NO_NEWLINE_MARKER = "\\ No newline at end of file";++/** A text's lines, without the empty one that a trailing newline leaves behind a split. */+function contentLines(contents: string): ReadonlyArray<string> {+ if (contents === "") return [];+ const lines = contents.split("\n");+ if (lines.at(-1) === "") lines.pop();+ return lines;+}++/** A NUL byte is git's own test for it, and it survives Azure's JSON envelope intact. */+function isBinary(contents: string): boolean {+ return contents.includes("\u0000");+}++/**+ * What a file costs on the wire, which is its bytes rather than its code units: a ceiling counted+ * in characters lets a file of three-byte glyphs through at three times the intended size.+ */+export const byteLength = (contents: string) => Buffer.byteLength(contents, "utf8");++/**+ * Git points an empty range at the line before it, which is line zero for a file that is wholly+ * new or wholly gone, and writes a single line as its number alone.+ */+function hunkRange(start: number, lines: number): string {+ if (lines === 0) return `${start - 1},0`;+ return lines === 1 ? String(start) : `${start},${lines}`;+}++/**+ * The `diff --git` preamble a viewer reads a file's identity and fate from. Azure reports no file+ * mode, so the ordinary one stands in. Names are quoted the way git quotes them, prefix inside the+ * quoting: a header reader stops a bare name at its first tab or newline, so a path holding either+ * would be truncated and its viewed mark would land on the wrong file.+ */+function patchHeader(change: AzureDevOpsChangeEntry): string {+ const oldSide = quoteGitPatchPath(`a/${change.oldPath}`);+ const newSide = quoteGitPatchPath(`b/${change.path}`);+ const lines = [`diff --git ${oldSide} ${newSide}`];+ if (change.changeKind === "new") lines.push("new file mode 100644");+ if (change.changeKind === "deleted") lines.push("deleted file mode 100644");+ if (change.changeKind === "rename-pure" || change.changeKind === "rename-changed") {+ lines.push(+ `rename from ${quoteGitPatchPath(change.oldPath)}`,+ `rename to ${quoteGitPatchPath(change.path)}`,+ );+ }+ lines.push(+ `--- ${change.changeKind === "new" ? "/dev/null" : oldSide}`,+ `+++ ${change.changeKind === "deleted" ? "/dev/null" : newSide}`,+ );+ return lines.join("\n");+}++/**+ * A file written out as wholly replaced: every old line gone, every new line arrived, in one+ * hunk, which needs no edit-distance search at all.+ */+function replacementSection(header: string, texts: AzureDevOpsFileTexts): string {+ const oldLines = contentLines(texts.oldContents);+ const newLines = contentLines(texts.newContents);+ const noNewline = (contents: string, lines: ReadonlyArray<string>) =>+ lines.length > 0 && !contents.endsWith("\n") ? [NO_NEWLINE_MARKER] : [];+ return [+ header,+ `@@ -${hunkRange(1, oldLines.length)} +${hunkRange(1, newLines.length)} @@`,+ ...oldLines.map((line) => `-${line}`),+ ...noNewline(texts.oldContents, oldLines),+ ...newLines.map((line) => `+${line}`),+ ...noNewline(texts.newContents, newLines),+ "",+ ].join("\n");+}++/**+ * One file's section of a unified patch, built here because Azure has no route that returns one:+ * its diff routes name the files that changed, and the contents are a separate read per side.+ */+export function azureDevOpsFilePatch(input: {+ readonly change: AzureDevOpsChangeEntry;+ readonly texts: AzureDevOpsFileTexts;+}): AzureDevOpsFilePatch {+ const header = patchHeader(input.change);+ const { oldContents, newContents } = input.texts;++ if (input.texts.binary || isBinary(oldContents) || isBinary(newContents)) {+ // Git's own wording for a file it will not spell out.+ const oldSide = quoteGitPatchPath(`a/${input.change.oldPath}`);+ const newSide = quoteGitPatchPath(`b/${input.change.path}`);+ const binary = `Binary files ${oldSide} and ${newSide} differ`;+ return { section: `${header}\n${binary}\n`, truncated: true, abandoned: false, edits: 0 };+ }+ if (byteLength(oldContents) > MAX_FILE_BYTES || byteLength(newContents) > MAX_FILE_BYTES) {+ return { section: `${header}\n`, truncated: true, abandoned: false, edits: 0 };+ }++ // A creation or deletion has nothing on one side, so writing both sides in full is already the+ // minimal patch and needs no diff search.+ const created = oldContents === "" && newContents !== "";+ const deleted = newContents === "" && oldContents !== "";+ if (created || deleted) {+ const contents = created ? newContents : oldContents;+ const lines = contentLines(contents);+ // A `+`/`-` marker on every line can put a side that just fits the size ceiling over it.+ // Checked against bytes-plus-marker-count rather than building the section, since that upper+ // bound is cheaper and this is exactly the file shape that would cost the most to build.+ if (byteLength(contents) + lines.length > MAX_FILE_BYTES) {+ return { section: `${header}\n`, truncated: true, abandoned: false, edits: lines.length };+ }+ const section = replacementSection(header, input.texts);+ if (byteLength(section) > MAX_FILE_BYTES) {+ return { section: `${header}\n`, truncated: true, abandoned: false, edits: lines.length };+ }+ return { section, truncated: false, abandoned: false, edits: lines.length };+ }++ const patch = structuredPatch(+ `a/${input.change.oldPath}`,+ `b/${input.change.path}`,+ oldContents,+ newContents,+ undefined,+ undefined,+ {+ context: PATCH_CONTEXT_LINES,+ maxEditLength: MAX_FILE_DIFF_EDITS,+ timeout: MAX_FILE_DIFF_MILLIS,+ },+ );+ // Hitting the edit ceiling lists the file without hunks rather than falling back to a full+ // replacement: the ceiling is a distance, not a proportion, so a long file can reach it having+ // changed in one small corner, and both sides in full would bury that corner in a wall of text.+ if (patch === undefined) {+ return {+ section: `${header}\n`,+ truncated: true,+ abandoned: true,+ edits: MAX_FILE_DIFF_EDITS,+ };+ }++ let edits = 0;+ const hunks = patch.hunks.map((hunk) => {+ for (const line of hunk.lines) {+ if (line.startsWith("+") || line.startsWith("-")) edits += 1;+ }+ return [+ `@@ -${hunkRange(hunk.oldStart, hunk.oldLines)} +${hunkRange(hunk.newStart, hunk.newLines)} @@`,+ ...hunk.lines,+ ].join("\n");+ });+ // A pure rename has no hunks to give but is still listed, since dropping it would take the file+ // out of the change altogether.+ const section = hunks.length === 0 ? `${header}\n` : `${header}\n${hunks.join("\n")}\n`;+ // The edit ceiling bounds edit distance, not the hunks' size: a handful of very long lines plus+ // context can still exceed the size ceiling even well inside the edit ceiling.+ if (byteLength(section) > MAX_FILE_BYTES) {+ return { section: `${header}\n`, truncated: true, abandoned: false, edits };+ }+ return { section, truncated: false, abandoned: false, edits };+}++/** A file listed without its hunks, for when the host would not hand one of its two sides over. */+export function azureDevOpsUnreadableFilePatch(+ change: AzureDevOpsChangeEntry,+): AzureDevOpsFilePatch {+ return { section: `${patchHeader(change)}\n`, truncated: true, abandoned: false, edits: 0 };+}diff --git a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.ts b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.tsindex 6f55eb937bc..8e863b8751d 100644--- a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.ts+++ b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.ts@@ -2,6 +2,9 @@ import * as Result from "effect/Result";import { describe, expect, it } from "vite-plus/test";import {+ decodeItemContentJson,+ decodeIterationChangesJson,+ decodeIterationsJson,decodePullRequestJson,decodePullRequestListJson,decodeThreadsJson,@@ -187,17 +190,15 @@ describe("decodePullRequestJson", () => {expect(unspecified?.autoMergeMethod).toBeUndefined();});- it("works out where the conversation lives from what Azure returned", () => {+ it("works out where the repository lives from what Azure returned", () => {const detail = expectSuccess(decodePullRequestJson(asJson(pullRequest())));- expect(detail?.threadsUrl).toBe(- "https://dev.azure.com/acme/platform/_apis/git/repositories/web/pullRequests/42/threads",- );+ expect(detail?.location).toEqual({ project: "platform", repository: "web" });});- it("reports no conversation url when Azure said too little to build one", () => {- // A web link places the pull request, but without the REST url and repository there is- // nothing to hang a threads collection off.+ it("reports no repository location when Azure said too little to name one", () => {+ // A web link places the pull request, but with no repository named there is nothing to+ // address the routes that read its files and its conversation.const detail = expectSuccess(decodePullRequestJson(asJson(@@ -212,7 +213,7 @@ describe("decodePullRequestJson", () => {),);- expect(detail?.threadsUrl).toBeNull();+ expect(detail?.location).toBeNull();});it("returns nothing when Azure gave no way to place the pull request at all", () => {@@ -341,3 +342,311 @@ describe("decodeThreadsJson", () => {expect(comments).toEqual([]);});});++describe("decodeIterationsJson", () => {+ const iteration = (id: number, head: string, base: string) => ({+ id,+ sourceRefCommit: { commitId: head },+ commonRefCommit: { commitId: base },+ targetRefCommit: { commitId: base },+ });++ it("reads every push in order, oldest first", () => {+ const iterations = expectSuccess(+ decodeIterationsJson(+ asJson({ value: [iteration(2, "bbb", "base"), iteration(1, "aaa", "base")] }),+ ),+ );++ expect(iterations.map((entry) => entry.id)).toEqual([1, 2]);+ expect(iterations.at(-1)).toEqual({ id: 2, headCommit: "bbb", mergeBaseCommit: "base" });+ });++ it("skips a push Azure could not place both ends of", () => {+ // A patch is taken over a range, and an iteration missing either end names no range at all.+ const iterations = expectSuccess(+ decodeIterationsJson(+ asJson({+ value: [{ id: 1, sourceRefCommit: { commitId: "aaa" } }, iteration(2, "bbb", "base")],+ }),+ ),+ );++ expect(iterations.map((entry) => entry.id)).toEqual([2]);+ });+});++describe("decodeIterationChangesJson", () => {+ it("names each changed file without the slash Azure leads its paths with", () => {+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ changeEntries: [+ { changeType: "add", item: { path: "/DEMO.md", objectId: "ec00" } },+ {+ changeType: "edit",+ item: { path: "/README.md", objectId: "8f80", originalObjectId: "0ca4" },+ },+ { changeType: "delete", item: { path: "/OLD.md", originalObjectId: "1111" } },+ ],+ }),+ ),+ );++ expect(page.changes.map((change) => [change.path, change.changeKind])).toEqual([+ ["DEMO.md", "new"],+ ["README.md", "change"],+ ["OLD.md", "deleted"],+ ]);+ });++ it("keeps a space at the end of a file's name, which belongs to the name", () => {+ // Git will carry a name that ends in a space, and the patch and the viewed mark are both+ // keyed by it. Tidying it here files the change under a name nothing else uses.+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ changeEntries: [+ { changeType: "edit", item: { path: "/docs/readme.md ", objectId: "ec00" } },+ {+ changeType: "rename",+ sourceServerItem: "/docs/old.md ",+ item: { path: "/docs/moved.md", objectId: "aaaa", originalObjectId: "aaaa" },+ },+ ],+ }),+ ),+ );++ expect(page.changes.map((change) => [change.path, change.oldPath])).toEqual([+ ["docs/readme.md ", "docs/readme.md "],+ ["docs/moved.md", "docs/old.md "],+ ]);+ });++ it("reads a rename as one file that moved, and says whether it also changed", () => {+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ changeEntries: [+ {+ changeType: "rename",+ sourceServerItem: "/docs/old.md",+ item: { path: "/docs/new.md", objectId: "aaaa", originalObjectId: "aaaa" },+ },+ {+ changeType: "edit, rename",+ sourceServerItem: "/src/old.ts",+ item: { path: "/src/new.ts", objectId: "bbbb", originalObjectId: "cccc" },+ },+ ],+ }),+ ),+ );++ expect(page.changes).toEqual([+ {+ path: "docs/new.md",+ oldPath: "docs/old.md",+ changeKind: "rename-pure",+ objectId: "aaaa",+ originalObjectId: "aaaa",+ },+ {+ path: "src/new.ts",+ oldPath: "src/old.ts",+ changeKind: "rename-changed",+ objectId: "bbbb",+ originalObjectId: "cccc",+ },+ ]);+ });++ it("drops the folders Azure lists alongside the files that changed", () => {+ // A review shows files, and a folder has no content on either side to show for one.+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ changeEntries: [+ { changeType: "add", item: { path: "/docs", isFolder: true, gitObjectType: "tree" } },+ { changeType: "add", item: { path: "/docs/page.md", objectId: "dddd" } },+ ],+ }),+ ),+ );++ expect(page.changes.map((change) => change.path)).toEqual(["docs/page.md"]);+ });++ it("carries where the next page of a long change starts", () => {+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ changeEntries: [{ changeType: "add", item: { path: "/DEMO.md", objectId: "ec00" } }],+ nextSkip: 2000,+ }),+ ),+ );++ expect(page.nextSkip).toBe(2000);+ });++ it("reads the last page, which names no page after it, as the end of the change", () => {+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ changeEntries: [{ changeType: "add", item: { path: "/DEMO.md", objectId: "ec00" } }],+ }),+ ),+ );++ expect(page.nextSkip).toBeNull();+ });++ it("reads where a rename came from out of either of the two places Azure names it", () => {+ // The iteration-changes route answers with `originalPath`; the commit routes answer with+ // `sourceServerItem`, and both are the same fact under two names.+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ changeEntries: [+ {+ changeType: "rename",+ originalPath: "/docs/old.md",+ item: { path: "/docs/new.md", objectId: "aaaa", originalObjectId: "aaaa" },+ },+ ],+ }),+ ),+ );++ expect(page.changes.at(0)?.oldPath).toBe("docs/old.md");+ });+});++describe("decodeItemContentJson", () => {+ it("reads the file's text out of the envelope Azure wraps it in", () => {+ expect(+ expectSuccess(decodeItemContentJson(asJson({ path: "/a.md", content: "one\ntwo" }))),+ ).toEqual({ contents: "one\ntwo", isBinary: false });+ });++ it("reads an empty file as empty rather than as a failure to look", () => {+ expect(expectSuccess(decodeItemContentJson(asJson({ path: "/a.md" })))).toEqual({+ contents: "",+ isBinary: false,+ });+ });++ it("keeps Azure's own word that a file is binary", () => {+ // Which it answers base64-encoded, so nothing in the text it sent would give it away.+ expect(+ expectSuccess(+ decodeItemContentJson(+ asJson({ path: "/logo.png", content: "b2xk", contentMetadata: { isBinary: true } }),+ ),+ ),+ ).toEqual({ contents: "b2xk", isBinary: true });+ });+});++/**+ * Every other fixture in this file is written from Azure's published contract. These are the+ * shapes a real organisation answered with, read back through `az devops invoke` rather than+ * `az rest`: the extension hands over the route's own body with one key of its own added, and a+ * live repository leaves out fields the contract documents.+ */+describe("what az devops invoke answers with", () => {+ it("reads the envelope the extension adds its own continuation token to", () => {+ // Set on every JSON body it returns, from a response header these routes do not send, so it+ // arrives as null rather than not at all. Nothing reads it, and it must not fail the decode.+ expect(+ expectSuccess(decodeThreadsJson(asJson({ value: [], count: 0, continuation_token: null }))),+ ).toEqual([]);++ expect(+ expectSuccess(+ decodeIterationsJson(+ asJson({+ count: 1,+ continuation_token: null,+ value: [+ {+ id: 1,+ sourceRefCommit: { commitId: "f4031105213c68f197cd46ea303bb5e72acc889a" },+ commonRefCommit: { commitId: "acbc805382edd6c38b8d6de6ba9f9bba9da4ad35" },+ },+ ],+ }),+ ),+ ),+ ).toEqual([+ {+ id: 1,+ headCommit: "f4031105213c68f197cd46ea303bb5e72acc889a",+ mergeBaseCommit: "acbc805382edd6c38b8d6de6ba9f9bba9da4ad35",+ },+ ]);+ });++ it("keeps the files of a change that names neither their object type nor their page after it", () => {+ // A live iteration states `changeType`, `item.path` and `item.objectId` and nothing else: no+ // `gitObjectType`, no `isFolder`, and no `nextSkip` on the only page. Each of those absences+ // is what the defaults in the decoder are for, and reading any of them as stated would drop+ // every file of every Azure change request.+ const page = expectSuccess(+ decodeIterationChangesJson(+ asJson({+ continuation_token: null,+ changeEntries: [+ { changeType: "add", item: { path: "/DEMO.md", objectId: "EC005DB24" } },+ { changeType: "edit", item: { path: "/README.md", objectId: "8F8047A49" } },+ ],+ }),+ ),+ );++ expect(page.nextSkip).toBeNull();+ expect(page.changes).toEqual([+ {+ path: "DEMO.md",+ oldPath: "DEMO.md",+ changeKind: "new",+ objectId: "EC005DB24",+ originalObjectId: null,+ },+ {+ path: "README.md",+ oldPath: "README.md",+ changeKind: "change",+ objectId: "8F8047A49",+ originalObjectId: null,+ },+ ]);+ });++ it("reads a text file whose content type Azure calls a stream", () => {+ // `contentMetadata` comes back for a markdown file with `application/octet-stream` on it and+ // no `isBinary` at all, so the content type is not the field to ask, and its absence is the+ // answer that the text is text.+ expect(+ expectSuccess(+ decodeItemContentJson(+ asJson({+ path: "/README.md",+ objectId: "8f8047a49",+ gitObjectType: "blob",+ content: "# T3Demo\n",+ contentMetadata: {+ contentType: "application/octet-stream",+ encoding: 65001,+ extension: "md",+ fileName: "README.md",+ },+ continuation_token: null,+ }),+ ),+ ),+ ).toEqual({ contents: "# T3Demo\n", isBinary: false });+ });+});diff --git a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.ts b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.tsindex 55d9b544ab3..2e949e10395 100644--- a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.ts+++ b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.ts@@ -12,10 +12,7 @@ import type {import { TrimmedNonEmptyString } from "@t3tools/contracts";import { decodeJsonResult } from "@t3tools/shared/schemaJson";-import {- azureDevOpsOrganizationBaseFromRestApiUrl,- azureDevOpsPullRequestWebUrl,-} from "../sourceControl/azureDevOpsPullRequests.ts";+import { azureDevOpsPullRequestWebUrl } from "../sourceControl/azureDevOpsPullRequests.ts";/*** Azure's enums are decoded as plain strings and normalized here, in the same tolerant style as@@ -117,6 +114,16 @@ const RawViewerSchema = Schema.Struct({),});+/**+ * Where a repository lives, in the terms Azure's REST routes address it by. They take the project+ * and the repository as separate route parameters rather than as one path, so the pair travels+ * together rather than as a URL that would have to be taken apart again to use.+ */+export interface AzureDevOpsRepositoryLocation {+ readonly project: string;+ readonly repository: string;+}+export interface AzureDevOpsPullRequest {readonly number: number;readonly title: string;@@ -137,8 +144,8 @@ export interface AzureDevOpsPullRequest {readonly body: string;readonly reviewRequestLogins: ReadonlyArray<string>;readonly reviewers: ReadonlyArray<PullRequestActor>;- /** Where this pull request's threads live, when Azure said enough to work it out. */- readonly threadsUrl: string | null;+ /** Where this pull request lives, when Azure said enough to work it out. */+ readonly location: AzureDevOpsRepositoryLocation | null;/** Whether Azure is set to complete this on its own once its policies pass. */readonly autoMergeEnabled: boolean;/** The completion strategy Azure stored with auto-complete, where it reported one. */@@ -188,15 +195,16 @@ function toMergeability(value: string | null | undefined): PullRequestMergeabili}/**- * The REST collection a pull request's threads hang from. Built from what Azure returned rather- * than from the local remote, whose shape differs between the modern, legacy and SSH forms.+ * Where a pull request's own repository sits. Taken from what Azure returned rather than from the+ * local remote, whose shape differs between the modern, legacy and SSH forms.*/-function toThreadsUrl(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): string | null {- const base = azureDevOpsOrganizationBaseFromRestApiUrl(raw.url);+function toLocation(+ raw: Schema.Schema.Type<typeof RawPullRequestSchema>,+): AzureDevOpsRepositoryLocation | null {const project = trimmed(raw.repository?.project?.name);const repository = trimmed(raw.repository?.name);- if (base === null || project === null || repository === null) return null;- return `${base}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repository)}/pullRequests/${raw.pullRequestId}/threads`;+ if (project === null || repository === null) return null;+ return { project, repository };}function toAutoMergeMethod(@@ -259,7 +267,7 @@ function toPullRequest(body: raw.description ?? "",reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),reviewers,- threadsUrl: toThreadsUrl(raw),+ location: toLocation(raw),autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),};@@ -370,3 +378,197 @@ export function decodeThreadsJson(comments.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),);}++/**+ * One push's worth of a pull request. Azure records every push as an iteration and keys the whole+ * review off them: the changed files, and the marks a reader leaves on those files, both hang+ * from an iteration rather than from the pull request.+ */+const RawIterationSchema = Schema.Struct({+ id: Schema.Int,+ sourceRefCommit: Schema.optional(+ Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),+ ),+ commonRefCommit: Schema.optional(+ Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),+ ),+});++const RawIterationPageSchema = Schema.Struct({ value: Schema.Array(Schema.Unknown) });++const RawChangeEntrySchema = Schema.Struct({+ changeType: Schema.optional(Schema.NullOr(Schema.String)),+ sourceServerItem: Schema.optional(Schema.NullOr(Schema.String)),+ /** Where a renamed file came from. Azure states it here on an iteration's changes. */+ originalPath: Schema.optional(Schema.NullOr(Schema.String)),+ item: Schema.optional(+ Schema.NullOr(+ Schema.Struct({+ path: Schema.optional(Schema.NullOr(Schema.String)),+ objectId: Schema.optional(Schema.NullOr(Schema.String)),+ originalObjectId: Schema.optional(Schema.NullOr(Schema.String)),+ /** Azure marks a directory this way; a review has nothing to show for one. */+ isFolder: Schema.optional(Schema.NullOr(Schema.Boolean)),+ gitObjectType: Schema.optional(Schema.NullOr(Schema.String)),+ }),+ ),+ ),+});++const RawChangePageSchema = Schema.Struct({+ changeEntries: Schema.Array(Schema.Unknown),+ /** Where the page after this one starts. Azure leaves it out on the last page. */+ nextSkip: Schema.optional(Schema.NullOr(Schema.Number)),+});++const RawItemContentSchema = Schema.Struct({+ content: Schema.optional(Schema.NullOr(Schema.String)),+ /** What Azure makes of the file it is handing over, which is where it says it is not text. */+ contentMetadata: Schema.optional(+ Schema.NullOr(Schema.Struct({ isBinary: Schema.optional(Schema.NullOr(Schema.Boolean)) })),+ ),+});++/** The head and the merge base of one iteration, which is the range its patch is taken over. */+export interface AzureDevOpsIteration {+ readonly id: number;+ readonly headCommit: string;+ readonly mergeBaseCommit: string;+}++/**+ * What one file did across an iteration. `oldPath` differs from `path` only for a rename, which+ * Azure reports by naming the file's previous home rather than as a delete and an add.+ */+export interface AzureDevOpsChangeEntry {+ readonly path: string;+ readonly oldPath: string;+ readonly changeKind: "new" | "deleted" | "change" | "rename-pure" | "rename-changed";+ readonly objectId: string | null;+ readonly originalObjectId: string | null;+}++/**+ * One page of what an iteration changed, and where the next one starts. Azure pages this route+ * rather than answering with the whole change, so a review large enough to be paged is followed+ * to its end instead of being cut off at the first page's worth.+ */+export interface AzureDevOpsChangePage {+ readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;+ readonly nextSkip: number | null;+}++/** One file's text at one commit, and whether Azure says the text is text at all. */+export interface AzureDevOpsItemContent {+ readonly contents: string;+ readonly isBinary: boolean;+}++const decodeIterationPage = decodeJsonResult(RawIterationPageSchema);+const decodeIterationEntry = Schema.decodeUnknownExit(RawIterationSchema);+const decodeChangePage = decodeJsonResult(RawChangePageSchema);+const decodeChangeEntry = Schema.decodeUnknownExit(RawChangeEntrySchema);+const decodeItemContent = decodeJsonResult(RawItemContentSchema);++/**+ * Azure leads a path with a slash that every other host and every patch omits. Not trimmed like+ * the rest of this payload, since a leading/trailing space is a legal part of a file's name and+ * the patch and viewed mark are keyed by the untrimmed path.+ */+function toRepositoryPath(value: string | null | undefined): string | null {+ if (value === undefined || value === null) return null;+ const path = value.replace(/^\/+/, "");+ return path.length === 0 ? null : path;+}++/**+ * Azure names a change with one word or two, and a rename arrives either alone or alongside the+ * edit that came with it. Anything it has added since reads as a plain change, which shows the+ * file rather than dropping it from the review.+ */+function toChangeKind(+ raw: string | null | undefined,+ renamed: boolean,+): AzureDevOpsChangeEntry["changeKind"] {+ const parts = new Set(+ (raw ?? "")+ .toLowerCase()+ .split(",")+ .map((part) => part.trim())+ .filter((part) => part.length > 0),+ );+ if (parts.has("delete")) return "deleted";+ if (renamed || parts.has("rename")) return parts.has("edit") ? "rename-changed" : "rename-pure";+ if (parts.has("add")) return "new";+ return "change";+}++export function decodeIterationsJson(+ raw: string,+): Result.Result<ReadonlyArray<AzureDevOpsIteration>, DecodeFailure> {+ const decoded = decodeIterationPage(raw);+ if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);+ const iterations: AzureDevOpsIteration[] = [];+ for (const entry of decoded.success.value) {+ const decodedIteration = decodeIterationEntry(entry);+ if (Exit.isFailure(decodedIteration)) continue;+ const iteration = decodedIteration.value;+ const headCommit = trimmed(iteration.sourceRefCommit?.commitId);+ const mergeBaseCommit = trimmed(iteration.commonRefCommit?.commitId);+ // An iteration Azure cannot place both ends of names no range, and a patch needs both.+ if (headCommit === null || mergeBaseCommit === null) continue;+ iterations.push({ id: iteration.id, headCommit, mergeBaseCommit });+ }+ return Result.succeed(iterations.toSorted((left, right) => left.id - right.id));+}++export function decodeIterationChangesJson(+ raw: string,+): Result.Result<AzureDevOpsChangePage, DecodeFailure> {+ const decoded = decodeChangePage(raw);+ if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);+ const changes: AzureDevOpsChangeEntry[] = [];+ for (const entry of decoded.success.changeEntries) {+ const decodedChange = decodeChangeEntry(entry);+ if (Exit.isFailure(decodedChange)) continue;+ const change = decodedChange.value;+ const path = toRepositoryPath(change.item?.path);+ if (path === null) continue;+ // Azure lists the folders a change touched alongside the files themselves. A review shows+ // files, and a folder has no content to show for either side of one.+ if (change.item?.isFolder === true) continue;+ if ((change.item?.gitObjectType ?? "blob").toLowerCase() !== "blob") continue;+ // Azure names where a renamed file came from in either of two places depending on the route+ // and the version, so both are read and the current path stands in when neither is there.+ const oldPath =+ toRepositoryPath(change.sourceServerItem) ?? toRepositoryPath(change.originalPath) ?? path;+ changes.push({+ path,+ oldPath,+ changeKind: toChangeKind(change.changeType, oldPath !== path),+ objectId: trimmed(change.item?.objectId),+ originalObjectId: trimmed(change.item?.originalObjectId),+ });+ }+ const nextSkip = decoded.success.nextSkip ?? null;+ return Result.succeed({+ changes,+ nextSkip: nextSkip !== null && Number.isSafeInteger(nextSkip) && nextSkip > 0 ? nextSkip : null,+ });+}++/**+ * Azure answers an absent file with an empty body rather than an error, which reads as empty.+ * Whether the bytes are text is Azure's own call, not this decoder's to guess from content.+ */+export function decodeItemContentJson(+ raw: string,+): Result.Result<AzureDevOpsItemContent, DecodeFailure> {+ const decoded = decodeItemContent(raw);+ return Result.isSuccess(decoded)+ ? Result.succeed({+ contents: decoded.success.content ?? "",+ isBinary: decoded.success.contentMetadata?.isBinary === true,+ })+ : Result.fail(decoded.failure);+}diff --git a/apps/server/src/pullRequest/bitbucketDiffRevisions.test.ts b/apps/server/src/pullRequest/bitbucketDiffRevisions.test.tsnew file mode 100644index 00000000000..1426a67d29d--- /dev/null+++ b/apps/server/src/pullRequest/bitbucketDiffRevisions.test.ts@@ -0,0 +1,280 @@+import { assert, describe, it } from "@effect/vitest";++import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";++function patchOf(...lines: ReadonlyArray<string>): string {+ return `${lines.join("\n")}\n`;+}++describe("parseDiffFileRevisions", () => {+ it("reads the head id of a changed file off its index line", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/src/a.ts b/src/a.ts",+ "index 7f2aa0ab6..b4a2a7c9a 100644",+ "--- a/src/a.ts",+ "+++ b/src/a.ts",+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ),+ );++ assert.deepStrictEqual([...revisions], [["src/a.ts", "b4a2a7c9a"]]);+ });++ it("names a deletion by the path it had, which is the one still on screen", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/gone.ts b/gone.ts",+ "deleted file mode 100644",+ "index 1111111..0000000",+ "--- a/gone.ts",+ "+++ /dev/null",+ "@@ -1 +0,0 @@",+ "-x",+ ),+ );++ assert.deepStrictEqual([...revisions], [["gone.ts", "0000000"]]);+ });++ it("names a rename by where it moved to", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/old.ts b/new.ts",+ "similarity index 90%",+ "rename from old.ts",+ "rename to new.ts",+ "index 2222222..3333333 100644",+ "--- a/old.ts",+ "+++ b/new.ts",+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ),+ );++ assert.deepStrictEqual([...revisions], [["new.ts", "3333333"]]);+ });++ it("names a rename that changed nothing, which states no paths of its own", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/old.ts b/new.ts",+ "similarity index 100%",+ "rename from old.ts",+ "rename to new.ts",+ "index 2222222..2222222 100644",+ ),+ );++ assert.deepStrictEqual([...revisions], [["new.ts", "2222222"]]);+ });++ it("leaves out a file Bitbucket excluded, which it gives no index line for", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/package.json b/package.json",+ "index 7f2aa0ab6..b4a2a7c9a 100644",+ "--- a/package.json",+ "+++ b/package.json",+ "@@ -1 +1 @@",+ '- "x": "1"',+ '+ "x": "2"',+ "diff --git a/yarn.lock b/yarn.lock",+ 'File excluded by pattern "yarn.lock"',+ ),+ );++ assert.deepStrictEqual([...revisions], [["package.json", "b4a2a7c9a"]]);+ });++ it("stops reading headers at the first hunk, so content cannot pose as one", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/notes.md b/notes.md",+ "index aaaaaaa..bbbbbbb 100644",+ "--- a/notes.md",+ "+++ b/notes.md",+ "@@ -1,2 +1,2 @@",+ "--- a/decoy.ts",+ "+++ b/decoy.ts",+ "+index ccccccc..ddddddd 100644",+ ),+ );++ assert.deepStrictEqual([...revisions], [["notes.md", "bbbbbbb"]]);+ });++ it("splits a header whose paths contain the separator, by the sides agreeing", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/one b/two.ts b/one b/two.ts",+ "index eeeeeee..fffffff 100644",+ "@@ -1 +1 @@",+ ),+ );++ assert.deepStrictEqual([...revisions], [["one b/two.ts", "fffffff"]]);+ });++ it("leaves out an added file that Bitbucket sent no index line for", () => {+ const revisions = parseDiffFileRevisions(+ patchOf("diff --git a/added.ts b/added.ts", "new file mode 100644", "--- /dev/null"),+ );++ assert.strictEqual(revisions.size, 0);+ });++ it("reads nothing out of an empty patch", () => {+ assert.strictEqual(parseDiffFileRevisions("").size, 0);+ });++ it("reads a name git had to quote, here one holding a tab", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ 'diff --git "a/we\\tird.ts" "b/we\\tird.ts"',+ "index 4444444..5555555 100644",+ '--- "a/we\\tird.ts"',+ '+++ "b/we\\tird.ts"',+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ),+ );++ assert.deepStrictEqual([...revisions], [["we\tird.ts", "5555555"]]);+ });++ it("rejoins the octal bytes git writes for a name outside ASCII", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ 'diff --git "a/caf\\303\\251/r\\303\\251sum\\303\\251.ts" "b/caf\\303\\251/r\\303\\251sum\\303\\251.ts"',+ "index 6666666..7777777 100644",+ "@@ -1 +1 @@",+ ),+ );++ assert.deepStrictEqual([...revisions], [["café/résumé.ts", "7777777"]]);+ });++ it("splits a rename header where git quoted only the side that needed it", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ 'diff --git a/old.ts "b/new\\tname.ts"',+ "similarity index 90%",+ "rename from old.ts",+ 'rename to "new\\tname.ts"',+ "index 8888888..9999999 100644",+ "--- a/old.ts",+ '+++ "b/new\\tname.ts"',+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ),+ );++ assert.deepStrictEqual([...revisions], [["new\tname.ts", "9999999"]]);+ });++ it("names a quoted rename that changed nothing, which states no paths of its own", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ 'diff --git "a/old\\tname.ts" "b/new\\tname.ts"',+ "similarity index 100%",+ 'rename from "old\\tname.ts"',+ 'rename to "new\\tname.ts"',+ "index abcabca..abcabca 100644",+ ),+ );++ assert.deepStrictEqual([...revisions], [["new\tname.ts", "abcabca"]]);+ });++ it("keeps a character from outside the basic plane that git left unescaped", () => {+ // `core.quotePath` off leaves the name's own bytes in place, and git still quotes the header+ // for the tab. Encoding what it left one unit at a time would split the pair into two halves.+ const revisions = parseDiffFileRevisions(+ patchOf(+ 'diff --git "a/we\\tird-\u{1f680}.ts" "b/we\\tird-\u{1f680}.ts"',+ "index aaaaaaa..bbbbbbb 100644",+ "@@ -1 +1 @@",+ ),+ );++ assert.deepStrictEqual([...revisions], [["we\tird-\u{1f680}.ts", "bbbbbbb"]]);+ });++ it("drops the tab git ends a name holding a space with", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/with space.txt b/with space.txt",+ "index 1111111..6178079 100644",+ "--- a/with space.txt\t",+ "+++ b/with space.txt\t",+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ),+ );++ assert.deepStrictEqual([...revisions], [["with space.txt", "6178079"]]);+ });++ it("drops that tab from a quoted name too, where it lands past the closing quote", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ 'diff --git "a/we ird\\tname.ts" "b/we ird\\tname.ts"',+ "index 2222222..7777777 100644",+ '--- "a/we ird\\tname.ts"\t',+ '+++ "b/we ird\\tname.ts"\t',+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ),+ );++ assert.deepStrictEqual([...revisions], [["we ird\tname.ts", "7777777"]]);+ });++ it("reads a deletion whose name holds a space, tab and all", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/with space.txt b/with space.txt",+ "deleted file mode 100644",+ "index 3333333..0000000",+ "--- a/with space.txt\t",+ "+++ /dev/null",+ "@@ -1 +0,0 @@",+ "-a",+ ),+ );++ assert.deepStrictEqual([...revisions], [["with space.txt", "0000000"]]);+ });++ it("drops the timestamp other producers of the format write past that tab", () => {+ const revisions = parseDiffFileRevisions(+ patchOf(+ "diff --git a/stamped.ts b/stamped.ts",+ "index 4444444..5555555 100644",+ "--- a/stamped.ts\t2024-01-01 00:00:00.000000000 +0000",+ "+++ b/stamped.ts\t2024-01-02 00:00:00.000000000 +0000",+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ),+ );++ assert.deepStrictEqual([...revisions], [["stamped.ts", "5555555"]]);+ });++ it("splits an unquoted header whose names hold a space, by the sides agreeing", () => {+ const revisions = parseDiffFileRevisions(+ patchOf("diff --git a/one two b/one two", "index ddddddd..eeeeeee 100644", "@@ -1 +1 @@"),+ );++ assert.deepStrictEqual([...revisions], [["one two", "eeeeeee"]]);+ });+});diff --git a/apps/server/src/pullRequest/bitbucketDiffRevisions.ts b/apps/server/src/pullRequest/bitbucketDiffRevisions.tsnew file mode 100644index 00000000000..135a23dfdff--- /dev/null+++ b/apps/server/src/pullRequest/bitbucketDiffRevisions.ts@@ -0,0 +1,129 @@+import { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";++const ENTRY = "diff --git ";+const QUOTE = '"';++interface Entry {+ oldPath: string | null;+ newPath: string | null;+ deleted: boolean;+ revision: string | null;+ /** Past the first hunk header every line is content, and content can start like a header. */+ inBody: boolean;+}++/** Where a quoted name closes, given git escapes every quote the name itself holds. */+function quotedEnd(rest: string): number {+ for (let at = 1; at < rest.length; at += 1) {+ const char = rest.charAt(at);+ if (char === "\\") {+ at += 1;+ continue;+ }+ if (char === QUOTE) return at;+ }+ return -1;+}++/**+ * `a/x`/`b/x` on a `---`/`+++` line; `/dev/null` marks the side that has no file. Git ends the+ * name with a tab when it holds a space, and a name with a tab of its own arrives quoted with+ * that tab escaped, so the first literal tab is never part of what the file is called.+ */+function sidePath(rest: string, prefix: string): string | null {+ const tab = rest.indexOf("\t");+ const token = tab === -1 ? rest : rest.slice(0, tab);+ if (token === "/dev/null") return null;+ const path = unquoteGitPatchPath(token);+ return path.startsWith(prefix) ? path.slice(prefix.length) : path;+}++function headerSide(token: string, prefix: string): string | null {+ const path = unquoteGitPatchPath(token);+ return path.startsWith(prefix) ? path.slice(prefix.length) : null;+}++/**+ * The two names on a `diff --git` line, written with no delimiter between them. `a/one two b/one+ * two` can split in more than one place, so the split leaving both sides equal wins; a rename+ * (the only case where sides differ) states its names on separate lines instead. A quoted name+ * ends at its own closing quote and needs none of that guessing.+ */+function headerPaths(rest: string): readonly [string | null, string | null] {+ if (rest.startsWith(QUOTE)) {+ const end = quotedEnd(rest);+ if (end === -1 || rest.charAt(end + 1) !== " ") return [null, null];+ return [headerSide(rest.slice(0, end + 1), "a/"), headerSide(rest.slice(end + 2), "b/")];+ }+ if (rest.endsWith(QUOTE)) {+ const opens = rest.indexOf(QUOTE);+ if (opens < 1 || rest.charAt(opens - 1) !== " ") return [null, null];+ return [headerSide(rest.slice(0, opens - 1), "a/"), headerSide(rest.slice(opens), "b/")];+ }+ if (!rest.startsWith("a/")) return [null, null];+ const splits: Array<number> = [];+ for (let at = rest.indexOf(" b/"); at !== -1; at = rest.indexOf(" b/", at + 1)) splits.push(at);+ const chosen =+ splits.find((at) => rest.slice(2, at) === rest.slice(at + 3)) ??+ (splits.length === 1 ? splits[0] : undefined);+ return chosen === undefined ? [null, null] : [rest.slice(2, chosen), rest.slice(chosen + 3)];+}++/** The right-hand id of `index <before>..<after> <mode>`. */+function headRevision(rest: string): string | null {+ const gap = rest.indexOf("..");+ if (gap === -1) return null;+ const after = rest.slice(gap + 2);+ const end = after.indexOf(" ");+ const head = end === -1 ? after : after.slice(0, end);+ return head.length === 0 ? null : head;+}++/**+ * What the head has of each file, as the blob ids from a unified patch's `index <before>..<after>`+ * line: Bitbucket exposes no blob id for a file anywhere else. Keyed by the head's name, except+ * for a deletion where only the old name exists. An entry with no `index` line (most often one+ * Bitbucket excluded by pattern) is left out.+ */+export function parseDiffFileRevisions(patch: string): ReadonlyMap<string, string> {+ const revisions = new Map<string, string>();+ let entry: Entry | null = null;++ const close = () => {+ if (entry === null) return;+ const path = entry.deleted ? entry.oldPath : (entry.newPath ?? entry.oldPath);+ if (path !== null && path.length > 0 && entry.revision !== null) {+ revisions.set(path, entry.revision);+ }+ entry = null;+ };++ for (const line of patch.split("\n")) {+ if (line.startsWith(ENTRY)) {+ close();+ const [oldPath, newPath] = headerPaths(line.slice(ENTRY.length));+ entry = { oldPath, newPath, deleted: false, revision: null, inBody: false };+ continue;+ }+ if (entry === null || entry.inBody) continue;+ if (line.startsWith("@@")) {+ entry.inBody = true;+ } else if (line.startsWith("index ")) {+ entry.revision = headRevision(line.slice("index ".length));+ } else if (line.startsWith("deleted file mode")) {+ entry.deleted = true;+ } else if (line.startsWith("rename from ")) {+ entry.oldPath = unquoteGitPatchPath(line.slice("rename from ".length));+ } else if (line.startsWith("rename to ")) {+ entry.newPath = unquoteGitPatchPath(line.slice("rename to ".length));+ } else if (line.startsWith("--- ")) {+ entry.oldPath = sidePath(line.slice(4), "a/");+ } else if (line.startsWith("+++ ")) {+ const side = sidePath(line.slice(4), "b/");+ entry.newPath = side;+ if (side === null) entry.deleted = true;+ }+ }+ close();+ return revisions;+}diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.tsindex 1a041dc333b..8100a167808 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts@@ -6,10 +6,12 @@ import {buildPullRequestStackMembershipsGraphQlQuery,decodePullRequestStackMembershipsJson,buildReviewerRequestJson,+ buildSetFilesViewedGraphQlMutation,decodeBaseComparisonJson,decodePullRequestActivityJson,decodePullRequestDetailJson,decodePullRequestFilesJson,+ decodePullRequestFilesViewedJson,decodePullRequestListJson,decodePullRequestNodeIdJson,decodePullRequestSearchJson,@@ -1360,6 +1362,57 @@ describe("review submission payload", () => {});describe("decodePullRequestFilesJson", () => {+ it("quotes literal backslashes without interpreting them as escapes", () => {+ const result = expectSuccess(+ decodePullRequestFilesJson(+ JSON.stringify([+ {+ filename: String.raw`src\notes.ts`,+ status: "modified",+ patch: "@@ -1 +1 @@\n-old\n+new",+ },+ ]),+ ),+ );++ expect(result.patch).toBe(+ [+ String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,+ String.raw`--- "a/src\\notes.ts"`,+ String.raw`+++ "b/src\\notes.ts"`,+ "@@ -1 +1 @@",+ "-old",+ "+new",+ "",+ ].join("\n"),+ );+ });++ it("preserves spaces and literal backslashes in both rename paths", () => {+ const result = expectSuccess(+ decodePullRequestFilesJson(+ JSON.stringify([+ {+ previous_filename: String.raw` old\name.ts `,+ filename: String.raw` new\name.ts `,+ status: "renamed",+ },+ ]),+ ),+ );++ expect(result.patch).toBe(+ [+ String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,+ String.raw`rename from " old\\name.ts "`,+ String.raw`rename to " new\\name.ts "`,+ String.raw`--- "a/ old\\name.ts "`,+ String.raw`+++ "b/ new\\name.ts "`,+ "",+ ].join("\n"),+ );+ });+it("assembles a unified patch the files API does not return", () => {const result = expectSuccess(decodePullRequestFilesJson(@@ -1528,6 +1581,100 @@ describe("how far a branch trails its base", () => {});});+describe("decodePullRequestFilesViewedJson", () => {+ const page = (+ nodes: ReadonlyArray<unknown>,+ pageInfo: { hasNextPage: boolean; endCursor: string | null },+ ) =>+ JSON.stringify({+ data: { repository: { pullRequest: { files: { pageInfo, nodes } } } },+ });++ it("reads each file's state and where the next page carries on", () => {+ const decoded = decodePullRequestFilesViewedJson(+ page(+ [+ { path: "src/a.ts", viewerViewedState: "VIEWED" },+ { path: "src/b.ts", viewerViewedState: "UNVIEWED" },+ { path: "src/c.ts", viewerViewedState: "DISMISSED" },+ ],+ { hasNextPage: true, endCursor: "cursor-2" },+ ),+ );+ expect(Result.isSuccess(decoded)).toBe(true);+ if (!Result.isSuccess(decoded)) return;+ expect(decoded.success).toEqual({+ files: [+ { path: "src/a.ts", state: "viewed" },+ { path: "src/b.ts", state: "unviewed" },+ { path: "src/c.ts", state: "dismissed" },+ ],+ nextCursor: "cursor-2",+ });+ });++ it("treats a state it has never heard of as unread rather than failing the page", () => {+ const decoded = decodePullRequestFilesViewedJson(+ page([{ path: "src/a.ts", viewerViewedState: "SOMETHING_NEW" }], {+ hasNextPage: false,+ endCursor: null,+ }),+ );+ expect(Result.isSuccess(decoded)).toBe(true);+ if (!Result.isSuccess(decoded)) return;+ expect(decoded.success).toEqual({+ files: [{ path: "src/a.ts", state: "unviewed" }],+ nextCursor: null,+ });+ });++ it("answers empty for a pull request the host has nothing to say about", () => {+ const decoded = decodePullRequestFilesViewedJson(+ JSON.stringify({ data: { repository: { pullRequest: null } } }),+ );+ expect(Result.isSuccess(decoded)).toBe(true);+ if (!Result.isSuccess(decoded)) return;+ expect(decoded.success).toEqual({ files: [], nextCursor: null });+ });+});++describe("buildSetFilesViewedGraphQlMutation", () => {+ it("asks for nothing when nothing was pressed", () => {+ expect(buildSetFilesViewedGraphQlMutation([])).toBeNull();+ });++ it("clears and restores in one document, each file under its own alias", () => {+ const mutation = buildSetFilesViewedGraphQlMutation([+ { path: "src/a.ts", viewed: true },+ { path: "src/b.ts", viewed: false },+ ]);+ expect(mutation).not.toBeNull();+ if (mutation === null) return;+ expect(mutation.query).toContain(+ "mutation($pullRequestId: ID!, $path0: String!, $path1: String!)",+ );+ expect(mutation.query).toContain(+ "f0: markFileAsViewed(input: { pullRequestId: $pullRequestId, path: $path0 })",+ );+ expect(mutation.query).toContain(+ "f1: unmarkFileAsViewed(input: { pullRequestId: $pullRequestId, path: $path1 })",+ );+ expect(mutation.variables).toEqual({ path0: "src/a.ts", path1: "src/b.ts" });+ });++ it("keeps a path out of the document, so one cannot be read as part of it", () => {+ const mutation = buildSetFilesViewedGraphQlMutation([+ { path: '") { __typename } evil: markFileAsViewed(input: { path: "x', viewed: true },+ ]);+ expect(mutation).not.toBeNull();+ if (mutation === null) return;+ expect(mutation.query).not.toContain("evil");+ expect(mutation.variables.path0).toBe(+ '") { __typename } evil: markFileAsViewed(input: { path: "x',+ );+ });+});+describe("host-native stack decoding", () => {/** A stack as the preview lists it, bottom to top, with the fields it answers today. */function stack(overrides: Record<string, unknown> = {}) {diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.tsindex 483557b7f11..6229c142a15 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts@@ -10,6 +10,7 @@ import type {PullRequestChecksState,PullRequestComment,PullRequestCommit,+ PullRequestFileViewedState,PullRequestLabel,PullRequestMergeCapabilities,PullRequestMergeMethod,@@ -30,6 +31,7 @@ import type {PullRequestState,PullRequestThreadComment,} from "@t3tools/contracts";+import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";import { decodeJsonResult } from "@t3tools/shared/schemaJson";import { dedupeChecks } from "./pullRequestChecks.ts";@@ -2510,16 +2512,21 @@ export function decodePullRequestFilesJson(}// A rename counts its hunks against the old path, which is the only place it is named.const oldPath =- status === "renamed" ? (trimmed(value.previous_filename) ?? value.filename) : value.filename;+ status === "renamed" ? value.previous_filename || value.filename : value.filename;const header = [- `diff --git a/${oldPath} b/${value.filename}`,+ `diff --git ${quoteGitPatchPath(`a/${oldPath}`)} ${quoteGitPatchPath(`b/${value.filename}`)}`,// The files API reports no file mode, so the ordinary one stands in: the viewer reads// these lines as "added" and "removed" rather than for the mode they carry....(status === "added" ? ["new file mode 100644"] : []),...(status === "removed" ? ["deleted file mode 100644"] : []),- ...(status === "renamed" ? [`rename from ${oldPath}`, `rename to ${value.filename}`] : []),- `--- ${status === "added" ? "/dev/null" : `a/${oldPath}`}`,- `+++ ${status === "removed" ? "/dev/null" : `b/${value.filename}`}`,+ ...(status === "renamed"+ ? [+ `rename from ${quoteGitPatchPath(oldPath)}`,+ `rename to ${quoteGitPatchPath(value.filename)}`,+ ]+ : []),+ `--- ${status === "added" ? "/dev/null" : quoteGitPatchPath(`a/${oldPath}`)}`,+ `+++ ${status === "removed" ? "/dev/null" : quoteGitPatchPath(`b/${value.filename}`)}`,].join("\n");sections.push(hunks.length === 0 ? `${header}\n` : `${header}\n${hunks.replace(/\n?$/, "\n")}`);}@@ -2531,6 +2538,119 @@ export function decodePullRequestFilesJson(});}+/**+ * Which files of a pull request the signed-in account has cleared. GraphQL only, since the REST+ * files endpoint the patch is read from carries no viewed state, so this is a second read rather+ * than a wider version of the first.+ */+export const PULL_REQUEST_FILES_VIEWED_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $after: String) {+ repository(owner: $owner, name: $name) {+ pullRequest(number: $number) {+ files(first: 100, after: $after) {+ pageInfo { hasNextPage endCursor }+ nodes { path viewerViewedState }+ }+ }+ }+}`;++const RawPullRequestFilesViewedSchema = Schema.Struct({+ data: Schema.Struct({+ repository: Schema.NullOr(+ Schema.Struct({+ pullRequest: Schema.NullOr(+ Schema.Struct({+ files: Schema.Struct({+ pageInfo: Schema.Struct({+ hasNextPage: Schema.Boolean,+ endCursor: Schema.NullOr(Schema.String),+ }),+ nodes: Schema.NullOr(+ Schema.Array(+ Schema.NullOr(+ Schema.Struct({+ path: Schema.String,+ // Decoded as a plain string and narrowed below: a GitHub release that adds+ // a fourth state must not fail the whole page.+ viewerViewedState: Schema.String,+ }),+ ),+ ),+ ),+ }),+ }),+ ),+ }),+ ),+ }),+});++const decodePullRequestFilesViewed = decodeJsonResult(RawPullRequestFilesViewedSchema);++export interface GitHubPullRequestFilesViewedPage {+ readonly files: ReadonlyArray<{+ readonly path: string;+ readonly state: PullRequestFileViewedState;+ }>;+ /** Where the next page carries on, or null once the host has no more to give. */+ readonly nextCursor: string | null;+}++/** Anything this host does not name is treated as unread, which is the state that asks for least. */+function toFileViewedState(raw: string): PullRequestFileViewedState {+ switch (raw.trim().toUpperCase()) {+ case "VIEWED":+ return "viewed";+ case "DISMISSED":+ return "dismissed";+ default:+ return "unviewed";+ }+}++export function decodePullRequestFilesViewedJson(+ raw: string,+): Result.Result<GitHubPullRequestFilesViewedPage, DecodeFailure> {+ const decoded = decodePullRequestFilesViewed(raw);+ if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);+ const files = decoded.success.data.repository?.pullRequest?.files;+ if (files === undefined) return Result.succeed({ files: [], nextCursor: null });+ return Result.succeed({+ files: (files.nodes ?? []).flatMap((node) =>+ node === null || node.path.length === 0+ ? []+ : [{ path: node.path, state: toFileViewedState(node.viewerViewedState) }],+ ),+ nextCursor: files.pageInfo.hasNextPage ? files.pageInfo.endCursor : null,+ });+}++/**+ * One document that clears and restores as many files as the reader ticked, rather than one+ * request each. GitHub has no bulk form of `markFileAsViewed`/`unmarkFileAsViewed`, which each+ * take a single path, so the batching is done with aliases; top-level mutation fields run in+ * write order, so the last word about a path is the one that sticks.+ *+ * Paths travel as variables rather than interpolated into the document, since a path is data+ * and a document is not.+ */+export function buildSetFilesViewedGraphQlMutation(+ files: ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>,+): { readonly query: string; readonly variables: Readonly<Record<string, string>> } | null {+ if (files.length === 0) return null;+ const parameters = files.map((_, index) => `$path${index}: String!`).join(", ");+ const fields = files+ .map(+ (file, index) =>+ ` f${index}: ${file.viewed ? "markFileAsViewed" : "unmarkFileAsViewed"}(input: { pullRequestId: $pullRequestId, path: $path${index} }) { clientMutationId }`,+ )+ .join("\n");+ return {+ query: `mutation($pullRequestId: ID!, ${parameters}) {\n${fields}\n}`,+ variables: Object.fromEntries(files.map((file, index) => [`path${index}`, file.path])),+ };+}+/** One pull request as the stacks API lists it: a number, a head, and whether it is done. */const RawStackPullRequestSchema = Schema.Struct({title: Schema.optional(Schema.String),diff --git a/apps/server/src/pullRequest/gitLabMergeRequestJson.test.ts b/apps/server/src/pullRequest/gitLabMergeRequestJson.test.tsindex 4438aa0c521..c9bc1274375 100644--- a/apps/server/src/pullRequest/gitLabMergeRequestJson.test.ts+++ b/apps/server/src/pullRequest/gitLabMergeRequestJson.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";import {decodeAwardEmojiJson,+ decodeRepositoryBlobsJson,decodeCommitsJson,decodeMergeRequestDetailJson,decodeMergeRequestDiffsJson,@@ -381,6 +382,57 @@ describe("decodeCommitsJson", () => {});describe("decodeMergeRequestDiffsJson", () => {+ it("quotes literal backslashes without interpreting them as escapes", () => {+ const result = expectSuccess(+ decodeMergeRequestDiffsJson(+ JSON.stringify([+ {+ old_path: String.raw`src\notes.ts`,+ new_path: String.raw`src\notes.ts`,+ diff: "@@ -1 +1 @@\n-old\n+new",+ },+ ]),+ ),+ );++ expect(result.patch).toBe(+ [+ String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,+ String.raw`--- "a/src\\notes.ts"`,+ String.raw`+++ "b/src\\notes.ts"`,+ "@@ -1 +1 @@",+ "-old",+ "+new",+ "",+ ].join("\n"),+ );+ });++ it("preserves spaces and literal backslashes in both rename paths", () => {+ const result = expectSuccess(+ decodeMergeRequestDiffsJson(+ JSON.stringify([+ {+ old_path: String.raw` old\name.ts `,+ new_path: String.raw` new\name.ts `,+ renamed_file: true,+ diff: "",+ },+ ]),+ ),+ );++ expect(result.patch).toBe(+ [+ String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,+ String.raw`rename from " old\\name.ts "`,+ String.raw`rename to " new\\name.ts "`,+ String.raw`--- "a/ old\\name.ts "`,+ String.raw`+++ "b/ new\\name.ts "`,+ ].join("\n"),+ );+ });+it("assembles a unified patch GitLab does not return", () => {const result = expectSuccess(decodeMergeRequestDiffsJson(@@ -630,3 +682,122 @@ describe("gitLabAwardName", () => {expect(gitLabAwardName("hooray")).toBe("tada");});});++describe("decodeRepositoryBlobsJson", () => {+ /** Null is the query going unanswered, which these cases are not about. */+ function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {+ const blobs = expectSuccess(result);+ expect(blobs).not.toBe(null);+ if (blobs === null) throw new Error("expected an answered blobs query");+ return blobs;+ }++ it("reads a blob id per path", () => {+ const blobs = expectBlobs(+ decodeRepositoryBlobsJson(+ JSON.stringify({+ data: {+ project: {+ repository: {+ blobs: {+ nodes: [+ { path: "src/a.ts", oid: "aaa111" },+ { path: "src/b.ts", oid: "bbb222" },+ ],+ },+ },+ },+ },+ }),+ ),+ );++ expect([...blobs]).toEqual([+ ["src/a.ts", "aaa111"],+ ["src/b.ts", "bbb222"],+ ]);+ });++ it("leaves out a node missing either half, which names no version", () => {+ const blobs = expectBlobs(+ decodeRepositoryBlobsJson(+ JSON.stringify({+ data: {+ project: {+ repository: {+ blobs: {+ nodes: [+ { path: "src/a.ts", oid: null },+ { path: null, oid: "bbb222" },+ null,+ { path: "src/c.ts", oid: "ccc333" },+ ],+ },+ },+ },+ },+ }),+ ),+ );++ expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);+ });++ it("keys a blob by the path the host spelled, spaces and all", () => {+ // A leading or trailing space is a legal part of a file's name. Trimmed here, the id lands+ // under a key the asked-for path is not spelled with, and the caller fills that path in as+ // the empty revision: a mark on the file then never compares against the real head blob.+ const blobs = expectBlobs(+ decodeRepositoryBlobsJson(+ JSON.stringify({+ data: {+ project: {+ repository: {+ blobs: {+ nodes: [+ { path: " leading.ts", oid: "aaa111" },+ { path: "trailing.ts ", oid: "bbb222" },+ { path: " ", oid: "ccc333" },+ { path: "", oid: "ddd444" },+ ],+ },+ },+ },+ },+ }),+ ),+ );++ expect([...blobs]).toEqual([+ [" leading.ts", "aaa111"],+ ["trailing.ts ", "bbb222"],+ // A name that is only spaces is one Git carries too, so it is a path like any other.+ [" ", "ccc333"],+ ]);+ });++ it("tells a project the reader cannot see from a revision with none of the files", () => {+ // Null is the query going unanswered. Read as an empty answer it would say the head has none+ // of the asked-for files, which reports every file a reader has cleared as changed.+ expect(+ expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),+ ).toBe(null);+ expect(+ expectSuccess(+ decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),+ ),+ ).toBe(null);+ expect(+ expectSuccess(+ decodeRepositoryBlobsJson(+ JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),+ ),+ ),+ ).toEqual(new Map());+ });++ it("fails on output that is not the query's shape", () => {+ expect(Result.isSuccess(decodeRepositoryBlobsJson("not json"))).toBe(false);+ expect(Result.isSuccess(decodeRepositoryBlobsJson(JSON.stringify({ errors: [] })))).toBe(false);+ });+});diff --git a/apps/server/src/pullRequest/gitLabMergeRequestJson.ts b/apps/server/src/pullRequest/gitLabMergeRequestJson.tsindex 4b3c797136f..b9991920d0d 100644--- a/apps/server/src/pullRequest/gitLabMergeRequestJson.ts+++ b/apps/server/src/pullRequest/gitLabMergeRequestJson.ts@@ -19,6 +19,7 @@ import type {PullRequestState,} from "@t3tools/contracts";import { TrimmedNonEmptyString } from "@t3tools/contracts";+import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";import { decodeJsonResult } from "@t3tools/shared/schemaJson";/**@@ -680,8 +681,8 @@ function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {readonly to: string;} {return {- from: raw.new_file === true ? "/dev/null" : `a/${raw.old_path}`,- to: raw.deleted_file === true ? "/dev/null" : `b/${raw.new_path}`,+ from: raw.new_file === true ? "/dev/null" : quoteGitPatchPath(`a/${raw.old_path}`),+ to: raw.deleted_file === true ? "/dev/null" : quoteGitPatchPath(`b/${raw.new_path}`),};}@@ -718,11 +719,14 @@ export function decodeMergeRequestDiffsJson(}const { from, to } = diffHeaderPaths(value);const header = [- `diff --git a/${value.old_path} b/${value.new_path}`,+ `diff --git ${quoteGitPatchPath(`a/${value.old_path}`)} ${quoteGitPatchPath(`b/${value.new_path}`)}`,...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),...(value.renamed_file === true- ? [`rename from ${value.old_path}`, `rename to ${value.new_path}`]+ ? [+ `rename from ${quoteGitPatchPath(value.old_path)}`,+ `rename to ${quoteGitPatchPath(value.new_path)}`,+ ]: []),`--- ${from}`,`+++ ${to}`,@@ -947,3 +951,82 @@ export function decodeOwnAwardIdJson(}return Result.succeed(null);}++/**+ * What the given paths are at one revision, as blob ids. Asked for by path rather than by walking+ * the tree, since GitLab charges this query by how many paths it is given. A path the revision+ * does not have comes back missing rather than as an error, which is the answer for a deleted file.+ */+export const REPOSITORY_BLOBS_GRAPHQL_QUERY = `query($fullPath: ID!, $ref: String!, $paths: [String!]!) {+ project(fullPath: $fullPath) {+ repository {+ blobs(ref: $ref, paths: $paths) {+ nodes { path oid }+ }+ }+ }+}`;++const RawRepositoryBlobsSchema = Schema.Struct({+ data: Schema.Struct({+ project: Schema.NullOr(+ Schema.Struct({+ repository: Schema.optional(+ Schema.NullOr(+ Schema.Struct({+ blobs: Schema.optional(+ Schema.NullOr(+ Schema.Struct({+ nodes: Schema.optional(+ Schema.NullOr(+ Schema.Array(+ Schema.NullOr(+ Schema.Struct({+ path: Schema.optional(Schema.NullOr(Schema.String)),+ oid: Schema.optional(Schema.NullOr(Schema.String)),+ }),+ ),+ ),+ ),+ ),+ }),+ ),+ ),+ }),+ ),+ ),+ }),+ ),+ }),+});++const decodeRepositoryBlobs = decodeJsonResult(RawRepositoryBlobsSchema);++/**+ * Blob ids by path, or null where GitLab did not answer the query at all (a project the token+ * cannot see, or a repository with no blobs connection). That case must be told apart from an+ * empty answer: read as "the revision has none of these files", it would report every cleared+ * file as changed again. A node missing either half is left out, since the caller treats an+ * absent path as one the revision does not carry.+ */+export function decodeRepositoryBlobsJson(+ raw: string,+): Result.Result<ReadonlyMap<string, string> | null, DecodeFailure> {+ const decoded = decodeRepositoryBlobs(raw);+ if (!Result.isSuccess(decoded)) {+ return Result.fail(decoded.failure);+ }+ const nodes = decoded.success.data.project?.repository?.blobs?.nodes;+ if (nodes === undefined || nodes === null) return Result.succeed(null);+ const blobs = new Map<string, string>();+ for (const node of nodes) {+ // Not trimmed, unlike everything else read out of this payload: a leading or trailing space+ // is a legal part of a file's name, and trimming it would key this map under a name the+ // caller's asked-for path never matches.+ const path = node?.path;+ const oid = trimmed(node?.oid);+ if (path === undefined || path === null || path.length === 0 || oid === null) continue;+ blobs.set(path, oid);+ }+ return Result.succeed(blobs);+}diff --git a/apps/server/src/pullRequest/pullRequestViewedFiles.ts b/apps/server/src/pullRequest/pullRequestViewedFiles.tsnew file mode 100644index 00000000000..1f9aa33ac79--- /dev/null+++ b/apps/server/src/pullRequest/pullRequestViewedFiles.ts@@ -0,0 +1,423 @@+/**+ * The marks a reader has ticked off, for a host that keeps none of its own, and the held record of+ * what the head has of those files. The revisions cache is filed here because this is its only+ * consumer: when a second one appears, export `makeFileRevisions` and split it into its own file.+ */+import * as Clock from "effect/Clock";+import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Semaphore from "effect/Semaphore";+import {+ PullRequestOperationError,+ type PullRequestFilesViewedResult,+ type PullRequestRef,+ type PullRequestSetFilesViewedInput,+} from "@t3tools/contracts";++import type * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";+import type { ProviderFileRevisions, PullRequestProviderError } from "./PullRequestProvider.ts";+import type { PullRequestError, SupportedProject } from "./PullRequestService.ts";++/**+ * How long the head's version of a file is believed, and how long a held answer stands while the+ * next one is fetched. This is the host call behind the **Changed** badge alone, so a held answer+ * costs a badge that is a minute behind rather than a stale tick.+ */+const FILE_REVISIONS_CACHE_TTL = Duration.seconds(60);+const FILE_REVISIONS_STALE_WINDOW = Duration.minutes(10);+export const FILE_REVISIONS_CACHE_CAPACITY = 64;++/**+ * How many paths one scope's entry carries. Bounds a single scope, not how many scopes are held:+ * a reader ticking one file after another renews the same scope and grows it without limit+ * otherwise.+ */+export const MAX_FILE_REVISION_PATHS = 1_000;++interface FileRevisionsDependencies {+ readonly runFork: (effect: Effect.Effect<void>) => unknown;+ readonly refEpoch: (ref: PullRequestRef) => number;+ readonly fileRevisionsEpoch: () => number;+ readonly toPullRequestError: (+ operation: string,+ ) => (error: PullRequestProviderError) => PullRequestError;+}++const makeFileRevisions = (dependencies: FileRevisionsDependencies) => {+ const { runFork, refEpoch, fileRevisionsEpoch, toPullRequestError } = dependencies;+ /**+ * What the head has of the files a reader has marked, held between reads. The entry tracks what+ * has been asked as well as what was heard, since a path missing from an answer keeps whatever+ * version was last given for it rather than being cleared.+ */+ interface HeldFileRevisions {+ readonly at: number;+ readonly asked: ReadonlySet<string>;+ readonly revisions: ReadonlyMap<string, string>;+ }+ const heldFileRevisions = new Map<string, HeldFileRevisions>();+ const refreshingFileRevisions = new Set<string>();++ /**+ * Carries the reference's epoch, so whatever moved the head strands what was held (or in+ * flight) against the old one. Spelled from the project rather than the reference, since a+ * reference arrives however the client spelled it while the epoch is bumped against the+ * remote's own spelling.+ */+ const fileRevisionsKey = (project: SupportedProject, ref: PullRequestRef) =>+ [+ refEpoch({ ...ref, host: project.host, repository: project.repository }),+ fileRevisionsEpoch(),+ ref.projectId,+ project.repository.trim().toLowerCase(),+ ref.number,+ ].join(" ");++ /**+ * `paths` are what was asked about, and are held as answered for whether the host had a version+ * for them or not: that is what stops the same question being asked again. A `complete` answer+ * adds every other path it carries, since a host that read the whole change to answer for one+ * file has already paid for all of them, and the tick after this one names a file nothing has+ * asked about yet.+ */+ const recordFileRevisions = (+ key: string,+ paths: ReadonlyArray<string>,+ answer: ProviderFileRevisions,+ ) =>+ Effect.map(Clock.currentTimeMillis, (at) => {+ const held = heldFileRevisions.get(key);+ // Past the stale window the old entry is not worth merging into: it would carry paths+ // nobody has asked about since, at revisions the head has long moved off.+ const carried =+ held !== undefined && at - held.at <= Duration.toMillis(FILE_REVISIONS_STALE_WINDOW)+ ? held+ : null;+ const revisions = new Map(carried?.revisions ?? []);+ const asked = new Set(carried?.asked ?? []);+ // The paths asked for go last, so a whole-change answer wider than the cap is trimmed down+ // to the reader's own files rather than over them.+ const learned = answer.complete === true ? [...answer.revisions.keys(), ...paths] : paths;+ for (const path of learned) {+ // Reinserted rather than added, so what a full entry drops below is the path nobody has+ // asked about in the longest rather than one just asked for.+ asked.delete(path);+ asked.add(path);+ const revision = answer.revisions.get(path);+ // A path left out of the answer keeps its last known version rather than being cleared.+ if (revision !== undefined) {+ revisions.delete(path);+ revisions.set(path, revision);+ }+ }+ for (const path of asked) {+ if (asked.size <= MAX_FILE_REVISION_PATHS) break;+ asked.delete(path);+ revisions.delete(path);+ }+ heldFileRevisions.delete(key);+ if (heldFileRevisions.size >= FILE_REVISIONS_CACHE_CAPACITY) {+ const oldest = heldFileRevisions.keys().next().value;+ if (oldest !== undefined) heldFileRevisions.delete(oldest);+ }+ // The entry is only as fresh as its oldest revision: stamping it with `now` on a partial+ // answer would let an old revision ride past the point it should have been re-read.+ const stamped = [...revisions.keys()].every((path) => answer.revisions.has(path))+ ? at+ : (carried?.at ?? at);+ heldFileRevisions.set(key, { at: stamped, asked, revisions });+ return revisions;+ });++ /** A held entry that covers every path asked for and is still worth answering from. */+ const heldFileRevisionsFor = (key: string, paths: ReadonlyArray<string>, now: number) => {+ const held = heldFileRevisions.get(key);+ if (held === undefined) return null;+ // Put back at the end on every read, so the scope a reader is working through is not the one+ // evicted by a listing walking scopes nobody has open.+ heldFileRevisions.delete(key);+ heldFileRevisions.set(key, held);+ if (now - held.at > Duration.toMillis(FILE_REVISIONS_STALE_WINDOW)) return null;+ return paths.every((path) => held.asked.has(path)) ? held : null;+ };++ /**+ * What the head has of these files, or null where the host cannot say (not an error: the marks+ * just stop reporting staleness). `held` answers from a stale value and refetches off the+ * critical path, since a badge a moment behind beats a page that won't paint until the host+ * answers; `fresh` is for the press itself, which must not store a revision the head already+ * moved off.+ */+ const fileRevisionsOf = (+ project: SupportedProject,+ ref: PullRequestRef,+ paths: ReadonlyArray<string>,+ operation: string,+ freshness: "held" | "fresh" = "held",+ ): Effect.Effect<ReadonlyMap<string, string> | null, PullRequestError> => {+ const read = project.api.getFileRevisions;+ if (read === undefined) return Effect.succeed(null);+ // Suspended, so a held answer costs the host nothing: a provider is free to do its work as+ // the request is built rather than as the effect is run.+ const fetch = Effect.suspend(() => {+ const key = fileRevisionsKey(project, ref);+ return read({+ cwd: project.project.workspaceRoot,+ repository: project.repository,+ host: project.host,+ number: ref.number,+ paths,+ }).pipe(+ Effect.mapError(toPullRequestError(operation)),+ Effect.flatMap((answer) => recordFileRevisions(key, paths, answer)),+ );+ });+ return Effect.flatMap(Clock.currentTimeMillis, (now) => {+ const key = fileRevisionsKey(project, ref);+ const held = heldFileRevisionsFor(key, paths, now);+ if (held === null) return fetch;+ if (now - held.at <= Duration.toMillis(FILE_REVISIONS_CACHE_TTL))+ return Effect.succeed(held.revisions);+ if (freshness === "fresh") return fetch;+ if (refreshingFileRevisions.has(key)) return Effect.succeed(held.revisions);+ // Its own fiber rather than a child: the caller has been answered and is gone before this+ // lands. One at a time per change request, so a page of files costs one host read.+ return Effect.sync(() => {+ refreshingFileRevisions.add(key);+ runFork(+ Effect.ignore(fetch).pipe(+ Effect.ensuring(Effect.sync(() => refreshingFileRevisions.delete(key))),+ ),+ );+ }).pipe(Effect.as(held.revisions));+ });+ };++ return { fileRevisionsOf } as const;+};++export interface Dependencies extends FileRevisionsDependencies {+ readonly filesViewedStore: PullRequestFilesViewed.PullRequestFilesViewedRepository["Service"];+ readonly requireProject: (+ ref: PullRequestRef,+ ) => Effect.Effect<SupportedProject, PullRequestError>;+ readonly requiredViewerOf: (+ project: SupportedProject,+ operation: string,+ ) => Effect.Effect<string | null, PullRequestError>;+}++// A plain factory rather than a `Context.Service` (against the preference in+// `.repos/effect-smol/LLMS.md`): the held revisions, refresh set, and write gates are only correct+// at one instance per service, and a layer provided at two points would give two of each behind+// one epoch counter.+export const make = (dependencies: Dependencies) => {+ const { filesViewedStore, requireProject, requiredViewerOf, toPullRequestError } = dependencies;+ const { fileRevisionsOf } = makeFileRevisions(dependencies);+ /**+ * Which change request's marks, and whose. Provider and host lead the key because the same+ * repository can exist on more than one install; the reader is part of it because a host's own+ * record is per-account. A host that names no reader is one reader, not none.+ */+ const filesViewedScope = (project: SupportedProject, number: number, viewer: string | null) => ({+ provider: project.api.kind,+ host: project.host,+ repository: project.remote,+ number,+ viewer: viewer ?? "",+ });++ const toFilesViewedStoreError = (operation: string) => (cause: unknown) =>+ new PullRequestOperationError({+ operation,+ detail: "This environment could not reach its record of which files you have seen.",+ cause,+ });++ /**+ * The marks this environment keeps for a host that keeps none of its own. A file the head+ * still has at the revision it was cleared at is cleared; one the head has moved on from is+ * reported as changed. Revisions are asked for the marked paths alone, so a reader who has+ * marked nothing costs no host call.+ */+ const environmentFilesViewed = (+ project: SupportedProject,+ ref: PullRequestRef,+ ): Effect.Effect<PullRequestFilesViewedResult, PullRequestError> =>+ Effect.gen(function* () {+ const viewer = yield* requiredViewerOf(project, "filesViewed");+ const held = yield* filesViewedStore+ .list(filesViewedScope(project, ref.number, viewer))+ .pipe(Effect.mapError(toFilesViewedStoreError("filesViewed")));+ const marks = held.files;+ if (marks.length === 0) return { files: [], truncated: held.truncated };+ // A host that won't say what its head has costs the marks their staleness (`fileRevisionsOf`+ // returns null), rather than costing the reader every tick they've made.+ const revisions = yield* fileRevisionsOf(+ project,+ ref,+ marks.map((mark) => mark.path),+ "filesViewed",+ ).pipe(+ Effect.catch((error) =>+ Effect.logWarning("reporting viewed files without what the head has of them", {+ operation: "filesViewed",+ reason: error._tag,+ }).pipe(Effect.as(null)),+ ),+ );+ return {+ files: marks.map((mark) => {+ // A mark stamped with no baseline holds until the reader presses it again.+ if (mark.revision === null) return { path: mark.path, state: "viewed" as const };+ const revision = revisions?.get(mark.path);+ // A deleted file is answered as the empty revision, matching its stamp, so it stays+ // cleared; a path the host had no answer for (`undefined`) also holds as cleared.+ return {+ path: mark.path,+ state:+ revision === undefined || revision === mark.revision+ ? ("viewed" as const)+ : ("dismissed" as const),+ };+ }),+ // The store caps marks per scope; a reader over that cap is told so, like a paginated read.+ truncated: held.truncated,+ };+ });++ /**+ * One environment-backed write at a time per change request. A tick's host round trip is+ * slower than an untick's, so unordered presses could finish out of order and leave a stale+ * tick standing over a later untick.+ */+ const filesViewedGates = new Map<+ string,+ { readonly gate: Semaphore.Semaphore; pending: number }+ >();++ const inFilesViewedOrder = (+ project: SupportedProject,+ number: number,+ write: Effect.Effect<void, PullRequestError>,+ ) =>+ // Suspended rather than generated, so finding the gate, putting it in and taking a place in+ // its queue are one step: yielding for `Semaphore.make` between the lookup and the insert+ // lets two presses each make a gate of their own and neither wait on the other.+ Effect.suspend(() => {+ const key = `${project.project.id} ${project.remote} ${number}`;+ const held = filesViewedGates.get(key);+ const entry = held ?? { gate: Semaphore.makeUnsafe(1), pending: 0 };+ if (held === undefined) filesViewedGates.set(key, entry);+ entry.pending += 1;+ // Dropped once nobody is queued behind it, so a long-lived server does not keep a gate per+ // change request anyone has ever ticked a file in.+ return entry.gate+ .withPermits(1)(write)+ .pipe(+ Effect.ensuring(+ Effect.sync(() => {+ entry.pending -= 1;+ if (entry.pending === 0) filesViewedGates.delete(key);+ }),+ ),+ );+ });++ const environmentSetFilesViewed = (+ project: SupportedProject,+ input: PullRequestSetFilesViewedInput,+ ): Effect.Effect<void, PullRequestError> =>+ Effect.gen(function* () {+ const viewer = yield* requiredViewerOf(project, "setFilesViewed");+ // Only the files being cleared need a revision. An unticked one is about to lose its row,+ // and what the head has of it changes nothing about deleting it.+ const cleared = input.files.filter((file) => file.viewed).map((file) => file.path);+ const revisions =+ cleared.length === 0+ ? null+ : yield* fileRevisionsOf(project, input, cleared, "setFilesViewed", "fresh").pipe(+ // A host that won't say what its head has costs the press its baseline, not the+ // press itself: the mark is stored with none and holds until pressed again.+ Effect.catch((error) =>+ Effect.logWarning("recording viewed files without what the head has of them", {+ operation: "setFilesViewed",+ reason: error._tag,+ }).pipe(Effect.as(null)),+ ),+ );+ const viewedAt = DateTime.formatIso(yield* DateTime.now);+ yield* filesViewedStore+ .set({+ ...filesViewedScope(project, input.number, viewer),+ // A path left out of the answer stores with no baseline, not the empty revision, since+ // the empty revision is itself an answer and would misreport the file once it turns+ // out to have a version after all.+ files: input.files.map((file) => ({+ path: file.path,+ revision: revisions?.get(file.path) ?? null,+ viewed: file.viewed,+ })),+ viewedAt,+ })+ .pipe(Effect.mapError(toFilesViewedStoreError("setFilesViewed")));+ });++ const filesViewed = (input: PullRequestRef) =>+ requireProject(input).pipe(+ Effect.flatMap((project): Effect.Effect<PullRequestFilesViewedResult, PullRequestError> => {+ const read = project.api.getFilesViewed;+ if (project.api.capabilities.viewedFiles === "host" && read) {+ return read({+ cwd: project.project.workspaceRoot,+ repository: project.repository,+ host: project.host,+ number: input.number,+ }).pipe(Effect.mapError(toPullRequestError("filesViewed")));+ }+ if (project.api.capabilities.viewedFiles === "environment") {+ return environmentFilesViewed(project, input);+ }+ return Effect.fail(+ new PullRequestOperationError({+ operation: "filesViewed",+ detail: "This host does not track which files a reader has seen.",+ }),+ );+ }),+ );++ const setFilesViewed = (+ input: PullRequestSetFilesViewedInput,+ ): Effect.Effect<void, PullRequestError> =>+ requireProject(input).pipe(+ Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {+ const write = project.api.setFilesViewed;+ if (project.api.capabilities.viewedFiles === "host" && write) {+ return write({+ cwd: project.project.workspaceRoot,+ repository: project.repository,+ host: project.host,+ number: input.number,+ files: input.files,+ }).pipe(Effect.mapError(toPullRequestError("setFilesViewed")));+ }+ if (project.api.capabilities.viewedFiles === "environment") {+ return inFilesViewedOrder(+ project,+ input.number,+ environmentSetFilesViewed(project, input),+ );+ }+ return Effect.fail(+ new PullRequestOperationError({+ operation: "setFilesViewed",+ detail: "This host does not track which files a reader has seen.",+ }),+ );+ }),+ );++ return { filesViewed, setFilesViewed };+};diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 5970c81affa..be16a3f7fb5 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -755,7 +755,11 @@ const buildAppUnderTest = (options?: {);const servedRoutesLayer = HttpRouter.serve(- makeRoutesLayer.pipe(Layer.provide(serviceLauncherClientLayer)),+ // Viewed-file marks for a host that keeps none of its own are rows, so the routes want a+ // database. Its own, in memory: nothing here shares a table with the auth store.+ makeRoutesLayer.pipe(+ Layer.provide(Layer.mergeAll(serviceLauncherClientLayer, SqlitePersistenceMemory)),+ ),{disableListenLog: true,disableLogger: true,diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex c04f07c4ac6..3fd0bb7274a 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -39,6 +39,7 @@ import { pullRequestHttpApiLayer } from "./pullRequest/http.ts";import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";import * as PullRequestService from "./pullRequest/PullRequestService.ts";import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";+import * as PullRequestFilesViewed from "./persistence/PullRequestFilesViewed.ts";import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";import * as AnalyticsService from "./telemetry/AnalyticsService.ts";import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";@@ -329,6 +330,8 @@ const RepositoryIdentityResolverLayerLive = Layer.effect(const PullRequestServiceLive = PullRequestService.layer.pipe(Layer.provide(PullRequestProviderRegistry.layer),+ // Where the viewed-file marks live for a host that keeps none of its own.+ Layer.provide(PullRequestFilesViewed.layer),Layer.provide(PullRequestReadCache.layer),Layer.provide(SourceControlProviderRegistryLayerLive),Layer.provide(SourceControlRateLimit.layer),diff --git a/apps/server/src/sourceControl/azureDevOpsPullRequests.ts b/apps/server/src/sourceControl/azureDevOpsPullRequests.tsindex d11d1a87077..6179a61aa65 100644--- a/apps/server/src/sourceControl/azureDevOpsPullRequests.ts+++ b/apps/server/src/sourceControl/azureDevOpsPullRequests.ts@@ -77,11 +77,11 @@ function encodeAzureDevOpsPathSegment(segment: string): string {}/**- * The organization root a REST url belongs to, which is where a browser url and any further- * REST call have to be hung. Exported because the pull requests page derives its own urls from- * whatever Azure returned rather than from the local remote, whose shape varies.+ * The organization root a REST url belongs to, which is where a browser url has to be hung when+ * Azure answered with neither a web link nor a repository url. Read from what Azure returned+ * rather than from the local remote, whose shape varies.*/-export function azureDevOpsOrganizationBaseFromRestApiUrl(+function azureDevOpsOrganizationBaseFromRestApiUrl(value: string | null | undefined,): string | null {const rawUrl = trimOptionalString(value);diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 1cc5cafbe6f..802a0396d68 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -2751,6 +2751,18 @@ const makeWsRpcLayer = (withPullRequestViewer(input, pullRequests.diffFileContents(input)),{ "rpc.aggregate": "pull-requests" },),+ [WS_METHODS.pullRequestsFilesViewed]: (input) =>+ observeRpcEffect(+ WS_METHODS.pullRequestsFilesViewed,+ withPullRequestViewer(input, pullRequests.filesViewed(input)),+ { "rpc.aggregate": "pull-requests" },+ ),+ [WS_METHODS.pullRequestsSetFilesViewed]: (input) =>+ observeRpcEffect(+ WS_METHODS.pullRequestsSetFilesViewed,+ withPullRequestViewer(input, pullRequests.setFilesViewed(input)),+ { "rpc.aggregate": "pull-requests" },+ ),[WS_METHODS.pullRequestsRunAction]: (input) =>observeRpcEffect(WS_METHODS.pullRequestsRunAction,@@ -2824,7 +2836,7 @@ const makeWsRpcLayer = (// A reader asking for fresh host state also wants the thread badges it feeds to// catch up, including a merged link the sweep would otherwise never revisit.Effect.andThen(- input.reference === undefined+ input.reference === undefined || input.filesViewedOnly === true? Effect.void: resolvePullRequestSyncKey(input.reference).pipe(Effect.flatMap((key) =>diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 4e80768b315..9136900fe0f 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -53,6 +53,7 @@ import { inlineCodeFilePathCandidate } from "@t3tools/client-runtime/markdown-liimport { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";import * as Cause from "effect/Cause";+import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import { AsyncResult } from "effect/unstable/reactivity";import React, {Children,@@ -2905,7 +2906,7 @@ const CHAT_MARKDOWN_COMPONENTS = {input: {projectId: pullRequestProject.id,repository:- pullRequestProject.repositoryIdentity?.displayName ??+ sourceControlRepositorySelector(pullRequestProject.repositoryIdentity) ??pullRequestCandidate.repository,number: pullRequestCandidate.number,},diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex db5e3d8822a..44c09d73565 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -76,6 +76,7 @@ import {resolveProjectScripts,} from "@t3tools/shared/projectScripts";import { resolveProjectSettings } from "@t3tools/shared/projectSettings";+import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import { truncate } from "@t3tools/shared/String";import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";import {@@ -4663,7 +4664,9 @@ export default function ChatView(props: ChatViewProps) {const hasLinkedPullRequestDetail = activeThreadMetadata?.linkedPullRequest != null;const linkedThreadPullRequest =activeThreadMetadata?.linkedPullRequest ?? activeThreadMetadata?.branchPullRequest ?? null;- const activeProjectRepository = activeProject?.repositoryIdentity?.displayName ?? null;+ const activeProjectRepository = sourceControlRepositorySelector(+ activeProject?.repositoryIdentity,+ );const linkedThreadPullRequestKey = linkedThreadPullRequest? JSON.stringify([linkedThreadPullRequest.projectId,diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex 54cfc025868..b535c4f45e9 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -17,6 +17,7 @@ import {ChevronsUpDownIcon,Columns2Icon,FolderTreeIcon,+ InfoIcon,MessageSquareIcon,MessageSquareOffIcon,Rows3Icon,@@ -44,6 +45,7 @@ import {resolveFileDiffPreviousPath,type RenderablePatch,} from "~/lib/diffRendering";+import { APP_BASE_NAME } from "~/branding";import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";import { cn } from "~/lib/utils";import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents";@@ -63,6 +65,7 @@ import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";import { diffFileTreeEntries } from "../diffs/diffFileTree.logic";import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";import { Button } from "../ui/button";+import { Checkbox } from "../ui/checkbox";import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";import {DropdownMenu,@@ -78,9 +81,11 @@ import { PullRequestReviewBar } from "./PullRequestReviewBar";import {isFileDiffCollapsed,isLineInFileDiff,+ toggleFileDiffFoldForViewed,type DiffFoldOverride,} from "./pullRequestDiff.logic";import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation";+import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";import {nextPendingReviewCommentId,pullRequestReviewKey,@@ -223,6 +228,8 @@ function PullRequestCodeTab({const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE);/** Set once the reader has asked for every file at once, until they pick a file apart again. */const [foldOverride, setFoldOverride] = useState<DiffFoldOverride>(null);+ const effectiveFoldOverride =+ foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded");const diffLayout = settings.diffLayout;const updateClientSettings = useUpdateClientSettings();const [wordWrap, setWordWrap] = useState(settings.wordWrap);@@ -331,13 +338,6 @@ function PullRequestCodeTab({input: { ...reference, ...(commit === null ? {} : { commit }) },}),);- const appliedRefreshToken = useRef(refreshToken);- useEffect(() => {- if (appliedRefreshToken.current === refreshToken) return;- appliedRefreshToken.current = refreshToken;- setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });- refreshFirstDiffPage();- }, [refreshToken, scopeKey, refreshFirstDiffPage]);const reviewKey = referenceKey;const pendingComments = usePendingReviewComments(reference);const addComment = usePullRequestReviewStore((store) => store.addComment);@@ -410,6 +410,35 @@ function PullRequestCodeTab({),[parsedSlices],);+ const filePaths = useMemo(() => files.map((file) => resolveFileDiffPath(file)), [files]);+ // Offered under a commit scope as well as from the whole change, because reading a change one+ // commit at a time is what the scope is for. The tick is kept against the change request rather+ // than the scope it was made in, so clearing a file here clears it everywhere.+ const viewedFilesStore = detail.capabilities.viewedFiles;+ const filesViewed = usePullRequestFilesViewed({+ environmentId,+ reference,+ enabled: viewedFilesStore !== undefined,+ paths: filePaths,+ });+ const {+ setViewed,+ refresh: refreshFilesViewed,+ enabled: filesViewedEnabled,+ isViewed: isFileViewed,+ isStale: isFileViewedStale,+ } = filesViewed;+ // The button goes around the host's cache, so everything the tab reads from it starts over:+ // the diff from its first page, and with it the ticks, which a push since the last read can+ // have marked as standing against an older version of the file.+ const appliedRefreshToken = useRef(refreshToken);+ useEffect(() => {+ if (appliedRefreshToken.current === refreshToken) return;+ appliedRefreshToken.current = refreshToken;+ setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });+ refreshFirstDiffPage();+ refreshFilesViewed();+ }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;// What a slice withheld: the host declining to inline part of it, or a patch the viewer could// not structure and so dropped. Neither says anything about there being more to fetch.@@ -442,7 +471,9 @@ function PullRequestCodeTab({return placed;}, [commit, detail.reviewThreads, files]);- const items = useMemo<CodeViewDiffItem<ReviewAnnotationGroup>[]>(+ // Hashing what the annotations show is the costly part of an item's version, and none of it+ // moves when a file is ticked or folded, so it is kept apart from the two that do.+ const annotatedFiles = useMemo(() =>files.map((fileDiff) => {const fileKey = buildFileDiffRenderKey(fileDiff);@@ -484,27 +515,20 @@ function PullRequestCodeTab({groupAt(anchor.side, anchor.line).draft = true;}- const collapsed = isFileDiffCollapsed(- fileKey,- foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded"),- toggledFiles,- );-const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({side: toViewerSide(group.side),lineNumber: group.line,metadata: { threads: group.threads, pending: group.pending, draft: group.draft },}));return {- id: fileKey,- type: "diff" as const,+ fileKey,+ path,fileDiff,annotations,- collapsed,// The viewer re-renders an item only when its version changes, so everything the// annotations show has to be part of it.- version: fnv1a32(- `${collapsed ? "1" : "0"}:${annotations+ annotationsVersion: fnv1a32(+ annotations.map(({ side, lineNumber, metadata }) =>`${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending@@ -529,19 +553,37 @@ function PullRequestCodeTab({).join(",")}`,)- .join("|")}`,+ .join("|"),),};}),+ [commit, detail.reviewThreads, draft, files, pendingComments, placedThreadIds],+ );++ const items = useMemo<CodeViewDiffItem<ReviewAnnotationGroup>[]>(+ () =>+ annotatedFiles.map(({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {+ const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles);+ // Ticking a file that is already folded changes no fold, so without this the box on+ // screen would keep saying the opposite of what the count says.+ const viewedMark = filesViewedEnabled+ ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}`+ : "";+ return {+ id: fileKey,+ type: "diff" as const,+ fileDiff,+ annotations,+ collapsed,+ version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),+ };+ }),[- commit,- detail.reviewThreads,- draft,- files,- foldOverride,- pendingComments,- placedThreadIds,- settings.diffFilesCollapsed,+ annotatedFiles,+ filesViewedEnabled,+ effectiveFoldOverride,+ isFileViewed,+ isFileViewedStale,toggledFiles,],);@@ -606,6 +648,19 @@ function PullRequestCodeTab({[],);+ // The tick and the fold are one gesture: clearing a file puts it away, un-clearing brings it+ // back. Folding is still held as the reader's difference from the toolbar's default rather+ // than derived from what has been ticked, so folding everything ticks nothing off.+ const setFileViewed = useCallback(+ (fileKey: string, path: string, viewed: boolean) => {+ setViewed(path, viewed);+ setToggledFiles((current) =>+ toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current),+ );+ },+ [effectiveFoldOverride, setViewed],+ );+const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);const revealFile = useCallback((path: string) => {@@ -743,6 +798,14 @@ function PullRequestCodeTab({[toggleFile],);+ // Read through refs rather than closed over. The viewer memoizes each visible file's header+ // portal on the callback below, so a fresh identity on every tick, and on every refresh of the+ // host's answer, would rebuild every header on screen.+ const filesViewedRef = useRef(filesViewed);+ filesViewedRef.current = filesViewed;+ const setFileViewedRef = useRef(setFileViewed);+ setFileViewedRef.current = setFileViewed;+const renderHeaderMetadata = useCallback((item: CodeViewItem<ReviewAnnotationGroup>) => {if (item.type !== "diff") return null;@@ -752,17 +815,52 @@ function PullRequestCodeTab({additions += hunk.additionLines;deletions += hunk.deletionLines;}+ const path = resolveFileDiffPath(item.fileDiff);if (additions === 0 && deletions === 0) {- const withheld = omittedFileStats.get(resolveFileDiffPath(item.fileDiff));+ const withheld = omittedFileStats.get(path);if (withheld) ({ additions, deletions } = withheld);}- return (+ const stat = (<PullRequestDiffStatadditions={additions}deletions={deletions}className="font-mono text-[11px]"/>);+ const viewedFiles = filesViewedRef.current;+ if (!viewedFiles.enabled) return stat;+ const viewed = viewedFiles.isViewed(path);+ const stale = viewedFiles.isStale(path);+ return (+ <span className="flex items-center gap-3">+ {stat}+ {/* The header itself folds the file, so the tick keeps its press to itself. The+ attribute is what the header's capture listener looks for. */}+ <label+ data-viewed-toggle=""+ className="flex cursor-pointer select-none items-center gap-1.5 text-[11px] text-muted-foreground"+ onClick={(event) => event.stopPropagation()}+ >+ <Checkbox+ aria-label={stale ? "Changed" : "Viewed"}+ checked={viewed}+ onCheckedChange={(next) => setFileViewedRef.current(item.id, path, next === true)}+ />+ {stale ? (+ <Tooltip>+ <TooltipTrigger render={<span className="text-amber-600 dark:text-amber-500" />}>+ Changed+ </TooltipTrigger>+ <TooltipPopup side="bottom">+ This file has been pushed to since you marked it viewed.+ </TooltipPopup>+ </Tooltip>+ ) : (+ "Viewed"+ )}+ </label>+ </span>+ );},[omittedFileStats],);@@ -1092,6 +1190,62 @@ function PullRequestCodeTab({{files.length} {files.length === 1 ? "file" : "files"}{nextCursor === null ? "" : "+"}</span>+ {filesViewed.enabled && files.length > 0 ? (+ <span className="flex min-w-0 items-center gap-1 tabular-nums">+ {/* Named on a host that keeps no record of its own, so the reader is told whose+ ticks these are without having to find the icon beside them. The count holds its+ width and the wording gives way, so the narrow right panel keeps its controls. */}+ <span className="shrink-0">+ {filesViewed.viewedCount} / {files.length}+ </span>+ <span className="truncate">+ {viewedFilesStore === "environment" ? `viewed in ${APP_BASE_NAME}` : "viewed"}+ </span>+ {viewedFilesStore === "environment" ? (+ <Tooltip>+ <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>+ <InfoIcon+ aria-label="These ticks are kept here, not on the host"+ className="text-muted-foreground size-3.5"+ />+ </TooltipTrigger>+ <TooltipPopup side="bottom">+ This host keeps no shared record of which files you have read, so these ticks+ are kept by this environment. They follow you between the apps connected to it,+ but the host's own web UI will not show them.+ </TooltipPopup>+ </Tooltip>+ ) : null}+ {filesViewed.error !== null ? (+ <Tooltip>+ <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>+ <TriangleAlertIcon+ aria-label="Your ticks could not be read"+ className="size-3.5 text-amber-600 dark:text-amber-500"+ />+ </TooltipTrigger>+ <TooltipPopup side="bottom">+ The boxes below are whatever was last read, and empty if nothing has been read+ yet. {filesViewed.error}+ </TooltipPopup>+ </Tooltip>+ ) : null}+ {filesViewed.truncated ? (+ <Tooltip>+ <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>+ <TriangleAlertIcon+ aria-label="This count covers only part of the change"+ className="size-3.5 text-amber-600 dark:text-amber-500"+ />+ </TooltipTrigger>+ <TooltipPopup side="bottom">+ This change has more files than the host will report ticks for in one read, so+ the count is short and some boxes below start empty.+ </TooltipPopup>+ </Tooltip>+ ) : null}+ </span>+ ) : null}{withheldContent ? (<Tooltip><TooltipTrigger render={<span className="flex shrink-0 items-center" />}>@@ -1375,6 +1529,9 @@ function PullRequestCodeTab({if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {return;}+ // A label answers for the control it names and this listener runs before it hears+ // anything, so stopping the press keeps the header from folding what the tick folds.+ if (node.hasAttribute("data-viewed-toggle")) return;if (node.hasAttribute("data-diffs-header")) {const filePath = node.querySelector("[data-title]")?.textContent?.trim();if (filePath === undefined || filePath === "") return;diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.tsindex 203be64eebe..181ebe6cfec 100644--- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts@@ -1,7 +1,11 @@import type { FileDiffMetadata } from "@pierre/diffs";import { describe, expect, it } from "vite-plus/test";-import { isFileDiffCollapsed, isLineInFileDiff } from "./pullRequestDiff.logic";+import {+ isFileDiffCollapsed,+ isLineInFileDiff,+ toggleFileDiffFoldForViewed,+} from "./pullRequestDiff.logic";/** Only the hunk ranges matter here; the viewer fills the rest in when it renders. */function fileWithHunks(@@ -79,3 +83,30 @@ describe("isFileDiffCollapsed", () => {expect(isFileDiffCollapsed("a.ts", "folded", new Set(["a.ts"]))).toBe(false);});});++describe("toggleFileDiffFoldForViewed", () => {+ it("puts a file away when it is ticked off", () => {+ // Files start expanded, so ticking one off is the case that has somewhere to go.+ expect([...toggleFileDiffFoldForViewed("a.ts", true, null, new Set())]).toEqual(["a.ts"]);+ });++ it("brings a file back when the tick is taken off", () => {+ expect([...toggleFileDiffFoldForViewed("a.ts", false, null, new Set(["a.ts"]))]).toEqual([]);+ });++ it("leaves the fold alone when it already says what the tick does", () => {+ const folded = new Set(["a.ts"]);+ expect(toggleFileDiffFoldForViewed("a.ts", true, null, folded)).toBe(folded);+ });++ it("moves against whatever the toolbar last asked for", () => {+ // Everything is open, so ticking a file off has to fold that one against the default.+ expect([...toggleFileDiffFoldForViewed("a.ts", true, "expanded", new Set())]).toEqual(["a.ts"]);+ expect(toggleFileDiffFoldForViewed("a.ts", false, "expanded", new Set()).size).toBe(0);+ });++ it("touches only the file that was ticked", () => {+ const toggled = new Set(["a.ts", "b.ts"]);+ expect([...toggleFileDiffFoldForViewed("a.ts", false, null, toggled)]).toEqual(["b.ts"]);+ });+});diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.tsindex e818e989d20..b7b836cb3b5 100644--- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts@@ -41,3 +41,24 @@ export function isFileDiffCollapsed(const foldedByDefault = foldOverride === "folded";return toggledFileKeys.has(fileKey) ? !foldedByDefault : foldedByDefault;}++/**+ * The reader's fold choices after a file was ticked off, or put back.+ *+ * Clearing a file puts it away and un-clearing brings it back, so the tick moves the fold as if+ * the reader had pressed the chevron themselves, which keeps folding a difference from what the+ * toolbar last asked, and so keeps "collapse all" from ticking anything off.+ */+export function toggleFileDiffFoldForViewed(+ fileKey: string,+ viewed: boolean,+ foldOverride: DiffFoldOverride,+ toggledFileKeys: ReadonlySet<string>,+): ReadonlySet<string> {+ if (isFileDiffCollapsed(fileKey, foldOverride, toggledFileKeys) === viewed)+ return toggledFileKeys;+ const next = new Set(toggledFileKeys);+ if (next.has(fileKey)) next.delete(fileKey);+ else next.add(fileKey);+ return next;+}diff --git a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.tsnew file mode 100644index 00000000000..72d5a631acb--- /dev/null+++ b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts@@ -0,0 +1,174 @@+import { describe, expect, it } from "vite-plus/test";++import {+ countViewedFiles,+ isFileViewed,+ isStaleViewedState,+ revertFileViewedOverlay,+ settleFileViewedOverlay,+ toFileViewedBatch,+ toFileViewedStates,+ type FileViewedOverlay,+} from "./pullRequestFilesViewed.logic";++const NO_OVERLAY: FileViewedOverlay = new Map();+const NOTHING_PENDING: ReadonlySet<string> = new Set();+const NOTHING_ANSWERED: ReadonlySet<string> = new Set();++const states = toFileViewedStates({+ files: [+ { path: "a.ts", state: "viewed" },+ { path: "b.ts", state: "unviewed" },+ { path: "c.ts", state: "dismissed" },+ ],+ truncated: false,+});++describe("isFileViewed", () => {+ it("follows the host for a file the reader has not pressed", () => {+ expect(isFileViewed("a.ts", states, NO_OVERLAY)).toBe(true);+ expect(isFileViewed("b.ts", states, NO_OVERLAY)).toBe(false);+ });++ it("reads a file pushed to since it was cleared as unread", () => {+ expect(isFileViewed("c.ts", states, NO_OVERLAY)).toBe(false);+ expect(isStaleViewedState(states?.get("c.ts"))).toBe(true);+ expect(isStaleViewedState(states?.get("a.ts"))).toBe(false);+ });++ it("shows the press ahead of the host's answer", () => {+ expect(isFileViewed("b.ts", states, new Map([["b.ts", true]]))).toBe(true);+ expect(isFileViewed("a.ts", states, new Map([["a.ts", false]]))).toBe(false);+ });++ it("answers a file the host has said nothing about, before its answer arrives", () => {+ expect(isFileViewed("z.ts", null, NO_OVERLAY)).toBe(false);+ expect(isFileViewed("z.ts", null, new Map([["z.ts", true]]))).toBe(true);+ });+});++describe("countViewedFiles", () => {+ it("counts only the files on screen, presses included", () => {+ expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, NO_OVERLAY)).toBe(1);+ expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, new Map([["b.ts", true]]))).toBe(2);+ // A file the host knows about but the diff has not paged in yet is not counted.+ expect(countViewedFiles(["b.ts"], states, NO_OVERLAY)).toBe(0);+ });+});++describe("settleFileViewedOverlay", () => {+ it("drops a press the host has caught up on", () => {+ const settled = settleFileViewedOverlay(+ new Map([["a.ts", true]]),+ states,+ NOTHING_PENDING,+ NOTHING_ANSWERED,+ );+ expect(settled.size).toBe(0);+ });++ it("keeps a press the host still disagrees with", () => {+ const overlay = new Map([["b.ts", true]]);+ expect(settleFileViewedOverlay(overlay, states, NOTHING_PENDING, NOTHING_ANSWERED)).toBe(+ overlay,+ );+ });++ it("keeps a press the host cannot have heard yet", () => {+ // An answer already on its way when the file was un-ticked would otherwise put the tick back.+ const overlay = new Map([["a.ts", false]]);+ const settled = settleFileViewedOverlay(overlay, states, new Set(["a.ts"]), NOTHING_ANSWERED);+ expect(settled.get("a.ts")).toBe(false);+ });++ it("settles a file pushed to since it was cleared against un-ticking it", () => {+ const settled = settleFileViewedOverlay(+ new Map([["c.ts", false]]),+ states,+ NOTHING_PENDING,+ NOTHING_ANSWERED,+ );+ expect(settled.size).toBe(0);+ });++ it("drops a tick once a read has answered for it, against what the reader pressed", () => {+ // The tick landed, the file was pushed to before the read that followed it came back, and the+ // host answers `dismissed`. Holding the tick would hide that push for as long as the tab+ // stayed open, and no refresh would recover it: every later answer says `dismissed` too.+ const settled = settleFileViewedOverlay(+ new Map([["c.ts", true]]),+ states,+ NOTHING_PENDING,+ new Set(["c.ts"]),+ );+ expect(settled.size).toBe(0);+ expect(isFileViewed("c.ts", states, settled)).toBe(false);+ expect(isStaleViewedState(states?.get("c.ts"))).toBe(true);+ });++ it("holds a press made since the read that would otherwise answer for it", () => {+ const overlay = new Map([["c.ts", true]]);+ const settled = settleFileViewedOverlay(overlay, states, new Set(["c.ts"]), new Set(["c.ts"]));+ expect(settled.get("c.ts")).toBe(true);+ });++ it("holds everything until the host has answered at all", () => {+ const overlay = new Map([["a.ts", true]]);+ expect(settleFileViewedOverlay(overlay, null, NOTHING_PENDING, NOTHING_ANSWERED)).toBe(overlay);+ });+});++describe("toFileViewedBatch", () => {+ it("carries both directions in one batch", () => {+ expect(+ toFileViewedBatch(+ new Map([+ ["a.ts", false],+ ["b.ts", true],+ ]),+ ),+ ).toEqual([+ { path: "a.ts", viewed: false },+ { path: "b.ts", viewed: true },+ ]);+ });+});++describe("revertFileViewedOverlay", () => {+ const batch = [+ { path: "a.ts", viewed: true },+ { path: "b.ts", viewed: false },+ ];+ const both = new Set(["a.ts", "b.ts"]);++ it("puts the checkbox back to the host's answer for everything the request answers for", () => {+ const overlay = new Map([+ ["a.ts", true],+ ["b.ts", false],+ ]);+ expect(revertFileViewedOverlay(overlay, batch, both).size).toBe(0);+ });++ it("leaves a press the reader made after the request went out", () => {+ // The second press is waiting on a flush of its own, so the first one failing says nothing+ // about it.+ const overlay = new Map([+ ["a.ts", false],+ ["b.ts", false],+ ]);+ const reverted = revertFileViewedOverlay(overlay, batch, new Set(["b.ts"]));+ expect([...reverted]).toEqual([["a.ts", false]]);+ });++ it("leaves a path a later request took over, even pressed the same way", () => {+ // Both requests carry `a.ts` as viewed, so the value cannot tell them apart. The later one+ // owns the path now and is the one that answers for it.+ const overlay = new Map([["a.ts", true]]);+ expect(revertFileViewedOverlay(overlay, batch, new Set(["b.ts"]))).toBe(overlay);+ });++ it("leaves a path the request never carried", () => {+ const overlay = new Map([["c.ts", true]]);+ expect(revertFileViewedOverlay(overlay, batch, both)).toBe(overlay);+ });+});diff --git a/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.tsnew file mode 100644index 00000000000..409013a1b2c--- /dev/null+++ b/apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts@@ -0,0 +1,100 @@+import type { PullRequestFileViewedState, PullRequestFilesViewedResult } from "@t3tools/contracts";++/** What the host last said about each file, by path. Absent means the host said nothing. */+export type FileViewedStates = ReadonlyMap<string, PullRequestFileViewedState>;++/** Presses the host has not confirmed yet, by path. */+export type FileViewedOverlay = ReadonlyMap<string, boolean>;++export function toFileViewedStates(+ result: PullRequestFilesViewedResult | null,+): FileViewedStates | null {+ if (result === null) return null;+ return new Map(result.files.map((file) => [file.path, file.state]));+}++/**+ * Whether a file counts as seen. `dismissed` is the host saying it has been pushed to since the+ * reader cleared it, which reads as unseen: the point of the tick is that the code behind it has+ * been looked at, and it is not the same code any more.+ */+function isViewedState(state: PullRequestFileViewedState | undefined): boolean {+ return state === "viewed";+}++/** Whether the file was cleared and has since moved, which the header says out loud. */+export function isStaleViewedState(state: PullRequestFileViewedState | undefined): boolean {+ return state === "dismissed";+}++/** The press the reader made if it has not landed, and the host's answer otherwise. */+export function isFileViewed(+ path: string,+ states: FileViewedStates | null,+ overlay: FileViewedOverlay,+): boolean {+ const pressed = overlay.get(path);+ return pressed ?? isViewedState(states?.get(path));+}++export function countViewedFiles(+ paths: ReadonlyArray<string>,+ states: FileViewedStates | null,+ overlay: FileViewedOverlay,+): number {+ return paths.reduce(+ (total, path) => (isFileViewed(path, states, overlay) ? total + 1 : total),+ 0,+ );+}++/**+ * The overlay with everything the host has caught up on removed. A press is held until a read that+ * could have seen it comes back, rather than cleared when the write succeeds: that read is a+ * separate round trip, and dropping the press in between flashes the checkbox back.+ *+ * `pending` are the paths whose press the host cannot have heard yet, which an answer already on+ * its way must not overrule. `answered` are the paths a read has landed for since their write was+ * acknowledged, and those go on that read alone, including where it contradicts the press: a tick+ * held over a `dismissed` would hide a file pushed to since, with no refresh able to recover it.+ */+export function settleFileViewedOverlay(+ overlay: FileViewedOverlay,+ states: FileViewedStates | null,+ pending: ReadonlySet<string>,+ answered: ReadonlySet<string>,+): FileViewedOverlay {+ if (states === null || overlay.size === 0) return overlay;+ const next = new Map(overlay);+ for (const [path, pressed] of overlay) {+ if (pending.has(path)) continue;+ if (answered.has(path) || isViewedState(states.get(path)) === pressed) next.delete(path);+ }+ return next.size === overlay.size ? overlay : next;+}++/**+ * The overlay with a failed request's presses taken back. `owned` are the paths that request still+ * answers for, which keeps a failure from reaching past its own presses: a path pressed again+ * since belongs to a later request or to the next flush, and putting that box back to the host's+ * answer would take a press out from under the reader's hand.+ */+export function revertFileViewedOverlay(+ overlay: FileViewedOverlay,+ batch: ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>,+ owned: ReadonlySet<string>,+): FileViewedOverlay {+ const next = new Map(overlay);+ for (const { path, viewed } of batch) {+ if (!owned.has(path)) continue;+ if (next.get(path) === viewed) next.delete(path);+ }+ return next.size === overlay.size ? overlay : next;+}++/** The presses in an overlay as the batch the host is told about. */+export function toFileViewedBatch(+ overlay: FileViewedOverlay,+): ReadonlyArray<{ readonly path: string; readonly viewed: boolean }> {+ return [...overlay].map(([path, viewed]) => ({ path, viewed }));+}diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsxnew file mode 100644index 00000000000..78314b7ca7d--- /dev/null+++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx@@ -0,0 +1,161 @@+import {+ EnvironmentId,+ ProjectId,+ type PullRequestFilesViewedResult,+ type PullRequestRef,+} from "@t3tools/contracts";+import { AsyncResult } from "effect/unstable/reactivity";+import { act, StrictMode } from "react";+import { create, type ReactTestRenderer } from "react-test-renderer";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const { host, setFilesViewed, toastAdd } = vi.hoisted(() => ({+ host: { data: null as unknown, refresh: vi.fn() },+ setFilesViewed: vi.fn(),+ toastAdd: vi.fn(),+}));++vi.mock("~/state/pullRequests", () => ({+ pullRequestEnvironment: { filesViewed: () => null, setFilesViewed: {} },+}));+vi.mock("~/state/query", () => ({+ useEnvironmentQuery: () => ({+ data: host.data,+ error: null,+ isPending: false,+ isSuccess: true,+ refresh: host.refresh,+ }),+}));+vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => setFilesViewed }));+vi.mock("../ui/toast", () => ({ toastManager: { add: toastAdd } }));++import {+ usePullRequestFilesViewed,+ type PullRequestFilesViewedView,+} from "./usePullRequestFilesViewed";++const environmentId = EnvironmentId.make("pr-files-viewed-audit");+const reference: PullRequestRef = {+ projectId: ProjectId.make("project-a"),+ repository: "acme/web",+ number: 42,+};+const paths = ["a.ts"];++/** What the host answers, as a fresh object each time: a read is only a read if it is a new one. */+function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesViewedResult {+ return { files: [{ path: "a.ts", state }], truncated: false };+}++let renderer: ReactTestRenderer | null = null;++function Probe(_props: { readonly view: PullRequestFilesViewedView }) {+ return null;+}++function Surface() {+ const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true, paths });+ return <Probe view={view} />;+}++function view(): PullRequestFilesViewedView {+ return renderer!.root.findByType(Probe).props.view;+}++/** The host's next answer landing, which is what a `refresh` ends in. */+async function reads(state: "unviewed" | "viewed" | "dismissed") {+ host.data = answer(state);+ await act(async () =>+ renderer!.update(+ <StrictMode>+ <Surface />+ </StrictMode>,+ ),+ );+}++beforeEach(async () => {+ vi.useFakeTimers();+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ host.data = answer("unviewed");+ host.refresh.mockReset();+ toastAdd.mockReset();+ setFilesViewed.mockReset().mockResolvedValue(AsyncResult.success(undefined));+ act(() => {+ renderer = create(+ <StrictMode>+ <Surface />+ </StrictMode>,+ );+ });+});++afterEach(async () => {+ await act(async () => renderer?.unmount());+ renderer = null;+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("a mark whose file was pushed to before the read that followed it", () => {+ it("gives way to the host and shows the file as changed", async () => {+ view().setViewed("a.ts", true);+ await act(async () => vi.advanceTimersByTimeAsync(500));+ expect(setFilesViewed).toHaveBeenCalledExactlyOnceWith({+ environmentId,+ input: { ...reference, files: [{ path: "a.ts", viewed: true }] },+ });+ expect(host.refresh).toHaveBeenCalled();++ // The push landed between the write and this read, so the host answers `dismissed` rather+ // than the `viewed` the press asked for.+ await reads("dismissed");++ expect(view().isViewed("a.ts")).toBe(false);+ expect(view().isStale("a.ts")).toBe(true);+ expect(view().viewedCount).toBe(0);+ });++ it("stays given way to on every later read, having nothing left to recover", async () => {+ view().setViewed("a.ts", true);+ await act(async () => vi.advanceTimersByTimeAsync(500));+ await reads("dismissed");++ view().refresh();+ await reads("dismissed");++ expect(view().isViewed("a.ts")).toBe(false);+ expect(view().isStale("a.ts")).toBe(true);+ });+});++describe("a mark the host has not answered for yet", () => {+ it("holds the press while the write is still out", async () => {+ let land = (_result: unknown) => {};+ setFilesViewed.mockReturnValueOnce(new Promise((resolve) => (land = resolve)));++ view().setViewed("a.ts", true);+ await act(async () => vi.advanceTimersByTimeAsync(500));++ // An answer already on its way when the box was ticked must not put it back.+ await reads("unviewed");+ expect(view().isViewed("a.ts")).toBe(true);++ await act(async () => land(AsyncResult.success(undefined)));+ expect(view().isViewed("a.ts")).toBe(true);+ });++ it("holds a press made since the read that would otherwise answer for it", async () => {+ view().setViewed("a.ts", true);+ await act(async () => vi.advanceTimersByTimeAsync(500));++ // Pressed again before the post-write read came back. That press is the one on screen, and+ // the read that answers for the first one says nothing about it.+ view().setViewed("a.ts", true);+ await reads("dismissed");++ expect(view().isViewed("a.ts")).toBe(true);+ expect(view().isStale("a.ts")).toBe(false);+ });+});diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.tsnew file mode 100644index 00000000000..c2ee3f4c0bf--- /dev/null+++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts@@ -0,0 +1,211 @@+import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";+import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";++import { pullRequestEnvironment } from "~/state/pullRequests";+import { useEnvironmentQuery } from "~/state/query";+import { useAtomCommand } from "~/state/use-atom-command";++import { toastManager } from "../ui/toast";+import {+ countViewedFiles,+ isFileViewed,+ isStaleViewedState,+ revertFileViewedOverlay,+ settleFileViewedOverlay,+ toFileViewedBatch,+ toFileViewedStates,+ type FileViewedOverlay,+ type FileViewedStates,+} from "./pullRequestFilesViewed.logic";++/**+ * How long presses gather before the host is told. Long enough that ticking down a file list+ * costs one request rather than one per file, short enough that a reader who ticks one file and+ * closes the tab has already been recorded.+ */+const FLUSH_DELAY_MS = 400;++const NO_OVERLAY: FileViewedOverlay = new Map();++export interface PullRequestFilesViewedView {+ /** Whether anything remembers this at all, which is what hides the whole control. */+ readonly enabled: boolean;+ readonly isViewed: (path: string) => boolean;+ /** This file has been pushed to since it was cleared. */+ readonly isStale: (path: string) => boolean;+ readonly setViewed: (path: string, viewed: boolean) => void;+ /** How many of the files on screen are ticked off. */+ readonly viewedCount: number;+ /** The host had more files than the read covered, so the count above may be short. */+ readonly truncated: boolean;+ /**+ * Why the marks could not be read, when they could not. The boxes fall back to the last answer+ * there was, or to empty when there has not been one, and neither of those says so on its own:+ * a reader who sees every box unticked has no way to tell a fresh review from a failed read.+ */+ readonly error: string | null;+ /** Re-ask the host, for the page's refresh button, which goes around the host's cache. */+ readonly refresh: () => void;+}++/**+ * Which files this reader has already cleared. The marks live on the server rather than in this+ * tab, so a review carried on from another machine picks up where it was left. Presses show+ * immediately and are held over the server's answer until a read that could have seen them comes+ * back, so the checkbox never waits on a round trip and never outlasts the record behind it.+ */+export function usePullRequestFilesViewed(options: {+ readonly environmentId: EnvironmentId;+ readonly reference: PullRequestRef;+ readonly enabled: boolean;+ /** The paths on screen, which is what the counter counts. */+ readonly paths: ReadonlyArray<string>;+}): PullRequestFilesViewedView {+ const { environmentId, reference, enabled, paths } = options;+ const query = useEnvironmentQuery(+ enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,+ );+ const refresh = query.refresh;+ // `query.data` holds the last answer through a failure, so the boxes stay where the host last+ // put them rather than emptying under the reader; the error travels with them, because ticks+ // that stopped being refreshed look exactly like ticks that are current.+ const states = useMemo(() => toFileViewedStates(query.data), [query.data]);+ const truncated = query.data?.truncated === true;+ const error = query.error;+ const [overlay, setOverlay] = useState<FileViewedOverlay>(NO_OVERLAY);+ const setFilesViewed = useAtomCommand(pullRequestEnvironment.setFilesViewed, {+ reportFailure: false,+ });++ // Presses waiting for the next flush, and, for every path a request is already carrying, which+ // request that is. A path pressed again while its request is out belongs to the later request+ // from then on, and the earlier one stops answering for it. Both are refs rather than state:+ // nothing on screen reads them, and the flush must see the latest.+ const queued = useRef<Map<string, boolean>>(new Map());+ const sentBy = useRef<Map<string, number>>(new Map());+ const requests = useRef(0);+ const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ // Everything held here belongs to one change request on one environment. The environment is+ // part of that: two of them can hand out the same project id, and a press made against one+ // must never be answered for by the other.+ const scopeKey = `${environmentId} ${reference.projectId} ${reference.repository} ${reference.number}`;+ const scope = useRef(scopeKey);++ // The host's answer as it stood when a completed write was acknowledged, per path. The first+ // answer that differs from it is the first read that could have seen the write, which is what+ // retires the press rather than the host happening to agree with it.+ const answeredFrom = useRef<Map<string, FileViewedStates | null>>(new Map());+ const statesRef = useRef(states);+ statesRef.current = states;++ useEffect(() => {+ const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]);+ const answered = new Set<string>();+ for (const [path, from] of answeredFrom.current) {+ if (pending.has(path) || from === states) continue;+ answered.add(path);+ answeredFrom.current.delete(path);+ }+ setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered));+ }, [states]);++ const flush = useCallback(() => {+ flushTimer.current = null;+ const batch = toFileViewedBatch(queued.current);+ if (batch.length === 0) return;+ queued.current = new Map();+ const sentFrom = scope.current;+ const request = ++requests.current;+ for (const file of batch) sentBy.current.set(file.path, request);+ void setFilesViewed({ environmentId, input: { ...reference, files: batch } }).then((result) => {+ const mine = batch+ .map((file) => file.path)+ .filter((path) => sentBy.current.get(path) === request);+ for (const path of mine) sentBy.current.delete(path);+ // The reader has moved on, and what is on screen now has nothing to do with this answer.+ if (scope.current !== sentFrom) return;+ if (result._tag === "Failure") {+ // The host never heard these, so the ticks go back to whatever it last said. Only the+ // paths this request still answers for: one pressed again since is waiting on a request+ // of its own, or on the next flush, and that press is the one on screen.+ const owned = new Set(mine.filter((path) => !queued.current.has(path)));+ setOverlay((current) => revertFileViewedOverlay(current, batch, owned));+ // Silent when nothing was still this request's to answer for, so nothing on screen went+ // back, and when the connection went away mid-flight, which the reader is already being+ // told about and which the host never refused.+ if (owned.size > 0 && !isAtomCommandInterrupted(result)) {+ toastManager.add({ type: "error", title: "Could not update viewed files" });+ }+ return;+ }+ // Answered for from the next read on, whatever it says. A push landing between the write+ // and that read comes back as `dismissed`, and the press must not stand over it.+ for (const path of mine) answeredFrom.current.set(path, statesRef.current);+ refresh();+ });+ }, [environmentId, reference, refresh, setFilesViewed]);++ // Read through a ref rather than closed over: `setViewed` is handed to every file header the+ // viewer draws, and a new identity per render would rebuild all of them.+ const flushRef = useRef(flush);+ flushRef.current = flush;++ // Leaving a change request, the environment it lives on, or the page itself records what was+ // pressed and then drops the rest. The flush kept here is the one bound to the scope being+ // left, which is what sends those last presses where they were meant to go.+ useEffect(() => {+ const flushScope = flushRef.current;+ scope.current = scopeKey;+ return () => {+ if (flushTimer.current !== null) {+ clearTimeout(flushTimer.current);+ flushScope();+ }+ queued.current = new Map();+ sentBy.current = new Map();+ answeredFrom.current = new Map();+ setOverlay(NO_OVERLAY);+ };+ }, [scopeKey]);++ const refreshRef = useRef(refresh);+ refreshRef.current = refresh;+ const refreshFromHost = useCallback(() => refreshRef.current(), []);++ const setViewed = useCallback((path: string, viewed: boolean) => {+ setOverlay((current) => new Map(current).set(path, viewed));+ queued.current.set(path, viewed);+ if (flushTimer.current !== null) clearTimeout(flushTimer.current);+ flushTimer.current = setTimeout(() => flushRef.current(), FLUSH_DELAY_MS);+ }, []);++ const isViewed = useCallback(+ (path: string) => isFileViewed(path, states, overlay),+ [overlay, states],+ );+ const isStale = useCallback(+ (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),+ [overlay, states],+ );+ const viewedCount = useMemo(+ () => countViewedFiles(paths, states, overlay),+ [overlay, paths, states],+ );++ // One identity per change of what it says: the viewer keys every file it draws off this.+ return useMemo(+ () => ({+ enabled,+ isViewed,+ isStale,+ setViewed,+ viewedCount,+ truncated,+ error,+ refresh: refreshFromHost,+ }),+ [enabled, error, isStale, isViewed, refreshFromHost, setViewed, truncated, viewedCount],+ );+}diff --git a/apps/web/src/lib/diffRendering.test.ts b/apps/web/src/lib/diffRendering.test.tsindex 33d015d52d3..4f6746942af 100644--- a/apps/web/src/lib/diffRendering.test.ts+++ b/apps/web/src/lib/diffRendering.test.ts@@ -209,3 +209,62 @@ describe("getDiffLineStat", () => {expect(getDiffLineStat(parsed.files)).toEqual({ additions: 3, deletions: 2 });});});++describe("a file whose name a patch header cannot carry plainly", () => {+ /** How git writes such a name, and so how every provider's patch arrives here. */+ const quotedPatch = (written: string) =>+ [+ `diff --git "a/${written}" "b/${written}"`,+ "index 1111111..2222222 100644",+ `--- "a/${written}"`,+ `+++ "b/${written}"`,+ "@@ -1 +1 @@",+ "-before",+ "+after",+ "",+ ].join("\n");++ const pathOf = (patch: string) => {+ const parsed = getRenderablePatch(patch, "review");+ expect(parsed?.kind).toBe("files");+ if (parsed?.kind !== "files") throw new Error("patch did not parse as files");+ const file = parsed.files[0];+ expect(file).toBeDefined();+ if (!file) throw new Error("patch carried no file");+ return resolveFileDiffPath(file);+ };++ it("is the name the host knows, not the part of it before the tab", () => {+ // The path is what a viewed mark, a review comment and a file read are all asked for by, so a+ // name read short is a mark put on a path the host has never heard of.+ expect(pathOf(quotedPatch("tab\\tfile.txt"))).toBe("tab\tfile.txt");+ });++ it("is the name the host knows, not the part of it before the newline", () => {+ expect(pathOf(quotedPatch("line\\nfile.txt"))).toBe("line\nfile.txt");+ });++ it("reads the octal a host with core.quotePath on writes for a name outside ASCII", () => {+ expect(pathOf(quotedPatch("caf\\303\\251/r\\303\\251sum\\303\\251.ts"))).toBe("café/résumé.ts");+ });++ it("reads both sides of a rename under the names they really have", () => {+ const patch = [+ 'diff --git "a/old\\tname.ts" "b/new\\tname.ts"',+ "similarity index 90%",+ 'rename from "old\\tname.ts"',+ 'rename to "new\\tname.ts"',+ "",+ ].join("\n");++ const parsed = getRenderablePatch(patch, "review");+ expect(parsed?.kind).toBe("files");+ if (parsed?.kind !== "files") return;+ const file = parsed.files[0];+ expect(file).toBeDefined();+ if (!file) return;++ expect(resolveFileDiffPath(file)).toBe("new\tname.ts");+ expect(resolveFileDiffPreviousPath(file)).toBe("old\tname.ts");+ });+});diff --git a/apps/web/src/lib/diffRendering.ts b/apps/web/src/lib/diffRendering.tsindex 2af48db53a8..257b4e7f8d6 100644--- a/apps/web/src/lib/diffRendering.ts+++ b/apps/web/src/lib/diffRendering.ts@@ -1,5 +1,6 @@import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";import type { FileDiffMetadata } from "@pierre/diffs/types";+import { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";const DIFF_THEME_NAMES = {light: "pierre-light",@@ -143,8 +144,18 @@ export function getRenderablePatch(}}+/**+ * What the patch called the file, as the file's own name. Git writes a name holding a tab, a+ * newline, a quote or a backslash quoted and escaped, and the parser hands one of those back still+ * escaped. A viewed mark, a review comment and a file's contents are all asked for by this path,+ * and the host knows the file only under the name it really has.+ */+function fileDiffPath(raw: string): string {+ return unquoteGitPatchPath(raw);+}+export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {- return fileDiff.name ?? fileDiff.prevName ?? "";+ return fileDiffPath(fileDiff.name ?? fileDiff.prevName ?? "");}/**@@ -152,7 +163,7 @@ export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {* path, and the hosts that resolve a diff position against both sides need both names.*/export function resolveFileDiffPreviousPath(fileDiff: FileDiffMetadata): string {- return fileDiff.prevName ?? fileDiff.name ?? "";+ return fileDiffPath(fileDiff.prevName ?? fileDiff.name ?? "");}export function buildFileDiffIdentityKey(fileDiff: FileDiffMetadata): string {diff --git a/apps/web/src/lib/openPullRequestLink.test.ts b/apps/web/src/lib/openPullRequestLink.test.tsindex a709b7d8add..0aaa43a735a 100644--- a/apps/web/src/lib/openPullRequestLink.test.ts+++ b/apps/web/src/lib/openPullRequestLink.test.ts@@ -11,6 +11,7 @@ import {shouldOpenPullRequestExternally,} from "./openPullRequestLink";import { ProjectId, type RepositoryIdentity } from "@t3tools/contracts";+import { normalizeGitRemoteUrl } from "@t3tools/shared/git";function repositoryIdentity(provider: string,@@ -498,6 +499,32 @@ describe("findProjectForChangeRequest", () => {).toBeUndefined();});+ it("matches an Azure repository cloned over SSH, whose remote shares no part with its URL", () => {+ // Azure alone addresses one repository under two names: `ssh.dev.azure.com` and `v3/...` over+ // SSH against `dev.azure.com` and `.../_git/...` everywhere a person sees it. The identity is+ // recorded in the spelling a link arrives in, so both halves of this comparison line up.+ //+ // Derived from the SSH remote the way the server derives it rather than written out, so the+ // day that normalization stops reaching the web spelling this fails here too.+ const canonicalKey = normalizeGitRemoteUrl("[email protected]:v3/T3Tools/Platform/T3Code");+ const projects = [+ project({+ canonicalKey,+ provider: "azure-devops",+ displayName: canonicalKey.split("/").slice(1).join("/"),+ owner: "t3tools",+ name: "t3code",+ }),+ ];+ expect(+ findProjectForChangeRequest(projects, {+ host: "dev.azure.com",+ repository: "t3tools/platform/_git/t3code",+ number: 1,+ }),+ ).toBe(projects[0]);+ });+it("claims nothing for a lookalike host, which is what keeps a link a link", () => {const projects = [project({diff --git a/docs/README.md b/docs/README.mdindex 4691e6f83c8..09c6269ed58 100644--- a/docs/README.md+++ b/docs/README.md@@ -36,6 +36,7 @@ source alone does not explain. Most code changes do not need an internal documen- [Glossary](./internals/glossary.md)- [Connection runtime](./internals/connection-runtime.md)- [Providers](./internals/providers.md)+- [Pull request file revisions](./internals/pull-request-file-revisions.md)- [Model classification](./internals/model-manifest.md)- [Remote environments](./internals/remote.md)- [Server updates](./internals/server-updates.md)diff --git a/docs/internals/pull-request-file-revisions.md b/docs/internals/pull-request-file-revisions.mdnew file mode 100644index 00000000000..3a84b8de665--- /dev/null+++ b/docs/internals/pull-request-file-revisions.md@@ -0,0 +1,65 @@+# Pull request file revisions++On a host that keeps no viewed-file record of its own, this environment keeps the marks and asks+the host what version each marked file is at, so that a push can report a cleared file as changed.+That version travels through four layers, and a missing entry means something different at each+one. No type distinguishes those meanings and no single file states the whole path, which is what+this page is for.++The failure is on record rather than hypothetical. The interface doc above+[GitLab's `getFileRevisions`](../../apps/server/src/pullRequest/GitLabPullRequestCli.ts) once said+the opposite of the code beneath it, because it described a missing path the way the layer below+means it. Anything written against that reading would treat a version the host declined to give as+a file the change request deleted, which reports every file a reader has cleared as changed across+a project the token cannot see.++## An absence changes meaning at the provider boundary++Below the boundary, in a patch parser or a response decoder, a missing path means this revision+does not carry that file. Above it, in+[`ProviderFileRevisions`](../../apps/server/src/pullRequest/PullRequestProvider.ts), a missing path+means the read could not say. A provider's `getFileRevisions` converts on the way up: a path its+host looked at and has no version for arrives as the empty string, and absence is kept for what+the provider never got to look at. Absence below the boundary does not survive it.++What "never got to look at" is belongs to the host, and the contract cannot know any of them:++- [Azure DevOps](../../apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts) reads every+ version off one iteration listing, so a change too long to follow to its end leaves the paths+ past that point out.+- [Bitbucket](../../apps/server/src/pullRequest/BitbucketPullRequestApi.ts) reads them off the+ pull request's own patch, the only place it states a file's version, so a patch cut short at the+ byte ceiling leaves the paths past the cut out.+- [GitLab](../../apps/server/src/pullRequest/GitLabPullRequestCli.ts) asks in batches, so a batch+ it could not read leaves that batch's paths out.++Those three facts stay with their providers. The contract states only that absence means the read+could not say, which is the half a provider must convert to.++## Three nulls, and the empty string is not one of them++The empty string is an answer: the host looked, and the head has no version, which is where a+deleted file sits. It compares equal to a mark stamped with it, so a mark taken against a deletion+is cleared once and stays cleared. Everything below is the absence of an answer, and the three+forms are not interchangeable.++A null map, from the service's read of the whole scope, costs those marks their staleness. They+still report as cleared; they stop noticing pushes. It happens when the provider offers no+`getFileRevisions` at all, and, on either path, when the call failed and was logged. A press that+gets no answer does not refuse the reader's tick: it stores the mark with no baseline, which is+the third form below.++A path absent from an answered map is the per-path case, and it is the one that must not be read+as a deletion. [`HeldFileRevisions`](../../apps/server/src/pullRequest/pullRequestViewedFiles.ts)+records what it has asked as well as what it heard, so an absent path keeps the last version given+for it instead of losing one.++A null on the stored mark is the third, and the only one this environment invents.+[`PullRequestFileViewedMark`](../../apps/server/src/persistence/PullRequestFilesViewed.ts) stores+`revision` as nullable so a press that got no answer for a path can store no baseline at all.+Storing the empty string instead would report the file as changed the moment the host turned out+to have a version after all. A mark with no baseline reads as cleared until the reader presses it+again.++Both read-side nulls collapse into that third one on the write path: whether the map was null or+the path was only absent from it, the press stores a mark with no baseline.diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex d8a06fc34b6..40881057163 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -118,8 +118,22 @@ for ten minutes during a GitHub outage; new credentials must be verified first.an uncertain result is never automatically retried elsewhere. Listings, diffs, and checkout orPR creation from Git actions continue to use the project's environment.-For Azure DevOps, use the host website to view diffs or change comments. Bitbucket does not support-reopening a declined pull request.+For Azure DevOps, use the host website to change comments. Bitbucket does not support reopening a+declined pull request.++### Mark files as viewed++Tick a file off in the **Code** tab once you have read it and it collapses; the toolbar keeps a+running count. A tick belongs to the pull request rather than to a commit, so scoping the tab to a+single commit keeps them. A file pushed to after you cleared it comes back marked **Changed**.++On GitHub these are GitHub's own viewed marks, so a review carries between T3 Code and github.com+in either direction. Forgejo, GitLab, Bitbucket, and Azure DevOps expose no record T3 Code can read, so the+server you are connected to keeps them instead: they follow you across the apps connected to that+server, but the host's own site will not show them, and the count reads **viewed in T3 Code**.++The **Code** tab is a web and desktop surface. The mobile app reports a pull request's status but+does not show its diff, so marks are made and read on web and desktop.## Troubleshootingdiff --git a/packages/client-runtime/src/state/pullRequestRouting.ts b/packages/client-runtime/src/state/pullRequestRouting.tsindex 555c870d04e..64ccb9cdad8 100644--- a/packages/client-runtime/src/state/pullRequestRouting.ts+++ b/packages/client-runtime/src/state/pullRequestRouting.ts@@ -32,10 +32,12 @@ const reads = new Set<string>([WS_METHODS.pullRequestsActivity,WS_METHODS.pullRequestsThreadComments,WS_METHODS.pullRequestsDiffFileContents,+ WS_METHODS.pullRequestsFilesViewed,WS_METHODS.pullRequestsReviewerCandidates,WS_METHODS.pullRequestsLabelCandidates,]);const writes = new Set<string>([+ WS_METHODS.pullRequestsSetFilesViewed,WS_METHODS.pullRequestsRunAction,WS_METHODS.pullRequestsUpdate,WS_METHODS.pullRequestsComment,@@ -182,7 +184,7 @@ export function createPullRequestRouter() {targets,([target, reference]) =>invalidateTarget(registry, origin.target.environmentId, target, [- input.reference === undefined ? {} : { reference },+ { ...input, ...(input.reference === undefined ? {} : { reference }) },]),{ concurrency: 4, discard: true },);@@ -229,8 +231,13 @@ export function createPullRequestRouter() {targets,([target, refs]) =>invalidateTarget(registry, origin.target.environmentId, target, [- ...refs.map((reference) => ({ reference })),- {},+ ...refs.map((reference) => ({+ reference,+ ...(tag === WS_METHODS.pullRequestsSetFilesViewed+ ? { filesViewedOnly: true }+ : {}),+ })),+ ...(tag === WS_METHODS.pullRequestsSetFilesViewed ? [] : [{}]),]),{ concurrency: 4, discard: true },);diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.tsindex 8b359b68517..6fa1141669a 100644--- a/packages/client-runtime/src/state/pullRequests.test.ts+++ b/packages/client-runtime/src/state/pullRequests.test.ts@@ -236,6 +236,84 @@ for (const scenario of [);}+for (const provider of ["github", "gitlab", "bitbucket", "azure-devops"] as const) {+ it.effect(`routes ${provider} viewed marks to their storage environment`, () =>+ Effect.scoped(+ Effect.gen(function* () {+ const reference = {+ projectId: ProjectId.make("project-1"),+ host: "github.com",+ repository: "acme/web",+ number: 7,+ };+ const calls: { environment: string; operation: string; input: unknown }[] = [];+ const clientFor = (environment: string) =>+ ({+ [WS_METHODS.pullRequestsRouting]: () =>+ Effect.succeed({+ host: reference.host,+ provider,+ accountId: "123",+ viewer: "maria-rcks",+ }),+ [WS_METHODS.pullRequestsRoutingIdentity]: () =>+ Effect.succeed({+ host: reference.host,+ provider,+ accountId: "123",+ viewer: "maria-rcks",+ }),+ [WS_METHODS.pullRequestsFilesViewed]: (input: unknown) =>+ Effect.sync(() => {+ calls.push({ environment, operation: "read", input });+ return { files: [{ path: "a.ts", state: "viewed" }], truncated: false };+ }),+ [WS_METHODS.pullRequestsSetFilesViewed]: (input: unknown) =>+ Effect.sync(() => {+ calls.push({ environment, operation: "write", input });+ }),+ [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>+ Effect.sync(() => {+ calls.push({ environment, operation: "invalidate", input });+ }),+ }) as unknown as WsRpcProtocolClient;+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(+ clientFor("origin"),+ clientFor("local"),+ );+ const files = [{ path: "a.ts", viewed: false }];+ const route = createPullRequestRouter();+ yield* Effect.gen(function* () {+ expect(yield* route(WS_METHODS.pullRequestsFilesViewed, reference)).toEqual({+ files: [{ path: "a.ts", state: "viewed" }],+ truncated: false,+ });+ yield* route(WS_METHODS.pullRequestsSetFilesViewed, { ...reference, files });+ }).pipe(+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),+ Effect.provideService(GitHubRoutingPermissions, trustedRouting),+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ );+ const environment = provider === "github" ? "local" : "origin";+ const guard = provider === "github" ? { expectedAccountId: "123" } : {};+ expect(calls.filter((call) => call.operation !== "invalidate")).toEqual([+ { environment, operation: "read", input: { ...reference, allowStale: false, ...guard } },+ { environment, operation: "write", input: { ...reference, files, ...guard } },+ ]);+ const invalidations = calls.filter((call) => call.operation === "invalidate");+ if (provider === "github") expect(invalidations.length).toBeGreaterThan(0);+ else expect(invalidations).toEqual([]);+ for (const call of invalidations) {+ expect(call.input).toEqual({+ reference: expect.objectContaining(reference),+ filesViewedOnly: true,+ });+ }+ }),+ ),+ );+}+const TARGET = new PrimaryConnectionTarget({environmentId: EnvironmentId.make("environment-1"),label: "Test environment",diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 1086066de68..d8c000863ab 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -270,6 +270,27 @@ export function createPullRequestEnvironmentAtoms<R, E>(]),},}),+ filesViewed: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:pull-requests:files-viewed",+ tag: WS_METHODS.pullRequestsFilesViewed,+ execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),+ staleTimeMs: 15_000,+ }),+ /**+ * One write in flight per change request: the host applies these in order, and a reader+ * ticking down a file list faster than the round trip would otherwise race their own presses.+ */+ setFilesViewed: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:pull-requests:set-files-viewed",+ tag: WS_METHODS.pullRequestsSetFilesViewed,+ execute: (input) => routedRequest(WS_METHODS.pullRequestsSetFilesViewed, input),+ scheduler: commandScheduler,+ concurrency: {+ mode: "serial",+ key: ({ environmentId, input }) =>+ JSON.stringify([environmentId, input.projectId, input.repository, input.number]),+ },+ }),runAction: createEnvironmentRpcCommand(runtime, {label: "environment-data:pull-requests:run-action",tag: WS_METHODS.pullRequestsRunAction,diff --git a/packages/contracts/src/pullRequest.test.ts b/packages/contracts/src/pullRequest.test.tsindex f268e309ae6..9ea74eb7873 100644--- a/packages/contracts/src/pullRequest.test.ts+++ b/packages/contracts/src/pullRequest.test.ts@@ -4,9 +4,11 @@ import { describe, expect, it } from "vite-plus/test";import {PullRequestActionInput,PullRequestCapabilities,+ PullRequestFilesViewedResult,PullRequestListInput,PullRequestListResult,PullRequestReviewerRequestInput,+ PullRequestSetFilesViewedInput,pullRequestHostOf,resolvePullRequestAuthorFilter,} from "./pullRequest.ts";@@ -15,6 +17,8 @@ const decodeListResult = Schema.decodeUnknownSync(PullRequestListResult);const decodeListInput = Schema.decodeUnknownSync(PullRequestListInput);const decodeReviewerRequest = Schema.decodeUnknownSync(PullRequestReviewerRequestInput);const decodeAction = Schema.decodeUnknownSync(PullRequestActionInput);+const decodeSetFilesViewed = Schema.decodeUnknownSync(PullRequestSetFilesViewedInput);+const decodeFilesViewed = Schema.decodeUnknownSync(PullRequestFilesViewedResult);const LIST_RESULT: PullRequestListResult = {viewers: { "github.com": "bilal", "gitlab.com": "bilal.hassan" },@@ -271,3 +275,66 @@ describe("naming the reader as the author to narrow by", () => {expect(resolvePullRequestAuthorFilter("me", " ")).toBe("me");});});++describe("naming the file a tick belongs to", () => {+ // A space on either end of a name is part of the name as far as git is concerned. The patch on+ // screen and the environment's record of what was cleared are both keyed by it, so a path+ // tidied in transit ticks a file that does not exist and leaves the one on screen unticked.+ it("keeps the spaces around a path being ticked", () => {+ expect(+ decodeSetFilesViewed({+ projectId: "p1",+ repository: "group/project",+ number: 7,+ files: [{ path: "docs/readme.md ", viewed: true }],+ }).files,+ ).toEqual([{ path: "docs/readme.md ", viewed: true }]);+ });++ it("keeps the spaces around a path being reported back", () => {+ expect(+ decodeFilesViewed({+ files: [{ path: " leading.md", state: "viewed" }],+ truncated: false,+ }).files,+ ).toEqual([{ path: " leading.md", state: "viewed" }]);+ });++ it("still refuses a path that is nothing at all", () => {+ expect(() =>+ decodeSetFilesViewed({+ projectId: "p1",+ repository: "group/project",+ number: 7,+ files: [{ path: "", viewed: true }],+ }),+ ).toThrow();+ });++ it("refuses a batch larger than a reader can press", () => {+ // Every element of a batch is a statement of its own inside one transaction on an+ // environment-kept host, or a field of its own in one GraphQL document on GitHub, so what a+ // client may send has to be bounded rather than trusted to be a burst of presses.+ const press = (path: string) => ({ path, viewed: true });+ const batch = (count: number) => ({+ projectId: "p1",+ repository: "group/project",+ number: 7,+ files: Array.from({ length: count }, (_, at) => press(`src/f${at}.ts`)),+ });++ expect(() => decodeSetFilesViewed(batch(500))).not.toThrow();+ expect(() => decodeSetFilesViewed(batch(501))).toThrow();+ });++ it("refuses a path far longer than any real one", () => {+ expect(() =>+ decodeSetFilesViewed({+ projectId: "p1",+ repository: "group/project",+ number: 7,+ files: [{ path: `src/${"a".repeat(4096)}.ts`, viewed: true }],+ }),+ ).toThrow();+ });+});diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex 4045fe4126b..41c9250f2c6 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -371,6 +371,14 @@ export const PullRequestReviewerCapabilities = Schema.Struct({});export type PullRequestReviewerCapabilities = typeof PullRequestReviewerCapabilities.Type;+/**+ * Who remembers which files a reader has cleared. `host` is the host's own record, so the marks+ * are the ones its web UI shows and a review can be carried on from either side. `environment` is+ * this server's record, for a host that keeps none anything outside one browser can read.+ */+export const PullRequestViewedFilesStore = Schema.Literals(["host", "environment"]);+export type PullRequestViewedFilesStore = typeof PullRequestViewedFilesStore.Type;+/*** What a provider can actually do, so a surface can hide what is missing rather than offer an* action that would fail. Every provider fills this in for itself; nothing is assumed.@@ -407,6 +415,11 @@ export const PullRequestCapabilities = Schema.Struct({* what every server before this field was.*/reactions: Schema.optional(Schema.Boolean),+ /**+ * Where the reader's own marks are kept, or absent where they are kept nowhere and the+ * checkbox is not offered at all. Optional for the same reason as `reactions`.+ */+ viewedFiles: Schema.optional(PullRequestViewedFilesStore),review: PullRequestReviewCapabilities,reviewers: PullRequestReviewerCapabilities,/**@@ -784,6 +797,8 @@ export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type;*/export const PullRequestInvalidateInput = Schema.Struct({reference: Schema.optional(PullRequestRef),+ /** Refresh review progress across routed environments without discarding the patch. */+ filesViewedOnly: Schema.optional(Schema.Boolean),});export type PullRequestInvalidateInput = typeof PullRequestInvalidateInput.Type;@@ -953,6 +968,66 @@ export const PullRequestDiffFileContentsResult = Schema.Struct({});export type PullRequestDiffFileContentsResult = typeof PullRequestDiffFileContentsResult.Type;+/**+ * Bounded because a path arrives from a client rather than from the host: one element of a write+ * batch could otherwise carry a megabyte into a SQL statement or a GraphQL field.+ */+const MAX_FILE_PATH_LENGTH = 4096;+/**+ * Not trimmed: a leading or trailing space is a legal part of a file's name, and the mark is+ * keyed by the name the host gave, so trimming files it under a name nothing else uses.+ */+const FilePath = Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(MAX_FILE_PATH_LENGTH));++/**+ * Where one file of a change request stands with the person reading it. `dismissed` is the file+ * that was cleared and has since been pushed to, which is worth telling a reader apart from+ * `unviewed`: this file and not the other forty is the one that moved.+ */+export const PullRequestFileViewedState = Schema.Literals(["unviewed", "viewed", "dismissed"]);+export type PullRequestFileViewedState = typeof PullRequestFileViewedState.Type;++export const PullRequestFileViewed = Schema.Struct({+ path: FilePath,+ state: PullRequestFileViewedState,+});+export type PullRequestFileViewed = typeof PullRequestFileViewed.Type;++/**+ * Which files of a change request the reader has cleared. Its own read rather than a field on the+ * patch: a patch changes when somebody pushes and is cached by the minute, this changes on every+ * press, so one read would have to be wrong for the other to be right.+ */+export const PullRequestFilesViewedResult = Schema.Struct({+ /** Only the files the host reported a state for. A file missing from this list is unviewed. */+ files: Schema.Array(PullRequestFileViewed),+ /** The host had more files than were read, so the count is short and says so. */+ truncated: Schema.Boolean,+});+export type PullRequestFilesViewedResult = typeof PullRequestFilesViewedResult.Type;++/**+ * How many presses one write carries. Every element is a statement of its own inside one+ * transaction here, or a field of its own in one GraphQL document on GitHub. Matched to what a+ * read of the marks carries, so a client cannot write more of them than it can ever read back.+ */+const MAX_FILES_VIEWED_PRESSES = 500;++/**+ * Files to clear, or to put back. Several at once because a reader working down a diff ticks+ * boxes far faster than a host answers, so a burst is gathered into one request.+ */+export const PullRequestSetFilesViewedInput = Schema.Struct({+ ...PullRequestRef.fields,+ files: Schema.Array(+ Schema.Struct({+ path: FilePath,+ viewed: Schema.Boolean,+ }),+ ).check(Schema.isMaxLength(MAX_FILES_VIEWED_PRESSES)),+});+export type PullRequestSetFilesViewedInput = typeof PullRequestSetFilesViewedInput.Type;+export const PullRequestStackHead = Schema.Struct({number: PositiveInt,headSha: TrimmedNonEmptyString,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 9096dd6e27f..dec42aac153 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -113,6 +113,7 @@ import {PullRequestDetail,PullRequestDiffFileContentsInput,PullRequestDiffFileContentsResult,+ PullRequestFilesViewedResult,PullRequestInvalidateInput,PullRequestListInput,PullRequestListResult,@@ -131,6 +132,7 @@ import {PullRequestReviewerRequestInput,PullRequestLabelCandidateList,PullRequestLabelChangeInput,+ PullRequestSetFilesViewedInput,PullRequestSubmitReviewInput,PullRequestThreadCommentsInput,PullRequestThreadCommentsResult,@@ -396,6 +398,8 @@ export const WS_METHODS = {pullRequestsActivity: "pullRequests.activity",pullRequestsThreadComments: "pullRequests.threadComments",pullRequestsDiffFileContents: "pullRequests.diffFileContents",+ pullRequestsFilesViewed: "pullRequests.filesViewed",+ pullRequestsSetFilesViewed: "pullRequests.setFilesViewed",pullRequestsRunAction: "pullRequests.runAction",pullRequestsUpdate: "pullRequests.update",pullRequestsComment: "pullRequests.comment",@@ -751,6 +755,18 @@ const WsPullRequestsDiffFileContentsRpc = Rpc.make(WS_METHODS.pullRequestsDiffFierror: PullRequestRpcError,});+const WsPullRequestsFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsFilesViewed, {+ payload: PullRequestRef,+ success: PullRequestFilesViewedResult,+ error: PullRequestRpcError,+});++const WsPullRequestsSetFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsSetFilesViewed, {+ payload: PullRequestSetFilesViewedInput,+ success: Schema.Void,+ error: PullRequestRpcError,+});+const WsPullRequestsRunActionRpc = Rpc.make(WS_METHODS.pullRequestsRunAction, {payload: PullRequestActionInput,success: Schema.Void,@@ -1405,6 +1421,8 @@ export const WsRpcGroup = RpcGroup.make(WsPullRequestsActivityRpc,WsPullRequestsThreadCommentsRpc,WsPullRequestsDiffFileContentsRpc,+ WsPullRequestsFilesViewedRpc,+ WsPullRequestsSetFilesViewedRpc,WsPullRequestsRunActionRpc,WsPullRequestsUpdateRpc,WsPullRequestsCommentRpc,diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 2a698489376..97452f4d4a9 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -338,6 +338,10 @@"./cliRelease": {"types": "./src/cliRelease.ts","import": "./src/cliRelease.ts"+ },+ "./gitPatchPath": {+ "types": "./src/gitPatchPath.ts",+ "import": "./src/gitPatchPath.ts"}},"scripts": {diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.tsindex 9d7ed527088..ce0defd0587 100644--- a/packages/shared/src/git.test.ts+++ b/packages/shared/src/git.test.ts@@ -50,6 +50,38 @@ describe("normalizeGitRemoteUrl", () => {"bitbucket.org/workspace/repo",);});++ it("gives an Azure DevOps repository the same key over SSH as over HTTPS", () => {+ expect(normalizeGitRemoteUrl("[email protected]:v3/T3Tools/Platform/T3Code")).toBe(+ "dev.azure.com/t3tools/platform/_git/t3code",+ );+ expect(normalizeGitRemoteUrl("ssh://[email protected]:22/v3/T3Tools/Platform/T3Code")).toBe(+ "dev.azure.com/t3tools/platform/_git/t3code",+ );+ expect(+ normalizeGitRemoteUrl("https://[email protected]/T3Tools/Platform/_git/T3Code"),+ ).toBe("dev.azure.com/t3tools/platform/_git/t3code");+ });++ it("puts the organization back in the host on the name dev.azure.com replaced", () => {+ expect(+ normalizeGitRemoteUrl("[email protected]:v3/T3Tools/Platform/T3Code"),+ ).toBe("t3tools.visualstudio.com/platform/_git/t3code");+ expect(normalizeGitRemoteUrl("https://T3Tools.visualstudio.com/Platform/_git/T3Code")).toBe(+ "t3tools.visualstudio.com/platform/_git/t3code",+ );+ });++ it("leaves an Azure SSH host it cannot read as the path it was given", () => {+ // Not `v3`, and not four segments: rewriting either would invent a repository that the web+ // spelling has no name for, so the remote stands as it arrived.+ expect(normalizeGitRemoteUrl("[email protected]:v4/T3Tools/Platform/T3Code")).toBe(+ "ssh.dev.azure.com/v4/t3tools/platform/t3code",+ );+ expect(normalizeGitRemoteUrl("[email protected]:v3/T3Tools/T3Code")).toBe(+ "ssh.dev.azure.com/v3/t3tools/t3code",+ );+ });});describe("parseOriginUrlFromGitConfig", () => {diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.tsindex 8e618d2d644..0c727955175 100644--- a/packages/shared/src/git.ts+++ b/packages/shared/src/git.ts@@ -108,6 +108,25 @@ export function isTemporaryWorktreeBranch(refName: string): boolean {return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());}+/**+ * The web spelling of an Azure DevOps repository reached over SSH, or null for anything else.+ *+ * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and+ * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`+ * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository+ * to every comparison made against a pull request URL, which arrives in the web spelling. So the+ * web spelling is the one both are keyed by.+ */+function azureDevOpsRepositoryKey(host: string, segments: ReadonlyArray<string>): string | null {+ if (host !== "ssh.dev.azure.com" && host !== "vs-ssh.visualstudio.com") return null;+ const [marker, organization, project, repository] = segments;+ if (segments.length !== 4 || marker !== "v3") return null;+ if (!organization || !project || !repository) return null;+ return host === "ssh.dev.azure.com"+ ? `dev.azure.com/${organization}/${project}/_git/${repository}`+ : `${organization}.visualstudio.com/${project}/_git/${repository}`;+}+/*** Normalize a git remote URL into a stable comparison key.*/@@ -121,12 +140,12 @@ export function normalizeGitRemoteUrl(value: string): string {if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {try {const url = new URL(normalized);- const repositoryPath = url.pathname- .split("/")- .filter((segment) => segment.length > 0)- .join("/");- if (url.hostname && repositoryPath.includes("/")) {- return `${url.hostname}/${repositoryPath}`;+ const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);+ if (url.hostname && repositorySegments.length > 1) {+ return (+ azureDevOpsRepositoryKey(url.hostname, repositorySegments) ??+ `${url.hostname}/${repositorySegments.join("/")}`+ );}} catch {return normalized;@@ -136,8 +155,10 @@ export function normalizeGitRemoteUrl(value: string): string {const scpStyleHostAndPath = /^[a-zA-Z0-9._-]+@([^:/\s]+):([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized,);- if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {- return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;+ const scpHost = scpStyleHostAndPath?.[1];+ const scpPath = scpStyleHostAndPath?.[2];+ if (scpHost && scpPath) {+ return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;}return normalized;diff --git a/packages/shared/src/gitPatchPath.test.ts b/packages/shared/src/gitPatchPath.test.tsnew file mode 100644index 00000000000..20c5065729f--- /dev/null+++ b/packages/shared/src/gitPatchPath.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from "vite-plus/test";++import { quoteGitPatchPath, unquoteGitPatchPath } from "./gitPatchPath.ts";++const BELL = "\u0007";+const UNIT_SEPARATOR = "\u001f";+const DELETE = "\u007f";++describe("quoteGitPatchPath", () => {+ it("leaves a name a header can carry as itself", () => {+ expect(quoteGitPatchPath("src/app.ts")).toBe("src/app.ts");+ expect(quoteGitPatchPath("with space.txt")).toBe("with space.txt");+ // Outside ASCII is only quoted for what a terminal can show, and a diff viewer is not one.+ expect(quoteGitPatchPath("café/résumé.ts")).toBe("café/résumé.ts");+ expect(quoteGitPatchPath("🚀.ts")).toBe("🚀.ts");+ });++ it("writes git's escape for a character the header would read as its own", () => {+ expect(quoteGitPatchPath("tab\tfile.txt")).toBe('"tab\\tfile.txt"');+ expect(quoteGitPatchPath("line\nfile.txt")).toBe('"line\\nfile.txt"');+ expect(quoteGitPatchPath('quo"te.txt')).toBe('"quo\\"te.txt"');+ expect(quoteGitPatchPath("back\\slash.txt")).toBe('"back\\\\slash.txt"');+ expect(quoteGitPatchPath(`ring${BELL}.txt`)).toBe('"ring\\a.txt"');+ });++ it("writes the octal of a control character git has no name for", () => {+ expect(quoteGitPatchPath(`unit${UNIT_SEPARATOR}.txt`)).toBe('"unit\\037.txt"');+ expect(quoteGitPatchPath(`del${DELETE}.txt`)).toBe('"del\\177.txt"');+ });+});++describe("a name written into a header and read back out", () => {+ const names = [+ "src/app.ts",+ "with space.txt",+ "café/résumé.ts",+ "🚀.ts",+ "tab\tfile.txt",+ "line\nfile.txt",+ "carriage\rfile.txt",+ 'quo"te.txt',+ "back\\slash.txt",+ `ring${BELL}.txt`,+ `unit${UNIT_SEPARATOR}.txt`,+ `del${DELETE}.txt`,+ `every\t\n\r"\\${BELL}.txt`,+ ];++ for (const name of names) {+ it(`is the name that went in: ${JSON.stringify(name)}`, () => {+ const written = quoteGitPatchPath(name);+ expect(unquoteGitPatchPath(written)).toBe(name);+ // A parser that takes the quotes off itself, as the clients' one does, gets there too.+ const unwrapped = written.startsWith('"') ? written.slice(1, -1) : written;+ expect(unquoteGitPatchPath(unwrapped)).toBe(name);+ });+ }++ it("carries the whole name past the first thing a header stops at", () => {+ const written = quoteGitPatchPath("tab\tfile.txt");++ // The bug this guards: a header line ends at a tab and splits on a space, so the name written+ // as itself would be read as `tab` and marked viewed under a path no host has.+ expect(written).not.toContain("\t");+ expect(written).not.toContain("\n");+ expect(unquoteGitPatchPath(written)).not.toBe("tab");+ });+});++describe("unquoteGitPatchPath", () => {+ it("leaves a token git saw no need to quote alone", () => {+ expect(unquoteGitPatchPath("src/app.ts")).toBe("src/app.ts");+ expect(unquoteGitPatchPath("with space.txt")).toBe("with space.txt");+ expect(unquoteGitPatchPath("")).toBe("");+ expect(unquoteGitPatchPath('"')).toBe('"');+ });++ it("reads the octal escapes a host with core.quotePath on writes", () => {+ expect(unquoteGitPatchPath('"caf\\303\\251/r\\303\\251sum\\303\\251.ts"')).toBe(+ "café/résumé.ts",+ );+ expect(unquoteGitPatchPath('"\\360\\237\\232\\200.ts"')).toBe("🚀.ts");+ });+});++describe("a name a parser handed back with its quotes already off", () => {+ it("is read for the escapes it still carries", () => {+ expect(unquoteGitPatchPath("tab\\tfile.txt")).toBe("tab\tfile.txt");+ expect(unquoteGitPatchPath("caf\\303\\251.ts")).toBe("café.ts");+ });++ it("reads an escape git would never write the way C reads it", () => {+ expect(unquoteGitPatchPath("odd\\zname.txt")).toBe("oddzname.txt");+ expect(unquoteGitPatchPath("trailing\\")).toBe("trailing\\");+ expect(unquoteGitPatchPath("short\\12.txt")).toBe("short12.txt");+ });+});diff --git a/packages/shared/src/gitPatchPath.ts b/packages/shared/src/gitPatchPath.tsnew file mode 100644index 00000000000..767600c4a4b--- /dev/null+++ b/packages/shared/src/gitPatchPath.ts@@ -0,0 +1,140 @@+/**+ * How a file's name travels in a unified patch, which is not as itself. A reader finds the name in+ * a header by where it stops: `diff --git a/<old> b/<new>` splits on a space, `--- a/<name>` stops+ * at a tab. So a name holding a tab or a newline reads back as the part of itself before that+ * byte, or fabricates a header line of its own, and git's answer is to write such a name quoted+ * with C-style escapes. Both halves live here so what one writes is what the other reads.+ */++/**+ * What git escapes by name, as the character written and the escape written for it. Not every byte+ * git would escape: `core.quotePath` also escapes anything outside ASCII, which is a setting for+ * what a terminal can show rather than anything the format needs, and a patch here is read by a+ * diff viewer.+ */+const ESCAPE_BY_CHARACTER = new Map([+ ['"', '\\"'],+ ["\\", "\\\\"],+ ["\u0007", "\\a"],+ ["\b", "\\b"],+ ["\t", "\\t"],+ ["\n", "\\n"],+ ["\v", "\\v"],+ ["\f", "\\f"],+ ["\r", "\\r"],+]);++/** The escape written for a character, as the byte it stands for. */+const CHARACTER_BY_ESCAPE: Record<string, number> = {+ '"': 0x22,+ "\\": 0x5c,+ a: 0x07,+ b: 0x08,+ f: 0x0c,+ n: 0x0a,+ r: 0x0d,+ t: 0x09,+ v: 0x0b,+};++const QUOTE = '"';+const DELETE_CHARACTER = 0x7f;+const LOWEST_PRINTABLE = 0x20;+const BACKSLASH = 0x5c;++const utf8 = new TextEncoder();+const fromUtf8 = new TextDecoder();++/**+ * A name as a patch header can carry it: itself where that is unambiguous, and git's quoted form+ * where it is not, which is any name holding a quote, a backslash or a control character. A header+ * side's `a/` or `b/` belongs inside the quoting, so pass it in along with the name: what git+ * quotes is the whole token a reader takes off the line, side letter and all.+ */+export function quoteGitPatchPath(path: string): string {+ let body = "";+ let quoting = false;+ for (const character of path) {+ const escape = ESCAPE_BY_CHARACTER.get(character);+ if (escape !== undefined) {+ body += escape;+ quoting = true;+ continue;+ }+ const code = character.codePointAt(0) ?? 0;+ // Every character git has no name for is written as the octal of its byte, and a control+ // character is one byte in UTF-8, so the character's own code point is that byte.+ if (code < LOWEST_PRINTABLE || code === DELETE_CHARACTER) {+ body += `\\${code.toString(8).padStart(3, "0")}`;+ quoting = true;+ continue;+ }+ body += character;+ }+ return quoting ? `${QUOTE}${body}${QUOTE}` : path;+}++/**+ * The escapes inside a quoted form undone, whether or not the quotes are still around them. A name+ * holding no backslash is already itself, and an escape git would never write reads the way C+ * reads it. The escapes are per byte, so a name in another alphabet arrives as a run of octal and+ * only reads back as itself once those bytes are rejoined and decoded together.+ */+function unescapeBody(body: string): string {+ if (!body.includes("\\")) return body;+ const bytes: Array<number> = [];+ // Anything left as itself is encoded a run at a time rather than a unit at a time, so a+ // character outside the basic plane keeps its pair together rather than coming back as halves.+ let literal = "";+ const flush = () => {+ if (literal.length === 0) return;+ bytes.push(...utf8.encode(literal));+ literal = "";+ };+ let at = 0;+ while (at < body.length) {+ const character = body.charAt(at);+ if (character !== "\\") {+ literal += character;+ at += 1;+ continue;+ }+ const escaped = body.charAt(at + 1);+ if (escaped === "") {+ flush();+ bytes.push(BACKSLASH);+ break;+ }+ const named = CHARACTER_BY_ESCAPE[escaped];+ if (named !== undefined) {+ flush();+ bytes.push(named);+ at += 2;+ continue;+ }+ const octal = body.slice(at + 1, at + 4);+ if (/^[0-7]{3}$/.test(octal)) {+ flush();+ bytes.push(Number.parseInt(octal, 8));+ at += 4;+ continue;+ }+ literal += escaped;+ at += 2;+ }+ flush();+ return fromUtf8.decode(new Uint8Array(bytes));+}++/**+ * One header's name token as the name it stands for. The escapes are undone whether the quotes are+ * still there or not, because patch parsers disagree about how much of the quoting they hand back:+ * the one the clients read diffs with takes the quotes off the `diff --git` line's names and+ * leaves them on a rename's.+ */+export function unquoteGitPatchPath(token: string): string {+ if (token.length >= 2 && token.startsWith(QUOTE) && token.endsWith(QUOTE)) {+ return unescapeBody(token.slice(1, -1));+ }+ return unescapeBody(token);+}diff --git a/packages/shared/src/sourceControl.test.ts b/packages/shared/src/sourceControl.test.tsindex f9c009fac04..d6c3bc5e1f8 100644--- a/packages/shared/src/sourceControl.test.ts+++ b/packages/shared/src/sourceControl.test.ts@@ -208,3 +208,17 @@ it("keeps a GitLab identity's whole path, because a nested group is part of the});expect(selector).toBe("group/subgroup/service");});++it("puts owner and name back together for an identity recorded before displayName", () => {+ const selector = sourceControlRepositorySelector({+ provider: "github",+ owner: "t3tools",+ name: "t3code",+ });+ expect(selector).toBe("t3tools/t3code");+});++it("names nothing for a project with no remote to name it by", () => {+ expect(sourceControlRepositorySelector(null)).toBeNull();+ expect(sourceControlRepositorySelector({ provider: "github" })).toBeNull();+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a2a0d9a9633..6feae2edd57 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -512,6 +512,9 @@ importers:'@opencode-ai/sdk':specifier: ^1.3.15version: 1.15.13+ diff:+ specifier: 8.0.3+ version: 8.0.3effect:specifier: 4.0.0-rc.112version: 4.0.0-rc.112(patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2)