From d60e9a9e1dbadbce2731f3de12c8a53e73aaec9a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:34:33 +0100 Subject: [PATCH 01/10] test(web): reproduce workspace default on first machine switch Co-authored-by: GPT 6.2 Sol --- ...hine-switch-reads-workspace-default.e2e.ts | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 scripts/scenarios/machine-switch-reads-workspace-default.e2e.ts diff --git a/scripts/scenarios/machine-switch-reads-workspace-default.e2e.ts b/scripts/scenarios/machine-switch-reads-workspace-default.e2e.ts new file mode 100644 index 0000000000000..7ff6f6a520cbc --- /dev/null +++ b/scripts/scenarios/machine-switch-reads-workspace-default.e2e.ts @@ -0,0 +1,58 @@ +import { expect } from "e2e"; + +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { run } from "./shell.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "The first switch to another machine uses that checkout's project file workspace default", + WEB, + async ({ t3, app, screen, browser }) => { + const repository = { + ".git/config": '[remote "origin"]\n\turl = https://github.com/scenario/demo.git\n', + }; + await t3.project("demo", repository); + const second = makeState(SECOND_HOME); + const server = startSecondServer(app.baseUrl ?? ""); + try { + const { host, token } = await server.ready; + const remoteProject = await second.state.project("demo", { + ...repository, + "t3.json": JSON.stringify({ defaultThreadEnvMode: "worktree" }), + }); + await runPromise(run("git", ["branch", "-m", "remote-base"], { cwd: remoteProject })); + + await t3.open(); + const workspace = screen.getByRole("combobox", "Workspace", { exact: true }); + await workspace.getByText("Current checkout").waitFor(); + await screen.getByRole("combobox", "Branch: main", { exact: true }).first().waitFor(); + await screen.getByRole("textbox").fill("Plan the next change"); + const draftPath = new URL(await browser.url()).pathname; + + await app.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 screen.getByRole("button", "List", { exact: true }).tap(); + await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60_000 }); + await app.open(draftPath); + + const runOn = screen.getByRole("combobox", "Run on", { exact: true }); + await runOn.tap(); + // Both servers use the scenario label. The primary machine is listed first. + const remote = screen.getByRole("option", "Scenario", { exact: true }).nth(1); + await remote.tap(); + await screen + .getByRole("combobox", /^Branch: (From )?remote-base/) + .first() + .waitFor(); + + await app.screenshot("workspace-after-first-machine-switch"); + await expect(workspace).toHaveText("New worktree"); + } finally { + await server.stop(); + } + }, +); From ffe56be0244e131da2acdee7fa6afd6eff077366 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:36:30 +0100 Subject: [PATCH 02/10] fix(web): use the destination workspace default when switching machines Co-authored-by: GPT 6.2 Sol --- .../chat/useDraftEnvironmentRouting.ts | 104 +++++++++++------- apps/web/src/lib/retargetDraftWorkspace.ts | 41 +++++-- 2 files changed, 91 insertions(+), 54 deletions(-) diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts index 278ba7529a96a..77c12e3214741 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts @@ -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, ); @@ -225,12 +241,37 @@ 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 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; + }; const onAutoEnvironment = () => { if (envLocked || !draftId || sendInFlightRef.current) return; if (composerHasAttachments) { @@ -246,6 +287,8 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) }); return; } + environmentChangeRef.current = null; + setBusyEnvironmentChange(null); loadBalancing.refresh( logicalProjectEnvironments.map((environment) => environment.environmentId), ); @@ -267,39 +310,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); @@ -311,8 +321,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) const request = { 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 || @@ -323,7 +332,21 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) currentDraft.environmentId !== originalDraft.environmentId || currentDraft.projectId !== originalDraft.projectId ) - return; + 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) => { + const draft = readSwitchingDraft(); + if (!draft) return; + const projectRef = scopeProjectRef(target.environmentId, project.id); + const defaultWorkspace = await retargetDraftWorkspace(draft, projectRef); + const currentDraft = readSwitchingDraft(); + if (!currentDraft) return; + 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 ?? ""; @@ -331,8 +354,6 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) 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), @@ -360,8 +381,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; } @@ -389,7 +409,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); diff --git a/apps/web/src/lib/retargetDraftWorkspace.ts b/apps/web/src/lib/retargetDraftWorkspace.ts index c91aebfb954d9..ee7c6271b3b32 100644 --- a/apps/web/src/lib/retargetDraftWorkspace.ts +++ b/apps/web/src/lib/retargetDraftWorkspace.ts @@ -1,4 +1,8 @@ -import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef } from "@t3tools/contracts"; +import { + DEFAULT_SERVER_SETTINGS, + type ScopedProjectRef, + type T3ProjectFile, +} from "@t3tools/contracts"; import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings"; import type { DraftSessionState } from "../composerDraftStore"; @@ -8,22 +12,35 @@ import { readEnvironment } from "../state/environments"; import { readUnloadedThreadCount } from "../state/olderSettledShelf"; import { environmentSummaries } from "../state/presentation"; import { resolveNewDraftStartFromOrigin } from "./chatThreadActions"; -import { peekT3ProjectFile } from "./t3ProjectFileDefaults"; +import { peekT3ProjectFile, readT3ProjectFile } from "./t3ProjectFileDefaults"; -function newThreadWorkspace(projectRef: ScopedProjectRef) { +function readWorkspaceContext(projectRef: ScopedProjectRef) { const project = readProject(projectRef); const serverConfig = readEnvironment(projectRef.environmentId)?.serverConfig; - const settings = serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS; - const consultProjectFile = - project !== null && + return { project, serverConfig, settings: serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS }; +} + +async function newThreadWorkspace(projectRef: ScopedProjectRef) { + let { project, serverConfig, settings } = readWorkspaceContext(projectRef); + let projectFile: T3ProjectFile | null = null; + const workspaceRoot = project?.workspaceRoot; + if ( + workspaceRoot && resolveProjectSettings(settings, projectRef.projectId, project).settings .defaultThreadEnvMode === null && appAtomRegistry .get(environmentSummaries.connectedEnvironmentIdsAtom) - .includes(projectRef.environmentId); - const projectFile = consultProjectFile - ? (peekT3ProjectFile(projectRef.environmentId, project.workspaceRoot) ?? null) - : null; + .includes(projectRef.environmentId) + ) { + const cached = peekT3ProjectFile(projectRef.environmentId, workspaceRoot); + if (cached === undefined) { + const loaded = await readT3ProjectFile(projectRef.environmentId, workspaceRoot); + ({ project, serverConfig, settings } = readWorkspaceContext(projectRef)); + if (project?.workspaceRoot === workspaceRoot) projectFile = loaded; + } else { + projectFile = cached; + } + } const projectSettings = resolveProjectSettings( settings, projectRef.projectId, @@ -58,10 +75,10 @@ function newThreadWorkspace(projectRef: ScopedProjectRef) { * The workspace for a draft moving to another project or machine: the default a new thread * there starts with, unless the user chose one, which carries over. */ -export function retargetDraftWorkspace( +export async function retargetDraftWorkspace( draft: Pick, projectRef: ScopedProjectRef, -): { envMode?: DraftSessionState["envMode"]; startFromOrigin?: boolean } { +): Promise<{ envMode?: DraftSessionState["envMode"]; startFromOrigin?: boolean }> { return draft.workspaceExplicit || draft.worktreePath !== null ? {} : newThreadWorkspace(projectRef); From 54a944b19fbfcd06b7ec734e542efad1d68b8bb9 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:18:22 +0100 Subject: [PATCH 03/10] fix(web): recheck destination projects before switching drafts Co-authored-by: GPT 6.2 Sol --- ...seDraftEnvironmentRouting.browser.test.tsx | 60 ++++++++++++++++++- .../chat/useDraftEnvironmentRouting.ts | 24 +++++++- 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx index c8b0632be428f..69321d5c6731d 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx @@ -3,7 +3,7 @@ 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"; -import type { ServerProvider } from "@t3tools/contracts"; +import type { ServerProvider, T3ProjectFile } from "@t3tools/contracts"; import { scopedThreadKey, scopeProjectRef, @@ -17,16 +17,20 @@ import { ProviderDriverKind, ProviderInstanceId, } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; 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, AppAtomRegistryProvider } from "../../rpc/atomRegistry"; +import { environmentSummaries } from "../../state/presentation"; import { draftFanoutSelectionsAtom } from "./chatViewSend"; const resources = vi.hoisted(() => ({ projects: [] as EnvironmentProject[], + readProjectFile: + vi.fn<(environmentId: EnvironmentId, root: string) => Promise>(), pickedEnvironmentId: null as EnvironmentId | null, refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise>(), })); @@ -49,8 +53,24 @@ vi.mock("../../state/entities", () => ({ })); vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) })); +vi.mock("../../lib/t3ProjectFileDefaults", () => ({ + peekT3ProjectFile: () => undefined, + readT3ProjectFile: resources.readProjectFile, +})); +vi.mock(import("../../state/presentation"), async (original) => { + const actual = await original(); + return { + ...actual, + environmentSummaries: { + ...actual.environmentSummaries, + connectedEnvironmentIdsAtom: Atom.make([]), + }, + }; +}); + function setup() { resources.refreshSelection.mockReset(); + resources.readProjectFile.mockReset(); resources.projects = []; resources.pickedEnvironmentId = null; const a = EnvironmentId.make("machine-a"); @@ -165,6 +185,7 @@ function RoutingProbe({ input, onPrepared }: HarnessProps) { ))} {draft?.environmentId} ))} {draft?.environmentId} +