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
Expand Up @@ -2,8 +2,9 @@ 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 { AsyncResult, Atom } from "effect/reactivity";
import type { EnvironmentPresentation } from "../../state/environments";
import type { ServerProvider } from "@t3tools/contracts";
import type { ProjectReadFileResult, ServerProvider } from "@t3tools/contracts";
import {
scopedThreadKey,
scopeProjectRef,
Expand All @@ -24,9 +25,18 @@ import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
import { appAtomRegistry, AppAtomRegistryProvider } from "../../rpc/atomRegistry";
import { draftFanoutSelectionsAtom } from "./chatViewSend";
import { readProjects } from "../../state/entities";

const resources = vi.hoisted(() => ({
projects: [] as EnvironmentProject[],
projectListeners: new Set<(projects: readonly EnvironmentProject[]) => void>(),
getProjectFileQueryAtom:
vi.fn<
(
environmentId: EnvironmentId,
root: string,
) => Atom.Atom<AsyncResult.AsyncResult<ProjectReadFileResult, never>>
>(),
pickedEnvironmentId: null as EnvironmentId | null,
refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(),
}));
Expand All @@ -41,6 +51,11 @@ vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({
}));
vi.mock("../../state/entities", () => ({
useProjects: () => resources.projects,
readProjects: () => resources.projects,
subscribeProjects: (listener: (projects: readonly EnvironmentProject[]) => void) => {
resources.projectListeners.add(listener);
return () => resources.projectListeners.delete(listener);
},
readThreadShells: () => [],
readProject: (ref: { environmentId: EnvironmentId; projectId: ProjectId }) =>
resources.projects.find(
Expand All @@ -49,9 +64,27 @@ vi.mock("../../state/entities", () => ({
}));
vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) }));

vi.mock(import("../files/projectFilesQueryState"), async (original) => ({
...(await original()),
getProjectFileQueryAtom: resources.getProjectFileQueryAtom,
}));

function projectFileAtom(contents: string) {
return Atom.make(
AsyncResult.success<ProjectReadFileResult>({
relativePath: "t3.json",
byteLength: new TextEncoder().encode(contents).byteLength,
contents,
truncated: false,
}),
);
}

function setup() {
resources.refreshSelection.mockReset();
resources.getProjectFileQueryAtom.mockReset().mockReturnValue(projectFileAtom("{}"));
resources.projects = [];
resources.projectListeners.clear();
resources.pickedEnvironmentId = null;
const a = EnvironmentId.make("machine-a");
const b = EnvironmentId.make("machine-b");
Expand Down Expand Up @@ -164,7 +197,9 @@ function RoutingProbe({ input, onPrepared }: HarnessProps) {
</button>
))}
<span>{draft?.environmentId}</span>
<button onClick={routing.onAutoEnvironmentStable}>Auto balance</button>
<button
disabled={routing.isEnvironmentChanging}
onClick={async () => {
const ready = await routing.refreshBeforeSend();
onPrepared?.(ready);
Expand Down Expand Up @@ -396,3 +431,64 @@ it("keeps a workspace the user picked when the draft switches machine by hand",
await expect.element(screen.getByText(b)).toBeInTheDocument();
expect(store.getDraftSession(draftId)?.envMode).toBe("local");
});

it.each(["deleted", "moved"] as const)(
"checks the destination again when the project was %s during the default read",
async (change) => {
const { a, b, draftId, input, store } = fanoutSetup();
const pending = Atom.make(AsyncResult.initial<ProjectReadFileResult, never>());
const moved = projectFileAtom('{"defaultThreadEnvMode":"worktree"}');
resources.getProjectFileQueryAtom.mockImplementation((_environmentId, root) =>
root === "/workspace/moved" ? moved : pending,
);
store.setDraftThreadContext(draftId, { envMode: "local" });

await using screen = await render(
<Harness input={{ ...input, automaticEnvironment: false }} />,
);
await screen.getByRole("button", { name: `Switch to ${b}` }).click();
const send = screen.getByRole("button", { name: "Send", exact: true });
await expect.element(send).toBeDisabled();
await act(async () => {
resources.projects = resources.projects.flatMap((project) => {
if (project.environmentId !== b) return [project];
return change === "deleted" ? [] : [{ ...project, workspaceRoot: "/workspace/moved" }];
});
for (const listener of resources.projectListeners) listener(readProjects());
});
await expect.element(send).toBeEnabled();
expect(store.getDraftSession(draftId)).toMatchObject({
environmentId: change === "moved" ? b : a,
envMode: change === "moved" ? "worktree" : "local",
});
expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt");
},
);

it.each(["leave the draft", "choose automatic routing", "switch to another machine"] as const)(
"stops watching the destination when users %s before the default loads",
async (action) => {
const { a, b, input } = fanoutSetup();
const pending = Atom.make(AsyncResult.initial<ProjectReadFileResult, never>());
const settled = projectFileAtom("{}");
resources.getProjectFileQueryAtom.mockImplementation((environmentId) =>
environmentId === b ? pending : settled,
);
await using screen = await render(
<Harness input={{ ...input, automaticEnvironment: false }} />,
);
await screen.getByRole("button", { name: `Switch to ${b}` }).click();
const send = screen.getByRole("button", { name: "Send", exact: true });
await expect.element(send).toBeDisabled();
expect(resources.projectListeners.size).toBe(1);

if (action === "leave the draft") {
await screen.unmount();
} else {
const button = action === "choose automatic routing" ? "Auto balance" : `Switch to ${a}`;
await screen.getByRole("button", { name: button, exact: true }).click();
await expect.element(send).toBeEnabled();
}
expect(resources.projectListeners.size).toBe(0);
},
);
153 changes: 109 additions & 44 deletions apps/web/src/components/chat/useDraftEnvironmentRouting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {
import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
import { currentClientMetadata } from "../../connection/platform";
import { useProjects } from "../../state/entities";
import { readProjects, subscribeProjects, useProjects } from "../../state/entities";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import type { DraftSessionState } from "../../composerDraftStore";
Expand Down Expand Up @@ -207,9 +207,25 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
return true;
});
};
const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
// The busy state belongs to the request that set it, so an older request settling late
// (abandoned, or superseded by a newer switch) can never clear a newer one's.
const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
readonly environmentId: EnvironmentId;
readonly scope: string;
} | null>(null);
const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;

// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the resolved load-balanced environment into the draft store once the async pick settles
useEffect(() => {
if (!needsLoadBalancing || loadBalancing.pending || !draftId || sendInFlightRef.current) return;
if (
!needsLoadBalancing ||
loadBalancing.pending ||
!draftId ||
isEnvironmentChanging ||
sendInFlightRef.current
)
return;
const target = logicalProjectEnvironments.find(
(environment) => environment.environmentId === loadBalancing.environmentId,
);
Expand All @@ -225,12 +241,39 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
needsLoadBalancing,
loadBalancing.pending,
loadBalancing.environmentId,
isEnvironmentChanging,
draftId,
logicalProjectEnvironments,
sendInFlightRef,
getDraftSession,
setDraftThreadContext,
]);
// A change in flight belongs to the draft and project it started on.
const environmentChangeRef = useRef<{
readonly controller: AbortController;
readonly environmentId: EnvironmentId;
readonly scope: string;
} | null>(null);
const environmentChangeScopeRef = useRef("");
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the current change scope into a ref that async environment switches compare against
useLayoutEffect(() => {
environmentChangeScopeRef.current = environmentChangeScope;
});
// Leaving the scope, or unmounting, abandons a change still in flight.
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons an in-flight environment change when the draft or project scope changes or unmounts
useLayoutEffect(
() => () => {
if (environmentChangeRef.current?.scope === environmentChangeScope) {
environmentChangeRef.current.controller.abort();
environmentChangeRef.current = null;
}
},
[environmentChangeScope],
);
const readPendingEnvironmentChange = () => {
const pending = environmentChangeRef.current;
return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
};
const onAutoEnvironment = () => {
if (envLocked || !draftId || sendInFlightRef.current) return;
if (composerHasAttachments) {
Expand All @@ -246,6 +289,9 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
});
return;
}
environmentChangeRef.current?.controller.abort();
environmentChangeRef.current = null;
setBusyEnvironmentChange(null);
loadBalancing.refresh(
logicalProjectEnvironments.map((environment) => environment.environmentId),
);
Expand All @@ -267,39 +313,6 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
: gt("Auto balance")
: undefined;

// A change in flight belongs to the draft and project it started on.
const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
const environmentChangeRef = useRef<{
readonly environmentId: EnvironmentId;
readonly scope: string;
} | null>(null);
const environmentChangeScopeRef = useRef("");
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the current change scope into a ref that async environment switches compare against
useLayoutEffect(() => {
environmentChangeScopeRef.current = environmentChangeScope;
});
// Leaving the scope, or unmounting, abandons a change still in flight.
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons an in-flight environment change when the draft or project scope changes or unmounts
useLayoutEffect(
() => () => {
if (environmentChangeRef.current?.scope === environmentChangeScope) {
environmentChangeRef.current = null;
}
},
[environmentChangeScope],
);
const readPendingEnvironmentChange = () => {
const pending = environmentChangeRef.current;
return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
};
// The busy state belongs to the request that set it, so an older request settling late
// (abandoned, or superseded by a newer switch) can never clear a newer one's.
const [busyEnvironmentChange, setBusyEnvironmentChange] = useState<{
readonly environmentId: EnvironmentId;
readonly scope: string;
} | null>(null);
const isEnvironmentChanging = busyEnvironmentChange?.scope === environmentChangeScope;

