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