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 { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { m } from "~/i18n/messages"; |
| 3 | import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 4 | import { |
| 5 | isAtomCommandInterrupted, |
| 6 | squashAtomCommandFailure, |
| 7 | } from "@t3tools/client-runtime/state/runtime"; |
| 8 | import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; |
| 9 | import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; |
| 10 | import { promptLinkAppPath } from "@t3tools/shared/promptLinks"; |
| 11 | import { readPairingAppLink, resolveRemotePairingTarget } from "@t3tools/shared/remote"; |
| 12 | import { useRouter } from "@tanstack/react-router"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import { AtomRegistry } from "effect/reactivity"; |
| 15 | import * as Stream from "effect/Stream"; |
| 16 | import { useGT } from "gt-react"; |
| 17 | import { useEffect, useEffectEvent, useRef, useState } from "react"; |
| 18 | |
| 19 | import { openFileInPreview, openUrlInPreview } from "../../browser/openFileInPreview"; |
| 20 | import { isPreviewAvailableFor } from "../../browser/previewRuntime"; |
| 21 | import { requestConfirmDialog } from "../../confirmDialog"; |
| 22 | import { connectPairing } from "../../connection/onboarding"; |
| 23 | import { isLocalEnvironmentDisabled } from "../../localEnvironment"; |
| 24 | import { useComposerDraftStore } from "../../composerDraftStore"; |
| 25 | import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; |
| 26 | import { useScratchProject } from "../../hooks/useScratchProject"; |
| 27 | import { useClientSettings } from "../../hooks/useSettings"; |
| 28 | import { useOpenChangeRequestLink } from "../../lib/openPullRequestLink"; |
| 29 | import { selectActiveRightPanelSurface, useRightPanelStore } from "../../rightPanelStore"; |
| 30 | import { appAtomRegistry } from "../../rpc/atomRegistry"; |
| 31 | import { resolveThreadRouteTarget } from "../../threadRoutes"; |
| 32 | import { assetEnvironment } from "../../state/assets"; |
| 33 | import { readProject, readThreadShell } from "../../state/entities"; |
| 34 | import { useEnvironmentHttpBaseUrl, usePrimaryEnvironment } from "../../state/environments"; |
| 35 | import { previewEnvironment } from "../../state/preview"; |
| 36 | import { allReachableShellsLiveAtom } from "../../state/shell"; |
| 37 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 38 | import { useAtomQueryRunner } from "../../state/use-atom-query-runner"; |
| 39 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 40 | |
| 41 | /** A link handed over by the OS is a plain click: nothing about it asks for the browser. */ |
| 42 | const externalClick = { |
| 43 | preventDefault() {}, |
| 44 | stopPropagation() {}, |
| 45 | metaKey: false, |
| 46 | ctrlKey: false, |
| 47 | }; |
| 48 | |
| 49 | /** Resolves once every reachable environment has reported its projects or settled offline. */ |
| 50 | const projectsSettled = (): Promise<void> => |
| 51 | Effect.runPromise( |
| 52 | AtomRegistry.toStream(appAtomRegistry, allReachableShellsLiveAtom).pipe( |
| 53 | Stream.filter((settled) => settled), |
| 54 | Stream.runHead, |
| 55 | Effect.asVoid, |
| 56 | ), |
| 57 | ); |
| 58 | |
| 59 | /** |
| 60 | * HTML files are served by this machine's environment, so only its threads can |
| 61 | * take them. |
| 62 | */ |
| 63 | function threadShowingBrowser( |
| 64 | routeParams: Record<string, string | undefined>, |
| 65 | fileEnvironmentId: EnvironmentId | null, |
| 66 | ): ScopedThreadRef | null { |
| 67 | const target = resolveThreadRouteTarget(routeParams); |
| 68 | if (target === null) return null; |
| 69 | let threadRef = target.kind === "server" ? target.threadRef : null; |
| 70 | if (target.kind === "draft") { |
| 71 | const session = useComposerDraftStore.getState().getDraftSession(target.draftId); |
| 72 | if (!session || session.promotedTo) return null; |
| 73 | threadRef = scopeThreadRef(session.environmentId, session.threadId); |
| 74 | } |
| 75 | if (threadRef === null || !isPreviewAvailableFor(threadRef.environmentId)) return null; |
| 76 | if (fileEnvironmentId !== null && threadRef.environmentId !== fileEnvironmentId) return null; |
| 77 | const surface = selectActiveRightPanelSurface( |
| 78 | useRightPanelStore.getState().byThreadKey, |
| 79 | threadRef, |
| 80 | ); |
| 81 | return surface?.kind === "preview" ? threadRef : null; |
| 82 | } |
| 83 | |
| 84 | export function DesktopWebLinkCoordinator() { |
| 85 | const router = useRouter(); |
| 86 | const gt = useGT(); |
| 87 | const primaryEnvironment = usePrimaryEnvironment(); |
| 88 | const openPullRequestsInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp); |
| 89 | const openChangeRequest = useOpenChangeRequestLink(); |
| 90 | const { scratchEnvironmentId, openScratchProject } = useScratchProject(); |
| 91 | const openThread = useNewThreadHandler(); |
| 92 | const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); |
| 93 | const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { |
| 94 | reportFailure: false, |
| 95 | refresh: true, |
| 96 | }); |
| 97 | const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false }); |
| 98 | const httpBaseUrl = useEnvironmentHttpBaseUrl(primaryEnvironment?.environmentId ?? null); |
| 99 | const queueRef = useRef(Promise.resolve()); |
| 100 | const pairedUrlsRef = useRef(new Set<string>()); |
| 101 | const webLinks = window.desktopBridge?.webLinks; |
| 102 | // A sync IPC read; the setting only changes across a relaunch. |
| 103 | const [localEnvironmentDisabled] = useState(isLocalEnvironmentDisabled); |
| 104 | // With Local environment disabled there is no primary to wait for, so links run against the |
| 105 | // saved remote environments instead of waiting forever. |
| 106 | const ready = |
| 107 | webLinks !== undefined && |
| 108 | (localEnvironmentDisabled || |
| 109 | (primaryEnvironment?.connection.phase === "connected" && |
| 110 | primaryEnvironment.serverConfig !== null)); |
| 111 | |
| 112 | const reportFailure = (url: string, description = url) => |
| 113 | toastManager.add( |
| 114 | stackedThreadToast({ type: "error", title: gt("Could not open the link"), description }), |
| 115 | ); |
| 116 | |
| 117 | const reportPairingFailure = (error: unknown) => |
| 118 | toastManager.add( |
| 119 | stackedThreadToast({ |
| 120 | type: "error", |
| 121 | title: gt("Could not add backend"), |
| 122 | description: thrownErrorMessage(error, m) ?? gt("Failed to add backend."), |
| 123 | }), |
| 124 | ); |
| 125 | |
| 126 | // Any page can open a pairing link, so the user confirms the host before its one-time token is spent. |
| 127 | const pairFromLink = async (pairingUrl: string) => { |
| 128 | // A repeated click would only ask again and then fail on the spent one-time token. |
| 129 | if (pairedUrlsRef.current.has(pairingUrl)) return; |
| 130 | // The origin keeps the scheme visible, so a plain HTTP backend is not mistaken for HTTPS. |
| 131 | let origin: string; |
| 132 | try { |
| 133 | origin = new URL(resolveRemotePairingTarget({ pairingUrl }).httpBaseUrl).origin; |
| 134 | } catch (error) { |
| 135 | reportPairingFailure(error); |
| 136 | return; |
| 137 | } |
| 138 | const confirmed = |
| 139 | (await requestConfirmDialog(gt("Add the backend at {origin}?", { origin }))) ?? false; |
| 140 | if (!confirmed) return; |
| 141 | const result = await connectPairingEnvironment({ pairingUrl }); |
| 142 | if (result._tag === "Failure") { |
| 143 | if (!isAtomCommandInterrupted(result)) reportPairingFailure(squashAtomCommandFailure(result)); |
| 144 | return; |
| 145 | } |
| 146 | pairedUrlsRef.current.add(pairingUrl); |
| 147 | toastManager.add({ |
| 148 | type: "success", |
| 149 | title: gt("Backend added"), |
| 150 | description: gt("The environment is saved and will reconnect on app startup."), |
| 151 | }); |
| 152 | }; |
| 153 | |
| 154 | const startThread = async (url: string): Promise<ScopedThreadRef | null> => { |
| 155 | const environmentId = scratchEnvironmentId(primaryEnvironment?.environmentId ?? null); |
| 156 | if (environmentId === null) { |
| 157 | reportFailure(url); |
| 158 | return null; |
| 159 | } |
| 160 | const project = await openScratchProject(environmentId, gt("Could not open the link")); |
| 161 | if (!project) return null; |
| 162 | const opened = await openThread(scopeProjectRef(project.environmentId, project.id)); |
| 163 | if (!opened) { |
| 164 | reportFailure(url); |
| 165 | return null; |
| 166 | } |
| 167 | const threadRef = scopeThreadRef(project.environmentId, opened.threadId); |
| 168 | useRightPanelStore.getState().requestMaximize(threadRef); |
| 169 | return threadRef; |
| 170 | }; |
| 171 | |
| 172 | const openInBrowser = useEffectEvent(async (url: string) => { |
| 173 | const routeParams = router.state.matches.at(-1)?.params ?? {}; |
| 174 | const isFile = url.startsWith("file:"); |
| 175 | // Only this machine's environment serves files, so fail before starting a thread. |
| 176 | if (isFile && httpBaseUrl === null) { |
| 177 | reportFailure(url); |
| 178 | return; |
| 179 | } |
| 180 | const threadRef = |
| 181 | threadShowingBrowser( |
| 182 | routeParams, |
| 183 | isFile ? (primaryEnvironment?.environmentId ?? null) : null, |
| 184 | ) ?? (await startThread(url)); |
| 185 | if (threadRef === null) return; |
| 186 | const result = isFile |
| 187 | ? httpBaseUrl === null |
| 188 | ? null |
| 189 | : await openFileInPreview({ |
| 190 | threadRef, |
| 191 | filePath: decodeURIComponent(new URL(url).pathname), |
| 192 | workspaceRoot: undefined, |
| 193 | httpBaseUrl, |
| 194 | createAssetUrl, |
| 195 | openPreview, |
| 196 | }) |
| 197 | : await openUrlInPreview({ threadRef, url, openPreview }); |
| 198 | if (result === null) { |
| 199 | reportFailure(url); |
| 200 | return; |
| 201 | } |
| 202 | if (result._tag === "Failure") { |
| 203 | const error = squashAtomCommandFailure(result); |
| 204 | reportFailure(url, thrownErrorMessage(error, m) ?? url); |
| 205 | } |
| 206 | }); |
| 207 | |
| 208 | const openLink = useEffectEvent(async (url: string) => { |
| 209 | const pairingUrl = readPairingAppLink(url); |
| 210 | if (pairingUrl !== null) { |
| 211 | await pairFromLink(pairingUrl); |
| 212 | return; |
| 213 | } |
| 214 | const appPath = promptLinkAppPath(url); |
| 215 | if (appPath !== null) { |
| 216 | await router.navigate({ href: appPath }); |
| 217 | return; |
| 218 | } |
| 219 | const routeParams = router.state.matches.at(-1)?.params ?? {}; |
| 220 | const routeTarget = resolveThreadRouteTarget(routeParams); |
| 221 | const activeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : undefined; |
| 222 | const activeThread = activeThreadRef ? readThreadShell(activeThreadRef) : null; |
| 223 | const activeProject = |
| 224 | activeThread && activeThreadRef |
| 225 | ? readProject(scopeProjectRef(activeThreadRef.environmentId, activeThread.projectId)) |
| 226 | : null; |
| 227 | const commitThreadRef = |
| 228 | activeThread && |
| 229 | sourceControlClients.parseCommitUrl(url, activeProject?.repositoryIdentity?.provider) !== null |
| 230 | ? activeThreadRef |
| 231 | : undefined; |
| 232 | // A commit the thread's workspace lacks continues here, after its lookup. |
| 233 | const openUnavailableCommit = () => { |
| 234 | queueRef.current = queueRef.current.then(() => openInBrowser(url)).catch(() => undefined); |
| 235 | }; |
| 236 | if (openChangeRequest(externalClick, url, commitThreadRef, undefined, openUnavailableCommit)) |
| 237 | return; |
| 238 | await openInBrowser(url); |
| 239 | }); |
| 240 | |
| 241 | const receiveLink = useEffectEvent((url: string) => { |
| 242 | // A connected server publishes its config before its project snapshot, so a source control |
| 243 | // link delivered at launch would miss its project and fall through to the browser. Hold |
| 244 | // those links until discovery settles; an ordinary link never waits for it. |
| 245 | const hold = |
| 246 | openPullRequestsInApp && |
| 247 | (sourceControlClients.parseChangeRequestUrl(url) !== null || |
| 248 | sourceControlClients.parseCommitUrl(url) !== null) |
| 249 | ? projectsSettled() |
| 250 | : Promise.resolve(); |
| 251 | void hold.then(() => { |
| 252 | queueRef.current = queueRef.current.then(() => openLink(url)).catch(() => undefined); |
| 253 | }); |
| 254 | }); |
| 255 | |
| 256 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop web link opens over the bridge and marks the renderer ready |
| 257 | useEffect(() => { |
| 258 | if (!ready || webLinks === undefined) return; |
| 259 | let subscribed = true; |
| 260 | const unsubscribe = webLinks.onOpen(receiveLink); |
| 261 | queueMicrotask(() => { |
| 262 | if (subscribed) void webLinks.setReady(true).catch(() => undefined); |
| 263 | }); |
| 264 | return () => { |
| 265 | subscribed = false; |
| 266 | void webLinks.setReady(false).catch(() => undefined); |
| 267 | unsubscribe(); |
| 268 | }; |
| 269 | }, [ready, webLinks]); |
| 270 | |
| 271 | return null; |
| 272 | } |