The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts"; |
| 2 | import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment"; |
| 3 | import { |
| 4 | Outlet, |
| 5 | Link, |
| 6 | redirect, |
| 7 | createRootRoute, |
| 8 | type ErrorComponentProps, |
| 9 | useLocation, |
| 10 | useNavigate, |
| 11 | useRouter, |
| 12 | } from "@tanstack/react-router"; |
| 13 | import { msg, T, useGT, Var } from "gt-react"; |
| 14 | import { CheckIcon, CopyIcon } from "lucide-react"; |
| 15 | import { useEffect, useEffectEvent, useRef, useState } from "react"; |
| 16 | |
| 17 | import { APP_DISPLAY_NAME, APP_VERSION } from "../branding"; |
| 18 | import { AppSidebarLayout } from "../components/AppSidebarLayout"; |
| 19 | import { CommandPalette } from "../components/CommandPalette"; |
| 20 | import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog"; |
| 21 | import { GuestShareDialogHost } from "../components/chat/GuestShareControls"; |
| 22 | import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog"; |
| 23 | import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog"; |
| 24 | import { ConfirmDialogHost } from "../components/ConfirmDialogHost"; |
| 25 | import { DevReplayHost } from "../components/DevReplayHost"; |
| 26 | import { FirstRunGate } from "../components/onboarding/FirstRunGate"; |
| 27 | import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog"; |
| 28 | import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog"; |
| 29 | import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog"; |
| 30 | import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator"; |
| 31 | import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator"; |
| 32 | import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator"; |
| 33 | import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive"; |
| 34 | import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut"; |
| 35 | import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator"; |
| 36 | import { ConnectDeviceApprovalCoordinator } from "../components/ConnectDeviceApprovalCoordinator"; |
| 37 | import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator"; |
| 38 | import { ThemeEditorHost } from "../components/settings/ThemeEditorHost"; |
| 39 | import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; |
| 40 | import { Button } from "../components/ui/button"; |
| 41 | import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page"; |
| 42 | import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast"; |
| 43 | import { isElectron } from "../env"; |
| 44 | import { useClientSettings } from "../hooks/useSettings"; |
| 45 | import { |
| 46 | deriveLogicalProjectKeyFromSettings, |
| 47 | derivePhysicalProjectKeyFromPath, |
| 48 | selectProjectGroupingSettings, |
| 49 | } from "@t3tools/client-runtime/state/project-grouping"; |
| 50 | import { useUiStateStore } from "../uiStateStore"; |
| 51 | import { configureClientTracing } from "../observability/clientTracing"; |
| 52 | import { resolveInitialServerAuthGateState } from "../environments/primary"; |
| 53 | import { GUEST_PAGE_PATH } from "../guestPage"; |
| 54 | import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing"; |
| 55 | import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding"; |
| 56 | import { isLocalEnvironmentDisabled } from "../localEnvironment"; |
| 57 | import { useAtomValue } from "@effect/atom-react"; |
| 58 | import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../state/server"; |
| 59 | import { readProject } from "../state/entities"; |
| 60 | |
| 61 | import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; |
| 62 | import { isChunkLoadError } from "../lib/chunkReloadGuard"; |
| 63 | import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; |
| 64 | |
| 65 | export const Route = createRootRoute({ |
| 66 | beforeLoad: async ({ location }) => { |
| 67 | // Guest links open on the owner's tunnel host in a browser with no T3 session, and must |
| 68 | // not trigger pairing or an environment connection. |
| 69 | if (location.pathname === GUEST_PAGE_PATH) { |
| 70 | return { |
| 71 | authGateState: { |
| 72 | status: "guest", |
| 73 | } as const, |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) { |
| 78 | return { |
| 79 | authGateState: { |
| 80 | status: "hosted-pairing", |
| 81 | } as const, |
| 82 | }; |
| 83 | } |
| 84 | |
| 85 | if (isLocalEnvironmentDisabled() || isHostedStaticApp(new URL(window.location.href))) { |
| 86 | return { |
| 87 | authGateState: { |
| 88 | status: "hosted-static", |
| 89 | } as const, |
| 90 | }; |
| 91 | } |
| 92 | |
| 93 | const authGateState = await resolveInitialServerAuthGateState(); |
| 94 | if (authGateState.status === "authenticated") { |
| 95 | // Idempotent, so every navigation can ask for it. |
| 96 | void configureClientTracing(); |
| 97 | } |
| 98 | if ( |
| 99 | authGateState.status === "authenticated" && |
| 100 | getDesktopSnapShotBridge() && |
| 101 | shouldResumeSnapShotSetupOnStartup() && |
| 102 | location.pathname !== "/settings/snap-shot" |
| 103 | ) { |
| 104 | throw redirect({ to: "/settings/snap-shot", replace: true }); |
| 105 | } |
| 106 | return { |
| 107 | authGateState, |
| 108 | }; |
| 109 | }, |
| 110 | component: RootRouteView, |
| 111 | errorComponent: RootRouteErrorView, |
| 112 | notFoundComponent: RootRouteNotFoundView, |
| 113 | head: () => ({ |
| 114 | meta: [{ name: "title", content: APP_DISPLAY_NAME }], |
| 115 | }), |
| 116 | }); |
| 117 | |
| 118 | function RootRouteNotFoundView() { |
| 119 | return ( |
| 120 | <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-6"> |
| 121 | <div className="flex max-w-sm flex-col items-center gap-4 text-center"> |
| 122 | <h1 className="text-lg font-medium text-foreground"> |
| 123 | <T>Page not found</T> |
| 124 | </h1> |
| 125 | <p className="text-sm text-muted-foreground"> |
| 126 | <T> |
| 127 | This link doesn't point to a page in <Var>{APP_DISPLAY_NAME}</Var>. Go home to choose a |
| 128 | project or start a thread. |
| 129 | </T> |
| 130 | </p> |
| 131 | <Button render={<Link to="/" replace />}> |
| 132 | <T>Go home</T> |
| 133 | </Button> |
| 134 | </div> |
| 135 | </main> |
| 136 | ); |
| 137 | } |
| 138 | |
| 139 | function RootRouteView() { |
| 140 | // Above every branch: app services raise toasts for the whole page, so the surface they write to |
| 141 | // must not unmount when the root switches branches (for example /welcome to the app shell). |
| 142 | return ( |
| 143 | <ToastProvider> |
| 144 | <AnchoredToastProvider> |
| 145 | <RootRouteBranch /> |
| 146 | </AnchoredToastProvider> |
| 147 | </ToastProvider> |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | function RootRouteBranch() { |
| 152 | const pathname = useLocation({ select: (location) => location.pathname }); |
| 153 | const { authGateState } = Route.useRouteContext(); |
| 154 | const primaryEnvironmentAuthenticated = authGateState.status === "authenticated"; |
| 155 | // A sync IPC read; the setting only changes across a relaunch. |
| 156 | const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled); |
| 157 | // Once true, stays true: a visit to /welcome means the bootstrap already chose a route. |
| 158 | const [returningFromWelcome, setReturningFromWelcome] = useState(pathname === "/welcome"); |
| 159 | if (pathname === "/welcome" && !returningFromWelcome) setReturningFromWelcome(true); |
| 160 | const hostedPromptLinkLanding = useHostedPromptLinkLanding( |
| 161 | authGateState.status === "hosted-static", |
| 162 | ); |
| 163 | |
| 164 | if (pathname === GUEST_PAGE_PATH) return <Outlet />; |
| 165 | |
| 166 | if ( |
| 167 | pathname === "/pair" || |
| 168 | pathname === "/connect" || |
| 169 | pathname === "/connect-agent" || |
| 170 | pathname === "/approve-agent" |
| 171 | ) { |
| 172 | return <Outlet />; |
| 173 | } |
| 174 | |
| 175 | // Handle links before onboarding redirects lose them. |
| 176 | if (hostedPromptLinkLanding !== null) { |
| 177 | return hostedPromptLinkLanding; |
| 178 | } |
| 179 | |
| 180 | const isWelcome = pathname === "/welcome"; |
| 181 | if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") { |
| 182 | return <Outlet />; |
| 183 | } |
| 184 | |
| 185 | // Settings can reopen /welcome mid-session, so it mounts everything the app does except the |
| 186 | // first-run gate and the event router, whose first navigation would leave the page. |
| 187 | const appHosts = ( |
| 188 | <> |
| 189 | {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? ( |
| 190 | <> |
| 191 | <DesktopAppActivationCoordinator /> |
| 192 | <DesktopWebLinkCoordinator /> |
| 193 | </> |
| 194 | ) : null} |
| 195 | {isElectron ? <RunningThreadKeepAlive /> : null} |
| 196 | <RelayClientInstallDialog /> |
| 197 | <ConnectOnboardingDialog /> |
| 198 | <SshPasswordPromptDialog /> |
| 199 | <SnapShotCoordinator /> |
| 200 | <ReopenClosedViewShortcut /> |
| 201 | <ConfirmDialogHost /> |
| 202 | <CustomSnoozeDialogHost /> |
| 203 | <GuestShareDialogHost /> |
| 204 | <ProjectCloneToastCoordinator /> |
| 205 | <ConnectDeviceApprovalCoordinator /> |
| 206 | <AddProjectToMachineDialogHost /> |
| 207 | <UseInAnotherAppDialogHost /> |
| 208 | {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null} |
| 209 | </> |
| 210 | ); |
| 211 | const appShell = ( |
| 212 | <CommandPalette> |
| 213 | {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */} |
| 214 | <AppSidebarLayout showSidebar={!isWelcome}> |
| 215 | <Outlet /> |
| 216 | </AppSidebarLayout> |
| 217 | </CommandPalette> |
| 218 | ); |
| 219 | |
| 220 | return ( |
| 221 | <> |
| 222 | <ChatGptWelcomeCoordinator /> |
| 223 | {isWelcome ? ( |
| 224 | <> |
| 225 | {appHosts} |
| 226 | {appShell} |
| 227 | </> |
| 228 | ) : ( |
| 229 | <FirstRunGate |
| 230 | enabled={primaryEnvironmentAuthenticated} |
| 231 | hostedStatic={authGateState.status === "hosted-static"} |
| 232 | > |
| 233 | {appHosts} |
| 234 | {primaryEnvironmentAuthenticated ? ( |
| 235 | <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} /> |
| 236 | ) : null} |
| 237 | {appShell} |
| 238 | </FirstRunGate> |
| 239 | )} |
| 240 | {/* Above both shells and the router, so drafts survive navigation, including to /welcome. */} |
| 241 | <ThemeEditorHost /> |
| 242 | </> |
| 243 | ); |
| 244 | } |
| 245 | |
| 246 | function RootRouteErrorView({ error }: ErrorComponentProps) { |
| 247 | const router = useRouter(); |
| 248 | const gt = useGT(); |
| 249 | const message = errorMessage(error) ?? gt("An unexpected router error occurred."); |
| 250 | // Router pathname rather than window.location: desktop uses hash history, where the window path is always "/". |
| 251 | const pathname = useLocation({ select: (location) => location.pathname }); |
| 252 | const report = errorReport(error, pathname); |
| 253 | |
| 254 | return ( |
| 255 | <StandalonePage> |
| 256 | <StandalonePageHeader title={gt("Something went wrong.")} description={message} /> |
| 257 | |
| 258 | <div className="mt-5 flex flex-wrap gap-2"> |
| 259 | <Button |
| 260 | size="sm" |
| 261 | onClick={() => |
| 262 | isChunkLoadError(error) ? window.location.reload() : void router.invalidate() |
| 263 | } |
| 264 | > |
| 265 | <T>Try again</T> |
| 266 | </Button> |
| 267 | <Button size="sm" variant="outline" onClick={() => window.location.reload()}> |
| 268 | <T>Reload app</T> |
| 269 | </Button> |
| 270 | <CopyErrorButton report={report} /> |
| 271 | </div> |
| 272 | |
| 273 | <div className="mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55"> |
| 274 | <p className="px-3 py-1.5 text-xs font-medium text-muted-foreground"> |
| 275 | <T>Error report</T> |
| 276 | </p> |
| 277 | <pre className="max-h-64 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs whitespace-pre-wrap text-foreground/85"> |
| 278 | {report} |
| 279 | </pre> |
| 280 | </div> |
| 281 | </StandalonePage> |
| 282 | ); |
| 283 | } |
| 284 | |
| 285 | function CopyErrorButton({ report }: { report: string }) { |
| 286 | const { copyToClipboard, isCopied } = useCopyToClipboard({ |
| 287 | target: { |
| 288 | target: "error-report", |
| 289 | unavailableMessage: msg("Clipboard API is unavailable while copying error-report."), |
| 290 | failureMessage: msg("Failed to copy error-report to the clipboard."), |
| 291 | }, |
| 292 | }); |
| 293 | const gt = useGT(); |
| 294 | |
| 295 | return ( |
| 296 | <Button size="sm" variant="outline" onClick={() => copyToClipboard(report)}> |
| 297 | {isCopied ? <CheckIcon className="text-success" /> : <CopyIcon />} |
| 298 | {isCopied ? gt("Copied") : gt("Copy error")} |
| 299 | </Button> |
| 300 | ); |
| 301 | } |
| 302 | |
| 303 | function errorMessage(error: unknown): string | null { |
| 304 | if (error instanceof Error && error.message.trim().length > 0) { |
| 305 | return error.message; |
| 306 | } |
| 307 | |
| 308 | if (typeof error === "string" && error.trim().length > 0) { |
| 309 | return error; |
| 310 | } |
| 311 | |
| 312 | return null; |
| 313 | } |
| 314 | |
| 315 | function errorDetails(error: unknown): string { |
| 316 | if (error instanceof Error) { |
| 317 | return error.stack ?? error.message; |
| 318 | } |
| 319 | |
| 320 | if (typeof error === "string") { |
| 321 | return error; |
| 322 | } |
| 323 | |
| 324 | try { |
| 325 | return JSON.stringify(error, null, 2); |
| 326 | } catch { |
| 327 | // oxlint-disable-next-line t3code/no-untranslated-copy -- error report pasted into bug reports |
| 328 | return "No additional error details are available."; |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | const MAX_ERROR_CAUSE_DEPTH = 5; |
| 333 | |
| 334 | // Use only pathname to keep query tokens off the clipboard. |
| 335 | function errorReport(error: unknown, pathname: string): string { |
| 336 | const lines = [ |
| 337 | `${APP_DISPLAY_NAME} ${APP_VERSION}`, |
| 338 | `Path: ${pathname}`, |
| 339 | `Time: ${new Date().toISOString()}`, |
| 340 | "", |
| 341 | errorDetails(error), |
| 342 | ]; |
| 343 | let cause = error instanceof Error ? error.cause : undefined; |
| 344 | for (let depth = 0; cause !== undefined && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) { |
| 345 | lines.push("", "Caused by:", errorDetails(cause)); |
| 346 | cause = cause instanceof Error ? cause.cause : undefined; |
| 347 | } |
| 348 | return lines.join("\n"); |
| 349 | } |
| 350 | |
| 351 | function EventRouter({ |
| 352 | skipInitialBootstrapNavigation, |
| 353 | }: { |
| 354 | readonly skipInitialBootstrapNavigation: boolean; |
| 355 | }) { |
| 356 | const navigate = useNavigate(); |
| 357 | const pathname = useLocation({ select: (loc) => loc.pathname }); |
| 358 | const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); |
| 359 | const serverConfig = useAtomValue(primaryServerConfigAtom); |
| 360 | const serverWelcome = useAtomValue(primaryServerWelcomeAtom); |
| 361 | const readPathname = useEffectEvent(() => pathname); |
| 362 | const handledBootstrapThreadIdRef = useRef<string | null>(null); |
| 363 | const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation); |
| 364 | |
| 365 | const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => { |
| 366 | if (!payload) return; |
| 367 | |
| 368 | void (async () => { |
| 369 | if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) { |
| 370 | return; |
| 371 | } |
| 372 | const bootstrapProject = readProject( |
| 373 | scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId), |
| 374 | ); |
| 375 | const bootstrapProjectKey = |
| 376 | (bootstrapProject |
| 377 | ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings) |
| 378 | : null) ?? |
| 379 | (serverConfig?.cwd |
| 380 | ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd) |
| 381 | : null) ?? |
| 382 | scopedProjectKey( |
| 383 | scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId), |
| 384 | ); |
| 385 | useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true); |
| 386 | |
| 387 | if (readPathname() !== "/") { |
| 388 | return; |
| 389 | } |
| 390 | if (skipInitialBootstrapNavigationRef.current) { |
| 391 | skipInitialBootstrapNavigationRef.current = false; |
| 392 | handledBootstrapThreadIdRef.current = payload.bootstrapThreadId; |
| 393 | return; |
| 394 | } |
| 395 | if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) { |
| 396 | return; |
| 397 | } |
| 398 | await navigate({ |
| 399 | to: "/$environmentId/$threadId", |
| 400 | params: { |
| 401 | environmentId: payload.environment.environmentId, |
| 402 | threadId: payload.bootstrapThreadId, |
| 403 | }, |
| 404 | replace: true, |
| 405 | }); |
| 406 | handledBootstrapThreadIdRef.current = payload.bootstrapThreadId; |
| 407 | })().catch(() => undefined); |
| 408 | }); |
| 409 | |
| 410 | // 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 |
| 411 | useEffect(() => { |
| 412 | handleWelcome(serverWelcome); |
| 413 | }, [serverWelcome]); |
| 414 | |
| 415 | return null; |
| 416 | } |