From 370f6af00df43fa37b151c02695a724828538878 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 19:48:49 +0000 Subject: [PATCH 1/3] fix(web): dropped folders open on this computer's server when the desktop app's own environment is off useOpenLocalWorkspace only accepted the primary environment, which exists only when the desktop app runs its own backend. With that turned off and a separate t3 serve sharing the app's T3 home, folder drops and t3 activations were never ready. Use the same primary-else-host resolution themes already use. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/hooks/useDefaultTheme.ts | 8 +++--- apps/web/src/hooks/useOpenLocalWorkspace.ts | 28 +++++++++---------- apps/web/src/state/primaryEnvironment.test.ts | 16 +++++------ apps/web/src/state/primaryEnvironment.ts | 8 +++--- apps/web/src/state/server.ts | 4 +-- apps/web/src/themeBackground.test.ts | 2 +- apps/web/src/themeBackground.ts | 4 +-- 7 files changed, 35 insertions(+), 35 deletions(-) diff --git a/apps/web/src/hooks/useDefaultTheme.ts b/apps/web/src/hooks/useDefaultTheme.ts index c50ba78cb0111..0f13d75727a4e 100644 --- a/apps/web/src/hooks/useDefaultTheme.ts +++ b/apps/web/src/hooks/useDefaultTheme.ts @@ -1,5 +1,5 @@ import { appAtomRegistry } from "../rpc/atomRegistry"; -import { themeEnvironmentIdAtom } from "../state/primaryEnvironment"; +import { localEnvironmentIdAtom } from "../state/primaryEnvironment"; import { themeServerSettingsAtom } from "../state/server"; import { getThemeDefinition, singleAppearanceOf, subscribeToCustomThemes } from "../themePalette"; import { getThemeSnapshot, setAppearanceMode, setTheme } from "./useTheme"; @@ -58,7 +58,7 @@ function writeAppliedGeneration(storageKey: string, generation: string): void { function adoptDefaultTheme(): void { if (typeof window === "undefined") return; - const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + const environmentId = appAtomRegistry.get(localEnvironmentIdAtom); if (environmentId === null) return; const settings = appAtomRegistry.get(themeServerSettingsAtom); const { defaultTheme, defaultThemeSetAt } = settings; @@ -89,7 +89,7 @@ function adoptDefaultTheme(): void { /** Like the theme, the environment's mode applies once per set, then local choices win. */ function adoptDefaultAppearance(): void { if (typeof window === "undefined") return; - const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + const environmentId = appAtomRegistry.get(localEnvironmentIdAtom); const { defaultAppearance, defaultAppearanceSetAt } = appAtomRegistry.get(themeServerSettingsAtom); const storageKey = `${APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX}${environmentId}`; @@ -117,7 +117,7 @@ function adoptDefaults(): void { */ export function startDefaultThemeAdoption(): () => void { const unsubscribes = [ - appAtomRegistry.subscribe(themeEnvironmentIdAtom, adoptDefaults), + appAtomRegistry.subscribe(localEnvironmentIdAtom, adoptDefaults), appAtomRegistry.subscribe(themeServerSettingsAtom, adoptDefaults), subscribeToCustomThemes(adoptDefaults), ]; diff --git a/apps/web/src/hooks/useOpenLocalWorkspace.ts b/apps/web/src/hooks/useOpenLocalWorkspace.ts index 7f8c7999660d3..b6a34a91da6a1 100644 --- a/apps/web/src/hooks/useOpenLocalWorkspace.ts +++ b/apps/web/src/hooks/useOpenLocalWorkspace.ts @@ -3,6 +3,7 @@ import { findProjectByPath, inferProjectTitleFromPath, } from "@t3tools/client-runtime/state/projects"; +import { useAtomValue } from "@effect/atom-react"; import type { DesktopAppActivationRequest } from "@t3tools/contracts"; import { msg } from "gt-react"; @@ -10,7 +11,8 @@ import { handleDesktopAppActivationRequest } from "../desktopAppActivation"; import { m } from "../i18n/messages"; import { newProjectId } from "../lib/utils"; import { readProjects, waitForProject } from "../state/entities"; -import { usePrimaryEnvironment } from "../state/environments"; +import { useEnvironment } from "../state/environments"; +import { localEnvironmentIdAtom } from "../state/primaryEnvironment"; import { projectEnvironment } from "../state/projects"; import { useEnvironmentShellHasSnapshot } from "../state/shell"; import { useAtomCommand } from "../state/use-atom-command"; @@ -19,38 +21,36 @@ import { reportProjectFailure } from "./useProjectGroupUpdate"; import { useNewThreadHandler } from "./useHandleNewThread"; /** - * Opens a folder on this computer as a project in the primary environment: an + * Opens a folder on this computer as a project in this computer's environment: an * existing project opens (and unarchives), a new one is added. Used by `t3 ` - * activations and folders dropped on the sidebar. `ready` is false until the - * primary environment's projects have loaded, so a known folder is not added twice. + * activations and folders dropped on the sidebar. `ready` is false until that + * environment's projects have loaded, so a known folder is not added twice. */ export function useOpenLocalWorkspace() { - const primaryEnvironment = usePrimaryEnvironment(); + const localEnvironment = useEnvironment(useAtomValue(localEnvironmentIdAtom)); const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const updateProject = useOrchestrationCommand(projectEnvironment.update, { label: "project unarchive", }); const openThread = useNewThreadHandler(); - const shellHasSnapshot = useEnvironmentShellHasSnapshot( - primaryEnvironment?.environmentId ?? null, - ); + const shellHasSnapshot = useEnvironmentShellHasSnapshot(localEnvironment?.environmentId ?? null); const ready = - primaryEnvironment?.connection.phase === "connected" && - primaryEnvironment.serverConfig !== null && + localEnvironment?.connection.phase === "connected" && + localEnvironment.serverConfig !== null && shellHasSnapshot; const open = (request: DesktopAppActivationRequest) => handleDesktopAppActivationRequest(request, { getTarget: () => { if ( - primaryEnvironment?.connection.phase !== "connected" || - primaryEnvironment.serverConfig === null + localEnvironment?.connection.phase !== "connected" || + localEnvironment.serverConfig === null ) { return null; } return { - environmentId: primaryEnvironment.environmentId, - platform: primaryEnvironment.serverConfig.environment.platform.os, + environmentId: localEnvironment.environmentId, + platform: localEnvironment.serverConfig.environment.platform.os, }; }, findProject: (environmentId, workspaceRoot) => diff --git a/apps/web/src/state/primaryEnvironment.test.ts b/apps/web/src/state/primaryEnvironment.test.ts index 4fbb52aed6cd6..aad415d94e2f4 100644 --- a/apps/web/src/state/primaryEnvironment.test.ts +++ b/apps/web/src/state/primaryEnvironment.test.ts @@ -8,18 +8,18 @@ import { EnvironmentId } from "@t3tools/contracts"; import { Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; -import { createThemeEnvironmentIdAtom } from "./primaryEnvironment"; +import { createLocalEnvironmentIdAtom } from "./primaryEnvironment"; const PRIMARY = EnvironmentId.make("primary"); const SERVICE = EnvironmentId.make("service"); const REMOTE = EnvironmentId.make("remote"); -function themeEnvironmentId(input: { +function localEnvironmentId(input: { primary: EnvironmentId | null; host: string | null; catalog: ReadonlyArray; }) { - const atom = createThemeEnvironmentIdAtom({ + const atom = createLocalEnvironmentIdAtom({ primaryEnvironmentIdAtom: Atom.make(input.primary), hostEnvironmentIdAtom: Atom.make(input.host), catalogValueAtom: Atom.make({ entries: new Map(input.catalog.map((id) => [id, null])) }), @@ -27,22 +27,22 @@ function themeEnvironmentId(input: { return AtomRegistry.make().get(atom); } -describe("themeEnvironmentIdAtom", () => { +describe("localEnvironmentIdAtom", () => { it("prefers the primary environment over this machine's background service", () => { expect( - themeEnvironmentId({ primary: PRIMARY, host: "service", catalog: [PRIMARY, SERVICE] }), + localEnvironmentId({ primary: PRIMARY, host: "service", catalog: [PRIMARY, SERVICE] }), ).toBe(PRIMARY); }); it("uses the connected background service sharing the app's T3 home when there is no primary", () => { - expect(themeEnvironmentId({ primary: null, host: "service", catalog: [REMOTE, SERVICE] })).toBe( + expect(localEnvironmentId({ primary: null, host: "service", catalog: [REMOTE, SERVICE] })).toBe( SERVICE, ); }); it("uses no environment when that service is not among the connections", () => { - expect(themeEnvironmentId({ primary: null, host: "service", catalog: [REMOTE] })).toBeNull(); - expect(themeEnvironmentId({ primary: null, host: null, catalog: [REMOTE] })).toBeNull(); + expect(localEnvironmentId({ primary: null, host: "service", catalog: [REMOTE] })).toBeNull(); + expect(localEnvironmentId({ primary: null, host: null, catalog: [REMOTE] })).toBeNull(); }); }); diff --git a/apps/web/src/state/primaryEnvironment.ts b/apps/web/src/state/primaryEnvironment.ts index 51264adb7c5e7..3271cf9140a54 100644 --- a/apps/web/src/state/primaryEnvironment.ts +++ b/apps/web/src/state/primaryEnvironment.ts @@ -18,8 +18,8 @@ export const hostEnvironmentIdAtom = Atom.make(null).pipe( Atom.withLabel("web-host-environment-id"), ); -// Without a primary, only the service sharing the desktop app's T3 home supplies themes. -export function createThemeEnvironmentIdAtom(input: { +// This computer's environment: the primary, else a connection to the service sharing the app's T3 home. +export function createLocalEnvironmentIdAtom(input: { readonly primaryEnvironmentIdAtom: Atom.Atom; readonly hostEnvironmentIdAtom: Atom.Atom; readonly catalogValueAtom: Atom.Atom<{ readonly entries: ReadonlyMap }>; @@ -32,10 +32,10 @@ export function createThemeEnvironmentIdAtom(input: { if (environmentId === hostEnvironmentId) return environmentId; } return null; - }).pipe(Atom.withLabel("web-theme-environment-id")); + }).pipe(Atom.withLabel("web-local-environment-id")); } -export const themeEnvironmentIdAtom = createThemeEnvironmentIdAtom({ +export const localEnvironmentIdAtom = createLocalEnvironmentIdAtom({ primaryEnvironmentIdAtom, hostEnvironmentIdAtom, catalogValueAtom: environmentCatalog.catalogValueAtom, diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.ts index 6e2a71baf53e4..eae8aaa9f0eea 100644 --- a/apps/web/src/state/server.ts +++ b/apps/web/src/state/server.ts @@ -25,7 +25,7 @@ import { isConnectedWithConfig } from "../components/settings/scopedSettings"; import { environmentCatalog } from "../connection/catalog"; import { connectionAtomRuntime } from "../connection/runtime"; import { environmentAtomList } from "./environmentAtomList"; -import { primaryEnvironmentIdAtom, themeEnvironmentIdAtom } from "./primaryEnvironment"; +import { primaryEnvironmentIdAtom, localEnvironmentIdAtom } from "./primaryEnvironment"; import { environmentSession } from "./session"; import { reuseProvidersIgnoringCheckedAt } from "./serverProviders.logic"; @@ -167,7 +167,7 @@ export const primaryServerKeybindingsAtom = createShortcutKeybindingsAtom({ const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray = []; const themeServerConfigAtom = Atom.make((get): ServerConfig | null => { - const environmentId = get(themeEnvironmentIdAtom); + const environmentId = get(localEnvironmentIdAtom); return environmentId === null ? null : get(serverEnvironment.configValueAtom(environmentId)); }).pipe(Atom.withLabel("web-theme-server-config")); diff --git a/apps/web/src/themeBackground.test.ts b/apps/web/src/themeBackground.test.ts index 589b2d411f5d9..33d2a3dc4de8d 100644 --- a/apps/web/src/themeBackground.test.ts +++ b/apps/web/src/themeBackground.test.ts @@ -11,7 +11,7 @@ vi.mock( ); vi.mock(import("./state/primaryEnvironment"), async () => { const { Atom } = await import("effect/reactivity"); - return { themeEnvironmentIdAtom: Atom.make(EnvironmentId.make("host")) } as never; + return { localEnvironmentIdAtom: Atom.make(EnvironmentId.make("host")) } as never; }); vi.mock(import("./state/server"), async () => { const { Atom } = await import("effect/reactivity"); diff --git a/apps/web/src/themeBackground.ts b/apps/web/src/themeBackground.ts index 2eec19b5a98b5..22f5f8f1d34fe 100644 --- a/apps/web/src/themeBackground.ts +++ b/apps/web/src/themeBackground.ts @@ -4,7 +4,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry"; import { assetEnvironment } from "./state/assets"; -import { themeEnvironmentIdAtom } from "./state/primaryEnvironment"; +import { localEnvironmentIdAtom } from "./state/primaryEnvironment"; import { themeServerEnvironmentThemesAtom } from "./state/server"; import { environmentSession } from "./state/session"; import { getCustomThemes } from "./themePalette"; @@ -58,7 +58,7 @@ async function loadBackground( export function applyThemeBackground(themeId: string | undefined): void { if (typeof document === "undefined") return; appliedThemeId = themeId; - const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + const environmentId = appAtomRegistry.get(localEnvironmentIdAtom); // A saved theme wins its id over a published one, so the published image is not its. const revision = themeId === undefined || getCustomThemes().some((theme) => theme.id === themeId) From 5423301a7bbd19f2c8ffa58849e2f2a198188874 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 20:55:41 +0000 Subject: [PATCH 2/3] fix(desktop): t3 and first folder drops work with Local environment off With the local environment turned off, the desktop app never started its control socket and never mounted the activation coordinator, so t3 could not reach the app. Start the socket on that path too and mount the coordinator like the web-link one. The first folder dropped on an empty home also raced home's own draft for the new project and reported a failure; it now retries into that draft. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app/DesktopApp.test.ts | 103 +++++++++++--------- apps/desktop/src/app/DesktopApp.ts | 11 ++- apps/web/src/hooks/useOpenLocalWorkspace.ts | 5 +- apps/web/src/routes/__root.tsx | 6 +- 4 files changed, 71 insertions(+), 54 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index 9cc3a187e83f3..8faaee8f41f18 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -84,6 +84,7 @@ interface StubbedDesktop { readonly backends?: ReadonlyArray<{ readonly stop: () => Effect.Effect }>; readonly flushRendererHistory?: Effect.Effect; readonly tokenRequested?: Deferred.Deferred; + readonly activationStarted?: Deferred.Deferred; } const runStubbedDesktop = (stub: StubbedDesktop) => @@ -189,7 +190,9 @@ const runStubbedDesktop = (stub: StubbedDesktop) => reconcile: Effect.void, } as DesktopWslBackend.DesktopWslBackend["Service"]), Effect.provideService(DesktopAppActivation.DesktopAppActivation, { - start: Effect.void, + start: stub.activationStarted + ? Deferred.succeed(stub.activationStarted, undefined) + : Effect.void, } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { shutdown: stub.flushRendererHistory ?? Effect.void, @@ -323,52 +326,60 @@ it.effect.each([false, true])( }).pipe(Effect.provide(DesktopShutdown.layer)), ); -it.effect("points a stale t3 launcher at the updated AppImage with Local environment off", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); - const launcher = DesktopCliShim.launcherPath({ - path, - baseDir, - platform: "linux", - } as DesktopEnvironment.DesktopEnvironment["Service"]); - const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); - const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); - yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); - yield* fs.writeFileString( - launcher, - DesktopCliShim.renderCliShim({ - target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, - shimPath: launcher, - t3Home: baseDir, - }), - ); - yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); - const windowStarted = yield* Deferred.make(); - - const app = yield* runStubbedDesktop({ - localEnvironmentEnabled: false, - environment: { +it.effect( + "points a stale t3 launcher at the updated AppImage and accepts t3 with Local environment off", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); + const launcher = DesktopCliShim.launcherPath({ path, baseDir, - serverRoot: path.join(baseDir, "resources", "app.asar"), - appImagePath: Option.some(updatedAppImage), - }, - fileSystem: Layer.succeed(FileSystem.FileSystem, fs), - record: () => Effect.void, - windowStarted, - registerLinuxUrlHandler: Effect.void, - }); - yield* Deferred.await(windowStarted); - yield* (yield* DesktopShutdown.DesktopShutdown).request; - yield* Fiber.join(app); + platform: "linux", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); + const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString( + launcher, + DesktopCliShim.renderCliShim({ + target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, + shimPath: launcher, + t3Home: baseDir, + }), + ); + yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); + const windowStarted = yield* Deferred.make(); + const activationStarted = yield* Deferred.make(); - const content = yield* fs.readFileString(launcher); - assert.include( - content, - `app='${updatedAppImage}'`, - "startup left the t3 launcher pointing at the removed AppImage", - ); - }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: false, + activationStarted, + environment: { + path, + baseDir, + serverRoot: path.join(baseDir, "resources", "app.asar"), + appImagePath: Option.some(updatedAppImage), + }, + fileSystem: Layer.succeed(FileSystem.FileSystem, fs), + record: () => Effect.void, + windowStarted, + registerLinuxUrlHandler: Effect.void, + }); + yield* Deferred.await(windowStarted); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + + const content = yield* fs.readFileString(launcher); + assert.include( + content, + `app='${updatedAppImage}'`, + "startup left the t3 launcher pointing at the removed AppImage", + ); + assert.isTrue( + yield* Deferred.isDone(activationStarted), + "startup left the t3 control socket closed", + ); + }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), ); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 34476ee7855b5..0ccce648bba61 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -285,6 +285,10 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool const snapShot = yield* DesktopSnapShot.DesktopSnapShot; const appActivation = yield* DesktopAppActivation.DesktopAppActivation; const settings = yield* desktopSettings.get; + const startAppActivation = appActivation.start.pipe( + Effect.tap(() => logBootstrapInfo("desktop app control socket ready")), + Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })), + ); if (settings.localEnvironmentEnabled && (!backendStarted || (yield* Ref.get(state.quitting)))) { return; } @@ -309,6 +313,8 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool if (!(yield* Ref.get(state.quitting))) { yield* desktopWindow.createMainIfBackendReady; } + // `t3 ` still reaches the renderer, which opens it on this machine's connected service. + yield* startAppActivation; return; } @@ -321,10 +327,7 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool ) { yield* desktopWindow.ensureMain; } - yield* appActivation.start.pipe( - Effect.tap(() => logBootstrapInfo("desktop app control socket ready")), - Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })), - ); + yield* startAppActivation; yield* Effect.forkScoped((yield* DesktopWslBackend.DesktopWslBackend).reconcile); }); diff --git a/apps/web/src/hooks/useOpenLocalWorkspace.ts b/apps/web/src/hooks/useOpenLocalWorkspace.ts index b6a34a91da6a1..d27465ab2267b 100644 --- a/apps/web/src/hooks/useOpenLocalWorkspace.ts +++ b/apps/web/src/hooks/useOpenLocalWorkspace.ts @@ -81,7 +81,7 @@ export function useOpenLocalWorkspace() { waitForProject: async (projectRef) => { await waitForProject(projectRef); }, - openThread: (projectRef) => { + openThread: async (projectRef) => { const project = readProjects().find( (candidate) => candidate.environmentId === projectRef.environmentId && @@ -94,7 +94,8 @@ export function useOpenLocalWorkspace() { input: { projectId: projectRef.projectId, archived: false }, }).then((result) => reportProjectFailure(m(msg("Failed to unarchive project")), result)); } - return openThread(projectRef); + // Home opens a draft in the first project on its own; when it wins the race, ours retries into it. + return (await openThread(projectRef)) ?? openThread(projectRef); }, }); diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 21a981ef00a76..3cbef77306c8e 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -186,9 +186,11 @@ function RootRouteBranch() { // first-run gate and the event router, whose first navigation would leave the page. const appHosts = ( <> - {primaryEnvironmentAuthenticated ? : null} {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? ( - + <> + + + ) : null} {isElectron ? : null} From aa90d0bd29fcd3d1509678e8f2ef56a52f62957d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 21:55:11 +0000 Subject: [PATCH 3/3] fix(web): a new-thread request that lost a race to the same project's draft resolves to it Drops on an empty home raced home's own first-project draft; the losing request saw the route change and reported failure. Replace the hook-level retry, which also pulled users back after they navigated elsewhere, with a check in the shared handler: an abandoned request resolves to this project's draft only when that draft is already where the router went. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/hooks/useHandleNewThread.test.ts | 31 +++++++++++++++++++ apps/web/src/hooks/useHandleNewThread.ts | 19 ++++++++++-- apps/web/src/hooks/useOpenLocalWorkspace.ts | 5 ++- 3 files changed, 50 insertions(+), 5 deletions(-) diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts index 6f318bce409ce..7c64d0077cc2b 100644 --- a/apps/web/src/hooks/useHandleNewThread.test.ts +++ b/apps/web/src/hooks/useHandleNewThread.test.ts @@ -28,6 +28,9 @@ const testState = vi.hoisted(() => { navigate: vi.fn(async (request: { readonly params: { readonly draftId: string } }) => { router.state.location.href = `/draft/${request.params.draftId}`; }), + buildLocation: (request: { readonly params: { readonly draftId: string } }) => ({ + href: `/draft/${request.params.draftId}`, + }), }; const draftStore = { getComposerDraft: vi.fn((draftId: string) => ({ draftId })), @@ -78,6 +81,9 @@ const testState = vi.hoisted(() => { get openDraftRoute() { return openDraftRoute; }, + registerDraft(draft: NonNullable) { + storedDraft = draft; + }, openEmptyDraft(draftId: string) { openDraftRoute = { kind: "draft", draftId }; }, @@ -282,6 +288,31 @@ describe.each([ expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); }); + it("resolves to the draft another opener showed for the same project meanwhile", async () => { + testState.reset(draft); + const pendingOpen = useNewThreadHandler()( + { environmentId: "environment-ssh", projectId: "project-remote" } as never, + { replace: true }, + ); + + // The location moves before the route matches do. + testState.registerDraft({ + draftId: "draft-home", + environmentId: "environment-ssh", + promotedTo: null, + threadId: "thread-home", + }); + testState.router.state.location.href = "/draft/draft-home"; + testState.completeProjectFileRead(null); + + await expect(pendingOpen).resolves.toEqual({ + draftId: "draft-home", + threadId: "thread-home", + }); + expect(testState.router.navigate).not.toHaveBeenCalled(); + expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); + }); + it("sets the prompt before the draft shows", async () => { testState.reset(draft); const pendingOpen = useNewThreadHandler()( diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 9fae0319539b4..49e8812628b1b 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -233,6 +233,21 @@ export function createNewThreadHandler(router: AnyRouter) { const logicalProjectKey = project ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings) : scopedProjectKey(projectRef); + // Another opener (home's own first-project draft) may have reached this project's draft first. + // Matches lag the location during a navigation, so compare against the location. + const resultIfAbandoned = () => { + const draft = getDraftSessionByLogicalProjectKey(logicalProjectKey); + if (draft === null || draft.promotedTo != null || readProject(projectRef) === null) { + return null; + } + const draftHref = router.buildLocation({ + to: "/draft/$draftId", + params: { draftId: draft.draftId }, + }).href; + return router.state.location.href === draftHref + ? { draftId: draft.draftId, threadId: draft.threadId } + : null; + }; const hasBranchOption = options?.branch !== undefined; const hasWorktreePathOption = options?.worktreePath !== undefined; const hasEnvModeOption = options?.envMode !== undefined; @@ -274,7 +289,7 @@ export function createNewThreadHandler(router: AnyRouter) { } else if (!isDraftAlreadyOpen) { const defaultEnvMode = await resolveDefaultEnvMode(); if (abandonedSinceRequest()) { - return null; + return resultIfAbandoned(); } // Concurrent calls may change the draft; stale resets, remaps, or navigation could clobber it. const routeTargetNow = getCurrentRouteTarget(); @@ -390,7 +405,7 @@ export function createNewThreadHandler(router: AnyRouter) { return (async () => { const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode()); if (abandonedSinceRequest()) { - return null; + return resultIfAbandoned(); } // Reuse drafts registered while awaiting so their pending navigation cannot lose them. const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey); diff --git a/apps/web/src/hooks/useOpenLocalWorkspace.ts b/apps/web/src/hooks/useOpenLocalWorkspace.ts index d27465ab2267b..b6a34a91da6a1 100644 --- a/apps/web/src/hooks/useOpenLocalWorkspace.ts +++ b/apps/web/src/hooks/useOpenLocalWorkspace.ts @@ -81,7 +81,7 @@ export function useOpenLocalWorkspace() { waitForProject: async (projectRef) => { await waitForProject(projectRef); }, - openThread: async (projectRef) => { + openThread: (projectRef) => { const project = readProjects().find( (candidate) => candidate.environmentId === projectRef.environmentId && @@ -94,8 +94,7 @@ export function useOpenLocalWorkspace() { input: { projectId: projectRef.projectId, archived: false }, }).then((result) => reportProjectFailure(m(msg("Failed to unarchive project")), result)); } - // Home opens a draft in the first project on its own; when it wins the race, ours retries into it. - return (await openThread(projectRef)) ?? openThread(projectRef); + return openThread(projectRef); }, });