fix(dev): keep shared dev reloads and hot updates working (#9543)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-09-03 18:45:08 -07:00
1 parent dddc0bdcb2
commit 6f405370c8
11 files changed
+404 -9

No files matched your search

+25 -1
View File
@@ -452,6 +452,30 @@
height: 64px;
object-fit: contain;
}
#boot-error {
display: grid;
justify-items: center;
gap: 16px;
max-width: 600px;
padding: 24px;
text-align: center;
}
#boot-error p {
margin: 0;
overflow-wrap: anywhere;
}
#boot-error button {
padding: 8px 16px;
border: 1px solid currentColor;
border-radius: 4px;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
}
</style>
<title>T3 Code (Alpha)</title>
</head>
@@ -463,6 +487,6 @@
</div>
</div>
</div>
<script type="module" src="/src/main.tsx"></script>
<script type="module" src="/src/bootstrap.ts"></script>
</body>
</html>
+92
View File
@@ -0,0 +1,92 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { showBootError } from "./lib/bootError";
class BootElement extends EventTarget {
children: BootElement[] = [];
textContent = "";
constructor(readonly tagName: string) {
super();
}
setAttribute() {}
append(child: BootElement) {
this.children.push(child);
}
replaceChildren(...children: BootElement[]) {
this.children = children;
}
get text(): string {
return this.textContent + this.children.map((child) => child.text).join(" ");
}
}
describe("app startup failures", () => {
let bootShell: BootElement | null;
beforeEach(() => {
vi.resetModules();
vi.doMock("./main", () => {
throw new Error("@vitejs/plugin-react can't detect preamble. Something is wrong.");
});
bootShell = new BootElement("div");
vi.stubGlobal("document", {
getElementById: () => bootShell,
createElement: (tagName: string) => new BootElement(tagName),
});
vi.spyOn(console, "error").mockImplementation(() => {});
});
it("shows failures from asynchronous app startup", async () => {
vi.doMock("./main", () => ({ startup: Promise.reject(new Error("Startup chunks failed")) }));
await import("./bootstrap");
await vi.dynamicImportSettled();
expect(bootShell?.text).toContain("Startup chunks failed");
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
it("replaces the splash when an app import throws before main can run", async () => {
const reload = vi.fn();
vi.stubGlobal("window", { location: { reload } });
await import("./bootstrap");
await vi.dynamicImportSettled();
expect(bootShell?.text).toContain("T3 Code could not load.");
const reloadButton = bootShell?.children[0]?.children.find(
(element) => element.tagName === "button",
);
expect(reloadButton?.text).toBe("Reload");
reloadButton?.dispatchEvent(new Event("click"));
expect(reload).toHaveBeenCalledOnce();
});
it.each([true, false])("shows startup error details only in dev mode, DEV=%s", (dev) => {
vi.stubEnv("DEV", dev);
showBootError(new Error("internal module path"));
expect(bootShell?.text).toContain("T3 Code could not load.");
expect(bootShell?.text.includes("internal module path")).toBe(dev);
});
it("does not replace the app after React removes the splash", () => {
bootShell = null;
const createElement = vi.spyOn(document, "createElement");
showBootError(new Error("late failure"));
expect(createElement).not.toHaveBeenCalled();
});
});
+5
View File
@@ -0,0 +1,5 @@
import { showBootError } from "./lib/bootError";
// Bundled dev can move UI code into shared chunks. Load it only after this
// entry runs the React refresh preamble, and catch failures before React mounts.
void import("./main").then(({ startup }) => startup).catch(showBootError);
+223
View File
@@ -0,0 +1,223 @@
// @effect-diagnostics nodeBuiltinImport:off - builds and executes real dev bundles on disk.
import * as NodeChildProcess from "node:child_process";
import * as NodeEvents from "node:events";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as NodeUtil from "node:util";
import react from "@vitejs/plugin-react";
import { createLogger, createServer } from "vite-plus";
import { expect, it } from "vite-plus/test";
import { tailwindPlugins } from "../vite/tailwind";
const execFile = NodeUtil.promisify(NodeChildProcess.execFile);
it("initializes React refresh before a shared UI chunk runs in bundled dev", async () => {
const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-bootstrap-"));
const output = NodePath.join(root, "output");
let resolveBundle!: (files: Map<string, string>) => void;
let rejectBundle!: (error: unknown) => void;
const bundled = new Promise<Map<string, string>>((resolve, reject) => {
resolveBundle = resolve;
rejectBundle = reject;
});
let server: Awaited<ReturnType<typeof createServer>> | undefined;
try {
await NodeFSP.mkdir(NodePath.join(root, "src/lib"), { recursive: true });
await NodeFSP.writeFile(NodePath.join(root, "package.json"), '{"type":"module"}');
for (const file of ["index.html", "src/bootstrap.ts", "src/lib/bootError.ts"]) {
await NodeFSP.copyFile(new URL(`../${file}`, import.meta.url), NodePath.join(root, file));
}
await NodeFSP.writeFile(
NodePath.join(root, "src/shared.tsx"),
"export function Shared() { return <div>ready</div>; }",
);
await NodeFSP.writeFile(
NodePath.join(root, "src/main.tsx"),
`import { Shared } from "./shared";
export const startup = Promise.resolve().then(() => globalThis.onStarted(Shared()));`,
);
server = await createServer({
configFile: false,
root,
publicDir: NodeURL.fileURLToPath(new URL("../public", import.meta.url)),
logLevel: "silent",
resolve: {
alias: { react: NodePath.dirname(NodeURL.fileURLToPath(import.meta.resolve("react"))) },
},
experimental: { bundledDev: true },
plugins: [
react(),
{
name: "capture-bootstrap-bundle",
buildEnd(error) {
if (error) rejectBundle(error);
},
generateBundle(_options, bundle) {
resolveBundle(
new Map(
Object.values(bundle)
.filter((file) => file.type === "chunk")
.map((file) => [file.fileName, file.code]),
),
);
},
},
],
build: {
rolldownOptions: {
experimental: { devMode: { lazy: false } },
output: {
// Reproduce the shared chunks Vite creates after lazy routes load,
// without needing a browser to trigger the lazy compiler first.
codeSplitting: {
groups: [
{ name: "vendor", test: /node_modules|@react-refresh/, priority: 10 },
{ name: "shared-ui", test: /shared\.tsx$/, includeDependenciesRecursively: false },
],
},
},
},
},
server: { host: "127.0.0.1", port: 0 },
});
await server.listen();
for (const [file, code] of await bundled) {
const target = NodePath.join(output, file);
await NodeFSP.mkdir(NodePath.dirname(target), { recursive: true });
await NodeFSP.writeFile(target, code);
}
// Run the actual generated ES modules so their import order and refresh
// checks execute. These stubs replace only the browser and HMR transport.
const runner = NodePath.join(output, "check.mjs");
await NodeFSP.writeFile(
runner,
`import assert from "node:assert/strict";
const started = Promise.withResolvers();
globalThis.window = globalThis;
globalThis.document = {
createElement: () => ({ relList: { supports: () => true } }),
getElementById: () => null,
};
globalThis.__rolldown_runtime__ = {
registerGraph() {},
registerModule() {},
createModuleHotContext: () => ({ accept() {} }),
};
globalThis.onStarted = started.resolve;
console.error = (_message, error) => started.reject(error);
await import("./assets/index.js");
const element = await started.promise;
assert.equal(element.props.children, "ready");
assert.equal(typeof window.$RefreshReg$, "function");
console.log("App started with React refresh ready.");`,
);
const result = await execFile("node", [runner]);
expect(result.stdout).toContain("App started with React refresh ready.");
} finally {
await server?.close();
await NodeFSP.rm(root, { recursive: true, force: true });
}
});
it("hot updates Tailwind classes when a source file changes in bundled dev", async () => {
const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-tailwind-"));
const events = new NodeEvents.EventEmitter();
let server: Awaited<ReturnType<typeof createServer>> | undefined;
let socket: WebSocket | undefined;
let css = "";
try {
await NodeFSP.writeFile(
NodePath.join(root, "index.html"),
'<html><body><script type="module" src="/main.ts"></script></body></html>',
);
const source =
'import "./style.css"; export const margin = "m-[13px]"; import.meta.hot?.accept();';
await NodeFSP.writeFile(NodePath.join(root, "main.ts"), source);
await NodeFSP.writeFile(
NodePath.join(root, "style.css"),
'@import "tailwindcss" source(none); @source "./main.ts";',
);
const logger = createLogger("silent");
logger.error = (message) => events.emit("error", new Error(message));
const built = NodeEvents.EventEmitter.once(events, "built");
server = await createServer({
configFile: false,
root,
customLogger: logger,
resolve: {
alias: {
tailwindcss: NodeURL.fileURLToPath(
new URL("../node_modules/tailwindcss/index.css", import.meta.url),
),
},
},
experimental: { bundledDev: true },
plugins: [
...tailwindPlugins(true),
{
name: "observe-tailwind-output",
enforce: "pre",
transform(code, id) {
if (id.endsWith("/style.css")) css = code;
},
generateBundle() {
events.emit("built");
},
},
],
server: { host: "127.0.0.1", port: 0 },
});
await server.listen();
await built;
const address = server.httpServer?.address();
if (!address || typeof address === "string") throw new Error("Vite did not bind a port");
const connected = NodeEvents.EventEmitter.once(events, "connected");
server.ws.on("vite:client-connected", () => events.emit("connected"));
socket = new WebSocket(
`ws://127.0.0.1:${address.port}/?token=${server.config.webSocketToken}`,
"vite-hmr",
);
socket.addEventListener("open", () => {
socket?.send(
JSON.stringify({
type: "custom",
event: "vite:client-connected",
data: { clientId: "tailwind-test" },
}),
);
});
socket.addEventListener("message", ({ data }) => {
const message: unknown = JSON.parse(String(data));
if (
message !== null &&
typeof message === "object" &&
"type" in message &&
message.type === "bundled-dev-update"
) {
events.emit("updated");
}
});
await connected;
const entry = await fetch(`http://127.0.0.1:${address.port}/assets/index.js`);
expect(entry.headers.get("content-type")).toContain("javascript");
await entry.text();
const updated = NodeEvents.EventEmitter.once(events, "updated");
await NodeFSP.writeFile(NodePath.join(root, "main.ts"), source.replace("13px", "137px"));
await updated;
expect(css).toContain("margin: 137px");
} finally {
socket?.close();
await server?.close();
await NodeFSP.rm(root, { recursive: true, force: true });
}
});
+27
View File
@@ -0,0 +1,27 @@
/** Shows startup failures before React can replace the boot splash. */
export function showBootError(error: unknown) {
console.error("T3 Code failed to start.", error);
const bootShell = document.getElementById("boot-shell");
if (!bootShell) return;
const content = document.createElement("div");
content.id = "boot-error";
content.setAttribute("role", "alert");
const message = document.createElement("p");
message.textContent = "T3 Code could not load.";
content.append(message);
if (import.meta.env.DEV && error instanceof Error) {
const detail = document.createElement("p");
detail.textContent = error.message;
content.append(detail);
}
const reload = document.createElement("button");
reload.type = "button";
reload.textContent = "Reload";
reload.addEventListener("click", () => window.location.reload());
content.append(reload);
bootShell.replaceChildren(content);
}
+6 -6
View File
@@ -56,7 +56,10 @@ const managedAuthShellModule =
// managed-auth runtime and the initial route's split chunks, before
// rendering, so the splash holds until real UI paints instead of dropping to
// a blank window while chunks download.
void Promise.all([managedAuthShellModule?.then((module) => module.default) ?? null, router.load()])
export const startup = Promise.all([
managedAuthShellModule?.then((module) => module.default) ?? null,
router.load(),
])
.then(([ManagedAuthShell]) => {
// A route chunk failure still resolves router.load(): the error is parked in
// the lazy component and surfaces through the route error boundary. Skip the
@@ -75,10 +78,7 @@ void Promise.all([managedAuthShellModule?.then((module) => module.default) ?? nu
);
})
.catch((error: unknown) => {
// The auth shell chunk failed and the guarded reload is spent. Say so
// instead of leaving the splash up forever.
// Let the bootstrap entry show the error unless a reload is already scheduled.
if (reloadScheduled) return;
console.error("T3 Code failed to load its startup chunks.", error);
const bootShell = document.getElementById("boot-shell");
if (bootShell) bootShell.textContent = "T3 Code could not load. Reload to try again.";
throw error;
});
+1
View File
@@ -27,6 +27,7 @@
},
"include": [
"src",
"vite",
"vite.config.ts",
"vercel.ts",
"test",
+2 -2
View File
@@ -1,6 +1,5 @@
import * as NodeZlib from "node:zlib";
import tailwindcss from "@tailwindcss/vite";
import react, { reactCompilerPreset } from "@vitejs/plugin-react";
import babel from "@rolldown/plugin-babel";
import { tanstackRouter } from "@tanstack/router-plugin/vite";
@@ -13,6 +12,7 @@ import pkg from "./package.json" with { type: "json" };
import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
import { loadRepoEnv } from "../../scripts/lib/public-config";
import { tailwindPlugins } from "./vite/tailwind";
const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
@@ -169,7 +169,7 @@ export default defineConfig(() => {
parserOpts: { plugins: ["typescript", "jsx"] },
presets: [reactCompilerPreset()],
}),
tailwindcss(),
tailwindPlugins(bundledDev),
],
optimizeDeps: {
include: [
+15
View File
@@ -0,0 +1,15 @@
import tailwindcss from "@tailwindcss/vite";
/** Adapts Tailwind's dev hooks to Vite's experimental bundled mode. */
export function tailwindPlugins(bundledDev: boolean) {
const plugins = tailwindcss();
if (bundledDev) {
for (const plugin of plugins) {
// This hook expects Vite ModuleNodes and a server, which Rolldown does
// not supply. Bundled dev tracks Tailwind's addWatchFile dependencies
// and rebuilds CSS when those files change without this hook.
delete plugin.hotUpdate;
}
}
return plugins;
}
+5
View File
@@ -27,6 +27,11 @@ authenticated.
Shared runs default to Vite's bundled dev mode (`T3CODE_BUNDLED_DEV=1`): a remote browser pays a
network round trip per import level in unbundled dev, which turns a cold module graph into
minutes of waterfall. Set `T3CODE_BUNDLED_DEV=0` to opt a shared run back out.
The web entry loads the app with a dynamic import so React refresh starts before shared UI
chunks run. Keep app imports out of that entry. A static import can work on the first load
and then fail on reload after Vite splits code for lazy routes.
Bundled dev uses Tailwind's watched files to rebuild CSS. Its Vite-only hot-update hook is
disabled in this mode because Rolldown does not supply the Vite server or module graph.
- `vp run dev --browser`: Auto-opens a browser. Off by default. The dev runner writes
`T3CODE_NO_BROWSER` itself from this flag, so setting `T3CODE_NO_BROWSER=0` in your environment has
no effect; use `--browser`.
+3
View File
@@ -18,6 +18,9 @@ npx t3@latest
This starts the T3 Code server on your machine and opens the local web app. Use
`npx t3@latest --help` for the full CLI reference.
If the web or desktop app shows "T3 Code could not load", check your connection and select
**Reload** to try again.
## Open a project in the desktop app
When the T3 Code desktop app is running on the same machine, open the current directory with: