@devries-cameron20 / t3code Mirror · read-only / commits / 0bb6eaa546
Fork 0

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, 18:30 UTC

fix(web): auto-balanced drafts recheck machine load before sending (#35658)

Co-authored-by: Lakshmi Tanmay <lakshmi@voltcrash.com>

Julius Marminge committed Nov 12, 2026 at 16:56 UTC 0bb6eaa546c91915efbd3f092088c694f3949709
5 files changed +347 -5
apps/web/src/components/ChatView.tsx
+2
@@ -1798,6 +1798,7 @@ export default function ChatView(props: ChatViewProps) {
1798 const {
1799 needsLoadBalancing,
1800 loadBalancing,
1801 + refreshBeforeSend,
1802 onAutoEnvironmentStable,
1803 autoEnvironmentLabel,
1804 isEnvironmentChanging,
@@ -2939,6 +2940,7 @@ export default function ChatView(props: ChatViewProps) {
2940 clearUsageLimitsFor,
2941 needsLoadBalancing,
2942 loadBalancing,
2943 + refreshBeforeSend,
2944 readPendingEnvironmentChange,
2945 pendingApprovals,
2946 respondingRequestIds,
apps/web/src/components/chat/useComposerSend.ts
+18 -1
@@ -96,6 +96,7 @@ import { environmentServerConfigsAtom } from "../../state/server";
96 import { threadEnvironment } from "../../state/threads";
97 import { runMobileComposerTransition } from "./draftHeroTransition";
98 import { useClientSettingsHydrated } from "../../hooks/useSettings";
99 +import { useStableCallback } from "../../hooks/useStableCallback";
100 import { environmentPresentations } from "../../state/presentation";
101 import {
102 approvalRedirectNotice,
@@ -216,6 +217,7 @@ interface ComposerSendInput {
217 readonly clearUsageLimitsFor: UsageLimitsPanel["clearFor"];
218 readonly needsLoadBalancing: boolean;
219 readonly loadBalancing: DraftEnvironmentRouting["loadBalancing"];
220 + readonly refreshBeforeSend: DraftEnvironmentRouting["refreshBeforeSend"];
221 readonly readPendingEnvironmentChange: DraftEnvironmentRouting["readPendingEnvironmentChange"];
222 readonly pendingApprovals: PendingThreadRequests["pendingApprovals"];
223 readonly respondingRequestIds: PendingThreadRequests["respondingRequestIds"];
@@ -311,6 +313,7 @@ export function useComposerSend(input: ComposerSendInput) {
313 clearUsageLimitsFor,
314 needsLoadBalancing,
315 loadBalancing,
316 + refreshBeforeSend,
317 readPendingEnvironmentChange,
318 pendingApprovals,
319 respondingRequestIds,
@@ -1488,5 +1491,19 @@ export function useComposerSend(input: ComposerSendInput) {
1491 }
1492 };
1493
1491 - return { onSend };
1494 + const onSendLatest = useStableCallback(onSend);
1495 + const onSendWithRouting = async (...args: Parameters<typeof onSend>) => {
1496 + args[0]?.preventDefault();
1497 + const refresh =
1498 + args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null
1499 + ? null
1500 + : refreshBeforeSend();
1501 + if (refresh === null) return onSend(...args);
1502 + sendInFlightRef.current = true;
1503 + const ready = await refresh.finally(() => {
1504 + sendInFlightRef.current = false;
1505 + });
1506 + if (ready) return onSendLatest(...args);
1507 + };
1508 + return { onSend: onSendWithRouting };
1509 }
apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx new
+227
@@ -0,0 +1,227 @@
1 +import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2 +import * as Option from "effect/Option";
3 +import type { EnvironmentPresentation } from "../../state/environments";
4 +import type { ServerProvider } from "@t3tools/contracts";
5 +import {
6 + scopedThreadKey,
7 + scopeProjectRef,
8 + scopeThreadRef,
9 +} from "@t3tools/client-runtime/environment";
10 +import { createModelSelection } from "@t3tools/shared/model";
11 +import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
12 +import {
13 + EnvironmentId,
14 + ProjectId,
15 + ProviderDriverKind,
16 + ProviderInstanceId,
17 +} from "@t3tools/contracts";
18 +import { expect, it, vi } from "vite-plus/test";
19 +
20 +import { act, render } from "../../../test/render";
21 +import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
22 +import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
23 +import { appAtomRegistry } from "../../rpc/atomRegistry";
24 +import { draftFanoutSelectionsAtom } from "./chatViewSend";
25 +
26 +const resources = vi.hoisted(() => ({
27 + refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(),
28 +}));
29 +vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({
30 + useLoadBalancedEnvironment: () => ({
31 + pending: false,
32 + failed: false,
33 + environmentId: null,
34 + refresh: () => {},
35 + refreshSelection: resources.refreshSelection,
36 + }),
37 +}));
38 +vi.mock("../../state/entities", () => ({ useProjects: () => [] }));
39 +vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) }));
40 +
41 +function setup() {
42 + resources.refreshSelection.mockReset();
43 + const a = EnvironmentId.make("machine-a");
44 + const b = EnvironmentId.make("machine-b");
45 + const draftId = DraftId.make("fresh-routing-draft");
46 + const projectId = ProjectId.make("project");
47 + const store = useComposerDraftStore.getState();
48 + store.clearDraftThread(draftId);
49 + store.setProjectDraftThreadId(scopeProjectRef(a, projectId), draftId, {
50 + environmentSelection: "auto",
51 + loadBalancedEnvironmentId: a,
52 + });
53 + store.setPrompt(draftId, "Keep this prompt");
54 + const provider: ServerProvider = {
55 + instanceId: ProviderInstanceId.make("codex"),
56 + driver: ProviderDriverKind.make("codex"),
57 + enabled: true,
58 + installed: true,
59 + status: "ready",
60 + auth: { status: "authenticated" },
61 + availability: "available",
62 + version: null,
63 + checkedAt: "2026-11-10T01:00:00.000Z",
64 + models: [],
65 + slashCommands: [],
66 + skills: [],
67 + };
68 + const input: Parameters<typeof useDraftEnvironmentRouting>[0] = {
69 + draftId,
70 + draftThread: store.getDraftSession(draftId),
71 + envLocked: false,
72 + automaticEnvironment: true,
73 + logicalProjectEnvironments: [a, b].map((environmentId) => ({
74 + environmentId,
75 + projectId,
76 + label: environmentId,
77 + isPrimary: environmentId === a,
78 + machine: "desktop",
79 + })),
80 + environmentById: new Map(
81 + [a, b].map((id): [EnvironmentId, EnvironmentPresentation] => [
82 + id,
83 + {
84 + environmentId: id,
85 + label: id,
86 + displayUrl: null,
87 + relayManaged: false,
88 + entry: {
89 + target: new PrimaryConnectionTarget({
90 + environmentId: id,
91 + label: id,
92 + httpBaseUrl: "http://localhost:3000",
93 + wsBaseUrl: "ws://localhost:3000",
94 + }),
95 + profile: Option.none(),
96 + enabled: true,
97 + },
98 + connection: { phase: "connected", error: null, traceId: null },
99 + serverConfig: null,
100 + },
101 + ]),
102 + ),
103 + providersByEnvironment: new Map([a, b].map((id) => [id, [provider]])),
104 + loadBalancingSettings: { loadBalancingWeights: {} },
105 + referencedThreadContexts: [],
106 + activeProviderInstanceId: provider.instanceId,
107 + selectedProvider: provider.driver,
108 + composerHasAttachments: false,
109 + activeProjectKey: "project",
110 + activeProjectIsScratch: false,
111 + projectGroupingSettings: DEFAULT_UNIFIED_SETTINGS,
112 + sendInFlightRef: { current: false },
113 + };
114 + resources.refreshSelection.mockImplementation(async (ids) => (ids.includes(b) ? b : null));
115 + return { a, b, draftId, input, store };
116 +}
117 +
118 +function Harness({
119 + input,
120 + onPrepared,
121 +}: {
122 + input: Parameters<typeof useDraftEnvironmentRouting>[0];
123 + onPrepared?: (ready: boolean | null) => void;
124 +}) {
125 + const routing = useDraftEnvironmentRouting(input);
126 + const draft = useComposerDraftStore((state) => state.getDraftSession(input.draftId!));
127 + return (
128 + <>
129 + <span>{draft?.environmentId}</span>
130 + <button
131 + onClick={async () => {
132 + const ready = await routing.refreshBeforeSend();
133 + onPrepared?.(ready);
134 + }}
135 + >
136 + Send
137 + </button>
138 + </>
139 + );
140 +}
141 +
142 +it("refreshes a stored automatic choice before sending an unsent draft", async () => {
143 + const { a, b, draftId, input, store } = setup();
144 + const selections = ["model-a", "model-b"].map((model) =>
145 + createModelSelection(ProviderInstanceId.make("codex"), model),
146 + );
147 + const threadId = input.draftThread!.threadId;
148 + const destinationSelections = draftFanoutSelectionsAtom(
149 + scopedThreadKey(scopeThreadRef(b, threadId)),
150 + );
151 + appAtomRegistry.set(destinationSelections, null);
152 + appAtomRegistry.set(
153 + draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(a, threadId))),
154 + selections,
155 + );
156 + store.setDraftThreadContext(draftId, {
157 + branch: "main",
158 + envMode: "worktree",
159 + environmentSelection: "auto",
160 + });
161 + await using screen = await render(
162 + <Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />,
163 + );
164 + await expect.element(screen.getByText(a)).toBeInTheDocument();
165 + await screen.getByRole("button", { name: "Send" }).click();
166 + await expect.element(screen.getByText(b)).toBeInTheDocument();
167 + expect(resources.refreshSelection).toHaveBeenCalledWith([a, b]);
168 + expect(store.getDraftSession(draftId)).toMatchObject({
169 + loadBalancedEnvironmentId: b,
170 + branch: "main",
171 + envMode: "worktree",
172 + });
173 + expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt");
174 + expect(appAtomRegistry.get(destinationSelections)).toEqual(selections);
175 +});
176 +
177 +it.each(["manual", "attachments", "promoted"] as const)(
178 + "keeps the machine for %s drafts",
179 + async (kind) => {
180 + const { a, draftId, input, store } = setup();
181 + if (kind === "manual") store.setDraftThreadContext(draftId, { environmentSelection: "manual" });
182 + const guardedInput = {
183 + ...input,
184 + automaticEnvironment: kind !== "manual",
185 + composerHasAttachments: kind === "attachments",
186 + draftThread:
187 + kind === "promoted"
188 + ? {
189 + ...input.draftThread!,
190 + promotedTo: { environmentId: a, threadId: input.draftThread!.threadId },
191 + }
192 + : input.draftThread,
193 + };
194 + await using screen = await render(<Harness input={guardedInput} />);
195 + await screen.getByRole("button", { name: "Send" }).click();
196 + expect(resources.refreshSelection).not.toHaveBeenCalled();
197 + expect(store.getDraftSession(draftId)?.environmentId).toBe(a);
198 + },
199 +);
200 +
201 +it("does not reuse a stored choice when refreshed resources have no winner", async () => {
202 + const { a, input } = setup();
203 + resources.refreshSelection.mockResolvedValue(null);
204 + const onPrepared = vi.fn();
205 + await using screen = await render(<Harness input={input} onPrepared={onPrepared} />);
206 + await screen.getByRole("button", { name: "Send" }).click();
207 + await expect.element(screen.getByText(a)).toBeInTheDocument();
208 + await vi.waitFor(() => expect(onPrepared).toHaveBeenCalledWith(false));
209 +});
210 +
211 +it("abandons a refresh when the draft changes while resources are in flight", async () => {
212 + const { a, b, draftId, input, store } = setup();
213 + let resolve!: (environmentId: EnvironmentId) => void;
214 + resources.refreshSelection.mockReturnValue(
215 + new Promise<EnvironmentId>((done) => {
216 + resolve = done;
217 + }),
218 + );
219 + await using screen = await render(<Harness input={input} />);
220 + await screen.getByRole("button", { name: "Send" }).click();
221 + await act(async () => {
222 + store.setPrompt(draftId, "Edited while checking");
223 + resolve(b);
224 + });
225 + await expect.element(screen.getByText(a)).toBeInTheDocument();
226 + expect(store.getComposerDraft(draftId)?.prompt).toBe("Edited while checking");
227 +});
apps/web/src/components/chat/useDraftEnvironmentRouting.ts
+80 -4
@@ -9,8 +9,13 @@ import {
9 resolveProjectProviderInstanceEnabled,
10 type ThreadContextRecord,
11 } from "@t3tools/contracts";
12 -import { scopeProjectRef } from "@t3tools/client-runtime/environment";
12 +import {
13 + scopedThreadKey,
14 + scopeProjectRef,
15 + scopeThreadRef,
16 +} from "@t3tools/client-runtime/environment";
17 import { useEffect, useLayoutEffect, useRef, useState } from "react";
18 +import { flushSync } from "react-dom";
19 import { toastManager } from "../ui/toast";
20 import {
21 deriveLogicalProjectKeyFromSettings,
@@ -20,6 +25,9 @@ import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
25 import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
26 import { useProjects } from "../../state/entities";
27 import type { DraftSessionState } from "../../composerDraftStore";
28 +import { loadBalancingSendWarning } from "./composerSend.logic";
29 +import { appAtomRegistry } from "../../rpc/atomRegistry";
30 +import { draftFanoutSelectionsAtom } from "./chatViewSend";
31
32 interface DraftEnvironmentRoutingInput {
33 readonly draftId: DraftId | null;
@@ -74,7 +82,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
82 const allProjects = useProjects();
83 const { openScratchProject } = useScratchProject();
84 const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
77 - const loadBalancingCandidates = needsLoadBalancing
85 + const loadBalancingCandidates = automaticEnvironment
86 ? logicalProjectEnvironments
87 .filter((candidate) => {
88 const environment = environmentById.get(candidate.environmentId);
@@ -108,9 +116,76 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
116 .map((candidate) => candidate.environmentId)
117 : [];
118 const loadBalancing = useLoadBalancedEnvironment(
111 - loadBalancingCandidates,
119 + needsLoadBalancing ? loadBalancingCandidates : [],
120 loadBalancingSettings.loadBalancingWeights,
121 );
122 + const readRouting = useStableCallback(() => ({ input, loadBalancingCandidates }));
123 + const refreshBeforeSend = () => {
124 + if (
125 + !automaticEnvironment ||
126 + !draftId ||
127 + !draftThread?.loadBalancedEnvironmentId ||
128 + draftThread.promotedTo ||
129 + composerHasAttachments
130 + )
131 + return null;
132 + const originalDraft = getDraftSession(draftId);
133 + const composerDraft = useComposerDraftStore.getState().getComposerDraft(draftId);
134 + return loadBalancing.refreshSelection(loadBalancingCandidates).then((environmentId) => {
135 + const current = readRouting();
136 + if (
137 + current.input.draftId !== draftId ||
138 + !current.input.automaticEnvironment ||
139 + current.input.composerHasAttachments ||
140 + current.input.activeProjectKey !== activeProjectKey ||
141 + current.input.selectedProvider !== selectedProvider ||
142 + current.input.activeProviderInstanceId !== activeProviderInstanceId ||
143 + current.input.loadBalancingSettings.loadBalancingWeights !==
144 + loadBalancingSettings.loadBalancingWeights ||
145 + current.loadBalancingCandidates.join("\n") !== loadBalancingCandidates.join("\n") ||
146 + getDraftSession(draftId) !== originalDraft ||
147 + useComposerDraftStore.getState().getComposerDraft(draftId) !== composerDraft
148 + )
149 + return false;
150 + const target = current.input.logicalProjectEnvironments.find(
151 + (candidate) => candidate.environmentId === environmentId,
152 + );
153 + if (!target?.projectId) {
154 + toastManager.add({
155 + type: "warning",
156 + ...loadBalancingSendWarning({
157 + pending: false,
158 + threadContexts: referencedThreadContexts,
159 + candidateEnvironmentIds: loadBalancingCandidates,
160 + }),
161 + });
162 + return false;
163 + }
164 + const projectRef = scopeProjectRef(target.environmentId, target.projectId);
165 + if (originalDraft && target.environmentId !== originalDraft.environmentId) {
166 + appAtomRegistry.set(
167 + draftFanoutSelectionsAtom(
168 + scopedThreadKey(scopeThreadRef(target.environmentId, originalDraft.threadId)),
169 + ),
170 + appAtomRegistry.get(
171 + draftFanoutSelectionsAtom(
172 + scopedThreadKey(scopeThreadRef(originalDraft.environmentId, originalDraft.threadId)),
173 + ),
174 + ),
175 + );
176 + }
177 + // The send must read the target project's composer and provider context after retargeting.
178 + flushSync(() =>
179 + setDraftThreadContext(draftId, {
180 + projectRef,
181 + environmentSelection: "auto",
182 + loadBalancedEnvironmentId: target.environmentId,
183 + branch: originalDraft?.branch ?? null,
184 + }),
185 + );
186 + return true;
187 + });
188 + };
189 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the resolved load-balanced environment into the draft store once the async pick settles
190 useEffect(() => {
191 if (!needsLoadBalancing || loadBalancing.pending || !draftId || sendInFlightRef.current) return;
@@ -133,7 +208,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
208 setDraftThreadContext,
209 ]);
210 const onAutoEnvironment = () => {
136 - if (envLocked || !draftId) return;
211 + if (envLocked || !draftId || sendInFlightRef.current) return;
212 if (composerHasAttachments) {
213 toastManager.add({
214 type: "warning",
@@ -262,6 +337,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
337 return {
338 needsLoadBalancing,
339 loadBalancing,
340 + refreshBeforeSend,
341 onAutoEnvironmentStable,
342 autoEnvironmentLabel,
343 isEnvironmentChanging,
apps/web/src/hooks/useLoadBalancedEnvironment.ts
+20
@@ -1,5 +1,6 @@
1 import { RegistryContext, useAtomValue } from "@effect/atom-react";
2 import { chooseLoadBalancedEnvironment } from "@t3tools/client-runtime/load-balancing";
3 +import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
4 import type { EnvironmentId } from "@t3tools/contracts";
5 import { Atom } from "effect/reactivity";
6 import { useContext } from "react";
@@ -50,6 +51,24 @@ export function useLoadBalancedEnvironment(
51 registry.refresh(serverEnvironment.hostResources({ environmentId, input: {} }));
52 }
53 };
54 + const refreshSelection = async (ids: readonly EnvironmentId[]) => {
55 + const candidates = await Promise.all(
56 + ids.map(async (environmentId) => {
57 + const result = await executeAtomQuery(
58 + registry,
59 + serverEnvironment.hostResources({ environmentId, input: {} }),
60 + { refresh: true, reportFailure: false, signal: AbortSignal.timeout(5_000) },
61 + );
62 + return {
63 + environmentId,
64 + resources: result._tag === "Success" ? result.value : null,
65 + receivedAt: Date.now(),
66 + weight: weights[environmentId] ?? 50,
67 + };
68 + }),
69 + );
70 + return chooseLoadBalancedEnvironment(candidates, Date.now()) as EnvironmentId | null;
71 + };
72 const { evaluatedAt, resources } = useAtomValue(hostResourcesAtom(environmentIds.join("\n")));
73 const pending = resources.some((resource) => resource.pending);
74 const environmentId = chooseLoadBalancedEnvironment(
@@ -61,6 +80,7 @@ export function useLoadBalancedEnvironment(
80 ) as EnvironmentId | null;
81 return {
82 refresh,
83 + refreshSelection,
84 pending,
85 environmentId,
86 failed: !pending && environmentId === null && resources.some((resource) => resource.failed),