perf(web): shrink the critical startup graph

This commit is contained in:
maria-rcks committed 2026-07-27 13:13:42 -04:00
1 parent 827f921c02
commit 8ed20241d2
17 files changed
+545 -476

No files matched your search

+2 -2
View File
@@ -1,4 +1,4 @@
import { Children, isValidElement, Suspense, type ReactElement, type ReactNode } from "react";
import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
import { RouterProvider } from "@tanstack/react-router";
import { describe, expect, it } from "vite-plus/test";
@@ -16,6 +16,6 @@ describe("AppRoot", () => {
);
expect(children).toHaveLength(2);
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
expect(isValidElement(children[1]) && children[1].type).toBe(Suspense);
expect(isValidElement(children[1])).toBe(true);
});
});
+14 -4
View File
@@ -2,6 +2,7 @@ import { lazy, Suspense } from "react";
import { RouterProvider } from "@tanstack/react-router";
import { isElectron } from "./env";
import { STARTUP_OPTIONAL_UI_DELAY_MS, useAfterFirstPaint } from "./hooks/useAfterFirstPaint";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import type { AppRouter } from "./router";
@@ -16,6 +17,18 @@ const ElectronBrowserHost = lazy(() =>
})),
);
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
@@ -25,10 +38,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
return (
<AppAtomRegistryProvider>
<RouterProvider router={router} />
<Suspense fallback={null}>
<PreviewAutomationHosts />
{isElectron ? <ElectronBrowserHost /> : null}
</Suspense>
<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>
);
}
+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}
@@ -108,6 +108,7 @@ import { resolveDefaultProviderModelSelection } from "../providerInstances";
import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";
import {
Command,
CommandDialog,
CommandDialogPopup,
CommandFooter,
CommandInput,
@@ -339,6 +340,18 @@ export function CommandPaletteDialog(props: {
readonly openIntent: CommandPaletteOpenIntent | null;
readonly setOpen: (open: boolean) => void;
readonly clearOpenIntent: () => void;
}) {
return (
<CommandDialog open onOpenChange={props.setOpen}>
<OpenCommandPaletteDialog {...props} />
</CommandDialog>
);
}
function OpenCommandPaletteDialog(props: {
readonly openIntent: CommandPaletteOpenIntent | null;
readonly setOpen: (open: boolean) => void;
readonly clearOpenIntent: () => void;
}) {
const navigate = useNavigate();
const { clearOpenIntent, openIntent, setOpen } = props;
+10 -13
View File
@@ -10,7 +10,6 @@ import { primaryServerKeybindingsAtom } from "../state/server";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { resolveThreadRouteTarget } from "../threadRoutes";
import type { ChatComposerHandle } from "./chat/ChatComposer";
import { CommandDialog } from "./ui/command";
const CommandPaletteDialog = lazy(() =>
import("./CommandPalette").then((module) => ({
@@ -99,18 +98,16 @@ export function CommandPaletteShell({ children }: { readonly children: ReactNode
return (
<ComposerHandleContext value={composerHandleRef}>
<CommandDialog open={state.open} onOpenChange={setOpen}>
{children}
{state.open ? (
<Suspense fallback={null}>
<CommandPaletteDialog
openIntent={state.openIntent}
setOpen={setOpen}
clearOpenIntent={clearOpenIntent}
/>
</Suspense>
) : null}
</CommandDialog>
{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>
+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;
}
+9 -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 {
@@ -35,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;
}
+18 -176
View File
@@ -1,60 +1,35 @@
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 { lazy, Suspense, 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 { 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,
useAllEnvironmentShellsBootstrapped,
} from "../state/entities";
import {
createKeybindingsUpdateToastController,
type KeybindingsUpdateToastController,
} from "../components/KeybindingsUpdateToast.logic";
const AppOverlays = lazy(() => import("../components/AppOverlays"));
const EventRouter = lazy(() => import("./-EventRouter"));
const ProviderUpdateLaunchNotification = lazy(() =>
import("../components/ProviderUpdateLaunchNotification").then((module) => ({
default: module.ProviderUpdateLaunchNotification,
@@ -84,6 +59,8 @@ 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");
@@ -131,12 +108,18 @@ function RootRouteView() {
<GlassAppearanceSync />
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
{primaryEnvironmentAuthenticated ? <StartupConnectionMilestones /> : null}
<Suspense fallback={null}>
<AppOverlays />
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
</Suspense>
{loadOptionalUi ? (
<Suspense fallback={null}>
<AppOverlays />
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
</Suspense>
) : null}
<HostedStaticEnvironmentBootstrap />
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
{primaryEnvironmentAuthenticated && loadEventRouter ? (
<Suspense fallback={null}>
<EventRouter />
</Suspense>
) : null}
{appShell}
</AnchoredToastProvider>
</ToastProvider>
@@ -300,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 />
</>
);