Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useDraftEnvironmentRouting.ts

397 lines16.4 KB

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 {
13 scopedThreadKey,
14 scopeProjectRef,
15 scopeThreadRef,
16} from "@t3tools/client-runtime/environment";
17import {
18 isAtomCommandInterrupted,
19 squashAtomCommandFailure,
20} from "@t3tools/client-runtime/state/runtime";
21import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triagePrompt";
22import { useEffect, useLayoutEffect, useRef, useState } from "react";
23import { flushSync } from "react-dom";
24import { stackedThreadToast, toastManager } from "../ui/toast";
25import {
26 deriveLogicalProjectKeyFromSettings,
27 selectProjectGroupingSettings,
28} from "@t3tools/client-runtime/state/project-grouping";
29import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
30import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
31import { currentClientMetadata } from "../../connection/platform";
32import { useProjects } from "../../state/entities";
33import { serverEnvironment } from "../../state/server";
34import { useAtomCommand } from "../../state/use-atom-command";
35import type { DraftSessionState } from "../../composerDraftStore";
36import { loadBalancingSendWarning } from "./composerSend.logic";
37import { appAtomRegistry } from "../../rpc/atomRegistry";
38import { draftFanoutSelectionsAtom } from "./chatViewSend";
39​
40interface DraftEnvironmentRoutingInput {
41 readonly draftId: DraftId | null;
42 readonly draftThread: DraftSessionState | null;
43 readonly envLocked: boolean;
44 readonly automaticEnvironment: boolean;
45 readonly logicalProjectEnvironments: ReturnType<typeof useLogicalProjectEnvironments>;
46 readonly environmentById: ReadonlyMap<EnvironmentId, EnvironmentPresentation>;
47 readonly providersByEnvironment: ReturnType<typeof useEnvironmentProviders>;
48 readonly loadBalancingSettings: {
49 readonly loadBalancingWeights: Readonly<Record<string, number>>;
50 };
51 readonly referencedThreadContexts: ReadonlyArray<ThreadContextRecord>;
52 readonly activeProviderInstanceId: ProviderInstanceId | null;
53 readonly selectedProvider: ProviderDriverKind;
54 readonly composerHasAttachments: boolean;
55 readonly activeProjectKey: string | null;
56 readonly activeProjectIsScratch: boolean;
57 readonly projectGroupingSettings: ReturnType<typeof selectProjectGroupingSettings>;
58 readonly sendInFlightRef: { readonly current: boolean };
60​
61// Multiple-model selections are kept per route, so a draft moving machine takes them along.
62function carryFanoutSelections(
63 draft: Pick<DraftSessionState, "environmentId" | "threadId">,
64 environmentId: EnvironmentId,
65) {
66 if (draft.environmentId === environmentId) return;
67 const selectionsOn = (id: EnvironmentId) =>
68 draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(id, draft.threadId)));
69 appAtomRegistry.set(
70 selectionsOn(environmentId),
71 appAtomRegistry.get(selectionsOn(draft.environmentId)),
72 );
74​
75/**
76 * Which machine an unsent draft runs on: automatic load balancing across the
77 * project's machines, or a manual switch, which may first open a scratch
78 * project on the target machine. A triage draft takes its session along: the
79 * target machine prepares one, and the playbook link follows.
80 */
81export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) {
82 const {
83 draftId,
84 draftThread,
85 envLocked,
86 automaticEnvironment,
87 logicalProjectEnvironments,
88 environmentById,
89 providersByEnvironment,
90 loadBalancingSettings,
91 referencedThreadContexts,
92 activeProviderInstanceId,
93 selectedProvider,
94 composerHasAttachments,
95 activeProjectKey,
96 activeProjectIsScratch,
97 projectGroupingSettings,
98 sendInFlightRef,
99 } = input;
100 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
101 const getDraftSession = useComposerDraftStore((store) => store.getDraftSession);
102 const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
103 const setPrompt = useComposerDraftStore((store) => store.setPrompt);
104 const prepareTriage = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
105 const setLogicalProjectDraftThreadId = useComposerDraftStore(
106 (store) => store.setLogicalProjectDraftThreadId,
107 );
108 const allProjects = useProjects();
109 const { openScratchProject } = useScratchProject();
110 const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
111 const loadBalancingCandidates = automaticEnvironment
112 ? logicalProjectEnvironments
113 .filter((candidate) => {
114 const environment = environmentById.get(candidate.environmentId);
115 return (
116 environment?.connection.phase === "connected" &&
117 (loadBalancingSettings.loadBalancingWeights[candidate.environmentId] ?? 50) > 0 &&
118 referencedThreadContexts.every(
119 (record) => record.environmentId === candidate.environmentId,
120 ) &&
121 providersByEnvironment
122 .get(candidate.environmentId)
123 ?.some(
124 (provider) =>
125 (activeProviderInstanceId === null ||
126 provider.instanceId === activeProviderInstanceId) &&
127 provider.driver === selectedProvider &&
128 (environment.serverConfig?.settings
129 ? resolveProjectProviderInstanceEnabled(
130 environment.serverConfig.settings,
131 candidate.projectId,
132 provider.instanceId,
133 )
134 : provider.enabled) &&
135 provider.installed &&
136 provider.status !== "error" &&
137 provider.auth.status !== "unauthenticated" &&
138 provider.availability !== "unavailable",
139 )
140 );
141 })
142 .map((candidate) => candidate.environmentId)
143 : [];
144 const loadBalancing = useLoadBalancedEnvironment(
145 needsLoadBalancing ? loadBalancingCandidates : [],
146 loadBalancingSettings.loadBalancingWeights,
147 );
148 const readRouting = useStableCallback(() => ({ input, loadBalancingCandidates }));
149 const refreshBeforeSend = () => {
150 if (
151 !automaticEnvironment ||
152 !draftId ||
153 !draftThread?.loadBalancedEnvironmentId ||
154 draftThread.promotedTo ||
155 composerHasAttachments
156 )
157 return null;
158 const originalDraft = getDraftSession(draftId);
159 const composerDraft = useComposerDraftStore.getState().getComposerDraft(draftId);
160 return loadBalancing.refreshSelection(loadBalancingCandidates).then((environmentId) => {
161 const current = readRouting();
162 if (
163 current.input.draftId !== draftId ||
164 !current.input.automaticEnvironment ||
165 current.input.composerHasAttachments ||
166 current.input.activeProjectKey !== activeProjectKey ||
167 current.input.selectedProvider !== selectedProvider ||
168 current.input.activeProviderInstanceId !== activeProviderInstanceId ||
169 current.input.loadBalancingSettings.loadBalancingWeights !==
170 loadBalancingSettings.loadBalancingWeights ||
171 current.loadBalancingCandidates.join("\n") !== loadBalancingCandidates.join("\n") ||
172 getDraftSession(draftId) !== originalDraft ||
173 useComposerDraftStore.getState().getComposerDraft(draftId) !== composerDraft
174 )
175 return false;
176 const target = current.input.logicalProjectEnvironments.find(
177 (candidate) => candidate.environmentId === environmentId,
178 );
179 if (!target?.projectId) {
180 toastManager.add({
181 type: "warning",
182 ...loadBalancingSendWarning({
183 pending: false,
184 threadContexts: referencedThreadContexts,
185 candidateEnvironmentIds: loadBalancingCandidates,
186 }),
187 });
188 return false;
189 }
190 const projectRef = scopeProjectRef(target.environmentId, target.projectId);
191 if (originalDraft) carryFanoutSelections(originalDraft, target.environmentId);
192 // The send must read the target project's composer and provider context after retargeting.
193 flushSync(() =>
194 setDraftThreadContext(draftId, {
195 projectRef,
196 environmentSelection: "auto",
197 loadBalancedEnvironmentId: target.environmentId,
198 branch: originalDraft?.branch ?? null,
199 }),
200 );
201 return true;
202 });
203 };
204 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the resolved load-balanced environment into the draft store once the async pick settles
205 useEffect(() => {
206 if (!needsLoadBalancing || loadBalancing.pending || !draftId || sendInFlightRef.current) return;
207 const target = logicalProjectEnvironments.find(
208 (environment) => environment.environmentId === loadBalancing.environmentId,
209 );
210 if (!target?.projectId) return;
211 const draft = getDraftSession(draftId);
212 if (draft) carryFanoutSelections(draft, target.environmentId);
213 setDraftThreadContext(draftId, {
214 projectRef: scopeProjectRef(target.environmentId, target.projectId),
215 environmentSelection: "auto",
216 loadBalancedEnvironmentId: target.environmentId,
217 });
218 }, [
219 needsLoadBalancing,
220 loadBalancing.pending,
221 loadBalancing.environmentId,
222 draftId,
223 logicalProjectEnvironments,
224 sendInFlightRef,
225 getDraftSession,
226 setDraftThreadContext,
227 ]);
228 const onAutoEnvironment = () => {
229 if (envLocked || !draftId || sendInFlightRef.current) return;
230 if (composerHasAttachments) {
231 toastManager.add({
232 type: "warning",
233 id: "load-balancing-attachments",
234 title: "Keep attachments on this machine",
235 description:
236 "Remove attachments before choosing automatic routing, then attach them on the selected machine.",
237 });
238 return;
239 }
240 loadBalancing.refresh(
241 logicalProjectEnvironments.map((environment) => environment.environmentId),
242 );
243 setDraftThreadContext(draftId, {
244 environmentSelection: "auto",
245 loadBalancedEnvironmentId: null,
246 branch: null,
247 worktreePath: null,
248 });
249 };
250 const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
251 const autoEnvironmentLabel = automaticEnvironment
252 ? draftThread?.loadBalancedEnvironmentId
253 ? "Auto balance"
254 : loadBalancing.pending
255 ? "Checking machines…"
256 : loadBalancing.failed
257 ? "Auto balance unavailable"
258 : "Auto balance"
259 : undefined;
260​
261 // A change in flight belongs to the draft and project it started on.
262 const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
263 const environmentChangeRef = useRef<{
264 readonly environmentId: EnvironmentId;
265 readonly scope: string;
266 } | null>(null);
267 const environmentChangeScopeRef = useRef("");
268 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the current change scope into a ref that async environment switches compare against
269 useLayoutEffect(() => {
270 environmentChangeScopeRef.current = environmentChangeScope;
271 });
272 // Leaving the scope, or unmounting, abandons a change still in flight.
273 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons an in-flight environment change when the draft or project scope changes or unmounts
274 useLayoutEffect(
275 () => () => {
276 if (environmentChangeRef.current?.scope === environmentChangeScope) {
277 environmentChangeRef.current = null;
278 }
279 },
280 [environmentChangeScope],
281 );
282 const readPendingEnvironmentChange = () => {
283 const pending = environmentChangeRef.current;
284 return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
285 };
286 // The busy state belongs to the request that set it, so an older request settling late
287 // (abandoned, or superseded by a newer switch) can never clear a newer one's.
288 const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
289 readonly environmentId: EnvironmentId;
290 readonly scope: string;
291 } | null>(null);
292 const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;
293​
294 const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
295 if (envLocked || !draftId || sendInFlightRef.current) return;
296 const originalDraft = getDraftSession(draftId);
297 if (!originalDraft || originalDraft.promotedTo) return;
298 const target = logicalProjectEnvironments.find(
299 (env) => env.environmentId === nextEnvironmentId,
300 );
301 if (!target) return;
302 const request = { environmentId: target.environmentId, scope: environmentChangeScope };
303 environmentChangeRef.current = request;
304 setBusyEnvironmentChange(null);
305 // `triagePrompt` is the prompt the target machine prepared for a triage draft.
306 const retarget = (project: (typeof allProjects)[number], triagePrompt?: string) => {
307 const currentDraft = getDraftSession(draftId);
308 if (
309 environmentChangeRef.current !== request ||
310 environmentChangeScopeRef.current !== request.scope ||
311 sendInFlightRef.current ||
312 !currentDraft ||
313 currentDraft.promotedTo ||
314 currentDraft.environmentId !== originalDraft.environmentId ||
315 currentDraft.projectId !== originalDraft.projectId
316 )
317 return;
318 if (triagePrompt !== undefined) {
319 // Read now, so text typed while the machine prepared the session is kept.
320 const prompt = getComposerDraft(draftId)?.prompt ?? "";
321 const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt);
322 if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt);
323 }
324 carryFanoutSelections(currentDraft, target.environmentId);
325 const projectRef = scopeProjectRef(target.environmentId, project.id);
326 if (activeProjectIsScratch) {
327 setLogicalProjectDraftThreadId(
328 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings),
329 projectRef,
330 draftId,
331 { environmentSelection: "manual", loadBalancedEnvironmentId: null },
332 );
333 } else {
334 setDraftThreadContext(draftId, {
335 projectRef,
336 environmentSelection: "manual",
337 loadBalancedEnvironmentId: null,
338 });
339 }
340 };
341 const finish = () => {
342 if (environmentChangeRef.current === request) environmentChangeRef.current = null;
343 setBusyEnvironmentChange((busy) => (busy === request ? null : busy));
344 };
345 const knownProject = allProjects.find(
346 (project) =>
347 project.environmentId === target.environmentId && project.id === target.projectId,
348 );
349 // The playbook and context files exist only on the machine that prepared them.
350 const followsTriage = isTriagePrompt(getComposerDraft(draftId)?.prompt ?? "");
351 if (target.projectId !== null && !(knownProject && followsTriage)) {
352 if (knownProject) retarget(knownProject);
353 finish();
354 return;
355 }
356 const prepareTriagePrompt = async () => {
357 const prepared = await prepareTriage({
358 environmentId: target.environmentId,
359 input: { client: currentClientMetadata() },
360 });
361 if (prepared._tag === "Success") return prepared.value.prompt;
362 if (!isAtomCommandInterrupted(prepared)) {
363 const error = squashAtomCommandFailure(prepared);
364 toastManager.add(
365 stackedThreadToast({
366 type: "error",
367 title: "Could not switch machine",
368 description: error instanceof Error ? error.message : "An error occurred.",
369 }),
370 );
371 }
372 return null;
373 };
374 const switchMachine = async () => {
375 const triagePrompt = followsTriage ? await prepareTriagePrompt() : undefined;
376 if (triagePrompt === null) return;
377 const project =
378 knownProject ??
379 (await openScratchProject(target.environmentId, "Could not switch machine"));
380 if (project) retarget(project, triagePrompt);
381 };
382 setBusyEnvironmentChange(request);
383 void switchMachine().finally(finish);
384 };
385 const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
386​
387 return {
388 needsLoadBalancing,
389 loadBalancing,
390 refreshBeforeSend,
391 onAutoEnvironmentStable,
392 autoEnvironmentLabel,
393 isEnvironmentChanging,
394 readPendingEnvironmentChange,
395 onEnvironmentChangeStable,
396 };