feat(web): first-run welcome wizard with agent setup and project import
New onboarding flow for fresh installs: choose how to connect (Local Only / T3 Connect / Direct), verify Claude Code and Codex with live probe status and an inline install terminal, then import existing projects discovered from Claude/Codex home directories. - FirstRunGate at the root holds back the entire authenticated tree until the first-run decision is known, so fresh installs see nothing before /welcome (no shell flash, no EventRouter thread navigation) - New read-only agentSessions.scan RPC discovers project candidates from ~/.claude/projects and Codex session rollouts (cwd from transcript first lines, never the lossy dir slug; T3-managed worktrees excluded) - Import creates projects via existing project.create dispatch; default window is last 30 days, full checklist behind Choose - onboardingCompletedAt client setting gates the wizard; installs that predate the field only qualify when the workspace is fresh Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
d7950ac153
commit
3905ec8321
17 files changed
+2047
-9
No files matched your search
@@ -60,6 +60,7 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { type OrchestrationProject, 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 ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as AgentSessionScanner from "./AgentSessionScanner.ts";
|
||||
|
||||
const makeProject = (workspaceRoot: string): OrchestrationProject => ({
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Imported",
|
||||
workspaceRoot,
|
||||
defaultModelSelection: null,
|
||||
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. */
|
||||
const makeProjectionSnapshotQueryLayer = (importedWorkspaceRoots: ReadonlyArray<string>) =>
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
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(),
|
||||
),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
searchThreads: () => Effect.die("unused"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Run a scan against the given homes. Homes are temp dirs created inside the
|
||||
* test, so the layer is built per run rather than shared.
|
||||
*/
|
||||
const runScan = (input: {
|
||||
readonly claudeHomePath: string;
|
||||
readonly codexHomePath: string;
|
||||
readonly importedWorkspaceRoots?: ReadonlyArray<string>;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const scanner = yield* AgentSessionScanner.AgentSessionScanner;
|
||||
return yield* scanner.scan;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentSessionScanner.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
ServerSettings.layerTest({
|
||||
providers: {
|
||||
claudeAgent: { homePath: input.claudeHomePath },
|
||||
codex: { homePath: input.codexHomePath },
|
||||
},
|
||||
}),
|
||||
makeProjectionSnapshotQueryLayer(input.importedWorkspaceRoots ?? []),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.fn("AgentSessionScanner.test.makeTempDir")(function* (prefix: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
||||
});
|
||||
|
||||
const writeTranscript = Effect.fn("AgentSessionScanner.test.writeTranscript")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly contents: string;
|
||||
/** Epoch millis, so ordering assertions never depend on write timing. */
|
||||
readonly mtimeMs: number;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fileSystem.makeDirectory(path.dirname(input.filePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(input.filePath, input.contents);
|
||||
// Numeric utimes arguments are seconds, not milliseconds.
|
||||
const seconds = input.mtimeMs / 1000;
|
||||
yield* fileSystem.utimes(input.filePath, seconds, seconds);
|
||||
});
|
||||
|
||||
/** Claude session line: the first record carries the real `cwd`. */
|
||||
const claudeSessionLine = (cwd: string) =>
|
||||
`${JSON.stringify({ type: "user", cwd, sessionId: "s1" })}\n${JSON.stringify({ type: "assistant" })}\n`;
|
||||
|
||||
/** Codex rollout line: session metadata is nested under `payload`. */
|
||||
const codexRolloutLine = (cwd: string) =>
|
||||
`${JSON.stringify({ timestamp: "2026-01-01T00:00:00.000Z", type: "session_meta", payload: { id: "r1", cwd } })}\n`;
|
||||
|
||||
it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
|
||||
describe("scan", () => {
|
||||
it.effect("reads Claude project cwds from transcripts, newest first", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
|
||||
const codexHomePath = yield* makeTempDir("t3code-codex-home-");
|
||||
const olderWorkspace = yield* makeTempDir("t3code-workspace-older-");
|
||||
const newerWorkspace = yield* makeTempDir("t3code-workspace-newer-");
|
||||
|
||||
// Slugs are intentionally lossy; the scanner must not decode them.
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-slug-older", "a.jsonl"),
|
||||
contents: claudeSessionLine(olderWorkspace),
|
||||
mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
|
||||
});
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-slug-older", "b.jsonl"),
|
||||
contents: claudeSessionLine(olderWorkspace),
|
||||
mtimeMs: Date.parse("2026-01-02T00:00:00.000Z"),
|
||||
});
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-slug-newer", "c.jsonl"),
|
||||
contents: claudeSessionLine(newerWorkspace),
|
||||
mtimeMs: Date.parse("2026-03-01T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
const result = yield* runScan({ claudeHomePath, codexHomePath });
|
||||
|
||||
expect(result.candidates).toEqual([
|
||||
{
|
||||
path: newerWorkspace,
|
||||
title: path.basename(newerWorkspace),
|
||||
sources: ["claudeAgent"],
|
||||
threadCount: 1,
|
||||
lastActiveAt: "2026-03-01T00:00:00.000Z",
|
||||
alreadyImported: false,
|
||||
},
|
||||
{
|
||||
path: olderWorkspace,
|
||||
title: path.basename(olderWorkspace),
|
||||
sources: ["claudeAgent"],
|
||||
threadCount: 2,
|
||||
lastActiveAt: "2026-01-02T00:00:00.000Z",
|
||||
alreadyImported: false,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("groups Codex rollouts by cwd across date directories", () =>
|
||||
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-");
|
||||
const otherWorkspace = yield* makeTempDir("t3code-workspace-other-");
|
||||
|
||||
const rollout = (year: string, month: string, day: string, name: string) =>
|
||||
path.join(codexHomePath, "sessions", year, month, day, name);
|
||||
|
||||
yield* writeTranscript({
|
||||
filePath: rollout("2026", "01", "05", "rollout-2026-01-05T10-00-00-aaa.jsonl"),
|
||||
contents: codexRolloutLine(workspace),
|
||||
mtimeMs: Date.parse("2026-01-05T10:00:00.000Z"),
|
||||
});
|
||||
yield* writeTranscript({
|
||||
filePath: rollout("2026", "02", "09", "rollout-2026-02-09T10-00-00-bbb.jsonl"),
|
||||
contents: codexRolloutLine(workspace),
|
||||
mtimeMs: Date.parse("2026-02-09T10:00:00.000Z"),
|
||||
});
|
||||
yield* writeTranscript({
|
||||
filePath: rollout("2026", "02", "09", "rollout-2026-02-09T11-00-00-ccc.jsonl"),
|
||||
contents: codexRolloutLine(otherWorkspace),
|
||||
mtimeMs: Date.parse("2026-02-09T11:00:00.000Z"),
|
||||
});
|
||||
|
||||
const result = yield* runScan({ claudeHomePath, codexHomePath });
|
||||
|
||||
expect(result.candidates).toEqual([
|
||||
{
|
||||
path: otherWorkspace,
|
||||
title: path.basename(otherWorkspace),
|
||||
sources: ["codex"],
|
||||
threadCount: 1,
|
||||
lastActiveAt: "2026-02-09T11:00:00.000Z",
|
||||
alreadyImported: false,
|
||||
},
|
||||
{
|
||||
path: workspace,
|
||||
title: path.basename(workspace),
|
||||
sources: ["codex"],
|
||||
threadCount: 2,
|
||||
lastActiveAt: "2026-02-09T10:00:00.000Z",
|
||||
alreadyImported: false,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("merges the same cwd seen by both agents and flags imported projects", () =>
|
||||
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-");
|
||||
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
|
||||
contents: claudeSessionLine(workspace),
|
||||
mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
|
||||
});
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(
|
||||
codexHomePath,
|
||||
"sessions",
|
||||
"2026",
|
||||
"04",
|
||||
"01",
|
||||
"rollout-2026-04-01T09-00-00-aaa.jsonl",
|
||||
),
|
||||
contents: codexRolloutLine(workspace),
|
||||
mtimeMs: Date.parse("2026-04-01T09:00:00.000Z"),
|
||||
});
|
||||
|
||||
const result = yield* runScan({
|
||||
claudeHomePath,
|
||||
codexHomePath,
|
||||
importedWorkspaceRoots: [workspace],
|
||||
});
|
||||
|
||||
expect(result.candidates).toEqual([
|
||||
{
|
||||
path: workspace,
|
||||
title: path.basename(workspace),
|
||||
sources: ["claudeAgent", "codex"],
|
||||
threadCount: 2,
|
||||
lastActiveAt: "2026-04-01T09:00:00.000Z",
|
||||
alreadyImported: true,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops candidates whose directory no longer exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
|
||||
const codexHomePath = yield* makeTempDir("t3code-codex-home-");
|
||||
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
|
||||
contents: claudeSessionLine(path.join(claudeHomePath, "does-not-exist")),
|
||||
mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
const result = yield* runScan({ claudeHomePath, codexHomePath });
|
||||
|
||||
expect(result.candidates).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes T3-managed worktree sandboxes", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
|
||||
const codexHomePath = yield* makeTempDir("t3code-codex-home-");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const worktreeCwd = path.join(claudeHomePath, ".t3", "worktrees", "t3code", "wt-1");
|
||||
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 });
|
||||
|
||||
expect(result.candidates).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips malformed transcripts without failing the scan", () =>
|
||||
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-");
|
||||
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-broken", "a.jsonl"),
|
||||
contents: "not json at all\n",
|
||||
mtimeMs: Date.parse("2026-05-01T00:00:00.000Z"),
|
||||
});
|
||||
// Valid JSON, but no cwd anywhere in the record.
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-no-cwd", "a.jsonl"),
|
||||
contents: `{"type":"summary"}\n`,
|
||||
mtimeMs: Date.parse("2026-05-02T00:00:00.000Z"),
|
||||
});
|
||||
yield* writeTranscript({
|
||||
filePath: path.join(claudeHomePath, "projects", "-good", "a.jsonl"),
|
||||
contents: claudeSessionLine(workspace),
|
||||
mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
const result = yield* runScan({ claudeHomePath, codexHomePath });
|
||||
|
||||
expect(result.candidates).toEqual([
|
||||
{
|
||||
path: workspace,
|
||||
title: path.basename(workspace),
|
||||
sources: ["claudeAgent"],
|
||||
threadCount: 1,
|
||||
lastActiveAt: "2026-05-03T00:00:00.000Z",
|
||||
alreadyImported: false,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns an empty result when neither home directory exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* makeTempDir("t3code-missing-homes-");
|
||||
|
||||
const result = yield* runScan({
|
||||
claudeHomePath: path.join(root, "no-claude"),
|
||||
codexHomePath: path.join(root, "no-codex"),
|
||||
});
|
||||
|
||||
expect(result.candidates).toEqual([]);
|
||||
expect(result.scannedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,402 @@
|
||||
/**
|
||||
* AgentSessionScanner - discovery of projects a user already works on.
|
||||
*
|
||||
* Claude Code and Codex both keep a per-session transcript on disk, and each
|
||||
* transcript records the directory the session ran in. Reading those `cwd`
|
||||
* values gives us the set of directories worth offering as projects during
|
||||
* onboarding, without asking the user to browse the filesystem.
|
||||
*
|
||||
* The scan is read-only and best-effort: an unreadable home, a malformed
|
||||
* transcript, or a directory that has since been deleted is skipped rather
|
||||
* than failing the scan. Project creation stays with the client, which
|
||||
* dispatches `project.create` for whichever candidates the user picks.
|
||||
*
|
||||
* @module project/AgentSessionScanner
|
||||
*/
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import type { AgentSessionProjectCandidate, AgentSessionScanResult } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 Schema from "effect/Schema";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
|
||||
import { expandHomePath } from "../pathExpansion.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
|
||||
/**
|
||||
* Bytes read from the head of each transcript. Session metadata (including
|
||||
* `cwd`) is written in the first record, so reading a prefix keeps the scan
|
||||
* cheap even when a transcript is hundreds of megabytes.
|
||||
*/
|
||||
const TRANSCRIPT_PREFIX_BYTES = 32 * 1024;
|
||||
|
||||
/**
|
||||
* Upper bound on transcripts inspected per source. Newest-first ordering means
|
||||
* the cap drops only stale sessions when a home directory is unusually large.
|
||||
*/
|
||||
const MAX_TRANSCRIPTS_PER_SOURCE = 5000;
|
||||
|
||||
export class AgentSessionScanFailedError extends Schema.TaggedErrorClass<AgentSessionScanFailedError>()(
|
||||
"AgentSessionScanFailedError",
|
||||
{
|
||||
operation: Schema.Literals(["read-settings", "read-projects"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to scan agent sessions during ${this.operation}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Service tag for agent session discovery. */
|
||||
export class AgentSessionScanner extends Context.Service<
|
||||
AgentSessionScanner,
|
||||
{
|
||||
/**
|
||||
* Discover every directory the configured Claude and Codex homes have run
|
||||
* a session in. Candidates are returned newest-first; the client decides
|
||||
* which ones to import and how far back to look.
|
||||
*/
|
||||
readonly scan: Effect.Effect<AgentSessionScanResult, AgentSessionScanFailedError>;
|
||||
}
|
||||
>()("t3/project/AgentSessionScanner") {}
|
||||
|
||||
type AgentSessionSource = AgentSessionProjectCandidate["sources"][number];
|
||||
|
||||
/** A single directory's worth of evidence from one source. */
|
||||
interface RawCandidate {
|
||||
readonly cwd: string;
|
||||
readonly source: AgentSessionSource;
|
||||
readonly threadCount: number;
|
||||
readonly lastActiveAtMs: number | null;
|
||||
}
|
||||
|
||||
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.
|
||||
*/
|
||||
function isT3ManagedWorktree(resolvedPath: string): boolean {
|
||||
return /[/\\]\.t3[/\\]worktrees[/\\]/.test(`${resolvedPath}/`);
|
||||
}
|
||||
|
||||
/** Extract `cwd` from a session-meta record, tolerating the shapes each CLI writes. */
|
||||
function extractCwd(line: string): string | null {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null) return null;
|
||||
|
||||
const record = parsed as Record<string, unknown>;
|
||||
if (typeof record.cwd === "string" && record.cwd.trim().length > 0) {
|
||||
return record.cwd;
|
||||
}
|
||||
// Codex nests session metadata under `payload`.
|
||||
const payload = record.payload;
|
||||
if (typeof payload === "object" && payload !== null) {
|
||||
const nested = (payload as Record<string, unknown>).cwd;
|
||||
if (typeof nested === "string" && nested.trim().length > 0) {
|
||||
return nested;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const listDirectory = (directory: string) =>
|
||||
fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
|
||||
|
||||
const statOption = (target: string) =>
|
||||
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.
|
||||
*/
|
||||
const readFirstLine = Effect.fn("AgentSessionScanner.readFirstLine")(function* (
|
||||
filePath: string,
|
||||
): Effect.fn.Return<string | null> {
|
||||
const prefix = yield* Effect.scoped(
|
||||
fileSystem
|
||||
.open(filePath, { flag: "r" })
|
||||
.pipe(Effect.flatMap((file) => file.readAlloc(TRANSCRIPT_PREFIX_BYTES))),
|
||||
).pipe(Effect.orElseSucceed(Option.none<Uint8Array>));
|
||||
if (Option.isNone(prefix)) return null;
|
||||
|
||||
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;
|
||||
}
|
||||
return text.slice(0, newlineIndex);
|
||||
});
|
||||
|
||||
const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (filePath: string) {
|
||||
const line = yield* readFirstLine(filePath);
|
||||
return line === null ? null : extractCwd(line.trim());
|
||||
});
|
||||
|
||||
const latestMtimeMs = Effect.fn("AgentSessionScanner.latestMtimeMs")(function* (
|
||||
filePaths: ReadonlyArray<string>,
|
||||
) {
|
||||
let latest: number | null = null;
|
||||
for (const filePath of filePaths) {
|
||||
const stats = yield* statOption(filePath);
|
||||
if (Option.isNone(stats)) continue;
|
||||
const mtime = stats.value.mtime;
|
||||
if (Option.isNone(mtime)) continue;
|
||||
const value = mtime.value.getTime();
|
||||
if (latest === null || value > latest) {
|
||||
latest = value;
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
});
|
||||
|
||||
/**
|
||||
* Resolve the Claude config directory the CLI would use, matching the
|
||||
* precedence the spawned CLI sees: the instance's `homePath` (exported as
|
||||
* `CLAUDE_CONFIG_DIR`), then a `CLAUDE_CONFIG_DIR` already in the
|
||||
* environment, then `~/.claude`.
|
||||
*/
|
||||
const resolveClaudeConfigDir = (homePath: string): string => {
|
||||
const configured = homePath.trim();
|
||||
if (configured.length > 0) {
|
||||
return path.resolve(expandHomePath(configured));
|
||||
}
|
||||
const fromEnvironment = process.env.CLAUDE_CONFIG_DIR?.trim() ?? "";
|
||||
if (fromEnvironment.length > 0) {
|
||||
return path.resolve(fromEnvironment);
|
||||
}
|
||||
return path.join(NodeOS.homedir(), ".claude");
|
||||
};
|
||||
|
||||
/**
|
||||
* Claude keeps one directory per project under `projects/`, named after a
|
||||
* lossy slug of the path. The slug can't be decoded (both `/` and `.` become
|
||||
* `-`), so the real path comes from the `cwd` recorded in the newest
|
||||
* transcript inside it.
|
||||
*/
|
||||
const scanClaude = Effect.fn("AgentSessionScanner.scanClaude")(function* (homePath: string) {
|
||||
const projectsDir = path.join(resolveClaudeConfigDir(homePath), "projects");
|
||||
const projectDirectories = yield* listDirectory(projectsDir);
|
||||
const candidates: Array<RawCandidate> = [];
|
||||
let budget = MAX_TRANSCRIPTS_PER_SOURCE;
|
||||
|
||||
for (const projectDirectory of projectDirectories) {
|
||||
if (budget <= 0) break;
|
||||
const directory = path.join(projectsDir, projectDirectory);
|
||||
const transcripts = (yield* listDirectory(directory))
|
||||
.filter((entry) => entry.endsWith(".jsonl"))
|
||||
.map((entry) => path.join(directory, entry));
|
||||
if (transcripts.length === 0) continue;
|
||||
|
||||
const inspected = transcripts.slice(0, budget);
|
||||
budget -= inspected.length;
|
||||
|
||||
const withMtimes: Array<{ filePath: string; mtimeMs: number }> = [];
|
||||
for (const filePath of inspected) {
|
||||
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);
|
||||
|
||||
// The newest transcript is the most likely to still name a live path.
|
||||
let cwd: string | null = null;
|
||||
for (const entry of withMtimes) {
|
||||
cwd = yield* readCwd(entry.filePath);
|
||||
if (cwd !== null) break;
|
||||
}
|
||||
if (cwd === null) continue;
|
||||
|
||||
candidates.push({
|
||||
cwd,
|
||||
source: "claudeAgent",
|
||||
threadCount: transcripts.length,
|
||||
lastActiveAtMs: withMtimes[0]?.mtimeMs ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return candidates;
|
||||
});
|
||||
|
||||
/**
|
||||
* Codex writes `sessions/YYYY/MM/DD/rollout-*.jsonl`. Always scan the shared
|
||||
* home: in auth-overlay mode the effective home only symlinks to it.
|
||||
*/
|
||||
const scanCodex = Effect.fn("AgentSessionScanner.scanCodex")(function* (
|
||||
codexSettings: Parameters<typeof resolveCodexHomeLayout>[0],
|
||||
) {
|
||||
const layout = yield* resolveCodexHomeLayout(codexSettings).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
const sessionsDir = path.join(layout.sharedHomePath, "sessions");
|
||||
|
||||
const rollouts: Array<string> = [];
|
||||
// Date-partitioned directories sort chronologically, so walking them in
|
||||
// reverse keeps the newest sessions when the budget runs out.
|
||||
for (const year of (yield* listDirectory(sessionsDir)).toSorted().toReversed()) {
|
||||
for (const month of (yield* listDirectory(path.join(sessionsDir, year)))
|
||||
.toSorted()
|
||||
.toReversed()) {
|
||||
for (const day of (yield* listDirectory(path.join(sessionsDir, year, month)))
|
||||
.toSorted()
|
||||
.toReversed()) {
|
||||
const directory = path.join(sessionsDir, year, month, day);
|
||||
for (const entry of (yield* listDirectory(directory)).toSorted().toReversed()) {
|
||||
if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue;
|
||||
rollouts.push(path.join(directory, entry));
|
||||
if (rollouts.length >= MAX_TRANSCRIPTS_PER_SOURCE) break;
|
||||
}
|
||||
if (rollouts.length >= MAX_TRANSCRIPTS_PER_SOURCE) break;
|
||||
}
|
||||
if (rollouts.length >= MAX_TRANSCRIPTS_PER_SOURCE) break;
|
||||
}
|
||||
if (rollouts.length >= MAX_TRANSCRIPTS_PER_SOURCE) break;
|
||||
}
|
||||
|
||||
const byCwd = new Map<string, Array<string>>();
|
||||
for (const rollout of rollouts) {
|
||||
const cwd = yield* readCwd(rollout);
|
||||
if (cwd === null) continue;
|
||||
const existing = byCwd.get(cwd);
|
||||
if (existing) {
|
||||
existing.push(rollout);
|
||||
} else {
|
||||
byCwd.set(cwd, [rollout]);
|
||||
}
|
||||
}
|
||||
|
||||
const candidates: Array<RawCandidate> = [];
|
||||
for (const [cwd, filePaths] of byCwd) {
|
||||
candidates.push({
|
||||
cwd,
|
||||
source: "codex",
|
||||
threadCount: filePaths.length,
|
||||
lastActiveAtMs: yield* latestMtimeMs(filePaths),
|
||||
});
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const scan: AgentSessionScanner["Service"]["scan"] = Effect.gen(function* () {
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new AgentSessionScanFailedError({ operation: "read-settings", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const raw = [
|
||||
...(yield* scanClaude(settings.providers.claudeAgent.homePath)),
|
||||
...(yield* scanCodex(settings.providers.codex)),
|
||||
];
|
||||
|
||||
// Merge by resolved path first so both sources agree on a key, then by
|
||||
// realpath so a symlinked home and its target collapse into one candidate.
|
||||
const merged = new Map<
|
||||
string,
|
||||
{
|
||||
path: string;
|
||||
sources: Array<AgentSessionSource>;
|
||||
threadCount: number;
|
||||
lastActiveAtMs: number | null;
|
||||
}
|
||||
>();
|
||||
const realPathKeys = new Map<string, string>();
|
||||
|
||||
for (const candidate of raw) {
|
||||
const resolved = path.resolve(expandHomePath(candidate.cwd.trim()));
|
||||
if (isT3ManagedWorktree(resolved)) continue;
|
||||
let key = realPathKeys.get(resolved);
|
||||
if (key === undefined) {
|
||||
const stats = yield* statOption(resolved);
|
||||
// Directories that no longer exist can't be imported.
|
||||
if (Option.isNone(stats) || stats.value.type !== "Directory") {
|
||||
realPathKeys.set(resolved, "");
|
||||
continue;
|
||||
}
|
||||
key = yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved));
|
||||
realPathKeys.set(resolved, key);
|
||||
}
|
||||
if (key === "") continue;
|
||||
|
||||
const existing = merged.get(key);
|
||||
if (!existing) {
|
||||
merged.set(key, {
|
||||
path: resolved,
|
||||
sources: [candidate.source],
|
||||
threadCount: candidate.threadCount,
|
||||
lastActiveAtMs: candidate.lastActiveAtMs,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (!existing.sources.includes(candidate.source)) {
|
||||
existing.sources.push(candidate.source);
|
||||
}
|
||||
existing.threadCount += candidate.threadCount;
|
||||
existing.lastActiveAtMs =
|
||||
existing.lastActiveAtMs === null || candidate.lastActiveAtMs === null
|
||||
? (existing.lastActiveAtMs ?? candidate.lastActiveAtMs)
|
||||
: Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs);
|
||||
}
|
||||
|
||||
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 }),
|
||||
),
|
||||
);
|
||||
candidates.push({
|
||||
path: entry.path,
|
||||
title: path.basename(entry.path) || entry.path,
|
||||
sources: entry.sources,
|
||||
threadCount: entry.threadCount,
|
||||
lastActiveAt:
|
||||
entry.lastActiveAtMs === null
|
||||
? null
|
||||
: DateTime.formatIso(DateTime.makeUnsafe(entry.lastActiveAtMs)),
|
||||
alreadyImported: Option.isSome(existingProject),
|
||||
});
|
||||
}
|
||||
|
||||
// Newest first, undated candidates last.
|
||||
candidates.sort((left, right) => {
|
||||
if (left.lastActiveAt === right.lastActiveAt) return left.path.localeCompare(right.path);
|
||||
if (left.lastActiveAt === null) return 1;
|
||||
if (right.lastActiveAt === null) return -1;
|
||||
return right.lastActiveAt.localeCompare(left.lastActiveAt);
|
||||
});
|
||||
|
||||
return {
|
||||
candidates,
|
||||
scannedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
};
|
||||
});
|
||||
|
||||
return AgentSessionScanner.of({ scan });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(AgentSessionScanner, make);
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
type ServerSelfUpdateProgressEvent,
|
||||
type FilesystemBrowseFailure,
|
||||
FilesystemBrowseError,
|
||||
AgentSessionScanError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspaceContextResolutionError,
|
||||
RpcClientId,
|
||||
@@ -97,6 +98,7 @@ import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
|
||||
import * as AgentSessionScanner from "./project/AgentSessionScanner.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
@@ -375,6 +377,7 @@ const makeWsRpcLayer = (
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner;
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const rpcClientIds = yield* Ref.make(new Set<RpcClientId>());
|
||||
@@ -1699,6 +1702,21 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.agentSessionsScan]: () =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.agentSessionsScan,
|
||||
agentSessionScanner.scan.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AgentSessionScanError({
|
||||
failure: "scan_failed",
|
||||
message: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.assetsCreateUrl]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsCreateUrl,
|
||||
@@ -2130,6 +2148,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
Effect.provide(
|
||||
makeWsRpcLayer(session, previewAutomationBroker).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(AgentSessionScanner.layer),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
|
||||
Layer.provide(
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useClientSettings, useClientSettingsHydrated } from "../../hooks/useSettings";
|
||||
import {
|
||||
useAllEnvironmentShellsBootstrapped,
|
||||
useProjects,
|
||||
useThreadShells,
|
||||
} from "../../state/entities";
|
||||
import { primaryServerConfigAtom } from "../../state/server";
|
||||
|
||||
/**
|
||||
* Holds back the authenticated app tree until the first-run decision is known,
|
||||
* so a fresh install never flashes the main screen before the welcome wizard.
|
||||
* Nothing renders while pending — no shell, no EventRouter (whose welcome
|
||||
* payload would otherwise navigate into a thread), no dialogs.
|
||||
*
|
||||
* Decision order: a set `onboardingCompletedAt` resolves to the app as soon as
|
||||
* settings hydrate (the common case, no server round-trip). A `null` flag also
|
||||
* covers installs that predate the field, so it alone is not enough — the gate
|
||||
* waits for environment shells to bootstrap and inspects the workspace. A
|
||||
* timeout guards the pathological case where shells never bootstrap
|
||||
* (unreachable server): after it, the app renders as usual.
|
||||
*/
|
||||
|
||||
const FIRST_RUN_DECISION_TIMEOUT_MS = 4_000;
|
||||
|
||||
type FirstRunDecision = "pending" | "app" | "wizard";
|
||||
|
||||
export function FirstRunGate({ children }: { readonly children: React.ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const hydrated = useClientSettingsHydrated();
|
||||
const onboardingCompletedAt = useClientSettings((settings) => settings.onboardingCompletedAt);
|
||||
const bootstrapped = useAllEnvironmentShellsBootstrapped();
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const serverConfig = useAtomValue(primaryServerConfigAtom);
|
||||
// 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",
|
||||
);
|
||||
|
||||
// A workspace still counts as fresh when its only content is the server's
|
||||
// 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.
|
||||
const serverCwd = serverConfig?.cwd ?? null;
|
||||
const workspaceFresh =
|
||||
projects.every((project) => serverCwd !== null && project.workspaceRoot === serverCwd) &&
|
||||
threads.length <= 1;
|
||||
|
||||
useEffect(() => {
|
||||
if (decision !== "pending" || !hydrated) return;
|
||||
if (onboardingCompletedAt !== null) {
|
||||
setDecision("app");
|
||||
return;
|
||||
}
|
||||
if (!bootstrapped) return;
|
||||
setDecision(workspaceFresh ? "wizard" : "app");
|
||||
}, [bootstrapped, decision, hydrated, onboardingCompletedAt, workspaceFresh]);
|
||||
|
||||
useEffect(() => {
|
||||
if (decision !== "pending") return;
|
||||
const timer = window.setTimeout(() => setDecision("app"), FIRST_RUN_DECISION_TIMEOUT_MS);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [decision]);
|
||||
|
||||
useEffect(() => {
|
||||
if (decision === "wizard") {
|
||||
void navigate({ to: "/welcome", replace: true });
|
||||
}
|
||||
}, [decision, navigate]);
|
||||
|
||||
if (decision !== "app") {
|
||||
return null;
|
||||
}
|
||||
return children;
|
||||
}
|
||||
@@ -0,0 +1,976 @@
|
||||
import { useAuth } from "@clerk/react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
AgentSessionProjectCandidate,
|
||||
EnvironmentId,
|
||||
ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { CheckIcon, ChevronLeftIcon, CopyIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../../branding";
|
||||
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
|
||||
import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
|
||||
import { useCompleteOnboarding } from "../../onboarding/firstRun";
|
||||
import { newProjectId } from "../../lib/utils";
|
||||
import { resolveDefaultProviderModelSelection } from "../../providerInstances";
|
||||
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 { terminalEnvironment } from "../../state/terminal";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { connectPairing } from "../../connection/onboarding";
|
||||
import { getProviderSummary } from "../settings/providerStatus";
|
||||
import { getDriverOption } from "../settings/providerDriverMeta";
|
||||
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
|
||||
import { TerminalViewport } from "../ThreadTerminalDrawer";
|
||||
import { Button } from "../ui/button";
|
||||
import { Checkbox } from "../ui/checkbox";
|
||||
import { Input } from "../ui/input";
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
/**
|
||||
* First-run welcome wizard. Rendered as the full-screen `/welcome` route on a
|
||||
* fresh install (no completed-onboarding flag, empty workspace). Flow per the
|
||||
* onboarding overhaul spec: connection choice → sign-in/pair (remote paths) →
|
||||
* agent setup with inline install terminal → project import → main screen.
|
||||
* Every step past the connection gate is skippable; the whole wizard is
|
||||
* re-runnable by clearing the flag.
|
||||
*/
|
||||
|
||||
type WizardStep = "connection" | "connect-machines" | "pair-direct" | "agents" | "import";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function useOnboardingTargetEnvironment() {
|
||||
const { environments } = useEnvironments();
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
if (primaryEnvironment !== null && primaryEnvironment.connection.phase === "connected") {
|
||||
return primaryEnvironment;
|
||||
}
|
||||
return environments.find((environment) => environment.connection.phase === "connected") ?? null;
|
||||
}
|
||||
|
||||
const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup");
|
||||
const IMPORT_RECENT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export function WelcomeWizard({
|
||||
localAvailable,
|
||||
onDone,
|
||||
}: {
|
||||
/**
|
||||
* Whether the "Local Only" card is offered. True whenever the app is served
|
||||
* by an authenticated primary server — desktop, `npx t3`, or a dev server —
|
||||
* since that server is "this machine" regardless of the hostname the app
|
||||
* was opened from. Only hosted-static (app.t3.codes) has no local server.
|
||||
*/
|
||||
readonly localAvailable: boolean;
|
||||
readonly onDone: () => void;
|
||||
}) {
|
||||
const completeOnboarding = useCompleteOnboarding();
|
||||
const [step, setStep] = useState<WizardStep>("connection");
|
||||
const finish = useCallback(() => {
|
||||
completeOnboarding();
|
||||
onDone();
|
||||
}, [completeOnboarding, onDone]);
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
|
||||
<div className="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-emerald-500)_14%,transparent),transparent)]" />
|
||||
<div className="absolute inset-y-0 left-0 w-72 bg-[radial-gradient(28rem_18rem_at_left,color-mix(in_srgb,var(--color-sky-500)_10%,transparent),transparent)]" />
|
||||
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
|
||||
</div>
|
||||
|
||||
<section className="relative w-full max-w-2xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
|
||||
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
|
||||
{APP_DISPLAY_NAME}
|
||||
</p>
|
||||
{step === "connection" ? (
|
||||
<ConnectionStep
|
||||
localAvailable={localAvailable}
|
||||
onLocal={() => setStep("agents")}
|
||||
onConnect={() => setStep("connect-machines")}
|
||||
onDirect={() => setStep("pair-direct")}
|
||||
/>
|
||||
) : step === "connect-machines" ? (
|
||||
<ConnectMachinesStep
|
||||
onBack={() => setStep("connection")}
|
||||
onContinue={() => setStep("agents")}
|
||||
/>
|
||||
) : step === "pair-direct" ? (
|
||||
<PairDirectStep onBack={() => setStep("connection")} onPaired={() => setStep("agents")} />
|
||||
) : step === "agents" ? (
|
||||
<AgentsStep onContinue={() => setStep("import")} onSkip={() => setStep("import")} />
|
||||
) : (
|
||||
<ImportStep onDone={finish} />
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Step 1: connection choice ────────────────────────────────
|
||||
|
||||
function ConnectionStep({
|
||||
localAvailable,
|
||||
onLocal,
|
||||
onConnect,
|
||||
onDirect,
|
||||
}: {
|
||||
readonly localAvailable: boolean;
|
||||
readonly onLocal: () => void;
|
||||
readonly onConnect: () => void;
|
||||
readonly onDirect: () => void;
|
||||
}) {
|
||||
const cloudEnabled = hasCloudPublicConfig();
|
||||
const [choice, setChoice] = useState<"local" | "connect" | "direct">(
|
||||
localAvailable ? "local" : cloudEnabled ? "connect" : "direct",
|
||||
);
|
||||
|
||||
const advance = () => {
|
||||
if (choice === "local") onLocal();
|
||||
else if (choice === "connect") onConnect();
|
||||
else onDirect();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
|
||||
How do you want to connect?
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
Choose where your agents run. You can add more connections later in Settings.
|
||||
</p>
|
||||
<div className="mt-6 grid gap-3 sm:grid-cols-3">
|
||||
{localAvailable ? (
|
||||
<ConnectionCard
|
||||
title="Local Only"
|
||||
description="Use T3 Code with agents on this machine."
|
||||
tag="no account"
|
||||
selected={choice === "local"}
|
||||
onSelect={() => setChoice("local")}
|
||||
/>
|
||||
) : null}
|
||||
{cloudEnabled ? (
|
||||
<ConnectionCard
|
||||
title="T3 Connect"
|
||||
description="Sign in and connect to any of your computers."
|
||||
tag="account"
|
||||
selected={choice === "connect"}
|
||||
onSelect={() => setChoice("connect")}
|
||||
/>
|
||||
) : null}
|
||||
<ConnectionCard
|
||||
title="Direct"
|
||||
description="Connect to a server by URL. Works over LAN and Tailscale."
|
||||
tag="advanced"
|
||||
selected={choice === "direct"}
|
||||
onSelect={() => setChoice("direct")}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-6 flex justify-end">
|
||||
<Button onClick={advance}>Continue</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectionCard({
|
||||
title,
|
||||
description,
|
||||
tag,
|
||||
selected,
|
||||
onSelect,
|
||||
}: {
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly tag: string;
|
||||
readonly selected: boolean;
|
||||
readonly onSelect: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
"flex flex-col rounded-xl border p-4 text-left transition-colors",
|
||||
selected
|
||||
? "border-primary bg-primary/5 ring-1 ring-primary/25"
|
||||
: "border-border/70 bg-background/40 hover:border-border",
|
||||
)}
|
||||
>
|
||||
<span className="text-sm font-semibold">{title}</span>
|
||||
<span className="mt-1 flex-1 text-xs leading-relaxed text-muted-foreground">
|
||||
{description}
|
||||
</span>
|
||||
<span className="mt-3 self-start rounded border border-border/70 px-1.5 py-0.5 text-[10px] text-muted-foreground">
|
||||
{tag}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Step 2: T3 Connect (sign in, then connect machines) ──────
|
||||
|
||||
const CONNECT_LOGIN_COMMAND = "npx t3 connect";
|
||||
|
||||
/**
|
||||
* Sign-in and machine-connection combined: signed out shows the Clerk prompt,
|
||||
* signed in forks on account state — zero connected machines blocks on the
|
||||
* `npx t3 connect` command and auto-advance is left to the user pressing
|
||||
* Continue once their machine appears; existing machines show a confirmation
|
||||
* list with the command folded away. There is deliberately no "primary
|
||||
* machine" selection.
|
||||
*/
|
||||
function ConnectMachinesStep({
|
||||
onBack,
|
||||
onContinue,
|
||||
}: {
|
||||
readonly onBack: () => void;
|
||||
readonly onContinue: () => void;
|
||||
}) {
|
||||
// Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read
|
||||
// as signed-out mid-transition.
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { openAuthPrompt } = useT3ConnectAuthPrompt();
|
||||
const { environments } = useEnvironments();
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const savedEnvironments = environments.filter(
|
||||
(environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
|
||||
);
|
||||
const hasRemoteMachines = savedEnvironments.length > 0;
|
||||
|
||||
if (!isLoaded) {
|
||||
return <StepShell title="Sign in to T3 Connect" onBack={onBack} />;
|
||||
}
|
||||
|
||||
if (!isSignedIn) {
|
||||
return (
|
||||
<StepShell
|
||||
title="Sign in to T3 Connect"
|
||||
description="One account links all your machines. Machines signed into your account connect automatically."
|
||||
onBack={onBack}
|
||||
>
|
||||
<div className="mt-6">
|
||||
<Button onClick={openAuthPrompt}>Sign in</Button>
|
||||
</div>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StepShell
|
||||
title={hasRemoteMachines ? "Your machines are connected" : "Run this where your code lives"}
|
||||
description={
|
||||
hasRemoteMachines
|
||||
? "These machines connected automatically from your account."
|
||||
: "SSH in if you need to. The machine signs into your account and connects on its own."
|
||||
}
|
||||
onBack={onBack}
|
||||
>
|
||||
{hasRemoteMachines ? (
|
||||
<>
|
||||
<div className="mt-5 overflow-hidden rounded-lg border">
|
||||
<CloudEnvironmentConnectRows
|
||||
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
|
||||
savedEnvironments={savedEnvironments}
|
||||
showSavedEnvironments
|
||||
empty={null}
|
||||
/>
|
||||
</div>
|
||||
<details className="mt-4">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground">
|
||||
Add another machine
|
||||
</summary>
|
||||
<CommandBlock command={CONNECT_LOGIN_COMMAND} className="mt-2" />
|
||||
</details>
|
||||
<div className="mt-6 flex justify-end">
|
||||
<Button onClick={onContinue}>Continue</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CommandBlock command={CONNECT_LOGIN_COMMAND} className="mt-6" prominent />
|
||||
<div className="mt-5 overflow-hidden rounded-lg border border-dashed border-border/60">
|
||||
<CloudEnvironmentConnectRows
|
||||
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
|
||||
savedEnvironments={savedEnvironments}
|
||||
showSavedEnvironments
|
||||
empty={
|
||||
<p className="px-4 py-4 text-center text-xs text-muted-foreground">
|
||||
Waiting for a machine. It appears here the moment it signs in.
|
||||
</p>
|
||||
}
|
||||
/>
|
||||
</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>
|
||||
</>
|
||||
)}
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Step 2′: Direct pairing ──────────────────────────────────
|
||||
|
||||
/**
|
||||
* Server-minted pairing, D-B treatment: numbered steps, `t3 pair` on the
|
||||
* server, paste the URL here. Registers the remote environment in this
|
||||
* browser's catalog (same path the hosted /pair surface uses).
|
||||
*/
|
||||
function PairDirectStep({
|
||||
onBack,
|
||||
onPaired,
|
||||
}: {
|
||||
readonly onBack: () => void;
|
||||
readonly onPaired: () => void;
|
||||
}) {
|
||||
const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false });
|
||||
const [pairingUrl, setPairingUrl] = useState("");
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [isPairing, setIsPairing] = useState(false);
|
||||
|
||||
const submit = async () => {
|
||||
setIsPairing(true);
|
||||
setErrorMessage("");
|
||||
const result = await connectPairingEnvironment({ pairingUrl });
|
||||
setIsPairing(false);
|
||||
if (result._tag === "Success") {
|
||||
onPaired();
|
||||
return;
|
||||
}
|
||||
if (isAtomCommandInterrupted(result)) return;
|
||||
const cause = squashAtomCommandFailure(result);
|
||||
setErrorMessage(cause instanceof Error ? cause.message : "Pairing failed.");
|
||||
};
|
||||
|
||||
return (
|
||||
<StepShell title="Pair with your server" onBack={onBack}>
|
||||
<div className="mt-5 space-y-4">
|
||||
<div>
|
||||
<p className="text-sm">
|
||||
<span className="font-semibold">1.</span>{" "}
|
||||
<span className="text-muted-foreground">On the server:</span>
|
||||
</p>
|
||||
<CommandBlock command="npx t3 pair" className="mt-2" />
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Prints a one-time pairing URL. Add{" "}
|
||||
<code className="rounded bg-muted px-1 font-mono">--tailscale</code> to publish on your
|
||||
tailnet.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm">
|
||||
<span className="font-semibold">2.</span>{" "}
|
||||
<span className="text-muted-foreground">Paste the URL it prints:</span>
|
||||
</p>
|
||||
<Input
|
||||
className="mt-2"
|
||||
autoCapitalize="none"
|
||||
autoComplete="off"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
nativeInput
|
||||
disabled={isPairing}
|
||||
placeholder="https://your-server:5230/pair#token=…"
|
||||
value={pairingUrl}
|
||||
onChange={(event) => setPairingUrl(event.currentTarget.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && pairingUrl.trim().length > 0) void submit();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{errorMessage ? (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-6 flex justify-end">
|
||||
<Button
|
||||
disabled={isPairing || pairingUrl.trim().length === 0}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{isPairing ? "Pairing…" : "Pair"}
|
||||
</Button>
|
||||
</div>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Step 3: agents ───────────────────────────────────────────
|
||||
|
||||
const PRIMARY_AGENT_DRIVERS = ["claudeAgent", "codex"] as const;
|
||||
|
||||
const AGENT_INSTALL_COMMANDS: Record<string, string> = {
|
||||
claudeAgent: "npm install -g @anthropic-ai/claude-code",
|
||||
codex: "npm install -g @openai/codex",
|
||||
};
|
||||
|
||||
// Claude has no `login` subcommand — running it interactively prompts OAuth.
|
||||
const AGENT_LOGIN_COMMANDS: Record<string, string> = {
|
||||
claudeAgent: "claude",
|
||||
codex: "codex login",
|
||||
};
|
||||
|
||||
/**
|
||||
* Claude Code and Codex as hero cards with live probe status; the remaining
|
||||
* drivers listed quietly below. Install opens the built-in terminal inline
|
||||
* with the command pre-typed — the update RPC can't install a binary that
|
||||
* isn't there yet (it infers the package manager from the installed binary's
|
||||
* path), and the terminal also handles the interactive login that follows.
|
||||
*/
|
||||
function AgentsStep({
|
||||
onContinue,
|
||||
onSkip,
|
||||
}: {
|
||||
readonly onContinue: () => void;
|
||||
readonly onSkip: () => void;
|
||||
}) {
|
||||
const targetEnvironment = useOnboardingTargetEnvironment();
|
||||
if (targetEnvironment === null) {
|
||||
return (
|
||||
<StepShell title="Set up your agents" description="Waiting for an environment connection…">
|
||||
<div className="mt-6 flex justify-end">
|
||||
<Button variant="ghost" onClick={onSkip}>
|
||||
Skip for now
|
||||
</Button>
|
||||
</div>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ConnectedAgentsStep
|
||||
environmentId={targetEnvironment.environmentId}
|
||||
machineLabel={targetEnvironment.label}
|
||||
onContinue={onContinue}
|
||||
onSkip={onSkip}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectedAgentsStep({
|
||||
environmentId,
|
||||
machineLabel,
|
||||
onContinue,
|
||||
onSkip,
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly machineLabel: string;
|
||||
readonly onContinue: () => void;
|
||||
readonly onSkip: () => void;
|
||||
}) {
|
||||
const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));
|
||||
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const [terminalAgent, setTerminalAgent] = useState<string | null>(null);
|
||||
|
||||
// Re-probe on entry so freshly installed CLIs show up without a manual
|
||||
// refresh; harmless when nothing changed (single-flighted per environment).
|
||||
useEffect(() => {
|
||||
void refreshProviders({ environmentId, input: {} });
|
||||
}, [environmentId, refreshProviders]);
|
||||
|
||||
const byDriver = useMemo(() => {
|
||||
const map = new Map<string, ServerProvider>();
|
||||
for (const provider of providers ?? []) {
|
||||
if (!map.has(provider.driver)) map.set(provider.driver, provider);
|
||||
}
|
||||
return map;
|
||||
}, [providers]);
|
||||
|
||||
const primaryAgents = PRIMARY_AGENT_DRIVERS.map((driver) => ({
|
||||
driver,
|
||||
provider: byDriver.get(driver),
|
||||
}));
|
||||
const readyCount = primaryAgents.filter(
|
||||
({ provider }) => provider?.installed && provider.auth.status === "authenticated",
|
||||
).length;
|
||||
const otherAgents = [...byDriver.keys()].filter(
|
||||
(driver) => !PRIMARY_AGENT_DRIVERS.includes(driver as (typeof PRIMARY_AGENT_DRIVERS)[number]),
|
||||
);
|
||||
|
||||
return (
|
||||
<StepShell
|
||||
title="Set up your agents"
|
||||
description={`Checked on ${machineLabel}. You need at least one to start.`}
|
||||
>
|
||||
<div className="mt-5 grid gap-3 sm:grid-cols-2">
|
||||
{primaryAgents.map(({ driver, provider }) => (
|
||||
<AgentCard
|
||||
key={driver}
|
||||
driver={driver}
|
||||
provider={provider}
|
||||
terminalOpen={terminalAgent === driver}
|
||||
onOpenTerminal={() => setTerminalAgent(driver)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{terminalAgent !== null ? (
|
||||
<AgentInstallTerminal
|
||||
key={terminalAgent}
|
||||
environmentId={environmentId}
|
||||
driver={terminalAgent}
|
||||
installed={byDriver.get(terminalAgent)?.installed ?? false}
|
||||
onClose={() => {
|
||||
setTerminalAgent(null);
|
||||
void refreshProviders({ environmentId, input: {} });
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{otherAgents.length > 0 ? (
|
||||
<p className="mt-4 text-xs text-muted-foreground">
|
||||
Also supported:{" "}
|
||||
{otherAgents
|
||||
.map((driver) => getDriverOption(driver as never)?.label ?? driver)
|
||||
.join(" · ")}{" "}
|
||||
— configure in Settings.
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-6 flex items-center justify-between">
|
||||
<Button variant="ghost" onClick={onSkip}>
|
||||
Skip for now
|
||||
</Button>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{readyCount} of {primaryAgents.length} ready
|
||||
</span>
|
||||
<Button onClick={onContinue}>Continue</Button>
|
||||
</div>
|
||||
</div>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentCard({
|
||||
driver,
|
||||
provider,
|
||||
terminalOpen,
|
||||
onOpenTerminal,
|
||||
}: {
|
||||
readonly driver: string;
|
||||
readonly provider: ServerProvider | undefined;
|
||||
readonly terminalOpen: boolean;
|
||||
readonly onOpenTerminal: () => void;
|
||||
}) {
|
||||
const meta = getDriverOption(driver as never);
|
||||
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";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-xl border p-4",
|
||||
ready ? "border-emerald-500/40" : terminalOpen ? "border-primary" : "border-border/70",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
{Icon ? <Icon className="size-6" /> : null}
|
||||
<span className="text-sm font-semibold">{displayName}</span>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{summary.headline}
|
||||
{summary.detail ? ` · ${summary.detail}` : ""}
|
||||
</p>
|
||||
<div className="mt-3">
|
||||
{ready ? (
|
||||
<span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-500">
|
||||
<CheckIcon className="size-3.5" />
|
||||
Ready
|
||||
</span>
|
||||
) : (
|
||||
<Button size="xs" variant="outline" onClick={onOpenTerminal} disabled={terminalOpen}>
|
||||
<TerminalIcon className="size-3.5" />
|
||||
{needsLogin ? "Sign in" : "Install"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline install terminal. Opens a PTY on the connected environment under a
|
||||
* synthetic onboarding thread id (terminals are keyed by free-form thread id;
|
||||
* the server validates only the cwd) and pre-types the install or login
|
||||
* command without submitting, so the user reviews and presses Enter.
|
||||
*/
|
||||
function AgentInstallTerminal({
|
||||
environmentId,
|
||||
driver,
|
||||
installed,
|
||||
onClose,
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly driver: string;
|
||||
readonly installed: boolean;
|
||||
readonly onClose: () => void;
|
||||
}) {
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
|
||||
const openTerminal = useAtomCommand(terminalEnvironment.open, { reportFailure: false });
|
||||
const writeTerminal = useAtomCommand(terminalEnvironment.write, { reportFailure: false });
|
||||
const preparedRef = useRef(false);
|
||||
const terminalId = `onboarding-${driver}`;
|
||||
const threadRef = useMemo(
|
||||
() => scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID),
|
||||
[environmentId],
|
||||
);
|
||||
// The terminal manager stats the cwd verbatim (no tilde expansion), so use
|
||||
// the server process's own working directory — always real on that machine.
|
||||
const cwd = serverConfig?.cwd ?? null;
|
||||
|
||||
const command = installed
|
||||
? (AGENT_LOGIN_COMMANDS[driver] ?? "")
|
||||
: (AGENT_INSTALL_COMMANDS[driver] ?? "");
|
||||
|
||||
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;
|
||||
// Pre-type without the trailing carriage return; the user submits.
|
||||
await writeTerminal({
|
||||
environmentId,
|
||||
input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, data: command },
|
||||
});
|
||||
})();
|
||||
}, [command, cwd, environmentId, openTerminal, terminalId, writeTerminal]);
|
||||
|
||||
if (cwd === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-4 overflow-hidden rounded-lg border border-border/70">
|
||||
<div className="flex items-center justify-between border-b border-border/60 bg-background/60 px-3 py-1.5">
|
||||
<span className="text-[11px] font-medium text-muted-foreground">
|
||||
Review the command, then press Enter to run it.
|
||||
</span>
|
||||
<Button size="xs" variant="ghost" onClick={onClose}>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
<div className="h-64">
|
||||
<TerminalViewport
|
||||
threadRef={threadRef}
|
||||
threadId={AGENT_ONBOARDING_THREAD_ID}
|
||||
terminalId={terminalId}
|
||||
terminalLabel={`Install ${driver}`}
|
||||
cwd={cwd}
|
||||
onSessionExited={onClose}
|
||||
onAddTerminalContext={() => undefined}
|
||||
focusRequestId={1}
|
||||
autoFocus
|
||||
resizeEpoch={0}
|
||||
drawerHeight={256}
|
||||
keybindings={keybindings}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Step 4: import ───────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* One-decision import (4B): a summary line with Import recent / Choose /
|
||||
* Skip. The default imports only projects touched in the last 30 days;
|
||||
* Choose expands a checklist including older ones. Projects only — thread
|
||||
* history import is a follow-up.
|
||||
*/
|
||||
function ImportStep({ onDone }: { readonly onDone: () => void }) {
|
||||
const targetEnvironment = useOnboardingTargetEnvironment();
|
||||
const environmentId = targetEnvironment?.environmentId ?? null;
|
||||
const machineLabel = targetEnvironment?.label ?? "this machine";
|
||||
const providers = useAtomValue(
|
||||
serverEnvironment.providersValueAtom(environmentId ?? ("" as EnvironmentId)),
|
||||
);
|
||||
const scan = useEnvironmentQuery(
|
||||
environmentId === null ? null : agentSessionScan({ environmentId, input: {} }),
|
||||
);
|
||||
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
|
||||
const [choosing, setChoosing] = useState(false);
|
||||
const [deselected, setDeselected] = useState<ReadonlySet<string>>(new Set());
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importError, setImportError] = useState("");
|
||||
|
||||
const candidates = useMemo(
|
||||
() => (scan.data?.candidates ?? []).filter((candidate) => !candidate.alreadyImported),
|
||||
[scan.data],
|
||||
);
|
||||
const recentCutoff = Date.now() - IMPORT_RECENT_WINDOW_MS;
|
||||
const recent = useMemo(
|
||||
() =>
|
||||
candidates.filter(
|
||||
(candidate) =>
|
||||
candidate.lastActiveAt !== null && Date.parse(candidate.lastActiveAt) >= recentCutoff,
|
||||
),
|
||||
[candidates, recentCutoff],
|
||||
);
|
||||
const older = candidates.length - recent.length;
|
||||
|
||||
const runImport = async (selection: ReadonlyArray<AgentSessionProjectCandidate>) => {
|
||||
if (environmentId === null || selection.length === 0) {
|
||||
onDone();
|
||||
return;
|
||||
}
|
||||
setIsImporting(true);
|
||||
setImportError("");
|
||||
const defaultModelSelection = resolveDefaultProviderModelSelection(providers ?? [], null);
|
||||
let failures = 0;
|
||||
for (const candidate of selection) {
|
||||
const result = await createProject({
|
||||
environmentId,
|
||||
input: {
|
||||
projectId: newProjectId(),
|
||||
title: candidate.title,
|
||||
workspaceRoot: candidate.path,
|
||||
createWorkspaceRootIfMissing: false,
|
||||
defaultModelSelection,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
failures += 1;
|
||||
}
|
||||
}
|
||||
setIsImporting(false);
|
||||
if (failures > 0 && failures === selection.length) {
|
||||
setImportError("Import failed. You can add projects manually from the command palette.");
|
||||
return;
|
||||
}
|
||||
onDone();
|
||||
};
|
||||
|
||||
if (environmentId === null || (scan.isPending && scan.data === null)) {
|
||||
return (
|
||||
<StepShell
|
||||
title="Bring your work with you"
|
||||
description="Looking for existing Claude Code and Codex projects…"
|
||||
>
|
||||
<div className="mt-6 flex justify-end">
|
||||
<Button variant="ghost" onClick={onDone}>
|
||||
Skip
|
||||
</Button>
|
||||
</div>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (scan.error !== null || candidates.length === 0) {
|
||||
return (
|
||||
<StepShell
|
||||
title="Bring your work with you"
|
||||
description={
|
||||
scan.error !== null
|
||||
? "We couldn't scan for existing agent projects on this machine."
|
||||
: "No existing Claude Code or Codex projects found on this machine."
|
||||
}
|
||||
>
|
||||
<p className="mt-3 text-xs text-muted-foreground">
|
||||
You can add projects any time from the command palette.
|
||||
</p>
|
||||
<div className="mt-6 flex justify-end">
|
||||
<Button onClick={onDone}>Finish</Button>
|
||||
</div>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (choosing) {
|
||||
const selectedCount = candidates.length - deselected.size;
|
||||
return (
|
||||
<StepShell
|
||||
title="Choose projects to import"
|
||||
onBack={() => setChoosing(false)}
|
||||
description={`${candidates.length} projects found on ${machineLabel}.`}
|
||||
>
|
||||
<div className="mt-4 max-h-72 space-y-1.5 overflow-y-auto pr-1">
|
||||
{candidates.map((candidate) => (
|
||||
<label
|
||||
key={candidate.path}
|
||||
className="flex cursor-pointer items-baseline gap-2.5 rounded-lg border border-border/60 px-3 py-2"
|
||||
>
|
||||
<Checkbox
|
||||
checked={!deselected.has(candidate.path)}
|
||||
onCheckedChange={(checked) => {
|
||||
setDeselected((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (checked === true) next.delete(candidate.path);
|
||||
else next.add(candidate.path);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-xs">{candidate.path}</span>
|
||||
<span className="shrink-0 text-[11px] text-muted-foreground">
|
||||
{candidate.sources.map(formatSource).join(", ")} · {candidate.threadCount}{" "}
|
||||
{candidate.threadCount === 1 ? "thread" : "threads"}
|
||||
{candidate.lastActiveAt ? ` · ${formatRelativeTime(candidate.lastActiveAt)}` : ""}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{importError ? <p className="mt-3 text-sm text-destructive">{importError}</p> : null}
|
||||
<div className="mt-6 flex items-center justify-between">
|
||||
<Button variant="ghost" disabled={isImporting} onClick={onDone}>
|
||||
Skip
|
||||
</Button>
|
||||
<Button
|
||||
disabled={isImporting || selectedCount === 0}
|
||||
onClick={() =>
|
||||
void runImport(candidates.filter((candidate) => !deselected.has(candidate.path)))
|
||||
}
|
||||
>
|
||||
{isImporting ? "Importing…" : `Import ${selectedCount}`}
|
||||
</Button>
|
||||
</div>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StepShell
|
||||
title="Bring your work with you"
|
||||
description={`Found ${recent.length} ${recent.length === 1 ? "project" : "projects"} active in the last 30 days on ${machineLabel}, from Claude Code and Codex.${older > 0 ? ` ${older} older ${older === 1 ? "project is" : "projects are"} available too.` : ""}`}
|
||||
>
|
||||
{importError ? <p className="mt-3 text-sm text-destructive">{importError}</p> : null}
|
||||
<div className="mt-6 flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
disabled={isImporting || recent.length === 0}
|
||||
onClick={() => void runImport(recent)}
|
||||
>
|
||||
{isImporting ? "Importing…" : `Import recent (${recent.length})`}
|
||||
</Button>
|
||||
<Button variant="outline" disabled={isImporting} onClick={() => setChoosing(true)}>
|
||||
Choose…
|
||||
</Button>
|
||||
<Button variant="ghost" disabled={isImporting} onClick={onDone}>
|
||||
Skip
|
||||
</Button>
|
||||
</div>
|
||||
<p className="mt-4 text-xs text-muted-foreground">
|
||||
Imports projects only. Thread history import coming soon.
|
||||
</p>
|
||||
</StepShell>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Shared bits ──────────────────────────────────────────────
|
||||
|
||||
function StepShell({
|
||||
title,
|
||||
description,
|
||||
onBack,
|
||||
children,
|
||||
}: {
|
||||
readonly title: string;
|
||||
readonly description?: string;
|
||||
readonly onBack?: () => void;
|
||||
readonly children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{onBack ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
className="mt-3 inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ChevronLeftIcon className="size-3.5" />
|
||||
Back
|
||||
</button>
|
||||
) : null}
|
||||
<h1
|
||||
className={cn(
|
||||
"text-2xl font-semibold tracking-tight sm:text-3xl",
|
||||
onBack ? "mt-2" : "mt-3",
|
||||
)}
|
||||
>
|
||||
{title}
|
||||
</h1>
|
||||
{description ? (
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandBlock({
|
||||
command,
|
||||
className,
|
||||
prominent = false,
|
||||
}: {
|
||||
readonly command: string;
|
||||
readonly className?: string;
|
||||
readonly prominent?: boolean;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-3 rounded-lg border border-border/70 bg-background/60 font-mono",
|
||||
prominent ? "px-4 py-3.5 text-base" : "px-3 py-2.5 text-sm",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="min-w-0 truncate">
|
||||
<span className="mr-2 text-muted-foreground">$</span>
|
||||
{command}
|
||||
</span>
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
aria-label="Copy command"
|
||||
onClick={() => {
|
||||
void navigator.clipboard.writeText(command);
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1500);
|
||||
}}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatSource(source: "claudeAgent" | "codex"): string {
|
||||
return source === "claudeAgent" ? "Claude" : "Codex";
|
||||
}
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const deltaMs = Date.now() - Date.parse(iso);
|
||||
const minutes = Math.round(deltaMs / 60_000);
|
||||
if (minutes < 60) return `${Math.max(minutes, 1)}m ago`;
|
||||
const hours = Math.round(minutes / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
const days = Math.round(hours / 24);
|
||||
if (days < 30) return `${days}d ago`;
|
||||
const months = Math.round(days / 30);
|
||||
return `${months}mo ago`;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { useUpdateClientSettings } from "../hooks/useSettings";
|
||||
|
||||
/**
|
||||
* Marks first-run onboarding finished (or skipped) so FirstRunGate never
|
||||
* routes to the welcome wizard again. The gate itself lives in
|
||||
* `components/onboarding/FirstRunGate.tsx`.
|
||||
*/
|
||||
export function useCompleteOnboarding(): () => void {
|
||||
const updateClientSettings = useUpdateClientSettings();
|
||||
return useCallback(() => {
|
||||
updateClientSettings({ onboardingCompletedAt: new Date().toISOString() });
|
||||
}, [updateClientSettings]);
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as WelcomeRouteImport } from './routes/welcome'
|
||||
import { Route as SettingsRouteImport } from './routes/settings'
|
||||
import { Route as PairRouteImport } from './routes/pair'
|
||||
import { Route as ConnectRouteImport } from './routes/connect'
|
||||
@@ -27,6 +28,11 @@ import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
|
||||
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
|
||||
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
|
||||
|
||||
const WelcomeRoute = WelcomeRouteImport.update({
|
||||
id: '/welcome',
|
||||
path: '/welcome',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const SettingsRoute = SettingsRouteImport.update({
|
||||
id: '/settings',
|
||||
path: '/settings',
|
||||
@@ -118,6 +124,7 @@ export interface FileRoutesByFullPath {
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/welcome': typeof WelcomeRoute
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -135,6 +142,7 @@ export interface FileRoutesByTo {
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/welcome': typeof WelcomeRoute
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -155,6 +163,7 @@ export interface FileRoutesById {
|
||||
'/connect': typeof ConnectRoute
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/welcome': typeof WelcomeRoute
|
||||
'/connect_/callback': typeof ConnectCallbackRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
@@ -176,6 +185,7 @@ export interface FileRouteTypes {
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/welcome'
|
||||
| '/connect/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
@@ -193,6 +203,7 @@ export interface FileRouteTypes {
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/welcome'
|
||||
| '/connect/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
@@ -212,6 +223,7 @@ export interface FileRouteTypes {
|
||||
| '/connect'
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/welcome'
|
||||
| '/connect_/callback'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
@@ -232,11 +244,19 @@ export interface RootRouteChildren {
|
||||
ConnectRoute: typeof ConnectRoute
|
||||
PairRoute: typeof PairRoute
|
||||
SettingsRoute: typeof SettingsRouteWithChildren
|
||||
WelcomeRoute: typeof WelcomeRoute
|
||||
ConnectCallbackRoute: typeof ConnectCallbackRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/welcome': {
|
||||
id: '/welcome'
|
||||
path: '/welcome'
|
||||
fullPath: '/welcome'
|
||||
preLoaderRoute: typeof WelcomeRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/settings': {
|
||||
id: '/settings'
|
||||
path: '/settings'
|
||||
@@ -406,6 +426,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
ConnectRoute: ConnectRoute,
|
||||
PairRoute: PairRoute,
|
||||
SettingsRoute: SettingsRouteWithChildren,
|
||||
WelcomeRoute: WelcomeRoute,
|
||||
ConnectCallbackRoute: ConnectCallbackRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
|
||||
@@ -14,6 +14,7 @@ import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";
|
||||
import { resolveServerBackedAppDisplayName } from "../branding.logic";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import { CommandPalette } from "../components/CommandPalette";
|
||||
import { FirstRunGate } from "../components/onboarding/FirstRunGate";
|
||||
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
|
||||
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
|
||||
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
|
||||
@@ -106,6 +107,17 @@ function RootRouteView() {
|
||||
);
|
||||
}
|
||||
|
||||
// The welcome wizard is full-screen like /pair, but keeps toasts so its
|
||||
// connect/import actions can report failures.
|
||||
if (pathname === "/welcome") {
|
||||
return (
|
||||
<ToastProvider>
|
||||
<DocumentTitleSync />
|
||||
<Outlet />
|
||||
</ToastProvider>
|
||||
);
|
||||
}
|
||||
|
||||
if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
|
||||
return (
|
||||
<>
|
||||
@@ -123,20 +135,26 @@ function RootRouteView() {
|
||||
</CommandPalette>
|
||||
);
|
||||
|
||||
// FirstRunGate holds back everything below it — including EventRouter,
|
||||
// whose welcome payload navigates into a thread — until the first-run
|
||||
// decision is known, so a fresh install renders nothing (not the shell,
|
||||
// not a flash of threads) before landing on the welcome wizard.
|
||||
return (
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
<DocumentTitleSync />
|
||||
<GlassAppearanceSync />
|
||||
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
|
||||
<RelayClientInstallDialog />
|
||||
<ConnectOnboardingDialog />
|
||||
<SshPasswordPromptDialog />
|
||||
<SlowRpcRequestToastCoordinator />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{appShell}
|
||||
<FirstRunGate>
|
||||
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
|
||||
<RelayClientInstallDialog />
|
||||
<ConnectOnboardingDialog />
|
||||
<SshPasswordPromptDialog />
|
||||
<SlowRpcRequestToastCoordinator />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{appShell}
|
||||
</FirstRunGate>
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
);
|
||||
|
||||
@@ -80,6 +80,8 @@ function IndexDraftLanding() {
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
// First-run routing to the welcome wizard happens in FirstRunGate at the
|
||||
// root, before this route ever renders.
|
||||
return <NoProjectsHero />;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { WelcomeWizard } from "../components/onboarding/WelcomeWizard";
|
||||
|
||||
/**
|
||||
* First-run welcome wizard. Full-screen, outside the sidebar shell (the root
|
||||
* route mounts this path bare, like /pair). Reached only via the first-run
|
||||
* gate on the index route; visiting it directly after onboarding is harmless —
|
||||
* finishing again just refreshes the completion flag.
|
||||
*/
|
||||
export const Route = createFileRoute("/welcome")({
|
||||
beforeLoad: ({ context }) => {
|
||||
const { authGateState } = context;
|
||||
if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
|
||||
throw redirect({ to: "/pair", replace: true });
|
||||
}
|
||||
},
|
||||
component: WelcomeRouteView,
|
||||
});
|
||||
|
||||
function WelcomeRouteView() {
|
||||
const { authGateState } = Route.useRouteContext();
|
||||
const navigate = useNavigate();
|
||||
// An authenticated gate means a primary server is serving this app —
|
||||
// desktop, `npx t3`, or a dev server — and that server is "this machine"
|
||||
// no matter what hostname the browser used. Only hosted-static has no
|
||||
// local server to offer.
|
||||
const localAvailable = authGateState.status === "authenticated";
|
||||
return (
|
||||
<WelcomeWizard
|
||||
localAvailable={localAvailable}
|
||||
onDone={() => {
|
||||
void navigate({ to: "/", replace: true });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { createEnvironmentRpcQueryAtomFamily } from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
|
||||
/**
|
||||
* Scan of Claude Code / Codex home directories on an environment, surfacing
|
||||
* project candidates for the welcome wizard's import step. The scan walks the
|
||||
* filesystem server-side, so results are cached briefly and refreshed when the
|
||||
* import step remounts.
|
||||
*/
|
||||
export const agentSessionScan = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, {
|
||||
label: "environment-data:agent-sessions:scan",
|
||||
tag: WS_METHODS.agentSessionsScan,
|
||||
staleTimeMs: 30_000,
|
||||
idleTtlMs: 5 * 60_000,
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
# Welcome Wizard
|
||||
|
||||
On a fresh install, T3 Code opens a short setup flow before the main app.
|
||||
Existing installs never see it.
|
||||
|
||||
## Choose how to connect
|
||||
|
||||
- **Local Only** — agents run on this machine. No account needed. Shown on the
|
||||
desktop app and locally served web app.
|
||||
- **T3 Connect** — sign in and reach any of your machines from anywhere.
|
||||
Machines signed into your account connect automatically. If none are
|
||||
connected yet, the wizard shows the command to run on the machine with your
|
||||
code (`npx t3 connect`) and advances when it appears.
|
||||
- **Direct** — connect to a server by URL. Works over LAN and Tailscale. Run
|
||||
`npx t3 pair` on the server and paste the pairing URL it prints.
|
||||
|
||||
## Set up your agents
|
||||
|
||||
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.
|
||||
|
||||
## Import your projects
|
||||
|
||||
T3 Code scans the connected machine for directories where Claude Code or Codex
|
||||
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.
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { IsoDateTime, NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
|
||||
/** Coding agent home directories the scanner knows how to read. */
|
||||
export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex"]);
|
||||
export type AgentSessionSource = typeof AgentSessionSource.Type;
|
||||
|
||||
/**
|
||||
* Empty for now. Kept as a struct so future scan options (source filters,
|
||||
* explicit roots) can be added without a new method.
|
||||
*/
|
||||
export const AgentSessionScanInput = Schema.Struct({});
|
||||
export type AgentSessionScanInput = typeof AgentSessionScanInput.Type;
|
||||
|
||||
/**
|
||||
* A directory that at least one agent CLI has run in, suitable for import as a
|
||||
* T3 Code project. `alreadyImported` marks candidates that already have an
|
||||
* active project rooted at the same path.
|
||||
*/
|
||||
export const AgentSessionProjectCandidate = Schema.Struct({
|
||||
path: TrimmedNonEmptyString,
|
||||
title: TrimmedNonEmptyString,
|
||||
sources: Schema.Array(AgentSessionSource),
|
||||
threadCount: NonNegativeInt,
|
||||
lastActiveAt: Schema.NullOr(IsoDateTime),
|
||||
alreadyImported: Schema.Boolean,
|
||||
});
|
||||
export type AgentSessionProjectCandidate = typeof AgentSessionProjectCandidate.Type;
|
||||
|
||||
export const AgentSessionScanResult = Schema.Struct({
|
||||
candidates: Schema.Array(AgentSessionProjectCandidate),
|
||||
scannedAt: IsoDateTime,
|
||||
});
|
||||
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,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
@@ -23,6 +23,7 @@ export * from "./t3ProjectFile.ts";
|
||||
export * from "./editor.ts";
|
||||
export * from "./project.ts";
|
||||
export * from "./filesystem.ts";
|
||||
export * from "./agentSessions.ts";
|
||||
export * from "./assets.ts";
|
||||
export * from "./review.ts";
|
||||
export * from "./preview.ts";
|
||||
|
||||
@@ -18,6 +18,11 @@ import {
|
||||
FilesystemBrowseResult,
|
||||
FilesystemBrowseError,
|
||||
} from "./filesystem.ts";
|
||||
import {
|
||||
AgentSessionScanInput,
|
||||
AgentSessionScanResult,
|
||||
AgentSessionScanError,
|
||||
} from "./agentSessions.ts";
|
||||
import { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
@@ -180,6 +185,9 @@ export const WS_METHODS = {
|
||||
filesystemBrowse: "filesystem.browse",
|
||||
assetsCreateUrl: "assets.createUrl",
|
||||
|
||||
// Agent session discovery methods
|
||||
agentSessionsScan: "agentSessions.scan",
|
||||
|
||||
// VCS methods
|
||||
vcsPull: "vcs.pull",
|
||||
vcsRefreshStatus: "vcs.refreshStatus",
|
||||
@@ -477,6 +485,12 @@ export const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {
|
||||
error: Schema.Union([FilesystemBrowseError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsAgentSessionsScanRpc = Rpc.make(WS_METHODS.agentSessionsScan, {
|
||||
payload: AgentSessionScanInput,
|
||||
success: AgentSessionScanResult,
|
||||
error: Schema.Union([AgentSessionScanError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, {
|
||||
payload: AssetCreateUrlInput,
|
||||
success: AssetCreateUrlResult,
|
||||
@@ -816,6 +830,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsProjectsWriteFileRpc,
|
||||
WsShellOpenInEditorRpc,
|
||||
WsFilesystemBrowseRpc,
|
||||
WsAgentSessionsScanRpc,
|
||||
WsAssetsCreateUrlRpc,
|
||||
WsSubscribeVcsStatusRpc,
|
||||
WsVcsPullRpc,
|
||||
|
||||
@@ -80,6 +80,14 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
glassOpacity: GlassOpacity.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),
|
||||
),
|
||||
// When the first-run welcome wizard finished (or was skipped), as an ISO
|
||||
// timestamp. `null` alone does not mean "show the wizard" — every install
|
||||
// that predates this field decodes to `null` — so the gate also requires an
|
||||
// empty workspace (no projects or threads) before it treats the client as a
|
||||
// fresh install.
|
||||
onboardingCompletedAt: Schema.NullOr(Schema.String).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(null)),
|
||||
),
|
||||
// Model favorites. Historically keyed by provider kind, now
|
||||
// widened to `ProviderInstanceId` so users can favorite a specific model
|
||||
// on a custom provider instance (e.g. "Codex Personal · gpt-5") without
|
||||
@@ -690,6 +698,7 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
|
||||
glassOpacity: Schema.optionalKey(GlassOpacity),
|
||||
onboardingCompletedAt: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
favorites: Schema.optionalKey(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
|
||||
Reference in new issue
Block a user