Open History to see the last commit
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 };
69}
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 );
83}
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));
88}
89
90function changesProject(draft: DraftSessionState, projectRef: ScopedProjectRef) {
91 return (
92 draft.environmentId !== projectRef.environmentId || draft.projectId !== projectRef.projectId
93 );
94}
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: {
192 cwd,
193 query: branch.slice(0, 256),
194 cursor,
195 includeMatchingRemoteRefs: true,
196 // Only a refresh confirms a base created outside T3 Code since the last listing.
197 refresh: cursor === undefined,
198 },
199 },
200 call,
201 );
202 if (matching._tag !== "Success") break;
203 if (matching.value.refs.some((ref) => ref.name === branch)) return branch;
204 cursor = matching.value.nextCursor ?? undefined;
205 } while (cursor !== undefined && !call.signal.aborted);
206 }
207 const result = await readRefs({ environmentId, input: { cwd, limit: 2 } }, call);
208 return result._tag === "Success" ? resolveDefaultWorktreeBaseBranch(result.value.refs) : null;
209 };
210 const refreshBeforeSend = () => {
211 if (
212 !automaticEnvironment ||
213 !draftId ||
214 !draftThread?.loadBalancedEnvironmentId ||
215 draftThread.promotedTo ||
216 composerHasAttachments
217 )
218 return null;
219 const originalDraft = getDraftSession(draftId);
220 const scope = mountedRoutingScope.current;
221 if (!originalDraft || !scope) return null;
222 const composerDraft = useComposerDraftStore.getState().getComposerDraft(draftId);
223 const readCurrentRouting = () => {
224 const current = readRouting();
225 const latestDraft = getDraftSession(draftId);
226 const draftMatches =
227 latestDraft === originalDraft ||
228 // The picker may fill an empty base while any of the routing reads are pending.
229 // Its automatic write keeps the routing mode; a manual pick switches it to manual.
230 (originalDraft.envMode === "worktree" &&
231 originalDraft.branch === null &&
232 latestDraft?.branch != null &&
233 shallow(latestDraft, {
234 ...originalDraft,
235 branch: latestDraft.branch,
236 environmentSelection: originalDraft.environmentSelection ?? "auto",
237 }));
238 return mountedRoutingScope.current === scope &&
239 current.input.draftId === draftId &&
240 current.input.automaticEnvironment &&
241 !current.input.composerHasAttachments &&
242 current.input.activeProjectKey === activeProjectKey &&
243 current.input.selectedProvider === selectedProvider &&
244 current.input.activeProviderInstanceId === activeProviderInstanceId &&
245 current.input.loadBalancingSettings.loadBalancingWeights ===
246 loadBalancingSettings.loadBalancingWeights &&
247 current.loadBalancingCandidates.join("\n") === loadBalancingCandidates.join("\n") &&
248 draftMatches &&
249 useComposerDraftStore.getState().getComposerDraft(draftId) === composerDraft
250 ? current
251 : null;
252 };
253 return loadBalancing.refreshSelection(loadBalancingCandidates).then(async (environmentId) => {
254 const current = readCurrentRouting();
255 if (!current) return false;
256 const target = current.input.logicalProjectEnvironments.find(
257 (candidate) => candidate.environmentId === environmentId,
258 );
259 if (!target?.projectId) {
260 toastManager.add({
261 type: "warning",
262 ...loadBalancingSendWarning({
263 pending: false,
264 threadContexts: referencedThreadContexts,
265 candidateEnvironmentIds: loadBalancingCandidates,
266 }),
267 });
268 return false;
269 }
270 const projectRef = scopeProjectRef(target.environmentId, target.projectId);
271 const moved = changesProject(originalDraft, projectRef);
272 const workspace = moved ? await readDestinationWorkspace(originalDraft, projectRef) : {};
273 const isWorktree = (workspace.envMode ?? originalDraft.envMode) === "worktree";
274 const branch =
275 isWorktree && (moved || originalDraft.branch === null)
276 ? await readWorktreeBase(projectRef, originalDraft.branch)
277 : moved
278 ? null
279 : originalDraft.branch;
280 if (
281 !readCurrentRouting()?.input.logicalProjectEnvironments.some(
282 (candidate) =>
283 candidate.environmentId === environmentId && candidate.projectId === target.projectId,
284 )
285 )
286 return false;
287
288 carryFanoutSelections(originalDraft, target.environmentId);
289 // The send must read the target project's composer and provider context after retargeting.
290 flushSync(() =>
291 setDraftThreadContext(draftId, {
292 projectRef,
293 environmentSelection: "auto",
294 loadBalancedEnvironmentId: target.environmentId,
295 ...workspace,
296 branch,
297 }),
298 );
299 return true;
300 });
301 };
302 const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
303 // The busy state belongs to the request that set it, so an older request settling late
304 // (abandoned, or superseded by a newer switch) can never clear a newer one's.
305 const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
306 readonly environmentId: EnvironmentId;
307 readonly scope: string;
308 } | null>(null);
309 const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;
310
311 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the resolved load-balanced environment into the draft store once the async pick settles
312 useEffect(() => {
313 if (
314 !needsLoadBalancing ||
315 loadBalancing.pending ||
316 !draftId ||
317 isEnvironmentChanging ||
318 sendInFlightRef.current
319 )
320 return;
321 const target = logicalProjectEnvironments.find(
322 (environment) => environment.environmentId === loadBalancing.environmentId,
323 );
324 if (!target?.projectId) return;
325 const draft = getDraftSession(draftId);
326 if (!draft) return;
327 const projectRef = scopeProjectRef(target.environmentId, target.projectId);
328 carryFanoutSelections(draft, target.environmentId);
329 setDraftThreadContext(draftId, {
330 projectRef,
331 environmentSelection: "auto",
332 loadBalancedEnvironmentId: target.environmentId,
333 });
334 if (changesProject(draft, projectRef)) {
335 const current = { envMode: draft.envMode, startFromOrigin: draft.startFromOrigin };
336 trackPendingWorkspaceDefault(
337 draftId,
338 projectRef,
339 current,
340 readDestinationWorkspace(draft, projectRef).then((workspace) => ({
341 ...current,
342 ...workspace,
343 })),
344 );
345 }
346 }, [
347 needsLoadBalancing,
348 loadBalancing.pending,
349 loadBalancing.environmentId,
350 isEnvironmentChanging,
351 draftId,
352 logicalProjectEnvironments,
353 sendInFlightRef,
354 getDraftSession,
355 setDraftThreadContext,
356 ]);
357 // A change in flight belongs to the draft and project it started on.
358 const environmentChangeRef = useRef<{
359 readonly controller: AbortController;
360 readonly environmentId: EnvironmentId;
361 readonly scope: string;
362 } | null>(null);
363 const environmentChangeScopeRef = useRef("");
364 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the current change scope into a ref that async environment switches compare against
365 useLayoutEffect(() => {
366 environmentChangeScopeRef.current = environmentChangeScope;
367 });
368 // Leaving the scope, or unmounting, abandons a change still in flight.
369 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons an in-flight environment change when the draft or project scope changes or unmounts
370 useLayoutEffect(
371 () => () => {
372 if (environmentChangeRef.current?.scope === environmentChangeScope) {
373 environmentChangeRef.current.controller.abort();
374 environmentChangeRef.current = null;
375 }
376 },
377 [environmentChangeScope],
378 );
379 const readPendingEnvironmentChange = () => {
380 const pending = environmentChangeRef.current;
381 return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
382 };
383 const onAutoEnvironment = () => {
384 if (envLocked || !draftId || sendInFlightRef.current) return;
385 if (composerHasAttachments) {
386 toastManager.add({
387 type: "warning",
388 id: "load-balancing-attachments",
389 title: m(msg("Keep attachments on this machine")),
390 description: m(
391 msg(
392 "Remove attachments before choosing automatic routing, then attach them on the selected machine.",
393 ),
394 ),
395 });
396 return;
397 }
398 environmentChangeRef.current?.controller.abort();
399 environmentChangeRef.current = null;
400 setBusyEnvironmentChange(null);
401 loadBalancing.refresh(
402 logicalProjectEnvironments.map((environment) => environment.environmentId),
403 );
404 setDraftThreadContext(draftId, {
405 environmentSelection: "auto",
406 loadBalancedEnvironmentId: null,
407 branch: null,
408 worktreePath: null,
409 });
410 };
411 const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
412 const autoEnvironmentLabel = automaticEnvironment
413 ? draftThread?.loadBalancedEnvironmentId
414 ? gt`Auto balance`
415 : loadBalancing.pending
416 ? gt`Checking machines…`
417 : loadBalancing.failed
418 ? gt`Auto balance unavailable`
419 : gt`Auto balance`
420 : undefined;
421
422 const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
423 if (envLocked || !draftId || sendInFlightRef.current) return;
424 const originalDraft = getDraftSession(draftId);
425 if (!originalDraft || originalDraft.promotedTo) return;
426 const target = logicalProjectEnvironments.find(
427 (env) => env.environmentId === nextEnvironmentId,
428 );
429 if (!target) return;
430 environmentChangeRef.current?.controller.abort();
431 const request = {
432 controller: new AbortController(),
433 environmentId: target.environmentId,
434 scope: environmentChangeScope,
435 };
436 environmentChangeRef.current = request;
437 setBusyEnvironmentChange(null);
438 const readSwitchingDraft = () => {
439 const currentDraft = getDraftSession(draftId);
440 if (
441 environmentChangeRef.current !== request ||
442 environmentChangeScopeRef.current !== request.scope ||
443 sendInFlightRef.current ||
444 !currentDraft ||
445 currentDraft.promotedTo ||
446 currentDraft.environmentId !== originalDraft.environmentId ||
447 currentDraft.projectId !== originalDraft.projectId
448 )
449 return null;
450 return currentDraft;
451 };
452 // `triagePrompt` is the prompt the target machine prepared for a triage draft.
453 const retarget = async (
454 project: (typeof allProjects)[number],
455 triagePrompt?: string,
456 ): Promise<void> => {
457 const draft = readSwitchingDraft();
458 if (!draft) return;
459 const projectRef = scopeProjectRef(target.environmentId, project.id);
460 // Use the catalog-backed list: an unpaired machine can still have a cached project snapshot.
461 const findDestination = (projects: typeof allProjects) =>
462 projects.find(
463 (candidate) =>
464 candidate.environmentId === projectRef.environmentId &&
465 candidate.id === projectRef.projectId,
466 );
467 const workspaceRoot = findDestination(readProjects())?.workspaceRoot;
468 const controller = new AbortController();
469 const unsubscribe = subscribeProjects((projects) => {
470 if (findDestination(projects)?.workspaceRoot !== workspaceRoot) controller.abort();
471 });
472 const workspaceRead =
473 workspaceRoot === undefined
474 ? Promise.resolve({})
475 : retargetDraftWorkspace(
476 draft,
477 projectRef,
478 AbortSignal.any([request.controller.signal, controller.signal]),
479 );
480 const defaultWorkspace = await workspaceRead.finally(unsubscribe);
481 const currentDraft = readSwitchingDraft();
482 if (!currentDraft) return;
483 const destination = findDestination(readProjects());
484 if (!destination) {
485 toastManager.add(
486 stackedThreadToast({
487 type: "error",
488 title: m(msg("Could not switch machine")),
489 description: m(msg("This project is no longer available.")),
490 }),
491 );
492 return;
493 }
494 if (controller.signal.aborted || destination.workspaceRoot !== workspaceRoot) {
495 return retarget(destination, triagePrompt);
496 }
497 const workspace =
498 currentDraft.workspaceExplicit || currentDraft.worktreePath !== null
499 ? {}
500 : defaultWorkspace;
501 if (triagePrompt !== undefined) {
502 // Read now, so text typed while the machine prepared the session is kept.
503 const prompt = getComposerDraft(draftId)?.prompt ?? "";
504 const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt);
505 if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt);
506 }
507 const moved = changesProject(currentDraft, projectRef);
508 carryFanoutSelections(currentDraft, target.environmentId);
509 if (activeProjectIsScratch) {
510 setLogicalProjectDraftThreadId(
511 deriveLogicalProjectKeyFromSettings(destination, projectGroupingSettings),
512 projectRef,
513 draftId,
514 { environmentSelection: "manual", loadBalancedEnvironmentId: null, ...workspace },
515 );
516 } else {
517 setDraftThreadContext(draftId, {
518 projectRef,
519 environmentSelection: "manual",
520 loadBalancedEnvironmentId: null,
521 ...workspace,
522 });
523 }
524 if (moved) seedDraftModelSelection(draftId, projectRef);
525 };
526 const finish = () => {
527 if (environmentChangeRef.current === request) environmentChangeRef.current = null;
528 setBusyEnvironmentChange((busy) => (busy === request ? null : busy));
529 };
530 const knownProject = allProjects.find(
531 (project) =>
532 project.environmentId === target.environmentId && project.id === target.projectId,
533 );
534 // The playbook and context files exist only on the machine that prepared them.
535 const followsTriage = isTriagePrompt(getComposerDraft(draftId)?.prompt ?? "");
536 if (target.projectId !== null && !knownProject) {
537 finish();
538 return;
539 }
540 const prepareTriagePrompt = async () => {
541 const prepared = await prepareTriage({
542 environmentId: target.environmentId,
543 input: { client: currentClientMetadata() },
544 });
545 if (prepared._tag === "Success") return prepared.value.prompt;
546 if (!isAtomCommandInterrupted(prepared)) {
547 const error = squashAtomCommandFailure(prepared);
548 toastManager.add(
549 stackedThreadToast({
550 type: "error",
551 title: m(msg("Could not switch machine")),
552 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
553 }),
554 );
555 }
556 return null;
557 };
558 const switchMachine = async () => {
559 const triagePrompt = followsTriage ? await prepareTriagePrompt() : undefined;
560 if (triagePrompt === null) return;
561 const project =
562 knownProject ??
563 (await openScratchProject(target.environmentId, m(msg("Could not switch machine"))));
564 if (project) await retarget(project, triagePrompt);
565 };
566 setBusyEnvironmentChange(request);
567 void switchMachine().finally(finish);
568 };
569 const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
570
571 return {
572 needsLoadBalancing,
573 loadBalancing,
574 refreshBeforeSend,
575 onAutoEnvironmentStable,
576 autoEnvironmentLabel,
577 isEnvironmentChanging,
578 readPendingEnvironmentChange,
579 onEnvironmentChangeStable,
580 };
581}