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

useDraftEnvironmentRouting.ts

409 lines16.9 KB

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