Open History to see the last commit
1import { useLoadBalancedEnvironment } from "../../hooks/useLoadBalancedEnvironment";
2import { useLogicalProjectEnvironments } from "../../hooks/useLogicalProjectEnvironments";
3import { useScratchProject } from "../../hooks/useScratchProject";
4import { useStableCallback } from "../../hooks/useStableCallback";
5import {
6 type EnvironmentId,
7 type ProviderDriverKind,
8 ProviderInstanceId,
9 resolveProjectProviderInstanceEnabled,
10 type ThreadContextRecord,
11} from "@t3tools/contracts";
12import { scopeProjectRef } from "@t3tools/client-runtime/environment";
13import { useEffect, useLayoutEffect, useRef, useState } from "react";
14import { toastManager } from "../ui/toast";
15import {
16 deriveLogicalProjectKeyFromSettings,
17 selectProjectGroupingSettings,
18} from "@t3tools/client-runtime/state/project-grouping";
19import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
20import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
21import { useProjects } from "../../state/entities";
22import type { DraftSessionState } from "../../composerDraftStore";
23
24interface 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 */
50export 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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the resolved load-balanced environment into the draft store once the async pick settles
115 useEffect(() => {
116 if (!needsLoadBalancing || loadBalancing.pending || !draftId || sendInFlightRef.current) return;
117 const target = logicalProjectEnvironments.find(
118 (environment) => environment.environmentId === loadBalancing.environmentId,
119 );
120 if (!target?.projectId) return;
121 setDraftThreadContext(draftId, {
122 projectRef: scopeProjectRef(target.environmentId, target.projectId),
123 environmentSelection: "auto",
124 loadBalancedEnvironmentId: target.environmentId,
125 });
126 }, [
127 needsLoadBalancing,
128 loadBalancing.pending,
129 loadBalancing.environmentId,
130 draftId,
131 logicalProjectEnvironments,
132 sendInFlightRef,
133 setDraftThreadContext,
134 ]);
135 const onAutoEnvironment = () => {
136 if (envLocked || !draftId) return;
137 if (composerHasAttachments) {
138 toastManager.add({
139 type: "warning",
140 id: "load-balancing-attachments",
141 title: "Keep attachments on this machine",
142 description:
143 "Remove attachments before choosing automatic routing, then attach them on the selected machine.",
144 });
145 return;
146 }
147 loadBalancing.refresh(
148 logicalProjectEnvironments.map((environment) => environment.environmentId),
149 );
150 setDraftThreadContext(draftId, {
151 environmentSelection: "auto",
152 loadBalancedEnvironmentId: null,
153 branch: null,
154 worktreePath: null,
155 });
156 };
157 const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
158 const autoEnvironmentLabel = automaticEnvironment
159 ? draftThread?.loadBalancedEnvironmentId
160 ? "Auto balance"
161 : loadBalancing.pending
162 ? "Checking machines…"
163 : loadBalancing.failed
164 ? "Auto balance unavailable"
165 : "Auto balance"
166 : undefined;
167
168 // A change in flight belongs to the draft and project it started on.
169 const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
170 const environmentChangeRef = useRef<{
171 readonly environmentId: EnvironmentId;
172 readonly scope: string;
173 } | null>(null);
174 const environmentChangeScopeRef = useRef("");
175 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the current change scope into a ref that async environment switches compare against
176 useLayoutEffect(() => {
177 environmentChangeScopeRef.current = environmentChangeScope;
178 });
179 // Leaving the scope, or unmounting, abandons a change still in flight.
180 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons an in-flight environment change when the draft or project scope changes or unmounts
181 useLayoutEffect(
182 () => () => {
183 if (environmentChangeRef.current?.scope === environmentChangeScope) {
184 environmentChangeRef.current = null;
185 }
186 },
187 [environmentChangeScope],
188 );
189 const readPendingEnvironmentChange = () => {
190 const pending = environmentChangeRef.current;
191 return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
192 };
193 // The busy state belongs to the request that set it, so an older request settling late
194 // (abandoned, or superseded by a newer switch) can never clear a newer one's.
195 const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
196 readonly environmentId: EnvironmentId;
197 readonly scope: string;
198 } | null>(null);
199 const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;
200
201 const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
202 if (envLocked || !draftId || sendInFlightRef.current) return;
203 const originalDraft = getDraftSession(draftId);
204 if (!originalDraft || originalDraft.promotedTo) return;
205 const target = logicalProjectEnvironments.find(
206 (env) => env.environmentId === nextEnvironmentId,
207 );
208 if (!target) return;
209 const request = { environmentId: target.environmentId, scope: environmentChangeScope };
210 environmentChangeRef.current = request;
211 setBusyEnvironmentChange(null);
212 const retarget = (project: (typeof allProjects)[number]) => {
213 const currentDraft = getDraftSession(draftId);
214 if (
215 environmentChangeRef.current !== request ||
216 environmentChangeScopeRef.current !== request.scope ||
217 sendInFlightRef.current ||
218 !currentDraft ||
219 currentDraft.promotedTo ||
220 currentDraft.environmentId !== originalDraft.environmentId ||
221 currentDraft.projectId !== originalDraft.projectId
222 )
223 return;
224 const projectRef = scopeProjectRef(target.environmentId, project.id);
225 if (activeProjectIsScratch) {
226 setLogicalProjectDraftThreadId(
227 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings),
228 projectRef,
229 draftId,
230 { environmentSelection: "manual", loadBalancedEnvironmentId: null },
231 );
232 } else {
233 setDraftThreadContext(draftId, {
234 projectRef,
235 environmentSelection: "manual",
236 loadBalancedEnvironmentId: null,
237 });
238 }
239 };
240 const finish = () => {
241 if (environmentChangeRef.current === request) environmentChangeRef.current = null;
242 setBusyEnvironmentChange((busy) => (busy === request ? null : busy));
243 };
244 if (target.projectId !== null) {
245 const project = allProjects.find(
246 (project) =>
247 project.environmentId === target.environmentId && project.id === target.projectId,
248 );
249 if (project) retarget(project);
250 finish();
251 return;
252 }
253 setBusyEnvironmentChange(request);
254 void openScratchProject(target.environmentId, "Could not switch machine")
255 .then((project) => {
256 if (project) retarget(project);
257 })
258 .finally(finish);
259 };
260 const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
261
262 return {
263 needsLoadBalancing,
264 loadBalancing,
265 onAutoEnvironmentStable,
266 autoEnvironmentLabel,
267 isEnvironmentChanging,
268 readPendingEnvironmentChange,
269 onEnvironmentChangeStable,
270 };
271}