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 { useAtomValue } from "@effect/atom-react"; |
| 3 | import { |
| 4 | AuthEnvironmentMaintainScope, |
| 5 | type AuthSessionState, |
| 6 | sessionGrantsScope, |
| 7 | } from "@t3tools/contracts"; |
| 8 | import { managedUpdatesDenial } from "@t3tools/client-runtime/contract-labels"; |
| 9 | import type { AsyncResult } from "effect/reactivity"; |
| 10 | import { environmentSession } from "~/state/session"; |
| 11 | import type { |
| 12 | DesktopUpdateChannel, |
| 13 | EnvironmentId, |
| 14 | ServerInstallation, |
| 15 | ServerSelfUpdateCapability, |
| 16 | } from "@t3tools/contracts"; |
| 17 | import { |
| 18 | serverUpdateFailureText, |
| 19 | type ServerUpdateStage, |
| 20 | type ServerUpdateState, |
| 21 | } from "@t3tools/client-runtime/state/server"; |
| 22 | import { |
| 23 | isAtomCommandInterrupted, |
| 24 | settlePromise, |
| 25 | squashAtomCommandFailure, |
| 26 | } from "@t3tools/client-runtime/state/runtime"; |
| 27 | import { CircleArrowUpIcon } from "lucide-react"; |
| 28 | import { type ComponentProps, useRef, useState } from "react"; |
| 29 | import { msg, T, useGT, useMessages } from "gt-react"; |
| 30 | import { m, type MessageResolver } from "../i18n/messages"; |
| 31 | |
| 32 | import { requestConfirmDialog } from "~/confirmDialog"; |
| 33 | import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; |
| 34 | import { serverEnvironment, updateOutdatedServer } from "~/state/server"; |
| 35 | import { appAtomRegistry } from "~/rpc/atomRegistry"; |
| 36 | import { useAtomCommand } from "~/state/use-atom-command"; |
| 37 | import { useServerConfigs } from "~/state/entities"; |
| 38 | import { useManagedPolicy } from "~/state/managedPolicy"; |
| 39 | import { environmentPresentations } from "~/state/presentation"; |
| 40 | import { ManagedControl } from "./ManagedPolicy"; |
| 41 | import { manualServerUpdateCommand } from "~/versionSkew"; |
| 42 | import { crossesReleaseTrack } from "@t3tools/shared/cliRelease"; |
| 43 | import { Button } from "./ui/button"; |
| 44 | import { toastManager } from "./ui/toast"; |
| 45 | import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; |
| 46 | |
| 47 | const UPDATE_STAGE_LABELS: Record<ServerUpdateStage, string> = { |
| 48 | downloading: msg("Downloading…"), |
| 49 | installing: msg("Downloading…"), |
| 50 | resuming: msg("Restarting…"), |
| 51 | }; |
| 52 | const pendingUpdateEnvironmentIds = new Set<EnvironmentId>(); |
| 53 | |
| 54 | export function serverUpdateStageLabel( |
| 55 | stage: ServerUpdateStage, |
| 56 | resolve: MessageResolver = m, |
| 57 | ): string { |
| 58 | return resolve(UPDATE_STAGE_LABELS[stage]); |
| 59 | } |
| 60 | |
| 61 | /** Why the environment's policy refuses server updates, read outside render. */ |
| 62 | function readUpdatesDenial(environmentId: EnvironmentId): string | undefined { |
| 63 | return managedUpdatesDenial( |
| 64 | appAtomRegistry.get(environmentPresentations.serverConfigsAtom).get(environmentId) |
| 65 | ?.managedPolicy, |
| 66 | m, |
| 67 | ); |
| 68 | } |
| 69 | |
| 70 | /** Hosts refuse a Stable/Nightly crossing outside a track switch, which checks the database first. */ |
| 71 | function refusedCrossing( |
| 72 | target: { |
| 73 | readonly selfUpdate: ServerSelfUpdateCapability | null; |
| 74 | readonly targetVersion: string; |
| 75 | readonly channel?: DesktopUpdateChannel | undefined; |
| 76 | }, |
| 77 | serverVersion: string | undefined, |
| 78 | ): boolean { |
| 79 | return ( |
| 80 | target.channel === undefined && |
| 81 | target.selfUpdate !== null && |
| 82 | serverVersion !== undefined && |
| 83 | crossesReleaseTrack(serverVersion, target.targetVersion) |
| 84 | ); |
| 85 | } |
| 86 | |
| 87 | function CrossTrackNote() { |
| 88 | return ( |
| 89 | <span className="text-muted-foreground text-xs"> |
| 90 | <T>Switch tracks in About → Update track</T> |
| 91 | </span> |
| 92 | ); |
| 93 | } |
| 94 | |
| 95 | function updateFailureMessage(error: unknown): string { |
| 96 | return thrownErrorMessage(error, m) ?? m(msg("Server update failed.")); |
| 97 | } |
| 98 | |
| 99 | export interface ServerUpdateTarget { |
| 100 | readonly environmentId: EnvironmentId; |
| 101 | readonly serverLabel: string; |
| 102 | readonly selfUpdate: ServerSelfUpdateCapability | null; |
| 103 | readonly installation?: ServerInstallation | undefined; |
| 104 | readonly desktopAppUpdate?: boolean; |
| 105 | readonly targetVersion: string; |
| 106 | /** Set only by a track switch; the host's desktop app moves to this track. */ |
| 107 | readonly channel?: DesktopUpdateChannel; |
| 108 | /** A track switch's checked release migration; the host re-checks its own database. */ |
| 109 | readonly targetDatabaseMigration?: number; |
| 110 | /** The host already runs its track's newest build and only saves the track. */ |
| 111 | readonly trackOnly?: boolean; |
| 112 | } |
| 113 | |
| 114 | type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & { |
| 115 | readonly label?: string; |
| 116 | readonly appearance?: "button" | "icon"; |
| 117 | }; |
| 118 | |
| 119 | export type ServerUpdateOutcome = |
| 120 | | { readonly status: "updated" | "skipped" } |
| 121 | | { readonly status: "failed"; readonly message: string }; |
| 122 | |
| 123 | /** Toasts its success or failure unless `quiet`; never rejects. */ |
| 124 | export function useServerUpdate() { |
| 125 | const updateServer = useAtomCommand(serverEnvironment.updateServer, { reportFailure: false }); |
| 126 | return async ( |
| 127 | target: ServerUpdateTarget, |
| 128 | { quiet = false }: { readonly quiet?: boolean } = {}, |
| 129 | ): Promise<ServerUpdateOutcome> => { |
| 130 | const { environmentId, serverLabel, selfUpdate, targetVersion } = target; |
| 131 | const denial = readUpdatesDenial(environmentId); |
| 132 | if (denial !== undefined) { |
| 133 | if (!quiet) { |
| 134 | toastManager.add({ |
| 135 | type: "error", |
| 136 | title: m(msg("{serverLabel} not updated", { serverLabel })), |
| 137 | description: denial, |
| 138 | }); |
| 139 | } |
| 140 | return { status: "failed", message: denial }; |
| 141 | } |
| 142 | if ( |
| 143 | !canUpdateServer(appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId))) || |
| 144 | pendingUpdateEnvironmentIds.has(environmentId) |
| 145 | ) |
| 146 | return { status: "skipped" }; |
| 147 | pendingUpdateEnvironmentIds.add(environmentId); |
| 148 | const result = await updateServer({ |
| 149 | environmentId, |
| 150 | input: { |
| 151 | targetVersion, |
| 152 | ...(target.channel === undefined ? {} : { channel: target.channel }), |
| 153 | ...(target.targetDatabaseMigration === undefined |
| 154 | ? {} |
| 155 | : { targetDatabaseMigration: target.targetDatabaseMigration }), |
| 156 | }, |
| 157 | }); |
| 158 | pendingUpdateEnvironmentIds.delete(environmentId); |
| 159 | if (result._tag === "Failure") { |
| 160 | if (isAtomCommandInterrupted(result)) return { status: "skipped" }; |
| 161 | const message = updateFailureMessage(squashAtomCommandFailure(result)); |
| 162 | if (!quiet) { |
| 163 | toastManager.add({ |
| 164 | type: "error", |
| 165 | title: m(msg("{serverLabel} update failed", { serverLabel })), |
| 166 | description: message, |
| 167 | }); |
| 168 | } |
| 169 | return { status: "failed", message }; |
| 170 | } |
| 171 | if (!quiet) { |
| 172 | toastManager.add({ |
| 173 | type: "success", |
| 174 | title: m(msg("{serverLabel} updated", { serverLabel })), |
| 175 | description: |
| 176 | selfUpdate === "desktop-managed" |
| 177 | ? m( |
| 178 | msg("Desktop app relaunched on {version}.", { |
| 179 | version: result.value.targetVersion, |
| 180 | }), |
| 181 | ) |
| 182 | : m(msg("Reconnected on t3@{version}.", { version: result.value.targetVersion })), |
| 183 | }); |
| 184 | } |
| 185 | return { status: "updated" }; |
| 186 | }; |
| 187 | } |
| 188 | |
| 189 | export function ServerUpdatesAction({ |
| 190 | targets, |
| 191 | label, |
| 192 | variant = "outline", |
| 193 | size = "xs", |
| 194 | className, |
| 195 | }: UpdateButtonProps & { |
| 196 | readonly targets: ReadonlyArray<ServerUpdateTarget>; |
| 197 | }) { |
| 198 | const gt = useGT(); |
| 199 | const messages = useMessages(); |
| 200 | const update = useServerUpdate(); |
| 201 | const serverConfigs = useServerConfigs(); |
| 202 | const pending = useRef(false); |
| 203 | const [isPending, setIsPending] = useState(false); |
| 204 | const eligible = targets.filter( |
| 205 | (target) => |
| 206 | target.selfUpdate !== null && |
| 207 | (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) && |
| 208 | managedUpdatesDenial(serverConfigs.get(target.environmentId)?.managedPolicy, messages) === |
| 209 | undefined && |
| 210 | !refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion), |
| 211 | ); |
| 212 | const handleUpdate = async () => { |
| 213 | if (pending.current) return; |
| 214 | pending.current = true; |
| 215 | setIsPending(true); |
| 216 | await settlePromise(async () => { |
| 217 | const available = eligible.filter( |
| 218 | (target) => !pendingUpdateEnvironmentIds.has(target.environmentId), |
| 219 | ); |
| 220 | const desktopTargets = available.filter((target) => target.selfUpdate === "desktop-managed"); |
| 221 | if (desktopTargets.length > 0) { |
| 222 | const confirmed = |
| 223 | (await requestConfirmDialog( |
| 224 | gt( |
| 225 | "Update the T3 Code desktop apps on {servers}? They will close and relaunch on those machines.", |
| 226 | { servers: desktopTargets.map((target) => target.serverLabel).join(", ") }, |
| 227 | ), |
| 228 | { initialFocus: "confirm" }, |
| 229 | )) ?? true; |
| 230 | if (!confirmed) return; |
| 231 | } |
| 232 | await Promise.all(available.map((target) => update(target))); |
| 233 | }); |
| 234 | pending.current = false; |
| 235 | setIsPending(false); |
| 236 | }; |
| 237 | return ( |
| 238 | <Button |
| 239 | size={size} |
| 240 | variant={variant} |
| 241 | className={className} |
| 242 | disabled={isPending || eligible.length === 0} |
| 243 | onClick={() => void handleUpdate()} |
| 244 | > |
| 245 | {label ?? gt("Update all")} |
| 246 | </Button> |
| 247 | ); |
| 248 | } |
| 249 | |
| 250 | export function canUpdateServer( |
| 251 | result: AsyncResult.AsyncResult<AuthSessionState, unknown>, |
| 252 | ): boolean { |
| 253 | if (result._tag !== "Success" || !result.value.authenticated) return false; |
| 254 | return sessionGrantsScope(result.value, AuthEnvironmentMaintainScope); |
| 255 | } |
| 256 | |
| 257 | export function ServerUpdateProgress({ |
| 258 | state, |
| 259 | }: { |
| 260 | readonly state: Exclude<ServerUpdateState, { status: "idle" }>; |
| 261 | }) { |
| 262 | const messages = useMessages(); |
| 263 | if (state.status === "failed") { |
| 264 | return ( |
| 265 | <div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-destructive" role="alert"> |
| 266 | <span className="size-1.5 shrink-0 rounded-full bg-destructive" aria-hidden="true" /> |
| 267 | <Tooltip> |
| 268 | <TooltipTrigger |
| 269 | render={ |
| 270 | <span className="min-w-0 truncate">{serverUpdateFailureText(state, messages)}</span> |
| 271 | } |
| 272 | /> |
| 273 | <TooltipPopup side="top">{serverUpdateFailureText(state, messages)}</TooltipPopup> |
| 274 | </Tooltip> |
| 275 | </div> |
| 276 | ); |
| 277 | } |
| 278 | return ( |
| 279 | <div className="mt-1 flex items-center gap-2 text-xs font-medium text-foreground"> |
| 280 | <span className="size-1.5 shrink-0 rounded-full bg-foreground" aria-hidden="true" /> |
| 281 | <span>{serverUpdateStageLabel(state.stage, messages)}</span> |
| 282 | </div> |
| 283 | ); |
| 284 | } |
| 285 | |
| 286 | /** client-runtime owns self-updates so unmounting during reconnect preserves operation state. */ |
| 287 | export function ServerUpdateAction({ |
| 288 | environmentId, |
| 289 | serverLabel, |
| 290 | selfUpdate, |
| 291 | installation, |
| 292 | desktopAppUpdate = false, |
| 293 | targetVersion, |
| 294 | channel, |
| 295 | label, |
| 296 | variant = "outline", |
| 297 | size = "xs", |
| 298 | className, |
| 299 | appearance = "button", |
| 300 | }: ServerUpdateTarget & UpdateButtonProps) { |
| 301 | const gt = useGT(); |
| 302 | const messages = useMessages(); |
| 303 | const isDesktopAppUpdate = selfUpdate === "desktop-managed"; |
| 304 | const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion; |
| 305 | const sessionStateAtom = environmentSession.sessionStateAtom(environmentId); |
| 306 | const canUpdate = useAtomValue(sessionStateAtom, canUpdateServer); |
| 307 | const updatesDenial = managedUpdatesDenial(useManagedPolicy(environmentId), messages); |
| 308 | const update = useServerUpdate(); |
| 309 | const updatesInstall = |
| 310 | installation?.kind === "npm-global" || installation?.kind === "t3-launcher"; |
| 311 | const { copyToClipboard } = useCopyToClipboard<{ command: string }>({ |
| 312 | target: updatesInstall |
| 313 | ? { |
| 314 | target: "update command", |
| 315 | unavailableMessage: msg("Clipboard API is unavailable while copying update command."), |
| 316 | failureMessage: msg("Failed to copy update command to the clipboard."), |
| 317 | } |
| 318 | : { |
| 319 | target: "relaunch command", |
| 320 | unavailableMessage: msg("Clipboard API is unavailable while copying relaunch command."), |
| 321 | failureMessage: msg("Failed to copy relaunch command to the clipboard."), |
| 322 | }, |
| 323 | onCopy: ({ command }) => { |
| 324 | toastManager.add({ |
| 325 | type: "success", |
| 326 | title: updatesInstall ? gt("Update command copied") : gt("Relaunch command copied"), |
| 327 | description: updatesInstall |
| 328 | ? gt("Run `{command}` on {serverLabel}, then restart t3 with your usual options.", { |
| 329 | command, |
| 330 | serverLabel, |
| 331 | }) |
| 332 | : gt( |
| 333 | "Stop t3 on {serverLabel}, then relaunch with `{command}` using the same subcommand and options. This does not update an installed t3 command.", |
| 334 | { command, serverLabel }, |
| 335 | ), |
| 336 | }); |
| 337 | }, |
| 338 | onError: (error) => { |
| 339 | toastManager.add({ |
| 340 | type: "error", |
| 341 | title: gt("Could not copy update command"), |
| 342 | description: error.message, |
| 343 | }); |
| 344 | }, |
| 345 | }); |
| 346 | |
| 347 | const handleUpdate = async () => { |
| 348 | if ( |
| 349 | !canUpdateServer(appAtomRegistry.get(sessionStateAtom)) || |
| 350 | pendingUpdateEnvironmentIds.has(environmentId) |
| 351 | ) { |
| 352 | return; |
| 353 | } |
| 354 | if (isDesktopAppUpdate) { |
| 355 | const confirmed = |
| 356 | (await requestConfirmDialog( |
| 357 | gt( |
| 358 | "Update the T3 Code desktop app that runs the {serverLabel}? It will close and relaunch on that machine.", |
| 359 | { serverLabel }, |
| 360 | ), |
| 361 | { initialFocus: "confirm" }, |
| 362 | )) ?? true; |
| 363 | if (!confirmed) { |
| 364 | return; |
| 365 | } |
| 366 | } |
| 367 | if (!canUpdateServer(appAtomRegistry.get(sessionStateAtom))) return; |
| 368 | await update({ |
| 369 | environmentId, |
| 370 | serverLabel, |
| 371 | selfUpdate, |
| 372 | desktopAppUpdate, |
| 373 | targetVersion, |
| 374 | }); |
| 375 | }; |
| 376 | |
| 377 | if (updatesDenial !== undefined) { |
| 378 | return appearance === "icon" ? ( |
| 379 | <ManagedControl reason={updatesDenial}> |
| 380 | <Button size="icon-xs" variant="ghost-muted" aria-label={updatesDenial} disabled> |
| 381 | <CircleArrowUpIcon className="size-3.5" /> |
| 382 | </Button> |
| 383 | </ManagedControl> |
| 384 | ) : ( |
| 385 | <span className="text-muted-foreground text-xs">{updatesDenial}</span> |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | if (selfUpdate === "desktop-managed" && !desktopAppUpdate) { |
| 390 | return ( |
| 391 | <span className="text-muted-foreground text-xs"> |
| 392 | <T>Update the desktop app on that machine to update this server.</T> |
| 393 | </span> |
| 394 | ); |
| 395 | } |
| 396 | |
| 397 | if (refusedCrossing({ selfUpdate, targetVersion, channel }, serverVersion)) { |
| 398 | return <CrossTrackNote />; |
| 399 | } |
| 400 | |
| 401 | const manualCommand = |
| 402 | selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null; |
| 403 | const actionLabel = |
| 404 | manualCommand !== null |
| 405 | ? updatesInstall |
| 406 | ? gt("Copy update command") |
| 407 | : gt("Copy relaunch command") |
| 408 | : (label ?? gt("Update", { $context: "verb, updates the server" })); |
| 409 | const onClick = |
| 410 | manualCommand !== null |
| 411 | ? () => copyToClipboard(manualCommand, { command: manualCommand }) |
| 412 | : () => void handleUpdate(); |
| 413 | |
| 414 | if (appearance === "icon") { |
| 415 | return ( |
| 416 | <Tooltip> |
| 417 | <TooltipTrigger |
| 418 | render={ |
| 419 | <Button |
| 420 | size="icon-xs" |
| 421 | variant="ghost-muted" |
| 422 | className={className} |
| 423 | aria-label={gt("{action} for {serverLabel}", { action: actionLabel, serverLabel })} |
| 424 | disabled={manualCommand === null && !canUpdate} |
| 425 | onClick={onClick} |
| 426 | /> |
| 427 | } |
| 428 | > |
| 429 | <CircleArrowUpIcon className="size-3.5" /> |
| 430 | </TooltipTrigger> |
| 431 | <TooltipPopup side="top">{actionLabel}</TooltipPopup> |
| 432 | </Tooltip> |
| 433 | ); |
| 434 | } |
| 435 | |
| 436 | return ( |
| 437 | <Button |
| 438 | size={size} |
| 439 | variant={variant} |
| 440 | className={className} |
| 441 | disabled={manualCommand === null && !canUpdate} |
| 442 | onClick={onClick} |
| 443 | > |
| 444 | {actionLabel} |
| 445 | </Button> |
| 446 | ); |
| 447 | } |
| 448 | |
| 449 | /** Read the host descriptor's version because the host never delivers server config. */ |
| 450 | export function OutdatedServerUpdateAction({ |
| 451 | environmentId, |
| 452 | serverLabel, |
| 453 | fromVersion, |
| 454 | targetVersion, |
| 455 | label, |
| 456 | }: { |
| 457 | readonly environmentId: EnvironmentId; |
| 458 | readonly serverLabel: string; |
| 459 | readonly fromVersion: string | undefined; |
| 460 | readonly targetVersion: string; |
| 461 | readonly label?: string; |
| 462 | }) { |
| 463 | const gt = useGT(); |
| 464 | const update = useAtomCommand(updateOutdatedServer, { reportFailure: false }); |
| 465 | const handleUpdate = async () => { |
| 466 | if (pendingUpdateEnvironmentIds.has(environmentId)) return; |
| 467 | pendingUpdateEnvironmentIds.add(environmentId); |
| 468 | const result = await update({ |
| 469 | environmentId, |
| 470 | input: { targetVersion }, |
| 471 | ...(fromVersion === undefined ? {} : { fromVersion }), |
| 472 | }); |
| 473 | pendingUpdateEnvironmentIds.delete(environmentId); |
| 474 | if (result._tag === "Failure") { |
| 475 | if (isAtomCommandInterrupted(result)) return; |
| 476 | toastManager.add({ |
| 477 | type: "error", |
| 478 | title: m(msg("{serverLabel} update failed", { serverLabel })), |
| 479 | description: updateFailureMessage(squashAtomCommandFailure(result)), |
| 480 | }); |
| 481 | return; |
| 482 | } |
| 483 | toastManager.add({ |
| 484 | type: "success", |
| 485 | title: m(msg("{serverLabel} updated", { serverLabel })), |
| 486 | description: m(msg("Reconnected on t3@{version}.", { version: result.value.targetVersion })), |
| 487 | }); |
| 488 | }; |
| 489 | if (fromVersion !== undefined && crossesReleaseTrack(fromVersion, targetVersion)) { |
| 490 | return <CrossTrackNote />; |
| 491 | } |
| 492 | return ( |
| 493 | <Button size="xs" variant="outline" onClick={() => void handleUpdate()}> |
| 494 | {label ?? gt("Update", { $context: "verb, updates the server" })} |
| 495 | </Button> |
| 496 | ); |
| 497 | } |