diff --git a/apps/web/src/components/onboarding/ProjectImportStep.tsx b/apps/web/src/components/onboarding/ProjectImportStep.tsx new file mode 100644 index 0000000000000..5302d036cf7ca --- /dev/null +++ b/apps/web/src/components/onboarding/ProjectImportStep.tsx @@ -0,0 +1,646 @@ +import type { + AgentSessionProjectCandidate, + EnvironmentId, + ProjectId, + ScopedProjectRef, +} from "@t3tools/contracts"; +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; +import { AuthOrchestrationOperateScope, CommandId, ProviderDriverKind } from "@t3tools/contracts"; +import { ChevronRightIcon } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; + +import { + groupOnboardingProjects, + partitionOnboardingProjects, + onboardingProjectKey, + resolveOnboardingLandingProject, + resolveOnboardingProjectId, + type OnboardingProjectGroup, + splitOnboardingProjectPath, +} from "../../onboarding/projectImport.logic"; +import type { useProjectScans } from "../../onboarding/useProjectScans"; +import { cn, newProjectId } from "../../lib/utils"; +import { agentSessionImport } from "../../state/agentSessions"; +import { readProjects, waitForProject } from "../../state/entities"; +import { useEnvironments } from "../../state/environments"; +import { projectEnvironment } from "../../state/projects"; +import { readEnvironmentScope, useEnvironmentsWithScope } from "../../state/session"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { formatRelativeTime } from "../../timestampFormat"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { Button } from "../ui/button"; +import { Checkbox } from "../ui/checkbox"; +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; +import { ScrollArea } from "../ui/scroll-area"; +import { Spinner } from "../ui/spinner"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; + +const SCAN_LIMIT_MESSAGE = "Scan limit reached. Some projects or conversations may be missing."; +const IMPORT_PERMISSION_MESSAGE = "This connection cannot import projects or thread history."; + +export function ProjectImportStep({ + scans, + isImporting, + setIsImporting, + onDone, + skipLabel = "Do not import projects", +}: { + readonly scans: ReturnType; + readonly skipLabel?: string; + readonly isImporting: boolean; + readonly setIsImporting: (value: boolean) => void; + readonly onDone: ( + projectRef?: ScopedProjectRef, + importWarning?: string, + importedThreadCount?: number, + ) => Promise; +}) { + const { environments } = useEnvironments(); + const writableEnvironments = useEnvironmentsWithScope(scans, AuthOrchestrationOperateScope); + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false }); + const [selectedPaths, setSelectedPaths] = useState | null>(null); + const importWarningRef = useRef(""); + const importedThreadCountRef = useRef(0); + const importedProjectsRef = useRef(new Map()); + const projectsWithImportedHistoryRef = useRef(new Map()); + const lastImportSelectionRef = useRef>([]); + const projectAttemptsRef = useRef( + new Map(), + ); + const importGenerationRef = useRef(0); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- bumps the import generation on mount and unmount so in-flight imports drop stale results + useEffect(() => { + importGenerationRef.current += 1; + return () => { + importGenerationRef.current += 1; + }; + }, []); + + const { available: candidates, recent } = partitionOnboardingProjects( + scans.flatMap((scan) => + (scan.data?.candidates ?? []).map((candidate) => ({ + ...candidate, + environmentId: scan.environmentId, + key: onboardingProjectKey(scan.environmentId, candidate.path), + })), + ), + ); + const selectedKeys = selectedPaths ?? new Set(recent.map((candidate) => candidate.key)); + const selected = candidates.filter((candidate) => selectedKeys.has(candidate.key)); + + const canImport = selected.every((candidate) => + writableEnvironments.has(candidate.environmentId), + ); + const [importError, setImportError] = useState(""); + const visibleImportError = !canImport + ? IMPORT_PERMISSION_MESSAGE + : importError === IMPORT_PERMISSION_MESSAGE + ? "" + : importError; + + const finishAfterImport = () => { + const projectRef = resolveOnboardingLandingProject( + lastImportSelectionRef.current, + projectsWithImportedHistoryRef.current, + importedProjectsRef.current, + ); + if (projectRef === undefined) { + void onDone(undefined, importWarningRef.current, importedThreadCountRef.current); + return; + } + setIsImporting(true); + const importGeneration = importGenerationRef.current; + // waitForProject gives up after its timeout, so a project that never reaches the client + // still finishes setup, just without landing in it. + void waitForProject(projectRef) + .then( + () => projectRef, + () => undefined, + ) + .then(async (landing) => { + if (importGeneration !== importGenerationRef.current) return; + const completed = await onDone( + landing, + importWarningRef.current, + importedThreadCountRef.current, + ); + if (!completed) setIsImporting(false); + }); + }; + + const runImport = async (selection: typeof candidates) => { + if (isImporting) return; + const hasAccess = () => + selection.every((candidate) => + readEnvironmentScope(candidate.environmentId, AuthOrchestrationOperateScope), + ); + const stopForDeniedAccess = () => { + setIsImporting(false); + setImportError(IMPORT_PERMISSION_MESSAGE); + }; + if (!hasAccess()) { + stopForDeniedAccess(); + return; + } + if (selection.length === 0) { + void onDone(); + return; + } + setIsImporting(true); + importWarningRef.current = ""; + importedThreadCountRef.current = 0; + lastImportSelectionRef.current = selection.map((candidate) => candidate.key); + const importGeneration = importGenerationRef.current; + const importedProjects = importedProjectsRef.current; + const projectAttempts = projectAttemptsRef.current; + let importedProjectsCount = + importedProjects.size > 0 + ? selection.filter((candidate) => importedProjects.has(candidate.key)).length + : 0; + let importedThreadCount = 0; + let skippedThreadCount = 0; + const refreshEnvironments = new Set(); + for (const candidate of selection) { + const { environmentId } = candidate; + if ( + importGeneration !== importGenerationRef.current || + importedProjects !== importedProjectsRef.current + ) { + return; + } + if (!hasAccess()) { + stopForDeniedAccess(); + return; + } + if (importedProjects.has(candidate.key)) continue; + let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate); + if (projectId === null) { + let attempt = projectAttempts.get(candidate.key); + if (attempt === undefined) { + const nextProjectId = newProjectId(); + attempt = { + projectId: nextProjectId, + commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`), + }; + projectAttempts.set(candidate.key, attempt); + } + projectId = attempt.projectId; + const result = await createProject({ + environmentId, + input: { + projectId, + commandId: attempt.commandId, + title: candidate.title, + workspaceRoot: candidate.path, + createWorkspaceRootIfMissing: false, + defaultModelSelection: null, + }, + }); + if ( + importGeneration !== importGenerationRef.current || + importedProjects !== importedProjectsRef.current + ) { + return; + } + if (result._tag !== "Success") { + if (!isAtomCommandInterrupted(result)) { + projectAttempts.delete(candidate.key); + refreshEnvironments.add(environmentId); + } + continue; + } + } + + if (!hasAccess()) { + stopForDeniedAccess(); + return; + } + const threadImportResult = await importThreads({ + environmentId, + input: { projectId, expectedWorkspaceRoot: candidate.path }, + }); + if ( + importGeneration !== importGenerationRef.current || + importedProjects !== importedProjectsRef.current + ) { + return; + } + if (threadImportResult._tag === "Success") { + importedThreadCount += threadImportResult.value.importedCount; + skippedThreadCount += threadImportResult.value.skippedCount; + if (threadImportResult.value.importedCount > 0) { + projectsWithImportedHistoryRef.current.set( + candidate.key, + scopeProjectRef(environmentId, projectId), + ); + } + if (threadImportResult.value.skippedCount === 0) { + importedProjectsCount += 1; + importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId)); + } + } else if (!isAtomCommandInterrupted(threadImportResult)) { + projectAttempts.delete(candidate.key); + refreshEnvironments.add(environmentId); + } + } + for (const scan of scans) { + if (refreshEnvironments.has(scan.environmentId)) scan.refresh(); + } + setIsImporting(false); + importedThreadCountRef.current = importedThreadCount; + if (importedProjectsCount < selection.length) { + if (importedThreadCount > 0 && skippedThreadCount > 0) { + importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedThreadCount} ${skippedThreadCount === 1 ? "thread" : "threads"} could not be imported.`; + } else if (skippedThreadCount > 0) { + importWarningRef.current = `${skippedThreadCount} ${skippedThreadCount === 1 ? "thread could" : "threads could"} not be imported.`; + } else if (importedThreadCount > 0) { + importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`; + } else { + importWarningRef.current = "Could not import thread history."; + } + } + finishAfterImport(); + }; + + if (scans.every((scan) => scan.data === null) && scans.some((scan) => scan.isPending)) { + return ( +
+

Your projects

+
+ +

+ Looking for projects from Claude Code and Codex… +

+
+
+ +
+
+ ); + } + + return ( + + {candidates.length > 0 ? ( +
+ + {selected.length} of {candidates.length} selected + +
+ + +
+
+ ) : null} + +
+ {scans.map((scan) => { + const scanCandidates = candidates.filter( + (candidate) => candidate.environmentId === scan.environmentId, + ); + const label = + environments.find((environment) => environment.environmentId === scan.environmentId) + ?.label ?? "Computer"; + return ( +
+ {scans.length > 1 ? ( + {label} + ) : null} + {scan.isPending && scan.data === null ? ( +
+ + Looking for projects… +
+ ) : scan.error !== null ? ( +
+ Could not check projects. {scan.error} + +
+ ) : scanCandidates.length === 0 ? ( +

+ No existing Claude Code or Codex projects found. +

+ ) : null} + {scan.data?.truncated ? ( +

+ {SCAN_LIMIT_MESSAGE} +

+ ) : null} + +
+ ); + })} +
+
+ {visibleImportError ? ( +

{visibleImportError}

+ ) : null} +
+ + +
+
+ ); +} + +type ImportCandidate = AgentSessionProjectCandidate & { + readonly environmentId: EnvironmentId; + readonly key: string; +}; + +function ImportCandidateList({ + candidates, + selectedKeys, + onSelectionChange, +}: { + readonly candidates: ReadonlyArray; + readonly selectedKeys: ReadonlySet; + readonly onSelectionChange: (next: ReadonlySet) => void; +}) { + const { repositories, other } = groupOnboardingProjects(candidates); + const setKeys = (keys: ReadonlyArray, checked: boolean) => { + const next = new Set(selectedKeys); + for (const key of keys) { + if (checked) next.add(key); + else next.delete(key); + } + onSelectionChange(next); + }; + const otherSelected = other.filter((candidate) => selectedKeys.has(candidate.key)).length; + + return ( + <> + {repositories.map((group) => ( + + ))} + {other.length > 0 ? ( + +
+ 0 && otherSelected < other.length} + onCheckedChange={(checked) => + setKeys( + other.map((candidate) => candidate.key), + checked === true, + ) + } + /> + + + Other folders + + {other.length} {other.length === 1 ? "folder" : "folders"} + + +
+ + {other.map((candidate) => ( + setKeys([candidate.key], checked)} + /> + ))} + +
+ ) : null} + + ); +} + +function ImportRepositoryGroup({ + group, + selectedKeys, + onToggle, +}: { + readonly group: OnboardingProjectGroup; + readonly selectedKeys: ReadonlySet; + readonly onToggle: (keys: ReadonlyArray, checked: boolean) => void; +}) { + const keys = group.candidates.map((candidate) => candidate.key); + const selectedCount = keys.filter((key) => selectedKeys.has(key)).length; + const single = group.candidates.length === 1; + const only = group.candidates[0]; + if (single && only !== undefined) { + return ( + onToggle([only.key], checked)} + /> + ); + } + return ( + +
+ 0 && selectedCount < keys.length} + onCheckedChange={(checked) => onToggle(keys, checked === true)} + /> + + + {group.label} + c.sources))]} + threadCount={group.threadCount} + lastActiveAt={group.lastActiveAt} + /> + +
+ + {group.candidates.map((candidate) => ( + onToggle([candidate.key], checked)} + /> + ))} + +
+ ); +} + +function ProjectPathText({ + path, + className, +}: { + readonly path: string; + readonly className?: string; +}) { + const { name, parent } = splitOnboardingProjectPath(path); + return ( + + {parent.length > 0 ? {parent} : null} + {name} + + ); +} + +function ImportCandidateRow({ + candidate, + label, + path, + nested = false, + checked, + onCheckedChange, +}: { + readonly candidate: ImportCandidate; + readonly label?: string; + readonly path?: string; + readonly nested?: boolean; + readonly checked: boolean; + readonly onCheckedChange: (checked: boolean) => void; +}) { + return ( + + ); +} + +function ImportRowMeta({ + sources, + threadCount, + lastActiveAt, +}: { + readonly sources: ReadonlyArray<"claudeAgent" | "codex"> | null; + readonly threadCount: number; + readonly lastActiveAt: string | null; +}) { + const relative = lastActiveAt === null ? null : formatRelativeTime(lastActiveAt); + const age = relative === null ? "" : relative.suffix === null ? "now" : relative.value; + return ( + + + {sources?.includes("claudeAgent") ? ( + + + + ) : null} + + + {sources?.includes("codex") ? ( + + + + ) : null} + + {threadCount} + {age} + + ); +} + +export function StepShell({ + title, + description, + children, +}: { + readonly title: string; + readonly description?: string; + readonly children?: React.ReactNode; +}) { + return ( + <> +

{title}

+ {description ? ( +

{description}

+ ) : null} + {children} + + ); +} diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx index 50d65192c0249..a34249988b9a1 100644 --- a/apps/web/src/components/onboarding/WelcomeWizard.tsx +++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx @@ -1,24 +1,20 @@ import { useAuth } from "@clerk/react"; import { useAtomValue } from "@effect/atom-react"; import type { - AgentSessionProjectCandidate, EnvironmentId, - ProjectId, ProviderInstanceId, ScopedProjectRef, ServerConfig, ServerProvider, } from "@t3tools/contracts"; -import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { AuthTerminalOperateScope, - CommandId, defaultInstanceIdForDriver, - AuthOrchestrationOperateScope, ProviderDriverKind, ThreadId, } from "@t3tools/contracts"; @@ -40,37 +36,21 @@ import { hasCloudPublicConfig } from "../../cloud/publicConfig"; import { PRIVACY_POLICY_URL } from "../../legalLinks"; import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; import { completeOnboarding } from "../../onboarding/firstRun"; -import { - groupOnboardingProjects, - partitionOnboardingProjects, - onboardingProjectKey, - resolveOnboardingLandingProject, - resolveOnboardingProjectId, - type OnboardingProjectGroup, - splitOnboardingProjectPath, -} from "../../onboarding/projectImport.logic"; import { getOnboardingProviderState, resolveOnboardingProviderInstallCommand, resolveOnboardingProviderLoginCommand, selectOnboardingProvidersByDriver, } from "../../onboarding/providerReadiness.logic"; -import { newProjectId, randomUUID } from "../../lib/utils"; -import { agentSessionImport } from "../../state/agentSessions"; -import { readProjects, waitForProject } from "../../state/entities"; +import { randomUUID } from "../../lib/utils"; import { useEnvironments, usePrimaryEnvironment } from "../../state/environments"; import { isOnboardingRelayEnvironment, resolveOnboardingSetup, } from "../../onboarding/targetEnvironment.logic"; import { useProjectScans } from "../../onboarding/useProjectScans"; -import { projectEnvironment } from "../../state/projects"; import { serverEnvironment } from "../../state/server"; -import { - readEnvironmentScope, - useEnvironmentScope, - useEnvironmentsWithScope, -} from "../../state/session"; +import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; import { terminalEnvironment } from "../../state/terminal"; import { useAtomCommand } from "../../state/use-atom-command"; import { connectPairing } from "../../connection/onboarding"; @@ -85,27 +65,24 @@ import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectLis import { presentSavedCloudEnvironmentConnection } from "../cloud/cloudEnvironmentConnectionPresentation"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { T3Wordmark } from "../T3Wordmark"; +import { ProjectImportStep, StepShell } from "./ProjectImportStep"; import { Alert, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; import { CommandBlock } from "../CommandBlock"; import { Checkbox } from "../ui/checkbox"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { Input } from "../ui/input"; -import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; import { ScrollArea } from "../ui/scroll-area"; -import { Spinner } from "../ui/spinner"; import { WizardPanel, WizardSteps, WizardPopup, WizardHeader } from "../ui/wizard"; import { Dialog } from "../ui/dialog"; import { toastManager } from "../ui/toast"; import { cn } from "../../lib/utils"; -import { formatRelativeTime } from "../../timestampFormat"; type WizardStep = "connection" | "agents" | "import"; const NO_ENVIRONMENTS: readonly EnvironmentId[] = []; const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup"); const ONBOARDING_STAGES = ["Connect", "Agents", "Projects"] as const; -const SCAN_LIMIT_MESSAGE = "Scan limit reached. Some projects or conversations may be missing."; export function WelcomeWizard({ localAvailable, @@ -277,7 +254,7 @@ export function WelcomeWizard({ ) : step === "agents" ? ( setStep("import")} /> ) : ( - ); } - -const IMPORT_PERMISSION_MESSAGE = "This connection cannot import projects or thread history."; - -function ImportStep({ - scans, - isImporting, - setIsImporting, - onDone, -}: { - readonly scans: ReturnType; - readonly isImporting: boolean; - readonly setIsImporting: (value: boolean) => void; - readonly onDone: ( - projectRef?: ScopedProjectRef, - importWarning?: string, - importedThreadCount?: number, - ) => Promise; -}) { - const { environments } = useEnvironments(); - const writableEnvironments = useEnvironmentsWithScope(scans, AuthOrchestrationOperateScope); - const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); - const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false }); - const [selectedPaths, setSelectedPaths] = useState | null>(null); - const importWarningRef = useRef(""); - const importedThreadCountRef = useRef(0); - const importedProjectsRef = useRef(new Map()); - const projectsWithImportedHistoryRef = useRef(new Map()); - const lastImportSelectionRef = useRef>([]); - const projectAttemptsRef = useRef( - new Map(), - ); - const importGenerationRef = useRef(0); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- bumps the import generation on mount and unmount so in-flight imports drop stale results - useEffect(() => { - importGenerationRef.current += 1; - return () => { - importGenerationRef.current += 1; - }; - }, []); - - const { available: candidates, recent } = partitionOnboardingProjects( - scans.flatMap((scan) => - (scan.data?.candidates ?? []).map((candidate) => ({ - ...candidate, - environmentId: scan.environmentId, - key: onboardingProjectKey(scan.environmentId, candidate.path), - })), - ), - ); - const selectedKeys = selectedPaths ?? new Set(recent.map((candidate) => candidate.key)); - const selected = candidates.filter((candidate) => selectedKeys.has(candidate.key)); - - const canImport = selected.every((candidate) => - writableEnvironments.has(candidate.environmentId), - ); - const [importError, setImportError] = useState(""); - const visibleImportError = !canImport - ? IMPORT_PERMISSION_MESSAGE - : importError === IMPORT_PERMISSION_MESSAGE - ? "" - : importError; - - const finishAfterImport = () => { - const projectRef = resolveOnboardingLandingProject( - lastImportSelectionRef.current, - projectsWithImportedHistoryRef.current, - importedProjectsRef.current, - ); - if (projectRef === undefined) { - void onDone(undefined, importWarningRef.current, importedThreadCountRef.current); - return; - } - setIsImporting(true); - const importGeneration = importGenerationRef.current; - // waitForProject gives up after its timeout, so a project that never reaches the client - // still finishes setup, just without landing in it. - void waitForProject(projectRef) - .then( - () => projectRef, - () => undefined, - ) - .then(async (landing) => { - if (importGeneration !== importGenerationRef.current) return; - const completed = await onDone( - landing, - importWarningRef.current, - importedThreadCountRef.current, - ); - if (!completed) setIsImporting(false); - }); - }; - - const runImport = async (selection: typeof candidates) => { - if (isImporting) return; - const hasAccess = () => - selection.every((candidate) => - readEnvironmentScope(candidate.environmentId, AuthOrchestrationOperateScope), - ); - const stopForDeniedAccess = () => { - setIsImporting(false); - setImportError(IMPORT_PERMISSION_MESSAGE); - }; - if (!hasAccess()) { - stopForDeniedAccess(); - return; - } - if (selection.length === 0) { - void onDone(); - return; - } - setIsImporting(true); - importWarningRef.current = ""; - importedThreadCountRef.current = 0; - lastImportSelectionRef.current = selection.map((candidate) => candidate.key); - const importGeneration = importGenerationRef.current; - const importedProjects = importedProjectsRef.current; - const projectAttempts = projectAttemptsRef.current; - let importedProjectsCount = - importedProjects.size > 0 - ? selection.filter((candidate) => importedProjects.has(candidate.key)).length - : 0; - let importedThreadCount = 0; - let skippedThreadCount = 0; - const refreshEnvironments = new Set(); - for (const candidate of selection) { - const { environmentId } = candidate; - if ( - importGeneration !== importGenerationRef.current || - importedProjects !== importedProjectsRef.current - ) { - return; - } - if (!hasAccess()) { - stopForDeniedAccess(); - return; - } - if (importedProjects.has(candidate.key)) continue; - let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate); - if (projectId === null) { - let attempt = projectAttempts.get(candidate.key); - if (attempt === undefined) { - const nextProjectId = newProjectId(); - attempt = { - projectId: nextProjectId, - commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`), - }; - projectAttempts.set(candidate.key, attempt); - } - projectId = attempt.projectId; - const result = await createProject({ - environmentId, - input: { - projectId, - commandId: attempt.commandId, - title: candidate.title, - workspaceRoot: candidate.path, - createWorkspaceRootIfMissing: false, - defaultModelSelection: null, - }, - }); - if ( - importGeneration !== importGenerationRef.current || - importedProjects !== importedProjectsRef.current - ) { - return; - } - if (result._tag !== "Success") { - if (!isAtomCommandInterrupted(result)) { - projectAttempts.delete(candidate.key); - refreshEnvironments.add(environmentId); - } - continue; - } - } - - if (!hasAccess()) { - stopForDeniedAccess(); - return; - } - const threadImportResult = await importThreads({ - environmentId, - input: { projectId, expectedWorkspaceRoot: candidate.path }, - }); - if ( - importGeneration !== importGenerationRef.current || - importedProjects !== importedProjectsRef.current - ) { - return; - } - if (threadImportResult._tag === "Success") { - importedThreadCount += threadImportResult.value.importedCount; - skippedThreadCount += threadImportResult.value.skippedCount; - if (threadImportResult.value.importedCount > 0) { - projectsWithImportedHistoryRef.current.set( - candidate.key, - scopeProjectRef(environmentId, projectId), - ); - } - if (threadImportResult.value.skippedCount === 0) { - importedProjectsCount += 1; - importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId)); - } - } else if (!isAtomCommandInterrupted(threadImportResult)) { - projectAttempts.delete(candidate.key); - refreshEnvironments.add(environmentId); - } - } - for (const scan of scans) { - if (refreshEnvironments.has(scan.environmentId)) scan.refresh(); - } - setIsImporting(false); - importedThreadCountRef.current = importedThreadCount; - if (importedProjectsCount < selection.length) { - if (importedThreadCount > 0 && skippedThreadCount > 0) { - importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedThreadCount} ${skippedThreadCount === 1 ? "thread" : "threads"} could not be imported.`; - } else if (skippedThreadCount > 0) { - importWarningRef.current = `${skippedThreadCount} ${skippedThreadCount === 1 ? "thread could" : "threads could"} not be imported.`; - } else if (importedThreadCount > 0) { - importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`; - } else { - importWarningRef.current = "Could not import thread history."; - } - } - finishAfterImport(); - }; - - if (scans.every((scan) => scan.data === null) && scans.some((scan) => scan.isPending)) { - return ( -
-

Your projects

-
- -

- Looking for projects from Claude Code and Codex… -

-
-
- -
-
- ); - } - - return ( - - {candidates.length > 0 ? ( -
- - {selected.length} of {candidates.length} selected - -
- - -
-
- ) : null} - -
- {scans.map((scan) => { - const scanCandidates = candidates.filter( - (candidate) => candidate.environmentId === scan.environmentId, - ); - const label = - environments.find((environment) => environment.environmentId === scan.environmentId) - ?.label ?? "Computer"; - return ( -
- {scans.length > 1 ? ( - {label} - ) : null} - {scan.isPending && scan.data === null ? ( -
- - Looking for projects… -
- ) : scan.error !== null ? ( -
- Could not check projects. {scan.error} - -
- ) : scanCandidates.length === 0 ? ( -

- No existing Claude Code or Codex projects found. -

- ) : null} - {scan.data?.truncated ? ( -

- {SCAN_LIMIT_MESSAGE} -

- ) : null} - -
- ); - })} -
-
- {visibleImportError ? ( -

{visibleImportError}

- ) : null} -
- - -
-
- ); -} - -type ImportCandidate = AgentSessionProjectCandidate & { - readonly environmentId: EnvironmentId; - readonly key: string; -}; - -function ImportCandidateList({ - candidates, - selectedKeys, - onSelectionChange, -}: { - readonly candidates: ReadonlyArray; - readonly selectedKeys: ReadonlySet; - readonly onSelectionChange: (next: ReadonlySet) => void; -}) { - const { repositories, other } = groupOnboardingProjects(candidates); - const setKeys = (keys: ReadonlyArray, checked: boolean) => { - const next = new Set(selectedKeys); - for (const key of keys) { - if (checked) next.add(key); - else next.delete(key); - } - onSelectionChange(next); - }; - const otherSelected = other.filter((candidate) => selectedKeys.has(candidate.key)).length; - - return ( - <> - {repositories.map((group) => ( - - ))} - {other.length > 0 ? ( - -
- 0 && otherSelected < other.length} - onCheckedChange={(checked) => - setKeys( - other.map((candidate) => candidate.key), - checked === true, - ) - } - /> - - - Other folders - - {other.length} {other.length === 1 ? "folder" : "folders"} - - -
- - {other.map((candidate) => ( - setKeys([candidate.key], checked)} - /> - ))} - -
- ) : null} - - ); -} - -function ImportRepositoryGroup({ - group, - selectedKeys, - onToggle, -}: { - readonly group: OnboardingProjectGroup; - readonly selectedKeys: ReadonlySet; - readonly onToggle: (keys: ReadonlyArray, checked: boolean) => void; -}) { - const keys = group.candidates.map((candidate) => candidate.key); - const selectedCount = keys.filter((key) => selectedKeys.has(key)).length; - const single = group.candidates.length === 1; - const only = group.candidates[0]; - if (single && only !== undefined) { - return ( - onToggle([only.key], checked)} - /> - ); - } - return ( - -
- 0 && selectedCount < keys.length} - onCheckedChange={(checked) => onToggle(keys, checked === true)} - /> - - - {group.label} - c.sources))]} - threadCount={group.threadCount} - lastActiveAt={group.lastActiveAt} - /> - -
- - {group.candidates.map((candidate) => ( - onToggle([candidate.key], checked)} - /> - ))} - -
- ); -} - -function ProjectPathText({ - path, - className, -}: { - readonly path: string; - readonly className?: string; -}) { - const { name, parent } = splitOnboardingProjectPath(path); - return ( - - {parent.length > 0 ? {parent} : null} - {name} - - ); -} - -function ImportCandidateRow({ - candidate, - label, - path, - nested = false, - checked, - onCheckedChange, -}: { - readonly candidate: ImportCandidate; - readonly label?: string; - readonly path?: string; - readonly nested?: boolean; - readonly checked: boolean; - readonly onCheckedChange: (checked: boolean) => void; -}) { - return ( - - ); -} - -function ImportRowMeta({ - sources, - threadCount, - lastActiveAt, -}: { - readonly sources: ReadonlyArray<"claudeAgent" | "codex"> | null; - readonly threadCount: number; - readonly lastActiveAt: string | null; -}) { - const relative = lastActiveAt === null ? null : formatRelativeTime(lastActiveAt); - const age = relative === null ? "" : relative.suffix === null ? "now" : relative.value; - return ( - - - {sources?.includes("claudeAgent") ? ( - - - - ) : null} - - - {sources?.includes("codex") ? ( - - - - ) : null} - - {threadCount} - {age} - - ); -} - -function StepShell({ - title, - description, - children, -}: { - readonly title: string; - readonly description?: string; - readonly children?: React.ReactNode; -}) { - return ( - <> -

{title}

- {description ? ( -

{description}

- ) : null} - {children} - - ); -} diff --git a/apps/web/src/components/settings/ImportProjectsDialog.tsx b/apps/web/src/components/settings/ImportProjectsDialog.tsx new file mode 100644 index 0000000000000..1f83e539c98a7 --- /dev/null +++ b/apps/web/src/components/settings/ImportProjectsDialog.tsx @@ -0,0 +1,71 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { useEffect, useState } from "react"; + +import { useProjectScans } from "../../onboarding/useProjectScans"; +import { ProjectImportStep } from "../onboarding/ProjectImportStep"; +import { Dialog, DialogTitle } from "../ui/dialog"; +import { toastManager } from "../ui/toast"; +import { WizardPanel, WizardPopup } from "../ui/wizard"; + +export function ImportProjectsDialog({ + environmentIds, + onClose, +}: { + readonly environmentIds: readonly EnvironmentId[]; + readonly onClose: () => void; +}) { + // Freeze the targets so a reconnect elsewhere does not rescan mid-selection. + const [scanIds] = useState(environmentIds); + const scans = useProjectScans(scanIds); + const [initialScans] = useState(scans); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a cached scan can be up to 30s old on reopen, so rescan once to pick up new conversations; scans already in flight are left alone + useEffect(() => { + for (const scan of initialScans) { + if (scan.data !== null && !scan.isPending) scan.refresh(); + } + }, [initialScans]); + const [isImporting, setIsImporting] = useState(false); + const isLoadingProjects = + scans.every((scan) => scan.data === null) && scans.some((scan) => scan.isPending); + + const finish = async (_projectRef?: unknown, importWarning?: string, importedThreadCount = 0) => { + onClose(); + if (importWarning) { + toastManager.add({ + type: "warning", + title: "Some history was not imported", + description: importWarning, + timeout: 0, + }); + } else if (importedThreadCount > 0) { + toastManager.add({ + type: "success", + title: `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}`, + }); + } + return true; + }; + + return ( + { + if (!open && !isImporting) onClose(); + }} + > + + Import projects + + + + + + ); +} diff --git a/apps/web/src/components/settings/ProjectsSettings.tsx b/apps/web/src/components/settings/ProjectsSettings.tsx index 826c92bca26e3..856e3e52cf992 100644 --- a/apps/web/src/components/settings/ProjectsSettings.tsx +++ b/apps/web/src/components/settings/ProjectsSettings.tsx @@ -1,11 +1,14 @@ -import { EnvironmentId } from "@t3tools/contracts"; -import { LayersIcon } from "lucide-react"; +import { AuthOrchestrationOperateScope, EnvironmentId } from "@t3tools/contracts"; +import { DownloadIcon, LayersIcon } from "lucide-react"; +import { useState } from "react"; +import { useEnvironmentsWithScope } from "../../state/session"; import { Button } from "../ui/button"; +import { ImportProjectsDialog } from "./ImportProjectsDialog"; import { ProjectSettingsPanel } from "./ProjectSettingsPanel"; import { useSettingsScope } from "./SettingsScopeContext"; import { SettingsScopeNotice } from "./SettingsScopeNotice"; -import { SettingsPageContainer } from "./settingsLayout"; +import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { ALL_ENVIRONMENTS_VALUE, selectEnvironmentAxis } from "./settingsScopeAxis"; export function ProjectsSettings() { @@ -46,10 +49,48 @@ export function ProjectsSettings() { ) : unavailable ? ( unavailable ) : ( - - Choose a project to manage its name, icon, checkouts and actions. - + + + + Choose a project to manage its name, icon, checkouts and actions. + + )} ); } + +function ImportProjectsSection() { + const { connectedEnvironments } = useSettingsScope(); + const writableIds = useEnvironmentsWithScope( + connectedEnvironments, + AuthOrchestrationOperateScope, + ); + const environmentIds = connectedEnvironments + .map((environment) => environment.environmentId) + .filter((environmentId) => writableIds.has(environmentId)); + const [open, setOpen] = useState(false); + return ( + + setOpen(true)} + > + + Import projects + + } + /> + {open ? ( + setOpen(false)} /> + ) : null} + + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 07d1d5dd6c8b9..4251c0e7c3637 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -205,6 +205,11 @@ describe("settings search targets", () => { expect(isSettingsSearchScopeAvailable(updates.scope, "environment")).toBe(true); expect(isSettingsSearchScopeAvailable(updates.scope, "all")).toBe(true); expect(isSettingsSearchScopeAvailable(updates.scope, "project")).toBe(false); + // The import row only renders while no project is selected. + const importProjects = getSettingsSearchTargetScope("import-projects")!; + expect(isSettingsSearchScopeAvailable(importProjects.scope, "all")).toBe(true); + expect(isSettingsSearchScopeAvailable(importProjects.scope, "environment")).toBe(true); + expect(isSettingsSearchScopeAvailable(importProjects.scope, "project")).toBe(false); const streaming = getSettingsSearchTargetScope("response-streaming")!; expect(streaming.scope).toBe("project-defaults"); expect(isSettingsSearchScopeAvailable(streaming.scope, "project")).toBe(true); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index dc494caf5344d..51dd666cf6ac2 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -269,6 +269,13 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/projects", searchTerms: ["name icon emoji image checkout remove delete"], }, + { + id: "import-projects", + title: "Import from Claude Code and Codex", + to: "/settings/projects", + scope: "environment-defaults", + searchTerms: ["import projects threads conversations history sessions transcripts"], + }, { id: "default-model", title: "Default model", diff --git a/docs/user/welcome-wizard.md b/docs/user/welcome-wizard.md index d4604fa7e6668..827515aaebb03 100644 --- a/docs/user/welcome-wizard.md +++ b/docs/user/welcome-wizard.md @@ -93,5 +93,9 @@ with up to 100,000 input records. Run import again to continue a large batch. Completed conversations are not imported again. You can continue without the remaining history. +To import later, or to pick up newer conversations, open **Settings → Projects** +and choose **Import projects**. It scans the connected computers in the current +settings scope. + You can continue without configuring agents or importing projects, or return to an earlier step using the setup progress bar. Navigation pauses while an import is running.