Skip to content
TypeScript

fix(pull-requests): shared state + not settling? (#9332)

maria854541a04e07
diff --git a/apps/server/src/orchestration/ThreadSettlementReactor.test.ts b/apps/server/src/orchestration/ThreadSettlementReactor.test.ts
index e0aabe973e6..382d5812c1a 100644
--- a/apps/server/src/orchestration/ThreadSettlementReactor.test.ts
+++ b/apps/server/src/orchestration/ThreadSettlementReactor.test.ts
@@ -25,7 +25,10 @@ import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { GitManager } from "../git/GitManager.ts";
-import { PullRequestService } from "../pullRequest/PullRequestService.ts";
+import {
+ PullRequestService,
+ type PullRequestMergeEvent,
+} from "../pullRequest/PullRequestService.ts";
import { ServerActivation } from "../serverActivation.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
@@ -143,6 +146,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
const snapshotReads = yield* Queue.unbounded<number>();
const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
+ const mergedPullRequests = yield* PubSub.unbounded<PullRequestMergeEvent>();
const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
const branchCalls = yield* Ref.make<
ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
@@ -168,7 +172,6 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
);
-
const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
Effect.gen(function* () {
yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
@@ -217,7 +220,12 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
),
}),
Layer.mock(GitManager)({ branchPullRequest }),
- Layer.mock(PullRequestService)({ summary: pullRequestSummary }),
+ Layer.mock(PullRequestService)({
+ summary: pullRequestSummary,
+ subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
+ Effect.map((subscription) => Stream.fromSubscription(subscription)),
+ ),
+ }),
Layer.mock(OrchestrationEngineService)({
readEvents: () => Stream.empty,
dispatch,
@@ -239,6 +247,12 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
summaryCalls,
summaryRecovery,
updateSettings,
+ publishMerge: PubSub.publish(mergedPullRequests, {
+ projectId: PROJECT_ID,
+ repository: "owner/repository",
+ number: 42,
+ mergedAt: NOW,
+ }),
layer: ThreadSettlementReactor.layer.pipe(Layer.provide(dependencies)),
};
});
@@ -373,6 +387,60 @@ describe("ThreadSettlementReactor", () => {
),
);
+ it.effect("reevaluates immediately after a pull request merge", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse(NOW));
+ const periodicLookupStarted = yield* Deferred.make<void>();
+ const releasePeriodicLookup = yield* Deferred.make<void>();
+ const mergedThreadSettled = yield* Deferred.make<void>();
+ const branchLookupCount = yield* Ref.make(0);
+ const fixture = yield* makeHarness({
+ snapshot: makeSnapshot([
+ makeThread("merged-in-app", {
+ linkedPullRequest: {
+ projectId: PROJECT_ID,
+ repository: "owner/repository",
+ number: 42,
+ url: "https://example.test/owner/repository/pull/42",
+ },
+ }),
+ makeThread("slow-periodic-lookup", { branch: "another-feature" }),
+ ]),
+ branchPullRequest: () =>
+ Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
+ Effect.flatMap((count) =>
+ count === 1
+ ? Effect.succeed({ state: "open" as const, updatedAt: NOW })
+ : Deferred.succeed(periodicLookupStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(releasePeriodicLookup)),
+ Effect.as({ state: "open" as const, updatedAt: NOW }),
+ ),
+ ),
+ ),
+ onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
+ });
+
+ yield* Effect.gen(function* () {
+ const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
+ yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
+ yield* Deferred.await(periodicLookupStarted);
+
+ yield* fixture.publishMerge;
+ yield* Deferred.await(mergedThreadSettled);
+
+ assert.deepStrictEqual(
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
+ [ThreadId.make("merged-in-app")],
+ );
+ yield* Deferred.succeed(releasePeriodicLookup, undefined);
+ yield* reactor.drain;
+ }).pipe(Effect.provide(fixture.layer));
+ }),
+ ),
+ );
+
it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration/ThreadSettlementReactor.ts b/apps/server/src/orchestration/ThreadSettlementReactor.ts
index 4971ae643c0..9dd7cd5e76f 100644
--- a/apps/server/src/orchestration/ThreadSettlementReactor.ts
+++ b/apps/server/src/orchestration/ThreadSettlementReactor.ts
@@ -38,11 +38,22 @@ export const make = Effect.gen(function* () {
const pullRequests = yield* PullRequestService.PullRequestService;
const crypto = yield* Crypto.Crypto;
- const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* () {
+ const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* (
+ mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
+ ) {
const snapshot = yield* snapshots.getShellSnapshot();
const now = DateTime.formatIso(yield* DateTime.now);
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
- const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
+ const candidates = snapshot.threads.filter(
+ (thread) =>
+ isAutoSettlementCandidate(thread, now) &&
+ (mergedPullRequest === null ||
+ (thread.linkedPullRequest != null &&
+ thread.linkedPullRequest.projectId === mergedPullRequest.projectId &&
+ thread.linkedPullRequest.repository.toLowerCase() ===
+ mergedPullRequest.repository.toLowerCase() &&
+ thread.linkedPullRequest.number === mergedPullRequest.number)),
+ );
const lookupKey = (thread: (typeof candidates)[number]) => {
if (thread.linkedPullRequest != null) {
return JSON.stringify([
@@ -66,6 +77,12 @@ export const make = Effect.gen(function* () {
thread: (typeof candidates)[number],
) {
if (thread.linkedPullRequest != null) {
+ if (mergedPullRequest !== null) {
+ return {
+ state: "merged",
+ updatedAt: mergedPullRequest.mergedAt,
+ } satisfies SettlementPullRequest;
+ }
if (!projects.has(thread.linkedPullRequest.projectId)) {
return yield* Effect.die(new Error("linked pull request project not found"));
}
@@ -145,8 +162,8 @@ export const make = Effect.gen(function* () {
);
});
- const worker = yield* makeDrainableWorker(() =>
- sweep().pipe(
+ const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
+ sweep(mergedPullRequest).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause)
@@ -154,13 +171,14 @@ export const make = Effect.gen(function* () {
cause: Cause.pretty(cause),
}),
),
- ),
- );
+ );
+ const worker = yield* makeDrainableWorker(() => runSweep(null));
const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
"ThreadSettlementReactor.start",
)(function* () {
const settingsChanges = yield* settingsService.subscribeChanges;
+ const mergedPullRequests = yield* pullRequests.subscribeMerges;
const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
@@ -183,6 +201,7 @@ export const make = Effect.gen(function* () {
return worker.enqueue(undefined);
}),
);
+ yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
});
return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 0a4d17280ad..0dc7a928c26 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -1,7 +1,10 @@
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import type {
OrchestrationProjectShell,
@@ -1002,6 +1005,41 @@ it.effect("refuses an action the host never claimed it could run", () =>
}),
);
+it.effect("publishes a successful merge for immediate settlement", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const mergedAt = "2026-09-03T02:00:00.000Z";
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ ],
+ providers: [
+ fakeProvider("github", {
+ runAction: () => TestClock.setTime(Date.parse(mergedAt)),
+ }),
+ ],
+ });
+ const merges = yield* service.subscribeMerges;
+ const observedMerge = yield* Stream.runHead(merges).pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ yield* service.runAction({
+ ...reference,
+ repository: " ACME/WEB ",
+ action: "merge",
+ mergeMethod: "merge",
+ });
+
+ assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
+ ...reference,
+ mergedAt,
+ });
+ }),
+ ),
+);
+
it.effect("refuses an action this viewer may not take, and says what access it takes", () =>
Effect.gen(function* () {
let ran: string | null = null;
@@ -3192,6 +3230,32 @@ it.effect("does not ask the host again for a linked summary it already holds", (
}),
);
+it.effect("reuses an observed merged state for strict settlement reads", () =>
+ Effect.gen(function* () {
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ getChangeRequest: () =>
+ Effect.succeed({
+ ...hostedChangeRequest("merged body", 4),
+ state: "merged",
+ updatedAt: "2026-07-03T00:00:00Z",
+ }),
+ getChangeRequestSummary: () => Effect.die("strict merged state must not refresh"),
+ }),
+ ],
+ });
+
+ yield* service.detail(reference);
+
+ const summary = yield* service.summary(reference, { recoverTransientFailure: false });
+ assert.strictEqual(summary.state, "merged");
+ assert.strictEqual(summary.updatedAt, "2026-07-03T00:00:00Z");
+ }),
+);
+
it.effect("does not let a stale detail reopen overwrite a fresher linked summary", () =>
Effect.gen(function* () {
const gate = yield* Deferred.make<void>();
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 509127fc9cf..b27fff3534a 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -1,11 +1,15 @@
import * as Cache from "effect/Cache";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
+import * as DateTime from "effect/DateTime";
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 PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
+import type * as Scope from "effect/Scope";
+import * as Stream from "effect/Stream";
import {
PullRequestOperationError,
PullRequestUnavailableError,
@@ -63,6 +67,10 @@ import {
} from "./PullRequestProvider.ts";
import { PullRequestProviderRegistry } from "./PullRequestProviderRegistry.ts";
+export interface PullRequestMergeEvent extends PullRequestRef {
+ readonly mergedAt: string;
+}
+
/**
* Rows per repository when the client does not ask for a page size, and rows per slice when a
* listing is carried on from a cursor.
@@ -135,6 +143,11 @@ export class PullRequestService extends Context.Service<
input: PullRequestRef,
options?: { readonly recoverTransientFailure?: boolean },
) => Effect.Effect<PullRequestSummary, PullRequestError>;
+ readonly subscribeMerges: Effect.Effect<
+ Stream.Stream<PullRequestMergeEvent>,
+ never,
+ Scope.Scope
+ >;
readonly detail: (input: PullRequestRef) => Effect.Effect<PullRequestDetail, PullRequestError>;
readonly activity: (
input: PullRequestRef,
@@ -517,6 +530,7 @@ export function repositoryIdentityOf(project: OrchestrationProjectShell): string
}
export const make = Effect.gen(function* () {
+ const mergedPullRequests = yield* PubSub.sliding<PullRequestMergeEvent>(64);
const registry = yield* PullRequestProviderRegistry;
const projections = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
@@ -1410,9 +1424,9 @@ export const make = Effect.gen(function* () {
}),
);
- const runAction: PullRequestService["Service"]["runAction"] = (input) =>
+ const runAction = (input: PullRequestActionInput): Effect.Effect<string, PullRequestError> =>
requireProject(input).pipe(
- Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
+ Effect.flatMap((project): Effect.Effect<string, PullRequestError> => {
// The surface hides what a host cannot do, and this refuses it as well: a request that
// reached here anyway must not be handed to a provider that never claimed the action.
if (!project.api.capabilities.actions.includes(input.action)) {
@@ -1454,7 +1468,7 @@ export const make = Effect.gen(function* () {
// have to say yes. The second is asked last, because it costs a request and the checks
// above do not.
return viewerPermissionsOf(project, input, "runAction").pipe(
- Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => {
+ Effect.flatMap((viewer): Effect.Effect<string, PullRequestError> => {
if (!viewer.actions.includes(input.action)) {
return Effect.fail(
new PullRequestOperationError({
@@ -1484,7 +1498,10 @@ export const make = Effect.gen(function* () {
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
- .pipe(Effect.mapError(toPullRequestError("runAction")));
+ .pipe(
+ Effect.mapError(toPullRequestError("runAction")),
+ Effect.as(project.repository),
+ );
}),
);
}),
@@ -2151,9 +2168,13 @@ export const make = Effect.gen(function* () {
const summary: PullRequestService["Service"]["summary"] = (input, options) => {
const key = refCacheKey(input);
const cached = Cache.get(summaryCache, key);
- return options?.recoverTransientFailure === false
- ? cached.pipe(Effect.tap((value) => lastGoodSummary.record(key, value)))
- : lastGoodSummary.serveHeld(key, cached, "reuse");
+ if (options?.recoverTransientFailure !== false) {
+ return lastGoodSummary.serveHeld(key, cached, "reuse");
+ }
+ const held = lastGoodSummary.peek(key);
+ return held?.state === "merged"
+ ? Effect.succeed(held)
+ : cached.pipe(Effect.tap((value) => lastGoodSummary.record(key, value)));
};
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
@@ -2391,17 +2412,35 @@ export const make = Effect.gen(function* () {
}),
),
);
+ const runActionAndInvalidate: PullRequestService["Service"]["runAction"] = Effect.fn(
+ "PullRequestService.runActionAndInvalidate",
+ )(function* (input) {
+ const repository = yield* runAction(input);
+ bumpRefEpoch({ ...input, repository });
+ listingsEpoch = ++epochCounter;
+ if (input.action === "merge") {
+ yield* PubSub.publish(mergedPullRequests, {
+ projectId: input.projectId,
+ repository,
+ number: input.number,
+ mergedAt: DateTime.formatIso(yield* DateTime.now),
+ });
+ }
+ });
return PullRequestService.of({
list,
listStats,
summary,
+ subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
+ Effect.map((subscription) => Stream.fromSubscription(subscription)),
+ ),
detail,
activity,
threadComments,
diff,
diffFileContents,
- runAction: invalidatedByMutation(runAction),
+ runAction: runActionAndInvalidate,
update: invalidatedByMutation(update),
comment: invalidatedByMutation(comment),
updateComment: invalidatedByMutation(updateComment),
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index d15122abccf..1d76b4ae5d6 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -265,7 +265,6 @@ import { environmentCatalog } from "../connection/catalog";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
import { projectEnvironment } from "../state/projects";
-import { linkedPullRequestDetailAtom } from "../state/pullRequests";
import { useEnvironmentQuery } from "../state/query";
import {
environmentServerConfigsAtom,
@@ -325,7 +324,6 @@ import {
} from "./chat/ThreadErrorBanner";
import {
resolveDisplayedThreadPr,
- threadPullRequestRefreshSource,
threadChangeRequestSnapshotsAtom,
useLinkedThreadPullRequest,
} from "./ThreadStatusIndicators";
@@ -1787,6 +1785,8 @@ function ChatViewContent(props: ChatViewProps) {
);
const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, { reportFailure: false });
const sidebarPrRefreshKeyRef = useRef<string | null>(null);
+ const threadPrRelinkKeysRef = useRef(new Map<string, string>());
+ const threadPrRelinkWriteRef = useRef(Promise.resolve());
const activePreviewState = useThreadPreviewState(activeThreadRef);
const activePreviewServerEpoch = activePreviewState.serverEpoch;
const resolvePreviewRuntimeTabId = useMemo(
@@ -3645,9 +3645,50 @@ function ChatViewContent(props: ChatViewProps) {
);
// The thread's own change request, placed against the project it belongs to. Without a
// project there is nothing to resolve it against, so the caller falls back to the browser.
- const linkedThreadPullRequest = isServerThread
+ const persistedLinkedThreadPullRequest = isServerThread
? (activeThreadShell?.linkedPullRequest ?? activeThread?.linkedPullRequest ?? null)
: (activeThread?.linkedPullRequest ?? null);
+ const activeProjectRepository = activeProject?.repositoryIdentity?.displayName ?? null;
+ const persistedLinkedThreadPullRequestStatus = useLinkedThreadPullRequest(
+ activeThreadRef?.environmentId ?? null,
+ persistedLinkedThreadPullRequest,
+ );
+ const replacementLinkedThreadPullRequest = useMemo(() => {
+ const detected = gitStatusQuery.data?.pr;
+ const threadBranch = activeThread?.branch;
+ const projectId = activeProject?.id;
+ if (
+ persistedLinkedThreadPullRequest === null ||
+ (persistedLinkedThreadPullRequestStatus?.pr.state !== "merged" &&
+ persistedLinkedThreadPullRequestStatus?.pr.state !== "closed") ||
+ gitStatusQuery.data?.refName !== threadBranch ||
+ detected?.state !== "open" ||
+ detected.headRef !== threadBranch ||
+ projectId === undefined ||
+ activeProjectRepository === null ||
+ (persistedLinkedThreadPullRequest.projectId === projectId &&
+ persistedLinkedThreadPullRequest.repository.toLowerCase() ===
+ activeProjectRepository.toLowerCase() &&
+ persistedLinkedThreadPullRequest.number === detected.number)
+ ) {
+ return null;
+ }
+ return {
+ projectId,
+ repository: activeProjectRepository,
+ number: detected.number,
+ url: detected.url,
+ };
+ }, [
+ activeProject?.id,
+ activeProjectRepository,
+ activeThread?.branch,
+ gitStatusQuery.data,
+ persistedLinkedThreadPullRequest,
+ persistedLinkedThreadPullRequestStatus?.pr.state,
+ ]);
+ const linkedThreadPullRequest =
+ replacementLinkedThreadPullRequest ?? persistedLinkedThreadPullRequest;
const linkedThreadPullRequestKey = linkedThreadPullRequest
? JSON.stringify([
linkedThreadPullRequest.projectId,
@@ -3655,7 +3696,6 @@ function ChatViewContent(props: ChatViewProps) {
linkedThreadPullRequest.number,
])
: null;
- const activeProjectRepository = activeProject?.repositoryIdentity?.displayName ?? null;
const threadRepository = linkedThreadPullRequest?.repository ?? activeProjectRepository;
const openThreadPullRequest = useCallback(
(number: number) => {
@@ -3679,6 +3719,63 @@ function ChatViewContent(props: ChatViewProps) {
supportsPullRequests,
],
);
+ useEffect(() => {
+ if (!isServerThread || activeThreadKey === null || activeThreadRef === null) {
+ return;
+ }
+ if (replacementLinkedThreadPullRequest === null) {
+ threadPrRelinkKeysRef.current.delete(activeThreadKey);
+ return;
+ }
+ const relinkKey = `${replacementLinkedThreadPullRequest.projectId}:${replacementLinkedThreadPullRequest.repository}#${replacementLinkedThreadPullRequest.number}`;
+ if (threadPrRelinkKeysRef.current.get(activeThreadKey) === relinkKey) return;
+ threadPrRelinkKeysRef.current.set(activeThreadKey, relinkKey);
+ const openSurface = selectActiveRightPanelSurface(
+ useRightPanelStore.getState().byThreadKey,
+ activeThreadRef,
+ );
+ if (
+ openSurface?.kind === "pull-request" &&
+ persistedLinkedThreadPullRequest !== null &&
+ openSurface.projectId === persistedLinkedThreadPullRequest.projectId &&
+ openSurface.repository.toLowerCase() ===
+ persistedLinkedThreadPullRequest.repository.toLowerCase() &&
+ openSurface.number === persistedLinkedThreadPullRequest.number
+ ) {
+ useRightPanelStore
+ .getState()
+ .openPullRequest(activeThreadRef, replacementLinkedThreadPullRequest);
+ }
+
+ threadPrRelinkWriteRef.current = threadPrRelinkWriteRef.current.then(async () => {
+ if (threadPrRelinkKeysRef.current.get(activeThreadKey) !== relinkKey) return;
+ const result = await updateThreadMetadata({
+ environmentId: activeThreadRef.environmentId,
+ input: {
+ threadId: activeThreadRef.threadId,
+ linkedPullRequest: replacementLinkedThreadPullRequest,
+ },
+ });
+ if (threadPrRelinkKeysRef.current.get(activeThreadKey) !== relinkKey) return;
+ if (result._tag !== "Failure") return;
+ threadPrRelinkKeysRef.current.delete(activeThreadKey);
+ if (isAtomCommandInterrupted(result)) return;
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Unable to update the thread pull request",
+ description: chatActionErrorMessage(squashAtomCommandFailure(result)),
+ }),
+ );
+ });
+ }, [
+ activeThreadKey,
+ activeThreadRef,
+ isServerThread,
+ persistedLinkedThreadPullRequest,
+ replacementLinkedThreadPullRequest,
+ updateThreadMetadata,
+ ]);
const openProjectPullRequest = useCallback(
(number: number) => {
if (
@@ -4782,60 +4879,39 @@ function ChatViewContent(props: ChatViewProps) {
resizeObserver.disconnect();
};
}, [composerOverlayElement]);
- const linkedPullRequestStatus = useLinkedThreadPullRequest(
- activeThreadRef?.environmentId ?? null,
- linkedThreadPullRequest,
- );
- const activeThreadPr = resolveDisplayedThreadPr({
- threadBranch: activeThread?.branch ?? null,
- gitStatus: gitStatusQuery.data ?? null,
- snapshot: activeThreadKey ? changeRequestSnapshotByKey.get(activeThreadKey) : undefined,
- retainTerminalOnBranchMismatch: activeThread?.worktreePath === null,
- linkedPullRequest: linkedThreadPullRequest,
- linkedPullRequestStatus,
- });
+ const activeThreadPr =
+ replacementLinkedThreadPullRequest !== null
+ ? (gitStatusQuery.data?.pr ?? null)
+ : resolveDisplayedThreadPr({
+ threadBranch: activeThread?.branch ?? null,
+ gitStatus: gitStatusQuery.data ?? null,
+ snapshot: activeThreadKey ? changeRequestSnapshotByKey.get(activeThreadKey) : undefined,
+ retainTerminalOnBranchMismatch: activeThread?.worktreePath === null,
+ linkedPullRequest: linkedThreadPullRequest,
+ linkedPullRequestStatus: persistedLinkedThreadPullRequestStatus,
+ });
const handlePullRequestTabStatusChange = useCallback(
- (status: PullRequestTabStatus) => {
- const source = threadPullRequestRefreshSource({
- panel: status,
- thread: {
- repository: threadRepository,
- number: linkedThreadPullRequest?.number ?? activeThreadPr?.number ?? null,
- state: activeThreadPr?.state ?? null,
- linked: linkedThreadPullRequest !== null,
- },
- });
- if (source === null) {
+ (status: Pick<PullRequestTabStatus, "repository" | "number" | "state">) => {
+ if (
+ threadRepository?.toLowerCase() !== status.repository.toLowerCase() ||
+ activeThreadPr?.number !== status.number ||
+ activeThreadPr.state === status.state
+ ) {
sidebarPrRefreshKeyRef.current = null;
return;
}
- const refreshKey = `${activeThreadKey}:${source}:${status.repository}#${status.number}:${status.state}`;
+ const refreshKey = `${activeThreadKey}:vcs:${status.repository}#${status.number}:${status.state}`;
if (sidebarPrRefreshKeyRef.current === refreshKey) return;
sidebarPrRefreshKeyRef.current = refreshKey;
-
- if (source === "linked-detail" && activeThreadRef && linkedThreadPullRequest) {
- appAtomRegistry.refresh(
- linkedPullRequestDetailAtom({
- environmentId: activeThreadRef.environmentId,
- input: {
- projectId: linkedThreadPullRequest.projectId,
- repository: linkedThreadPullRequest.repository,
- number: linkedThreadPullRequest.number,
- },
- }),
- );
- return;
- }
- if (source === "vcs" && activeThreadRef && gitCwd !== null) {
- void refreshVcsStatus({
- environmentId: activeThreadRef.environmentId,
- input: { cwd: gitCwd },
- }).then(() => {
- if (sidebarPrRefreshKeyRef.current === refreshKey) {
- sidebarPrRefreshKeyRef.current = null;
- }
- });
- }
+ if (activeThreadRef === null || gitCwd === null) return;
+ void refreshVcsStatus({
+ environmentId: activeThreadRef.environmentId,
+ input: { cwd: gitCwd },
+ }).then(() => {
+ if (sidebarPrRefreshKeyRef.current === refreshKey) {
+ sidebarPrRefreshKeyRef.current = null;
+ }
+ });
},
[
activeThreadKey,
@@ -4843,7 +4919,6 @@ function ChatViewContent(props: ChatViewProps) {
activeThreadPr?.state,
activeThreadRef,
gitCwd,
- linkedThreadPullRequest,
refreshVcsStatus,
threadRepository,
],
@@ -7346,7 +7421,9 @@ function ChatViewContent(props: ChatViewProps) {
: "page"
}
composerDraftTarget={composerDraftTarget}
- onStateChange={handlePullRequestTabStatusChange}
+ {...(linkedThreadPullRequest === null
+ ? { onStateChange: handlePullRequestTabStatusChange }
+ : {})}
/>
) : renderedRightPanelSurface?.kind === "agents" ? (
<AgentsPanel
diff --git a/apps/web/src/components/ThreadStatusIndicators.test.ts b/apps/web/src/components/ThreadStatusIndicators.test.ts
index 078c3e97f5f..31b94db36d4 100644
--- a/apps/web/src/components/ThreadStatusIndicators.test.ts
+++ b/apps/web/src/components/ThreadStatusIndicators.test.ts
@@ -1,4 +1,4 @@
-import { ProjectId, type VcsStatusResult } from "@t3tools/contracts";
+import { ProjectId, type PullRequestSummary, type VcsStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { AtomRegistry } from "effect/unstable/reactivity";
@@ -10,10 +10,10 @@ import {
resolveDisplayedThreadPrProvider,
resolveThreadPr,
settledPrHoverColorClass,
- threadPullRequestRefreshSource,
threadChangeRequestSnapshotsAtom,
type ThreadChangeRequestSnapshot,
} from "./ThreadStatusIndicators";
+import { newestPullRequestSummary } from "../state/pullRequests";
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
return {
@@ -57,58 +57,44 @@ function snapshotFor(
return { branch, pr, sourceControlProvider };
}
-describe("threadPullRequestRefreshSource", () => {
- const panel = { repository: "pingdotgg/t3code", number: 42, state: "merged" as const };
+function pullRequestSummary(
+ state: PullRequestSummary["state"],
+ updatedAt: string,
+): PullRequestSummary {
+ return {
+ provider: "github",
+ projectId: ProjectId.make("project-1"),
+ repository: "pingdotgg/t3code",
+ number: 42,
+ title: "Feature PR",
+ url: "https://github.com/pingdotgg/t3code/pull/42",
+ state,
+ headBranch: "feature/current",
+ baseBranch: "main",
+ updatedAt,
+ };
+}
- it("refreshes the VCS stream when the open panel is newer than an inferred sidebar PR", () => {
- expect(
- threadPullRequestRefreshSource({
- panel,
- thread: { repository: "pingdotgg/t3code", number: 42, state: "open", linked: false },
- }),
- ).toBe("vcs");
- });
+describe("shared pull request state", () => {
+ it("shows a panel-observed merge instead of an older sidebar summary", () => {
+ const open = pullRequestSummary("open", "2026-09-03T01:00:00.000Z");
+ const merged = pullRequestSummary("merged", "2026-09-03T01:01:00.000Z");
- it("refreshes linked detail when the open panel is newer than a linked sidebar PR", () => {
- expect(
- threadPullRequestRefreshSource({
- panel,
- thread: { repository: "pingdotgg/t3code", number: 42, state: "open", linked: true },
- }),
- ).toBe("linked-detail");
+ expect(newestPullRequestSummary(open, merged)).toBe(merged);
});
- it("refreshes when the sidebar has not resolved state yet", () => {
- expect(
- threadPullRequestRefreshSource({
- panel,
- thread: { repository: "pingdotgg/t3code", number: 42, state: null, linked: false },
- }),
- ).toBe("vcs");
- });
+ it("never lets a stale open response regress a merged observation", () => {
+ const merged = pullRequestSummary("merged", "2026-09-03T01:01:00.000Z");
+ const staleOpen = pullRequestSummary("open", "2026-09-03T01:00:00.000Z");
- it("does nothing once sidebar state matches or the panel shows another PR", () => {
- expect(
- threadPullRequestRefreshSource({
- panel,
- thread: { repository: "pingdotgg/t3code", number: 42, state: "merged", linked: false },
- }),
- ).toBeNull();
- expect(
- threadPullRequestRefreshSource({
- panel,
- thread: { repository: "pingdotgg/t3code", number: 41, state: "open", linked: false },
- }),
- ).toBeNull();
+ expect(newestPullRequestSummary(merged, staleOpen)).toBe(merged);
});
- it("matches repository identity without case sensitivity", () => {
- expect(
- threadPullRequestRefreshSource({
- panel: { ...panel, repository: "PingDotGG/T3Code" },
- thread: { repository: "pingdotgg/t3code", number: 42, state: "open", linked: false },
- }),
- ).toBe("vcs");
+ it("accepts a newer open state after a closed pull request is reopened", () => {
+ const closed = pullRequestSummary("closed", "2026-09-03T01:00:00.000Z");
+ const reopened = pullRequestSummary("open", "2026-09-03T01:01:00.000Z");
+
+ expect(newestPullRequestSummary(closed, reopened)).toBe(reopened);
});
});
diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx
index e879c78b971..6bc5424cfed 100644
--- a/apps/web/src/components/ThreadStatusIndicators.tsx
+++ b/apps/web/src/components/ThreadStatusIndicators.tsx
@@ -12,7 +12,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
import { useProject } from "../state/entities";
import { useEnvironmentQuery } from "../state/query";
-import { linkedPullRequestDetailAtom } from "../state/pullRequests";
+import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { vcsEnvironment } from "../state/vcs";
import { useUiStateStore } from "../uiStateStore";
@@ -39,32 +39,6 @@ export interface TerminalStatusIndicator {
export type ThreadPr = VcsStatusResult["pr"];
-export type ThreadPullRequestRefreshSource = "linked-detail" | "vcs";
-
-/** Refresh only when the panel has newer state for this thread's own pull request. */
-export function threadPullRequestRefreshSource(input: {
- readonly panel: {
- readonly repository: string;
- readonly number: number;
- readonly state: NonNullable<ThreadPr>["state"];
- };
- readonly thread: {
- readonly repository: string | null;
- readonly number: number | null;
- readonly state: NonNullable<ThreadPr>["state"] | null;
- readonly linked: boolean;
- };
-}): ThreadPullRequestRefreshSource | null {
- if (
- input.thread.repository?.toLowerCase() !== input.panel.repository.toLowerCase() ||
- input.thread.number !== input.panel.number ||
- input.thread.state === input.panel.state
- ) {
- return null;
- }
- return input.thread.linked ? "linked-detail" : "vcs";
-}
-
export interface LinkedThreadPullRequestStatus {
readonly pr: NonNullable<ThreadPr>;
readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
@@ -74,7 +48,7 @@ export function useLinkedThreadPullRequest(
environmentId: EnvironmentId | null,
linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
): LinkedThreadPullRequestStatus | null {
- const detail = useEnvironmentQuery(
+ const queried = useEnvironmentQuery(
environmentId === null || linkedPullRequest == null
? null
: linkedPullRequestDetailAtom({
@@ -86,6 +60,7 @@ export function useLinkedThreadPullRequest(
},
}),
).data;
+ const detail = useSharedPullRequestSummary(environmentId, linkedPullRequest ?? null, queried);
return useMemo(
() =>
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index b318744e3dd..59aa1333896 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -63,7 +63,7 @@ import { useProjects } from "~/state/entities";
import { useEnvironments } from "~/state/environments";
import { useEnvironmentQuery } from "~/state/query";
import { useLiveRefresh } from "~/hooks/useLiveRefresh";
-import { pullRequestEnvironment } from "~/state/pullRequests";
+import { pullRequestEnvironment, useSharedPullRequestSummary } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { vcsEnvironment } from "~/state/vcs";
import { formatRelativeTimeLabel } from "~/timestampFormat";
@@ -476,14 +476,8 @@ export function PullRequestDetailPanel({
onActed?: () => void;
/** Page-owned detail columns use this to clear the selected pull request. */
onClose?: () => void;
- /** Keeps surrounding thread state in step with refreshed host state. */
- onStateChange?: (status: {
- projectId: string;
- repository: string;
- number: number;
- state: PullRequestState;
- isDraft: boolean;
- }) => void;
+ /** Keeps surrounding inferred thread state in step with refreshed host state. */
+ onStateChange?: (status: { repository: string; number: number; state: PullRequestState }) => void;
/**
* Beside a thread, the checkout affordance disappears: the panel is showing that thread's
* own pull request, so the branch is already under the reader's feet — and checking it out
@@ -606,11 +600,19 @@ export function PullRequestDetailPanel({
reference.repository,
reference.number,
]);
- const coreDetail = resolveDisplayedPullRequestDetail({
+ const resolvedCoreDetail = resolveDisplayedPullRequestDetail({
live: detailQuery.data,
cached: cachedDetail,
reference,
});
+ const sharedSummary = useSharedPullRequestSummary(environmentId, reference, resolvedCoreDetail);
+ const coreDetail = useMemo(
+ () =>
+ resolvedCoreDetail === null || sharedSummary === null || sharedSummary === resolvedCoreDetail
+ ? resolvedCoreDetail
+ : { ...resolvedCoreDetail, ...sharedSummary },
+ [resolvedCoreDetail, sharedSummary],
+ );
const activity = activityQuery.data;
const detail = useMemo(
() =>
@@ -674,16 +676,14 @@ export function PullRequestDetailPanel({
}
activityRevision.current = next;
}, [activityQuery.refresh, coreDetail, pullRequestKey]);
- useEffect(() => {
- if (!detail) return;
+ useLayoutEffect(() => {
+ if (!resolvedCoreDetail) return;
onStateChange?.({
- projectId: detail.projectId,
- repository: detail.repository,
- number: detail.number,
- state: detail.state,
- isDraft: detail.isDraft,
+ repository: resolvedCoreDetail.repository,
+ number: resolvedCoreDetail.number,
+ state: resolvedCoreDetail.state,
});
- }, [detail, onStateChange]);
+ }, [onStateChange, resolvedCoreDetail]);
// Core detail is cheap enough to re-read while this stays open. Activity is heavier, so the
// revision effect above reads it only after this same pull request reports a change. Keyed by
// the pull request rather than by the panel, because this one panel shows a different pull
diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts
index 601b6efa3dc..bde8b4c2d9c 100644
--- a/apps/web/src/state/pullRequests.ts
+++ b/apps/web/src/state/pullRequests.ts
@@ -7,10 +7,12 @@ import type {
EnvironmentId,
PullRequestListInput,
PullRequestListStatsInput,
+ PullRequestRef,
+ PullRequestSummary,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
-import { useCallback, useMemo } from "react";
+import { useCallback, useLayoutEffect, useMemo } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -25,6 +27,50 @@ export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connecti
export const linkedPullRequestDetailAtom =
createLinkedPullRequestSummaryAtomFamily(connectionAtomRuntime);
+const observedPullRequestSummaryAtom = Atom.family((key: string) =>
+ Atom.make<PullRequestSummary | null>(null).pipe(
+ Atom.setIdleTTL(5 * 60_000),
+ Atom.withLabel(`web-pull-requests:observed-summary:${key}`),
+ ),
+);
+
+export function newestPullRequestSummary(
+ current: PullRequestSummary | null,
+ observed: PullRequestSummary | null,
+): PullRequestSummary | null {
+ if (current === null) return observed;
+ if (observed === null) return current;
+ if (current.state === "merged") return current;
+ if (observed.state === "merged") return observed;
+ return Date.parse(observed.updatedAt) >= Date.parse(current.updatedAt) ? observed : current;
+}
+
+export function useSharedPullRequestSummary(
+ environmentId: EnvironmentId | null,
+ reference: PullRequestRef | null,
+ current: PullRequestSummary | null,
+): PullRequestSummary | null {
+ const key =
+ environmentId === null || reference === null
+ ? "none"
+ : JSON.stringify([
+ environmentId,
+ reference.projectId,
+ reference.repository.toLowerCase(),
+ reference.number,
+ ]);
+ const atom = observedPullRequestSummaryAtom(key);
+ const observed = useAtomValue(atom);
+ useLayoutEffect(() => {
+ if (environmentId === null || current === null) return;
+ appAtomRegistry.modify(atom, (previous) => {
+ const next = newestPullRequestSummary(previous, current);
+ return next === previous ? [false, previous] : [true, next];
+ });
+ }, [atom, current, environmentId]);
+ return newestPullRequestSummary(current, observed);
+}
+
export interface EnvironmentQueryTarget<Input> {
readonly environmentId: EnvironmentId;
readonly input: Input;