Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
import * as Option from "effect/Option";
import type { EnvironmentPresentation } from "../../state/environments";
Expand All @@ -20,26 +22,30 @@ import { expect, it, vi } from "vite-plus/test";
import { act, render } from "../../../test/render";
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
import { appAtomRegistry } from "../../rpc/atomRegistry";
import { appAtomRegistry, AppAtomRegistryProvider } from "../../rpc/atomRegistry";
import { draftFanoutSelectionsAtom } from "./chatViewSend";

const resources = vi.hoisted(() => ({
projects: [] as EnvironmentProject[],
pickedEnvironmentId: null as EnvironmentId | null,
refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(),
}));
vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({
useLoadBalancedEnvironment: () => ({
pending: false,
failed: false,
environmentId: null,
environmentId: resources.pickedEnvironmentId,
refresh: () => {},
refreshSelection: resources.refreshSelection,
}),
}));
vi.mock("../../state/entities", () => ({ useProjects: () => [] }));
vi.mock("../../state/entities", () => ({ useProjects: () => resources.projects }));
vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) }));

function setup() {
resources.refreshSelection.mockReset();
resources.projects = [];
resources.pickedEnvironmentId = null;
const a = EnvironmentId.make("machine-a");
const b = EnvironmentId.make("machine-b");
const draftId = DraftId.make("fresh-routing-draft");
Expand Down Expand Up @@ -115,17 +121,40 @@ function setup() {
return { a, b, draftId, input, store };
}

function Harness({
input,
onPrepared,
}: {
interface HarnessProps {
input: Parameters<typeof useDraftEnvironmentRouting>[0];
onPrepared?: (ready: boolean | null) => void;
}) {
}

function Harness(props: HarnessProps) {
return (
<AppAtomRegistryProvider>
<RoutingProbe {...props} />
</AppAtomRegistryProvider>
);
}

function RoutingProbe({ input, onPrepared }: HarnessProps) {
const routing = useDraftEnvironmentRouting(input);
const draft = useComposerDraftStore((state) => state.getDraftSession(input.draftId!));
const selections = useAtomValue(
draftFanoutSelectionsAtom(
scopedThreadKey(scopeThreadRef(draft!.environmentId, draft!.threadId)),
),
);
return (
<>
<output>
{selections?.map((selection) => selection.model).join(", ") ?? "single model"}
</output>
{input.logicalProjectEnvironments.map(({ environmentId }) => (
<button
key={environmentId}
onClick={() => routing.onEnvironmentChangeStable(environmentId)}
>
Switch to {environmentId}
</button>
))}
<span>{draft?.environmentId}</span>
<button
onClick={async () => {
Expand Down Expand Up @@ -225,3 +254,63 @@ it("abandons a refresh when the draft changes while resources are in flight", as
await expect.element(screen.getByText(a)).toBeInTheDocument();
expect(store.getComposerDraft(draftId)?.prompt).toBe("Edited while checking");
});

function fanoutSetup() {
const routing = setup();
const { a, b, draftId, input, store } = routing;
resources.projects = [a, b].map((environmentId) => ({
environmentId,
id: input.draftThread!.projectId,
title: "Project",
workspaceRoot: "/workspace/project",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-11-10T01:00:00.000Z",
updatedAt: "2026-11-10T01:00:00.000Z",
}));
const threadId = input.draftThread!.threadId;
const selectionsOn = (environmentId: EnvironmentId) =>
draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(environmentId, threadId)));
const models = (...names: string[]) =>
names.map((model) => createModelSelection(ProviderInstanceId.make("codex"), model));
appAtomRegistry.set(selectionsOn(b), null);
appAtomRegistry.set(selectionsOn(a), models("gpt-6.1-sol", "gpt-6.1-luna"));
store.setDraftThreadContext(draftId, {
environmentSelection: "manual",
loadBalancedEnvironmentId: null,
branch: "main",
envMode: "worktree",
});
return { ...routing, selectionsOn, models };
}

it("keeps the selected models when the draft switches machine by hand", async () => {
const { a, b, draftId, input, store, selectionsOn, models } = fanoutSetup();
await using screen = await render(
<Harness
input={{ ...input, automaticEnvironment: false, draftThread: store.getDraftSession(draftId) }}
/>,
);
await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument();
await screen.getByRole("button", { name: `Switch to ${b}` }).click();
await expect.element(screen.getByText(b)).toBeInTheDocument();
await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument();
expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt");

// Changes made on the new machine come back with the draft.
await act(async () => appAtomRegistry.set(selectionsOn(b), models("gpt-6.1-sol")));
await screen.getByRole("button", { name: `Switch to ${a}` }).click();
await expect.element(screen.getByText(a)).toBeInTheDocument();
await expect.element(screen.getByText("gpt-6.1-sol", { exact: true })).toBeInTheDocument();
});

it("keeps the selected models when automatic routing picks another machine", async () => {
const { b, draftId, input, store } = fanoutSetup();
store.setDraftThreadContext(draftId, { environmentSelection: "auto" });
resources.pickedEnvironmentId = b;
await using screen = await render(
<Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />,
);
await expect.element(screen.getByText(b)).toBeInTheDocument();
await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument();
});
31 changes: 19 additions & 12 deletions apps/web/src/components/chat/useDraftEnvironmentRouting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,20 @@ interface DraftEnvironmentRoutingInput {
readonly sendInFlightRef: { readonly current: boolean };
}

// Multiple-model selections are kept per route, so a draft moving machine takes them along.
function carryFanoutSelections(
draft: Pick<DraftSessionState, "environmentId" | "threadId">,
environmentId: EnvironmentId,
) {
if (draft.environmentId === environmentId) return;
const selectionsOn = (id: EnvironmentId) =>
draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(id, draft.threadId)));
appAtomRegistry.set(
selectionsOn(environmentId),
appAtomRegistry.get(selectionsOn(draft.environmentId)),
);
}

/**
* Which machine an unsent draft runs on: automatic load balancing across the
* project's machines, or a manual switch, which may first open a scratch
Expand Down Expand Up @@ -174,18 +188,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
return false;
}
const projectRef = scopeProjectRef(target.environmentId, target.projectId);
if (originalDraft && target.environmentId !== originalDraft.environmentId) {
appAtomRegistry.set(
draftFanoutSelectionsAtom(
scopedThreadKey(scopeThreadRef(target.environmentId, originalDraft.threadId)),
),
appAtomRegistry.get(
draftFanoutSelectionsAtom(
scopedThreadKey(scopeThreadRef(originalDraft.environmentId, originalDraft.threadId)),
),
),
);
}
if (originalDraft) carryFanoutSelections(originalDraft, target.environmentId);
// The send must read the target project's composer and provider context after retargeting.
flushSync(() =>
setDraftThreadContext(draftId, {
Expand All @@ -205,6 +208,8 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
(environment) => environment.environmentId === loadBalancing.environmentId,
);
if (!target?.projectId) return;
const draft = getDraftSession(draftId);
if (draft) carryFanoutSelections(draft, target.environmentId);
setDraftThreadContext(draftId, {
projectRef: scopeProjectRef(target.environmentId, target.projectId),
environmentSelection: "auto",
Expand All @@ -217,6 +222,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
draftId,
logicalProjectEnvironments,
sendInFlightRef,
getDraftSession,
setDraftThreadContext,
]);
const onAutoEnvironment = () => {
Expand Down Expand Up @@ -315,6 +321,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt);
if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt);
}
carryFanoutSelections(currentDraft, target.environmentId);
const projectRef = scopeProjectRef(target.environmentId, project.id);
if (activeProjectIsScratch) {
setLogicalProjectDraftThreadId(
Expand Down
86 changes: 86 additions & 0 deletions scripts/scenarios/machine-switch-keeps-selected-models.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test(
"A new draft keeps its selected models when it moves to another machine",
WEB,
async ({ t3, app, screen, browser }) => {
const primary = makeState(T3_HOME);
const second = makeState(SECOND_HOME);
// Machines share a project through its repository, which needs a remote to be named by.
const workspace = await runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.join(T3_HOME, "workspaces"), { recursive: true });
const directory = yield* fs.makeTempDirectory({
directory: path.join(T3_HOME, "workspaces"),
prefix: "demo-",
});
yield* fs.writeFileString(path.join(directory, "README.md"), "");
return directory;
}),
);
const git = (args: ReadonlyArray<string>) => runPromise(run("git", args, { cwd: workspace }));
await git(["init", "--quiet", "--initial-branch=main"]);
await git(["remote", "add", "origin", "https://github.com/scenario/demo.git"]);
await git(["add", "--all"]);
await git([
"-c",
"user.name=Scenario",
"-c",
"user.email=scenario@example.invalid",
"commit",
"--quiet",
"--message",
"Initial commit",
]);
await runPromise(primary.cli(["project", "add", workspace, "--title", "demo"]));
const server = startSecondServer(app.baseUrl ?? "");
try {
const { host, token } = await server.ready;
await runPromise(second.cli(["project", "add", workspace, "--title", "demo"]));

await t3.open("/settings/connections");
await screen.getByRole("button", "Add environment").tap();
const dialog = screen.getByRole("dialog");
await dialog.getByPlaceholder("backend.example.com").fill(host);
await dialog.getByPlaceholder("PAIRCODE").fill(token);
await dialog.getByRole("button", "Add environment").tap();
await expect(screen.getByRole("button", "More actions for Scenario")).toBeVisible({
timeout: 60_000,
});
await app.open("/");
// Shift adds a model to the draft instead of replacing it.
await screen.getByRole("button", "Showcase", { exact: false }).first().tap();
await browser.keyboard.type("Plan and reads");
await browser.keyboard.press("Shift+Enter");
await browser.keyboard.press("Escape");
const models = screen.getByRole("button", "Showcase, Plan and reads", { exact: false });
await expect(models.first()).toBeVisible();

// Both machines are named Scenario; the draft runs on the checked one.
const runOn = () => screen.getByText("Scenario").last().tap();
const machine = (index: number) => browser.locator('[role="menuitemradio"]').nth(index);
await runOn();
const target = (await machine(0).getAttribute("aria-checked")) === "true" ? 1 : 0;
await machine(target).click();
await runOn();
await expect(machine(target)).toHaveAttribute("aria-checked", "true");
await browser.keyboard.press("Escape");

await app.screenshot("after-machine-switch");
await expect(models.first()).toBeVisible();
} finally {
await server.stop();
await runPromise(primary.cli(["project", "remove", workspace, "--force"]));
}
},
);
67 changes: 5 additions & 62 deletions scripts/scenarios/removed-environment-closes-its-toasts.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
import { expect } from "e2e";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";

import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { prepareHome, start } from "./start-app.ts";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const SECOND_HOME = `${T3_HOME}-second-environment`;

/** A second server on its own T3 home, running until interrupted. `--dev-url` admits the web
* origin through CORS and registers the replay agent; `paired` gets the Add environment input. */
const runSecondServer = Effect.fn("scenario.secondServer")(function* (
devUrl: string,
paired: (target: { readonly host: string; readonly token: string }) => void,
) {
const path = yield* Path.Path;
const node = yield* HostProcess.ExecutablePath;
const hostEnvironment = yield* HostProcess.Environment;
const port = yield* (yield* NetService.NetService).reserveLoopbackPort();
yield* prepareHome(SECOND_HOME);
const token = yield* Deferred.make<string>();
yield* start({
cwd: APP_DIR,
command: node,
args: [
"apps/server/src/bin.ts",
"serve",
"--host",
"127.0.0.1",
"--port",
String(port),
"--base-dir",
SECOND_HOME,
"--dev-url",
devUrl,
],
env: {
PATH: `${path.join(SECOND_HOME, "bin")}:${hostEnvironment.PATH ?? ""}`,
HOME: hostEnvironment.HOME,
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
},
onLine: (line) => {
const value = /^Token:\s*(\S+)/.exec(line)?.[1];
return value === undefined ? Effect.void : Deferred.succeed(token, value).pipe(Effect.asVoid);
},
});
paired({ host: `http://127.0.0.1:${port}`, token: yield* Deferred.await(token) });
return yield* Effect.never;
});

test(
"Removing an environment closes the in-app notifications it raised",
WEB,
Expand All @@ -66,16 +16,9 @@ test(
});
const primary = makeState(T3_HOME);
const second = makeState(SECOND_HOME);
const pairing = Promise.withResolvers<{ host: string; token: string }>();
const server = Effect.runFork(
runSecondServer(app.baseUrl ?? "", pairing.resolve).pipe(
Effect.scoped,
Effect.provide([NodeServices.layer, NetService.layer]),
),
);
server.addObserver(() => pairing.reject(new Error("The second server stopped.")));
const server = startSecondServer(app.baseUrl ?? "");
try {
const { host, token } = await pairing.promise;
const { host, token } = await server.ready;
const project = await second.state.project("remote-demo");
const thread = await second.state.thread({
project,
Expand Down Expand Up @@ -127,7 +70,7 @@ test(
}
await expect(moreActions).toBeHidden({ timeout: 30_000 });
} finally {
await Effect.runPromise(Fiber.interrupt(server));
await server.stop();
}
},
);
Loading
Loading