TypeScript
fix(server): link thread PRs without an open client (#10101)
Theo Browne223ff4490f76
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsxindex 4c41ce2bf15..798a6a840c9 100644--- a/apps/mobile/src/features/home/HomeScreen.tsx+++ b/apps/mobile/src/features/home/HomeScreen.tsx@@ -416,14 +416,6 @@ export function HomeScreen(props: HomeScreenProps) {[threadListV2Enabled, projectGroups, effectiveGroupDisplayStates, hasSearchQuery],);- const projectCwdByKey = useMemo(() => {- const map = new Map<string, string>();- for (const project of props.projects) {- map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);- }- return map;- }, [props.projects]);-const projectByKey = useMemo(() => {const map = new Map<string, EnvironmentProject>();for (const project of props.projects) {@@ -850,9 +842,6 @@ export function HomeScreen(props: HomeScreenProps) {onPinThread={handlePinThread}onUnpinThread={handleUnpinThread}onMovePinnedThread={handleMovePinnedThread}- projectCwd={- projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null- }onSwipeableClose={handleSwipeableClose}onSwipeableWillOpen={handleSwipeableWillOpen}/>@@ -875,7 +864,6 @@ export function HomeScreen(props: HomeScreenProps) {machineByEnvironmentId,pinReorderEnvironmentIds,projectByKey,- projectCwdByKey,props.onArchiveThread,props.onDeletePendingTask,props.onSelectPendingTask,@@ -903,7 +891,6 @@ export function HomeScreen(props: HomeScreenProps) {const v2ExtraData = useMemo(() => ({projectByKey,- projectCwdByKey,projectTitleByProjectKey: v2ProjectTitleByProjectKey,serverConfigs,savedConnectionsById: props.savedConnectionsById,@@ -913,7 +900,6 @@ export function HomeScreen(props: HomeScreenProps) {}),[projectByKey,- projectCwdByKey,props.searchQuery,props.savedConnectionsById,serverConfigs,@@ -925,12 +911,11 @@ export function HomeScreen(props: HomeScreenProps) {const extraData = useMemo(() => ({- projectCwdByKey,savedConnectionsById: props.savedConnectionsById,searchQuery: props.searchQuery,threadSearchMatchByKey,}),- [projectCwdByKey, props.savedConnectionsById, props.searchQuery, threadSearchMatchByKey],+ [props.savedConnectionsById, props.searchQuery, threadSearchMatchByKey],);const renderItem = useCallback(@@ -982,10 +967,6 @@ export function HomeScreen(props: HomeScreenProps) {props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null}environmentMachine={machineByEnvironmentId.get(thread.environmentId)}- projectCwd={- projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??- null- }isLast={item.isLast}searchMatch={threadSearchMatchByKey.get(threadSearchMatchKey({@@ -1021,7 +1002,6 @@ export function HomeScreen(props: HomeScreenProps) {handleSwipeableWillOpen,handleRegenerateThreadTitle,machineByEnvironmentId,- projectCwdByKey,props.onArchiveThread,props.onDeletePendingTask,props.onDeleteThread,diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsxindex 909bbcf5a76..ad29e0f32a1 100644--- a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx+++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx@@ -12,10 +12,8 @@ import {import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";-import { useProject, useThreadShell } from "../../state/entities";-import { useEnvironmentQuery } from "../../state/query";+import { useThreadShell } from "../../state/entities";import type { GitActionProgress } from "../../state/use-vcs-action-state";-import { vcsEnvironment } from "../../state/vcs";import { GitActionProgressOverlay } from "../threads/GitActionProgressOverlay";import {dispatchHardwareKeyboardCommand,@@ -40,43 +38,16 @@ export function HardwareKeyboardCommandProvider({const navigation = useNavigation();const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]);const activeThread = useThreadShell(activeThreadRef);- const activeProjectRef = useMemo(- () =>- activeThread === null- ? null- : {- environmentId: activeThread.environmentId,- projectId: activeThread.projectId,- },- [activeThread],- );- const activeProject = useProject(activeProjectRef);- const activeThreadCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot ?? null;- const gitStatus = useEnvironmentQuery(- activeThread !== null &&- activeThread.linkedPullRequest == null &&- activeThread.branch !== null &&- activeThreadCwd !== null- ? vcsEnvironment.status({- environmentId: activeThread.environmentId,- input: { cwd: activeThreadCwd },- })- : null,- ).data;- const detectedPullRequestUrl =- activeThread?.branch != null && gitStatus?.refName === activeThread.branch- ? (gitStatus.pr?.url ?? null)- : null;const copyTarget = useMemo(() =>activeThreadRef === null? null: resolveThreadReferenceCopyTarget({threadId: activeThread?.id ?? activeThreadRef.threadId,- linkedPullRequestUrl: activeThread?.linkedPullRequest?.url ?? null,- detectedPullRequestUrl,+ linkedPullRequestUrl:+ (activeThread?.linkedPullRequest ?? activeThread?.branchPullRequest)?.url ?? null,}),- [activeThread, activeThreadRef, detectedPullRequestUrl],+ [activeThread, activeThreadRef],);const [copyFeedback, setCopyFeedback] = useState<GitActionProgress>(EMPTY_COPY_FEEDBACK);const copyRequestIdRef = useRef(0);diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsxindex 07357a1b752..f529432070b 100644--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx@@ -353,13 +353,6 @@ function ThreadNavigationSidebarPane(}),[threadListV2Enabled, groups, groupDisplayStates, hasSearchQuery],);- const projectCwdByKey = useMemo(() => {- const map = new Map<string, string>();- for (const project of projects) {- map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);- }- return map;- }, [projects]);const projectByKey = useMemo(() => {const map = new Map<string, EnvironmentProject>();for (const project of projects) {@@ -742,7 +735,6 @@ function ThreadNavigationSidebarPane(() => ({selectedThreadKey: props.selectedThreadKey ?? "",projectByKey,- projectCwdByKey,projectTitleByProjectKey,savedConnectionsById,serverConfigs,@@ -752,7 +744,6 @@ function ThreadNavigationSidebarPane([props.selectedThreadKey,projectByKey,- projectCwdByKey,projectTitleByProjectKey,savedConnectionsById,serverConfigs,@@ -914,7 +905,6 @@ function ThreadNavigationSidebarPane(onPinThread={pinThread}onUnpinThread={unpinThread}onMovePinnedThread={movePinnedThread}- projectCwd={projectCwdByKey.get(scopeKey) ?? null}onSwipeableClose={handleSwipeableClose}onSwipeableWillOpen={handleSwipeableWillOpen}simultaneousSwipeGesture={sidebarScrollGesture}@@ -1000,10 +990,6 @@ function ThreadNavigationSidebarPane(savedConnectionsById[thread.environmentId]?.environmentLabel ?? null}environmentMachine={machineByEnvironmentId.get(thread.environmentId)}- projectCwd={- projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??- null- }isLast={item.isLast}searchMatch={threadSearchMatchByKey.get(threadSearchMatchKey({@@ -1054,7 +1040,6 @@ function ThreadNavigationSidebarPane(pinThread,pinningEnvironmentIds,projectByKey,- projectCwdByKey,projectTitleByProjectKey,regenerateThreadTitle,props.onNewThreadInProject,diff --git a/apps/mobile/src/features/threads/thread-list-items.tsx b/apps/mobile/src/features/threads/thread-list-items.tsxindex fc3898279e3..e65cf7a9fb4 100644--- a/apps/mobile/src/features/threads/thread-list-items.tsx+++ b/apps/mobile/src/features/threads/thread-list-items.tsx@@ -416,7 +416,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {readonly thread: EnvironmentThreadShell;readonly environmentLabel: string | null;readonly environmentMachine?: EnvironmentMachineKind;- readonly projectCwd: string | null;readonly searchMatch?: EnvironmentThreadSearchMatch;readonly searchQuery?: string;readonly isLast: boolean;@@ -453,7 +452,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =props;const status = resolveThreadStatus(thread);- const pr = useThreadPr(thread, props.projectCwd);+ const pr = useThreadPr(thread);const timestamp = relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,);diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsxindex e34dce05901..e66fa778476 100644--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx@@ -377,7 +377,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {readonly canMovePinnedDown?: boolean;readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;readonly onSwipeableClose: (methods: SwipeableMethods) => void;- readonly projectCwd?: string | null;readonly searchMatch?: EnvironmentThreadSearchMatch;readonly searchQuery?: string;readonly simultaneousSwipeGesture?: ComponentProps<@@ -403,7 +402,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {const snoozedRow = props.snoozed === true;const pinnedRow = props.pinned === true;- const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);+ const pr = useThreadPr(thread);const theme = useUniwindTheme();const screenColor = theme["--color-screen"];diff --git a/apps/mobile/src/state/use-thread-pr.ts b/apps/mobile/src/state/use-thread-pr.tsindex 8e4eb27963a..e824ce56217 100644--- a/apps/mobile/src/state/use-thread-pr.ts+++ b/apps/mobile/src/state/use-thread-pr.ts@@ -12,9 +12,8 @@ import { connectionAtomRuntime } from "../connection/runtime";import { appAtomRegistry } from "./atom-registry";import { useEnvironmentQuery } from "./query";import { presentThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation";-import { vcsEnvironment } from "./vcs";-const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFamily(connectionAtomRuntime);+const pullRequestSummaryAtom = createLinkedPullRequestSummaryAtomFamily(connectionAtomRuntime);const MAX_THREAD_PR_SNAPSHOTS = 500;interface ThreadPrSnapshot {@@ -23,7 +22,7 @@ interface ThreadPrSnapshot {}// One bounded cache survives row virtualization without retaining one live-// atom for every thread, branch, directory, or linked pull request ever seen.+// atom for every thread or pull request ever seen.const threadPrSnapshotsAtom = Atom.make<ReadonlyMap<string, ThreadPrSnapshot>>(new Map()).pipe(Atom.keepAlive,Atom.withLabel("mobile:thread-pr-snapshots"),@@ -36,20 +35,13 @@ export {} from "./thread-pr-presentation";/**- * Live PR status for a thread's branch. Subscriptions are deduplicated per- * (environmentId, cwd) by the atom family, so many rows on the same worktree- * or project root share one stream — and virtualization means only visible- * rows subscribe at all.+ * Live status for a thread's server-provided PR. Visible rows share a summary+ * request for the same PR in the same environment.*/-export function useThreadPr(- thread: EnvironmentThreadShell,- projectCwd: string | null,-): ThreadPrPresentation | null {- const cwd = thread.worktreePath ?? projectCwd;+export function useThreadPr(thread: EnvironmentThreadShell): ThreadPrPresentation | null {+ const pullRequestRef = thread.linkedPullRequest ?? thread.branchPullRequest ?? null;const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));- const snapshotIdentity = JSON.stringify(- thread.linkedPullRequest ?? { branch: thread.branch, cwd },- );+ const snapshotIdentity = JSON.stringify(pullRequestRef);// Select this row's entry so writes for other rows do not re-render it.const snapshotEntry = useAtomValue(threadPrSnapshotsAtom,@@ -59,45 +51,30 @@ export function useThreadPr(),);const snapshot = snapshotEntry?.identity === snapshotIdentity ? snapshotEntry.presentation : null;- const gitStatus = useEnvironmentQuery(- thread.linkedPullRequest == null && thread.branch !== null && cwd !== null- ? vcsEnvironment.status({- environmentId: thread.environmentId,- input: { cwd },- })- : null,- );- const linkedPullRequest = useEnvironmentQuery(- thread.linkedPullRequest == null+ const pullRequestSummary = useEnvironmentQuery(+ pullRequestRef === null? null- : linkedPullRequestDetailAtom({+ : pullRequestSummaryAtom({environmentId: thread.environmentId,input: {- projectId: thread.linkedPullRequest.projectId,- repository: thread.linkedPullRequest.repository,- number: thread.linkedPullRequest.number,+ projectId: pullRequestRef.projectId,+ repository: pullRequestRef.repository,+ number: pullRequestRef.number,},}),);const live = useMemo<ThreadPrPresentation | null | undefined>(() => {- if (thread.linkedPullRequest != null) {- const detail = linkedPullRequest.data;- return detail === null- ? undefined- : presentThreadPr(pullRequestDetailToVcsStatus(detail), {- kind: detail.provider,- name: detail.provider,- baseUrl: "",- });- }-- const status = gitStatus.data;- if (thread.branch === null) return null;- if (status === null) return undefined;- if (status.refName !== thread.branch || !status.pr) return null;- return presentThreadPr(status.pr, status.sourceControlProvider);- }, [gitStatus.data, linkedPullRequest.data, thread.branch, thread.linkedPullRequest]);+ if (pullRequestRef === null) return null;+ const summary = pullRequestSummary.data;+ return summary === null+ ? undefined+ : presentThreadPr(pullRequestDetailToVcsStatus(summary), {+ kind: summary.provider,+ name: summary.provider,+ baseUrl: "",+ });+ }, [pullRequestRef, pullRequestSummary.data]);useEffect(() => {if (live === undefined) return;diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.tsindex e0e87d609d5..b7350dd5ddd 100644--- a/apps/mobile/src/state/use-thread-selection.ts+++ b/apps/mobile/src/state/use-thread-selection.ts@@ -55,6 +55,7 @@ function threadDetailToShell(branch: thread.branch,worktreePath: thread.worktreePath,linkedPullRequest: thread.linkedPullRequest ?? null,+ branchPullRequest: thread.branchPullRequest ?? null,latestTurn: thread.latestTurn,createdAt: thread.createdAt,updatedAt: thread.updatedAt,diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.tsindex ce34855a319..1c035d5fa15 100644--- a/apps/server/integration/OrchestrationEngineHarness.integration.ts+++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts@@ -67,6 +67,7 @@ import {} from "../src/orchestration/Services/OrchestrationEngine.ts";import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";import * as ThreadSettlementReactor from "../src/orchestration/ThreadSettlementReactor.ts";+import * as ThreadPullRequestReactor from "../src/orchestration/ThreadPullRequestReactor.ts";import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";import {@@ -394,6 +395,12 @@ export const makeOrchestrationIntegrationHarness = (drainThrough: () => Effect.void,}),),+ Layer.provideMerge(+ Layer.succeed(ThreadPullRequestReactor.ThreadPullRequestReactor, {+ start: () => Effect.void,+ drain: Effect.void,+ }),+ ),Layer.provideMerge(Layer.succeed(ThreadSettlementReactor.ThreadSettlementReactor, {start: () => Effect.void,diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.tsindex b8f4090453b..999a0c20221 100644--- a/apps/server/src/git/GitManager.test.ts+++ b/apps/server/src/git/GitManager.test.ts@@ -13,6 +13,7 @@ import * as Logger from "effect/Logger";import * as Option from "effect/Option";import * as PlatformError from "effect/PlatformError";import * as References from "effect/References";+import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";import { ChildProcessSpawner } from "effect/unstable/process";import { expect } from "vite-plus/test";@@ -30,10 +31,13 @@ import {TextGenerationError,} from "@t3tools/contracts";import * as GitHubCli from "../sourceControl/GitHubCli.ts";+import * as GitLabCli from "../sourceControl/GitLabCli.ts";import * as TextGeneration from "../textGeneration/TextGeneration.ts";import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as VcsProcess from "../vcs/VcsProcess.ts";import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";+import * as GitLabSourceControlProvider from "../sourceControl/GitLabSourceControlProvider.ts";+import type { SourceControlProvider } from "../sourceControl/SourceControlProvider.ts";import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";import * as ServerConfig from "../config.ts";import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";@@ -41,6 +45,8 @@ import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";import * as ServerSettings from "../serverSettings.ts";import * as GitManager from "./GitManager.ts";+const encodeCliJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));+interface FakeGhScenario {prListSequence?: string[];prListByHeadSelector?: Record<string, string>;@@ -620,6 +626,7 @@ function preparePullRequestThread(function makeManager(input?: {ghScenario?: FakeGhScenario;+ sourceControlProvider?: SourceControlProvider["Service"];textGeneration?: Partial<FakeGitTextGeneration>;serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];@@ -659,7 +666,10 @@ function makeManager(input?: {);const sourceControlRegistryLayer = Layer.effect(SourceControlProviderRegistry.SourceControlProviderRegistry,- GitHubSourceControlProvider.make.pipe(+ (input?.sourceControlProvider === undefined+ ? GitHubSourceControlProvider.make+ : Effect.succeed(input.sourceControlProvider)+ ).pipe(Effect.map((provider) =>SourceControlProviderRegistry.SourceControlProviderRegistry.of({get: () => Effect.succeed(provider),@@ -1146,7 +1156,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {branch: "feature/saved-branch",});- expect(pullRequest).toEqual({+ expect(pullRequest).toMatchObject({+ number: 216,+ title: "Saved branch PR",+ url: "https://github.com/pingdotgg/t3code/pull/216",+ baseRef: "main",+ headRef: "feature/saved-branch",state: "open",closedAt: null,mergedAt: null,@@ -1191,7 +1206,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {const pullRequest = yield* manager.branchPullRequest({ cwd: repoDir, branch: "main" });- expect(pullRequest).toEqual({+ expect(pullRequest).toMatchObject({state: "merged",closedAt: null,mergedAt: "2026-04-07T15:00:00Z",@@ -1244,7 +1259,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {branch: "feature/deleted-local-branch",});- expect(pullRequest).toEqual({+ expect(pullRequest).toMatchObject({state: "merged",closedAt: null,mergedAt: null,@@ -1310,7 +1325,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {branch: "feature/deleted-fork-branch",});- expect(pullRequest).toEqual({+ expect(pullRequest).toMatchObject({state: "merged",closedAt: null,mergedAt: null,@@ -1432,6 +1447,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {updatedAt: "2026-04-07T15:00:00Z",},]),+ encodeCliJson([+ {+ number: 221,+ title: "New PR on the same branch",+ url: "https://github.com/pingdotgg/codething-mvp/pull/221",+ baseRefName: "main",+ headRefName: "feature/shared-pr-cache",+ state: "OPEN",+ updatedAt: "2026-04-08T15:00:00Z",+ },+ ]),],},});@@ -1445,6 +1471,16 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {expect(status.pr?.state).toBe("merged");expect(pullRequest?.state).toBe("merged");expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1);+ const refreshed = yield* manager.branchPullRequest(+ { cwd: repoDir, branch: "feature/shared-pr-cache" },+ { refresh: true },+ );+ expect(refreshed).toMatchObject({+ number: 221,+ state: "open",+ repositoryKey: "github.com/pingdotgg/codething-mvp",+ });+ expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2);}),);@@ -1459,7 +1495,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {yield* runGit(repoDir, ["push", "-u", "origin", "feature/lookup-failure"]);yield* runGit(repoDir, ["checkout", "main"]);- const { manager } = yield* makeManager({+ const { manager, ghCalls } = yield* makeManager({ghScenario: {failWith: new GitHubCli.GitHubCliUnavailableError({command: "gh",@@ -1474,6 +1510,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {.pipe(Effect.flip);expect(error._tag).toBe("SourceControlProviderError");+ const refreshError = yield* manager+ .branchPullRequest({ cwd: repoDir, branch: "feature/lookup-failure" }, { refresh: true })+ .pipe(Effect.flip);+ expect(refreshError._tag).toBe("SourceControlProviderError");+ expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1);}),);@@ -1594,6 +1635,186 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {expect(Duration.toMillis(GitManager.prLookupFailureTtl(20))).toBe(900_000);});+ it.each([+ [+ "https://github.example.com/team/repository/pull/42?tab=files",+ "github.example.com/team/repository",+ ],+ [+ "https://gitlab.example.com/group/subgroup/repository/-/merge_requests/42",+ "gitlab.example.com/group/subgroup/repository",+ ],+ ["https://bitbucket.org/team/repository/pull-requests/42", "bitbucket.org/team/repository"],+ [+ "https://dev.azure.com/org/project/_git/repository/pullrequest/42",+ "dev.azure.com/org/project/_git/repository",+ ],+ [+ "https://org.visualstudio.com/project/_git/repository/pullrequest/42",+ "org.visualstudio.com/project/_git/repository",+ ],+ [+ "https://gitlab.example/group/pull/123/repository/-/merge_requests/42",+ "gitlab.example/group/pull/123/repository",+ ],+ ["https://github.example.com/team/repository/issues/42", null],+ ] as const)("reads the repository from the returned PR URL %s", (url, expected) => {+ expect(GitManager.pullRequestRepositoryKey(url)).toBe(expected);+ });++ it.effect("distinguishes Enterprise forks with the same head branch", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ const originDir = yield* createBareRemote();+ const forkDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", originDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "main"]);+ yield* runGit(repoDir, ["remote", "add", "fork", forkDir]);+ yield* runGit(repoDir, ["checkout", "-b", "feature"]);+ yield* runGit(repoDir, ["push", "-u", "fork", "feature"]);+ yield* configureVisibleRemoteUrlWithLocalRewrite(+ repoDir,+ "origin",+ "[email protected]:team/repository.git",+ originDir,+ );+ yield* configureVisibleRemoteUrlWithLocalRewrite(+ repoDir,+ "fork",+ "[email protected]:alice/repository.git",+ forkDir,+ );+ const output = encodeCliJson([+ {+ number: 2,+ title: "Another fork",+ url: "https://github.example.com/team/repository/pull/2",+ baseRefName: "main",+ headRefName: "feature",+ state: "OPEN",+ updatedAt: "2026-04-08T15:00:00Z",+ isCrossRepository: true,+ headRepository: { nameWithOwner: "bob/repository" },+ headRepositoryOwner: { login: "bob" },+ },+ {+ number: 1,+ title: "This fork",+ url: "https://github.example.com/team/repository/pull/1",+ baseRefName: "main",+ headRefName: "feature",+ state: "OPEN",+ updatedAt: "2026-04-07T15:00:00Z",+ isCrossRepository: true,+ headRepository: { nameWithOwner: "alice/repository" },+ headRepositoryOwner: { login: "alice" },+ },+ ]);+ const { manager } = yield* makeManager({+ ghScenario: {+ prListByHeadSelector: {+ "alice:feature": output,+ "fork:feature": output,+ feature: output,+ },+ },+ });+ expect(yield* manager.branchPullRequest({ cwd: repoDir, branch: "feature" })).toMatchObject({+ number: 1,+ repositoryKey: "github.example.com/team/repository",+ });+ }),+ );++ it.effect.each([+ "[email protected]:Group/Subgroup/Fork.git",+ "https://gitlab.com/Group/Subgroup/Fork.git",+ ])("matches nested GitLab forks through the adapter for %s", (remoteUrl) =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ const originDir = yield* createBareRemote();+ const forkDir = yield* createBareRemote();+ const branch = "feature/NestedGroups";+ yield* runGit(repoDir, ["remote", "add", "origin", originDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "main"]);+ yield* runGit(repoDir, ["remote", "add", "fork", forkDir]);+ yield* runGit(repoDir, ["checkout", "-b", branch]);+ yield* runGit(repoDir, ["push", "-u", "fork", branch]);+ yield* configureVisibleRemoteUrlWithLocalRewrite(+ repoDir,+ "origin",+ "[email protected]:Group/Upstream/Repository.git",+ originDir,+ );+ yield* configureVisibleRemoteUrlWithLocalRewrite(repoDir, "fork", remoteUrl, forkDir);+ const output = encodeCliJson([+ {+ iid: 2,+ title: "Another subgroup's fork",+ web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/2",+ target_branch: "main",+ source_branch: branch,+ state: "opened",+ updated_at: "2026-04-08T15:00:00Z",+ source_project_id: 102,+ target_project_id: 100,+ source_project: { path_with_namespace: "Group/Other/Fork" },+ },+ {+ iid: 1,+ title: "This subgroup's fork",+ web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",+ target_branch: "main",+ source_branch: branch,+ state: "opened",+ updated_at: "2026-04-07T15:00:00Z",+ source_project_id: 101,+ target_project_id: 100,+ source_project: { path_with_namespace: "Group/Subgroup/Fork" },+ },+ ]);+ const calls: VcsProcess.VcsProcessInput[] = [];+ const provider = yield* GitLabSourceControlProvider.make.pipe(+ Effect.provide(+ GitLabCli.layer.pipe(+ Layer.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) =>+ Effect.sync(() => {+ calls.push(input);+ return fakeGhOutput(output);+ }),+ }),+ ),+ ),+ ),+ );+ const { manager } = yield* makeManager({ sourceControlProvider: provider });++ expect(yield* manager.branchPullRequest({ cwd: repoDir, branch })).toMatchObject({+ number: 1,+ repositoryKey: "gitlab.com/group/upstream/repository",+ });+ expect(calls.length).toBeGreaterThan(0);+ for (const call of calls) {+ expect(call.command).toBe("glab");+ expect(call.args).toEqual([+ "mr",+ "list",+ "--source-branch",+ branch,+ "--all",+ "--per-page",+ "20",+ "--output",+ "json",+ ]);+ }+ }),+ );+it.effect("status ignores unrelated fork PRs when the current branch tracks the same repository",() =>@@ -2149,7 +2370,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {branch: "feature/fork-settle",});- expect(pullRequest).toEqual({+ expect(pullRequest).toMatchObject({state: "merged",closedAt: null,mergedAt: null,diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.tsindex 76f2ebc6b51..f60eb278187 100644--- a/apps/server/src/git/GitManager.ts+++ b/apps/server/src/git/GitManager.ts@@ -77,6 +77,13 @@ export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOptireadonly refreshMissingPullRequest?: boolean;}+export type GitBranchPullRequest = NonNullable<VcsStatusResult["pr"]> & {+ readonly repositoryKey: string | null;+ readonly updatedAt: string | null;+ readonly closedAt?: string | null;+ readonly mergedAt?: string | null;+};+interface SourceControlTextGenerationSettings {readonly modelSelection: ModelSelection;readonly style: SourceControlWritingStyleSettings;@@ -96,18 +103,10 @@ export class GitManager extends Context.Service<options?: GitRemoteStatusOptions,) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;/** Resolve the PR for a saved branch without changing the current checkout. */- readonly branchPullRequest: (input: {- readonly cwd: string;- readonly branch: string;- }) => Effect.Effect<- {- readonly state: "open" | "closed" | "merged";- readonly updatedAt: string | null;- readonly closedAt?: string | null;- readonly mergedAt?: string | null;- } | null,- GitManagerServiceError- >;+ readonly branchPullRequest: (+ input: { readonly cwd: string; readonly branch: string },+ options?: { readonly refresh?: boolean },+ ) => Effect.Effect<GitBranchPullRequest | null, GitManagerServiceError>;readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;@@ -214,9 +213,26 @@ interface BranchHeadContext {isCrossRepository: boolean;}+export function pullRequestRepositoryKey(value: string): string | null {+ try {+ const url = new URL(value);+ const match =+ /^(.*)(?:\/pull\/|\/-\/merge_requests\/|\/pull-requests\/|\/pullrequest\/)\d+(?:\/.*)?$/iu.exec(+ url.pathname,+ );+ if (match?.[1] === undefined) return null;+ url.pathname = match[1];+ url.search = "";+ url.hash = "";+ return normalizeGitRemoteUrl(url.toString());+ } catch {+ return null;+ }+}+function parseRepositoryNameFromPullRequestUrl(url: string): string | null {const trimmed = url.trim();- const match = /^https:\/\/github\.com\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);+ const match = /^https?:\/\/[^/]+\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);const repositoryName = match?.[1]?.trim() ?? "";return repositoryName.length > 0 ? repositoryName : null;}@@ -254,14 +270,14 @@ function resolvePullRequestWorktreeLocalBranchName(return `t3code/pr-${pullRequest.number}/${suffix}`;}-function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {+function parseRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {const trimmed = url?.trim() ?? "";if (trimmed.length === 0) {return null;}const match =- /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(+ /^(?:[^@/\s]+@[^:/\s]+:|(?:ssh|https?|git):\/\/[^/]+\/)((?:[^/\s]+\/)+[^/\s]+?)(?:\.git)?\/?$/iu.exec(trimmed,);const repositoryNameWithOwner = match?.[1]?.trim() ?? "";@@ -273,6 +289,7 @@ function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | nullif (trimmed.length === 0) {return null;}+ // GitLab reports the top-level group as owner. The full path distinguishes subgroups.const [ownerLogin] = trimmed.split("/");const normalizedOwnerLogin = ownerLogin?.trim() ?? "";return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;@@ -1261,7 +1278,7 @@ export const make = Effect.gen(function* () {}const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);- const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);+ const repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);return {remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,repositoryNameWithOwner,@@ -2031,7 +2048,7 @@ export const make = Effect.gen(function* () {});const branchPullRequest: GitManager["Service"]["branchPullRequest"] = Effect.fn("branchPullRequest",- )(function* ({ cwd, branch }) {+ )(function* ({ cwd, branch }, options) {const cacheCwd = yield* normalizeStatusCacheKey(cwd);const remotes = yield* gitCore.execute({operation: "GitManager.branchPullRequest.remotes",@@ -2111,6 +2128,14 @@ export const make = Effect.gen(function* () {localBranchExists,...(localBranchExists ? {} : { remoteName }),});+ if (options?.refresh) {+ // A completed turn can create a PR or reuse a merged PR's branch.+ // Refresh successful answers, but keep failed lookups' retry backoff.+ const cached = yield* Cache.getOption(prLookupCache, cacheKey).pipe(+ Effect.orElseSucceed(() => Option.none()),+ );+ if (Option.isSome(cached)) yield* Cache.invalidate(prLookupCache, cacheKey);+ }let cached = yield* Cache.get(prLookupCache, cacheKey);// The cached head context may have resolved on a different remote than// the saved upstream: a branch tracking origin/main but pushed to a fork@@ -2165,12 +2190,13 @@ export const make = Effect.gen(function* () {) {return null;}- const statusPr = toStatusPr(latest);return {- state: statusPr.state,- updatedAt: statusPr.updatedAt,+ ...toStatusPr(latest),closedAt: latest.closedAt ?? null,mergedAt: latest.mergedAt ?? null,+ // Hosting CLIs can select an upstream repository instead of origin.+ // The returned PR URL names the repository that actually owns it.+ repositoryKey: pullRequestRepositoryKey(latest.url),};});const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsindex 2c426c5ee5d..0b2e08c40d6 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts@@ -13,6 +13,7 @@ import {ProjectId,ThreadId,TurnId,+ type OrchestrationCommand,type OrchestrationEvent,ProviderInstanceId,} from "@t3tools/contracts";@@ -993,6 +994,216 @@ describe("OrchestrationEngine", () => {await system.dispose();});+ it.each(["unlink", "relink", "branch", "worktree", "project", "delete"] as const)(+ "rejects PR discovery completed after a newer %s command",+ async (change) => {+ const system = await createOrchestrationSystem();+ try {+ const projectId = ProjectId.make("pr-race-project");+ const threadId = ThreadId.make("pr-race-thread");+ const previous = {+ projectId,+ repository: "owner/repository",+ number: 1,+ url: "https://example.test/owner/repository/pull/1",+ };+ const replacement = {+ ...previous,+ number: 2,+ url: "https://example.test/owner/repository/pull/2",+ };+ await system.run(+ system.engine.dispatch({+ type: "project.create",+ commandId: CommandId.make("pr-race-project-create"),+ projectId,+ title: "PR race project",+ workspaceRoot: "/tmp/pr-race-project",+ defaultModelSelection: null,+ createdAt: now(),+ }),+ );+ await system.run(+ system.engine.dispatch({+ type: "thread.create",+ commandId: CommandId.make("pr-race-thread-create"),+ threadId,+ projectId,+ title: "PR race thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: "feature",+ worktreePath: null,+ createdAt: now(),+ }),+ );+ const observed = await system.run(+ system.engine.dispatch({+ type: "thread.meta.update",+ commandId: CommandId.make("pr-race-link"),+ threadId,+ linkedPullRequest: previous,+ }),+ );+ const metadataChanges = {+ unlink: { linkedPullRequest: null },+ relink: {+ linkedPullRequest: {+ ...previous,+ number: 3,+ url: "https://example.test/owner/repository/pull/3",+ },+ },+ branch: { branch: "another-feature" },+ worktree: { worktreePath: "/tmp/another-worktree" },+ project: {},+ };+ await system.run(+ system.engine.dispatch(+ change === "project"+ ? {+ type: "project.meta.update",+ commandId: CommandId.make("pr-race-project-move"),+ projectId,+ workspaceRoot: "/tmp/another-project-root",+ }+ : change === "delete"+ ? { type: "thread.delete", commandId: CommandId.make("pr-race-delete"), threadId }+ : {+ type: "thread.meta.update",+ commandId: CommandId.make(`pr-race-${change}`),+ threadId,+ ...metadataChanges[change],+ },+ ),+ );+ const command = {+ type: "thread.pull-request.sync",+ commandId: CommandId.make("pr-race-stale-sync"),+ threadId,+ projectId,+ snapshotSequence: observed.sequence,+ expected: {+ workspaceRoot: "/tmp/pr-race-project",+ branch: "feature",+ worktreePath: null,+ linkedPullRequest: previous,+ branchPullRequest: null,+ },+ branchPullRequest: replacement,+ linkedPullRequest: replacement,+ } satisfies OrchestrationCommand;+ const error = await system.run(system.engine.dispatch(command).pipe(Effect.flip));+ expect(error._tag).toBe("OrchestrationCommandInvariantError");+ if (change === "delete") return;+ const current = (await system.readModel()).threads[0];+ expect(current?.branchPullRequest ?? null).toBeNull();+ expect(current?.linkedPullRequest ?? null).toEqual(+ change === "unlink"+ ? null+ : change === "relink"+ ? metadataChanges.relink.linkedPullRequest+ : previous,+ );+ } finally {+ await system.dispose();+ }+ },+ );++ it("saves PR associations through streaming and unrelated metadata edits", async () => {+ const system = await createOrchestrationSystem();+ try {+ const projectId = ProjectId.make("pr-sync-project");+ const threadId = ThreadId.make("pr-sync-thread");+ await system.run(+ system.engine.dispatch({+ type: "project.create",+ commandId: CommandId.make("pr-sync-project-create"),+ projectId,+ title: "PR sync project",+ workspaceRoot: "/tmp/pr-sync-project",+ defaultModelSelection: null,+ createdAt: now(),+ }),+ );+ const created = await system.run(+ system.engine.dispatch({+ type: "thread.create",+ commandId: CommandId.make("pr-sync-thread-create"),+ threadId,+ projectId,+ title: "PR sync thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: "feature",+ worktreePath: null,+ createdAt: now(),+ }),+ );+ const reference = {+ projectId,+ repository: "owner/repository",+ number: 42,+ url: "https://example.test/owner/repository/pull/42",+ };+ const activityAt = "2026-01-01T01:00:00.000Z";+ await system.run(+ system.engine.dispatch({+ type: "thread.message.assistant.delta",+ commandId: CommandId.make("pr-sync-streaming-message"),+ threadId,+ messageId: MessageId.make("pr-sync-message"),+ delta: "The PR is ready.",+ createdAt: activityAt,+ }),+ );+ await system.run(+ system.engine.dispatch({+ type: "thread.meta.update",+ commandId: CommandId.make("pr-sync-title-and-model"),+ threadId,+ title: "Renamed thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },+ }),+ );+ await system.run(+ system.engine.dispatch({+ type: "project.meta.update",+ commandId: CommandId.make("pr-sync-project-title"),+ projectId,+ title: "Renamed project",+ }),+ );+ const beforeSync = (await system.readModel()).threads[0];+ await system.run(+ system.engine.dispatch({+ type: "thread.pull-request.sync",+ commandId: CommandId.make("pr-sync-discovery"),+ projectId,+ threadId,+ snapshotSequence: created.sequence,+ expected: {+ workspaceRoot: "/tmp/pr-sync-project",+ branch: "feature",+ worktreePath: null,+ linkedPullRequest: null,+ branchPullRequest: null,+ },+ branchPullRequest: reference,+ }),+ );+ const current = (await system.readModel()).threads[0];+ expect(current?.branchPullRequest).toEqual(reference);+ expect(current?.linkedPullRequest ?? null).toBeNull();+ expect(current?.updatedAt).toBe(beforeSync?.updatedAt);+ } finally {+ await system.dispose();+ }+ });+it("allows authoritative worktree bootstrap to assign a temporary branch", async () => {const system = await createOrchestrationSystem();const { engine } = system;diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.tsindex 8512007ae8d..4350d145810 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts@@ -185,6 +185,23 @@ const makeOrchestrationEngine = Effect.gen(function* () {});}+ // The decider compares the lookup inputs. Only recreation needs an+ // event check, since it can reset a thread to the same field values.+ if (+ envelope.command.type === "thread.pull-request.sync" &&+ (yield* eventStore.hasEventAfter({+ aggregateKind: "thread",+ aggregateId: envelope.command.threadId,+ sequenceExclusive: envelope.command.snapshotSequence,+ type: "thread.created",+ }))+ ) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: envelope.command.type,+ detail: `thread ${envelope.command.threadId} was recreated before pull request discovery`,+ });+ }+if (envelope.command.type === "thread.auto-settle" &&threadBackgroundLiveness.getThreadBackgroundLiveness(envelope.command.threadId) !== nulldiff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.tsindex 1340480bce5..dd76721defa 100644--- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts@@ -10,6 +10,7 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";import * as ThreadSettlementReactor from "../ThreadSettlementReactor.ts";+import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";@@ -65,6 +66,15 @@ describe("OrchestrationReactor", () => {drainThrough: () => Effect.void,}),),+ Layer.provideMerge(+ Layer.succeed(ThreadPullRequestReactor.ThreadPullRequestReactor, {+ start: () => {+ started.push("thread-pull-request-reactor");+ return Effect.void;+ },+ drain: Effect.void,+ }),+ ),Layer.provideMerge(Layer.succeed(ThreadSettlementReactor.ThreadSettlementReactor, {start: () => {@@ -95,6 +105,7 @@ describe("OrchestrationReactor", () => {"provider-command-reactor","checkpoint-reactor","thread-deletion-reactor",+ "thread-pull-request-reactor","thread-settlement-reactor","agent-awareness-relay",]);diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.tsindex 649e803809d..a86907b0d78 100644--- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts@@ -10,6 +10,7 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";import * as ThreadSettlementReactor from "../ThreadSettlementReactor.ts";+import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";export const makeOrchestrationReactor = Effect.gen(function* () {@@ -18,6 +19,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {const checkpointReactor = yield* CheckpointReactor;const threadDeletionReactor = yield* ThreadDeletionReactor;const threadSettlementReactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;+ const threadPullRequestReactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {@@ -25,6 +27,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {yield* providerCommandReactor.start();yield* checkpointReactor.start();yield* threadDeletionReactor.start();+ yield* threadPullRequestReactor.start();yield* threadSettlementReactor.start();yield* agentAwarenessRelay.start();});diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex eb67d8a5b85..f619f6a9391 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -8,6 +8,7 @@ import {MessageId,ProjectId,ThreadId,+ ThreadLinkedPullRequest,TurnId,ProviderInstanceId,} from "@t3tools/contracts";@@ -18,6 +19,7 @@ import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Path from "effect/Path";+import * as Schema from "effect/Schema";import * as SqlClient from "effect/unstable/sql/SqlClient";import { makeSqlStatementCounter } from "../../../integration/SqlStatementCounter.integration.ts";@@ -59,6 +61,9 @@ const exists = (filePath: string) =>});const BaseTestLayer = makeProjectionPipelinePrefixedTestLayer("t3-projection-pipeline-test-");+const encodeThreadLinkedPullRequest = Schema.encodeSync(+ Schema.fromJsonString(ThreadLinkedPullRequest),+);it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-cursor-batch-")))("OrchestrationProjectionPipeline cursor batches",@@ -204,6 +209,93 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-import-shell-")},);+it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-branch-pr-projection-")))(+ "branch pull request projection",+ (it) => {+ it.effect("persists branch pull request updates without changing manual links", () =>+ Effect.gen(function* () {+ const projectionPipeline = yield* OrchestrationProjectionPipeline;+ const eventStore = yield* OrchestrationEventStore;+ const sql = yield* SqlClient.SqlClient;+ const now = "2026-01-01T00:00:00.000Z";+ const threadId = ThreadId.make("thread-pull-request");+ const projectId = ProjectId.make("project-pull-request");+ const eventFields = {+ aggregateKind: "thread" as const,+ aggregateId: threadId,+ occurredAt: now,+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ };+ const created = yield* eventStore.append({+ ...eventFields,+ type: "thread.created",+ eventId: EventId.make("evt-pull-request-created"),+ payload: {+ threadId,+ projectId,+ title: "Pull request thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: "feature",+ worktreePath: null,+ createdAt: now,+ updatedAt: now,+ },+ });+ yield* projectionPipeline.projectEvent(created);+ const linkedPullRequest = {+ projectId,+ repository: "pingdotgg/t3code",+ number: 42,+ url: "https://github.com/pingdotgg/t3code/pull/42",+ };+ const branchPullRequest = {+ ...linkedPullRequest,+ number: 43,+ url: "https://github.com/pingdotgg/t3code/pull/43",+ };+ const updates = [+ { payload: { linkedPullRequest, branchPullRequest }, expected: branchPullRequest },+ { payload: { title: "Renamed thread" }, expected: branchPullRequest },+ { payload: { branchPullRequest: null }, expected: null },+ ];++ for (const [index, update] of updates.entries()) {+ const event = yield* eventStore.append({+ ...eventFields,+ type: "thread.meta-updated",+ eventId: EventId.make(`evt-pull-request-update-${index}`),+ payload: { threadId, updatedAt: now, ...update.payload },+ });+ yield* projectionPipeline.projectEvent(event);++ const rows = yield* sql<{+ readonly linkedPullRequest: string | null;+ readonly branchPullRequest: string | null;+ }>`+ SELECT+ linked_pull_request_json AS "linkedPullRequest",+ branch_pull_request_json AS "branchPullRequest"+ FROM projection_threads+ WHERE thread_id = ${threadId}+ `;+ assert.deepEqual(rows, [+ {+ linkedPullRequest: encodeThreadLinkedPullRequest(linkedPullRequest),+ branchPullRequest:+ update.expected === null ? null : encodeThreadLinkedPullRequest(update.expected),+ },+ ]);+ }+ }),+ );+ },+);+it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {it.effect("bootstraps all projection states and writes projection rows", () =>Effect.gen(function* () {diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 7c71d7b6ee6..bcef68170a4 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -605,6 +605,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectibranch: event.payload.branch,worktreePath: event.payload.worktreePath,linkedPullRequest: null,+ branchPullRequest: null,latestTurnId: null,createdAt: event.payload.createdAt,updatedAt: event.payload.updatedAt,@@ -805,6 +806,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti...(event.payload.linkedPullRequest !== undefined? { linkedPullRequest: event.payload.linkedPullRequest }: {}),+ ...(event.payload.branchPullRequest !== undefined+ ? { branchPullRequest: event.payload.branchPullRequest }+ : {}),updatedAt: event.payload.updatedAt,});return;diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex 2e0a3c3459a..08a07c0be75 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -6,6 +6,7 @@ import {MessageId,ProjectId,ThreadId,+ ThreadLinkedPullRequest,TurnId,ProviderInstanceId,} from "@t3tools/contracts";@@ -36,6 +37,9 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(valconst encodeChatAttachments = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(ChatAttachment)),);+const encodeThreadLinkedPullRequest = Schema.encodeSync(+ Schema.fromJsonString(ThreadLinkedPullRequest),+);const projectionSnapshotLayer = it.layer(OrchestrationProjectionSnapshotQueryLive.pipe(@@ -52,6 +56,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {Effect.gen(function* () {const snapshotQuery = yield* ProjectionSnapshotQuery;const sql = yield* SqlClient.SqlClient;+ const branchPullRequest = {+ projectId: asProjectId("project-1"),+ repository: "pingdotgg/t3code",+ number: 43,+ url: "https://github.com/pingdotgg/t3code/pull/43",+ };yield* sql`DELETE FROM projection_projects`;yield* sql`DELETE FROM projection_state`;@@ -92,6 +102,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {branch,worktree_path,linked_pull_request_json,+ branch_pull_request_json,latest_turn_id,latest_user_message_at,pending_approval_count,@@ -113,6 +124,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {NULL,NULL,'{"projectId":"project-1","repository":"pingdotgg/t3code","number":42,"url":"https://github.com/pingdotgg/t3code/pull/42"}',+ ${encodeThreadLinkedPullRequest(branchPullRequest)},'turn-1','2026-02-24T00:00:04.000Z',1,@@ -323,6 +335,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {number: 42,url: "https://github.com/pingdotgg/t3code/pull/42",},+ branchPullRequest,latestTurn: {turnId: asTurnId("turn-1"),state: "completed",@@ -451,6 +464,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {number: 42,url: "https://github.com/pingdotgg/t3code/pull/42",},+ branchPullRequest,latestTurn: {turnId: asTurnId("turn-1"),state: "completed",@@ -498,6 +512,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {assert.deepEqual(threadDetail.value, snapshot.threads[0]);}+ const commandSnapshot = yield* snapshotQuery.getCommandReadModel();+ assert.deepEqual(commandSnapshot.threads[0]?.branchPullRequest, branchPullRequest);+ const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));+ assert.equal(threadShell._tag, "Some");+ if (threadShell._tag === "Some") {+ assert.deepEqual(threadShell.value.branchPullRequest, branchPullRequest);+ }+yield* sql`INSERT INTO projection_thread_activities (activity_id,@@ -743,6 +765,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {Effect.gen(function* () {const snapshotQuery = yield* ProjectionSnapshotQuery;const sql = yield* SqlClient.SqlClient;+ const branchPullRequest = {+ projectId: asProjectId("project-archive-test"),+ repository: "pingdotgg/t3code",+ number: 43,+ url: "https://github.com/pingdotgg/t3code/pull/43",+ };yield* sql`DELETE FROM projection_projects`;yield* sql`DELETE FROM projection_threads`;@@ -849,6 +877,13 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {shellSnapshot.threads.map((thread) => thread.id),[ThreadId.make("thread-active")],);+ assert.equal(shellSnapshot.threads[0]?.branchPullRequest, null);++ yield* sql`+ UPDATE projection_threads+ SET branch_pull_request_json = ${encodeThreadLinkedPullRequest(branchPullRequest)}+ WHERE thread_id = 'thread-archived'+ `;const archivedShellSnapshot = yield* snapshotQuery.getArchivedShellSnapshot();assert.deepEqual(@@ -856,6 +891,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {[ThreadId.make("thread-archived")],);assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z");+ assert.deepEqual(archivedShellSnapshot.threads[0]?.branchPullRequest, branchPullRequest);const activeContext = yield* snapshotQuery.getThreadRuntimeContext(ThreadId.make("thread-active"),);diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex d9f4526e9e6..b15b72ee567 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -116,6 +116,7 @@ const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(Struct.assign({modelSelection: Schema.fromJsonString(ModelSelection),linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),+ branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),}),);const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(@@ -500,6 +501,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {branch,worktree_path AS "worktreePath",linked_pull_request_json AS "linkedPullRequest",+ branch_pull_request_json AS "branchPullRequest",latest_turn_id AS "latestTurnId",created_at AS "createdAt",updated_at AS "updatedAt",@@ -538,6 +540,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {branch,worktree_path AS "worktreePath",linked_pull_request_json AS "linkedPullRequest",+ branch_pull_request_json AS "branchPullRequest",latest_turn_id AS "latestTurnId",created_at AS "createdAt",updated_at AS "updatedAt",@@ -578,6 +581,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {branch,worktree_path AS "worktreePath",linked_pull_request_json AS "linkedPullRequest",+ branch_pull_request_json AS "branchPullRequest",latest_turn_id AS "latestTurnId",created_at AS "createdAt",updated_at AS "updatedAt",@@ -1067,6 +1071,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {branch,worktree_path AS "worktreePath",linked_pull_request_json AS "linkedPullRequest",+ branch_pull_request_json AS "branchPullRequest",latest_turn_id AS "latestTurnId",created_at AS "createdAt",updated_at AS "updatedAt",@@ -2062,6 +2067,7 @@ pending_approval_requests AS (interactionMode: row.interactionMode,branch: row.branch,worktreePath: row.worktreePath,+ branchPullRequest: row.branchPullRequest,...(row.linkedPullRequest === null? {}: { linkedPullRequest: row.linkedPullRequest }),@@ -2275,6 +2281,7 @@ pending_approval_requests AS (interactionMode: row.interactionMode,branch: row.branch,worktreePath: row.worktreePath,+ branchPullRequest: row.branchPullRequest,...(row.linkedPullRequest === null? {}: { linkedPullRequest: row.linkedPullRequest }),@@ -2415,6 +2422,7 @@ pending_approval_requests AS (interactionMode: row.interactionMode,branch: row.branch,worktreePath: row.worktreePath,+ branchPullRequest: row.branchPullRequest,...(row.linkedPullRequest === null? {}: { linkedPullRequest: row.linkedPullRequest }),@@ -2563,6 +2571,7 @@ pending_approval_requests AS (interactionMode: row.interactionMode,branch: row.branch,worktreePath: row.worktreePath,+ branchPullRequest: row.branchPullRequest,...(row.linkedPullRequest === null? {}: { linkedPullRequest: row.linkedPullRequest }),@@ -2884,6 +2893,7 @@ pending_approval_requests AS (interactionMode: threadRow.value.interactionMode,branch: threadRow.value.branch,worktreePath: threadRow.value.worktreePath,+ branchPullRequest: threadRow.value.branchPullRequest,...(threadRow.value.linkedPullRequest === null? {}: { linkedPullRequest: threadRow.value.linkedPullRequest }),@@ -3165,6 +3175,7 @@ pending_approval_requests AS (interactionMode: threadRow.value.interactionMode,branch: threadRow.value.branch,worktreePath: threadRow.value.worktreePath,+ branchPullRequest: threadRow.value.branchPullRequest,...(threadRow.value.linkedPullRequest === null? {}: { linkedPullRequest: threadRow.value.linkedPullRequest }),diff --git a/apps/server/src/orchestration/ThreadPullRequestReactor.test.ts b/apps/server/src/orchestration/ThreadPullRequestReactor.test.tsnew file mode 100644index 00000000000..f9872e6dd22--- /dev/null+++ b/apps/server/src/orchestration/ThreadPullRequestReactor.test.ts@@ -0,0 +1,613 @@+import {+ EventId,+ GitManagerError,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ type OrchestrationCommand,+ type OrchestrationEvent,+ type OrchestrationProjectShell,+ type OrchestrationShellSnapshot,+ type OrchestrationThreadShell,+ type PullRequestRef,+ type PullRequestSummary,+ type ThreadLinkedPullRequest,+} from "@t3tools/contracts";+import { describe, expect, it } from "@effect/vitest";+import * as Crypto from "effect/Crypto";+import * as Deferred from "effect/Deferred";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as PubSub from "effect/PubSub";+import * as Queue from "effect/Queue";+import * as Ref from "effect/Ref";+import * as Stream from "effect/Stream";+import { TestClock } from "effect/testing";++import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";+import { PullRequestService } from "../pullRequest/PullRequestService.ts";+import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";+import { ServerActivation } from "../serverActivation.ts";+import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";+import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";+import * as ThreadPullRequestReactor from "./ThreadPullRequestReactor.ts";++const NOW = "2026-09-01T12:00:00.000Z";+const PROJECT_ID = ProjectId.make("project");+const REPOSITORY = "owner/repository";+const REPOSITORY_KEY = `github.com/${REPOSITORY}`;+type SyncCommand = Extract<OrchestrationCommand, { type: "thread.pull-request.sync" }>;++function reference(number: number): ThreadLinkedPullRequest {+ return {+ projectId: PROJECT_ID,+ repository: REPOSITORY,+ number,+ url: `https://github.com/${REPOSITORY}/pull/${number}`,+ };+}++function branchPullRequest(+ number = 42,+ state: GitBranchPullRequest["state"] = "open",+): GitBranchPullRequest {+ return {+ ...reference(number),+ title: "Branch pull request",+ baseRef: "main",+ headRef: "feature",+ state,+ updatedAt: NOW,+ repositoryKey: REPOSITORY_KEY,+ };+}++function summary(input: PullRequestRef, state: PullRequestSummary["state"]): PullRequestSummary {+ return {+ ...input,+ provider: "github",+ title: "Pull request",+ url: reference(input.number).url,+ state,+ headBranch: "feature",+ baseBranch: "main",+ updatedAt: NOW,+ };+}++function thread(+ id: string,+ overrides: Partial<OrchestrationThreadShell> = {},+): OrchestrationThreadShell {+ return {+ id: ThreadId.make(id),+ projectId: PROJECT_ID,+ title: id,+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: "feature",+ worktreePath: null,+ latestTurn: null,+ createdAt: NOW,+ updatedAt: NOW,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ session: null,+ latestUserMessageAt: NOW,+ hasPendingApprovals: false,+ hasPendingUserInput: false,+ hasActionableProposedPlan: false,+ ...overrides,+ };+}++const project = {+ id: PROJECT_ID,+ title: "Project",+ workspaceRoot: "/workspace/project",+ repositoryIdentity: {+ canonicalKey: REPOSITORY_KEY,+ displayName: REPOSITORY,+ rootPath: "/workspace/project",+ locator: {+ source: "git-remote",+ remoteName: "origin",+ remoteUrl: `[email protected]:${REPOSITORY}.git`,+ },+ },+ defaultModelSelection: null,+ scripts: [],+ createdAt: NOW,+ updatedAt: NOW,+} satisfies OrchestrationProjectShell;++const makeHarness = Effect.fn("makeThreadPullRequestHarness")(function* (options: {+ readonly threads: ReadonlyArray<OrchestrationThreadShell>;+ readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];+ readonly summary?: PullRequestService["Service"]["summary"];+ readonly existingWorktrees?: ReadonlyArray<string>;+ readonly project?: OrchestrationProjectShell;+ readonly resolveRepositoryIdentity?: RepositoryIdentityResolver["Service"]["resolve"];+}) {+ const activation = yield* Deferred.make<void>();+ const snapshots = yield* Ref.make<OrchestrationShellSnapshot>({+ snapshotSequence: 1,+ projects: [options.project ?? project],+ threads: options.threads,+ updatedAt: NOW,+ });+ const reads = yield* Queue.unbounded<void>();+ const events = yield* PubSub.unbounded<OrchestrationEvent>();+ const commands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);+ const branchCalls = yield* Ref.make<+ ReadonlyArray<{ readonly cwd: string; readonly branch: string; readonly refresh: boolean }>+ >([]);+ const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);+ let uuid = 0;+ const dependencies = Layer.mergeAll(+ Layer.mock(ProjectionSnapshotQuery)({+ getShellSnapshot: () =>+ Ref.get(snapshots).pipe(Effect.tap(() => Queue.offer(reads, undefined))),+ }),+ Layer.mock(GitManager)({+ branchPullRequest: (input, readOptions) =>+ Ref.update(branchCalls, (calls) => [+ ...calls,+ { ...input, refresh: readOptions?.refresh === true },+ ]).pipe(+ Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),+ ),+ }),+ Layer.mock(PullRequestService)({+ summary: (input, readOptions) =>+ Ref.update(summaryCalls, (calls) => [...calls, input]).pipe(+ Effect.andThen(+ options.summary?.(input, readOptions) ?? Effect.succeed(summary(input, "open")),+ ),+ ),+ }),+ Layer.mock(RepositoryIdentityResolver)({+ resolve:+ options.resolveRepositoryIdentity ??+ (() => Effect.succeed(options.project?.repositoryIdentity ?? project.repositoryIdentity)),+ }),+ Layer.mock(OrchestrationEngineService)({+ subscribeDomainEvents: PubSub.subscribe(events).pipe(+ Effect.map((subscription) => Stream.fromSubscription(subscription)),+ ),+ dispatch: (command) => {+ if (command.type !== "thread.pull-request.sync") {+ return Effect.die(`Unexpected command: ${command.type}`);+ }+ return Ref.update(commands, (current) => [...current, command]).pipe(+ Effect.andThen(+ Ref.updateAndGet(snapshots, (snapshot) => ({+ ...snapshot,+ snapshotSequence: snapshot.snapshotSequence + 1,+ threads: snapshot.threads.map((current) =>+ current.id === command.threadId+ ? {+ ...current,+ branchPullRequest: command.branchPullRequest,+ ...(command.linkedPullRequest !== undefined+ ? { linkedPullRequest: command.linkedPullRequest }+ : {}),+ }+ : current,+ ),+ })),+ ),+ Effect.map((snapshot) => ({ sequence: snapshot.snapshotSequence })),+ );+ },+ }),+ Layer.succeed(ServerActivation, Deferred.await(activation)),+ Layer.succeed(+ Crypto.Crypto,+ Crypto.make({+ randomBytes: (size) => new Uint8Array(size).fill(++uuid),+ digest: (_algorithm, data) => Effect.succeed(data),+ }),+ ),+ FileSystem.layerNoop({+ exists: (path) => Effect.succeed(options.existingWorktrees?.includes(path) ?? false),+ }),+ );++ const start = Effect.fn("startThreadPullRequestHarness")(function* () {+ const reactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;+ yield* reactor.start();+ yield* Deferred.succeed(activation, undefined);+ yield* Queue.take(reads);+ yield* reactor.drain;+ return reactor;+ });++ return {+ start,+ reads,+ snapshots,+ commands,+ branchCalls,+ summaryCalls,+ publish: (event: OrchestrationEvent) => PubSub.publish(events, event),+ layer: ThreadPullRequestReactor.layer.pipe(Layer.provide(dependencies)),+ };+});++describe("ThreadPullRequestReactor", () => {+ it.effect("discovers saved branch PRs without a client and shares branch lookups", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ threads: [+ thread("first"),+ thread("second"),+ thread("archived", { archivedAt: NOW }),+ thread("no-branch", { branch: null }),+ ],+ branchPullRequest: () => Effect.succeed(branchPullRequest()),+ });+ yield* Effect.gen(function* () {+ const reactor = yield* fixture.start();+ expect(yield* Ref.get(fixture.branchCalls)).toEqual([+ { cwd: project.workspaceRoot, branch: "feature", refresh: false },+ { cwd: project.workspaceRoot, branch: "feature", refresh: false },+ ]);+ expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([+ "first",+ "second",+ ]);+ expect((yield* Ref.get(fixture.snapshots)).threads[0]?.branchPullRequest).toEqual(+ reference(42),+ );++ yield* TestClock.adjust("1 minute");+ yield* Queue.take(fixture.reads);+ yield* reactor.drain;+ expect(yield* Ref.get(fixture.commands)).toHaveLength(2);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("replaces terminal manual links but preserves open links and explicit unlink", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ threads: [+ thread("merged", { linkedPullRequest: reference(1) }),+ thread("closed", { linkedPullRequest: reference(2) }),+ thread("open", { linkedPullRequest: reference(3) }),+ thread("unlinked", { linkedPullRequest: null }),+ ],+ branchPullRequest: () => Effect.succeed(branchPullRequest()),+ summary: (input) =>+ Effect.succeed(+ summary(+ input,+ input.number === 1 ? "merged" : input.number === 2 ? "closed" : "open",+ ),+ ),+ });+ yield* Effect.gen(function* () {+ yield* fixture.start();+ const snapshot = yield* Ref.get(fixture.snapshots);+ expect(snapshot.threads.map((current) => current.linkedPullRequest)).toEqual([+ reference(42),+ reference(42),+ reference(3),+ null,+ ]);+ expect(+ snapshot.threads.every((current) => current.branchPullRequest?.number === 42),+ ).toBe(true);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("refreshes discovery after a turn ends without client demand", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const current = thread("turn-thread");+ const detected = yield* Ref.make<GitBranchPullRequest | null>(null);+ const fixture = yield* makeHarness({+ threads: [current],+ branchPullRequest: (_input, options) =>+ options?.refresh+ ? Ref.set(detected, branchPullRequest()).pipe(Effect.andThen(Ref.get(detected)))+ : Ref.get(detected),+ });+ yield* Effect.gen(function* () {+ const reactor = yield* fixture.start();+ expect(yield* Ref.get(fixture.commands)).toHaveLength(0);+ yield* fixture.publish({+ type: "thread.session-set",+ sequence: 2,+ eventId: EventId.make("turn-finished"),+ aggregateKind: "thread",+ aggregateId: current.id,+ occurredAt: NOW,+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ payload: {+ threadId: current.id,+ session: {+ threadId: current.id,+ status: "ready",+ providerName: "Codex",+ runtimeMode: "full-access",+ activeTurnId: null,+ lastError: null,+ updatedAt: NOW,+ },+ },+ });+ yield* Queue.take(fixture.reads);+ yield* reactor.drain;+ expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual(reference(42));+ expect((yield* Ref.get(fixture.branchCalls)).filter((call) => call.refresh)).toHaveLength(+ 1,+ );+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("uses live worktrees and falls back to the project for removed worktrees", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ threads: [+ thread("live", { worktreePath: "/workspace/worktree" }),+ thread("removed", { worktreePath: "/workspace/removed" }),+ ],+ existingWorktrees: ["/workspace/worktree"],+ branchPullRequest: () => Effect.succeed(branchPullRequest()),+ });+ yield* Effect.gen(function* () {+ yield* fixture.start();+ expect(new Set((yield* Ref.get(fixture.branchCalls)).map((call) => call.cwd))).toEqual(+ new Set(["/workspace/project", "/workspace/worktree"]),+ );+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("retains only terminal PRs on shared checkouts and clears a removed branch", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ threads: [+ thread("terminal", { branch: "main", branchPullRequest: reference(1) }),+ thread("open", { branchPullRequest: reference(2) }),+ thread("worktree", {+ worktreePath: "/workspace/worktree",+ branchPullRequest: reference(1),+ }),+ thread("cleared", {+ branch: null,+ branchPullRequest: reference(1),+ linkedPullRequest: reference(3),+ }),+ ],+ summary: (input) =>+ Effect.succeed(summary(input, input.number === 1 ? "merged" : "open")),+ });+ yield* Effect.gen(function* () {+ yield* fixture.start();+ const snapshot = yield* Ref.get(fixture.snapshots);+ expect(snapshot.threads.map((current) => current.branchPullRequest)).toEqual([+ reference(1),+ null,+ null,+ null,+ ]);+ expect(snapshot.threads[3]?.linkedPullRequest).toEqual(reference(3));+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("keeps saved links on lookup failures and rejects a different repository", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ threads: [+ thread("failed", { branch: "failed", branchPullRequest: reference(1) }),+ thread("wrong-repository", {+ branch: "wrong-repository",+ branchPullRequest: reference(2),+ }),+ thread("healthy"),+ ],+ branchPullRequest: ({ cwd, branch }) =>+ branch === "failed"+ ? Effect.fail(+ new GitManagerError({+ operation: "branchPullRequest",+ cwd,+ detail: "Lookup failed",+ }),+ )+ : Effect.succeed({+ ...branchPullRequest(),+ repositoryKey:+ branch === "wrong-repository" ? "github.com/other/repository" : REPOSITORY_KEY,+ }),+ });+ yield* Effect.gen(function* () {+ yield* fixture.start();+ expect(+ (yield* Ref.get(fixture.snapshots)).threads.map((current) => current.branchPullRequest),+ ).toEqual([reference(1), reference(2), reference(42)]);+ expect(yield* Ref.get(fixture.commands)).toHaveLength(1);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("retries failed settled backfills and stops querying them after success", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const online = yield* Ref.make(false);+ const fixture = yield* makeHarness({+ threads: [+ thread("backfill", { settledOverride: "settled", settledAt: NOW }),+ thread("known", {+ branch: "known",+ settledOverride: "settled",+ settledAt: NOW,+ branchPullRequest: reference(1),+ }),+ ],+ branchPullRequest: ({ cwd }) =>+ Ref.get(online).pipe(+ Effect.flatMap((connected) =>+ connected+ ? Effect.succeed(branchPullRequest(42, "merged"))+ : Effect.fail(+ new GitManagerError({+ operation: "branchPullRequest",+ cwd,+ detail: "Offline",+ }),+ ),+ ),+ ),+ });+ yield* Effect.gen(function* () {+ const reactor = yield* fixture.start();+ expect(yield* Ref.get(fixture.commands)).toHaveLength(0);+ yield* Ref.set(online, true);+ yield* TestClock.adjust("1 minute");+ yield* Queue.take(fixture.reads);+ yield* reactor.drain;+ expect((yield* Ref.get(fixture.commands))[0]?.threadId).toBe("backfill");+ yield* TestClock.adjust("1 minute");+ yield* Queue.take(fixture.reads);+ yield* reactor.drain;+ expect((yield* Ref.get(fixture.branchCalls)).map((call) => call.branch)).toEqual([+ "feature",+ "feature",+ "feature",+ ]);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("stops retrying a settled backfill after repeated lookup failures", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ threads: [thread("backfill", { settledOverride: "settled", settledAt: NOW })],+ branchPullRequest: ({ cwd }) =>+ Effect.fail(+ new GitManagerError({ operation: "branchPullRequest", cwd, detail: "No gh" }),+ ),+ });+ yield* Effect.gen(function* () {+ const reactor = yield* fixture.start();+ for (+ let attempt = 1;+ attempt < ThreadPullRequestReactor.BACKFILL_ATTEMPTS + 2;+ attempt+++ ) {+ yield* TestClock.adjust("1 minute");+ yield* Queue.take(fixture.reads);+ yield* reactor.drain;+ }+ expect(yield* Ref.get(fixture.branchCalls)).toHaveLength(+ ThreadPullRequestReactor.BACKFILL_ATTEMPTS,+ );+ expect(yield* Ref.get(fixture.commands)).toHaveLength(0);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("matches Azure SSH projects to HTTPS PRs with the provider repository selector", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ threads: [thread("azure")],+ project: {+ ...project,+ repositoryIdentity: {+ canonicalKey: "ssh.dev.azure.com/v3/org/project/repository",+ displayName: "v3/org/project/repository",+ name: "repository",+ provider: "azure-devops",+ rootPath: project.workspaceRoot,+ locator: {+ source: "git-remote",+ remoteName: "origin",+ remoteUrl: "[email protected]:v3/org/project/repository",+ },+ },+ },+ branchPullRequest: () =>+ Effect.succeed({+ ...branchPullRequest(),+ repositoryKey: "dev.azure.com/org/project/_git/repository",+ url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",+ }),+ });+ yield* Effect.gen(function* () {+ yield* fixture.start();+ expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual({+ projectId: PROJECT_ID,+ repository: "repository",+ number: 42,+ url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",+ });+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect.each(["primary", "branch"] as const)(+ "rejects the group's links if the %s remote changes during a summary read",+ (changedRemote) =>+ Effect.scoped(+ Effect.gen(function* () {+ const identity = yield* Ref.make(project.repositoryIdentity);+ const detected = yield* Ref.make(branchPullRequest());+ const fixture = yield* makeHarness({+ threads: [thread("manual", { linkedPullRequest: reference(1) }), thread("automatic")],+ branchPullRequest: () => Ref.get(detected),+ resolveRepositoryIdentity: (_cwd, options) =>+ options?.refresh ? Ref.get(identity) : Effect.succeed(project.repositoryIdentity),+ summary: (input) =>+ (changedRemote === "primary"+ ? Ref.set(identity, {+ ...project.repositoryIdentity,+ canonicalKey: "github.com/other/repository",+ displayName: "other/repository",+ })+ : Ref.set(detected, {+ ...branchPullRequest(99),+ repositoryKey: "github.com/other/repository",+ url: "https://github.com/other/repository/pull/99",+ })+ ).pipe(Effect.as(summary(input, "merged"))),+ });+ yield* Effect.gen(function* () {+ yield* fixture.start();+ expect(yield* Ref.get(fixture.commands)).toEqual([]);+ expect((yield* Ref.get(fixture.snapshots)).threads[0]?.linkedPullRequest).toEqual(+ reference(1),+ );+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );+});diff --git a/apps/server/src/orchestration/ThreadPullRequestReactor.ts b/apps/server/src/orchestration/ThreadPullRequestReactor.tsnew file mode 100644index 00000000000..6e2aa0b3e05--- /dev/null+++ b/apps/server/src/orchestration/ThreadPullRequestReactor.ts@@ -0,0 +1,371 @@+import {+ CommandId,+ type OrchestrationEvent,+ type OrchestrationProjectShell,+ type ThreadId,+ type ThreadLinkedPullRequest,+} from "@t3tools/contracts";+import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";+import * as Cause from "effect/Cause";+import * as Context from "effect/Context";+import * as Crypto from "effect/Crypto";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Schedule from "effect/Schedule";+import type * as Scope from "effect/Scope";+import * as Stream from "effect/Stream";++import * as GitManager from "../git/GitManager.ts";+import * as PullRequestService from "../pullRequest/PullRequestService.ts";+import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";+import { forkParked } from "../serverActivation.ts";+import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";+import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";++export class ThreadPullRequestReactor extends Context.Service<+ ThreadPullRequestReactor,+ {+ readonly start: () => Effect.Effect<void, never, Scope.Scope>;+ readonly drain: Effect.Effect<void>;+ }+>()("t3/orchestration/ThreadPullRequestReactor") {}++function samePullRequest(+ left: ThreadLinkedPullRequest | null | undefined,+ right: ThreadLinkedPullRequest | null,+): boolean {+ if (left == null || right === null) return left == null && right === null;+ return (+ left.projectId === right.projectId &&+ left.repository.toLowerCase() === right.repository.toLowerCase() &&+ left.number === right.number &&+ left.url === right.url+ );+}++/** Startup lookups per settled thread before discovery gives up on it. */+export const BACKFILL_ATTEMPTS = 5;++interface RefreshRequest {+ readonly threadId: ThreadId | null;+ readonly refresh: boolean;+ readonly backfill?: boolean;+}++function canonicalRepositoryKey(key: string): string {+ return key+ .replace(+ /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,+ "dev.azure.com/$1/$2/_git/$3",+ )+ .replace(+ /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,+ "dev.azure.com/$1/$2/_git/$3",+ );+}++export function pullRequestMatchesProject(+ pullRequest: GitManager.GitBranchPullRequest,+ project: OrchestrationProjectShell,+): boolean {+ return (+ pullRequest.repositoryKey !== null &&+ project.repositoryIdentity != null &&+ canonicalRepositoryKey(pullRequest.repositoryKey) ===+ canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)+ );+}++export const make = Effect.gen(function* () {+ const engine = yield* OrchestrationEngine.OrchestrationEngineService;+ const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;+ const git = yield* GitManager.GitManager;+ const pullRequests = yield* PullRequestService.PullRequestService;+ const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;+ const crypto = yield* Crypto.Crypto;+ const fileSystem = yield* FileSystem.FileSystem;+ // Settled threads get one link discovery at startup. Failed lookups retry on+ // the periodic pass a few times, then stop until the thread changes or the+ // server restarts, so a missing or logged-out CLI cannot loop forever.+ const pendingBackfill = new Map<ThreadId, number>();+ const finishBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {+ for (const thread of threads) pendingBackfill.delete(thread.id);+ };+ const failBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {+ for (const thread of threads) {+ const remaining = pendingBackfill.get(thread.id);+ if (remaining === undefined) continue;+ if (remaining <= 1) pendingBackfill.delete(thread.id);+ else pendingBackfill.set(thread.id, remaining - 1);+ }+ };++ const synchronize = Effect.fn("ThreadPullRequestReactor.synchronize")(function* (+ request: RefreshRequest,+ ) {+ const snapshot = yield* snapshots.getShellSnapshot();+ const projects = new Map(snapshot.projects.map((project) => [project.id, project]));+ if (request.backfill) {+ for (const thread of snapshot.threads) {+ if (thread.settledOverride === "settled" && thread.branchPullRequest == null) {+ pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);+ }+ }+ }+ const threadIds = new Set(snapshot.threads.map((thread) => thread.id));+ for (const threadId of pendingBackfill.keys()) {+ if (!threadIds.has(threadId)) pendingBackfill.delete(threadId);+ }+ const threads = snapshot.threads.filter(+ (thread) =>+ thread.archivedAt === null &&+ (request.threadId === null || thread.id === request.threadId) &&+ (thread.settledOverride !== "settled" ||+ request.threadId !== null ||+ pendingBackfill.has(thread.id)) &&+ (thread.branch !== null || thread.branchPullRequest != null),+ );+ const groups = Map.groupBy(threads, (thread) =>+ JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),+ );++ yield* Effect.forEach(+ groups.values(),+ (group) =>+ Effect.gen(function* () {+ const first = group[0]!;+ const project = projects.get(first.projectId);+ if (project === undefined) return finishBackfill(group);+ const repository = PullRequestService.repositoryIdentityOf(project);+ if (first.branch !== null && repository === null) return finishBackfill(group);+ const worktreeExists =+ first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));+ const cwd =+ worktreeExists && first.worktreePath !== null+ ? first.worktreePath+ : project.workspaceRoot;+ const detected =+ first.branch === null+ ? null+ : yield* git.branchPullRequest(+ { cwd, branch: first.branch },+ { refresh: request.refresh },+ );+ // A worktree can have different remotes, and the project identity+ // can lag a remote edit. Do not attach its PR to the wrong repository.+ if (detected !== null && !pullRequestMatchesProject(detected, project)) {+ return finishBackfill(group);+ }+ const detectedReference =+ detected !== null && repository !== null+ ? {+ projectId: project.id,+ repository,+ number: detected.number,+ url: detected.url,+ }+ : null;++ const plans = yield* Effect.forEach(group, (thread) =>+ Effect.gen(function* () {+ let branchPullRequest = detectedReference;+ // Shared checkouts often return to the default branch after+ // a merge. Keep that thread's terminal PR across the change.+ if (+ branchPullRequest === null &&+ thread.branch !== null &&+ thread.worktreePath === null &&+ thread.branchPullRequest != null+ ) {+ const previous = yield* pullRequests.summary(thread.branchPullRequest, {+ recoverTransientFailure: false,+ });+ if (previous.state === "merged" || previous.state === "closed") {+ branchPullRequest = thread.branchPullRequest;+ }+ }++ let replacement: ThreadLinkedPullRequest | undefined;+ if (+ thread.linkedPullRequest != null &&+ detected?.state === "open" &&+ detectedReference !== null &&+ !samePullRequest(thread.linkedPullRequest, detectedReference)+ ) {+ const linked = yield* pullRequests.summary(thread.linkedPullRequest, {+ recoverTransientFailure: false,+ });+ if (linked.state === "merged" || linked.state === "closed") {+ replacement = detectedReference;+ }+ }++ if (+ samePullRequest(thread.branchPullRequest, branchPullRequest) &&+ replacement === undefined+ ) {+ pendingBackfill.delete(thread.id);+ return null;+ }+ return { thread, branchPullRequest, replacement };+ }).pipe(+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause)+ ? Effect.failCause(cause)+ : Effect.logWarning("thread pull request discovery failed", {+ threadId: thread.id,+ cause: Cause.pretty(cause),+ }).pipe(+ Effect.tap(() => Effect.sync(() => failBackfill([thread]))),+ Effect.as(null),+ ),+ ),+ ),+ );+ const updates = plans.filter((plan) => plan !== null);+ if (updates.length === 0) return;++ if (detected !== null && first.branch !== null) {+ // Summary reads can outlast a remote edit. Recheck the branch and+ // the project's primary remote before saving the group's links.+ const current = yield* git.branchPullRequest({ cwd, branch: first.branch });+ const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {+ refresh: true,+ });+ if (+ current === null ||+ current.number !== detected.number ||+ current.url !== detected.url ||+ current.state !== detected.state ||+ current.repositoryKey !== detected.repositoryKey ||+ !pullRequestMatchesProject(current, {+ ...project,+ repositoryIdentity: currentIdentity,+ })+ ) {+ return failBackfill(updates.map((update) => update.thread));+ }+ }++ yield* Effect.forEach(+ updates,+ ({ thread, branchPullRequest, replacement }) =>+ Effect.gen(function* () {+ const uuid = yield* crypto.randomUUIDv4;+ yield* engine.dispatch({+ type: "thread.pull-request.sync",+ commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),+ threadId: thread.id,+ projectId: project.id,+ snapshotSequence: snapshot.snapshotSequence,+ expected: {+ workspaceRoot: project.workspaceRoot,+ branch: thread.branch,+ worktreePath: thread.worktreePath,+ linkedPullRequest: thread.linkedPullRequest ?? null,+ branchPullRequest: thread.branchPullRequest ?? null,+ },+ branchPullRequest,+ ...(replacement !== undefined ? { linkedPullRequest: replacement } : {}),+ });+ pendingBackfill.delete(thread.id);+ }).pipe(+ // The thread changed since the lookup. Its own events requeue it.+ Effect.catchTags({+ OrchestrationCommandInvariantError: () =>+ Effect.sync(() => finishBackfill([thread])),+ }),+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause)+ ? Effect.failCause(cause)+ : Effect.logWarning("thread pull request update failed", {+ threadId: thread.id,+ cause: Cause.pretty(cause),+ }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),+ ),+ ),+ { discard: true },+ );+ }).pipe(+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause)+ ? Effect.failCause(cause)+ : Effect.logWarning("thread branch pull request lookup failed", {+ threadIds: group.map((thread) => thread.id),+ cause: Cause.pretty(cause),+ }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),+ ),+ ),+ { concurrency: 8, discard: true },+ );+ });++ const worker = yield* makeDrainableWorker((request: RefreshRequest) =>+ synchronize(request).pipe(+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause)+ ? Effect.failCause(cause)+ : Effect.logWarning("thread pull request refresh failed", {+ cause: Cause.pretty(cause),+ }),+ ),+ ),+ );++ const processEvent = (event: OrchestrationEvent) => {+ switch (event.type) {+ case "thread.created":+ case "thread.unarchived":+ return worker.enqueue({ threadId: event.payload.threadId, refresh: false });+ case "thread.meta-updated":+ if (+ event.payload.branchPullRequest === undefined &&+ (event.payload.branch !== undefined ||+ event.payload.worktreePath !== undefined ||+ event.payload.linkedPullRequest !== undefined)+ ) {+ return worker.enqueue({ threadId: event.payload.threadId, refresh: false });+ }+ break;+ case "thread.session-set":+ if (+ event.payload.session.status !== "running" &&+ event.payload.session.status !== "starting"+ ) {+ return worker.enqueue({ threadId: event.payload.threadId, refresh: true });+ }+ break;+ case "thread.turn-diff-completed":+ case "thread.unsettled":+ return worker.enqueue({ threadId: event.payload.threadId, refresh: true });+ case "project.meta-updated":+ if (event.payload.workspaceRoot !== undefined) {+ return worker.enqueue({ threadId: null, refresh: false });+ }+ break;+ }+ return Effect.void;+ };++ const start = Effect.fn("ThreadPullRequestReactor.start")(function* () {+ const events = yield* engine.subscribeDomainEvents;+ yield* forkParked(Stream.runForEach(events, processEvent));+ // Run without client demand. Saved branch lookups share GitManager's+ // provider cache and retry backoff with status and automatic settlement.+ yield* forkParked(+ Effect.gen(function* () {+ yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });+ yield* worker.drain;+ yield* Effect.gen(function* () {+ yield* worker.enqueue({ threadId: null, refresh: false });+ yield* worker.drain;+ }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));+ }).pipe(Effect.asVoid),+ );+ });++ return { start, drain: worker.drain } satisfies ThreadPullRequestReactor["Service"];+});++export const layer = Layer.effect(ThreadPullRequestReactor, make);diff --git a/apps/server/src/orchestration/ThreadSettlementReactor.test.ts b/apps/server/src/orchestration/ThreadSettlementReactor.test.tsindex 50cabe90c1d..f2038bfe689 100644--- a/apps/server/src/orchestration/ThreadSettlementReactor.test.ts+++ b/apps/server/src/orchestration/ThreadSettlementReactor.test.ts@@ -25,7 +25,7 @@ import * as Ref from "effect/Ref";import * as Stream from "effect/Stream";import { TestClock } from "effect/testing";-import { GitManager } from "../git/GitManager.ts";+import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";import {PullRequestService,type PullRequestMergeEvent,@@ -132,6 +132,24 @@ function makePullRequestSummary(input: {};}+function makeBranchPullRequest(+ state: GitBranchPullRequest["state"],+ updatedAt: string | null = NOW,+): GitBranchPullRequest {+ return {+ number: 42,+ title: "Branch pull request",+ url: "https://example.test/owner/repository/pull/42",+ baseRef: "main",+ headRef: "saved-feature",+ repositoryKey: "example.test/owner/repository",+ state,+ updatedAt,+ closedAt: state === "closed" ? updatedAt : null,+ mergedAt: state === "merged" ? updatedAt : null,+ };+}+interface HarnessOptions {readonly snapshot: OrchestrationShellSnapshot;readonly settings?: ServerSettings;@@ -173,9 +191,9 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:return next;});- const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input) =>+ const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input, readOptions) =>Ref.update(branchCalls, (calls) => [...calls, input]).pipe(- Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),+ Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),);const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>Effect.gen(function* () {@@ -281,6 +299,83 @@ const startHarness = Effect.fn("startThreadSettlementHarness")(function* (});describe("ThreadSettlementReactor", () => {+ it.effect("uses saved PRs without settling resumed threads or branches with newer PRs", () =>+ Effect.scoped(+ Effect.gen(function* () {+ yield* TestClock.setTime(Date.parse(NOW));+ const previous = {+ projectId: PROJECT_ID,+ repository: "owner/repository",+ number: 1,+ url: "https://example.test/owner/repository/pull/1",+ };+ const project = {+ ...makeProject(),+ repositoryIdentity: {+ canonicalKey: "example.test/owner/repository",+ rootPath: "/workspace/project",+ displayName: "owner/repository",+ locator: {+ source: "git-remote" as const,+ remoteName: "origin",+ remoteUrl: "https://example.test/owner/repository.git",+ },+ },+ };+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot(+ [+ makeThread("retained-terminal", { branch: "main", branchPullRequest: previous }),+ makeThread("reused-manual", { branch: "reused", linkedPullRequest: previous }),+ makeThread("reused-detected", { branch: "reused", branchPullRequest: previous }),+ makeThread("foreign-branch-pr", { branch: "foreign", linkedPullRequest: previous }),+ makeThread("resumed-manual", {+ branch: "main",+ linkedPullRequest: previous,+ latestUserMessageAt: "2026-08-28T00:00:00.000Z",+ }),+ makeThread("resumed-detected", {+ branch: "main",+ branchPullRequest: previous,+ latestUserMessageAt: "2026-08-28T00:00:00.000Z",+ }),+ ],+ [project],+ ),+ settings: {+ ...DEFAULT_SERVER_SETTINGS,+ sidebarAutoSettleAfterDays: null,+ sidebarAutoSettleOnMerge: true,+ },+ branchPullRequest: ({ branch }, options) =>+ Effect.succeed(+ branch === "reused"+ ? makeBranchPullRequest(options?.refresh ? "open" : "merged")+ : branch === "foreign"+ ? {+ ...makeBranchPullRequest("open"),+ repositoryKey: "example.test/another/repository",+ }+ : null,+ ),+ pullRequestSummary: (input) =>+ Effect.succeed({+ ...makePullRequestSummary({ ...input, state: "merged" }),+ mergedAt: "2026-08-27T00:00:00.000Z",+ }),+ });+ yield* Effect.gen(function* () {+ const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);+ assert.deepStrictEqual(+ new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),+ new Set([ThreadId.make("retained-terminal"), ThreadId.make("foreign-branch-pr")]),+ );+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );+it.effect("starts without clients and skips protected threads before pull request lookup", () =>Effect.scoped(Effect.gen(function* () {@@ -375,9 +470,7 @@ describe("ThreadSettlementReactor", () => {}),]),branchPullRequest: () =>- Ref.get(pullRequest).pipe(- Effect.map((state) => ({ state, updatedAt: NOW, closedAt: NOW, mergedAt: NOW })),- ),+ Ref.get(pullRequest).pipe(Effect.map((state) => makeBranchPullRequest(state))),});yield* Effect.gen(function* () {@@ -430,10 +523,10 @@ describe("ThreadSettlementReactor", () => {Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(Effect.flatMap((count) =>count === 1- ? Effect.succeed({ state: "open" as const, updatedAt: NOW })+ ? Effect.succeed(makeBranchPullRequest("open")): Deferred.succeed(periodicLookupStarted, undefined).pipe(Effect.andThen(Deferred.await(releasePeriodicLookup)),- Effect.as({ state: "open" as const, updatedAt: NOW }),+ Effect.as(makeBranchPullRequest("open")),),),),@@ -477,12 +570,7 @@ describe("ThreadSettlementReactor", () => {]),branchPullRequest: () =>Ref.get(state).pipe(- Effect.map((pullRequestState) => ({- state: pullRequestState,- updatedAt: NOW,- closedAt: NOW,- mergedAt: NOW,- })),+ Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),),onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),});@@ -618,12 +706,7 @@ describe("ThreadSettlementReactor", () => {: Effect.void,),Effect.andThen(Ref.get(state)),- Effect.map((pullRequestState) => ({- state: pullRequestState,- updatedAt: NOW,- closedAt: NOW,- mergedAt: NOW,- })),+ Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),),});@@ -896,8 +979,7 @@ describe("ThreadSettlementReactor", () => {makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),],),- branchPullRequest: () =>- Effect.succeed({ state: "closed", updatedAt: NOW, closedAt: NOW }),+ branchPullRequest: () => Effect.succeed(makeBranchPullRequest("closed")),pullRequestSummary: (input) =>Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),});diff --git a/apps/server/src/orchestration/ThreadSettlementReactor.ts b/apps/server/src/orchestration/ThreadSettlementReactor.tsindex 77a6546365f..994830b30a4 100644--- a/apps/server/src/orchestration/ThreadSettlementReactor.ts+++ b/apps/server/src/orchestration/ThreadSettlementReactor.ts@@ -17,6 +17,7 @@ import * as ServerSettings from "../serverSettings.ts";import { forkParked } from "../serverActivation.ts";import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";+import { pullRequestMatchesProject } from "./ThreadPullRequestReactor.ts";import {isAutoSettlementCandidate,resolveAutoSettlementAt,@@ -46,10 +47,8 @@ export const make = Effect.gen(function* () {const snapshot = yield* snapshots.getShellSnapshot();const now = DateTime.formatIso(yield* DateTime.now);const projects = new Map(snapshot.projects.map((project) => [project.id, project]));- // A merge event re-sweeps every candidate, not just the threads linked to- // the merged pull request: most threads carry no link and settle from- // their branch lookup, which would otherwise wait for the next minute's- // sweep on a possibly stale cached answer.+ // A merge rechecks all candidates, including branches that discovery has+ // not linked yet. Those lookups can still have cached the PR as open.const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));// Return the thread when it still needs a pull request decision. A rejected@@ -101,14 +100,14 @@ export const make = Effect.gen(function* () {},)).filter((thread) => thread !== null);- // Use the same cwd as the sidebar so both paths share GitManager's PR cache.+ // Use the same cwd as PR discovery so both paths share GitManager's cache.const lookupCwdByThreadId = new Map<string, string>();yield* Effect.forEach(lookupCandidates,(thread) =>Effect.gen(function* () {const project = projects.get(thread.projectId);- if (project === undefined || thread.linkedPullRequest != null) return;+ if (project === undefined || thread.branch === null) return;const worktreeExists =thread.worktreePath !== null &&(yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));@@ -122,12 +121,8 @@ export const make = Effect.gen(function* () {{ concurrency: 8, discard: true },);if (mergedPullRequest !== null) {- // The merge just confirmed a terminal state the lookup caches can still- // call open (branch answers live two minutes, the sweep runs every- // minute). Drop the swept checkouts' cached answers so the merge settles- // its branch threads now instead of on a later sweep. Threads linked to- // the merged pull request settle from the event itself below and need no- // lookup, so they are absent from this map by construction.+ // The merge confirmed a state the branch cache can still call open.+ // Recheck those branches now instead of waiting for cache expiry.const cwds = [...new Set(lookupCwdByThreadId.values())];yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {concurrency: 8,@@ -135,12 +130,15 @@ export const make = Effect.gen(function* () {});}const lookupKey = (thread: (typeof candidates)[number]) => {- if (thread.linkedPullRequest != null) {+ const reference = thread.linkedPullRequest ?? thread.branchPullRequest;+ if (reference != null) {return JSON.stringify(["linked",- thread.linkedPullRequest.projectId,- thread.linkedPullRequest.repository,- thread.linkedPullRequest.number,+ reference.projectId,+ reference.repository,+ reference.number,+ lookupCwdByThreadId.get(thread.id),+ thread.branch,]);}if (thread.branch === null) return JSON.stringify(["none", thread.id]);@@ -154,35 +152,47 @@ export const make = Effect.gen(function* () {const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (thread: (typeof candidates)[number],) {- if (thread.linkedPullRequest != null) {- // The event carries the merged state, so only the threads linked to- // that exact pull request settle from it. Every other linked thread- // falls through to a fresh summary lookup below: the merge sweep- // covers all candidates, and an unrelated merge must never settle- // them.- if (+ const reference = thread.linkedPullRequest ?? thread.branchPullRequest;+ if (reference != null) {+ const matchesMerge =mergedPullRequest !== null &&- thread.linkedPullRequest.projectId === mergedPullRequest.projectId &&- thread.linkedPullRequest.repository.toLowerCase() ===- mergedPullRequest.repository.toLowerCase() &&- thread.linkedPullRequest.number === mergedPullRequest.number- ) {- return {- state: "merged",- mergedAt: mergedPullRequest.mergedAt,- } satisfies SettlementPullRequest;- }- if (!projects.has(thread.linkedPullRequest.projectId)) {+ reference.projectId === mergedPullRequest.projectId &&+ reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&+ reference.number === mergedPullRequest.number;+ if (!matchesMerge && !projects.has(reference.projectId)) {return yield* Effect.die(new Error("linked pull request project not found"));}- const summary = yield* pullRequests.summary(- {- projectId: thread.linkedPullRequest.projectId,- repository: thread.linkedPullRequest.repository,- number: thread.linkedPullRequest.number,- },- { recoverTransientFailure: false },- );+ const summary = matchesMerge+ ? ({+ state: "merged",+ closedAt: null,+ mergedAt: mergedPullRequest.mergedAt,+ } satisfies SettlementPullRequest)+ : yield* pullRequests.summary(+ {+ projectId: reference.projectId,+ repository: reference.repository,+ number: reference.number,+ },+ { recoverTransientFailure: false },+ );+ const cwd = lookupCwdByThreadId.get(thread.id);+ if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {+ // A reused branch can already have a new open PR while discovery+ // is replacing its old link. Do not let settlement win that race.+ const current = yield* git.branchPullRequest(+ { cwd, branch: thread.branch },+ { refresh: true },+ );+ const project = projects.get(thread.projectId);+ if (+ current?.state === "open" &&+ project !== undefined &&+ pullRequestMatchesProject(current, project)+ ) {+ return current;+ }+ }return {state: summary.state,closedAt: summary.closedAt ?? null,diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex 1fd9feba7c4..a20dba468c6 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -1,6 +1,7 @@import {EventId,MessageId,+ ThreadLinkedPullRequest,UserInputRequestedPayload,isImportedAgentSessionMessageId,type OrchestrationCommand,@@ -38,6 +39,7 @@ import { threadHasQueuedTurnStart } from "./ThreadSettlementPolicy.ts";const nowIso = Effect.map(DateTime.now, DateTime.formatIso);const decodeUserInputRequestedPayload = Schema.decodeUnknownOption(UserInputRequestedPayload);+const threadPullRequestLinksEqual = Schema.toEquivalence(Schema.NullOr(ThreadLinkedPullRequest));/*** Blocked-on-you work derived from the thread's retained activities: an@@ -836,6 +838,63 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"};}+ case "thread.pull-request.sync": {+ const thread = yield* requireThreadNotArchived({+ readModel,+ command,+ threadId: command.threadId,+ });+ if (thread.deletedAt !== null) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `thread ${command.threadId} was deleted before pull request discovery`,+ });+ }+ if (+ thread.projectId !== command.projectId ||+ thread.branch !== command.expected.branch ||+ thread.worktreePath !== command.expected.worktreePath ||+ !threadPullRequestLinksEqual(+ thread.linkedPullRequest ?? null,+ command.expected.linkedPullRequest,+ ) ||+ !threadPullRequestLinksEqual(+ thread.branchPullRequest ?? null,+ command.expected.branchPullRequest,+ )+ ) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `thread ${command.threadId} changed before pull request discovery`,+ });+ }+ const project = yield* requireProject({ readModel, command, projectId: command.projectId });+ if (project.deletedAt !== null || project.workspaceRoot !== command.expected.workspaceRoot) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `project ${command.projectId} changed before pull request discovery`,+ });+ }+ const occurredAt = yield* nowIso;+ return {+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.meta-updated",+ payload: {+ threadId: command.threadId,+ branchPullRequest: command.branchPullRequest,+ ...(command.linkedPullRequest !== undefined+ ? { linkedPullRequest: command.linkedPullRequest }+ : {}),+ updatedAt: thread.updatedAt,+ },+ };+ }+case "thread.title.regeneration.complete": {const thread = yield* requireThread({readModel,diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.tsindex 4b37137936f..d4e1213b2ab 100644--- a/apps/server/src/orchestration/projector.test.ts+++ b/apps/server/src/orchestration/projector.test.ts@@ -86,6 +86,7 @@ describe("orchestration projector", () => {interactionMode: "default",branch: null,worktreePath: null,+ branchPullRequest: null,latestTurn: null,createdAt: now,updatedAt: now,@@ -105,6 +106,67 @@ describe("orchestration projector", () => {]);});+ effectIt.effect("sets and clears branch pull requests without changing manual links", () =>+ Effect.gen(function* () {+ const now = "2026-01-01T00:00:00.000Z";+ const eventFields = {+ aggregateKind: "thread" as const,+ aggregateId: "thread-1",+ occurredAt: now,+ commandId: null,+ };+ let model = yield* projectEvent(+ createEmptyReadModel(now),+ makeEvent({+ ...eventFields,+ sequence: 1,+ type: "thread.created",+ payload: {+ threadId: "thread-1",+ projectId: "project-1",+ title: "Pull request thread",+ modelSelection: { provider: "codex", model: "gpt-5-codex" },+ runtimeMode: "full-access",+ branch: "feature",+ worktreePath: null,+ createdAt: now,+ updatedAt: now,+ },+ }),+ );+ const linkedPullRequest = {+ projectId: "project-1",+ repository: "pingdotgg/t3code",+ number: 42,+ url: "https://github.com/pingdotgg/t3code/pull/42",+ };+ const branchPullRequest = {+ ...linkedPullRequest,+ number: 43,+ url: "https://github.com/pingdotgg/t3code/pull/43",+ };+ const updates = [+ { payload: { linkedPullRequest, branchPullRequest }, expected: branchPullRequest },+ { payload: { title: "Renamed thread" }, expected: branchPullRequest },+ { payload: { branchPullRequest: null }, expected: null },+ ];++ for (const [index, update] of updates.entries()) {+ model = yield* projectEvent(+ model,+ makeEvent({+ ...eventFields,+ sequence: index + 2,+ type: "thread.meta-updated",+ payload: { threadId: "thread-1", updatedAt: now, ...update.payload },+ }),+ );+ expect(model.threads[0]?.branchPullRequest).toEqual(update.expected);+ expect(model.threads[0]?.linkedPullRequest).toEqual(linkedPullRequest);+ }+ }),+ );+it("fails when event payload cannot be decoded by runtime schema", async () => {const now = "2026-01-01T00:00:00.000Z";const model = createEmptyReadModel(now);diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex 77dbe51b954..58c4876905e 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -336,6 +336,7 @@ export function projectEvent(interactionMode: payload.interactionMode,branch: payload.branch,worktreePath: payload.worktreePath,+ branchPullRequest: null,latestTurn: null,createdAt: payload.createdAt,updatedAt: payload.updatedAt,@@ -510,6 +511,9 @@ export function projectEvent(...(payload.linkedPullRequest !== undefined? { linkedPullRequest: payload.linkedPullRequest }: {}),+ ...(payload.branchPullRequest !== undefined+ ? { branchPullRequest: payload.branchPullRequest }+ : {}),updatedAt: payload.updatedAt,}),})),diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.tsindex 2f8285d8c1f..68ceb8573b7 100644--- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts+++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts@@ -462,7 +462,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {}),);- it.effect("round-trips a linked pull request through the thread row", () =>+ it.effect("round-trips manual and branch pull requests through the thread row", () =>Effect.gen(function* () {const threads = yield* ProjectionThreadRepository;const linkedPullRequest = {@@ -471,6 +471,11 @@ projectionRepositoriesLayer("Projection repositories", (it) => {number: 42,url: "https://github.com/pingdotgg/t3code/pull/42",};+ const branchPullRequest = {+ ...linkedPullRequest,+ number: 43,+ url: "https://github.com/pingdotgg/t3code/pull/43",+ };yield* threads.upsert({threadId: ThreadId.make("thread-linked-pr"),@@ -485,6 +490,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {branch: null,worktreePath: null,linkedPullRequest,+ branchPullRequest,latestTurnId: null,createdAt: "2026-03-24T00:00:00.000Z",updatedAt: "2026-03-24T00:00:00.000Z",@@ -504,6 +510,10 @@ projectionRepositoriesLayer("Projection repositories", (it) => {const persisted = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });assert.deepStrictEqual(Option.getOrNull(persisted)?.linkedPullRequest, linkedPullRequest);+ assert.deepStrictEqual(Option.getOrNull(persisted)?.branchPullRequest, branchPullRequest);++ const listed = yield* threads.listByProjectId({ projectId: linkedPullRequest.projectId });+ assert.deepStrictEqual(listed[0]?.branchPullRequest, branchPullRequest);const row = Option.getOrNull(persisted);if (row === null) return yield* Effect.die("Expected linked thread row to exist.");@@ -511,6 +521,12 @@ projectionRepositoriesLayer("Projection repositories", (it) => {const cleared = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });assert.strictEqual(Option.getOrNull(cleared)?.linkedPullRequest, null);+ assert.deepStrictEqual(Option.getOrNull(cleared)?.branchPullRequest, branchPullRequest);++ yield* threads.upsert({ ...row, branchPullRequest: null });+ const branchCleared = yield* threads.getById({ threadId: row.threadId });+ assert.strictEqual(Option.getOrNull(branchCleared)?.branchPullRequest, null);+ assert.deepStrictEqual(Option.getOrNull(branchCleared)?.linkedPullRequest, linkedPullRequest);}),);});diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.tsindex d5653a2c8b4..79938684541 100644--- a/apps/server/src/persistence/Layers/ProjectionThreads.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts@@ -20,6 +20,7 @@ const ProjectionThreadDbRow = ProjectionThread.mapFields(Struct.assign({modelSelection: Schema.fromJsonString(ModelSelection),linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),+ branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),}),);type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;@@ -41,6 +42,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {branch,worktree_path,linked_pull_request_json,+ branch_pull_request_json,latest_turn_id,created_at,updated_at,@@ -70,6 +72,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {${row.branch},${row.worktreePath},${row.linkedPullRequest === undefined || row.linkedPullRequest === null ? null : JSON.stringify(row.linkedPullRequest)},+ ${row.branchPullRequest === undefined || row.branchPullRequest === null ? null : JSON.stringify(row.branchPullRequest)},${row.latestTurnId},${row.createdAt},${row.updatedAt},@@ -99,6 +102,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {branch = excluded.branch,worktree_path = excluded.worktree_path,linked_pull_request_json = excluded.linked_pull_request_json,+ branch_pull_request_json = excluded.branch_pull_request_json,latest_turn_id = excluded.latest_turn_id,created_at = excluded.created_at,updated_at = excluded.updated_at,@@ -135,6 +139,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {branch,worktree_path AS "worktreePath",linked_pull_request_json AS "linkedPullRequest",+ branch_pull_request_json AS "branchPullRequest",latest_turn_id AS "latestTurnId",created_at AS "createdAt",updated_at AS "updatedAt",@@ -173,6 +178,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {branch,worktree_path AS "worktreePath",linked_pull_request_json AS "linkedPullRequest",+ branch_pull_request_json AS "branchPullRequest",latest_turn_id AS "latestTurnId",created_at AS "createdAt",updated_at AS "updatedAt",diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex 92dc1829105..7f89170d29f 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -59,6 +59,7 @@ import Migration0044 from "./Migrations/044_ClearAutomaticProjectModelDefaults.timport Migration0045 from "./Migrations/045_ProjectionProjectsAutoPull.ts";import Migration0046 from "./Migrations/046_RepairAutomaticSettlementTimestamps.ts";import Migration0047 from "./Migrations/047_ProjectionProjectIcon.ts";+import Migration0048 from "./Migrations/048_ProjectionThreadBranchPullRequest.ts";/*** Migration loader with all migrations defined inline.@@ -118,6 +119,7 @@ export const migrationEntries = [[45, "ProjectionProjectsAutoPull", Migration0045],[46, "RepairAutomaticSettlementTimestamps", Migration0046],[47, "ProjectionProjectIcon", Migration0047],+ [48, "ProjectionThreadBranchPullRequest", Migration0048],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/048_ProjectionThreadBranchPullRequest.ts b/apps/server/src/persistence/Migrations/048_ProjectionThreadBranchPullRequest.tsnew file mode 100644index 00000000000..49870b59635--- /dev/null+++ b/apps/server/src/persistence/Migrations/048_ProjectionThreadBranchPullRequest.ts@@ -0,0 +1,16 @@+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/unstable/sql/SqlClient";++export default Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const columns = yield* sql<{ readonly name: string }>`+ PRAGMA table_info(projection_threads)+ `;++ if (!columns.some((column) => column.name === "branch_pull_request_json")) {+ yield* sql`+ ALTER TABLE projection_threads+ ADD COLUMN branch_pull_request_json TEXT+ `;+ }+});diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.tsindex a70548bc110..ee442624be5 100644--- a/apps/server/src/persistence/Services/ProjectionThreads.ts+++ b/apps/server/src/persistence/Services/ProjectionThreads.ts@@ -35,6 +35,7 @@ export const ProjectionThread = Schema.Struct({branch: Schema.NullOr(Schema.String),worktreePath: Schema.NullOr(Schema.String),linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),+ branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),latestTurnId: Schema.NullOr(TurnId),createdAt: IsoDateTime,updatedAt: IsoDateTime,diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.tsindex 7c73752ee83..ac1cbfb44d0 100644--- a/apps/server/src/project/RepositoryIdentityResolver.test.ts+++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts@@ -38,15 +38,16 @@ const makeRepositoryIdentityResolverTestLayer = (options: {).pipe(Layer.provide(ProcessRunner.layer));it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {- it.effect("reuses the cached Git root for repeated workspace lookups", () => {+ it.effect("refreshes the Git root only when requested", () => {const calls: Array<ReadonlyArray<string>> = [];+ let rootPath = "/repo";const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {run: (input) =>Effect.sync(() => {calls.push(input.args);return {stdout: input.args.includes("rev-parse")- ? "/repo\n"+ ? `${rootPath}\n`: "origin\[email protected]:T3Tools/t3code.git (fetch)\n",stderr: "",code: ChildProcessSpawner.ExitCode(0),@@ -66,6 +67,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {return Effect.gen(function* () {const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;const first = yield* resolver.resolve("/repo/packages/web");+ rootPath = "/repo/packages/web";const second = yield* resolver.resolve("/repo/packages/web");expect(first?.canonicalKey).toBe("github.com/t3tools/t3code");@@ -74,6 +76,14 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],["-C", "/repo", "remote", "-v"],]);++ const refreshed = yield* resolver.resolve("/repo/packages/web", { refresh: true });+ expect(refreshed?.rootPath).toBe("/repo/packages/web");+ expect(yield* resolver.resolve("/repo/packages/web")).toEqual(refreshed);+ expect(calls.slice(2)).toEqual([+ ["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],+ ["-C", "/repo/packages/web", "remote", "-v"],+ ]);}).pipe(Effect.provide(resolverLayer));});@@ -197,25 +207,42 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {}).pipe(Effect.provide(RepositoryIdentityResolver.layer)),);- it.effect("prefers upstream over origin when both remotes are configured", () =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const cwd = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-repository-identity-upstream-test-",- });-- yield* git(cwd, ["init"]);- yield* git(cwd, ["remote", "add", "origin", "[email protected]:julius/t3code.git"]);- yield* git(cwd, ["remote", "add", "upstream", "[email protected]:T3Tools/t3code.git"]);+ it.effect.each(["add", "replace"] as const)(+ "refreshes the primary upstream after %s before cache expiry",+ (change) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const cwd = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-repository-identity-upstream-test-",+ });- const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;- const identity = yield* resolver.resolve(cwd);+ yield* git(cwd, ["init"]);+ yield* git(cwd, ["remote", "add", "origin", "[email protected]:julius/t3code.git"]);+ if (change === "replace") {+ yield* git(cwd, ["remote", "add", "upstream", "[email protected]:T3Tools/previous.git"]);+ }- expect(identity).not.toBeNull();- expect(identity?.locator.remoteName).toBe("upstream");- expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");- expect(identity?.displayName).toBe("t3tools/t3code");- }).pipe(Effect.provide(RepositoryIdentityResolver.layer)),+ const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;+ const initialIdentity = yield* resolver.resolve(cwd);+ expect(initialIdentity?.canonicalKey).toBe(+ change === "add" ? "github.com/julius/t3code" : "github.com/t3tools/previous",+ );++ yield* git(cwd, [+ "remote",+ change === "add" ? "add" : "set-url",+ "upstream",+ "[email protected]:T3Tools/t3code.git",+ ]);+ expect(yield* resolver.resolve(cwd)).toEqual(initialIdentity);+ const identity = yield* resolver.resolve(cwd, { refresh: true });++ expect(identity).not.toBeNull();+ expect(identity?.locator.remoteName).toBe("upstream");+ expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");+ expect(identity?.displayName).toBe("t3tools/t3code");+ expect(yield* resolver.resolve(cwd)).toEqual(identity);+ }).pipe(Effect.provide(RepositoryIdentityResolver.layer)),);it.effect("uses the last remote path segment as the repository name for nested groups", () =>diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.tsindex bf3c570c3ca..755008f6ded 100644--- a/apps/server/src/project/RepositoryIdentityResolver.ts+++ b/apps/server/src/project/RepositoryIdentityResolver.ts@@ -25,7 +25,10 @@ export interface RepositoryIdentityResolverOptions {export class RepositoryIdentityResolver extends Context.Service<RepositoryIdentityResolver,{- readonly resolve: (cwd: string) => Effect.Effect<RepositoryIdentity | null>;+ readonly resolve: (+ cwd: string,+ options?: { readonly refresh?: boolean },+ ) => Effect.Effect<RepositoryIdentity | null>;}>()("t3/project/RepositoryIdentityResolver") {}@@ -170,9 +173,11 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fn("RepositoryIdentityResolver.resolve",- )(function* (cwd) {+ )(function* (cwd, options) {+ if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);const cacheKey = yield* Cache.get(repositoryRootCache, cwd);if (cacheKey === null) return null;+ if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);return yield* Cache.get(repositoryIdentityCache, cacheKey);});diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex ce39ee64f51..696210b36b8 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -71,6 +71,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommaimport { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";import * as ThreadSettlementReactor from "./orchestration/ThreadSettlementReactor.ts";+import * as ThreadPullRequestReactor from "./orchestration/ThreadPullRequestReactor.ts";import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";@@ -279,6 +280,7 @@ const ReactorLayerLive = Layer.empty.pipe(Layer.provideMerge(CheckpointReactorLive),Layer.provideMerge(ThreadDeletionReactorLive),Layer.provideMerge(ThreadSettlementReactor.layer),+ Layer.provideMerge(ThreadPullRequestReactor.layer),Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),Layer.provideMerge(RuntimeReceiptBusLive),);diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsxindex c3c59129ca3..c952fab99d6 100644--- a/apps/web/src/components/BranchToolbarBranchSelector.tsx+++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx@@ -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.diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex f26f40dd2cd..1dd686cc803 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -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(diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 08043bd1c6d..649ffef081d 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -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;diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 3ff390c6640..faeab7e75ac 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -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" ? (<AgentsPaneldiff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex e54671f8e2f..ec1e79dc2d7 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -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;diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex fd1343c115c..7ffb79e3809 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -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: SidebarThreadRowPconst 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(<SidebarThreadRowkey={threadKey}thread={thread}- projectCwd={projectCwd}orderedProjectThreadKeys={orderedProjectThreadKeys}isActive={activeRouteThreadKey === threadKey}openPullRequestsInRightPanel={openPullRequestsInRightPanel}@@ -2444,7 +2400,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjecshowEmptyThreadState={showEmptyThreadState}shouldShowThreadPanel={shouldShowThreadPanel}isThreadListExpanded={isThreadListExpanded}- projectCwd={project.workspaceRoot}activeRouteThreadKey={activeRouteThreadKey}openPullRequestsInRightPanel={openPullRequestsInRightPanel}threadJumpLabelByKey={threadJumpLabelByKey}diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex f57872291f8..a0d98397637 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -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}/>);};diff --git a/apps/web/src/components/ThreadStatusIndicators.test.ts b/apps/web/src/components/ThreadStatusIndicators.test.tsindex 21949a1d180..7dd8c79c9b4 100644--- a/apps/web/src/components/ThreadStatusIndicators.test.ts+++ b/apps/web/src/components/ThreadStatusIndicators.test.ts@@ -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({diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsxindex e7b24f80cb7..76815441992 100644--- a/apps/web/src/components/ThreadStatusIndicators.tsx+++ b/apps/web/src/components/ThreadStatusIndicators.tsx@@ -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: SidebarThreadSummarconst 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,diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 227d13d18bb..f8514f83dcd 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -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.diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex e6c89c0343e..0a2e7aebad7 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -49,8 +49,13 @@ in the warning. Changing a rule does not reopen already settled threads.## Link a pull request+The server finds the PR for each unsettled thread's saved branch, even when your+apps are closed. Settled threads keep their saved links. Update the server if+automatic branch links do not appear.+On web and desktop, right-click a pull request link in a thread and choose-**Link to thread**. Use **Unlink from thread** on the same link to remove it.+**Link to thread** to select a different PR. Use **Unlink from thread** on the+same link to return to the branch PR, if one exists.The linked pull request participates in automatic settlement.## Find and reference workdiff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.tsindex 1f52eccc94c..59b3cb0551e 100644--- a/packages/client-runtime/src/state/threadReducer.test.ts+++ b/packages/client-runtime/src/state/threadReducer.test.ts@@ -306,50 +306,65 @@ describe("applyThreadDetailEvent", () => {}});- it("sets and clears a linked pull request", () => {- const linkedPullRequest = {- projectId: ProjectId.make("project-1"),- repository: "pingdotgg/t3code",- number: 42,- url: "https://github.com/pingdotgg/t3code/pull/42",- };- const linked = applyThreadDetailEvent(baseThread, {- ...baseEventFields,- sequence: 5,- occurredAt: "2026-04-01T05:00:00.000Z",- aggregateKind: "thread",- aggregateId: ThreadId.make("thread-1"),- type: "thread.meta-updated",- payload: {- threadId: ThreadId.make("thread-1"),- linkedPullRequest,- updatedAt: "2026-04-01T05:00:00.000Z",- },- });+ it.each(["linkedPullRequest", "branchPullRequest"] as const)(+ "sets and clears %s without changing the other link",+ (field) => {+ const linkedPullRequest = {+ projectId: ProjectId.make("project-1"),+ repository: "pingdotgg/t3code",+ number: 42,+ url: "https://github.com/pingdotgg/t3code/pull/42",+ };+ const otherField =+ field === "linkedPullRequest" ? "branchPullRequest" : "linkedPullRequest";+ const otherPullRequest = {+ ...linkedPullRequest,+ number: 43,+ url: "https://github.com/pingdotgg/t3code/pull/43",+ };+ const linked = applyThreadDetailEvent(+ { ...baseThread, [otherField]: otherPullRequest },+ {+ ...baseEventFields,+ sequence: 5,+ occurredAt: "2026-04-01T05:00:00.000Z",+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.meta-updated",+ payload: {+ threadId: ThreadId.make("thread-1"),+ [field]: linkedPullRequest,+ updatedAt: "2026-04-01T05:00:00.000Z",+ },+ },+ );- expect(linked.kind).toBe("updated");- if (linked.kind !== "updated") return;- expect(linked.thread.linkedPullRequest).toEqual(linkedPullRequest);+ expect(linked.kind).toBe("updated");+ if (linked.kind !== "updated") return;+ expect(linked.thread[field]).toEqual(linkedPullRequest);+ expect(linked.thread[otherField]).toEqual(otherPullRequest);- const cleared = applyThreadDetailEvent(linked.thread, {- ...baseEventFields,- sequence: 6,- occurredAt: "2026-04-01T06:00:00.000Z",- aggregateKind: "thread",- aggregateId: ThreadId.make("thread-1"),- type: "thread.meta-updated",- payload: {- threadId: ThreadId.make("thread-1"),- linkedPullRequest: null,- updatedAt: "2026-04-01T06:00:00.000Z",- },- });+ const cleared = applyThreadDetailEvent(linked.thread, {+ ...baseEventFields,+ sequence: 6,+ occurredAt: "2026-04-01T06:00:00.000Z",+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.meta-updated",+ payload: {+ threadId: ThreadId.make("thread-1"),+ [field]: null,+ updatedAt: "2026-04-01T06:00:00.000Z",+ },+ });- expect(cleared.kind).toBe("updated");- if (cleared.kind === "updated") {- expect(cleared.thread.linkedPullRequest).toBeNull();- }- });+ expect(cleared.kind).toBe("updated");+ if (cleared.kind === "updated") {+ expect(cleared.thread[field]).toBeNull();+ expect(cleared.thread[otherField]).toEqual(otherPullRequest);+ }+ },+ );});describe("thread.message-sent", () => {diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.tsindex c237856f90b..09272cd065c 100644--- a/packages/client-runtime/src/state/threadReducer.ts+++ b/packages/client-runtime/src/state/threadReducer.ts@@ -97,6 +97,7 @@ export function applyThreadDetailEvent(interactionMode: event.payload.interactionMode,branch: event.payload.branch,worktreePath: event.payload.worktreePath,+ branchPullRequest: null,latestTurn: null,createdAt: event.payload.createdAt,updatedAt: event.payload.updatedAt,@@ -240,6 +241,9 @@ export function applyThreadDetailEvent(...(event.payload.linkedPullRequest !== undefined? { linkedPullRequest: event.payload.linkedPullRequest }: {}),+ ...(event.payload.branchPullRequest !== undefined+ ? { branchPullRequest: event.payload.branchPullRequest }+ : {}),updatedAt: event.payload.updatedAt,},};diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.tsindex 11c21deecdd..61dbdb9a551 100644--- a/packages/contracts/src/orchestration.test.ts+++ b/packages/contracts/src/orchestration.test.ts@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as Schema from "effect/Schema";+import { CommandId, ProjectId, ThreadId } from "./baseSchemas.ts";import {DEFAULT_PROVIDER_INTERACTION_MODE,@@ -837,6 +838,47 @@ it.effect("accepts an internal title regeneration completion", () =>}),);+it.effect("accepts pull request synchronization only as an internal command", () =>+ Effect.gen(function* () {+ const pullRequest = {+ projectId: ProjectId.make("project-1"),+ repository: "pingdotgg/t3code",+ number: 42,+ url: "https://github.com/pingdotgg/t3code/pull/42",+ };+ const command = {+ type: "thread.pull-request.sync" as const,+ commandId: CommandId.make("cmd-pull-request-sync"),+ threadId: ThreadId.make("thread-1"),+ projectId: pullRequest.projectId,+ snapshotSequence: 12,+ expected: {+ workspaceRoot: "/workspace/project",+ branch: "feature",+ worktreePath: null,+ linkedPullRequest: null,+ branchPullRequest: null,+ },+ branchPullRequest: pullRequest,+ linkedPullRequest: pullRequest,+ };++ assert.deepStrictEqual(yield* decodeOrchestrationCommand(command), command);+ assert.ok(yield* decodeClientOrchestrationCommand(command).pipe(Effect.flip));++ const cleared = { ...command, branchPullRequest: null };+ assert.deepStrictEqual(yield* decodeOrchestrationCommand(cleared), cleared);++ const metadata = yield* decodeClientOrchestrationCommand({+ type: "thread.meta.update",+ commandId: "cmd-forged-branch-pull-request",+ threadId: "thread-1",+ branchPullRequest: pullRequest,+ });+ assert.isFalse("branchPullRequest" in metadata);+ }),+);+it.effect("rejects an explicit title combined with title regeneration", () =>Effect.gen(function* () {const result = yield* Effect.exit(diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 92e9fe01dd4..47501e32344 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -494,6 +494,7 @@ export const OrchestrationThread = Schema.Struct({branch: Schema.NullOr(TrimmedNonEmptyString),worktreePath: Schema.NullOr(TrimmedNonEmptyString),linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),+ branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),latestTurn: Schema.NullOr(OrchestrationLatestTurn),createdAt: IsoDateTime,updatedAt: IsoDateTime,@@ -572,6 +573,7 @@ export const OrchestrationThreadShell = Schema.Struct({branch: Schema.NullOr(TrimmedNonEmptyString),worktreePath: Schema.NullOr(TrimmedNonEmptyString),linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),+ branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),latestTurn: Schema.NullOr(OrchestrationLatestTurn),createdAt: IsoDateTime,updatedAt: IsoDateTime,@@ -1183,6 +1185,23 @@ const ThreadTitleRegenerationCompleteCommand = Schema.Struct({title: Schema.optional(TrimmedNonEmptyString),});+const ThreadPullRequestSyncCommand = Schema.Struct({+ type: Schema.Literal("thread.pull-request.sync"),+ commandId: CommandId,+ threadId: ThreadId,+ projectId: ProjectId,+ snapshotSequence: NonNegativeInt,+ expected: Schema.Struct({+ workspaceRoot: TrimmedNonEmptyString,+ branch: Schema.NullOr(TrimmedNonEmptyString),+ worktreePath: Schema.NullOr(TrimmedNonEmptyString),+ linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest),+ branchPullRequest: Schema.NullOr(ThreadLinkedPullRequest),+ }),+ branchPullRequest: Schema.NullOr(ThreadLinkedPullRequest),+ linkedPullRequest: Schema.optional(ThreadLinkedPullRequest),+});+const InternalOrchestrationCommand = Schema.Union([ThreadAutoSettleCommand,ThreadSessionSetCommand,@@ -1194,6 +1213,7 @@ const InternalOrchestrationCommand = Schema.Union([ThreadActivityAppendCommand,ThreadRevertCompleteCommand,ThreadTitleRegenerationCompleteCommand,+ ThreadPullRequestSyncCommand,]);export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;@@ -1367,6 +1387,7 @@ export const ThreadMetaUpdatedPayload = Schema.Struct({branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),+ branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),updatedAt: IsoDateTime,});diff --git a/packages/shared/src/threadReference.test.ts b/packages/shared/src/threadReference.test.tsindex 60600c7e146..1b975a8defe 100644--- a/packages/shared/src/threadReference.test.ts+++ b/packages/shared/src/threadReference.test.ts@@ -9,18 +9,16 @@ describe("resolveThreadReferenceCopyTarget", () => {threadId: "thread-1",openPanelPullRequestUrl: null,linkedPullRequestUrl: "https://github.com/t3/pr/12",- detectedPullRequestUrl: "https://github.com/t3/pr/13",}),).toBeNull();});- it("prefers the open panel pull request over linked and detected pull requests", () => {+ it("prefers the open panel pull request over the thread pull request", () => {expect(resolveThreadReferenceCopyTarget({threadId: "thread-1",openPanelPullRequestUrl: "https://github.com/t3/pr/14",linkedPullRequestUrl: "https://github.com/t3/pr/12",- detectedPullRequestUrl: "https://github.com/t3/pr/13",}),).toMatchObject({kind: "pull-request",@@ -29,12 +27,11 @@ describe("resolveThreadReferenceCopyTarget", () => {});});- it("prefers a durable linked pull request", () => {+ it("uses the thread pull request when no panel is open", () => {expect(resolveThreadReferenceCopyTarget({threadId: "thread-1",linkedPullRequestUrl: "https://github.com/t3/pr/12",- detectedPullRequestUrl: "https://github.com/t3/pr/13",}),).toMatchObject({kind: "pull-request",@@ -43,18 +40,6 @@ describe("resolveThreadReferenceCopyTarget", () => {});});- it("uses a pull request detected from the active branch", () => {- expect(- resolveThreadReferenceCopyTarget({- threadId: "thread-1",- detectedPullRequestUrl: "https://github.com/t3/pr/13",- }),- ).toMatchObject({- kind: "pull-request",- value: "https://github.com/t3/pr/13",- });- });-it("falls back to the thread ID", () => {expect(resolveThreadReferenceCopyTarget({ threadId: "thread-1" })).toEqual({kind: "thread",diff --git a/packages/shared/src/threadReference.ts b/packages/shared/src/threadReference.tsindex 20eac6fba03..ce53078862a 100644--- a/packages/shared/src/threadReference.ts+++ b/packages/shared/src/threadReference.ts@@ -11,11 +11,9 @@ export function resolveThreadReferenceCopyTarget(input: {/** Undefined means no PR panel; null means its URL is not available yet. */readonly openPanelPullRequestUrl?: string | null | undefined;readonly linkedPullRequestUrl?: string | null;- readonly detectedPullRequestUrl?: string | null;}): ThreadReferenceCopyTarget | null {if (input.openPanelPullRequestUrl === null) return null;- const pullRequestUrl =- input.openPanelPullRequestUrl ?? input.linkedPullRequestUrl ?? input.detectedPullRequestUrl;+ const pullRequestUrl = input.openPanelPullRequestUrl ?? input.linkedPullRequestUrl;return pullRequestUrl? {kind: "pull-request",