The best way to control Claude Code, Codex and more from any computer or phone
Scope git toast state by thread ref (#1855)
Julius Marminge committed
Apr 9, 2026 at 12:59 UTC
b547fee77e77b3e813ce81284aea25781fec28b3
8 files changed
+352
-79
apps/web/src/components/BranchToolbarBranchSelector.tsx
+1
-1
@@ -144,7 +144,7 @@ export function BranchToolbarBranchSelector({
144
});
145
}
146
if (hasServerThread) {
147
- setThreadBranchAction(activeThreadId, branch, worktreePath);
147
+ setThreadBranchAction(threadRef, branch, worktreePath);
148
return;
149
}
150
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
apps/web/src/components/GitActionsControl.browser.tsx
+133
-26
@@ -4,9 +4,9 @@ import { useState } from "react";
4
import { afterEach, describe, expect, it, vi } from "vitest";
5
import { render } from "vitest-browser-react";
6
7
-const THREAD_A = ThreadId.makeUnsafe("thread-a");
8
-const THREAD_B = ThreadId.makeUnsafe("thread-b");
9
-const ENVIRONMENT_ID = "environment-local" as never;
7
+const SHARED_THREAD_ID = ThreadId.makeUnsafe("thread-shared");
8
+const ENVIRONMENT_A = "environment-local" as never;
9
+const ENVIRONMENT_B = "environment-remote" as never;
10
const GIT_CWD = "/repo/project";
11
const BRANCH_NAME = "feature/toast-scope";
12
@@ -24,9 +24,12 @@ function createDeferredPromise<T>() {
24
25
const {
26
activeRunStackedActionDeferredRef,
27
+ activeDraftThreadRef,
28
+ hasServerThreadRef,
29
invalidateGitQueriesSpy,
30
refreshGitStatusSpy,
31
runStackedActionMutateAsyncSpy,
32
+ setDraftThreadContextSpy,
33
setThreadBranchSpy,
34
toastAddSpy,
35
toastCloseSpy,
@@ -34,9 +37,12 @@ const {
37
toastUpdateSpy,
38
} = vi.hoisted(() => ({
39
activeRunStackedActionDeferredRef: { current: createDeferredPromise<never>() },
40
+ activeDraftThreadRef: { current: null as unknown },
41
+ hasServerThreadRef: { current: true },
42
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
43
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
44
runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
45
+ setDraftThreadContextSpy: vi.fn(),
46
setThreadBranchSpy: vi.fn(),
47
toastAddSpy: vi.fn(() => "toast-1"),
48
toastCloseSpy: vi.fn(),
@@ -123,6 +129,36 @@ vi.mock("~/localApi", () => ({
129
readLocalApi: vi.fn(() => null),
130
}));
131
132
+vi.mock("~/composerDraftStore", async () => {
133
+ const draftStoreState = {
134
+ getDraftThreadByRef: () => activeDraftThreadRef.current,
135
+ getDraftSession: () => activeDraftThreadRef.current,
136
+ getDraftThread: () => activeDraftThreadRef.current,
137
+ getDraftSessionByLogicalProjectKey: () => null,
138
+ setDraftThreadContext: setDraftThreadContextSpy,
139
+ setLogicalProjectDraftThreadId: vi.fn(),
140
+ setProjectDraftThreadId: vi.fn(),
141
+ hasDraftThreadsInEnvironment: () => false,
142
+ clearDraftThread: vi.fn(),
143
+ };
144
+
145
+ return {
146
+ DraftId: {
147
+ makeUnsafe: (value: string) => value,
148
+ },
149
+ useComposerDraftStore: Object.assign(
150
+ (selector: (state: unknown) => unknown) => selector(draftStoreState),
151
+ { getState: () => draftStoreState },
152
+ ),
153
+ markPromotedDraftThread: vi.fn(),
154
+ markPromotedDraftThreadByRef: vi.fn(),
155
+ markPromotedDraftThreads: vi.fn(),
156
+ markPromotedDraftThreadsByRef: vi.fn(),
157
+ finalizePromotedDraftThreadByRef: vi.fn(),
158
+ finalizePromotedDraftThreadsByRef: vi.fn(),
159
+ };
160
+});
161
+
162
vi.mock("~/store", () => ({
163
selectEnvironmentState: (
164
state: { environmentStateById: Record<string, unknown> },
@@ -154,11 +190,37 @@ vi.mock("~/store", () => ({
190
selector({
191
setThreadBranch: setThreadBranchSpy,
192
environmentStateById: {
157
- [ENVIRONMENT_ID]: {
158
- threadShellById: {
159
- [THREAD_A]: { id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
160
- [THREAD_B]: { id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
161
- },
193
+ [ENVIRONMENT_A]: {
194
+ threadShellById: hasServerThreadRef.current
195
+ ? {
196
+ [SHARED_THREAD_ID]: {
197
+ id: SHARED_THREAD_ID,
198
+ branch: BRANCH_NAME,
199
+ worktreePath: null,
200
+ },
201
+ }
202
+ : {},
203
+ threadSessionById: {},
204
+ threadTurnStateById: {},
205
+ messageIdsByThreadId: {},
206
+ messageByThreadId: {},
207
+ activityIdsByThreadId: {},
208
+ activityByThreadId: {},
209
+ proposedPlanIdsByThreadId: {},
210
+ proposedPlanByThreadId: {},
211
+ turnDiffIdsByThreadId: {},
212
+ turnDiffSummaryByThreadId: {},
213
+ },
214
+ [ENVIRONMENT_B]: {
215
+ threadShellById: hasServerThreadRef.current
216
+ ? {
217
+ [SHARED_THREAD_ID]: {
218
+ id: SHARED_THREAD_ID,
219
+ branch: BRANCH_NAME,
220
+ worktreePath: null,
221
+ },
222
+ }
223
+ : {},
224
threadSessionById: {},
225
threadTurnStateById: {},
226
messageIdsByThreadId: {},
@@ -187,17 +249,19 @@ function findButtonByText(text: string): HTMLButtonElement | null {
249
}
250
251
function Harness() {
190
- const [activeThreadId, setActiveThreadId] = useState(THREAD_A);
252
+ const [activeThreadRef, setActiveThreadRef] = useState(
253
+ scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
254
+ );
255
256
return (
257
<>
194
- <button type="button" onClick={() => setActiveThreadId(THREAD_B)}>
195
- Switch thread
258
+ <button
259
+ type="button"
260
+ onClick={() => setActiveThreadRef(scopeThreadRef(ENVIRONMENT_B, SHARED_THREAD_ID))}
261
+ >
262
+ Switch environment
263
</button>
197
- <GitActionsControl
198
- gitCwd={GIT_CWD}
199
- activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, activeThreadId)}
200
- />
264
+ <GitActionsControl gitCwd={GIT_CWD} activeThreadRef={activeThreadRef} />
265
</>
266
);
267
}
@@ -207,10 +271,12 @@ describe("GitActionsControl thread-scoped progress toast", () => {
271
vi.useRealTimers();
272
vi.clearAllMocks();
273
activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
274
+ activeDraftThreadRef.current = null;
275
+ hasServerThreadRef.current = true;
276
document.body.innerHTML = "";
277
});
278
213
- it("keeps an in-flight git action toast pinned to the thread that started it", async () => {
279
+ it("keeps an in-flight git action toast pinned to the thread ref that started it", async () => {
280
vi.useFakeTimers();
281
282
const host = document.createElement("div");
@@ -227,7 +293,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
293
294
expect(toastAddSpy).toHaveBeenCalledWith(
295
expect.objectContaining({
230
- data: { threadId: THREAD_A },
296
+ data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
297
title: "Pushing...",
298
type: "loading",
299
}),
@@ -238,24 +304,27 @@ describe("GitActionsControl thread-scoped progress toast", () => {
304
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
305
"toast-1",
306
expect.objectContaining({
241
- data: { threadId: THREAD_A },
307
+ data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
308
title: "Pushing...",
309
type: "loading",
310
}),
311
);
312
247
- const switchThreadButton = findButtonByText("Switch thread");
248
- expect(switchThreadButton, 'Unable to find button containing "Switch thread"').toBeTruthy();
249
- if (!(switchThreadButton instanceof HTMLButtonElement)) {
250
- throw new Error('Unable to find button containing "Switch thread"');
313
+ const switchEnvironmentButton = findButtonByText("Switch environment");
314
+ expect(
315
+ switchEnvironmentButton,
316
+ 'Unable to find button containing "Switch environment"',
317
+ ).toBeTruthy();
318
+ if (!(switchEnvironmentButton instanceof HTMLButtonElement)) {
319
+ throw new Error('Unable to find button containing "Switch environment"');
320
}
252
- switchThreadButton.click();
321
+ switchEnvironmentButton.click();
322
await vi.advanceTimersByTimeAsync(1_000);
323
324
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
325
"toast-1",
326
expect.objectContaining({
258
- data: { threadId: THREAD_A },
327
+ data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
328
title: "Pushing...",
329
type: "loading",
330
}),
@@ -284,7 +353,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
353
const screen = await render(
354
<GitActionsControl
355
gitCwd={GIT_CWD}
287
- activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, THREAD_A)}
356
+ activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
357
/>,
358
{
359
container: host,
@@ -304,7 +373,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
373
await vi.advanceTimersByTimeAsync(1);
374
expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1);
375
expect(refreshGitStatusSpy).toHaveBeenCalledWith({
307
- environmentId: ENVIRONMENT_ID,
376
+ environmentId: ENVIRONMENT_A,
377
cwd: GIT_CWD,
378
});
379
} finally {
@@ -316,4 +385,42 @@ describe("GitActionsControl thread-scoped progress toast", () => {
385
host.remove();
386
}
387
});
388
+
389
+ it("syncs the live branch into the active draft thread when no server thread exists", async () => {
390
+ hasServerThreadRef.current = false;
391
+ activeDraftThreadRef.current = {
392
+ threadId: SHARED_THREAD_ID,
393
+ environmentId: ENVIRONMENT_A,
394
+ branch: null,
395
+ worktreePath: null,
396
+ };
397
+
398
+ const host = document.createElement("div");
399
+ document.body.append(host);
400
+ const screen = await render(
401
+ <GitActionsControl
402
+ gitCwd={GIT_CWD}
403
+ activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
404
+ />,
405
+ {
406
+ container: host,
407
+ },
408
+ );
409
+
410
+ try {
411
+ await Promise.resolve();
412
+
413
+ expect(setDraftThreadContextSpy).toHaveBeenCalledWith(
414
+ scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
415
+ {
416
+ branch: BRANCH_NAME,
417
+ worktreePath: null,
418
+ },
419
+ );
420
+ expect(setThreadBranchSpy).not.toHaveBeenCalled();
421
+ } finally {
422
+ await screen.unmount();
423
+ host.remove();
424
+ }
425
+ });
426
});
apps/web/src/components/GitActionsControl.tsx
+44
-18
@@ -49,6 +49,7 @@ import {
49
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
50
import { newCommandId, randomUUID } from "~/lib/utils";
51
import { resolvePathLinkTarget } from "~/terminal-links";
52
+import { useComposerDraftStore } from "~/composerDraftStore";
53
import { readEnvironmentApi } from "~/environmentApi";
54
import { readLocalApi } from "~/localApi";
55
import { useStore } from "~/store";
@@ -209,17 +210,20 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
210
}
211
212
export default function GitActionsControl({ gitCwd, activeThreadRef }: GitActionsControlProps) {
212
- const activeThreadId = activeThreadRef?.threadId ?? null;
213
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
214
const threadToastData = useMemo(
215
- () => (activeThreadId ? { threadId: activeThreadId } : undefined),
216
- [activeThreadId],
215
+ () => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
216
+ [activeThreadRef],
217
);
218
const activeServerThreadSelector = useMemo(
219
() => createThreadSelectorByRef(activeThreadRef),
220
[activeThreadRef],
221
);
222
const activeServerThread = useStore(activeServerThreadSelector);
223
+ const activeDraftThread = useComposerDraftStore((store) =>
224
+ activeThreadRef ? store.getDraftThreadByRef(activeThreadRef) : null,
225
+ );
226
+ const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
227
const setThreadBranch = useStore((store) => store.setThreadBranch);
228
const queryClient = useQueryClient();
229
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
@@ -247,27 +251,49 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
251
252
const persistThreadBranchSync = useCallback(
253
(branch: string | null) => {
250
- if (!activeThreadId || !activeServerThread || activeServerThread.branch === branch) {
254
+ if (!activeThreadRef) {
255
+ return;
256
+ }
257
+
258
+ if (activeServerThread) {
259
+ if (activeServerThread.branch === branch) {
260
+ return;
261
+ }
262
+
263
+ const worktreePath = activeServerThread.worktreePath;
264
+ const api = readEnvironmentApi(activeThreadRef.environmentId);
265
+ if (api) {
266
+ void api.orchestration
267
+ .dispatchCommand({
268
+ type: "thread.meta.update",
269
+ commandId: newCommandId(),
270
+ threadId: activeThreadRef.threadId,
271
+ branch,
272
+ worktreePath,
273
+ })
274
+ .catch(() => undefined);
275
+ }
276
+
277
+ setThreadBranch(activeThreadRef, branch, worktreePath);
278
return;
279
}
280
254
- const worktreePath = activeServerThread.worktreePath;
255
- const api = activeEnvironmentId ? readEnvironmentApi(activeEnvironmentId) : undefined;
256
- if (api) {
257
- void api.orchestration
258
- .dispatchCommand({
259
- type: "thread.meta.update",
260
- commandId: newCommandId(),
261
- threadId: activeThreadId,
262
- branch,
263
- worktreePath,
264
- })
265
- .catch(() => undefined);
281
+ if (!activeDraftThread || activeDraftThread.branch === branch) {
282
+ return;
283
}
284
268
- setThreadBranch(activeThreadId, branch, worktreePath);
285
+ setDraftThreadContext(activeThreadRef, {
286
+ branch,
287
+ worktreePath: activeDraftThread.worktreePath,
288
+ });
289
},
270
- [activeEnvironmentId, activeServerThread, activeThreadId, setThreadBranch],
290
+ [
291
+ activeDraftThread,
292
+ activeServerThread,
293
+ activeThreadRef,
294
+ setDraftThreadContext,
295
+ setThreadBranch,
296
+ ],
297
);
298
299
const syncThreadBranchAfterGitAction = useCallback(
apps/web/src/components/ui/toast.logic.test.ts
+52
-1
@@ -1,5 +1,10 @@
1
+import type { ScopedThreadRef } from "@t3tools/contracts";
2
import { assert, describe, it } from "vitest";
2
-import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
3
+import {
4
+ buildVisibleToastLayout,
5
+ shouldHideCollapsedToastContent,
6
+ shouldRenderThreadScopedToast,
7
+} from "./toast.logic";
8
9
describe("shouldHideCollapsedToastContent", () => {
10
it("keeps a single visible toast readable", () => {
@@ -61,3 +66,49 @@ describe("buildVisibleToastLayout", () => {
66
);
67
});
68
});
69
+
70
+describe("shouldRenderThreadScopedToast", () => {
71
+ const activeThreadRef = {
72
+ environmentId: "environment-a",
73
+ threadId: "thread-1",
74
+ } as ScopedThreadRef;
75
+
76
+ it("renders a toast scoped to the active thread ref", () => {
77
+ assert.equal(
78
+ shouldRenderThreadScopedToast(
79
+ {
80
+ threadRef: activeThreadRef,
81
+ },
82
+ activeThreadRef,
83
+ ),
84
+ true,
85
+ );
86
+ });
87
+
88
+ it("hides a scoped toast when the environment differs", () => {
89
+ assert.equal(
90
+ shouldRenderThreadScopedToast(
91
+ {
92
+ threadRef: {
93
+ environmentId: "environment-b",
94
+ threadId: "thread-1",
95
+ } as ScopedThreadRef,
96
+ },
97
+ activeThreadRef,
98
+ ),
99
+ false,
100
+ );
101
+ });
102
+
103
+ it("keeps legacy thread-id scoped toasts working", () => {
104
+ assert.equal(
105
+ shouldRenderThreadScopedToast(
106
+ {
107
+ threadId: "thread-1" as never,
108
+ },
109
+ activeThreadRef,
110
+ ),
111
+ true,
112
+ );
113
+ });
114
+});
apps/web/src/components/ui/toast.logic.ts
+27
@@ -1,3 +1,5 @@
1
+import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
2
+
3
export function shouldHideCollapsedToastContent(
4
visibleToastIndex: number,
5
visibleToastCount: number,
@@ -44,3 +46,28 @@ export function buildVisibleToastLayout<TToast extends object>(
46
function normalizeToastHeight(height: number | null | undefined): number {
47
return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : 0;
48
}
49
+
50
+export function shouldRenderThreadScopedToast(
51
+ data:
52
+ | {
53
+ threadRef?: ScopedThreadRef | null;
54
+ threadId?: ThreadId | null;
55
+ }
56
+ | undefined,
57
+ activeThreadRef: ScopedThreadRef | null,
58
+): boolean {
59
+ if (data?.threadRef) {
60
+ return (
61
+ activeThreadRef !== null &&
62
+ data.threadRef.environmentId === activeThreadRef.environmentId &&
63
+ data.threadRef.threadId === activeThreadRef.threadId
64
+ );
65
+ }
66
+
67
+ const toastThreadId = data?.threadId;
68
+ if (!toastThreadId) {
69
+ return true;
70
+ }
71
+
72
+ return activeThreadRef?.threadId === toastThreadId;
73
+}
apps/web/src/components/ui/toast.tsx
+33
-20
@@ -1,9 +1,9 @@
1
"use client";
2
3
import { Toast } from "@base-ui/react/toast";
4
-import { useEffect, type CSSProperties } from "react";
4
+import { useEffect, useMemo, type CSSProperties } from "react";
5
import { useParams } from "@tanstack/react-router";
6
-import { ThreadId } from "@t3tools/contracts";
6
+import { type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
7
import {
8
CheckIcon,
9
CircleAlertIcon,
@@ -16,10 +16,17 @@ import {
16
17
import { cn } from "~/lib/utils";
18
import { buttonVariants } from "~/components/ui/button";
19
+import { useComposerDraftStore } from "~/composerDraftStore";
20
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
20
-import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
21
+import { resolveThreadRouteTarget } from "~/threadRoutes";
22
+import {
23
+ buildVisibleToastLayout,
24
+ shouldHideCollapsedToastContent,
25
+ shouldRenderThreadScopedToast,
26
+} from "./toast.logic";
27
28
export type ThreadToastData = {
29
+ threadRef?: ScopedThreadRef | null;
30
threadId?: ThreadId | null;
31
tooltipStyle?: boolean;
32
dismissAfterVisibleMs?: number;
@@ -70,21 +77,27 @@ interface ToastProviderProps extends Toast.Provider.Props {
77
position?: ToastPosition;
78
}
79
73
-function shouldRenderForActiveThread(
74
- data: ThreadToastData | undefined,
75
- activeThreadId: ThreadId | null,
76
-): boolean {
77
- const toastThreadId = data?.threadId;
78
- if (!toastThreadId) return true;
79
- return toastThreadId === activeThreadId;
80
-}
81
-
82
-function useActiveThreadIdFromRoute(): ThreadId | null {
83
- return useParams({
80
+function useActiveThreadRefFromRoute(): ScopedThreadRef | null {
81
+ const routeTarget = useParams({
82
strict: false,
85
- select: (params) =>
86
- typeof params.threadId === "string" ? ThreadId.makeUnsafe(params.threadId) : null,
83
+ select: (params) => resolveThreadRouteTarget(params),
84
});
85
+ const activeDraftSession = useComposerDraftStore((store) =>
86
+ routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
87
+ );
88
+
89
+ return useMemo(() => {
90
+ if (routeTarget?.kind === "server") {
91
+ return routeTarget.threadRef;
92
+ }
93
+ if (routeTarget?.kind === "draft" && activeDraftSession) {
94
+ return {
95
+ environmentId: activeDraftSession.environmentId,
96
+ threadId: activeDraftSession.threadId,
97
+ };
98
+ }
99
+ return null;
100
+ }, [activeDraftSession, routeTarget]);
101
}
102
103
function ThreadToastVisibleAutoDismiss({
@@ -176,10 +189,10 @@ function ToastProvider({ children, position = "top-right", ...props }: ToastProv
189
190
function Toasts({ position = "top-right" }: { position: ToastPosition }) {
191
const { toasts } = Toast.useToastManager<ThreadToastData>();
179
- const activeThreadId = useActiveThreadIdFromRoute();
192
+ const activeThreadRef = useActiveThreadRefFromRoute();
193
const isTop = position.startsWith("top");
194
const visibleToasts = toasts.filter((toast) =>
182
- shouldRenderForActiveThread(toast.data, activeThreadId),
195
+ shouldRenderThreadScopedToast(toast.data, activeThreadRef),
196
);
197
const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
198
@@ -350,13 +363,13 @@ function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
363
364
function AnchoredToasts() {
365
const { toasts } = Toast.useToastManager<ThreadToastData>();
353
- const activeThreadId = useActiveThreadIdFromRoute();
366
+ const activeThreadRef = useActiveThreadRefFromRoute();
367
368
return (
369
<Toast.Portal data-slot="toast-portal-anchored">
370
<Toast.Viewport className="outline-none" data-slot="toast-viewport-anchored">
371
{toasts
359
- .filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
372
+ .filter((toast) => shouldRenderThreadScopedToast(toast.data, activeThreadRef))
373
.map((toast) => {
374
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
375
const tooltipStyle = toast.data?.tooltipStyle ?? false;
apps/web/src/store.test.ts
+51
-2
@@ -1,3 +1,4 @@
1
+import { scopeThreadRef } from "@t3tools/client-runtime";
2
import {
3
CheckpointRef,
4
DEFAULT_MODEL_BY_PROVIDER,
@@ -17,6 +18,7 @@ import {
18
applyOrchestrationEvents,
19
selectEnvironmentState,
20
selectProjectsAcrossEnvironments,
21
+ setThreadBranch,
22
selectThreadsAcrossEnvironments,
23
syncServerReadModel,
24
type AppState,
@@ -25,6 +27,7 @@ import {
27
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
28
29
const localEnvironmentId = EnvironmentId.makeUnsafe("environment-local");
30
+const remoteEnvironmentId = EnvironmentId.makeUnsafe("environment-remote");
31
32
function withActiveEnvironmentState(
33
environmentState: EnvironmentState,
@@ -86,7 +89,7 @@ function makeState(thread: Thread): AppState {
89
const projectId = ProjectId.makeUnsafe("project-1");
90
const project = {
91
id: projectId,
89
- environmentId: localEnvironmentId,
92
+ environmentId: thread.environmentId,
93
name: "Project",
94
cwd: "/tmp/project",
95
defaultModelSelection: {
@@ -171,7 +174,9 @@ function makeState(thread: Thread): AppState {
174
sidebarThreadSummaryById: {},
175
bootstrapComplete: true,
176
};
174
- return withActiveEnvironmentState(environmentState);
177
+ return withActiveEnvironmentState(environmentState, {
178
+ activeEnvironmentId: thread.environmentId,
179
+ });
180
}
181
182
function makeEmptyState(overrides: Partial<AppState & EnvironmentState> = {}): AppState {
@@ -201,6 +206,10 @@ function localEnvironmentStateOf(state: AppState): EnvironmentState {
206
return selectEnvironmentState(state, localEnvironmentId);
207
}
208
209
+function environmentStateOf(state: AppState, environmentId: EnvironmentId): EnvironmentState {
210
+ return selectEnvironmentState(state, environmentId);
211
+}
212
+
213
function projectsOf(state: AppState) {
214
return selectProjectsAcrossEnvironments(state);
215
}
@@ -305,6 +314,46 @@ function makeReadModelProject(
314
};
315
}
316
317
+describe("setThreadBranch", () => {
318
+ it("updates only the scoped thread environment", () => {
319
+ const sharedThreadId = ThreadId.makeUnsafe("thread-shared");
320
+ const localThread = makeThread({
321
+ id: sharedThreadId,
322
+ environmentId: localEnvironmentId,
323
+ branch: "local-branch",
324
+ });
325
+ const remoteThread = makeThread({
326
+ id: sharedThreadId,
327
+ environmentId: remoteEnvironmentId,
328
+ branch: "remote-branch",
329
+ });
330
+ const state: AppState = {
331
+ activeEnvironmentId: localEnvironmentId,
332
+ environmentStateById: {
333
+ [localEnvironmentId]: environmentStateOf(makeState(localThread), localEnvironmentId),
334
+ [remoteEnvironmentId]: environmentStateOf(makeState(remoteThread), remoteEnvironmentId),
335
+ },
336
+ };
337
+
338
+ const next = setThreadBranch(
339
+ state,
340
+ scopeThreadRef(remoteEnvironmentId, sharedThreadId),
341
+ "remote-next",
342
+ "/tmp/remote-worktree",
343
+ );
344
+
345
+ expect(
346
+ environmentStateOf(next, localEnvironmentId).threadShellById[sharedThreadId]?.branch,
347
+ ).toBe("local-branch");
348
+ expect(
349
+ environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.branch,
350
+ ).toBe("remote-next");
351
+ expect(
352
+ environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.worktreePath,
353
+ ).toBe("/tmp/remote-worktree");
354
+ });
355
+});
356
+
357
describe("store read model sync", () => {
358
it("marks bootstrap complete after snapshot sync", () => {
359
const initialState = withActiveEnvironmentState(
apps/web/src/store.ts
+11
-11
@@ -1737,17 +1737,13 @@ export function setActiveEnvironmentId(state: AppState, environmentId: Environme
1737
1738
export function setThreadBranch(
1739
state: AppState,
1740
- threadId: ThreadId,
1740
+ threadRef: ScopedThreadRef,
1741
branch: string | null,
1742
worktreePath: string | null,
1743
): AppState {
1744
- if (state.activeEnvironmentId === null) {
1745
- return state;
1746
- }
1747
-
1744
const nextEnvironmentState = updateThreadState(
1749
- getStoredEnvironmentState(state, state.activeEnvironmentId),
1750
- threadId,
1745
+ getStoredEnvironmentState(state, threadRef.environmentId),
1746
+ threadRef.threadId,
1747
(thread) => {
1748
if (thread.branch === branch && thread.worktreePath === worktreePath) return thread;
1749
const cwdChanged = thread.worktreePath !== worktreePath;
@@ -1759,7 +1755,7 @@ export function setThreadBranch(
1755
};
1756
},
1757
);
1762
- return commitEnvironmentState(state, state.activeEnvironmentId, nextEnvironmentState);
1758
+ return commitEnvironmentState(state, threadRef.environmentId, nextEnvironmentState);
1759
}
1760
1761
interface AppStore extends AppState {
@@ -1771,7 +1767,11 @@ interface AppStore extends AppState {
1767
environmentId: EnvironmentId,
1768
) => void;
1769
setError: (threadId: ThreadId, error: string | null) => void;
1774
- setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
1770
+ setThreadBranch: (
1771
+ threadRef: ScopedThreadRef,
1772
+ branch: string | null,
1773
+ worktreePath: string | null,
1774
+ ) => void;
1775
}
1776
1777
export const useStore = create<AppStore>((set) => ({
@@ -1785,6 +1785,6 @@ export const useStore = create<AppStore>((set) => ({
1785
applyOrchestrationEvents: (events, environmentId) =>
1786
set((state) => applyOrchestrationEvents(state, events, environmentId)),
1787
setError: (threadId, error) => set((state) => setError(state, threadId, error)),
1788
- setThreadBranch: (threadId, branch, worktreePath) =>
1789
- set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
1788
+ setThreadBranch: (threadRef, branch, worktreePath) =>
1789
+ set((state) => setThreadBranch(state, threadRef, branch, worktreePath)),
1790
}));