import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts"; import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment"; import { Outlet, Link, redirect, createRootRoute, type ErrorComponentProps, useLocation, useNavigate, useRouter, } from "@tanstack/react-router"; import { msg, T, useGT, Var } from "gt-react"; import { CheckIcon, CopyIcon } from "lucide-react"; import { useEffect, useEffectEvent, useRef, useState } from "react"; import { APP_DISPLAY_NAME, APP_VERSION } from "../branding"; import { AppSidebarLayout } from "../components/AppSidebarLayout"; import { CommandPalette } from "../components/CommandPalette"; import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog"; import { GuestShareDialogHost } from "../components/chat/GuestShareControls"; import { ThreadWorkspaceDialogHost } from "../components/chat/ThreadWorkspaceDialog"; import { ThreadHandoffDialogHost } from "../components/chat/ThreadHandoffDialog"; import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog"; import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog"; import { ConfirmDialogHost } from "../components/ConfirmDialogHost"; import { WorktreeLayoutApprovalDialogHost } from "../components/WorktreeLayoutApprovalDialogHost"; import { DevReplayHost } from "../components/DevReplayHost"; import { FirstRunGate } from "../components/onboarding/FirstRunGate"; import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog"; import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog"; import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog"; import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator"; import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator"; import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator"; import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive"; import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut"; import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator"; import { ConnectDeviceApprovalCoordinator } from "../components/ConnectDeviceApprovalCoordinator"; import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator"; import { ThemeEditorHost } from "../components/settings/ThemeEditorHost"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { Button } from "../components/ui/button"; import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page"; import { SharedTooltipProvider } from "../components/ui/shared-tooltip"; import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast"; import { isElectron } from "../env"; import { useClientSettings } from "../hooks/useSettings"; import { deriveLogicalProjectKeyFromSettings, derivePhysicalProjectKeyFromPath, selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; import { useUiStateStore } from "../uiStateStore"; import { configureClientTracing } from "../observability/clientTracing"; import { resolveInitialServerAuthGateState } from "../environments/primary"; import { GUEST_PAGE_PATH } from "../guestPage"; import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing"; import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding"; import { isLocalEnvironmentDisabled } from "../localEnvironment"; import { useAtomValue } from "@effect/atom-react"; import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../state/server"; import { readProject } from "../state/entities"; import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; export const Route = createRootRoute({ beforeLoad: async ({ location }) => { // Guest links open on the owner's tunnel host in a browser with no T3 session, and must // not trigger pairing or an environment connection. if (location.pathname === GUEST_PAGE_PATH) { return { authGateState: { status: "guest", } as const, }; } if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) { return { authGateState: { status: "hosted-pairing", } as const, }; } if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) { return { authGateState: { status: "hosted-static", } as const, }; } const authGateState = await resolveInitialServerAuthGateState(); if (authGateState.status === "authenticated") { // Idempotent, so every navigation can ask for it. void configureClientTracing(); } if ( authGateState.status === "authenticated" && getDesktopSnapShotBridge() && shouldResumeSnapShotSetupOnStartup() && location.pathname !== "/settings/snap-shot" ) { throw redirect({ to: "/settings/snap-shot", replace: true }); } return { authGateState, }; }, component: RootRouteView, errorComponent: RootRouteErrorView, notFoundComponent: RootRouteNotFoundView, head: () => ({ meta: [{ name: "title", content: APP_DISPLAY_NAME }], }), }); function RootRouteNotFoundView() { return ( Page not found This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or start a thread. }> Go home ); } function RootRouteView() { // Above every branch: app services raise toasts for the whole page, so the surface they write to // must not unmount when the root switches branches (for example /welcome to the app shell). return ( {/* One tooltip for every trigger in the app: mounting a tooltip per trigger made opening a thread, panel or message pay for tooltips nobody hovers. */} ); } function RootRouteBranch() { const pathname = useLocation({ select: (location) => location.pathname }); const { authGateState } = Route.useRouteContext(); const primaryEnvironmentAuthenticated = authGateState.status === "authenticated"; // A sync IPC read; the setting only changes across a relaunch. const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled); // Once true, stays true: a visit to /welcome means the bootstrap already chose a route. const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome"); if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true); const hostedPromptLinkLanding = useHostedPromptLinkLanding( authGateState.status === "hosted-static", ); if (pathname === GUEST_PAGE_PATH) return ; if ( pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent" || pathname === "/approve-agent" ) { return ; } // Handle links before onboarding redirects lose them. if (hostedPromptLinkLanding !== null) { return hostedPromptLinkLanding; } const isWelcome = pathname === "/welcome"; if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") { return ; } // Settings can reopen /welcome mid-session, so it mounts everything the app does except the // first-run gate and the event router, whose first navigation would leave the page. const appHosts = ( <> {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? ( <> > ) : null} {isElectron ? : null} {import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null} > ); const appShell = ( {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */} ); return ( <> {isWelcome ? ( <> {appHosts} {appShell} > ) : ( {appHosts} {primaryEnvironmentAuthenticated ? ( ) : null} {appShell} )} {/* Above both shells and the router, so drafts survive navigation, including to /welcome. */} > ); } function RootRouteErrorView({ error }: ErrorComponentProps) { const router = useRouter(); const gt = useGT(); const message = errorMessage(error) ?? gt`An unexpected router error occurred.`; // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/". const pathname = useLocation({ select: (location) => location.pathname }); const report = errorReport(error, pathname); return ( isChunkLoadError(error) ? window.location.reload() : void router.invalidate() } > Try again window.location.reload()}> Reload app Error report {report} ); } function CopyErrorButton({ report }: { report: string }) { const { copyToClipboard, isCopied } = useCopyToClipboard({ target: { target: "error-report", unavailableMessage: msg("Clipboard API is unavailable while copying error-report."), failureMessage: msg("Failed to copy error-report to the clipboard."), }, }); const gt = useGT(); return ( copyToClipboard(report)}> {isCopied ? : } {isCopied ? gt`Copied` : gt`Copy error`} ); } function errorMessage(error: unknown): string | null { if (error instanceof Error && error.message.trim().length > 0) { return error.message; } if (typeof error === "string" && error.trim().length > 0) { return error; } return null; } function errorDetails(error: unknown): string { if (error instanceof Error) { return error.stack ?? error.message; } if (typeof error === "string") { return error; } try { return JSON.stringify(error, null, 2); } catch { // oxlint-disable-next-line t3code/no-untranslated-copy -- error report pasted into bug reports return "No additional error details are available."; } } const MAX_ERROR_CAUSE_DEPTH = 5; // Use only pathname to keep query tokens off the clipboard. function errorReport(error: unknown, pathname: string): string { const lines = [ `${APP_DISPLAY_NAME} ${APP_VERSION}`, `Path: ${pathname}`, `Time: ${new Date().toISOString()}`, "", errorDetails(error), ]; let cause = error instanceof Error ? error.cause : undefined; for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) { lines.push("", "Caused by:", errorDetails(cause)); cause = cause instanceof Error ? cause.cause : undefined; } return lines.join("\n"); } function EventRouter({ skipInitialBootstrapNavigation, }: { readonly skipInitialBootstrapNavigation: boolean; }) { const navigate = useNavigate(); const pathname = useLocation({ select: (loc) => loc.pathname }); const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); const serverConfig = useAtomValue(primaryServerConfigAtom); const serverWelcome = useAtomValue(primaryServerWelcomeAtom); const readPathname = useEffectEvent(() => pathname); const handledBootstrapThreadIdRef = useRef(null); const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation); const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => { if (!payload) return; 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 (skipInitialBootstrapNavigationRef.current) { skipInitialBootstrapNavigationRef.current = false; handledBootstrapThreadIdRef.current = payload.bootstrapThreadId; 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); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands the bootstrap project in the UI store and navigates the router on a server welcome useEffect(() => { handleWelcome(serverWelcome); }, [serverWelcome]); return null; }
This link doesn't point to a page in {APP_DISPLAY_NAME}. Go home to choose a project or start a thread.
Error report
{report}