Skip to content
TypeScript

fix(server): refresh cached PR review replies (#18835)

Alex Southwell965a366e5719
diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
index 6589d51d56d..3e4896d8a5c 100644
--- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
@@ -245,7 +245,14 @@ export const make = Effect.gen(function* () {
const lastReads = new Map<string, LastRead>();
const threadTails = new Map<
string,
- Map<string, { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }>
+ {
+ readonly fetchedAt: number;
+ readonly visibleThrough: number;
+ readonly tails: ReadonlyMap<
+ string,
+ { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }
+ >;
+ }
>();
const identityOf = (link: ThreadPullRequestLink) => ({
@@ -294,23 +301,45 @@ export const make = Effect.gen(function* () {
);
const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")(
- function* (key: string, reference: PullRequestRef, activity: PullRequestActivity) {
+ function* (
+ key: string,
+ reference: PullRequestRef,
+ activity: PullRequestActivity,
+ now: number,
+ rereadMs: number,
+ ) {
// Comment cursors cannot account for missing threads. Only finish a truncated read
// when the host confirms that every thread was listed.
if (activity.commentsTruncated && activity.reviewThreadsTruncated !== false) return null;
- let tails = threadTails.get(key);
- if (tails === undefined) {
- tails = new Map();
- threadTails.set(key, tails);
- }
+ const visibleThrough = activity.comments.reduce(
+ (latest, comment) => Math.max(latest, Date.parse(comment.editedAt ?? comment.createdAt)),
+ 0,
+ );
+ const paginated = activity.reviewThreads.filter(
+ (thread) => thread.nextCommentsCursor != null,
+ );
+ const cached = threadTails.get(key);
+ // All tails share one watermark, so newer visible remarks or a changed thread must
+ // refresh the entire group before any remarks can advance it.
+ const reuse =
+ cached !== undefined &&
+ now - cached.fetchedAt < rereadMs &&
+ cached.visibleThrough === visibleThrough &&
+ cached.tails.size === paginated.length &&
+ paginated.every(
+ (thread) => cached.tails.get(thread.id)?.count === (thread.commentCount ?? 0),
+ );
+ const tails = new Map<
+ string,
+ { count: number; comments: ReadonlyArray<PullRequestComment> }
+ >();
const remarks = [...activity.comments];
- for (const thread of activity.reviewThreads) {
+ for (const thread of paginated) {
let cursor = thread.nextCommentsCursor ?? null;
- if (cursor === null) continue;
const count = thread.commentCount ?? 0;
- let tail = tails.get(thread.id);
- if (tail?.count !== count) {
+ let tail = reuse ? cached.tails.get(thread.id) : undefined;
+ if (tail === undefined) {
const comments = new Map<string, PullRequestComment>();
const cursors = new Set<string>();
while (cursor !== null) {
@@ -333,10 +362,15 @@ export const make = Effect.gen(function* () {
}
if (thread.comments.length + comments.size < count) return null;
tail = { count, comments: [...comments.values()] };
- tails.set(thread.id, tail);
}
+ tails.set(thread.id, tail);
remarks.push(...tail.comments);
}
+ threadTails.set(key, {
+ fetchedAt: reuse ? cached.fetchedAt : now,
+ visibleThrough,
+ tails,
+ });
return remarks.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
},
Effect.catch((error) =>
@@ -344,6 +378,15 @@ export const make = Effect.gen(function* () {
Effect.as(null),
),
),
+ (effect, key) =>
+ effect.pipe(
+ Effect.onExit((exit) =>
+ Effect.sync(() => {
+ // A retry must refresh every tail before advancing the shared remark watermark.
+ if (Exit.isFailure(exit) || exit.value === null) threadTails.delete(key);
+ }),
+ ),
+ ),
);
const closed = (target: WatchTarget) =>
@@ -413,6 +456,14 @@ export const make = Effect.gen(function* () {
const last = lastReads.get(group.key);
const plan = planRead(group, last, fingerprint, now);
if (!plan.detail) return;
+ if (
+ last === undefined ||
+ group.targets.some((target) => !last.watches.has(watchKey(target))) ||
+ (fingerprint !== null && last.remarks !== fingerprint.remarks)
+ ) {
+ // A new watch or changed host remarks needs a fresh view of every tail.
+ threadTails.delete(group.key);
+ }
const reference = referenceOf(group);
// The reads are recorded against this fingerprint, so a cached answer older than it must not
// stand in for them. Clients are not told: this only drops this pull request's cached reads.
@@ -465,10 +516,19 @@ export const make = Effect.gen(function* () {
// Never advance the remark watermark past comments an incomplete read could have missed.
const remarks = Option.isSome(activity)
- ? yield* readRemarks(group.key, reference, activity.value)
+ ? yield* readRemarks(
+ group.key,
+ reference,
+ activity.value,
+ now,
+ fingerprint === null ? QUIET_REREAD_MS : FINGERPRINT_REREAD_MS,
+ )
: null;
lastReads.set(group.key, {
- at: plan.activity || last === undefined ? now : last.at,
+ at:
+ plan.activity || last === undefined
+ ? (threadTails.get(group.key)?.fetchedAt ?? now)
+ : last.at,
fingerprint: group.fingerprint,
inFlight:
detail.mergeability === "unknown" ||
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 59ccca86a16..0dd515a1a8c 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -3356,6 +3356,248 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
+ it.effect.each(["deadline", "fingerprint lost", "fingerprint changed", "mixed-age remarks"])(
+ "delivers edited cached review replies: %s",
+ (mode) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const projectId = ProjectId.make(`pr-watch-tail-project-${mode}`);
+ const threadId = ThreadId.make(`runtime-pr-watch-tail-${mode}`);
+ const startedAt = "2026-10-02T12:00:00.000Z";
+ yield* TestClock.setTime(Date.parse(startedAt));
+ yield* seedProject({
+ projectId,
+ title: "Watch edited replies",
+ workspaceRoot: "/workspace/watch-tail",
+ defaultModelSelection: null,
+ createdAt: startedAt,
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`pr-watch-tail-create-${mode}`),
+ threadId,
+ projectId,
+ title: "Watch edited replies",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.pull-request.watch",
+ commandId: CommandId.make(`pr-watch-tail-start-${mode}`),
+ threadId,
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number: 12,
+ watching: true,
+ link: { url: "https://github.com/pingdotgg/t3code/pull/12", source: "agent" },
+ });
+ const reply: PullRequestComment = {
+ id: "reply-11",
+ kind: "review-comment",
+ author: { login: "reviewer", name: null, avatarUrl: null },
+ body: "Original feedback.",
+ createdAt: "2026-10-02T11:00:00.000Z",
+ url: null,
+ path: "src/index.ts",
+ reviewState: null,
+ };
+ let replies = Array.from(
+ { length: mode === "fingerprint changed" ? 2 : 1 },
+ (_, index) => ({
+ ...reply,
+ id: `reply-${index}-11`,
+ }),
+ );
+ const reviewThreads = replies.map((reply, index) => ({
+ id: `review-thread-${index}`,
+ path: "src/index.ts",
+ line: index + 1,
+ side: "right" as const,
+ isResolved: false,
+ isOutdated: false,
+ comments: Array.from({ length: 10 }, (_, index) => ({
+ ...reply,
+ id: `${reply.id}-preview-${index}`,
+ })),
+ commentCount: 11,
+ nextCommentsCursor: "after-10",
+ }));
+ let fingerprint: string | null = mode === "mixed-age remarks" ? null : "before";
+ let failPage = false;
+ let activityReads = 0;
+ const pageReads: Array<{ threadId: string; cursor: string }> = [];
+ const expectedPages = reviewThreads.map((thread) => ({
+ threadId: thread.id,
+ cursor: "after-10",
+ }));
+ const reactor = yield* PullRequestWatchReactor.make.pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ NodeServices.layer,
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getThreadsWithPullRequests: () =>
+ projections
+ .getThreadsWithPullRequests()
+ .pipe(
+ Effect.map((threads) => threads.filter((thread) => thread.id === threadId)),
+ ),
+ }),
+ Layer.mock(PullRequestService.PullRequestService)({
+ watchFingerprint: () =>
+ Effect.succeed(
+ fingerprint === null ? null : { status: "OPEN pending", remarks: fingerprint },
+ ),
+ invalidate: () => Effect.void,
+ detail: () =>
+ Effect.succeed({
+ ...watchedPullRequestDetail({ projectId, number: 12, at: startedAt }),
+ checks: [{ name: "test", status: "pending", description: null, url: null }],
+ }),
+ activity: () =>
+ Effect.sync(() => {
+ activityReads += 1;
+ return {
+ comments: reviewThreads.flatMap((thread) => thread.comments),
+ commentCount: reviewThreads.length * 11,
+ commentsTruncated: true,
+ reviewThreadsTruncated: false,
+ reviewThreads,
+ commits: [],
+ };
+ }),
+ threadComments: (input) =>
+ Effect.suspend(() => {
+ const index = reviewThreads.findIndex((thread) => thread.id === input.threadId);
+ assert.isAtLeast(index, 0);
+ pageReads.push({ threadId: input.threadId, cursor: input.cursor });
+ return failPage && index === 1
+ ? Effect.fail(
+ new PullRequestOperationError({
+ operation: "threadComments",
+ detail: "Page unavailable",
+ }),
+ )
+ : Effect.succeed({ comments: [replies[index]!], nextCursor: null });
+ }),
+ }),
+ ),
+ ),
+ );
+ const messages = orchestrator
+ .getThreadRecords(threadId, ["messages"])
+ .pipe(Effect.map((records) => records.messages));
+ const watch = orchestrator
+ .getThreadShell(threadId)
+ .pipe(Effect.map((thread) => thread?.pullRequests?.[0]?.watch));
+ yield* reactor.sweep;
+ const baseline = yield* watch;
+ replies = replies.map((reply) => ({
+ ...reply,
+ body: "Edited feedback.",
+ editedAt: "2026-10-02T12:00:01.000Z",
+ }));
+
+ if (mode === "mixed-age remarks") {
+ const thread = reviewThreads[0]!;
+ const visibleReply = {
+ ...thread.comments[0]!,
+ body: "Edited visible feedback.",
+ editedAt: "2026-10-02T12:02:00.000Z",
+ };
+ thread.comments[0] = visibleReply;
+ yield* TestClock.adjust("5 minutes");
+ yield* reactor.sweep;
+ const intermediateWatch = yield* watch;
+ const intermediatePageReads = [...pageReads];
+ yield* TestClock.adjust("5 minutes");
+ yield* reactor.sweep;
+ const wakes = yield* messages;
+ assert.isTrue(wakes.every((wake) => wake.notification?.summary === "#12: new comments"));
+ assert.equal((yield* watch)?.remarksThrough, visibleReply.editedAt);
+ assert.deepEqual((yield* watch)?.remarkIds, [visibleReply.id]);
+ assert.deepEqual(pageReads, [...expectedPages, ...expectedPages]);
+ const wakeText = wakes.map((wake) => wake.text).join("\n");
+ for (const reply of [visibleReply, ...replies]) {
+ assert.include(wakeText, reply.body);
+ assert.equal(wakeText.split(reply.body).length - 1, 1);
+ }
+ // A watermark past the deep edit requires a fresh tail, even before its deadline.
+ if (intermediateWatch?.remarksThrough === visibleReply.editedAt) {
+ assert.deepEqual(intermediatePageReads, [...expectedPages, ...expectedPages]);
+ } else {
+ assert.equal(intermediateWatch?.remarksThrough, baseline?.remarksThrough);
+ }
+ yield* reactor.sweep;
+ yield* TestClock.adjust("30 minutes");
+ yield* reactor.sweep;
+ assert.deepEqual(yield* messages, wakes);
+ assert.equal((yield* watch)?.remarksThrough, visibleReply.editedAt);
+ assert.deepEqual(pageReads, [...expectedPages, ...expectedPages, ...expectedPages]);
+ return;
+ }
+
+ if (mode === "fingerprint changed") {
+ yield* TestClock.adjust("1 minute");
+ fingerprint = "after";
+ failPage = true;
+ yield* reactor.sweep;
+ assert.deepEqual(yield* messages, []);
+ assert.deepEqual(yield* watch, baseline);
+ assert.deepEqual(pageReads, [...expectedPages, ...expectedPages]);
+ yield* TestClock.adjust("2 seconds");
+ // Neither deep edit changes the host fingerprint or the thread's comment count.
+ replies = replies.map((reply, index) => ({
+ ...reply,
+ body: `Latest feedback ${index + 1}.`,
+ editedAt: `2026-10-02T12:01:0${index + 1}.000Z`,
+ }));
+ failPage = false;
+ } else {
+ if (mode === "fingerprint lost") fingerprint = null;
+ yield* TestClock.adjust(mode === "deadline" ? "29 minutes" : "5 minutes");
+ yield* reactor.sweep;
+ assert.deepEqual(pageReads, expectedPages);
+ assert.deepEqual(yield* messages, []);
+ // An activity read at five minutes must not move the tail's ten-minute deadline.
+ assert.equal(activityReads, mode === "deadline" ? 1 : 2);
+ yield* TestClock.adjust(mode === "deadline" ? "1 minute" : "5 minutes");
+ }
+ yield* reactor.sweep;
+ const wakes = yield* messages;
+ assert.deepEqual(
+ wakes.map((message) => message.notification?.summary),
+ ["#12: new comments"],
+ );
+ for (const reply of replies) {
+ assert.include(wakes[0]?.text ?? "", reply.body);
+ }
+ assert.notInclude(wakes[0]?.text ?? "", "Original feedback.");
+ assert.deepEqual(
+ pageReads,
+ Array.from(
+ { length: mode === "fingerprint changed" ? 3 : 2 },
+ () => expectedPages,
+ ).flat(),
+ );
+ const latestReply = replies.at(-1)!;
+ assert.equal((yield* watch)?.remarksThrough, latestReply.editedAt);
+ assert.deepEqual((yield* watch)?.remarkIds, [latestReply.id]);
+ yield* reactor.sweep;
+ assert.lengthOf(yield* messages, 1);
+ assert.lengthOf(pageReads, mode === "fingerprint changed" ? 6 : 2);
+ yield* TestClock.adjust("30 minutes");
+ yield* reactor.sweep;
+ assert.lengthOf(yield* messages, 1);
+ assert.lengthOf(pageReads, mode === "fingerprint changed" ? 8 : 3);
+ }),
+ );
+
it.effect.each([
"single page",
"paginated",