Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(eve): share AI Gateway key and spinner helpers across setup flows (#179)

Ruib42da82b9d41
diff --git a/packages/eve/src/setup/ai-gateway-api-key.test.ts b/packages/eve/src/setup/ai-gateway-api-key.test.ts
new file mode 100644
index 000000000..98c43839a
--- /dev/null
+++ b/packages/eve/src/setup/ai-gateway-api-key.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { writeAiGatewayApiKey } from "./ai-gateway-api-key.js";
+
+describe("writeAiGatewayApiKey", () => {
+ it("trims and replaces the key in the project env file", async () => {
+ const appendEnv = vi.fn(async () => ({ written: ["AI_GATEWAY_API_KEY"], skipped: [] }));
+
+ await expect(
+ writeAiGatewayApiKey({ projectRoot: "/app/my-agent", apiKey: " sk-test ", appendEnv }),
+ ).resolves.toEqual({
+ envKey: "AI_GATEWAY_API_KEY",
+ envFile: ".env.local",
+ envPath: "/app/my-agent/.env.local",
+ });
+
+ expect(appendEnv).toHaveBeenCalledExactlyOnceWith(
+ "/app/my-agent/.env.local",
+ { AI_GATEWAY_API_KEY: "sk-test" },
+ { force: true },
+ );
+ });
+});
diff --git a/packages/eve/src/setup/ai-gateway-api-key.ts b/packages/eve/src/setup/ai-gateway-api-key.ts
new file mode 100644
index 000000000..bd6ec08ed
--- /dev/null
+++ b/packages/eve/src/setup/ai-gateway-api-key.ts
@@ -0,0 +1,32 @@
+import { join } from "node:path";
+
+import { appendEnv } from "./append-env.js";
+
+export const AI_GATEWAY_API_KEY_ENV_VAR = "AI_GATEWAY_API_KEY";
+export const AI_GATEWAY_API_KEY_ENV_FILE = ".env.local";
+
+/** The location written by eve when a user supplies an AI Gateway API key. */
+export interface AiGatewayApiKeyLocation {
+ envKey: typeof AI_GATEWAY_API_KEY_ENV_VAR;
+ envFile: typeof AI_GATEWAY_API_KEY_ENV_FILE;
+ envPath: string;
+}
+
+/** Trims and saves an explicit AI Gateway API key, replacing any prior value. */
+export async function writeAiGatewayApiKey(input: {
+ projectRoot: string;
+ apiKey: string;
+ appendEnv?: typeof appendEnv;
+}): Promise<AiGatewayApiKeyLocation> {
+ const envPath = join(input.projectRoot, AI_GATEWAY_API_KEY_ENV_FILE);
+ await (input.appendEnv ?? appendEnv)(
+ envPath,
+ { [AI_GATEWAY_API_KEY_ENV_VAR]: input.apiKey.trim() },
+ { force: true },
+ );
+ return {
+ envKey: AI_GATEWAY_API_KEY_ENV_VAR,
+ envFile: AI_GATEWAY_API_KEY_ENV_FILE,
+ envPath,
+ };
+}
diff --git a/packages/eve/src/setup/boxes/apply-ai-gateway-credential.ts b/packages/eve/src/setup/boxes/apply-ai-gateway-credential.ts
index a7bd53f5b..f7901f25a 100644
--- a/packages/eve/src/setup/boxes/apply-ai-gateway-credential.ts
+++ b/packages/eve/src/setup/boxes/apply-ai-gateway-credential.ts
@@ -1,12 +1,15 @@
-import { join } from "node:path";
-
import { createPromptCommandOutput } from "#setup/cli/index.js";
+import {
+ AI_GATEWAY_API_KEY_ENV_FILE,
+ AI_GATEWAY_API_KEY_ENV_VAR,
+ writeAiGatewayApiKey,
+} from "../ai-gateway-api-key.js";
import { appendEnv } from "../append-env.js";
import { isProjectResolved } from "../project-resolution.js";
import type { Prompter } from "../prompter.js";
import { runVercelEnvPull } from "../run-vercel-link.js";
-import { withNetworkSpinner } from "../vercel-project.js";
+import { withSpinner } from "../with-spinner.js";
import {
requireProjectPath,
type ResolvedAiGatewayCredentials,
@@ -15,9 +18,6 @@ import {
import type { SetupBox } from "../step.js";
import { detectAiGatewayResolution } from "./detect-ai-gateway.js";
-const AI_GATEWAY_ENV_KEY = "AI_GATEWAY_API_KEY";
-const ENV_FILE_NAME = ".env.local";
-
/** Injected for tests; defaults to the real env-file and Vercel helpers. */
export interface ApplyAiGatewayCredentialDeps {
appendEnv: typeof appendEnv;
@@ -46,14 +46,6 @@ export function applyAiGatewayCredential(
): SetupBox<SetupState, null, ResolvedAiGatewayCredentials> {
const deps = options.deps ?? { appendEnv, runVercelEnvPull, detectAiGatewayResolution };
- async function writeAiGatewayApiKey(projectRoot: string, apiKey: string): Promise<void> {
- const envPath = join(projectRoot, ENV_FILE_NAME);
- // Force the write: a pasted key is an explicit override, so it must win over
- // any key already present rather than being silently preserved.
- await deps.appendEnv(envPath, { [AI_GATEWAY_ENV_KEY]: apiKey.trim() }, { force: true });
- options.prompter.log.success(`Wrote ${AI_GATEWAY_ENV_KEY} to ${envPath}`);
- }
-
return {
id: "apply-ai-gateway-credential",
@@ -84,20 +76,25 @@ export function applyAiGatewayCredential(
return { kind: "unresolved" };
}
if (plan.kind === "byok") {
- await writeAiGatewayApiKey(projectRoot, plan.apiGatewayKey);
- return { kind: "api-key", envFile: ENV_FILE_NAME };
+ const location = await writeAiGatewayApiKey({
+ projectRoot,
+ apiKey: plan.apiGatewayKey,
+ appendEnv: deps.appendEnv,
+ });
+ options.prompter.log.success(`Wrote ${location.envKey} to ${location.envPath}`);
+ return { kind: "api-key", envFile: location.envFile };
}
if (!linked) {
prompter.log.warning(
"No Vercel project linked and no API key provided. The agent will not reach a model " +
- `until you set ${AI_GATEWAY_ENV_KEY} in ${ENV_FILE_NAME} or link a project.`,
+ `until you set ${AI_GATEWAY_API_KEY_ENV_VAR} in ${AI_GATEWAY_API_KEY_ENV_FILE} or link a project.`,
);
return { kind: "unresolved" };
}
// Only claim success when the pull actually completed; a failed pull leaves
// no inherited credential, so reporting "connected" would be a lie.
const onOutput = createPromptCommandOutput(prompter.log);
- const pulled = await withNetworkSpinner(
+ const pulled = await withSpinner(
prompter,
"Pulling Vercel environment variables into .env.local...",
() => deps.runVercelEnvPull(projectRoot, onOutput, signal),
diff --git a/packages/eve/src/setup/boxes/detect-ai-gateway.ts b/packages/eve/src/setup/boxes/detect-ai-gateway.ts
index 8eec55d19..85d4860d8 100644
--- a/packages/eve/src/setup/boxes/detect-ai-gateway.ts
+++ b/packages/eve/src/setup/boxes/detect-ai-gateway.ts
@@ -1,6 +1,7 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
+import { AI_GATEWAY_API_KEY_ENV_FILE, AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";
import {
requireProjectPath,
type AiGatewayEnvFile,
@@ -9,8 +10,10 @@ import {
} from "../state.js";
import type { SetupBox } from "../step.js";
-const AI_GATEWAY_ENV_KEY = "AI_GATEWAY_API_KEY";
-const ENV_FILE_CANDIDATES = [".env.local", ".env"] as const satisfies readonly AiGatewayEnvFile[];
+const ENV_FILE_CANDIDATES = [
+ AI_GATEWAY_API_KEY_ENV_FILE,
+ ".env",
+] as const satisfies readonly AiGatewayEnvFile[];
function readEnvValue(line: string, key: string): string | undefined {
const trimmed = line.trim();
@@ -57,7 +60,7 @@ export async function findEnvFileWithKey(
export async function detectAiGatewayResolution(
projectRoot: string,
): Promise<ResolvedAiGatewayCredentials> {
- const envFile = await findEnvFileWithKey(projectRoot, AI_GATEWAY_ENV_KEY);
+ const envFile = await findEnvFileWithKey(projectRoot, AI_GATEWAY_API_KEY_ENV_VAR);
if (envFile !== undefined) {
return { kind: "api-key", envFile };
}
diff --git a/packages/eve/src/setup/boxes/resolve-provisioning.ts b/packages/eve/src/setup/boxes/resolve-provisioning.ts
index c29988421..a17422343 100644
--- a/packages/eve/src/setup/boxes/resolve-provisioning.ts
+++ b/packages/eve/src/setup/boxes/resolve-provisioning.ts
@@ -31,8 +31,8 @@ import {
requireAuth,
resolveTeam,
validateTeam,
- withNetworkSpinner,
} from "../vercel-project.js";
+import { withSpinner } from "../with-spinner.js";
/** Injected for tests; defaults to the real Vercel project and fs helpers. */
export interface ResolveProvisioningDeps {
@@ -174,7 +174,7 @@ export function resolveProvisioning(
if (state.projectPath.kind !== "resolved") return undefined;
const path = state.projectPath.path;
if (!(await deps.pathExists(join(path, ".vercel", "project.json")))) return undefined;
- return withNetworkSpinner(options.prompter, whimsyFor("project-detect"), async () => {
+ return withSpinner(options.prompter, whimsyFor("project-detect"), async () => {
const detected = await deps.detectProjectResolution(path, { signal });
if (!isProjectResolved(detected)) return undefined;
const authenticated = await deps.isVercelAuthenticated(path, { signal });
diff --git a/packages/eve/src/setup/flows/channels.ts b/packages/eve/src/setup/flows/channels.ts
index 7ee5d3d03..1fb7fc8fa 100644
--- a/packages/eve/src/setup/flows/channels.ts
+++ b/packages/eve/src/setup/flows/channels.ts
@@ -18,7 +18,12 @@ import type { Prompter, SelectOption, SingleSelectOptions } from "../prompter.js
import { WizardCancelledError } from "../step.js";
import { runInteractive, type AnySetupBox } from "../runner.js";
import { createDefaultSetupState, snapshotSetupState, type SetupState } from "../state.js";
-import { getVercelAuthStatus, type VercelAuthStatus } from "../vercel-project.js";
+import {
+ getVercelAuthStatus,
+ vercelAuthBlockerReason,
+ type VercelAuthStatus,
+} from "../vercel-project.js";
+import { withSpinner } from "../with-spinner.js";
import { prompterSink } from "./in-project.js";
@@ -157,9 +162,8 @@ function vercelChannelBlocker(
authStatus: VercelAuthStatus,
projectLinked: boolean,
): string | undefined {
- if (authStatus === "cli-missing") return "Vercel CLI not found, see /vc";
- if (authStatus === "logged-out") return "Log in to Vercel first, see /login";
- if (authStatus === "unavailable") return "Couldn't reach Vercel, check your connection";
+ const authBlocker = vercelAuthBlockerReason(authStatus);
+ if (authBlocker !== undefined) return authBlocker;
if (!projectLinked) return "Requires Vercel account, see /model";
return undefined;
}
@@ -249,26 +253,20 @@ export async function runChannelsFlow(input: {
...input.deps,
};
- async function checkProject<T>(task: () => Promise<T>): Promise<T> {
- const spinner = prompter.log.spinner?.("Checking the project…");
- try {
- return await task();
- } finally {
- spinner?.stop();
- }
- }
-
// Link detection and the auth probe are independent `vercel` round-trips;
// the registration compile is local. One ephemeral spinner covers all three
// so the list paints with no persisted loading lines. Login is a separate
// axis from link: a logged-out (or CLI-missing) session blocks a Vercel-backed
// channel even when the directory is linked.
- const [deployment, initialRegistrations, authStatus] = await checkProject(() =>
- Promise.all([
- deps.detectDeployment(appRoot, { signal }),
- deps.inspectExistingChannelRegistrations(appRoot),
- deps.getVercelAuthStatus(appRoot, { signal }),
- ]),
+ const [deployment, initialRegistrations, authStatus] = await withSpinner(
+ prompter,
+ "Checking the project…",
+ () =>
+ Promise.all([
+ deps.detectDeployment(appRoot, { signal }),
+ deps.inspectExistingChannelRegistrations(appRoot),
+ deps.getVercelAuthStatus(appRoot, { signal }),
+ ]),
);
signal?.throwIfAborted();
let registrations = initialRegistrations;
@@ -319,7 +317,9 @@ export async function runChannelsFlow(input: {
signal,
});
} catch (error) {
- const observed = await checkProject(() => deps.inspectExistingChannelRegistrations(appRoot));
+ const observed = await withSpinner(prompter, "Checking the project…", () =>
+ deps.inspectExistingChannelRegistrations(appRoot),
+ );
if (channelLandedDuringSubflow(registrations, observed, pick)) {
state = { ...state, channels: appendChannel(state.channels, pick) };
registrations = observed;
@@ -334,7 +334,9 @@ export async function runChannelsFlow(input: {
}
if (result.kind === "done") {
state = result.state;
- registrations = await checkProject(() => deps.inspectExistingChannelRegistrations(appRoot));
+ registrations = await withSpinner(prompter, "Checking the project…", () =>
+ deps.inspectExistingChannelRegistrations(appRoot),
+ );
signal?.throwIfAborted();
// A fresh Slack connection only comes alive once deployed, so offer the
// shortcut right here; "Later" falls back to the list like any other lap.
@@ -350,7 +352,9 @@ export async function runChannelsFlow(input: {
};
}
} else {
- const observed = await checkProject(() => deps.inspectExistingChannelRegistrations(appRoot));
+ const observed = await withSpinner(prompter, "Checking the project…", () =>
+ deps.inspectExistingChannelRegistrations(appRoot),
+ );
if (channelLandedDuringSubflow(registrations, observed, pick)) {
return { kind: "done", addedChannels: appendChannel(state.channels, pick) };
}
diff --git a/packages/eve/src/setup/flows/deploy.ts b/packages/eve/src/setup/flows/deploy.ts
index b7d784404..5162368a0 100644
--- a/packages/eve/src/setup/flows/deploy.ts
+++ b/packages/eve/src/setup/flows/deploy.ts
@@ -14,6 +14,7 @@ import {
import type { Prompter } from "../prompter.js";
import { runHeadless, runInteractive, type AnySetupBox } from "../runner.js";
import { snapshotSetupState, type SetupState } from "../state.js";
+import { withSpinner } from "../with-spinner.js";
import { inProjectSetupState, prompterSink } from "./in-project.js";
@@ -57,15 +58,11 @@ export async function runDeployFlow(input: {
const { appRoot, prompter, interactive, signal } = input;
const deps: DeployFlowDeps = { detectDeployment, ...input.deps };
- const spinner = prompter.log.spinner?.("Checking the current Vercel link...");
- let project: ProjectResolution;
- try {
+ const project = await withSpinner(prompter, "Checking the current Vercel link...", async () => {
const deployment = await deps.detectDeployment(appRoot, { signal });
signal?.throwIfAborted();
- project = projectResolutionFromDeployment(deployment);
- } finally {
- spinner?.stop();
- }
+ return projectResolutionFromDeployment(deployment);
+ });
const linked = isProjectResolved(project);
if (!linked && !interactive) {
diff --git a/packages/eve/src/setup/flows/install-vercel-cli.ts b/packages/eve/src/setup/flows/install-vercel-cli.ts
index 7ddf07626..9a7005782 100644
--- a/packages/eve/src/setup/flows/install-vercel-cli.ts
+++ b/packages/eve/src/setup/flows/install-vercel-cli.ts
@@ -4,6 +4,7 @@ import { spawnPackageManager } from "#setup/primitives/index.js";
import { getVercelAuthStatus } from "#setup/vercel-project.js";
import type { Prompter } from "../prompter.js";
+import { withSpinner } from "../with-spinner.js";
export type InstallVercelCliResult =
/** The CLI is already resolvable; nothing to do. */
@@ -41,19 +42,6 @@ function globalInstallArguments(kind: PackageManagerKind): string[] {
}
}
-async function withSpinner<T>(
- prompter: Prompter,
- message: string,
- task: () => Promise<T>,
-): Promise<T> {
- const spinner = prompter.log.spinner?.(message);
- try {
- return await task();
- } finally {
- spinner?.stop();
- }
-}
-
/**
* THE INSTALL FLOW for the dev TUI's `/vc`: the fix command for the
* "Vercel CLI not found" diagnostic, so every diagnostic has a matching
diff --git a/packages/eve/src/setup/flows/link.ts b/packages/eve/src/setup/flows/link.ts
index 5accad224..27088d42d 100644
--- a/packages/eve/src/setup/flows/link.ts
+++ b/packages/eve/src/setup/flows/link.ts
@@ -1,4 +1,5 @@
import { interactiveAsker, withAnswers } from "../ask.js";
+import { AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";
import {
applyAiGatewayCredential,
type ApplyAiGatewayCredentialDeps,
@@ -14,6 +15,7 @@ import type { Prompter } from "../prompter.js";
import { WizardCancelledError } from "../step.js";
import { runInteractive, type AnySetupBox } from "../runner.js";
import { snapshotSetupState, type SetupState } from "../state.js";
+import { withSpinner } from "../with-spinner.js";
import pc from "picocolors";
import { inProjectSetupState, prompterSink } from "./in-project.js";
@@ -31,7 +33,7 @@ export type LinkFlowResult =
| {
kind: "done";
/** The model credential verified in an env file, when one landed. */
- credential?: "VERCEL_OIDC_TOKEN" | "AI_GATEWAY_API_KEY";
+ credential?: "VERCEL_OIDC_TOKEN" | typeof AI_GATEWAY_API_KEY_ENV_VAR;
}
| { kind: "cancelled" };
@@ -71,20 +73,17 @@ export async function runLinkFlow(input: {
...input.deps,
};
- const spinner = prompter.log.spinner?.("Checking the current Vercel link...");
- let identity: Awaited<ReturnType<typeof detectProjectIdentity>>;
- try {
- identity = await deps.detectProjectIdentity(appRoot, { signal });
+ const identity = await withSpinner(prompter, "Checking the current Vercel link...", async () => {
+ const detected = await deps.detectProjectIdentity(appRoot, { signal });
signal?.throwIfAborted();
- } finally {
- spinner?.stop();
- }
+ return detected;
+ });
if (identity === undefined) {
// A working model is NOT evidence of a link — credentials can come from
// an env file or the shell. Naming the source heads off "but it clearly
// works" confusion when the link detection correctly says unlinked.
const [gatewayKey, oidc] = await Promise.all([
- deps.findEnvFileWithKey(appRoot, "AI_GATEWAY_API_KEY"),
+ deps.findEnvFileWithKey(appRoot, AI_GATEWAY_API_KEY_ENV_VAR),
deps.findEnvFileWithKey(appRoot, "VERCEL_OIDC_TOKEN"),
]);
const credentialFile = gatewayKey ?? oidc;
@@ -154,7 +153,7 @@ export async function runLinkFlow(input: {
const [oidcFile, gatewayKeyFile] = await Promise.all([
deps.findEnvFileWithKey(appRoot, "VERCEL_OIDC_TOKEN"),
- deps.findEnvFileWithKey(appRoot, "AI_GATEWAY_API_KEY"),
+ deps.findEnvFileWithKey(appRoot, AI_GATEWAY_API_KEY_ENV_VAR),
]);
signal?.throwIfAborted();
// Success stays silent here: the caller owns the closing line (`eve link`'s
@@ -168,6 +167,6 @@ export async function runLinkFlow(input: {
}
const done: LinkFlowResult = { kind: "done" };
if (oidcFile !== undefined) done.credential = "VERCEL_OIDC_TOKEN";
- else if (gatewayKeyFile !== undefined) done.credential = "AI_GATEWAY_API_KEY";
+ else if (gatewayKeyFile !== undefined) done.credential = AI_GATEWAY_API_KEY_ENV_VAR;
return done;
}
diff --git a/packages/eve/src/setup/flows/login.ts b/packages/eve/src/setup/flows/login.ts
index 87583785b..3a28848ca 100644
--- a/packages/eve/src/setup/flows/login.ts
+++ b/packages/eve/src/setup/flows/login.ts
@@ -3,6 +3,7 @@ import { runVercel } from "#setup/primitives/run-vercel.js";
import { getVercelAuthStatus, type VercelAuthStatus } from "#setup/vercel-project.js";
import type { Prompter } from "../prompter.js";
+import { withSpinner } from "../with-spinner.js";
export type LoginFlowResult =
/** A `vercel whoami` already succeeds; nothing to do. */
@@ -51,19 +52,6 @@ const defaultDeps: LoginFlowDeps = {
}),
};
-async function withSpinner<T>(
- prompter: Prompter,
- message: string,
- task: () => Promise<T>,
-): Promise<T> {
- const spinner = prompter.log.spinner?.(message);
- try {
- return await task();
- } finally {
- spinner?.stop();
- }
-}
-
/**
* Runs `vercel login` while the dev TUI stays live, mirroring the Slack Connect
* browser wait: an interactive prompter races the login subprocess against a
diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.ts
index 0bddb5c58..cac2bba0f 100644
--- a/packages/eve/src/setup/flows/model.ts
+++ b/packages/eve/src/setup/flows/model.ts
@@ -8,6 +8,7 @@ import { createStaticSourceChange } from "#source-change/static-source-change.js
import pc from "picocolors";
+import { AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";
import { interactiveAsker } from "../ask.js";
import { findEnvFileWithKey } from "../boxes/detect-ai-gateway.js";
import {
@@ -22,6 +23,7 @@ import type { Prompter, SelectNotice, SelectOption } from "../prompter.js";
import { runInteractive } from "../runner.js";
import { snapshotSetupState } from "../state.js";
import { WizardCancelledError } from "../step.js";
+import { withSpinner } from "../with-spinner.js";
import { inProjectSetupState, prompterSink } from "./in-project.js";
import { runVercelFlow } from "./vercel.js";
@@ -66,7 +68,7 @@ export type ModelProviderStatus =
| { kind: "gateway-project"; projectName: string; teamName?: string }
| {
kind: "gateway-key";
- envKey: "AI_GATEWAY_API_KEY" | "VERCEL_OIDC_TOKEN";
+ envKey: typeof AI_GATEWAY_API_KEY_ENV_VAR | "VERCEL_OIDC_TOKEN";
envFile: string;
};
@@ -79,7 +81,7 @@ export type ModelProviderStatus =
* disk — so it never surfaces as an outcome.
*/
export interface ModelProviderOutcome {
- credential?: "VERCEL_OIDC_TOKEN" | "AI_GATEWAY_API_KEY";
+ credential?: "VERCEL_OIDC_TOKEN" | typeof AI_GATEWAY_API_KEY_ENV_VAR;
status: ModelProviderStatus;
}
@@ -191,7 +193,7 @@ export async function detectModelProviderStatus(
): Promise<ModelProviderStatus> {
const [identity, gatewayKeyFile, oidcFile] = await Promise.all([
detectProjectIdentity(appRoot, options),
- findEnvFileWithKey(appRoot, "AI_GATEWAY_API_KEY"),
+ findEnvFileWithKey(appRoot, AI_GATEWAY_API_KEY_ENV_VAR),
findEnvFileWithKey(appRoot, "VERCEL_OIDC_TOKEN"),
]);
if (identity !== undefined) {
@@ -203,7 +205,7 @@ export async function detectModelProviderStatus(
return status;
}
if (gatewayKeyFile !== undefined) {
- return { kind: "gateway-key", envKey: "AI_GATEWAY_API_KEY", envFile: gatewayKeyFile };
+ return { kind: "gateway-key", envKey: AI_GATEWAY_API_KEY_ENV_VAR, envFile: gatewayKeyFile };
}
if (oidcFile !== undefined) {
return { kind: "gateway-key", envKey: "VERCEL_OIDC_TOKEN", envFile: oidcFile };
@@ -240,22 +242,15 @@ export async function runModelFlow(input: {
...input.deps,
};
- async function checkProject<T>(task: () => Promise<T>): Promise<T> {
- const spinner = prompter.log.spinner?.("Checking the project…");
- try {
- return await task();
- } finally {
- spinner?.stop();
- }
- }
-
// The model read is local, the provider status is a `vercel` round-trip;
// one ephemeral spinner covers both so the menu paints with no persisted
// loading lines.
const detectProvider = (): Promise<ModelProviderStatus> =>
deps.detectProviderStatus(appRoot, { signal });
- let [{ id: current, routing, editable }, provider] = await checkProject(() =>
- Promise.all([deps.readCurrentModel(appRoot), detectProvider()]),
+ let [{ id: current, routing, editable }, provider] = await withSpinner(
+ prompter,
+ "Checking the project…",
+ () => Promise.all([deps.readCurrentModel(appRoot), detectProvider()]),
);
signal?.throwIfAborted();
@@ -339,7 +334,7 @@ export async function runModelFlow(input: {
}
// Only a completed link/own-key sub-flow can move the link or
// credentials, so this is the one place the status is re-read.
- provider = await checkProject(detectProvider);
+ provider = await withSpinner(prompter, "Checking the project…", detectProvider);
signal?.throwIfAborted();
providerOutcome = { status: provider };
if (result.credential !== undefined) providerOutcome.credential = result.credential;
@@ -374,14 +369,8 @@ async function pickModelFromCatalog(input: {
deps: {
// The box fetches inside its gather, so the catalog spinner has to ride
// the fetch itself to bracket exactly the slow part.
- fetchModels: async (requestSignal) => {
- const spinner = prompter.log.spinner?.("Loading the model catalog...");
- try {
- return await baseFetch(requestSignal);
- } finally {
- spinner?.stop();
- }
- },
+ fetchModels: (requestSignal) =>
+ withSpinner(prompter, "Loading the model catalog...", () => baseFetch(requestSignal)),
},
};
if (current !== null) options.defaultModel = current;
diff --git a/packages/eve/src/setup/flows/vercel.ts b/packages/eve/src/setup/flows/vercel.ts
index 42cb567e9..b326fdab0 100644
--- a/packages/eve/src/setup/flows/vercel.ts
+++ b/packages/eve/src/setup/flows/vercel.ts
@@ -1,19 +1,19 @@
-import { join } from "node:path";
-
import pc from "picocolors";
+import {
+ AI_GATEWAY_API_KEY_ENV_FILE,
+ AI_GATEWAY_API_KEY_ENV_VAR,
+ writeAiGatewayApiKey,
+} from "../ai-gateway-api-key.js";
import { appendEnv } from "../append-env.js";
import type { Prompter, SelectOption } from "../prompter.js";
import { WizardCancelledError } from "../step.js";
import { validateGatewayApiKey } from "../validate-gateway-key.js";
import { getVercelAuthStatus, type VercelAuthStatus } from "../vercel-project.js";
+import { withSpinner } from "../with-spinner.js";
import { runLinkFlow, type LinkFlowResult } from "./link.js";
-// Mirrors the private constants in boxes/apply-ai-gateway-credential.ts; the
-// key name is also user-facing copy here, so the literal is the contract.
-const AI_GATEWAY_ENV_KEY = "AI_GATEWAY_API_KEY";
-const ENV_FILE_NAME = ".env.local";
type GatewayConnection = "project" | "own-key";
export const PROVIDER_QUESTION = "Which model provider do you want to use?";
@@ -21,7 +21,7 @@ export const CONNECTION_QUESTION = "How do you want to connect to AI Gateway?";
export const EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE = "Using another model provider";
export const EXTERNAL_PROVIDER_INSTRUCTIONS: readonly string[] = [
- `Set your provider's API key in ${ENV_FILE_NAME} — e.g. ANTHROPIC_API_KEY or OPENAI_API_KEY.`,
+ `Set your provider's API key in ${AI_GATEWAY_API_KEY_ENV_FILE} — e.g. ANTHROPIC_API_KEY or OPENAI_API_KEY.`,
'In agent/agent.ts, set `model` to a provider-authored model — e.g. `anthropic("claude-opus-4.8")` from `@ai-sdk/anthropic`.',
"See https://eve.dev/docs/agent-config for details.",
"A running `eve dev` reloads env files automatically — no restart needed.",
@@ -118,20 +118,21 @@ export async function runVercelFlow(input: {
hintLayout: "stacked",
});
if (provider === "gateway") {
- const spinner = prompter.log.spinner?.("Checking your Vercel login…");
- let authStatus: VercelAuthStatus;
- try {
- authStatus = await deps.getVercelAuthStatus(appRoot, { signal });
+ const authStatus = await withSpinner(prompter, "Checking your Vercel login…", async () => {
+ const status = await deps.getVercelAuthStatus(appRoot, { signal });
signal?.throwIfAborted();
- } finally {
- spinner?.stop();
- }
+ return status;
+ });
connection = await prompter.select<GatewayConnection>({
message: CONNECTION_QUESTION,
options: [
projectConnectionOption(authStatus),
- { value: "own-key", label: "Use my own key", hint: `paste an ${AI_GATEWAY_ENV_KEY}` },
+ {
+ value: "own-key",
+ label: "Use my own key",
+ hint: `paste an ${AI_GATEWAY_API_KEY_ENV_VAR}`,
+ },
],
hintLayout: "stacked",
});
@@ -167,7 +168,7 @@ export async function runVercelFlow(input: {
let key: string;
try {
key = await prompter.password({
- message: `Enter your ${AI_GATEWAY_ENV_KEY}`,
+ message: `Enter your ${AI_GATEWAY_API_KEY_ENV_VAR}`,
validate: (value) => (value.trim().length === 0 ? "API key cannot be empty." : undefined),
});
} catch (error) {
@@ -179,13 +180,9 @@ export async function runVercelFlow(input: {
signal?.throwIfAborted();
const trimmed = key.trim();
- const spinner = prompter.log.spinner?.("Validating…");
- let validation: Awaited<ReturnType<typeof validateGatewayApiKey>>;
- try {
- validation = await deps.validateGatewayApiKey(trimmed, signal);
- } finally {
- spinner?.stop();
- }
+ const validation = await withSpinner(prompter, "Validating…", () =>
+ deps.validateGatewayApiKey(trimmed, signal),
+ );
signal?.throwIfAborted();
if (validation.kind === "invalid") {
@@ -200,16 +197,14 @@ export async function runVercelFlow(input: {
prompter.log.success(`${pc.green("✓")} ${pc.bold("Valid key")}`);
}
- await deps.appendEnv(
- join(appRoot, ENV_FILE_NAME),
- { [AI_GATEWAY_ENV_KEY]: trimmed },
- {
- force: true,
- },
- );
+ const location = await writeAiGatewayApiKey({
+ projectRoot: appRoot,
+ apiKey: trimmed,
+ appendEnv: deps.appendEnv,
+ });
signal?.throwIfAborted();
- prompter.log.success(`Saved ${AI_GATEWAY_ENV_KEY} to ${ENV_FILE_NAME}.`);
- return { kind: "done", credential: AI_GATEWAY_ENV_KEY };
+ prompter.log.success(`Saved ${location.envKey} to ${location.envFile}.`);
+ return { kind: "done", credential: AI_GATEWAY_API_KEY_ENV_VAR };
}
} else {
// A fresh agent often has no Vercel project yet, so this branch can create
diff --git a/packages/eve/src/setup/vercel-project.test.ts b/packages/eve/src/setup/vercel-project.test.ts
index c7476a42a..f21aec584 100644
--- a/packages/eve/src/setup/vercel-project.test.ts
+++ b/packages/eve/src/setup/vercel-project.test.ts
@@ -18,6 +18,7 @@ import {
pickTeam,
requireAuth,
validateTeam,
+ vercelAuthBlockerReason,
} from "./vercel-project.js";
vi.mock("#setup/primitives/index.js", async (importOriginal) => {
@@ -209,6 +210,22 @@ describe("listProjects", () => {
});
});
+describe("vercelAuthBlockerReason", () => {
+ it("maps non-authenticated states to their setup blockers", () => {
+ expect([
+ vercelAuthBlockerReason("authenticated"),
+ vercelAuthBlockerReason("cli-missing"),
+ vercelAuthBlockerReason("logged-out"),
+ vercelAuthBlockerReason("unavailable"),
+ ]).toEqual([
+ undefined,
+ "Vercel CLI not found, see /vc",
+ "Log in to Vercel first, see /login",
+ "Couldn't reach Vercel, check your connection",
+ ]);
+ });
+});
+
describe("getVercelAuthStatus", () => {
it("reports authenticated when whoami succeeds", async () => {
mockedCaptureVercel.mockResolvedValueOnce(captured("acme\n"));
diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.ts
index 12da80edc..2187ba918 100644
--- a/packages/eve/src/setup/vercel-project.ts
+++ b/packages/eve/src/setup/vercel-project.ts
@@ -8,6 +8,7 @@ import { z } from "zod";
import type { ProjectResolution } from "./project-resolution.js";
import type { Prompter } from "./prompter.js";
import type { ResolvedVercelProjectSpec } from "./state.js";
+import { withSpinner } from "./with-spinner.js";
const JsonObjectSchema = z.record(z.string(), z.unknown());
@@ -57,24 +58,6 @@ export function unresolvedProject(): ProjectResolution {
return { kind: "unresolved" };
}
-/**
- * Runs a network reach behind a section-like spinner so the user sees the CLI
- * is working, not hung. The spinner clears whether the work resolves or throws,
- * and degrades to nothing when the prompter has no spinner (headless/test).
- */
-export async function withNetworkSpinner<T>(
- prompter: Prompter,
- message: string,
- task: () => Promise<T>,
-): Promise<T> {
- const spinner = prompter.log.spinner?.(message);
- try {
- return await task();
- } finally {
- spinner?.stop();
- }
-}
-
/** Resolves the linked project id from a resolution, if any. */
export function projectIdFromResolution(project: ProjectResolution): string | undefined {
return project.kind === "unresolved" ? undefined : project.projectId;
@@ -362,6 +345,24 @@ export function requireVercelAuth(failure: VercelCaptureFailure): never {
*/
export type VercelAuthStatus = "authenticated" | "logged-out" | "cli-missing" | "unavailable";
+/** Returns the user-facing reason Vercel-backed setup is unavailable. */
+export function vercelAuthBlockerReason(authStatus: VercelAuthStatus): string | undefined {
+ switch (authStatus) {
+ case "authenticated":
+ return undefined;
+ case "cli-missing":
+ return "Vercel CLI not found, see /vc";
+ case "logged-out":
+ return "Log in to Vercel first, see /login";
+ case "unavailable":
+ return "Couldn't reach Vercel, check your connection";
+ default: {
+ const exhaustive: never = authStatus;
+ return exhaustive;
+ }
+ }
+}
+
export async function getVercelAuthStatus(
projectRoot: string,
options: VercelProjectOperationOptions = {},
@@ -411,7 +412,7 @@ export async function requireAuth(
await check();
return;
}
- await withNetworkSpinner(prompter, whimsyFor("auth"), check);
+ await withSpinner(prompter, whimsyFor("auth"), check);
}
/**
@@ -495,7 +496,7 @@ export async function pickTeam(
await validateTeam(prompter, projectRoot, presetTeam, options);
return resolveTeam(projectRoot, presetTeam, options);
}
- const teams = await withNetworkSpinner(prompter, whimsyFor("teams"), () =>
+ const teams = await withSpinner(prompter, whimsyFor("teams"), () =>
listTeams(projectRoot, options),
);
if (teams.length <= 1) {
@@ -532,7 +533,7 @@ export async function pickProject(
team: string,
options: PickProjectOptions = {},
): Promise<ArgsPickedProject> {
- const projects = await withNetworkSpinner(prompter, whimsyFor("projects", team), () =>
+ const projects = await withSpinner(prompter, whimsyFor("projects", team), () =>
listProjects(projectRoot, team, options),
);
if (projects.length === 0) {
@@ -565,7 +566,7 @@ export async function pickNewProjectName(
defaultProjectName: string,
options: VercelProjectOperationOptions = {},
): Promise<string> {
- let existing = await withNetworkSpinner(prompter, whimsyFor("project-name", team), () =>
+ let existing = await withSpinner(prompter, whimsyFor("project-name", team), () =>
resolveProjectByNameOrId(projectRoot, team, defaultProjectName.trim(), options),
);
let projectName = defaultProjectName.trim();
@@ -614,7 +615,7 @@ export async function linkProject(
const scope = ["--scope", spec.team];
let project: VercelProjectReference;
if (spec.kind === "new") {
- project = await withNetworkSpinner(
+ project = await withSpinner(
prompter,
`Creating Vercel project "${spec.project}" in ${spec.team}...`,
async () => {
@@ -629,7 +630,7 @@ export async function linkProject(
}
project = existing;
}
- return withNetworkSpinner(
+ return withSpinner(
prompter,
`Linking this directory to Vercel project "${project.name}"...`,
() =>
diff --git a/packages/eve/src/setup/with-spinner.test.ts b/packages/eve/src/setup/with-spinner.test.ts
new file mode 100644
index 000000000..28ec28b11
--- /dev/null
+++ b/packages/eve/src/setup/with-spinner.test.ts
@@ -0,0 +1,42 @@
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+import { describe, expect, it, vi } from "vitest";
+
+import { withSpinner } from "./with-spinner.js";
+
+describe("withSpinner", () => {
+ it("returns the task result and stops the spinner", async () => {
+ const { prompter } = createFakePrompter();
+ const stop = vi.fn();
+ const spinner = vi.fn(() => ({ stop }));
+ prompter.log.spinner = spinner;
+
+ await expect(withSpinner(prompter, "Working…", async () => 42)).resolves.toBe(42);
+
+ expect(spinner).toHaveBeenCalledExactlyOnceWith("Working…");
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it("stops the spinner when the task rejects", async () => {
+ const { prompter } = createFakePrompter();
+ const failure = new Error("boom");
+ const stop = vi.fn();
+ prompter.log.spinner = vi.fn(() => ({ stop }));
+
+ await expect(
+ withSpinner(prompter, "Working…", async () => {
+ throw failure;
+ }),
+ ).rejects.toBe(failure);
+
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it("runs the task when the prompter has no spinner", async () => {
+ const { prompter } = createFakePrompter();
+ const task = vi.fn(async () => "done");
+
+ await expect(withSpinner(prompter, "Working…", task)).resolves.toBe("done");
+
+ expect(task).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/eve/src/setup/with-spinner.ts b/packages/eve/src/setup/with-spinner.ts
new file mode 100644
index 000000000..445597cae
--- /dev/null
+++ b/packages/eve/src/setup/with-spinner.ts
@@ -0,0 +1,15 @@
+import type { Prompter } from "./prompter.js";
+
+/** Runs asynchronous work behind an optional spinner that always stops. */
+export async function withSpinner<T>(
+ prompter: Prompter,
+ message: string,
+ task: () => Promise<T>,
+): Promise<T> {
+ const spinner = prompter.log.spinner?.(message);
+ try {
+ return await task();
+ } finally {
+ spinner?.stop();
+ }
+}