Compare commits

...
Author SHA1 Message Date
maria-rcks 8ed20241d2 perf(web): shrink the critical startup graph 2026-07-27 13:13:42 -04:00
maria-rcks 827f921c02 perf(web): make cold dev startup 1.71x faster 2026-07-27 01:11:02 -04:00
24 changed files with 947 additions and 626 deletions

No files matched your search

+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>
);
}
+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>
@@ -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;
}
+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);
}
+4 -5
View File
@@ -52,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";
@@ -127,7 +127,7 @@ 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
@@ -141,7 +141,6 @@ export default defineConfig(() => {
],
optimizeDeps: {
include: [
"@clerk/clerk-js",
"@clerk/react/internal",
"@pierre/diffs",
"@pierre/diffs/editor",
+1
View File
@@ -15,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",
+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"}`);
});