The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): ChatView's draft machine routing lives in useDraftEnvironmentRouting (#22728)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 01:36 UTC
91a0a2901ac51d330b3cd06618629c98da3f4694
2 files changed
+290
-183
apps/web/src/components/ChatView.tsx
+22
-183
@@ -23,9 +23,7 @@ import {
23
recallCheckoutIsRepo,
24
rememberCheckoutIsRepo,
25
} from "./ChatView.logic";
26
-import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";
26
import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
28
-import { useScratchProject } from "../hooks/useScratchProject";
27
import { useStableCallback } from "../hooks/useStableCallback";
28
import { useProjectScriptEditing } from "./chat/useProjectScriptEditing";
29
import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent";
@@ -72,7 +70,6 @@ import {
70
type RunId,
71
type RunAttemptId,
72
ProviderInteractionMode,
75
- resolveProjectProviderInstanceEnabled,
73
RuntimeMode,
74
} from "@t3tools/contracts";
75
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
@@ -336,7 +333,6 @@ import {
333
resolveThreadDetailRef,
334
useEnvironmentSupportsServerBrowser,
335
useProject,
339
- useProjects,
336
useThreadProjection,
337
useThreadStatus,
338
useThreadHistory,
@@ -486,6 +482,7 @@ import { observeResize } from "~/lib/observeResize";
482
import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
483
import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
484
import { ChatRightPanel } from "./chat/ChatRightPanel";
485
+import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting";
486
import {
487
backgroundWorkBannerItem,
488
branchMismatchBannerItem,
@@ -1479,7 +1476,6 @@ export default function ChatView(props: ChatViewProps) {
1476
useRightPanelStore.getState().reconcileFileSurfaces(activeThreadRef, activeProject !== null);
1477
}, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]);
1478
1482
- const allProjects = useProjects();
1479
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
1480
useEffect(() => {
1481
if (!activeThreadRef || !activeProjectRef) return;
@@ -1501,7 +1497,6 @@ export default function ChatView(props: ChatViewProps) {
1497
connection: activeEnvironment.connection,
1498
};
1499
})() as EnvironmentUnavailableState | null;
1504
- const { openScratchProject } = useScratchProject();
1500
const activeProjectIsScratch =
1501
activeProject !== null &&
1502
isScratchProject(
@@ -2475,188 +2470,32 @@ export default function ChatView(props: ChatViewProps) {
2470
};
2471
const onToggleDiffStable = useStableCallback(onToggleDiff);
2472
2478
- const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
2479
- const loadBalancingCandidates = needsLoadBalancing
2480
- ? logicalProjectEnvironments
2481
- .filter((candidate) => {
2482
- const environment = environmentById.get(candidate.environmentId);
2483
- return (
2484
- environment?.connection.phase === "connected" &&
2485
- (loadBalancingSettings.loadBalancingWeights[candidate.environmentId] ?? 50) > 0 &&
2486
- referencedThreadContexts.every(
2487
- (record) => record.environmentId === candidate.environmentId,
2488
- ) &&
2489
- providersByEnvironment
2490
- .get(candidate.environmentId)
2491
- ?.some(
2492
- (provider) =>
2493
- (activeProviderInstanceId === null ||
2494
- provider.instanceId === activeProviderInstanceId) &&
2495
- provider.driver === selectedProvider &&
2496
- (environment.serverConfig?.settings
2497
- ? resolveProjectProviderInstanceEnabled(
2498
- environment.serverConfig.settings,
2499
- candidate.projectId,
2500
- provider.instanceId,
2501
- )
2502
- : provider.enabled) &&
2503
- provider.installed &&
2504
- provider.status !== "error" &&
2505
- provider.auth.status !== "unauthenticated" &&
2506
- provider.availability !== "unavailable",
2507
- )
2508
- );
2509
- })
2510
- .map((candidate) => candidate.environmentId)
2511
- : [];
2512
- const loadBalancing = useLoadBalancedEnvironment(
2513
- loadBalancingCandidates,
2514
- loadBalancingSettings.loadBalancingWeights,
2515
- );
2516
- useEffect(() => {
2517
- if (!needsLoadBalancing || loadBalancing.pending || !draftId || sendInFlightRef.current) return;
2518
- const target = logicalProjectEnvironments.find(
2519
- (environment) => environment.environmentId === loadBalancing.environmentId,
2520
- );
2521
- if (!target?.projectId) return;
2522
- setDraftThreadContext(draftId, {
2523
- projectRef: scopeProjectRef(target.environmentId, target.projectId),
2524
- environmentSelection: "auto",
2525
- loadBalancedEnvironmentId: target.environmentId,
2526
- });
2527
- }, [
2473
+ const {
2474
needsLoadBalancing,
2529
- loadBalancing.pending,
2530
- loadBalancing.environmentId,
2475
+ loadBalancing,
2476
+ onAutoEnvironmentStable,
2477
+ autoEnvironmentLabel,
2478
+ isEnvironmentChanging,
2479
+ readPendingEnvironmentChange,
2480
+ onEnvironmentChangeStable,
2481
+ } = useDraftEnvironmentRouting({
2482
draftId,
2483
+ draftThread,
2484
+ envLocked,
2485
+ automaticEnvironment,
2486
logicalProjectEnvironments,
2487
+ environmentById,
2488
+ providersByEnvironment,
2489
+ loadBalancingSettings,
2490
+ referencedThreadContexts,
2491
+ activeProviderInstanceId,
2492
+ selectedProvider,
2493
+ composerHasAttachments,
2494
+ activeProjectKey,
2495
+ activeProjectIsScratch,
2496
+ projectGroupingSettings,
2497
sendInFlightRef,
2534
- setDraftThreadContext,
2535
- ]);
2536
- const onAutoEnvironment = () => {
2537
- if (envLocked || !draftId) return;
2538
- if (composerHasAttachments) {
2539
- toastManager.add({
2540
- type: "warning",
2541
- id: "load-balancing-attachments",
2542
- title: "Keep attachments on this machine",
2543
- description:
2544
- "Remove attachments before choosing automatic routing, then attach them on the selected machine.",
2545
- });
2546
- return;
2547
- }
2548
- loadBalancing.refresh(
2549
- logicalProjectEnvironments.map((environment) => environment.environmentId),
2550
- );
2551
- setDraftThreadContext(draftId, {
2552
- environmentSelection: "auto",
2553
- loadBalancedEnvironmentId: null,
2554
- branch: null,
2555
- worktreePath: null,
2556
- });
2557
- };
2558
- const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
2559
- const autoEnvironmentLabel = automaticEnvironment
2560
- ? draftThread?.loadBalancedEnvironmentId
2561
- ? "Auto balance"
2562
- : loadBalancing.pending
2563
- ? "Checking machines…"
2564
- : loadBalancing.failed
2565
- ? "Auto balance unavailable"
2566
- : "Auto balance"
2567
- : undefined;
2568
-
2569
- // A change in flight belongs to the draft and project it started on.
2570
- const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
2571
- const environmentChangeRef = useRef<{
2572
- readonly environmentId: EnvironmentId;
2573
- readonly scope: string;
2574
- } | null>(null);
2575
- const environmentChangeScopeRef = useRef("");
2576
- useLayoutEffect(() => {
2577
- environmentChangeScopeRef.current = environmentChangeScope;
2498
});
2579
- // Leaving the scope, or unmounting, abandons a change still in flight.
2580
- useLayoutEffect(
2581
- () => () => {
2582
- if (environmentChangeRef.current?.scope === environmentChangeScope) {
2583
- environmentChangeRef.current = null;
2584
- }
2585
- },
2586
- [environmentChangeScope],
2587
- );
2588
- const readPendingEnvironmentChange = () => {
2589
- const pending = environmentChangeRef.current;
2590
- return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
2591
- };
2592
- // The busy state belongs to the request that set it, so an older request settling late
2593
- // (abandoned, or superseded by a newer switch) can never clear a newer one's.
2594
- const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
2595
- readonly environmentId: EnvironmentId;
2596
- readonly scope: string;
2597
- } | null>(null);
2598
- const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;
2599
-
2600
- const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
2601
- if (envLocked || !draftId || sendInFlightRef.current) return;
2602
- const originalDraft = getDraftSession(draftId);
2603
- if (!originalDraft || originalDraft.promotedTo) return;
2604
- const target = logicalProjectEnvironments.find(
2605
- (env) => env.environmentId === nextEnvironmentId,
2606
- );
2607
- if (!target) return;
2608
- const request = { environmentId: target.environmentId, scope: environmentChangeScope };
2609
- environmentChangeRef.current = request;
2610
- setBusyEnvironmentChange(null);
2611
- const retarget = (project: (typeof allProjects)[number]) => {
2612
- const currentDraft = getDraftSession(draftId);
2613
- if (
2614
- environmentChangeRef.current !== request ||
2615
- environmentChangeScopeRef.current !== request.scope ||
2616
- sendInFlightRef.current ||
2617
- !currentDraft ||
2618
- currentDraft.promotedTo ||
2619
- currentDraft.environmentId !== originalDraft.environmentId ||
2620
- currentDraft.projectId !== originalDraft.projectId
2621
- )
2622
- return;
2623
- const projectRef = scopeProjectRef(target.environmentId, project.id);
2624
- if (activeProjectIsScratch) {
2625
- setLogicalProjectDraftThreadId(
2626
- deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings),
2627
- projectRef,
2628
- draftId,
2629
- { environmentSelection: "manual", loadBalancedEnvironmentId: null },
2630
- );
2631
- } else {
2632
- setDraftThreadContext(draftId, {
2633
- projectRef,
2634
- environmentSelection: "manual",
2635
- loadBalancedEnvironmentId: null,
2636
- });
2637
- }
2638
- };
2639
- const finish = () => {
2640
- if (environmentChangeRef.current === request) environmentChangeRef.current = null;
2641
- setBusyEnvironmentChange((busy) => (busy === request ? null : busy));
2642
- };
2643
- if (target.projectId !== null) {
2644
- const project = allProjects.find(
2645
- (project) =>
2646
- project.environmentId === target.environmentId && project.id === target.projectId,
2647
- );
2648
- if (project) retarget(project);
2649
- finish();
2650
- return;
2651
- }
2652
- setBusyEnvironmentChange(request);
2653
- void openScratchProject(target.environmentId, "Could not switch machine")
2654
- .then((project) => {
2655
- if (project) retarget(project);
2656
- })
2657
- .finally(finish);
2658
- };
2659
- const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
2499
2500
const activeTerminalGroup =
2501
terminalUiState.terminalGroups.find(
apps/web/src/components/chat/useDraftEnvironmentRouting.ts
new
+268
@@ -0,0 +1,268 @@
1
+import { useLoadBalancedEnvironment } from "../../hooks/useLoadBalancedEnvironment";
2
+import { useLogicalProjectEnvironments } from "../../hooks/useLogicalProjectEnvironments";
3
+import { useScratchProject } from "../../hooks/useScratchProject";
4
+import { useStableCallback } from "../../hooks/useStableCallback";
5
+import {
6
+ type EnvironmentId,
7
+ type ProviderDriverKind,
8
+ ProviderInstanceId,
9
+ resolveProjectProviderInstanceEnabled,
10
+ type ThreadContextRecord,
11
+} from "@t3tools/contracts";
12
+import { scopeProjectRef } from "@t3tools/client-runtime/environment";
13
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
14
+import { toastManager } from "../ui/toast";
15
+import {
16
+ deriveLogicalProjectKeyFromSettings,
17
+ selectProjectGroupingSettings,
18
+} from "../../logicalProject";
19
+import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
20
+import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
21
+import { useProjects } from "../../state/entities";
22
+import type { DraftSessionState } from "../../composerDraftStore";
23
+
24
+interface DraftEnvironmentRoutingInput {
25
+ readonly draftId: DraftId | null;
26
+ readonly draftThread: DraftSessionState | null;
27
+ readonly envLocked: boolean;
28
+ readonly automaticEnvironment: boolean;
29
+ readonly logicalProjectEnvironments: ReturnType<typeof useLogicalProjectEnvironments>;
30
+ readonly environmentById: ReadonlyMap<EnvironmentId, EnvironmentPresentation>;
31
+ readonly providersByEnvironment: ReturnType<typeof useEnvironmentProviders>;
32
+ readonly loadBalancingSettings: {
33
+ readonly loadBalancingWeights: Readonly<Record<string, number>>;
34
+ };
35
+ readonly referencedThreadContexts: ReadonlyArray<ThreadContextRecord>;
36
+ readonly activeProviderInstanceId: ProviderInstanceId | null;
37
+ readonly selectedProvider: ProviderDriverKind;
38
+ readonly composerHasAttachments: boolean;
39
+ readonly activeProjectKey: string | null;
40
+ readonly activeProjectIsScratch: boolean;
41
+ readonly projectGroupingSettings: ReturnType<typeof selectProjectGroupingSettings>;
42
+ readonly sendInFlightRef: { readonly current: boolean };
43
+}
44
+
45
+/**
46
+ * Which machine an unsent draft runs on: automatic load balancing across the
47
+ * project's machines, or a manual switch, which may first open a scratch
48
+ * project on the target machine.
49
+ */
50
+export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) {
51
+ const {
52
+ draftId,
53
+ draftThread,
54
+ envLocked,
55
+ automaticEnvironment,
56
+ logicalProjectEnvironments,
57
+ environmentById,
58
+ providersByEnvironment,
59
+ loadBalancingSettings,
60
+ referencedThreadContexts,
61
+ activeProviderInstanceId,
62
+ selectedProvider,
63
+ composerHasAttachments,
64
+ activeProjectKey,
65
+ activeProjectIsScratch,
66
+ projectGroupingSettings,
67
+ sendInFlightRef,
68
+ } = input;
69
+ const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
70
+ const getDraftSession = useComposerDraftStore((store) => store.getDraftSession);
71
+ const setLogicalProjectDraftThreadId = useComposerDraftStore(
72
+ (store) => store.setLogicalProjectDraftThreadId,
73
+ );
74
+ const allProjects = useProjects();
75
+ const { openScratchProject } = useScratchProject();
76
+ const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
77
+ const loadBalancingCandidates = needsLoadBalancing
78
+ ? logicalProjectEnvironments
79
+ .filter((candidate) => {
80
+ const environment = environmentById.get(candidate.environmentId);
81
+ return (
82
+ environment?.connection.phase === "connected" &&
83
+ (loadBalancingSettings.loadBalancingWeights[candidate.environmentId] ?? 50) > 0 &&
84
+ referencedThreadContexts.every(
85
+ (record) => record.environmentId === candidate.environmentId,
86
+ ) &&
87
+ providersByEnvironment
88
+ .get(candidate.environmentId)
89
+ ?.some(
90
+ (provider) =>
91
+ (activeProviderInstanceId === null ||
92
+ provider.instanceId === activeProviderInstanceId) &&
93
+ provider.driver === selectedProvider &&
94
+ (environment.serverConfig?.settings
95
+ ? resolveProjectProviderInstanceEnabled(
96
+ environment.serverConfig.settings,
97
+ candidate.projectId,
98
+ provider.instanceId,
99
+ )
100
+ : provider.enabled) &&
101
+ provider.installed &&
102
+ provider.status !== "error" &&
103
+ provider.auth.status !== "unauthenticated" &&
104
+ provider.availability !== "unavailable",
105
+ )
106
+ );
107
+ })
108
+ .map((candidate) => candidate.environmentId)
109
+ : [];
110
+ const loadBalancing = useLoadBalancedEnvironment(
111
+ loadBalancingCandidates,
112
+ loadBalancingSettings.loadBalancingWeights,
113
+ );
114
+ useEffect(() => {
115
+ if (!needsLoadBalancing || loadBalancing.pending || !draftId || sendInFlightRef.current) return;
116
+ const target = logicalProjectEnvironments.find(
117
+ (environment) => environment.environmentId === loadBalancing.environmentId,
118
+ );
119
+ if (!target?.projectId) return;
120
+ setDraftThreadContext(draftId, {
121
+ projectRef: scopeProjectRef(target.environmentId, target.projectId),
122
+ environmentSelection: "auto",
123
+ loadBalancedEnvironmentId: target.environmentId,
124
+ });
125
+ }, [
126
+ needsLoadBalancing,
127
+ loadBalancing.pending,
128
+ loadBalancing.environmentId,
129
+ draftId,
130
+ logicalProjectEnvironments,
131
+ sendInFlightRef,
132
+ setDraftThreadContext,
133
+ ]);
134
+ const onAutoEnvironment = () => {
135
+ if (envLocked || !draftId) return;
136
+ if (composerHasAttachments) {
137
+ toastManager.add({
138
+ type: "warning",
139
+ id: "load-balancing-attachments",
140
+ title: "Keep attachments on this machine",
141
+ description:
142
+ "Remove attachments before choosing automatic routing, then attach them on the selected machine.",
143
+ });
144
+ return;
145
+ }
146
+ loadBalancing.refresh(
147
+ logicalProjectEnvironments.map((environment) => environment.environmentId),
148
+ );
149
+ setDraftThreadContext(draftId, {
150
+ environmentSelection: "auto",
151
+ loadBalancedEnvironmentId: null,
152
+ branch: null,
153
+ worktreePath: null,
154
+ });
155
+ };
156
+ const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
157
+ const autoEnvironmentLabel = automaticEnvironment
158
+ ? draftThread?.loadBalancedEnvironmentId
159
+ ? "Auto balance"
160
+ : loadBalancing.pending
161
+ ? "Checking machines…"
162
+ : loadBalancing.failed
163
+ ? "Auto balance unavailable"
164
+ : "Auto balance"
165
+ : undefined;
166
+
167
+ // A change in flight belongs to the draft and project it started on.
168
+ const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
169
+ const environmentChangeRef = useRef<{
170
+ readonly environmentId: EnvironmentId;
171
+ readonly scope: string;
172
+ } | null>(null);
173
+ const environmentChangeScopeRef = useRef("");
174
+ useLayoutEffect(() => {
175
+ environmentChangeScopeRef.current = environmentChangeScope;
176
+ });
177
+ // Leaving the scope, or unmounting, abandons a change still in flight.
178
+ useLayoutEffect(
179
+ () => () => {
180
+ if (environmentChangeRef.current?.scope === environmentChangeScope) {
181
+ environmentChangeRef.current = null;
182
+ }
183
+ },
184
+ [environmentChangeScope],
185
+ );
186
+ const readPendingEnvironmentChange = () => {
187
+ const pending = environmentChangeRef.current;
188
+ return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
189
+ };
190
+ // The busy state belongs to the request that set it, so an older request settling late
191
+ // (abandoned, or superseded by a newer switch) can never clear a newer one's.
192
+ const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
193
+ readonly environmentId: EnvironmentId;
194
+ readonly scope: string;
195
+ } | null>(null);
196
+ const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;
197
+
198
+ const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
199
+ if (envLocked || !draftId || sendInFlightRef.current) return;
200
+ const originalDraft = getDraftSession(draftId);
201
+ if (!originalDraft || originalDraft.promotedTo) return;
202
+ const target = logicalProjectEnvironments.find(
203
+ (env) => env.environmentId === nextEnvironmentId,
204
+ );
205
+ if (!target) return;
206
+ const request = { environmentId: target.environmentId, scope: environmentChangeScope };
207
+ environmentChangeRef.current = request;
208
+ setBusyEnvironmentChange(null);
209
+ const retarget = (project: (typeof allProjects)[number]) => {
210
+ const currentDraft = getDraftSession(draftId);
211
+ if (
212
+ environmentChangeRef.current !== request ||
213
+ environmentChangeScopeRef.current !== request.scope ||
214
+ sendInFlightRef.current ||
215
+ !currentDraft ||
216
+ currentDraft.promotedTo ||
217
+ currentDraft.environmentId !== originalDraft.environmentId ||
218
+ currentDraft.projectId !== originalDraft.projectId
219
+ )
220
+ return;
221
+ const projectRef = scopeProjectRef(target.environmentId, project.id);
222
+ if (activeProjectIsScratch) {
223
+ setLogicalProjectDraftThreadId(
224
+ deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings),
225
+ projectRef,
226
+ draftId,
227
+ { environmentSelection: "manual", loadBalancedEnvironmentId: null },
228
+ );
229
+ } else {
230
+ setDraftThreadContext(draftId, {
231
+ projectRef,
232
+ environmentSelection: "manual",
233
+ loadBalancedEnvironmentId: null,
234
+ });
235
+ }
236
+ };
237
+ const finish = () => {
238
+ if (environmentChangeRef.current === request) environmentChangeRef.current = null;
239
+ setBusyEnvironmentChange((busy) => (busy === request ? null : busy));
240
+ };
241
+ if (target.projectId !== null) {
242
+ const project = allProjects.find(
243
+ (project) =>
244
+ project.environmentId === target.environmentId && project.id === target.projectId,
245
+ );
246
+ if (project) retarget(project);
247
+ finish();
248
+ return;
249
+ }
250
+ setBusyEnvironmentChange(request);
251
+ void openScratchProject(target.environmentId, "Could not switch machine")
252
+ .then((project) => {
253
+ if (project) retarget(project);
254
+ })
255
+ .finally(finish);
256
+ };
257
+ const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
258
+
259
+ return {
260
+ needsLoadBalancing,
261
+ loadBalancing,
262
+ onAutoEnvironmentStable,
263
+ autoEnvironmentLabel,
264
+ isEnvironmentChanging,
265
+ readPendingEnvironmentChange,
266
+ onEnvironmentChangeStable,
267
+ };
268
+}