The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useAuth } from "@clerk/react"; |
| 2 | import { useAtomValue } from "@effect/atom-react"; |
| 3 | import type { |
| 4 | AgentSessionProjectCandidate, |
| 5 | EnvironmentId, |
| 6 | ProjectId, |
| 7 | ProviderInstanceId, |
| 8 | ScopedProjectRef, |
| 9 | ServerConfig, |
| 10 | ServerProvider, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 13 | import { resolveProviderInstanceDisplayName as agentName } from "@t3tools/client-runtime/state/provider-instance-display"; |
| 14 | import { |
| 15 | isAtomCommandInterrupted, |
| 16 | squashAtomCommandFailure, |
| 17 | } from "@t3tools/client-runtime/state/runtime"; |
| 18 | import { |
| 19 | AgentSessionSource, |
| 20 | AuthProvidersManageScope, |
| 21 | AuthRelayReadScope, |
| 22 | AuthRelayWriteScope, |
| 23 | AuthTerminalOperateScope, |
| 24 | CommandId, |
| 25 | AuthOrchestrationOperateScope, |
| 26 | isManagedDriverAllowed, |
| 27 | ProviderDriverKind, |
| 28 | ThreadId, |
| 29 | } from "@t3tools/contracts"; |
| 30 | import { Link, useBlocker } from "@tanstack/react-router"; |
| 31 | import * as Schema from "effect/Schema"; |
| 32 | import { |
| 33 | CheckIcon, |
| 34 | ChevronDownIcon, |
| 35 | ChevronRightIcon, |
| 36 | PlusIcon, |
| 37 | SmartphoneIcon, |
| 38 | TerminalIcon, |
| 39 | } from "lucide-react"; |
| 40 | import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react"; |
| 41 | import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react"; |
| 42 | |
| 43 | import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts"; |
| 44 | import { MOBILE_APP_URL } from "../../branding"; |
| 45 | import { isElectron } from "../../env"; |
| 46 | import { useLocalStorage } from "../../hooks/useLocalStorage"; |
| 47 | import { usePersistEnvironmentProviderInstanceMutation } from "../../hooks/useSettings"; |
| 48 | import { useCloudLinkState } from "../../cloud/cloudLinkState"; |
| 49 | import { hasCloudPublicConfig } from "../../cloud/publicConfig"; |
| 50 | import { PRIVACY_POLICY_URL } from "../../legalLinks"; |
| 51 | import { workspaceAreaProps } from "../../lib/workspaceFocus"; |
| 52 | import { retryClerkLoad, useClerkLoadFailed } from "../clerk/clerkLoadFailure"; |
| 53 | import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; |
| 54 | import { completeOnboarding } from "../../onboarding/firstRun"; |
| 55 | import { |
| 56 | groupOnboardingProjects, |
| 57 | partitionOnboardingProjects, |
| 58 | onboardingProjectKey, |
| 59 | resolveOnboardingLandingProject, |
| 60 | isNewOnboardingProject, |
| 61 | resolveOnboardingProjectId, |
| 62 | type OnboardingProjectGroup, |
| 63 | splitOnboardingProjectPath, |
| 64 | } from "../../onboarding/projectImport.logic"; |
| 65 | import { |
| 66 | resolveOnboardingProviderInstallCommand, |
| 67 | resolveOnboardingProviderLoginCommand, |
| 68 | } from "../../onboarding/providerReadiness.logic"; |
| 69 | import { |
| 70 | cliTerminalStep, |
| 71 | codexCardProvider, |
| 72 | codexNeedsSetup, |
| 73 | groupWelcomeAgents, |
| 74 | isBrokenVersion, |
| 75 | turnedOnInstance, |
| 76 | welcomeAgentState, |
| 77 | welcomeOffersPhone, |
| 78 | } from "../../onboarding/welcomePage.logic"; |
| 79 | import { |
| 80 | StoredWelcomeImportSelection, |
| 81 | type WelcomeImportSelection, |
| 82 | welcomeImportSelectionKey, |
| 83 | } from "../../onboarding/welcomeState"; |
| 84 | import { newProjectId, randomUUID } from "../../lib/utils"; |
| 85 | import { agentSessionImport } from "../../state/agentSessions"; |
| 86 | import { readProjects, useProjects, waitForProject } from "../../state/entities"; |
| 87 | import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments"; |
| 88 | import { managedTelemetryOffMessage, useManagedPolicy } from "../../state/managedPolicy"; |
| 89 | import { useProjectScans } from "../../onboarding/useProjectScans"; |
| 90 | import { projectEnvironment } from "../../state/projects"; |
| 91 | import { serverEnvironment } from "../../state/server"; |
| 92 | import { |
| 93 | readEnvironmentScope, |
| 94 | useEnvironmentScope, |
| 95 | useEnvironmentsWithScope, |
| 96 | } from "../../state/session"; |
| 97 | import { terminalEnvironment } from "../../state/terminal"; |
| 98 | import { useThreadRunningTerminalIds } from "../../state/terminalSessions"; |
| 99 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 100 | import { getProviderSummary } from "../settings/providerStatus"; |
| 101 | import { AddProviderInstanceDialog } from "../settings/AddProviderInstanceDialog"; |
| 102 | import { useDesktopCliCommand } from "../settings/CliCommandSettingsRow"; |
| 103 | import { CodexSetupSection } from "../settings/CodexSetupSection"; |
| 104 | import { readCodexSetupMode } from "../settings/CodexSetupSection.logic"; |
| 105 | import { TerminalViewport } from "../ThreadTerminalDrawer"; |
| 106 | import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; |
| 107 | import { ACPRegistryIcon } from "../Icons"; |
| 108 | import { Button } from "../ui/button"; |
| 109 | import { Checkbox } from "../ui/checkbox"; |
| 110 | import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; |
| 111 | import { QRCodeSvg } from "../ui/qr-code"; |
| 112 | import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; |
| 113 | import { ScrollArea } from "../ui/scroll-area"; |
| 114 | import { SidebarInset } from "../ui/sidebar"; |
| 115 | import { toastManager } from "../ui/toast"; |
| 116 | import { WorkspacePageHeader } from "../WorkspacePageHeader"; |
| 117 | import { cn } from "../../lib/utils"; |
| 118 | import { formatRelativeTime } from "../../timestampFormat"; |
| 119 | |
| 120 | const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup"); |
| 121 | const SCAN_LIMIT_MESSAGE = msg( |
| 122 | "Scan limit reached. Some projects or conversations may be missing.", |
| 123 | ); |
| 124 | |
| 125 | /** |
| 126 | * First-run page for one computer: its agents, the projects found in agent history, and the |
| 127 | * phone app. Every part is optional except one ready agent to start chatting. |
| 128 | */ |
| 129 | export function WelcomePage({ |
| 130 | environmentId, |
| 131 | onDone, |
| 132 | }: { |
| 133 | readonly environmentId: EnvironmentId; |
| 134 | readonly onDone: (projectRef?: ScopedProjectRef) => void | Promise<void>; |
| 135 | }) { |
| 136 | const { environments } = useEnvironments(); |
| 137 | const gt = useGT(); |
| 138 | const label = |
| 139 | environments.find((environment) => environment.environmentId === environmentId)?.label ?? |
| 140 | gt("this computer"); |
| 141 | const agentReady = useWelcomeAgents(environmentId).readyCount > 0; |
| 142 | // The phone and `t3` on PATH belong to the primary computer, so only it offers them. |
| 143 | const isPrimary = usePrimaryEnvironmentId() === environmentId; |
| 144 | // The same access Settings → Sharing & access checks. |
| 145 | const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope); |
| 146 | const canWriteRelay = useEnvironmentScope(environmentId, AuthRelayWriteScope); |
| 147 | const showPhone = welcomeOffersPhone({ |
| 148 | isPrimary, |
| 149 | cloud: hasCloudPublicConfig(), |
| 150 | canShare: canReadRelay && canWriteRelay, |
| 151 | policy: useManagedPolicy(environmentId), |
| 152 | }); |
| 153 | const scans = useProjectScans([environmentId]); |
| 154 | const [storedSelection, storeSelection] = useLocalStorage( |
| 155 | welcomeImportSelectionKey(environmentId), |
| 156 | null, |
| 157 | StoredWelcomeImportSelection, |
| 158 | ); |
| 159 | // The page keeps its own copy, so a failed write (a full quota) cannot undo a choice. |
| 160 | const [importSelection, setImportSelectionState] = useState(storedSelection); |
| 161 | const setImportSelection = (next: WelcomeImportSelection | null) => { |
| 162 | setImportSelectionState(next); |
| 163 | storeSelection(next); |
| 164 | }; |
| 165 | const [isImporting, setIsImporting] = useState(false); |
| 166 | // True from Start until the landing; leaving earlier would drop the import or the landing. |
| 167 | const holdPageRef = useRef(false); |
| 168 | useBlocker({ |
| 169 | shouldBlockFn: () => { |
| 170 | if (!holdPageRef.current) return false; |
| 171 | toastManager.add({ |
| 172 | id: "welcome-finishing", |
| 173 | type: "info", |
| 174 | title: gt("Finishing setup"), |
| 175 | description: gt("One moment."), |
| 176 | }); |
| 177 | return true; |
| 178 | }, |
| 179 | // Electron cancels a quit silently when unload is blocked. A later visit resumes the import. |
| 180 | enableBeforeUnload: false, |
| 181 | }); |
| 182 | const finishingPromiseRef = useRef<Promise<boolean> | null>(null); |
| 183 | // Starting before the project list loads keeps saved picks, such as an import a quit cut short. |
| 184 | const keepChoicesRef = useRef(false); |
| 185 | const completionErrorToastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null); |
| 186 | const finish = ( |
| 187 | projectRef?: ScopedProjectRef, |
| 188 | importWarning?: string, |
| 189 | importedThreadCount = 0, |
| 190 | ) => { |
| 191 | if (finishingPromiseRef.current !== null) return finishingPromiseRef.current; |
| 192 | if (completionErrorToastIdRef.current !== null) { |
| 193 | toastManager.close(completionErrorToastIdRef.current); |
| 194 | completionErrorToastIdRef.current = null; |
| 195 | } |
| 196 | |
| 197 | holdPageRef.current = true; |
| 198 | const completion = completeOnboarding() |
| 199 | .then(async () => { |
| 200 | if (completionErrorToastIdRef.current !== null) { |
| 201 | toastManager.close(completionErrorToastIdRef.current); |
| 202 | completionErrorToastIdRef.current = null; |
| 203 | } |
| 204 | // Release before onDone so its own navigation is not blocked. |
| 205 | holdPageRef.current = false; |
| 206 | await onDone(projectRef); |
| 207 | if (!keepChoicesRef.current) setImportSelection(null); |
| 208 | if (importWarning) { |
| 209 | toastManager.add({ |
| 210 | type: "warning", |
| 211 | title: gt("Some history was not imported"), |
| 212 | description: importWarning, |
| 213 | timeout: 0, |
| 214 | }); |
| 215 | } else if (importedThreadCount > 0) { |
| 216 | toastManager.add({ |
| 217 | type: "success", |
| 218 | title: gt( |
| 219 | "{count, plural, one {Imported {count} thread} other {Imported {count} threads}}", |
| 220 | { count: importedThreadCount }, |
| 221 | ), |
| 222 | }); |
| 223 | } |
| 224 | return true; |
| 225 | }) |
| 226 | .catch(() => { |
| 227 | holdPageRef.current = false; |
| 228 | const errorToast = { |
| 229 | type: "error", |
| 230 | title: gt("Could not finish setup"), |
| 231 | description: gt("Your settings could not be saved. Try again."), |
| 232 | } as const; |
| 233 | if (completionErrorToastIdRef.current === null) { |
| 234 | completionErrorToastIdRef.current = toastManager.add(errorToast); |
| 235 | } else { |
| 236 | toastManager.update(completionErrorToastIdRef.current, errorToast); |
| 237 | } |
| 238 | return false; |
| 239 | }) |
| 240 | .finally(() => { |
| 241 | if (finishingPromiseRef.current === completion) { |
| 242 | finishingPromiseRef.current = null; |
| 243 | } |
| 244 | }); |
| 245 | finishingPromiseRef.current = completion; |
| 246 | return completion; |
| 247 | }; |
| 248 | const projectImport = useProjectImport({ |
| 249 | scans, |
| 250 | importSelection, |
| 251 | onImportSelectionChange: setImportSelection, |
| 252 | isImporting, |
| 253 | setIsImporting, |
| 254 | holdPageRef, |
| 255 | onDone: finish, |
| 256 | }); |
| 257 | // Without import permission, starting simply skips the projects. |
| 258 | const selected = projectImport.canWrite ? projectImport.selected : []; |
| 259 | const newCount = selected.filter(projectImport.isNew).length; |
| 260 | const start = () => { |
| 261 | keepChoicesRef.current = scans.some((scan) => scan.data === null); |
| 262 | if (selected.length === 0) { |
| 263 | projectImport.finishAfterImport(); |
| 264 | return; |
| 265 | } |
| 266 | // Stored now, so after a restart mid-import these stay checked even once they exist. |
| 267 | projectImport.setSelectedKeys(new Set(selected.map((candidate) => candidate.key))); |
| 268 | void projectImport.runImport(selected); |
| 269 | }; |
| 270 | |
| 271 | return ( |
| 272 | <SidebarInset |
| 273 | {...workspaceAreaProps("home", 1, gt("Welcome"))} |
| 274 | role="main" |
| 275 | className="h-dvh min-h-0 overflow-hidden overscroll-y-none" |
| 276 | > |
| 277 | <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background"> |
| 278 | {/* The desktop window only moves where CSS opts in, so keep a titlebar strip. */} |
| 279 | {isElectron ? <WorkspacePageHeader electron /> : null} |
| 280 | <div className="min-h-0 flex-1 overflow-y-auto scrollbar-gutter-both"> |
| 281 | <div className="mx-auto flex min-h-full w-full max-w-3xl flex-col px-6 pt-12 pb-8 sm:pt-20"> |
| 282 | <h1 className="text-2xl font-semibold tracking-tight text-foreground"> |
| 283 | <T>Welcome to T3 Code</T> |
| 284 | </h1> |
| 285 | <p className="mt-1.5 text-sm text-muted-foreground"> |
| 286 | <T> |
| 287 | Setting up{" "} |
| 288 | <span className="text-foreground"> |
| 289 | <Var>{label}</Var> |
| 290 | </span> |
| 291 | . |
| 292 | </T> |
| 293 | </p> |
| 294 | <div className="mt-10 border-t border-border/60"> |
| 295 | <AgentsSection |
| 296 | environmentId={environmentId} |
| 297 | label={label} |
| 298 | isPrimary={isPrimary} |
| 299 | onImportSourceEnabled={() => scans[0]?.refresh()} |
| 300 | /> |
| 301 | <ProjectsSection |
| 302 | scan={scans[0]} |
| 303 | projectImport={projectImport} |
| 304 | isImporting={isImporting} |
| 305 | /> |
| 306 | {showPhone ? <PhoneSection environmentId={environmentId} /> : null} |
| 307 | </div> |
| 308 | <div className="mt-6 flex flex-wrap items-center justify-between gap-3"> |
| 309 | {agentReady ? ( |
| 310 | <span /> |
| 311 | ) : ( |
| 312 | <Button variant="ghost-muted" disabled={isImporting} onClick={start}> |
| 313 | <T>Start without an agent</T> |
| 314 | </Button> |
| 315 | )} |
| 316 | <div className="flex items-center gap-3"> |
| 317 | {agentReady ? null : ( |
| 318 | <span className="text-xs text-muted-foreground"> |
| 319 | <T>Set up one agent to start.</T> |
| 320 | </span> |
| 321 | )} |
| 322 | <Button disabled={!agentReady || isImporting} onClick={start}> |
| 323 | {isImporting |
| 324 | ? selected.length > 0 |
| 325 | ? gt("Importing…") |
| 326 | : gt("Starting…") |
| 327 | : newCount > 0 |
| 328 | ? gt( |
| 329 | "{count, plural, one {Import {count} project and start} other {Import {count} projects and start}}", |
| 330 | { count: newCount }, |
| 331 | ) |
| 332 | : selected.length > 0 |
| 333 | ? gt("Import threads and start") |
| 334 | : gt("Start", { $context: "verb, finishes setup" })} |
| 335 | </Button> |
| 336 | </div> |
| 337 | </div> |
| 338 | <TelemetryNotice environmentId={environmentId} /> |
| 339 | </div> |
| 340 | </div> |
| 341 | </div> |
| 342 | </SidebarInset> |
| 343 | ); |
| 344 | } |
| 345 | |
| 346 | function TelemetryNotice({ environmentId }: { readonly environmentId: EnvironmentId }) { |
| 347 | const messages = useMessages(); |
| 348 | const telemetryOff = managedTelemetryOffMessage(useManagedPolicy(environmentId), messages); |
| 349 | return ( |
| 350 | <p className="mt-auto pt-12 text-2xs leading-relaxed text-muted-foreground/70"> |
| 351 | {telemetryOff === undefined ? ( |
| 352 | <T> |
| 353 | T3 Code collects anonymous usage data to improve the app. To opt out, see the{" "} |
| 354 | <a |
| 355 | className="underline decoration-current/40 underline-offset-2 hover:text-muted-foreground" |
| 356 | href={PRIVACY_POLICY_URL} |
| 357 | target="_blank" |
| 358 | rel="noreferrer noopener" |
| 359 | > |
| 360 | privacy policy |
| 361 | </a> |
| 362 | . |
| 363 | </T> |
| 364 | ) : ( |
| 365 | <> |
| 366 | {telemetryOff}{" "} |
| 367 | <T> |
| 368 | See the{" "} |
| 369 | <a |
| 370 | className="underline decoration-current/40 underline-offset-2 hover:text-muted-foreground" |
| 371 | href={PRIVACY_POLICY_URL} |
| 372 | target="_blank" |
| 373 | rel="noreferrer noopener" |
| 374 | > |
| 375 | privacy policy |
| 376 | </a> |
| 377 | . |
| 378 | </T> |
| 379 | </> |
| 380 | )} |
| 381 | </p> |
| 382 | ); |
| 383 | } |
| 384 | |
| 385 | // Each part of the page is one band: its label on the left, its rows on the right. |
| 386 | function WelcomeSection({ |
| 387 | title, |
| 388 | children, |
| 389 | }: { |
| 390 | readonly title: string; |
| 391 | readonly children: ReactNode; |
| 392 | }) { |
| 393 | return ( |
| 394 | <section className="grid gap-x-10 border-b border-border/60 py-4 sm:grid-cols-[6rem_minmax(0,1fr)]"> |
| 395 | <h2 className="text-sm leading-10 text-muted-foreground">{title}</h2> |
| 396 | <div className="min-w-0">{children}</div> |
| 397 | </section> |
| 398 | ); |
| 399 | } |
| 400 | |
| 401 | // Rows share one icon column, so names, checkboxes, and steps line up down the page. |
| 402 | function RowIcon({ children }: { readonly children: ReactNode }) { |
| 403 | return ( |
| 404 | <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground"> |
| 405 | {children} |
| 406 | </span> |
| 407 | ); |
| 408 | } |
| 409 | |
| 410 | const INSTALLABLE_DRIVERS = ["codex", "claudeAgent"] as const; |
| 411 | type OnboardingAgentDriver = (typeof INSTALLABLE_DRIVERS)[number]; |
| 412 | const isInstallableDriver = (driver: string): driver is OnboardingAgentDriver => |
| 413 | (INSTALLABLE_DRIVERS as ReadonlyArray<string>).includes(driver); |
| 414 | |
| 415 | interface AgentTerminalSession { |
| 416 | readonly environmentId: EnvironmentId; |
| 417 | readonly driver: OnboardingAgentDriver; |
| 418 | readonly providerInstanceId: ServerProvider["instanceId"]; |
| 419 | readonly cwd: string; |
| 420 | readonly command: string; |
| 421 | readonly keybindings: ServerConfig["keybindings"]; |
| 422 | } |
| 423 | |
| 424 | // Shared by the page (to enable Start) and the agents section, so both agree on what is ready. |
| 425 | function useWelcomeAgents(environmentId: EnvironmentId) { |
| 426 | const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId)); |
| 427 | const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); |
| 428 | const managedPolicy = serverConfig?.managedPolicy; |
| 429 | return { |
| 430 | providers, |
| 431 | serverConfig, |
| 432 | ...groupWelcomeAgents(providers, serverConfig?.settings, agentName, (provider) => |
| 433 | isManagedDriverAllowed(managedPolicy, provider.driver), |
| 434 | ), |
| 435 | }; |
| 436 | } |
| 437 | |
| 438 | const isImportSource = Schema.is(AgentSessionSource); |
| 439 | |
| 440 | // The setup card opens below a long list, so bring it into view once. |
| 441 | const revealOnMount = (node: HTMLElement | null) => node?.scrollIntoView({ block: "nearest" }); |
| 442 | |
| 443 | const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); |
| 444 | |
| 445 | function AgentsSection({ |
| 446 | environmentId, |
| 447 | label, |
| 448 | isPrimary, |
| 449 | onImportSourceEnabled, |
| 450 | }: { |
| 451 | readonly environmentId: EnvironmentId; |
| 452 | readonly label: string; |
| 453 | readonly isPrimary: boolean; |
| 454 | // The project scan only reads agents that are on, so turning one on can find more history. |
| 455 | readonly onImportSourceEnabled: () => void; |
| 456 | }) { |
| 457 | const { providers, serverConfig, checking, found, available } = useWelcomeAgents(environmentId); |
| 458 | const gt = useGT(); |
| 459 | const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { |
| 460 | reportFailure: false, |
| 461 | }); |
| 462 | const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId); |
| 463 | const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); |
| 464 | const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); |
| 465 | const [terminalSession, setTerminalSession] = useState<AgentTerminalSession | null>(null); |
| 466 | const [moreOpen, setMoreOpen] = useState<boolean | null>(null); |
| 467 | const [addingProvider, setAddingProvider] = useState(false); |
| 468 | const [codexSetupId, setCodexSetupId] = useState<ProviderInstanceId | null>(null); |
| 469 | const [cliTerminalFor, setCliTerminalFor] = useState<ProviderInstanceId | null>(null); |
| 470 | |
| 471 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the environment to refresh its provider list when the environment changes |
| 472 | useEffect(() => { |
| 473 | void refreshProviders({ environmentId, input: {} }); |
| 474 | }, [environmentId, refreshProviders]); |
| 475 | |
| 476 | // Opened once the finished checks find nothing, since adding an agent is then the task. A first |
| 477 | // status can be wrong, so this waits for the checks, and a later check never closes it. |
| 478 | if (moreOpen === null && !checking && found.length === 0) setMoreOpen(true); |
| 479 | const showMore = moreOpen ?? false; |
| 480 | const acpAllowed = isManagedDriverAllowed(serverConfig?.managedPolicy, ACP_REGISTRY_DRIVER_KIND); |
| 481 | const stateOf = (provider: ServerProvider) => welcomeAgentState(provider, serverConfig?.settings); |
| 482 | const needsInstallOrSignIn = (provider: ServerProvider) => { |
| 483 | const state = stateOf(provider); |
| 484 | return ( |
| 485 | isInstallableDriver(provider.driver) && |
| 486 | !isBrokenVersion(provider) && |
| 487 | (state === "install" || state === "signIn") |
| 488 | ); |
| 489 | }; |
| 490 | // Codex's card also offers ChatGPT sign-in, which still works when the CLI check failed. |
| 491 | // Codex setup stays mounted by instance while its status changes, so a sign-in that starts |
| 492 | // after an install is not lost when the agent moves between groups or briefly leaves the list. |
| 493 | const [lastCodex, setLastCodex] = useState<ServerProvider | null>(null); |
| 494 | const listedCodex = |
| 495 | codexSetupId === null |
| 496 | ? undefined |
| 497 | : providers?.find((provider) => provider.instanceId === codexSetupId); |
| 498 | if (listedCodex !== undefined && listedCodex !== lastCodex) setLastCodex(listedCodex); |
| 499 | const codexSetupProvider = codexCardProvider({ |
| 500 | providers, |
| 501 | instanceId: codexSetupId, |
| 502 | last: lastCodex, |
| 503 | settings: serverConfig?.settings, |
| 504 | }); |
| 505 | // Once the card closes, a later status change does not reopen it and move the page. |
| 506 | if (listedCodex !== undefined && codexSetupProvider === null) setCodexSetupId(null); |
| 507 | |
| 508 | const openTerminal = (provider: ServerProvider) => { |
| 509 | if ( |
| 510 | !isInstallableDriver(provider.driver) || |
| 511 | serverConfig === null || |
| 512 | !readEnvironmentScope(environmentId, AuthTerminalOperateScope) |
| 513 | ) |
| 514 | return; |
| 515 | setTerminalSession({ |
| 516 | environmentId, |
| 517 | driver: provider.driver, |
| 518 | providerInstanceId: provider.instanceId, |
| 519 | cwd: serverConfig.cwd, |
| 520 | command: provider.installed |
| 521 | ? resolveOnboardingProviderLoginCommand( |
| 522 | provider, |
| 523 | serverConfig.settings, |
| 524 | serverConfig.environment.platform.os, |
| 525 | ) |
| 526 | : resolveOnboardingProviderInstallCommand( |
| 527 | provider.driver, |
| 528 | serverConfig.environment.platform.os, |
| 529 | ), |
| 530 | keybindings: serverConfig.keybindings, |
| 531 | }); |
| 532 | }; |
| 533 | |
| 534 | // "Use existing CLI" opens the CLI's terminal once Codex has checked the CLI. |
| 535 | const cliProvider = |
| 536 | cliTerminalFor === null |
| 537 | ? undefined |
| 538 | : providers?.find((provider) => provider.instanceId === cliTerminalFor); |
| 539 | const cliStep = |
| 540 | cliProvider === undefined ? "done" : cliTerminalStep(cliProvider, serverConfig?.settings); |
| 541 | if (cliProvider !== undefined && cliStep !== "wait") { |
| 542 | setCliTerminalFor(null); |
| 543 | if (cliStep === "open") openTerminal(cliProvider); |
| 544 | } |
| 545 | |
| 546 | const turnOn = async (provider: ServerProvider) => { |
| 547 | if (serverConfig === null) return; |
| 548 | const instance = serverConfig.settings.providerInstances[provider.instanceId] ?? { |
| 549 | driver: provider.driver, |
| 550 | }; |
| 551 | const result = await persistProviderInstance({ |
| 552 | operation: "upsert", |
| 553 | instanceId: provider.instanceId, |
| 554 | instance: turnedOnInstance(instance), |
| 555 | }); |
| 556 | if (result._tag === "Failure") { |
| 557 | if (!isAtomCommandInterrupted(result)) { |
| 558 | const cause = squashAtomCommandFailure(result); |
| 559 | toastManager.add({ |
| 560 | type: "error", |
| 561 | title: gt("Could not turn on {agent}", { agent: agentName(provider) }), |
| 562 | ...(cause instanceof Error ? { description: cause.message } : {}), |
| 563 | }); |
| 564 | } |
| 565 | return; |
| 566 | } |
| 567 | void refreshProviders({ environmentId, input: { instanceId: provider.instanceId } }); |
| 568 | if (isImportSource(provider.driver)) onImportSourceEnabled(); |
| 569 | }; |
| 570 | |
| 571 | // One action per agent, the same in the list and in the grid. |
| 572 | const actionFor = (provider: ServerProvider) => { |
| 573 | const state = stateOf(provider); |
| 574 | const name = agentName(provider); |
| 575 | const settingsAction = (actionLabel: string) => ( |
| 576 | <Button |
| 577 | size="xs" |
| 578 | variant="outline" |
| 579 | aria-label={gt("{action}: {agent}", { action: actionLabel, agent: name })} |
| 580 | render={ |
| 581 | <Link |
| 582 | to="/settings/providers" |
| 583 | search={{ environmentId, instanceId: provider.instanceId }} |
| 584 | /> |
| 585 | } |
| 586 | > |
| 587 | {actionLabel} |
| 588 | </Button> |
| 589 | ); |
| 590 | if (state === "disabled") { |
| 591 | return ( |
| 592 | <Button |
| 593 | size="xs" |
| 594 | variant="outline" |
| 595 | aria-label={gt("Turn on: {agent}", { agent: name })} |
| 596 | disabled={!canManageProviders || serverConfig === null} |
| 597 | onClick={() => void turnOn(provider)} |
| 598 | > |
| 599 | <T>Turn on</T> |
| 600 | </Button> |
| 601 | ); |
| 602 | } |
| 603 | // Settings updates a broken CLI the way it was installed, including a custom binary path. |
| 604 | if (isBrokenVersion(provider)) |
| 605 | return settingsAction(gt("Update", { $context: "verb, updates an agent CLI" })); |
| 606 | if (serverConfig !== null && codexNeedsSetup(provider, serverConfig.settings)) { |
| 607 | const open = codexSetupId === provider.instanceId; |
| 608 | return ( |
| 609 | <Button |
| 610 | size="xs" |
| 611 | variant="outline" |
| 612 | aria-label={gt("Set up: {agent}", { agent: name })} |
| 613 | aria-expanded={open} |
| 614 | onClick={() => setCodexSetupId(open ? null : provider.instanceId)} |
| 615 | > |
| 616 | <T>Set up</T> |
| 617 | </Button> |
| 618 | ); |
| 619 | } |
| 620 | if (needsInstallOrSignIn(provider)) { |
| 621 | return ( |
| 622 | <TerminalAction |
| 623 | name={name} |
| 624 | signIn={state === "signIn"} |
| 625 | disabled={ |
| 626 | terminalSession?.providerInstanceId === provider.instanceId || |
| 627 | serverConfig === null || |
| 628 | !canOperateTerminal |
| 629 | } |
| 630 | onClick={() => openTerminal(provider)} |
| 631 | /> |
| 632 | ); |
| 633 | } |
| 634 | return settingsAction( |
| 635 | state === "signIn" ? gt("Sign in") : state === "attention" ? gt("Details") : gt("Set up"), |
| 636 | ); |
| 637 | }; |
| 638 | |
| 639 | const notes = [ |
| 640 | !canOperateTerminal && |
| 641 | [...found, ...available].some( |
| 642 | (provider) => |
| 643 | needsInstallOrSignIn(provider) || codexNeedsSetup(provider, serverConfig?.settings), |
| 644 | ) |
| 645 | ? gt("This connection cannot control terminals.") |
| 646 | : null, |
| 647 | !canManageProviders && |
| 648 | (acpAllowed || |
| 649 | [...found, ...available].some( |
| 650 | (provider) => |
| 651 | stateOf(provider) === "disabled" || codexNeedsSetup(provider, serverConfig?.settings), |
| 652 | )) |
| 653 | ? gt("This connection cannot manage agents.") |
| 654 | : null, |
| 655 | ].filter((note) => note !== null); |
| 656 | |
| 657 | return ( |
| 658 | <WelcomeSection title={gt("Agents")}> |
| 659 | {found.map((provider) => ( |
| 660 | <AgentRow |
| 661 | key={provider.instanceId} |
| 662 | provider={provider} |
| 663 | state={stateOf(provider)} |
| 664 | action={actionFor(provider)} |
| 665 | /> |
| 666 | ))} |
| 667 | {checking && found.length === 0 ? ( |
| 668 | <p className="text-sm leading-10 text-muted-foreground"> |
| 669 | <T> |
| 670 | Checking <Var>{label}</Var>… |
| 671 | </T> |
| 672 | </p> |
| 673 | ) : null} |
| 674 | {notes.map((note) => ( |
| 675 | <p key={note} className="pl-8 text-xs text-muted-foreground"> |
| 676 | {note} |
| 677 | </p> |
| 678 | ))} |
| 679 | <Collapsible open={showMore} onOpenChange={setMoreOpen}> |
| 680 | <CollapsibleTrigger className="group flex min-h-10 w-full items-center gap-3 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"> |
| 681 | <RowIcon> |
| 682 | <PlusIcon className="size-4" /> |
| 683 | </RowIcon> |
| 684 | <span |
| 685 | className={cn( |
| 686 | "text-sm group-hover:text-foreground", |
| 687 | found.length > 0 ? "text-muted-foreground" : "text-foreground", |
| 688 | )} |
| 689 | > |
| 690 | {found.length > 0 ? gt("Add more agents") : gt("Set up an agent")} |
| 691 | </span> |
| 692 | {showMore ? null : <AgentLogoStack providers={available} acp={acpAllowed} />} |
| 693 | <ChevronDownIcon className="ml-auto size-4 text-muted-foreground group-data-panel-open:rotate-180" /> |
| 694 | </CollapsibleTrigger> |
| 695 | <CollapsiblePanel> |
| 696 | <div className="grid grid-cols-1 gap-x-8 sm:grid-cols-2"> |
| 697 | {available.map((provider) => ( |
| 698 | <AgentRow |
| 699 | key={provider.instanceId} |
| 700 | provider={provider} |
| 701 | state={stateOf(provider)} |
| 702 | compact |
| 703 | action={actionFor(provider)} |
| 704 | /> |
| 705 | ))} |
| 706 | </div> |
| 707 | {acpAllowed ? ( |
| 708 | <div className="flex min-h-9 items-center gap-3"> |
| 709 | <RowIcon> |
| 710 | <ACPRegistryIcon className="size-4" /> |
| 711 | </RowIcon> |
| 712 | <span className="min-w-0 flex-1 text-sm text-muted-foreground"> |
| 713 | <T>More agents in the ACP Registry</T> |
| 714 | </span> |
| 715 | <Button |
| 716 | size="xs" |
| 717 | variant="outline" |
| 718 | disabled={!canManageProviders} |
| 719 | onClick={() => setAddingProvider(true)} |
| 720 | > |
| 721 | <T>Browse</T> |
| 722 | </Button> |
| 723 | </div> |
| 724 | ) : null} |
| 725 | </CollapsiblePanel> |
| 726 | </Collapsible> |
| 727 | {codexSetupProvider !== null && serverConfig !== null ? ( |
| 728 | <div key={codexSetupProvider.instanceId} ref={revealOnMount} className="mt-2"> |
| 729 | <OnboardingCodexSetup |
| 730 | environmentId={environmentId} |
| 731 | provider={codexSetupProvider} |
| 732 | serverConfig={serverConfig} |
| 733 | onUseCliChange={(useCli) => |
| 734 | setCliTerminalFor(useCli ? codexSetupProvider.instanceId : null) |
| 735 | } |
| 736 | /> |
| 737 | </div> |
| 738 | ) : null} |
| 739 | {isPrimary ? <CliPathSetup /> : null} |
| 740 | {terminalSession !== null ? ( |
| 741 | <AgentInstallTerminal |
| 742 | key={`${terminalSession.environmentId}:${terminalSession.providerInstanceId}:${terminalSession.driver}`} |
| 743 | session={terminalSession} |
| 744 | onCommandFinished={() => |
| 745 | void refreshProviders({ |
| 746 | environmentId, |
| 747 | input: { instanceId: terminalSession.providerInstanceId }, |
| 748 | }) |
| 749 | } |
| 750 | onClose={() => { |
| 751 | setTerminalSession(null); |
| 752 | void refreshProviders({ environmentId, input: {} }); |
| 753 | }} |
| 754 | /> |
| 755 | ) : null} |
| 756 | {addingProvider ? ( |
| 757 | <AddProviderInstanceDialog |
| 758 | open |
| 759 | environmentId={environmentId} |
| 760 | environmentLabel={label} |
| 761 | showMoreProviders |
| 762 | onOpenChange={setAddingProvider} |
| 763 | onCreated={(_instanceId, driver) => { |
| 764 | void refreshProviders({ environmentId, input: {} }); |
| 765 | // A new Claude Code, Codex, or Pi instance can bring more history to import. |
| 766 | if (isImportSource(driver)) onImportSourceEnabled(); |
| 767 | }} |
| 768 | /> |
| 769 | ) : null} |
| 770 | </WelcomeSection> |
| 771 | ); |
| 772 | } |
| 773 | |
| 774 | // A quiet preview of what the fold holds; the names are inside it. |
| 775 | function AgentLogoStack({ |
| 776 | providers, |
| 777 | acp, |
| 778 | }: { |
| 779 | readonly providers: ReadonlyArray<ServerProvider>; |
| 780 | readonly acp: boolean; |
| 781 | }) { |
| 782 | if (providers.length === 0 && !acp) return null; |
| 783 | return ( |
| 784 | <span className="flex items-center gap-2 opacity-60 grayscale" aria-hidden> |
| 785 | {providers.slice(0, 6).map((provider) => ( |
| 786 | <ProviderInstanceIcon |
| 787 | key={provider.instanceId} |
| 788 | driverKind={provider.driver} |
| 789 | displayName={agentName(provider)} |
| 790 | iconClassName="size-3.5" |
| 791 | /> |
| 792 | ))} |
| 793 | {acp ? <ACPRegistryIcon className="size-3.5" /> : null} |
| 794 | </span> |
| 795 | ); |
| 796 | } |
| 797 | |
| 798 | function ProjectsSection({ |
| 799 | scan, |
| 800 | projectImport, |
| 801 | isImporting, |
| 802 | }: { |
| 803 | readonly scan: ReturnType<typeof useProjectScans>[number] | undefined; |
| 804 | readonly projectImport: ReturnType<typeof useProjectImport>; |
| 805 | readonly isImporting: boolean; |
| 806 | }) { |
| 807 | const gt = useGT(); |
| 808 | const m = useMessages(); |
| 809 | const importSourcesLabel = useImportSourcesLabel(); |
| 810 | const [reviewing, setReviewing] = useState(false); |
| 811 | const { |
| 812 | canWrite, |
| 813 | candidates, |
| 814 | isNew, |
| 815 | recent, |
| 816 | selected, |
| 817 | selectedKeys, |
| 818 | setSelectedKeys, |
| 819 | visibleImportError, |
| 820 | } = projectImport; |
| 821 | if (scan === undefined) return null; |
| 822 | if (scan.isPending && candidates.length === 0) { |
| 823 | return ( |
| 824 | <WelcomeSection title={gt("Projects")}> |
| 825 | <p className="text-sm leading-10 text-muted-foreground"> |
| 826 | <T> |
| 827 | Looking for projects in your <Var>{importSourcesLabel}</Var> history… |
| 828 | </T> |
| 829 | </p> |
| 830 | </WelcomeSection> |
| 831 | ); |
| 832 | } |
| 833 | const retry = ( |
| 834 | <Button variant="ghost" size="sm" onClick={scan.refresh}> |
| 835 | <T>Retry</T> |
| 836 | </Button> |
| 837 | ); |
| 838 | if (scan.error !== null && candidates.length === 0) { |
| 839 | return ( |
| 840 | <WelcomeSection title={gt("Projects")}> |
| 841 | <div |
| 842 | role="alert" |
| 843 | className="flex min-h-10 items-center justify-between gap-3 text-sm text-muted-foreground" |
| 844 | > |
| 845 | <span>{gt("Could not check projects. {error}", { error: scan.error })}</span> |
| 846 | {retry} |
| 847 | </div> |
| 848 | </WelcomeSection> |
| 849 | ); |
| 850 | } |
| 851 | if (candidates.length === 0) { |
| 852 | return scan.data?.truncated ? ( |
| 853 | <WelcomeSection title={gt("Projects")}> |
| 854 | <p className="text-xs leading-10 text-muted-foreground" role="status"> |
| 855 | {m(SCAN_LIMIT_MESSAGE)} |
| 856 | </p> |
| 857 | </WelcomeSection> |
| 858 | ) : null; |
| 859 | } |
| 860 | |
| 861 | const allKeys = candidates.map((candidate) => candidate.key); |
| 862 | // Checking the box picks recent new projects, else any new ones, else everything listed. |
| 863 | const fresh = candidates.filter(isNew); |
| 864 | const defaultKeys = (recent.length > 0 ? recent : fresh.length > 0 ? fresh : candidates).map( |
| 865 | (candidate) => candidate.key, |
| 866 | ); |
| 867 | const partial = |
| 868 | selected.length > 0 && |
| 869 | selected.length < candidates.length && |
| 870 | !(selected.length === defaultKeys.length && defaultKeys.every((key) => selectedKeys.has(key))); |
| 871 | return ( |
| 872 | <WelcomeSection title={gt("Projects")}> |
| 873 | <div className="flex min-h-10 items-center gap-3 py-1"> |
| 874 | <label className="flex min-w-0 flex-1 items-center gap-3"> |
| 875 | <RowIcon> |
| 876 | <Checkbox |
| 877 | checked={canWrite && selected.length > 0} |
| 878 | indeterminate={canWrite && partial} |
| 879 | disabled={isImporting || !canWrite} |
| 880 | onCheckedChange={(checked) => |
| 881 | setSelectedKeys(new Set(checked ? defaultKeys : []), { optedOut: !checked }) |
| 882 | } |
| 883 | /> |
| 884 | </RowIcon> |
| 885 | <span className="min-w-0 flex-1"> |
| 886 | <span className="block text-sm font-medium text-foreground"> |
| 887 | {canWrite && selected.length > 0 |
| 888 | ? gt( |
| 889 | "{count, plural, one {Import {count} project and their threads} other {Import {count} projects and their threads}}", |
| 890 | { count: selected.length }, |
| 891 | ) |
| 892 | : gt("Import projects and their threads")} |
| 893 | </span> |
| 894 | <span className="block text-xs text-muted-foreground"> |
| 895 | <T> |
| 896 | From your <Var>{importSourcesLabel}</Var> history |
| 897 | </T> |
| 898 | </span> |
| 899 | </span> |
| 900 | </label> |
| 901 | {canWrite ? ( |
| 902 | <Button |
| 903 | variant="ghost-muted" |
| 904 | size="xs" |
| 905 | aria-expanded={reviewing} |
| 906 | onClick={() => setReviewing((open) => !open)} |
| 907 | > |
| 908 | {reviewing |
| 909 | ? gt("Hide") |
| 910 | : gt("{count, plural, one {Review all {count}} other {Review all {count}}}", { |
| 911 | count: candidates.length, |
| 912 | })} |
| 913 | <ChevronDownIcon className={cn("size-3.5", reviewing && "rotate-180")} /> |
| 914 | </Button> |
| 915 | ) : null} |
| 916 | </div> |
| 917 | {reviewing && canWrite ? ( |
| 918 | // The negative margin lines the list's checkboxes up with the one above it. |
| 919 | <fieldset className="-mx-1.5 mt-1 min-w-0" disabled={isImporting}> |
| 920 | <div className="flex items-center justify-between gap-3 px-2 text-xs text-muted-foreground"> |
| 921 | <span role="status"> |
| 922 | {gt( |
| 923 | "{selected, plural, one {{selected} of {total} selected} other {{selected} of {total} selected}}", |
| 924 | { |
| 925 | selected: selected.length, |
| 926 | total: candidates.length, |
| 927 | }, |
| 928 | )} |
| 929 | </span> |
| 930 | <div className="flex items-center gap-1"> |
| 931 | <Button |
| 932 | variant="ghost" |
| 933 | size="xs" |
| 934 | disabled={selected.length === candidates.length} |
| 935 | onClick={() => setSelectedKeys(new Set(allKeys))} |
| 936 | > |
| 937 | <T>Select all</T> |
| 938 | </Button> |
| 939 | <Button |
| 940 | variant="ghost" |
| 941 | size="xs" |
| 942 | disabled={selected.length === 0} |
| 943 | onClick={() => setSelectedKeys(new Set())} |
| 944 | > |
| 945 | <T>Select none</T> |
| 946 | </Button> |
| 947 | </div> |
| 948 | </div> |
| 949 | <ScrollArea scrollFade className="mt-1 h-auto max-h-80"> |
| 950 | <div className="space-y-0.5 pr-3"> |
| 951 | <ImportCandidateList |
| 952 | candidates={candidates} |
| 953 | selectedKeys={selectedKeys} |
| 954 | onSelectionChange={setSelectedKeys} |
| 955 | /> |
| 956 | </div> |
| 957 | </ScrollArea> |
| 958 | </fieldset> |
| 959 | ) : null} |
| 960 | {scan.data?.truncated ? ( |
| 961 | <p className="pl-8 text-xs text-muted-foreground" role="status"> |
| 962 | {m(SCAN_LIMIT_MESSAGE)} |
| 963 | </p> |
| 964 | ) : null} |
| 965 | {scan.error !== null ? ( |
| 966 | <div |
| 967 | role="alert" |
| 968 | className="flex items-center justify-between gap-3 pl-8 text-sm text-muted-foreground" |
| 969 | > |
| 970 | <span>{gt("Could not check projects again. {error}", { error: scan.error })}</span> |
| 971 | {retry} |
| 972 | </div> |
| 973 | ) : null} |
| 974 | {visibleImportError ? ( |
| 975 | <p className="pt-1 pl-8 text-sm text-destructive">{m(visibleImportError)}</p> |
| 976 | ) : null} |
| 977 | </WelcomeSection> |
| 978 | ); |
| 979 | } |
| 980 | |
| 981 | function PhoneSection({ environmentId }: { readonly environmentId: EnvironmentId }) { |
| 982 | const gt = useGT(); |
| 983 | const [open, setOpen] = useState(false); |
| 984 | return ( |
| 985 | <WelcomeSection title={gt("Phone")}> |
| 986 | <Collapsible open={open} onOpenChange={setOpen}> |
| 987 | <div className="flex min-h-10 items-center gap-3 py-1"> |
| 988 | <RowIcon> |
| 989 | <SmartphoneIcon className="size-4" /> |
| 990 | </RowIcon> |
| 991 | <span className="min-w-0 flex-1 text-sm font-medium text-foreground"> |
| 992 | <T>Use T3 Code on your phone</T> |
| 993 | </span> |
| 994 | <CollapsibleTrigger render={<Button variant="ghost-muted" size="xs" />}> |
| 995 | {open ? gt("Hide") : gt("Set up")} |
| 996 | <ChevronDownIcon className={cn("size-3.5", open && "rotate-180")} /> |
| 997 | </CollapsibleTrigger> |
| 998 | </div> |
| 999 | <CollapsiblePanel> |
| 1000 | <div className="flex items-center gap-8 pt-2 pb-3 pl-8"> |
| 1001 | <ol className="min-w-0 flex-1 space-y-5"> |
| 1002 | <PhoneStep step={1}> |
| 1003 | <p className="text-sm text-foreground"> |
| 1004 | <T>Scan with your phone to get the app.</T> |
| 1005 | </p> |
| 1006 | </PhoneStep> |
| 1007 | <PhoneStep step={2}> |
| 1008 | <PhoneConnectLink environmentId={environmentId} /> |
| 1009 | </PhoneStep> |
| 1010 | </ol> |
| 1011 | {/* One code for both stores: the link opens the store that matches the phone. */} |
| 1012 | <div className="shrink-0 rounded-lg bg-white p-1.5"> |
| 1013 | <QRCodeSvg |
| 1014 | value={MOBILE_APP_URL} |
| 1015 | size={124} |
| 1016 | level="M" |
| 1017 | marginSize={2} |
| 1018 | title={gt("T3 Code app for iPhone and Android")} |
| 1019 | /> |
| 1020 | </div> |
| 1021 | </div> |
| 1022 | </CollapsiblePanel> |
| 1023 | </Collapsible> |
| 1024 | </WelcomeSection> |
| 1025 | ); |
| 1026 | } |
| 1027 | |
| 1028 | function PhoneStep({ step, children }: { readonly step: number; readonly children: ReactNode }) { |
| 1029 | return ( |
| 1030 | <li className="flex gap-3"> |
| 1031 | <span className="w-3 shrink-0 text-sm text-muted-foreground tabular-nums">{step}</span> |
| 1032 | <div className="flex min-w-0 flex-col items-start gap-2">{children}</div> |
| 1033 | </li> |
| 1034 | ); |
| 1035 | } |
| 1036 | |
| 1037 | function PhoneConnectLink({ environmentId }: { readonly environmentId: EnvironmentId }) { |
| 1038 | const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false }); |
| 1039 | const gt = useGT(); |
| 1040 | const loadFailed = useClerkLoadFailed(); |
| 1041 | const { openAuthPrompt } = useT3ConnectAuthPrompt(); |
| 1042 | const linkState = useCloudLinkState(environmentId); |
| 1043 | const refreshLinkState = useEffectEvent(linkState.refresh); |
| 1044 | // The server rechecks the tunnel every 30 s; read its latest result while this panel is open. |
| 1045 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- 30 s interval that refreshes the cloud link reachability while mounted |
| 1046 | useEffect(() => { |
| 1047 | const interval = window.setInterval(() => refreshLinkState(), 30_000); |
| 1048 | return () => window.clearInterval(interval); |
| 1049 | }, []); |
| 1050 | const link = linkState.data; |
| 1051 | // The phone reaches this computer through its tunnel; older servers leave that flag out. |
| 1052 | const shared = |
| 1053 | link !== null && |
| 1054 | link.linked && |
| 1055 | link.linkRevoked !== true && |
| 1056 | link.cloudUserId === userId && |
| 1057 | link.managedTunnelActive !== false; |
| 1058 | // The server checks the tunnel on its own; until it has, the result is unknown. |
| 1059 | const reachability = shared ? link.reachability?.status : undefined; |
| 1060 | const settingsLink = (label: string) => ( |
| 1061 | <Button variant="outline" size="xs" render={<Link to="/settings/access" />}> |
| 1062 | {label} |
| 1063 | </Button> |
| 1064 | ); |
| 1065 | if (isSignedIn && link === null && linkState.isPending) { |
| 1066 | return ( |
| 1067 | <p className="text-sm text-muted-foreground"> |
| 1068 | <T>Checking T3 Connect…</T> |
| 1069 | </p> |
| 1070 | ); |
| 1071 | } |
| 1072 | if (isSignedIn && linkState.error !== null) { |
| 1073 | return ( |
| 1074 | <> |
| 1075 | <p className="text-sm text-foreground"> |
| 1076 | <T>Could not check T3 Connect.</T> |
| 1077 | </p> |
| 1078 | {settingsLink(gt("Check T3 Connect"))} |
| 1079 | </> |
| 1080 | ); |
| 1081 | } |
| 1082 | if (isSignedIn && reachability === "reachable") { |
| 1083 | return ( |
| 1084 | <p className="flex gap-1.5 text-sm text-foreground"> |
| 1085 | <CheckIcon className="mt-0.5 size-4 shrink-0 text-success-foreground" /> |
| 1086 | <T>Your phone can reach this computer. Sign in to the app with the same account.</T> |
| 1087 | </p> |
| 1088 | ); |
| 1089 | } |
| 1090 | if (isSignedIn && shared && reachability === undefined) { |
| 1091 | return ( |
| 1092 | <p className="text-sm text-foreground"> |
| 1093 | <T>T3 Connect is on for this computer. Sign in to the app with the same account.</T> |
| 1094 | </p> |
| 1095 | ); |
| 1096 | } |
| 1097 | if (isSignedIn) { |
| 1098 | // Signing in alone does not share this computer, for example after "Not now". |
| 1099 | return ( |
| 1100 | <> |
| 1101 | <p className="text-sm text-foreground"> |
| 1102 | {shared |
| 1103 | ? gt("T3 Connect is on, but the app cannot reach this computer.") |
| 1104 | : gt("Signed in. Share this computer so the app can reach it.")} |
| 1105 | </p> |
| 1106 | {settingsLink(shared ? gt("Check T3 Connect") : gt("Set up T3 Connect"))} |
| 1107 | </> |
| 1108 | ); |
| 1109 | } |
| 1110 | return ( |
| 1111 | <> |
| 1112 | <p className="text-sm text-foreground"> |
| 1113 | <T>Sign in to T3 Connect here, then in the app with the same account.</T> |
| 1114 | </p> |
| 1115 | {loadFailed ? ( |
| 1116 | <Button variant="outline" size="xs" onClick={retryClerkLoad}> |
| 1117 | <T>Retry sign-in</T> |
| 1118 | </Button> |
| 1119 | ) : ( |
| 1120 | <Button variant="outline" size="xs" disabled={!isLoaded} onClick={openAuthPrompt}> |
| 1121 | <T>Sign in to T3 Connect</T> |
| 1122 | </Button> |
| 1123 | )} |
| 1124 | </> |
| 1125 | ); |
| 1126 | } |
| 1127 | |
| 1128 | // The ChatGPT card and the CLI card stay one card, so either choice can be undone here. |
| 1129 | function OnboardingCodexSetup({ |
| 1130 | environmentId, |
| 1131 | provider, |
| 1132 | serverConfig, |
| 1133 | onUseCliChange, |
| 1134 | }: { |
| 1135 | readonly environmentId: EnvironmentId; |
| 1136 | readonly provider: ServerProvider; |
| 1137 | readonly serverConfig: ServerConfig; |
| 1138 | // True asks for the CLI's install or sign-in terminal once Codex has checked the CLI. |
| 1139 | readonly onUseCliChange: (useCli: boolean) => void; |
| 1140 | }) { |
| 1141 | const gt = useGT(); |
| 1142 | const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); |
| 1143 | const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); |
| 1144 | const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId); |
| 1145 | const instanceId = provider.instanceId; |
| 1146 | const instance = serverConfig.settings.providerInstances[instanceId] ?? { |
| 1147 | driver: provider.driver, |
| 1148 | config: {}, |
| 1149 | }; |
| 1150 | const config = |
| 1151 | instance.config !== null && typeof instance.config === "object" ? instance.config : {}; |
| 1152 | const mode = readCodexSetupMode(config); |
| 1153 | const changeMode = (setupMode: "managed" | "existing") => { |
| 1154 | // "Use existing CLI" also opens a terminal to install or sign in to the CLI. |
| 1155 | onUseCliChange(setupMode === "existing"); |
| 1156 | const unchanged = mode === setupMode && provider.enabled; |
| 1157 | if (unchanged || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; |
| 1158 | // One-instance upsert keeps a provider another client added in the meantime. |
| 1159 | void persistProviderInstance({ |
| 1160 | operation: "upsert", |
| 1161 | instanceId, |
| 1162 | instance: { ...instance, enabled: true, config: { ...config, enabled: true, setupMode } }, |
| 1163 | }).then((result) => { |
| 1164 | if (result._tag === "Failure") { |
| 1165 | onUseCliChange(false); |
| 1166 | if (!isAtomCommandInterrupted(result)) { |
| 1167 | const cause = squashAtomCommandFailure(result); |
| 1168 | toastManager.add({ |
| 1169 | type: "error", |
| 1170 | title: gt("Could not save Codex setup"), |
| 1171 | ...(cause instanceof Error ? { description: cause.message } : {}), |
| 1172 | }); |
| 1173 | } |
| 1174 | } |
| 1175 | }); |
| 1176 | }; |
| 1177 | return ( |
| 1178 | <CodexSetupSection |
| 1179 | presentation="onboarding" |
| 1180 | environmentId={environmentId} |
| 1181 | instanceId={instanceId} |
| 1182 | provider={provider} |
| 1183 | mode={mode} |
| 1184 | enabled={provider.enabled} |
| 1185 | readOnly={!canManageProviders} |
| 1186 | existingCliDisabled={!canOperateTerminal} |
| 1187 | displayName={agentName(provider)} |
| 1188 | onModeChange={changeMode} |
| 1189 | /> |
| 1190 | ); |
| 1191 | } |
| 1192 | |
| 1193 | function TerminalAction({ |
| 1194 | name, |
| 1195 | signIn, |
| 1196 | disabled, |
| 1197 | onClick, |
| 1198 | }: { |
| 1199 | readonly name: string; |
| 1200 | readonly signIn: boolean; |
| 1201 | readonly disabled: boolean; |
| 1202 | readonly onClick: () => void; |
| 1203 | }) { |
| 1204 | const gt = useGT(); |
| 1205 | const label = signIn ? gt("Sign in") : gt("Install"); |
| 1206 | return ( |
| 1207 | <Button |
| 1208 | size="xs" |
| 1209 | variant="outline" |
| 1210 | aria-label={gt("{action}: {agent}", { action: label, agent: name })} |
| 1211 | disabled={disabled} |
| 1212 | onClick={onClick} |
| 1213 | > |
| 1214 | <TerminalIcon className="size-3.5" /> |
| 1215 | {label} |
| 1216 | </Button> |
| 1217 | ); |
| 1218 | } |
| 1219 | |
| 1220 | function AgentRow({ |
| 1221 | provider, |
| 1222 | state, |
| 1223 | action, |
| 1224 | compact = false, |
| 1225 | }: { |
| 1226 | readonly provider: ServerProvider; |
| 1227 | readonly state: ReturnType<typeof welcomeAgentState>; |
| 1228 | readonly action?: ReactNode; |
| 1229 | // A row in the "Add more agents" grid: the button carries the state, so no detail line. |
| 1230 | readonly compact?: boolean; |
| 1231 | }) { |
| 1232 | const name = agentName(provider); |
| 1233 | const gt = useGT(); |
| 1234 | const messages = useMessages(); |
| 1235 | // Claude Code and Codex tiles show Install or Set up; other agents that are on say why not. |
| 1236 | const brokenMessage = isBrokenVersion(provider) |
| 1237 | ? (provider.compatibilityAdvisory?.message ?? null) |
| 1238 | : null; |
| 1239 | const detail = |
| 1240 | state === "install" |
| 1241 | ? isInstallableDriver(provider.driver) |
| 1242 | ? null |
| 1243 | : gt("Not installed") |
| 1244 | : compact || state === "ready" || state === "checking" |
| 1245 | ? null |
| 1246 | : state === "attention" |
| 1247 | ? (provider.unavailableReason ?? |
| 1248 | brokenMessage ?? |
| 1249 | provider.message ?? |
| 1250 | getProviderSummary(provider, messages).headline) |
| 1251 | : (brokenMessage ?? getProviderSummary(provider, messages).headline); |
| 1252 | return ( |
| 1253 | <div className={cn("flex items-center gap-3", compact ? "min-h-9" : "min-h-10 py-1")}> |
| 1254 | <RowIcon> |
| 1255 | <ProviderInstanceIcon |
| 1256 | driverKind={provider.driver} |
| 1257 | displayName={name} |
| 1258 | iconClassName={compact ? "size-4" : "size-[18px]"} |
| 1259 | /> |
| 1260 | </RowIcon> |
| 1261 | <div className="min-w-0 flex-1"> |
| 1262 | <span className={cn("block truncate text-sm text-foreground", !compact && "font-medium")}> |
| 1263 | {name} |
| 1264 | </span> |
| 1265 | {detail ? ( |
| 1266 | <p className="line-clamp-2 text-xs leading-relaxed break-words text-muted-foreground"> |
| 1267 | {detail} |
| 1268 | </p> |
| 1269 | ) : null} |
| 1270 | </div> |
| 1271 | <div className="shrink-0"> |
| 1272 | {state === "ready" ? ( |
| 1273 | <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground"> |
| 1274 | <CheckIcon className="size-3.5" /> |
| 1275 | <T context="agent status">Ready</T> |
| 1276 | </span> |
| 1277 | ) : state === "checking" ? ( |
| 1278 | <span className="text-xs text-muted-foreground"> |
| 1279 | <T>Checking…</T> |
| 1280 | </span> |
| 1281 | ) : ( |
| 1282 | action |
| 1283 | )} |
| 1284 | </div> |
| 1285 | </div> |
| 1286 | ); |
| 1287 | } |
| 1288 | |
| 1289 | function AgentInstallTerminal({ |
| 1290 | session, |
| 1291 | onCommandFinished, |
| 1292 | onClose, |
| 1293 | }: { |
| 1294 | readonly session: AgentTerminalSession; |
| 1295 | readonly onCommandFinished: () => void; |
| 1296 | readonly onClose: () => void; |
| 1297 | }) { |
| 1298 | const { command, cwd, driver, environmentId, keybindings, providerInstanceId } = session; |
| 1299 | const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); |
| 1300 | const gt = useGT(); |
| 1301 | const [advancedTypography] = useLocalStorage( |
| 1302 | TYPOGRAPHY_ADVANCED_STORAGE_KEY, |
| 1303 | false, |
| 1304 | Schema.Boolean, |
| 1305 | ); |
| 1306 | const openTerminal = useAtomCommand(terminalEnvironment.open, { reportFailure: false }); |
| 1307 | const writeTerminal = useAtomCommand(terminalEnvironment.write, { reportFailure: false }); |
| 1308 | const closeTerminal = useAtomCommand(terminalEnvironment.close, { reportFailure: false }); |
| 1309 | const setupQueueRef = useRef(Promise.resolve()); |
| 1310 | const setupGenerationRef = useRef(0); |
| 1311 | const activeSetupGenerationRef = useRef<number | null>(null); |
| 1312 | const [terminalId] = useState(() => `onboarding-${driver}-${randomUUID()}`); |
| 1313 | const threadRef = scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID); |
| 1314 | const [setupAttempt, setSetupAttempt] = useState(0); |
| 1315 | const [setupState, setSetupState] = useState< |
| 1316 | "preparing" | "ready" | "openFailed" | "writeFailed" |
| 1317 | >("preparing"); |
| 1318 | const terminalReady = setupState === "ready" || setupState === "writeFailed"; |
| 1319 | const commandRunning = useThreadRunningTerminalIds({ |
| 1320 | environmentId, |
| 1321 | threadId: AGENT_ONBOARDING_THREAD_ID, |
| 1322 | }).includes(terminalId); |
| 1323 | const commandStartedRef = useRef(false); |
| 1324 | const handleCommandFinished = useEffectEvent(onCommandFinished); |
| 1325 | |
| 1326 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the shell stays open after an install or sign-in, so its command exiting is the only signal to check the agent again |
| 1327 | useEffect(() => { |
| 1328 | if (commandRunning) { |
| 1329 | commandStartedRef.current = true; |
| 1330 | } else if (commandStartedRef.current) { |
| 1331 | commandStartedRef.current = false; |
| 1332 | handleCommandFinished(); |
| 1333 | } |
| 1334 | }, [commandRunning]); |
| 1335 | |
| 1336 | // StrictMode can finish a cancelled open after replacement setup; it must not close or pre-type into that |
| 1337 | // session. |
| 1338 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the setup PTY, types the command into it, and closes it on cleanup |
| 1339 | useEffect(() => { |
| 1340 | const generation = setupGenerationRef.current + 1; |
| 1341 | setupGenerationRef.current = generation; |
| 1342 | activeSetupGenerationRef.current = generation; |
| 1343 | // oxlint-disable-next-line react/set-state-in-effect -- A retry or a new command reopens the terminal, which shows as preparing until the open settles. |
| 1344 | setSetupState("preparing"); |
| 1345 | |
| 1346 | setupQueueRef.current = setupQueueRef.current.then(async () => { |
| 1347 | if (activeSetupGenerationRef.current !== generation) return; |
| 1348 | if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { |
| 1349 | setSetupState("openFailed"); |
| 1350 | return; |
| 1351 | } |
| 1352 | const opened = await openTerminal({ |
| 1353 | environmentId, |
| 1354 | input: { |
| 1355 | threadId: AGENT_ONBOARDING_THREAD_ID, |
| 1356 | terminalId, |
| 1357 | cwd, |
| 1358 | providerInstanceId, |
| 1359 | }, |
| 1360 | }); |
| 1361 | if (opened._tag !== "Success") { |
| 1362 | if (activeSetupGenerationRef.current === generation) setSetupState("openFailed"); |
| 1363 | return; |
| 1364 | } |
| 1365 | |
| 1366 | if (activeSetupGenerationRef.current !== generation) return; |
| 1367 | if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { |
| 1368 | setSetupState("writeFailed"); |
| 1369 | return; |
| 1370 | } |
| 1371 | |
| 1372 | const wrote = await writeTerminal({ |
| 1373 | environmentId, |
| 1374 | input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, data: command }, |
| 1375 | }); |
| 1376 | if (activeSetupGenerationRef.current !== generation) return; |
| 1377 | setSetupState(wrote._tag === "Success" ? "ready" : "writeFailed"); |
| 1378 | }); |
| 1379 | |
| 1380 | // Revocation leaves the PTY running; close only while terminal access remains. |
| 1381 | return () => { |
| 1382 | if (activeSetupGenerationRef.current === generation) { |
| 1383 | activeSetupGenerationRef.current = null; |
| 1384 | } |
| 1385 | setupQueueRef.current = setupQueueRef.current.then(async () => { |
| 1386 | if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) return; |
| 1387 | await closeTerminal({ |
| 1388 | environmentId, |
| 1389 | input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, deleteHistory: true }, |
| 1390 | }); |
| 1391 | }); |
| 1392 | }; |
| 1393 | }, [ |
| 1394 | closeTerminal, |
| 1395 | command, |
| 1396 | cwd, |
| 1397 | environmentId, |
| 1398 | openTerminal, |
| 1399 | providerInstanceId, |
| 1400 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry bumps setupAttempt to open the terminal again. |
| 1401 | setupAttempt, |
| 1402 | terminalId, |
| 1403 | writeTerminal, |
| 1404 | ]); |
| 1405 | |
| 1406 | return ( |
| 1407 | <div |
| 1408 | data-thread-terminal-drawer |
| 1409 | className="mt-4 overflow-hidden rounded-lg border border-border/70 bg-background text-foreground" |
| 1410 | > |
| 1411 | <div className="flex items-center justify-between border-b border-border/60 bg-background/60 px-3 py-1.5"> |
| 1412 | <span className="text-2xs font-medium text-muted-foreground"> |
| 1413 | {!canOperateTerminal ? ( |
| 1414 | gt("This connection cannot control terminals.") |
| 1415 | ) : setupState === "writeFailed" ? ( |
| 1416 | <T> |
| 1417 | Run{" "} |
| 1418 | <code className="rounded bg-muted px-1 font-mono"> |
| 1419 | <Var>{command}</Var> |
| 1420 | </code>{" "} |
| 1421 | in this terminal. |
| 1422 | </T> |
| 1423 | ) : setupState === "ready" ? ( |
| 1424 | gt("Review the command, then press Enter to run it.") |
| 1425 | ) : setupState === "openFailed" ? ( |
| 1426 | gt("Could not open the setup terminal.") |
| 1427 | ) : ( |
| 1428 | gt("Preparing command...") |
| 1429 | )} |
| 1430 | </span> |
| 1431 | <div className="flex items-center gap-1"> |
| 1432 | {setupState === "openFailed" ? ( |
| 1433 | <Button |
| 1434 | size="xs" |
| 1435 | variant="ghost" |
| 1436 | disabled={!canOperateTerminal} |
| 1437 | onClick={() => { |
| 1438 | if (readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { |
| 1439 | setSetupAttempt((value) => value + 1); |
| 1440 | } |
| 1441 | }} |
| 1442 | > |
| 1443 | <T>Retry</T> |
| 1444 | </Button> |
| 1445 | ) : null} |
| 1446 | <Button size="xs" variant="ghost-muted" onClick={onClose}> |
| 1447 | <T>Close</T> |
| 1448 | </Button> |
| 1449 | </div> |
| 1450 | </div> |
| 1451 | <div className="h-64"> |
| 1452 | {terminalReady ? ( |
| 1453 | <TerminalViewport |
| 1454 | threadRef={threadRef} |
| 1455 | threadId={AGENT_ONBOARDING_THREAD_ID} |
| 1456 | terminalId={terminalId} |
| 1457 | terminalLabel={gt("Install {agent}", { agent: driver })} |
| 1458 | cwd={cwd} |
| 1459 | providerInstanceId={providerInstanceId} |
| 1460 | advancedTypography={advancedTypography} |
| 1461 | onSessionExited={onClose} |
| 1462 | autoFocus |
| 1463 | visible |
| 1464 | keybindings={keybindings} |
| 1465 | /> |
| 1466 | ) : null} |
| 1467 | </div> |
| 1468 | </div> |
| 1469 | ); |
| 1470 | } |
| 1471 | |
| 1472 | const IMPORT_PERMISSION_MESSAGE = msg("This connection cannot import projects or thread history."); |
| 1473 | |
| 1474 | // Creates the selected projects, then imports each one's agent history. Owns retry state so a |
| 1475 | // second Start resumes instead of recreating projects. |
| 1476 | function useProjectImport({ |
| 1477 | scans, |
| 1478 | importSelection, |
| 1479 | onImportSelectionChange, |
| 1480 | isImporting, |
| 1481 | setIsImporting, |
| 1482 | holdPageRef, |
| 1483 | onDone, |
| 1484 | }: { |
| 1485 | readonly scans: ReturnType<typeof useProjectScans>; |
| 1486 | readonly importSelection: WelcomeImportSelection | null; |
| 1487 | readonly onImportSelectionChange: (next: WelcomeImportSelection) => void; |
| 1488 | readonly isImporting: boolean; |
| 1489 | readonly setIsImporting: (value: boolean) => void; |
| 1490 | // Blocks leaving the page; onDone releases it before landing. |
| 1491 | readonly holdPageRef: { current: boolean }; |
| 1492 | readonly onDone: ( |
| 1493 | projectRef?: ScopedProjectRef, |
| 1494 | importWarning?: string, |
| 1495 | importedThreadCount?: number, |
| 1496 | ) => Promise<boolean>; |
| 1497 | }) { |
| 1498 | const writableEnvironments = useEnvironmentsWithScope(scans, AuthOrchestrationOperateScope); |
| 1499 | const gt = useGT(); |
| 1500 | const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); |
| 1501 | const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false }); |
| 1502 | const importWarningRef = useRef(""); |
| 1503 | // Per project, so a retry that skips finished projects still counts their threads. |
| 1504 | const importedThreadsRef = useRef(new Map<string, number>()); |
| 1505 | const importedProjectsRef = useRef(new Map<string, ScopedProjectRef>()); |
| 1506 | const projectsWithImportedHistoryRef = useRef(new Map<string, ScopedProjectRef>()); |
| 1507 | const lastImportSelectionRef = useRef<ReadonlyArray<string>>([]); |
| 1508 | const projectAttemptsRef = useRef( |
| 1509 | new Map<string, { readonly projectId: ProjectId; readonly commandId: CommandId }>(), |
| 1510 | ); |
| 1511 | const importGenerationRef = useRef(0); |
| 1512 | |
| 1513 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- bumps the import generation on mount and unmount so in-flight imports drop stale results |
| 1514 | useEffect(() => { |
| 1515 | importGenerationRef.current += 1; |
| 1516 | return () => { |
| 1517 | importGenerationRef.current += 1; |
| 1518 | }; |
| 1519 | }, []); |
| 1520 | |
| 1521 | const { available: candidates, recent: recentActive } = partitionOnboardingProjects( |
| 1522 | scans.flatMap((scan) => |
| 1523 | (scan.data?.candidates ?? []).map((candidate) => ({ |
| 1524 | ...candidate, |
| 1525 | environmentId: scan.environmentId, |
| 1526 | key: onboardingProjectKey(scan.environmentId, candidate.path), |
| 1527 | })), |
| 1528 | ), |
| 1529 | ); |
| 1530 | // Projects already in T3 Code stay in the list, but reopening the page does not import their |
| 1531 | // history again unless the user picks them. The scan can be 30 s old, so the live list decides. |
| 1532 | const projects = useProjects(); |
| 1533 | const isNewProject = isNewOnboardingProject(projects); |
| 1534 | const isNew = (candidate: ImportCandidate) => isNewProject(candidate.environmentId, candidate); |
| 1535 | const recent = recentActive.filter(isNew); |
| 1536 | const recentKeys = new Set(recent.map((candidate) => candidate.key)); |
| 1537 | const knownKeys = new Set(importSelection?.knownKeys); |
| 1538 | const pickedKeys = new Set(importSelection?.keys); |
| 1539 | const selected = importSelection?.optedOut |
| 1540 | ? [] |
| 1541 | : candidates.filter((candidate) => |
| 1542 | knownKeys.has(candidate.key) |
| 1543 | ? pickedKeys.has(candidate.key) |
| 1544 | : recentKeys.has(candidate.key), |
| 1545 | ); |
| 1546 | const selectedKeys = new Set(selected.map((candidate) => candidate.key)); |
| 1547 | const setSelectedKeys = (keys: ReadonlySet<string>, { optedOut = false } = {}) => |
| 1548 | onImportSelectionChange({ |
| 1549 | knownKeys: candidates.map((candidate) => candidate.key), |
| 1550 | keys: [...keys], |
| 1551 | optedOut, |
| 1552 | }); |
| 1553 | |
| 1554 | const canWrite = scans.every((scan) => writableEnvironments.has(scan.environmentId)); |
| 1555 | const canImport = selected.every((candidate) => |
| 1556 | writableEnvironments.has(candidate.environmentId), |
| 1557 | ); |
| 1558 | const visibleImportError = canWrite && canImport ? "" : IMPORT_PERMISSION_MESSAGE; |
| 1559 | |
| 1560 | const importedThreadTotal = () => |
| 1561 | lastImportSelectionRef.current.reduce( |
| 1562 | (total, key) => total + (importedThreadsRef.current.get(key) ?? 0), |
| 1563 | 0, |
| 1564 | ); |
| 1565 | |
| 1566 | const finishAfterImport = () => { |
| 1567 | const projectRef = resolveOnboardingLandingProject( |
| 1568 | lastImportSelectionRef.current, |
| 1569 | projectsWithImportedHistoryRef.current, |
| 1570 | importedProjectsRef.current, |
| 1571 | ); |
| 1572 | // Busy until setup is saved, so Start cannot run the import again meanwhile. |
| 1573 | setIsImporting(true); |
| 1574 | if (projectRef === undefined) { |
| 1575 | void onDone(undefined, importWarningRef.current, importedThreadTotal()).then((completed) => { |
| 1576 | if (!completed) setIsImporting(false); |
| 1577 | }); |
| 1578 | return; |
| 1579 | } |
| 1580 | holdPageRef.current = true; |
| 1581 | const importGeneration = importGenerationRef.current; |
| 1582 | // waitForProject gives up after its timeout, so a project that never reaches the client |
| 1583 | // still finishes setup, just without landing in it. |
| 1584 | void waitForProject(projectRef) |
| 1585 | .then( |
| 1586 | () => projectRef, |
| 1587 | () => undefined, |
| 1588 | ) |
| 1589 | .then(async (landing) => { |
| 1590 | if (importGeneration !== importGenerationRef.current) { |
| 1591 | holdPageRef.current = false; |
| 1592 | return; |
| 1593 | } |
| 1594 | const completed = await onDone(landing, importWarningRef.current, importedThreadTotal()); |
| 1595 | if (!completed) setIsImporting(false); |
| 1596 | }); |
| 1597 | }; |
| 1598 | |
| 1599 | const runImport = async (selection: typeof candidates) => { |
| 1600 | if (isImporting) return; |
| 1601 | const hasAccess = () => |
| 1602 | selection.every((candidate) => |
| 1603 | readEnvironmentScope(candidate.environmentId, AuthOrchestrationOperateScope), |
| 1604 | ); |
| 1605 | // The permission message shows from the session's scopes. |
| 1606 | const stopForDeniedAccess = () => setIsImporting(false); |
| 1607 | if (!hasAccess()) { |
| 1608 | stopForDeniedAccess(); |
| 1609 | return; |
| 1610 | } |
| 1611 | setIsImporting(true); |
| 1612 | importWarningRef.current = ""; |
| 1613 | lastImportSelectionRef.current = selection.map((candidate) => candidate.key); |
| 1614 | const importGeneration = importGenerationRef.current; |
| 1615 | const importedThreads = importedThreadsRef.current; |
| 1616 | const importedProjects = importedProjectsRef.current; |
| 1617 | const projectAttempts = projectAttemptsRef.current; |
| 1618 | let importedProjectsCount = |
| 1619 | importedProjects.size > 0 |
| 1620 | ? selection.filter((candidate) => importedProjects.has(candidate.key)).length |
| 1621 | : 0; |
| 1622 | let skippedThreadCount = 0; |
| 1623 | const refreshEnvironments = new Set<EnvironmentId>(); |
| 1624 | // Resolves false when the run stopped early: a newer run, an unmount, or lost access. |
| 1625 | const importEach = async () => { |
| 1626 | for (const candidate of selection) { |
| 1627 | const { environmentId } = candidate; |
| 1628 | if (importGeneration !== importGenerationRef.current) return false; |
| 1629 | if (!hasAccess()) { |
| 1630 | stopForDeniedAccess(); |
| 1631 | return false; |
| 1632 | } |
| 1633 | if (importedProjects.has(candidate.key)) continue; |
| 1634 | let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate); |
| 1635 | if (projectId === null) { |
| 1636 | let attempt = projectAttempts.get(candidate.key); |
| 1637 | if (attempt === undefined) { |
| 1638 | const nextProjectId = newProjectId(); |
| 1639 | attempt = { |
| 1640 | projectId: nextProjectId, |
| 1641 | commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`), |
| 1642 | }; |
| 1643 | projectAttempts.set(candidate.key, attempt); |
| 1644 | } |
| 1645 | projectId = attempt.projectId; |
| 1646 | const result = await createProject({ |
| 1647 | environmentId, |
| 1648 | input: { |
| 1649 | projectId, |
| 1650 | commandId: attempt.commandId, |
| 1651 | title: candidate.title, |
| 1652 | workspaceRoot: candidate.path, |
| 1653 | createWorkspaceRootIfMissing: false, |
| 1654 | defaultModelSelection: null, |
| 1655 | }, |
| 1656 | }); |
| 1657 | if (importGeneration !== importGenerationRef.current) return false; |
| 1658 | if (result._tag !== "Success") { |
| 1659 | if (!isAtomCommandInterrupted(result)) { |
| 1660 | projectAttempts.delete(candidate.key); |
| 1661 | refreshEnvironments.add(environmentId); |
| 1662 | } |
| 1663 | continue; |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | if (!hasAccess()) { |
| 1668 | stopForDeniedAccess(); |
| 1669 | return false; |
| 1670 | } |
| 1671 | const threadImportResult = await importThreads({ |
| 1672 | environmentId, |
| 1673 | input: { projectId, expectedWorkspaceRoot: candidate.path }, |
| 1674 | }); |
| 1675 | if (importGeneration !== importGenerationRef.current) return false; |
| 1676 | if (threadImportResult._tag === "Success") { |
| 1677 | importedThreads.set( |
| 1678 | candidate.key, |
| 1679 | (importedThreads.get(candidate.key) ?? 0) + threadImportResult.value.importedCount, |
| 1680 | ); |
| 1681 | skippedThreadCount += threadImportResult.value.skippedCount; |
| 1682 | if (threadImportResult.value.importedCount > 0) { |
| 1683 | projectsWithImportedHistoryRef.current.set( |
| 1684 | candidate.key, |
| 1685 | scopeProjectRef(environmentId, projectId), |
| 1686 | ); |
| 1687 | } |
| 1688 | if (threadImportResult.value.skippedCount === 0) { |
| 1689 | importedProjectsCount += 1; |
| 1690 | importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId)); |
| 1691 | } |
| 1692 | } else if (!isAtomCommandInterrupted(threadImportResult)) { |
| 1693 | projectAttempts.delete(candidate.key); |
| 1694 | refreshEnvironments.add(environmentId); |
| 1695 | } |
| 1696 | } |
| 1697 | return true; |
| 1698 | }; |
| 1699 | holdPageRef.current = true; |
| 1700 | const completed = await importEach().finally(() => { |
| 1701 | holdPageRef.current = false; |
| 1702 | }); |
| 1703 | if (!completed) return; |
| 1704 | for (const scan of scans) { |
| 1705 | if (refreshEnvironments.has(scan.environmentId)) scan.refresh(); |
| 1706 | } |
| 1707 | setIsImporting(false); |
| 1708 | const importedThreadCount = importedThreadTotal(); |
| 1709 | if (importedProjectsCount < selection.length) { |
| 1710 | if (importedThreadCount > 0 && skippedThreadCount > 0) { |
| 1711 | importWarningRef.current = `${gt( |
| 1712 | "{count, plural, one {Imported {count} thread.} other {Imported {count} threads.}}", |
| 1713 | { count: importedThreadCount }, |
| 1714 | )} ${gt( |
| 1715 | "{count, plural, one {{count} thread could not be imported.} other {{count} threads could not be imported.}}", |
| 1716 | { count: skippedThreadCount }, |
| 1717 | )}`; |
| 1718 | } else if (skippedThreadCount > 0) { |
| 1719 | importWarningRef.current = gt( |
| 1720 | "{count, plural, one {{count} thread could not be imported.} other {{count} threads could not be imported.}}", |
| 1721 | { count: skippedThreadCount }, |
| 1722 | ); |
| 1723 | } else if (importedThreadCount > 0) { |
| 1724 | importWarningRef.current = gt( |
| 1725 | "{count, plural, one {Imported {count} thread. Some thread history could not be imported.} other {Imported {count} threads. Some thread history could not be imported.}}", |
| 1726 | { count: importedThreadCount }, |
| 1727 | ); |
| 1728 | } else { |
| 1729 | importWarningRef.current = gt("Could not import thread history."); |
| 1730 | } |
| 1731 | } |
| 1732 | finishAfterImport(); |
| 1733 | }; |
| 1734 | |
| 1735 | return { |
| 1736 | canWrite, |
| 1737 | candidates, |
| 1738 | isNew, |
| 1739 | recent, |
| 1740 | selected, |
| 1741 | selectedKeys, |
| 1742 | setSelectedKeys, |
| 1743 | visibleImportError, |
| 1744 | runImport, |
| 1745 | finishAfterImport, |
| 1746 | }; |
| 1747 | } |
| 1748 | |
| 1749 | type ImportCandidate = AgentSessionProjectCandidate & { |
| 1750 | readonly environmentId: EnvironmentId; |
| 1751 | readonly key: string; |
| 1752 | }; |
| 1753 | |
| 1754 | function ImportCandidateList({ |
| 1755 | candidates, |
| 1756 | selectedKeys, |
| 1757 | onSelectionChange, |
| 1758 | }: { |
| 1759 | readonly candidates: ReadonlyArray<ImportCandidate>; |
| 1760 | readonly selectedKeys: ReadonlySet<string>; |
| 1761 | readonly onSelectionChange: (next: ReadonlySet<string>) => void; |
| 1762 | }) { |
| 1763 | const { repositories, other } = groupOnboardingProjects(candidates); |
| 1764 | const setKeys = (keys: ReadonlyArray<string>, checked: boolean) => { |
| 1765 | const next = new Set(selectedKeys); |
| 1766 | for (const key of keys) { |
| 1767 | if (checked) next.add(key); |
| 1768 | else next.delete(key); |
| 1769 | } |
| 1770 | onSelectionChange(next); |
| 1771 | }; |
| 1772 | const otherSelected = other.filter((candidate) => selectedKeys.has(candidate.key)).length; |
| 1773 | const gt = useGT(); |
| 1774 | |
| 1775 | return ( |
| 1776 | <> |
| 1777 | {repositories.map((group) => ( |
| 1778 | <ImportRepositoryGroup |
| 1779 | key={group.key} |
| 1780 | group={group} |
| 1781 | selectedKeys={selectedKeys} |
| 1782 | onToggle={setKeys} |
| 1783 | /> |
| 1784 | ))} |
| 1785 | {other.length > 0 ? ( |
| 1786 | <Collapsible> |
| 1787 | <div className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40"> |
| 1788 | <Checkbox |
| 1789 | checked={otherSelected === other.length} |
| 1790 | indeterminate={otherSelected > 0 && otherSelected < other.length} |
| 1791 | onCheckedChange={(checked) => |
| 1792 | setKeys( |
| 1793 | other.map((candidate) => candidate.key), |
| 1794 | checked === true, |
| 1795 | ) |
| 1796 | } |
| 1797 | /> |
| 1798 | <CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-1.5 text-left"> |
| 1799 | <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-panel-open:rotate-90" /> |
| 1800 | <span className="truncate text-sm text-muted-foreground"> |
| 1801 | <T>Other folders</T> |
| 1802 | </span> |
| 1803 | <span className="ml-auto shrink-0 text-xs text-muted-foreground tabular-nums"> |
| 1804 | {gt("{count, plural, one {{count} folder} other {{count} folders}}", { |
| 1805 | count: other.length, |
| 1806 | })} |
| 1807 | </span> |
| 1808 | </CollapsibleTrigger> |
| 1809 | </div> |
| 1810 | <CollapsiblePanel> |
| 1811 | {other.map((candidate) => ( |
| 1812 | <ImportCandidateRow |
| 1813 | key={candidate.key} |
| 1814 | candidate={candidate} |
| 1815 | path={candidate.path} |
| 1816 | nested |
| 1817 | checked={selectedKeys.has(candidate.key)} |
| 1818 | onCheckedChange={(checked) => setKeys([candidate.key], checked)} |
| 1819 | /> |
| 1820 | ))} |
| 1821 | </CollapsiblePanel> |
| 1822 | </Collapsible> |
| 1823 | ) : null} |
| 1824 | </> |
| 1825 | ); |
| 1826 | } |
| 1827 | |
| 1828 | function ImportRepositoryGroup({ |
| 1829 | group, |
| 1830 | selectedKeys, |
| 1831 | onToggle, |
| 1832 | }: { |
| 1833 | readonly group: OnboardingProjectGroup<ImportCandidate>; |
| 1834 | readonly selectedKeys: ReadonlySet<string>; |
| 1835 | readonly onToggle: (keys: ReadonlyArray<string>, checked: boolean) => void; |
| 1836 | }) { |
| 1837 | const keys = group.candidates.map((candidate) => candidate.key); |
| 1838 | const selectedCount = keys.filter((key) => selectedKeys.has(key)).length; |
| 1839 | const single = group.candidates.length === 1; |
| 1840 | const only = group.candidates[0]; |
| 1841 | if (single && only !== undefined) { |
| 1842 | return ( |
| 1843 | <ImportCandidateRow |
| 1844 | candidate={only} |
| 1845 | label={group.label} |
| 1846 | path={only.path} |
| 1847 | checked={selectedKeys.has(only.key)} |
| 1848 | onCheckedChange={(checked) => onToggle([only.key], checked)} |
| 1849 | /> |
| 1850 | ); |
| 1851 | } |
| 1852 | return ( |
| 1853 | <Collapsible defaultOpen> |
| 1854 | <div className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40"> |
| 1855 | <Checkbox |
| 1856 | checked={selectedCount === keys.length} |
| 1857 | indeterminate={selectedCount > 0 && selectedCount < keys.length} |
| 1858 | onCheckedChange={(checked) => onToggle(keys, checked === true)} |
| 1859 | /> |
| 1860 | <CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-1.5 text-left"> |
| 1861 | <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-panel-open:rotate-90" /> |
| 1862 | <span className="truncate text-sm font-medium">{group.label}</span> |
| 1863 | <ImportRowMeta |
| 1864 | sources={[...new Set(group.candidates.flatMap((c) => c.sources))]} |
| 1865 | threadCount={group.threadCount} |
| 1866 | lastActiveAt={group.lastActiveAt} |
| 1867 | /> |
| 1868 | </CollapsibleTrigger> |
| 1869 | </div> |
| 1870 | <CollapsiblePanel> |
| 1871 | {group.candidates.map((candidate) => ( |
| 1872 | <ImportCandidateRow |
| 1873 | key={candidate.key} |
| 1874 | candidate={candidate} |
| 1875 | path={candidate.path} |
| 1876 | nested |
| 1877 | checked={selectedKeys.has(candidate.key)} |
| 1878 | onCheckedChange={(checked) => onToggle([candidate.key], checked)} |
| 1879 | /> |
| 1880 | ))} |
| 1881 | </CollapsiblePanel> |
| 1882 | </Collapsible> |
| 1883 | ); |
| 1884 | } |
| 1885 | |
| 1886 | function ProjectPathText({ |
| 1887 | path, |
| 1888 | className, |
| 1889 | }: { |
| 1890 | readonly path: string; |
| 1891 | readonly className?: string; |
| 1892 | }) { |
| 1893 | const { name, parent } = splitOnboardingProjectPath(path); |
| 1894 | return ( |
| 1895 | <span className={cn("flex min-w-0 items-baseline font-mono", className)}> |
| 1896 | {parent.length > 0 ? <span className="truncate">{parent}</span> : null} |
| 1897 | <span className="max-w-full shrink-0 truncate">{name}</span> |
| 1898 | </span> |
| 1899 | ); |
| 1900 | } |
| 1901 | |
| 1902 | function ImportCandidateRow({ |
| 1903 | candidate, |
| 1904 | label, |
| 1905 | path, |
| 1906 | nested = false, |
| 1907 | checked, |
| 1908 | onCheckedChange, |
| 1909 | }: { |
| 1910 | readonly candidate: ImportCandidate; |
| 1911 | readonly label?: string; |
| 1912 | readonly path?: string; |
| 1913 | readonly nested?: boolean; |
| 1914 | readonly checked: boolean; |
| 1915 | readonly onCheckedChange: (checked: boolean) => void; |
| 1916 | }) { |
| 1917 | return ( |
| 1918 | <label |
| 1919 | className={cn( |
| 1920 | "flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40 has-disabled:cursor-default", |
| 1921 | nested && "pl-8", |
| 1922 | )} |
| 1923 | > |
| 1924 | <Checkbox checked={checked} onCheckedChange={(value) => onCheckedChange(value === true)} /> |
| 1925 | <Tooltip> |
| 1926 | <TooltipTrigger |
| 1927 | render={<span className="flex min-w-0 flex-1 items-baseline gap-2 truncate" />} |
| 1928 | > |
| 1929 | {label !== undefined ? ( |
| 1930 | <span className="truncate text-sm font-medium">{label}</span> |
| 1931 | ) : null} |
| 1932 | {path !== undefined ? ( |
| 1933 | <ProjectPathText |
| 1934 | path={path} |
| 1935 | className={label === undefined ? "text-xs" : "text-2xs text-muted-foreground"} |
| 1936 | /> |
| 1937 | ) : null} |
| 1938 | </TooltipTrigger> |
| 1939 | <TooltipPopup variant="code">{candidate.path}</TooltipPopup> |
| 1940 | </Tooltip> |
| 1941 | <ImportRowMeta |
| 1942 | sources={nested ? null : candidate.sources} |
| 1943 | threadCount={candidate.threadCount} |
| 1944 | lastActiveAt={candidate.lastActiveAt} |
| 1945 | /> |
| 1946 | </label> |
| 1947 | ); |
| 1948 | } |
| 1949 | |
| 1950 | const IMPORT_SOURCE_NAMES: Record<AgentSessionSource, string> = { |
| 1951 | claudeAgent: "Claude Code", |
| 1952 | codex: "Codex", |
| 1953 | pi: "Pi", |
| 1954 | }; |
| 1955 | function useImportSourcesLabel() { |
| 1956 | return new Intl.ListFormat(useLocale(), { type: "conjunction" }).format( |
| 1957 | AgentSessionSource.literals.map((source) => IMPORT_SOURCE_NAMES[source]), |
| 1958 | ); |
| 1959 | } |
| 1960 | |
| 1961 | function ImportRowMeta({ |
| 1962 | sources, |
| 1963 | threadCount, |
| 1964 | lastActiveAt, |
| 1965 | }: { |
| 1966 | readonly sources: ReadonlyArray<AgentSessionSource> | null; |
| 1967 | readonly threadCount: number; |
| 1968 | readonly lastActiveAt: string | null; |
| 1969 | }) { |
| 1970 | const gt = useGT(); |
| 1971 | const messages = useMessages(); |
| 1972 | const relative = |
| 1973 | lastActiveAt === null ? null : formatRelativeTime(lastActiveAt, undefined, messages); |
| 1974 | const age = |
| 1975 | relative === null |
| 1976 | ? "" |
| 1977 | : relative.suffix === null |
| 1978 | ? gt("now", { $context: "relative time" }) |
| 1979 | : relative.value; |
| 1980 | return ( |
| 1981 | <span className="ml-auto grid shrink-0 grid-cols-[1rem_1rem_1rem_2.5rem_2.25rem] items-center gap-x-1 text-xs text-muted-foreground tabular-nums"> |
| 1982 | {AgentSessionSource.literals.map((source) => ( |
| 1983 | <span key={source} className="flex size-4 items-center justify-center"> |
| 1984 | {sources?.includes(source) ? ( |
| 1985 | <span role="img" aria-label={IMPORT_SOURCE_NAMES[source]}> |
| 1986 | <ProviderInstanceIcon |
| 1987 | driverKind={ProviderDriverKind.make(source)} |
| 1988 | displayName={IMPORT_SOURCE_NAMES[source]} |
| 1989 | iconClassName="size-3" |
| 1990 | /> |
| 1991 | </span> |
| 1992 | ) : null} |
| 1993 | </span> |
| 1994 | ))} |
| 1995 | <span className="text-right">{threadCount}</span> |
| 1996 | <span className="text-right whitespace-nowrap">{age}</span> |
| 1997 | </span> |
| 1998 | ); |
| 1999 | } |
| 2000 | |
| 2001 | /** The desktop app links `t3` on a fresh install; this puts its folder on PATH when it is not. */ |
| 2002 | function CliPathSetup() { |
| 2003 | const { state, busy, run } = useDesktopCliCommand(); |
| 2004 | const setup = state?.pathSetup; |
| 2005 | if (!setup) return null; |
| 2006 | return ( |
| 2007 | <div className="flex min-h-10 items-center gap-3"> |
| 2008 | <RowIcon> |
| 2009 | <TerminalIcon className="size-4" /> |
| 2010 | </RowIcon> |
| 2011 | <p className="min-w-0 flex-1 text-sm text-muted-foreground"> |
| 2012 | {setup.added ? ( |
| 2013 | <T> |
| 2014 | Added to <Var>{setup.file}</Var>. Open a new terminal to use{" "} |
| 2015 | <code className="font-mono">t3</code>. |
| 2016 | </T> |
| 2017 | ) : ( |
| 2018 | <T> |
| 2019 | Use <code className="font-mono">t3</code> from any terminal. Adds one line to{" "} |
| 2020 | <Var>{setup.file}</Var>. |
| 2021 | </T> |
| 2022 | )} |
| 2023 | </p> |
| 2024 | {setup.added ? null : ( |
| 2025 | <Button size="xs" variant="outline" disabled={busy} onClick={() => run("addToPath")}> |
| 2026 | <T>Add to PATH</T> |
| 2027 | </Button> |
| 2028 | )} |
| 2029 | </div> |
| 2030 | ); |
| 2031 | } |