TypeScript
fix(gitlab): threads on changed code show as outdated (#30423)
Antony6593f78f4437
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.tsindex e2162603fe0..39c57fba8b7 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts@@ -1260,6 +1260,9 @@ layer("GitLabPullRequestCli.layer", (it) => {old_path: "src/a.ts",new_line: 12,old_line: null,+ base_sha: "base",+ start_sha: "start",+ head_sha: "head",},},{@@ -1342,7 +1345,7 @@ layer("GitLabPullRequestCli.layer", (it) => {);const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;- const { threads, overviewFindingIds } = yield* cli.listDiscussions({+ const { threads, diffRefsByThreadId, overviewFindingIds } = yield* cli.listDiscussions({cwd: "/w",repository: "acme/web",number: 7,@@ -1354,6 +1357,9 @@ layer("GitLabPullRequestCli.layer", (it) => {{ id: "file789", path: "src/b.ts", line: null, side: "right" },{ id: "img012", path: "logo.png", line: null, side: "right" },]);+ expect([...diffRefsByThreadId]).toEqual([+ ["abc123", { baseSha: "base", startSha: "start", headSha: "head" }],+ ]);expect(threads[0]).toMatchObject({ isResolved: true });assert.strictEqual(threads[0]?.comments.length, 2);}),diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex b293e45ae4b..44390544f8d 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -283,6 +283,13 @@ const DIFF_TIMEOUT_MS = 60_000;const isVcsProcessExitError = Schema.is(VcsProcessExitError);const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;+export interface GitLabDiscussionThreads {+ readonly threads: ReadonlyArray<PullRequestReviewThread>;+ readonly diffRefsByThreadId: ReadonlyMap<string, GitLabDiffRefs>;+ readonly overviewFindingIds: ReadonlyArray<string>;+ readonly truncated: boolean;+}+export interface GitLabMergeRequestListBatch {readonly items: ReadonlyArray<GitLabMergeRequestListItem>;readonly truncated: boolean;@@ -523,14 +530,7 @@ export class GitLabPullRequestCli extends Context.Service<readonly host?: string | undefined;readonly repository: string;readonly number: number;- }) => Effect.Effect<- {- readonly threads: ReadonlyArray<PullRequestReviewThread>;- readonly overviewFindingIds: ReadonlyArray<string>;- readonly truncated: boolean;- },- GitLabPullRequestCliError- >;+ }) => Effect.Effect<GitLabDiscussionThreads, GitLabPullRequestCliError>;readonly submitReview: (input: {readonly cwd: string;@@ -1073,15 +1073,9 @@ export const make = Effect.gen(function* () {readonly number: number;readonly page: number;readonly collected: ReadonlyArray<PullRequestReviewThread>;+ readonly collectedDiffRefs: ReadonlyMap<string, GitLabDiffRefs>;readonly collectedFindingIds: ReadonlyArray<string>;- }): Effect.Effect<- {- readonly threads: ReadonlyArray<PullRequestReviewThread>;- readonly overviewFindingIds: ReadonlyArray<string>;- readonly truncated: boolean;- },- GitLabPullRequestCliError- > =>+ }): Effect.Effect<GitLabDiscussionThreads, GitLabPullRequestCliError> =>api({cwd: input.cwd,host: input.host,@@ -1105,21 +1099,31 @@ export const make = Effect.gen(function* () {);}const collected = [...input.collected, ...decoded.success.threads];+ const collectedDiffRefs = new Map([+ ...input.collectedDiffRefs,+ ...decoded.success.diffRefsByThreadId,+ ]);const collectedFindingIds = [...input.collectedFindingIds,...decoded.success.overviewFindingIds,];- const done = (truncated: boolean) =>- Effect.succeed({- threads: collected,- overviewFindingIds: collectedFindingIds,- truncated,- });+ const read = (truncated: boolean) => ({+ threads: collected,+ diffRefsByThreadId: collectedDiffRefs,+ overviewFindingIds: collectedFindingIds,+ truncated,+ });// Plain notes count toward the page size even when no positioned threads survive decoding.- if (decoded.success.rawCount < MAX_PAGE_SIZE) return done(false);+ if (decoded.success.rawCount < MAX_PAGE_SIZE) return Effect.succeed(read(false));return input.page >= CONVERSATION_PAGES- ? done(true)- : discussionsPage({ ...input, page: input.page + 1, collected, collectedFindingIds });+ ? Effect.succeed(read(true))+ : discussionsPage({+ ...input,+ page: input.page + 1,+ collected,+ collectedDiffRefs,+ collectedFindingIds,+ });}),);@@ -2295,7 +2299,13 @@ export const make = Effect.gen(function* () {}),listDiscussions: Effect.fn("GitLabPullRequestCli.listDiscussions")(function (input) {- return discussionsPage({ ...input, page: 1, collected: [], collectedFindingIds: [] });+ return discussionsPage({+ ...input,+ page: 1,+ collected: [],+ collectedDiffRefs: new Map(),+ collectedFindingIds: [],+ });}),submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) {diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.tsindex 768d2619676..d5e5793c68b 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts@@ -503,6 +503,7 @@ describe("optional activity reads", () => {committedDate: "2026-07-01T00:00:00Z",};const webUrl = "https://git.acme.dev/acme/web/-/merge_requests/7";+ const currentRefs = { baseSha: "base2", startSha: "start2", headSha: "head2" };const reads = {getMergeRequestDetail: () =>Effect.succeed({@@ -529,11 +530,17 @@ describe("optional activity reads", () => {checks: [],viewerCanMerge: true,reviewerIds: [],+ diffRefs: currentRefs,}),listNotes: () => Effect.succeed({ comments: [comment], truncated: false }),listCommits: () => Effect.succeed([commit]),listDiscussions: () =>- Effect.succeed({ threads: [], overviewFindingIds: [], truncated: false }),+ Effect.succeed({+ threads: [],+ diffRefsByThreadId: new Map(),+ overviewFindingIds: [],+ truncated: false,+ }),listReactions: () =>Effect.succeed({reactions: [],@@ -598,7 +605,12 @@ describe("optional activity reads", () => {listNotes: () =>Effect.succeed({ comments: [comment, finding, reply], truncated: false }),listDiscussions: () =>- Effect.succeed({ threads: [], overviewFindingIds: ["10"], truncated: false }),+ Effect.succeed({+ threads: [],+ diffRefsByThreadId: new Map(),+ overviewFindingIds: ["10"],+ truncated: false,+ }),}),),);@@ -633,6 +645,7 @@ describe("optional activity reads", () => {comments: [comment],},],+ diffRefsByThreadId: new Map(),overviewFindingIds: [],truncated: false,}),@@ -673,6 +686,7 @@ describe("optional activity reads", () => {comments: [comment],},],+ diffRefsByThreadId: new Map(),overviewFindingIds: [],truncated: false,}),@@ -687,6 +701,53 @@ describe("optional activity reads", () => {}),);+ it.effect("marks a thread outdated once the merge request's diff moves past it", () =>+ Effect.gen(function* () {+ let detailReads = 0;+ const thread = (id: string) => ({+ id,+ path: "src/a.ts",+ line: 3,+ side: "right" as const,+ isResolved: false,+ isOutdated: false,+ comments: [],+ });+ const provider = yield* make.pipe(+ Effect.provide(+ Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({+ ...reads,+ getMergeRequestDetail: () =>+ Effect.map(reads.getMergeRequestDetail(), (detail) => ({+ ...detail,+ diffRefs: ++detailReads === 1 ? { ...currentRefs, headSha: "head1" } : currentRefs,+ })),+ listDiscussions: () =>+ Effect.succeed({+ threads: [thread("current"), thread("moved"), thread("unplaced")],+ diffRefsByThreadId: new Map([+ ["current", currentRefs],+ ["moved", { ...currentRefs, headSha: "head1" }],+ ]),+ overviewFindingIds: [],+ truncated: false,+ }),+ }),+ ),+ );++ const checks = provider.getChangeRequestChecks;+ if (!checks) throw new Error("missing getChangeRequestChecks");+ yield* checks(reference);+ const { reviewThreads } = yield* provider.getChangeRequestActivity(reference);+ expect(reviewThreads.map(({ id, isOutdated }) => [id, isOutdated])).toEqual([+ ["current", false],+ ["moved", true],+ ["unplaced", false],+ ]);+ }),+ );+it.effect("keeps comments and commits when optional discussions, reactions and links fail", () =>Effect.gen(function* () {const provider = yield* make.pipe(@@ -750,6 +811,7 @@ describe("optional activity reads", () => {],},],+ diffRefsByThreadId: new Map(),overviewFindingIds: [],truncated: false,}),diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.tsindex db86e10e8d5..ec3f46f0ac2 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts@@ -12,7 +12,7 @@ import type {} from "@t3tools/contracts";import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";-import type { GitLabMergeRequestListState } from "./gitLabMergeRequestJson.ts";+import type { GitLabDiffRefs, GitLabMergeRequestListState } from "./gitLabMergeRequestJson.ts";import {PullRequestProviderError,type PullRequestProviderFailure,@@ -107,6 +107,17 @@ function gitLabProviderFailure(return { reason: "failed" };}+// GitLab keeps a thread on the latest diff while its line survives, so older refs mean the code moved.+const isOutdated = (+ thread: GitLabDiffRefs | undefined,+ current: GitLabDiffRefs | undefined,+): boolean =>+ thread !== undefined &&+ current !== undefined &&+ (thread.baseSha !== current.baseSha ||+ thread.startSha !== current.startSha ||+ thread.headSha !== current.headSha);+export const make = Effect.gen(function* () {const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;@@ -364,6 +375,7 @@ export const make = Effect.gen(function* () {recoverRead(cli.listCommits(input), []),recoverRead(cli.listDiscussions(input), {threads: [],+ diffRefsByThreadId: new Map(),overviewFindingIds: [],truncated: true,}),@@ -373,9 +385,14 @@ export const make = Effect.gen(function* () {editedAtByNoteId: new Map<string, string>(),botLogins: new Set<string>(),}),- // Usually cached by the detail read beside this one; web_url holds the real web origin.+ // Fresh, not the cached detail: refs from before a push would mark every thread outdated.recoverRead(- mergeRequestDetail(input).pipe(Effect.map((mergeRequest) => mergeRequest.url)),+ cli.getMergeRequestDetail({ ...input, downstreamChecks: false }).pipe(+ Effect.map((mergeRequest) => ({+ url: mergeRequest.url,+ diffRefs: mergeRequest.diffRefs,+ })),+ ),null,),],@@ -383,8 +400,8 @@ export const make = Effect.gen(function* () {).pipe(Effect.mapError(fail("getChangeRequestActivity")),Effect.map(- ([notes, commits, discussions, awards, webUrl]): ProviderChangeRequestActivity => {- const noteUrl = (id: string) => (webUrl === null ? null : `${webUrl}#note_${id}`);+ ([notes, commits, discussions, awards, detail]): ProviderChangeRequestActivity => {+ const noteUrl = (id: string) => (detail === null ? null : `${detail.url}#note_${id}`);const findingIds = new Set(discussions.overviewFindingIds);const edited = (id: string) => {const editedAt = awards.editedAtByNoteId.get(id);@@ -409,6 +426,10 @@ export const make = Effect.gen(function* () {commentsTruncated: notes.truncated || discussions.truncated,reviewThreads: discussions.threads.map((thread) => ({...thread,+ isOutdated: isOutdated(+ discussions.diffRefsByThreadId.get(thread.id),+ detail?.diffRefs,+ ),comments: thread.comments.map((comment) => ({...comment,...edited(comment.id),diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.tsindex 1ff3de91626..b231a25b3d3 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts@@ -181,6 +181,21 @@ describe("decodeMergeRequestDetailJson", () => {expect(headSha({ sha: " " })).toBeUndefined();});+ it("reads the diff refs threads are placed against", () => {+ const diffRefs = (entry: Record<string, unknown>) =>+ expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).diffRefs;++ expect(diffRefs({ diff_refs: { base_sha: "b", start_sha: "s", head_sha: "h" } })).toEqual({+ baseSha: "b",+ startSha: "s",+ headSha: "h",+ });+ expect(diffRefs({ diff_refs: null })).toBeUndefined();+ expect(+ diffRefs({ diff_refs: { base_sha: null, start_sha: "s", head_sha: "h" } }),+ ).toBeUndefined();+ });+it("reads either auto-merge field, and says nothing where GitLab named neither", () => {const armed = (entry: Record<string, unknown>) =>expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.tsindex 3ea4b6e63db..f456236b852 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts@@ -47,6 +47,18 @@ const RawTriggerJobSchema = Schema.Struct({downstream_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)),});+const RawDiffRefs = Schema.Struct({+ base_sha: Schema.String,+ head_sha: Schema.String,+ start_sha: Schema.String,+});++const RawMergeRequestDiffRefs = Schema.Struct({+ base_sha: Schema.NullOr(Schema.String),+ head_sha: Schema.NullOr(Schema.String),+ start_sha: Schema.NullOr(Schema.String),+});+const RawMergeRequestSchema = Schema.Struct({iid: Schema.Int,title: Schema.String,@@ -79,6 +91,7 @@ const RawMergeRequestSchema = Schema.Struct({squash: Schema.optional(Schema.NullOr(Schema.Boolean)),/** Only detail reads with include_diverged_commits_count return this expensive count. */diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),+ diff_refs: Schema.optional(Schema.NullOr(RawMergeRequestDiffRefs)),});const RawNoteSchema = Schema.Struct({@@ -114,6 +127,9 @@ const RawDiscussionNoteSchema = Schema.Struct({old_path: Schema.optional(Schema.NullOr(Schema.String)),new_line: Schema.optional(Schema.NullOr(Schema.Int)),old_line: Schema.optional(Schema.NullOr(Schema.Int)),+ base_sha: Schema.optional(Schema.NullOr(Schema.String)),+ start_sha: Schema.optional(Schema.NullOr(Schema.String)),+ head_sha: Schema.optional(Schema.NullOr(Schema.String)),}),),),@@ -125,15 +141,7 @@ const RawDiscussionSchema = Schema.Struct({});const RawDiffRefsSchema = Schema.Struct({- diff_refs: Schema.optional(- Schema.NullOr(- Schema.Struct({- base_sha: Schema.String,- head_sha: Schema.String,- start_sha: Schema.String,- }),- ),- ),+ diff_refs: Schema.optional(Schema.NullOr(RawDiffRefs)),});const RawCommitSchema = Schema.Struct({@@ -212,6 +220,7 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {/** Absent means not counted, not up to date. */readonly divergedCommits?: number;readonly headSha?: string;+ readonly diffRefs?: GitLabDiffRefs;/** On a fork the pipeline often belongs to the source project, not the target. */readonly headPipeline?: { readonly id: number; readonly projectId: number };}@@ -324,6 +333,11 @@ function toListItem(function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {const listItem = toListItem(raw);const headSha = trimmed(raw.sha);+ const refs = raw.diff_refs;+ const diffRefs =+ refs && refs.base_sha !== null && refs.head_sha !== null && refs.start_sha !== null+ ? toDiffRefs({ base_sha: refs.base_sha, head_sha: refs.head_sha, start_sha: refs.start_sha })+ : null;const autoMerge =raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null? undefined@@ -349,6 +363,7 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLab: {}),...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),...(headSha === null ? {} : { headSha }),+ ...(diffRefs === null ? {} : { diffRefs }),...(raw.head_pipeline?.id == null || raw.head_pipeline.project_id == null? {}: { headPipeline: { id: raw.head_pipeline.id, projectId: raw.head_pipeline.project_id } }),@@ -556,11 +571,17 @@ export interface GitLabDiffRefs {export interface GitLabDiscussions {readonly threads: ReadonlyArray<PullRequestReviewThread>;+ /** GitLab moves a thread onto each new diff that still has its line; this is the last one. */+ readonly diffRefsByThreadId: ReadonlyMap<string, GitLabDiffRefs>;/** First notes of unresolved discussions on the MR itself rather than a diff line. */readonly overviewFindingIds: ReadonlyArray<string>;readonly rawCount: number;}+function toDiffRefs(raw: Schema.Schema.Type<typeof RawDiffRefs>): GitLabDiffRefs {+ return { baseSha: raw.base_sha, headSha: raw.head_sha, startSha: raw.start_sha };+}+export function decodeDiscussionsJson(raw: string,): Result.Result<GitLabDiscussions, DecodeFailure> {@@ -569,6 +590,7 @@ export function decodeDiscussionsJson(return Result.fail(decoded.failure);}const threads: PullRequestReviewThread[] = [];+ const diffRefsByThreadId = new Map<string, GitLabDiffRefs>();const overviewFindingIds: string[] = [];for (const entry of decoded.success) {const discussion = decodeDiscussionEntry(entry);@@ -595,6 +617,13 @@ export function decodeDiscussionsJson(continue;}if (path === null) continue;+ if (position.base_sha && position.start_sha && position.head_sha) {+ diffRefsByThreadId.set(discussion.value.id, {+ baseSha: position.base_sha,+ startSha: position.start_sha,+ headSha: position.head_sha,+ });+ }threads.push({id: discussion.value.id,path,@@ -611,7 +640,12 @@ export function decodeDiscussionsJson(})),});}- return Result.succeed({ threads, overviewFindingIds, rawCount: decoded.success.length });+ return Result.succeed({+ threads,+ diffRefsByThreadId,+ overviewFindingIds,+ rawCount: decoded.success.length,+ });}export function decodeDiffRefsJson(@@ -620,9 +654,7 @@ export function decodeDiffRefsJson(const decoded = decodeDiffRefs(raw);if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);const refs = decoded.success.diff_refs;- return Result.succeed(- refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,- );+ return Result.succeed(refs ? toDiffRefs(refs) : null);}export function decodeNotesJson(