const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
if (envLocked || !draftId || sendInFlightRef.current) return;
const originalDraft = getDraftSession(draftId);
Expand All @@ -308,11 +321,15 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
(env) => env.environmentId === nextEnvironmentId,
);
if (!target) return;
const request = { environmentId: target.environmentId, scope: environmentChangeScope };
environmentChangeRef.current?.controller.abort();
const request = {
controller: new AbortController(),
environmentId: target.environmentId,
scope: environmentChangeScope,
};
environmentChangeRef.current = request;
setBusyEnvironmentChange(null);
// `triagePrompt` is the prompt the target machine prepared for a triage draft.
const retarget = (project: (typeof allProjects)[number], triagePrompt?: string) => {
const readSwitchingDraft = () => {
const currentDraft = getDraftSession(draftId);
if (
environmentChangeRef.current !== request ||
Expand All @@ -323,19 +340,68 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
currentDraft.environmentId !== originalDraft.environmentId ||
currentDraft.projectId !== originalDraft.projectId
)
return null;
return currentDraft;
};
// `triagePrompt` is the prompt the target machine prepared for a triage draft.
const retarget = async (
project: (typeof allProjects)[number],
triagePrompt?: string,
): Promise<void> => {
const draft = readSwitchingDraft();
if (!draft) return;
const projectRef = scopeProjectRef(target.environmentId, project.id);
// Use the catalog-backed list: an unpaired machine can still have a cached project snapshot.
const findDestination = (projects: typeof allProjects) =>
projects.find(
(candidate) =>
candidate.environmentId === projectRef.environmentId &&
candidate.id === projectRef.projectId,
);
const workspaceRoot = findDestination(readProjects())?.workspaceRoot;
const controller = new AbortController();
const unsubscribe = subscribeProjects((projects) => {
if (findDestination(projects)?.workspaceRoot !== workspaceRoot) controller.abort();
});
const workspaceRead =
workspaceRoot === undefined
? Promise.resolve({})
: retargetDraftWorkspace(
draft,
projectRef,
AbortSignal.any([request.controller.signal, controller.signal]),
);
const defaultWorkspace = await workspaceRead.finally(unsubscribe);
const currentDraft = readSwitchingDraft();
if (!currentDraft) return;
const destination = findDestination(readProjects());
if (!destination) {
toastManager.add(
stackedThreadToast({
type: "error",
title: m(msg("Could not switch machine")),
description: m(msg("This project is no longer available.")),
}),
);
return;
}
if (controller.signal.aborted || destination.workspaceRoot !== workspaceRoot) {
return retarget(destination, triagePrompt);
}
const workspace =
currentDraft.workspaceExplicit || currentDraft.worktreePath !== null
? {}
: defaultWorkspace;
if (triagePrompt !== undefined) {
// Read now, so text typed while the machine prepared the session is kept.
const prompt = getComposerDraft(draftId)?.prompt ?? "";
const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt);
if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt);
}
carryFanoutSelections(currentDraft, target.environmentId);
const projectRef = scopeProjectRef(target.environmentId, project.id);
const workspace = retargetDraftWorkspace(currentDraft, projectRef);
if (activeProjectIsScratch) {
setLogicalProjectDraftThreadId(
deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings),
deriveLogicalProjectKeyFromSettings(destination, projectGroupingSettings),
projectRef,
draftId,
{ environmentSelection: "manual", loadBalancedEnvironmentId: null, ...workspace },
Expand All @@ -360,8 +426,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
);
// The playbook and context files exist only on the machine that prepared them.
const followsTriage = isTriagePrompt(getComposerDraft(draftId)?.prompt ?? "");
if (target.projectId !== null && !(knownProject && followsTriage)) {
if (knownProject) retarget(knownProject);
if (target.projectId !== null && !knownProject) {
finish();
return;
}
Expand Down Expand Up @@ -389,7 +454,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
const project =
knownProject ??
(await openScratchProject(target.environmentId, m(msg("Could not switch machine"))));
if (project) retarget(project, triagePrompt);
if (project) await retarget(project, triagePrompt);
};
setBusyEnvironmentChange(request);
void switchMachine().finally(finish);
Expand Down
Loading
Loading