Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(eve): refactor channel add flow (#1174)

OwenKephart0a8b63c53569
diff --git a/.changeset/plan-channel-setup.md b/.changeset/plan-channel-setup.md
new file mode 100644
index 000000000..4fa6a4090
--- /dev/null
+++ b/.changeset/plan-channel-setup.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve channels add` now scaffolds portable channel variants when Vercel is unavailable and asks before deploying Vercel-integrated channels. Portable Slack setup uses environment credentials and records the required variables in `.env.example`.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 5c03aed3c..73e18ef12 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -38,6 +38,9 @@ export default slackChannel({
`connectSlackCredentials` returns `{ botToken, webhookVerifier }`, keeping token rotation, multi-workspace tenancy, and request verification inside Connect rather than your code.
+If eve cannot find an authenticated Vercel session, `eve channels add slack` asks whether to set up Vercel Connect or use portable environment credentials. The portable option adds the required names to `.env.example`. Before deploying, appropriate values must be supplied to your runtime environment.
+
+
### Deploy
Deploy once the trigger destination and channel file are ready:
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index abf5d590f..b18453573 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -240,7 +240,7 @@ See [Evals](../evals/overview) for authoring evals.
eve channels add [kind] [-f] [-y]
```
-Scaffolds a channel into `agent/channels/`. With no `kind` it prompts interactively; pass a `kind` (`slack` \| `web`) to scaffold one directly.
+Scaffolds a channel into `agent/channels/`. With no `kind` it prompts interactively; pass a `kind` (`slack` \| `web`) to scaffold one directly. When the Vercel CLI has an authenticated session, eve scaffolds the Vercel-integrated variant and asks whether to deploy after setup. Without one, Slack setup asks whether to set up Vercel Connect or use portable credentials. The portable variant reads `SLACK_BOT_TOKEN` and `SLACK_SIGNING_SECRET` and adds both names to `.env.example`.
| Flag | Type | Default | Description |
| ------------- | ---- | ------- | --------------------------------------------------------- |
diff --git a/packages/eve/src/cli/commands/channels.integration.test.ts b/packages/eve/src/cli/commands/channels.integration.test.ts
index bae1c62fb..dad983791 100644
--- a/packages/eve/src/cli/commands/channels.integration.test.ts
+++ b/packages/eve/src/cli/commands/channels.integration.test.ts
@@ -12,6 +12,7 @@ import type { DeploymentInfo } from "#setup/project-resolution.js";
import type { AddChannelsDeps } from "#setup/boxes/add-channels.js";
import type { DeployProjectDeps } from "#setup/boxes/deploy-project.js";
import { createFakePrompter, type FakePrompterConfig } from "#internal/testing/fake-prompter.js";
+import { WizardCancelledError } from "#setup/step.js";
import { runChannelsAddCommand, type CliLogger } from "./channels.js";
@@ -168,10 +169,11 @@ describe("runChannelsAddCommand", () => {
await runChannelsAddCommand(
logger,
projectRoot,
- { kind: "slack", options: { force: true } },
+ { kind: "slack", options: { force: true, yes: true } },
{
createPrompter: () => fake.prompter,
detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => DEPLOYED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
addChannelsDeps,
deployProjectDeps,
},
@@ -185,6 +187,8 @@ describe("runChannelsAddCommand", () => {
// agentName stays "" in this command, so the slug derives from the
// package.json name, never the directory basename (R6).
"my-agent",
+ undefined,
+ expect.objectContaining({ selectConnector: expect.any(Function) }),
);
expect(addChannelsDeps.ensureChannel).toHaveBeenCalledWith(
expect.objectContaining({ kind: "slack", slackConnectorSlug: "my-agent", force: true }),
@@ -214,6 +218,7 @@ describe("runChannelsAddCommand", () => {
{
createPrompter: () => fake.prompter,
detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
addChannelsDeps,
deployProjectDeps: createDeployProjectDeps(),
},
@@ -239,6 +244,7 @@ describe("runChannelsAddCommand", () => {
{
createPrompter: () => fake.prompter,
detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
addChannelsDeps,
deployProjectDeps,
},
@@ -265,7 +271,15 @@ describe("runChannelsAddCommand", () => {
const detectDeployment = vi.fn(async (): Promise<DeploymentInfo> => UNLINKED);
await withInteractiveTerminal(() =>
- runChannelsAddCommand(logger, projectRoot, { options: { yes: true } }, { detectDeployment }),
+ runChannelsAddCommand(
+ logger,
+ projectRoot,
+ { options: { yes: true } },
+ {
+ detectDeployment,
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
+ },
+ ),
);
expect(detectDeployment).not.toHaveBeenCalled();
@@ -298,10 +312,11 @@ describe("runChannelsAddCommand", () => {
await runChannelsAddCommand(
logger,
projectRoot,
- { kind: "web", options: {} },
+ { kind: "web", options: { yes: true } },
{
createPrompter: () => fake.prompter,
detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
addChannelsDeps,
deployProjectDeps,
},
@@ -341,6 +356,92 @@ describe("runChannelsAddCommand", () => {
expect(process.exitCode).toBeUndefined();
});
+ test("deploys once after scaffolding multiple selected channels", async () => {
+ const projectRoot = await createAgentProject();
+ const logger = new TestLogger();
+ const fake = createTestPrompter({
+ multiple: () => ["web", "slack"],
+ single: () => "yes",
+ });
+ const addChannelsDeps = createAddChannelsDeps({ state: "linked", projectId: "prj_demo" });
+ const deployProjectDeps = createDeployProjectDeps();
+
+ await withInteractiveTerminal(() =>
+ runChannelsAddCommand(
+ logger,
+ projectRoot,
+ { options: {} },
+ {
+ createPrompter: () => fake.prompter,
+ detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
+ addChannelsDeps,
+ deployProjectDeps,
+ },
+ ),
+ );
+
+ expect(addChannelsDeps.ensureChannel).toHaveBeenCalledTimes(2);
+ expect(
+ deployProjectDeps.runVercel.mock.calls.filter(([args]) => args[0] === "deploy"),
+ ).toHaveLength(1);
+ expect(logger.errors).toEqual([]);
+ });
+
+ test("treats cancelling Slack credential selection as a normal command cancellation", async () => {
+ const projectRoot = await createAgentProject();
+ const logger = new TestLogger();
+ const fake = createTestPrompter({
+ single: () => {
+ throw new WizardCancelledError();
+ },
+ });
+ const addChannelsDeps = createAddChannelsDeps();
+
+ await runChannelsAddCommand(
+ logger,
+ projectRoot,
+ { kind: "slack", options: {} },
+ {
+ createPrompter: () => fake.prompter,
+ detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"logged-out"> => "logged-out"),
+ addChannelsDeps,
+ },
+ );
+
+ expect(addChannelsDeps.ensureChannel).not.toHaveBeenCalled();
+ expect(logger.errors).toEqual([]);
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ test("prompts before choosing portable Slack credentials when Vercel is unavailable", async () => {
+ const projectRoot = await createAgentProject();
+ const logger = new TestLogger();
+ const fake = createTestPrompter({ single: () => "portable" });
+ const addChannelsDeps = createAddChannelsDeps();
+
+ await runChannelsAddCommand(
+ logger,
+ projectRoot,
+ { kind: "slack", options: {} },
+ {
+ createPrompter: () => fake.prompter,
+ detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"unavailable"> => "unavailable"),
+ addChannelsDeps,
+ deployProjectDeps: createDeployProjectDeps(),
+ },
+ );
+
+ expect(fake.selectMessages).toContain("How would you like to configure Slack?");
+ expect(addChannelsDeps.ensureChannel).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: "slack", slackCredentials: "environment" }),
+ );
+ expect(addChannelsDeps.provisionSlackbot).not.toHaveBeenCalled();
+ expect(logger.errors).toEqual([]);
+ });
+
test("does not scaffold Web Chat over an existing eve session channel", async () => {
const projectRoot = await createAgentProject();
const logger = new TestLogger();
@@ -367,6 +468,7 @@ describe("runChannelsAddCommand", () => {
{
createPrompter: () => fake.prompter,
detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
},
);
@@ -406,6 +508,7 @@ describe("runChannelsAddCommand", () => {
{
createPrompter: () => fake.prompter,
detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
addChannelsDeps,
},
);
@@ -472,6 +575,7 @@ describe("runChannelsAddCommand", () => {
{
createPrompter: () => fake.prompter,
detectDeployment: vi.fn(async (): Promise<DeploymentInfo> => UNLINKED),
+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
addChannelsDeps,
deployProjectDeps,
},
diff --git a/packages/eve/src/cli/commands/channels.ts b/packages/eve/src/cli/commands/channels.ts
index abfb502ac..a094e0e88 100644
--- a/packages/eve/src/cli/commands/channels.ts
+++ b/packages/eve/src/cli/commands/channels.ts
@@ -1,8 +1,17 @@
import { isEveProject, listAuthoredChannels, type ChannelKind } from "#setup/scaffold/index.js";
import { interactiveAsker } from "#setup/ask.js";
-import { addChannels, type AddChannelsDeps } from "#setup/boxes/add-channels.js";
-import { deployProject, type DeployProjectDeps } from "#setup/boxes/deploy-project.js";
+import type { AddChannelsDeps } from "#setup/boxes/add-channels.js";
+import type { DeployProjectDeps } from "#setup/boxes/deploy-project.js";
+import {
+ channelSetupEnvironment,
+ describeChannelSetupEnvironment,
+} from "#setup/channel-setup-environment.js";
+import { deployChannelSetup } from "#setup/channel-setup-deployment.js";
+import {
+ channelSetupIntegration,
+ createChannelSetupUi,
+} from "#setup/channel-setup-integrations.js";
import { selectChannels } from "#setup/boxes/select-channels.js";
import {
detectDeployment,
@@ -13,6 +22,7 @@ import { createPrompter, type Prompter } from "#setup/prompter.js";
import { runInteractive, type AnySetupBox } from "#setup/runner.js";
import { createDefaultSetupState, snapshotSetupState, type SetupState } from "#setup/state.js";
import type { OutputSink } from "#setup/step.js";
+import { getVercelAuthStatus, type VercelAuthStatus } from "#setup/vercel-project.js";
import {
assertCanAddSelectedChannels,
@@ -47,6 +57,8 @@ export interface AddChannelCommandOptions {
export interface ChannelsAddDependencies {
createPrompter?: () => Prompter;
detectDeployment(projectPath: string): Promise<DeploymentInfo>;
+ /** Read-only Vercel session probe. Optional only for legacy test seams. */
+ getVercelAuthStatus(projectPath: string): Promise<VercelAuthStatus>;
/** Test seam into the add-channels box's scaffold/Connect/Vercel effects. */
addChannelsDeps?: AddChannelsDeps;
/** Test seam into the deploy box's subprocess effects. */
@@ -55,14 +67,13 @@ export interface ChannelsAddDependencies {
const defaultChannelsAddDependencies: ChannelsAddDependencies = {
detectDeployment,
+ getVercelAuthStatus,
};
/**
- * `eve channels add` composes the channel picker, scaffold, and deploy boxes.
- * Its picker allows an empty submit and keeps Slack viable while unlinked;
- * conflict validation against existing authored registrations, the interactive
- * `vercel link` fallback inside the add-channels box, Vercel services config
- * pinned on, and build-stamped web package versions.
+ * `eve channels add` detects Vercel capabilities, resolves portable or
+ * Vercel-specific channel plans, scaffolds the selection, then offers an
+ * optional deployment when the selected plan supports it.
*/
async function runAddChannelsFlow(
appRoot: string,
@@ -78,14 +89,21 @@ async function runAddChannelsFlow(
const prompter = dependencies.createPrompter?.() ?? createPrompter();
prompter.intro("Add channels to your eve agent");
- prompter.log.message("Checking the current Vercel project...");
+ prompter.log.message("Checking Vercel setup...");
+ const deployment = await dependencies.detectDeployment(appRoot);
+ const authStatus = await dependencies.getVercelAuthStatus(appRoot);
+ const environment = channelSetupEnvironment(
+ authStatus,
+ projectResolutionFromDeployment(deployment),
+ );
+ prompter.log.info(describeChannelSetupEnvironment(environment));
// The detected on-disk link is the only seeded fact; there are no onboarding
// plans in this command, so the rest of the state keeps its defaults. The
// default agentName ("") keeps deriveSlackConnectorSlug on its package.json
// fallback instead of the directory basename, as the dissolved engine did.
const state: SetupState = {
...createDefaultSetupState(),
- project: projectResolutionFromDeployment(await dependencies.detectDeployment(appRoot)),
+ project: projectResolutionFromDeployment(deployment),
projectPath: { kind: "resolved", inPlace: true, path: appRoot },
};
let registrationInspection: ReturnType<typeof inspectExistingChannelRegistrations> | undefined;
@@ -115,33 +133,45 @@ async function runAddChannelsFlow(
assertCanAddSelectedChannels(selectedChannels, await inspectRegistrations());
},
}),
- addChannels({
- // The slackbot question only runs interactively here (a passed kind or
- // --yes short-circuits it), so the interactive base suffices, mirroring
- // the select-channels box above.
- asker: interactiveAsker(prompter),
- prompter,
- presetCreateSlackbot: options.yes ? true : undefined,
- force: options.force,
- // An unlinked directory still gets the Vercel services config (the engine
- // never gated it), and the link fallback keeps unlinked Slack viable.
- configureVercelServices: true,
- ensureLinkedProject: "interactive-vercel-link",
- deps: dependencies.addChannelsDeps,
- }),
- deployProject({
- prompter,
- ensureLinkedProject: "interactive-vercel-link",
- deps: dependencies.deployProjectDeps,
- }),
];
const sink: OutputSink = { write: (line) => prompter.log.message(line) };
- const result = await runInteractive(boxes, state, sink, { snapshot: snapshotSetupState });
- if (result.kind === "cancelled") {
- return;
+ const selected = await runInteractive(boxes, state, sink, { snapshot: snapshotSetupState });
+ if (selected.kind === "cancelled") return;
+
+ let finalState = selected.state;
+ const ui = createChannelSetupUi({ asker: interactiveAsker(prompter), prompter });
+ for (const selectedKind of selected.state.channelSelection) {
+ const result = await channelSetupIntegration(selectedKind).setup({
+ environment,
+ state: { ...finalState, channelSelection: [selectedKind] },
+ ui,
+ force: options.force,
+ presetCreateSlackbot: options.yes ? true : undefined,
+ presetPortableCredentials: options.yes === true ? true : undefined,
+ deps: dependencies.addChannelsDeps,
+ });
+ if (result.kind === "cancelled") return;
+ finalState = result.state;
+ }
+
+ const addedVercelChannel =
+ finalState.slackbotAttached ||
+ (environment.vercel.kind === "available" && finalState.channels.includes("web"));
+ if (addedVercelChannel) {
+ finalState = await deployChannelSetup({
+ state: finalState,
+ ui,
+ presetDeploy:
+ options.yes === true
+ ? true
+ : !process.stdin.isTTY || !process.stdout.isTTY
+ ? false
+ : undefined,
+ deps: dependencies.deployProjectDeps,
+ });
}
- prompter.outro(result.state.channels.length === 0 ? "No channels added." : "Channels added.");
+ prompter.outro(finalState.channels.length === 0 ? "No channels added." : "Channels added.");
}
export async function runChannelsAddCommand(
diff --git a/packages/eve/src/setup/boxes/add-channels.test.ts b/packages/eve/src/setup/boxes/add-channels.test.ts
index 20c88c49c..520a00e80 100644
--- a/packages/eve/src/setup/boxes/add-channels.test.ts
+++ b/packages/eve/src/setup/boxes/add-channels.test.ts
@@ -48,14 +48,31 @@ function createDeps() {
action: "created",
filesWritten: ["/tmp/project/app/page.tsx"],
filesSkipped: [],
- packageJsonUpdated: [],
+ packageJsonUpdated: [
+ {
+ path: "/tmp/project/package.json",
+ dependencies: ["next"],
+ devDependencies: [],
+ scripts: [],
+ },
+ ],
}
: {
kind: "slack",
action: "created",
filesWritten: ["/tmp/project/agent/channels/slack.ts"],
filesSkipped: [],
- packageJsonUpdated: [],
+ packageJsonUpdated:
+ options.slackCredentials === "environment"
+ ? []
+ : [
+ {
+ path: "/tmp/project/package.json",
+ dependencies: ["@vercel/connect"],
+ devDependencies: [],
+ scripts: [],
+ },
+ ],
slackConnectorSlug: normalizeSlackConnectorSlug("my-agent"),
},
),
@@ -127,6 +144,35 @@ describe("addChannels box", () => {
expect(deps.provisionSlackbot).not.toHaveBeenCalled();
});
+ it("uses portable Slack credentials without provisioning when Vercel is unavailable", async () => {
+ const deps = createDeps();
+ const box = makeBox({
+ prompter: createPrompter(),
+ evePackage: TEST_EVE_PACKAGE,
+ slackCredentials: "environment",
+ deps,
+ });
+
+ const next = await runHeadless(
+ [box],
+ { ...noVercelState(), channelSelection: ["slack"] },
+ silentSink,
+ snapshot,
+ );
+
+ expect(deps.provisionSlackbot).not.toHaveBeenCalled();
+ expect(deps.runVercel).not.toHaveBeenCalled();
+ expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
+ expect(deps.ensureChannel).toHaveBeenCalledWith({
+ projectRoot: "/tmp/project",
+ kind: "slack",
+ slackConnectorSlug: "my-agent",
+ slackCredentials: "environment",
+ force: undefined,
+ });
+ expect(next.channels).toEqual(["slack"]);
+ });
+
it("passes the web scaffold options through to ensureChannel", async () => {
const deps = createDeps();
deps.detectPackageManager.mockResolvedValue({
@@ -351,28 +397,6 @@ describe("addChannels box", () => {
}
});
- it("skips the link fallback when the slackbot is declined", async () => {
- const deps = createDeps();
- const state = resolvedState(["slack"]);
- state.project = { kind: "unresolved" };
- state.vercelProject = { kind: "none" };
- const prompter = createFakePrompter({ single: () => "no" }).prompter;
- const box = makeBox({
- prompter,
- ensureLinkedProject: "interactive-vercel-link",
- deps,
- });
-
- const result = await runInteractive([box], state, silentSink, snapshot);
-
- expect(deps.runVercel).not.toHaveBeenCalled();
- expect(deps.provisionSlackbot).not.toHaveBeenCalled();
- expect(prompter.log.info).toHaveBeenCalledWith(
- "Slack channel was not added because Slackbot setup was skipped.",
- );
- expect(result.kind).toBe("done");
- });
-
it("fails the link fallback with the engine's copy when `vercel link` fails", async () => {
const deps = createDeps();
deps.runVercel.mockResolvedValue(false);
@@ -428,24 +452,41 @@ describe("addChannels box", () => {
}
});
- it("asks the slackbot question only when Slack is selected and undecided", async () => {
+ it("offers concrete existing connectors and a create-new option", async () => {
const deps = createDeps();
- const fake = createFakePrompter({ single: () => "no" });
+ let pickerOptions: unknown;
+ const fake = createFakePrompter({
+ single: (options) => {
+ pickerOptions = options;
+ return "slack/operations";
+ },
+ });
+ deps.provisionSlackbot.mockImplementation(async (_log, _root, _slug, _deps, options) => {
+ const selected = await options?.selectConnector?.(
+ [
+ { uid: "slack/my-agent", id: "scl_expected" },
+ { uid: "slack/operations", id: "scl_operations" },
+ ],
+ { uid: "slack/my-agent", id: "scl_expected" },
+ );
+ expect(selected).toEqual({ uid: "slack/operations", id: "scl_operations" });
+ return { state: "attached", connectorUid: "slack/operations" };
+ });
const box = makeBox({ prompter: fake.prompter, evePackage: TEST_EVE_PACKAGE, deps });
- const result = await runInteractive([box], resolvedState(["slack"]), silentSink, snapshot);
+ await runInteractive([box], resolvedState(["slack"]), silentSink, snapshot);
- expect(fake.selectMessages).toEqual(["Do you want to create your slackbot?"]);
- expect(deps.provisionSlackbot).not.toHaveBeenCalled();
- expect(deps.ensureChannel).not.toHaveBeenCalled();
- expect(fake.prompter.log.info).toHaveBeenCalledWith(
- "Slack channel was not added because Slackbot setup was skipped.",
+ expect(fake.selectMessages).toEqual(["Which Slack app would you like to use?"]);
+ expect(pickerOptions).toEqual(
+ expect.objectContaining({
+ initialValue: "slack/my-agent",
+ options: [
+ { value: "slack/my-agent", label: "Use slack/my-agent", hint: "Matches this agent" },
+ { value: "slack/operations", label: "Use slack/operations" },
+ { value: "create", label: "Create a new Slack app" },
+ ],
+ }),
);
- expect(result.kind).toBe("done");
- if (result.kind === "done") {
- expect(result.state.channels).toEqual([]);
- expect(result.state.deploymentPending).toBe(false);
- }
});
it("does not prompt when the slackbot decision is preset", async () => {
@@ -487,33 +528,11 @@ describe("addChannels box", () => {
"/tmp/project",
"my-agent",
undefined,
- { awaitChoice },
+ { awaitChoice, selectConnector: expect.any(Function) },
);
expect("awaitChoice" in prompter.log).toBe(false);
});
- it("still scaffolds Web Chat when the slackbot is skipped", async () => {
- const deps = createDeps();
- const prompter = createFakePrompter({ single: () => "no" }).prompter;
- const box = makeBox({ prompter, evePackage: TEST_EVE_PACKAGE, deps });
-
- const result = await runInteractive(
- [box],
- resolvedState(["web", "slack"]),
- silentSink,
- snapshot,
- );
-
- expect(deps.ensureChannel).toHaveBeenCalledTimes(1);
- expect(deps.ensureChannel).toHaveBeenCalledWith(expect.objectContaining({ kind: "web" }));
- expect(deps.provisionSlackbot).not.toHaveBeenCalled();
- expect(result.kind).toBe("done");
- if (result.kind === "done") {
- expect(result.state.channels).toEqual(["web"]);
- expect(result.state.deploymentPending).toBe(true);
- }
- });
-
it("records nothing for web when a Next.js project skips the scaffold", async () => {
const deps = createDeps();
deps.ensureChannel.mockResolvedValueOnce({
diff --git a/packages/eve/src/setup/boxes/add-channels.ts b/packages/eve/src/setup/boxes/add-channels.ts
index 6d0b6c98d..8d7c8db85 100644
--- a/packages/eve/src/setup/boxes/add-channels.ts
+++ b/packages/eve/src/setup/boxes/add-channels.ts
@@ -20,7 +20,7 @@ import {
projectResolutionFromDeployment,
type ProjectResolution,
} from "../project-resolution.js";
-import { confirm, SkippedSignal, type Asker } from "../ask.js";
+import type { Asker } from "../ask.js";
import type { Prompter } from "../prompter.js";
import {
provisionSlackbot,
@@ -152,14 +152,16 @@ export interface AddChannelsOptions {
* every package value comes from the build-stamped defaults.
*/
evePackage?: EvePackageContract;
- /** Skip the "Create slackbot?" prompt and use this answer. */
+ /** Reuse the preferred existing Slack connector without prompting. */
presetCreateSlackbot?: boolean;
/** Overwrite existing channel files (`eve channels add --force`). */
force?: boolean;
+ /** Credential source for Slack. Defaults to Vercel Connect. */
+ slackCredentials?: "vercel-connect" | "environment";
/**
- * Override for the web scaffold's Vercel services config. Defaults to
- * `hasVercelProject(state)`; `eve channels add` pins it to true so an
- * unlinked directory still gets the config, matching the dissolved engine.
+ * Override for the web scaffold's Vercel services config. The explicit
+ * environment plan takes precedence; otherwise this defaults to
+ * `hasVercelProject(state)`.
*/
configureVercelServices?: boolean;
/**
@@ -181,8 +183,7 @@ export interface AddChannelsOptions {
}
/**
- * What the user (or the preset) decided before `perform` runs effects.
- * `createSlackbot` is only consulted when Slack is in the channel selection.
+ * Inputs resolved before `perform` runs channel effects.
*/
export interface AddChannelsInput {
headless: boolean;
@@ -214,6 +215,7 @@ export interface AddChannelsPayload {
* channels were recorded (nothing ran) and when the install failed; only a
* success lets `apply` mark the deploy-time install as already done.
*/
+ dependenciesChanged: boolean;
dependenciesInstalled: boolean;
project: ProjectResolution;
slackbot?: AddChannelsSlackbotFacts;
@@ -278,6 +280,7 @@ export function addChannels(
slackConnectorSlug: slug,
force: options.force,
});
+ payload.dependenciesChanged ||= result.packageJsonUpdated.length > 0;
warnOverwrittenFiles(log, result.filesOverwritten);
if (result.action === "created" || result.action === "overwritten") {
log.success("Scaffolded channel: slack");
@@ -356,6 +359,7 @@ export function addChannels(
ensureWebOptions.webPackageVersions = { evePackage: options.evePackage };
}
const result = await deps.ensureChannel(ensureWebOptions);
+ payload.dependenciesChanged ||= result.packageJsonUpdated.length > 0;
signal?.throwIfAborted();
warnOverwrittenFiles(log, result.filesOverwritten);
if (
@@ -395,11 +399,27 @@ export function addChannels(
slug: SlackConnectorSlug,
signal?: AbortSignal,
): Promise<ProvisionSlackbotResult> {
- if (signal === undefined && options.prompter.awaitChoice === undefined) {
- return deps.provisionSlackbot(log, projectPath, slug);
- }
-
- const provisionOptions: ProvisionSlackbotOptions = {};
+ const provisionOptions: ProvisionSlackbotOptions = {
+ selectConnector: async (connectors, preferred) => {
+ if (options.presetCreateSlackbot === true) return preferred ?? connectors[0]!;
+ const choices = connectors.map((connector) => {
+ const choice: { value: string; label: string; hint?: string } = {
+ value: connector.uid,
+ label: `Use ${connector.uid}`,
+ };
+ if (connector.uid === preferred?.uid) choice.hint = "Matches this agent";
+ return choice;
+ });
+ const request = {
+ message: "Which Slack app would you like to use?",
+ options: [...choices, { value: "create", label: "Create a new Slack app" }],
+ initialValue: preferred?.uid,
+ };
+ const selected = await options.prompter.select<string>(request);
+ if (selected === "create") return "create";
+ return connectors.find((connector) => connector.uid === selected)!;
+ },
+ };
if (signal !== undefined) provisionOptions.signal = signal;
if (options.prompter.awaitChoice !== undefined) {
provisionOptions.awaitChoice = options.prompter.awaitChoice;
@@ -440,9 +460,31 @@ export function addChannels(
signal?: AbortSignal,
): Promise<void> {
if (!state.channelSelection.includes("slack")) return;
- assertSlackProjectReady(state);
const slug = await deps.deriveSlackConnectorSlug(projectPath, state.agentName);
+ if (options.slackCredentials === "environment") {
+ if (!state.slackScaffolded) {
+ const result = await deps.ensureChannel({
+ projectRoot: projectPath,
+ kind: "slack",
+ slackConnectorSlug: slug,
+ slackCredentials: "environment",
+ force: options.force,
+ });
+ payload.dependenciesChanged ||= result.packageJsonUpdated.length > 0;
+ warnOverwrittenFiles(log, result.filesOverwritten);
+ if (result.action === "created" || result.action === "overwritten") {
+ log.success("Scaffolded channel: slack");
+ } else {
+ log.info('Channel "slack" already exists. Skipping file creation.');
+ }
+ payload.slackScaffolded = true;
+ }
+ payload.channelsAdded.push("slack");
+ return;
+ }
+
+ assertSlackProjectReady(state);
if (state.slackbotCreated) {
// Rerun with a provisioned slackbot: never create a second connector.
if (!state.slackbotAttached) throw new Error(SLACKBOT_NOT_ATTACHED_ERROR);
@@ -459,11 +501,6 @@ export function addChannels(
return;
}
- if (input.createSlackbot !== true) {
- log.info("Slack channel was not added because Slackbot setup was skipped.");
- return;
- }
-
if (!isProjectResolved(payload.project)) {
// Only reachable with the ensureLinkedProject seam; without it the gate
// above already required a resolved project.
@@ -509,7 +546,7 @@ export function addChannels(
payload: AddChannelsPayload,
signal?: AbortSignal,
): Promise<void> {
- if (payload.channelsAdded.length === 0) return;
+ if (!payload.dependenciesChanged) return;
const installed = await withPhase(
log,
`Installing channel dependencies (${packageManager} install)...`,
@@ -543,6 +580,7 @@ export function addChannels(
channelsAdded: [],
webScaffolded: state.webScaffolded,
slackScaffolded: state.slackScaffolded,
+ dependenciesChanged: false,
dependenciesInstalled: false,
project: state.project,
};
@@ -561,37 +599,16 @@ export function addChannels(
async gather({ state }): Promise<AddChannelsInput> {
const headless = options.headless ?? false;
- // A deliberately plain Error, not HumanActionRequiredError: there is no
- // single command a human can run to finish this; the guided flow owns it.
- // A presetCreateSlackbot does not rescue headless Slack either.
- if (headless && state.channelSelection.includes("slack")) {
- throw new Error(SLACK_HEADLESS_ERROR);
- }
- // The preset short-circuits the question, exactly as the dual-face box did,
- // so it stays a factory option rather than a withAnswers rung.
+ // Connect opens a browser and remains interactive. Environment-backed
+ // Slack has no provisioning effect, so headless setup can scaffold it.
if (
- !state.channelSelection.includes("slack") ||
- options.presetCreateSlackbot !== undefined ||
- state.slackbotCreated
+ headless &&
+ state.channelSelection.includes("slack") &&
+ options.slackCredentials !== "environment"
) {
- return { headless, createSlackbot: options.presetCreateSlackbot };
- }
- try {
- const createSlackbot = await options.asker.ask(
- confirm({
- key: "create-slackbot",
- message: "Do you want to create your slackbot?",
- }),
- );
- return { headless, createSlackbot };
- } catch (error) {
- // The question is not required: a headless/assume skip means "do not
- // create", preserving the dual-face box's "false when unset" behavior.
- if (error instanceof SkippedSignal) {
- return { headless, createSlackbot: false };
- }
- throw error;
+ throw new Error(SLACK_HEADLESS_ERROR);
}
+ return { headless, createSlackbot: options.presetCreateSlackbot };
},
async perform({ state, input, signal }): Promise<AddChannelsPayload> {
@@ -620,13 +637,10 @@ export function addChannels(
webScaffolded: payload.webScaffolded,
slackScaffolded: payload.slackScaffolded,
deploymentPending: state.deploymentPending || payload.channelsAdded.length > 0,
- // Recorded channels touched the manifest, so the deploy-time install
- // gate must reflect this run's install outcome — an earlier success is
- // stale the moment new dependencies land in package.json.
- deploymentDependenciesInstalled:
- payload.channelsAdded.length > 0
- ? payload.dependenciesInstalled
- : state.deploymentDependenciesInstalled,
+ // Only manifest mutations invalidate an earlier dependency install.
+ deploymentDependenciesInstalled: payload.dependenciesChanged
+ ? payload.dependenciesInstalled
+ : state.deploymentDependenciesInstalled,
project: mergeProjectResolution(state.project, payload.project),
};
if (payload.slackbot === undefined) {
diff --git a/packages/eve/src/setup/boxes/select-channels.ts b/packages/eve/src/setup/boxes/select-channels.ts
index 1b4106800..eaee2e9ec 100644
--- a/packages/eve/src/setup/boxes/select-channels.ts
+++ b/packages/eve/src/setup/boxes/select-channels.ts
@@ -33,10 +33,9 @@ export interface SelectChannelsOptions {
presetChannels?: ChannelKind[];
/**
* Picker shape, chosen explicitly because the variants differ in whether a
- * selection is required, whether the REPL row is shown, and how Slack is
- * gated. The "channels-add" picker allows an empty submission and keeps Slack
- * selectable from an unlinked directory because its add-channels box can run
- * an interactive `vercel link` on demand.
+ * selection is required and whether the REPL row is shown. The
+ * "channels-add" picker allows an empty submission and keeps Slack selectable
+ * because capability planning later chooses Connect or environment credentials.
*/
variant: "onboarding" | "in-project" | "channels-add";
/**
@@ -58,7 +57,7 @@ export interface SelectChannelsOptions {
* chosen channels afterward from `state.channelSelection`. During onboarding
* the deployment decision has not been made yet, so Slack is never gated here:
* picking it is what makes the later provisioning box resolve to Vercel. Only
- * the in-project variant gates Slack, on the detected on-disk link.
+ * the legacy in-project variant gates Slack on the detected on-disk link.
*
* The onboarding picker is required and always carries a locked, pre-selected
* Terminal UI row, so an empty selection is impossible: every agent can at least be
diff --git a/packages/eve/src/setup/channel-setup-deployment.ts b/packages/eve/src/setup/channel-setup-deployment.ts
new file mode 100644
index 000000000..df5e84655
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-deployment.ts
@@ -0,0 +1,42 @@
+import type { DeployProjectDeps } from "./boxes/deploy-project.js";
+import { deployProject } from "./boxes/deploy-project.js";
+import type { ChannelSetupUi } from "./channel-setup-ui.js";
+import { runInteractive } from "./runner.js";
+import { snapshotSetupState, type SetupState } from "./state.js";
+import type { OutputSink } from "./step.js";
+
+/** Offers and, when accepted, performs deployment after channel setup completes. */
+export async function deployChannelSetup(input: {
+ state: SetupState;
+ ui: ChannelSetupUi;
+ signal?: AbortSignal;
+ presetDeploy?: boolean;
+ deps?: DeployProjectDeps;
+}): Promise<SetupState> {
+ const shouldDeploy =
+ input.presetDeploy ??
+ (await input.ui.confirm({
+ key: "deploy-channels",
+ message: "Deploy this project to Vercel now?",
+ recommended: true,
+ }));
+ if (!shouldDeploy) {
+ input.ui.nextSteps(["Run `eve deploy` to deploy when ready."]);
+ return input.state;
+ }
+
+ const sink: OutputSink = { write: (line) => input.ui.prompter.log.message(line) };
+ const result = await runInteractive(
+ [
+ deployProject({
+ prompter: input.ui.prompter,
+ ensureLinkedProject: "interactive-vercel-link",
+ deps: input.deps,
+ }),
+ ],
+ input.state,
+ sink,
+ { snapshot: snapshotSetupState, signal: input.signal },
+ );
+ return result.kind === "done" ? result.state : input.state;
+}
diff --git a/packages/eve/src/setup/channel-setup-environment.test.ts b/packages/eve/src/setup/channel-setup-environment.test.ts
new file mode 100644
index 000000000..5a9c26670
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-environment.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ channelSetupEnvironment,
+ describeChannelSetupEnvironment,
+} from "./channel-setup-environment.js";
+
+describe("channel setup environment", () => {
+ it("keeps authenticated and unlinked as an available Vercel setup", () => {
+ const environment = channelSetupEnvironment("authenticated", { kind: "unresolved" });
+ expect(environment).toEqual({
+ vercel: { kind: "available", project: { kind: "unresolved" } },
+ });
+ expect(describeChannelSetupEnvironment(environment)).toBe(
+ "Found an authenticated Vercel account; this directory is not linked to a project.",
+ );
+ });
+
+ it("reports the portable fallback when logged out", () => {
+ const environment = channelSetupEnvironment("logged-out", { kind: "unresolved" });
+ expect(environment).toEqual({ vercel: { kind: "unavailable", reason: "logged-out" } });
+ expect(describeChannelSetupEnvironment(environment)).toBe(
+ "No authenticated Vercel account found; using portable channel setup.",
+ );
+ });
+});
diff --git a/packages/eve/src/setup/channel-setup-environment.ts b/packages/eve/src/setup/channel-setup-environment.ts
new file mode 100644
index 000000000..449832273
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-environment.ts
@@ -0,0 +1,41 @@
+import type { ProjectResolution } from "./project-resolution.js";
+import type { VercelAuthStatus } from "./vercel-project.js";
+
+/** Read-only hosting facts available to channel-owned setup hooks. */
+export interface ChannelSetupEnvironment {
+ vercel:
+ | { kind: "available"; project: ProjectResolution }
+ | { kind: "unavailable"; reason: Exclude<VercelAuthStatus, "authenticated"> };
+}
+
+/** Describes the result of the read-only Vercel capability probe. */
+export function describeChannelSetupEnvironment(environment: ChannelSetupEnvironment): string {
+ if (environment.vercel.kind === "available") {
+ switch (environment.vercel.project.kind) {
+ case "deployed":
+ return `Found an authenticated Vercel account and deployed project (${environment.vercel.project.productionUrl}).`;
+ case "linked":
+ return "Found an authenticated Vercel account and linked project.";
+ case "unresolved":
+ return "Found an authenticated Vercel account; this directory is not linked to a project.";
+ }
+ }
+ switch (environment.vercel.reason) {
+ case "logged-out":
+ return "No authenticated Vercel account found; using portable channel setup.";
+ case "cli-missing":
+ return "Vercel CLI not found; using portable channel setup.";
+ case "unavailable":
+ return "Could not verify the Vercel account; using portable channel setup.";
+ }
+}
+
+/** Builds channel setup facts from the independent Vercel probes. */
+export function channelSetupEnvironment(
+ authStatus: VercelAuthStatus,
+ project: ProjectResolution,
+): ChannelSetupEnvironment {
+ return authStatus === "authenticated"
+ ? { vercel: { kind: "available", project } }
+ : { vercel: { kind: "unavailable", reason: authStatus } };
+}
diff --git a/packages/eve/src/setup/channel-setup-integration.ts b/packages/eve/src/setup/channel-setup-integration.ts
new file mode 100644
index 000000000..965b8a3b1
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-integration.ts
@@ -0,0 +1,31 @@
+import type { AddChannelsDeps } from "./boxes/add-channels.js";
+import type { ChannelSetupEnvironment } from "./channel-setup-environment.js";
+import type { ChannelSetupUi } from "./channel-setup-ui.js";
+import type { ChannelKind } from "./scaffold/index.js";
+import type { SetupState } from "./state.js";
+
+/** Shared inputs available to a channel-owned setup implementation. */
+export interface ChannelSetupContext {
+ readonly environment: ChannelSetupEnvironment;
+ readonly state: Readonly<SetupState>;
+ readonly ui: ChannelSetupUi;
+ readonly signal?: AbortSignal;
+ readonly force?: boolean;
+ readonly headless?: boolean;
+ readonly presetCreateSlackbot?: boolean;
+ readonly presetPortableCredentials?: boolean;
+ readonly deps?: AddChannelsDeps;
+}
+
+/** Structured outcome from a channel-owned setup implementation. */
+export type ChannelSetupResult =
+ | { readonly kind: "done"; readonly state: SetupState }
+ | { readonly kind: "cancelled" };
+
+/** Setup behavior paired with canonical channel catalog metadata. */
+export interface ChannelSetupIntegration {
+ readonly kind: ChannelKind;
+ readonly label: string;
+ readonly hint?: string;
+ setup(context: ChannelSetupContext): Promise<ChannelSetupResult>;
+}
diff --git a/packages/eve/src/setup/channel-setup-integrations.test.ts b/packages/eve/src/setup/channel-setup-integrations.test.ts
new file mode 100644
index 000000000..6433e690c
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-integrations.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+
+import { interactiveAsker } from "./ask.js";
+import type { AddChannelsDeps } from "./boxes/add-channels.js";
+import { channelSetupEnvironment } from "./channel-setup-environment.js";
+import { channelSetupIntegration, createChannelSetupUi } from "./channel-setup-integrations.js";
+import { createDefaultSetupState } from "./state.js";
+import { WizardCancelledError } from "./step.js";
+
+function context(prompter = createFakePrompter().prompter) {
+ return {
+ environment: channelSetupEnvironment("logged-out", { kind: "unresolved" } as const),
+ state: {
+ ...createDefaultSetupState(),
+ projectPath: { kind: "resolved", inPlace: true, path: "/tmp/project" } as const,
+ channelSelection: ["slack" as const],
+ },
+ ui: createChannelSetupUi({ asker: interactiveAsker(prompter), prompter }),
+ };
+}
+
+describe("channel setup integrations", () => {
+ it("keeps picker cancellation as a structured result", async () => {
+ const fake = createFakePrompter({
+ single: () => {
+ throw new WizardCancelledError();
+ },
+ });
+
+ const result = await channelSetupIntegration("slack").setup(context(fake.prompter));
+
+ expect(result).toMatchObject({ kind: "cancelled" });
+ });
+
+ it("keeps Web setup independent of Slack credential prompts", async () => {
+ const fake = createFakePrompter();
+ const ensureChannel = vi.fn<AddChannelsDeps["ensureChannel"]>(async () => ({
+ kind: "web",
+ action: "skipped",
+ skipReason: "nextjs-project",
+ filesWritten: [],
+ filesSkipped: ["/tmp/project/package.json"],
+ packageJsonUpdated: [],
+ }));
+
+ const result = await channelSetupIntegration("web").setup({
+ ...context(fake.prompter),
+ state: {
+ ...context(fake.prompter).state,
+ channelSelection: ["web"],
+ },
+ deps: {
+ ensureChannel,
+ deriveSlackConnectorSlug: vi.fn(),
+ provisionSlackbot: vi.fn(),
+ reconcileSlackUid: vi.fn(),
+ detectPackageManager: vi.fn<AddChannelsDeps["detectPackageManager"]>(async () => ({
+ kind: "pnpm",
+ source: "default",
+ })),
+ runPackageManagerInstall: vi.fn(),
+ runVercel: vi.fn(),
+ detectDeployment: vi.fn(),
+ },
+ });
+
+ expect(result.kind).toBe("done");
+ expect(ensureChannel).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: "web", configureVercelServices: false }),
+ );
+ expect(fake.selectMessages).toEqual([]);
+ });
+});
diff --git a/packages/eve/src/setup/channel-setup-integrations.ts b/packages/eve/src/setup/channel-setup-integrations.ts
new file mode 100644
index 000000000..3f016eaa2
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-integrations.ts
@@ -0,0 +1,19 @@
+import type { ChannelSetupIntegration } from "./channel-setup-integration.js";
+import { SLACK_CHANNEL_SETUP } from "./channel-setup-slack.js";
+import { WEB_CHANNEL_SETUP } from "./channel-setup-web.js";
+import type { ChannelKind } from "./scaffold/index.js";
+
+/** Built-in channel integrations in canonical picker order. */
+export const CHANNEL_SETUP_INTEGRATIONS: readonly ChannelSetupIntegration[] = [
+ WEB_CHANNEL_SETUP,
+ SLACK_CHANNEL_SETUP,
+];
+
+/** Resolves a channel setup integration by its filesystem-facing kind. */
+export function channelSetupIntegration(kind: ChannelKind): ChannelSetupIntegration {
+ const integration = CHANNEL_SETUP_INTEGRATIONS.find((candidate) => candidate.kind === kind);
+ if (integration === undefined) throw new Error(`No channel setup integration for "${kind}".`);
+ return integration;
+}
+
+export { createChannelSetupUi } from "./channel-setup-ui.js";
diff --git a/packages/eve/src/setup/channel-setup-runner.ts b/packages/eve/src/setup/channel-setup-runner.ts
new file mode 100644
index 000000000..d3c9bda2b
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-runner.ts
@@ -0,0 +1,33 @@
+import { addChannels } from "./boxes/add-channels.js";
+import type { ChannelSetupContext, ChannelSetupResult } from "./channel-setup-integration.js";
+import { runInteractive } from "./runner.js";
+import { snapshotSetupState, type SetupState } from "./state.js";
+import type { OutputSink } from "./step.js";
+
+/** Runs the shared scaffold box with decisions supplied by a channel integration. */
+export async function runChannelSetup(
+ context: ChannelSetupContext,
+ options: {
+ configureVercelServices?: boolean;
+ slackCredentials?: "vercel-connect" | "environment";
+ ensureLinkedProject?: "interactive-vercel-link";
+ },
+): Promise<ChannelSetupResult> {
+ const box = addChannels({
+ asker: context.ui.asker,
+ prompter: context.ui.prompter,
+ headless: context.headless,
+ presetCreateSlackbot: context.presetCreateSlackbot,
+ force: context.force,
+ configureVercelServices: options.configureVercelServices,
+ slackCredentials: options.slackCredentials,
+ ensureLinkedProject: options.ensureLinkedProject,
+ deps: context.deps,
+ });
+ const sink: OutputSink = { write: (line) => context.ui.prompter.log.message(line) };
+ const result = await runInteractive([box], context.state as SetupState, sink, {
+ snapshot: snapshotSetupState,
+ signal: context.signal,
+ });
+ return result.kind === "done" ? { kind: "done", state: result.state } : { kind: "cancelled" };
+}
diff --git a/packages/eve/src/setup/channel-setup-slack.ts b/packages/eve/src/setup/channel-setup-slack.ts
new file mode 100644
index 000000000..4b667c635
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-slack.ts
@@ -0,0 +1,66 @@
+import type { ChannelSetupIntegration } from "./channel-setup-integration.js";
+import { runChannelSetup } from "./channel-setup-runner.js";
+import { WizardCancelledError } from "./step.js";
+
+async function choosePortableCredentials(
+ context: Parameters<ChannelSetupIntegration["setup"]>[0],
+): Promise<"vercel-connect" | "environment" | "cancelled"> {
+ if (context.environment.vercel.kind === "available") return "vercel-connect";
+ if (context.presetPortableCredentials !== undefined) {
+ return context.presetPortableCredentials ? "environment" : "vercel-connect";
+ }
+ try {
+ return (await context.ui.prompter.select<"vercel" | "portable">({
+ message: "How would you like to configure Slack?",
+ options: [
+ {
+ value: "vercel",
+ label: "Set up Vercel Connect",
+ hint: "Sign in and link this project",
+ },
+ {
+ value: "portable",
+ label: "Use portable credentials",
+ hint: "Read Slack tokens from environment variables",
+ },
+ ],
+ })) === "portable"
+ ? "environment"
+ : "vercel-connect";
+ } catch (error) {
+ if (error instanceof WizardCancelledError) return "cancelled";
+ throw error;
+ }
+}
+
+/** Slack's channel-owned credential choice, provisioning, and scaffold behavior. */
+export const SLACK_CHANNEL_SETUP: ChannelSetupIntegration = {
+ kind: "slack",
+ label: "Slack",
+ hint: "Slack app mentions and DMs",
+ async setup(context) {
+ const credentials = await choosePortableCredentials(context);
+ if (credentials === "cancelled") return { kind: "cancelled" };
+
+ const result = await runChannelSetup(
+ context,
+ credentials === "environment"
+ ? { slackCredentials: "environment" }
+ : {
+ slackCredentials: "vercel-connect",
+ ensureLinkedProject: "interactive-vercel-link",
+ },
+ );
+ if (
+ result.kind === "done" &&
+ credentials === "environment" &&
+ result.state.channels.includes("slack")
+ ) {
+ context.ui.nextSteps([
+ "Set SLACK_BOT_TOKEN and SLACK_SIGNING_SECRET in .env.local (listed in .env.example).",
+ "Configure your Slack app to send events to /eve/v1/slack on your public agent URL.",
+ ]);
+ }
+ return result;
+ },
+};
diff --git a/packages/eve/src/setup/channel-setup-ui.test.ts b/packages/eve/src/setup/channel-setup-ui.test.ts
new file mode 100644
index 000000000..39c510c91
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-ui.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+
+import { interactiveAsker } from "./ask.js";
+import { createChannelSetupUi } from "./channel-setup-ui.js";
+
+describe("createChannelSetupUi", () => {
+ it("renders integration-owned next steps through the shared notice", () => {
+ const fake = createFakePrompter();
+ const ui = createChannelSetupUi({
+ asker: interactiveAsker(fake.prompter),
+ prompter: fake.prompter,
+ });
+
+ ui.nextSteps(["Set TOKEN in .env.local.", "Configure the webhook."]);
+
+ expect(fake.prompter.note).toHaveBeenCalledWith(
+ "Set TOKEN in .env.local.\nConfigure the webhook.",
+ "Next steps",
+ { tone: "success" },
+ );
+ });
+});
diff --git a/packages/eve/src/setup/channel-setup-ui.ts b/packages/eve/src/setup/channel-setup-ui.ts
new file mode 100644
index 000000000..8d8db0723
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-ui.ts
@@ -0,0 +1,29 @@
+import { confirm, SkippedSignal, type Asker } from "./ask.js";
+import type { Prompter } from "./prompter.js";
+
+/** UI capabilities available to a channel-owned setup hook. */
+export interface ChannelSetupUi {
+ readonly asker: Asker;
+ readonly prompter: Prompter;
+ confirm(input: { key: string; message: string; recommended?: boolean }): Promise<boolean>;
+ nextSteps(lines: readonly string[]): void;
+}
+
+/** Adapts the shared setup asker and prompter to the channel hook UI. */
+export function createChannelSetupUi(input: { asker: Asker; prompter: Prompter }): ChannelSetupUi {
+ return {
+ ...input,
+ async confirm(question) {
+ try {
+ return await input.asker.ask(confirm(question));
+ } catch (error) {
+ if (error instanceof SkippedSignal) return false;
+ throw error;
+ }
+ },
+ nextSteps(lines) {
+ if (lines.length === 0) return;
+ input.prompter.note(lines.join("\n"), "Next steps", { tone: "success" });
+ },
+ };
+}
diff --git a/packages/eve/src/setup/channel-setup-web.ts b/packages/eve/src/setup/channel-setup-web.ts
new file mode 100644
index 000000000..0cf4cf171
--- /dev/null
+++ b/packages/eve/src/setup/channel-setup-web.ts
@@ -0,0 +1,14 @@
+import type { ChannelSetupIntegration } from "./channel-setup-integration.js";
+import { runChannelSetup } from "./channel-setup-runner.js";
+
+/** Web Chat's channel-owned setup behavior. */
+export const WEB_CHANNEL_SETUP: ChannelSetupIntegration = {
+ kind: "web",
+ label: "Web Chat",
+ hint: "Browser-based chat interface",
+ setup(context) {
+ return runChannelSetup(context, {
+ configureVercelServices: context.environment.vercel.kind === "available",
+ });
+ },
+};
diff --git a/packages/eve/src/setup/flows/channels.test.ts b/packages/eve/src/setup/flows/channels.test.ts
index 878f1441e..1cf95041b 100644
--- a/packages/eve/src/setup/flows/channels.test.ts
+++ b/packages/eve/src/setup/flows/channels.test.ts
@@ -248,46 +248,20 @@ describe("runChannelsFlow", () => {
return listPaints[0]?.find((option) => option.value === "slack");
}
- it("points an unlinked Vercel-dependent channel at /model when logged in", async () => {
- expect(await slackRowFor({ deployment: UNLINKED, authStatus: "authenticated" })).toMatchObject({
- disabled: true,
- disabledReason: "Requires Vercel account, see /model",
- disabledReasonTone: "warning",
- });
- });
-
- it("points a Vercel-dependent channel at /vc:login when logged out, even if linked", async () => {
- // Authentication is a separate axis from link: a linked-but-logged-out
- // directory still cannot provision, so the row routes to /vc:login, not /model.
- for (const deployment of [UNLINKED, LINKED]) {
- expect(await slackRowFor({ deployment, authStatus: "logged-out" })).toMatchObject({
- disabled: true,
- disabledReason: "Log in to Vercel first, see /vc:login",
- disabledReasonTone: "warning",
- });
- }
- });
-
- it("points a Vercel-dependent channel at the CLI install when the CLI is missing", async () => {
- expect(await slackRowFor({ deployment: UNLINKED, authStatus: "cli-missing" })).toMatchObject({
- disabled: true,
- disabledReason: "Vercel CLI not found, see /vc:install",
- disabledReasonTone: "warning",
- });
- });
-
- it("flags a Vercel-dependent channel as unreachable on a transient fault", async () => {
- expect(await slackRowFor({ deployment: LINKED, authStatus: "unavailable" })).toMatchObject({
- disabled: true,
- disabledReason: "Couldn't reach Vercel, check your connection",
- disabledReasonTone: "warning",
- });
- });
-
- it("keeps a Vercel-dependent channel addable when authenticated and linked", async () => {
- const slackRow = await slackRowFor({ deployment: LINKED, authStatus: "authenticated" });
- expect(slackRow?.disabled).toBeUndefined();
- });
+ it.each([
+ [UNLINKED, "authenticated"],
+ [UNLINKED, "logged-out"],
+ [LINKED, "logged-out"],
+ [UNLINKED, "cli-missing"],
+ [LINKED, "unavailable"],
+ ] as const)(
+ "keeps Slack addable for deployment %o and Vercel status %s",
+ async (deployment, authStatus) => {
+ const slackRow = await slackRowFor({ deployment, authStatus });
+ expect(slackRow).toMatchObject({ value: "slack", label: "Slack" });
+ expect(slackRow?.disabled).toBeUndefined();
+ },
+ );
it("shows the active Terminal UI as a checked task and keeps Web Chat addable", async () => {
const { single, listPaints } = scriptList(["web", "done"]);
@@ -412,12 +386,10 @@ describe("runChannelsFlow", () => {
});
it("returns to the list when a channel's sub-flow is cancelled", async () => {
- const { single, listPaints } = scriptList(["slack", "done"], (opts) => {
- if (/slackbot/i.test(opts.message)) throw new WizardCancelledError();
- throw new Error(`Unexpected select: ${opts.message}`);
- });
+ const { single, listPaints } = scriptList(["slack", "done"]);
const fake = createFakePrompter({ single });
const addChannelsDeps = createAddChannelsDeps();
+ addChannelsDeps.provisionSlackbot.mockResolvedValue({ state: "cancelled" });
const result = await runChannelsFlow({
appRoot: APP_ROOT,
diff --git a/packages/eve/src/setup/flows/channels.ts b/packages/eve/src/setup/flows/channels.ts
index 05156335c..1e55773f2 100644
--- a/packages/eve/src/setup/flows/channels.ts
+++ b/packages/eve/src/setup/flows/channels.ts
@@ -1,31 +1,27 @@
-import { SCAFFOLDABLE_CHANNELS, type ChannelKind } from "#setup/scaffold/index.js";
+import type { ChannelKind } from "#setup/scaffold/index.js";
import { toErrorMessage } from "#shared/errors.js";
import { interactiveAsker } from "../ask.js";
-import { addChannels, type AddChannelsDeps } from "../boxes/add-channels.js";
-import { CHANNELS_PROMPT_MESSAGE, selectChannels } from "../boxes/select-channels.js";
+import type { AddChannelsDeps } from "../boxes/add-channels.js";
+import { CHANNELS_PROMPT_MESSAGE } from "../boxes/select-channels.js";
+import { channelSetupEnvironment } from "../channel-setup-environment.js";
+import {
+ CHANNEL_SETUP_INTEGRATIONS,
+ channelSetupIntegration,
+ createChannelSetupUi,
+} from "../channel-setup-integrations.js";
import {
assertCanAddSelectedChannels,
inspectExistingChannelRegistrations,
type ExistingChannelRegistrations,
} from "../channel-add-conflicts.js";
-import {
- detectDeployment,
- isProjectResolved,
- projectResolutionFromDeployment,
-} from "../project-resolution.js";
+import { detectDeployment, projectResolutionFromDeployment } from "../project-resolution.js";
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,
- vercelAuthBlockerReason,
- type VercelAuthStatus,
-} from "../vercel-project.js";
-import { withSpinner } from "../with-spinner.js";
-import { prompterSink } from "./in-project.js";
+import { createDefaultSetupState, type SetupState } from "../state.js";
+import { getVercelAuthStatus } from "../vercel-project.js";
+import { withSpinner } from "../with-spinner.js";
/** Injected for tests; defaults to the real detection and box effects. */
export interface ChannelsFlowDeps {
@@ -56,27 +52,22 @@ export type ChannelsFlowResult =
message: string;
};
-/** The post-Slack "see it live" chooser's title. */
+/** Title for Slack's optional deploy-and-chat continuation. */
export const SEE_IT_LIVE_MESSAGE = "See it live";
-/**
- * The streamlined hop from a fresh Slack connection to a live agent. A Slack
- * bot only receives messages once the project is deployed, so rather than leave
- * the user to discover `/deploy`, offer it inline: "Deploy and chat" ends the
- * channel loop so the caller can deploy and surface the workspace; "Later" (or
- * Esc) drops back to the channel list unchanged.
- */
-async function promptSeeItLive(prompter: Prompter): Promise<"deploy" | "later"> {
+async function offerDeployAndChat(prompter: Prompter): Promise<boolean> {
try {
- return await prompter.select<"deploy" | "later">({
- message: SEE_IT_LIVE_MESSAGE,
- options: [
- { value: "deploy", label: "Deploy and chat" },
- { value: "later", label: "Later" },
- ],
- });
+ return (
+ (await prompter.select<"deploy" | "later">({
+ message: SEE_IT_LIVE_MESSAGE,
+ options: [
+ { value: "deploy", label: "Deploy and chat" },
+ { value: "later", label: "Later" },
+ ],
+ })) === "deploy"
+ );
} catch (error) {
- if (error instanceof WizardCancelledError) return "later";
+ if (error instanceof WizardCancelledError) return false;
throw error;
}
}
@@ -100,10 +91,8 @@ type ChannelPickResult = { kind: "picked"; value: ChannelListRow } | { kind: "ca
async function pickChannel(
prompter: Prompter,
registrations: ExistingChannelRegistrations,
- projectLinked: boolean,
- authStatus: VercelAuthStatus,
): Promise<ChannelPickResult> {
- const rows = channelListRows(registrations, projectLinked, authStatus);
+ const rows = channelListRows(registrations);
// When every channel is already added or unavailable, the only action left
// is to finish: default to "Done" instead of a completed row.
const onlyDoneRemains = !rows.some(
@@ -150,28 +139,8 @@ function deployAndChatDetails(state: Readonly<SetupState>): {
* Next.js app itself (`webAppPresent`), not the authored session-route channel
* used by this REPL.
*/
-/**
- * Why a Vercel-backed channel can't be added yet, or `undefined` when it can.
- * Provisioning needs an installed CLI, a logged-in session, and a linked
- * project — all three, on independent axes — so each missing piece points at
- * its own fix rather than dead-ending. Authentication is checked regardless of
- * link state: a linked directory whose session is logged out still cannot
- * provision.
- */
-function vercelChannelBlocker(
- authStatus: VercelAuthStatus,
- projectLinked: boolean,
-): string | undefined {
- const authBlocker = vercelAuthBlockerReason(authStatus);
- if (authBlocker !== undefined) return authBlocker;
- if (!projectLinked) return "Requires Vercel account, see /model";
- return undefined;
-}
-
function channelListRows(
registrations: ExistingChannelRegistrations,
- projectLinked: boolean,
- authStatus: VercelAuthStatus,
): SelectOption<ChannelListRow>[] {
const rows: SelectOption<ChannelListRow>[] = [
{
@@ -181,7 +150,7 @@ function channelListRows(
focusHint: "Already installed",
},
];
- for (const channel of SCAFFOLDABLE_CHANNELS) {
+ for (const channel of CHANNEL_SETUP_INTEGRATIONS) {
if (channelAlreadyAdded(registrations, channel.kind)) {
rows.push({
value: channel.kind,
@@ -196,22 +165,6 @@ function channelListRows(
rows.push({ value: channel.kind, label: channel.label, disabled: true, disabledReason });
continue;
}
- // The add sub-flow for these channels provisions against the linked Vercel
- // project, which needs an installed CLI, a logged-in session, and a link.
- // The row points at whichever is missing instead of dead-ending.
- if (channel.requiresVercelProject === true) {
- const blocker = vercelChannelBlocker(authStatus, projectLinked);
- if (blocker !== undefined) {
- rows.push({
- value: channel.kind,
- label: channel.label,
- disabled: true,
- disabledReason: blocker,
- disabledReasonTone: "warning",
- });
- continue;
- }
- }
const row: SelectOption<ChannelListRow> = { value: channel.kind, label: channel.label };
if (channel.hint !== undefined) row.hint = channel.hint;
rows.push(row);
@@ -230,14 +183,9 @@ function channelListRows(
* the list after something was added reports the additions exactly like Done;
* only an empty exit folds to cancelled.
*
- * Each pick reuses the `eve channels add` composition — the same conflict
- * validation, Vercel services config pinned on, and the default empty agent
- * name (the Slack connector slug falls back to the package.json name) — with
- * two TUI-specific differences: no trailing deploy box (the TUI exposes
- * `/deploy` as its own command), and no inline link pickers — channels that
- * provision against the Vercel project render disabled with a warning
- * pointing at /model while the directory is unlinked, so a pick can never
- * reach provisioning without a link.
+ * The outer loop owns only picker lifecycle, conflict validation, and durable
+ * re-inspection. Each selected integration owns its prompts, provisioning,
+ * scaffold choices, deployment continuation, and next-step guidance.
*/
export async function runChannelsFlow(input: {
appRoot: string;
@@ -274,6 +222,10 @@ export async function runChannelsFlow(input: {
// The detected on-disk link is the only seeded fact, exactly like
// `eve channels add`. The state carries forward across picks so a link or
// slackbot established for one channel is not redone for the next.
+ const environment = channelSetupEnvironment(
+ authStatus,
+ projectResolutionFromDeployment(deployment),
+ );
let state: SetupState = {
...createDefaultSetupState(),
project: projectResolutionFromDeployment(deployment),
@@ -282,12 +234,7 @@ export async function runChannelsFlow(input: {
let retainedFailure: string | undefined;
while (true) {
- const picked = await pickChannel(
- prompter,
- registrations,
- isProjectResolved(state.project),
- authStatus,
- );
+ const picked = await pickChannel(prompter, registrations);
if (picked.kind === "cancelled") {
if (state.channels.length === 0) return { kind: "cancelled" };
break;
@@ -296,69 +243,60 @@ export async function runChannelsFlow(input: {
if (pick === "done") break;
if (pick === "repl" || channelAlreadyAdded(registrations, pick)) continue;
- const boxes: AnySetupBox<SetupState>[] = [
- selectChannels({
- asker: interactiveAsker(prompter),
- variant: "channels-add",
- presetChannels: [pick],
- validateSelection: (channels) => assertCanAddSelectedChannels(channels, registrations),
- }),
- addChannels({
- asker: interactiveAsker(prompter),
- prompter,
- configureVercelServices: true,
- deps: deps.addChannels,
- }),
- ];
- let result: Awaited<ReturnType<typeof runInteractive<SetupState>>>;
+ assertCanAddSelectedChannels([pick], registrations);
+ let result: Awaited<ReturnType<ReturnType<typeof channelSetupIntegration>["setup"]>>;
try {
- result = await runInteractive(boxes, state, prompterSink(prompter), {
- snapshot: snapshotSetupState,
+ result = await channelSetupIntegration(pick).setup({
+ environment,
+ state: { ...state, channelSelection: [pick] },
+ ui: createChannelSetupUi({ asker: interactiveAsker(prompter), prompter }),
signal,
+ deps: deps.addChannels,
});
} catch (error) {
- const observed = await withSpinner(prompter, "Checking the project…", () =>
- deps.inspectExistingChannelRegistrations(appRoot),
- );
+ // Cancellation can arrive after files land. Re-inspect without an
+ // abort-aware spinner in that case so durable success is still reported.
+ const observed =
+ signal?.aborted === true
+ ? await deps.inspectExistingChannelRegistrations(appRoot)
+ : await withSpinner(prompter, "Checking the project…", () =>
+ deps.inspectExistingChannelRegistrations(appRoot),
+ );
if (channelLandedDuringSubflow(registrations, observed, pick)) {
state = { ...state, channels: appendChannel(state.channels, pick) };
registrations = observed;
- retainedFailure = toErrorMessage(error);
+ if (!(error instanceof WizardCancelledError)) retainedFailure = toErrorMessage(error);
if (signal?.aborted === true) break;
continue;
}
+ if (error instanceof WizardCancelledError) {
+ registrations = observed;
+ continue;
+ }
// A provisioning failure (login / forbidden / missing CLI) throws before
// the channel file is scaffolded, so it never lands here — it propagates
// to the command handler, which routes it to its fix command.
throw error;
}
- if (result.kind === "done") {
- state = result.state;
- 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.
- if (
- pick === "slack" &&
- state.slackbotAttached &&
- (await promptSeeItLive(prompter)) === "deploy"
- ) {
- return {
- kind: "deploy-and-chat",
- addedChannels: state.channels,
- chat: deployAndChatDetails(state),
- };
- }
- } else {
- const observed = await withSpinner(prompter, "Checking the project…", () =>
- deps.inspectExistingChannelRegistrations(appRoot),
- );
- if (channelLandedDuringSubflow(registrations, observed, pick)) {
- return { kind: "done", addedChannels: appendChannel(state.channels, pick) };
- }
- registrations = observed;
+ if (result.kind === "done") state = result.state;
+ const observed =
+ signal?.aborted === true
+ ? await deps.inspectExistingChannelRegistrations(appRoot)
+ : await withSpinner(prompter, "Checking the project…", () =>
+ deps.inspectExistingChannelRegistrations(appRoot),
+ );
+ if (channelLandedDuringSubflow(registrations, observed, pick)) {
+ state = { ...state, channels: appendChannel(state.channels, pick) };
+ }
+ registrations = observed;
+ if (signal?.aborted === true) break;
+ if (result.kind === "cancelled") continue;
+ if (pick === "slack" && state.slackbotAttached && (await offerDeployAndChat(prompter))) {
+ return {
+ kind: "deploy-and-chat",
+ addedChannels: state.channels,
+ chat: deployAndChatDetails(state),
+ };
}
}
diff --git a/packages/eve/src/setup/scaffold/channels-catalog.ts b/packages/eve/src/setup/scaffold/channels-catalog.ts
index a157a0784..9a52d4632 100644
--- a/packages/eve/src/setup/scaffold/channels-catalog.ts
+++ b/packages/eve/src/setup/scaffold/channels-catalog.ts
@@ -23,8 +23,6 @@ interface ChannelScaffold {
label: string;
/** Optional picker hint. */
hint?: string;
- /** The add sub-flow provisions against the linked Vercel project. */
- requiresVercelProject?: true;
}
/**
@@ -40,8 +38,7 @@ const CHANNEL_SCAFFOLDS: readonly ChannelScaffold[] = [
slug: "slack",
kind: "slack",
label: "Slack",
- hint: "Creates slackbot and deploys to Vercel",
- requiresVercelProject: true,
+ hint: "Slack app mentions and DMs",
},
];
@@ -55,8 +52,6 @@ export interface ScaffoldableChannel {
label: string;
/** Optional picker hint. */
hint?: string;
- /** The add sub-flow provisions against the linked Vercel project. */
- requiresVercelProject?: true;
}
function buildScaffoldableChannels(): ScaffoldableChannel[] {
@@ -81,9 +76,6 @@ function buildScaffoldableChannels(): ScaffoldableChannel[] {
if (scaffold.hint !== undefined) {
channel.hint = scaffold.hint;
}
- if (scaffold.requiresVercelProject !== undefined) {
- channel.requiresVercelProject = scaffold.requiresVercelProject;
- }
channels.push(channel);
}
diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.ts
index 8254d8f7f..167f5558f 100644
--- a/packages/eve/src/setup/scaffold/index.integration.test.ts
+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts
@@ -89,6 +89,55 @@ describe("ensureChannel", () => {
);
});
+ test("writes a portable Slack channel and merges its environment example", async () => {
+ const projectRoot = await createTempDir();
+ await mkdir(join(projectRoot, "agent"), { recursive: true });
+ await writeFile(join(projectRoot, "package.json"), "{}\n", "utf8");
+ await writeFile(
+ join(projectRoot, ".env.example"),
+ "EXISTING=value\nSLACK_BOT_TOKEN=old\n",
+ "utf8",
+ );
+
+ const result = await ensureChannel({
+ projectRoot,
+ kind: "slack",
+ slackCredentials: "environment",
+ });
+
+ await expect(readFile(join(projectRoot, "agent/channels/slack.ts"), "utf8")).resolves.toBe(
+ 'import { slackChannel } from "eve/channels/slack";\n\nexport default slackChannel();\n',
+ );
+ await expect(readFile(join(projectRoot, ".env.example"), "utf8")).resolves.toBe(
+ "EXISTING=value\nSLACK_BOT_TOKEN=old\n\nSLACK_SIGNING_SECRET=\n",
+ );
+ await expect(readFile(join(projectRoot, "package.json"), "utf8")).resolves.toBe("{}\n");
+ expect(result.packageJsonUpdated).toEqual([]);
+ expect(result.filesWritten).toEqual([
+ join(projectRoot, "agent/channels/slack.ts"),
+ join(projectRoot, ".env.example"),
+ ]);
+ });
+
+ test("rolls back the environment example when portable Slack scaffolding fails", async () => {
+ const projectRoot = await createTempDir();
+ await mkdir(join(projectRoot, "agent/channels/slack.ts"), { recursive: true });
+ await writeFile(join(projectRoot, ".env.example"), "EXISTING=value\n", "utf8");
+
+ await expect(
+ ensureChannel({
+ projectRoot,
+ kind: "slack",
+ slackCredentials: "environment",
+ force: true,
+ }),
+ ).rejects.toThrow();
+
+ await expect(readFile(join(projectRoot, ".env.example"), "utf8")).resolves.toBe(
+ "EXISTING=value\n",
+ );
+ });
+
test("writes the exact Slack connector UID returned by Connect", async () => {
const projectRoot = await createTempDir();
await mkdir(join(projectRoot, "agent"), { recursive: true });
diff --git a/packages/eve/src/setup/scaffold/update/channels.ts b/packages/eve/src/setup/scaffold/update/channels.ts
index a9dd09e65..4ee503816 100644
--- a/packages/eve/src/setup/scaffold/update/channels.ts
+++ b/packages/eve/src/setup/scaffold/update/channels.ts
@@ -1,6 +1,8 @@
-import { readFile, readdir } from "node:fs/promises";
+import { readFile, readdir, unlink, writeFile } from "node:fs/promises";
import { basename, join, resolve } from "node:path";
+import { appendEnv } from "../../append-env.js";
+
import type { PackageManagerKind } from "../../package-manager.js";
import { pinnedNodeEngineMajor, type NodeEngineOverride } from "../../node-engine.js";
import { pathExists, writeTextFile } from "../files.js";
@@ -71,9 +73,9 @@ export type ChannelMutationResult = SlackChannelMutationResult | WebChannelMutat
interface SlackChannelWrittenResult {
kind: "slack";
action: "created" | "overwritten";
- filesWritten: [string];
- filesOverwritten?: [string];
- filesSkipped: [];
+ filesWritten: string[];
+ filesOverwritten?: string[];
+ filesSkipped: string[];
packageJsonUpdated: PackageJsonMutation[];
slackConnectorSlug: SlackConnectorSlug;
}
@@ -379,7 +381,7 @@ export async function deriveSlackConnectorSlug(
return normalizeSlackConnectorSlug(dir || DEFAULT_SLACK_CONNECTOR_SLUG);
}
-function buildSlackTemplate(connectorUid: string): string {
+function buildSlackConnectTemplate(connectorUid: string): string {
if (!connectorUid.startsWith("slack/") || connectorUid.length === "slack/".length) {
throw new Error(`Invalid Slack connector UID "${connectorUid}".`);
}
@@ -392,6 +394,16 @@ export default slackChannel({
`;
}
+const SLACK_ENV_TEMPLATE = `import { slackChannel } from "eve/channels/slack";
+
+export default slackChannel();
+`;
+
+const SLACK_ENV_EXAMPLE_VALUES = {
+ SLACK_BOT_TOKEN: "",
+ SLACK_SIGNING_SECRET: "",
+} as const;
+
function renderWebAppTemplate(content: string, appName: string): string {
return content
.replaceAll("__EVE_INIT_APP_NAME__", appName)
@@ -450,6 +462,8 @@ export interface EnsureChannelOptions {
/** Exact UID returned by Vercel Connect; takes precedence over the derived slug. */
slackConnectorUid?: string;
slackConnectorSlug?: SlackConnectorSlug;
+ /** Credential source rendered into a Slack channel. Defaults to Vercel Connect. */
+ slackCredentials?: "vercel-connect" | "environment";
connectPackageVersion?: string;
webPackageVersions?: WebPackageVersions;
/** When false, Web Chat leaves Vercel Services config unwritten for preview-only scaffolds. */
@@ -588,24 +602,53 @@ async function ensureSlackChannel(
};
}
- const connectPackageVersion = resolveVersionToken(
- "connectPackageVersion",
- options.connectPackageVersion ?? DEFAULT_CONNECT_PACKAGE_VERSION,
- );
-
- const packageJsonUpdated = await ensurePackageDependency(
- join(options.projectRoot, "package.json"),
- CONNECT_PACKAGE_NAME,
- connectPackageVersion,
- );
+ const credentials = options.slackCredentials ?? "vercel-connect";
const slug = options.slackConnectorSlug ?? (await deriveSlackConnectorSlug(options.projectRoot));
- const connectorUid = options.slackConnectorUid ?? `slack/${slug}`;
- await writeTextFile(filePath, buildSlackTemplate(connectorUid), { force: options.force });
+ let template: string;
+ let packageJsonUpdated: PackageJsonMutation[] = [];
+ const filesWritten = [filePath];
+ const filesSkipped: string[] = [];
+ let envExampleRollback: { path: string; content?: string } | undefined;
+
+ if (credentials === "vercel-connect") {
+ const connectPackageVersion = resolveVersionToken(
+ "connectPackageVersion",
+ options.connectPackageVersion ?? DEFAULT_CONNECT_PACKAGE_VERSION,
+ );
+ packageJsonUpdated = await ensurePackageDependency(
+ join(options.projectRoot, "package.json"),
+ CONNECT_PACKAGE_NAME,
+ connectPackageVersion,
+ );
+ const connectorUid = options.slackConnectorUid ?? `slack/${slug}`;
+ template = buildSlackConnectTemplate(connectorUid);
+ } else {
+ template = SLACK_ENV_TEMPLATE;
+ const envExamplePath = join(options.projectRoot, ".env.example");
+ const envExampleExisted = await pathExists(envExamplePath);
+ envExampleRollback = {
+ path: envExamplePath,
+ ...(envExampleExisted ? { content: await readFile(envExamplePath, "utf8") } : {}),
+ };
+ const envExample = await appendEnv(envExamplePath, SLACK_ENV_EXAMPLE_VALUES);
+ if (envExample.written.length > 0) filesWritten.push(envExamplePath);
+ else filesSkipped.push(envExamplePath);
+ }
+
+ try {
+ await writeTextFile(filePath, template, { force: options.force });
+ } catch (error) {
+ if (envExampleRollback !== undefined) {
+ if (envExampleRollback.content === undefined) await unlink(envExampleRollback.path);
+ else await writeFile(envExampleRollback.path, envExampleRollback.content, "utf8");
+ }
+ throw error;
+ }
const result: SlackChannelWrittenResult = {
kind: "slack",
action: fileAlreadyExists ? "overwritten" : "created",
- filesWritten: [filePath],
- filesSkipped: [],
+ filesWritten,
+ filesSkipped,
packageJsonUpdated,
slackConnectorSlug: slug,
};
diff --git a/packages/eve/src/setup/slack-connect-lifecycle.ts b/packages/eve/src/setup/slack-connect-lifecycle.ts
index 50dc671fe..598a80200 100644
--- a/packages/eve/src/setup/slack-connect-lifecycle.ts
+++ b/packages/eve/src/setup/slack-connect-lifecycle.ts
@@ -9,7 +9,6 @@ import { z } from "zod";
import {
parseSlackConnectorDetails,
parseSlackConnectors,
- pickSlackConnector,
type RawSlackConnector,
type SlackConnectorDetails,
type SlackConnectorRef,
@@ -94,11 +93,16 @@ export async function readProjectLink(projectRoot: string): Promise<VercelProjec
}
export type SlackConnectorLookup =
- | { state: "found"; connector: SlackConnectorRef; connectorUids: ReadonlySet<string> }
+ | {
+ state: "found";
+ connectors: readonly SlackConnectorRef[];
+ preferred?: SlackConnectorRef;
+ connectorUids: ReadonlySet<string>;
+ }
| { state: "not-found"; connectorUids: ReadonlySet<string> }
| { state: "failed"; message: string };
-/** Resolves the expected (or newest project-attached) Slack connector from the inventory. */
+/** Lists Slack connectors attached to the linked project and identifies the expected UID. */
export async function findSlackConnector(
deps: SlackConnectLifecycleDeps,
projectRoot: string,
@@ -110,10 +114,19 @@ export async function findSlackConnector(
const list = await listSlackConnectors(deps, projectRoot, onOutput, signal);
if (list.state === "failed") return list;
const connectorUids = new Set(list.connectors.map((connector) => connector.uid));
- const connector = pickSlackConnector(list.body, projectId, expectedUid);
- return connector === undefined
- ? { state: "not-found", connectorUids }
- : { state: "found", connector, connectorUids };
+ if (projectId === undefined) return { state: "not-found", connectorUids };
+ const connectors = list.connectors
+ .filter(
+ (connector): connector is RawSlackConnector & { id: string } =>
+ connector.id !== undefined && connector.projectIds.includes(projectId),
+ )
+ .sort((left, right) => right.createdAt - left.createdAt)
+ .map(({ uid, id }) => ({ uid, id }));
+ if (connectors.length === 0) return { state: "not-found", connectorUids };
+ const preferred = connectors.find((connector) => connector.uid === expectedUid);
+ return preferred === undefined
+ ? { state: "found", connectors, connectorUids }
+ : { state: "found", connectors, preferred, connectorUids };
}
/**
diff --git a/packages/eve/src/setup/slack-connect.ts b/packages/eve/src/setup/slack-connect.ts
index 2258cd6e5..07feb0fb8 100644
--- a/packages/eve/src/setup/slack-connect.ts
+++ b/packages/eve/src/setup/slack-connect.ts
@@ -164,7 +164,9 @@ export function slackMessageDeepLink(url: string): string {
/** A Slack connector plus the project ids it is attached to. */
export interface RawSlackConnector {
uid: string;
+ id?: string;
projectIds: readonly string[];
+ createdAt: number;
}
/** Parses Slack connectors (uid + attached project ids) from a connect-list response. */
@@ -185,7 +187,13 @@ export function parseSlackConnectors(listJson: unknown): RawSlackConnector[] {
)
.filter((id): id is string => typeof id === "string")
: [];
- parsed.push({ uid: raw.uid, projectIds });
+ const connector: RawSlackConnector = {
+ uid: raw.uid,
+ projectIds,
+ createdAt: typeof raw.createdAt === "number" ? raw.createdAt : 0,
+ };
+ if (typeof raw.id === "string") connector.id = raw.id;
+ parsed.push(connector);
}
return parsed;
}
diff --git a/packages/eve/src/setup/slackbot.test.ts b/packages/eve/src/setup/slackbot.test.ts
index e30ff59dd..293cb1909 100644
--- a/packages/eve/src/setup/slackbot.test.ts
+++ b/packages/eve/src/setup/slackbot.test.ts
@@ -10,6 +10,7 @@ import {
pickSlackConnector,
provisionSlackbot,
reconcileSlackUid,
+ type SlackConnectorSelection,
} from "./slackbot.js";
vi.mock("#setup/primitives/run-vercel.js", () => ({
@@ -333,6 +334,110 @@ describe("provisionSlackbot", () => {
expect(mockedRunVercelCaptureStdout).not.toHaveBeenCalled();
});
+ it("lets interactive setup choose among project connectors or create a new one", async () => {
+ mockedCaptureVercel
+ .mockResolvedValueOnce({
+ ok: true,
+ stdout: JSON.stringify({
+ connectors: [
+ {
+ uid: "slack/other",
+ id: "scl_other",
+ type: "slack",
+ createdAt: 2,
+ projects: [{ id: "prj_demo" }],
+ },
+ {
+ uid: "slack/my-agent",
+ id: "scl_expected",
+ type: "slack",
+ createdAt: 1,
+ projects: [{ id: "prj_demo" }],
+ },
+ ],
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ stdout: connectedSlackConnectorJson("slack/other", "scl_other"),
+ });
+ mockedRunVercel.mockResolvedValue(true);
+ const selectConnector = vi.fn<
+ (
+ connectors: readonly { uid: string; id: string }[],
+ preferred: { uid: string; id: string } | undefined,
+ ) => Promise<SlackConnectorSelection>
+ >(async (connectors, preferred) => {
+ expect(connectors.map((connector) => connector.uid)).toEqual([
+ "slack/other",
+ "slack/my-agent",
+ ]);
+ expect(preferred?.uid).toBe("slack/my-agent");
+ return connectors[0]!;
+ });
+
+ await expect(
+ provisionSlackbot(
+ createTestLog(),
+ "/tmp/eve-agent",
+ "my-agent",
+ {
+ captureVercel: mockedCaptureVercel,
+ runVercel: mockedRunVercel,
+ runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ },
+ { selectConnector },
+ ),
+ ).resolves.toMatchObject({ state: "attached", connectorUid: "slack/other" });
+ expect(selectConnector).toHaveBeenCalledOnce();
+ expect(mockedRunVercelCaptureStdout).not.toHaveBeenCalled();
+ });
+
+ it("creates a new connector when interactive setup requests one", async () => {
+ mockedCaptureVercel
+ .mockResolvedValueOnce({
+ ok: true,
+ stdout: JSON.stringify({
+ connectors: [
+ {
+ uid: "slack/existing",
+ id: "scl_existing",
+ type: "slack",
+ createdAt: 1,
+ projects: [{ id: "prj_demo" }],
+ },
+ ],
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ stdout: connectedSlackConnectorJson("slack/my-agent", "scl_new"),
+ });
+ mockedRunVercelCaptureStdout.mockResolvedValue({
+ ok: true,
+ stdout: createSlackConnectorJson("slack/my-agent", "scl_new"),
+ });
+ mockedRunVercel.mockResolvedValue(true);
+
+ await expect(
+ provisionSlackbot(
+ createTestLog(),
+ "/tmp/eve-agent",
+ "my-agent",
+ {
+ captureVercel: mockedCaptureVercel,
+ runVercel: mockedRunVercel,
+ runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ delay: async () => {},
+ },
+ { selectConnector: async () => "create" },
+ ),
+ ).resolves.toMatchObject({ state: "attached", connectorUid: "slack/my-agent" });
+ expect(mockedRunVercelCaptureStdout).toHaveBeenCalled();
+ });
+
it("recognizes Slack workspace metadata from the connector detail payload", async () => {
mockedCaptureVercel
.mockResolvedValueOnce({
diff --git a/packages/eve/src/setup/slackbot.ts b/packages/eve/src/setup/slackbot.ts
index 6472c733f..2afc398d0 100644
--- a/packages/eve/src/setup/slackbot.ts
+++ b/packages/eve/src/setup/slackbot.ts
@@ -313,12 +313,19 @@ async function raceAttemptAgainstChoice(input: {
* flow. Existing connectors are verified through their team-scoped detail
* payload before attachment.
*/
+export type SlackConnectorSelection = SlackConnectorRef | "create";
+
export interface ProvisionSlackbotOptions {
/**
* Cancels the caller's whole operation. The promise rejects after attempting
* cleanup; only the explicit interactive Cancel action returns `cancelled`.
*/
signal?: AbortSignal;
+ /** Chooses a project-attached connector or requests a new one. */
+ selectConnector?: (
+ connectors: readonly SlackConnectorRef[],
+ preferred: SlackConnectorRef | undefined,
+ ) => Promise<SlackConnectorSelection>;
/** Concurrent retry/cancel controls supplied by an interactive prompter. */
awaitChoice?: ChannelSetupAwaitChoice;
}
@@ -607,7 +614,14 @@ export async function provisionSlackbot(
}
if (existing.state === "found") {
- return runExistingConnector({ state: "existing", ref: existing.connector });
+ const selection =
+ options.selectConnector === undefined
+ ? (existing.preferred ?? existing.connectors[0]!)
+ : await options.selectConnector(existing.connectors, existing.preferred);
+ options.signal?.throwIfAborted();
+ if (selection !== "create") {
+ return runExistingConnector({ state: "existing", ref: selection });
+ }
}
let source: NewAttemptSource = {