The best way to control Claude Code, Codex and more from any computer or phone
fix(web): switching a draft’s machine keeps its selected models (#37208)
Co-authored-by: Grok 4.7 <noreply@x.ai> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 15, 2026 at 14:47 UTC
0b489dada1f00db39c99074239c09c006f223aee
5 files changed
+275
-82
apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx
+97
-8
@@ -1,3 +1,5 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3
import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
4
import * as Option from "effect/Option";
5
import type { EnvironmentPresentation } from "../../state/environments";
@@ -20,26 +22,30 @@ import { expect, it, vi } from "vite-plus/test";
22
import { act, render } from "../../../test/render";
23
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
24
import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
23
-import { appAtomRegistry } from "../../rpc/atomRegistry";
25
+import { appAtomRegistry, AppAtomRegistryProvider } from "../../rpc/atomRegistry";
26
import { draftFanoutSelectionsAtom } from "./chatViewSend";
27
28
const resources = vi.hoisted(() => ({
29
+ projects: [] as EnvironmentProject[],
30
+ pickedEnvironmentId: null as EnvironmentId | null,
31
refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(),
32
}));
33
vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({
34
useLoadBalancedEnvironment: () => ({
35
pending: false,
36
failed: false,
33
- environmentId: null,
37
+ environmentId: resources.pickedEnvironmentId,
38
refresh: () => {},
39
refreshSelection: resources.refreshSelection,
40
}),
41
}));
38
-vi.mock("../../state/entities", () => ({ useProjects: () => [] }));
42
+vi.mock("../../state/entities", () => ({ useProjects: () => resources.projects }));
43
vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) }));
44
45
function 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");
@@ -115,17 +121,40 @@ function setup() {
121
return { a, b, draftId, input, store };
122
}
123
118
-function Harness({
119
- input,
120
- onPrepared,
121
-}: {
124
+interface HarnessProps {
125
input: Parameters<typeof useDraftEnvironmentRouting>[0];
126
onPrepared?: (ready: boolean | null) => void;
124
-}) {
127
+}
128
+
129
+function Harness(props: HarnessProps) {
130
+ return (
131
+ <AppAtomRegistryProvider>
132
+ <RoutingProbe {...props} />
133
+ </AppAtomRegistryProvider>
134
+ );
135
+}
136
+
137
+function 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 () => {
@@ -225,3 +254,63 @@ it("abandons a refresh when the draft changes while resources are in flight", as
254
await expect.element(screen.getByText(a)).toBeInTheDocument();
255
expect(store.getComposerDraft(draftId)?.prompt).toBe("Edited while checking");
256
});
257
+
258
+function 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
+
287
+it("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
+
307
+it("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
+});
apps/web/src/components/chat/useDraftEnvironmentRouting.ts
+19
-12
@@ -58,6 +58,20 @@ interface DraftEnvironmentRoutingInput {
58
readonly sendInFlightRef: { readonly current: boolean };
59
}
60
61
+// Multiple-model selections are kept per route, so a draft moving machine takes them along.
62
+function carryFanoutSelections(
63
+ draft: Pick<DraftSessionState, "environmentId" | "threadId">,
64
+ environmentId: EnvironmentId,
65
+) {
66
+ if (draft.environmentId === environmentId) return;
67
+ const selectionsOn = (id: EnvironmentId) =>
68
+ draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(id, draft.threadId)));
69
+ appAtomRegistry.set(
70
+ selectionsOn(environmentId),
71
+ appAtomRegistry.get(selectionsOn(draft.environmentId)),
72
+ );
73
+}
74
+
75
/**
76
* Which machine an unsent draft runs on: automatic load balancing across the
77
* project's machines, or a manual switch, which may first open a scratch
@@ -174,18 +188,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
188
return false;
189
}
190
const projectRef = scopeProjectRef(target.environmentId, target.projectId);
177
- if (originalDraft && target.environmentId !== originalDraft.environmentId) {
178
- appAtomRegistry.set(
179
- draftFanoutSelectionsAtom(
180
- scopedThreadKey(scopeThreadRef(target.environmentId, originalDraft.threadId)),
181
- ),
182
- appAtomRegistry.get(
183
- draftFanoutSelectionsAtom(
184
- scopedThreadKey(scopeThreadRef(originalDraft.environmentId, originalDraft.threadId)),
185
- ),
186
- ),
187
- );
188
- }
191
+ if (originalDraft) carryFanoutSelections(originalDraft, target.environmentId);
192
// The send must read the target project's composer and provider context after retargeting.
193
flushSync(() =>
194
setDraftThreadContext(draftId, {
@@ -205,6 +208,8 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
208
(environment) => environment.environmentId === loadBalancing.environmentId,
209
);
210
if (!target?.projectId) return;
211
+ const draft = getDraftSession(draftId);
212
+ if (draft) carryFanoutSelections(draft, target.environmentId);
213
setDraftThreadContext(draftId, {
214
projectRef: scopeProjectRef(target.environmentId, target.projectId),
215
environmentSelection: "auto",
@@ -217,6 +222,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
222
draftId,
223
logicalProjectEnvironments,
224
sendInFlightRef,
225
+ getDraftSession,
226
setDraftThreadContext,
227
]);
228
const onAutoEnvironment = () => {
@@ -315,6 +321,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
321
const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt);
322
if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt);
323
}
324
+ carryFanoutSelections(currentDraft, target.environmentId);
325
const projectRef = scopeProjectRef(target.environmentId, project.id);
326
if (activeProjectIsScratch) {
327
setLogicalProjectDraftThreadId(
scripts/scenarios/machine-switch-keeps-selected-models.e2e.ts
new
+86
@@ -0,0 +1,86 @@
1
+import { expect } from "e2e";
2
+import * as Effect from "effect/Effect";
3
+import * as FileSystem from "effect/FileSystem";
4
+import * as Path from "effect/Path";
5
+
6
+import { T3_HOME } from "../e2e.config.ts";
7
+import { SECOND_HOME, startSecondServer } from "./second-server.ts";
8
+import { run } from "./shell.ts";
9
+import { makeState, runPromise, test, WEB } from "./t3.ts";
10
+
11
+test(
12
+ "A new draft keeps its selected models when it moves to another machine",
13
+ WEB,
14
+ async ({ t3, app, screen, browser }) => {
15
+ const primary = makeState(T3_HOME);
16
+ const second = makeState(SECOND_HOME);
17
+ // Machines share a project through its repository, which needs a remote to be named by.
18
+ const workspace = await runPromise(
19
+ Effect.gen(function* () {
20
+ const fs = yield* FileSystem.FileSystem;
21
+ const path = yield* Path.Path;
22
+ yield* fs.makeDirectory(path.join(T3_HOME, "workspaces"), { recursive: true });
23
+ const directory = yield* fs.makeTempDirectory({
24
+ directory: path.join(T3_HOME, "workspaces"),
25
+ prefix: "demo-",
26
+ });
27
+ yield* fs.writeFileString(path.join(directory, "README.md"), "");
28
+ return directory;
29
+ }),
30
+ );
31
+ const git = (args: ReadonlyArray<string>) => runPromise(run("git", args, { cwd: workspace }));
32
+ await git(["init", "--quiet", "--initial-branch=main"]);
33
+ await git(["remote", "add", "origin", "https://github.com/scenario/demo.git"]);
34
+ await git(["add", "--all"]);
35
+ await git([
36
+ "-c",
37
+ "user.name=Scenario",
38
+ "-c",
39
+ "user.email=scenario@example.invalid",
40
+ "commit",
41
+ "--quiet",
42
+ "--message",
43
+ "Initial commit",
44
+ ]);
45
+ await runPromise(primary.cli(["project", "add", workspace, "--title", "demo"]));
46
+ const server = startSecondServer(app.baseUrl ?? "");
47
+ try {
48
+ const { host, token } = await server.ready;
49
+ await runPromise(second.cli(["project", "add", workspace, "--title", "demo"]));
50
+
51
+ await t3.open("/settings/connections");
52
+ await screen.getByRole("button", "Add environment").tap();
53
+ const dialog = screen.getByRole("dialog");
54
+ await dialog.getByPlaceholder("backend.example.com").fill(host);
55
+ await dialog.getByPlaceholder("PAIRCODE").fill(token);
56
+ await dialog.getByRole("button", "Add environment").tap();
57
+ await expect(screen.getByRole("button", "More actions for Scenario")).toBeVisible({
58
+ timeout: 60_000,
59
+ });
60
+ await app.open("/");
61
+ // Shift adds a model to the draft instead of replacing it.
62
+ await screen.getByRole("button", "Showcase", { exact: false }).first().tap();
63
+ await browser.keyboard.type("Plan and reads");
64
+ await browser.keyboard.press("Shift+Enter");
65
+ await browser.keyboard.press("Escape");
66
+ const models = screen.getByRole("button", "Showcase, Plan and reads", { exact: false });
67
+ await expect(models.first()).toBeVisible();
68
+
69
+ // Both machines are named Scenario; the draft runs on the checked one.
70
+ const runOn = () => screen.getByText("Scenario").last().tap();
71
+ const machine = (index: number) => browser.locator('[role="menuitemradio"]').nth(index);
72
+ await runOn();
73
+ const target = (await machine(0).getAttribute("aria-checked")) === "true" ? 1 : 0;
74
+ await machine(target).click();
75
+ await runOn();
76
+ await expect(machine(target)).toHaveAttribute("aria-checked", "true");
77
+ await browser.keyboard.press("Escape");
78
+
79
+ await app.screenshot("after-machine-switch");
80
+ await expect(models.first()).toBeVisible();
81
+ } finally {
82
+ await server.stop();
83
+ await runPromise(primary.cli(["project", "remove", workspace, "--force"]));
84
+ }
85
+ },
86
+);
scripts/scenarios/removed-environment-closes-its-toasts.e2e.ts
+5
-62
@@ -1,59 +1,9 @@
1
-import * as NodeServices from "@effect/platform-node/NodeServices";
2
-import * as HostProcess from "@t3tools/shared/HostProcess";
3
-import * as NetService from "@t3tools/shared/Net";
1
import { expect } from "e2e";
5
-import * as Deferred from "effect/Deferred";
6
-import * as Effect from "effect/Effect";
7
-import * as Fiber from "effect/Fiber";
8
-import * as Path from "effect/Path";
2
10
-import { APP_DIR, T3_HOME } from "../e2e.config.ts";
11
-import { prepareHome, start } from "./start-app.ts";
3
+import { T3_HOME } from "../e2e.config.ts";
4
+import { SECOND_HOME, startSecondServer } from "./second-server.ts";
5
import { makeState, runPromise, test, WEB } from "./t3.ts";
6
14
-const SECOND_HOME = `${T3_HOME}-second-environment`;
15
-
16
-/** A second server on its own T3 home, running until interrupted. `--dev-url` admits the web
17
- * origin through CORS and registers the replay agent; `paired` gets the Add environment input. */
18
-const runSecondServer = Effect.fn("scenario.secondServer")(function* (
19
- devUrl: string,
20
- paired: (target: { readonly host: string; readonly token: string }) => void,
21
-) {
22
- const path = yield* Path.Path;
23
- const node = yield* HostProcess.ExecutablePath;
24
- const hostEnvironment = yield* HostProcess.Environment;
25
- const port = yield* (yield* NetService.NetService).reserveLoopbackPort();
26
- yield* prepareHome(SECOND_HOME);
27
- const token = yield* Deferred.make<string>();
28
- yield* start({
29
- cwd: APP_DIR,
30
- command: node,
31
- args: [
32
- "apps/server/src/bin.ts",
33
- "serve",
34
- "--host",
35
- "127.0.0.1",
36
- "--port",
37
- String(port),
38
- "--base-dir",
39
- SECOND_HOME,
40
- "--dev-url",
41
- devUrl,
42
- ],
43
- env: {
44
- PATH: `${path.join(SECOND_HOME, "bin")}:${hostEnvironment.PATH ?? ""}`,
45
- HOME: hostEnvironment.HOME,
46
- T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
47
- },
48
- onLine: (line) => {
49
- const value = /^Token:\s*(\S+)/.exec(line)?.[1];
50
- return value === undefined ? Effect.void : Deferred.succeed(token, value).pipe(Effect.asVoid);
51
- },
52
- });
53
- paired({ host: `http://127.0.0.1:${port}`, token: yield* Deferred.await(token) });
54
- return yield* Effect.never;
55
-});
56
-
7
test(
8
"Removing an environment closes the in-app notifications it raised",
9
WEB,
@@ -66,16 +16,9 @@ test(
16
});
17
const primary = makeState(T3_HOME);
18
const second = makeState(SECOND_HOME);
69
- const pairing = Promise.withResolvers<{ host: string; token: string }>();
70
- const server = Effect.runFork(
71
- runSecondServer(app.baseUrl ?? "", pairing.resolve).pipe(
72
- Effect.scoped,
73
- Effect.provide([NodeServices.layer, NetService.layer]),
74
- ),
75
- );
76
- server.addObserver(() => pairing.reject(new Error("The second server stopped.")));
19
+ const server = startSecondServer(app.baseUrl ?? "");
20
try {
78
- const { host, token } = await pairing.promise;
21
+ const { host, token } = await server.ready;
22
const project = await second.state.project("remote-demo");
23
const thread = await second.state.thread({
24
project,
@@ -127,7 +70,7 @@ test(
70
}
71
await expect(moreActions).toBeHidden({ timeout: 30_000 });
72
} finally {
130
- await Effect.runPromise(Fiber.interrupt(server));
73
+ await server.stop();
74
}
75
},
76
);
scripts/scenarios/second-server.ts
new
+68
@@ -0,0 +1,68 @@
1
+// A second T3 server for scenarios that need another machine: its own T3 home, the replay
2
+// agent, and a pairing token for Settings > Connections > Add environment.
3
+import * as NodeServices from "@effect/platform-node/NodeServices";
4
+import * as HostProcess from "@t3tools/shared/HostProcess";
5
+import * as NetService from "@t3tools/shared/Net";
6
+import * as Deferred from "effect/Deferred";
7
+import * as Effect from "effect/Effect";
8
+import * as Fiber from "effect/Fiber";
9
+import * as Path from "effect/Path";
10
+
11
+import { APP_DIR, T3_HOME } from "../e2e.config.ts";
12
+import { prepareHome, start } from "./start-app.ts";
13
+
14
+export const SECOND_HOME = `${T3_HOME}-second-environment`;
15
+
16
+/** A second server on its own T3 home, running until interrupted. `--dev-url` admits the web
17
+ * origin through CORS and registers the replay agent; `paired` gets the Add environment input. */
18
+const runSecondServer = Effect.fn("scenario.secondServer")(function* (
19
+ devUrl: string,
20
+ paired: (target: { readonly host: string; readonly token: string }) => void,
21
+) {
22
+ const path = yield* Path.Path;
23
+ const node = yield* HostProcess.ExecutablePath;
24
+ const hostEnvironment = yield* HostProcess.Environment;
25
+ const port = yield* (yield* NetService.NetService).reserveLoopbackPort();
26
+ yield* prepareHome(SECOND_HOME);
27
+ const token = yield* Deferred.make<string>();
28
+ yield* start({
29
+ cwd: APP_DIR,
30
+ command: node,
31
+ args: [
32
+ "apps/server/src/bin.ts",
33
+ "serve",
34
+ "--host",
35
+ "127.0.0.1",
36
+ "--port",
37
+ String(port),
38
+ "--base-dir",
39
+ SECOND_HOME,
40
+ "--dev-url",
41
+ devUrl,
42
+ ],
43
+ env: {
44
+ PATH: `${path.join(SECOND_HOME, "bin")}:${hostEnvironment.PATH ?? ""}`,
45
+ HOME: hostEnvironment.HOME,
46
+ T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
47
+ },
48
+ onLine: (line) => {
49
+ const value = /^Token:\s*(\S+)/.exec(line)?.[1];
50
+ return value === undefined ? Effect.void : Deferred.succeed(token, value).pipe(Effect.asVoid);
51
+ },
52
+ });
53
+ paired({ host: `http://127.0.0.1:${port}`, token: yield* Deferred.await(token) });
54
+ return yield* Effect.never;
55
+});
56
+
57
+/** Starts the second server for the web app at `devUrl`. `ready` settles with its pairing input. */
58
+export function startSecondServer(devUrl: string) {
59
+ const pairing = Promise.withResolvers<{ readonly host: string; readonly token: string }>();
60
+ const server = Effect.runFork(
61
+ runSecondServer(devUrl, pairing.resolve).pipe(
62
+ Effect.scoped,
63
+ Effect.provide([NodeServices.layer, NetService.layer]),
64
+ ),
65
+ );
66
+ server.addObserver(() => pairing.reject(new Error("The second server stopped.")));
67
+ return { ready: pairing.promise, stop: () => Effect.runPromise(Fiber.interrupt(server)) };
68
+}