The best way to control Claude Code, Codex and more from any computer or phone
feat: link pull requests to threads (#8160)
Theo Browne committed
Aug 24, 2026 at 21:51 UTC
3c75eb1132bb5d67cfa95ac6271ef68959f986c1
39 files changed
+1039
-63
apps/mobile/src/features/home/HomeScreen.tsx
+5
-4
@@ -12,7 +12,6 @@ import {
12
type EnvironmentThreadSearchMatch,
13
} from "@t3tools/client-runtime/state/thread-search";
14
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
15
-import type { ChangeRequestSettleSource } from "@t3tools/client-runtime/state/thread-settled";
15
import type {
16
EnvironmentId,
17
SidebarProjectGroupingMode,
@@ -54,6 +53,7 @@ import {
53
buildThreadListV2ListItems,
54
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
55
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
56
+ type ThreadListV2ChangeRequestState,
57
type ThreadListV2ListItem,
58
} from "../threads/threadListV2";
59
import { useThreadListV2ShelfPreferences } from "../threads/use-thread-list-v2-shelf-preferences";
@@ -491,15 +491,16 @@ export function HomeScreen(props: HomeScreenProps) {
491
// PR states stream in per-row. The next partition applies the configured
492
// merge rule and the always-on close rule, matching web.
493
const [changeRequestByKey, setChangeRequestByKey] = useState<
494
- ReadonlyMap<string, ChangeRequestSettleSource>
494
+ ReadonlyMap<string, ThreadListV2ChangeRequestState>
495
>(() => new Map());
496
const handleChangeRequestState = useCallback(
497
- (threadKey: string, changeRequest: ChangeRequestSettleSource | null) => {
497
+ (threadKey: string, changeRequest: ThreadListV2ChangeRequestState | null) => {
498
setChangeRequestByKey((current) => {
499
const existing = current.get(threadKey) ?? null;
500
if (
501
(existing?.state ?? null) === (changeRequest?.state ?? null) &&
502
- (existing?.updatedAt ?? null) === (changeRequest?.updatedAt ?? null)
502
+ (existing?.updatedAt ?? null) === (changeRequest?.updatedAt ?? null) &&
503
+ (existing?.linkedPullRequestKey ?? null) === (changeRequest?.linkedPullRequestKey ?? null)
504
) {
505
return current;
506
}
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+5
-4
@@ -12,7 +12,6 @@ import { useAtomValue } from "@effect/atom-react";
12
import { AsyncResult } from "effect/unstable/reactivity";
13
import type { EnvironmentId } from "@t3tools/contracts";
14
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
15
-import type { ChangeRequestSettleSource } from "@t3tools/client-runtime/state/thread-settled";
15
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
16
import type { LayoutChangeEvent } from "react-native";
17
import { Platform, Pressable, StyleSheet, TextInput, View } from "react-native";
@@ -84,6 +83,7 @@ import {
83
buildThreadListV2ListItems,
84
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
85
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
86
+ type ThreadListV2ChangeRequestState,
87
type ThreadListV2ListItem,
88
} from "./threadListV2";
89
@@ -377,15 +377,16 @@ function ThreadNavigationSidebarPane(
377
// PR states stream in per-row. The next partition applies the configured
378
// merge rule and the always-on close rule.
379
const [changeRequestByKey, setChangeRequestByKey] = useState<
380
- ReadonlyMap<string, ChangeRequestSettleSource>
380
+ ReadonlyMap<string, ThreadListV2ChangeRequestState>
381
>(() => new Map());
382
const handleChangeRequestState = useCallback(
383
- (threadKey: string, changeRequest: ChangeRequestSettleSource | null) => {
383
+ (threadKey: string, changeRequest: ThreadListV2ChangeRequestState | null) => {
384
setChangeRequestByKey((current) => {
385
const existing = current.get(threadKey) ?? null;
386
if (
387
(existing?.state ?? null) === (changeRequest?.state ?? null) &&
388
- (existing?.updatedAt ?? null) === (changeRequest?.updatedAt ?? null)
388
+ (existing?.updatedAt ?? null) === (changeRequest?.updatedAt ?? null) &&
389
+ (existing?.linkedPullRequestKey ?? null) === (changeRequest?.linkedPullRequestKey ?? null)
390
) {
391
return current;
392
}
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+12
-11
@@ -3,11 +3,7 @@ import type {
3
EnvironmentThreadShell,
4
} from "@t3tools/client-runtime/state/shell";
5
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
6
-import {
7
- canSnooze,
8
- resolveSnoozePresets,
9
- type ChangeRequestSettleSource,
10
-} from "@t3tools/client-runtime/state/thread-settled";
6
+import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
7
import type { MenuAction } from "@react-native-menu/menu";
8
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
9
import { Alert, Platform, Pressable, useWindowDimensions, View } from "react-native";
@@ -27,10 +23,12 @@ import { ThreadSwipeable } from "../home/thread-swipe-actions";
23
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
24
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
25
import {
26
+ resolveThreadListV2ChangeRequestState,
27
resolveThreadListV2SnoozeMenuSelection,
28
resolveThreadListV2SnoozeGateExpiryMs,
29
resolveThreadListV2Status,
30
resolveThreadListV2SwipeActions,
31
+ type ThreadListV2ChangeRequestState,
32
type ThreadListV2Status,
33
} from "./threadListV2";
34
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
@@ -377,7 +375,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
375
merge and close rules. Mirrors web's onChangeRequestState. */
376
readonly onChangeRequestState?: (
377
threadKey: string,
380
- changeRequest: ChangeRequestSettleSource | null,
378
+ changeRequest: ThreadListV2ChangeRequestState | null,
379
) => void;
380
readonly projectCwd?: string | null;
381
readonly searchMatch?: EnvironmentThreadSearchMatch;
@@ -411,11 +409,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
409
const prUpdatedAt = pr?.updatedAt ?? null;
410
const threadKey = `${thread.environmentId}:${thread.id}`;
411
useEffect(() => {
414
- onChangeRequestState?.(
415
- threadKey,
416
- prState === null ? null : { state: prState, updatedAt: prUpdatedAt },
417
- );
418
- }, [onChangeRequestState, prState, prUpdatedAt, threadKey]);
412
+ const changeRequest = resolveThreadListV2ChangeRequestState({
413
+ linkedPullRequest: thread.linkedPullRequest,
414
+ state: prState,
415
+ updatedAt: prUpdatedAt,
416
+ });
417
+ if (changeRequest === undefined) return;
418
+ onChangeRequestState?.(threadKey, changeRequest);
419
+ }, [onChangeRequestState, prState, prUpdatedAt, thread.linkedPullRequest, threadKey]);
420
421
const screenColor = useThemeColor("--color-screen");
422
const drawerColor = useThemeColor("--color-drawer");
apps/mobile/src/features/threads/threadListV2.test.ts
+95
@@ -16,6 +16,7 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
16
import {
17
buildThreadListV2Items,
18
buildThreadListV2ListItems,
19
+ resolveThreadListV2ChangeRequestState,
20
resolveThreadListV2Enabled,
21
resolveThreadListV2SnoozeMenuSelection,
22
resolveThreadListV2SnoozeGateExpiryMs,
@@ -53,6 +54,48 @@ function makeThread(
54
}
55
56
const NOW = "2026-06-02T00:00:00.000Z";
57
+const linkedPullRequest = {
58
+ projectId: ProjectId.make("project-1"),
59
+ repository: "pingdotgg/t3code",
60
+ number: 42,
61
+ url: "https://github.com/pingdotgg/t3code/pull/42",
62
+};
63
+
64
+describe("resolveThreadListV2ChangeRequestState", () => {
65
+ it("preserves the previous state while a linked pull request reloads", () => {
66
+ expect(
67
+ resolveThreadListV2ChangeRequestState({
68
+ linkedPullRequest,
69
+ state: null,
70
+ updatedAt: null,
71
+ }),
72
+ ).toBeUndefined();
73
+ });
74
+
75
+ it("clears the previous state after a pull request is unlinked", () => {
76
+ expect(
77
+ resolveThreadListV2ChangeRequestState({
78
+ linkedPullRequest: null,
79
+ state: null,
80
+ updatedAt: null,
81
+ }),
82
+ ).toBeNull();
83
+ });
84
+
85
+ it("reports a loaded linked pull request", () => {
86
+ expect(
87
+ resolveThreadListV2ChangeRequestState({
88
+ linkedPullRequest,
89
+ state: "merged",
90
+ updatedAt: "2026-06-02T00:00:00.000Z",
91
+ }),
92
+ ).toEqual({
93
+ state: "merged",
94
+ updatedAt: "2026-06-02T00:00:00.000Z",
95
+ linkedPullRequestKey: '["project-1","pingdotgg/t3code",42]',
96
+ });
97
+ });
98
+});
99
100
describe("resolveThreadListV2SnoozeMenuSelection", () => {
101
it("accepts a displayed evening preset while its wake time is still future", () => {
@@ -263,6 +306,58 @@ describe("sortThreadsForListV2", () => {
306
});
307
308
describe("buildThreadListV2Items", () => {
309
+ it("ignores the previous pull request state after a different pull request is linked", () => {
310
+ const thread = makeThread({
311
+ id: ThreadId.make("linked"),
312
+ title: "Linked pull request",
313
+ linkedPullRequest,
314
+ });
315
+ const layout = buildThreadListV2Items({
316
+ threads: [thread],
317
+ environmentId: null,
318
+ searchQuery: "",
319
+ changeRequestByKey: new Map([
320
+ [
321
+ `${environmentId}:${thread.id}`,
322
+ {
323
+ state: "merged" as const,
324
+ linkedPullRequestKey: '["project-1","pingdotgg/t3code",41]',
325
+ },
326
+ ],
327
+ ]),
328
+ now: NOW,
329
+ });
330
+
331
+ expect(layout.settledCount).toBe(0);
332
+ expect(layout.items[0]?.variant).toBe("card");
333
+ });
334
+
335
+ it("settles a thread only when the cached pull request identity matches", () => {
336
+ const thread = makeThread({
337
+ id: ThreadId.make("linked-merged"),
338
+ title: "Linked merged pull request",
339
+ linkedPullRequest,
340
+ });
341
+ const layout = buildThreadListV2Items({
342
+ threads: [thread],
343
+ environmentId: null,
344
+ searchQuery: "",
345
+ changeRequestByKey: new Map([
346
+ [
347
+ `${environmentId}:${thread.id}`,
348
+ {
349
+ state: "merged" as const,
350
+ linkedPullRequestKey: '["project-1","pingdotgg/t3code",42]',
351
+ },
352
+ ],
353
+ ]),
354
+ now: NOW,
355
+ });
356
+
357
+ expect(layout.settledCount).toBe(1);
358
+ expect(layout.items[0]?.variant).toBe("slim");
359
+ });
360
+
361
it("keeps a merged thread active when auto-settle on merge is off", () => {
362
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
363
const layout = buildThreadListV2Items({
apps/mobile/src/features/threads/threadListV2.ts
+38
-3
@@ -13,7 +13,7 @@ import type {
13
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
14
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
15
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
16
-import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
16
+import type { EnvironmentId, ProjectId, ThreadLinkedPullRequest } from "@t3tools/contracts";
17
18
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
19
@@ -30,6 +30,35 @@ export { snoozeWakeLabel };
30
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
31
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
32
33
+export interface ThreadListV2ChangeRequestState extends ChangeRequestSettleSource {
34
+ readonly linkedPullRequestKey?: string | null;
35
+}
36
+
37
+function linkedPullRequestKey(
38
+ linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
39
+): string | null {
40
+ if (linkedPullRequest == null) return null;
41
+ return JSON.stringify([
42
+ linkedPullRequest.projectId,
43
+ linkedPullRequest.repository.toLowerCase(),
44
+ linkedPullRequest.number,
45
+ ]);
46
+}
47
+
48
+/** Keep the previous linked PR state while its detail query reloads. */
49
+export function resolveThreadListV2ChangeRequestState(input: {
50
+ readonly linkedPullRequest: ThreadLinkedPullRequest | null | undefined;
51
+ readonly state: ChangeRequestSettleSource["state"] | null;
52
+ readonly updatedAt: string | null;
53
+}): ThreadListV2ChangeRequestState | null | undefined {
54
+ if (input.state === null) return input.linkedPullRequest == null ? null : undefined;
55
+ return {
56
+ state: input.state,
57
+ updatedAt: input.updatedAt,
58
+ linkedPullRequestKey: linkedPullRequestKey(input.linkedPullRequest),
59
+ };
60
+}
61
+
62
export function resolveThreadListV2SnoozeMenuSelection(input: {
63
readonly event: string;
64
readonly displayedPresets: ReadonlyArray<SnoozePreset>;
@@ -322,7 +351,7 @@ export function buildThreadListV2Items(input: {
351
readonly searchQuery: string;
352
readonly matchedThreadKeys?: ReadonlySet<string>;
353
/** Per-row PR reported up by visible rows ("env:threadId" keys). */
325
- readonly changeRequestByKey?: ReadonlyMap<string, ChangeRequestSettleSource>;
354
+ readonly changeRequestByKey?: ReadonlyMap<string, ThreadListV2ChangeRequestState>;
355
/** Environments whose server supports thread.settle/unsettle. Threads on
356
other environments never classify as settled — the user could neither
357
un-settle nor pin them. Absent = no gating (tests). */
@@ -384,8 +413,14 @@ export function buildThreadListV2Items(input: {
413
}
414
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
415
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
387
- const changeRequest =
416
+ const cachedChangeRequest =
417
input.changeRequestByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
418
+ const changeRequest =
419
+ cachedChangeRequest !== null &&
420
+ (cachedChangeRequest.linkedPullRequestKey ?? null) ===
421
+ linkedPullRequestKey(thread.linkedPullRequest)
422
+ ? cachedChangeRequest
423
+ : null;
424
// Snooze outranks settlement and pinning until the thread wakes.
425
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
426
snoozed.push(thread);
apps/mobile/src/state/use-thread-pr.ts
+31
-1
@@ -1,9 +1,16 @@
1
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2
+import {
3
+ createLinkedPullRequestDetailAtomFamily,
4
+ pullRequestDetailToVcsStatus,
5
+} from "@t3tools/client-runtime/state/pull-requests";
6
7
+import { connectionAtomRuntime } from "../connection/runtime";
8
import { useEnvironmentQuery } from "./query";
9
import { presentThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation";
10
import { vcsEnvironment } from "./vcs";
11
12
+const linkedPullRequestDetailAtom = createLinkedPullRequestDetailAtomFamily(connectionAtomRuntime);
13
+
14
export {
15
presentThreadPr,
16
type ThreadPr,
@@ -22,13 +29,36 @@ export function useThreadPr(
29
): ThreadPrPresentation | null {
30
const cwd = thread.worktreePath ?? projectCwd;
31
const gitStatus = useEnvironmentQuery(
25
- thread.branch !== null && cwd !== null
32
+ thread.linkedPullRequest == null && thread.branch !== null && cwd !== null
33
? vcsEnvironment.status({
34
environmentId: thread.environmentId,
35
input: { cwd },
36
})
37
: null,
38
);
39
+ const linkedPullRequest = useEnvironmentQuery(
40
+ thread.linkedPullRequest == null
41
+ ? null
42
+ : linkedPullRequestDetailAtom({
43
+ environmentId: thread.environmentId,
44
+ input: {
45
+ projectId: thread.linkedPullRequest.projectId,
46
+ repository: thread.linkedPullRequest.repository,
47
+ number: thread.linkedPullRequest.number,
48
+ },
49
+ }),
50
+ );
51
+
52
+ if (thread.linkedPullRequest != null) {
53
+ const detail = linkedPullRequest.data;
54
+ return detail === null
55
+ ? null
56
+ : presentThreadPr(pullRequestDetailToVcsStatus(detail), {
57
+ kind: detail.provider,
58
+ name: detail.provider,
59
+ baseUrl: "",
60
+ });
61
+ }
62
63
const status = gitStatus.data;
64
if (status === null || thread.branch === null || status.refName !== thread.branch) {
apps/server/src/environment/ServerEnvironment.test.ts
+1
@@ -93,6 +93,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
93
expect(second.capabilities.attachmentUploads).toBe(true);
94
expect(second.capabilities.pullRequests).toBe(true);
95
expect(second.capabilities.threadTitleRegeneration).toBe(true);
96
+ expect(second.capabilities.threadPullRequestLinking).toBe(true);
97
expect(second.capabilities.agentActivityPublishing).toBe(false);
98
}),
99
);
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -153,6 +153,7 @@ export const make = Effect.gen(function* () {
153
threadPinning: true,
154
threadPinReorder: true,
155
threadTitleRegeneration: true,
156
+ threadPullRequestLinking: true,
157
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
158
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
159
},
apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+4
@@ -634,6 +634,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
634
interactionMode: event.payload.interactionMode,
635
branch: event.payload.branch,
636
worktreePath: event.payload.worktreePath,
637
+ linkedPullRequest: null,
638
latestTurnId: null,
639
createdAt: event.payload.createdAt,
640
updatedAt: event.payload.updatedAt,
@@ -822,6 +823,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
823
...(event.payload.worktreePath !== undefined
824
? { worktreePath: event.payload.worktreePath }
825
: {}),
826
+ ...(event.payload.linkedPullRequest !== undefined
827
+ ? { linkedPullRequest: event.payload.linkedPullRequest }
828
+ : {}),
829
updatedAt: event.payload.updatedAt,
830
});
831
return;
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+14
@@ -82,6 +82,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
82
interaction_mode,
83
branch,
84
worktree_path,
85
+ linked_pull_request_json,
86
latest_turn_id,
87
latest_user_message_at,
88
pending_approval_count,
@@ -102,6 +103,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
103
'default',
104
NULL,
105
NULL,
106
+ '{"projectId":"project-1","repository":"pingdotgg/t3code","number":42,"url":"https://github.com/pingdotgg/t3code/pull/42"}',
107
'turn-1',
108
'2026-02-24T00:00:04.000Z',
109
1,
@@ -304,6 +306,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
306
runtimeMode: "full-access",
307
branch: null,
308
worktreePath: null,
309
+ linkedPullRequest: {
310
+ projectId: asProjectId("project-1"),
311
+ repository: "pingdotgg/t3code",
312
+ number: 42,
313
+ url: "https://github.com/pingdotgg/t3code/pull/42",
314
+ },
315
latestTurn: {
316
turnId: asTurnId("turn-1"),
317
state: "completed",
@@ -423,6 +431,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
431
runtimeMode: "full-access",
432
branch: null,
433
worktreePath: null,
434
+ linkedPullRequest: {
435
+ projectId: asProjectId("project-1"),
436
+ repository: "pingdotgg/t3code",
437
+ number: 42,
438
+ url: "https://github.com/pingdotgg/t3code/pull/42",
439
+ },
440
latestTurn: {
441
turnId: asTurnId("turn-1"),
442
state: "completed",
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+24
@@ -24,6 +24,7 @@ import {
24
type OrchestrationThreadShell,
25
ModelSelection,
26
ProjectId,
27
+ ThreadLinkedPullRequest,
28
ThreadId,
29
} from "@t3tools/contracts";
30
import * as Arr from "effect/Array";
@@ -89,6 +90,7 @@ const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
90
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
91
Struct.assign({
92
modelSelection: Schema.fromJsonString(ModelSelection),
93
+ linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
94
}),
95
);
96
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
@@ -422,6 +424,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
424
interaction_mode AS "interactionMode",
425
branch,
426
worktree_path AS "worktreePath",
427
+ linked_pull_request_json AS "linkedPullRequest",
428
latest_turn_id AS "latestTurnId",
429
created_at AS "createdAt",
430
updated_at AS "updatedAt",
@@ -458,6 +461,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
461
interaction_mode AS "interactionMode",
462
branch,
463
worktree_path AS "worktreePath",
464
+ linked_pull_request_json AS "linkedPullRequest",
465
latest_turn_id AS "latestTurnId",
466
created_at AS "createdAt",
467
updated_at AS "updatedAt",
@@ -496,6 +500,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
500
interaction_mode AS "interactionMode",
501
branch,
502
worktree_path AS "worktreePath",
503
+ linked_pull_request_json AS "linkedPullRequest",
504
latest_turn_id AS "latestTurnId",
505
created_at AS "createdAt",
506
updated_at AS "updatedAt",
@@ -938,6 +943,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
943
interaction_mode AS "interactionMode",
944
branch,
945
worktree_path AS "worktreePath",
946
+ linked_pull_request_json AS "linkedPullRequest",
947
latest_turn_id AS "latestTurnId",
948
created_at AS "createdAt",
949
updated_at AS "updatedAt",
@@ -1694,6 +1700,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1700
interactionMode: row.interactionMode,
1701
branch: row.branch,
1702
worktreePath: row.worktreePath,
1703
+ ...(row.linkedPullRequest === null
1704
+ ? {}
1705
+ : { linkedPullRequest: row.linkedPullRequest }),
1706
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
1707
createdAt: row.createdAt,
1708
updatedAt: row.updatedAt,
@@ -1901,6 +1910,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1910
interactionMode: row.interactionMode,
1911
branch: row.branch,
1912
worktreePath: row.worktreePath,
1913
+ ...(row.linkedPullRequest === null
1914
+ ? {}
1915
+ : { linkedPullRequest: row.linkedPullRequest }),
1916
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
1917
createdAt: row.createdAt,
1918
updatedAt: row.updatedAt,
@@ -2037,6 +2049,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
2049
interactionMode: row.interactionMode,
2050
branch: row.branch,
2051
worktreePath: row.worktreePath,
2052
+ ...(row.linkedPullRequest === null
2053
+ ? {}
2054
+ : { linkedPullRequest: row.linkedPullRequest }),
2055
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
2056
createdAt: row.createdAt,
2057
updatedAt: row.updatedAt,
@@ -2182,6 +2197,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
2197
interactionMode: row.interactionMode,
2198
branch: row.branch,
2199
worktreePath: row.worktreePath,
2200
+ ...(row.linkedPullRequest === null
2201
+ ? {}
2202
+ : { linkedPullRequest: row.linkedPullRequest }),
2203
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
2204
createdAt: row.createdAt,
2205
updatedAt: row.updatedAt,
@@ -2461,6 +2479,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
2479
interactionMode: threadRow.value.interactionMode,
2480
branch: threadRow.value.branch,
2481
worktreePath: threadRow.value.worktreePath,
2482
+ ...(threadRow.value.linkedPullRequest === null
2483
+ ? {}
2484
+ : { linkedPullRequest: threadRow.value.linkedPullRequest }),
2485
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
2486
createdAt: threadRow.value.createdAt,
2487
updatedAt: threadRow.value.updatedAt,
@@ -2602,6 +2623,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
2623
interactionMode: threadRow.value.interactionMode,
2624
branch: threadRow.value.branch,
2625
worktreePath: threadRow.value.worktreePath,
2626
+ ...(threadRow.value.linkedPullRequest === null
2627
+ ? {}
2628
+ : { linkedPullRequest: threadRow.value.linkedPullRequest }),
2629
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
2630
createdAt: threadRow.value.createdAt,
2631
updatedAt: threadRow.value.updatedAt,
apps/server/src/orchestration/decider.ts
+3
@@ -847,6 +847,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
847
: {}),
848
...(branch !== undefined ? { branch } : {}),
849
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
850
+ ...(command.linkedPullRequest !== undefined
851
+ ? { linkedPullRequest: command.linkedPullRequest }
852
+ : {}),
853
updatedAt: occurredAt,
854
},
855
};
apps/server/src/orchestration/projector.ts
+3
@@ -456,6 +456,9 @@ export function projectEvent(
456
: {}),
457
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
458
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
459
+ ...(payload.linkedPullRequest !== undefined
460
+ ? { linkedPullRequest: payload.linkedPullRequest }
461
+ : {}),
462
updatedAt: payload.updatedAt,
463
}),
464
})),
apps/server/src/persistence/Layers/ProjectionRepositories.test.ts
+51
@@ -201,4 +201,55 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
201
assert.strictEqual(updated?.pinnedAt, null);
202
}),
203
);
204
+
205
+ it.effect("round-trips a linked pull request through the thread row", () =>
206
+ Effect.gen(function* () {
207
+ const threads = yield* ProjectionThreadRepository;
208
+ const linkedPullRequest = {
209
+ projectId: ProjectId.make("project-linked-pr"),
210
+ repository: "pingdotgg/t3code",
211
+ number: 42,
212
+ url: "https://github.com/pingdotgg/t3code/pull/42",
213
+ };
214
+
215
+ yield* threads.upsert({
216
+ threadId: ThreadId.make("thread-linked-pr"),
217
+ projectId: ProjectId.make("project-linked-pr"),
218
+ title: "Linked pull request",
219
+ modelSelection: {
220
+ instanceId: ProviderInstanceId.make("codex"),
221
+ model: "gpt-5.4",
222
+ },
223
+ runtimeMode: "full-access",
224
+ interactionMode: "default",
225
+ branch: null,
226
+ worktreePath: null,
227
+ linkedPullRequest,
228
+ latestTurnId: null,
229
+ createdAt: "2026-03-24T00:00:00.000Z",
230
+ updatedAt: "2026-03-24T00:00:00.000Z",
231
+ archivedAt: null,
232
+ settledOverride: null,
233
+ settledAt: null,
234
+ snoozedUntil: null,
235
+ snoozedAt: null,
236
+ pinnedAt: null,
237
+ latestUserMessageAt: null,
238
+ pendingApprovalCount: 0,
239
+ pendingUserInputCount: 0,
240
+ hasActionableProposedPlan: 0,
241
+ deletedAt: null,
242
+ });
243
+
244
+ const persisted = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
245
+ assert.deepStrictEqual(Option.getOrNull(persisted)?.linkedPullRequest, linkedPullRequest);
246
+
247
+ const row = Option.getOrNull(persisted);
248
+ if (row === null) return yield* Effect.die("Expected linked thread row to exist.");
249
+ yield* threads.upsert({ ...row, linkedPullRequest: null });
250
+
251
+ const cleared = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
252
+ assert.strictEqual(Option.getOrNull(cleared)?.linkedPullRequest, null);
253
+ }),
254
+ );
255
});
apps/server/src/persistence/Layers/ProjectionThreads.ts
+7
-1
@@ -14,11 +14,12 @@ import {
14
ProjectionThreadRepository,
15
type ProjectionThreadRepositoryShape,
16
} from "../Services/ProjectionThreads.ts";
17
-import { ModelSelection } from "@t3tools/contracts";
17
+import { ModelSelection, ThreadLinkedPullRequest } from "@t3tools/contracts";
18
19
const ProjectionThreadDbRow = ProjectionThread.mapFields(
20
Struct.assign({
21
modelSelection: Schema.fromJsonString(ModelSelection),
22
+ linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
23
}),
24
);
25
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
@@ -39,6 +40,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
40
interaction_mode,
41
branch,
42
worktree_path,
43
+ linked_pull_request_json,
44
latest_turn_id,
45
created_at,
46
updated_at,
@@ -66,6 +68,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
68
${row.interactionMode},
69
${row.branch},
70
${row.worktreePath},
71
+ ${row.linkedPullRequest === undefined || row.linkedPullRequest === null ? null : JSON.stringify(row.linkedPullRequest)},
72
${row.latestTurnId},
73
${row.createdAt},
74
${row.updatedAt},
@@ -93,6 +96,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
96
interaction_mode = excluded.interaction_mode,
97
branch = excluded.branch,
98
worktree_path = excluded.worktree_path,
99
+ linked_pull_request_json = excluded.linked_pull_request_json,
100
latest_turn_id = excluded.latest_turn_id,
101
created_at = excluded.created_at,
102
updated_at = excluded.updated_at,
@@ -127,6 +131,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
131
interaction_mode AS "interactionMode",
132
branch,
133
worktree_path AS "worktreePath",
134
+ linked_pull_request_json AS "linkedPullRequest",
135
latest_turn_id AS "latestTurnId",
136
created_at AS "createdAt",
137
updated_at AS "updatedAt",
@@ -163,6 +168,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
168
interaction_mode AS "interactionMode",
169
branch,
170
worktree_path AS "worktreePath",
171
+ linked_pull_request_json AS "linkedPullRequest",
172
latest_turn_id AS "latestTurnId",
173
created_at AS "createdAt",
174
updated_at AS "updatedAt",
apps/server/src/persistence/Migrations.ts
+2
@@ -54,6 +54,7 @@ import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
54
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
55
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
56
import Migration0041 from "./Migrations/041_AuthSessionClientConnection.ts";
57
+import Migration0042 from "./Migrations/042_ProjectionThreadLinkedPullRequest.ts";
58
59
/**
60
* Migration loader with all migrations defined inline.
@@ -107,6 +108,7 @@ export const migrationEntries = [
108
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
109
[40, "ProjectionProjectFaviconPath", Migration0040],
110
[41, "AuthSessionClientConnection", Migration0041],
111
+ [42, "ProjectionThreadLinkedPullRequest", Migration0042],
112
] as const;
113
114
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/042_ProjectionThreadLinkedPullRequest.test.ts
new
+25
@@ -0,0 +1,25 @@
1
+import { assert, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as Layer from "effect/Layer";
4
+import * as SqlClient from "effect/unstable/sql/SqlClient";
5
+
6
+import { runMigrations } from "../Migrations.ts";
7
+import * as NodeSqliteClient from "../NodeSqliteClient.ts";
8
+
9
+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
10
+
11
+layer("042_ProjectionThreadLinkedPullRequest", (it) => {
12
+ it.effect("adds the linked pull request column", () =>
13
+ Effect.gen(function* () {
14
+ const sql = yield* SqlClient.SqlClient;
15
+
16
+ yield* runMigrations({ toMigrationInclusive: 41 });
17
+ yield* runMigrations({ toMigrationInclusive: 42 });
18
+
19
+ const columns = yield* sql<{ readonly name: string }>`
20
+ PRAGMA table_info(projection_threads)
21
+ `;
22
+ assert.ok(columns.some((column) => column.name === "linked_pull_request_json"));
23
+ }),
24
+ );
25
+});
apps/server/src/persistence/Migrations/042_ProjectionThreadLinkedPullRequest.ts
new
+16
@@ -0,0 +1,16 @@
1
+import * as Effect from "effect/Effect";
2
+import * as SqlClient from "effect/unstable/sql/SqlClient";
3
+
4
+export default Effect.gen(function* () {
5
+ const sql = yield* SqlClient.SqlClient;
6
+ const columns = yield* sql<{ readonly name: string }>`
7
+ PRAGMA table_info(projection_threads)
8
+ `;
9
+
10
+ if (!columns.some((column) => column.name === "linked_pull_request_json")) {
11
+ yield* sql`
12
+ ALTER TABLE projection_threads
13
+ ADD COLUMN linked_pull_request_json TEXT
14
+ `;
15
+ }
16
+});
apps/server/src/persistence/Services/ProjectionThreads.ts
+2
@@ -14,6 +14,7 @@ import {
14
ProjectId,
15
ProviderInteractionMode,
16
RuntimeMode,
17
+ ThreadLinkedPullRequest,
18
ThreadId,
19
TurnId,
20
} from "@t3tools/contracts";
@@ -33,6 +34,7 @@ export const ProjectionThread = Schema.Struct({
34
interactionMode: ProviderInteractionMode,
35
branch: Schema.NullOr(Schema.String),
36
worktreePath: Schema.NullOr(Schema.String),
37
+ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
38
latestTurnId: Schema.NullOr(TurnId),
39
createdAt: IsoDateTime,
40
updatedAt: IsoDateTime,
apps/web/src/components/ChatMarkdown.test.tsx
+8
-1
@@ -11,10 +11,17 @@ vi.mock("../state/session", async (importOriginal) => ({
11
usePreparedConnection: () => ({ _tag: "Loading" }),
12
}));
13
vi.mock("../state/entities", () => ({
14
+ readThreadShell: () => null,
15
useActiveEnvironmentId: () => EnvironmentId.make("env-windows"),
16
+ useProjects: () => [],
17
}));
18
vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => vi.fn() }));
17
-vi.mock("~/lib/openPullRequestLink", () => ({ useOpenChangeRequestLink: () => vi.fn() }));
19
+vi.mock("~/lib/openPullRequestLink", () => ({
20
+ findProjectForChangeRequest: () => undefined,
21
+ matchesLinkedPullRequestUrl: () => false,
22
+ parseChangeRequestUrl: () => null,
23
+ useOpenChangeRequestLink: () => vi.fn(),
24
+}));
25
26
import ChatMarkdown, { orderedListGutterStyle } from "./ChatMarkdown";
27
apps/web/src/components/ChatMarkdown.tsx
+99
-3
@@ -13,7 +13,11 @@ import {
13
TriangleAlertIcon,
14
WrapTextIcon,
15
} from "lucide-react";
16
-import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
16
+import type {
17
+ ScopedThreadRef,
18
+ ServerProviderSkill,
19
+ ThreadLinkedPullRequest,
20
+} from "@t3tools/contracts";
21
import {
22
isAtomCommandInterrupted,
23
squashAtomCommandFailure,
@@ -88,7 +92,7 @@ import { readLocalApi } from "../localApi";
92
import { useAssetUrlState } from "../assets/assetUrls";
93
import { cn } from "../lib/utils";
94
import { useRightPanelStore } from "../rightPanelStore";
91
-import { useActiveEnvironmentId } from "../state/entities";
95
+import { readThreadShell, useActiveEnvironmentId, useProjects } from "../state/entities";
96
import { serverEnvironment } from "../state/server";
97
import { assetEnvironment } from "../state/assets";
98
import { usePreparedConnection } from "../state/session";
@@ -96,13 +100,19 @@ import { previewEnvironment } from "../state/preview";
100
import { useAtomCommand } from "../state/use-atom-command";
101
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
102
import { projectEnvironment } from "../state/projects";
103
+import { threadEnvironment } from "../state/threads";
104
import {
105
claimWorkspaceBasenameLookup,
106
needsWorkspaceBasenameLookup,
107
pickWorkspaceBasenameMatch,
108
WORKSPACE_BASENAME_LOOKUP_LIMIT,
109
} from "../workspaceBasenameLookup";
105
-import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
110
+import {
111
+ findProjectForChangeRequest,
112
+ matchesLinkedPullRequestUrl,
113
+ parseChangeRequestUrl,
114
+ useOpenChangeRequestLink,
115
+} from "~/lib/openPullRequestLink";
116
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
117
import { isPreviewSupportedInRuntime } from "../previewStateStore";
118
import {
@@ -1472,9 +1482,16 @@ function ChatMarkdown({
1482
const openPreview = useAtomCommand(previewEnvironment.open, {
1483
reportFailure: false,
1484
});
1485
+ const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
1486
+ reportFailure: false,
1487
+ });
1488
const preparedConnection = usePreparedConnection(threadRef?.environmentId ?? null);
1489
const environmentId = useActiveEnvironmentId();
1490
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
1491
+ const threadServerConfig = useAtomValue(
1492
+ serverEnvironment.configValueAtom(threadRef?.environmentId ?? environmentId),
1493
+ );
1494
+ const projects = useProjects();
1495
const openInPreferredEditor = useOpenInPreferredEditor(
1496
environmentId,
1497
serverConfig?.availableEditors ?? [],
@@ -1528,6 +1545,54 @@ function ChatMarkdown({
1545
event.clipboardData.setData("text/html", payload.html);
1546
}, []);
1547
const openChangeRequestLink = useOpenChangeRequestLink(threadRef);
1548
+ const resolveThreadPullRequest = useCallback(
1549
+ (href: string): ThreadLinkedPullRequest | null => {
1550
+ if (
1551
+ threadRef === undefined ||
1552
+ readThreadShell(threadRef) === null ||
1553
+ threadServerConfig?.environment.capabilities.threadPullRequestLinking !== true
1554
+ ) {
1555
+ return null;
1556
+ }
1557
+ const parsed = parseChangeRequestUrl(href);
1558
+ if (parsed === null) return null;
1559
+ const project = findProjectForChangeRequest(
1560
+ projects.filter((candidate) => candidate.environmentId === threadRef.environmentId),
1561
+ parsed,
1562
+ );
1563
+ if (project === undefined) return null;
1564
+ return {
1565
+ projectId: project.id,
1566
+ repository: project.repositoryIdentity?.displayName ?? parsed.repository,
1567
+ number: parsed.number,
1568
+ url: href,
1569
+ };
1570
+ },
1571
+ [projects, threadRef, threadServerConfig],
1572
+ );
1573
+ const updateThreadPullRequestLink = useCallback(
1574
+ async (href: string, linked: boolean) => {
1575
+ if (threadRef === undefined) return;
1576
+ const linkedPullRequest = linked ? resolveThreadPullRequest(href) : null;
1577
+ if (linked && linkedPullRequest === null) {
1578
+ throw new Error("The pull request is not available in this environment.");
1579
+ }
1580
+ if (!linked) {
1581
+ const currentPullRequest = readThreadShell(threadRef)?.linkedPullRequest;
1582
+ if (currentPullRequest == null || !matchesLinkedPullRequestUrl(currentPullRequest, href)) {
1583
+ return;
1584
+ }
1585
+ }
1586
+ const result = await updateThreadMetadata({
1587
+ environmentId: threadRef.environmentId,
1588
+ input: { threadId: threadRef.threadId, linkedPullRequest },
1589
+ });
1590
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1591
+ throw squashAtomCommandFailure(result);
1592
+ }
1593
+ },
1594
+ [resolveThreadPullRequest, threadRef, updateThreadMetadata],
1595
+ );
1596
const openExternalLinkInPreview = useCallback(
1597
(url: string) => {
1598
if (!threadRef) {
@@ -1760,9 +1825,20 @@ function ChatMarkdown({
1825
event.stopPropagation();
1826
const api = readLocalApi();
1827
if (!api) return;
1828
+ const pullRequest = resolveThreadPullRequest(href);
1829
+ const currentPullRequest =
1830
+ threadRef === undefined ? null : readThreadShell(threadRef)?.linkedPullRequest;
1831
+ const threadLinkAction =
1832
+ currentPullRequest != null &&
1833
+ matchesLinkedPullRequestUrl(currentPullRequest, href)
1834
+ ? "unlink-from-thread"
1835
+ : pullRequest === null
1836
+ ? undefined
1837
+ : "link-to-thread";
1838
void showExternalLinkContextMenu({
1839
href,
1840
canOpenInPreview,
1841
+ threadLinkAction,
1842
position: { x: event.clientX, y: event.clientY },
1843
showContextMenu: (items, position) => api.contextMenu.show(items, position),
1844
openInPreview: async (target) => {
@@ -1776,8 +1852,25 @@ function ChatMarkdown({
1852
},
1853
openExternal: (target) => api.shell.openExternal(target),
1854
copyLink: (target) => writeTextToClipboard(target, "link"),
1855
+ updateThreadLink: updateThreadPullRequestLink,
1856
reportFailure: (operation, cause) => {
1857
reportMarkdownActionFailure({ operation, target: href }, cause);
1858
+ if (
1859
+ operation === "link-pull-request-to-thread" ||
1860
+ operation === "unlink-pull-request-from-thread"
1861
+ ) {
1862
+ toastManager.add(
1863
+ stackedThreadToast({
1864
+ type: "error",
1865
+ title:
1866
+ operation === "link-pull-request-to-thread"
1867
+ ? "Unable to link pull request"
1868
+ : "Unable to unlink pull request",
1869
+ description:
1870
+ cause instanceof Error ? cause.message : "The request failed.",
1871
+ }),
1872
+ );
1873
+ }
1874
},
1875
});
1876
}}
@@ -1900,12 +1993,15 @@ function ChatMarkdown({
1993
onTaskListChange,
1994
openFileInPanel,
1995
openInPreferredEditor,
1996
+ openChangeRequestLink,
1997
openExternalLinkInPreview,
1998
openMarkdownFileInPreview,
1999
+ resolveThreadPullRequest,
2000
resolvedTheme,
2001
skills,
2002
text,
2003
threadRef,
2004
+ updateThreadPullRequestLink,
2005
]);
2006
/* eslint-enable react/no-unstable-nested-components */
2007
apps/web/src/components/ChatMarkdown.workspace-images.test.tsx
+8
-1
@@ -24,10 +24,17 @@ vi.mock("../state/session", async (importOriginal) => ({
24
usePreparedConnection: () => ({ _tag: "Loading" }),
25
}));
26
vi.mock("../state/entities", () => ({
27
+ readThreadShell: () => null,
28
useActiveEnvironmentId: () => EnvironmentId.make("env-windows"),
29
+ useProjects: () => [],
30
}));
31
vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => vi.fn() }));
30
-vi.mock("~/lib/openPullRequestLink", () => ({ useOpenChangeRequestLink: () => vi.fn() }));
32
+vi.mock("~/lib/openPullRequestLink", () => ({
33
+ findProjectForChangeRequest: () => undefined,
34
+ matchesLinkedPullRequestUrl: () => false,
35
+ parseChangeRequestUrl: () => null,
36
+ useOpenChangeRequestLink: () => vi.fn(),
37
+}));
38
39
import ChatMarkdown from "./ChatMarkdown";
40
apps/web/src/components/ChatView.tsx
+38
-7
@@ -302,6 +302,7 @@ import {
302
import {
303
resolveDisplayedThreadPr,
304
threadChangeRequestSnapshotsAtom,
305
+ useLinkedThreadPullRequest,
306
} from "./ThreadStatusIndicators";
307
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
308
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
@@ -3412,24 +3413,48 @@ function ChatViewContent(props: ChatViewProps) {
3413
);
3414
// The thread's own change request, placed against the project it belongs to. Without a
3415
// project there is nothing to resolve it against, so the caller falls back to the browser.
3415
- const threadRepository = activeProject?.repositoryIdentity?.displayName ?? null;
3416
+ const linkedThreadPullRequest = activeThread?.linkedPullRequest ?? null;
3417
+ const activeProjectRepository = activeProject?.repositoryIdentity?.displayName ?? null;
3418
+ const threadRepository = linkedThreadPullRequest?.repository ?? activeProjectRepository;
3419
const openThreadPullRequest = useCallback(
3420
+ (number: number) => {
3421
+ if (!supportsPullRequests || !activeThreadRef) {
3422
+ return;
3423
+ }
3424
+ const projectId = linkedThreadPullRequest?.projectId ?? activeProject?.id;
3425
+ const repository = linkedThreadPullRequest?.repository ?? activeProjectRepository;
3426
+ if (projectId === undefined || repository === null) return;
3427
+ useRightPanelStore.getState().openPullRequest(activeThreadRef, {
3428
+ projectId,
3429
+ repository,
3430
+ number,
3431
+ });
3432
+ },
3433
+ [
3434
+ activeProject,
3435
+ activeProjectRepository,
3436
+ activeThreadRef,
3437
+ linkedThreadPullRequest,
3438
+ supportsPullRequests,
3439
+ ],
3440
+ );
3441
+ const openProjectPullRequest = useCallback(
3442
(number: number) => {
3443
if (
3444
!supportsPullRequests ||
3445
!activeThreadRef ||
3446
!activeProject ||
3422
- threadRepository === null
3447
+ activeProjectRepository === null
3448
) {
3449
return;
3450
}
3451
useRightPanelStore.getState().openPullRequest(activeThreadRef, {
3452
projectId: activeProject.id,
3428
- repository: threadRepository,
3453
+ repository: activeProjectRepository,
3454
number,
3455
});
3456
},
3432
- [activeProject, activeThreadRef, supportsPullRequests, threadRepository],
3457
+ [activeProject, activeProjectRepository, activeThreadRef, supportsPullRequests],
3458
);
3459
const togglePreviewPanel = useCallback(() => {
3460
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
@@ -4307,11 +4332,17 @@ function ChatViewContent(props: ChatViewProps) {
4332
: null;
4333
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
4334
const autoSettleOnMerge = useClientSettings((settings) => settings.sidebarAutoSettleOnMerge);
4335
+ const linkedPullRequestStatus = useLinkedThreadPullRequest(
4336
+ activeThreadRef?.environmentId ?? null,
4337
+ linkedThreadPullRequest,
4338
+ );
4339
const activeThreadPr = resolveDisplayedThreadPr({
4340
threadBranch: activeThread?.branch ?? null,
4341
gitStatus: gitStatusQuery.data ?? null,
4342
snapshot: activeThreadKey ? changeRequestSnapshotByKey.get(activeThreadKey) : undefined,
4343
retainTerminalOnBranchMismatch: activeThread?.worktreePath === null,
4344
+ linkedPullRequest: linkedThreadPullRequest,
4345
+ linkedPullRequestStatus,
4346
});
4347
// The right panel offers the thread's own change request, so it can only offer it once the
4348
// branch has one; until then the picker says so rather than opening an empty panel.
@@ -6578,7 +6609,7 @@ function ChatViewContent(props: ChatViewProps) {
6609
context={
6610
isThreadOwnPullRequest(
6611
{
6581
- projectId: activeProject?.id ?? null,
6612
+ projectId: linkedThreadPullRequest?.projectId ?? activeProject?.id ?? null,
6613
repository: threadRepository,
6614
number: activeThreadPr?.number ?? null,
6615
},
@@ -6651,9 +6682,9 @@ function ChatViewContent(props: ChatViewProps) {
6682
>
6683
{!rightPanelOpen ? panelLayoutControls : null}
6684
<ChatHeader
6654
- {...(!supportsPullRequests || threadRepository === null
6685
+ {...(!supportsPullRequests || activeProjectRepository === null
6686
? {}
6656
- : { onOpenPullRequest: openThreadPullRequest })}
6687
+ : { onOpenPullRequest: openProjectPullRequest })}
6688
activeThreadEnvironmentId={activeThread.environmentId}
6689
activeThreadId={activeThread.id}
6690
{...(routeKind === "draft" && draftId ? { draftId } : {})}
apps/web/src/components/LegacySidebar.tsx
+14
-6
@@ -20,6 +20,7 @@ import {
20
terminalStatusFromRunningIds,
21
ThreadStatusLabel,
22
ThreadWorktreeIndicator,
23
+ useLinkedThreadPullRequest,
24
} from "./ThreadStatusIndicators";
25
import { ProjectFavicon } from "./ProjectFavicon";
26
import { useAtomValue } from "@effect/atom-react";
@@ -416,7 +417,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
417
const threadProjectCwd = threadProject?.workspaceRoot ?? null;
418
const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd;
419
const gitStatus = useEnvironmentQuery(
419
- thread.branch != null && gitCwd !== null
420
+ thread.linkedPullRequest == null && thread.branch != null && gitCwd !== null
421
? vcsEnvironment.status({
422
environmentId: thread.environmentId,
423
input: { cwd: gitCwd },
@@ -457,11 +458,18 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
458
lastVisitedAt,
459
},
460
});
460
- const pr = resolveThreadPr({
461
- threadBranch: thread.branch,
462
- gitStatus: gitStatus.data,
463
- });
464
- const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
461
+ const linkedPullRequestStatus = useLinkedThreadPullRequest(
462
+ thread.environmentId,
463
+ thread.linkedPullRequest,
464
+ );
465
+ const pr =
466
+ thread.linkedPullRequest == null
467
+ ? resolveThreadPr({ threadBranch: thread.branch, gitStatus: gitStatus.data })
468
+ : (linkedPullRequestStatus?.pr ?? null);
469
+ const prStatus = prStatusIndicator(
470
+ pr,
471
+ linkedPullRequestStatus?.sourceControlProvider ?? gitStatus.data?.sourceControlProvider,
472
+ );
473
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
474
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
475
const threadMetaClassName = isConfirmingArchive
apps/web/src/components/Sidebar.tsx
+19
-1
@@ -156,6 +156,7 @@ import {
156
threadChangeRequestSnapshotsAtom,
157
type ThreadChangeRequestSnapshot,
158
type TerminalStatusIndicator,
159
+ useLinkedThreadPullRequest,
160
} from "./ThreadStatusIndicators";
161
import {
162
resolveSnoozePresets,
@@ -787,6 +788,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
788
const terminalProcessCount = runningTerminalIds.length;
789
790
const gitCwd = thread.worktreePath ?? props.projectCwd;
791
+ const linkedPullRequestStatus = useLinkedThreadPullRequest(
792
+ thread.environmentId,
793
+ thread.linkedPullRequest,
794
+ );
795
const gitStatus = useEnvironmentQuery(
796
(thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
797
? vcsEnvironment.status({
@@ -801,6 +806,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
806
gitStatus: gitStatus.data,
807
snapshot: changeRequestSnapshot,
808
retainTerminalOnBranchMismatch,
809
+ linkedPullRequest: thread.linkedPullRequest,
810
+ linkedPullRequestStatus,
811
});
812
813
// Same semantics as the legacy sidebar (never-visited counts as read):
@@ -901,6 +908,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
908
gitStatus: gitStatus.data,
909
snapshot: changeRequestSnapshot,
910
retainTerminalOnBranchMismatch,
911
+ linkedPullRequest: thread.linkedPullRequest,
912
+ linkedPullRequestStatus,
913
});
914
const prStatus = prStatusIndicator(pr, prProvider);
915
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
@@ -910,15 +919,19 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
919
gitStatus: gitStatus.data,
920
snapshot: changeRequestSnapshot,
921
retainTerminalOnBranchMismatch,
922
+ linkedPullRequest: thread.linkedPullRequest,
923
+ linkedPullRequestStatus,
924
});
925
if (nextSnapshot === undefined) return;
926
onChangeRequestSnapshot(threadKey, nextSnapshot);
927
}, [
928
changeRequestSnapshot,
929
gitStatus.data,
930
+ linkedPullRequestStatus,
931
onChangeRequestSnapshot,
932
retainTerminalOnBranchMismatch,
933
thread.branch,
934
+ thread.linkedPullRequest,
935
threadKey,
936
]);
937
@@ -2039,7 +2052,12 @@ export default function Sidebar() {
2052
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
2053
const snapshot = changeRequestSnapshotByKey.get(threadKey);
2054
const changeRequest =
2042
- snapshot != null && (thread.worktreePath === null || snapshot.branch === thread.branch)
2055
+ snapshot != null &&
2056
+ (thread.linkedPullRequest == null
2057
+ ? thread.worktreePath === null || snapshot.branch === thread.branch
2058
+ : snapshot.linkedPullRequest?.projectId === thread.linkedPullRequest.projectId &&
2059
+ snapshot.linkedPullRequest.repository === thread.linkedPullRequest.repository &&
2060
+ snapshot.linkedPullRequest.number === thread.linkedPullRequest.number)
2061
? snapshot.pr
2062
: null;
2063
// Snooze outranks settlement and pinning until the thread wakes.
apps/web/src/components/ThreadStatusIndicators.test.ts
+119
@@ -101,6 +101,12 @@ describe("resolveThreadPr", () => {
101
describe("resolveDisplayedThreadPr + nextThreadChangeRequestSnapshot", () => {
102
const featureBranch = "feature/current";
103
const mergedPr = mergedFeaturePr();
104
+ const linkedPullRequest = {
105
+ projectId: ProjectId.make("project-1"),
106
+ repository: "pingdotgg/t3code",
107
+ number: 42,
108
+ url: "https://github.com/pingdotgg/t3code/pull/42",
109
+ };
110
const provider = {
111
kind: "github" as const,
112
name: "GitHub",
@@ -132,6 +138,119 @@ describe("resolveDisplayedThreadPr + nextThreadChangeRequestSnapshot", () => {
138
).toEqual(provider);
139
});
140
141
+ it("shows a linked pull request when the checkout has a different branch", () => {
142
+ const linkedPullRequestStatus = {
143
+ pr: mergedPr,
144
+ sourceControlProvider: provider,
145
+ };
146
+
147
+ expect(
148
+ resolveDisplayedThreadPr({
149
+ threadBranch: "feature/other",
150
+ gitStatus: status({ refName: "feature/other", pr: null }),
151
+ snapshot: undefined,
152
+ retainTerminalOnBranchMismatch: false,
153
+ linkedPullRequest,
154
+ linkedPullRequestStatus,
155
+ }),
156
+ ).toEqual(mergedPr);
157
+ expect(
158
+ resolveDisplayedThreadPrProvider({
159
+ threadBranch: "feature/other",
160
+ gitStatus: status({ refName: "feature/other", pr: null }),
161
+ snapshot: undefined,
162
+ retainTerminalOnBranchMismatch: false,
163
+ linkedPullRequest,
164
+ linkedPullRequestStatus,
165
+ }),
166
+ ).toEqual(provider);
167
+ expect(
168
+ nextThreadChangeRequestSnapshot({
169
+ threadBranch: "feature/other",
170
+ gitStatus: status({ refName: "feature/other", pr: null }),
171
+ snapshot: undefined,
172
+ retainTerminalOnBranchMismatch: false,
173
+ linkedPullRequest,
174
+ linkedPullRequestStatus,
175
+ }),
176
+ ).toEqual({
177
+ branch: "feature/other",
178
+ pr: mergedPr,
179
+ sourceControlProvider: provider,
180
+ linkedPullRequest,
181
+ });
182
+ });
183
+
184
+ it("keeps a matching linked pull request snapshot while its status reloads", () => {
185
+ const snapshot = {
186
+ ...snapshotFor(featureBranch, mergedPr, provider),
187
+ linkedPullRequest,
188
+ };
189
+
190
+ expect(
191
+ resolveDisplayedThreadPr({
192
+ threadBranch: null,
193
+ gitStatus: null,
194
+ snapshot,
195
+ retainTerminalOnBranchMismatch: false,
196
+ linkedPullRequest,
197
+ linkedPullRequestStatus: null,
198
+ }),
199
+ ).toEqual(mergedPr);
200
+ expect(
201
+ nextThreadChangeRequestSnapshot({
202
+ threadBranch: null,
203
+ gitStatus: null,
204
+ snapshot,
205
+ retainTerminalOnBranchMismatch: false,
206
+ linkedPullRequest,
207
+ linkedPullRequestStatus: null,
208
+ }),
209
+ ).toBeUndefined();
210
+ });
211
+
212
+ it("clears an old snapshot when a different pull request is linked", () => {
213
+ const snapshot = {
214
+ ...snapshotFor(featureBranch, mergedPr, provider),
215
+ linkedPullRequest: { ...linkedPullRequest, number: 41 },
216
+ };
217
+
218
+ expect(
219
+ nextThreadChangeRequestSnapshot({
220
+ threadBranch: featureBranch,
221
+ gitStatus: null,
222
+ snapshot,
223
+ retainTerminalOnBranchMismatch: true,
224
+ linkedPullRequest,
225
+ linkedPullRequestStatus: null,
226
+ }),
227
+ ).toBeNull();
228
+ });
229
+
230
+ it("removes a linked pull request snapshot after the link is cleared", () => {
231
+ const snapshot = {
232
+ ...snapshotFor(featureBranch, mergedPr, provider),
233
+ linkedPullRequest,
234
+ };
235
+
236
+ expect(
237
+ resolveDisplayedThreadPr({
238
+ threadBranch: featureBranch,
239
+ gitStatus: status({ refName: "main", pr: null }),
240
+ snapshot,
241
+ retainTerminalOnBranchMismatch: true,
242
+ }),
243
+ ).toBeNull();
244
+ expect(
245
+ nextThreadChangeRequestSnapshot({
246
+ threadBranch: featureBranch,
247
+ gitStatus: null,
248
+ snapshot,
249
+ retainTerminalOnBranchMismatch: true,
250
+ }),
251
+ ).toBeNull();
252
+ });
253
+
254
it("after caching a merged PR, resolves main status back to the cached feature PR", () => {
255
const matchingStatus = status({
256
refName: featureBranch,
apps/web/src/components/ThreadStatusIndicators.tsx
+136
-12
@@ -3,7 +3,8 @@ import {
3
scopedThreadKey,
4
scopeThreadRef,
5
} from "@t3tools/client-runtime/environment";
6
-import type { VcsStatusResult } from "@t3tools/contracts";
6
+import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
7
+import type { EnvironmentId, ThreadLinkedPullRequest, VcsStatusResult } from "@t3tools/contracts";
8
import { Atom } from "effect/unstable/reactivity";
9
import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
10
import { useMemo } from "react";
@@ -11,6 +12,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
12
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
13
import { useProject } from "../state/entities";
14
import { useEnvironmentQuery } from "../state/query";
15
+import { linkedPullRequestDetailAtom } from "../state/pullRequests";
16
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
17
import { vcsEnvironment } from "../state/vcs";
18
import { useUiStateStore } from "../uiStateStore";
@@ -37,6 +39,44 @@ export interface TerminalStatusIndicator {
39
40
export type ThreadPr = VcsStatusResult["pr"];
41
42
+export interface LinkedThreadPullRequestStatus {
43
+ readonly pr: NonNullable<ThreadPr>;
44
+ readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
45
+}
46
+
47
+export function useLinkedThreadPullRequest(
48
+ environmentId: EnvironmentId | null,
49
+ linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
50
+): LinkedThreadPullRequestStatus | null {
51
+ const detail = useEnvironmentQuery(
52
+ environmentId === null || linkedPullRequest == null
53
+ ? null
54
+ : linkedPullRequestDetailAtom({
55
+ environmentId,
56
+ input: {
57
+ projectId: linkedPullRequest.projectId,
58
+ repository: linkedPullRequest.repository,
59
+ number: linkedPullRequest.number,
60
+ },
61
+ }),
62
+ ).data;
63
+
64
+ return useMemo(
65
+ () =>
66
+ detail === null
67
+ ? null
68
+ : {
69
+ pr: pullRequestDetailToVcsStatus(detail),
70
+ sourceControlProvider: {
71
+ kind: detail.provider,
72
+ name: detail.provider,
73
+ baseUrl: "",
74
+ },
75
+ },
76
+ [detail],
77
+ );
78
+}
79
+
80
export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
81
switch (state) {
82
case "open":
@@ -136,6 +176,7 @@ export interface ThreadChangeRequestSnapshot {
176
readonly branch: string;
177
readonly pr: NonNullable<ThreadPr>;
178
readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
179
+ readonly linkedPullRequest?: ThreadLinkedPullRequest;
180
}
181
182
export const threadChangeRequestSnapshotsAtom = Atom.make<
@@ -157,6 +198,19 @@ function sourceControlProvidersEqual(
198
return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
199
}
200
201
+function linkedPullRequestsEqual(
202
+ left: ThreadLinkedPullRequest | null | undefined,
203
+ right: ThreadLinkedPullRequest | null | undefined,
204
+): boolean {
205
+ if (left == null || right == null) return left == null && right == null;
206
+ return (
207
+ left.projectId === right.projectId &&
208
+ left.repository === right.repository &&
209
+ left.number === right.number &&
210
+ left.url === right.url
211
+ );
212
+}
213
+
214
export function threadChangeRequestSnapshotsEqual(
215
left: ThreadChangeRequestSnapshot,
216
right: ThreadChangeRequestSnapshot,
@@ -170,7 +224,8 @@ export function threadChangeRequestSnapshotsEqual(
224
left.pr.headRef === right.pr.headRef &&
225
left.pr.state === right.pr.state &&
226
(left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
173
- sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider)
227
+ sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
228
+ linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
229
);
230
}
231
@@ -206,10 +261,32 @@ export function nextThreadChangeRequestSnapshot(input: {
261
gitStatus: VcsStatusResult | null;
262
snapshot: ThreadChangeRequestSnapshot | null | undefined;
263
retainTerminalOnBranchMismatch: boolean;
264
+ linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
265
+ linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
266
}): ThreadChangeRequestSnapshot | null | undefined {
210
- const { threadBranch, gitStatus, snapshot, retainTerminalOnBranchMismatch } = input;
267
+ const {
268
+ threadBranch,
269
+ gitStatus,
270
+ snapshot,
271
+ retainTerminalOnBranchMismatch,
272
+ linkedPullRequest,
273
+ linkedPullRequestStatus,
274
+ } = input;
275
+ if (linkedPullRequest != null) {
276
+ if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
277
+ return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
278
+ ? undefined
279
+ : null;
280
+ }
281
+ return {
282
+ branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
283
+ pr: linkedPullRequestStatus.pr,
284
+ sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
285
+ linkedPullRequest,
286
+ };
287
+ }
288
if (gitStatus === null) {
212
- return undefined;
289
+ return snapshot?.linkedPullRequest === undefined ? undefined : null;
290
}
291
if (threadBranch === null) {
292
return null;
@@ -217,6 +294,7 @@ export function nextThreadChangeRequestSnapshot(input: {
294
if (gitStatus.refName !== threadBranch) {
295
return retainTerminalOnBranchMismatch &&
296
snapshot != null &&
297
+ snapshot.linkedPullRequest === undefined &&
298
isTerminalChangeRequestState(snapshot.pr.state)
299
? undefined
300
: null;
@@ -225,6 +303,7 @@ export function nextThreadChangeRequestSnapshot(input: {
303
if (
304
retainTerminalOnBranchMismatch &&
305
snapshot != null &&
306
+ snapshot.linkedPullRequest === undefined &&
307
isTerminalChangeRequestState(snapshot.pr.state)
308
) {
309
return undefined;
@@ -250,8 +329,25 @@ export function resolveDisplayedThreadPr(input: {
329
gitStatus: VcsStatusResult | null;
330
snapshot: ThreadChangeRequestSnapshot | null | undefined;
331
retainTerminalOnBranchMismatch: boolean;
332
+ linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
333
+ linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
334
}): ThreadPr | null {
254
- const { threadBranch, gitStatus, snapshot, retainTerminalOnBranchMismatch } = input;
335
+ const {
336
+ threadBranch,
337
+ gitStatus,
338
+ snapshot,
339
+ retainTerminalOnBranchMismatch,
340
+ linkedPullRequest,
341
+ linkedPullRequestStatus,
342
+ } = input;
343
+ if (linkedPullRequest != null) {
344
+ return (
345
+ linkedPullRequestStatus?.pr ??
346
+ (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
347
+ ? (snapshot?.pr ?? null)
348
+ : null)
349
+ );
350
+ }
351
if (
352
threadBranch !== null &&
353
gitStatus !== null &&
@@ -265,6 +361,7 @@ export function resolveDisplayedThreadPr(input: {
361
threadBranch !== null &&
362
retainTerminalOnBranchMismatch &&
363
snapshot != null &&
364
+ snapshot.linkedPullRequest === undefined &&
365
isTerminalChangeRequestState(snapshot.pr.state)
366
) {
367
return snapshot.pr;
@@ -278,8 +375,25 @@ export function resolveDisplayedThreadPrProvider(input: {
375
gitStatus: VcsStatusResult | null;
376
snapshot: ThreadChangeRequestSnapshot | null | undefined;
377
retainTerminalOnBranchMismatch: boolean;
378
+ linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
379
+ linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
380
}): VcsStatusResult["sourceControlProvider"] | undefined {
282
- const { threadBranch, gitStatus, snapshot, retainTerminalOnBranchMismatch } = input;
381
+ const {
382
+ threadBranch,
383
+ gitStatus,
384
+ snapshot,
385
+ retainTerminalOnBranchMismatch,
386
+ linkedPullRequest,
387
+ linkedPullRequestStatus,
388
+ } = input;
389
+ if (linkedPullRequest != null) {
390
+ return (
391
+ linkedPullRequestStatus?.sourceControlProvider ??
392
+ (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
393
+ ? snapshot?.sourceControlProvider
394
+ : undefined)
395
+ );
396
+ }
397
if (
398
threadBranch !== null &&
399
gitStatus !== null &&
@@ -293,6 +407,7 @@ export function resolveDisplayedThreadPrProvider(input: {
407
threadBranch !== null &&
408
retainTerminalOnBranchMismatch &&
409
snapshot != null &&
410
+ snapshot.linkedPullRequest === undefined &&
411
isTerminalChangeRequestState(snapshot.pr.state)
412
) {
413
return snapshot.sourceControlProvider;
@@ -417,19 +532,28 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
532
);
533
const threadProjectCwd = threadProject?.workspaceRoot ?? null;
534
const gitCwd = thread.worktreePath ?? threadProjectCwd;
535
+ const linkedPullRequest = useLinkedThreadPullRequest(
536
+ thread.environmentId,
537
+ thread.linkedPullRequest,
538
+ );
539
const gitStatus = useEnvironmentQuery(
421
- (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
540
+ thread.linkedPullRequest == null &&
541
+ (thread.branch != null || thread.worktreePath !== null) &&
542
+ gitCwd !== null
543
? vcsEnvironment.status({
544
environmentId: thread.environmentId,
545
input: { cwd: gitCwd },
546
})
547
: null,
548
);
428
- const pr = resolveThreadPr({
429
- threadBranch: thread.branch,
430
- gitStatus: gitStatus.data,
431
- });
432
- const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
549
+ const pr =
550
+ thread.linkedPullRequest == null
551
+ ? resolveThreadPr({ threadBranch: thread.branch, gitStatus: gitStatus.data })
552
+ : (linkedPullRequest?.pr ?? null);
553
+ const prStatus = prStatusIndicator(
554
+ pr,
555
+ linkedPullRequest?.sourceControlProvider ?? gitStatus.data?.sourceControlProvider,
556
+ );
557
const threadStatus = resolveThreadStatusPill({
558
thread: {
559
...thread,
apps/web/src/components/chat/externalLinkContextMenu.test.ts
+47
-1
@@ -2,11 +2,20 @@ import { describe, expect, it, vi } from "vite-plus/test";
2
3
import { resolveExternalWebLinkHost, showExternalLinkContextMenu } from "./externalLinkContextMenu";
4
5
-function createHarness(selection: "open-in-preview" | "open-external" | "copy-link" | null) {
5
+function createHarness(
6
+ selection:
7
+ | "open-in-preview"
8
+ | "open-external"
9
+ | "copy-link"
10
+ | "link-to-thread"
11
+ | "unlink-from-thread"
12
+ | null,
13
+) {
14
const showContextMenu = vi.fn().mockResolvedValue(selection);
15
const openInPreview = vi.fn().mockResolvedValue(undefined);
16
const openExternal = vi.fn().mockResolvedValue(undefined);
17
const copyLink = vi.fn().mockResolvedValue(undefined);
18
+ const updateThreadLink = vi.fn().mockResolvedValue(undefined);
19
const reportFailure = vi.fn();
20
21
return {
@@ -14,6 +23,7 @@ function createHarness(selection: "open-in-preview" | "open-external" | "copy-li
23
openInPreview,
24
openExternal,
25
copyLink,
26
+ updateThreadLink,
27
reportFailure,
28
};
29
}
@@ -71,6 +81,27 @@ describe("external chat link context menu", () => {
81
expect(harness.openExternal).not.toHaveBeenCalled();
82
});
83
84
+ it.each([
85
+ ["link-to-thread", "Link to thread", true],
86
+ ["unlink-from-thread", "Unlink from thread", false],
87
+ ] as const)("offers and runs the %s action", async (action, label, linked) => {
88
+ const harness = createHarness(action);
89
+ const href = "https://github.com/pingdotgg/t3code/pull/42";
90
+
91
+ await showExternalLinkContextMenu({
92
+ href,
93
+ threadLinkAction: action,
94
+ position: { x: 1, y: 2 },
95
+ ...harness,
96
+ });
97
+
98
+ expect(harness.showContextMenu).toHaveBeenCalledWith(
99
+ expect.arrayContaining([{ id: action, label }]),
100
+ { x: 1, y: 2 },
101
+ );
102
+ expect(harness.updateThreadLink).toHaveBeenCalledWith(href, linked);
103
+ });
104
+
105
it.each([
106
["open-in-preview" as const, "openInPreview" as const],
107
["open-external" as const, "openExternal" as const],
@@ -132,6 +163,21 @@ describe("external chat link context menu", () => {
163
expect(harness.reportFailure).toHaveBeenCalledWith(operation, cause);
164
});
165
166
+ it("reports a failed thread link action", async () => {
167
+ const harness = createHarness("link-to-thread");
168
+ const cause = new Error("thread update failed");
169
+ harness.updateThreadLink.mockRejectedValue(cause);
170
+
171
+ await showExternalLinkContextMenu({
172
+ href: "https://github.com/pingdotgg/t3code/pull/42",
173
+ threadLinkAction: "link-to-thread",
174
+ position: { x: 1, y: 2 },
175
+ ...harness,
176
+ });
177
+
178
+ expect(harness.reportFailure).toHaveBeenCalledWith("link-pull-request-to-thread", cause);
179
+ });
180
+
181
it.each([
182
["https://example.com", "example.com"],
183
["http://localhost:3000/path", "localhost"],
apps/web/src/components/chat/externalLinkContextMenu.ts
+32
-4
@@ -1,17 +1,26 @@
1
import type { ContextMenuItem } from "@t3tools/contracts";
2
3
-export type ExternalLinkContextMenuAction = "open-in-preview" | "open-external" | "copy-link";
3
+export type ExternalLinkContextMenuAction =
4
+ | "open-in-preview"
5
+ | "open-external"
6
+ | "copy-link"
7
+ | "link-to-thread"
8
+ | "unlink-from-thread";
9
10
export type ExternalLinkContextMenuFailureOperation =
11
| "show-link-context-menu"
12
| "open-link-in-preview"
13
| "open-link-external"
9
- | "copy-link";
14
+ | "copy-link"
15
+ | "link-pull-request-to-thread"
16
+ | "unlink-pull-request-from-thread";
17
18
const FAILURE_OPERATION_BY_ACTION = {
19
"open-in-preview": "open-link-in-preview",
20
"open-external": "open-link-external",
21
"copy-link": "copy-link",
22
+ "link-to-thread": "link-pull-request-to-thread",
23
+ "unlink-from-thread": "unlink-pull-request-from-thread",
24
} as const satisfies Record<ExternalLinkContextMenuAction, ExternalLinkContextMenuFailureOperation>;
25
26
const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [
@@ -28,10 +37,20 @@ const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [
37
*/
38
export function externalLinkContextMenuItems(options: {
39
readonly canOpenInPreview: boolean;
40
+ readonly threadLinkAction?: "link-to-thread" | "unlink-from-thread" | undefined;
41
}): readonly ContextMenuItem<ExternalLinkContextMenuAction>[] {
32
- return options.canOpenInPreview
42
+ const items = options.canOpenInPreview
43
? EXTERNAL_LINK_CONTEXT_MENU_ITEMS
44
: EXTERNAL_LINK_CONTEXT_MENU_ITEMS.filter((item) => item.id !== "open-in-preview");
45
+ if (options.threadLinkAction === undefined) return items;
46
+ return [
47
+ {
48
+ id: options.threadLinkAction,
49
+ label:
50
+ options.threadLinkAction === "link-to-thread" ? "Link to thread" : "Unlink from thread",
51
+ },
52
+ ...items,
53
+ ];
54
}
55
56
interface ShowExternalLinkContextMenuOptions {
@@ -39,6 +58,7 @@ interface ShowExternalLinkContextMenuOptions {
58
readonly position: { readonly x: number; readonly y: number };
59
/** Absent means yes, which is what every caller before the browser could be missing meant. */
60
readonly canOpenInPreview?: boolean;
61
+ readonly threadLinkAction?: "link-to-thread" | "unlink-from-thread" | undefined;
62
readonly showContextMenu: (
63
items: readonly ContextMenuItem<ExternalLinkContextMenuAction>[],
64
position: { readonly x: number; readonly y: number },
@@ -46,6 +66,7 @@ interface ShowExternalLinkContextMenuOptions {
66
readonly openInPreview: (href: string) => Promise<void>;
67
readonly openExternal: (href: string) => Promise<void>;
68
readonly copyLink: (href: string) => Promise<unknown>;
69
+ readonly updateThreadLink?: (href: string, linked: boolean) => Promise<void>;
70
readonly reportFailure: (
71
operation: ExternalLinkContextMenuFailureOperation,
72
cause: unknown,
@@ -67,15 +88,20 @@ export async function showExternalLinkContextMenu({
88
href,
89
position,
90
canOpenInPreview = true,
91
+ threadLinkAction,
92
showContextMenu,
93
openInPreview,
94
openExternal,
95
copyLink,
96
+ updateThreadLink,
97
reportFailure,
98
}: ShowExternalLinkContextMenuOptions): Promise<void> {
99
let action: ExternalLinkContextMenuAction | null;
100
try {
78
- action = await showContextMenu(externalLinkContextMenuItems({ canOpenInPreview }), position);
101
+ action = await showContextMenu(
102
+ externalLinkContextMenuItems({ canOpenInPreview, threadLinkAction }),
103
+ position,
104
+ );
105
} catch (cause) {
106
reportFailure("show-link-context-menu", cause);
107
return;
@@ -88,6 +114,8 @@ export async function showExternalLinkContextMenu({
114
await openExternal(href);
115
} else if (action === "copy-link") {
116
await copyLink(href);
117
+ } else if (action === "link-to-thread" || action === "unlink-from-thread") {
118
+ await updateThreadLink?.(href, action === "link-to-thread");
119
}
120
} catch (cause) {
121
if (action) reportFailure(FAILURE_OPERATION_BY_ACTION[action], cause);
apps/web/src/lib/openPullRequestLink.test.ts
+32
@@ -3,11 +3,13 @@ import { describe, expect, it, vi } from "vite-plus/test";
3
import {
4
changeRequestRepositoryUrl,
5
findProjectForChangeRequest,
6
+ matchesLinkedPullRequestUrl,
7
openPullRequestLink,
8
parseChangeRequestUrl,
9
PullRequestLinkOpenError,
10
shouldOpenPullRequestExternally,
11
} from "./openPullRequestLink";
12
+import { ProjectId } from "@t3tools/contracts";
13
14
describe("changeRequestRepositoryUrl", () => {
15
it("preserves repository path casing", () => {
@@ -27,6 +29,36 @@ describe("changeRequestRepositoryUrl", () => {
29
});
30
});
31
32
+describe("matchesLinkedPullRequestUrl", () => {
33
+ const linkedPullRequest = {
34
+ projectId: ProjectId.make("project-1"),
35
+ repository: "pingdotgg/t3code",
36
+ number: 42,
37
+ url: "https://github.com/pingdotgg/t3code/pull/42",
38
+ };
39
+
40
+ it("matches the same pull request without looking up its project", () => {
41
+ expect(
42
+ matchesLinkedPullRequestUrl(
43
+ linkedPullRequest,
44
+ "https://github.com/PingDotGG/T3Code/pull/42/files",
45
+ ),
46
+ ).toBe(true);
47
+ });
48
+
49
+ it("rejects a different pull request or host", () => {
50
+ expect(
51
+ matchesLinkedPullRequestUrl(linkedPullRequest, "https://github.com/pingdotgg/t3code/pull/43"),
52
+ ).toBe(false);
53
+ expect(
54
+ matchesLinkedPullRequestUrl(
55
+ linkedPullRequest,
56
+ "https://github.example.com/pingdotgg/t3code/pull/42",
57
+ ),
58
+ ).toBe(false);
59
+ });
60
+});
61
+
62
describe("openPullRequestLink", () => {
63
it("opens the requested pull request URL", async () => {
64
const openExternal = vi.fn(async () => undefined);
apps/web/src/lib/openPullRequestLink.ts
+22
-1
@@ -1,4 +1,9 @@
1
-import type { EnvironmentId, LocalApi, ScopedThreadRef } from "@t3tools/contracts";
1
+import type {
2
+ EnvironmentId,
3
+ LocalApi,
4
+ ScopedThreadRef,
5
+ ThreadLinkedPullRequest,
6
+} from "@t3tools/contracts";
7
import { useNavigate } from "@tanstack/react-router";
8
import * as Schema from "effect/Schema";
9
import { type MouseEvent, useCallback } from "react";
@@ -118,6 +123,22 @@ export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | nu
123
return null;
124
}
125
126
+/** Match a stored PR without requiring its project to remain available. */
127
+export function matchesLinkedPullRequestUrl(
128
+ linkedPullRequest: ThreadLinkedPullRequest,
129
+ targetUrl: string,
130
+): boolean {
131
+ const linked = parseChangeRequestUrl(linkedPullRequest.url);
132
+ const target = parseChangeRequestUrl(targetUrl);
133
+ return (
134
+ linked !== null &&
135
+ target !== null &&
136
+ linked.host === target.host &&
137
+ linked.repository === target.repository &&
138
+ linked.number === target.number
139
+ );
140
+}
141
+
142
/** The repository root behind a recognised change-request URL, without PR-specific state. */
143
export function changeRequestRepositoryUrl(targetUrl: string): string | null {
144
const changeRequest = parseChangeRequestUrl(targetUrl);
apps/web/src/state/pullRequests.ts
+6
-1
@@ -1,5 +1,8 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import { createPullRequestEnvironmentAtoms } from "@t3tools/client-runtime/state/pull-requests";
2
+import {
3
+ createLinkedPullRequestDetailAtomFamily,
4
+ createPullRequestEnvironmentAtoms,
5
+} from "@t3tools/client-runtime/state/pull-requests";
6
import type {
7
EnvironmentId,
8
PullRequestListInput,
@@ -19,6 +22,8 @@ import {
22
import { formatEnvironmentQueryError } from "./query";
23
24
export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime);
25
+export const linkedPullRequestDetailAtom =
26
+ createLinkedPullRequestDetailAtomFamily(connectionAtomRuntime);
27
28
export interface EnvironmentQueryTarget<Input> {
29
readonly environmentId: EnvironmentId;
docs/user/thread-sidebar.md
+4
@@ -7,6 +7,10 @@ one environment.
7
Pinned threads still move to **Settled** when they become inactive. They also move when their pull
8
request merges if **Auto-settle merged threads** is enabled.
9
10
+Right-click a pull request link in a thread and choose **Link to thread** to show that pull request
11
+in the sidebar. The thread settles when the linked pull request merges if **Auto-settle merged
12
+threads** is enabled. Right-click the same link and choose **Unlink from thread** to remove it.
13
+
14
On web and desktop, drag a pinned thread to change its position. On mobile, open the thread's menu
15
and choose **Move up** or **Move down**. The order is stored by the server and appears on your
16
other connected devices.
packages/client-runtime/src/state/pullRequests.ts
+32
-1
@@ -1,4 +1,9 @@
1
-import { WS_METHODS, type PullRequestDiffInput } from "@t3tools/contracts";
1
+import {
2
+ WS_METHODS,
3
+ type PullRequestDetail,
4
+ type PullRequestDiffInput,
5
+ type VcsStatusResult,
6
+} from "@t3tools/contracts";
7
import * as Data from "effect/Data";
8
import * as Effect from "effect/Effect";
9
import * as Option from "effect/Option";
@@ -21,6 +26,32 @@ export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError(
26
"EnvironmentHttpConnectionNotReadyError",
27
)<{ readonly message: string }> {}
28
29
+/** Refresh a linked PR while its thread is visible so merges update the sidebar. */
30
+export function createLinkedPullRequestDetailAtomFamily<R, E>(
31
+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
32
+) {
33
+ return createEnvironmentRpcQueryAtomFamily(runtime, {
34
+ label: "environment-data:pull-requests:linked-detail",
35
+ tag: WS_METHODS.pullRequestsDetail,
36
+ staleTimeMs: 15_000,
37
+ refreshIntervalMs: 30_000,
38
+ });
39
+}
40
+
41
+export function pullRequestDetailToVcsStatus(
42
+ detail: PullRequestDetail,
43
+): NonNullable<VcsStatusResult["pr"]> {
44
+ return {
45
+ number: detail.number,
46
+ title: detail.title,
47
+ url: detail.url,
48
+ baseRef: detail.baseBranch,
49
+ headRef: detail.headBranch,
50
+ state: detail.state,
51
+ updatedAt: detail.updatedAt,
52
+ };
53
+}
54
+
55
/**
56
* Every read shells out to the GitHub CLI, so results are reused for a short while and
57
* refreshed explicitly. Mutations run serially per environment: `gh` actions on the same
packages/client-runtime/src/state/threadReducer.test.ts
+45
@@ -305,6 +305,51 @@ describe("applyThreadDetailEvent", () => {
305
expect(result.thread.modelSelection).toEqual(baseThread.modelSelection);
306
}
307
});
308
+
309
+ it("sets and clears a linked pull request", () => {
310
+ const linkedPullRequest = {
311
+ projectId: ProjectId.make("project-1"),
312
+ repository: "pingdotgg/t3code",
313
+ number: 42,
314
+ url: "https://github.com/pingdotgg/t3code/pull/42",
315
+ };
316
+ const linked = applyThreadDetailEvent(baseThread, {
317
+ ...baseEventFields,
318
+ sequence: 5,
319
+ occurredAt: "2026-04-01T05:00:00.000Z",
320
+ aggregateKind: "thread",
321
+ aggregateId: ThreadId.make("thread-1"),
322
+ type: "thread.meta-updated",
323
+ payload: {
324
+ threadId: ThreadId.make("thread-1"),
325
+ linkedPullRequest,
326
+ updatedAt: "2026-04-01T05:00:00.000Z",
327
+ },
328
+ });
329
+
330
+ expect(linked.kind).toBe("updated");
331
+ if (linked.kind !== "updated") return;
332
+ expect(linked.thread.linkedPullRequest).toEqual(linkedPullRequest);
333
+
334
+ const cleared = applyThreadDetailEvent(linked.thread, {
335
+ ...baseEventFields,
336
+ sequence: 6,
337
+ occurredAt: "2026-04-01T06:00:00.000Z",
338
+ aggregateKind: "thread",
339
+ aggregateId: ThreadId.make("thread-1"),
340
+ type: "thread.meta-updated",
341
+ payload: {
342
+ threadId: ThreadId.make("thread-1"),
343
+ linkedPullRequest: null,
344
+ updatedAt: "2026-04-01T06:00:00.000Z",
345
+ },
346
+ });
347
+
348
+ expect(cleared.kind).toBe("updated");
349
+ if (cleared.kind === "updated") {
350
+ expect(cleared.thread.linkedPullRequest).toBeNull();
351
+ }
352
+ });
353
});
354
355
describe("thread.message-sent", () => {
packages/client-runtime/src/state/threadReducer.ts
+3
@@ -218,6 +218,9 @@ export function applyThreadDetailEvent(
218
...(event.payload.worktreePath !== undefined
219
? { worktreePath: event.payload.worktreePath }
220
: {}),
221
+ ...(event.payload.linkedPullRequest !== undefined
222
+ ? { linkedPullRequest: event.payload.linkedPullRequest }
223
+ : {}),
224
updatedAt: event.payload.updatedAt,
225
},
226
};
packages/contracts/src/environment.ts
+2
@@ -69,6 +69,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
69
/** Server understands regenerateTitle on thread.meta.update. Absent on
70
older servers, so clients hide the action instead of sending it. */
71
threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),
72
+ /** Server persists a pull request reference on thread.meta.update. */
73
+ threadPullRequestLinking: Schema.optionalKey(Schema.Boolean),
74
/** The update path clients should offer for this server. Absent on
75
servers that must be relaunched manually (dev checkouts, Windows
76
foreground runs, pre-update servers). */
packages/contracts/src/orchestration.test.ts
+22
@@ -709,6 +709,28 @@ it.effect("accepts a title regeneration intent in thread.meta.update", () =>
709
}),
710
);
711
712
+it.effect("accepts a linked pull request in thread.meta.update", () =>
713
+ Effect.gen(function* () {
714
+ const linkedPullRequest = {
715
+ projectId: "project-1",
716
+ repository: "pingdotgg/t3code",
717
+ number: 42,
718
+ url: "https://github.com/pingdotgg/t3code/pull/42",
719
+ };
720
+ const parsed = yield* decodeOrchestrationCommand({
721
+ type: "thread.meta.update",
722
+ commandId: "cmd-link-pull-request",
723
+ threadId: "thread-1",
724
+ linkedPullRequest,
725
+ });
726
+
727
+ assert.strictEqual(parsed.type, "thread.meta.update");
728
+ if (parsed.type === "thread.meta.update") {
729
+ assert.deepStrictEqual(parsed.linkedPullRequest, linkedPullRequest);
730
+ }
731
+ }),
732
+);
733
+
734
it.effect("accepts an internal title regeneration completion", () =>
735
Effect.gen(function* () {
736
const parsed = yield* decodeOrchestrationCommand({
packages/contracts/src/orchestration.ts
+12
@@ -387,6 +387,14 @@ export const ThreadTitleRegeneration = Schema.Struct({
387
});
388
export type ThreadTitleRegeneration = typeof ThreadTitleRegeneration.Type;
389
390
+export const ThreadLinkedPullRequest = Schema.Struct({
391
+ projectId: ProjectId,
392
+ repository: TrimmedNonEmptyString,
393
+ number: PositiveInt,
394
+ url: TrimmedNonEmptyString,
395
+});
396
+export type ThreadLinkedPullRequest = typeof ThreadLinkedPullRequest.Type;
397
+
398
export const OrchestrationThread = Schema.Struct({
399
id: ThreadId,
400
projectId: ProjectId,
@@ -398,6 +406,7 @@ export const OrchestrationThread = Schema.Struct({
406
),
407
branch: Schema.NullOr(TrimmedNonEmptyString),
408
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
409
+ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
410
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
411
createdAt: IsoDateTime,
412
updatedAt: IsoDateTime,
@@ -468,6 +477,7 @@ export const OrchestrationThreadShell = Schema.Struct({
477
),
478
branch: Schema.NullOr(TrimmedNonEmptyString),
479
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
480
+ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
481
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
482
createdAt: IsoDateTime,
483
updatedAt: IsoDateTime,
@@ -784,6 +794,7 @@ const ThreadMetaUpdateCommand = Schema.Struct({
794
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
795
expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
796
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
797
+ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
798
}).check(
799
Schema.makeFilter(
800
(input) =>
@@ -1227,6 +1238,7 @@ export const ThreadMetaUpdatedPayload = Schema.Struct({
1238
modelSelection: Schema.optional(ModelSelection),
1239
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1240
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1241
+ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
1242
updatedAt: IsoDateTime,
1243
});
1244