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 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-08-04 14:49:20 -07:00
1 parent 3905ec8321
commit 6378909671
8 files changed
+153 -52

No files matched your search

@@ -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<string>;
/** 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 `<baseDir>/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;
+41 -21
View File
@@ -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
* `<t3-home>/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<string> => []));
@@ -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<AgentSessionProjectCandidate> = [];
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,
});
}
+1 -2
View File
@@ -1709,8 +1709,7 @@ const makeWsRpcLayer = (
Effect.mapError(
(cause) =>
new AgentSessionScanError({
failure: "scan_failed",
message: cause.message,
operation: cause.operation,
cause,
}),
),
@@ -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<FirstRunDecision>(() =>
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;
@@ -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 <StepShell title="Sign in to T3 Connect" onBack={onBack} />;
@@ -317,9 +322,14 @@ function ConnectMachinesStep({
}
/>
</div>
<div className="mt-6 flex items-center justify-end gap-3">
<span className="text-xs text-muted-foreground">Waiting for a machine…</span>
<Button disabled>Continue</Button>
<div className="mt-6 flex items-center justify-between">
<Button variant="ghost" onClick={onContinue}>
Skip for now
</Button>
<div className="flex items-center gap-3">
<span className="text-xs text-muted-foreground">Waiting for a machine…</span>
<Button disabled>Continue</Button>
</div>
</div>
</>
)}
@@ -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 (
<div
@@ -598,6 +613,8 @@ function AgentCard({
<CheckIcon className="size-3.5" />
Ready
</span>
) : disabled ? (
<span className="text-xs text-muted-foreground">Enable in Settings</span>
) : (
<Button size="xs" variant="outline" onClick={onOpenTerminal} disabled={terminalOpen}>
<TerminalIcon className="size-3.5" />
@@ -646,13 +663,16 @@ function AgentInstallTerminal({
useEffect(() => {
if (preparedRef.current || cwd === null) return;
preparedRef.current = true;
void (async () => {
const opened = await openTerminal({
environmentId,
input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, cwd },
});
if (opened._tag !== "Success" || command.length === 0) return;
// Only a successful open ends the attempts, so a transient RPC failure
// retries on the next render instead of leaving a dead terminal.
if (opened._tag !== "Success") return;
preparedRef.current = true;
if (command.length === 0) return;
// Pre-type without the trailing carriage return; the user submits.
await writeTerminal({
environmentId,
@@ -759,8 +779,12 @@ function ImportStep({ onDone }: { readonly onDone: () => void }) {
}
}
setIsImporting(false);
if (failures > 0 && failures === selection.length) {
setImportError("Import failed. You can add projects manually from the command palette.");
if (failures > 0) {
setImportError(
failures === selection.length
? "Import failed. You can add projects manually from the command palette."
: `Imported ${selection.length - failures} of ${selection.length} projects. The rest can be added from the command palette.`,
);
return;
}
onDone();
+1 -1
View File
@@ -144,7 +144,7 @@ function RootRouteView() {
<AnchoredToastProvider>
<DocumentTitleSync />
<GlassAppearanceSync />
<FirstRunGate>
<FirstRunGate enabled={primaryEnvironmentAuthenticated}>
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
<RelayClientInstallDialog />
<ConnectOnboardingDialog />
+5 -4
View File
@@ -1,7 +1,7 @@
# Welcome Wizard
On a fresh install, T3 Code opens a short setup flow before the main app.
Existing installs never see it.
Installs with existing projects or completed onboarding skip it.
## Choose how to connect
@@ -18,9 +18,10 @@ Existing installs never see it.
The wizard checks the connected machine for Claude Code and Codex and shows
their install and sign-in status. If one is missing, an inline terminal opens
with the install command pre-typed — press Enter to run it, then complete the
CLI's own sign-in in the same terminal. Other supported agents are configured
in Settings → Providers.
with the install command pre-typed — press Enter to run it. It's a real shell,
so you can run the CLI's sign-in there too, or use the card's **Sign in**
action after the install finishes. Other supported agents are configured in
Settings → Providers.
## Import your projects
+6 -6
View File
@@ -33,14 +33,14 @@ export const AgentSessionScanResult = Schema.Struct({
});
export type AgentSessionScanResult = typeof AgentSessionScanResult.Type;
export const AgentSessionScanFailure = Schema.Literals(["scan_failed"]);
export type AgentSessionScanFailure = typeof AgentSessionScanFailure.Type;
export class AgentSessionScanError extends Schema.TaggedErrorClass<AgentSessionScanError>()(
"AgentSessionScanError",
{
failure: AgentSessionScanFailure,
message: TrimmedNonEmptyString,
operation: Schema.Literals(["read-settings", "read-projects"]),
cause: Schema.optional(Schema.Defect()),
},
) {}
) {
override get message(): string {
return `Failed to scan agent sessions during ${this.operation}.`;
}
}