fix(server): link thread PRs without an open client (#10101)

Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5.1 authored and GitHub committed 2026-09-06 04:06:15 -07:00
1 parent 5fa35d2116
commit 223ff4490f
50 files changed
+2308 -1485

No files matched your search

@@ -47,11 +47,7 @@ import {
sanitizeNewRefName,
shouldIncludeBranchPickerItem,
} from "./BranchToolbar.logic";
import {
ChangeRequestStatusIcon,
prStatusIndicator,
resolveThreadPr,
} from "./ThreadStatusIndicators";
import { ChangeRequestStatusIcon, prStatusIndicator } from "./ThreadStatusIndicators";
import { Button } from "./ui/button";
import { Switch } from "./ui/switch";
import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
@@ -617,13 +613,14 @@ export function BranchToolbarBranchSelector({
});
// PR pill shown next to the branch selector when the active branch has one.
const branchPr = resolveThreadPr({
threadBranch: resolveBranchToolbarPrBranch({
activeThreadBranch,
resolvedActiveBranch,
}),
gitStatus: branchStatusQuery.data ?? null,
const branchPrBranch = resolveBranchToolbarPrBranch({
activeThreadBranch,
resolvedActiveBranch,
});
const branchPr =
branchPrBranch !== null && branchStatusQuery.data?.refName === branchPrBranch
? (branchStatusQuery.data.pr ?? null)
: null;
const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider);
// Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
// state-description tooltip.
@@ -60,6 +60,7 @@ import {
shouldDockDraftHeroForSubmission,
shouldReleaseTimelineAnchorForToolActivity,
shouldOpenProactivePullRequest,
shouldRetargetThreadPullRequestPanel,
shouldOpenProactiveTurnDiff,
shouldRenderPreviewMiniPlayer,
shouldShowBranchMismatchBanner,
@@ -249,6 +250,40 @@ describe("proactive panels", () => {
expect(shouldOpenProactivePullRequest("project:repo:42", null)).toBe(false);
});
it("follows a changed server PR link without replacing an unrelated open panel", () => {
const previous = {
projectId: ProjectId.make("project-1"),
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
};
const current = {
...previous,
number: 43,
url: "https://github.com/pingdotgg/t3code/pull/43",
};
const surface = {
id: "pull-request:previous",
kind: "pull-request",
projectId: previous.projectId,
repository: "PingDotGG/T3Code",
number: previous.number,
} satisfies RightPanelSurface;
expect(shouldRetargetThreadPullRequestPanel(previous, current, surface)).toBe(true);
expect(shouldRetargetThreadPullRequestPanel(previous, previous, surface)).toBe(false);
expect(shouldRetargetThreadPullRequestPanel(previous, null, surface)).toBe(false);
expect(
shouldRetargetThreadPullRequestPanel(previous, current, { ...surface, number: 99 }),
).toBe(false);
expect(
shouldRetargetThreadPullRequestPanel(previous, current, {
...surface,
projectId: "another-project",
}),
).toBe(false);
});
it("opens the diff only when the observed running turn settles", () => {
const turnId = TurnId.make("turn-1");
expect(
+19
View File
@@ -15,6 +15,7 @@ import {
type ScopedProjectRef,
type ScopedThreadRef,
type ThreadId,
type ThreadLinkedPullRequest,
type TurnId,
} from "@t3tools/contracts";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
@@ -132,6 +133,24 @@ export function observeProactivePanelUserChoice(
};
}
/** Follow a changed server link only when the panel still shows the previous linked PR. */
export function shouldRetargetThreadPullRequestPanel(
previous: ThreadLinkedPullRequest | null,
current: ThreadLinkedPullRequest | null,
surface: RightPanelSurface | null,
): boolean {
if (previous === null || current === null || surface?.kind !== "pull-request") return false;
const previousRepository = previous.repository.toLowerCase();
return (
(previous.projectId !== current.projectId ||
previousRepository !== current.repository.toLowerCase() ||
previous.number !== current.number) &&
surface.projectId === previous.projectId &&
surface.repository.toLowerCase() === previousRepository &&
surface.number === previous.number
);
}
export function shouldOpenProactiveTurnDiff(input: {
previousRunningTurnId: TurnId | null | undefined;
runningTurnId: TurnId | null;
+34 -194
View File
@@ -24,6 +24,7 @@ import {
type ResolvedKeybindingsConfig,
type ScopedThreadRef,
type ThreadId,
type ThreadLinkedPullRequest,
type TurnId,
type KeybindingCommand,
OrchestrationThreadActivity,
@@ -188,7 +189,7 @@ import { isThreadOwnPullRequest } from "./pullRequest/pullRequestDetail.logic";
import { PullRequestDetailPanel } from "./pullRequest/PullRequestDetailPanel";
import { PullRequestDetailGhost } from "./pullRequest/PullRequestGhosts";
import { PullRequestsUnavailableState } from "./pullRequest/PullRequestsUnavailableState";
import { RightPanelTabs, type PullRequestTabStatus } from "./RightPanelTabs";
import { RightPanelTabs } from "./RightPanelTabs";
import { AgentsPanel } from "./AgentsPanel";
import {
deriveAgentPanelModel,
@@ -337,11 +338,6 @@ import {
shouldShowThreadErrorBanner,
ThreadErrorBanner,
} from "./chat/ThreadErrorBanner";
import {
resolveDisplayedThreadPr,
threadChangeRequestSnapshotsAtom,
useLinkedThreadPullRequest,
} from "./ThreadStatusIndicators";
import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ComposerSurface } from "./chat/ComposerSurface";
import {
@@ -380,6 +376,7 @@ import {
shouldShowBranchMismatchBanner,
shouldShowPlanFollowUpPrompt,
shouldOpenProactivePullRequest,
shouldRetargetThreadPullRequestPanel,
shouldOpenProactiveTurnDiff,
shouldRenderPreviewMiniPlayer,
getStartedThreadModelChangeBlockReason,
@@ -1845,7 +1842,6 @@ export default function ChatView(props: ChatViewProps) {
);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom);
const [timelineAnchor, setTimelineAnchor] = useState<{
readonly threadKey: string | null;
readonly messageId: MessageId | null;
@@ -1864,10 +1860,6 @@ export default function ChatView(props: ChatViewProps) {
const activeRightPanelSurface = useRightPanelStore((state) =>
selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef),
);
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(
@@ -3970,52 +3962,11 @@ export default function ChatView(props: ChatViewProps) {
},
[activeProject, activeThreadRef],
);
// 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 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,
]);
// The shell carries server PR updates even while thread detail is still loading.
const activeThreadMetadata = activeThreadShell ?? activeThread;
const linkedThreadPullRequest =
replacementLinkedThreadPullRequest ?? persistedLinkedThreadPullRequest;
activeThreadMetadata?.linkedPullRequest ?? activeThreadMetadata?.branchPullRequest ?? null;
const activeProjectRepository = activeProject?.repositoryIdentity?.displayName ?? null;
const linkedThreadPullRequestKey = linkedThreadPullRequest
? JSON.stringify([
linkedThreadPullRequest.projectId,
@@ -4023,68 +3974,10 @@ export default function ChatView(props: ChatViewProps) {
linkedThreadPullRequest.number,
])
: null;
const threadRepository = linkedThreadPullRequest?.repository ?? activeProjectRepository;
const openThreadPullRequest = useCallback(
(number: number) => {
if (!supportsPullRequests || !activeThreadRef) {
return;
}
const projectId = linkedThreadPullRequest?.projectId ?? activeProject?.id;
const repository = linkedThreadPullRequest?.repository ?? activeProjectRepository;
if (projectId === undefined || repository === null) return;
useRightPanelStore.getState().openPullRequest(activeThreadRef, {
projectId,
repository,
number,
});
},
[
activeProject,
activeProjectRepository,
activeThreadRef,
linkedThreadPullRequest,
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);
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,
replacementLinkedThreadPullRequest,
updateThreadMetadata,
]);
const observedThreadPullRequestRef = useRef<{
readonly threadKey: string;
readonly reference: ThreadLinkedPullRequest | null;
} | null>(null);
const openProjectPullRequest = useCallback(
(number: number) => {
if (
@@ -4110,6 +4003,7 @@ export default function ChatView(props: ChatViewProps) {
useEffect(() => {
if (!isServerThread || activeThreadKey === null || activeThreadRef === null) {
proactivePanelObservationRef.current = null;
observedThreadPullRequestRef.current = null;
return;
}
const panels = useRightPanelStore.getState();
@@ -4125,20 +4019,24 @@ export default function ChatView(props: ChatViewProps) {
userActionRevision,
} = observation;
const openSurface = selectActiveRightPanelSurface(panels.byThreadKey, activeThreadRef);
const previousPullRequest = observedThreadPullRequestRef.current;
observedThreadPullRequestRef.current = {
threadKey: activeThreadKey,
reference: linkedThreadPullRequest,
};
const followSelectedPullRequest =
replacementLinkedThreadPullRequest !== null &&
openSurface?.kind === "pull-request" &&
persistedLinkedThreadPullRequest !== null &&
openSurface.projectId === persistedLinkedThreadPullRequest.projectId &&
openSurface.repository.toLowerCase() ===
persistedLinkedThreadPullRequest.repository.toLowerCase() &&
openSurface.number === persistedLinkedThreadPullRequest.number;
previousPullRequest?.threadKey === activeThreadKey &&
shouldRetargetThreadPullRequestPanel(
previousPullRequest.reference,
linkedThreadPullRequest,
openSurface,
);
// Following the selected linked PR does not open an unrelated panel, so it
// remains available with proactive panels off. It still respects a later choice.
if (followSelectedPullRequest && replacementLinkedThreadPullRequest !== null) {
if (followSelectedPullRequest && linkedThreadPullRequest !== null) {
panels.openProactive(
activeThreadRef,
pullRequestSurface(replacementLinkedThreadPullRequest),
pullRequestSurface(linkedThreadPullRequest),
userActionRevision,
);
}
@@ -4207,9 +4105,7 @@ export default function ChatView(props: ChatViewProps) {
linkedThreadPullRequest,
linkedThreadPullRequestKey,
onDiffPanelOpen,
persistedLinkedThreadPullRequest,
pullRequestsCapabilityKnown,
replacementLinkedThreadPullRequest,
settings.proactivePanelsEnabled,
shouldUseRightPanelSheet,
supportsPullRequests,
@@ -5223,50 +5119,6 @@ export default function ChatView(props: ChatViewProps) {
resizeObserver.disconnect();
};
}, [composerOverlayElement, publishComposerOverlayHeight]);
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: 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}:vcs:${status.repository}#${status.number}:${status.state}`;
if (sidebarPrRefreshKeyRef.current === refreshKey) return;
sidebarPrRefreshKeyRef.current = refreshKey;
if (activeThreadRef === null || gitCwd === null) return;
void refreshVcsStatus({
environmentId: activeThreadRef.environmentId,
input: { cwd: gitCwd },
}).then(() => {
if (sidebarPrRefreshKeyRef.current === refreshKey) {
sidebarPrRefreshKeyRef.current = null;
}
});
},
[
activeThreadKey,
activeThreadPr?.number,
activeThreadPr?.state,
activeThreadRef,
gitCwd,
refreshVcsStatus,
threadRepository,
],
);
const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef);
const activeThreadReferenceCopyTarget = useMemo(
() =>
@@ -5276,15 +5128,8 @@ export default function ChatView(props: ChatViewProps) {
threadId: activeThreadId,
openPanelPullRequestUrl,
linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,
detectedPullRequestUrl: activeThreadPr?.url ?? null,
}),
[
activeThreadId,
activeThreadPr?.url,
isServerThread,
linkedThreadPullRequest?.url,
openPanelPullRequestUrl,
],
[activeThreadId, isServerThread, linkedThreadPullRequest?.url, openPanelPullRequestUrl],
);
const copyActiveThreadReference = useCallback(() => {
const target = activeThreadReferenceCopyTarget;
@@ -5310,14 +5155,12 @@ export default function ChatView(props: ChatViewProps) {
},
);
}, [activeThreadReferenceCopyTarget]);
// The right panel offers the thread's own change request, so it can only offer it once the
// branch has one; until then the picker says so rather than opening an empty panel.
const addPullRequestSurface = useCallback(() => {
if (activeThreadPr === null) return;
openThreadPullRequest(activeThreadPr.number);
}, [activeThreadPr, openThreadPullRequest]);
const pullRequestSurfaceAvailable =
supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
if (!supportsPullRequests || activeThreadRef === null || linkedThreadPullRequest === null)
return;
useRightPanelStore.getState().openPullRequest(activeThreadRef, linkedThreadPullRequest);
}, [activeThreadRef, linkedThreadPullRequest, supportsPullRequests]);
const pullRequestSurfaceAvailable = supportsPullRequests && linkedThreadPullRequest !== null;
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true;
@@ -7849,9 +7692,9 @@ export default function ChatView(props: ChatViewProps) {
context={
isThreadOwnPullRequest(
{
projectId: linkedThreadPullRequest?.projectId ?? activeProject?.id ?? null,
repository: threadRepository,
number: activeThreadPr?.number ?? null,
projectId: linkedThreadPullRequest?.projectId ?? null,
repository: linkedThreadPullRequest?.repository ?? null,
number: linkedThreadPullRequest?.number ?? null,
},
{
projectId: renderedRightPanelSurface.projectId,
@@ -7863,9 +7706,6 @@ export default function ChatView(props: ChatViewProps) {
: "page"
}
composerDraftTarget={composerDraftTarget}
{...(linkedThreadPullRequest === null
? { onStateChange: handlePullRequestTabStatusChange }
: {})}
/>
) : renderedRightPanelSurface?.kind === "agents" ? (
<AgentsPanel
+4 -39
View File
@@ -1,10 +1,6 @@
"use client";
import {
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
canCreateProjectInEnvironment,
getCloneDestinationBrowsePath,
@@ -81,13 +77,11 @@ import { filesystemEnvironment } from "../state/filesystem";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { sourceControlEnvironment } from "../state/sourceControl";
import { vcsEnvironment } from "../state/vcs";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProject, useProjects, useThreadShells } from "../state/entities";
import { useProjects, useThreadShells } from "../state/entities";
import { useThreadSearch } from "../state/queries";
import * as ThreadPr from "./ThreadStatusIndicators";
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
import {
appendBrowsePathSegment,
@@ -605,35 +599,6 @@ function OpenCommandPaletteDialog(props: {
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
useHandleNewThread();
const projects = useProjects();
const changeRequestSnapshotByKey = useAtomValue(ThreadPr.threadChangeRequestSnapshotsAtom);
const activeThreadProject = useProject(
activeThread === null
? null
: scopeProjectRef(activeThread.environmentId, activeThread.projectId),
);
const activeThreadCwd = activeThread?.worktreePath ?? activeThreadProject?.workspaceRoot ?? null;
const activeThreadGitStatus = useEnvironmentQuery(
activeThread != null &&
activeThread.linkedPullRequest == null &&
activeThread.branch !== null &&
activeThreadCwd !== null
? vcsEnvironment.status({
environmentId: activeThread.environmentId,
input: { cwd: activeThreadCwd },
})
: null,
).data;
const detectedPullRequestUrl =
activeThread == null || activeThread.linkedPullRequest != null
? null
: (ThreadPr.resolveDisplayedThreadPr({
threadBranch: activeThread.branch,
gitStatus: activeThreadGitStatus ?? null,
snapshot: changeRequestSnapshotByKey.get(
scopedThreadKey(scopeThreadRef(activeThread.environmentId, activeThread.id)),
),
retainTerminalOnBranchMismatch: activeThread.worktreePath === null,
})?.url ?? null);
const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(
activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null,
);
@@ -643,8 +608,8 @@ function OpenCommandPaletteDialog(props: {
: resolveThreadReferenceCopyTarget({
threadId: activeThread.id,
openPanelPullRequestUrl,
linkedPullRequestUrl: activeThread.linkedPullRequest?.url ?? null,
detectedPullRequestUrl,
linkedPullRequestUrl:
activeThread.linkedPullRequest?.url ?? activeThread.branchPullRequest?.url ?? null,
});
const copyActiveThreadReference = useCallback(async () => {
const target = activeThreadReferenceCopyTarget;
+5 -50
View File
@@ -16,7 +16,6 @@ import {
ChangeRequestStatusIcon,
prStatusIndicator,
PrStatusTooltipContent,
resolveThreadPr,
terminalStatusFromRunningIds,
ThreadStatusLabel,
ThreadWorktreeIndicator,
@@ -83,7 +82,6 @@ import { isTerminalFocused } from "../lib/terminalFocus";
import { isMacPlatform } from "../lib/utils";
import {
readThreadShell,
useProject,
useProjects,
useThreadShells,
useThreadShellsForProjectRefs,
@@ -116,9 +114,7 @@ import { useDesktopUpdateState } from "../state/desktopUpdate";
import { useThreadActions } from "../hooks/useThreadActions";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { threadEnvironment, useEnvironmentThread } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import {
buildThreadRouteParams,
@@ -191,7 +187,6 @@ import {
orderItemsByPreferredIds,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
useRetainedValue,
useSidebarRowSubscriptionLease,
useThreadJumpHintVisibility,
ThreadStatusPill,
@@ -314,7 +309,6 @@ function buildThreadJumpLabelMap(input: {
interface SidebarThreadRowProps {
thread: SidebarThreadSummary;
projectCwd: string | null;
orderedProjectThreadKeys: readonly string[];
isActive: boolean;
openPullRequestsInRightPanel: boolean;
@@ -416,25 +410,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
const threadEnvironmentLabel = isRemoteThread
? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote"))
: null;
// For grouped projects, the thread may belong to a different environment
// than the representative project. Look up the thread's own project cwd
// so git status (and thus PR detection) queries the correct path.
const threadProject = useProject(
useMemo(
() => scopeProjectRef(thread.environmentId, thread.projectId),
[thread.environmentId, thread.projectId],
),
);
const threadProjectCwd = threadProject?.workspaceRoot ?? null;
const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd;
const gitStatus = useEnvironmentQuery(
leaseLiveStatus && thread.linkedPullRequest == null && thread.branch != null && gitCwd !== null
? vcsEnvironment.status({
environmentId: thread.environmentId,
input: { cwd: gitCwd },
})
: null,
);
const isHighlighted = isActive || isSelected;
const handleOpenDiscoveredPort = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
@@ -470,28 +445,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
},
});
const linkedPullRequestStatus = useLinkedThreadPullRequest(
leaseLiveStatus ? thread.environmentId : null,
leaseLiveStatus ? thread.linkedPullRequest : null,
);
const visibleGitStatus = useRetainedValue(
JSON.stringify([thread.environmentId, gitCwd]),
gitStatus.data,
);
const visibleLinkedPullRequestStatus = useRetainedValue(
thread.linkedPullRequest === null
? null
: JSON.stringify([thread.environmentId, thread.linkedPullRequest]),
linkedPullRequestStatus,
);
const pr =
thread.linkedPullRequest == null
? resolveThreadPr({ threadBranch: thread.branch, gitStatus: visibleGitStatus })
: (visibleLinkedPullRequestStatus?.pr ?? null);
const prStatus = prStatusIndicator(
pr,
visibleLinkedPullRequestStatus?.sourceControlProvider ??
visibleGitStatus?.sourceControlProvider,
thread.environmentId,
thread.linkedPullRequest ?? thread.branchPullRequest,
leaseLiveStatus,
);
const pr = linkedPullRequestStatus?.pr ?? null;
const prStatus = prStatusIndicator(pr, linkedPullRequestStatus?.sourceControlProvider);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
@@ -940,7 +899,6 @@ interface SidebarProjectThreadListProps {
showEmptyThreadState: boolean;
shouldShowThreadPanel: boolean;
isThreadListExpanded: boolean;
projectCwd: string;
activeRouteThreadKey: string | null;
openPullRequestsInRightPanel: boolean;
threadJumpLabelByKey: ReadonlyMap<string, string>;
@@ -996,7 +954,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
projectCwd,
activeRouteThreadKey,
openPullRequestsInRightPanel,
threadJumpLabelByKey,
@@ -1048,7 +1005,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
<SidebarThreadRow
key={threadKey}
thread={thread}
projectCwd={projectCwd}
orderedProjectThreadKeys={orderedProjectThreadKeys}
isActive={activeRouteThreadKey === threadKey}
openPullRequestsInRightPanel={openPullRequestsInRightPanel}
@@ -2444,7 +2400,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
showEmptyThreadState={showEmptyThreadState}
shouldShowThreadPanel={shouldShowThreadPanel}
isThreadListExpanded={isThreadListExpanded}
projectCwd={project.workspaceRoot}
activeRouteThreadKey={activeRouteThreadKey}
openPullRequestsInRightPanel={openPullRequestsInRightPanel}
threadJumpLabelByKey={threadJumpLabelByKey}
+5 -58
View File
@@ -167,15 +167,9 @@ import {
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
import {
ThreadWorktreeIndicator,
nextThreadChangeRequestSnapshot,
prStatusIndicator,
resolveDisplayedThreadPr,
resolveDisplayedThreadPrProvider,
setThreadChangeRequestSnapshot,
settledPrHoverColorClass,
terminalStatusFromRunningIds,
threadChangeRequestSnapshotsAtom,
type ThreadChangeRequestSnapshot,
type TerminalStatusIndicator,
useLinkedThreadPullRequest,
} from "./ThreadStatusIndicators";
@@ -795,16 +789,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
onUnsnooze: (threadRef: ScopedThreadRef) => void;
onUnpin: (threadRef: ScopedThreadRef) => void;
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
changeRequestSnapshot: ThreadChangeRequestSnapshot | null;
onChangeRequestSnapshot: (
threadKey: string,
snapshot: ThreadChangeRequestSnapshot | null,
) => void;
}) {
const {
isRenaming,
changeRequestSnapshot,
onChangeRequestSnapshot,
onCancelRename,
onCommitRename,
onContextMenu,
@@ -856,8 +843,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
const gitCwd = thread.worktreePath ?? props.projectCwd;
const linkedPullRequestStatus = useLinkedThreadPullRequest(
leaseLiveStatus ? thread.environmentId : null,
leaseLiveStatus ? thread.linkedPullRequest : null,
thread.environmentId,
thread.linkedPullRequest ?? thread.branchPullRequest,
leaseLiveStatus,
);
const gitStatus = useEnvironmentQuery(
leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
@@ -871,15 +859,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
JSON.stringify([thread.environmentId, gitCwd]),
gitStatus.data,
);
const retainTerminalOnBranchMismatch = thread.worktreePath === null;
const pr = resolveDisplayedThreadPr({
threadBranch: thread.branch,
gitStatus: visibleGitStatus,
snapshot: changeRequestSnapshot,
retainTerminalOnBranchMismatch,
linkedPullRequest: thread.linkedPullRequest,
linkedPullRequestStatus,
});
const pr = linkedPullRequestStatus?.pr ?? null;
// Same semantics as the legacy sidebar (never-visited counts as read):
// switching sidebars must not light up every historical thread as unread.
@@ -972,37 +952,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
activeThreadBranch: thread.branch,
currentGitBranch: visibleGitStatus?.refName ?? null,
});
const prProvider = resolveDisplayedThreadPrProvider({
threadBranch: thread.branch,
gitStatus: visibleGitStatus,
snapshot: changeRequestSnapshot,
retainTerminalOnBranchMismatch,
linkedPullRequest: thread.linkedPullRequest,
linkedPullRequestStatus,
});
const prStatus = prStatusIndicator(pr, prProvider);
const prStatus = prStatusIndicator(pr, linkedPullRequestStatus?.sourceControlProvider);
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state, pr.isDraft) : undefined;
useEffect(() => {
const nextSnapshot = nextThreadChangeRequestSnapshot({
threadBranch: thread.branch,
gitStatus: visibleGitStatus,
snapshot: changeRequestSnapshot,
retainTerminalOnBranchMismatch,
linkedPullRequest: thread.linkedPullRequest,
linkedPullRequestStatus,
});
if (nextSnapshot === undefined) return;
onChangeRequestSnapshot(threadKey, nextSnapshot);
}, [
changeRequestSnapshot,
visibleGitStatus,
linkedPullRequestStatus,
onChangeRequestSnapshot,
retainTerminalOnBranchMismatch,
thread.branch,
thread.linkedPullRequest,
threadKey,
]);
const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
@@ -2104,8 +2055,6 @@ export default function Sidebar() {
// fresh clock whenever it recomputes.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom);
// Project scope: one menu above the list. Scoping filters the list without
// making the header width depend on the number or length of project names.
// The selection lives in the persisted UI store next to the other sidebar
@@ -4092,8 +4041,6 @@ export default function Sidebar() {
onUnsnooze={attemptUnsnooze}
onUnpin={attemptUnpin}
onAcknowledgeWoke={acknowledgeWoke}
changeRequestSnapshot={changeRequestSnapshotByKey.get(threadKey) ?? null}
onChangeRequestSnapshot={setThreadChangeRequestSnapshot}
/>
);
};
@@ -1,7 +1,5 @@
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";
import {
GitMergeIcon,
GitPullRequestClosedIcon,
@@ -11,15 +9,8 @@ import {
import {
ChangeRequestStatusIcon,
nextThreadChangeRequestSnapshot,
prStatusIndicator,
resolveDisplayedThreadPr,
resolveDisplayedThreadPrProvider,
resolveThreadPr,
settledPrHoverColorClass,
threadChangeRequestSnapshotsEqual,
threadChangeRequestSnapshotsAtom,
type ThreadChangeRequestSnapshot,
} from "./ThreadStatusIndicators";
import { newestPullRequestSummary } from "../state/pullRequests";
@@ -57,25 +48,6 @@ function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
};
}
function mergedFeaturePr(): NonNullable<VcsStatusResult["pr"]> {
return {
number: 42,
title: "Feature PR",
url: "https://github.com/pingdotgg/t3code/pull/42",
baseRef: "main",
headRef: "feature/current",
state: "merged",
};
}
function snapshotFor(
branch: string,
pr: NonNullable<VcsStatusResult["pr"]>,
sourceControlProvider?: VcsStatusResult["sourceControlProvider"],
): ThreadChangeRequestSnapshot {
return { branch, pr, sourceControlProvider };
}
function pullRequestSummary(
state: PullRequestSummary["state"],
updatedAt: string,
@@ -117,503 +89,6 @@ describe("shared pull request state", () => {
});
});
describe("resolveThreadPr", () => {
it("keeps local-checkout PR indicators scoped to the stored thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "feature/other",
gitStatus: status(),
}),
).toBeNull();
});
it("hides PR indicators when a dedicated worktree has switched away from the thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "stack/base",
gitStatus: status(),
}),
).toBeNull();
});
it("hides PR indicators when thread branch metadata is missing", () => {
expect(
resolveThreadPr({
threadBranch: null,
gitStatus: status(),
}),
).toBeNull();
});
it("shows the PR when the live checkout matches the stored thread branch", () => {
const gitStatus = status();
expect(
resolveThreadPr({
threadBranch: "feature/current",
gitStatus,
}),
).toBe(gitStatus.pr);
});
});
describe("resolveDisplayedThreadPr + nextThreadChangeRequestSnapshot", () => {
const featureBranch = "feature/current";
const mergedPr = mergedFeaturePr();
const linkedPullRequest = {
projectId: ProjectId.make("project-1"),
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
};
const provider = {
kind: "github" as const,
name: "GitHub",
baseUrl: "https://github.com",
};
it("returns the live merged PR when the checkout matches the feature branch", () => {
const gitStatus = status({
refName: featureBranch,
pr: mergedPr,
sourceControlProvider: provider,
});
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus,
snapshot: undefined,
retainTerminalOnBranchMismatch: true,
}),
).toBe(mergedPr);
expect(
resolveDisplayedThreadPrProvider({
threadBranch: featureBranch,
gitStatus,
snapshot: undefined,
retainTerminalOnBranchMismatch: true,
}),
).toEqual(provider);
});
it("shows a linked pull request when the checkout has a different branch", () => {
const linkedPullRequestStatus = {
pr: mergedPr,
sourceControlProvider: provider,
};
expect(
resolveDisplayedThreadPr({
threadBranch: "feature/other",
gitStatus: status({ refName: "feature/other", pr: null }),
snapshot: undefined,
retainTerminalOnBranchMismatch: false,
linkedPullRequest,
linkedPullRequestStatus,
}),
).toEqual(mergedPr);
expect(
resolveDisplayedThreadPrProvider({
threadBranch: "feature/other",
gitStatus: status({ refName: "feature/other", pr: null }),
snapshot: undefined,
retainTerminalOnBranchMismatch: false,
linkedPullRequest,
linkedPullRequestStatus,
}),
).toEqual(provider);
expect(
nextThreadChangeRequestSnapshot({
threadBranch: "feature/other",
gitStatus: status({ refName: "feature/other", pr: null }),
snapshot: undefined,
retainTerminalOnBranchMismatch: false,
linkedPullRequest,
linkedPullRequestStatus,
}),
).toEqual({
branch: "feature/other",
pr: mergedPr,
sourceControlProvider: provider,
linkedPullRequest,
});
});
it("keeps a matching linked pull request snapshot while its status reloads", () => {
const snapshot = {
...snapshotFor(featureBranch, mergedPr, provider),
linkedPullRequest,
};
expect(
resolveDisplayedThreadPr({
threadBranch: null,
gitStatus: null,
snapshot,
retainTerminalOnBranchMismatch: false,
linkedPullRequest,
linkedPullRequestStatus: null,
}),
).toEqual(mergedPr);
expect(
nextThreadChangeRequestSnapshot({
threadBranch: null,
gitStatus: null,
snapshot,
retainTerminalOnBranchMismatch: false,
linkedPullRequest,
linkedPullRequestStatus: null,
}),
).toBeUndefined();
});
it("clears an old snapshot when a different pull request is linked", () => {
const snapshot = {
...snapshotFor(featureBranch, mergedPr, provider),
linkedPullRequest: { ...linkedPullRequest, number: 41 },
};
expect(
nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: null,
snapshot,
retainTerminalOnBranchMismatch: true,
linkedPullRequest,
linkedPullRequestStatus: null,
}),
).toBeNull();
});
it("removes a linked pull request snapshot after the link is cleared", () => {
const snapshot = {
...snapshotFor(featureBranch, mergedPr, provider),
linkedPullRequest,
};
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: status({ refName: "main", pr: null }),
snapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
expect(
nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: null,
snapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
});
it("after caching a merged PR, resolves main status back to the cached feature PR", () => {
const matchingStatus = status({
refName: featureBranch,
pr: mergedPr,
sourceControlProvider: provider,
});
const cached = nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: matchingStatus,
snapshot: undefined,
retainTerminalOnBranchMismatch: true,
});
expect(cached).toEqual(snapshotFor(featureBranch, mergedPr, provider));
const mainStatus = status({
refName: "main",
isDefaultRef: true,
pr: {
number: 99,
title: "Unrelated main PR",
url: "https://github.com/pingdotgg/t3code/pull/99",
baseRef: "main",
headRef: "main",
state: "open",
},
sourceControlProvider: provider,
});
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: mainStatus,
snapshot: cached as ThreadChangeRequestSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toEqual(mergedPr);
expect(
resolveDisplayedThreadPrProvider({
threadBranch: featureBranch,
gitStatus: mainStatus,
snapshot: cached as ThreadChangeRequestSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toEqual(provider);
});
it("never attaches a PR reported by main to the feature thread", () => {
const mainPr = {
number: 99,
title: "Unrelated main PR",
url: "https://github.com/pingdotgg/t3code/pull/99",
baseRef: "develop",
headRef: "main",
state: "merged" as const,
};
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: status({ refName: "main", pr: mainPr }),
snapshot: undefined,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
expect(
nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: status({ refName: "main", pr: mainPr }),
snapshot: undefined,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
});
it("does not show a cached open PR across a branch mismatch", () => {
const openSnapshot = snapshotFor(featureBranch, {
...mergedPr,
state: "open",
title: "Still open",
});
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: status({ refName: "main", pr: null }),
snapshot: openSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
});
it("retains a cached closed PR across a branch mismatch", () => {
const closedPr = { ...mergedPr, state: "closed" as const, title: "Closed feature" };
const closedSnapshot = snapshotFor(featureBranch, closedPr, provider);
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: status({ refName: "main", pr: null }),
snapshot: closedSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toEqual(closedPr);
});
it("does not retain or display a terminal PR when a worktree switches branches", () => {
const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider);
const mismatchedStatus = status({ refName: "feature/other", pr: null });
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: mismatchedStatus,
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: false,
}),
).toBeNull();
expect(
resolveDisplayedThreadPrProvider({
threadBranch: featureBranch,
gitStatus: mismatchedStatus,
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: false,
}),
).toBeUndefined();
expect(
nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: mismatchedStatus,
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: false,
}),
).toBeNull();
});
it("retains a local terminal snapshot when thread metadata follows the new branch", () => {
const otherBranchSnapshot = snapshotFor("feature/other", mergedPr, provider);
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: status({ refName: "main", pr: null }),
snapshot: otherBranchSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toEqual(mergedPr);
});
it("retains a terminal snapshot when a local thread and status move to a branch with no PR", () => {
const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider);
expect(
nextThreadChangeRequestSnapshot({
threadBranch: "main",
gitStatus: status({ refName: "main", pr: null }),
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeUndefined();
expect(
resolveDisplayedThreadPr({
threadBranch: "main",
gitStatus: status({ refName: "main", pr: null }),
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toEqual(mergedPr);
});
it("clears an open snapshot when a local thread moves to a branch with no PR", () => {
const openSnapshot = snapshotFor(featureBranch, { ...mergedPr, state: "open" });
expect(
nextThreadChangeRequestSnapshot({
threadBranch: "main",
gitStatus: status({ refName: "main", pr: null }),
snapshot: openSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
});
it("clears an open snapshot when a local checkout moves to a different branch", () => {
const openSnapshot = snapshotFor(featureBranch, { ...mergedPr, state: "open" });
expect(
nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: status({ refName: "main", pr: null }),
snapshot: openSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
});
it("clears a retained snapshot when the thread branch is cleared", () => {
const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider);
expect(
nextThreadChangeRequestSnapshot({
threadBranch: null,
gitStatus: status({ refName: "main", pr: null }),
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
expect(
resolveDisplayedThreadPr({
threadBranch: null,
gitStatus: status({ refName: "main", pr: null }),
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeNull();
expect(
resolveDisplayedThreadPrProvider({
threadBranch: null,
gitStatus: status({ refName: "main", pr: null }),
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeUndefined();
});
it("does not erase a terminal snapshot when VCS data is missing", () => {
const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider);
expect(
nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: null,
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toBeUndefined();
expect(
resolveDisplayedThreadPr({
threadBranch: featureBranch,
gitStatus: null,
snapshot: terminalSnapshot,
retainTerminalOnBranchMismatch: true,
}),
).toEqual(mergedPr);
});
it("retains a merged PR after a main checkout", () => {
const matchingStatus = status({
refName: featureBranch,
pr: mergedPr,
sourceControlProvider: provider,
});
const cached = nextThreadChangeRequestSnapshot({
threadBranch: featureBranch,
gitStatus: matchingStatus,
snapshot: undefined,
retainTerminalOnBranchMismatch: true,
});
expect(cached).not.toBeNull();
expect(cached).not.toBeUndefined();
const mainStatus = status({ refName: "main", pr: null, isDefaultRef: true });
const displayed = resolveDisplayedThreadPr({
threadBranch: "main",
gitStatus: mainStatus,
snapshot: cached as ThreadChangeRequestSnapshot,
retainTerminalOnBranchMismatch: true,
});
expect(displayed?.state).toBe("merged");
});
it("refreshes a cached snapshot when a pull request becomes ready", () => {
const readyPr = { ...mergedPr, state: "open" as const };
const draftPr = { ...readyPr, isDraft: true };
expect(
threadChangeRequestSnapshotsEqual(
snapshotFor(featureBranch, draftPr),
snapshotFor(featureBranch, readyPr),
),
).toBe(false);
});
});
describe("threadChangeRequestSnapshotsAtom", () => {
it.effect("retains snapshots while sidebar and chat consumers are unmounted", () =>
Effect.gen(function* () {
const registry = AtomRegistry.make();
const threadKey = "environment-1:thread-1";
const snapshot = snapshotFor("feature/current", mergedFeaturePr());
const unmount = registry.mount(threadChangeRequestSnapshotsAtom);
registry.set(threadChangeRequestSnapshotsAtom, new Map([[threadKey, snapshot]]));
unmount();
yield* Effect.yieldNow;
const remount = registry.mount(threadChangeRequestSnapshotsAtom);
expect(registry.get(threadChangeRequestSnapshotsAtom).get(threadKey)).toEqual(snapshot);
remount();
registry.dispose();
}),
);
});
describe("prStatusIndicator", () => {
it("formats PR tooltips with number, uppercase status, and title", () => {
expect(prStatusIndicator(status().pr, undefined)).toMatchObject({
@@ -1,8 +1,4 @@
import {
scopeProjectRef,
scopedThreadKey,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
import {
type EnvironmentId,
@@ -10,17 +6,13 @@ import {
type ThreadLinkedPullRequest,
type VcsStatusResult,
} from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { FolderGit2Icon, TerminalIcon } from "lucide-react";
import { useMemo } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { useProject } from "../state/entities";
import { useEnvironmentQuery } from "../state/query";
import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { vcsEnvironment } from "../state/vcs";
import { useUiStateStore } from "../uiStateStore";
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
@@ -51,12 +43,14 @@ export interface LinkedThreadPullRequestStatus {
readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
}
/** Keep cached summaries visible when an offscreen row stops live queries. */
export function useLinkedThreadPullRequest(
environmentId: EnvironmentId | null,
linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
enabled = true,
): LinkedThreadPullRequestStatus | null {
const queried = useEnvironmentQuery(
environmentId === null || linkedPullRequest == null
!enabled || environmentId === null || linkedPullRequest == null
? null
: linkedPullRequestDetailAtom({
environmentId,
@@ -178,271 +172,6 @@ export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }
);
}
export function resolveThreadPr(input: {
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
}): ThreadPr | null {
const { threadBranch, gitStatus } = input;
if (gitStatus === null) {
return null;
}
if (threadBranch === null || gitStatus.refName !== threadBranch) {
return null;
}
return gitStatus.pr ?? null;
}
/**
* Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
* partitions move them, so terminal PR metadata must live above the row.
*/
export interface ThreadChangeRequestSnapshot {
readonly branch: string;
readonly pr: NonNullable<ThreadPr>;
readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
readonly linkedPullRequest?: ThreadLinkedPullRequest;
}
export const threadChangeRequestSnapshotsAtom = Atom.make<
ReadonlyMap<string, ThreadChangeRequestSnapshot>
>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots"));
function isTerminalChangeRequestState(
state: NonNullable<ThreadPr>["state"],
): state is "merged" | "closed" {
return state === "merged" || state === "closed";
}
function sourceControlProvidersEqual(
left: VcsStatusResult["sourceControlProvider"] | undefined,
right: VcsStatusResult["sourceControlProvider"] | undefined,
): boolean {
if (left === right) return true;
if (left == null || right == null) return left == null && right == null;
return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
}
function linkedPullRequestsEqual(
left: ThreadLinkedPullRequest | null | undefined,
right: ThreadLinkedPullRequest | null | undefined,
): boolean {
if (left == null || right == null) return left == null && right == null;
return (
left.projectId === right.projectId &&
left.repository === right.repository &&
left.number === right.number &&
left.url === right.url
);
}
export function threadChangeRequestSnapshotsEqual(
left: ThreadChangeRequestSnapshot,
right: ThreadChangeRequestSnapshot,
): boolean {
return (
left.branch === right.branch &&
left.pr.number === right.pr.number &&
left.pr.title === right.pr.title &&
left.pr.url === right.pr.url &&
left.pr.baseRef === right.pr.baseRef &&
left.pr.headRef === right.pr.headRef &&
left.pr.state === right.pr.state &&
left.pr.isDraft === right.pr.isDraft &&
(left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
);
}
export function setThreadChangeRequestSnapshot(
threadKey: string,
snapshot: ThreadChangeRequestSnapshot | null,
): void {
appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
const existing = current.get(threadKey);
if (snapshot === null) {
if (existing === undefined) return [false, current];
const next = new Map(current);
next.delete(threadKey);
return [true, next];
}
if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
return [false, current];
}
const next = new Map(current);
next.set(threadKey, snapshot);
return [true, next];
});
}
/**
* Authoritative snapshot update from live VCS status.
* - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
* - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
* - snapshot: matching branch reports a PR — store/replace
*/
export function nextThreadChangeRequestSnapshot(input: {
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
snapshot: ThreadChangeRequestSnapshot | null | undefined;
retainTerminalOnBranchMismatch: boolean;
linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
}): ThreadChangeRequestSnapshot | null | undefined {
const {
threadBranch,
gitStatus,
snapshot,
retainTerminalOnBranchMismatch,
linkedPullRequest,
linkedPullRequestStatus,
} = input;
if (linkedPullRequest != null) {
if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
? undefined
: null;
}
return {
branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
pr: linkedPullRequestStatus.pr,
sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
linkedPullRequest,
};
}
if (gitStatus === null) {
return snapshot?.linkedPullRequest === undefined ? undefined : null;
}
if (threadBranch === null) {
return null;
}
if (gitStatus.refName !== threadBranch) {
return retainTerminalOnBranchMismatch &&
snapshot != null &&
snapshot.linkedPullRequest === undefined &&
isTerminalChangeRequestState(snapshot.pr.state)
? undefined
: null;
}
if (gitStatus.pr == null) {
if (
retainTerminalOnBranchMismatch &&
snapshot != null &&
snapshot.linkedPullRequest === undefined &&
isTerminalChangeRequestState(snapshot.pr.state)
) {
return undefined;
}
return null;
}
return {
branch: threadBranch,
pr: gitStatus.pr,
sourceControlProvider: gitStatus.sourceControlProvider,
};
}
/**
* Live PR when the checkout matches the thread branch; otherwise, for local
* checkouts only, a cached merged/closed PR for the thread. Local thread
* metadata follows the shared checkout, so the cached branch intentionally
* survives that metadata changing to the newly checked-out branch. Open PRs
* are never retained — their state can still change.
*/
export function resolveDisplayedThreadPr(input: {
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
snapshot: ThreadChangeRequestSnapshot | null | undefined;
retainTerminalOnBranchMismatch: boolean;
linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
}): ThreadPr | null {
const {
threadBranch,
gitStatus,
snapshot,
retainTerminalOnBranchMismatch,
linkedPullRequest,
linkedPullRequestStatus,
} = input;
if (linkedPullRequest != null) {
return (
linkedPullRequestStatus?.pr ??
(linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
? (snapshot?.pr ?? null)
: null)
);
}
if (
threadBranch !== null &&
gitStatus !== null &&
gitStatus.refName === threadBranch &&
gitStatus.pr != null
) {
return gitStatus.pr;
}
if (
threadBranch !== null &&
retainTerminalOnBranchMismatch &&
snapshot != null &&
snapshot.linkedPullRequest === undefined &&
isTerminalChangeRequestState(snapshot.pr.state)
) {
return snapshot.pr;
}
return null;
}
export function resolveDisplayedThreadPrProvider(input: {
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
snapshot: ThreadChangeRequestSnapshot | null | undefined;
retainTerminalOnBranchMismatch: boolean;
linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
}): VcsStatusResult["sourceControlProvider"] | undefined {
const {
threadBranch,
gitStatus,
snapshot,
retainTerminalOnBranchMismatch,
linkedPullRequest,
linkedPullRequestStatus,
} = input;
if (linkedPullRequest != null) {
return (
linkedPullRequestStatus?.sourceControlProvider ??
(linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
? snapshot?.sourceControlProvider
: undefined)
);
}
if (
threadBranch !== null &&
gitStatus !== null &&
gitStatus.refName === threadBranch &&
gitStatus.pr != null
) {
return gitStatus.sourceControlProvider;
}
if (
threadBranch !== null &&
retainTerminalOnBranchMismatch &&
snapshot != null &&
snapshot.linkedPullRequest === undefined &&
isTerminalChangeRequestState(snapshot.pr.state)
) {
return snapshot.sourceControlProvider;
}
return undefined;
}
export function terminalStatusFromRunningIds(
runningTerminalIds: ReadonlyArray<string>,
): TerminalStatusIndicator | null {
@@ -551,36 +280,12 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
const lastVisitedAt = useUiStateStore(
(state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
);
const threadProject = useProject(
useMemo(
() => scopeProjectRef(thread.environmentId, thread.projectId),
[thread.environmentId, thread.projectId],
),
);
const threadProjectCwd = threadProject?.workspaceRoot ?? null;
const gitCwd = thread.worktreePath ?? threadProjectCwd;
const linkedPullRequest = useLinkedThreadPullRequest(
const pullRequest = useLinkedThreadPullRequest(
thread.environmentId,
thread.linkedPullRequest,
);
const gitStatus = useEnvironmentQuery(
thread.linkedPullRequest == null &&
(thread.branch != null || thread.worktreePath !== null) &&
gitCwd !== null
? vcsEnvironment.status({
environmentId: thread.environmentId,
input: { cwd: gitCwd },
})
: null,
);
const pr =
thread.linkedPullRequest == null
? resolveThreadPr({ threadBranch: thread.branch, gitStatus: gitStatus.data })
: (linkedPullRequest?.pr ?? null);
const prStatus = prStatusIndicator(
pr,
linkedPullRequest?.sourceControlProvider ?? gitStatus.data?.sourceControlProvider,
thread.linkedPullRequest ?? thread.branchPullRequest,
);
const pr = pullRequest?.pr ?? null;
const prStatus = prStatusIndicator(pr, pullRequest?.sourceControlProvider);
const threadStatus = resolveThreadStatusPill({
thread: {
...thread,
@@ -8,7 +8,6 @@ import {
type PullRequestListEntry,
type PullRequestUpdateMethod,
type PullRequestRef,
type PullRequestState,
resolveEnvironmentMachineKind,
type ScopedThreadRef,
} from "@t3tools/contracts";
@@ -454,7 +453,6 @@ export function PullRequestDetailPanel({
refreshToken: forcedRefreshToken = 0,
onActed,
onClose,
onStateChange,
context = "page",
composerDraftTarget,
}: {
@@ -482,8 +480,6 @@ export function PullRequestDetailPanel({
onActed?: () => void;
/** Page-owned detail columns use this to clear the selected pull request. */
onClose?: () => 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
@@ -714,14 +710,6 @@ export function PullRequestDetailPanel({
}
activityRevision.current = next;
}, [activityQuery.refresh, coreDetail, tabScopeKey]);
useLayoutEffect(() => {
if (!resolvedCoreDetail) return;
onStateChange?.({
repository: resolvedCoreDetail.repository,
number: resolvedCoreDetail.number,
state: resolvedCoreDetail.state,
});
}, [onStateChange, resolvedCoreDetail]);
// Reuse activity and diff until core detail reports a changed revision. Keyed by
// the pull request rather than by the panel, because this one panel shows a different pull
// request every time it is opened.