Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): keep init progress on one line (#99)

Ruic707ca3699aa
diff --git a/.changeset/calm-init-progress.md b/.changeset/calm-init-progress.md
new file mode 100644
index 000000000..3a53f3bae
--- /dev/null
+++ b/.changeset/calm-init-progress.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Keep `eve init` and local `eve dev` progress on one terminal row. Init now includes elapsed completion times and preserves useful package-manager diagnostics on failure. With `EVE_LOG_LEVEL=debug`, both commands use plain phase logs instead of animation.
diff --git a/packages/eve/src/cli/banner.ts b/packages/eve/src/cli/banner.ts
index 02ae34a6a..f709b8a2e 100644
--- a/packages/eve/src/cli/banner.ts
+++ b/packages/eve/src/cli/banner.ts
@@ -13,5 +13,5 @@ export const EVE_BETA_TERMS_URL = "https://vercel.com/docs/release-phases/public
*/
export function eveCliBanner(): string {
const { version } = resolveInstalledPackageInfo();
- return `${pc.bgBlack(pc.white(` ${EVE_WORDMARK} `))} ${pc.dim(`v${version}`)}`;
+ return `${pc.bgBlack(pc.white(`☰${EVE_WORDMARK} `))} ${pc.dim(`v${version}`)}`;
}
diff --git a/packages/eve/src/cli/commands/init-git.scenario.test.ts b/packages/eve/src/cli/commands/init-git.scenario.test.ts
index e5106cc84..93a364d67 100644
--- a/packages/eve/src/cli/commands/init-git.scenario.test.ts
+++ b/packages/eve/src/cli/commands/init-git.scenario.test.ts
@@ -32,7 +32,7 @@ describe("tryInitializeGit", () => {
delete process.env.GIT_COMMITTER_NAME;
try {
- expect(tryInitializeGit(projectPath)).toMatchObject({ kind: "failed" });
+ await expect(tryInitializeGit(projectPath)).resolves.toMatchObject({ kind: "failed" });
await expect(pathExists(join(projectPath, ".git"))).resolves.toBe(false);
} finally {
process.env = previousEnv;
diff --git a/packages/eve/src/cli/commands/init-git.ts b/packages/eve/src/cli/commands/init-git.ts
index b4c9c0891..61371461f 100644
--- a/packages/eve/src/cli/commands/init-git.ts
+++ b/packages/eve/src/cli/commands/init-git.ts
@@ -1,54 +1,48 @@
-import { execSync } from "node:child_process";
-import { rmSync } from "node:fs";
+import { execFile, type ExecFileOptions } from "node:child_process";
+import { rm } from "node:fs/promises";
import { join } from "node:path";
+import { promisify } from "node:util";
const GIT_TIMEOUT_MS = 5_000;
+const runFile = promisify(execFile);
export type GitInitResult =
| { kind: "initialized" }
| { kind: "skipped" }
| { kind: "failed"; reason: string };
-function isGitAvailable(): boolean {
+async function commandSucceeds(
+ command: string,
+ args: readonly string[],
+ cwd?: string,
+): Promise<boolean> {
try {
- execSync("git --version", { stdio: "ignore", timeout: GIT_TIMEOUT_MS });
+ const options: ExecFileOptions = { timeout: GIT_TIMEOUT_MS, windowsHide: true };
+ if (cwd !== undefined) options.cwd = cwd;
+ await runFile(command, [...args], options);
return true;
} catch {
return false;
}
}
-function isInsideExistingRepository(cwd: string): boolean {
- try {
- execSync("git rev-parse --is-inside-work-tree", {
- cwd,
- stdio: "ignore",
- timeout: GIT_TIMEOUT_MS,
- });
- return true;
- } catch {
- // Fall through to the Mercurial probe.
- }
+function isGitAvailable(): Promise<boolean> {
+ return commandSucceeds("git", ["--version"]);
+}
- try {
- execSync("hg --cwd . root", { cwd, stdio: "ignore", timeout: GIT_TIMEOUT_MS });
- return true;
- } catch {
- return false;
- }
+async function isInsideExistingRepository(cwd: string): Promise<boolean> {
+ return (
+ (await commandSucceeds("git", ["rev-parse", "--is-inside-work-tree"], cwd)) ||
+ (await commandSucceeds("hg", ["--cwd", ".", "root"], cwd))
+ );
}
-function hasConfiguredDefaultBranch(cwd: string): boolean {
- try {
- execSync("git config init.defaultBranch", {
- cwd,
- stdio: "ignore",
- timeout: GIT_TIMEOUT_MS,
- });
- return true;
- } catch {
- return false;
- }
+function hasConfiguredDefaultBranch(cwd: string): Promise<boolean> {
+ return commandSucceeds("git", ["config", "init.defaultBranch"], cwd);
+}
+
+async function runGit(cwd: string, args: readonly string[]): Promise<void> {
+ await runFile("git", [...args], { cwd, timeout: GIT_TIMEOUT_MS, windowsHide: true });
}
/**
@@ -57,38 +51,26 @@ function hasConfiguredDefaultBranch(cwd: string): boolean {
* initialization is removed and returned as a `failed` result; presenting the
* failure (without failing `eve init`) is the caller's job.
*/
-export function tryInitializeGit(projectPath: string): GitInitResult {
- if (!isGitAvailable() || isInsideExistingRepository(projectPath)) {
+export async function tryInitializeGit(projectPath: string): Promise<GitInitResult> {
+ if (!(await isGitAvailable()) || (await isInsideExistingRepository(projectPath))) {
return { kind: "skipped" };
}
let initialized = false;
try {
- execSync("git init", { cwd: projectPath, stdio: "ignore", timeout: GIT_TIMEOUT_MS });
+ await runGit(projectPath, ["init"]);
initialized = true;
- if (!hasConfiguredDefaultBranch(projectPath)) {
- execSync("git checkout -b main", {
- cwd: projectPath,
- stdio: "ignore",
- timeout: GIT_TIMEOUT_MS,
- });
+ if (!(await hasConfiguredDefaultBranch(projectPath))) {
+ await runGit(projectPath, ["checkout", "-b", "main"]);
}
- execSync("git add -A", { cwd: projectPath, stdio: "ignore", timeout: GIT_TIMEOUT_MS });
- execSync('git commit -m "Initial commit from eve"', {
- cwd: projectPath,
- stdio: "ignore",
- timeout: GIT_TIMEOUT_MS,
- });
+ await runGit(projectPath, ["add", "-A"]);
+ await runGit(projectPath, ["commit", "-m", "Initial commit from eve"]);
return { kind: "initialized" };
} catch (error) {
if (initialized) {
- try {
- rmSync(join(projectPath, ".git"), { recursive: true, force: true });
- } catch {
- // Best-effort cleanup.
- }
+ await rm(join(projectPath, ".git"), { recursive: true, force: true }).catch(() => {});
}
const reason = error instanceof Error ? error.message : String(error);
diff --git a/packages/eve/src/cli/commands/init.integration.test.ts b/packages/eve/src/cli/commands/init.integration.test.ts
index aca2ddb50..e22a4ff46 100644
--- a/packages/eve/src/cli/commands/init.integration.test.ts
+++ b/packages/eve/src/cli/commands/init.integration.test.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { MockScreen } from "#cli/dev/tui/test/mock-terminal.js";
import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
import { detectPackageManager } from "#setup/package-manager.js";
import {
@@ -62,6 +63,7 @@ function dependencies(
typeof vi.fn<InitCommandDependencies["detectInvokingPackageManager"]>
>;
isCodingAgentLaunch: ReturnType<typeof vi.fn<InitCommandDependencies["isCodingAgentLaunch"]>>;
+ now: ReturnType<typeof vi.fn<InitCommandDependencies["now"]>>;
runPackageManagerInstall: ReturnType<
typeof vi.fn<InitCommandDependencies["runPackageManagerInstall"]>
>;
@@ -82,6 +84,7 @@ function dependencies(
// Stubbed to "human launch" for the same reason: the runner is often
// launched by a coding agent, and these tests assert the human path.
isCodingAgentLaunch: vi.fn(async () => false),
+ now: vi.fn(() => 0),
detectPackageManager,
scaffoldBaseProject: (options: ScaffoldBaseProjectOptions) => {
const merged = { ...BASE_VERSIONS, ...options };
@@ -97,7 +100,7 @@ function dependencies(
}),
runPackageManagerInstall: vi.fn(async () => true),
spawnPackageManager: vi.fn(async () => true),
- tryInitializeGit: vi.fn(() => gitResult),
+ tryInitializeGit: vi.fn(async () => gitResult),
};
}
@@ -127,6 +130,11 @@ describe("runInitCommand", () => {
const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-base-"));
const output = logger();
const deps = dependencies();
+ deps.now
+ .mockReturnValueOnce(0)
+ .mockReturnValueOnce(467)
+ .mockReturnValueOnce(467)
+ .mockReturnValueOnce(13_667);
await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
@@ -167,11 +175,13 @@ describe("runInitCommand", () => {
// decides at import time whether the strings carry escape codes. The boot
// banner is the CLI program's pre-action hook, not the command's output.
expect(output.messages).toHaveLength(4);
- expect(output.messages[0]).toContain("✓");
- expect(output.messages[0]).toContain("Created an eve agent in ");
- expect(output.messages[0]).toContain(projectPath);
- expect(output.messages[1]).toContain("Installing dependencies...");
+ expect(output.messages[0]).toContain("Preparing project...");
+ expect(output.messages[1]).toContain("✓");
+ expect(output.messages[1]).toContain("Created an eve agent in ");
+ expect(output.messages[1]).toContain(projectPath);
+ expect(output.messages[1]).toContain("in 467ms");
expect(output.messages[2]).toContain("Installed dependencies");
+ expect(output.messages[2]).toContain("in 13.2s");
expect(output.messages[3]).toContain("$ eve dev --input /model");
});
@@ -233,8 +243,8 @@ describe("runInitCommand", () => {
"--input",
"/model",
]);
- expect(output.messages[0]).toContain("Created an eve agent in ");
- expect(output.messages[0]).toContain(projectPath);
+ expect(output.messages[1]).toContain("Created an eve agent in ");
+ expect(output.messages[1]).toContain(projectPath);
},
);
@@ -702,6 +712,7 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
deps.runPackageManagerInstall.mockImplementation(async (_kind, _projectPath, options) => {
+ options?.onOutput?.({ stream: "stdout", text: "Packages: +12" });
options?.onOutput?.({ stream: "stderr", text: "ERR_PNPM_FETCH_404 not found" });
return false;
});
@@ -711,8 +722,190 @@ describe("runInitCommand", () => {
);
await expect(pathExists(join(parentDirectory, "my-agent"))).resolves.toBe(true);
- expect(output.errors.join("\n")).toContain("ERR_PNPM_FETCH_404 not found");
+ expect(output.errors).toEqual(["Packages: +12", "ERR_PNPM_FETCH_404 not found"]);
expect(deps.tryInitializeGit).not.toHaveBeenCalled();
expect(deps.spawnPackageManager).not.toHaveBeenCalled();
});
+
+ it("replays only the actionable npm error, dropping silly/verbose/http/timing noise", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-npm-noise-"));
+ const output = logger();
+ const deps = dependencies();
+ deps.runPackageManagerInstall.mockImplementation(async (_kind, _projectPath, options) => {
+ options?.onOutput?.({ stream: "stderr", text: "npm silly logfile start cleaning logs" });
+ options?.onOutput?.({ stream: "stderr", text: "npm verbose cli /usr/local/bin/node" });
+ options?.onOutput?.({
+ stream: "stderr",
+ text: "npm http fetch GET 200 https://registry.npmjs.org/eve 41ms",
+ });
+ options?.onOutput?.({ stream: "stderr", text: "npm timing idealTree Completed in 42ms" });
+ options?.onOutput?.({ stream: "stderr", text: "npm error code ERESOLVE" });
+ options?.onOutput?.({
+ stream: "stderr",
+ text: "npm error ERESOLVE unable to resolve dependency tree",
+ });
+ return false;
+ });
+
+ await expect(runInitCommand(output, parentDirectory, "my-agent", {}, deps)).rejects.toThrow(
+ "Failed to install dependencies",
+ );
+
+ expect(output.errors).toEqual([
+ "npm error code ERESOLVE",
+ "npm error ERESOLVE unable to resolve dependency tree",
+ ]);
+ expect(output.errors.join("\n")).not.toMatch(/npm (?:silly|verbose|http|timing)/u);
+ });
+
+ it("replays only the final npm detail lines when filtering leaves no error", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-npm-fallback-"));
+ const output = logger();
+ const deps = dependencies();
+ deps.runPackageManagerInstall.mockImplementation(async (_kind, _projectPath, options) => {
+ for (let index = 0; index < 25; index += 1) {
+ options?.onOutput?.({ stream: "stderr", text: `npm silly step ${index}` });
+ }
+ options?.onOutput?.({ stream: "stderr", text: "" });
+ return false;
+ });
+
+ await expect(runInitCommand(output, parentDirectory, "my-agent", {}, deps)).rejects.toThrow(
+ "Failed to install dependencies",
+ );
+
+ expect(output.errors).toHaveLength(20);
+ expect(output.errors.at(0)).toBe("npm silly step 5");
+ expect(output.errors.at(-1)).toBe("npm silly step 24");
+ });
+
+ it("streams init phases and package-manager output as debug logs", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-debug-"));
+ const output = logger();
+ const deps = dependencies();
+ deps.runPackageManagerInstall.mockImplementation(async (_kind, _projectPath, options) => {
+ options?.onOutput?.({ stream: "stdout", text: "Progress: resolved 62, reused 62, done" });
+ return true;
+ });
+
+ const previous = process.env.EVE_LOG_LEVEL;
+ process.env.EVE_LOG_LEVEL = "debug";
+ const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
+ const debugLines = consoleLog.mock.calls.map((call) => String(call[0]));
+ expect(debugLines).toContain("[eve:init] creating agent");
+ expect(
+ debugLines.some((line) => line.startsWith("[eve:init] installing dependencies with")),
+ ).toBe(true);
+ expect(debugLines).toContain("[eve:init] Progress: resolved 62, reused 62, done");
+ expect(debugLines).toContain("[eve:init] initializing git repository");
+ expect(deps.runPackageManagerInstall).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.objectContaining({ progressDetails: false }),
+ );
+ } finally {
+ consoleLog.mockRestore();
+ if (previous === undefined) {
+ delete process.env.EVE_LOG_LEVEL;
+ } else {
+ process.env.EVE_LOG_LEVEL = previous;
+ }
+ }
+ });
+
+ it("reports a failed install as failed under debug", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-debug-failure-"));
+ const output = logger();
+ const deps = dependencies();
+ deps.runPackageManagerInstall.mockResolvedValue(false);
+
+ const previous = process.env.EVE_LOG_LEVEL;
+ process.env.EVE_LOG_LEVEL = "debug";
+ const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ await expect(runInitCommand(output, parentDirectory, "my-agent", {}, deps)).rejects.toThrow(
+ "Failed to install dependencies",
+ );
+ const debugLines = consoleLog.mock.calls.map((call) => String(call[0]));
+ expect(debugLines.some((line) => line.includes("dependency installation failed"))).toBe(true);
+ expect(debugLines.some((line) => line.includes("dependencies installed"))).toBe(false);
+ } finally {
+ consoleLog.mockRestore();
+ if (previous === undefined) {
+ delete process.env.EVE_LOG_LEVEL;
+ } else {
+ process.env.EVE_LOG_LEVEL = previous;
+ }
+ }
+ });
+
+ it("keeps interactive progress on one physical row", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-progress-"));
+ const output = logger();
+ const deps = dependencies();
+ const screen = new MockScreen({ columns: 80, rows: 10 });
+ const snapshots: string[] = [];
+ const isTtyDescriptor = Object.getOwnPropertyDescriptor(process.stdout, "isTTY");
+ const columnsDescriptor = Object.getOwnPropertyDescriptor(process.stdout, "columns");
+
+ Object.defineProperty(process.stdout, "isTTY", { configurable: true, value: true });
+ Object.defineProperty(process.stdout, "columns", { configurable: true, value: screen.columns });
+ vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array) => {
+ screen.write(chunk);
+ snapshots.push(screen.snapshot());
+ return true;
+ });
+ deps.isCodingAgentLaunch.mockResolvedValue(true);
+ deps.detectInvokingPackageManager.mockReturnValue("npm");
+ deps.runPackageManagerInstall.mockImplementation(async (_kind, _projectPath, options) => {
+ options?.onOutput?.({ stream: "stderr", text: "npm silly config load:file:/tmp/.npmrc" });
+ options?.onOutput?.({
+ stream: "stderr",
+ text: "npm silly fetch manifest @vercel/[email protected]",
+ });
+ options?.onOutput?.({ stream: "stderr", text: "npm silly fetch manifest [email protected]" });
+ options?.onOutput?.({
+ stream: "stderr",
+ text: "npm http fetch GET https://registry.npmjs.org/@vercel%2fconnect attempt 1 failed with ENOTFOUND",
+ });
+ options?.onOutput?.({ stream: "stdout", text: `Downloading ${"package".repeat(20)}` });
+ return true;
+ });
+
+ try {
+ await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
+ } finally {
+ if (isTtyDescriptor === undefined) {
+ Reflect.deleteProperty(process.stdout, "isTTY");
+ } else {
+ Object.defineProperty(process.stdout, "isTTY", isTtyDescriptor);
+ }
+ if (columnsDescriptor === undefined) {
+ Reflect.deleteProperty(process.stdout, "columns");
+ } else {
+ Object.defineProperty(process.stdout, "columns", columnsDescriptor);
+ }
+ }
+
+ const rendered = snapshots.join("\n");
+ expect(rendered).toContain("Preparing project");
+ expect(rendered).toContain("Creating agent");
+ expect(rendered).toContain("Installing dependencies");
+ expect(rendered).toContain("npm install");
+ expect(rendered).toContain("Resolving @vercel/[email protected]");
+ expect(rendered).toContain("npm registry · attempt 1 failed: ENOTFOUND");
+ expect(rendered).not.toContain("config load:file");
+ expect(rendered).toContain("Initializing Git repository");
+ expect(deps.runPackageManagerInstall).toHaveBeenCalledWith(
+ "npm",
+ join(parentDirectory, "my-agent"),
+ expect.objectContaining({ progressDetails: true }),
+ );
+ for (const snapshot of snapshots.filter(Boolean)) {
+ expect(snapshot.split("\n")).toHaveLength(1);
+ expect([...snapshot].length).toBeLessThan(screen.columns);
+ }
+ });
});
diff --git a/packages/eve/src/cli/commands/init.ts b/packages/eve/src/cli/commands/init.ts
index b2ea4f1cb..a8acdbf4f 100644
--- a/packages/eve/src/cli/commands/init.ts
+++ b/packages/eve/src/cli/commands/init.ts
@@ -1,12 +1,15 @@
import { mkdtemp, readdir, rename, rm, stat } from "node:fs/promises";
import { basename, join, resolve } from "node:path";
+import { performance } from "node:perf_hooks";
import pc from "picocolors";
import { isCodingAgentLaunch } from "#cli/agent-detection.js";
import { EVE_WORDMARK } from "#cli/banner.js";
+import { formatElapsed } from "#cli/format-elapsed.js";
+import { startCliLiveRow } from "#cli/ui/live-row.js";
+import { createLogger, isLogLevelEnabled } from "#internal/logging.js";
import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
-import { SPINNER_FRAME_MS, SPINNER_FRAMES } from "#setup/cli/rail-log.js";
import { formatNodeEngineOverrideWarning, type NodeEngineOverride } from "#setup/node-engine.js";
import {
detectInvokingPackageManager,
@@ -20,6 +23,7 @@ import {
runPackageManagerInstall,
spawnPackageManager,
} from "#setup/primitives/index.js";
+import type { ProcessOutputLine } from "#setup/primitives/process-output.js";
import { addAgentToProject } from "#setup/scaffold/create/add-to-project.js";
import { ensureChannel, scaffoldBaseProject } from "#setup/scaffold/index.js";
import {
@@ -28,7 +32,7 @@ import {
} from "#setup/scaffold/create/project.js";
import { initAgentDevHandoff } from "./agent-instructions.js";
-import { tryInitializeGit } from "./init-git.js";
+import { tryInitializeGit, type GitInitResult } from "./init-git.js";
export interface InitCliLogger {
error(message: string): void;
@@ -46,6 +50,7 @@ export interface InitCommandDependencies {
detectPackageManager: typeof detectPackageManager;
ensureChannel: typeof ensureChannel;
isCodingAgentLaunch: typeof isCodingAgentLaunch;
+ now: () => number;
runPackageManagerInstall: typeof runPackageManagerInstall;
scaffoldBaseProject: typeof scaffoldBaseProject;
spawnPackageManager: typeof spawnPackageManager;
@@ -58,6 +63,7 @@ const defaultDependencies: InitCommandDependencies = {
detectPackageManager,
ensureChannel,
isCodingAgentLaunch,
+ now: () => performance.now(),
runPackageManagerInstall,
scaffoldBaseProject,
spawnPackageManager,
@@ -68,6 +74,8 @@ const CURRENT_DIRECTORY_PROJECT_NAME = ".";
const ALLOWED_CREATE_IN_PLACE_ENTRIES = new Set([".DS_Store", ".git", ".gitkeep", ".hg"]);
export const EVE_INIT_PACKAGE_SPEC_ENV = "EVE_INIT_PACKAGE_SPEC";
+const initLog = createLogger("init");
+
/** Resolves `target` to an existing directory, or undefined for name mode. */
async function resolveTargetDirectory(
parentDirectory: string,
@@ -196,35 +204,178 @@ async function scaffoldProject(
}
}
-/**
- * A spinner is purely a liveness affordance, so it draws only on a TTY; piped
- * output gets the pending message once and never sees redraw control codes.
- */
-function startSpinner(logger: InitCliLogger, message: string): { stop(): void } {
- if (process.stdout.isTTY !== true) {
- logger.log(message);
- return { stop() {} };
+type PreparedInitProject =
+ | {
+ kind: "added";
+ nodeEngineOverride?: NodeEngineOverride;
+ packageManager: PackageManagerKind;
+ projectPath: string;
+ }
+ | {
+ kind: "created";
+ packageManager: PackageManagerKind;
+ projectPath: string;
+ };
+
+type InitResult = {
+ agentElapsedMs: number;
+ agentLaunched: boolean;
+ installElapsedMs: number;
+ packageManager: PackageManagerKind;
+ projectPath: string;
+} & (
+ | {
+ kind: "added";
+ nodeEngineOverride?: NodeEngineOverride;
+ }
+ | {
+ gitResult: GitInitResult;
+ kind: "created";
+ }
+);
+
+function installProgressDetail(
+ packageManager: PackageManagerKind,
+ line: ProcessOutputLine,
+): string | undefined {
+ const text = line.text.trim();
+ if (text === "" || packageManager !== "npm") return text || undefined;
+
+ const manifest = /^npm silly fetch manifest (.+)$/u.exec(text);
+ if (manifest !== null) return `Resolving ${manifest[1]}`;
+
+ const failedRequest = /^npm http fetch \S+ \S+ attempt (\d+) failed with (\S+)$/u.exec(text);
+ if (failedRequest !== null) {
+ return `npm registry · attempt ${failedRequest[1]} failed: ${failedRequest[2]}`;
}
- const row = (glyph: string): string => `${pc.green(glyph)} ${message}`;
- process.stdout.write(row(SPINNER_FRAMES[0]));
- let frame = 0;
- const timer = setInterval(() => {
- frame += 1;
- const glyph = SPINNER_FRAMES[frame % SPINNER_FRAMES.length] ?? SPINNER_FRAMES[0];
- process.stdout.write(`\r\u001B[K${row(glyph)}`);
- }, SPINNER_FRAME_MS);
- timer.unref?.();
-
- let stopped = false;
- return {
- stop() {
- if (stopped) return;
- stopped = true;
- clearInterval(timer);
- process.stdout.write("\r\u001B[K");
- },
- };
+ if (line.stream === "stdout" || /^npm (?:error|warn)\b/u.test(text)) return text;
+ return undefined;
+}
+
+const NPM_NOISE_LINE = /^\s*npm (?:silly|verbose|http|timing)\b/u;
+const INSTALL_OUTPUT_FALLBACK_LINES = 20;
+
+async function runInitSteps(input: {
+ dependencies: InitCommandDependencies;
+ logger: InitCliLogger;
+ options: InitCommandOptions;
+ parentDirectory: string;
+ target: string | undefined;
+}): Promise<InitResult> {
+ const { dependencies, logger, options, parentDirectory, target } = input;
+ const debug = isLogLevelEnabled("debug");
+ const progress = startCliLiveRow(logger);
+ progress.update("Preparing project");
+
+ try {
+ const agentLaunched = await dependencies.isCodingAgentLaunch();
+ const rawTarget = target ?? CURRENT_DIRECTORY_PROJECT_NAME;
+ const currentDirectoryTarget = isCurrentDirectoryTarget(rawTarget);
+ const existingDirectory = currentDirectoryTarget
+ ? (await pathExists(join(resolve(parentDirectory), "package.json")))
+ ? resolve(parentDirectory)
+ : undefined
+ : await resolveTargetDirectory(parentDirectory, rawTarget);
+ const evePackage = resolveInitEvePackageOverride();
+
+ const scaffoldPhase = existingDirectory === undefined ? "creating agent" : "adding agent";
+ progress.update(existingDirectory === undefined ? "Creating agent" : "Adding agent");
+ initLog.debug(scaffoldPhase);
+ const agentStartedAt = dependencies.now();
+ let project: PreparedInitProject;
+ if (existingDirectory === undefined) {
+ const projectName = currentDirectoryTarget
+ ? CURRENT_DIRECTORY_PROJECT_NAME
+ : parseProjectName(rawTarget);
+ const parentPath = resolve(parentDirectory);
+ const plannedProjectPath =
+ projectName === CURRENT_DIRECTORY_PROJECT_NAME ? parentPath : join(parentPath, projectName);
+ const packageManager = await resolveScaffoldPackageManager(plannedProjectPath, dependencies);
+ const projectPath = await scaffoldProject(
+ parentDirectory,
+ projectName,
+ packageManager,
+ options,
+ dependencies,
+ evePackage,
+ );
+ project = { kind: "created", packageManager, projectPath };
+ } else {
+ const addition = await addToExistingProject(existingDirectory, options, dependencies, evePackage);
+ project =
+ addition.nodeEngineOverride === undefined
+ ? {
+ kind: "added",
+ packageManager: addition.packageManager,
+ projectPath: existingDirectory,
+ }
+ : {
+ kind: "added",
+ nodeEngineOverride: addition.nodeEngineOverride,
+ packageManager: addition.packageManager,
+ projectPath: existingDirectory,
+ };
+ }
+ const agentElapsedMs = dependencies.now() - agentStartedAt;
+ initLog.debug(`${scaffoldPhase} done`, { ms: agentElapsedMs });
+
+ progress.update("Installing dependencies", `${project.packageManager} install`);
+ initLog.debug(`installing dependencies with ${project.packageManager}`);
+ const installStartedAt = dependencies.now();
+ const installFailureOutput: string[] = [];
+ const recentInstallOutput: string[] = [];
+ const installed = await dependencies.runPackageManagerInstall(
+ project.packageManager,
+ project.projectPath,
+ {
+ // The scaffold pins versions younger than typical release-age cooldown
+ // windows; gating them would fail every fresh bootstrap.
+ bypassMinimumReleaseAge: true,
+ progressDetails: process.stdout.isTTY === true && !debug,
+ onOutput: (line) => {
+ if (line.text.trim() !== "") {
+ recentInstallOutput.push(line.text);
+ if (recentInstallOutput.length > INSTALL_OUTPUT_FALLBACK_LINES) {
+ recentInstallOutput.shift();
+ }
+ if (!NPM_NOISE_LINE.test(line.text)) {
+ installFailureOutput.push(line.text);
+ }
+ }
+ if (debug) initLog.debug(line.text);
+ const detail = installProgressDetail(project.packageManager, line);
+ if (detail !== undefined) progress.update("Installing dependencies", detail);
+ },
+ },
+ );
+ const installElapsedMs = dependencies.now() - installStartedAt;
+ if (!installed) {
+ initLog.debug("dependency installation failed", { ms: installElapsedMs });
+ progress.stop();
+ const failureOutput =
+ installFailureOutput.length > 0 ? installFailureOutput : recentInstallOutput;
+ for (const line of failureOutput) logger.error(line);
+ throw new Error(`Failed to install dependencies in "${project.projectPath}".`);
+ }
+ initLog.debug("dependencies installed", { ms: installElapsedMs });
+
+ if (project.kind === "created") {
+ progress.update("Initializing Git repository");
+ initLog.debug("initializing git repository");
+ return {
+ ...project,
+ agentElapsedMs,
+ agentLaunched,
+ gitResult: await dependencies.tryInitializeGit(project.projectPath),
+ installElapsedMs,
+ };
+ }
+
+ return { ...project, agentElapsedMs, agentLaunched, installElapsedMs };
+ } finally {
+ progress.stop();
+ }
}
/**
@@ -242,94 +393,34 @@ export async function runInitCommand(
options: InitCommandOptions,
dependencies: InitCommandDependencies = defaultDependencies,
): Promise<void> {
- const agentLaunched = await dependencies.isCodingAgentLaunch();
- const rawTarget = target ?? CURRENT_DIRECTORY_PROJECT_NAME;
- const evePackage = resolveInitEvePackageOverride();
- const currentDirectoryTarget = isCurrentDirectoryTarget(rawTarget);
- const existingDirectory = currentDirectoryTarget
- ? (await pathExists(join(resolve(parentDirectory), "package.json")))
- ? resolve(parentDirectory)
- : undefined
- : await resolveTargetDirectory(parentDirectory, rawTarget);
-
- // A fresh project inside a workspace inherits that workspace's manager before
- // considering the launcher (`npx`, `pnpm dlx`, `yarn dlx`); an existing
- // project keeps whatever manager it already uses.
- let packageManager: PackageManagerKind;
- let projectPath: string;
- let freshScaffold: boolean;
- if (existingDirectory === undefined) {
- const projectName = currentDirectoryTarget
- ? CURRENT_DIRECTORY_PROJECT_NAME
- : parseProjectName(rawTarget);
- const parentPath = resolve(parentDirectory);
- const plannedProjectPath =
- projectName === CURRENT_DIRECTORY_PROJECT_NAME ? parentPath : join(parentPath, projectName);
- packageManager = await resolveScaffoldPackageManager(plannedProjectPath, dependencies);
- projectPath = await scaffoldProject(
- parentDirectory,
- projectName,
- packageManager,
- options,
- dependencies,
- evePackage,
+ const result = await runInitSteps({ dependencies, logger, options, parentDirectory, target });
+ const freshScaffold = result.kind === "created";
+
+ if (result.kind === "created") {
+ logger.log(
+ `${pc.green("✓")} Created an ${EVE_WORDMARK} agent in ${pc.bold(result.projectPath)} ${pc.dim(`in ${formatElapsed(result.agentElapsedMs)}`)}`,
);
- freshScaffold = true;
- logger.log(`${pc.green("✓")} Created an ${EVE_WORDMARK} agent in ${pc.bold(projectPath)}`);
} else {
- const addition = await addToExistingProject(
- existingDirectory,
- options,
- dependencies,
- evePackage,
+ logger.log(
+ `${pc.green("✓")} Added an ${EVE_WORDMARK} agent to ${pc.bold(result.projectPath)} ${pc.dim(`in ${formatElapsed(result.agentElapsedMs)}`)}`,
);
- packageManager = addition.packageManager;
- projectPath = existingDirectory;
- freshScaffold = false;
- logger.log(`${pc.green("✓")} Added an ${EVE_WORDMARK} agent to ${pc.bold(projectPath)}`);
- if (addition.nodeEngineOverride !== undefined) {
- logger.log(pc.yellow(`⚠ ${formatNodeEngineOverrideWarning(addition.nodeEngineOverride)}`));
+ if (result.nodeEngineOverride !== undefined) {
+ logger.log(pc.yellow(`⚠ ${formatNodeEngineOverrideWarning(result.nodeEngineOverride)}`));
}
}
+ logger.log(
+ `${pc.green("✓")} Installed dependencies ${pc.dim(`in ${formatElapsed(result.installElapsedMs)}`)}`,
+ );
- // Install output is elided behind the spinner; it is replayed only when the
- // install fails, so the user sees the manager's diagnostics exactly when
- // relevant.
- const installLog: string[] = [];
- const spinner = startSpinner(logger, "Installing dependencies...");
- let installed: boolean;
- try {
- installed = await dependencies.runPackageManagerInstall(packageManager, projectPath, {
- // The scaffold pins versions younger than typical release-age cooldown
- // windows; gating them would fail every fresh bootstrap.
- bypassMinimumReleaseAge: true,
- onOutput: (line) => installLog.push(line.text),
- });
- } finally {
- spinner.stop();
- }
- if (!installed) {
- for (const line of installLog) {
- logger.error(line);
- }
- throw new Error(`Failed to install dependencies in "${projectPath}".`);
- }
- logger.log(`${pc.green("✓")} Installed dependencies`);
-
- // Git is initialized only for a freshly created project; an existing
- // project's history is its own.
- if (freshScaffold) {
- const gitResult = dependencies.tryInitializeGit(projectPath);
- if (gitResult.kind === "failed") {
- logger.error(pc.yellow(`Git initialization failed: ${gitResult.reason}`));
- }
+ if (result.kind === "created" && result.gitResult.kind === "failed") {
+ logger.error(pc.yellow(`Git initialization failed: ${result.gitResult.reason}`));
}
- if (agentLaunched) {
+ if (result.agentLaunched) {
logger.log(
initAgentDevHandoff({
- projectPath,
- devCommand: [packageManager, ...eveDevArguments(packageManager)].join(" "),
+ projectPath: result.projectPath,
+ devCommand: [result.packageManager, ...eveDevArguments(result.packageManager)].join(" "),
}),
);
return;
@@ -339,11 +430,17 @@ export async function runInitCommand(
// existing app may start unrelated processes. Exec-style runs do not echo
// the command the way run-scripts do, so the handoff line is printed here.
const devArguments = freshScaffold
- ? [...eveDevArguments(packageManager), "--input", "/model"]
- : eveDevArguments(packageManager);
+ ? [...eveDevArguments(result.packageManager), "--input", "/model"]
+ : eveDevArguments(result.packageManager);
logger.log(pc.dim(freshScaffold ? "$ eve dev --input /model" : "$ eve dev"));
- if (!(await dependencies.spawnPackageManager(packageManager, projectPath, devArguments))) {
- throw new Error(`Development server exited unsuccessfully in "${projectPath}".`);
+ if (
+ !(await dependencies.spawnPackageManager(
+ result.packageManager,
+ result.projectPath,
+ devArguments,
+ ))
+ ) {
+ throw new Error(`Development server exited unsuccessfully in "${result.projectPath}".`);
}
}
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 4c5662603..2db5d7cb8 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -191,9 +191,29 @@ async function settleAsyncWork(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
+ await Promise.resolve();
}
describe("EveTUIRunner agent header", () => {
+ it("reports the paint boundary before rendering the startup header", async () => {
+ const order: string[] = [];
+ const client = stubClient();
+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);
+ const runner = new EveTUIRunner({
+ session: stubSession(),
+ client,
+ renderer: fakeRenderer({
+ renderAgentHeader: () => order.push("render"),
+ }),
+ serverUrl: "http://localhost:3000",
+ onBootProgress: (event) => order.push(event.type),
+ });
+
+ await runner.run();
+
+ expect(order).toEqual(["phase-started", "phase-finished", "before-first-paint", "render"]);
+ });
+
it("fetches agent info and renders the startup header", async () => {
const headers: AgentTUIAgentHeader[] = [];
const renderer = fakeRenderer({
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index b95701469..15bb08444 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -26,6 +26,7 @@ import {
type DevelopmentRuntimeArtifactSessionRefresher,
} from "#services/dev-client.js";
import { toErrorMessage } from "#shared/errors.js";
+import { devBootPhase, type DevBootProgressReporter } from "#internal/dev-boot-progress.js";
import {
type FailureStreamEvent,
@@ -337,6 +338,8 @@ export type EveTUIRunnerOptions = TuiDisplayOptions & {
detectProjectIdentity?: typeof detectProjectIdentity;
/** Test seam for the off-critical-path boot login probe; defaults to the real one. */
getVercelAuthStatus?: typeof getVercelAuthStatus;
+ /** Reports phases from this runner's initial local-dev connection. */
+ onBootProgress?: DevBootProgressReporter;
};
/** The attention-line issue for a Vercel auth state, or undefined when nothing's wrong. */
@@ -366,6 +369,7 @@ export class EveTUIRunner {
readonly #promptCommandHandler?: PromptCommandHandler;
readonly #bootDetections: readonly BootDetection[];
readonly #getVercelAuthStatus: typeof getVercelAuthStatus;
+ #onBootProgress?: DevBootProgressReporter;
/** Set when the run loop unwinds, so a late boot login probe cannot paint into a torn-down terminal. */
#disposed = false;
/** Aborts the off-critical-path boot auth probe when the run loop unwinds. */
@@ -467,6 +471,7 @@ export class EveTUIRunner {
}
this.#bootDetections = options.bootDetections ?? BOOT_DETECTIONS;
this.#getVercelAuthStatus = options.getVercelAuthStatus ?? getVercelAuthStatus;
+ if (options.onBootProgress !== undefined) this.#onBootProgress = options.onBootProgress;
if (options.serverUrl !== undefined) {
this.#serverUrl = options.serverUrl;
this.#runtimeArtifacts = createDevelopmentRuntimeArtifactSessionRefresher({
@@ -483,13 +488,18 @@ export class EveTUIRunner {
async #renderAgentHeader(): Promise<void> {
const serverUrl = this.#serverUrl;
if (serverUrl === undefined) {
+ this.#reportBeforeFirstPaint();
await this.#renderSetupIssues(undefined);
return;
}
let info: AgentInfoResult | undefined;
try {
- info = await this.#client?.info();
+ info = await devBootPhase(
+ "connecting to agent",
+ () => (this.#client ? this.#client.info() : Promise.resolve(undefined)),
+ this.#onBootProgress,
+ );
} catch {
info = undefined;
}
@@ -501,10 +511,17 @@ export class EveTUIRunner {
};
if (info !== undefined) header.info = info;
if (this.#appRoot !== undefined) header.tip = this.#headerTip;
+ this.#reportBeforeFirstPaint();
this.#renderer.renderAgentHeader?.(header);
await this.#renderSetupIssues(info);
}
+ #reportBeforeFirstPaint(): void {
+ const report = this.#onBootProgress;
+ this.#onBootProgress = undefined;
+ report?.({ type: "before-first-paint" });
+ }
+
async run() {
try {
await this.#run();
diff --git a/packages/eve/src/cli/dev/tui/tui.ts b/packages/eve/src/cli/dev/tui/tui.ts
index b4799f2f3..c19134db8 100644
--- a/packages/eve/src/cli/dev/tui/tui.ts
+++ b/packages/eve/src/cli/dev/tui/tui.ts
@@ -5,6 +5,7 @@ import {
isVercelAuthChallenge,
} from "#services/dev-client/vercel-auth-error.js";
import { toErrorMessage } from "#shared/errors.js";
+import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
import { createPromptCommandHandler } from "./prompt-command-handler.js";
import { EveTUIRunner, type EveTUIRunnerOptions } from "./runner.js";
@@ -31,6 +32,8 @@ export interface RunDevelopmentTuiInput extends TuiDisplayOptions {
* Applies to the first prompt only.
*/
readonly initialInput?: string;
+ /** Reports local CLI boot phases. Omitted for remote and programmatic TUI runs. */
+ readonly onBootProgress?: DevBootProgressReporter;
}
/**
@@ -43,7 +46,7 @@ export interface RunDevelopmentTuiInput extends TuiDisplayOptions {
* the inline error region rather than crashing the command.
*/
export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<void> {
- const { serverUrl, appRoot, initialInput, ...display } = input;
+ const { serverUrl, appRoot, initialInput, onBootProgress, ...display } = input;
const client = new Client(resolveDevelopmentClientOptions(serverUrl));
@@ -60,6 +63,7 @@ export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<
};
if (appRoot !== undefined) options.appRoot = appRoot;
if (initialInput !== undefined) options.initialInput = initialInput;
+ if (onBootProgress !== undefined) options.onBootProgress = onBootProgress;
await new EveTUIRunner(options).run();
}
diff --git a/packages/eve/src/cli/format-elapsed.test.ts b/packages/eve/src/cli/format-elapsed.test.ts
new file mode 100644
index 000000000..dd46eebc5
--- /dev/null
+++ b/packages/eve/src/cli/format-elapsed.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import { formatElapsed } from "./format-elapsed.js";
+
+describe("formatElapsed", () => {
+ it.each([
+ [0, "0ms"],
+ [467, "467ms"],
+ [1_000, "1s"],
+ [13_200, "13.2s"],
+ [60_000, "1m 0s"],
+ [62_000, "1m 2s"],
+ [3_599_999, "59m 59s"],
+ [3_600_000, "1h 0m 0s"],
+ [3_662_000, "1h 1m 2s"],
+ [86_399_999, "23h 59m 59s"],
+ [86_400_000, "1d 0h 0m 0s"],
+ [90_062_000, "1d 1h 1m 2s"],
+ ])("formats %dms as %s", (milliseconds, expected) => {
+ expect(formatElapsed(milliseconds)).toBe(expected);
+ });
+
+ it("rejects invalid elapsed times", () => {
+ expect(() => formatElapsed(-1)).toThrow(RangeError);
+ expect(() => formatElapsed(Number.NaN)).toThrow(RangeError);
+ });
+});
diff --git a/packages/eve/src/cli/format-elapsed.ts b/packages/eve/src/cli/format-elapsed.ts
new file mode 100644
index 000000000..4cec970b0
--- /dev/null
+++ b/packages/eve/src/cli/format-elapsed.ts
@@ -0,0 +1,27 @@
+const SECOND_MS = 1_000;
+const MINUTE_MS = 60 * SECOND_MS;
+
+/** Formats elapsed milliseconds with the smallest useful unit breakdown. */
+export function formatElapsed(milliseconds: number): string {
+ if (!Number.isFinite(milliseconds) || milliseconds < 0) {
+ throw new RangeError("Elapsed time must be a finite, non-negative number.");
+ }
+
+ const roundedMilliseconds = Math.round(milliseconds);
+ if (roundedMilliseconds < SECOND_MS) return `${roundedMilliseconds}ms`;
+ if (roundedMilliseconds < MINUTE_MS) {
+ return `${Math.round(roundedMilliseconds / 100) / 10}s`;
+ }
+
+ const totalSeconds = Math.floor(roundedMilliseconds / SECOND_MS);
+ const seconds = totalSeconds % 60;
+ const totalMinutes = Math.floor(totalSeconds / 60);
+ const minutes = totalMinutes % 60;
+ const totalHours = Math.floor(totalMinutes / 60);
+ const hours = totalHours % 24;
+ const days = Math.floor(totalHours / 24);
+
+ if (days > 0) return `${days}d ${hours}h ${minutes}m ${seconds}s`;
+ if (totalHours > 0) return `${totalHours}h ${minutes}m ${seconds}s`;
+ return `${totalMinutes}m ${seconds}s`;
+}
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index 998b89d94..c0293fe7e 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDevUiMode, resolveTuiDisplayOptions, resolveTuiTitle, runCli } from "#cli/run.js";
+import type { RunDevelopmentTuiInput } from "#cli/dev/tui/tui.js";
+import type { DevelopmentServerOptions } from "#internal/nitro/host/types.js";
async function withInteractiveTerminal<T>(fn: () => Promise<T>): Promise<T> {
const stdinDescriptor = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");
@@ -101,6 +103,44 @@ describe("eve dev --logs", () => {
});
});
+describe("eve dev boot progress", () => {
+ it("passes one reporter through local startup and clears the row on failure", async () => {
+ const writes: string[] = [];
+ const close = vi.fn(async () => {});
+ let hostReporter: DevelopmentServerOptions["onBootProgress"] = undefined;
+ let tuiReporter: RunDevelopmentTuiInput["onBootProgress"] = undefined;
+ const startHost = vi.fn(async (_appRoot: string, options?: DevelopmentServerOptions) => {
+ hostReporter = options?.onBootProgress;
+ hostReporter?.({ phase: "compiling agent", type: "phase-started" });
+ hostReporter?.({ elapsedMs: 1, phase: "compiling agent", type: "phase-finished" });
+ return { close, url: "http://127.0.0.1:2000" };
+ });
+ const runDevelopmentTui = vi.fn(async (input: RunDevelopmentTuiInput) => {
+ tuiReporter = input.onBootProgress;
+ throw new Error("TUI startup failed");
+ });
+ const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ writes.push(String(chunk));
+ return true;
+ });
+
+ try {
+ await expect(
+ withInteractiveTerminal(() =>
+ runCli(["dev"], { error: () => {}, log: () => {} }, { runDevelopmentTui, startHost }),
+ ),
+ ).rejects.toThrow("TUI startup failed");
+ } finally {
+ stdoutWrite.mockRestore();
+ }
+
+ expect(hostReporter).toBeTypeOf("function");
+ expect(tuiReporter).toBe(hostReporter);
+ expect(writes.at(-1)).toBe("\r\u001B[K");
+ expect(close).toHaveBeenCalledOnce();
+ });
+});
+
describe("resolveDevUiMode", () => {
it("defaults to the terminal UI in an interactive terminal", () => {
expect(resolveDevUiMode({ options: {}, interactive: true })).toBe("tui");
diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.ts
index d9395d10b..23ab692bb 100644
--- a/packages/eve/src/cli/run.ts
+++ b/packages/eve/src/cli/run.ts
@@ -1,13 +1,22 @@
import { basename } from "node:path";
import { Command, CommanderError, InvalidArgumentError } from "#compiled/commander/index.js";
+import { devBootPhase, type DevBootProgressReporter } from "#internal/dev-boot-progress.js";
import { resolveApplicationRoot } from "#internal/application/paths.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { eveCliBanner } from "#cli/banner.js";
import { registerProjectCommands } from "#cli/commands/register-project-commands.js";
+import type { RunDevelopmentTuiInput } from "#cli/dev/tui/tui.js";
import { LOG_DISPLAY_MODES, parseLogDisplayMode } from "#cli/dev/tui/log-display-mode.js";
import { parseDevelopmentServerUrl } from "#cli/dev/url.js";
+import { startCliLiveRow } from "#cli/ui/live-row.js";
import { createCliTheme, renderCliTaggedLine } from "#cli/ui/output.js";
+import { createLogger } from "#internal/logging.js";
+import type {
+ DevelopmentServerHandle,
+ DevelopmentServerOptions,
+ ProductionServerHandle,
+} from "#internal/nitro/host/types.js";
import type {
AssistantResponseStatsMode,
LogDisplayMode,
@@ -41,17 +50,6 @@ interface ProductionCliOptions {
port?: number;
}
-interface DevelopmentServerHandle {
- readonly url: string;
- close(): Promise<void>;
-}
-
-interface ProductionServerHandle {
- readonly url: string;
- close(): Promise<void>;
- wait(): Promise<void>;
-}
-
interface CliRuntimeDependencies {
buildHost(appRoot: string): Promise<string>;
printApplicationInfo(
@@ -59,21 +57,13 @@ interface CliRuntimeDependencies {
appRoot: string,
options?: { json?: boolean },
): Promise<void>;
- runDevelopmentTui(
- input: { serverUrl: string; appRoot?: string; initialInput?: string } & TuiDisplayOptions,
- ): Promise<void>;
+ runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<void>;
runEvalCommand(
evalIds: readonly string[],
options: EvalCliOptions,
logger: CliLogger,
): Promise<void>;
- startHost(
- appRoot: string,
- options?: {
- host?: string;
- port?: number;
- },
- ): Promise<DevelopmentServerHandle>;
+ startHost(appRoot: string, options?: DevelopmentServerOptions): Promise<DevelopmentServerHandle>;
startProductionHost(
appRoot: string,
options?: {
@@ -85,6 +75,31 @@ interface CliRuntimeDependencies {
type CliRuntimeOverrides = Partial<CliRuntimeDependencies>;
+const devBootLog = createLogger("dev.boot");
+
+function createDevBootProgressReporter(
+ row: ReturnType<typeof startCliLiveRow> | undefined,
+): DevBootProgressReporter {
+ return (event) => {
+ switch (event.type) {
+ case "phase-started":
+ row?.update("Building your agent", event.phase);
+ devBootLog.debug(event.phase);
+ return;
+ case "phase-finished":
+ devBootLog.debug(`${event.phase} finished`, { ms: event.elapsedMs });
+ return;
+ case "before-first-paint":
+ row?.stop();
+ return;
+ default: {
+ const exhaustive: never = event;
+ return exhaustive;
+ }
+ }
+ };
+}
+
interface EvalCliOptions {
json?: boolean;
junit?: string;
@@ -513,23 +528,22 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
loadDevelopmentEnvironmentFiles(appRoot);
- const runInteractiveUi = async (serverUrl: string): Promise<void> => {
- logger.log("");
-
- const runDevelopmentTui = runtime.runDevelopmentTui ?? (await loadRunDevelopmentTui());
+ const runInteractiveUi = async (serverUrl: string, report?: DevBootProgressReporter) => {
+ const runDevelopmentTui = await devBootPhase(
+ "loading interactive UI",
+ async () => runtime.runDevelopmentTui ?? (await loadRunDevelopmentTui()),
+ report,
+ );
const display = resolveTuiDisplayOptions(options);
const title = resolveTuiTitle({ name: options.name, remoteServerUrl, appRoot });
if (title !== undefined) display.name = title;
- const tuiInput: Parameters<CliRuntimeDependencies["runDevelopmentTui"]>[0] = {
+ const tuiInput: RunDevelopmentTuiInput = {
+ appRoot: remoteServerUrl === undefined ? appRoot : undefined,
+ initialInput: options.input,
+ onBootProgress: report,
serverUrl,
...display,
};
- if (remoteServerUrl === undefined) {
- tuiInput.appRoot = appRoot;
- }
- if (options.input !== undefined) {
- tuiInput.initialInput = options.input;
- }
await runDevelopmentTui(tuiInput);
};
@@ -553,19 +567,21 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
return;
}
+ logger.log("");
await runInteractiveUi(remoteServerUrl);
return;
}
- const startHost = runtime.startHost ?? (await loadStartHost());
- const server = await startHost(appRoot, {
- host: options.host,
- port: options.port,
- });
- let closed = false;
+ // Print spacing before the live row; a later write would strand the row.
+ if (mode === "tui") logger.log("");
+ const buildProgress = mode === "tui" ? startCliLiveRow(logger) : undefined;
+ const onBootProgress = createDevBootProgressReporter(buildProgress);
+ buildProgress?.update("Building your agent");
+ let closed = false;
+ let server: DevelopmentServerHandle | undefined;
const closeServer = async () => {
- if (closed) {
+ if (closed || server === undefined) {
return;
}
@@ -574,6 +590,13 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
};
try {
+ const startHost = runtime.startHost ?? (await loadStartHost());
+ server = await startHost(appRoot, {
+ host: options.host,
+ onBootProgress,
+ port: options.port,
+ });
+
// The terminal UI's header already shows the server URL, and startup
// no longer clears the screen, so the line would linger as noise.
// Headless consumers (scripts, scenario tests) still parse it.
@@ -606,8 +629,9 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
});
}
- await runInteractiveUi(server.url);
+ await runInteractiveUi(server.url, onBootProgress);
} finally {
+ buildProgress?.stop();
await closeServer();
}
});
diff --git a/packages/eve/src/cli/ui/live-row.test.ts b/packages/eve/src/cli/ui/live-row.test.ts
new file mode 100644
index 000000000..a270be72e
--- /dev/null
+++ b/packages/eve/src/cli/ui/live-row.test.ts
@@ -0,0 +1,244 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { stripAnsi, visibleLength } from "#cli/dev/tui/terminal-text.js";
+
+import { startCliLiveRow } from "./live-row.js";
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("startCliLiveRow", () => {
+ it("starts each indicator at the first sequence step", () => {
+ vi.useFakeTimers();
+ const sequence = "10100000";
+ const makeIndicator = () => {
+ const writes: string[] = [];
+ const progress = startCliLiveRow(
+ { log: vi.fn() },
+ {
+ output: { columns: 80, isTTY: true, write: (chunk) => writes.push(chunk) },
+ pulseSequence: sequence,
+ },
+ );
+ return { progress, writes };
+ };
+ const lit = (writes: string[]): boolean =>
+ stripAnsi(writes.at(-1) ?? "")
+ .trimStart()
+ .startsWith("▪");
+
+ const first = makeIndicator();
+ first.progress.update("First");
+ expect(lit(first.writes)).toBe(true);
+
+ vi.advanceTimersByTime(125);
+ expect(lit(first.writes)).toBe(false);
+
+ const second = makeIndicator();
+ second.progress.update("Second");
+ expect(lit(second.writes)).toBe(true);
+
+ vi.advanceTimersByTime(125);
+ expect(lit(first.writes)).toBe(true);
+ expect(lit(second.writes)).toBe(false);
+
+ first.progress.stop();
+ second.progress.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("renders installer detail inline without a second animation", () => {
+ vi.useFakeTimers();
+ const writes: string[] = [];
+ const progress = startCliLiveRow(
+ { log: vi.fn() },
+ {
+ output: {
+ columns: 80,
+ isTTY: true,
+ write: (chunk) => writes.push(chunk),
+ },
+ pulseSequence: "00000000",
+ },
+ );
+ const rendered = (): string => stripAnsi(writes.at(-1) ?? "");
+
+ progress.update("Preparing project");
+ expect(rendered()).toContain("Preparing project...");
+
+ progress.update("Installing dependencies", "npm install");
+ expect(rendered()).toContain("Installing dependencies npm install");
+ expect(rendered()).not.toContain(" · ");
+ expect(rendered()).not.toContain("dependencies...");
+ const writesAfterUpdate = writes.length;
+
+ vi.advanceTimersByTime(600);
+ expect(writes).toHaveLength(writesAfterUpdate);
+
+ progress.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("collapses whitespace before fitting a progress row", () => {
+ vi.useFakeTimers();
+ const writes: string[] = [];
+ const progress = startCliLiveRow(
+ { log: vi.fn() },
+ {
+ output: {
+ columns: 20,
+ isTTY: true,
+ write: (chunk) => writes.push(chunk),
+ },
+ pulseSequence: "00000000",
+ },
+ );
+
+ progress.update("X\nY", "\u001B]0;title\u0007aa\t\u001B[31mbbbbbbb\u001B[0m");
+ const row = stripAnsi(writes.at(-1) ?? "");
+ expect(row).toContain("X Y aa bbbbbbb");
+ expect(row).not.toContain("title");
+ expect(row).not.toContain("\n");
+ expect(row).not.toContain("\t");
+ expect(visibleLength(row)).toBeLessThan(20);
+
+ progress.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("plays a 16-step sequence over the same one-second loop", () => {
+ vi.useFakeTimers();
+ const writes: string[] = [];
+ const progress = startCliLiveRow(
+ { log: vi.fn() },
+ {
+ output: {
+ columns: 80,
+ isTTY: true,
+ write: (chunk) => writes.push(chunk),
+ },
+ pulseSequence: "1000000010000000",
+ },
+ );
+ const rendered = (): string => stripAnsi(writes.at(-1) ?? "");
+
+ progress.update("Preparing project");
+ expect(rendered()).toContain("▪ Preparing project...");
+
+ vi.advanceTimersByTime(63);
+ expect(rendered()).toContain(" Preparing project...");
+
+ vi.advanceTimersByTime(437);
+ expect(rendered()).toContain("▪ Preparing project...");
+
+ progress.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("rejects non-binary sequences outside the 8- or 16-step grids", () => {
+ expect(() => startCliLiveRow({ log: vi.fn() }, { pulseSequence: "1000" })).toThrow(RangeError);
+ expect(() => startCliLiveRow({ log: vi.fn() }, { pulseSequence: "10002000" })).toThrow(
+ RangeError,
+ );
+ });
+
+ it("keeps the 00000000 sequence silent", () => {
+ vi.useFakeTimers();
+ const writes: string[] = [];
+ const progress = startCliLiveRow(
+ { log: vi.fn() },
+ {
+ output: {
+ columns: 80,
+ isTTY: true,
+ write: (chunk) => writes.push(chunk),
+ },
+ pulseSequence: "00000000",
+ },
+ );
+
+ progress.update("Preparing project");
+ expect(stripAnsi(writes.at(-1) ?? "")).toContain(" Preparing project...");
+
+ vi.advanceTimersByTime(1000);
+ expect(writes).toHaveLength(1);
+
+ progress.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("follows an eight-step pulse sequence", () => {
+ vi.useFakeTimers();
+ const writes: string[] = [];
+ const progress = startCliLiveRow(
+ { log: vi.fn() },
+ {
+ output: {
+ columns: 80,
+ isTTY: true,
+ write: (chunk) => writes.push(chunk),
+ },
+ pulseSequence: "10100100",
+ },
+ );
+ const rendered = (): string => stripAnsi(writes.at(-1) ?? "");
+
+ progress.update("Preparing project");
+ expect(rendered()).toContain("▪ Preparing project...");
+
+ vi.advanceTimersByTime(125);
+ expect(rendered()).toContain(" Preparing project...");
+
+ vi.advanceTimersByTime(125);
+ expect(rendered()).toContain("▪ Preparing project...");
+
+ vi.advanceTimersByTime(125);
+ expect(rendered()).toContain(" Preparing project...");
+
+ vi.advanceTimersByTime(250);
+ expect(rendered()).toContain("▪ Preparing project...");
+
+ vi.advanceTimersByTime(125);
+ expect(rendered()).toContain(" Preparing project...");
+
+ vi.advanceTimersByTime(250);
+ expect(rendered()).toContain("▪ Preparing project...");
+
+ progress.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("does not animate while debug logging is enabled", () => {
+ vi.useFakeTimers();
+ const previous = process.env.EVE_LOG_LEVEL;
+ process.env.EVE_LOG_LEVEL = "debug";
+ try {
+ const writes: string[] = [];
+ const logs: string[] = [];
+ const progress = startCliLiveRow(
+ { log: (message) => logs.push(message) },
+ {
+ output: { columns: 80, isTTY: true, write: (chunk) => writes.push(chunk) },
+ pulseSequence: "10101010",
+ },
+ );
+
+ progress.update("Preparing project");
+ progress.update("Creating agent");
+ vi.advanceTimersByTime(1000);
+
+ expect(writes).toEqual([]);
+ expect(logs).toEqual(["Preparing project..."]);
+ expect(vi.getTimerCount()).toBe(0);
+
+ progress.stop();
+ } finally {
+ if (previous === undefined) {
+ delete process.env.EVE_LOG_LEVEL;
+ } else {
+ process.env.EVE_LOG_LEVEL = previous;
+ }
+ }
+ });
+});
diff --git a/packages/eve/src/cli/ui/live-row.ts b/packages/eve/src/cli/ui/live-row.ts
new file mode 100644
index 000000000..f97051b24
--- /dev/null
+++ b/packages/eve/src/cli/ui/live-row.ts
@@ -0,0 +1,150 @@
+import pc from "picocolors";
+
+import { sliceVisible, visibleLength } from "#cli/dev/tui/terminal-text.js";
+import { sanitizeForTerminal } from "#cli/ui/output.js";
+import { isLogLevelEnabled } from "#internal/logging.js";
+
+interface CliLiveRow {
+ update(message: string, detail?: string): void;
+ stop(): void;
+}
+
+interface CliLiveRowLogger {
+ log(message: string): void;
+}
+
+interface CliLiveRowOutput {
+ readonly columns?: number;
+ readonly isTTY?: boolean;
+ write(chunk: string): unknown;
+}
+
+interface CliLiveRowOptions {
+ readonly output?: CliLiveRowOutput;
+ readonly pulseSequence?: string;
+}
+
+const REDRAW_PROGRESS_ROW = "\r\u001B[K";
+const PULSE_GLYPH = "▪";
+const PULSE_SEQUENCE_DURATION_MS = 1000;
+const DEFAULT_PULSE_SEQUENCE = "1111110000111111";
+
+function validatePulseSequence(sequence: string): void {
+ if (sequence.length !== 8 && sequence.length !== 16) {
+ throw new RangeError("Pulse sequence must contain 8 or 16 steps.");
+ }
+ if (/[^01]/u.test(sequence)) {
+ throw new RangeError('Pulse sequence steps must be "0" or "1".');
+ }
+}
+
+function pulseStepDurationMs(index: number, stepCount: number): number {
+ const start = Math.round((index * PULSE_SEQUENCE_DURATION_MS) / stepCount);
+ const end = Math.round(((index + 1) * PULSE_SEQUENCE_DURATION_MS) / stepCount);
+ return end - start;
+}
+
+function sanitizeProgressText(input: string): string {
+ return sanitizeForTerminal(input).replaceAll(/\s+/gu, " ").trim();
+}
+
+function fitProgressText(input: string, width: number): string {
+ if (width <= 0) return "";
+ if (visibleLength(input) <= width) return input;
+ if (width === 1) return "…";
+ return `${sliceVisible(input, width - 1)}…`;
+}
+
+function renderProgressRow(
+ glyph: string,
+ message: string,
+ detail: string,
+ columns: number | undefined,
+): string {
+ const hasDetail = detail !== "";
+ const prefix = `${glyph} ${message}${hasDetail ? "" : "..."}`;
+ const maxWidth = Math.max(0, (columns ?? 80) - 1);
+ const prefixWidth = visibleLength(prefix);
+ if (prefixWidth >= maxWidth) {
+ const fitted = fitProgressText(prefix, maxWidth);
+ return fitted.startsWith(glyph) ? `${pc.green(glyph)}${fitted.slice(glyph.length)}` : fitted;
+ }
+
+ const fittedDetail = hasDetail ? fitProgressText(` ${detail}`, maxWidth - prefixWidth) : "";
+ const styledDetail = fittedDetail === "" ? "" : pc.dim(fittedDetail);
+ return `${pc.green(glyph)}${prefix.slice(glyph.length)}${styledDetail}`;
+}
+
+/** Starts one transient CLI row, or logs its first message when repainting is unavailable. */
+export function startCliLiveRow(
+ logger: CliLiveRowLogger,
+ options: CliLiveRowOptions = {},
+): CliLiveRow {
+ const output = options.output ?? process.stdout;
+ const pulseSequence = options.pulseSequence ?? DEFAULT_PULSE_SEQUENCE;
+ validatePulseSequence(pulseSequence);
+ const animate = output.isTTY === true && !isLogLevelEnabled("debug");
+
+ let pulseStepIndex = 0;
+ let pulseVisible = pulseSequence[0] === "1";
+ let current: { detail: string; message: string } | undefined;
+ let painted = false;
+ let logged = false;
+ let stopped = false;
+ let pulseTimer: ReturnType<typeof setTimeout> | undefined;
+
+ const paint = (): void => {
+ if (current === undefined) return;
+ const row = renderProgressRow(
+ pulseVisible ? PULSE_GLYPH : " ",
+ current.message,
+ current.detail,
+ output.columns,
+ );
+ output.write(`${painted ? REDRAW_PROGRESS_ROW : ""}${row}`);
+ painted = true;
+ };
+
+ const schedulePulseStep = (): void => {
+ pulseTimer = setTimeout(
+ () => {
+ if (stopped) return;
+ pulseStepIndex = (pulseStepIndex + 1) % pulseSequence.length;
+ const nextPulseVisible = pulseSequence[pulseStepIndex] === "1";
+ if (nextPulseVisible !== pulseVisible) {
+ pulseVisible = nextPulseVisible;
+ paint();
+ }
+ schedulePulseStep();
+ },
+ pulseStepDurationMs(pulseStepIndex, pulseSequence.length),
+ );
+ pulseTimer.unref?.();
+ };
+
+ return {
+ update(message, detail = "") {
+ if (stopped) return;
+ current = {
+ detail: sanitizeProgressText(detail),
+ message: sanitizeProgressText(message),
+ };
+ if (!animate) {
+ if (!logged) {
+ logger.log(`${current.message}...`);
+ logged = true;
+ }
+ return;
+ }
+
+ paint();
+ if (pulseTimer === undefined) schedulePulseStep();
+ },
+ stop() {
+ if (stopped) return;
+ stopped = true;
+ if (pulseTimer !== undefined) clearTimeout(pulseTimer);
+ if (animate && painted) output.write(REDRAW_PROGRESS_ROW);
+ },
+ };
+}
diff --git a/packages/eve/src/internal/dev-boot-progress.test.ts b/packages/eve/src/internal/dev-boot-progress.test.ts
new file mode 100644
index 000000000..9cab65035
--- /dev/null
+++ b/packages/eve/src/internal/dev-boot-progress.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+
+import { devBootPhase, type DevBootProgressEvent } from "./dev-boot-progress.js";
+
+describe("devBootPhase", () => {
+ it("reports one phase to its own observer", async () => {
+ const events: DevBootProgressEvent[] = [];
+
+ await expect(
+ devBootPhase(
+ "compiling agent",
+ async () => 42,
+ (event) => events.push(event),
+ ),
+ ).resolves.toBe(42);
+
+ expect(events).toEqual([
+ { phase: "compiling agent", type: "phase-started" },
+ { elapsedMs: expect.any(Number), phase: "compiling agent", type: "phase-finished" },
+ ]);
+ });
+
+ it("keeps concurrent observers isolated", async () => {
+ const first: DevBootProgressEvent[] = [];
+ const second: DevBootProgressEvent[] = [];
+
+ await Promise.all([
+ devBootPhase(
+ "first",
+ async () => undefined,
+ (event) => first.push(event),
+ ),
+ devBootPhase(
+ "second",
+ async () => undefined,
+ (event) => second.push(event),
+ ),
+ ]);
+
+ expect(first).toEqual([
+ { phase: "first", type: "phase-started" },
+ { elapsedMs: expect.any(Number), phase: "first", type: "phase-finished" },
+ ]);
+ expect(second).toEqual([
+ { phase: "second", type: "phase-started" },
+ { elapsedMs: expect.any(Number), phase: "second", type: "phase-finished" },
+ ]);
+ });
+
+ it("does not observe an uninstrumented phase", async () => {
+ await expect(devBootPhase("orphan", async () => "ok")).resolves.toBe("ok");
+ });
+});
diff --git a/packages/eve/src/internal/dev-boot-progress.ts b/packages/eve/src/internal/dev-boot-progress.ts
new file mode 100644
index 000000000..e7ec3c161
--- /dev/null
+++ b/packages/eve/src/internal/dev-boot-progress.ts
@@ -0,0 +1,32 @@
+export type DevBootProgressEvent =
+ | {
+ readonly phase: string;
+ readonly type: "phase-started";
+ }
+ | {
+ readonly elapsedMs: number;
+ readonly phase: string;
+ readonly type: "phase-finished";
+ }
+ | {
+ readonly type: "before-first-paint";
+ };
+
+export type DevBootProgressReporter = (event: DevBootProgressEvent) => void;
+
+/** Runs one measured boot phase and reports it to this invocation's observer. */
+export async function devBootPhase<T>(
+ phase: string,
+ run: () => Promise<T>,
+ report?: DevBootProgressReporter,
+): Promise<T> {
+ if (report === undefined) return await run();
+
+ const startedAt = Date.now();
+ report({ phase, type: "phase-started" });
+ try {
+ return await run();
+ } finally {
+ report({ elapsedMs: Date.now() - startedAt, phase, type: "phase-finished" });
+ }
+}
diff --git a/packages/eve/src/internal/logging.ts b/packages/eve/src/internal/logging.ts
index 0d1a40f4a..282ae2939 100644
--- a/packages/eve/src/internal/logging.ts
+++ b/packages/eve/src/internal/logging.ts
@@ -258,6 +258,11 @@ function resolveThreshold(): number {
return LEVEL_SEVERITY.info;
}
+/** Returns whether the current threshold emits `level`. */
+export function isLogLevelEnabled(level: LogLevel): boolean {
+ return LEVEL_SEVERITY[level] >= resolveThreshold();
+}
+
function write(level: LogLevel, namespace: string, message: string, fields?: LogFields): void {
if (LEVEL_SEVERITY[level] < resolveThreshold()) {
return;
diff --git a/packages/eve/src/internal/nitro/host.ts b/packages/eve/src/internal/nitro/host.ts
index 1becf2010..c3d270e54 100644
--- a/packages/eve/src/internal/nitro/host.ts
+++ b/packages/eve/src/internal/nitro/host.ts
@@ -3,5 +3,6 @@ export { startDevelopmentServer } from "#internal/nitro/host/start-development-s
export { startProductionServer } from "#internal/nitro/host/start-production-server.js";
export type {
DevelopmentServerHandle,
+ DevelopmentServerOptions,
ProductionServerHandle,
} from "#internal/nitro/host/types.js";
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.ts
index 5db5a10ef..06c0ee49a 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts
@@ -24,7 +24,10 @@ import {
EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,
getInitializedDevelopmentSandboxBackendNames,
} from "#execution/sandbox/development-run.js";
-import type { DevelopmentServerHandle } from "#internal/nitro/host/types.js";
+import type {
+ DevelopmentServerHandle,
+ DevelopmentServerOptions,
+} from "#internal/nitro/host/types.js";
import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
import { pruneDevelopmentRuntimeArtifactsSnapshotsInBackground } from "#internal/nitro/dev-runtime-artifacts.js";
import {
@@ -33,6 +36,7 @@ import {
} from "#internal/nitro/host/ports.js";
import { detectPackageManager, type PackageManagerKind } from "#setup/package-manager.js";
import { eveDevArguments } from "#setup/primitives/index.js";
+import { devBootPhase } from "#internal/dev-boot-progress.js";
const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT = 65_535;
const WORKFLOW_LOCAL_BASE_URL_ENV = "WORKFLOW_LOCAL_BASE_URL";
@@ -464,10 +468,7 @@ async function listenForDevelopmentServer(input: {
*/
export async function startDevelopmentServer(
rootDir: string,
- options: {
- host?: string;
- port?: number;
- } = {},
+ options: DevelopmentServerOptions = {},
): Promise<DevelopmentServerHandle> {
// Marks this process tree as an `eve dev` session so runtime features
// that must never run in production (for example auto-installing
@@ -484,7 +485,11 @@ export async function startDevelopmentServer(
let removeDevelopmentProcessId: (() => Promise<void>) | undefined;
try {
- const preparedHost = await prepareApplicationHost(rootDir, { dev: true });
+ const preparedHost = await devBootPhase(
+ "compiling agent",
+ () => prepareApplicationHost(rootDir, { dev: true }),
+ options.onBootProgress,
+ );
removeDevelopmentProcessId = await writeDevelopmentProcessId(preparedHost.appRoot);
pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(preparedHost.appRoot);
const compiledArtifactsSource = resolveNitroCompiledArtifactsSource(
@@ -498,19 +503,30 @@ export async function startDevelopmentServer(
compiledArtifactsSource,
});
pruneLocalSandboxTemplatesInBackground(preparedHost.appRoot);
- nitro = await createApplicationNitro(preparedHost, true);
- devServer = createDevServer(nitro);
- guardDevelopmentServerWebSocketUpgrades(nitro, devServer);
+ const activeNitro = await devBootPhase(
+ "creating dev server",
+ () => createApplicationNitro(preparedHost, true),
+ options.onBootProgress,
+ );
+ nitro = activeNitro;
+ devServer = createDevServer(activeNitro);
+ const activeDevServer = devServer;
+ guardDevelopmentServerWebSocketUpgrades(activeNitro, devServer);
const hostname =
- options.host ?? nitro.options.devServer.hostname ?? DEFAULT_DEVELOPMENT_SERVER_HOST;
+ options.host ?? activeNitro.options.devServer.hostname ?? DEFAULT_DEVELOPMENT_SERVER_HOST;
const requestedPort = options.port ?? readEnvironmentPort();
const retryOnAddressInUse = requestedPort === undefined;
- const server = await listenForDevelopmentServer({
- devServer,
- host: hostname,
- port: requestedPort,
- retryOnAddressInUse,
- });
+ const server = await devBootPhase(
+ "binding port",
+ () =>
+ listenForDevelopmentServer({
+ devServer: activeDevServer,
+ host: hostname,
+ port: requestedPort,
+ retryOnAddressInUse,
+ }),
+ options.onBootProgress,
+ );
if (!server.url) {
throw new Error("Nitro dev server did not expose a URL.");
@@ -519,15 +535,24 @@ export async function startDevelopmentServer(
const serverUrl = normalizeDevelopmentServerClientUrl(server.url);
await writeDevelopmentServerMetadata(preparedHost.appRoot, serverUrl);
restoreWorkflowLocalQueueEnvironment = installWorkflowLocalQueueEnvironment(serverUrl);
- await prepare(nitro);
- await buildNitro(nitro);
-
- const { startAuthoredSourceWatcher } =
- await import("#internal/nitro/host/dev-authored-source-watcher.js");
- authoredSourceWatcher = await startAuthoredSourceWatcher({
- nitro,
- preparedHost,
- });
+ await devBootPhase(
+ "building dev bundle",
+ async () => {
+ await prepare(activeNitro);
+ await buildNitro(activeNitro);
+ },
+ options.onBootProgress,
+ );
+
+ authoredSourceWatcher = await devBootPhase(
+ "starting file watcher",
+ async () => {
+ const { startAuthoredSourceWatcher } =
+ await import("#internal/nitro/host/dev-authored-source-watcher.js");
+ return startAuthoredSourceWatcher({ nitro: activeNitro, preparedHost });
+ },
+ options.onBootProgress,
+ );
const restoreWorkflowLocalQueueEnvironmentOnClose = restoreWorkflowLocalQueueEnvironment;
if (restoreWorkflowLocalQueueEnvironmentOnClose === undefined) {
throw new Error("Workflow local queue environment was not initialized.");
@@ -535,7 +560,7 @@ export async function startDevelopmentServer(
const authoredSourceWatcherOnClose = authoredSourceWatcher;
const devServerOnClose = devServer;
- const nitroOnClose = nitro;
+ const nitroOnClose = activeNitro;
return {
async close() {
try {
diff --git a/packages/eve/src/internal/nitro/host/types.ts b/packages/eve/src/internal/nitro/host/types.ts
index 8659a936f..96522fefb 100644
--- a/packages/eve/src/internal/nitro/host/types.ts
+++ b/packages/eve/src/internal/nitro/host/types.ts
@@ -2,6 +2,7 @@ import type { CompileAgentResult } from "#compiler/compile-agent.js";
import type { ScheduleRegistration } from "#runtime/schedules/register.js";
import type { ResolvedSchedule } from "#runtime/types.js";
import type { GeneratedCompiledArtifactsFiles } from "#internal/application/compiled-artifacts.js";
+import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
/**
* Route surface included in one programmatic Nitro host build.
@@ -16,6 +17,12 @@ export interface DevelopmentServerHandle {
url: string;
}
+export interface DevelopmentServerOptions {
+ readonly host?: string;
+ readonly onBootProgress?: DevBootProgressReporter;
+ readonly port?: number;
+}
+
/**
* Handle returned after starting one built Nitro server.
*/
diff --git a/packages/eve/src/setup/primitives/pm/npm.ts b/packages/eve/src/setup/primitives/pm/npm.ts
index 4bbf05f09..c080cce3d 100644
--- a/packages/eve/src/setup/primitives/pm/npm.ts
+++ b/packages/eve/src/setup/primitives/pm/npm.ts
@@ -9,6 +9,7 @@ export const npmPackageManager = {
installArguments: (options) => [
"install",
...(options.bypassMinimumReleaseAge === true ? ["--min-release-age=0"] : []),
+ ...(options.progressDetails === true ? ["--loglevel=silly"] : []),
],
prepareArguments: (_projectRoot, args) => args,
resolveInvocation: (args) => resolveStandardInvocation("npm", args),
diff --git a/packages/eve/src/setup/primitives/pm/run.ts b/packages/eve/src/setup/primitives/pm/run.ts
index 0a8678ac2..3ea8dcf5f 100644
--- a/packages/eve/src/setup/primitives/pm/run.ts
+++ b/packages/eve/src/setup/primitives/pm/run.ts
@@ -147,12 +147,23 @@ function capturePackageManager(
process.stderr.write(`\n${message}\n`);
}
}
+ function replayCapturedStdout(): void {
+ const captured = Buffer.concat(stdout);
+ if (captured.length === 0) return;
+ if (outputBuffer) {
+ outputBuffer.write("stdout", captured);
+ outputBuffer.flush();
+ } else {
+ process.stdout.write(captured);
+ }
+ }
child.on("error", (error: NodeJS.ErrnoException) => {
if (options.signal?.aborted === true || error.name === "AbortError") {
return;
} else {
disarmAbort();
+ replayCapturedStdout();
reportFailure(
error.code === "ENOENT"
? `${kind} not found. Install it before running this step.`
@@ -164,6 +175,7 @@ function capturePackageManager(
child.on("close", (code) => {
disarmAbort();
if (!settled && code !== 0 && options.signal?.aborted !== true) {
+ replayCapturedStdout();
reportFailure(`${kind} ${args.join(" ")} exited with code ${code ?? "unknown"}.`);
}
settle(options.signal?.aborted === true ? false : code === 0);
diff --git a/packages/eve/src/setup/primitives/pm/types.ts b/packages/eve/src/setup/primitives/pm/types.ts
index 565355c54..e1a4b3940 100644
--- a/packages/eve/src/setup/primitives/pm/types.ts
+++ b/packages/eve/src/setup/primitives/pm/types.ts
@@ -18,6 +18,8 @@ export interface PackageManagerInstallOptions {
readonly bypassMinimumReleaseAge?: boolean;
/** Resolves the project standalone even when an ancestor workspace exists. */
readonly ignoreWorkspace?: boolean;
+ /** Requests verbose package-manager output for a live progress display. */
+ readonly progressDetails?: boolean;
}
/**
diff --git a/packages/eve/src/setup/primitives/run-pnpm.test.ts b/packages/eve/src/setup/primitives/run-pnpm.test.ts
index 7e9d5ec39..205b77186 100644
--- a/packages/eve/src/setup/primitives/run-pnpm.test.ts
+++ b/packages/eve/src/setup/primitives/run-pnpm.test.ts
@@ -123,6 +123,23 @@ describe("runPnpmInstall", () => {
{ stream: "stderr", text: "WARN deprecated package" },
]);
});
+
+ test("replays stdout when the ancestor workspace probe fails", async () => {
+ mockedExistsSync.mockImplementation((path) => path === "/tmp/pnpm-workspace.yaml");
+ const child = createMockChildProcess();
+ mockedSpawn.mockReturnValueOnce(child);
+ const onOutput = vi.fn();
+
+ const result = runPnpmInstall("/tmp/eve-agent", { onOutput });
+ child.stdout.emit("data", Buffer.from("workspace parse failed\n"));
+ child.emit("close", 1);
+
+ await expect(result).resolves.toBe(false);
+ expect(onOutput.mock.calls.map(([line]) => line)).toEqual([
+ { stream: "stdout", text: "workspace parse failed" },
+ { stream: "stderr", text: "pnpm list --depth -1 --json exited with code 1." },
+ ]);
+ });
});
describe("runPackageManagerInstall", () => {
@@ -146,6 +163,18 @@ describe("runPackageManagerInstall", () => {
expect.objectContaining({ cwd: "/tmp/app" }),
);
});
+
+ test("requests npm output before registry operations complete", async () => {
+ await expect(
+ runPackageManagerInstall("npm", "/tmp/app", { progressDetails: true }),
+ ).resolves.toBe(true);
+
+ expect(mockedSpawn).toHaveBeenCalledWith(
+ "npm",
+ ["install", "--loglevel=silly"],
+ expect.objectContaining({ cwd: "/tmp/app" }),
+ );
+ });
});
describe("eveDevArguments", () => {
diff --git a/packages/eve/test/scenarios/eve-init.scenario.test.ts b/packages/eve/test/scenarios/eve-init.scenario.test.ts
index 133ae0dca..66577b90b 100644
--- a/packages/eve/test/scenarios/eve-init.scenario.test.ts
+++ b/packages/eve/test/scenarios/eve-init.scenario.test.ts
@@ -194,7 +194,7 @@ describe("eve init smoke", () => {
},
]);
expect(result.stdout).toContain("Created an eve agent in ");
- expect(result.stdout).toContain("Installing dependencies...");
+ expect(result.stdout).toContain("Preparing project...");
expect(result.stdout).toContain("Installed dependencies");
expect(result.stdout).not.toContain("Progress: resolved");
await expect(pathExists(join(projectDir, ".git"))).resolves.toBe(true);