Open History to see the last commit
1import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2import * as Option from "effect/Option";
3import type { EnvironmentPresentation } from "../../state/environments";
4import type { ServerProvider } from "@t3tools/contracts";
5import {
6 scopedThreadKey,
7 scopeProjectRef,
8 scopeThreadRef,
9} from "@t3tools/client-runtime/environment";
10import { createModelSelection } from "@t3tools/shared/model";
11import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
12import {
13 EnvironmentId,
14 ProjectId,
15 ProviderDriverKind,
16 ProviderInstanceId,
17} from "@t3tools/contracts";
18import { expect, it, vi } from "vite-plus/test";
19
20import { act, render } from "../../../test/render";
21import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
22import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
23import { appAtomRegistry } from "../../rpc/atomRegistry";
24import { draftFanoutSelectionsAtom } from "./chatViewSend";
25
26const resources = vi.hoisted(() => ({
27 refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(),
28}));
29vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({
30 useLoadBalancedEnvironment: () => ({
31 pending: false,
32 failed: false,
33 environmentId: null,
34 refresh: () => {},
35 refreshSelection: resources.refreshSelection,
36 }),
37}));
38vi.mock("../../state/entities", () => ({ useProjects: () => [] }));
39vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) }));
40
41function 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
118function 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
142it("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
177it.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
201it("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
211it("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});