Skip to content

Commit 72b90c5

Browse files
committed
fix(web): refresh automatic draft routing before send
1 parent 80e6261 commit 72b90c5

5 files changed

Lines changed: 308 additions & 4 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1771,6 +1771,7 @@ export default function ChatView(props: ChatViewProps) {
17711771
const {
17721772
needsLoadBalancing,
17731773
loadBalancing,
1774+
refreshBeforeSend,
17741775
onAutoEnvironmentStable,
17751776
autoEnvironmentLabel,
17761777
isEnvironmentChanging,
@@ -2919,6 +2920,7 @@ export default function ChatView(props: ChatViewProps) {
29192920
clearUsageLimitsFor,
29202921
needsLoadBalancing,
29212922
loadBalancing,
2923+
refreshBeforeSend,
29222924
readPendingEnvironmentChange,
29232925
pendingApprovals,
29242926
respondingRequestIds,

‎apps/web/src/components/chat/useComposerSend.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ import { environmentServerConfigsAtom } from "../../state/server";
8888
import { threadEnvironment } from "../../state/threads";
8989
import { runMobileComposerTransition } from "./draftHeroTransition";
9090
import { useClientSettingsHydrated } from "../../hooks/useSettings";
91+
import { useStableCallback } from "../../hooks/useStableCallback";
9192
import { environmentPresentations } from "../../state/presentation";
9293
import {
9394
approvalRedirectNotice,
@@ -208,6 +209,7 @@ interface ComposerSendInput {
208209
readonly clearUsageLimitsFor: UsageLimitsPanel["clearFor"];
209210
readonly needsLoadBalancing: boolean;
210211
readonly loadBalancing: DraftEnvironmentRouting["loadBalancing"];
212+
readonly refreshBeforeSend: DraftEnvironmentRouting["refreshBeforeSend"];
211213
readonly readPendingEnvironmentChange: DraftEnvironmentRouting["readPendingEnvironmentChange"];
212214
readonly pendingApprovals: PendingThreadRequests["pendingApprovals"];
213215
readonly respondingRequestIds: PendingThreadRequests["respondingRequestIds"];
@@ -301,6 +303,7 @@ export function useComposerSend(input: ComposerSendInput) {
301303
clearUsageLimitsFor,
302304
needsLoadBalancing,
303305
loadBalancing,
306+
refreshBeforeSend,
304307
readPendingEnvironmentChange,
305308
pendingApprovals,
306309
respondingRequestIds,
@@ -1400,5 +1403,19 @@ export function useComposerSend(input: ComposerSendInput) {
14001403
}
14011404
};
14021405

1403-
return { onSend };
1406+
const onSendLatest = useStableCallback(onSend);
1407+
const onSendWithRouting = async (...args: Parameters<typeof onSend>) => {
1408+
args[0]?.preventDefault();
1409+
const refresh =
1410+
args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null
1411+
? null
1412+
: refreshBeforeSend();
1413+
if (refresh === null) return onSend(...args);
1414+
sendInFlightRef.current = true;
1415+
const ready = await refresh.finally(() => {
1416+
sendInFlightRef.current = false;
1417+
});
1418+
if (ready) return onSendLatest(...args);
1419+
};
1420+
return { onSend: onSendWithRouting };
14041421
}
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
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 { scopeProjectRef } from "@t3tools/client-runtime/environment";
6+
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
7+
import {
8+
EnvironmentId,
9+
ProjectId,
10+
ProviderDriverKind,
11+
ProviderInstanceId,
12+
} from "@t3tools/contracts";
13+
import { expect, it, vi } from "vite-plus/test";
14+
15+
import { act, render } from "../../../test/render";
16+
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
17+
import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
18+
19+
const resources = vi.hoisted(() => ({
20+
refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(),
21+
}));
22+
vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({
23+
useLoadBalancedEnvironment: () => ({
24+
pending: false,
25+
failed: false,
26+
environmentId: null,
27+
refresh: () => {},
28+
refreshSelection: resources.refreshSelection,
29+
}),
30+
}));
31+
vi.mock("../../state/entities", () => ({ useProjects: () => [] }));
32+
vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) }));
33+
34+
function setup() {
35+
resources.refreshSelection.mockReset();
36+
const a = EnvironmentId.make("machine-a");
37+
const b = EnvironmentId.make("machine-b");
38+
const draftId = DraftId.make("fresh-routing-draft");
39+
const projectId = ProjectId.make("project");
40+
const store = useComposerDraftStore.getState();
41+
store.clearDraftThread(draftId);
42+
store.setProjectDraftThreadId(scopeProjectRef(a, projectId), draftId, {
43+
environmentSelection: "auto",
44+
loadBalancedEnvironmentId: a,
45+
});
46+
store.setPrompt(draftId, "Keep this prompt");
47+
const provider: ServerProvider = {
48+
instanceId: ProviderInstanceId.make("codex"),
49+
driver: ProviderDriverKind.make("codex"),
50+
enabled: true,
51+
installed: true,
52+
status: "ready",
53+
auth: { status: "authenticated" },
54+
availability: "available",
55+
version: null,
56+
checkedAt: "2026-11-10T01:00:00.000Z",
57+
models: [],
58+
slashCommands: [],
59+
skills: [],
60+
};
61+
const input: Parameters<typeof useDraftEnvironmentRouting>[0] = {
62+
draftId,
63+
draftThread: store.getDraftSession(draftId),
64+
envLocked: false,
65+
automaticEnvironment: true,
66+
logicalProjectEnvironments: [a, b].map((environmentId) => ({
67+
environmentId,
68+
projectId,
69+
label: environmentId,
70+
isPrimary: environmentId === a,
71+
machine: "desktop",
72+
})),
73+
environmentById: new Map(
74+
[a, b].map((id): [EnvironmentId, EnvironmentPresentation] => [
75+
id,
76+
{
77+
environmentId: id,
78+
label: id,
79+
displayUrl: null,
80+
relayManaged: false,
81+
entry: {
82+
target: new PrimaryConnectionTarget({
83+
environmentId: id,
84+
label: id,
85+
httpBaseUrl: "http://localhost:3000",
86+
wsBaseUrl: "ws://localhost:3000",
87+
}),
88+
profile: Option.none(),
89+
enabled: true,
90+
},
91+
connection: { phase: "connected", error: null, traceId: null },
92+
serverConfig: null,
93+
},
94+
]),
95+
),
96+
providersByEnvironment: new Map([a, b].map((id) => [id, [provider]])),
97+
loadBalancingSettings: { loadBalancingWeights: {} },
98+
referencedThreadContexts: [],
99+
activeProviderInstanceId: provider.instanceId,
100+
selectedProvider: provider.driver,
101+
composerHasAttachments: false,
102+
activeProjectKey: "project",
103+
activeProjectIsScratch: false,
104+
projectGroupingSettings: DEFAULT_UNIFIED_SETTINGS,
105+
sendInFlightRef: { current: false },
106+
};
107+
resources.refreshSelection.mockImplementation(async (ids) => (ids.includes(b) ? b : null));
108+
return { a, b, draftId, input, store };
109+
}
110+
111+
function Harness({
112+
input,
113+
onPrepared,
114+
}: {
115+
input: Parameters<typeof useDraftEnvironmentRouting>[0];
116+
onPrepared?: (ready: boolean | null) => void;
117+
}) {
118+
const routing = useDraftEnvironmentRouting(input);
119+
const draft = useComposerDraftStore((state) => state.getDraftSession(input.draftId!));
120+
return (
121+
<>
122+
<span>{draft?.environmentId}</span>
123+
<button
124+
onClick={async () => {
125+
const ready = await routing.refreshBeforeSend();
126+
onPrepared?.(ready);
127+
}}
128+
>
129+
Send
130+
</button>
131+
</>
132+
);
133+
}
134+
135+
it("refreshes a stored automatic choice before sending an unsent draft", async () => {
136+
const { a, b, draftId, input, store } = setup();
137+
store.setDraftThreadContext(draftId, {
138+
branch: "main",
139+
envMode: "worktree",
140+
environmentSelection: "auto",
141+
});
142+
await using screen = await render(
143+
<Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />,
144+
);
145+
await expect.element(screen.getByText(a)).toBeInTheDocument();
146+
await screen.getByRole("button", { name: "Send" }).click();
147+
await expect.element(screen.getByText(b)).toBeInTheDocument();
148+
expect(resources.refreshSelection).toHaveBeenCalledWith([a, b]);
149+
expect(store.getDraftSession(draftId)).toMatchObject({
150+
loadBalancedEnvironmentId: b,
151+
branch: "main",
152+
envMode: "worktree",
153+
});
154+
expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt");
155+
});
156+
157+
it.each(["manual", "attachments", "promoted"] as const)(
158+
"keeps the machine for %s drafts",
159+
async (kind) => {
160+
const { a, draftId, input, store } = setup();
161+
if (kind === "manual") store.setDraftThreadContext(draftId, { environmentSelection: "manual" });
162+
const guardedInput = {
163+
...input,
164+
automaticEnvironment: kind !== "manual",
165+
composerHasAttachments: kind === "attachments",
166+
draftThread:
167+
kind === "promoted"
168+
? {
169+
...input.draftThread!,
170+
promotedTo: { environmentId: a, threadId: input.draftThread!.threadId },
171+
}
172+
: input.draftThread,
173+
};
174+
await using screen = await render(<Harness input={guardedInput} />);
175+
await screen.getByRole("button", { name: "Send" }).click();
176+
expect(resources.refreshSelection).not.toHaveBeenCalled();
177+
expect(store.getDraftSession(draftId)?.environmentId).toBe(a);
178+
},
179+
);
180+
181+
it("does not reuse a stored choice when refreshed resources have no winner", async () => {
182+
const { a, input } = setup();
183+
resources.refreshSelection.mockResolvedValue(null);
184+
const onPrepared = vi.fn();
185+
await using screen = await render(<Harness input={input} onPrepared={onPrepared} />);
186+
await screen.getByRole("button", { name: "Send" }).click();
187+
await expect.element(screen.getByText(a)).toBeInTheDocument();
188+
await vi.waitFor(() => expect(onPrepared).toHaveBeenCalledWith(false));
189+
});
190+
191+
it("abandons a refresh when the draft changes while resources are in flight", async () => {
192+
const { a, b, draftId, input, store } = setup();
193+
let resolve!: (environmentId: EnvironmentId) => void;
194+
resources.refreshSelection.mockReturnValue(
195+
new Promise<EnvironmentId>((done) => {
196+
resolve = done;
197+
}),
198+
);
199+
await using screen = await render(<Harness input={input} />);
200+
await screen.getByRole("button", { name: "Send" }).click();
201+
await act(async () => {
202+
store.setPrompt(draftId, "Edited while checking");
203+
resolve(b);
204+
});
205+
await expect.element(screen.getByText(a)).toBeInTheDocument();
206+
expect(store.getComposerDraft(draftId)?.prompt).toBe("Edited while checking");
207+
});

‎apps/web/src/components/chat/useDraftEnvironmentRouting.ts‎

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
} from "@t3tools/contracts";
1212
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
1313
import { useEffect, useLayoutEffect, useRef, useState } from "react";
14+
import { flushSync } from "react-dom";
1415
import { toastManager } from "../ui/toast";
1516
import {
1617
deriveLogicalProjectKeyFromSettings,
@@ -20,6 +21,7 @@ import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
2021
import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
2122
import { useProjects } from "../../state/entities";
2223
import type { DraftSessionState } from "../../composerDraftStore";
24+
import { loadBalancingSendWarning } from "./composerSend.logic";
2325

2426
interface DraftEnvironmentRoutingInput {
2527
readonly draftId: DraftId | null;
@@ -74,7 +76,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
7476
const allProjects = useProjects();
7577
const { openScratchProject } = useScratchProject();
7678
const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
77-
const loadBalancingCandidates = needsLoadBalancing
79+
const loadBalancingCandidates = automaticEnvironment
7880
? logicalProjectEnvironments
7981
.filter((candidate) => {
8082
const environment = environmentById.get(candidate.environmentId);
@@ -108,9 +110,64 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
108110
.map((candidate) => candidate.environmentId)
109111
: [];
110112
const loadBalancing = useLoadBalancedEnvironment(
111-
loadBalancingCandidates,
113+
needsLoadBalancing ? loadBalancingCandidates : [],
112114
loadBalancingSettings.loadBalancingWeights,
113115
);
116+
const readRouting = useStableCallback(() => ({ input, loadBalancingCandidates }));
117+
const refreshBeforeSend = () => {
118+
if (
119+
!automaticEnvironment ||
120+
!draftId ||
121+
!draftThread?.loadBalancedEnvironmentId ||
122+
draftThread.promotedTo ||
123+
composerHasAttachments
124+
)
125+
return null;
126+
const originalDraft = getDraftSession(draftId);
127+
const composerDraft = useComposerDraftStore.getState().getComposerDraft(draftId);
128+
return loadBalancing.refreshSelection(loadBalancingCandidates).then((environmentId) => {
129+
const current = readRouting();
130+
if (
131+
current.input.draftId !== draftId ||
132+
!current.input.automaticEnvironment ||
133+
current.input.composerHasAttachments ||
134+
current.input.activeProjectKey !== activeProjectKey ||
135+
current.input.selectedProvider !== selectedProvider ||
136+
current.input.activeProviderInstanceId !== activeProviderInstanceId ||
137+
current.input.loadBalancingSettings.loadBalancingWeights !==
138+
loadBalancingSettings.loadBalancingWeights ||
139+
current.loadBalancingCandidates.join("\n") !== loadBalancingCandidates.join("\n") ||
140+
getDraftSession(draftId) !== originalDraft ||
141+
useComposerDraftStore.getState().getComposerDraft(draftId) !== composerDraft
142+
)
143+
return false;
144+
const target = current.input.logicalProjectEnvironments.find(
145+
(candidate) => candidate.environmentId === environmentId,
146+
);
147+
if (!target?.projectId) {
148+
toastManager.add({
149+
type: "warning",
150+
...loadBalancingSendWarning({
151+
pending: false,
152+
threadContexts: referencedThreadContexts,
153+
candidateEnvironmentIds: loadBalancingCandidates,
154+
}),
155+
});
156+
return false;
157+
}
158+
const projectRef = scopeProjectRef(target.environmentId, target.projectId);
159+
// The send must read the target project's composer and provider context after retargeting.
160+
flushSync(() =>
161+
setDraftThreadContext(draftId, {
162+
projectRef,
163+
environmentSelection: "auto",
164+
loadBalancedEnvironmentId: target.environmentId,
165+
branch: originalDraft?.branch ?? null,
166+
}),
167+
);
168+
return true;
169+
});
170+
};
114171
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the resolved load-balanced environment into the draft store once the async pick settles
115172
useEffect(() => {
116173
if (!needsLoadBalancing || loadBalancing.pending || !draftId || sendInFlightRef.current) return;
@@ -133,7 +190,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
133190
setDraftThreadContext,
134191
]);
135192
const onAutoEnvironment = () => {
136-
if (envLocked || !draftId) return;
193+
if (envLocked || !draftId || sendInFlightRef.current) return;
137194
if (composerHasAttachments) {
138195
toastManager.add({
139196
type: "warning",
@@ -262,6 +319,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
262319
return {
263320
needsLoadBalancing,
264321
loadBalancing,
322+
refreshBeforeSend,
265323
onAutoEnvironmentStable,
266324
autoEnvironmentLabel,
267325
isEnvironmentChanging,

0 commit comments

Comments
 (0)