Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): resume Slack setup from partial state (#4552)

prha0ef5c4c782f4
diff --git a/.changeset/resumable-slack-setup.md b/.changeset/resumable-slack-setup.md
new file mode 100644
index 000000000..7a398e0d4
--- /dev/null
+++ b/.changeset/resumable-slack-setup.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+`eve add channel/slack` now resumes interrupted setup, reopens workspace installation for existing connectors, fixes stale routes without detaching, and avoids sharing a Slack app with another project or creating one with a taken name. The `eve/setup` Slack provisioning API now takes a connector selection from `inspectSlackbotConnectors` rather than inspecting a second time; a failed Vercel create reports its original error instead of a misleading cleanup failure.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 3849e472c..d6d9ccd9a 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -14,13 +14,7 @@ Run the guided setup from your agent project:
eve add channel/slack
```
-The command recommends Vercel Connect, then scaffolds `agent/channels/slack.ts` and installs any required dependency. Choose the environment-variable option only when you need to manage the Slack bot token and signing secret yourself.
-
-### Recommended: use Vercel Connect
-
-Vercel Connect setup requires the Vercel CLI. The guided flow signs you in when needed, creates or links a Vercel project, creates or reuses a Slack connector, waits for you to install it in a workspace, and registers `/eve/v1/slack` as a trigger destination before writing the channel file.
-
-The generated channel resolves credentials at runtime:
+With Vercel Connect, the recommended option, setup signs you in to Vercel and links a project when needed. It reuses a suitable Slack app (a Connect connector) or creates one, prompts you to install it in a workspace if needed, routes its events to `/eve/v1/slack`, and writes the channel file:
```ts title="agent/channels/slack.ts"
import { connectSlackCredentials } from "@vercel/connect/eve";
@@ -31,55 +25,29 @@ export default slackChannel({
});
```
-`connectSlackCredentials` returns `{ botToken, webhookVerifier }`, keeping token rotation, multi-workspace tenancy, and request verification inside Connect rather than your code.
-
-Function-form bot tokens receive `{ teamId }` when Slack supplies the app installation workspace. Use it to select an installation in a self-managed multi-workspace app. The id can differ from the actor or content workspace for Slack Connect events:
-
-```ts title="agent/channels/slack.ts"
-import { slackChannel } from "eve/channels/slack";
+`connectSlackCredentials` keeps the bot token, token rotation, multiple workspace installations, and request verification inside Connect. Deploy with `eve deploy` once setup finishes.
-export default slackChannel({
- credentials: {
- botToken: ({ teamId }) => loadInstallationToken(teamId),
- },
-});
-```
+### Resume setup
-Literal tokens and zero-argument token functions remain supported. A multi-workspace provider should reject a missing `teamId` instead of selecting a default installation.
+If setup stops partway, or Slack events stop reaching the agent, run `eve add channel/slack` again. Setup checks what is already in place and runs only the missing steps. When `agent/channels/slack.ts` names a connector, setup finishes that connector without asking anything. Setup never runs `vercel connect detach`, which would remove the project's token access and every trigger destination for the project.
### Manage Slack credentials yourself
-Use this fallback when the agent does not run on Vercel or Vercel Connect is unavailable. In the setup command, **Use portable credentials** is the environment-variable option; eve adds `SLACK_BOT_TOKEN` and `SLACK_SIGNING_SECRET` to `.env.example`.
-
-This option does not create or install the Slack app. Configure it in [Slack app settings](https://api.slack.com/apps):
-
-1. Add the `app_mentions:read` and `chat:write` bot scopes. Add `im:history` for DMs, `files:read` for inbound attachments, and `files:write` for explicit uploads and automatic long-response snippets.
-2. Install or reinstall the app, copy its Bot User OAuth Token to `SLACK_BOT_TOKEN`, and copy the signing secret from **Basic Information** to `SLACK_SIGNING_SECRET`.
-3. Set both values in `.env.local` for local development or in the target runtime's environment, then start or deploy the agent at a public URL.
-4. Under **Event Subscriptions**, set the Request URL to `https://your-agent.example/eve/v1/slack`. Subscribe to `app_mention`, plus `message.im` for DMs.
-5. Under **Interactivity & Shortcuts**, use the same Request URL when the agent uses buttons, shortcuts, or HITL prompts.
-6. Under **Slash Commands**, create each command your app handles and use the same Request URL.
-
-Add the matching message events and history scopes if you also want unmentioned thread replies, as described in [Continue conversations without repeated mentions](#continue-conversations-without-repeated-mentions).
+Choose **Use portable credentials** when the agent does not run on Vercel or you can't use Vercel Connect. eve adds `SLACK_BOT_TOKEN` and `SLACK_SIGNING_SECRET` to `.env.example` but doesn't create the Slack app. In [Slack app settings](https://api.slack.com/apps):
-## Deploy
+1. Add the `app_mentions:read` and `chat:write` bot scopes, plus `im:history` for DMs, `files:read` for inbound attachments, and `files:write` for long-response snippets.
+2. Install the app, then set `SLACK_BOT_TOKEN` to its Bot User OAuth Token and `SLACK_SIGNING_SECRET` to the signing secret from **Basic Information**. Put both values in `.env.local` for local development or in the target runtime's environment when deployed.
+3. Set the Request URL to `https://your-agent.example/eve/v1/slack` under **Event Subscriptions** (subscribe to `app_mention`, plus `message.im` for DMs), **Interactivity & Shortcuts**, and each **Slash Command**.
-Deploy the production agent after the trigger destination and channel file are ready:
+A function-form `botToken` receives `{ teamId }`, the app installation workspace, so a self-managed multi-workspace app can select an installation: `credentials: { botToken: ({ teamId }) => loadInstallationToken(teamId) }`. Reject a missing `teamId` instead of falling back to a default installation.
-```bash
-eve deploy
-```
-
-`eve deploy` deploys the linked Vercel project to production. The guided flow registers the trigger destination against the production branch, which is the Vercel CLI default. Manage trigger destinations separately in the Connect dashboard when you need a different branch or environment.
-
-## Test a preview branch with Vercel Connect
+## Test a preview branch
-Use a separate connector when you want preview Slack traffic isolated from production, then register the preview branch as a trigger destination:
+Create a second connector for preview traffic and route it to your preview branch:
```bash
-npm install -g vercel@latest
-vercel connect create slack --name your-agent-preview --triggers
-vercel connect attach slack/your-agent-preview \
+vercel connect create slack --name my-agent-preview --triggers
+vercel connect attach slack/my-agent-preview \
--environment preview \
--triggers \
--trigger-branch your-preview-branch \
@@ -87,56 +55,38 @@ vercel connect attach slack/your-agent-preview \
--yes
```
-Run these commands from the linked project directory. `--environment preview` makes the connector credentials available to Preview deployments. `--trigger-branch` selects the branch that receives forwarded Slack webhooks.
-
-Select the matching connector at runtime instead of leaving the generated production UID hard-coded:
+Then select the connector at runtime:
```ts title="agent/channels/slack.ts"
import { connectSlackCredentials } from "@vercel/connect/eve";
import { slackChannel } from "eve/channels/slack";
const connectorUid =
- process.env.VERCEL_ENV === "preview" ? "slack/your-agent-preview" : "slack/my-agent";
+ process.env.VERCEL_ENV === "preview" ? "slack/my-agent-preview" : "slack/my-agent";
export default slackChannel({
credentials: connectSlackCredentials(connectorUid),
});
```
-Creating a connector with triggers also registers a default production destination. Remove that destination from the Connect dashboard before treating the preview connector as isolated. The guided production setup does not restrict credential environments, so also set the production connector's project access to **Production** and the preview connector's access to **Preview** in the dashboard. `vercel connect detach` removes project token access, not trigger destinations. Vercel Connect supports up to three trigger destinations per connector; see the [Vercel Connect guide](https://vercel.com/kb/guide/vercel-connect) for current limits and environment guidance.
-
-Slack must be able to reach the preview route without an interactive authentication challenge. For a Connect trigger, exempt the branch domain with a [Deployment Protection Exception](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/deployment-protection-exceptions) when that feature is available, or use an unprotected preview domain. For a Slack app that uses environment-variable credentials, append `?x-vercel-protection-bypass=your-generated-secret` to its event and interaction request URLs. Enabling [Protection Bypass for Automation](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/protection-bypass-automation) does not bypass a request unless the sender presents that secret.
-
-## Set up Vercel Connect manually
-
-To set up the connector outside the guided flow, create it, then register eve's Slack route with the linked project:
-
-```bash
-npm install -g vercel@latest
-vercel connect create slack --name your-agent --triggers
-vercel connect attach slack/your-agent \
- --environment production \
- --triggers \
- --trigger-path /eve/v1/slack \
- --yes
-```
+`connect create --triggers` also adds a default production destination; remove it in the [Connect dashboard](https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Go+to+Connect) so preview traffic stays isolated. Guided setup does not restrict credential environments. Set the production connector's project access to **Production** and the preview connector's to **Preview** in the dashboard. A connector can have at most three trigger destinations.
-`--triggers` enables Slack Event Subscriptions. The attach command registers eve's route in addition to the default destination created with the connector. Remove the default destination separately in the [Connect dashboard](https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Go+to+Connect). For an existing connector, skip `create` and attach the intended route directly.
+Slack must reach the preview route without an authentication challenge. For a Connect trigger, exempt the branch domain with a [Deployment Protection Exception](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/deployment-protection-exceptions) or use an unprotected domain. For a Slack app using environment-variable credentials, append `?x-vercel-protection-bypass=your-generated-secret` to its event and interaction Request URLs. Enabling [Protection Bypass for Automation](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/protection-bypass-automation) does not help unless Slack sends the secret with each request.
## Troubleshoot Slack delivery
-Check the delivery path in order so you can identify where a Slack event stops:
-
-| Symptom | Check | Next action |
-| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `eve add channel/slack` stops before scaffolding the channel | Read the setup error for the failed Vercel login, project link, workspace install, connector lookup, or trigger registration step. | Resolve that step, then rerun `eve add channel/slack`. |
-| Setup says it could not remove an existing trigger destination | Check the connector's destinations in the Connect dashboard. `vercel connect detach` removes project token access, not trigger destinations. | Edit or remove the stale destination in the dashboard, then register `/eve/v1/slack` with `vercel connect attach`. |
-| Mentions never reach the deployment | Confirm that the connector trigger destination uses the intended project and branch, enables triggers, and points to `/eve/v1/slack`. | Edit or remove stale destinations in the Connect dashboard, then register the intended destination with `vercel connect attach`. |
-| Mentions work but DMs or thread replies do not | Check the Slack app's Event Subscriptions and OAuth scopes. DMs require `message.im` and `im:history`; channel replies require the matching message event and history scope. | Add the missing events or scopes, then reinstall the Slack app if Slack requires it. |
-| A long response cannot be uploaded as a snippet | Check whether the installed Slack app has the `files:write` bot scope. | Add `files:write`, then reinstall the Slack app so the new scope takes effect. |
-| The thread says the agent couldn't deliver its answer | Search the Vercel runtime logs for the error id in the notice. The `final reply was not delivered to Slack` line carries the error, including one thrown by an authored renderer. | Fix the cause, such as a missing `files:write` scope or a renderer that posts invalid blocks. A renderer can post through `postCompletedSlackReply` to get eve's fallbacks. Then ask the agent to resend the answer. |
-| A preview request receives an authentication page or protection error | Check whether the branch domain is exempt or the direct Slack request URL includes `x-vercel-protection-bypass`. Slack cannot complete an interactive Vercel Authentication challenge. | Add a Deployment Protection Exception for the branch domain, or add the automation bypass query parameter to a Slack app that uses environment-variable credentials. |
-| The webhook reaches the deployment but the agent does not reply | Open the project's Vercel runtime logs, then inspect the session in [**Agent Runs**](/docs/observability/agent-runs) when your team has access. | Use the first missing or failed stage to narrow the issue to channel dispatch, the agent run, or outbound Slack delivery. |
+| Symptom | Next action |
+| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `eve add channel/slack` stops before finishing | Fix the step the error names, then rerun `eve add channel/slack`. |
+| Setup says the Slack app isn't installed in a workspace | Rerun `eve add channel/slack`. It opens the app's install page again; finish the install in your browser while setup waits. |
+| Setup says a connector is used by another project | Let setup create a new Slack app for this agent. To keep the existing app, remove it from the other project in the Connect dashboard first. |
+| Setup says the connector has too many destinations | Remove a destination you no longer need in the Connect dashboard, then rerun setup. |
+| Mentions never reach the deployment | Rerun `eve add channel/slack` to repair the production destination. Check branch destinations in the Connect dashboard. |
+| A preview request receives an authentication page | Exempt the branch domain from Deployment Protection, or add the automation bypass secret to a self-managed Slack app's event and interaction Request URLs. |
+| Mentions work but DMs or thread replies don't | Add `message.im` and `im:history` for DMs, or the matching message event and history scope for channel replies, then reinstall the Slack app. |
+| A long response can't be uploaded as a snippet | Add the `files:write` bot scope and reinstall the Slack app. |
+| The thread says the agent couldn't deliver its answer | Search the Vercel runtime logs for the notice's error id. The `final reply was not delivered to Slack` line carries the error, including one thrown by an authored renderer. |
+| The webhook arrives but the agent doesn't reply | Check the Vercel runtime logs, then the session in [**Agent Runs**](/docs/observability/agent-runs) when your team has access. |
## Audience
diff --git a/packages/eve/src/cli/dev/environment.ts b/packages/eve/src/cli/dev/environment.ts
index 94e1cdf75..42512e194 100644
--- a/packages/eve/src/cli/dev/environment.ts
+++ b/packages/eve/src/cli/dev/environment.ts
@@ -1,28 +1,13 @@
-import { MODEL_CONNECTION_ENV } from "#shared/model-helper.js";
-import { readFileSync } from "node:fs";
import { join, resolve } from "node:path";
-import { parseEnv } from "node:util";
import { findEveProjectRoot } from "#internal/eve-project-root.js";
-import { isObject } from "#shared/guards.js";
+import {
+ DEVELOPMENT_ENV_FILE_NAMES,
+ readDevelopmentEnvironmentValues,
+} from "#shared/development-env-files.js";
+import { MODEL_CONNECTION_ENV } from "#shared/model-helper.js";
import { readProviderSettingsSync } from "#setup/provider-settings.js";
-/**
- * Development environment files loaded by local CLI commands such as
- * `eve dev`, `eve build`, and `eve eval`, ordered from highest to lowest
- * precedence.
- */
-export const DEVELOPMENT_ENV_FILE_NAMES = [
- ".env.development.local",
- ".env.local",
- ".env.development",
- ".env",
-] as const;
-
-function isMissingEnvironmentFileError(error: unknown): error is NodeJS.ErrnoException {
- return isObject(error) && error.code === "ENOENT";
-}
-
interface DevelopmentEnvironmentLoader {
readonly environmentRoot: string;
reload(): void;
@@ -197,21 +182,3 @@ function applyDevelopmentEnvironmentValues(input: {
input.managedValues.set(key, value);
}
}
-
-function readDevelopmentEnvironmentValues(environmentRoot: string): Map<string, string> {
- const values = new Map<string, string>();
-
- for (const fileName of [...DEVELOPMENT_ENV_FILE_NAMES].reverse()) {
- try {
- const parsedValues = parseEnv(readFileSync(join(environmentRoot, fileName), "utf8"));
-
- for (const [key, value] of Object.entries(parsedValues)) {
- if (value !== undefined) values.set(key, value);
- }
- } catch (error) {
- if (!isMissingEnvironmentFileError(error)) throw error;
- }
- }
-
- return values;
-}
diff --git a/packages/eve/src/internal/mcp/skills.ts b/packages/eve/src/internal/mcp/skills.ts
index fd6b85bcc..9d955afeb 100644
--- a/packages/eve/src/internal/mcp/skills.ts
+++ b/packages/eve/src/internal/mcp/skills.ts
@@ -25,6 +25,7 @@ import {
type McpServerFeature,
} from "#internal/mcp/streamable-http-server.js";
import type { JsonObject } from "#shared/json.js";
+import { mapWithConcurrency } from "#shared/map-with-concurrency.js";
/** SEP-2640 extension identifier. */
export const MCP_SKILLS_EXTENSION = "io.modelcontextprotocol/skills";
@@ -608,21 +609,3 @@ function servedMimeType(path: string, file: ServedFile): string {
function mimeTypeFor(path: string): string {
return servedMimeType(path, { bytes: new Uint8Array() });
}
-
-async function mapWithConcurrency<T, R>(
- items: readonly T[],
- limit: number,
- map: (item: T) => Promise<R>,
-): Promise<R[]> {
- const results: R[] = Array.from({ length: items.length });
- let next = 0;
- const worker = async () => {
- while (next < items.length) {
- const index = next;
- next += 1;
- results[index] = await map(items[index] as T);
- }
- };
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
- return results;
-}
diff --git a/packages/eve/src/setup/connection-connector.ts b/packages/eve/src/setup/connection-connector.ts
index 8db1f7e1a..4485b8cef 100644
--- a/packages/eve/src/setup/connection-connector.ts
+++ b/packages/eve/src/setup/connection-connector.ts
@@ -1,5 +1,5 @@
import { createPromptCommandOutput, type ChannelSetupLog, withPhase } from "#setup/cli/index.js";
-import type { ProcessOutputHandler } from "#setup/primitives/process-output.js";
+import { vercelErrorDetail, type ProcessOutputHandler } from "#setup/primitives/process-output.js";
import type { Prompter } from "#setup/prompter.js";
import { readProjectLink, type VercelProjectReference } from "#setup/project-resolution.js";
import { captureVercel, runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";
@@ -51,11 +51,7 @@ function parseJson(source: string): unknown {
}
function connectorCreationFailure(service: string, stderr: string | undefined): string {
- const detail = stderr
- ?.split("\n")
- .map((line) => line.trim())
- .filter((line) => line.length > 0 && !line.startsWith("Vercel CLI "))
- .at(-1);
+ const detail = vercelErrorDetail(stderr);
return detail === undefined
? `Could not create the ${service} connector.`
: `Could not create the ${service} connector. Vercel returned: ${detail}`;
diff --git a/packages/eve/src/setup/index.ts b/packages/eve/src/setup/index.ts
index 27c8aa851..70c9ce02b 100644
--- a/packages/eve/src/setup/index.ts
+++ b/packages/eve/src/setup/index.ts
@@ -67,7 +67,15 @@ export {
type ProjectResolution,
} from "./project-resolution.js";
export { runVercelEnvPull } from "./run-vercel-link.js";
-export { provisionSlackbot, reconcileSlackUid, type ProvisionSlackbotResult } from "./slackbot.js";
+export {
+ inspectSlackbotConnectors,
+ provisionSlackbot,
+ reconcileSlackUid,
+ type ProvisionSlackbotResult,
+ type SlackbotConnectorInspection,
+ type SlackConnectorCandidate,
+ type SlackConnectorSelection,
+} from "./slackbot.js";
export { runRemoteAuthFlow } from "../cli/dev/tui/remote-auth.js";
export {
inspectVerifiedRemoteAgent,
diff --git a/packages/eve/src/setup/integrations/slack/setup.test.ts b/packages/eve/src/setup/integrations/slack/setup.test.ts
index 3b32e873a..1b30834b0 100644
--- a/packages/eve/src/setup/integrations/slack/setup.test.ts
+++ b/packages/eve/src/setup/integrations/slack/setup.test.ts
@@ -1,37 +1,79 @@
import { describe, expect, it, vi } from "vitest";
import { createFakePrompter } from "#internal/testing/fake-prompter.js";
-import { headlessAsker, InteractionRequired, withAnswers, withPolicy } from "#setup/ask.js";
+import {
+ headlessAsker,
+ InteractionRequired,
+ InvalidAnswerError,
+ withAnswers,
+ withPolicy,
+} from "#setup/ask.js";
import type { SlackConnectorSlug } from "#setup/scaffold/index.js";
+import type { SlackbotConnectorInspection, SlackConnectorCandidate } from "#setup/slackbot.js";
import { integrationSetupEnvironment } from "../shared/environment.js";
import { createSetupContexts } from "../shared/ui.js";
import { applySlackSetup, prepareSlackSetup, type SlackSetupDeps } from "./setup.js";
-function channelResult() {
+function channelResult(action: "created" | "skipped" = "created") {
+ return action === "skipped"
+ ? {
+ kind: "slack" as const,
+ action,
+ filesWritten: [] as [],
+ filesSkipped: ["/project/agent/channels/slack.ts"] as [string],
+ packageJsonUpdated: [] as [],
+ }
+ : {
+ kind: "slack" as const,
+ action,
+ filesWritten: [],
+ filesOverwritten: [],
+ filesSkipped: [],
+ packageJsonUpdated: [],
+ slackConnectorSlug: "agent" as SlackConnectorSlug,
+ };
+}
+
+function candidate(uid: string, overrides: Partial<SlackConnectorCandidate> = {}) {
return {
- kind: "slack" as const,
- action: "created" as const,
- filesWritten: [],
- filesOverwritten: [],
- filesSkipped: [],
- packageJsonUpdated: [],
- slackConnectorSlug: "agent" as SlackConnectorSlug,
+ uid,
+ id: `scl_${uid.slice("slack/".length)}`,
+ attached: true,
+ triggerDestinations: [],
+ otherProjects: [],
+ createdAt: 1,
+ workspace: { workspaceUrl: "https://slack.com/app_redirect?app=A0&team=T0" },
+ ...overrides,
};
}
+
+function inspection(
+ overrides: Partial<SlackbotConnectorInspection> = {},
+): SlackbotConnectorInspection {
+ return {
+ projectId: "project",
+ orgId: "team",
+ slug: "agent",
+ candidates: [],
+ inUse: [],
+ ...overrides,
+ };
+}
+
function deps(): SlackSetupDeps {
return {
deriveSlackConnectorSlug: vi.fn(async () => "agent" as SlackConnectorSlug),
ensureChannel: vi.fn(async () => channelResult()),
- inspectConnectors: vi.fn(async () => ({
- state: "not-found" as const,
- connectorUids: new Set<string>(),
- })),
+ inspectConnectors: vi.fn(async () => inspection()),
provisionSlackbot: vi.fn(async () => ({
state: "attached" as const,
connectorUid: "slack/agent",
})),
reconcileSlackUid: vi.fn(async () => true),
+ readSlackChannelFile: vi.fn(async () => ({ kind: "absent" as const })),
+ missingSlackEnvironment: vi.fn(async () => []),
};
}
+
function contexts(
answers: Record<string, unknown>,
assume = false,
@@ -39,18 +81,24 @@ function contexts(
) {
const base = headlessAsker();
const resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" }));
+ const fake = createFakePrompter();
return {
...createSetupContexts({
appRoot: "/project",
asker: withAnswers(answers)(assume ? withPolicy("assume")(base) : base),
environment: integrationSetupEnvironment(auth, { kind: "unresolved" }),
- prompter: createFakePrompter().prompter,
+ prompter: fake.prompter,
resolveVercelProject,
}),
+ log: fake.prompter.log,
resolveVercelProject,
};
}
+function selectedConnector(effects: SlackSetupDeps) {
+ return vi.mocked(effects.provisionSlackbot).mock.calls[0]?.[3];
+}
+
describe("Slack setup", () => {
it("accepts recommendations before apply", async () => {
const effects = deps();
@@ -60,6 +108,25 @@ describe("Slack setup", () => {
await applySlackSetup(plan, ctx.apply, effects);
expect(effects.provisionSlackbot).toHaveBeenCalledOnce();
});
+ it("passes Vercel's create error through and explains an unconfirmed browser request", async () => {
+ const effects = deps();
+ const ctx = contexts({}, true);
+ const plan = await prepareSlackSetup(ctx.prepare, effects);
+ vi.mocked(effects.provisionSlackbot).mockResolvedValueOnce({
+ state: "create-failed",
+ detail: "Error: Connect is not available for this team.",
+ });
+ await expect(applySlackSetup(plan, ctx.apply, effects)).rejects.toThrow(
+ "Vercel could not create the Slack connector: Error: Connect is not available for this team. Slack channel was not added. Fix the problem Vercel reported, then re-run `eve add channel/slack`.",
+ );
+ vi.mocked(effects.provisionSlackbot).mockResolvedValueOnce({
+ state: "cleanup-failed",
+ connectorUids: [],
+ });
+ await expect(applySlackSetup(plan, ctx.apply, effects)).rejects.toThrow(
+ "eve couldn't confirm that the Slack setup in your browser ended. Slack channel was not added. Close the Slack setup page in your browser",
+ );
+ });
it("scaffolds portable credentials without provisioning", async () => {
const effects = deps();
const ctx = contexts({ "slack-credentials": "portable" });
@@ -77,20 +144,152 @@ describe("Slack setup", () => {
);
expect(effects.deriveSlackConnectorSlug).not.toHaveBeenCalled();
});
- it("resolves connector choice during prepare", async () => {
- const connector = { id: "existing", uid: "slack/existing" };
+ it("offers team connectors and resolves the choice during prepare", async () => {
+ const connector = candidate("slack/existing");
const effects = deps();
- vi.mocked(effects.inspectConnectors).mockResolvedValue({
- state: "found",
- connectors: [connector],
- preferred: connector,
- connectorUids: new Set([connector.uid]),
- });
+ vi.mocked(effects.inspectConnectors).mockResolvedValue(
+ inspection({
+ inUse: [],
+ candidates: [connector],
+ preferred: connector,
+ }),
+ );
const ctx = contexts({ "slack-credentials": "vercel", "slack-connector": connector.uid });
const plan = await prepareSlackSetup(ctx.prepare, effects);
await applySlackSetup(plan, ctx.apply, effects);
- const options = vi.mocked(effects.provisionSlackbot).mock.calls[0]?.[4];
- expect(await options?.selectConnector?.([], undefined)).toBe(connector);
+ expect(selectedConnector(effects)).toBe(connector);
+ });
+ it("names the searched team when the connector answer is unknown", async () => {
+ const effects = deps();
+ vi.mocked(effects.inspectConnectors).mockResolvedValue(
+ inspection({
+ inUse: [],
+ candidates: [candidate("slack/existing")],
+ }),
+ );
+ const ctx = contexts({ "slack-credentials": "vercel", "slack-connector": "slack/missing" });
+
+ const error = await prepareSlackSetup(ctx.prepare, effects).catch((caught: unknown) => caught);
+ expect(error).toBeInstanceOf(InvalidAnswerError);
+ expect((error as InvalidAnswerError).message).toContain(
+ "Searched Slack connectors in team team.",
+ );
+ });
+ it("explains which connectors setup reuses when the answer isn't one", async () => {
+ const effects = deps();
+ vi.mocked(effects.inspectConnectors).mockResolvedValue(
+ inspection({
+ candidates: [candidate("slack/agent")],
+ inUse: [],
+ }),
+ );
+ const ctx = contexts({ "slack-credentials": "vercel", "slack-connector": "slack/elsewhere" });
+
+ await expect(prepareSlackSetup(ctx.prepare, effects)).rejects.toThrow(
+ "eve reuses a Slack app only when it is attached to this project, or named slack/agent and unused by other projects.",
+ );
+ });
+ it("stops when the channel file names a connector another project uses", async () => {
+ const shared = candidate("slack/shared", {
+ attached: false,
+ otherProjects: [{ id: "prj_prod", name: "chief-prod" }],
+ });
+ const effects = deps();
+ vi.mocked(effects.readSlackChannelFile).mockResolvedValue({
+ kind: "connect",
+ connectorUid: shared.uid,
+ });
+ vi.mocked(effects.inspectConnectors).mockResolvedValue(
+ inspection({ candidates: [], inUse: [shared] }),
+ );
+
+ await expect(prepareSlackSetup(contexts({}).prepare, effects)).rejects.toThrow(
+ "`slack/shared` is used by chief-prod.",
+ );
+ expect(effects.provisionSlackbot).not.toHaveBeenCalled();
+ });
+ it("resumes from a channel file's connector without asking anything", async () => {
+ const named = candidate("slack/named");
+ const effects = deps();
+ vi.mocked(effects.readSlackChannelFile).mockResolvedValue({
+ kind: "connect",
+ connectorUid: named.uid,
+ });
+ vi.mocked(effects.inspectConnectors).mockResolvedValue(
+ inspection({
+ inUse: [],
+ candidates: [candidate("slack/agent"), named],
+ preferred: named,
+ }),
+ );
+ vi.mocked(effects.ensureChannel).mockResolvedValue(channelResult("skipped"));
+ vi.mocked(effects.provisionSlackbot).mockResolvedValue({
+ state: "already-configured",
+ connectorUid: named.uid,
+ chatUrl: "https://slack.com/app_redirect?app=A0&team=T0",
+ });
+ const ctx = contexts({});
+
+ const plan = await prepareSlackSetup(ctx.prepare, effects);
+ const completion = await applySlackSetup(plan, ctx.apply, effects);
+
+ expect(selectedConnector(effects)).toBe(named);
+ expect(vi.mocked(effects.inspectConnectors).mock.calls[0]?.[3]).toMatchObject({
+ channelConnectorUid: named.uid,
+ });
+ expect(effects.reconcileSlackUid).toHaveBeenCalledWith(
+ expect.anything(),
+ "/project",
+ expect.objectContaining({ connectorUid: named.uid }),
+ named.uid,
+ );
+ expect(completion.facts).toEqual([
+ expect.objectContaining({ label: "Agent Slack DM", kind: "url" }),
+ ]);
+ expect(ctx.log.success).toHaveBeenCalledWith("Slack is already set up with slack/named.");
+ });
+ it("offers selection when the channel file's connector is not in the team", async () => {
+ const replacement = candidate("slack/agent");
+ const effects = deps();
+ vi.mocked(effects.readSlackChannelFile).mockResolvedValue({
+ kind: "connect",
+ connectorUid: "slack/gone",
+ });
+ vi.mocked(effects.inspectConnectors).mockResolvedValue(
+ inspection({
+ inUse: [],
+ candidates: [replacement],
+ preferred: replacement,
+ }),
+ );
+ vi.mocked(effects.ensureChannel).mockResolvedValue(channelResult("skipped"));
+ const ctx = contexts({ "slack-connector": replacement.uid });
+
+ const plan = await prepareSlackSetup(ctx.prepare, effects);
+ await applySlackSetup(plan, ctx.apply, effects);
+
+ expect(ctx.log.warning).toHaveBeenCalledWith(
+ expect.stringContaining("`slack/gone`, which was not found in team team"),
+ );
+ expect(selectedConnector(effects)).toBe(replacement);
+ // The file still names the missing UID, so apply patches it.
+ expect(vi.mocked(effects.reconcileSlackUid).mock.calls[0]?.[3]).toBe("slack/gone");
+ });
+ it("leaves a portable-credential channel file alone and reports missing variables", async () => {
+ const effects = deps();
+ vi.mocked(effects.readSlackChannelFile).mockResolvedValue({ kind: "environment" });
+ vi.mocked(effects.missingSlackEnvironment).mockResolvedValue(["SLACK_SIGNING_SECRET"]);
+ const ctx = contexts({});
+
+ const plan = await prepareSlackSetup(ctx.prepare, effects);
+ await expect(applySlackSetup(plan, ctx.apply, effects)).resolves.toEqual({ facts: [] });
+
+ expect(ctx.log.warning).toHaveBeenCalledWith(
+ expect.stringContaining("SLACK_SIGNING_SECRET is not set"),
+ );
+ expect(effects.ensureChannel).not.toHaveBeenCalled();
+ expect(effects.provisionSlackbot).not.toHaveBeenCalled();
+ expect(ctx.resolveVercelProject).not.toHaveBeenCalled();
});
it("allows the project resolver to authenticate and link Vercel Connect", async () => {
const effects = deps();
@@ -98,7 +297,6 @@ describe("Slack setup", () => {
await expect(prepareSlackSetup(ctx.prepare, effects)).resolves.toMatchObject({
credentials: "vercel-connect",
- project: { orgId: "team", projectId: "project" },
});
expect(ctx.resolveVercelProject).toHaveBeenCalledWith("Slack");
});
diff --git a/packages/eve/src/setup/integrations/slack/setup.ts b/packages/eve/src/setup/integrations/slack/setup.ts
index 7c0c9c080..b38f14fc8 100644
--- a/packages/eve/src/setup/integrations/slack/setup.ts
+++ b/packages/eve/src/setup/integrations/slack/setup.ts
@@ -1,18 +1,24 @@
-import { select } from "#setup/ask.js";
-import type { VercelProjectReference } from "#setup/project-resolution.js";
+import { join } from "node:path";
+
+import { readDevelopmentEnvironmentValues } from "#shared/development-env-files.js";
+import { InvalidAnswerError, select } from "#setup/ask.js";
import {
deriveSlackConnectorSlug,
ensureChannel,
type SlackConnectorSlug,
} from "#setup/scaffold/index.js";
+import { readSlackChannelFile } from "#setup/scaffold/update/update-slack-channel.js";
import {
+ connectorInUseMessage,
inspectSlackbotConnectors,
provisionSlackbot,
reconcileSlackUid,
type ProvisionSlackbotResult,
+ type SlackbotConnectorInspection,
+ type SlackConnectorCandidate,
type SlackConnectorSelection,
} from "#setup/slackbot.js";
-import { slackMessageDeepLink, type SlackConnectorRef } from "#setup/slack-connect.js";
+import { slackMessageDeepLink } from "#setup/slack-connect.js";
import { WizardCancelledError } from "#setup/step.js";
import { installScaffoldDependencies, reportOverwrittenFiles } from "../shared/scaffold.js";
@@ -23,10 +29,14 @@ import {
} from "../types.js";
const SLACK_REQUIRES_VERCEL = "Slack setup with Vercel Connect requires a linked Vercel project.";
+const SLACK_CHANNEL_PATH = "agent/channels/slack.ts";
+const SLACK_ENVIRONMENT_VARIABLES = ["SLACK_BOT_TOKEN", "SLACK_SIGNING_SECRET"] as const;
+/** Above this many connectors the question offers a type-ahead filter. */
+const SEARCHABLE_CONNECTOR_COUNT = 7;
type SlackbotFailure = Exclude<
ProvisionSlackbotResult,
- { state: "attached" } | { state: "cancelled" }
+ { state: "attached" } | { state: "already-configured" } | { state: "cancelled" }
>;
function slackbotFailureCopy(result: SlackbotFailure): { reason: string; followUp: string } {
@@ -36,11 +46,21 @@ function slackbotFailureCopy(result: SlackbotFailure): { reason: string; followU
reason: "Slackbot is not connected to a Slack workspace. Slack channel was not added.",
followUp: "Re-run `eve add channel/slack` after the workspace install is complete.",
};
- case "cleanup-failed":
+ case "cleanup-failed": {
+ if (result.connectorUids.length === 0) {
+ return {
+ reason:
+ "eve couldn't confirm that the Slack setup in your browser ended. Slack channel was not added.",
+ followUp:
+ "Close the Slack setup page in your browser, wait a few minutes for the request to expire, then re-run `eve add channel/slack`.",
+ };
+ }
+ const uids = result.connectorUids.map((uid) => `\`${uid}\``).join(", ");
return {
- reason: "The abandoned Slack connector could not be removed. Slack channel was not added.",
- followUp: "Resolve the cleanup warning above before trying again.",
+ reason: `eve could not remove the Slack connector this attempt may have created (${uids}). Slack channel was not added.`,
+ followUp: `Check that no other project uses it, remove it with \`vercel connect remove <uid> --disconnect-all --yes\`, then re-run \`eve add channel/slack\`.`,
};
+ }
case "connector-lookup-failed":
return {
reason: "Existing Slack connectors could not be inspected. Slack channel was not added.",
@@ -54,25 +74,36 @@ function slackbotFailureCopy(result: SlackbotFailure): { reason: string; followU
case "existing-not-installed":
return {
reason:
- "The existing Slack connector is not connected to a Slack workspace. Slack channel was not added.",
- followUp: "Resolve the existing connector warning above before trying again.",
+ "The Slack connector is not installed in a Slack workspace yet. Slack channel was not added.",
+ followUp: "Re-run `eve add channel/slack` to open its install page again.",
};
- case "detach-failed":
+ case "connector-in-use":
return {
- reason:
- "Slackbot provisioning could not replace the existing trigger destination. Slack channel was not added.",
- followUp: "Run the `vercel connect detach` and `vercel connect attach` commands above.",
+ reason: `${result.connectorUid} is used by another project. Slack channel was not added.`,
+ followUp: "Re-run `eve add channel/slack` and create a new Slack app for this agent.",
};
- case "attach-failed":
+ case "trigger-limit-reached":
return {
- reason: "Slackbot provisioning did not attach this project. Slack channel was not added.",
- followUp: "Finish event delivery with the `vercel connect attach` command above.",
+ reason: `${result.connectorUid} already has the maximum number of trigger destinations. Slack channel was not added.`,
+ followUp:
+ "Remove one destination in the Connect dashboard, then re-run `eve add channel/slack`.",
};
- case "create-failed":
+ case "attach-failed":
return {
- reason: "Slackbot creation failed.",
- followUp: "Add it later with `eve add channel/slack`.",
+ reason:
+ "Slackbot provisioning did not finish event delivery for this project. Slack channel was not added.",
+ followUp: "Re-run `eve add channel/slack` to finish the remaining steps.",
};
+ case "create-failed":
+ return result.detail === undefined
+ ? {
+ reason: "Vercel could not create the Slack connector. Slack channel was not added.",
+ followUp: "Re-run `eve add channel/slack` to try again.",
+ }
+ : {
+ reason: `Vercel could not create the Slack connector: ${result.detail} Slack channel was not added.`,
+ followUp: "Fix the problem Vercel reported, then re-run `eve add channel/slack`.",
+ };
}
}
@@ -82,6 +113,14 @@ export interface SlackSetupDeps {
inspectConnectors: typeof inspectSlackbotConnectors;
provisionSlackbot: typeof provisionSlackbot;
reconcileSlackUid: typeof reconcileSlackUid;
+ readSlackChannelFile: typeof readSlackChannelFile;
+ missingSlackEnvironment: (environmentRoot: string) => Promise<string[]>;
+}
+
+/** Slack variables unset in both the process and the local development env files. */
+async function missingSlackEnvironment(environmentRoot: string): Promise<string[]> {
+ const defined = readDevelopmentEnvironmentValues(environmentRoot);
+ return SLACK_ENVIRONMENT_VARIABLES.filter((name) => !process.env[name] && !defined.get(name));
}
const defaultDeps: SlackSetupDeps = {
@@ -90,47 +129,81 @@ const defaultDeps: SlackSetupDeps = {
inspectConnectors: inspectSlackbotConnectors,
provisionSlackbot,
reconcileSlackUid,
+ readSlackChannelFile,
+ missingSlackEnvironment,
};
type SlackSetupPlan =
| { credentials: "environment"; slug: SlackConnectorSlug }
+ /** The channel file already exists and isn't Connect-backed; setup leaves it alone. */
+ | { credentials: "existing-file"; file: "environment"; missing: readonly string[] }
+ | { credentials: "existing-file"; file: "custom" }
| {
credentials: "vercel-connect";
slug: SlackConnectorSlug;
- project: VercelProjectReference;
+ inspection: SlackbotConnectorInspection;
connector: SlackConnectorSelection;
+ /** UID the existing channel file names; patched when another connector is chosen. */
+ channelConnectorUid: string | undefined;
};
+function connectorHint(
+ candidate: SlackConnectorCandidate,
+ preferred: SlackConnectorCandidate | undefined,
+ channelConnectorUid: string | undefined,
+): string {
+ const parts: string[] = [];
+ if (candidate.uid === channelConnectorUid) parts.push(`Named in ${SLACK_CHANNEL_PATH}`);
+ else if (candidate.uid === preferred?.uid) parts.push("Matches this agent");
+ parts.push(candidate.attached ? "attached" : "eve will attach it to this project");
+ if (candidate.workspace === undefined) parts.push("not installed in a Slack workspace");
+ if (candidate.otherProjects.length > 0) {
+ const names = candidate.otherProjects.map((project) => project.name ?? project.id);
+ parts.push(`also used by ${names.join(", ")}`);
+ }
+ return parts.join(" · ");
+}
+
async function chooseConnector(
context: SetupPrepareContext,
- connectors: readonly SlackConnectorRef[],
- preferred: SlackConnectorRef | undefined,
+ inspection: SlackbotConnectorInspection,
+ teamScope: string,
+ channelConnectorUid: string | undefined,
+ expectedUid: string,
): Promise<SlackConnectorSelection> {
- if (connectors.length === 0) return "create";
- return context.asker.ask(
- select({
- key: "slack-connector",
- message: "Which Slack app would you like to use?",
- options: [
- ...connectors.map((connector) => ({
- id: connector.uid,
- value: connector,
- label: `Use ${connector.uid}`,
- hint: connector.uid === preferred?.uid ? "Matches this agent" : undefined,
- })),
- { id: "create", value: "create" as const, label: "Create a new Slack app" },
- ],
- recommended: preferred ?? connectors[0] ?? ("create" as const),
- required: true,
- }),
- );
+ const { candidates, preferred } = inspection;
+ if (candidates.length === 0) return "create";
+ try {
+ return await context.asker.ask<SlackConnectorSelection>(
+ select({
+ key: "slack-connector",
+ message: "Which Slack app would you like to use?",
+ options: [
+ ...candidates.map((candidate) => ({
+ id: candidate.uid,
+ value: candidate,
+ label: `Use ${candidate.uid}`,
+ hint: connectorHint(candidate, preferred, channelConnectorUid),
+ })),
+ { id: "create", value: "create" as const, label: "Create a new Slack app" },
+ ],
+ recommended: preferred ?? ("create" as const),
+ required: true,
+ search: candidates.length > SEARCHABLE_CONNECTOR_COUNT,
+ placeholder: "type to search Slack apps",
+ }),
+ );
+ } catch (error) {
+ if (!(error instanceof InvalidAnswerError)) throw error;
+ throw new InvalidAnswerError(
+ error.question,
+ `${error.message} Searched Slack connectors in team ${teamScope}. eve reuses a Slack app only when it is attached to this project, or named ${expectedUid} and unused by other projects.`,
+ );
+ }
}
-export async function prepareSlackSetup(
- context: SetupPrepareContext,
- deps: SlackSetupDeps = defaultDeps,
-): Promise<SlackSetupPlan> {
- const credentials = await context.asker.ask(
+async function askCredentials(context: SetupPrepareContext) {
+ return context.asker.ask(
select({
key: "slack-credentials",
message: "How would you like to configure Slack?",
@@ -152,21 +225,100 @@ export async function prepareSlackSetup(
required: true,
}),
);
+}
+
+/**
+ * Reads what is already in place before asking anything, so a re-run only
+ * asks the questions an earlier attempt left open. A channel file that names
+ * a connector settles the credential and connector questions.
+ */
+export async function prepareSlackSetup(
+ context: SetupPrepareContext,
+ deps: SlackSetupDeps = defaultDeps,
+): Promise<SlackSetupPlan> {
+ const channelFile = await deps.readSlackChannelFile(join(context.appRoot, SLACK_CHANNEL_PATH));
+ if (!context.force && channelFile.kind === "environment") {
+ return {
+ credentials: "existing-file",
+ file: "environment",
+ missing: await deps.missingSlackEnvironment(context.projectRoot),
+ };
+ }
+ if (!context.force && channelFile.kind === "custom") {
+ return { credentials: "existing-file", file: "custom" };
+ }
+ const channelConnectorUid = channelFile.kind === "connect" ? channelFile.connectorUid : undefined;
+ const resuming = !context.force && channelConnectorUid !== undefined;
+ if (!resuming) {
+ const credentials = await askCredentials(context);
+ if (credentials === "environment") {
+ return { credentials, slug: await deps.deriveSlackConnectorSlug(context.appRoot) };
+ }
+ }
const slug = await deps.deriveSlackConnectorSlug(context.appRoot);
- if (credentials === "environment") return { credentials, slug };
const project = await context.resolveVercelProject("Slack");
if (project.projectId.length === 0) throw new Error(SLACK_REQUIRES_VERCEL);
- const lookup = await deps.inspectConnectors(
+ const inspection = await deps.inspectConnectors(
context.presenter.log,
context.projectRoot,
slug,
- context.signal,
+ {
+ signal: context.signal,
+ channelConnectorUid,
+ },
);
- const connector =
- lookup.state === "found"
- ? await chooseConnector(context, lookup.connectors, lookup.preferred)
- : "create";
- return { credentials, slug, project, connector };
+ let connector: SlackConnectorSelection | undefined;
+ if (resuming) {
+ const inUse = inspection.inUse.find((candidate) => candidate.uid === channelConnectorUid);
+ if (inUse !== undefined) {
+ throw new Error(
+ `${connectorInUseMessage(inUse)} To replace the connector ${SLACK_CHANNEL_PATH} names, re-run \`eve add channel/slack --overwrite\`.`,
+ );
+ }
+ connector = inspection.candidates.find((candidate) => candidate.uid === channelConnectorUid);
+ if (connector === undefined) {
+ context.presenter.log.warning(
+ `${SLACK_CHANNEL_PATH} names \`${channelConnectorUid}\`, which was not found in team ${project.orgId}. Choose a Slack app and eve will update the channel file.`,
+ );
+ }
+ }
+ connector ??= await chooseConnector(
+ context,
+ inspection,
+ project.orgId,
+ channelConnectorUid,
+ `slack/${slug}`,
+ );
+ return {
+ credentials: "vercel-connect",
+ slug,
+ inspection,
+ connector,
+ channelConnectorUid,
+ };
+}
+
+function reportExistingFile(
+ plan: Extract<SlackSetupPlan, { credentials: "existing-file" }>,
+ context: SetupApplyContext,
+) {
+ const { log } = context.presenter;
+ if (plan.file === "custom") {
+ log.info(
+ `${SLACK_CHANNEL_PATH} already configures its own Slack credentials, so eve left it unchanged. Re-run with \`--overwrite\` to replace it with a Vercel Connect channel.`,
+ );
+ } else if (plan.missing.length === 0) {
+ log.success(`${SLACK_CHANNEL_PATH} already uses portable Slack credentials.`);
+ } else {
+ log.warning(
+ `${SLACK_CHANNEL_PATH} reads Slack credentials from environment variables, but ${plan.missing.join(" and ")} ${plan.missing.length === 1 ? "is" : "are"} not set. eve left the channel file unchanged.`,
+ );
+ context.presenter.nextSteps([
+ `Set ${plan.missing.join(" and ")} in .env.local and in the deployment environment.`,
+ "To switch to Vercel Connect instead, re-run `eve add channel/slack --overwrite`.",
+ ]);
+ }
+ return { facts: [] };
}
export async function applySlackSetup(
@@ -174,6 +326,7 @@ export async function applySlackSetup(
context: SetupApplyContext,
deps: SlackSetupDeps = defaultDeps,
) {
+ if (plan.credentials === "existing-file") return reportExistingFile(plan, context);
if (plan.credentials === "environment") {
const result = await deps.ensureChannel({
projectRoot: context.appRoot,
@@ -195,16 +348,14 @@ export async function applySlackSetup(
const result = await deps.provisionSlackbot(
context.presenter.log,
context.projectRoot,
- plan.slug,
+ plan.inspection,
+ plan.connector,
undefined,
- {
- signal: context.signal,
- selectConnector: async () => plan.connector,
- },
+ { signal: context.signal },
);
context.signal?.throwIfAborted();
if (result.state === "cancelled") throw new WizardCancelledError();
- if (result.state !== "attached") {
+ if (result.state !== "attached" && result.state !== "already-configured") {
const copy = slackbotFailureCopy(result);
throw new Error(`${copy.reason} ${copy.followUp}`);
}
@@ -217,16 +368,24 @@ export async function applySlackSetup(
skipDependencyMutation: true,
});
reportOverwrittenFiles(context.presenter.log, channel.filesOverwritten);
+ const unchanged =
+ channel.action === "skipped" &&
+ result.state === "already-configured" &&
+ result.connectorUid === plan.channelConnectorUid;
if (channel.action === "skipped") {
const ready = await deps.reconcileSlackUid(
context.presenter.log,
- context.projectRoot,
+ context.appRoot,
result,
- `slack/${plan.slug}`,
+ plan.channelConnectorUid ?? `slack/${plan.slug}`,
);
if (!ready) throw new Error("Slack connector UID update is required before deployment.");
}
- context.presenter.log.success("Scaffolded channel: slack");
+ context.presenter.log.success(
+ unchanged
+ ? `Slack is already set up with ${result.connectorUid}.`
+ : "Scaffolded channel: slack",
+ );
await installScaffoldDependencies({
changed: channel.packageJsonUpdated.length > 0,
log: context.presenter.log,
diff --git a/packages/eve/src/setup/primitives/process-output.ts b/packages/eve/src/setup/primitives/process-output.ts
index 1a2bf9240..5d518a81f 100644
--- a/packages/eve/src/setup/primitives/process-output.ts
+++ b/packages/eve/src/setup/primitives/process-output.ts
@@ -45,3 +45,15 @@ export function createProcessOutputBuffer(onOutput: ProcessOutputHandler): Proce
},
};
}
+
+/**
+ * The last meaningful stderr line of a failed Vercel CLI run, which is where
+ * the CLI prints its `Error: …` message after any progress output.
+ */
+export function vercelErrorDetail(stderr: string | undefined): string | undefined {
+ return stderr
+ ?.split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0 && !line.startsWith("Vercel CLI "))
+ .at(-1);
+}
diff --git a/packages/eve/src/setup/scaffold/update/update-slack-channel.integration.test.ts b/packages/eve/src/setup/scaffold/update/update-slack-channel.integration.test.ts
new file mode 100644
index 000000000..99ca55e02
--- /dev/null
+++ b/packages/eve/src/setup/scaffold/update/update-slack-channel.integration.test.ts
@@ -0,0 +1,50 @@
+import { mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { ensureChannel } from "./channels.js";
+import { readSlackChannelFile } from "./update-slack-channel.js";
+
+describe("readSlackChannelFile", () => {
+ it("recognizes the channel files eve scaffolds", async () => {
+ const connect = await mkdtemp(join(tmpdir(), "eve-slack-file-"));
+ const environment = await mkdtemp(join(tmpdir(), "eve-slack-file-"));
+ await ensureChannel({
+ projectRoot: connect,
+ kind: "slack",
+ slackConnectorUid: "slack/chief",
+ skipDependencyMutation: true,
+ });
+ await ensureChannel({
+ projectRoot: environment,
+ kind: "slack",
+ slackCredentials: "environment",
+ skipDependencyMutation: true,
+ });
+
+ await expect(readSlackChannelFile(join(connect, "agent/channels/slack.ts"))).resolves.toEqual({
+ kind: "connect",
+ connectorUid: "slack/chief",
+ });
+ await expect(
+ readSlackChannelFile(join(environment, "agent/channels/slack.ts")),
+ ).resolves.toEqual({ kind: "environment" });
+ await expect(readSlackChannelFile(join(connect, "missing.ts"))).resolves.toEqual({
+ kind: "absent",
+ });
+ });
+
+ it("treats hand-written credential wiring as custom", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-slack-file-"));
+ const path = join(root, "slack.ts");
+ await writeFile(
+ path,
+ `const uid = process.env.VERCEL_ENV === "preview" ? "slack/a" : "slack/b";
+export default slackChannel({ credentials: connectSlackCredentials(uid) });
+`,
+ );
+
+ await expect(readSlackChannelFile(path)).resolves.toEqual({ kind: "custom" });
+ });
+});
diff --git a/packages/eve/src/setup/scaffold/update/update-slack-channel.ts b/packages/eve/src/setup/scaffold/update/update-slack-channel.ts
index 04aa6d190..dddf56e83 100644
--- a/packages/eve/src/setup/scaffold/update/update-slack-channel.ts
+++ b/packages/eve/src/setup/scaffold/update/update-slack-channel.ts
@@ -27,3 +27,33 @@ export async function updateSlackChannelConnectorUid(
await writeFile(slackChannelPath, next, "utf8");
return { patched: true };
}
+
+/**
+ * What an existing `agent/channels/slack.ts` already decides. `connect` names
+ * one connector UID literal; `environment` reads the default Slack environment
+ * variables; `custom` is hand-written credential wiring eve does not parse.
+ */
+export type SlackChannelFileState =
+ | { kind: "absent" }
+ | { kind: "connect"; connectorUid: string }
+ | { kind: "environment" }
+ | { kind: "custom" };
+
+/** Reads the Slack channel definition without changing it. */
+export async function readSlackChannelFile(
+ slackChannelPath: string,
+): Promise<SlackChannelFileState> {
+ let source: string;
+ try {
+ source = await readFile(slackChannelPath, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { kind: "absent" };
+ throw error;
+ }
+ const connectorUid = CONNECT_SLACK_CREDENTIALS_REGEX.exec(source)?.[3];
+ if (connectorUid !== undefined && !connectorUid.includes("${")) {
+ return { kind: "connect", connectorUid };
+ }
+ if (/\bconnectSlackCredentials\b|\bcredentials\s*:/.test(source)) return { kind: "custom" };
+ return { kind: "environment" };
+}
diff --git a/packages/eve/src/setup/slack-connect-create.ts b/packages/eve/src/setup/slack-connect-create.ts
index a2cc28867..7bf332010 100644
--- a/packages/eve/src/setup/slack-connect-create.ts
+++ b/packages/eve/src/setup/slack-connect-create.ts
@@ -1,7 +1,7 @@
import { performance } from "node:perf_hooks";
import { setTimeout as sleep } from "node:timers/promises";
-import type { ProcessOutputHandler } from "#setup/primitives/process-output.js";
+import { vercelErrorDetail, type ProcessOutputHandler } from "#setup/primitives/process-output.js";
import type { captureVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";
import {
@@ -29,7 +29,12 @@ type SlackConnectorCreateResult =
ref: SlackConnectorRef;
workspace: SlackWorkspaceConnection;
}
- | { state: "failed" }
+ /**
+ * `detail` is the CLI's own error line, when it printed one. `rejected`
+ * proves no connector exists: the CLI reported an error before it printed
+ * the browser URL, the only flow that can create a managed connector.
+ */
+ | { state: "failed"; detail?: string; rejected: boolean }
| { state: "unresolved" };
type Phase = <T>(message: string, task: () => Promise<T>) => Promise<T>;
@@ -38,6 +43,14 @@ const CREATE_TIMEOUT_MS = 10 * 60_000;
const LOOKUP_REQUEST_TIMEOUT_MS = 10_000;
const LOOKUP_POLL_INTERVAL_MS = 3_000;
const CREATED_CONNECTOR_PROGRESS = /\bConnector created:\s*(scl_[A-Za-z0-9]+)\b/;
+/**
+ * The CLI prints these once Connect hands back the browser URL. Connect
+ * creates a managed connector only inside that browser flow, so a run that
+ * reports its own error before either line (or a `Connector created` line)
+ * cannot have created one. Any other run fails closed, so a reworded CLI
+ * line costs a cleanup warning rather than an orphaned connector.
+ */
+const BROWSER_FLOW_STARTED = /^(Opening browser for |If the browser doesn't open, visit:)/;
const realDelay = (ms: number, signal?: AbortSignal): Promise<void> =>
sleep(ms, undefined, { signal });
@@ -126,6 +139,7 @@ export async function createSlackConnector(input: {
resolveWorkspace = resolve;
rejectWorkspace = reject;
});
+ let browserStarted = false;
let progressLookup: Promise<SlackConnectorRef | undefined> | undefined;
let workspaceWork: Promise<SlackWorkspaceConnection | undefined> | undefined;
const startWorkspaceLookup = (ref: SlackConnectorRef): void => {
@@ -143,6 +157,9 @@ export async function createSlackConnector(input: {
const createOutput: ProcessOutputHandler = (line) => {
input.onOutput(line);
const connectorId = line.text.match(CREATED_CONNECTOR_PROGRESS)?.[1];
+ if (connectorId !== undefined || BROWSER_FLOW_STARTED.test(line.text.trim())) {
+ browserStarted = true;
+ }
if (connectorId === undefined || progressLookup !== undefined) return;
progressLookup = pollCreatedSlackConnector(
input.deps,
@@ -204,7 +221,9 @@ export async function createSlackConnector(input: {
workspaceController.abort();
if (workspaceWork !== undefined) await workspaceWork;
input.signal?.throwIfAborted();
- return { state: "failed" };
+ const detail = vercelErrorDetail(created.result.stderr);
+ if (detail === undefined) return { state: "failed", rejected: false };
+ return { state: "failed", detail, rejected: !browserStarted };
}
const finalRef = parseCreatedSlackConnector(created.result.stdout);
diff --git a/packages/eve/src/setup/slack-connect-lifecycle.ts b/packages/eve/src/setup/slack-connect-lifecycle.ts
index 2bcfd5503..fe7d10210 100644
--- a/packages/eve/src/setup/slack-connect-lifecycle.ts
+++ b/packages/eve/src/setup/slack-connect-lifecycle.ts
@@ -1,143 +1,425 @@
-import { SLACK_CHANNEL_DEFAULT_ROUTE } from "#setup/scaffold/index.js";
-import {
- CONNECT_MUTATION_TIMEOUT_MS,
- replaceConnectTrigger,
- type ConnectTriggerAttachmentResult,
-} from "#setup/connect-provisioning.js";
+import { CONNECT_MUTATION_TIMEOUT_MS } from "#setup/connect-provisioning.js";
import { createPromptCommandOutput, type ChannelSetupLog } from "#setup/cli/index.js";
import { captureVercel, runVercel } from "#setup/primitives/run-vercel.js";
+import { mapWithConcurrency } from "#shared/map-with-concurrency.js";
+import { isNotFoundApiFailure, normalizeVercelApiResult } from "#setup/vercel-api-failure.js";
import {
+ parseConnectorProjects,
parseSlackConnectorDetails,
- parseSlackConnectors,
+ parseSlackConnectorPage,
type RawSlackConnector,
type SlackConnectorDetails,
+ type SlackConnectorProject,
type SlackConnectorRef,
+ type SlackTriggerDestination,
type SlackWorkspaceConnection,
- type VercelConnectListResponse,
} from "./slack-connect.js";
+import type { SlackConnectorCandidate, SlackRoutingPlan } from "./slack-setup-plan.js";
export const CONNECT_LOOKUP_TIMEOUT_MS = 60_000;
-/** Connect subprocess operations needed to inventory and remove Slack connectors. */
+/** Connect subprocess operations needed to inspect and remove Slack connectors. */
export interface SlackConnectLifecycleDeps {
captureVercel: typeof captureVercel;
runVercel: typeof runVercel;
}
-type SlackConnectorInventory =
- | { state: "ok"; body: unknown; connectors: readonly RawSlackConnector[] }
- | { state: "failed"; message: string };
-
export type SlackConnectorCleanupResult =
| { state: "clean" }
| { state: "failed"; connectorUids: readonly string[] };
type CommandOutput = ReturnType<typeof createPromptCommandOutput>;
+type LookupFailure = { state: "failed"; message: string };
+
/** Shared dependencies and output routing for one connector cleanup operation. */
interface SlackConnectorCleanupContext {
log: ChannelSetupLog;
deps: SlackConnectLifecycleDeps;
projectRoot: string;
+ orgId: string | undefined;
onOutput: CommandOutput;
}
-/** Reads and validates the account-level Slack connector inventory. */
-export async function listSlackConnectors(
- deps: SlackConnectLifecycleDeps,
- projectRoot: string,
- onOutput: CommandOutput,
- signal?: AbortSignal,
-): Promise<SlackConnectorInventory> {
- const result = await deps.captureVercel(["connect", "list", "-F", "json", "--all-projects"], {
- cwd: projectRoot,
- onOutput,
- timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
- signal,
- });
- if (!result.ok) return { state: "failed", message: result.failure.message };
+/** `vercel api` arguments for a team-scoped Connect request. */
+function connectApiArgs(
+ path: string,
+ orgId: string | undefined,
+ params: Record<string, string> = {},
+ flags: readonly string[] = [],
+): string[] {
+ const query = new URLSearchParams(params);
+ if (orgId !== undefined) query.set("teamId", orgId);
+ const search = query.toString();
+ const args = ["api", search === "" ? path : `${path}?${search}`, ...flags];
+ if (orgId !== undefined) args.push("--scope", orgId);
+ return args;
+}
- try {
- const parsed = JSON.parse(result.stdout) as unknown;
- if (typeof parsed !== "object" || parsed === null) {
- return { state: "failed", message: "Vercel returned a malformed connector list." };
+function connectorPath(key: string): string {
+ return `/v1/connect/connectors/${encodeURIComponent(key)}`;
+}
+
+/** The largest page the connector list accepts. */
+const CONNECTOR_LIST_PAGE_SIZE = 100;
+/** Upper bound on list pages so a misbehaving cursor cannot loop forever. */
+const MAX_CONNECTOR_LIST_PAGES = 50;
+
+/**
+ * Lists the Slack connectors attached to one project, with each connector's
+ * attached projects. Connect filters by project server-side, so the team's
+ * size doesn't matter.
+ */
+async function listProjectSlackConnectors(input: {
+ deps: SlackConnectLifecycleDeps;
+ projectRoot: string;
+ projectId: string;
+ orgId: string | undefined;
+ onOutput: CommandOutput;
+ signal?: AbortSignal;
+}): Promise<{ state: "ok"; connectors: readonly RawSlackConnector[] } | LookupFailure> {
+ const connectors: RawSlackConnector[] = [];
+ const seenCursors = new Set<string>();
+ let cursor: string | undefined;
+ for (let page = 0; page < MAX_CONNECTOR_LIST_PAGES; page += 1) {
+ const params: Record<string, string> = {
+ projectId: input.projectId,
+ type: "slack",
+ include: "projects",
+ limit: String(CONNECTOR_LIST_PAGE_SIZE),
+ };
+ if (cursor !== undefined) params.cursor = cursor;
+ const result = await input.deps.captureVercel(
+ connectApiArgs("/v1/connect/connectors", input.orgId, params),
+ {
+ cwd: input.projectRoot,
+ onOutput: input.onOutput,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
+ signal: input.signal,
+ },
+ );
+ if (!result.ok) return { state: "failed", message: result.failure.message };
+
+ let parsed: ReturnType<typeof parseSlackConnectorPage>;
+ try {
+ parsed = parseSlackConnectorPage(JSON.parse(result.stdout));
+ } catch {
+ return { state: "failed", message: "Vercel returned invalid JSON for the connector list." };
}
- const response = parsed as VercelConnectListResponse;
- if (!Array.isArray(response.connectors ?? response.clients)) {
+ if (parsed === undefined) {
return { state: "failed", message: "Vercel returned a malformed connector list." };
}
- return { state: "ok", body: parsed, connectors: parseSlackConnectors(parsed) };
- } catch {
- return { state: "failed", message: "Vercel returned invalid JSON for the connector list." };
+ connectors.push(...parsed.connectors);
+ if (parsed.next === undefined) return { state: "ok", connectors };
+ if (seenCursors.has(parsed.next)) {
+ return { state: "failed", message: `The connector list repeated cursor ${parsed.next}.` };
+ }
+ seenCursors.add(parsed.next);
+ cursor = parsed.next;
}
+ return {
+ state: "failed",
+ message: `The connector list has more than ${MAX_CONNECTOR_LIST_PAGES} pages.`,
+ };
}
-export type SlackConnectorLookup =
- | {
- state: "found";
- connectors: readonly SlackConnectorRef[];
- preferred?: SlackConnectorRef;
- connectorUids: ReadonlySet<string>;
- }
- | { state: "not-found"; connectorUids: ReadonlySet<string> }
- | { state: "failed"; message: string };
-
-/** Lists Slack connectors attached to the linked project and identifies the expected UID. */
-export async function findSlackConnector(
- deps: SlackConnectLifecycleDeps,
- projectRoot: string,
- projectId: string | undefined,
- expectedUid: string | undefined,
- onOutput: CommandOutput,
- signal?: AbortSignal,
-): Promise<SlackConnectorLookup> {
- const list = await listSlackConnectors(deps, projectRoot, onOutput, signal);
- if (list.state === "failed") return list;
- const connectorUids = new Set(list.connectors.map((connector) => connector.uid));
- 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 };
+/**
+ * The first page of a connector's attached projects. A connector with more
+ * than one page is used elsewhere either way, so later pages never change
+ * whether setup may reuse it.
+ */
+async function fetchConnectorProjects(input: {
+ deps: Pick<SlackConnectLifecycleDeps, "captureVercel">;
+ projectRoot: string;
+ connectorId: string;
+ orgId: string | undefined;
+ onOutput: CommandOutput;
+ signal?: AbortSignal;
+}): Promise<{ state: "ok"; projects: readonly SlackConnectorProject[] } | LookupFailure> {
+ const result = await input.deps.captureVercel(
+ connectApiArgs(`${connectorPath(input.connectorId)}/projects`, input.orgId),
+ {
+ cwd: input.projectRoot,
+ onOutput: input.onOutput,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
+ signal: input.signal,
+ },
+ );
+ if (!result.ok) return { state: "failed", message: result.failure.message };
+ try {
+ const projects = parseConnectorProjects(JSON.parse(result.stdout));
+ return projects === undefined
+ ? { state: "failed", message: "Vercel returned a malformed connector project list." }
+ : { state: "ok", projects };
+ } catch {
+ return {
+ state: "failed",
+ message: "Vercel returned invalid JSON for the connector project list.",
+ };
+ }
}
/**
- * Outcome of pointing a connector's trigger destination at this project's eve
- * route. Detach and attach are reported separately because attach must not run
- * while an old trigger destination may still exist. A `detach-failed` connector
- * is left in a known-stale state the caller surfaces with manual recovery steps.
+ * Projects other than this one that use the connector, by attachment or by
+ * trigger destination.
*/
-type SlackConnectorAttachmentResult = ConnectTriggerAttachmentResult;
+function otherProjectsOf(
+ projects: readonly SlackConnectorProject[],
+ destinations: readonly SlackTriggerDestination[],
+ projectId: string,
+): SlackConnectorProject[] {
+ const others = projects.filter((project) => project.id !== projectId);
+ for (const destination of destinations) {
+ if (destination.projectId === projectId) continue;
+ if (others.some((project) => project.id === destination.projectId)) continue;
+ others.push({ id: destination.projectId });
+ }
+ return others;
+}
+
+function toCandidate(input: {
+ details: SlackConnectorDetails;
+ attached: boolean;
+ projects: readonly SlackConnectorProject[];
+ projectId: string;
+ createdAt: number;
+}): SlackConnectorCandidate {
+ const { details, projectId } = input;
+ const destinations = details.triggerDestinations;
+ const candidate: SlackConnectorCandidate = {
+ ...details.ref,
+ attached: input.attached,
+ triggerDestinations: destinations,
+ otherProjects: otherProjectsOf(input.projects, destinations, projectId),
+ createdAt: input.createdAt,
+ };
+ if (details.workspace !== undefined) candidate.workspace = details.workspace;
+ return candidate;
+}
+
+/** Detail lookups run a few at a time so many connectors cannot fan out unbounded subprocesses. */
+const INSPECTION_CONCURRENCY = 4;
+
+export type SlackConnectorInspection =
+ | {
+ state: "ok";
+ /** Connectors attached to this project or found by UID, with details. */
+ candidates: readonly SlackConnectorCandidate[];
+ }
+ | LookupFailure;
/**
- * Replaces the connector's default trigger destination with the eve route:
- * detach the existing destination first, then attach this project. Either
- * subprocess failing short-circuits so a half-configured connector is reported
- * rather than silently left pointing at the wrong place.
+ * Read-only snapshot of the Slack connectors that matter to the linked
+ * project: those attached to it, plus `namedUids` looked up directly. Each
+ * carries its attachment, workspace installation, and trigger destination.
+ * Any unreadable connector fails the whole snapshot so setup never guesses.
*/
-export async function attachSlackConnector(
- deps: SlackConnectLifecycleDeps,
- projectRoot: string,
- ref: SlackConnectorRef,
- onOutput: CommandOutput,
- signal?: AbortSignal,
-): Promise<SlackConnectorAttachmentResult> {
- return replaceConnectTrigger({
- connectorUid: ref.uid,
+export async function inspectSlackConnectors(input: {
+ deps: SlackConnectLifecycleDeps;
+ projectRoot: string;
+ projectId: string;
+ orgId: string | undefined;
+ /**
+ * UIDs to look up even when this project isn't attached: the channel
+ * file's connector and `slack/<slug>`, the names a connector made for this
+ * agent would carry. No other unattached connector is ever reused.
+ */
+ namedUids: ReadonlySet<string>;
+ onOutput: CommandOutput;
+ signal?: AbortSignal;
+}): Promise<SlackConnectorInspection> {
+ const { deps, projectRoot, projectId, orgId, onOutput, signal } = input;
+ const list = await listProjectSlackConnectors(input);
+ if (list.state === "failed") return list;
+ const listedUids = new Set(list.connectors.map((connector) => connector.uid));
+ const unlisted = [...input.namedUids].filter((uid) => !listedUids.has(uid));
+ const lookupInput = { deps, projectRoot, orgId, onOutput, signal };
+
+ const inspectListed = async (
+ connector: RawSlackConnector,
+ ): Promise<SlackConnectorCandidate | string> => {
+ const details = await fetchSlackConnectorDetails({
+ ...lookupInput,
+ connectorId: connector.id,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
+ });
+ if (details.state === "failed") return `${connector.uid}: ${details.message}`;
+ return toCandidate({
+ details: details.details,
+ attached: true,
+ projects: connector.projects,
+ projectId,
+ createdAt: connector.createdAt,
+ });
+ };
+ const inspectNamed = async (
+ uid: string,
+ ): Promise<SlackConnectorCandidate | string | undefined> => {
+ const lookup = await lookupSlackConnector({
+ ...lookupInput,
+ key: uid,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
+ });
+ if (lookup.state === "absent") return undefined;
+ if (lookup.state === "failed") return `${uid}: ${lookup.message}`;
+ const projects = await fetchConnectorProjects({
+ ...lookupInput,
+ connectorId: lookup.details.ref.id,
+ });
+ if (projects.state === "failed") return `${uid}: ${projects.message}`;
+ return toCandidate({
+ details: lookup.details,
+ // The project-scoped list is authoritative; this only absorbs a lagging list.
+ attached: projects.projects.some((project) => project.id === projectId),
+ projects: projects.projects,
+ projectId,
+ createdAt: 0,
+ });
+ };
+ const inspected = await mapWithConcurrency(
+ [
+ ...list.connectors.map((connector) => () => inspectListed(connector)),
+ ...unlisted.map((uid) => () => inspectNamed(uid)),
+ ],
+ INSPECTION_CONCURRENCY,
+ (inspect) => inspect(),
+ );
+ const failure = inspected.find((entry) => typeof entry === "string");
+ if (failure !== undefined) return { state: "failed", message: failure };
+ const candidates = inspected.filter((entry) => typeof entry === "object");
+ return { state: "ok", candidates };
+}
+
+/** Rechecks the chosen connector before changing its project access or destinations. */
+export async function refreshSlackCandidate(input: {
+ deps: SlackConnectLifecycleDeps;
+ projectRoot: string;
+ candidate: SlackConnectorCandidate;
+ projectId: string;
+ orgId: string | undefined;
+ onOutput: CommandOutput;
+ signal?: AbortSignal;
+}): Promise<{ state: "ok"; candidate: SlackConnectorCandidate } | LookupFailure> {
+ const { deps, projectRoot, candidate, projectId, orgId, onOutput, signal } = input;
+ const details = await fetchSlackConnectorDetails({
+ deps,
projectRoot,
- triggerPath: SLACK_CHANNEL_DEFAULT_ROUTE,
+ connectorId: candidate.id,
+ orgId,
onOutput,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
signal,
+ });
+ if (details.state === "failed") return details;
+ if (details.details.ref.uid !== candidate.uid) {
+ return { state: "failed", message: `The connector ${candidate.uid} changed since inspection.` };
+ }
+ const projects = await fetchConnectorProjects({
deps,
+ projectRoot,
+ connectorId: candidate.id,
+ orgId,
+ onOutput,
+ signal,
});
+ if (projects.state === "failed") return projects;
+ return {
+ state: "ok",
+ candidate: toCandidate({
+ details: details.details,
+ attached: projects.projects.some((project) => project.id === projectId),
+ projects: projects.projects,
+ projectId,
+ createdAt: candidate.createdAt,
+ }),
+ };
+}
+
+/** Name probes stop here so a long run of taken names fails with a clear error. */
+const MAX_CONNECTOR_NAME_PROBES = 20;
+
+/**
+ * Picks the `--name` for a new connector: `slug`, then `slug-2`, `slug-3`,
+ * and so on. Connect derives the UID `slack/<name>` from it, and a UID a
+ * team connector already uses fails the create, so each name is checked by
+ * looking its UID up directly.
+ */
+export async function findFreeSlackConnectorName(input: {
+ deps: Pick<SlackConnectLifecycleDeps, "captureVercel">;
+ projectRoot: string;
+ orgId: string | undefined;
+ slug: string;
+ onOutput: CommandOutput;
+ signal?: AbortSignal;
+}): Promise<{ state: "ok"; name: string } | LookupFailure> {
+ for (let index = 1; index <= MAX_CONNECTOR_NAME_PROBES; index += 1) {
+ const name = index === 1 ? input.slug : `${input.slug}-${index}`;
+ const uid = `slack/${name}`;
+ const lookup = await lookupSlackConnector({
+ ...input,
+ key: uid,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
+ });
+ if (lookup.state === "failed") return lookup;
+ if (lookup.state === "absent") return { state: "ok", name };
+ }
+ return {
+ state: "failed",
+ message: `Slack connectors \`slack/${input.slug}\` through \`slack/${input.slug}-${MAX_CONNECTOR_NAME_PROBES}\` already exist. Remove unused ones with \`vercel connect remove <uid> --disconnect-all --yes\`, then try again.`,
+ };
+}
+
+/** Result of making a connector deliver this project's events to eve's Slack route. */
+export type SlackRoutingResult =
+ | { state: "configured" }
+ | { state: "attach-failed"; message?: string };
+
+/**
+ * Applies the planned routing mutation. Never detaches: attach only adds
+ * token access, and the trigger-destinations replacement keeps the project's
+ * token access and every other project's entries intact.
+ */
+export async function applySlackRouting(input: {
+ deps: SlackConnectLifecycleDeps;
+ projectRoot: string;
+ ref: SlackConnectorRef;
+ plan: Extract<SlackRoutingPlan, { kind: "apply" }>;
+ orgId: string | undefined;
+ onOutput: CommandOutput;
+ signal?: AbortSignal;
+}): Promise<SlackRoutingResult> {
+ const { deps, projectRoot, ref, plan, orgId, onOutput, signal } = input;
+ if (plan.attach) {
+ const args = ["connect", "attach", ref.uid, "--yes"];
+ if (orgId !== undefined) args.push("--scope", orgId);
+ const attached = await deps.runVercel(args, {
+ cwd: projectRoot,
+ onOutput,
+ nonInteractive: true,
+ timeoutMs: CONNECT_MUTATION_TIMEOUT_MS,
+ signal,
+ });
+ if (!attached) return { state: "attach-failed" };
+ }
+ if (plan.destinations === undefined) return { state: "configured" };
+ const args = connectApiArgs(`${connectorPath(ref.id)}/trigger-destinations`, orgId, {}, [
+ "--method",
+ "PATCH",
+ "--input",
+ "-",
+ ]);
+ const result = normalizeVercelApiResult(
+ await deps.captureVercel(args, {
+ cwd: projectRoot,
+ onOutput,
+ stdin: JSON.stringify({ destinations: plan.destinations }),
+ timeoutMs: CONNECT_MUTATION_TIMEOUT_MS,
+ signal,
+ }),
+ );
+ return result.ok
+ ? { state: "configured" }
+ : { state: "attach-failed", message: result.failure.message };
}
type SlackWorkspaceLookup =
@@ -149,30 +431,38 @@ type SlackConnectorDetailsLookup =
| { state: "found"; details: SlackConnectorDetails }
| { state: "failed"; message: string };
-/** Fetches and validates one team-scoped connector detail payload. */
-export async function fetchSlackConnectorDetails(input: {
+/**
+ * Looks one connector up by ID or UID. Connect answers 404 for a key no team
+ * connector uses, which is how a UID is proven free.
+ */
+async function lookupSlackConnector(input: {
deps: Pick<SlackConnectLifecycleDeps, "captureVercel">;
projectRoot: string;
- connectorId: string;
+ key: string;
orgId: string | undefined;
onOutput: CommandOutput;
timeoutMs: number;
signal?: AbortSignal;
-}): Promise<SlackConnectorDetailsLookup> {
- const suffix = input.orgId === undefined ? "" : `?teamId=${encodeURIComponent(input.orgId)}`;
- const args = ["api", `/v1/connect/connectors/${encodeURIComponent(input.connectorId)}${suffix}`];
- if (input.orgId !== undefined) args.push("--scope", input.orgId);
- const result = await input.deps.captureVercel(args, {
- cwd: input.projectRoot,
- onOutput: input.onOutput,
- timeoutMs: input.timeoutMs,
- signal: input.signal,
- });
- if (!result.ok) return { state: "failed", message: result.failure.message };
+}): Promise<SlackConnectorDetailsLookup | { state: "absent"; message: string }> {
+ const result = await input.deps.captureVercel(
+ connectApiArgs(connectorPath(input.key), input.orgId),
+ {
+ cwd: input.projectRoot,
+ onOutput: input.onOutput,
+ timeoutMs: input.timeoutMs,
+ signal: input.signal,
+ },
+ );
+ if (!result.ok) {
+ return {
+ state: isNotFoundApiFailure(result.failure) ? "absent" : "failed",
+ message: result.failure.message,
+ };
+ }
try {
const parsed = JSON.parse(result.stdout) as unknown;
const details = parseSlackConnectorDetails(parsed);
- return details?.ref.id === input.connectorId
+ return details?.ref.id === input.key || details?.ref.uid === input.key
? { state: "found", details }
: { state: "failed", message: "Vercel returned an invalid Slack connector." };
} catch {
@@ -180,6 +470,20 @@ export async function fetchSlackConnectorDetails(input: {
}
}
+/** Fetches and validates one team-scoped connector detail payload. */
+export async function fetchSlackConnectorDetails(input: {
+ deps: Pick<SlackConnectLifecycleDeps, "captureVercel">;
+ projectRoot: string;
+ connectorId: string;
+ orgId: string | undefined;
+ onOutput: CommandOutput;
+ timeoutMs: number;
+ signal?: AbortSignal;
+}): Promise<SlackConnectorDetailsLookup> {
+ const lookup = await lookupSlackConnector({ ...input, key: input.connectorId });
+ return lookup.state === "absent" ? { state: "failed", message: lookup.message } : lookup;
+}
+
/** Fetches the Slack workspace connected to a connector, if one exists yet. */
export async function fetchSlackWorkspace(input: {
deps: Pick<SlackConnectLifecycleDeps, "captureVercel">;
@@ -230,37 +534,39 @@ async function cleanupConnectorUids(
}
/**
- * Removes the exact connector returned by `connect create`. When no UID was
- * returned, ownership cannot be proven: a concurrent or eventually-consistent
- * connector looks the same as this attempt's. So cleanup fails closed. It
- * removes nothing and instead surfaces the connectors that look like this
- * attempt's, matching `expectedUid` and absent from the pre-create snapshot, so
- * the caller can stop rather than risk removing a bystander's connector.
+ * Removes the exact connector returned by `connect create`. A run the CLI
+ * rejected before its browser flow cannot have created a connector, so there
+ * is nothing to remove. Otherwise, when no UID was returned, ownership cannot be
+ * proven: the browser page may still create one, and a concurrent or
+ * eventually-consistent connector looks the same as this attempt's. So
+ * cleanup fails closed. It removes nothing and instead surfaces
+ * `expectedUid`, which was free before this attempt, if it now exists, so the
+ * caller can stop rather than risk removing a bystander's connector.
*/
export async function cleanupCreatedAttempt(
context: SlackConnectorCleanupContext,
input: {
expectedUid: string;
- baselineConnectorUids: ReadonlySet<string>;
createdRef: SlackConnectorRef | undefined;
+ /** The CLI reported its own error before printing the browser URL. */
+ rejected: boolean;
},
): Promise<SlackConnectorCleanupResult> {
if (input.createdRef) {
return cleanupConnectorUids(context, [input.createdRef.uid]);
}
+ if (input.rejected) return { state: "clean" };
context.log.warning(
"eve couldn't confirm the Slack request in your browser was cancelled. Wait for it to expire before retrying.",
);
- const inventory = await listSlackConnectors(context.deps, context.projectRoot, context.onOutput);
- if (inventory.state === "failed") return { state: "failed", connectorUids: [] };
-
- const suspected = inventory.connectors
- .map((connector) => connector.uid)
- .filter(
- (uid) =>
- (uid === input.expectedUid || uid.startsWith(`${input.expectedUid}-`)) &&
- !input.baselineConnectorUids.has(uid),
- );
- return { state: "failed", connectorUids: suspected };
+ const lookup = await lookupSlackConnector({
+ ...context,
+ key: input.expectedUid,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
+ });
+ return {
+ state: "failed",
+ connectorUids: lookup.state === "found" ? [input.expectedUid] : [],
+ };
}
diff --git a/packages/eve/src/setup/slack-connect.ts b/packages/eve/src/setup/slack-connect.ts
index 497aeef2c..b6a25eb60 100644
--- a/packages/eve/src/setup/slack-connect.ts
+++ b/packages/eve/src/setup/slack-connect.ts
@@ -8,21 +8,6 @@
import { z } from "#compiled/zod/index.js";
-interface VercelConnectListClient {
- uid?: unknown;
- id?: unknown;
- type?: unknown;
- createdAt?: unknown;
- projects?: unknown;
-}
-
-export interface VercelConnectListResponse {
- /** `vercel connect list -F json` (current CLI). */
- connectors?: unknown;
- /** Older CLI builds emitted the same array under `clients`. */
- clients?: unknown;
-}
-
const NonEmptyStringSchema = z.string().min(1);
const SlackConnectorRefSchema = z.object({
@@ -30,7 +15,15 @@ const SlackConnectorRefSchema = z.object({
id: NonEmptyStringSchema,
});
+const SlackTriggerDestinationSchema = z.object({
+ projectId: NonEmptyStringSchema,
+ path: NonEmptyStringSchema.nullish(),
+ branch: NonEmptyStringSchema.nullish(),
+ customEnvironmentId: NonEmptyStringSchema.nullish(),
+});
+
const SlackConnectorDetailsSchema = SlackConnectorRefSchema.extend({
+ triggerDestinations: z.array(SlackTriggerDestinationSchema).nullish(),
data: z
.object({
appId: NonEmptyStringSchema.nullish(),
@@ -53,10 +46,32 @@ export interface SlackWorkspaceConnection {
workspaceName?: string;
}
+/**
+ * One place Vercel Connect forwards Slack events. A destination without
+ * `branch` or `customEnvironmentId` targets the project's default deployment.
+ */
+export interface SlackTriggerDestination {
+ projectId: string;
+ path?: string;
+ branch?: string;
+ customEnvironmentId?: string;
+}
+
/** Parsed Slack connector state returned by Vercel's connector detail API. */
export interface SlackConnectorDetails {
ref: SlackConnectorRef;
workspace?: SlackWorkspaceConnection;
+ triggerDestinations: readonly SlackTriggerDestination[];
+}
+
+function toTriggerDestination(
+ raw: z.infer<typeof SlackTriggerDestinationSchema>,
+): SlackTriggerDestination {
+ const destination: SlackTriggerDestination = { projectId: raw.projectId };
+ if (raw.path != null) destination.path = raw.path;
+ if (raw.branch != null) destination.branch = raw.branch;
+ if (raw.customEnvironmentId != null) destination.customEnvironmentId = raw.customEnvironmentId;
+ return destination;
}
/**
@@ -69,7 +84,8 @@ export function parseSlackConnectorDetails(body: unknown): SlackConnectorDetails
if (!parsed.success) return undefined;
const { id, uid, data } = parsed.data;
const ref = { id, uid };
- if (data?.appId == null || data.slackTeam == null) return { ref };
+ const triggerDestinations = (parsed.data.triggerDestinations ?? []).map(toTriggerDestination);
+ if (data?.appId == null || data.slackTeam == null) return { ref, triggerDestinations };
const workspaceUrl = new URL("https://slack.com/app_redirect");
workspaceUrl.searchParams.set("app", data.appId);
@@ -78,10 +94,7 @@ export function parseSlackConnectorDetails(body: unknown): SlackConnectorDetails
data.slackTeam.name == null
? { workspaceUrl: workspaceUrl.href }
: { workspaceUrl: workspaceUrl.href, workspaceName: data.slackTeam.name };
- return {
- ref,
- workspace,
- };
+ return { ref, workspace, triggerDestinations };
}
/**
@@ -122,39 +135,78 @@ export function slackMessageDeepLink(url: string): string {
return parsed.href;
}
-/** A Slack connector plus the project ids it is attached to. */
+/** A project attached to a connector. */
+export interface SlackConnectorProject {
+ id: string;
+ name?: string;
+}
+
+/** A Slack connector plus the projects it is attached to. */
export interface RawSlackConnector {
uid: string;
- id?: string;
- projectIds: readonly string[];
+ id: string;
+ /** Attached projects, possibly truncated to the first few. */
+ projects: readonly SlackConnectorProject[];
createdAt: number;
}
-/** Parses Slack connectors (uid + attached project ids) from a connect-list response. */
-export function parseSlackConnectors(listJson: unknown): RawSlackConnector[] {
- if (typeof listJson !== "object" || listJson === null) return [];
- const response = listJson as VercelConnectListResponse;
- const connectors = response.connectors ?? response.clients;
- if (!Array.isArray(connectors)) return [];
- const parsed: RawSlackConnector[] = [];
- for (const raw of connectors as VercelConnectListClient[]) {
- if (raw.type !== "slack" || typeof raw.uid !== "string") continue;
- const projectIds = Array.isArray(raw.projects)
- ? raw.projects
- .map((project) =>
- typeof project === "object" && project !== null
- ? (project as { id?: unknown }).id
- : undefined,
- )
- .filter((id): id is string => typeof id === "string")
- : [];
- 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;
+const ProjectLinkSchema = z.object({
+ projectId: NonEmptyStringSchema,
+ project: z.object({ id: NonEmptyStringSchema, name: z.string().nullish() }).nullish(),
+});
+
+const PaginationSchema = z.object({ next: z.string().nullish() }).nullish();
+
+const ConnectorPageSchema = z.object({
+ clients: z.array(
+ z.object({
+ id: NonEmptyStringSchema,
+ uid: NonEmptyStringSchema,
+ type: z.string(),
+ createdAt: z.number().nullish(),
+ includes: z
+ .object({
+ projects: z.object({ items: z.array(ProjectLinkSchema) }).nullish(),
+ })
+ .nullish(),
+ }),
+ ),
+ pagination: PaginationSchema,
+});
+
+const ConnectorProjectsSchema = z.object({ projects: z.array(ProjectLinkSchema) });
+
+function toProject(link: z.infer<typeof ProjectLinkSchema>): SlackConnectorProject {
+ const id = link.project?.id ?? link.projectId;
+ const name = link.project?.name;
+ return name == null ? { id } : { id, name };
+}
+
+/** One page of `GET /v1/connect/connectors?include=projects`. */
+export interface SlackConnectorPage {
+ connectors: RawSlackConnector[];
+ /** Cursor for the next page, absent on the last one. */
+ next?: string;
+}
+
+/** Parses one connector list page, keeping only Slack connectors. */
+export function parseSlackConnectorPage(body: unknown): SlackConnectorPage | undefined {
+ const parsed = ConnectorPageSchema.safeParse(body);
+ if (!parsed.success) return undefined;
+ const connectors = parsed.data.clients
+ .filter((client) => client.type === "slack")
+ .map((client) => ({
+ uid: client.uid,
+ id: client.id,
+ projects: (client.includes?.projects?.items ?? []).map(toProject),
+ createdAt: client.createdAt ?? 0,
+ }));
+ const next = parsed.data.pagination?.next;
+ return next == null ? { connectors } : { connectors, next };
+}
+
+/** Parses one page of `GET /v1/connect/connectors/<id>/projects`. */
+export function parseConnectorProjects(body: unknown): SlackConnectorProject[] | undefined {
+ const parsed = ConnectorProjectsSchema.safeParse(body);
+ return parsed.success ? parsed.data.projects.map(toProject) : undefined;
}
diff --git a/packages/eve/src/setup/slack-setup-plan.test.ts b/packages/eve/src/setup/slack-setup-plan.test.ts
new file mode 100644
index 000000000..8e21c418d
--- /dev/null
+++ b/packages/eve/src/setup/slack-setup-plan.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from "vitest";
+
+import type { SlackTriggerDestination } from "./slack-connect.js";
+import {
+ orderSlackConnectorCandidates,
+ planSlackRouting,
+ type SlackConnectorCandidate,
+ type SlackRoutingPlan,
+} from "./slack-setup-plan.js";
+
+const ROUTE = "/eve/v1/slack";
+const PROJECT = "prj_this";
+
+const branch: SlackTriggerDestination = { projectId: PROJECT, branch: "preview", path: "/x" };
+const customEnvironment: SlackTriggerDestination = {
+ projectId: PROJECT,
+ customEnvironmentId: "env_staging",
+ path: "/x",
+};
+const otherProject: SlackTriggerDestination = { projectId: "prj_other", path: ROUTE };
+
+describe("planSlackRouting", () => {
+ const own = { projectId: PROJECT, path: ROUTE };
+ const stale = { projectId: PROJECT, path: "/triggers/slack" };
+
+ it.each<[string, boolean, SlackTriggerDestination[], SlackRoutingPlan]>([
+ ["changes nothing when attached and routed", true, [own], { kind: "apply", attach: false }],
+ [
+ "replaces a stale default even beside the correct route",
+ true,
+ [stale, own, branch],
+ { kind: "apply", attach: false, destinations: [branch, own] },
+ ],
+ [
+ "deduplicates two correct default destinations",
+ true,
+ [own, own],
+ { kind: "apply", attach: false, destinations: [own] },
+ ],
+ ["only attaches when routed but unattached", false, [own], { kind: "apply", attach: true }],
+ [
+ "adds a missing destination without re-attaching",
+ true,
+ [otherProject],
+ { kind: "apply", attach: false, destinations: [otherProject, own] },
+ ],
+ [
+ "attaches and adds a missing destination",
+ false,
+ [otherProject],
+ { kind: "apply", attach: true, destinations: [otherProject, own] },
+ ],
+ [
+ "attaches and replaces a stale destination",
+ false,
+ [stale],
+ { kind: "apply", attach: true, destinations: [own] },
+ ],
+ [
+ "replaces only this project's stale default destination",
+ true,
+ [otherProject, stale, branch],
+ { kind: "apply", attach: false, destinations: [otherProject, branch, own] },
+ ],
+ ])("%s", (_name, attached, destinations, expected) => {
+ expect(planSlackRouting({ attached, destinations, projectId: PROJECT, route: ROUTE })).toEqual(
+ expected,
+ );
+ });
+
+ it("stops before exceeding three destinations, not counting a replaced stale entry", () => {
+ const full = [otherProject, branch, customEnvironment];
+ for (const attached of [true, false]) {
+ expect(
+ planSlackRouting({ attached, destinations: full, projectId: PROJECT, route: ROUTE }),
+ ).toEqual({ kind: "limit-reached", destinations: full });
+ }
+ expect(
+ planSlackRouting({
+ attached: true,
+ destinations: [otherProject, branch, stale],
+ projectId: PROJECT,
+ route: ROUTE,
+ }),
+ ).toMatchObject({ kind: "apply" });
+ });
+});
+
+function candidate(uid: string, createdAt: number, attached: boolean): SlackConnectorCandidate {
+ return {
+ uid,
+ id: `scl_${createdAt}`,
+ attached,
+ triggerDestinations: [],
+ otherProjects: [],
+ createdAt,
+ };
+}
+
+describe("orderSlackConnectorCandidates", () => {
+ const named = candidate("slack/named", 1, false);
+ const matching = candidate("slack/my-agent", 2, false);
+ const olderAttached = candidate("slack/old", 3, true);
+ const newerAttached = candidate("slack/new", 4, true);
+ const unrelated = candidate("slack/unrelated", 5, false);
+ const all = [named, matching, olderAttached, newerAttached, unrelated];
+
+ it.each([
+ ["the channel file UID", { channelConnectorUid: "slack/named" }, all, named],
+ ["the derived slug", {}, all, matching],
+ ["the newest attached connector", {}, [olderAttached, newerAttached, unrelated], newerAttached],
+ ["nothing, so a new connector", {}, [unrelated], undefined],
+ ])("suggests %s", (_name, input, candidates, expected) => {
+ expect(
+ orderSlackConnectorCandidates(candidates, { expectedUid: "slack/my-agent", ...input })
+ .preferred,
+ ).toBe(expected);
+ });
+
+ it("lists the suggestion first, then attached connectors, then the rest by age", () => {
+ expect(
+ orderSlackConnectorCandidates(all, { expectedUid: "slack/my-agent" }).candidates.map(
+ (entry) => entry.uid,
+ ),
+ ).toEqual(["slack/my-agent", "slack/new", "slack/old", "slack/unrelated", "slack/named"]);
+ });
+});
diff --git a/packages/eve/src/setup/slack-setup-plan.ts b/packages/eve/src/setup/slack-setup-plan.ts
new file mode 100644
index 000000000..093938124
--- /dev/null
+++ b/packages/eve/src/setup/slack-setup-plan.ts
@@ -0,0 +1,124 @@
+/**
+ * Pure decisions for resumable Slack setup: which mutation (if any) finishes
+ * event delivery and which connector setup suggests.
+ */
+
+import type {
+ SlackConnectorProject,
+ SlackConnectorRef,
+ SlackTriggerDestination,
+ SlackWorkspaceConnection,
+} from "./slack-connect.js";
+
+/** Connect rejects a fourth trigger destination on one connector. */
+export const MAX_SLACK_TRIGGER_DESTINATIONS = 3;
+
+/** A connector other projects use, which setup never attaches to this one. */
+export interface SlackConnectorInUse {
+ uid: string;
+ otherProjects: readonly SlackConnectorProject[];
+}
+
+/** One team Slack connector as setup sees it before changing anything. */
+export interface SlackConnectorCandidate extends SlackConnectorRef {
+ /** Whether the linked project has token access to this connector. */
+ attached: boolean;
+ /** Present once the Slack app is installed into a workspace. */
+ workspace?: SlackWorkspaceConnection;
+ triggerDestinations: readonly SlackTriggerDestination[];
+ /**
+ * Other projects that use this connector, by attachment or by trigger
+ * destination. Setup never changes their attachments or destinations.
+ */
+ otherProjects: readonly SlackConnectorProject[];
+ createdAt: number;
+}
+
+/**
+ * Whether setup may reuse a connector: it already belongs to this project, or
+ * no other project uses it (for example, one created by hand for this agent).
+ * One Slack app forwards every event to every destination, so attaching a
+ * second agent would make both respond.
+ */
+export function isReusableSlackConnector(candidate: SlackConnectorCandidate): boolean {
+ return candidate.attached || candidate.otherProjects.length === 0;
+}
+
+function isDefaultDeployment(destination: SlackTriggerDestination): boolean {
+ return destination.branch === undefined && destination.customEnvironmentId === undefined;
+}
+
+function isProjectDefault(destination: SlackTriggerDestination, projectId: string): boolean {
+ return destination.projectId === projectId && isDefaultDeployment(destination);
+}
+
+/**
+ * What finishes event delivery for one connector. `attach` gives the project
+ * token access; `destinations`, when present, is the full destination set to
+ * write, changing only this project's default-deployment entry. Each half is
+ * idempotent, so a run that stops between them resumes on the next one.
+ */
+export type SlackRoutingPlan =
+ | { kind: "apply"; attach: boolean; destinations?: readonly SlackTriggerDestination[] }
+ | { kind: "limit-reached"; destinations: readonly SlackTriggerDestination[] };
+
+/**
+ * Plans the routing mutation. An attached project is never re-attached,
+ * because `connect attach` without `--environment` resets its environment
+ * scoping.
+ */
+export function planSlackRouting(input: {
+ attached: boolean;
+ destinations: readonly SlackTriggerDestination[];
+ projectId: string;
+ route: string;
+}): SlackRoutingPlan {
+ const { attached, destinations, projectId, route } = input;
+ const attach = !attached;
+ const own = destinations.filter((destination) => isProjectDefault(destination, projectId));
+ if (own.length === 1 && own[0]?.path === route) return { kind: "apply", attach };
+ const kept = destinations.filter((destination) => !isProjectDefault(destination, projectId));
+ const next = [...kept, { projectId, path: route }];
+ if (next.length > MAX_SLACK_TRIGGER_DESTINATIONS) {
+ return { kind: "limit-reached", destinations };
+ }
+ return { kind: "apply", attach, destinations: next };
+}
+
+/**
+ * Orders candidates for the connector question and picks the suggestion:
+ * the channel file's UID, then `slack/<slug>`, then the newest connector
+ * already attached to this project. `undefined` suggests a new connector.
+ */
+export function orderSlackConnectorCandidates(
+ candidates: readonly SlackConnectorCandidate[],
+ input: { channelConnectorUid?: string | undefined; expectedUid: string },
+): { candidates: SlackConnectorCandidate[]; preferred?: SlackConnectorCandidate } {
+ const byNewest = [...candidates].sort((left, right) => right.createdAt - left.createdAt);
+ const preferred =
+ byNewest.find((candidate) => candidate.uid === input.channelConnectorUid) ??
+ byNewest.find((candidate) => candidate.uid === input.expectedUid) ??
+ byNewest.find((candidate) => candidate.attached);
+ const rest = byNewest
+ .filter((candidate) => candidate !== preferred)
+ .sort((left, right) => Number(right.attached) - Number(left.attached));
+ const ordered = preferred === undefined ? rest : [preferred, ...rest];
+ return preferred === undefined ? { candidates: ordered } : { candidates: ordered, preferred };
+}
+
+/** Human-readable destination list for the trigger-limit report. */
+export function describeSlackDestinations(
+ destinations: readonly SlackTriggerDestination[],
+ projectNames: ReadonlyMap<string, string>,
+): string[] {
+ return destinations.map((destination) => {
+ const project = projectNames.get(destination.projectId) ?? destination.projectId;
+ const target =
+ destination.customEnvironmentId !== undefined
+ ? `custom environment ${destination.customEnvironmentId}`
+ : destination.branch !== undefined
+ ? `branch ${destination.branch}`
+ : "production";
+ return `${project} (${target}) ${destination.path ?? "<default path>"}`;
+ });
+}
diff --git a/packages/eve/src/setup/slackbot.test.ts b/packages/eve/src/setup/slackbot.test.ts
index 94b9d9d26..a58335f63 100644
--- a/packages/eve/src/setup/slackbot.test.ts
+++ b/packages/eve/src/setup/slackbot.test.ts
@@ -1,11 +1,22 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelSetupAwaitChoice, ChannelSetupLog } from "#setup/cli/index.js";
+import { openUrl } from "#setup/primitives/open-url.js";
import { captureVercel, runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";
import { updateSlackChannelConnectorUid } from "#setup/scaffold/update/update-slack-channel.js";
-import { parseCreatedSlackConnector, parseSlackConnectorDetails } from "./slack-connect.js";
-import { provisionSlackbot, reconcileSlackUid, type SlackConnectorSelection } from "./slackbot.js";
+import {
+ parseCreatedSlackConnector,
+ parseSlackConnectorDetails,
+ type SlackTriggerDestination,
+} from "./slack-connect.js";
+import {
+ inspectSlackbotConnectors,
+ provisionSlackbot,
+ reconcileSlackUid,
+ type SlackbotConnectorInspection,
+ type SlackConnectorSelection,
+} from "./slackbot.js";
vi.mock("#setup/primitives/run-vercel.js", () => ({
captureVercel: vi.fn(),
@@ -13,6 +24,8 @@ vi.mock("#setup/primitives/run-vercel.js", () => ({
runVercelCaptureStdout: vi.fn(),
}));
+vi.mock("#setup/primitives/open-url.js", () => ({ openUrl: vi.fn() }));
+
vi.mock("#setup/scaffold/update/update-slack-channel.js", () => ({
updateSlackChannelConnectorUid: vi.fn(),
}));
@@ -21,6 +34,10 @@ const mockedCaptureVercel = vi.mocked(captureVercel);
const mockedRunVercel = vi.mocked(runVercel);
const mockedRunVercelCaptureStdout = vi.mocked(runVercelCaptureStdout);
const mockedUpdateSlackChannelConnectorUid = vi.mocked(updateSlackChannelConnectorUid);
+const mockedOpenUrl = vi.mocked(openUrl);
+
+const INSTALL_URL =
+ /^https:\/\/vercel\.com\/api\/v1\/connect\/install\/scl_my_agent\?teamId=team_demo&request_code=[\w-]{43}$/;
/** `vercel connect create slack … -F json` stdout payload on CLI 54.x. */
function createSlackConnectorJson(uid: string, id = "scl_my_agent"): string {
@@ -52,6 +69,20 @@ function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
return { promise, resolve };
}
+/**
+ * A `connect create` that reached the browser flow, so the run may have
+ * created a connector even when its stdout names none.
+ */
+function browserCreate<T>(result: T | (() => Promise<T>)) {
+ return async (
+ _args: string[],
+ options: { onOutput?: (line: { stream: "stderr"; text: string }) => void },
+ ) => {
+ options.onOutput?.({ stream: "stderr", text: "Opening browser for slack app setup…" });
+ return typeof result === "function" ? await (result as () => Promise<T>)() : result;
+ };
+}
+
function createTestLog(): ChannelSetupLog {
return {
message: vi.fn(),
@@ -63,17 +94,218 @@ function createTestLog(): ChannelSetupLog {
};
}
-/** Mocks the full new-connector path: inventory, completed browser verifier, attachment. */
+const ROOT = "/tmp/eve-agent";
+const PROJECT = "prj_demo";
+const ROUTE = "/eve/v1/slack";
+const LINK = { projectId: PROJECT, orgId: "team_demo" };
+
+/** Provisioning deps over the mocked Vercel CLI, linked to {@link LINK}. */
+function linkedDeps() {
+ return {
+ captureVercel: mockedCaptureVercel,
+ runVercel: mockedRunVercel,
+ runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
+ };
+}
+
+const FAILURE = {
+ ok: false as const,
+ failure: { code: 1, stdout: "", stderr: "", message: "failed" },
+};
+const NOT_FOUND = {
+ ok: false as const,
+ failure: { code: 1, stdout: "", stderr: "Error: Not Found (404)", message: "failed" },
+};
+
+interface ListedConnector {
+ uid: string;
+ id: string;
+ createdAt?: number;
+ projects?: { id: string; name?: string }[];
+}
+
+/** One page of `GET /v1/connect/connectors?include=projects`. */
+function listPage(connectors: readonly ListedConnector[], next?: string) {
+ return {
+ ok: true as const,
+ stdout: JSON.stringify({
+ clients: connectors.map((entry) => ({
+ uid: entry.uid,
+ id: entry.id,
+ type: "slack",
+ createdAt: entry.createdAt ?? 1,
+ includes: {
+ projects: {
+ items: (entry.projects ?? [{ id: PROJECT }]).map((project) => ({
+ projectId: project.id,
+ project,
+ })),
+ },
+ },
+ })),
+ pagination: { next: next ?? null },
+ }),
+ };
+}
+
+const isListCall = (args: readonly string[]): boolean =>
+ args[0] === "api" && (args[1] ?? "").startsWith("/v1/connect/connectors?");
+const isUidLookup = (args: readonly string[]): boolean =>
+ args[0] === "api" && /^\/v1\/connect\/connectors\/slack%2F[^/?]*\?/.test(args[1] ?? "");
+
+/** The reads before a create when nothing exists yet: an empty project list and free UIDs. */
+function emptyInspection(args: readonly string[]) {
+ if (isListCall(args)) return listPage([]);
+ if (isUidLookup(args)) return NOT_FOUND;
+ return undefined;
+}
+
+/** Mocks the full new-connector path: nothing existing, completed browser verifier, routing. */
function mockHappyPathProvision(): void {
mockedRunVercelCaptureStdout.mockResolvedValue({
ok: true,
stdout: createSlackConnectorJson("slack/my-agent"),
});
mockedRunVercel.mockResolvedValue(true);
- mockedCaptureVercel.mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
+ mockedCaptureVercel.mockImplementation(
+ async (args) =>
+ emptyInspection(args) ?? {
+ ok: true,
+ stdout: connectedSlackConnectorJson("slack/my-agent"),
+ },
+ );
+}
+
+interface FakeConnector {
+ uid: string;
+ id: string;
+ createdAt: number;
+ projects: { id: string; name?: string }[];
+ installed: boolean;
+ destinations: SlackTriggerDestination[];
+}
+
+function connector(input: Partial<FakeConnector> & { uid: string }): FakeConnector {
+ return {
+ id: `scl_${input.uid.slice("slack/".length).replaceAll("-", "_")}`,
+ createdAt: 1,
+ projects: [{ id: PROJECT }],
+ installed: true,
+ destinations: [],
+ ...input,
+ };
+}
+
+/**
+ * In-memory Vercel Connect behind the mocked CLI. It applies attach, create,
+ * and trigger-destination replacement the way Connect does, so tests assert
+ * the commands eve issued and the destinations they leave behind.
+ */
+function fakeConnect(initial: FakeConnector[]) {
+ const state = new Map(initial.map((entry) => [entry.uid, structuredClone(entry)]));
+ const commands: string[] = [];
+ const details = (entry: FakeConnector) =>
+ JSON.stringify({
+ id: entry.id,
+ uid: entry.uid,
+ type: "slack",
+ data: entry.installed
+ ? { appId: "A0", slackTeam: { id: "T0", name: "Vercel" } }
+ : { appId: null, slackTeam: null },
+ triggerDestinations: entry.destinations,
+ });
+ const attachProject = (entry: FakeConnector, projectId: string) => {
+ if (!entry.projects.some((project) => project.id === projectId)) {
+ entry.projects.push({ id: projectId });
+ }
+ };
+ const fake = {
+ state,
+ commands,
+ pageSize: Number.POSITIVE_INFINITY,
+ fail: (_args: readonly string[]): boolean => false,
+ patchError: undefined as string | undefined,
+ /** Every command that changes Connect state, in order; detach included. */
+ mutations: () =>
+ commands.filter(
+ (command) =>
+ /^connect (attach|detach|remove|create)\b/.test(command) ||
+ command.includes("--method PATCH"),
+ ),
+ deps: linkedDeps(),
+ };
+ mockedCaptureVercel.mockImplementation(async (args, options) => {
+ commands.push(args.join(" "));
+ if (fake.fail(args)) return FAILURE;
+ if (args[0] !== "api") throw new Error(`Unexpected: ${args.join(" ")}`);
+ const url = new URL(args[1]!, "https://api.vercel.com");
+ if (url.pathname === "/v1/connect/connectors") {
+ const projectId = url.searchParams.get("projectId");
+ const attached = [...state.values()].filter((entry) =>
+ entry.projects.some((project) => project.id === projectId),
+ );
+ const start = Number(url.searchParams.get("cursor") ?? 0);
+ const end = start + fake.pageSize;
+ return listPage(attached.slice(start, end), end < attached.length ? String(end) : undefined);
+ }
+ const match = /^\/v1\/connect\/connectors\/([^/]+)(\/.*)?$/.exec(url.pathname);
+ if (match === null) throw new Error(`Unexpected: ${args.join(" ")}`);
+ const key = decodeURIComponent(match[1]!);
+ const entry = [...state.values()].find(
+ (candidate) => key === candidate.id || key === candidate.uid,
+ );
+ if (entry === undefined) return NOT_FOUND;
+ const suffix = match[2];
+ if (suffix === "/trigger-destinations" && args.includes("PATCH")) {
+ if (fake.patchError !== undefined) {
+ return {
+ ok: true,
+ stdout: JSON.stringify({ error: { code: 403, message: fake.patchError } }),
+ };
+ }
+ entry.destinations = (
+ JSON.parse(options.stdin!) as { destinations: SlackTriggerDestination[] }
+ ).destinations;
+ return { ok: true, stdout: details(entry) };
+ }
+ if (suffix === "/projects") {
+ const projects = entry.projects.map((project) => ({ projectId: project.id, project }));
+ return { ok: true, stdout: JSON.stringify({ projects }) };
+ }
+ return { ok: true, stdout: details(entry) };
+ });
+ mockedRunVercel.mockImplementation(async (args) => {
+ commands.push(args.join(" "));
+ if (fake.fail(args)) return false;
+ if (args[1] === "attach") {
+ const entry = state.get(args[2]!)!;
+ attachProject(entry, PROJECT);
+ // Like the CLI, `--triggers` appends a destination; plain attach only grants token access.
+ if (args.includes("--triggers")) {
+ entry.destinations.push({
+ projectId: PROJECT,
+ path: args[args.indexOf("--trigger-path") + 1],
+ });
+ }
+ return true;
+ }
+ if (args[1] === "remove") return state.delete(args[2]!);
+ if (args[1] === "detach") return true;
+ throw new Error(`Unexpected: ${args.join(" ")}`);
+ });
+ mockedRunVercelCaptureStdout.mockImplementation(async (args) => {
+ commands.push(args.join(" "));
+ const name = args[args.indexOf("--name") + 1]!;
+ const created = connector({
+ uid: `slack/${name}`,
+ createdAt: 100,
+ destinations: [{ projectId: PROJECT, path: "/triggers/slack" }],
+ });
+ state.set(created.uid, created);
+ return { ok: true, stdout: createSlackConnectorJson(created.uid, created.id) };
});
+ return fake;
}
beforeEach(() => {
@@ -97,9 +329,26 @@ describe("parseSlackConnectorDetails", () => {
workspaceUrl: "https://slack.com/app_redirect?app=A0&team=T0",
workspaceName: "Vercel",
},
+ triggerDestinations: [],
});
});
+ it("reads trigger destinations, dropping null branch and environment fields", () => {
+ expect(
+ parseSlackConnectorDetails({
+ id: "scl_1",
+ uid: "slack/my-agent",
+ triggerDestinations: [
+ { projectId: "prj_1", path: "/eve/v1/slack", branch: null, customEnvironmentId: null },
+ { projectId: "prj_1", path: "/x", branch: "preview" },
+ ],
+ })?.triggerDestinations,
+ ).toEqual([
+ { projectId: "prj_1", path: "/eve/v1/slack" },
+ { projectId: "prj_1", path: "/x", branch: "preview" },
+ ]);
+ });
+
it("keeps a valid connector ref while workspace metadata is incomplete", () => {
expect(
parseSlackConnectorDetails({
@@ -107,7 +356,7 @@ describe("parseSlackConnectorDetails", () => {
uid: "slack/my-agent",
data: { appId: null, slackTeam: null },
}),
- ).toEqual({ ref: { id: "scl_1", uid: "slack/my-agent" } });
+ ).toEqual({ ref: { id: "scl_1", uid: "slack/my-agent" }, triggerDestinations: [] });
});
it("rejects malformed connector references", () => {
@@ -133,309 +382,374 @@ describe("parseCreatedSlackConnector", () => {
});
});
+/** Inspects, then provisions the preferred connector or `select`'s choice, as setup does. */
+async function provision(
+ log: ChannelSetupLog,
+ root: string,
+ slug: string,
+ deps: Parameters<typeof provisionSlackbot>[4],
+ options: Parameters<typeof provisionSlackbot>[5] & {
+ channelConnectorUid?: string;
+ select?: (inspection: SlackbotConnectorInspection) => SlackConnectorSelection;
+ } = {},
+) {
+ const { channelConnectorUid, select, ...provisionOptions } = options;
+ const inspection = await inspectSlackbotConnectors(
+ log,
+ root,
+ slug,
+ { signal: options.signal, channelConnectorUid },
+ deps,
+ );
+ const selection = select?.(inspection) ?? inspection.preferred ?? "create";
+ return provisionSlackbot(log, root, inspection, selection, deps, provisionOptions);
+}
+
describe("provisionSlackbot", () => {
- it("adopts an existing project connector instead of creating a duplicate", async () => {
- mockedCaptureVercel
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_existing",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- stdout: connectedSlackConnectorJson("slack/my-agent", "scl_existing"),
- });
- mockedRunVercel.mockResolvedValue(true);
+ it("makes no changes when the channel's connector is already configured", async () => {
+ const connect = fakeConnect([
+ connector({ uid: "slack/my-agent", destinations: [{ projectId: PROJECT, path: ROUTE }] }),
+ ]);
await expect(
- provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
- captureVercel: mockedCaptureVercel,
- runVercel: mockedRunVercel,
- runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ provision(createTestLog(), ROOT, "my-agent", connect.deps, {
+ channelConnectorUid: "slack/my-agent",
}),
- ).resolves.toEqual(
- expect.objectContaining({
- state: "attached",
- connectorUid: "slack/my-agent",
+ ).resolves.toEqual({
+ state: "already-configured",
+ connectorUid: "slack/my-agent",
+ chatUrl: "https://slack.com/app_redirect?app=A0&team=T0",
+ workspaceName: "Vercel",
+ });
+ expect(connect.mutations()).toEqual([]);
+ });
+
+ it.each([
+ ["no destination", []],
+ // An earlier run that detached the project but failed to re-attach it.
+ ["a stale default destination", [{ projectId: PROJECT, path: "/triggers/slack" }]],
+ ])(
+ "attaches an unattached connector no other project uses, with %s",
+ async (_name, destinations) => {
+ const connect = fakeConnect([
+ connector({ uid: "slack/my-agent", projects: [], destinations }),
+ ]);
+
+ await expect(
+ provision(createTestLog(), ROOT, "my-agent", connect.deps),
+ ).resolves.toMatchObject({ state: "attached", connectorUid: "slack/my-agent" });
+ expect(connect.mutations()).toEqual([
+ "connect attach slack/my-agent --yes --scope team_demo",
+ expect.stringContaining("/trigger-destinations?teamId=team_demo --method PATCH"),
+ ]);
+ const routed = connect.state.get("slack/my-agent")!;
+ expect(routed.projects).toEqual([{ id: PROJECT }]);
+ expect(routed.destinations).toEqual([{ projectId: PROJECT, path: ROUTE }]);
+ },
+ );
+
+ it("reads only connectors attached here or named for this agent", async () => {
+ const connect = fakeConnect([
+ connector({ uid: "slack/someone-elses", id: "scl_orphan", projects: [] }),
+ connector({ uid: "slack/prod", id: "scl_prod", projects: [{ id: "prj_prod" }] }),
+ connector({ uid: "slack/attached", id: "scl_attached" }),
+ connector({ uid: "slack/my-agent", id: "scl_named", projects: [] }),
+ ]);
+ const offered: string[] = [];
+
+ await provision(createTestLog(), ROOT, "my-agent", connect.deps, {
+ select: ({ candidates }) => {
+ offered.push(...candidates.map((entry) => entry.uid));
+ return "create";
+ },
+ });
+
+ expect(connect.commands.slice(0, 4)).toEqual([
+ "api /v1/connect/connectors?projectId=prj_demo&type=slack&include=projects&limit=100&teamId=team_demo --scope team_demo",
+ "api /v1/connect/connectors/scl_attached?teamId=team_demo --scope team_demo",
+ "api /v1/connect/connectors/slack%2Fmy-agent?teamId=team_demo --scope team_demo",
+ "api /v1/connect/connectors/scl_named/projects?teamId=team_demo --scope team_demo",
+ ]);
+ expect(connect.commands.join("\n")).not.toMatch(/orphan|someone-elses|prod/);
+ expect(offered).toEqual(["slack/my-agent", "slack/attached"]);
+ });
+
+ it("never offers a connector another project uses", async () => {
+ fakeConnect([
+ connector({
+ uid: "slack/my-agent",
+ projects: [{ id: "prj_prod", name: "chief-prod" }],
+ destinations: [{ projectId: "prj_prod", path: ROUTE }],
}),
+ // Only a destination ties this one to another project.
+ connector({ uid: "slack/routed", projects: [], destinations: [{ projectId: "prj_prod" }] }),
+ ]);
+
+ const inspection = await inspectSlackbotConnectors(
+ createTestLog(),
+ ROOT,
+ "my-agent",
+ { channelConnectorUid: "slack/routed" },
+ linkedDeps(),
);
- expect(mockedRunVercelCaptureStdout).not.toHaveBeenCalled();
+ expect(inspection.candidates).toEqual([]);
+ expect(inspection.preferred).toBeUndefined();
+ expect(inspection.inUse.map(({ uid, otherProjects }) => ({ uid, otherProjects }))).toEqual([
+ { uid: "slack/my-agent", otherProjects: [{ id: "prj_prod", name: "chief-prod" }] },
+ { uid: "slack/routed", otherProjects: [{ id: "prj_prod" }] },
+ ]);
});
- 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]!;
+ it("refuses a connector another project started using after inspection", async () => {
+ const connect = fakeConnect([connector({ uid: "slack/my-agent", projects: [] })]);
+ const log = createTestLog();
+ const result = await provision(log, ROOT, "my-agent", connect.deps, {
+ select: ({ preferred }) => {
+ connect.state.get("slack/my-agent")!.projects.push({ id: "prj_other", name: "other" });
+ return preferred!;
+ },
});
+ expect(result).toEqual({
+ state: "connector-in-use",
+ connectorUid: "slack/my-agent",
+ projects: [{ id: "prj_other", name: "other" }],
+ });
+ expect(connect.mutations()).toEqual([]);
+ });
- 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("fixes a stale destination with one replacement that keeps other entries", async () => {
+ const preview = { projectId: PROJECT, branch: "preview", path: "/custom" };
+ const connect = fakeConnect([
+ connector({
+ uid: "slack/my-agent",
+ projects: [{ id: PROJECT }, { id: "prj_prod" }],
+ destinations: [
+ { projectId: "prj_prod", path: ROUTE },
+ { projectId: PROJECT, path: "/triggers/slack" },
+ preview,
+ ],
+ }),
+ ]);
+
+ await expect(provision(createTestLog(), ROOT, "my-agent", connect.deps)).resolves.toMatchObject(
+ { state: "attached", connectorUid: "slack/my-agent" },
+ );
+ expect(connect.mutations()).toEqual([
+ "api /v1/connect/connectors/scl_my_agent/trigger-destinations?teamId=team_demo --method PATCH --input - --scope team_demo",
+ ]);
+ expect(connect.state.get("slack/my-agent")?.destinations).toEqual([
+ { projectId: "prj_prod", path: ROUTE },
+ preview,
+ { projectId: PROJECT, path: ROUTE },
+ ]);
});
- 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);
+ it("adds a missing destination without re-attaching an attached project", async () => {
+ const connect = fakeConnect([connector({ uid: "slack/my-agent", destinations: [] })]);
- 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();
+ await provision(createTestLog(), ROOT, "my-agent", connect.deps);
+
+ expect(connect.mutations()).toEqual([
+ expect.stringContaining("/trigger-destinations?teamId=team_demo --method PATCH"),
+ ]);
+ expect(connect.state.get("slack/my-agent")?.destinations).toEqual([
+ { projectId: PROJECT, path: ROUTE },
+ ]);
});
- it("recognizes Slack workspace metadata from the connector detail payload", async () => {
- mockedCaptureVercel
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_existing",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({
- id: "scl_existing",
- uid: "slack/my-agent",
- data: {
- appId: "A0",
- slackTeam: { id: "T0", name: "Vercel" },
- },
- }),
- });
- mockedRunVercel.mockResolvedValue(true);
+ it("replaces a new connector's default destination with the eve route", async () => {
+ const connect = fakeConnect([]);
- await expect(
- provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
- captureVercel: mockedCaptureVercel,
- runVercel: mockedRunVercel,
- runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
- }),
- ).resolves.toEqual({
+ await expect(provision(createTestLog(), ROOT, "my-agent", connect.deps)).resolves.toEqual({
state: "attached",
connectorUid: "slack/my-agent",
chatUrl: "https://slack.com/app_redirect?app=A0&team=T0",
workspaceName: "Vercel",
});
- expect(mockedCaptureVercel).toHaveBeenNthCalledWith(
- 2,
- ["api", "/v1/connect/connectors/scl_existing?teamId=team_demo", "--scope", "team_demo"],
- expect.objectContaining({ cwd: "/tmp/eve-agent" }),
+ expect(connect.commands[0]).toBe(
+ "api /v1/connect/connectors?projectId=prj_demo&type=slack&include=projects&limit=100&teamId=team_demo --scope team_demo",
);
+ expect(connect.mutations()).toEqual([
+ "connect create slack --triggers --name my-agent -F json",
+ expect.stringContaining("/trigger-destinations?teamId=team_demo --method PATCH"),
+ ]);
+ expect(connect.state.get("slack/my-agent")?.destinations).toEqual([
+ { projectId: PROJECT, path: ROUTE },
+ ]);
});
- it("fails closed when creation succeeds without an exact connector ref", async () => {
- mockedRunVercelCaptureStdout.mockResolvedValue({ ok: true, stdout: "" });
- mockedCaptureVercel.mockResolvedValue({ ok: true, stdout: JSON.stringify({ clients: [] }) });
-
- const result = await provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent");
+ it("reports a full connector without changing anything", async () => {
+ const destinations = [
+ { projectId: "prj_a", path: ROUTE },
+ { projectId: "prj_b", path: ROUTE },
+ { projectId: "prj_c", path: ROUTE },
+ ];
+ const log = createTestLog();
+ const connect = fakeConnect([
+ connector({
+ uid: "slack/my-agent",
+ projects: [{ id: PROJECT }, { id: "prj_a", name: "alpha" }],
+ destinations,
+ }),
+ ]);
- expect(result).toEqual({
- state: "cleanup-failed",
- connectorUids: [],
+ await expect(provision(log, ROOT, "my-agent", connect.deps)).resolves.toEqual({
+ state: "trigger-limit-reached",
+ connectorUid: "slack/my-agent",
+ destinations,
});
+ expect(connect.mutations()).toEqual([]);
+ expect(log.warning).toHaveBeenCalledWith(
+ expect.stringContaining("alpha (production) /eve/v1/slack"),
+ );
});
- it("preserves creation success when trigger attachment fails", async () => {
- mockedCaptureVercel
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
- })
- .mockResolvedValue({
- ok: true,
- stdout: connectedSlackConnectorJson("slack/my-agent", "scl_my_agent", "Vercel"),
- });
- mockedRunVercelCaptureStdout.mockResolvedValue({
- ok: true,
- stdout: createSlackConnectorJson("slack/my-agent"),
- });
- mockedRunVercel.mockImplementation(async (args) => {
- const command = args.join(" ");
- if (command.startsWith("connect detach slack/my-agent")) return true;
- if (command.startsWith("connect attach slack/my-agent")) return false;
- throw new Error(`Unexpected vercel command: ${command}`);
+ it("follows every page of the project's connector list", async () => {
+ const connect = fakeConnect([
+ connector({ uid: "slack/first", id: "scl_first", createdAt: 1 }),
+ connector({ uid: "slack/my-agent", destinations: [{ projectId: PROJECT, path: ROUTE }] }),
+ ]);
+ connect.pageSize = 1;
+
+ await expect(provision(createTestLog(), ROOT, "my-agent", connect.deps)).resolves.toMatchObject(
+ { state: "already-configured", connectorUid: "slack/my-agent" },
+ );
+ expect(connect.commands).toContain(
+ "api /v1/connect/connectors?projectId=prj_demo&type=slack&include=projects&limit=100&cursor=1&teamId=team_demo --scope team_demo",
+ );
+ });
+
+ it("creates a new connector when the caller requests one", async () => {
+ const connect = fakeConnect([connector({ uid: "slack/other", id: "scl_other" })]);
+
+ await expect(
+ provision(createTestLog(), ROOT, "my-agent", connect.deps, {
+ select: () => "create",
+ }),
+ ).resolves.toMatchObject({ state: "attached", connectorUid: "slack/my-agent" });
+ expect(connect.mutations()[0]).toBe("connect create slack --triggers --name my-agent -F json");
+ });
+
+ it.each([
+ ["the project's connector list", isListCall],
+ ["a connector's details", (args: readonly string[]) => args[0] === "api"],
+ ])("never creates when %s cannot be read", async (_name, fails) => {
+ const connect = fakeConnect([connector({ uid: "slack/my-agent" })]);
+ connect.fail = fails;
+
+ await expect(provision(createTestLog(), ROOT, "my-agent", connect.deps)).rejects.toThrow(
+ "Could not inspect existing Slack connectors",
+ );
+ expect(connect.mutations()).toEqual([]);
+ });
+
+ it("never creates without a linked project to scope connectors", async () => {
+ const connect = fakeConnect([]);
+
+ await expect(
+ provision(createTestLog(), ROOT, "my-agent", {
+ ...connect.deps,
+ readProjectLink: async () => undefined,
+ }),
+ ).rejects.toThrow("needs a linked Vercel project");
+ expect(connect.commands).toEqual([]);
+ });
+
+ it("keeps a created connector when routing fails", async () => {
+ const connect = fakeConnect([]);
+ connect.fail = (args) => args.includes("PATCH");
+
+ await expect(provision(createTestLog(), ROOT, "my-agent", connect.deps)).resolves.toEqual({
+ state: "attach-failed",
+ connectorUid: "slack/my-agent",
});
+ expect(connect.state.has("slack/my-agent")).toBe(true);
+ });
- const result = await provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent");
+ it("reports the API reason when routing a connector fails", async () => {
+ const connect = fakeConnect([]);
+ connect.patchError = "You do not have access to update trigger destinations.";
+ const log = createTestLog();
- expect(result).toEqual({
+ await expect(provision(log, ROOT, "my-agent", connect.deps)).resolves.toEqual({
state: "attach-failed",
connectorUid: "slack/my-agent",
});
+ expect(connect.state.get("slack/my-agent")?.destinations).toEqual([
+ { projectId: PROJECT, path: "/triggers/slack" },
+ ]);
+ expect(log.warning).toHaveBeenCalledWith(
+ expect.stringContaining(
+ "Vercel API request failed: You do not have access to update trigger destinations.",
+ ),
+ );
});
- it("does not attach when the existing trigger destination cannot be detached", async () => {
- mockedCaptureVercel
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
- })
- .mockResolvedValue({
- ok: true,
- stdout: connectedSlackConnectorJson("slack/my-agent", "scl_my_agent", "Vercel"),
- });
+ it("reports Vercel's error when create fails before the browser flow starts", async () => {
+ const connect = fakeConnect([]);
mockedRunVercelCaptureStdout.mockResolvedValue({
- ok: true,
- stdout: createSlackConnectorJson("slack/my-agent"),
+ ok: false,
+ stdout: "",
+ stderr: "Vercel CLI 62.7.0\nSetting up…\nError: Connect is not available for this team.\n",
});
- mockedRunVercel.mockImplementation(async (args) => {
- const command = args.join(" ");
- if (command.startsWith("connect detach slack/my-agent")) return false;
- throw new Error(`Unexpected vercel command: ${command}`);
+ const log = createTestLog();
+
+ await expect(provision(log, ROOT, "my-agent", connect.deps)).resolves.toEqual({
+ state: "create-failed",
+ detail: "Error: Connect is not available for this team.",
});
+ // Nothing could exist, so there is no browser warning and no ownership lookup.
+ expect(log.warning).not.toHaveBeenCalled();
+ // One lookup during discovery and one to reserve the name at create time.
+ expect(connect.commands.filter((command) => command.includes("slack%2F"))).toHaveLength(2);
+ });
- const result = await provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent");
+ it("fails closed when create fails without proving it stopped before the browser flow", async () => {
+ const connect = fakeConnect([]);
+ // No recognized browser line and no CLI error: the browser may still create one.
+ mockedRunVercelCaptureStdout.mockResolvedValue({ ok: false, stdout: "", stderr: "" });
+ const log = createTestLog();
- expect(result).toEqual({
- state: "detach-failed",
- connectorUid: "slack/my-agent",
+ await expect(provision(log, ROOT, "my-agent", connect.deps)).resolves.toEqual({
+ state: "cleanup-failed",
+ connectorUids: [],
});
- expect(mockedRunVercel).toHaveBeenCalledTimes(1);
+ expect(log.warning).toHaveBeenCalledWith(
+ expect.stringContaining("couldn't confirm the Slack request in your browser was cancelled"),
+ );
});
- it("resolves the UID from create JSON, then attaches the eve trigger route", async () => {
- mockHappyPathProvision();
+ it("names a new connector around one another project already uses", async () => {
+ const connect = fakeConnect([
+ connector({ uid: "slack/my-agent", projects: [{ id: "prj_other", name: "other" }] }),
+ connector({ uid: "slack/my-agent-2", projects: [{ id: "prj_more" }] }),
+ ]);
+ const log = createTestLog();
- await expect(provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent")).resolves.toEqual(
- {
- state: "attached",
- connectorUid: "slack/my-agent",
- },
- );
+ const result = await provision(log, ROOT, "my-agent", connect.deps, {
+ select: () => "create",
+ });
- // Created with --triggers, the slug name, and JSON output for deterministic UID capture.
- expect(mockedRunVercelCaptureStdout).toHaveBeenCalledWith(
- ["connect", "create", "slack", "--triggers", "--name", "my-agent", "-F", "json"],
- expect.objectContaining({ cwd: "/tmp/eve-agent", nonInteractive: true }),
- );
- expect(mockedCaptureVercel).toHaveBeenCalledWith(
- ["connect", "list", "-F", "json", "--all-projects"],
- expect.objectContaining({ cwd: "/tmp/eve-agent" }),
+ expect(result).toMatchObject({ state: "attached", connectorUid: "slack/my-agent-3" });
+ expect(connect.mutations()).toContainEqual(
+ expect.stringContaining("connect create slack --triggers --name my-agent-3"),
);
- expect(mockedCaptureVercel).toHaveBeenCalledTimes(1);
- expect(mockedRunVercel).toHaveBeenNthCalledWith(
- 1,
- ["connect", "detach", "slack/my-agent", "--yes"],
- expect.objectContaining({ cwd: "/tmp/eve-agent", nonInteractive: true }),
- );
- expect(mockedRunVercel).toHaveBeenNthCalledWith(
- 2,
- [
- "connect",
- "attach",
- "slack/my-agent",
- "--triggers",
- "--trigger-path",
- "/eve/v1/slack",
- "--yes",
- ],
- expect.objectContaining({ cwd: "/tmp/eve-agent", nonInteractive: true }),
+ expect(log.info).toHaveBeenCalledWith(
+ "`slack/my-agent` is already used by another project (other), so eve will create `slack/my-agent-3` for this project.",
);
});
+ it("fails closed when creation succeeds without an exact connector ref", async () => {
+ const connect = fakeConnect([]);
+ mockedRunVercelCaptureStdout.mockImplementation(browserCreate({ ok: true, stdout: "" }));
+
+ await expect(provision(createTestLog(), ROOT, "my-agent", connect.deps)).resolves.toEqual({
+ state: "cleanup-failed",
+ connectorUids: [],
+ });
+ });
+
it("finishes a parked create when connector details prove the workspace connection", async () => {
const createClose = deferred<{ ok: boolean; stdout: string }>();
const workspaceLookup = deferred<{ ok: true; stdout: string }>();
@@ -457,9 +771,9 @@ describe("provisionSlackbot", () => {
mockedRunVercel.mockResolvedValue(true);
let connectorLookups = 0;
mockedCaptureVercel.mockImplementation(async (args) => {
- if (args[0] === "connect") {
- return { ok: true, stdout: JSON.stringify({ connectors: [] }) };
- }
+ const inspection = emptyInspection(args);
+ if (inspection !== undefined) return inspection;
+ if (args.includes("PATCH")) return { ok: true, stdout: "{}" };
if (
args[1] === "/v1/connect/connectors/scl_partial?teamId=team_demo" &&
args[2] === "--scope" &&
@@ -496,7 +810,7 @@ describe("provisionSlackbot", () => {
},
};
- const provisioning = provisionSlackbot(
+ const provisioning = provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -504,7 +818,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
delay: async () => {},
},
{ awaitChoice },
@@ -532,7 +846,7 @@ describe("provisionSlackbot", () => {
);
expect(close).toHaveBeenCalledOnce();
expect(phases).toEqual([
- { message: "Checking for an existing Slackbot...", stopped: true },
+ { message: "Checking existing Slack connectors...", stopped: true },
{ message: "Waiting for Slack setup to finish...", stopped: true },
{ message: "Configuring Slack event delivery for this agent...", stopped: true },
]);
@@ -556,9 +870,9 @@ describe("provisionSlackbot", () => {
mockedRunVercel.mockResolvedValue(true);
let connectorLookups = 0;
mockedCaptureVercel.mockImplementation(async (args) => {
- if (args[0] === "connect") {
- return { ok: true, stdout: JSON.stringify({ connectors: [] }) };
- }
+ const inspection = emptyInspection(args);
+ if (inspection !== undefined) return inspection;
+ if (args.includes("PATCH")) return { ok: true, stdout: "{}" };
if (
args[1] === "/v1/connect/connectors/scl_partial?teamId=team_demo" &&
args[2] === "--scope" &&
@@ -589,11 +903,11 @@ describe("provisionSlackbot", () => {
});
let now = 0;
- const provisioning = provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
+ const provisioning = provision(createTestLog(), "/tmp/eve-agent", "my-agent", {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
delay: async (ms) => {
now += ms;
},
@@ -601,7 +915,8 @@ describe("provisionSlackbot", () => {
});
await expect(provisioning).resolves.toMatchObject({ state: "attached" });
- expect(connectorLookups).toBe(3);
+ // Three lookups until the workspace connects, then one fresh routing read.
+ expect(connectorLookups).toBe(4);
expect(createSignal?.aborted).toBe(true);
});
@@ -616,23 +931,23 @@ describe("provisionSlackbot", () => {
});
mockedRunVercel.mockResolvedValue(true);
mockedCaptureVercel.mockImplementation(async (args) => {
- if (args[0] === "connect") {
- return { ok: true, stdout: JSON.stringify({ connectors: [] }) };
- }
- if (args[1] === "/v1/connect/connectors/scl_partial") {
+ const inspection = emptyInspection(args);
+ if (inspection !== undefined) return inspection;
+ if (args[1] === "/v1/connect/connectors/scl_partial?teamId=team_demo") {
return connectorLookup.promise;
}
throw new Error(`Unexpected vercel command: ${args.join(" ")}`);
});
- const provisioning = provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
+ const provisioning = provision(createTestLog(), "/tmp/eve-agent", "my-agent", {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
});
await vi.waitFor(() =>
expect(mockedCaptureVercel).toHaveBeenCalledWith(
- ["api", "/v1/connect/connectors/scl_partial"],
+ ["api", "/v1/connect/connectors/scl_partial?teamId=team_demo", "--scope", "team_demo"],
expect.anything(),
),
);
@@ -665,10 +980,10 @@ describe("provisionSlackbot", () => {
},
};
- await provisionSlackbot(log, "/tmp/eve-agent", "my-agent");
+ await provision(log, ROOT, "my-agent", linkedDeps());
expect(phases).toEqual([
- { message: "Checking for an existing Slackbot...", stopped: true },
+ { message: "Checking existing Slack connectors...", stopped: true },
{ message: "Waiting for Slack setup to finish...", stopped: true },
{ message: "Configuring Slack event delivery for this agent...", stopped: true },
]);
@@ -681,10 +996,10 @@ describe("provisionSlackbot", () => {
mockHappyPathProvision();
const log = createTestLog();
- await provisionSlackbot(log, "/tmp/eve-agent", "my-agent");
+ await provision(log, ROOT, "my-agent", linkedDeps());
expect(vi.mocked(log.message).mock.calls.map(([text]) => text)).toEqual([
- "Checking for an existing Slackbot...",
+ "Checking existing Slack connectors...",
"Waiting for Slack setup to finish...",
"Configuring Slack event delivery for this agent...",
]);
@@ -729,29 +1044,13 @@ describe("provisionSlackbot", () => {
mockedRunVercel.mockResolvedValue(true);
// The existing-check sees nothing; cancellation removes the UID returned by
// the create command.
- let listCalls = 0;
- mockedCaptureVercel.mockImplementation(async (args) => {
- if (args[0] === "api") {
- return { ok: true, stdout: createSlackConnectorJson("slack/my-agent") };
- }
- listCalls += 1;
- const connectors =
- listCalls === 1
- ? []
- : [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- createdAt: 1,
- projects: [],
- },
- ];
- return { ok: true, stdout: JSON.stringify({ connectors }) };
- });
+ mockedCaptureVercel.mockImplementation(
+ async (args) =>
+ emptyInspection(args) ?? { ok: true, stdout: createSlackConnectorJson("slack/my-agent") },
+ );
const log = choiceLog(["cancel"]);
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -759,6 +1058,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -772,19 +1072,18 @@ describe("provisionSlackbot", () => {
expect(log.success).not.toHaveBeenCalled();
});
- it("fails closed when remove fails even if one inventory read omits the connector", async () => {
+ it("fails closed when removing the created connector fails", async () => {
mockedRunVercelCaptureStdout.mockResolvedValue({
ok: true,
stdout: createSlackConnectorJson("slack/my-agent"),
});
mockedRunVercel.mockImplementation(async (args) => args[1] !== "remove");
- mockedCaptureVercel.mockResolvedValue({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
- });
+ mockedCaptureVercel.mockImplementation(
+ async (args) => emptyInspection(args) ?? { ok: true, stdout: "{}" },
+ );
const log = choiceLog(["cancel"]);
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -792,6 +1091,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -810,14 +1110,13 @@ describe("provisionSlackbot", () => {
it("cleans up before propagating an outer abort", async () => {
const create = deferred<{ ok: boolean; stdout: string }>();
const controller = new AbortController();
- mockedRunVercelCaptureStdout.mockImplementationOnce(() => create.promise);
+ mockedRunVercelCaptureStdout.mockImplementationOnce(browserCreate(() => create.promise));
mockedRunVercel.mockResolvedValue(true);
- mockedCaptureVercel.mockResolvedValue({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
- });
+ mockedCaptureVercel.mockImplementation(
+ async (args) => emptyInspection(args) ?? { ok: true, stdout: "{}" },
+ );
- const provisioning = provisionSlackbot(
+ const provisioning = provision(
createTestLog(),
"/tmp/eve-agent",
"my-agent",
@@ -825,6 +1124,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
},
{ signal: controller.signal },
);
@@ -847,13 +1147,12 @@ describe("provisionSlackbot", () => {
const create = deferred<{ ok: boolean; stdout: string }>();
const controller = new AbortController();
const log = createTestLog();
- mockedRunVercelCaptureStdout.mockImplementationOnce(() => create.promise);
- mockedCaptureVercel.mockResolvedValue({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
- });
+ mockedRunVercelCaptureStdout.mockImplementationOnce(browserCreate(() => create.promise));
+ mockedCaptureVercel.mockImplementation(
+ async (args) => emptyInspection(args) ?? { ok: true, stdout: "{}" },
+ );
- const provisioning = provisionSlackbot(
+ const provisioning = provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -861,6 +1160,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
},
{ signal: controller.signal },
);
@@ -875,45 +1175,19 @@ describe("provisionSlackbot", () => {
);
});
- it("fails closed when create returns no exact connector ref and the inventory changed", async () => {
- mockedRunVercelCaptureStdout.mockResolvedValue({ ok: true, stdout: "" });
+ it("reports the requested UID when create returns no exact ref and that UID now exists", async () => {
+ mockedRunVercelCaptureStdout.mockImplementation(browserCreate({ ok: true, stdout: "" }));
mockedRunVercel.mockResolvedValue(true);
- let listCalls = 0;
- mockedCaptureVercel.mockImplementation(async () => {
- listCalls += 1;
- return {
- ok: true,
- stdout: JSON.stringify({
- connectors:
- listCalls === 1
- ? [
- {
- uid: "slack/my-agent-legacy",
- id: "scl_legacy",
- type: "slack",
- projects: [],
- },
- ]
- : [
- {
- uid: "slack/my-agent-legacy",
- id: "scl_legacy",
- type: "slack",
- projects: [],
- },
- {
- uid: "slack/my-agent-2",
- id: "scl_new",
- type: "slack",
- projects: [],
- },
- ],
- }),
- };
+ mockedCaptureVercel.mockImplementation(async (args) => {
+ const created = mockedRunVercelCaptureStdout.mock.calls.length > 0;
+ if (!created) return emptyInspection(args)!;
+ return isUidLookup(args)
+ ? { ok: true, stdout: createSlackConnectorJson("slack/my-agent", "scl_new") }
+ : NOT_FOUND;
});
const log = choiceLog(["cancel"]);
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -921,7 +1195,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -929,28 +1203,20 @@ describe("provisionSlackbot", () => {
expect(result).toEqual({
state: "cleanup-failed",
- connectorUids: ["slack/my-agent-2"],
+ connectorUids: ["slack/my-agent"],
});
- expect(mockedRunVercel).not.toHaveBeenCalledWith(
- ["connect", "remove", "slack/my-agent-2", "--disconnect-all", "--yes"],
- expect.anything(),
- );
- expect(mockedRunVercel).not.toHaveBeenCalledWith(
- ["connect", "remove", "slack/my-agent-legacy", "--disconnect-all", "--yes"],
- expect.anything(),
- );
+ expect(mockedRunVercel).not.toHaveBeenCalled();
});
it("does not retry an aborted request when no exact connector ref was returned", async () => {
- mockedRunVercelCaptureStdout.mockResolvedValue({ ok: true, stdout: "" });
+ mockedRunVercelCaptureStdout.mockImplementation(browserCreate({ ok: true, stdout: "" }));
mockedRunVercel.mockResolvedValue(true);
- mockedCaptureVercel.mockResolvedValue({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
- });
+ mockedCaptureVercel.mockImplementation(
+ async (args) => emptyInspection(args) ?? { ok: true, stdout: "{}" },
+ );
const log = choiceLog(["cancel"]);
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -958,6 +1224,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -978,20 +1245,19 @@ describe("provisionSlackbot", () => {
mockedRunVercel.mockResolvedValue(true);
// The install only lands on the second attempt (after one create + retry).
mockedCaptureVercel.mockImplementation(async (args) => {
- if (args[0] === "api") {
- const installed = mockedRunVercelCaptureStdout.mock.calls.length >= 2;
- return {
- ok: true,
- stdout: installed
- ? connectedSlackConnectorJson("slack/my-agent", "scl_my_agent", "Vercel")
- : createSlackConnectorJson("slack/my-agent"),
- };
- }
- return { ok: true, stdout: JSON.stringify({ connectors: [] }) };
+ const inspection = emptyInspection(args);
+ if (inspection !== undefined) return inspection;
+ const installed = mockedRunVercelCaptureStdout.mock.calls.length >= 2;
+ return {
+ ok: true,
+ stdout: installed
+ ? connectedSlackConnectorJson("slack/my-agent", "scl_my_agent", "Vercel")
+ : createSlackConnectorJson("slack/my-agent"),
+ };
});
const log = choiceLog(["retry"]);
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -999,6 +1265,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -1022,17 +1289,16 @@ describe("provisionSlackbot", () => {
stdout: createSlackConnectorJson("slack/my-agent-2", "scl_second"),
});
mockedRunVercel.mockResolvedValue(true);
- mockedCaptureVercel.mockImplementation(async (args) =>
- args[0] === "api"
- ? {
- ok: true,
- stdout: connectedSlackConnectorJson("slack/my-agent-2", "scl_second", "Vercel"),
- }
- : { ok: true, stdout: JSON.stringify({ connectors: [] }) },
+ mockedCaptureVercel.mockImplementation(
+ async (args) =>
+ emptyInspection(args) ?? {
+ ok: true,
+ stdout: connectedSlackConnectorJson("slack/my-agent-2", "scl_second", "Vercel"),
+ },
);
const log = choiceLog(["retry", "never"]);
- const provisioning = provisionSlackbot(
+ const provisioning = provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -1040,6 +1306,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -1070,29 +1337,13 @@ describe("provisionSlackbot", () => {
stdout: createSlackConnectorJson("slack/my-agent"),
});
mockedRunVercel.mockImplementation(async (args) => args[1] !== "remove");
- let listCalls = 0;
- mockedCaptureVercel.mockImplementation(async () => {
- listCalls += 1;
- return {
- ok: true,
- stdout: JSON.stringify({
- connectors:
- listCalls === 1
- ? []
- : [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- projects: [],
- },
- ],
- }),
- };
- });
+ mockedCaptureVercel.mockImplementation(
+ async (args) =>
+ emptyInspection(args) ?? { ok: true, stdout: createSlackConnectorJson("slack/my-agent") },
+ );
const log = choiceLog(["retry", "cancel"]);
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -1100,6 +1351,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -1112,30 +1364,55 @@ describe("provisionSlackbot", () => {
expect(mockedRunVercelCaptureStdout).toHaveBeenCalledTimes(1);
});
- it("blocks recovery of a pre-existing connector without a workspace connection", async () => {
+ it("opens the install page for an existing connector and finishes once it is installed", async () => {
+ const connect = fakeConnect([connector({ uid: "slack/my-agent", installed: false })]);
+ mockedOpenUrl.mockImplementation(() => {
+ connect.state.get("slack/my-agent")!.installed = true;
+ });
+
+ const result = await provision(createTestLog(), ROOT, "my-agent", {
+ ...connect.deps,
+ ...makeClock(),
+ });
+
+ expect(result).toMatchObject({ state: "attached", connectorUid: "slack/my-agent" });
+ expect(mockedOpenUrl).toHaveBeenCalledOnce();
+ expect(mockedOpenUrl.mock.calls[0]![0]).toMatch(INSTALL_URL);
+ expect(connect.mutations()).not.toContainEqual(
+ expect.stringMatching(/^connect (create|remove)/),
+ );
+ });
+
+ it("opens a fresh install page when the user asks to try again", async () => {
+ fakeConnect([connector({ uid: "slack/my-agent", installed: false })]);
+ const log = choiceLog(["retry", "cancel"]);
+
+ const result = await provision(
+ log,
+ ROOT,
+ "my-agent",
+ { ...linkedDeps(), ...makeClock() },
+ { awaitChoice: log.awaitChoice },
+ );
+
+ expect(result).toEqual({ state: "existing-not-installed", connectorUid: "slack/my-agent" });
+ const urls = mockedOpenUrl.mock.calls.map(([url]) => url);
+ expect(urls).toHaveLength(2);
+ for (const url of urls) expect(url).toMatch(INSTALL_URL);
+ expect(urls[0]).not.toBe(urls[1]);
+ });
+
+ it("reports an existing connector that never installs without removing it", async () => {
mockedRunVercel.mockResolvedValue(true);
mockedCaptureVercel.mockImplementation(async (args) => {
- if (args[0] === "api") {
+ if (!isListCall(args)) {
return { ok: true, stdout: createSlackConnectorJson("slack/my-agent") };
}
- return {
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
- };
+ return listPage([{ uid: "slack/my-agent", id: "scl_my_agent" }]);
});
const log = choiceLog(["never"]);
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -1143,7 +1420,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -1154,9 +1431,12 @@ describe("provisionSlackbot", () => {
connectorUid: "slack/my-agent",
});
expect(log.awaitChoice).toHaveBeenCalledWith({
- status: "Waiting for the existing Slack workspace connection...",
- context: "Complete the original setup in the browser",
- actions: [{ value: "cancel", label: "Stop waiting" }],
+ status: "Waiting for the Slack workspace install...",
+ context: "Install the Slack app in your browser, then wait while eve verifies it",
+ actions: [
+ { value: "retry", label: "Did your browser not open? Try again" },
+ { value: "cancel", label: "Stop waiting" },
+ ],
});
expect(mockedRunVercelCaptureStdout).not.toHaveBeenCalled();
expect(mockedRunVercel).not.toHaveBeenCalledWith(
@@ -1164,7 +1444,7 @@ describe("provisionSlackbot", () => {
expect.anything(),
);
expect(log.warning).toHaveBeenCalledWith(
- "The existing Slack connector `slack/my-agent` is not connected to a Slack workspace. eve did not remove it because this run did not create it. If its original browser request is still open, complete it; otherwise run `vercel connect remove slack/my-agent --disconnect-all --yes` before trying again.",
+ 'The Slack connector `slack/my-agent` is not installed in a Slack workspace yet. Re-run `eve add channel/slack` to open its install page again, or choose "Create a new Slack app" instead.',
);
});
@@ -1172,27 +1452,21 @@ describe("provisionSlackbot", () => {
const workspace = deferred<{ ok: true; stdout: string }>();
const controller = new AbortController();
mockedRunVercel.mockResolvedValue(true);
+ let detailCalls = 0;
mockedCaptureVercel.mockImplementation(async (args) => {
- // Park the workspace lookup so the wait is in-flight when we abort.
- if (args[0] === "api") return workspace.promise;
- return {
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
- };
+ // The snapshot sees no workspace; park the next lookup so the wait is
+ // in flight when we abort.
+ if (!isListCall(args)) {
+ detailCalls += 1;
+ return detailCalls === 1
+ ? { ok: true, stdout: createSlackConnectorJson("slack/my-agent") }
+ : workspace.promise;
+ }
+ return listPage([{ uid: "slack/my-agent", id: "scl_my_agent" }]);
});
const log = choiceLog(["never"]);
- const provisioning = provisionSlackbot(
+ const provisioning = provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -1200,17 +1474,12 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice, signal: controller.signal },
);
- await vi.waitFor(() =>
- expect(mockedCaptureVercel).toHaveBeenCalledWith(
- ["api", "/v1/connect/connectors/scl_my_agent?teamId=team_demo", "--scope", "team_demo"],
- expect.anything(),
- ),
- );
+ await vi.waitFor(() => expect(detailCalls).toBe(2));
controller.abort();
workspace.resolve({ ok: true, stdout: createSlackConnectorJson("slack/my-agent") });
@@ -1219,26 +1488,18 @@ describe("provisionSlackbot", () => {
// claims the connector is disconnected (it never finished checking).
await expect(provisioning).rejects.toMatchObject({ name: "AbortError" });
expect(log.warning).not.toHaveBeenCalledWith(
- expect.stringContaining("is not connected to a Slack workspace"),
+ expect.stringContaining("is not installed in a Slack workspace"),
);
});
it("attaches and dismisses the prompt when the browser verifier finishes first", async () => {
- mockedRunVercelCaptureStdout.mockResolvedValue({
- ok: true,
- stdout: createSlackConnectorJson("slack/my-agent"),
- });
- mockedRunVercel.mockResolvedValue(true);
- mockedCaptureVercel.mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({ connectors: [] }),
- });
+ mockHappyPathProvision();
const close = vi.fn();
const log: ChoiceLog = Object.assign(createTestLog(), {
awaitChoice: vi.fn(() => ({ choice: new Promise<string | undefined>(() => {}), close })),
});
- const result = await provisionSlackbot(
+ const result = await provision(
log,
"/tmp/eve-agent",
"my-agent",
@@ -1246,6 +1507,7 @@ describe("provisionSlackbot", () => {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
+ readProjectLink: async () => LINK,
...makeClock(),
},
{ awaitChoice: log.awaitChoice },
@@ -1263,20 +1525,7 @@ describe("provisionSlackbot", () => {
it("keeps polling an existing connector until workspace metadata appears", async () => {
mockedRunVercel.mockResolvedValue(true);
mockedCaptureVercel
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
- })
+ .mockResolvedValueOnce(listPage([{ uid: "slack/my-agent", id: "scl_my_agent" }]))
.mockResolvedValueOnce({
ok: true,
stdout: createSlackConnectorJson("slack/my-agent"),
@@ -1285,16 +1534,17 @@ describe("provisionSlackbot", () => {
ok: true,
stdout: createSlackConnectorJson("slack/my-agent"),
})
- .mockResolvedValue({
- ok: true,
- stdout: connectedSlackConnectorJson("slack/my-agent"),
- });
+ .mockImplementation(async (args) =>
+ args[1]?.includes("/projects?")
+ ? { ok: true, stdout: JSON.stringify({ projects: [{ projectId: PROJECT }] }) }
+ : { ok: true, stdout: connectedSlackConnectorJson("slack/my-agent") },
+ );
- const result = await provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
+ const result = await provision(createTestLog(), "/tmp/eve-agent", "my-agent", {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
delay: async () => {},
});
@@ -1302,26 +1552,19 @@ describe("provisionSlackbot", () => {
state: "attached",
chatUrl: "https://slack.com/app_redirect?app=A0&team=T0",
});
- expect(mockedCaptureVercel).toHaveBeenCalledTimes(4);
+ // Inventory, snapshot, two polls, fresh details and projects, then the replacement.
+ expect(mockedCaptureVercel).toHaveBeenCalledTimes(7);
+ expect(mockedCaptureVercel.mock.calls.at(-1)?.[0]).toContain("PATCH");
expect(mockedRunVercelCaptureStdout).not.toHaveBeenCalled();
});
it("reports an existing connector detail lookup failure instead of calling it pending", async () => {
mockedRunVercel.mockResolvedValue(true);
mockedCaptureVercel
+ .mockResolvedValueOnce(listPage([{ uid: "slack/my-agent", id: "scl_my_agent" }]))
.mockResolvedValueOnce({
ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
+ stdout: createSlackConnectorJson("slack/my-agent"),
})
.mockResolvedValueOnce({
ok: false,
@@ -1333,11 +1576,11 @@ describe("provisionSlackbot", () => {
},
});
- const result = await provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
+ const result = await provision(createTestLog(), "/tmp/eve-agent", "my-agent", {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
delay: async () => {},
});
@@ -1345,117 +1588,37 @@ describe("provisionSlackbot", () => {
state: "installation-check-failed",
connectorUid: "slack/my-agent",
});
- expect(mockedCaptureVercel).toHaveBeenCalledTimes(2);
+ expect(mockedCaptureVercel).toHaveBeenCalledTimes(3);
});
- it("reports a malformed connector detail response instead of calling it pending", async () => {
- mockedRunVercel.mockResolvedValue(true);
- mockedCaptureVercel
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- stdout: JSON.stringify({ uid: "slack/my-agent" }),
- });
-
- const result = await provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
- captureVercel: mockedCaptureVercel,
- runVercel: mockedRunVercel,
- runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
- });
-
- expect(result.state).toBe("installation-check-failed");
- expect(mockedCaptureVercel).toHaveBeenCalledTimes(2);
- });
-
- it("never creates when the existing-connector lookup fails", async () => {
- mockedCaptureVercel.mockResolvedValue({
- ok: false,
- failure: {
- code: 1,
- stdout: "",
- stderr: "service unavailable",
- message: "vercel connect list failed",
- },
- });
-
- await expect(provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent")).resolves.toEqual(
- {
- state: "connector-lookup-failed",
- },
+ it("never creates when a connector detail response is malformed", async () => {
+ const connect = fakeConnect([connector({ uid: "slack/my-agent" })]);
+ mockedCaptureVercel.mockImplementation(async (args) =>
+ isListCall(args)
+ ? listPage([{ uid: "slack/my-agent", id: "scl_my_agent" }])
+ : { ok: true, stdout: JSON.stringify({ uid: "slack/my-agent" }) },
);
- expect(mockedRunVercelCaptureStdout).not.toHaveBeenCalled();
- });
- it("never creates when project ownership is unknown and Slack connectors already exist", async () => {
- mockedCaptureVercel.mockResolvedValue({
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_other_project",
- type: "slack",
- projects: [{ id: "prj_other" }],
- },
- ],
- }),
- });
- mockedRunVercelCaptureStdout.mockResolvedValue({
- ok: true,
- stdout: createSlackConnectorJson("slack/my-agent-2"),
- });
-
- await expect(provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent")).resolves.toEqual(
- {
- state: "connector-lookup-failed",
- },
+ await expect(provision(createTestLog(), ROOT, "my-agent", connect.deps)).rejects.toThrow(
+ "Could not inspect existing Slack connectors",
);
- expect(mockedRunVercelCaptureStdout).not.toHaveBeenCalled();
+ expect(connect.mutations()).toEqual([]);
});
it("enforces one five-minute deadline across existing connector detail requests", async () => {
mockedRunVercel.mockResolvedValue(true);
let now = 0;
mockedCaptureVercel.mockImplementation(async (args, options) => {
- if (args[0] === "connect") {
- return {
- ok: true,
- stdout: JSON.stringify({
- connectors: [
- {
- uid: "slack/my-agent",
- id: "scl_my_agent",
- type: "slack",
- createdAt: 1,
- projects: [{ id: "prj_demo" }],
- },
- ],
- }),
- };
- }
+ if (isListCall(args)) return listPage([{ uid: "slack/my-agent", id: "scl_my_agent" }]);
now += options.timeoutMs ?? 0;
return { ok: true, stdout: createSlackConnectorJson("slack/my-agent") };
});
- const result = await provisionSlackbot(createTestLog(), "/tmp/eve-agent", "my-agent", {
+ const result = await provision(createTestLog(), "/tmp/eve-agent", "my-agent", {
captureVercel: mockedCaptureVercel,
runVercel: mockedRunVercel,
runVercelCaptureStdout: mockedRunVercelCaptureStdout,
- readProjectLink: async () => ({ projectId: "prj_demo", orgId: "team_demo" }),
+ readProjectLink: async () => LINK,
delay: async (ms) => {
now += ms;
},
@@ -1463,9 +1626,10 @@ describe("provisionSlackbot", () => {
});
expect(result.state).toBe("existing-not-installed");
- expect(now).toBe(5 * 60_000);
- const detailCalls = mockedCaptureVercel.mock.calls.filter(([args]) => args[0] === "api");
- expect(detailCalls).toHaveLength(5);
+ // One snapshot read, then five polls inside the five-minute deadline.
+ expect(now).toBe(6 * 60_000);
+ const detailCalls = mockedCaptureVercel.mock.calls.filter(([args]) => !isListCall(args));
+ expect(detailCalls).toHaveLength(6);
});
});
diff --git a/packages/eve/src/setup/slackbot.ts b/packages/eve/src/setup/slackbot.ts
index 9c9c4de0f..c3266765c 100644
--- a/packages/eve/src/setup/slackbot.ts
+++ b/packages/eve/src/setup/slackbot.ts
@@ -1,3 +1,4 @@
+import { createHash, randomBytes } from "node:crypto";
import { join } from "node:path";
import { performance } from "node:perf_hooks";
import { setTimeout as sleep } from "node:timers/promises";
@@ -11,22 +12,39 @@ import {
type ChannelSetupChoice,
type ChannelSetupLog,
} from "#setup/cli/index.js";
+import { openUrl } from "#setup/primitives/open-url.js";
import { captureVercel, runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";
import { updateSlackChannelConnectorUid } from "#setup/scaffold/update/update-slack-channel.js";
-import type { SlackConnectorRef, SlackWorkspaceConnection } from "./slack-connect.js";
+import type {
+ SlackConnectorProject,
+ SlackConnectorRef,
+ SlackTriggerDestination,
+ SlackWorkspaceConnection,
+} from "./slack-connect.js";
import { createSlackConnector, type SlackConnectorCreateDeps } from "./slack-connect-create.js";
import {
- attachSlackConnector,
+ applySlackRouting,
cleanupCreatedAttempt,
CONNECT_LOOKUP_TIMEOUT_MS,
+ fetchSlackConnectorDetails,
fetchSlackWorkspace,
- findSlackConnector,
- listSlackConnectors,
+ refreshSlackCandidate,
+ findFreeSlackConnectorName,
+ inspectSlackConnectors,
type SlackConnectLifecycleDeps,
type SlackConnectorCleanupResult,
- type SlackConnectorLookup,
} from "./slack-connect-lifecycle.js";
+import {
+ describeSlackDestinations,
+ isReusableSlackConnector,
+ type SlackConnectorInUse,
+ orderSlackConnectorCandidates,
+ planSlackRouting,
+ type SlackConnectorCandidate,
+} from "./slack-setup-plan.js";
+
+export type { SlackConnectorCandidate } from "./slack-setup-plan.js";
/** Injected for tests; defaults to the real Vercel CLI subprocess primitives. */
interface SlackbotProvisionDeps extends SlackConnectLifecycleDeps, SlackConnectorCreateDeps {
@@ -51,34 +69,44 @@ const monotonicNow = (): number => performance.now();
const WORKSPACE_POLL_TIMEOUT_MS = 5 * 60_000;
const WORKSPACE_POLL_INTERVAL_MS = 3_000;
+/** A Slack connector that delivers this project's events to eve's Slack route. */
+interface SlackbotConnection {
+ connectorUid: string;
+ /** Deep link that opens a DM compose with the bot ("chat with your agent"). */
+ chatUrl?: string;
+ workspaceName?: string;
+}
+
/**
- * Outcome of the Connect create-and-attach sequence for a Slackbot. The
- * discriminant is the complete lifecycle state: `attached` means a connector
- * exists, this project is registered as the trigger destination, and the app
- * is installed into a Slack workspace.
- * `not-installed` means the workspace-install deadline elapsed and any connector
- * created by this attempt was removed. `cleanup-failed` means it may remain and
- * callers must stop rather than create another connector. Attachment setup
- * reports detach and attach failures separately because attach must not run
- * while an old trigger destination may still exist.
+ * Outcome of Slackbot provisioning. `attached` means a connector exists, this
+ * project receives its events at eve's Slack route, and the app is installed
+ * into a Slack workspace. `already-configured` is the same state reached
+ * without changing anything. `not-installed` means the workspace-install
+ * deadline elapsed and any connector created by this attempt was removed.
+ * `cleanup-failed` means it may remain and callers must stop rather than
+ * create another connector. `trigger-limit-reached` changed nothing because
+ * the connector already has the maximum number of trigger destinations.
+ * `connector-in-use` changed nothing because another project now uses the
+ * chosen connector.
*/
export type ProvisionSlackbotResult =
| { state: "connector-lookup-failed" }
- | { state: "create-failed" }
+ /** `detail` is the Vercel CLI's own error line, when it printed one. */
+ | { state: "create-failed"; detail?: string }
| { state: "cancelled" }
| { state: "existing-not-installed"; connectorUid: string }
| { state: "cleanup-failed"; connectorUids: readonly string[] }
- | { state: "detach-failed"; connectorUid: string }
| { state: "attach-failed"; connectorUid: string }
- | { state: "not-installed" }
- | { state: "installation-check-failed"; connectorUid: string }
+ | { state: "connector-in-use"; connectorUid: string; projects: readonly SlackConnectorProject[] }
| {
- state: "attached";
+ state: "trigger-limit-reached";
connectorUid: string;
- /** Deep link that opens a DM compose with the bot ("chat with your agent"). */
- chatUrl?: string;
- workspaceName?: string;
- };
+ destinations: readonly SlackTriggerDestination[];
+ }
+ | { state: "not-installed" }
+ | { state: "installation-check-failed"; connectorUid: string }
+ | ({ state: "attached" } & SlackbotConnection)
+ | ({ state: "already-configured" } & SlackbotConnection);
/** Terminal result of polling connector details for Slack workspace metadata. */
type SlackWorkspacePollResult =
@@ -86,17 +114,25 @@ type SlackWorkspacePollResult =
| { state: "timed-out" }
| { state: "failed"; message: string };
-/** What one create/reuse → workspace → attach attempt settled on. */
+/** What one create/reuse → workspace → routing attempt settled on. */
type AttemptOutcome =
| {
state: "attached";
ref: SlackConnectorRef;
workspace?: SlackWorkspaceConnection;
+ /** False only when an existing connector was already fully configured. */
+ changed: boolean;
}
- | { state: "create-failed" }
+ | { state: "create-failed"; detail?: string }
| { state: "unresolved" }
- | { state: "detach-failed"; ref: SlackConnectorRef }
- | { state: "attach-failed"; ref: SlackConnectorRef }
+ | { state: "attach-failed"; ref: SlackConnectorRef; message?: string }
+ | { state: "in-use"; ref: SlackConnectorRef; projects: readonly SlackConnectorProject[] }
+ | {
+ state: "limit-reached";
+ ref: SlackConnectorRef;
+ destinations: readonly SlackTriggerDestination[];
+ description: readonly string[];
+ }
| { state: "timed-out"; ref: SlackConnectorRef }
| { state: "failed"; ref: SlackConnectorRef; message: string };
@@ -107,10 +143,20 @@ type AttemptOutcome =
type Phase = <T>(message: string, task: () => Promise<T>) => Promise<T>;
type AttemptSource =
- | { state: "existing"; ref: SlackConnectorRef }
- | { state: "new"; baselineConnectorUids: ReadonlySet<string> };
+ | { state: "existing"; candidate: SlackConnectorCandidate }
+ /** `name` is the `--name` for `connect create`, already checked against the team. */
+ | { state: "new"; name: string };
type ExistingAttemptSource = Extract<AttemptSource, { state: "existing" }>;
+
+/**
+ * What one new-connector attempt observed, so cleanup removes exactly what it
+ * created and skips cleanup only when the CLI proved nothing was created.
+ */
+interface CreateAttemptTrace {
+ createdRef?: SlackConnectorRef;
+ rejected: boolean;
+}
type NewAttemptSource = Extract<AttemptSource, { state: "new" }>;
/**
@@ -168,42 +214,132 @@ function cleanupFailureResult(
};
}
+/**
+ * Opens Vercel Connect's install page for an existing connector, the page
+ * `vercel connect token` opens on `installation_required`. The browser flow
+ * that created a connector is its only other install path, and it is gone
+ * once that run stops. Connect keys the browser result to the request code;
+ * eve observes completion through `data.slackTeam` instead, so the verifier
+ * is never kept.
+ */
+function openSlackInstall(
+ log: ChannelSetupLog,
+ ref: SlackConnectorRef,
+ orgId: string | undefined,
+): void {
+ if (orgId === undefined) {
+ log.info(`Run \`vercel connect open ${ref.uid}\` to install it in a Slack workspace.`);
+ return;
+ }
+ const verifier = randomBytes(37).toString("base64url");
+ const url = new URL(`https://vercel.com/api/v1/connect/install/${encodeURIComponent(ref.id)}`);
+ url.searchParams.set("teamId", orgId);
+ url.searchParams.set("request_code", createHash("sha256").update(verifier).digest("base64url"));
+ log.info(`Install \`${ref.uid}\` in a Slack workspace: ${url.href}`);
+ openUrl(url.href);
+}
+
+/**
+ * Explains why a new connector won't carry the agent's name, naming the
+ * projects that hold `slack/<slug>` when this snapshot knows them.
+ */
+function renamedConnectorMessage(
+ slug: string,
+ name: string,
+ inUse: readonly SlackConnectorInUse[],
+): string {
+ const holder = inUse.find((entry) => entry.uid === `slack/${slug}`);
+ if (holder === undefined) {
+ return `A Slack connector named \`slack/${slug}\` already exists, so eve will name the new one \`slack/${name}\`.`;
+ }
+ const projects = holder.otherProjects.map((project) => project.name ?? project.id);
+ const owner = projects.length === 1 ? "another project" : "other projects";
+ return `\`slack/${slug}\` is already used by ${owner} (${projects.join(", ")}), so eve will create \`slack/${name}\` for this project.`;
+}
+
+/** Explains why setup won't attach a connector another project uses. */
+export function connectorInUseMessage(candidate: SlackConnectorInUse): string {
+ const projects = candidate.otherProjects.map((project) => project.name ?? project.id).join(", ");
+ return `\`${candidate.uid}\` is used by ${projects}. eve does not add a second agent to one Slack app because both would respond to the same events. Create a new Slack app for this agent instead.`;
+}
+
/**
* Runs one provisioning attempt end to end. A new connector completes when the
* CLI's browser verifier succeeds (or connector details prove the workspace
- * connection first). A reused connector must expose workspace metadata before
- * eve attaches this project's trigger route.
- * `onCreated` fires the instant a fresh connector exists so an aborted attempt
- * can remove exactly what it made. The `phase` seam lets each caller route
+ * connection first); its destinations are then read fresh. A reused connector
+ * must expose workspace metadata before eve changes its event delivery.
+ * Routing runs only the mutation the destinations still need, so an attempt
+ * over an already-configured connector changes nothing.
+ * `trace` records a fresh connector the instant it exists, and whether the
+ * CLI rejected the request before its browser flow, so an aborted attempt can
+ * remove exactly what it made. The `phase` seam lets each caller route
* progress through its own transient status surface.
*/
async function runAttempt(input: {
log: ChannelSetupLog;
deps: SlackbotProvisionDeps;
projectRoot: string;
+ projectId: string;
orgId: string | undefined;
- slug: string;
source: AttemptSource;
onOutput: ReturnType<typeof createPromptCommandOutput>;
signal: AbortSignal | undefined;
phase: Phase;
- onCreated: (ref: SlackConnectorRef) => void;
+ trace: CreateAttemptTrace;
}): Promise<AttemptOutcome> {
- const { log, deps, projectRoot, orgId, onOutput, signal, phase } = input;
+ const { log, deps, projectRoot, projectId, orgId, onOutput, signal, phase } = input;
let ref: SlackConnectorRef;
let workspace: SlackWorkspaceConnection | undefined;
+ let attached: boolean;
+ let destinations: readonly SlackTriggerDestination[];
+ let otherProjects: readonly SlackConnectorProject[] = [];
+ let changed = input.source.state === "new";
if (input.source.state === "existing") {
- ref = input.source.ref;
+ const { candidate } = input.source;
+ ref = { uid: candidate.uid, id: candidate.id };
+ workspace = candidate.workspace;
+ if (workspace === undefined) {
+ openSlackInstall(log, ref, orgId);
+ const poll = await phase("Waiting for the Slack workspace install...", () =>
+ pollSlackWorkspace(deps, projectRoot, ref.id, orgId, onOutput, signal),
+ );
+ if (poll.state === "timed-out") return { state: "timed-out", ref };
+ if (poll.state === "failed") return { state: "failed", ref, message: poll.message };
+ workspace = poll.workspace;
+ changed = true;
+ }
+ // The chosen connector may have changed since the question was answered.
+ // Recheck both its project access and destinations before routing it.
+ const fresh = await refreshSlackCandidate({
+ deps,
+ projectRoot,
+ candidate,
+ projectId,
+ orgId,
+ onOutput,
+ signal,
+ });
+ signal?.throwIfAborted();
+ if (fresh.state === "failed") return { state: "attach-failed", ref, message: fresh.message };
+ if (!isReusableSlackConnector(fresh.candidate)) {
+ return { state: "in-use", ref, projects: fresh.candidate.otherProjects };
+ }
+ attached = fresh.candidate.attached;
+ destinations = fresh.candidate.triggerDestinations;
+ otherProjects = fresh.candidate.otherProjects;
+ workspace ??= fresh.candidate.workspace;
} else {
const created = await createSlackConnector({
deps,
projectRoot,
orgId,
- slug: input.slug,
+ slug: input.source.name,
onOutput,
signal,
phase,
- onCreated: input.onCreated,
+ onCreated: (createdRef) => {
+ input.trace.createdRef = createdRef;
+ },
waitForWorkspace: async (createdRef, workspaceSignal) => {
const result = await pollSlackWorkspace(
deps,
@@ -216,7 +352,12 @@ async function runAttempt(input: {
return result.state === "connected" ? result.workspace : undefined;
},
});
- if (created.state === "failed") return { state: "create-failed" };
+ if (created.state === "failed") {
+ input.trace.rejected = created.rejected;
+ return created.detail === undefined
+ ? { state: "create-failed" }
+ : { state: "create-failed", detail: created.detail };
+ }
if (created.state === "unresolved") {
log.warning(
"Vercel did not return an exact Slack connector UID for this request, so eve cannot attach or remove it safely.",
@@ -225,25 +366,55 @@ async function runAttempt(input: {
}
ref = created.ref;
if (created.via === "workspace") workspace = created.workspace;
+ // `connect create` runs in the linked directory, which attaches the project.
+ attached = true;
+ // Connect adds a default destination at creation; read it back.
+ const details = await fetchSlackConnectorDetails({
+ deps,
+ projectRoot,
+ connectorId: ref.id,
+ orgId,
+ onOutput,
+ timeoutMs: CONNECT_LOOKUP_TIMEOUT_MS,
+ signal,
+ });
+ signal?.throwIfAborted();
+ if (details.state === "failed")
+ return { state: "attach-failed", ref, message: details.message };
+ destinations = details.details.triggerDestinations;
+ workspace ??= details.details.workspace;
}
- if (input.source.state === "existing" && workspace === undefined) {
- const poll = await phase("Waiting for the Slack workspace connection...", () =>
- pollSlackWorkspace(deps, projectRoot, ref.id, orgId, onOutput, signal),
+ const plan = planSlackRouting({
+ attached,
+ destinations,
+ projectId,
+ route: SLACK_CHANNEL_DEFAULT_ROUTE,
+ });
+ if (plan.kind === "limit-reached") {
+ const projectNames = new Map(
+ otherProjects.map((project) => [project.id, project.name ?? project.id]),
);
- if (poll.state === "timed-out") return { state: "timed-out", ref };
- if (poll.state === "failed") return { state: "failed", ref, message: poll.message };
- workspace = poll.workspace;
+ projectNames.set(projectId, "this project");
+ return {
+ state: "limit-reached",
+ ref,
+ destinations: plan.destinations,
+ description: describeSlackDestinations(plan.destinations, projectNames),
+ };
+ }
+ if (plan.attach || plan.destinations !== undefined) {
+ const routing = await phase("Configuring Slack event delivery for this agent...", () =>
+ applySlackRouting({ deps, projectRoot, ref, plan, orgId, onOutput, signal }),
+ );
+ signal?.throwIfAborted();
+ if (routing.state === "attach-failed")
+ return { state: "attach-failed", ref, message: routing.message };
+ changed = true;
}
-
- const attachment = await phase("Configuring Slack event delivery for this agent...", () =>
- attachSlackConnector(deps, projectRoot, ref, onOutput, signal),
- );
- signal?.throwIfAborted();
- if (attachment.state !== "attached") return { state: attachment.state, ref };
return workspace === undefined
- ? { state: "attached", ref }
- : { state: "attached", ref, workspace };
+ ? { state: "attached", ref, changed }
+ : { state: "attached", ref, workspace, changed };
}
/** How an interactive attempt resolved: the work finished, or the user acted. */
@@ -299,33 +470,78 @@ async function raceAttemptAgainstChoice(input: {
}
}
+/** A reusable connector from {@link inspectSlackbotConnectors}, or a request to create one. */
+export type SlackConnectorSelection = SlackConnectorCandidate | "create";
+
/**
- * Creates or reuses a Slack connector and points its event destination at eve.
- * A successful `connect create` is the completion boundary for a new browser
- * flow. Existing connectors are verified through their team-scoped detail
- * payload before attachment.
+ * Read-only snapshot of the Slack connectors setup may reuse for the linked
+ * project. Setup takes it once, asks its questions from it, and hands it to
+ * {@link provisionSlackbot}.
*/
-export type SlackConnectorSelection = SlackConnectorRef | "create";
+export interface SlackbotConnectorInspection {
+ projectId: string;
+ orgId: string | undefined;
+ /** Preferred short-name for `connect create slack --name`; suffixed when taken. */
+ slug: string;
+ /**
+ * Reusable connectors in question order: the suggestion first, then
+ * attached, then the rest. Connectors other projects use are excluded.
+ */
+ candidates: readonly SlackConnectorCandidate[];
+ preferred?: SlackConnectorCandidate;
+ /** Connectors other projects use, which setup never attaches to this one. */
+ inUse: readonly SlackConnectorInUse[];
+}
+
+const UNLINKED_PROJECT_WARNING =
+ "Slack setup with Vercel Connect needs a linked Vercel project to tell which Slack connectors belong to it, so eve did not create one. Run `vercel link`, then try again.";
-/** Read-only connector inventory used to resolve the create/reuse decision before provisioning. */
+/**
+ * Inspects the connectors attached to the linked project, plus
+ * `slack/<slug>` and the channel file's UID looked up by name. Throws when
+ * the project isn't linked or any connector can't be read, so setup never
+ * creates a connector on a guess.
+ */
export async function inspectSlackbotConnectors(
log: ChannelSetupLog,
projectRoot: string,
slug: string,
- signal?: AbortSignal,
+ options: { signal?: AbortSignal; channelConnectorUid?: string | undefined } = {},
deps: SlackbotProvisionDeps = defaultDeps,
-): Promise<Extract<SlackConnectorLookup, { state: "found" | "not-found" }>> {
+): Promise<SlackbotConnectorInspection> {
const projectLink = await (deps.readProjectLink ?? readProjectLink)(projectRoot);
- const lookup = await findSlackConnector(
- deps,
- projectRoot,
- projectLink?.projectId,
- `slack/${slug}`,
- createPromptCommandOutput(log),
- signal,
+ if (projectLink?.projectId === undefined) throw new Error(UNLINKED_PROJECT_WARNING);
+ const { projectId, orgId } = projectLink;
+ const { channelConnectorUid } = options;
+ const expectedUid = `slack/${slug}`;
+ const namedUids = new Set([expectedUid]);
+ if (channelConnectorUid !== undefined) namedUids.add(channelConnectorUid);
+ const inspection = await withPhase(log, "Checking existing Slack connectors...", () =>
+ inspectSlackConnectors({
+ deps,
+ projectRoot,
+ projectId,
+ orgId,
+ namedUids,
+ onOutput: createPromptCommandOutput(log),
+ signal: options.signal,
+ }),
);
- if (lookup.state === "failed") throw new Error(lookup.message);
- return lookup;
+ if (inspection.state === "failed") {
+ throw new Error(
+ `Could not inspect existing Slack connectors, so eve did not create another one. ${inspection.message}`,
+ );
+ }
+ return {
+ projectId,
+ orgId,
+ slug,
+ ...orderSlackConnectorCandidates(inspection.candidates.filter(isReusableSlackConnector), {
+ expectedUid,
+ channelConnectorUid,
+ }),
+ inUse: inspection.candidates.filter((candidate) => !isReusableSlackConnector(candidate)),
+ };
}
interface ProvisionSlackbotOptions {
@@ -334,47 +550,44 @@ interface ProvisionSlackbotOptions {
* 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;
}
+/**
+ * Reuses the selected connector or creates a new one, then points its event
+ * destination at eve, running only the steps the connector still needs.
+ * Re-running it after a partial failure resumes where the previous run
+ * stopped; it never detaches a project. A successful `connect create` is the
+ * completion boundary for a new browser flow.
+ */
export async function provisionSlackbot(
log: ChannelSetupLog,
projectRoot: string,
- /** Connector short-name passed to `vercel connect create slack --name`. */
- slug: string,
+ inspection: SlackbotConnectorInspection,
+ selection: SlackConnectorSelection,
deps: SlackbotProvisionDeps = defaultDeps,
options: ProvisionSlackbotOptions = {},
): Promise<ProvisionSlackbotResult> {
options.signal?.throwIfAborted();
const onOutput = createPromptCommandOutput(log);
- const cleanupContext = { log, deps, projectRoot, onOutput };
- const projectLink = await (deps.readProjectLink ?? readProjectLink)(projectRoot);
- const projectId = projectLink?.projectId;
- const orgId = projectLink?.orgId;
- const expectedUid = `slack/${slug}`;
+ const { projectId, orgId, slug } = inspection;
+ const cleanupContext = { log, deps, projectRoot, orgId, onOutput };
- const existing = await withPhase(log, "Checking for an existing Slackbot...", () =>
- findSlackConnector(deps, projectRoot, projectId, expectedUid, onOutput, options.signal),
- );
- options.signal?.throwIfAborted();
- if (existing.state === "failed") {
- log.warning(
- `Could not inspect existing Slack connectors, so eve did not create another one. ${existing.message}`,
- );
- return { state: "connector-lookup-failed" };
- }
- if (projectId === undefined && existing.connectorUids.size > 0) {
- log.warning(
- "Could not verify which Slack connectors belong to this Vercel project, so eve did not create another one. Restore `.vercel/project.json`, then try again.",
- );
- return { state: "connector-lookup-failed" };
- }
+ const findFreeName = async () => {
+ const free = await findFreeSlackConnectorName({
+ deps,
+ projectRoot,
+ orgId,
+ slug,
+ onOutput,
+ signal: options.signal,
+ });
+ if (free.state === "failed") {
+ log.warning(`Could not pick a name for the new Slack connector. ${free.message}`);
+ }
+ return free;
+ };
/** Folds a finished attempt into a result, cleaning up terminal abandonments. */
const finishOutcome = async (
@@ -389,7 +602,9 @@ export async function provisionSlackbot(
const cleanup = await cleanupAttempt();
if (cleanup.state === "failed") return cleanupFailureResult(cleanup);
}
- return { state: "create-failed" };
+ return outcome.detail === undefined
+ ? { state: "create-failed" }
+ : { state: "create-failed", detail: outcome.detail };
}
case "unresolved": {
if (attemptCreated) {
@@ -398,31 +613,47 @@ export async function provisionSlackbot(
}
return { state: "create-failed" };
}
- case "detach-failed":
+ case "in-use":
log.warning(
- `Could not remove the connector's existing trigger destination. Run \`vercel connect detach ${outcome.ref.uid} --yes\`, then \`vercel connect attach ${outcome.ref.uid} --triggers --trigger-path ${SLACK_CHANNEL_DEFAULT_ROUTE} --yes\`.`,
+ connectorInUseMessage({ uid: outcome.ref.uid, otherProjects: outcome.projects }),
);
return {
- state: "detach-failed",
+ state: "connector-in-use",
connectorUid: outcome.ref.uid,
+ projects: outcome.projects,
};
case "attach-failed":
log.warning(
- `Could not register this project as a trigger destination. Run \`vercel connect attach ${outcome.ref.uid} --triggers --trigger-path ${SLACK_CHANNEL_DEFAULT_ROUTE} --yes\` to enable event delivery.`,
+ `Could not register ${SLACK_CHANNEL_DEFAULT_ROUTE} on this project as a trigger destination for \`${outcome.ref.uid}\`.${outcome.message === undefined ? "" : ` ${outcome.message}`} eve kept the connector; re-run \`eve add channel/slack\` to finish event delivery.`,
);
return {
state: "attach-failed",
connectorUid: outcome.ref.uid,
};
- case "attached":
+ case "limit-reached":
+ log.warning(
+ [
+ `\`${outcome.ref.uid}\` already has ${outcome.destinations.length} trigger destinations, the most Vercel Connect allows, so eve changed nothing:`,
+ ...outcome.description.map((line) => ` - ${line}`),
+ "Remove one in the Connect dashboard, then re-run `eve add channel/slack`.",
+ ].join("\n"),
+ );
+ return {
+ state: "trigger-limit-reached",
+ connectorUid: outcome.ref.uid,
+ destinations: outcome.destinations,
+ };
+ case "attached": {
+ const state = outcome.changed ? "attached" : "already-configured";
return outcome.workspace === undefined
- ? { state: "attached", connectorUid: outcome.ref.uid }
+ ? { state, connectorUid: outcome.ref.uid }
: {
- state: "attached",
+ state,
connectorUid: outcome.ref.uid,
chatUrl: outcome.workspace.workspaceUrl,
workspaceName: outcome.workspace.workspaceName,
};
+ }
case "failed":
// The workspace state is unknown, so the connector is left in place
// rather than risk destroying a working connection.
@@ -444,25 +675,25 @@ export async function provisionSlackbot(
const cleanupNewAttempt = async (
attempt: NewAttemptSource,
- createdRef: SlackConnectorRef | undefined,
+ trace: CreateAttemptTrace,
): Promise<SlackConnectorCleanupResult> => {
return cleanupCreatedAttempt(cleanupContext, {
- expectedUid,
- baselineConnectorUids: attempt.baselineConnectorUids,
- createdRef,
+ expectedUid: `slack/${attempt.name}`,
+ createdRef: trace.createdRef,
+ rejected: trace.rejected,
});
};
- function attemptInput(attempt: AttemptSource, onCreated: (ref: SlackConnectorRef) => void) {
+ function attemptInput(attempt: AttemptSource, trace: CreateAttemptTrace) {
return {
log,
deps,
projectRoot,
+ projectId,
orgId,
- slug,
source: attempt,
onOutput,
- onCreated,
+ trace,
};
}
@@ -472,13 +703,14 @@ export async function provisionSlackbot(
const cleanupCurrentAttempt = async (): Promise<SlackConnectorCleanupResult> => ({
state: "clean",
});
+ const uid = attempt.candidate.uid;
const notInstalled = (): ProvisionSlackbotResult => {
log.warning(
- `The existing Slack connector \`${attempt.ref.uid}\` is not connected to a Slack workspace. eve did not remove it because this run did not create it. If its original browser request is still open, complete it; otherwise run \`vercel connect remove ${attempt.ref.uid} --disconnect-all --yes\` before trying again.`,
+ `The Slack connector \`${uid}\` is not installed in a Slack workspace yet. Re-run \`eve add channel/slack\` to open its install page again, or choose "Create a new Slack app" instead.`,
);
return {
state: "existing-not-installed",
- connectorUid: attempt.ref.uid,
+ connectorUid: uid,
};
};
const finishExistingOutcome = async (
@@ -488,30 +720,40 @@ export async function provisionSlackbot(
return finishOutcome(outcome, attempt, cleanupCurrentAttempt);
};
- // An existing connector belongs to a prior run. Reconfigure and inspect it,
- // but never offer a fresh browser request or remove it under this run's
- // ownership.
- if (options.awaitChoice !== undefined) {
- const prompt = options.awaitChoice({
- status: "Waiting for the existing Slack workspace connection...",
- context: "Complete the original setup in the browser",
- actions: [{ value: "cancel", label: "Stop waiting" }],
- });
- const race = await raceAttemptAgainstChoice({
- prompt,
- outerSignal: options.signal,
- run: (signal) =>
- runAttempt({ ...attemptInput(attempt, () => {}), signal, phase: (_m, task) => task() }),
- });
- if (race.via === "work") return finishExistingOutcome(race.outcome);
- if (race.settled?.state === "attached") return finishExistingOutcome(race.settled);
- // The user stopped waiting (or Esc): an existing connector is never ours
- // to remove, so report it as not yet connected.
- return notInstalled();
+ // An existing connector belongs to a prior run. Reconfigure it and open its
+ // install page when needed, but never remove it under this run's
+ // ownership. Only a workspace wait is worth racing against a prompt.
+ if (options.awaitChoice !== undefined && attempt.candidate.workspace === undefined) {
+ while (true) {
+ const prompt = options.awaitChoice({
+ status: "Waiting for the Slack workspace install...",
+ context: "Install the Slack app in your browser, then wait while eve verifies it",
+ actions: [
+ { value: "retry", label: "Did your browser not open? Try again" },
+ { value: "cancel", label: "Stop waiting" },
+ ],
+ });
+ const race = await raceAttemptAgainstChoice({
+ prompt,
+ outerSignal: options.signal,
+ run: (signal) =>
+ runAttempt({
+ ...attemptInput(attempt, { rejected: false }),
+ signal,
+ phase: (_m, task) => task(),
+ }),
+ });
+ if (race.via === "work") return finishExistingOutcome(race.outcome);
+ if (race.settled?.state === "attached") return finishExistingOutcome(race.settled);
+ if (race.choice === "retry") continue;
+ // The user stopped waiting (or Esc): an existing connector is never ours
+ // to remove, so report it as not yet installed.
+ return notInstalled();
+ }
}
const outcome = await runAttempt({
- ...attemptInput(attempt, () => {}),
+ ...attemptInput(attempt, { rejected: false }),
signal: options.signal,
phase: (message, task) => withPhase(log, message, task),
});
@@ -521,14 +763,12 @@ export async function provisionSlackbot(
async function runUncontrolledAttempt(
attempt: NewAttemptSource,
): Promise<ProvisionSlackbotResult> {
- let createdRef: SlackConnectorRef | undefined;
- const cleanupCurrentAttempt = () => cleanupNewAttempt(attempt, createdRef);
+ const trace: CreateAttemptTrace = { rejected: false };
+ const cleanupCurrentAttempt = () => cleanupNewAttempt(attempt, trace);
// No interactive surface (plain/headless): run the new request to a
// terminal outcome with per-step spinners; abort/retry are unavailable.
const work = runAttempt({
- ...attemptInput(attempt, (ref) => {
- createdRef = ref;
- }),
+ ...attemptInput(attempt, trace),
signal: options.signal,
phase: (message, task) => withPhase(log, message, task),
});
@@ -550,8 +790,8 @@ export async function provisionSlackbot(
attempt: NewAttemptSource,
awaitChoice: ChannelSetupAwaitChoice,
): Promise<InteractiveAttemptDecision> {
- let createdRef: SlackConnectorRef | undefined;
- const cleanupCurrentAttempt = () => cleanupNewAttempt(attempt, createdRef);
+ const trace: CreateAttemptTrace = { rejected: false };
+ const cleanupCurrentAttempt = () => cleanupNewAttempt(attempt, trace);
// Interactive: one prompt races the whole create → attach attempt,
// so "Try again" / "Cancel" are live even while `connect create` parks on
// the browser. A user action aborts the attempt and removes its connector.
@@ -570,9 +810,7 @@ export async function provisionSlackbot(
outerSignal: options.signal,
run: (signal) =>
runAttempt({
- ...attemptInput(attempt, (ref) => {
- createdRef = ref;
- }),
+ ...attemptInput(attempt, trace),
signal,
phase:
log.spinner === undefined
@@ -605,42 +843,27 @@ export async function provisionSlackbot(
return { state: "finished", result: cleanupFailureResult(cleanup) };
}
if (race.choice === "retry") {
- const inventory = await withPhase(log, "Checking existing Slack connectors...", () =>
- listSlackConnectors(deps, projectRoot, onOutput, options.signal),
+ const free = await withPhase(log, "Checking existing Slack connectors...", () =>
+ findFreeName(),
);
options.signal?.throwIfAborted();
- if (inventory.state === "failed") {
- log.warning(
- `Could not inspect existing Slack connectors, so eve did not create another one. ${inventory.message}`,
- );
+ if (free.state === "failed") {
return { state: "finished", result: { state: "connector-lookup-failed" } };
}
- return {
- state: "retry",
- source: {
- state: "new",
- baselineConnectorUids: new Set(inventory.connectors.map((connector) => connector.uid)),
- },
- };
+ return { state: "retry", source: { state: "new", name: free.name } };
}
return { state: "finished", result: { state: "cancelled" } };
}
- if (existing.state === "found") {
- 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 });
- }
+ if (selection !== "create") {
+ return runExistingConnector({ state: "existing", candidate: selection });
}
- let source: NewAttemptSource = {
- state: "new",
- baselineConnectorUids: existing.connectorUids,
- };
+ const free = await findFreeName();
+ options.signal?.throwIfAborted();
+ if (free.state === "failed") return { state: "connector-lookup-failed" };
+ if (free.name !== slug) log.info(renamedConnectorMessage(slug, free.name, inspection.inUse));
+ let source: NewAttemptSource = { state: "new", name: free.name };
if (options.awaitChoice === undefined) {
return runUncontrolledAttempt(source);
}
@@ -661,7 +884,8 @@ export async function reconcileSlackUid(
slackbot: ProvisionSlackbotResult,
expectedUid: string,
): Promise<boolean> {
- if (slackbot.state !== "attached" || slackbot.connectorUid === expectedUid) return true;
+ if (slackbot.state !== "attached" && slackbot.state !== "already-configured") return true;
+ if (slackbot.connectorUid === expectedUid) return true;
const slackChannelPath = join(projectRoot, "agent/channels/slack.ts");
const { patched } = await updateSlackChannelConnectorUid(slackChannelPath, slackbot.connectorUid);
if (!patched) {
diff --git a/packages/eve/src/shared/development-env-files.ts b/packages/eve/src/shared/development-env-files.ts
new file mode 100644
index 000000000..1e98e4cd6
--- /dev/null
+++ b/packages/eve/src/shared/development-env-files.ts
@@ -0,0 +1,36 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { parseEnv } from "node:util";
+
+import { isObject } from "#shared/guards.js";
+
+/** Development env files, from highest to lowest precedence. */
+export const DEVELOPMENT_ENV_FILE_NAMES = [
+ ".env.development.local",
+ ".env.local",
+ ".env.development",
+ ".env",
+] as const;
+
+function isMissingEnvironmentFileError(error: unknown): error is NodeJS.ErrnoException {
+ return isObject(error) && error.code === "ENOENT";
+}
+
+/** Merged values of the development env files in `environmentRoot`, by precedence. */
+export function readDevelopmentEnvironmentValues(environmentRoot: string): Map<string, string> {
+ const values = new Map<string, string>();
+
+ for (const fileName of [...DEVELOPMENT_ENV_FILE_NAMES].reverse()) {
+ try {
+ const parsedValues = parseEnv(readFileSync(join(environmentRoot, fileName), "utf8"));
+
+ for (const [key, value] of Object.entries(parsedValues)) {
+ if (value !== undefined) values.set(key, value);
+ }
+ } catch (error) {
+ if (!isMissingEnvironmentFileError(error)) throw error;
+ }
+ }
+
+ return values;
+}
diff --git a/packages/eve/src/shared/map-with-concurrency.ts b/packages/eve/src/shared/map-with-concurrency.ts
new file mode 100644
index 000000000..1fc149370
--- /dev/null
+++ b/packages/eve/src/shared/map-with-concurrency.ts
@@ -0,0 +1,18 @@
+/** Maps `items` with at most `limit` calls in flight, preserving input order. */
+export async function mapWithConcurrency<T, R>(
+ items: readonly T[],
+ limit: number,
+ map: (item: T) => Promise<R>,
+): Promise<R[]> {
+ const results: R[] = Array.from({ length: items.length });
+ let next = 0;
+ const worker = async () => {
+ while (next < items.length) {
+ const index = next;
+ next += 1;
+ results[index] = await map(items[index] as T);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
+ return results;
+}