diff --git a/apps/web/src/environments/primary/bootstrap.test.ts b/apps/web/src/environments/primary/bootstrap.test.ts index dae6d28925..353c151b91 100644 --- a/apps/web/src/environments/primary/bootstrap.test.ts +++ b/apps/web/src/environments/primary/bootstrap.test.ts @@ -110,6 +110,32 @@ describe("environmentBootstrap", () => { expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment"); }); + it("derives the websocket url when only VITE_HTTP_URL is configured", async () => { + const fetchMock = vi.fn().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT)); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com"); + + await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT); + expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment"); + expect(getPrimaryKnownEnvironment()?.target).toEqual({ + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + }); + }); + + it("derives the http url when only VITE_WS_URL is configured", async () => { + const fetchMock = vi.fn().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT)); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("VITE_WS_URL", "wss://remote.example.com"); + + await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT); + expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment"); + expect(getPrimaryKnownEnvironment()?.target).toEqual({ + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + }); + }); + it("uses the current origin as the descriptor base for local dev environments", async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT)); vi.stubGlobal("fetch", fetchMock); diff --git a/apps/web/src/environments/primary/target.ts b/apps/web/src/environments/primary/target.ts index 3c0090b792..04b7d903d4 100644 --- a/apps/web/src/environments/primary/target.ts +++ b/apps/web/src/environments/primary/target.ts @@ -16,6 +16,15 @@ function normalizeBaseUrl(rawValue: string): string { return new URL(rawValue, window.location.origin).toString(); } +function swapBaseUrlProtocol( + rawValue: string, + nextProtocol: "http:" | "https:" | "ws:" | "wss:", +): string { + const url = new URL(normalizeBaseUrl(rawValue)); + url.protocol = nextProtocol; + return url.toString(); +} + function normalizeHostname(hostname: string): string { return hostname .trim() @@ -54,22 +63,29 @@ function resolveHttpRequestBaseUrl(httpBaseUrl: string): string { } function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null { - const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim(); - const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim(); + const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined; + const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined; if (!configuredHttpBaseUrl && !configuredWsBaseUrl) { return null; } - if (!configuredHttpBaseUrl || !configuredWsBaseUrl) { - throw new Error("Configured primary environments require both VITE_HTTP_URL and VITE_WS_URL."); - } + const resolvedHttpBaseUrl = + configuredHttpBaseUrl ?? + (configuredWsBaseUrl?.startsWith("wss:") + ? swapBaseUrlProtocol(configuredWsBaseUrl, "https:") + : swapBaseUrlProtocol(configuredWsBaseUrl!, "http:")); + const resolvedWsBaseUrl = + configuredWsBaseUrl ?? + (configuredHttpBaseUrl?.startsWith("https:") + ? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:") + : swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:")); return { source: "configured", target: { - httpBaseUrl: normalizeBaseUrl(configuredHttpBaseUrl), - wsBaseUrl: normalizeBaseUrl(configuredWsBaseUrl), + httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl), + wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl), }, }; } diff --git a/apps/web/src/environments/runtime/catalog.test.ts b/apps/web/src/environments/runtime/catalog.test.ts index abc851775b..2f6325ed75 100644 --- a/apps/web/src/environments/runtime/catalog.test.ts +++ b/apps/web/src/environments/runtime/catalog.test.ts @@ -1,4 +1,4 @@ -import { EnvironmentId, type LocalApi } from "@t3tools/contracts"; +import { EnvironmentId, type LocalApi, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { @@ -6,6 +6,7 @@ import { resetSavedEnvironmentRuntimeStoreForTests, useSavedEnvironmentRegistryStore, useSavedEnvironmentRuntimeStore, + waitForSavedEnvironmentRegistryHydration, } from "./catalog"; describe("environment runtime catalog stores", () => { @@ -88,4 +89,49 @@ describe("environment runtime catalog stores", () => { expect(errorSpy).toHaveBeenCalledWith("[SAVED_ENVIRONMENTS] persist failed", expect.any(Error)); }); + + it("does not let stale hydration overwrite records added while hydration is in flight", async () => { + let resolveRegistryRead: () => void = () => { + throw new Error("Registry read resolver was not initialized."); + }; + + vi.stubGlobal("window", { + nativeApi: { + persistence: { + getClientSettings: async () => null, + setClientSettings: async () => undefined, + getSavedEnvironmentRegistry: () => + new Promise((resolve) => { + resolveRegistryRead = () => resolve([]); + }), + setSavedEnvironmentRegistry: async () => undefined, + getSavedEnvironmentSecret: async () => null, + setSavedEnvironmentSecret: async () => true, + removeSavedEnvironmentSecret: async () => undefined, + }, + } satisfies Pick, + }); + + const { __resetLocalApiForTests } = await import("../../localApi"); + await __resetLocalApiForTests(); + + const hydrationPromise = waitForSavedEnvironmentRegistryHydration(); + + const environmentId = EnvironmentId.makeUnsafe("environment-1"); + const record = { + environmentId, + label: "Remote environment", + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + createdAt: "2026-04-09T00:00:00.000Z", + lastConnectedAt: null, + } as const; + + useSavedEnvironmentRegistryStore.getState().upsert(record); + + resolveRegistryRead(); + await hydrationPromise; + + expect(useSavedEnvironmentRegistryStore.getState().byId[environmentId]).toEqual(record); + }); }); diff --git a/apps/web/src/environments/runtime/catalog.ts b/apps/web/src/environments/runtime/catalog.ts index d85cbb135c..6aecf80f80 100644 --- a/apps/web/src/environments/runtime/catalog.ts +++ b/apps/web/src/environments/runtime/catalog.ts @@ -74,8 +74,13 @@ function persistSavedEnvironmentRegistryState( function replaceSavedEnvironmentRegistryState( records: ReadonlyArray, ): void { + const currentById = useSavedEnvironmentRegistryStore.getState().byId; + const hydratedById = Object.fromEntries(records.map((record) => [record.environmentId, record])); useSavedEnvironmentRegistryStore.setState({ - byId: Object.fromEntries(records.map((record) => [record.environmentId, record])), + byId: { + ...hydratedById, + ...currentById, + }, }); } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 7c123b4fed..01b5076695 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -7,6 +7,7 @@ import pkg from "./package.json" with { type: "json" }; const port = Number(process.env.PORT ?? 5733); const host = process.env.HOST?.trim() || "localhost"; +const configuredHttpUrl = process.env.VITE_HTTP_URL?.trim(); const configuredWsUrl = process.env.VITE_WS_URL?.trim(); const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase(); @@ -58,6 +59,7 @@ export default defineConfig({ include: ["@pierre/diffs", "@pierre/diffs/react", "@pierre/diffs/worker/worker.js"], }, define: { + "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""), // In dev mode, tell the web app where the WebSocket server lives "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""), "import.meta.env.APP_VERSION": JSON.stringify(pkg.version), diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.ts index fc4a7b5733..0918e6986a 100644 --- a/scripts/dev-runner.test.ts +++ b/scripts/dev-runner.test.ts @@ -84,6 +84,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => { assert.equal(env.T3CODE_HOME, resolve("/tmp/custom-t3")); assert.equal(env.T3CODE_PORT, "4222"); + assert.equal(env.VITE_HTTP_URL, "http://localhost:4222"); assert.equal(env.VITE_WS_URL, "ws://localhost:4222"); assert.equal(env.T3CODE_NO_BROWSER, "1"); assert.equal(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD, "0"); @@ -183,6 +184,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => { assert.equal(env.VITE_DEV_SERVER_URL, "http://127.0.0.1:5733"); assert.equal(env.HOST, "127.0.0.1"); assert.equal(env.T3CODE_PORT, "4222"); + assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:4222"); assert.equal(env.T3CODE_MODE, undefined); assert.equal(env.T3CODE_NO_BROWSER, undefined); assert.equal(env.T3CODE_HOST, undefined); diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts index b50c8237f6..4522c21d70 100644 --- a/scripts/dev-runner.ts +++ b/scripts/dev-runner.ts @@ -159,9 +159,11 @@ export function createDevRunnerEnv({ if (!isDesktopMode) { output.T3CODE_PORT = String(serverPort); + output.VITE_HTTP_URL = `http://localhost:${serverPort}`; output.VITE_WS_URL = `ws://localhost:${serverPort}`; } else { output.T3CODE_PORT = String(serverPort); + output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`; output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`; delete output.T3CODE_MODE; delete output.T3CODE_NO_BROWSER;