From 6378909671c433810ea9497fef7a0e33d266ae91 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 4 Aug 2026 14:49:20 -0700 Subject: [PATCH] fix: address review findings on onboarding scanner and wizard - Scanner: expand ~ in CLAUDE_CONFIG_DIR; sort transcripts by mtime before applying the per-source cap; check alreadyImported against both recorded and realpath spellings; derive the worktree-sandbox filter from the configured worktreesDir instead of hard-coding .t3 - Contracts: AgentSessionScanError carries the structural operation discriminator and derives its message (drops redundant failure literal) - FirstRunGate: require server config before judging workspace freshness (fixes both the offline-install-sees-wizard and config-race cases); only gate authenticated sessions - Wizard: T3 Connect "connected" view requires a live connection; the no-machine wait gets a Skip; partial import failures keep the step open and report the count; disabled providers show "Enable in Settings" instead of Ready/Install; failed terminal opens retry - Docs: match actual first-run and terminal sign-in behavior Co-Authored-By: Claude Fable 5 --- .../src/project/AgentSessionScanner.test.ts | 32 ++++++++++ .../server/src/project/AgentSessionScanner.ts | 62 ++++++++++++------- apps/server/src/ws.ts | 3 +- .../components/onboarding/FirstRunGate.tsx | 39 +++++++++--- .../components/onboarding/WelcomeWizard.tsx | 46 ++++++++++---- apps/web/src/routes/__root.tsx | 2 +- docs/user/welcome-wizard.md | 9 +-- packages/contracts/src/agentSessions.ts | 12 ++-- 8 files changed, 153 insertions(+), 52 deletions(-) diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 1c912b5dfa..bdbbfbdc66 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -7,6 +7,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as ServerConfig from "../config.ts"; import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as AgentSessionScanner from "./AgentSessionScanner.ts"; @@ -55,6 +56,8 @@ const runScan = (input: { readonly claudeHomePath: string; readonly codexHomePath: string; readonly importedWorkspaceRoots?: ReadonlyArray; + /** Base dir for the test ServerConfig; worktreesDir derives from it. */ + readonly configBaseDir?: string; }) => Effect.gen(function* () { const scanner = yield* AgentSessionScanner.AgentSessionScanner; @@ -70,6 +73,10 @@ const runScan = (input: { codex: { homePath: input.codexHomePath }, }, }), + ServerConfig.layerTest( + input.claudeHomePath, + input.configBaseDir ?? { prefix: "t3code-scanner-config-" }, + ), makeProjectionSnapshotQueryLayer(input.importedWorkspaceRoots ?? []), ), ), @@ -288,6 +295,31 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("excludes sandboxes under the configured worktrees dir without .t3 in the path", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const configBaseDir = yield* makeTempDir("t3code-scanner-base-"); + const fileSystem = yield* FileSystem.FileSystem; + + // worktreesDir derives as `/worktrees`, and the temp base + // dir contains no `.t3` segment — only the config-based prefix match + // can exclude this one. + const worktreeCwd = path.join(configBaseDir, "worktrees", "t3code", "wt-2"); + yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true }); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents: claudeSessionLine(worktreeCwd), + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); + + expect(result.candidates).toEqual([]); + }), + ); + it.effect("skips malformed transcripts without failing the scan", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index aeaae05b10..dd78482f8a 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -25,6 +25,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as ServerConfig from "../config.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { expandHomePath } from "../pathExpansion.ts"; @@ -81,12 +82,18 @@ interface RawCandidate { const decoder = new TextDecoder(); /** - * T3 Code runs its own agent sessions inside disposable worktrees under - * `/worktrees/`. Their transcripts look exactly like user sessions, - * but re-importing the app's own sandboxes as projects is never right. + * T3 Code runs its own agent sessions inside disposable worktrees. Their + * transcripts look exactly like user sessions, but re-importing the app's own + * sandboxes as projects is never right. Matches this server's configured + * worktrees directory plus the conventional `.t3/worktrees` layout, which + * also catches sandboxes from other T3 homes on the same machine. */ -function isT3ManagedWorktree(resolvedPath: string): boolean { - return /[/\\]\.t3[/\\]worktrees[/\\]/.test(`${resolvedPath}/`); +function isT3ManagedWorktree(resolvedPath: string, worktreesDir: string): boolean { + const withSeparator = `${resolvedPath}/`; + return ( + withSeparator.startsWith(`${worktreesDir}/`) || + /[/\\]\.t3[/\\]worktrees[/\\]/.test(withSeparator) + ); } /** Extract `cwd` from a session-meta record, tolerating the shapes each CLI writes. */ @@ -114,11 +121,13 @@ function extractCwd(line: string): string | null { return null; } -const make = Effect.gen(function* () { +export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const serverConfig = yield* ServerConfig.ServerConfig; const serverSettings = yield* ServerSettings.ServerSettingsService; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const worktreesDir = path.resolve(serverConfig.worktreesDir); const listDirectory = (directory: string) => fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); @@ -185,7 +194,7 @@ const make = Effect.gen(function* () { } const fromEnvironment = process.env.CLAUDE_CONFIG_DIR?.trim() ?? ""; if (fromEnvironment.length > 0) { - return path.resolve(fromEnvironment); + return path.resolve(expandHomePath(fromEnvironment)); } return path.join(NodeOS.homedir(), ".claude"); }; @@ -210,16 +219,17 @@ const make = Effect.gen(function* () { .map((entry) => path.join(directory, entry)); if (transcripts.length === 0) continue; - const inspected = transcripts.slice(0, budget); - budget -= inspected.length; - + // Stat everything, then spend the budget newest-first, so the cap only + // ever drops the oldest transcripts. const withMtimes: Array<{ filePath: string; mtimeMs: number }> = []; - for (const filePath of inspected) { + for (const filePath of transcripts) { const stats = yield* statOption(filePath); if (Option.isNone(stats) || Option.isNone(stats.value.mtime)) continue; withMtimes.push({ filePath, mtimeMs: stats.value.mtime.value.getTime() }); } withMtimes.sort((left, right) => right.mtimeMs - left.mtimeMs); + withMtimes.splice(budget); + budget -= withMtimes.length; // The newest transcript is the most likely to still name a live path. let cwd: string | null = null; @@ -326,7 +336,7 @@ const make = Effect.gen(function* () { for (const candidate of raw) { const resolved = path.resolve(expandHomePath(candidate.cwd.trim())); - if (isT3ManagedWorktree(resolved)) continue; + if (isT3ManagedWorktree(resolved, worktreesDir)) continue; let key = realPathKeys.get(resolved); if (key === undefined) { const stats = yield* statOption(resolved); @@ -361,14 +371,24 @@ const make = Effect.gen(function* () { } const candidates: Array = []; - for (const entry of merged.values()) { - const existingProject = yield* projectionSnapshotQuery - .getActiveProjectByWorkspaceRoot(entry.path) - .pipe( - Effect.mapError( - (cause) => new AgentSessionScanFailedError({ operation: "read-projects", cause }), - ), - ); + for (const [key, entry] of merged.entries()) { + // Projects may have been created under either the recorded spelling or + // the resolved realpath (e.g. a symlinked home) — check both. + const lookupPaths = key === entry.path ? [entry.path] : [entry.path, key]; + let alreadyImported = false; + for (const lookupPath of lookupPaths) { + const existingProject = yield* projectionSnapshotQuery + .getActiveProjectByWorkspaceRoot(lookupPath) + .pipe( + Effect.mapError( + (cause) => new AgentSessionScanFailedError({ operation: "read-projects", cause }), + ), + ); + if (Option.isSome(existingProject)) { + alreadyImported = true; + break; + } + } candidates.push({ path: entry.path, title: path.basename(entry.path) || entry.path, @@ -378,7 +398,7 @@ const make = Effect.gen(function* () { entry.lastActiveAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)), - alreadyImported: Option.isSome(existingProject), + alreadyImported, }); } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 8e4b3a5258..0172130106 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1709,8 +1709,7 @@ const makeWsRpcLayer = ( Effect.mapError( (cause) => new AgentSessionScanError({ - failure: "scan_failed", - message: cause.message, + operation: cause.operation, cause, }), ), diff --git a/apps/web/src/components/onboarding/FirstRunGate.tsx b/apps/web/src/components/onboarding/FirstRunGate.tsx index 3582ce1172..21edce7123 100644 --- a/apps/web/src/components/onboarding/FirstRunGate.tsx +++ b/apps/web/src/components/onboarding/FirstRunGate.tsx @@ -28,7 +28,18 @@ const FIRST_RUN_DECISION_TIMEOUT_MS = 4_000; type FirstRunDecision = "pending" | "app" | "wizard"; -export function FirstRunGate({ children }: { readonly children: React.ReactNode }) { +export function FirstRunGate({ + enabled, + children, +}: { + /** + * Only an authenticated primary-server session gates. Hosted-static has no + * primary server config to inspect and its empty state handles onboarding + * itself; gating it would just add a decision timeout to every load. + */ + readonly enabled: boolean; + readonly children: React.ReactNode; +}) { const navigate = useNavigate(); const hydrated = useClientSettingsHydrated(); const onboardingCompletedAt = useClientSettings((settings) => settings.onboardingCompletedAt); @@ -39,7 +50,7 @@ export function FirstRunGate({ children }: { readonly children: React.ReactNode // Within a session settings stay hydrated, so remounts (e.g. returning from // the wizard) resolve synchronously instead of blanking a frame. const [decision, setDecision] = useState(() => - hydrated && onboardingCompletedAt !== null ? "app" : "pending", + !enabled || (hydrated && onboardingCompletedAt !== null) ? "app" : "pending", ); // A workspace still counts as fresh when its only content is the server's @@ -49,18 +60,32 @@ export function FirstRunGate({ children }: { readonly children: React.ReactNode // other project, or more than one thread, is real user state. const serverCwd = serverConfig?.cwd ?? null; const workspaceFresh = - projects.every((project) => serverCwd !== null && project.workspaceRoot === serverCwd) && - threads.length <= 1; + projects.every((project) => project.workspaceRoot === serverCwd) && threads.length <= 1; useEffect(() => { if (decision !== "pending" || !hydrated) return; - if (onboardingCompletedAt !== null) { + if (!enabled || onboardingCompletedAt !== null) { setDecision("app"); return; } - if (!bootstrapped) return; + // Both shells AND the server config must be in before the workspace can + // be judged: shells bootstrap and config load independently, and a + // disconnected environment reports bootstrapped with empty projections. + // Without the config a fresh cwd-bootstrapped install would read as + // non-fresh (projects but no cwd yet), and an offline existing install + // would read as fresh (nothing at all). Config never arriving means the + // timeout below falls back to the app. + if (!bootstrapped || serverConfig === null) return; setDecision(workspaceFresh ? "wizard" : "app"); - }, [bootstrapped, decision, hydrated, onboardingCompletedAt, workspaceFresh]); + }, [ + bootstrapped, + decision, + enabled, + hydrated, + onboardingCompletedAt, + serverConfig, + workspaceFresh, + ]); useEffect(() => { if (decision !== "pending") return; diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx index bd552a5154..3e584606bd 100644 --- a/apps/web/src/components/onboarding/WelcomeWizard.tsx +++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx @@ -252,7 +252,12 @@ function ConnectMachinesStep({ const savedEnvironments = environments.filter( (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget", ); - const hasRemoteMachines = savedEnvironments.length > 0; + // Only a live connection counts: a saved-but-offline machine must not show + // the "connected" confirmation (the agents step would find nothing to + // probe). Its row still renders in the list either way. + const hasRemoteMachines = savedEnvironments.some( + (environment) => environment.connection.phase === "connected", + ); if (!isLoaded) { return ; @@ -317,9 +322,14 @@ function ConnectMachinesStep({ } /> -
- Waiting for a machine… - +
+ +
+ Waiting for a machine… + +
)} @@ -501,7 +511,8 @@ function ConnectedAgentsStep({ provider: byDriver.get(driver), })); const readyCount = primaryAgents.filter( - ({ provider }) => provider?.installed && provider.auth.status === "authenticated", + ({ provider }) => + provider?.enabled === true && provider.installed && provider.auth.status === "authenticated", ).length; const otherAgents = [...byDriver.keys()].filter( (driver) => !PRIMARY_AGENT_DRIVERS.includes(driver as (typeof PRIMARY_AGENT_DRIVERS)[number]), @@ -574,8 +585,12 @@ function AgentCard({ const Icon = meta?.icon; const displayName = driver === "claudeAgent" ? "Claude Code" : (meta?.label ?? driver); const summary = getProviderSummary(provider); - const ready = provider?.installed === true && provider.auth.status === "authenticated"; - const needsLogin = provider?.installed === true && provider.auth.status !== "authenticated"; + // A provider disabled in settings is neither ready nor installable from + // here; the summary already reads "Disabled" and the card offers no action. + const disabled = provider !== undefined && !provider.enabled; + const usable = provider?.enabled === true && provider.installed; + const ready = usable && provider.auth.status === "authenticated"; + const needsLogin = usable && provider.auth.status !== "authenticated"; return (
Ready + ) : disabled ? ( + Enable in Settings ) : (