The best way to control Claude Code, Codex and more from any computer or phone
perf(server): linked-thread counts update when links change instead of polling every 10s (#35865)
Julius Marminge committed
Nov 12, 2026 at 23:14 UTC
4596872940e3ca4a57e70ec40e7733ca67e02a96
14 files changed
+436
-14
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -142,6 +142,7 @@ export const RPC_REQUIRED_SCOPES = {
142
[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
143
[WS_METHODS.pullRequestsReportState]: AuthOrchestrationReadScope,
144
[WS_METHODS.pullRequestsSubscribeRefreshes]: AuthOrchestrationReadScope,
145
+ [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: AuthOrchestrationReadScope,
146
[WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
147
[WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
148
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -227,6 +227,7 @@ export const make = Effect.gen(function* () {
227
fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
228
pullRequests: true,
229
pullRequestChecks: true,
230
+ linkedThreadRefreshes: true,
231
sideChats: true,
232
vcsBranchStatus: true,
233
inlineMessageContext: true,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -137,6 +137,7 @@ const RPC_AGGREGATES = {
137
[WS_METHODS.pullRequestsInvalidate]: "pull-requests",
138
[WS_METHODS.pullRequestsReportState]: "pull-requests",
139
[WS_METHODS.pullRequestsSubscribeRefreshes]: "pull-requests",
140
+ [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: "pull-requests",
141
[WS_METHODS.pullRequestsReviewerCandidates]: "pull-requests",
142
[WS_METHODS.pullRequestsRequestReviewers]: "pull-requests",
143
[WS_METHODS.pullRequestsLabelCandidates]: "pull-requests",
apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts
+96
-9
@@ -129,7 +129,9 @@ describe("ThreadPullRequestServiceV2 reads", () => {
129
return null;
130
}),
131
}),
132
- Layer.mock(PullRequestService.PullRequestService)({}),
132
+ Layer.mock(PullRequestService.PullRequestService)({
133
+ notifyLinkedThreadsChanged: Effect.void,
134
+ }),
135
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
136
resolve: () =>
137
Effect.succeed({
@@ -179,6 +181,81 @@ describe("ThreadPullRequestServiceV2 reads", () => {
181
}),
182
);
183
184
+ it.effect("refreshes linked-thread readers at most every 10s while activity reorders them", () =>
185
+ Effect.gen(function* () {
186
+ const link = {
187
+ host: "github.com",
188
+ repository: "acme/web",
189
+ number: 7,
190
+ url: "https://github.com/acme/web/pull/7",
191
+ source: "agent",
192
+ };
193
+ const linked = (id: string) =>
194
+ ({
195
+ type: "thread.pull-request-synced",
196
+ threadId: ThreadId.make(id),
197
+ payload: { ...threadShell(id), pullRequests: [link] },
198
+ }) as unknown as OrchestrationV2DomainEvent;
199
+ const activity = (id: string, second: number) =>
200
+ ({
201
+ type: "message.updated",
202
+ threadId: ThreadId.make(id),
203
+ occurredAt: DateTime.makeUnsafe(`2026-09-20T00:00:${String(second).padStart(2, "0")}Z`),
204
+ }) as unknown as OrchestrationV2DomainEvent;
205
+ const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
206
+ const notified = yield* Queue.unbounded<void>();
207
+ const dependencies = Layer.mergeAll(
208
+ Layer.mock(Orchestrator.OrchestratorV2)({
209
+ streamDomainEvents: Stream.fromQueue(domainEvents),
210
+ getPullRequestSnapshot: () =>
211
+ Effect.succeed({
212
+ schemaVersion: 2,
213
+ snapshotSequence: 1,
214
+ threads: [],
215
+ archivedThreads: [],
216
+ }),
217
+ }),
218
+ Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Effect.succeed([]) }),
219
+ Layer.mock(GitManager.GitManager)({}),
220
+ Layer.mock(PullRequestService.PullRequestService)({
221
+ notifyLinkedThreadsChanged: Queue.offer(notified, undefined).pipe(Effect.asVoid),
222
+ }),
223
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
224
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
225
+ shouldRunOpportunisticWork: Effect.succeed(false),
226
+ }),
227
+ Layer.succeed(ServerActivation.ServerActivation, undefined),
228
+ Layer.succeed(
229
+ SecureRandom.SecureRandom,
230
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
231
+ ),
232
+ FileSystem.layerNoop({}),
233
+ Path.layer,
234
+ );
235
+ yield* Effect.gen(function* () {
236
+ const service = yield* ThreadPullRequestService.make;
237
+ yield* service.start();
238
+
239
+ yield* Queue.offerAll(domainEvents, [linked("a"), linked("b"), activity("a", 1)]);
240
+ yield* Queue.takeN(notified, 3);
241
+ // Two turns on threads linked to one pull request swap its top thread on every event.
242
+ yield* Queue.offerAll(
243
+ domainEvents,
244
+ Array.from({ length: 20 }, (_, index) => activity(index % 2 ? "a" : "b", index + 2)),
245
+ );
246
+ // A link change still refreshes at once, and marks the burst as processed.
247
+ yield* Queue.offer(domainEvents, linked("c"));
248
+ yield* Queue.take(notified);
249
+ expect(yield* Queue.size(notified)).toBe(0);
250
+
251
+ yield* TestClock.adjust("10 seconds");
252
+ yield* Queue.take(notified);
253
+ yield* TestClock.adjust("10 seconds");
254
+ expect(yield* Queue.size(notified)).toBe(0);
255
+ }).pipe(Effect.provide(dependencies));
256
+ }),
257
+ );
258
+
259
it.effect("looks up a finished turn's branch once for all its turn-end events", () =>
260
Effect.gen(function* () {
261
const thread = { ...threadShell("turn-end-thread"), branch: "t3/turn-end" };
@@ -198,7 +275,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
275
// A turn end commits its checkpoints and the run's end together. The queued
276
// non-refresh request ahead of them must still become a refresh when they join it.
277
const turnEnd = [
201
- { type: "thread.metadata-updated", threadId: thread.id },
278
+ { type: "thread.metadata-updated", threadId: thread.id, payload: thread },
279
{ type: "checkpoint.captured", threadId: thread.id },
280
{ type: "checkpoint.captured", threadId: thread.id },
281
{ type: "run.updated", threadId: thread.id, payload: { status: "completed" } },
@@ -208,8 +285,8 @@ describe("ThreadPullRequestServiceV2 reads", () => {
285
// Arrives during the thread's own lookup, which may already have read the old host state.
286
const duringLookup = [
287
{ type: "checkpoint.captured", threadId: thread.id },
211
- { type: "thread.metadata-updated", threadId: thread.id },
212
- ] as Array<OrchestrationV2DomainEvent>;
288
+ { type: "thread.metadata-updated", threadId: thread.id, payload: thread },
289
+ ] as unknown as Array<OrchestrationV2DomainEvent>;
290
const activation = yield* Deferred.make<void>();
291
const sweepStarted = yield* Deferred.make<void>();
292
const turnEndQueued = yield* Deferred.make<void>();
@@ -263,7 +340,9 @@ describe("ThreadPullRequestServiceV2 reads", () => {
340
return null;
341
}),
342
}),
266
- Layer.mock(PullRequestService.PullRequestService)({}),
343
+ Layer.mock(PullRequestService.PullRequestService)({
344
+ notifyLinkedThreadsChanged: Effect.void,
345
+ }),
346
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
347
resolve: () =>
348
Effect.succeed({
@@ -383,7 +462,9 @@ describe("ThreadPullRequestServiceV2 reads", () => {
462
return null;
463
}),
464
}),
386
- Layer.mock(PullRequestService.PullRequestService)({}),
465
+ Layer.mock(PullRequestService.PullRequestService)({
466
+ notifyLinkedThreadsChanged: Effect.void,
467
+ }),
468
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
469
resolve: () =>
470
Effect.succeed({
@@ -492,7 +573,9 @@ describe("ThreadPullRequestServiceV2 reads", () => {
573
return null;
574
}),
575
}),
495
- Layer.mock(PullRequestService.PullRequestService)({}),
576
+ Layer.mock(PullRequestService.PullRequestService)({
577
+ notifyLinkedThreadsChanged: Effect.void,
578
+ }),
579
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
580
resolve: () =>
581
Effect.succeed({
@@ -888,7 +971,9 @@ describe("ThreadPullRequestServiceV2 reads", () => {
971
};
972
}),
973
}),
891
- Layer.mock(PullRequestService.PullRequestService)({}),
974
+ Layer.mock(PullRequestService.PullRequestService)({
975
+ notifyLinkedThreadsChanged: Effect.void,
976
+ }),
977
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
978
resolve: () =>
979
Effect.succeed({
@@ -1010,7 +1095,9 @@ describe("ThreadPullRequestServiceV2 reads", () => {
1095
branchPullRequest: (_input, options) =>
1096
Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
1097
}),
1013
- Layer.mock(PullRequestService.PullRequestService)({}),
1098
+ Layer.mock(PullRequestService.PullRequestService)({
1099
+ notifyLinkedThreadsChanged: Effect.void,
1100
+ }),
1101
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1102
resolve: () =>
1103
Effect.succeed({
apps/server/src/orchestration-v2/ThreadPullRequestService.ts
+29
-1
@@ -16,6 +16,7 @@ import * as Effect from "effect/Effect";
16
import * as FileSystem from "effect/FileSystem";
17
import * as Option from "effect/Option";
18
import * as Path from "effect/Path";
19
+import * as Queue from "effect/Queue";
20
import * as Schedule from "effect/Schedule";
21
import type * as Scope from "effect/Scope";
22
import * as Stream from "effect/Stream";
@@ -25,6 +26,7 @@ import * as GitManager from "../git/GitManager.ts";
26
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
27
import * as ProjectStore from "./ProjectStore.ts";
28
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
29
+import { makeLinkedThreadsChangeDetector } from "../pullRequest/linkedThreads.ts";
30
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
31
import { forkParked } from "../serverActivation.ts";
32
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
@@ -407,7 +409,26 @@ export const make = Effect.gen(function* () {
409
return worker.enqueue(request);
410
});
411
410
- const processEvent = (event: OrchestrationV2DomainEvent) => {
412
+ const linkedThreadsChange = makeLinkedThreadsChangeDetector();
413
+ // A running linked thread can reorder its answers on every event, so reorders refresh readers at
414
+ // most once per 10s, the cadence clients used to poll at.
415
+ const linkedThreadReorders = yield* Queue.dropping<void>(1);
416
+
417
+ const notifyLinkedThreads = (event: OrchestrationV2DomainEvent) => {
418
+ switch (linkedThreadsChange(event)) {
419
+ case "changed":
420
+ return pullRequests.notifyLinkedThreadsChanged;
421
+ case "reordered":
422
+ return Queue.offer(linkedThreadReorders, undefined).pipe(Effect.asVoid);
423
+ case null:
424
+ return Effect.void;
425
+ }
426
+ };
427
+
428
+ const processEvent = (event: OrchestrationV2DomainEvent) =>
429
+ Effect.andThen(notifyLinkedThreads(event), refreshForEvent(event));
430
+
431
+ const refreshForEvent = (event: OrchestrationV2DomainEvent) => {
432
switch (event.type) {
433
case "thread.created":
434
case "thread.unarchived":
@@ -434,6 +455,13 @@ export const make = Effect.gen(function* () {
455
"ThreadPullRequestServiceV2.start",
456
)(function* () {
457
yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
458
+ yield* forkParked(
459
+ Queue.take(linkedThreadReorders).pipe(
460
+ Effect.andThen(pullRequests.notifyLinkedThreadsChanged),
461
+ Effect.andThen(Effect.sleep("10 seconds")),
462
+ Effect.forever,
463
+ ),
464
+ );
465
yield* forkParked(
466
Effect.gen(function* () {
467
yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
apps/server/src/pullRequest/PullRequestService.ts
+13
@@ -224,6 +224,9 @@ export class PullRequestService extends Context.Service<
224
input: PullRequestReportStateInput,
225
) => Effect.Effect<void, PullRequestError>;
226
readonly subscribeRefreshes: Stream.Stream<number>;
227
+ readonly subscribeLinkedThreadRefreshes: Stream.Stream<number>;
228
+ /** Wakes linked-thread readers only; other pull request reads don't depend on thread links. */
229
+ readonly notifyLinkedThreadsChanged: Effect.Effect<void>;
230
readonly refreshAfterTurn: (
231
projectId: ProjectId,
232
options?: { readonly pushed?: boolean },
@@ -738,6 +741,7 @@ export const make = Effect.gen(function* () {
741
const mergedPullRequests = yield* PubSub.sliding<PullRequestMergeEvent>(64);
742
const stateChanges = yield* PubSub.sliding<ThreadPullRequestKey>(64);
743
const pullRequestRefreshes = yield* SubscriptionRef.make(0);
744
+ const linkedThreadRefreshes = yield* SubscriptionRef.make(0);
745
const registry = yield* PullRequestProviderRegistry.PullRequestProviderRegistry;
746
const requirementOf: UnavailableRequirementOf = (kind) =>
747
registry.get(kind)?.unavailableRequirement;
@@ -3687,6 +3691,11 @@ export const make = Effect.gen(function* () {
3691
yield* SubscriptionRef.set(pullRequestRefreshes, epoch);
3692
});
3693
3694
+ const notifyLinkedThreadsChanged = SubscriptionRef.update(
3695
+ linkedThreadRefreshes,
3696
+ (revision) => revision + 1,
3697
+ );
3698
+
3699
const invalidatedByMutation =
3700
<I extends PullRequestRef>(
3701
method: (input: I) => Effect.Effect<void, PullRequestError>,
@@ -3886,6 +3895,10 @@ export const make = Effect.gen(function* () {
3895
subscribeRefreshes: SubscriptionRef.changes(pullRequestRefreshes).pipe(
3896
Stream.filter((revision) => revision > 0),
3897
),
3898
+ subscribeLinkedThreadRefreshes: SubscriptionRef.changes(linkedThreadRefreshes).pipe(
3899
+ Stream.filter((revision) => revision > 0),
3900
+ ),
3901
+ notifyLinkedThreadsChanged,
3902
refreshAfterTurn,
3903
detail: credentialCached(detail),
3904
checks: credentialCached((input) => Cache.get(checksCache, refCacheKey(input))),
apps/server/src/pullRequest/linkedThreads.test.ts
+138
-1
@@ -1,10 +1,18 @@
1
+import {
2
+ ProjectId,
3
+ ThreadId,
4
+ type OrchestrationV2AppThread,
5
+ type OrchestrationV2DomainEvent,
6
+ type ThreadPullRequestLink,
7
+} from "@t3tools/contracts";
8
import { assert, expect, it } from "@effect/vitest";
9
+import * as DateTime from "effect/DateTime";
10
import * as Effect from "effect/Effect";
11
import * as Schema from "effect/Schema";
12
import * as SqlClient from "effect/sql/SqlClient";
13
14
import * as SqlitePersistence from "../persistence/Sqlite.ts";
7
-import { listLinkedPullRequestThreads } from "./linkedThreads.ts";
15
+import { listLinkedPullRequestThreads, makeLinkedThreadsChangeDetector } from "./linkedThreads.ts";
16
17
const encodePayload = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
18
@@ -209,3 +217,132 @@ it.effect(
217
);
218
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
219
);
220
+
221
+it("signals linked-thread changes only when a linked answer could change", () => {
222
+ const now = DateTime.makeUnsafe("2026-11-12T00:00:00.000Z");
223
+ const threadId = ThreadId.make("thread-a");
224
+ const link: ThreadPullRequestLink = {
225
+ host: "github.com",
226
+ repository: "acme/web",
227
+ number: 7,
228
+ url: "https://github.com/acme/web/pull/7",
229
+ source: "agent",
230
+ linkedAt: "2026-11-12T00:00:00.000Z",
231
+ snapshot: null,
232
+ stack: null,
233
+ };
234
+ const base = {
235
+ id: threadId,
236
+ projectId: ProjectId.make("project-a"),
237
+ title: "Thread A",
238
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
239
+ archivedAt: null,
240
+ settledOverride: null,
241
+ settledAt: null,
242
+ deletedAt: null,
243
+ updatedAt: now,
244
+ } as unknown as OrchestrationV2AppThread;
245
+ const event = (
246
+ type: OrchestrationV2DomainEvent["type"],
247
+ payload: Partial<OrchestrationV2AppThread>,
248
+ ) => ({ type, threadId, payload: { ...base, ...payload } }) as OrchestrationV2DomainEvent;
249
+ const changed = makeLinkedThreadsChangeDetector();
250
+
251
+ expect(
252
+ [
253
+ event("thread.metadata-updated", { title: "Unlinked rename" }),
254
+ event("thread.pull-request-synced", { pullRequests: [link] }),
255
+ event("thread.pull-request-synced", {
256
+ pullRequests: [{ ...link, watch: { since: "2026-11-12T00:00:00.000Z" } as never }],
257
+ }),
258
+ event("thread.visited", { pullRequests: [link] }),
259
+ event("thread.pinned", { pullRequests: [link], settledAt: now }),
260
+ { type: "thread.pull-request-link-updated", threadId, payload: link } as never,
261
+ event("thread.metadata-updated", { pullRequests: [link], title: "Renamed" }),
262
+ event("thread.archived", { pullRequests: [link], title: "Renamed", archivedAt: now }),
263
+ event("thread.pull-request-synced", {
264
+ pullRequests: [{ ...link, source: "stack-dismissed" }],
265
+ title: "Renamed",
266
+ archivedAt: now,
267
+ }),
268
+ event("thread.deleted", { pullRequests: [], deletedAt: now }),
269
+ ].map(changed),
270
+ ).toEqual([
271
+ "changed",
272
+ "changed",
273
+ null,
274
+ null,
275
+ "changed",
276
+ null,
277
+ "changed",
278
+ "changed",
279
+ "changed",
280
+ null,
281
+ ]);
282
+
283
+ const afterRestart = makeLinkedThreadsChangeDetector();
284
+ expect(afterRestart(event("thread.created", { title: "New" }))).toBe(null);
285
+ expect(
286
+ makeLinkedThreadsChangeDetector()(
287
+ event("thread.deleted", { pullRequests: [], deletedAt: now }),
288
+ ),
289
+ ).toBe("changed");
290
+});
291
+
292
+it("signals when activity reorders the threads linked to a pull request", () => {
293
+ const at = (second: number) => DateTime.makeUnsafe(`2026-11-12T00:00:0${second}.000Z`);
294
+ const link = {
295
+ host: "github.com",
296
+ repository: "acme/web",
297
+ number: 7,
298
+ url: "https://github.com/acme/web/pull/7",
299
+ source: "agent",
300
+ };
301
+ const thread = (id: string, second: number, pullRequests: ReadonlyArray<unknown> = [link]) =>
302
+ ({
303
+ type: "thread.pull-request-synced",
304
+ threadId: ThreadId.make(id),
305
+ payload: {
306
+ id: ThreadId.make(id),
307
+ projectId: ProjectId.make("project-a"),
308
+ title: id,
309
+ lineage: { rootThreadId: ThreadId.make(id) },
310
+ pullRequests,
311
+ archivedAt: null,
312
+ settledOverride: null,
313
+ settledAt: null,
314
+ deletedAt: null,
315
+ updatedAt: at(second),
316
+ },
317
+ }) as unknown as OrchestrationV2DomainEvent;
318
+ const activity = (id: string, second: number) =>
319
+ ({
320
+ type: "message.updated",
321
+ threadId: ThreadId.make(id),
322
+ occurredAt: at(second),
323
+ }) as unknown as OrchestrationV2DomainEvent;
324
+ const changed = makeLinkedThreadsChangeDetector();
325
+ changed(thread("a", 1));
326
+ changed(thread("b", 2));
327
+
328
+ expect(
329
+ [
330
+ { ...thread("a", 3), type: "thread.pinned" } as OrchestrationV2DomainEvent,
331
+ activity("a", 4),
332
+ activity("b", 5),
333
+ activity("b", 5),
334
+ // Seen since startup without links, so its activity can't reorder an answer.
335
+ thread("unlinked", 5, []),
336
+ activity("unlinked", 6),
337
+ // Not seen since startup, so it may be linked from before the restart.
338
+ activity("persisted", 6),
339
+ ].map(changed),
340
+ ).toEqual(["reordered", "reordered", "reordered", null, "changed", null, "reordered"]);
341
+
342
+ // Other threads linked to the pull request may have had no event since the restart.
343
+ const afterRestart = makeLinkedThreadsChangeDetector();
344
+ afterRestart(thread("a", 2));
345
+ expect(
346
+ afterRestart({ ...thread("a", 6), type: "thread.pinned" } as OrchestrationV2DomainEvent),
347
+ ).toBe("reordered");
348
+});
apps/server/src/pullRequest/linkedThreads.ts
+70
@@ -1,12 +1,18 @@
1
import {
2
normalizeThreadPullRequestKey,
3
+ threadPullRequestKeyOf,
4
threadPullRequestKeysEqual,
5
+ visibleThreadPullRequests,
6
} from "../sourceControl/threadPullRequests.ts";
7
import {
8
PullRequestLinkedThreadsResult,
9
PullRequestOperationError,
10
+ type OrchestrationV2AppThread,
11
+ type OrchestrationV2DomainEvent,
12
+ type ThreadId,
13
type ThreadPullRequestKey,
14
} from "@t3tools/contracts";
15
+import * as DateTime from "effect/DateTime";
16
import * as Effect from "effect/Effect";
17
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
18
import * as Schema from "effect/Schema";
@@ -66,3 +72,67 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre
72
}),
73
),
74
);
75
+
76
+// Mirrors the rows and filters of `listLinkedPullRequestThreads`.
77
+function linkedKeys(thread: OrchestrationV2AppThread): ReadonlyArray<string> {
78
+ if (thread.deletedAt !== null || thread.lineage.sideChat === true) return [];
79
+ return visibleThreadPullRequests(thread.pullRequests ?? [])
80
+ .map(threadPullRequestKeyOf)
81
+ .toSorted();
82
+}
83
+
84
+function linkedThreadsView(
85
+ thread: OrchestrationV2AppThread,
86
+ keys: ReadonlyArray<string>,
87
+): string | null {
88
+ if (keys.length === 0) return null;
89
+ const settled = thread.settledAt !== null || thread.settledOverride === "settled";
90
+ return JSON.stringify([
91
+ keys,
92
+ thread.title,
93
+ thread.projectId,
94
+ thread.archivedAt !== null,
95
+ settled,
96
+ ]);
97
+}
98
+
99
+/**
100
+ * Tells how a domain event changed `pullRequests.linkedThreads` answers, so readers can refresh on
101
+ * change instead of polling. `reordered` means activity on a linked thread, or on one whose links
102
+ * are unknown since a restart, which can reorder answers. A thread's first full event after a
103
+ * restart counts as a change, since its earlier links are unknown.
104
+ */
105
+export function makeLinkedThreadsChangeDetector() {
106
+ const views = new Map<ThreadId, string | null>();
107
+ // Last activity of each thread with visible links.
108
+ const activeAt = new Map<ThreadId, number>();
109
+ const active = (threadId: ThreadId, at: DateTime.Utc): boolean => {
110
+ const previous = activeAt.get(threadId);
111
+ if (previous === undefined) return false;
112
+ const millis = DateTime.toEpochMillis(at);
113
+ if (millis <= previous) return false;
114
+ activeAt.set(threadId, millis);
115
+ return true;
116
+ };
117
+ return (event: OrchestrationV2DomainEvent): "changed" | "reordered" | null => {
118
+ // The projection stamps every non-thread event as the thread's activity. A thread not seen
119
+ // since startup may be linked already, since history is not replayed.
120
+ if (!event.type.startsWith("thread.")) {
121
+ if (!views.has(event.threadId)) return "reordered";
122
+ return active(event.threadId, event.occurredAt) ? "reordered" : null;
123
+ }
124
+ if (!("lineage" in event.payload)) return null;
125
+ const thread = event.payload;
126
+ const view = linkedThreadsView(thread, linkedKeys(thread));
127
+ const known = views.has(event.threadId) || event.type === "thread.created";
128
+ const previous = views.get(event.threadId) ?? null;
129
+ if (event.type === "thread.deleted") views.delete(event.threadId);
130
+ else views.set(event.threadId, view);
131
+ if (view === null) activeAt.delete(event.threadId);
132
+ if (!known || view !== previous) {
133
+ if (view !== null) activeAt.set(event.threadId, DateTime.toEpochMillis(thread.updatedAt));
134
+ return "changed";
135
+ }
136
+ return active(event.threadId, thread.updatedAt) ? "reordered" : null;
137
+ };
138
+}
apps/server/src/ws.ts
+2
@@ -2807,6 +2807,8 @@ export const layerWsRpc = (
2807
),
2808
),
2809
[WS_METHODS.pullRequestsSubscribeRefreshes]: () => pullRequests.subscribeRefreshes,
2810
+ [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: () =>
2811
+ pullRequests.subscribeLinkedThreadRefreshes,
2812
[WS_METHODS.pullRequestsReviewerCandidates]: (input) =>
2813
withPullRequestViewer(input, pullRequests.reviewerCandidates(input)),
2814
[WS_METHODS.pullRequestsRequestReviewers]: (input) =>
packages/client-runtime/src/rpc/client.ts
+1
@@ -68,6 +68,7 @@ export type EnvironmentSubscriptionRpcTag =
68
| typeof WS_METHODS.subscribeDeviceState
69
| typeof WS_METHODS.subscribeResourceTelemetry
70
| typeof WS_METHODS.pullRequestsSubscribeRefreshes
71
+ | typeof WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes
72
| typeof WS_METHODS.subscribeVcsStatus
73
| typeof WS_METHODS.subscribeVcsBranch
74
| typeof WS_METHODS.subscribeWorktreeSetup
packages/client-runtime/src/state/pullRequests.test.ts
+48
-1
@@ -1789,6 +1789,49 @@ it.effect("shares one refresh stream between independently created pull request
1789
}),
1790
);
1791
1792
+it.effect.each([
1793
+ { linkedThreadRefreshes: undefined, polledReads: 1, signalledReads: 0 },
1794
+ { linkedThreadRefreshes: true, polledReads: 0, signalledReads: 1 },
1795
+])(
1796
+ "polls linked threads only on servers without linked-thread refreshes ($linkedThreadRefreshes)",
1797
+ ({ linkedThreadRefreshes, polledReads, signalledReads }) =>
1798
+ Effect.gen(function* () {
1799
+ let reads = 0;
1800
+ const linkedThreadSignal = yield* SubscriptionRef.make(0);
1801
+ const client = {
1802
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1803
+ [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: () =>
1804
+ SubscriptionRef.changes(linkedThreadSignal).pipe(Stream.filter((value) => value > 0)),
1805
+ [WS_METHODS.pullRequestsLinkedThreads]: () =>
1806
+ Effect.sync(() => {
1807
+ reads++;
1808
+ return { threads: [] };
1809
+ }),
1810
+ } as unknown as WsRpcProtocolClient;
1811
+ vi.useFakeTimers();
1812
+ yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers()));
1813
+ const { atoms, registry } = yield* makeTestRuntime(client);
1814
+ registry.set(initialConfigs(TARGET.environmentId), {
1815
+ environment: { capabilities: { linkedThreadRefreshes } },
1816
+ });
1817
+ const linked = atoms.linkedThreads({
1818
+ environmentId: TARGET.environmentId,
1819
+ input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1820
+ });
1821
+ const unmount = registry.mount(linked);
1822
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1823
+ yield* AtomRegistry.getResult(registry, linked);
1824
+ expect(reads).toBe(1);
1825
+
1826
+ yield* Effect.promise(() => vi.advanceTimersByTimeAsync(10_000));
1827
+ expect(reads).toBe(1 + polledReads);
1828
+
1829
+ yield* SubscriptionRef.set(linkedThreadSignal, 1);
1830
+ yield* Effect.promise(() => vi.advanceTimersByTimeAsync(0));
1831
+ expect(reads).toBe(1 + polledReads + signalledReads);
1832
+ }),
1833
+);
1834
+
1835
it.effect("shares close, reopen, and merge with an untouched client's mounted PR readers", () =>
1836
Effect.gen(function* () {
1837
const revision = yield* SubscriptionRef.make(0);
@@ -2107,8 +2150,12 @@ it.effect("updates cached labels after successful edits without rereading the ho
2150
);
2151
2152
vi.mock("./session.ts", () => ({
2110
- createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
2153
+ createEnvironmentSessionAtoms: () => ({
2154
+ sessionStateAtom: grantedSessions,
2155
+ initialConfigValueAtom: initialConfigs,
2156
+ }),
2157
}));
2158
+const initialConfigs = Atom.family((_id: EnvironmentId) => Atom.make<unknown>(null));
2159
const grantedSessions = Atom.family((_id: EnvironmentId) =>
2160
Atom.make<AsyncResult.AsyncResult<AuthSessionState>>(
2161
AsyncResult.success({
packages/client-runtime/src/state/pullRequests.ts
+21
-2
@@ -49,6 +49,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts";
49
import { isStalePullRequestReply } from "../pullRequestReply.ts";
50
import { parsePullRequestQuery } from "../pullRequestQuery.ts";
51
import { reuseUnchanged } from "./serverConfigProjection.ts";
52
+import { createEnvironmentSessionAtoms } from "./session.ts";
53
54
export {
55
type PullRequestDiffLoadError,
@@ -433,6 +434,25 @@ export function createPullRequestEnvironmentAtoms<R, E>(
434
onAnswer: PullRequestAnswerHandlers = {},
435
) {
436
const refreshes = createPullRequestRefreshAtomFamily(runtime);
437
+ const sessions = createEnvironmentSessionAtoms(runtime);
438
+ const linkedThreadSignals = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
439
+ label: "environment-data:pull-requests:linked-thread-refreshes",
440
+ tag: WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes,
441
+ });
442
+ // Servers without `linkedThreadRefreshes` never signal link changes, so poll them instead.
443
+ const linkedThreadsRefreshes = Atom.family((environmentId: EnvironmentId) =>
444
+ Atom.make((get): unknown => {
445
+ const signal = get(refreshes({ environmentId, input: {} }));
446
+ const config = get(sessions.initialConfigValueAtom(environmentId));
447
+ if (config?.environment.capabilities.linkedThreadRefreshes === true) {
448
+ return [signal, get(linkedThreadSignals({ environmentId, input: {} }))];
449
+ }
450
+ // @effect-diagnostics-next-line globalTimers:off - Mirrors `Atom.withRefresh`, outside an Effect runtime.
451
+ const handle = setTimeout(() => get.refreshSelf(), 10_000);
452
+ get.addFinalizer(() => clearTimeout(handle));
453
+ return {};
454
+ }),
455
+ );
456
const commandScheduler = createAtomCommandScheduler();
457
const routedRequest = createPullRequestRouter();
458
const serialPerEnvironment = {
@@ -709,8 +729,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
729
persistence: persistQuery(PullRequestLinkedThreadsResult),
730
tag: WS_METHODS.pullRequestsLinkedThreads,
731
staleTimeMs: 0,
712
- refreshIntervalMs: 10_000,
713
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
732
+ refreshTrigger: ({ environmentId }) => linkedThreadsRefreshes(environmentId),
733
}),
734
// For callers that open a thread from the answer: a persisted one reads as final before
735
// the connection is known, and a kept one can predate the thread.
packages/contracts/src/environment.ts
+2
@@ -201,6 +201,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
201
*/
202
shellThreadFamilies: Schema.optionalKey(Schema.Boolean),
203
shellOlderSettled: Schema.optionalKey(Schema.Boolean),
204
+ /** Publishes a pull request refresh when linked-thread answers change; older servers need polling. */
205
+ linkedThreadRefreshes: Schema.optionalKey(Schema.Boolean),
206
});
207
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
208
packages/contracts/src/rpc.ts
+13
@@ -595,6 +595,7 @@ export const WS_METHODS = {
595
pullRequestsInvalidate: "pullRequests.invalidate",
596
pullRequestsReportState: "pullRequests.reportState",
597
pullRequestsSubscribeRefreshes: "pullRequests.subscribeRefreshes",
598
+ pullRequestsSubscribeLinkedThreadRefreshes: "pullRequests.subscribeLinkedThreadRefreshes",
599
pullRequestsReviewerCandidates: "pullRequests.reviewerCandidates",
600
pullRequestsRequestReviewers: "pullRequests.requestReviewers",
601
pullRequestsLabelCandidates: "pullRequests.labelCandidates",
@@ -1238,6 +1239,17 @@ const WsPullRequestsSubscribeRefreshesRpc = Rpc.make(WS_METHODS.pullRequestsSubs
1239
stream: true,
1240
});
1241
1242
+// Separate from the refreshes above so linked-thread changes don't refetch forge-backed reads.
1243
+const WsPullRequestsSubscribeLinkedThreadRefreshesRpc = Rpc.make(
1244
+ WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes,
1245
+ {
1246
+ payload: Schema.Struct({}),
1247
+ success: NonNegativeInt,
1248
+ error: EnvironmentAuthorizationError,
1249
+ stream: true,
1250
+ },
1251
+);
1252
+
1253
// Fetch reviewer candidates only when the menu opens to avoid unused host requests.
1254
const WsPullRequestsReviewerCandidatesRpc = Rpc.make(WS_METHODS.pullRequestsReviewerCandidates, {
1255
payload: PullRequestReviewerCandidatesInput,
@@ -2193,6 +2205,7 @@ export const WsRpcGroup = RpcGroup.make(
2205
WsPullRequestsInvalidateRpc,
2206
WsPullRequestsReportStateRpc,
2207
WsPullRequestsSubscribeRefreshesRpc,
2208
+ WsPullRequestsSubscribeLinkedThreadRefreshesRpc,
2209
WsPullRequestsReviewerCandidatesRpc,
2210
WsPullRequestsRequestReviewersRpc,
2211
WsPullRequestsLabelCandidatesRpc,