From 8ed20241d2e752eb5fe5b0725777b95222040ce9 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Mon, 27 Jul 2026 13:13:42 -0400 Subject: [PATCH] perf(web): shrink the critical startup graph --- apps/web/src/AppRoot.test.tsx | 4 +- apps/web/src/AppRoot.tsx | 18 +- apps/web/src/cloud/CloudAuthRoot.tsx | 18 ++ apps/web/src/cloud/ElectronCloudAuthRoot.tsx | 19 ++ apps/web/src/components/AppSidebarLayout.tsx | 14 +- apps/web/src/components/CommandPalette.tsx | 13 ++ .../src/components/CommandPaletteShell.tsx | 23 +-- apps/web/src/components/Sidebar.tsx | 17 +- apps/web/src/components/SidebarV2.tsx | 20 +- apps/web/src/hooks/useAfterFirstPaint.ts | 27 +++ apps/web/src/main.tsx | 23 +-- .../src/routes/-ChatRouteGlobalShortcuts.tsx | 155 ++++++++++++++ apps/web/src/routes/-EventRouter.tsx | 153 ++++++++++++++ apps/web/src/routes/-ExistingProjectIndex.tsx | 60 ++++++ apps/web/src/routes/__root.tsx | 194 ++---------------- apps/web/src/routes/_chat.index.tsx | 78 +------ apps/web/src/routes/_chat.tsx | 185 +---------------- 17 files changed, 545 insertions(+), 476 deletions(-) create mode 100644 apps/web/src/cloud/CloudAuthRoot.tsx create mode 100644 apps/web/src/cloud/ElectronCloudAuthRoot.tsx create mode 100644 apps/web/src/hooks/useAfterFirstPaint.ts create mode 100644 apps/web/src/routes/-ChatRouteGlobalShortcuts.tsx create mode 100644 apps/web/src/routes/-EventRouter.tsx create mode 100644 apps/web/src/routes/-ExistingProjectIndex.tsx diff --git a/apps/web/src/AppRoot.test.tsx b/apps/web/src/AppRoot.test.tsx index d582adcf5d..ec3742832b 100644 --- a/apps/web/src/AppRoot.test.tsx +++ b/apps/web/src/AppRoot.test.tsx @@ -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); }); }); diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsx index 7254095254..33f8450dd1 100644 --- a/apps/web/src/AppRoot.tsx +++ b/apps/web/src/AppRoot.tsx @@ -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 ( + + + {isElectron ? : null} + + ); +} + /** * 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 ( - - - {isElectron ? : null} - + ); } diff --git a/apps/web/src/cloud/CloudAuthRoot.tsx b/apps/web/src/cloud/CloudAuthRoot.tsx new file mode 100644 index 0000000000..dd37806986 --- /dev/null +++ b/apps/web/src/cloud/CloudAuthRoot.tsx @@ -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 ( + + {children} + + ); +} diff --git a/apps/web/src/cloud/ElectronCloudAuthRoot.tsx b/apps/web/src/cloud/ElectronCloudAuthRoot.tsx new file mode 100644 index 0000000000..00b72f685f --- /dev/null +++ b/apps/web/src/cloud/ElectronCloudAuthRoot.tsx @@ -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 ( + + {children} + + ); +} diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 3a70390d0c..e7243d4551 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -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 ? : } + {loadSidebarContent ? ( + + {useSidebarV2 ? : } + + ) : null} {children} diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 93352d9240..0ed18969f4 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -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 ( + + + + ); +} + +function OpenCommandPaletteDialog(props: { + readonly openIntent: CommandPaletteOpenIntent | null; + readonly setOpen: (open: boolean) => void; + readonly clearOpenIntent: () => void; }) { const navigate = useNavigate(); const { clearOpenIntent, openIntent, setOpen } = props; diff --git a/apps/web/src/components/CommandPaletteShell.tsx b/apps/web/src/components/CommandPaletteShell.tsx index e0e50da10f..65d8b6277b 100644 --- a/apps/web/src/components/CommandPaletteShell.tsx +++ b/apps/web/src/components/CommandPaletteShell.tsx @@ -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 ( - - {children} - {state.open ? ( - - - - ) : null} - + {children} + {state.open ? ( + + + + ) : null} ); } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a1d95eaa73..2d2b257311 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -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( - - } + openCommandPalette()} > Search @@ -2843,7 +2840,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent( {commandPaletteShortcutLabel} ) : null} - + diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index 8c5891ebe7..678f9dd85a 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -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() {
- - } + openCommandPalette()} >
Search
@@ -2236,7 +2232,7 @@ export default function SidebarV2() { {commandPaletteShortcutLabel} ) : null} -
+
diff --git a/apps/web/src/hooks/useAfterFirstPaint.ts b/apps/web/src/hooks/useAfterFirstPaint.ts new file mode 100644 index 0000000000..74cd142828 --- /dev/null +++ b/apps/web/src/hooks/useAfterFirstPaint.ts @@ -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; +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index c0cc64285a..47dcd75415 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -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 = ; +const cloudAuthPublishableKey = + clerkPublishableKey && hasCloudPublicConfig() ? clerkPublishableKey : null; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( - {clerkPublishableKey && hasCloudPublicConfig() ? ( - isElectron ? ( - - {app} - - ) : ( - - {app} - - ) + {cloudAuthPublishableKey ? ( + + {app} + ) : ( app )} diff --git a/apps/web/src/routes/-ChatRouteGlobalShortcuts.tsx b/apps/web/src/routes/-ChatRouteGlobalShortcuts.tsx new file mode 100644 index 0000000000..84657a31ca --- /dev/null +++ b/apps/web/src/routes/-ChatRouteGlobalShortcuts.tsx @@ -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; +} diff --git a/apps/web/src/routes/-EventRouter.tsx b/apps/web/src/routes/-EventRouter.tsx new file mode 100644 index 0000000000..31a77a3703 --- /dev/null +++ b/apps/web/src/routes/-EventRouter.tsx @@ -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(null); + const handledConfigEventRef = useRef(serverConfigEvent); + const [keybindingsToastController] = useState(() => + 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; +} diff --git a/apps/web/src/routes/-ExistingProjectIndex.tsx b/apps/web/src/routes/-ExistingProjectIndex.tsx new file mode 100644 index 0000000000..cc68f64bb8 --- /dev/null +++ b/apps/web/src/routes/-ExistingProjectIndex.tsx @@ -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 ? ( + + + + Couldn’t start a new thread + + The project is still available. Try opening the draft again. + +
+ +
+
+
+
+ ) : null; +} diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index d7aff2f3c3..06456bd629 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -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() { {primaryEnvironmentAuthenticated ? : null} {primaryEnvironmentAuthenticated ? : null} - - - {primaryEnvironmentAuthenticated ? : null} - + {loadOptionalUi ? ( + + + {primaryEnvironmentAuthenticated ? : null} + + ) : null} - {primaryEnvironmentAuthenticated ? : null} + {primaryEnvironmentAuthenticated && loadEventRouter ? ( + + + + ) : null} {appShell} @@ -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(null); - const handledConfigEventRef = useRef(serverConfigEvent); - const [keybindingsToastController] = useState(() => - 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; -} diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsx index 6e8dbe33ff..6fe3d55d80 100644 --- a/apps/web/src/routes/_chat.index.tsx +++ b/apps/web/src/routes/_chat.index.tsx @@ -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 ? ( - { - setStartState((state) => ({ - failed: false, - retryRequest: state.retryRequest + 1, - })); - }} - /> - ) : null; + if (projects.length > 0) { + return ( + + + + ); } return ; } -function DraftStartError({ onRetry }: { readonly onRetry: () => void }) { - return ( - - - - Couldn’t start a new thread - - The project is still available. Try opening the draft again. - -
- -
-
-
-
- ); -} - function NoProjectsHero() { const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []); diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index d3cf003d99..93d5749e4c 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -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 ( <> - + {loadGlobalShortcuts ? ( + + + + ) : null} );