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

Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
mariaandmaria-rcks authored and GitHub committed 2026-09-03 01:47:41 -04:00
1 parent 48ba76bc26
commit 854541a04e
9 files changed
+440 -166

No files matched your search

+131 -54
View File
@@ -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
@@ -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");
expect(newestPullRequestSummary(open, merged)).toBe(merged);
});
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");
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");
expect(newestPullRequestSummary(merged, staleOpen)).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("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");
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();
});
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");
expect(newestPullRequestSummary(closed, reopened)).toBe(reopened);
});
});
@@ -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(
() =>
@@ -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
+47 -1
View File
@@ -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;