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

useDraftEnvironmentRouting.ts

574 lines23.3 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 ScopedProjectRef,
14 type ThreadContextRecord,
15} from "@t3tools/contracts";
16import {
17 scopedThreadKey,
18 scopeProjectRef,
19 scopeThreadRef,
20} from "@t3tools/client-runtime/environment";
21import {
22 isAtomCommandInterrupted,
23 squashAtomCommandFailure,
24} from "@t3tools/client-runtime/state/runtime";
25import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triagePrompt";
26import { useEffect, useLayoutEffect, useRef, useState } from "react";
27import { flushSync } from "react-dom";
28import { shallow } from "zustand/shallow";
29import { stackedThreadToast, toastManager } from "../ui/toast";
30import {
31 deriveLogicalProjectKeyFromSettings,
32 selectProjectGroupingSettings,
33} from "@t3tools/client-runtime/state/project-grouping";
34import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
35import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
36import { currentClientMetadata } from "../../connection/platform";
37import { readProject, readProjects, subscribeProjects, useProjects } from "../../state/entities";
38import { serverEnvironment } from "../../state/server";
39import { useAtomCommand } from "../../state/use-atom-command";
40import type { DraftSessionState } from "../../composerDraftStore";
41import { loadBalancingSendWarning } from "./composerSend.logic";
42import { appAtomRegistry } from "../../rpc/atomRegistry";
43import { retargetDraftWorkspace } from "../../lib/retargetDraftWorkspace";
44import { trackPendingWorkspaceDefault } from "../../lib/draftWorkspaceDefaults";
45import { vcsEnvironment } from "../../state/vcs";
46import { resolveDefaultWorktreeBaseBranch } from "../BranchToolbar.logic";
47import { seedDraftModelSelection } from "../../lib/seedDraftModelSelection";
48import { draftFanoutSelectionsAtom } from "./chatViewSend";
49​
50interface DraftEnvironmentRoutingInput {
51 readonly draftId: DraftId | null;
52 readonly draftThread: DraftSessionState | null;
53 readonly envLocked: boolean;
54 readonly automaticEnvironment: boolean;
55 readonly logicalProjectEnvironments: ReturnType<typeof useLogicalProjectEnvironments>;
56 readonly environmentById: ReadonlyMap<EnvironmentId, EnvironmentPresentation>;
57 readonly providersByEnvironment: ReturnType<typeof useEnvironmentProviders>;
58 readonly loadBalancingSettings: {
59 readonly loadBalancingWeights: Readonly<Record<string, number>>;
60 };
61 readonly referencedThreadContexts: ReadonlyArray<ThreadContextRecord>;
62 readonly activeProviderInstanceId: ProviderInstanceId | null;
63 readonly selectedProvider: ProviderDriverKind;
64 readonly composerHasAttachments: boolean;
65 readonly activeProjectKey: string | null;
66 readonly activeProjectIsScratch: boolean;
67 readonly projectGroupingSettings: ReturnType<typeof selectProjectGroupingSettings>;
68 readonly sendInFlightRef: { readonly current: boolean };
70​
71// Multiple-model selections are kept per route, so a draft moving machine takes them along.
72function carryFanoutSelections(
73 draft: Pick<DraftSessionState, "environmentId" | "threadId">,
74 environmentId: EnvironmentId,
75) {
76 if (draft.environmentId === environmentId) return;
77 const selectionsOn = (id: EnvironmentId) =>
78 draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(id, draft.threadId)));
79 appAtomRegistry.set(
80 selectionsOn(environmentId),
81 appAtomRegistry.get(selectionsOn(draft.environmentId)),
82 );
84​
85// A send waits on this; a read stuck on a reconnecting machine falls back to no project file.
86function readDestinationWorkspace(draft: DraftSessionState, projectRef: ScopedProjectRef) {
87 return retargetDraftWorkspace(draft, projectRef, AbortSignal.timeout(5_000));
89​
90function changesProject(draft: DraftSessionState, projectRef: ScopedProjectRef) {
91 return (
92 draft.environmentId !== projectRef.environmentId || draft.projectId !== projectRef.projectId
93 );
95​
96/**
97 * Which machine an unsent draft runs on: automatic load balancing across the
98 * project's machines, or a manual switch, which may first open a scratch
99 * project on the target machine. A triage draft takes its session along: the
100 * target machine prepares one, and the playbook link follows.
101 */
102export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) {
103 const gt = useGT();
104 const {
105 draftId,
106 draftThread,
107 envLocked,
108 automaticEnvironment,
109 logicalProjectEnvironments,
110 environmentById,
111 providersByEnvironment,
112 loadBalancingSettings,
113 referencedThreadContexts,
114 activeProviderInstanceId,
115 selectedProvider,
116 composerHasAttachments,
117 activeProjectKey,
118 activeProjectIsScratch,
119 projectGroupingSettings,
120 sendInFlightRef,
121 } = input;
122 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
123 const getDraftSession = useComposerDraftStore((store) => store.getDraftSession);
124 const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
125 const setPrompt = useComposerDraftStore((store) => store.setPrompt);
126 const prepareTriage = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
127 const setLogicalProjectDraftThreadId = useComposerDraftStore(
128 (store) => store.setLogicalProjectDraftThreadId,
129 );
130 const allProjects = useProjects();
131 const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
132 const { openScratchProject } = useScratchProject();
133 const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
134 const loadBalancingCandidates = automaticEnvironment
135 ? logicalProjectEnvironments
136 .filter((candidate) => {
137 const environment = environmentById.get(candidate.environmentId);
138 return (
139 environment?.connection.phase === "connected" &&
140 (loadBalancingSettings.loadBalancingWeights[candidate.environmentId] ?? 50) > 0 &&
141 referencedThreadContexts.every(
142 (record) => record.environmentId === candidate.environmentId,
143 ) &&
144 providersByEnvironment
145 .get(candidate.environmentId)
146 ?.some(
147 (provider) =>
148 (activeProviderInstanceId === null ||
149 provider.instanceId === activeProviderInstanceId) &&
150 provider.driver === selectedProvider &&
151 (environment.serverConfig?.settings
152 ? resolveProjectProviderInstanceEnabled(
153 environment.serverConfig.settings,
154 candidate.projectId,
155 provider.instanceId,
156 )
157 : provider.enabled) &&
158 provider.installed &&
159 provider.status !== "error" &&
160 provider.auth.status !== "unauthenticated" &&
161 provider.availability !== "unavailable",
162 )
163 );
164 })
165 .map((candidate) => candidate.environmentId)
166 : [];
167 const loadBalancing = useLoadBalancedEnvironment(
168 needsLoadBalancing ? loadBalancingCandidates : [],
169 loadBalancingSettings.loadBalancingWeights,
170 );
171 const mountedRoutingScope = useRef<object | null>(null);
172 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- invalidates send preparation when the draft or project scope closes
173 useLayoutEffect(() => {
174 mountedRoutingScope.current = { draftId, activeProjectKey };
175 return () => {
176 mountedRoutingScope.current = null;
177 };
178 }, [draftId, activeProjectKey]);
179 const readRouting = useStableCallback(() => ({ input, loadBalancingCandidates }));
180 const readWorktreeBase = async (projectRef: ScopedProjectRef, branch: string | null) => {
181 const cwd = readProject(projectRef)?.workspaceRoot;
182 if (!cwd) return null;
183 const { environmentId } = projectRef;
184 const call = { signal: AbortSignal.timeout(5_000) };
185 if (branch) {
186 let cursor: number | undefined;
187 do {
188 const matching = await readRefs(
189 {
190 environmentId,
191 input: { cwd, query: branch.slice(0, 256), cursor, includeMatchingRemoteRefs: true },
192 },
193 call,
194 );
195 if (matching._tag !== "Success") break;
196 if (matching.value.refs.some((ref) => ref.name === branch)) return branch;
197 cursor = matching.value.nextCursor ?? undefined;
198 } while (cursor !== undefined && !call.signal.aborted);
199 }
200 const result = await readRefs({ environmentId, input: { cwd, limit: 2 } }, call);
201 return result._tag === "Success" ? resolveDefaultWorktreeBaseBranch(result.value.refs) : null;
202 };
203 const refreshBeforeSend = () => {
204 if (
205 !automaticEnvironment ||
206 !draftId ||
207 !draftThread?.loadBalancedEnvironmentId ||
208 draftThread.promotedTo ||
209 composerHasAttachments
210 )
211 return null;
212 const originalDraft = getDraftSession(draftId);
213 const scope = mountedRoutingScope.current;
214 if (!originalDraft || !scope) return null;
215 const composerDraft = useComposerDraftStore.getState().getComposerDraft(draftId);
216 const readCurrentRouting = () => {
217 const current = readRouting();
218 const latestDraft = getDraftSession(draftId);
219 const draftMatches =
220 latestDraft === originalDraft ||
221 // The picker may fill an empty base while any of the routing reads are pending.
222 // Its automatic write keeps the routing mode; a manual pick switches it to manual.
223 (originalDraft.envMode === "worktree" &&
224 originalDraft.branch === null &&
225 latestDraft?.branch != null &&
226 shallow(latestDraft, {
227 ...originalDraft,
228 branch: latestDraft.branch,
229 environmentSelection: originalDraft.environmentSelection ?? "auto",
230 }));
231 return mountedRoutingScope.current === scope &&
232 current.input.draftId === draftId &&
233 current.input.automaticEnvironment &&
234 !current.input.composerHasAttachments &&
235 current.input.activeProjectKey === activeProjectKey &&
236 current.input.selectedProvider === selectedProvider &&
237 current.input.activeProviderInstanceId === activeProviderInstanceId &&
238 current.input.loadBalancingSettings.loadBalancingWeights ===
239 loadBalancingSettings.loadBalancingWeights &&
240 current.loadBalancingCandidates.join("\n") === loadBalancingCandidates.join("\n") &&
241 draftMatches &&
242 useComposerDraftStore.getState().getComposerDraft(draftId) === composerDraft
243 ? current
244 : null;
245 };
246 return loadBalancing.refreshSelection(loadBalancingCandidates).then(async (environmentId) => {
247 const current = readCurrentRouting();
248 if (!current) return false;
249 const target = current.input.logicalProjectEnvironments.find(
250 (candidate) => candidate.environmentId === environmentId,
251 );
252 if (!target?.projectId) {
253 toastManager.add({
254 type: "warning",
255 ...loadBalancingSendWarning({
256 pending: false,
257 threadContexts: referencedThreadContexts,
258 candidateEnvironmentIds: loadBalancingCandidates,
259 }),
260 });
261 return false;
262 }
263 const projectRef = scopeProjectRef(target.environmentId, target.projectId);
264 const moved = changesProject(originalDraft, projectRef);
265 const workspace = moved ? await readDestinationWorkspace(originalDraft, projectRef) : {};
266 const isWorktree = (workspace.envMode ?? originalDraft.envMode) === "worktree";
267 const branch =
268 isWorktree && (moved || originalDraft.branch === null)
269 ? await readWorktreeBase(projectRef, originalDraft.branch)
270 : moved
271 ? null
272 : originalDraft.branch;
273 if (
274 !readCurrentRouting()?.input.logicalProjectEnvironments.some(
275 (candidate) =>
276 candidate.environmentId === environmentId && candidate.projectId === target.projectId,
277 )
278 )
279 return false;
280​
281 carryFanoutSelections(originalDraft, target.environmentId);
282 // The send must read the target project's composer and provider context after retargeting.
283 flushSync(() =>
284 setDraftThreadContext(draftId, {
285 projectRef,
286 environmentSelection: "auto",
287 loadBalancedEnvironmentId: target.environmentId,
288 ...workspace,
289 branch,
290 }),
291 );
292 return true;
293 });
294 };
295 const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
296 // The busy state belongs to the request that set it, so an older request settling late
297 // (abandoned, or superseded by a newer switch) can never clear a newer one's.
298 const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
299 readonly environmentId: EnvironmentId;
300 readonly scope: string;
301 } | null>(null);
302 const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;
303​
304 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the resolved load-balanced environment into the draft store once the async pick settles
305 useEffect(() => {
306 if (
307 !needsLoadBalancing ||
308 loadBalancing.pending ||
309 !draftId ||
310 isEnvironmentChanging ||
311 sendInFlightRef.current
312 )
313 return;
314 const target = logicalProjectEnvironments.find(
315 (environment) => environment.environmentId === loadBalancing.environmentId,
316 );
317 if (!target?.projectId) return;
318 const draft = getDraftSession(draftId);
319 if (!draft) return;
320 const projectRef = scopeProjectRef(target.environmentId, target.projectId);
321 carryFanoutSelections(draft, target.environmentId);
322 setDraftThreadContext(draftId, {
323 projectRef,
324 environmentSelection: "auto",
325 loadBalancedEnvironmentId: target.environmentId,
326 });
327 if (changesProject(draft, projectRef)) {
328 const current = { envMode: draft.envMode, startFromOrigin: draft.startFromOrigin };
329 trackPendingWorkspaceDefault(
330 draftId,
331 projectRef,
332 current,
333 readDestinationWorkspace(draft, projectRef).then((workspace) => ({
334 ...current,
335 ...workspace,
336 })),
337 );
338 }
339 }, [
340 needsLoadBalancing,
341 loadBalancing.pending,
342 loadBalancing.environmentId,
343 isEnvironmentChanging,
344 draftId,
345 logicalProjectEnvironments,
346 sendInFlightRef,
347 getDraftSession,
348 setDraftThreadContext,
349 ]);
350 // A change in flight belongs to the draft and project it started on.
351 const environmentChangeRef = useRef<{
352 readonly controller: AbortController;
353 readonly environmentId: EnvironmentId;
354 readonly scope: string;
355 } | null>(null);
356 const environmentChangeScopeRef = useRef("");
357 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the current change scope into a ref that async environment switches compare against
358 useLayoutEffect(() => {
359 environmentChangeScopeRef.current = environmentChangeScope;
360 });
361 // Leaving the scope, or unmounting, abandons a change still in flight.
362 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons an in-flight environment change when the draft or project scope changes or unmounts
363 useLayoutEffect(
364 () => () => {
365 if (environmentChangeRef.current?.scope === environmentChangeScope) {
366 environmentChangeRef.current.controller.abort();
367 environmentChangeRef.current = null;
368 }
369 },
370 [environmentChangeScope],
371 );
372 const readPendingEnvironmentChange = () => {
373 const pending = environmentChangeRef.current;
374 return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
375 };
376 const onAutoEnvironment = () => {
377 if (envLocked || !draftId || sendInFlightRef.current) return;
378 if (composerHasAttachments) {
379 toastManager.add({
380 type: "warning",
381 id: "load-balancing-attachments",
382 title: m(msg("Keep attachments on this machine")),
383 description: m(
384 msg(
385 "Remove attachments before choosing automatic routing, then attach them on the selected machine.",
386 ),
387 ),
388 });
389 return;
390 }
391 environmentChangeRef.current?.controller.abort();
392 environmentChangeRef.current = null;
393 setBusyEnvironmentChange(null);
394 loadBalancing.refresh(
395 logicalProjectEnvironments.map((environment) => environment.environmentId),
396 );
397 setDraftThreadContext(draftId, {
398 environmentSelection: "auto",
399 loadBalancedEnvironmentId: null,
400 branch: null,
401 worktreePath: null,
402 });
403 };
404 const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
405 const autoEnvironmentLabel = automaticEnvironment
406 ? draftThread?.loadBalancedEnvironmentId
407 ? gt("Auto balance")
408 : loadBalancing.pending
409 ? gt("Checking machines…")
410 : loadBalancing.failed
411 ? gt("Auto balance unavailable")
412 : gt("Auto balance")
413 : undefined;
414​
415 const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
416 if (envLocked || !draftId || sendInFlightRef.current) return;
417 const originalDraft = getDraftSession(draftId);
418 if (!originalDraft || originalDraft.promotedTo) return;
419 const target = logicalProjectEnvironments.find(
420 (env) => env.environmentId === nextEnvironmentId,
421 );
422 if (!target) return;
423 environmentChangeRef.current?.controller.abort();
424 const request = {
425 controller: new AbortController(),
426 environmentId: target.environmentId,
427 scope: environmentChangeScope,
428 };
429 environmentChangeRef.current = request;
430 setBusyEnvironmentChange(null);
431 const readSwitchingDraft = () => {
432 const currentDraft = getDraftSession(draftId);
433 if (
434 environmentChangeRef.current !== request ||
435 environmentChangeScopeRef.current !== request.scope ||
436 sendInFlightRef.current ||
437 !currentDraft ||
438 currentDraft.promotedTo ||
439 currentDraft.environmentId !== originalDraft.environmentId ||
440 currentDraft.projectId !== originalDraft.projectId
441 )
442 return null;
443 return currentDraft;
444 };
445 // `triagePrompt` is the prompt the target machine prepared for a triage draft.
446 const retarget = async (
447 project: (typeof allProjects)[number],
448 triagePrompt?: string,
449 ): Promise<void> => {
450 const draft = readSwitchingDraft();
451 if (!draft) return;
452 const projectRef = scopeProjectRef(target.environmentId, project.id);
453 // Use the catalog-backed list: an unpaired machine can still have a cached project snapshot.
454 const findDestination = (projects: typeof allProjects) =>
455 projects.find(
456 (candidate) =>
457 candidate.environmentId === projectRef.environmentId &&
458 candidate.id === projectRef.projectId,
459 );
460 const workspaceRoot = findDestination(readProjects())?.workspaceRoot;
461 const controller = new AbortController();
462 const unsubscribe = subscribeProjects((projects) => {
463 if (findDestination(projects)?.workspaceRoot !== workspaceRoot) controller.abort();
464 });
465 const workspaceRead =
466 workspaceRoot === undefined
467 ? Promise.resolve({})
468 : retargetDraftWorkspace(
469 draft,
470 projectRef,
471 AbortSignal.any([request.controller.signal, controller.signal]),
472 );
473 const defaultWorkspace = await workspaceRead.finally(unsubscribe);
474 const currentDraft = readSwitchingDraft();
475 if (!currentDraft) return;
476 const destination = findDestination(readProjects());
477 if (!destination) {
478 toastManager.add(
479 stackedThreadToast({
480 type: "error",
481 title: m(msg("Could not switch machine")),
482 description: m(msg("This project is no longer available.")),
483 }),
484 );
485 return;
486 }
487 if (controller.signal.aborted || destination.workspaceRoot !== workspaceRoot) {
488 return retarget(destination, triagePrompt);
489 }
490 const workspace =
491 currentDraft.workspaceExplicit || currentDraft.worktreePath !== null
492 ? {}
493 : defaultWorkspace;
494 if (triagePrompt !== undefined) {
495 // Read now, so text typed while the machine prepared the session is kept.
496 const prompt = getComposerDraft(draftId)?.prompt ?? "";
497 const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt);
498 if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt);
499 }
500 const moved = changesProject(currentDraft, projectRef);
501 carryFanoutSelections(currentDraft, target.environmentId);
502 if (activeProjectIsScratch) {
503 setLogicalProjectDraftThreadId(
504 deriveLogicalProjectKeyFromSettings(destination, projectGroupingSettings),
505 projectRef,
506 draftId,
507 { environmentSelection: "manual", loadBalancedEnvironmentId: null, ...workspace },
508 );
509 } else {
510 setDraftThreadContext(draftId, {
511 projectRef,
512 environmentSelection: "manual",
513 loadBalancedEnvironmentId: null,
514 ...workspace,
515 });
516 }
517 if (moved) seedDraftModelSelection(draftId, projectRef);
518 };
519 const finish = () => {
520 if (environmentChangeRef.current === request) environmentChangeRef.current = null;
521 setBusyEnvironmentChange((busy) => (busy === request ? null : busy));
522 };
523 const knownProject = allProjects.find(
524 (project) =>
525 project.environmentId === target.environmentId && project.id === target.projectId,
526 );
527 // The playbook and context files exist only on the machine that prepared them.
528 const followsTriage = isTriagePrompt(getComposerDraft(draftId)?.prompt ?? "");
529 if (target.projectId !== null && !knownProject) {
530 finish();
531 return;
532 }
533 const prepareTriagePrompt = async () => {
534 const prepared = await prepareTriage({
535 environmentId: target.environmentId,
536 input: { client: currentClientMetadata() },
537 });
538 if (prepared._tag === "Success") return prepared.value.prompt;
539 if (!isAtomCommandInterrupted(prepared)) {
540 const error = squashAtomCommandFailure(prepared);
541 toastManager.add(
542 stackedThreadToast({
543 type: "error",
544 title: m(msg("Could not switch machine")),
545 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
546 }),
547 );
548 }
549 return null;
550 };
551 const switchMachine = async () => {
552 const triagePrompt = followsTriage ? await prepareTriagePrompt() : undefined;
553 if (triagePrompt === null) return;
554 const project =
555 knownProject ??
556 (await openScratchProject(target.environmentId, m(msg("Could not switch machine"))));
557 if (project) await retarget(project, triagePrompt);
558 };
559 setBusyEnvironmentChange(request);
560 void switchMachine().finally(finish);
561 };
562 const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
563​
564 return {
565 needsLoadBalancing,
566 loadBalancing,
567 refreshBeforeSend,
568 onAutoEnvironmentStable,
569 autoEnvironmentLabel,
570 isEnvironmentChanging,
571 readPendingEnvironmentChange,
572 onEnvironmentChangeStable,
573 };