Compare commits

...
59 changed files with 3044 additions and 714 deletions

No files matched your search

+14 -2
View File
@@ -13,13 +13,25 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
2. Choose a base directory that belongs only to the current worktree or test:
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
### Verify a shared environment before human handoff
When another person will use the printed pairing URL, first open the shared origin without the pairing path or fragment in the controlled browser and confirm the T3 Code app loads. This browser navigation is required even when curl succeeds because browsers block some otherwise reachable ports before making a network request.
Do not open the other person's complete pairing URL during this reachability check; doing so consumes its one-time token. If the agent also needs an authenticated browser, create and consume a separate pairing token, then leave a fresh token for the other person.
## Preserve the environment while iterating
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
@@ -55,7 +67,7 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
## Inspect or seed SQLite state
+8
View File
@@ -13,6 +13,14 @@
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## Dev Servers
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
+15 -1
View File
@@ -8,9 +8,13 @@ import * as ServerConfig from "../config.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import { resolveSessionCookieName } from "./utils.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
const TEST_SERVER_PORT = 13_773;
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
Layer.effect(
ServerConfig.ServerConfig,
@@ -19,6 +23,12 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
return {
...config,
...overrides,
// Last, so the port cannot be overridden out from under
// makeCookieRequest — which builds the cookie name from this constant.
// An override that changed it would leave the server reading
// t3_session_<other> while every request still sent t3_session_13773,
// and the tests would fail for a reason unrelated to what they assert.
port: TEST_SERVER_PORT,
} satisfies ServerConfig.ServerConfig["Service"];
}),
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
@@ -35,7 +45,11 @@ const makeCookieRequest = (
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
({
cookies: {
t3_session: sessionToken,
// Derived, not hardcoded: the name is port-scoped so concurrent servers
// on one hostname don't share a cookie. Mode and devUrl mirror
// ServerConfig.layerTest, so this resolves to whatever the server reads.
[resolveSessionCookieName({ mode: "web", port: TEST_SERVER_PORT, devUrl: undefined })]:
sessionToken,
},
headers: {},
}) as unknown as Parameters<
+5
View File
@@ -438,6 +438,7 @@ export class EnvironmentAuth extends Context.Service<
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly proofKeyThumbprint?: string;
readonly purpose?: "startup";
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
@@ -746,11 +747,13 @@ export const make = Effect.gen(function* () {
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly subject: string;
readonly label?: string;
readonly purpose?: "startup";
}) =>
createPairingLink({
scopes: input.scopes,
subject: input.subject,
...(input.label ? { label: input.label } : {}),
...(input.purpose ? { purpose: input.purpose } : {}),
}).pipe(
Effect.map(
(issued) =>
@@ -774,6 +777,7 @@ export const make = Effect.gen(function* () {
...(input?.ttl ? { ttl: input.ttl } : {}),
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
...(input?.purpose ? { purpose: input.purpose } : {}),
});
return {
id: issued.id,
@@ -872,6 +876,7 @@ export const make = Effect.gen(function* () {
issuePairingCredentialForSubject({
scopes: AuthAdministrativeScopes,
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
purpose: "startup",
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
@@ -34,6 +34,9 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
expect(descriptor.policy).toBe("desktop-managed-local");
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
// Packaged desktop has no devUrl, but still needs the port scope: it
// scans upward from 3773 for a free port and binds 127.0.0.1, so a second
// instance shares this one's hostname on a different port.
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
}).pipe(
Effect.provide(
@@ -45,6 +48,22 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
),
);
it.effect("keeps desktop cookies port-scoped on the port a second instance lands on", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_3774");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "desktop",
port: 3774,
}),
),
),
);
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
@@ -75,6 +94,24 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
makeEnvironmentAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
port: 13773,
}),
),
),
);
it.effect("scopes web session cookies by port only in development", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
port: 13773,
devUrl: new URL("http://127.0.0.1:5733"),
}),
),
),
@@ -41,6 +41,7 @@ export const make = Effect.gen(function* () {
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.port,
devUrl: config.devUrl,
}),
};
+18 -1
View File
@@ -202,6 +202,11 @@ export class PairingGrantStore extends Context.Service<
readonly subject?: string;
readonly label?: string;
readonly proofKeyThumbprint?: string;
/**
* "startup" marks the credential the server mints for itself at boot,
* which gets the long dev TTL when a dev URL is configured.
*/
readonly purpose?: "startup";
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthPairingLink>,
@@ -243,6 +248,15 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
// window can still recover by re-bootstrapping rather than locking
// the user out of the backend.
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
// A dev server's startup token is read off a log by whoever (or whatever) is
// driving the session, often minutes later — after a `node --watch` restart, a
// detour into another task, or a hand-off to the person actually doing the
// testing. Five minutes turns that into a restart-the-server loop for no
// security benefit: the token only unlocks a local dev backend, and its holder
// could read the log anyway. Same reasoning (and duration) as the desktop
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
// pairing links and real servers keep the 5-minute default.
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const PAIRING_TOKEN_REJECTION_LIMIT =
@@ -371,7 +385,10 @@ export const make = Effect.gen(function* () {
),
);
const credential = yield* generatePairingToken;
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
const ttl =
input?.ttl ??
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
const issued: IssuedBootstrapCredential = {
+1
View File
@@ -470,6 +470,7 @@ export const make = Effect.gen(function* () {
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.port,
devUrl: serverConfig.devUrl,
});
const emitUpsert = (clientSession: AuthClientSession) =>
+19 -5
View File
@@ -10,15 +10,29 @@ import * as Result from "effect/Result";
const SESSION_COOKIE_NAME = "t3_session";
/**
* Cookies are scoped by host but *not* by port, so any two servers that can be
* live on one hostname at once need separate names — otherwise the second
* clobbers the first's session and both sides see "Invalid session token
* signature" until someone clears cookies by hand.
*
* Two populations qualify, for the same reason but from different causes:
*
* - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
* - **Desktop**, which scans upward from 3773 for a free port and binds
* 127.0.0.1, so a second instance lands on a different port and the same host.
*
* Hosted deployments keep the stable production name: their public port can
* change between releases, and scoping it would log every user out.
*/
export function resolveSessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly port: number;
readonly devUrl: URL | undefined;
}): string {
if (input.mode !== "desktop") {
return SESSION_COOKIE_NAME;
}
return `${SESSION_COOKIE_NAME}_${input.port}`;
return input.devUrl === undefined && input.mode !== "desktop"
? SESSION_COOKIE_NAME
: `${SESSION_COOKIE_NAME}_${input.port}`;
}
export function base64UrlEncode(input: string | Uint8Array): string {
+1
View File
@@ -84,6 +84,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
...derivedPaths,
staticDir: undefined,
devUrl: undefined,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
+4
View File
@@ -48,6 +48,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
devAllowedOrigins: [],
} as const;
const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
@@ -95,6 +96,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_DEV_ALLOWED_ORIGINS:
"https://host.example.ts.net, https://phone.example.ts.net ",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "true",
@@ -117,6 +120,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
host: "0.0.0.0",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
devAllowedOrigins: ["https://host.example.ts.net", "https://phone.example.ts.net"],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
+10
View File
@@ -106,6 +106,15 @@ const EnvServerConfig = Config.all({
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
devAllowedOrigins: Config.string("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
Config.withDefault(""),
Config.map((value) =>
value
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0),
),
),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -363,6 +372,7 @@ export const resolveServerConfig = (
host,
staticDir,
devUrl,
devAllowedOrigins: env.devAllowedOrigins,
noBrowser,
startupPresentation,
desktopBootstrapToken,
+2
View File
@@ -72,6 +72,7 @@ export class ServerConfig extends Context.Service<
readonly baseDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly devAllowedOrigins: ReadonlyArray<string>;
readonly noBrowser: boolean;
readonly startupPresentation: StartupPresentation;
readonly desktopBootstrapToken: string | undefined;
@@ -187,6 +188,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
desktopBootstrapToken: undefined,
staticDir: undefined,
devUrl,
devAllowedOrigins: [],
noBrowser: false,
startupPresentation: "browser",
});
@@ -43,6 +43,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
desktopBootstrapToken: undefined,
staticDir: undefined,
devUrl: undefined,
devAllowedOrigins: [],
noBrowser: false,
startupPresentation: "browser",
} satisfies ServerConfig.ServerConfig["Service"];
+14 -1
View File
@@ -4,6 +4,7 @@ import {
AuthOrchestrationReadScope,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
@@ -48,9 +49,17 @@ export const browserApiCorsLayer = Layer.unwrap(
const devOrigin = config.devUrl?.origin;
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
//
// T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
// origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
// through Vite and is same-origin (no preflight at all), so this is a
// safety net for the desktop renderer and any direct-to-backend caller.
return HttpRouter.cors({
...(devOrigin
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
? {
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
credentials: true,
}
: {}),
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
@@ -216,6 +225,10 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
const config = yield* ServerConfig.ServerConfig;
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
status: 302,
+31
View File
@@ -380,6 +380,7 @@ const buildAppUnderTest = (options?: {
...derivedPaths,
staticDir: undefined,
devUrl,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: defaultDesktopBootstrapToken,
@@ -1328,6 +1329,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
"bearer-access-token",
"dpop-access-token",
]);
// Desktop, so port-scoped: instances scan for a free port and share
// 127.0.0.1, and cookies are not scoped by port.
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -3246,6 +3249,34 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("allows configured development origins through ServerConfig", () =>
Effect.gen(function* () {
const tailnetOrigin = "https://host.example.ts.net";
yield* buildAppUnderTest({
config: {
devUrl: new URL(crossOriginClientOrigin),
devAllowedOrigins: [tailnetOrigin],
},
});
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const response = yield* fetchEffect(sessionUrl, {
method: "OPTIONS",
headers: {
origin: tailnetOrigin,
"access-control-request-method": "GET",
"access-control-request-headers": "content-type",
},
});
assert.equal(response.status, 204);
assertBrowserApiCorsPreflightHeaders(response.headers, {
origin: tailnetOrigin,
credentials: true,
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
Effect.gen(function* () {
+3
View File
@@ -11,6 +11,9 @@
<meta name="theme-color" content="#161616" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<script>
performance.mark("navigation.start");
</script>
<script>
(() => {
const LIGHT_BACKGROUND = "#ffffff";
+3 -6
View File
@@ -2,23 +2,20 @@ import { Children, isValidElement, type ReactElement, type ReactNode } from "rea
import { RouterProvider } from "@tanstack/react-router";
import { describe, expect, it } from "vite-plus/test";
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import type { AppRouter } from "./router";
import { AppRoot } from "./AppRoot";
describe("AppRoot", () => {
it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => {
it("shares the application atom registry with routed UI and lazy runtime hosts", () => {
const root = AppRoot({ router: {} as AppRouter });
expect(root.type).toBe(AppAtomRegistryProvider);
const children = Children.toArray(
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
);
expect(children).toHaveLength(3);
expect(children).toHaveLength(2);
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
expect(isValidElement(children[1])).toBe(true);
});
});
+27 -4
View File
@@ -1,10 +1,34 @@
import { lazy, Suspense } from "react";
import { RouterProvider } from "@tanstack/react-router";
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
import { isElectron } from "./env";
import { STARTUP_OPTIONAL_UI_DELAY_MS, useAfterFirstPaint } from "./hooks/useAfterFirstPaint";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import type { AppRouter } from "./router";
const PreviewAutomationHosts = lazy(() =>
import("./components/preview/PreviewAutomationHosts").then((module) => ({
default: module.PreviewAutomationHosts,
})),
);
const ElectronBrowserHost = lazy(() =>
import("./browser/ElectronBrowserHost").then((module) => ({
default: module.ElectronBrowserHost,
})),
);
function DeferredRuntimeHosts() {
const ready = useAfterFirstPaint(STARTUP_OPTIONAL_UI_DELAY_MS);
if (!ready) return null;
return (
<Suspense fallback={null}>
<PreviewAutomationHosts />
{isElectron ? <ElectronBrowserHost /> : null}
</Suspense>
);
}
/**
* Owns renderer-wide providers. The Electron browser host intentionally sits
* outside the router so its webviews survive route transitions, but it must
@@ -14,8 +38,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
return (
<AppAtomRegistryProvider>
<RouterProvider router={router} />
<PreviewAutomationHosts />
<ElectronBrowserHost />
<DeferredRuntimeHosts />
</AppAtomRegistryProvider>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { ClerkProvider } from "@clerk/react";
import type { ReactNode } from "react";
import { ManagedRelayAuthProvider } from "./managedAuth";
export default function CloudAuthRoot({
children,
publishableKey,
}: {
readonly children: ReactNode;
readonly publishableKey: string;
}) {
return (
<ClerkProvider publishableKey={publishableKey}>
<ManagedRelayAuthProvider>{children}</ManagedRelayAuthProvider>
</ClerkProvider>
);
}
@@ -0,0 +1,19 @@
import { passkeys } from "@clerk/electron/passkeys";
import { ClerkProvider } from "@clerk/electron/react";
import type { ReactNode } from "react";
import { ManagedRelayAuthProvider } from "./managedAuth";
export default function ElectronCloudAuthRoot({
children,
publishableKey,
}: {
readonly children: ReactNode;
readonly publishableKey: string;
}) {
return (
<ClerkProvider publishableKey={publishableKey} passkeys={passkeys}>
<ManagedRelayAuthProvider>{children}</ManagedRelayAuthProvider>
</ClerkProvider>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { ConnectOnboardingDialog } from "./cloud/ConnectOnboardingDialog";
import { RelayClientInstallDialog } from "./cloud/RelayClientInstallDialog";
import { SshPasswordPromptDialog } from "./desktop/SshPasswordPromptDialog";
import { SlowRpcRequestToastCoordinator } from "./SlowRpcRequestToastCoordinator";
export default function AppOverlays() {
return (
<>
<RelayClientInstallDialog />
<ConnectOnboardingDialog />
<SshPasswordPromptDialog />
<SlowRpcRequestToastCoordinator />
</>
);
}
+10 -4
View File
@@ -1,16 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import * as Schema from "effect/Schema";
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { lazy, Suspense, useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
import { useAfterFirstPaint } from "../hooks/useAfterFirstPaint";
import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import { useClientSettings } from "../hooks/useSettings";
import ThreadSidebar from "./Sidebar";
import ThreadSidebarV2 from "./SidebarV2";
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import {
resolveInitialThreadSidebarWidth,
@@ -30,6 +29,8 @@ import {
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
const ThreadSidebar = lazy(() => import("./Sidebar"));
const ThreadSidebarV2 = lazy(() => import("./SidebarV2"));
function readInitialThreadSidebarWidth(): number {
try {
@@ -100,6 +101,7 @@ function SidebarControl() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const loadSidebarContent = useAfterFirstPaint();
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
// Settings routes render the settings nav, which lives in the v1 component
// and is identical for both sidebars — so v1 stays mounted there.
@@ -178,7 +180,11 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
onResize: setSidebarWidth,
}}
>
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
{loadSidebarContent ? (
<Suspense fallback={null}>
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
</Suspense>
) : null}
<SidebarRail />
</Sidebar>
{children}
+7 -126
View File
@@ -16,7 +16,7 @@ import {
type SourceControlRepositoryInfo,
PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useNavigate } from "@tanstack/react-router";
import * as Option from "effect/Option";
import {
ArrowDownIcon,
@@ -33,11 +33,8 @@ import {
import {
useCallback,
useDeferredValue,
useEffect,
useLayoutEffect,
useMemo,
useReducer,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
@@ -74,12 +71,9 @@ import {
isUnsupportedWindowsProjectPath,
resolveProjectPathForDispatch,
} from "../lib/projectPaths";
import { onOpenCommandPalette } from "../commandPaletteBus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import { buildThreadRouteParams } from "../threadRoutes";
import {
applyWslEnvironmentConfiguration,
parseWslUncPath,
@@ -124,8 +118,7 @@ import { Button } from "./ui/button";
import { Kbd, KbdGroup } from "./ui/kbd";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
import type { ChatComposerHandle } from "./chat/ChatComposer";
import { useComposerHandleContext } from "../composerHandleContext";
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import {
@@ -343,127 +336,15 @@ interface CommandPaletteOpenIntent {
readonly kind: "add-project" | "new-thread-in";
}
interface CommandPaletteUiState {
readonly open: boolean;
readonly openIntent: CommandPaletteOpenIntent | null;
}
type CommandPaletteUiAction =
| { readonly _tag: "SetOpen"; readonly open: boolean }
| { readonly _tag: "Toggle" }
| { readonly _tag: "OpenAddProject" }
| { readonly _tag: "OpenNewThreadIn" }
| { readonly _tag: "ClearOpenIntent" };
function reduceCommandPaletteUiState(
state: CommandPaletteUiState,
action: CommandPaletteUiAction,
): CommandPaletteUiState {
switch (action._tag) {
case "SetOpen":
return {
open: action.open,
openIntent: action.open ? state.openIntent : null,
};
case "Toggle":
return { open: !state.open, openIntent: null };
case "OpenAddProject":
return { open: true, openIntent: { kind: "add-project" } };
case "OpenNewThreadIn":
return { open: true, openIntent: { kind: "new-thread-in" } };
case "ClearOpenIntent":
return state.openIntent ? { ...state, openIntent: null } : state;
}
}
export function CommandPalette({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reduceCommandPaletteUiState, {
open: false,
openIntent: null,
});
const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);
const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const terminalOpen = useTerminalUiStateStore((state) =>
routeThreadRef
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.defaultPrevented) return;
const command = resolveShortcutCommand(event, keybindings, {
context: {
terminalFocus: isTerminalFocused(),
terminalOpen,
},
});
if (command !== "commandPalette.toggle") {
return;
}
event.preventDefault();
event.stopPropagation();
toggleOpen();
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [keybindings, terminalOpen, toggleOpen]);
useEffect(
() =>
onOpenCommandPalette((detail) => {
if (detail.open === "new-thread-in") {
openNewThreadIn();
} else if (detail.open === "add-project") {
openAddProject();
} else {
setOpen(true);
}
}),
[openAddProject, openNewThreadIn, setOpen],
);
return (
<ComposerHandleContext value={composerHandleRef}>
<CommandDialog open={state.open} onOpenChange={setOpen}>
{children}
<CommandPaletteDialog
open={state.open}
openIntent={state.openIntent}
setOpen={setOpen}
clearOpenIntent={clearOpenIntent}
/>
</CommandDialog>
</ComposerHandleContext>
);
}
function CommandPaletteDialog(props: {
readonly open: boolean;
export function CommandPaletteDialog(props: {
readonly openIntent: CommandPaletteOpenIntent | null;
readonly setOpen: (open: boolean) => void;
readonly clearOpenIntent: () => void;
}) {
if (!props.open) {
return null;
}
return (
<OpenCommandPaletteDialog
openIntent={props.openIntent}
setOpen={props.setOpen}
clearOpenIntent={props.clearOpenIntent}
/>
<CommandDialog open onOpenChange={props.setOpen}>
<OpenCommandPaletteDialog {...props} />
</CommandDialog>
);
}
@@ -0,0 +1,113 @@
import { useAtomValue } from "@effect/atom-react";
import { useParams } from "@tanstack/react-router";
import { lazy, Suspense, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { onOpenCommandPalette } from "../commandPaletteBus";
import { ComposerHandleContext } from "../composerHandleContext";
import { resolveShortcutCommand } from "../keybindings";
import { isTerminalFocused } from "../lib/terminalFocus";
import { primaryServerKeybindingsAtom } from "../state/server";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { resolveThreadRouteTarget } from "../threadRoutes";
import type { ChatComposerHandle } from "./chat/ChatComposer";
const CommandPaletteDialog = lazy(() =>
import("./CommandPalette").then((module) => ({
default: module.CommandPaletteDialog,
})),
);
interface CommandPaletteOpenIntent {
readonly kind: "add-project" | "new-thread-in";
}
interface CommandPaletteState {
readonly open: boolean;
readonly openIntent: CommandPaletteOpenIntent | null;
}
/**
* Keeps the command-palette keyboard/event bridge in the startup graph while
* deferring its filesystem, source-control, and dialog implementation until
* the palette is opened.
*/
export function CommandPaletteShell({ children }: { readonly children: ReactNode }) {
const [state, setState] = useState<CommandPaletteState>({
open: false,
openIntent: null,
});
const setOpen = useCallback(
(open: boolean) =>
setState((current) => ({
open,
openIntent: open ? current.openIntent : null,
})),
[],
);
const toggleOpen = useCallback(
() => setState((current) => ({ open: !current.open, openIntent: null })),
[],
);
const clearOpenIntent = useCallback(
() => setState((current) => ({ ...current, openIntent: null })),
[],
);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const terminalOpen = useTerminalUiStateStore((value) =>
routeThreadRef
? selectThreadTerminalUiState(value.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.defaultPrevented) return;
const command = resolveShortcutCommand(event, keybindings, {
context: {
terminalFocus: isTerminalFocused(),
terminalOpen,
},
});
if (command !== "commandPalette.toggle") return;
event.preventDefault();
event.stopPropagation();
toggleOpen();
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [keybindings, terminalOpen, toggleOpen]);
useEffect(
() =>
onOpenCommandPalette((detail) => {
if (!detail.open) {
setOpen(true);
return;
}
setState({ open: true, openIntent: { kind: detail.open } });
}),
[setOpen],
);
return (
<ComposerHandleContext value={composerHandleRef}>
{children}
{state.open ? (
<Suspense fallback={null}>
<CommandPaletteDialog
openIntent={state.openIntent}
setOpen={setOpen}
clearOpenIntent={clearOpenIntent}
/>
</Suspense>
) : null}
</ComposerHandleContext>
);
}
+43 -1
View File
@@ -11,6 +11,8 @@ import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronsDownUpIcon,
ChevronsUpDownIcon,
Columns2Icon,
PilcrowIcon,
Rows3Icon,
@@ -32,6 +34,7 @@ import {
resolveDiffThemeName,
resolveFileDiffPath,
} from "../lib/diffRendering";
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useProject, useThread } from "../state/entities";
import { resolveThreadRouteRef } from "../threadRoutes";
@@ -39,6 +42,7 @@ import { useClientSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
import { Button } from "./ui/button";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { Switch } from "./ui/switch";
import {
@@ -446,6 +450,8 @@ export default function DiffPanel({
}),
[collapsedDiffFileKeys, renderableFiles],
);
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
useEffect(() => {
if (!selectedFilePath) return;
@@ -496,6 +502,18 @@ export default function DiffPanel({
[collapseScopeKey],
);
const toggleDiffFileCollapse = useCallback(() => {
setCollapsedDiffFiles((current) => {
const currentKeys =
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
return {
scopeKey: collapseScopeKey,
fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
};
});
}, [collapseScopeKey, diffFileKeys]);
const selectTurn = (turnId: TurnId) => {
if (!routeThreadRef) return;
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
@@ -695,6 +713,30 @@ export default function DiffPanel({
)}
</div>
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
{codeViewFiles.length > 0 && (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
onClick={toggleDiffFileCollapse}
/>
}
>
{allDiffFilesCollapsed ? (
<ChevronsUpDownIcon className="size-3" />
) : (
<ChevronsDownUpIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
</TooltipPopup>
</Tooltip>
)}
<ToggleGroup
className="shrink-0"
variant="outline"
@@ -824,7 +866,7 @@ export default function DiffPanel({
<AnnotatableCodeView
viewerRef={codeViewRef}
key={collapseScopeKey ?? reviewSectionId}
className="diff-render-surface h-full min-h-0 overflow-auto"
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
files={codeViewFiles}
sectionId={reviewSectionId}
sectionTitle={reviewSectionTitle}
+7 -10
View File
@@ -189,7 +189,6 @@ import { sortThreads } from "../lib/threadSort";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { primaryServerKeybindingsAtom } from "../state/server";
import {
@@ -2827,14 +2826,12 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
<SidebarGroup className="px-2 pt-2 pb-1">
<SidebarMenu>
<SidebarMenuItem>
<CommandDialogTrigger
render={
<SidebarMenuButton
size="sm"
className="h-8 gap-2 rounded-md px-2 py-1.5 text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-0"
data-testid="command-palette-trigger"
/>
}
<SidebarMenuButton
size="sm"
type="button"
className="h-8 gap-2 rounded-md px-2 py-1.5 text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-0"
data-testid="command-palette-trigger"
onClick={() => openCommandPalette()}
>
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
<span className="flex-1 truncate text-left text-sm font-medium">Search</span>
@@ -2843,7 +2840,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
{commandPaletteShortcutLabel}
</Kbd>
) : null}
</CommandDialogTrigger>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
+8 -12
View File
@@ -133,7 +133,6 @@ import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils";
import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances";
import { primaryServerProvidersAtom } from "../state/server";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { CommandDialogTrigger } from "./ui/command";
import { Button } from "./ui/button";
import {
Dialog,
@@ -2218,16 +2217,13 @@ export default function SidebarV2() {
<SidebarGroup className="px-2 pb-2 pt-3">
<div className="flex items-center gap-1">
<div className="min-w-0 flex-1">
<CommandDialogTrigger
render={
<SidebarMenuButton
size="sm"
type="button"
aria-label="Search threads and commands"
className="h-8 gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
data-testid="command-palette-trigger"
/>
}
<SidebarMenuButton
size="sm"
type="button"
aria-label="Search threads and commands"
className="h-8 gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
data-testid="command-palette-trigger"
onClick={() => openCommandPalette()}
>
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
<div className="flex-1 truncate text-left">Search</div>
@@ -2236,7 +2232,7 @@ export default function SidebarV2() {
{commandPaletteShortcutLabel}
</Kbd>
) : null}
</CommandDialogTrigger>
</SidebarMenuButton>
</div>
<div className="shrink-0">
<Tooltip>
@@ -0,0 +1,110 @@
import { describe, expect, it } from "vite-plus/test";
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
import { buildTraitsTriggerDisplay } from "./TraitsPicker";
function selectDescriptor(
id: string,
options: ReadonlyArray<{ id: string; label: string }>,
currentValue: string,
): Extract<ProviderOptionDescriptor, { type: "select" }> {
return { id, label: id, type: "select", options: [...options], currentValue };
}
function fastModeDescriptor(
currentValue: boolean,
): Extract<ProviderOptionDescriptor, { type: "boolean" }> {
return { id: "fastMode", label: "Fast Mode", type: "boolean", currentValue };
}
const EFFORT = selectDescriptor(
"effort",
[
{ id: "high", label: "High" },
{ id: "max", label: "Max" },
],
"high",
);
const CONTEXT_WINDOW = selectDescriptor(
"contextWindow",
[
{ id: "200k", label: "200k" },
{ id: "1m", label: "1M" },
],
"1m",
);
function display(descriptors: ReadonlyArray<ProviderOptionDescriptor>, fastModeEnabled: boolean) {
return buildTraitsTriggerDisplay({
descriptors,
primarySelectDescriptorId: "effort",
ultrathinkPromptControlled: false,
fastModeEnabled,
});
}
describe("buildTraitsTriggerDisplay", () => {
it("omits fast mode from the label entirely when it is off", () => {
expect(display([EFFORT, fastModeDescriptor(false), CONTEXT_WINDOW], false)).toEqual({
label: "High · 1M",
showFastModeIcon: false,
});
});
it("shows the bolt instead of a text label when fast mode is on", () => {
expect(display([EFFORT, fastModeDescriptor(true), CONTEXT_WINDOW], true)).toEqual({
label: "High · 1M",
showFastModeIcon: true,
});
});
it("keeps non-fastMode booleans as text labels", () => {
const thinking: Extract<ProviderOptionDescriptor, { type: "boolean" }> = {
id: "thinking",
label: "Thinking",
type: "boolean",
currentValue: true,
};
expect(display([EFFORT, thinking], false)).toEqual({
label: "High · Thinking On",
showFastModeIcon: false,
});
});
it("falls back to a text label when fast mode is the only trait", () => {
expect(display([fastModeDescriptor(true)], true)).toEqual({
label: "Fast",
showFastModeIcon: false,
});
expect(display([fastModeDescriptor(false)], false)).toEqual({
label: "Normal",
showFastModeIcon: false,
});
});
it("stays blank when descriptors resolve to no label and there is no fast mode", () => {
// A select with neither a currentValue nor an isDefault option yields no
// label. Without a fastMode descriptor present that must stay blank rather
// than falling through to a bogus "Normal".
const unresolved: Extract<ProviderOptionDescriptor, { type: "select" }> = {
id: "effort",
label: "effort",
type: "select",
options: [
{ id: "low", label: "Low" },
{ id: "high", label: "High" },
],
};
expect(display([unresolved], false)).toEqual({ label: "", showFastModeIcon: false });
});
it("still renders the prompt-controlled ultrathink label alongside the bolt", () => {
expect(
buildTraitsTriggerDisplay({
descriptors: [EFFORT, fastModeDescriptor(true)],
primarySelectDescriptorId: "effort",
ultrathinkPromptControlled: true,
fastModeEnabled: true,
}),
).toEqual({ label: "Ultrathink", showFastModeIcon: true });
});
});
+58 -21
View File
@@ -16,7 +16,7 @@ import {
} from "@t3tools/shared/model";
import { memo, useCallback, useState } from "react";
import type { VariantProps } from "class-variance-authority";
import { ChevronDownIcon } from "lucide-react";
import { ChevronDownIcon, ZapIcon } from "lucide-react";
import { Button, buttonVariants } from "../ui/button";
import {
Menu,
@@ -379,6 +379,46 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
);
});
/**
* Build the traits trigger's text label plus whether the fast-mode bolt should
* render. Fast mode is a lightning bolt when on and nothing at all when off —
* "Normal" is the near-universal case and isn't worth the horizontal space. The
* one exception is when fast mode is the only trait, where a bare bolt (or bare
* chevron) would leave the trigger unreadable.
*/
export function buildTraitsTriggerDisplay(input: {
descriptors: ReadonlyArray<ProviderOptionDescriptor>;
primarySelectDescriptorId: string | null;
ultrathinkPromptControlled: boolean;
fastModeEnabled: boolean;
}): { label: string; showFastModeIcon: boolean } {
let hasFastMode = false;
const labels: Array<string> = [];
for (const descriptor of input.descriptors) {
if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
hasFastMode = true;
continue;
}
const label =
input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
? "Ultrathink"
: descriptor.type === "boolean"
? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
: getProviderOptionCurrentLabel(descriptor);
if (typeof label === "string" && label.length > 0) {
labels.push(label);
}
}
// Only fall back to text when fast mode is genuinely the sole trait. Keying
// off an empty label list alone would also catch descriptors that resolved to
// no label at all, printing a bogus "Normal" for a model without fast mode.
if (labels.length === 0 && hasFastMode) {
return { label: input.fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
}
return { label: labels.join(" · "), showFastModeIcon: input.fastModeEnabled };
}
export const TraitsPicker = memo(function TraitsPicker({
provider,
instanceId,
@@ -393,7 +433,7 @@ export const TraitsPicker = memo(function TraitsPicker({
...persistence
}: TraitsMenuContentProps & TraitsPersistence) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled, fastModeEnabled } =
getTraitsSectionVisibility({
provider,
models,
@@ -415,23 +455,18 @@ export const TraitsPicker = memo(function TraitsPicker({
return null;
}
const triggerLabels: Array<string> = [];
for (const descriptor of descriptors) {
const label =
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
? "Ultrathink"
: descriptor.type === "boolean"
? descriptor.id === "fastMode"
? descriptor.currentValue === true
? "Fast"
: "Normal"
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
: getProviderOptionCurrentLabel(descriptor);
if (typeof label === "string" && label.length > 0) {
triggerLabels.push(label);
}
}
const triggerLabel = triggerLabels.join(" · ");
const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
descriptors,
primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
ultrathinkPromptControlled,
fastModeEnabled,
});
const fastModeIcon = showFastModeIcon ? (
<>
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
<span className="sr-only">Fast mode on</span>
</>
) : null;
const isCodexStyle = provider === "codex";
@@ -457,12 +492,14 @@ export const TraitsPicker = memo(function TraitsPicker({
}
>
{isCodexStyle ? (
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
{triggerLabel}
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
{fastModeIcon}
<span className="min-w-0 truncate">{triggerLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
</span>
) : (
<>
{fastModeIcon}
<span>{triggerLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
</>
@@ -21,6 +21,7 @@ import {
import { PrimaryEnvironmentHttpClient } from "./httpClient";
import { runPrimaryHttp } from "../../lib/runtime";
import { markStartupMilestone } from "../../startupPerformance";
const PrimaryEnvironmentRequestOperation = Schema.Literals([
"fetch-session-state",
@@ -333,6 +334,7 @@ async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
try {
await exchangeBootstrapCredential(bootstrapCredential);
markStartupMilestone("pairing.exchanged");
await waitForAuthenticatedSessionAfterBootstrap();
return { status: "authenticated" };
} catch (error) {
@@ -354,6 +356,7 @@ export async function submitServerAuthCredential(credential: string): Promise<vo
resolvedAuthenticatedGateState = null;
await exchangeBootstrapCredential(trimmedCredential);
markStartupMilestone("pairing.exchanged");
bootstrapPromise = null;
stripPairingTokenFromUrl();
}
+27
View File
@@ -0,0 +1,27 @@
import { useEffect, useState } from "react";
export const STARTUP_OPTIONAL_UI_DELAY_MS = 2_500;
/**
* Lets the first usable shell paint before optional runtime UI starts loading.
*/
export function useAfterFirstPaint(delayMs = 0): boolean {
const [ready, setReady] = useState(false);
useEffect(() => {
let timeout: number | undefined;
const frame = window.requestAnimationFrame(() => {
if (delayMs <= 0) {
setReady(true);
} else {
timeout = window.setTimeout(() => setReady(true), delayMs);
}
});
return () => {
window.cancelAnimationFrame(frame);
if (timeout !== undefined) window.clearTimeout(timeout);
};
}, [delayMs]);
return ready;
}
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vite-plus/test";
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "./diffCollapse";
const FILE_KEYS = ["src/app.ts", "src/index.ts"];
const FIRST_FILE_KEY = FILE_KEYS[0]!;
describe("diff collapse controls", () => {
it("reports whether every rendered file is collapsed", () => {
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set(FILE_KEYS))).toBe(true);
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toBe(false);
expect(areAllDiffFilesCollapsed([], new Set())).toBe(false);
});
it("collapses all files when any rendered file is expanded", () => {
expect(toggleAllDiffFiles(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toEqual(new Set(FILE_KEYS));
});
it("expands all files when every rendered file is collapsed", () => {
expect(toggleAllDiffFiles(FILE_KEYS, new Set(FILE_KEYS))).toEqual(new Set());
});
});
+13
View File
@@ -0,0 +1,13 @@
export function areAllDiffFilesCollapsed(
fileKeys: ReadonlyArray<string>,
collapsedFileKeys: ReadonlySet<string>,
): boolean {
return fileKeys.length > 0 && fileKeys.every((fileKey) => collapsedFileKeys.has(fileKey));
}
export function toggleAllDiffFiles(
fileKeys: ReadonlyArray<string>,
collapsedFileKeys: ReadonlySet<string>,
): ReadonlySet<string> {
return areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? new Set() : new Set(fileKeys);
}
+12 -14
View File
@@ -1,8 +1,5 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { ClerkProvider } from "@clerk/react";
import { passkeys } from "@clerk/electron/passkeys";
import { ClerkProvider as ElectronClerkProvider } from "@clerk/electron/react";
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
import "@fontsource-variable/dm-sans/index.css";
@@ -12,7 +9,6 @@ import "@xterm/xterm/css/xterm.css";
import "./index.css";
import { isElectron } from "./env";
import { ManagedRelayAuthProvider } from "./cloud/managedAuth";
import { hasCloudPublicConfig } from "./cloud/publicConfig";
import { getRouter } from "./router";
import {
@@ -20,8 +16,11 @@ import {
syncDocumentWindowControlsOverlayClass,
} from "./lib/windowControlsOverlay";
import { AppRoot } from "./AppRoot";
import { markStartupMilestone } from "./startupPerformance";
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
markStartupMilestone("entry.loaded");
const history = isElectron ? createHashHistory() : createBrowserHistory();
const router = getRouter(history);
@@ -32,21 +31,20 @@ if (isElectron) {
}
const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;
const CloudAuthRoot = React.lazy(() =>
isElectron ? import("./cloud/ElectronCloudAuthRoot") : import("./cloud/CloudAuthRoot"),
);
const app = <AppRoot router={router} />;
const cloudAuthPublishableKey =
clerkPublishableKey && hasCloudPublicConfig() ? clerkPublishableKey : null;
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
{clerkPublishableKey && hasCloudPublicConfig() ? (
isElectron ? (
<ElectronClerkProvider publishableKey={clerkPublishableKey} passkeys={passkeys}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</ElectronClerkProvider>
) : (
<ClerkProvider publishableKey={clerkPublishableKey}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</ClerkProvider>
)
{cloudAuthPublishableKey ? (
<React.Suspense fallback={null}>
<CloudAuthRoot publishableKey={cloudAuthPublishableKey}>{app}</CloudAuthRoot>
</React.Suspense>
) : (
app
)}
@@ -0,0 +1,155 @@
import { useAtomValue } from "@effect/atom-react";
import { useEffect, useMemo } from "react";
import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { useClientSettings } from "../hooks/useSettings";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { resolveShortcutCommand } from "../keybindings";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
import { isPreviewFocused } from "../lib/previewFocus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { selectProjectGroupingSettings } from "../logicalProject";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
import { usePrimaryEnvironmentId } from "../state/environments";
import { useProjects } from "../state/entities";
import { primaryServerKeybindingsAtom } from "../state/server";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
export default function ChatRouteGlobalShortcuts() {
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
useHandleNewThread();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const projects = useProjects();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const projectGroupCount = useMemo(
() =>
buildSidebarProjectSnapshots({
projects,
settings: projectGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: () => null,
}).length,
[primaryEnvironmentId, projectGroupingSettings, projects],
);
const terminalOpen = useTerminalUiStateStore((state) =>
routeThreadRef
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
// The `previewOpen` shortcut-context flag here uses the store-only value;
// the URL-aware arbitration lives inside ChatView's `onTogglePreview`,
// which we invoke via the action bus to avoid duplicating the rule.
const previewOpen = useRightPanelStore((state) =>
routeThreadRef
? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
: false,
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
const command = resolveShortcutCommand(event, keybindings, {
context: {
terminalFocus: isTerminalFocused(),
terminalOpen,
previewFocus: isPreviewFocused(),
previewOpen,
},
});
if (isCommandPaletteOpen()) return;
if (event.key === "Escape" && selectedThreadKeysSize > 0) {
event.preventDefault();
clearSelection();
return;
}
if (command === "chat.newLocal" || command === "chat.new") {
event.preventDefault();
event.stopPropagation();
if (command === "chat.new" && sidebarV2Enabled && projectGroupCount > 1) {
openCommandPalette({ open: "new-thread-in" });
return;
}
void startNewThreadFromContext({
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
});
return;
}
if (command === "preview.toggle") {
event.preventDefault();
event.stopPropagation();
if (!routeThreadRef) return;
if (!isPreviewSupportedInRuntime()) {
toastManager.add(
stackedThreadToast({
type: "info",
title: "Preview is desktop-only",
description: "Open T3 Code in the desktop app to use the in-app preview.",
}),
);
return;
}
dispatchPreviewAction("toggle-panel");
return;
}
// The remaining preview commands only fire when the panel is the
// currently-focused tenant. The `when: previewFocus` rule already
// gates this, but defend against the keybinding being misconfigured.
if (
command === "preview.refresh" ||
command === "preview.focusUrl" ||
command === "preview.zoomIn" ||
command === "preview.zoomOut" ||
command === "preview.resetZoom"
) {
event.preventDefault();
event.stopPropagation();
const action =
command === "preview.refresh"
? "refresh"
: command === "preview.focusUrl"
? "focus-url"
: command === "preview.zoomIn"
? "zoom-in"
: command === "preview.zoomOut"
? "zoom-out"
: "reset-zoom";
dispatchPreviewAction(action);
}
};
window.addEventListener("keydown", onWindowKeyDown);
return () => window.removeEventListener("keydown", onWindowKeyDown);
}, [
activeDraftThread,
activeThread,
clearSelection,
defaultProjectRef,
handleNewThread,
keybindings,
previewOpen,
projectGroupCount,
routeThreadRef,
selectedThreadKeysSize,
sidebarV2Enabled,
terminalOpen,
]);
return null;
}
+153
View File
@@ -0,0 +1,153 @@
import { useAtomValue } from "@effect/atom-react";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { useEffect, useEffectEvent, useRef, useState } from "react";
import {
createKeybindingsUpdateToastController,
type KeybindingsUpdateToastController,
} from "../components/KeybindingsUpdateToast.logic";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { useClientSettings } from "../hooks/useSettings";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKeyFromPath,
selectProjectGroupingSettings,
} from "../logicalProject";
import { shellEnvironment } from "../state/shell";
import { useAtomCommand } from "../state/use-atom-command";
import { usePrimaryEnvironment } from "../state/environments";
import { readProject, setActiveEnvironmentId } from "../state/entities";
import {
primaryServerConfigAtom,
primaryServerConfigEventAtom,
primaryServerWelcomeAtom,
} from "../state/server";
import { useUiStateStore } from "../uiStateStore";
export default function EventRouter() {
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const primaryEnvironment = usePrimaryEnvironment();
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
reportFailure: false,
});
const serverConfig = useAtomValue(primaryServerConfigAtom);
const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const handledConfigEventRef = useRef(serverConfigEvent);
const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
createKeybindingsUpdateToastController({}),
);
const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
if (!payload) return;
setActiveEnvironmentId(payload.environment.environmentId);
void (async () => {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) return;
const bootstrapProject = readProject(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
);
const bootstrapProjectKey =
(bootstrapProject
? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
: null) ??
(serverConfig?.cwd
? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
: null) ??
scopedProjectKey(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
);
useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
if (
readPathname() !== "/" ||
handledBootstrapThreadIdRef.current === payload.bootstrapThreadId
) {
return;
}
await navigate({
to: "/$environmentId/$threadId",
params: {
environmentId: payload.environment.environmentId,
threadId: payload.bootstrapThreadId,
},
replace: true,
});
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
})().catch(() => undefined);
});
const handleServerConfigUpdated = useEffectEvent(() => {
const decision = keybindingsToastController.handle(serverConfigEvent);
if (!decision) return;
if (decision._tag === "Success") {
toastManager.add({
type: "success",
title: "Keybindings updated",
description: "Keybindings configuration reloaded successfully.",
});
return;
}
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Invalid keybindings configuration",
description: decision.message,
actionVariant: "outline",
actionProps: {
children: "Open keybindings.json",
onClick: () => {
if (!serverConfig || !primaryEnvironment) return;
const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
if (!editor) return;
void (async () => {
const result = await openInEditor({
environmentId: primaryEnvironment.environmentId,
input: {
cwd: serverConfig.keybindingsConfigPath,
editor,
},
});
if (result._tag === "Success") return;
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open keybindings file",
description:
error instanceof Error ? error.message : "Unknown error opening file.",
}),
);
})();
},
},
}),
);
});
useEffect(() => {
if (serverConfig) setActiveEnvironmentId(serverConfig.environment.environmentId);
}, [serverConfig]);
useEffect(() => {
handleWelcome(serverWelcome);
}, [serverWelcome]);
useEffect(() => {
if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) return;
handledConfigEventRef.current = serverConfigEvent;
handleServerConfigUpdated();
}, [serverConfigEvent]);
return null;
}
@@ -0,0 +1,60 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { RotateCcwIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
import { Button } from "../components/ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
import { SidebarInset } from "../components/ui/sidebar";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { useProjects, useThreadShells } from "../state/entities";
export default function ExistingProjectIndex() {
const projects = useProjects();
const threads = useThreadShells();
const handleNewThread = useNewThreadHandler();
const startingRef = useRef(false);
const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });
const mostRecentProject = useMemo(
() => sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null,
[projects, threads],
);
useEffect(() => {
if (mostRecentProject === null || startingRef.current) return;
startingRef.current = true;
void handleNewThread(scopeProjectRef(mostRecentProject.environmentId, mostRecentProject.id), {
replace: true,
}).catch(() => {
startingRef.current = false;
setStartState((state) => ({ ...state, failed: true }));
});
}, [handleNewThread, mostRecentProject, startState.retryRequest]);
return startState.failed ? (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<Empty className="flex-1">
<EmptyHeader className="max-w-md">
<EmptyTitle className="text-foreground text-xl">Couldn’t start a new thread</EmptyTitle>
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
The project is still available. Try opening the draft again.
</EmptyDescription>
<div className="mt-5 flex justify-center">
<Button
size="sm"
onClick={() => {
setStartState((state) => ({
failed: false,
retryRequest: state.retryRequest + 1,
}));
}}
>
<RotateCcwIcon className="size-4" />
Try again
</Button>
</div>
</EmptyHeader>
</Empty>
</SidebarInset>
) : null;
}
+71 -204
View File
@@ -1,80 +1,52 @@
import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
Outlet,
createRootRoute,
type ErrorComponentProps,
useLocation,
useNavigate,
} from "@tanstack/react-router";
import { useEffect, useEffectEvent, useRef, useState } from "react";
import { lazy, Suspense, useEffect } from "react";
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";
import { resolveServerBackedAppDisplayName } from "../branding.logic";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { CommandPalette } from "../components/CommandPalette";
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
import { CommandPaletteShell } from "../components/CommandPaletteShell";
import { Button } from "../components/ui/button";
import {
AnchoredToastProvider,
stackedThreadToast,
ToastProvider,
toastManager,
} from "../components/ui/toast";
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { STARTUP_OPTIONAL_UI_DELAY_MS, useAfterFirstPaint } from "../hooks/useAfterFirstPaint";
import { useClientSettings } from "../hooks/useSettings";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKeyFromPath,
selectProjectGroupingSettings,
} from "../logicalProject";
import { useUiStateStore } from "../uiStateStore";
import { syncBrowserChromeTheme } from "../hooks/useTheme";
import { configureClientTracing } from "../observability/clientTracing";
import { markStartupMilestone } from "../startupPerformance";
import { resolveInitialServerAuthGateState } from "../environments/primary";
import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
import { shellEnvironment } from "../state/shell";
import { useAtomValue } from "@effect/atom-react";
import { useAtomCommand } from "../state/use-atom-command";
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import { primaryServerConfigAtom } from "../state/server";
import {
primaryServerConfigAtom,
primaryServerConfigEventAtom,
primaryServerWelcomeAtom,
} from "../state/server";
import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
import {
createKeybindingsUpdateToastController,
type KeybindingsUpdateToastController,
} from "../components/KeybindingsUpdateToast.logic";
setActiveEnvironmentId,
useActiveEnvironmentId,
useAllEnvironmentShellsBootstrapped,
} from "../state/entities";
const AppOverlays = lazy(() => import("../components/AppOverlays"));
const EventRouter = lazy(() => import("./-EventRouter"));
const ProviderUpdateLaunchNotification = lazy(() =>
import("../components/ProviderUpdateLaunchNotification").then((module) => ({
default: module.ProviderUpdateLaunchNotification,
})),
);
export const Route = createRootRoute({
beforeLoad: async ({ location }) => {
if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
return {
authGateState: {
status: "hosted-pairing",
} as const,
};
}
if (isHostedStaticApp(new URL(window.location.href))) {
return {
authGateState: {
status: "hosted-static",
} as const,
};
}
const authGateState = await resolveInitialServerAuthGateState();
return {
authGateState,
};
const url = new URL(window.location.href);
const authGateState =
location.pathname === "/pair" && hasHostedPairingRequest(url)
? ({ status: "hosted-pairing" } as const)
: isHostedStaticApp(url)
? ({ status: "hosted-static" } as const)
: await resolveInitialServerAuthGateState();
markStartupMilestone("auth.gate.resolved");
return { authGateState };
},
component: RootRouteView,
errorComponent: RootRouteErrorView,
@@ -87,6 +59,12 @@ function RootRouteView() {
const pathname = useLocation({ select: (location) => location.pathname });
const { authGateState } = Route.useRouteContext();
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
const loadEventRouter = useAfterFirstPaint();
const loadOptionalUi = useAfterFirstPaint(STARTUP_OPTIONAL_UI_DELAY_MS);
useEffect(() => {
markStartupMilestone("react.usable");
}, []);
useEffect(() => {
const frame = window.requestAnimationFrame(() => {
@@ -116,11 +94,11 @@ function RootRouteView() {
}
const appShell = (
<CommandPalette>
<CommandPaletteShell>
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</CommandPalette>
</CommandPaletteShell>
);
return (
@@ -129,13 +107,19 @@ function RootRouteView() {
<DocumentTitleSync />
<GlassAppearanceSync />
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
<RelayClientInstallDialog />
<ConnectOnboardingDialog />
<SshPasswordPromptDialog />
<SlowRpcRequestToastCoordinator />
{primaryEnvironmentAuthenticated ? <StartupConnectionMilestones /> : null}
{loadOptionalUi ? (
<Suspense fallback={null}>
<AppOverlays />
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
</Suspense>
) : null}
<HostedStaticEnvironmentBootstrap />
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
{primaryEnvironmentAuthenticated && loadEventRouter ? (
<Suspense fallback={null}>
<EventRouter />
</Suspense>
) : null}
{appShell}
</AnchoredToastProvider>
</ToastProvider>
@@ -165,6 +149,30 @@ function DocumentTitleSync() {
useEffect(() => {
document.title = title;
}, [title]);
useEffect(() => {
if (primaryServerVersion !== null) {
markStartupMilestone("config.received");
}
}, [primaryServerVersion]);
return null;
}
function StartupConnectionMilestones() {
const primaryEnvironment = usePrimaryEnvironment();
const shellsBootstrapped = useAllEnvironmentShellsBootstrapped();
useEffect(() => {
if (primaryEnvironment?.connection.phase === "connected") {
markStartupMilestone("ws.open");
}
}, [primaryEnvironment?.connection.phase]);
useEffect(() => {
if (shellsBootstrapped) {
markStartupMilestone("shell.live");
}
}, [shellsBootstrapped]);
return null;
}
@@ -275,144 +283,3 @@ function AuthenticatedTracingBootstrap() {
return null;
}
function EventRouter() {
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const primaryEnvironment = usePrimaryEnvironment();
const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
reportFailure: false,
});
const serverConfig = useAtomValue(primaryServerConfigAtom);
const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const handledConfigEventRef = useRef(serverConfigEvent);
const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
createKeybindingsUpdateToastController({}),
);
const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
if (!payload) return;
setActiveEnvironmentId(payload.environment.environmentId);
void (async () => {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
const bootstrapProject = readProject(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
);
const bootstrapProjectKey =
(bootstrapProject
? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
: null) ??
(serverConfig?.cwd
? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
: null) ??
scopedProjectKey(
scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
);
useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
if (readPathname() !== "/") {
return;
}
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
return;
}
await navigate({
to: "/$environmentId/$threadId",
params: {
environmentId: payload.environment.environmentId,
threadId: payload.bootstrapThreadId,
},
replace: true,
});
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
})().catch(() => undefined);
});
const handleServerConfigUpdated = useEffectEvent(() => {
const decision = keybindingsToastController.handle(serverConfigEvent);
if (!decision) {
return;
}
if (decision._tag === "Success") {
toastManager.add({
type: "success",
title: "Keybindings updated",
description: "Keybindings configuration reloaded successfully.",
});
return;
}
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Invalid keybindings configuration",
description: decision.message,
actionVariant: "outline",
actionProps: {
children: "Open keybindings.json",
onClick: () => {
if (!serverConfig || !primaryEnvironment) {
return;
}
const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
if (!editor) {
return;
}
void (async () => {
const result = await openInEditor({
environmentId: primaryEnvironment.environmentId,
input: {
cwd: serverConfig.keybindingsConfigPath,
editor,
},
});
if (result._tag === "Success") {
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open keybindings file",
description:
error instanceof Error ? error.message : "Unknown error opening file.",
}),
);
})();
},
},
}),
);
});
useEffect(() => {
if (!serverConfig) {
return;
}
setActiveEnvironmentId(serverConfig.environment.environmentId);
}, [serverConfig]);
useEffect(() => {
handleWelcome(serverWelcome);
}, [serverWelcome]);
useEffect(() => {
if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
return;
}
handledConfigEventRef.current = serverConfigEvent;
handleServerConfigUpdated();
}, [serverConfigEvent]);
return null;
}
+11 -67
View File
@@ -1,25 +1,20 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { createFileRoute, Link } from "@tanstack/react-router";
import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LinkIcon, PlusIcon } from "lucide-react";
import { lazy, Suspense, useCallback } from "react";
import { openCommandPalette } from "../commandPaletteBus";
import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
import { Button } from "../components/ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
import { SidebarInset } from "../components/ui/sidebar";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import {
useAllEnvironmentShellsBootstrapped,
useProjects,
useThreadShells,
} from "../state/entities";
import { useAllEnvironmentShellsBootstrapped, useProjects } from "../state/entities";
import { useEnvironments } from "../state/environments";
import { APP_DISPLAY_NAME } from "~/branding";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { cn } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
const ExistingProjectIndex = lazy(() => import("./-ExistingProjectIndex"));
function ChatIndexRouteView() {
const { authGateState } = Route.useRouteContext();
const { environments } = useEnvironments();
@@ -38,72 +33,21 @@ function ChatIndexRouteView() {
*/
function IndexDraftLanding() {
const projects = useProjects();
const threads = useThreadShells();
const bootstrapped = useAllEnvironmentShellsBootstrapped();
const handleNewThread = useNewThreadHandler();
const startingRef = useRef(false);
const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });
const mostRecentProject = useMemo(
() =>
bootstrapped
? (sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null)
: null,
[bootstrapped, projects, threads],
);
useEffect(() => {
if (mostRecentProject === null || startingRef.current) {
return;
}
startingRef.current = true;
void handleNewThread(scopeProjectRef(mostRecentProject.environmentId, mostRecentProject.id), {
replace: true,
}).catch(() => {
startingRef.current = false;
setStartState((state) => ({ ...state, failed: true }));
});
}, [handleNewThread, mostRecentProject, startState.retryRequest]);
if (!bootstrapped) {
return null;
}
if (mostRecentProject !== null) {
return startState.failed ? (
<DraftStartError
onRetry={() => {
setStartState((state) => ({
failed: false,
retryRequest: state.retryRequest + 1,
}));
}}
/>
) : null;
if (projects.length > 0) {
return (
<Suspense fallback={null}>
<ExistingProjectIndex />
</Suspense>
);
}
return <NoProjectsHero />;
}
function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<Empty className="flex-1">
<EmptyHeader className="max-w-md">
<EmptyTitle className="text-foreground text-xl">Couldn’t start a new thread</EmptyTitle>
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
The project is still available. Try opening the draft again.
</EmptyDescription>
<div className="mt-5 flex justify-center">
<Button size="sm" onClick={onRetry}>
<RotateCcwIcon className="size-4" />
Try again
</Button>
</div>
</EmptyHeader>
</Empty>
</SidebarInset>
);
}
function NoProjectsHero() {
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
+11 -174
View File
@@ -1,183 +1,20 @@
import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import { useAtomValue } from "@effect/atom-react";
import { useEffect, useMemo } from "react";
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
import { lazy, Suspense } from "react";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { useClientSettings } from "../hooks/useSettings";
import { openCommandPalette } from "../commandPaletteBus";
import { useProjects } from "../state/entities";
import { usePrimaryEnvironmentId } from "../state/environments";
import { selectProjectGroupingSettings } from "../logicalProject";
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
import { isPreviewFocused } from "../lib/previewFocus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { resolveShortcutCommand } from "../keybindings";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { STARTUP_OPTIONAL_UI_DELAY_MS, useAfterFirstPaint } from "../hooks/useAfterFirstPaint";
function ChatRouteGlobalShortcuts() {
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
useHandleNewThread();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const projects = useProjects();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const projectGroupCount = useMemo(
() =>
buildSidebarProjectSnapshots({
projects,
settings: projectGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: () => null,
}).length,
[primaryEnvironmentId, projectGroupingSettings, projects],
);
const terminalOpen = useTerminalUiStateStore((state) =>
routeThreadRef
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
// The `previewOpen` shortcut-context flag here uses the store-only value;
// the URL-aware arbitration lives inside ChatView's `onTogglePreview`,
// which we invoke via the action bus to avoid duplicating the rule.
const previewOpen = useRightPanelStore((state) =>
routeThreadRef
? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
: false,
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
const command = resolveShortcutCommand(event, keybindings, {
context: {
terminalFocus: isTerminalFocused(),
terminalOpen,
previewFocus: isPreviewFocused(),
previewOpen,
},
});
if (isCommandPaletteOpen()) {
return;
}
if (event.key === "Escape" && selectedThreadKeysSize > 0) {
event.preventDefault();
clearSelection();
return;
}
if (command === "chat.newLocal") {
event.preventDefault();
event.stopPropagation();
void startNewThreadFromContext({
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
});
return;
}
if (command === "chat.new") {
event.preventDefault();
event.stopPropagation();
// Sidebar v2 routes creation through the command palette whenever
// there is a real choice to make; v1 (and single-project setups)
// keep the immediate contextual create.
if (sidebarV2Enabled && projectGroupCount > 1) {
openCommandPalette({ open: "new-thread-in" });
return;
}
void startNewThreadFromContext({
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
});
return;
}
if (command === "preview.toggle") {
event.preventDefault();
event.stopPropagation();
if (!routeThreadRef) return;
if (!isPreviewSupportedInRuntime()) {
toastManager.add(
stackedThreadToast({
type: "info",
title: "Preview is desktop-only",
description: "Open T3 Code in the desktop app to use the in-app preview.",
}),
);
return;
}
dispatchPreviewAction("toggle-panel");
return;
}
// The remaining preview commands only fire when the panel is the
// currently-focused tenant. The `when: previewFocus` rule already
// gates this, but defend against the keybinding being misconfigured.
if (
command === "preview.refresh" ||
command === "preview.focusUrl" ||
command === "preview.zoomIn" ||
command === "preview.zoomOut" ||
command === "preview.resetZoom"
) {
event.preventDefault();
event.stopPropagation();
const action =
command === "preview.refresh"
? "refresh"
: command === "preview.focusUrl"
? "focus-url"
: command === "preview.zoomIn"
? "zoom-in"
: command === "preview.zoomOut"
? "zoom-out"
: "reset-zoom";
dispatchPreviewAction(action);
}
};
window.addEventListener("keydown", onWindowKeyDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [
activeDraftThread,
activeThread,
clearSelection,
handleNewThread,
keybindings,
defaultProjectRef,
previewOpen,
projectGroupCount,
routeThreadRef,
selectedThreadKeysSize,
sidebarV2Enabled,
terminalOpen,
]);
return null;
}
const ChatRouteGlobalShortcuts = lazy(() => import("./-ChatRouteGlobalShortcuts"));
function ChatRouteLayout() {
const loadGlobalShortcuts = useAfterFirstPaint(STARTUP_OPTIONAL_UI_DELAY_MS);
return (
<>
<ChatRouteGlobalShortcuts />
{loadGlobalShortcuts ? (
<Suspense fallback={null}>
<ChatRouteGlobalShortcuts />
</Suspense>
) : null}
<Outlet />
</>
);
+13
View File
@@ -0,0 +1,13 @@
const markedStartupMilestones = new Set<string>();
/**
* Records startup timing without coupling it to tracing, which is configured
* only after authentication.
*/
export function markStartupMilestone(name: string): void {
if (markedStartupMilestones.has(name) || typeof performance === "undefined") {
return;
}
markedStartupMilestones.add(name);
performance.mark(name);
}
+78 -30
View File
@@ -7,14 +7,27 @@ import "vite-plus/test/config";
import { defineConfig } from "vite-plus";
import pkg from "./package.json" with { type: "json" };
import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
import { loadRepoEnv } from "../../scripts/lib/public-config";
const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
// Single-origin dev is signalled positively, because it cannot be inferred
// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
// a developer with either URL in their `.env` gets it back here. Baking it then
// pins the client to localhost and breaks every non-localhost origin — the
// exact failure single-origin mode exists to prevent, and an invisible one
// since the page still loads.
const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
const port = Number(process.env.PORT ?? 5733);
const host = process.env.HOST?.trim() || "localhost";
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const explicitHost = process.env.HOST?.trim();
const host = explicitHost || "localhost";
const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
@@ -39,9 +52,9 @@ const configuredHostedAppUrl = (() => {
})();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
// Vite 8.1's experimental bundled dev mode: serves rolldown-bundled chunks in
// dev for much faster startup/reload on large module graphs, with HMR served
// as hot patches. Opt-in while experimental: T3CODE_BUNDLED_DEV=1 pnpm dev:web
// Vite 8.1's experimental bundled dev mode. Keep this opt-in until its cold
// build is reliably faster than the regular dev server:
// T3CODE_BUNDLED_DEV=1 vp run dev
const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();
const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";
@@ -65,7 +78,20 @@ const unitTestProject = {
},
} satisfies TestProjectInlineConfiguration;
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
function resolveDevProxyTarget(
backendPort: string | undefined,
wsUrl: string | undefined,
): string | undefined {
// Browser dev is single-origin: the backend port is proxied through this
// server so the app works from any origin (localhost, tailnet, LAN, phone).
// T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
const port = Number(backendPort?.trim());
if (Number.isInteger(port) && port > 0) {
return `http://localhost:${port}/`;
}
// dev:desktop still points the renderer straight at the backend, so fall
// back to deriving the target from the explicit websocket URL.
if (!wsUrl) {
return undefined;
}
@@ -86,12 +112,22 @@ function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
}
}
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
// Vite rejects requests whose Host header isn't localhost, which blocks sharing
// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
// Anything else (ngrok, a LAN IP alias) goes through the env var.
const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
const allowedHosts = [".ts.net", ...configuredAllowedHosts];
export default defineConfig(() => {
return {
plugins: [
tanstackRouter(),
tanstackRouter({ autoCodeSplitting: !bundledDev }),
react(),
babel({
// We need to be explicit about the parser options after moving to @vitejs/plugin-react v6.0.0
@@ -105,7 +141,6 @@ export default defineConfig(() => {
],
optimizeDeps: {
include: [
"@clerk/clerk-js",
"@clerk/react/internal",
"@pierre/diffs",
"@pierre/diffs/editor",
@@ -119,6 +154,10 @@ export default defineConfig(() => {
define: {
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
// Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
// under single-origin dev this must stay empty even when a `.env`
// supplies it, so the client falls back to window.location.origin.
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
"import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
"import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
@@ -145,32 +184,41 @@ export default defineConfig(() => {
host,
port,
strictPort: true,
allowedHosts,
...(devProxyTarget
? {
proxy: {
"/.well-known": {
target: devProxyTarget,
changeOrigin: true,
},
"/api": {
target: devProxyTarget,
changeOrigin: true,
},
"/attachments": {
target: devProxyTarget,
changeOrigin: true,
},
// One entry per shared prefix; the server's dev catch-all 404s the
// same list, so the two sides cannot drift. `/ws` is the app's own
// socket — Vite's HMR socket is matched separately and exactly
// (path "/" plus a vite-hmr subprotocol), so the two upgrade
// handlers don't collide.
proxy: Object.fromEntries(
DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
prefix,
{
target: devProxyTarget,
changeOrigin: true,
...(prefix === "/ws" ? { ws: true } : {}),
},
]),
),
}
: {}),
// Electron's BrowserWindow needs the HMR socket pinned to an explicit
// host to connect reliably; dev:desktop is the only mode that sets HOST.
// Everywhere else, leaving this unset lets the client derive it from the
// page origin, which is what makes HMR work over Tailscale/LAN instead of
// failing an attempt against the wrong machine's localhost first.
// (Vite 8 logs connection state via console.debug — enable "Verbose".)
...(explicitHost
? {
hmr: {
protocol: "ws",
host: explicitHost,
clientPort: port,
},
}
: {}),
hmr: {
// Explicit config so Vite's HMR WebSocket connects reliably
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
host,
clientPort: port,
},
},
build: {
outDir: "dist",
+10 -1
View File
@@ -1,9 +1,11 @@
# Scripts
- `vp run dev` — Starts contracts, server, and web in watch mode.
- `vp run dev --share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit.
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
- `vp run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `<worktree>/.t3/userdata`. Pass `--home-dir <path>` to choose another isolated directory explicitly. Submodules are not worktrees and keep the normal precedence.
- From the **main checkout**, dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
- Pass dev-runner flags directly after the root task name, for example:
`vp run dev --home-dir /tmp/t3code-dev`
@@ -23,6 +25,7 @@
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/prod/black-macos-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3code://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `vp run dist:desktop:dmg -- --keep-stage`
@@ -36,6 +39,12 @@
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
## Browser development
`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the server, allowing the same bundle to work from localhost or a tailnet hostname.
Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied or the web port is blocked by browsers, so treat the `[dev-runner]` output as authoritative.
## Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
+2
View File
@@ -5,6 +5,7 @@
"scripts": {
"prepare": "effect-tsgo patch && vp config --no-agent",
"dev": "node scripts/dev-runner.ts dev",
"dev:share": "node scripts/dev-runner.ts dev --share",
"dev:server": "node scripts/dev-runner.ts dev:server",
"dev:web": "node scripts/dev-runner.ts dev:web",
"dev:marketing": "vp run --filter @t3tools/marketing dev",
@@ -14,6 +15,7 @@
"start:marketing": "vp run --filter @t3tools/marketing preview",
"start:mock-update-server": "node scripts/mock-update-server.ts",
"screenshots:mobile": "node scripts/mobile-showcase.ts",
"profile:startup": "node scripts/profile-startup.ts",
"icons:export": "node scripts/export-brand-icons.ts",
"icons:check": "node scripts/export-brand-icons.ts --check",
"build": "vp run --filter './apps/*' --filter './packages/*' --filter './oxlint-plugin-t3code' --filter './scripts' build",
+8
View File
@@ -194,6 +194,14 @@
"./httpReadiness": {
"types": "./src/httpReadiness.ts",
"import": "./src/httpReadiness.ts"
},
"./devHome": {
"types": "./src/devHome.ts",
"import": "./src/devHome.ts"
},
"./devProxy": {
"types": "./src/devProxy.ts",
"import": "./src/devProxy.ts"
}
},
"scripts": {
+106
View File
@@ -0,0 +1,106 @@
// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as Effect from "effect/Effect";
import { resolveGitWorktreePath, resolveWorktreeT3Home } from "./devHome.ts";
const makeRepo = (
kind:
| "worktree"
| "checkout"
| "bare"
| "submodule"
| "unreadable-git-file"
| "bare-repo-worktree"
| "custom-common-dir-worktree",
) =>
Effect.acquireRelease(
Effect.sync(() => {
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devhome-"));
if (kind === "worktree") {
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /elsewhere/.git/worktrees/x\n");
} else if (kind === "bare-repo-worktree") {
// `git worktree add` from a bare repo: the common dir is `<name>.git`.
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/myrepo.git/worktrees/x\n");
} else if (kind === "custom-common-dir-worktree") {
// $GIT_COMMON_DIR need not be named `.git` at all.
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/store/worktrees/x\n");
} else if (kind === "submodule") {
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: ../.git/modules/sub\n");
} else if (kind === "unreadable-git-file") {
NodeFS.writeFileSync(NodePath.join(root, ".git"), "not a gitdir pointer\n");
} else if (kind === "checkout") {
NodeFS.mkdirSync(NodePath.join(root, ".git"));
}
const nested = NodePath.join(root, "apps", "web", "src");
NodeFS.mkdirSync(nested, { recursive: true });
return { root, nested };
}),
({ root }) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
);
describe("resolveGitWorktreePath", () => {
it.effect("finds a worktree root from a nested directory", () =>
Effect.gen(function* () {
const { root, nested } = yield* makeRepo("worktree");
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("reports a main checkout as not a linked worktree", () =>
Effect.gen(function* () {
const { nested } = yield* makeRepo("checkout");
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("reports a directory outside a repository", () =>
Effect.gen(function* () {
const { nested } = yield* makeRepo("bare");
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("reports a submodule as not a linked worktree", () =>
Effect.gen(function* () {
const { nested } = yield* makeRepo("submodule");
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("reports a .git file without a usable gitdir pointer", () =>
Effect.gen(function* () {
const { nested } = yield* makeRepo("unreadable-git-file");
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("finds a worktree of a bare repository", () =>
Effect.gen(function* () {
const { root, nested } = yield* makeRepo("bare-repo-worktree");
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("finds a worktree whose common dir is not named .git", () =>
Effect.gen(function* () {
const { root, nested } = yield* makeRepo("custom-common-dir-worktree");
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
describe("resolveWorktreeT3Home", () => {
it.effect("answers with .t3 before the dev runner creates it", () =>
Effect.gen(function* () {
const { root, nested } = yield* makeRepo("worktree");
const home = yield* resolveWorktreeT3Home(nested);
assert.equal(home, NodePath.join(NodePath.resolve(root), ".t3"));
assert.isFalse(NodeFS.existsSync(home ?? ""));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
+103
View File
@@ -0,0 +1,103 @@
/**
* Where development state lives, and how to keep it away from the shared
* `~/.t3` that a user's installed T3 Code runs against.
*
* A linked git worktree gets its own (gitignored) `.t3`: feature work in a
* throwaway branch must not share a database with the real app, and an ambient
* `T3CODE_HOME` counts as an explicit base dir — flipping the state directory
* from `<base>/dev` to `<base>/userdata`, the live production database.
*/
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
/**
* A `.git` file points at the real git directory. A linked worktree's lives at
* `<common-dir>/worktrees/<name>`; a submodule's at
* `<super-git-dir>/modules/<name>`. Both are files, so the pointer — not the
* file-vs-directory distinction alone — is what identifies a worktree.
*
* The common dir is not necessarily named `.git`: a worktree of a bare repo
* points at `<repo>.git/worktrees/<name>`, and `$GIT_COMMON_DIR` can be
* anything. So match on the `worktrees/<name>` tail, which git always uses,
* rather than on the name of the directory containing it.
*/
const pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolean => {
const gitdir = gitFileContents
.split(/\r?\n/)
.map((line) => line.trim())
.find((line) => line.startsWith("gitdir:"))
?.slice("gitdir:".length)
.trim();
if (gitdir === undefined || gitdir.length === 0) {
return false;
}
// Compare as path segments so a directory merely named `…worktrees…` cannot
// match as a substring. Trailing separators normalize away first.
const segments = path
.normalize(gitdir.replaceAll("\\", "/"))
.split(/[/\\]/)
.filter((segment) => segment.length > 0);
// `<common-dir>/worktrees/<name>`: `worktrees` is the penultimate segment,
// and something must precede it. This excludes `<git-dir>/modules/<name>`.
return segments.length >= 3 && segments.at(-2) === "worktrees";
};
/**
* The path of the linked git worktree containing `cwd`, or undefined when
* `cwd` is not inside one. Git marks a linked worktree by making `.git` a file
* whose `gitdir:` points into the repository's `.git/worktrees`.
*
* Walks up to the repository root, so running from a subdirectory resolves the
* same worktree as running from the top.
*/
export const resolveGitWorktreePath = (
cwd: string,
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
let directory = path.resolve(cwd);
for (;;) {
const gitPath = path.join(directory, ".git");
const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);
if (Option.isSome(info)) {
// A directory means the main checkout. Stop either way: nesting one
// repository inside another does not make the outer one this root.
if (info.value.type !== "File") {
return undefined;
}
// A submodule also has a `.git` file, but it is not a worktree of this
// repository and gets no worktree-local home.
const contents = yield* fileSystem
.readFileString(gitPath)
.pipe(Effect.orElseSucceed(() => ""));
return pointsAtLinkedWorktree(contents, path) ? directory : undefined;
}
const parent = path.dirname(directory);
if (parent === directory) {
return undefined;
}
directory = parent;
}
});
/**
* The worktree-local data directory for `cwd`, or undefined outside a linked
* worktree. Deliberately does not require the directory to exist yet: falling
* back because it is missing would send callers at the shared home.
*/
export const resolveWorktreeT3Home = (
cwd: string,
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
Effect.gen(function* () {
const worktreePath = yield* resolveGitWorktreePath(cwd);
if (worktreePath === undefined) {
return undefined;
}
const path = yield* Path.Path;
return path.join(worktreePath, ".t3");
});
+17
View File
@@ -0,0 +1,17 @@
/**
* Backend paths the web dev server proxies in single-origin browser dev.
*
* Two consumers must agree on this list: the Vite proxy map
* (apps/web/vite.config.ts) that forwards these to the backend, and the
* server's dev catch-all (apps/server/src/http.ts) that 404s them instead of
* redirecting back to Vite. Drift is silent and nasty in both directions — a
* prefix only Vite knows gets answered with index.html; a prefix only the
* server knows redirect-loops through the proxy.
*/
export const DEV_PROXIED_PATH_PREFIXES = ["/api", "/oauth", "/.well-known", "/ws"] as const;
export function isDevProxiedPath(pathname: string): boolean {
return DEV_PROXIED_PATH_PREFIXES.some(
(prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),
);
}
+7
View File
@@ -30,6 +30,13 @@ export const HostProcessEnvironment = Context.Reference<NodeJS.ProcessEnv>(
},
);
export const HostProcessWorkingDirectory = Context.Reference<string>(
"@t3tools/shared/hostProcess/HostProcessWorkingDirectory",
{
defaultValue: () => process.cwd(),
},
);
export const HostProcessExecutablePath = Context.Reference<string>(
"@t3tools/shared/hostProcess/HostProcessExecutablePath",
{
+62
View File
@@ -25,6 +25,44 @@ import {
} from "./tailscale.ts";
const encoder = new TextEncoder();
/**
* Asserts nothing reachable from `error` contains `secret`. Recurses through
* nested objects, arrays, and `cause` chains rather than checking only
* top-level strings: a leak one level down (say, a wrapped cause carrying raw
* stderr) is just as visible in a log, and a shallow check would pass it.
*
* Walks values instead of serializing so it holds for fields added later, and
* tracks visited objects so a cyclic cause chain terminates.
*/
function assertCarriesNoSecret(error: object, secret: string): void {
const seen = new WeakSet<object>();
const walk = (value: unknown, path: string): void => {
if (typeof value === "string") {
assert.notInclude(value, secret, `${path} leaked stderr`);
return;
}
if (typeof value !== "object" || value === null || seen.has(value)) {
return;
}
seen.add(value);
if (Array.isArray(value)) {
value.forEach((entry, index) => walk(entry, `${path}[${String(index)}]`));
return;
}
// `message` and `cause` are getters on Error subclasses, so they are not
// own enumerable properties and Object.entries alone would skip them.
walk((value as { message?: unknown }).message, `${path}.message`);
walk((value as { cause?: unknown }).cause, `${path}.cause`);
for (const [key, nested] of Object.entries(value)) {
walk(nested, `${path}.${key}`);
}
};
walk(error, "error");
}
const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`;
@@ -194,6 +232,26 @@ describe("tailscale", () => {
assert.notProperty(error, "stderr");
assert.notInclude(error.message, "tskey-auth-secret-token-value");
assert.equal(error.message, "tailscale status exited with code 7.");
assert.equal(error.stderrDiagnostic, "not-logged-in");
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
});
});
it.effect("classifies unrecognized stderr without quoting it", () => {
const layer = mockSpawnerLayer(() => ({
code: 3,
stderr: "something novel went wrong for node fluffy-badger tskey-auth-secret-token-value",
}));
return Effect.gen(function* () {
const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
assert.instanceOf(error, TailscaleCommandExitError);
// Unmatched stderr degrades to "unknown" rather than passing text
// through — that fallback is what keeps novel output from leaking.
assert.equal(error.stderrDiagnostic, "unknown");
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
assertCarriesNoSecret(error, "fluffy-badger");
});
});
@@ -253,6 +311,10 @@ describe("tailscale", () => {
assert.notProperty(error, "command");
assert.notProperty(error, "stderr");
assert.notInclude(error.message, "tskey-auth-secret-token-value");
// The diagnostic classifies the failure without quoting stderr, so the
// key cannot reach a log through it either.
assert.equal(error.stderrDiagnostic, "permission-denied");
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
});
});
+43
View File
@@ -23,6 +23,37 @@ const TailscaleCommandContext = {
argumentCount: Schema.Number,
};
/**
* Failure kinds we can name without quoting the CLI. Anything unrecognized
* becomes "unknown" rather than falling back to raw text — stderr can contain
* auth keys (`tskey-…`) and node names, and these labels are logged.
*/
export const TailscaleStderrDiagnostic = Schema.Literals([
"no-existing-handler",
"not-logged-in",
"permission-denied",
"unknown",
]);
export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
// Matched against stderr, most specific first. Patterns are deliberately short
// and anchored on tailscale's own wording.
const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
> = [
[/handler does not exist/i, "no-existing-handler"],
[/not logged in|logged out|needs? login/i, "not-logged-in"],
[/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
];
/** Classifies stderr into a safe label, dropping the text itself. */
export const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
if (stderr.trim().length === 0) {
return undefined;
}
return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
};
export class TailscaleCommandSpawnError extends Schema.TaggedErrorClass<TailscaleCommandSpawnError>()(
"TailscaleCommandSpawnError",
{
@@ -54,6 +85,12 @@ export class TailscaleCommandExitError extends Schema.TaggedErrorClass<Tailscale
exitCode: Schema.Number,
stdoutLength: Schema.optional(Schema.Number),
stderrLength: Schema.Number,
// A classified diagnostic, never raw CLI output. `tailscale` prints auth
// keys and node identifiers into stderr, and this field is surfaced in
// dev-runner logs — so it carries only a known-safe label from the closed
// set below. Callers that need to recognize a specific failure (e.g.
// `serve off` on a port with no mapping) match on the label.
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
},
) {
override get message(): string {
@@ -212,6 +249,9 @@ export const readTailscaleStatus = Effect.gen(function* () {
exitCode,
stdoutLength: stdout.length,
stderrLength: stderr.length,
...(stderrDiagnosticOf(stderr) !== undefined
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
: {}),
});
}
return yield* parseTailscaleStatus(stdout);
@@ -275,6 +315,9 @@ const runTailscaleCommand = (
...commandContext,
exitCode,
stderrLength: stderr.length,
...(stderrDiagnosticOf(stderr) !== undefined
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
: {}),
});
}
}).pipe(
+3
View File
@@ -905,6 +905,9 @@ importers:
'@t3tools/shared':
specifier: workspace:*
version: link:../packages/shared
'@t3tools/tailscale':
specifier: workspace:*
version: link:../packages/tailscale
effect:
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
+553 -2
View File
@@ -1,6 +1,14 @@
// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import {
HostProcessEnvironment,
HostProcessPlatform,
HostProcessWorkingDirectory,
} from "@t3tools/shared/hostProcess";
import { assert, describe, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
@@ -14,8 +22,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkPortAvailabilityOnHosts,
createDevRunnerEnv,
devPortProbeHosts,
findFirstAvailableOffset,
getDevRunnerModeArgs,
isBrowserAllowedPort,
resolveModePortOffsets,
resolveOffset,
runDevRunnerWithInput,
@@ -58,6 +68,7 @@ const devServerInput = {
port: 13_773,
devUrl: undefined,
dryRun: false,
share: false,
runArgs: ["--inspect", "secret-token-value"],
} as const;
@@ -336,8 +347,175 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
});
assert.equal(env.T3CODE_PORT, "13773");
assert.equal(env.PORT, "5733");
}),
);
// Browser dev is single-origin: Vite proxies the backend, and the client
// resolves it from window.location.origin. Baking a localhost URL here is
// what breaks sharing a dev server to another device.
for (const mode of ["dev", "dev:web"] as const) {
it.effect(`leaves the client backend URLs unset in ${mode} mode`, () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode,
baseEnv: {
VITE_HTTP_URL: "http://localhost:1234",
VITE_WS_URL: "ws://localhost:1234",
},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.VITE_HTTP_URL, undefined);
assert.equal(env.VITE_WS_URL, undefined);
assert.equal(env.T3CODE_PORT, "13773");
// Deleting the keys is not sufficient — vite.config.ts merges
// `.env`/`.env.local` underneath this env and would revive them, so
// the intent has to be stated positively.
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, "1");
}),
);
}
// Desktop pins the renderer at loopback deliberately; an ambient marker
// must not make Vite discard those URLs.
it.effect("clears the single-origin marker in dev:desktop mode", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:desktop",
baseEnv: { T3CODE_SINGLE_ORIGIN_DEV: "1" },
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, undefined);
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:13773");
}),
);
it.effect("clears the single-origin marker in dev:server mode", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:server",
baseEnv: { T3CODE_SINGLE_ORIGIN_DEV: "1" },
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, undefined);
assert.equal(env.VITE_HTTP_URL, "http://localhost:13773");
assert.equal(env.VITE_WS_URL, "ws://localhost:13773");
}),
);
// HOST is Vite's bind address and gates the HMR pin in vite.config.ts. An
// inherited one would survive into browser dev and point HMR at the wrong
// interface — invisible over a shared origin, since the page still loads.
for (const mode of ["dev", "dev:web"] as const) {
it.effect(`drops an inherited HOST in ${mode} mode`, () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode,
baseEnv: { HOST: "0.0.0.0" },
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.HOST, undefined);
}),
);
}
// --host configures the *backend* (T3CODE_HOST). It must not become Vite's
// bind address by way of an inherited HOST that happens to agree with it.
it.effect("drops an inherited HOST even when --host is given", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: { HOST: "0.0.0.0" },
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: "0.0.0.0",
port: undefined,
devUrl: undefined,
});
assert.equal(env.HOST, undefined);
assert.equal(env.T3CODE_HOST, "0.0.0.0");
}),
);
// Desktop sets HOST itself, so the clearing must not reach it.
it.effect("still pins HOST for dev:desktop", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:desktop",
baseEnv: { HOST: "0.0.0.0" },
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.HOST, "127.0.0.1");
}),
);
it.effect("keeps explicit backend URLs for the desktop renderer", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:desktop",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:13773");
assert.equal(env.VITE_WS_URL, "ws://127.0.0.1:13773");
}),
);
});
@@ -370,6 +548,41 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
}),
);
it.effect("skips browser-blocked web ports before probing availability", () =>
Effect.gen(function* () {
const probed: Array<{ port: number; role: string | undefined }> = [];
const offset = yield* findFirstAvailableOffset({
// 5733 + 833 = 6566, which browsers block as sane-port.
startOffset: 833,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: (port, role) => {
probed.push({ port, role });
return Effect.succeed(true);
},
});
assert.equal(offset, 834);
assert.deepStrictEqual(probed, [
{ port: 14_607, role: "server" },
{ port: 6567, role: "web" },
]);
}),
);
it.effect("does not reject a server-only offset because its unused web port is blocked", () =>
Effect.gen(function* () {
const offset = yield* findFirstAvailableOffset({
startOffset: 833,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: () => Effect.succeed(true),
});
assert.equal(offset, 833);
}),
);
it.effect("allows offsets where the non-required server port exceeds max", () =>
Effect.gen(function* () {
const offset = yield* findFirstAvailableOffset({
@@ -406,6 +619,19 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
);
});
describe("isBrowserAllowedPort", () => {
it.each([6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697])(
"rejects Fetch-blocked web port %s from the worktree offset range",
(port) => {
assert.equal(isBrowserAllowedPort(port), false);
},
);
it.each([5733, 5900, 6567, 6670, 8733])("allows browser-safe web port %s", (port) => {
assert.equal(isBrowserAllowedPort(port), true);
});
});
describe("checkPortAvailabilityOnHosts", () => {
it.effect("checks overlapping hosts sequentially to avoid self-interference", () =>
Effect.gen(function* () {
@@ -436,6 +662,59 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
);
});
describe("devPortProbeHosts", () => {
it.effect("probes loopback only when no bind host is configured", () =>
Effect.sync(() => {
assert.deepStrictEqual(devPortProbeHosts(undefined), ["127.0.0.1", "::1"]);
assert.deepStrictEqual(devPortProbeHosts(" "), ["127.0.0.1", "::1"]);
}),
);
// A port free on loopback can be taken on the interface the server will
// actually bind, so --host/T3CODE_HOST has to be probed as well.
it.effect("adds a non-loopback bind host to the probe list", () =>
Effect.sync(() => {
assert.deepStrictEqual(devPortProbeHosts("0.0.0.0"), ["127.0.0.1", "::1", "0.0.0.0"]);
assert.deepStrictEqual(devPortProbeHosts("192.168.1.10"), [
"127.0.0.1",
"::1",
"192.168.1.10",
]);
}),
);
it.effect("does not probe loopback twice when it is the configured host", () =>
Effect.sync(() => {
assert.deepStrictEqual(devPortProbeHosts("127.0.0.1"), ["127.0.0.1", "::1"]);
}),
);
// Only the backend honours --host/T3CODE_HOST. Vite reads HOST (set for
// desktop only), so judging the web port against the backend's interface
// would reject ports for a server that never binds there.
it.effect("passes the port role so only the server port sees the bind host", () =>
Effect.gen(function* () {
const probed: Array<{ port: number; role: string | undefined }> = [];
yield* resolveModePortOffsets({
mode: "dev",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: false,
checkPortAvailability: (port, role) => {
probed.push({ port, role });
return Effect.succeed(true);
},
});
assert.deepStrictEqual(probed, [
{ port: 13_773, role: "server" },
{ port: 5733, role: "web" },
]);
}),
);
});
describe("resolveModePortOffsets", () => {
it.effect("uses a shared fallback offset for dev mode", () =>
Effect.gen(function* () {
@@ -569,6 +848,170 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
});
});
// `tailscale serve` config outlives the process, so a dry run that shared
// would replace and then tear down whatever mapping the port already had.
// Base-dir precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME)
// lives in runDevRunnerWithInput; the env builder must not consult the
// ambient variable on its own, or it would silently outrank the worktree
// default and land dev state on the user's real database.
it.effect("ignores an ambient T3CODE_HOME when no home is resolved", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: { T3CODE_HOME: "/home/user/.t3" },
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.T3CODE_HOME, undefined);
}),
);
// Sharing dev:desktop would publish a URL whose renderer dials the
// visitor's own loopback, and would clobber the VITE_DEV_SERVER_URL that
// Electron loads from. It must decline, not half-work.
it.effect("declines to share for dev:desktop and still starts the stack", () => {
let spawnCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => {
spawnCount += 1;
return Effect.succeed(mockProcess(0));
}),
);
return Effect.gen(function* () {
yield* runDevRunnerWithInput({
...devServerInput,
mode: "dev:desktop",
port: undefined,
share: true,
}).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
);
assert.equal(spawnCount, 1);
});
});
// Single-origin browser dev proxies the backend at localhost, so a backend
// bound only to a specific interface breaks every proxied request in a way
// that looks like a broken server. Reject the combination up front.
it.effect("rejects a specific non-loopback --host for browser dev modes", () => {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.succeed(mockProcess(0))),
);
return Effect.gen(function* () {
const error = yield* runDevRunnerWithInput({
...devServerInput,
mode: "dev",
port: undefined,
host: "192.168.1.10",
}).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.flip,
);
if (error._tag !== "DevRunnerHostNotProxiableError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.mode, "dev");
assert.equal(error.host, "192.168.1.10");
assert.include(error.message, "0.0.0.0");
assert.include(error.message, "--share");
});
});
// Wildcards keep loopback answering, so the proxy target stays valid and
// the combination must keep working — it is the documented way to serve a
// LAN interface and the browser proxy at once.
it.effect("still spawns the stack for a wildcard --host in dev mode", () => {
let spawnCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => {
spawnCount += 1;
return Effect.succeed(mockProcess(0));
}),
);
return Effect.gen(function* () {
yield* runDevRunnerWithInput({
...devServerInput,
mode: "dev",
port: undefined,
host: "0.0.0.0",
}).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
);
assert.equal(spawnCount, 1);
});
});
// dev:server does not proxy — the client talks to the backend directly —
// so a specific interface bind stays legitimate there.
it.effect("keeps a specific --host working for dev:server", () => {
let spawnCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => {
spawnCount += 1;
return Effect.succeed(mockProcess(0));
}),
);
return Effect.gen(function* () {
yield* runDevRunnerWithInput({
...devServerInput,
host: "192.168.1.10",
}).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
);
assert.equal(spawnCount, 1);
});
});
it.effect("spawns nothing when --dry-run is combined with --share", () => {
let spawnCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => {
spawnCount += 1;
return Effect.succeed(mockProcess(0));
}),
);
return Effect.gen(function* () {
yield* runDevRunnerWithInput({
...devServerInput,
mode: "dev",
port: undefined,
dryRun: true,
share: true,
}).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
);
assert.equal(spawnCount, 0);
});
});
it.effect("reports non-zero exits without manufacturing a cause", () => {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
@@ -629,5 +1072,113 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.notInclude(error.message, "secret-token-value");
});
});
describe("t3 home precedence", () => {
const makeWorktree = Effect.acquireRelease(
Effect.sync(() => {
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devrunner-"));
NodeFS.writeFileSync(
NodePath.join(root, ".git"),
"gitdir: /elsewhere/.git/worktrees/x\n",
);
return root;
}),
(root) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
);
const spawnedHome = (input: {
readonly t3Home: string | undefined;
readonly cwd: string;
readonly ambientHome: string | undefined;
}) =>
Effect.gen(function* () {
let captured: Record<string, string | undefined> | undefined;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
captured = (
command as {
readonly options?: { readonly env?: Record<string, string | undefined> };
}
).options?.env;
return Effect.succeed(mockProcess(0));
}),
);
yield* runDevRunnerWithInput({ ...devServerInput, t3Home: input.t3Home }).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.provideService(HostProcessWorkingDirectory, input.cwd),
Effect.provideService(
HostProcessEnvironment,
input.ambientHome === undefined ? {} : { T3CODE_HOME: input.ambientHome },
),
);
return captured?.T3CODE_HOME;
});
it.effect("prefers an explicit --home-dir over the worktree default", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const root = yield* makeWorktree;
const home = yield* spawnedHome({
t3Home: "/tmp/explicit-home",
cwd: root,
ambientHome: "/home/user/.t3",
});
assert.equal(home, path.resolve("/tmp/explicit-home"));
}).pipe(Effect.scoped),
);
it.effect("treats a blank --home-dir as unset rather than as a selection", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const root = yield* makeWorktree;
const home = yield* spawnedHome({
t3Home: " ",
cwd: root,
ambientHome: "/home/user/.t3",
});
assert.equal(home, path.join(path.resolve(root), ".t3"));
}).pipe(Effect.scoped),
);
it.effect("prefers the worktree .t3 over an ambient T3CODE_HOME", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const root = yield* makeWorktree;
const home = yield* spawnedHome({
t3Home: undefined,
cwd: root,
ambientHome: "/home/user/.t3",
});
assert.equal(home, path.join(path.resolve(root), ".t3"));
}).pipe(Effect.scoped),
);
it.effect("falls back to an ambient T3CODE_HOME outside a worktree", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const home = yield* spawnedHome({
t3Home: undefined,
cwd: NodeOS.tmpdir(),
ambientHome: "/home/user/.t3",
});
assert.equal(home, path.resolve("/home/user/.t3"));
}),
);
it.effect("leaves the home implicit with no worktree and no ambient value", () =>
Effect.gen(function* () {
const home = yield* spawnedHome({
t3Home: undefined,
cwd: NodeOS.tmpdir(),
ambientHome: undefined,
});
assert.equal(home, undefined);
}),
);
});
});
});
+287 -28
View File
@@ -5,7 +5,8 @@ import * as NodeOS from "node:os";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { resolveGitWorktreePath, resolveWorktreeT3Home } from "@t3tools/shared/devHome";
import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
@@ -18,6 +19,7 @@ import * as Schema from "effect/Schema";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { ChildProcess } from "effect/unstable/process";
import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
import { loadRepoEnv } from "./lib/public-config.ts";
Object.assign(process.env, loadRepoEnv());
@@ -27,7 +29,43 @@ const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;
// HTTP(S) requests to these ports are blocked by the Fetch standard before a
// browser reaches the network. Keep the complete list here so explicit or
// future wider offsets cannot produce a URL that curl accepts but browsers
// reject. https://fetch.spec.whatwg.org/#port-blocking
const FETCH_BAD_PORTS = new Set([
0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102,
103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
6669, 6679, 6697, 10080,
]);
// Dev servers bind loopback, so loopback is the only interface whose
// availability decides whether we can use a port. Probing wildcards too made
// the runner walk away from a perfectly free port whenever something else held
// the same number on another interface — `tailscale serve` does exactly that,
// which silently moved the ports out from under a URL that had just been shared.
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
/**
* Bind hosts on which a backend still answers `http://localhost:<port>`, which
* is where single-origin browser dev proxies to. Loopback and the wildcards
* qualify; a specific interface (e.g. a LAN IP) does not — the OS binds only
* that address and the proxy target goes dark.
*/
export function isProxiableBindHost(host: string): boolean {
const normalized = host.trim();
return (
normalized === "" ||
normalized === "localhost" ||
normalized === "127.0.0.1" ||
normalized === "::1" ||
normalized === "[::1]" ||
normalized === "0.0.0.0" ||
normalized === "::" ||
normalized === "[::]"
);
}
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
path.join(NodeOS.homedir(), ".t3"),
@@ -48,7 +86,15 @@ const MODE_ARGS = {
} as const satisfies Record<string, ReadonlyArray<string>>;
type DevMode = keyof typeof MODE_ARGS;
type PortAvailabilityCheck<R = never> = (port: number) => Effect.Effect<boolean, never, R>;
/**
* `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the
* web port is always loopback. Passed explicitly rather than inferred from the
* port number, which stops distinguishing them under a large port offset.
*/
type PortAvailabilityCheck<R = never> = (
port: number,
role?: "server" | "web",
) => Effect.Effect<boolean, never, R>;
const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
@@ -56,6 +102,10 @@ export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
return MODE_ARGS[mode];
}
export function isBrowserAllowedPort(port: number): boolean {
return !FETCH_BAD_PORTS.has(port);
}
export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<DevRunnerConfigurationError>()(
"DevRunnerConfigurationError",
{
@@ -128,8 +178,21 @@ export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunner
}
}
export class DevRunnerHostNotProxiableError extends Schema.TaggedErrorClass<DevRunnerHostNotProxiableError>()(
"DevRunnerHostNotProxiableError",
{
mode: Schema.Literals(["dev", "dev:web"]),
host: Schema.String,
},
) {
override get message(): string {
return `--host ${this.host} cannot be combined with ${this.mode}: single-origin browser dev proxies the backend at localhost, and a backend bound only to ${this.host} leaves localhost unanswered, so every proxied request fails. Use a wildcard (0.0.0.0 or ::) to serve that interface and loopback together, or --share for remote access.`;
}
}
export const DevRunnerError = Schema.Union([
DevRunnerConfigurationError,
DevRunnerHostNotProxiableError,
DevRunnerInvalidPortOffsetError,
DevRunnerPortExhaustedError,
DevRunnerProcessError,
@@ -166,6 +229,7 @@ const OffsetConfig = Config.all({
export function resolveOffset(config: {
readonly portOffset: number | undefined;
readonly devInstance: string | undefined;
readonly worktreePath?: string | undefined;
}): Effect.Effect<
{ readonly offset: number; readonly source: string },
DevRunnerInvalidPortOffsetError
@@ -187,19 +251,30 @@ export function resolveOffset(config: {
}
const seed = config.devInstance?.trim();
if (!seed) {
return Effect.succeed({ offset: 0, source: "default ports" });
if (seed) {
if (/^\d+$/.test(seed)) {
return Effect.succeed({
offset: Number(seed),
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
});
}
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
}
if (/^\d+$/.test(seed)) {
return Effect.succeed({
offset: Number(seed),
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
});
// Worktrees get ports derived from their path so each one is stable across
// restarts and distinct from its siblings. Without this every worktree starts
// at offset 0 and scan-collides onto whatever happens to be free that minute,
// so ports move under you between runs — which breaks any URL you already
// shared. The main checkout keeps the documented 5733/13773.
const worktreePath = config.worktreePath?.trim();
if (worktreePath) {
const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
}
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
return Effect.succeed({ offset: 0, source: "default ports" });
}
function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
@@ -245,7 +320,9 @@ export function createDevRunnerEnv({
return Effect.gen(function* () {
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
const webPort = BASE_WEB_PORT + webOffset;
const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;
// Precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME) is resolved
// by the caller; an unset t3Home here genuinely means "use the default".
const configuredBaseDir = t3Home?.trim() || undefined;
const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
const isDesktopMode = mode === "dev:desktop";
@@ -265,12 +342,41 @@ export function createDevRunnerEnv({
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
// HOST is Vite's own bind address, and the desktop branch below is the
// only place we set it. An inherited one (an exported HOST, a container,
// a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
// its HMR socket to that address — see the `explicitHost` gate in
// apps/web/vite.config.ts. Over a shared origin that is invisible: the
// page loads and only HMR quietly dials the wrong machine.
delete output.HOST;
if (mode === "dev" || mode === "dev:web") {
// Browser dev is single-origin: everything (including /ws) is proxied
// through Vite, so the client must resolve its backend from
// window.location.origin rather than a baked-in localhost URL. See
// resolveConfiguredPrimaryTarget in apps/web/src/environments/primary/target.ts
// — it only defers to the origin when both of these are absent. Baking
// localhost here is what breaks any non-localhost origin (tailnet, LAN,
// phone): the remote browser dials its own machine.
delete output.VITE_HTTP_URL;
delete output.VITE_WS_URL;
// Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
// which merges `.env`/`.env.local` *under* this env, so a developer
// with either URL in their `.env` would get it back and silently lose
// single-origin mode. This states the intent positively so Vite can
// ignore those values rather than infer from their absence.
output.T3CODE_SINGLE_ORIGIN_DEV = "1";
} else {
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
delete output.T3CODE_SINGLE_ORIGIN_DEV;
}
} 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}`;
// Desktop pins the renderer to loopback on purpose; an ambient marker
// must not make Vite drop those URLs.
delete output.T3CODE_SINGLE_ORIGIN_DEV;
delete output.T3CODE_MODE;
delete output.T3CODE_NO_BROWSER;
delete output.T3CODE_HOST;
@@ -341,13 +447,41 @@ export function checkPortAvailabilityOnHosts<R>(
});
}
const defaultCheckPortAvailability: PortAvailabilityCheck<NetService.NetService> = (port) =>
Effect.gen(function* () {
const net = yield* NetService.NetService;
return yield* checkPortAvailabilityOnHosts(port, DEV_PORT_PROBE_HOSTS, (candidatePort, host) =>
net.canListenOnHost(candidatePort, host),
);
});
/**
* Hosts to probe for a dev server bound to `configuredHost`.
*
* Loopback is always checked because the web server and the desktop renderer
* target reach it there. When `--host`/`T3CODE_HOST` moves the backend onto
* another interface, that interface decides whether the bind actually
* succeeds — probing only loopback would hand back a port that is free here
* and taken there, and the server would fail to start.
*
* `configuredHost` applies to the *backend* only. Vite takes its bind address
* from `HOST`, which the runner sets for desktop alone, so the web port stays
* on loopback and must not be judged against the backend's interface —
* a port free on loopback but busy on that interface would otherwise be
* rejected for a server that was never going to bind there.
*/
export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
const host = configuredHost?.trim();
if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
return DEV_PORT_PROBE_HOSTS;
}
return [...DEV_PORT_PROBE_HOSTS, host];
}
const makeDefaultCheckPortAvailability =
(configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
(port, role) =>
Effect.gen(function* () {
const net = yield* NetService.NetService;
const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
net.canListenOnHost(candidatePort, host),
);
});
const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
readonly startOffset: number;
@@ -379,12 +513,16 @@ export function findFirstAvailableOffset<R = NetService.NetService>({
break;
}
if (requireWebPort && !isBrowserAllowedPort(webPort)) {
continue;
}
const checks: Array<Effect.Effect<boolean, never, R>> = [];
if (requireServerPort) {
checks.push(checkPort(serverPort));
checks.push(checkPort(serverPort, "server"));
}
if (requireWebPort) {
checks.push(checkPort(webPort));
checks.push(checkPort(webPort, "web"));
}
if (checks.length === 0) {
@@ -480,6 +618,7 @@ interface DevRunnerCliInput {
readonly port: number | undefined;
readonly devUrl: URL | undefined;
readonly dryRun: boolean;
readonly share: boolean;
readonly runArgs: ReadonlyArray<string>;
}
@@ -495,22 +634,55 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
),
);
const { offset, source } = yield* resolveOffset({ portOffset, devInstance });
// Single-origin browser dev proxies the backend at localhost. A wildcard
// bind still answers there; a specific non-loopback interface does not,
// which breaks every proxied request in a way that reads as "server is
// broken" rather than "flag combination is unsupported". Reject it up
// front instead. (dev:server and dev:desktop don't proxy — untouched.)
if (
(input.mode === "dev" || input.mode === "dev:web") &&
input.host !== undefined &&
!isProxiableBindHost(input.host)
) {
return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
}
const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
const { offset, source } = yield* resolveOffset({
portOffset,
devInstance,
worktreePath,
});
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
mode: input.mode,
startOffset: offset,
hasExplicitServerPort: input.port !== undefined,
hasExplicitDevUrl: input.devUrl !== undefined,
// A non-loopback bind host decides whether the backend can actually take
// the port, so it has to be probed alongside loopback.
checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
});
const hostEnvironment = yield* HostProcessEnvironment;
// A dev server started inside a worktree defaults to that worktree's own
// (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
// outrank an ambient T3CODE_HOME. `--home-dir` still wins.
const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);
// Trim before choosing: `--home-dir ""` is not a selection, and treating it
// as one would skip the worktree default and land on the shared home —
// exactly the outcome this precedence exists to prevent.
const resolvedT3Home =
(input.t3Home?.trim() || undefined) ??
worktreeHome ??
(hostEnvironment.T3CODE_HOME?.trim() || undefined);
const env = yield* createDevRunnerEnv({
mode: input.mode,
baseEnv: hostEnvironment,
serverOffset,
webOffset,
t3Home: input.t3Home,
t3Home: resolvedT3Home,
browser: input.browser,
autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
logWebSocketEvents: input.logWebSocketEvents,
@@ -529,10 +701,90 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
);
// Before the share block: --dry-run only resolves and prints. Sharing would
// replace, then tear down, whatever mapping the port already had — a
// surprising side effect from a command documented as inert.
if (input.dryRun) {
return;
}
const sharedWebPort = BASE_WEB_PORT + webOffset;
if (input.share) {
if (input.mode === "dev:server") {
yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
} else if (input.mode === "dev:desktop") {
// Desktop is not single-origin: the renderer gets VITE_HTTP_URL and
// VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI
// and then watch it dial its own 127.0.0.1 for the backend. Worse,
// sharing would overwrite VITE_DEV_SERVER_URL, which is the origin
// Electron itself loads the renderer from. Refuse rather than hand out
// a URL that is broken in a way the user cannot see.
yield* Effect.logWarning(
"[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
);
} else {
// acquireRelease, not share-then-addFinalizer: the mapping outlives this
// process (and reboots), so the cleanup has to be registered atomically
// with creating it. An interrupt landing in between would otherwise
// leave a mapping pointing at a port nothing is listening on.
//
// Deliberately no ownership tracking beyond that: if a second runner
// takes this port during a fast restart, the first's exit can briefly
// tear down the new mapping — visible (the URL stops working) and fixed
// by re-running --share. A lease protocol closing that window existed
// and was removed as more machinery than a dev convenience warrants.
//
// A tailnet that isn't up shouldn't stop the dev server from starting —
// warn, and carry on serving locally.
const shared = yield* Effect.acquireRelease(
shareDevServer({ webPort: sharedWebPort }),
() =>
// Serve config outlives this process, so a cleanup that did not
// take leaves a tailnet URL pointing at a port nothing serves.
unshareDevServer(sharedWebPort).pipe(
Effect.flatMap((result) =>
result.cleared
? Effect.void
: Effect.logWarning(
`[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
result.explanation ? `: ${result.explanation}` : ""
}. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
),
),
),
).pipe(
Effect.tapError((error: DevShareError) =>
Effect.logWarning(
`[dev-runner] could not share on the tailnet: ${error.message}${
error.hint ? ` — ${error.hint}` : ""
}`,
),
),
Effect.option,
Effect.map(Option.getOrUndefined),
);
if (shared) {
// The app is reached from the tailnet origin. Vite already allows
// *.ts.net hosts; the backend needs the origin for credentialed
// requests that bypass the proxy (desktop renderer, direct calls).
env.T3CODE_DEV_ALLOWED_ORIGINS = [
env.T3CODE_DEV_ALLOWED_ORIGINS,
new URL(shared.url).origin,
]
.filter((entry) => entry && entry.length > 0)
.join(",");
// The server builds its pairing URL from this, so the URL printed at
// startup is already the shareable one — no rewriting by hand. An
// explicit --dev-url still wins.
if (input.devUrl === undefined) {
env.VITE_DEV_SERVER_URL = shared.url;
}
yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
}
}
}
const spawnCommand = yield* resolveSpawnCommand(
"vp",
[...MODE_ARGS[input.mode], ...input.runArgs],
@@ -592,9 +844,10 @@ const devRunnerCli = Command.make("dev-runner", {
),
t3Home: Flag.string("home-dir").pipe(
Flag.withDescription(
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME). Inside a git worktree this defaults to that worktree's own .t3 so dev state stays off the shared home.",
),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),
Flag.optional,
Flag.map(Option.getOrUndefined),
),
browser: Flag.boolean("browser").pipe(
Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
@@ -631,6 +884,12 @@ const devRunnerCli = Command.make("dev-runner", {
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
Flag.withDefault(false),
),
share: Flag.boolean("share").pipe(
Flag.withDescription(
"Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.",
),
Flag.withDefault(false),
),
runArgs: Argument.string("run-arg").pipe(
Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
Argument.variadic(),
+178
View File
@@ -0,0 +1,178 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
type DevShareError,
DevServeFailedError,
shareDevServer,
unshareDevServer,
} from "./dev-share.ts";
const TAILNET_STATUS = JSON.stringify({ Self: { DNSName: "host.example.ts.net." } });
const NO_HANDLER_STDERR = "error: failed to remove web serve: handler does not exist";
interface CallResult {
readonly exitCode: number;
readonly stderr?: string;
}
const encode = (value: string) => Stream.make(new TextEncoder().encode(value));
/**
* Answers `tailscale status --json` with a valid tailnet name, and lets each
* test set the outcome of the `off` (pre-clear) and `serve` calls separately —
* they are the same subcommand and are told apart by the trailing `off`.
*/
const spawnerLayer = (input: { readonly off?: CallResult; readonly serve?: CallResult }) =>
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const args = "args" in command ? (command.args as ReadonlyArray<string>) : [];
const result: CallResult = args.includes("status")
? { exitCode: 0 }
: args.includes("off")
? (input.off ?? { exitCode: 0 })
: (input.serve ?? { exitCode: 0 });
return Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: args.includes("status") ? encode(TAILNET_STATUS) : Stream.empty,
stderr: result.stderr ? encode(result.stderr) : Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
);
}),
);
describe("unshareDevServer", () => {
it.effect("treats a removed mapping as cleared", () =>
Effect.gen(function* () {
const result = yield* unshareDevServer(5788).pipe(
Effect.provide(spawnerLayer({ off: { exitCode: 0 } })),
);
assert.isTrue(result.cleared);
}),
);
// `tailscale serve … off` exits 1 when the port had no mapping, which is the
// normal first-share case — the port is clear, so this must not be an error.
it.effect("treats a missing handler as cleared", () =>
Effect.gen(function* () {
const result = yield* unshareDevServer(5788).pipe(
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: NO_HANDLER_STDERR } })),
);
assert.isTrue(result.cleared);
}),
);
it.effect("reports a genuine removal failure as not cleared", () =>
Effect.gen(function* () {
const result = yield* unshareDevServer(5788).pipe(
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: "permission denied" } })),
);
assert.isFalse(result.cleared);
assert.include(result.explanation, "permission denied");
// Structured, so a wrapping error can keep the real chain.
assert.equal(result.cause?._tag, "TailscaleCommandExitError");
}),
);
});
describe("shareDevServer", () => {
it.effect("returns the tailnet URL for the same port", () =>
Effect.gen(function* () {
const shared = yield* shareDevServer({ webPort: 5788 }).pipe(
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: NO_HANDLER_STDERR } })),
);
assert.equal(shared.host, "host.example.ts.net");
assert.equal(shared.url, "https://host.example.ts.net:5788/");
}),
);
// The stale-mapping clear runs before serve, so a failure here leaves the
// port serving nothing. Saying only "serve failed" would let an operator
// assume their previous mapping survived.
it.effect("reports that the prior mapping was cleared when serve fails", () =>
Effect.gen(function* () {
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
Effect.provide(
spawnerLayer({
off: { exitCode: 0 },
serve: { exitCode: 1, stderr: "port already in use" },
}),
),
Effect.flip,
);
assert.instanceOf(error, DevServeFailedError);
assert.equal(error.stage, "serve");
assert.equal(error.webPort, 5788);
// The underlying failure is preserved rather than flattened to a string.
assert.equal(
(error.cause as { _tag?: string } | undefined)?._tag,
"TailscaleCommandExitError",
);
// Unclassifiable stderr is never quoted (it can carry auth keys), so the
// message points at the command instead of echoing the CLI.
assert.notInclude(error.message, "port already in use");
assert.include(error.message, "run the command by hand");
assert.include(error.message, "no longer served");
assert.include(error.message, "5788");
}),
);
// A recognized failure gets our own wording for it — enough to act on
// without passing CLI text through.
it.effect("explains a recognized serve failure without quoting stderr", () =>
Effect.gen(function* () {
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
Effect.provide(
spawnerLayer({
off: { exitCode: 0 },
serve: {
exitCode: 1,
stderr: "permission denied for tskey-auth-secret-token-value",
},
}),
),
Effect.flip,
);
assert.instanceOf(error, DevServeFailedError);
assert.equal(error.stage, "serve");
assert.include(error.message, "permission denied");
assert.include(error.message, "elevated privileges");
assert.notInclude(error.message, "tskey-auth-secret-token-value");
}),
);
// Serving over routes we could not remove yields a URL that loads but whose
// /ws and /api quietly point at a dead backend.
it.effect("refuses to serve when the existing mapping could not be cleared", () =>
Effect.gen(function* () {
const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
Effect.provide(spawnerLayer({ off: { exitCode: 1, stderr: "permission denied" } })),
Effect.flip,
);
assert.instanceOf(error, DevServeFailedError);
// A distinct stage: the prior mapping survived, so nothing was replaced.
assert.equal(error.stage, "clear-existing");
assert.include(error.message, "could not clear the existing mapping");
assert.include(error.message, "permission denied");
}),
);
});
+217
View File
@@ -0,0 +1,217 @@
/**
* Shares a running dev server on the local tailnet via `tailscale serve`, so it
* can be opened from a phone, another laptop, or by whoever is reviewing the
* work.
*
* Thin wrapper over `@t3tools/tailscale` (the same client the server's own
* `--tailscale-serve` uses). What it adds is dev-share semantics: replacing a
* stale mapping left by a killed run, and refusing to serve over routes it
* could not remove.
*
* Because browser dev is single-origin (Vite proxies the backend — see
* `resolveDevProxyTarget` in apps/web/vite.config.ts), one proxy rule covering
* the web port is enough; the backend needs no mapping of its own.
*/
import {
buildTailscaleHttpsBaseUrl,
disableTailscaleServe,
ensureTailscaleServe,
readTailscaleStatus,
type TailscaleCommandError,
type TailscaleStderrDiagnostic,
} from "@t3tools/tailscale";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import type { ChildProcessSpawner } from "effect/unstable/process";
/**
* Human-readable gloss for each diagnostic. Deliberately our own words rather
* than the CLI's: tailscale prints auth keys and node names into stderr, and
* this string is logged.
*/
const DIAGNOSTIC_EXPLANATIONS: Record<TailscaleStderrDiagnostic, string | undefined> = {
"no-existing-handler": "no mapping existed for that port",
"not-logged-in": "this machine is not logged into a tailnet — run `tailscale up`",
"permission-denied": "permission denied — `tailscale serve` may need elevated privileges",
unknown: undefined,
};
/**
* Our own wording for why a tailscale command failed, derived from the
* classified diagnostic. Never the CLI's text — see `stderrDiagnosticOf`.
*/
const explainCommandFailure = (error: TailscaleCommandError): string | undefined =>
error._tag === "TailscaleCommandExitError" && error.stderrDiagnostic !== undefined
? (DIAGNOSTIC_EXPLANATIONS[error.stderrDiagnostic] ?? "run the command by hand to see why")
: undefined;
/**
* Three distinct failures, three classes: each has its own caller-visible
* message and its own remedy, and `shareDevServer` chooses between them
* structurally. A single error with a `reason` discriminator would encode that
* distinction twice and put a lookup table in the `message` getter.
*
* Each wraps a real underlying failure and so keeps it as `cause`; the message
* is derived only from the structural fields, never from `cause.message`.
*/
export class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(
"TailscaleUnavailableError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "could not talk to tailscale";
}
get hint(): string {
return "Is Tailscale installed and tailscaled running? Try `tailscale status` — or drop --share and open the printed localhost URL.";
}
}
/** No underlying failure: the status read succeeded and simply had no name. */
export class TailnetNameMissingError extends Schema.TaggedErrorClass<TailnetNameMissingError>()(
"TailnetNameMissingError",
{},
) {
override get message(): string {
return "this machine has no tailnet DNS name";
}
get hint(): string {
return "Run `tailscale up` and make sure MagicDNS is enabled.";
}
}
/**
* `stage` is a genuine multi-value discriminator: both stages share the same
* semantics (a `tailscale serve` invocation failed for this port) and differ
* only in which one, which the message states plainly.
*/
export class DevServeFailedError extends Schema.TaggedErrorClass<DevServeFailedError>()(
"DevServeFailedError",
{
stage: Schema.Literals(["clear-existing", "serve"]),
webPort: Schema.Number,
explanation: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
const port = String(this.webPort);
const base =
this.stage === "clear-existing"
? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} off\` and retry`
: `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
return this.explanation ? `${base}: ${this.explanation}` : base;
}
get hint(): undefined {
return undefined;
}
}
export const DevShareError = Schema.Union([
TailscaleUnavailableError,
TailnetNameMissingError,
DevServeFailedError,
]);
export type DevShareError = typeof DevShareError.Type;
export const isDevShareError = Schema.is(DevShareError);
/**
* Removes any mapping for `webPort`, reporting whether the port is now clear.
*
* Runs uninterruptibly: this is called from a finalizer on the way out of an
* interrupted program, and cancelling the cleanup subprocess would leave
* exactly the stale mapping it exists to remove.
*/
export const unshareDevServer = (
webPort: number,
): Effect.Effect<
{
readonly cleared: boolean;
readonly explanation?: string | undefined;
// Kept structured so a caller wrapping this can preserve the real error
// chain rather than a flattened string.
readonly cause?: TailscaleCommandError | undefined;
},
never,
ChildProcessSpawner.ChildProcessSpawner
> =>
disableTailscaleServe({ servePort: webPort }).pipe(
Effect.as({ cleared: true } as const),
Effect.catch((error: TailscaleCommandError) =>
Effect.succeed(
// "Nothing was mapped" leaves the port clear either way.
error._tag === "TailscaleCommandExitError" &&
error.stderrDiagnostic === "no-existing-handler"
? ({ cleared: true } as const)
: ({
cleared: false,
...(explainCommandFailure(error) !== undefined
? { explanation: explainCommandFailure(error) }
: {}),
cause: error,
} as const),
),
),
Effect.uninterruptible,
);
export interface DevShareResult {
readonly url: string;
readonly host: string;
}
/**
* Publishes `webPort` on the tailnet at the same port number and returns the
* resulting HTTPS URL. Idempotent: re-running replaces any existing mapping.
*/
export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {
readonly webPort: number;
}) {
const status = yield* readTailscaleStatus.pipe(
Effect.mapError((error) => new TailscaleUnavailableError({ cause: error })),
);
if (status.magicDnsName === null) {
return yield* new TailnetNameMissingError();
}
// Clear any mapping left behind by a run that was killed before its finalizer
// could fire. Serve config survives both the process and a reboot, and a
// stale entry may carry path routes we no longer want — older versions mapped
// /ws, /api and friends to a separate backend port, and serving "/" alone
// would leave those pointing at a port nothing is listening on.
const cleared = yield* unshareDevServer(input.webPort);
if (!cleared.cleared) {
// Serving over routes we failed to remove would hand out a URL that is
// broken in a way the user cannot see: the page loads while /ws and /api
// silently resolve to a dead backend. Better to refuse and say why.
return yield* new DevServeFailedError({
stage: "clear-existing",
webPort: input.webPort,
...(cleared.explanation !== undefined ? { explanation: cleared.explanation } : {}),
...(cleared.cause !== undefined ? { cause: cleared.cause } : {}),
});
}
yield* ensureTailscaleServe({ localPort: input.webPort, servePort: input.webPort }).pipe(
Effect.mapError((error) => {
const explanation = explainCommandFailure(error);
return new DevServeFailedError({
stage: "serve",
webPort: input.webPort,
...(explanation !== undefined ? { explanation } : {}),
cause: error,
});
}),
);
return {
url: buildTailscaleHttpsBaseUrl({
magicDnsName: status.magicDnsName,
servePort: input.webPort,
}),
host: status.magicDnsName,
} satisfies DevShareResult;
});
+1
View File
@@ -10,6 +10,7 @@
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"pngjs": "7.0.0",
"yaml": "catalog:"
+196
View File
@@ -0,0 +1,196 @@
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalFetch:off globalTimers:off - This script intentionally measures a child process with host APIs.
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import * as NodePerfHooks from "node:perf_hooks";
const args = process.argv.slice(2);
const readArg = (name: string): string | undefined => {
const index = args.indexOf(name);
return index === -1 ? undefined : args[index + 1];
};
const homeDir = NodePath.resolve(readArg("--home-dir") ?? ".t3/startup-profile");
const outputDir = NodePath.resolve(readArg("--output-dir") ?? NodePath.join(homeDir, "profile"));
const command = readArg("--command") ?? "dev";
const stopAfter = readArg("--stop-after") ?? "pairing-url-emitted";
const timeoutMs = Number(readArg("--timeout-ms") ?? "30000");
const hostPlatform = Effect.runSync(HostProcessPlatform);
const startedAtEpochMs = Date.now();
const startedAt = NodePerfHooks.performance.now();
interface Milestone {
readonly name: string;
readonly elapsedMs: number;
readonly [detail: string]: unknown;
}
const milestones: Array<Milestone> = [];
const seenMilestones = new Set<string>();
const outputBuffers = { stdout: "", stderr: "" };
let serverPort: number | undefined;
let webPort: number | undefined;
let pairingUrl: string | undefined;
let finishing = false;
await NodeFSP.mkdir(outputDir, { recursive: true });
const elapsedMs = (): number => Number((NodePerfHooks.performance.now() - startedAt).toFixed(3));
const redact = (text: string): string =>
text
.replace(/(https?:\/\/\S+\/pair#token=)\S+/gi, "$1[REDACTED]")
.replace(/("?(?:token|credential)"?\s*[:=]\s*"?)[^\s",}]+/gi, "$1[REDACTED]");
function mark(name: string, detail: Record<string, unknown> = {}): void {
if (seenMilestones.has(name)) return;
seenMilestones.add(name);
const milestone = { name, elapsedMs: elapsedMs(), ...detail };
milestones.push(milestone);
process.stdout.write(`[profile +${milestone.elapsedMs.toFixed(3)}ms] ${name}\n`);
if (name === stopAfter) queueMicrotask(() => void finish(`milestone:${name}`));
}
async function probeHttp(name: string, url: string): Promise<void> {
while (true) {
if (finishing || seenMilestones.has(name)) return;
try {
const response = await fetch(url, {
redirect: "manual",
signal: AbortSignal.timeout(250),
});
mark(name, { status: response.status });
return;
} catch {
await new Promise((resolve) => setTimeout(resolve, 20));
}
}
}
function inspectLine(stream: keyof typeof outputBuffers, line: string): void {
const runner = line.match(/\[dev-runner\].*serverPort=(\d+).*webPort=(\d+).*baseDir=(.+?)\s*$/);
if (runner && webPort === undefined) {
serverPort = Number(runner[1]);
webPort = Number(runner[2]);
mark("runner-config-resolved", { serverPort, webPort });
void probeHttp("web-http-ready", `http://localhost:${webPort}/`);
void probeHttp(
"environment-descriptor-ready",
`http://localhost:${serverPort}/.well-known/t3/environment`,
);
}
if (/apps\/web\$.*vp dev/.test(line)) mark("web-task-started");
if (/apps\/server\$.*node --watch/.test(line)) mark("server-task-started");
if (/Local:\s+https?:\/\//.test(line) || /ready in \d+ ?ms/i.test(line)) {
mark("vite-ready");
}
const pairingMatch = line.match(
/pairingUrl\s*[:=]\s*["']?(https?:\/\/\S+\/pair#token=[^\s"'}]+)/i,
);
if (pairingMatch?.[1]) {
pairingUrl = pairingMatch[1];
}
if (/Authentication required\./.test(line)) mark("pairing-url-emitted");
process.stdout.write(`[${stream} +${elapsedMs().toFixed(3)}ms] ${redact(line)}\n`);
}
function consume(stream: keyof typeof outputBuffers, chunk: Buffer): void {
outputBuffers[stream] += chunk.toString("utf8");
const lines = outputBuffers[stream].split(/\r?\n/);
outputBuffers[stream] = lines.pop() ?? "";
for (const line of lines) inspectLine(stream, line);
}
const child = NodeChildProcess.spawn(
NodePath.resolve("node_modules/.bin/vp"),
["run", command, "--home-dir", homeDir],
{
cwd: process.cwd(),
detached: hostPlatform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
},
);
const childClosed = new Promise<void>((resolve) => child.once("close", () => resolve()));
mark("process-spawned", { pid: child.pid ?? null });
child.stdout.on("data", (chunk) => consume("stdout", chunk));
child.stderr.on("data", (chunk) => consume("stderr", chunk));
async function writeResults(reason: string): Promise<void> {
await NodeFSP.writeFile(
NodePath.join(outputDir, "startup-profile.json"),
`${JSON.stringify(
{
schemaVersion: 1,
command: `vp run ${command} --home-dir <isolated>`,
startedAtEpochMs,
stoppedAtEpochMs: Date.now(),
reason,
stopAfter,
serverPort,
webPort,
milestones,
browserMilestoneNames: [
"navigation.start",
"entry.loaded",
"auth.gate.resolved",
"pairing.exchanged",
"ws.open",
"config.received",
"react.usable",
"shell.live",
],
},
null,
2,
)}\n`,
);
if (pairingUrl) {
await NodeFSP.writeFile(NodePath.join(outputDir, "pairing-url.secret"), `${pairingUrl}\n`, {
mode: 0o600,
});
}
process.stdout.write(`[profile] results=${NodePath.join(outputDir, "startup-profile.json")}\n`);
}
async function finish(reason: string): Promise<void> {
if (finishing) return;
finishing = true;
clearTimeout(timeout);
signalChild("SIGINT");
const forceKill = setTimeout(() => signalChild("SIGTERM"), 3_000);
await childClosed;
clearTimeout(forceKill);
await writeResults(reason);
}
function signalChild(signal: NodeJS.Signals): void {
if (hostPlatform !== "win32" && child.pid !== undefined) {
try {
process.kill(-child.pid, signal);
return;
} catch {
// The process group may already be gone; fall back to the direct child.
}
}
child.kill(signal);
}
const timeout = setTimeout(() => void finish("timeout"), timeoutMs);
process.once("SIGINT", () => void finish("SIGINT"));
process.once("SIGTERM", () => void finish("SIGTERM"));
child.once("error", (error) => {
process.stderr.write(`[profile] spawn failed: ${error.message}\n`);
void finish("spawn-error");
});
child.once("exit", (code, signal) => {
if (!finishing) void finish(signal ?? `exit-${code ?? "unknown"}`);
});