Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
4import * as Option from "effect/Option";
5import type { EnvironmentPresentation } from "../../state/environments";
6import type { ServerProvider } from "@t3tools/contracts";
7import {
8 scopedThreadKey,
9 scopeProjectRef,
10 scopeThreadRef,
11} from "@t3tools/client-runtime/environment";
12import { createModelSelection } from "@t3tools/shared/model";
13import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
14import {
15 EnvironmentId,
16 ProjectId,
17 ProviderDriverKind,
18 ProviderInstanceId,
19} from "@t3tools/contracts";
20import { expect, it, vi } from "vite-plus/test";
21
22import { act, render } from "../../../test/render";
23import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
24import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
25import { appAtomRegistry, AppAtomRegistryProvider } from "../../rpc/atomRegistry";
26import { draftFanoutSelectionsAtom } from "./chatViewSend";
27
28const resources = vi.hoisted(() => ({
29 projects: [] as EnvironmentProject[],
30 pickedEnvironmentId: null as EnvironmentId | null,
31 refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(),
32}));
33vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({
34 useLoadBalancedEnvironment: () => ({
35 pending: false,
36 failed: false,
37 environmentId: resources.pickedEnvironmentId,
38 refresh: () => {},
39 refreshSelection: resources.refreshSelection,
40 }),
41}));
42vi.mock("../../state/entities", () => ({ useProjects: () => resources.projects }));
43vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) }));
44
45function setup() {
46 resources.refreshSelection.mockReset();
47 resources.projects = [];
48 resources.pickedEnvironmentId = null;
49 const a = EnvironmentId.make("machine-a");
50 const b = EnvironmentId.make("machine-b");
51 const draftId = DraftId.make("fresh-routing-draft");
52 const projectId = ProjectId.make("project");
53 const store = useComposerDraftStore.getState();
54 store.clearDraftThread(draftId);
55 store.setProjectDraftThreadId(scopeProjectRef(a, projectId), draftId, {
56 environmentSelection: "auto",
57 loadBalancedEnvironmentId: a,
58 });
59 store.setPrompt(draftId, "Keep this prompt");
60 const provider: ServerProvider = {
61 instanceId: ProviderInstanceId.make("codex"),
62 driver: ProviderDriverKind.make("codex"),
63 enabled: true,
64 installed: true,
65 status: "ready",
66 auth: { status: "authenticated" },
67 availability: "available",
68 version: null,
69 checkedAt: "2026-11-10T01:00:00.000Z",
70 models: [],
71 slashCommands: [],
72 skills: [],
73 };
74 const input: Parameters<typeof useDraftEnvironmentRouting>[0] = {
75 draftId,
76 draftThread: store.getDraftSession(draftId),
77 envLocked: false,
78 automaticEnvironment: true,
79 logicalProjectEnvironments: [a, b].map((environmentId) => ({
80 environmentId,
81 projectId,
82 label: environmentId,
83 isPrimary: environmentId === a,
84 machine: "desktop",
85 })),
86 environmentById: new Map(
87 [a, b].map((id): [EnvironmentId, EnvironmentPresentation] => [
88 id,
89 {
90 environmentId: id,
91 label: id,
92 displayUrl: null,
93 relayManaged: false,
94 entry: {
95 target: new PrimaryConnectionTarget({
96 environmentId: id,
97 label: id,
98 httpBaseUrl: "http://localhost:3000",
99 wsBaseUrl: "ws://localhost:3000",
100 }),
101 profile: Option.none(),
102 enabled: true,
103 },
104 connection: { phase: "connected", error: null, traceId: null },
105 serverConfig: null,
106 },
107 ]),
108 ),
109 providersByEnvironment: new Map([a, b].map((id) => [id, [provider]])),
110 loadBalancingSettings: { loadBalancingWeights: {} },
111 referencedThreadContexts: [],
112 activeProviderInstanceId: provider.instanceId,
113 selectedProvider: provider.driver,
114 composerHasAttachments: false,
115 activeProjectKey: "project",
116 activeProjectIsScratch: false,
117 projectGroupingSettings: DEFAULT_UNIFIED_SETTINGS,
118 sendInFlightRef: { current: false },
119 };
120 resources.refreshSelection.mockImplementation(async (ids) => (ids.includes(b) ? b : null));
121 return { a, b, draftId, input, store };
122}
123
124interface HarnessProps {
125 input: Parameters<typeof useDraftEnvironmentRouting>[0];
126 onPrepared?: (ready: boolean | null) => void;
127}
128
129function Harness(props: HarnessProps) {
130 return (
131 <AppAtomRegistryProvider>
132 <RoutingProbe {...props} />
133 </AppAtomRegistryProvider>
134 );
135}
136
137function RoutingProbe({ input, onPrepared }: HarnessProps) {
138 const routing = useDraftEnvironmentRouting(input);
139 const draft = useComposerDraftStore((state) => state.getDraftSession(input.draftId!));
140 const selections = useAtomValue(
141 draftFanoutSelectionsAtom(
142 scopedThreadKey(scopeThreadRef(draft!.environmentId, draft!.threadId)),
143 ),
144 );
145 return (
146 <>
147 <output>
148 {selections?.map((selection) => selection.model).join(", ") ?? "single model"}
149 </output>
150 {input.logicalProjectEnvironments.map(({ environmentId }) => (
151 <button
152 key={environmentId}
153 onClick={() => routing.onEnvironmentChangeStable(environmentId)}
154 >
155 Switch to {environmentId}
156 </button>
157 ))}
158 <span>{draft?.environmentId}</span>
159 <button
160 onClick={async () => {
161 const ready = await routing.refreshBeforeSend();
162 onPrepared?.(ready);
163 }}
164 >
165 Send
166 </button>
167 </>
168 );
169}
170
171it("refreshes a stored automatic choice before sending an unsent draft", async () => {
172 const { a, b, draftId, input, store } = setup();
173 const selections = ["model-a", "model-b"].map((model) =>
174 createModelSelection(ProviderInstanceId.make("codex"), model),
175 );
176 const threadId = input.draftThread!.threadId;
177 const destinationSelections = draftFanoutSelectionsAtom(
178 scopedThreadKey(scopeThreadRef(b, threadId)),
179 );
180 appAtomRegistry.set(destinationSelections, null);
181 appAtomRegistry.set(
182 draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(a, threadId))),
183 selections,
184 );
185 store.setDraftThreadContext(draftId, {
186 branch: "main",
187 envMode: "worktree",
188 environmentSelection: "auto",
189 });
190 await using screen = await render(
191 <Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />,
192 );
193 await expect.element(screen.getByText(a)).toBeInTheDocument();
194 await screen.getByRole("button", { name: "Send" }).click();
195 await expect.element(screen.getByText(b)).toBeInTheDocument();
196 expect(resources.refreshSelection).toHaveBeenCalledWith([a, b]);
197 expect(store.getDraftSession(draftId)).toMatchObject({
198 loadBalancedEnvironmentId: b,
199 branch: "main",
200 envMode: "worktree",
201 });
202 expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt");
203 expect(appAtomRegistry.get(destinationSelections)).toEqual(selections);
204});
205
206it.each(["manual", "attachments", "promoted"] as const)(
207 "keeps the machine for %s drafts",
208 async (kind) => {
209 const { a, draftId, input, store } = setup();
210 if (kind === "manual") store.setDraftThreadContext(draftId, { environmentSelection: "manual" });
211 const guardedInput = {
212 ...input,
213 automaticEnvironment: kind !== "manual",
214 composerHasAttachments: kind === "attachments",
215 draftThread:
216 kind === "promoted"
217 ? {
218 ...input.draftThread!,
219 promotedTo: { environmentId: a, threadId: input.draftThread!.threadId },
220 }
221 : input.draftThread,
222 };
223 await using screen = await render(<Harness input={guardedInput} />);
224 await screen.getByRole("button", { name: "Send" }).click();
225 expect(resources.refreshSelection).not.toHaveBeenCalled();
226 expect(store.getDraftSession(draftId)?.environmentId).toBe(a);
227 },
228);
229
230it("does not reuse a stored choice when refreshed resources have no winner", async () => {
231 const { a, input } = setup();
232 resources.refreshSelection.mockResolvedValue(null);
233 const onPrepared = vi.fn();
234 await using screen = await render(<Harness input={input} onPrepared={onPrepared} />);
235 await screen.getByRole("button", { name: "Send" }).click();
236 await expect.element(screen.getByText(a)).toBeInTheDocument();
237 await vi.waitFor(() => expect(onPrepared).toHaveBeenCalledWith(false));
238});
239
240it("abandons a refresh when the draft changes while resources are in flight", async () => {
241 const { a, b, draftId, input, store } = setup();
242 let resolve!: (environmentId: EnvironmentId) => void;
243 resources.refreshSelection.mockReturnValue(
244 new Promise<EnvironmentId>((done) => {
245 resolve = done;
246 }),
247 );
248 await using screen = await render(<Harness input={input} />);
249 await screen.getByRole("button", { name: "Send" }).click();
250 await act(async () => {
251 store.setPrompt(draftId, "Edited while checking");
252 resolve(b);
253 });
254 await expect.element(screen.getByText(a)).toBeInTheDocument();
255 expect(store.getComposerDraft(draftId)?.prompt).toBe("Edited while checking");
256});
257
258function fanoutSetup() {
259 const routing = setup();
260 const { a, b, draftId, input, store } = routing;
261 resources.projects = [a, b].map((environmentId) => ({
262 environmentId,
263 id: input.draftThread!.projectId,
264 title: "Project",
265 workspaceRoot: "/workspace/project",
266 defaultModelSelection: null,
267 scripts: [],
268 createdAt: "2026-11-10T01:00:00.000Z",
269 updatedAt: "2026-11-10T01:00:00.000Z",
270 }));
271 const threadId = input.draftThread!.threadId;
272 const selectionsOn = (environmentId: EnvironmentId) =>
273 draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(environmentId, threadId)));
274 const models = (...names: string[]) =>
275 names.map((model) => createModelSelection(ProviderInstanceId.make("codex"), model));
276 appAtomRegistry.set(selectionsOn(b), null);
277 appAtomRegistry.set(selectionsOn(a), models("gpt-6.1-sol", "gpt-6.1-luna"));
278 store.setDraftThreadContext(draftId, {
279 environmentSelection: "manual",
280 loadBalancedEnvironmentId: null,
281 branch: "main",
282 envMode: "worktree",
283 });
284 return { ...routing, selectionsOn, models };
285}
286
287it("keeps the selected models when the draft switches machine by hand", async () => {
288 const { a, b, draftId, input, store, selectionsOn, models } = fanoutSetup();
289 await using screen = await render(
290 <Harness
291 input={{ ...input, automaticEnvironment: false, draftThread: store.getDraftSession(draftId) }}
292 />,
293 );
294 await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument();
295 await screen.getByRole("button", { name: `Switch to ${b}` }).click();
296 await expect.element(screen.getByText(b)).toBeInTheDocument();
297 await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument();
298 expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt");
299
300 // Changes made on the new machine come back with the draft.
301 await act(async () => appAtomRegistry.set(selectionsOn(b), models("gpt-6.1-sol")));
302 await screen.getByRole("button", { name: `Switch to ${a}` }).click();
303 await expect.element(screen.getByText(a)).toBeInTheDocument();
304 await expect.element(screen.getByText("gpt-6.1-sol", { exact: true })).toBeInTheDocument();
305});
306
307it("keeps the selected models when automatic routing picks another machine", async () => {
308 const { b, draftId, input, store } = fanoutSetup();
309 store.setDraftThreadContext(draftId, { environmentSelection: "auto" });
310 resources.pickedEnvironmentId = b;
311 await using screen = await render(
312 <Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />,
313 );
314 await expect.element(screen.getByText(b)).toBeInTheDocument();
315 await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument();
316});