From 5988af8179245c189a4becc2dcf65d73a681abae Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Fri, 14 Aug 2026 17:27:15 -0700 Subject: [PATCH] fix: address review batch on scanner accuracy, wizard targeting, and a11y MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Scanner: cwd is read from every complete line in the transcript prefix (Claude often opens with cwd-less records); alreadyImported compares with normalizeProjectPathForComparison against one shell snapshot instead of exact-match lookups. Wizard: remote paths target the machine the user just connected instead of the local primary — agent probes, terminal, keybindings, and import all follow it; per-driver cards pick the most usable instance; probes still pending show Checking instead of an Install button; import retries skip already-landed paths and the chooser resets on target switch; an unmount during an in-flight terminal open now reaps the created PTY; copy falls back when the Clipboard API is missing (plain-HTTP LAN). FirstRunGate: freshness is judged only against primary-environment state, so a saved remote's project can't masquerade as the cwd bootstrap. UI consistency: connection cards expose aria-pressed and a focus ring, ready status uses success tokens, the back control is the Button primitive. Co-Authored-By: Claude Fable 5 --- .../src/project/AgentSessionScanner.test.ts | 49 +++-- .../server/src/project/AgentSessionScanner.ts | 69 +++++--- .../components/onboarding/FirstRunGate.tsx | 13 +- .../components/onboarding/WelcomeWizard.tsx | 167 +++++++++++++----- docs/user/welcome-wizard.md | 5 +- 5 files changed, 219 insertions(+), 84 deletions(-) diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 78f651ed69..8f89d34fd9 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1,10 +1,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; -import { type OrchestrationProject, ProjectId } from "@t3tools/contracts"; +import { type OrchestrationProjectShell, ProjectId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; @@ -12,7 +11,7 @@ import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSn import * as ServerSettings from "../serverSettings.ts"; import * as AgentSessionScanner from "./AgentSessionScanner.ts"; -const makeProject = (workspaceRoot: string): OrchestrationProject => ({ +const makeProjectShell = (workspaceRoot: string): OrchestrationProjectShell => ({ id: ProjectId.make("project-1"), title: "Imported", workspaceRoot, @@ -20,24 +19,24 @@ const makeProject = (workspaceRoot: string): OrchestrationProject => ({ scripts: [], createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", - deletedAt: null, }); -/** Only `getActiveProjectByWorkspaceRoot` is exercised; the rest must not be called. */ +/** Only `getShellSnapshot` is exercised; the rest must not be called. */ const makeProjectionSnapshotQueryLayer = (importedWorkspaceRoots: ReadonlyArray) => Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { getCommandReadModel: () => Effect.die("unused"), getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), + getShellSnapshot: () => + Effect.succeed({ + snapshotSequence: 0, + projects: importedWorkspaceRoots.map((workspaceRoot) => makeProjectShell(workspaceRoot)), + threads: [], + updatedAt: "2026-01-01T00:00:00.000Z", + }), getArchivedShellSnapshot: () => Effect.die("unused"), getSnapshotSequence: () => Effect.die("unused"), getCounts: () => Effect.die("unused"), - getActiveProjectByWorkspaceRoot: (workspaceRoot) => - Effect.succeed( - importedWorkspaceRoots.includes(workspaceRoot) - ? Option.some(makeProject(workspaceRoot)) - : Option.none(), - ), + getActiveProjectByWorkspaceRoot: () => Effect.die("unused"), getProjectShellById: () => Effect.die("unused"), getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), getThreadCheckpointContext: () => Effect.die("unused"), @@ -347,6 +346,32 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("finds the cwd on a later line when the first records carry none", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + + // Claude transcripts often open with records that have no cwd. + const contents = [ + JSON.stringify({ type: "file-history-snapshot", messageId: "m1" }), + JSON.stringify({ type: "queue-operation", operation: "enqueue" }), + JSON.stringify({ type: "user", cwd: workspace, sessionId: "s1" }), + "", + ].join("\n"); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents, + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath }); + + expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]); + }), + ); + 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 bb7718265f..98f1606196 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -29,6 +29,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import * as ServerConfig from "../config.ts"; import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; @@ -155,32 +156,40 @@ export const make = Effect.gen(function* () { fileSystem.stat(target).pipe(Effect.map(Option.some), Effect.orElseSucceed(Option.none)); /** - * Read the head of a transcript and return its first complete line. Returns - * `null` when the file is unreadable or its first line exceeds the prefix. + * Read the head of a transcript and return its complete lines. Returns an + * empty list when the file is unreadable; a trailing partial line (cut by + * the prefix cap) is dropped rather than parsed as truncated JSON. */ - const readFirstLine = Effect.fn("AgentSessionScanner.readFirstLine")(function* ( + const readHeadLines = Effect.fn("AgentSessionScanner.readHeadLines")(function* ( filePath: string, - ): Effect.fn.Return { + ): Effect.fn.Return> { const prefix = yield* Effect.scoped( fileSystem .open(filePath, { flag: "r" }) .pipe(Effect.flatMap((file) => file.readAlloc(TRANSCRIPT_PREFIX_BYTES))), ).pipe(Effect.orElseSucceed(Option.none)); - if (Option.isNone(prefix)) return null; + if (Option.isNone(prefix)) return []; const text = decoder.decode(prefix.value); - const newlineIndex = text.indexOf("\n"); - if (newlineIndex === -1) { - // Either a single-line file smaller than the prefix, or a first record - // too large to trust as complete JSON. - return prefix.value.length < TRANSCRIPT_PREFIX_BYTES ? text : null; + const lines = text.split("\n"); + // A prefix-capped read may end mid-line; only a file smaller than the cap + // is guaranteed to have a complete final line. + if (prefix.value.length >= TRANSCRIPT_PREFIX_BYTES) { + lines.pop(); } - return text.slice(0, newlineIndex); + return lines; }); + // Transcripts often open with records that carry no cwd (Claude writes + // file-history snapshots and queue operations first), so scan every + // complete line in the prefix for the first one that names a directory. const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (filePath: string) { - const line = yield* readFirstLine(filePath); - return line === null ? null : extractCwd(line.trim()); + const lines = yield* readHeadLines(filePath); + for (const line of lines) { + const cwd = extractCwd(line.trim()); + if (cwd !== null) return cwd; + } + return null; }); const latestMtimeMs = Effect.fn("AgentSessionScanner.latestMtimeMs")(function* ( @@ -404,25 +413,29 @@ export const make = Effect.gen(function* () { : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs); } + // One snapshot read, compared with the same normalization the + // project.create invariant uses, so a root that differs only by case or + // separators is still recognized as imported. + const shellSnapshot = yield* projectionSnapshotQuery + .getShellSnapshot() + .pipe( + Effect.mapError( + (cause) => new AgentSessionScanError({ operation: "read-projects", cause }), + ), + ); + const importedRoots = new Set( + shellSnapshot.projects.map((project) => + normalizeProjectPathForComparison(project.workspaceRoot), + ), + ); + const candidates: Array = []; 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 AgentSessionScanError({ operation: "read-projects", cause }), - ), - ); - if (Option.isSome(existingProject)) { - alreadyImported = true; - break; - } - } + const alreadyImported = + importedRoots.has(normalizeProjectPathForComparison(entry.path)) || + importedRoots.has(normalizeProjectPathForComparison(key)); candidates.push({ path: entry.path, title: path.basename(entry.path) || entry.path, diff --git a/apps/web/src/components/onboarding/FirstRunGate.tsx b/apps/web/src/components/onboarding/FirstRunGate.tsx index 6d4b13b269..0f35122232 100644 --- a/apps/web/src/components/onboarding/FirstRunGate.tsx +++ b/apps/web/src/components/onboarding/FirstRunGate.tsx @@ -57,10 +57,19 @@ export function FirstRunGate({ // own cwd auto-bootstrap: web mode creates a project + thread from cwd at // startup (`autoBootstrapProjectFromCwd` defaults on there), so "no // projects at all" would mean `npx t3` users never see the wizard. Any - // other project, or more than one thread, is real user state. + // other project, more than one thread, or state in a non-primary + // environment is real user state — the aggregate hooks span every + // environment, and a saved remote's project must never read as "the + // bootstrap project" just because its root string matches the primary cwd. const serverCwd = serverConfig?.cwd ?? null; + const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null; const workspaceFresh = - projects.every((project) => project.workspaceRoot === serverCwd) && threads.length <= 1; + projects.every( + (project) => + project.environmentId === primaryEnvironmentId && project.workspaceRoot === serverCwd, + ) && + threads.length <= 1 && + threads.every((thread) => thread.environmentId === primaryEnvironmentId); useEffect(() => { if (decision !== "pending" || !hydrated) return; diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx index 791cf24149..2ebf7b33d7 100644 --- a/apps/web/src/components/onboarding/WelcomeWizard.tsx +++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx @@ -27,7 +27,9 @@ import { agentSessionScan } from "../../state/agentSessions"; import { useEnvironments, usePrimaryEnvironment } from "../../state/environments"; import { useEnvironmentQuery } from "../../state/query"; import { projectEnvironment } from "../../state/projects"; -import { primaryServerKeybindingsAtom, serverEnvironment } from "../../state/server"; +import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; + +import { serverEnvironment } from "../../state/server"; import { terminalEnvironment } from "../../state/terminal"; import { useAtomCommand } from "../../state/use-atom-command"; import { connectPairing } from "../../connection/onboarding"; @@ -51,20 +53,33 @@ import { cn } from "../../lib/utils"; type WizardStep = "connection" | "connect-machines" | "pair-direct" | "agents" | "import"; +type ConnectionMode = "local" | "connect" | "direct"; + /** - * The machine the agent and import steps run against: the primary environment - * when it's connected, otherwise the first connected environment (the remote - * paths on web/hosted have no primary). Deliberately not a persisted "primary - * machine" concept — just whichever machine is reachable right now, labeled - * inline on each step. + * The machine the agent and import steps run against. Local mode targets the + * primary environment; the remote modes prefer the machine the user just + * connected (the most recently added connected non-primary environment), so + * probing and import happen where their code lives rather than on the local + * server that happens to serve the app. Deliberately not a persisted + * "primary machine" concept — just whichever machine fits the chosen path + * right now, labeled inline on each step. */ -function useOnboardingTargetEnvironment() { +function useOnboardingTargetEnvironment(mode: ConnectionMode) { const { environments } = useEnvironments(); const primaryEnvironment = usePrimaryEnvironment(); + const connectedRemotes = environments.filter( + (environment) => + environment.connection.phase === "connected" && + environment.entry.target._tag !== "PrimaryConnectionTarget", + ); + if (mode !== "local" && connectedRemotes.length > 0) { + // Registry order is append-order, so the last entry is the newest link. + return connectedRemotes[connectedRemotes.length - 1] ?? null; + } if (primaryEnvironment !== null && primaryEnvironment.connection.phase === "connected") { return primaryEnvironment; } - return environments.find((environment) => environment.connection.phase === "connected") ?? null; + return connectedRemotes[0] ?? null; } const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup"); @@ -85,6 +100,7 @@ export function WelcomeWizard({ }) { const completeOnboarding = useCompleteOnboarding(); const [step, setStep] = useState("connection"); + const [mode, setMode] = useState("local"); const finish = useCallback(() => { completeOnboarding(); onDone(); @@ -105,9 +121,18 @@ export function WelcomeWizard({ {step === "connection" ? ( setStep("agents")} - onConnect={() => setStep("connect-machines")} - onDirect={() => setStep("pair-direct")} + onLocal={() => { + setMode("local"); + setStep("agents"); + }} + onConnect={() => { + setMode("connect"); + setStep("connect-machines"); + }} + onDirect={() => { + setMode("direct"); + setStep("pair-direct"); + }} /> ) : step === "connect-machines" ? ( setStep("connection")} onPaired={() => setStep("agents")} /> ) : step === "agents" ? ( - setStep("import")} onSkip={() => setStep("import")} /> + setStep("import")} + onSkip={() => setStep("import")} + /> ) : ( - + )} @@ -208,9 +237,11 @@ function ConnectionCard({ return ( + ) : null}

{ + if (navigator.clipboard !== undefined) { + void navigator.clipboard.writeText(command); + } else { + const scratch = document.createElement("textarea"); + scratch.value = command; + document.body.append(scratch); + scratch.select(); + document.execCommand("copy"); + scratch.remove(); + } + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + }; return (
$ {command} -
diff --git a/docs/user/welcome-wizard.md b/docs/user/welcome-wizard.md index 6a9872720c..e4ba84a769 100644 --- a/docs/user/welcome-wizard.md +++ b/docs/user/welcome-wizard.md @@ -31,5 +31,6 @@ have already run and offers them as projects. The default imports projects active in the last 30 days; **Choose** lists everything found. Imports create projects only — thread history import is coming later. -Every step after the connection choice can be skipped. Projects can always be -added later from the command palette. +The agent and import steps can be skipped, and the remote paths offer Back to +choose a different connection. Projects can always be added later from the +command palette.